v4-native-goal-compact.test.ts 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624
  1. // L2:v4 原生 goal/compact 命令组(compact / sendGoalCommand / pauseGoal / resumeGoal)——
  2. // 验证自旧 server-operations compactSession/goalSession 搬运的状态机 barrier 在原生层保真:
  3. // compact 去重幂等、active /goal 入队、重复 set 收敛 replace、goal 续跑的锁生命周期。
  4. import { describe, expect, it, vi } from "vitest";
  5. import type { CommandEnvelope } from "@zcode/shared/zcode-protocol-v4";
  6. import { V4CommandExecutor } from "../src/zcode-protocol-v4/commands/executor.js";
  7. import type {
  8. V4CommandCoreHost,
  9. V4SessionRecordView,
  10. } from "../src/zcode-protocol-v4/commands/types.js";
  11. function makeApp(overrides: Record<string, unknown> = {}) {
  12. return {
  13. sessionId: "s1",
  14. runtime: {
  15. getActiveTurnInfo: vi.fn().mockReturnValue(undefined),
  16. setExecutionState: vi.fn().mockResolvedValue(undefined),
  17. },
  18. getModel: vi.fn().mockReturnValue("primary-provider/default-model"),
  19. getThoughtLevel: vi.fn().mockReturnValue("high"),
  20. getMode: vi.fn().mockReturnValue("auto"),
  21. submitPrompt: vi.fn().mockResolvedValue({}),
  22. steerTurn: vi.fn().mockResolvedValue({ kind: "queued" }),
  23. setQueueAutoDrain: vi.fn().mockResolvedValue(undefined),
  24. readTarget: vi.fn().mockResolvedValue(null),
  25. setTarget: vi.fn().mockImplementation(async (input: { objective: string }) => ({
  26. targetID: "g1",
  27. objective: input.objective,
  28. status: "active",
  29. })),
  30. updateTargetStatus: vi
  31. .fn()
  32. .mockResolvedValue({ targetID: "g1", objective: "旧目标", status: "active" }),
  33. continueActiveTarget: vi.fn().mockResolvedValue(null),
  34. ...overrides,
  35. };
  36. }
  37. function makeRecord(
  38. overrides: Partial<V4SessionRecordView> & { app?: ReturnType<typeof makeApp> } = {},
  39. ): V4SessionRecordView {
  40. return {
  41. app: (overrides.app ?? makeApp()) as unknown as V4SessionRecordView["app"],
  42. workspace: { workspacePath: "/w" },
  43. persistence: "immediate",
  44. ...overrides,
  45. } as V4SessionRecordView;
  46. }
  47. function makeHost(
  48. record: V4SessionRecordView,
  49. overrides: Partial<V4CommandCoreHost> = {},
  50. ): V4CommandCoreHost & {
  51. legacyMutations: string[];
  52. } {
  53. const legacyMutations: string[] = [];
  54. return {
  55. getRecord: (id) => (id === "s1" ? record : undefined),
  56. afterLegacyStateMutation: async (_r, reason) => {
  57. legacyMutations.push(reason);
  58. },
  59. ...overrides,
  60. legacyMutations,
  61. };
  62. }
  63. function envelope(type: string, payload: unknown): CommandEnvelope {
  64. return {
  65. type,
  66. payload,
  67. sessionId: "s1",
  68. commandId: "cmd-1",
  69. baseRevision: 0,
  70. } as unknown as CommandEnvelope;
  71. }
  72. async function settle() {
  73. // 后台 turn 是 void 起跑的微任务链,flush 两轮保证 finally 执行完。
  74. await new Promise((r) => setTimeout(r, 0));
  75. await new Promise((r) => setTimeout(r, 0));
  76. }
  77. describe("v4 原生 compact", () => {
  78. it.each([false, true])("compact 固定提交的 B:busy=%s", async (busy) => {
  79. const modelSelection = { providerId: "provider-b", modelId: "model-b" };
  80. const app = makeApp();
  81. const record = makeRecord({
  82. app,
  83. ...(busy ? { activeAbortController: new AbortController() } : {}),
  84. });
  85. await new V4CommandExecutor(makeHost(record)).execute(envelope("compact", { modelSelection }));
  86. const call = (busy ? app.steerTurn : app.submitPrompt).mock.calls[0];
  87. expect(call?.[0]).toBe("/compact");
  88. expect(call?.[1]).toMatchObject({
  89. intent: { kind: "compact", sourceCommandId: "cmd-1", modelSelection },
  90. });
  91. expect(call?.[1]?.intent).not.toHaveProperty("mode");
  92. expect(call?.[1]?.intent).not.toHaveProperty("planEnabled");
  93. await settle();
  94. });
  95. it("旧 compact 在接收时固定 A,后台起跑前切到 C 不改写请求", async () => {
  96. const app = makeApp();
  97. const record = makeRecord({ app });
  98. const executing = new V4CommandExecutor(makeHost(record)).execute(envelope("compact", {}));
  99. // Selection 在接收时 structuredClone 固定;后台 submitPrompt 之前改模型不能回写进请求。
  100. app.getModel.mockReturnValue("provider-c/model-c");
  101. await executing;
  102. await settle();
  103. expect(app.submitPrompt).toHaveBeenCalledWith(
  104. "/compact",
  105. expect.objectContaining({
  106. intent: expect.objectContaining({
  107. modelSelection: {
  108. providerId: "primary-provider",
  109. modelId: "default-model",
  110. },
  111. }),
  112. }),
  113. );
  114. await settle();
  115. });
  116. it("compact 的 Selection 不在 Worker Registry 时在接纳前拒绝,不进入 Core 建模", async () => {
  117. // Bug 根因:体验套餐到期后 Provider 下架,排队/直接的 /compact 仍按会话常驻选择进入 Core,
  118. // 以 "Provider Registry 中不存在 Provider" 的 TurnError 结束。现在与 sendText 共用同一份准入。
  119. const app = makeApp({ listModels: () => [] });
  120. const record = makeRecord({ app });
  121. await expect(
  122. new V4CommandExecutor(makeHost(record)).execute(
  123. envelope("compact", {
  124. modelSelection: { providerId: "account:bigmodel-start-plan", modelId: "glm-5" },
  125. }),
  126. ),
  127. ).rejects.toMatchObject({ reasonCode: "modelUnavailable" });
  128. expect(app.submitPrompt).not.toHaveBeenCalled();
  129. expect(app.steerTurn).not.toHaveBeenCalled();
  130. expect(record.activeAbortController).toBeUndefined();
  131. });
  132. it("compact 的 Selection 在 Worker Registry 时放行", async () => {
  133. const app = makeApp({
  134. listModels: () => [{ ref: { providerId: "primary-provider", modelId: "default-model" } }],
  135. });
  136. const record = makeRecord({ app });
  137. await new V4CommandExecutor(makeHost(record)).execute(envelope("compact", {}));
  138. await settle();
  139. expect(app.submitPrompt).toHaveBeenCalledWith("/compact", expect.anything());
  140. });
  141. it("正路径:后台 submitPrompt('/compact') + 上锁 + ready 边界释放", async () => {
  142. let finishCompact!: () => void;
  143. const compactGate = new Promise<Record<string, never>>((resolve) => {
  144. finishCompact = () => resolve({});
  145. });
  146. const app = makeApp({ submitPrompt: vi.fn().mockReturnValue(compactGate) });
  147. const record = makeRecord({ app });
  148. const host = makeHost(record);
  149. host.recordPersistentCommandFact = vi.fn().mockResolvedValue(undefined);
  150. await new V4CommandExecutor(host).execute(envelope("compact", {}));
  151. // 提交即返:execute 已回,compact 仍挂起 → Stop 可用的锁必须在。
  152. expect(record.activeAbortController).toBeDefined();
  153. expect(app.submitPrompt).toHaveBeenCalledWith(
  154. "/compact",
  155. expect.objectContaining({ inputId: "cmd-1" }),
  156. );
  157. finishCompact();
  158. await settle();
  159. // ready 边界:compact 结束先释放锁再 legacy 广播。
  160. expect(record.activeAbortController).toBeUndefined();
  161. expect(host.recordPersistentCommandFact).toHaveBeenCalledWith(
  162. "s1",
  163. "timeline",
  164. expect.objectContaining({ commandId: "cmd-1", status: "accepted" }),
  165. { lifecycleStatus: "success" },
  166. );
  167. expect(host.legacyMutations).toEqual(["session_compacted"]);
  168. });
  169. it("释放 active lock 后,state mutation 收尾完成前仍持有 residency lease", async () => {
  170. let finishCompact!: () => void;
  171. let finishMutation!: () => void;
  172. let mutationStarted!: () => void;
  173. const compactGate = new Promise<Record<string, never>>((resolve) => {
  174. finishCompact = () => resolve({});
  175. });
  176. const mutationGate = new Promise<void>((resolve) => {
  177. finishMutation = resolve;
  178. });
  179. const mutationStartedGate = new Promise<void>((resolve) => {
  180. mutationStarted = resolve;
  181. });
  182. const record = makeRecord({
  183. app: makeApp({ submitPrompt: vi.fn().mockReturnValue(compactGate) }),
  184. });
  185. const host = makeHost(record, {
  186. afterLegacyStateMutation: async () => {
  187. mutationStarted();
  188. await mutationGate;
  189. },
  190. });
  191. await new V4CommandExecutor(host).execute(envelope("compact", {}));
  192. expect(record.residencyFinalizationCount).toBe(1);
  193. finishCompact();
  194. await mutationStartedGate;
  195. expect(record.activeAbortController).toBeUndefined();
  196. expect(record.residencyFinalizationCount).toBe(1);
  197. finishMutation();
  198. await settle();
  199. expect(record.residencyFinalizationCount).toBe(0);
  200. });
  201. it("compact 进行中:显式拒绝(不再次提交)", async () => {
  202. const app = makeApp({
  203. runtime: {
  204. getActiveTurnInfo: vi
  205. .fn()
  206. .mockReturnValue({ kind: "compact", queueLength: 0, steerable: false }),
  207. },
  208. });
  209. const controller = new AbortController();
  210. const record = makeRecord({ app, activeAbortController: controller });
  211. const host = makeHost(record);
  212. await expect(
  213. new V4CommandExecutor(host).execute(envelope("compact", {})),
  214. ).rejects.toMatchObject({ reasonCode: "compactOperationLock" });
  215. expect(app.submitPrompt).not.toHaveBeenCalled();
  216. // 显式拒绝不得触碰进行中 compact 的锁。
  217. expect(record.activeAbortController).toBe(controller);
  218. });
  219. it("其他 active turn:/compact 以 typed maintenance intent 入队,不立即提交", async () => {
  220. const app = makeApp({
  221. runtime: {
  222. getActiveTurnInfo: vi
  223. .fn()
  224. .mockReturnValue({ kind: "primaryTurn", queueLength: 0, steerable: true }),
  225. },
  226. });
  227. const record = makeRecord({ app, activeAbortController: new AbortController() });
  228. await new V4CommandExecutor(makeHost(record)).execute(envelope("compact", {}));
  229. expect(app.steerTurn).toHaveBeenCalledWith(
  230. "/compact",
  231. expect.objectContaining({
  232. commandKind: "compact",
  233. delivery: "queue",
  234. inputId: "cmd-1",
  235. intent: expect.objectContaining({
  236. kind: "compact",
  237. text: "/compact",
  238. requestedDelivery: "queue",
  239. }),
  240. }),
  241. );
  242. expect(app.submitPrompt).not.toHaveBeenCalled();
  243. });
  244. it("goal verifier busy routing:即使没有 steerable active turn,也进入 deferred FIFO", async () => {
  245. const modelSelection = { providerId: "provider-b", modelId: "model-b" };
  246. const enqueueDeferredInput = vi.fn().mockResolvedValue({ kind: "queued" });
  247. const app = makeApp({ enqueueDeferredInput });
  248. const record = makeRecord({ app });
  249. await new V4CommandExecutor(
  250. makeHost(record, { getInputRoutingMode: vi.fn().mockReturnValue("enqueue") }),
  251. ).execute(envelope("compact", { modelSelection }));
  252. expect(enqueueDeferredInput).toHaveBeenCalledWith(
  253. "/compact",
  254. expect.objectContaining({
  255. commandKind: "compact",
  256. delivery: "queue",
  257. intent: expect.objectContaining({ modelSelection }),
  258. }),
  259. );
  260. expect(app.submitPrompt).not.toHaveBeenCalled();
  261. });
  262. it("已有 queued compact:compactOperationLock 拒绝,避免 FIFO 内重复维护意图", async () => {
  263. const app = makeApp();
  264. const record = makeRecord({ app });
  265. await expect(
  266. new V4CommandExecutor(
  267. makeHost(record, { hasQueueItemKind: vi.fn().mockReturnValue(true) }),
  268. ).execute(envelope("compact", {})),
  269. ).rejects.toMatchObject({ reasonCode: "compactOperationLock" });
  270. expect(app.steerTurn).not.toHaveBeenCalled();
  271. expect(app.submitPrompt).not.toHaveBeenCalled();
  272. });
  273. it("后台 compact 登记 runtime active turn 前重复提交:同步 operation lock 仍拒绝", async () => {
  274. let finishCompact!: () => void;
  275. const compactGate = new Promise<Record<string, never>>((resolve) => {
  276. finishCompact = () => resolve({});
  277. });
  278. const app = makeApp({ submitPrompt: vi.fn().mockReturnValue(compactGate) });
  279. const record = makeRecord({ app });
  280. const host = makeHost(record);
  281. await new V4CommandExecutor(host).execute(envelope("compact", {}));
  282. await expect(
  283. new V4CommandExecutor(host).execute({
  284. ...envelope("compact", {}),
  285. commandId: "cmd-2",
  286. }),
  287. ).rejects.toMatchObject({ reasonCode: "compactOperationLock" });
  288. finishCompact();
  289. await settle();
  290. });
  291. it("compact 失败:finally 仍释放锁,reason=session_compact_failed", async () => {
  292. const app = makeApp({
  293. submitPrompt: vi.fn().mockRejectedValue(new Error("boom")),
  294. });
  295. const record = makeRecord({ app });
  296. const host = makeHost(record);
  297. await new V4CommandExecutor(host).execute(envelope("compact", {}));
  298. await settle();
  299. expect(record.activeAbortController).toBeUndefined();
  300. expect(host.legacyMutations).toEqual(["session_compact_failed"]);
  301. });
  302. it("queued compact 失败且后方仍有输入:关闭 autoDrain,保持 FIFO failure barrier", async () => {
  303. const app = makeApp({
  304. submitPrompt: vi.fn().mockRejectedValue(new Error("boom")),
  305. });
  306. const record = makeRecord({ app });
  307. const host = makeHost(record, { getQueueLength: vi.fn().mockReturnValue(1) });
  308. await new V4CommandExecutor(host).execute(envelope("compact", {}));
  309. await settle();
  310. expect(app.setQueueAutoDrain).toHaveBeenCalledWith(false);
  311. expect(host.legacyMutations).toEqual(["session_compact_failed"]);
  312. });
  313. });
  314. describe("v4 原生 sendGoalCommand", () => {
  315. it("set 正路径:setTarget(active) + 后台续跑 + 锁生命周期", async () => {
  316. let finishContinuation!: () => void;
  317. const continuationGate = new Promise<null>((resolve) => {
  318. finishContinuation = () => resolve(null);
  319. });
  320. const app = makeApp({
  321. continueActiveTarget: vi.fn().mockReturnValue(continuationGate),
  322. });
  323. const record = makeRecord({ app });
  324. const host = makeHost(record);
  325. await new V4CommandExecutor(host).execute(
  326. envelope("sendGoalCommand", {
  327. text: " 完成登录页 ",
  328. displayText: "/TaRgEt replace 完成登录页",
  329. modelSelection: {
  330. providerId: "alternate-provider",
  331. modelId: "goal-model",
  332. options: { reasoningLevel: "max" },
  333. },
  334. mode: "yolo",
  335. }),
  336. );
  337. // objective 落库为 trim 后文本,状态直接 active。
  338. expect(app.setTarget).toHaveBeenCalledWith(
  339. expect.objectContaining({
  340. displayText: "/TaRgEt replace 完成登录页",
  341. objective: "完成登录页",
  342. status: "active",
  343. intent: expect.objectContaining({
  344. sourceCommandId: "cmd-1",
  345. modelSelection: {
  346. providerId: "alternate-provider",
  347. modelId: "goal-model",
  348. options: { reasoningLevel: "max" },
  349. },
  350. mode: "yolo",
  351. }),
  352. }),
  353. );
  354. // 续跑期间持锁(连续 /goal 会被 active turn barrier 拒绝)。
  355. expect(record.activeAbortController).toBeDefined();
  356. expect(host.legacyMutations).toEqual(["goal_set"]);
  357. finishContinuation();
  358. await settle();
  359. expect(app.continueActiveTarget).toHaveBeenCalledWith(
  360. expect.objectContaining({
  361. inputId: "cmd-1",
  362. intent: expect.objectContaining({
  363. modelSelection: {
  364. providerId: "alternate-provider",
  365. modelId: "goal-model",
  366. options: { reasoningLevel: "max" },
  367. },
  368. mode: "yolo",
  369. }),
  370. }),
  371. );
  372. // 续跑结束释放锁(旧实现修过的 bug:占锁会让连续 /goal 误判活跃 turn)。
  373. expect(record.activeAbortController).toBeUndefined();
  374. expect(host.legacyMutations).toEqual(["goal_set", "goal_continuation_completed"]);
  375. });
  376. it("set 的 Selection 不在 Worker Registry 时在写目标前拒绝,不改 target、不续跑", async () => {
  377. // Bug 根因:目标续跑没有模型准入,Provider 下架后 /goal 先写入目标再在 Core 建模失败。
  378. const app = makeApp({ listModels: () => [] });
  379. const record = makeRecord({ app });
  380. await expect(
  381. new V4CommandExecutor(makeHost(record)).execute(
  382. envelope("sendGoalCommand", {
  383. text: "新目标",
  384. modelSelection: { providerId: "account:bigmodel-start-plan", modelId: "glm-5" },
  385. }),
  386. ),
  387. ).rejects.toMatchObject({ reasonCode: "modelUnavailable" });
  388. expect(app.setTarget).not.toHaveBeenCalled();
  389. expect(app.continueActiveTarget).not.toHaveBeenCalled();
  390. expect(record.activeAbortController).toBeUndefined();
  391. });
  392. it("重复 set:已有 target 收敛 replace 语义(reason=goal_replaced)", async () => {
  393. const app = makeApp({
  394. readTarget: vi
  395. .fn()
  396. .mockResolvedValue({ targetID: "g0", objective: "旧目标", status: "active" }),
  397. });
  398. const record = makeRecord({ app });
  399. const host = makeHost(record);
  400. await new V4CommandExecutor(host).execute(envelope("sendGoalCommand", { text: "新目标" }));
  401. await settle();
  402. // 不要求用户先 clear/replace:直接覆盖写入新目标。
  403. expect(app.setTarget).toHaveBeenCalledWith(
  404. expect.objectContaining({
  405. displayText: "/goal 新目标",
  406. objective: "新目标",
  407. status: "active",
  408. intent: expect.objectContaining({ sourceCommandId: "cmd-1" }),
  409. }),
  410. );
  411. expect(host.legacyMutations[0]).toBe("goal_replaced");
  412. });
  413. it("active turn 存在:入队为 goal command,不立即写 target", async () => {
  414. const app = makeApp();
  415. const record = makeRecord({ app, activeAbortController: new AbortController() });
  416. await new V4CommandExecutor(makeHost(record)).execute(
  417. envelope("sendGoalCommand", {
  418. text: "x",
  419. displayText: "/target x",
  420. modelSelection: { providerId: "queued-provider", modelId: "queued-model" },
  421. mode: "edit",
  422. }),
  423. );
  424. expect(app.steerTurn).toHaveBeenCalledWith(
  425. "/target x",
  426. expect.objectContaining({
  427. commandKind: "sendGoalCommand",
  428. inputId: "cmd-1",
  429. queryId: "cmd-1",
  430. intent: expect.objectContaining({
  431. kind: "sendGoalCommand",
  432. text: "x",
  433. modelSelection: { providerId: "queued-provider", modelId: "queued-model" },
  434. mode: "edit",
  435. }),
  436. }),
  437. );
  438. expect(app.setTarget).not.toHaveBeenCalled();
  439. });
  440. it("goal verifier routing 早于 controller:/goal 仍进入 deferred FIFO", async () => {
  441. const enqueueDeferredInput = vi.fn().mockResolvedValue({ kind: "queued" });
  442. const app = makeApp({
  443. enqueueDeferredInput,
  444. runtime: { getActiveTurnInfo: vi.fn().mockReturnValue(undefined) },
  445. });
  446. const record = makeRecord({ app });
  447. await new V4CommandExecutor(
  448. makeHost(record, { getInputRoutingMode: vi.fn().mockReturnValue("enqueue") }),
  449. ).execute(envelope("sendGoalCommand", { text: "验证后继续目标" }));
  450. expect(enqueueDeferredInput).toHaveBeenCalledWith(
  451. "/goal 验证后继续目标",
  452. expect.objectContaining({ commandKind: "sendGoalCommand", delivery: "queue" }),
  453. );
  454. expect(app.setTarget).not.toHaveBeenCalled();
  455. expect(app.continueActiveTarget).not.toHaveBeenCalled();
  456. });
  457. it("active turn queue 拒绝:显式失败,不伪装成已受理", async () => {
  458. const app = makeApp({
  459. steerTurn: vi.fn().mockResolvedValue({ kind: "rejected", reason: "input_too_large" }),
  460. });
  461. const record = makeRecord({ app, activeAbortController: new AbortController() });
  462. await expect(
  463. new V4CommandExecutor(makeHost(record)).execute(
  464. envelope("sendGoalCommand", { text: "过大的目标" }),
  465. ),
  466. ).rejects.toMatchObject({ reasonCode: "proto.payloadTooLarge" });
  467. expect(app.setTarget).not.toHaveBeenCalled();
  468. });
  469. it("Plan 与 Goal 互斥:拒绝同时开启,不先落库目标", async () => {
  470. const app = makeApp({ getMode: vi.fn().mockReturnValue("plan") });
  471. const record = makeRecord({ app });
  472. const host = makeHost(record);
  473. await expect(
  474. new V4CommandExecutor(host).execute(envelope("sendGoalCommand", { text: "目标" })),
  475. ).rejects.toMatchObject({ reasonCode: "guard.planGoalMutuallyExclusive" });
  476. await settle();
  477. expect(app.setTarget).not.toHaveBeenCalled();
  478. expect(app.continueActiveTarget).not.toHaveBeenCalled();
  479. expect(record.activeAbortController).toBeUndefined();
  480. expect(host.legacyMutations).toEqual([]);
  481. });
  482. });
  483. describe("v4 原生 resumeGoal", () => {
  484. it("Plan 中不能把暂停目标恢复为 active", async () => {
  485. const app = makeApp({
  486. runtime: { getPlanEnabled: () => true },
  487. readTarget: vi.fn().mockResolvedValue({ targetID: "g1", status: "paused" }),
  488. });
  489. await expect(
  490. new V4CommandExecutor(makeHost(makeRecord({ app }))).execute(envelope("resumeGoal", {})),
  491. ).rejects.toMatchObject({ reasonCode: "guard.planGoalMutuallyExclusive" });
  492. expect(app.updateTargetStatus).not.toHaveBeenCalled();
  493. expect(app.continueActiveTarget).not.toHaveBeenCalled();
  494. });
  495. it("会话常驻模型不在 Worker Registry 时拒绝恢复,不改 target 状态", async () => {
  496. const app = makeApp({
  497. listModels: () => [],
  498. runtime: {
  499. getActiveTurnInfo: vi.fn().mockReturnValue(undefined),
  500. getSessionModelSelection: () => ({
  501. providerId: "account:bigmodel-start-plan",
  502. modelId: "glm-5",
  503. }),
  504. },
  505. });
  506. await expect(
  507. new V4CommandExecutor(makeHost(makeRecord({ app }))).execute(envelope("resumeGoal", {})),
  508. ).rejects.toMatchObject({ reasonCode: "modelUnavailable" });
  509. expect(app.updateTargetStatus).not.toHaveBeenCalled();
  510. expect(app.continueActiveTarget).not.toHaveBeenCalled();
  511. });
  512. it("正路径:updateTargetStatus(active) + 后台续跑", async () => {
  513. const app = makeApp();
  514. const record = makeRecord({ app });
  515. const host = makeHost(record);
  516. await new V4CommandExecutor(host).execute(envelope("resumeGoal", {}));
  517. await settle();
  518. expect(app.updateTargetStatus).toHaveBeenCalledWith("active");
  519. expect(app.continueActiveTarget).toHaveBeenCalledWith(
  520. expect.objectContaining({ inputId: "cmd-1" }),
  521. );
  522. expect(record.activeAbortController).toBeUndefined();
  523. expect(host.legacyMutations).toContain("goal_resumed");
  524. expect(host.legacyMutations).toContain("goal_continuation_completed");
  525. });
  526. it("无 target:幂等成功(不抛错、不续跑、不广播)", async () => {
  527. const app = makeApp({ updateTargetStatus: vi.fn().mockResolvedValue(null) });
  528. const record = makeRecord({ app });
  529. const host = makeHost(record);
  530. await expect(
  531. new V4CommandExecutor(host).execute(envelope("resumeGoal", {})),
  532. ).resolves.toBeUndefined();
  533. expect(app.continueActiveTarget).not.toHaveBeenCalled();
  534. expect(host.legacyMutations).toEqual([]);
  535. });
  536. });
  537. describe("v4 原生 pauseGoal", () => {
  538. it("没有 active work 也会独立暂停 target,不触发 stop queue 语义", async () => {
  539. const app = makeApp({
  540. readTarget: vi
  541. .fn()
  542. .mockResolvedValue({ targetID: "g1", objective: "旧目标", status: "active" }),
  543. updateTargetStatus: vi
  544. .fn()
  545. .mockResolvedValue({ targetID: "g1", objective: "旧目标", status: "paused" }),
  546. });
  547. const record = makeRecord({ app });
  548. const host = makeHost(record);
  549. await new V4CommandExecutor(host).execute(envelope("pauseGoal", {}));
  550. expect(app.updateTargetStatus).toHaveBeenCalledWith("paused");
  551. expect(app.setQueueAutoDrain).not.toHaveBeenCalled();
  552. expect(app.continueActiveTarget).not.toHaveBeenCalled();
  553. expect(host.legacyMutations).toEqual(["goal_paused"]);
  554. });
  555. it("先结算 paused target,再终止当前 goal work", async () => {
  556. const controller = new AbortController();
  557. const app = makeApp({
  558. readTarget: vi
  559. .fn()
  560. .mockResolvedValue({ targetID: "g1", objective: "旧目标", status: "active" }),
  561. updateTargetStatus: vi.fn().mockImplementation(async () => {
  562. expect(controller.signal.aborted).toBe(false);
  563. return { targetID: "g1", objective: "旧目标", status: "paused" };
  564. }),
  565. });
  566. const record = makeRecord({ app, activeAbortController: controller });
  567. await new V4CommandExecutor(makeHost(record)).execute(envelope("pauseGoal", {}));
  568. expect(controller.signal.aborted).toBe(true);
  569. });
  570. it("没有 active target 时幂等 noop", async () => {
  571. const app = makeApp();
  572. const host = makeHost(makeRecord({ app }));
  573. await expect(
  574. new V4CommandExecutor(host).execute(envelope("pauseGoal", {})),
  575. ).resolves.toBeUndefined();
  576. expect(app.updateTargetStatus).not.toHaveBeenCalled();
  577. expect(host.legacyMutations).toEqual([]);
  578. });
  579. });
  580. describe("supports 分流(goal/compact 组)", () => {
  581. it("pauseGoal 已原生", () => {
  582. const executor = new V4CommandExecutor(makeHost(makeRecord()));
  583. expect(executor.supports("pauseGoal")).toBe(true);
  584. });
  585. });