conversation-session-ssh-remote-new-project-sidebar.test.ts 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451
  1. import { join } from "node:path";
  2. import { writeFile } from "node:fs/promises";
  3. import { ServiceChannels } from "@zcode/shared";
  4. import { TID_TASK_ITEM, testId } from "@zcode/shared/test-ids";
  5. import type { WindowHostControllerTaskListResult } from "@zcode/services";
  6. import { releaseControlledReplay } from "#e2e/helpers/controlled-replay";
  7. import {
  8. holdProjectUnread,
  9. releaseProjectUnread,
  10. restoreProjectUnreadProbe,
  11. } from "#e2e/helpers/project-unread-probe";
  12. import {
  13. callHandoffHost,
  14. installHandoffRpcProbe,
  15. restoreHandoffProbes,
  16. } from "#e2e/helpers/remote-project-handoff-probe";
  17. import { clearAppData } from "#e2e/helpers/desktop-app";
  18. import { waitForUpstreamRequest } from "#e2e/helpers/conversation-session-network";
  19. import {
  20. ensureProjectExpanded,
  21. projectSectionSelector,
  22. selectRemoteProjectDirectory,
  23. startDraftFromProject,
  24. } from "#e2e/helpers/project-sidebar";
  25. import {
  26. prepareSSHLifecycle,
  27. SSH_LIFECYCLE_MODEL_ID,
  28. SSH_LIFECYCLE_THOUGHT_LEVEL,
  29. type SSHLifecycleProvider,
  30. } from "#e2e/helpers/ssh-remote-lifecycle";
  31. import {
  32. connectSSHWorkspace,
  33. readRemoteTabSnapshot,
  34. runSSHCommand,
  35. waitForRemoteTab,
  36. } from "#e2e/helpers/ssh-remote-p0";
  37. import {
  38. selectUpstreamProviderModelById,
  39. selectUpstreamThoughtLevelValue,
  40. } from "#e2e/helpers/upstream-provider";
  41. import {
  42. approveV4Permission,
  43. sendV4PromptAndWaitAccepted,
  44. selectV4TaskById,
  45. startNewV4Draft,
  46. switchV4Mode,
  47. waitForV4ConversationState,
  48. waitForV4PermissionDialog,
  49. waitForV4TimelineContaining,
  50. } from "#e2e/helpers/v4-conversation";
  51. const CASE_MARKER = "E2E_SSH_NEW_PROJECT_SIDEBAR";
  52. const EXISTING_PROMPT = "E2E_SSH_NEW_PROJECT_SIDEBAR_EXISTING";
  53. const EXISTING_REPLY = "SSH_NEW_PROJECT_EXISTING_DONE";
  54. const PROMPT = "E2E_SSH_NEW_PROJECT_SIDEBAR_WRITE";
  55. const REPLY = "SSH_NEW_PROJECT_SIDEBAR_DONE";
  56. const FOREGROUND_PROMPT = "E2E_SSH_NEW_PROJECT_SIDEBAR_FOREGROUND";
  57. const FOREGROUND_REPLY = "SSH_NEW_PROJECT_FOREGROUND_DONE";
  58. const SIBLING_PROMPT = "E2E_SSH_NEW_PROJECT_SIDEBAR_SIBLING";
  59. const SIBLING_REPLY = "SSH_NEW_PROJECT_SIBLING_DONE";
  60. const NAVIGATION_PROMPT = "E2E_SSH_NEW_PROJECT_SIDEBAR_NAVIGATION";
  61. const NAVIGATION_REPLY = "SSH_NEW_PROJECT_NAVIGATION_DONE";
  62. const OUTPUT_PATH = ".zcode-e2e/ssh-new-project-sidebar/output.txt";
  63. interface SidebarState {
  64. exists: boolean;
  65. running: boolean;
  66. waiting: boolean;
  67. unread: boolean;
  68. }
  69. async function waitForSidebarState(taskId: string, expected: Omit<SidebarState, "exists">) {
  70. let latest: SidebarState | null = null;
  71. try {
  72. await browser.waitUntil(
  73. async () => {
  74. latest = await browser.execute(
  75. (taskTestId) => {
  76. const row = document.querySelector(`[data-testid="${taskTestId}"]`);
  77. return {
  78. exists: Boolean(row),
  79. running: Boolean(row?.querySelector(".animate-spin")),
  80. waiting: Boolean(
  81. row?.querySelector('[data-task-interaction-badge="permission"]') ||
  82. Array.from(row?.querySelectorAll('[data-slot="badge"]') ?? []).some((badge) =>
  83. /^(等待确认|Awaiting approval)$/.test(badge.textContent?.trim() ?? ""),
  84. ),
  85. ),
  86. unread: Boolean(row?.querySelector('[data-unread-indicator="true"]')),
  87. };
  88. },
  89. testId(TID_TASK_ITEM, taskId),
  90. );
  91. return (
  92. latest.exists &&
  93. latest.running === expected.running &&
  94. latest.waiting === expected.waiting &&
  95. latest.unread === expected.unread
  96. );
  97. },
  98. { timeout: 30_000, interval: 100 },
  99. );
  100. } catch (cause) {
  101. const navigation = await browser.execute(() => {
  102. const target = window as Window & {
  103. __zcodeTabStoreE2E?: {
  104. getState(): {
  105. activeTabId?: string;
  106. activeWorkspaceIdentity?: string;
  107. activeWorkspacePath?: string;
  108. tabs?: Array<{
  109. id: string;
  110. workspaceIdentity?: string;
  111. workspacePath?: string;
  112. remoteSessionId?: string;
  113. }>;
  114. };
  115. };
  116. __zcodeSessionStoreE2E?: {
  117. getState(): {
  118. workspaces?: Record<string, { activeTaskId?: string }>;
  119. taskNavHistory?: unknown;
  120. };
  121. };
  122. };
  123. const tabs = target.__zcodeTabStoreE2E?.getState();
  124. const state = target.__zcodeSessionStoreE2E?.getState();
  125. const tab = tabs?.tabs?.find((item) => item.id === tabs.activeTabId);
  126. return {
  127. activeTab: tab
  128. ? {
  129. id: tab.id,
  130. workspaceIdentity: tab.workspaceIdentity,
  131. workspacePath: tab.workspacePath,
  132. remoteSessionId: tab.remoteSessionId,
  133. }
  134. : null,
  135. activeWorkspaceIdentity: tabs?.activeWorkspaceIdentity,
  136. activeWorkspacePath: tabs?.activeWorkspacePath,
  137. activeTasks: Object.entries(state?.workspaces ?? {}).map(([workspaceKey, item]) => ({
  138. workspaceKey,
  139. taskId: item.activeTaskId,
  140. })),
  141. taskNavHistory: state?.taskNavHistory,
  142. };
  143. });
  144. if (process.env.ZCODE_E2E_ARTIFACT_DIR) {
  145. await writeFile(
  146. join(process.env.ZCODE_E2E_ARTIFACT_DIR, "sidebar-failure-state.json"),
  147. JSON.stringify({ taskId, expected, latest, navigation }, null, 2),
  148. );
  149. await saveStateScreenshot("sidebar-state-failure");
  150. }
  151. throw new Error(
  152. `${CASE_MARKER}: 侧栏状态未收敛 expected=${JSON.stringify(expected)} actual=${JSON.stringify(latest)}`,
  153. { cause },
  154. );
  155. }
  156. }
  157. describe(`${CASE_MARKER}: 新建远程项目首次任务的侧栏实时状态`, () => {
  158. let provider: SSHLifecycleProvider | null = null;
  159. after(async () => {
  160. await restoreProjectUnreadProbe();
  161. await restoreHandoffProbes();
  162. await provider?.tunnel.close().catch(() => undefined);
  163. await browser.electron.restoreAllMocks();
  164. await clearAppData();
  165. });
  166. it("SSH-P0-TASK-04 云图标、首发权限和后台未读无需重启,打开后清除未读", async function () {
  167. this.timeout(20 * 60_000);
  168. const prepared = await prepareSSHLifecycle(CASE_MARKER, { apiType: "anthropic-messages" });
  169. provider = prepared.provider;
  170. await installHandoffRpcProbe();
  171. const [existingPath, workspacePath] = prepared.config.workspacePaths;
  172. await connectSSHWorkspace({
  173. caseMarker: CASE_MARKER,
  174. config: prepared.config,
  175. workspacePath: existingPath,
  176. });
  177. // 新建项目会自动选中当前草稿;先完成 A 的真实会话,使 B 保持未打开,保留首次绑定边界。
  178. await selectUpstreamProviderModelById(SSH_LIFECYCLE_MODEL_ID, {
  179. includePlainModelFallback: false,
  180. providerId: provider.id,
  181. providerName: provider.name,
  182. });
  183. await selectUpstreamThoughtLevelValue(SSH_LIFECYCLE_THOUGHT_LEVEL);
  184. await sendV4PromptAndWaitAccepted(
  185. `${EXISTING_PROMPT}: 只回复 ${EXISTING_REPLY}`,
  186. EXISTING_PROMPT,
  187. "A 项目前置会话未接受",
  188. );
  189. await waitForV4TimelineContaining(EXISTING_REPLY, 60_000);
  190. await waitForV4ConversationState(
  191. (snapshot) =>
  192. Boolean(snapshot.taskId && snapshot.taskId !== "draft" && snapshot.state === "idle"),
  193. "A 项目前置会话未完成",
  194. 60_000,
  195. );
  196. const existingSection = $(projectSectionSelector(existingPath));
  197. const hostId = await existingSection.getAttribute("data-project-host");
  198. expect(hostId).toMatch(/^remote:server:/);
  199. await $('[data-testid="project-section"]').moveTo();
  200. await $('[data-testid="virtual-project-add"]').click();
  201. await $('[data-testid="virtual-project-name"]').waitForDisplayed();
  202. await $('[data-testid="virtual-project-device"]').click();
  203. await $(`[role="option"][data-device-id=${JSON.stringify(hostId)}]`).click();
  204. await selectRemoteProjectDirectory(workspacePath);
  205. await $('[data-testid="virtual-project-name"]').setValue(workspacePath.split("/").at(-1)!);
  206. await $('[data-testid="virtual-project-save"]').click();
  207. await $('[data-testid="project-folder-trust-confirm"]').waitForDisplayed();
  208. await $('[data-testid="project-folder-trust-confirm"]').click();
  209. await ensureProjectExpanded(workspacePath);
  210. // 原因:新空项目树曾只从已有任务生成 identity 映射。先创建第二个未打开的项目,
  211. // 等项目行发布及状态订阅,再首次绑定并发消息;预先打开 B 会掩盖绑定前的订阅错误。
  212. const section = $(projectSectionSelector(workspacePath));
  213. expect(await section.$$(`[data-testid^="${TID_TASK_ITEM}-"]`).length).toBe(0);
  214. expect((await readRemoteTabSnapshot(undefined, workspacePath)).remoteSessionId).toBeNull();
  215. await section.$('[data-remote-state-icon="cloud"]').waitForExist({ timeout: 15_000 });
  216. await startDraftFromProject(workspacePath);
  217. const tab = await waitForRemoteTab({ caseMarker: CASE_MARKER, expectedPath: workspacePath });
  218. expect(tab.remoteSessionId).toBeTruthy();
  219. if (!tab.workspaceIdentity) throw new Error("Missing remote workspace identity");
  220. expect(tab.remoteKind).toBe("ssh");
  221. await selectUpstreamProviderModelById(SSH_LIFECYCLE_MODEL_ID, {
  222. includePlainModelFallback: false,
  223. providerId: provider.id,
  224. providerName: provider.name,
  225. });
  226. await selectUpstreamThoughtLevelValue(SSH_LIFECYCLE_THOUGHT_LEVEL);
  227. await switchV4Mode("build");
  228. await sendV4PromptAndWaitAccepted(
  229. `${PROMPT}: 创建测试文件后回复 ${REPLY}`,
  230. PROMPT,
  231. "首发未接受",
  232. );
  233. const state = await waitForV4ConversationState(
  234. (snapshot) => Boolean(snapshot.taskId && snapshot.taskId !== "draft"),
  235. "首次远程任务未建立",
  236. 60_000,
  237. );
  238. if (!state.taskId) throw new Error("Missing remote task id");
  239. const taskId = state.taskId;
  240. await waitForV4PermissionDialog();
  241. await waitForSidebarState(taskId, { running: true, waiting: true, unread: false });
  242. await saveStateScreenshot("first-permission");
  243. expect(await approveV4Permission()).toBe(true);
  244. await waitForUpstreamRequest(
  245. { includes: [PROMPT, "toolu_ssh_new_project_write"] },
  246. "批准后未收到真实 tool_result",
  247. 60_000,
  248. );
  249. await waitForV4TimelineContaining(REPLY, 60_000);
  250. await waitForSidebarState(taskId, { running: true, waiting: false, unread: false });
  251. const file = await runSSHCommand(prepared.config, `cat '${workspacePath}/${OUTPUT_PATH}'`);
  252. expect(file.code).toBe(0);
  253. expect(file.stdout).toBe("SSH_NEW_PROJECT_FILE\n");
  254. // 由 fixture release 确定后台完成的顺序,不靠 sleep 猜测模型完成时间。
  255. await startNewV4Draft();
  256. await releaseControlledReplay("ssh-new-project-complete");
  257. await waitForSidebarState(taskId, { running: false, waiting: false, unread: true });
  258. await saveStateScreenshot("background-unread");
  259. await selectV4TaskById(taskId, 30_000);
  260. await waitForV4TimelineContaining(REPLY);
  261. await waitForSidebarState(taskId, { running: false, waiting: false, unread: false });
  262. const after = await readRemoteTabSnapshot(tab.workspaceIdentity, workspacePath);
  263. expect(after.workspaceIdentity).toBe(tab.workspaceIdentity);
  264. expect(after.remoteSessionId).toBe(tab.remoteSessionId);
  265. // 旧 Host 先等待列表读取再发完成信号,前台已查看的完成会在切走后被误判成后台未读。
  266. // 这里验证真实 SSH 用户闭环;读取暂挂期间的精确导航顺序由 Host/renderer 集成单测控制。
  267. await sendV4PromptAndWaitAccepted(
  268. `${FOREGROUND_PROMPT}: 只回复 ${FOREGROUND_REPLY}`,
  269. FOREGROUND_PROMPT,
  270. "前台续发未接受",
  271. );
  272. await waitForV4TimelineContaining(FOREGROUND_REPLY, 60_000);
  273. await releaseControlledReplay("ssh-new-project-foreground");
  274. await waitForV4ConversationState(
  275. (snapshot) => snapshot.taskId === taskId && snapshot.state === "idle",
  276. "前台续发未完成",
  277. 60_000,
  278. );
  279. await startNewV4Draft();
  280. // 核对真实 Controller 投影与 UI;缓存查询不保证等待全部 IO,精确在途时序由集成单测覆盖。
  281. const settled = await callHandoffHost<WindowHostControllerTaskListResult>(
  282. ServiceChannels.WindowController,
  283. "listTaskList",
  284. [
  285. {
  286. kind: "active",
  287. workspaceScopes: [{ workspacePath, workspaceIdentity: tab.workspaceIdentity }],
  288. sortBy: "updated",
  289. },
  290. ],
  291. );
  292. const completed = settled.items.find((item) => item.taskId === taskId);
  293. expect(completed).toBeDefined();
  294. expect(completed?.unreadAt).toBeUndefined();
  295. await waitForSidebarState(taskId, { running: false, waiting: false, unread: false });
  296. await saveStateScreenshot("foreground-completed-read");
  297. // T2 先就绪,再从 T1 切到 A。回到 B/T2 的 tab 中间态不能吞掉 T1 的后台完成。
  298. await startDraftFromProject(workspacePath);
  299. expect(
  300. (await readRemoteTabSnapshot(tab.workspaceIdentity, workspacePath)).activeWorkspaceIdentity,
  301. ).toBe(tab.workspaceIdentity);
  302. await sendV4PromptAndWaitAccepted(
  303. `${SIBLING_PROMPT}: 只回复 ${SIBLING_REPLY}`,
  304. SIBLING_PROMPT,
  305. "T2 未接受",
  306. );
  307. await waitForV4TimelineContaining(SIBLING_REPLY, 60_000);
  308. const sibling = await waitForV4ConversationState(
  309. (snapshot) =>
  310. Boolean(
  311. snapshot.taskId &&
  312. snapshot.taskId !== "draft" &&
  313. snapshot.taskId !== taskId &&
  314. snapshot.state === "idle",
  315. ),
  316. "T2 未完成",
  317. 60_000,
  318. );
  319. if (!sibling.taskId) throw new Error("Missing sibling task id");
  320. await selectV4TaskById(taskId);
  321. await sendV4PromptAndWaitAccepted(
  322. `${NAVIGATION_PROMPT}: 只回复 ${NAVIGATION_REPLY}`,
  323. NAVIGATION_PROMPT,
  324. "T1 续发未接受",
  325. );
  326. await waitForV4TimelineContaining(NAVIGATION_REPLY, 60_000);
  327. await startDraftFromProject(existingPath);
  328. expect(
  329. (await readRemoteTabSnapshot(tab.workspaceIdentity, workspacePath)).activeWorkspaceIdentity,
  330. ).not.toBe(tab.workspaceIdentity);
  331. const cachedTask = await browser.execute((identity) => {
  332. const target = window as Window & {
  333. __zcodeSessionStoreE2E?: {
  334. getState(): { workspaces: Record<string, { activeTaskId: string | null }> };
  335. };
  336. };
  337. return target.__zcodeSessionStoreE2E?.getState().workspaces[identity]?.activeTaskId;
  338. }, tab.workspaceIdentity);
  339. expect(cachedTask).toBe(taskId);
  340. await holdProjectUnread(taskId, tab.workspaceIdentity);
  341. await releaseControlledReplay("ssh-new-project-navigation");
  342. await browser.waitUntil(
  343. () => browser.execute(() => Boolean(window.__projectUnreadProbe?.held)),
  344. {
  345. timeout: 30_000,
  346. timeoutMsg: "T1 后台完成未触发未读命令",
  347. },
  348. );
  349. await selectV4TaskById(sibling.taskId);
  350. await waitForV4TimelineContaining(SIBLING_REPLY);
  351. await releaseProjectUnread();
  352. await waitForSidebarState(taskId, { running: false, waiting: false, unread: true });
  353. const unread = await callHandoffHost<WindowHostControllerTaskListResult>(
  354. ServiceChannels.WindowController,
  355. "listTaskList",
  356. [
  357. {
  358. kind: "active",
  359. workspaceScopes: [{ workspacePath, workspaceIdentity: tab.workspaceIdentity }],
  360. sortBy: "updated",
  361. },
  362. ],
  363. );
  364. expect(unread.items.find((item) => item.taskId === taskId)?.unreadAt).toEqual(
  365. expect.any(Number),
  366. );
  367. await saveStateScreenshot("cross-workspace-sibling-keeps-unread");
  368. await restoreProjectUnreadProbe();
  369. await selectV4TaskById(taskId);
  370. await waitForSidebarState(taskId, { running: false, waiting: false, unread: false });
  371. await captureRemoteProjectThemes();
  372. });
  373. });
  374. async function saveStateScreenshot(name: string) {
  375. if (process.env.ZCODE_E2E_ARTIFACT_DIR)
  376. await browser.saveScreenshot(join(process.env.ZCODE_E2E_ARTIFACT_DIR, `${name}.png`));
  377. }
  378. /** 390px 是桌面 renderer 窄屏视觉证据,不冒充手机 replayable 路径。 */
  379. async function captureRemoteProjectThemes() {
  380. const emulate = (width?: number) =>
  381. browser.electron.execute(async (electron, width) => {
  382. const window = electron.BrowserWindow.getAllWindows().find(
  383. (item) => !item.isDestroyed() && item.isVisible(),
  384. );
  385. if (!window) throw new Error("Missing renderer window");
  386. if (!window.webContents.debugger.isAttached()) window.webContents.debugger.attach("1.3");
  387. await window.webContents.debugger.sendCommand(
  388. width ? "Emulation.setDeviceMetricsOverride" : "Emulation.clearDeviceMetricsOverride",
  389. width ? { width, height: 844, deviceScaleFactor: 1, mobile: false } : {},
  390. );
  391. }, width);
  392. const setTheme = (theme: string) =>
  393. browser.execute((theme) => {
  394. const actions = (window as Window & { __testActions?: { setTheme(theme: string): void } })
  395. .__testActions;
  396. if (!actions) throw new Error("Missing theme actions");
  397. actions.setTheme(theme);
  398. }, theme);
  399. try {
  400. for (const width of [1200, 390]) {
  401. await emulate(width);
  402. await browser.waitUntil(() => browser.execute((width) => innerWidth === width, width));
  403. await browser.executeAsync((done) =>
  404. requestAnimationFrame(() => requestAnimationFrame(() => done())),
  405. );
  406. const sidebarVisible = await browser.execute(() => {
  407. const sidebar = document.querySelector('[data-testid="sidebar"]');
  408. const rect = sidebar?.getBoundingClientRect();
  409. return Boolean(
  410. rect &&
  411. rect.right > 0 &&
  412. rect.left < innerWidth &&
  413. rect.width > 0 &&
  414. sidebar?.closest("aside")?.getAttribute("aria-hidden") !== "true",
  415. );
  416. });
  417. if (!sidebarVisible) {
  418. await $('button[aria-label="Toggle sidebar"],button[aria-label="切换侧边栏"]').click();
  419. }
  420. await browser.waitUntil(
  421. () =>
  422. browser.execute(() => {
  423. const rect = document
  424. .querySelector('[data-testid="project-section"]')
  425. ?.getBoundingClientRect();
  426. return Boolean(
  427. rect &&
  428. rect.left >= 0 &&
  429. rect.right <= innerWidth &&
  430. document.querySelector("aside")?.getAttribute("aria-hidden") === "false",
  431. );
  432. }),
  433. { timeout: 10_000, timeoutMsg: "窄屏侧栏未显示,不能保存无目标视觉证据" },
  434. );
  435. for (const theme of ["zai-light", "zai-dark"]) {
  436. await setTheme(theme);
  437. await browser.waitUntil(() =>
  438. browser.execute(
  439. (theme) => document.documentElement.classList.contains(`theme-${theme}`),
  440. theme,
  441. ),
  442. );
  443. await saveStateScreenshot(`remote-cloud-${width}-${theme}`);
  444. }
  445. }
  446. } finally {
  447. await emulate();
  448. await setTheme("zai-light");
  449. }
  450. }