model-provider-restart.ts 15 KB

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