conversation-session-background-connection.test.ts 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788
  1. import { join } from "node:path";
  2. import { writeFile } from "node:fs/promises";
  3. import {
  4. PlatformChannels,
  5. ServiceChannels,
  6. type SourceServerManagementSnapshot,
  7. buildServerRemoteWorkspaceIdentity,
  8. remoteHostIdFromWorkspaceIdentity,
  9. } from "@zcode/shared";
  10. import {
  11. TID_TASK_SETTINGS_BUTTON,
  12. TID_SETTINGS_BACK_BUTTON,
  13. TID_SETTINGS_SECTION_NAV,
  14. TID_COMPOSER_WORKSPACE_TRIGGER,
  15. TID_COMPOSER_REMOTE_CONNECTION,
  16. TID_REMOTE_KIND_DOCKER,
  17. TID_VIRTUAL_PROJECT_CREATE_TASK,
  18. testId,
  19. } from "@zcode/shared/test-ids";
  20. import type { RemoteProjectDirectory, ProjectTree, VirtualProject } from "@zcode/services";
  21. import { clearAppData, clickTestIdByDom } from "#e2e/helpers/desktop-app";
  22. import { expandRemoteDeviceRowsNeedingAttention } from "#e2e/helpers/remote-project-actions";
  23. import {
  24. prepareV4ConversationE2E,
  25. setV4ComposerText,
  26. getV4ComposerText,
  27. pasteV4ComposerFileAttachment,
  28. getV4ComposerAttachments,
  29. selectV4TaskById,
  30. sendV4PromptAndWaitAccepted,
  31. waitForV4AssistantMessageContaining,
  32. } from "#e2e/helpers/v4-conversation";
  33. import {
  34. installHandoffRpcProbe,
  35. callHandoffHost,
  36. restoreHandoffProbes,
  37. } from "#e2e/helpers/remote-project-handoff-probe";
  38. import {
  39. readSSHRuntimeConfig,
  40. fillSSHPasswordSettings,
  41. clickLastEnabledSSHDialogButton,
  42. waitForRemoteTab,
  43. waitForSSHDirectoryStep,
  44. runSSHCommand,
  45. } from "#e2e/helpers/ssh-remote-p0";
  46. import {
  47. createSSHLifecycleProvider,
  48. SSH_LIFECYCLE_MODEL_ID,
  49. type SSHLifecycleProvider,
  50. } from "#e2e/helpers/ssh-remote-lifecycle";
  51. import {
  52. selectUpstreamProviderModelById,
  53. selectUpstreamThoughtLevelValue,
  54. } from "#e2e/helpers/upstream-provider";
  55. const marker = "E2E_BACKGROUND_CONNECTION";
  56. type Handler = (...args: unknown[]) => Promise<unknown>;
  57. declare global {
  58. interface Window {
  59. __backgroundSourceReads?: {
  60. requests: { bytes: Uint8Array; port: MessagePort }[];
  61. restore(): void;
  62. };
  63. }
  64. var __backgroundConnectionProbe:
  65. | { held: boolean; code?: string; calls: number; release(): void; restore(): void }
  66. | undefined;
  67. }
  68. // 用例不稳定原因:点项目行的“新建任务”时鼠标停在行上,300ms 后弹出的项目悬停卡片会盖住
  69. // composer 的项目选择器,高负载下后续点击被拦截(element click intercepted)。点完后移开鼠标并等卡片关闭。
  70. async function leaveProjectRow() {
  71. await browser.action("pointer").move({ x: 0, y: 0, origin: "viewport" }).perform();
  72. await $('[data-testid="project-identity-details"]').waitForExist({
  73. reverse: true,
  74. timeout: 5000,
  75. });
  76. }
  77. /** 扣住真实 Source 查询请求,验证显式继续在资格 IO 之前同步禁发。 */
  78. async function holdSourceReads() {
  79. await browser.execute((channel) => {
  80. const original = MessagePort.prototype.postMessage;
  81. const requests: { bytes: Uint8Array; port: MessagePort }[] = [];
  82. window.__backgroundSourceReads = {
  83. requests,
  84. restore() {
  85. MessagePort.prototype.postMessage = original;
  86. for (const request of requests) original.call(request.port, request.bytes);
  87. delete window.__backgroundSourceReads;
  88. },
  89. };
  90. MessagePort.prototype.postMessage = function (message: unknown, options?: unknown) {
  91. const text = message instanceof Uint8Array ? new TextDecoder().decode(message) : "";
  92. if (text.includes(channel) && text.includes("getSnapshot")) {
  93. requests.push({ bytes: message as Uint8Array, port: this });
  94. return;
  95. }
  96. Reflect.apply(original, this, options === undefined ? [message] : [message, options]);
  97. };
  98. }, ServiceChannels.SourceServerManagement);
  99. }
  100. async function releaseSourceReads() {
  101. await browser.execute(() => window.__backgroundSourceReads?.restore());
  102. }
  103. const snapshot = () =>
  104. callHandoffHost<SourceServerManagementSnapshot>(
  105. ServiceChannels.SourceServerManagement,
  106. "getSnapshot",
  107. );
  108. const directory = () =>
  109. callHandoffHost<RemoteProjectDirectory>(ServiceChannels.RemoteProjects, "readDirectory");
  110. /** 只扣住真实平台连接结果;SSH/Docker 与 Host 状态仍按真实链路运行。 */
  111. async function holdConnection() {
  112. await browser.electron.execute((electron, channel) => {
  113. globalThis.__backgroundConnectionProbe?.restore();
  114. const handlers = (electron.ipcMain as unknown as { _invokeHandlers: Map<string, Handler> })
  115. ._invokeHandlers;
  116. const original = handlers.get(channel);
  117. if (!original) throw new Error("Remote connection handler is unavailable");
  118. let release!: () => void;
  119. const barrier = new Promise<void>((resolve) => {
  120. release = resolve;
  121. });
  122. const probe = {
  123. held: false,
  124. calls: 0,
  125. code: undefined as string | undefined,
  126. release,
  127. restore() {
  128. release();
  129. handlers.set(channel, original);
  130. delete globalThis.__backgroundConnectionProbe;
  131. },
  132. };
  133. handlers.set(channel, async (...args) => {
  134. probe.calls++;
  135. let value: unknown;
  136. let failure: unknown;
  137. try {
  138. value = await original(...args);
  139. } catch (cause) {
  140. failure = cause;
  141. }
  142. const response = value as { success?: boolean; reasonCode?: string } | undefined;
  143. probe.code =
  144. (failure as { code?: string } | undefined)?.code ??
  145. (response?.success === false ? (response.reasonCode ?? "connect-failed") : undefined);
  146. probe.held = true;
  147. await barrier;
  148. if (failure) throw failure;
  149. return value;
  150. });
  151. globalThis.__backgroundConnectionProbe = probe;
  152. }, PlatformChannels.ConnectRemote);
  153. }
  154. async function waitHeld() {
  155. await browser.waitUntil(
  156. () => browser.electron.execute(() => Boolean(globalThis.__backgroundConnectionProbe?.held)),
  157. { timeout: 120_000 },
  158. );
  159. return browser.electron.execute(() => globalThis.__backgroundConnectionProbe?.code);
  160. }
  161. async function releaseConnection() {
  162. await browser.electron.execute(() => globalThis.__backgroundConnectionProbe?.release());
  163. }
  164. async function restoreConnection() {
  165. await browser.electron.execute(() => globalThis.__backgroundConnectionProbe?.restore());
  166. }
  167. async function background() {
  168. await $('[data-testid="ssh-dialog"]')
  169. .$('.//button[contains(.,"后台") or contains(.,"Background") or contains(.,"收起")]')
  170. .click();
  171. await $('[data-testid="ssh-dialog"]').waitForExist({ reverse: true });
  172. }
  173. async function settings() {
  174. await clickTestIdByDom(TID_TASK_SETTINGS_BUTTON);
  175. await clickTestIdByDom(testId(TID_SETTINGS_SECTION_NAV, "remoteDevices"));
  176. }
  177. async function back() {
  178. await clickTestIdByDom(TID_SETTINGS_BACK_BUTTON);
  179. }
  180. async function openConnectionEntry() {
  181. await $("[data-settings-content-frame]")
  182. .$('.//button[normalize-space(.)="新建连接" or normalize-space(.)="New connection"]')
  183. .click();
  184. }
  185. async function newConnection() {
  186. await openConnectionEntry();
  187. await $('[data-testid="ssh-host-input"]').waitForDisplayed();
  188. }
  189. async function readyProgress() {
  190. const card = $('[data-testid="remote-connection-minimized"]');
  191. await browser.waitUntil(
  192. async () => {
  193. // RDUX-13:已识别设备的后台连接进度块在展开区;只展开提示“需要处理”的设备行。
  194. await expandRemoteDeviceRowsNeedingAttention();
  195. const text = (await card.isExisting()) ? await card.getText() : "";
  196. return text.includes("连接已完成") || text.includes("Connection complete");
  197. },
  198. { timeout: 90_000 },
  199. );
  200. expect(await $$('[data-testid="remote-connection-minimized"]').length).toBe(1);
  201. return card;
  202. }
  203. async function continueReady() {
  204. await (await readyProgress()).click();
  205. }
  206. async function assertUninterrupted(text: string, attachments = false) {
  207. // 显式继续会展示校验进度;成功返回后等待原 Dialog 的退出动画,不把尚未卸载误判为抢焦点。
  208. await $('[data-testid="ssh-dialog"]').waitForExist({ reverse: true });
  209. expect(await $('[data-testid="source-server-boundary-dialog"]').isExisting()).toBe(false);
  210. expect(await $('[data-testid="virtual-project-name"]').isDisplayed()).toBe(false);
  211. expect(await getV4ComposerText()).toBe(text);
  212. if (attachments)
  213. expect(await getV4ComposerAttachments()).toEqual([
  214. expect.objectContaining({
  215. uploadStatus: "ready",
  216. text: expect.stringContaining(`${marker}.txt`),
  217. }),
  218. ]);
  219. }
  220. async function openProjectForm(sourceId?: string) {
  221. await $('[data-testid="project-section"]').moveTo();
  222. await $('[data-testid="virtual-project-add"]').click();
  223. await $('[data-testid="virtual-project-name"]').setValue(marker);
  224. if (sourceId) {
  225. await $('[data-testid="virtual-project-device"]').click();
  226. await $(`[role="option"][data-device-id="remote:server:${sourceId}"]`).click();
  227. }
  228. }
  229. async function closeProjectForm() {
  230. await $('[data-testid="virtual-project-name"]').waitForDisplayed();
  231. await browser.keys("Escape");
  232. await $('[data-testid="virtual-project-name"]').waitForExist({ reverse: true });
  233. }
  234. async function settle() {
  235. await browser.executeAsync((done) => {
  236. void Promise.all(
  237. document
  238. .getAnimations()
  239. .filter((animation) => animation.effect?.getComputedTiming().iterations !== Infinity)
  240. .map((animation) => animation.finished.catch(() => undefined)),
  241. ).then(() => requestAnimationFrame(() => done()));
  242. });
  243. }
  244. describe(marker, () => {
  245. let provider: SSHLifecycleProvider | undefined;
  246. afterEach(async function () {
  247. if (this.currentTest?.state === "failed") {
  248. await browser.saveScreenshot(
  249. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, "background-failure.png"),
  250. );
  251. const details = $('//summary[contains(.,"组件堆栈")]');
  252. if (await details.isExisting()) await details.click();
  253. await writeFile(
  254. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, "background-failure.txt"),
  255. await $("body").getText(),
  256. );
  257. }
  258. await restoreConnection();
  259. await releaseSourceReads();
  260. });
  261. after(async () => {
  262. await provider?.tunnel.close();
  263. await restoreHandoffProbes();
  264. await browser.electron.restoreAllMocks();
  265. await clearAppData();
  266. });
  267. it("RDUX15-19/20 four origins preserve navigation and resume the exact project intent", async function () {
  268. this.timeout(20 * 60_000);
  269. const config = readSSHRuntimeConfig(marker);
  270. await prepareV4ConversationE2E({ skipProvider: true });
  271. provider = await createSSHLifecycleProvider(config, marker);
  272. await selectUpstreamProviderModelById(SSH_LIFECYCLE_MODEL_ID, {
  273. providerId: provider.id,
  274. providerName: provider.name,
  275. });
  276. await selectUpstreamThoughtLevelValue("disabled");
  277. await installHandoffRpcProbe();
  278. await browser.execute(() =>
  279. (
  280. window as Window & { __testActions?: { setLocale(value: string): void } }
  281. ).__testActions?.setLocale("zh-CN"),
  282. );
  283. await openProjectForm();
  284. await $('[data-testid="virtual-project-name"]').setValue(`${marker}_LOCAL`);
  285. await $('[data-testid="virtual-project-save"]').click();
  286. const localRow = $(`[data-project-name="${marker}_LOCAL"]`);
  287. await localRow.waitForDisplayed();
  288. await localRow.moveTo();
  289. await localRow.$(`[data-testid="${TID_VIRTUAL_PROJECT_CREATE_TASK}"]`).click();
  290. await leaveProjectRow();
  291. await browser.waitUntil(async () =>
  292. Boolean(
  293. (await callHandoffHost<ProjectTree>(ServiceChannels.Project, "readTree")).projects.find(
  294. (project) => project.name === `${marker}_LOCAL`,
  295. )?.roots.length,
  296. ),
  297. );
  298. const localProject = (
  299. await callHandoffHost<ProjectTree>(ServiceChannels.Project, "readTree")
  300. ).projects.find((project) => project.name === `${marker}_LOCAL`)!;
  301. const localPath = localProject.roots[0]!.rootPath;
  302. const created = await callHandoffHost<{ session: { sessionId: string } }>(
  303. ServiceChannels.ZCodeAgent,
  304. "createSession",
  305. [
  306. {
  307. workspacePath: localPath,
  308. projectId: localProject.id,
  309. persistence: "immediate",
  310. importedHistory: {
  311. source: "claudeCode",
  312. title: marker,
  313. messages: [
  314. { role: "user", content: marker },
  315. { role: "assistant", content: "Original task remains local" },
  316. ],
  317. },
  318. },
  319. ],
  320. );
  321. const taskId = created.session.sessionId;
  322. await callHandoffHost(ServiceChannels.ZCodeTask, "resumeTask", [
  323. { taskId, workspacePath: localPath },
  324. ]);
  325. const toggle = localRow.$('[data-testid="virtual-project-toggle"]');
  326. if ((await toggle.getAttribute("aria-expanded")) !== "true") await toggle.click();
  327. await selectV4TaskById(taskId);
  328. await localRow.moveTo();
  329. await localRow.$(`[data-testid="${TID_VIRTUAL_PROJECT_CREATE_TASK}"]`).click();
  330. await leaveProjectRow();
  331. const text = `${marker} retained local draft`;
  332. await setV4ComposerText(text);
  333. await pasteV4ComposerFileAttachment(`${marker}.txt`, {
  334. base64: "YXR0YWNobWVudCBzdGF5cyBsb2NhbA==",
  335. mimeType: "text/plain",
  336. });
  337. await browser.waitUntil(
  338. async () => (await getV4ComposerAttachments())[0]?.uploadStatus === "ready",
  339. );
  340. await settings();
  341. await newConnection();
  342. await fillSSHPasswordSettings(config);
  343. await holdConnection();
  344. await clickLastEnabledSSHDialogButton(marker);
  345. await background();
  346. await back();
  347. const code = await waitHeld();
  348. await releaseConnection();
  349. await assertUninterrupted(text, true);
  350. await settings();
  351. if (code === "source-server-install-required") {
  352. const card = $('[data-testid="remote-connection-minimized"]');
  353. await card.waitForDisplayed();
  354. await browser.waitUntil(
  355. async () =>
  356. (await card.getText()).includes("处理") || (await card.getText()).includes("等待"),
  357. );
  358. await card.click();
  359. await holdConnection();
  360. await $('[data-testid="ssh-dialog"]').$('.//button[normalize-space(.)="安装并继续"]').click();
  361. await background();
  362. await back();
  363. expect(await waitHeld()).toBeUndefined();
  364. await releaseConnection();
  365. await assertUninterrupted(text, true);
  366. await settings();
  367. } else expect(code).toBeUndefined();
  368. // 普通设置入口也须消费已完成的后台流程,不能只显示空的连接进度页。
  369. await readyProgress();
  370. await openConnectionEntry();
  371. expect(await waitForSSHDirectoryStep(marker)).toBe("closed");
  372. await $('[data-testid="remote-connection-minimized"]').waitForExist({ reverse: true });
  373. const sourceId = (await snapshot()).servers[0]!.sourceServerId;
  374. expect((await directory()).entries).toHaveLength(0);
  375. const originalTask = (
  376. await callHandoffHost<ProjectTree>(ServiceChannels.Project, "readTree")
  377. ).tasks.find((task) => task.taskId === taskId);
  378. expect(originalTask?.hostId).toBe("local");
  379. expect(originalTask?.projectId).toBe(localProject.id);
  380. expect(originalTask?.workspacePath).toBe(localPath);
  381. await $(`[data-source-server-card="${sourceId}"]`).waitForDisplayed();
  382. // 结果仍在途时从同一普通入口重开,释放后必须按前台完成,不能再等待一次隐藏的继续。
  383. await newConnection();
  384. await fillSSHPasswordSettings(config);
  385. await holdConnection();
  386. await clickLastEnabledSSHDialogButton(marker);
  387. await background();
  388. expect(await waitHeld()).toBeUndefined();
  389. await openConnectionEntry();
  390. await $('[data-testid="ssh-dialog"]').waitForDisplayed();
  391. await releaseConnection();
  392. await $('[data-testid="ssh-dialog"]').waitForExist({ reverse: true });
  393. await $('[data-testid="remote-connection-minimized"]').waitForExist({ reverse: true });
  394. expect(
  395. await browser.electron.execute(() => globalThis.__backgroundConnectionProbe?.calls),
  396. ).toBe(1);
  397. expect((await directory()).entries).toHaveLength(0);
  398. expect((await snapshot()).servers.map((server) => server.sourceServerId)).toContain(sourceId);
  399. for (const close of await $$('#zcode-toast-host button[aria-label="关闭"]'))
  400. await close.click();
  401. await back();
  402. // 项目新增:原表单在设置背后保持同一 owner;完成与继续均不自动保存。
  403. await openProjectForm();
  404. await $('[data-testid="virtual-project-device"]').click();
  405. await $('//*[@role="option" and contains(.,"添加远程设备")]').click();
  406. await fillSSHPasswordSettings(config);
  407. await holdConnection();
  408. await clickLastEnabledSSHDialogButton(marker);
  409. await background();
  410. await back();
  411. expect(await waitHeld()).toBeUndefined();
  412. await releaseConnection();
  413. await assertUninterrupted(text, true);
  414. const noticeContinue = $('//div[@id="zcode-toast-host"]//button[normalize-space(.)="继续"]');
  415. await noticeContinue.waitForDisplayed({ timeout: 90_000 });
  416. await browser.saveScreenshot(
  417. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, "background-completion-notice.png"),
  418. );
  419. await noticeContinue.click();
  420. await $('[data-testid="virtual-project-name"]').waitForDisplayed();
  421. expect(await $('[data-testid="virtual-project-name"]').getValue()).toBe(marker);
  422. expect((await directory()).entries).toHaveLength(0);
  423. await closeProjectForm();
  424. // 后台取消配置也不能让隐藏项目弹窗在设置上重新出现。
  425. await openProjectForm();
  426. await $('[data-testid="virtual-project-device"]').click();
  427. await $('//*[@role="option" and contains(.,"添加远程设备")]').click();
  428. await background();
  429. await $("[data-background-connection]").$('.//button[normalize-space(.)="取消此连接"]').click();
  430. expect(await $('[data-testid="virtual-project-name"]').isDisplayed()).toBe(false);
  431. expect(await $("[data-settings-content-frame]").isDisplayed()).toBe(true);
  432. await back();
  433. expect(await $('[data-testid="virtual-project-name"]').getValue()).toBe(marker);
  434. await closeProjectForm();
  435. // 同一离线设备:选择目录和已有项目必须保留不同的后续动作。
  436. for (const action of ["virtual-project-browse", "virtual-project-existing"]) {
  437. await callHandoffHost(ServiceChannels.SourceServerManagement, "disconnectSource", [sourceId]);
  438. await openProjectForm(sourceId);
  439. await browser.waitUntil(async () =>
  440. (await $('[data-testid="virtual-project-device"]').getText()).includes("离线"),
  441. );
  442. await holdConnection();
  443. await $(`[data-testid="${action}"]`).click();
  444. await $('[data-testid="ssh-dialog"]').waitForDisplayed();
  445. // 已有设备连接必须留在原项目页;后台只收起同一 flow。
  446. expect(await $("[data-settings-content-frame]").isDisplayed()).toBe(false);
  447. await background();
  448. expect(await $("[data-settings-content-frame]").isDisplayed()).toBe(false);
  449. expect(await waitHeld()).toBeUndefined();
  450. await releaseConnection();
  451. await assertUninterrupted(text, true);
  452. await settings();
  453. await continueReady();
  454. if (action === "virtual-project-existing") {
  455. await $('[data-testid="remote-project-back"]').waitForDisplayed();
  456. expect(await $('[data-testid="virtual-project-directory-browser"]').isExisting()).toBe(
  457. false,
  458. );
  459. await $('[data-testid="remote-project-back"]').click();
  460. } else {
  461. const browserPanel = $('[data-testid="virtual-project-directory-browser"]');
  462. await browserPanel.waitForDisplayed();
  463. await browserPanel.$('.//button[normalize-space(.)="取消"]').click();
  464. }
  465. await $('[data-testid="virtual-project-name"]').waitForDisplayed();
  466. expect(await $('[data-testid="virtual-project-name"]').getValue()).toBe(marker);
  467. expect((await directory()).entries).toHaveLength(0);
  468. await closeProjectForm();
  469. }
  470. // 聊天来源:后台不锁原草稿,完成只通知;显式继续必须确认目录,再手动首发。
  471. const hostId = remoteHostIdFromWorkspaceIdentity(
  472. buildServerRemoteWorkspaceIdentity({ serverId: sourceId, workspacePath: "/" }),
  473. )!;
  474. const remotePath = `${config.workspacePaths[0]!}/background-folder-${Date.now()}`;
  475. expect(
  476. (await runSSHCommand(config, "mkdir -p -- '" + remotePath.replaceAll("'", "'\\''") + "'"))
  477. .code,
  478. ).toBe(0);
  479. const existing = await callHandoffHost<VirtualProject>(ServiceChannels.Project, "saveProject", [
  480. { hostId, roots: [remotePath], name: marker + " remote existing" },
  481. ]);
  482. const beforeRemote = await callHandoffHost<ProjectTree>(ServiceChannels.Project, "readTree", [
  483. { hostId },
  484. ]);
  485. const beforeLocal = await callHandoffHost<ProjectTree>(ServiceChannels.Project, "readTree", [
  486. { hostId: "local" },
  487. ]);
  488. await $(`[data-testid="${TID_COMPOSER_WORKSPACE_TRIGGER}"]`).click();
  489. await $(`[data-testid="${TID_COMPOSER_REMOTE_CONNECTION}"]`).click();
  490. await fillSSHPasswordSettings(config);
  491. await holdConnection();
  492. await clickLastEnabledSSHDialogButton(marker);
  493. await background();
  494. await back();
  495. await assertUninterrupted(text, true);
  496. expect(await $('[data-testid="v4-composer-send"]').isEnabled()).toBe(true);
  497. expect(await waitHeld()).toBeUndefined();
  498. await releaseConnection();
  499. await assertUninterrupted(text, true);
  500. expect(await $('[data-testid="chat-remote-folder"]').isExisting()).toBe(false);
  501. await settings();
  502. await continueReady();
  503. const picker = $('[data-testid="chat-remote-folder"]');
  504. await picker.waitForDisplayed();
  505. expect(await getV4ComposerText()).toBe(text);
  506. expect(await $('[data-testid="v4-composer-send"]').isEnabled()).toBe(false);
  507. await browser.execute(() =>
  508. document
  509. .querySelector<HTMLButtonElement>('[data-testid="v4-composer-send"]')
  510. ?.form?.requestSubmit(),
  511. );
  512. expect(
  513. (
  514. await callHandoffHost<ProjectTree>(ServiceChannels.Project, "readTree", [
  515. { hostId: "local" },
  516. ])
  517. ).tasks,
  518. ).toEqual(beforeLocal.tasks);
  519. // 首次继续取消只恢复原目标,Source 和其他已用连接仍存在。
  520. await browser.keys("Escape");
  521. await picker.waitForExist({ reverse: true });
  522. await assertUninterrupted(text, true);
  523. expect(await $('[data-testid="chat-restored-target"]').getText()).toContain(localProject.name);
  524. expect(
  525. (await snapshot()).states.some(
  526. (state) => state.sourceServerId === sourceId && state.state === "online",
  527. ),
  528. ).toBe(true);
  529. expect((await directory()).entries).toHaveLength(0);
  530. // 已放弃的原草稿不能由旧后台继续恢复,也不能锁住新任务。
  531. await $(`[data-testid="${TID_COMPOSER_WORKSPACE_TRIGGER}"]`).click();
  532. await $(`[data-testid="${TID_COMPOSER_REMOTE_CONNECTION}"]`).click();
  533. await fillSSHPasswordSettings(config);
  534. await holdConnection();
  535. await clickLastEnabledSSHDialogButton(marker);
  536. await background();
  537. await back();
  538. await selectV4TaskById(taskId);
  539. expect(await waitHeld()).toBeUndefined();
  540. await releaseConnection();
  541. await settings();
  542. await continueReady();
  543. await $('[data-testid="remote-connection-minimized"]').waitForExist({ reverse: true });
  544. expect(await picker.isExisting()).toBe(false);
  545. expect(await $("[data-settings-content-frame]").isDisplayed()).toBe(true);
  546. await back();
  547. await localRow.moveTo();
  548. await localRow.$(`[data-testid="${TID_VIRTUAL_PROJECT_CREATE_TASK}"]`).click();
  549. await leaveProjectRow();
  550. await setV4ComposerText(text);
  551. await $(`[data-testid="${TID_COMPOSER_WORKSPACE_TRIGGER}"]`).click();
  552. await $(`[data-testid="${TID_COMPOSER_REMOTE_CONNECTION}"]`).click();
  553. await fillSSHPasswordSettings(config);
  554. await holdConnection();
  555. await clickLastEnabledSSHDialogButton(marker);
  556. await background();
  557. await back();
  558. expect(await waitHeld()).toBeUndefined();
  559. await releaseConnection();
  560. await assertUninterrupted(text);
  561. const continueNotice = $(
  562. '(//div[@id="zcode-toast-host"]//button[normalize-space(.)="继续"])[last()]',
  563. );
  564. await continueNotice.waitForDisplayed({ timeout: 90_000 });
  565. await holdSourceReads();
  566. await continueNotice.click();
  567. await browser.waitUntil(() =>
  568. browser.execute(() => Boolean(window.__backgroundSourceReads?.requests.length)),
  569. );
  570. expect(await $('[data-testid="v4-composer-send"]').isEnabled()).toBe(false);
  571. await $('[data-testid="ssh-dialog"]').waitForDisplayed();
  572. // 前台焦点属于连接弹窗,直接按 Enter 会合法触发“收起”;定向向原输入框发送事件以验证提交门禁。
  573. await browser.execute(() => {
  574. document.querySelector('[data-testid="v4-composer-input"]')?.dispatchEvent(
  575. new KeyboardEvent("keydown", {
  576. key: "Enter",
  577. code: "Enter",
  578. bubbles: true,
  579. cancelable: true,
  580. }),
  581. );
  582. document
  583. .querySelector<HTMLButtonElement>('[data-testid="v4-composer-send"]')
  584. ?.form?.requestSubmit();
  585. });
  586. expect(await $('[data-testid="ssh-dialog"]').isDisplayed()).toBe(true);
  587. expect(
  588. (
  589. await callHandoffHost<ProjectTree>(ServiceChannels.Project, "readTree", [
  590. { hostId: "local" },
  591. ])
  592. ).tasks,
  593. ).toEqual(beforeLocal.tasks);
  594. await browser.saveScreenshot(
  595. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, "background-resume-validation-pending.png"),
  596. );
  597. await releaseSourceReads();
  598. await picker.waitForDisplayed();
  599. await picker.$("input").setValue(remotePath);
  600. await picker.$('button[type="submit"]').click();
  601. const confirmFolder = picker.$('[data-testid="directory-browser-confirm"]');
  602. await confirmFolder.waitForEnabled();
  603. await browser.saveScreenshot(
  604. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, "background-explicit-folder.png"),
  605. );
  606. await confirmFolder.click();
  607. const identity = buildServerRemoteWorkspaceIdentity({
  608. serverId: sourceId,
  609. workspacePath: remotePath,
  610. });
  611. await waitForRemoteTab({
  612. caseMarker: marker,
  613. expectedPath: remotePath,
  614. expectedIdentity: identity,
  615. });
  616. await picker.waitForExist({ reverse: true });
  617. expect(await $(`[data-testid="${TID_COMPOSER_WORKSPACE_TRIGGER}"]`).getText()).toContain(
  618. existing.name,
  619. );
  620. await selectUpstreamProviderModelById(SSH_LIFECYCLE_MODEL_ID, {
  621. providerId: provider.id,
  622. providerName: provider.name,
  623. });
  624. await selectUpstreamThoughtLevelValue("disabled");
  625. await sendV4PromptAndWaitAccepted(
  626. marker + " remote first message",
  627. marker,
  628. "后台继续后首发必须提交到远程项目",
  629. );
  630. await waitForV4AssistantMessageContaining("SSH_P0_TASK_LIFECYCLE_REPLY");
  631. const afterRemote = await callHandoffHost<ProjectTree>(ServiceChannels.Project, "readTree", [
  632. { hostId },
  633. ]);
  634. const sent = afterRemote.tasks.find((task) => task.projectId === existing.id)!;
  635. expect(sent).toMatchObject({
  636. hostId,
  637. projectId: existing.id,
  638. workspacePath: remotePath,
  639. workspaceIdentity: identity,
  640. });
  641. expect(afterRemote.projects.map((project) => project.id).sort()).toEqual(
  642. beforeRemote.projects.map((project) => project.id).sort(),
  643. );
  644. expect(
  645. (await directory()).entries.filter(
  646. (entry) => entry.projectId === existing.id && entry.hostId === hostId,
  647. ),
  648. ).toHaveLength(1);
  649. expect(
  650. (
  651. await callHandoffHost<ProjectTree>(ServiceChannels.Project, "readTree", [
  652. { hostId: "local" },
  653. ])
  654. ).tasks,
  655. ).toEqual(beforeLocal.tasks);
  656. await writeFile(
  657. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, "background-remote-first-submission.json"),
  658. JSON.stringify({ project: existing, task: sent }, null, 2),
  659. );
  660. await localRow.moveTo();
  661. await localRow.$(`[data-testid="${TID_VIRTUAL_PROJECT_CREATE_TASK}"]`).click();
  662. await leaveProjectRow();
  663. await assertUninterrupted(text, true);
  664. await settings();
  665. // 后台错误留在设置,不弹窗;查看不重发,取消不恢复项目/聊天旧界面。
  666. await newConnection();
  667. // 先填写目标再填口令:修改用户名按产品规则清除凭据;不同用户名防止复用在线认证。
  668. await fillSSHPasswordSettings({
  669. ...config,
  670. username: `${config.username}-missing`,
  671. password: `${config.password}-wrong`,
  672. });
  673. await holdConnection();
  674. await clickLastEnabledSSHDialogButton(marker);
  675. await background();
  676. await back();
  677. expect(await waitHeld()).toBeTruthy();
  678. await releaseConnection();
  679. await assertUninterrupted(text, true);
  680. await settings();
  681. const failed = $('[data-testid="remote-connection-minimized"]');
  682. await browser.waitUntil(async () => (await failed.getText()).includes("失败"));
  683. for (const locale of ["zh-CN", "en-US"])
  684. for (const theme of ["light", "dark"]) {
  685. await browser.execute(
  686. (language, color) => {
  687. const actions = (
  688. window as Window & {
  689. __testActions?: { setLocale(value: string): void; setTheme(value: string): void };
  690. }
  691. ).__testActions;
  692. actions?.setLocale(language);
  693. actions?.setTheme(color);
  694. },
  695. locale,
  696. theme,
  697. );
  698. await browser.electron.execute((electron) =>
  699. electron.BrowserWindow.getAllWindows()
  700. .find((window) => window.isVisible())
  701. ?.setSize(480, 900),
  702. );
  703. await settle();
  704. await browser.saveScreenshot(
  705. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, `background-${locale}-${theme}.png`),
  706. );
  707. expect(await failed.isDisplayed()).toBe(true);
  708. }
  709. await failed.click();
  710. expect(
  711. await browser.electron.execute(() => globalThis.__backgroundConnectionProbe?.calls),
  712. ).toBe(1);
  713. await browser.keys("Escape");
  714. expect(await $('[data-testid="remote-connection-minimized"]').isExisting()).toBe(false);
  715. await back();
  716. // Docker 使用独立远端环境;同一 Host 与前一来源串行验收。
  717. const container = process.env.ZCODE_E2E_SSH_CONTAINER;
  718. if (!container) throw new Error("Dedicated Docker container is required");
  719. await browser.electron.execute((electron) =>
  720. electron.BrowserWindow.getAllWindows()
  721. .find((window) => window.isVisible())
  722. ?.setSize(1440, 900),
  723. );
  724. await browser.execute(() =>
  725. (
  726. window as Window & { __testActions?: { setLocale(value: string): void } }
  727. ).__testActions?.setLocale("zh-CN"),
  728. );
  729. await setV4ComposerText("Docker background draft");
  730. await settings();
  731. await newConnection();
  732. await clickTestIdByDom(TID_REMOTE_KIND_DOCKER);
  733. await $('[data-testid="ssh-dialog"]')
  734. .$('.//button[normalize-space(.)="选择运行中的容器"]')
  735. .click();
  736. await $('[data-testid="docker-container-select"]').click();
  737. // 用例不稳定原因:容器列表来自本机 docker ps,多个 runner 并发时超过默认 5 秒才返回,
  738. // 直接 click 会报找不到条目(录像最后一帧条目已出现)。显式等待列表加载。
  739. const containerItem = $(
  740. `//*[@cmdk-item and .//*[normalize-space(.)=${JSON.stringify(container)}]]`,
  741. );
  742. await containerItem.waitForDisplayed({ timeout: 30_000 });
  743. await containerItem.click();
  744. await holdConnection();
  745. await clickLastEnabledSSHDialogButton(marker);
  746. await background();
  747. await back();
  748. let dockerCode = await waitHeld();
  749. await releaseConnection();
  750. await assertUninterrupted("Docker background draft");
  751. await settings();
  752. if (dockerCode === "source-server-install-required") {
  753. await $('[data-testid="remote-connection-minimized"]').click();
  754. await holdConnection();
  755. await $('[data-testid="ssh-dialog"]').$('.//button[normalize-space(.)="安装并继续"]').click();
  756. await background();
  757. await back();
  758. dockerCode = await waitHeld();
  759. await releaseConnection();
  760. await assertUninterrupted("Docker background draft");
  761. await settings();
  762. }
  763. expect(dockerCode).toBeUndefined();
  764. await continueReady();
  765. await $('[data-testid="remote-connection-minimized"]').waitForExist({ reverse: true });
  766. expect(
  767. (await snapshot()).profiles.some(
  768. (profile) => profile.transport === "docker" && profile.sourceServerId,
  769. ),
  770. ).toBe(true);
  771. expect((await directory()).entries).toHaveLength(1);
  772. await browser.saveScreenshot(
  773. join(process.env.ZCODE_E2E_ARTIFACT_DIR!, "background-docker-complete.png"),
  774. );
  775. });
  776. });