v4-native-commands.test.ts 73 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109
  1. // L2:v4 原生命令执行器(sendText / stop)——验证自旧 server-operations 搬运的
  2. // 决策语义在原生层保真:steer 分流、draft 提升、ready 边界、goal-pause barrier。
  3. // 08-phasing M4 完成定义的 L2 层(命令 → core 调用 → 状态推进,不经旧协议代码)。
  4. import { SessionEventType, type SessionEvent } from "@zcode/contracts";
  5. import { describe, expect, it, vi } from "vitest";
  6. import { V4InteractionRegistry } from "../src/zcode-protocol-v4/interaction-registry.js";
  7. import {
  8. PERMISSION_FULL_ACCESS_OPTION_ID,
  9. type CommandEnvelope,
  10. } from "@zcode/shared/zcode-protocol-v4";
  11. import { createInputFacade } from "../src/app/input-facade.js";
  12. import type { SendInputOptions } from "../src/app/types.js";
  13. import { V4CommandExecutor } from "../src/zcode-protocol-v4/commands/executor.js";
  14. import { V4PromptRejectedError } from "../src/zcode-protocol-v4/commands/prompt-turn.js";
  15. import { V4InputAdmissionRejectedError } from "../src/zcode-protocol-v4/commands/input-admission.js";
  16. import type {
  17. V4CommandCoreHost,
  18. V4SessionRecordView,
  19. } from "../src/zcode-protocol-v4/commands/types.js";
  20. const ORDINARY_MODEL_SELECTION = {
  21. providerId: "builtin:bigmodel-coding-plan",
  22. modelId: "GLM-5.3",
  23. };
  24. function makeApp(overrides: Record<string, unknown> = {}) {
  25. return {
  26. sessionId: "s1",
  27. sendInput: vi.fn().mockImplementation(async (_input, options) => {
  28. if (options?.requireQueue) {
  29. return {
  30. kind: "queued",
  31. pendingInputId: "queue_cmd-1",
  32. queueLength: 1,
  33. turnId: "turn-1",
  34. };
  35. }
  36. options?.onTurnStartedObserved?.({
  37. id: "event-started",
  38. type: SessionEventType.TurnStarted,
  39. payload: { messageId: "msg-event-started" },
  40. });
  41. return {
  42. completion: Promise.resolve({}),
  43. kind: "started_turn",
  44. turnId: "turn-1",
  45. };
  46. }),
  47. steerTurn: vi.fn().mockResolvedValue({
  48. kind: "queued",
  49. pendingInputId: "queue_cmd-1",
  50. queueLength: 1,
  51. turnId: "turn-1",
  52. }),
  53. getModel: vi.fn().mockReturnValue("account:bigmodel-start-plan/glm-5"),
  54. readTarget: vi.fn().mockResolvedValue(null),
  55. updateTargetStatus: vi.fn().mockResolvedValue(null),
  56. ...overrides,
  57. };
  58. }
  59. function makeRecord(
  60. overrides: Partial<V4SessionRecordView> & { app?: ReturnType<typeof makeApp> } = {},
  61. ): V4SessionRecordView {
  62. return {
  63. app: (overrides.app ?? makeApp()) as unknown as V4SessionRecordView["app"],
  64. workspace: { workspacePath: "/w" },
  65. persistence: "immediate",
  66. ...overrides,
  67. } as V4SessionRecordView;
  68. }
  69. function makeHost(
  70. record: V4SessionRecordView,
  71. overrides: Partial<V4CommandCoreHost> = {},
  72. ): V4CommandCoreHost & {
  73. legacyMutations: string[];
  74. } {
  75. const legacyMutations: string[] = [];
  76. return {
  77. getRecord: (id) => (id === "s1" ? record : undefined),
  78. afterLegacyStateMutation: async (_r, reason) => {
  79. legacyMutations.push(reason);
  80. },
  81. waitForProjectionEventCommit: async () => {},
  82. legacyMutations,
  83. ...overrides,
  84. };
  85. }
  86. function envelope(type: string, payload: unknown): CommandEnvelope {
  87. return {
  88. type,
  89. payload,
  90. sessionId: "s1",
  91. commandId: "cmd-1",
  92. clientId: "client-test",
  93. issuedAt: 1,
  94. baseRevision: 0,
  95. } as unknown as CommandEnvelope;
  96. }
  97. it("完全访问仅在实际授权后向发起端返回可保存的权限凭据", async () => {
  98. const interactions = new V4InteractionRegistry();
  99. interactions.register("permission", vi.fn(), {
  100. sessionId: "s1",
  101. kind: "other",
  102. fullAccess: async () => {},
  103. });
  104. const executor = new V4CommandExecutor(makeHost(makeRecord(), { interactions }));
  105. const command = envelope("resolveInteraction", {
  106. interactionId: "permission",
  107. answer: { optionId: PERMISSION_FULL_ACCESS_OPTION_ID },
  108. });
  109. expect(await executor.execute(command)).toMatchObject({
  110. type: "resolveInteraction",
  111. resolvedBy: { clientId: command.clientId, optionId: PERMISSION_FULL_ACCESS_OPTION_ID },
  112. });
  113. expect(await executor.execute({ ...command, commandId: "late" })).toBeUndefined();
  114. });
  115. async function settle() {
  116. // 后台 turn 是 void 起跑的微任务链,flush 两轮保证 finally 执行完。
  117. await new Promise((r) => setTimeout(r, 0));
  118. await new Promise((r) => setTimeout(r, 0));
  119. }
  120. async function flushMicrotasks(turns = 8) {
  121. for (let index = 0; index < turns; index += 1) {
  122. await Promise.resolve();
  123. }
  124. }
  125. function deferred<T>() {
  126. let resolve!: (value: T | PromiseLike<T>) => void;
  127. let reject!: (reason?: unknown) => void;
  128. const promise = new Promise<T>((resolvePromise, rejectPromise) => {
  129. resolve = resolvePromise;
  130. reject = rejectPromise;
  131. });
  132. return { promise, reject, resolve };
  133. }
  134. type PromptSendInputOptions = {
  135. abortSignal: AbortSignal;
  136. onEvent?: (event: SessionEvent) => void;
  137. onTurnStartedObserved?: (event: SessionEvent) => void;
  138. };
  139. function workspaceHookReviewRequest(input: {
  140. interactionId: string;
  141. deadlineAt: number;
  142. createdAt?: number;
  143. generation?: number;
  144. reviewFlowId?: string;
  145. }) {
  146. return {
  147. kind: "workspaceHookReview",
  148. reviewFlowId: input.reviewFlowId ?? "review-flow-1",
  149. generation: input.generation ?? 1,
  150. interactionId: input.interactionId,
  151. sessionId: "s1",
  152. taskId: "task-1",
  153. runId: "run-1",
  154. workspaceIdentity: "/w",
  155. workspaceLabel: "w",
  156. bundleDigest: "a".repeat(64),
  157. createdAt: input.createdAt ?? Date.now(),
  158. deadlineAt: input.deadlineAt,
  159. sourceFiles: [
  160. {
  161. path: "/w/.zcode/config.json",
  162. displayPath: ".zcode/config.json",
  163. editable: true,
  164. },
  165. ],
  166. summary: { eventCount: 1, hookCount: 1, pendingCount: 1 },
  167. items: [
  168. {
  169. reviewItemId: "review-item-1",
  170. event: "PreToolUse",
  171. matcher: "*",
  172. type: "process",
  173. displayName: "echo hello",
  174. displayCommand: "echo hello",
  175. sourcePath: "/w/.zcode/config.json",
  176. resolvedTimeoutMs: 1_000,
  177. resolvedMaxOutputBytes: 1_024,
  178. executionMode: "foreground",
  179. configuredEnabled: true,
  180. editable: true,
  181. trustState: "pending_trust",
  182. },
  183. ],
  184. warningCode: "workspace_hooks_execute_code",
  185. };
  186. }
  187. function workspaceHookReviewRequestedEvent(input: {
  188. id: string;
  189. interactionId: string;
  190. deadlineAt: number;
  191. createdAt?: number;
  192. generation?: number;
  193. reviewFlowId?: string;
  194. sequenceNumber?: number;
  195. }): SessionEvent {
  196. return {
  197. id: input.id,
  198. sequenceNumber: input.sequenceNumber ?? 1,
  199. timestamp: new Date("2026-08-07T00:00:00.000Z"),
  200. type: SessionEventType.WorkspaceHookReviewRequested,
  201. payload: {
  202. request: workspaceHookReviewRequest(input),
  203. },
  204. } as unknown as SessionEvent;
  205. }
  206. function workspaceHookReviewSettledEvent(input: {
  207. id: string;
  208. interactionId: string;
  209. sequenceNumber?: number;
  210. }): SessionEvent {
  211. return {
  212. id: input.id,
  213. sequenceNumber: input.sequenceNumber ?? 2,
  214. timestamp: new Date("2026-08-07T00:00:01.000Z"),
  215. type: SessionEventType.WorkspaceHookReviewSettled,
  216. payload: {
  217. interactionId: input.interactionId,
  218. state: "resolved",
  219. },
  220. } as unknown as SessionEvent;
  221. }
  222. function turnStartedEvent(id = "event-turn-started"): SessionEvent {
  223. return {
  224. id,
  225. type: SessionEventType.TurnStarted,
  226. payload: { inputId: "cmd-1", messageId: `msg-${id}` },
  227. } as unknown as SessionEvent;
  228. }
  229. function makeAbortablePendingPromptApp() {
  230. let options: PromptSendInputOptions | undefined;
  231. const app = makeApp({
  232. sendInput: vi.fn().mockImplementation(
  233. (_input: unknown, nextOptions: PromptSendInputOptions) =>
  234. new Promise<Record<string, never>>((_resolve, reject) => {
  235. options = nextOptions;
  236. const rejectOnAbort = () => reject(nextOptions.abortSignal.reason);
  237. if (nextOptions.abortSignal.aborted) rejectOnAbort();
  238. else nextOptions.abortSignal.addEventListener("abort", rejectOnAbort, { once: true });
  239. }),
  240. ),
  241. });
  242. return {
  243. app,
  244. getOptions: () => {
  245. if (!options) throw new Error("sendInput options have not been captured");
  246. return options;
  247. },
  248. };
  249. }
  250. describe("v4 原生 sendText", () => {
  251. it("旧发送端 admission 保留 runtime 的稀疏 Session Selection,不回填 effective thought", async () => {
  252. let capturedOptions: SendInputOptions | undefined;
  253. const app = makeApp({
  254. getThoughtLevel: vi.fn(() => "high"),
  255. runtime: {
  256. getSessionModelSelection: vi.fn(() => ({ providerId: "provider-a", modelId: "model-a" })),
  257. },
  258. sendInput: vi.fn().mockImplementation(async (_input, options) => {
  259. capturedOptions = options;
  260. return {
  261. completion: Promise.resolve({}),
  262. kind: "started_turn",
  263. turnId: "turn-sparse-selection",
  264. };
  265. }),
  266. });
  267. await new V4CommandExecutor(makeHost(makeRecord({ app }))).execute(
  268. envelope("sendText", { text: "keep sparse selection" }),
  269. );
  270. expect(capturedOptions?.intent?.modelSelection).toEqual({
  271. providerId: "provider-a",
  272. modelId: "model-a",
  273. });
  274. });
  275. it("app input facade 把 start/queue 决策交给 Core admission,不查询 activeTurn", async () => {
  276. const runtime = {
  277. getActiveTurnInfo: vi.fn().mockReturnValue(undefined),
  278. admitPrompt: vi.fn().mockResolvedValue({
  279. completion: Promise.resolve({}),
  280. kind: "started",
  281. turnId: "turn-1",
  282. }),
  283. };
  284. const facade = createInputFacade({
  285. logger: { warn: vi.fn() } as never,
  286. prepareUserExecutionBoundary: async () => {},
  287. runtime: runtime as never,
  288. sessionId: "s1" as never,
  289. traceContext: { traceId: "trace-1" } as never,
  290. });
  291. const modelExecution = {
  292. selectionScope: "execution",
  293. requestDependencies: {
  294. requestAuth: { source: { resolve: vi.fn().mockResolvedValue({ apiKey: "request-key" }) } },
  295. },
  296. } as const;
  297. await facade.sendInput("hi", {
  298. inputId: "cmd-1",
  299. offPeakTaskId: "off-peak-task-1",
  300. offPeakRunType: "init",
  301. modelExecution,
  302. });
  303. expect(runtime.getActiveTurnInfo).not.toHaveBeenCalled();
  304. expect(runtime.admitPrompt).toHaveBeenCalledWith(
  305. "hi",
  306. undefined,
  307. expect.objectContaining({
  308. offPeakTaskId: "off-peak-task-1",
  309. offPeakRunType: "init",
  310. modelExecution,
  311. }),
  312. );
  313. });
  314. it("cold resume boundary 的 Hook review 被 prompt observer 捕获,且 AbortSignal 贯穿 admission", async () => {
  315. let temporarySink: { onSessionEvent(event: SessionEvent): Promise<void> | void } | undefined;
  316. const onEvent = vi.fn();
  317. const abortController = new AbortController();
  318. const reviewEvent = workspaceHookReviewRequestedEvent({
  319. id: "review-during-resume",
  320. interactionId: "interaction-resume",
  321. deadlineAt: Date.now() + 60_000,
  322. });
  323. const runtime = {
  324. getActiveTurnInfo: vi.fn().mockReturnValue(undefined),
  325. subscribeEvents: vi.fn().mockImplementation((sink) => {
  326. temporarySink = sink;
  327. return () => {};
  328. }),
  329. admitPrompt: vi.fn().mockResolvedValue({
  330. completion: Promise.resolve({}),
  331. kind: "started",
  332. turnId: "turn-resume",
  333. }),
  334. };
  335. const prepareUserExecutionBoundary = vi.fn(async (options?: { abortSignal?: AbortSignal }) => {
  336. expect(options?.abortSignal).toBe(abortController.signal);
  337. expect(temporarySink).toBeDefined();
  338. await temporarySink?.onSessionEvent(reviewEvent);
  339. });
  340. const facade = createInputFacade({
  341. logger: { warn: vi.fn() } as never,
  342. prepareUserExecutionBoundary,
  343. runtime: runtime as never,
  344. sessionId: "s1" as never,
  345. traceContext: { traceId: "trace-1" } as never,
  346. });
  347. await facade.sendInput("resume me", {
  348. abortSignal: abortController.signal,
  349. inputId: "cmd-resume",
  350. onEvent,
  351. });
  352. expect(onEvent).toHaveBeenCalledWith(reviewEvent);
  353. expect(runtime.admitPrompt).toHaveBeenCalledTimes(1);
  354. });
  355. it("空闲会话:Core admission receipt 立即返回,完成后执行 ready 清理", async () => {
  356. let finishTurn!: () => void;
  357. const turnGate = new Promise<Record<string, never>>((resolve) => {
  358. finishTurn = () => resolve({});
  359. });
  360. const app = makeApp({
  361. sendInput: vi.fn().mockReturnValue({
  362. completion: turnGate,
  363. kind: "started_turn",
  364. turnId: "turn-1",
  365. }),
  366. });
  367. const record = makeRecord({ app });
  368. const host = makeHost(record);
  369. const executing = new V4CommandExecutor(host)
  370. .execute(
  371. envelope("sendText", {
  372. text: "hi",
  373. browserAmbientContext: {
  374. tabCount: 1,
  375. currentUrl: "https://example.com/current",
  376. },
  377. }),
  378. )
  379. .then((result) => {
  380. expect(result).toEqual({
  381. type: "inputAccepted",
  382. delivery: "startNow",
  383. inputId: "cmd-1",
  384. });
  385. });
  386. await vi.waitFor(() => expect(app.sendInput).toHaveBeenCalledTimes(1));
  387. await executing;
  388. expect(record.activeAbortController).toBeUndefined();
  389. finishTurn();
  390. await settle();
  391. expect(app.sendInput).toHaveBeenCalledWith(
  392. { text: "hi" },
  393. expect.objectContaining({
  394. inputId: "cmd-1",
  395. queryId: "cmd-1",
  396. browserAmbientContext: {
  397. tabCount: 1,
  398. currentUrl: "https://example.com/current",
  399. },
  400. intent: expect.objectContaining({
  401. sourceCommandId: "cmd-1",
  402. queueItemId: "queue_cmd-1",
  403. clientId: "client-test",
  404. requestedDelivery: "startNow",
  405. }),
  406. }),
  407. );
  408. // Core completion 后再执行 legacy cleanup;Bootstrap controller 从不参与 busy 判定。
  409. expect(record.activeAbortController).toBeUndefined();
  410. expect(host.legacyMutations).toEqual(["prompt_completed"]);
  411. });
  412. it("TurnStarted 缺 messageId 时仍提交 Chat authority,仅省略 repo 归因结果", async () => {
  413. const app = makeApp({
  414. sendInput: vi.fn().mockResolvedValue({
  415. completion: Promise.resolve({}),
  416. kind: "started_turn",
  417. turnId: "turn-without-message-id",
  418. }),
  419. });
  420. await expect(
  421. new V4CommandExecutor(makeHost(makeRecord({ app }))).execute(
  422. envelope("sendText", { text: "chat 必须继续" }),
  423. ),
  424. ).resolves.toEqual({
  425. type: "inputAccepted",
  426. delivery: "startNow",
  427. inputId: "cmd-1",
  428. });
  429. });
  430. it("Highspeed turn 运行中再次发送仍进入 queue,加速执行材料只暂存在 CLI 内存", async () => {
  431. const app = makeApp();
  432. const record = makeRecord({ app, activeAbortController: new AbortController() });
  433. const retainQueuedTurnExecution = vi.fn();
  434. const host = makeHost(record, {
  435. getInputRoutingMode: () => "enqueue",
  436. retainQueuedTurnExecution,
  437. });
  438. await expect(
  439. new V4CommandExecutor(host).execute(
  440. envelope("sendText", {
  441. text: "排队继续问",
  442. highspeedMeta: {
  443. schemaVersion: 1,
  444. cardId: "card-1",
  445. taskId: "s1",
  446. provider: "bigmodel",
  447. model: "GLM-5.3",
  448. issuedAt: 1,
  449. expiresAt: Date.now() + 60_000,
  450. },
  451. modelSelection: {
  452. providerId: "account:bigmodel-highspeed-card",
  453. modelId: "GLM-5.3",
  454. },
  455. modelExecution: {
  456. selectionScope: "execution",
  457. requestAuth: { apiKey: "card-jwt", headers: { "X-Highspeed-Card-ID": "card-1" } },
  458. selectionFallback: {
  459. providerId: "account:bigmodel-highspeed-card",
  460. target: ORDINARY_MODEL_SELECTION,
  461. rules: [
  462. { reason: "highspeed_card_expired", providerErrorCode: "3402" },
  463. { reason: "highspeed_request_failed" },
  464. ],
  465. },
  466. },
  467. }),
  468. ),
  469. ).resolves.toEqual({
  470. type: "inputAccepted",
  471. delivery: "queue",
  472. inputId: "cmd-1",
  473. });
  474. expect(app.sendInput).toHaveBeenCalledWith(
  475. { text: "排队继续问" },
  476. expect.objectContaining({
  477. requireQueue: true,
  478. intent: expect.objectContaining({
  479. highspeed: expect.objectContaining({ cardId: "card-1" }),
  480. // 队列只持久化普通模型;临时 Selection 与凭据必须成包驻留内存。
  481. modelSelection: ORDINARY_MODEL_SELECTION,
  482. }),
  483. }),
  484. );
  485. // 凭据不进队列事件,只按 (sessionId, sourceCommandId) 暂存在 CLI 进程内。
  486. expect(retainQueuedTurnExecution).toHaveBeenCalledWith("s1", "cmd-1", {
  487. modelSelection: {
  488. providerId: "account:bigmodel-highspeed-card",
  489. modelId: "GLM-5.3",
  490. },
  491. modelExecution: expect.objectContaining({
  492. selectionScope: "execution",
  493. requestAuth: expect.objectContaining({ apiKey: "card-jwt" }),
  494. }),
  495. });
  496. });
  497. it("Highspeed 入队忽略被污染为加速 Provider 的退回目标", async () => {
  498. const app = makeApp({ getModel: () => "builtin:bigmodel-coding-plan/GLM-5.3" });
  499. const record = makeRecord({ app, activeAbortController: new AbortController() });
  500. const host = makeHost(record, {
  501. getInputRoutingMode: () => "enqueue",
  502. retainQueuedTurnExecution: vi.fn(),
  503. });
  504. await new V4CommandExecutor(host).execute(
  505. envelope("sendText", {
  506. text: "退回目标被污染时仍保存普通模型",
  507. highspeedMeta: {
  508. schemaVersion: 1,
  509. cardId: "card-polluted-fallback",
  510. taskId: "s1",
  511. provider: "bigmodel",
  512. model: "GLM-5.3",
  513. issuedAt: 1,
  514. expiresAt: Date.now() + 60_000,
  515. },
  516. modelSelection: {
  517. providerId: "account:bigmodel-highspeed-card",
  518. modelId: "GLM-5.3",
  519. },
  520. modelExecution: {
  521. selectionScope: "execution",
  522. requestAuth: { apiKey: "card-jwt" },
  523. selectionFallback: {
  524. providerId: "account:bigmodel-highspeed-card",
  525. target: {
  526. providerId: "account:bigmodel-highspeed-card",
  527. modelId: "GLM-5.3",
  528. },
  529. rules: [{ reason: "highspeed_request_failed" }],
  530. },
  531. },
  532. }),
  533. );
  534. expect(app.sendInput).toHaveBeenCalledWith(
  535. { text: "退回目标被污染时仍保存普通模型" },
  536. expect.objectContaining({
  537. requireQueue: true,
  538. intent: expect.objectContaining({ modelSelection: ORDINARY_MODEL_SELECTION }),
  539. }),
  540. );
  541. });
  542. it("Highspeed 运行中输入在 guide 模式下仍进入 queue", async () => {
  543. const app = makeApp({
  544. runtime: { getActiveTurnInfo: vi.fn().mockReturnValue({ steerable: true }) },
  545. });
  546. const record = makeRecord({ app, activeAbortController: new AbortController() });
  547. const retainQueuedTurnExecution = vi.fn();
  548. const host = makeHost(record, {
  549. getInputRoutingMode: () => "guide",
  550. hasQueuedDelivery: () => false,
  551. retainQueuedTurnExecution,
  552. });
  553. await new V4CommandExecutor(host).execute(
  554. envelope("sendText", {
  555. text: "加速输入不应内联当前轮",
  556. highspeedMeta: {
  557. schemaVersion: 1,
  558. cardId: "card-guide",
  559. taskId: "s1",
  560. provider: "bigmodel",
  561. model: "GLM-5.3",
  562. issuedAt: 1,
  563. expiresAt: Date.now() + 60_000,
  564. },
  565. modelSelection: {
  566. providerId: "account:bigmodel-highspeed-card",
  567. modelId: "GLM-5.3",
  568. },
  569. modelExecution: {
  570. selectionScope: "execution",
  571. requestAuth: { apiKey: "card-jwt", headers: { "X-Highspeed-Card-ID": "card-guide" } },
  572. selectionFallback: {
  573. providerId: "account:bigmodel-highspeed-card",
  574. target: ORDINARY_MODEL_SELECTION,
  575. rules: [
  576. { reason: "highspeed_card_expired", providerErrorCode: "3402" },
  577. { reason: "highspeed_request_failed" },
  578. ],
  579. },
  580. },
  581. }),
  582. );
  583. expect(app.sendInput).toHaveBeenCalledWith(
  584. { text: "加速输入不应内联当前轮" },
  585. expect.objectContaining({
  586. requireQueue: true,
  587. intent: expect.objectContaining({
  588. requestedDelivery: "guide",
  589. admittedDelivery: "queue",
  590. fallbackReasonCode: "highspeed.requiresQueue",
  591. highspeed: expect.objectContaining({ cardId: "card-guide" }),
  592. modelSelection: ORDINARY_MODEL_SELECTION,
  593. }),
  594. }),
  595. );
  596. expect(retainQueuedTurnExecution).toHaveBeenCalledWith("s1", "cmd-1", {
  597. modelSelection: {
  598. providerId: "account:bigmodel-highspeed-card",
  599. modelId: "GLM-5.3",
  600. },
  601. modelExecution: expect.objectContaining({ selectionScope: "execution" }),
  602. });
  603. });
  604. it("Core active turn 已存在但 controller 与投影尚未同步时,Highspeed 输入仍进入 queue", async () => {
  605. const app = makeApp({
  606. runtime: {
  607. getActiveTurnInfo: vi.fn().mockReturnValue({
  608. kind: "regular",
  609. steerable: true,
  610. turnId: "turn-highspeed",
  611. }),
  612. },
  613. });
  614. const listModels = vi.fn(() => [{ ref: ORDINARY_MODEL_SELECTION }]);
  615. app.listModels = listModels;
  616. const record = makeRecord({ app });
  617. const retainQueuedTurnExecution = vi.fn();
  618. const host = makeHost(record, {
  619. getInputRoutingMode: () => "startNow",
  620. retainQueuedTurnExecution,
  621. });
  622. await expect(
  623. new V4CommandExecutor(host).execute(
  624. envelope("sendText", {
  625. text: "controller 同步前也要排队",
  626. highspeedMeta: {
  627. schemaVersion: 1,
  628. cardId: "card-1",
  629. taskId: "s1",
  630. provider: "bigmodel",
  631. model: "GLM-5.3",
  632. issuedAt: 1,
  633. expiresAt: Date.now() + 60_000,
  634. },
  635. modelSelection: {
  636. providerId: "account:bigmodel-highspeed-card",
  637. modelId: "GLM-5.3",
  638. },
  639. modelExecution: {
  640. selectionScope: "execution",
  641. requestAuth: { apiKey: "card-jwt", headers: { "X-Highspeed-Card-ID": "card-1" } },
  642. selectionFallback: {
  643. providerId: "account:bigmodel-highspeed-card",
  644. target: ORDINARY_MODEL_SELECTION,
  645. rules: [
  646. { reason: "highspeed_card_expired", providerErrorCode: "3402" },
  647. { reason: "highspeed_request_failed" },
  648. ],
  649. },
  650. },
  651. }),
  652. ),
  653. ).resolves.toEqual({
  654. type: "inputAccepted",
  655. delivery: "queue",
  656. inputId: "cmd-1",
  657. });
  658. expect(app.sendInput).toHaveBeenCalledWith(
  659. { text: "controller 同步前也要排队" },
  660. expect.objectContaining({
  661. requireQueue: true,
  662. intent: expect.objectContaining({
  663. highspeed: expect.objectContaining({ cardId: "card-1" }),
  664. modelSelection: ORDINARY_MODEL_SELECTION,
  665. }),
  666. }),
  667. );
  668. // 入队只下发普通 Selection 与卡元数据,不下发 execution 与凭据,仍按普通轮做 Session 模型
  669. // preflight:卡失效后提升使用 QueueItem 的普通 Selection,模型不可用必须在 admission 就暴露。
  670. expect(listModels).toHaveBeenCalled();
  671. expect(app.sendInput.mock.calls[0]?.[1]).not.toHaveProperty("modelExecution");
  672. expect(retainQueuedTurnExecution).toHaveBeenCalledWith("s1", "cmd-1", {
  673. modelSelection: {
  674. providerId: "account:bigmodel-highspeed-card",
  675. modelId: "GLM-5.3",
  676. },
  677. modelExecution: expect.objectContaining({ selectionScope: "execution" }),
  678. });
  679. });
  680. it("execution-scoped Selection 直接进入 Core,Session 模型从不临时切换", async () => {
  681. const order: string[] = [];
  682. const currentModel = "user-provider/user-model";
  683. let capturedOptions: SendInputOptions | undefined;
  684. let finishTurn!: () => void;
  685. const turnGate = new Promise<Record<string, never>>((resolve) => {
  686. finishTurn = () => resolve({});
  687. });
  688. const app = makeApp({
  689. getModel: vi.fn(() => currentModel),
  690. sendInput: vi.fn().mockImplementation(async (_input, options) => {
  691. capturedOptions = options;
  692. order.push(`send:${currentModel}`);
  693. return {
  694. completion: turnGate,
  695. kind: "started_turn",
  696. turnId: "turn-offpeak",
  697. };
  698. }),
  699. });
  700. const record = makeRecord({ app });
  701. const host = makeHost(record, {
  702. afterLegacyStateMutation: vi.fn().mockImplementation(async () => {
  703. order.push(`ready:${currentModel}`);
  704. }),
  705. });
  706. await new V4CommandExecutor(host).execute(
  707. envelope("sendText", {
  708. text: "run in idle pool",
  709. modelSelection: { providerId: "account:zai-offpeak-idle-plan", modelId: "GLM-5.2" },
  710. modelExecution: {
  711. memoryExtraction: "skip",
  712. selectionScope: "execution",
  713. requestAuth: {
  714. apiKey: "request-key",
  715. headers: { "X-Off-Peak-Ticket-ID": "ticket-1" },
  716. },
  717. subagents: {
  718. foregroundModel: "submission",
  719. background: "deny",
  720. },
  721. },
  722. }),
  723. );
  724. expect(record.activeAbortController).toBeUndefined();
  725. finishTurn();
  726. await settle();
  727. expect(order).toEqual(["send:user-provider/user-model", "ready:user-provider/user-model"]);
  728. expect(capturedOptions?.intent?.modelSelection).toEqual({
  729. providerId: "account:zai-offpeak-idle-plan",
  730. modelId: "GLM-5.2",
  731. });
  732. expect(capturedOptions?.modelExecution).toMatchObject({
  733. memoryExtraction: "skip",
  734. selectionScope: "execution",
  735. subagents: { foregroundModel: "submission", background: "deny" },
  736. });
  737. await expect(
  738. capturedOptions?.modelExecution?.requestDependencies?.requestAuth?.source?.resolve({}),
  739. ).resolves.toEqual({
  740. apiKey: "request-key",
  741. headers: { "X-Off-Peak-Ticket-ID": "ticket-1" },
  742. });
  743. expect(record.activeAbortController).toBeUndefined();
  744. });
  745. it("execution-scoped Selection 不受 Session 模型恢复告警阻断", async () => {
  746. const app = makeApp();
  747. const record = makeRecord({
  748. app,
  749. restoreWarning: { message: "session model unavailable", type: "model_unavailable" },
  750. });
  751. const host = makeHost(record, {
  752. hasUsableRuntimeModelTarget: vi.fn().mockReturnValue(false),
  753. });
  754. await expect(
  755. new V4CommandExecutor(host).execute(
  756. envelope("sendText", {
  757. text: "run in idle pool",
  758. modelSelection: { providerId: "account:zai-offpeak-idle-plan", modelId: "GLM-5.2" },
  759. modelExecution: {
  760. selectionScope: "execution",
  761. requestAuth: { apiKey: "request-key" },
  762. },
  763. }),
  764. ),
  765. ).resolves.toBeDefined();
  766. await settle();
  767. expect(record.restoreWarning).toEqual({
  768. message: "session model unavailable",
  769. type: "model_unavailable",
  770. });
  771. });
  772. it.each(["failed", "cancelled"] as const)(
  773. "execution-scoped turn %s 后不污染下一条普通 prompt",
  774. async (outcome) => {
  775. const observedExecutionContexts: unknown[] = [];
  776. let sendCount = 0;
  777. const app = makeApp({
  778. sendInput: vi.fn().mockImplementation(async (_input, options) => {
  779. sendCount += 1;
  780. observedExecutionContexts.push(options?.modelExecution);
  781. if (sendCount === 1) {
  782. return {
  783. completion: Promise.reject(
  784. new DOMException(
  785. outcome === "cancelled" ? "idle turn cancelled" : "idle turn failed",
  786. outcome === "cancelled" ? "AbortError" : "Error",
  787. ),
  788. ),
  789. kind: "started_turn",
  790. turnId: `turn-${outcome}`,
  791. };
  792. }
  793. return {
  794. completion: Promise.resolve({}),
  795. kind: "started_turn",
  796. turnId: "turn-ordinary",
  797. };
  798. }),
  799. });
  800. const record = makeRecord({ app });
  801. const host = makeHost(record);
  802. await new V4CommandExecutor(host).execute(
  803. envelope("sendText", {
  804. text: "idle prompt",
  805. modelSelection: { providerId: "account:zai-offpeak-idle-plan", modelId: "GLM-5.2" },
  806. modelExecution: {
  807. selectionScope: "execution",
  808. requestAuth: { apiKey: `ticket-${outcome}` },
  809. },
  810. }),
  811. );
  812. await settle();
  813. expect(record.activeAbortController).toBeUndefined();
  814. await new V4CommandExecutor(host).execute(envelope("sendText", { text: "ordinary prompt" }));
  815. await settle();
  816. expect(observedExecutionContexts[0]).toBeDefined();
  817. expect(observedExecutionContexts[1]).toBeUndefined();
  818. },
  819. );
  820. it("automation sendText 仅在当前 turn 隐藏全部 automation 写工具", async () => {
  821. const app = makeApp();
  822. const record = makeRecord({ app });
  823. const host = makeHost(record);
  824. await new V4CommandExecutor(host).execute(
  825. envelope("sendText", {
  826. text: "automation prompt",
  827. automationId: "automation-1",
  828. highspeedMeta: {
  829. schemaVersion: 1,
  830. cardId: "card-1",
  831. taskId: "s1",
  832. provider: "bigmodel",
  833. model: "GLM-5.3",
  834. issuedAt: 1,
  835. expiresAt: Date.now() + 60_000,
  836. },
  837. modelSelection: {
  838. providerId: "account:bigmodel-highspeed-card",
  839. modelId: "GLM-5.3",
  840. },
  841. modelExecution: {
  842. selectionScope: "execution",
  843. requestAuth: { apiKey: "card-jwt" },
  844. },
  845. }),
  846. );
  847. await settle();
  848. await new V4CommandExecutor(host).execute(envelope("sendText", { text: "normal prompt" }));
  849. await settle();
  850. expect(app.sendInput.mock.calls[0]?.[1]).toEqual(
  851. expect.objectContaining({
  852. toolDisallowlist: ["CronCreate", "CronUpdate", "CronDelete"],
  853. }),
  854. );
  855. expect(app.sendInput.mock.calls[0]?.[1]?.intent).not.toHaveProperty("highspeed");
  856. // 定时执行身份优先:加速 Selection 与执行材料必须在 admission 前被整体丢弃。intent 仍会
  857. // 固化本会话常驻 Selection(普通轮的通用行为),但绝不能是加速卡 Provider,否则本轮会
  858. // 拿加速卡凭据发请求,或把普通输出持久化成 Highspeed 消息。
  859. expect(app.sendInput.mock.calls[0]?.[1]?.intent?.modelSelection).toEqual({
  860. providerId: "account:bigmodel-start-plan",
  861. modelId: "glm-5",
  862. });
  863. expect(app.sendInput.mock.calls[0]?.[1]).not.toHaveProperty("modelExecution");
  864. expect(app.sendInput.mock.calls[1]?.[1]).not.toHaveProperty("toolDisallowlist");
  865. expect(record.activeAutomationId).toBeUndefined();
  866. });
  867. it("Highspeed 用户 turn 保留 CronCreate 工具可见性", async () => {
  868. const app = makeApp();
  869. const record = makeRecord({ app });
  870. const host = makeHost(record);
  871. await new V4CommandExecutor(host).execute(
  872. envelope("sendText", {
  873. text: "加速期间创建一个定时任务",
  874. highspeedMeta: {
  875. schemaVersion: 1,
  876. cardId: "card-1",
  877. taskId: "s1",
  878. provider: "bigmodel",
  879. model: "GLM-5.3",
  880. issuedAt: 1,
  881. expiresAt: Date.now() + 60_000,
  882. },
  883. modelSelection: {
  884. providerId: "account:bigmodel-highspeed-card",
  885. modelId: "GLM-5.3",
  886. },
  887. modelExecution: {
  888. selectionScope: "execution",
  889. requestAuth: { apiKey: "card-jwt" },
  890. },
  891. }),
  892. );
  893. await settle();
  894. expect(app.sendInput).toHaveBeenCalledWith(
  895. { text: "加速期间创建一个定时任务" },
  896. expect.not.objectContaining({ toolDisallowlist: expect.anything() }),
  897. );
  898. });
  899. it("Bot delivery target 仅在当前 turn 可见,并在 turn 结束后恢复", async () => {
  900. let releaseTurn!: () => void;
  901. const turnGate = new Promise<void>((resolve) => {
  902. releaseTurn = resolve;
  903. });
  904. const app = makeApp({
  905. sendInput: vi.fn().mockResolvedValue({
  906. completion: turnGate,
  907. kind: "started_turn",
  908. turnId: "turn-bot",
  909. }),
  910. });
  911. const record = makeRecord({ app });
  912. const host = makeHost(record);
  913. const botDeliveryTarget = {
  914. provider: "weixin" as const,
  915. botId: "bot-weixin",
  916. providerUserId: "chat-1",
  917. chatType: "private" as const,
  918. };
  919. await new V4CommandExecutor(host).execute(
  920. envelope("sendText", { text: "创建提醒", botDeliveryTarget }),
  921. );
  922. expect(record.activeBotDeliveryTarget).toEqual(botDeliveryTarget);
  923. releaseTurn();
  924. await settle();
  925. expect(record.activeBotDeliveryTarget).toBeUndefined();
  926. });
  927. it("off-peak sendText 保留本轮归因与独立创建限制,普通后续轮不继承", async () => {
  928. const app = makeApp();
  929. const record = makeRecord({ app });
  930. const host = makeHost(record);
  931. await new V4CommandExecutor(host).execute(
  932. envelope("sendText", {
  933. text: "off-peak prompt",
  934. offPeakTaskId: "off-peak-task-1",
  935. offPeakRunType: "resume",
  936. }),
  937. );
  938. await settle();
  939. await new V4CommandExecutor(host).execute(envelope("sendText", { text: "manual follow-up" }));
  940. await settle();
  941. expect(app.sendInput.mock.calls[0]?.[1]).toEqual(
  942. expect.objectContaining({
  943. offPeakTaskId: "off-peak-task-1",
  944. offPeakRunType: "resume",
  945. }),
  946. );
  947. // 闲时支持 SendMessage;独立工作流无法继承票据,执行与修改入口继续限制。
  948. // Host 的额外 denylist 另行合并。
  949. expect(app.sendInput.mock.calls[0]?.[1].toolDisallowlist).toEqual([
  950. "OffPeakCreate",
  951. "Workflow",
  952. "CreateWorkflow",
  953. "AmendWorkflow",
  954. "ResumeWorkflowRun",
  955. "EvalWorkflowSnippet",
  956. ]);
  957. expect(app.sendInput.mock.calls[1]?.[1]).not.toHaveProperty("offPeakTaskId");
  958. expect(app.sendInput.mock.calls[1]?.[1]).not.toHaveProperty("offPeakRunType");
  959. expect(app.sendInput.mock.calls[1]?.[1]).not.toHaveProperty("toolDisallowlist");
  960. });
  961. it("调用方伪造 automation inputId 时不恢复任务身份", async () => {
  962. const app = makeApp();
  963. const record = makeRecord({ app });
  964. const host = makeHost(record);
  965. await new V4CommandExecutor(host).execute({
  966. ...envelope("sendText", { text: "ordinary prompt" }),
  967. commandId: "automation-other-task:manual:forged-run",
  968. });
  969. await settle();
  970. expect(app.sendInput.mock.calls[0]?.[1]).not.toHaveProperty("automationId");
  971. expect(app.sendInput.mock.calls[0]?.[1]).not.toHaveProperty("toolDisallowlist");
  972. expect(record.activeAutomationId).toBeUndefined();
  973. });
  974. it("cron task 普通 sendText 隐藏 CronCreate 但不进入 automation 派发态", async () => {
  975. const app = makeApp();
  976. const record = makeRecord({ app });
  977. const host = makeHost(record);
  978. await new V4CommandExecutor(host).execute(
  979. envelope("sendText", {
  980. text: "拒绝删除旧任务后继续设置新提醒",
  981. toolDisallowlist: ["CronCreate"],
  982. }),
  983. );
  984. await settle();
  985. expect(app.sendInput.mock.calls[0]?.[1]).toEqual(
  986. expect.objectContaining({ toolDisallowlist: ["CronCreate"] }),
  987. );
  988. expect(record.activeAutomationId).toBeUndefined();
  989. });
  990. it("运行中会话:Bootstrap 仍走 Core admission,由 Core 返回 queue receipt", async () => {
  991. const app = makeApp({
  992. sendInput: vi.fn().mockResolvedValue({
  993. kind: "queued",
  994. pendingInputId: "pending-followup",
  995. queueLength: 1,
  996. turnId: "turn-1",
  997. }),
  998. });
  999. const record = makeRecord({ app, activeAbortController: new AbortController() });
  1000. const host = makeHost(record);
  1001. await new V4CommandExecutor(host).execute(
  1002. envelope("sendText", {
  1003. text: "追加",
  1004. modelSelection: {
  1005. providerId: "provider-b",
  1006. modelId: "model-b",
  1007. options: { reasoningLevel: "high" },
  1008. },
  1009. mode: "plan",
  1010. }),
  1011. );
  1012. expect(app.sendInput).toHaveBeenCalledWith(
  1013. { text: "追加" },
  1014. expect.objectContaining({
  1015. delivery: "start_turn",
  1016. inputId: "cmd-1",
  1017. intent: expect.objectContaining({
  1018. sourceCommandId: "cmd-1",
  1019. queueItemId: "queue_cmd-1",
  1020. clientId: "client-test",
  1021. modelSelection: {
  1022. providerId: "provider-b",
  1023. modelId: "model-b",
  1024. options: { reasoningLevel: "high" },
  1025. },
  1026. mode: "build",
  1027. planEnabled: true,
  1028. }),
  1029. }),
  1030. );
  1031. expect(app.steerTurn).not.toHaveBeenCalled();
  1032. });
  1033. // 立即发送是用户的新指令:实际抢占旧执行后,输入仍是普通用户消息,与空闲时发送相同。
  1034. it.each([
  1035. { stopKind: "stopped", attachmentMime: undefined },
  1036. { stopKind: "idle", attachmentMime: undefined },
  1037. { stopKind: "stopped", attachmentMime: "text/plain" },
  1038. ])(
  1039. "startNow 抢占后仍是普通用户输入:$stopKind / $attachmentMime",
  1040. async ({ stopKind, attachmentMime }) => {
  1041. const app = makeApp({
  1042. runtime: {
  1043. acquireForegroundPromotionLease: vi.fn().mockReturnValue({ kind: "acquired" }),
  1044. getActiveForegroundExecutionId: vi.fn().mockReturnValue(undefined),
  1045. releaseForegroundPromotionLease: vi.fn().mockReturnValue(true),
  1046. stopActiveForegroundExecution: vi
  1047. .fn()
  1048. .mockReturnValue(
  1049. stopKind === "stopped"
  1050. ? { kind: "stopped", foregroundExecutionId: "foreground-1" }
  1051. : { kind: "idle" },
  1052. ),
  1053. },
  1054. });
  1055. // UI 即使仍显示 busy,Core 的 idle 回执也不能被猜成一次抢占。
  1056. const host = makeHost(makeRecord({ app }), { getInputRoutingMode: () => "enqueue" });
  1057. await new V4CommandExecutor(host).execute(
  1058. envelope("sendText", {
  1059. text: "先处理这个短任务",
  1060. requestedDelivery: "startNow",
  1061. ...(attachmentMime
  1062. ? {
  1063. attachments: [
  1064. { ref: "/tmp/note", fileName: "note", mime: attachmentMime, bytes: 9 },
  1065. ],
  1066. }
  1067. : {}),
  1068. }),
  1069. );
  1070. expect(app.sendInput).toHaveBeenCalledTimes(1);
  1071. const [input, options] = app.sendInput.mock.calls[0]!;
  1072. expect(input.text).toBe("先处理这个短任务");
  1073. expect(options).not.toHaveProperty("inputPresentation");
  1074. expect(options).toMatchObject({
  1075. inputId: "cmd-1",
  1076. requireIdle: true,
  1077. intent: { requestedDelivery: "startNow" },
  1078. });
  1079. },
  1080. );
  1081. it("抢占后的 startNow 经真实 input facade 以普通用户输入进入新轮 Core admission", async () => {
  1082. const runtime = {
  1083. acquireForegroundPromotionLease: vi.fn().mockReturnValue({ kind: "acquired" }),
  1084. getActiveForegroundExecutionId: vi.fn().mockReturnValue(undefined),
  1085. releaseForegroundPromotionLease: vi.fn().mockReturnValue(true),
  1086. stopActiveForegroundExecution: vi
  1087. .fn()
  1088. .mockReturnValue({ kind: "stopped", foregroundExecutionId: "foreground-1" }),
  1089. admitPrompt: vi
  1090. .fn()
  1091. .mockResolvedValue({ kind: "started", turnId: "turn-2", completion: Promise.resolve({}) }),
  1092. };
  1093. const facade = createInputFacade({
  1094. logger: { warn: vi.fn() } as never,
  1095. prepareUserExecutionBoundary: async () => {},
  1096. runtime: runtime as never,
  1097. sessionId: "s1" as never,
  1098. traceContext: { traceId: "trace-1" } as never,
  1099. });
  1100. const app = makeApp({ runtime, sendInput: facade.sendInput });
  1101. await new V4CommandExecutor(makeHost(makeRecord({ app }))).execute(
  1102. envelope("sendText", { text: "短任务", requestedDelivery: "startNow" }),
  1103. );
  1104. expect(runtime.admitPrompt).toHaveBeenCalledWith(
  1105. "短任务",
  1106. undefined,
  1107. expect.objectContaining({
  1108. inputId: "cmd-1",
  1109. requireIdle: true,
  1110. delivery: "start_turn",
  1111. }),
  1112. );
  1113. expect(runtime.admitPrompt.mock.calls[0]![2]).not.toHaveProperty("inputPresentation");
  1114. });
  1115. it("运行中 startNow:原子抢占后直接启动新 turn,不创建 queue item", async () => {
  1116. const controller = new AbortController();
  1117. const acquireForegroundPromotionLease = vi.fn().mockReturnValue({ kind: "acquired" });
  1118. const releaseForegroundPromotionLease = vi.fn().mockReturnValue(true);
  1119. const app = makeApp({
  1120. runtime: {
  1121. acquireForegroundPromotionLease,
  1122. getActiveForegroundExecutionId: vi.fn().mockReturnValue(undefined),
  1123. releaseForegroundPromotionLease,
  1124. stopActiveForegroundExecution: vi.fn().mockReturnValue({ kind: "idle" }),
  1125. },
  1126. });
  1127. const record = makeRecord({ app, activeAbortController: controller });
  1128. controller.signal.addEventListener("abort", () => {
  1129. record.activeAbortController = undefined;
  1130. });
  1131. await new V4CommandExecutor(makeHost(record)).execute(
  1132. envelope("sendText", { text: "现在执行", requestedDelivery: "startNow" }),
  1133. );
  1134. expect(acquireForegroundPromotionLease).toHaveBeenCalledWith({
  1135. leaseId: "send-now:cmd-1",
  1136. mode: "after-current",
  1137. promotedInputId: "cmd-1",
  1138. });
  1139. expect(app.sendInput).toHaveBeenCalledWith(
  1140. { text: "现在执行" },
  1141. expect.objectContaining({
  1142. requireIdle: true,
  1143. intent: expect.objectContaining({
  1144. admittedDelivery: "startNow",
  1145. requestedDelivery: "startNow",
  1146. sourceCommandId: "cmd-1",
  1147. }),
  1148. }),
  1149. );
  1150. expect(app.steerTurn).not.toHaveBeenCalled();
  1151. expect(releaseForegroundPromotionLease).toHaveBeenCalledWith("send-now:cmd-1");
  1152. });
  1153. it("伪造 automation inputId 排队时仍保持普通用户轮", async () => {
  1154. const app = makeApp({
  1155. sendInput: vi.fn().mockResolvedValue({
  1156. kind: "queued",
  1157. pendingInputId: "pending-ordinary-followup",
  1158. queueLength: 1,
  1159. turnId: "turn-1",
  1160. }),
  1161. });
  1162. const record = makeRecord({ app, activeAbortController: new AbortController() });
  1163. const host = makeHost(record);
  1164. await new V4CommandExecutor(host).execute({
  1165. ...envelope("sendText", { text: "ordinary followup" }),
  1166. commandId: "automation-other-task:manual:forged-run",
  1167. });
  1168. expect(app.sendInput).toHaveBeenCalledWith(
  1169. { text: "ordinary followup" },
  1170. expect.objectContaining({
  1171. delivery: "start_turn",
  1172. inputId: "automation-other-task:manual:forged-run",
  1173. }),
  1174. );
  1175. expect(app.sendInput.mock.calls[0]?.[1]).not.toHaveProperty("automationId");
  1176. expect(app.sendInput.mock.calls[0]?.[1]).not.toHaveProperty("toolDisallowlist");
  1177. expect(app.steerTurn).not.toHaveBeenCalled();
  1178. });
  1179. it.each([
  1180. "account:bigmodel-start-plan/glm-5",
  1181. "custom-openai/gpt-5",
  1182. "anthropic/claude-sonnet-4-5",
  1183. ])("guide eligible:running + 无普通 queue 时模型 %s 按 guide 投递", async (model) => {
  1184. const app = makeApp({
  1185. sendInput: vi.fn().mockResolvedValue({
  1186. kind: "queued",
  1187. pendingInputId: "pending-guide",
  1188. queueLength: 1,
  1189. turnId: "turn-1",
  1190. }),
  1191. getModel: vi.fn().mockReturnValue(model),
  1192. runtime: { getActiveTurnInfo: vi.fn().mockReturnValue({ steerable: true }) },
  1193. });
  1194. const record = makeRecord({ app, activeAbortController: new AbortController() });
  1195. const host = makeHost(record, {
  1196. getInputRoutingMode: () => "guide",
  1197. hasQueuedDelivery: () => false,
  1198. });
  1199. const [providerId, ...modelSegments] = model.split("/");
  1200. await new V4CommandExecutor(host).execute(
  1201. envelope("sendText", {
  1202. text: "引导当前工作",
  1203. modelSelection: { providerId, modelId: modelSegments.join("/") },
  1204. mode: "build",
  1205. }),
  1206. );
  1207. expect(app.sendInput).toHaveBeenCalledWith(
  1208. { text: "引导当前工作" },
  1209. expect.objectContaining({
  1210. delivery: "start_turn",
  1211. queueDelivery: "guide",
  1212. intent: expect.objectContaining({
  1213. requestedDelivery: "guide",
  1214. admittedDelivery: "guide",
  1215. modelSelection: { providerId, modelId: modelSegments.join("/") },
  1216. mode: "build",
  1217. }),
  1218. }),
  1219. );
  1220. expect(app.getModel).not.toHaveBeenCalled();
  1221. });
  1222. it.each([
  1223. {
  1224. routingMode: "enqueue" as const,
  1225. requestedDelivery: "guide" as const,
  1226. expectedQueueDelivery: "guide" as const,
  1227. },
  1228. {
  1229. routingMode: "guide" as const,
  1230. requestedDelivery: "queue" as const,
  1231. expectedQueueDelivery: undefined,
  1232. },
  1233. ])(
  1234. "one-message $requestedDelivery overrides session routing $routingMode",
  1235. async ({ routingMode, requestedDelivery, expectedQueueDelivery }) => {
  1236. const app = makeApp({
  1237. sendInput: vi.fn().mockResolvedValue({
  1238. kind: "queued",
  1239. pendingInputId: "pending-delivery-override",
  1240. queueLength: 1,
  1241. turnId: "turn-1",
  1242. }),
  1243. });
  1244. const record = makeRecord({ app, activeAbortController: new AbortController() });
  1245. const host = makeHost(record, { getInputRoutingMode: () => routingMode });
  1246. await new V4CommandExecutor(host).execute(
  1247. envelope("sendText", { text: "只反转这一条", requestedDelivery }),
  1248. );
  1249. expect(app.sendInput).toHaveBeenCalledWith(
  1250. { text: "只反转这一条" },
  1251. expect.objectContaining({
  1252. delivery: "start_turn",
  1253. ...(expectedQueueDelivery ? { queueDelivery: expectedQueueDelivery } : {}),
  1254. intent: expect.objectContaining({
  1255. requestedDelivery,
  1256. admittedDelivery: requestedDelivery,
  1257. }),
  1258. }),
  1259. );
  1260. if (!expectedQueueDelivery) {
  1261. expect(app.sendInput.mock.calls[0]?.[1]).not.toHaveProperty("queueDelivery");
  1262. }
  1263. },
  1264. );
  1265. it("guide intent 交给 Core,由 Core 决定 guide 或 queue", async () => {
  1266. const app = makeApp({
  1267. sendInput: vi.fn().mockResolvedValue({
  1268. kind: "queued",
  1269. pendingInputId: "pending-guide-fallback",
  1270. queueLength: 2,
  1271. turnId: "turn-1",
  1272. }),
  1273. runtime: { getActiveTurnInfo: vi.fn().mockReturnValue({ steerable: true }) },
  1274. });
  1275. const record = makeRecord({ app, activeAbortController: new AbortController() });
  1276. const host = makeHost(record, {
  1277. getInputRoutingMode: () => "guide",
  1278. hasQueuedDelivery: (_sessionId, delivery) => delivery === "queue",
  1279. });
  1280. await new V4CommandExecutor(host).execute(envelope("sendText", { text: "回退内容" }));
  1281. expect(app.sendInput).toHaveBeenCalledWith(
  1282. { text: "回退内容" },
  1283. expect.objectContaining({
  1284. delivery: "start_turn",
  1285. queueDelivery: "guide",
  1286. intent: expect.objectContaining({
  1287. requestedDelivery: "guide",
  1288. admittedDelivery: "guide",
  1289. }),
  1290. }),
  1291. );
  1292. });
  1293. it("goal verifier busy routing 早于 controller:进入 deferred queue,不误起第二条 turn", async () => {
  1294. const app = makeApp({
  1295. sendInput: vi.fn().mockResolvedValue({
  1296. kind: "queued",
  1297. pendingInputId: "pending-deferred-1",
  1298. queueLength: 1,
  1299. turnId: "turn-1",
  1300. }),
  1301. runtime: { getActiveTurnInfo: vi.fn().mockReturnValue(undefined) },
  1302. });
  1303. const record = makeRecord({ app });
  1304. const host = makeHost(record, { getInputRoutingMode: () => "enqueue" });
  1305. await new V4CommandExecutor(host).execute(envelope("sendText", { text: "验证期间追加" }));
  1306. expect(app.sendInput).toHaveBeenCalledWith(
  1307. { text: "验证期间追加" },
  1308. expect.objectContaining({
  1309. delivery: "start_turn",
  1310. inputId: "cmd-1",
  1311. queryId: "cmd-1",
  1312. intent: expect.objectContaining({
  1313. sourceCommandId: "cmd-1",
  1314. queueItemId: "queue_cmd-1",
  1315. requestedDelivery: "queue",
  1316. }),
  1317. }),
  1318. );
  1319. expect(app.steerTurn).not.toHaveBeenCalled();
  1320. });
  1321. it("automation 在 busy routing 入队时保留全部写工具 denylist", async () => {
  1322. const app = makeApp({
  1323. sendInput: vi.fn().mockResolvedValue({
  1324. kind: "queued",
  1325. pendingInputId: "pending-automation-1",
  1326. queueLength: 1,
  1327. turnId: "turn-1",
  1328. }),
  1329. runtime: { getActiveTurnInfo: vi.fn().mockReturnValue(undefined) },
  1330. });
  1331. const record = makeRecord({ app });
  1332. const host = makeHost(record, { getInputRoutingMode: () => "enqueue" });
  1333. await new V4CommandExecutor(host).execute(
  1334. envelope("sendText", {
  1335. text: "automation busy prompt",
  1336. automationId: "automation-1",
  1337. }),
  1338. );
  1339. expect(app.sendInput).toHaveBeenCalledWith(
  1340. { text: "automation busy prompt" },
  1341. expect.objectContaining({
  1342. automationId: "automation-1",
  1343. delivery: "start_turn",
  1344. inputId: "cmd-1",
  1345. queryId: "cmd-1",
  1346. toolDisallowlist: ["CronCreate", "CronUpdate", "CronDelete"],
  1347. }),
  1348. );
  1349. expect(app.steerTurn).not.toHaveBeenCalled();
  1350. });
  1351. it("empty/oversize admission 显式失败,不返回 accepted 后静默丢输入", async () => {
  1352. const idle = makeRecord({ app: makeApp() });
  1353. await expect(
  1354. new V4CommandExecutor(makeHost(idle)).execute(envelope("sendText", { text: " " })),
  1355. ).rejects.toMatchObject({ reasonCode: "proto.invalidPayload" });
  1356. const app = makeApp({
  1357. sendInput: vi.fn().mockResolvedValue({
  1358. kind: "rejected",
  1359. reason: "input_too_large",
  1360. }),
  1361. });
  1362. const busy = makeRecord({ app, activeAbortController: new AbortController() });
  1363. await expect(
  1364. new V4CommandExecutor(makeHost(busy)).execute(envelope("sendText", { text: "oversized" })),
  1365. ).rejects.toBeInstanceOf(V4PromptRejectedError);
  1366. expect(app.steerTurn).not.toHaveBeenCalled();
  1367. });
  1368. it("draft 会话:首条发送把 persistence 提升为 immediate", async () => {
  1369. const record = makeRecord({ persistence: "deferred" });
  1370. await new V4CommandExecutor(makeHost(record)).execute(envelope("sendText", { text: "首条" }));
  1371. expect(record.persistence).toBe("immediate");
  1372. });
  1373. it("restoreWarning 会话:拒绝新 turn(历史损坏不静默续写)", async () => {
  1374. const record = makeRecord({
  1375. restoreWarning: { message: "restore failed", type: "corrupt" },
  1376. });
  1377. await expect(
  1378. new V4CommandExecutor(makeHost(record)).execute(envelope("sendText", { text: "x" })),
  1379. ).rejects.toThrow(V4PromptRejectedError);
  1380. });
  1381. it("restoreWarning 时序自愈:进程 Registry 已有可用模型 → 清告警放行", async () => {
  1382. // 场景:app 重启后冷恢复跑在 provider registry 推送之前,record 挂上「模型
  1383. // 不可解析」告警;registry 随后到达(宿主探针判可用),发送不得再被这个
  1384. // 过期的一次性标志永久拒绝。
  1385. const app = makeApp();
  1386. const record = makeRecord({
  1387. app,
  1388. restoreWarning: {
  1389. message: "runtime model unavailable",
  1390. type: "ZCODE_RUNTIME_MODEL_UNAVAILABLE",
  1391. },
  1392. });
  1393. await new V4CommandExecutor(
  1394. makeHost(record, { hasUsableRuntimeModelTarget: () => true }),
  1395. ).execute(envelope("sendText", { text: "重启后第一条" }));
  1396. await settle();
  1397. expect(record.restoreWarning).toBeUndefined();
  1398. expect(app.sendInput).toHaveBeenCalled();
  1399. });
  1400. it("restoreWarning 保真:catalog 仍无可用模型 → 继续拒绝(不误放行)", async () => {
  1401. const record = makeRecord({
  1402. restoreWarning: {
  1403. message: "runtime model unavailable",
  1404. type: "ZCODE_RUNTIME_MODEL_UNAVAILABLE",
  1405. },
  1406. });
  1407. await expect(
  1408. new V4CommandExecutor(makeHost(record, { hasUsableRuntimeModelTarget: () => false })).execute(
  1409. envelope("sendText", { text: "x" }),
  1410. ),
  1411. ).rejects.toThrow(V4PromptRejectedError);
  1412. expect(record.restoreWarning).toBeDefined();
  1413. });
  1414. it("普通 Selection 不在 Worker Registry 时在 ACK 前拒绝并保留输入", async () => {
  1415. const app = makeApp({ listModels: () => [] });
  1416. const record = makeRecord({ app });
  1417. await expect(
  1418. new V4CommandExecutor(makeHost(record)).execute(
  1419. envelope("sendText", {
  1420. text: "使用新 Provider",
  1421. modelSelection: { providerId: "new-provider", modelId: "new-model" },
  1422. }),
  1423. ),
  1424. ).rejects.toMatchObject({ reasonCode: "modelUnavailable" });
  1425. expect(app.sendInput).not.toHaveBeenCalled();
  1426. });
  1427. it("无退回声明的 execution Selection 不在 Registry 时仍在 ACK 前拒绝", async () => {
  1428. const app = makeApp({ listModels: () => [] });
  1429. const record = makeRecord({ app });
  1430. await expect(
  1431. new V4CommandExecutor(makeHost(record)).execute(
  1432. envelope("sendText", {
  1433. text: "使用不可退回的执行模型",
  1434. modelSelection: { providerId: "new-provider", modelId: "new-model" },
  1435. modelExecution: { selectionScope: "execution" },
  1436. }),
  1437. ),
  1438. ).rejects.toMatchObject({ reasonCode: "modelUnavailable" });
  1439. expect(app.sendInput).not.toHaveBeenCalled();
  1440. });
  1441. it("带同 Provider 退回声明且退回目标可用时,execution Selection 延迟到 Core 解析", async () => {
  1442. const app = makeApp({
  1443. listModels: () => [
  1444. {
  1445. ref: { providerId: "account:bigmodel-start-plan", modelId: "glm-5" },
  1446. },
  1447. ],
  1448. });
  1449. const record = makeRecord({ app });
  1450. const selectionFallback = {
  1451. providerId: "account:bigmodel-highspeed-card",
  1452. rules: [{ reason: "highspeed_selection_unavailable" as const }],
  1453. target: { providerId: "account:bigmodel-start-plan", modelId: "glm-5" },
  1454. };
  1455. await expect(
  1456. new V4CommandExecutor(makeHost(record)).execute(
  1457. envelope("sendText", {
  1458. text: "使用可退回的执行模型",
  1459. modelSelection: {
  1460. providerId: "account:bigmodel-highspeed-card",
  1461. modelId: "missing-highspeed-model",
  1462. },
  1463. modelExecution: { selectionScope: "execution", selectionFallback },
  1464. }),
  1465. ),
  1466. ).resolves.toBeDefined();
  1467. await settle();
  1468. expect(app.sendInput).toHaveBeenCalledWith(
  1469. { text: "使用可退回的执行模型" },
  1470. expect.objectContaining({
  1471. intent: expect.objectContaining({
  1472. modelSelection: {
  1473. providerId: "account:bigmodel-highspeed-card",
  1474. modelId: "missing-highspeed-model",
  1475. },
  1476. }),
  1477. modelExecution: expect.objectContaining({
  1478. selectionScope: "execution",
  1479. selectionFallback,
  1480. }),
  1481. }),
  1482. );
  1483. });
  1484. it("Highspeed execution Selection 可用时不因退回目标缺失而拒绝", async () => {
  1485. const highspeedSelection = {
  1486. providerId: "account:bigmodel-highspeed-card",
  1487. modelId: "GLM-5.3",
  1488. };
  1489. const app = makeApp({
  1490. listModels: () => [{ ref: highspeedSelection }],
  1491. });
  1492. const record = makeRecord({ app });
  1493. await expect(
  1494. new V4CommandExecutor(makeHost(record)).execute(
  1495. envelope("sendText", {
  1496. text: "执行模型可用时继续发送",
  1497. modelSelection: highspeedSelection,
  1498. modelExecution: {
  1499. selectionScope: "execution",
  1500. selectionFallback: {
  1501. providerId: highspeedSelection.providerId,
  1502. rules: [{ reason: "highspeed_selection_unavailable" }],
  1503. target: { providerId: "missing-fallback", modelId: "missing-model" },
  1504. },
  1505. },
  1506. }),
  1507. ),
  1508. ).resolves.toBeDefined();
  1509. expect(app.sendInput).toHaveBeenCalledTimes(1);
  1510. });
  1511. it("Highspeed execution Selection 与退回目标都不在 Registry 时在 ACK 前拒绝", async () => {
  1512. const app = makeApp({ listModels: () => [] });
  1513. const record = makeRecord({ app });
  1514. await expect(
  1515. new V4CommandExecutor(makeHost(record)).execute(
  1516. envelope("sendText", {
  1517. text: "双模型都不可用时保留输入",
  1518. modelSelection: {
  1519. providerId: "account:bigmodel-highspeed-card",
  1520. modelId: "missing-highspeed-model",
  1521. },
  1522. modelExecution: {
  1523. selectionScope: "execution",
  1524. selectionFallback: {
  1525. providerId: "account:bigmodel-highspeed-card",
  1526. rules: [{ reason: "highspeed_selection_unavailable" }],
  1527. target: { providerId: "account:bigmodel-start-plan", modelId: "glm-5" },
  1528. },
  1529. },
  1530. }),
  1531. ),
  1532. ).rejects.toMatchObject({ reasonCode: "modelUnavailable" });
  1533. expect(app.sendInput).not.toHaveBeenCalled();
  1534. });
  1535. it("退回声明与 execution Provider 不一致时仍在 ACK 前拒绝", async () => {
  1536. const app = makeApp({ listModels: () => [] });
  1537. const record = makeRecord({ app });
  1538. await expect(
  1539. new V4CommandExecutor(makeHost(record)).execute(
  1540. envelope("sendText", {
  1541. text: "使用声明不一致的执行模型",
  1542. modelSelection: {
  1543. providerId: "account:bigmodel-highspeed-card",
  1544. modelId: "missing-highspeed-model",
  1545. },
  1546. modelExecution: {
  1547. selectionScope: "execution",
  1548. selectionFallback: {
  1549. providerId: "other-provider",
  1550. rules: [{ reason: "highspeed_selection_unavailable" }],
  1551. target: { providerId: "account:bigmodel-start-plan", modelId: "glm-5" },
  1552. },
  1553. },
  1554. }),
  1555. ),
  1556. ).rejects.toMatchObject({ reasonCode: "modelUnavailable" });
  1557. expect(app.sendInput).not.toHaveBeenCalled();
  1558. });
  1559. it("排队 execution Selection 仍按原模型目录做 admission 预检", async () => {
  1560. const app = makeApp({ listModels: () => [] });
  1561. const record = makeRecord({ app, activeAbortController: new AbortController() });
  1562. await expect(
  1563. new V4CommandExecutor(makeHost(record, { getInputRoutingMode: () => "enqueue" })).execute(
  1564. envelope("sendText", {
  1565. text: "排队执行模型",
  1566. modelSelection: {
  1567. providerId: "account:bigmodel-highspeed-card",
  1568. modelId: "missing-highspeed-model",
  1569. },
  1570. modelExecution: {
  1571. selectionScope: "execution",
  1572. selectionFallback: {
  1573. providerId: "account:bigmodel-highspeed-card",
  1574. rules: [{ reason: "highspeed_selection_unavailable" }],
  1575. target: { providerId: "account:bigmodel-start-plan", modelId: "glm-5" },
  1576. },
  1577. },
  1578. }),
  1579. ),
  1580. ).rejects.toMatchObject({ reasonCode: "modelUnavailable" });
  1581. expect(app.sendInput).not.toHaveBeenCalled();
  1582. });
  1583. it("turn 失败:finally 仍释放锁,legacy 广播 reason=prompt_failed", async () => {
  1584. const app = makeApp({ sendInput: vi.fn().mockRejectedValue(new Error("boom")) });
  1585. const record = makeRecord({ app });
  1586. const host = makeHost(record);
  1587. await expect(
  1588. new V4CommandExecutor(host).execute(envelope("sendText", { text: "x" })),
  1589. ).rejects.toThrow("boom");
  1590. expect(record.activeAbortController).toBeUndefined();
  1591. expect(host.legacyMutations).toEqual(["prompt_failed"]);
  1592. });
  1593. });
  1594. describe("v4 原生 sendText:软门禁(soft gate)", () => {
  1595. it("startPromptTurn 不再把 authority observer 传给 Core admission", async () => {
  1596. let capturedOptions: PromptSendInputOptions | undefined;
  1597. const app = makeApp({
  1598. sendInput: vi.fn().mockImplementation(async (_input, options) => {
  1599. capturedOptions = options as PromptSendInputOptions;
  1600. return {
  1601. completion: Promise.resolve({}),
  1602. kind: "started_turn",
  1603. turnId: "turn-1",
  1604. };
  1605. }),
  1606. });
  1607. const record = makeRecord({ app });
  1608. const host = makeHost(record);
  1609. await new V4CommandExecutor(host).execute(envelope("sendText", { text: "test" }));
  1610. await settle();
  1611. // projection observer 已移除,Core admission ACK 不等待 TurnStarted。
  1612. expect(capturedOptions!.onEvent).toBeUndefined();
  1613. expect(capturedOptions!.onTurnStartedObserved).toBeUndefined();
  1614. });
  1615. it("projection commit 永不完成时,input ACK 仍立即返回", async () => {
  1616. const turnGate = deferred<void>();
  1617. const app = makeApp({
  1618. sendInput: vi.fn().mockResolvedValue({
  1619. completion: turnGate.promise,
  1620. kind: "started_turn",
  1621. turnId: "turn-1",
  1622. }),
  1623. });
  1624. const record = makeRecord({ app });
  1625. const host = makeHost(record, {
  1626. waitForProjectionEventCommit: async () => {
  1627. await new Promise<void>(() => {});
  1628. },
  1629. });
  1630. const executing = new V4CommandExecutor(host).execute(
  1631. envelope("sendText", { text: "等待 projection commit" }),
  1632. );
  1633. await vi.waitFor(() => expect(app.sendInput).toHaveBeenCalled());
  1634. await flushMicrotasks();
  1635. // projection commit 完全不参与 admission;故意不 resolve 它。
  1636. await executing;
  1637. turnGate.resolve(undefined);
  1638. await settle();
  1639. });
  1640. it("回归:TurnStarted 后 projection 延迟时,第二条只产生一个 Core queue item", async () => {
  1641. const admissions: Array<"started" | "queued"> = [];
  1642. const runtime = {
  1643. // Bootstrap 不再查询 activeTurn;Core admission 自己持有 starting/active 状态。
  1644. getActiveTurnInfo: vi.fn(),
  1645. };
  1646. const sendInput = vi.fn().mockImplementation(async () => {
  1647. const admission = admissions.length === 0 ? "started" : "queued";
  1648. admissions.push(admission);
  1649. return admission === "started"
  1650. ? { kind: "accepted", delivery: "startNow", inputId: `cmd-${admissions.length}` }
  1651. : {
  1652. kind: "queued",
  1653. pendingInputId: "pending-stalled-followup",
  1654. queueLength: 1,
  1655. turnId: "turn-stalled-before-model",
  1656. };
  1657. });
  1658. const app = makeApp({ sendInput, runtime });
  1659. const record = makeRecord({ app });
  1660. const host = makeHost(record, {
  1661. getInputRoutingMode: () => "startNow",
  1662. waitForProjectionEventCommit: vi.fn(() => new Promise<void>(() => {})),
  1663. });
  1664. const executor = new V4CommandExecutor(host);
  1665. const first = executor.execute(envelope("sendText", { text: "触发卡住的首条" }));
  1666. await flushMicrotasks();
  1667. const second = executor.execute(envelope("sendText", { text: "卡住期间的下一条" }));
  1668. await Promise.all([first, second]);
  1669. expect(admissions).toEqual(["started", "queued"]);
  1670. expect(runtime.getActiveTurnInfo).not.toHaveBeenCalled();
  1671. });
  1672. });
  1673. describe("v4 原生 sendText:held choice 裁决(catalog B06/B07)", () => {
  1674. it("held(routing=choice)缺 disposition → 拒绝 heldQueueDispositionRequired", async () => {
  1675. const app = makeApp({ clearQueueItems: vi.fn().mockResolvedValue(0) });
  1676. const record = makeRecord({ app });
  1677. const host = makeHost(record, { getInputRoutingMode: () => "choice" });
  1678. await expect(
  1679. new V4CommandExecutor(host).execute(envelope("sendText", { text: "x" })),
  1680. ).rejects.toMatchObject({ reasonCode: "heldQueueDispositionRequired" });
  1681. expect(app.sendInput).not.toHaveBeenCalled();
  1682. expect(app.clearQueueItems).not.toHaveBeenCalled();
  1683. });
  1684. it("held + clearQueueAndSend → 先清空 queue 再起 turn", async () => {
  1685. const calls: string[] = [];
  1686. const app = makeApp({
  1687. clearQueueItems: vi.fn().mockImplementation(async () => {
  1688. calls.push("clear");
  1689. return 2;
  1690. }),
  1691. sendInput: vi.fn().mockImplementation(async (_input, options) => {
  1692. calls.push("send");
  1693. return {
  1694. completion: Promise.resolve({}),
  1695. kind: "started_turn",
  1696. turnId: "turn-held-clear",
  1697. };
  1698. }),
  1699. });
  1700. const record = makeRecord({ app });
  1701. const host = makeHost(record, { getInputRoutingMode: () => "choice" });
  1702. await new V4CommandExecutor(host).execute(
  1703. envelope("sendText", { text: "新问题", heldQueueDisposition: "clearQueueAndSend" }),
  1704. );
  1705. await settle();
  1706. expect(calls).toEqual(["clear", "send"]);
  1707. });
  1708. it("held + startNow + clearQueueAndSend → 仍先清空 queue 再起 turn", async () => {
  1709. const calls: string[] = [];
  1710. const app = makeApp({
  1711. clearQueueItems: vi.fn().mockImplementation(async () => {
  1712. calls.push("clear");
  1713. return 2;
  1714. }),
  1715. runtime: {
  1716. acquireForegroundPromotionLease: vi.fn().mockReturnValue({ kind: "acquired" }),
  1717. getActiveForegroundExecutionId: vi.fn().mockReturnValue(undefined),
  1718. releaseForegroundPromotionLease: vi.fn().mockReturnValue(true),
  1719. stopActiveForegroundExecution: vi.fn().mockReturnValue({ kind: "idle" }),
  1720. },
  1721. sendInput: vi.fn().mockImplementation(async (_input, options) => {
  1722. calls.push("send");
  1723. return {
  1724. completion: Promise.resolve({}),
  1725. kind: "started_turn",
  1726. turnId: "turn-held-start-now",
  1727. };
  1728. }),
  1729. });
  1730. const record = makeRecord({ app });
  1731. const host = makeHost(record, {
  1732. getInputRoutingMode: () => "choice",
  1733. getQueueLength: () => 2,
  1734. getQueueItem: (_sessionId, queueItemId) => ({ queueItemId }) as never,
  1735. });
  1736. await new V4CommandExecutor(host).execute(
  1737. envelope("sendText", {
  1738. text: "新问题",
  1739. requestedDelivery: "startNow",
  1740. heldQueueDisposition: "clearQueueAndSend",
  1741. expectedHeldQueueItemIds: ["q-1", "q-2"],
  1742. }),
  1743. );
  1744. await settle();
  1745. expect(calls).toEqual(["clear", "send"]);
  1746. });
  1747. it("held + startNow 的 queue ids 过期时拒绝清空和启动 turn", async () => {
  1748. const app = makeApp({
  1749. clearQueueItems: vi.fn().mockResolvedValue(0),
  1750. runtime: {
  1751. acquireForegroundPromotionLease: vi.fn().mockReturnValue({ kind: "acquired" }),
  1752. releaseForegroundPromotionLease: vi.fn().mockReturnValue(true),
  1753. },
  1754. });
  1755. const record = makeRecord({ app });
  1756. const host = makeHost(record, {
  1757. getInputRoutingMode: () => "choice",
  1758. getQueueLength: () => 2,
  1759. getQueueItem: (_sessionId, queueItemId) =>
  1760. queueItemId === "q-1" ? ({ queueItemId } as never) : null,
  1761. });
  1762. await expect(
  1763. new V4CommandExecutor(host).execute(
  1764. envelope("sendText", {
  1765. text: "新问题",
  1766. requestedDelivery: "startNow",
  1767. heldQueueDisposition: "clearQueueAndSend",
  1768. expectedHeldQueueItemIds: ["q-1"],
  1769. }),
  1770. ),
  1771. ).rejects.toMatchObject({ reasonCode: "guard.heldQueueConfirmationStale" });
  1772. expect(app.clearQueueItems).not.toHaveBeenCalled();
  1773. expect(app.sendInput).not.toHaveBeenCalled();
  1774. });
  1775. it("held + keepQueueAndSend → 不清 queue 直接起 turn", async () => {
  1776. const app = makeApp({ clearQueueItems: vi.fn().mockResolvedValue(0) });
  1777. const record = makeRecord({ app });
  1778. const host = makeHost(record, { getInputRoutingMode: () => "choice" });
  1779. await new V4CommandExecutor(host).execute(
  1780. envelope("sendText", { text: "新问题", heldQueueDisposition: "keepQueueAndSend" }),
  1781. );
  1782. await settle();
  1783. expect(app.clearQueueItems).not.toHaveBeenCalled();
  1784. expect(app.sendInput).toHaveBeenCalled();
  1785. });
  1786. it("held 确认绑定 queueItemId 集合:跨端增删后拒绝旧确认且不清空/发送", async () => {
  1787. const app = makeApp({ clearQueueItems: vi.fn().mockResolvedValue(0) });
  1788. const record = makeRecord({ app });
  1789. const getQueueItem = vi.fn((_sessionId: string, queueItemId: string) =>
  1790. queueItemId === "q-1" ? ({ queueItemId } as never) : null,
  1791. );
  1792. const host = makeHost(record, {
  1793. getInputRoutingMode: () => "choice",
  1794. getQueueLength: () => 2,
  1795. getQueueItem,
  1796. });
  1797. await expect(
  1798. new V4CommandExecutor(host).execute(
  1799. envelope("sendText", {
  1800. text: "新问题",
  1801. heldQueueDisposition: "clearQueueAndSend",
  1802. expectedHeldQueueItemIds: ["q-1"],
  1803. }),
  1804. ),
  1805. ).rejects.toMatchObject({ reasonCode: "guard.heldQueueConfirmationStale" });
  1806. expect(app.clearQueueItems).not.toHaveBeenCalled();
  1807. expect(app.sendInput).not.toHaveBeenCalled();
  1808. });
  1809. it("held 确认的 ID 集合未变化时允许执行;重排不使确认失效", async () => {
  1810. const app = makeApp({ clearQueueItems: vi.fn().mockResolvedValue(2) });
  1811. const record = makeRecord({ app });
  1812. const host = makeHost(record, {
  1813. getInputRoutingMode: () => "choice",
  1814. getQueueLength: () => 2,
  1815. getQueueItem: (_sessionId, queueItemId) => ({ queueItemId }) as never,
  1816. });
  1817. await new V4CommandExecutor(host).execute(
  1818. envelope("sendText", {
  1819. text: "新问题",
  1820. heldQueueDisposition: "clearQueueAndSend",
  1821. expectedHeldQueueItemIds: ["q-2", "q-1"],
  1822. }),
  1823. );
  1824. await settle();
  1825. expect(app.clearQueueItems).toHaveBeenCalledTimes(1);
  1826. expect(app.sendInput).toHaveBeenCalledTimes(1);
  1827. });
  1828. it("非 held(routing=startNow)缺 disposition → 正常起 turn(不误拒)", async () => {
  1829. const app = makeApp({ clearQueueItems: vi.fn().mockResolvedValue(0) });
  1830. const record = makeRecord({ app });
  1831. const host = makeHost(record, { getInputRoutingMode: () => "startNow" });
  1832. await new V4CommandExecutor(host).execute(envelope("sendText", { text: "x" }));
  1833. await settle();
  1834. expect(app.sendInput).toHaveBeenCalled();
  1835. expect(app.clearQueueItems).not.toHaveBeenCalled();
  1836. });
  1837. });
  1838. describe("v4 原生 stop", () => {
  1839. it("active turn + active goal:先 pause goal 再 abort(barrier 顺序)", async () => {
  1840. const calls: string[] = [];
  1841. const app = makeApp({
  1842. readTarget: vi.fn().mockResolvedValue({ targetID: "g1", status: "active" }),
  1843. updateTargetStatus: vi.fn().mockImplementation(async () => {
  1844. calls.push("pause");
  1845. return { targetID: "g1", status: "paused" };
  1846. }),
  1847. });
  1848. const controller = new AbortController();
  1849. controller.signal.addEventListener("abort", () => calls.push("abort"));
  1850. const record = makeRecord({ app, activeAbortController: controller });
  1851. const host = makeHost(record);
  1852. await new V4CommandExecutor(host).execute(envelope("stop", {}));
  1853. expect(calls).toEqual(["pause", "abort"]);
  1854. expect(host.legacyMutations).toEqual(["session_stop_goal_paused"]);
  1855. });
  1856. it("无 active turn:不触碰 goal,abort 为 noop", async () => {
  1857. const app = makeApp();
  1858. const record = makeRecord({ app });
  1859. const host = makeHost(record);
  1860. await new V4CommandExecutor(host).execute(envelope("stop", {}));
  1861. expect(app.readTarget).not.toHaveBeenCalled();
  1862. expect(host.legacyMutations).toEqual([]);
  1863. });
  1864. it("pause goal 抛错:不阻断 abort(stop 必须成功)", async () => {
  1865. const app = makeApp({
  1866. readTarget: vi.fn().mockResolvedValue({ targetID: "g1", status: "active" }),
  1867. updateTargetStatus: vi.fn().mockRejectedValue(new Error("verifier busy")),
  1868. });
  1869. const controller = new AbortController();
  1870. const record = makeRecord({ app, activeAbortController: controller });
  1871. await new V4CommandExecutor(makeHost(record)).execute(envelope("stop", {}));
  1872. expect(controller.signal.aborted).toBe(true);
  1873. });
  1874. it("goal verifier:先取消 runtime 前台执行,再暂停 goal 并关闭外层窗口", async () => {
  1875. const calls: string[] = [];
  1876. const setQueueAutoDrain = vi.fn().mockImplementation(async () => {
  1877. calls.push("hold-queue");
  1878. });
  1879. const stopActiveForegroundExecution = vi.fn().mockImplementation(() => {
  1880. calls.push("runtime-abort");
  1881. return { kind: "stopped", foregroundExecutionId: "foreground-1" };
  1882. });
  1883. const app = makeApp({
  1884. runtime: { stopActiveForegroundExecution },
  1885. setQueueAutoDrain,
  1886. readTarget: vi.fn().mockResolvedValue({ targetID: "g1", status: "active" }),
  1887. updateTargetStatus: vi.fn().mockImplementation(async () => {
  1888. calls.push("pause");
  1889. return { targetID: "g1", status: "paused" };
  1890. }),
  1891. });
  1892. const controller = new AbortController();
  1893. controller.signal.addEventListener("abort", () => calls.push("outer-abort"));
  1894. const record = makeRecord({ app, activeAbortController: controller });
  1895. const info = vi.fn();
  1896. await new V4CommandExecutor(
  1897. makeHost(record, {
  1898. getQueueLength: () => 1,
  1899. logger: { info } as never,
  1900. }),
  1901. ).execute(envelope("stop", { expectedForegroundExecutionId: "foreground-1" }));
  1902. expect(stopActiveForegroundExecution).toHaveBeenCalledWith({
  1903. expectedForegroundExecutionId: "foreground-1",
  1904. reason: "v4 session stopped",
  1905. });
  1906. expect(setQueueAutoDrain).toHaveBeenCalledWith(false);
  1907. expect(calls).toEqual(["runtime-abort", "outer-abort", "hold-queue", "pause"]);
  1908. expect(info).toHaveBeenCalledWith("v4 stop foreground execution inspected", {
  1909. activeForegroundExecutionId: "foreground-1",
  1910. event: "v4.stop.foreground_execution_inspected",
  1911. expectedForegroundExecutionId: "foreground-1",
  1912. module: "bootstrap.zcode_protocol_v4.commands",
  1913. runtimeStopKind: "stopped",
  1914. sessionId: "s1",
  1915. });
  1916. });
  1917. it("迟到 Stop 的 execution id 已变化:返回 noop,且不误杀新执行", async () => {
  1918. const stopActiveForegroundExecution = vi.fn().mockReturnValue({
  1919. kind: "mismatch",
  1920. activeForegroundExecutionId: "foreground-2",
  1921. });
  1922. const app = makeApp({ runtime: { stopActiveForegroundExecution } });
  1923. const controller = new AbortController();
  1924. const record = makeRecord({ app, activeAbortController: controller });
  1925. await expect(
  1926. new V4CommandExecutor(makeHost(record)).execute(
  1927. envelope("stop", { expectedForegroundExecutionId: "foreground-1" }),
  1928. ),
  1929. ).rejects.toMatchObject({ reasonCode: "guard.stopTargetChanged" });
  1930. expect(controller.signal.aborted).toBe(false);
  1931. expect(app.readTarget).not.toHaveBeenCalled();
  1932. });
  1933. });
  1934. describe("supports 分流", () => {
  1935. it("协议命令全部原生(回落面清零);未知命令不 supports", () => {
  1936. const executor = new V4CommandExecutor(makeHost(makeRecord()));
  1937. // 与 packages/shared/src/zcode-protocol-v4/command.ts 的 payload map 同步维护。
  1938. const allCommands = [
  1939. "createSession",
  1940. "sendText",
  1941. "sendGoalCommand",
  1942. "stop",
  1943. "compact",
  1944. "forkAssistant",
  1945. "applyFileRewind",
  1946. "editUserQuery",
  1947. "retryTurn",
  1948. "setAssistantFeedback",
  1949. "setHighspeedMetrics",
  1950. "sendQueuedNow",
  1951. "editQueueItem",
  1952. "applyQueueItemsConfig",
  1953. "lockQueueItemEdit",
  1954. "releaseQueueItemEdit",
  1955. "reorderQueueItem",
  1956. "deleteQueueItem",
  1957. "setAutoDrain",
  1958. "resolveInteraction",
  1959. "snoozeInteractionAutoResolution",
  1960. "switchModelConfig",
  1961. "setFollowupMode",
  1962. "resumeGoal",
  1963. "cancelBackgroundWork",
  1964. "renameSession",
  1965. "deleteSession",
  1966. ] as const;
  1967. for (const command of allCommands) {
  1968. expect(executor.supports(command), command).toBe(true);
  1969. }
  1970. expect(executor.supports("unknownCommand" as never)).toBe(false);
  1971. });
  1972. });