v4-native-commands.test.ts 64 KB

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