workspace-management.e2e.ts 34 KB

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