agiledev-cli 0.1.5 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +300 -185
- package/SKILL.md +114 -98
- package/adev.js +1319 -1285
- package/autofix/agents/antigravity.js +379 -0
- package/autofix/agents/claude.js +147 -0
- package/autofix/agents/codex.js +179 -0
- package/autofix/agents/exec.js +230 -0
- package/autofix/agents/index.js +400 -0
- package/autofix/agents/opencode.js +233 -0
- package/autofix/agents/pi.js +247 -0
- package/autofix/agiledev.js +98 -0
- package/autofix/bridge.js +371 -0
- package/autofix/cli.js +712 -0
- package/autofix/context.js +152 -0
- package/autofix/conversation.js +302 -0
- package/autofix/coordinator.js +2892 -0
- package/autofix/git.js +459 -0
- package/autofix/policy.js +230 -0
- package/autofix/profile.js +578 -0
- package/autofix/public/app.js +3668 -0
- package/autofix/public/i18n-id.js +282 -0
- package/autofix/public/index.html +32 -0
- package/autofix/public/style.css +2463 -0
- package/autofix/queue.js +146 -0
- package/autofix/scheduler.js +994 -0
- package/autofix/scope.js +32 -0
- package/autofix/service.js +1940 -0
- package/autofix/store.js +375 -0
- package/autofix/workspace.js +298 -0
- package/autofix/worktree.js +379 -0
- package/docs/autofix-design.md +801 -0
- package/docs/autofix-profiles.example.json +65 -0
- package/imgs/Bug/350/247/243/345/206/263/345/244/207/346/263/250.png +0 -0
- package/imgs/logo.png +0 -0
- package/imgs//344/277/256/346/224/271Bug/347/212/266/346/200/201.png +0 -0
- package/imgs//345/270/256/346/210/221/344/277/256/345/244/215Bug-20260922-010.png +0 -0
- package/imgs//346/237/245/347/234/213/345/271/266/345/210/206/346/236/220/351/234/200/346/261/202/346/226/207/346/241/243.png +0 -0
- package/imgs//347/234/213/344/270/200/344/270/213/346/210/221/347/216/260/345/234/250/346/234/211/345/223/252/344/272/233/345/274/200/345/217/221/344/273/273/345/212/241.png +0 -0
- package/imgs//347/234/213/344/270/200/344/270/213/346/210/221/350/277/230/346/234/211/345/223/252/344/272/233Bug/346/234/252/350/247/243/345/206/263.png +0 -0
- package/package.json +39 -36
|
@@ -0,0 +1,1940 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Autofix 服务:生命周期、启动配置、控制接口、实时会话流与单页控制台。
|
|
3
|
+
*
|
|
4
|
+
* 两种阶段:
|
|
5
|
+
* - setup:只提供控制台与配置 API,不轮询、不派工、不写 AgileDev;
|
|
6
|
+
* - running:用户点击「启动自动修复」后创建调度器与协调器。
|
|
7
|
+
*
|
|
8
|
+
* 控制接口只监听 127.0.0.1,校验 token、Origin 与 JSON Content-Type。
|
|
9
|
+
*/
|
|
10
|
+
import http from "node:http";
|
|
11
|
+
import fs from "node:fs";
|
|
12
|
+
import os from "node:os";
|
|
13
|
+
import path from "node:path";
|
|
14
|
+
import crypto from "node:crypto";
|
|
15
|
+
import { fileURLToPath } from "node:url";
|
|
16
|
+
import { execFile, spawn } from "node:child_process";
|
|
17
|
+
|
|
18
|
+
import {
|
|
19
|
+
appendEvent, clearServiceState, createStore, readConfig, readEvents, readJsonFile, readServiceState,
|
|
20
|
+
readWorkspace, statePath, writeConfig, writeJsonAtomic, writeServiceState, writeWorkspace,
|
|
21
|
+
listTasks, readTask, writeTask, listPendingQuestions, readQuestions, updateQuestion,
|
|
22
|
+
listWorkspaces, readProjectFolderStore, writeProjectFolderStore,
|
|
23
|
+
} from "./store.js";
|
|
24
|
+
import { Scheduler, transitionTask, classifyError } from "./scheduler.js";
|
|
25
|
+
import { Coordinator, DEFAULT_PROMPT } from "./coordinator.js";
|
|
26
|
+
import { createApi } from "./agiledev.js";
|
|
27
|
+
import {
|
|
28
|
+
getAdapter, detectAgents, describeAgents, abortAgents, refreshAgentCache, SUPPORTED_AGENTS,
|
|
29
|
+
} from "./agents/index.js";
|
|
30
|
+
import { killPidTree, processCommandLine } from "./agents/exec.js";
|
|
31
|
+
import { ConversationHub } from "./conversation.js";
|
|
32
|
+
import { inspectWorkspace, matchProjects, detectVerifyCommand } from "./workspace.js";
|
|
33
|
+
import { taskWorktreeValid, worktreeRepos } from "./worktree.js";
|
|
34
|
+
import {
|
|
35
|
+
commonAncestorPath, describeSchedule, detectProjectFromFolders, folderPathUsable, listProfiles,
|
|
36
|
+
missingProjectFolders, normalizeProjectFolders, profileToWorkspace, projectFoldersToRepos, resolveProfile,
|
|
37
|
+
} from "./profile.js";
|
|
38
|
+
import { boundProjectSet, filterTasksInScope, taskInProjectScope } from "./scope.js";
|
|
39
|
+
|
|
40
|
+
const HERE = path.dirname(fileURLToPath(import.meta.url));
|
|
41
|
+
const PUBLIC_DIR = path.join(HERE, "public");
|
|
42
|
+
const DEFAULT_PORT = 3210;
|
|
43
|
+
const SESSION_COOKIE = "adev_autofix_sid";
|
|
44
|
+
const SETUP_CACHE_MS = 15000;
|
|
45
|
+
|
|
46
|
+
export const REASON_CODES = Object.freeze({
|
|
47
|
+
setup: "setup",
|
|
48
|
+
needs_binding: "needs_binding",
|
|
49
|
+
invalid_workspace: "invalid_workspace",
|
|
50
|
+
auth_required: "auth_required",
|
|
51
|
+
agent_missing: "agent_missing",
|
|
52
|
+
no_permission: "no_permission",
|
|
53
|
+
network: "network",
|
|
54
|
+
not_found: "not_found",
|
|
55
|
+
normal: "normal",
|
|
56
|
+
});
|
|
57
|
+
|
|
58
|
+
/* ======================== 状态提示语 ======================== */
|
|
59
|
+
|
|
60
|
+
export const REASON_MESSAGES = Object.freeze({
|
|
61
|
+
setup: "等待完成启动配置。",
|
|
62
|
+
needs_binding: "尚未绑定敏捷项目,服务只会观察,不会自动修复。",
|
|
63
|
+
invalid_workspace: "当前工作目录已失效,服务已暂停。",
|
|
64
|
+
auth_required: "AgileDev 登录已失效,请先在终端执行 adev login。",
|
|
65
|
+
agent_missing: "未找到可用的 Agent CLI。",
|
|
66
|
+
no_permission: "当前账号无权访问该项目,未开始修复。",
|
|
67
|
+
network: "连接 AgileDev 失败,请确认已接入公司网络/VPN。",
|
|
68
|
+
not_found: "AgileDev 返回的资源不存在。",
|
|
69
|
+
normal: "已连接,当前没有分配给你的新 bug 或重开 bug。",
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
/** 把关键事件写进会话时间线,刷新页面后仍能看到来龙去脉。 */
|
|
73
|
+
function describeEvent(e) {
|
|
74
|
+
switch (e.type) {
|
|
75
|
+
case "task_discovered": return `发现缺陷 ${e.taskId},已加入队列`;
|
|
76
|
+
case "task_dispatched": return `已派工 ${e.taskId} 给 ${e.worker || "修复 Agent"}`;
|
|
77
|
+
case "task_needs_human": return `需要人工处理:${e.reason || "原因未说明"}`;
|
|
78
|
+
case "task_ready_review": return "本地修复完成,等待主 Agent 复核";
|
|
79
|
+
case "task_code_review": {
|
|
80
|
+
if (e.phase === "start") return "开始只读代码复核";
|
|
81
|
+
if (e.phase === "done") return e.verdict === "PASS" ? "只读复核通过" : "只读复核发现问题";
|
|
82
|
+
if (e.phase === "error") return `只读复核出错:${e.message || "原因未说明"}`;
|
|
83
|
+
if (e.phase === "no_verdict") return "只读复核未给出结论";
|
|
84
|
+
return null;
|
|
85
|
+
}
|
|
86
|
+
case "task_context_loaded": return `已装载缺陷上下文${e.hasScreenshots ? "(含截图)" : ""}`;
|
|
87
|
+
case "task_context_error": return `缺陷上下文装载失败:${e.message || "原因未说明"}`;
|
|
88
|
+
case "task_comment": return e.message || "已在缺陷下留下验证要点";
|
|
89
|
+
case "poll_skipped": return e.message || "不在巡检时段,本轮未检测";
|
|
90
|
+
case "task_done": return "已通过验证并转为待验证";
|
|
91
|
+
case "bug_status": return `线上状态已更新为 ${e.to}`;
|
|
92
|
+
case "question": return `需要你决定:${e.question?.question || ""}`;
|
|
93
|
+
case "question_answered": return `已记录你的回答:${e.answer || ""}`;
|
|
94
|
+
case "service_paused": return "服务已暂停";
|
|
95
|
+
case "service_resumed": return "服务已恢复";
|
|
96
|
+
case "service_recovered": return e.message || "检测到上次异常结束,已恢复会话记录";
|
|
97
|
+
case "service_crash": return `服务异常退出:${e.message || e.kind || "原因未说明"}`;
|
|
98
|
+
// 内存不足的提示只进事件日志,不刷进会话时间线
|
|
99
|
+
case "resource_low": return null;
|
|
100
|
+
case "main_turn": {
|
|
101
|
+
const secs = e.durationMs ? `(${Math.round(e.durationMs / 1000)}s)` : "";
|
|
102
|
+
return e.ok ? `主 Agent 本轮完成${secs}` : `主 Agent 本轮异常结束${secs}`;
|
|
103
|
+
}
|
|
104
|
+
case "main_error": return `主 Agent 出错:${e.message || "原因未说明"}`;
|
|
105
|
+
case "worker_error": return `修复 Agent 出错:${e.message || "原因未说明"}`;
|
|
106
|
+
case "worker_aborted": return e.message || `子 Agent ${e.taskId || ""} 已被手动终止`;
|
|
107
|
+
case "tasks_recovered": return e.message || "服务重启,已恢复遗留任务";
|
|
108
|
+
default: return null;
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/* ======================== 服务 ======================== */
|
|
113
|
+
|
|
114
|
+
export class Service {
|
|
115
|
+
constructor({ workspace, options = {}, api, store, setup = false, deps = {} } = {}) {
|
|
116
|
+
this.workspace = { ...workspace };
|
|
117
|
+
this.options = { ...options };
|
|
118
|
+
this.api = api || createApi();
|
|
119
|
+
this.store = store || createStore();
|
|
120
|
+
this.deps = deps;
|
|
121
|
+
this.port = options.port || DEFAULT_PORT;
|
|
122
|
+
this.token = options.token || crypto.randomBytes(16).toString("hex");
|
|
123
|
+
// 本次服务运行的唯一标识:任务在创建时打上它,界面默认只显示本次发现的缺陷,
|
|
124
|
+
// 历史已解决缺陷收进「历史」里,避免每次启动都被一屏旧 bug 淹没。
|
|
125
|
+
this.runId = options.runId || crypto.randomBytes(8).toString("hex");
|
|
126
|
+
// 用户从哪个目录启动 CLI:用于自动匹配已保存的「敏捷项目 → 本地文件夹」映射。
|
|
127
|
+
// 子进程会继承启动目录,所以即使工作区归一到了 git 根目录,这里仍是用户所在位置。
|
|
128
|
+
this.launchCwd = path.resolve(options.cwd || process.cwd());
|
|
129
|
+
// 同一时间只允许弹一个系统原生文件夹选择窗口(Windows 不走该路径)
|
|
130
|
+
this.folderPickerBusy = false;
|
|
131
|
+
this.server = null;
|
|
132
|
+
this.scheduler = null;
|
|
133
|
+
this.coordinator = null;
|
|
134
|
+
this.phase = "idle";
|
|
135
|
+
this.setup = setup === true;
|
|
136
|
+
this.paused = false;
|
|
137
|
+
this.stopped = false;
|
|
138
|
+
// 本次启动是否在恢复上一次异常结束的会话(用于日志与启动提示)
|
|
139
|
+
this.resumeFromCrash = false;
|
|
140
|
+
this.reason = this.setup ? REASON_CODES.setup : REASON_CODES.normal;
|
|
141
|
+
this.reasonDetail = null;
|
|
142
|
+
this.sessions = new Set();
|
|
143
|
+
this.streams = new Set();
|
|
144
|
+
this.heartbeat = null;
|
|
145
|
+
this.wakeTimer = null;
|
|
146
|
+
this._setupCache = null;
|
|
147
|
+
this._setupCacheAt = 0;
|
|
148
|
+
this._agents = null;
|
|
149
|
+
this._detailCache = new Map();
|
|
150
|
+
this.hub = new ConversationHub({
|
|
151
|
+
onMessage: (scope, message) => this.broadcast({ type: "conversation", scope, message }),
|
|
152
|
+
});
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
emit(event) {
|
|
156
|
+
// Agent 原始输出进入会话流,不写事件日志(否则日志会被逐块输出撑爆)
|
|
157
|
+
if (event.type === "agent_output") {
|
|
158
|
+
this.hub.feed(event.taskId || "main", event.chunk);
|
|
159
|
+
return;
|
|
160
|
+
}
|
|
161
|
+
if (event.type === "main_output") {
|
|
162
|
+
this.hub.feed("main", event.chunk);
|
|
163
|
+
return;
|
|
164
|
+
}
|
|
165
|
+
// 发给主 Agent 的原文:只进会话,不写事件日志(内容较长,且每轮都会重复)
|
|
166
|
+
if (event.type === "main_prompt" || event.type === "agent_prompt") {
|
|
167
|
+
this.hub.append(event.taskId || "main", {
|
|
168
|
+
role: "system",
|
|
169
|
+
kind: "prompt",
|
|
170
|
+
text: event.prompt,
|
|
171
|
+
trigger: event.trigger || "",
|
|
172
|
+
newSession: !!event.newSession,
|
|
173
|
+
});
|
|
174
|
+
return;
|
|
175
|
+
}
|
|
176
|
+
if (event.type === "message") {
|
|
177
|
+
this.hub.append(event.taskId || "main", {
|
|
178
|
+
role: event.from === "user" ? "user" : "agent",
|
|
179
|
+
kind: "text",
|
|
180
|
+
text: event.text,
|
|
181
|
+
});
|
|
182
|
+
} else {
|
|
183
|
+
const note = describeEvent(event);
|
|
184
|
+
if (note) this.hub.append(event.taskId || "main", { role: "system", kind: "event", text: note });
|
|
185
|
+
}
|
|
186
|
+
appendEvent(event);
|
|
187
|
+
this.broadcast(event);
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/**
|
|
191
|
+
* 合并短时间内的多次发现,只唤醒一次主 Agent。
|
|
192
|
+
* 主 Agent 是唯一决定"派哪个任务"的一方,调度器不越权派工。
|
|
193
|
+
*/
|
|
194
|
+
scheduleMainWake(trigger) {
|
|
195
|
+
if (this.paused || this.stopped || this.phase !== "running") return;
|
|
196
|
+
clearTimeout(this.wakeTimer);
|
|
197
|
+
this.wakeTimer = setTimeout(() => {
|
|
198
|
+
this.coordinator?.wakeMainAgent(trigger)
|
|
199
|
+
.catch(e => this.emit({ type: "main_error", message: String(e?.message || e) }));
|
|
200
|
+
}, 500);
|
|
201
|
+
if (typeof this.wakeTimer.unref === "function") this.wakeTimer.unref();
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
get endpoint() {
|
|
205
|
+
return `http://127.0.0.1:${this.port}/api/tools`;
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/* ---------- 单实例 ---------- */
|
|
209
|
+
|
|
210
|
+
static existingInstance() {
|
|
211
|
+
const state = readServiceState();
|
|
212
|
+
if (!state?.pid) return null;
|
|
213
|
+
if (!isProcessAlive(state.pid)) return null;
|
|
214
|
+
return state;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
claimLock() {
|
|
218
|
+
const existing = Service.existingInstance();
|
|
219
|
+
if (existing) return { ok: false, existing };
|
|
220
|
+
writeServiceState({
|
|
221
|
+
pid: process.pid,
|
|
222
|
+
port: this.port,
|
|
223
|
+
workspace: this.workspace.path,
|
|
224
|
+
startedAt: new Date().toISOString(),
|
|
225
|
+
token: this.token,
|
|
226
|
+
phase: this.phase,
|
|
227
|
+
});
|
|
228
|
+
return { ok: true };
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
releaseLock() {
|
|
232
|
+
const state = readServiceState();
|
|
233
|
+
if (state?.pid === process.pid) clearServiceState();
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/* ---------- 启动 ---------- */
|
|
237
|
+
|
|
238
|
+
async start() {
|
|
239
|
+
const lock = this.claimLock();
|
|
240
|
+
if (!lock.ok) return { ok: false, reason: "instance_exists", existing: lock.existing };
|
|
241
|
+
|
|
242
|
+
await this.listen();
|
|
243
|
+
this.startHeartbeat();
|
|
244
|
+
|
|
245
|
+
if (this.setup) {
|
|
246
|
+
this.phase = "setup";
|
|
247
|
+
this.reason = REASON_CODES.setup;
|
|
248
|
+
writeServiceState({ phase: "setup" });
|
|
249
|
+
this.emit({ type: "service_setup_ready", port: this.port, workspace: this.workspace.path });
|
|
250
|
+
return { ok: true, phase: "setup", port: this.port, token: this.token };
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
await this.startRuntime();
|
|
254
|
+
return { ok: true, phase: "running", port: this.port, token: this.token };
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/**
|
|
258
|
+
* 创建调度器与协调器并开始轮询;setup 阶段由 /api/start 调用。
|
|
259
|
+
* restartRuntime 会传入原基线,避免把中断时残留的改动误记为新基线。
|
|
260
|
+
*/
|
|
261
|
+
async startRuntime(baseline = null, { fresh = true } = {}) {
|
|
262
|
+
if (this.scheduler) return { ok: true, already: true };
|
|
263
|
+
const ws = this.workspace;
|
|
264
|
+
// 上次是用户主动停止 → 从干净会话开始;上次是被系统杀掉/崩溃 → 保留会话,
|
|
265
|
+
// 让用户重新打开时能看到刚才处理到哪一步(主 Agent 会话 ID 也已按工作区落盘)。
|
|
266
|
+
if (fresh) {
|
|
267
|
+
const recovering = this.isCrashRecovery(ws.path);
|
|
268
|
+
this.resumeFromCrash = recovering;
|
|
269
|
+
if (!recovering) {
|
|
270
|
+
this.hub.clearAll();
|
|
271
|
+
// 会话记录清空后,主 Agent 也从新会话开始,避免界面空白却续接了旧上下文
|
|
272
|
+
try { this.store.setSession(`main:${String(ws.path).toLowerCase()}`, null); } catch { /* 忽略 */ }
|
|
273
|
+
this.broadcast({ type: "conversation_cleared" });
|
|
274
|
+
} else {
|
|
275
|
+
const crash = this.readLastCrash();
|
|
276
|
+
this.broadcast({ type: "conversation_restored" });
|
|
277
|
+
this.emit({
|
|
278
|
+
type: "service_recovered",
|
|
279
|
+
message: crash
|
|
280
|
+
? `检测到上次运行异常结束(${crash}),已恢复会话记录,将在原会话中继续处理。`
|
|
281
|
+
: "检测到上次运行异常结束,已恢复会话记录,将在原会话中继续处理。",
|
|
282
|
+
});
|
|
283
|
+
}
|
|
284
|
+
}
|
|
285
|
+
// 运行标记:正常停止才写 cleanExit,进程被系统杀掉时它会保持 false,下次启动据此恢复。
|
|
286
|
+
this.writeRunMarker({
|
|
287
|
+
workspace: ws.path,
|
|
288
|
+
pid: process.pid,
|
|
289
|
+
phase: "running",
|
|
290
|
+
cleanExit: false,
|
|
291
|
+
startedAt: new Date().toISOString(),
|
|
292
|
+
});
|
|
293
|
+
const agent = ws.agent || this.options.agent || null;
|
|
294
|
+
const workerAgent = ws.workerAgent || this.options.workerAgent || agent;
|
|
295
|
+
|
|
296
|
+
this.scheduler = new Scheduler({
|
|
297
|
+
api: this.api,
|
|
298
|
+
store: this.store,
|
|
299
|
+
workspace: ws,
|
|
300
|
+
options: { intervalSeconds: ws.intervalSeconds || this.options.intervalSeconds },
|
|
301
|
+
onEvent: e => {
|
|
302
|
+
// 本次运行新发现的缺陷(含线上重开后重新排队的)打上 runId。
|
|
303
|
+
// 界面是否属于历史只看线上是否已关闭,runId 仅作运行批次记录。
|
|
304
|
+
if (this.runId && (e.type === "task_discovered" || e.type === "task_reopened")) {
|
|
305
|
+
try { this.store.writeTask({ taskId: e.taskId, runId: this.runId }); } catch { /* 写失败不影响主流程 */ }
|
|
306
|
+
}
|
|
307
|
+
if (e.type === "poll_error") {
|
|
308
|
+
this.reason = e.reason && e.reason !== "unknown" ? e.reason : this.reason;
|
|
309
|
+
this.reasonDetail = e.message;
|
|
310
|
+
}
|
|
311
|
+
if (e.type === "task_discovered") this.scheduleMainWake("发现新的待处理缺陷");
|
|
312
|
+
// 已完成的缺陷被测试重新打开:任务已退回队列,必须立刻通知主 Agent 重新派工,
|
|
313
|
+
// 否则要等到「长时间闲置」的兜底派工才会动。
|
|
314
|
+
if (e.type === "task_reopened") this.scheduleMainWake(`缺陷 ${e.taskId || ""} 被重新打开,已重新排队`);
|
|
315
|
+
// 有任务结束时把「只提交、未合并」的改动补合入测试分支,不需要人工点
|
|
316
|
+
if (["worker_finished", "task_done"].includes(e.type)) {
|
|
317
|
+
this.coordinator?.flushPendingMerges?.().catch(() => {});
|
|
318
|
+
}
|
|
319
|
+
// worker 结束/需要复核/卡死重排后都要让主 Agent 回来复核并继续派工
|
|
320
|
+
if (["task_ready_review", "worker_finished", "task_retry"].includes(e.type)) {
|
|
321
|
+
this.scheduleMainWake(`任务 ${e.taskId || ""} 状态更新`);
|
|
322
|
+
}
|
|
323
|
+
this.emit(e);
|
|
324
|
+
},
|
|
325
|
+
});
|
|
326
|
+
|
|
327
|
+
this.coordinator = new Coordinator({
|
|
328
|
+
api: this.api,
|
|
329
|
+
store: this.store,
|
|
330
|
+
scheduler: this.scheduler,
|
|
331
|
+
workspace: ws,
|
|
332
|
+
options: {
|
|
333
|
+
agent,
|
|
334
|
+
workerAgent,
|
|
335
|
+
model: ws.model ?? this.options.model ?? null,
|
|
336
|
+
workerModel: ws.workerModel ?? this.options.workerModel ?? null,
|
|
337
|
+
maxWorkers: ws.maxWorkers ?? this.options.maxWorkers ?? 3,
|
|
338
|
+
endpoint: this.endpoint,
|
|
339
|
+
token: this.token,
|
|
340
|
+
},
|
|
341
|
+
onEvent: e => this.emit(e),
|
|
342
|
+
// 仅供测试或自定义接入注入 Agent 适配器;默认使用内置注册表
|
|
343
|
+
adapters: this.deps.adapters,
|
|
344
|
+
});
|
|
345
|
+
|
|
346
|
+
this.phase = "running";
|
|
347
|
+
this.reason = REASON_CODES.normal;
|
|
348
|
+
this.reasonDetail = null;
|
|
349
|
+
|
|
350
|
+
if (baseline) this.scheduler.baseline = baseline;
|
|
351
|
+
else await this.scheduler.captureBaseline();
|
|
352
|
+
|
|
353
|
+
this.recoverInterruptedTasks();
|
|
354
|
+
// 旧版本遗留的「提测确认」不再等待人工:启动时自动补齐并转待验证,
|
|
355
|
+
// 避免服务重启后这些任务永远停在「需要你处理」。
|
|
356
|
+
this.coordinator.autoCompletePendingDeliveries()
|
|
357
|
+
.then(n => {
|
|
358
|
+
if (n > 0) this.scheduleMainWake(`已自动完成 ${n} 个遗留提测确认`);
|
|
359
|
+
})
|
|
360
|
+
.catch(() => {});
|
|
361
|
+
// 为 review / needs_human 任务重建任务级基线,避免重启后越界判定失准
|
|
362
|
+
this.recoverTaskBaselines().catch(() => {});
|
|
363
|
+
// 历史已交付任务的工作树不再需要,后台清理即可
|
|
364
|
+
this.cleanupDoneWorktrees().catch(() => {});
|
|
365
|
+
|
|
366
|
+
if (ws.projectIds?.length) {
|
|
367
|
+
// 启动后立刻同步一次线上缺陷,控制台第一次渲染就能拿到最新状态;
|
|
368
|
+
// 网络慢时不阻塞启动超过 8 秒,剩余工作交给周期轮询。
|
|
369
|
+
await this.initialBugScan();
|
|
370
|
+
this.scheduler.start({ immediate: false });
|
|
371
|
+
} else {
|
|
372
|
+
this.reason = REASON_CODES.needs_binding;
|
|
373
|
+
this.reasonDetail = REASON_MESSAGES.needs_binding;
|
|
374
|
+
this.emit({ type: "service_observation_mode", reason: this.reason });
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
// 只数当前绑定项目的待办:范围外任务不属于本次运行,不能写进启动提示
|
|
378
|
+
const bound = boundProjectSet(ws.projectIds);
|
|
379
|
+
const pendingCount = listTasks().filter(t =>
|
|
380
|
+
["discovered", "queued", "review", "needs_human"].includes(t.status)
|
|
381
|
+
&& taskInProjectScope(t, null, bound),
|
|
382
|
+
).length;
|
|
383
|
+
// 启动后总是唤醒一次主 Agent:即使暂无待处理任务,也要建立会话并汇报扫描结果,
|
|
384
|
+
// 否则控制台会长时间空白,用户不知道主 Agent 是否已经收到指令。
|
|
385
|
+
const startTrigger = this.resumeFromCrash
|
|
386
|
+
? `服务异常退出后已恢复,续接原会话继续处理(待处理 ${pendingCount} 个)`
|
|
387
|
+
: pendingCount > 0
|
|
388
|
+
? `服务启动,发现 ${pendingCount} 个待处理任务`
|
|
389
|
+
: ws.projectIds?.length
|
|
390
|
+
? "服务启动,开始扫描缺陷"
|
|
391
|
+
: "服务启动(观察模式),建立主 Agent 会话";
|
|
392
|
+
this.scheduleMainWake(startTrigger);
|
|
393
|
+
|
|
394
|
+
writeServiceState({ phase: "running" });
|
|
395
|
+
this.emit({ type: "service_started", port: this.port, workspace: ws.path, agent, workerAgent });
|
|
396
|
+
return { ok: true };
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
/**
|
|
400
|
+
* 启动时的一次性缺陷扫描:同步已有任务的线上状态并拉取新缺陷。
|
|
401
|
+
* 失败或超时都不阻断启动,交给之后的周期轮询继续重试。
|
|
402
|
+
*/
|
|
403
|
+
async initialBugScan() {
|
|
404
|
+
if (!this.scheduler) return;
|
|
405
|
+
let timer = null;
|
|
406
|
+
try {
|
|
407
|
+
await Promise.race([
|
|
408
|
+
this.scheduler.refreshNow(),
|
|
409
|
+
new Promise(resolve => {
|
|
410
|
+
timer = setTimeout(resolve, 8000);
|
|
411
|
+
if (typeof timer.unref === "function") timer.unref();
|
|
412
|
+
}),
|
|
413
|
+
]);
|
|
414
|
+
} catch (e) {
|
|
415
|
+
this.emit({ type: "poll_error", message: String(e?.message || e), reason: "unknown" });
|
|
416
|
+
} finally {
|
|
417
|
+
if (timer) clearTimeout(timer);
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
/**
|
|
422
|
+
* 在原进程内重启运行时:中断正在运行的 Agent,保留配置、会话 ID、
|
|
423
|
+
* 工作区基线与任务记录,再重新创建调度器与协调器。
|
|
424
|
+
* 用于模型临时不可用/额度用尽后切换模型,或清掉卡住的会话。
|
|
425
|
+
*/
|
|
426
|
+
async restartRuntime() {
|
|
427
|
+
if (this.phase !== "running" || !this.scheduler) {
|
|
428
|
+
return { ok: false, code: 409, message: "服务尚未启动,无法重启。" };
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
const baseline = this.scheduler.baseline || null;
|
|
432
|
+
const mainSessionId = this.coordinator?.mainSessionId || null;
|
|
433
|
+
const workerSessions = new Map(this.coordinator?.workerSessions || []);
|
|
434
|
+
const wasPaused = this.paused;
|
|
435
|
+
|
|
436
|
+
this.emit({ type: "service_restarting", message: "正在重启服务:中断当前 Agent 会话…" });
|
|
437
|
+
this.coordinator?.stop();
|
|
438
|
+
abortAgents();
|
|
439
|
+
this.scheduler.stop();
|
|
440
|
+
this.scheduler = null;
|
|
441
|
+
this.coordinator = null;
|
|
442
|
+
clearTimeout(this.wakeTimer);
|
|
443
|
+
this.wakeTimer = null;
|
|
444
|
+
|
|
445
|
+
await this.startRuntime(baseline, { fresh: false });
|
|
446
|
+
|
|
447
|
+
// 原生会话 ID 不在磁盘上重建,重启后继续沿用,避免主 Agent 丢失上下文。
|
|
448
|
+
if (this.coordinator) {
|
|
449
|
+
this.coordinator.mainSessionId = mainSessionId;
|
|
450
|
+
for (const [taskId, sessionId] of workerSessions) {
|
|
451
|
+
this.coordinator.workerSessions.set(taskId, sessionId);
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
if (wasPaused) {
|
|
455
|
+
this.paused = true;
|
|
456
|
+
this.scheduler.paused = true;
|
|
457
|
+
this.coordinator.options.paused = true;
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
this.emit({ type: "service_restarted", message: "服务已重启,配置与任务记录已保留。" });
|
|
461
|
+
return { ok: true, status: this.status() };
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
/**
|
|
465
|
+
* 恢复上次退出时停在中间态的任务。
|
|
466
|
+
*
|
|
467
|
+
* launching / running / verifying 都依赖本进程内的 worker 子进程,服务一停这些子进程就没了。
|
|
468
|
+
* 默认退回 queued 让主 Agent 重新派工;同一任务连续中断 3 次则转人工。
|
|
469
|
+
*/
|
|
470
|
+
/**
|
|
471
|
+
* 上一次进程异常退出时留下的 Agent 可能还在改文件。
|
|
472
|
+
*
|
|
473
|
+
* 先按派工执行号确认进程身份,再结束它;确认不了就不动它,也不能让新任务
|
|
474
|
+
* 和它同时改同一批文件——那种情况交给人工确认。
|
|
475
|
+
*/
|
|
476
|
+
reapOrphanWorker(task) {
|
|
477
|
+
const pid = Number(task?.workerPid) || null;
|
|
478
|
+
if (!pid || !isProcessAlive(pid)) return { killed: false, unverified: false, pid: null };
|
|
479
|
+
const command = processCommandLine(pid);
|
|
480
|
+
// 命令行里带着本轮特有的执行号,是最可靠的归属证明。
|
|
481
|
+
const marker = task.attemptId ? `autofix-run:${task.attemptId}` : null;
|
|
482
|
+
if (command && marker && command.includes(marker)) {
|
|
483
|
+
return this.finishOrphan(pid);
|
|
484
|
+
}
|
|
485
|
+
// 读不到完整命令行时,至少要求它看起来是同一类 Agent CLI。
|
|
486
|
+
const hint = String(task.workerAgent || "").toLowerCase();
|
|
487
|
+
if (command && hint && command.toLowerCase().includes(hint)) {
|
|
488
|
+
return this.finishOrphan(pid);
|
|
489
|
+
}
|
|
490
|
+
return { killed: false, unverified: true, pid };
|
|
491
|
+
}
|
|
492
|
+
|
|
493
|
+
/**
|
|
494
|
+
* 结束已确认归属的孤儿进程。
|
|
495
|
+
* 结束失败且进程仍活着时不能当成已回收:否则会一边重新派工、一边还有旧
|
|
496
|
+
* Agent 在改文件。这种情况交给人工确认。
|
|
497
|
+
*/
|
|
498
|
+
finishOrphan(pid) {
|
|
499
|
+
const killed = killPidTree(pid);
|
|
500
|
+
if (killed || !isProcessAlive(pid)) return { killed, unverified: false, pid };
|
|
501
|
+
return { killed: false, unverified: true, pid };
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
recoverInterruptedTasks() {
|
|
505
|
+
const INTERRUPTED = ["launching", "running", "verifying", "resolving"];
|
|
506
|
+
const bound = boundProjectSet(this.workspace?.projectIds);
|
|
507
|
+
const recovered = [];
|
|
508
|
+
for (const t of listTasks()) {
|
|
509
|
+
if (!INTERRUPTED.includes(t.status)) continue;
|
|
510
|
+
// 未勾选项目的任务不认领、不重排、不动进程:保留原状态,等重新勾选后再恢复
|
|
511
|
+
if (!taskInProjectScope(t, null, bound)) continue;
|
|
512
|
+
// 恢复出来的任务仍在本轮继续处理,算作本次运行的可见任务
|
|
513
|
+
writeTask({ taskId: t.taskId, runId: this.runId });
|
|
514
|
+
|
|
515
|
+
const orphan = this.reapOrphanWorker(t);
|
|
516
|
+
if (orphan.killed) {
|
|
517
|
+
this.emit({
|
|
518
|
+
type: "orphan_worker_reaped",
|
|
519
|
+
taskId: t.taskId,
|
|
520
|
+
pid: orphan.pid,
|
|
521
|
+
message: `服务重启前留下的 Agent 进程 ${orphan.pid} 仍在运行,已结束,避免它和新一轮修复同时改文件`,
|
|
522
|
+
});
|
|
523
|
+
}
|
|
524
|
+
if (orphan.unverified) {
|
|
525
|
+
// 确认不了身份时宁可停下来:同时有两个 Agent 改同一批文件,比晚一点修复更糟。
|
|
526
|
+
writeTask({ taskId: t.taskId, runId: this.runId, workerPid: null, workerPidAt: null });
|
|
527
|
+
this.scheduler.needsHuman(t.taskId, {
|
|
528
|
+
reason: "orphan_worker_unverified",
|
|
529
|
+
done: [`服务重启时任务处于 ${t.status},发现旧 Agent 进程 ${orphan.pid} 仍在运行,但无法确认它属于本任务`],
|
|
530
|
+
next: "确认该进程是否属于这个任务;若是,结束它后点「重新排队修复」",
|
|
531
|
+
});
|
|
532
|
+
continue;
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
const count = Number(t.interruptCount || 0) + 1;
|
|
536
|
+
if (count >= 3) {
|
|
537
|
+
this.scheduler.needsHuman(t.taskId, {
|
|
538
|
+
reason: "service_restarted_repeatedly",
|
|
539
|
+
done: [`服务重启时任务处于 ${t.status},已连续中断 ${count} 次`],
|
|
540
|
+
next: "确认该任务是否反复导致服务异常,再决定重新排队或人工处理",
|
|
541
|
+
});
|
|
542
|
+
continue;
|
|
543
|
+
}
|
|
544
|
+
writeTask({
|
|
545
|
+
taskId: t.taskId,
|
|
546
|
+
runId: this.runId,
|
|
547
|
+
status: "queued",
|
|
548
|
+
needsHuman: null,
|
|
549
|
+
workerPid: null,
|
|
550
|
+
workerPidAt: null,
|
|
551
|
+
interruptCount: count,
|
|
552
|
+
interruptedAt: new Date().toISOString(),
|
|
553
|
+
interruptedFrom: t.status,
|
|
554
|
+
});
|
|
555
|
+
recovered.push(t.taskId);
|
|
556
|
+
}
|
|
557
|
+
if (recovered.length) {
|
|
558
|
+
this.emit({
|
|
559
|
+
type: "tasks_recovered",
|
|
560
|
+
taskIds: recovered,
|
|
561
|
+
message: `服务重启,${recovered.length} 个中间态任务已退回待分派`,
|
|
562
|
+
});
|
|
563
|
+
}
|
|
564
|
+
return recovered;
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
/**
|
|
568
|
+
* 重启后为 review / needs_human 任务重建任务级基线,避免 applyWorkerResult 拿全局基线比较越界。
|
|
569
|
+
* 有有效工作树的任务 → 重新 captureBaseline;无工作树的 → 标记 _baselineUntrusted。
|
|
570
|
+
* 异步执行,不阻塞主流程;基线重建失败不影响任务继续排队。
|
|
571
|
+
*/
|
|
572
|
+
async recoverTaskBaselines() {
|
|
573
|
+
const PENDING_REVIEW = ["review", "needs_human"];
|
|
574
|
+
// 只给当前绑定项目的任务重建基线:范围外任务的工作树属于别的项目,
|
|
575
|
+
// 启动时不该去读它们的 git 状态,也不该改写它们的标记
|
|
576
|
+
const tasks = filterTasksInScope(listTasks(), this.workspace?.projectIds)
|
|
577
|
+
.filter(t => PENDING_REVIEW.includes(t.status));
|
|
578
|
+
if (!tasks.length) return;
|
|
579
|
+
const rebuilt = [];
|
|
580
|
+
const untrusted = [];
|
|
581
|
+
for (const t of tasks) {
|
|
582
|
+
const wt = t.worktree && taskWorktreeValid(t.worktree) ? t.worktree : null;
|
|
583
|
+
if (wt) {
|
|
584
|
+
try {
|
|
585
|
+
const repos = worktreeRepos(wt);
|
|
586
|
+
const repoPaths = repos
|
|
587
|
+
.filter(r => r?.path)
|
|
588
|
+
.map(r => ({ path: r.path, name: r.name || path.basename(r.path) }));
|
|
589
|
+
const baseline = await this.scheduler.captureBaseline(
|
|
590
|
+
wt.workdir || wt.path,
|
|
591
|
+
{ repos: repoPaths.length ? repoPaths : null },
|
|
592
|
+
);
|
|
593
|
+
this.coordinator.taskBaselines.set(t.taskId, baseline);
|
|
594
|
+
rebuilt.push(t.taskId);
|
|
595
|
+
} catch {
|
|
596
|
+
writeTask({ taskId: t.taskId, _baselineUntrusted: true });
|
|
597
|
+
untrusted.push(t.taskId);
|
|
598
|
+
}
|
|
599
|
+
} else {
|
|
600
|
+
writeTask({ taskId: t.taskId, _baselineUntrusted: true });
|
|
601
|
+
untrusted.push(t.taskId);
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
if (rebuilt.length || untrusted.length) {
|
|
605
|
+
this.emit({
|
|
606
|
+
type: "baselines_recovered",
|
|
607
|
+
rebuilt,
|
|
608
|
+
untrusted,
|
|
609
|
+
message: [
|
|
610
|
+
rebuilt.length ? `${rebuilt.length} 个任务基线已重建` : "",
|
|
611
|
+
untrusted.length ? `${untrusted.length} 个任务无工作树,已标记基线不可信` : "",
|
|
612
|
+
].filter(Boolean).join(";"),
|
|
613
|
+
});
|
|
614
|
+
}
|
|
615
|
+
}
|
|
616
|
+
|
|
617
|
+
/**
|
|
618
|
+
* 启动时清理已交付任务的工作树:任务已 done,目录留着只会占磁盘。
|
|
619
|
+
* 分支保留,需要回看修复提交时仍能找到。异步执行,不拖慢启动。
|
|
620
|
+
*/
|
|
621
|
+
async cleanupDoneWorktrees() {
|
|
622
|
+
const bound = boundProjectSet(this.workspace?.projectIds);
|
|
623
|
+
const done = listTasks().filter(t => {
|
|
624
|
+
// 只清理当前绑定项目的任务,其他项目的工作树留给对应工作区处理
|
|
625
|
+
if (!taskInProjectScope(t, null, bound)) return false;
|
|
626
|
+
if (t.status !== "done" || !t.worktree || t.worktree.removedAt) return false;
|
|
627
|
+
// 合并仍挂起的任务要保留工作树,等 flushPendingMerges 或人工处理
|
|
628
|
+
const pending = t.commit?.pendingMerge === true
|
|
629
|
+
|| (Array.isArray(t.commit?.repoResults) && t.commit.repoResults.some(r => r.pendingMerge));
|
|
630
|
+
return !pending;
|
|
631
|
+
});
|
|
632
|
+
for (const task of done) {
|
|
633
|
+
try {
|
|
634
|
+
await this.coordinator?.cleanupWorktree(task.taskId);
|
|
635
|
+
} catch (e) {
|
|
636
|
+
this.emit({ type: "worktree_error", taskId: task.taskId, message: String(e?.message || e) });
|
|
637
|
+
}
|
|
638
|
+
}
|
|
639
|
+
return done.length;
|
|
640
|
+
}
|
|
641
|
+
|
|
642
|
+
async listen() {
|
|
643
|
+
// 请求处理里的任何异常都不能变成 unhandledRejection(会留下一个永远不返回的
|
|
644
|
+
// 请求,Agent 只能干等到超时),这里兜底回 500。
|
|
645
|
+
this.server = http.createServer((req, res) => {
|
|
646
|
+
this.handleRequest(req, res).catch(e => {
|
|
647
|
+
try {
|
|
648
|
+
if (!res.headersSent) res.writeHead(500, { "Content-Type": "application/json; charset=utf-8" });
|
|
649
|
+
res.end(JSON.stringify({ message: String(e?.message || e) }));
|
|
650
|
+
} catch { /* 连接已断开 */ }
|
|
651
|
+
});
|
|
652
|
+
});
|
|
653
|
+
await new Promise((resolve, reject) => {
|
|
654
|
+
this.server.once("error", reject);
|
|
655
|
+
this.server.listen(this.port, "127.0.0.1", resolve);
|
|
656
|
+
});
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
/* ---------- 实时流 ---------- */
|
|
660
|
+
|
|
661
|
+
startHeartbeat() {
|
|
662
|
+
if (this.heartbeat) return;
|
|
663
|
+
let ticks = 0;
|
|
664
|
+
this.heartbeat = setInterval(() => {
|
|
665
|
+
for (const res of this.streams) {
|
|
666
|
+
try { res.write(": ping\n\n"); } catch { this.streams.delete(res); }
|
|
667
|
+
}
|
|
668
|
+
// 每 4 个心跳(约 1 分钟)检查一次:主 Agent 长时间没动就兜底派工
|
|
669
|
+
if (++ticks % 4 === 0) this.maybeAutoDispatchWhenIdle();
|
|
670
|
+
}, 15000);
|
|
671
|
+
if (typeof this.heartbeat.unref === "function") this.heartbeat.unref();
|
|
672
|
+
}
|
|
673
|
+
|
|
674
|
+
/**
|
|
675
|
+
* 主 Agent 长时间闲置时,交给确定性派工计划推进。
|
|
676
|
+
*
|
|
677
|
+
* 只处理 discovered/queued 且有空闲槽位的任务;主 Agent 最近 3 分钟有活动、
|
|
678
|
+
* 服务暂停或已停止时都不插手,避免和正常调度抢活。
|
|
679
|
+
*/
|
|
680
|
+
maybeAutoDispatchWhenIdle() {
|
|
681
|
+
if (this.phase !== "running" || this.paused || this.stopped || !this.coordinator) return;
|
|
682
|
+
const main = this.coordinator.mainState || {};
|
|
683
|
+
if (main.status === "running") return;
|
|
684
|
+
const last = Date.parse(main.lastAt || "") || 0;
|
|
685
|
+
if (last && Date.now() - last < 3 * 60 * 1000) return;
|
|
686
|
+
const hasPending = filterTasksInScope(listTasks(), this.workspace?.projectIds)
|
|
687
|
+
.some(t => ["discovered", "queued"].includes(t.status));
|
|
688
|
+
if (!hasPending) return;
|
|
689
|
+
this.coordinator.maybeAutoDispatch("长时间闲置").catch(() => {});
|
|
690
|
+
}
|
|
691
|
+
|
|
692
|
+
broadcast(event) {
|
|
693
|
+
if (!this.streams.size) return;
|
|
694
|
+
const payload = `data: ${JSON.stringify(event)}\n\n`;
|
|
695
|
+
for (const res of this.streams) {
|
|
696
|
+
try { res.write(payload); } catch { this.streams.delete(res); }
|
|
697
|
+
}
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
/* ---------- 停止 ---------- */
|
|
701
|
+
|
|
702
|
+
async stop() {
|
|
703
|
+
this.stopped = true;
|
|
704
|
+
clearTimeout(this.wakeTimer);
|
|
705
|
+
this.coordinator?.stop();
|
|
706
|
+
abortAgents();
|
|
707
|
+
this.scheduler?.stop();
|
|
708
|
+
for (const res of this.streams) {
|
|
709
|
+
try { res.end(); } catch { /* 已断开 */ }
|
|
710
|
+
}
|
|
711
|
+
this.streams.clear();
|
|
712
|
+
if (this.heartbeat) { clearInterval(this.heartbeat); this.heartbeat = null; }
|
|
713
|
+
if (this.server) {
|
|
714
|
+
await new Promise(resolve => this.server.close(resolve));
|
|
715
|
+
this.server = null;
|
|
716
|
+
}
|
|
717
|
+
// 正常停止:下次启动可以放心清空会话;异常退出不会执行到这里。
|
|
718
|
+
this.writeRunMarker({ cleanExit: true, stoppedAt: new Date().toISOString(), pid: null });
|
|
719
|
+
this.releaseLock();
|
|
720
|
+
this.emit({ type: "service_stopped" });
|
|
721
|
+
return { ok: true };
|
|
722
|
+
}
|
|
723
|
+
|
|
724
|
+
/* ---------- 运行标记 / 异常恢复 ---------- */
|
|
725
|
+
|
|
726
|
+
/**
|
|
727
|
+
* 上一次运行是否属于「异常结束」。
|
|
728
|
+
*
|
|
729
|
+
* 只有正常停止(/api/stop、SIGINT/SIGTERM)才会把 cleanExit 写成 true。
|
|
730
|
+
* 进程被系统因资源问题杀掉、崩溃退出时标记保持 false,下次在同一工作区启动
|
|
731
|
+
* 就按崩溃恢复处理:保留会话记录并续接主 Agent 的原生会话。
|
|
732
|
+
*/
|
|
733
|
+
isCrashRecovery(workspacePath) {
|
|
734
|
+
try {
|
|
735
|
+
const prior = readJsonFile(statePath("run.json"), null);
|
|
736
|
+
if (!prior || prior.cleanExit !== false) return false;
|
|
737
|
+
if (!prior.workspace) return false;
|
|
738
|
+
return String(prior.workspace).toLowerCase() === String(workspacePath || "").toLowerCase();
|
|
739
|
+
} catch {
|
|
740
|
+
return false;
|
|
741
|
+
}
|
|
742
|
+
}
|
|
743
|
+
|
|
744
|
+
/** 读 crash.log 里最后一条异常记录,恢复启动时告诉用户上次为什么退出。 */
|
|
745
|
+
readLastCrash() {
|
|
746
|
+
try {
|
|
747
|
+
const lines = fs.readFileSync(statePath("logs", "crash.log"), "utf8").split(/\r?\n/).filter(Boolean);
|
|
748
|
+
// 优先展示真正的异常行;只有退出码时再退而求其次
|
|
749
|
+
const line = [...lines].reverse().find(l => /uncaughtException|unhandledRejection/.test(l))
|
|
750
|
+
|| [...lines].reverse().find(l => /进程退出码/.test(l));
|
|
751
|
+
return line ? line.replace(/^\[[^\]]+\]\s*/, "").slice(0, 240) : null;
|
|
752
|
+
} catch {
|
|
753
|
+
return null;
|
|
754
|
+
}
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
writeRunMarker(patch) {
|
|
758
|
+
try {
|
|
759
|
+
const prior = readJsonFile(statePath("run.json"), {}) || {};
|
|
760
|
+
writeJsonAtomic(statePath("run.json"), { ...prior, ...patch });
|
|
761
|
+
} catch {
|
|
762
|
+
// 标记文件写失败只影响下次的恢复判断,不影响本次运行
|
|
763
|
+
}
|
|
764
|
+
}
|
|
765
|
+
|
|
766
|
+
/* ---------- HTTP ---------- */
|
|
767
|
+
|
|
768
|
+
async handleRequest(req, res) {
|
|
769
|
+
const url = new URL(req.url, `http://127.0.0.1:${this.port}`);
|
|
770
|
+
const send = (code, payload, type = "application/json") => {
|
|
771
|
+
res.writeHead(code, { "Content-Type": `${type}; charset=utf-8`, "Cache-Control": "no-store" });
|
|
772
|
+
res.end(type === "application/json" ? JSON.stringify(payload) : payload);
|
|
773
|
+
};
|
|
774
|
+
|
|
775
|
+
// 静态页面:首次加载时下发一个绑定本进程的会话 cookie,
|
|
776
|
+
// 这样 token 不出现在 URL 里,只在本机浏览器会话内有效。
|
|
777
|
+
if (req.method === "GET" && (url.pathname === "/" || url.pathname === "/index.html")) {
|
|
778
|
+
const file = path.join(PUBLIC_DIR, "index.html");
|
|
779
|
+
try {
|
|
780
|
+
const body = fs.readFileSync(file);
|
|
781
|
+
const sid = crypto.randomBytes(16).toString("hex");
|
|
782
|
+
this.sessions.add(sid);
|
|
783
|
+
res.writeHead(200, {
|
|
784
|
+
"Content-Type": "text/html; charset=utf-8",
|
|
785
|
+
"Cache-Control": "no-store",
|
|
786
|
+
"Set-Cookie": `${SESSION_COOKIE}=${sid}; Path=/; HttpOnly; SameSite=Strict`,
|
|
787
|
+
});
|
|
788
|
+
return res.end(body);
|
|
789
|
+
} catch { return send(500, "控制台页面缺失", "text/plain"); }
|
|
790
|
+
}
|
|
791
|
+
if (req.method === "GET" && url.pathname === "/app.js") {
|
|
792
|
+
try { return send(200, fs.readFileSync(path.join(PUBLIC_DIR, "app.js")), "text/javascript"); } catch { return send(500, "// 缺失", "text/plain"); }
|
|
793
|
+
}
|
|
794
|
+
if (req.method === "GET" && url.pathname === "/style.css") {
|
|
795
|
+
try { return send(200, fs.readFileSync(path.join(PUBLIC_DIR, "style.css")), "text/css"); } catch { return send(500, "/* 缺失 */", "text/plain"); }
|
|
796
|
+
}
|
|
797
|
+
// 其余前端静态资源(如 app.js 依赖的 i18n 模块):只允许 public 目录下的白名单后缀,
|
|
798
|
+
// 之前漏了这条,模块 404 会让整个页面停在启动屏。
|
|
799
|
+
if (req.method === "GET" && /^\/[\w.-]+\.(?:js|mjs|css|svg|png|jpg|ico|woff2?)$/.test(url.pathname)) {
|
|
800
|
+
const name = path.basename(url.pathname);
|
|
801
|
+
const file = path.join(PUBLIC_DIR, name);
|
|
802
|
+
const type = name.endsWith(".css") ? "text/css"
|
|
803
|
+
: name.endsWith(".js") || name.endsWith(".mjs") ? "text/javascript"
|
|
804
|
+
: name.endsWith(".html") ? "text/html; charset=utf-8"
|
|
805
|
+
: "application/octet-stream";
|
|
806
|
+
try { return send(200, fs.readFileSync(file), type); } catch { return send(404, "not found", "text/plain"); }
|
|
807
|
+
}
|
|
808
|
+
if (req.method === "GET" && url.pathname === "/favicon.ico") {
|
|
809
|
+
res.writeHead(204);
|
|
810
|
+
return res.end();
|
|
811
|
+
}
|
|
812
|
+
|
|
813
|
+
// 控制接口
|
|
814
|
+
if (url.pathname.startsWith("/api/")) {
|
|
815
|
+
const token = req.headers["x-autofix-token"];
|
|
816
|
+
const sid = parseCookies(req.headers.cookie || "")[SESSION_COOKIE];
|
|
817
|
+
const authorized = token === this.token || (sid && this.sessions.has(sid));
|
|
818
|
+
if (!authorized) return send(403, { message: "无效的访问令牌" });
|
|
819
|
+
|
|
820
|
+
const origin = req.headers.origin;
|
|
821
|
+
// 只接受本机回环地址;localhost / [::1] 与 127.0.0.1 等价,
|
|
822
|
+
// 浏览器或预览工具可能用其中任意一个打开控制台。
|
|
823
|
+
if (origin && !/^http:\/\/(127\.0\.0\.1|localhost|\[::1\])(:\d+)?$/.test(origin)) {
|
|
824
|
+
return send(403, { message: "只接受本机控制台请求" });
|
|
825
|
+
}
|
|
826
|
+
if (req.method === "POST" && !String(req.headers["content-type"] || "").includes("application/json")) {
|
|
827
|
+
return send(415, { message: "只接受 application/json" });
|
|
828
|
+
}
|
|
829
|
+
|
|
830
|
+
try {
|
|
831
|
+
return await this.handleApi(url, req, res, send);
|
|
832
|
+
} catch (e) {
|
|
833
|
+
return send(500, { message: String(e?.message || e) });
|
|
834
|
+
}
|
|
835
|
+
}
|
|
836
|
+
|
|
837
|
+
return send(404, { message: "not found" });
|
|
838
|
+
}
|
|
839
|
+
|
|
840
|
+
async handleApi(url, req, res, send) {
|
|
841
|
+
const p = url.pathname;
|
|
842
|
+
const method = req.method;
|
|
843
|
+
|
|
844
|
+
/* ---------- 实时事件流(GET,不能读 body) ---------- */
|
|
845
|
+
if (p === "/api/stream" && method === "GET") {
|
|
846
|
+
res.writeHead(200, {
|
|
847
|
+
"Content-Type": "text/event-stream; charset=utf-8",
|
|
848
|
+
"Cache-Control": "no-store",
|
|
849
|
+
"Connection": "keep-alive",
|
|
850
|
+
"X-Accel-Buffering": "no",
|
|
851
|
+
});
|
|
852
|
+
res.write(": connected\n\n");
|
|
853
|
+
this.streams.add(res);
|
|
854
|
+
const cleanup = () => this.streams.delete(res);
|
|
855
|
+
req.on("close", cleanup);
|
|
856
|
+
res.on("close", cleanup);
|
|
857
|
+
return;
|
|
858
|
+
}
|
|
859
|
+
|
|
860
|
+
const body = method === "POST" ? await readJsonBody(req) : {};
|
|
861
|
+
|
|
862
|
+
if (p === "/api/tools" && method === "POST") {
|
|
863
|
+
if (!this.coordinator) return send(400, { message: "服务尚未启动" });
|
|
864
|
+
// bridge 按本轮派工带上执行号:用于拒绝旧进程迟到的汇报、识别重复提交。
|
|
865
|
+
const meta = { attempt: req.headers["x-autofix-attempt"] || null };
|
|
866
|
+
let result;
|
|
867
|
+
try {
|
|
868
|
+
result = await this.coordinator.handleTool(body.name, body.arguments || {}, meta);
|
|
869
|
+
} catch (e) {
|
|
870
|
+
// 工具执行抛错也要给 Agent 一个明确的错误结果,不能让它一直等响应
|
|
871
|
+
result = { isError: true, content: [{ type: "text", text: `工具 ${body.name || ""} 执行失败:${e?.message || e}` }] };
|
|
872
|
+
this.emit({ type: "tool_error", message: String(e?.message || e) });
|
|
873
|
+
}
|
|
874
|
+
return send(200, { result });
|
|
875
|
+
}
|
|
876
|
+
|
|
877
|
+
if (p === "/api/status" && method === "GET") {
|
|
878
|
+
return send(200, this.status());
|
|
879
|
+
}
|
|
880
|
+
|
|
881
|
+
if (p === "/api/setup" && method === "GET") {
|
|
882
|
+
const data = await this.setupData(url.searchParams.get("refresh") === "1");
|
|
883
|
+
return send(200, { ...data, phase: this.phase });
|
|
884
|
+
}
|
|
885
|
+
|
|
886
|
+
if (p === "/api/start" && method === "POST") {
|
|
887
|
+
const result = await this.handleStart(body);
|
|
888
|
+
return send(result.ok ? 200 : result.code || 400, result);
|
|
889
|
+
}
|
|
890
|
+
|
|
891
|
+
if (p === "/api/models" && method === "GET") {
|
|
892
|
+
return send(200, await this.modelsData(url.searchParams.get("refresh") === "1"));
|
|
893
|
+
}
|
|
894
|
+
|
|
895
|
+
if (p === "/api/model" && method === "POST") {
|
|
896
|
+
const result = await this.handleModelChange(body);
|
|
897
|
+
return send(result.ok ? 200 : result.code || 400, result);
|
|
898
|
+
}
|
|
899
|
+
|
|
900
|
+
if (p === "/api/restart" && method === "POST") {
|
|
901
|
+
const result = await this.restartRuntime();
|
|
902
|
+
return send(result.ok ? 200 : result.code || 400, result);
|
|
903
|
+
}
|
|
904
|
+
|
|
905
|
+
// 启动页选择本地文件夹:只读列出目录,供可视化选择器使用
|
|
906
|
+
if (p === "/api/fs/list" && method === "GET") {
|
|
907
|
+
const target = url.searchParams.get("path") || this.workspace.path || os.homedir();
|
|
908
|
+
return send(200, listDirectories(target));
|
|
909
|
+
}
|
|
910
|
+
|
|
911
|
+
// 打开系统原生文件夹选择窗口(只能由本机服务进程拉起)。
|
|
912
|
+
// Windows 后台服务进程拉起 COM / WinForms 对话框时窗口不会显示且永久挂起,
|
|
913
|
+
// 直接拒绝,前端会立刻退回页面内选择器,避免点击后长时间无响应。
|
|
914
|
+
if (p === "/api/fs/pick-folder" && method === "POST") {
|
|
915
|
+
if (process.platform === "win32") {
|
|
916
|
+
return send(200, { ok: false, unsupported: true, message: "Windows 请使用页面内文件夹选择器" });
|
|
917
|
+
}
|
|
918
|
+
if (this.folderPickerBusy) {
|
|
919
|
+
return send(409, { ok: false, message: "已经打开了文件夹选择窗口,请先完成上一个选择" });
|
|
920
|
+
}
|
|
921
|
+
this.folderPickerBusy = true;
|
|
922
|
+
// 30 秒后自动释放,防止原生对话框在某些环境下挂起导致永久锁死
|
|
923
|
+
const busyTimer = setTimeout(() => { this.folderPickerBusy = false; }, 30000);
|
|
924
|
+
try {
|
|
925
|
+
const result = await pickSystemFolder({ initialPath: body.initialPath || this.workspace.path });
|
|
926
|
+
return send(200, result);
|
|
927
|
+
} finally {
|
|
928
|
+
clearTimeout(busyTimer);
|
|
929
|
+
this.folderPickerBusy = false;
|
|
930
|
+
}
|
|
931
|
+
}
|
|
932
|
+
|
|
933
|
+
// 启动页修改「敏捷项目 → 本地文件夹」映射:立即落盘,下次启动无需重选。
|
|
934
|
+
// 全局保存一份,换一个目录启动服务也能看到之前配好的文件夹;
|
|
935
|
+
// 工作区再镜像一份,兼容旧版本与其它只读工作区记录的地方。
|
|
936
|
+
if (p === "/api/project-folders" && method === "POST") {
|
|
937
|
+
const projectFolders = normalizeProjectFolders(body.projectFolders, { root: this.workspace.path });
|
|
938
|
+
writeProjectFolderStore(projectFolders);
|
|
939
|
+
writeWorkspace(this.workspace.path, { projectFolders });
|
|
940
|
+
this._setupCacheAt = 0;
|
|
941
|
+
return send(200, { ok: true, projectFolders });
|
|
942
|
+
}
|
|
943
|
+
|
|
944
|
+
if (p === "/api/events" && method === "GET") {
|
|
945
|
+
const limit = Number(url.searchParams.get("limit") || 100);
|
|
946
|
+
return send(200, { events: readEvents(limit) });
|
|
947
|
+
}
|
|
948
|
+
|
|
949
|
+
if (p === "/api/tasks" && method === "GET") {
|
|
950
|
+
// 范围外任务仍然返回(便于排查历史),但带 outOfScope 标记,
|
|
951
|
+
// 前端不展示、不提供任何操作入口。
|
|
952
|
+
const bound = boundProjectSet(this.workspace?.projectIds);
|
|
953
|
+
return send(200, {
|
|
954
|
+
tasks: listTasks().map(t => ({ ...t, outOfScope: !taskInProjectScope(t, null, bound) })),
|
|
955
|
+
});
|
|
956
|
+
}
|
|
957
|
+
|
|
958
|
+
if (p === "/api/task" && method === "GET") {
|
|
959
|
+
const task = readTask(url.searchParams.get("id"));
|
|
960
|
+
return task ? send(200, { task }) : send(404, { message: "未知任务" });
|
|
961
|
+
}
|
|
962
|
+
|
|
963
|
+
if (p === "/api/task-detail" && method === "GET") {
|
|
964
|
+
return send(200, await this.taskDetail(url.searchParams.get("id")));
|
|
965
|
+
}
|
|
966
|
+
|
|
967
|
+
if (p === "/api/conversation" && method === "GET") {
|
|
968
|
+
const scope = url.searchParams.get("scope") || "main";
|
|
969
|
+
const limit = Math.min(1000, Math.max(1, Number(url.searchParams.get("limit") || 500)));
|
|
970
|
+
return send(200, { scope, messages: this.hub.read(scope, limit) });
|
|
971
|
+
}
|
|
972
|
+
|
|
973
|
+
if (p === "/api/questions" && method === "GET") {
|
|
974
|
+
return send(200, { questions: readQuestions().questions });
|
|
975
|
+
}
|
|
976
|
+
|
|
977
|
+
if (p === "/api/answer" && method === "POST") {
|
|
978
|
+
if (!this.coordinator) return send(400, { message: "服务尚未启动" });
|
|
979
|
+
const result = await this.coordinator.answerQuestion(body.id, body.answer, body.optionId ?? null);
|
|
980
|
+
return send(result.ok ? 200 : 400, result);
|
|
981
|
+
}
|
|
982
|
+
|
|
983
|
+
if (p === "/api/pause" && method === "POST") {
|
|
984
|
+
if (this.phase !== "running") return send(400, { message: "服务尚未启动" });
|
|
985
|
+
this.paused = true;
|
|
986
|
+
this.scheduler.paused = true;
|
|
987
|
+
if (this.coordinator) this.coordinator.options.paused = true;
|
|
988
|
+
clearTimeout(this.wakeTimer);
|
|
989
|
+
this.emit({ type: "service_paused" });
|
|
990
|
+
return send(200, { ok: true, paused: true });
|
|
991
|
+
}
|
|
992
|
+
|
|
993
|
+
if (p === "/api/resume" && method === "POST") {
|
|
994
|
+
if (this.phase !== "running") return send(400, { message: "服务尚未启动" });
|
|
995
|
+
this.paused = false;
|
|
996
|
+
this.scheduler.paused = false;
|
|
997
|
+
if (this.coordinator) this.coordinator.options.paused = false;
|
|
998
|
+
this.emit({ type: "service_resumed" });
|
|
999
|
+
return send(200, { ok: true, paused: false });
|
|
1000
|
+
}
|
|
1001
|
+
|
|
1002
|
+
if (p === "/api/check" && method === "POST") {
|
|
1003
|
+
if (this.phase !== "running") return send(400, { message: "服务尚未启动" });
|
|
1004
|
+
const found = await this.scheduler.poll();
|
|
1005
|
+
return send(200, { ok: true, found });
|
|
1006
|
+
}
|
|
1007
|
+
|
|
1008
|
+
if (p === "/api/say" && method === "POST") {
|
|
1009
|
+
if (this.phase !== "running" || !this.coordinator) return send(400, { message: "服务尚未启动" });
|
|
1010
|
+
const text = String(body.text || "").trim();
|
|
1011
|
+
if (!text) return send(400, { message: "指令不能为空" });
|
|
1012
|
+
this.hub.append("main", { role: "user", kind: "text", text });
|
|
1013
|
+
await this.coordinator.wakeMainAgent(`用户指令:${text}`);
|
|
1014
|
+
return send(200, { ok: true });
|
|
1015
|
+
}
|
|
1016
|
+
|
|
1017
|
+
if (p === "/api/task-message" && method === "POST") {
|
|
1018
|
+
if (this.phase !== "running" || !this.coordinator) return send(400, { message: "服务尚未启动" });
|
|
1019
|
+
const taskId = String(body.id || "").trim();
|
|
1020
|
+
const text = String(body.text || "").trim();
|
|
1021
|
+
if (!taskId || !text) return send(400, { message: "缺少任务编号或内容" });
|
|
1022
|
+
const result = await this.coordinator.handleTool("send_message", { taskId, text, to: "user" });
|
|
1023
|
+
return send(result.isError ? 400 : 200, result.isError
|
|
1024
|
+
? { message: result.content?.[0]?.text || "发送失败" }
|
|
1025
|
+
: { ok: true });
|
|
1026
|
+
}
|
|
1027
|
+
|
|
1028
|
+
if (p === "/api/retry" && method === "POST") {
|
|
1029
|
+
const taskId = body.id;
|
|
1030
|
+
const task = readTask(taskId);
|
|
1031
|
+
if (!task) return send(404, { message: "未知任务" });
|
|
1032
|
+
const violation = this.taskScopeViolation(task);
|
|
1033
|
+
if (violation) return send(400, { message: violation });
|
|
1034
|
+
transitionTask(this.store, taskId, "queued", { needsHuman: null, interruptCount: 0 });
|
|
1035
|
+
// 人工重试的历史任务算回本次运行,否则会被「只显示本次」的过滤隐藏
|
|
1036
|
+
writeTask({ taskId, runId: this.runId });
|
|
1037
|
+
this.emit({ type: "task_retry", taskId });
|
|
1038
|
+
return send(200, { ok: true });
|
|
1039
|
+
}
|
|
1040
|
+
|
|
1041
|
+
if (p === "/api/task-action" && method === "POST") {
|
|
1042
|
+
if (this.phase !== "running" || !this.coordinator) return send(400, { message: "服务尚未启动" });
|
|
1043
|
+
const taskId = String(body.id || "").trim();
|
|
1044
|
+
const action = String(body.action || "").trim();
|
|
1045
|
+
if (!taskId || !action) return send(400, { message: "缺少任务编号或操作" });
|
|
1046
|
+
const result = await this.coordinator.applyTaskAction(taskId, action);
|
|
1047
|
+
if (result.ok) writeTask({ taskId, runId: this.runId });
|
|
1048
|
+
this.emit({ type: "task_action", taskId, action, message: result.message || "" });
|
|
1049
|
+
return send(result.ok ? 200 : 400, result);
|
|
1050
|
+
}
|
|
1051
|
+
|
|
1052
|
+
if (p === "/api/abort-worker" && method === "POST") {
|
|
1053
|
+
if (this.phase !== "running" || !this.coordinator) return send(400, { message: "服务尚未启动" });
|
|
1054
|
+
const taskId = String(body.id || "").trim();
|
|
1055
|
+
const result = await this.coordinator.abortWorker(taskId, body.reason || "用户手动终止");
|
|
1056
|
+
return send(result.ok ? 200 : 400, result);
|
|
1057
|
+
}
|
|
1058
|
+
|
|
1059
|
+
if (p === "/api/sync-task" && method === "POST") {
|
|
1060
|
+
if (this.phase !== "running" || !this.scheduler) return send(400, { message: "服务尚未启动" });
|
|
1061
|
+
const taskId = String(body.id || "").trim();
|
|
1062
|
+
const task = readTask(taskId);
|
|
1063
|
+
if (!task) return send(404, { message: "未知任务" });
|
|
1064
|
+
// 未勾选项目的任务连线上状态都不去查,界面也不会展示它
|
|
1065
|
+
const violation = this.taskScopeViolation(task);
|
|
1066
|
+
if (violation) return send(400, { message: violation });
|
|
1067
|
+
try {
|
|
1068
|
+
const fresh = task.bugId ? await this.api.getBug(task.bugId) : null;
|
|
1069
|
+
if (!fresh) return send(400, { message: "无法从敏捷系统获取该缺陷状态" });
|
|
1070
|
+
const patch = { lastStatus: fresh.status };
|
|
1071
|
+
if (fresh.title) patch.title = fresh.title;
|
|
1072
|
+
if (fresh.severity) patch.severity = fresh.severity;
|
|
1073
|
+
this.store.writeTask({ taskId: task.taskId, ...patch });
|
|
1074
|
+
this.emit({
|
|
1075
|
+
type: "task_updated",
|
|
1076
|
+
taskId: task.taskId,
|
|
1077
|
+
lastStatus: fresh.status,
|
|
1078
|
+
status: task.status,
|
|
1079
|
+
});
|
|
1080
|
+
return send(200, { ok: true, taskId: task.taskId, status: task.status, lastStatus: fresh.status, bug: fresh });
|
|
1081
|
+
} catch (e) {
|
|
1082
|
+
return send(500, { message: `同步状态失败: ${String(e?.message || e)}` });
|
|
1083
|
+
}
|
|
1084
|
+
}
|
|
1085
|
+
|
|
1086
|
+
if (p === "/api/bind" && method === "POST") {
|
|
1087
|
+
if (this.phase !== "running") return send(400, { message: "请先在控制台完成启动配置" });
|
|
1088
|
+
const ids = (Array.isArray(body.projectIds) ? body.projectIds : [])
|
|
1089
|
+
.map(v => String(v ?? "").trim()).filter(Boolean);
|
|
1090
|
+
if (!ids.length) return send(400, { message: "请选择至少一个项目" });
|
|
1091
|
+
// 运行中换绑定同样要求每个项目有可用文件夹,否则又会退回启动目录/别的项目
|
|
1092
|
+
const folders = mergeProjectFolders(
|
|
1093
|
+
normalizeProjectFolders(this.workspace.projectFolders || {}, { root: this.workspace.path }),
|
|
1094
|
+
normalizeProjectFolders(loadGlobalProjectFolders(), { root: this.workspace.path }),
|
|
1095
|
+
);
|
|
1096
|
+
const missing = missingProjectFolders(ids, folders);
|
|
1097
|
+
if (missing.length) {
|
|
1098
|
+
const names = missing.map(id => {
|
|
1099
|
+
const index = ids.indexOf(id);
|
|
1100
|
+
return (Array.isArray(body.projectNames) && body.projectNames[index]) || id;
|
|
1101
|
+
});
|
|
1102
|
+
return send(400, {
|
|
1103
|
+
ok: false,
|
|
1104
|
+
missingProjects: missing,
|
|
1105
|
+
message: `以下项目还没有可用的本地文件夹:${names.join("、")}。请先停止服务,在启动页为它们添加文件夹后再启动。`,
|
|
1106
|
+
});
|
|
1107
|
+
}
|
|
1108
|
+
// 运行中可能新增勾选项目:按新的范围重建仓库与根目录。
|
|
1109
|
+
// 否则新项目的任务仍按启动时的旧 repos / rootPath 派工,修复 Agent
|
|
1110
|
+
// 会落到别的项目目录里改代码;新项目也会因 describeRepos 找不到映射而拿不到文件夹。
|
|
1111
|
+
const selectedFolders = Object.fromEntries(
|
|
1112
|
+
Object.entries(folders).filter(([id]) => ids.includes(String(id))),
|
|
1113
|
+
);
|
|
1114
|
+
const mappedRoot = commonAncestorPath(
|
|
1115
|
+
Object.values(selectedFolders).flatMap(entry => (entry.folders || []).map(f => f.path)),
|
|
1116
|
+
);
|
|
1117
|
+
const mappedRepos = projectFoldersToRepos(selectedFolders, { root: mappedRoot || this.workspace.path });
|
|
1118
|
+
const confirmedAt = new Date().toISOString();
|
|
1119
|
+
const patch = {
|
|
1120
|
+
projectIds: ids,
|
|
1121
|
+
projectNames: body.projectNames || [],
|
|
1122
|
+
confirmedAt,
|
|
1123
|
+
// 全局映射可能在上次启动后又加过文件夹,一并刷新到运行中的工作区
|
|
1124
|
+
projectFolders: folders,
|
|
1125
|
+
};
|
|
1126
|
+
if (mappedRepos.length) {
|
|
1127
|
+
patch.repos = mappedRepos;
|
|
1128
|
+
patch.multiRepo = true;
|
|
1129
|
+
patch.rootPath = mappedRoot || this.workspace.path;
|
|
1130
|
+
}
|
|
1131
|
+
const previousIds = (this.workspace.projectIds || []).map(v => String(v).trim());
|
|
1132
|
+
writeWorkspace(this.workspace.path, { projectIds: ids, projectNames: body.projectNames || [], confirmedAt });
|
|
1133
|
+
Object.assign(this.workspace, patch);
|
|
1134
|
+
if (patch.rootPath && this.coordinator) this.coordinator.rootPath = patch.rootPath;
|
|
1135
|
+
|
|
1136
|
+
// 取消勾选的项目不能再继续改文件:终止它正在跑的 worker(迟到汇报也会被作用域拦下)。
|
|
1137
|
+
// 不在内存里跑的中间态任务保持原状,等下次启动或重新勾选时恢复。
|
|
1138
|
+
const removed = new Set(previousIds.filter(id => id && !ids.includes(id)));
|
|
1139
|
+
if (removed.size && this.coordinator) {
|
|
1140
|
+
for (const t of listTasks()) {
|
|
1141
|
+
if (!removed.has(String(t.projectId ?? "").trim())) continue;
|
|
1142
|
+
if (!this.coordinator.running?.has(t.taskId)) continue;
|
|
1143
|
+
await this.coordinator.abortWorker(t.taskId, "项目已从绑定范围移除");
|
|
1144
|
+
}
|
|
1145
|
+
}
|
|
1146
|
+
this.reason = REASON_CODES.normal;
|
|
1147
|
+
this.scheduler.start();
|
|
1148
|
+
this.emit({ type: "workspace_bound", projectIds: ids });
|
|
1149
|
+
return send(200, { ok: true });
|
|
1150
|
+
}
|
|
1151
|
+
|
|
1152
|
+
if (p === "/api/stop" && method === "POST") {
|
|
1153
|
+
setTimeout(() => this.stop().then(() => process.exit(0)), 100);
|
|
1154
|
+
return send(200, { ok: true });
|
|
1155
|
+
}
|
|
1156
|
+
|
|
1157
|
+
return send(404, { message: `未知接口: ${p}` });
|
|
1158
|
+
}
|
|
1159
|
+
|
|
1160
|
+
/* ---------- 启动配置 ---------- */
|
|
1161
|
+
|
|
1162
|
+
async setupData(force = false) {
|
|
1163
|
+
const now = Date.now();
|
|
1164
|
+
if (!force && this._setupCache && now - this._setupCacheAt < SETUP_CACHE_MS) {
|
|
1165
|
+
return { ...this._setupCache, phase: this.phase };
|
|
1166
|
+
}
|
|
1167
|
+
// 「重新检测」必须重新探测 Agent:用户可能刚在另一个终端安装并登录。
|
|
1168
|
+
if (force) {
|
|
1169
|
+
this._agents = null;
|
|
1170
|
+
refreshAgentCache();
|
|
1171
|
+
}
|
|
1172
|
+
|
|
1173
|
+
const wsPath = this.workspace.path;
|
|
1174
|
+
const [info, agents, projectData] = await Promise.all([
|
|
1175
|
+
inspectWorkspace(wsPath).catch(() => ({
|
|
1176
|
+
isRepo: false, multiRepo: false, repos: [], remote: null, dirty: false,
|
|
1177
|
+
dirtyFiles: [], fingerprints: [], recognizable: false,
|
|
1178
|
+
})),
|
|
1179
|
+
this.describeAgentsCached(),
|
|
1180
|
+
this.loadProjects(),
|
|
1181
|
+
]);
|
|
1182
|
+
|
|
1183
|
+
const saved = readWorkspace(wsPath) || {};
|
|
1184
|
+
const config = readConfig();
|
|
1185
|
+
// 文件夹映射是跨工作区配置:全局文件为准,同时并入本工作区旧版本遗留的条目。
|
|
1186
|
+
const projectFolders = annotateFolderExistence(mergeProjectFolders(
|
|
1187
|
+
normalizeProjectFolders(saved.projectFolders, { root: wsPath }),
|
|
1188
|
+
normalizeProjectFolders(loadGlobalProjectFolders(), { root: wsPath }),
|
|
1189
|
+
));
|
|
1190
|
+
// 启动目录如果落在某个已映射的项目文件夹里,自动带出对应项目,省一次手动勾选
|
|
1191
|
+
const detected = detectProjectFromFolders(projectFolders, this.launchCwd);
|
|
1192
|
+
const candidates = matchProjects(projectData.projects, {
|
|
1193
|
+
fingerprints: info.fingerprints || [],
|
|
1194
|
+
remote: info.remote || null,
|
|
1195
|
+
});
|
|
1196
|
+
|
|
1197
|
+
// 工作区配置档:目录命中或用户显式指定的那个排在最前
|
|
1198
|
+
const profiles = listProfiles(wsPath);
|
|
1199
|
+
const picked = resolveProfile({ cwd: wsPath, profileId: saved.profileId || null, profiles });
|
|
1200
|
+
const activeProfile = picked.ok ? picked.profile : null;
|
|
1201
|
+
const profileWorkspace = activeProfile
|
|
1202
|
+
? profileToWorkspace(activeProfile, { workspacePath: wsPath, remoteKey: info.remoteKey })
|
|
1203
|
+
: null;
|
|
1204
|
+
|
|
1205
|
+
const rec = new Map(candidates.map(c => [String(c.projectId), c]));
|
|
1206
|
+
const projects = projectData.projects
|
|
1207
|
+
.map(p => {
|
|
1208
|
+
const hit = rec.get(String(p.id));
|
|
1209
|
+
return {
|
|
1210
|
+
id: p.id,
|
|
1211
|
+
name: p.name,
|
|
1212
|
+
status: p.status ?? null,
|
|
1213
|
+
recommended: !!hit,
|
|
1214
|
+
reasons: hit?.reasons || [],
|
|
1215
|
+
score: hit?.score || 0,
|
|
1216
|
+
};
|
|
1217
|
+
})
|
|
1218
|
+
.sort((a, b) => (Number(b.recommended) - Number(a.recommended))
|
|
1219
|
+
|| (b.score - a.score)
|
|
1220
|
+
|| String(a.name).localeCompare(String(b.name)));
|
|
1221
|
+
|
|
1222
|
+
const detectedVerify = detectVerifyCommand(wsPath);
|
|
1223
|
+
const savedVerify = Array.isArray(saved.verifyCommands) && saved.verifyCommands.length
|
|
1224
|
+
? saved.verifyCommands
|
|
1225
|
+
: (saved.verifyCommand
|
|
1226
|
+
? [saved.verifyCommand]
|
|
1227
|
+
: (detectedVerify ? [detectedVerify] : []));
|
|
1228
|
+
|
|
1229
|
+
const data = {
|
|
1230
|
+
workspace: {
|
|
1231
|
+
path: wsPath,
|
|
1232
|
+
isRepo: !!info.isRepo,
|
|
1233
|
+
multiRepo: !!info.multiRepo,
|
|
1234
|
+
repos: (info.repos || []).map(r => ({ name: r.name, remote: r.remote || null })),
|
|
1235
|
+
remote: info.remote || null,
|
|
1236
|
+
dirty: !!info.dirty,
|
|
1237
|
+
dirtyFiles: info.dirtyFiles || [],
|
|
1238
|
+
recognizable: !!info.recognizable,
|
|
1239
|
+
},
|
|
1240
|
+
agents,
|
|
1241
|
+
projects,
|
|
1242
|
+
projectsError: projectData.error || null,
|
|
1243
|
+
// 工作区配置档:供配置页选择,并显示仓库结构与巡检时段
|
|
1244
|
+
profiles: profiles.map(p => ({
|
|
1245
|
+
id: p.id,
|
|
1246
|
+
label: p.label,
|
|
1247
|
+
root: p.root,
|
|
1248
|
+
projectIds: p.projectIds,
|
|
1249
|
+
projectNames: p.projectNames,
|
|
1250
|
+
repos: p.repos.map(r => ({
|
|
1251
|
+
name: r.name,
|
|
1252
|
+
role: r.role,
|
|
1253
|
+
branch: r.branch,
|
|
1254
|
+
testBranch: r.testBranch,
|
|
1255
|
+
verify: r.verify,
|
|
1256
|
+
})),
|
|
1257
|
+
schedule: describeSchedule(p.schedule),
|
|
1258
|
+
active: activeProfile?.id === p.id,
|
|
1259
|
+
})),
|
|
1260
|
+
activeProfile: activeProfile
|
|
1261
|
+
? {
|
|
1262
|
+
id: activeProfile.id,
|
|
1263
|
+
label: activeProfile.label,
|
|
1264
|
+
projectIds: activeProfile.projectIds,
|
|
1265
|
+
projectNames: activeProfile.projectNames,
|
|
1266
|
+
intervalSeconds: activeProfile.intervalSeconds,
|
|
1267
|
+
maxWorkers: activeProfile.maxWorkers,
|
|
1268
|
+
autoVerify: activeProfile.autoVerify,
|
|
1269
|
+
prompt: activeProfile.prompt,
|
|
1270
|
+
push: activeProfile.push,
|
|
1271
|
+
repos: profileWorkspace.repos.map(r => ({
|
|
1272
|
+
name: r.name, role: r.role, branch: r.branch, testBranch: r.testBranch, verify: r.verify,
|
|
1273
|
+
})),
|
|
1274
|
+
schedule: describeSchedule(activeProfile.schedule),
|
|
1275
|
+
}
|
|
1276
|
+
: null,
|
|
1277
|
+
saved: {
|
|
1278
|
+
agent: saved.agent || config.lastAgent || null,
|
|
1279
|
+
workerAgent: saved.workerAgent || null,
|
|
1280
|
+
model: saved.model || config.model || "",
|
|
1281
|
+
workerModel: saved.workerModel || config.workerModel || "",
|
|
1282
|
+
projectIds: saved.projectIds || [],
|
|
1283
|
+
projectNames: saved.projectNames || [],
|
|
1284
|
+
// 启动页选择的「敏捷项目 → 本地文件夹」映射
|
|
1285
|
+
projectFolders,
|
|
1286
|
+
// 配置档声明的值作为配置页预填;用户已保存过的优先
|
|
1287
|
+
intervalSeconds: saved.intervalSeconds || activeProfile?.intervalSeconds || config.intervalSeconds || 60,
|
|
1288
|
+
maxWorkers: saved.maxWorkers || activeProfile?.maxWorkers || 3,
|
|
1289
|
+
verifyCommands: savedVerify,
|
|
1290
|
+
autoVerify: saved.autoVerify === true || activeProfile?.autoVerify === true,
|
|
1291
|
+
isolateWorktrees: saved.isolateWorktrees ?? null,
|
|
1292
|
+
testBranch: saved.testBranch || "",
|
|
1293
|
+
prompt: saved.prompt || activeProfile?.prompt || "",
|
|
1294
|
+
profileId: activeProfile?.id || saved.profileId || null,
|
|
1295
|
+
},
|
|
1296
|
+
// 启动目录自动匹配结果:前端据此直接勾选对应项目并给出提示
|
|
1297
|
+
detected: {
|
|
1298
|
+
cwd: detected.cwd,
|
|
1299
|
+
projectIds: detected.projectIds,
|
|
1300
|
+
projects: detected.projects,
|
|
1301
|
+
},
|
|
1302
|
+
// 系统原生文件夹选择窗口:Windows 的服务进程拉起 COM / WinForms 对话框时,
|
|
1303
|
+
// 窗口不会显示且 ShowDialog 永久挂起(实测),因此 Windows 统一走页面内选择器;
|
|
1304
|
+
// macOS / Linux 的 osascript / zenity 可正常弹出,保留为次要入口。
|
|
1305
|
+
nativeFolderPicker: process.platform !== "win32",
|
|
1306
|
+
startedAt: new Date().toISOString(),
|
|
1307
|
+
};
|
|
1308
|
+
|
|
1309
|
+
this._setupCache = data;
|
|
1310
|
+
this._setupCacheAt = now;
|
|
1311
|
+
return { ...data, phase: this.phase };
|
|
1312
|
+
}
|
|
1313
|
+
|
|
1314
|
+
async describeAgentsCached() {
|
|
1315
|
+
if (this._agents) return this._agents;
|
|
1316
|
+
if (this.deps.describeAgents) this._agents = await this.deps.describeAgents();
|
|
1317
|
+
else this._agents = await describeAgents();
|
|
1318
|
+
return this._agents;
|
|
1319
|
+
}
|
|
1320
|
+
|
|
1321
|
+
async loadProjects() {
|
|
1322
|
+
try {
|
|
1323
|
+
await this.api.whoami();
|
|
1324
|
+
const list = await this.api.listProjects();
|
|
1325
|
+
return {
|
|
1326
|
+
projects: (list || []).map(p => ({ id: p.id, name: p.name, status: p.status ?? null })),
|
|
1327
|
+
error: null,
|
|
1328
|
+
};
|
|
1329
|
+
} catch (e) {
|
|
1330
|
+
return {
|
|
1331
|
+
projects: [],
|
|
1332
|
+
error: {
|
|
1333
|
+
code: classifyError(e),
|
|
1334
|
+
message: String(e?.message || e),
|
|
1335
|
+
},
|
|
1336
|
+
};
|
|
1337
|
+
}
|
|
1338
|
+
}
|
|
1339
|
+
|
|
1340
|
+
async handleStart(body = {}) {
|
|
1341
|
+
if (this.phase === "running") {
|
|
1342
|
+
return { ok: false, code: 409, message: "服务已经在运行,如需修改配置请先停止服务。" };
|
|
1343
|
+
}
|
|
1344
|
+
if (body.acceptRisk !== true) {
|
|
1345
|
+
return { ok: false, code: 400, message: "请先确认最大权限提示。" };
|
|
1346
|
+
}
|
|
1347
|
+
|
|
1348
|
+
const mainAgent = String(body.mainAgent || "").trim();
|
|
1349
|
+
const workerAgent = String(body.workerAgent || mainAgent).trim();
|
|
1350
|
+
if (!SUPPORTED_AGENTS.includes(mainAgent)) {
|
|
1351
|
+
return { ok: false, code: 400, message: `未知的主 Agent:${mainAgent || "(空)"}` };
|
|
1352
|
+
}
|
|
1353
|
+
if (!SUPPORTED_AGENTS.includes(workerAgent)) {
|
|
1354
|
+
return { ok: false, code: 400, message: `未知的修复 Agent:${workerAgent || "(空)"}` };
|
|
1355
|
+
}
|
|
1356
|
+
|
|
1357
|
+
const setup = await this.setupData();
|
|
1358
|
+
const projectIds = (Array.isArray(body.projectIds) ? body.projectIds : [])
|
|
1359
|
+
.map(v => String(v).trim())
|
|
1360
|
+
.filter(Boolean);
|
|
1361
|
+
const nameById = new Map((setup.projects || []).map(p => [String(p.id), p.name]));
|
|
1362
|
+
const projectNames = projectIds.map((id, i) => (
|
|
1363
|
+
Array.isArray(body.projectNames) && body.projectNames[i] ? String(body.projectNames[i]) : (nameById.get(id) || id)
|
|
1364
|
+
));
|
|
1365
|
+
|
|
1366
|
+
// 工作区配置档:页面选了哪个档,就按它声明的仓库结构与巡检策略来跑
|
|
1367
|
+
const profileId = String(body.profileId || setup.activeProfile?.id || "").trim();
|
|
1368
|
+
let profile = null;
|
|
1369
|
+
let profileWorkspace = null;
|
|
1370
|
+
if (profileId) {
|
|
1371
|
+
const picked = resolveProfile({ cwd: this.workspace.path, profileId, profiles: listProfiles(this.workspace.path) });
|
|
1372
|
+
if (!picked.ok) return { ok: false, code: 400, message: picked.message };
|
|
1373
|
+
profile = picked.profile;
|
|
1374
|
+
profileWorkspace = profileToWorkspace(profile, { workspacePath: profile.root || this.workspace.path });
|
|
1375
|
+
}
|
|
1376
|
+
|
|
1377
|
+
const verifyCommands = (Array.isArray(body.verifyCommands) ? body.verifyCommands : [body.verifyCommands])
|
|
1378
|
+
.map(v => String(v || "").trim())
|
|
1379
|
+
.filter(Boolean);
|
|
1380
|
+
const intervalSeconds = Math.max(15, Number.parseInt(body.intervalSeconds, 10) || profile?.intervalSeconds || 60);
|
|
1381
|
+
// 并行修复的 worker 数量:太少效率低,太多会互相拖慢并放大冲突风险
|
|
1382
|
+
const maxWorkers = Math.min(6, Math.max(1, Number.parseInt(body.maxWorkers, 10) || profile?.maxWorkers || 3));
|
|
1383
|
+
// 工作树隔离:true 强制开启、false 强制关闭、null 明确回自动;未传则保持上次选择/自动
|
|
1384
|
+
let isolateWorktrees;
|
|
1385
|
+
if (Object.prototype.hasOwnProperty.call(body, "isolateWorktrees")) {
|
|
1386
|
+
isolateWorktrees = body.isolateWorktrees === true ? true : body.isolateWorktrees === false ? false : null;
|
|
1387
|
+
} else {
|
|
1388
|
+
isolateWorktrees = this.workspace.isolateWorktrees ?? null;
|
|
1389
|
+
}
|
|
1390
|
+
const clean = (v) => {
|
|
1391
|
+
const s = String(v ?? "").trim();
|
|
1392
|
+
return s || null;
|
|
1393
|
+
};
|
|
1394
|
+
|
|
1395
|
+
// 启动页选择的「敏捷项目 → 本地文件夹」映射优先级最高:
|
|
1396
|
+
// 用户明确指定了缺陷该在哪个电脑文件夹里修,就按这个来。
|
|
1397
|
+
const allProjectFolders = normalizeProjectFolders(
|
|
1398
|
+
body.projectFolders !== undefined
|
|
1399
|
+
? body.projectFolders
|
|
1400
|
+
: mergeProjectFolders(
|
|
1401
|
+
this.workspace.projectFolders || readWorkspace(this.workspace.path)?.projectFolders || {},
|
|
1402
|
+
loadGlobalProjectFolders(),
|
|
1403
|
+
),
|
|
1404
|
+
{ root: this.workspace.path },
|
|
1405
|
+
);
|
|
1406
|
+
// 勾了项目却没告诉系统代码在哪,修复 Agent 会退回启动目录或别的项目文件夹。
|
|
1407
|
+
// 启动前强制校验:每个已选项目至少有一个存在的本地文件夹;配置档不豁免。
|
|
1408
|
+
const missingProjects = missingProjectFolders(projectIds, allProjectFolders);
|
|
1409
|
+
if (missingProjects.length) {
|
|
1410
|
+
const names = missingProjects.map(id => nameById.get(String(id)) || id);
|
|
1411
|
+
return {
|
|
1412
|
+
ok: false,
|
|
1413
|
+
code: 400,
|
|
1414
|
+
missingProjects,
|
|
1415
|
+
message: `以下已选项目还没有可用的本地文件夹:${names.join("、")}。请先在项目行里点「+ 添加文件夹」;文件夹被移动或删除的也要重新选择。`,
|
|
1416
|
+
};
|
|
1417
|
+
}
|
|
1418
|
+
|
|
1419
|
+
// 启动时把本次映射并入全局文件(取并集,删除仍以启动页的即时保存为准),
|
|
1420
|
+
// 下一次换目录启动也照样能带出来。
|
|
1421
|
+
writeProjectFolderStore(mergeProjectFolders(loadGlobalProjectFolders(), allProjectFolders));
|
|
1422
|
+
const selectedProjectFolders = Object.fromEntries(
|
|
1423
|
+
Object.entries(allProjectFolders).filter(([id]) => projectIds.includes(String(id))),
|
|
1424
|
+
);
|
|
1425
|
+
// 一个项目可能对应多个并列文件夹(前端 / 后端 / 移动端)。任务工作区
|
|
1426
|
+
// 需要落在它们的公共父目录上,工作树、提交、验证才能按仓库拆分;
|
|
1427
|
+
// 没有公共父目录时退回启动目录。
|
|
1428
|
+
const mappedRoot = commonAncestorPath(
|
|
1429
|
+
Object.values(selectedProjectFolders).flatMap(entry => (entry.folders || []).map(f => f.path)),
|
|
1430
|
+
);
|
|
1431
|
+
const repoRoot = mappedRoot || this.workspace.path;
|
|
1432
|
+
const mappedRepos = projectFoldersToRepos(selectedProjectFolders, { root: repoRoot });
|
|
1433
|
+
|
|
1434
|
+
const repos = mappedRepos.length
|
|
1435
|
+
? mappedRepos
|
|
1436
|
+
: (profileWorkspace?.repos?.length
|
|
1437
|
+
? profileWorkspace.repos
|
|
1438
|
+
: (this.workspace.repos || []));
|
|
1439
|
+
const schedule = profileWorkspace?.schedule || this.workspace.schedule || null;
|
|
1440
|
+
const review = profileWorkspace?.review || this.workspace.review || null;
|
|
1441
|
+
|
|
1442
|
+
const workspace = {
|
|
1443
|
+
...this.workspace,
|
|
1444
|
+
agent: mainAgent,
|
|
1445
|
+
workerAgent,
|
|
1446
|
+
model: clean(body.mainModel),
|
|
1447
|
+
workerModel: clean(body.workerModel),
|
|
1448
|
+
projectIds,
|
|
1449
|
+
projectNames,
|
|
1450
|
+
intervalSeconds,
|
|
1451
|
+
maxWorkers,
|
|
1452
|
+
verifyCommand: verifyCommands[0] || null,
|
|
1453
|
+
verifyCommands,
|
|
1454
|
+
autoVerify: body.autoVerify === true,
|
|
1455
|
+
// 任务级 Git 工作树隔离:未明确指定时交由 Coordinator 按仓库形态自动判断
|
|
1456
|
+
isolateWorktrees,
|
|
1457
|
+
// 提测要合并到哪个分支:留空则由 git 自动在 test/dev/uat 里挑一个
|
|
1458
|
+
testBranch: clean(body.testBranch),
|
|
1459
|
+
prompt: String(body.prompt || "").trim() || DEFAULT_PROMPT,
|
|
1460
|
+
confirmedAt: new Date().toISOString(),
|
|
1461
|
+
// 配置档带来的调度策略
|
|
1462
|
+
profileId: profile?.id || null,
|
|
1463
|
+
profileLabel: profile?.label || null,
|
|
1464
|
+
repos,
|
|
1465
|
+
multiRepo: repos.length > 0,
|
|
1466
|
+
// 任务实际根目录:项目文件夹的公共父目录(或配置档根目录)。
|
|
1467
|
+
// 与 path(用户启动 CLI 的目录)分开,避免写配置 / 会话时改变工作区标识。
|
|
1468
|
+
rootPath: mappedRepos.length ? repoRoot : (profileWorkspace?.root || null),
|
|
1469
|
+
// 「敏捷项目 → 本地文件夹」映射:启动页可选择、控制台可展示
|
|
1470
|
+
projectFolders: allProjectFolders,
|
|
1471
|
+
schedule,
|
|
1472
|
+
review,
|
|
1473
|
+
excludedRepos: profileWorkspace?.excludedRepos ?? this.workspace.excludedRepos ?? null,
|
|
1474
|
+
push: profile?.push ?? this.workspace.push ?? null,
|
|
1475
|
+
};
|
|
1476
|
+
|
|
1477
|
+
writeWorkspace(workspace.path, {
|
|
1478
|
+
agent: workspace.agent,
|
|
1479
|
+
workerAgent: workspace.workerAgent,
|
|
1480
|
+
model: workspace.model,
|
|
1481
|
+
workerModel: workspace.workerModel,
|
|
1482
|
+
projectIds: workspace.projectIds,
|
|
1483
|
+
projectNames: workspace.projectNames,
|
|
1484
|
+
intervalSeconds: workspace.intervalSeconds,
|
|
1485
|
+
maxWorkers: workspace.maxWorkers,
|
|
1486
|
+
verifyCommand: workspace.verifyCommand,
|
|
1487
|
+
verifyCommands: workspace.verifyCommands,
|
|
1488
|
+
autoVerify: workspace.autoVerify,
|
|
1489
|
+
isolateWorktrees: workspace.isolateWorktrees ?? null,
|
|
1490
|
+
testBranch: workspace.testBranch,
|
|
1491
|
+
prompt: workspace.prompt,
|
|
1492
|
+
profileId: workspace.profileId,
|
|
1493
|
+
projectFolders: workspace.projectFolders,
|
|
1494
|
+
confirmedAt: workspace.confirmedAt,
|
|
1495
|
+
});
|
|
1496
|
+
writeConfig({
|
|
1497
|
+
agent: "auto",
|
|
1498
|
+
lastAgent: mainAgent,
|
|
1499
|
+
model: workspace.model,
|
|
1500
|
+
workerModel: workspace.workerModel,
|
|
1501
|
+
intervalSeconds,
|
|
1502
|
+
});
|
|
1503
|
+
|
|
1504
|
+
this.workspace = workspace;
|
|
1505
|
+
this.options = {
|
|
1506
|
+
...this.options,
|
|
1507
|
+
agent: mainAgent,
|
|
1508
|
+
workerAgent,
|
|
1509
|
+
model: workspace.model,
|
|
1510
|
+
workerModel: workspace.workerModel,
|
|
1511
|
+
intervalSeconds,
|
|
1512
|
+
};
|
|
1513
|
+
this.setup = false;
|
|
1514
|
+
this._setupCache = null;
|
|
1515
|
+
this._detailCache.clear();
|
|
1516
|
+
|
|
1517
|
+
await this.startRuntime();
|
|
1518
|
+
this.emit({
|
|
1519
|
+
type: "workspace_configured",
|
|
1520
|
+
agent: mainAgent,
|
|
1521
|
+
workerAgent,
|
|
1522
|
+
projectIds,
|
|
1523
|
+
projectNames,
|
|
1524
|
+
message: projectIds.length
|
|
1525
|
+
? `已启动:主 Agent ${mainAgent},修复 Agent ${workerAgent},项目 ${projectNames.join(", ")}`
|
|
1526
|
+
: "已以观察模式启动:未绑定敏捷项目,不会拉取缺陷。",
|
|
1527
|
+
});
|
|
1528
|
+
|
|
1529
|
+
return { ok: true, status: this.status() };
|
|
1530
|
+
}
|
|
1531
|
+
|
|
1532
|
+
/** 运行中切换模型:写入工作区并立即用于下一次主 Agent 唤醒 / worker 派工。 */
|
|
1533
|
+
async handleModelChange(body = {}) {
|
|
1534
|
+
if (this.phase !== "running") {
|
|
1535
|
+
return { ok: false, code: 409, message: "服务尚未启动,请先在控制台完成启动配置。" };
|
|
1536
|
+
}
|
|
1537
|
+
const clean = (value) => {
|
|
1538
|
+
const text = String(value ?? "").trim();
|
|
1539
|
+
return text || null;
|
|
1540
|
+
};
|
|
1541
|
+
const model = clean(body.mainModel);
|
|
1542
|
+
const workerModel = clean(body.workerModel);
|
|
1543
|
+
for (const value of [model, workerModel]) {
|
|
1544
|
+
if (value && value.length > 300) {
|
|
1545
|
+
return { ok: false, code: 400, message: "模型名称过长。" };
|
|
1546
|
+
}
|
|
1547
|
+
}
|
|
1548
|
+
|
|
1549
|
+
this.workspace = { ...this.workspace, model, workerModel };
|
|
1550
|
+
this.options = { ...this.options, model, workerModel };
|
|
1551
|
+
if (this.coordinator) {
|
|
1552
|
+
this.coordinator.options = { ...this.coordinator.options, model, workerModel };
|
|
1553
|
+
}
|
|
1554
|
+
writeWorkspace(this.workspace.path, { model, workerModel });
|
|
1555
|
+
writeConfig({ model, workerModel });
|
|
1556
|
+
|
|
1557
|
+
this.emit({
|
|
1558
|
+
type: "model_changed",
|
|
1559
|
+
agent: this.workspace.agent,
|
|
1560
|
+
workerAgent: this.workspace.workerAgent,
|
|
1561
|
+
model,
|
|
1562
|
+
workerModel,
|
|
1563
|
+
});
|
|
1564
|
+
return { ok: true, status: this.status() };
|
|
1565
|
+
}
|
|
1566
|
+
|
|
1567
|
+
/** 运行中读取可选模型列表,供「切换大模型」弹窗使用。 */
|
|
1568
|
+
async modelsData(force = false) {
|
|
1569
|
+
if (force) {
|
|
1570
|
+
this._agents = null;
|
|
1571
|
+
refreshAgentCache();
|
|
1572
|
+
}
|
|
1573
|
+
return {
|
|
1574
|
+
agents: await this.describeAgentsCached(),
|
|
1575
|
+
current: {
|
|
1576
|
+
mainAgent: this.workspace.agent || null,
|
|
1577
|
+
workerAgent: this.workspace.workerAgent || this.workspace.agent || null,
|
|
1578
|
+
model: this.workspace.model || null,
|
|
1579
|
+
workerModel: this.workspace.workerModel || null,
|
|
1580
|
+
},
|
|
1581
|
+
};
|
|
1582
|
+
}
|
|
1583
|
+
|
|
1584
|
+
/* ---------- 任务详情 ---------- */
|
|
1585
|
+
|
|
1586
|
+
async taskDetail(id) {
|
|
1587
|
+
const task = readTask(id);
|
|
1588
|
+
if (!task) return { task: null, remote: null, comments: [], error: { code: "not_found", message: "未知任务" } };
|
|
1589
|
+
|
|
1590
|
+
const cached = this._detailCache.get(id);
|
|
1591
|
+
if (cached && Date.now() - cached.at < 10000) {
|
|
1592
|
+
return { task, remote: cached.remote, comments: cached.comments, error: cached.error };
|
|
1593
|
+
}
|
|
1594
|
+
|
|
1595
|
+
let remote = null;
|
|
1596
|
+
let comments = [];
|
|
1597
|
+
let error = null;
|
|
1598
|
+
if (task.bugId != null) {
|
|
1599
|
+
try {
|
|
1600
|
+
const [bug, list] = await Promise.all([
|
|
1601
|
+
this.api.getBug(task.bugId),
|
|
1602
|
+
this.api.listComments(task.bugId),
|
|
1603
|
+
]);
|
|
1604
|
+
remote = bug;
|
|
1605
|
+
comments = Array.isArray(list) ? list.slice(0, 20) : [];
|
|
1606
|
+
} catch (e) {
|
|
1607
|
+
error = { code: classifyError(e), message: String(e?.message || e) };
|
|
1608
|
+
}
|
|
1609
|
+
}
|
|
1610
|
+
this._detailCache.set(id, { at: Date.now(), remote, comments, error });
|
|
1611
|
+
return { task, remote, comments, error };
|
|
1612
|
+
}
|
|
1613
|
+
|
|
1614
|
+
/** 控制台手动操作的任务是否越界;没有 projectId 的旧任务不算。 */
|
|
1615
|
+
taskScopeViolation(task) {
|
|
1616
|
+
const projectId = String(task?.projectId ?? "").trim();
|
|
1617
|
+
if (!projectId) return null;
|
|
1618
|
+
if (taskInProjectScope(task, null, boundProjectSet(this.workspace?.projectIds))) return null;
|
|
1619
|
+
return `任务 ${task.taskId || ""} 属于项目 ${projectId},不在当前绑定范围内,拒绝处理`;
|
|
1620
|
+
}
|
|
1621
|
+
|
|
1622
|
+
status() {
|
|
1623
|
+
const ws = this.workspace;
|
|
1624
|
+
// 统计只算当前绑定项目,避免别的项目的历史任务撑大待办/已完成数量
|
|
1625
|
+
const bound = boundProjectSet(ws.projectIds);
|
|
1626
|
+
const tasks = listTasks().filter(t => taskInProjectScope(t, null, bound));
|
|
1627
|
+
const counts = {};
|
|
1628
|
+
for (const t of tasks) counts[t.status] = (counts[t.status] || 0) + 1;
|
|
1629
|
+
const agent = ws.agent || this.options.agent || null;
|
|
1630
|
+
const workerAgent = ws.workerAgent || this.options.workerAgent || agent;
|
|
1631
|
+
return {
|
|
1632
|
+
phase: this.phase,
|
|
1633
|
+
running: this.phase === "running" && !this.stopped,
|
|
1634
|
+
paused: this.paused,
|
|
1635
|
+
port: this.port,
|
|
1636
|
+
// 本次运行批次号;界面按缺陷线上是否已关闭区分历史,不再用它过滤任务
|
|
1637
|
+
runId: this.runId,
|
|
1638
|
+
workspace: {
|
|
1639
|
+
path: ws.path,
|
|
1640
|
+
// 任务实际根目录:多文件夹项目的公共父目录,通常与 path 不同
|
|
1641
|
+
rootPath: ws.rootPath || null,
|
|
1642
|
+
agent,
|
|
1643
|
+
model: ws.model ?? this.options.model ?? null,
|
|
1644
|
+
workerAgent,
|
|
1645
|
+
workerModel: ws.workerModel ?? this.options.workerModel ?? null,
|
|
1646
|
+
intervalSeconds: ws.intervalSeconds ?? this.options.intervalSeconds ?? 60,
|
|
1647
|
+
projectIds: ws.projectIds || [],
|
|
1648
|
+
projectNames: ws.projectNames || [],
|
|
1649
|
+
verifyCommand: ws.verifyCommand || null,
|
|
1650
|
+
verifyCommands: Array.isArray(ws.verifyCommands) && ws.verifyCommands.length
|
|
1651
|
+
? ws.verifyCommands
|
|
1652
|
+
: (ws.verifyCommand ? [ws.verifyCommand] : []),
|
|
1653
|
+
autoVerify: !!ws.autoVerify,
|
|
1654
|
+
// 工作树隔离:null 表示自动(Git 仓库默认启用),保留 null 不抹成布尔值
|
|
1655
|
+
isolateWorktrees: ws.isolateWorktrees ?? null,
|
|
1656
|
+
testBranch: ws.testBranch || null,
|
|
1657
|
+
prompt: ws.prompt || null,
|
|
1658
|
+
multiRepo: !!ws.multiRepo,
|
|
1659
|
+
// 工作区配置档信息:多仓库结构与巡检时段
|
|
1660
|
+
profileId: ws.profileId || null,
|
|
1661
|
+
profileLabel: ws.profileLabel || null,
|
|
1662
|
+
repos: (ws.repos || []).map(r => ({
|
|
1663
|
+
name: r.name,
|
|
1664
|
+
path: r.path || null,
|
|
1665
|
+
role: r.role,
|
|
1666
|
+
projectId: r.projectId ?? null,
|
|
1667
|
+
projectName: r.projectName || null,
|
|
1668
|
+
branch: r.branch || null,
|
|
1669
|
+
testBranch: r.testBranch || null,
|
|
1670
|
+
verify: r.verify || [],
|
|
1671
|
+
})),
|
|
1672
|
+
projectFolders: ws.projectFolders || {},
|
|
1673
|
+
schedule: ws.schedule || null,
|
|
1674
|
+
scheduleText: describeSchedule(ws.schedule),
|
|
1675
|
+
review: ws.review || null,
|
|
1676
|
+
push: ws.push ?? null,
|
|
1677
|
+
},
|
|
1678
|
+
reason: this.phase === "setup" ? REASON_CODES.setup : this.reason,
|
|
1679
|
+
reasonDetail: this.reasonDetail
|
|
1680
|
+
|| (this.phase === "setup" ? REASON_MESSAGES.setup : REASON_MESSAGES[this.reason])
|
|
1681
|
+
|| null,
|
|
1682
|
+
tasks: counts,
|
|
1683
|
+
questions: listPendingQuestions().length,
|
|
1684
|
+
agentAvailable: !!getAdapter(agent),
|
|
1685
|
+
mainSessionId: this.coordinator?.mainSessionId || null,
|
|
1686
|
+
// 主 Agent 一轮一轮跑,卡住时这里会长期停在 running,是判断“是否失联”的依据
|
|
1687
|
+
main: this.coordinator?.mainState || { status: "idle", lastTrigger: null, lastAt: null, lastOk: null, lastError: null },
|
|
1688
|
+
// 当前各任务的执行阶段:刷新页面后也能立刻看到进度,不用等 SSE 推送
|
|
1689
|
+
stages: this.coordinator ? Object.fromEntries(this.coordinator.taskStages) : {},
|
|
1690
|
+
mainStage: this.coordinator?.mainState?.stage || null,
|
|
1691
|
+
// 本轮为什么没巡检(例如不在工作时段):让用户知道是"没人管"还是"时段外"
|
|
1692
|
+
pollSkipped: this.scheduler?.lastPollSkipped || null,
|
|
1693
|
+
// 并行槽位信息:控制台可以告诉用户「为什么这个缺陷还没派」
|
|
1694
|
+
workers: {
|
|
1695
|
+
running: this.coordinator ? this.coordinator.running.size : 0,
|
|
1696
|
+
max: this.coordinator ? this.coordinator.maxWorkers : (this.workspace.maxWorkers ?? this.options.maxWorkers ?? 3),
|
|
1697
|
+
},
|
|
1698
|
+
};
|
|
1699
|
+
}
|
|
1700
|
+
}
|
|
1701
|
+
|
|
1702
|
+
/* ======================== 辅助 ======================== */
|
|
1703
|
+
|
|
1704
|
+
/**
|
|
1705
|
+
* 合并多份「敏捷项目 → 本地文件夹」映射。
|
|
1706
|
+
* 同一项目下按路径(不区分大小写)去重,后面的映射字段优先,文件夹取并集;
|
|
1707
|
+
* 这样旧工作区里已有的映射能迁移进全局文件,又不会覆盖用户新加的条目。
|
|
1708
|
+
*/
|
|
1709
|
+
export function mergeProjectFolders(...maps) {
|
|
1710
|
+
const out = {};
|
|
1711
|
+
for (const map of maps) {
|
|
1712
|
+
for (const [id, entry] of Object.entries(map || {})) {
|
|
1713
|
+
if (!entry || typeof entry !== "object") continue;
|
|
1714
|
+
const prev = out[id] || { projectName: entry.projectName || "", folders: [] };
|
|
1715
|
+
const folders = [...(prev.folders || [])];
|
|
1716
|
+
for (const folder of entry.folders || []) {
|
|
1717
|
+
if (!folder?.path) continue;
|
|
1718
|
+
const key = String(folder.path).toLowerCase();
|
|
1719
|
+
if (!folders.some(x => String(x.path).toLowerCase() === key)) folders.push(folder);
|
|
1720
|
+
}
|
|
1721
|
+
out[id] = {
|
|
1722
|
+
...prev,
|
|
1723
|
+
...entry,
|
|
1724
|
+
projectName: entry.projectName || prev.projectName || "",
|
|
1725
|
+
folders,
|
|
1726
|
+
};
|
|
1727
|
+
}
|
|
1728
|
+
}
|
|
1729
|
+
return out;
|
|
1730
|
+
}
|
|
1731
|
+
|
|
1732
|
+
/**
|
|
1733
|
+
* 读取全局「项目 → 文件夹」映射,首次调用时做一次性迁移。
|
|
1734
|
+
*
|
|
1735
|
+
* 旧版本把映射存在各工作区文件里,导致换个目录启动就"全没了"。升级后第一次
|
|
1736
|
+
* 启动会扫描全部工作区记录,把已有映射汇总到 project-folders.json;文件一旦
|
|
1737
|
+
* 写入(即使是空对象)就不再迁移,避免用户删掉的条目被旧文件复活。
|
|
1738
|
+
*/
|
|
1739
|
+
/**
|
|
1740
|
+
* 给启动页的映射补一个 exists 标记,前端才能提示「文件夹已被移动/删除」。
|
|
1741
|
+
* 只影响返回值,不写入磁盘(normalizeProjectFolders 会剥掉额外字段)。
|
|
1742
|
+
*/
|
|
1743
|
+
export function annotateFolderExistence(projectFolders = {}) {
|
|
1744
|
+
const out = {};
|
|
1745
|
+
for (const [id, entry] of Object.entries(projectFolders || {})) {
|
|
1746
|
+
out[id] = {
|
|
1747
|
+
...entry,
|
|
1748
|
+
folders: (Array.isArray(entry?.folders) ? entry.folders : []).map(folder => ({
|
|
1749
|
+
...folder,
|
|
1750
|
+
exists: folderPathUsable(folder.path),
|
|
1751
|
+
})),
|
|
1752
|
+
};
|
|
1753
|
+
}
|
|
1754
|
+
return out;
|
|
1755
|
+
}
|
|
1756
|
+
|
|
1757
|
+
export function loadGlobalProjectFolders() {
|
|
1758
|
+
const stored = readProjectFolderStore();
|
|
1759
|
+
if (stored && typeof stored.projectFolders === "object" && stored.projectFolders) {
|
|
1760
|
+
return stored.projectFolders;
|
|
1761
|
+
}
|
|
1762
|
+
let merged = {};
|
|
1763
|
+
for (const ws of listWorkspaces()) {
|
|
1764
|
+
const map = normalizeProjectFolders(ws.projectFolders, { root: ws.path || process.cwd() });
|
|
1765
|
+
merged = mergeProjectFolders(merged, map);
|
|
1766
|
+
}
|
|
1767
|
+
writeProjectFolderStore(merged);
|
|
1768
|
+
return merged;
|
|
1769
|
+
}
|
|
1770
|
+
|
|
1771
|
+
/**
|
|
1772
|
+
* 列出目录下的子文件夹(启动页文件夹选择器使用)。
|
|
1773
|
+
* 只读、不递归;跳过 .git / node_modules 等噪音目录,避免选择器里全是无关项。
|
|
1774
|
+
*/
|
|
1775
|
+
export function listDirectories(rawPath) {
|
|
1776
|
+
const home = os.homedir();
|
|
1777
|
+
let target;
|
|
1778
|
+
try { target = path.resolve(String(rawPath || home || ".")); } catch {
|
|
1779
|
+
return { ok: false, path: String(rawPath || ""), message: "路径无效" };
|
|
1780
|
+
}
|
|
1781
|
+
|
|
1782
|
+
let stat;
|
|
1783
|
+
try { stat = fs.statSync(target); } catch {
|
|
1784
|
+
return { ok: false, path: target, message: "文件夹不存在或无法访问" };
|
|
1785
|
+
}
|
|
1786
|
+
if (!stat.isDirectory()) {
|
|
1787
|
+
return { ok: false, path: target, message: "该路径不是文件夹" };
|
|
1788
|
+
}
|
|
1789
|
+
|
|
1790
|
+
let entries;
|
|
1791
|
+
try {
|
|
1792
|
+
entries = fs.readdirSync(target, { withFileTypes: true });
|
|
1793
|
+
} catch (e) {
|
|
1794
|
+
return { ok: false, path: target, message: `无法读取该文件夹:${e?.message || e}` };
|
|
1795
|
+
}
|
|
1796
|
+
|
|
1797
|
+
const IGNORED = new Set(["node_modules"]);
|
|
1798
|
+
const dirs = entries
|
|
1799
|
+
.filter(d => d.isDirectory() && !d.name.startsWith(".") && !IGNORED.has(d.name))
|
|
1800
|
+
.map(d => {
|
|
1801
|
+
const full = path.join(target, d.name);
|
|
1802
|
+
let isGit = false;
|
|
1803
|
+
try { isGit = fs.existsSync(path.join(full, ".git")); } catch { /* 忽略 */ }
|
|
1804
|
+
return { name: d.name, path: full, isGit };
|
|
1805
|
+
})
|
|
1806
|
+
.sort((a, b) => a.name.localeCompare(b.name, "zh-CN"));
|
|
1807
|
+
|
|
1808
|
+
const parent = path.dirname(target);
|
|
1809
|
+
return {
|
|
1810
|
+
ok: true,
|
|
1811
|
+
path: target,
|
|
1812
|
+
parent: parent && parent !== target ? parent : null,
|
|
1813
|
+
home,
|
|
1814
|
+
// Windows 上「上级」最多回到当前盘符根目录,必须额外给出磁盘列表,
|
|
1815
|
+
// 否则从 C 盘启动就永远选不到 D 盘。
|
|
1816
|
+
drives: listWindowsDrives(),
|
|
1817
|
+
dirs,
|
|
1818
|
+
};
|
|
1819
|
+
}
|
|
1820
|
+
|
|
1821
|
+
let driveCache = { at: 0, drives: [] };
|
|
1822
|
+
|
|
1823
|
+
/**
|
|
1824
|
+
* Windows 可用磁盘根目录列表。
|
|
1825
|
+
*
|
|
1826
|
+
* 浏览器与服务端都没有跨平台的盘符枚举 API,这里探测 C: ~ Z:。
|
|
1827
|
+
* 结果缓存 60 秒,避免每次进出文件夹都重复探测(断开的网络盘可能很慢)。
|
|
1828
|
+
*/
|
|
1829
|
+
export function listWindowsDrives() {
|
|
1830
|
+
if (process.platform !== "win32") return [];
|
|
1831
|
+
const now = Date.now();
|
|
1832
|
+
if (now - driveCache.at < 60_000) return driveCache.drives;
|
|
1833
|
+
const drives = [];
|
|
1834
|
+
for (let code = 67; code <= 90; code += 1) {
|
|
1835
|
+
const letter = String.fromCharCode(code);
|
|
1836
|
+
const root = `${letter}:\\`;
|
|
1837
|
+
try {
|
|
1838
|
+
if (fs.existsSync(root)) drives.push({ name: `${letter}:`, path: root });
|
|
1839
|
+
} catch { /* 未就绪或无权限的盘符跳过 */ }
|
|
1840
|
+
}
|
|
1841
|
+
driveCache = { at: now, drives };
|
|
1842
|
+
return drives;
|
|
1843
|
+
}
|
|
1844
|
+
|
|
1845
|
+
/**
|
|
1846
|
+
* 打开操作系统原生的文件夹选择窗口,返回用户选择的绝对路径。
|
|
1847
|
+
*
|
|
1848
|
+
* 浏览器出于安全限制拿不到本地绝对路径(webkitdirectory 只给相对路径),
|
|
1849
|
+
* 所以对话框必须由本机服务进程拉起:
|
|
1850
|
+
* - macOS:osascript 的 choose folder
|
|
1851
|
+
* - Linux:zenity
|
|
1852
|
+
* - Windows:不调用。后台服务进程拉起 Shell.Application.BrowseForFolder /
|
|
1853
|
+
* WinForms.FolderBrowserDialog / OpenFileDialog 时,对象都能创建成功,但窗口
|
|
1854
|
+
* 不会显示且 ShowDialog 永久挂起(实测);Windows 统一由页面内选择器完成。
|
|
1855
|
+
* 取消返回 { canceled: true };环境不支持时返回 { unsupported: true },前端会退回页面内选择器。
|
|
1856
|
+
*/
|
|
1857
|
+
export function pickSystemFolder({ initialPath = "" } = {}) {
|
|
1858
|
+
if (process.platform === "win32") {
|
|
1859
|
+
return Promise.resolve({ ok: false, unsupported: true, message: "Windows 请使用页面内文件夹选择器" });
|
|
1860
|
+
}
|
|
1861
|
+
|
|
1862
|
+
const start = String(initialPath || "").trim();
|
|
1863
|
+
let command;
|
|
1864
|
+
let args;
|
|
1865
|
+
|
|
1866
|
+
if (process.platform === "darwin") {
|
|
1867
|
+
command = "osascript";
|
|
1868
|
+
args = ["-e", 'POSIX path of (choose folder with prompt "选择项目文件夹")'];
|
|
1869
|
+
} else {
|
|
1870
|
+
command = "zenity";
|
|
1871
|
+
args = ["--file-selection", "--directory", "--title=选择项目文件夹"];
|
|
1872
|
+
if (start) args.push(`--filename=${start}${start.endsWith(path.sep) ? "" : path.sep}`);
|
|
1873
|
+
}
|
|
1874
|
+
|
|
1875
|
+
return new Promise(resolve => {
|
|
1876
|
+
execFile(command, args, { timeout: 60000, windowsHide: true, maxBuffer: 1024 * 1024 }, (err, stdout) => {
|
|
1877
|
+
if (err) {
|
|
1878
|
+
if (err.code === "ENOENT") {
|
|
1879
|
+
return resolve({ ok: false, unsupported: true, message: "当前系统没有可用的文件夹选择器" });
|
|
1880
|
+
}
|
|
1881
|
+
if (err.killed || err.signal === "SIGTERM") {
|
|
1882
|
+
return resolve({ ok: false, canceled: true, message: "选择文件夹超时" });
|
|
1883
|
+
}
|
|
1884
|
+
// macOS / Linux 取消时以非 0 退出,按取消处理
|
|
1885
|
+
if (!String(stdout || "").trim()) {
|
|
1886
|
+
return resolve({ ok: false, canceled: true });
|
|
1887
|
+
}
|
|
1888
|
+
return resolve({ ok: false, canceled: true, message: String(err.message || err) });
|
|
1889
|
+
}
|
|
1890
|
+
|
|
1891
|
+
const picked = String(stdout || "").trim();
|
|
1892
|
+
if (!picked) return resolve({ ok: false, canceled: true });
|
|
1893
|
+
let stat = null;
|
|
1894
|
+
try { stat = fs.statSync(picked); } catch { /* 目录可能刚被删 */ }
|
|
1895
|
+
if (!stat?.isDirectory()) return resolve({ ok: false, message: "选择的文件夹不存在" });
|
|
1896
|
+
resolve({ ok: true, path: path.resolve(picked) });
|
|
1897
|
+
});
|
|
1898
|
+
});
|
|
1899
|
+
}
|
|
1900
|
+
|
|
1901
|
+
export function isProcessAlive(pid) {
|
|
1902
|
+
if (!pid) return false;
|
|
1903
|
+
try {
|
|
1904
|
+
process.kill(pid, 0);
|
|
1905
|
+
return true;
|
|
1906
|
+
} catch (e) {
|
|
1907
|
+
return e?.code === "EPERM";
|
|
1908
|
+
}
|
|
1909
|
+
}
|
|
1910
|
+
|
|
1911
|
+
async function readJsonBody(req) {
|
|
1912
|
+
const chunks = [];
|
|
1913
|
+
for await (const c of req) chunks.push(c);
|
|
1914
|
+
const text = Buffer.concat(chunks).toString("utf8");
|
|
1915
|
+
if (!text.trim()) return {};
|
|
1916
|
+
try { return JSON.parse(text); } catch { return {}; }
|
|
1917
|
+
}
|
|
1918
|
+
|
|
1919
|
+
/** 解析 Cookie 头,取指定键。 */
|
|
1920
|
+
export function parseCookies(header) {
|
|
1921
|
+
const out = {};
|
|
1922
|
+
for (const part of String(header || "").split(";")) {
|
|
1923
|
+
const i = part.indexOf("=");
|
|
1924
|
+
if (i < 0) continue;
|
|
1925
|
+
out[part.slice(0, i).trim()] = decodeURIComponent(part.slice(i + 1).trim());
|
|
1926
|
+
}
|
|
1927
|
+
return out;
|
|
1928
|
+
}
|
|
1929
|
+
|
|
1930
|
+
/** 打开控制台页面。 */
|
|
1931
|
+
export function openConsole(port) {
|
|
1932
|
+
const url = `http://127.0.0.1:${port}/`;
|
|
1933
|
+
const cmd = process.platform === "win32" ? "cmd" : process.platform === "darwin" ? "open" : "xdg-open";
|
|
1934
|
+
const args = process.platform === "win32" ? ["/c", "start", "", url] : [url];
|
|
1935
|
+
try {
|
|
1936
|
+
const child = spawn(cmd, args, { detached: true, stdio: "ignore", windowsHide: true, shell: false });
|
|
1937
|
+
child.unref();
|
|
1938
|
+
} catch { /* 打不开浏览器不影响服务 */ }
|
|
1939
|
+
return url;
|
|
1940
|
+
}
|