workspace-management.e2e.ts 34 KB

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