conversation-session-workspace-readonly-notice.test.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. import { DatabaseSync } from "node:sqlite";
  2. import { mkdir, rename, stat, writeFile } from "node:fs/promises";
  3. import { join } from "node:path";
  4. import { TID_V4_COMPOSER_INPUT, TID_V4_COMPOSER_SEND } from "@zcode/shared/test-ids";
  5. import { DEFAULT_WORKSPACE, waitForWorkspaceApp } from "#e2e/helpers/desktop-app";
  6. import { reloadElectronSessionPreservingBrowserProfile } from "#e2e/helpers/e2e-electron-reload";
  7. import { selectNativeProjectDirectories } from "#e2e/helpers/project-sidebar";
  8. import { prepareV4ConversationE2E } from "#e2e/helpers/v4-conversation";
  9. const PROJECT = '[data-project-name="E2E_READONLY_NOTICE"]';
  10. const HISTORY_ID = "sess_e2e_readonly_notice_history";
  11. const HISTORY_BODY = "E2E_READONLY_NOTICE_HISTORY_BODY";
  12. const NOTICE = '[data-testid="v4-workspace-readonly-notice"]';
  13. const COPY = {
  14. "zh-CN":
  15. "工作区目录不存在或无法访问,当前仅可查看历史记录。恢复该目录后重启 ZCode 即可继续使用。",
  16. "en-US":
  17. "The workspace directory does not exist or cannot be accessed. You can only view history for now. Restore the directory and restart ZCode to continue.",
  18. };
  19. type TestWindow = Window & {
  20. __testActions?: { setLocale(locale: string): void; setTheme(theme: string): void };
  21. };
  22. describe("VP-ROOT-02:目录失效时的会话输入区提示", () => {
  23. it("冷启动只读历史在原输入区说明原因,目录恢复并重启后恢复输入", async function () {
  24. this.timeout(240_000);
  25. const artifact = process.env.ZCODE_E2E_ARTIFACT_DIR!;
  26. const root = join(DEFAULT_WORKSPACE, ".zcode-e2e", "readonly-notice");
  27. const primary = join(root, "primary");
  28. const moved = join(root, "moved");
  29. await prepareV4ConversationE2E({ skipProvider: true });
  30. await browser.execute(() => (window as TestWindow).__testActions!.setLocale("zh-CN"));
  31. await mkdir(primary, { recursive: true });
  32. await $('[data-testid="project-section"]').moveTo();
  33. await $('[data-testid="virtual-project-add"]').click();
  34. await $('[data-testid="virtual-project-name"]').setValue("E2E_READONLY_NOTICE");
  35. await selectNativeProjectDirectories([primary]);
  36. await $('[data-testid="virtual-project-save"]').click();
  37. await $('[data-testid="project-folder-trust-confirm"]').waitForDisplayed();
  38. await $('[data-testid="project-folder-trust-confirm"]').click();
  39. await $(PROJECT).waitForDisplayed();
  40. await $(PROJECT).$('[data-testid="virtual-project-create-task"]').click();
  41. await waitForWorkspaceApp(primary, 30_000);
  42. // 两库夹具只在旧 Main/Host/Agent 完整退出后写入,再经 UI 打开真实持久历史。
  43. await reloadElectronSessionPreservingBrowserProfile(browser, {
  44. afterElectronProcessExit: () => seedHistory(primary),
  45. });
  46. await openHistory();
  47. await $(`[data-testid="${TID_V4_COMPOSER_INPUT}"]`).waitForDisplayed({ timeout: 30_000 });
  48. expect(await $(NOTICE).isExisting()).toBe(false);
  49. await browser.saveScreenshot(join(artifact, "readonly-notice-before.png"));
  50. await reloadElectronSessionPreservingBrowserProfile(browser, {
  51. afterElectronProcessExit: () => rename(primary, moved),
  52. });
  53. await $(PROJECT).waitForDisplayed({ timeout: 45_000 });
  54. // 启动仍进入可输入的无项目草稿,目录提示只属于用户随后打开的旧会话。
  55. await $(`[data-testid="${TID_V4_COMPOSER_INPUT}"]`).waitForDisplayed({ timeout: 30_000 });
  56. expect(await $(NOTICE).isExisting()).toBe(false);
  57. await openHistory();
  58. await browser.saveScreenshot(join(artifact, "readonly-notice-history-opened.png"));
  59. await $(NOTICE).waitForDisplayed({ timeout: 10_000 });
  60. expect(await $(NOTICE).getAttribute("role")).toBe("status");
  61. await expect(stat(primary)).rejects.toMatchObject({ code: "ENOENT" });
  62. const measurements: unknown[] = [];
  63. let sidebarCollapsed = false;
  64. try {
  65. for (const width of [1200, 390]) {
  66. if (width === 390) {
  67. // 先收起再缩窄,避免 resize 自动收起与 UI toggle 交错;不改桌面壳的最小宽度。
  68. if ((await $("#sidebar > aside").getAttribute("aria-hidden")) !== "true") {
  69. await $('button[aria-label="Toggle sidebar"]').click();
  70. }
  71. sidebarCollapsed = true;
  72. await browser.waitUntil(() =>
  73. browser.execute(() => {
  74. const panel = document.querySelector("#sidebar")!;
  75. return (
  76. panel.querySelector("aside")!.getAttribute("aria-hidden") === "true" &&
  77. panel.getAnimations().every((item) => item.playState !== "running")
  78. );
  79. }),
  80. );
  81. }
  82. await emulateViewport(width);
  83. for (const theme of ["zai-light", "zai-dark"]) {
  84. for (const locale of ["zh-CN", "en-US"] as const) {
  85. await browser.execute(
  86. ({ theme, locale }) => {
  87. (window as TestWindow).__testActions!.setTheme(theme);
  88. (window as TestWindow).__testActions!.setLocale(locale);
  89. },
  90. { theme, locale },
  91. );
  92. await expect($(NOTICE)).toHaveText(COPY[locale]);
  93. await assertReadOnlyHistory();
  94. const bounds = await browser.execute((selector) => {
  95. const notice = document.querySelector<HTMLElement>(selector)!;
  96. const pane = notice.closest('[data-testid="v4-session-pane-workspace-main"]')!;
  97. const rect = notice.getBoundingClientRect();
  98. const paneRect = pane.getBoundingClientRect();
  99. return {
  100. left: rect.left,
  101. right: rect.right,
  102. top: rect.top,
  103. bottom: rect.bottom,
  104. paneTop: paneRect.top,
  105. paneBottom: paneRect.bottom,
  106. viewportWidth: innerWidth,
  107. viewportHeight: innerHeight,
  108. scrollWidth: notice.scrollWidth,
  109. clientWidth: notice.clientWidth,
  110. };
  111. }, NOTICE);
  112. measurements.push({ width, theme, locale, ...bounds });
  113. await writeFile(
  114. join(artifact, "readonly-notice-layout.json"),
  115. JSON.stringify(measurements, null, 2),
  116. );
  117. await browser.saveScreenshot(
  118. join(artifact, `readonly-notice-${width}-${theme}-${locale}.png`),
  119. );
  120. expect(bounds.left).toBeGreaterThanOrEqual(0);
  121. expect(bounds.right).toBeLessThanOrEqual(bounds.viewportWidth);
  122. expect(bounds.bottom).toBeLessThanOrEqual(bounds.viewportHeight);
  123. expect(bounds.top).toBeGreaterThan((bounds.paneTop + bounds.paneBottom) / 2);
  124. expect(bounds.scrollWidth).toBeLessThanOrEqual(bounds.clientWidth);
  125. }
  126. }
  127. }
  128. } finally {
  129. await emulateViewport();
  130. if (sidebarCollapsed) {
  131. await browser.execute(() => (window as TestWindow).__testActions!.setLocale("en-US"));
  132. await $('button[aria-label="Toggle sidebar"]').click();
  133. }
  134. await browser.execute(() => {
  135. (window as TestWindow).__testActions!.setTheme("system");
  136. (window as TestWindow).__testActions!.setLocale("zh-CN");
  137. });
  138. }
  139. await rename(moved, primary);
  140. await browser.execute(() => window.dispatchEvent(new Event("focus")));
  141. await browser.waitUntil(
  142. async () => (await $(PROJECT).getAttribute("data-primary-root-status")) === "available",
  143. );
  144. // 侧栏目录刷新不改变既有 tab 只读状态;本次仅补提示,不新增自动恢复。
  145. await assertReadOnlyHistory();
  146. await reloadElectronSessionPreservingBrowserProfile(browser);
  147. await openHistory();
  148. await $(`[data-testid="${TID_V4_COMPOSER_INPUT}"]`).waitForDisplayed({ timeout: 30_000 });
  149. expect(await $(NOTICE).isExisting()).toBe(false);
  150. await browser.saveScreenshot(join(artifact, "readonly-notice-restored.png"));
  151. // 隔离 HOME 的清理归 runner,不能删除仍被当前 Main/Host 使用的目录。
  152. });
  153. });
  154. async function openHistory() {
  155. const toggle = $(PROJECT).$('[data-testid="virtual-project-toggle"]');
  156. await toggle.waitForDisplayed({ timeout: 45_000 });
  157. if ((await toggle.getAttribute("aria-expanded")) !== "true") await toggle.click();
  158. const history = $(PROJECT).$(`[data-testid="task-item-${HISTORY_ID}"]`);
  159. await history.waitForDisplayed({ timeout: 30_000 });
  160. await history.click();
  161. await $(`//*[normalize-space(.)="${HISTORY_BODY}" and not(*)]`).waitForDisplayed({
  162. timeout: 30_000,
  163. });
  164. }
  165. async function assertReadOnlyHistory() {
  166. expect(await $(`[data-testid="${TID_V4_COMPOSER_INPUT}"]`).isExisting()).toBe(false);
  167. expect(await $(`[data-testid="${TID_V4_COMPOSER_SEND}"]`).isExisting()).toBe(false);
  168. expect(await $(NOTICE).isDisplayed()).toBe(true);
  169. expect(await $(`//*[normalize-space(.)="${HISTORY_BODY}" and not(*)]`).isDisplayed()).toBe(true);
  170. }
  171. async function emulateViewport(width?: number) {
  172. await browser.electron.execute(async (electron, width) => {
  173. const appWindow = electron.BrowserWindow.getAllWindows().find((item) => item.isVisible())!;
  174. if (!appWindow.webContents.debugger.isAttached()) appWindow.webContents.debugger.attach("1.3");
  175. await appWindow.webContents.debugger.sendCommand(
  176. width ? "Emulation.setDeviceMetricsOverride" : "Emulation.clearDeviceMetricsOverride",
  177. width ? { width, height: 844, deviceScaleFactor: 1, mobile: false } : {},
  178. );
  179. }, width);
  180. if (width) {
  181. await browser.waitUntil(() =>
  182. browser.execute((expected) => {
  183. const sidebar = document.querySelector('[data-workspace-sidebar-panel="true"]');
  184. return (
  185. innerWidth === expected &&
  186. (sidebar?.getAnimations().every((item) => item.playState !== "running") ?? true)
  187. );
  188. }, width),
  189. );
  190. }
  191. }
  192. function seedHistory(workspacePath: string) {
  193. // 只写 runner 的隔离 HOME;复用真实 Host/CLI 两库数据合同,不 mock 消息或目录状态。
  194. const home = process.env.ZCODE_E2E_HOME_DIR;
  195. if (!home || !DEFAULT_WORKSPACE.startsWith(home)) throw new Error("isolated HOME required");
  196. const app = new DatabaseSync(join(home, ".zcode/v2/tasks-index.sqlite"));
  197. const cli = new DatabaseSync(join(home, ".zcode/cli/db/db.sqlite"));
  198. try {
  199. const projectId = app
  200. .prepare("SELECT project_id FROM project_roots WHERE root_path=? LIMIT 1")
  201. .get(workspacePath)?.project_id;
  202. if (typeof projectId !== "string") throw new Error("fixture project missing");
  203. const now = Date.now();
  204. cli
  205. .prepare(
  206. "INSERT INTO session(id,project_id,slug,directory,title,version,time_created,time_updated,title_source,last_outcome) VALUES(?,?,?,?,?,'1',?,?,'custom','completed')",
  207. )
  208. .run(
  209. HISTORY_ID,
  210. "e2e-primary-history",
  211. HISTORY_ID,
  212. workspacePath,
  213. "E2E_READONLY_HISTORY",
  214. now,
  215. now,
  216. );
  217. cli
  218. .prepare(
  219. "INSERT INTO message(id,session_id,time_created,time_updated,data,sequence) VALUES(?,?,?,?,?,0)",
  220. )
  221. .run(
  222. `${HISTORY_ID}_message`,
  223. HISTORY_ID,
  224. now,
  225. now,
  226. JSON.stringify({ role: "user", time: { created: now }, agent: "build" }),
  227. );
  228. cli
  229. .prepare(
  230. "INSERT INTO part(id,message_id,session_id,time_created,time_updated,data,sequence) VALUES(?,?,?,?,?,?,0)",
  231. )
  232. .run(
  233. `${HISTORY_ID}_part`,
  234. `${HISTORY_ID}_message`,
  235. HISTORY_ID,
  236. now,
  237. now,
  238. JSON.stringify({ type: "text", text: HISTORY_BODY }),
  239. );
  240. app
  241. .prepare(
  242. "INSERT INTO tasks(workspace_key,workspace_path,task_id,title,provider,mode,created_at,updated_at,host_id,root_path,project_id,cli_title,cli_title_source,cli_created_at,cli_updated_at,cli_last_outcome,cli_deleted,meta_json) VALUES(?,?,?,?,'glm','default',?,?,'local',?,?,?,'custom',?,?,'completed',0,?)",
  243. )
  244. .run(
  245. workspacePath,
  246. workspacePath,
  247. HISTORY_ID,
  248. "E2E_READONLY_HISTORY",
  249. now,
  250. now,
  251. workspacePath,
  252. projectId,
  253. "E2E_READONLY_HISTORY",
  254. now,
  255. now,
  256. JSON.stringify({
  257. taskId: HISTORY_ID,
  258. traceId: HISTORY_ID,
  259. title: "E2E_READONLY_HISTORY",
  260. workspacePath,
  261. createdAt: now,
  262. updatedAt: now,
  263. mode: "build",
  264. }),
  265. );
  266. } finally {
  267. cli.close();
  268. app.close();
  269. }
  270. }