v4-native-queue.test.ts 42 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120
  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("compact queue item:sendQueuedNow 走手动 compact path,不作为普通 prompt 重发", async () => {
  653. let finishCompact!: () => void;
  654. const compactGate = new Promise<Record<string, never>>((resolve) => {
  655. finishCompact = () => resolve({});
  656. });
  657. const app = makeApp({ submitPrompt: vi.fn().mockReturnValue(compactGate) });
  658. const record = makeRecord({ app });
  659. const host = makeHost(record, {
  660. getQueueItem: vi.fn().mockReturnValue(
  661. queueItem({
  662. queueItemId: "q-compact",
  663. sourceCommandId: "source-compact",
  664. kind: "compact",
  665. text: "/compact",
  666. attachments: [],
  667. }),
  668. ),
  669. recordPersistentCommandFact: vi.fn().mockResolvedValue(undefined),
  670. });
  671. await new V4CommandExecutor(host).execute(
  672. envelope("sendQueuedNow", { queueItemId: "q-compact" }),
  673. );
  674. expect(app.submitPrompt).toHaveBeenCalledWith(
  675. "/compact",
  676. expect.objectContaining({ inputId: "source-compact" }),
  677. );
  678. expect(app.sendInput).not.toHaveBeenCalled();
  679. expect(app.removeQueueItem).toHaveBeenCalledWith(
  680. "q-compact",
  681. expect.objectContaining({ reason: "promoted", reservationId: "cmd-q1" }),
  682. );
  683. expect(host.legacyMutations).toContain("queue_compact_promoted");
  684. finishCompact();
  685. await new Promise((resolve) => setTimeout(resolve, 0));
  686. });
  687. it("运行中会话:stop(只 abort 不 await)→ 轮询等 finally 释放锁 → 重发", async () => {
  688. const calls: string[] = [];
  689. const app = makeApp({
  690. sendInput: vi.fn().mockImplementation(async (_input, options) => {
  691. calls.push("resend");
  692. options?.onTurnStartedObserved?.({
  693. id: "event-queue-resend-turn-started",
  694. type: SessionEventType.TurnStarted,
  695. payload: { messageId: "msg-event-queue-resend-turn-started" },
  696. });
  697. return {};
  698. }),
  699. });
  700. const controller = new AbortController();
  701. // 模拟后台 turn 的 finally:收到 abort 后延迟 60ms(>1 个轮询间隔)才释放锁。
  702. controller.signal.addEventListener("abort", () => {
  703. calls.push("abort");
  704. setTimeout(() => {
  705. calls.push("release");
  706. record.activeAbortController = undefined;
  707. }, 60);
  708. });
  709. const record = makeRecord({ app, activeAbortController: controller });
  710. await new V4CommandExecutor(makeHost(record)).execute(
  711. envelope("sendQueuedNow", { queueItemId: "q-1" }),
  712. );
  713. // 关键顺序:abort → 锁释放 → 才重发(否则撞 "A prompt is already running")。
  714. expect(calls).toEqual(["abort", "release", "resend"]);
  715. expect(app.sendInput).toHaveBeenCalledWith(
  716. expect.objectContaining({ text: "排队原文" }),
  717. expect.objectContaining({ inputId: "source-command-q1" }),
  718. );
  719. });
  720. it.each([
  721. { stopKind: "stopped", withAttachment: false, autoDrain: false, expected: "user_steer" },
  722. { stopKind: "idle", withAttachment: false, autoDrain: false, expected: undefined },
  723. { stopKind: "stopped", withAttachment: true, autoDrain: false, expected: undefined },
  724. { stopKind: "stopped", withAttachment: false, autoDrain: true, expected: undefined },
  725. ])(
  726. "队列立即发送 human 提示:$stopKind / attachment=$withAttachment / auto=$autoDrain",
  727. async ({ stopKind, withAttachment, autoDrain, expected }) => {
  728. const stopActiveForegroundExecution = vi
  729. .fn()
  730. .mockReturnValue(
  731. stopKind === "stopped"
  732. ? { kind: "stopped", foregroundExecutionId: "foreground-1" }
  733. : { kind: "idle" },
  734. );
  735. const app = makeApp({ runtime: { stopActiveForegroundExecution } });
  736. const item = queueItem(withAttachment ? {} : { attachments: [] });
  737. await new V4CommandExecutor(
  738. makeHost(makeRecord({ app }), { getQueueItem: () => item }),
  739. ).execute(
  740. envelope("sendQueuedNow", { queueItemId: "q-1" }),
  741. undefined,
  742. autoDrain ? { autoDrainPromotion: true } : undefined,
  743. );
  744. expect(app.sendInput).toHaveBeenCalledTimes(1);
  745. const [input, options] = app.sendInput.mock.calls[0]!;
  746. expect(input.text).toBe(item.text);
  747. expect(options.inputPresentation).toBe(expected);
  748. expect(options).toMatchObject({
  749. inputId: item.sourceCommandId,
  750. requireIdle: true,
  751. intent: {
  752. sourceCommandId: item.sourceCommandId,
  753. clientId: item.clientId,
  754. requestedDelivery: "queue",
  755. },
  756. });
  757. expect(stopActiveForegroundExecution).toHaveBeenCalledTimes(autoDrain ? 0 : 1);
  758. expect(app.removeQueueItem).toHaveBeenCalledWith(
  759. "q-1",
  760. expect.objectContaining({ reason: "promoted", reservationId: "cmd-q1" }),
  761. );
  762. },
  763. );
  764. it("M07a:运行中立即发送把内部抢占标记为保留 queue auto-drain", async () => {
  765. const calls: string[] = [];
  766. let record!: V4SessionRecordView;
  767. const stopActiveForegroundExecution = vi.fn().mockImplementation(() => {
  768. calls.push("runtime-stop");
  769. setTimeout(() => {
  770. calls.push("release");
  771. record.activeAbortController = undefined;
  772. }, 20);
  773. return { kind: "stopped", foregroundExecutionId: "foreground-1" };
  774. });
  775. const app = makeApp({
  776. runtime: { stopActiveForegroundExecution },
  777. sendInput: vi.fn().mockImplementation(async (_input, options) => {
  778. calls.push("resend");
  779. options?.onTurnStartedObserved?.({
  780. id: "event-queue-preserve-turn-started",
  781. type: SessionEventType.TurnStarted,
  782. payload: { messageId: "msg-event-queue-preserve-turn-started" },
  783. });
  784. return {};
  785. }),
  786. });
  787. const controller = new AbortController();
  788. record = makeRecord({ app, activeAbortController: controller });
  789. await new V4CommandExecutor(makeHost(record)).execute(
  790. envelope("sendQueuedNow", { queueItemId: "q-1" }),
  791. );
  792. expect(stopActiveForegroundExecution).toHaveBeenCalledWith({
  793. preserveQueueAutoDrainOnCancel: true,
  794. reason: "v4 sendQueuedNow preempts active turn",
  795. });
  796. expect(controller.signal.aborted).toBe(false);
  797. expect(calls).toEqual(["runtime-stop", "release", "resend"]);
  798. });
  799. it("BG42:notification 只占用 Core foreground 时仍先 stop 再提升 queue item", async () => {
  800. const calls: string[] = [];
  801. let activeForegroundExecutionId: string | undefined = "notification-foreground-1";
  802. const stopActiveForegroundExecution = vi.fn().mockImplementation(() => {
  803. calls.push("runtime-stop");
  804. setTimeout(() => {
  805. calls.push("runtime-release");
  806. activeForegroundExecutionId = undefined;
  807. }, 60);
  808. return { kind: "stopped", foregroundExecutionId: "notification-foreground-1" };
  809. });
  810. const app = makeApp({
  811. runtime: {
  812. getActiveForegroundExecutionId: vi.fn(() => activeForegroundExecutionId),
  813. stopActiveForegroundExecution,
  814. },
  815. sendInput: vi.fn().mockImplementation(async (_input, options) => {
  816. // Bug 原因:model-only notification turn 只登记在 Core foreground authority,
  817. // Bootstrap 没有 activeAbortController。真实 input facade 在旧 foreground 未停止时
  818. // 会把同一 queue item 当 steer 接收,因而不会提交 TurnStarted authority。
  819. if (activeForegroundExecutionId !== undefined) {
  820. calls.push("steer-old-notification");
  821. return {};
  822. }
  823. calls.push("resend");
  824. options?.onTurnStartedObserved?.({
  825. id: "event-notification-send-now-turn-started",
  826. type: SessionEventType.TurnStarted,
  827. payload: { messageId: "msg-event-notification-send-now-turn-started" },
  828. });
  829. return {};
  830. }),
  831. });
  832. const record = makeRecord({ app });
  833. await new V4CommandExecutor(makeHost(record)).execute(
  834. envelope("sendQueuedNow", { queueItemId: "q-1" }),
  835. );
  836. expect(record.activeAbortController).toBeUndefined();
  837. expect(stopActiveForegroundExecution).toHaveBeenCalledWith({
  838. preserveQueueAutoDrainOnCancel: true,
  839. reason: "v4 sendQueuedNow preempts active turn",
  840. });
  841. expect(calls).toEqual(["runtime-stop", "runtime-release", "resend"]);
  842. expect(app.removeQueueItem).toHaveBeenCalledWith(
  843. "q-1",
  844. expect.objectContaining({ reason: "promoted", reservationId: "cmd-q1" }),
  845. );
  846. });
  847. it("BG42:Core foreground stop 后未释放时超时,原 queue item 保持可重试", async () => {
  848. vi.useFakeTimers();
  849. const stopActiveForegroundExecution = vi.fn().mockReturnValue({
  850. kind: "stopped",
  851. foregroundExecutionId: "notification-foreground-stuck",
  852. });
  853. const app = makeApp({
  854. runtime: {
  855. getActiveForegroundExecutionId: vi.fn(() => "notification-foreground-stuck"),
  856. stopActiveForegroundExecution,
  857. },
  858. });
  859. const record = makeRecord({ app });
  860. const pending = new V4CommandExecutor(makeHost(record)).execute(
  861. envelope("sendQueuedNow", { queueItemId: "q-1" }),
  862. );
  863. const assertion = expect(pending).rejects.toBeInstanceOf(V4SessionIdleTimeoutError);
  864. await vi.advanceTimersByTimeAsync(5_100);
  865. await assertion;
  866. expect(app.sendInput).not.toHaveBeenCalled();
  867. expect(app.removeQueueItem).not.toHaveBeenCalled();
  868. expect(app.releaseQueueItemReservation).toHaveBeenCalledWith(
  869. "q-1",
  870. "cmd-q1",
  871. expect.any(Object),
  872. );
  873. });
  874. it("BG44:notification A 释放后的 promotion 空窗不得让 notification B 抢入", async () => {
  875. const calls: string[] = [];
  876. let activeForegroundExecutionId: string | undefined = "notification-a";
  877. let foregroundPromotionLeaseId: string | undefined;
  878. let foregroundPromotionInputId: string | undefined;
  879. const acquireForegroundPromotionLease = vi
  880. .fn()
  881. .mockImplementation(({ leaseId, promotedInputId }) => {
  882. if (foregroundPromotionLeaseId && foregroundPromotionLeaseId !== leaseId) {
  883. return { kind: "conflict", leaseId: foregroundPromotionLeaseId };
  884. }
  885. foregroundPromotionLeaseId = leaseId;
  886. foregroundPromotionInputId = promotedInputId;
  887. calls.push("acquire-promotion-lease");
  888. return { kind: "acquired", leaseId };
  889. });
  890. const releaseForegroundPromotionLease = vi.fn().mockImplementation((leaseId) => {
  891. if (foregroundPromotionLeaseId === leaseId) foregroundPromotionLeaseId = undefined;
  892. foregroundPromotionInputId = undefined;
  893. });
  894. const stopActiveForegroundExecution = vi.fn().mockImplementation(() => {
  895. calls.push("stop-notification-a");
  896. activeForegroundExecutionId = undefined;
  897. return { kind: "stopped", foregroundExecutionId: "notification-a" };
  898. });
  899. const sendInput = vi.fn().mockImplementation(async (_input, options) => {
  900. if (options?.inputId === foregroundPromotionInputId) {
  901. foregroundPromotionLeaseId = undefined;
  902. foregroundPromotionInputId = undefined;
  903. }
  904. if (activeForegroundExecutionId !== undefined) {
  905. calls.push("promoted-prompt-rejected");
  906. throw new Error("A runtime foreground command is already active");
  907. }
  908. calls.push("promoted-prompt-started");
  909. options?.onTurnStartedObserved?.({
  910. id: "event-bg44-promoted-turn-started",
  911. type: SessionEventType.TurnStarted,
  912. payload: { messageId: "msg-event-bg44-promoted-turn-started" },
  913. });
  914. return {};
  915. });
  916. const app = makeApp({
  917. runtime: {
  918. acquireForegroundPromotionLease,
  919. getActiveForegroundExecutionId: vi.fn(() => activeForegroundExecutionId),
  920. releaseForegroundPromotionLease,
  921. stopActiveForegroundExecution,
  922. },
  923. markQueueItemPromoting: vi.fn().mockImplementation(async () => {
  924. calls.push("queue-item-promoting");
  925. // 复现 runtime command drain 在 stop/wait 与 startPromptTurn 之间取得调度权。
  926. queueMicrotask(() => {
  927. if (
  928. activeForegroundExecutionId === undefined &&
  929. foregroundPromotionLeaseId === undefined
  930. ) {
  931. activeForegroundExecutionId = "notification-b";
  932. calls.push("notification-b-started");
  933. }
  934. });
  935. return true;
  936. }),
  937. sendInput,
  938. });
  939. await new V4CommandExecutor(makeHost(makeRecord({ app }))).execute(
  940. envelope("sendQueuedNow", { queueItemId: "q-1" }),
  941. );
  942. expect(calls).toEqual([
  943. "acquire-promotion-lease",
  944. "stop-notification-a",
  945. "queue-item-promoting",
  946. "promoted-prompt-started",
  947. ]);
  948. expect(acquireForegroundPromotionLease).toHaveBeenCalledWith({
  949. leaseId: "queue-promotion:cmd-q1",
  950. mode: "after-current",
  951. promotedInputId: "source-command-q1",
  952. });
  953. expect(app.removeQueueItem).toHaveBeenCalledOnce();
  954. });
  955. it("运行中 + active goal:先 pause goal 再 abort(barrier 顺序)+ legacy 广播", async () => {
  956. const calls: string[] = [];
  957. const app = makeApp({
  958. readTarget: vi.fn().mockResolvedValue({ targetID: "g1", status: "active" }),
  959. updateTargetStatus: vi.fn().mockImplementation(async () => {
  960. calls.push("pause");
  961. return { targetID: "g1", status: "paused" };
  962. }),
  963. });
  964. const controller = new AbortController();
  965. controller.signal.addEventListener("abort", () => {
  966. calls.push("abort");
  967. record.activeAbortController = undefined;
  968. });
  969. const record = makeRecord({ app, activeAbortController: controller });
  970. const host = makeHost(record);
  971. await new V4CommandExecutor(host).execute(envelope("sendQueuedNow", { queueItemId: "q-1" }));
  972. expect(calls).toEqual(["pause", "abort"]);
  973. expect(host.legacyMutations).toContain("send_queued_now_goal_paused");
  974. });
  975. it("5s 超时:锁始终不释放 → V4SessionIdleTimeoutError,且不重发", async () => {
  976. vi.useFakeTimers();
  977. const stopActiveForegroundExecution = vi.fn().mockReturnValue({
  978. kind: "stopped",
  979. foregroundExecutionId: "foreground-timeout",
  980. });
  981. const app = makeApp({
  982. runtime: { stopActiveForegroundExecution },
  983. });
  984. const controller = new AbortController();
  985. // 不挂 abort 监听:模拟 turn 卡死,finally 永不释放锁。
  986. const record = makeRecord({ app, activeAbortController: controller });
  987. const pending = new V4CommandExecutor(makeHost(record)).execute(
  988. envelope("sendQueuedNow", { queueItemId: "q-1" }),
  989. );
  990. const assertion = expect(pending).rejects.toBeInstanceOf(V4SessionIdleTimeoutError);
  991. await vi.advanceTimersByTimeAsync(5_100);
  992. await assertion;
  993. expect(app.sendInput).not.toHaveBeenCalled();
  994. expect(app.removeQueueItem).not.toHaveBeenCalled();
  995. expect(app.releaseQueueItemReservation).toHaveBeenCalledWith(
  996. "q-1",
  997. "cmd-q1",
  998. expect.any(Object),
  999. );
  1000. expect(stopActiveForegroundExecution).toHaveBeenCalledWith({
  1001. preserveQueueAutoDrainOnCancel: true,
  1002. reason: "v4 sendQueuedNow preempts active turn",
  1003. });
  1004. });
  1005. it("原文查不到(已 drain/删除或 id 无效):拒绝且绝不盲删", async () => {
  1006. const app = makeApp();
  1007. const record = makeRecord({ app });
  1008. const host = makeHost(record, {
  1009. getQueueItem: vi.fn().mockReturnValue(null),
  1010. });
  1011. await expect(
  1012. new V4CommandExecutor(host).execute(envelope("sendQueuedNow", { queueItemId: "q-missing" })),
  1013. ).rejects.toBeInstanceOf(V4QueueItemTextUnavailableError);
  1014. expect(app.removeQueueItem).not.toHaveBeenCalled();
  1015. expect(app.sendInput).not.toHaveBeenCalled();
  1016. });
  1017. it("host 未接 getQueueItem 能力:同样拒绝(不能退化为 text-only 重发)", async () => {
  1018. const app = makeApp();
  1019. const record = makeRecord({ app });
  1020. const host = makeHost(record, { getQueueItem: undefined });
  1021. await expect(
  1022. new V4CommandExecutor(host).execute(envelope("sendQueuedNow", { queueItemId: "q-1" })),
  1023. ).rejects.toBeInstanceOf(V4QueueItemTextUnavailableError);
  1024. });
  1025. it("同 queue item 已被另一端 reserve:明确拒绝且不 stop/start/remove", async () => {
  1026. const app = makeApp({ reserveQueueItem: vi.fn().mockResolvedValue(false) });
  1027. const controller = new AbortController();
  1028. const record = makeRecord({ app, activeAbortController: controller });
  1029. await expect(
  1030. new V4CommandExecutor(makeHost(record)).execute(
  1031. envelope("sendQueuedNow", { queueItemId: "q-1" }),
  1032. ),
  1033. ).rejects.toBeInstanceOf(V4QueueItemReservedError);
  1034. expect(controller.signal.aborted).toBe(false);
  1035. expect(app.sendInput).not.toHaveBeenCalled();
  1036. expect(app.removeQueueItem).not.toHaveBeenCalled();
  1037. });
  1038. it("start barrier 失败:释放 reservation,原 queue item 不移除", async () => {
  1039. const app = makeApp();
  1040. const record = makeRecord({ app });
  1041. const host = makeHost(record, {
  1042. ensureModelReady: vi.fn().mockRejectedValue(new Error("model unavailable")),
  1043. });
  1044. await expect(
  1045. new V4CommandExecutor(host).execute(envelope("sendQueuedNow", { queueItemId: "q-1" })),
  1046. ).rejects.toThrow("model unavailable");
  1047. expect(app.releaseQueueItemReservation).toHaveBeenCalledWith(
  1048. "q-1",
  1049. "cmd-q1",
  1050. expect.any(Object),
  1051. );
  1052. expect(app.removeQueueItem).not.toHaveBeenCalled();
  1053. });
  1054. });