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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  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: 1, reasoningLevel: "low" });
  157. });
  158. it("does not raise the connectivity output budget above the model limit", async () => {
  159. let boundOptions: ModelOptions | undefined;
  160. const model = createStreamingModel({
  161. maxOutputTokens: 4_096,
  162. onBind: (options) => {
  163. boundOptions = options;
  164. },
  165. streamEvents: (async function* () {
  166. yield { type: "finish", finishReason: "stop" };
  167. })(),
  168. });
  169. const runtime = createRuntimeWithModel(model);
  170. await runtime.testModelConnectivity({
  171. selection: { providerId: "test-provider", modelId: "glm-test" },
  172. });
  173. expect(boundOptions).toEqual({ maxOutputTokens: 1, reasoningLevel: "disabled" });
  174. });
  175. it("uses the disabled baseline when the model does not reason", async () => {
  176. let boundOptions: ModelOptions | undefined;
  177. const model = createStreamingModel({
  178. onBind: (options) => {
  179. boundOptions = options;
  180. },
  181. streamEvents: (async function* () {
  182. yield { type: "finish", finishReason: "stop" };
  183. })(),
  184. });
  185. const runtime = createRuntimeWithModel(model);
  186. await runtime.testModelConnectivity({
  187. selection: { providerId: "test-provider", modelId: "glm-test" },
  188. });
  189. expect(boundOptions).toEqual({ maxOutputTokens: 1, reasoningLevel: "disabled" });
  190. });
  191. it.each(["stop", "length"])("accepts %s without any response text", async (finishReason) => {
  192. const model = createStreamingModel({
  193. streamEvents: (async function* () {
  194. yield { type: "start" };
  195. yield { type: "finish", finishReason, usage: { outputTokens: 1 } };
  196. })(),
  197. });
  198. await expect(
  199. createRuntimeWithModel(model).testModelConnectivity({
  200. selection: { providerId: "test-provider", modelId: "glm-test" },
  201. }),
  202. ).resolves.toBeUndefined();
  203. });
  204. it.each([
  205. "test-provider",
  206. "account:bigmodel-start-plan",
  207. "account:bigmodel-individual-coding-plan",
  208. "account:zai-team-coding-plan",
  209. ])("keeps the exact connectivity whitelist messages for %s", async (providerId) => {
  210. let receivedRequest: ModelRequest | undefined;
  211. const model = createStreamingModel({
  212. onRequest: (request) => {
  213. receivedRequest = request;
  214. },
  215. streamEvents: (async function* () {
  216. yield { type: "finish", finishReason: "stop" };
  217. })(),
  218. });
  219. const runtime = createRuntimeWithModel(model);
  220. await runtime.testModelConnectivity({
  221. selection: { providerId, modelId: "glm-test" },
  222. });
  223. expect(receivedRequest?.messages).toEqual([
  224. { role: "system", content: "You are ZCode connectivity probe." },
  225. { role: "user", content: "hi" },
  226. ]);
  227. expect(receivedRequest?.tools).toBeUndefined();
  228. expect(Object.keys(receivedRequest!).sort()).toEqual(["abortSignal", "messages"]);
  229. });
  230. it.each(["throw", "error-event", "no-finish"])(
  231. "does not report connectivity success for %s",
  232. async (failure) => {
  233. const model = createStreamingModel({
  234. ...(failure === "throw" ? { streamError: new Error("probe rejected") } : {}),
  235. streamEvents: (async function* () {
  236. if (failure === "error-event")
  237. yield { type: "error", error: new Error("probe rejected") };
  238. else yield { type: "text_delta", text: "partial" };
  239. })(),
  240. });
  241. await expect(
  242. createRuntimeWithModel(model).testModelConnectivity({
  243. selection: { providerId: "test-provider", modelId: "glm-test" },
  244. }),
  245. ).rejects.toThrow(failure === "no-finish" ? "finish" : "probe rejected");
  246. },
  247. );
  248. it("keeps non-stream generateText for the git commit message querySource", async () => {
  249. let streamCalled = false;
  250. let boundOptions: ModelOptions | undefined;
  251. const model = createStreamingModel({
  252. onBind: (options) => {
  253. boundOptions = options;
  254. },
  255. });
  256. model.streamText = ((request: ModelRequest) => {
  257. void request;
  258. streamCalled = true;
  259. throw new Error("streamText should not be called");
  260. }) as never;
  261. model.generateText = async () => ({
  262. finishReason: "stop",
  263. text: "fix: commit message",
  264. usage: { inputTokens: 1, outputTokens: 1, totalTokens: 2 },
  265. });
  266. const runtime = createRuntimeWithModel(model);
  267. const result = await runtime.generateWorkspaceText({
  268. selection: { providerId: "test-provider", modelId: "glm-test" },
  269. prompt: "Generate a commit message",
  270. querySource: "git_commit_message",
  271. maxOutputTokens: 256,
  272. });
  273. expect(streamCalled).toBe(false);
  274. expect(result.text).toBe("fix: commit message");
  275. expect(boundOptions).toEqual({ maxOutputTokens: 5_000, reasoningLevel: "disabled" });
  276. });
  277. });