@sleep2agi/commhub-server 0.9.0-preview.280 → 0.9.0-preview.282

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 (50) hide show
  1. package/build-info.json +2 -2
  2. package/package.json +1 -1
  3. package/src/anet-variant-real-daemon-http.test.ts +3 -2
  4. package/src/api-host-supervisors-source-capabilities.test.ts +107 -0
  5. package/src/auth_login_guard.test.ts +15 -0
  6. package/src/auth_login_guard.ts +20 -1
  7. package/src/board-grants.test.ts +134 -0
  8. package/src/broadcast-attribution.test.ts +93 -0
  9. package/src/build-commit-report-http.test.ts +13 -2
  10. package/src/clone-node-adopted-db.test.ts +78 -0
  11. package/src/clone-node.ts +5 -1
  12. package/src/create-node.ts +17 -0
  13. package/src/department-heads.ts +3 -0
  14. package/src/expiry-counters.test.ts +50 -1
  15. package/src/expiry-counters.ts +31 -9
  16. package/src/health-redaction.test.ts +8 -4
  17. package/src/launched-by-cli-report-http.test.ts +155 -0
  18. package/src/mcp-write-network-resolution.test.ts +36 -0
  19. package/src/node-config-last-update.test.ts +103 -1
  20. package/src/node-config-last-update.ts +70 -5
  21. package/src/node-daemon-bindings.ts +9 -0
  22. package/src/node-grants-http.test.ts +239 -0
  23. package/src/node-grants.ts +234 -0
  24. package/src/node-inbox-allowlist-http.test.ts +355 -0
  25. package/src/node-lifecycle-read.ts +1 -1
  26. package/src/node-permissions.ts +168 -2
  27. package/src/opencode-v2-catalog.test.ts +22 -1
  28. package/src/opencode-v2-catalog.ts +36 -3
  29. package/src/peer-allowlist.test.ts +29 -0
  30. package/src/registration-switch-http.test.ts +60 -0
  31. package/src/reply-bare-infer-4315.test.ts +86 -0
  32. package/src/requirements-comment-http.test.ts +1 -1
  33. package/src/requirements-status-participants-http.test.ts +3 -3
  34. package/src/requirements.ts +29 -4
  35. package/src/schedule-agent.ts +45 -10
  36. package/src/scheduled-tasks-http.test.ts +25 -0
  37. package/src/scheduled-tasks.ts +65 -5
  38. package/src/server.ts +186 -11
  39. package/src/session-project-attach-migration.test.ts +2 -1
  40. package/src/session-project-attach-native.test.ts +3 -1
  41. package/src/session-project-create-http.test.ts +3 -2
  42. package/src/session-project-create-native.test.ts +3 -1
  43. package/src/session-source-delivery.ts +5 -0
  44. package/src/session-source-directory-http.test.ts +5 -1
  45. package/src/session-source-evidence.test.ts +11 -4
  46. package/src/session-source-transport.ts +7 -1
  47. package/src/steer-send-message.test.ts +121 -0
  48. package/src/task-access.ts +21 -1
  49. package/src/test-work-root.ts +18 -0
  50. package/src/tools.ts +117 -33
@@ -69,7 +69,7 @@ describe("#3271 从未取走过的过期计数", () => {
69
69
  });
70
70
 
71
71
  // ---- 派单侧硬闸(#3271)----
72
- import { neverConsumeGate, NEVER_CONSUME_LIMIT, NEVER_CONSUME_STALE_MS } from "./expiry-counters.js";
72
+ import { neverConsumeGate, NEVER_CONSUME_LIMIT, NEVER_CONSUME_STALE_MS, parseHubTime } from "./expiry-counters.js";
73
73
 
74
74
  describe("#3271 派单侧硬闸:从未取走过的目标", () => {
75
75
  const NOW = Date.parse("2026-10-31T10:00:00.000Z");
@@ -185,3 +185,52 @@ describe("#3271 硬闸的时效:只数不衰减会把恢复了的节点永久
185
185
  expect(c.by_node["ghost"]).toBe(1);
186
186
  });
187
187
  });
188
+
189
+ describe("2026-11-13 内存计数也以「最后一次回复」为界(恢复了的节点不该等 Hub 重启)", () => {
190
+ const NOW = Date.parse("2026-11-13T12:00:00.000Z");
191
+ const sqlite = (ms: number) => new Date(ms).toISOString().replace("T", " ").slice(0, 19);
192
+ const mem = (n: number, lastAtMs: number) => ({
193
+ since: "2026-11-13T00:00:00.000Z", total: n, by_node: { ghost: n }, last_at: { ghost: new Date(lastAtMs).toISOString() },
194
+ });
195
+
196
+ test("🔴 内存 5 次过期(20 分钟前),之后节点回复过(5 分钟前)⇒ 放行", () => {
197
+ const r = neverConsumeGate({
198
+ alias: "ghost", counters: mem(5, NOW - 20 * 60_000), force: false, forceAllowed: true, now: NOW,
199
+ persistent: { expiries: 0, last_at: null, last_reply_at: sqlite(NOW - 5 * 60_000) },
200
+ });
201
+ expect(r.ok).toBe(true);
202
+ });
203
+
204
+ test("负数用例:回复早于最近一次内存过期 ⇒ 仍然拒(它恢复前那一下不算恢复)", () => {
205
+ const r = neverConsumeGate({
206
+ alias: "ghost", counters: mem(5, NOW - 5 * 60_000), force: false, forceAllowed: true, now: NOW,
207
+ persistent: { expiries: 0, last_at: null, last_reply_at: sqlite(NOW - 20 * 60_000) },
208
+ });
209
+ expect(r.ok).toBe(false);
210
+ });
211
+
212
+ test("负数用例:从来没回复过 ⇒ 内存计数照常生效", () => {
213
+ const r = neverConsumeGate({
214
+ alias: "ghost", counters: mem(5, NOW - 5 * 60_000), force: false, forceAllowed: true, now: NOW,
215
+ persistent: { expiries: 0, last_at: null, last_reply_at: null },
216
+ });
217
+ expect(r.ok).toBe(false);
218
+ });
219
+
220
+ test("回复之后 DB 里又攒了 ≥3 条过期 ⇒ 仍然拒(DB 证据自带边界,不受这条修正影响)", () => {
221
+ const r = neverConsumeGate({
222
+ alias: "ghost", counters: mem(5, NOW - 20 * 60_000), force: false, forceAllowed: true, now: NOW,
223
+ persistent: { expiries: 3, last_at: sqlite(NOW - 60_000), last_reply_at: sqlite(NOW - 5 * 60_000) },
224
+ });
225
+ expect(r.ok).toBe(false);
226
+ });
227
+
228
+ test("parseHubTime:SQLite 时间按 UTC 解析,不随宿主时区漂 8 小时", () => {
229
+ expect(parseHubTime("2026-11-13 12:00:00")).toBe(NOW);
230
+ expect(parseHubTime("2026-11-13T12:00:00")).toBe(NOW);
231
+ expect(parseHubTime("2026-11-13T12:00:00.000Z")).toBe(NOW);
232
+ expect(parseHubTime("2026-11-13T20:00:00+08:00")).toBe(NOW);
233
+ expect(parseHubTime(null)).toBeNull();
234
+ expect(parseHubTime("garbage")).toBeNull();
235
+ });
236
+ });
@@ -182,7 +182,15 @@ export function neverConsumeGate(input: {
182
182
  persistent?: PersistentExpiryEvidence;
183
183
  }): NeverConsumeGate {
184
184
  const limit = input.limit ?? NEVER_CONSUME_LIMIT;
185
- const fromMemory = input.counters.by_node[input.alias] ?? 0;
185
+ // 2026-11-13 —— **内存计数也要以「最后一次回复」为界**(与 DB 证据同一条判据)。
186
+ // 现场:TMA客户端欧 卡住期间攒了 ≥3 次内存过期,之后它恢复并正常回复了,DB 证据随即归零,
187
+ // 但内存桶只有 count + lastAt,没有回复边界 ⇒ 闸继续拒发直到 2 小时 TTL 或 Hub 重启。
188
+ // 有人为此重启了 Hub。回复本身就是「它活着」的证据:最后一次回复晚于内存里最近一次过期
189
+ // ⇒ 那些内存计数全部发生在恢复之前,不再算数。
190
+ const memLastAt = parseHubTime(input.counters.last_at?.[input.alias]);
191
+ const lastReplyAt = parseHubTime(input.persistent?.last_reply_at ?? undefined);
192
+ const memorySupersededByReply = memLastAt !== null && lastReplyAt !== null && lastReplyAt >= memLastAt;
193
+ const fromMemory = memorySupersededByReply ? 0 : (input.counters.by_node[input.alias] ?? 0);
186
194
  const fromDb = input.persistent?.expiries ?? 0;
187
195
  const expiries = Math.max(fromMemory, fromDb);
188
196
  if (expiries < limit) return { ok: true };
@@ -199,19 +207,22 @@ export function neverConsumeGate(input: {
199
207
  message:
200
208
  `this target has ${fromDb} expired task(s) with no reply since its last reply`
201
209
  + `${input.persistent?.last_reply_at ? ` (${input.persistent.last_reply_at})` : " (it has never replied)"}; `
202
- + `nothing will queue correctly here until it replies again — pass force:true (user tokens) if you know it recovered`,
210
+ + `nothing will queue correctly here until it replies again — pass force:true (user tokens) if you know it recovered, `
211
+ + `or as a user token cancel the expired rows (cancel_task accepts expired for user tokens) to clear this gate`,
203
212
  };
204
213
  }
205
214
  // 2026-10-31 —— **只数不衰减会把恢复了的节点永久拉黑**。
206
215
  // 实测的教训来自另一台机(TM中转运维):连「抑制了多少」这个数本身都在被环缓冲淘汰,
207
216
  // 所以任何「累计」都只在它的窗口内可引用;这里把窗口写进判据:最近一次过期超过 TTL ⇒ 放行。
208
- const lastAt = [input.counters.last_at?.[input.alias], input.persistent?.last_at ?? undefined]
209
- .filter((x): x is string => typeof x === "string")
210
- .sort()
211
- .pop();
212
- if (lastAt) {
213
- const age = (input.now ?? Date.now()) - Date.parse(lastAt);
214
- if (Number.isFinite(age) && age > (input.staleAfterMs ?? NEVER_CONSUME_STALE_MS)) return { ok: true };
217
+ // 两个来源的时间格式不同(内存是 ISO,tasks 表是 SQLite 的 "YYYY-MM-DD HH:MM:SS" UTC),
218
+ // 原来按字符串排序再 Date.parse —— 后者会把 SQLite 时间当成**本地时间**解析(Hub 机是 UTC+8)。
219
+ const lastAtMs = [input.counters.last_at?.[input.alias], input.persistent?.last_at ?? undefined]
220
+ .map(parseHubTime)
221
+ .filter((x): x is number => x !== null)
222
+ .reduce<number | null>((a, b) => (a === null || b > a ? b : a), null);
223
+ if (lastAtMs !== null) {
224
+ const age = (input.now ?? Date.now()) - lastAtMs;
225
+ if (age > (input.staleAfterMs ?? NEVER_CONSUME_STALE_MS)) return { ok: true };
215
226
  }
216
227
  if (input.force && input.forceAllowed) return { ok: true };
217
228
  return {
@@ -225,3 +236,14 @@ export function neverConsumeGate(input: {
225
236
  + `nothing will queue correctly here until it consumes again — pass force:true (user tokens) if you know it recovered`,
226
237
  };
227
238
  }
239
+
240
+ /**
241
+ * 解析 Hub 里出现的两种时间:ISO(带 Z / 偏移)和 SQLite `datetime('now')` 的
242
+ * "YYYY-MM-DD HH:MM:SS"(UTC、无时区标记)。后者必须按 UTC 解析,不能交给 Date.parse 当本地时间。
243
+ */
244
+ export function parseHubTime(v: string | null | undefined): number | null {
245
+ if (typeof v !== "string" || !v) return null;
246
+ const sqlite = /^(\d{4}-\d{2}-\d{2})[ T](\d{2}:\d{2}:\d{2}(?:\.\d+)?)$/.exec(v);
247
+ const ms = Date.parse(sqlite ? `${sqlite[1]}T${sqlite[2]}Z` : v);
248
+ return Number.isFinite(ms) ? ms : null;
249
+ }
@@ -1274,10 +1274,14 @@ describe("#473 anonymous /health — watchdog contract intact, no topology leak"
1274
1274
  expect(Number.isInteger(body.alert_baselines.aliases)).toBe(true);
1275
1275
  }
1276
1276
  // clk_tck_assumed_reason:一个必须能解释「为什么用假设值」的字符串(空串是合法的:读到了真实值)
1277
- expect(typeof body.clk_tck_assumed_reason).toBe("string");
1278
- // 它与 clk_tck_source 配对:source=assumed 时必须有理由,否则必须是空串
1279
- if (body.clk_tck_source === "assumed") expect(body.clk_tck_assumed_reason.length).toBeGreaterThan(0);
1280
- else expect(body.clk_tck_assumed_reason).toBe("");
1277
+ // d5869d53 起「读到了真实值」报 null(此前是空串);两者都表示「没有退回 assumed」。
1278
+ // 它与 clk_tck_source 配对:source=assumed 时必须是非空理由,否则必须是 null 或空串。
1279
+ if (body.clk_tck_source === "assumed") {
1280
+ expect(typeof body.clk_tck_assumed_reason).toBe("string");
1281
+ expect(body.clk_tck_assumed_reason.length).toBeGreaterThan(0);
1282
+ } else {
1283
+ expect([null, ""]).toContain(body.clk_tck_assumed_reason);
1284
+ }
1281
1285
  });
1282
1286
 
1283
1287
  test("every /health field is read by at least one test (unread = unverified)", async () => {
@@ -0,0 +1,155 @@
1
+ // 2026-11-10 —— 「起这份 agent-node 的 anet CLI 版本」必须真的走到 `/api/nodes`。
2
+ //
3
+ // 为什么不是「加一列就完了」:Hub 的 report_status schema 对**不认识的键是静默丢弃**的
4
+ // (tools.ts 里那段 #1545 注释写得很清楚)。这条链路必须三处同时成立:
5
+ // ① schema 里有这个键(否则 zod 丢掉)
6
+ // ② 写路径把它落库(JSON.stringify 会连 `undefined` 一起吞掉)
7
+ // ③ 读路径把它投影出来(否则界面上看不见)
8
+ // 少任何一处,现场表现都是「节点明明发了、hub 上什么都没有」—— 本仓库已经吃过两次
9
+ // (#3294 的 build_commit、#2293 的 opencode_catalog)。
10
+ //
11
+ // 所以这里走**真** HTTP:真 node 令牌 + 真 MCP `tools/call report_status` + 真 `GET /api/nodes`,
12
+ // 不做镜像 handler(镜像会与真实 handler 各自漂移)。
13
+ import { afterAll, beforeAll, describe, expect, test } from "bun:test";
14
+ import { mkdtempSync, rmSync } from "node:fs";
15
+ import { tmpdir } from "node:os";
16
+ import { join } from "node:path";
17
+ import { createNetworkTokenForNode, register } from "./auth.js";
18
+ import { db } from "./db.js";
19
+
20
+ const DIR = mkdtempSync(join(tmpdir(), "anet-launched-by-"));
21
+ process.env.COMMHUB_DB ||= join(DIR, "commhub.db");
22
+
23
+ const stamp = `${process.pid}_${Date.now()}`;
24
+ const NET_ALIAS = `launchedby-${stamp}`;
25
+ let hub: any;
26
+ let base = "";
27
+ let adminToken = "";
28
+ let nodeToken = "";
29
+ let networkId = "";
30
+ let nodeId = "";
31
+
32
+ /** CLI 侧真实会上报的版本形态(npm 预发布版)。 */
33
+ const CLI_VERSION = "2.3.0-preview.226";
34
+
35
+ async function send(token: string, method: string, path: string, body?: unknown) {
36
+ const r = await fetch(`${base}${path}`, {
37
+ method,
38
+ headers: { Authorization: `Bearer ${token}`, "Content-Type": "application/json" },
39
+ body: body === undefined ? undefined : JSON.stringify(body),
40
+ });
41
+ const text = await r.text();
42
+ let json: any = null;
43
+ try { json = text ? JSON.parse(text) : null; } catch { /* MCP may answer as SSE */ }
44
+ return { status: r.status, body: json, text };
45
+ }
46
+
47
+ /** 真 MCP `tools/call report_status`,与 agent-node 心跳同一条入参路径。 */
48
+ async function reportStatus(snapshot: Record<string, unknown>) {
49
+ const r = await fetch(`${base}/mcp`, {
50
+ method: "POST",
51
+ headers: {
52
+ Authorization: `Bearer ${nodeToken}`,
53
+ "Content-Type": "application/json",
54
+ Accept: "application/json, text/event-stream",
55
+ },
56
+ body: JSON.stringify({
57
+ jsonrpc: "2.0", id: 1, method: "tools/call",
58
+ params: {
59
+ name: "report_status",
60
+ arguments: {
61
+ resume_id: `r_launchedby_${stamp}`, alias: NET_ALIAS, status: "idle", node_id: nodeId,
62
+ runtime: "opencode-sdk",
63
+ config_snapshot: { model: "deepseek/deepseek-flash", ...snapshot },
64
+ },
65
+ },
66
+ }),
67
+ });
68
+ await r.text();
69
+ return r.status;
70
+ }
71
+
72
+ async function nodeRow() {
73
+ const r = await send(adminToken, "GET", `/api/nodes?network_id=${networkId}`);
74
+ expect(r.status).toBe(200);
75
+ return ((r.body?.nodes ?? []) as Array<Record<string, unknown>>).find(n => n.node_id === nodeId)!;
76
+ }
77
+
78
+ function storedSnapshot(): Record<string, unknown> {
79
+ const stored = db.get<{ config_snapshot: string }>(
80
+ "SELECT config_snapshot FROM nodes WHERE node_id = ?1", nodeId,
81
+ )!;
82
+ return JSON.parse(stored.config_snapshot);
83
+ }
84
+
85
+ beforeAll(async () => {
86
+ const admin = register(`launchedby_admin_${stamp}`, "LaunchedByAdmin123!", undefined, "LaunchedBy Admin");
87
+ expect(admin.ok).toBe(true);
88
+ adminToken = admin.token!;
89
+ networkId = admin.network_id!;
90
+ const ownerId = admin.user!.user_id;
91
+ nodeId = `n_launchedby_${stamp}`;
92
+ const minted = createNetworkTokenForNode(ownerId, networkId, NET_ALIAS, nodeId);
93
+ expect(minted.ok).toBe(true);
94
+ nodeToken = minted.token!;
95
+ const mod: any = await import("./server.js");
96
+ hub = mod.bootServer({ port: 0, hostname: "127.0.0.1" });
97
+ base = `http://127.0.0.1:${hub.port}`;
98
+ }, 30_000);
99
+
100
+ afterAll(() => {
101
+ try { hub?.stop?.(true); } catch { /* already down */ }
102
+ try { rmSync(DIR, { recursive: true, force: true }); } catch { /* best effort */ }
103
+ });
104
+
105
+ describe("launched_by_cli_version 从真上报走到 GET /api/nodes", () => {
106
+ test("schema 不吞这个键:落库 + /api/nodes 投影都看得见", async () => {
107
+ expect(await reportStatus({ launched_by_cli_version: CLI_VERSION })).toBe(200);
108
+
109
+ // ② 写路径
110
+ expect(storedSnapshot().launched_by_cli_version).toBe(CLI_VERSION);
111
+
112
+ // ③ 读路径
113
+ const row = await nodeRow();
114
+ expect(row.launched_by_cli_version).toBe(CLI_VERSION);
115
+ // 整个快照仍然不外泄(这一格只是快照里的一个标量)。
116
+ expect(row).not.toHaveProperty("config_snapshot");
117
+ });
118
+
119
+ test("没有这一格时投影是 null —— 不是 undefined 缺席,也不回退成占位版本", async () => {
120
+ expect(await reportStatus({})).toBe(200);
121
+ expect(storedSnapshot()).not.toHaveProperty("launched_by_cli_version");
122
+ const row = await nodeRow();
123
+ expect(row.launched_by_cli_version).toBeNull();
124
+ });
125
+
126
+ test("形状不对(超过 64 字符)只丢这一格,整份心跳照收", async () => {
127
+ const tooLong = `1.0.0${"0".repeat(60)}`;
128
+ expect(tooLong.length).toBeGreaterThan(64);
129
+ expect(await reportStatus({ launched_by_cli_version: tooLong })).toBe(200);
130
+ // `.catch(undefined)` ⇒ 落库时被 JSON.stringify 吞掉(不是存一个半截值)
131
+ expect(storedSnapshot()).not.toHaveProperty("launched_by_cli_version");
132
+ expect((await nodeRow()).launched_by_cli_version).toBeNull();
133
+ });
134
+
135
+ test("类型不对(对象/数字)同样只丢这一格", async () => {
136
+ expect(await reportStatus({ launched_by_cli_version: { v: CLI_VERSION } })).toBe(200);
137
+ expect((await nodeRow()).launched_by_cli_version).toBeNull();
138
+ expect(await reportStatus({ launched_by_cli_version: 42 })).toBe(200);
139
+ expect((await nodeRow()).launched_by_cli_version).toBeNull();
140
+ });
141
+ });
142
+
143
+ describe("per-node config 端点:刻意不加这一格(说明理由,不是忘了)", () => {
144
+ // `GET /api/nodes/:id/config` 的白名单只装**可编辑/可门控**的配置项
145
+ // (model / modelVariant / flags / agent / *_config_capable …),
146
+ // 溯源类只读标量(build_commit、opencode_catalog、role)一律不出现在那里。
147
+ // launched_by_cli_version 属于后者 ⇒ 只走 /api/nodes,与邻居保持一致。
148
+ test("该端点仍然只回配置项,不带这一格", async () => {
149
+ expect(await reportStatus({ launched_by_cli_version: CLI_VERSION })).toBe(200);
150
+ const r = await send(adminToken, "GET", `/api/nodes/${nodeId}/config`);
151
+ expect(r.status).toBe(200);
152
+ expect(r.body).not.toHaveProperty("launched_by_cli_version");
153
+ expect(r.body).toHaveProperty("model");
154
+ });
155
+ });
@@ -448,3 +448,39 @@ describe("legacy global-token mode pinned", () => {
448
448
  expect(inboxRow("x517 g5 legacy")?.network_id).toBeNull();
449
449
  });
450
450
  });
451
+
452
+ // ─────────────────────────────────────────────────────────────────────
453
+ // Group 9 — #4307: `expired` 行的清理权限
454
+ // target_never_consumes 的判据是「最后一次回复之后仍 status='expired' 且 result 为空」。
455
+ // 节点令牌不得改写终态(那是别人的历史);但**用户令牌必须能清**,否则那个节点
456
+ // 永远收不到新消息(实测 4 个节点各 14–46 条,只能人工改库)。
457
+ // ─────────────────────────────────────────────────────────────────────
458
+ describe("#4307 cancel_task 对 expired:用户令牌可清、节点令牌不可", () => {
459
+ test("用户令牌:可以取消 expired,且 result 被写上(从而不再被 409 计数)", async () => {
460
+ const { tools } = buildHandlers({ userId: U_SINGLE });
461
+ const t = makeTask(A1, "expired", "x517 g9 expired by user");
462
+ const r = await call(tools["cancel_task"], { task_id: t, reason: "clear backlog" });
463
+ expect(r.ok).toBe(true);
464
+ expect(r.cancelled).toBe(true);
465
+ expect(taskById(t)?.status).toBe("cancelled");
466
+ const row = db.get<{ result: string | null }>("SELECT result FROM tasks WHERE task_id = ?1", t);
467
+ expect(row?.result).toBe("clear backlog");
468
+ });
469
+
470
+ test("节点令牌:expired 仍不可取消(不重写终态历史)", async () => {
471
+ const { tools } = buildHandlers({ netId: NET_A, alias: A1, isNetwork: true });
472
+ const t = makeTask(A1, "expired", "x517 g9 expired by node");
473
+ const r = await call(tools["cancel_task"], { task_id: t });
474
+ expect(r.ok).toBe(false);
475
+ expect(r.cancelled).toBe(false);
476
+ expect(taskById(t)?.status).toBe("expired");
477
+ });
478
+
479
+ test("节点令牌:非终态仍可取消(既有行为不变)", async () => {
480
+ const { tools } = buildHandlers({ netId: NET_A, alias: A1, isNetwork: true });
481
+ const t = makeTask(A1, "delivered", "x517 g9 delivered by node");
482
+ const r = await call(tools["cancel_task"], { task_id: t });
483
+ expect(r.cancelled).toBe(true);
484
+ expect(taskById(t)?.status).toBe("cancelled");
485
+ });
486
+ });
@@ -71,7 +71,8 @@ describe("#3146 上一次配置下发的投影", () => {
71
71
  test("不投影 created_by_token(凭据标识不是界面信息)", () => {
72
72
  const v: any = projectLastConfigUpdate(row() as any);
73
73
  expect(Object.keys(v).sort()).toEqual([
74
- "acked_at", "created_at", "error", "observed_status", "requested_model", "status", "terminal", "update_id",
74
+ "acked_at", "created_at", "error", "observed_status", "requested_model", "requested_variant",
75
+ "resolved_after_queue", "status", "terminal", "update_id",
75
76
  ]);
76
77
  expect(JSON.stringify(v)).not.toContain("created_by_token");
77
78
  });
@@ -124,3 +125,104 @@ describe("#3146 GET /api/nodes/:id/config 的接线", () => {
124
125
  expect(configGetHandler()).not.toContain("created_by_token");
125
126
  });
126
127
  });
128
+
129
+ // ── #4499 ────────────────────────────────────────────────────────────────────
130
+ // 现象(2026-11-10 生产实测,通信欧):档位被拒(busy)→ 节点排队 → 29s 后真的应用上了
131
+ // → 顶层 modelVariant 已变 → 但 last_update 永远停在 rejected/variant_busy,
132
+ // 客户端于是一直显示「被拒绝」,而它其实已经生效。
133
+ //
134
+ // 判据(三条同时成立才算已生效,缺一条都保持 rejected):
135
+ // ① ack 原因是 variant_busy;② patch 里确实要了档位;③ 节点当前回读的档位 == 请求值。
136
+ // 另加 15 分钟时间窗;`applied` 仍然只代表「写入并回读一致」,不用「已排队」冒充。
137
+ describe("#4499 被拒后排队已生效的下发", () => {
138
+ const busyRow = (over: Record<string, unknown> = {}) => ({
139
+ update_id: "cu_busy",
140
+ status: "rejected",
141
+ patch_json: JSON.stringify({ modelVariant: "high" }),
142
+ error: "variant_busy (in_flight=1, turn_age_ms=31421)",
143
+ created_at: "1793519656437",
144
+ acked_at: "1793519656466",
145
+ ...over,
146
+ });
147
+ const now = 1793519656437 + 29_000; // 29 秒后:正是生产里实际应用的时刻
148
+
149
+ test("回读档位 == 请求值 ⇒ 投影成 applied,但保留原始 rejected 与标记", () => {
150
+ const v = projectLastConfigUpdate(busyRow(), { currentVariant: "high", nowMs: now });
151
+ expect(v.status).toBe("applied");
152
+ expect(v.terminal).toBe(true);
153
+ expect(v.error).toBeNull();
154
+ expect(v.resolved_after_queue).toBe(true);
155
+ expect(v.observed_status).toBe("rejected"); // 原始事实不丢
156
+ expect(v.requested_variant).toBe("high");
157
+ });
158
+
159
+ test("回读档位对不上 ⇒ 保持 rejected(不许猜)", () => {
160
+ const v = projectLastConfigUpdate(busyRow(), { currentVariant: "low", nowMs: now });
161
+ expect(v.status).toBe("rejected");
162
+ expect(v.resolved_after_queue).toBe(false);
163
+ expect(v.error).toContain("variant_busy");
164
+ });
165
+
166
+ test("没有回读上下文 ⇒ 保持 rejected(不可能凭 patch 猜)", () => {
167
+ const v = projectLastConfigUpdate(busyRow(), { nowMs: now });
168
+ expect(v.status).toBe("rejected");
169
+ expect(v.resolved_after_queue).toBe(false);
170
+ });
171
+
172
+ test("超过 15 分钟窗口 ⇒ 不假设已生效", () => {
173
+ const late = 1793519656437 + 16 * 60 * 1000;
174
+ const v = projectLastConfigUpdate(busyRow(), { currentVariant: "high", nowMs: late });
175
+ expect(v.status).toBe("rejected");
176
+ expect(v.resolved_after_queue).toBe(false);
177
+ });
178
+
179
+ test("原因不是 variant_busy ⇒ 不参与这个推断(例如 session 没起)", () => {
180
+ const v = projectLastConfigUpdate(
181
+ busyRow({ error: "OpenCode V2 session is not running; model was not changed" }),
182
+ { currentVariant: "high", nowMs: now },
183
+ );
184
+ expect(v.status).toBe("rejected");
185
+ expect(v.resolved_after_queue).toBe(false);
186
+ });
187
+
188
+ test("patch 里没有 modelVariant ⇒ 与档位无关,不推断", () => {
189
+ const v = projectLastConfigUpdate(busyRow({ patch_json: JSON.stringify({ model: "a/b" }) }), {
190
+ currentVariant: "high",
191
+ nowMs: now,
192
+ });
193
+ expect(v.status).toBe("rejected");
194
+ expect(v.resolved_after_queue).toBe(false);
195
+ expect(v.requested_variant).toBeNull();
196
+ });
197
+
198
+ test("要求清空(modelVariant:null / \"default\")⇒ 与回读的 null 相等才算生效", () => {
199
+ for (const patch of [{ modelVariant: null }, { modelVariant: "default" }]) {
200
+ const applied = projectLastConfigUpdate(busyRow({ patch_json: JSON.stringify(patch) }), {
201
+ currentVariant: null,
202
+ nowMs: now,
203
+ });
204
+ expect(applied.status).toBe("applied");
205
+ const notApplied = projectLastConfigUpdate(busyRow({ patch_json: JSON.stringify(patch) }), {
206
+ currentVariant: "high",
207
+ nowMs: now,
208
+ });
209
+ expect(notApplied.status).toBe("rejected");
210
+ }
211
+ });
212
+
213
+ test("真的 applied 行不受影响:resolved_after_queue=false 且 requested_variant 仍然带出", () => {
214
+ const v = projectLastConfigUpdate(busyRow({ status: "applied", error: null }), {
215
+ currentVariant: "high",
216
+ nowMs: now,
217
+ });
218
+ expect(v.status).toBe("applied");
219
+ expect(v.resolved_after_queue).toBe(false);
220
+ expect(v.requested_variant).toBe("high");
221
+ });
222
+
223
+ test("接线:GET /api/nodes/:id/config 把当前档位传给投影", () => {
224
+ const block = configGetHandler();
225
+ expect(block).toContain("currentVariant:");
226
+ expect(block).toContain("modelVariant");
227
+ });
228
+ });
@@ -41,6 +41,15 @@ export interface LastConfigUpdate {
41
41
  terminal: boolean;
42
42
  /** 这次下发要的模型(来自 patch_json.model);patch 里没有就是 null。 */
43
43
  requested_model: string | null;
44
+ /** 这次下发要的思考档位(来自 patch_json.modelVariant);patch 里没有就是 null。 */
45
+ requested_variant: string | null;
46
+ /**
47
+ * #4499 —— 「排队后被应用」是**推断**出来的,不是节点回报的:
48
+ * 原来 ack 是 rejected/variant_busy,之后节点把排队的档位应用上了,回读档位 == 请求值。
49
+ * 这种情况下 status 投影成 applied(因为它确实生效且回读一致),但这里留 true 便于排查;
50
+ * observed_status 仍然保留原始的 rejected。应用窗口外的、或回读对不上的,一律 false。
51
+ */
52
+ resolved_after_queue: boolean;
44
53
  /** 节点自报的失败原因(rejected/timeout 才有;applied 是 null)。 */
45
54
  error: string | null;
46
55
  /** ISO;TEXT 存的是 ms epoch,转不出来就是 null。 */
@@ -76,17 +85,72 @@ function requestedModel(patchJson: string | null): string | null {
76
85
  }
77
86
  }
78
87
 
88
+ /**
89
+ * patch_json 里的思考档位(`modelVariant`)。
90
+ *
91
+ * 三种「没要档位」必须分开,不能都折叠成 null:
92
+ * · patch 里**没有** modelVariant 这个键 ⇒ undefined(这次下发与档位无关)
93
+ * · patch 里是 `null` / `"default"` ⇒ null(**明确要求清空**回默认)
94
+ * · patch 里是字符串 ⇒ 原样
95
+ */
96
+ function requestedVariant(patchJson: string | null): string | null | undefined {
97
+ if (!patchJson) return undefined;
98
+ try {
99
+ const parsed = JSON.parse(patchJson) as { modelVariant?: unknown };
100
+ if (!Object.prototype.hasOwnProperty.call(parsed, "modelVariant")) return undefined;
101
+ const v = (parsed as { modelVariant?: unknown }).modelVariant;
102
+ if (v === null || v === undefined) return null;
103
+ if (typeof v === "string") return v === "default" ? null : v;
104
+ return undefined;
105
+ } catch {
106
+ return undefined;
107
+ }
108
+ }
109
+
110
+ /** #4499 —— 排队应用的时间窗。超过这个窗口就不再假设「它后来生效了」。 */
111
+ export const QUEUED_VARIANT_WINDOW_MS = 15 * 60 * 1000;
112
+
113
+ /** ack 的原因是「档位忙」吗?只认节点自己写的 `variant_busy`(后面可能带细节)。 */
114
+ function isVariantBusy(error: string | null): boolean {
115
+ return typeof error === "string" && /^variant_busy\b/.test(error);
116
+ }
117
+
79
118
  /** 纯函数:一行 → 对外形状。抽出来是为了能单独钉住「闭集外不折叠」那条。 */
80
- export function projectLastConfigUpdate(row: Row): LastConfigUpdate {
119
+ export function projectLastConfigUpdate(
120
+ row: Row,
121
+ ctx: { currentVariant?: string | null; nowMs?: number } = {},
122
+ ): LastConfigUpdate {
81
123
  const observed = typeof row.status === "string" ? row.status : "";
82
124
  const known = (CONFIG_UPDATE_STATUSES as readonly string[]).includes(observed);
125
+ const reqVariant = requestedVariant(row.patch_json);
126
+
127
+ // #4499:rejected/variant_busy 之后,节点把排队的档位应用上了。
128
+ // 判据三条同时成立才算(缺一条都保持 rejected,绝不把「排队中」冒充 applied):
129
+ // ① ack 原因是 variant_busy;② patch 里确实要了档位;③ 节点当前回读的档位 == 请求值。
130
+ // 另外加一条时间窗:太久以前的下发即使值巧合相等也不算(那是另一件事)。
131
+ let resolvedAfterQueue = false;
132
+ if (known && observed === "rejected" && isVariantBusy(row.error) && reqVariant !== undefined) {
133
+ const nowMs = ctx.nowMs ?? Date.now();
134
+ const createdMs = Number(row.created_at);
135
+ const inWindow =
136
+ Number.isFinite(createdMs) && createdMs > 0 &&
137
+ nowMs >= createdMs && nowMs - createdMs <= QUEUED_VARIANT_WINDOW_MS;
138
+ const current = ctx.currentVariant === undefined ? undefined : ctx.currentVariant === "default" ? null : ctx.currentVariant;
139
+ const requested = reqVariant === null ? null : reqVariant;
140
+ if (inWindow && current !== undefined && current === requested) resolvedAfterQueue = true;
141
+ }
142
+
143
+ const effectiveStatus = resolvedAfterQueue ? "applied" : known ? (observed as ConfigUpdateStatus) : "unknown";
144
+
83
145
  return {
84
146
  update_id: row.update_id,
85
- status: known ? (observed as ConfigUpdateStatus) : "unknown",
147
+ status: effectiveStatus,
86
148
  observed_status: observed,
87
- terminal: known ? TERMINAL[observed as ConfigUpdateStatus] : false,
149
+ terminal: resolvedAfterQueue ? true : known ? TERMINAL[observed as ConfigUpdateStatus] : false,
88
150
  requested_model: requestedModel(row.patch_json),
89
- error: typeof row.error === "string" && row.error ? row.error : null,
151
+ requested_variant: reqVariant === undefined ? null : reqVariant,
152
+ resolved_after_queue: resolvedAfterQueue,
153
+ error: resolvedAfterQueue ? null : typeof row.error === "string" && row.error ? row.error : null,
90
154
  created_at: msToIso(row.created_at),
91
155
  acked_at: msToIso(row.acked_at),
92
156
  };
@@ -101,7 +165,8 @@ export const LAST_CONFIG_UPDATE_SQL =
101
165
  export function readLastConfigUpdate(
102
166
  get: (sql: string, ...params: any[]) => Row | null,
103
167
  nodeId: string,
168
+ ctx: { currentVariant?: string | null; nowMs?: number } = {},
104
169
  ): LastConfigUpdate | null {
105
170
  const row = get(LAST_CONFIG_UPDATE_SQL, nodeId);
106
- return row ? projectLastConfigUpdate(row) : null;
171
+ return row ? projectLastConfigUpdate(row, ctx) : null;
107
172
  }
@@ -22,6 +22,15 @@ export function createdDaemon(nodeId: string): string | null {
22
22
  export function activeBinding(nodeId: string): Binding | null {
23
23
  return db.get<Binding>("SELECT * FROM node_daemon_bindings WHERE node_id=?1 AND status='active'", nodeId);
24
24
  }
25
+ /** clone_node source facts for an ADOPTED node (no succeeded create row).
26
+ * Same shape as the create row clone_node reads; flags stay empty (the
27
+ * daemon reads the real config from disk), runtime/model come from the node row. */
28
+ export function adoptedCloneSourceRow(nodeId: string, networkId: string, runtime: string | null, alias: string):
29
+ { daemon_node_id: string; runtime: string; model: string | null; flags_json: string; child_name: string } | undefined {
30
+ const b = db.get<Binding>("SELECT * FROM node_daemon_bindings WHERE node_id=?1 AND network_id=?2 AND status='active'", nodeId, networkId);
31
+ if (!b) return undefined;
32
+ return { daemon_node_id: b.daemon_node_id, runtime: runtime || "", model: null, flags_json: "{}", child_name: alias };
33
+ }
25
34
  export function resolveManagedDaemon(nodeId: string): string | null {
26
35
  return createdDaemon(nodeId) ?? activeBinding(nodeId)?.daemon_node_id ?? null;
27
36
  }