v4-native-queue.test.ts 53 KB

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