workspace-management.e2e.ts 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  1. // Web e2e scenarios: workspace management — adding a workspace through the
  2. // composed directory dialog (its own New folder affordance is the product's
  3. // one creation route), same-basename directory adoption, the rename round
  4. // trip over the real wire (workspace.rename RPC + durable registry), the
  5. // duplicate-name pre-check, the
  6. // flat "In one list" view with its persisted group-by preference, the session
  7. // hover card and row action menu, and the session archive round trip (row
  8. // menu → workspace.archiveSession RPC → durable global set → row hidden
  9. // across reload). Zero model calls: workspace.create/rename/archiveSession
  10. // are host RPCs with no model involvement, and the one session row the
  11. // flat/hover/menu/archive scenarios need comes from a seeded fixture (the
  12. // seeded-history seed reused verbatim — no new recording).
  13. import { mkdir, readFile, stat, writeFile } from 'node:fs/promises'
  14. import { fileURLToPath } from 'node:url'
  15. import { join } from 'node:path'
  16. import type { Browser, Locator, Page } from 'playwright'
  17. import { chromium } from 'playwright'
  18. import { afterAll, beforeAll, describe, expect, it, onTestFailed } from 'vitest'
  19. import { SessionId } from '@deepseek-ai/dsh-session'
  20. import {
  21. acknowledgeReloadConnectionLoss, assertFixtureInventory, captureStableAria, compareOrRefreshGolden,
  22. launchWebScaffold, seedSession, watchConsole, webSnapshotMode, type WebScaffold,
  23. } from './scaffold.ts'
  24. import { newEnglishPage, saveFailureShot } from './support.ts'
  25. const SNAPSHOT_DIR = fileURLToPath(new URL('./snapshots/workspace-management', import.meta.url))
  26. // The seed is another scenario's committed fixture, reused read-only: this
  27. // spec needs any one cold session row, not new recorded content.
  28. const SEED = fileURLToPath(new URL('./snapshots/seeded-history/seed.jsonl', import.meta.url))
  29. const MODE = webSnapshotMode()
  30. const BROWSER_EXPECTED = join(SNAPSHOT_DIR, 'directory-browser.expected.md')
  31. const SEED_ID = 'workspace-management-web-e2e'
  32. // Both waits exceed ui-primitives' 200ms POINTER_GRACE_MS. Keep them coupled
  33. // to that contract if the shared grace tuning changes.
  34. const POINTER_TRANSIT_MS = 300
  35. const POINTER_HOLD_MS = 600
  36. describe('web e2e: workspace management (create / rename / flat view / hover affordances)', () => {
  37. let scaffold: WebScaffold
  38. let browser: Browser
  39. let page: Page
  40. let tripwire: ReturnType<typeof watchConsole>
  41. /**
  42. * Raise the region header's directory dialog and drive it to a directory via
  43. * the path-edit affordance. Adding is the header button's only action, so
  44. * the click lands in the dialog with no menu in between.
  45. */
  46. async function browseTo(path: string): Promise<Locator> {
  47. await page.getByRole('button', { name: 'Add workspace' }).click()
  48. const dialog = page.getByRole('dialog', { name: 'Select Workspace Directory' })
  49. await dialog.waitFor({ timeout: 10_000 })
  50. await dialog.getByRole('button', { name: 'Edit path' }).click()
  51. await dialog.getByLabel('Edit path').fill(path)
  52. await dialog.getByLabel('Edit path').press('Enter')
  53. return dialog
  54. }
  55. /**
  56. * Create a folder inside `parent` through the dialog and adopt it — the
  57. * product's only route to a brand-new workspace directory.
  58. */
  59. async function addNewFolderWorkspace(parent: string, name: string): Promise<void> {
  60. const dialog = await browseTo(parent)
  61. await dialog.getByRole('button', { name: 'New folder' }).click()
  62. await page.getByLabel('Folder name').fill(name)
  63. await page.getByRole('button', { name: 'Create', exact: true }).click()
  64. // Creating selects the new folder in the listing; Open adopts it.
  65. await dialog.getByRole('button', { name: 'Open', exact: true }).click()
  66. await dialog.waitFor({ state: 'hidden', timeout: 10_000 })
  67. await expect.poll(
  68. () => scaffold.ctx.workspace.resolveByPath(join(parent, name)),
  69. { timeout: 10_000 },
  70. ).not.toBeUndefined()
  71. }
  72. /**
  73. * Adopt an existing directory, waiting for the adoption to settle host-side
  74. * (workspace registered + the flow's New-Session agent up), so later test
  75. * steps can't race the in-flight blank-session attach.
  76. */
  77. async function adoptDirectory(path: string, options: { waitForAgent?: boolean } = {}): Promise<void> {
  78. const agentsBefore = scaffold.ctx.agents.list().length
  79. const dialog = await browseTo(path)
  80. await dialog.getByRole('button', { name: 'Open', exact: true }).click()
  81. await dialog.waitFor({ state: 'hidden', timeout: 10_000 })
  82. await expect.poll(
  83. () => scaffold.ctx.workspace.resolveByPath(path),
  84. { timeout: 10_000 },
  85. ).not.toBeUndefined()
  86. // First adoption births a blank Session+Agent whose workspace attach must
  87. // settle before a test may delete the registration; the reuse path (same
  88. // canonical cwd already has a blank session) creates no agent, so callers
  89. // opt in only where a fresh attach is possible.
  90. if (options.waitForAgent === true) {
  91. await expect.poll(() => scaffold.ctx.agents.list().length, { timeout: 10_000 })
  92. .toBeGreaterThan(agentsBefore)
  93. }
  94. }
  95. beforeAll(async () => {
  96. scaffold = await launchWebScaffold({})
  97. // Seed one cold session (Ungrouped bucket) for the flat view + hover card.
  98. const sessionCwd = join(scaffold.workspaceCwd, 'workspace')
  99. await mkdir(sessionCwd, { recursive: true })
  100. await writeFile(join(sessionCwd, 'a.txt'), 'alpha\n')
  101. await writeFile(join(sessionCwd, 'b.txt'), 'beta\n')
  102. await seedSession(scaffold, await readFile(SEED, 'utf8'), SEED_ID)
  103. browser = await chromium.launch()
  104. page = await newEnglishPage(browser)
  105. tripwire = watchConsole(page)
  106. await page.goto(scaffold.baseUrl, { waitUntil: 'load' })
  107. await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  108. }, 120_000)
  109. afterAll(async () => {
  110. await browser?.close()
  111. await scaffold?.close()
  112. })
  113. it('adds two workspaces through the dialog, each on a folder it created', async () => {
  114. onTestFailed(() => saveFailureShot(page, 'web-e2e-ws-create'))
  115. const add = async (name: string): Promise<void> => {
  116. await addNewFolderWorkspace(scaffold.workspaceCwd, name)
  117. // The real workspace materializes in the tree as a group row.
  118. await expect.poll(() => page.getByText(name, { exact: true }).count(), { timeout: 10_000 }).toBeGreaterThanOrEqual(1)
  119. }
  120. await add('alpha-ws')
  121. await add('beta-ws')
  122. // Durable on the host: both registered, newest first (create prepends),
  123. // each titled after the folder the dialog made.
  124. const titles = scaffold.ctx.workspace.list().map(workspace => workspace.title)
  125. expect(titles.slice(0, 2)).toEqual(['beta-ws', 'alpha-ws'])
  126. expect(tripwire.pageErrors).toEqual([])
  127. }, 90_000)
  128. it('renames a workspace over the wire with a duplicate-name pre-check', async () => {
  129. onTestFailed(() => saveFailureShot(page, 'web-e2e-ws-rename'))
  130. // The actions button is display:none until its row hovers — hover the
  131. // group row first, then the revealed button becomes actionable.
  132. await page.locator('[role="treeitem"]').filter({ hasText: 'alpha-ws' }).first().hover()
  133. await page.getByRole('button', { name: 'Workspace actions for alpha-ws' }).click()
  134. await page.getByRole('menuitem', { name: 'Rename' }).click()
  135. const dialog = page.getByRole('dialog', { name: 'Rename workspace' })
  136. await dialog.waitFor({ timeout: 10_000 })
  137. const input = dialog.getByLabel('Workspace name')
  138. // Client pre-check: a name colliding with another live workspace raises
  139. // the inline alert and blocks the primary button before any wire call.
  140. await input.fill('beta-ws')
  141. await expect.poll(() => dialog.getByRole('alert').count(), { timeout: 5_000 }).toBe(1)
  142. expect(await dialog.getByRole('button', { name: 'Rename' }).isDisabled()).toBe(true)
  143. // A fresh name goes through workspace.rename to the durable registry.
  144. await input.fill('gamma-ws')
  145. await expect.poll(() => dialog.getByRole('alert').count(), { timeout: 5_000 }).toBe(0)
  146. await dialog.getByRole('button', { name: 'Rename' }).click()
  147. await expect.poll(() => page.getByRole('dialog', { name: 'Rename workspace' }).count(), { timeout: 10_000 }).toBe(0)
  148. await expect.poll(() => page.getByText('gamma-ws', { exact: true }).count(), { timeout: 10_000 }).toBeGreaterThanOrEqual(1)
  149. expect(await page.getByText('alpha-ws', { exact: true }).count()).toBe(0)
  150. // Host durability, then reload: the projection is rebuilt from the wire.
  151. expect(scaffold.ctx.workspace.list().map(workspace => workspace.title)).toContain('gamma-ws')
  152. const warningStart = tripwire.warnings.length
  153. await page.reload({ waitUntil: 'load' })
  154. await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  155. acknowledgeReloadConnectionLoss(tripwire, warningStart)
  156. await expect.poll(() => page.getByText('gamma-ws', { exact: true }).count(), { timeout: 15_000 }).toBeGreaterThanOrEqual(1)
  157. expect(tripwire.pageErrors).toEqual([])
  158. }, 90_000)
  159. it('deletes only the Workspace registration and keeps its current Session, folder, and log', async () => {
  160. onTestFailed(() => saveFailureShot(page, 'web-e2e-ws-delete'))
  161. const slotConsoleErrors: string[] = []
  162. const transientSlotErrors: string[] = []
  163. page.on('console', (message) => {
  164. if (message.type() === 'error' && /slot entry crashed/i.test(message.text())) {
  165. slotConsoleErrors.push(message.text())
  166. }
  167. })
  168. await page.exposeFunction('recordDshSlotError', (key: string) => {
  169. if (!transientSlotErrors.includes(key)) transientSlotErrors.push(key)
  170. })
  171. await page.evaluate(() => {
  172. const target = window as unknown as { recordDshSlotError(key: string): Promise<void> }
  173. const seen = new Set<string>()
  174. const collect = (): void => {
  175. for (const node of document.querySelectorAll<HTMLElement>('[data-slot-error]')) {
  176. const key = node.dataset.slotError ?? ''
  177. if (!seen.has(key)) {
  178. seen.add(key)
  179. void target.recordDshSlotError(key)
  180. }
  181. }
  182. }
  183. new MutationObserver(collect).observe(document.documentElement, { childList: true, subtree: true })
  184. collect()
  185. })
  186. // Register the scaffold's existing project directory through the real UI.
  187. await adoptDirectory(scaffold.workspaceCwd, { waitForAgent: true })
  188. const workspace = await scaffold.ctx.workspace.resolveByPath(scaffold.workspaceCwd)
  189. if (workspace === undefined) throw new Error('GUI did not register the existing project directory')
  190. await workspace.attachSession(SessionId(SEED_ID))
  191. const header = (await scaffold.ctx.sessionPersistence.list())
  192. .find(candidate => candidate.id === SEED_ID)
  193. if (header === undefined) throw new Error('seeded Session log disappeared before deletion')
  194. const logLocation = scaffold.ctx.sessionPersistence.locate(header)
  195. if (logLocation === undefined) throw new Error('JSONL persistence did not expose the seeded log path')
  196. expect(await readFile(join(scaffold.workspaceCwd, 'workspace', 'a.txt'), 'utf8')).toBe('alpha\n')
  197. await stat(logLocation.path)
  198. // Open the seeded (first/accounted) Session so deletion must preserve the
  199. // current selection while it moves into Ungrouped.
  200. const groupRow = page.locator('[role="treeitem"]').filter({ hasText: workspace.title }).first()
  201. await groupRow.waitFor({ timeout: 10_000 })
  202. // The header row is wrapped by its HoverCard anchor span, so the section
  203. // is the nearest groupSection ancestor, not the immediate parent.
  204. const groupSection = groupRow.locator('xpath=ancestor::*[contains(@class, "groupSection")][1]')
  205. if (await groupSection.locator('[role="treeitem"]').count() < 2) await groupRow.click()
  206. await expect.poll(
  207. () => groupSection.locator('[role="treeitem"]').count(),
  208. { timeout: 10_000 },
  209. ).toBeGreaterThanOrEqual(2)
  210. const seededRow = groupSection.locator('[role="treeitem"]').nth(1)
  211. await seededRow.click()
  212. await expect.poll(() => seededRow.getAttribute('aria-selected'), { timeout: 10_000 }).toBe('true')
  213. await groupRow.hover()
  214. await page.getByRole('button', { name: `Workspace actions for ${workspace.title}` }).click()
  215. await page.getByRole('menuitem', { name: 'Delete workspace' }).click()
  216. const dialog = page.getByRole('dialog', { name: 'Delete workspace' })
  217. await dialog.waitFor({ timeout: 10_000 })
  218. const copy = await dialog.textContent()
  219. expect(copy).toContain('workspace list')
  220. expect(copy).toContain('folder and session logs will be kept')
  221. expect(copy).toContain('sessions will appear under Ungrouped')
  222. await dialog.getByRole('button', { name: 'Delete workspace' }).click()
  223. await expect.poll(() => dialog.count(), { timeout: 10_000 }).toBe(0)
  224. expect(scaffold.ctx.workspace.get(workspace.id)).toBeUndefined()
  225. await expect.poll(
  226. () => page.getByRole('button', { name: `Workspace actions for ${workspace.title}` }).count(),
  227. { timeout: 10_000 },
  228. ).toBe(0)
  229. await expect.poll(() => page.getByText('Ungrouped', { exact: true }).count(), { timeout: 10_000 })
  230. .toBeGreaterThanOrEqual(1)
  231. await expect.poll(
  232. () => page.locator('[role="treeitem"][aria-selected="true"]').count(),
  233. { timeout: 10_000 },
  234. ).toBe(1)
  235. expect(await readFile(join(scaffold.workspaceCwd, 'workspace', 'a.txt'), 'utf8')).toBe('alpha\n')
  236. await stat(logLocation.path)
  237. expect((await scaffold.ctx.sessionPersistence.inspect(SessionId(SEED_ID))).events.length).toBeGreaterThan(0)
  238. // Re-registering the exact deleted path immediately, without a reload, is
  239. // a supported reversible flow. It creates a fresh Workspace id without
  240. // re-adopting the retained Session.
  241. await adoptDirectory(scaffold.workspaceCwd)
  242. await expect.poll(
  243. () => scaffold.ctx.workspace.resolveByPath(scaffold.workspaceCwd),
  244. { timeout: 10_000 },
  245. ).not.toBeUndefined()
  246. const reregistered = await scaffold.ctx.workspace.resolveByPath(scaffold.workspaceCwd)
  247. expect(reregistered?.id).toBeDefined()
  248. expect(reregistered?.id).not.toBe(workspace.id)
  249. expect(reregistered?.sessionIds).toEqual([])
  250. await expect.poll(() => page.getByText('Ungrouped', { exact: true }).count(), { timeout: 10_000 })
  251. .toBeGreaterThanOrEqual(1)
  252. expect(await readFile(join(scaffold.workspaceCwd, 'workspace', 'a.txt'), 'utf8')).toBe('alpha\n')
  253. await stat(logLocation.path)
  254. // Restore the deleted-registry state so reload still verifies deletion
  255. // persistence independently of the successful re-registration above.
  256. if (reregistered === undefined) throw new Error('same-path re-registration did not materialize')
  257. await scaffold.ctx.workspace.delete(reregistered.id)
  258. await expect.poll(
  259. () => page.getByRole('button', { name: `Workspace actions for ${reregistered.title}` }).count(),
  260. { timeout: 10_000 },
  261. ).toBe(0)
  262. const warningStart = tripwire.warnings.length
  263. await page.reload({ waitUntil: 'load' })
  264. await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  265. acknowledgeReloadConnectionLoss(tripwire, warningStart)
  266. await expect.poll(() => page.getByText('Ungrouped', { exact: true }).count(), { timeout: 15_000 })
  267. .toBeGreaterThanOrEqual(1)
  268. await expect.poll(
  269. () => page.locator('[role="treeitem"][aria-selected="true"]').count(),
  270. { timeout: 15_000 },
  271. ).toBe(1)
  272. expect(scaffold.ctx.workspace.get(workspace.id)).toBeUndefined()
  273. expect(await readFile(join(scaffold.workspaceCwd, 'workspace', 'a.txt'), 'utf8')).toBe('alpha\n')
  274. await stat(logLocation.path)
  275. expect((await scaffold.ctx.sessionPersistence.inspect(SessionId(SEED_ID))).events.length).toBeGreaterThan(0)
  276. expect(transientSlotErrors).toEqual([])
  277. expect(slotConsoleErrors).toEqual([])
  278. expect(tripwire.pageErrors).toEqual([])
  279. }, 90_000)
  280. it('reuses a deleted title for a different new directory without any transient error surface', async () => {
  281. onTestFailed(() => saveFailureShot(page, 'web-e2e-ws-reuse-title'))
  282. const title = 'same-name'
  283. const oldPath = join(scaffold.workspaceCwd, 'adopted', title)
  284. await mkdir(oldPath, { recursive: true })
  285. const transientErrors: string[] = []
  286. const consoleErrors: string[] = []
  287. page.on('console', (message) => {
  288. if (message.type() === 'error') consoleErrors.push(message.text())
  289. })
  290. await page.exposeFunction('recordDshTransientWorkspaceError', (message: string) => {
  291. if (!transientErrors.includes(message)) transientErrors.push(message)
  292. })
  293. await page.evaluate(() => {
  294. const target = window as unknown as {
  295. recordDshTransientWorkspaceError(message: string): Promise<void>
  296. }
  297. const collect = (): void => {
  298. for (const node of document.querySelectorAll<HTMLElement>('[data-slot-error], [role="alert"]')) {
  299. const message = node.dataset.slotError ?? node.textContent?.trim() ?? ''
  300. if (message !== '') void target.recordDshTransientWorkspaceError(message)
  301. }
  302. }
  303. new MutationObserver(collect).observe(document.documentElement, { childList: true, subtree: true })
  304. collect()
  305. })
  306. await adoptDirectory(oldPath)
  307. await expect.poll(
  308. () => scaffold.ctx.workspace.resolveByPath(oldPath),
  309. { timeout: 10_000 },
  310. ).not.toBeUndefined()
  311. const oldWorkspace = await scaffold.ctx.workspace.resolveByPath(oldPath)
  312. if (oldWorkspace === undefined) throw new Error('old same-name Workspace was not registered')
  313. const oldRow = page.locator('[role="treeitem"]').filter({ hasText: title }).first()
  314. await oldRow.hover()
  315. await page.getByRole('button', { name: `Workspace actions for ${title}` }).click()
  316. await page.getByRole('menuitem', { name: 'Delete workspace' }).click()
  317. await page.getByRole('dialog', { name: 'Delete workspace' })
  318. .getByRole('button', { name: 'Delete workspace' }).click()
  319. await expect.poll(() => scaffold.ctx.workspace.get(oldWorkspace.id), { timeout: 10_000 }).toBeUndefined()
  320. await addNewFolderWorkspace(scaffold.workspaceCwd, title)
  321. const fresh = scaffold.ctx.workspace.list().find(workspace => workspace.title === title)
  322. expect(fresh?.id).toBeDefined()
  323. expect(fresh?.id).not.toBe(oldWorkspace.id)
  324. expect(fresh?.path).toBe(join(scaffold.workspaceCwd, title))
  325. expect(transientErrors).toEqual([])
  326. expect(consoleErrors).toEqual([])
  327. expect(tripwire.pageErrors).toEqual([])
  328. }, 90_000)
  329. it('switches to the flat "In one list" view and persists the preference', async () => {
  330. onTestFailed(() => saveFailureShot(page, 'web-e2e-ws-flat'))
  331. // Grouped default: workspace group rows render (the seeded session sits
  332. // under Ungrouped; the created workspaces are empty groups).
  333. await expect.poll(() => page.getByText('Workspaces', { exact: true }).count(), { timeout: 10_000 }).toBe(1)
  334. await page.getByRole('button', { name: 'Group by' }).click()
  335. await page.getByRole('menuitem', { name: 'In one list' }).click()
  336. // Flat mode: the section label flips and the seeded session is a
  337. // top-level row with no group headers above it.
  338. await expect.poll(() => page.getByText('Sessions', { exact: true }).count(), { timeout: 10_000 }).toBeGreaterThanOrEqual(1)
  339. await expect.poll(() => page.getByText('Ungrouped', { exact: true }).count(), { timeout: 5_000 }).toBe(0)
  340. await expect.poll(() => page.locator('[role="treeitem"]').count(), { timeout: 10_000 }).toBeGreaterThanOrEqual(1)
  341. expect(await page.evaluate(() => localStorage.getItem('dsh.workspace.view'))).toContain('flat')
  342. // Persisted across reload; then restore grouped for inter-spec hygiene.
  343. const warningStart = tripwire.warnings.length
  344. await page.reload({ waitUntil: 'load' })
  345. await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  346. acknowledgeReloadConnectionLoss(tripwire, warningStart)
  347. await expect.poll(() => page.getByText('Ungrouped', { exact: true }).count(), { timeout: 15_000 }).toBe(0)
  348. await page.getByRole('button', { name: 'Group by' }).click()
  349. await page.getByRole('menuitem', { name: 'WorkSpace' }).click()
  350. await expect.poll(() => page.getByText('Ungrouped', { exact: true }).count(), { timeout: 10_000 }).toBeGreaterThanOrEqual(1)
  351. expect(tripwire.pageErrors).toEqual([])
  352. }, 90_000)
  353. it('matches the directory-browser dialog aria golden at a staged directory', async () => {
  354. // A staged subtree under the scaffold cwd keeps the listing deterministic
  355. // (normalizeAria scrubs the cwd), and pointing the in-process host's HOME
  356. // at the cwd collapses the breadcrumb ancestry into the Home crumb — no
  357. // machine-specific path segments or real $HOME contents enter the golden.
  358. const staged = join(scaffold.workspaceCwd, 'browse-golden')
  359. await mkdir(join(staged, 'alpha'), { recursive: true })
  360. await mkdir(join(staged, 'beta'), { recursive: true })
  361. // homedir() reads HOME on POSIX and USERPROFILE on Windows: root both
  362. // at the scaffold cwd so the golden's ancestry collapses everywhere.
  363. const realHome = process.env.HOME
  364. const realUserProfile = process.env.USERPROFILE
  365. process.env.HOME = scaffold.workspaceCwd
  366. process.env.USERPROFILE = scaffold.workspaceCwd
  367. try {
  368. const dialog = await browseTo(staged)
  369. await expect.poll(() => dialog.getByText('alpha', { exact: true }).count(), { timeout: 10_000 }).toBe(1)
  370. const snapshot = await captureStableAria(page, '[role="dialog"]', scaffold.workspaceCwd)
  371. await compareOrRefreshGolden(BROWSER_EXPECTED, snapshot, MODE)
  372. await dialog.getByRole('button', { name: 'Cancel' }).click()
  373. await dialog.waitFor({ state: 'hidden', timeout: 10_000 })
  374. } finally {
  375. if (realHome === undefined) delete process.env.HOME
  376. else process.env.HOME = realHome
  377. if (realUserProfile === undefined) delete process.env.USERPROFILE
  378. else process.env.USERPROFILE = realUserProfile
  379. }
  380. expect(tripwire.pageErrors).toEqual([])
  381. }, 60_000)
  382. /**
  383. * Expand Ungrouped and return its seeded session row. The only visible child
  384. * is the non-blank persisted Session; the blank Session created while
  385. * adopting the Workspace stays hidden.
  386. * @returns the session row locator, already present.
  387. */
  388. async function seededSessionRow() {
  389. const ungroupedRow = page.getByText('Ungrouped', { exact: true }).locator('..').locator('..')
  390. const ungroupedSection = ungroupedRow.locator('..')
  391. // Initial-current auto-expansion can race this gesture; converge on
  392. // expanded rather than assuming which update wins first.
  393. await expect.poll(async () => {
  394. if (await ungroupedRow.getAttribute('aria-expanded') !== 'true') {
  395. await page.getByText('Ungrouped', { exact: true }).click()
  396. await page.waitForTimeout(50)
  397. }
  398. return await ungroupedRow.getAttribute('aria-expanded')
  399. }, { timeout: 5_000 }).toBe('true')
  400. const row = ungroupedSection.locator('[role="treeitem"]').nth(1)
  401. await row.waitFor({ timeout: 10_000 })
  402. return row
  403. }
  404. it('shows the session hover card after a dwell on the row', async () => {
  405. onTestFailed(() => saveFailureShot(page, 'web-e2e-ws-hover'))
  406. // Dwell on the seeded row; the card opens after a 500ms hover delay,
  407. // portaled to body.
  408. const sessionRow = await seededSessionRow()
  409. const rowTitle = await sessionRow.locator('[class*="title"]').innerText()
  410. await sessionRow.hover()
  411. // Card content: the full title plus the Idle status line (no aria role —
  412. // text anchors are the stable selector).
  413. await expect.poll(() => page.getByText('Idle', { exact: true }).count(), { timeout: 5_000 }).toBeGreaterThanOrEqual(1)
  414. // The card is REACHABLE: it sits 8px off the row, so getting to it means
  415. // crossing ground that belongs to neither. Hovering it must not dismiss
  416. // it — the regression this scenario guards.
  417. const card = page.getByRole('button', { name: `Copy: ${rowTitle}` })
  418. await card.hover()
  419. await page.waitForTimeout(POINTER_HOLD_MS)
  420. expect(await page.getByText('Idle', { exact: true }).count()).toBeGreaterThanOrEqual(1)
  421. // The full title is the card's primary value: activating anywhere on the
  422. // card writes it through the browser clipboard and localizes the success
  423. // feedback through the English locale seat.
  424. await page.context().grantPermissions(['clipboard-read', 'clipboard-write'])
  425. const cardHeight = (await card.boundingBox())?.height
  426. await card.click()
  427. const copied = page.getByRole('status').getByText('Copied', { exact: true })
  428. await copied.waitFor({ timeout: 5_000 })
  429. await page.waitForTimeout(POINTER_HOLD_MS)
  430. expect((await card.boundingBox())?.height).toBe(cardHeight)
  431. expect(await copied.isVisible()).toBe(true)
  432. expect(await page.evaluate(() => navigator.clipboard.readText())).toBe(rowTitle)
  433. // Leaving anchor and card together closes it after the grace.
  434. await page.getByRole('button', { name: 'Settings' }).hover()
  435. await expect.poll(() => card.count(), { timeout: 5_000 }).toBe(0)
  436. expect(tripwire.pageErrors).toEqual([])
  437. }, 60_000)
  438. it('keeps an open row menu up while the pointer moves between trigger and list', async () => {
  439. onTestFailed(() => saveFailureShot(page, 'web-e2e-ws-row-menu'))
  440. const sessionRow = await seededSessionRow()
  441. // The trigger is display:none until its row hovers.
  442. await sessionRow.hover()
  443. const trigger = sessionRow.locator('button[aria-label^="Session actions for "]')
  444. await trigger.click()
  445. const item = page.getByRole('menuitem', { name: 'Rename' })
  446. await item.waitFor({ timeout: 5_000 })
  447. // Into the list, then back up to the trigger across the 4px gap below it:
  448. // that return trip used to fire the list's pointerleave and close the
  449. // menu, so a hesitating pointer lost it. Order matters — clicking leaves
  450. // the pointer ON the trigger, so entering the list has to come first for
  451. // the return to be a real departure.
  452. await item.hover()
  453. await page.waitForTimeout(POINTER_TRANSIT_MS)
  454. await trigger.hover()
  455. await page.waitForTimeout(POINTER_HOLD_MS)
  456. expect(await page.getByRole('menuitem', { name: 'Rename' }).count()).toBe(1)
  457. // ...and back down into the list, which must still be there to enter.
  458. await item.hover()
  459. await page.waitForTimeout(POINTER_HOLD_MS)
  460. expect(await page.getByRole('menuitem', { name: 'Rename' }).count()).toBe(1)
  461. // Pointer-leave dismissal still applies once the pointer genuinely leaves.
  462. await page.getByRole('button', { name: 'Settings' }).hover()
  463. await expect.poll(() => page.getByRole('menuitem', { name: 'Rename' }).count(), { timeout: 5_000 }).toBe(0)
  464. expect(tripwire.pageErrors).toEqual([])
  465. }, 60_000)
  466. it('archives the seeded session from its row menu, hiding it durably across reload', async () => {
  467. onTestFailed(() => saveFailureShot(page, 'web-e2e-ws-archive'))
  468. // The seeded session lives under Ungrouped (expanded by the hover-card
  469. // test's gesture; converge again for order independence).
  470. const ungroupedRow = page.getByText('Ungrouped', { exact: true }).locator('..').locator('..')
  471. const ungroupedSection = ungroupedRow.locator('..')
  472. await expect.poll(async () => {
  473. if (await ungroupedRow.getAttribute('aria-expanded') !== 'true') {
  474. await page.getByText('Ungrouped', { exact: true }).click()
  475. await page.waitForTimeout(50)
  476. }
  477. return await ungroupedRow.getAttribute('aria-expanded')
  478. }, { timeout: 5_000 }).toBe('true')
  479. // Anchor on session rows (the rows carrying a session actions button),
  480. // not a positional index, and assert the single-stray assumption loudly
  481. // so a fixture gaining a second stray fails here instead of archiving
  482. // the wrong row. CSS attribute match, not getByRole: the button is
  483. // display:none until its row hovers, and role queries skip hidden nodes.
  484. const sessionRows = ungroupedSection.locator('[role="treeitem"]')
  485. .filter({ has: page.locator('button[aria-label^="Session actions for "]') })
  486. await expect.poll(() => sessionRows.count(), { timeout: 10_000 }).toBe(1)
  487. const sessionRow = sessionRows.first()
  488. const rowTitle = await sessionRow.locator('[class*="title"]').innerText()
  489. // Row menu: hover reveals the actions button; Archive session commits
  490. // without a confirmation dialog (non-destructive: log + accounting stay).
  491. await sessionRow.hover()
  492. await sessionRow.getByRole('button', { name: `Session actions for ${rowTitle}` }).click()
  493. await page.getByRole('menuitem', { name: 'Archive session' }).click()
  494. // The row disappears on the archive-set echo; with no other visible
  495. // stray, the whole Ungrouped bucket withdraws.
  496. await expect.poll(() => page.getByText(rowTitle, { exact: true }).count(), { timeout: 10_000 }).toBe(0)
  497. await expect.poll(() => page.getByText('Ungrouped', { exact: true }).count(), { timeout: 10_000 }).toBe(0)
  498. // Durable on the host: the registry-global set carries the id while the
  499. // session log itself stays in persistence untouched.
  500. expect([...scaffold.ctx.workspace.archivedSessionIds]).toEqual([SessionId(SEED_ID)])
  501. expect((await scaffold.ctx.sessionPersistence.list()).map(header => header.id)).toContain(SessionId(SEED_ID))
  502. // Reload: the hidden state is rebuilt from the workspace.list baseline.
  503. const warningStart = tripwire.warnings.length
  504. await page.reload({ waitUntil: 'load' })
  505. await page.waitForSelector('[class*="frame"]', { timeout: 30_000 })
  506. acknowledgeReloadConnectionLoss(tripwire, warningStart)
  507. await expect.poll(() => page.getByText('Workspaces', { exact: true }).count(), { timeout: 15_000 }).toBe(1)
  508. // The archived row must not resurface (the Ungrouped bucket itself may
  509. // reappear if selection restore lands on another stray — not this test's
  510. // concern).
  511. expect(await page.getByText(rowTitle, { exact: true }).count()).toBe(0)
  512. expect(tripwire.pageErrors).toEqual([])
  513. }, 90_000)
  514. it('opens folders with identical basenames as distinct workspaces', async () => {
  515. onTestFailed(() => saveFailureShot(page, 'web-e2e-ws-duplicate-basename'))
  516. const firstPath = join(scaffold.workspaceCwd, 'same-basename-a', 'xx')
  517. const secondPath = join(scaffold.workspaceCwd, 'same-basename-b', 'xx')
  518. await mkdir(firstPath, { recursive: true })
  519. await mkdir(secondPath, { recursive: true })
  520. await adoptDirectory(firstPath, { waitForAgent: true })
  521. await adoptDirectory(secondPath, { waitForAgent: true })
  522. const matchingWorkspaces = scaffold.ctx.workspace.list()
  523. .filter(workspace => workspace.title === 'xx')
  524. expect(matchingWorkspaces.map(workspace => workspace.path).sort())
  525. .toEqual([firstPath, secondPath].sort())
  526. await expect.poll(
  527. () => page.locator('button[aria-label="Workspace actions for xx"]').count(),
  528. { timeout: 10_000 },
  529. ).toBe(2)
  530. expect(tripwire.pageErrors).toEqual([])
  531. }, 90_000)
  532. it.skipIf(MODE === 'record')('issued zero model calls and stayed clean', async () => {
  533. expect(tripwire.warnings).toEqual([])
  534. // The directory-browser aria golden is this spec's one owned artifact;
  535. // the seed it reuses is owned (and inventory-guarded) by seeded-history.
  536. await assertFixtureInventory(SNAPSHOT_DIR, ['.gitkeep', 'directory-browser.expected.md'])
  537. })
  538. })