model-provider-restart.ts 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  1. import { DatabaseSync } from "node:sqlite";
  2. import { mkdir, readFile, readdir, writeFile } from "node:fs/promises";
  3. import { dirname, join } from "node:path";
  4. import {
  5. BUILTIN_MODEL_PROVIDER_IDS,
  6. BUILTIN_PROVIDER_TEMPLATE_IDS,
  7. ZCODE_AGENT_PROVIDER,
  8. encodeCustomModelValue,
  9. type ProviderFamilyConnectionSelection,
  10. } from "@zcode/shared";
  11. import { TID_CHAT_MODEL_SELECT_TRIGGER, TID_V4_MODEL_CONFIG } from "@zcode/shared/test-ids";
  12. import { getE2EAppDataPaths } from "./desktop-app.js";
  13. import { getUpstreamApiKey } from "./upstream-provider.js";
  14. import { waitForSqliteTable } from "./e2e-sqlite-readiness.js";
  15. import { resolveSeededReplayBaseUrl } from "./custom-openai-provider-store.js";
  16. import {
  17. restartIntoWorkspacePreservingProfile as restartIntoWorkspacePreservingProfileFixture,
  18. restartIntoWorkspaceRestoringPreferences,
  19. type ModelProviderRestartOptions,
  20. } from "./model-provider-restart-runtime.js";
  21. import {
  22. seedPersonalProviderConfig,
  23. type PersonalProviderConfigSeed,
  24. type SeedReplayProviderModel,
  25. } from "./model-provider-restart-config.js";
  26. import { getV4DraftThoughtState } from "./v4-conversation.js";
  27. const paths = getE2EAppDataPaths();
  28. const SETTINGS_FILE = join(paths.appDataDir, "setting.json");
  29. const CREDENTIALS_FILE = paths.credentialsFile;
  30. const MODEL_SELECTION_RECENT_KEY_PREFIX = "zcode-model-selection-recent-v1";
  31. export { seedTurboAgentStartupModel } from "./model-provider-restart-runtime.js";
  32. export const E2E_BIGMODEL_PLAN_PROVIDER_ID = BUILTIN_MODEL_PROVIDER_IDS.bigmodelTeamCodingPlan;
  33. export const E2E_BIGMODEL_START_PROVIDER_ID = BUILTIN_MODEL_PROVIDER_IDS.bigmodelStartPlan;
  34. export const E2E_BIGMODEL_API_PROVIDER_ID = BUILTIN_PROVIDER_TEMPLATE_IDS.bigmodel;
  35. export const E2E_PLAN_FIRST_MODEL = "GLM-5.3";
  36. export const E2E_PLAN_DEFAULT_MODEL = "GLM-5.2";
  37. export const E2E_PLAN_NON_DEFAULT_MODEL = "GLM-5.3-Flash";
  38. export const E2E_PLAN_TURBO_MODEL = "GLM-5-Turbo";
  39. export async function seedBigModelConnectionSelection(
  40. selection: ProviderFamilyConnectionSelection,
  41. ) {
  42. await writeJsonPatch(SETTINGS_FILE, {
  43. providerFamilyConnectionSelections: {
  44. bigmodel: selection,
  45. },
  46. providerFamilyDomain: "bigmodel",
  47. providerFamilyDomainMigrated: true,
  48. });
  49. }
  50. export async function readBigModelConnectionSelection(): Promise<
  51. ProviderFamilyConnectionSelection | undefined
  52. > {
  53. const settings = await readJson(SETTINGS_FILE);
  54. const selections = settings.providerFamilyConnectionSelections;
  55. if (!selections || typeof selections !== "object" || Array.isArray(selections)) {
  56. return undefined;
  57. }
  58. return (selections as { bigmodel?: ProviderFamilyConnectionSelection }).bigmodel;
  59. }
  60. export async function seedBigModelOAuthCredential() {
  61. await writeJsonPatch(CREDENTIALS_FILE, {
  62. "oauth:active_provider": "bigmodel",
  63. "oauth:bigmodel:access_token": "e2e-bigmodel-oauth-token",
  64. "oauth:bigmodel:user_info": JSON.stringify({
  65. displayName: "BigModel E2E",
  66. id: "bigmodel-e2e-user",
  67. username: "bigmodel-e2e-user",
  68. }),
  69. });
  70. }
  71. /** 为需要经过 Highspeed 网关鉴权的 E2E 补齐登录 JWT。 */
  72. export async function seedHighspeedLoginCredential() {
  73. await writeJsonPatch(CREDENTIALS_FILE, {
  74. zcodejwttoken: "e2e-highspeed-zcode-jwt",
  75. });
  76. }
  77. /**
  78. * 为需要实际进入 BigModel Start Plan 的 E2E 补齐 zcode JWT。
  79. *
  80. * Start Plan 与个人 Coding Plan 共用 OAuth 用户身份,但请求授权读取的是
  81. * `zcodejwttoken`;只 seed business access token 会让菜单把 Start Plan 判成未认证。
  82. */
  83. export async function seedBigModelStartPlanCredential() {
  84. await writeJsonPatch(CREDENTIALS_FILE, {
  85. "oauth:active_provider": "bigmodel",
  86. "oauth:bigmodel:access_token": "e2e-bigmodel-oauth-token",
  87. "oauth:bigmodel:user_info": JSON.stringify({
  88. displayName: "BigModel E2E",
  89. id: "bigmodel-e2e-user",
  90. username: "bigmodel-e2e-user",
  91. }),
  92. zcodejwttoken: "e2e-bigmodel-start-plan-jwt",
  93. });
  94. }
  95. export async function seedReplayProvider(params: {
  96. apiKey?: string;
  97. baseURL?: string;
  98. enabled?: boolean;
  99. id: string;
  100. models: readonly SeedReplayProviderModel[];
  101. name: string;
  102. }) {
  103. const baseURL = params.baseURL ?? (await resolveSeededReplayBaseUrl());
  104. if (!baseURL) {
  105. throw new Error("没有可用 replay Base URL,无法 seed model provider restart case");
  106. }
  107. const provider: PersonalProviderConfigSeed = {
  108. id: params.id,
  109. label: params.name,
  110. // 内建 account provider 的模型规则按 anthropic-messages 匹配;若用 OpenAI Chat Completions
  111. // 格式覆盖连接配置,GLM builtin model rules 不会命中,模型在 Registry 中
  112. // 会因缺少完整 option/properties 被过滤,UI 菜单就看不到该计划模型。
  113. apiFormat: params.id.startsWith("account:") ? "anthropic-messages" : "openai-chat-completions",
  114. apiKey: params.apiKey ?? getUpstreamApiKey(),
  115. baseURL,
  116. enabled: params.enabled ?? true,
  117. models: params.models.map((input) =>
  118. typeof input === "string"
  119. ? { id: input }
  120. : {
  121. contextWindow: input.contextWindow,
  122. id: input.id,
  123. maxOutputTokens: input.maxOutputTokens ?? input.limit?.output,
  124. // 保留场景声明的档位,避免退回 disabled 后拒绝已保存的 high/max 偏好。
  125. reasoningLevel: input.reasoningLevel,
  126. },
  127. ),
  128. };
  129. await seedPersonalProviderConfig(paths.configFile, provider);
  130. }
  131. export async function seedPersistedModelSelection(params: {
  132. modelId: string;
  133. providerId: string;
  134. reasoningLevel: string;
  135. }) {
  136. await browser.execute(
  137. (workspacePath, keyPrefix, selection, appProvider) => {
  138. window.localStorage.setItem(
  139. `${keyPrefix}:${workspacePath}`,
  140. JSON.stringify({
  141. providerId: selection.providerId,
  142. modelId: selection.modelId,
  143. options: { reasoningLevel: selection.reasoningLevel },
  144. }),
  145. );
  146. window.localStorage.setItem("zcode-last-agent-provider", appProvider);
  147. },
  148. paths.workspace,
  149. MODEL_SELECTION_RECENT_KEY_PREFIX,
  150. params,
  151. ZCODE_AGENT_PROVIDER,
  152. );
  153. }
  154. export async function readLastSelectedAgentConfig() {
  155. return await browser.execute(
  156. (workspacePath, keyPrefix) => {
  157. const raw = window.localStorage.getItem(`${keyPrefix}:${workspacePath}`);
  158. if (!raw) return null;
  159. const recent: unknown = JSON.parse(raw);
  160. // Recent 扩展为模型与权限并列保存;重启断言同时兼容旧的纯模型种子。
  161. const record = recent && typeof recent === "object" && !Array.isArray(recent) ? recent : null;
  162. const selection =
  163. record && "modelSelection" in record ? record.modelSelection : (record ?? recent);
  164. const candidate =
  165. selection && typeof selection === "object" && !Array.isArray(selection)
  166. ? (selection as {
  167. providerId?: unknown;
  168. modelId?: unknown;
  169. options?: { reasoningLevel?: unknown };
  170. })
  171. : null;
  172. if (
  173. !candidate ||
  174. typeof candidate.providerId !== "string" ||
  175. typeof candidate.modelId !== "string" ||
  176. candidate.providerId.length === 0 ||
  177. candidate.modelId.length === 0
  178. ) {
  179. return null;
  180. }
  181. return {
  182. schemaVersion: 1,
  183. model: `${candidate.providerId}/${candidate.modelId}`,
  184. thoughtLevel: candidate.options?.reasoningLevel ?? null,
  185. };
  186. },
  187. paths.workspace,
  188. MODEL_SELECTION_RECENT_KEY_PREFIX,
  189. );
  190. }
  191. export async function waitForLastSelectedAgentConfig(params: {
  192. model: string;
  193. thoughtLevel: string;
  194. }) {
  195. let latest: Awaited<ReturnType<typeof readLastSelectedAgentConfig>> = null;
  196. try {
  197. await browser.waitUntil(
  198. async () => {
  199. latest = await readLastSelectedAgentConfig();
  200. return Boolean(
  201. latest?.model.includes(params.model) && latest.thoughtLevel === params.thoughtLevel,
  202. );
  203. },
  204. {
  205. timeout: 30000,
  206. timeoutMsg: `last-selected 配置没有收敛到 ${params.model}/${params.thoughtLevel}`,
  207. },
  208. );
  209. } catch {
  210. const storedAgentPreferences = await browser.execute(() =>
  211. Object.fromEntries(
  212. Object.entries(window.localStorage).filter(([key]) => key.startsWith("zcode-last-agent-")),
  213. ),
  214. );
  215. throw new Error(
  216. `last-selected 配置没有收敛到 ${params.model}/${params.thoughtLevel},实际值:${JSON.stringify(latest)},全部偏好:${JSON.stringify(storedAgentPreferences)}`,
  217. );
  218. }
  219. return latest;
  220. }
  221. export async function seedGlobalAgentReasoningLevel(thoughtLevel: string) {
  222. const databasePath = join(paths.storageRoot, "cli", "db", "db.sqlite");
  223. // Bug 根因:workspace UI ready 不代表 Agent DB migration ready;直接打开 writable DB
  224. // 会在父目录尚未创建时报 unable to open,甚至可能抢先生成缺少 schema 的空库。
  225. await waitForSqliteTable(databasePath, "local_setting");
  226. const db = new DatabaseSync(databasePath);
  227. const now = Date.now();
  228. try {
  229. db.exec("pragma busy_timeout = 5000");
  230. // Bug 根因:同一 spec 内 Agent SQLite 会跨 case 保留上一条显式 thought,
  231. // 只 seed renderer localStorage 不能隔离跨模型默认值。这里固定 Agent 侧前置状态,
  232. // 避免 I39 的 GLM high 泄漏到 I42,让用例真正验证 Turbo enabled → GLM 默认值。
  233. db.prepare(`
  234. insert into local_setting (
  235. scope, scope_id, namespace, key, value, schema_version, time_created, time_updated
  236. ) values (?, ?, ?, ?, ?, ?, ?, ?)
  237. on conflict(scope, scope_id, namespace, key) do update set
  238. value = excluded.value,
  239. schema_version = excluded.schema_version,
  240. time_updated = excluded.time_updated
  241. `).run(
  242. "user",
  243. "default",
  244. "model",
  245. "reasoningLevel",
  246. JSON.stringify({ level: thoughtLevel }),
  247. 1,
  248. now,
  249. now,
  250. );
  251. } finally {
  252. db.close();
  253. }
  254. }
  255. export async function waitForDraftThoughtLevelState(params: {
  256. current: string;
  257. values: readonly string[];
  258. timeoutMsg?: string;
  259. }) {
  260. let latest: Awaited<ReturnType<typeof getV4DraftThoughtState>> | null = null;
  261. await browser.waitUntil(
  262. async () => {
  263. // Bugfix:legacy workspace 目录可能仍属于上一模型;当前值与能力集优先读 V4
  264. // 当前模型投影,避免把 Turbo 二态误判成旧模型的 off/high/max。
  265. latest = await getV4DraftThoughtState(paths.workspace);
  266. const actualValues = [...latest.values].sort();
  267. const expectedValues = [...params.values].sort();
  268. return (
  269. latest.current === params.current &&
  270. JSON.stringify(actualValues) === JSON.stringify(expectedValues)
  271. );
  272. },
  273. {
  274. timeout: 30000,
  275. timeoutMsg: params.timeoutMsg ?? `draft thought 没有收敛到 ${params.current}`,
  276. },
  277. );
  278. return latest;
  279. }
  280. export async function waitForV4DraftModelConfig(params: { model: string; thought: string }) {
  281. let latest: { model: string | null; thought: string | null } | null = null;
  282. await browser.waitUntil(
  283. async () => {
  284. latest = await browser.execute((configTestId) => {
  285. const config = document.querySelector<HTMLElement>(`[data-testid="${configTestId}"]`);
  286. return {
  287. model: config?.dataset.model?.trim() || null,
  288. thought: config?.dataset.thought?.trim() || null,
  289. };
  290. }, TID_V4_MODEL_CONFIG);
  291. const modelMatches =
  292. latest.model === params.model || latest.model?.endsWith(`/${params.model}`) === true;
  293. return modelMatches && latest.thought === params.thought;
  294. },
  295. {
  296. timeout: 30000,
  297. timeoutMsg: `V4 draft 配置没有收敛到 ${params.model}/${params.thought}`,
  298. },
  299. );
  300. return latest;
  301. }
  302. export async function waitForPlanModelIoRequest(expectedText: string) {
  303. const debugDir = join(paths.homeDir, ".zcode", "cli", "debug");
  304. let matched: { model?: string; thinking?: { type?: string } } | null = null;
  305. await browser.waitUntil(
  306. async () => {
  307. const files = await readdir(debugDir).catch(() => []);
  308. for (const file of files.filter(
  309. (item) => item.startsWith("model-io-") && item.endsWith(".jsonl"),
  310. )) {
  311. const content = await readFile(join(debugDir, file), "utf-8").catch(() => "");
  312. for (const line of content.split("\n")) {
  313. if (!line.includes(expectedText)) continue;
  314. try {
  315. const record = JSON.parse(line) as {
  316. querySource?: string;
  317. request?: { body?: { model?: string; thinking?: { type?: string } } };
  318. };
  319. if (record.querySource === "main_turn" && record.request?.body) {
  320. matched = record.request.body;
  321. return true;
  322. }
  323. } catch {
  324. // model IO 正在追加时可能读到半行,下一轮重试即可。
  325. }
  326. }
  327. }
  328. return false;
  329. },
  330. { timeout: 30000, timeoutMsg: `没有找到 Plan model IO 请求: ${expectedText}` },
  331. );
  332. return matched as { model?: string; thinking?: { type?: string } } | null;
  333. }
  334. export async function restartIntoWorkspace(options: ModelProviderRestartOptions = {}) {
  335. await restartIntoWorkspaceRestoringPreferences(paths.workspace, options);
  336. }
  337. export async function restartIntoWorkspacePreservingProfile() {
  338. await restartIntoWorkspacePreservingProfileFixture(paths.workspace);
  339. }
  340. export async function waitForSelectedModel(providerId: string, modelId: string) {
  341. const expected = encodeCustomModelValue(providerId, modelId);
  342. let actual: string | null = null;
  343. let storedConfig: string | null = null;
  344. try {
  345. await browser.waitUntil(
  346. async () => {
  347. const snapshot = await browser.execute(
  348. (value, triggerTestId, workspacePath, keyPrefix) => {
  349. const trigger = document.querySelector<HTMLElement>(`[data-testid="${triggerTestId}"]`);
  350. return {
  351. actual: trigger?.dataset.modelCurrentValue ?? null,
  352. matched: trigger?.dataset.modelCurrentValue === value,
  353. storedConfig: window.localStorage.getItem(`${keyPrefix}:${workspacePath}`),
  354. };
  355. },
  356. expected,
  357. TID_CHAT_MODEL_SELECT_TRIGGER,
  358. paths.workspace,
  359. MODEL_SELECTION_RECENT_KEY_PREFIX,
  360. );
  361. actual = snapshot.actual;
  362. storedConfig = snapshot.storedConfig;
  363. return snapshot.matched;
  364. },
  365. {
  366. timeout: 30000,
  367. timeoutMsg: `toolbar 没有选择 ${expected}`,
  368. },
  369. );
  370. } catch (error) {
  371. throw new Error(
  372. `toolbar 没有选择 ${expected},actual=${actual},storedConfig=${storedConfig}`,
  373. { cause: error },
  374. );
  375. }
  376. }
  377. async function writeJsonPatch(file: string, patch: Record<string, unknown>) {
  378. const current = await readJson(file);
  379. await mkdir(dirname(file), { recursive: true });
  380. await writeFile(file, JSON.stringify({ ...current, ...patch }, null, 2), "utf-8");
  381. }
  382. async function readJson(file: string): Promise<Record<string, unknown>> {
  383. try {
  384. return JSON.parse(await readFile(file, "utf-8")) as Record<string, unknown>;
  385. } catch {
  386. return {};
  387. }
  388. }