v4-native-queue.test.ts 41 KB

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