dsh-workflow-execute 0.0.0-stage → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,13 @@
1
+ # dsh-workflow-execute bundle patch: contributes the plugin row into the host composition
2
+ # when this package is installed via `dsh plugin add`.
3
+ #
4
+ # HOST-PLANE plugin: scans the workflow library (~/.rjWorkflow/workflows writable
5
+ # + ~/.rjWorkflow/bundled/workflows read-only), serves same-origin JSON + SSE routes
6
+ # under /dsh-workflow-execute/*, registers the workflow_* agent tools and a short systemPrompt
7
+ # section. The `dsh.client` declaration in package.json makes the browser half
8
+ # (client/bundle.js) load in the web GUI. It must land in the host composition
9
+ # (this insert), never inside an agent preset.
10
+
11
+ - insert:
12
+ - id: dsh-workflow-execute
13
+ name: 'dsh-workflow-execute'
package/package.json CHANGED
@@ -1,6 +1,64 @@
1
1
  {
2
2
  "name": "dsh-workflow-execute",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "DSH 插件 · 工作流执行:「工作流」= 可复用的多阶段·多环节 agent 工作流模板——浏览/编辑(表单与 YAML 双向同步)/校验/导入导出/AI 生成,面板里可直接发起运行,逐环节开真实会话执行、门禁评审,看板跟踪全程。",
5
+ "author": "xiaojiaxin",
6
+ "license": "MIT",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/xiao0o0/dsh-workflow-execute.git"
10
+ },
11
+ "homepage": "https://github.com/xiao0o0/dsh-workflow-execute#readme",
12
+ "bugs": {
13
+ "url": "https://github.com/xiao0o0/dsh-workflow-execute/issues"
14
+ },
15
+ "main": "src/index.js",
16
+ "exports": {
17
+ ".": "./src/index.js",
18
+ "./client": "./client/bundle.js",
19
+ "./package.json": "./package.json"
20
+ },
21
+ "files": [
22
+ "src",
23
+ "client",
24
+ "scripts",
25
+ "cordis.patch.yml",
26
+ "README.md",
27
+ "LICENSE"
28
+ ],
29
+ "engines": {
30
+ "node": ">=20",
31
+ "dsh": ">=0.1.7-rc.2"
32
+ },
33
+ "dsh": {
34
+ "bundle": {
35
+ "patch": "./cordis.patch.yml"
36
+ },
37
+ "client": {
38
+ "platform": "web"
39
+ }
40
+ },
41
+ "scripts": {
42
+ "check": "node --check src/index.js && node --check src/store.js && node --check src/validate.js && node --check src/routes.js && node --check src/tools.js && node --check src/prompt.js && node --check src/zip.js && node --check src/artifacts.js && node --check src/runs.js && node --check src/execution.js && node --check client/index.js",
43
+ "test": "node --test \"test/*.test.mjs\"",
44
+ "build:client": "node scripts/build-client.mjs",
45
+ "prepublishOnly": "npm run build:client && npm run check && npm test"
46
+ },
47
+ "keywords": [
48
+ "dsh",
49
+ "deepseek-harness",
50
+ "dsh-plugin",
51
+ "workflow",
52
+ "workflow-template",
53
+ "agent-workflow",
54
+ "工作流",
55
+ "yaml"
56
+ ],
57
+ "dependencies": {
58
+ "@weibaohui/dsh-plugin-kit": "^0.5.0",
59
+ "yaml": "^2.9.0"
60
+ },
61
+ "devDependencies": {
62
+ "esbuild": "^0.28.2"
63
+ }
64
+ }
@@ -0,0 +1,85 @@
1
+ /**
2
+ * Build `client/bundle.js` from `client/index.js`.
3
+ *
4
+ * The static-install artifact follows the client-modules bundle protocol:
5
+ * `window.__ModuleLoader__.load({ id, factory })` registers a lazy CommonJS
6
+ * factory that receives a `require` resolving framework modules (react is a
7
+ * platform module; every other dependency is inlined). This script is a thin
8
+ * wrapper: it injects `var React = require("react")` and the module/exports
9
+ * scaffolding, then wraps the dynamic-plugin source verbatim.
10
+ *
11
+ * Run: `npm run build:client`
12
+ */
13
+
14
+ import { readFileSync, writeFileSync, existsSync } from "node:fs"
15
+ import { fileURLToPath } from 'node:url'
16
+ import { dirname, join } from 'node:path'
17
+
18
+ const here = dirname(fileURLToPath(import.meta.url))
19
+ const sourcePath = join(here, '..', 'client', 'index.js')
20
+ const bundlePath = join(here, '..', 'client', 'bundle.js')
21
+
22
+ const pkg = JSON.parse(readFileSync(join(here, '..', 'package.json'), 'utf8'))
23
+
24
+ const source = readFileSync(sourcePath, 'utf8')
25
+
26
+ // 共享工具箱内联(@weibaohui/dsh-plugin-kit/client/source.js):构建期打进
27
+ // bundle,kit 升级随消费者重新构建生效;kit 不在时静默跳过(消费者需自行
28
+ // 兜底 PluginKit 缺失的分支)
29
+ let kitSource = ''
30
+ try {
31
+ const { createRequire } = await import('node:module')
32
+ const kitPath = createRequire(import.meta.url).resolve('@weibaohui/dsh-plugin-kit/client/source.js')
33
+ kitSource = readFileSync(kitPath, 'utf8')
34
+ } catch { /* kit 未安装:bundle 照常产出,消费者需保证不触发 PluginKit 分支 */ }
35
+
36
+ // yaml 打包体以**字符串**注入 factory 顶部(最先执行),运行时经 new Function
37
+ // 隔离求值:factory 作用域内直接 `var YamlLib=(()=>{...})()` 会在页面加载期
38
+ // 构造 lib,其他插件加载期临时污染的全局会被固化进 lib 内部状态,parseDocument
39
+ // 对特定输入死循环(2026-09-09 表单编辑挂死根因)。隔离 + 首次使用时构造双保险。
40
+ let yamlBundleText = ''
41
+ const yamlBundlePath = join(here, "yaml-bundle.js")
42
+ if (existsSync(yamlBundlePath)) {
43
+ const yamlSource = readFileSync(yamlBundlePath, 'utf8')
44
+ yamlBundleText = `var YamlLibSrc = ${JSON.stringify(yamlSource)};\nvar YamlLib = null;\nfunction makeYamlLibIsolated() { return new Function(YamlLibSrc + "\\n;return YamlLib")() }\n`
45
+ }
46
+
47
+ const banner = `/* Generated from client/index.js by scripts/build-client.mjs — do not edit by hand.
48
+ * Regenerate with: npm run build:client
49
+ */
50
+ window.__ModuleLoader__.load({
51
+ id: ${JSON.stringify(pkg.name)},
52
+ factory: (require) => {
53
+ var module = { exports: {} }
54
+ var exports = module.exports
55
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" })
56
+ var React = require("react")
57
+ `
58
+
59
+ const footer = `
60
+ return module.exports
61
+ }
62
+ })
63
+ `
64
+
65
+ // The dynamic source references the React global directly; in the static
66
+ // bundle the factory's `var React` above satisfies it. Indent the wrapped
67
+ // body uniformly for readability of the artifact.
68
+ // kit 源同样缩进后注入 factory 顶部(consumer source 之前),供其引用 PluginKit
69
+ const kitIndented = kitSource === ''
70
+ ? ''
71
+ : kitSource.split('\n').map((line) => (line.length === 0 ? line : ' ' + line)).join('\n') + '\n'
72
+
73
+ // yaml 打包体同样缩进注入 factory 顶部(最先执行)
74
+ const yamlIndented = yamlBundleText === ''
75
+ ? ''
76
+ : yamlBundleText.split('\n').map((line) => (line.length === 0 ? line : ' ' + line)).join('\n') + '\n'
77
+
78
+ const indented = source
79
+ .split('\n')
80
+ .map((line) => (line.length === 0 ? line : ' ' + line))
81
+ .join('\n')
82
+
83
+ const body = banner + yamlIndented + kitIndented + indented + footer
84
+ writeFileSync(bundlePath, body)
85
+ console.log(`built ${bundlePath} (${Buffer.byteLength(body, 'utf8')} bytes)`)
@@ -0,0 +1,71 @@
1
+ import { readFileSync, writeFileSync } from 'node:fs'
2
+ let s = readFileSync('test/execution.test.mjs', 'utf8')
3
+ const must = (c, m) => { if (!c) { console.error('ANCHOR FAIL: ' + m); process.exit(1) } }
4
+
5
+ const SNAP_PLAIN = `const SNAP_PLAIN = { limits: {}, phases: [
6
+ { id: 'p1', name: '阶段一', links: [
7
+ { id: 'a1', prompt: '做 A', on_success: 'next' },
8
+ { id: 'a2', prompt: '做 B', on_success: 'end' },
9
+ ] },
10
+ { id: 'p2', name: '阶段二', links: [
11
+ { id: 'b1', prompt: '做 C', on_success: 'end' },
12
+ ] },
13
+ ] }
14
+
15
+ test('driveLoop: 无门禁直通 → done', async () => {
16
+ const { runs, execution, run } = setup(['A 报告', 'B 报告', 'C 报告'], SNAP_PLAIN)`
17
+
18
+ must(s.includes(`test('driveLoop: 无门禁直通 → done', async () => {
19
+ const { runs, execution, run } = setup(['A 报告', 'B 报告', 'C 报告'])`), 'test1')
20
+ s = s.replace(`test('driveLoop: 无门禁直通 → done', async () => {
21
+ const { runs, execution, run } = setup(['A 报告', 'B 报告', 'C 报告'])`, SNAP_PLAIN)
22
+
23
+ must(s.includes('function setup(responses) {'), 'setup')
24
+ s = s.replace(`function setup(responses) {
25
+ const dir = mkdtempSync(join(tmpdir(), 'dsh-prc-exec-'))
26
+ const runs = new RunStore(join(dir, 'runs.json'), console)
27
+ const execution = new ExecutionService({ ctx: fakeCtx(responses), runs, settings: { get: () => ({ userRoot: dir }) }, logger: console })
28
+ const run = runs.create({ processId: 'user:x.yaml', processName: 'x', displayName: 'X 工艺', snapshotYaml: '', snapshot: SNAP })
29
+ return { runs, execution, run }
30
+ }`, `function setup(responses, snapshot = SNAP) {
31
+ const dir = mkdtempSync(join(tmpdir(), 'dsh-prc-exec-'))
32
+ const runs = new RunStore(join(dir, 'runs.json'), console)
33
+ const execution = new ExecutionService({ ctx: fakeCtx(responses), runs, settings: { get: () => ({ userRoot: dir }) }, logger: console })
34
+ const run = runs.create({ processId: 'user:x.yaml', processName: 'x', displayName: 'X 工艺', snapshotYaml: '', snapshot })
35
+ return { runs, execution, run }
36
+ }`)
37
+
38
+ must(s.includes(` const { runs, execution, run } = setup([
39
+ 'A', // a1 会话
40
+ 'B', // a2 会话
41
+ 'score 30', // a2 首次门禁裁判 → 不过
42
+ 'B 重做', // a2 返工会话
43
+ 'score 90', // a2 第二次裁判 → 过
44
+ ])`), 'test2')
45
+ s = s.replace(` const { runs, execution, run } = setup([
46
+ 'A', // a1 会话
47
+ 'B', // a2 会话
48
+ 'score 30', // a2 首次门禁裁判 → 不过
49
+ 'B 重做', // a2 返工会话
50
+ 'score 90', // a2 第二次裁判 → 过
51
+ ])`, ` const { runs, execution, run } = setup([
52
+ 'A', // a1 会话
53
+ 'B', // a2 会话
54
+ 'score 30', // a2 首次门禁裁判 → 不过 → goto:a1
55
+ 'A2', // a1 会话(回跳)
56
+ 'B2', // a2 返工会话
57
+ 'score 90', // a2 第二次裁判 → 过
58
+ ])`)
59
+
60
+ must(s.includes("setup(['A', 'score 10', 'score 10', 'score 10', 'score 10', 'score 99'])"), 'test3')
61
+ s = s.replace("setup(['A', 'score 10', 'score 10', 'score 10', 'score 10', 'score 99'])",
62
+ "setup(['A', 'B', 'score 10', 'A2', 'B2', 'score 10', 'A3', 'B3', 'score 10', 'B4', 'score 99'])")
63
+
64
+ must(s.includes("setup(['A', 'B?', 'judge99', 'A2', 'B?', 'judge99'])"), 'test5')
65
+ s = s.replace("setup(['A', 'B?', 'judge99', 'A2', 'B?', 'judge99'])", "setup(['A', 'B', 'score 99'])")
66
+ must(s.includes("assert.ok(['done', 'awaiting', 'failed'].includes(run.status))"), 'test5 assert')
67
+ s = s.replace("assert.ok(['done', 'awaiting', 'failed'].includes(run.status))",
68
+ "assert.equal(run.status, 'done', 'error=' + run.error)")
69
+
70
+ writeFileSync('test/execution.test.mjs', s)
71
+ console.log('tests fixed')
@@ -0,0 +1,21 @@
1
+ /**
2
+ * 生成 scripts/yaml-bundle.js(esbuild IIFE,globalName=YamlLib)。
3
+ * 由 build-client.mjs 内联进 client bundle。运行:node scripts/make-yaml-bundle.mjs
4
+ */
5
+ import esbuild from 'esbuild'
6
+ import { writeFileSync } from 'node:fs'
7
+ import { fileURLToPath } from 'node:url'
8
+ import { dirname, join } from 'node:path'
9
+
10
+ const here = dirname(fileURLToPath(import.meta.url))
11
+ const r = esbuild.buildSync({
12
+ stdin: { contents: 'module.exports = require("yaml");', resolveDir: here },
13
+ bundle: true,
14
+ format: 'iife',
15
+ globalName: 'YamlLib',
16
+ write: false,
17
+ define: { 'process.env.NODE_ENV': '"production"' },
18
+ minify: true,
19
+ })
20
+ writeFileSync(join(here, 'yaml-bundle.js'), r.outputFiles[0].text)
21
+ console.log('yaml-bundle.js:', r.outputFiles[0].text.length, 'bytes')
@@ -0,0 +1,196 @@
1
+ import { readFileSync, writeFileSync } from 'node:fs'
2
+ let s = readFileSync('client/index.js', 'utf8')
3
+ const must = (cond, msg) => { if (!cond) { console.error('ANCHOR FAIL: ' + msg); process.exit(1) } }
4
+
5
+ // ── CSS ──
6
+ const CSS_ANCHOR = `.dsh-prc-sec h4 { margin:0 0 6px; font-size:13px; }
7
+ `
8
+ must(s.includes(CSS_ANCHOR), 'css anchor')
9
+ s = s.replace(CSS_ANCHOR, CSS_ANCHOR + `
10
+ .dsh-prc-runlist { width:280px; min-width:220px; overflow-y:auto; border-right:1px solid var(--dsw-alias-border-l2, rgba(128,128,128,.35)); padding:6px; box-sizing:border-box; }
11
+ .dsh-prc-runrow { display:flex; flex-direction:column; gap:3px; width:100%; text-align:left; border:1px solid transparent; border-radius:8px; background:transparent; color:inherit; padding:7px 9px; margin:2px 0; cursor:pointer; font:inherit; font-size:12px; box-sizing:border-box; }
12
+ .dsh-prc-runrow:hover { background:var(--dsw-hover, rgba(128,128,128,.1)); }
13
+ .dsh-prc-runrow[data-selected="true"] { background:var(--dsw-active, rgba(128,128,128,.16)); border-color:var(--dsw-alias-border-l2, rgba(128,128,128,.3)); }
14
+ .dsh-prc-pill { border-radius:999px; padding:1px 8px; font-size:10px; white-space:nowrap; border:1px solid var(--dsw-alias-border-l2, rgba(128,128,128,.3)); }
15
+ .dsh-prc-pill[data-status="running"] { color:#d9822b; border-color:#d9822b; }
16
+ .dsh-prc-pill[data-status="queued"] { color:#3e63dd; border-color:#3e63dd; }
17
+ .dsh-prc-pill[data-status="awaiting"] { color:#c75050; border-color:#c75050; }
18
+ .dsh-prc-pill[data-status="paused"] { color:#b8860b; border-color:#b8860b; }
19
+ .dsh-prc-pill[data-status="done"] { color:#2e9e5b; border-color:#2e9e5b; }
20
+ .dsh-prc-pill[data-status="stopped"] { color:var(--dsw-text-secondary, gray); }
21
+ .dsh-prc-pill[data-status="failed"] { color:var(--dsw-alias-state-error, #c75050); border-color:var(--dsw-alias-state-error, #c75050); }
22
+ .dsh-prc-board { flex:1; min-width:0; overflow-y:auto; padding:14px 18px; box-sizing:border-box; }
23
+ .dsh-prc-runhead { display:flex; align-items:flex-start; gap:10px; flex-wrap:wrap; margin-bottom:8px; }
24
+ .dsh-prc-break { border:1px solid var(--dsw-alias-state-error, #c75050); border-radius:10px; padding:10px 12px; margin:8px 0; display:flex; gap:8px; align-items:center; flex-wrap:wrap; }
25
+ .dsh-prc-linkcard { border:1px solid var(--dsw-alias-border-l2, rgba(128,128,128,.3)); border-radius:8px; padding:6px 9px; margin:4px 0; display:flex; flex-direction:column; gap:4px; }
26
+ .dsh-prc-linkcard[data-state="running"] { border-color:#d9822b; }
27
+ .dsh-prc-linkcard[data-state="done"] { opacity:.82; }
28
+ .dsh-prc-linkcard[data-state="gate_failed"] { border-color:var(--dsw-alias-state-error, #c75050); }
29
+ .dsh-prc-linktop { display:flex; align-items:baseline; gap:8px; flex-wrap:wrap; }
30
+ .dsh-prc-linktop .grow { flex:1; }
31
+ .dsh-prc-mini { border:1px solid var(--dsw-alias-border-l2, rgba(128,128,128,.3)); background:transparent; color:inherit; border-radius:6px; padding:2px 7px; font:inherit; font-size:11px; cursor:pointer; white-space:nowrap; }
32
+ .dsh-prc-mini:hover { background:var(--dsw-hover, rgba(128,128,128,.12)); }
33
+ .dsh-prc-tail { max-height:180px; overflow:auto; margin:0; }
34
+ `)
35
+
36
+ // ── 组件(插在设置页 section 之前)──
37
+ const ANCHOR = `// ── 设置页 section(M3) ─────────────────────────────────────────────────`
38
+ must(s.includes(ANCHOR), 'components anchor')
39
+
40
+ const COMPONENTS = `// ── 执行视图(v0.2)─────────────────────────────────────────────────────
41
+
42
+ const LINK_STATE_KEY = { running: 'linkRunning', done: 'linkDone', gate_failed: 'linkGateFailed', skipped: 'linkSkipped', failed: 'linkFailed', abandoned: 'linkAbandoned' }
43
+
44
+ function StatusPill({ t, status }) {
45
+ return h('span', { className: 'dsh-prc-pill', 'data-status': status }, t('status' + status[0].toUpperCase() + status.slice(1)))
46
+ }
47
+
48
+ /** 每个环节的最新一次执行记录。 */
49
+ function latestAttempts(run) {
50
+ const map = new Map()
51
+ for (const t of run.trail || []) {
52
+ const prev = map.get(t.linkId)
53
+ if (!prev || t.startedAt >= prev.startedAt) map.set(t.linkId, t)
54
+ }
55
+ return map
56
+ }
57
+
58
+ function runProgress(run) {
59
+ const latest = latestAttempts(run)
60
+ const total = new Set([...indexLinksOf(run).keys()]).size
61
+ let done = 0
62
+ for (const [linkId] of indexLinksOf(run)) {
63
+ const st = latest.get(linkId) && latest.get(linkId).status
64
+ if (st === 'done' || st === 'skipped') done++
65
+ }
66
+ return { done, total }
67
+ }
68
+ function indexLinksOf(run) {
69
+ const phases = run.snapshot && Array.isArray(run.snapshot.phases) ? run.snapshot.phases : []
70
+ const map = new Map()
71
+ for (const ph of phases) for (const ln of (Array.isArray(ph.links) ? ph.links : [])) if (ln.id) map.set(ln.id, { phase: ph, link: ln })
72
+ return map
73
+ }
74
+
75
+ function RunList({ state, controller, t }) {
76
+ const runs = state.runs.list
77
+ return h('div', { className: 'dsh-prc-runlist' },
78
+ runs.length === 0
79
+ ? h('div', { style: { padding: '16px 8px', color: 'var(--dsw-text-secondary, gray)', fontSize: 12 } }, t('noRuns'), h('div', { style: { marginTop: 4, opacity: .8 } }, t('noRunsHint')))
80
+ : runs.map((r) => h('button', {
81
+ key: r.id, className: 'dsh-prc-runrow', 'data-selected': state.runId === r.id ? 'true' : undefined,
82
+ onClick: () => controller.selectRun(r.id),
83
+ },
84
+ h('div', { style: { display: 'flex', gap: 6, alignItems: 'center' } },
85
+ h('span', { className: 'dsh-prc-pill', 'data-status': r.status }, t('status' + r.status[0].toUpperCase() + r.status.slice(1))),
86
+ h('span', { style: { flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', fontWeight: 500 } }, r.displayName || r.processName)),
87
+ h('div', { style: { display: 'flex', gap: 6, color: 'var(--dsw-text-secondary, gray)', fontSize: 11 } },
88
+ h('span', null, t('progress', { done: r.doneLinks, total: r.totalLinks })),
89
+ h('span', null, new Date(r.updatedAt).toLocaleTimeString())))))
90
+ }
91
+
92
+ function LinkCard({ t, run, phase, link, attempt, controller }) {
93
+ const [open, setOpen] = useState(false)
94
+ const st = attempt ? attempt.status : 'pending'
95
+ const isCurrent = run.current && run.current.linkId === link.id && ['running', 'queued', 'awaiting'].includes(run.status)
96
+ const rework = (run.rework && run.rework[link.id]) || 0
97
+ const active = ['queued', 'running', 'awaiting', 'paused'].includes(run.status)
98
+ return h('div', { className: 'dsh-prc-linkcard', 'data-state': st },
99
+ h('div', { className: 'dsh-prc-linktop' },
100
+ h('span', { className: 'dsh-prc-link-id' }, link.id),
101
+ h('span', { style: { fontWeight: 500 } }, link.name || ''),
102
+ isCurrent ? h('span', { className: 'dsh-prc-badge', 'data-kind': 'warn' }, t('currentStep')) : null,
103
+ h('span', { className: 'grow' }),
104
+ attempt && attempt.attempt > 1 ? h('span', { style: { fontSize: 11, opacity: .7 } }, t('attemptN', { n: attempt.attempt })) : null,
105
+ rework > 0 ? h('span', { style: { fontSize: 11, color: '#b8860b' } }, t('reworkN', { n: rework })) : null,
106
+ attempt && attempt.gate && attempt.gate.score !== null && attempt.gate.score !== undefined
107
+ ? h('span', { className: 'dsh-prc-badge', 'data-kind': attempt.gate.score >= (attempt.gate.minScore || 0) ? 'ok' : 'err', title: attempt.gate.reason },
108
+ t('gateLabel') + ' ' + attempt.gate.score + ' / ' + (attempt.gate.minScore || 0)) : null,
109
+ h('span', { style: { fontSize: 11, opacity: .75 } }, t(LINK_STATE_KEY[st] || 'linkPending'))),
110
+ h('div', { style: { display: 'flex', gap: 6, flexWrap: 'wrap' } },
111
+ attempt && attempt.sessionId ? h('button', { className: 'dsh-prc-mini', onClick: () => controller.openSession(attempt.sessionId) }, t('openSession')) : null,
112
+ attempt && attempt.outputTail ? h('button', { className: 'dsh-prc-mini', onClick: () => setOpen(!open) }, (open ? '▾ ' : '▸ ') + t('outputLabel')) : null,
113
+ !active && attempt ? h('button', { className: 'dsh-prc-mini', onClick: () => void controller.runAction('retry-link', { id: run.id, linkId: link.id }) }, t('retryLink')) : null,
114
+ !active && st !== 'pending' ? h('button', { className: 'dsh-prc-mini', onClick: () => void controller.runAction('skip-link', { id: run.id, linkId: link.id }) }, t('skipLink')) : null),
115
+ open && attempt && attempt.outputTail ? h('pre', { className: 'dsh-prc-pre dsh-prc-tail' }, attempt.outputTail) : null)
116
+ }
117
+
118
+ function RunBoard({ state, controller, t }) {
119
+ const run = state.run
120
+ if (state.runLoading) return h('div', { className: 'dsh-prc-board' }, t('loading'))
121
+ if (!run) return h('div', { className: 'dsh-prc-empty' }, t('emptyRun'))
122
+ const latest = latestAttempts(run)
123
+ const phases = Array.isArray(run.snapshot && run.snapshot.phases) ? run.snapshot.phases : []
124
+ const { done, total } = runProgress(run)
125
+ const active = ['queued', 'running', 'awaiting', 'paused'].includes(run.status)
126
+ return h('div', { className: 'dsh-prc-board' },
127
+ h('div', { className: 'dsh-prc-runhead' },
128
+ h('h3', { className: 'dsh-prc-detail-title' }, run.displayName || run.processName),
129
+ h(StatusPill, { t, status: run.status }),
130
+ h('span', { className: 'dsh-prc-count' }, t('progress', { done, total })),
131
+ h('div', { className: 'dsh-prc-actions' },
132
+ run.status === 'running' || run.status === 'queued' ? h('button', { className: 'dsh-prc-btn', onClick: () => void controller.runAction('pause', { id: run.id }) }, t('pause')) : null,
133
+ run.status === 'paused' ? h('button', { className: 'dsh-prc-btn', 'data-primary': 'true', onClick: () => void controller.runAction('resume', { id: run.id }) }, t('resume')) : null,
134
+ active ? h('button', { className: 'dsh-prc-btn', 'data-danger': 'true', onClick: () => void controller.runAction('stop', { id: run.id }) }, t('stopRun')) : null)),
135
+ h('div', { className: 'dsh-prc-chips' },
136
+ h('span', { className: 'dsh-prc-chip' }, run.processId),
137
+ run.error ? h('span', { className: 'dsh-prc-badge', 'data-kind': 'err' }, t('runError') + ': ' + run.error) : null,
138
+ h('span', { style: { fontSize: 11, opacity: .6 } }, new Date(run.updatedAt).toLocaleString()))),
139
+ run.pendingBreak ? h('div', { className: 'dsh-prc-break' },
140
+ h('span', { style: { fontWeight: 600 } }, '⚠ ' + t('breakTitle')),
141
+ h('span', { style: { fontSize: 12 } },
142
+ run.pendingBreak.linkId + (run.pendingBreak.gate && run.pendingBreak.gate.score !== null && run.pendingBreak.gate.score !== undefined
143
+ ? ' · ' + t('gateLabel') + ' ' + run.pendingBreak.gate.score + ' / ' + (run.pendingBreak.gate.minScore || 0) : '')
144
+ + ' · ' + (run.pendingBreak.reason || '')),
145
+ h('div', { className: 'dsh-prc-actions' },
146
+ h('button', { className: 'dsh-prc-btn', 'data-primary': 'true', onClick: () => void controller.runAction('resolve-break', { id: run.id, decision: 'retry' }) }, t('decisionRetry')),
147
+ h('button', { className: 'dsh-prc-btn', onClick: () => void controller.runAction('resolve-break', { id: run.id, decision: 'skip' }) }, t('decisionSkip')),
148
+ h('button', { className: 'dsh-prc-btn', 'data-danger': 'true', onClick: () => void controller.runAction('resolve-break', { id: run.id, decision: 'stop' }) }, t('decisionStop')))) : null,
149
+ phases.map((ph, i) => h('div', { className: 'dsh-prc-phase', key: ph.id || i },
150
+ h('div', { className: 'dsh-prc-phase-head' },
151
+ h('span', { className: 'dsh-prc-link-id' }, ph.id || i + 1),
152
+ h('span', null, ph.name || ''),
153
+ h('span', { className: 'dsh-prc-link-meta' }, (Array.isArray(ph.links) ? ph.links.length : 0) + ' ' + t('links'))),
154
+ (Array.isArray(ph.links) ? ph.links : []).map((ln) => h(LinkCard, {
155
+ key: ln.id, t, run, phase, link: ln, attempt: latest.get(ln.id), controller,
156
+ })))))
157
+ }
158
+
159
+ function ExecView({ state, controller, t }) {
160
+ return h('div', { style: { display: 'contents' } },
161
+ h(RunList, { state, controller, t }),
162
+ state.runId && (state.runLoading || state.run) ? h(RunBoard, { state, controller, t })
163
+ : state.runId ? h('div', { className: 'dsh-prc-empty' }, t('loading')) : h('div', { className: 'dsh-prc-empty' }, t('emptyRun')))
164
+ }
165
+
166
+ function NewRunDialog({ state, controller, t }) {
167
+ const dlg = state.dialog
168
+ const [workspaces, setWorkspaces] = useState(null)
169
+ const [ws, setWs] = useState('')
170
+ useEffect(() => {
171
+ api('/workspaces').then((d) => setWorkspaces(d.workspaces || [])).catch(() => setWorkspaces([]))
172
+ }, [])
173
+ const proc = state.processes.find((p) => p.id === dlg.processId)
174
+ const [busy, setBusy] = useState(false)
175
+ return h(Modal, { title: t('runCreate') + ':' + (proc ? (proc.display_name || proc.name) : ''), onClose: () => controller.setState({ dialog: null }) },
176
+ h('div', { className: 'dsh-prc-kv' }, h('b', null, t('name') + ':'), proc ? proc.relPath : '—'),
177
+ h('label', { className: 'dsh-prc-field' }, t('runWorkspace'),
178
+ h('select', { value: ws, onChange: (e) => setWs(e.target.value) },
179
+ workspaces === null ? h('option', { value: '' }, t('loading')) : [
180
+ h('option', { key: '_', value: '' }, t('workspaceDefault')),
181
+ workspaces.map((w) => h('option', { key: w.id, value: w.id }, w.title)),
182
+ ])),
183
+ h('div', { style: { fontSize: 12, opacity: .7 } }, '每个环节开一个全新会话执行;门禁由评审会话打分,不过按 on_gate_fail 流转,返工不超过 max_rework。'),
184
+ h('div', { style: { display: 'flex', gap: 8, justifyContent: 'flex-end' } },
185
+ h('button', { className: 'dsh-prc-btn', onClick: () => controller.setState({ dialog: null }) }, t('cancel')),
186
+ h('button', { className: 'dsh-prc-btn', 'data-primary': 'true', disabled: busy || !proc, onClick: async () => {
187
+ setBusy(true)
188
+ try { await controller.createRun({ processId: dlg.processId, workspaceId: ws || undefined }) } catch (error) { controller.toast(String(error && error.message || error), 'err') } finally { setBusy(false) }
189
+ } }, t('runCreate'))))
190
+ }
191
+
192
+ ` + ANCHOR
193
+ s = s.replace(ANCHOR, COMPONENTS)
194
+
195
+ writeFileSync('client/index.js', s)
196
+ console.log('exec components appended')
@@ -0,0 +1,147 @@
1
+ import { readFileSync, writeFileSync } from 'node:fs'
2
+ let s = readFileSync('client/index.js', 'utf8')
3
+ const must = (cond, msg) => { if (!cond) { console.error('ANCHOR FAIL: ' + msg); process.exit(1) } }
4
+
5
+ // 1. initialState
6
+ must(s.includes(` settings: undefined,
7
+ }
8
+ }`), 'initialState')
9
+ s = s.replace(` settings: undefined,
10
+ }
11
+ }`, ` settings: undefined,
12
+ view: prefs.view || 'lib',
13
+ runs: { revision: -1, list: [] },
14
+ runId: prefs.runId, run: undefined, runLoading: false,
15
+ }
16
+ }`)
17
+
18
+ // 2. constructor + persist
19
+ s = s.replace(` this.seenRevision = undefined
20
+ this.refreshInFlight = null`, ` this.seenRevision = undefined
21
+ this.seenRunsRevision = undefined
22
+ this.refreshInFlight = null`)
23
+ s = s.replace(` savePrefs({ selectedId: s.selectedId, tab: s.tab, filters: s.filters, sortBy: s.sortBy })`,
24
+ ` savePrefs({ selectedId: s.selectedId, tab: s.tab, filters: s.filters, sortBy: s.sortBy, view: s.view, runId: s.runId })`)
25
+
26
+ // 3. stream handler + refresh(runs 一并追赶)
27
+ s = s.replace(` connectStream() {
28
+ const es = new EventSource(API + '/events')
29
+ this.es = es
30
+ es.addEventListener('hello', (e) => {
31
+ try { this.seenRevision = JSON.parse(e.data).revision } catch {}
32
+ void this.refresh()
33
+ })
34
+ es.addEventListener('change', (e) => {
35
+ try { this.seenRevision = JSON.parse(e.data).revision } catch {}
36
+ void this.refresh()
37
+ })
38
+ es.onerror = () => { /* EventSource 自动重连;hello 里对齐 gap */ }
39
+ }`, ` connectStream() {
40
+ const es = new EventSource(API + '/events')
41
+ this.es = es
42
+ const onFrame = (e) => {
43
+ try { const d = JSON.parse(e.data); this.seenRevision = d.revision; this.seenRunsRevision = d.runsRevision } catch {}
44
+ void this.refresh()
45
+ }
46
+ es.addEventListener('hello', onFrame)
47
+ es.addEventListener('change', onFrame)
48
+ es.onerror = () => { /* EventSource 自动重连;hello 里对齐 gap */ }
49
+ }`)
50
+
51
+ s = s.replace(` let snap
52
+ // revision 追赶:变更帧落在请求飞行中时,旧响应可能落后(taskboard S16)
53
+ for (let round = 0; round < 3; round++) {
54
+ snap = await api('/state')
55
+ const keep = this.state.selectedId && snap.processes.some((p) => p.id === this.state.selectedId)
56
+ ? this.state.selectedId : undefined
57
+ this.setState({
58
+ loaded: true, revision: snap.revision, roots: snap.roots, processes: snap.processes,
59
+ lastError: snap.lastError, error: undefined, selectedId: keep,
60
+ })
61
+ if (this.seenRevision === undefined || snap.revision >= this.seenRevision) break
62
+ }`, ` let snap
63
+ // revision 追赶:变更帧落在请求飞行中时,旧响应可能落后(taskboard S16)
64
+ for (let round = 0; round < 3; round++) {
65
+ const [stateRsp, runsRsp] = await Promise.all([api('/state'), api('/runs')])
66
+ snap = stateRsp
67
+ const keep = this.state.selectedId && snap.processes.some((p) => p.id === this.state.selectedId)
68
+ ? this.state.selectedId : undefined
69
+ this.setState({
70
+ loaded: true, revision: snap.revision, roots: snap.roots, processes: snap.processes,
71
+ lastError: snap.lastError, error: undefined, selectedId: keep,
72
+ runs: { revision: runsRsp.revision, list: runsRsp.runs },
73
+ })
74
+ const libCaughtUp = this.seenRevision === undefined || snap.revision >= this.seenRevision
75
+ const runsCaughtUp = this.seenRunsRevision === undefined || runsRsp.revision >= this.seenRunsRevision
76
+ if (libCaughtUp && runsCaughtUp) break
77
+ }
78
+ // 运行看板:活跃运行随帧刷新;静态运行只取一次
79
+ if (this.state.view === 'exec' && this.state.runId) {
80
+ const active = ['queued', 'running', 'awaiting'].includes((this.state.run && this.state.run.status) || '')
81
+ if (active || !this.state.run) void this.loadRun(this.state.runId)
82
+ }`)
83
+
84
+ // 4. controller methods(追加在 aiPoll 之后)
85
+ s = s.replace(` aiRun(prompt) { return api('/ai-generate', { method: 'POST', body: { prompt } }).then((d) => d.jobId) }
86
+ aiPoll(jobId) { return api('/jobs?id=' + encodeURIComponent(jobId)) }
87
+ }`, ` aiRun(prompt) { return api('/ai-generate', { method: 'POST', body: { prompt } }).then((d) => d.jobId) }
88
+ aiPoll(jobId) { return api('/jobs?id=' + encodeURIComponent(jobId)) }
89
+
90
+ // ── 执行视图(v0.2)──
91
+ setView(view) { this.setState({ view }); this.persist() }
92
+ selectRun(id) {
93
+ if (!id) return
94
+ this.setState({ runId: id, run: undefined, runLoading: true })
95
+ this.persist()
96
+ void this.loadRun(id)
97
+ }
98
+ async loadRun(id) {
99
+ try {
100
+ const d = await api('/run?id=' + encodeURIComponent(id))
101
+ if (this.state.runId !== id) return
102
+ this.setState({ run: d.run, runLoading: false })
103
+ } catch (error) {
104
+ if (this.state.runId === id) this.setState({ runLoading: false, error: String(error && error.message || error) })
105
+ }
106
+ }
107
+ async runAction(action, body) {
108
+ const d = await api('/run-action', { method: 'POST', body: { action, ...body } })
109
+ if (this.state.runId === d.run.id) void this.loadRun(d.run.id)
110
+ void this.refresh()
111
+ return d.run
112
+ }
113
+ async createRun(body) {
114
+ const d = await api('/run-create', { method: 'POST', body })
115
+ this.setState({ dialog: null, view: 'exec', runId: d.run.id, run: undefined, runLoading: true })
116
+ this.persist()
117
+ void this.loadRun(d.run.id)
118
+ this.toast(this.tr('runStarted'))
119
+ return d.run
120
+ }
121
+ }`)
122
+
123
+ // 5. Toolbar:视图切换 tabs(放在 count 之后)
124
+ s = s.replace(` h('span', { className: 'dsh-prc-count' }, t('count', { user, bundled })),
125
+ h('input', { className: 'dsh-prc-input dsh-prc-search'`, ` h('span', { className: 'dsh-prc-count' }, t('count', { user, bundled })),
126
+ h('div', { className: 'dsh-prc-tabs', style: { borderBottom: 'none', margin: '0 4px' } },
127
+ h('button', { className: 'dsh-prc-tab', 'data-on': state.view === 'lib' ? 'true' : undefined, onClick: () => controller.setView('lib') }, t('viewLib')),
128
+ h('button', { className: 'dsh-prc-tab', 'data-on': state.view === 'exec' ? 'true' : undefined, onClick: () => controller.setView('exec') }, t('viewExec'))),
129
+ h('input', { className: 'dsh-prc-input dsh-prc-search'`)
130
+
131
+ // 6. ProcessPanel:视图切换 + 新建运行对话框
132
+ s = s.replace(` h('div', { className: 'dsh-prc-body' },
133
+ h(ListPane, { state, controller, t }),
134
+ detail),`, ` h('div', { className: 'dsh-prc-body' },
135
+ state.view === 'exec' ? h(ExecView, { state, controller, t }) : h('div', { style: { display: 'contents' } }, h(ListPane, { state, controller, t }), detail)),`)
136
+
137
+ s = s.replace(` state.dialog && state.dialog.type === 'ai' ? h(AiDialog, { state, controller, t }) : null,`,
138
+ ` state.dialog && state.dialog.type === 'ai' ? h(AiDialog, { state, controller, t }) : null,
139
+ state.dialog && state.dialog.type === 'newrun' ? h(NewRunDialog, { state, controller, t }) : null,`)
140
+
141
+ // 7. DetailPane:加「▶ 按工艺执行」按钮(库视图,所有来源可运行)
142
+ s = s.replace(` h('button', { key: 'x', className: 'dsh-prc-btn', onClick: copyYaml }, t('copyYaml')))),`,
143
+ ` h('button', { key: 'r', className: 'dsh-prc-btn', 'data-primary': 'true', title: t('runCreate'), onClick: () => controller.setState({ dialog: { type: 'newrun', processId: meta.id } }) }, t('runCreate')),
144
+ h('button', { key: 'x', className: 'dsh-prc-btn', onClick: copyYaml }, t('copyYaml')))),`)
145
+
146
+ writeFileSync('client/index.js', s)
147
+ console.log('controller/toolbar/panel patched')