| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541 |
- /* eslint-disable max-lines -- Bot service 的共享测试桩集中维护协议、任务和模型 registry 能力。 */
- import { afterEach, vi } from "vitest";
- import type {
- ZCodeConfigOption,
- BotsConfigFile,
- BotsStateFile,
- Locale,
- ModelSelection,
- ZCodeTaskMode,
- ZCodeSessionSettingsState,
- } from "@zcode/shared";
- import {
- ZCODE_MODEL_REASONING_SEPARATOR,
- ZCODE_PROTOCOL_NAME,
- ZCODE_PROTOCOL_VERSION,
- botsConfigFileSchema,
- } from "@zcode/shared";
- export { botsConfigFileSchema };
- import type { IZCodeSessionService } from "../src/zcode-session/zcodeSession.js";
- import type { IZCodeTaskService } from "../src/session/zcodeTaskService.js";
- import type { IBroadcastService } from "../src/broadcast/broadcast.js";
- import type { ICredentialService } from "../src/credential/credential.js";
- import type { ISettingService } from "../src/setting/setting.js";
- import type { VirtualProject } from "../src/project/contract.js";
- import { remoteHostIdFromWorkspaceIdentity } from "@zcode/shared";
- import { createBotsService as createBotsServiceImpl } from "../src/bots/botsService.js";
- afterEach(() => {
- vi.unstubAllGlobals();
- });
- export const defaultUserCommands = {
- status: true,
- new: true,
- workspace: true,
- model: true,
- thoughtLevel: true,
- sandboxMode: true,
- approvalPolicy: true,
- reply: true,
- };
- export function createMemoryRepo(config: BotsConfigFile, state?: BotsStateFile) {
- let currentConfig = config;
- let currentState = state ?? { version: 3 as const, bots: {} };
- return {
- async readConfig() {
- return currentConfig;
- },
- async writeConfig(nextConfig: BotsConfigFile) {
- currentConfig = nextConfig;
- return currentConfig;
- },
- async readState() {
- return currentState;
- },
- async writeState(nextState: BotsStateFile) {
- currentState = nextState;
- return currentState;
- },
- async updateContext(
- botId: string,
- update: (
- current: BotsStateFile["bots"][string] | undefined,
- ) => BotsStateFile["bots"][string] | undefined,
- ) {
- const next = update(currentState.bots[botId]);
- if (next) currentState.bots[botId] = next;
- else delete currentState.bots[botId];
- return next;
- },
- };
- }
- export function createLegacyTaskService(): IZCodeTaskService {
- return {
- listTasks: vi.fn(async () => []),
- listDeletedTaskIds: vi.fn(async () => []),
- createTask: vi.fn(async () => ({
- taskId: "task-1",
- title: "Task 1",
- workspacePath: "/tmp/workspace",
- workspaceIdentity: "remote:server:test-owner:/tmp/workspace",
- provider: "glm",
- })),
- sendPrompt: vi.fn(async () => undefined),
- setMode: vi.fn(async () => undefined),
- setConfigOption: vi.fn(async () => []),
- setModel: vi.fn(async () => []),
- getTaskConfigOptions: vi.fn(async () => []),
- getTaskModelSelection: vi.fn(async () => ({
- providerId: "glm",
- modelId: "glm-4.6",
- options: { reasoningLevel: "high" },
- })),
- getTaskSnapshot: vi.fn(async () => null),
- getTaskTokenUsage: vi.fn(async (params: { taskId: string }) => ({
- sessionId: params.taskId,
- totalTokens: 0,
- inputTokens: 0,
- outputTokens: 0,
- reasoningTokens: 0,
- cacheCreationTokens: 0,
- cacheReadTokens: 0,
- modelRequestCount: 0,
- modelErrorCount: 0,
- inputBaselineBySource: {},
- })),
- resumeTask: vi.fn(async () => ({
- taskId: "task-1",
- title: "Task 1",
- workspacePath: "/tmp/workspace",
- workspaceIdentity: "remote:server:test-owner:/tmp/workspace",
- provider: "glm",
- })),
- switchAgent: vi.fn(async () => ({
- meta: {
- taskId: "task-1",
- title: "Task 1",
- workspacePath: "/tmp/workspace",
- workspaceIdentity: "remote:server:test-owner:/tmp/workspace",
- provider: "glm",
- },
- provider: "glm",
- sessionId: "session-1",
- reusedBinding: false,
- })),
- respondPermission: vi.fn(async () => true),
- respondElicitation: vi.fn(async () => true),
- stopGeneration: vi.fn(async () => undefined),
- onDynamicStreamEvent: vi.fn(() => () => ({ dispose() {} })),
- } as unknown as IZCodeTaskService;
- }
- export function createCredentialService(values: Record<string, string> = {}): ICredentialService {
- return {
- load: vi.fn(async (key: string) => values[key] ?? null),
- save: vi.fn(async (key: string, value: string) => {
- values[key] = value;
- }),
- delete: vi.fn(async (key: string) => {
- delete values[key];
- }),
- };
- }
- export function createBroadcastService(): IBroadcastService {
- return {
- send: vi.fn(async () => undefined),
- onMessage: vi.fn(),
- } as unknown as IBroadcastService;
- }
- export function createSettingService(settings: {
- recentProjects?: string[];
- lastWorkspaceSession?: Array<
- | { kind: "local"; workspacePath: string }
- | (Record<string, unknown> & {
- kind: "remote";
- workspacePath: string;
- workspaceIdentity?: string;
- })
- >;
- locale?: Locale;
- enabledBuiltinAgentCliProviders?: Array<"claude" | "opencode" | "gemini" | "codex" | "glm">;
- }): ISettingService {
- return {
- get: vi.fn(async () => ({
- recentProjects: settings.recentProjects ?? [],
- lastWorkspaceSession: settings.lastWorkspaceSession ?? [],
- locale: settings.locale ?? "en-US",
- enabledBuiltinAgentCliProviders: settings.enabledBuiltinAgentCliProviders ?? ["glm"],
- })),
- update: vi.fn(async () => undefined),
- updateDataBaseDir: vi.fn(async () => undefined),
- } as unknown as ISettingService;
- }
- export function createModelSelectionService(providers: readonly TestModelSelectionProvider[] = []) {
- return {
- getView: vi.fn(async (input?: { selection: ModelSelection | null }) => ({
- revision: 1,
- // 服务桩显式支持按输入返回结果;账号转换/失效分支由各自用例注入权威结果。
- ...(input ? { effectiveSelection: input.selection } : {}),
- providers: providers.map((provider) => ({
- providerId: provider.id,
- // 名称是 View 元数据;放进旧 config.label 会让展示测试错误回落到 ID。
- providerName: provider.name,
- config: {},
- models: provider.models.map((model) => ({
- modelId: typeof model === "string" ? model : model.id,
- config: typeof model === "string" ? {} : (model.config ?? {}),
- })),
- })),
- preferredSelection: providers[0]?.models[0]
- ? {
- providerId: providers[0].id,
- modelId:
- typeof providers[0].models[0] === "string"
- ? providers[0].models[0]
- : providers[0].models[0].id,
- }
- : undefined,
- })),
- };
- }
- export interface TestModelSelectionProvider {
- id: string;
- models: readonly (string | { id: string; config?: Record<string, unknown> })[];
- name: string;
- }
- function parseModelSelectionForTest(value: string): ModelSelection {
- const separatorIndex = value.indexOf("/");
- if (separatorIndex <= 0) {
- return { providerId: "glm", modelId: value || "default" };
- }
- const providerId = value.slice(0, separatorIndex);
- const rawModelId = value.slice(separatorIndex + 1);
- const reasoningSeparatorIndex = rawModelId.indexOf(ZCODE_MODEL_REASONING_SEPARATOR);
- if (reasoningSeparatorIndex <= 0 || reasoningSeparatorIndex >= rawModelId.length - 1) {
- return { providerId, modelId: rawModelId };
- }
- return {
- providerId,
- modelId: rawModelId.slice(0, reasoningSeparatorIndex),
- variant: rawModelId.slice(reasoningSeparatorIndex + 1),
- };
- }
- function normalizeZCodeModeForTest(value: unknown): ZCodeTaskMode {
- switch (value) {
- case "plan":
- case "build":
- case "yolo":
- case "auto":
- return value;
- case "read-only":
- return "plan";
- case "full-access":
- case "agent-full-access":
- return "yolo";
- default:
- return "build";
- }
- }
- function readSelectOption(
- configOptions: readonly ZCodeConfigOption[],
- category: string,
- ): (ZCodeConfigOption & { type: "select" }) | undefined {
- return configOptions.find(
- (option): option is ZCodeConfigOption & { type: "select" } =>
- option.type === "select" && (option.category === category || option.id === category),
- );
- }
- export function createZCodeSessionSettingsFromConfigOptions(
- configOptions: readonly ZCodeConfigOption[] = [],
- ): ZCodeSessionSettingsState {
- const modelOption = readSelectOption(configOptions, "model");
- const currentModelValue =
- typeof modelOption?.currentValue === "string"
- ? modelOption.currentValue
- : (modelOption?.options?.[0]?.value ?? "glm/default");
- const currentModel = parseModelSelectionForTest(currentModelValue);
- const modelOptions = modelOption?.options?.length
- ? modelOption.options
- : [{ value: currentModelValue, name: currentModel.modelId }];
- const thoughtOption = readSelectOption(configOptions, "thought_level");
- const modeOption = readSelectOption(configOptions, "mode");
- return {
- model: {
- current: currentModel,
- available: modelOptions.map((option) => ({
- ref: parseModelSelectionForTest(option.value),
- label: option.name ?? option.value,
- description: option.description,
- })),
- lastUsed: currentModel,
- },
- thoughtLevel: {
- enabled: Boolean(thoughtOption),
- current:
- typeof thoughtOption?.currentValue === "string"
- ? thoughtOption.currentValue
- : thoughtOption?.options?.[0]?.value,
- available:
- thoughtOption?.options?.map((option) => ({
- value: option.value,
- label: option.name ?? option.value,
- description: option.description,
- })) ?? [],
- },
- mode: {
- current: normalizeZCodeModeForTest(modeOption?.currentValue),
- },
- permission: {
- mode: normalizeZCodeModeForTest(modeOption?.currentValue),
- },
- };
- }
- function createZCodeWorkspaceState(
- settings: ZCodeSessionSettingsState = createZCodeSessionSettingsFromConfigOptions(),
- ): ZCodeWorkspaceStateSnapshot {
- return {
- workspace: {
- workspacePath: "/tmp/workspace",
- workspaceIdentity: "remote:server:test-owner:/tmp/workspace",
- workspaceKey: "remote:server:test-owner:/tmp/workspace",
- },
- settings,
- };
- }
- export function createZCodeSessionService(
- settings: ZCodeSessionSettingsState = createZCodeSessionSettingsFromConfigOptions(),
- ): IZCodeSessionService {
- const workspaceState = createZCodeWorkspaceState(settings);
- return {
- initializeWorkspace: vi.fn(async () => ({
- available: true,
- workspaceKey: workspaceState.workspace.workspaceKey,
- protocolName: ZCODE_PROTOCOL_NAME,
- protocolVersion: ZCODE_PROTOCOL_VERSION,
- transportKind: "stdio",
- })),
- readWorkspacePresentation: vi.fn(async () => ({
- workspace: workspaceState.workspace,
- mode: workspaceState.settings.mode.current,
- slashCommands: [],
- })),
- updateProviderRegistry: vi.fn(async () => ({
- applied: true,
- revision: "test-provider-registry",
- })),
- } as unknown as IZCodeSessionService;
- }
- export function createBotsService(
- deps: Omit<
- Parameters<typeof createBotsServiceImpl>[0],
- "zcodeSessionService" | "zcodeTaskService" | "projectService"
- > & {
- zcodeTaskService?: IZCodeTaskService;
- /** 旧测试名保留为别名;真实注入的是 ZCode task service。 */
- legacyTaskService?: IZCodeTaskService;
- zcodeSessionService?: IZCodeSessionService;
- projectService?: Parameters<typeof createBotsServiceImpl>[0]["projectService"];
- },
- ): ReturnType<typeof createBotsServiceImpl> {
- const {
- legacyTaskService,
- zcodeTaskService: providedZCodeTaskService,
- zcodeSessionService: _providedZCodeSessionService,
- ...rest
- } = deps;
- const zcodeTaskService =
- providedZCodeTaskService ?? legacyTaskService ?? createLegacyTaskService();
- const modelSelectionService =
- deps.modelSelectionService ??
- createModelSelectionService([{ id: "glm", name: "GLM", models: ["default"] }]);
- return createBotsServiceImpl({
- ...createBotProjectServices(undefined, (target) => zcodeTaskService.listTasks(target)),
- settingService: createSettingService({
- locale: "zh-CN",
- lastWorkspaceSession: [
- {
- kind: "remote",
- workspacePath: "/tmp/workspace",
- workspaceIdentity: "remote:server:test-owner:/tmp/workspace",
- },
- ],
- }),
- remoteWorkspaceService: {
- isConnected: vi.fn(async () => true),
- ensureConnected: vi.fn(async () => ({ ok: true })),
- getZCodeTaskService: vi.fn(async () => zcodeTaskService),
- getModelSelectionService: vi.fn(async () => modelSelectionService),
- },
- modelSelectionService,
- ...rest,
- zcodeTaskService,
- });
- }
- /** 显式项目服务夹具;生产候选不得从 settings/tab 历史恢复。 */
- export function createBotProjectServices(
- workspaces = [
- {
- workspacePath: "/tmp/workspace",
- workspaceIdentity: "remote:server:test-owner:/tmp/workspace",
- } as { workspacePath: string; workspaceIdentity?: string },
- ],
- readTasks?: (target: {
- workspacePath: string;
- workspaceIdentity?: string;
- }) => ReturnType<IZCodeTaskService["listTasks"]>,
- ) {
- const projects: VirtualProject[] = workspaces.map((workspace, index) => ({
- id: `project-${index}`,
- hostId: workspace.workspaceIdentity
- ? remoteHostIdFromWorkspaceIdentity(workspace.workspaceIdentity)!
- : "local",
- name: workspace.workspacePath.split("/").at(-1)!,
- roots: [{ rootPath: workspace.workspacePath, position: 0, isPrimary: true }],
- nameOverridden: false,
- position: index,
- pinned: false,
- deleted: false,
- createdAt: 1,
- updatedAt: 1,
- }));
- const hosts = [
- ...new Set(projects.map((project) => project.hostId).filter((id) => id !== "local")),
- ];
- return {
- projectService: {
- readTree: vi.fn(async (input?: { hostId?: string }) => ({
- projects: projects.filter((project) => project.hostId === (input?.hostId ?? "local")),
- tasks: (
- await Promise.all(
- projects.map(async (project, index) =>
- project.hostId !== (input?.hostId ?? "local")
- ? []
- : ((await readTasks?.(workspaces[index]!)) ?? []).map((task) => ({
- ...task,
- projectId: project.id,
- hostId: project.hostId,
- pinned: false,
- archived: false,
- })),
- ),
- )
- ).flat(),
- })),
- readProjects: vi.fn(async (input?: { hostId?: string }) =>
- projects.filter((project) => project.hostId === (input?.hostId ?? "local")),
- ),
- prepareSession: vi.fn(async (input?: { projectId?: string; hostId?: string }) => {
- const index = projects.findIndex(
- (project) =>
- project.id === input?.projectId && project.hostId === (input?.hostId ?? "local"),
- );
- if (index < 0) throw new Error("project missing");
- return { ...workspaces[index]!, projectId: projects[index]!.id, additionalDirectories: [] };
- }),
- },
- remoteProjectService: {
- readDirectory: vi.fn(async () => ({
- hosts: hosts.map((id) => ({
- id,
- membershipId: id,
- kind: "server" as const,
- target: null,
- position: 0,
- connectionStatus: "online" as const,
- })),
- entries: projects
- .filter((project) => project.hostId !== "local")
- .map((project) => ({
- id: project.id,
- projectId: project.id,
- hostId: project.hostId,
- name: project.name,
- roots: project.roots,
- legacyWorkspace: null,
- lastSyncedAt: 1,
- })),
- })),
- },
- };
- }
- export const baseConfig: BotsConfigFile = {
- version: 3,
- bots: [
- {
- id: "webhook-1",
- name: "Webhook",
- provider: "webhook",
- enabled: true,
- webhookSecretRef: "secret-1",
- allowedWorkspaces: ["*"],
- allowedCommands: defaultUserCommands,
- currentOptions: {},
- replyMode: "assistant_changes",
- },
- ],
- };
- export const telegramConfig: BotsConfigFile = {
- ...baseConfig,
- bots: [
- {
- ...baseConfig.bots[0]!,
- id: "telegram-1",
- name: "Telegram",
- provider: "telegram",
- credentialRef: "telegram-token",
- webhookSecretRef: undefined,
- providerUserId: "user-1",
- allowedWorkspaces: ["*"],
- },
- ],
- };
- export const feishuConfig: BotsConfigFile = {
- ...baseConfig,
- bots: [
- {
- ...baseConfig.bots[0]!,
- id: "feishu-1",
- name: "Feishu",
- provider: "feishu",
- credentialRef: "feishu-secret",
- webhookSecretRef: undefined,
- feishuAppId: "cli_xxx",
- providerUserId: "ou_user",
- allowedWorkspaces: ["*"],
- },
- ],
- };
- export const weixinConfig: BotsConfigFile = {
- ...baseConfig,
- bots: [
- {
- ...baseConfig.bots[0]!,
- id: "weixin-1",
- name: "Weixin",
- provider: "weixin",
- credentialRef: "weixin-token",
- webhookSecretRef: undefined,
- allowedWorkspaces: ["*"],
- },
- ],
- };
|