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

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