@v587d/capital-generation 2.12.0 → 2.13.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.
@@ -0,0 +1,777 @@
1
+ /**
2
+ * Browser half of `@v587d/capital-automation`: a host-plane page at the `capital-automation`
3
+ * main key plus the adjacent sidebar row. No turn-tail slot, no custom session events, and no
4
+ * official `schedules` identity. Requests go to our own `/capital-automation` route; the page
5
+ * only reads the one profile the server put it in and never sends a profile or owner field.
6
+ */
7
+ const { createElement: h, useEffect, useRef, useState } = require('react')
8
+ const { IconChecklistOutlineRegular, Modal, Switch } = require('@deepseek-ai/dsh-client-ui-primitives')
9
+
10
+ const ENTRY_NAME = 'capital-automation'
11
+ const ROUTE = '/capital-automation'
12
+ const PANEL_ID = 'capital-automation'
13
+ const STYLE_TAG = 'capital-automation-css'
14
+
15
+ const zh = {
16
+ panel: 'CapGen 投研自动化',
17
+ title: 'CapGen 投研自动化',
18
+ subtitle: '独立于官方「自动化任务」的定时投研任务、运行记录与通知',
19
+ profile: '当前 profile',
20
+ scheduler: '调度器',
21
+ schedulerActive: '运行权已取得',
22
+ schedulerStandby: '未取得运行权(只读)',
23
+ schedulerStarting: '启动中',
24
+ schedulerStopped: '已停止',
25
+ calendar: '交易日历',
26
+ calendarOk: '可用',
27
+ calendarMissing: '不可用(交易日任务会跳过)',
28
+ storageUnavailable: '存储不可用,页面只读',
29
+ loading: '读取中…',
30
+ empty: '还没有任务。',
31
+ noSelection: '从左侧选择一个任务。',
32
+ newTask: '新建任务',
33
+ groups: { running: '运行中', news: '资讯', market: '行情', review: '复盘', research: '研究', custom: '我的任务' },
34
+ stateLabel: '状态',
35
+ state: { dormant: '休眠', active: '启用', paused: '暂停' },
36
+ status: {
37
+ queued: '排队中', starting: '启动中', running: '运行中', succeeded: '成功', failed: '失败',
38
+ canceled: '已取消', timed_out: '超时', blocked_requires_user: '需要用户确认',
39
+ unknown_after_restart: '重启后未知', skipped_overlap: '重叠跳过',
40
+ skipped_calendar_unavailable: '日历不可用跳过', missed: '错过',
41
+ },
42
+ mode: { news: '资讯', market: '行情', review: '复盘', research: '研究' },
43
+ cadence: { daily: '每天', weekly: '每周', monthly: '每月' },
44
+ nextRun: '下次运行',
45
+ lastResult: '上次结果',
46
+ unread: '未读',
47
+ never: '暂无',
48
+ overview: '概览',
49
+ config: '配置',
50
+ runs: '运行记录',
51
+ policy: '执行策略',
52
+ notifications: '通知',
53
+ titleField: '标题',
54
+ descriptionField: '说明',
55
+ instructionField: '任务指令',
56
+ triggerField: '触发',
57
+ timeField: '时间',
58
+ timezoneField: '时区',
59
+ weekdayField: '星期(ISO 1–7)',
60
+ dayField: '每月几号(1–28)',
61
+ tradingDaysField: '仅交易日',
62
+ modeField: '输出侧重',
63
+ modeHint: '只影响输出结构,不改变 Agent preset;所有运行固定使用 Capital 自动模式。',
64
+ presetLabel: 'Agent preset',
65
+ presetValue: 'capital-generation(自动模式)',
66
+ workspaceField: '工作区',
67
+ workspaceDefault: '跟随默认工作区',
68
+ workspaceMissing: '已移除的工作区(请重新选择)',
69
+ workspaceUnavailable: '工作区服务暂时不可用,运行会退回默认目录。',
70
+ limitsField: '运行上限',
71
+ runTimeout: 'wall-clock(分钟)',
72
+ idleTimeout: '空闲超时(分钟)',
73
+ maxSteps: '最大步骤',
74
+ maxToolCalls: '最大工具调用',
75
+ notifyField: '通知',
76
+ notifyInApp: '应用内通知',
77
+ notifyFailure: '失败时通知',
78
+ notifySuccess: '成功时通知',
79
+ save: '保存',
80
+ saving: '保存中…',
81
+ saved: '已保存',
82
+ activate: '启用',
83
+ pause: '暂停',
84
+ hibernate: '休眠并恢复默认',
85
+ copy: '复制为我的任务',
86
+ remove: '删除',
87
+ runNow: '手动运行',
88
+ cancelRun: '取消运行',
89
+ openSession: '打开 session',
90
+ detail: '详情',
91
+ close: '关闭',
92
+ create: '创建',
93
+ back: '上一步',
94
+ next: '下一步',
95
+ step1: '基本信息',
96
+ step2: '触发',
97
+ step3: '执行',
98
+ required: '标题、指令不能为空。',
99
+ inboxEmpty: '没有通知。',
100
+ markRead: '全部已读',
101
+ noRuns: '还没有运行记录。',
102
+ duration: '耗时',
103
+ steps: '步骤',
104
+ tools: '工具调用',
105
+ errorTitle: '错误',
106
+ policyText: '固定 preset:capital-generation(Capital 自动模式);cwd:任务选定的工作区,'
107
+ + '未选择时使用 CapGen 投研自动化工作区;只允许 Capital 角色工具族;'
108
+ + '无人值守运行禁止提问、写文件与 shell 提权。',
109
+ budgetHint: '工具调用与步骤预算覆盖整棵运行子树:子 Agent 与 PTC 派发都计入。',
110
+ errorGeneric: '操作失败,请稍后重试。',
111
+ needConfirm: '需要用户确认',
112
+ }
113
+
114
+ const STATUS_ORDER = ['queued', 'starting', 'running', 'succeeded', 'failed', 'canceled', 'timed_out', 'blocked_requires_user', 'unknown_after_restart', 'skipped_overlap', 'skipped_calendar_unavailable', 'missed']
115
+
116
+ function installStyles() {
117
+ if (typeof document === 'undefined' || document.querySelector(`style[data-${STYLE_TAG}]`)) return () => {}
118
+ const style = document.createElement('style')
119
+ style.setAttribute(`data-${STYLE_TAG}`, 'true')
120
+ style.textContent = `
121
+ .capital-automation-page { display: flex; flex-direction: column; gap: 14px; min-height: 0; height: 100%; padding: 20px 24px 24px; color: var(--dsw-alias-label-primary); }
122
+ .capital-automation-head { display: flex; flex-wrap: wrap; align-items: flex-start; justify-content: space-between; gap: 12px; }
123
+ .capital-automation-title { margin: 0; font-size: 20px; line-height: 28px; font-weight: 600; letter-spacing: .2px; }
124
+ .capital-automation-sub { margin: 2px 0 0; color: var(--dsw-alias-label-tertiary); font-size: 12px; line-height: 18px; }
125
+ .capital-automation-meta { display: flex; flex-wrap: wrap; gap: 6px 12px; color: var(--dsw-alias-label-secondary); font-size: 12px; line-height: 20px; }
126
+ .capital-automation-badge { display: inline-flex; align-items: center; gap: 4px; padding: 2px 8px; border-radius: 999px; background: var(--dsw-alias-bg-module-platform); }
127
+ .capital-automation-badge[data-ok="false"] { color: var(--dsw-alias-state-warn-label); }
128
+ .capital-automation-badge[data-ok="true"] { color: var(--dsw-alias-state-success-primary); }
129
+ .capital-automation-banner { padding: 10px 14px; border: .5px solid var(--dsw-alias-state-error-primary); border-radius: 10px; color: var(--dsw-alias-state-error-primary); background: var(--dsw-alias-state-error-tertiary, transparent); font-size: 12px; line-height: 18px; }
130
+ .capital-automation-body { display: grid; grid-template-columns: minmax(260px, 340px) minmax(0, 1fr); gap: 16px; min-height: 0; flex: 1 1 auto; }
131
+ .capital-automation-list { display: flex; flex-direction: column; gap: 10px; min-height: 0; overflow: auto; padding-right: 4px; }
132
+ .capital-automation-group { display: flex; flex-direction: column; gap: 4px; }
133
+ .capital-automation-group-title { margin: 0; padding: 4px 2px; color: var(--dsw-alias-label-tertiary); font-size: 11px; font-weight: 600; letter-spacing: .3px; }
134
+ .capital-automation-task { display: flex; flex-direction: column; gap: 3px; width: 100%; padding: 10px 12px; border: .5px solid var(--dsw-alias-border-l1); border-radius: 10px; background: var(--dsw-alias-bg-layer-2); color: inherit; font: inherit; text-align: left; cursor: pointer; }
135
+ .capital-automation-task[aria-selected="true"] { border-color: var(--dsw-alias-brand-primary); box-shadow: inset 0 0 0 1px var(--dsw-alias-brand-primary); }
136
+ .capital-automation-task:hover { background: var(--dsw-alias-interactive-bg-hover); }
137
+ .capital-automation-task-row { display: flex; align-items: center; gap: 6px; min-width: 0; }
138
+ .capital-automation-task-title { flex: 1 1 auto; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; font-size: 13px; font-weight: 500; }
139
+ .capital-automation-task-meta { display: flex; flex-wrap: wrap; gap: 4px 10px; color: var(--dsw-alias-label-tertiary); font-size: 11px; line-height: 16px; }
140
+ .capital-automation-dot { flex: none; width: 6px; height: 6px; border-radius: 50%; background: var(--dsw-alias-label-tertiary); }
141
+ .capital-automation-dot[data-run="true"] { background: var(--dsw-alias-state-business-primary); }
142
+ .capital-automation-count { flex: none; min-width: 16px; padding: 0 5px; border-radius: 999px; background: var(--dsw-alias-state-business-primary); color: #fff; font-size: 10px; line-height: 16px; text-align: center; }
143
+ .capital-automation-detail { display: flex; flex-direction: column; gap: 14px; min-width: 0; overflow: auto; padding: 4px 4px 8px; }
144
+ .capital-automation-card { border: .5px solid var(--dsw-alias-border-l1); border-radius: 12px; background: var(--dsw-alias-bg-layer-2); padding: 14px 16px; display: flex; flex-direction: column; gap: 10px; }
145
+ .capital-automation-card h3 { margin: 0; font-size: 14px; font-weight: 600; }
146
+ .capital-automation-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); gap: 10px; }
147
+ .capital-automation-field { display: flex; flex-direction: column; gap: 4px; min-width: 0; }
148
+ .capital-automation-field > span { color: var(--dsw-alias-label-tertiary); font-size: 11px; line-height: 16px; }
149
+ .capital-automation-field input, .capital-automation-field select, .capital-automation-field textarea { width: 100%; box-sizing: border-box; padding: 7px 9px; border: .5px solid var(--dsw-alias-border-l1); border-radius: 8px; background: var(--dsw-alias-bg-module-platform); color: var(--dsw-alias-label-primary); font: inherit; font-size: 12px; line-height: 18px; }
150
+ .capital-automation-field textarea { min-height: 120px; resize: vertical; }
151
+ .capital-automation-field input:focus-visible, .capital-automation-field select:focus-visible, .capital-automation-field textarea:focus-visible, .capital-automation-btn:focus-visible, .capital-automation-task:focus-visible { outline: var(--dsw-focus-ring-width) solid var(--dsw-focus-ring-color, var(--dsw-alias-brand-primary)); outline-offset: 1px; }
152
+ .capital-automation-actions { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; }
153
+ .capital-automation-btn { padding: 5px 11px; border: .5px solid var(--dsw-alias-border-l1); border-radius: 8px; background: var(--dsw-alias-bg-module-platform); color: var(--dsw-alias-label-primary); font: inherit; font-size: 12px; line-height: 18px; cursor: pointer; }
154
+ .capital-automation-btn:hover { background: var(--dsw-alias-interactive-bg-hover); }
155
+ .capital-automation-btn[data-primary="true"] { border-color: transparent; background: var(--dsw-alias-brand-primary); color: #fff; }
156
+ .capital-automation-btn[data-danger="true"] { color: var(--dsw-alias-state-error-primary); }
157
+ .capital-automation-btn:disabled { opacity: .5; cursor: not-allowed; }
158
+ .capital-automation-hint { margin: 0; color: var(--dsw-alias-label-tertiary); font-size: 11px; line-height: 17px; }
159
+ .capital-automation-notice { margin: 0; color: var(--dsw-alias-state-success-primary); font-size: 12px; line-height: 18px; }
160
+ .capital-automation-error { margin: 0; color: var(--dsw-alias-state-error-primary); font-size: 12px; line-height: 18px; }
161
+ .capital-automation-run { display: flex; flex-direction: column; gap: 4px; padding: 9px 0; border-bottom: .5px solid var(--dsw-alias-border-l2); }
162
+ .capital-automation-run:last-child { border-bottom: 0; }
163
+ .capital-automation-run-head { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; font-size: 12px; }
164
+ .capital-automation-run-status { font-weight: 600; }
165
+ .capital-automation-run-status[data-status="failed"], .capital-automation-run-status[data-status="timed_out"], .capital-automation-run-status[data-status="blocked_requires_user"] { color: var(--dsw-alias-state-error-primary); }
166
+ .capital-automation-run-status[data-status="succeeded"] { color: var(--dsw-alias-state-success-primary); }
167
+ .capital-automation-run-meta { color: var(--dsw-alias-label-tertiary); font-size: 11px; line-height: 16px; }
168
+ .capital-automation-error-item { color: var(--dsw-alias-state-error-primary); font-size: 11px; line-height: 16px; overflow-wrap: anywhere; }
169
+ .capital-automation-switch-row { display: flex; align-items: center; justify-content: space-between; gap: 10px; padding: 2px 0; }
170
+ .capital-automation-switch-row span { font-size: 12px; }
171
+ .capital-automation-wizard { display: flex; flex-direction: column; gap: 12px; min-height: 0; }
172
+ .capital-automation-steps { display: flex; gap: 6px; }
173
+ .capital-automation-step { flex: 1 1 auto; padding: 5px 8px; border-radius: 8px; background: var(--dsw-alias-bg-module-platform); color: var(--dsw-alias-label-tertiary); font-size: 11px; text-align: center; }
174
+ .capital-automation-step[data-active="true"] { background: var(--dsw-alias-brand-primary); color: #fff; }
175
+ .capital-automation-empty { padding: 28px 0; color: var(--dsw-alias-label-tertiary); font-size: 12px; text-align: center; }
176
+ @media (max-width: 780px) { .capital-automation-body { grid-template-columns: 1fr; } }
177
+ `
178
+ document.head.appendChild(style)
179
+ return () => style.remove()
180
+ }
181
+
182
+ function createApi() {
183
+ async function request(path, options = {}) {
184
+ const controller = typeof AbortController === 'function' ? new AbortController() : undefined
185
+ const timeout = setTimeout(() => controller?.abort(), 20_000)
186
+ let response
187
+ let payload
188
+ try {
189
+ response = await fetch(`${ROUTE}${path}`, {
190
+ method: options.method ?? 'GET',
191
+ credentials: 'same-origin',
192
+ headers: options.body === undefined ? {} : { 'content-type': 'application/json' },
193
+ body: options.body === undefined ? undefined : JSON.stringify(options.body),
194
+ ...(controller === undefined ? {} : { signal: controller.signal }),
195
+ })
196
+ try {
197
+ payload = await response.json()
198
+ } catch {
199
+ throw new Error(zh.errorGeneric)
200
+ }
201
+ } finally {
202
+ clearTimeout(timeout)
203
+ }
204
+ if (!response.ok || payload?.ok === false) {
205
+ const error = new Error(payload?.message ?? zh.errorGeneric)
206
+ error.code = payload?.code
207
+ throw error
208
+ }
209
+ return payload
210
+ }
211
+ return {
212
+ meta: () => request('/meta'),
213
+ tasks: () => request('/tasks'),
214
+ detail: (id) => request(`/tasks/${encodeURIComponent(id)}`),
215
+ create: (body) => request('/tasks', { method: 'POST', body }),
216
+ patch: (id, body) => request(`/tasks/${encodeURIComponent(id)}`, { method: 'PATCH', body }),
217
+ remove: (id) => request(`/tasks/${encodeURIComponent(id)}`, { method: 'DELETE' }),
218
+ action: (id, action) => request(`/tasks/${encodeURIComponent(id)}/${action}`, { method: 'POST' }),
219
+ run: (id) => request(`/tasks/${encodeURIComponent(id)}/run`, { method: 'POST' }),
220
+ cancel: (id) => request(`/runs/${encodeURIComponent(id)}/cancel`, { method: 'POST' }),
221
+ runs: (query = '') => request(`/runs${query}`),
222
+ notifications: () => request('/notifications'),
223
+ markRead: (body) => request('/notifications/read', { method: 'POST', body }),
224
+ }
225
+ }
226
+
227
+ function statusLabel(status) {
228
+ return zh.status[status] ?? status
229
+ }
230
+
231
+ function stateLabel(state) {
232
+ return zh.state[state] ?? state
233
+ }
234
+
235
+ function workspaceOptions(meta, current) {
236
+ const options = [{ id: '', title: zh.workspaceDefault }]
237
+ const list = Array.isArray(meta?.workspaces) ? meta.workspaces : []
238
+ for (const item of list) {
239
+ if (typeof item?.id !== 'string' || item.id.length === 0) continue
240
+ options.push({ id: item.id, title: item.default === true ? `${item.title}(默认)` : item.title })
241
+ }
242
+ if (typeof current === 'string' && current.length > 0 && !options.some((item) => item.id === current)) {
243
+ options.push({ id: current, title: zh.workspaceMissing })
244
+ }
245
+ return options
246
+ }
247
+
248
+ function formatTime(value) {
249
+ if (typeof value !== 'string' || value.length === 0) return zh.never
250
+ const date = new Date(value)
251
+ if (Number.isNaN(date.getTime())) return value
252
+ return new Intl.DateTimeFormat('zh-CN', { year: 'numeric', month: '2-digit', day: '2-digit', hour: '2-digit', minute: '2-digit', hourCycle: 'h23' }).format(date)
253
+ }
254
+
255
+ function formatDuration(ms) {
256
+ if (typeof ms !== 'number' || ms < 0) return zh.never
257
+ const seconds = Math.round(ms / 1000)
258
+ if (seconds < 60) return `${seconds}s`
259
+ const minutes = Math.floor(seconds / 60)
260
+ return `${minutes}m ${seconds % 60}s`
261
+ }
262
+
263
+ function groupTasks(tasks) {
264
+ const groups = new Map()
265
+ const running = tasks.filter((task) => task.lastRun && ['queued', 'starting', 'running'].includes(task.lastRun.status))
266
+ if (running.length > 0) groups.set('running', running)
267
+ const seen = new Set(running.map((task) => task.id))
268
+ for (const task of tasks) {
269
+ if (seen.has(task.id)) continue
270
+ const key = task.origin === 'custom' ? 'custom' : (task.category === 'market' ? 'market' : task.category === 'review' ? 'review' : task.category === 'research' ? 'research' : 'news')
271
+ const bucket = groups.get(key) ?? []
272
+ bucket.push(task)
273
+ groups.set(key, bucket)
274
+ }
275
+ return groups
276
+ }
277
+
278
+ function TaskRow(props) {
279
+ const { task, selected, onSelect } = props
280
+ const run = task.lastRun
281
+ const isRunning = run && ['queued', 'starting', 'running'].includes(run.status)
282
+ return h('button', {
283
+ type: 'button',
284
+ className: 'capital-automation-task',
285
+ 'aria-selected': selected ? 'true' : 'false',
286
+ onClick: () => onSelect(task.id),
287
+ },
288
+ h('span', { className: 'capital-automation-task-row' },
289
+ h('span', { className: 'capital-automation-dot', 'data-run': isRunning ? 'true' : 'false' }),
290
+ h('span', { className: 'capital-automation-task-title' }, task.title),
291
+ task.unread > 0 ? h('span', { className: 'capital-automation-count' }, String(task.unread)) : null,
292
+ h('span', { className: 'capital-automation-task-meta' }, stateLabel(task.state))),
293
+ h('span', { className: 'capital-automation-task-meta' },
294
+ h('span', null, `${zh.nextRun}: ${task.nextRunLocal ?? (task.nextRunUnavailable ? zh.calendarMissing : zh.never)}`),
295
+ h('span', null, `${zh.lastResult}: ${run ? statusLabel(run.status) : zh.never}`)))
296
+ }
297
+
298
+ function SwitchRow(props) {
299
+ return h('div', { className: 'capital-automation-switch-row' },
300
+ h('span', null, props.label),
301
+ h(Switch, { checked: props.checked === true, onChange: props.onChange, label: props.label, disabled: props.disabled }))
302
+ }
303
+
304
+ function TriggerFields(props) {
305
+ const { trigger, onChange, disabled } = props
306
+ const set = (patch) => onChange({ ...trigger, ...patch })
307
+ return h('div', { className: 'capital-automation-grid' },
308
+ h('label', { className: 'capital-automation-field' },
309
+ h('span', null, '节奏'),
310
+ h('select', {
311
+ value: trigger.cadence,
312
+ disabled,
313
+ onChange: (event) => {
314
+ const cadence = event.target.value
315
+ set({
316
+ cadence,
317
+ ...(cadence === 'weekly' ? { weekdays: trigger.weekdays ?? [1, 3, 5] } : { weekdays: undefined }),
318
+ ...(cadence === 'monthly' ? { dayOfMonth: trigger.dayOfMonth ?? 1 } : { dayOfMonth: undefined }),
319
+ })
320
+ },
321
+ },
322
+ Object.entries(zh.cadence).map(([value, label]) => h('option', { key: value, value }, label)))),
323
+ h('label', { className: 'capital-automation-field' },
324
+ h('span', null, zh.timeField),
325
+ h('input', { type: 'time', value: trigger.time, disabled, onChange: (event) => set({ time: event.target.value }) })),
326
+ h('label', { className: 'capital-automation-field' },
327
+ h('span', null, zh.timezoneField),
328
+ h('input', { type: 'text', value: trigger.timezone, disabled, onChange: (event) => set({ timezone: event.target.value }) })),
329
+ h('label', { className: 'capital-automation-field' },
330
+ h('span', null, zh.tradingDaysField),
331
+ h(Switch, { checked: trigger.tradingDaysOnly === true, onChange: (value) => set({ tradingDaysOnly: value }), label: zh.tradingDaysField, disabled })),
332
+ trigger.cadence === 'weekly' ? h('label', { className: 'capital-automation-field' },
333
+ h('span', null, zh.weekdayField),
334
+ h('input', {
335
+ type: 'text',
336
+ value: (trigger.weekdays ?? []).join(','),
337
+ disabled,
338
+ onChange: (event) => set({ weekdays: event.target.value.split(',').map((item) => Number(item.trim())).filter((item) => Number.isInteger(item) && item >= 1 && item <= 7) }),
339
+ })) : null,
340
+ trigger.cadence === 'monthly' ? h('label', { className: 'capital-automation-field' },
341
+ h('span', null, zh.dayField),
342
+ h('input', { type: 'number', min: 1, max: 28, value: trigger.dayOfMonth ?? 1, disabled, onChange: (event) => set({ dayOfMonth: Number(event.target.value) }) })) : null)
343
+ }
344
+
345
+ function TaskDetail(props) {
346
+ const { detail, meta, api, onChanged, openSession } = props
347
+ const [draft, setDraft] = useState(null)
348
+ const [busy, setBusy] = useState('')
349
+ const [notice, setNotice] = useState('')
350
+ const [error, setError] = useState('')
351
+
352
+ useEffect(() => {
353
+ setDraft(detail.task ? { ...detail.task, trigger: { ...detail.task.trigger }, limits: { ...detail.task.limits }, notifications: { ...detail.task.notifications } } : null)
354
+ setNotice('')
355
+ setError('')
356
+ }, [detail])
357
+
358
+ if (draft === null) return h('p', { className: 'capital-automation-empty' }, zh.loading)
359
+ const task = draft
360
+ const storageReady = meta?.storage?.state !== 'unavailable'
361
+ const running = detail.runs.some((run) => ['queued', 'starting', 'running'].includes(run.status))
362
+ const set = (patch) => setDraft((current) => ({
363
+ ...current,
364
+ ...(typeof patch === 'function' ? patch(current) : patch),
365
+ }))
366
+
367
+ async function act(name, action) {
368
+ if (busy) return
369
+ setBusy(name)
370
+ setError('')
371
+ setNotice('')
372
+ try {
373
+ await action()
374
+ setNotice(zh.saved)
375
+ await onChanged(detail.task.id)
376
+ } catch (failure) {
377
+ setError(failure.message ?? zh.errorGeneric)
378
+ } finally {
379
+ setBusy('')
380
+ }
381
+ }
382
+
383
+ async function save() {
384
+ await act('save', async () => {
385
+ const body = {
386
+ title: task.title.trim(),
387
+ description: task.description ?? '',
388
+ instruction: task.instruction,
389
+ category: task.category,
390
+ trigger: task.trigger,
391
+ mode: task.mode,
392
+ workspaceId: task.workspaceId ?? '',
393
+ limits: task.limits,
394
+ notifications: task.notifications,
395
+ }
396
+ if (body.title.length === 0 || body.instruction.trim().length === 0) throw new Error(zh.required)
397
+ await api.patch(task.id, body)
398
+ })
399
+ }
400
+
401
+ return h('div', { className: 'capital-automation-detail' },
402
+ h('section', { className: 'capital-automation-card' },
403
+ h('h3', null, zh.overview),
404
+ h('div', { className: 'capital-automation-grid' },
405
+ h('div', { className: 'capital-automation-field' }, h('span', null, zh.stateLabel), h('strong', null, stateLabel(task.state))),
406
+ h('div', { className: 'capital-automation-field' }, h('span', null, zh.nextRun), h('strong', null, detail.task.nextRunLocal ?? zh.never)),
407
+ h('div', { className: 'capital-automation-field' }, h('span', null, zh.lastResult), h('strong', null, detail.runs[0] ? statusLabel(detail.runs[0].status) : zh.never)),
408
+ h('div', { className: 'capital-automation-field' }, h('span', null, '来源'), h('strong', null, task.origin === 'builtin' ? '内置模板' : '我的任务'))),
409
+ h('div', { className: 'capital-automation-actions' },
410
+ h('button', { type: 'button', className: 'capital-automation-btn', 'data-primary': 'true', disabled: busy || !storageReady, onClick: () => act('run', async () => { await api.run(task.id) }) }, zh.runNow),
411
+ task.state === 'active'
412
+ ? h('button', { type: 'button', className: 'capital-automation-btn', disabled: busy || !storageReady, onClick: () => act('pause', async () => { await api.action(task.id, 'pause') }) }, zh.pause)
413
+ : h('button', { type: 'button', className: 'capital-automation-btn', disabled: busy || !storageReady, onClick: () => act('activate', async () => { await api.action(task.id, 'activate') }) }, zh.activate),
414
+ task.origin === 'builtin' && task.state !== 'dormant'
415
+ ? h('button', { type: 'button', className: 'capital-automation-btn', disabled: busy || running || !storageReady, onClick: () => act('hibernate', async () => { await api.action(task.id, 'hibernate') }) }, zh.hibernate)
416
+ : null,
417
+ task.origin === 'builtin'
418
+ ? h('button', { type: 'button', className: 'capital-automation-btn', disabled: busy || !storageReady, onClick: () => act('copy', async () => { await api.action(task.id, 'copy') }) }, zh.copy)
419
+ : h('button', { type: 'button', className: 'capital-automation-btn', 'data-danger': 'true', disabled: busy || running || !storageReady, onClick: () => act('remove', async () => { await api.remove(task.id) }) }, zh.remove)),
420
+ notice.length > 0 ? h('p', { className: 'capital-automation-notice' }, notice) : null,
421
+ error.length > 0 ? h('p', { className: 'capital-automation-error' }, error) : null),
422
+
423
+ h('section', { className: 'capital-automation-card' },
424
+ h('h3', null, zh.config),
425
+ h('label', { className: 'capital-automation-field' }, h('span', null, zh.titleField), h('input', { value: task.title, disabled: busy, onChange: (event) => set({ title: event.target.value }) })),
426
+ h('label', { className: 'capital-automation-field' }, h('span', null, zh.descriptionField), h('textarea', { value: task.description ?? '', disabled: busy, onChange: (event) => set({ description: event.target.value }) })),
427
+ h('label', { className: 'capital-automation-field' }, h('span', null, zh.instructionField), h('textarea', { value: task.instruction, disabled: busy, onChange: (event) => set({ instruction: event.target.value }) })),
428
+ h('h3', null, zh.triggerField),
429
+ h(TriggerFields, { trigger: task.trigger, disabled: busy, onChange: (trigger) => set({ trigger }) }),
430
+ h('div', { className: 'capital-automation-grid' },
431
+ h('label', { className: 'capital-automation-field' }, h('span', null, zh.workspaceField),
432
+ h('select', { value: task.workspaceId ?? '', disabled: busy, onChange: (event) => set({ workspaceId: event.target.value }) },
433
+ workspaceOptions(meta, task.workspaceId).map((option) => h('option', { key: option.id, value: option.id }, option.title)))),
434
+ h('label', { className: 'capital-automation-field' }, h('span', null, zh.modeField),
435
+ h('select', { value: task.mode, disabled: busy, onChange: (event) => set({ mode: event.target.value }) },
436
+ Object.entries(zh.mode).map(([value, label]) => h('option', { key: value, value }, label)))),
437
+ h('label', { className: 'capital-automation-field' }, h('span', null, zh.runTimeout),
438
+ h('input', { type: 'number', min: 5, max: 120, value: task.limits.runTimeoutMinutes, disabled: busy, onChange: (event) => set((current) => ({ limits: { ...current.limits, runTimeoutMinutes: Number(event.target.value) } })) })),
439
+ h('label', { className: 'capital-automation-field' }, h('span', null, zh.idleTimeout),
440
+ h('input', { type: 'number', min: 1, max: 30, value: task.limits.idleTimeoutMinutes, disabled: busy, onChange: (event) => set((current) => ({ limits: { ...current.limits, idleTimeoutMinutes: Number(event.target.value) } })) })),
441
+ h('label', { className: 'capital-automation-field' }, h('span', null, zh.maxSteps),
442
+ h('input', { type: 'number', min: 10, max: 2000, value: task.limits.maxSteps, disabled: busy, onChange: (event) => set((current) => ({ limits: { ...current.limits, maxSteps: Number(event.target.value) } })) })),
443
+ h('label', { className: 'capital-automation-field' }, h('span', null, zh.maxToolCalls),
444
+ h('input', { type: 'number', min: 10, max: 6000, value: task.limits.maxToolCalls, disabled: busy, onChange: (event) => set((current) => ({ limits: { ...current.limits, maxToolCalls: Number(event.target.value) } })) }))),
445
+ h('p', { className: 'capital-automation-hint' }, zh.modeHint),
446
+ meta?.workspaceError ? h('p', { className: 'capital-automation-error' }, zh.workspaceUnavailable) : null,
447
+ h('h3', null, zh.notifyField),
448
+ h(SwitchRow, { label: zh.notifyInApp, checked: task.notifications.inApp, disabled: busy, onChange: (value) => set((current) => ({ notifications: { ...current.notifications, inApp: value } })) }),
449
+ h(SwitchRow, { label: zh.notifyFailure, checked: task.notifications.onFailure, disabled: busy, onChange: (value) => set((current) => ({ notifications: { ...current.notifications, onFailure: value } })) }),
450
+ h(SwitchRow, { label: zh.notifySuccess, checked: task.notifications.onSuccess, disabled: busy, onChange: (value) => set((current) => ({ notifications: { ...current.notifications, onSuccess: value } })) }),
451
+ h('div', { className: 'capital-automation-actions' },
452
+ h('button', { type: 'button', className: 'capital-automation-btn', 'data-primary': 'true', disabled: busy || !storageReady, onClick: save }, busy === 'save' ? zh.saving : zh.save))),
453
+
454
+ h('section', { className: 'capital-automation-card' },
455
+ h('h3', null, zh.runs),
456
+ detail.runs.length === 0 ? h('p', { className: 'capital-automation-hint' }, zh.noRuns) : null,
457
+ detail.runs.map((run) => h('div', { key: run.id, className: 'capital-automation-run' },
458
+ h('div', { className: 'capital-automation-run-head' },
459
+ h('span', { className: 'capital-automation-run-status', 'data-status': run.status }, statusLabel(run.status)),
460
+ h('span', { className: 'capital-automation-run-meta' }, `${formatTime(run.queuedAt)} · ${run.trigger === 'manual' ? '手动' : '定时'}`),
461
+ typeof run.durationMs === 'number' ? h('span', { className: 'capital-automation-run-meta' }, `${zh.duration} ${formatDuration(run.durationMs)}`) : null,
462
+ h('span', { className: 'capital-automation-run-meta' }, `${zh.steps} ${run.steps} · ${zh.tools} ${run.toolCalls}`),
463
+ ['queued', 'starting', 'running'].includes(run.status)
464
+ ? h('button', { type: 'button', className: 'capital-automation-btn', 'data-danger': 'true', disabled: busy, onClick: () => act(`cancel-${run.id}`, async () => { await api.cancel(run.id) }) }, zh.cancelRun)
465
+ : run.sessionId && openSession
466
+ ? h('button', { type: 'button', className: 'capital-automation-btn', onClick: () => openSession(run.sessionId) }, zh.openSession)
467
+ : null),
468
+ run.sessionTitle ? h('span', { className: 'capital-automation-run-meta' }, run.sessionTitle) : null,
469
+ run.summary ? h('span', { className: 'capital-automation-run-meta' }, run.summary) : null,
470
+ run.errors.map((item, index) => h('span', { key: `${run.id}-${index}`, className: 'capital-automation-error-item' }, `${item.code}: ${item.message}`)))),
471
+
472
+ h('section', { className: 'capital-automation-card' },
473
+ h('h3', null, zh.policy),
474
+ h('p', { className: 'capital-automation-hint' }, zh.policyText),
475
+ h('p', { className: 'capital-automation-hint' }, zh.budgetHint),
476
+ h('p', { className: 'capital-automation-hint' }, `profileKey: ${meta?.profile?.key ?? '-'} · ${zh.presetLabel}: ${zh.presetValue} · cwdKind: profile`)),
477
+
478
+ h('section', { className: 'capital-automation-card' },
479
+ h('div', { className: 'capital-automation-actions' },
480
+ h('h3', null, zh.notifications),
481
+ detail.notifications.some((item) => item.readAt === undefined)
482
+ ? h('button', { type: 'button', className: 'capital-automation-btn', disabled: busy, onClick: () => act('read-notifications', async () => { await api.markRead({ all: true }) }) }, zh.markRead)
483
+ : null),
484
+ detail.notifications.length === 0 ? h('p', { className: 'capital-automation-hint' }, zh.inboxEmpty) : null,
485
+ detail.notifications.map((item) => h('div', { key: item.id, className: 'capital-automation-run' },
486
+ h('div', { className: 'capital-automation-run-head' },
487
+ h('strong', null, item.title),
488
+ h('span', { className: 'capital-automation-run-meta' }, formatTime(item.createdAt))),
489
+ h('span', { className: 'capital-automation-run-meta' }, item.message))))))
490
+ }
491
+
492
+ function NewTaskWizard(props) {
493
+ const { open, onClose, api, onCreated, meta } = props
494
+ const [step, setStep] = useState(0)
495
+ const [busy, setBusy] = useState(false)
496
+ const [error, setError] = useState('')
497
+ const [draft, setDraft] = useState({
498
+ title: '',
499
+ description: '',
500
+ instruction: '',
501
+ category: 'research',
502
+ trigger: { kind: 'schedule', cadence: 'daily', time: '09:00', timezone: 'Asia/Shanghai', tradingDaysOnly: true },
503
+ mode: 'research',
504
+ workspaceId: '',
505
+ limits: { runTimeoutMinutes: 30, idleTimeoutMinutes: 5, maxSteps: 300, maxToolCalls: 1200 },
506
+ notifications: { inApp: true, onFailure: true, onSuccess: false },
507
+ })
508
+ useEffect(() => {
509
+ if (!open) return
510
+ setStep(0)
511
+ setError('')
512
+ setBusy(false)
513
+ setDraft({
514
+ title: '',
515
+ description: '',
516
+ instruction: '',
517
+ category: 'research',
518
+ trigger: { kind: 'schedule', cadence: 'daily', time: '09:00', timezone: 'Asia/Shanghai', tradingDaysOnly: true },
519
+ mode: 'research',
520
+ workspaceId: '',
521
+ limits: { runTimeoutMinutes: 30, idleTimeoutMinutes: 5, maxSteps: 300, maxToolCalls: 1200 },
522
+ notifications: { inApp: true, onFailure: true, onSuccess: false },
523
+ })
524
+ }, [open])
525
+ const set = (patch) => setDraft((current) => ({
526
+ ...current,
527
+ ...(typeof patch === 'function' ? patch(current) : patch),
528
+ }))
529
+ async function create() {
530
+ if (draft.title.trim().length === 0 || draft.instruction.trim().length === 0) { setError(zh.required); return }
531
+ setBusy(true)
532
+ setError('')
533
+ try {
534
+ await api.create({
535
+ title: draft.title.trim(),
536
+ description: draft.description,
537
+ instruction: draft.instruction,
538
+ category: draft.category,
539
+ trigger: draft.trigger,
540
+ mode: draft.mode,
541
+ workspaceId: draft.workspaceId ?? '',
542
+ limits: draft.limits,
543
+ notifications: draft.notifications,
544
+ })
545
+ onCreated()
546
+ } catch (failure) {
547
+ setError(failure.message ?? zh.errorGeneric)
548
+ } finally {
549
+ setBusy(false)
550
+ }
551
+ }
552
+ if (!open) return null
553
+ return h(Modal, {
554
+ open,
555
+ onClose,
556
+ title: zh.newTask,
557
+ closeLabel: zh.close,
558
+ footer: h('div', { className: 'capital-automation-actions' },
559
+ step > 0 ? h('button', { type: 'button', className: 'capital-automation-btn', onClick: () => setStep(step - 1), disabled: busy }, zh.back) : null,
560
+ step < 2
561
+ ? h('button', { type: 'button', className: 'capital-automation-btn', 'data-primary': 'true', onClick: () => setStep(step + 1), disabled: busy }, zh.next)
562
+ : h('button', { type: 'button', className: 'capital-automation-btn', 'data-primary': 'true', onClick: create, disabled: busy || meta?.storage?.state === 'unavailable' }, busy ? zh.saving : zh.create)),
563
+ },
564
+ h('div', { className: 'capital-automation-wizard' },
565
+ h('div', { className: 'capital-automation-steps' },
566
+ [zh.step1, zh.step2, zh.step3].map((label, index) => h('span', { key: label, className: 'capital-automation-step', 'data-active': index === step ? 'true' : 'false' }, `${index + 1}. ${label}`))),
567
+ step === 0 ? h('div', { className: 'capital-automation-grid' },
568
+ h('label', { className: 'capital-automation-field' }, h('span', null, zh.titleField), h('input', { value: draft.title, onChange: (event) => set({ title: event.target.value }) })),
569
+ h('label', { className: 'capital-automation-field' }, h('span', null, zh.descriptionField), h('textarea', { value: draft.description, onChange: (event) => set({ description: event.target.value }) })),
570
+ h('label', { className: 'capital-automation-field' }, h('span', null, zh.instructionField), h('textarea', { value: draft.instruction, onChange: (event) => set({ instruction: event.target.value }) }))) : null,
571
+ step === 1 ? h('div', null,
572
+ h(TriggerFields, { trigger: draft.trigger, onChange: (trigger) => set({ trigger }) }),
573
+ h('p', { className: 'capital-automation-hint' }, '交易日历不可用时任务会记为 skipped_calendar_unavailable,不按周一至周五猜测运行。')) : null,
574
+ step === 2 ? h('div', null,
575
+ h('div', { className: 'capital-automation-grid' },
576
+ h('label', { className: 'capital-automation-field' }, h('span', null, zh.workspaceField),
577
+ h('select', { value: draft.workspaceId ?? '', onChange: (event) => set({ workspaceId: event.target.value }) },
578
+ workspaceOptions(meta, draft.workspaceId).map((option) => h('option', { key: option.id, value: option.id }, option.title)))),
579
+ h('label', { className: 'capital-automation-field' }, h('span', null, zh.modeField),
580
+ h('select', { value: draft.mode, onChange: (event) => set({ mode: event.target.value }) },
581
+ Object.entries(zh.mode).map(([value, label]) => h('option', { key: value, value }, label)))),
582
+ h('label', { className: 'capital-automation-field' }, h('span', null, zh.runTimeout), h('input', { type: 'number', min: 5, max: 120, value: draft.limits.runTimeoutMinutes, onChange: (event) => set((current) => ({ limits: { ...current.limits, runTimeoutMinutes: Number(event.target.value) } })) })),
583
+ h('label', { className: 'capital-automation-field' }, h('span', null, zh.idleTimeout), h('input', { type: 'number', min: 1, max: 30, value: draft.limits.idleTimeoutMinutes, onChange: (event) => set((current) => ({ limits: { ...current.limits, idleTimeoutMinutes: Number(event.target.value) } })) })),
584
+ h('label', { className: 'capital-automation-field' }, h('span', null, zh.maxSteps), h('input', { type: 'number', min: 10, max: 2000, value: draft.limits.maxSteps, onChange: (event) => set((current) => ({ limits: { ...current.limits, maxSteps: Number(event.target.value) } })) })),
585
+ h('label', { className: 'capital-automation-field' }, h('span', null, zh.maxToolCalls), h('input', { type: 'number', min: 10, max: 6000, value: draft.limits.maxToolCalls, onChange: (event) => set((current) => ({ limits: { ...current.limits, maxToolCalls: Number(event.target.value) } })) }))),
586
+ h('p', { className: 'capital-automation-hint' }, zh.modeHint),
587
+ meta?.workspaceError ? h('p', { className: 'capital-automation-error' }, zh.workspaceUnavailable) : null,
588
+ h(SwitchRow, { label: zh.notifyInApp, checked: draft.notifications.inApp, onChange: (value) => set((current) => ({ notifications: { ...current.notifications, inApp: value } })) }),
589
+ h(SwitchRow, { label: zh.notifyFailure, checked: draft.notifications.onFailure, onChange: (value) => set((current) => ({ notifications: { ...current.notifications, onFailure: value } })) }),
590
+ h(SwitchRow, { label: zh.notifySuccess, checked: draft.notifications.onSuccess, onChange: (value) => set((current) => ({ notifications: { ...current.notifications, onSuccess: value } })) })) : null,
591
+ error.length > 0 ? h('p', { className: 'capital-automation-error' }, error) : null))
592
+ }
593
+
594
+ function AutomationPage(props) {
595
+ const { api, openSession } = props
596
+ const [meta, setMeta] = useState(null)
597
+ const [tasks, setTasks] = useState([])
598
+ const [selectedId, setSelectedId] = useState(null)
599
+ const [detail, setDetail] = useState(null)
600
+ const [wizard, setWizard] = useState(false)
601
+ const [loadError, setLoadError] = useState('')
602
+ const mountedRef = useRef(false)
603
+ const selectedIdRef = useRef(null)
604
+ const refreshInFlightRef = useRef(null)
605
+ const refreshSequenceRef = useRef(0)
606
+ const detailSequenceRef = useRef(0)
607
+
608
+ async function refresh() {
609
+ if (refreshInFlightRef.current !== null) return refreshInFlightRef.current
610
+ const requestSequence = refreshSequenceRef.current + 1
611
+ refreshSequenceRef.current = requestSequence
612
+ const request = (async () => {
613
+ try {
614
+ const [nextMeta, nextTasks] = await Promise.all([api.meta(), api.tasks()])
615
+ if (!mountedRef.current || requestSequence !== refreshSequenceRef.current) return
616
+ const nextTaskList = Array.isArray(nextTasks.tasks) ? nextTasks.tasks : []
617
+ setMeta(nextMeta)
618
+ setTasks(nextTaskList)
619
+ setLoadError('')
620
+ const currentId = selectedIdRef.current
621
+ const nextId = currentId !== null && nextTaskList.some((task) => task.id === currentId)
622
+ ? currentId
623
+ : (nextTaskList[0]?.id ?? null)
624
+ if (nextId !== currentId) {
625
+ selectedIdRef.current = nextId
626
+ detailSequenceRef.current += 1
627
+ setDetail(null)
628
+ setSelectedId(nextId)
629
+ }
630
+ } catch (error) {
631
+ if (mountedRef.current && requestSequence === refreshSequenceRef.current) {
632
+ setLoadError(error.message ?? zh.errorGeneric)
633
+ }
634
+ }
635
+ })()
636
+ refreshInFlightRef.current = request
637
+ try {
638
+ await request
639
+ } finally {
640
+ if (refreshInFlightRef.current === request) refreshInFlightRef.current = null
641
+ }
642
+ }
643
+
644
+ async function loadDetail(id) {
645
+ const requestSequence = detailSequenceRef.current + 1
646
+ detailSequenceRef.current = requestSequence
647
+ try {
648
+ const value = await api.detail(id)
649
+ if (!mountedRef.current || requestSequence !== detailSequenceRef.current || selectedIdRef.current !== id) return
650
+ setDetail(value)
651
+ } catch (error) {
652
+ if (mountedRef.current && requestSequence === detailSequenceRef.current && selectedIdRef.current === id) {
653
+ setLoadError(error.message ?? zh.errorGeneric)
654
+ }
655
+ }
656
+ }
657
+
658
+ function selectTask(id) {
659
+ if (selectedIdRef.current === id) return
660
+ selectedIdRef.current = id
661
+ detailSequenceRef.current += 1
662
+ setDetail(null)
663
+ setSelectedId(id)
664
+ }
665
+
666
+ useEffect(() => {
667
+ mountedRef.current = true
668
+ void refresh()
669
+ const timer = setInterval(() => {
670
+ if (document.visibilityState !== 'hidden') void refresh()
671
+ }, 15_000)
672
+ const onVisibilityChange = () => {
673
+ if (document.visibilityState === 'visible') void refresh()
674
+ }
675
+ document.addEventListener?.('visibilitychange', onVisibilityChange)
676
+ return () => {
677
+ mountedRef.current = false
678
+ refreshSequenceRef.current += 1
679
+ detailSequenceRef.current += 1
680
+ refreshInFlightRef.current = null
681
+ clearInterval(timer)
682
+ document.removeEventListener?.('visibilitychange', onVisibilityChange)
683
+ }
684
+ }, [])
685
+
686
+ useEffect(() => {
687
+ if (selectedId === null) {
688
+ setDetail(null)
689
+ detailSequenceRef.current += 1
690
+ return undefined
691
+ }
692
+ setDetail(null)
693
+ void loadDetail(selectedId)
694
+ return () => { detailSequenceRef.current += 1 }
695
+ }, [selectedId])
696
+
697
+ const groups = groupTasks(tasks)
698
+ const schedulerState = meta?.scheduler?.state
699
+ const storageReady = meta?.storage?.state !== 'unavailable'
700
+ return h('div', { className: 'capital-automation-page' },
701
+ h('header', { className: 'capital-automation-head' },
702
+ h('div', null,
703
+ h('h1', { className: 'capital-automation-title' }, zh.title),
704
+ h('p', { className: 'capital-automation-sub' }, zh.subtitle)),
705
+ h('div', { className: 'capital-automation-meta' },
706
+ h('span', { className: 'capital-automation-badge' }, `${zh.profile}: ${meta?.profile?.name ?? '—'}`),
707
+ h('span', { className: 'capital-automation-badge', 'data-ok': schedulerState === 'active' ? 'true' : 'false' },
708
+ `${zh.scheduler}: ${schedulerState === 'active' ? zh.schedulerActive : schedulerState === 'standby' ? zh.schedulerStandby : schedulerState === 'stopped' ? zh.schedulerStopped : zh.schedulerStarting}`),
709
+ h('span', { className: 'capital-automation-badge', 'data-ok': meta?.calendar?.available === true ? 'true' : 'false' },
710
+ `${zh.calendar}: ${meta?.calendar?.available === true ? zh.calendarOk : zh.calendarMissing}`),
711
+ h('span', { className: 'capital-automation-badge' }, `v${meta?.version ?? '—'}`),
712
+ h('button', { type: 'button', className: 'capital-automation-btn', 'data-primary': 'true', disabled: !storageReady, onClick: () => setWizard(true) }, zh.newTask))),
713
+ !storageReady && meta ? h('div', { className: 'capital-automation-banner' }, `${zh.storageUnavailable}${meta.storage?.error ? `:${meta.storage.error}` : ''}`) : null,
714
+ loadError.length > 0 ? h('p', { className: 'capital-automation-error' }, loadError) : null,
715
+ h('div', { className: 'capital-automation-body' },
716
+ h('aside', { className: 'capital-automation-list' },
717
+ tasks.length === 0 ? h('p', { className: 'capital-automation-empty' }, zh.empty) : null,
718
+ [...groups.entries()].map(([key, bucket]) => h('section', { key, className: 'capital-automation-group' },
719
+ h('h2', { className: 'capital-automation-group-title' }, zh.groups[key] ?? key),
720
+ bucket.map((task) => h(TaskRow, { key: task.id, task, selected: task.id === selectedId, onSelect: selectTask }))))),
721
+ h('main', { className: 'capital-automation-detail' },
722
+ detail === null ? h('p', { className: 'capital-automation-empty' }, zh.noSelection) : null,
723
+ detail !== null ? h(TaskDetail, {
724
+ detail,
725
+ meta,
726
+ api,
727
+ openSession,
728
+ onChanged: async (taskId) => {
729
+ await refresh()
730
+ const id = taskId ?? selectedIdRef.current
731
+ if (id !== null && selectedIdRef.current === id) await loadDetail(id)
732
+ },
733
+ }) : null)),
734
+ h(NewTaskWizard, {
735
+ open: wizard,
736
+ onClose: () => setWizard(false),
737
+ api,
738
+ meta,
739
+ onCreated: async () => {
740
+ setWizard(false)
741
+ await refresh()
742
+ },
743
+ }))
744
+ }
745
+
746
+ function AutomationIcon() {
747
+ return h(IconChecklistOutlineRegular, { width: 18, height: 18 })
748
+ }
749
+
750
+ function apply(ctx) {
751
+ const api = createApi()
752
+ const openSession = (sessionId) => {
753
+ try {
754
+ const workspace = ctx.get('uiWorkspace')
755
+ workspace?.openSession?.(sessionId)
756
+ } catch {
757
+ // Session navigation is optional; the run detail stays readable without it.
758
+ }
759
+ }
760
+ ctx.effect(() => installStyles(), `${ENTRY_NAME}: styles`)
761
+ ctx.slots.inject('main', () => ctx.slots.register({
762
+ name: 'main',
763
+ key: PANEL_ID,
764
+ inject: () => ({ api, openSession }),
765
+ }, AutomationPage))
766
+ ctx.slots.inject('sidebar.panellist', () => ctx.slots.register({
767
+ name: 'sidebar.panellist',
768
+ id: PANEL_ID,
769
+ order: 11,
770
+ label: () => zh.panel,
771
+ }, AutomationIcon))
772
+ ctx.logger?.info?.(`${ENTRY_NAME}: 客户端半边已挂载(页面 + 侧栏入口)`)
773
+ }
774
+
775
+ exports.name = ENTRY_NAME
776
+ exports.inject = ['slots']
777
+ exports.apply = apply