v4-native-commands.test.ts 72 KB

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