fake-zcode-app.ts 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215
  1. import type { ExecutionShellSelection, SessionId } from "@zcode/contracts";
  2. import type { ZCodeApp, ZCodeAppOptions } from "../../src/app/types.js";
  3. export function createFakeApp(
  4. options?: ZCodeAppOptions,
  5. overrides: Partial<ZCodeApp> = {},
  6. ): ZCodeApp {
  7. const sessionId = options?.sessionId ?? ("sess_test" as SessionId);
  8. const traceId = options?.traceContext?.traceId ?? ("trace_test" as never);
  9. let mode = options?.runtimeConfig?.mode ?? "build";
  10. let model = options?.runtimeConfig?.modelSelection
  11. ? `${options.runtimeConfig.modelSelection.providerId}/${options.runtimeConfig.modelSelection.modelId}`
  12. : "glm/glm-4.6";
  13. let thoughtLevel = options?.runtimeConfig?.modelSelection?.options?.reasoningLevel ?? "medium";
  14. let bashShellSelection = options?.runtimeConfig?.bashShellSelection;
  15. let runtimeContextWindow = options?.runtimeConfig?.contextWindow ?? 128_000;
  16. let foregroundPromotionLeaseId: string | undefined;
  17. const modelProperties = {
  18. inputFormat: {
  19. supportsText: true,
  20. supportsImage: false,
  21. supportsVideo: false,
  22. supportsAudio: false,
  23. supportsPdf: false,
  24. },
  25. outputFormat: { supportsText: true },
  26. } as const;
  27. const baseModels = [
  28. {
  29. ref: { providerId: "glm", modelId: "glm-4.6" },
  30. label: "GLM 4.6",
  31. providerLabel: "glm",
  32. properties: modelProperties,
  33. },
  34. {
  35. ref: { providerId: "glm", modelId: "glm-4-air" },
  36. label: "GLM 4 Air",
  37. providerLabel: "glm",
  38. properties: modelProperties,
  39. },
  40. ];
  41. let models = [...baseModels];
  42. let thoughtLevelsByModel = new Map<string, string[]>([
  43. ["glm/glm-4.6", ["medium", "deep"]],
  44. ["glm/glm-4-air", ["medium", "deep"]],
  45. ]);
  46. return {
  47. clearTarget: async () => false,
  48. close: async () => {},
  49. connectMcpServer: async () => {
  50. throw new Error("MCP is not available in fake app");
  51. },
  52. continueActiveTarget: async () => null,
  53. disconnectMcpServer: async () => undefined,
  54. forkFromCheckpoint: async () => {
  55. throw new Error("Fork is not available in fake app");
  56. },
  57. getLocale: () => "en-US",
  58. getMode: () => mode,
  59. getModel: () => model,
  60. getTheme: () => "auto",
  61. getDefaultThoughtLevel: () => thoughtLevelsByModel.get(model)?.[0],
  62. getThoughtLevel: () => thoughtLevel,
  63. generateWorkspaceText: async () => {
  64. throw new Error("Workspace text generation is not available in fake app");
  65. },
  66. testModelConnectivity: async () => {
  67. throw new Error("Model connectivity testing is not available in fake app");
  68. },
  69. listCheckpoints: async () => [],
  70. listMcpServers: async () => ({}),
  71. listModels: () => models,
  72. listPlugins: async () => ({ loaded: [], failed: [] }) as never,
  73. listThoughtLevels: () => thoughtLevelsByModel.get(model) ?? [],
  74. loadSessionTranscript: async () => [],
  75. readToolResultArtifact: async (uri) => ({
  76. bytes: 0,
  77. content: "",
  78. contentType: "text/plain",
  79. uri,
  80. }),
  81. readTodos: async () => [],
  82. readTarget: async () => null,
  83. recallPreviousInputHistory: async () => null,
  84. recordInputHistory: async () => null,
  85. resume: async () => ({
  86. directory: options?.runtimeConfig?.workingDirectory ?? "/workspace/app",
  87. interruptedToolCount: 0,
  88. messageCount: 0,
  89. partCount: 0,
  90. persistedMessagesReloadRequired: false,
  91. restoredMessages: [],
  92. traceId,
  93. }),
  94. runtime: {
  95. beginShutdown: () => {},
  96. acquireForegroundPromotionLease: ({ leaseId }) => {
  97. if (foregroundPromotionLeaseId && foregroundPromotionLeaseId !== leaseId) {
  98. return { kind: "conflict", leaseId: foregroundPromotionLeaseId };
  99. }
  100. foregroundPromotionLeaseId = leaseId;
  101. return { kind: "acquired", leaseId };
  102. },
  103. emitModelSelected: async () => undefined,
  104. getProjection: async () =>
  105. ({
  106. activeToolCalls: [],
  107. backgroundTasks: [],
  108. contextUsed: 0,
  109. contextWindow: runtimeContextWindow,
  110. createdAt: new Date(1),
  111. id: sessionId,
  112. mode,
  113. pendingPermissions: [],
  114. pendingSteerInputs: [],
  115. status: "idle",
  116. streamingToolLedger: [],
  117. target: null,
  118. totalTokenCount: 0,
  119. turnCount: 0,
  120. updatedAt: new Date(1),
  121. }) as never,
  122. getActiveTurnInfo: () => undefined,
  123. hasActiveOrQueuedTurnWork: () => false,
  124. hasResidencyBlockingWork: () => false,
  125. hasRunningBackgroundTasks: () => false,
  126. isSessionPersisted: () => false,
  127. getActiveForegroundExecutionId: () => undefined,
  128. getSessionModelSelection: () => {
  129. const [providerId = "", modelId = ""] = model.split("/", 2);
  130. return {
  131. providerId,
  132. modelId,
  133. ...(thoughtLevel ? { options: { reasoningLevel: thoughtLevel } } : {}),
  134. };
  135. },
  136. getSessionShellSelection: () => bashShellSelection,
  137. initializeSessionShellEnvironmentIfNeeded: (selection) => {
  138. if (bashShellSelection) {
  139. return false;
  140. }
  141. bashShellSelection = resolveShellInitializationCandidate(selection);
  142. return true;
  143. },
  144. subscribeEvents: () => () => {},
  145. releaseForegroundPromotionLease: (leaseId) => {
  146. if (foregroundPromotionLeaseId !== leaseId) return false;
  147. foregroundPromotionLeaseId = undefined;
  148. return true;
  149. },
  150. stopActiveForegroundExecution: () => ({ kind: "idle" }),
  151. updateConfig: (patch) => {
  152. if ("contextWindow" in patch) {
  153. runtimeContextWindow = patch.contextWindow ?? 0;
  154. }
  155. },
  156. } as never,
  157. sendInput: async () => ({ kind: "rejected", reason: "no_active_turn" }),
  158. sessionId,
  159. setLocale: async (locale) => ({
  160. configPath: "/tmp/zcode/config.json",
  161. locale: locale === "zh-CN" ? "zh-CN" : "en-US",
  162. previousLocale: "en-US",
  163. requestedLocale: locale,
  164. traceId,
  165. }),
  166. setMode: async (nextMode) => {
  167. const previousMode = mode;
  168. mode = nextMode;
  169. return { mode, previousMode, traceId };
  170. },
  171. setPluginEnabled: async () => {
  172. throw new Error("Plugins are not available in fake app");
  173. },
  174. setTarget: async () => {
  175. throw new Error("Targets are not available in fake app");
  176. },
  177. setModel: async (nextModel) => {
  178. const nextIdentity =
  179. typeof nextModel === "string" ? nextModel : `${nextModel.providerId}/${nextModel.modelId}`;
  180. if (
  181. !models.some((option) => `${option.ref.providerId}/${option.ref.modelId}` === nextIdentity)
  182. ) {
  183. throw new Error(`Unsupported model in fake app: ${nextModel}`);
  184. }
  185. const previousModel = model;
  186. model = nextIdentity;
  187. if (typeof nextModel !== "string") thoughtLevel = nextModel.options?.reasoningLevel ?? "";
  188. return { model, previousModel, traceId };
  189. },
  190. setThoughtLevel: async (level) => {
  191. const previousThoughtLevel = thoughtLevel;
  192. thoughtLevel = level;
  193. return { previousThoughtLevel, thoughtLevel, traceId };
  194. },
  195. steerTurn: async () => ({ kind: "rejected", reason: "no_active_turn" }),
  196. submitPrompt: async () => {
  197. throw new Error("Prompt execution is not available in fake app");
  198. },
  199. traceId,
  200. updateTargetStatus: async () => null,
  201. ...overrides,
  202. } as ZCodeApp;
  203. }
  204. type ShellInitializationCandidate = Parameters<
  205. ZCodeApp["runtime"]["initializeSessionShellEnvironmentIfNeeded"]
  206. >[0];
  207. function resolveShellInitializationCandidate(
  208. candidate: ShellInitializationCandidate,
  209. ): ExecutionShellSelection {
  210. return typeof candidate === "function" ? candidate() : candidate;
  211. }