conversation-session-remote-draft-prewarm.test.ts 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  1. import { writeFile } from "node:fs/promises";
  2. import { resolve } from "node:path";
  3. import { chromium, type Browser, type Page } from "playwright-core";
  4. import { ServiceChannels, parseRemoteWorkspaceIdentity } from "@zcode/shared";
  5. import type { ProjectTree } from "@zcode/services";
  6. import {
  7. TID_CHAT_MODEL_SELECT_TRIGGER,
  8. TID_CHAT_MODEL_SELECT_GROUP,
  9. TID_CHAT_MODEL_SELECT_ITEM,
  10. TID_V4_MODEL_CONFIG,
  11. testId,
  12. TID_V4_COMPOSER_INPUT,
  13. TID_V4_COMPOSER_SEND,
  14. } from "@zcode/shared/test-ids";
  15. import { waitForUpstreamRequest } from "#e2e/helpers/conversation-session-network";
  16. import {
  17. seedCustomOpenAIChatCompletionsProvider,
  18. refreshSeededOpenAIProvidersThroughSettings,
  19. } from "#e2e/helpers/custom-openai-provider";
  20. import { clearAppData } from "#e2e/helpers/desktop-app";
  21. import { reloadElectronSessionPreservingBrowserProfile } from "#e2e/helpers/e2e-electron-reload";
  22. import { openMobilePairingPage } from "#e2e/helpers/mobile-pairing";
  23. import { disconnectRemoteSource } from "#e2e/helpers/remote-project-actions";
  24. import {
  25. callHandoffHost,
  26. installHandoffRpcProbe,
  27. restoreHandoffProbes,
  28. } from "#e2e/helpers/remote-project-handoff-probe";
  29. import {
  30. prepareSSHLifecycle,
  31. connectSSHWorkspaceAndSendFirstTurn,
  32. waitForRendererAfterColdRestart,
  33. SSH_LIFECYCLE_MODEL_ID,
  34. type SSHLifecycleProvider,
  35. type SSHLifecycleTask,
  36. } from "#e2e/helpers/ssh-remote-lifecycle";
  37. import { prepareSSHConnectionPage, waitForRemoteTab } from "#e2e/helpers/ssh-remote-p0";
  38. import {
  39. getUpstreamProviderModelValues,
  40. selectUpstreamProviderModelById,
  41. selectUpstreamThoughtLevelValue,
  42. } from "#e2e/helpers/upstream-provider";
  43. import {
  44. sendV4PromptAndWaitAccepted,
  45. waitForV4AssistantMessageContaining,
  46. waitForV4ConversationState,
  47. } from "#e2e/helpers/v4-conversation";
  48. import { WEB_REMOTE_CONTROL_FIXTURE_CREDENTIALS } from "#e2e/helpers/web-remote-control-session-events-fixture";
  49. import { obtainUnreadPairingUrl, showMobileTaskHome } from "#e2e/helpers/web-remote-unread";
  50. import { startDraftFromProject } from "#e2e/helpers/project-sidebar";
  51. const CASE = "E2E_REMOTE_DRAFT_PREWARM";
  52. const REPLY = "REMOTE_DRAFT_PREWARM_REPLY";
  53. type Address = { path: string; identity?: string };
  54. type Ack = { type: string; status: string; reasonCode?: string };
  55. type ProbeWindow = Window & {
  56. __zcodeV4CommandAcksE2E?: Ack[];
  57. __zcodeTabStoreE2E?: {
  58. getState(): { activeWorkspacePath: string; activeWorkspaceIdentity?: string };
  59. };
  60. __zcodeSessionStoreE2E?: {
  61. getState(): {
  62. getWorkspaceState(
  63. path: string,
  64. identity?: string,
  65. ): { activeTaskId: string | null; draftProjectId?: string | null };
  66. startDraft(
  67. path: string,
  68. provider: undefined,
  69. identity: string,
  70. options: { projectId: null },
  71. ): void;
  72. };
  73. };
  74. };
  75. // 同时读取实际 Composer、workspace owner 与真实命令回执,不用模拟 createSession 结果。
  76. function readDraft(address?: Address) {
  77. const w = window as ProbeWindow;
  78. const tab = w.__zcodeTabStoreE2E!.getState();
  79. const path = address?.path ?? tab.activeWorkspacePath;
  80. const identity = address?.identity ?? tab.activeWorkspaceIdentity;
  81. const state = w.__zcodeSessionStoreE2E!.getState().getWorkspaceState(path, identity);
  82. return {
  83. path,
  84. identity,
  85. activeTaskId: state.activeTaskId,
  86. projectId: state.draftProjectId ?? null,
  87. createAcks: (w.__zcodeV4CommandAcksE2E ?? []).filter((a) => a.type === "createSession"),
  88. };
  89. }
  90. function clearAcks() {
  91. (window as ProbeWindow).__zcodeV4CommandAcksE2E = [];
  92. }
  93. function assertNoCreateErrors(facts: ReturnType<typeof readDraft>) {
  94. expect(facts.createAcks.filter((a) => a.status !== "accepted")).toEqual([]);
  95. }
  96. describe(`${CASE}: 远端草稿先确定项目归属再预热`, () => {
  97. let provider: SSHLifecycleProvider | undefined;
  98. let task: SSHLifecycleTask;
  99. let mobile: Browser | undefined;
  100. let page: Page | undefined;
  101. const evidence: Record<string, unknown> = {};
  102. const artifactDir = process.env.ZCODE_E2E_ARTIFACT_DIR!;
  103. after(async () => {
  104. await writeFile(
  105. resolve(artifactDir, "draft-prewarm-evidence.json"),
  106. JSON.stringify(evidence, null, 2),
  107. );
  108. await page
  109. ?.screenshot({ path: resolve(artifactDir, "mobile-last.png") })
  110. .catch(() => undefined);
  111. await mobile?.close();
  112. await restoreHandoffProbes();
  113. await provider?.tunnel.close();
  114. await browser.electron.restoreAllMocks();
  115. await clearAppData();
  116. });
  117. it("PD13–PD16:冷恢复缺归属不创建,项目恢复可首发,本地与手机路径可用", async function () {
  118. this.timeout(20 * 60_000);
  119. await prepareSSHConnectionPage(CASE);
  120. const prepared = await prepareSSHLifecycle(CASE);
  121. provider = prepared.provider;
  122. // 已有服务端可能先自动升级;连接 helper 必须等待连接状态收口,不能将升级进度误作终态错误。
  123. task = await connectSSHWorkspaceAndSendFirstTurn({
  124. caseMarker: CASE,
  125. config: prepared.config,
  126. provider,
  127. label: "A",
  128. workspacePath: prepared.config.workspacePaths[0],
  129. });
  130. const address = { path: task.workspacePath, identity: task.identity };
  131. const sourceId = parseRemoteWorkspaceIdentity(task.identity)!.sourceServerId!;
  132. // 远端已有同名项目时会追加后缀;按本轮身份选择入口,不按目录名猜测项目名。
  133. await startDraftFromProject(task.workspacePath, { workspaceIdentity: task.identity });
  134. const projectId = (await browser.execute(readDraft, address)).projectId;
  135. expect(projectId).toBeTruthy();
  136. for (const removeScope of [false, true]) {
  137. await disconnectRemoteSource(sourceId, CASE, { workspaceIdentities: [task.identity] });
  138. if (removeScope) {
  139. const removed = await browser.execute((identity) => {
  140. const keys = Object.keys(localStorage).filter(
  141. (k) => k.startsWith("zcode-composer-workspace-scope:v1:") && k.includes(identity),
  142. );
  143. keys.forEach((k) => localStorage.removeItem(k));
  144. return keys.length;
  145. }, task.identity);
  146. expect(removed).toBeGreaterThan(0);
  147. }
  148. // 保留 profile,完整重启 Electron/Main/Host;只删导航作用域,不改项目和会话事实。
  149. await reloadElectronSessionPreservingBrowserProfile(browser);
  150. await waitForRendererAfterColdRestart(CASE);
  151. await waitForRemoteTab({
  152. caseMarker: CASE,
  153. expectedIdentity: task.identity,
  154. expectedPath: task.workspacePath,
  155. requireActive: false,
  156. });
  157. if (!removeScope) {
  158. await browser.waitUntil(
  159. async () =>
  160. (await browser.execute(readDraft, address)).createAcks.some(
  161. (a) => a.status === "accepted",
  162. ),
  163. { timeout: 60_000, timeoutMsg: "PD13: 有归属的冷恢复未完成预热" },
  164. );
  165. const facts = await browser.execute(readDraft, address);
  166. evidence.savedScope = facts;
  167. expect(facts.projectId).toBe(projectId);
  168. assertNoCreateErrors(facts);
  169. } else {
  170. const input = $(`[data-testid="${TID_V4_COMPOSER_INPUT}"]`);
  171. await input.waitForDisplayed();
  172. await input.click();
  173. await browser.keys(`${CASE}_UNASSIGNED`);
  174. await browser.keys("Enter");
  175. // 负向观察窗口覆盖旧实现 0/500/1000/2000ms 四次自动创建;正向恢复另等真实 ACK。
  176. await browser.pause(4_500);
  177. const facts = await browser.execute(readDraft, address);
  178. evidence.missingScope = facts;
  179. await browser.saveScreenshot(resolve(artifactDir, "desktop-missing-scope.png"));
  180. expect(facts.projectId).toBeNull();
  181. expect(facts.createAcks).toEqual([]);
  182. expect(await input.getText()).toContain(`${CASE}_UNASSIGNED`);
  183. expect(await $(`[data-testid="${TID_V4_COMPOSER_SEND}"]`).isEnabled()).toBe(false);
  184. }
  185. }
  186. await browser.execute(clearAcks);
  187. await startDraftFromProject(task.workspacePath, { workspaceIdentity: task.identity });
  188. await sendV4PromptAndWaitAccepted(
  189. `${CASE}_DESKTOP_RECOVERED`,
  190. `${CASE}_DESKTOP_RECOVERED`,
  191. "PD14: 选项目后首发未接纳",
  192. );
  193. await waitForV4AssistantMessageContaining(REPLY);
  194. await waitForUpstreamRequest(
  195. { lastUserMessageIncludes: [`${CASE}_DESKTOP_RECOVERED`] },
  196. "远端首发没有到达 Provider",
  197. );
  198. const recovered = await waitForV4ConversationState(
  199. (s) => Boolean(s.taskId && s.state === "idle"),
  200. "PD14: 首发未完成",
  201. );
  202. evidence.desktopRecovered = await browser.execute(readDraft, address);
  203. assertNoCreateErrors(evidence.desktopRecovered as ReturnType<typeof readDraft>);
  204. await installHandoffRpcProbe();
  205. const assertOwnership = async (taskId: string, expected: string | null, hostId?: string) => {
  206. const tree = await callHandoffHost<ProjectTree>(ServiceChannels.Project, "readTree", [
  207. { hostId },
  208. ]);
  209. const row = tree.tasks.find((t) => t.taskId === taskId);
  210. expect(row?.projectId).toBe(expected);
  211. evidence[`owner-${taskId}`] = { projectId: row?.projectId, hostId: row?.hostId };
  212. };
  213. const hostId = `remote:server:${sourceId}`;
  214. await assertOwnership(recovered.taskId!, projectId, hostId);
  215. // 同一正式会话的续发也经过发送屏障,不能被缺少 draftProjectId 误挡。
  216. await sendV4PromptAndWaitAccepted(
  217. `${CASE}_DESKTOP_FOLLOW`,
  218. `${CASE}_DESKTOP_FOLLOW`,
  219. "PD16: 正式会话续发未接纳",
  220. );
  221. await waitForUpstreamRequest(
  222. { lastUserMessageIncludes: [`${CASE}_DESKTOP_FOLLOW`] },
  223. "正式会话续发没有到达 Provider",
  224. );
  225. await waitForV4ConversationState(
  226. (s) => s.taskId === recovered.taskId && s.state === "idle",
  227. "PD16: 正式会话续发未完成",
  228. );
  229. // 通用“新建”沿用当前项目;任务区专用入口才创建本地未归类草稿。
  230. await $('[data-testid="conversation-section"]').moveTo();
  231. await $('[data-testid="virtual-project-new-task"]').click();
  232. await browser.waitUntil(
  233. async () => {
  234. const facts = await browser.execute(readDraft, undefined);
  235. return !facts.identity && facts.projectId === null && facts.activeTaskId === null;
  236. },
  237. { timeout: 30_000, timeoutMsg: "PD16: 没有进入本地未归类草稿" },
  238. );
  239. const pairingUrl = await obtainUnreadPairingUrl();
  240. mobile = await chromium.launch({
  241. ...(process.env.ZCODE_E2E_MOBILE_BROWSER_EXECUTABLE
  242. ? { executablePath: process.env.ZCODE_E2E_MOBILE_BROWSER_EXECUTABLE }
  243. : { channel: "chrome" }),
  244. headless: true,
  245. });
  246. const context = await mobile.newContext({
  247. viewport: { width: 390, height: 844 },
  248. isMobile: true,
  249. hasTouch: true,
  250. locale: "zh-CN",
  251. });
  252. await context.addInitScript((credentials) => {
  253. for (const [key, value] of Object.entries(credentials)) localStorage.setItem(key, value);
  254. }, WEB_REMOTE_CONTROL_FIXTURE_CREDENTIALS);
  255. page = await context.newPage();
  256. const rowSelector = `[data-project-id=${JSON.stringify(projectId)}]`;
  257. await openMobilePairingPage(page, pairingUrl, {
  258. artifactDir,
  259. caseMarker: CASE,
  260. phase: "draft-prewarm",
  261. readySelector: rowSelector,
  262. });
  263. const openMobileProject = async () => {
  264. await showMobileTaskHome(page!);
  265. const row = page!.locator(rowSelector).first();
  266. await row.hover();
  267. await row.getByTestId("virtual-project-create-task").click();
  268. await page!.waitForFunction(
  269. ({ path, identity, projectId }) => {
  270. const state = (window as ProbeWindow).__zcodeSessionStoreE2E
  271. ?.getState()
  272. .getWorkspaceState(path, identity);
  273. return state?.draftProjectId === projectId && !state.activeTaskId;
  274. },
  275. { ...address, projectId },
  276. );
  277. };
  278. const selectMobileModel = async () => {
  279. // 桌面与手机的 Recent 独立;手机必须经真实菜单选择 SSH 可达的回放 Provider。
  280. const values = getUpstreamProviderModelValues(SSH_LIFECYCLE_MODEL_ID, {
  281. providerId: provider!.id,
  282. includePlainModelFallback: false,
  283. });
  284. const trigger = page!.getByTestId(TID_CHAT_MODEL_SELECT_TRIGGER).first();
  285. if (!values.includes((await trigger.getAttribute("data-model-current-value")) ?? "")) {
  286. await trigger.click();
  287. await page!.getByTestId("composer-provider-trigger").click();
  288. await page!
  289. .getByTestId(testId(TID_CHAT_MODEL_SELECT_GROUP, `registry-provider:${provider!.id}`))
  290. .click();
  291. const candidates = values
  292. .map(
  293. (value) => `[data-testid=${JSON.stringify(testId(TID_CHAT_MODEL_SELECT_ITEM, value))}]`,
  294. )
  295. .join(",");
  296. await page!.waitForFunction(
  297. ({ values, candidates }) =>
  298. values.includes(
  299. document
  300. .querySelector('[data-testid="chat-model-select-trigger"]')
  301. ?.getAttribute("data-model-current-value") ?? "",
  302. ) || Boolean(document.querySelector(candidates)),
  303. { values, candidates },
  304. );
  305. if (!values.includes((await trigger.getAttribute("data-model-current-value")) ?? ""))
  306. await page!.locator(candidates).first().click();
  307. }
  308. await page!.waitForFunction(
  309. (values) =>
  310. values.includes(
  311. document
  312. .querySelector('[data-testid="chat-model-select-trigger"]')
  313. ?.getAttribute("data-model-current-value") ?? "",
  314. ),
  315. values,
  316. );
  317. if ((await trigger.getAttribute("aria-expanded")) !== "true") await trigger.click();
  318. const toggle = page!.getByTestId("composer-thought-switch");
  319. const slider = page!.getByTestId("composer-thought-slider");
  320. if (await toggle.isVisible()) {
  321. expect(await toggle.getAttribute("data-off-value")).toBe("disabled");
  322. if ((await toggle.getAttribute("aria-checked")) !== "false") await toggle.click();
  323. } else if (await slider.isVisible()) {
  324. const levels = JSON.parse((await slider.getAttribute("data-levels")) ?? "[]") as string[];
  325. const index = levels.indexOf("disabled");
  326. expect(index).toBeGreaterThanOrEqual(0);
  327. await slider.press("Home");
  328. for (let i = 0; i < index; i++) await slider.press("ArrowRight");
  329. }
  330. await page!.keyboard.press("Escape");
  331. expect(await page!.getByTestId(TID_V4_MODEL_CONFIG).getAttribute("data-thought")).toBe(
  332. "disabled",
  333. );
  334. };
  335. const sendMobile = async (marker: string) => {
  336. await selectMobileModel();
  337. await page!.getByTestId(TID_V4_COMPOSER_INPUT).first().fill(marker);
  338. await page!.getByTestId(TID_V4_COMPOSER_SEND).first().click({ timeout: 60_000 });
  339. await page!.getByText(REPLY, { exact: false }).first().waitFor({ timeout: 90_000 });
  340. await waitForUpstreamRequest(
  341. { lastUserMessageIncludes: [marker] },
  342. "手机首发没有到达 Provider",
  343. );
  344. const facts = await page!.evaluate(readDraft, address);
  345. expect(facts.activeTaskId).toBeTruthy();
  346. assertNoCreateErrors(facts);
  347. await assertOwnership(facts.activeTaskId!, projectId, hostId);
  348. return facts;
  349. };
  350. await openMobileProject();
  351. evidence.mobileInitial = await sendMobile(`${CASE}_MOBILE_INITIAL`);
  352. await page.evaluate(clearAcks);
  353. // 手机正常导航显式交付项目;这里仅将缺失归属作为受控前置,后续恢复仍走真实 UI。
  354. await page.evaluate(({ path, identity }) => {
  355. (window as ProbeWindow)
  356. .__zcodeSessionStoreE2E!.getState()
  357. .startDraft(path, undefined, identity, { projectId: null });
  358. }, address);
  359. const input = page.getByTestId(TID_V4_COMPOSER_INPUT).first();
  360. await input.fill(`${CASE}_MOBILE_UNASSIGNED`);
  361. await input.press("Enter");
  362. await page.waitForTimeout(4_500);
  363. evidence.mobileMissing = await page.evaluate(readDraft, address);
  364. expect((evidence.mobileMissing as ReturnType<typeof readDraft>).projectId).toBeNull();
  365. expect((evidence.mobileMissing as ReturnType<typeof readDraft>).activeTaskId).toBeNull();
  366. expect((evidence.mobileMissing as ReturnType<typeof readDraft>).createAcks).toEqual([]);
  367. expect(await input.innerText()).toContain(`${CASE}_MOBILE_UNASSIGNED`);
  368. expect(await page.getByTestId(TID_V4_COMPOSER_SEND).first().isDisabled()).toBe(true);
  369. await page.screenshot({ path: resolve(artifactDir, "mobile-missing-scope.png") });
  370. await openMobileProject();
  371. evidence.mobileRecovered = await sendMobile(`${CASE}_MOBILE_RECOVERED`);
  372. // 远端 Provider 的 loopback 端口属于 SSH 目标;本地首发使用本轮本机 replay 入口。
  373. const localProvider = await seedCustomOpenAIChatCompletionsProvider({
  374. modelId: SSH_LIFECYCLE_MODEL_ID,
  375. providerId: "e2e-prewarm-local",
  376. providerName: "Draft prewarm local",
  377. });
  378. await refreshSeededOpenAIProvidersThroughSettings([localProvider.name], {
  379. workspacePath: (await browser.execute(readDraft, undefined)).path,
  380. });
  381. await selectUpstreamProviderModelById(SSH_LIFECYCLE_MODEL_ID, {
  382. includePlainModelFallback: false,
  383. providerId: localProvider.id,
  384. providerName: localProvider.name,
  385. });
  386. await selectUpstreamThoughtLevelValue("disabled");
  387. await sendV4PromptAndWaitAccepted(
  388. `${CASE}_LOCAL_UNCLASSIFIED`,
  389. `${CASE}_LOCAL_UNCLASSIFIED`,
  390. "PD16: 本地未归类首发未接纳",
  391. );
  392. await waitForV4AssistantMessageContaining(REPLY);
  393. await waitForUpstreamRequest(
  394. { lastUserMessageIncludes: [`${CASE}_LOCAL_UNCLASSIFIED`] },
  395. "本地首发没有到达 Provider",
  396. );
  397. const local = await waitForV4ConversationState(
  398. (s) => Boolean(s.taskId && s.state === "idle"),
  399. "PD16: 本地未归类未完成",
  400. );
  401. evidence.local = await browser.execute(readDraft, undefined);
  402. expect((evidence.local as ReturnType<typeof readDraft>).identity).toBeFalsy();
  403. await assertOwnership(local.taskId!, null);
  404. });
  405. });