@cheemsup/dsh-plugin-console 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (101) hide show
  1. package/LICENSE +23 -0
  2. package/README.md +95 -3
  3. package/cordis.patch.yml +5 -0
  4. package/icon.svg +203 -0
  5. package/lib/client.activity.js +222 -0
  6. package/lib/client.apply.js +171 -0
  7. package/lib/client.changes.js +206 -0
  8. package/lib/client.cleanup.js +270 -0
  9. package/lib/client.control.js +247 -0
  10. package/lib/client.dialog.js +77 -0
  11. package/lib/client.disable-preview.js +904 -0
  12. package/lib/client.draft.js +280 -0
  13. package/lib/client.editor-messages.js +421 -0
  14. package/lib/client.editor-store.js +266 -0
  15. package/lib/client.editor.js +433 -0
  16. package/lib/client.effects.js +115 -0
  17. package/lib/client.impact-tree.js +487 -0
  18. package/lib/client.influence.js +361 -0
  19. package/lib/client.js +246 -0
  20. package/lib/client.page.js +646 -0
  21. package/lib/client.plugin-filters.js +62 -0
  22. package/lib/client.plugins.js +506 -0
  23. package/lib/client.preview-messages.js +506 -0
  24. package/lib/client.preview-raw.js +132 -0
  25. package/lib/client.preview-store.js +128 -0
  26. package/lib/client.preview-tools.js +194 -0
  27. package/lib/client.preview.js +448 -0
  28. package/lib/client.relation-graph.js +364 -0
  29. package/lib/client.schema.js +327 -0
  30. package/lib/client.search.js +409 -0
  31. package/lib/client.session-detail.js +503 -0
  32. package/lib/client.sessions.js +495 -0
  33. package/lib/client.shared.js +562 -0
  34. package/lib/client.store.js +452 -0
  35. package/lib/client.styles.js +589 -0
  36. package/lib/client.template-card.js +240 -0
  37. package/lib/client.tools.js +366 -0
  38. package/lib/client.workspace-picker.js +204 -0
  39. package/lib/host/activity.js +252 -0
  40. package/lib/host/assembly-preview.js +244 -0
  41. package/lib/host/attribution.js +341 -0
  42. package/lib/host/catalog.js +133 -0
  43. package/lib/host/categorize.js +40 -0
  44. package/lib/host/config-layers.js +589 -0
  45. package/lib/host/constants.js +69 -0
  46. package/lib/host/control.js +159 -0
  47. package/lib/host/disable-preview.js +651 -0
  48. package/lib/host/entries.js +289 -0
  49. package/lib/host/fiber.js +86 -0
  50. package/lib/host/fs.js +99 -0
  51. package/lib/host/health.js +178 -0
  52. package/lib/host/http.js +65 -0
  53. package/lib/host/impact.js +138 -0
  54. package/lib/host/injection-owners.js +60 -0
  55. package/lib/host/layers.js +132 -0
  56. package/lib/host/masks.js +145 -0
  57. package/lib/host/modes.js +96 -0
  58. package/lib/host/names.js +44 -0
  59. package/lib/host/patch-config.js +554 -0
  60. package/lib/host/patch-scan.js +103 -0
  61. package/lib/host/preview-conditions.js +281 -0
  62. package/lib/host/preview-contexts.js +174 -0
  63. package/lib/host/preview-envelope.js +31 -0
  64. package/lib/host/preview-instructions.js +450 -0
  65. package/lib/host/preview-messages.js +284 -0
  66. package/lib/host/preview-modules.js +233 -0
  67. package/lib/host/preview-skills.js +200 -0
  68. package/lib/host/prompt.js +213 -0
  69. package/lib/host/recipe-overlay.js +209 -0
  70. package/lib/host/request-preview.js +114 -0
  71. package/lib/host/routes/activation.js +96 -0
  72. package/lib/host/routes/activity.js +22 -0
  73. package/lib/host/routes/apply.js +93 -0
  74. package/lib/host/routes/cleanup.js +62 -0
  75. package/lib/host/routes/control.js +22 -0
  76. package/lib/host/routes/disable-preview.js +19 -0
  77. package/lib/host/routes/impact.js +19 -0
  78. package/lib/host/routes/operations.js +22 -0
  79. package/lib/host/routes/preview.js +58 -0
  80. package/lib/host/routes/session-influence.js +23 -0
  81. package/lib/host/routes/snapshot.js +21 -0
  82. package/lib/host/routes/template.js +54 -0
  83. package/lib/host/routes/templates.js +28 -0
  84. package/lib/host/scope-impact.js +125 -0
  85. package/lib/host/session-events.js +39 -0
  86. package/lib/host/session-influence.js +467 -0
  87. package/lib/host/sessions.js +293 -0
  88. package/lib/host/snapshot.js +218 -0
  89. package/lib/host/source-scan.js +225 -0
  90. package/lib/host/templates/cleanup.js +219 -0
  91. package/lib/host/templates/inheritance.js +144 -0
  92. package/lib/host/templates/materialize.js +317 -0
  93. package/lib/host/templates/message-overlay.js +184 -0
  94. package/lib/host/templates/repository.js +323 -0
  95. package/lib/host/templates/store.js +131 -0
  96. package/lib/host/tool-set.js +150 -0
  97. package/lib/host/tools.js +129 -0
  98. package/lib/index.js +106 -0
  99. package/locale/en.json +6 -0
  100. package/locale/zh.json +6 -0
  101. package/package.json +124 -6
@@ -0,0 +1,171 @@
1
+ /**
2
+ * 「应用提示词模板到会话」那条五步链,单独成一个纯函数。
3
+ *
4
+ * 顺序不能变,而且每一步的失败语义都不一样:存版本失败就整体失败,建会话失败
5
+ * 就整体失败,物化失败要保留会话并报告原因,首句失败**不该**让整个流程失败。
6
+ * 把这些判断从 React 状态里拿出来,才能单独读、单独测。
7
+ *
8
+ * 链:
9
+ * 1. 保存草稿为新版本(保证「应用到会话的」就是眼前看到的)
10
+ * 2. 建会话(返回时 agent 已发布、首个 turn 尚未开始)
11
+ * 3. 物化提示词模板到这个会话
12
+ * 4. 首句:自动发送,或只填进输入框
13
+ * 5. 决定要不要跳过去
14
+ *
15
+ * 本文件是一个包内 chunk:入口用 `require.async('./client.apply.js')` 取它。
16
+ */
17
+
18
+ window.__ModuleLoader__.load({
19
+ id: '@cheemsup/dsh-plugin-console',
20
+ chunk: 'client.apply.js',
21
+ factory: () => (deps) => {
22
+ const { fetchJson, TEMPLATE_ROUTE, APPLY_ROUTE } = deps
23
+
24
+ /**
25
+ * 把首句投递到会话:自动发送,或只填进输入框。
26
+ *
27
+ * 两件事都需要一个「已 retain 的 binding」,而刚 create 出来的会话还没有。
28
+ * 所以这里自己 retain 一次:不导航、只把 scope 建起来拿到 binding,做完再释放。
29
+ * 这样即使后面发现物化有失败、决定不跳走,也已经落好了。
30
+ *
31
+ * 发送走 `binding.session.prompt()` 而不是 `conversation.send()`:
32
+ * 后者要求「调用方 ctx 带 session scope」,而我们是从根 ctx 拿到的
33
+ * conversation,直接调会抛 root-context 错误。binding.session 是那个会话
34
+ * 自己的对象层,不需要再借 scope。
35
+ * @param {object} options - 投递参数。
36
+ * @returns {Promise<{promptSent: boolean, draftFilled: boolean, promptError: string | null}>} 投递结果。
37
+ */
38
+ async function deliverFirstPrompt({ ctx, sessionsService, sessionId, prompt, autoSend }) {
39
+ let reference
40
+ let promptSent = false
41
+ let draftFilled = false
42
+ let promptError = null
43
+ try {
44
+ reference = sessionsService.retain?.(sessionId, { source: 'pluginTree' })
45
+ const binding = reference === undefined ? sessionsService.binding?.(sessionId) : await reference.ready
46
+ if (binding !== undefined) {
47
+ if (autoSend) {
48
+ const result = await binding.session.prompt([{ type: 'text', text: prompt }], 'queue')
49
+ if (result?.ok === true) promptSent = true
50
+ else promptError = result?.error?.message ?? '发送被拒绝'
51
+ } else {
52
+ const conversation = ctx?.get?.('conversation')
53
+ if (conversation?.input?.requestDraftInitialization !== undefined) {
54
+ conversation.input.requestDraftInitialization(binding, { prompt, whenDraftExists: 'replace' })
55
+ draftFilled = true
56
+ }
57
+ }
58
+ }
59
+ } catch (cause) {
60
+ // 首句没落好不该让整个流程失败:会话和物化都已经成了
61
+ promptError = cause instanceof Error ? cause.message : String(cause)
62
+ } finally {
63
+ reference?.release?.()
64
+ }
65
+ return { promptSent, draftFilled, promptError }
66
+ }
67
+
68
+ /**
69
+ * 把一条提示行拼出来:成功项与失败项都要说清楚,不能只报一句「完成」。
70
+ * @param {object} state - 本次运行的中间结果。
71
+ * @returns {{notes: string, failed: boolean}} 提示文本与是否算失败。
72
+ */
73
+ function summarize({ sessionId, applied, prompt, wantPrompt }) {
74
+ const notes = []
75
+ notes.push('已建会话 ' + sessionId.slice(0, 16) + '… 并应用提示词模板')
76
+ if (applied.created === true) notes.push('(新建)')
77
+ const appliedSections = applied.applied0?.sections?.length ?? 0
78
+ const appliedOverrides = applied.applied0?.overrides?.length ?? 0
79
+ const denied = applied.applied0?.deniedTools?.length ?? 0
80
+ const contexts = applied.applied0?.contextOverrides?.length ?? 0
81
+ const messageKinds = applied.applied0?.messageKinds?.length ?? 0
82
+ notes.push(' · 追加段落 ' + appliedSections + ' · 改写 ' + appliedOverrides + ' · 禁用工具 ' + denied)
83
+ if (contexts > 0) notes.push(' · 上下文 ' + contexts)
84
+ if (messageKinds > 0) notes.push(' · 消息 ' + messageKinds)
85
+ const skipped = applied.applied0?.skippedTools ?? []
86
+ if (skipped.length > 0) notes.push(' · ' + skipped.length + ' 个工具名不在当前 scope,跳过(' + skipped.join('、') + ')')
87
+ const failures = applied.errors ?? []
88
+ if (failures.length > 0) notes.push(' · 失败 ' + failures.length + ' 项:' + failures.join(';'))
89
+ if (applied.applied !== true) notes.push(' · 物化没发生:' + (applied.reason ?? '未知原因'))
90
+ if (prompt.promptSent) notes.push(' · 首句已发送')
91
+ else if (prompt.promptError !== null) notes.push(' · 首句发送失败:' + prompt.promptError)
92
+ else if (wantPrompt && !prompt.draftFilled) notes.push(' · 首句没能填进输入框,请手动粘贴')
93
+ const failed = failures.length > 0 || applied.applied !== true
94
+ return { notes: notes.join(''), failed }
95
+ }
96
+
97
+ /**
98
+ * 跑完整条链。
99
+ *
100
+ * @param {object} options - 运行参数。
101
+ * @param {object} options.ctx - 浏览器插件上下文(按需取宿主服务)。
102
+ * @param {string} options.templateId - 目标提示词模板。
103
+ * @param {object} options.recipe - 当前草稿算出的配方。
104
+ * @param {string | null} options.workspaceId - 目标工作区;null 表示让宿主决定。
105
+ * @param {string | null} options.presetId - 会话模式(= 编辑器基线模式)。
106
+ * @param {string} options.promptText - 首句内容。
107
+ * @param {boolean} options.autoSend - true 表示物化后立刻发送。
108
+ * @param {Function} options.onPhase - 阶段回调('saving' | 'creating' | 'applying')。
109
+ * @returns {Promise<{ok: true, sessionId: string, notes: string, failed: boolean} | {ok: false, message: string}>} 结果。
110
+ */
111
+ async function runApplyChain(options) {
112
+ const { ctx, templateId, recipe, workspaceId, presetId, promptText, autoSend, onPhase } = options
113
+ const sessionsService = ctx?.get?.('sessions')
114
+ const uiWorkspace = ctx?.get?.('uiWorkspace')
115
+ if (sessionsService === undefined) {
116
+ return { ok: false, message: '宿主没有 sessions 服务,无法新建会话' }
117
+ }
118
+
119
+ try {
120
+ // 1. 先把草稿存成新版本,保证「应用到会话的」就是眼前看到的。
121
+ onPhase('saving')
122
+ await fetchJson(TEMPLATE_ROUTE + '?id=' + encodeURIComponent(templateId), {
123
+ method: 'POST',
124
+ body: JSON.stringify({ recipe }),
125
+ })
126
+
127
+ // 2. 建会话:这一步返回时 agent 已经在册、还没开始任何 turn。
128
+ // 模式就用编辑器的基线模式——提示词模板的覆盖是按它的段落名算的。
129
+ onPhase('creating')
130
+ const sessionId = await sessionsService.create({
131
+ ...(workspaceId === null ? {} : { workspaceId }),
132
+ ...(presetId === null ? {} : { agentPreset: presetId }),
133
+ })
134
+
135
+ // 3. 物化到这个会话上。
136
+ onPhase('applying')
137
+ const applied = await fetchJson(APPLY_ROUTE, {
138
+ method: 'POST',
139
+ body: JSON.stringify({
140
+ templateId,
141
+ sessionId,
142
+ ...(presetId === null ? {} : { presetId }),
143
+ }),
144
+ })
145
+
146
+ // 4. 首句。
147
+ const wantPrompt = promptText.trim().length > 0
148
+ const prompt = wantPrompt
149
+ ? await deliverFirstPrompt({ ctx, sessionsService, sessionId, prompt: promptText, autoSend })
150
+ : { promptSent: false, draftFilled: false, promptError: null }
151
+
152
+ const { notes, failed } = summarize({ sessionId, applied, prompt, wantPrompt })
153
+
154
+ // 5. 一切正常才跳走。有失败就停在面板上——跳过去面板卸载,
155
+ // 通知跟着消失,用户永远看不到哪几项没成。
156
+ if (!failed && uiWorkspace?.openSession !== undefined) {
157
+ uiWorkspace.openSession(sessionId)
158
+ }
159
+ const suffix = uiWorkspace?.openSession === undefined
160
+ ? ' · 宿主没有 uiWorkspace,没能自动打开,请从侧边栏点进去'
161
+ : ''
162
+
163
+ return { ok: true, sessionId, notes: notes + suffix, failed }
164
+ } catch (cause) {
165
+ return { ok: false, message: cause instanceof Error ? cause.message : String(cause) }
166
+ }
167
+ }
168
+
169
+ return { runApplyChain, deliverFirstPrompt, summarize }
170
+ },
171
+ })
@@ -0,0 +1,206 @@
1
+ /**
2
+ * 快照差分:回答「自上次刷新以来,插件树变了什么」。
3
+ *
4
+ * 只比较用户能感知的字段:版本、启用、fiber 阶段、来源层、覆盖、工具/提示词段、
5
+ * 服务供需、配置字段、禁用表达式,以及工具集合的增删。会话与工作区不在这里比较,
6
+ * 它们的变化频率高,且不属于「插件树变更」。
7
+ *
8
+ * 本文件是一个包内 chunk:入口用 `require.async('./client.changes.js')` 取它。
9
+ */
10
+
11
+ window.__ModuleLoader__.load({
12
+ id: '@cheemsup/dsh-plugin-console',
13
+ chunk: 'client.changes.js',
14
+ factory: (require) => {
15
+ const React = require('react')
16
+ const { createElement: h } = React
17
+
18
+ return function create(deps) {
19
+ const { textButton } = deps
20
+
21
+ /** 数组字段排序后再比,避免源码扫描/注册顺序造成的假变化。 */
22
+ function sorted(values) {
23
+ return Array.isArray(values) ? [...values].sort() : []
24
+ }
25
+
26
+ /** 配置摘要:现在比较生效值,旧快照只有字段名时退回名字列表。 */
27
+ function configOf(entry) {
28
+ const rows = Array.isArray(entry?.configEntries) ? entry.configEntries : []
29
+ return rows.length ? rows.map((row) => [row.key, row.value]) : sorted(entry?.configKeys)
30
+ }
31
+
32
+ /** 一个条目的可比较摘要。 */
33
+ function digest(entry) {
34
+ return JSON.stringify({
35
+ version: entry?.version ?? null,
36
+ enabled: entry?.enabled === true,
37
+ phase: entry?.phase ?? null,
38
+ layer: entry?.layer ?? null,
39
+ overriddenBy: sorted(entry?.overriddenBy),
40
+ disabledExpr: entry?.disabledExpr ?? null,
41
+ tools: sorted(entry?.registrations?.tools),
42
+ sections: sorted(entry?.registrations?.sections),
43
+ contexts: sorted(entry?.registrations?.contexts),
44
+ requires: sorted(entry?.requires),
45
+ provides: sorted(entry?.provides),
46
+ config: configOf(entry),
47
+ })
48
+ }
49
+
50
+ /** 一个条目具体哪些字段变了。 */
51
+ function changedFields(before, after) {
52
+ const fields = []
53
+ const compare = (label, left, right) => {
54
+ if (JSON.stringify(left) !== JSON.stringify(right)) fields.push(label)
55
+ }
56
+ compare('版本', before?.version ?? null, after?.version ?? null)
57
+ compare('启用', before?.enabled === true, after?.enabled === true)
58
+ compare('阶段', before?.phase ?? null, after?.phase ?? null)
59
+ compare('来源层', before?.layer ?? null, after?.layer ?? null)
60
+ compare('覆盖', sorted(before?.overriddenBy), sorted(after?.overriddenBy))
61
+ compare('工具', sorted(before?.registrations?.tools), sorted(after?.registrations?.tools))
62
+ compare(
63
+ '提示词段',
64
+ [...sorted(before?.registrations?.sections), ...sorted(before?.registrations?.contexts)],
65
+ [...sorted(after?.registrations?.sections), ...sorted(after?.registrations?.contexts)],
66
+ )
67
+ compare('服务需求', sorted(before?.requires), sorted(after?.requires))
68
+ compare('服务提供', sorted(before?.provides), sorted(after?.provides))
69
+ compare('配置字段', configOf(before), configOf(after))
70
+ compare('禁用表达式', before?.disabledExpr ?? null, after?.disabledExpr ?? null)
71
+ return fields
72
+ }
73
+
74
+ /** 条目的展示名。 */
75
+ function labelOf(entry) {
76
+ return entry?.title || entry?.packageName || entry?.moduleName || entry?.entryId || '未知插件'
77
+ }
78
+
79
+ /**
80
+ * 比较两份快照。
81
+ * @param {object | null} previous - 上一次成功的快照。
82
+ * @param {object | null} next - 当前快照。
83
+ * @returns {object | null} 差集;缺少任一侧时 null。
84
+ */
85
+ function diffSnapshots(previous, next) {
86
+ if (previous === null || previous === undefined || next === null || next === undefined) return null
87
+ const beforeEntries = Array.isArray(previous.entries) ? previous.entries : []
88
+ const afterEntries = Array.isArray(next.entries) ? next.entries : []
89
+ const beforeById = new Map(beforeEntries.map((entry) => [entry.entryId, entry]))
90
+ const afterById = new Map(afterEntries.map((entry) => [entry.entryId, entry]))
91
+
92
+ const added = afterEntries.filter((entry) => !beforeById.has(entry.entryId))
93
+ const removed = beforeEntries.filter((entry) => !afterById.has(entry.entryId))
94
+ const changed = []
95
+ for (const entry of afterEntries) {
96
+ const before = beforeById.get(entry.entryId)
97
+ if (before === undefined) continue
98
+ if (digest(before) === digest(entry)) continue
99
+ changed.push({ entry, fields: changedFields(before, entry) })
100
+ }
101
+
102
+ const beforeTools = new Set((previous.tools?.attributed ?? []).map((tool) => tool.name))
103
+ const afterTools = new Set((next.tools?.attributed ?? []).map((tool) => tool.name))
104
+ const toolsAdded = [...afterTools].filter((name) => !beforeTools.has(name))
105
+ const toolsRemoved = [...beforeTools].filter((name) => !afterTools.has(name))
106
+
107
+ const items = [
108
+ ...added.map((entry) => ({
109
+ kind: 'added',
110
+ title: '新增 ' + labelOf(entry),
111
+ detail: entry.moduleName,
112
+ entryId: entry.entryId,
113
+ rowId: entry.rowId,
114
+ })),
115
+ ...removed.map((entry) => ({
116
+ kind: 'removed',
117
+ title: '移除 ' + labelOf(entry),
118
+ detail: entry.moduleName,
119
+ entryId: entry.entryId,
120
+ })),
121
+ ...changed.map(({ entry, fields }) => ({
122
+ kind: 'changed',
123
+ title: '变化 ' + labelOf(entry),
124
+ detail: fields.length > 0 ? fields.join('、') : '注册内容变化',
125
+ entryId: entry.entryId,
126
+ rowId: entry.rowId,
127
+ })),
128
+ ...toolsAdded.map((name) => ({ kind: 'tool-added', title: '新增工具 ' + name, toolName: name })),
129
+ ...toolsRemoved.map((name) => ({ kind: 'tool-removed', title: '移除工具 ' + name, toolName: name })),
130
+ ]
131
+
132
+ return {
133
+ from: previous.generatedAt,
134
+ to: next.generatedAt,
135
+ added,
136
+ removed,
137
+ changed,
138
+ toolsAdded,
139
+ toolsRemoved,
140
+ total: items.length,
141
+ items: items.slice(0, 40),
142
+ }
143
+ }
144
+
145
+ /** 变更项的展示类型。 */
146
+ const KIND_LABEL = {
147
+ added: '新增',
148
+ removed: '移除',
149
+ changed: '变化',
150
+ 'tool-added': '工具+',
151
+ 'tool-removed': '工具-',
152
+ }
153
+
154
+ /**
155
+ * 插件页顶部的变更条;没有变化时不占位置。
156
+ * @param {object} vc - 视图上下文。
157
+ * @returns {object | null} React 节点。
158
+ */
159
+ function renderChanges(vc) {
160
+ const { changes, gotoPlugin, gotoTool } = vc
161
+ if (changes === null || changes === undefined || changes.total === 0) return null
162
+ return h(
163
+ 'details',
164
+ { className: 'ptAttention ptChanges' },
165
+ h(
166
+ 'summary',
167
+ null,
168
+ h('span', null, '自上次刷新'),
169
+ h('span', { className: 'ptCount' }, `+${changes.added.length} / -${changes.removed.length} / 改 ${changes.changed.length}`),
170
+ changes.toolsAdded.length + changes.toolsRemoved.length > 0
171
+ ? h('span', { className: 'ptFoldMeta' }, `工具 +${changes.toolsAdded.length} / -${changes.toolsRemoved.length}`)
172
+ : h('span', { className: 'ptFoldMeta' }, '点开看明细'),
173
+ ),
174
+ h(
175
+ 'ul',
176
+ { className: 'ptAttentionList' },
177
+ changes.items.map((item) => {
178
+ const action = item.rowId !== undefined
179
+ ? textButton('查看', () => gotoPlugin(item.rowId), { title: '在插件页展开这一条' })
180
+ : item.toolName !== undefined
181
+ ? textButton('查看工具', () => gotoTool(item.toolName), { title: '在工具页查看这个工具' })
182
+ : null
183
+ return h(
184
+ 'li',
185
+ { key: item.kind + ':' + (item.entryId ?? item.toolName ?? item.title), className: 'ptAttentionRow', 'data-severity': 'info' },
186
+ h('span', { className: 'ptSeverity', 'data-severity': 'info' }, KIND_LABEL[item.kind] ?? '变化'),
187
+ h(
188
+ 'span',
189
+ { className: 'ptAttentionText' },
190
+ h('span', { className: 'ptAttentionTitle' }, item.title),
191
+ item.detail ? h('span', { className: 'ptAttentionDetail' }, item.detail) : null,
192
+ ),
193
+ action,
194
+ )
195
+ }),
196
+ changes.total > changes.items.length
197
+ ? h('li', { className: 'ptAttentionRow', 'data-severity': 'info' }, h('span', { className: 'ptAttentionDetail' }, `还有 ${changes.total - changes.items.length} 项未列出`))
198
+ : null,
199
+ ),
200
+ )
201
+ }
202
+
203
+ return { diffSnapshots, renderChanges }
204
+ }
205
+ },
206
+ })
@@ -0,0 +1,270 @@
1
+ /**
2
+ * 提示词模板数据清理的状态与动作。
3
+ *
4
+ * 单独成一个 chunk:它只依赖 shared 的请求函数和若干回调,不需要编辑器状态;
5
+ * `client.store.js` 把「刷新快照 / 重取提示词模板列表 / 清空编辑器」作为参数传进来。
6
+ *
7
+ * 三种范围:
8
+ * - session:只清该会话的绑定与开关;
9
+ * - workspace:只清该工作区的绑定与开关,提示词模板定义保留;
10
+ * - all:清空全部并删除存储文件。
11
+ *
12
+ * 本文件是一个包内 chunk:入口用 `require.async('./client.cleanup.js')` 取它。
13
+ */
14
+ window.__ModuleLoader__.load({
15
+ id: '@cheemsup/dsh-plugin-console',
16
+ chunk: 'client.cleanup.js',
17
+ factory: (require) => {
18
+ const React = require('react')
19
+ const { useCallback, useState } = React
20
+
21
+ return function create(deps) {
22
+ const { shared } = deps
23
+ const { fetchJson, CLEANUP_ROUTE, selectField, h } = shared
24
+
25
+ /** 清理目标的稳定标识,用来判断两次点击是不是同一个目标。 */
26
+ function keyOf(target) {
27
+ if (target === null) return null
28
+ if (target.scope === 'session') return 'session:' + target.sessionId
29
+ return target.scope === 'workspace' ? 'workspace:' + target.workspaceId : 'all'
30
+ }
31
+
32
+ /** 把接口结果说成一句人话。 */
33
+ function describe(data) {
34
+ if (data.scope === 'session') {
35
+ return [
36
+ '已清理会话 ' + data.sessionId,
37
+ '绑定 ' + (data.removedManifests ?? 0) + ' 条',
38
+ '开关 ' + (data.removedActivations ?? 0) + ' 条',
39
+ '掩码 ' + (data.removedMasks ?? 0) + ' 条',
40
+ '提示词模板定义保留(' + (data.keptTemplates ?? 0) + ' 个)',
41
+ '运行中的会话不受影响',
42
+ ].join(' · ')
43
+ }
44
+ if (data.scope === 'workspace') {
45
+ const notes = [
46
+ '已清理 ' + (data.touchedSessions ?? 0) + ' 个会话',
47
+ '绑定 ' + (data.removedManifests ?? 0) + ' 条',
48
+ '开关 ' + (data.removedActivations ?? 0) + ' 条',
49
+ '提示词模板定义保留(' + (data.keptTemplates ?? 0) + ' 个)',
50
+ ]
51
+ if (data.liveSessionsUntouched === true) notes.push('运行中的会话不受影响')
52
+ return notes.join(' · ')
53
+ }
54
+ const notes = [
55
+ '已清除 ' + (data.removedTemplates ?? 0) + ' 个提示词模板',
56
+ (data.removedRevisions ?? 0) + ' 条历史',
57
+ '绑定 ' + (data.removedManifests ?? 0) + ' 条',
58
+ '开关 ' + (data.removedActivations ?? 0) + ' 条',
59
+ ]
60
+ notes.push(data.fileDeleted === true
61
+ ? '提示词模板文件已删除'
62
+ : '提示词模板文件删除失败:' + (data.fileError ?? '原因未知'))
63
+ if (data.liveSessionsUntouched === true) notes.push('运行中的会话不受影响')
64
+ return notes.join(' · ')
65
+ }
66
+
67
+ /**
68
+ * 清理状态。
69
+ * @param {object} options - 回调。
70
+ * @param {Function} options.reloadSnapshot - 重取快照。
71
+ * @param {Function} options.loadTemplates - 重取提示词模板列表。
72
+ * @param {Function} options.onClearedAll - 全局清理后把编辑器退回纯基线。
73
+ * @returns {object} 清理状态与动作。
74
+ */
75
+ function useCleanupStore({ reloadSnapshot, loadTemplates, onClearedAll }) {
76
+ const [cleanupPending, setCleanupPending] = useState(null)
77
+ const [cleanupBusy, setCleanupBusy] = useState(null)
78
+ const [cleanupNotice, setCleanupNotice] = useState(null)
79
+
80
+ const runCleanup = useCallback(async (target) => {
81
+ setCleanupBusy(keyOf(target))
82
+ setCleanupNotice(null)
83
+ try {
84
+ const data = await fetchJson(CLEANUP_ROUTE, {
85
+ method: 'POST',
86
+ body: JSON.stringify(target.scope === 'session'
87
+ ? { scope: 'session', sessionId: target.sessionId }
88
+ : target.scope === 'workspace'
89
+ ? { scope: 'workspace', workspaceId: target.workspaceId }
90
+ : { scope: 'all' }),
91
+ })
92
+ setCleanupPending(null)
93
+ setCleanupNotice(describe(data))
94
+ await loadTemplates()
95
+ if (target.scope === 'all') onClearedAll()
96
+ await reloadSnapshot()
97
+ } catch (cause) {
98
+ setCleanupNotice('清理失败:' + (cause instanceof Error ? cause.message : String(cause)))
99
+ } finally {
100
+ setCleanupBusy(null)
101
+ }
102
+ }, [reloadSnapshot, loadTemplates, onClearedAll])
103
+
104
+ const requestCleanup = useCallback((target) => {
105
+ if (cleanupPending !== null && keyOf(cleanupPending) === keyOf(target)) {
106
+ void runCleanup(target)
107
+ return
108
+ }
109
+ setCleanupPending(target)
110
+ setCleanupNotice(null)
111
+ }, [cleanupPending, runCleanup])
112
+
113
+ const cancelCleanup = useCallback(() => {
114
+ setCleanupPending(null)
115
+ setCleanupNotice(null)
116
+ }, [])
117
+
118
+ return {
119
+ cleanupPending,
120
+ cleanupBusy,
121
+ cleanupNotice,
122
+ requestCleanup,
123
+ runCleanup,
124
+ cancelCleanup,
125
+ }
126
+ }
127
+
128
+ /**
129
+ * 定制页底部的「清除提示词定制模板快照数据」卡片。
130
+ *
131
+ * 会话页只保留单会话清理;工作区与全部清理收在这里,因为它们动的是
132
+ * 提示词模板存储本身,而不是某个会话的开关。两种范围都沿用两段式确认。
133
+ * @param {object} vc - 视图上下文。
134
+ * @returns {object} React 节点。
135
+ */
136
+ function renderCleanupCard(vc) {
137
+ return h(CleanupCard, { vc })
138
+ }
139
+
140
+ function CleanupCard({ vc }) {
141
+ const { snapshot, cleanupPending, cleanupBusy, cleanupNotice, requestCleanup, runCleanup, cancelCleanup } = vc
142
+ const workspaces = snapshot?.workspaces ?? []
143
+ const [scope, setScope] = useState('workspace')
144
+ const [workspaceId, setWorkspaceId] = useState(workspaces[0]?.id ?? '')
145
+ const effectiveWorkspace = workspaceId !== '' ? workspaceId : (workspaces[0]?.id ?? '')
146
+ const target = scope === 'all'
147
+ ? { scope: 'all' }
148
+ : { scope: 'workspace', workspaceId: effectiveWorkspace }
149
+ const pending = cleanupPending !== null && cleanupPending !== undefined && keyOf(cleanupPending) === keyOf(target)
150
+ const busy = cleanupBusy !== null && cleanupBusy !== undefined
151
+ const boundCount = countWorkspaceBindings(snapshot, effectiveWorkspace, vc.allSessions)
152
+ const disabled = busy || (scope === 'workspace' && effectiveWorkspace === '')
153
+ const label = scope === 'all' ? '清理全部提示词模板数据' : '清理本工作区绑定'
154
+ // 范围不同、影响面也不同:说明收进标题的悬停里,不占正文行。
155
+ const explain = scope === 'all'
156
+ ? '会删除全部提示词定制模板、历史、绑定、开关、掩码与控制审计,并删除 plugin_console_templates.json。运行中的会话不受影响。'
157
+ : '删除工作区会话(含派生子 Agent)的相关快照文件,运行中会话不受影响'
158
+
159
+ return h(
160
+ // 破坏性操作不常驻版面:收起时只留一行居中小字,点开才是真正的清理卡。
161
+ // 用 details 而不是受控 state:展开/收起是纯显示状态,浏览器自己管更省事,
162
+ // 也让键盘与无障碍行为保持原生。
163
+ 'details',
164
+ { className: 'ptCleanupFold' },
165
+ h(
166
+ 'summary',
167
+ {
168
+ className: 'ptCleanupSummary',
169
+ title: '清理快照数据:展开后可以清理单个工作区的绑定,或删除全部提示词模板数据',
170
+ },
171
+ h('span', null, '清理快照数据'),
172
+ h('span', { className: 'ptCleanupCaret', 'aria-hidden': 'true' }),
173
+ ),
174
+ h(
175
+ 'div',
176
+ { className: 'ptCard ptDangerCard' },
177
+ h(
178
+ 'div',
179
+ { className: 'ptCardHead' },
180
+ h('p', { className: 'ptCardTitle', title: explain }, '清除提示词定制模板快照数据'),
181
+ ),
182
+ h(
183
+ 'div',
184
+ { className: 'ptCardRow' },
185
+ selectField('范围', scope, [
186
+ { value: 'workspace', label: '单个工作区的绑定' },
187
+ { value: 'all', label: '全部提示词模板数据' },
188
+ ], setScope),
189
+ scope === 'workspace'
190
+ ? selectField('工作区', effectiveWorkspace, workspaces.map((workspace) => ({
191
+ value: workspace.id,
192
+ label: (workspace.title ?? workspace.path ?? workspace.id) + (typeof workspace.lastActiveAt === 'number' ? ' · 最近活跃 ' + ageText(workspace.lastActiveAt) : ''),
193
+ })), setWorkspaceId)
194
+ : null,
195
+ scope === 'workspace'
196
+ ? h('span', { className: 'ptMeta' }, `该工作区 ${boundCount} 个会话绑定了提示词模板`)
197
+ : null,
198
+ h(
199
+ 'div',
200
+ { className: 'ptCardActions' },
201
+ pending
202
+ ? h(
203
+ React.Fragment,
204
+ null,
205
+ h('button', {
206
+ type: 'button',
207
+ className: 'ptBtn',
208
+ 'data-tone': 'danger',
209
+ disabled,
210
+ onClick: () => { void runCleanup(target) },
211
+ }, '确认' + label),
212
+ h('button', {
213
+ type: 'button',
214
+ className: 'ptBtn',
215
+ disabled,
216
+ onClick: cancelCleanup,
217
+ }, '取消'),
218
+ )
219
+ : h('button', {
220
+ type: 'button',
221
+ className: 'ptBtn',
222
+ 'data-tone': 'danger',
223
+ disabled,
224
+ onClick: () => { requestCleanup(target) },
225
+ }, label),
226
+ ),
227
+ ),
228
+ cleanupNotice !== null && cleanupNotice !== undefined
229
+ ? h('p', { className: 'ptSub', style: { margin: 0 } }, cleanupNotice)
230
+ : null,
231
+ ),
232
+ )
233
+ }
234
+
235
+ /** 工作区里绑了提示词模板的会话数(沿 parentSession 把派生会话也算进来)。 */
236
+ function countWorkspaceBindings(snapshot, workspaceId, allSessions) {
237
+ const workspace = (snapshot?.workspaces ?? []).find((candidate) => candidate.id === workspaceId)
238
+ if (workspace === undefined) return 0
239
+ const owned = new Set((workspace.sessions ?? []).map((session) => session.id))
240
+ return Object.keys(snapshot?.bindings ?? {}).filter((sessionId) => {
241
+ let cursor = allSessions?.get?.(sessionId)
242
+ const seen = new Set()
243
+ while (cursor !== undefined && !seen.has(cursor.id)) {
244
+ if (owned.has(cursor.id)) return true
245
+ seen.add(cursor.id)
246
+ cursor = typeof cursor.parentSession === 'string' ? allSessions.get(cursor.parentSession) : undefined
247
+ }
248
+ return false
249
+ }).length
250
+ }
251
+
252
+ /** 只用于卡片里的相对时间,避免再引一份格式化工具。 */
253
+ function ageText(timestamp) {
254
+ const delta = Date.now() - timestamp
255
+ if (!Number.isFinite(delta) || delta < 0) return '—'
256
+ const minutes = Math.floor(delta / 60000)
257
+ if (minutes < 1) return '刚刚'
258
+ if (minutes < 60) return minutes + ' 分钟前'
259
+ const hours = Math.floor(minutes / 60)
260
+ if (hours < 24) return hours + ' 小时前'
261
+ return Math.floor(hours / 24) + ' 天前'
262
+ }
263
+
264
+ // 这个 chunk 的主出口仍是 store 工厂(`cleanup(...)`);清理卡片作为
265
+ // 它的属性导出,避免 store 与编辑器各拿一份不同的实例。
266
+ useCleanupStore.renderCleanupCard = renderCleanupCard
267
+ return useCleanupStore
268
+ }
269
+ },
270
+ })