conversation-session-rpn-same-path-local-task.test.ts 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235
  1. import { mkdir, writeFile } from "node:fs/promises";
  2. import { resolve } from "node:path";
  3. import { TID_WORKSPACE_PATH } from "@zcode/shared/test-ids";
  4. import { clearAppData, DEFAULT_WORKSPACE } from "#e2e/helpers/desktop-app";
  5. import {
  6. getUpstreamRequestRecordCount,
  7. waitForUpstreamRequest,
  8. } from "#e2e/helpers/conversation-session-network";
  9. import {
  10. connectSSHWorkspaceAndSendFirstTurn,
  11. prepareSSHLifecycle,
  12. SSH_LIFECYCLE_MODEL_ID,
  13. type SSHLifecycleProvider,
  14. } from "#e2e/helpers/ssh-remote-lifecycle";
  15. import {
  16. prepareSSHConnectionPage,
  17. readRemoteTabSnapshot,
  18. runSSHCommand,
  19. type SSHConnectionConfig,
  20. } from "#e2e/helpers/ssh-remote-p0";
  21. import {
  22. selectUpstreamProviderModelById,
  23. selectUpstreamThoughtLevelValue,
  24. } from "#e2e/helpers/upstream-provider";
  25. import {
  26. selectV4TaskById,
  27. sendV4PromptAndWaitAccepted,
  28. waitForV4AssistantMessageContaining,
  29. waitForV4ConversationState,
  30. } from "#e2e/helpers/v4-conversation";
  31. import { openWorkspaceDraftFromSidebar } from "#e2e/helpers/workspace-agent-warmup";
  32. const CASE_MARKER = "E2E_RPN_SAME_PATH_LOCAL_TASK";
  33. const REPLY = "RPN_SAME_PATH_LOCAL_TASK_REPLY";
  34. const artifactDir = resolve(
  35. process.env.ZCODE_E2E_ARTIFACT_DIR ?? ".e2e-artifacts/rpn-same-path-local-task",
  36. );
  37. interface TabRow {
  38. id: string;
  39. workspacePath: string | null;
  40. workspaceIdentity: string | null;
  41. remoteSessionId: string | null;
  42. }
  43. function readTabs(): Promise<{
  44. activeWorkspacePath: string | null;
  45. activeWorkspaceIdentity: string | null;
  46. tabs: TabRow[];
  47. }> {
  48. return browser.execute(() => {
  49. const state = (
  50. window as Window & {
  51. __zcodeTabStoreE2E?: {
  52. getState(): {
  53. activeWorkspacePath: string | null;
  54. activeWorkspaceIdentity: string | null;
  55. tabs: Array<{
  56. id: string;
  57. kind: string;
  58. workspacePath?: string;
  59. workspaceIdentity?: string;
  60. remoteSessionId?: string;
  61. }>;
  62. };
  63. };
  64. }
  65. ).__zcodeTabStoreE2E?.getState();
  66. if (!state) throw new Error("导航 store 未就绪");
  67. return {
  68. activeWorkspacePath: state.activeWorkspacePath,
  69. activeWorkspaceIdentity: state.activeWorkspaceIdentity,
  70. tabs: state.tabs
  71. .filter((tab) => tab.kind === "workspace")
  72. .map((tab) => ({
  73. id: tab.id,
  74. workspacePath: tab.workspacePath ?? null,
  75. workspaceIdentity: tab.workspaceIdentity ?? null,
  76. remoteSessionId: tab.remoteSessionId ?? null,
  77. })),
  78. };
  79. });
  80. }
  81. /** Header 的工作区按钮:远程 workspace 才渲染设备名,本地只显示文件夹图标。 */
  82. function readHeaderWorkspace(): Promise<{ path: string | null; device: string | null }> {
  83. return browser.execute((testId) => {
  84. const button = document.querySelector(`[data-testid="${testId}"]`);
  85. return {
  86. path: button?.getAttribute("data-workspace-abs-path") ?? null,
  87. device: button?.querySelector("[data-workspace-device-name]")?.textContent ?? null,
  88. };
  89. }, TID_WORKSPACE_PATH);
  90. }
  91. async function sendLocalTurn(marker: string): Promise<string> {
  92. const start = await getUpstreamRequestRecordCount();
  93. await sendV4PromptAndWaitAccepted(
  94. `${marker} 只回复 ${REPLY}`,
  95. marker,
  96. `${CASE_MARKER}: ${marker} 未被接受`,
  97. );
  98. const running = await waitForV4ConversationState(
  99. (s) => Boolean(s.taskId && s.taskId !== "draft"),
  100. `${CASE_MARKER}: ${marker} 没有产生 task`,
  101. 60_000,
  102. );
  103. await waitForUpstreamRequest(
  104. { lastUserMessageIncludes: [marker] },
  105. `${CASE_MARKER}: ${marker} 没有到达回放`,
  106. 90_000,
  107. { afterIndex: start - 1 },
  108. );
  109. await waitForV4AssistantMessageContaining(REPLY, 90_000);
  110. await waitForV4ConversationState(
  111. (s) => s.taskId === running.taskId && s.state === "idle",
  112. `${CASE_MARKER}: ${marker} 没有收口`,
  113. 90_000,
  114. );
  115. return running.taskId!;
  116. }
  117. /** 远端建出与本机 E2E 项目相同的绝对路径;非 root 账号经免密 sudo 创建后交还所有权。 */
  118. async function createRemoteSamePath(config: SSHConnectionConfig, path: string): Promise<boolean> {
  119. const quoted = `'${path.replaceAll("'", "'\\''")}'`;
  120. const existed = await runSSHCommand(config, `test -e ${quoted}`);
  121. if (existed.code === 0) return false;
  122. const created = await runSSHCommand(
  123. config,
  124. `mkdir -p -- ${quoted} 2>/dev/null || { sudo -n mkdir -p -- ${quoted} && sudo -n chown "$(id -u):$(id -g)" -- ${quoted}; }`,
  125. );
  126. expect(created.code).toBe(0);
  127. return true;
  128. }
  129. describe(`${CASE_MARKER}: 本地与远程项目同路径时点击本地任务`, () => {
  130. let provider: SSHLifecycleProvider | null = null;
  131. let remoteCleanup: (() => Promise<unknown>) | null = null;
  132. const facts: Record<string, unknown> = {};
  133. after(async () => {
  134. await mkdir(artifactDir, { recursive: true });
  135. facts.final = await readTabs().catch((error: unknown) => String(error));
  136. await writeFile(
  137. resolve(artifactDir, "same-path-local-task.json"),
  138. JSON.stringify(facts, null, 2),
  139. );
  140. await browser.saveScreenshot(resolve(artifactDir, "same-path-local-task.png"));
  141. await remoteCleanup?.().catch(() => undefined);
  142. await provider?.tunnel.close().catch(() => undefined);
  143. provider = null;
  144. await browser.electron.restoreAllMocks();
  145. await clearAppData();
  146. });
  147. it("RPN-25 远程同路径 tab 在前时,点击本地任务打开本地任务,远程任务不受影响", async function () {
  148. this.timeout(20 * 60_000);
  149. await prepareSSHConnectionPage(CASE_MARKER);
  150. // 本地任务也要走同一个 replay provider;镜像端口让本机直接命中 baseURL。
  151. const prepared = await prepareSSHLifecycle(CASE_MARKER, {
  152. tunnelUsername: "tunnel",
  153. mirrorLocalPort: true,
  154. });
  155. provider = prepared.provider;
  156. // ① 本地项目先产生一个任务。
  157. await openWorkspaceDraftFromSidebar(DEFAULT_WORKSPACE);
  158. await selectUpstreamProviderModelById(SSH_LIFECYCLE_MODEL_ID, {
  159. includePlainModelFallback: false,
  160. providerId: provider.id,
  161. providerName: provider.name,
  162. });
  163. await selectUpstreamThoughtLevelValue("disabled");
  164. const localTaskId = await sendLocalTurn(`${CASE_MARKER}_LOCAL`);
  165. expect((await readTabs()).activeWorkspaceIdentity).toBeNull();
  166. // ② 远端打开同一绝对路径的项目并产生任务;新 tab 排在本地 tab 前面。
  167. if (await createRemoteSamePath(prepared.config, DEFAULT_WORKSPACE)) {
  168. const quoted = `'${DEFAULT_WORKSPACE.replaceAll("'", "'\\''")}'`;
  169. remoteCleanup = () =>
  170. runSSHCommand(
  171. prepared.config,
  172. `rm -rf -- ${quoted} 2>/dev/null || sudo -n rm -rf -- ${quoted}`,
  173. );
  174. }
  175. const remoteTask = await connectSSHWorkspaceAndSendFirstTurn({
  176. caseMarker: CASE_MARKER,
  177. config: prepared.config,
  178. label: "A",
  179. provider,
  180. workspacePath: DEFAULT_WORKSPACE,
  181. });
  182. const before = await readTabs();
  183. facts.before = { localTaskId, remoteTask, tabs: before };
  184. const localIndex = before.tabs.findIndex(
  185. (tab) => tab.workspacePath === DEFAULT_WORKSPACE && !tab.workspaceIdentity,
  186. );
  187. const remoteIndex = before.tabs.findIndex(
  188. (tab) => tab.workspaceIdentity === remoteTask.identity,
  189. );
  190. // 前置条件:同路径远程 tab 排在本地 tab 之前,只按路径匹配就会先命中远程 tab。
  191. expect(localIndex).toBeGreaterThanOrEqual(0);
  192. expect(remoteIndex).toBeGreaterThanOrEqual(0);
  193. expect(remoteIndex).toBeLessThan(localIndex);
  194. expect(before.activeWorkspaceIdentity).toBe(remoteTask.identity);
  195. // ③ 点击本地任务:必须激活本地 tab 并打开本地任务。
  196. await selectV4TaskById(localTaskId, 30_000);
  197. const afterLocal = await readTabs();
  198. const headerLocal = await readHeaderWorkspace();
  199. facts.afterLocal = { ...afterLocal, header: headerLocal };
  200. expect(afterLocal.activeWorkspacePath).toBe(DEFAULT_WORKSPACE);
  201. expect(afterLocal.activeWorkspaceIdentity).toBeNull();
  202. // Header 也要按本地 tab 展示,不能沿用同路径远程 tab 的设备标记。
  203. expect(headerLocal).toEqual({ path: DEFAULT_WORKSPACE, device: null });
  204. const remoteAfterLocal = await readRemoteTabSnapshot(remoteTask.identity, DEFAULT_WORKSPACE);
  205. expect(remoteAfterLocal.remoteSessionId).toBe(remoteTask.remoteSessionId);
  206. // ④ 来回切换:远程任务仍打开远程 tab,再回到本地任务仍正确。
  207. await selectV4TaskById(remoteTask.taskId, 30_000);
  208. const afterRemote = await readTabs();
  209. const headerRemote = await readHeaderWorkspace();
  210. facts.afterRemote = { ...afterRemote, header: headerRemote };
  211. expect(afterRemote.activeWorkspaceIdentity).toBe(remoteTask.identity);
  212. expect(headerRemote.path).toBe(DEFAULT_WORKSPACE);
  213. expect(headerRemote.device).toBeTruthy();
  214. await selectV4TaskById(localTaskId, 30_000);
  215. const afterLocalAgain = await readTabs();
  216. const headerLocalAgain = await readHeaderWorkspace();
  217. facts.afterLocalAgain = { ...afterLocalAgain, header: headerLocalAgain };
  218. expect(afterLocalAgain.activeWorkspacePath).toBe(DEFAULT_WORKSPACE);
  219. expect(afterLocalAgain.activeWorkspaceIdentity).toBeNull();
  220. expect(headerLocalAgain).toEqual({ path: DEFAULT_WORKSPACE, device: null });
  221. });
  222. });