conversation-session-r3-mixed-entries.test.ts 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. import { reloadElectronSessionPreservingBrowserProfile } from "#e2e/helpers/e2e-electron-reload";
  2. import { mkdir, writeFile } from "node:fs/promises";
  3. import { resolve } from "node:path";
  4. import { parseRemoteWorkspaceIdentity } from "@zcode/shared";
  5. import { clearAppData, DEFAULT_WORKSPACE, readSettings } from "#e2e/helpers/desktop-app";
  6. import {
  7. connectSSHWorkspaceAndSendFirstTurn,
  8. prepareSSHLifecycle,
  9. sendSSHFollowTurn,
  10. waitForRendererAfterColdRestart,
  11. type SSHLifecycleProvider,
  12. } from "#e2e/helpers/ssh-remote-lifecycle";
  13. import {
  14. prepareSSHConnectionPage,
  15. openSSHSourceDirectory,
  16. readHostProcesses,
  17. readRemoteTabSnapshot,
  18. selectSSHRemoteDirectory,
  19. waitForRemoteTab,
  20. waitForSSHDirectoryStep,
  21. } from "#e2e/helpers/ssh-remote-p0";
  22. import {
  23. openWorkspaceDraftFromSidebar,
  24. selectTaskOrganizeMode,
  25. } from "#e2e/helpers/workspace-agent-warmup";
  26. const CASE_MARKER = "E2E_R3_MIXED_ENTRIES";
  27. const artifactDir = resolve(
  28. process.env.ZCODE_E2E_ARTIFACT_DIR ?? ".e2e-artifacts/r3-mixed-entries",
  29. );
  30. interface TabRow {
  31. id: string;
  32. workspacePath: string | null;
  33. workspaceIdentity: string | null;
  34. remoteSessionId: string | null;
  35. }
  36. function readTabs(): Promise<{ active: string | null; tabs: TabRow[] }> {
  37. return browser.execute(() => {
  38. const store = (
  39. window as Window & {
  40. __zcodeTabStoreE2E?: {
  41. getState?: () => {
  42. activeWorkspaceIdentity?: string | null;
  43. activeWorkspacePath?: string | null;
  44. tabs?: Array<{
  45. id: string;
  46. workspacePath?: string;
  47. workspaceIdentity?: string;
  48. remoteSessionId?: string;
  49. }>;
  50. };
  51. };
  52. }
  53. ).__zcodeTabStoreE2E;
  54. const state = store?.getState?.();
  55. return {
  56. active: state?.activeWorkspaceIdentity ?? state?.activeWorkspacePath ?? null,
  57. tabs: (state?.tabs ?? []).map((tab) => ({
  58. id: tab.id,
  59. workspacePath: tab.workspacePath ?? null,
  60. workspaceIdentity: tab.workspaceIdentity ?? null,
  61. remoteSessionId: tab.remoteSessionId ?? null,
  62. })),
  63. };
  64. });
  65. }
  66. describe(`${CASE_MARKER}: 本地与远端项目入口保留,冷启动只恢复活动目录`, () => {
  67. let provider: SSHLifecycleProvider | null = null;
  68. const facts: Record<string, unknown> = {};
  69. after(async () => {
  70. await mkdir(artifactDir, { recursive: true });
  71. await writeFile(resolve(artifactDir, "mixed-entries.json"), JSON.stringify(facts, null, 2));
  72. await provider?.tunnel.close().catch(() => undefined);
  73. provider = null;
  74. await browser.electron.restoreAllMocks();
  75. await clearAppData();
  76. });
  77. it("R3A-ID-08/REC-10 冷启动恢复原远端焦点,保留项目入口;其他项目按需打开且原任务可续发", async function () {
  78. this.timeout(30 * 60_000);
  79. await prepareSSHConnectionPage(CASE_MARKER);
  80. const prepared = await prepareSSHLifecycle(CASE_MARKER, { tunnelUsername: "tunnel" });
  81. provider = prepared.provider;
  82. const [workspaceA, workspaceB] = prepared.config.workspacePaths;
  83. const taskA = await connectSSHWorkspaceAndSendFirstTurn({
  84. caseMarker: CASE_MARKER,
  85. config: prepared.config,
  86. label: "A",
  87. provider,
  88. workspacePath: workspaceA,
  89. });
  90. const sourceId = parseRemoteWorkspaceIdentity(taskA.identity)?.sourceServerId ?? "";
  91. // 远端项目 A/B 与本地 workspace 混合恢复;旧 conversation 不属于 open set。
  92. await openSSHSourceDirectory(prepared.config, CASE_MARKER);
  93. await waitForSSHDirectoryStep(CASE_MARKER);
  94. await selectSSHRemoteDirectory(workspaceB, CASE_MARKER);
  95. const tabB = await waitForRemoteTab({
  96. caseMarker: CASE_MARKER,
  97. expectedPath: workspaceB,
  98. timeoutMs: 120_000,
  99. });
  100. await openWorkspaceDraftFromSidebar(DEFAULT_WORKSPACE);
  101. // 让 active 回到远端 project a,再冷启动。
  102. await openWorkspaceDraftFromSidebar(workspaceA);
  103. const before = await readTabs();
  104. expect(before.active).toBe(taskA.identity);
  105. await browser.waitUntil(
  106. async () => {
  107. const settings = await readSettings();
  108. return (
  109. settings.lastActiveWorkspace?.kind === "remote" &&
  110. settings.lastActiveWorkspace.workspacePath === workspaceA
  111. );
  112. },
  113. { timeout: 15_000, timeoutMsg: `${CASE_MARKER}: 冷启动前远端 active 尚未持久化` },
  114. );
  115. const settingsBefore = (await readSettings()).lastWorkspaceSession ?? [];
  116. facts.before = {
  117. tabs: before.tabs.map((t) => ({
  118. path: t.workspacePath,
  119. identity: t.workspaceIdentity,
  120. online: Boolean(t.remoteSessionId),
  121. })),
  122. active: before.active,
  123. entries: settingsBefore.map((e) => ({ kind: e.kind, path: e.workspacePath })),
  124. };
  125. // Project entry 是持久成员;导航缓存里无会话的临时未分类目录不属于恢复合同。
  126. const readProjectEntries = () =>
  127. browser.execute(() =>
  128. [...document.querySelectorAll("[data-project-id]")]
  129. .map(
  130. (row) =>
  131. `${row.getAttribute("data-project-host")}::${row.getAttribute("data-project-id")}`,
  132. )
  133. .sort(),
  134. );
  135. const projectEntriesBefore = await readProjectEntries();
  136. expect(projectEntriesBefore.length).toBeGreaterThanOrEqual(3);
  137. const expectedRemoteIdentities = [taskA.identity, tabB.workspaceIdentity!];
  138. await reloadElectronSessionPreservingBrowserProfile(browser);
  139. await waitForRendererAfterColdRestart(CASE_MARKER);
  140. // active-first:记录 tab store 首次非空快照(哪些 entry 先出现、哪些先在线),随后等待远端全部补齐。
  141. let early = await readTabs();
  142. await browser.waitUntil(
  143. async () => {
  144. early = await readTabs();
  145. return early.tabs.length > 0;
  146. },
  147. { timeout: 60_000, interval: 200, timeoutMsg: `${CASE_MARKER}: 冷启动后 tab store 一直为空` },
  148. );
  149. facts.earlyAfterCold = {
  150. tabs: early.tabs.map((t) => ({
  151. path: t.workspacePath,
  152. identity: t.workspaceIdentity,
  153. online: Boolean(t.remoteSessionId),
  154. })),
  155. active: early.active,
  156. };
  157. const restoreStarted = Date.now();
  158. const timeline: Array<{ t: number; online: string[] }> = [];
  159. // 失败也保存实际观察序列;waitUntil 创建 options 时插值只会留下初始空数组。
  160. facts.restoreTimeline = timeline;
  161. await browser
  162. .waitUntil(
  163. async () => {
  164. const now = await readTabs();
  165. const online = now.tabs
  166. .filter((t) => t.remoteSessionId)
  167. .map((t) => t.workspacePath ?? "");
  168. if (timeline.length === 0 || timeline.at(-1)!.online.join("|") !== online.join("|"))
  169. timeline.push({ t: Date.now() - restoreStarted, online });
  170. // F5:新版自动恢复活动执行目录,旧 A/B 列表只是 Host 派生的兼容投影。
  171. return now.tabs.some(
  172. (tab) => tab.workspaceIdentity === taskA.identity && tab.remoteSessionId,
  173. );
  174. },
  175. {
  176. timeout: 240_000,
  177. interval: 1000,
  178. timeoutMsg: `${CASE_MARKER}: 冷启动后活动项目没有恢复`,
  179. },
  180. )
  181. .catch(async (cause: unknown) => {
  182. facts.restoreFailure = await readTabs();
  183. throw new Error(`${CASE_MARKER}: 冷启动后活动项目没有恢复: ${JSON.stringify(timeline)}`, {
  184. cause,
  185. });
  186. });
  187. const after = await readTabs();
  188. // RDUX-09:启动激活页签由持久化导航决定;后台补齐不得改写原远端焦点。
  189. expect(early.active).toBe(taskA.identity);
  190. expect(after.active).toBe(taskA.identity);
  191. const afterKeys = after.tabs
  192. .filter((t) => t.workspacePath)
  193. .map((t) => `${t.workspaceIdentity ?? "local"}::${t.workspacePath}`);
  194. facts.afterCold = {
  195. tabs: after.tabs.map((t) => ({
  196. path: t.workspacePath,
  197. identity: t.workspaceIdentity,
  198. online: Boolean(t.remoteSessionId),
  199. })),
  200. duplicates: afterKeys.length - new Set(afterKeys).size,
  201. active: after.active,
  202. };
  203. expect(new Set(afterKeys).size).toBe(afterKeys.length);
  204. expect(after.tabs.filter((tab) => tab.workspaceIdentity)).toHaveLength(1);
  205. const projectEntriesAfter = await readProjectEntries();
  206. expect(projectEntriesAfter).toEqual(projectEntriesBefore);
  207. facts.projectEntries = { before: projectEntriesBefore, after: projectEntriesAfter };
  208. const settingsAfter = (await readSettings()).lastWorkspaceSession ?? [];
  209. expect(settingsAfter.filter((e) => e.kind === "remote").length).toBe(
  210. settingsBefore.filter((e) => e.kind === "remote").length,
  211. );
  212. // 先证明冷启动不复活非活动 tab,再通过真实项目入口验证按需创建 attachment。
  213. expect((await readRemoteTabSnapshot(tabB.workspaceIdentity!)).remoteSessionId).toBeNull();
  214. await openWorkspaceDraftFromSidebar(workspaceB);
  215. await waitForRemoteTab({
  216. caseMarker: CASE_MARKER,
  217. expectedIdentity: tabB.workspaceIdentity!,
  218. expectedPath: workspaceB,
  219. });
  220. expect(expectedRemoteIdentities).toHaveLength(2);
  221. const snapA = await readRemoteTabSnapshot(taskA.identity);
  222. const snapB = await readRemoteTabSnapshot(tabB.workspaceIdentity!);
  223. facts.siblings = {
  224. a: snapA.remoteSessionId,
  225. b: snapB.remoteSessionId,
  226. sameSource:
  227. parseRemoteWorkspaceIdentity(tabB.workspaceIdentity!)?.sourceServerId === sourceId,
  228. };
  229. expect(snapA.remoteSessionId).toBeTruthy();
  230. expect(snapB.remoteSessionId).toBeTruthy();
  231. expect(snapA.remoteSessionId).not.toBe(snapB.remoteSessionId);
  232. expect(parseRemoteWorkspaceIdentity(tabB.workspaceIdentity!)?.sourceServerId).toBe(sourceId);
  233. // 仅恢复 tab/session 外观不能证明任务可继续;独立回复标记防止把旧回合当作续发完成。
  234. await sendSSHFollowTurn(
  235. {
  236. ...taskA,
  237. remoteSessionId: snapA.remoteSessionId!,
  238. followReply: "R3_MIXED_ENTRIES_FOLLOW_REPLY",
  239. },
  240. CASE_MARKER,
  241. );
  242. facts.followTurnVerified = true;
  243. await selectTaskOrganizeMode(["项目", "Project"]);
  244. expect((await readHostProcesses()).length).toBe(1);
  245. });
  246. });