zen-gitsync 2.13.3 → 2.13.4

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.
@@ -1,1702 +1,1702 @@
1
- // Copyright 2026 xz333221
2
- //
3
- // Licensed under the Apache License, Version 2.0 (the "License");
4
- // you may not use this file except in compliance with the License.
5
- // You may obtain a copy of the License at
6
- //
7
- // http://www.apache.org/licenses/LICENSE-2.0
8
- //
9
- // Unless required by applicable law or agreed to in writing, software
10
- // distributed under the License is distributed on an "AS IS" BASIS,
11
- // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
- // See the License for the specific language governing permissions and
13
- // limitations under the License.
14
- //
15
- // 工作台后端:管理预置提示词 / 任务 / 子任务,
16
- // 并以 bypassPermissions 模式依次 spawn claude CLI 执行子任务(每次新窗口)。
17
- // 数据存到用户主目录 ~/.zen-gitsync/,跨项目共享。
18
-
19
- import fs from 'fs';
20
- import fsp from 'fs/promises';
21
- import path from 'path';
22
- import os from 'os';
23
- import { spawn, execFileSync, execFile } from 'child_process';
24
- import { EventEmitter } from 'events';
25
- import express from 'express';
26
-
27
- const DATA_DIR = path.join(os.homedir(), '.zen-gitsync');
28
- const PROMPTS_FILE = path.join(DATA_DIR, 'prompts.json');
29
- const TASKS_FILE = path.join(DATA_DIR, 'tasks.json');
30
- const IMAGES_DIR = path.join(DATA_DIR, 'workbench-images');
31
- const INSTRUCTION_FILE = path.join(DATA_DIR, 'ai-instruction.json');
32
- const SUBTASK_INSTRUCTION_FILE = path.join(DATA_DIR, 'ai-subtask-instruction.json');
33
-
34
- // 子项目识别 / 文件扫描时需要跳过的目录
35
- const SKIP_DIRS = new Set([
36
- 'node_modules', 'dist', 'build', '.next', '.nuxt', '__pycache__',
37
- 'target', 'out', 'coverage', 'vendor', '.git', '.svn', '.hg',
38
- '.idea', '.vscode', '.gradle', '.terraform', '.cache', '.parcel-cache',
39
- '.turbo', '.svelte-kit', 'storybook-static'
40
- ]);
41
-
42
- // 默认生成指令:用户首次使用时作为可编辑指令的初始值
43
- const DEFAULT_INSTRUCTION = `你是一名资深软件架构师。
44
-
45
- 【探索步骤】
46
- 1. 先识别项目结构:扫描根目录是否包含 .git 目录,以及 package.json / pyproject.toml / go.mod / Cargo.toml / pom.xml / build.gradle{,.kts} / composer.json / Gemfile / pubspec.yaml 这 9 种 manifest。
47
- 2. 如果根目录含 manifest,就把整个根目录视为一个子项目。
48
- 3. 如果根目录不含 manifest、但子目录(含一层 .git 或上述 manifest)形成多个子项目,对每个子项目分别探索。
49
- 4. 对每个子项目,重点读取:
50
- - 所有识别到的 manifest(限制单文件 20KB)
51
- - README.md(限制 8KB)
52
- - 入口文件:package.json 的 main / scripts / workspaces 字段;pyproject.toml 的 [project.scripts];go.mod 的 module;Cargo.toml 的 [[bin]];pom.xml 的 <modules>
53
- - 2 层目录树(最多 200 行)
54
-
55
- 【输出要求】
56
- 1. 给出一段 400-800 字的中文「项目架构说明」,覆盖:项目整体定位、技术栈、模块划分、核心流程、关键设计决策。
57
- 2. 必须引用子项目里实际存在的文件路径、目录名、依赖名,不要编造。
58
- 3. 多个子项目时:先逐个说明,最后输出一段「整体架构」总结它们之间的关系。
59
- 4. 语气专业、具体、面向接手这个项目的开发者。
60
- 5. 只返回 JSON:{ "name": "项目名(10-20字)", "summary": "架构说明正文" }。`;
61
-
62
- // 单个附件最大 5MB;与 Anthropic Messages API 文档约束一致
63
- const MAX_IMAGE_BYTES = 5 * 1024 * 1024;
64
- // 一个子任务最多挂 9 个附件
65
- const MAX_ATTACHMENTS_PER_SUBTASK = 9;
66
-
67
- // AI 拆分子任务:默认系统指令(用户在 GUI 可编辑覆盖)。
68
- // 国际化:根据请求 Accept-Language 在 zh / en 之间选默认。
69
- // 中英两份都内置——用户保存到 ~/.zen-gitsync/ai-subtask-instruction.json 后覆盖。
70
- const DEFAULT_SUBTASK_INSTRUCTION_ZH = `你是一名任务拆分助手。
71
-
72
- 【思考过程】
73
- 在给出 JSON 之前,请先在内部仔细思考(如果模型支持,把思考放在 reasoning 中;否则可以先输出一段简短分析,再输出 JSON):
74
- - 任务的真实目标是什么?用户提供的描述/图片/上下文里有哪些关键信息?
75
- - 涉及哪些技术栈、模块、文件、约束?是否有易被忽略的边界条件?
76
- - 自然的执行顺序是什么?哪些步骤是前置依赖?哪些可以并行?
77
- - 哪些步骤可能失败、需要单独验证?
78
-
79
- 【拆分原则】
80
- 1. 单一职责:每个子任务只做一件事,避免"做 A 和 B"。
81
- 2. 粒度适中:单个子任务应当能在一次会话里完成(既不要"实现整个登录功能"这么大,也不要"打印 hello"这么琐碎)。
82
- 3. 顺序合理:子任务按依赖关系和执行顺序排列(先准备、后实现、最后验证)。
83
- 4. 可验证:每个子任务都有明确的完成标志("输出文件 xxx"、"通过测试 yyy"、"控制台打印 zzz")。
84
- 5. 数量:拆成 3-6 个子任务为宜。任务很简单时 2-3 个;复杂时 5-6 个,不要超过 8 个。
85
- 6. 描述具体:desc 字段要写清楚"要做什么、参考什么、产出什么",不要只是把 title 改写一遍。
86
- 7. 如果任务里附带了图片,必须基于图片的实际内容拆分(例如指出图片中的哪个区域、哪个元素需要改),而不是泛泛而谈。
87
-
88
- 【输出要求】
89
- 最后必须输出 JSON,结构:
90
- {
91
- "subtasks": [
92
- { "title": "子任务标题(10-20字)", "desc": "子任务的具体描述,包含要做什么、输入是什么、输出/验证标志是什么" }
93
- ]
94
- }
95
-
96
- JSON 要用 \`\`\`json ... \`\`\` 代码块包裹,前面可以有分析文字,但 JSON 必须完整、合法、可解析。`;
97
-
98
- const DEFAULT_SUBTASK_INSTRUCTION_EN = `You are a task breakdown assistant.
99
-
100
- [Thinking process]
101
- Before producing JSON, think carefully (put your thoughts in reasoning if the model supports it; otherwise output a short analysis first, then JSON):
102
- - What is the real goal? What key information is in the description / images / context?
103
- - Which stack, modules, files, constraints are involved? Any easily missed edge cases?
104
- - What is the natural execution order? What blocks what? What can run in parallel?
105
- - Which steps may fail and need separate verification?
106
-
107
- [Breakdown principles]
108
- 1. Single responsibility: each subtask does only one thing, avoid bundling "do A and B".
109
- 2. Right granularity: a subtask should finish in one Claude session (not as big as "implement the whole login flow", not as trivial as "print hello").
110
- 3. Sensible order: arrange subtasks by dependency / execution order (prepare first, implement, then verify).
111
- 4. Verifiable: every subtask has a clear completion signal (e.g. "produce file xxx", "pass test yyy", "log zzz to console").
112
- 5. Quantity: prefer 3-6 subtasks. Very simple tasks 2-3, complex ones 5-6, never exceed 8.
113
- 6. Concrete desc: write what to do, what to reference, what to produce — don't just paraphrase the title.
114
- 7. If the task includes images, the breakdown must reference the actual image content (which region, which element to change), not just generic talk.
115
-
116
- [Output requirements]
117
- End with JSON, structure:
118
- {
119
- "subtasks": [
120
- { "title": "subtask title (10-20 chars)", "desc": "concrete description: what to do, what the input is, what the output / verification signal is" }
121
- ]
122
- }
123
-
124
- Wrap the JSON in \`\`\`json ... \`\`\`. Analysis text before it is allowed, but the JSON must be complete and parseable.`;
125
-
126
- // 兼容旧引用
127
- const DEFAULT_SUBTASK_INSTRUCTION = DEFAULT_SUBTASK_INSTRUCTION_ZH
128
-
129
- // 根据请求 Accept-Language 选默认(zh / en)
130
- function pickDefaultSubtaskInstruction(req) {
131
- const al = String(req?.headers?.['accept-language'] || '').toLowerCase()
132
- if (al.startsWith('en')) return DEFAULT_SUBTASK_INSTRUCTION_EN
133
- return DEFAULT_SUBTASK_INSTRUCTION_ZH
134
- }
135
- // 白名单后缀:图片 + 常见文档(PDF / 纯文本 / Markdown)
136
- const IMAGE_EXTS = new Set(['png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'svg']);
137
- const DOC_EXTS = new Set(['pdf', 'txt', 'md', 'markdown', 'csv', 'json', 'log']);
138
- const ALLOWED_EXTS = new Set([...IMAGE_EXTS, ...DOC_EXTS]);
139
-
140
- // mime → 文件后缀;与前端 el-upload accept 对齐
141
- const MIME_TO_EXT = {
142
- 'image/png': 'png',
143
- 'image/jpeg': 'jpg',
144
- 'image/jpg': 'jpg',
145
- 'image/gif': 'gif',
146
- 'image/webp': 'webp',
147
- 'image/bmp': 'bmp',
148
- 'image/svg+xml': 'svg',
149
- 'image/x-icon': 'ico',
150
- 'image/vnd.microsoft.icon': 'ico',
151
- 'application/pdf': 'pdf',
152
- 'text/plain': 'txt',
153
- 'text/markdown': 'md',
154
- 'text/x-markdown': 'md',
155
- 'text/csv': 'csv',
156
- 'application/json': 'json',
157
- 'text/json': 'json',
158
- 'text/x-log': 'log',
159
- };
160
-
161
- function sanitizeExt(name, fallback = 'bin') {
162
- if (typeof name !== 'string') return fallback;
163
- const m = name.toLowerCase().match(/\.([a-z0-9]+)$/);
164
- if (!m) return fallback;
165
- return ALLOWED_EXTS.has(m[1]) ? m[1] : fallback;
166
- }
167
-
168
- function isImageExt(ext) {
169
- return IMAGE_EXTS.has(String(ext || '').toLowerCase());
170
- }
171
-
172
- async function ensureImagesDir() {
173
- await fsp.mkdir(IMAGES_DIR, { recursive: true });
174
- }
175
-
176
- // 把 mime 或文件名规范成统一后缀;遇到不在白名单的情况返回 null
177
- function resolveExt({ originalName, mime }) {
178
- if (mime && MIME_TO_EXT[mime.toLowerCase()]) {
179
- return MIME_TO_EXT[mime.toLowerCase()];
180
- }
181
- const fromName = sanitizeExt(originalName, '');
182
- if (fromName) return fromName;
183
- return null;
184
- }
185
-
186
- // 解析 manifest 文件名(按优先级)
187
- const MANIFEST_FILES = [
188
- 'package.json', 'pyproject.toml', 'go.mod', 'Cargo.toml',
189
- 'pom.xml', 'build.gradle', 'build.gradle.kts', 'composer.json',
190
- 'Gemfile', 'pubspec.yaml'
191
- ];
192
-
193
- // 轻量级:仅告诉 LLM 项目的主 manifest 是什么(用于 AI 拆分时让 LLM 知道项目类型)。
194
- // 不读内容,只 stat 存在性——拆分子任务不需要细节。
195
- async function detectProjectManifest(projectPath) {
196
- if (!projectPath) return ''
197
- for (const f of MANIFEST_FILES) {
198
- try {
199
- const stat = await fsp.stat(path.join(projectPath, f))
200
- if (stat.isFile()) return f
201
- } catch { /* 不存在,继续 */ }
202
- }
203
- return ''
204
- }
205
-
206
- async function readProjectManifest(projectPath) {
207
- const out = {};
208
- for (const f of MANIFEST_FILES) {
209
- const p = path.join(projectPath, f);
210
- try {
211
- const stat = await fsp.stat(p);
212
- if (!stat.isFile()) continue;
213
- // 限制大小,避免巨型 pom.xml 把上下文打爆
214
- const content = stat.size > 20000
215
- ? (await safeReadFile(p, 20000))
216
- : (await fsp.readFile(p, 'utf8'));
217
- out[f] = content;
218
- } catch { /* 不存在就跳过 */ }
219
- }
220
- return out;
221
- }
222
-
223
- async function safeReadFile(filePath, maxBytes = 200000) {
224
- try {
225
- const stat = await fsp.stat(filePath);
226
- if (stat.size > maxBytes) {
227
- const buf = Buffer.alloc(maxBytes);
228
- const fd = await fsp.open(filePath, 'r');
229
- await fd.read(buf, 0, maxBytes, 0);
230
- await fd.close();
231
- return buf.toString('utf8').slice(0, maxBytes);
232
- }
233
- return await fsp.readFile(filePath, 'utf8');
234
- } catch {
235
- return '';
236
- }
237
- }
238
-
239
- async function listDirTree(projectPath, maxDepth = 2, maxEntries = 400) {
240
- const lines = [];
241
- async function walk(dir, depth) {
242
- if (depth > maxDepth || lines.length >= maxEntries) return;
243
- let entries;
244
- try { entries = await fsp.readdir(dir, { withFileTypes: true }); }
245
- catch { return; }
246
- const filtered = entries.filter(e => {
247
- if (e.name.startsWith('.')) return false;
248
- if (['node_modules', 'dist', 'build', '.next', '.nuxt', '__pycache__', 'target', 'out', 'coverage', 'vendor'].includes(e.name)) return false;
249
- return true;
250
- });
251
- const indent = ' '.repeat(depth);
252
- for (const e of filtered) {
253
- if (lines.length >= maxEntries) return;
254
- if (e.isDirectory()) {
255
- lines.push(`${indent}${e.name}/`);
256
- await walk(path.join(dir, e.name), depth + 1);
257
- } else if (e.isFile()) {
258
- lines.push(`${indent}${e.name}`);
259
- }
260
- }
261
- }
262
- await walk(projectPath, 0);
263
- return lines.join('\n');
264
- }
265
-
266
- async function callLlmJson(model, prompt, opts = {}) {
267
- const { maxTokens = 1500, timeoutMs = 60000, images = [] } = opts;
268
- const { default: fetch } = await import('node-fetch').catch(() => ({ default: globalThis.fetch }));
269
- const url = `${String(model.baseURL || '').replace(/\/$/, '')}/chat/completions`;
270
- const headers = { 'Content-Type': 'application/json' };
271
- if (model.apiKey) headers['Authorization'] = `Bearer ${model.apiKey}`;
272
-
273
- // 有图片时改用 OpenAI multimodal content 数组(text + image_url)。
274
- // 非多模态模型遇到 image_url 会忽略图片块,相当于退化成纯文本,不会报错。
275
- let userContent;
276
- if (Array.isArray(images) && images.length > 0) {
277
- userContent = [
278
- { type: 'text', text: prompt },
279
- ...images.map(img => ({ type: 'image_url', image_url: { url: img } }))
280
- ];
281
- } else {
282
- userContent = prompt;
283
- }
284
-
285
- const body = JSON.stringify({
286
- model: model.model,
287
- messages: [{ role: 'user', content: userContent }],
288
- max_tokens: maxTokens,
289
- temperature: 0.4,
290
- response_format: { type: 'json_object' },
291
- stream: false,
292
- });
293
-
294
- const controller = new AbortController();
295
- const timer = setTimeout(() => controller.abort(), timeoutMs);
296
- try {
297
- const resp = await fetch(url, { method: 'POST', headers, body, signal: controller.signal });
298
- const data = await resp.json().catch(() => ({}));
299
- if (!resp.ok) throw new Error(data?.error?.message || `HTTP ${resp.status}`);
300
- const content = data?.choices?.[0]?.message?.content || '{}';
301
- try {
302
- const m = content.match(/```json\s*([\s\S]*?)```/) || content.match(/({[\s\S]*})/);
303
- return JSON.parse(m ? m[1] : content);
304
- } catch {
305
- return {};
306
- }
307
- } finally {
308
- clearTimeout(timer);
309
- }
310
- }
311
-
312
- /**
313
- * 流式调用 OpenAI 兼容 LLM。每收到一个 chunk 调 onDelta 回调。
314
- * onDelta 接收 { thinking?: string, content?: string },二选一。
315
- * - reasoning_content / reasoning:部分模型(如 deepseek)放在 delta.reasoning_content
316
- * - reasoning / reasoning_text:openai o1 风格
317
- * - content:普通输出
318
- * 返回完整 content 字符串。
319
- */
320
- async function callLlmStream(model, prompt, onDelta, opts = {}) {
321
- const { maxTokens = 2000, timeoutMs = 600000, signal, images = [] } = opts
322
- const { default: fetch } = await import('node-fetch').catch(() => ({ default: globalThis.fetch }))
323
- const url = `${String(model.baseURL || '').replace(/\/$/, '')}/chat/completions`
324
- const headers = { 'Content-Type': 'application/json' }
325
- if (model.apiKey) headers['Authorization'] = `Bearer ${model.apiKey}`
326
-
327
- let userContent
328
- if (Array.isArray(images) && images.length > 0) {
329
- userContent = [
330
- { type: 'text', text: prompt },
331
- ...images.map(img => ({ type: 'image_url', image_url: { url: img } }))
332
- ]
333
- } else {
334
- userContent = prompt
335
- }
336
-
337
- const body = JSON.stringify({
338
- model: model.model,
339
- messages: [{ role: 'user', content: userContent }],
340
- max_tokens: maxTokens,
341
- temperature: 0.4,
342
- // 注意:stream: true 模式下不能同时使用 response_format:{type:'json_object'},
343
- // 部分 provider 会在收到两个一起时报错/静默卡住。改在 prompt 里约束 JSON 输出即可。
344
- stream: true,
345
- })
346
-
347
- const controller = new AbortController()
348
- const timer = setTimeout(() => controller.abort(), timeoutMs)
349
- // 允许外部 signal 触发取消(用户在 GUI 点停止)
350
- const onAbort = () => controller.abort()
351
- if (signal) {
352
- if (signal.aborted) controller.abort()
353
- else signal.addEventListener('abort', onAbort)
354
- }
355
-
356
- let fullContent = ''
357
- let aborted = false
358
- try {
359
- const resp = await fetch(url, { method: 'POST', headers, body, signal: controller.signal })
360
- if (!resp.ok || !resp.body) {
361
- const errText = await resp.text().catch(() => '')
362
- throw new Error(errText || `HTTP ${resp.status}`)
363
- }
364
-
365
- // SSE 格式:每行 "data: {...}",最后 "data: [DONE]"
366
- const decoder = new TextDecoder('utf-8')
367
- let buf = ''
368
- for await (const chunk of resp.body) {
369
- buf += decoder.decode(chunk, { stream: true })
370
- const lines = buf.split('\n')
371
- buf = lines.pop() ?? ''
372
- for (const line of lines) {
373
- const trimmed = line.trim()
374
- if (!trimmed || !trimmed.startsWith('data:')) continue
375
- const payload = trimmed.slice(5).trim()
376
- if (payload === '[DONE]') continue
377
- try {
378
- const evt = JSON.parse(payload)
379
- const delta = evt.choices?.[0]?.delta || {}
380
- // thinking 在不同 provider 字段名不同,全部尝试
381
- const thinkingChunk = delta.reasoning_content
382
- || delta.reasoning
383
- || delta.reasoning_text
384
- || ''
385
- const contentChunk = delta.content || ''
386
- if (thinkingChunk) onDelta({ thinking: thinkingChunk })
387
- if (contentChunk) {
388
- fullContent += contentChunk
389
- onDelta({ content: contentChunk })
390
- }
391
- } catch { /* 跳过无法解析的行 */ }
392
- }
393
- }
394
- } catch (err) {
395
- if (err?.name === 'AbortError' || controller.signal.aborted) {
396
- aborted = true
397
- // 中断不算错误——上层会决定怎么处理
398
- } else {
399
- throw err
400
- }
401
- } finally {
402
- clearTimeout(timer)
403
- if (signal) signal.removeEventListener('abort', onAbort)
404
- }
405
- return { content: fullContent, aborted }
406
- }
407
-
408
- function nowIso() {
409
- return new Date().toISOString();
410
- }
411
-
412
- function genId() {
413
- return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
414
- }
415
-
416
- async function ensureDataDir() {
417
- await fsp.mkdir(DATA_DIR, { recursive: true });
418
- }
419
-
420
- async function readJson(file, fallback) {
421
- try {
422
- const buf = await fsp.readFile(file, 'utf-8');
423
- return JSON.parse(buf);
424
- } catch (err) {
425
- if (err && err.code === 'ENOENT') return fallback;
426
- throw err;
427
- }
428
- }
429
-
430
- async function writeJson(file, data) {
431
- await ensureDataDir();
432
- const tmp = `${file}.tmp`;
433
- await fsp.writeFile(tmp, JSON.stringify(data, null, 2), 'utf-8');
434
- await fsp.rename(tmp, file);
435
- }
436
-
437
- // 简单的 Mustache 风格变量插值:{{task.title}} / {{task.desc}} / {{repo.path}} / {{branch}}
438
- function interpolate(template, ctx) {
439
- if (typeof template !== 'string') return template;
440
- return template.replace(/\{\{\s*([\w.]+)\s*\}\}/g, (_, key) => {
441
- const parts = key.split('.');
442
- let cur = ctx;
443
- for (const p of parts) {
444
- if (cur == null) return '';
445
- cur = cur[p];
446
- }
447
- return cur == null ? '' : String(cur);
448
- });
449
- }
450
-
451
- // ── 进程表:记录每个子任务的运行状态 ──────────────────────────────────────
452
- const bus = new EventEmitter();
453
- const jobs = new Map(); // jobId -> { id, taskId, subId, status, pid, startedAt, endedAt, exitCode, error, prompt }
454
- // 被用户主动取消的 jobId 集合——runTaskQueue 在 waitProcessExit 之后检查这个集合
455
- // 来决定把 job 标为 'cancelled' 还是 'done'。
456
- // 用 Set 而不是 job.cancelled 标志,是为了在 SIGTERM 发出后到 child 真正退出之间
457
- // 有一个简洁的"待回收"窗口。
458
- const cancelledJobs = new Set();
459
-
460
- // ── 生成指令持久化(~/.zen-gitsync/ai-instruction.json) ────────────────────
461
- async function readInstruction() {
462
- try {
463
- const buf = await fsp.readFile(INSTRUCTION_FILE, 'utf-8');
464
- const obj = JSON.parse(buf);
465
- if (obj && typeof obj.instruction === 'string' && obj.instruction.trim()) {
466
- return obj.instruction;
467
- }
468
- } catch { /* 文件不存在或解析失败 */ }
469
- return DEFAULT_INSTRUCTION;
470
- }
471
-
472
- async function writeInstruction(instruction) {
473
- await ensureDataDir();
474
- const text = String(instruction || '').trim() || DEFAULT_INSTRUCTION;
475
- const tmp = `${INSTRUCTION_FILE}.tmp`;
476
- await fsp.writeFile(tmp, JSON.stringify({ instruction: text, updatedAt: nowIso() }, null, 2), 'utf-8');
477
- await fsp.rename(tmp, INSTRUCTION_FILE);
478
- }
479
-
480
- // AI 拆分子任务的指令:与生成项目架构说明的指令分开持久化,
481
- // 因为它面向的输出形态(subtask 列表)和任务粒度完全不同。
482
- // 支持传入 req:根据 Accept-Language 选默认(zh/en)
483
- async function readSubtaskInstruction(req) {
484
- try {
485
- const buf = await fsp.readFile(SUBTASK_INSTRUCTION_FILE, 'utf-8');
486
- const obj = JSON.parse(buf);
487
- if (obj && typeof obj.instruction === 'string' && obj.instruction.trim()) {
488
- return obj.instruction;
489
- }
490
- } catch { /* 文件不存在或解析失败 */ }
491
- return pickDefaultSubtaskInstruction(req);
492
- }
493
- async function writeSubtaskInstruction(instruction) {
494
- await ensureDataDir();
495
- // 写入时如果与当前 locale 默认一致,不写文件——这样前端"isDefault"判定永远准确
496
- const text = String(instruction || '').trim() || DEFAULT_SUBTASK_INSTRUCTION_ZH;
497
- const tmp = `${SUBTASK_INSTRUCTION_FILE}.tmp`;
498
- await fsp.writeFile(tmp, JSON.stringify({ instruction: text, updatedAt: nowIso() }, null, 2), 'utf-8');
499
- await fsp.rename(tmp, SUBTASK_INSTRUCTION_FILE);
500
- }
501
-
502
- // ── 子项目识别:递归找 .git / manifest;A 是 B 的祖先时只保留 B ─────────────
503
- async function findSubProjects(projectPath, opts = {}) {
504
- const { maxDepth = 4 } = opts;
505
- const candidates = [];
506
-
507
- async function walk(dir, depth) {
508
- if (depth > maxDepth) return;
509
- let entries;
510
- try { entries = await fsp.readdir(dir, { withFileTypes: true }); }
511
- catch { return; }
512
-
513
- let hasManifest = false;
514
- let hasGit = false;
515
- const subDirs = [];
516
- for (const e of entries) {
517
- if (!e.isDirectory() && !e.isFile()) continue;
518
- if (e.name.startsWith('.')) {
519
- if (e.name === '.git' && e.isDirectory()) hasGit = true;
520
- continue;
521
- }
522
- if (e.isDirectory()) {
523
- if (SKIP_DIRS.has(e.name)) continue;
524
- subDirs.push(path.join(dir, e.name));
525
- } else if (e.isFile() && MANIFEST_FILES.includes(e.name)) {
526
- hasManifest = true;
527
- }
528
- }
529
- if (hasManifest || hasGit) {
530
- candidates.push(dir);
531
- return; // 子目录里若还有 manifest,会被自己发现;这里不再下钻避免冗余
532
- }
533
- if (depth >= maxDepth) return;
534
- for (const sub of subDirs) {
535
- await walk(sub, depth + 1);
536
- }
537
- }
538
-
539
- await walk(projectPath, 0);
540
-
541
- // 去重:若 candidates 里 A 是 B 的祖先,只保留更深一级的 B
542
- candidates.sort((a, b) => a.length - b.length);
543
- const kept = [];
544
- for (const c of candidates) {
545
- let dominated = false;
546
- for (const k of kept) {
547
- if (c === k || c.startsWith(k + path.sep)) { dominated = true; break; }
548
- }
549
- if (!dominated) kept.push(c);
550
- }
551
-
552
- // 收集每个子项目的关键文件
553
- const result = [];
554
- for (const root of kept) {
555
- const manifests = {};
556
- for (const m of MANIFEST_FILES) {
557
- const p = path.join(root, m);
558
- try {
559
- const stat = await fsp.stat(p);
560
- if (stat.isFile()) {
561
- manifests[m] = stat.size > 20000
562
- ? await safeReadFile(p, 20000)
563
- : await fsp.readFile(p, 'utf8');
564
- }
565
- } catch { /* 不存在就跳过 */ }
566
- }
567
- let readme = '';
568
- try {
569
- const stat = await fsp.stat(path.join(root, 'README.md'));
570
- if (stat.isFile()) readme = await safeReadFile(path.join(root, 'README.md'), 8000);
571
- } catch { /* 不存在就跳过 */ }
572
- const dirTree = await listDirTree(root, 2, 200);
573
- result.push({
574
- root,
575
- name: path.basename(root) || path.basename(projectPath),
576
- manifests,
577
- readme,
578
- dirTree
579
- });
580
- }
581
- return result;
582
- }
583
-
584
- function publish(event, payload) {
585
- bus.emit('event', { event, payload, ts: nowIso() });
586
- }
587
-
588
- function snapshotJobs() {
589
- return Array.from(jobs.values()).map(j => ({
590
- id: j.id,
591
- taskId: j.taskId,
592
- subId: j.subId,
593
- title: j.title,
594
- status: j.status,
595
- prompt: j.prompt || '',
596
- output: j.output || '',
597
- pid: j.pid || null,
598
- startedAt: j.startedAt || null,
599
- endedAt: j.endedAt || null,
600
- exitCode: typeof j.exitCode === 'number' ? j.exitCode : null,
601
- error: j.error || null
602
- }));
603
- }
604
-
605
- // 用 detached 进程跑 claude;进程退出时回填状态。
606
- // 返回 { pid, child }:调用方可以监听 child.stdout/stderr 实时收集输出。
607
- // 不再走 cmd /k 弹窗——claude -p 是非交互模式,输出通过 stdout pipe 实时回传
608
- // 到前端面板展示。
609
- function launchClaudeInNewWindow(cwd, promptText) {
610
- return new Promise((resolve, reject) => {
611
- const args = [
612
- '-p', promptText,
613
- '--input-format', 'text',
614
- '--output-format', 'stream-json',
615
- '--verbose',
616
- '--permission-mode', 'bypassPermissions',
617
- '--dangerously-skip-permissions'
618
- ];
619
- let child;
620
- let spawnedExe = 'claude';
621
- if (process.platform === 'win32') {
622
- // 直接 spawn claude.exe(npm 全局 @anthropic-ai/claude-code 里的真实二进制),
623
- // 避开两件事:
624
- // 1. Node 23 在 Windows 上拒绝 spawn .cmd/.bat(EINVAL)
625
- // 2. shell:true 会把 argv 拼成命令行交给 cmd 解释,prompt 里的 \n 被切成多段
626
- // 用 `where claude` 找到 claude.cmd,再从 cmd 内容推断对应 .exe 路径。
627
- let claudeExe = 'claude.exe';
628
- try {
629
- const cmdShim = execFileSync('where', ['claude'], { encoding: 'utf8' })
630
- .split(/\r?\n/).map(s => s.trim()).find(s => /\.cmd$/i.test(s));
631
- if (cmdShim) {
632
- const txt = fs.readFileSync(cmdShim, 'utf8');
633
- if (/%dp0%\\node_modules\\@anthropic-ai\\claude-code\\bin\\claude\.exe/i.test(txt)) {
634
- claudeExe = path.join(path.dirname(cmdShim), 'node_modules', '@anthropic-ai', 'claude-code', 'bin', 'claude.exe');
635
- }
636
- }
637
- } catch { /* fallback */ }
638
- spawnedExe = claudeExe;
639
- child = spawn(claudeExe, args, {
640
- cwd,
641
- stdio: ['ignore', 'pipe', 'pipe'],
642
- windowsHide: false,
643
- env: { ...process.env, LANG: 'zh_CN.UTF-8' }
644
- });
645
- } else {
646
- // macOS / Linux:直接 spawn claude(Node spawn 不走 shell,
647
- // prompt 中的引号 / 反斜杠无需手动 escape)
648
- child = spawn('claude', args, {
649
- cwd,
650
- detached: true,
651
- stdio: ['ignore', 'pipe', 'pipe'],
652
- env: { ...process.env, LANG: 'zh_CN.UTF-8' }
653
- });
654
- }
655
- child.on('error', reject);
656
- child.on('spawn', () => {
657
- // unref 让 claude 独立于父进程事件循环;返回 child 引用让调用方继续读 stdout。
658
- child.unref();
659
- resolve({ pid: child.pid, child });
660
- });
661
- });
662
- }
663
-
664
- // 顺序执行一个任务下所有子任务;上一个结束再启动下一个
665
- async function runTaskQueue(task, repoPath, branch) {
666
- // 前序上下文:跑完一个 sub 后把它"完成态"摘要存到这里,下一个 sub 启动时
667
- // 拼到 prompt 头部,让 Claude 知道前面做了什么、产出了什么。
668
- // 故意不用 raw output 全文——LLM 已经习惯"摘要 + 关键结论"的格式,且不会
669
- // 一次塞几 MB 进 prompt 烧 token。truncate 到每条 MAX_PREV_OUTPUT_CHARS。
670
- const MAX_PREV_OUTPUT_CHARS = 2000
671
- const priorOutputs = []
672
- for (const sub of task.subtasks) {
673
- if (sub.status === 'done') continue;
674
- const promptTemplate = sub.promptOverride || (task.promptId
675
- ? (await readJson(PROMPTS_FILE, { prompts: [] })).prompts.find(p => p.id === task.promptId)?.content
676
- : null) || '';
677
- const ctx = {
678
- task: { title: task.title, desc: task.desc || '' },
679
- sub: { title: sub.title, desc: sub.desc || '' },
680
- repo: { path: repoPath || '' },
681
- branch: branch || ''
682
- };
683
- const interpolated = interpolate(promptTemplate, ctx);
684
- const parts = [interpolated, sub.title, sub.desc].filter(s => s && s.trim());
685
- let prompt = parts.join('\n\n');
686
-
687
- // ── 前序上下文:把前几个 done 子任务的输出摘要拼到 prompt 头部 ──
688
- if (priorOutputs.length > 0) {
689
- const prevBlock = priorOutputs.map((p, i) => {
690
- const text = (p.output || '').slice(0, MAX_PREV_OUTPUT_CHARS)
691
- const truncated = (p.output || '').length > MAX_PREV_OUTPUT_CHARS ? '\n…(前文已截断)' : ''
692
- return `### [${i + 1}] ${p.title}\n${text}${truncated}`
693
- }).join('\n\n')
694
- prompt = `以下是同一任务下已经完成的前序子任务输出(仅作上下文参考,请基于这些结论继续当前子任务,无需重复执行它们):
695
-
696
- ${prevBlock}
697
-
698
- ---
699
-
700
- ${prompt}`
701
- }
702
-
703
- // ── 附件:合并 sub.attachments + task.attachments 后拼到 prompt 末尾 ──
704
- // claude -p 字符串模式会扫描 prompt 中出现的本地文件路径并自动
705
- // 识别为附件(图片 / PDF / 文本均可)。
706
- // 主任务附件对所有 sub 都可见;子任务自己的附件只对该 sub 可见。
707
- const allAttachments = [
708
- ...(Array.isArray(task.attachments) ? task.attachments : []),
709
- ...(Array.isArray(sub.attachments) ? sub.attachments : [])
710
- ];
711
- if (allAttachments.length > 0) {
712
- const lines = allAttachments
713
- .filter(a => a && a.absolutePath)
714
- .map((a, i) => ` ${i + 1}. [${a.mimeType || 'application/octet-stream'}] ${a.absolutePath}`);
715
- if (lines.length > 0) {
716
- prompt += `\n\n---\n本任务包含 ${lines.length} 个附件(请按文件路径读取,不要让用户重新提供):\n${lines.join('\n')}\n---`;
717
- }
718
- }
719
-
720
- const jobId = genId();
721
- const job = {
722
- id: jobId,
723
- taskId: task.id,
724
- subId: sub.id,
725
- title: `${task.title} / ${sub.title}`,
726
- status: 'pending',
727
- prompt
728
- };
729
- jobs.set(jobId, job);
730
- sub.status = 'running';
731
- publish('sub:update', { taskId: task.id, sub });
732
- publish('job:update', job);
733
-
734
- try {
735
- const { pid, child } = await launchClaudeInNewWindow(repoPath || process.cwd(), prompt);
736
- job.pid = pid;
737
- // 保存 child 引用,供 cancel 接口调用 kill
738
- job.child = child;
739
- job.startedAt = nowIso();
740
- job.status = 'running';
741
- publish('job:update', job);
742
-
743
- // 流式 NDJSON 解析:把 stdout 当作 stream-json 协议处理
744
- // assistant.text → job.output (用户主要关心的内容)
745
- // assistant.thinking → job.thinking (折叠展示,让用户知道 Claude 在想)
746
- // 其他事件(init / tool_use / result 等)忽略,避免噪声
747
- // 解析失败的行原样进 output,便于排查协议异常。
748
- // 过长时(>256KB)只截断尾部 256KB,避免内存膨胀。
749
- const MAX_OUTPUT = 256 * 1024;
750
- const MAX_THINKING = 64 * 1024;
751
- job.output = '';
752
- job.thinking = '';
753
- const lineBuf = { stdout: '', stderr: '' };
754
-
755
- const parseLines = (channel, buf) => {
756
- const chunk = buf.toString('utf8');
757
- lineBuf[channel] += chunk;
758
- const lines = lineBuf[channel].split('\n');
759
- lineBuf[channel] = lines.pop() ?? ''; // 最后一段可能不完整,留给下次
760
- for (const line of lines) {
761
- const trimmed = line.trim();
762
- if (!trimmed) continue;
763
- if (channel === 'stderr' || !trimmed.startsWith('{')) {
764
- // 非 stream-json 行:原样塞进 output(兼容老版本 claude / 错误信息)
765
- job.output = (job.output + trimmed + '\n').slice(-MAX_OUTPUT);
766
- continue;
767
- }
768
- let evt;
769
- try { evt = JSON.parse(trimmed) } catch { continue }
770
- if (evt.type !== 'assistant') continue;
771
- const blocks = evt.message?.content;
772
- if (!Array.isArray(blocks)) continue;
773
- for (const b of blocks) {
774
- if (b.type === 'text' && typeof b.text === 'string') {
775
- job.output = (job.output + b.text).slice(-MAX_OUTPUT);
776
- } else if (b.type === 'thinking' && typeof b.thinking === 'string') {
777
- job.thinking = (job.thinking + b.thinking).slice(-MAX_THINKING);
778
- }
779
- }
780
- }
781
- publish('job:update', job);
782
- };
783
- if (child.stdout) child.stdout.on('data', (buf) => parseLines('stdout', buf));
784
- if (child.stderr) child.stderr.on('data', (buf) => parseLines('stderr', buf));
785
-
786
- // 等待进程退出(detached 不阻塞主进程,用 polling /proc 兜底)
787
- await waitProcessExit(pid);
788
- const wasCancelled = cancelledJobs.has(jobId)
789
- if (wasCancelled) cancelledJobs.delete(jobId)
790
- // 进程退出时 stdout 可能残留最后一段未换行的 NDJSON,flush 一次
791
- if (lineBuf.stdout.trim()) {
792
- try {
793
- const evt = JSON.parse(lineBuf.stdout.trim())
794
- if (evt.type === 'assistant' && Array.isArray(evt.message?.content)) {
795
- for (const b of evt.message.content) {
796
- if (b.type === 'text' && typeof b.text === 'string') {
797
- job.output = (job.output + b.text).slice(-MAX_OUTPUT)
798
- } else if (b.type === 'thinking' && typeof b.thinking === 'string') {
799
- job.thinking = (job.thinking + b.thinking).slice(-MAX_THINKING)
800
- }
801
- }
802
- }
803
- } catch { /* 不是 JSON,忽略 */ }
804
- }
805
- job.endedAt = nowIso();
806
- if (wasCancelled) {
807
- job.exitCode = 130; // 128 + SIGINT(2),约定俗成的"用户取消"退出码
808
- job.status = 'cancelled';
809
- job.error = '用户已停止执行';
810
- // sub 不改状态——cancelled 是 job 维度,同 task 后续 sub 仍可继续执行
811
- } else {
812
- job.exitCode = 0;
813
- job.status = 'done';
814
- sub.status = 'done';
815
- // 把这个 sub 的输出累积到前序上下文,喂给下一个 sub
816
- priorOutputs.push({ title: sub.title, output: job.output || '' })
817
- }
818
- } catch (err) {
819
- job.error = err && err.message ? err.message : String(err);
820
- job.status = 'error';
821
- sub.status = 'error';
822
- } finally {
823
- // 移除 child 引用——避免后续被 SSE 序列化到前端
824
- delete job.child
825
- publish('job:update', job);
826
- publish('sub:update', { taskId: task.id, sub });
827
- }
828
- }
829
- // 写回 tasks.json
830
- const data = await readJson(TASKS_FILE, { tasks: [] });
831
- const t = data.tasks.find(x => x.id === task.id);
832
- if (t) {
833
- t.subtasks = task.subtasks;
834
- t.updatedAt = nowIso();
835
- await writeJson(TASKS_FILE, data);
836
- publish('task:update', t);
837
- }
838
- }
839
-
840
- function waitProcessExit(pid) {
841
- return new Promise(resolve => {
842
- let exited = false;
843
- const tryCheck = () => {
844
- if (exited) return;
845
- try {
846
- process.kill(pid, 0); // 信号 0 = 探测存活
847
- } catch (err) {
848
- // 只在进程真的消失(ESRCH / EPERM)时才 resolve;
849
- // 其他错误(比如参数类型)保留 polling 状态,由超时兜底。
850
- if (err && (err.code === 'ESRCH' || err.code === 'EPERM')) {
851
- exited = true;
852
- resolve();
853
- return;
854
- }
855
- }
856
- setTimeout(tryCheck, 1500);
857
- };
858
- tryCheck();
859
- // 兜底:30 分钟超时自动结束
860
- setTimeout(() => { if (!exited) { exited = true; resolve(); } }, 30 * 60 * 1000);
861
- });
862
- }
863
-
864
- export function registerWorkbenchRoutes({ app, getCurrentProjectPath, getProjectRoomId, io, configManager }) {
865
- // ── AI 生成提示词(基于当前项目) ─────────────────────────────────────
866
- app.post('/api/workbench/prompts/ai-generate', async (req, res) => {
867
- try {
868
- const projectPath = typeof getCurrentProjectPath === 'function' ? getCurrentProjectPath() : '';
869
- if (!projectPath) {
870
- return res.status(400).json({ success: false, error: '未选中项目' });
871
- }
872
- let stat;
873
- try { stat = await fsp.stat(projectPath); }
874
- catch { return res.status(400).json({ success: false, error: '项目路径不存在' }); }
875
- if (!stat.isDirectory()) {
876
- return res.status(400).json({ success: false, error: '项目路径不是目录' });
877
- }
878
-
879
- // 取模型
880
- let model;
881
- try {
882
- if (!configManager) throw new Error('configManager 不可用');
883
- const rawConfig = await configManager.readRawConfigFile();
884
- const models = Array.isArray(rawConfig.models) ? rawConfig.models : [];
885
- model = models.find(m => m.isDefault) || models[0];
886
- } catch (err) {
887
- return res.status(500).json({ success: false, error: '读取 AI 配置失败: ' + err.message });
888
- }
889
- if (!model) {
890
- return res.status(400).json({ success: false, error: '未配置 AI 模型,请先在通用设置中添加模型' });
891
- }
892
-
893
- // 读取用户可编辑的生成指令;没存就用默认
894
- const userInstruction = await readInstruction();
895
-
896
- // 递归识别多子项目
897
- const subProjects = await findSubProjects(projectPath);
898
- if (subProjects.length === 0) {
899
- // 没识别到任何子项目:回退到根目录本身
900
- const fallbackTree = await listDirTree(projectPath, 2, 400);
901
- const fallbackManifest = await readProjectManifest(projectPath);
902
- const fallbackReadme = await safeReadFile(path.join(projectPath, 'README.md'), 8000);
903
- subProjects.push({
904
- root: projectPath,
905
- name: path.basename(projectPath),
906
- manifests: fallbackManifest,
907
- readme: fallbackReadme,
908
- dirTree: fallbackTree
909
- });
910
- }
911
-
912
- const projectName = path.basename(projectPath);
913
- const LLM_OPTS = { maxTokens: 4000, timeoutMs: 1200000 };
914
-
915
- // ── 第一阶段:基于可编辑指令 + 根目录概览,生成「可复用的提示词模板」 ──
916
- const overviewBlock = subProjects.map(sp =>
917
- `### 子项目 ${sp.name} (${sp.root})\n目录:\n${sp.dirTree || '(无)'}`
918
- ).join('\n\n');
919
-
920
- const firstPrompt = `${userInstruction}
921
-
922
- ---
923
-
924
- 以下是你需要分析的项目(请先生成「可复用的提示词模板」,不要直接给总结):
925
-
926
- 项目根目录:${projectPath}
927
- 项目名称:${projectName}
928
- 子项目数:${subProjects.length}
929
-
930
- ## 子项目概览
931
- ${overviewBlock || '(无)'}
932
-
933
- ## 各子项目 manifest 与 README
934
- ${subProjects.map(sp => {
935
- const manifestBlock = Object.entries(sp.manifests)
936
- .map(([n, c]) => `\n--- ${n} ---\n${c}`)
937
- .join('\n');
938
- return `\n### ${sp.name}\n${manifestBlock || '(无 manifest)'}\n\nREADME(前 8KB):\n${sp.readme || '(无)'}`;
939
- }).join('\n')}
940
-
941
- 只返回 JSON:
942
- {
943
- "name": "项目名(10-20字)",
944
- "template": "可复用的提示词模板(300-600字),应明确使用 {{task.title}} / {{task.desc}} / {{sub.title}} / {{sub.desc}} / {{repo.path}} / {{branch}} 这 6 个变量"
945
- }`;
946
-
947
- const first = await callLlmJson(model, firstPrompt, LLM_OPTS);
948
- const templateName = String(first.name || '').trim() || projectName || '项目架构说明';
949
- const template = String(first.template || '').trim();
950
-
951
- // ── 第二阶段:为每个子项目分别生成总结(单子项目 = 现在的行为) ──
952
- async function summarizeOneSub(sp) {
953
- const manifestBlock = Object.entries(sp.manifests)
954
- .map(([n, c]) => `\n--- ${n} ---\n${c}`)
955
- .join('\n');
956
- const subPrompt = `${template}
957
-
958
- ---
959
-
960
- 以下是你需要分析的一个子项目(请直接基于这些数据输出该子项目的架构说明):
961
-
962
- 子项目根目录:${sp.root}
963
- 子项目名称:${sp.name}
964
-
965
- ## 目录结构(前 2 层)
966
- ${sp.dirTree || '(无)'}
967
-
968
- ## manifest
969
- ${manifestBlock || '(无)'}
970
-
971
- ## README
972
- ${sp.readme || '(无)'}
973
-
974
- 只返回 JSON:
975
- {
976
- "summary": "该子项目的架构说明(300-600字)"
977
- }`;
978
- const r = await callLlmJson(model, subPrompt, LLM_OPTS);
979
- return { name: sp.name, root: sp.root, summary: String(r.summary || '').trim() };
980
- }
981
-
982
- const subSummaries = await Promise.all(subProjects.map(summarizeOneSub));
983
-
984
- // ── 第三阶段:仅多子项目时合并(单子项目直接拿它的 summary) ──
985
- let finalSummary = '';
986
- let finalName = templateName;
987
-
988
- if (subSummaries.length === 1) {
989
- finalSummary = subSummaries[0].summary;
990
- } else {
991
- const mergePrompt = `你是项目架构师。下列是同一仓库下 N 个子项目的架构说明,请合并输出**单一**的「项目架构说明」(800-1500字),覆盖:项目整体定位、技术栈、模块划分、子项目间关系、核心流程、关键设计决策。
992
- 子项目之间用清晰的小标题或编号分隔。最后输出一段「整体架构」总结它们如何协同。
993
- 只引用实际出现的子项目名 / 文件路径 / 依赖名,不要编造。只返回 JSON:
994
-
995
- {
996
- "name": "项目名(10-20字)",
997
- "summary": "合并后的架构说明"
998
- }
999
-
1000
- ## 子项目说明
1001
- ${subSummaries.map((s, i) => `\n### [${i + 1}] ${s.name} (${s.root})\n${s.summary || '(空)'}`).join('\n')}`;
1002
-
1003
- const merged = await callLlmJson(model, mergePrompt, LLM_OPTS);
1004
- finalSummary = String(merged.summary || '').trim()
1005
- || subSummaries.map(s => `### ${s.name}\n${s.summary}`).join('\n\n');
1006
- finalName = String(merged.name || '').trim() || templateName;
1007
- }
1008
-
1009
- if (!finalSummary) {
1010
- // 兜底:仅返回模板
1011
- return res.json({
1012
- success: true,
1013
- name: finalName,
1014
- template,
1015
- result: '',
1016
- content: template
1017
- });
1018
- }
1019
-
1020
- // 顶层 request 已经自带 20 分钟(1200s)超时;
1021
- // 这里在 express 处理器内部不再额外加整体超时。
1022
- res.json({
1023
- success: true,
1024
- name: finalName,
1025
- template,
1026
- result: finalSummary,
1027
- content: finalSummary
1028
- });
1029
- } catch (err) {
1030
- res.status(500).json({ success: false, error: err.message });
1031
- }
1032
- });
1033
-
1034
- // ── 生成指令:读 / 写(用户可在弹窗里自定义) ───────────────────────
1035
- app.get('/api/workbench/prompts/ai-instruction', async (_req, res) => {
1036
- try {
1037
- const instruction = await readInstruction();
1038
- res.json({ success: true, instruction, isDefault: instruction === DEFAULT_INSTRUCTION });
1039
- } catch (err) {
1040
- res.status(500).json({ success: false, error: err.message });
1041
- }
1042
- });
1043
-
1044
- app.put('/api/workbench/prompts/ai-instruction', async (req, res) => {
1045
- try {
1046
- const text = req.body && typeof req.body.instruction === 'string'
1047
- ? req.body.instruction.trim()
1048
- : '';
1049
- if (!text) {
1050
- return res.status(400).json({ success: false, error: '指令不能为空' });
1051
- }
1052
- if (text.length > 50000) {
1053
- return res.status(413).json({ success: false, error: '指令过长(最多 50000 字符)' });
1054
- }
1055
- await writeInstruction(text);
1056
- res.json({ success: true });
1057
- } catch (err) {
1058
- res.status(500).json({ success: false, error: err.message });
1059
- }
1060
- });
1061
-
1062
- // ── AI 拆分子任务:独立的指令文件、独立的端点 ───────────────────────
1063
- // GET /api/workbench/tasks/ai-subtask-instruction
1064
- // → { success, instruction, isDefault }
1065
- // PUT /api/workbench/tasks/ai-subtask-instruction
1066
- // body: { instruction: string }
1067
- // → { success }
1068
- app.get('/api/workbench/tasks/ai-subtask-instruction', async (req, res) => {
1069
- try {
1070
- const def = pickDefaultSubtaskInstruction(req);
1071
- const instruction = await readSubtaskInstruction(req);
1072
- // isDefault:当前 instruction 和 locale 默认完全一致
1073
- res.json({ success: true, instruction, isDefault: instruction === def });
1074
- } catch (err) {
1075
- res.status(500).json({ success: false, error: err.message });
1076
- }
1077
- });
1078
-
1079
- app.put('/api/workbench/tasks/ai-subtask-instruction', async (req, res) => {
1080
- try {
1081
- const text = req.body && typeof req.body.instruction === 'string'
1082
- ? req.body.instruction.trim()
1083
- : '';
1084
- if (!text) {
1085
- return res.status(400).json({ success: false, error: '指令不能为空' });
1086
- }
1087
- if (text.length > 50000) {
1088
- return res.status(413).json({ success: false, error: '指令过长(最多 50000 字符)' });
1089
- }
1090
- // 如果保存的文本正好等于当前 locale 的默认——不写文件,保持 fallback 行为
1091
- const def = pickDefaultSubtaskInstruction(req);
1092
- if (text === def) {
1093
- // 删除已存在的自定义文件
1094
- try { await fsp.unlink(SUBTASK_INSTRUCTION_FILE) } catch {}
1095
- return res.json({ success: true, isDefault: true });
1096
- }
1097
- await writeSubtaskInstruction(text);
1098
- res.json({ success: true, isDefault: false });
1099
- } catch (err) {
1100
- res.status(500).json({ success: false, error: err.message });
1101
- }
1102
- });
1103
-
1104
- // POST /api/workbench/tasks/ai-split-subtasks
1105
- // body: { title, desc, taskId? }
1106
- // → SSE 流:
1107
- // data:{"type":"meta","prompt":{system,user}}\n\n
1108
- // data:{"type":"thinking","delta":"..."}\n\n (多次)
1109
- // data:{"type":"content","delta":"..."}\n\n (多次)
1110
- // data:{"type":"done","subtasks":[...],"raw":"..."}\n\n
1111
- // data:{"type":"error","error":"..."}\n\n (失败时)
1112
- //
1113
- // 走流式是为了让用户看到模型真实的 reasoning_content(如果模型支持),
1114
- // 而不是前端用 setInterval 假装"打字机"——拆分质量也会因为给了模型
1115
- // 充分的思考空间而显著提升。
1116
- app.post('/api/workbench/tasks/ai-split-subtasks', async (req, res) => {
1117
- const title = String(req.body?.title || '').trim();
1118
- const desc = String(req.body?.desc || '').trim();
1119
- const taskId = String(req.body?.taskId || '').trim();
1120
- const promptId = String(req.body?.promptId || '').trim();
1121
- if (!title) {
1122
- return res.status(400).json({ success: false, error: '任务标题不能为空' });
1123
- }
1124
-
1125
- // 建立 SSE
1126
- res.set({
1127
- 'Content-Type': 'text/event-stream',
1128
- 'Cache-Control': 'no-cache, no-transform',
1129
- 'Connection': 'keep-alive',
1130
- 'X-Accel-Buffering': 'no'
1131
- });
1132
- res.flushHeaders?.();
1133
- const send = (obj) => {
1134
- try { res.write(`data: ${JSON.stringify(obj)}\n\n`); } catch {}
1135
- };
1136
-
1137
- const abortController = new AbortController();
1138
- let finished = false; // 标记响应是否已正常结束
1139
- // 客户端真实断开:监听 socket close,而不是 req.close。
1140
- // Node 22+ 的 req 'close' 事件会在 HTTP keep-alive socket 池回收时过早触发,
1141
- // 导致正常请求中途被 abort。这里改用 socket 真实断开事件,
1142
- // 并只在响应还没 end 时才取消上游 LLM。
1143
- const onSocketClose = () => {
1144
- if (!finished) abortController.abort()
1145
- };
1146
- if (req.socket) {
1147
- req.socket.once('close', onSocketClose);
1148
- }
1149
-
1150
- try {
1151
- let model;
1152
- try {
1153
- if (!configManager) throw new Error('configManager 不可用');
1154
- const rawConfig = await configManager.readRawConfigFile();
1155
- const models = Array.isArray(rawConfig.models) ? rawConfig.models : [];
1156
- model = models.find(m => m.isDefault) || models[0];
1157
- } catch (err) {
1158
- send({ type: 'error', error: '读取 AI 配置失败: ' + err.message });
1159
- finished = true;
1160
- return res.end();
1161
- }
1162
- if (!model) {
1163
- send({ type: 'error', error: '未配置 AI 模型,请先在通用设置中添加模型' });
1164
- finished = true;
1165
- return res.end();
1166
- }
1167
-
1168
- const userInstruction = await readSubtaskInstruction(req);
1169
- const projectPath = typeof getCurrentProjectPath === 'function' ? getCurrentProjectPath() : '';
1170
- const projectName = projectPath ? path.basename(projectPath) : '(未指定项目)';
1171
- const manifestHint = await detectProjectManifest(projectPath);
1172
-
1173
- // 取绑定的预置模板(promptId):模板内容作为"执行模板"提示
1174
- // 让 LLM 拆分时知道:每个 sub 最终都会被这套模板包裹后送进 claude
1175
- let templateBlock = '';
1176
- if (promptId) {
1177
- try {
1178
- const promptData = await readJson(PROMPTS_FILE, { prompts: [] });
1179
- const p = (promptData.prompts || []).find(x => x.id === promptId);
1180
- if (p && p.content) {
1181
- templateBlock = `\n\n## 子任务执行模板(每个拆出的子任务最终会被这套模板包裹后送给 claude 执行;拆分时请确保子任务能让模板里的 {{sub.title}} / {{sub.desc}} 等变量填得有意义)\n模板名:${p.name || '(未命名)'}\n---\n${p.content}\n---`;
1182
- }
1183
- } catch { /* 模板读取失败不影响拆分 */ }
1184
- }
1185
-
1186
- // 取任务附件
1187
- let attachmentBlock = '';
1188
- const imageDataUrls = [];
1189
- if (taskId) {
1190
- try {
1191
- const data = await readJson(TASKS_FILE, { tasks: [] });
1192
- const task = (data.tasks || []).find(t => t.id === taskId);
1193
- const atts = Array.isArray(task?.attachments) ? task.attachments : [];
1194
- if (atts.length > 0) {
1195
- const lines = [];
1196
- for (let i = 0; i < atts.length; i++) {
1197
- const a = atts[i];
1198
- if (!a || !a.absolutePath) continue;
1199
- lines.push(` ${i + 1}. [${a.mimeType || 'application/octet-stream'}] ${a.absolutePath}`);
1200
- if (isImageExt(a.ext)) {
1201
- try {
1202
- const buf = await fsp.readFile(a.absolutePath);
1203
- const mime = a.mimeType || 'image/png';
1204
- imageDataUrls.push(`data:${mime};base64,${buf.toString('base64')}`);
1205
- } catch { /* 文件丢失就跳过这张图 */ }
1206
- }
1207
- }
1208
- if (lines.length > 0) {
1209
- const imgNote = imageDataUrls.length > 0
1210
- ? `(其中 ${imageDataUrls.length} 张图片已随消息一并发送,请直接基于图片内容拆分)`
1211
- : '';
1212
- attachmentBlock = `\n\n## 任务附件${imgNote}\n${lines.join('\n')}`;
1213
- }
1214
- }
1215
- } catch { /* 没拿到附件不影响拆分 */ }
1216
- }
1217
-
1218
- const userBlock = `${userInstruction}
1219
-
1220
- ---
1221
-
1222
- ## 待拆分的任务
1223
- 标题:${title}
1224
- ${desc ? `描述:${desc}` : '描述:(无)'}${attachmentBlock}${templateBlock}
1225
-
1226
- ## 项目上下文(仅供参考,便于拆分时考虑项目特性)
1227
- - 项目名称:${projectName}
1228
- - 项目根目录:${projectPath || '(未指定)'}
1229
- - 主要 manifest:${manifestHint || '(未识别到)'}
1230
-
1231
- 请先简要分析(可以放在 reasoning 中或直接写出来),然后给出 JSON。JSON 用 \`\`\`json ... \`\`\` 包裹:
1232
- {
1233
- "subtasks": [
1234
- { "title": "子任务标题(10-20字)", "desc": "具体描述" }
1235
- ]
1236
- }`;
1237
-
1238
- // 先把 prompt 元信息推给前端
1239
- send({ type: 'meta', prompt: { system: userInstruction, user: userBlock } });
1240
-
1241
- // 流式调用 LLM,把 thinking / content 实时回传
1242
- const { content, aborted } = await callLlmStream(
1243
- model,
1244
- userBlock,
1245
- (delta) => {
1246
- if (delta.thinking) send({ type: 'thinking', delta: delta.thinking });
1247
- if (delta.content) send({ type: 'content', delta: delta.content });
1248
- },
1249
- { maxTokens: 4000, timeoutMs: 600000, images: imageDataUrls, signal: abortController.signal }
1250
- );
1251
-
1252
- if (aborted) {
1253
- send({ type: 'error', error: '已取消' });
1254
- finished = true;
1255
- return res.end();
1256
- }
1257
-
1258
- // 解析 JSON:兼容 ```json ... ``` 代码块或裸 JSON
1259
- let parsed = {};
1260
- try {
1261
- const m = content.match(/```json\s*([\s\S]*?)```/i)
1262
- || content.match(/```\s*([\s\S]*?)```/)
1263
- || content.match(/(\{[\s\S]*\})/);
1264
- parsed = JSON.parse(m ? m[1] : content);
1265
- } catch { parsed = {}; }
1266
-
1267
- const list = Array.isArray(parsed?.subtasks) ? parsed.subtasks : [];
1268
- const subtasks = list
1269
- .map(s => ({
1270
- title: String(s?.title || '').trim().slice(0, 80),
1271
- desc: String(s?.desc || '').trim().slice(0, 500)
1272
- }))
1273
- .filter(s => s.title)
1274
- .slice(0, 8);
1275
-
1276
- send({ type: 'done', subtasks, raw: content });
1277
- finished = true;
1278
- res.end();
1279
- } catch (err) {
1280
- send({ type: 'error', error: 'AI 拆分失败: ' + (err?.message || String(err)) });
1281
- finished = true;
1282
- res.end();
1283
- }
1284
- });
1285
-
1286
- // SSE 事件流
1287
- app.get('/api/workbench/events', (req, res) => {
1288
- res.set({
1289
- 'Content-Type': 'text/event-stream',
1290
- 'Cache-Control': 'no-cache, no-transform',
1291
- 'Connection': 'keep-alive',
1292
- 'X-Accel-Buffering': 'no'
1293
- });
1294
- res.flushHeaders?.();
1295
- const send = (data) => {
1296
- res.write(`data: ${JSON.stringify(data)}\n\n`);
1297
- };
1298
- // 初始快照
1299
- send({ event: 'hello', payload: { jobs: snapshotJobs() }, ts: nowIso() });
1300
- const handler = (evt) => send(evt);
1301
- bus.on('event', handler);
1302
- const ka = setInterval(() => res.write(`: keep-alive\n\n`), 15000);
1303
- req.on('close', () => {
1304
- clearInterval(ka);
1305
- bus.off('event', handler);
1306
- });
1307
- });
1308
-
1309
- // ── 提示词 CRUD ─────────────────────────────────────────────────────
1310
- app.get('/api/workbench/prompts', async (_req, res) => {
1311
- try {
1312
- const data = await readJson(PROMPTS_FILE, { prompts: [] });
1313
- res.json({ success: true, prompts: data.prompts || [] });
1314
- } catch (err) {
1315
- res.status(500).json({ success: false, error: err.message });
1316
- }
1317
- });
1318
-
1319
- app.post('/api/workbench/prompts', async (req, res) => {
1320
- try {
1321
- const { id, name, content } = req.body || {};
1322
- if (!name || typeof content !== 'string') {
1323
- return res.status(400).json({ success: false, error: 'name 和 content 必填' });
1324
- }
1325
- const data = await readJson(PROMPTS_FILE, { prompts: [] });
1326
- const prompts = data.prompts || [];
1327
- const now = nowIso();
1328
- if (id) {
1329
- const i = prompts.findIndex(p => p.id === id);
1330
- if (i < 0) return res.status(404).json({ success: false, error: '提示词不存在' });
1331
- prompts[i] = { ...prompts[i], name, content, updatedAt: now };
1332
- await writeJson(PROMPTS_FILE, { prompts });
1333
- return res.json({ success: true, prompt: prompts[i] });
1334
- }
1335
- const prompt = { id: genId(), name, content, createdAt: now, updatedAt: now };
1336
- prompts.push(prompt);
1337
- await writeJson(PROMPTS_FILE, { prompts });
1338
- res.json({ success: true, prompt });
1339
- } catch (err) {
1340
- res.status(500).json({ success: false, error: err.message });
1341
- }
1342
- });
1343
-
1344
- app.delete('/api/workbench/prompts/:id', async (req, res) => {
1345
- try {
1346
- const data = await readJson(PROMPTS_FILE, { prompts: [] });
1347
- const prompts = (data.prompts || []).filter(p => p.id !== req.params.id);
1348
- await writeJson(PROMPTS_FILE, { prompts });
1349
- res.json({ success: true });
1350
- } catch (err) {
1351
- res.status(500).json({ success: false, error: err.message });
1352
- }
1353
- });
1354
-
1355
- // ── 任务 CRUD ───────────────────────────────────────────────────────
1356
- app.get('/api/workbench/tasks', async (_req, res) => {
1357
- try {
1358
- const data = await readJson(TASKS_FILE, { tasks: [] });
1359
- res.json({ success: true, tasks: data.tasks || [] });
1360
- } catch (err) {
1361
- res.status(500).json({ success: false, error: err.message });
1362
- }
1363
- });
1364
-
1365
- app.post('/api/workbench/tasks', async (req, res) => {
1366
- try {
1367
- const { id, title, desc, promptId, subtasks } = req.body || {};
1368
- if (!title) return res.status(400).json({ success: false, error: 'title 必填' });
1369
- const data = await readJson(TASKS_FILE, { tasks: [] });
1370
- const tasks = data.tasks || [];
1371
- const now = nowIso();
1372
- if (id) {
1373
- const i = tasks.findIndex(t => t.id === id);
1374
- if (i < 0) return res.status(404).json({ success: false, error: '任务不存在' });
1375
- tasks[i] = {
1376
- ...tasks[i],
1377
- title,
1378
- desc: desc || '',
1379
- promptId: promptId || null,
1380
- subtasks: Array.isArray(subtasks) ? subtasks.map(s => ({
1381
- id: s.id || genId(),
1382
- title: s.title || '',
1383
- desc: s.desc || '',
1384
- status: s.status || 'todo',
1385
- promptOverride: s.promptOverride || '',
1386
- // 保留附件元数据(仅保留基础字段,丢弃客户端临时字段)
1387
- attachments: Array.isArray(s.attachments) ? s.attachments.map(a => ({
1388
- id: a.id,
1389
- originalName: a.originalName,
1390
- mimeType: a.mimeType,
1391
- size: a.size,
1392
- ext: a.ext,
1393
- storedName: a.storedName,
1394
- absolutePath: a.absolutePath,
1395
- createdAt: a.createdAt
1396
- })) : (tasks[i].subtasks.find(x => x.id === s.id)?.attachments || [])
1397
- })) : tasks[i].subtasks,
1398
- updatedAt: now
1399
- };
1400
- await writeJson(TASKS_FILE, { tasks });
1401
- return res.json({ success: true, task: tasks[i] });
1402
- }
1403
- const task = {
1404
- id: genId(),
1405
- title,
1406
- desc: desc || '',
1407
- promptId: promptId || null,
1408
- subtasks: Array.isArray(subtasks) ? subtasks.map(s => ({
1409
- id: s.id || genId(),
1410
- title: s.title || '',
1411
- desc: s.desc || '',
1412
- status: s.status || 'todo',
1413
- promptOverride: s.promptOverride || '',
1414
- attachments: Array.isArray(s.attachments) ? s.attachments : []
1415
- })) : [],
1416
- status: 'todo',
1417
- createdAt: now,
1418
- updatedAt: now
1419
- };
1420
- tasks.push(task);
1421
- await writeJson(TASKS_FILE, { tasks });
1422
- res.json({ success: true, task });
1423
- } catch (err) {
1424
- res.status(500).json({ success: false, error: err.message });
1425
- }
1426
- });
1427
-
1428
- app.delete('/api/workbench/tasks/:id', async (req, res) => {
1429
- try {
1430
- const data = await readJson(TASKS_FILE, { tasks: [] });
1431
- const tasks = (data.tasks || []).filter(t => t.id !== req.params.id);
1432
- await writeJson(TASKS_FILE, { tasks });
1433
- res.json({ success: true });
1434
- } catch (err) {
1435
- res.status(500).json({ success: false, error: err.message });
1436
- }
1437
- });
1438
-
1439
- // ── 执行任务 ────────────────────────────────────────────────────────
1440
- app.post('/api/workbench/tasks/:id/run', async (req, res) => {
1441
- try {
1442
- const data = await readJson(TASKS_FILE, { tasks: [] });
1443
- const task = (data.tasks || []).find(t => t.id === req.params.id);
1444
- if (!task) return res.status(404).json({ success: false, error: '任务不存在' });
1445
- if (!task.subtasks || task.subtasks.length === 0) {
1446
- return res.status(400).json({ success: false, error: '任务没有子任务' });
1447
- }
1448
- const repoPath = typeof getCurrentProjectPath === 'function' ? getCurrentProjectPath() : '';
1449
- // 异步执行,立即返回
1450
- res.json({ success: true, message: '已开始执行' });
1451
- runTaskQueue(task, repoPath, '').catch(err => {
1452
- publish('task:error', { taskId: task.id, error: err.message });
1453
- });
1454
- } catch (err) {
1455
- res.status(500).json({ success: false, error: err.message });
1456
- }
1457
- });
1458
-
1459
- // ── 进程状态查询(兜底,SSE 断了也能拉) ────────────────────────────
1460
- app.get('/api/workbench/jobs', (_req, res) => {
1461
- res.json({ success: true, jobs: snapshotJobs() });
1462
- });
1463
-
1464
- // ── 取消正在执行的 job ───────────────────────────────────────────
1465
- // POST /api/workbench/jobs/:id/cancel
1466
- // 行为:
1467
- // - 找到正在运行的 job,调 child.kill() 终止 claude 进程
1468
- // - Windows 下用 taskkill /T /F 杀进程树(claude 进程可能 fork 出子进程)
1469
- // - 加入 cancelledJobs 集合,runTaskQueue 退出循环后会把 job 标为 'cancelled'
1470
- // - 只影响这一个 sub;同 task 后续 sub 仍按队列顺序继续执行
1471
- app.post('/api/workbench/jobs/:id/cancel', (req, res) => {
1472
- const job = jobs.get(req.params.id)
1473
- if (!job) {
1474
- return res.status(404).json({ success: false, error: 'job 不存在' })
1475
- }
1476
- if (job.status !== 'running' && job.status !== 'pending') {
1477
- return res.status(400).json({ success: false, error: `当前状态 ${job.status} 不可取消` })
1478
- }
1479
- cancelledJobs.add(job.id)
1480
- // 立即给前端一个状态反馈(不等 child 真正退出)
1481
- job.status = 'cancelled'
1482
- job.error = '用户已停止执行'
1483
- job.endedAt = nowIso()
1484
- publish('job:update', { ...job }) // 用浅拷贝避免序列化 child 引用
1485
- const child = job.child
1486
- if (!child) {
1487
- return res.json({ success: true, message: '已标记取消,进程将尽快结束' })
1488
- }
1489
- try {
1490
- if (process.platform === 'win32') {
1491
- // Windows: child.kill(SIGTERM) 经常无效,用 taskkill 杀进程树
1492
- execFile('taskkill', ['/PID', String(child.pid), '/T', '/F'], (err) => {
1493
- if (err) {
1494
- console.warn(`[workbench] taskkill ${child.pid} 失败:`, err.message)
1495
- }
1496
- })
1497
- } else {
1498
- child.kill('SIGTERM')
1499
- }
1500
- res.json({ success: true, message: '已发送停止信号' })
1501
- } catch (err) {
1502
- cancelledJobs.delete(job.id)
1503
- res.status(500).json({ success: false, error: '发送停止信号失败: ' + err.message })
1504
- }
1505
- });
1506
-
1507
- // ── 子任务附件:上传 / 删除 / 列表 ───────────────────────────────
1508
- // 上传:POST /api/workbench/subtasks/:subId/attachments
1509
- // header: X-Original-Name, X-Mime-Type
1510
- // body: raw binary
1511
- // 删除:DELETE /api/workbench/subtasks/:subId/attachments/:attId
1512
- // 列表:GET /api/workbench/subtasks/:subId/attachments
1513
- //
1514
- // 文件存到 ~/.zen-gitsync/workbench-images/{subId}/{attId}.{ext}
1515
- // 元数据(id / originalName / mime / size / storedName)通过 sub.attachments
1516
- // 跟随 tasks.json 一起持久化。
1517
- const rawAttachment = express.raw({
1518
- type: '*/*',
1519
- limit: MAX_IMAGE_BYTES * 4 // 整体路由上限 20MB;单文件大小由业务再卡
1520
- });
1521
-
1522
- // 共享 helper:找到一个 attachment 所在的位置(task 主附件 或 sub 附件)
1523
- // 返回 { owner, task, sub?, list, att, storageDir } 或 null
1524
- async function findAttachmentLocation(attId) {
1525
- const data = await readJson(TASKS_FILE, { tasks: [] });
1526
- for (const t of data.tasks || []) {
1527
- const list = Array.isArray(t.attachments) ? t.attachments : [];
1528
- const att = list.find(x => x.id === attId);
1529
- if (att) {
1530
- return { owner: 'task', task: t, list, att, storageDir: path.join(IMAGES_DIR, '_task-' + t.id) };
1531
- }
1532
- }
1533
- for (const t of data.tasks || []) {
1534
- for (const s of t.subtasks || []) {
1535
- const list = Array.isArray(s.attachments) ? s.attachments : [];
1536
- const att = list.find(x => x.id === attId);
1537
- if (att) {
1538
- return { owner: 'sub', task: t, sub: s, list, att, storageDir: path.join(IMAGES_DIR, s.id) };
1539
- }
1540
- }
1541
- }
1542
- return null;
1543
- }
1544
-
1545
- // 共享 helper:写入新附件(参数化以支持 task / sub)
1546
- async function writeAttachmentTo({ req, target, maxCount }) {
1547
- if (!req.body || !(req.body instanceof Buffer) || req.body.length === 0) {
1548
- return { error: '请求体为空', status: 400 };
1549
- }
1550
- if (req.body.length > MAX_IMAGE_BYTES) {
1551
- return { error: `单文件不得超过 ${MAX_IMAGE_BYTES / 1024 / 1024}MB`, status: 413 };
1552
- }
1553
- const originalName = String(req.get('X-Original-Name') || 'attachment').slice(0, 200);
1554
- const mimeType = String(req.get('X-Mime-Type') || 'application/octet-stream').slice(0, 120);
1555
- const ext = resolveExt({ originalName, mime: mimeType });
1556
- if (!ext) {
1557
- return { error: `不支持的文件类型(仅允许 ${[...ALLOWED_EXTS].join(', ')})`, status: 400 };
1558
- }
1559
- if (!Array.isArray(target.attachments)) target.attachments = [];
1560
- if (target.attachments.length >= maxCount) {
1561
- return { error: `附件已达上限 ${maxCount} 个`, status: 400 };
1562
- }
1563
-
1564
- const attId = genId();
1565
- await fsp.mkdir(target.storageDir, { recursive: true });
1566
- const storedName = `${attId}.${ext}`;
1567
- const storedPath = path.join(target.storageDir, storedName);
1568
- await fsp.writeFile(storedPath, req.body);
1569
-
1570
- const attachment = {
1571
- id: attId,
1572
- originalName,
1573
- mimeType,
1574
- size: req.body.length,
1575
- ext,
1576
- storedName,
1577
- absolutePath: storedPath,
1578
- createdAt: nowIso()
1579
- };
1580
- target.attachments.push(attachment);
1581
- target.updatedAt = nowIso();
1582
- return { attachment };
1583
- }
1584
-
1585
- // 子任务附件
1586
- app.post('/api/workbench/subtasks/:subId/attachments', rawAttachment, async (req, res) => {
1587
- try {
1588
- const { subId } = req.params;
1589
- const data = await readJson(TASKS_FILE, { tasks: [] });
1590
- let foundSub = null;
1591
- for (const t of data.tasks || []) {
1592
- const s = (t.subtasks || []).find(x => x.id === subId);
1593
- if (s) { foundSub = s; break; }
1594
- }
1595
- if (!foundSub) {
1596
- return res.status(404).json({ success: false, error: '子任务不存在' });
1597
- }
1598
- const target = { ...foundSub, storageDir: path.join(IMAGES_DIR, subId) };
1599
- const result = await writeAttachmentTo({ req, target, maxCount: MAX_ATTACHMENTS_PER_SUBTASK });
1600
- if (result.error) return res.status(result.status).json({ success: false, error: result.error });
1601
- // target 是 spread 出来的浅拷贝,data 引用里的 foundSub 没改;显式 push 回去
1602
- const att = result.attachment;
1603
- foundSub.attachments = Array.isArray(foundSub.attachments) ? foundSub.attachments : [];
1604
- foundSub.attachments.push(att);
1605
- foundSub.updatedAt = nowIso();
1606
- await writeJson(TASKS_FILE, data);
1607
- res.json({ success: true, attachment: att });
1608
- } catch (err) {
1609
- res.status(500).json({ success: false, error: err.message });
1610
- }
1611
- });
1612
-
1613
- app.delete('/api/workbench/subtasks/:subId/attachments/:attId', async (req, res) => {
1614
- try {
1615
- const { subId, attId } = req.params;
1616
- const data = await readJson(TASKS_FILE, { tasks: [] });
1617
- let foundSub = null;
1618
- for (const t of data.tasks || []) {
1619
- const s = (t.subtasks || []).find(x => x.id === subId);
1620
- if (s) { foundSub = s; break; }
1621
- }
1622
- if (!foundSub) return res.status(404).json({ success: false, error: '子任务不存在' });
1623
- const list = Array.isArray(foundSub.attachments) ? foundSub.attachments : [];
1624
- const i = list.findIndex(a => a.id === attId);
1625
- if (i < 0) return res.status(404).json({ success: false, error: '附件不存在' });
1626
- const [removed] = list.splice(i, 1);
1627
- try {
1628
- await fsp.unlink(path.join(IMAGES_DIR, subId, removed.storedName));
1629
- } catch { /* 文件可能已不存在 */ }
1630
- foundSub.updatedAt = nowIso();
1631
- await writeJson(TASKS_FILE, data);
1632
- res.json({ success: true });
1633
- } catch (err) {
1634
- res.status(500).json({ success: false, error: err.message });
1635
- }
1636
- });
1637
-
1638
- // 主任务附件
1639
- app.post('/api/workbench/tasks/:taskId/attachments', rawAttachment, async (req, res) => {
1640
- try {
1641
- const { taskId } = req.params;
1642
- const data = await readJson(TASKS_FILE, { tasks: [] });
1643
- const task = (data.tasks || []).find(t => t.id === taskId);
1644
- if (!task) return res.status(404).json({ success: false, error: '任务不存在' });
1645
- const target = { ...task, storageDir: path.join(IMAGES_DIR, '_task-' + taskId) };
1646
- const result = await writeAttachmentTo({ req, target, maxCount: MAX_ATTACHMENTS_PER_SUBTASK });
1647
- if (result.error) return res.status(result.status).json({ success: false, error: result.error });
1648
- const att = result.attachment;
1649
- task.attachments = Array.isArray(task.attachments) ? task.attachments : [];
1650
- task.attachments.push(att);
1651
- task.updatedAt = nowIso();
1652
- await writeJson(TASKS_FILE, data);
1653
- res.json({ success: true, attachment: att });
1654
- } catch (err) {
1655
- res.status(500).json({ success: false, error: err.message });
1656
- }
1657
- });
1658
-
1659
- app.delete('/api/workbench/tasks/:taskId/attachments/:attId', async (req, res) => {
1660
- try {
1661
- const { taskId, attId } = req.params;
1662
- const data = await readJson(TASKS_FILE, { tasks: [] });
1663
- const task = (data.tasks || []).find(t => t.id === taskId);
1664
- if (!task) return res.status(404).json({ success: false, error: '任务不存在' });
1665
- const list = Array.isArray(task.attachments) ? task.attachments : [];
1666
- const i = list.findIndex(a => a.id === attId);
1667
- if (i < 0) return res.status(404).json({ success: false, error: '附件不存在' });
1668
- const [removed] = list.splice(i, 1);
1669
- try {
1670
- await fsp.unlink(path.join(IMAGES_DIR, '_task-' + taskId, removed.storedName));
1671
- } catch { /* 文件可能已不存在 */ }
1672
- task.updatedAt = nowIso();
1673
- await writeJson(TASKS_FILE, data);
1674
- res.json({ success: true });
1675
- } catch (err) {
1676
- res.status(500).json({ success: false, error: err.message });
1677
- }
1678
- });
1679
-
1680
- // 附件原文件读取(前端 <img> 缩略图用)—— 支持 task 和 sub 两种归属
1681
- app.get('/api/workbench/attachments/:attId/raw', async (req, res) => {
1682
- try {
1683
- const { attId } = req.params;
1684
- const loc = await findAttachmentLocation(attId);
1685
- if (!loc) return res.status(404).json({ success: false, error: '附件不存在' });
1686
- const filePath = path.join(loc.storageDir, loc.att.storedName);
1687
- try {
1688
- const stat = await fsp.stat(filePath);
1689
- res.set('Content-Type', loc.att.mimeType || 'application/octet-stream');
1690
- res.set('Content-Length', String(stat.size));
1691
- res.set('Cache-Control', 'private, max-age=3600');
1692
- const stream = (await import('fs')).createReadStream(filePath);
1693
- stream.on('error', () => res.end());
1694
- stream.pipe(res);
1695
- } catch {
1696
- res.status(404).json({ success: false, error: '文件已丢失' });
1697
- }
1698
- } catch (err) {
1699
- res.status(500).json({ success: false, error: err.message });
1700
- }
1701
- });
1702
- }
1
+ // Copyright 2026 xz333221
2
+ //
3
+ // Licensed under the Apache License, Version 2.0 (the "License");
4
+ // you may not use this file except in compliance with the License.
5
+ // You may obtain a copy of the License at
6
+ //
7
+ // http://www.apache.org/licenses/LICENSE-2.0
8
+ //
9
+ // Unless required by applicable law or agreed to in writing, software
10
+ // distributed under the License is distributed on an "AS IS" BASIS,
11
+ // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
+ // See the License for the specific language governing permissions and
13
+ // limitations under the License.
14
+ //
15
+ // 工作台后端:管理预置提示词 / 任务 / 子任务,
16
+ // 并以 bypassPermissions 模式依次 spawn claude CLI 执行子任务(每次新窗口)。
17
+ // 数据存到用户主目录 ~/.zen-gitsync/,跨项目共享。
18
+
19
+ import fs from 'fs';
20
+ import fsp from 'fs/promises';
21
+ import path from 'path';
22
+ import os from 'os';
23
+ import { spawn, execFileSync, execFile } from 'child_process';
24
+ import { EventEmitter } from 'events';
25
+ import express from 'express';
26
+
27
+ const DATA_DIR = path.join(os.homedir(), '.zen-gitsync');
28
+ const PROMPTS_FILE = path.join(DATA_DIR, 'prompts.json');
29
+ const TASKS_FILE = path.join(DATA_DIR, 'tasks.json');
30
+ const IMAGES_DIR = path.join(DATA_DIR, 'workbench-images');
31
+ const INSTRUCTION_FILE = path.join(DATA_DIR, 'ai-instruction.json');
32
+ const SUBTASK_INSTRUCTION_FILE = path.join(DATA_DIR, 'ai-subtask-instruction.json');
33
+
34
+ // 子项目识别 / 文件扫描时需要跳过的目录
35
+ const SKIP_DIRS = new Set([
36
+ 'node_modules', 'dist', 'build', '.next', '.nuxt', '__pycache__',
37
+ 'target', 'out', 'coverage', 'vendor', '.git', '.svn', '.hg',
38
+ '.idea', '.vscode', '.gradle', '.terraform', '.cache', '.parcel-cache',
39
+ '.turbo', '.svelte-kit', 'storybook-static'
40
+ ]);
41
+
42
+ // 默认生成指令:用户首次使用时作为可编辑指令的初始值
43
+ const DEFAULT_INSTRUCTION = `你是一名资深软件架构师。
44
+
45
+ 【探索步骤】
46
+ 1. 先识别项目结构:扫描根目录是否包含 .git 目录,以及 package.json / pyproject.toml / go.mod / Cargo.toml / pom.xml / build.gradle{,.kts} / composer.json / Gemfile / pubspec.yaml 这 9 种 manifest。
47
+ 2. 如果根目录含 manifest,就把整个根目录视为一个子项目。
48
+ 3. 如果根目录不含 manifest、但子目录(含一层 .git 或上述 manifest)形成多个子项目,对每个子项目分别探索。
49
+ 4. 对每个子项目,重点读取:
50
+ - 所有识别到的 manifest(限制单文件 20KB)
51
+ - README.md(限制 8KB)
52
+ - 入口文件:package.json 的 main / scripts / workspaces 字段;pyproject.toml 的 [project.scripts];go.mod 的 module;Cargo.toml 的 [[bin]];pom.xml 的 <modules>
53
+ - 2 层目录树(最多 200 行)
54
+
55
+ 【输出要求】
56
+ 1. 给出一段 400-800 字的中文「项目架构说明」,覆盖:项目整体定位、技术栈、模块划分、核心流程、关键设计决策。
57
+ 2. 必须引用子项目里实际存在的文件路径、目录名、依赖名,不要编造。
58
+ 3. 多个子项目时:先逐个说明,最后输出一段「整体架构」总结它们之间的关系。
59
+ 4. 语气专业、具体、面向接手这个项目的开发者。
60
+ 5. 只返回 JSON:{ "name": "项目名(10-20字)", "summary": "架构说明正文" }。`;
61
+
62
+ // 单个附件最大 5MB;与 Anthropic Messages API 文档约束一致
63
+ const MAX_IMAGE_BYTES = 5 * 1024 * 1024;
64
+ // 一个子任务最多挂 9 个附件
65
+ const MAX_ATTACHMENTS_PER_SUBTASK = 9;
66
+
67
+ // AI 拆分子任务:默认系统指令(用户在 GUI 可编辑覆盖)。
68
+ // 国际化:根据请求 Accept-Language 在 zh / en 之间选默认。
69
+ // 中英两份都内置——用户保存到 ~/.zen-gitsync/ai-subtask-instruction.json 后覆盖。
70
+ const DEFAULT_SUBTASK_INSTRUCTION_ZH = `你是一名任务拆分助手。
71
+
72
+ 【思考过程】
73
+ 在给出 JSON 之前,请先在内部仔细思考(如果模型支持,把思考放在 reasoning 中;否则可以先输出一段简短分析,再输出 JSON):
74
+ - 任务的真实目标是什么?用户提供的描述/图片/上下文里有哪些关键信息?
75
+ - 涉及哪些技术栈、模块、文件、约束?是否有易被忽略的边界条件?
76
+ - 自然的执行顺序是什么?哪些步骤是前置依赖?哪些可以并行?
77
+ - 哪些步骤可能失败、需要单独验证?
78
+
79
+ 【拆分原则】
80
+ 1. 单一职责:每个子任务只做一件事,避免"做 A 和 B"。
81
+ 2. 粒度适中:单个子任务应当能在一次会话里完成(既不要"实现整个登录功能"这么大,也不要"打印 hello"这么琐碎)。
82
+ 3. 顺序合理:子任务按依赖关系和执行顺序排列(先准备、后实现、最后验证)。
83
+ 4. 可验证:每个子任务都有明确的完成标志("输出文件 xxx"、"通过测试 yyy"、"控制台打印 zzz")。
84
+ 5. 数量:拆成 3-6 个子任务为宜。任务很简单时 2-3 个;复杂时 5-6 个,不要超过 8 个。
85
+ 6. 描述具体:desc 字段要写清楚"要做什么、参考什么、产出什么",不要只是把 title 改写一遍。
86
+ 7. 如果任务里附带了图片,必须基于图片的实际内容拆分(例如指出图片中的哪个区域、哪个元素需要改),而不是泛泛而谈。
87
+
88
+ 【输出要求】
89
+ 最后必须输出 JSON,结构:
90
+ {
91
+ "subtasks": [
92
+ { "title": "子任务标题(10-20字)", "desc": "子任务的具体描述,包含要做什么、输入是什么、输出/验证标志是什么" }
93
+ ]
94
+ }
95
+
96
+ JSON 要用 \`\`\`json ... \`\`\` 代码块包裹,前面可以有分析文字,但 JSON 必须完整、合法、可解析。`;
97
+
98
+ const DEFAULT_SUBTASK_INSTRUCTION_EN = `You are a task breakdown assistant.
99
+
100
+ [Thinking process]
101
+ Before producing JSON, think carefully (put your thoughts in reasoning if the model supports it; otherwise output a short analysis first, then JSON):
102
+ - What is the real goal? What key information is in the description / images / context?
103
+ - Which stack, modules, files, constraints are involved? Any easily missed edge cases?
104
+ - What is the natural execution order? What blocks what? What can run in parallel?
105
+ - Which steps may fail and need separate verification?
106
+
107
+ [Breakdown principles]
108
+ 1. Single responsibility: each subtask does only one thing, avoid bundling "do A and B".
109
+ 2. Right granularity: a subtask should finish in one Claude session (not as big as "implement the whole login flow", not as trivial as "print hello").
110
+ 3. Sensible order: arrange subtasks by dependency / execution order (prepare first, implement, then verify).
111
+ 4. Verifiable: every subtask has a clear completion signal (e.g. "produce file xxx", "pass test yyy", "log zzz to console").
112
+ 5. Quantity: prefer 3-6 subtasks. Very simple tasks 2-3, complex ones 5-6, never exceed 8.
113
+ 6. Concrete desc: write what to do, what to reference, what to produce — don't just paraphrase the title.
114
+ 7. If the task includes images, the breakdown must reference the actual image content (which region, which element to change), not just generic talk.
115
+
116
+ [Output requirements]
117
+ End with JSON, structure:
118
+ {
119
+ "subtasks": [
120
+ { "title": "subtask title (10-20 chars)", "desc": "concrete description: what to do, what the input is, what the output / verification signal is" }
121
+ ]
122
+ }
123
+
124
+ Wrap the JSON in \`\`\`json ... \`\`\`. Analysis text before it is allowed, but the JSON must be complete and parseable.`;
125
+
126
+ // 兼容旧引用
127
+ const DEFAULT_SUBTASK_INSTRUCTION = DEFAULT_SUBTASK_INSTRUCTION_ZH
128
+
129
+ // 根据请求 Accept-Language 选默认(zh / en)
130
+ function pickDefaultSubtaskInstruction(req) {
131
+ const al = String(req?.headers?.['accept-language'] || '').toLowerCase()
132
+ if (al.startsWith('en')) return DEFAULT_SUBTASK_INSTRUCTION_EN
133
+ return DEFAULT_SUBTASK_INSTRUCTION_ZH
134
+ }
135
+ // 白名单后缀:图片 + 常见文档(PDF / 纯文本 / Markdown)
136
+ const IMAGE_EXTS = new Set(['png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'svg']);
137
+ const DOC_EXTS = new Set(['pdf', 'txt', 'md', 'markdown', 'csv', 'json', 'log']);
138
+ const ALLOWED_EXTS = new Set([...IMAGE_EXTS, ...DOC_EXTS]);
139
+
140
+ // mime → 文件后缀;与前端 el-upload accept 对齐
141
+ const MIME_TO_EXT = {
142
+ 'image/png': 'png',
143
+ 'image/jpeg': 'jpg',
144
+ 'image/jpg': 'jpg',
145
+ 'image/gif': 'gif',
146
+ 'image/webp': 'webp',
147
+ 'image/bmp': 'bmp',
148
+ 'image/svg+xml': 'svg',
149
+ 'image/x-icon': 'ico',
150
+ 'image/vnd.microsoft.icon': 'ico',
151
+ 'application/pdf': 'pdf',
152
+ 'text/plain': 'txt',
153
+ 'text/markdown': 'md',
154
+ 'text/x-markdown': 'md',
155
+ 'text/csv': 'csv',
156
+ 'application/json': 'json',
157
+ 'text/json': 'json',
158
+ 'text/x-log': 'log',
159
+ };
160
+
161
+ function sanitizeExt(name, fallback = 'bin') {
162
+ if (typeof name !== 'string') return fallback;
163
+ const m = name.toLowerCase().match(/\.([a-z0-9]+)$/);
164
+ if (!m) return fallback;
165
+ return ALLOWED_EXTS.has(m[1]) ? m[1] : fallback;
166
+ }
167
+
168
+ function isImageExt(ext) {
169
+ return IMAGE_EXTS.has(String(ext || '').toLowerCase());
170
+ }
171
+
172
+ async function ensureImagesDir() {
173
+ await fsp.mkdir(IMAGES_DIR, { recursive: true });
174
+ }
175
+
176
+ // 把 mime 或文件名规范成统一后缀;遇到不在白名单的情况返回 null
177
+ function resolveExt({ originalName, mime }) {
178
+ if (mime && MIME_TO_EXT[mime.toLowerCase()]) {
179
+ return MIME_TO_EXT[mime.toLowerCase()];
180
+ }
181
+ const fromName = sanitizeExt(originalName, '');
182
+ if (fromName) return fromName;
183
+ return null;
184
+ }
185
+
186
+ // 解析 manifest 文件名(按优先级)
187
+ const MANIFEST_FILES = [
188
+ 'package.json', 'pyproject.toml', 'go.mod', 'Cargo.toml',
189
+ 'pom.xml', 'build.gradle', 'build.gradle.kts', 'composer.json',
190
+ 'Gemfile', 'pubspec.yaml'
191
+ ];
192
+
193
+ // 轻量级:仅告诉 LLM 项目的主 manifest 是什么(用于 AI 拆分时让 LLM 知道项目类型)。
194
+ // 不读内容,只 stat 存在性——拆分子任务不需要细节。
195
+ async function detectProjectManifest(projectPath) {
196
+ if (!projectPath) return ''
197
+ for (const f of MANIFEST_FILES) {
198
+ try {
199
+ const stat = await fsp.stat(path.join(projectPath, f))
200
+ if (stat.isFile()) return f
201
+ } catch { /* 不存在,继续 */ }
202
+ }
203
+ return ''
204
+ }
205
+
206
+ async function readProjectManifest(projectPath) {
207
+ const out = {};
208
+ for (const f of MANIFEST_FILES) {
209
+ const p = path.join(projectPath, f);
210
+ try {
211
+ const stat = await fsp.stat(p);
212
+ if (!stat.isFile()) continue;
213
+ // 限制大小,避免巨型 pom.xml 把上下文打爆
214
+ const content = stat.size > 20000
215
+ ? (await safeReadFile(p, 20000))
216
+ : (await fsp.readFile(p, 'utf8'));
217
+ out[f] = content;
218
+ } catch { /* 不存在就跳过 */ }
219
+ }
220
+ return out;
221
+ }
222
+
223
+ async function safeReadFile(filePath, maxBytes = 200000) {
224
+ try {
225
+ const stat = await fsp.stat(filePath);
226
+ if (stat.size > maxBytes) {
227
+ const buf = Buffer.alloc(maxBytes);
228
+ const fd = await fsp.open(filePath, 'r');
229
+ await fd.read(buf, 0, maxBytes, 0);
230
+ await fd.close();
231
+ return buf.toString('utf8').slice(0, maxBytes);
232
+ }
233
+ return await fsp.readFile(filePath, 'utf8');
234
+ } catch {
235
+ return '';
236
+ }
237
+ }
238
+
239
+ async function listDirTree(projectPath, maxDepth = 2, maxEntries = 400) {
240
+ const lines = [];
241
+ async function walk(dir, depth) {
242
+ if (depth > maxDepth || lines.length >= maxEntries) return;
243
+ let entries;
244
+ try { entries = await fsp.readdir(dir, { withFileTypes: true }); }
245
+ catch { return; }
246
+ const filtered = entries.filter(e => {
247
+ if (e.name.startsWith('.')) return false;
248
+ if (['node_modules', 'dist', 'build', '.next', '.nuxt', '__pycache__', 'target', 'out', 'coverage', 'vendor'].includes(e.name)) return false;
249
+ return true;
250
+ });
251
+ const indent = ' '.repeat(depth);
252
+ for (const e of filtered) {
253
+ if (lines.length >= maxEntries) return;
254
+ if (e.isDirectory()) {
255
+ lines.push(`${indent}${e.name}/`);
256
+ await walk(path.join(dir, e.name), depth + 1);
257
+ } else if (e.isFile()) {
258
+ lines.push(`${indent}${e.name}`);
259
+ }
260
+ }
261
+ }
262
+ await walk(projectPath, 0);
263
+ return lines.join('\n');
264
+ }
265
+
266
+ async function callLlmJson(model, prompt, opts = {}) {
267
+ const { maxTokens = 1500, timeoutMs = 60000, images = [] } = opts;
268
+ const { default: fetch } = await import('node-fetch').catch(() => ({ default: globalThis.fetch }));
269
+ const url = `${String(model.baseURL || '').replace(/\/$/, '')}/chat/completions`;
270
+ const headers = { 'Content-Type': 'application/json' };
271
+ if (model.apiKey) headers['Authorization'] = `Bearer ${model.apiKey}`;
272
+
273
+ // 有图片时改用 OpenAI multimodal content 数组(text + image_url)。
274
+ // 非多模态模型遇到 image_url 会忽略图片块,相当于退化成纯文本,不会报错。
275
+ let userContent;
276
+ if (Array.isArray(images) && images.length > 0) {
277
+ userContent = [
278
+ { type: 'text', text: prompt },
279
+ ...images.map(img => ({ type: 'image_url', image_url: { url: img } }))
280
+ ];
281
+ } else {
282
+ userContent = prompt;
283
+ }
284
+
285
+ const body = JSON.stringify({
286
+ model: model.model,
287
+ messages: [{ role: 'user', content: userContent }],
288
+ max_tokens: maxTokens,
289
+ temperature: 0.4,
290
+ response_format: { type: 'json_object' },
291
+ stream: false,
292
+ });
293
+
294
+ const controller = new AbortController();
295
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
296
+ try {
297
+ const resp = await fetch(url, { method: 'POST', headers, body, signal: controller.signal });
298
+ const data = await resp.json().catch(() => ({}));
299
+ if (!resp.ok) throw new Error(data?.error?.message || `HTTP ${resp.status}`);
300
+ const content = data?.choices?.[0]?.message?.content || '{}';
301
+ try {
302
+ const m = content.match(/```json\s*([\s\S]*?)```/) || content.match(/({[\s\S]*})/);
303
+ return JSON.parse(m ? m[1] : content);
304
+ } catch {
305
+ return {};
306
+ }
307
+ } finally {
308
+ clearTimeout(timer);
309
+ }
310
+ }
311
+
312
+ /**
313
+ * 流式调用 OpenAI 兼容 LLM。每收到一个 chunk 调 onDelta 回调。
314
+ * onDelta 接收 { thinking?: string, content?: string },二选一。
315
+ * - reasoning_content / reasoning:部分模型(如 deepseek)放在 delta.reasoning_content
316
+ * - reasoning / reasoning_text:openai o1 风格
317
+ * - content:普通输出
318
+ * 返回完整 content 字符串。
319
+ */
320
+ async function callLlmStream(model, prompt, onDelta, opts = {}) {
321
+ const { maxTokens = 2000, timeoutMs = 600000, signal, images = [] } = opts
322
+ const { default: fetch } = await import('node-fetch').catch(() => ({ default: globalThis.fetch }))
323
+ const url = `${String(model.baseURL || '').replace(/\/$/, '')}/chat/completions`
324
+ const headers = { 'Content-Type': 'application/json' }
325
+ if (model.apiKey) headers['Authorization'] = `Bearer ${model.apiKey}`
326
+
327
+ let userContent
328
+ if (Array.isArray(images) && images.length > 0) {
329
+ userContent = [
330
+ { type: 'text', text: prompt },
331
+ ...images.map(img => ({ type: 'image_url', image_url: { url: img } }))
332
+ ]
333
+ } else {
334
+ userContent = prompt
335
+ }
336
+
337
+ const body = JSON.stringify({
338
+ model: model.model,
339
+ messages: [{ role: 'user', content: userContent }],
340
+ max_tokens: maxTokens,
341
+ temperature: 0.4,
342
+ // 注意:stream: true 模式下不能同时使用 response_format:{type:'json_object'},
343
+ // 部分 provider 会在收到两个一起时报错/静默卡住。改在 prompt 里约束 JSON 输出即可。
344
+ stream: true,
345
+ })
346
+
347
+ const controller = new AbortController()
348
+ const timer = setTimeout(() => controller.abort(), timeoutMs)
349
+ // 允许外部 signal 触发取消(用户在 GUI 点停止)
350
+ const onAbort = () => controller.abort()
351
+ if (signal) {
352
+ if (signal.aborted) controller.abort()
353
+ else signal.addEventListener('abort', onAbort)
354
+ }
355
+
356
+ let fullContent = ''
357
+ let aborted = false
358
+ try {
359
+ const resp = await fetch(url, { method: 'POST', headers, body, signal: controller.signal })
360
+ if (!resp.ok || !resp.body) {
361
+ const errText = await resp.text().catch(() => '')
362
+ throw new Error(errText || `HTTP ${resp.status}`)
363
+ }
364
+
365
+ // SSE 格式:每行 "data: {...}",最后 "data: [DONE]"
366
+ const decoder = new TextDecoder('utf-8')
367
+ let buf = ''
368
+ for await (const chunk of resp.body) {
369
+ buf += decoder.decode(chunk, { stream: true })
370
+ const lines = buf.split('\n')
371
+ buf = lines.pop() ?? ''
372
+ for (const line of lines) {
373
+ const trimmed = line.trim()
374
+ if (!trimmed || !trimmed.startsWith('data:')) continue
375
+ const payload = trimmed.slice(5).trim()
376
+ if (payload === '[DONE]') continue
377
+ try {
378
+ const evt = JSON.parse(payload)
379
+ const delta = evt.choices?.[0]?.delta || {}
380
+ // thinking 在不同 provider 字段名不同,全部尝试
381
+ const thinkingChunk = delta.reasoning_content
382
+ || delta.reasoning
383
+ || delta.reasoning_text
384
+ || ''
385
+ const contentChunk = delta.content || ''
386
+ if (thinkingChunk) onDelta({ thinking: thinkingChunk })
387
+ if (contentChunk) {
388
+ fullContent += contentChunk
389
+ onDelta({ content: contentChunk })
390
+ }
391
+ } catch { /* 跳过无法解析的行 */ }
392
+ }
393
+ }
394
+ } catch (err) {
395
+ if (err?.name === 'AbortError' || controller.signal.aborted) {
396
+ aborted = true
397
+ // 中断不算错误——上层会决定怎么处理
398
+ } else {
399
+ throw err
400
+ }
401
+ } finally {
402
+ clearTimeout(timer)
403
+ if (signal) signal.removeEventListener('abort', onAbort)
404
+ }
405
+ return { content: fullContent, aborted }
406
+ }
407
+
408
+ function nowIso() {
409
+ return new Date().toISOString();
410
+ }
411
+
412
+ function genId() {
413
+ return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
414
+ }
415
+
416
+ async function ensureDataDir() {
417
+ await fsp.mkdir(DATA_DIR, { recursive: true });
418
+ }
419
+
420
+ async function readJson(file, fallback) {
421
+ try {
422
+ const buf = await fsp.readFile(file, 'utf-8');
423
+ return JSON.parse(buf);
424
+ } catch (err) {
425
+ if (err && err.code === 'ENOENT') return fallback;
426
+ throw err;
427
+ }
428
+ }
429
+
430
+ async function writeJson(file, data) {
431
+ await ensureDataDir();
432
+ const tmp = `${file}.tmp`;
433
+ await fsp.writeFile(tmp, JSON.stringify(data, null, 2), 'utf-8');
434
+ await fsp.rename(tmp, file);
435
+ }
436
+
437
+ // 简单的 Mustache 风格变量插值:{{task.title}} / {{task.desc}} / {{repo.path}} / {{branch}}
438
+ function interpolate(template, ctx) {
439
+ if (typeof template !== 'string') return template;
440
+ return template.replace(/\{\{\s*([\w.]+)\s*\}\}/g, (_, key) => {
441
+ const parts = key.split('.');
442
+ let cur = ctx;
443
+ for (const p of parts) {
444
+ if (cur == null) return '';
445
+ cur = cur[p];
446
+ }
447
+ return cur == null ? '' : String(cur);
448
+ });
449
+ }
450
+
451
+ // ── 进程表:记录每个子任务的运行状态 ──────────────────────────────────────
452
+ const bus = new EventEmitter();
453
+ const jobs = new Map(); // jobId -> { id, taskId, subId, status, pid, startedAt, endedAt, exitCode, error, prompt }
454
+ // 被用户主动取消的 jobId 集合——runTaskQueue 在 waitProcessExit 之后检查这个集合
455
+ // 来决定把 job 标为 'cancelled' 还是 'done'。
456
+ // 用 Set 而不是 job.cancelled 标志,是为了在 SIGTERM 发出后到 child 真正退出之间
457
+ // 有一个简洁的"待回收"窗口。
458
+ const cancelledJobs = new Set();
459
+
460
+ // ── 生成指令持久化(~/.zen-gitsync/ai-instruction.json) ────────────────────
461
+ async function readInstruction() {
462
+ try {
463
+ const buf = await fsp.readFile(INSTRUCTION_FILE, 'utf-8');
464
+ const obj = JSON.parse(buf);
465
+ if (obj && typeof obj.instruction === 'string' && obj.instruction.trim()) {
466
+ return obj.instruction;
467
+ }
468
+ } catch { /* 文件不存在或解析失败 */ }
469
+ return DEFAULT_INSTRUCTION;
470
+ }
471
+
472
+ async function writeInstruction(instruction) {
473
+ await ensureDataDir();
474
+ const text = String(instruction || '').trim() || DEFAULT_INSTRUCTION;
475
+ const tmp = `${INSTRUCTION_FILE}.tmp`;
476
+ await fsp.writeFile(tmp, JSON.stringify({ instruction: text, updatedAt: nowIso() }, null, 2), 'utf-8');
477
+ await fsp.rename(tmp, INSTRUCTION_FILE);
478
+ }
479
+
480
+ // AI 拆分子任务的指令:与生成项目架构说明的指令分开持久化,
481
+ // 因为它面向的输出形态(subtask 列表)和任务粒度完全不同。
482
+ // 支持传入 req:根据 Accept-Language 选默认(zh/en)
483
+ async function readSubtaskInstruction(req) {
484
+ try {
485
+ const buf = await fsp.readFile(SUBTASK_INSTRUCTION_FILE, 'utf-8');
486
+ const obj = JSON.parse(buf);
487
+ if (obj && typeof obj.instruction === 'string' && obj.instruction.trim()) {
488
+ return obj.instruction;
489
+ }
490
+ } catch { /* 文件不存在或解析失败 */ }
491
+ return pickDefaultSubtaskInstruction(req);
492
+ }
493
+ async function writeSubtaskInstruction(instruction) {
494
+ await ensureDataDir();
495
+ // 写入时如果与当前 locale 默认一致,不写文件——这样前端"isDefault"判定永远准确
496
+ const text = String(instruction || '').trim() || DEFAULT_SUBTASK_INSTRUCTION_ZH;
497
+ const tmp = `${SUBTASK_INSTRUCTION_FILE}.tmp`;
498
+ await fsp.writeFile(tmp, JSON.stringify({ instruction: text, updatedAt: nowIso() }, null, 2), 'utf-8');
499
+ await fsp.rename(tmp, SUBTASK_INSTRUCTION_FILE);
500
+ }
501
+
502
+ // ── 子项目识别:递归找 .git / manifest;A 是 B 的祖先时只保留 B ─────────────
503
+ async function findSubProjects(projectPath, opts = {}) {
504
+ const { maxDepth = 4 } = opts;
505
+ const candidates = [];
506
+
507
+ async function walk(dir, depth) {
508
+ if (depth > maxDepth) return;
509
+ let entries;
510
+ try { entries = await fsp.readdir(dir, { withFileTypes: true }); }
511
+ catch { return; }
512
+
513
+ let hasManifest = false;
514
+ let hasGit = false;
515
+ const subDirs = [];
516
+ for (const e of entries) {
517
+ if (!e.isDirectory() && !e.isFile()) continue;
518
+ if (e.name.startsWith('.')) {
519
+ if (e.name === '.git' && e.isDirectory()) hasGit = true;
520
+ continue;
521
+ }
522
+ if (e.isDirectory()) {
523
+ if (SKIP_DIRS.has(e.name)) continue;
524
+ subDirs.push(path.join(dir, e.name));
525
+ } else if (e.isFile() && MANIFEST_FILES.includes(e.name)) {
526
+ hasManifest = true;
527
+ }
528
+ }
529
+ if (hasManifest || hasGit) {
530
+ candidates.push(dir);
531
+ return; // 子目录里若还有 manifest,会被自己发现;这里不再下钻避免冗余
532
+ }
533
+ if (depth >= maxDepth) return;
534
+ for (const sub of subDirs) {
535
+ await walk(sub, depth + 1);
536
+ }
537
+ }
538
+
539
+ await walk(projectPath, 0);
540
+
541
+ // 去重:若 candidates 里 A 是 B 的祖先,只保留更深一级的 B
542
+ candidates.sort((a, b) => a.length - b.length);
543
+ const kept = [];
544
+ for (const c of candidates) {
545
+ let dominated = false;
546
+ for (const k of kept) {
547
+ if (c === k || c.startsWith(k + path.sep)) { dominated = true; break; }
548
+ }
549
+ if (!dominated) kept.push(c);
550
+ }
551
+
552
+ // 收集每个子项目的关键文件
553
+ const result = [];
554
+ for (const root of kept) {
555
+ const manifests = {};
556
+ for (const m of MANIFEST_FILES) {
557
+ const p = path.join(root, m);
558
+ try {
559
+ const stat = await fsp.stat(p);
560
+ if (stat.isFile()) {
561
+ manifests[m] = stat.size > 20000
562
+ ? await safeReadFile(p, 20000)
563
+ : await fsp.readFile(p, 'utf8');
564
+ }
565
+ } catch { /* 不存在就跳过 */ }
566
+ }
567
+ let readme = '';
568
+ try {
569
+ const stat = await fsp.stat(path.join(root, 'README.md'));
570
+ if (stat.isFile()) readme = await safeReadFile(path.join(root, 'README.md'), 8000);
571
+ } catch { /* 不存在就跳过 */ }
572
+ const dirTree = await listDirTree(root, 2, 200);
573
+ result.push({
574
+ root,
575
+ name: path.basename(root) || path.basename(projectPath),
576
+ manifests,
577
+ readme,
578
+ dirTree
579
+ });
580
+ }
581
+ return result;
582
+ }
583
+
584
+ function publish(event, payload) {
585
+ bus.emit('event', { event, payload, ts: nowIso() });
586
+ }
587
+
588
+ function snapshotJobs() {
589
+ return Array.from(jobs.values()).map(j => ({
590
+ id: j.id,
591
+ taskId: j.taskId,
592
+ subId: j.subId,
593
+ title: j.title,
594
+ status: j.status,
595
+ prompt: j.prompt || '',
596
+ output: j.output || '',
597
+ pid: j.pid || null,
598
+ startedAt: j.startedAt || null,
599
+ endedAt: j.endedAt || null,
600
+ exitCode: typeof j.exitCode === 'number' ? j.exitCode : null,
601
+ error: j.error || null
602
+ }));
603
+ }
604
+
605
+ // 用 detached 进程跑 claude;进程退出时回填状态。
606
+ // 返回 { pid, child }:调用方可以监听 child.stdout/stderr 实时收集输出。
607
+ // 不再走 cmd /k 弹窗——claude -p 是非交互模式,输出通过 stdout pipe 实时回传
608
+ // 到前端面板展示。
609
+ function launchClaudeInNewWindow(cwd, promptText) {
610
+ return new Promise((resolve, reject) => {
611
+ const args = [
612
+ '-p', promptText,
613
+ '--input-format', 'text',
614
+ '--output-format', 'stream-json',
615
+ '--verbose',
616
+ '--permission-mode', 'bypassPermissions',
617
+ '--dangerously-skip-permissions'
618
+ ];
619
+ let child;
620
+ let spawnedExe = 'claude';
621
+ if (process.platform === 'win32') {
622
+ // 直接 spawn claude.exe(npm 全局 @anthropic-ai/claude-code 里的真实二进制),
623
+ // 避开两件事:
624
+ // 1. Node 23 在 Windows 上拒绝 spawn .cmd/.bat(EINVAL)
625
+ // 2. shell:true 会把 argv 拼成命令行交给 cmd 解释,prompt 里的 \n 被切成多段
626
+ // 用 `where claude` 找到 claude.cmd,再从 cmd 内容推断对应 .exe 路径。
627
+ let claudeExe = 'claude.exe';
628
+ try {
629
+ const cmdShim = execFileSync('where', ['claude'], { encoding: 'utf8' })
630
+ .split(/\r?\n/).map(s => s.trim()).find(s => /\.cmd$/i.test(s));
631
+ if (cmdShim) {
632
+ const txt = fs.readFileSync(cmdShim, 'utf8');
633
+ if (/%dp0%\\node_modules\\@anthropic-ai\\claude-code\\bin\\claude\.exe/i.test(txt)) {
634
+ claudeExe = path.join(path.dirname(cmdShim), 'node_modules', '@anthropic-ai', 'claude-code', 'bin', 'claude.exe');
635
+ }
636
+ }
637
+ } catch { /* fallback */ }
638
+ spawnedExe = claudeExe;
639
+ child = spawn(claudeExe, args, {
640
+ cwd,
641
+ stdio: ['ignore', 'pipe', 'pipe'],
642
+ windowsHide: false,
643
+ env: { ...process.env, LANG: 'zh_CN.UTF-8' }
644
+ });
645
+ } else {
646
+ // macOS / Linux:直接 spawn claude(Node spawn 不走 shell,
647
+ // prompt 中的引号 / 反斜杠无需手动 escape)
648
+ child = spawn('claude', args, {
649
+ cwd,
650
+ detached: true,
651
+ stdio: ['ignore', 'pipe', 'pipe'],
652
+ env: { ...process.env, LANG: 'zh_CN.UTF-8' }
653
+ });
654
+ }
655
+ child.on('error', reject);
656
+ child.on('spawn', () => {
657
+ // unref 让 claude 独立于父进程事件循环;返回 child 引用让调用方继续读 stdout。
658
+ child.unref();
659
+ resolve({ pid: child.pid, child });
660
+ });
661
+ });
662
+ }
663
+
664
+ // 顺序执行一个任务下所有子任务;上一个结束再启动下一个
665
+ async function runTaskQueue(task, repoPath, branch) {
666
+ // 前序上下文:跑完一个 sub 后把它"完成态"摘要存到这里,下一个 sub 启动时
667
+ // 拼到 prompt 头部,让 Claude 知道前面做了什么、产出了什么。
668
+ // 故意不用 raw output 全文——LLM 已经习惯"摘要 + 关键结论"的格式,且不会
669
+ // 一次塞几 MB 进 prompt 烧 token。truncate 到每条 MAX_PREV_OUTPUT_CHARS。
670
+ const MAX_PREV_OUTPUT_CHARS = 2000
671
+ const priorOutputs = []
672
+ for (const sub of task.subtasks) {
673
+ if (sub.status === 'done') continue;
674
+ const promptTemplate = sub.promptOverride || (task.promptId
675
+ ? (await readJson(PROMPTS_FILE, { prompts: [] })).prompts.find(p => p.id === task.promptId)?.content
676
+ : null) || '';
677
+ const ctx = {
678
+ task: { title: task.title, desc: task.desc || '' },
679
+ sub: { title: sub.title, desc: sub.desc || '' },
680
+ repo: { path: repoPath || '' },
681
+ branch: branch || ''
682
+ };
683
+ const interpolated = interpolate(promptTemplate, ctx);
684
+ const parts = [interpolated, sub.title, sub.desc].filter(s => s && s.trim());
685
+ let prompt = parts.join('\n\n');
686
+
687
+ // ── 前序上下文:把前几个 done 子任务的输出摘要拼到 prompt 头部 ──
688
+ if (priorOutputs.length > 0) {
689
+ const prevBlock = priorOutputs.map((p, i) => {
690
+ const text = (p.output || '').slice(0, MAX_PREV_OUTPUT_CHARS)
691
+ const truncated = (p.output || '').length > MAX_PREV_OUTPUT_CHARS ? '\n…(前文已截断)' : ''
692
+ return `### [${i + 1}] ${p.title}\n${text}${truncated}`
693
+ }).join('\n\n')
694
+ prompt = `以下是同一任务下已经完成的前序子任务输出(仅作上下文参考,请基于这些结论继续当前子任务,无需重复执行它们):
695
+
696
+ ${prevBlock}
697
+
698
+ ---
699
+
700
+ ${prompt}`
701
+ }
702
+
703
+ // ── 附件:合并 sub.attachments + task.attachments 后拼到 prompt 末尾 ──
704
+ // claude -p 字符串模式会扫描 prompt 中出现的本地文件路径并自动
705
+ // 识别为附件(图片 / PDF / 文本均可)。
706
+ // 主任务附件对所有 sub 都可见;子任务自己的附件只对该 sub 可见。
707
+ const allAttachments = [
708
+ ...(Array.isArray(task.attachments) ? task.attachments : []),
709
+ ...(Array.isArray(sub.attachments) ? sub.attachments : [])
710
+ ];
711
+ if (allAttachments.length > 0) {
712
+ const lines = allAttachments
713
+ .filter(a => a && a.absolutePath)
714
+ .map((a, i) => ` ${i + 1}. [${a.mimeType || 'application/octet-stream'}] ${a.absolutePath}`);
715
+ if (lines.length > 0) {
716
+ prompt += `\n\n---\n本任务包含 ${lines.length} 个附件(请按文件路径读取,不要让用户重新提供):\n${lines.join('\n')}\n---`;
717
+ }
718
+ }
719
+
720
+ const jobId = genId();
721
+ const job = {
722
+ id: jobId,
723
+ taskId: task.id,
724
+ subId: sub.id,
725
+ title: `${task.title} / ${sub.title}`,
726
+ status: 'pending',
727
+ prompt
728
+ };
729
+ jobs.set(jobId, job);
730
+ sub.status = 'running';
731
+ publish('sub:update', { taskId: task.id, sub });
732
+ publish('job:update', job);
733
+
734
+ try {
735
+ const { pid, child } = await launchClaudeInNewWindow(repoPath || process.cwd(), prompt);
736
+ job.pid = pid;
737
+ // 保存 child 引用,供 cancel 接口调用 kill
738
+ job.child = child;
739
+ job.startedAt = nowIso();
740
+ job.status = 'running';
741
+ publish('job:update', job);
742
+
743
+ // 流式 NDJSON 解析:把 stdout 当作 stream-json 协议处理
744
+ // assistant.text → job.output (用户主要关心的内容)
745
+ // assistant.thinking → job.thinking (折叠展示,让用户知道 Claude 在想)
746
+ // 其他事件(init / tool_use / result 等)忽略,避免噪声
747
+ // 解析失败的行原样进 output,便于排查协议异常。
748
+ // 过长时(>256KB)只截断尾部 256KB,避免内存膨胀。
749
+ const MAX_OUTPUT = 256 * 1024;
750
+ const MAX_THINKING = 64 * 1024;
751
+ job.output = '';
752
+ job.thinking = '';
753
+ const lineBuf = { stdout: '', stderr: '' };
754
+
755
+ const parseLines = (channel, buf) => {
756
+ const chunk = buf.toString('utf8');
757
+ lineBuf[channel] += chunk;
758
+ const lines = lineBuf[channel].split('\n');
759
+ lineBuf[channel] = lines.pop() ?? ''; // 最后一段可能不完整,留给下次
760
+ for (const line of lines) {
761
+ const trimmed = line.trim();
762
+ if (!trimmed) continue;
763
+ if (channel === 'stderr' || !trimmed.startsWith('{')) {
764
+ // 非 stream-json 行:原样塞进 output(兼容老版本 claude / 错误信息)
765
+ job.output = (job.output + trimmed + '\n').slice(-MAX_OUTPUT);
766
+ continue;
767
+ }
768
+ let evt;
769
+ try { evt = JSON.parse(trimmed) } catch { continue }
770
+ if (evt.type !== 'assistant') continue;
771
+ const blocks = evt.message?.content;
772
+ if (!Array.isArray(blocks)) continue;
773
+ for (const b of blocks) {
774
+ if (b.type === 'text' && typeof b.text === 'string') {
775
+ job.output = (job.output + b.text).slice(-MAX_OUTPUT);
776
+ } else if (b.type === 'thinking' && typeof b.thinking === 'string') {
777
+ job.thinking = (job.thinking + b.thinking).slice(-MAX_THINKING);
778
+ }
779
+ }
780
+ }
781
+ publish('job:update', job);
782
+ };
783
+ if (child.stdout) child.stdout.on('data', (buf) => parseLines('stdout', buf));
784
+ if (child.stderr) child.stderr.on('data', (buf) => parseLines('stderr', buf));
785
+
786
+ // 等待进程退出(detached 不阻塞主进程,用 polling /proc 兜底)
787
+ await waitProcessExit(pid);
788
+ const wasCancelled = cancelledJobs.has(jobId)
789
+ if (wasCancelled) cancelledJobs.delete(jobId)
790
+ // 进程退出时 stdout 可能残留最后一段未换行的 NDJSON,flush 一次
791
+ if (lineBuf.stdout.trim()) {
792
+ try {
793
+ const evt = JSON.parse(lineBuf.stdout.trim())
794
+ if (evt.type === 'assistant' && Array.isArray(evt.message?.content)) {
795
+ for (const b of evt.message.content) {
796
+ if (b.type === 'text' && typeof b.text === 'string') {
797
+ job.output = (job.output + b.text).slice(-MAX_OUTPUT)
798
+ } else if (b.type === 'thinking' && typeof b.thinking === 'string') {
799
+ job.thinking = (job.thinking + b.thinking).slice(-MAX_THINKING)
800
+ }
801
+ }
802
+ }
803
+ } catch { /* 不是 JSON,忽略 */ }
804
+ }
805
+ job.endedAt = nowIso();
806
+ if (wasCancelled) {
807
+ job.exitCode = 130; // 128 + SIGINT(2),约定俗成的"用户取消"退出码
808
+ job.status = 'cancelled';
809
+ job.error = '用户已停止执行';
810
+ // sub 不改状态——cancelled 是 job 维度,同 task 后续 sub 仍可继续执行
811
+ } else {
812
+ job.exitCode = 0;
813
+ job.status = 'done';
814
+ sub.status = 'done';
815
+ // 把这个 sub 的输出累积到前序上下文,喂给下一个 sub
816
+ priorOutputs.push({ title: sub.title, output: job.output || '' })
817
+ }
818
+ } catch (err) {
819
+ job.error = err && err.message ? err.message : String(err);
820
+ job.status = 'error';
821
+ sub.status = 'error';
822
+ } finally {
823
+ // 移除 child 引用——避免后续被 SSE 序列化到前端
824
+ delete job.child
825
+ publish('job:update', job);
826
+ publish('sub:update', { taskId: task.id, sub });
827
+ }
828
+ }
829
+ // 写回 tasks.json
830
+ const data = await readJson(TASKS_FILE, { tasks: [] });
831
+ const t = data.tasks.find(x => x.id === task.id);
832
+ if (t) {
833
+ t.subtasks = task.subtasks;
834
+ t.updatedAt = nowIso();
835
+ await writeJson(TASKS_FILE, data);
836
+ publish('task:update', t);
837
+ }
838
+ }
839
+
840
+ function waitProcessExit(pid) {
841
+ return new Promise(resolve => {
842
+ let exited = false;
843
+ const tryCheck = () => {
844
+ if (exited) return;
845
+ try {
846
+ process.kill(pid, 0); // 信号 0 = 探测存活
847
+ } catch (err) {
848
+ // 只在进程真的消失(ESRCH / EPERM)时才 resolve;
849
+ // 其他错误(比如参数类型)保留 polling 状态,由超时兜底。
850
+ if (err && (err.code === 'ESRCH' || err.code === 'EPERM')) {
851
+ exited = true;
852
+ resolve();
853
+ return;
854
+ }
855
+ }
856
+ setTimeout(tryCheck, 1500);
857
+ };
858
+ tryCheck();
859
+ // 兜底:30 分钟超时自动结束
860
+ setTimeout(() => { if (!exited) { exited = true; resolve(); } }, 30 * 60 * 1000);
861
+ });
862
+ }
863
+
864
+ export function registerWorkbenchRoutes({ app, getCurrentProjectPath, getProjectRoomId, io, configManager }) {
865
+ // ── AI 生成提示词(基于当前项目) ─────────────────────────────────────
866
+ app.post('/api/workbench/prompts/ai-generate', async (req, res) => {
867
+ try {
868
+ const projectPath = typeof getCurrentProjectPath === 'function' ? getCurrentProjectPath() : '';
869
+ if (!projectPath) {
870
+ return res.status(400).json({ success: false, error: '未选中项目' });
871
+ }
872
+ let stat;
873
+ try { stat = await fsp.stat(projectPath); }
874
+ catch { return res.status(400).json({ success: false, error: '项目路径不存在' }); }
875
+ if (!stat.isDirectory()) {
876
+ return res.status(400).json({ success: false, error: '项目路径不是目录' });
877
+ }
878
+
879
+ // 取模型
880
+ let model;
881
+ try {
882
+ if (!configManager) throw new Error('configManager 不可用');
883
+ const rawConfig = await configManager.readRawConfigFile();
884
+ const models = Array.isArray(rawConfig.models) ? rawConfig.models : [];
885
+ model = models.find(m => m.isDefault) || models[0];
886
+ } catch (err) {
887
+ return res.status(500).json({ success: false, error: '读取 AI 配置失败: ' + err.message });
888
+ }
889
+ if (!model) {
890
+ return res.status(400).json({ success: false, error: '未配置 AI 模型,请先在通用设置中添加模型' });
891
+ }
892
+
893
+ // 读取用户可编辑的生成指令;没存就用默认
894
+ const userInstruction = await readInstruction();
895
+
896
+ // 递归识别多子项目
897
+ const subProjects = await findSubProjects(projectPath);
898
+ if (subProjects.length === 0) {
899
+ // 没识别到任何子项目:回退到根目录本身
900
+ const fallbackTree = await listDirTree(projectPath, 2, 400);
901
+ const fallbackManifest = await readProjectManifest(projectPath);
902
+ const fallbackReadme = await safeReadFile(path.join(projectPath, 'README.md'), 8000);
903
+ subProjects.push({
904
+ root: projectPath,
905
+ name: path.basename(projectPath),
906
+ manifests: fallbackManifest,
907
+ readme: fallbackReadme,
908
+ dirTree: fallbackTree
909
+ });
910
+ }
911
+
912
+ const projectName = path.basename(projectPath);
913
+ const LLM_OPTS = { maxTokens: 4000, timeoutMs: 1200000 };
914
+
915
+ // ── 第一阶段:基于可编辑指令 + 根目录概览,生成「可复用的提示词模板」 ──
916
+ const overviewBlock = subProjects.map(sp =>
917
+ `### 子项目 ${sp.name} (${sp.root})\n目录:\n${sp.dirTree || '(无)'}`
918
+ ).join('\n\n');
919
+
920
+ const firstPrompt = `${userInstruction}
921
+
922
+ ---
923
+
924
+ 以下是你需要分析的项目(请先生成「可复用的提示词模板」,不要直接给总结):
925
+
926
+ 项目根目录:${projectPath}
927
+ 项目名称:${projectName}
928
+ 子项目数:${subProjects.length}
929
+
930
+ ## 子项目概览
931
+ ${overviewBlock || '(无)'}
932
+
933
+ ## 各子项目 manifest 与 README
934
+ ${subProjects.map(sp => {
935
+ const manifestBlock = Object.entries(sp.manifests)
936
+ .map(([n, c]) => `\n--- ${n} ---\n${c}`)
937
+ .join('\n');
938
+ return `\n### ${sp.name}\n${manifestBlock || '(无 manifest)'}\n\nREADME(前 8KB):\n${sp.readme || '(无)'}`;
939
+ }).join('\n')}
940
+
941
+ 只返回 JSON:
942
+ {
943
+ "name": "项目名(10-20字)",
944
+ "template": "可复用的提示词模板(300-600字),应明确使用 {{task.title}} / {{task.desc}} / {{sub.title}} / {{sub.desc}} / {{repo.path}} / {{branch}} 这 6 个变量"
945
+ }`;
946
+
947
+ const first = await callLlmJson(model, firstPrompt, LLM_OPTS);
948
+ const templateName = String(first.name || '').trim() || projectName || '项目架构说明';
949
+ const template = String(first.template || '').trim();
950
+
951
+ // ── 第二阶段:为每个子项目分别生成总结(单子项目 = 现在的行为) ──
952
+ async function summarizeOneSub(sp) {
953
+ const manifestBlock = Object.entries(sp.manifests)
954
+ .map(([n, c]) => `\n--- ${n} ---\n${c}`)
955
+ .join('\n');
956
+ const subPrompt = `${template}
957
+
958
+ ---
959
+
960
+ 以下是你需要分析的一个子项目(请直接基于这些数据输出该子项目的架构说明):
961
+
962
+ 子项目根目录:${sp.root}
963
+ 子项目名称:${sp.name}
964
+
965
+ ## 目录结构(前 2 层)
966
+ ${sp.dirTree || '(无)'}
967
+
968
+ ## manifest
969
+ ${manifestBlock || '(无)'}
970
+
971
+ ## README
972
+ ${sp.readme || '(无)'}
973
+
974
+ 只返回 JSON:
975
+ {
976
+ "summary": "该子项目的架构说明(300-600字)"
977
+ }`;
978
+ const r = await callLlmJson(model, subPrompt, LLM_OPTS);
979
+ return { name: sp.name, root: sp.root, summary: String(r.summary || '').trim() };
980
+ }
981
+
982
+ const subSummaries = await Promise.all(subProjects.map(summarizeOneSub));
983
+
984
+ // ── 第三阶段:仅多子项目时合并(单子项目直接拿它的 summary) ──
985
+ let finalSummary = '';
986
+ let finalName = templateName;
987
+
988
+ if (subSummaries.length === 1) {
989
+ finalSummary = subSummaries[0].summary;
990
+ } else {
991
+ const mergePrompt = `你是项目架构师。下列是同一仓库下 N 个子项目的架构说明,请合并输出**单一**的「项目架构说明」(800-1500字),覆盖:项目整体定位、技术栈、模块划分、子项目间关系、核心流程、关键设计决策。
992
+ 子项目之间用清晰的小标题或编号分隔。最后输出一段「整体架构」总结它们如何协同。
993
+ 只引用实际出现的子项目名 / 文件路径 / 依赖名,不要编造。只返回 JSON:
994
+
995
+ {
996
+ "name": "项目名(10-20字)",
997
+ "summary": "合并后的架构说明"
998
+ }
999
+
1000
+ ## 子项目说明
1001
+ ${subSummaries.map((s, i) => `\n### [${i + 1}] ${s.name} (${s.root})\n${s.summary || '(空)'}`).join('\n')}`;
1002
+
1003
+ const merged = await callLlmJson(model, mergePrompt, LLM_OPTS);
1004
+ finalSummary = String(merged.summary || '').trim()
1005
+ || subSummaries.map(s => `### ${s.name}\n${s.summary}`).join('\n\n');
1006
+ finalName = String(merged.name || '').trim() || templateName;
1007
+ }
1008
+
1009
+ if (!finalSummary) {
1010
+ // 兜底:仅返回模板
1011
+ return res.json({
1012
+ success: true,
1013
+ name: finalName,
1014
+ template,
1015
+ result: '',
1016
+ content: template
1017
+ });
1018
+ }
1019
+
1020
+ // 顶层 request 已经自带 20 分钟(1200s)超时;
1021
+ // 这里在 express 处理器内部不再额外加整体超时。
1022
+ res.json({
1023
+ success: true,
1024
+ name: finalName,
1025
+ template,
1026
+ result: finalSummary,
1027
+ content: finalSummary
1028
+ });
1029
+ } catch (err) {
1030
+ res.status(500).json({ success: false, error: err.message });
1031
+ }
1032
+ });
1033
+
1034
+ // ── 生成指令:读 / 写(用户可在弹窗里自定义) ───────────────────────
1035
+ app.get('/api/workbench/prompts/ai-instruction', async (_req, res) => {
1036
+ try {
1037
+ const instruction = await readInstruction();
1038
+ res.json({ success: true, instruction, isDefault: instruction === DEFAULT_INSTRUCTION });
1039
+ } catch (err) {
1040
+ res.status(500).json({ success: false, error: err.message });
1041
+ }
1042
+ });
1043
+
1044
+ app.put('/api/workbench/prompts/ai-instruction', async (req, res) => {
1045
+ try {
1046
+ const text = req.body && typeof req.body.instruction === 'string'
1047
+ ? req.body.instruction.trim()
1048
+ : '';
1049
+ if (!text) {
1050
+ return res.status(400).json({ success: false, error: '指令不能为空' });
1051
+ }
1052
+ if (text.length > 50000) {
1053
+ return res.status(413).json({ success: false, error: '指令过长(最多 50000 字符)' });
1054
+ }
1055
+ await writeInstruction(text);
1056
+ res.json({ success: true });
1057
+ } catch (err) {
1058
+ res.status(500).json({ success: false, error: err.message });
1059
+ }
1060
+ });
1061
+
1062
+ // ── AI 拆分子任务:独立的指令文件、独立的端点 ───────────────────────
1063
+ // GET /api/workbench/tasks/ai-subtask-instruction
1064
+ // → { success, instruction, isDefault }
1065
+ // PUT /api/workbench/tasks/ai-subtask-instruction
1066
+ // body: { instruction: string }
1067
+ // → { success }
1068
+ app.get('/api/workbench/tasks/ai-subtask-instruction', async (req, res) => {
1069
+ try {
1070
+ const def = pickDefaultSubtaskInstruction(req);
1071
+ const instruction = await readSubtaskInstruction(req);
1072
+ // isDefault:当前 instruction 和 locale 默认完全一致
1073
+ res.json({ success: true, instruction, isDefault: instruction === def });
1074
+ } catch (err) {
1075
+ res.status(500).json({ success: false, error: err.message });
1076
+ }
1077
+ });
1078
+
1079
+ app.put('/api/workbench/tasks/ai-subtask-instruction', async (req, res) => {
1080
+ try {
1081
+ const text = req.body && typeof req.body.instruction === 'string'
1082
+ ? req.body.instruction.trim()
1083
+ : '';
1084
+ if (!text) {
1085
+ return res.status(400).json({ success: false, error: '指令不能为空' });
1086
+ }
1087
+ if (text.length > 50000) {
1088
+ return res.status(413).json({ success: false, error: '指令过长(最多 50000 字符)' });
1089
+ }
1090
+ // 如果保存的文本正好等于当前 locale 的默认——不写文件,保持 fallback 行为
1091
+ const def = pickDefaultSubtaskInstruction(req);
1092
+ if (text === def) {
1093
+ // 删除已存在的自定义文件
1094
+ try { await fsp.unlink(SUBTASK_INSTRUCTION_FILE) } catch {}
1095
+ return res.json({ success: true, isDefault: true });
1096
+ }
1097
+ await writeSubtaskInstruction(text);
1098
+ res.json({ success: true, isDefault: false });
1099
+ } catch (err) {
1100
+ res.status(500).json({ success: false, error: err.message });
1101
+ }
1102
+ });
1103
+
1104
+ // POST /api/workbench/tasks/ai-split-subtasks
1105
+ // body: { title, desc, taskId? }
1106
+ // → SSE 流:
1107
+ // data:{"type":"meta","prompt":{system,user}}\n\n
1108
+ // data:{"type":"thinking","delta":"..."}\n\n (多次)
1109
+ // data:{"type":"content","delta":"..."}\n\n (多次)
1110
+ // data:{"type":"done","subtasks":[...],"raw":"..."}\n\n
1111
+ // data:{"type":"error","error":"..."}\n\n (失败时)
1112
+ //
1113
+ // 走流式是为了让用户看到模型真实的 reasoning_content(如果模型支持),
1114
+ // 而不是前端用 setInterval 假装"打字机"——拆分质量也会因为给了模型
1115
+ // 充分的思考空间而显著提升。
1116
+ app.post('/api/workbench/tasks/ai-split-subtasks', async (req, res) => {
1117
+ const title = String(req.body?.title || '').trim();
1118
+ const desc = String(req.body?.desc || '').trim();
1119
+ const taskId = String(req.body?.taskId || '').trim();
1120
+ const promptId = String(req.body?.promptId || '').trim();
1121
+ if (!title) {
1122
+ return res.status(400).json({ success: false, error: '任务标题不能为空' });
1123
+ }
1124
+
1125
+ // 建立 SSE
1126
+ res.set({
1127
+ 'Content-Type': 'text/event-stream',
1128
+ 'Cache-Control': 'no-cache, no-transform',
1129
+ 'Connection': 'keep-alive',
1130
+ 'X-Accel-Buffering': 'no'
1131
+ });
1132
+ res.flushHeaders?.();
1133
+ const send = (obj) => {
1134
+ try { res.write(`data: ${JSON.stringify(obj)}\n\n`); } catch {}
1135
+ };
1136
+
1137
+ const abortController = new AbortController();
1138
+ let finished = false; // 标记响应是否已正常结束
1139
+ // 客户端真实断开:监听 socket close,而不是 req.close。
1140
+ // Node 22+ 的 req 'close' 事件会在 HTTP keep-alive socket 池回收时过早触发,
1141
+ // 导致正常请求中途被 abort。这里改用 socket 真实断开事件,
1142
+ // 并只在响应还没 end 时才取消上游 LLM。
1143
+ const onSocketClose = () => {
1144
+ if (!finished) abortController.abort()
1145
+ };
1146
+ if (req.socket) {
1147
+ req.socket.once('close', onSocketClose);
1148
+ }
1149
+
1150
+ try {
1151
+ let model;
1152
+ try {
1153
+ if (!configManager) throw new Error('configManager 不可用');
1154
+ const rawConfig = await configManager.readRawConfigFile();
1155
+ const models = Array.isArray(rawConfig.models) ? rawConfig.models : [];
1156
+ model = models.find(m => m.isDefault) || models[0];
1157
+ } catch (err) {
1158
+ send({ type: 'error', error: '读取 AI 配置失败: ' + err.message });
1159
+ finished = true;
1160
+ return res.end();
1161
+ }
1162
+ if (!model) {
1163
+ send({ type: 'error', error: '未配置 AI 模型,请先在通用设置中添加模型' });
1164
+ finished = true;
1165
+ return res.end();
1166
+ }
1167
+
1168
+ const userInstruction = await readSubtaskInstruction(req);
1169
+ const projectPath = typeof getCurrentProjectPath === 'function' ? getCurrentProjectPath() : '';
1170
+ const projectName = projectPath ? path.basename(projectPath) : '(未指定项目)';
1171
+ const manifestHint = await detectProjectManifest(projectPath);
1172
+
1173
+ // 取绑定的预置模板(promptId):模板内容作为"执行模板"提示
1174
+ // 让 LLM 拆分时知道:每个 sub 最终都会被这套模板包裹后送进 claude
1175
+ let templateBlock = '';
1176
+ if (promptId) {
1177
+ try {
1178
+ const promptData = await readJson(PROMPTS_FILE, { prompts: [] });
1179
+ const p = (promptData.prompts || []).find(x => x.id === promptId);
1180
+ if (p && p.content) {
1181
+ templateBlock = `\n\n## 子任务执行模板(每个拆出的子任务最终会被这套模板包裹后送给 claude 执行;拆分时请确保子任务能让模板里的 {{sub.title}} / {{sub.desc}} 等变量填得有意义)\n模板名:${p.name || '(未命名)'}\n---\n${p.content}\n---`;
1182
+ }
1183
+ } catch { /* 模板读取失败不影响拆分 */ }
1184
+ }
1185
+
1186
+ // 取任务附件
1187
+ let attachmentBlock = '';
1188
+ const imageDataUrls = [];
1189
+ if (taskId) {
1190
+ try {
1191
+ const data = await readJson(TASKS_FILE, { tasks: [] });
1192
+ const task = (data.tasks || []).find(t => t.id === taskId);
1193
+ const atts = Array.isArray(task?.attachments) ? task.attachments : [];
1194
+ if (atts.length > 0) {
1195
+ const lines = [];
1196
+ for (let i = 0; i < atts.length; i++) {
1197
+ const a = atts[i];
1198
+ if (!a || !a.absolutePath) continue;
1199
+ lines.push(` ${i + 1}. [${a.mimeType || 'application/octet-stream'}] ${a.absolutePath}`);
1200
+ if (isImageExt(a.ext)) {
1201
+ try {
1202
+ const buf = await fsp.readFile(a.absolutePath);
1203
+ const mime = a.mimeType || 'image/png';
1204
+ imageDataUrls.push(`data:${mime};base64,${buf.toString('base64')}`);
1205
+ } catch { /* 文件丢失就跳过这张图 */ }
1206
+ }
1207
+ }
1208
+ if (lines.length > 0) {
1209
+ const imgNote = imageDataUrls.length > 0
1210
+ ? `(其中 ${imageDataUrls.length} 张图片已随消息一并发送,请直接基于图片内容拆分)`
1211
+ : '';
1212
+ attachmentBlock = `\n\n## 任务附件${imgNote}\n${lines.join('\n')}`;
1213
+ }
1214
+ }
1215
+ } catch { /* 没拿到附件不影响拆分 */ }
1216
+ }
1217
+
1218
+ const userBlock = `${userInstruction}
1219
+
1220
+ ---
1221
+
1222
+ ## 待拆分的任务
1223
+ 标题:${title}
1224
+ ${desc ? `描述:${desc}` : '描述:(无)'}${attachmentBlock}${templateBlock}
1225
+
1226
+ ## 项目上下文(仅供参考,便于拆分时考虑项目特性)
1227
+ - 项目名称:${projectName}
1228
+ - 项目根目录:${projectPath || '(未指定)'}
1229
+ - 主要 manifest:${manifestHint || '(未识别到)'}
1230
+
1231
+ 请先简要分析(可以放在 reasoning 中或直接写出来),然后给出 JSON。JSON 用 \`\`\`json ... \`\`\` 包裹:
1232
+ {
1233
+ "subtasks": [
1234
+ { "title": "子任务标题(10-20字)", "desc": "具体描述" }
1235
+ ]
1236
+ }`;
1237
+
1238
+ // 先把 prompt 元信息推给前端
1239
+ send({ type: 'meta', prompt: { system: userInstruction, user: userBlock } });
1240
+
1241
+ // 流式调用 LLM,把 thinking / content 实时回传
1242
+ const { content, aborted } = await callLlmStream(
1243
+ model,
1244
+ userBlock,
1245
+ (delta) => {
1246
+ if (delta.thinking) send({ type: 'thinking', delta: delta.thinking });
1247
+ if (delta.content) send({ type: 'content', delta: delta.content });
1248
+ },
1249
+ { maxTokens: 4000, timeoutMs: 600000, images: imageDataUrls, signal: abortController.signal }
1250
+ );
1251
+
1252
+ if (aborted) {
1253
+ send({ type: 'error', error: '已取消' });
1254
+ finished = true;
1255
+ return res.end();
1256
+ }
1257
+
1258
+ // 解析 JSON:兼容 ```json ... ``` 代码块或裸 JSON
1259
+ let parsed = {};
1260
+ try {
1261
+ const m = content.match(/```json\s*([\s\S]*?)```/i)
1262
+ || content.match(/```\s*([\s\S]*?)```/)
1263
+ || content.match(/(\{[\s\S]*\})/);
1264
+ parsed = JSON.parse(m ? m[1] : content);
1265
+ } catch { parsed = {}; }
1266
+
1267
+ const list = Array.isArray(parsed?.subtasks) ? parsed.subtasks : [];
1268
+ const subtasks = list
1269
+ .map(s => ({
1270
+ title: String(s?.title || '').trim().slice(0, 80),
1271
+ desc: String(s?.desc || '').trim().slice(0, 500)
1272
+ }))
1273
+ .filter(s => s.title)
1274
+ .slice(0, 8);
1275
+
1276
+ send({ type: 'done', subtasks, raw: content });
1277
+ finished = true;
1278
+ res.end();
1279
+ } catch (err) {
1280
+ send({ type: 'error', error: 'AI 拆分失败: ' + (err?.message || String(err)) });
1281
+ finished = true;
1282
+ res.end();
1283
+ }
1284
+ });
1285
+
1286
+ // SSE 事件流
1287
+ app.get('/api/workbench/events', (req, res) => {
1288
+ res.set({
1289
+ 'Content-Type': 'text/event-stream',
1290
+ 'Cache-Control': 'no-cache, no-transform',
1291
+ 'Connection': 'keep-alive',
1292
+ 'X-Accel-Buffering': 'no'
1293
+ });
1294
+ res.flushHeaders?.();
1295
+ const send = (data) => {
1296
+ res.write(`data: ${JSON.stringify(data)}\n\n`);
1297
+ };
1298
+ // 初始快照
1299
+ send({ event: 'hello', payload: { jobs: snapshotJobs() }, ts: nowIso() });
1300
+ const handler = (evt) => send(evt);
1301
+ bus.on('event', handler);
1302
+ const ka = setInterval(() => res.write(`: keep-alive\n\n`), 15000);
1303
+ req.on('close', () => {
1304
+ clearInterval(ka);
1305
+ bus.off('event', handler);
1306
+ });
1307
+ });
1308
+
1309
+ // ── 提示词 CRUD ─────────────────────────────────────────────────────
1310
+ app.get('/api/workbench/prompts', async (_req, res) => {
1311
+ try {
1312
+ const data = await readJson(PROMPTS_FILE, { prompts: [] });
1313
+ res.json({ success: true, prompts: data.prompts || [] });
1314
+ } catch (err) {
1315
+ res.status(500).json({ success: false, error: err.message });
1316
+ }
1317
+ });
1318
+
1319
+ app.post('/api/workbench/prompts', async (req, res) => {
1320
+ try {
1321
+ const { id, name, content } = req.body || {};
1322
+ if (!name || typeof content !== 'string') {
1323
+ return res.status(400).json({ success: false, error: 'name 和 content 必填' });
1324
+ }
1325
+ const data = await readJson(PROMPTS_FILE, { prompts: [] });
1326
+ const prompts = data.prompts || [];
1327
+ const now = nowIso();
1328
+ if (id) {
1329
+ const i = prompts.findIndex(p => p.id === id);
1330
+ if (i < 0) return res.status(404).json({ success: false, error: '提示词不存在' });
1331
+ prompts[i] = { ...prompts[i], name, content, updatedAt: now };
1332
+ await writeJson(PROMPTS_FILE, { prompts });
1333
+ return res.json({ success: true, prompt: prompts[i] });
1334
+ }
1335
+ const prompt = { id: genId(), name, content, createdAt: now, updatedAt: now };
1336
+ prompts.push(prompt);
1337
+ await writeJson(PROMPTS_FILE, { prompts });
1338
+ res.json({ success: true, prompt });
1339
+ } catch (err) {
1340
+ res.status(500).json({ success: false, error: err.message });
1341
+ }
1342
+ });
1343
+
1344
+ app.delete('/api/workbench/prompts/:id', async (req, res) => {
1345
+ try {
1346
+ const data = await readJson(PROMPTS_FILE, { prompts: [] });
1347
+ const prompts = (data.prompts || []).filter(p => p.id !== req.params.id);
1348
+ await writeJson(PROMPTS_FILE, { prompts });
1349
+ res.json({ success: true });
1350
+ } catch (err) {
1351
+ res.status(500).json({ success: false, error: err.message });
1352
+ }
1353
+ });
1354
+
1355
+ // ── 任务 CRUD ───────────────────────────────────────────────────────
1356
+ app.get('/api/workbench/tasks', async (_req, res) => {
1357
+ try {
1358
+ const data = await readJson(TASKS_FILE, { tasks: [] });
1359
+ res.json({ success: true, tasks: data.tasks || [] });
1360
+ } catch (err) {
1361
+ res.status(500).json({ success: false, error: err.message });
1362
+ }
1363
+ });
1364
+
1365
+ app.post('/api/workbench/tasks', async (req, res) => {
1366
+ try {
1367
+ const { id, title, desc, promptId, subtasks } = req.body || {};
1368
+ if (!title) return res.status(400).json({ success: false, error: 'title 必填' });
1369
+ const data = await readJson(TASKS_FILE, { tasks: [] });
1370
+ const tasks = data.tasks || [];
1371
+ const now = nowIso();
1372
+ if (id) {
1373
+ const i = tasks.findIndex(t => t.id === id);
1374
+ if (i < 0) return res.status(404).json({ success: false, error: '任务不存在' });
1375
+ tasks[i] = {
1376
+ ...tasks[i],
1377
+ title,
1378
+ desc: desc || '',
1379
+ promptId: promptId || null,
1380
+ subtasks: Array.isArray(subtasks) ? subtasks.map(s => ({
1381
+ id: s.id || genId(),
1382
+ title: s.title || '',
1383
+ desc: s.desc || '',
1384
+ status: s.status || 'todo',
1385
+ promptOverride: s.promptOverride || '',
1386
+ // 保留附件元数据(仅保留基础字段,丢弃客户端临时字段)
1387
+ attachments: Array.isArray(s.attachments) ? s.attachments.map(a => ({
1388
+ id: a.id,
1389
+ originalName: a.originalName,
1390
+ mimeType: a.mimeType,
1391
+ size: a.size,
1392
+ ext: a.ext,
1393
+ storedName: a.storedName,
1394
+ absolutePath: a.absolutePath,
1395
+ createdAt: a.createdAt
1396
+ })) : (tasks[i].subtasks.find(x => x.id === s.id)?.attachments || [])
1397
+ })) : tasks[i].subtasks,
1398
+ updatedAt: now
1399
+ };
1400
+ await writeJson(TASKS_FILE, { tasks });
1401
+ return res.json({ success: true, task: tasks[i] });
1402
+ }
1403
+ const task = {
1404
+ id: genId(),
1405
+ title,
1406
+ desc: desc || '',
1407
+ promptId: promptId || null,
1408
+ subtasks: Array.isArray(subtasks) ? subtasks.map(s => ({
1409
+ id: s.id || genId(),
1410
+ title: s.title || '',
1411
+ desc: s.desc || '',
1412
+ status: s.status || 'todo',
1413
+ promptOverride: s.promptOverride || '',
1414
+ attachments: Array.isArray(s.attachments) ? s.attachments : []
1415
+ })) : [],
1416
+ status: 'todo',
1417
+ createdAt: now,
1418
+ updatedAt: now
1419
+ };
1420
+ tasks.push(task);
1421
+ await writeJson(TASKS_FILE, { tasks });
1422
+ res.json({ success: true, task });
1423
+ } catch (err) {
1424
+ res.status(500).json({ success: false, error: err.message });
1425
+ }
1426
+ });
1427
+
1428
+ app.delete('/api/workbench/tasks/:id', async (req, res) => {
1429
+ try {
1430
+ const data = await readJson(TASKS_FILE, { tasks: [] });
1431
+ const tasks = (data.tasks || []).filter(t => t.id !== req.params.id);
1432
+ await writeJson(TASKS_FILE, { tasks });
1433
+ res.json({ success: true });
1434
+ } catch (err) {
1435
+ res.status(500).json({ success: false, error: err.message });
1436
+ }
1437
+ });
1438
+
1439
+ // ── 执行任务 ────────────────────────────────────────────────────────
1440
+ app.post('/api/workbench/tasks/:id/run', async (req, res) => {
1441
+ try {
1442
+ const data = await readJson(TASKS_FILE, { tasks: [] });
1443
+ const task = (data.tasks || []).find(t => t.id === req.params.id);
1444
+ if (!task) return res.status(404).json({ success: false, error: '任务不存在' });
1445
+ if (!task.subtasks || task.subtasks.length === 0) {
1446
+ return res.status(400).json({ success: false, error: '任务没有子任务' });
1447
+ }
1448
+ const repoPath = typeof getCurrentProjectPath === 'function' ? getCurrentProjectPath() : '';
1449
+ // 异步执行,立即返回
1450
+ res.json({ success: true, message: '已开始执行' });
1451
+ runTaskQueue(task, repoPath, '').catch(err => {
1452
+ publish('task:error', { taskId: task.id, error: err.message });
1453
+ });
1454
+ } catch (err) {
1455
+ res.status(500).json({ success: false, error: err.message });
1456
+ }
1457
+ });
1458
+
1459
+ // ── 进程状态查询(兜底,SSE 断了也能拉) ────────────────────────────
1460
+ app.get('/api/workbench/jobs', (_req, res) => {
1461
+ res.json({ success: true, jobs: snapshotJobs() });
1462
+ });
1463
+
1464
+ // ── 取消正在执行的 job ───────────────────────────────────────────
1465
+ // POST /api/workbench/jobs/:id/cancel
1466
+ // 行为:
1467
+ // - 找到正在运行的 job,调 child.kill() 终止 claude 进程
1468
+ // - Windows 下用 taskkill /T /F 杀进程树(claude 进程可能 fork 出子进程)
1469
+ // - 加入 cancelledJobs 集合,runTaskQueue 退出循环后会把 job 标为 'cancelled'
1470
+ // - 只影响这一个 sub;同 task 后续 sub 仍按队列顺序继续执行
1471
+ app.post('/api/workbench/jobs/:id/cancel', (req, res) => {
1472
+ const job = jobs.get(req.params.id)
1473
+ if (!job) {
1474
+ return res.status(404).json({ success: false, error: 'job 不存在' })
1475
+ }
1476
+ if (job.status !== 'running' && job.status !== 'pending') {
1477
+ return res.status(400).json({ success: false, error: `当前状态 ${job.status} 不可取消` })
1478
+ }
1479
+ cancelledJobs.add(job.id)
1480
+ // 立即给前端一个状态反馈(不等 child 真正退出)
1481
+ job.status = 'cancelled'
1482
+ job.error = '用户已停止执行'
1483
+ job.endedAt = nowIso()
1484
+ publish('job:update', { ...job }) // 用浅拷贝避免序列化 child 引用
1485
+ const child = job.child
1486
+ if (!child) {
1487
+ return res.json({ success: true, message: '已标记取消,进程将尽快结束' })
1488
+ }
1489
+ try {
1490
+ if (process.platform === 'win32') {
1491
+ // Windows: child.kill(SIGTERM) 经常无效,用 taskkill 杀进程树
1492
+ execFile('taskkill', ['/PID', String(child.pid), '/T', '/F'], (err) => {
1493
+ if (err) {
1494
+ console.warn(`[workbench] taskkill ${child.pid} 失败:`, err.message)
1495
+ }
1496
+ })
1497
+ } else {
1498
+ child.kill('SIGTERM')
1499
+ }
1500
+ res.json({ success: true, message: '已发送停止信号' })
1501
+ } catch (err) {
1502
+ cancelledJobs.delete(job.id)
1503
+ res.status(500).json({ success: false, error: '发送停止信号失败: ' + err.message })
1504
+ }
1505
+ });
1506
+
1507
+ // ── 子任务附件:上传 / 删除 / 列表 ───────────────────────────────
1508
+ // 上传:POST /api/workbench/subtasks/:subId/attachments
1509
+ // header: X-Original-Name, X-Mime-Type
1510
+ // body: raw binary
1511
+ // 删除:DELETE /api/workbench/subtasks/:subId/attachments/:attId
1512
+ // 列表:GET /api/workbench/subtasks/:subId/attachments
1513
+ //
1514
+ // 文件存到 ~/.zen-gitsync/workbench-images/{subId}/{attId}.{ext}
1515
+ // 元数据(id / originalName / mime / size / storedName)通过 sub.attachments
1516
+ // 跟随 tasks.json 一起持久化。
1517
+ const rawAttachment = express.raw({
1518
+ type: '*/*',
1519
+ limit: MAX_IMAGE_BYTES * 4 // 整体路由上限 20MB;单文件大小由业务再卡
1520
+ });
1521
+
1522
+ // 共享 helper:找到一个 attachment 所在的位置(task 主附件 或 sub 附件)
1523
+ // 返回 { owner, task, sub?, list, att, storageDir } 或 null
1524
+ async function findAttachmentLocation(attId) {
1525
+ const data = await readJson(TASKS_FILE, { tasks: [] });
1526
+ for (const t of data.tasks || []) {
1527
+ const list = Array.isArray(t.attachments) ? t.attachments : [];
1528
+ const att = list.find(x => x.id === attId);
1529
+ if (att) {
1530
+ return { owner: 'task', task: t, list, att, storageDir: path.join(IMAGES_DIR, '_task-' + t.id) };
1531
+ }
1532
+ }
1533
+ for (const t of data.tasks || []) {
1534
+ for (const s of t.subtasks || []) {
1535
+ const list = Array.isArray(s.attachments) ? s.attachments : [];
1536
+ const att = list.find(x => x.id === attId);
1537
+ if (att) {
1538
+ return { owner: 'sub', task: t, sub: s, list, att, storageDir: path.join(IMAGES_DIR, s.id) };
1539
+ }
1540
+ }
1541
+ }
1542
+ return null;
1543
+ }
1544
+
1545
+ // 共享 helper:写入新附件(参数化以支持 task / sub)
1546
+ async function writeAttachmentTo({ req, target, maxCount }) {
1547
+ if (!req.body || !(req.body instanceof Buffer) || req.body.length === 0) {
1548
+ return { error: '请求体为空', status: 400 };
1549
+ }
1550
+ if (req.body.length > MAX_IMAGE_BYTES) {
1551
+ return { error: `单文件不得超过 ${MAX_IMAGE_BYTES / 1024 / 1024}MB`, status: 413 };
1552
+ }
1553
+ const originalName = String(req.get('X-Original-Name') || 'attachment').slice(0, 200);
1554
+ const mimeType = String(req.get('X-Mime-Type') || 'application/octet-stream').slice(0, 120);
1555
+ const ext = resolveExt({ originalName, mime: mimeType });
1556
+ if (!ext) {
1557
+ return { error: `不支持的文件类型(仅允许 ${[...ALLOWED_EXTS].join(', ')})`, status: 400 };
1558
+ }
1559
+ if (!Array.isArray(target.attachments)) target.attachments = [];
1560
+ if (target.attachments.length >= maxCount) {
1561
+ return { error: `附件已达上限 ${maxCount} 个`, status: 400 };
1562
+ }
1563
+
1564
+ const attId = genId();
1565
+ await fsp.mkdir(target.storageDir, { recursive: true });
1566
+ const storedName = `${attId}.${ext}`;
1567
+ const storedPath = path.join(target.storageDir, storedName);
1568
+ await fsp.writeFile(storedPath, req.body);
1569
+
1570
+ const attachment = {
1571
+ id: attId,
1572
+ originalName,
1573
+ mimeType,
1574
+ size: req.body.length,
1575
+ ext,
1576
+ storedName,
1577
+ absolutePath: storedPath,
1578
+ createdAt: nowIso()
1579
+ };
1580
+ target.attachments.push(attachment);
1581
+ target.updatedAt = nowIso();
1582
+ return { attachment };
1583
+ }
1584
+
1585
+ // 子任务附件
1586
+ app.post('/api/workbench/subtasks/:subId/attachments', rawAttachment, async (req, res) => {
1587
+ try {
1588
+ const { subId } = req.params;
1589
+ const data = await readJson(TASKS_FILE, { tasks: [] });
1590
+ let foundSub = null;
1591
+ for (const t of data.tasks || []) {
1592
+ const s = (t.subtasks || []).find(x => x.id === subId);
1593
+ if (s) { foundSub = s; break; }
1594
+ }
1595
+ if (!foundSub) {
1596
+ return res.status(404).json({ success: false, error: '子任务不存在' });
1597
+ }
1598
+ const target = { ...foundSub, storageDir: path.join(IMAGES_DIR, subId) };
1599
+ const result = await writeAttachmentTo({ req, target, maxCount: MAX_ATTACHMENTS_PER_SUBTASK });
1600
+ if (result.error) return res.status(result.status).json({ success: false, error: result.error });
1601
+ // target 是 spread 出来的浅拷贝,data 引用里的 foundSub 没改;显式 push 回去
1602
+ const att = result.attachment;
1603
+ foundSub.attachments = Array.isArray(foundSub.attachments) ? foundSub.attachments : [];
1604
+ foundSub.attachments.push(att);
1605
+ foundSub.updatedAt = nowIso();
1606
+ await writeJson(TASKS_FILE, data);
1607
+ res.json({ success: true, attachment: att });
1608
+ } catch (err) {
1609
+ res.status(500).json({ success: false, error: err.message });
1610
+ }
1611
+ });
1612
+
1613
+ app.delete('/api/workbench/subtasks/:subId/attachments/:attId', async (req, res) => {
1614
+ try {
1615
+ const { subId, attId } = req.params;
1616
+ const data = await readJson(TASKS_FILE, { tasks: [] });
1617
+ let foundSub = null;
1618
+ for (const t of data.tasks || []) {
1619
+ const s = (t.subtasks || []).find(x => x.id === subId);
1620
+ if (s) { foundSub = s; break; }
1621
+ }
1622
+ if (!foundSub) return res.status(404).json({ success: false, error: '子任务不存在' });
1623
+ const list = Array.isArray(foundSub.attachments) ? foundSub.attachments : [];
1624
+ const i = list.findIndex(a => a.id === attId);
1625
+ if (i < 0) return res.status(404).json({ success: false, error: '附件不存在' });
1626
+ const [removed] = list.splice(i, 1);
1627
+ try {
1628
+ await fsp.unlink(path.join(IMAGES_DIR, subId, removed.storedName));
1629
+ } catch { /* 文件可能已不存在 */ }
1630
+ foundSub.updatedAt = nowIso();
1631
+ await writeJson(TASKS_FILE, data);
1632
+ res.json({ success: true });
1633
+ } catch (err) {
1634
+ res.status(500).json({ success: false, error: err.message });
1635
+ }
1636
+ });
1637
+
1638
+ // 主任务附件
1639
+ app.post('/api/workbench/tasks/:taskId/attachments', rawAttachment, async (req, res) => {
1640
+ try {
1641
+ const { taskId } = req.params;
1642
+ const data = await readJson(TASKS_FILE, { tasks: [] });
1643
+ const task = (data.tasks || []).find(t => t.id === taskId);
1644
+ if (!task) return res.status(404).json({ success: false, error: '任务不存在' });
1645
+ const target = { ...task, storageDir: path.join(IMAGES_DIR, '_task-' + taskId) };
1646
+ const result = await writeAttachmentTo({ req, target, maxCount: MAX_ATTACHMENTS_PER_SUBTASK });
1647
+ if (result.error) return res.status(result.status).json({ success: false, error: result.error });
1648
+ const att = result.attachment;
1649
+ task.attachments = Array.isArray(task.attachments) ? task.attachments : [];
1650
+ task.attachments.push(att);
1651
+ task.updatedAt = nowIso();
1652
+ await writeJson(TASKS_FILE, data);
1653
+ res.json({ success: true, attachment: att });
1654
+ } catch (err) {
1655
+ res.status(500).json({ success: false, error: err.message });
1656
+ }
1657
+ });
1658
+
1659
+ app.delete('/api/workbench/tasks/:taskId/attachments/:attId', async (req, res) => {
1660
+ try {
1661
+ const { taskId, attId } = req.params;
1662
+ const data = await readJson(TASKS_FILE, { tasks: [] });
1663
+ const task = (data.tasks || []).find(t => t.id === taskId);
1664
+ if (!task) return res.status(404).json({ success: false, error: '任务不存在' });
1665
+ const list = Array.isArray(task.attachments) ? task.attachments : [];
1666
+ const i = list.findIndex(a => a.id === attId);
1667
+ if (i < 0) return res.status(404).json({ success: false, error: '附件不存在' });
1668
+ const [removed] = list.splice(i, 1);
1669
+ try {
1670
+ await fsp.unlink(path.join(IMAGES_DIR, '_task-' + taskId, removed.storedName));
1671
+ } catch { /* 文件可能已不存在 */ }
1672
+ task.updatedAt = nowIso();
1673
+ await writeJson(TASKS_FILE, data);
1674
+ res.json({ success: true });
1675
+ } catch (err) {
1676
+ res.status(500).json({ success: false, error: err.message });
1677
+ }
1678
+ });
1679
+
1680
+ // 附件原文件读取(前端 <img> 缩略图用)—— 支持 task 和 sub 两种归属
1681
+ app.get('/api/workbench/attachments/:attId/raw', async (req, res) => {
1682
+ try {
1683
+ const { attId } = req.params;
1684
+ const loc = await findAttachmentLocation(attId);
1685
+ if (!loc) return res.status(404).json({ success: false, error: '附件不存在' });
1686
+ const filePath = path.join(loc.storageDir, loc.att.storedName);
1687
+ try {
1688
+ const stat = await fsp.stat(filePath);
1689
+ res.set('Content-Type', loc.att.mimeType || 'application/octet-stream');
1690
+ res.set('Content-Length', String(stat.size));
1691
+ res.set('Cache-Control', 'private, max-age=3600');
1692
+ const stream = (await import('fs')).createReadStream(filePath);
1693
+ stream.on('error', () => res.end());
1694
+ stream.pipe(res);
1695
+ } catch {
1696
+ res.status(404).json({ success: false, error: '文件已丢失' });
1697
+ }
1698
+ } catch (err) {
1699
+ res.status(500).json({ success: false, error: err.message });
1700
+ }
1701
+ });
1702
+ }