session-features.test.ts 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630
  1. import { describe, expect, it, vi } from "vitest";
  2. import {
  3. CREATE_WORKFLOW_TOOL_NAME,
  4. ModelRequestSessionFeature,
  5. SESSION_ENTRY_SESSION_FEATURES,
  6. createMessageId,
  7. createPartId,
  8. createProjectId,
  9. createSessionId,
  10. getCurrentModelInvocationContext,
  11. runWithModelInvocationContext,
  12. type Logger,
  13. type MessageWithParts,
  14. type ModelInvocationContext,
  15. type SessionEntryInfo,
  16. type SessionId,
  17. type SessionStorePort,
  18. } from "@zcode/contracts";
  19. import type { AgentRuntime } from "../../src/runtime.js";
  20. import type { AgentRuntimeInternal } from "../../src/runtime/internal.js";
  21. import { createRuntimeModel } from "../../src/runtime/methods/runtime-model.js";
  22. import {
  23. parseSessionFeaturesEntryData,
  24. readSessionFeatures,
  25. sessionFeaturesFromPersistedMessages,
  26. sessionFeaturesFromToolResult,
  27. writeSessionFeaturesEntryAfterFirstPersist,
  28. } from "../../src/runtime/session-features/contract.js";
  29. import { createToolRegistry } from "../../src/tool/registry.js";
  30. import { createRecordingMessageStore } from "../runtime-output-token-continuation-test-helpers.js";
  31. import { createTestAgentRuntime } from "../test-agent-runtime.js";
  32. import { createTestSessionEventStore } from "../test-event-store.js";
  33. import { createTestModelFactory } from "../test-runtime-model.js";
  34. // 规格:docs/design/v2/model/session-features-header.md。
  35. const { WorkflowAuto, WorkflowCmd } = ModelRequestSessionFeature;
  36. const selection = { providerId: "test", modelId: "model" };
  37. const modelRequest = { messages: [{ role: "user" as const, content: "hi" }] };
  38. const stopResult = { text: "ok", finishReason: "stop" as const };
  39. function internal(runtime: AgentRuntime): AgentRuntimeInternal {
  40. return runtime as unknown as AgentRuntimeInternal;
  41. }
  42. function savedFeatureEntries(saveSessionEntry: ReturnType<typeof vi.fn>): string[][] {
  43. return saveSessionEntry.mock.calls
  44. .map(([entry]) => entry as SessionEntryInfo)
  45. .filter((entry) => entry.type === SESSION_ENTRY_SESSION_FEATURES)
  46. .map((entry) => (entry.data as { features: string[] }).features);
  47. }
  48. function warnLogger() {
  49. const warn = vi.fn();
  50. const logger = {
  51. debug: vi.fn(),
  52. info: vi.fn(),
  53. warn,
  54. error: vi.fn(),
  55. child: () => logger,
  56. } as unknown as Logger;
  57. return { logger, warn };
  58. }
  59. describe("sessionFeaturesFromToolResult", () => {
  60. it("只有 CreateWorkflow 成功启动后台 run 才打 workflow_auto", () => {
  61. const backgrounded = { status: "backgrounded", ok: true, backgroundTaskId: "run_1" };
  62. expect(
  63. sessionFeaturesFromToolResult({
  64. toolName: CREATE_WORKFLOW_TOOL_NAME,
  65. success: true,
  66. output: backgrounded,
  67. }),
  68. ).toEqual([WorkflowAuto]);
  69. // 编译失败与宿主没有 run 端口都返回 success,但没有 backgrounded。
  70. for (const output of [
  71. { ok: false, diagnostics: [], response: "errors" },
  72. { ok: true, diagnostics: [], response: "compiled cleanly" },
  73. ]) {
  74. expect(
  75. sessionFeaturesFromToolResult({
  76. toolName: CREATE_WORKFLOW_TOOL_NAME,
  77. success: true,
  78. output,
  79. }),
  80. ).toEqual([]);
  81. }
  82. expect(
  83. sessionFeaturesFromToolResult({
  84. toolName: CREATE_WORKFLOW_TOOL_NAME,
  85. success: false,
  86. output: backgrounded,
  87. }),
  88. ).toEqual([]);
  89. expect(
  90. sessionFeaturesFromToolResult({ toolName: "Bash", success: true, output: backgrounded }),
  91. ).toEqual([]);
  92. });
  93. });
  94. describe("sessionFeaturesFromPersistedMessages", () => {
  95. const sessionId = createSessionId("session-features-history");
  96. it("从 /workflow 原文与 CreateWorkflow 成功 display 推出标签", () => {
  97. expect(
  98. sessionFeaturesFromPersistedMessages([
  99. userMessage(sessionId, " /workflow tidy the repo"),
  100. createWorkflowMessage(sessionId, { kind: "create_workflow", ok: true }),
  101. ]),
  102. ).toEqual(new Set([WorkflowAuto, WorkflowCmd]));
  103. });
  104. it("不应命中的情况", () => {
  105. expect(
  106. sessionFeaturesFromPersistedMessages([
  107. userMessage(sessionId, "/workflows are cool"),
  108. userMessage(sessionId, "please run /workflow later"),
  109. assistantText(sessionId, "/workflow"),
  110. createWorkflowMessage(sessionId, { kind: "create_workflow", ok: false }),
  111. createWorkflowMessage(sessionId, undefined),
  112. createWorkflowMessage(sessionId, { kind: "create_workflow", ok: true }, "error"),
  113. ]),
  114. ).toEqual(new Set());
  115. });
  116. });
  117. describe("parseSessionFeaturesEntryData", () => {
  118. it("忽略词表外标签与非法载荷", () => {
  119. expect(
  120. parseSessionFeaturesEntryData({ features: ["workflow_cmd", "future_feature", 1] }),
  121. ).toEqual([WorkflowCmd]);
  122. expect(parseSessionFeaturesEntryData(undefined)).toEqual([]);
  123. expect(parseSessionFeaturesEntryData({ features: "workflow_cmd" })).toEqual([]);
  124. });
  125. });
  126. describe("recordSessionFeature(owner)", () => {
  127. function createRuntime(saveSessionEntry = vi.fn(async (_entry: SessionEntryInfo) => {})) {
  128. const { logger, warn } = warnLogger();
  129. const runtime = createTestAgentRuntime(
  130. createSessionId(`session-features-owner-${Math.random().toString(36).slice(2)}`),
  131. { modelSelection: selection },
  132. {
  133. eventStore: createTestSessionEventStore(),
  134. logger,
  135. sessionStore: { saveSessionEntry } as unknown as SessionStorePort,
  136. },
  137. );
  138. return { runtime, saveSessionEntry, warn };
  139. }
  140. it("幂等,读取为去重后的字典序", () => {
  141. const { runtime } = createRuntime();
  142. expect(runtime.recordSessionFeature({ feature: WorkflowCmd })).toBe(true);
  143. expect(runtime.recordSessionFeature({ feature: WorkflowAuto })).toBe(true);
  144. expect(runtime.recordSessionFeature({ feature: WorkflowCmd })).toBe(false);
  145. expect(readSessionFeatures(internal(runtime))).toEqual([WorkflowAuto, WorkflowCmd]);
  146. });
  147. it("未落盘时只改内存;首次落盘后补写一次", async () => {
  148. const { runtime, saveSessionEntry } = createRuntime();
  149. runtime.recordSessionFeature({ feature: WorkflowCmd });
  150. await internal(runtime).sessionFeaturesWrite;
  151. expect(savedFeatureEntries(saveSessionEntry)).toEqual([]);
  152. internal(runtime).sessionPersisted = true;
  153. await writeSessionFeaturesEntryAfterFirstPersist(internal(runtime));
  154. expect(savedFeatureEntries(saveSessionEntry)).toEqual([[WorkflowCmd]]);
  155. const entry = saveSessionEntry.mock.calls[0]![0];
  156. expect(entry).toMatchObject({
  157. id: `${runtime.getSessionId()}:runtime-session-features`,
  158. touchSession: false,
  159. });
  160. });
  161. it("没有标签时首次落盘不写", async () => {
  162. const { runtime, saveSessionEntry } = createRuntime();
  163. internal(runtime).sessionPersisted = true;
  164. await writeSessionFeaturesEntryAfterFirstPersist(internal(runtime));
  165. expect(saveSessionEntry).not.toHaveBeenCalled();
  166. });
  167. it("并发打点时写入串行,最后一次写入含全部标签", async () => {
  168. const gates: Array<() => void> = [];
  169. const saveSessionEntry = vi.fn(
  170. (_entry: SessionEntryInfo) => new Promise<void>((resolve) => gates.push(resolve)),
  171. );
  172. const { runtime } = createRuntime(saveSessionEntry);
  173. internal(runtime).sessionPersisted = true;
  174. runtime.recordSessionFeature({ feature: WorkflowCmd });
  175. runtime.recordSessionFeature({ feature: WorkflowAuto });
  176. // 第一次写入还没完成时,第二次不能开始。
  177. await vi.waitFor(() => expect(gates).toHaveLength(1));
  178. gates[0]!();
  179. await vi.waitFor(() => expect(gates).toHaveLength(2));
  180. gates[1]!();
  181. await internal(runtime).sessionFeaturesWrite;
  182. expect(savedFeatureEntries(saveSessionEntry).at(-1)).toEqual([WorkflowAuto, WorkflowCmd]);
  183. });
  184. it("写入失败只记 warn,内存标签保留,后续写入照常", async () => {
  185. const saveSessionEntry = vi
  186. .fn(async (_entry: SessionEntryInfo) => {})
  187. .mockRejectedValueOnce(new Error("disk I/O error"));
  188. const { runtime, warn } = createRuntime(saveSessionEntry);
  189. internal(runtime).sessionPersisted = true;
  190. runtime.recordSessionFeature({ feature: WorkflowCmd });
  191. await internal(runtime).sessionFeaturesWrite;
  192. expect(warn).toHaveBeenCalledWith(
  193. "Session features entry write failed",
  194. expect.objectContaining({ event: "session_features.entry_write_failed" }),
  195. );
  196. expect(readSessionFeatures(internal(runtime))).toEqual([WorkflowCmd]);
  197. runtime.recordSessionFeature({ feature: WorkflowAuto });
  198. await internal(runtime).sessionFeaturesWrite;
  199. expect(savedFeatureEntries(saveSessionEntry).at(-1)).toEqual([WorkflowAuto, WorkflowCmd]);
  200. });
  201. });
  202. describe("冷恢复", () => {
  203. async function resume(input: {
  204. messages: MessageWithParts[];
  205. entries?: SessionEntryInfo[];
  206. failEntryRead?: boolean;
  207. /** 只让前 N 次 entry 读取失败(默认全部失败)。 */
  208. failEntryReadTimes?: number;
  209. }) {
  210. const sessionId = createSessionId(
  211. `session-features-resume-${Math.random().toString(36).slice(2)}`,
  212. );
  213. const saveSessionEntry = vi.fn(async (_entry: SessionEntryInfo) => {});
  214. const { logger, warn } = warnLogger();
  215. let featureReads = 0;
  216. const store = {
  217. getSession: vi.fn(async () => persistedSession(sessionId)),
  218. messages: vi.fn(async () => input.messages),
  219. sessionEntries: vi.fn(async ({ type }: { type?: string }) => {
  220. if (type !== SESSION_ENTRY_SESSION_FEATURES) return [];
  221. featureReads += 1;
  222. const failing =
  223. input.failEntryRead === true &&
  224. (input.failEntryReadTimes === undefined || featureReads <= input.failEntryReadTimes);
  225. if (failing) throw new Error("database is locked");
  226. return input.entries ?? [];
  227. }),
  228. readTodos: vi.fn(async () => []),
  229. readTarget: vi.fn(async () => null),
  230. saveMessage: vi.fn(async () => {}),
  231. savePart: vi.fn(async () => {}),
  232. saveSessionEntry,
  233. updateSession: vi.fn(async () => persistedSession(sessionId)),
  234. } as unknown as SessionStorePort;
  235. const runtime = createTestAgentRuntime(
  236. sessionId,
  237. { modelSelection: selection, workingDirectory: "/workspace/project" },
  238. { eventStore: createTestSessionEventStore(), logger, sessionStore: store },
  239. );
  240. await runtime.resumeFromStore();
  241. await internal(runtime).sessionFeaturesWrite;
  242. return {
  243. runtime,
  244. writes: savedFeatureEntries(saveSessionEntry),
  245. saveSessionEntry,
  246. sessionId,
  247. warn,
  248. };
  249. }
  250. // MR !3185 评审第二轮 SG-01:恢复时没读到 entry,之后打新标签也不能用不完整的内存集合覆盖它。
  251. it("恢复时读 entry 失败、之后再打新标签:写入前合并 entry 原有标签", async () => {
  252. const sessionId = createSessionId("entry-read-failure-then-record");
  253. const { runtime, saveSessionEntry } = await resume({
  254. // 历史里推不出 workflow_auto:它只存在于 entry 中。
  255. messages: [],
  256. entries: [featuresEntry(sessionId, ["workflow_auto"])],
  257. failEntryRead: true,
  258. failEntryReadTimes: 1,
  259. });
  260. expect(readSessionFeatures(internal(runtime))).toEqual([]);
  261. runtime.recordSessionFeature({ feature: WorkflowCmd });
  262. await internal(runtime).sessionFeaturesWrite;
  263. expect(savedFeatureEntries(saveSessionEntry)).toEqual([[WorkflowAuto, WorkflowCmd]]);
  264. // 读到的 entry 标签同时并回内存,之后的请求也带上它。
  265. expect(readSessionFeatures(internal(runtime))).toEqual([WorkflowAuto, WorkflowCmd]);
  266. });
  267. it("写入前读 entry 仍失败:跳过这次写入并记 warn,内存标签保留", async () => {
  268. const sessionId = createSessionId("entry-read-failure-on-write");
  269. const { runtime, saveSessionEntry, warn } = await resume({
  270. messages: [],
  271. entries: [featuresEntry(sessionId, ["workflow_auto"])],
  272. failEntryRead: true,
  273. });
  274. runtime.recordSessionFeature({ feature: WorkflowCmd });
  275. await internal(runtime).sessionFeaturesWrite;
  276. expect(savedFeatureEntries(saveSessionEntry)).toEqual([]);
  277. // 恢复时一次、写入前一次。
  278. expect(
  279. warn.mock.calls.filter(
  280. ([, context]) =>
  281. (context as { event?: string } | undefined)?.event ===
  282. "session_features.entry_read_failed",
  283. ),
  284. ).toHaveLength(2);
  285. expect(readSessionFeatures(internal(runtime))).toEqual([WorkflowCmd]);
  286. });
  287. // MR !3185 评审 SG-01:标签只用于统计,entry 读取失败不能阻断冷恢复。
  288. it("entry 读取抛错:恢复照常完成,标签来自历史,记 warn 且不覆盖 entry", async () => {
  289. const sessionId = createSessionId("entry-read-failure");
  290. const { runtime, writes, warn } = await resume({
  291. messages: [userMessage(sessionId, "/workflow summarize")],
  292. failEntryRead: true,
  293. });
  294. expect(readSessionFeatures(internal(runtime))).toEqual([WorkflowCmd]);
  295. expect(warn).toHaveBeenCalledWith(
  296. "Session features entry read failed",
  297. expect.objectContaining({
  298. error: "database is locked",
  299. event: "session_features.entry_read_failed",
  300. }),
  301. );
  302. // 读不到就不知道 entry 里原有什么:此时补写可能用较少的标签覆盖它。
  303. expect(writes).toEqual([]);
  304. });
  305. it("只有 entry:恢复 entry 里的标签,不重写;词表外标签忽略", async () => {
  306. const sessionId = createSessionId("any");
  307. const { runtime, writes } = await resume({
  308. messages: [],
  309. entries: [featuresEntry(sessionId, ["workflow_auto", "future_feature"])],
  310. });
  311. expect(readSessionFeatures(internal(runtime))).toEqual([WorkflowAuto]);
  312. expect(writes).toEqual([]);
  313. });
  314. it("只有历史:推出标签并补写 entry(fork 子会话走这条)", async () => {
  315. const sessionId = createSessionId("history-only");
  316. const { runtime, writes } = await resume({
  317. messages: [userMessage(sessionId, "/workflow summarize")],
  318. });
  319. expect(readSessionFeatures(internal(runtime))).toEqual([WorkflowCmd]);
  320. expect(writes).toEqual([[WorkflowCmd]]);
  321. });
  322. it("entry ∪ 历史;并集比 entry 多时补写", async () => {
  323. const sessionId = createSessionId("union");
  324. const { runtime, writes } = await resume({
  325. messages: [userMessage(sessionId, "/workflow go")],
  326. entries: [featuresEntry(sessionId, ["workflow_auto"])],
  327. });
  328. expect(readSessionFeatures(internal(runtime))).toEqual([WorkflowAuto, WorkflowCmd]);
  329. expect(writes).toEqual([[WorkflowAuto, WorkflowCmd]]);
  330. });
  331. it("没有任何标签时不写", async () => {
  332. const { runtime, writes } = await resume({ messages: [] });
  333. expect(readSessionFeatures(internal(runtime))).toEqual([]);
  334. expect(writes).toEqual([]);
  335. });
  336. });
  337. describe("runtime 模型句柄", () => {
  338. function runtimeWithCapture(seen: ModelInvocationContext[], taskType?: "subagent_child") {
  339. return createTestAgentRuntime(
  340. createSessionId(`session-features-model-${Math.random().toString(36).slice(2)}`),
  341. { modelSelection: selection, ...(taskType ? { taskType } : {}) },
  342. {
  343. eventStore: createTestSessionEventStore(),
  344. modelFactory: createTestModelFactory({
  345. async generateText(_request, observation) {
  346. seen.push(observation.invocationContext!);
  347. return stopResult;
  348. },
  349. async *streamText() {
  350. await Promise.resolve();
  351. seen.push(getCurrentModelInvocationContext()!);
  352. yield { type: "finish", finishReason: "stop" };
  353. },
  354. }),
  355. },
  356. );
  357. }
  358. it("同一句柄在会话中途新增标签后,下一次调用(含 bind、stream)带上新值", async () => {
  359. const seen: ModelInvocationContext[] = [];
  360. const runtime = runtimeWithCapture(seen);
  361. const model = createRuntimeModel(internal(runtime), { selection });
  362. await model.generateText(modelRequest);
  363. runtime.recordSessionFeature({ feature: WorkflowCmd });
  364. await model.bind({ maxOutputTokens: 64 }).generateText(modelRequest);
  365. runtime.recordSessionFeature({ feature: WorkflowAuto });
  366. for await (const _event of model.streamText(modelRequest)) {
  367. /* 消费完整流。 */
  368. }
  369. expect(seen.map((context) => context.modelRequestSessionFeatures)).toEqual([
  370. undefined,
  371. [WorkflowCmd],
  372. [WorkflowAuto, WorkflowCmd],
  373. ]);
  374. });
  375. it("标题、compact 等用途继承宿主标签;调用层带进来的值被覆盖", async () => {
  376. const seen: ModelInvocationContext[] = [];
  377. const runtime = runtimeWithCapture(seen);
  378. const model = createRuntimeModel(internal(runtime), { selection });
  379. for (const querySource of ["compact", "session_title"]) {
  380. await runWithModelInvocationContext(
  381. { metadata: { querySource }, modelRequestSessionFeatures: [WorkflowAuto] },
  382. () => model.generateText(modelRequest),
  383. );
  384. }
  385. runtime.recordSessionFeature({ feature: WorkflowCmd });
  386. await runWithModelInvocationContext({ metadata: { querySource: "web_search_tool" } }, () =>
  387. model.generateText(modelRequest),
  388. );
  389. expect(seen.map((context) => context.modelRequestSessionFeatures)).toEqual([
  390. undefined,
  391. undefined,
  392. [WorkflowCmd],
  393. ]);
  394. });
  395. it("工作区独立请求不带标签", async () => {
  396. const seen: ModelInvocationContext[] = [];
  397. const runtime = runtimeWithCapture(seen);
  398. runtime.recordSessionFeature({ feature: WorkflowCmd });
  399. const model = createRuntimeModel(internal(runtime), { selection, scope: "workspace" });
  400. await model.generateText(modelRequest);
  401. expect(seen.map((context) => context.modelRequestSessionFeatures)).toEqual([undefined]);
  402. });
  403. it("subagent 复用父句柄时只带子会话自己的标签", async () => {
  404. const seen: ModelInvocationContext[] = [];
  405. const parent = runtimeWithCapture(seen);
  406. parent.recordSessionFeature({ feature: WorkflowCmd });
  407. const parentModel = createRuntimeModel(internal(parent), { selection });
  408. const child = createTestAgentRuntime(
  409. createSessionId("session-features-model-child"),
  410. { modelSelection: selection, taskType: "subagent_child" },
  411. { eventStore: createTestSessionEventStore(), modelFactory: () => parentModel },
  412. );
  413. const childModel = createRuntimeModel(internal(child), { selection });
  414. await childModel.generateText(modelRequest);
  415. child.recordSessionFeature({ feature: WorkflowAuto });
  416. await childModel.generateText(modelRequest);
  417. await parentModel.generateText(modelRequest);
  418. expect(
  419. seen.map((context) => [context.modelRequestSessionType, context.modelRequestSessionFeatures]),
  420. ).toEqual([
  421. ["subagent", undefined],
  422. ["subagent", [WorkflowAuto]],
  423. ["main", [WorkflowCmd]],
  424. ]);
  425. });
  426. });
  427. describe("工具结果结算打点(端到端)", () => {
  428. async function runTurnWithCreateWorkflow(output: Record<string, unknown>) {
  429. const store = createRecordingMessageStore();
  430. const entries = new Map<string, SessionEntryInfo>();
  431. const sessionStore = {
  432. ...store,
  433. async getProjectPermission() {
  434. return null;
  435. },
  436. async saveSessionEntry(entry: SessionEntryInfo) {
  437. entries.set(entry.id, entry);
  438. },
  439. } as unknown as SessionStorePort;
  440. const registry = createToolRegistry();
  441. const fakeCreateWorkflow = {
  442. inputSchema: {},
  443. metadata: {
  444. name: CREATE_WORKFLOW_TOOL_NAME,
  445. concurrentSafe: true,
  446. destructive: false,
  447. needsApproval: false,
  448. readOnly: true,
  449. riskLevel: "low",
  450. sideEffectScope: "none",
  451. },
  452. handler: async () => output,
  453. };
  454. const seen: ModelInvocationContext[] = [];
  455. const runtime = createTestAgentRuntime(
  456. createSessionId(`session-features-turn-${Math.random().toString(36).slice(2)}`),
  457. { mode: "yolo", modelStreaming: "off", titleGeneration: { enabled: false } },
  458. {
  459. eventStore: createTestSessionEventStore(),
  460. sessionStore,
  461. toolRegistry: registry,
  462. modelFactory: createTestModelFactory({
  463. async generateText(_request, observation) {
  464. seen.push(observation.invocationContext!);
  465. if (seen.length === 1)
  466. return {
  467. text: "",
  468. finishReason: "tool-calls",
  469. usage: {},
  470. toolCalls: [{ id: "call_workflow", name: CREATE_WORKFLOW_TOOL_NAME, input: {} }],
  471. };
  472. return { text: "done", finishReason: "stop", usage: {} };
  473. },
  474. }),
  475. },
  476. );
  477. // runtime 构造时注册内置工具,之后再换成只返回给定输出的假 CreateWorkflow。
  478. runtime.getToolRegistry().register(fakeCreateWorkflow, { silentDuplicateWarning: true });
  479. runtime.invalidateToolCache();
  480. await runtime.executeTurn("start a workflow");
  481. await internal(runtime).sessionFeaturesWrite;
  482. return {
  483. features: seen.map((context) => context.modelRequestSessionFeatures),
  484. entries: [...entries.values()].filter(
  485. (entry) => entry.type === SESSION_ENTRY_SESSION_FEATURES,
  486. ),
  487. };
  488. }
  489. it("CreateWorkflow backgrounded:下一次模型请求带 workflow_auto,并写入 entry", async () => {
  490. const { features, entries } = await runTurnWithCreateWorkflow({
  491. ok: true,
  492. diagnostics: [],
  493. response: "started",
  494. status: "backgrounded",
  495. backgroundTaskId: "run_1",
  496. });
  497. expect(features).toEqual([undefined, [WorkflowAuto]]);
  498. expect(entries.map((entry) => entry.data)).toEqual([{ features: [WorkflowAuto] }]);
  499. });
  500. it("只编译不启动:不打标签", async () => {
  501. const { features, entries } = await runTurnWithCreateWorkflow({
  502. ok: true,
  503. diagnostics: [],
  504. response: "compiled cleanly",
  505. });
  506. expect(features).toEqual([undefined, undefined]);
  507. expect(entries).toEqual([]);
  508. });
  509. });
  510. function persistedSession(sessionId: SessionId) {
  511. return {
  512. id: sessionId,
  513. projectID: createProjectId("session-features"),
  514. directory: "/workspace/project",
  515. slug: "session-features",
  516. title: "session features",
  517. version: "test",
  518. taskType: "interactive",
  519. time: { created: 1, updated: 1 },
  520. };
  521. }
  522. function featuresEntry(sessionId: SessionId, features: string[]): SessionEntryInfo {
  523. return {
  524. id: `${sessionId}:runtime-session-features`,
  525. sessionID: sessionId,
  526. type: SESSION_ENTRY_SESSION_FEATURES,
  527. time: { created: 1, updated: 1 },
  528. data: { features },
  529. };
  530. }
  531. function userMessage(sessionId: SessionId, text: string): MessageWithParts {
  532. return textMessage(sessionId, "user", text);
  533. }
  534. function assistantText(sessionId: SessionId, text: string): MessageWithParts {
  535. return textMessage(sessionId, "assistant", text);
  536. }
  537. function textMessage(
  538. sessionId: SessionId,
  539. role: "user" | "assistant",
  540. text: string,
  541. ): MessageWithParts {
  542. const messageId = createMessageId();
  543. return {
  544. info: { id: messageId, sessionID: sessionId, role, agent: "zcode-agent", time: { created: 1 } },
  545. parts: [
  546. { id: createPartId("u"), messageID: messageId, sessionID: sessionId, type: "text", text },
  547. ],
  548. } as unknown as MessageWithParts;
  549. }
  550. function createWorkflowMessage(
  551. sessionId: SessionId,
  552. display: Record<string, unknown> | undefined,
  553. status: "completed" | "error" = "completed",
  554. ): MessageWithParts {
  555. const messageId = createMessageId();
  556. const state =
  557. status === "completed"
  558. ? {
  559. status,
  560. input: {},
  561. output: "started",
  562. title: CREATE_WORKFLOW_TOOL_NAME,
  563. metadata: display === undefined ? {} : { display },
  564. time: { start: 1, end: 2 },
  565. }
  566. : { status, input: {}, error: "failed", metadata: { display }, time: { start: 1, end: 2 } };
  567. return {
  568. info: {
  569. id: messageId,
  570. sessionID: sessionId,
  571. role: "assistant",
  572. agent: "zcode-agent",
  573. time: { created: 2, completed: 3 },
  574. tokens: { input: 1, output: 1, reasoning: 0, cache: { read: 0, write: 0 } },
  575. },
  576. parts: [
  577. {
  578. id: createPartId("t"),
  579. messageID: messageId,
  580. sessionID: sessionId,
  581. type: "tool",
  582. callID: "call_1",
  583. tool: CREATE_WORKFLOW_TOOL_NAME,
  584. state,
  585. },
  586. ],
  587. } as unknown as MessageWithParts;
  588. }