v4-native-commands.test.ts 72 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090
  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 inputId 时不恢复任务身份", 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: "ordinary prompt" }),
  952. commandId: "automation-other-task:manual:forged-run",
  953. });
  954. await settle();
  955. expect(app.sendInput.mock.calls[0]?.[1]).not.toHaveProperty("automationId");
  956. expect(app.sendInput.mock.calls[0]?.[1]).not.toHaveProperty("toolDisallowlist");
  957. expect(record.activeAutomationId).toBeUndefined();
  958. });
  959. it("cron task 普通 sendText 隐藏 CronCreate 但不进入 automation 派发态", async () => {
  960. const app = makeApp();
  961. const record = makeRecord({ app });
  962. const host = makeHost(record);
  963. await new V4CommandExecutor(host).execute(
  964. envelope("sendText", {
  965. text: "拒绝删除旧任务后继续设置新提醒",
  966. toolDisallowlist: ["CronCreate"],
  967. }),
  968. );
  969. await settle();
  970. expect(app.sendInput.mock.calls[0]?.[1]).toEqual(
  971. expect.objectContaining({ toolDisallowlist: ["CronCreate"] }),
  972. );
  973. expect(record.activeAutomationId).toBeUndefined();
  974. });
  975. it("运行中会话:Bootstrap 仍走 Core admission,由 Core 返回 queue receipt", async () => {
  976. const app = makeApp({
  977. sendInput: vi.fn().mockResolvedValue({
  978. kind: "queued",
  979. pendingInputId: "pending-followup",
  980. queueLength: 1,
  981. turnId: "turn-1",
  982. }),
  983. });
  984. const record = makeRecord({ app, activeAbortController: new AbortController() });
  985. const host = makeHost(record);
  986. await new V4CommandExecutor(host).execute(
  987. envelope("sendText", {
  988. text: "追加",
  989. modelSelection: {
  990. providerId: "provider-b",
  991. modelId: "model-b",
  992. options: { reasoningLevel: "high" },
  993. },
  994. mode: "plan",
  995. }),
  996. );
  997. expect(app.sendInput).toHaveBeenCalledWith(
  998. { text: "追加" },
  999. expect.objectContaining({
  1000. delivery: "start_turn",
  1001. inputId: "cmd-1",
  1002. intent: expect.objectContaining({
  1003. sourceCommandId: "cmd-1",
  1004. queueItemId: "queue_cmd-1",
  1005. clientId: "client-test",
  1006. modelSelection: {
  1007. providerId: "provider-b",
  1008. modelId: "model-b",
  1009. options: { reasoningLevel: "high" },
  1010. },
  1011. mode: "build",
  1012. planEnabled: true,
  1013. }),
  1014. }),
  1015. );
  1016. expect(app.steerTurn).not.toHaveBeenCalled();
  1017. });
  1018. // 立即发送是用户的新指令:实际抢占旧执行后,输入仍是普通用户消息,与空闲时发送相同。
  1019. it.each([
  1020. { stopKind: "stopped", attachmentMime: undefined },
  1021. { stopKind: "idle", attachmentMime: undefined },
  1022. { stopKind: "stopped", attachmentMime: "text/plain" },
  1023. ])(
  1024. "startNow 抢占后仍是普通用户输入:$stopKind / $attachmentMime",
  1025. async ({ stopKind, attachmentMime }) => {
  1026. const app = makeApp({
  1027. runtime: {
  1028. acquireForegroundPromotionLease: vi.fn().mockReturnValue({ kind: "acquired" }),
  1029. getActiveForegroundExecutionId: vi.fn().mockReturnValue(undefined),
  1030. releaseForegroundPromotionLease: vi.fn().mockReturnValue(true),
  1031. stopActiveForegroundExecution: vi
  1032. .fn()
  1033. .mockReturnValue(
  1034. stopKind === "stopped"
  1035. ? { kind: "stopped", foregroundExecutionId: "foreground-1" }
  1036. : { kind: "idle" },
  1037. ),
  1038. },
  1039. });
  1040. // UI 即使仍显示 busy,Core 的 idle 回执也不能被猜成一次抢占。
  1041. const host = makeHost(makeRecord({ app }), { getInputRoutingMode: () => "enqueue" });
  1042. await new V4CommandExecutor(host).execute(
  1043. envelope("sendText", {
  1044. text: "先处理这个短任务",
  1045. requestedDelivery: "startNow",
  1046. ...(attachmentMime
  1047. ? {
  1048. attachments: [
  1049. { ref: "/tmp/note", fileName: "note", mime: attachmentMime, bytes: 9 },
  1050. ],
  1051. }
  1052. : {}),
  1053. }),
  1054. );
  1055. expect(app.sendInput).toHaveBeenCalledTimes(1);
  1056. const [input, options] = app.sendInput.mock.calls[0]!;
  1057. expect(input.text).toBe("先处理这个短任务");
  1058. expect(options).not.toHaveProperty("inputPresentation");
  1059. expect(options).toMatchObject({
  1060. inputId: "cmd-1",
  1061. requireIdle: true,
  1062. intent: { requestedDelivery: "startNow" },
  1063. });
  1064. },
  1065. );
  1066. it("抢占后的 startNow 经真实 input facade 以普通用户输入进入新轮 Core admission", async () => {
  1067. const runtime = {
  1068. acquireForegroundPromotionLease: vi.fn().mockReturnValue({ kind: "acquired" }),
  1069. getActiveForegroundExecutionId: vi.fn().mockReturnValue(undefined),
  1070. releaseForegroundPromotionLease: vi.fn().mockReturnValue(true),
  1071. stopActiveForegroundExecution: vi
  1072. .fn()
  1073. .mockReturnValue({ kind: "stopped", foregroundExecutionId: "foreground-1" }),
  1074. admitPrompt: vi
  1075. .fn()
  1076. .mockResolvedValue({ kind: "started", turnId: "turn-2", completion: Promise.resolve({}) }),
  1077. };
  1078. const facade = createInputFacade({
  1079. logger: { warn: vi.fn() } as never,
  1080. prepareUserExecutionBoundary: async () => {},
  1081. runtime: runtime as never,
  1082. sessionId: "s1" as never,
  1083. traceContext: { traceId: "trace-1" } as never,
  1084. });
  1085. const app = makeApp({ runtime, sendInput: facade.sendInput });
  1086. await new V4CommandExecutor(makeHost(makeRecord({ app }))).execute(
  1087. envelope("sendText", { text: "短任务", requestedDelivery: "startNow" }),
  1088. );
  1089. expect(runtime.admitPrompt).toHaveBeenCalledWith(
  1090. "短任务",
  1091. undefined,
  1092. expect.objectContaining({
  1093. inputId: "cmd-1",
  1094. requireIdle: true,
  1095. delivery: "start_turn",
  1096. }),
  1097. );
  1098. expect(runtime.admitPrompt.mock.calls[0]![2]).not.toHaveProperty("inputPresentation");
  1099. });
  1100. it("运行中 startNow:原子抢占后直接启动新 turn,不创建 queue item", async () => {
  1101. const controller = new AbortController();
  1102. const acquireForegroundPromotionLease = vi.fn().mockReturnValue({ kind: "acquired" });
  1103. const releaseForegroundPromotionLease = vi.fn().mockReturnValue(true);
  1104. const app = makeApp({
  1105. runtime: {
  1106. acquireForegroundPromotionLease,
  1107. getActiveForegroundExecutionId: vi.fn().mockReturnValue(undefined),
  1108. releaseForegroundPromotionLease,
  1109. stopActiveForegroundExecution: vi.fn().mockReturnValue({ kind: "idle" }),
  1110. },
  1111. });
  1112. const record = makeRecord({ app, activeAbortController: controller });
  1113. controller.signal.addEventListener("abort", () => {
  1114. record.activeAbortController = undefined;
  1115. });
  1116. await new V4CommandExecutor(makeHost(record)).execute(
  1117. envelope("sendText", { text: "现在执行", requestedDelivery: "startNow" }),
  1118. );
  1119. expect(acquireForegroundPromotionLease).toHaveBeenCalledWith({
  1120. leaseId: "send-now:cmd-1",
  1121. mode: "after-current",
  1122. promotedInputId: "cmd-1",
  1123. });
  1124. expect(app.sendInput).toHaveBeenCalledWith(
  1125. { text: "现在执行" },
  1126. expect.objectContaining({
  1127. requireIdle: true,
  1128. intent: expect.objectContaining({
  1129. admittedDelivery: "startNow",
  1130. requestedDelivery: "startNow",
  1131. sourceCommandId: "cmd-1",
  1132. }),
  1133. }),
  1134. );
  1135. expect(app.steerTurn).not.toHaveBeenCalled();
  1136. expect(releaseForegroundPromotionLease).toHaveBeenCalledWith("send-now:cmd-1");
  1137. });
  1138. it("伪造 automation inputId 排队时仍保持普通用户轮", async () => {
  1139. const app = makeApp({
  1140. sendInput: vi.fn().mockResolvedValue({
  1141. kind: "queued",
  1142. pendingInputId: "pending-ordinary-followup",
  1143. queueLength: 1,
  1144. turnId: "turn-1",
  1145. }),
  1146. });
  1147. const record = makeRecord({ app, activeAbortController: new AbortController() });
  1148. const host = makeHost(record);
  1149. await new V4CommandExecutor(host).execute({
  1150. ...envelope("sendText", { text: "ordinary followup" }),
  1151. commandId: "automation-other-task:manual:forged-run",
  1152. });
  1153. expect(app.sendInput).toHaveBeenCalledWith(
  1154. { text: "ordinary followup" },
  1155. expect.objectContaining({
  1156. delivery: "start_turn",
  1157. inputId: "automation-other-task:manual:forged-run",
  1158. }),
  1159. );
  1160. expect(app.sendInput.mock.calls[0]?.[1]).not.toHaveProperty("automationId");
  1161. expect(app.sendInput.mock.calls[0]?.[1]).not.toHaveProperty("toolDisallowlist");
  1162. expect(app.steerTurn).not.toHaveBeenCalled();
  1163. });
  1164. it.each([
  1165. "account:bigmodel-start-plan/glm-5",
  1166. "custom-openai/gpt-5",
  1167. "anthropic/claude-sonnet-4-5",
  1168. ])("guide eligible:running + 无普通 queue 时模型 %s 按 guide 投递", async (model) => {
  1169. const app = makeApp({
  1170. sendInput: vi.fn().mockResolvedValue({
  1171. kind: "queued",
  1172. pendingInputId: "pending-guide",
  1173. queueLength: 1,
  1174. turnId: "turn-1",
  1175. }),
  1176. getModel: vi.fn().mockReturnValue(model),
  1177. runtime: { getActiveTurnInfo: vi.fn().mockReturnValue({ steerable: true }) },
  1178. });
  1179. const record = makeRecord({ app, activeAbortController: new AbortController() });
  1180. const host = makeHost(record, {
  1181. getInputRoutingMode: () => "guide",
  1182. hasQueuedDelivery: () => false,
  1183. });
  1184. const [providerId, ...modelSegments] = model.split("/");
  1185. await new V4CommandExecutor(host).execute(
  1186. envelope("sendText", {
  1187. text: "引导当前工作",
  1188. modelSelection: { providerId, modelId: modelSegments.join("/") },
  1189. mode: "build",
  1190. }),
  1191. );
  1192. expect(app.sendInput).toHaveBeenCalledWith(
  1193. { text: "引导当前工作" },
  1194. expect.objectContaining({
  1195. delivery: "start_turn",
  1196. queueDelivery: "guide",
  1197. intent: expect.objectContaining({
  1198. requestedDelivery: "guide",
  1199. admittedDelivery: "guide",
  1200. modelSelection: { providerId, modelId: modelSegments.join("/") },
  1201. mode: "build",
  1202. }),
  1203. }),
  1204. );
  1205. expect(app.getModel).not.toHaveBeenCalled();
  1206. });
  1207. it.each([
  1208. {
  1209. routingMode: "enqueue" as const,
  1210. requestedDelivery: "guide" as const,
  1211. expectedQueueDelivery: "guide" as const,
  1212. },
  1213. {
  1214. routingMode: "guide" as const,
  1215. requestedDelivery: "queue" as const,
  1216. expectedQueueDelivery: undefined,
  1217. },
  1218. ])(
  1219. "one-message $requestedDelivery overrides session routing $routingMode",
  1220. async ({ routingMode, requestedDelivery, expectedQueueDelivery }) => {
  1221. const app = makeApp({
  1222. sendInput: vi.fn().mockResolvedValue({
  1223. kind: "queued",
  1224. pendingInputId: "pending-delivery-override",
  1225. queueLength: 1,
  1226. turnId: "turn-1",
  1227. }),
  1228. });
  1229. const record = makeRecord({ app, activeAbortController: new AbortController() });
  1230. const host = makeHost(record, { getInputRoutingMode: () => routingMode });
  1231. await new V4CommandExecutor(host).execute(
  1232. envelope("sendText", { text: "只反转这一条", requestedDelivery }),
  1233. );
  1234. expect(app.sendInput).toHaveBeenCalledWith(
  1235. { text: "只反转这一条" },
  1236. expect.objectContaining({
  1237. delivery: "start_turn",
  1238. ...(expectedQueueDelivery ? { queueDelivery: expectedQueueDelivery } : {}),
  1239. intent: expect.objectContaining({
  1240. requestedDelivery,
  1241. admittedDelivery: requestedDelivery,
  1242. }),
  1243. }),
  1244. );
  1245. if (!expectedQueueDelivery) {
  1246. expect(app.sendInput.mock.calls[0]?.[1]).not.toHaveProperty("queueDelivery");
  1247. }
  1248. },
  1249. );
  1250. it("guide intent 交给 Core,由 Core 决定 guide 或 queue", async () => {
  1251. const app = makeApp({
  1252. sendInput: vi.fn().mockResolvedValue({
  1253. kind: "queued",
  1254. pendingInputId: "pending-guide-fallback",
  1255. queueLength: 2,
  1256. turnId: "turn-1",
  1257. }),
  1258. runtime: { getActiveTurnInfo: vi.fn().mockReturnValue({ steerable: true }) },
  1259. });
  1260. const record = makeRecord({ app, activeAbortController: new AbortController() });
  1261. const host = makeHost(record, {
  1262. getInputRoutingMode: () => "guide",
  1263. hasQueuedDelivery: (_sessionId, delivery) => delivery === "queue",
  1264. });
  1265. await new V4CommandExecutor(host).execute(envelope("sendText", { text: "回退内容" }));
  1266. expect(app.sendInput).toHaveBeenCalledWith(
  1267. { text: "回退内容" },
  1268. expect.objectContaining({
  1269. delivery: "start_turn",
  1270. queueDelivery: "guide",
  1271. intent: expect.objectContaining({
  1272. requestedDelivery: "guide",
  1273. admittedDelivery: "guide",
  1274. }),
  1275. }),
  1276. );
  1277. });
  1278. it("goal verifier busy routing 早于 controller:进入 deferred queue,不误起第二条 turn", async () => {
  1279. const app = makeApp({
  1280. sendInput: vi.fn().mockResolvedValue({
  1281. kind: "queued",
  1282. pendingInputId: "pending-deferred-1",
  1283. queueLength: 1,
  1284. turnId: "turn-1",
  1285. }),
  1286. runtime: { getActiveTurnInfo: vi.fn().mockReturnValue(undefined) },
  1287. });
  1288. const record = makeRecord({ app });
  1289. const host = makeHost(record, { getInputRoutingMode: () => "enqueue" });
  1290. await new V4CommandExecutor(host).execute(envelope("sendText", { text: "验证期间追加" }));
  1291. expect(app.sendInput).toHaveBeenCalledWith(
  1292. { text: "验证期间追加" },
  1293. expect.objectContaining({
  1294. delivery: "start_turn",
  1295. inputId: "cmd-1",
  1296. queryId: "cmd-1",
  1297. intent: expect.objectContaining({
  1298. sourceCommandId: "cmd-1",
  1299. queueItemId: "queue_cmd-1",
  1300. requestedDelivery: "queue",
  1301. }),
  1302. }),
  1303. );
  1304. expect(app.steerTurn).not.toHaveBeenCalled();
  1305. });
  1306. it("automation 在 busy routing 入队时保留全部写工具 denylist", async () => {
  1307. const app = makeApp({
  1308. sendInput: vi.fn().mockResolvedValue({
  1309. kind: "queued",
  1310. pendingInputId: "pending-automation-1",
  1311. queueLength: 1,
  1312. turnId: "turn-1",
  1313. }),
  1314. runtime: { getActiveTurnInfo: vi.fn().mockReturnValue(undefined) },
  1315. });
  1316. const record = makeRecord({ app });
  1317. const host = makeHost(record, { getInputRoutingMode: () => "enqueue" });
  1318. await new V4CommandExecutor(host).execute(
  1319. envelope("sendText", {
  1320. text: "automation busy prompt",
  1321. automationId: "automation-1",
  1322. }),
  1323. );
  1324. expect(app.sendInput).toHaveBeenCalledWith(
  1325. { text: "automation busy prompt" },
  1326. expect.objectContaining({
  1327. automationId: "automation-1",
  1328. delivery: "start_turn",
  1329. inputId: "cmd-1",
  1330. queryId: "cmd-1",
  1331. toolDisallowlist: ["CronCreate", "CronUpdate", "CronDelete"],
  1332. }),
  1333. );
  1334. expect(app.steerTurn).not.toHaveBeenCalled();
  1335. });
  1336. it("empty/oversize admission 显式失败,不返回 accepted 后静默丢输入", async () => {
  1337. const idle = makeRecord({ app: makeApp() });
  1338. await expect(
  1339. new V4CommandExecutor(makeHost(idle)).execute(envelope("sendText", { text: " " })),
  1340. ).rejects.toMatchObject({ reasonCode: "proto.invalidPayload" });
  1341. const app = makeApp({
  1342. sendInput: vi.fn().mockResolvedValue({
  1343. kind: "rejected",
  1344. reason: "input_too_large",
  1345. }),
  1346. });
  1347. const busy = makeRecord({ app, activeAbortController: new AbortController() });
  1348. await expect(
  1349. new V4CommandExecutor(makeHost(busy)).execute(envelope("sendText", { text: "oversized" })),
  1350. ).rejects.toBeInstanceOf(V4PromptRejectedError);
  1351. expect(app.steerTurn).not.toHaveBeenCalled();
  1352. });
  1353. it("draft 会话:首条发送把 persistence 提升为 immediate", async () => {
  1354. const record = makeRecord({ persistence: "deferred" });
  1355. await new V4CommandExecutor(makeHost(record)).execute(envelope("sendText", { text: "首条" }));
  1356. expect(record.persistence).toBe("immediate");
  1357. });
  1358. it("restoreWarning 会话:拒绝新 turn(历史损坏不静默续写)", async () => {
  1359. const record = makeRecord({
  1360. restoreWarning: { message: "restore failed", type: "corrupt" },
  1361. });
  1362. await expect(
  1363. new V4CommandExecutor(makeHost(record)).execute(envelope("sendText", { text: "x" })),
  1364. ).rejects.toThrow(V4PromptRejectedError);
  1365. });
  1366. it("restoreWarning 时序自愈:进程 Registry 已有可用模型 → 清告警放行", async () => {
  1367. // 场景:app 重启后冷恢复跑在 provider registry 推送之前,record 挂上「模型
  1368. // 不可解析」告警;registry 随后到达(宿主探针判可用),发送不得再被这个
  1369. // 过期的一次性标志永久拒绝。
  1370. const app = makeApp();
  1371. const record = makeRecord({
  1372. app,
  1373. restoreWarning: {
  1374. message: "runtime model unavailable",
  1375. type: "ZCODE_RUNTIME_MODEL_UNAVAILABLE",
  1376. },
  1377. });
  1378. await new V4CommandExecutor(
  1379. makeHost(record, { hasUsableRuntimeModelTarget: () => true }),
  1380. ).execute(envelope("sendText", { text: "重启后第一条" }));
  1381. await settle();
  1382. expect(record.restoreWarning).toBeUndefined();
  1383. expect(app.sendInput).toHaveBeenCalled();
  1384. });
  1385. it("restoreWarning 保真:catalog 仍无可用模型 → 继续拒绝(不误放行)", async () => {
  1386. const record = makeRecord({
  1387. restoreWarning: {
  1388. message: "runtime model unavailable",
  1389. type: "ZCODE_RUNTIME_MODEL_UNAVAILABLE",
  1390. },
  1391. });
  1392. await expect(
  1393. new V4CommandExecutor(makeHost(record, { hasUsableRuntimeModelTarget: () => false })).execute(
  1394. envelope("sendText", { text: "x" }),
  1395. ),
  1396. ).rejects.toThrow(V4PromptRejectedError);
  1397. expect(record.restoreWarning).toBeDefined();
  1398. });
  1399. it("普通 Selection 不在 Worker Registry 时在 ACK 前拒绝并保留输入", async () => {
  1400. const app = makeApp({ listModels: () => [] });
  1401. const record = makeRecord({ app });
  1402. await expect(
  1403. new V4CommandExecutor(makeHost(record)).execute(
  1404. envelope("sendText", {
  1405. text: "使用新 Provider",
  1406. modelSelection: { providerId: "new-provider", modelId: "new-model" },
  1407. }),
  1408. ),
  1409. ).rejects.toMatchObject({ reasonCode: "modelUnavailable" });
  1410. expect(app.sendInput).not.toHaveBeenCalled();
  1411. });
  1412. it("无退回声明的 execution Selection 不在 Registry 时仍在 ACK 前拒绝", async () => {
  1413. const app = makeApp({ listModels: () => [] });
  1414. const record = makeRecord({ app });
  1415. await expect(
  1416. new V4CommandExecutor(makeHost(record)).execute(
  1417. envelope("sendText", {
  1418. text: "使用不可退回的执行模型",
  1419. modelSelection: { providerId: "new-provider", modelId: "new-model" },
  1420. modelExecution: { selectionScope: "execution" },
  1421. }),
  1422. ),
  1423. ).rejects.toMatchObject({ reasonCode: "modelUnavailable" });
  1424. expect(app.sendInput).not.toHaveBeenCalled();
  1425. });
  1426. it("带同 Provider 退回声明且退回目标可用时,execution Selection 延迟到 Core 解析", async () => {
  1427. const app = makeApp({
  1428. listModels: () => [
  1429. {
  1430. ref: { providerId: "account:bigmodel-start-plan", modelId: "glm-5" },
  1431. },
  1432. ],
  1433. });
  1434. const record = makeRecord({ app });
  1435. const selectionFallback = {
  1436. providerId: "account:bigmodel-highspeed-card",
  1437. rules: [{ reason: "highspeed_selection_unavailable" as const }],
  1438. target: { providerId: "account:bigmodel-start-plan", modelId: "glm-5" },
  1439. };
  1440. await expect(
  1441. new V4CommandExecutor(makeHost(record)).execute(
  1442. envelope("sendText", {
  1443. text: "使用可退回的执行模型",
  1444. modelSelection: {
  1445. providerId: "account:bigmodel-highspeed-card",
  1446. modelId: "missing-highspeed-model",
  1447. },
  1448. modelExecution: { selectionScope: "execution", selectionFallback },
  1449. }),
  1450. ),
  1451. ).resolves.toBeDefined();
  1452. await settle();
  1453. expect(app.sendInput).toHaveBeenCalledWith(
  1454. { text: "使用可退回的执行模型" },
  1455. expect.objectContaining({
  1456. intent: expect.objectContaining({
  1457. modelSelection: {
  1458. providerId: "account:bigmodel-highspeed-card",
  1459. modelId: "missing-highspeed-model",
  1460. },
  1461. }),
  1462. modelExecution: expect.objectContaining({
  1463. selectionScope: "execution",
  1464. selectionFallback,
  1465. }),
  1466. }),
  1467. );
  1468. });
  1469. it("Highspeed execution Selection 可用时不因退回目标缺失而拒绝", async () => {
  1470. const highspeedSelection = {
  1471. providerId: "account:bigmodel-highspeed-card",
  1472. modelId: "GLM-5.3",
  1473. };
  1474. const app = makeApp({
  1475. listModels: () => [{ ref: highspeedSelection }],
  1476. });
  1477. const record = makeRecord({ app });
  1478. await expect(
  1479. new V4CommandExecutor(makeHost(record)).execute(
  1480. envelope("sendText", {
  1481. text: "执行模型可用时继续发送",
  1482. modelSelection: highspeedSelection,
  1483. modelExecution: {
  1484. selectionScope: "execution",
  1485. selectionFallback: {
  1486. providerId: highspeedSelection.providerId,
  1487. rules: [{ reason: "highspeed_selection_unavailable" }],
  1488. target: { providerId: "missing-fallback", modelId: "missing-model" },
  1489. },
  1490. },
  1491. }),
  1492. ),
  1493. ).resolves.toBeDefined();
  1494. expect(app.sendInput).toHaveBeenCalledTimes(1);
  1495. });
  1496. it("Highspeed execution Selection 与退回目标都不在 Registry 时在 ACK 前拒绝", async () => {
  1497. const app = makeApp({ listModels: () => [] });
  1498. const record = makeRecord({ app });
  1499. await expect(
  1500. new V4CommandExecutor(makeHost(record)).execute(
  1501. envelope("sendText", {
  1502. text: "双模型都不可用时保留输入",
  1503. modelSelection: {
  1504. providerId: "account:bigmodel-highspeed-card",
  1505. modelId: "missing-highspeed-model",
  1506. },
  1507. modelExecution: {
  1508. selectionScope: "execution",
  1509. selectionFallback: {
  1510. providerId: "account:bigmodel-highspeed-card",
  1511. rules: [{ reason: "highspeed_selection_unavailable" }],
  1512. target: { providerId: "account:bigmodel-start-plan", modelId: "glm-5" },
  1513. },
  1514. },
  1515. }),
  1516. ),
  1517. ).rejects.toMatchObject({ reasonCode: "modelUnavailable" });
  1518. expect(app.sendInput).not.toHaveBeenCalled();
  1519. });
  1520. it("退回声明与 execution Provider 不一致时仍在 ACK 前拒绝", async () => {
  1521. const app = makeApp({ listModels: () => [] });
  1522. const record = makeRecord({ app });
  1523. await expect(
  1524. new V4CommandExecutor(makeHost(record)).execute(
  1525. envelope("sendText", {
  1526. text: "使用声明不一致的执行模型",
  1527. modelSelection: {
  1528. providerId: "account:bigmodel-highspeed-card",
  1529. modelId: "missing-highspeed-model",
  1530. },
  1531. modelExecution: {
  1532. selectionScope: "execution",
  1533. selectionFallback: {
  1534. providerId: "other-provider",
  1535. rules: [{ reason: "highspeed_selection_unavailable" }],
  1536. target: { providerId: "account:bigmodel-start-plan", modelId: "glm-5" },
  1537. },
  1538. },
  1539. }),
  1540. ),
  1541. ).rejects.toMatchObject({ reasonCode: "modelUnavailable" });
  1542. expect(app.sendInput).not.toHaveBeenCalled();
  1543. });
  1544. it("排队 execution Selection 仍按原模型目录做 admission 预检", async () => {
  1545. const app = makeApp({ listModels: () => [] });
  1546. const record = makeRecord({ app, activeAbortController: new AbortController() });
  1547. await expect(
  1548. new V4CommandExecutor(makeHost(record, { getInputRoutingMode: () => "enqueue" })).execute(
  1549. envelope("sendText", {
  1550. text: "排队执行模型",
  1551. modelSelection: {
  1552. providerId: "account:bigmodel-highspeed-card",
  1553. modelId: "missing-highspeed-model",
  1554. },
  1555. modelExecution: {
  1556. selectionScope: "execution",
  1557. selectionFallback: {
  1558. providerId: "account:bigmodel-highspeed-card",
  1559. rules: [{ reason: "highspeed_selection_unavailable" }],
  1560. target: { providerId: "account:bigmodel-start-plan", modelId: "glm-5" },
  1561. },
  1562. },
  1563. }),
  1564. ),
  1565. ).rejects.toMatchObject({ reasonCode: "modelUnavailable" });
  1566. expect(app.sendInput).not.toHaveBeenCalled();
  1567. });
  1568. it("turn 失败:finally 仍释放锁,legacy 广播 reason=prompt_failed", async () => {
  1569. const app = makeApp({ sendInput: vi.fn().mockRejectedValue(new Error("boom")) });
  1570. const record = makeRecord({ app });
  1571. const host = makeHost(record);
  1572. await expect(
  1573. new V4CommandExecutor(host).execute(envelope("sendText", { text: "x" })),
  1574. ).rejects.toThrow("boom");
  1575. expect(record.activeAbortController).toBeUndefined();
  1576. expect(host.legacyMutations).toEqual(["prompt_failed"]);
  1577. });
  1578. });
  1579. describe("v4 原生 sendText:软门禁(soft gate)", () => {
  1580. it("startPromptTurn 不再把 authority observer 传给 Core admission", async () => {
  1581. let capturedOptions: PromptSendInputOptions | undefined;
  1582. const app = makeApp({
  1583. sendInput: vi.fn().mockImplementation(async (_input, options) => {
  1584. capturedOptions = options as PromptSendInputOptions;
  1585. return {
  1586. completion: Promise.resolve({}),
  1587. kind: "started_turn",
  1588. turnId: "turn-1",
  1589. };
  1590. }),
  1591. });
  1592. const record = makeRecord({ app });
  1593. const host = makeHost(record);
  1594. await new V4CommandExecutor(host).execute(envelope("sendText", { text: "test" }));
  1595. await settle();
  1596. // projection observer 已移除,Core admission ACK 不等待 TurnStarted。
  1597. expect(capturedOptions!.onEvent).toBeUndefined();
  1598. expect(capturedOptions!.onTurnStartedObserved).toBeUndefined();
  1599. });
  1600. it("projection commit 永不完成时,input ACK 仍立即返回", async () => {
  1601. const turnGate = deferred<void>();
  1602. const app = makeApp({
  1603. sendInput: vi.fn().mockResolvedValue({
  1604. completion: turnGate.promise,
  1605. kind: "started_turn",
  1606. turnId: "turn-1",
  1607. }),
  1608. });
  1609. const record = makeRecord({ app });
  1610. const host = makeHost(record, {
  1611. waitForProjectionEventCommit: async () => {
  1612. await new Promise<void>(() => {});
  1613. },
  1614. });
  1615. const executing = new V4CommandExecutor(host).execute(
  1616. envelope("sendText", { text: "等待 projection commit" }),
  1617. );
  1618. await vi.waitFor(() => expect(app.sendInput).toHaveBeenCalled());
  1619. await flushMicrotasks();
  1620. // projection commit 完全不参与 admission;故意不 resolve 它。
  1621. await executing;
  1622. turnGate.resolve(undefined);
  1623. await settle();
  1624. });
  1625. it("回归:TurnStarted 后 projection 延迟时,第二条只产生一个 Core queue item", async () => {
  1626. const admissions: Array<"started" | "queued"> = [];
  1627. const runtime = {
  1628. // Bootstrap 不再查询 activeTurn;Core admission 自己持有 starting/active 状态。
  1629. getActiveTurnInfo: vi.fn(),
  1630. };
  1631. const sendInput = vi.fn().mockImplementation(async () => {
  1632. const admission = admissions.length === 0 ? "started" : "queued";
  1633. admissions.push(admission);
  1634. return admission === "started"
  1635. ? { kind: "accepted", delivery: "startNow", inputId: `cmd-${admissions.length}` }
  1636. : {
  1637. kind: "queued",
  1638. pendingInputId: "pending-stalled-followup",
  1639. queueLength: 1,
  1640. turnId: "turn-stalled-before-model",
  1641. };
  1642. });
  1643. const app = makeApp({ sendInput, runtime });
  1644. const record = makeRecord({ app });
  1645. const host = makeHost(record, {
  1646. getInputRoutingMode: () => "startNow",
  1647. waitForProjectionEventCommit: vi.fn(() => new Promise<void>(() => {})),
  1648. });
  1649. const executor = new V4CommandExecutor(host);
  1650. const first = executor.execute(envelope("sendText", { text: "触发卡住的首条" }));
  1651. await flushMicrotasks();
  1652. const second = executor.execute(envelope("sendText", { text: "卡住期间的下一条" }));
  1653. await Promise.all([first, second]);
  1654. expect(admissions).toEqual(["started", "queued"]);
  1655. expect(runtime.getActiveTurnInfo).not.toHaveBeenCalled();
  1656. });
  1657. });
  1658. describe("v4 原生 sendText:held choice 裁决(catalog B06/B07)", () => {
  1659. it("held(routing=choice)缺 disposition → 拒绝 heldQueueDispositionRequired", async () => {
  1660. const app = makeApp({ clearQueueItems: vi.fn().mockResolvedValue(0) });
  1661. const record = makeRecord({ app });
  1662. const host = makeHost(record, { getInputRoutingMode: () => "choice" });
  1663. await expect(
  1664. new V4CommandExecutor(host).execute(envelope("sendText", { text: "x" })),
  1665. ).rejects.toMatchObject({ reasonCode: "heldQueueDispositionRequired" });
  1666. expect(app.sendInput).not.toHaveBeenCalled();
  1667. expect(app.clearQueueItems).not.toHaveBeenCalled();
  1668. });
  1669. it("held + clearQueueAndSend → 先清空 queue 再起 turn", async () => {
  1670. const calls: string[] = [];
  1671. const app = makeApp({
  1672. clearQueueItems: vi.fn().mockImplementation(async () => {
  1673. calls.push("clear");
  1674. return 2;
  1675. }),
  1676. sendInput: vi.fn().mockImplementation(async (_input, options) => {
  1677. calls.push("send");
  1678. return {
  1679. completion: Promise.resolve({}),
  1680. kind: "started_turn",
  1681. turnId: "turn-held-clear",
  1682. };
  1683. }),
  1684. });
  1685. const record = makeRecord({ app });
  1686. const host = makeHost(record, { getInputRoutingMode: () => "choice" });
  1687. await new V4CommandExecutor(host).execute(
  1688. envelope("sendText", { text: "新问题", heldQueueDisposition: "clearQueueAndSend" }),
  1689. );
  1690. await settle();
  1691. expect(calls).toEqual(["clear", "send"]);
  1692. });
  1693. it("held + startNow + clearQueueAndSend → 仍先清空 queue 再起 turn", async () => {
  1694. const calls: string[] = [];
  1695. const app = makeApp({
  1696. clearQueueItems: vi.fn().mockImplementation(async () => {
  1697. calls.push("clear");
  1698. return 2;
  1699. }),
  1700. runtime: {
  1701. acquireForegroundPromotionLease: vi.fn().mockReturnValue({ kind: "acquired" }),
  1702. getActiveForegroundExecutionId: vi.fn().mockReturnValue(undefined),
  1703. releaseForegroundPromotionLease: vi.fn().mockReturnValue(true),
  1704. stopActiveForegroundExecution: vi.fn().mockReturnValue({ kind: "idle" }),
  1705. },
  1706. sendInput: vi.fn().mockImplementation(async (_input, options) => {
  1707. calls.push("send");
  1708. return {
  1709. completion: Promise.resolve({}),
  1710. kind: "started_turn",
  1711. turnId: "turn-held-start-now",
  1712. };
  1713. }),
  1714. });
  1715. const record = makeRecord({ app });
  1716. const host = makeHost(record, {
  1717. getInputRoutingMode: () => "choice",
  1718. getQueueLength: () => 2,
  1719. getQueueItem: (_sessionId, queueItemId) => ({ queueItemId }) as never,
  1720. });
  1721. await new V4CommandExecutor(host).execute(
  1722. envelope("sendText", {
  1723. text: "新问题",
  1724. requestedDelivery: "startNow",
  1725. heldQueueDisposition: "clearQueueAndSend",
  1726. expectedHeldQueueItemIds: ["q-1", "q-2"],
  1727. }),
  1728. );
  1729. await settle();
  1730. expect(calls).toEqual(["clear", "send"]);
  1731. });
  1732. it("held + startNow 的 queue ids 过期时拒绝清空和启动 turn", async () => {
  1733. const app = makeApp({
  1734. clearQueueItems: vi.fn().mockResolvedValue(0),
  1735. runtime: {
  1736. acquireForegroundPromotionLease: vi.fn().mockReturnValue({ kind: "acquired" }),
  1737. releaseForegroundPromotionLease: vi.fn().mockReturnValue(true),
  1738. },
  1739. });
  1740. const record = makeRecord({ app });
  1741. const host = makeHost(record, {
  1742. getInputRoutingMode: () => "choice",
  1743. getQueueLength: () => 2,
  1744. getQueueItem: (_sessionId, queueItemId) =>
  1745. queueItemId === "q-1" ? ({ queueItemId } as never) : null,
  1746. });
  1747. await expect(
  1748. new V4CommandExecutor(host).execute(
  1749. envelope("sendText", {
  1750. text: "新问题",
  1751. requestedDelivery: "startNow",
  1752. heldQueueDisposition: "clearQueueAndSend",
  1753. expectedHeldQueueItemIds: ["q-1"],
  1754. }),
  1755. ),
  1756. ).rejects.toMatchObject({ reasonCode: "guard.heldQueueConfirmationStale" });
  1757. expect(app.clearQueueItems).not.toHaveBeenCalled();
  1758. expect(app.sendInput).not.toHaveBeenCalled();
  1759. });
  1760. it("held + keepQueueAndSend → 不清 queue 直接起 turn", async () => {
  1761. const app = makeApp({ clearQueueItems: vi.fn().mockResolvedValue(0) });
  1762. const record = makeRecord({ app });
  1763. const host = makeHost(record, { getInputRoutingMode: () => "choice" });
  1764. await new V4CommandExecutor(host).execute(
  1765. envelope("sendText", { text: "新问题", heldQueueDisposition: "keepQueueAndSend" }),
  1766. );
  1767. await settle();
  1768. expect(app.clearQueueItems).not.toHaveBeenCalled();
  1769. expect(app.sendInput).toHaveBeenCalled();
  1770. });
  1771. it("held 确认绑定 queueItemId 集合:跨端增删后拒绝旧确认且不清空/发送", async () => {
  1772. const app = makeApp({ clearQueueItems: vi.fn().mockResolvedValue(0) });
  1773. const record = makeRecord({ app });
  1774. const getQueueItem = vi.fn((_sessionId: string, queueItemId: string) =>
  1775. queueItemId === "q-1" ? ({ queueItemId } as never) : null,
  1776. );
  1777. const host = makeHost(record, {
  1778. getInputRoutingMode: () => "choice",
  1779. getQueueLength: () => 2,
  1780. getQueueItem,
  1781. });
  1782. await expect(
  1783. new V4CommandExecutor(host).execute(
  1784. envelope("sendText", {
  1785. text: "新问题",
  1786. heldQueueDisposition: "clearQueueAndSend",
  1787. expectedHeldQueueItemIds: ["q-1"],
  1788. }),
  1789. ),
  1790. ).rejects.toMatchObject({ reasonCode: "guard.heldQueueConfirmationStale" });
  1791. expect(app.clearQueueItems).not.toHaveBeenCalled();
  1792. expect(app.sendInput).not.toHaveBeenCalled();
  1793. });
  1794. it("held 确认的 ID 集合未变化时允许执行;重排不使确认失效", async () => {
  1795. const app = makeApp({ clearQueueItems: vi.fn().mockResolvedValue(2) });
  1796. const record = makeRecord({ app });
  1797. const host = makeHost(record, {
  1798. getInputRoutingMode: () => "choice",
  1799. getQueueLength: () => 2,
  1800. getQueueItem: (_sessionId, queueItemId) => ({ queueItemId }) as never,
  1801. });
  1802. await new V4CommandExecutor(host).execute(
  1803. envelope("sendText", {
  1804. text: "新问题",
  1805. heldQueueDisposition: "clearQueueAndSend",
  1806. expectedHeldQueueItemIds: ["q-2", "q-1"],
  1807. }),
  1808. );
  1809. await settle();
  1810. expect(app.clearQueueItems).toHaveBeenCalledTimes(1);
  1811. expect(app.sendInput).toHaveBeenCalledTimes(1);
  1812. });
  1813. it("非 held(routing=startNow)缺 disposition → 正常起 turn(不误拒)", async () => {
  1814. const app = makeApp({ clearQueueItems: vi.fn().mockResolvedValue(0) });
  1815. const record = makeRecord({ app });
  1816. const host = makeHost(record, { getInputRoutingMode: () => "startNow" });
  1817. await new V4CommandExecutor(host).execute(envelope("sendText", { text: "x" }));
  1818. await settle();
  1819. expect(app.sendInput).toHaveBeenCalled();
  1820. expect(app.clearQueueItems).not.toHaveBeenCalled();
  1821. });
  1822. });
  1823. describe("v4 原生 stop", () => {
  1824. it("active turn + active goal:先 pause goal 再 abort(barrier 顺序)", async () => {
  1825. const calls: string[] = [];
  1826. const app = makeApp({
  1827. readTarget: vi.fn().mockResolvedValue({ targetID: "g1", status: "active" }),
  1828. updateTargetStatus: vi.fn().mockImplementation(async () => {
  1829. calls.push("pause");
  1830. return { targetID: "g1", status: "paused" };
  1831. }),
  1832. });
  1833. const controller = new AbortController();
  1834. controller.signal.addEventListener("abort", () => calls.push("abort"));
  1835. const record = makeRecord({ app, activeAbortController: controller });
  1836. const host = makeHost(record);
  1837. await new V4CommandExecutor(host).execute(envelope("stop", {}));
  1838. expect(calls).toEqual(["pause", "abort"]);
  1839. expect(host.legacyMutations).toEqual(["session_stop_goal_paused"]);
  1840. });
  1841. it("无 active turn:不触碰 goal,abort 为 noop", async () => {
  1842. const app = makeApp();
  1843. const record = makeRecord({ app });
  1844. const host = makeHost(record);
  1845. await new V4CommandExecutor(host).execute(envelope("stop", {}));
  1846. expect(app.readTarget).not.toHaveBeenCalled();
  1847. expect(host.legacyMutations).toEqual([]);
  1848. });
  1849. it("pause goal 抛错:不阻断 abort(stop 必须成功)", async () => {
  1850. const app = makeApp({
  1851. readTarget: vi.fn().mockResolvedValue({ targetID: "g1", status: "active" }),
  1852. updateTargetStatus: vi.fn().mockRejectedValue(new Error("verifier busy")),
  1853. });
  1854. const controller = new AbortController();
  1855. const record = makeRecord({ app, activeAbortController: controller });
  1856. await new V4CommandExecutor(makeHost(record)).execute(envelope("stop", {}));
  1857. expect(controller.signal.aborted).toBe(true);
  1858. });
  1859. it("goal verifier:先取消 runtime 前台执行,再暂停 goal 并关闭外层窗口", async () => {
  1860. const calls: string[] = [];
  1861. const setQueueAutoDrain = vi.fn().mockImplementation(async () => {
  1862. calls.push("hold-queue");
  1863. });
  1864. const stopActiveForegroundExecution = vi.fn().mockImplementation(() => {
  1865. calls.push("runtime-abort");
  1866. return { kind: "stopped", foregroundExecutionId: "foreground-1" };
  1867. });
  1868. const app = makeApp({
  1869. runtime: { stopActiveForegroundExecution },
  1870. setQueueAutoDrain,
  1871. readTarget: vi.fn().mockResolvedValue({ targetID: "g1", status: "active" }),
  1872. updateTargetStatus: vi.fn().mockImplementation(async () => {
  1873. calls.push("pause");
  1874. return { targetID: "g1", status: "paused" };
  1875. }),
  1876. });
  1877. const controller = new AbortController();
  1878. controller.signal.addEventListener("abort", () => calls.push("outer-abort"));
  1879. const record = makeRecord({ app, activeAbortController: controller });
  1880. const info = vi.fn();
  1881. await new V4CommandExecutor(
  1882. makeHost(record, {
  1883. getQueueLength: () => 1,
  1884. logger: { info } as never,
  1885. }),
  1886. ).execute(envelope("stop", { expectedForegroundExecutionId: "foreground-1" }));
  1887. expect(stopActiveForegroundExecution).toHaveBeenCalledWith({
  1888. expectedForegroundExecutionId: "foreground-1",
  1889. reason: "v4 session stopped",
  1890. });
  1891. expect(setQueueAutoDrain).toHaveBeenCalledWith(false);
  1892. expect(calls).toEqual(["runtime-abort", "outer-abort", "hold-queue", "pause"]);
  1893. expect(info).toHaveBeenCalledWith("v4 stop foreground execution inspected", {
  1894. activeForegroundExecutionId: "foreground-1",
  1895. event: "v4.stop.foreground_execution_inspected",
  1896. expectedForegroundExecutionId: "foreground-1",
  1897. module: "bootstrap.zcode_protocol_v4.commands",
  1898. runtimeStopKind: "stopped",
  1899. sessionId: "s1",
  1900. });
  1901. });
  1902. it("迟到 Stop 的 execution id 已变化:返回 noop,且不误杀新执行", async () => {
  1903. const stopActiveForegroundExecution = vi.fn().mockReturnValue({
  1904. kind: "mismatch",
  1905. activeForegroundExecutionId: "foreground-2",
  1906. });
  1907. const app = makeApp({ runtime: { stopActiveForegroundExecution } });
  1908. const controller = new AbortController();
  1909. const record = makeRecord({ app, activeAbortController: controller });
  1910. await expect(
  1911. new V4CommandExecutor(makeHost(record)).execute(
  1912. envelope("stop", { expectedForegroundExecutionId: "foreground-1" }),
  1913. ),
  1914. ).rejects.toMatchObject({ reasonCode: "guard.stopTargetChanged" });
  1915. expect(controller.signal.aborted).toBe(false);
  1916. expect(app.readTarget).not.toHaveBeenCalled();
  1917. });
  1918. });
  1919. describe("supports 分流", () => {
  1920. it("协议命令全部原生(回落面清零);未知命令不 supports", () => {
  1921. const executor = new V4CommandExecutor(makeHost(makeRecord()));
  1922. // 与 packages/shared/src/zcode-protocol-v4/command.ts 的 payload map 同步维护。
  1923. const allCommands = [
  1924. "createSession",
  1925. "sendText",
  1926. "sendGoalCommand",
  1927. "stop",
  1928. "compact",
  1929. "forkAssistant",
  1930. "applyFileRewind",
  1931. "editUserQuery",
  1932. "retryTurn",
  1933. "setAssistantFeedback",
  1934. "setHighspeedMetrics",
  1935. "sendQueuedNow",
  1936. "editQueueItem",
  1937. "reorderQueueItem",
  1938. "deleteQueueItem",
  1939. "setAutoDrain",
  1940. "resolveInteraction",
  1941. "snoozeInteractionAutoResolution",
  1942. "switchModelConfig",
  1943. "setFollowupMode",
  1944. "resumeGoal",
  1945. "cancelBackgroundWork",
  1946. "renameSession",
  1947. "deleteSession",
  1948. ] as const;
  1949. for (const command of allCommands) {
  1950. expect(executor.supports(command), command).toBe(true);
  1951. }
  1952. expect(executor.supports("unknownCommand" as never)).toBe(false);
  1953. });
  1954. });