zen-gitsync 2.12.7 → 2.12.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/README.md +58 -2
  2. package/package.json +1 -1
  3. package/scripts/README_COLOR_CONVERTER.md +196 -196
  4. package/scripts/README_FONTSIZE_CONVERTER.md +278 -278
  5. package/scripts/README_SPACING_CONVERTER.md +126 -126
  6. package/scripts/README_STYLE_VARS.md +180 -180
  7. package/src/ui/public/assets/EditorView-C4DezJRA.js +0 -0
  8. package/src/ui/public/assets/{EditorView-DK-Xgt7r.css → EditorView-DEd8QuPp.css} +1 -1
  9. package/src/ui/public/assets/SourceMapView-B521sL_k.js +3 -0
  10. package/src/ui/public/assets/SourceMapView-P9hbpXgz.css +1 -0
  11. package/src/ui/public/assets/WorkbenchView-75x9qygA.js +1 -0
  12. package/src/ui/public/assets/WorkbenchView-Dc9vThI8.css +1 -0
  13. package/src/ui/public/assets/_plugin-vue_export-helper-DMUTnP0C.js +9 -0
  14. package/src/ui/public/assets/{css.worker-CvXBzhp8.js → css.worker-Wv5dxAWO.js} +1 -1
  15. package/src/ui/public/assets/{html.worker-BO6WuOEO.js → html.worker-CQP8QQsS.js} +1 -1
  16. package/src/ui/public/assets/index-BCIFnj7e.css +1 -0
  17. package/src/ui/public/assets/index-cS1g7H--.js +65 -0
  18. package/src/ui/public/assets/{json.worker-BkJRGcCJ.js → json.worker-DzV-CpCQ.js} +1 -1
  19. package/src/ui/public/assets/{ts.worker-B0J26iPs.js → ts.worker-Dth06zuC.js} +15 -15
  20. package/src/ui/public/assets/vendor-B2yudN8R.css +1 -0
  21. package/src/ui/public/assets/{vendor-BMFU1ekz.js → vendor-C1sPhIEb.js} +242 -249
  22. package/src/ui/public/favicon.svg +75 -75
  23. package/src/ui/public/index.html +23 -22
  24. package/src/ui/public/logo.svg +74 -74
  25. package/src/ui/server/index.js +9 -0
  26. package/src/ui/server/routes/workbench.js +1068 -0
  27. package/src/ui/public/assets/EditorView-DDyMmxPI.js +0 -0
  28. package/src/ui/public/assets/SourceMapView-DakscAmd.js +0 -3
  29. package/src/ui/public/assets/SourceMapView-DyMK80hS.css +0 -1
  30. package/src/ui/public/assets/index-CPUqt5Ue.js +0 -73
  31. package/src/ui/public/assets/index-a-r8YYZJ.css +0 -1
  32. package/src/ui/public/assets/vendor-BPPhhD0O.css +0 -1
  33. /package/src/ui/public/assets/{editor.worker-Cn2oRESe.js → editor.worker-Bd9IXS8d.js} +0 -0
  34. /package/src/ui/public/assets/{rolldown-runtime-CMxvf4Kt.js → rolldown-runtime-BM3Ffeng.js} +0 -0
@@ -0,0 +1,1068 @@
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 } 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
+
33
+ // 子项目识别 / 文件扫描时需要跳过的目录
34
+ const SKIP_DIRS = new Set([
35
+ 'node_modules', 'dist', 'build', '.next', '.nuxt', '__pycache__',
36
+ 'target', 'out', 'coverage', 'vendor', '.git', '.svn', '.hg',
37
+ '.idea', '.vscode', '.gradle', '.terraform', '.cache', '.parcel-cache',
38
+ '.turbo', '.svelte-kit', 'storybook-static'
39
+ ]);
40
+
41
+ // 默认生成指令:用户首次使用时作为可编辑指令的初始值
42
+ const DEFAULT_INSTRUCTION = `你是一名资深软件架构师。
43
+
44
+ 【探索步骤】
45
+ 1. 先识别项目结构:扫描根目录是否包含 .git 目录,以及 package.json / pyproject.toml / go.mod / Cargo.toml / pom.xml / build.gradle{,.kts} / composer.json / Gemfile / pubspec.yaml 这 9 种 manifest。
46
+ 2. 如果根目录含 manifest,就把整个根目录视为一个子项目。
47
+ 3. 如果根目录不含 manifest、但子目录(含一层 .git 或上述 manifest)形成多个子项目,对每个子项目分别探索。
48
+ 4. 对每个子项目,重点读取:
49
+ - 所有识别到的 manifest(限制单文件 20KB)
50
+ - README.md(限制 8KB)
51
+ - 入口文件:package.json 的 main / scripts / workspaces 字段;pyproject.toml 的 [project.scripts];go.mod 的 module;Cargo.toml 的 [[bin]];pom.xml 的 <modules>
52
+ - 2 层目录树(最多 200 行)
53
+
54
+ 【输出要求】
55
+ 1. 给出一段 400-800 字的中文「项目架构说明」,覆盖:项目整体定位、技术栈、模块划分、核心流程、关键设计决策。
56
+ 2. 必须引用子项目里实际存在的文件路径、目录名、依赖名,不要编造。
57
+ 3. 多个子项目时:先逐个说明,最后输出一段「整体架构」总结它们之间的关系。
58
+ 4. 语气专业、具体、面向接手这个项目的开发者。
59
+ 5. 只返回 JSON:{ "name": "项目名(10-20字)", "summary": "架构说明正文" }。`;
60
+
61
+ // 单个附件最大 5MB;与 Anthropic Messages API 文档约束一致
62
+ const MAX_IMAGE_BYTES = 5 * 1024 * 1024;
63
+ // 一个子任务最多挂 9 个附件
64
+ const MAX_ATTACHMENTS_PER_SUBTASK = 9;
65
+ // 白名单后缀:图片 + 常见文档(PDF / 纯文本 / Markdown)
66
+ const IMAGE_EXTS = new Set(['png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'svg']);
67
+ const DOC_EXTS = new Set(['pdf', 'txt', 'md', 'markdown', 'csv', 'json', 'log']);
68
+ const ALLOWED_EXTS = new Set([...IMAGE_EXTS, ...DOC_EXTS]);
69
+
70
+ // mime → 文件后缀;与前端 el-upload accept 对齐
71
+ const MIME_TO_EXT = {
72
+ 'image/png': 'png',
73
+ 'image/jpeg': 'jpg',
74
+ 'image/jpg': 'jpg',
75
+ 'image/gif': 'gif',
76
+ 'image/webp': 'webp',
77
+ 'image/bmp': 'bmp',
78
+ 'image/svg+xml': 'svg',
79
+ 'image/x-icon': 'ico',
80
+ 'image/vnd.microsoft.icon': 'ico',
81
+ 'application/pdf': 'pdf',
82
+ 'text/plain': 'txt',
83
+ 'text/markdown': 'md',
84
+ 'text/x-markdown': 'md',
85
+ 'text/csv': 'csv',
86
+ 'application/json': 'json',
87
+ 'text/json': 'json',
88
+ 'text/x-log': 'log',
89
+ };
90
+
91
+ function sanitizeExt(name, fallback = 'bin') {
92
+ if (typeof name !== 'string') return fallback;
93
+ const m = name.toLowerCase().match(/\.([a-z0-9]+)$/);
94
+ if (!m) return fallback;
95
+ return ALLOWED_EXTS.has(m[1]) ? m[1] : fallback;
96
+ }
97
+
98
+ function isImageExt(ext) {
99
+ return IMAGE_EXTS.has(String(ext || '').toLowerCase());
100
+ }
101
+
102
+ async function ensureImagesDir() {
103
+ await fsp.mkdir(IMAGES_DIR, { recursive: true });
104
+ }
105
+
106
+ // 把 mime 或文件名规范成统一后缀;遇到不在白名单的情况返回 null
107
+ function resolveExt({ originalName, mime }) {
108
+ if (mime && MIME_TO_EXT[mime.toLowerCase()]) {
109
+ return MIME_TO_EXT[mime.toLowerCase()];
110
+ }
111
+ const fromName = sanitizeExt(originalName, '');
112
+ if (fromName) return fromName;
113
+ return null;
114
+ }
115
+
116
+ // 解析 manifest 文件名(按优先级)
117
+ const MANIFEST_FILES = [
118
+ 'package.json', 'pyproject.toml', 'go.mod', 'Cargo.toml',
119
+ 'pom.xml', 'build.gradle', 'build.gradle.kts', 'composer.json',
120
+ 'Gemfile', 'pubspec.yaml'
121
+ ];
122
+
123
+ async function readProjectManifest(projectPath) {
124
+ const out = {};
125
+ for (const f of MANIFEST_FILES) {
126
+ const p = path.join(projectPath, f);
127
+ try {
128
+ const stat = await fsp.stat(p);
129
+ if (!stat.isFile()) continue;
130
+ // 限制大小,避免巨型 pom.xml 把上下文打爆
131
+ const content = stat.size > 20000
132
+ ? (await safeReadFile(p, 20000))
133
+ : (await fsp.readFile(p, 'utf8'));
134
+ out[f] = content;
135
+ } catch { /* 不存在就跳过 */ }
136
+ }
137
+ return out;
138
+ }
139
+
140
+ async function safeReadFile(filePath, maxBytes = 200000) {
141
+ try {
142
+ const stat = await fsp.stat(filePath);
143
+ if (stat.size > maxBytes) {
144
+ const buf = Buffer.alloc(maxBytes);
145
+ const fd = await fsp.open(filePath, 'r');
146
+ await fd.read(buf, 0, maxBytes, 0);
147
+ await fd.close();
148
+ return buf.toString('utf8').slice(0, maxBytes);
149
+ }
150
+ return await fsp.readFile(filePath, 'utf8');
151
+ } catch {
152
+ return '';
153
+ }
154
+ }
155
+
156
+ async function listDirTree(projectPath, maxDepth = 2, maxEntries = 400) {
157
+ const lines = [];
158
+ async function walk(dir, depth) {
159
+ if (depth > maxDepth || lines.length >= maxEntries) return;
160
+ let entries;
161
+ try { entries = await fsp.readdir(dir, { withFileTypes: true }); }
162
+ catch { return; }
163
+ const filtered = entries.filter(e => {
164
+ if (e.name.startsWith('.')) return false;
165
+ if (['node_modules', 'dist', 'build', '.next', '.nuxt', '__pycache__', 'target', 'out', 'coverage', 'vendor'].includes(e.name)) return false;
166
+ return true;
167
+ });
168
+ const indent = ' '.repeat(depth);
169
+ for (const e of filtered) {
170
+ if (lines.length >= maxEntries) return;
171
+ if (e.isDirectory()) {
172
+ lines.push(`${indent}${e.name}/`);
173
+ await walk(path.join(dir, e.name), depth + 1);
174
+ } else if (e.isFile()) {
175
+ lines.push(`${indent}${e.name}`);
176
+ }
177
+ }
178
+ }
179
+ await walk(projectPath, 0);
180
+ return lines.join('\n');
181
+ }
182
+
183
+ async function callLlmJson(model, prompt, opts = {}) {
184
+ const { maxTokens = 1500, timeoutMs = 60000 } = opts;
185
+ const { default: fetch } = await import('node-fetch').catch(() => ({ default: globalThis.fetch }));
186
+ const url = `${String(model.baseURL || '').replace(/\/$/, '')}/chat/completions`;
187
+ const headers = { 'Content-Type': 'application/json' };
188
+ if (model.apiKey) headers['Authorization'] = `Bearer ${model.apiKey}`;
189
+
190
+ const body = JSON.stringify({
191
+ model: model.model,
192
+ messages: [{ role: 'user', content: prompt }],
193
+ max_tokens: maxTokens,
194
+ temperature: 0.4,
195
+ response_format: { type: 'json_object' },
196
+ stream: false,
197
+ });
198
+
199
+ const controller = new AbortController();
200
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
201
+ try {
202
+ const resp = await fetch(url, { method: 'POST', headers, body, signal: controller.signal });
203
+ const data = await resp.json().catch(() => ({}));
204
+ if (!resp.ok) throw new Error(data?.error?.message || `HTTP ${resp.status}`);
205
+ const content = data?.choices?.[0]?.message?.content || '{}';
206
+ try {
207
+ const m = content.match(/```json\s*([\s\S]*?)```/) || content.match(/({[\s\S]*})/);
208
+ return JSON.parse(m ? m[1] : content);
209
+ } catch {
210
+ return {};
211
+ }
212
+ } finally {
213
+ clearTimeout(timer);
214
+ }
215
+ }
216
+
217
+ function nowIso() {
218
+ return new Date().toISOString();
219
+ }
220
+
221
+ function genId() {
222
+ return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
223
+ }
224
+
225
+ async function ensureDataDir() {
226
+ await fsp.mkdir(DATA_DIR, { recursive: true });
227
+ }
228
+
229
+ async function readJson(file, fallback) {
230
+ try {
231
+ const buf = await fsp.readFile(file, 'utf-8');
232
+ return JSON.parse(buf);
233
+ } catch (err) {
234
+ if (err && err.code === 'ENOENT') return fallback;
235
+ throw err;
236
+ }
237
+ }
238
+
239
+ async function writeJson(file, data) {
240
+ await ensureDataDir();
241
+ const tmp = `${file}.tmp`;
242
+ await fsp.writeFile(tmp, JSON.stringify(data, null, 2), 'utf-8');
243
+ await fsp.rename(tmp, file);
244
+ }
245
+
246
+ // 简单的 Mustache 风格变量插值:{{task.title}} / {{task.desc}} / {{repo.path}} / {{branch}}
247
+ function interpolate(template, ctx) {
248
+ if (typeof template !== 'string') return template;
249
+ return template.replace(/\{\{\s*([\w.]+)\s*\}\}/g, (_, key) => {
250
+ const parts = key.split('.');
251
+ let cur = ctx;
252
+ for (const p of parts) {
253
+ if (cur == null) return '';
254
+ cur = cur[p];
255
+ }
256
+ return cur == null ? '' : String(cur);
257
+ });
258
+ }
259
+
260
+ // ── 进程表:记录每个子任务的运行状态 ──────────────────────────────────────
261
+ const bus = new EventEmitter();
262
+ const jobs = new Map(); // jobId -> { id, taskId, subId, status, pid, startedAt, endedAt, exitCode, error, prompt }
263
+
264
+ // ── 生成指令持久化(~/.zen-gitsync/ai-instruction.json) ────────────────────
265
+ async function readInstruction() {
266
+ try {
267
+ const buf = await fsp.readFile(INSTRUCTION_FILE, 'utf-8');
268
+ const obj = JSON.parse(buf);
269
+ if (obj && typeof obj.instruction === 'string' && obj.instruction.trim()) {
270
+ return obj.instruction;
271
+ }
272
+ } catch { /* 文件不存在或解析失败 */ }
273
+ return DEFAULT_INSTRUCTION;
274
+ }
275
+
276
+ async function writeInstruction(instruction) {
277
+ await ensureDataDir();
278
+ const text = String(instruction || '').trim() || DEFAULT_INSTRUCTION;
279
+ const tmp = `${INSTRUCTION_FILE}.tmp`;
280
+ await fsp.writeFile(tmp, JSON.stringify({ instruction: text, updatedAt: nowIso() }, null, 2), 'utf-8');
281
+ await fsp.rename(tmp, INSTRUCTION_FILE);
282
+ }
283
+
284
+ // ── 子项目识别:递归找 .git / manifest;A 是 B 的祖先时只保留 B ─────────────
285
+ async function findSubProjects(projectPath, opts = {}) {
286
+ const { maxDepth = 4 } = opts;
287
+ const candidates = [];
288
+
289
+ async function walk(dir, depth) {
290
+ if (depth > maxDepth) return;
291
+ let entries;
292
+ try { entries = await fsp.readdir(dir, { withFileTypes: true }); }
293
+ catch { return; }
294
+
295
+ let hasManifest = false;
296
+ let hasGit = false;
297
+ const subDirs = [];
298
+ for (const e of entries) {
299
+ if (!e.isDirectory() && !e.isFile()) continue;
300
+ if (e.name.startsWith('.')) {
301
+ if (e.name === '.git' && e.isDirectory()) hasGit = true;
302
+ continue;
303
+ }
304
+ if (e.isDirectory()) {
305
+ if (SKIP_DIRS.has(e.name)) continue;
306
+ subDirs.push(path.join(dir, e.name));
307
+ } else if (e.isFile() && MANIFEST_FILES.includes(e.name)) {
308
+ hasManifest = true;
309
+ }
310
+ }
311
+ if (hasManifest || hasGit) {
312
+ candidates.push(dir);
313
+ return; // 子目录里若还有 manifest,会被自己发现;这里不再下钻避免冗余
314
+ }
315
+ if (depth >= maxDepth) return;
316
+ for (const sub of subDirs) {
317
+ await walk(sub, depth + 1);
318
+ }
319
+ }
320
+
321
+ await walk(projectPath, 0);
322
+
323
+ // 去重:若 candidates 里 A 是 B 的祖先,只保留更深一级的 B
324
+ candidates.sort((a, b) => a.length - b.length);
325
+ const kept = [];
326
+ for (const c of candidates) {
327
+ let dominated = false;
328
+ for (const k of kept) {
329
+ if (c === k || c.startsWith(k + path.sep)) { dominated = true; break; }
330
+ }
331
+ if (!dominated) kept.push(c);
332
+ }
333
+
334
+ // 收集每个子项目的关键文件
335
+ const result = [];
336
+ for (const root of kept) {
337
+ const manifests = {};
338
+ for (const m of MANIFEST_FILES) {
339
+ const p = path.join(root, m);
340
+ try {
341
+ const stat = await fsp.stat(p);
342
+ if (stat.isFile()) {
343
+ manifests[m] = stat.size > 20000
344
+ ? await safeReadFile(p, 20000)
345
+ : await fsp.readFile(p, 'utf8');
346
+ }
347
+ } catch { /* 不存在就跳过 */ }
348
+ }
349
+ let readme = '';
350
+ try {
351
+ const stat = await fsp.stat(path.join(root, 'README.md'));
352
+ if (stat.isFile()) readme = await safeReadFile(path.join(root, 'README.md'), 8000);
353
+ } catch { /* 不存在就跳过 */ }
354
+ const dirTree = await listDirTree(root, 2, 200);
355
+ result.push({
356
+ root,
357
+ name: path.basename(root) || path.basename(projectPath),
358
+ manifests,
359
+ readme,
360
+ dirTree
361
+ });
362
+ }
363
+ return result;
364
+ }
365
+
366
+ function publish(event, payload) {
367
+ bus.emit('event', { event, payload, ts: nowIso() });
368
+ }
369
+
370
+ function snapshotJobs() {
371
+ return Array.from(jobs.values()).map(j => ({
372
+ id: j.id,
373
+ taskId: j.taskId,
374
+ subId: j.subId,
375
+ title: j.title,
376
+ status: j.status,
377
+ prompt: j.prompt || '',
378
+ output: j.output || '',
379
+ pid: j.pid || null,
380
+ startedAt: j.startedAt || null,
381
+ endedAt: j.endedAt || null,
382
+ exitCode: typeof j.exitCode === 'number' ? j.exitCode : null,
383
+ error: j.error || null
384
+ }));
385
+ }
386
+
387
+ // 用 detached 进程跑 claude;进程退出时回填状态。
388
+ // 返回 { pid, child }:调用方可以监听 child.stdout/stderr 实时收集输出。
389
+ // 不再走 cmd /k 弹窗——claude -p 是非交互模式,输出通过 stdout pipe 实时回传
390
+ // 到前端面板展示。
391
+ function launchClaudeInNewWindow(cwd, promptText) {
392
+ return new Promise((resolve, reject) => {
393
+ const args = [
394
+ '-p', promptText,
395
+ '--output-format', 'text',
396
+ '--permission-mode', 'bypassPermissions',
397
+ '--dangerously-skip-permissions'
398
+ ];
399
+ let child;
400
+ let spawnedExe = 'claude';
401
+ if (process.platform === 'win32') {
402
+ // 直接 spawn claude.exe(npm 全局 @anthropic-ai/claude-code 里的真实二进制),
403
+ // 避开两件事:
404
+ // 1. Node 23 在 Windows 上拒绝 spawn .cmd/.bat(EINVAL)
405
+ // 2. shell:true 会把 argv 拼成命令行交给 cmd 解释,prompt 里的 \n 被切成多段
406
+ // 用 `where claude` 找到 claude.cmd,再从 cmd 内容推断对应 .exe 路径。
407
+ let claudeExe = 'claude.exe';
408
+ try {
409
+ const cmdShim = execFileSync('where', ['claude'], { encoding: 'utf8' })
410
+ .split(/\r?\n/).map(s => s.trim()).find(s => /\.cmd$/i.test(s));
411
+ if (cmdShim) {
412
+ const txt = fs.readFileSync(cmdShim, 'utf8');
413
+ if (/%dp0%\\node_modules\\@anthropic-ai\\claude-code\\bin\\claude\.exe/i.test(txt)) {
414
+ claudeExe = path.join(path.dirname(cmdShim), 'node_modules', '@anthropic-ai', 'claude-code', 'bin', 'claude.exe');
415
+ }
416
+ }
417
+ } catch { /* fallback */ }
418
+ spawnedExe = claudeExe;
419
+ child = spawn(claudeExe, args, {
420
+ cwd,
421
+ stdio: ['ignore', 'pipe', 'pipe'],
422
+ windowsHide: false,
423
+ env: { ...process.env, LANG: 'zh_CN.UTF-8' }
424
+ });
425
+ } else {
426
+ // macOS / Linux:直接 spawn claude(Node spawn 不走 shell,
427
+ // prompt 中的引号 / 反斜杠无需手动 escape)
428
+ child = spawn('claude', args, {
429
+ cwd,
430
+ detached: true,
431
+ stdio: ['ignore', 'pipe', 'pipe'],
432
+ env: { ...process.env, LANG: 'zh_CN.UTF-8' }
433
+ });
434
+ }
435
+ child.on('error', reject);
436
+ child.on('spawn', () => {
437
+ // unref 让 claude 独立于父进程事件循环;返回 child 引用让调用方继续读 stdout。
438
+ child.unref();
439
+ resolve({ pid: child.pid, child });
440
+ });
441
+ });
442
+ }
443
+
444
+ // 顺序执行一个任务下所有子任务;上一个结束再启动下一个
445
+ async function runTaskQueue(task, repoPath, branch) {
446
+ for (const sub of task.subtasks) {
447
+ if (sub.status === 'done') continue;
448
+ const promptTemplate = sub.promptOverride || (task.promptId
449
+ ? (await readJson(PROMPTS_FILE, { prompts: [] })).prompts.find(p => p.id === task.promptId)?.content
450
+ : null) || '';
451
+ const ctx = {
452
+ task: { title: task.title, desc: task.desc || '' },
453
+ sub: { title: sub.title, desc: sub.desc || '' },
454
+ repo: { path: repoPath || '' },
455
+ branch: branch || ''
456
+ };
457
+ const interpolated = interpolate(promptTemplate, ctx);
458
+ const parts = [interpolated, sub.title, sub.desc].filter(s => s && s.trim());
459
+ let prompt = parts.join('\n\n');
460
+
461
+ // ── 附件:把 sub.attachments 列表里的本地绝对路径拼到 prompt 末尾 ──
462
+ // claude -p 字符串模式会扫描 prompt 中出现的本地文件路径并自动
463
+ // 识别为附件(图片 / PDF / 文本均可)。
464
+ const attachments = Array.isArray(sub.attachments) ? sub.attachments : [];
465
+ if (attachments.length > 0) {
466
+ const lines = attachments
467
+ .filter(a => a && a.absolutePath)
468
+ .map((a, i) => ` ${i + 1}. [${a.mimeType || 'application/octet-stream'}] ${a.absolutePath}`);
469
+ if (lines.length > 0) {
470
+ prompt += `\n\n---\n本子任务包含 ${lines.length} 个附件(请按文件路径读取,不要让用户重新提供):\n${lines.join('\n')}\n---`;
471
+ }
472
+ }
473
+
474
+ const jobId = genId();
475
+ const job = {
476
+ id: jobId,
477
+ taskId: task.id,
478
+ subId: sub.id,
479
+ title: `${task.title} / ${sub.title}`,
480
+ status: 'pending',
481
+ prompt
482
+ };
483
+ jobs.set(jobId, job);
484
+ sub.status = 'running';
485
+ publish('sub:update', { taskId: task.id, sub });
486
+ publish('job:update', job);
487
+
488
+ try {
489
+ const { pid, child } = await launchClaudeInNewWindow(repoPath || process.cwd(), prompt);
490
+ job.pid = pid;
491
+ job.startedAt = nowIso();
492
+ job.status = 'running';
493
+ publish('job:update', job);
494
+
495
+ // 累积子进程输出到 job.output,定期推送给前端;过长时截断尾部避免内存膨胀。
496
+ const MAX_OUTPUT = 256 * 1024;
497
+ const onChunk = (buf) => {
498
+ const text = buf.toString('utf8');
499
+ job.output = (job.output + text).slice(-MAX_OUTPUT);
500
+ publish('job:update', job);
501
+ };
502
+ if (child.stdout) child.stdout.on('data', onChunk);
503
+ if (child.stderr) child.stderr.on('data', onChunk);
504
+
505
+ // 等待进程退出(detached 不阻塞主进程,用 polling /proc 兜底)
506
+ await waitProcessExit(pid);
507
+ job.endedAt = nowIso();
508
+ job.exitCode = 0;
509
+ job.status = 'done';
510
+ sub.status = 'done';
511
+ } catch (err) {
512
+ job.error = err && err.message ? err.message : String(err);
513
+ job.status = 'error';
514
+ sub.status = 'error';
515
+ } finally {
516
+ publish('job:update', job);
517
+ publish('sub:update', { taskId: task.id, sub });
518
+ }
519
+ }
520
+ // 写回 tasks.json
521
+ const data = await readJson(TASKS_FILE, { tasks: [] });
522
+ const t = data.tasks.find(x => x.id === task.id);
523
+ if (t) {
524
+ t.subtasks = task.subtasks;
525
+ t.updatedAt = nowIso();
526
+ await writeJson(TASKS_FILE, data);
527
+ publish('task:update', t);
528
+ }
529
+ }
530
+
531
+ function waitProcessExit(pid) {
532
+ return new Promise(resolve => {
533
+ let exited = false;
534
+ const tryCheck = () => {
535
+ if (exited) return;
536
+ try {
537
+ process.kill(pid, 0); // 信号 0 = 探测存活
538
+ } catch (err) {
539
+ // 只在进程真的消失(ESRCH / EPERM)时才 resolve;
540
+ // 其他错误(比如参数类型)保留 polling 状态,由超时兜底。
541
+ if (err && (err.code === 'ESRCH' || err.code === 'EPERM')) {
542
+ exited = true;
543
+ resolve();
544
+ return;
545
+ }
546
+ }
547
+ setTimeout(tryCheck, 1500);
548
+ };
549
+ tryCheck();
550
+ // 兜底:30 分钟超时自动结束
551
+ setTimeout(() => { if (!exited) { exited = true; resolve(); } }, 30 * 60 * 1000);
552
+ });
553
+ }
554
+
555
+ export function registerWorkbenchRoutes({ app, getCurrentProjectPath, getProjectRoomId, io, configManager }) {
556
+ // ── AI 生成提示词(基于当前项目) ─────────────────────────────────────
557
+ app.post('/api/workbench/prompts/ai-generate', async (req, res) => {
558
+ try {
559
+ const projectPath = typeof getCurrentProjectPath === 'function' ? getCurrentProjectPath() : '';
560
+ if (!projectPath) {
561
+ return res.status(400).json({ success: false, error: '未选中项目' });
562
+ }
563
+ let stat;
564
+ try { stat = await fsp.stat(projectPath); }
565
+ catch { return res.status(400).json({ success: false, error: '项目路径不存在' }); }
566
+ if (!stat.isDirectory()) {
567
+ return res.status(400).json({ success: false, error: '项目路径不是目录' });
568
+ }
569
+
570
+ // 取模型
571
+ let model;
572
+ try {
573
+ if (!configManager) throw new Error('configManager 不可用');
574
+ const rawConfig = await configManager.readRawConfigFile();
575
+ const models = Array.isArray(rawConfig.models) ? rawConfig.models : [];
576
+ model = models.find(m => m.isDefault) || models[0];
577
+ } catch (err) {
578
+ return res.status(500).json({ success: false, error: '读取 AI 配置失败: ' + err.message });
579
+ }
580
+ if (!model) {
581
+ return res.status(400).json({ success: false, error: '未配置 AI 模型,请先在通用设置中添加模型' });
582
+ }
583
+
584
+ // 读取用户可编辑的生成指令;没存就用默认
585
+ const userInstruction = await readInstruction();
586
+
587
+ // 递归识别多子项目
588
+ const subProjects = await findSubProjects(projectPath);
589
+ if (subProjects.length === 0) {
590
+ // 没识别到任何子项目:回退到根目录本身
591
+ const fallbackTree = await listDirTree(projectPath, 2, 400);
592
+ const fallbackManifest = await readProjectManifest(projectPath);
593
+ const fallbackReadme = await safeReadFile(path.join(projectPath, 'README.md'), 8000);
594
+ subProjects.push({
595
+ root: projectPath,
596
+ name: path.basename(projectPath),
597
+ manifests: fallbackManifest,
598
+ readme: fallbackReadme,
599
+ dirTree: fallbackTree
600
+ });
601
+ }
602
+
603
+ const projectName = path.basename(projectPath);
604
+ const LLM_OPTS = { maxTokens: 4000, timeoutMs: 1200000 };
605
+
606
+ // ── 第一阶段:基于可编辑指令 + 根目录概览,生成「可复用的提示词模板」 ──
607
+ const overviewBlock = subProjects.map(sp =>
608
+ `### 子项目 ${sp.name} (${sp.root})\n目录:\n${sp.dirTree || '(无)'}`
609
+ ).join('\n\n');
610
+
611
+ const firstPrompt = `${userInstruction}
612
+
613
+ ---
614
+
615
+ 以下是你需要分析的项目(请先生成「可复用的提示词模板」,不要直接给总结):
616
+
617
+ 项目根目录:${projectPath}
618
+ 项目名称:${projectName}
619
+ 子项目数:${subProjects.length}
620
+
621
+ ## 子项目概览
622
+ ${overviewBlock || '(无)'}
623
+
624
+ ## 各子项目 manifest 与 README
625
+ ${subProjects.map(sp => {
626
+ const manifestBlock = Object.entries(sp.manifests)
627
+ .map(([n, c]) => `\n--- ${n} ---\n${c}`)
628
+ .join('\n');
629
+ return `\n### ${sp.name}\n${manifestBlock || '(无 manifest)'}\n\nREADME(前 8KB):\n${sp.readme || '(无)'}`;
630
+ }).join('\n')}
631
+
632
+ 只返回 JSON:
633
+ {
634
+ "name": "项目名(10-20字)",
635
+ "template": "可复用的提示词模板(300-600字),应明确使用 {{task.title}} / {{task.desc}} / {{sub.title}} / {{sub.desc}} / {{repo.path}} / {{branch}} 这 6 个变量"
636
+ }`;
637
+
638
+ const first = await callLlmJson(model, firstPrompt, LLM_OPTS);
639
+ const templateName = String(first.name || '').trim() || projectName || '项目架构说明';
640
+ const template = String(first.template || '').trim();
641
+
642
+ // ── 第二阶段:为每个子项目分别生成总结(单子项目 = 现在的行为) ──
643
+ async function summarizeOneSub(sp) {
644
+ const manifestBlock = Object.entries(sp.manifests)
645
+ .map(([n, c]) => `\n--- ${n} ---\n${c}`)
646
+ .join('\n');
647
+ const subPrompt = `${template}
648
+
649
+ ---
650
+
651
+ 以下是你需要分析的一个子项目(请直接基于这些数据输出该子项目的架构说明):
652
+
653
+ 子项目根目录:${sp.root}
654
+ 子项目名称:${sp.name}
655
+
656
+ ## 目录结构(前 2 层)
657
+ ${sp.dirTree || '(无)'}
658
+
659
+ ## manifest
660
+ ${manifestBlock || '(无)'}
661
+
662
+ ## README
663
+ ${sp.readme || '(无)'}
664
+
665
+ 只返回 JSON:
666
+ {
667
+ "summary": "该子项目的架构说明(300-600字)"
668
+ }`;
669
+ const r = await callLlmJson(model, subPrompt, LLM_OPTS);
670
+ return { name: sp.name, root: sp.root, summary: String(r.summary || '').trim() };
671
+ }
672
+
673
+ const subSummaries = await Promise.all(subProjects.map(summarizeOneSub));
674
+
675
+ // ── 第三阶段:仅多子项目时合并(单子项目直接拿它的 summary) ──
676
+ let finalSummary = '';
677
+ let finalName = templateName;
678
+
679
+ if (subSummaries.length === 1) {
680
+ finalSummary = subSummaries[0].summary;
681
+ } else {
682
+ const mergePrompt = `你是项目架构师。下列是同一仓库下 N 个子项目的架构说明,请合并输出**单一**的「项目架构说明」(800-1500字),覆盖:项目整体定位、技术栈、模块划分、子项目间关系、核心流程、关键设计决策。
683
+ 子项目之间用清晰的小标题或编号分隔。最后输出一段「整体架构」总结它们如何协同。
684
+ 只引用实际出现的子项目名 / 文件路径 / 依赖名,不要编造。只返回 JSON:
685
+
686
+ {
687
+ "name": "项目名(10-20字)",
688
+ "summary": "合并后的架构说明"
689
+ }
690
+
691
+ ## 子项目说明
692
+ ${subSummaries.map((s, i) => `\n### [${i + 1}] ${s.name} (${s.root})\n${s.summary || '(空)'}`).join('\n')}`;
693
+
694
+ const merged = await callLlmJson(model, mergePrompt, LLM_OPTS);
695
+ finalSummary = String(merged.summary || '').trim()
696
+ || subSummaries.map(s => `### ${s.name}\n${s.summary}`).join('\n\n');
697
+ finalName = String(merged.name || '').trim() || templateName;
698
+ }
699
+
700
+ if (!finalSummary) {
701
+ // 兜底:仅返回模板
702
+ return res.json({
703
+ success: true,
704
+ name: finalName,
705
+ template,
706
+ result: '',
707
+ content: template
708
+ });
709
+ }
710
+
711
+ // 顶层 request 已经自带 20 分钟(1200s)超时;
712
+ // 这里在 express 处理器内部不再额外加整体超时。
713
+ res.json({
714
+ success: true,
715
+ name: finalName,
716
+ template,
717
+ result: finalSummary,
718
+ content: finalSummary
719
+ });
720
+ } catch (err) {
721
+ res.status(500).json({ success: false, error: err.message });
722
+ }
723
+ });
724
+
725
+ // ── 生成指令:读 / 写(用户可在弹窗里自定义) ───────────────────────
726
+ app.get('/api/workbench/prompts/ai-instruction', async (_req, res) => {
727
+ try {
728
+ const instruction = await readInstruction();
729
+ res.json({ success: true, instruction, isDefault: instruction === DEFAULT_INSTRUCTION });
730
+ } catch (err) {
731
+ res.status(500).json({ success: false, error: err.message });
732
+ }
733
+ });
734
+
735
+ app.put('/api/workbench/prompts/ai-instruction', async (req, res) => {
736
+ try {
737
+ const text = req.body && typeof req.body.instruction === 'string'
738
+ ? req.body.instruction.trim()
739
+ : '';
740
+ if (!text) {
741
+ return res.status(400).json({ success: false, error: '指令不能为空' });
742
+ }
743
+ if (text.length > 50000) {
744
+ return res.status(413).json({ success: false, error: '指令过长(最多 50000 字符)' });
745
+ }
746
+ await writeInstruction(text);
747
+ res.json({ success: true });
748
+ } catch (err) {
749
+ res.status(500).json({ success: false, error: err.message });
750
+ }
751
+ });
752
+
753
+ // SSE 事件流
754
+ app.get('/api/workbench/events', (req, res) => {
755
+ res.set({
756
+ 'Content-Type': 'text/event-stream',
757
+ 'Cache-Control': 'no-cache, no-transform',
758
+ 'Connection': 'keep-alive',
759
+ 'X-Accel-Buffering': 'no'
760
+ });
761
+ res.flushHeaders?.();
762
+ const send = (data) => {
763
+ res.write(`data: ${JSON.stringify(data)}\n\n`);
764
+ };
765
+ // 初始快照
766
+ send({ event: 'hello', payload: { jobs: snapshotJobs() }, ts: nowIso() });
767
+ const handler = (evt) => send(evt);
768
+ bus.on('event', handler);
769
+ const ka = setInterval(() => res.write(`: keep-alive\n\n`), 15000);
770
+ req.on('close', () => {
771
+ clearInterval(ka);
772
+ bus.off('event', handler);
773
+ });
774
+ });
775
+
776
+ // ── 提示词 CRUD ─────────────────────────────────────────────────────
777
+ app.get('/api/workbench/prompts', async (_req, res) => {
778
+ try {
779
+ const data = await readJson(PROMPTS_FILE, { prompts: [] });
780
+ res.json({ success: true, prompts: data.prompts || [] });
781
+ } catch (err) {
782
+ res.status(500).json({ success: false, error: err.message });
783
+ }
784
+ });
785
+
786
+ app.post('/api/workbench/prompts', async (req, res) => {
787
+ try {
788
+ const { id, name, content } = req.body || {};
789
+ if (!name || typeof content !== 'string') {
790
+ return res.status(400).json({ success: false, error: 'name 和 content 必填' });
791
+ }
792
+ const data = await readJson(PROMPTS_FILE, { prompts: [] });
793
+ const prompts = data.prompts || [];
794
+ const now = nowIso();
795
+ if (id) {
796
+ const i = prompts.findIndex(p => p.id === id);
797
+ if (i < 0) return res.status(404).json({ success: false, error: '提示词不存在' });
798
+ prompts[i] = { ...prompts[i], name, content, updatedAt: now };
799
+ await writeJson(PROMPTS_FILE, { prompts });
800
+ return res.json({ success: true, prompt: prompts[i] });
801
+ }
802
+ const prompt = { id: genId(), name, content, createdAt: now, updatedAt: now };
803
+ prompts.push(prompt);
804
+ await writeJson(PROMPTS_FILE, { prompts });
805
+ res.json({ success: true, prompt });
806
+ } catch (err) {
807
+ res.status(500).json({ success: false, error: err.message });
808
+ }
809
+ });
810
+
811
+ app.delete('/api/workbench/prompts/:id', async (req, res) => {
812
+ try {
813
+ const data = await readJson(PROMPTS_FILE, { prompts: [] });
814
+ const prompts = (data.prompts || []).filter(p => p.id !== req.params.id);
815
+ await writeJson(PROMPTS_FILE, { prompts });
816
+ res.json({ success: true });
817
+ } catch (err) {
818
+ res.status(500).json({ success: false, error: err.message });
819
+ }
820
+ });
821
+
822
+ // ── 任务 CRUD ───────────────────────────────────────────────────────
823
+ app.get('/api/workbench/tasks', async (_req, res) => {
824
+ try {
825
+ const data = await readJson(TASKS_FILE, { tasks: [] });
826
+ res.json({ success: true, tasks: data.tasks || [] });
827
+ } catch (err) {
828
+ res.status(500).json({ success: false, error: err.message });
829
+ }
830
+ });
831
+
832
+ app.post('/api/workbench/tasks', async (req, res) => {
833
+ try {
834
+ const { id, title, desc, promptId, subtasks } = req.body || {};
835
+ if (!title) return res.status(400).json({ success: false, error: 'title 必填' });
836
+ const data = await readJson(TASKS_FILE, { tasks: [] });
837
+ const tasks = data.tasks || [];
838
+ const now = nowIso();
839
+ if (id) {
840
+ const i = tasks.findIndex(t => t.id === id);
841
+ if (i < 0) return res.status(404).json({ success: false, error: '任务不存在' });
842
+ tasks[i] = {
843
+ ...tasks[i],
844
+ title,
845
+ desc: desc || '',
846
+ promptId: promptId || null,
847
+ subtasks: Array.isArray(subtasks) ? subtasks.map(s => ({
848
+ id: s.id || genId(),
849
+ title: s.title || '',
850
+ desc: s.desc || '',
851
+ status: s.status || 'todo',
852
+ promptOverride: s.promptOverride || '',
853
+ // 保留附件元数据(仅保留基础字段,丢弃客户端临时字段)
854
+ attachments: Array.isArray(s.attachments) ? s.attachments.map(a => ({
855
+ id: a.id,
856
+ originalName: a.originalName,
857
+ mimeType: a.mimeType,
858
+ size: a.size,
859
+ ext: a.ext,
860
+ storedName: a.storedName,
861
+ absolutePath: a.absolutePath,
862
+ createdAt: a.createdAt
863
+ })) : (tasks[i].subtasks.find(x => x.id === s.id)?.attachments || [])
864
+ })) : tasks[i].subtasks,
865
+ updatedAt: now
866
+ };
867
+ await writeJson(TASKS_FILE, { tasks });
868
+ return res.json({ success: true, task: tasks[i] });
869
+ }
870
+ const task = {
871
+ id: genId(),
872
+ title,
873
+ desc: desc || '',
874
+ promptId: promptId || null,
875
+ subtasks: Array.isArray(subtasks) ? subtasks.map(s => ({
876
+ id: s.id || genId(),
877
+ title: s.title || '',
878
+ desc: s.desc || '',
879
+ status: s.status || 'todo',
880
+ promptOverride: s.promptOverride || '',
881
+ attachments: Array.isArray(s.attachments) ? s.attachments : []
882
+ })) : [],
883
+ status: 'todo',
884
+ createdAt: now,
885
+ updatedAt: now
886
+ };
887
+ tasks.push(task);
888
+ await writeJson(TASKS_FILE, { tasks });
889
+ res.json({ success: true, task });
890
+ } catch (err) {
891
+ res.status(500).json({ success: false, error: err.message });
892
+ }
893
+ });
894
+
895
+ app.delete('/api/workbench/tasks/:id', async (req, res) => {
896
+ try {
897
+ const data = await readJson(TASKS_FILE, { tasks: [] });
898
+ const tasks = (data.tasks || []).filter(t => t.id !== req.params.id);
899
+ await writeJson(TASKS_FILE, { tasks });
900
+ res.json({ success: true });
901
+ } catch (err) {
902
+ res.status(500).json({ success: false, error: err.message });
903
+ }
904
+ });
905
+
906
+ // ── 执行任务 ────────────────────────────────────────────────────────
907
+ app.post('/api/workbench/tasks/:id/run', async (req, res) => {
908
+ try {
909
+ const data = await readJson(TASKS_FILE, { tasks: [] });
910
+ const task = (data.tasks || []).find(t => t.id === req.params.id);
911
+ if (!task) return res.status(404).json({ success: false, error: '任务不存在' });
912
+ if (!task.subtasks || task.subtasks.length === 0) {
913
+ return res.status(400).json({ success: false, error: '任务没有子任务' });
914
+ }
915
+ const repoPath = typeof getCurrentProjectPath === 'function' ? getCurrentProjectPath() : '';
916
+ // 异步执行,立即返回
917
+ res.json({ success: true, message: '已开始执行' });
918
+ runTaskQueue(task, repoPath, '').catch(err => {
919
+ publish('task:error', { taskId: task.id, error: err.message });
920
+ });
921
+ } catch (err) {
922
+ res.status(500).json({ success: false, error: err.message });
923
+ }
924
+ });
925
+
926
+ // ── 进程状态查询(兜底,SSE 断了也能拉) ────────────────────────────
927
+ app.get('/api/workbench/jobs', (_req, res) => {
928
+ res.json({ success: true, jobs: snapshotJobs() });
929
+ });
930
+
931
+ // ── 子任务附件:上传 / 删除 / 列表 ───────────────────────────────
932
+ // 上传:POST /api/workbench/subtasks/:subId/attachments
933
+ // header: X-Original-Name, X-Mime-Type
934
+ // body: raw binary
935
+ // 删除:DELETE /api/workbench/subtasks/:subId/attachments/:attId
936
+ // 列表:GET /api/workbench/subtasks/:subId/attachments
937
+ //
938
+ // 文件存到 ~/.zen-gitsync/workbench-images/{subId}/{attId}.{ext}
939
+ // 元数据(id / originalName / mime / size / storedName)通过 sub.attachments
940
+ // 跟随 tasks.json 一起持久化。
941
+ const rawAttachment = express.raw({
942
+ type: '*/*',
943
+ limit: MAX_IMAGE_BYTES * 4 // 整体路由上限 20MB;单文件大小由业务再卡
944
+ });
945
+
946
+ app.post('/api/workbench/subtasks/:subId/attachments', rawAttachment, async (req, res) => {
947
+ try {
948
+ const { subId } = req.params;
949
+ if (!req.body || !(req.body instanceof Buffer) || req.body.length === 0) {
950
+ return res.status(400).json({ success: false, error: '请求体为空' });
951
+ }
952
+ if (req.body.length > MAX_IMAGE_BYTES) {
953
+ return res.status(413).json({ success: false, error: `单文件不得超过 ${MAX_IMAGE_BYTES / 1024 / 1024}MB` });
954
+ }
955
+ const originalName = String(req.get('X-Original-Name') || 'attachment').slice(0, 200);
956
+ const mimeType = String(req.get('X-Mime-Type') || 'application/octet-stream').slice(0, 120);
957
+ const ext = resolveExt({ originalName, mime: mimeType });
958
+ if (!ext) {
959
+ return res.status(400).json({ success: false, error: `不支持的文件类型(仅允许 ${[...ALLOWED_EXTS].join(', ')})` });
960
+ }
961
+
962
+ // 找到子任务,校验数量
963
+ const data = await readJson(TASKS_FILE, { tasks: [] });
964
+ let foundTask = null;
965
+ let foundSub = null;
966
+ for (const t of data.tasks || []) {
967
+ const s = (t.subtasks || []).find(x => x.id === subId);
968
+ if (s) { foundTask = t; foundSub = s; break; }
969
+ }
970
+ if (!foundSub) {
971
+ return res.status(404).json({ success: false, error: '子任务不存在' });
972
+ }
973
+ if (!Array.isArray(foundSub.attachments)) foundSub.attachments = [];
974
+ if (foundSub.attachments.length >= MAX_ATTACHMENTS_PER_SUBTASK) {
975
+ return res.status(400).json({
976
+ success: false,
977
+ error: `每个子任务最多 ${MAX_ATTACHMENTS_PER_SUBTASK} 个附件`
978
+ });
979
+ }
980
+
981
+ // 写入磁盘:~/.zen-gitsync/workbench-images/{subId}/{attId}.{ext}
982
+ const attId = genId();
983
+ const subDir = path.join(IMAGES_DIR, subId);
984
+ await fsp.mkdir(subDir, { recursive: true });
985
+ const storedName = `${attId}.${ext}`;
986
+ const storedPath = path.join(subDir, storedName);
987
+ await fsp.writeFile(storedPath, req.body);
988
+
989
+ const attachment = {
990
+ id: attId,
991
+ originalName,
992
+ mimeType,
993
+ size: req.body.length,
994
+ ext,
995
+ storedName,
996
+ // 绝对路径供 claude CLI 读取;同机直接读本地
997
+ absolutePath: storedPath,
998
+ createdAt: nowIso()
999
+ };
1000
+ foundSub.attachments.push(attachment);
1001
+ foundSub.updatedAt = nowIso();
1002
+ await writeJson(TASKS_FILE, data);
1003
+
1004
+ res.json({ success: true, attachment });
1005
+ } catch (err) {
1006
+ res.status(500).json({ success: false, error: err.message });
1007
+ }
1008
+ });
1009
+
1010
+ app.delete('/api/workbench/subtasks/:subId/attachments/:attId', async (req, res) => {
1011
+ try {
1012
+ const { subId, attId } = req.params;
1013
+ const data = await readJson(TASKS_FILE, { tasks: [] });
1014
+ let foundTask = null;
1015
+ let foundSub = null;
1016
+ for (const t of data.tasks || []) {
1017
+ const s = (t.subtasks || []).find(x => x.id === subId);
1018
+ if (s) { foundTask = t; foundSub = s; break; }
1019
+ }
1020
+ if (!foundSub) return res.status(404).json({ success: false, error: '子任务不存在' });
1021
+ const list = Array.isArray(foundSub.attachments) ? foundSub.attachments : [];
1022
+ const i = list.findIndex(a => a.id === attId);
1023
+ if (i < 0) return res.status(404).json({ success: false, error: '附件不存在' });
1024
+ const [removed] = list.splice(i, 1);
1025
+ // 删磁盘文件
1026
+ try {
1027
+ await fsp.unlink(path.join(IMAGES_DIR, subId, removed.storedName));
1028
+ } catch { /* 文件可能已不存在,忽略 */ }
1029
+ foundSub.updatedAt = nowIso();
1030
+ await writeJson(TASKS_FILE, data);
1031
+ res.json({ success: true });
1032
+ } catch (err) {
1033
+ res.status(500).json({ success: false, error: err.message });
1034
+ }
1035
+ });
1036
+
1037
+ // 附件原文件读取(前端 <img> 缩略图用)
1038
+ app.get('/api/workbench/attachments/:attId/raw', async (req, res) => {
1039
+ try {
1040
+ const { attId } = req.params;
1041
+ const data = await readJson(TASKS_FILE, { tasks: [] });
1042
+ let found = null;
1043
+ let parentSubId = null;
1044
+ for (const t of data.tasks || []) {
1045
+ for (const s of t.subtasks || []) {
1046
+ const a = (s.attachments || []).find(x => x.id === attId);
1047
+ if (a) { found = a; parentSubId = s.id; break; }
1048
+ }
1049
+ if (found) break;
1050
+ }
1051
+ if (!found) return res.status(404).json({ success: false, error: '附件不存在' });
1052
+ const filePath = path.join(IMAGES_DIR, parentSubId, found.storedName);
1053
+ try {
1054
+ const stat = await fsp.stat(filePath);
1055
+ res.set('Content-Type', found.mimeType || 'application/octet-stream');
1056
+ res.set('Content-Length', String(stat.size));
1057
+ res.set('Cache-Control', 'private, max-age=3600');
1058
+ const stream = (await import('fs')).createReadStream(filePath);
1059
+ stream.on('error', () => res.end());
1060
+ stream.pipe(res);
1061
+ } catch {
1062
+ res.status(404).json({ success: false, error: '文件已丢失' });
1063
+ }
1064
+ } catch (err) {
1065
+ res.status(500).json({ success: false, error: err.message });
1066
+ }
1067
+ });
1068
+ }