Skip to content

The agent that grows with you

Merge upstream main (b81383ec21) into the install-e2e suite branch

yoniebansd19038e76b49
diff --cc apps/desktop/e2e/batch-clarify.spec.ts
index 00000000000,acf97ddb2e3..ee4ec732535
mode 000000,100644..100644
--- a/apps/desktop/e2e/batch-clarify.spec.ts
+++ b/apps/desktop/e2e/batch-clarify.spec.ts
@@@ -1,0 -1,86 +1,86 @@@
+ /**
+ * E2E batch clarify test — the multi-question clarify card must mount ONCE.
+ *
+ * Regression coverage for the duplicated-card bug: `tool.start` carries the
+ * model's tool_call_id while `clarify.request` carries a gateway-generated
+ * request_id. A batch payload has no top-level `question`, so the two rows
+ * only merge when the correlation key comes from the question list
+ * (`batchClarifyMatchValue` in lib/chat-messages/tool-parts.ts). Before that
+ * fix this exact flow rendered two identical interactive cards.
+ *
+ * The flow runs the real chain: composer → gateway → agent → clarify tool →
+ * clarify.request event → renderer, against the mock inference server.
+ */
+
+ import { expect, test } from './test'
+
+ import { type MockBackendFixture, setupMockBackend, waitForAppReady } from './fixtures'
-import { BATCH_CLARIFY_QUESTIONS, BATCH_CLARIFY_TRIGGER } from './mock-server'
++import { BATCH_CLARIFY_QUESTIONS, BATCH_CLARIFY_TRIGGER } from '../../../tests-js/scripts/mock-server'
+
+ let fixture: MockBackendFixture | null = null
+
+ test.beforeAll(async () => {
+ fixture = await setupMockBackend()
+ await waitForAppReady(fixture!, 120_000)
+ })
+
+ test.afterAll(async () => {
+ await fixture?.cleanup()
+ fixture = null
+ })
+
+ test.describe('batch clarify card', () => {
+ test('renders exactly one card and completes via per-question locks', async () => {
+ const page = fixture!.page
+ const composer = page.locator('[contenteditable="true"]').first()
+ await composer.waitFor({ state: 'visible', timeout: 10_000 })
+
+ await composer.click()
+ await composer.type(BATCH_CLARIFY_TRIGGER, { delay: 20 })
+ await page.keyboard.press('Enter')
+
+ // The live batch form marks itself with data-clarify-batch=<count>.
+ const batchCard = page.locator('form[data-clarify-batch]')
+ await batchCard.first().waitFor({ state: 'visible', timeout: 60_000 })
+
+ // THE regression assertion: one card, not two.
+ await expect(batchCard).toHaveCount(1)
+ await expect(batchCard).toHaveAttribute('data-clarify-batch', String(BATCH_CLARIFY_QUESTIONS.length))
+
+ // Both questions render inside the single card.
+ for (const entry of BATCH_CLARIFY_QUESTIONS) {
+ await expect(batchCard.getByText(entry.question)).toHaveCount(1)
+ }
+
+ // Each question text also appears exactly once in the whole transcript —
+ // catches a duplicate that mounts outside a form[data-clarify-batch].
+ for (const entry of BATCH_CLARIFY_QUESTIONS) {
+ await expect(page.getByText(entry.question)).toHaveCount(1)
+ }
+
+ // Answer both questions: stage picks locally (no server traffic yet).
+ const confirmButton = batchCard.locator('button[type="submit"]')
+ await expect(confirmButton).toContainText('Confirm and continue')
+ await expect(confirmButton).toBeDisabled()
+
+ await batchCard.getByRole('button', { name: /Coffee/ }).click()
+ await expect(confirmButton).toBeDisabled()
+
+ await batchCard.getByRole('button', { name: /Morning/ }).click()
+ await expect(confirmButton).toBeEnabled()
+
+ // ONE confirm submits the whole batch.
+ await confirmButton.click()
+
+ // The settled card lists both questions with their locked answers.
+ const settled = page.locator('[data-clarify-settled]')
+ await settled.waitFor({ state: 'visible', timeout: 30_000 })
+ await expect(settled.getByText(BATCH_CLARIFY_QUESTIONS[0].question)).toBeVisible()
+ await expect(settled.getByText('Coffee', { exact: true })).toBeVisible()
+ await expect(settled.getByText(BATCH_CLARIFY_QUESTIONS[1].question)).toBeVisible()
+ await expect(settled.getByText('Morning', { exact: true })).toBeVisible()
+
+ // And still no duplicate live card lingering after settle.
+ await expect(page.locator('form[data-clarify-batch]')).toHaveCount(0)
+ })
+ })
diff --cc apps/desktop/e2e/bot-mode-closed-chat-stays-closed.spec.ts
index 00000000000,edf39d5515f..2a226c9a1b9
mode 000000,100644..100644
--- a/apps/desktop/e2e/bot-mode-closed-chat-stays-closed.spec.ts
+++ b/apps/desktop/e2e/bot-mode-closed-chat-stays-closed.spec.ts
@@@ -1,0 -1,208 +1,208 @@@
+ import fs from 'node:fs'
+ import path from 'node:path'
+
+ import {
+ buildAppEnv,
+ createSandbox,
+ launchDesktop,
+ type MockBackendFixture,
+ waitForAppReady,
+ writeEnvFile,
+ writeMockProviderConfig
+ } from './fixtures'
-import { MOCK_REPLY, startMockServer } from './mock-server'
++import { MOCK_REPLY, startMockServer } from '../../../tests-js/scripts/mock-server'
+ import { RealSessionBuilder } from './real-session-builder'
+ import { expect, test } from './test'
+
+ // A bot row click is "go to this bot", not "open its Bot Chat". Before the
+ // fix, every click resolved the canonical chat by name and opened it as a tab
+ // again — a Bot Chat the user had closed came back beside every newer thread
+ // on every bot switch, because nothing records a close (the plugin keeps no
+ // closed set; core's tile bucket only forgets). Now a bot whose workspace
+ // already holds tabs comes back to the one the user left; the forever-chat is
+ // re-opened only by the explicit asks (row menu "Open Bot Chat", Bots home
+ // "Open chat").
+
+ type Page = MockBackendFixture['page']
+
+ let fixture: MockBackendFixture | null = null
+
+ async function openBots(page: Page): Promise<void> {
+ const tab = page
+ .getByRole('button', { name: 'Bots', exact: true })
+ .or(page.getByRole('tab', { name: 'Bots', exact: true }))
+ .first()
+
+ await tab.click()
+ await expect(page.getByRole('button', { name: 'New bot or group chat' })).toBeVisible()
+ }
+
+ /** A bot's backend spawns on its first open; give the wake a real chance to
+ * clear before the next gesture races it. Tolerant: the mock backend can
+ * keep a tile's "Waking up…" notice around. */
+ async function settle(page: Page, timeout = 90_000): Promise<void> {
+ await page
+ .getByText(/Waking up/i)
+ .first()
+ .waitFor({ state: 'hidden', timeout })
+ .catch(() => undefined)
+ await page.waitForTimeout(500)
+ }
+
+ /** A first open right after a bot's backend spawned can strand on the
+ * profile socket (a separate, pre-existing reconnect race); a newer click
+ * supersedes it. Retry the gesture like a user would before giving up. */
+ async function openUntil(action: () => Promise<void>, expected: () => Promise<void>, attempts = 3): Promise<void> {
+ for (let attempt = 1; ; attempt += 1) {
+ await action()
+
+ try {
+ await expected()
+
+ return
+ } catch (error) {
+ if (attempt >= attempts) {
+ throw error
+ }
+ }
+ }
+ }
+
+ const SCREENSHOT_DIR = process.env.BOT_MODE_SCREENSHOT_DIR
+
+ async function snap(page: Page, name: string): Promise<void> {
+ if (SCREENSHOT_DIR) {
+ await page.screenshot({ path: `${SCREENSHOT_DIR}/${name}.png` })
+ }
+ }
+
+ /** The session tabs on the main strip (the Bots home tab may sit beside them). */
+ const mainTabs = (page: Page) =>
+ page.evaluate(() =>
+ [...document.querySelectorAll<HTMLElement>('[data-zone-tabstrip="grp-main"] [data-tree-tab]')]
+ .map(element => element.getAttribute('data-tree-tab') ?? '')
+ .filter(id => id.startsWith('session-tile:'))
+ )
+
+ /** Bots are profiles. Seeding one on disk before launch — with the mock
+ * provider so its own backend can answer, and a real, durable "Bot Chat"
+ * row (the plugin's canonical forever-chat, found by exact title) — keeps
+ * in-app creation and the intro turn it fires out of a scenario that is
+ * about the row click. With the row present, the click takes the open-as-
+ * tab path; without it, it would mint the chat into the workspace pane. */
+ async function seedBot(hermesHome: string, mockUrl: string, name: string): Promise<void> {
+ const dir = path.join(hermesHome, 'profiles', name)
+ fs.mkdirSync(dir, { recursive: true })
+ writeMockProviderConfig(dir, mockUrl)
+ writeEnvFile(dir)
+
+ const builder = await RealSessionBuilder.start(dir)
+
+ try {
+ await builder.createSession({ title: 'Bot Chat', turns: [`Hello ${name}`] })
+ } finally {
+ await builder.close()
+ }
+ }
+
+ test.beforeAll(async () => {
+ const mock = await startMockServer()
+ const sandbox = createSandbox('bots')
+ writeMockProviderConfig(sandbox.hermesHome, mock.url)
+ writeEnvFile(sandbox.hermesHome)
+ await seedBot(sandbox.hermesHome, mock.url, 'alpha')
+ await seedBot(sandbox.hermesHome, mock.url, 'beta')
+
+ const { app, page } = await launchDesktop(buildAppEnv(sandbox))
+
+ fixture = {
+ app,
+ page,
+ mock,
+ mockUrl: mock.url,
+ sandbox,
+ cleanup: async () => {
+ await app.close().catch(() => undefined)
+ await mock.close()
+ sandbox.cleanup()
+ }
+ }
+ await waitForAppReady(fixture, 120_000)
+ })
+
+ test.afterAll(async () => {
+ await fixture?.cleanup()
+ fixture = null
+ })
+
+ test('a bot row click returns to the open thread and does not re-open a closed Bot Chat', async () => {
+ test.setTimeout(300_000)
+ const page = fixture!.page
+
+ await openBots(page)
+
+ const alphaRow = page.getByRole('button', { name: /^alpha\b/i }).filter({ visible: true }).first()
+ const betaRow = page.getByRole('button', { name: /^beta\b/i }).filter({ visible: true }).first()
+ await expect(alphaRow).toBeVisible({ timeout: 30_000 })
+ await expect(betaRow).toBeVisible({ timeout: 30_000 })
+ const botChatTab = page.getByRole('tab', { name: /Bot Chat/ }).filter({ visible: true })
+
+ // The first click on a bot with nothing open lands on its canonical chat.
+ await openUntil(
+ () => alphaRow.click(),
+ () => expect(botChatTab.first()).toBeVisible({ timeout: 45_000 })
+ )
+ await settle(page, 15_000)
+ await snap(page, '01-first-click-opens-bot-chat')
+
+ // Close it, then start a fresh thread for Alpha (⌘/Ctrl+T — the strip's
+ // "+" leaves with the zone's last tab).
+ await botChatTab.first().hover()
+ await botChatTab.first().getByRole('button', { name: 'Close' }).click({ force: true })
+ await expect(botChatTab).toHaveCount(0)
+
+ await page.keyboard.press('Control+t')
+ const composer = page.locator('[data-slot="composer-root"] [contenteditable="true"]').filter({ visible: true }).first()
+ await expect(composer).toBeVisible({ timeout: 15_000 })
+ await composer.click()
+ await composer.fill('hello alpha thread')
+ await page.keyboard.press('Enter')
+ await expect(page.getByText('hello alpha thread').filter({ visible: true }).first()).toBeVisible({ timeout: 15_000 })
+ // The reply also becomes the tab's (clipped) title — match the visible copy.
+ await expect(page.getByText(MOCK_REPLY).filter({ visible: true }).first()).toBeVisible({ timeout: 60_000 })
+ await snap(page, '02-closed-bot-chat-new-thread')
+
+ const threadTabs = await mainTabs(page)
+ expect(threadTabs).toHaveLength(1)
+ const [threadTab] = threadTabs
+ expect(threadTab).toMatch(/^session-tile:/)
+
+ // Switch to Beta: Alpha's thread leaves the strip (scoped away, not closed).
+ await betaRow.click()
+ await expect(page.locator(`[data-zone-tabstrip="grp-main"] [data-tree-tab="${threadTab}"]`)).toHaveCount(0, {
+ timeout: 60_000
+ })
+ await settle(page)
+
+ // Back to Alpha: the thread is fronted, and the closed Bot Chat STAYS closed.
+ await alphaRow.click()
+ const threadTabLocator = page.locator(`[data-zone-tabstrip="grp-main"] [data-tree-tab="${threadTab}"]`)
+ await expect(threadTabLocator).toBeVisible({ timeout: 30_000 })
+ await expect(threadTabLocator).toHaveAttribute('aria-selected', 'true')
+ await page.waitForTimeout(3000)
+ await expect(botChatTab).toHaveCount(0)
+ expect(await mainTabs(page)).toEqual([threadTab])
+ await snap(page, '03-back-to-alpha-bot-chat-stays-closed')
+
+ // The explicit ask still opens the forever-chat, beside the thread.
+ await openUntil(
+ async () => {
+ await alphaRow.click({ button: 'right' })
+ await page.getByRole('menuitem', { name: 'Open Bot Chat' }).click()
+ },
+ () => expect(botChatTab.first()).toBeVisible({ timeout: 45_000 })
+ )
+ expect(await mainTabs(page)).toHaveLength(2)
+ expect(await mainTabs(page)).toContain(threadTab)
+ await snap(page, '04-explicit-open-bot-chat')
+ })
diff --cc apps/desktop/e2e/fixtures.ts
index 69ba0914e5e,5e2774b2c0f..2d177478e68
--- a/apps/desktop/e2e/fixtures.ts
+++ b/apps/desktop/e2e/fixtures.ts
@@@ -27,7 -26,8 +26,8 @@@ import * as path from 'node:path
import { _electron, type ElectronApplication, type Page } from '@playwright/test'
+ import { resolveElectronBinary } from './electron-binary'
-import { startMockServer, type MockServerOptions } from './mock-server'
+import { startMockServer, type MockServerOptions } from '../../../tests-js/scripts/mock-server'
import { installErrorBannerGuard } from './test'
const DESKTOP_ROOT = path.resolve(import.meta.dirname, '..')
diff --cc apps/desktop/e2e/fleet-profile-rail.spec.ts
index 00000000000,c54c619af65..4303b90cd51
mode 000000,100644..100644
--- a/apps/desktop/e2e/fleet-profile-rail.spec.ts
+++ b/apps/desktop/e2e/fleet-profile-rail.spec.ts
@@@ -1,0 -1,360 +1,360 @@@
+ /**
+ * E2E: the fleet profile rail with two registered gateways.
+ *
+ * "This device" is the Electron-managed local backend (mock inference). The
+ * second gateway, "Homelab", is a REAL second `hermes serve` this spec spawns
+ * with its own HERMES_HOME, profiles and session token, registered in the v2
+ * connections.json as a remote URL connection. A click on an at-rest square
+ * therefore performs the same dial → commit → re-home the statusbar switcher
+ * does, against a real backend — not a stub.
+ *
+ * Prerequisite: `npm run build` must have been run so dist/ exists, and the
+ * repo's Python venv (`.venv`) must exist for both backends.
+ */
+
+ import { type ChildProcess, spawn, spawnSync } from 'node:child_process'
+ import * as fs from 'node:fs'
+ import * as net from 'node:net'
+ import * as path from 'node:path'
+
+ import {
+ buildAppEnv,
+ createSandbox,
+ launchDesktop,
+ type MockBackendFixture,
+ type Sandbox,
+ waitForAppReady,
+ writeEnvFile,
+ writeMockProviderConfig,
+ } from './fixtures'
-import { startMockServer } from './mock-server'
++import { startMockServer } from '../../../tests-js/scripts/mock-server'
+ import { type ElectronApplication, expect, type Page, test } from './test'
+
+ const DESKTOP_ROOT = path.resolve(import.meta.dirname, '..')
+ const REPO_ROOT = path.resolve(DESKTOP_ROOT, '..', '..')
+
+ const REMOTE_LABEL = 'Homelab'
+ const REMOTE_ID = 'homelab'
+ const REMOTE_TOKEN = 'e2e-fleet-homelab-token'
+
+ interface RemoteGateway {
+ url: string
+ home: string
+ close: () => Promise<void>
+ }
+
+ function findHermesBinary(): string {
+ const venv = path.join(REPO_ROOT, '.venv', 'bin', 'hermes')
+
+ if (fs.existsSync(venv)) {
+ return venv
+ }
+
+ const result = spawnSync('which', ['hermes'], { encoding: 'utf8' })
+
+ if (result.status === 0 && result.stdout.trim()) {
+ return result.stdout.trim()
+ }
+
+ throw new Error('hermes binary not found: create the repo venv (uv sync) or put hermes on PATH')
+ }
+
+ async function freePort(): Promise<number> {
+ return new Promise((resolve, reject) => {
+ const server = net.createServer()
+ server.unref()
+ server.on('error', reject)
+ server.listen(0, '127.0.0.1', () => {
+ const { port } = server.address() as net.AddressInfo
+ server.close(() => resolve(port))
+ })
+ })
+ }
+
+ /** Seed `<home>/profiles/<name>/` so the backend's /api/profiles lists it. */
+ function seedProfiles(home: string, names: string[]): void {
+ for (const name of names) {
+ const dir = path.join(home, 'profiles', name)
+ fs.mkdirSync(dir, { recursive: true })
+ fs.writeFileSync(path.join(dir, 'config.yaml'), '', 'utf8')
+ }
+ }
+
+ /**
+ * Spawn a second, fully real `hermes serve` as the remote gateway. Its
+ * session token is pinned through HERMES_DASHBOARD_SESSION_TOKEN so the
+ * registry entry can carry a plaintext token envelope.
+ */
+ async function startRemoteGateway(root: string, mockUrl: string, profiles: string[]): Promise<RemoteGateway> {
+ const home = path.join(root, 'homelab-home')
+ fs.mkdirSync(home, { recursive: true })
+ writeMockProviderConfig(home, mockUrl)
+ writeEnvFile(home)
+ seedProfiles(home, profiles)
+
+ const port = await freePort()
+ const url = `http://127.0.0.1:${port}`
+
+ const child: ChildProcess = spawn(
+ findHermesBinary(),
+ ['serve', '--host', '127.0.0.1', '--port', String(port), '--skip-build'],
+ {
+ cwd: REPO_ROOT,
+ detached: true,
+ env: {
+ ...process.env,
+ HERMES_HOME: home,
+ HERMES_DASHBOARD_SESSION_TOKEN: REMOTE_TOKEN,
+ },
+ stdio: ['ignore', 'pipe', 'pipe'],
+ },
+ )
+
+ let log = ''
+ child.stdout?.on('data', (chunk: Buffer) => {
+ log += chunk.toString()
+ })
+ child.stderr?.on('data', (chunk: Buffer) => {
+ log += chunk.toString()
+ })
+
+ const deadline = Date.now() + 90_000
+
+ while (Date.now() < deadline) {
+ if (child.exitCode !== null) {
+ throw new Error(`remote hermes serve exited early (${child.exitCode}):\n${log}`)
+ }
+
+ try {
+ const response = await fetch(`${url}/api/status`, {
+ headers: { 'X-Hermes-Session-Token': REMOTE_TOKEN },
+ })
+
+ if (response.ok) {
+ break
+ }
+ } catch {
+ // not up yet
+ }
+
+ await new Promise(resolve => setTimeout(resolve, 500))
+ }
+
+ if (Date.now() >= deadline) {
+ throw new Error(`remote hermes serve never became ready:\n${log}`)
+ }
+
+ return {
+ url,
+ home,
+ close: async () => {
+ if (child.pid && child.exitCode === null) {
+ try {
+ process.kill(-child.pid, 'SIGTERM')
+ } catch {
+ child.kill('SIGTERM')
+ }
+ }
+
+ await new Promise(resolve => setTimeout(resolve, 500))
+ },
+ }
+ }
+
+ function writeConnectionsRegistry(sandbox: Sandbox, remoteUrl: string): void {
+ fs.writeFileSync(
+ path.join(sandbox.userDataDir, 'connections.json'),
+ JSON.stringify(
+ {
+ version: 2,
+ primary: 'local',
+ launchMode: 'primary',
+ lastUsed: 'local',
+ connections: [
+ { id: 'local', kind: 'local', label: 'This device' },
+ {
+ id: REMOTE_ID,
+ kind: 'remote',
+ label: REMOTE_LABEL,
+ url: remoteUrl,
+ authMode: 'token',
+ token: { encoding: 'plain', value: REMOTE_TOKEN },
+ },
+ ],
+ },
+ null,
+ 2,
+ ),
+ { encoding: 'utf8', mode: 0o600 },
+ )
+ }
+
+ // FLEET_RAIL_SCREENSHOT_DIR=<dir> saves full-window captures at the key
+ // states — handy for design review; never part of the assertions.
+ async function capture(page: Page, name: string): Promise<void> {
+ const dir = process.env.FLEET_RAIL_SCREENSHOT_DIR
+
+ if (!dir) {
+ return
+ }
+
+ fs.mkdirSync(dir, { recursive: true })
+ await page.screenshot({ path: path.join(dir, `${name}.png`) })
+ }
+
+ const rail = (page: Page) => page.locator('[data-slot="profile-rail"]')
+ const gatewayGroup = (page: Page, id: string) => rail(page).locator(`[data-slot="profile-rail-gateway"][data-connection-id="${id}"]`)
+ const activeGatewayLabel = (page: Page) => page.getByRole('button', { name: /^Registered gateways: / })
+
+ async function groupOrder(page: Page): Promise<Array<[string, boolean]>> {
+ return rail(page).locator('[data-slot="profile-rail-gateway"]').evaluateAll(nodes =>
+ nodes.map(node => [node.getAttribute('data-connection-id') ?? '', node.getAttribute('data-active') === 'true'] as [string, boolean]),
+ )
+ }
+
+ test.describe('fleet profile rail — two registered gateways', () => {
+ test.describe.configure({ mode: 'serial' })
+
+ let mock: Awaited<ReturnType<typeof startMockServer>>
+ let sandbox: Sandbox
+ let remote: RemoteGateway
+ let app: ElectronApplication
+ let page: Page
+
+ test.beforeAll(async () => {
+ test.setTimeout(240_000)
+ mock = await startMockServer()
+ sandbox = createSandbox('fleet')
+ writeMockProviderConfig(sandbox.hermesHome, mock.url)
+ writeEnvFile(sandbox.hermesHome)
+ // A named profile on This device too, so the active group has a square
+ // beside its home pill. "research" exists on BOTH gateways on purpose: the
+ // rail must keep the two apart by gateway, never by name alone.
+ seedProfiles(sandbox.hermesHome, ['research'])
+
+ remote = await startRemoteGateway(sandbox.root, mock.url, ['inbox', 'research'])
+ writeConnectionsRegistry(sandbox, remote.url)
+
+ ;({ app, page } = await launchDesktop(buildAppEnv(sandbox)))
+ await waitForAppReady({ app, page } as MockBackendFixture, 120_000)
+ // Let boot settle fully (the gateway health item reports "ready" once the
+ // primary socket is open) so the boot-time launch-mode restore has run
+ // before any click — the rail must then hold whatever the user picks.
+ await expect(page.locator('[data-slot="statusbar"]').getByText('ready', { exact: true })).toBeVisible({ timeout: 120_000 })
+ await page.waitForTimeout(2_000)
+ })
+
+ test.afterAll(async () => {
+ await app?.close().catch(() => undefined)
+ await remote?.close()
+ await mock?.close()
+ sandbox?.cleanup()
+ })
+
+ test('lays both gateways on one strip, active gateway in its registry slot', async () => {
+ // The statusbar readout names the gateway the workspace is on.
+ await expect(activeGatewayLabel(page)).toHaveAttribute('aria-label', 'Registered gateways: This device', { timeout: 60_000 })
+
+ // The remote gateway's group appears once the roster has enumerated it.
+ const homelab = gatewayGroup(page, REMOTE_ID)
+ await expect(homelab).toBeVisible({ timeout: 60_000 })
+ await expect(homelab.getByRole('button', { name: `default · ${REMOTE_LABEL}` })).toBeVisible()
+ await expect(homelab.getByRole('button', { name: `inbox · ${REMOTE_LABEL}` })).toBeVisible()
+ await expect(homelab.getByRole('button', { name: `research · ${REMOTE_LABEL}` })).toBeVisible()
+ await expect(homelab).toHaveAttribute('data-reachable', 'true')
+
+ // Its marker carries the remote (network) glyph.
+ await expect(
+ rail(page).locator(`[data-slot="profile-rail-divider"][data-connection-id="${REMOTE_ID}"] [data-connection-kind="remote"]`),
+ ).toBeVisible()
+
+ // This device is the active group: its squares are unqualified, as before.
+ const local = gatewayGroup(page, 'local')
+ await expect(local).toHaveAttribute('data-active', 'true')
+ await expect(local.getByRole('button', { name: 'research', exact: true })).toBeVisible()
+
+ // Registry order: This device first, Homelab second.
+ expect(await groupOrder(page)).toEqual([
+ ['local', true],
+ [REMOTE_ID, false],
+ ])
+
+ // Fleet pill replaces the default↔all toggle; the single-gateway plug is gone.
+ await expect(rail(page).getByRole('button', { name: 'All profiles on this gateway' })).toBeVisible()
+ await expect(rail(page).getByRole('button', { name: 'Manage gateways…' })).toHaveCount(0)
+
+ await gatewayGroup(page, REMOTE_ID).getByRole('button', { name: `inbox · ${REMOTE_LABEL}` }).hover()
+ await capture(page, '1-on-this-device-hover-inbox-homelab')
+ })
+
+ test('clicking an at-rest square re-homes onto that exact gateway and profile', async () => {
+ test.setTimeout(180_000)
+ await gatewayGroup(page, REMOTE_ID).getByRole('button', { name: `inbox · ${REMOTE_LABEL}` }).click()
+
+ // The workspace follows the agent: statusbar readout flips to Homelab…
+ await expect(activeGatewayLabel(page)).toHaveAttribute('aria-label', `Registered gateways: ${REMOTE_LABEL}`, { timeout: 120_000 })
+
+ // …Homelab's group is now the active one, on the clicked profile…
+ const homelab = gatewayGroup(page, REMOTE_ID)
+ await expect(homelab).toHaveAttribute('data-active', 'true', { timeout: 30_000 })
+ await expect(homelab.getByRole('button', { name: 'inbox', exact: true })).toHaveAttribute('aria-pressed', 'true', { timeout: 30_000 })
+
+ // …This device is at rest with qualified squares…
+ const local = gatewayGroup(page, 'local')
+ await expect(local).toHaveAttribute('data-active', 'false')
+ await expect(local.getByRole('button', { name: 'research · This device' })).toBeVisible()
+
+ // …and nothing moved: the order is still This device, then Homelab.
+ expect(await groupOrder(page)).toEqual([
+ ['local', false],
+ [REMOTE_ID, true],
+ ])
+
+ await capture(page, '2-re-homed-on-homelab-inbox')
+ })
+
+ test('an at-rest square offers gateway-scoped actions, never the legacy remote override', async () => {
+ const square = gatewayGroup(page, 'local').getByRole('button', { name: 'research · This device' })
+ await square.click({ button: 'right' })
+
+ const menu = page.getByRole('menu', { name: 'Actions' })
+ await expect(menu).toBeVisible()
+ await expect(menu.getByRole('menuitem', { name: 'Switch to research on This device' })).toBeVisible()
+ await expect(menu.getByRole('menuitem', { name: 'Rename…' })).toBeVisible()
+ await expect(menu.getByRole('menuitem', { name: 'Edit SOUL.md…' })).toBeVisible()
+ await expect(menu.getByRole('menuitem', { name: 'Delete' })).toBeVisible()
+ await expect(menu.getByRole('menuitem', { name: 'Connect to a remote host…' })).toHaveCount(0)
+
+ await capture(page, '3-at-rest-square-context-menu')
+ await page.keyboard.press('Escape')
+ await expect(menu).toBeHidden()
+ })
+
+ test('editing SOUL.md on an at-rest square reads the owning gateway, not the foreground one', async () => {
+ const square = gatewayGroup(page, 'local').getByRole('button', { name: 'research · This device' })
+ await square.click({ button: 'right' })
+ await page.getByRole('menu', { name: 'Actions' }).getByRole('menuitem', { name: 'Edit SOUL.md…' }).click()
+
+ const dialog = page.getByRole('dialog')
+ await expect(dialog).toBeVisible()
+ await expect(dialog.getByText('research · This device · SOUL.md')).toBeVisible()
+ await page.keyboard.press('Escape')
+ await expect(dialog).toBeHidden()
+ })
+
+ test('switching back lands on the clicked profile of This device and keeps the order', async () => {
+ test.setTimeout(180_000)
+ await gatewayGroup(page, 'local').getByRole('button', { name: 'research · This device' }).click()
+
+ await expect(activeGatewayLabel(page)).toHaveAttribute('aria-label', 'Registered gateways: This device', { timeout: 120_000 })
+ const local = gatewayGroup(page, 'local')
+ await expect(local).toHaveAttribute('data-active', 'true', { timeout: 30_000 })
+ await expect(local.getByRole('button', { name: 'research', exact: true })).toHaveAttribute('aria-pressed', 'true', { timeout: 30_000 })
+ await expect(gatewayGroup(page, REMOTE_ID).getByRole('button', { name: `inbox · ${REMOTE_LABEL}` })).toBeVisible()
+
+ expect(await groupOrder(page)).toEqual([
+ ['local', true],
+ [REMOTE_ID, false],
+ ])
+ })
+ })
diff --cc apps/desktop/e2e/task-panel-clearance.spec.ts
index 00000000000,19cf8d9541e..e6bcf6eb064
mode 000000,100644..100644
--- a/apps/desktop/e2e/task-panel-clearance.spec.ts
+++ b/apps/desktop/e2e/task-panel-clearance.spec.ts
@@@ -1,0 -1,145 +1,145 @@@
+ /**
+ * Regression coverage for returning to a working session as its task panel
+ * expands. The transcript must reconcile to the composer's full measured
+ * height without needing a manual scroll to repair the position.
+ */
+
+ import { expect, test, type Page } from './test'
+
+ import { type MockBackendFixture, setupMockBackend, waitForAppReady } from './fixtures'
-import { TASK_PANEL_RESUME_TRIGGER } from './mock-server'
++import { TASK_PANEL_RESUME_TRIGGER } from '../../../tests-js/scripts/mock-server'
+
+ const SURFACE = '[data-composer-target]:visible'
+ const PROMPT = `${TASK_PANEL_RESUME_TRIGGER}: keep the task panel expanded while this session is reopened.`
+
+ function activeSurface(page: Page) {
+ return page.locator(SURFACE).last()
+ }
+
+ async function send(page: Page, text: string): Promise<void> {
+ const composer = activeSurface(page).locator('[contenteditable="true"]').first()
+
+ await composer.waitFor({ state: 'visible', timeout: 15_000 })
+ await composer.click()
+ await composer.type(text, { delay: 5 })
+ await page.keyboard.press('Enter')
+ }
+
+ async function openFreshDraft(page: Page): Promise<void> {
+ await page.locator('[data-slot="sidebar"] button[aria-label="New session"]').first().click()
+ await expect(activeSurface(page).locator('[data-slot="aui_thread-viewport"]')).not.toContainText(PROMPT)
+ await page.waitForTimeout(1_000)
+ }
+
+ async function reopenWorkingSession(page: Page): Promise<void> {
+ const sidebar = page.locator('[data-slot="sidebar"]')
+ const row = sidebar.getByRole('button', { name: /^(?:Session running|Needs your input|Working)\b/ }).first()
+
+ await row.waitFor({ state: 'visible', timeout: 30_000 })
+ await row.click()
+ await expect(activeSurface(page).locator('[data-slot="aui_thread-viewport"]')).toContainText(
+ 'Task-panel clearance line 24',
+ { timeout: 30_000 },
+ )
+ }
+
+ interface ClearanceMetrics {
+ composerHeight: number
+ distanceFromBottom: number
+ latestMessageBottom: number
+ statusPanelTop: number
+ viewportHeight: number
+ }
+
+ async function clearanceMetrics(page: Page): Promise<ClearanceMetrics> {
+ return activeSurface(page).evaluate(surface => {
+ const chatSurface = surface.closest<HTMLElement>('[data-chat-surface]')!
+ const viewport = surface.querySelector<HTMLElement>('[data-slot="aui_thread-viewport"]')!
+ const latest = Array.from(surface.querySelectorAll<HTMLElement>('[data-role="assistant"]')).at(-1)!
+ const status = surface.querySelector<HTMLElement>('[data-slot="composer-status-stack"]')!
+ const styles = getComputedStyle(chatSurface)
+
+ return {
+ composerHeight: Number.parseFloat(styles.getPropertyValue('--composer-measured-height')),
+ distanceFromBottom: viewport.scrollHeight - viewport.clientHeight - viewport.scrollTop,
+ latestMessageBottom: latest.getBoundingClientRect().bottom,
+ statusPanelTop: status.getBoundingClientRect().top,
+ viewportHeight: viewport.clientHeight,
+ }
+ })
+ }
+
+ test.describe('working-session task-panel clearance', () => {
+ let fixture: MockBackendFixture | null = null
+
+ test.beforeEach(async () => {
+ fixture = await setupMockBackend({
+ mockServer: { holdFirstCompletionContaining: TASK_PANEL_RESUME_TRIGGER },
+ })
+ await waitForAppReady(fixture, 120_000)
+ })
+
+ test.afterEach(async () => {
+ await fixture?.cleanup()
+ fixture = null
+ })
+
+ test('window focus reanchors a working session above the expanded task panel', async ({}, testInfo) => {
+ const page = fixture!.page
+
+ await send(page, PROMPT)
+ await fixture!.mock.waitForHeldCompletion()
+ await openFreshDraft(page)
+
+ // Re-open while the long response is still streaming. Its todo call lands
+ // afterward, so the already-visible composer grows only after the initial
+ // session-load scroll settle has finished.
+ fixture!.mock.releaseHeldStream()
+ await page.waitForTimeout(1_000)
+ await reopenWorkingSession(page)
+ await expect(activeSurface(page).getByText('Tasks 1/5')).toBeVisible({ timeout: 30_000 })
+
+ // Reproduce the stale geometry at the foreground boundary. Active turns
+ // disable Chromium's background throttling, so visibility can stay `visible`
+ // and window focus is the only foreground edge that can repair it.
+ await page.waitForTimeout(750)
+ const staleState = await activeSurface(page)
+ .locator('[data-slot="aui_thread-viewport"]')
+ .evaluate(viewport => {
+ // Grow scrollHeight before the observed thread-content node. This
+ // shifts the transcript behind the dock without resizing the observed
+ // node or synthesizing a user scroll (which must escape the lock).
+ const staleClearance = document.createElement('div')
+ staleClearance.style.height = '160px'
+ staleClearance.setAttribute('aria-hidden', 'true')
+ viewport.prepend(staleClearance)
+
+ const distance = viewport.scrollHeight - viewport.clientHeight - viewport.scrollTop
+ const surface = viewport.closest<HTMLElement>('[data-composer-target]')!
+ const latest = Array.from(surface.querySelectorAll<HTMLElement>('[data-role="assistant"]')).at(-1)!
+ const status = surface.querySelector<HTMLElement>('[data-slot="composer-status-stack"]')!
+
+ window.dispatchEvent(new Event('focus'))
+
+ return {
+ distance,
+ following: viewport.dataset.following,
+ latestMessageBottom: latest.getBoundingClientRect().bottom,
+ statusPanelTop: status.getBoundingClientRect().top,
+ visibility: document.visibilityState,
+ }
+ })
+
+ expect(staleState.visibility, JSON.stringify(staleState)).toBe('visible')
+ expect(staleState.following, JSON.stringify(staleState)).toBe('true')
+ expect(staleState.distance).toBeGreaterThan(100)
+ expect(staleState.latestMessageBottom, JSON.stringify(staleState)).toBeGreaterThan(staleState.statusPanelTop)
+ await page.waitForTimeout(1_000)
+ const metrics = await clearanceMetrics(page)
+ await page.screenshot({ path: testInfo.outputPath('task-panel-after-resume.png') })
+
+ expect(metrics.composerHeight, JSON.stringify(metrics)).toBeGreaterThanOrEqual(190)
+ expect(metrics.distanceFromBottom, JSON.stringify(metrics)).toBeLessThan(staleState.distance / 2)
+ expect(metrics.latestMessageBottom, JSON.stringify(metrics)).toBeLessThanOrEqual(metrics.statusPanelTop)
+ })
+ })
diff --cc apps/desktop/e2e/unread-dot-restart.spec.ts
index 00000000000,9ef8c3d9e23..0d4525580c8
mode 000000,100644..100644
--- a/apps/desktop/e2e/unread-dot-restart.spec.ts
+++ b/apps/desktop/e2e/unread-dot-restart.spec.ts
@@@ -1,0 -1,162 +1,162 @@@
+ /**
+ * E2E test for PERSISTED unread state — the green "Finished — unread" dot
+ * must survive an app restart.
+ *
+ * Regression coverage for the reset-on-restart bug: the unread flag used to
+ * live only in the in-memory `$unreadFinishedSessionIds` atom, so closing and
+ * reopening the desktop app grayed out every green dot. The persisted layer
+ * (src/store/session-unread.ts) now rebuilds the dot from localStorage-backed
+ * finish markers + seen-count watermarks.
+ *
+ * The scenario uses TWO sessions on purpose: with a single session the app
+ * can reopen straight into it after a restart, which acks the session (the
+ * user is looking at it) and would mask the dot. Session A finishes in the
+ * background while session B is the selected one; the restart reopens into
+ * B, so A's dot is observable.
+ *
+ * 1. Session A: start a turn, hold its stream open.
+ * 2. Session B: new session, send a message, let it finish while SELECTED.
+ * 3. Release A's stream → its background finish paints A's green dot.
+ * 4. QUIT the app, relaunch on the SAME sandbox → A's dot must still be
+ * there (previously it was lost).
+ * 5. Open session A → dot clears.
+ * 6. Restart once more → the cleared state must persist too (no zombie dot).
+ *
+ * Prerequisite: `npm run build` must have been run so dist/ exists.
+ */
+
+ import { expect, type Page, test } from '@playwright/test'
+ import { type ElectronApplication } from '@playwright/test'
+
+ import {
+ buildAppEnv,
+ launchDesktop,
+ type MockBackendFixture,
+ setupMockBackend,
+ waitForAppReady,
+ } from './fixtures'
-import { restartMockServer } from './mock-server'
++import { restartMockServer } from '../../../tests-js/scripts/mock-server'
+
+ /** Finished-unread dot aria-label (from i18n en.ts). */
+ const UNREAD_DOT_LABEL = 'Finished — unread'
+
+ /** Held prompt — the mock pauses this stream until we release it, so the
+ * turn is deterministically still running when we switch away. */
+ const HELD_PROMPT = 'E2E unread restart: hold this stream until released.'
+ /** Second session's prompt — completes normally while selected. */
+ const SECOND_PROMPT = 'E2E unread restart: second session, read while open.'
+
+ const unreadDots = (page: Page) => page.locator(`[aria-label="${UNREAD_DOT_LABEL}"]`)
+
+ async function sendMessage(page: Page, text: string): Promise<void> {
+ const composer = page.locator('[contenteditable="true"]').first()
+ await composer.waitFor({ state: 'visible', timeout: 15_000 })
+ await composer.click()
+ await composer.type(text, { delay: 5 })
+ await page.keyboard.press('Enter')
+ }
+
+ test.describe('unread dot survives app restart', () => {
+ test.describe.configure({ mode: 'serial' })
+ // Three full app boots in one scenario — give it more than the global 90s.
+ test.setTimeout(300_000)
+
+ let fixture: MockBackendFixture
+ let app: ElectronApplication
+ let page: Page
+
+ test.beforeAll(async () => {
+ restartMockServer()
+ fixture = await setupMockBackend({
+ mockServer: { holdFirstStreamForPrompt: HELD_PROMPT },
+ })
+ app = fixture.app
+ page = fixture.page
+ await waitForAppReady(fixture, 120_000)
+ })
+
+ test.afterAll(async () => {
+ // The fixture's own app handle may already be closed by the restart
+ // steps — close whatever is current, then drop the sandbox + mock.
+ try {
+ await app?.close()
+ } catch {
+ // already closed
+ }
+
+ fixture?.mock.close()
+ fixture?.sandbox.cleanup()
+ })
+
+ /** Relaunch the desktop app against the SAME sandbox (same userData →
+ * same localStorage, same HERMES_HOME → same session store). */
+ async function restartApp(): Promise<void> {
+ await app.close()
+
+ const relaunched = await launchDesktop(buildAppEnv(fixture.sandbox))
+ app = relaunched.app
+ page = relaunched.page
+ await waitForAppReady({ ...fixture, app, page }, 120_000)
+ }
+
+ test('green dot persists across restart and its clear persists too', async () => {
+ // ── 1. Session A: start a turn whose stream the mock holds open ────
+ await sendMessage(page, HELD_PROMPT)
+ await fixture.mock.waitForHeldStream()
+
+ // ── 2. Session B: complete a turn while SELECTED (stays read) ──────
+ await page.locator('button:has-text("New session")').first().click()
+ await sendMessage(page, SECOND_PROMPT)
+
+ // B's reply lands in the open transcript — this session is "read".
+ await page.waitForFunction(
+ () => (document.body.textContent ?? '').includes('Hello from the mock inference server'),
+ undefined,
+ { timeout: 30_000 },
+ )
+
+ // ── 3. Release A's stream → background finish paints A's dot ──────
+ fixture.mock.releaseHeldStream()
+
+ await expect
+ .poll(() => unreadDots(page).count(), {
+ timeout: 30_000,
+ message: 'green unread dot should appear after the background finish',
+ })
+ .toBeGreaterThan(0)
+
+ // ── 4. Restart the app — the dot must survive ──────────────────────
+ // The app reopens into session B (or a fresh draft), NOT session A, so
+ // A's dot is observable rather than being acked by the route restore.
+ await restartApp()
+
+ await expect
+ .poll(() => unreadDots(page).count(), {
+ timeout: 60_000,
+ message: 'green unread dot should be rebuilt from persisted state after restart',
+ })
+ .toBeGreaterThan(0)
+
+ // ── 5. Open session A — the dot clears ─────────────────────────────
+ // The dot sits inside A's sidebar row button; click that row.
+ await unreadDots(page)
+ .first()
+ .locator('xpath=ancestor::button[1]')
+ .click()
+
+ await expect
+ .poll(() => unreadDots(page).count(), {
+ timeout: 15_000,
+ message: 'opening the session should clear its unread dot',
+ })
+ .toBe(0)
+
+ // ── 6. Restart again — the CLEARED state must persist as well ──────
+ await restartApp()
+
+ // Give the sidebar a moment to load rows, then assert no dot returns.
+ await page.waitForSelector('[data-slot="sidebar"]', { timeout: 60_000 })
+ await page.waitForTimeout(5_000)
+ expect(await unreadDots(page).count(), 'acked session must stay read after restart').toBe(0)
+ })
+ })