conversation-session-ssh-remote-p0.test.ts 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607
  1. import { readFile, readdir } from "node:fs/promises";
  2. import { join } from "node:path";
  3. import { releaseControlledReplay } from "#e2e/helpers/controlled-replay";
  4. import { parseRemoteWorkspaceIdentity } from "@zcode/shared";
  5. import { TID_V4_COMPOSER_INPUT } from "@zcode/shared/test-ids";
  6. import { clearAppData, waitForWorkspaceApp } from "#e2e/helpers/desktop-app";
  7. import {
  8. refreshSeededOpenAIProvidersThroughSettings,
  9. seedCustomOpenAIChatCompletionsProvider,
  10. } from "#e2e/helpers/custom-openai-provider";
  11. import { resolveSeededReplayBaseUrl } from "#e2e/helpers/custom-openai-provider-store";
  12. import {
  13. selectUpstreamProviderModelById,
  14. selectUpstreamThoughtLevelValue,
  15. } from "#e2e/helpers/upstream-provider";
  16. import {
  17. getUpstreamRequestRecordCount,
  18. waitForUpstreamRequest,
  19. } from "#e2e/helpers/conversation-session-network";
  20. import {
  21. prepareV4ConversationE2E,
  22. selectV4TaskById,
  23. sendV4PromptAndWaitAccepted,
  24. waitForV4AssistantMessageContaining,
  25. waitForV4ConversationState,
  26. } from "#e2e/helpers/v4-conversation";
  27. import {
  28. beginConversationTelemetryCapture,
  29. waitForConversationReportInventory,
  30. } from "#e2e/helpers/conversation-telemetry-parity-capture";
  31. import {
  32. clickLastEnabledSSHDialogButton,
  33. createSSHReplayTunnel,
  34. readHostProcesses,
  35. fillSSHPasswordSettings,
  36. openSSHRemoteDialog,
  37. openSSHSourceDirectory,
  38. runSSHCommand,
  39. selectSSHRemoteDirectory,
  40. waitForSSHDirectoryStep,
  41. } from "#e2e/helpers/ssh-remote-p0";
  42. import { readProjectTaskRowState, type ProjectTaskRowState } from "#e2e/helpers/project-sidebar";
  43. const CASE_MARKER = "R1_SSH_P0_01";
  44. const PROMPT_MARKER = "E2E_SSH_REMOTE_P0";
  45. const MODEL_ID = "e2e-ssh-remote-p0-model";
  46. const WORKSPACE_READY_TIMEOUT_MS = 2 * 60_000;
  47. const TURN_TIMEOUT_MS = 2 * 60_000;
  48. interface SSHRuntimeConfig {
  49. host: string;
  50. password: string;
  51. port: number;
  52. username: string;
  53. workspacePaths: readonly [string, string];
  54. }
  55. interface RemoteTabSnapshot {
  56. activeWorkspaceIdentity: string | null;
  57. activeWorkspacePath: string | null;
  58. remoteHost: string | null;
  59. remoteKind: string | null;
  60. remoteSessionId: string | null;
  61. secretPersistedInTab: boolean;
  62. workspaceIdentity: string | null;
  63. workspacePath: string | null;
  64. }
  65. interface ReplayTunnel {
  66. baseURL: string;
  67. close(): Promise<void>;
  68. }
  69. interface TaskCase {
  70. firstPrompt: string;
  71. firstReply: string;
  72. followPrompt: string;
  73. followReply: string;
  74. identity: string;
  75. label: "A" | "B";
  76. remoteSessionId: string;
  77. taskId: string;
  78. workspacePath: string;
  79. }
  80. const runningRowMismatches: Array<{
  81. taskId: string;
  82. label: string;
  83. observed: ProjectTaskRowState;
  84. }> = [];
  85. describe(`${CASE_MARKER}: SSH remote workspace P0`, () => {
  86. let replayTunnel: ReplayTunnel | null = null;
  87. after(async () => {
  88. await replayTunnel?.close();
  89. replayTunnel = null;
  90. await browser.electron.restoreAllMocks();
  91. await clearAppData();
  92. });
  93. it("R1-SSH-P0-01 在两个 SSH workspace 各自首发,并切回 task 续发", async function () {
  94. this.timeout(20 * 60_000);
  95. runningRowMismatches.length = 0;
  96. const config = readSSHRuntimeConfig();
  97. const [workspaceA, workspaceB] = config.workspacePaths;
  98. await prepareV4ConversationE2E({ skipProvider: true });
  99. const initialHosts = await readHostProcesses();
  100. expect(initialHosts).toHaveLength(1);
  101. const telemetryCapture = await beginConversationTelemetryCapture();
  102. replayTunnel = await createReplayTunnel(config);
  103. const previousReplayBaseURL = process.env.E2E_PROVIDER_RUNTIME_BASE_URL;
  104. let provider: { id: string; name: string };
  105. process.env.E2E_PROVIDER_RUNTIME_BASE_URL = replayTunnel.baseURL;
  106. try {
  107. provider = await seedCustomOpenAIChatCompletionsProvider({
  108. modelId: MODEL_ID,
  109. providerId: "e2e-ssh-remote-p0-provider",
  110. providerName: "SSH Remote P0",
  111. });
  112. await refreshSeededOpenAIProvidersThroughSettings([provider.name]);
  113. } finally {
  114. if (previousReplayBaseURL === undefined) {
  115. delete process.env.E2E_PROVIDER_RUNTIME_BASE_URL;
  116. } else {
  117. process.env.E2E_PROVIDER_RUNTIME_BASE_URL = previousReplayBaseURL;
  118. }
  119. }
  120. const provisioningRecordsBeforeConnect = await readProvisioningRecordCount(config);
  121. const runtimeLogCursor = await captureRuntimeLogCursor();
  122. const taskA = await connectWorkspaceAndSendFirstTurn({
  123. config,
  124. label: "A",
  125. provider,
  126. workspacePath: workspaceA,
  127. });
  128. const provisioningRecordsAfterFirstWorkspace = await waitForProvisioningRecordCountGreaterThan(
  129. config,
  130. provisioningRecordsBeforeConnect,
  131. );
  132. const taskB = await connectWorkspaceAndSendFirstTurn({
  133. config,
  134. label: "B",
  135. provider,
  136. workspacePath: workspaceB,
  137. });
  138. // 修复原因:Provisioning 的同步身份是 Remote Environment,不是 Workspace。
  139. // 同一 SSH Environment 打开第二个目录时必须复用已经完成的同步,不能再写一条记录。
  140. expect(await readProvisioningRecordCount(config)).toBe(provisioningRecordsAfterFirstWorkspace);
  141. expect(taskA.remoteSessionId).not.toBe(taskB.remoteSessionId);
  142. expect(await readHostProcesses()).toEqual(initialHosts);
  143. await switchTaskAndSendFollowTurn(taskA, taskB.firstPrompt);
  144. await switchTaskAndSendFollowTurn(taskB, taskA.firstPrompt);
  145. await assertTaskRow(taskA, { active: false, running: false });
  146. await assertTaskRow(taskB, { active: true, running: false });
  147. expect(await readHostProcesses()).toEqual(initialHosts);
  148. // Bug 回归(3.16.2 远程发送卡顿):远程 workspace 曾把高速卡与闲时任务请求发到远端,
  149. // 远端没有这两个频道,每次发送先等满 Host ChannelServer 的 1000ms 未知频道超时。
  150. // 三者只在本地生效:worktree 创建记录也必须读 base Host,不能因切到远程任务而误发订阅。
  151. // 四次远程发送与期间的后台查询不得出现这些未知频道超时。
  152. expect(
  153. await runtimeLogCursor.newLines(
  154. /Unknown channel: (?:highspeed-card|off-peak-task|managed-worktrees)\b/u,
  155. ),
  156. ).toEqual([]);
  157. expect(await runtimeLogCursor.newLines(/getCurrentOwnerKey.*is not a function/u)).toEqual([]);
  158. const reports = await waitForConversationReportInventory(telemetryCapture, {
  159. agent_step: 4,
  160. message_completion: 4,
  161. });
  162. for (const task of [taskA, taskB]) {
  163. const taskReports = reports.filter((report) => report.talk_id === task.taskId);
  164. expect(taskReports.filter((report) => report.element_name === "agent_step")).toHaveLength(2);
  165. expect(
  166. taskReports.filter((report) => report.element_name === "message_completion"),
  167. ).toHaveLength(2);
  168. for (const report of taskReports.filter(
  169. (candidate) =>
  170. candidate.element_name === "agent_step" ||
  171. candidate.element_name === "message_completion",
  172. )) {
  173. // 遥测合同(docs/monitoring/conversation-telemetry-v4.md):remote_kind 由稳定 workspace
  174. // identity 经 parseRemoteWorkspaceIdentity 解析,R3 Source Server 工作区的 identity kind 是
  175. // "server"(上方 waitForRemoteTab 亦按此断言);SSH 只是物理线路,不是该字段的取值。
  176. expect(report.event_extra_detail).toMatchObject({
  177. workspace_kind: "remote",
  178. remote_kind: "server",
  179. });
  180. }
  181. }
  182. process.stdout.write(
  183. `[${CASE_MARKER}] telemetry ${JSON.stringify(
  184. [taskA, taskB].map((task) => {
  185. const taskReports = reports.filter((report) => report.talk_id === task.taskId);
  186. return {
  187. agentStepCount: taskReports.filter((report) => report.element_name === "agent_step")
  188. .length,
  189. completionCount: taskReports.filter(
  190. (report) => report.element_name === "message_completion",
  191. ).length,
  192. taskId: task.taskId,
  193. };
  194. }),
  195. )}\n`,
  196. );
  197. expect(runningRowMismatches).toEqual([]);
  198. });
  199. });
  200. /** 只看游标之后新增的 Host/Main 运行日志,避免把启动期的日志算进本次断言。 */
  201. async function captureRuntimeLogCursor() {
  202. const root = await browser.electron.execute(() => process.env.ZCODE_E2E_RUNTIME_LOG_DIR!);
  203. const read = async () => {
  204. const names = (await readdir(root)).filter((name) => name.endsWith(".log"));
  205. return new Map(
  206. await Promise.all(
  207. names.map(async (name) => [name, await readFile(join(root, name), "utf8")] as const),
  208. ),
  209. );
  210. };
  211. const before = await read();
  212. return {
  213. async newLines(pattern: RegExp): Promise<string[]> {
  214. const after = await read();
  215. return [...after]
  216. .flatMap(([name, text]) => text.slice(before.get(name)?.length ?? 0).split("\n"))
  217. .filter((line) => pattern.test(line));
  218. },
  219. };
  220. }
  221. async function readProvisioningRecordCount(config: SSHRuntimeConfig): Promise<number> {
  222. const result = await runSSHCommand(
  223. config,
  224. 'if [ -f "$HOME/.zcode/v2/runtime/provider/provisioning.json" ]; then cat "$HOME/.zcode/v2/runtime/provider/provisioning.json"; else printf \'{"records":[]}\'; fi',
  225. );
  226. if (result.code !== 0) {
  227. throw new Error(`${CASE_MARKER}: 读取远端 Provisioning 状态失败:${result.stderr}`);
  228. }
  229. const parsed = JSON.parse(result.stdout) as { records?: unknown };
  230. if (!Array.isArray(parsed.records)) {
  231. throw new Error(`${CASE_MARKER}: 远端 Provisioning 状态缺少 records`);
  232. }
  233. return parsed.records.length;
  234. }
  235. async function waitForProvisioningRecordCountGreaterThan(
  236. config: SSHRuntimeConfig,
  237. baseline: number,
  238. ): Promise<number> {
  239. let observed = baseline;
  240. await browser.waitUntil(
  241. async () => {
  242. observed = await readProvisioningRecordCount(config);
  243. return observed > baseline;
  244. },
  245. {
  246. timeout: 30_000,
  247. interval: 500,
  248. timeoutMsg: `${CASE_MARKER}: 首个远端 Workspace 没有完成 Provisioning`,
  249. },
  250. );
  251. return observed;
  252. }
  253. function readSSHRuntimeConfig(): SSHRuntimeConfig {
  254. const host = requireSecretEnv("ZCODE_E2E_SSH_HOST");
  255. const username = requireSecretEnv("ZCODE_E2E_SSH_USERNAME");
  256. const password = requireSecretEnv("ZCODE_E2E_SSH_PASSWORD");
  257. const portText = process.env.ZCODE_E2E_SSH_PORT?.trim() || "22";
  258. const port = Number.parseInt(portText, 10);
  259. if (!Number.isSafeInteger(port) || port < 1 || port > 65_535) {
  260. throw new Error(`${CASE_MARKER}: ZCODE_E2E_SSH_PORT 必须是 1..65535 的整数`);
  261. }
  262. const workspacePaths = (
  263. process.env.ZCODE_E2E_SSH_WORKSPACE_PATHS?.split(",") ?? ["/root", "/home"]
  264. )
  265. .map((value) => value.trim())
  266. .filter(Boolean);
  267. if (
  268. workspacePaths.length !== 2 ||
  269. workspacePaths.some((value) => !value.startsWith("/")) ||
  270. workspacePaths[0] === workspacePaths[1]
  271. ) {
  272. throw new Error(`${CASE_MARKER}: ZCODE_E2E_SSH_WORKSPACE_PATHS 必须是两个不同的绝对路径`);
  273. }
  274. return {
  275. host,
  276. password,
  277. port,
  278. username,
  279. workspacePaths: [workspacePaths[0]!, workspacePaths[1]!],
  280. };
  281. }
  282. function requireSecretEnv(name: string): string {
  283. const value = process.env[name]?.trim();
  284. if (!value) {
  285. throw new Error(`${CASE_MARKER}: 缺少 ${name}`);
  286. }
  287. return value;
  288. }
  289. async function connectWorkspaceAndSendFirstTurn(options: {
  290. config: SSHRuntimeConfig;
  291. label: "A" | "B";
  292. provider: { id: string; name: string };
  293. workspacePath: string;
  294. }): Promise<TaskCase> {
  295. // Bug 原因:本 spec 曾自带一份 SSH 向导轮询副本,只认独立 ConfirmDialog 的安装确认和
  296. // 目录页;产品已把安装确认内联到连接步骤(“安装并继续”),副本可能等满连接超时。
  297. // 统一复用 helpers/ssh-remote-p0.ts 的共享流程,与 connection-p0 / soak-dual 保持同一状态机。
  298. await openSSHRemoteDialog(CASE_MARKER);
  299. await fillSSHPasswordSettings(options.config);
  300. await clickLastEnabledSSHDialogButton(CASE_MARKER);
  301. const flow = await waitForSSHDirectoryStep(CASE_MARKER);
  302. if (flow === "closed") {
  303. // 向导已收起:从已注册设备行进入目录选择,追加 project workspace。
  304. await openSSHSourceDirectory(options.config, CASE_MARKER);
  305. }
  306. await selectSSHRemoteDirectory(options.workspacePath, CASE_MARKER);
  307. await waitForWorkspaceApp(options.workspacePath, WORKSPACE_READY_TIMEOUT_MS);
  308. const tab = await waitForRemoteTab({
  309. expectedPath: options.workspacePath,
  310. });
  311. expect(tab.remoteKind).toBe("ssh");
  312. expect(tab.remoteHost).toBe(options.config.host);
  313. expect(tab.secretPersistedInTab).toBe(false);
  314. if (!tab.remoteSessionId) {
  315. throw new Error(`${CASE_MARKER}: workspace ${options.label} 缺少 remoteSessionId`);
  316. }
  317. if (!tab.workspaceIdentity) {
  318. throw new Error(`${CASE_MARKER}: workspace ${options.label} 缺少稳定 workspaceIdentity`);
  319. }
  320. await assertRemoteComposerMounted();
  321. await selectUpstreamProviderModelById(MODEL_ID, {
  322. includePlainModelFallback: false,
  323. providerId: options.provider.id,
  324. providerName: options.provider.name,
  325. });
  326. // 项目创建已打开远程草稿;全局新建会切到本地未分类并丢失目标模型。
  327. await selectUpstreamThoughtLevelValue("disabled");
  328. const draft = await readRemoteTabSnapshot(tab.workspaceIdentity, options.workspacePath);
  329. expect(draft.activeWorkspaceIdentity).toBe(tab.workspaceIdentity);
  330. expect(draft.activeWorkspacePath).toBe(options.workspacePath);
  331. const firstPrompt = `${PROMPT_MARKER}_${options.label}_FIRST_PROMPT`;
  332. const firstReply = `${PROMPT_MARKER}_${options.label}_FIRST_REPLY`;
  333. const followPrompt = `${PROMPT_MARKER}_${options.label}_FOLLOW_PROMPT`;
  334. const followReply = `${PROMPT_MARKER}_${options.label}_FOLLOW_REPLY`;
  335. const requestStart = await getUpstreamRequestRecordCount();
  336. await sendV4PromptAndWaitAccepted(
  337. `${firstPrompt}: 只回复 ${firstReply}`,
  338. firstPrompt,
  339. `${options.label} 首发没有进入远端 task`,
  340. );
  341. const running = await waitForV4ConversationState(
  342. (snapshot) =>
  343. Boolean(snapshot.taskId && snapshot.taskId !== "draft") && snapshot.state === "streaming",
  344. `${options.label} 首发没有进入 running`,
  345. TURN_TIMEOUT_MS,
  346. );
  347. if (!running.taskId) {
  348. throw new Error(`${CASE_MARKER}: workspace ${options.label} 首发没有 taskId`);
  349. }
  350. const task: TaskCase = {
  351. firstPrompt,
  352. firstReply,
  353. followPrompt,
  354. followReply,
  355. identity: tab.workspaceIdentity,
  356. label: options.label,
  357. remoteSessionId: tab.remoteSessionId,
  358. taskId: running.taskId,
  359. workspacePath: options.workspacePath,
  360. };
  361. await assertTaskRow(task, { active: true, running: true });
  362. await releaseControlledReplay(`ssh-remote-p0-${task.label.toLowerCase()}-first`);
  363. await waitForUpstreamRequest(
  364. {
  365. lastUserMessageIncludes: [firstPrompt],
  366. },
  367. `${options.label} 首发请求没有到达 provider`,
  368. TURN_TIMEOUT_MS,
  369. { afterIndex: requestStart - 1 },
  370. );
  371. await waitForV4AssistantMessageContaining(firstReply, TURN_TIMEOUT_MS);
  372. await waitForV4ConversationState(
  373. (snapshot) =>
  374. snapshot.taskId === task.taskId && snapshot.state === "idle" && snapshot.queueCount === 0,
  375. `${options.label} 首发完成后没有回到 idle`,
  376. TURN_TIMEOUT_MS,
  377. );
  378. await assertTaskRow(task, { active: true, running: false });
  379. return task;
  380. }
  381. async function switchTaskAndSendFollowTurn(
  382. task: TaskCase,
  383. foreignFirstPrompt: string,
  384. ): Promise<void> {
  385. await selectV4TaskById(task.taskId, 30_000);
  386. await waitForRemoteTab({
  387. expectedIdentity: task.identity,
  388. expectedPath: task.workspacePath,
  389. expectedRemoteSessionId: task.remoteSessionId,
  390. });
  391. await assertRemoteComposerMounted();
  392. await assertTaskRow(task, { active: true, running: false });
  393. const requestStart = await getUpstreamRequestRecordCount();
  394. await sendV4PromptAndWaitAccepted(
  395. `${task.followPrompt}: 只回复 ${task.followReply}`,
  396. task.followPrompt,
  397. `${task.label} 续发没有进入原 task`,
  398. );
  399. await assertTaskRow(task, { active: true, running: true });
  400. await releaseControlledReplay(`ssh-remote-p0-${task.label.toLowerCase()}-follow`);
  401. await waitForUpstreamRequest(
  402. {
  403. excludes: [foreignFirstPrompt],
  404. includes: [task.firstPrompt],
  405. lastUserMessageIncludes: [task.followPrompt],
  406. },
  407. `${task.label} 续发请求没有携带本 task 历史,或混入另一 workspace`,
  408. TURN_TIMEOUT_MS,
  409. { afterIndex: requestStart - 1 },
  410. );
  411. await waitForV4AssistantMessageContaining(task.followReply, TURN_TIMEOUT_MS);
  412. await waitForV4ConversationState(
  413. (snapshot) =>
  414. snapshot.taskId === task.taskId && snapshot.state === "idle" && snapshot.queueCount === 0,
  415. `${task.label} 续发完成后没有回到 idle`,
  416. TURN_TIMEOUT_MS,
  417. );
  418. await assertTaskRow(task, { active: true, running: false });
  419. }
  420. async function assertRemoteComposerMounted(): Promise<void> {
  421. // Bug 回归:远程 Highspeed 占位实现漏掉 owner 查询,SessionPane 挂载即同步抛错。
  422. // 草稿和历史任务都必须实际渲染输入框,不能只凭远程 tab 注册成功判断聊天可用。
  423. await expect($(`[data-testid="${TID_V4_COMPOSER_INPUT}"]`)).toBeDisplayed();
  424. expect(await browser.execute(() => document.body.innerText)).not.toContain(
  425. "getCurrentOwnerKey is not a function",
  426. );
  427. }
  428. async function assertTaskRow(
  429. task: TaskCase,
  430. expected: { active: boolean; running: boolean },
  431. ): Promise<void> {
  432. let latest: ProjectTaskRowState | null = null;
  433. await browser
  434. .waitUntil(
  435. async () => {
  436. // 虚拟项目侧栏:task 行必须落在其 workspace 对应的项目 section 内。
  437. latest = await readProjectTaskRowState(task.taskId, task.workspacePath, task.identity);
  438. return (
  439. latest.exists &&
  440. latest.inProject &&
  441. latest.active === expected.active &&
  442. latest.running === expected.running &&
  443. !latest.error
  444. );
  445. },
  446. {
  447. timeout: 30_000,
  448. interval: 100,
  449. timeoutMsg: `${CASE_MARKER}: task ${task.label} 列表状态不正确`,
  450. },
  451. )
  452. .catch((cause: unknown) => {
  453. // 运行图标缺失不应挡住历史隔离与遥测取证;严格保留末尾失败,不能放行归属或错误异常。
  454. if (
  455. expected.running &&
  456. latest?.exists &&
  457. latest.inProject &&
  458. latest.active === expected.active &&
  459. !latest.error &&
  460. !latest.running
  461. ) {
  462. runningRowMismatches.push({ taskId: task.taskId, label: task.label, observed: latest });
  463. process.stdout.write(
  464. `[${CASE_MARKER}] running-row-mismatch ${JSON.stringify(runningRowMismatches.at(-1))}\n`,
  465. );
  466. return;
  467. }
  468. throw new Error(
  469. `${CASE_MARKER}: task ${task.label} 列表状态不正确 expected=${JSON.stringify(expected)} latest=${JSON.stringify(latest)}`,
  470. { cause },
  471. );
  472. });
  473. }
  474. async function createReplayTunnel(config: SSHRuntimeConfig): Promise<ReplayTunnel> {
  475. return createSSHReplayTunnel(config, CASE_MARKER);
  476. }
  477. async function waitForRemoteTab(options: {
  478. expectedIdentity?: string;
  479. expectedPath: string;
  480. expectedRemoteSessionId?: string | null;
  481. timeoutMs?: number;
  482. }): Promise<RemoteTabSnapshot> {
  483. let snapshot: RemoteTabSnapshot | null = null;
  484. try {
  485. await browser.waitUntil(
  486. async () => {
  487. try {
  488. snapshot = await readRemoteTabSnapshot(options.expectedIdentity, options.expectedPath);
  489. const parsedIdentity = snapshot.workspaceIdentity
  490. ? parseRemoteWorkspaceIdentity(snapshot.workspaceIdentity)
  491. : null;
  492. const expectedIdentityMatches = options.expectedIdentity
  493. ? snapshot.workspaceIdentity === options.expectedIdentity
  494. : parsedIdentity?.kind === "server" &&
  495. parsedIdentity.workspacePath === options.expectedPath;
  496. return (
  497. snapshot.workspacePath === options.expectedPath &&
  498. snapshot.activeWorkspacePath === options.expectedPath &&
  499. expectedIdentityMatches &&
  500. snapshot.activeWorkspaceIdentity === snapshot.workspaceIdentity &&
  501. Boolean(snapshot.remoteSessionId) &&
  502. (!options.expectedRemoteSessionId ||
  503. snapshot.remoteSessionId === options.expectedRemoteSessionId)
  504. );
  505. } catch {
  506. return false;
  507. }
  508. },
  509. {
  510. timeout: options.timeoutMs ?? WORKSPACE_READY_TIMEOUT_MS,
  511. interval: 1_000,
  512. timeoutMsg: `${CASE_MARKER}: remote tab identity/session 没有收敛`,
  513. },
  514. );
  515. } catch (error) {
  516. // Bug 定位需要区分“remote tab 丢失”和“reload 后错误恢复到 local active tab”;
  517. // snapshot 不包含凭据,可以安全进入 E2E 失败证据。
  518. throw new Error(
  519. `${CASE_MARKER}: remote tab identity/session 没有收敛,latest=${JSON.stringify(snapshot)}`,
  520. { cause: error },
  521. );
  522. }
  523. if (!snapshot) throw new Error(`${CASE_MARKER}: remote tab snapshot 缺失`);
  524. return snapshot;
  525. }
  526. function readRemoteTabSnapshot(
  527. expectedIdentity?: string,
  528. expectedPath?: string,
  529. ): Promise<RemoteTabSnapshot> {
  530. return browser.execute(
  531. (identity, workspacePath) => {
  532. type RemoteTab = {
  533. id: string;
  534. kind: string;
  535. remoteSessionId?: string;
  536. remoteTarget?: Record<string, unknown>;
  537. workspaceIdentity?: string;
  538. workspacePath?: string;
  539. };
  540. const store = (
  541. window as Window & {
  542. __zcodeTabStoreE2E?: {
  543. getState?: () => {
  544. activeTabId?: string | null;
  545. activeWorkspaceIdentity?: string | null;
  546. activeWorkspacePath?: string | null;
  547. tabs?: RemoteTab[];
  548. };
  549. };
  550. }
  551. ).__zcodeTabStoreE2E;
  552. const state = store?.getState?.();
  553. const matchingRemoteTab = state?.tabs?.find((tab) =>
  554. identity ? tab.workspaceIdentity === identity : tab.workspacePath === workspacePath,
  555. );
  556. const remoteTarget = matchingRemoteTab?.remoteTarget;
  557. return {
  558. activeWorkspaceIdentity: state?.activeWorkspaceIdentity ?? null,
  559. activeWorkspacePath: state?.activeWorkspacePath ?? null,
  560. remoteHost: typeof remoteTarget?.host === "string" ? remoteTarget.host : null,
  561. remoteKind: typeof remoteTarget?.kind === "string" ? remoteTarget.kind : null,
  562. remoteSessionId: matchingRemoteTab?.remoteSessionId ?? null,
  563. secretPersistedInTab: Boolean(
  564. remoteTarget && ("password" in remoteTarget || "privateKeyPassphrase" in remoteTarget),
  565. ),
  566. workspaceIdentity: matchingRemoteTab?.workspaceIdentity ?? null,
  567. workspacePath: matchingRemoteTab?.workspacePath ?? null,
  568. };
  569. },
  570. expectedIdentity ?? null,
  571. expectedPath ?? null,
  572. );
  573. }