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

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