v4-native-queue.test.ts 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449
  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("M06k:直接立即发送同样把内部抢占标记为保留 queue auto-drain", async () => {
  1079. // 前台子代理是否转后台由这个标记决定(core 据此生成输入抢占原因),两个立即发送入口必须一致。
  1080. let record!: V4SessionRecordView;
  1081. const stopActiveForegroundExecution = vi.fn().mockImplementation(() => {
  1082. setTimeout(() => {
  1083. record.activeAbortController = undefined;
  1084. }, 20);
  1085. return { kind: "stopped", foregroundExecutionId: "foreground-1" };
  1086. });
  1087. const app = makeApp({
  1088. runtime: {
  1089. getSessionModelSelection: () => ({ providerId: "provider-test", modelId: "model-test" }),
  1090. stopActiveForegroundExecution,
  1091. },
  1092. sendInput: vi.fn().mockImplementation(async (_input, options) => {
  1093. options?.onTurnStartedObserved?.({
  1094. id: "event-start-now-preserve-turn-started",
  1095. type: SessionEventType.TurnStarted,
  1096. payload: { messageId: "msg-event-start-now-preserve-turn-started" },
  1097. });
  1098. return {};
  1099. }),
  1100. });
  1101. record = makeRecord({ app, activeAbortController: new AbortController() });
  1102. await new V4CommandExecutor(makeHost(record)).execute(
  1103. envelope("sendText", { text: "send this now", requestedDelivery: "startNow" }),
  1104. );
  1105. expect(stopActiveForegroundExecution).toHaveBeenCalledWith({
  1106. preserveQueueAutoDrainOnCancel: true,
  1107. reason: "v4 sendText startNow preempts active turn",
  1108. });
  1109. });
  1110. it("BG42:notification 只占用 Core foreground 时仍先 stop 再提升 queue item", async () => {
  1111. const calls: string[] = [];
  1112. let activeForegroundExecutionId: string | undefined = "notification-foreground-1";
  1113. const stopActiveForegroundExecution = vi.fn().mockImplementation(() => {
  1114. calls.push("runtime-stop");
  1115. setTimeout(() => {
  1116. calls.push("runtime-release");
  1117. activeForegroundExecutionId = undefined;
  1118. }, 60);
  1119. return { kind: "stopped", foregroundExecutionId: "notification-foreground-1" };
  1120. });
  1121. const app = makeApp({
  1122. runtime: {
  1123. getActiveForegroundExecutionId: vi.fn(() => activeForegroundExecutionId),
  1124. stopActiveForegroundExecution,
  1125. },
  1126. sendInput: vi.fn().mockImplementation(async (_input, options) => {
  1127. // Bug 原因:model-only notification turn 只登记在 Core foreground authority,
  1128. // Bootstrap 没有 activeAbortController。真实 input facade 在旧 foreground 未停止时
  1129. // 会把同一 queue item 当 steer 接收,因而不会提交 TurnStarted authority。
  1130. if (activeForegroundExecutionId !== undefined) {
  1131. calls.push("steer-old-notification");
  1132. return {};
  1133. }
  1134. calls.push("resend");
  1135. options?.onTurnStartedObserved?.({
  1136. id: "event-notification-send-now-turn-started",
  1137. type: SessionEventType.TurnStarted,
  1138. payload: { messageId: "msg-event-notification-send-now-turn-started" },
  1139. });
  1140. return {};
  1141. }),
  1142. });
  1143. const record = makeRecord({ app });
  1144. await new V4CommandExecutor(makeHost(record)).execute(
  1145. envelope("sendQueuedNow", { queueItemId: "q-1" }),
  1146. );
  1147. expect(record.activeAbortController).toBeUndefined();
  1148. expect(stopActiveForegroundExecution).toHaveBeenCalledWith({
  1149. preserveQueueAutoDrainOnCancel: true,
  1150. reason: "v4 sendQueuedNow preempts active turn",
  1151. });
  1152. expect(calls).toEqual(["runtime-stop", "runtime-release", "resend"]);
  1153. expect(app.removeQueueItem).toHaveBeenCalledWith(
  1154. "q-1",
  1155. expect.objectContaining({ reason: "promoted", reservationId: "cmd-q1" }),
  1156. );
  1157. });
  1158. it("BG42:Core foreground stop 后未释放时超时,原 queue item 保持可重试", async () => {
  1159. vi.useFakeTimers();
  1160. const stopActiveForegroundExecution = vi.fn().mockReturnValue({
  1161. kind: "stopped",
  1162. foregroundExecutionId: "notification-foreground-stuck",
  1163. });
  1164. const app = makeApp({
  1165. runtime: {
  1166. getActiveForegroundExecutionId: vi.fn(() => "notification-foreground-stuck"),
  1167. stopActiveForegroundExecution,
  1168. },
  1169. });
  1170. const record = makeRecord({ app });
  1171. const pending = new V4CommandExecutor(makeHost(record)).execute(
  1172. envelope("sendQueuedNow", { queueItemId: "q-1" }),
  1173. );
  1174. const assertion = expect(pending).rejects.toBeInstanceOf(V4SessionIdleTimeoutError);
  1175. await vi.advanceTimersByTimeAsync(5_100);
  1176. await assertion;
  1177. expect(app.sendInput).not.toHaveBeenCalled();
  1178. expect(app.removeQueueItem).not.toHaveBeenCalled();
  1179. expect(app.releaseQueueItemReservation).toHaveBeenCalledWith(
  1180. "q-1",
  1181. "cmd-q1",
  1182. expect.any(Object),
  1183. );
  1184. });
  1185. it("BG44:notification A 释放后的 promotion 空窗不得让 notification B 抢入", async () => {
  1186. const calls: string[] = [];
  1187. let activeForegroundExecutionId: string | undefined = "notification-a";
  1188. let foregroundPromotionLeaseId: string | undefined;
  1189. let foregroundPromotionInputId: string | undefined;
  1190. const acquireForegroundPromotionLease = vi
  1191. .fn()
  1192. .mockImplementation(({ leaseId, promotedInputId }) => {
  1193. if (foregroundPromotionLeaseId && foregroundPromotionLeaseId !== leaseId) {
  1194. return { kind: "conflict", leaseId: foregroundPromotionLeaseId };
  1195. }
  1196. foregroundPromotionLeaseId = leaseId;
  1197. foregroundPromotionInputId = promotedInputId;
  1198. calls.push("acquire-promotion-lease");
  1199. return { kind: "acquired", leaseId };
  1200. });
  1201. const releaseForegroundPromotionLease = vi.fn().mockImplementation((leaseId) => {
  1202. if (foregroundPromotionLeaseId === leaseId) foregroundPromotionLeaseId = undefined;
  1203. foregroundPromotionInputId = undefined;
  1204. });
  1205. const stopActiveForegroundExecution = vi.fn().mockImplementation(() => {
  1206. calls.push("stop-notification-a");
  1207. activeForegroundExecutionId = undefined;
  1208. return { kind: "stopped", foregroundExecutionId: "notification-a" };
  1209. });
  1210. const sendInput = vi.fn().mockImplementation(async (_input, options) => {
  1211. if (options?.inputId === foregroundPromotionInputId) {
  1212. foregroundPromotionLeaseId = undefined;
  1213. foregroundPromotionInputId = undefined;
  1214. }
  1215. if (activeForegroundExecutionId !== undefined) {
  1216. calls.push("promoted-prompt-rejected");
  1217. throw new Error("A runtime foreground command is already active");
  1218. }
  1219. calls.push("promoted-prompt-started");
  1220. options?.onTurnStartedObserved?.({
  1221. id: "event-bg44-promoted-turn-started",
  1222. type: SessionEventType.TurnStarted,
  1223. payload: { messageId: "msg-event-bg44-promoted-turn-started" },
  1224. });
  1225. return {};
  1226. });
  1227. const app = makeApp({
  1228. runtime: {
  1229. acquireForegroundPromotionLease,
  1230. getActiveForegroundExecutionId: vi.fn(() => activeForegroundExecutionId),
  1231. releaseForegroundPromotionLease,
  1232. stopActiveForegroundExecution,
  1233. },
  1234. markQueueItemPromoting: vi.fn().mockImplementation(async () => {
  1235. calls.push("queue-item-promoting");
  1236. // 复现 runtime command drain 在 stop/wait 与 startPromptTurn 之间取得调度权。
  1237. queueMicrotask(() => {
  1238. if (
  1239. activeForegroundExecutionId === undefined &&
  1240. foregroundPromotionLeaseId === undefined
  1241. ) {
  1242. activeForegroundExecutionId = "notification-b";
  1243. calls.push("notification-b-started");
  1244. }
  1245. });
  1246. return true;
  1247. }),
  1248. sendInput,
  1249. });
  1250. await new V4CommandExecutor(makeHost(makeRecord({ app }))).execute(
  1251. envelope("sendQueuedNow", { queueItemId: "q-1" }),
  1252. );
  1253. expect(calls).toEqual([
  1254. "acquire-promotion-lease",
  1255. "stop-notification-a",
  1256. "queue-item-promoting",
  1257. "promoted-prompt-started",
  1258. ]);
  1259. expect(acquireForegroundPromotionLease).toHaveBeenCalledWith({
  1260. leaseId: "queue-promotion:cmd-q1",
  1261. mode: "after-current",
  1262. promotedInputId: "source-command-q1",
  1263. });
  1264. expect(app.removeQueueItem).toHaveBeenCalledOnce();
  1265. });
  1266. it("运行中 + active goal:先 pause goal 再 abort(barrier 顺序)+ legacy 广播", async () => {
  1267. const calls: string[] = [];
  1268. const app = makeApp({
  1269. readTarget: vi.fn().mockResolvedValue({ targetID: "g1", status: "active" }),
  1270. updateTargetStatus: vi.fn().mockImplementation(async () => {
  1271. calls.push("pause");
  1272. return { targetID: "g1", status: "paused" };
  1273. }),
  1274. });
  1275. const controller = new AbortController();
  1276. controller.signal.addEventListener("abort", () => {
  1277. calls.push("abort");
  1278. record.activeAbortController = undefined;
  1279. });
  1280. const record = makeRecord({ app, activeAbortController: controller });
  1281. const host = makeHost(record);
  1282. await new V4CommandExecutor(host).execute(envelope("sendQueuedNow", { queueItemId: "q-1" }));
  1283. expect(calls).toEqual(["pause", "abort"]);
  1284. expect(host.legacyMutations).toContain("send_queued_now_goal_paused");
  1285. });
  1286. it("5s 超时:锁始终不释放 → V4SessionIdleTimeoutError,且不重发", async () => {
  1287. vi.useFakeTimers();
  1288. const stopActiveForegroundExecution = vi.fn().mockReturnValue({
  1289. kind: "stopped",
  1290. foregroundExecutionId: "foreground-timeout",
  1291. });
  1292. const app = makeApp({
  1293. runtime: { stopActiveForegroundExecution },
  1294. });
  1295. const controller = new AbortController();
  1296. // 不挂 abort 监听:模拟 turn 卡死,finally 永不释放锁。
  1297. const record = makeRecord({ app, activeAbortController: controller });
  1298. const pending = new V4CommandExecutor(makeHost(record)).execute(
  1299. envelope("sendQueuedNow", { queueItemId: "q-1" }),
  1300. );
  1301. const assertion = expect(pending).rejects.toBeInstanceOf(V4SessionIdleTimeoutError);
  1302. await vi.advanceTimersByTimeAsync(5_100);
  1303. await assertion;
  1304. expect(app.sendInput).not.toHaveBeenCalled();
  1305. expect(app.removeQueueItem).not.toHaveBeenCalled();
  1306. expect(app.releaseQueueItemReservation).toHaveBeenCalledWith(
  1307. "q-1",
  1308. "cmd-q1",
  1309. expect.any(Object),
  1310. );
  1311. expect(stopActiveForegroundExecution).toHaveBeenCalledWith({
  1312. preserveQueueAutoDrainOnCancel: true,
  1313. reason: "v4 sendQueuedNow preempts active turn",
  1314. });
  1315. });
  1316. it("原文查不到(已 drain/删除或 id 无效):拒绝且绝不盲删", async () => {
  1317. const app = makeApp();
  1318. const record = makeRecord({ app });
  1319. const host = makeHost(record, {
  1320. getQueueItem: vi.fn().mockReturnValue(null),
  1321. });
  1322. await expect(
  1323. new V4CommandExecutor(host).execute(envelope("sendQueuedNow", { queueItemId: "q-missing" })),
  1324. ).rejects.toBeInstanceOf(V4QueueItemTextUnavailableError);
  1325. expect(app.removeQueueItem).not.toHaveBeenCalled();
  1326. expect(app.sendInput).not.toHaveBeenCalled();
  1327. });
  1328. it("host 未接 getQueueItem 能力:同样拒绝(不能退化为 text-only 重发)", async () => {
  1329. const app = makeApp();
  1330. const record = makeRecord({ app });
  1331. const host = makeHost(record, { getQueueItem: undefined });
  1332. await expect(
  1333. new V4CommandExecutor(host).execute(envelope("sendQueuedNow", { queueItemId: "q-1" })),
  1334. ).rejects.toBeInstanceOf(V4QueueItemTextUnavailableError);
  1335. });
  1336. it("同 queue item 已被另一端 reserve:明确拒绝且不 stop/start/remove", async () => {
  1337. const app = makeApp({ reserveQueueItem: vi.fn().mockResolvedValue(false) });
  1338. const controller = new AbortController();
  1339. const record = makeRecord({ app, activeAbortController: controller });
  1340. await expect(
  1341. new V4CommandExecutor(makeHost(record)).execute(
  1342. envelope("sendQueuedNow", { queueItemId: "q-1" }),
  1343. ),
  1344. ).rejects.toBeInstanceOf(V4QueueItemReservedError);
  1345. expect(controller.signal.aborted).toBe(false);
  1346. expect(app.sendInput).not.toHaveBeenCalled();
  1347. expect(app.removeQueueItem).not.toHaveBeenCalled();
  1348. });
  1349. it("start barrier 失败:提升时模型已不在 Registry,释放 reservation,原 queue item 不移除", async () => {
  1350. // 排队期间 Provider 下架(套餐到期/切账号):提升走与 sendText 相同的模型准入,在 Core 建模前拒绝。
  1351. const app = makeApp({ listModels: () => [] });
  1352. const record = makeRecord({ app });
  1353. const host = makeHost(record);
  1354. await expect(
  1355. new V4CommandExecutor(host).execute(envelope("sendQueuedNow", { queueItemId: "q-1" })),
  1356. ).rejects.toMatchObject({ reasonCode: "modelUnavailable" });
  1357. expect(app.sendInput).not.toHaveBeenCalled();
  1358. expect(app.releaseQueueItemReservation).toHaveBeenCalledWith(
  1359. "q-1",
  1360. "cmd-q1",
  1361. expect.any(Object),
  1362. );
  1363. expect(app.removeQueueItem).not.toHaveBeenCalled();
  1364. });
  1365. });