model-provider-restart.ts 17 KB

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