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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  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 { openWorkspaceDraftFromSidebar } from "#e2e/helpers/workspace-agent-warmup";
  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. task = await connectSSHWorkspaceAndSendFirstTurn({
  123. caseMarker: CASE,
  124. config: prepared.config,
  125. provider,
  126. label: "A",
  127. workspacePath: prepared.config.workspacePaths[0],
  128. });
  129. const address = { path: task.workspacePath, identity: task.identity };
  130. const sourceId = parseRemoteWorkspaceIdentity(task.identity)!.sourceServerId!;
  131. await openWorkspaceDraftFromSidebar(task.workspacePath);
  132. const projectId = (await browser.execute(readDraft, address)).projectId;
  133. expect(projectId).toBeTruthy();
  134. for (const removeScope of [false, true]) {
  135. await disconnectRemoteSource(sourceId, CASE, { workspaceIdentities: [task.identity] });
  136. if (removeScope) {
  137. const removed = await browser.execute((identity) => {
  138. const keys = Object.keys(localStorage).filter(
  139. (k) => k.startsWith("zcode-composer-workspace-scope:v1:") && k.includes(identity),
  140. );
  141. keys.forEach((k) => localStorage.removeItem(k));
  142. return keys.length;
  143. }, task.identity);
  144. expect(removed).toBeGreaterThan(0);
  145. }
  146. // 保留 profile,完整重启 Electron/Main/Host;只删导航作用域,不改项目和会话事实。
  147. await reloadElectronSessionPreservingBrowserProfile(browser);
  148. await waitForRendererAfterColdRestart(CASE);
  149. await waitForRemoteTab({
  150. caseMarker: CASE,
  151. expectedIdentity: task.identity,
  152. expectedPath: task.workspacePath,
  153. requireActive: false,
  154. });
  155. if (!removeScope) {
  156. await browser.waitUntil(
  157. async () =>
  158. (await browser.execute(readDraft, address)).createAcks.some(
  159. (a) => a.status === "accepted",
  160. ),
  161. { timeout: 60_000, timeoutMsg: "PD13: 有归属的冷恢复未完成预热" },
  162. );
  163. const facts = await browser.execute(readDraft, address);
  164. evidence.savedScope = facts;
  165. expect(facts.projectId).toBe(projectId);
  166. assertNoCreateErrors(facts);
  167. } else {
  168. const input = $(`[data-testid="${TID_V4_COMPOSER_INPUT}"]`);
  169. await input.waitForDisplayed();
  170. await input.click();
  171. await browser.keys(`${CASE}_UNASSIGNED`);
  172. await browser.keys("Enter");
  173. // 负向观察窗口覆盖旧实现 0/500/1000/2000ms 四次自动创建;正向恢复另等真实 ACK。
  174. await browser.pause(4_500);
  175. const facts = await browser.execute(readDraft, address);
  176. evidence.missingScope = facts;
  177. await browser.saveScreenshot(resolve(artifactDir, "desktop-missing-scope.png"));
  178. expect(facts.projectId).toBeNull();
  179. expect(facts.createAcks).toEqual([]);
  180. expect(await input.getText()).toContain(`${CASE}_UNASSIGNED`);
  181. expect(await $(`[data-testid="${TID_V4_COMPOSER_SEND}"]`).isEnabled()).toBe(false);
  182. }
  183. }
  184. await browser.execute(clearAcks);
  185. await openWorkspaceDraftFromSidebar(task.workspacePath);
  186. await sendV4PromptAndWaitAccepted(
  187. `${CASE}_DESKTOP_RECOVERED`,
  188. `${CASE}_DESKTOP_RECOVERED`,
  189. "PD14: 选项目后首发未接纳",
  190. );
  191. await waitForV4AssistantMessageContaining(REPLY);
  192. await waitForUpstreamRequest(
  193. { lastUserMessageIncludes: [`${CASE}_DESKTOP_RECOVERED`] },
  194. "远端首发没有到达 Provider",
  195. );
  196. const recovered = await waitForV4ConversationState(
  197. (s) => Boolean(s.taskId && s.state === "idle"),
  198. "PD14: 首发未完成",
  199. );
  200. evidence.desktopRecovered = await browser.execute(readDraft, address);
  201. assertNoCreateErrors(evidence.desktopRecovered as ReturnType<typeof readDraft>);
  202. await installHandoffRpcProbe();
  203. const assertOwnership = async (taskId: string, expected: string | null, hostId?: string) => {
  204. const tree = await callHandoffHost<ProjectTree>(ServiceChannels.Project, "readTree", [
  205. { hostId },
  206. ]);
  207. const row = tree.tasks.find((t) => t.taskId === taskId);
  208. expect(row?.projectId).toBe(expected);
  209. evidence[`owner-${taskId}`] = { projectId: row?.projectId, hostId: row?.hostId };
  210. };
  211. const hostId = `remote:server:${sourceId}`;
  212. await assertOwnership(recovered.taskId!, projectId, hostId);
  213. // 同一正式会话的续发也经过发送屏障,不能被缺少 draftProjectId 误挡。
  214. await sendV4PromptAndWaitAccepted(
  215. `${CASE}_DESKTOP_FOLLOW`,
  216. `${CASE}_DESKTOP_FOLLOW`,
  217. "PD16: 正式会话续发未接纳",
  218. );
  219. await waitForUpstreamRequest(
  220. { lastUserMessageIncludes: [`${CASE}_DESKTOP_FOLLOW`] },
  221. "正式会话续发没有到达 Provider",
  222. );
  223. await waitForV4ConversationState(
  224. (s) => s.taskId === recovered.taskId && s.state === "idle",
  225. "PD16: 正式会话续发未完成",
  226. );
  227. // 通用“新建”沿用当前项目;任务区专用入口才创建本地未归类草稿。
  228. await $('[data-testid="conversation-section"]').moveTo();
  229. await $('[data-testid="virtual-project-new-task"]').click();
  230. await browser.waitUntil(
  231. async () => {
  232. const facts = await browser.execute(readDraft, undefined);
  233. return !facts.identity && facts.projectId === null && facts.activeTaskId === null;
  234. },
  235. { timeout: 30_000, timeoutMsg: "PD16: 没有进入本地未归类草稿" },
  236. );
  237. const pairingUrl = await obtainUnreadPairingUrl();
  238. mobile = await chromium.launch({
  239. ...(process.env.ZCODE_E2E_MOBILE_BROWSER_EXECUTABLE
  240. ? { executablePath: process.env.ZCODE_E2E_MOBILE_BROWSER_EXECUTABLE }
  241. : { channel: "chrome" }),
  242. headless: true,
  243. });
  244. const context = await mobile.newContext({
  245. viewport: { width: 390, height: 844 },
  246. isMobile: true,
  247. hasTouch: true,
  248. locale: "zh-CN",
  249. });
  250. await context.addInitScript((credentials) => {
  251. for (const [key, value] of Object.entries(credentials)) localStorage.setItem(key, value);
  252. }, WEB_REMOTE_CONTROL_FIXTURE_CREDENTIALS);
  253. page = await context.newPage();
  254. const rowSelector = `[data-project-id=${JSON.stringify(projectId)}]`;
  255. await openMobilePairingPage(page, pairingUrl, {
  256. artifactDir,
  257. caseMarker: CASE,
  258. phase: "draft-prewarm",
  259. readySelector: rowSelector,
  260. });
  261. const openMobileProject = async () => {
  262. await showMobileTaskHome(page!);
  263. const row = page!.locator(rowSelector).first();
  264. await row.hover();
  265. await row.getByTestId("virtual-project-create-task").click();
  266. await page!.waitForFunction(
  267. ({ path, identity, projectId }) => {
  268. const state = (window as ProbeWindow).__zcodeSessionStoreE2E
  269. ?.getState()
  270. .getWorkspaceState(path, identity);
  271. return state?.draftProjectId === projectId && !state.activeTaskId;
  272. },
  273. { ...address, projectId },
  274. );
  275. };
  276. const selectMobileModel = async () => {
  277. // 桌面与手机的 Recent 独立;手机必须经真实菜单选择 SSH 可达的回放 Provider。
  278. const values = getUpstreamProviderModelValues(SSH_LIFECYCLE_MODEL_ID, {
  279. providerId: provider!.id,
  280. includePlainModelFallback: false,
  281. });
  282. const trigger = page!.getByTestId(TID_CHAT_MODEL_SELECT_TRIGGER).first();
  283. if (!values.includes((await trigger.getAttribute("data-model-current-value")) ?? "")) {
  284. await trigger.click();
  285. await page!.getByTestId("composer-provider-trigger").click();
  286. await page!
  287. .getByTestId(testId(TID_CHAT_MODEL_SELECT_GROUP, `registry-provider:${provider!.id}`))
  288. .click();
  289. const candidates = values
  290. .map(
  291. (value) => `[data-testid=${JSON.stringify(testId(TID_CHAT_MODEL_SELECT_ITEM, value))}]`,
  292. )
  293. .join(",");
  294. await page!.waitForFunction(
  295. ({ values, candidates }) =>
  296. values.includes(
  297. document
  298. .querySelector('[data-testid="chat-model-select-trigger"]')
  299. ?.getAttribute("data-model-current-value") ?? "",
  300. ) || Boolean(document.querySelector(candidates)),
  301. { values, candidates },
  302. );
  303. if (!values.includes((await trigger.getAttribute("data-model-current-value")) ?? ""))
  304. await page!.locator(candidates).first().click();
  305. }
  306. await page!.waitForFunction(
  307. (values) =>
  308. values.includes(
  309. document
  310. .querySelector('[data-testid="chat-model-select-trigger"]')
  311. ?.getAttribute("data-model-current-value") ?? "",
  312. ),
  313. values,
  314. );
  315. if ((await trigger.getAttribute("aria-expanded")) !== "true") await trigger.click();
  316. const toggle = page!.getByTestId("composer-thought-switch");
  317. const slider = page!.getByTestId("composer-thought-slider");
  318. if (await toggle.isVisible()) {
  319. expect(await toggle.getAttribute("data-off-value")).toBe("disabled");
  320. if ((await toggle.getAttribute("aria-checked")) !== "false") await toggle.click();
  321. } else if (await slider.isVisible()) {
  322. const levels = JSON.parse((await slider.getAttribute("data-levels")) ?? "[]") as string[];
  323. const index = levels.indexOf("disabled");
  324. expect(index).toBeGreaterThanOrEqual(0);
  325. await slider.press("Home");
  326. for (let i = 0; i < index; i++) await slider.press("ArrowRight");
  327. }
  328. await page!.keyboard.press("Escape");
  329. expect(await page!.getByTestId(TID_V4_MODEL_CONFIG).getAttribute("data-thought")).toBe(
  330. "disabled",
  331. );
  332. };
  333. const sendMobile = async (marker: string) => {
  334. await selectMobileModel();
  335. await page!.getByTestId(TID_V4_COMPOSER_INPUT).first().fill(marker);
  336. await page!.getByTestId(TID_V4_COMPOSER_SEND).first().click({ timeout: 60_000 });
  337. await page!.getByText(REPLY, { exact: false }).first().waitFor({ timeout: 90_000 });
  338. await waitForUpstreamRequest(
  339. { lastUserMessageIncludes: [marker] },
  340. "手机首发没有到达 Provider",
  341. );
  342. const facts = await page!.evaluate(readDraft, address);
  343. expect(facts.activeTaskId).toBeTruthy();
  344. assertNoCreateErrors(facts);
  345. await assertOwnership(facts.activeTaskId!, projectId, hostId);
  346. return facts;
  347. };
  348. await openMobileProject();
  349. evidence.mobileInitial = await sendMobile(`${CASE}_MOBILE_INITIAL`);
  350. await page.evaluate(clearAcks);
  351. // 手机正常导航显式交付项目;这里仅将缺失归属作为受控前置,后续恢复仍走真实 UI。
  352. await page.evaluate(({ path, identity }) => {
  353. (window as ProbeWindow)
  354. .__zcodeSessionStoreE2E!.getState()
  355. .startDraft(path, undefined, identity, { projectId: null });
  356. }, address);
  357. const input = page.getByTestId(TID_V4_COMPOSER_INPUT).first();
  358. await input.fill(`${CASE}_MOBILE_UNASSIGNED`);
  359. await input.press("Enter");
  360. await page.waitForTimeout(4_500);
  361. evidence.mobileMissing = await page.evaluate(readDraft, address);
  362. expect((evidence.mobileMissing as ReturnType<typeof readDraft>).projectId).toBeNull();
  363. expect((evidence.mobileMissing as ReturnType<typeof readDraft>).activeTaskId).toBeNull();
  364. expect((evidence.mobileMissing as ReturnType<typeof readDraft>).createAcks).toEqual([]);
  365. expect(await input.innerText()).toContain(`${CASE}_MOBILE_UNASSIGNED`);
  366. expect(await page.getByTestId(TID_V4_COMPOSER_SEND).first().isDisabled()).toBe(true);
  367. await page.screenshot({ path: resolve(artifactDir, "mobile-missing-scope.png") });
  368. await openMobileProject();
  369. evidence.mobileRecovered = await sendMobile(`${CASE}_MOBILE_RECOVERED`);
  370. // 远端 Provider 的 loopback 端口属于 SSH 目标;本地首发使用本轮本机 replay 入口。
  371. const localProvider = await seedCustomOpenAIChatCompletionsProvider({
  372. modelId: SSH_LIFECYCLE_MODEL_ID,
  373. providerId: "e2e-prewarm-local",
  374. providerName: "Draft prewarm local",
  375. });
  376. await refreshSeededOpenAIProvidersThroughSettings([localProvider.name], {
  377. workspacePath: (await browser.execute(readDraft, undefined)).path,
  378. });
  379. await selectUpstreamProviderModelById(SSH_LIFECYCLE_MODEL_ID, {
  380. includePlainModelFallback: false,
  381. providerId: localProvider.id,
  382. providerName: localProvider.name,
  383. });
  384. await selectUpstreamThoughtLevelValue("disabled");
  385. await sendV4PromptAndWaitAccepted(
  386. `${CASE}_LOCAL_UNCLASSIFIED`,
  387. `${CASE}_LOCAL_UNCLASSIFIED`,
  388. "PD16: 本地未归类首发未接纳",
  389. );
  390. await waitForV4AssistantMessageContaining(REPLY);
  391. await waitForUpstreamRequest(
  392. { lastUserMessageIncludes: [`${CASE}_LOCAL_UNCLASSIFIED`] },
  393. "本地首发没有到达 Provider",
  394. );
  395. const local = await waitForV4ConversationState(
  396. (s) => Boolean(s.taskId && s.state === "idle"),
  397. "PD16: 本地未归类未完成",
  398. );
  399. evidence.local = await browser.execute(readDraft, undefined);
  400. expect((evidence.local as ReturnType<typeof readDraft>).identity).toBeFalsy();
  401. await assertOwnership(local.taskId!, null);
  402. });
  403. });