workspace-generate-text-streaming.test.ts 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  1. import { describe, expect, it } from "vitest";
  2. import { createTestModelSelection } from "./test-model-selection.js";
  3. import type {
  4. Model,
  5. ModelInvocationContext,
  6. ModelOptions,
  7. ModelRequest,
  8. SessionTaskType,
  9. } from "@zcode/contracts";
  10. import { createTestAgentRuntime } from "./test-agent-runtime.js";
  11. import { createSessionId, getCurrentModelInvocationContext } from "@zcode/contracts";
  12. import { createRuntimeModel } from "../src/runtime/methods/runtime-model.js";
  13. import { createTestSessionEventStore } from "./test-event-store.js";
  14. import { createTestModelFormatProperties } from "./test-runtime-model.js";
  15. function createStreamingModel(overrides?: {
  16. streamEvents?: AsyncIterable<{ type: string; [key: string]: unknown }>;
  17. streamError?: Error;
  18. reasoningLevels?: readonly string[];
  19. maxOutputTokens?: number;
  20. onBind?: (options: ModelOptions | undefined) => void;
  21. onRequest?: (request: ModelRequest) => void;
  22. }): Model {
  23. const model: Model = {
  24. providerId: "test-provider",
  25. modelId: "glm-test",
  26. properties: {
  27. contextWindow: 128_000,
  28. ...createTestModelFormatProperties(),
  29. supportsMidConversationSystem: false,
  30. supportsNativeWebSearch: false,
  31. supportsJsonSchemaOutput: false,
  32. supportsToolCall: true,
  33. },
  34. optionSpecs: {
  35. reasoningLevel: {
  36. values: overrides?.reasoningLevels ?? ["disabled"],
  37. },
  38. maxOutputTokens: { max: overrides?.maxOutputTokens ?? 128_000 },
  39. },
  40. options: {
  41. maxOutputTokens: 128_000,
  42. reasoningLevel: overrides?.reasoningLevels?.at(-1) ?? "disabled",
  43. },
  44. bind(options) {
  45. overrides?.onBind?.(options);
  46. return this;
  47. },
  48. async generateText(_request: ModelRequest) {
  49. throw new Error("generateText should not be called");
  50. },
  51. streamText(request: ModelRequest) {
  52. overrides?.onRequest?.(request);
  53. if (overrides?.streamError) {
  54. return (async function* () {
  55. yield { type: "start" };
  56. throw overrides.streamError;
  57. })();
  58. }
  59. const events = overrides?.streamEvents ?? [];
  60. return (async function* () {
  61. yield* events as AsyncIterable<{ type: string; [key: string]: unknown }>;
  62. })();
  63. },
  64. } as unknown as Model;
  65. return model;
  66. }
  67. function createRuntimeWithModel(model: Model, taskType: SessionTaskType = "interactive") {
  68. return createTestAgentRuntime(
  69. createSessionId("workspace-generate-text-streaming"),
  70. {
  71. taskType,
  72. modelSelection: createTestModelSelection(
  73. createTestModelSelection("test-provider/glm-test", {}),
  74. ),
  75. },
  76. {
  77. eventStore: createTestSessionEventStore(),
  78. modelFactory: () => model,
  79. },
  80. );
  81. }
  82. describe("workspace generateText streaming aggregation", () => {
  83. it.each([
  84. ["interactive", "main"],
  85. ["subagent_child", "subagent"],
  86. ["selection_side_chat", "side_chat"],
  87. ] as const)(
  88. "workspace calls borrowing a %s runtime stay other without reclassifying session requests",
  89. async (taskType, expectedSessionType) => {
  90. const seen: (ModelInvocationContext | undefined)[] = [];
  91. const model = createStreamingModel({
  92. onRequest: () => seen.push(getCurrentModelInvocationContext()),
  93. streamEvents: (async function* () {
  94. yield { type: "finish", finishReason: "stop" };
  95. })(),
  96. });
  97. model.generateText = async () => {
  98. seen.push(getCurrentModelInvocationContext());
  99. return { text: "ok", finishReason: "stop" };
  100. };
  101. const runtime = createRuntimeWithModel(model, taskType);
  102. const selection = { providerId: "test-provider", modelId: "glm-test" };
  103. await Promise.all([
  104. runtime.testModelConnectivity({ selection }),
  105. runtime.generateWorkspaceText({
  106. selection,
  107. prompt: "Write a commit message",
  108. querySource: "git_commit_message",
  109. }),
  110. createRuntimeModel(runtime as never, { selection }).generateText({ messages: [] }),
  111. ]);
  112. expect(seen).toHaveLength(3);
  113. expect(
  114. seen.find((context) => context?.metadata?.querySource === "provider_settings_connectivity")
  115. ?.modelRequestSessionType,
  116. ).toBe("other");
  117. expect(
  118. seen.find((context) => context?.metadata?.querySource === "git_commit_message")
  119. ?.modelRequestSessionType,
  120. ).toBe("other");
  121. expect(seen.find((context) => !context?.metadata?.querySource)?.modelRequestSessionType).toBe(
  122. expectedSessionType,
  123. );
  124. },
  125. );
  126. it("connectivity test creates the selected formal Model and consumes streamText", async () => {
  127. let streamConsumed = false;
  128. async function* events() {
  129. yield { type: "start" };
  130. yield { type: "text_delta", text: "ok" };
  131. yield { type: "finish", finishReason: "stop", usage: { totalTokens: 1 } };
  132. streamConsumed = true;
  133. }
  134. const model = createStreamingModel({ streamEvents: events() });
  135. const runtime = createRuntimeWithModel(model);
  136. await runtime.testModelConnectivity({
  137. selection: { providerId: "test-provider", modelId: "glm-test" },
  138. });
  139. expect(streamConsumed).toBe(true);
  140. });
  141. it("binds the lowest public reasoning level for connectivity tests", async () => {
  142. let boundOptions: ModelOptions | undefined;
  143. const model = createStreamingModel({
  144. reasoningLevels: ["low", "high", "max"],
  145. onBind: (options) => {
  146. boundOptions = options;
  147. },
  148. streamEvents: (async function* () {
  149. yield { type: "finish", finishReason: "stop" };
  150. })(),
  151. });
  152. const runtime = createRuntimeWithModel(model);
  153. await runtime.testModelConnectivity({
  154. selection: { providerId: "test-provider", modelId: "glm-test" },
  155. });
  156. expect(boundOptions).toEqual({ maxOutputTokens: 512, reasoningLevel: "low" });
  157. });
  158. it.each([
  159. { maxOutputTokens: 1, expectedBudget: 1 },
  160. { maxOutputTokens: 256, expectedBudget: 256 },
  161. { maxOutputTokens: 512, expectedBudget: 512 },
  162. { maxOutputTokens: 1024, expectedBudget: 512 },
  163. ])(
  164. "respects output cap $maxOutputTokens with reasoning disabled",
  165. async ({ maxOutputTokens, expectedBudget }) => {
  166. let boundOptions: ModelOptions | undefined;
  167. const model = createStreamingModel({
  168. maxOutputTokens,
  169. onBind: (options) => {
  170. boundOptions = options;
  171. },
  172. streamEvents: (async function* () {
  173. yield { type: "finish", finishReason: "stop" };
  174. })(),
  175. });
  176. const runtime = createRuntimeWithModel(model);
  177. await runtime.testModelConnectivity({
  178. selection: { providerId: "test-provider", modelId: "glm-test" },
  179. });
  180. expect(boundOptions).toEqual({ maxOutputTokens: expectedBudget, reasoningLevel: "disabled" });
  181. },
  182. );
  183. it.each(["stop", "length"])("accepts %s without any response text", async (finishReason) => {
  184. const model = createStreamingModel({
  185. streamEvents: (async function* () {
  186. yield { type: "start" };
  187. yield { type: "finish", finishReason, usage: { outputTokens: 1 } };
  188. })(),
  189. });
  190. await expect(
  191. createRuntimeWithModel(model).testModelConnectivity({
  192. selection: { providerId: "test-provider", modelId: "glm-test" },
  193. }),
  194. ).resolves.toBeUndefined();
  195. });
  196. it.each([
  197. "test-provider",
  198. "account:bigmodel-start-plan",
  199. "account:bigmodel-individual-coding-plan",
  200. "account:zai-team-coding-plan",
  201. ])("keeps the exact connectivity whitelist messages for %s", async (providerId) => {
  202. let receivedRequest: ModelRequest | undefined;
  203. const model = createStreamingModel({
  204. onRequest: (request) => {
  205. receivedRequest = request;
  206. },
  207. streamEvents: (async function* () {
  208. yield { type: "finish", finishReason: "stop" };
  209. })(),
  210. });
  211. const runtime = createRuntimeWithModel(model);
  212. await runtime.testModelConnectivity({
  213. selection: { providerId, modelId: "glm-test" },
  214. });
  215. expect(receivedRequest?.messages).toEqual([
  216. { role: "system", content: "You are ZCode connectivity probe." },
  217. { role: "user", content: "hi" },
  218. ]);
  219. expect(receivedRequest?.tools).toBeUndefined();
  220. expect(Object.keys(receivedRequest!).sort()).toEqual(["abortSignal", "messages"]);
  221. });
  222. it.each(["throw", "error-event", "no-finish"])(
  223. "does not report connectivity success for %s",
  224. async (failure) => {
  225. const model = createStreamingModel({
  226. ...(failure === "throw" ? { streamError: new Error("probe rejected") } : {}),
  227. streamEvents: (async function* () {
  228. if (failure === "error-event")
  229. yield { type: "error", error: new Error("probe rejected") };
  230. else yield { type: "text_delta", text: "partial" };
  231. })(),
  232. });
  233. await expect(
  234. createRuntimeWithModel(model).testModelConnectivity({
  235. selection: { providerId: "test-provider", modelId: "glm-test" },
  236. }),
  237. ).rejects.toThrow(failure === "no-finish" ? "finish" : "probe rejected");
  238. },
  239. );
  240. it("keeps non-stream generateText for the git commit message querySource", async () => {
  241. let streamCalled = false;
  242. let boundOptions: ModelOptions | undefined;
  243. const model = createStreamingModel({
  244. onBind: (options) => {
  245. boundOptions = options;
  246. },
  247. });
  248. model.streamText = ((request: ModelRequest) => {
  249. void request;
  250. streamCalled = true;
  251. throw new Error("streamText should not be called");
  252. }) as never;
  253. model.generateText = async () => ({
  254. finishReason: "stop",
  255. text: "fix: commit message",
  256. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  257. });
  258. const runtime = createRuntimeWithModel(model);
  259. const result = await runtime.generateWorkspaceText({
  260. selection: { providerId: "test-provider", modelId: "glm-test" },
  261. prompt: "Generate a commit message",
  262. querySource: "git_commit_message",
  263. maxOutputTokens: 256,
  264. });
  265. expect(streamCalled).toBe(false);
  266. expect(result.text).toBe("fix: commit message");
  267. expect(boundOptions).toEqual({ maxOutputTokens: 5_000, reasoningLevel: "disabled" });
  268. });
  269. });