ssh-remote-lifecycle.ts 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  1. /* eslint-disable max-lines -- SSH lifecycle case 共用 setup/teardown、身份与故障辅助逻辑,集中维护以保持同一安全边界。 */
  2. import {
  3. TID_SETTINGS_BACK_BUTTON,
  4. TID_TASK_ITEM,
  5. TID_WORKSPACE_CLOSE,
  6. TID_WORKSPACE_ITEM,
  7. buildRemoteWorkspaceIdentity,
  8. testId,
  9. type RemoteTarget,
  10. } from "@zcode/shared";
  11. import {
  12. clickTestIdByDom,
  13. waitForWorkspaceApp,
  14. } from "./desktop-app.js";
  15. import { createCustomOpenAIChatCompletionsProvider } from "./custom-openai-provider.js";
  16. import { selectUpstreamProviderModelById } from "./upstream-provider.js";
  17. import {
  18. getUpstreamRequestRecordCount,
  19. waitForUpstreamRequest,
  20. } from "./conversation-session-network.js";
  21. import {
  22. prepareV4ConversationE2E,
  23. selectV4TaskById,
  24. sendV4PromptAndWaitAccepted,
  25. startNewV4Draft,
  26. waitForV4AssistantMessageContaining,
  27. waitForV4ConversationState,
  28. } from "./v4-conversation.js";
  29. import {
  30. clickLastEnabledSSHDialogButton,
  31. createSSHReplayTunnel,
  32. fillSSHPasswordSettings,
  33. openSSHRemoteDialog,
  34. readHostProcesses,
  35. readRemoteTabSnapshot,
  36. readSSHRuntimeConfig,
  37. runSSHCommand,
  38. selectSSHRemoteDirectory,
  39. waitForRemoteTab,
  40. waitForSSHDirectoryStep,
  41. type ReplayTunnel,
  42. type SSHConnectionConfig,
  43. type SSHRuntimeConfig,
  44. SSH_WORKSPACE_READY_TIMEOUT_MS,
  45. } from "./ssh-remote-p0.js";
  46. export const SSH_LIFECYCLE_MODEL_ID = "e2e-ssh-remote-lifecycle-model";
  47. export const SSH_LIFECYCLE_TURN_TIMEOUT_MS = 2 * 60_000;
  48. export interface SSHLifecycleTask {
  49. firstPrompt: string;
  50. firstReply: string;
  51. followPrompt: string;
  52. followReply: string;
  53. identity: string;
  54. label: "A" | "B";
  55. remoteSessionId: string;
  56. taskId: string;
  57. workspacePath: string;
  58. }
  59. export interface SSHLifecycleProvider {
  60. id: string;
  61. name: string;
  62. tunnel: ReplayTunnel;
  63. }
  64. export async function createSSHLifecycleProvider(
  65. config: SSHConnectionConfig,
  66. caseMarker: string,
  67. ): Promise<SSHLifecycleProvider> {
  68. const tunnel = await createSSHReplayTunnel(config, caseMarker);
  69. try {
  70. const provider = await createCustomOpenAIChatCompletionsProvider({
  71. baseURL: tunnel.baseURL,
  72. modelId: SSH_LIFECYCLE_MODEL_ID,
  73. providerName: `SSH remote lifecycle ${Date.now()}`,
  74. });
  75. await clickTestIdByDom(TID_SETTINGS_BACK_BUTTON, {
  76. timeout: 30_000,
  77. timeoutMsg: `${caseMarker}: provider 创建后设置页没有返回入口`,
  78. });
  79. return { ...provider, tunnel };
  80. } catch (error) {
  81. await tunnel.close();
  82. throw error;
  83. }
  84. }
  85. export async function connectSSHWorkspaceAndSendFirstTurn(options: {
  86. caseMarker: string;
  87. config: SSHConnectionConfig;
  88. provider: SSHLifecycleProvider;
  89. label: "A" | "B";
  90. workspacePath: string;
  91. }): Promise<SSHLifecycleTask> {
  92. const target: RemoteTarget = {
  93. kind: "ssh",
  94. host: options.config.host,
  95. port: options.config.port,
  96. username: options.config.username,
  97. };
  98. const identity = buildRemoteWorkspaceIdentity(options.workspacePath, target);
  99. await startNewV4Draft();
  100. await openSSHRemoteDialog(options.caseMarker);
  101. await fillSSHPasswordSettings(options.config);
  102. await clickLastEnabledSSHDialogButton(options.caseMarker);
  103. await waitForSSHDirectoryStep(options.caseMarker);
  104. await selectSSHRemoteDirectory(options.workspacePath, options.caseMarker);
  105. await waitForWorkspaceApp(
  106. options.workspacePath,
  107. SSH_WORKSPACE_READY_TIMEOUT_MS,
  108. );
  109. const tab = await waitForRemoteTab({
  110. caseMarker: options.caseMarker,
  111. expectedIdentity: identity,
  112. expectedPath: options.workspacePath,
  113. });
  114. expect(tab.remoteKind).toBe("ssh");
  115. expect(tab.remoteHost).toBe(options.config.host);
  116. expect(tab.secretPersistedInTab).toBe(false);
  117. if (!tab.remoteSessionId) {
  118. throw new Error(
  119. `${options.caseMarker}: workspace ${options.label} 缺少 remoteSessionId`,
  120. );
  121. }
  122. await selectUpstreamProviderModelById(SSH_LIFECYCLE_MODEL_ID, {
  123. includePlainModelFallback: false,
  124. providerId: options.provider.id,
  125. providerName: options.provider.name,
  126. });
  127. await startNewV4Draft();
  128. // fixture contract 使用稳定的 case/label 标记;run 身份已由 E2E profile 隔离。
  129. const marker = options.caseMarker.startsWith("E2E_")
  130. ? `${options.caseMarker}_${options.label}`
  131. : `E2E_${options.caseMarker}_${options.label}`;
  132. const replyMarker = options.caseMarker.startsWith("E2E_")
  133. ? options.caseMarker.slice("E2E_".length)
  134. : options.caseMarker;
  135. const task = {
  136. firstPrompt: `${marker}_FIRST_PROMPT`,
  137. firstReply: `${replyMarker}_REPLY`,
  138. followPrompt: `${marker}_FOLLOW_PROMPT`,
  139. followReply: `${replyMarker}_REPLY`,
  140. };
  141. const requestStart = await getUpstreamRequestRecordCount();
  142. await sendV4PromptAndWaitAccepted(
  143. `${task.firstPrompt}: 只回复 ${task.firstReply}`,
  144. task.firstPrompt,
  145. `${options.caseMarker}: workspace ${options.label} 首发没有被接受`,
  146. );
  147. const running = await waitForV4ConversationState(
  148. (snapshot) =>
  149. Boolean(snapshot.taskId && snapshot.taskId !== "draft") &&
  150. snapshot.state === "streaming",
  151. `${options.caseMarker}: workspace ${options.label} 首发没有进入 streaming`,
  152. SSH_LIFECYCLE_TURN_TIMEOUT_MS,
  153. );
  154. if (!running.taskId) {
  155. throw new Error(
  156. `${options.caseMarker}: workspace ${options.label} 首发没有 taskId`,
  157. );
  158. }
  159. await waitForUpstreamRequest(
  160. { lastUserMessageIncludes: [task.firstPrompt] },
  161. `${options.caseMarker}: workspace ${options.label} 首发没有到达 provider`,
  162. SSH_LIFECYCLE_TURN_TIMEOUT_MS,
  163. { afterIndex: requestStart - 1 },
  164. );
  165. await waitForV4AssistantMessageContaining(
  166. task.firstReply,
  167. SSH_LIFECYCLE_TURN_TIMEOUT_MS,
  168. );
  169. await waitForV4ConversationState(
  170. (snapshot) =>
  171. snapshot.taskId === running.taskId &&
  172. snapshot.state === "idle" &&
  173. snapshot.queueCount === 0,
  174. `${options.caseMarker}: workspace ${options.label} 首发没有回到 idle`,
  175. SSH_LIFECYCLE_TURN_TIMEOUT_MS,
  176. );
  177. return {
  178. ...task,
  179. identity,
  180. label: options.label,
  181. remoteSessionId: tab.remoteSessionId,
  182. taskId: running.taskId,
  183. workspacePath: options.workspacePath,
  184. };
  185. }
  186. export async function sendSSHFollowTurn(
  187. task: SSHLifecycleTask,
  188. caseMarker: string,
  189. foreignPrompt?: string,
  190. ): Promise<void> {
  191. await selectV4TaskById(task.taskId, 30_000);
  192. await waitForRemoteTab({
  193. caseMarker,
  194. expectedIdentity: task.identity,
  195. expectedPath: task.workspacePath,
  196. expectedRemoteSessionId: task.remoteSessionId,
  197. });
  198. const requestStart = await getUpstreamRequestRecordCount();
  199. await sendV4PromptAndWaitAccepted(
  200. `${task.followPrompt}: 只回复 ${task.followReply}`,
  201. task.followPrompt,
  202. `${caseMarker}: workspace ${task.label} 续发没有被接受`,
  203. );
  204. await waitForUpstreamRequest(
  205. {
  206. ...(foreignPrompt ? { excludes: [foreignPrompt] } : {}),
  207. includes: [task.firstPrompt],
  208. lastUserMessageIncludes: [task.followPrompt],
  209. },
  210. `${caseMarker}: workspace ${task.label} 续发历史或目标 workspace 错误`,
  211. SSH_LIFECYCLE_TURN_TIMEOUT_MS,
  212. { afterIndex: requestStart - 1 },
  213. );
  214. await waitForV4AssistantMessageContaining(
  215. task.followReply,
  216. SSH_LIFECYCLE_TURN_TIMEOUT_MS,
  217. );
  218. await waitForV4ConversationState(
  219. (snapshot) =>
  220. snapshot.taskId === task.taskId &&
  221. snapshot.state === "idle" &&
  222. snapshot.queueCount === 0,
  223. `${caseMarker}: workspace ${task.label} 续发没有回到 idle`,
  224. SSH_LIFECYCLE_TURN_TIMEOUT_MS,
  225. );
  226. }
  227. export async function reconnectSSHWorkspaceThroughUI(options: {
  228. caseMarker: string;
  229. config: SSHConnectionConfig;
  230. workspacePath: string;
  231. }): Promise<{
  232. remoteSessionId: string;
  233. identity: string;
  234. }> {
  235. const identity = buildSSHIdentity(options.config, options.workspacePath);
  236. await startNewV4Draft();
  237. await openSSHRemoteDialog(options.caseMarker);
  238. await fillSSHPasswordSettings(options.config);
  239. await clickLastEnabledSSHDialogButton(options.caseMarker);
  240. await waitForSSHDirectoryStep(options.caseMarker);
  241. await selectSSHRemoteDirectory(options.workspacePath, options.caseMarker);
  242. await waitForWorkspaceApp(
  243. options.workspacePath,
  244. SSH_WORKSPACE_READY_TIMEOUT_MS,
  245. );
  246. const tab = await waitForRemoteTab({
  247. caseMarker: options.caseMarker,
  248. expectedIdentity: identity,
  249. expectedPath: options.workspacePath,
  250. });
  251. if (!tab.remoteSessionId) {
  252. throw new Error(`${options.caseMarker}: 重连后缺少 remoteSessionId`);
  253. }
  254. expect(tab.remoteKind).toBe("ssh");
  255. expect(tab.remoteHost).toBe(options.config.host);
  256. expect(tab.secretPersistedInTab).toBe(false);
  257. return { identity, remoteSessionId: tab.remoteSessionId };
  258. }
  259. export async function removeSSHWorkspace(
  260. workspacePath: string,
  261. caseMarker: string,
  262. ): Promise<void> {
  263. const workspaceItemId = testId(TID_WORKSPACE_ITEM, workspacePath);
  264. await browser.waitUntil(
  265. async () =>
  266. browser.execute((itemId) => {
  267. const item = Array.from(
  268. document.querySelectorAll<HTMLElement>("[data-testid]"),
  269. ).find((candidate) => candidate.dataset.testid === itemId);
  270. if (!item) return false;
  271. const moreButton = Array.from(
  272. item.closest("li")?.querySelectorAll<HTMLButtonElement>("button") ??
  273. [],
  274. ).find((button) => {
  275. const label = (button.getAttribute("aria-label") ?? "").toLowerCase();
  276. return label.includes("more") || label.includes("更多");
  277. });
  278. if (!moreButton) return false;
  279. moreButton.click();
  280. return true;
  281. }, workspaceItemId),
  282. {
  283. timeout: 30_000,
  284. timeoutMsg: `${caseMarker}: workspace ${workspacePath} 没有显示更多菜单入口`,
  285. },
  286. );
  287. await clickTestIdByDom(testId(TID_WORKSPACE_CLOSE, workspacePath), {
  288. timeout: 15_000,
  289. timeoutMsg: `${caseMarker}: workspace ${workspacePath} 没有显示移除入口`,
  290. });
  291. await browser.waitUntil(
  292. () =>
  293. browser.execute((itemId) => {
  294. const item = Array.from(
  295. document.querySelectorAll<HTMLElement>("[data-testid]"),
  296. ).find((candidate) => candidate.dataset.testid === itemId);
  297. return !item;
  298. }, workspaceItemId),
  299. {
  300. timeout: 30_000,
  301. timeoutMsg: `${caseMarker}: workspace ${workspacePath} 移除后仍在侧栏`,
  302. },
  303. );
  304. }
  305. export async function waitForRemoteWorkspaceDisconnected(
  306. identity: string,
  307. caseMarker: string,
  308. ): Promise<void> {
  309. await browser.waitUntil(
  310. async () => {
  311. try {
  312. const snapshot = await readRemoteTabSnapshot(identity);
  313. return (
  314. snapshot.workspaceIdentity === identity &&
  315. snapshot.remoteSessionId === null
  316. );
  317. } catch {
  318. return false;
  319. }
  320. },
  321. {
  322. timeout: SSH_WORKSPACE_READY_TIMEOUT_MS,
  323. timeoutMsg: `${caseMarker}: remote workspace 没有进入 disconnected 保留态`,
  324. },
  325. );
  326. }
  327. export async function reconnectSSHWorkspace(
  328. workspacePath: string,
  329. caseMarker: string,
  330. ): Promise<void> {
  331. const workspaceItemId = testId(TID_WORKSPACE_ITEM, workspacePath);
  332. await browser.waitUntil(
  333. async () =>
  334. browser.execute((itemId) => {
  335. const item = Array.from(
  336. document.querySelectorAll<HTMLElement>("[data-testid]"),
  337. ).find((candidate) => candidate.dataset.testid === itemId);
  338. const button = Array.from(
  339. item?.closest("li")?.querySelectorAll<HTMLButtonElement>("button") ??
  340. [],
  341. ).find((candidate) => {
  342. const label = (candidate.getAttribute("aria-label") ?? "").toLowerCase();
  343. return label.includes("reconnect") || label.includes("重新连接");
  344. });
  345. if (!button || button.disabled) return false;
  346. button.click();
  347. return true;
  348. }, workspaceItemId),
  349. {
  350. timeout: 30_000,
  351. timeoutMsg: `${caseMarker}: workspace ${workspacePath} 没有显示可用的重连按钮`,
  352. },
  353. );
  354. }
  355. export async function listRemoteZCodeServerPids(
  356. config: SSHConnectionConfig,
  357. ): Promise<number[]> {
  358. const result = await runSSHCommand(config, "ps -eo pid=,args=");
  359. if (result.code !== 0) {
  360. throw new Error(`读取远端 zcode-server PID 失败: ${result.stderr}`);
  361. }
  362. return result.stdout
  363. .split("\n")
  364. .flatMap((line) => {
  365. const match = line.match(/^\s*(\d+)\s+.*(?:^|\s)zcode-server\.cjs(?:\s|$)/u);
  366. return match ? [Number.parseInt(match[1]!, 10)] : [];
  367. })
  368. .filter((pid) => Number.isSafeInteger(pid) && pid > 0);
  369. }
  370. export async function stopOwnedSSHServer(
  371. config: SSHConnectionConfig,
  372. beforePids: readonly number[],
  373. caseMarker: string,
  374. ): Promise<number> {
  375. const currentPids = await listRemoteZCodeServerPids(config);
  376. const owned = currentPids.filter((pid) => !beforePids.includes(pid));
  377. if (owned.length !== 1) {
  378. throw new Error(
  379. `${caseMarker}: 只允许终止本 case 新建的一个 zcode-server,before=${beforePids.join(",")}, current=${currentPids.join(",")}`,
  380. );
  381. }
  382. const pid = owned[0]!;
  383. const result = await runSSHCommand(config, `kill -TERM -- ${pid}`);
  384. if (result.code !== 0) {
  385. throw new Error(`${caseMarker}: 终止远端 zcode-server ${pid} 失败: ${result.stderr}`);
  386. }
  387. await browser.waitUntil(
  388. async () => !(await listRemoteZCodeServerPids(config)).includes(pid),
  389. {
  390. timeout: SSH_WORKSPACE_READY_TIMEOUT_MS,
  391. timeoutMsg: `${caseMarker}: 远端 zcode-server ${pid} 没有退出`,
  392. },
  393. );
  394. return pid;
  395. }
  396. export async function waitForRendererAfterColdRestart(
  397. caseMarker: string,
  398. ): Promise<void> {
  399. await browser.waitUntil(
  400. async () => {
  401. try {
  402. const puppeteer = await browser.getPuppeteer();
  403. const target = puppeteer
  404. .targets()
  405. .find((candidate) => candidate.url().includes("/renderer/index.html"));
  406. const targetId = target
  407. ? ((target as unknown as { _targetId?: string })._targetId ?? null)
  408. : null;
  409. if (!targetId) return false;
  410. await browser.switchToWindow(targetId);
  411. return true;
  412. } catch {
  413. return false;
  414. }
  415. },
  416. {
  417. timeout: 60_000,
  418. interval: 250,
  419. timeoutMsg: `${caseMarker}: cold restart 后没有找到 renderer target`,
  420. },
  421. );
  422. }
  423. export async function readTaskRowInWorkspace(
  424. task: SSHLifecycleTask,
  425. caseMarker: string,
  426. ): Promise<void> {
  427. await browser.waitUntil(
  428. async () =>
  429. browser.execute((taskId, workspaceId) => {
  430. const taskRow = Array.from(
  431. document.querySelectorAll<HTMLElement>("[data-testid]"),
  432. ).find((candidate) => candidate.dataset.testid === taskId);
  433. const workspaceRow = Array.from(
  434. document.querySelectorAll<HTMLElement>("[data-testid]"),
  435. ).find((candidate) => candidate.dataset.testid === workspaceId);
  436. return Boolean(
  437. taskRow &&
  438. workspaceRow?.closest("li")?.contains(taskRow) &&
  439. !taskRow.querySelector('[data-error-indicator="true"]'),
  440. );
  441. }, testId(TID_TASK_ITEM, task.taskId), testId(TID_WORKSPACE_ITEM, task.workspacePath)),
  442. {
  443. timeout: 30_000,
  444. timeoutMsg: `${caseMarker}: task ${task.label} 没有恢复到正确 workspace`,
  445. },
  446. );
  447. }
  448. export function buildSSHIdentity(
  449. config: SSHConnectionConfig,
  450. workspacePath: string,
  451. ): string {
  452. const target: RemoteTarget = {
  453. kind: "ssh",
  454. host: config.host,
  455. port: config.port,
  456. username: config.username,
  457. };
  458. return buildRemoteWorkspaceIdentity(workspacePath, target);
  459. }
  460. export async function prepareSSHLifecycle(
  461. caseMarker: string,
  462. ): Promise<{
  463. config: SSHRuntimeConfig;
  464. initialHosts: Array<{ name: string; pid: number }>;
  465. provider: SSHLifecycleProvider;
  466. }> {
  467. const config = readSSHRuntimeConfig(caseMarker);
  468. await prepareV4ConversationE2E({ skipProvider: true });
  469. const initialHosts = await readHostProcesses();
  470. expect(initialHosts).toHaveLength(1);
  471. const provider = await createSSHLifecycleProvider(config, caseMarker);
  472. return { config, initialHosts, provider };
  473. }