v4-native-queue.test.ts 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171
  1. // L2:v4 原生 queue 命令组(deleteQueueItem / editQueueItem / reorderQueueItem /
  2. // setAutoDrain / setFollowupMode / sendQueuedNow)——验证命令直驱 core app 层 API,
  3. // sendQueuedNow 的「reserve → stop barrier → start/promote → remove」编排语义保真。
  4. // fake 风格参照 tests/v4-native-commands.test.ts(fake host/app,不经旧协议代码)。
  5. import { afterEach, describe, expect, it, vi } from "vitest";
  6. import { SessionEventType, type SessionEvent } from "@zcode/contracts";
  7. import type { CommandEnvelope, QueueItem } from "@zcode/shared/zcode-protocol-v4";
  8. import { V4CommandExecutor } from "../src/zcode-protocol-v4/commands/executor.js";
  9. import {
  10. V4QueueItemTextUnavailableError,
  11. V4QueueItemReservedError,
  12. V4QueueItemNotEditableError,
  13. V4SessionIdleTimeoutError,
  14. } from "../src/zcode-protocol-v4/commands/handlers/queue.js";
  15. import { V4CommandNoopError } from "../src/zcode-protocol-v4/index.js";
  16. import { shouldAutoDrainV4QueueHead } from "../src/zcode-protocol-v4/queue-auto-drain.js";
  17. import type {
  18. V4CommandCoreHost,
  19. V4SessionRecordView,
  20. } from "../src/zcode-protocol-v4/commands/types.js";
  21. function makeApp(overrides: Record<string, unknown> = {}) {
  22. const runtimeOverrides = (overrides.runtime ?? {}) as Record<string, unknown>;
  23. const appOverrides = { ...overrides };
  24. delete appOverrides.runtime;
  25. let foregroundPromotionLeaseId: string | undefined;
  26. return {
  27. sessionId: "s1",
  28. sendInput: vi.fn().mockImplementation(async (_input, options) => {
  29. options?.onTurnStartedObserved?.({
  30. id: "event-queue-turn-started",
  31. type: SessionEventType.TurnStarted,
  32. payload: { messageId: "msg-event-queue-turn-started" },
  33. });
  34. return {
  35. completion: Promise.resolve({}),
  36. kind: "started_turn",
  37. turnId: "turn-1",
  38. };
  39. }),
  40. submitPrompt: vi.fn().mockResolvedValue({}),
  41. steerTurn: vi.fn().mockResolvedValue({}),
  42. readTarget: vi.fn().mockResolvedValue(null),
  43. getMode: vi.fn().mockReturnValue("plan"),
  44. setTarget: vi.fn().mockImplementation(async (input: { objective: string }) => ({
  45. targetID: "g1",
  46. objective: input.objective,
  47. status: "active",
  48. })),
  49. continueActiveTarget: vi.fn().mockResolvedValue(null),
  50. updateTargetStatus: vi.fn().mockResolvedValue(null),
  51. reserveQueueItem: vi.fn().mockResolvedValue(true),
  52. markQueueItemPromoting: vi.fn().mockResolvedValue(true),
  53. releaseQueueItemReservation: vi.fn().mockResolvedValue(true),
  54. removeQueueItem: vi.fn().mockResolvedValue(true),
  55. editQueueItem: vi.fn().mockResolvedValue(true),
  56. reorderQueueItem: vi.fn().mockResolvedValue(true),
  57. setQueueAutoDrain: vi.fn().mockResolvedValue(undefined),
  58. setFollowupMode: vi.fn().mockResolvedValue(undefined),
  59. runtime: {
  60. acquireForegroundPromotionLease: vi.fn().mockImplementation(({ leaseId }) => {
  61. if (foregroundPromotionLeaseId && foregroundPromotionLeaseId !== leaseId) {
  62. return { kind: "conflict", leaseId: foregroundPromotionLeaseId };
  63. }
  64. foregroundPromotionLeaseId = leaseId;
  65. return { kind: "acquired", leaseId };
  66. }),
  67. getActiveForegroundExecutionId: vi.fn(() => undefined),
  68. releaseForegroundPromotionLease: vi.fn().mockImplementation((leaseId) => {
  69. if (foregroundPromotionLeaseId !== leaseId) return false;
  70. foregroundPromotionLeaseId = undefined;
  71. return true;
  72. }),
  73. stopActiveForegroundExecution: vi.fn().mockReturnValue({ kind: "idle" }),
  74. ...runtimeOverrides,
  75. },
  76. ...appOverrides,
  77. };
  78. }
  79. /**
  80. * 加速轮的协议原形:Selection 指向隐藏的加速卡内建 Provider(端点/能力来自 Provider Config),
  81. * 只有卡 JWT 与卡 ID 作为本次执行的动态鉴权随 modelExecution 下发。
  82. */
  83. const ORDINARY_MODEL_SELECTION = {
  84. providerId: "builtin:bigmodel-coding-plan",
  85. modelId: "GLM-5.3",
  86. };
  87. const HIGHSPEED_MODEL_SELECTION = {
  88. providerId: "account:bigmodel-highspeed-card",
  89. modelId: "GLM-5.3",
  90. };
  91. const HIGHSPEED_MODEL_EXECUTION = {
  92. selectionScope: "execution" as const,
  93. requestAuth: {
  94. apiKey: "card-1-jwt",
  95. headers: { Authorization: "Bearer card-1-jwt", "X-Highspeed-Card-ID": "card-1" },
  96. },
  97. selectionFallback: {
  98. providerId: "account:bigmodel-highspeed-card",
  99. target: ORDINARY_MODEL_SELECTION,
  100. rules: [
  101. { reason: "highspeed_card_expired" as const, providerErrorCode: "3402" },
  102. { reason: "highspeed_request_failed" as const },
  103. ],
  104. },
  105. };
  106. const HIGHSPEED_QUEUED_EXECUTION = {
  107. modelSelection: HIGHSPEED_MODEL_SELECTION,
  108. modelExecution: HIGHSPEED_MODEL_EXECUTION,
  109. };
  110. function queueItem(overrides: Partial<QueueItem> = {}): QueueItem {
  111. return {
  112. sourceCommandId: "source-command-q1",
  113. queueItemId: "q-1",
  114. clientId: "mobile-client",
  115. kind: "sendText",
  116. text: "排队原文",
  117. modelSelection: {
  118. providerId: "provider-at-submit",
  119. modelId: "model-at-submit",
  120. options: { reasoningLevel: "high" },
  121. },
  122. mode: "plan",
  123. attachments: [{ ref: "/tmp/note.txt", fileName: "note.txt", mime: "text/plain", bytes: 9 }],
  124. delivery: { requested: "queue", admitted: "queue" },
  125. order: { admissionSeq: 7, queuePosition: 0 },
  126. steer: { state: "notRequested" },
  127. dispatch: { state: "queued" },
  128. admittedAt: 1234,
  129. ...overrides,
  130. };
  131. }
  132. function makeRecord(
  133. overrides: Partial<V4SessionRecordView> & { app?: ReturnType<typeof makeApp> } = {},
  134. ): V4SessionRecordView {
  135. return {
  136. app: (overrides.app ?? makeApp()) as unknown as V4SessionRecordView["app"],
  137. workspace: { workspacePath: "/w" },
  138. persistence: "immediate",
  139. ...overrides,
  140. } as V4SessionRecordView;
  141. }
  142. function makeHost(
  143. record: V4SessionRecordView,
  144. hostOverrides: Partial<V4CommandCoreHost> = {},
  145. ): V4CommandCoreHost & { legacyMutations: string[] } {
  146. const legacyMutations: string[] = [];
  147. return {
  148. getRecord: (id) => (id === "s1" ? record : undefined),
  149. afterLegacyStateMutation: async (_r, reason) => {
  150. legacyMutations.push(reason);
  151. },
  152. waitForProjectionEventCommit: async () => {},
  153. // 默认查得到完整权威 intent(sendQueuedNow 正路径);各用例按需覆盖。
  154. getQueueItem: vi.fn().mockReturnValue(queueItem()),
  155. ...hostOverrides,
  156. legacyMutations,
  157. };
  158. }
  159. function envelope(type: string, payload: unknown): CommandEnvelope {
  160. return {
  161. type,
  162. payload,
  163. sessionId: "s1",
  164. commandId: "cmd-q1",
  165. baseRevision: 0,
  166. } as unknown as CommandEnvelope;
  167. }
  168. function deferred<T>() {
  169. let resolve!: (value: T | PromiseLike<T>) => void;
  170. let reject!: (reason?: unknown) => void;
  171. const promise = new Promise<T>((resolvePromise, rejectPromise) => {
  172. resolve = resolvePromise;
  173. reject = rejectPromise;
  174. });
  175. return { promise, reject, resolve };
  176. }
  177. async function flushDetachedWork() {
  178. await Promise.resolve();
  179. await Promise.resolve();
  180. await new Promise((resolve) => setTimeout(resolve, 0));
  181. }
  182. function workspaceHookReviewRequestedEvent(input: {
  183. id: string;
  184. interactionId: string;
  185. }): SessionEvent {
  186. return {
  187. id: input.id,
  188. type: SessionEventType.WorkspaceHookReviewRequested,
  189. payload: {
  190. request: {
  191. kind: "workspaceHookReview",
  192. reviewFlowId: "review-flow-queue",
  193. generation: 1,
  194. interactionId: input.interactionId,
  195. sessionId: "s1",
  196. taskId: "task-queue",
  197. runId: "run-queue",
  198. workspaceIdentity: "/w",
  199. workspaceLabel: "w",
  200. bundleDigest: "a".repeat(64),
  201. createdAt: Date.now(),
  202. deadlineAt: Date.now() + 10 * 60_000,
  203. sourceFiles: [
  204. {
  205. path: "/w/.zcode/config.json",
  206. displayPath: ".zcode/config.json",
  207. editable: true,
  208. },
  209. ],
  210. summary: { eventCount: 1, hookCount: 1, pendingCount: 1 },
  211. items: [
  212. {
  213. reviewItemId: "review-item-queue",
  214. event: "PreToolUse",
  215. matcher: "*",
  216. type: "process",
  217. displayName: "echo hello",
  218. displayCommand: "echo hello",
  219. sourcePath: "/w/.zcode/config.json",
  220. resolvedTimeoutMs: 1_000,
  221. resolvedMaxOutputBytes: 1_024,
  222. executionMode: "foreground",
  223. configuredEnabled: true,
  224. editable: true,
  225. trustState: "pending_trust",
  226. },
  227. ],
  228. warningCode: "workspace_hooks_execute_code",
  229. },
  230. },
  231. } as unknown as SessionEvent;
  232. }
  233. afterEach(() => {
  234. vi.useRealTimers();
  235. });
  236. describe("v4 原生 queue 单项命令", () => {
  237. it("deleteQueueItem:直驱 app.removeQueueItem(queueItemId ≡ pendingInputId)", async () => {
  238. const app = makeApp();
  239. const record = makeRecord({ app });
  240. await new V4CommandExecutor(makeHost(record)).execute(
  241. envelope("deleteQueueItem", { queueItemId: "q-1" }),
  242. );
  243. expect(app.removeQueueItem).toHaveBeenCalledWith("q-1");
  244. });
  245. it("editQueueItem:直驱 app.editQueueItem(保位原地更新)", async () => {
  246. const app = makeApp();
  247. const record = makeRecord({ app });
  248. await new V4CommandExecutor(makeHost(record)).execute(
  249. envelope("editQueueItem", { queueItemId: "q-1", newText: "改后文本" }),
  250. );
  251. expect(app.editQueueItem).toHaveBeenCalledWith("q-1", "改后文本");
  252. });
  253. it("editQueueItem:typed compact 不可编辑,避免 kind 与可见文本分裂", async () => {
  254. const app = makeApp();
  255. const record = makeRecord({ app });
  256. const host = makeHost(record, {
  257. getQueueItem: vi
  258. .fn()
  259. .mockReturnValue(queueItem({ kind: "compact", text: "/compact", attachments: [] })),
  260. });
  261. await expect(
  262. new V4CommandExecutor(host).execute(
  263. envelope("editQueueItem", { queueItemId: "q-1", newText: "伪装文本" }),
  264. ),
  265. ).rejects.toBeInstanceOf(V4QueueItemNotEditableError);
  266. expect(app.editQueueItem).not.toHaveBeenCalled();
  267. });
  268. it("reorderQueueItem:beforeQueueItemId 直传(null=队尾)", async () => {
  269. const app = makeApp();
  270. const record = makeRecord({ app });
  271. const executor = new V4CommandExecutor(makeHost(record));
  272. await executor.execute(
  273. envelope("reorderQueueItem", { queueItemId: "q-2", beforeQueueItemId: "q-1" }),
  274. );
  275. expect(app.reorderQueueItem).toHaveBeenCalledWith("q-2", "q-1");
  276. await executor.execute(
  277. envelope("reorderQueueItem", { queueItemId: "q-2", beforeQueueItemId: null }),
  278. );
  279. expect(app.reorderQueueItem).toHaveBeenLastCalledWith("q-2", null);
  280. });
  281. it("setAutoDrain:直驱 app.setQueueAutoDrain", async () => {
  282. const app = makeApp();
  283. const record = makeRecord({ app });
  284. const host = makeHost(record);
  285. await new V4CommandExecutor(host).execute(envelope("setAutoDrain", { autoDrain: true }));
  286. expect(app.setQueueAutoDrain).toHaveBeenCalledWith(true);
  287. expect(host.legacyMutations).toEqual(["queue_auto_drain_resumed"]);
  288. });
  289. it("setFollowupMode:直驱 app.setFollowupMode", async () => {
  290. const app = makeApp();
  291. const record = makeRecord({ app });
  292. await new V4CommandExecutor(makeHost(record)).execute(
  293. envelope("setFollowupMode", { mode: "guide" }),
  294. );
  295. expect(app.setFollowupMode).toHaveBeenCalledWith("guide");
  296. });
  297. it("delete 未命中抛可判别 noop,避免把已消费旧投影恢复到 composer", async () => {
  298. const app = makeApp({ removeQueueItem: vi.fn().mockResolvedValue(false) });
  299. const record = makeRecord({ app });
  300. const warn = vi.fn();
  301. await expect(
  302. new V4CommandExecutor(makeHost(record, { logger: { warn } })).execute(
  303. envelope("deleteQueueItem", { queueItemId: "q-gone" }),
  304. ),
  305. ).rejects.toMatchObject({
  306. reasonCode: "queue.itemMissing",
  307. } satisfies Partial<V4CommandNoopError>);
  308. expect(warn).toHaveBeenCalled();
  309. });
  310. });
  311. describe("v4 普通 queue 自动消费 goal gate", () => {
  312. it.each(["active", "paused", "budget_limited"] as const)(
  313. "target=%s 时即使 session ready 也不自动消费",
  314. (targetStatus) => {
  315. expect(
  316. shouldAutoDrainV4QueueHead({
  317. autoDrain: true,
  318. dispatchState: "queued",
  319. sessionBusy: false,
  320. targetStatus,
  321. }),
  322. ).toBe(false);
  323. },
  324. );
  325. it.each([null, "complete"] as const)(
  326. "target=%s 时保留既有 ready 自动消费语义",
  327. (targetStatus) => {
  328. expect(
  329. shouldAutoDrainV4QueueHead({
  330. autoDrain: true,
  331. dispatchState: "queued",
  332. sessionBusy: false,
  333. targetStatus,
  334. }),
  335. ).toBe(true);
  336. },
  337. );
  338. });
  339. describe("v4 原生 sendQueuedNow", () => {
  340. it("Highspeed queue 在卡仍有效时于提升边界应用单轮执行材料", async () => {
  341. const app = makeApp();
  342. const record = makeRecord({ app });
  343. const deleteQueuedTurnExecution = vi.fn();
  344. const host = makeHost(record, {
  345. getQueueItem: vi.fn().mockReturnValue(
  346. queueItem({
  347. // 队列持久化普通提交模型;临时 Highspeed Selection 与凭据只在 CLI 内存暂存。
  348. modelSelection: ORDINARY_MODEL_SELECTION,
  349. highspeed: {
  350. schemaVersion: 1,
  351. cardId: "card-1",
  352. taskId: "s1",
  353. provider: "bigmodel",
  354. model: "GLM-5.3",
  355. issuedAt: 1,
  356. expiresAt: Date.now() + 60_000,
  357. },
  358. }),
  359. ),
  360. readQueuedTurnExecution: vi.fn().mockReturnValue(HIGHSPEED_QUEUED_EXECUTION),
  361. deleteQueuedTurnExecution,
  362. });
  363. await new V4CommandExecutor(host).execute(envelope("sendQueuedNow", { queueItemId: "q-1" }));
  364. expect(host.readQueuedTurnExecution).toHaveBeenCalledWith("s1", "source-command-q1");
  365. expect(app.sendInput).toHaveBeenCalledWith(
  366. expect.any(Object),
  367. expect.objectContaining({
  368. intent: expect.objectContaining({
  369. highspeed: expect.objectContaining({ cardId: "card-1" }),
  370. modelSelection: HIGHSPEED_MODEL_SELECTION,
  371. }),
  372. }),
  373. );
  374. const sendOptions = app.sendInput.mock.calls[0]?.[1];
  375. // selectionScope=execution 表达「只作用于本轮」:不再需要提升后回写/恢复会话模型。
  376. expect(sendOptions.modelExecution.selectionScope).toBe("execution");
  377. await expect(
  378. sendOptions.modelExecution.requestDependencies.requestAuth.source.resolve(),
  379. ).resolves.toEqual(HIGHSPEED_MODEL_EXECUTION.requestAuth);
  380. expect(sendOptions.modelExecution.selectionFallback?.target).toEqual(ORDINARY_MODEL_SELECTION);
  381. // 凭据已冻结进本轮,暂存副本立即销毁,避免同一张卡被后续队列项复用。
  382. expect(deleteQueuedTurnExecution).toHaveBeenCalledWith("s1", "source-command-q1");
  383. });
  384. it("手动提升会使用命令补充的同卡执行材料,避免 CLI 暂存状态缺失后误降级", async () => {
  385. const app = makeApp();
  386. const record = makeRecord({ app });
  387. const highspeedMeta = {
  388. schemaVersion: 1 as const,
  389. cardId: "card-1",
  390. taskId: "s1",
  391. provider: "bigmodel",
  392. model: "GLM-5.3",
  393. issuedAt: 1,
  394. expiresAt: Date.now() + 60_000,
  395. };
  396. const refreshedExecution = {
  397. ...HIGHSPEED_MODEL_EXECUTION,
  398. requestAuth: {
  399. apiKey: "card-1-refreshed-jwt",
  400. headers: { Authorization: "Bearer card-1-refreshed-jwt", "X-Highspeed-Card-ID": "card-1" },
  401. },
  402. };
  403. const host = makeHost(record, {
  404. getQueueItem: vi
  405. .fn()
  406. .mockReturnValue(
  407. queueItem({ highspeed: highspeedMeta, modelSelection: ORDINARY_MODEL_SELECTION }),
  408. ),
  409. readQueuedTurnExecution: vi.fn().mockReturnValue(undefined),
  410. });
  411. await new V4CommandExecutor(host).execute(
  412. envelope("sendQueuedNow", {
  413. queueItemId: "q-1",
  414. highspeedMeta,
  415. modelSelection: HIGHSPEED_MODEL_SELECTION,
  416. modelExecution: refreshedExecution,
  417. }),
  418. );
  419. expect(app.sendInput).toHaveBeenCalledWith(
  420. expect.any(Object),
  421. expect.objectContaining({
  422. intent: expect.objectContaining({
  423. highspeed: highspeedMeta,
  424. modelSelection: HIGHSPEED_MODEL_SELECTION,
  425. }),
  426. }),
  427. );
  428. // 补供材料优先于内存暂存:这里 CLI 暂存为空,必须用命令带来的新 JWT 才不会降级。
  429. const sendOptions = app.sendInput.mock.calls[0]?.[1];
  430. await expect(
  431. sendOptions.modelExecution.requestDependencies.requestAuth.source.resolve(),
  432. ).resolves.toEqual(refreshedExecution.requestAuth);
  433. });
  434. it("Highspeed queue 提升时卡已过期则去掉加速标记并使用队列项普通模型", async () => {
  435. const sessionSelection = {
  436. providerId: "builtin:bigmodel-team-coding-plan",
  437. modelId: "GLM-5.3",
  438. };
  439. const app = makeApp({
  440. runtime: { getSessionModelSelection: vi.fn().mockReturnValue(sessionSelection) },
  441. });
  442. const record = makeRecord({ app });
  443. const deleteQueuedTurnExecution = vi.fn();
  444. const host = makeHost(record, {
  445. getQueueItem: vi.fn().mockReturnValue(
  446. queueItem({
  447. modelSelection: ORDINARY_MODEL_SELECTION,
  448. highspeed: {
  449. schemaVersion: 1,
  450. cardId: "expired-card",
  451. taskId: "s1",
  452. provider: "bigmodel",
  453. model: "GLM-5.3",
  454. issuedAt: 1,
  455. expiresAt: Date.now() - 1,
  456. },
  457. }),
  458. ),
  459. readQueuedTurnExecution: vi.fn().mockReturnValue(HIGHSPEED_QUEUED_EXECUTION),
  460. deleteQueuedTurnExecution,
  461. });
  462. await new V4CommandExecutor(host).execute(envelope("sendQueuedNow", { queueItemId: "q-1" }));
  463. const sendOptions = app.sendInput.mock.calls[0]?.[1];
  464. expect(sendOptions?.modelExecution).toBeUndefined();
  465. expect(sendOptions?.intent?.highspeed).toBeUndefined();
  466. // 队列项是发送时快照;降级不得回看之后可能已变化的 Session 模型。
  467. expect(sendOptions?.intent?.modelSelection).toEqual(ORDINARY_MODEL_SELECTION);
  468. expect(sendOptions?.intent?.modelSelection).not.toEqual(sessionSelection);
  469. expect(deleteQueuedTurnExecution).toHaveBeenCalledWith("s1", "source-command-q1");
  470. });
  471. it("旧队列把 Highspeed Provider 持久化且 execution 缺失时迁移回会话普通模型", async () => {
  472. const sessionSelection = {
  473. providerId: "builtin:bigmodel-team-coding-plan",
  474. modelId: "GLM-5.3",
  475. };
  476. const app = makeApp({
  477. runtime: { getSessionModelSelection: vi.fn().mockReturnValue(sessionSelection) },
  478. });
  479. const record = makeRecord({ app });
  480. const host = makeHost(record, {
  481. getQueueItem: vi.fn().mockReturnValue(
  482. queueItem({
  483. modelSelection: HIGHSPEED_MODEL_SELECTION,
  484. highspeed: {
  485. schemaVersion: 1,
  486. cardId: "legacy-card",
  487. taskId: "s1",
  488. provider: "bigmodel",
  489. model: "GLM-5.3",
  490. issuedAt: 1,
  491. expiresAt: Date.now() + 60_000,
  492. },
  493. }),
  494. ),
  495. readQueuedTurnExecution: vi.fn().mockReturnValue(undefined),
  496. });
  497. await new V4CommandExecutor(host).execute(envelope("sendQueuedNow", { queueItemId: "q-1" }));
  498. const sendOptions = app.sendInput.mock.calls[0]?.[1];
  499. expect(sendOptions?.modelExecution).toBeUndefined();
  500. expect(sendOptions?.intent?.highspeed).toBeUndefined();
  501. expect(sendOptions?.intent?.modelSelection).toEqual(sessionSelection);
  502. expect(sendOptions?.intent?.modelSelection).not.toEqual(HIGHSPEED_MODEL_SELECTION);
  503. });
  504. it("promotes quote-only input with its original sender metadata", async () => {
  505. const app = makeApp();
  506. const record = makeRecord({ app });
  507. const host = makeHost(record);
  508. const conversationQuotes = [{ text: "original", senderName: "Ryan Bot", senderId: "app-bot" }];
  509. vi.mocked(host.getQueueItem!).mockReturnValue(
  510. queueItem({ text: "", attachments: [], conversationQuotes }),
  511. );
  512. await new V4CommandExecutor(host).execute(envelope("sendQueuedNow", { queueItemId: "q-1" }));
  513. expect(app.sendInput).toHaveBeenCalledWith(
  514. expect.objectContaining({ text: "" }),
  515. expect.objectContaining({ intent: expect.objectContaining({ conversationQuotes }) }),
  516. );
  517. });
  518. it.each(["plan", "guarded", "yolo"] as const)(
  519. "%s 队列保留 mode/intent/附件:reserve → start → remove",
  520. async (mode) => {
  521. const app = makeApp();
  522. const record = makeRecord({ app });
  523. const host = makeHost(record, { getQueueItem: vi.fn().mockReturnValue(queueItem({ mode })) });
  524. await new V4CommandExecutor(host).execute(envelope("sendQueuedNow", { queueItemId: "q-1" }));
  525. expect(host.getQueueItem).toHaveBeenCalledWith("s1", "q-1");
  526. expect(app.reserveQueueItem).toHaveBeenCalledWith("q-1", "cmd-q1", expect.any(Object));
  527. expect(app.markQueueItemPromoting).toHaveBeenCalledWith("q-1", "cmd-q1", expect.any(Object));
  528. expect(app.sendInput).toHaveBeenCalledWith(
  529. {
  530. text: "排队原文",
  531. attachments: [expect.objectContaining({ path: "/tmp/note.txt", filename: "note.txt" })],
  532. },
  533. expect.objectContaining({
  534. delivery: "start_turn",
  535. inputId: "source-command-q1",
  536. queryId: "source-command-q1",
  537. intent: expect.objectContaining({
  538. sourceCommandId: "source-command-q1",
  539. queueItemId: "q-1",
  540. clientId: "mobile-client",
  541. modelSelection: {
  542. providerId: "provider-at-submit",
  543. modelId: "model-at-submit",
  544. options: { reasoningLevel: "high" },
  545. },
  546. mode,
  547. attachmentRefs: [
  548. { ref: "/tmp/note.txt", fileName: "note.txt", mime: "text/plain", bytes: 9 },
  549. ],
  550. }),
  551. }),
  552. );
  553. expect(app.removeQueueItem).toHaveBeenCalledWith(
  554. "q-1",
  555. expect.objectContaining({ reason: "promoted", reservationId: "cmd-q1" }),
  556. );
  557. expect(app.sendInput.mock.invocationCallOrder[0]).toBeLessThan(
  558. app.removeQueueItem.mock.invocationCallOrder[0],
  559. );
  560. },
  561. );
  562. it("Core admission 后直接 promoted/remove,不等待 turn completion", async () => {
  563. const turnGate = deferred<void>();
  564. const app = makeApp({
  565. sendInput: vi.fn().mockResolvedValue({
  566. completion: turnGate.promise,
  567. kind: "started_turn",
  568. turnId: "turn-q1",
  569. }),
  570. });
  571. const record = makeRecord({ app });
  572. const host = makeHost(record);
  573. await new V4CommandExecutor(host).execute(envelope("sendQueuedNow", { queueItemId: "q-1" }));
  574. // Core admission 完成后就移除队列项,不等待后台 turn 结束。
  575. expect(app.removeQueueItem).toHaveBeenCalledWith(
  576. "q-1",
  577. expect.objectContaining({ reason: "promoted", reservationId: "cmd-q1" }),
  578. );
  579. expect(app.releaseQueueItemReservation).not.toHaveBeenCalled();
  580. turnGate.resolve(undefined);
  581. await flushDetachedWork();
  582. });
  583. it("TurnStarted 缺 messageId 时仍完成 promotion,仅省略 repo 归因", async () => {
  584. const app = makeApp({
  585. sendInput: vi.fn().mockResolvedValue({
  586. completion: Promise.resolve({}),
  587. kind: "started_turn",
  588. turnId: "turn-q1",
  589. }),
  590. });
  591. await expect(
  592. new V4CommandExecutor(makeHost(makeRecord({ app }))).execute(
  593. envelope("sendQueuedNow", { queueItemId: "q-1" }),
  594. ),
  595. ).resolves.toBeUndefined();
  596. expect(app.removeQueueItem).toHaveBeenCalledWith(
  597. "q-1",
  598. expect.objectContaining({ reason: "promoted", reservationId: "cmd-q1" }),
  599. );
  600. expect(app.releaseQueueItemReservation).not.toHaveBeenCalled();
  601. });
  602. it("软门禁:pre-start failure 不误记 promoted,释放 reservation 回到 queued", async () => {
  603. const app = makeApp({
  604. sendInput: vi.fn().mockRejectedValue(new Error("runtime failed before queue TurnStarted")),
  605. });
  606. const record = makeRecord({ app });
  607. const executing = new V4CommandExecutor(makeHost(record)).execute(
  608. envelope("sendQueuedNow", { queueItemId: "q-1" }),
  609. );
  610. void executing.catch(() => undefined);
  611. await flushDetachedWork();
  612. await expect(executing).rejects.toMatchObject({
  613. message: expect.stringContaining("runtime failed"),
  614. });
  615. expect(app.removeQueueItem).not.toHaveBeenCalled();
  616. expect(app.releaseQueueItemReservation).toHaveBeenCalledWith(
  617. "q-1",
  618. "cmd-q1",
  619. expect.any(Object),
  620. );
  621. });
  622. it("goal queue item:sendQueuedNow 走 goal command path,不作为普通 prompt 重发", async () => {
  623. const app = makeApp();
  624. const record = makeRecord({ app });
  625. const host = makeHost(record, {
  626. getQueueItem: vi.fn().mockReturnValue({
  627. ...queueItem(),
  628. queueItemId: "q-goal",
  629. sourceCommandId: "source-goal",
  630. kind: "sendGoalCommand" as const,
  631. text: "/goal 排队目标",
  632. }),
  633. } as never);
  634. await new V4CommandExecutor(host).execute(envelope("sendQueuedNow", { queueItemId: "q-goal" }));
  635. expect(app.removeQueueItem).toHaveBeenCalledWith(
  636. "q-goal",
  637. expect.objectContaining({ reason: "promoted", reservationId: "cmd-q1" }),
  638. );
  639. expect(app.sendInput).not.toHaveBeenCalled();
  640. expect(app.setTarget).toHaveBeenCalledWith(
  641. expect.objectContaining({
  642. displayText: "/goal 排队目标",
  643. objective: "排队目标",
  644. status: "active",
  645. intent: expect.objectContaining({
  646. sourceCommandId: "source-goal",
  647. text: "排队目标",
  648. }),
  649. }),
  650. );
  651. });
  652. it.each([false, true])(
  653. "compact queue item:提升保留原选择,autoDrain=%s",
  654. async (autoDrainPromotion) => {
  655. let finishCompact!: () => void;
  656. const compactGate = new Promise<Record<string, never>>((resolve) => {
  657. finishCompact = () => resolve({});
  658. });
  659. const app = makeApp({ submitPrompt: vi.fn().mockReturnValue(compactGate) });
  660. const record = makeRecord({ app });
  661. const host = makeHost(record, {
  662. getQueueItem: vi.fn().mockReturnValue(
  663. queueItem({
  664. queueItemId: "q-compact",
  665. sourceCommandId: "source-compact",
  666. kind: "compact",
  667. text: "/compact",
  668. attachments: [],
  669. }),
  670. ),
  671. recordPersistentCommandFact: vi.fn().mockResolvedValue(undefined),
  672. });
  673. await new V4CommandExecutor(host).execute(
  674. Object.assign(envelope("sendQueuedNow", { queueItemId: "q-compact" }), {
  675. __v4ExecutionContext: autoDrainPromotion ? { autoDrainPromotion: true } : undefined,
  676. }),
  677. );
  678. expect(app.submitPrompt).toHaveBeenCalledWith(
  679. "/compact",
  680. expect.objectContaining({
  681. inputId: "source-compact",
  682. intent: expect.objectContaining({
  683. sourceCommandId: "source-compact",
  684. queueItemId: "q-compact",
  685. admissionSeq: 7,
  686. modelSelection: queueItem().modelSelection,
  687. }),
  688. }),
  689. );
  690. expect(app.sendInput).not.toHaveBeenCalled();
  691. expect(app.removeQueueItem).toHaveBeenCalledWith(
  692. "q-compact",
  693. expect.objectContaining({ reason: "promoted", reservationId: "cmd-q1" }),
  694. );
  695. expect(host.legacyMutations).toContain("queue_compact_promoted");
  696. finishCompact();
  697. await new Promise((resolve) => setTimeout(resolve, 0));
  698. },
  699. );
  700. it("运行中会话:stop(只 abort 不 await)→ 轮询等 finally 释放锁 → 重发", async () => {
  701. const calls: string[] = [];
  702. const app = makeApp({
  703. sendInput: vi.fn().mockImplementation(async (_input, options) => {
  704. calls.push("resend");
  705. options?.onTurnStartedObserved?.({
  706. id: "event-queue-resend-turn-started",
  707. type: SessionEventType.TurnStarted,
  708. payload: { messageId: "msg-event-queue-resend-turn-started" },
  709. });
  710. return {};
  711. }),
  712. });
  713. const controller = new AbortController();
  714. // 模拟后台 turn 的 finally:收到 abort 后延迟 60ms(>1 个轮询间隔)才释放锁。
  715. controller.signal.addEventListener("abort", () => {
  716. calls.push("abort");
  717. setTimeout(() => {
  718. calls.push("release");
  719. record.activeAbortController = undefined;
  720. }, 60);
  721. });
  722. const record = makeRecord({ app, activeAbortController: controller });
  723. await new V4CommandExecutor(makeHost(record)).execute(
  724. envelope("sendQueuedNow", { queueItemId: "q-1" }),
  725. );
  726. // 关键顺序:abort → 锁释放 → 才重发(否则撞 "A prompt is already running")。
  727. expect(calls).toEqual(["abort", "release", "resend"]);
  728. expect(app.sendInput).toHaveBeenCalledWith(
  729. expect.objectContaining({ text: "排队原文" }),
  730. expect.objectContaining({ inputId: "source-command-q1" }),
  731. );
  732. });
  733. it("automation queue 提升时回放可信身份,并在该 turn 结束后清理", async () => {
  734. const completion = deferred<unknown>();
  735. const app = makeApp({
  736. sendInput: vi.fn().mockImplementation(async (_input, options) => {
  737. options?.onTurnStartedObserved?.({
  738. id: "event-automation-queue-turn-started",
  739. type: SessionEventType.TurnStarted,
  740. payload: { messageId: "msg-automation-queue-turn-started" },
  741. });
  742. return {
  743. completion: completion.promise,
  744. kind: "started_turn",
  745. turnId: "turn-automation-queued",
  746. };
  747. }),
  748. });
  749. const record = makeRecord({ app });
  750. const item = queueItem({ attachments: [], automationId: "automation-queued" });
  751. await new V4CommandExecutor(makeHost(record, { getQueueItem: () => item })).execute(
  752. envelope("sendQueuedNow", { queueItemId: item.queueItemId }),
  753. );
  754. expect(app.sendInput).toHaveBeenCalledWith(
  755. expect.objectContaining({ text: item.text }),
  756. expect.objectContaining({
  757. automationId: "automation-queued",
  758. inputId: item.sourceCommandId,
  759. requireIdle: true,
  760. }),
  761. );
  762. expect(record.activeAutomationId).toBe("automation-queued");
  763. completion.resolve({});
  764. await flushDetachedWork();
  765. expect(record.activeAutomationId).toBeUndefined();
  766. });
  767. // 手动提升实际抢占旧执行时,被点文本同样是普通用户消息,与自动 drain 相同。
  768. it.each([
  769. { stopKind: "stopped", withAttachment: false, autoDrain: false },
  770. { stopKind: "idle", withAttachment: false, autoDrain: false },
  771. { stopKind: "stopped", withAttachment: false, autoDrain: true },
  772. ])(
  773. "队列立即发送仍是普通用户输入:$stopKind / attachment=$withAttachment / auto=$autoDrain",
  774. async ({ stopKind, withAttachment, autoDrain }) => {
  775. const stopActiveForegroundExecution = vi
  776. .fn()
  777. .mockReturnValue(
  778. stopKind === "stopped"
  779. ? { kind: "stopped", foregroundExecutionId: "foreground-1" }
  780. : { kind: "idle" },
  781. );
  782. const app = makeApp({ runtime: { stopActiveForegroundExecution } });
  783. const item = queueItem(withAttachment ? {} : { attachments: [] });
  784. await new V4CommandExecutor(
  785. makeHost(makeRecord({ app }), { getQueueItem: () => item }),
  786. ).execute(
  787. envelope("sendQueuedNow", { queueItemId: "q-1" }),
  788. undefined,
  789. autoDrain ? { autoDrainPromotion: true } : undefined,
  790. );
  791. expect(app.sendInput).toHaveBeenCalledTimes(1);
  792. const [input, options] = app.sendInput.mock.calls[0]!;
  793. expect(input.text).toBe(item.text);
  794. expect(options).not.toHaveProperty("inputPresentation");
  795. expect(options).toMatchObject({
  796. inputId: item.sourceCommandId,
  797. requireIdle: true,
  798. intent: {
  799. sourceCommandId: item.sourceCommandId,
  800. clientId: item.clientId,
  801. requestedDelivery: "queue",
  802. },
  803. });
  804. expect(stopActiveForegroundExecution).toHaveBeenCalledTimes(autoDrain ? 0 : 1);
  805. expect(app.removeQueueItem).toHaveBeenCalledWith(
  806. "q-1",
  807. expect.objectContaining({ reason: "promoted", reservationId: "cmd-q1" }),
  808. );
  809. },
  810. );
  811. it("M07a:运行中立即发送把内部抢占标记为保留 queue auto-drain", async () => {
  812. const calls: string[] = [];
  813. let record!: V4SessionRecordView;
  814. const stopActiveForegroundExecution = vi.fn().mockImplementation(() => {
  815. calls.push("runtime-stop");
  816. setTimeout(() => {
  817. calls.push("release");
  818. record.activeAbortController = undefined;
  819. }, 20);
  820. return { kind: "stopped", foregroundExecutionId: "foreground-1" };
  821. });
  822. const app = makeApp({
  823. runtime: { stopActiveForegroundExecution },
  824. sendInput: vi.fn().mockImplementation(async (_input, options) => {
  825. calls.push("resend");
  826. options?.onTurnStartedObserved?.({
  827. id: "event-queue-preserve-turn-started",
  828. type: SessionEventType.TurnStarted,
  829. payload: { messageId: "msg-event-queue-preserve-turn-started" },
  830. });
  831. return {};
  832. }),
  833. });
  834. const controller = new AbortController();
  835. record = makeRecord({ app, activeAbortController: controller });
  836. await new V4CommandExecutor(makeHost(record)).execute(
  837. envelope("sendQueuedNow", { queueItemId: "q-1" }),
  838. );
  839. expect(stopActiveForegroundExecution).toHaveBeenCalledWith({
  840. preserveQueueAutoDrainOnCancel: true,
  841. reason: "v4 sendQueuedNow preempts active turn",
  842. });
  843. expect(controller.signal.aborted).toBe(false);
  844. expect(calls).toEqual(["runtime-stop", "release", "resend"]);
  845. });
  846. it("BG42:notification 只占用 Core foreground 时仍先 stop 再提升 queue item", async () => {
  847. const calls: string[] = [];
  848. let activeForegroundExecutionId: string | undefined = "notification-foreground-1";
  849. const stopActiveForegroundExecution = vi.fn().mockImplementation(() => {
  850. calls.push("runtime-stop");
  851. setTimeout(() => {
  852. calls.push("runtime-release");
  853. activeForegroundExecutionId = undefined;
  854. }, 60);
  855. return { kind: "stopped", foregroundExecutionId: "notification-foreground-1" };
  856. });
  857. const app = makeApp({
  858. runtime: {
  859. getActiveForegroundExecutionId: vi.fn(() => activeForegroundExecutionId),
  860. stopActiveForegroundExecution,
  861. },
  862. sendInput: vi.fn().mockImplementation(async (_input, options) => {
  863. // Bug 原因:model-only notification turn 只登记在 Core foreground authority,
  864. // Bootstrap 没有 activeAbortController。真实 input facade 在旧 foreground 未停止时
  865. // 会把同一 queue item 当 steer 接收,因而不会提交 TurnStarted authority。
  866. if (activeForegroundExecutionId !== undefined) {
  867. calls.push("steer-old-notification");
  868. return {};
  869. }
  870. calls.push("resend");
  871. options?.onTurnStartedObserved?.({
  872. id: "event-notification-send-now-turn-started",
  873. type: SessionEventType.TurnStarted,
  874. payload: { messageId: "msg-event-notification-send-now-turn-started" },
  875. });
  876. return {};
  877. }),
  878. });
  879. const record = makeRecord({ app });
  880. await new V4CommandExecutor(makeHost(record)).execute(
  881. envelope("sendQueuedNow", { queueItemId: "q-1" }),
  882. );
  883. expect(record.activeAbortController).toBeUndefined();
  884. expect(stopActiveForegroundExecution).toHaveBeenCalledWith({
  885. preserveQueueAutoDrainOnCancel: true,
  886. reason: "v4 sendQueuedNow preempts active turn",
  887. });
  888. expect(calls).toEqual(["runtime-stop", "runtime-release", "resend"]);
  889. expect(app.removeQueueItem).toHaveBeenCalledWith(
  890. "q-1",
  891. expect.objectContaining({ reason: "promoted", reservationId: "cmd-q1" }),
  892. );
  893. });
  894. it("BG42:Core foreground stop 后未释放时超时,原 queue item 保持可重试", async () => {
  895. vi.useFakeTimers();
  896. const stopActiveForegroundExecution = vi.fn().mockReturnValue({
  897. kind: "stopped",
  898. foregroundExecutionId: "notification-foreground-stuck",
  899. });
  900. const app = makeApp({
  901. runtime: {
  902. getActiveForegroundExecutionId: vi.fn(() => "notification-foreground-stuck"),
  903. stopActiveForegroundExecution,
  904. },
  905. });
  906. const record = makeRecord({ app });
  907. const pending = new V4CommandExecutor(makeHost(record)).execute(
  908. envelope("sendQueuedNow", { queueItemId: "q-1" }),
  909. );
  910. const assertion = expect(pending).rejects.toBeInstanceOf(V4SessionIdleTimeoutError);
  911. await vi.advanceTimersByTimeAsync(5_100);
  912. await assertion;
  913. expect(app.sendInput).not.toHaveBeenCalled();
  914. expect(app.removeQueueItem).not.toHaveBeenCalled();
  915. expect(app.releaseQueueItemReservation).toHaveBeenCalledWith(
  916. "q-1",
  917. "cmd-q1",
  918. expect.any(Object),
  919. );
  920. });
  921. it("BG44:notification A 释放后的 promotion 空窗不得让 notification B 抢入", async () => {
  922. const calls: string[] = [];
  923. let activeForegroundExecutionId: string | undefined = "notification-a";
  924. let foregroundPromotionLeaseId: string | undefined;
  925. let foregroundPromotionInputId: string | undefined;
  926. const acquireForegroundPromotionLease = vi
  927. .fn()
  928. .mockImplementation(({ leaseId, promotedInputId }) => {
  929. if (foregroundPromotionLeaseId && foregroundPromotionLeaseId !== leaseId) {
  930. return { kind: "conflict", leaseId: foregroundPromotionLeaseId };
  931. }
  932. foregroundPromotionLeaseId = leaseId;
  933. foregroundPromotionInputId = promotedInputId;
  934. calls.push("acquire-promotion-lease");
  935. return { kind: "acquired", leaseId };
  936. });
  937. const releaseForegroundPromotionLease = vi.fn().mockImplementation((leaseId) => {
  938. if (foregroundPromotionLeaseId === leaseId) foregroundPromotionLeaseId = undefined;
  939. foregroundPromotionInputId = undefined;
  940. });
  941. const stopActiveForegroundExecution = vi.fn().mockImplementation(() => {
  942. calls.push("stop-notification-a");
  943. activeForegroundExecutionId = undefined;
  944. return { kind: "stopped", foregroundExecutionId: "notification-a" };
  945. });
  946. const sendInput = vi.fn().mockImplementation(async (_input, options) => {
  947. if (options?.inputId === foregroundPromotionInputId) {
  948. foregroundPromotionLeaseId = undefined;
  949. foregroundPromotionInputId = undefined;
  950. }
  951. if (activeForegroundExecutionId !== undefined) {
  952. calls.push("promoted-prompt-rejected");
  953. throw new Error("A runtime foreground command is already active");
  954. }
  955. calls.push("promoted-prompt-started");
  956. options?.onTurnStartedObserved?.({
  957. id: "event-bg44-promoted-turn-started",
  958. type: SessionEventType.TurnStarted,
  959. payload: { messageId: "msg-event-bg44-promoted-turn-started" },
  960. });
  961. return {};
  962. });
  963. const app = makeApp({
  964. runtime: {
  965. acquireForegroundPromotionLease,
  966. getActiveForegroundExecutionId: vi.fn(() => activeForegroundExecutionId),
  967. releaseForegroundPromotionLease,
  968. stopActiveForegroundExecution,
  969. },
  970. markQueueItemPromoting: vi.fn().mockImplementation(async () => {
  971. calls.push("queue-item-promoting");
  972. // 复现 runtime command drain 在 stop/wait 与 startPromptTurn 之间取得调度权。
  973. queueMicrotask(() => {
  974. if (
  975. activeForegroundExecutionId === undefined &&
  976. foregroundPromotionLeaseId === undefined
  977. ) {
  978. activeForegroundExecutionId = "notification-b";
  979. calls.push("notification-b-started");
  980. }
  981. });
  982. return true;
  983. }),
  984. sendInput,
  985. });
  986. await new V4CommandExecutor(makeHost(makeRecord({ app }))).execute(
  987. envelope("sendQueuedNow", { queueItemId: "q-1" }),
  988. );
  989. expect(calls).toEqual([
  990. "acquire-promotion-lease",
  991. "stop-notification-a",
  992. "queue-item-promoting",
  993. "promoted-prompt-started",
  994. ]);
  995. expect(acquireForegroundPromotionLease).toHaveBeenCalledWith({
  996. leaseId: "queue-promotion:cmd-q1",
  997. mode: "after-current",
  998. promotedInputId: "source-command-q1",
  999. });
  1000. expect(app.removeQueueItem).toHaveBeenCalledOnce();
  1001. });
  1002. it("运行中 + active goal:先 pause goal 再 abort(barrier 顺序)+ legacy 广播", async () => {
  1003. const calls: string[] = [];
  1004. const app = makeApp({
  1005. readTarget: vi.fn().mockResolvedValue({ targetID: "g1", status: "active" }),
  1006. updateTargetStatus: vi.fn().mockImplementation(async () => {
  1007. calls.push("pause");
  1008. return { targetID: "g1", status: "paused" };
  1009. }),
  1010. });
  1011. const controller = new AbortController();
  1012. controller.signal.addEventListener("abort", () => {
  1013. calls.push("abort");
  1014. record.activeAbortController = undefined;
  1015. });
  1016. const record = makeRecord({ app, activeAbortController: controller });
  1017. const host = makeHost(record);
  1018. await new V4CommandExecutor(host).execute(envelope("sendQueuedNow", { queueItemId: "q-1" }));
  1019. expect(calls).toEqual(["pause", "abort"]);
  1020. expect(host.legacyMutations).toContain("send_queued_now_goal_paused");
  1021. });
  1022. it("5s 超时:锁始终不释放 → V4SessionIdleTimeoutError,且不重发", async () => {
  1023. vi.useFakeTimers();
  1024. const stopActiveForegroundExecution = vi.fn().mockReturnValue({
  1025. kind: "stopped",
  1026. foregroundExecutionId: "foreground-timeout",
  1027. });
  1028. const app = makeApp({
  1029. runtime: { stopActiveForegroundExecution },
  1030. });
  1031. const controller = new AbortController();
  1032. // 不挂 abort 监听:模拟 turn 卡死,finally 永不释放锁。
  1033. const record = makeRecord({ app, activeAbortController: controller });
  1034. const pending = new V4CommandExecutor(makeHost(record)).execute(
  1035. envelope("sendQueuedNow", { queueItemId: "q-1" }),
  1036. );
  1037. const assertion = expect(pending).rejects.toBeInstanceOf(V4SessionIdleTimeoutError);
  1038. await vi.advanceTimersByTimeAsync(5_100);
  1039. await assertion;
  1040. expect(app.sendInput).not.toHaveBeenCalled();
  1041. expect(app.removeQueueItem).not.toHaveBeenCalled();
  1042. expect(app.releaseQueueItemReservation).toHaveBeenCalledWith(
  1043. "q-1",
  1044. "cmd-q1",
  1045. expect.any(Object),
  1046. );
  1047. expect(stopActiveForegroundExecution).toHaveBeenCalledWith({
  1048. preserveQueueAutoDrainOnCancel: true,
  1049. reason: "v4 sendQueuedNow preempts active turn",
  1050. });
  1051. });
  1052. it("原文查不到(已 drain/删除或 id 无效):拒绝且绝不盲删", async () => {
  1053. const app = makeApp();
  1054. const record = makeRecord({ app });
  1055. const host = makeHost(record, {
  1056. getQueueItem: vi.fn().mockReturnValue(null),
  1057. });
  1058. await expect(
  1059. new V4CommandExecutor(host).execute(envelope("sendQueuedNow", { queueItemId: "q-missing" })),
  1060. ).rejects.toBeInstanceOf(V4QueueItemTextUnavailableError);
  1061. expect(app.removeQueueItem).not.toHaveBeenCalled();
  1062. expect(app.sendInput).not.toHaveBeenCalled();
  1063. });
  1064. it("host 未接 getQueueItem 能力:同样拒绝(不能退化为 text-only 重发)", async () => {
  1065. const app = makeApp();
  1066. const record = makeRecord({ app });
  1067. const host = makeHost(record, { getQueueItem: undefined });
  1068. await expect(
  1069. new V4CommandExecutor(host).execute(envelope("sendQueuedNow", { queueItemId: "q-1" })),
  1070. ).rejects.toBeInstanceOf(V4QueueItemTextUnavailableError);
  1071. });
  1072. it("同 queue item 已被另一端 reserve:明确拒绝且不 stop/start/remove", async () => {
  1073. const app = makeApp({ reserveQueueItem: vi.fn().mockResolvedValue(false) });
  1074. const controller = new AbortController();
  1075. const record = makeRecord({ app, activeAbortController: controller });
  1076. await expect(
  1077. new V4CommandExecutor(makeHost(record)).execute(
  1078. envelope("sendQueuedNow", { queueItemId: "q-1" }),
  1079. ),
  1080. ).rejects.toBeInstanceOf(V4QueueItemReservedError);
  1081. expect(controller.signal.aborted).toBe(false);
  1082. expect(app.sendInput).not.toHaveBeenCalled();
  1083. expect(app.removeQueueItem).not.toHaveBeenCalled();
  1084. });
  1085. it("start barrier 失败:释放 reservation,原 queue item 不移除", async () => {
  1086. const app = makeApp();
  1087. const record = makeRecord({ app });
  1088. const host = makeHost(record, {
  1089. ensureModelReady: vi.fn().mockRejectedValue(new Error("model unavailable")),
  1090. });
  1091. await expect(
  1092. new V4CommandExecutor(host).execute(envelope("sendQueuedNow", { queueItemId: "q-1" })),
  1093. ).rejects.toThrow("model unavailable");
  1094. expect(app.releaseQueueItemReservation).toHaveBeenCalledWith(
  1095. "q-1",
  1096. "cmd-q1",
  1097. expect.any(Object),
  1098. );
  1099. expect(app.removeQueueItem).not.toHaveBeenCalled();
  1100. });
  1101. });