model-provider-restart.ts 14 KB

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