workspace-management.e2e.ts 34 KB

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