Skip to content

The agent that grows with you

test: purge low-value tests, lane js01 (202 removed)

teknium1a4f93ce250ce
diff --git a/apps/desktop/e2e/archived-hidden-session-recoverable.spec.ts b/apps/desktop/e2e/archived-hidden-session-recoverable.spec.ts
deleted file mode 100644
index b91c8b9d034..00000000000
--- a/apps/desktop/e2e/archived-hidden-session-recoverable.spec.ts
+++ /dev/null
@@ -1,132 +0,0 @@
-/**
- * E2E regression: an archived session stays reachable from Settings → Sessions
- * even when it is also `hidden` (Bot Mode marks its sessions hidden).
- *
- * The archived view is the only recovery surface for rows that dropped out of
- * the default Sessions list; a row that is both archived AND hidden used to be
- * excluded from it too, so the transcript was unrecoverable from any UI.
- */
-
-import { execFileSync } from 'node:child_process'
-import * as fs from 'node:fs'
-import * as path from 'node:path'
-
-import { startMockServer } from '../../../tests-js/scripts/mock-server'
-
-import {
- buildAppEnv,
- createSandbox,
- launchDesktop,
- type MockBackendFixture,
- waitForAppReady,
- writeEnvFile,
- writeMockProviderConfig,
-} from './fixtures'
-import { expect, test } from './test'
-
-const HIDDEN_ARCHIVED_TEXT = 'E2E_ARCHIVED_HIDDEN_ROW'
-const CONTROL_TEXT = 'E2E_ARCHIVED_VISIBLE_ROW'
-
-const DESKTOP_ROOT = path.resolve(import.meta.dirname, '..')
-const REPO_ROOT = path.resolve(DESKTOP_ROOT, '..', '..')
-const RUNTIME_PYTHON = path.join(REPO_ROOT, 'venv', 'bin', 'python')
-
-/**
- * Seed two durable rows through the real SessionDB (the same code the desktop
- * backend reads): one archived+hidden (the recovery case) and one plain
- * archived control. Direct SessionDB writes keep the seed deterministic under
- * host load; the desktop still reads them through the real `hermes serve`.
- */
-function seedArchivedRows(hermesHome: string, hiddenId: string, controlId: string): void {
- execFileSync(
- RUNTIME_PYTHON,
- [
- '-c',
- [
- 'import sys',
- 'from hermes_state import SessionDB',
- 'hidden_id, control_id, hidden_text, control_text = sys.argv[1:5]',
- 'db = SessionDB()',
- 'for sid, text in ((hidden_id, hidden_text), (control_id, control_text)):',
- ' db.create_session(sid, source="desktop")',
- ' db.append_message(sid, "user", text)',
- ' db.append_message(sid, "assistant", "ok " + text)',
- ' assert db.set_session_archived(sid, True) is True',
- 'assert db.set_session_hidden(hidden_id, True) is True',
- 'rows = {r["id"]: (r["archived"], r["hidden"]) for r in db.list_sessions_rich(include_archived=True, include_hidden=True)}',
- 'db.close()',
- 'assert rows[hidden_id] == (1, 1), rows',
- 'assert rows[control_id] == (1, 0), rows',
- ].join('\n'),
- hiddenId,
- controlId,
- HIDDEN_ARCHIVED_TEXT,
- CONTROL_TEXT,
- ],
- { cwd: REPO_ROOT, env: { ...process.env, HERMES_HOME: hermesHome }, stdio: 'pipe' },
- )
- expect(fs.existsSync(path.join(hermesHome, 'state.db'))).toBe(true)
-}
-
-async function setupSeededMockBackend(): Promise<MockBackendFixture & { controlId: string; hiddenId: string }> {
- const mock = await startMockServer()
- const sandbox = createSandbox('archived-hidden')
- writeMockProviderConfig(sandbox.hermesHome, mock.url)
- writeEnvFile(sandbox.hermesHome)
-
- const hiddenId = '20260916_000001_e2ehid'
- const controlId = '20260916_000002_e2ectl'
- seedArchivedRows(sandbox.hermesHome, hiddenId, controlId)
-
- const { app, page } = await launchDesktop(buildAppEnv(sandbox))
-
- return {
- app,
- page,
- mock,
- mockUrl: mock.url,
- sandbox,
- hiddenId,
- controlId,
- cleanup: async () => {
- await app.close().catch(() => undefined)
- await mock.close()
- sandbox.cleanup()
- },
- }
-}
-
-test.describe('archived + hidden session stays recoverable', () => {
- let fixture: Awaited<ReturnType<typeof setupSeededMockBackend>>
-
- test.beforeAll(async () => {
- fixture = await setupSeededMockBackend()
- await waitForAppReady(fixture)
- })
-
- test.afterAll(async () => {
- await fixture?.cleanup()
- })
-
- test('Settings → Sessions lists the archived+hidden row next to the plain archived row', async () => {
- const { page, hiddenId, controlId } = fixture
-
- // Hidden rows never show in the default Sessions list (unchanged contract).
- await expect(page.getByText(HIDDEN_ARCHIVED_TEXT, { exact: false })).toHaveCount(0)
-
- await page.evaluate(() => {
- window.location.hash = '#/settings?tab=sessions'
- })
-
- const controlRow = page.locator(`#archived-session-${controlId}`)
- await controlRow.waitFor({ state: 'visible', timeout: 60_000 })
-
- const hiddenRow = page.locator(`#archived-session-${hiddenId}`)
- await expect(hiddenRow, 'archived+hidden session must be listed in the archived view').toBeVisible({
- timeout: 15_000,
- })
- await expect(hiddenRow.getByRole('button', { name: /unarchive/i })).toBeVisible()
-
- await page.screenshot({ path: test.info().outputPath('archived-hidden-row.png'), fullPage: false })
- })
-})
diff --git a/apps/desktop/e2e/at-rest-connection-token.spec.ts b/apps/desktop/e2e/at-rest-connection-token.spec.ts
index 8fc8914d48a..2684b421fab 100644
--- a/apps/desktop/e2e/at-rest-connection-token.spec.ts
+++ b/apps/desktop/e2e/at-rest-connection-token.spec.ts
@@ -42,64 +42,20 @@
* separate credential file would break the test while being *more* correct.
* The load-bearing assertion is the raw-bytes absence of the secret.
*
- * Four at-rest paths, hence four tests — three enforced, one a documented gap:
+ * Three at-rest paths, hence three tests:
*
- * 1. A NEWLY configured token (ACTIVE). The app's own write path routes
- * through the strict `encryptDesktopSecret`; this test holds it there
- * against regression, and pins the mode of the file it actually wrote.
- * 2. An EXISTING `connection.json` at the old 0644 (ACTIVE). Covers the
- * read-side tighten, and ONLY the mode — its token is already ciphertext,
- * which is what keeps it independent of the migration test 4 defers.
- * 3. A CORRUPT `connection.json` at 0644 (ACTIVE). The tighten must not be
- * gated on the parse succeeding: a truncated file still holds the token
- * bytes, and the parse failure is swallowed, so nothing would ever come
- * back for it.
- * 4. An EXISTING plaintext `connection.json` (`test.fixme`). Legacy payloads
- * are deliberately NOT migrated yet. The test is kept, disabled, with a
- * precise reason — see the block comment above it.
+ * 1. A NEWLY configured token. The app's own write path routes through the
+ * strict `encryptDesktopSecret`; this test holds it there against
+ * regression, and pins the mode of the file it actually wrote.
+ * 2. An EXISTING `connection.json` at the old 0644. Covers the read-side
+ * tighten, and ONLY the mode — its token is already ciphertext.
+ * 3. A CORRUPT `connection.json` at 0644. The tighten must not be gated on
+ * the parse succeeding: a truncated file still holds the token bytes, and
+ * the parse failure is swallowed, so nothing would ever come back for it.
*
- * ── Correcting the record on test 4 ─────────────────────────────────────
- *
- * An earlier revision of this file asserted that migration and justified it by
- * claiming the first implementation (`d3d177283`) fell back to
- * `{ encoding: 'plain', value }` when `isEncryptionAvailable()` was false.
- * That citation is FALSE for this codebase. What is actually true:
- *
- * git merge-base --is-ancestor d3d1772837a7b0552940b55455ae734c72e0a8f1 HEAD -> 1 (NOT an ancestor)
- * git merge-base --is-ancestor 51c68d4ab1a9e3c62fb1048fccb84144c409f0e7 HEAD -> 0 (IS an ancestor)
- * git log -S 'Fall through to plaintext' upstream/main -- apps/desktop -> (no commits)
- *
- * `d3d177283` exists only on `upstream/bb/gui-mainmerge-tmp`,
- * `brooklyn/gui-installer-prereqs`, and the `desktop-pr20059-installers`
- * pre-release tag. Mainline NEVER shipped a code path that wrote a plaintext
- * gateway token: `51c68d4ab` ("Add Hermes desktop app (#20059)"), the commit
- * that brought the desktop app to mainline, already contained the strict
- * throw ("Secure token storage is unavailable, …") in `hardening.cjs`.
- *
- * One `{ encoding: 'plain', value }` literal does remain on mainline
- * (`electron/main.ts`, in `coerceDesktopConnectionConfig`), but it is
- * unreachable as an at-rest write: it is gated on `persistToken === false`,
- * whose only caller is the connection-TEST handler, which never calls
- * `writeDesktopConnectionConfig`. That token stays in memory for the duration
- * of one probe.
- *
- * So the affected population is not "anyone who configured a gateway before
- * the fix". It is narrow and non-mainline: pre-release `bb/gui` installs
- * (including the `desktop-pr20059-installers` build) plus hand-edited or
- * hand-migrated `connection.json` files. Those files DO still work, because
- * `decryptDesktopSecret` returns any non-safeStorage `value` verbatim on read
- * — the read path is intentionally unchanged, so nobody is signed out. That
- * read-path acceptance, not a mainline writer, is what makes the fixme'd
- * fixture realistic.
- *
- * Migration is DEFERRED, not forgotten. An adversarial review of the
- * migration that briefly lived here returned DO NOT SHIP, having reproduced
- * two token-loss scenarios: it silently reverts and then destroys the opt-in
- * plaintext choice that open upstream PR #62319 deliberately adds; and it
- * converts a portable credential into a keychain-bound one with no consent,
- * destroying the only recoverable copy while not actually remediating the
- * exposure (the plaintext is already in backups, so the real remedy is
- * ROTATION). The prerequisites are enumerated above test 2.
+ * Legacy plaintext `connection.json` payloads are deliberately NOT migrated
+ * yet (blocked on #62319's opt-in marker, writing through the config
+ * sanitizer, and surfacing token-rotation guidance).
*
* Environment limits are encoded rather than papered over. Electron's
* safeStorage is unavailable on Linux with no keyring, which is the shape of
@@ -109,8 +65,7 @@
* conditional: with secure storage the save must succeed, and without it the
* save must fail loudly (which is what the current strict `encryptDesktopSecret`
* does) instead of quietly writing plaintext. See the branch comments in each
- * test for the reasoning, including the one case this spec refuses to invent a
- * policy for.
+ * test for the reasoning.
*
* Prerequisite: `npm run build` must have been run so dist/ exists.
*/
@@ -722,13 +677,10 @@ test.describe('remote gateway session token at rest', () => {
* save would leave the file group/other-readable indefinitely, which is why
* `readDesktopConnectionConfig` tightens on a cache miss.
*
- * Scoped to the MODE, and deliberately independent of the deferred migration
- * below. The fixture's token is already safeStorage ciphertext (the app wrote
- * it), so nothing here re-encrypts anything, touches the #62319 opt-in
- * plaintext marker, or needs rotation guidance — the three prerequisites that
- * keep the next test fixme'd. Tightening a permission bit neither performs a
- * migration nor claims to, so it can be covered now while migration stays
- * deferred.
+ * Scoped to the MODE, and deliberately independent of the deferred legacy
+ * plaintext migration. The fixture's token is already safeStorage ciphertext
+ * (the app wrote it), so nothing here re-encrypts anything. Tightening a
+ * permission bit neither performs a migration nor claims to.
*
* The fixture is produced by the app itself rather than hand-written, so the
* only difference from a real pre-fix install is the one bit under test.
@@ -865,135 +817,4 @@ test.describe('remote gateway session token at rest', () => {
'tightening must not rewrite the file: mtime is the config cache key',
).toBeLessThan(1)
})
-
- /**
- * DEFERRED GAP — legacy plaintext payloads are not migrated.
- *
- * Held as `fixme` rather than deleted: the fixture below is the correct
- * fixture for the population that a migration must eventually cover, and
- * the harness (seed → boot-poll → authoritative re-save → raw-bytes scan →
- * wire check) is the harness such a migration needs. Keeping it typechecked
- * and listed makes the gap visible in `--list` and in every report; deleting
- * it would make the gap invisible and cost the next implementer this setup.
- *
- * It is NOT enabled because the migration it asserted was reviewed
- * DO NOT SHIP. Before this can be un-fixme'd, three prerequisites (see the
- * header, and the matching note in electron/main.ts readDesktopConnectionConfig):
- *
- * 1. Sequence with #62319's opt-in plaintext marker, so a user who
- * deliberately chose plaintext is not silently overridden. This
- * fixture has NO marker, so it stays in scope for migration — but the
- * implementation must be able to tell the two apart.
- * 2. Write through the config sanitizer, not around it.
- * 3. Surface ROTATION guidance. Re-encrypting cannot un-expose a secret
- * that is already in a backup; it only prevents future exposure.
- *
- * Un-fixme'ing this without (1) risks destroying a deliberate user choice,
- * and without (3) it reports a remediation it did not actually perform.
- */
- test('an existing plaintext connection.json is migrated off plaintext and keeps working', async () => {
- test.fixme(
- true,
- 'Deferred: legacy plaintext connection.json is intentionally NOT migrated. ' +
- 'Affected population is pre-release bb/gui installs (incl. the desktop-pr20059-installers build) ' +
- 'plus hand-edited configs — mainline never wrote a plaintext gateway token. ' +
- 'Blocked on: (1) #62319 opt-in-marker coordination, (2) writing through the config sanitizer, ' +
- '(3) surfacing token-rotation guidance. Re-encrypting alone does not remediate an already-backed-up secret.',
- )
-
- const fake = gateway!
- sandbox = createSandbox('at-rest-migrate')
-
- // Seed the file an affected user has on disk. This is live, usable
- // plaintext rather than a strawman, because `decryptDesktopSecret` returns
- // `value` verbatim for any non-safeStorage encoding — the READ path
- // accepts it. Note what does NOT justify this fixture: mainline never
- // WROTE this shape to disk. `coerceDesktopConnectionConfig` does build it,
- // but only under `persistToken: false`, whose sole caller is the
- // connection-test handler, which never persists. The writers were
- // non-mainline pre-release builds and hand edits. There is deliberately no
- // opt-in marker here, so this payload is in scope for a future migration.
- fs.writeFileSync(
- path.join(sandbox.userDataDir, 'connection.json'),
- JSON.stringify(
- {
- mode: 'remote',
- profiles: {},
- remote: {
- authMode: 'token',
- token: { encoding: 'plain', value: SENTINEL_TOKEN },
- url: fake.url,
- },
- },
- null,
- 2,
- ),
- 'utf8',
- )
-
- const launched = await launchAgainst(sandbox)
- app = launched.app
-
- const capability = await readSafeStorageCapability(app)
-
- test.info().annotations.push({
- description: `isEncryptionAvailable=${capability.available} backend=${capability.backend}`,
- type: 'safeStorage',
- })
-
- if (!capability.available) {
- // With no secure storage there is nowhere to migrate the secret TO, and
- // scrubbing it would silently sign the user out of a working gateway.
- // Asserting either outcome here would be inventing policy.
- test.skip(
- true,
- 'secure storage unavailable on this host — the correct migration policy for an existing plaintext file is undecided',
- )
-
- return
- }
-
- const userDataDir = await resolveUserDataDir(app)
- const connectionFile = path.join(userDataDir, 'connection.json')
- const needles = secretNeedles(SENTINEL_TOKEN)
-
- // Two chances, so the test does not depend on WHERE the fix hooks the
- // migration: (a) on read at boot, (b) on the next authoritative write.
- // Poll for (a) first.
- const deadline = Date.now() + 15_000
- let stillPlaintext = true
-
- while (Date.now() < deadline) {
- stillPlaintext = readIfExists(connectionFile).includes(needles[0].bytes)
-
- if (!stillPlaintext) {
- break
- }
-
- await launched.page.waitForTimeout(500)
- }
-
- if (stillPlaintext) {
- // (b) A real save through the app's own surface, carrying no new token —
- // the stored blob is inherited. Re-persisting an inherited secret is the
- // other place plaintext must not survive.
- const resaved = await saveRemoteToken(launched.page, fake.url)
- expect(resaved.error, 'a re-save that inherits the stored token must not fail').toBeNull()
- }
-
- expect(
- scanTreeForSecret(userDataDir, needles),
- 'an existing plaintext gateway token must not remain readable under userData after the app has run ' +
- `(stored token encoding is still "${storedTokenEncoding(connectionFile)}")`,
- ).toEqual([])
-
- // And the migration must not have cost the user their credential.
- const before = fake.sessionTokens.length
- await exerciseStoredToken(launched.page, fake.url)
-
- expect(
- fake.sessionTokens.slice(before),
- 'the migrated token must still reach the gateway unchanged',
- ).toContain(SENTINEL_TOKEN)
- })
})
diff --git a/apps/desktop/e2e/batch-clarify.spec.ts b/apps/desktop/e2e/batch-clarify.spec.ts
index ee4ec732535..a3280642d5f 100644
--- a/apps/desktop/e2e/batch-clarify.spec.ts
+++ b/apps/desktop/e2e/batch-clarify.spec.ts
@@ -60,7 +60,6 @@ test.describe('batch clarify card', () => {
// 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()
diff --git a/apps/desktop/e2e/boot.spec.ts b/apps/desktop/e2e/boot.spec.ts
index 19f2d81fa45..a23a2425490 100644
--- a/apps/desktop/e2e/boot.spec.ts
+++ b/apps/desktop/e2e/boot.spec.ts
@@ -32,24 +32,6 @@ test.afterAll(async () => {
})
test.describe('dev-mode boot with mock backend', () => {
- test('window opens with Hermes title', async () => {
- const title = await fixture!.page.title()
- expect(title).toContain('Hermes')
- })
-
- test('renderer mounts and shows DOM content', async () => {
- const page = fixture!.page
- // Wait for the React root to mount. The app renders into #root
- // (see src/main.tsx), but content may arrive through portals — so
- // check the body for any interactive content instead.
- await page.waitForSelector('body', { state: 'attached' })
- // Wait for the main app shell — the composer is always present.
- await page.waitForSelector('textarea, [contenteditable="true"]', {
- state: 'attached',
- timeout: 30_000,
- })
- })
-
// A preload that throws never reaches contextBridge, so the renderer boots
// into "Desktop IPC bridge is unavailable" and every test below it dies on a
// 120s never-became-ready timeout instead. Checking the bridge by name makes
diff --git a/apps/desktop/e2e/bot-chat-message-agent-friendly-name.spec.ts b/apps/desktop/e2e/bot-chat-message-agent-friendly-name.spec.ts
deleted file mode 100644
index e8f337dab92..00000000000
--- a/apps/desktop/e2e/bot-chat-message-agent-friendly-name.spec.ts
+++ /dev/null
@@ -1,106 +0,0 @@
-import { execFileSync } from 'node:child_process'
-import fs from 'node:fs'
-import path from 'node:path'
-
-import { type MockBackendFixture, setupMockBackend, waitForAppReady, writeEnvFile } from './fixtures'
-import { expect, test } from './test'
-
-/**
- * Bot Mode `message_agent` target resolution, driven from a real Bot Chat.
- *
- * The Desktop autocompletes a bot by its friendly name (Bot Mode title /
- * profile display_name) as an @-slug, while the backend keyed local targets on
- * the profile folder id only. Sending to "Scribe" (folder `writer`) therefore
- * came back "No teammate named 'Scribe'" and nothing reached the writer's Bot
- * Chat (#100671). The mock model emits exactly the tool call the user text
- * scripts (`E2E_CALL(message_agent)[…]`) so the REAL tool runs in the sender's
- * backend and the REAL delivery lands in the recipient profile's state.db.
- */
-
-let fixture: MockBackendFixture | null = null
-
-async function openBots(page: MockBackendFixture['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()
-}
-
-async function createAgent(page: MockBackendFixture['page'], name: string, title: string): Promise<void> {
- await page.getByRole('button', { name: 'New bot or group chat' }).click()
- await page.getByRole('menuitem', { name: 'New Bot' }).click()
-
- const dialog = page.getByRole('dialog', { name: 'New Bot' })
- await dialog.getByPlaceholder('inbox-triage').fill(name)
- await dialog.getByPlaceholder('Inbox Triage').fill(title)
- await dialog.getByRole('button', { name: 'Create Bot' }).click()
- await expect(dialog).toBeHidden({ timeout: 30_000 })
- await expect(page.getByRole('button', { name: new RegExp(`^${title}\\b`) }).first()).toBeVisible({ timeout: 30_000 })
-}
-
-/** A Bot the Desktop never touched: folder `writer`, Bot Mode title "Scribe", its own
- * model — the shape of a bot created on another machine or renamed by hand. */
-function seedWriterProfile(home: string): string {
- const writerHome = path.join(home, 'profiles', 'writer')
- fs.mkdirSync(writerHome, { recursive: true })
- fs.writeFileSync(path.join(writerHome, 'profile.yaml'), 'description: Writes things\nui_meta:\n hermes-bots:\n title: Scribe\n', 'utf8')
- const base = fs.readFileSync(path.join(home, 'config.yaml'), 'utf8')
- fs.writeFileSync(
- path.join(writerHome, 'config.yaml'),
- base.replace('default: mock-model', 'default: mock-model-writer').replace('mock-model: {}', 'mock-model: {}\n mock-model-writer: {}'),
- 'utf8',
- )
- writeEnvFile(writerHome)
-
- return writerHome
-}
-
-function sqlite(dbPath: string, sql: string): string {
- return execFileSync('python3', ['-c', 'import sqlite3,sys; c=sqlite3.connect(f"file:{sys.argv[1]}?mode=ro", uri=True); print("\\n".join(str(r[0]) for r in c.execute(sys.argv[2])))', dbPath, sql], {
- encoding: 'utf8',
- }).trim()
-}
-
-test.beforeAll(async () => {
- fixture = await setupMockBackend()
- seedWriterProfile(fixture.sandbox.hermesHome)
- await waitForAppReady(fixture, 120_000)
-})
-
-test.afterAll(async () => {
- await fixture?.cleanup()
- fixture = null
-})
-
-test('a DM addressed by the friendly name lands in that bot\'s Bot Chat', async () => {
- test.setTimeout(600_000)
- const page = fixture!.page
- const home = fixture!.sandbox.hermesHome
-
- await openBots(page)
- await expect(page.getByRole('button', { name: /^Scribe · @writer\b/ }).first()).toBeVisible({ timeout: 60_000 })
- await createAgent(page, 'sender', 'Sender')
- // The row click opens the sender's canonical Bot Chat into the main workspace
- // (its fresh-chat splash replaces the default profile's welcome pane).
- await page.getByRole('button', { name: /^Sender · @sender\b/ }).filter({ visible: true }).first().click()
- await expect(page.getByText('Say something to get started.').filter({ visible: true })).toBeVisible({ timeout: 120_000 })
- await expect(page.getByText('What are we building?')).toHaveCount(0)
- const composer = page.locator('[data-slot="composer-root"] [contenteditable="true"]').filter({ visible: true })
- await expect(composer).toHaveCount(1, { timeout: 120_000 })
-
- await composer.click()
- await composer.type('E2E_CALL(message_agent)[{"target":"Scribe","message":"codeword-7A91 please ack"}]', { delay: 5 })
- await page.keyboard.press('Enter')
-
- // The tool result the model saw: base answers "No teammate named 'Scribe'".
- await expect(page.getByText(/E2E_CALL_RESULT:/).filter({ visible: true }).first()).toBeVisible({ timeout: 240_000 })
- await expect(page.getByText(/Message dispatched to @writer/).first()).toBeVisible()
- await expect(page.getByText(/No teammate named/)).toHaveCount(0)
- const senderDb = path.join(home, 'profiles', 'sender', 'state.db')
- const toolResult = sqlite(senderDb, "SELECT content FROM messages WHERE role='tool' ORDER BY rowid DESC LIMIT 1")
- expect(toolResult).toContain('"to": "@writer"')
-
- // The recipient turn is a full `hermes -p writer` CLI boot in the background; its
- // landing in writer/state.db is covered by tests/tools (delivery runner) — under a
- // saturated host it can outlast any sane spec budget, so it is not awaited here.
- await page.screenshot({ path: 'test-results/bot-chat-message-agent-friendly-name.png', fullPage: true })
-})
diff --git a/apps/desktop/e2e/bot-mailbox-unreadable-ticket.spec.ts b/apps/desktop/e2e/bot-mailbox-unreadable-ticket.spec.ts
deleted file mode 100644
index 0cb0c79f772..00000000000
--- a/apps/desktop/e2e/bot-mailbox-unreadable-ticket.spec.ts
+++ /dev/null
@@ -1,148 +0,0 @@
-import { execFileSync } from 'node:child_process'
-import fs from 'node:fs'
-import path from 'node:path'
-
-import { MOCK_REPLY, startMockServer } from '../../../tests-js/scripts/mock-server'
-
-import {
- buildAppEnv,
- createSandbox,
- launchDesktop,
- type MockBackendFixture,
- waitForAppReady,
- writeEnvFile,
- writeMockProviderConfig
-} from './fixtures'
-import { RealSessionBuilder } from './real-session-builder'
-import { expect, test } from './test'
-
-// A teammate's `message_agent` DM into a Bot Chat the Desktop holds open travels through the
-// live-owner mailbox (`<profile>/runtime/bot_live_delivery/<id>.json`): the sender admits a
-// ticket, the gateway's idle poller claims it and runs the turn. Both sides bulk-scan the
-// directory, so ONE unreadable ticket (ACL drift, elevated-owner file, AV lock) used to make
-// every sender report `ambiguous` and crash the receiver's poll each cycle — the healthy DM
-// never rendered in the open chat. Regression: the DM must still arrive.
-
-type Page = MockBackendFixture['page']
-
-let fixture: MockBackendFixture | null = null
-
-const REPO_ROOT = path.resolve(import.meta.dirname, '..', '..', '..')
-const PYTHON = process.env.HERMES_E2E_PYTHON ?? path.join(REPO_ROOT, '.venv', 'bin', 'python')
-
-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()
-}
-
-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()
- }
-}
-
-/** Plant one chmod-000 ticket, then admit a real DM through the production mailbox API. */
-function admitDmBesideUnreadableTicket(profileHome: string, message: string): string {
- const script = `
-import json, sys
-from pathlib import Path
-from tools import bot_live_delivery as mailbox
-home = Path(sys.argv[1]); message = sys.argv[2]
-owner = mailbox.find_canonical_live_owner(home)
-if owner is None:
- print(json.dumps({"error": "no live owner advertised for " + str(home)})); raise SystemExit(0)
-root = home / "runtime" / mailbox.DELIVERY_DIR_NAME
-root.mkdir(parents=True, exist_ok=True)
-bad = root / ("e" * 32 + ".json")
-bad.write_text('{"status": "queued"}', encoding="utf-8")
-bad.chmod(0)
-try:
- record = mailbox.deliver_to_live_owner(home, owner, message, author={"id": "bot:beta", "name": "beta", "is_bot": True})
- print(json.dumps({"status": record["status"], "delivery_id": record["delivery_id"]}))
-except Exception as exc:
- print(json.dumps({"error": f"{type(exc).__name__}: {exc}"}))
-`
-
- return execFileSync(PYTHON, ['-c', script, profileHome, message], {
- cwd: REPO_ROOT,
- env: { ...process.env, PYTHONPATH: REPO_ROOT, HERMES_HOME: profileHome },
- encoding: 'utf8'
- }).trim()
-}
-
-test.beforeAll(async () => {
- const mock = await startMockServer()
- const sandbox = createSandbox('bots-mailbox-unreadable')
- writeMockProviderConfig(sandbox.hermesHome, mock.url)
- writeEnvFile(sandbox.hermesHome)
- await seedBot(sandbox.hermesHome, mock.url, 'alpha')
-
- 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 teammate DM still reaches the open Bot Chat when an unreadable ticket sits in the mailbox', async () => {
- test.setTimeout(300_000)
- const page = fixture!.page
- const profileHome = path.join(fixture!.sandbox.hermesHome, 'profiles', 'alpha')
-
- await openBots(page)
- const alphaRow = page.getByRole('button', { name: /^alpha\b/i }).filter({ visible: true }).first()
- await expect(alphaRow).toBeVisible({ timeout: 30_000 })
- await alphaRow.click()
- await expect(page.getByText('Hello alpha', { exact: true }).filter({ visible: true }).first()).toBeVisible({
- timeout: 60_000
- })
-
- // One real Desktop turn first: the lease (and its live-consumer advertisement) is acquired on submit.
- 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('warm up alpha')
- await page.keyboard.press('Enter')
- await expect(page.getByText(MOCK_REPLY).filter({ visible: true }).first()).toBeVisible({ timeout: 60_000 })
-
- const dm = 'Message from 🤖 beta (@beta): PROBE-MAILBOX-DM please ack'
- const admission = JSON.parse(admitDmBesideUnreadableTicket(profileHome, dm)) as { status?: string; error?: string }
- await test.info().attach('admission', { body: JSON.stringify(admission), contentType: 'application/json' })
- expect(admission.error, 'sender admission must not degrade to ambiguous').toBeUndefined()
- expect(admission.status).toBe('queued')
-
- // The gateway poller claims the ticket at the idle boundary and runs it as a real inbound turn;
- // the transcript renders the teammate message as a collapsed inter-agent directive card, so
- // assert on presence in the transcript DOM rather than on visibility of the folded text.
- await expect(page.getByText(/PROBE-MAILBOX-DM/).first()).toBeAttached({ timeout: 90_000 })
- await test.info().attach('bot-chat-after-dm', { body: await page.screenshot(), contentType: 'image/png' })
-})
diff --git a/apps/desktop/e2e/bot-mode-cjk-bot-name.spec.ts b/apps/desktop/e2e/bot-mode-cjk-bot-name.spec.ts
deleted file mode 100644
index d4473a7dc18..00000000000
--- a/apps/desktop/e2e/bot-mode-cjk-bot-name.spec.ts
+++ /dev/null
@@ -1,66 +0,0 @@
-import fs from 'node:fs'
-import path from 'node:path'
-
-import { type MockBackendFixture, setupMockBackend, waitForAppReady } from './fixtures'
-import { expect, test } from './test'
-
-// The New Bot dialog derived the profile id with an ASCII-only slugify, so a
-// CJK name like 小助手 slugged to '' and Create Bot stayed disabled (#96153).
-// The id must be a deterministic ASCII token and the entered name must
-// survive as the bot's display title.
-
-let fixture: MockBackendFixture | null = null
-
-const SHOTS = process.env.BOTS_I18N_SHOTS || ''
-
-async function shot(page: MockBackendFixture['page'], name: string): Promise<void> {
- if (!SHOTS) {
- return
- }
-
- fs.mkdirSync(SHOTS, { recursive: true })
- await page.screenshot({ path: path.join(SHOTS, `${name}.png`) })
-}
-
-test.beforeAll(async () => {
- fixture = await setupMockBackend()
- await waitForAppReady(fixture, 120_000)
-})
-
-test.afterAll(async () => {
- await fixture?.cleanup()
- fixture = null
-})
-
-test('a CJK bot name enables Create Bot and lands as the display title over an ASCII profile id', async () => {
- test.setTimeout(300_000)
- const page = fixture!.page
-
- const tab = page
- .getByRole('button', { name: 'Bots', exact: true })
- .or(page.getByRole('tab', { name: 'Bots', exact: true }))
- .first()
- await tab.click()
- await page.getByRole('button', { name: 'New bot or group chat' }).click()
- await page.getByRole('menuitem', { name: 'New Bot' }).click()
-
- const dialog = page.getByRole('dialog', { name: 'New Bot' })
- await dialog.getByPlaceholder('inbox-triage').fill('小助手')
-
- const create = dialog.getByRole('button', { name: 'Create Bot' })
- await shot(page, 'cjk-name-typed')
- await expect(create).toBeEnabled({ timeout: 10_000 })
- await create.click()
- await expect(dialog).toBeHidden({ timeout: 30_000 })
-
- // Roster row carries the entered name as its title …
- const row = page.getByRole('button', { name: /^小助手 · @u5c0f-u52a9-u624b/ }).filter({ visible: true }).first()
- await expect(row).toBeVisible({ timeout: 30_000 })
- await shot(page, 'cjk-bot-row')
-
- // … while the backend profile id is the deterministic ASCII form.
- const profileDir = path.join(fixture!.sandbox.hermesHome, 'profiles', 'u5c0f-u52a9-u624b')
- await expect.poll(() => fs.existsSync(profileDir), { timeout: 30_000 }).toBe(true)
- const profileYaml = fs.readFileSync(path.join(profileDir, 'profile.yaml'), 'utf8')
- expect(profileYaml).toContain('小助手')
-})
diff --git a/apps/desktop/e2e/bot-mode-roster-localized.spec.ts b/apps/desktop/e2e/bot-mode-roster-localized.spec.ts
deleted file mode 100644
index 1ded251058c..00000000000
--- a/apps/desktop/e2e/bot-mode-roster-localized.spec.ts
+++ /dev/null
@@ -1,141 +0,0 @@
-import fs from 'node:fs'
-import path from 'node:path'
-
-import {
- buildAppEnv,
- createSandbox,
- launchDesktop,
- type MockBackendFixture,
- waitForAppReady,
- writeEnvFile,
- writeMockProviderConfig
-} from './fixtures'
-import { startMockServer } from '../../../tests-js/scripts/mock-server'
-import { RealSessionBuilder } from './real-session-builder'
-import { expect, test } from './test'
-
-// The Bot Mode roster ships locale bundles (en/ja/zh/zh-hant), but a handful of
-// row strings stayed English literals after the bundle landed: the bot row's
-// right-click Pin/Hide/Groups entries and the group row's "N bots" / "N of M
-// available" preview and accessible name. Under display.language=zh a Chinese
-// reader saw an English menu inside an otherwise translated pane.
-
-type Page = MockBackendFixture['page']
-
-let fixture: MockBackendFixture | null = null
-
-const SHOTS = process.env.BOTS_I18N_SHOTS || ''
-
-async function shot(page: Page, name: string): Promise<void> {
- if (!SHOTS) {
- return
- }
-
- fs.mkdirSync(SHOTS, { recursive: true })
- await page.screenshot({ path: path.join(SHOTS, `${name}.png`) })
-}
-
-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()
- // The `+` button's accessible name comes from the zh bundle.
- await expect(page.getByRole('button', { name: '新建机器人或群聊' })).toBeVisible()
-}
-
-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, ' language: zh')
- 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-i18n')
- writeMockProviderConfig(sandbox.hermesHome, mock.url, ' language: zh')
- 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('the bot row context menu is in the active language (zh)', 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()
- await expect(alphaRow).toBeVisible({ timeout: 30_000 })
- await alphaRow.click({ button: 'right' })
-
- const menu = page.getByRole('menu').filter({ visible: true }).first()
- await expect(menu).toBeVisible({ timeout: 10_000 })
- await expect(menu.getByRole('menuitem', { name: '置顶' })).toBeVisible()
- await expect(menu.getByRole('menuitem', { name: '隐藏' })).toBeVisible()
- await expect(menu.getByRole('menuitem', { name: '管理群聊…' })).toBeVisible()
- await expect(menu.getByRole('menuitem', { name: 'Pin to top' })).toHaveCount(0)
- await expect(menu.getByRole('menuitem', { name: 'Hide' })).toHaveCount(0)
- await shot(page, 'bot-row-context-menu-zh')
- await page.keyboard.press('Escape')
- await expect(menu).toBeHidden()
-})
-
-test('a fresh group row previews its member count and availability in zh', async () => {
- test.setTimeout(300_000)
- const page = fixture!.page
-
- await openBots(page)
- await page.getByRole('button', { name: '新建机器人或群聊' }).click()
- await page.getByRole('menuitem', { name: '新建群聊' }).click()
-
- const dialog = page.getByRole('dialog', { name: '新建群聊' })
- await expect(dialog).toBeVisible({ timeout: 15_000 })
-
- for (const name of ['Alpha @alpha', 'Beta @beta']) {
- await dialog.getByRole('checkbox', { name }).click()
- }
-
- await dialog.getByRole('textbox', { name: '群组名称' }).fill('crew')
- await dialog.getByRole('button', { name: /Create Group|创建群聊/ }).click()
- await expect(dialog).toBeHidden({ timeout: 30_000 })
-
- const groupRow = page.getByRole('button', { name: /^crew, / }).filter({ visible: true }).first()
- await expect(groupRow).toBeVisible({ timeout: 30_000 })
- await expect(groupRow).toHaveAccessibleName('crew, 2 个机器人, 2 个中 2 个可用')
- await expect(groupRow.getByText('2 个机器人', { exact: true })).toBeVisible()
- await expect(page.getByText('2 bots', { exact: true })).toHaveCount(0)
- await shot(page, 'group-row-zh')
-})
diff --git a/apps/desktop/e2e/bot-mode-row-click-mirrors-registry.spec.ts b/apps/desktop/e2e/bot-mode-row-click-mirrors-registry.spec.ts
deleted file mode 100644
index 1ea609318b6..00000000000
--- a/apps/desktop/e2e/bot-mode-row-click-mirrors-registry.spec.ts
+++ /dev/null
@@ -1,158 +0,0 @@
-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 '../../../tests-js/scripts/mock-server'
-import { RealSessionBuilder } from './real-session-builder'
-import { expect, test } from './test'
-
-// A bot row previews the bot's canonical Bot Chat (the gateway resolves it by
-// name on every roster poll). Clicking the row must land on THAT conversation.
-// Before this fix a plain click fronted whatever bots-workspace tile the user
-// last had open for that bot — a `+` side thread outlived every restart in
-// Local Storage and won every click forever, while the row kept previewing the
-// Bot Chat. The user saw the sidebar and the center describe two different
-// conversations ("sessions not in sync"; support thread 1544460286084391043).
-
-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()
-}
-
-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)
-}
-
-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
- }
- }
- }
-}
-
-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-sync')
- 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 lands on the Bot Chat the row previews, not a side thread', 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 seededTurn = page.getByText('Hello alpha', { exact: true }).filter({ visible: true })
-
- await openUntil(
- () => alphaRow.click(),
- () => expect(seededTurn.first()).toBeVisible({ timeout: 45_000 })
- )
- await settle(page, 15_000)
-
- // A `+` side thread for alpha, with a real turn so it is a persisted tile.
- 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(MOCK_REPLY).filter({ visible: true }).first()).toBeVisible({ timeout: 60_000 })
-
- // Leave alpha on the side thread, go to beta, come back via the row.
- await betaRow.click()
- await expect(page.getByText('Hello beta', { exact: true }).filter({ visible: true }).first()).toBeVisible({
- timeout: 60_000
- })
- await settle(page)
-
- await alphaRow.click()
- // The row previews the Bot Chat; the click must front it.
- await expect(seededTurn.first()).toBeVisible({ timeout: 45_000 })
- // The side thread is still open beside it (scoped to alpha), not closed.
- await expect
- .poll(
- () =>
- 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:')).length
- ),
- { timeout: 15_000 }
- )
- .toBe(1)
-})
diff --git a/apps/desktop/e2e/bot-mode-tab-shows-bot-name.spec.ts b/apps/desktop/e2e/bot-mode-tab-shows-bot-name.spec.ts
deleted file mode 100644
index 8eac23c5a1f..00000000000
--- a/apps/desktop/e2e/bot-mode-tab-shows-bot-name.spec.ts
+++ /dev/null
@@ -1,137 +0,0 @@
-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 '../../../tests-js/scripts/mock-server'
-import { RealSessionBuilder } from './real-session-builder'
-import { expect, test } from './test'
-
-// Every bot's canonical chat is STORED under the same title ("Bot Chat" — the
-// name the gateway resolves it by), so the main tab strip captioned every open
-// bot chat identically and two bots' tabs were indistinguishable (#99152). The
-// tab must read the bot's display name while the stored title stays canonical.
-
-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()
-}
-
-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
- }
- }
- }
-}
-
-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()
- }
-}
-
-/** Every tab caption in the main strip (the main `workspace` tab + tiles). */
-function mainStripTabTitles(page: Page): Promise<string[]> {
- return page.evaluate(() =>
- [...document.querySelectorAll<HTMLElement>('[data-zone-tabstrip="grp-main"] [data-tree-tab]')].map(element =>
- (element.textContent ?? '').trim()
- )
- )
-}
-
-test.beforeAll(async () => {
- const mock = await startMockServer()
- const sandbox = createSandbox('bots-tabname')
- 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("an open Bot Chat's tab reads the bot's name, not the canonical 'Bot Chat' title", 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()
- await expect(alphaRow).toBeVisible({ timeout: 30_000 })
-
- await openUntil(
- () => alphaRow.click(),
- () =>
- expect(page.getByText('Hello alpha', { exact: true }).filter({ visible: true }).first()).toBeVisible({
- timeout: 45_000
- })
- )
-
- // A `+` side thread beside the Bot Chat gives the main zone a tab strip —
- // the surface where every bot chat used to read "Bot Chat".
- 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(MOCK_REPLY).filter({ visible: true }).first()).toBeVisible({ timeout: 60_000 })
-
- await expect.poll(() => mainStripTabTitles(page), { timeout: 15_000 }).toHaveLength(2)
- const captions = await mainStripTabTitles(page)
- expect(captions.some(caption => /alpha/i.test(caption))).toBe(true)
- expect(captions.some(caption => /bot chat/i.test(caption))).toBe(false)
-})
diff --git a/apps/desktop/e2e/bot-roster-group-row-organisation.spec.ts b/apps/desktop/e2e/bot-roster-group-row-organisation.spec.ts
deleted file mode 100644
index 2c02bf92f69..00000000000
--- a/apps/desktop/e2e/bot-roster-group-row-organisation.spec.ts
+++ /dev/null
@@ -1,184 +0,0 @@
-import fs from 'node:fs'
-import path from 'node:path'
-
-import { startMockServer } from '../../../tests-js/scripts/mock-server'
-
-import {
- buildAppEnv,
- createSandbox,
- launchDesktop,
- type MockBackendFixture,
- waitForAppReady,
- writeEnvFile,
- writeMockProviderConfig
-} from './fixtures'
-import { RealSessionBuilder } from './real-session-builder'
-import { expect, test } from './test'
-
-// A group chat's roster row gets the same organisation affordances a bot row
-// has: right-click → Pin to top floats the room above unpinned rows and
-// persists on the room record; right-click → Move to section files the room
-// into a user-made section, with membership riding the durable group-chats
-// record rather than any bot's profile meta (hermes-agent#89813, #105544).
-
-type Page = MockBackendFixture['page']
-
-let fixture: MockBackendFixture | null = null
-
-// BOT_GROUP_ROW_SCREENSHOT_DIR=<dir> saves full-window captures at the key
-// states — PR evidence; never part of the assertions.
-async function capture(page: Page, name: string): Promise<void> {
- const dir = process.env.BOT_GROUP_ROW_SCREENSHOT_DIR
-
- if (!dir) {
- return
- }
-
- fs.mkdirSync(dir, { recursive: true })
- await page.screenshot({ path: path.join(dir, `${name}.png`) })
-}
-
-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()
- }
-}
-
-const ROOM = 'Standup'
-
-const roster = (page: Page) => page.locator('[data-slot="bots-roster"]')
-const groupRow = (page: Page) => roster(page).getByRole('button', { name: new RegExp(`^${ROOM}, `) })
-const sectionLabel = (page: Page, name: string) => page.locator('span.truncate', { hasText: new RegExp(`^${name}$`, 'i') })
-
-const sectionBlock = (page: Page, name: string) =>
- roster(page).locator('[data-slot="bots-section"]').filter({ has: sectionLabel(page, name) })
-
-/** Roster rows top to bottom: bot rows by roster key, the room by its label. */
-async function rowOrder(page: Page): Promise<string[]> {
- return roster(page)
- .locator(`[data-roster-key], button[aria-label^="${ROOM},"]`)
- .evaluateAll(rows => rows.map(row => (row as HTMLElement).dataset.rosterKey || 'group'))
-}
-
-async function storedRoom(page: Page): Promise<{ pinned?: boolean; sectionId?: null | string }> {
- return page.evaluate(
- room => JSON.parse(localStorage.getItem('hermes.plugin.hermes-bots.group-chats') || '{}')[room] || {},
- ROOM
- )
-}
-
-test.beforeAll(async () => {
- const mock = await startMockServer()
- const sandbox = createSandbox('bots-group-row')
- writeMockProviderConfig(sandbox.hermesHome, mock.url)
- writeEnvFile(sandbox.hermesHome)
-
- for (const name of ['alpha', 'beta']) {
- await seedBot(sandbox.hermesHome, mock.url, name)
- }
-
- 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 group chat row pins to the top and files into a user section like a bot row', async () => {
- test.setTimeout(300_000)
- const page = fixture!.page
-
- 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()
- await expect(roster(page).locator('[data-roster-key="local::alpha"]')).toBeVisible({ timeout: 30_000 })
- await expect(roster(page).locator('[data-roster-key="local::beta"]')).toBeVisible({ timeout: 30_000 })
-
- // Make a room from the two bots.
- await page.getByRole('button', { name: 'New bot or group chat' }).click()
- await page.getByRole('menuitem', { name: 'New Group Chat' }).click()
- const dialog = page.getByRole('dialog', { name: 'New Group Chat' })
-
- for (const name of ['Alpha @alpha', 'Beta @beta']) {
- await dialog.getByRole('checkbox', { name }).click()
- }
-
- await dialog.getByRole('textbox', { name: 'Group name' }).fill(ROOM)
- await dialog.getByRole('button', { name: 'Create Group (2)' }).click()
- await expect(dialog).toBeHidden({ timeout: 30_000 })
-
- // Back to the roster: the fresh, quiet room sinks under the bots that have
- // history, so a pin has something to change.
- await tab.click()
- await expect(groupRow(page)).toBeVisible({ timeout: 30_000 })
- await expect.poll(() => rowOrder(page).then(rows => rows.at(-1))).toBe('group')
- await capture(page, '1-room-unpinned-last')
-
- await groupRow(page).click({ button: 'right' })
- await expect(page.getByRole('menuitem', { name: 'Pin to top' })).toBeVisible()
- await capture(page, '2-group-row-menu')
- await page.getByRole('menuitem', { name: 'Pin to top' }).click()
-
- await expect.poll(() => rowOrder(page).then(rows => rows[0])).toBe('group')
- await expect(groupRow(page).locator('.codicon-pinned')).toHaveCount(1)
- // Storage truth: the flag is on the room record, where a reload hydrates it.
- await expect.poll(async () => (await storedRoom(page)).pinned).toBe(true)
- await capture(page, '3-room-pinned-first')
-
- // Unpin through the same item — the room sinks again.
- await groupRow(page).click({ button: 'right' })
- await page.getByRole('menuitem', { name: 'Unpin' }).click()
- await expect.poll(() => rowOrder(page).then(rows => rows.at(-1))).toBe('group')
- await expect.poll(async () => (await storedRoom(page)).pinned).toBe(false)
-
- // File the room into a brand-new section from its own menu.
- await groupRow(page).click({ button: 'right' })
- await page.getByRole('menuitem', { name: 'Move to section' }).hover()
- await expect(page.getByRole('menuitem', { name: 'New section…' })).toBeVisible()
- await capture(page, '4-group-row-move-to-section')
- await page.getByRole('menuitem', { name: 'New section…' }).click()
- const nameField = page.getByRole('textbox', { name: 'Section name' })
- await nameField.fill('Rooms')
- await page.getByRole('button', { name: 'Create' }).click()
-
- await expect(sectionBlock(page, 'Rooms').getByRole('button', { name: new RegExp(`^${ROOM}, `) })).toBeVisible()
- await expect(sectionBlock(page, 'Unassigned').getByRole('button', { name: new RegExp(`^${ROOM}, `) })).toHaveCount(0)
- await expect.poll(async () => (await storedRoom(page)).sectionId).toMatch(/^sec-/)
- await capture(page, '5-room-filed-into-rooms')
-
- // Remove from section returns it to the unassigned bucket.
- await groupRow(page).click({ button: 'right' })
- await page.getByRole('menuitem', { name: 'Move to section' }).hover()
- await page.getByRole('menuitem', { name: 'Remove from section' }).click()
- await expect(sectionBlock(page, 'Unassigned').getByRole('button', { name: new RegExp(`^${ROOM}, `) })).toBeVisible()
- await expect.poll(async () => (await storedRoom(page)).sectionId).toBeNull()
- await capture(page, '6-room-unfiled')
-})
diff --git a/apps/desktop/e2e/bot-roster-ignores-infra-dirs.spec.ts b/apps/desktop/e2e/bot-roster-ignores-infra-dirs.spec.ts
deleted file mode 100644
index d66d619efce..00000000000
--- a/apps/desktop/e2e/bot-roster-ignores-infra-dirs.spec.ts
+++ /dev/null
@@ -1,98 +0,0 @@
-import fs from 'node:fs'
-import path from 'node:path'
-
-import { startMockServer } from '../../../tests-js/scripts/mock-server'
-
-import {
- buildAppEnv,
- createSandbox,
- launchDesktop,
- type MockBackendFixture,
- waitForAppReady,
- writeEnvFile,
- writeMockProviderConfig
-} from './fixtures'
-import { RealSessionBuilder } from './real-session-builder'
-import { expect, test } from './test'
-
-// A directory under profiles/ is a profile only when it carries an identity
-// file. Infrastructure dirs the runtime leaves there (`sessions/`, `logs/`
-// from a log rotation or cron tick) and tombstoned (deleted) profiles must not
-// surface as bots in the roster (#99392, #95188).
-
-let fixture: MockBackendFixture | null = null
-
-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-infra-dirs')
- writeMockProviderConfig(sandbox.hermesHome, mock.url)
- writeEnvFile(sandbox.hermesHome)
- await seedBot(sandbox.hermesHome, mock.url, 'alpha')
-
- // Marker-less infrastructure dirs, exactly the shells a cron tick / log rotation leaves behind.
- for (const stray of ['sessions', 'logs']) {
- fs.mkdirSync(path.join(sandbox.hermesHome, 'profiles', stray, 'cron'), { recursive: true })
- }
-
- // A deleted profile: identity file present, tombstone in profiles/.deleted/<name>.
- const ghost = path.join(sandbox.hermesHome, 'profiles', 'ghost')
- fs.mkdirSync(ghost, { recursive: true })
- fs.writeFileSync(path.join(ghost, 'profile.yaml'), 'ui_meta:\n hermes-bots: {}\n')
- fs.mkdirSync(path.join(sandbox.hermesHome, 'profiles', '.deleted'), { recursive: true })
- fs.writeFileSync(path.join(sandbox.hermesHome, 'profiles', '.deleted', 'ghost'), '')
-
- 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('the Bots roster lists real bots only — never profiles/ infra dirs or tombstones', async () => {
- test.setTimeout(240_000)
- const page = fixture!.page
-
- await page
- .getByRole('button', { name: 'Bots', exact: true })
- .or(page.getByRole('tab', { name: 'Bots', exact: true }))
- .first()
- .click()
- await expect(page.getByRole('button', { name: 'New bot or group chat' })).toBeVisible()
-
- const roster = page.locator('[data-slot="bots-roster"]')
- await expect(roster.locator('[data-roster-key="local::alpha"]')).toBeVisible({ timeout: 30_000 })
-
- for (const stray of ['sessions', 'logs', 'ghost', '.deleted']) {
- await expect(roster.locator(`[data-roster-key="local::${stray}"]`)).toHaveCount(0)
- }
-})
diff --git a/apps/desktop/e2e/bot-roster-timestamp-meta.spec.ts b/apps/desktop/e2e/bot-roster-timestamp-meta.spec.ts
deleted file mode 100644
index 89b6a26abac..00000000000
--- a/apps/desktop/e2e/bot-roster-timestamp-meta.spec.ts
+++ /dev/null
@@ -1,105 +0,0 @@
-/**
- * E2E: the Bots roster must load when a profile.yaml carries an unquoted ISO
- * timestamp under `ui_meta` (YAML parses it as a datetime).
- *
- * On a gateway without the serialization guard, `profiles.list` never answers
- * over /api/ws and the roster spins forever (#92506). The assertion is the
- * rendered roster rows within a bounded window.
- */
-
-import * as fs from 'node:fs'
-import * as path from 'node:path'
-
-import { startMockServer } from '../../../tests-js/scripts/mock-server'
-
-import {
- buildAppEnv,
- createSandbox,
- launchDesktop,
- type MockBackendFixture,
- waitForAppReady,
- writeEnvFile,
- writeMockProviderConfig
-} from './fixtures'
-import { expect, type Page, test } from './test'
-
-const SHOT_DIR = process.env.BOT_LIFECYCLE_SHOT_DIR || ''
-
-let fixture: MockBackendFixture | null = null
-
-async function capture(page: Page, name: string): Promise<void> {
- if (!SHOT_DIR) {
- return
- }
-
- fs.mkdirSync(SHOT_DIR, { recursive: true })
- await page.screenshot({ path: path.join(SHOT_DIR, `${name}.png`) })
-}
-
-test.describe('Bots roster — profile with timestamp metadata', () => {
- test.beforeAll(async () => {
- test.setTimeout(300_000)
- const mock = await startMockServer()
- const sandbox = createSandbox('bot-tsmeta')
- writeMockProviderConfig(sandbox.hermesHome, mock.url)
- writeEnvFile(sandbox.hermesHome)
-
- for (const name of ['alpha', 'zeta']) {
- const dir = path.join(sandbox.hermesHome, 'profiles', name)
- fs.mkdirSync(dir, { recursive: true })
- writeMockProviderConfig(dir, mock.url)
- writeEnvFile(dir)
- }
-
- // The trigger: an unquoted ISO-8601 timestamp — yaml.safe_load → datetime.
- fs.writeFileSync(
- path.join(sandbox.hermesHome, 'profiles', 'zeta', 'profile.yaml'),
- 'ui_meta:\n hermes-bots:\n created: 2026-08-22T00:00:00Z\n',
- 'utf8'
- )
-
- const env = buildAppEnv(sandbox)
- const { app, page } = await launchDesktop(env)
- 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()
- })
-
- test('roster rows render instead of spinning forever', async () => {
- test.setTimeout(300_000)
- const { page } = fixture!
-
- 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({ timeout: 60_000 })
-
- const rows = page.locator('[data-slot="bots-roster"] [data-roster-key^="local::"]')
-
- try {
- await expect(rows.first()).toBeVisible({ timeout: 60_000 })
- } finally {
- await capture(page, 'tsmeta-roster')
- console.log(`[probe] roster rows after 60s: ${await rows.count()}`)
- }
-
- await expect(page.locator('[data-roster-key="local::zeta"]').first()).toBeVisible({ timeout: 30_000 })
- })
-})
diff --git a/apps/desktop/e2e/bot-roster-user-sections.spec.ts b/apps/desktop/e2e/bot-roster-user-sections.spec.ts
deleted file mode 100644
index 7439777cce2..00000000000
--- a/apps/desktop/e2e/bot-roster-user-sections.spec.ts
+++ /dev/null
@@ -1,254 +0,0 @@
-import fs from 'node:fs'
-import path from 'node:path'
-
-import {
- buildAppEnv,
- createSandbox,
- launchDesktop,
- type MockBackendFixture,
- waitForAppReady,
- writeEnvFile,
- writeMockProviderConfig
-} from './fixtures'
-import { startMockServer } from '../../../tests-js/scripts/mock-server'
-import { RealSessionBuilder } from './real-session-builder'
-import { expect, test } from './test'
-
-// User-made sections in the Bots roster: a bot is filed by dragging it onto a
-// section or through its row menu, the section is renamed through the same
-// dialog shape sessions use, and deleting a section returns its bots to
-// Unassigned (with an Undo toast, no confirmation). With no sections created
-// the roster is the plain list it always was.
-
-type Page = MockBackendFixture['page']
-
-let fixture: MockBackendFixture | null = null
-
-// BOT_SECTIONS_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.BOT_SECTIONS_SCREENSHOT_DIR
-
- if (!dir) {
- return
- }
-
- fs.mkdirSync(dir, { recursive: true })
- await page.screenshot({ path: path.join(dir, `${name}.png`) })
-}
-
-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()
- }
-}
-
-const roster = (page: Page) => page.locator('[data-slot="bots-roster"]')
-const botRow = (page: Page, name: string) => roster(page).locator(`[data-roster-key="local::${name}"]`)
-
-/** A section's label span — the one node whose text is exactly the name. */
-const sectionLabel = (page: Page, name: string) =>
- page.locator('span.truncate', { hasText: new RegExp(`^${name}$`, 'i') })
-
-/** The heading's fold button (label + count) — the ⋯ menu trigger is a sibling with no text. */
-const sectionHeading = (page: Page, name: string) =>
- roster(page).locator('[data-slot="bots-section"] button[aria-expanded]').filter({ has: sectionLabel(page, name) })
-
-const sectionBlock = (page: Page, name: string) =>
- roster(page).locator('[data-slot="bots-section"]').filter({ has: sectionLabel(page, name) })
-
-/** Section name → roster keys of the rows under it (the plain list has no sections). */
-async function layout(page: Page): Promise<Array<[string, string[]]>> {
- return roster(page).locator('[data-slot="bots-section"]').evaluateAll(blocks =>
- blocks.map(block => [
- block.querySelector('button[aria-expanded] span.truncate')?.textContent?.trim() ?? '',
- [...block.querySelectorAll<HTMLElement>('[data-roster-key]')].map(row => row.dataset.rosterKey ?? '')
- ])
- )
-}
-
-test.beforeAll(async () => {
- const mock = await startMockServer()
- const sandbox = createSandbox('bots-sections')
- writeMockProviderConfig(sandbox.hermesHome, mock.url)
- writeEnvFile(sandbox.hermesHome)
-
- for (const name of ['alpha', 'beta', 'gamma']) {
- await seedBot(sandbox.hermesHome, mock.url, name)
- }
-
- 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('file bots into user sections by menu and drag; rename; delete returns them to Unassigned', async () => {
- test.setTimeout(300_000)
- const page = fixture!.page
-
- 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()
- await expect(botRow(page, 'alpha')).toBeVisible({ timeout: 30_000 })
- await expect(botRow(page, 'beta')).toBeVisible({ timeout: 30_000 })
-
- // No sections yet: the plain list, no section chrome at all.
- await expect(roster(page).locator('[data-slot="bots-section"]')).toHaveCount(0)
- await capture(page, '1-plain-roster')
-
- // Right-click alpha → Move to section → New section… → name it → alpha is filed.
- await botRow(page, 'alpha').click({ button: 'right' })
- await page.getByRole('menuitem', { name: 'Move to section' }).hover()
- await expect(page.getByRole('menuitem', { name: 'New section…' })).toBeVisible()
- await capture(page, '2-row-menu-move-to-section')
- await page.getByRole('menuitem', { name: 'New section…' }).click()
- const nameField = page.getByRole('textbox', { name: 'Section name' })
- await expect(nameField).toBeVisible()
- await nameField.fill('Clients')
- await capture(page, '3-new-section-dialog')
- await page.getByRole('button', { name: 'Create' }).click()
-
- await expect(sectionHeading(page, 'Clients')).toBeVisible()
- await expect(sectionBlock(page, 'Clients').locator('[data-roster-key="local::alpha"]')).toBeVisible()
- // The remainder is Unassigned, drawn last.
- await expect
- .poll(async () => (await layout(page)).map(([name, keys]) => [name, keys.length]))
- .toEqual([
- ['Clients', 1],
- ['Unassigned', 3]
- ])
- await capture(page, '4-alpha-filed')
-
- // Drag beta over the Clients block: the target highlights while over it.
- // Escape cancels — nothing moves, nothing stays highlighted or faded.
- const target = sectionBlock(page, 'Clients')
- const from = (await botRow(page, 'beta').boundingBox())!
- const to = (await sectionHeading(page, 'Clients').boundingBox())!
-
- const dragBetaOverClients = async () => {
- await page.mouse.move(from.x + from.width / 2, from.y + from.height / 2)
- await page.mouse.down()
- await page.mouse.move(from.x + from.width / 2, from.y + from.height / 2 - 10, { steps: 4 })
- await page.mouse.move(to.x + to.width / 2, to.y + to.height / 2, { steps: 12 })
- await expect(target).toHaveAttribute('data-drop-over', 'true')
- }
-
- await dragBetaOverClients()
- await page.keyboard.press('Escape')
- await page.mouse.up()
- await expect(target).not.toHaveAttribute('data-drop-over', 'true')
- await expect(botRow(page, 'beta')).toHaveCSS('opacity', '1')
- expect((await layout(page)).map(([name, keys]) => [name, keys.length])).toEqual([
- ['Clients', 1],
- ['Unassigned', 3]
- ])
-
- // Drop it for real: the bot is filed.
- await dragBetaOverClients()
- await capture(page, '5-drag-over-clients')
- await page.mouse.up()
-
- await expect(target.locator('[data-roster-key="local::beta"]')).toBeVisible()
- await expect(target).not.toHaveAttribute('data-drop-over', 'true')
- // The moved row remounts under its new section; it must not stay faded.
- await expect(botRow(page, 'beta')).toHaveCSS('opacity', '1')
- await expect
- .poll(async () => (await layout(page)).map(([name, keys]) => [name, keys.length]))
- .toEqual([
- ['Clients', 2],
- ['Unassigned', 2]
- ])
- await capture(page, '6-beta-dropped')
-
- // Rename through the heading's context menu — the same Dialog + Input
- // + Save shape as a session rename.
- await sectionHeading(page, 'Clients').click({ button: 'right' })
- await page.getByRole('menuitem', { name: 'Rename…' }).click()
- await expect(nameField).toHaveValue('Clients')
- await nameField.fill('Customers')
- await page.getByRole('button', { name: 'Save' }).click()
- await expect(sectionHeading(page, 'Customers')).toBeVisible()
- await expect(sectionHeading(page, 'Clients')).toHaveCount(0)
- await capture(page, '7-renamed')
-
- // A second, empty section from the + menu shows its drop hint; collapsing
- // a section folds its rows like the gateway headings do.
- await page.getByRole('button', { name: 'New bot or group chat' }).click()
- await page.getByRole('menuitem', { name: 'New section' }).click()
- await nameField.fill('Team')
- await page.getByRole('button', { name: 'Create' }).click()
- await expect(sectionBlock(page, 'Team').getByText('Drag bots here')).toBeVisible()
- await sectionHeading(page, 'Customers').click()
- await expect(sectionBlock(page, 'Customers').locator('[data-roster-key]')).toHaveCount(0)
- await capture(page, '8-empty-section-and-collapsed')
- await sectionHeading(page, 'Customers').click()
- await expect(sectionBlock(page, 'Customers').locator('[data-roster-key]')).toHaveCount(2)
-
- // Delete Customers: no confirmation, its two bots return to Unassigned,
- // and the toast offers Undo.
- await sectionHeading(page, 'Customers').click({ button: 'right' })
- await page.getByRole('menuitem', { name: 'Delete' }).click()
- await expect(sectionHeading(page, 'Customers')).toHaveCount(0)
- const toast = page.getByRole('status').filter({ hasText: 'Deleted “Customers”' })
- await expect(toast).toBeVisible()
- await expect
- .poll(async () => (await layout(page)).map(([name, keys]) => [name, keys.length]))
- .toEqual([
- ['Team', 0],
- ['Unassigned', 4]
- ])
- await capture(page, '9-deleted-with-undo-toast')
-
- await toast.getByRole('button', { name: 'Undo' }).click()
- await expect(sectionHeading(page, 'Customers')).toBeVisible()
- await expect
- .poll(async () => (await layout(page)).map(([name, keys]) => [name, keys.length]))
- .toEqual([
- ['Customers', 2],
- ['Team', 0],
- ['Unassigned', 2]
- ])
-
- // Membership rides the bot's profile ui_meta, so it follows profile sync.
- const alphaProfile = path.join(fixture!.sandbox.hermesHome, 'profiles', 'alpha', 'profile.yaml')
- await expect.poll(() => (fs.existsSync(alphaProfile) ? fs.readFileSync(alphaProfile, 'utf8') : '')).toMatch(/sectionId:\s*sec-/)
-
- // Delete both sections: the roster is the plain list again.
- for (const name of ['Customers', 'Team']) {
- await sectionHeading(page, name).click({ button: 'right' })
- await page.getByRole('menuitem', { name: 'Delete' }).click()
- }
-
- await expect(roster(page).locator('[data-slot="bots-section"]')).toHaveCount(0)
- await expect(botRow(page, 'alpha')).toBeVisible()
-})
diff --git a/apps/desktop/e2e/bot-routines-pane-narrow.spec.ts b/apps/desktop/e2e/bot-routines-pane-narrow.spec.ts
deleted file mode 100644
index 0941de3cbcc..00000000000
--- a/apps/desktop/e2e/bot-routines-pane-narrow.spec.ts
+++ /dev/null
@@ -1,257 +0,0 @@
-import { execFileSync } from 'node:child_process'
-import fs from 'node:fs'
-import path from 'node:path'
-
-import { startMockServer } from '../../../tests-js/scripts/mock-server'
-
-import {
- buildAppEnv,
- createSandbox,
- launchDesktop,
- type MockBackendFixture,
- waitForAppReady,
- writeEnvFile,
- writeMockProviderConfig
-} from './fixtures'
-import { RealSessionBuilder } from './real-session-builder'
-import { expect, test } from './test'
-
-// The Scheduled jobs (Routines) pane docks at 250px beside a bot chat. A job
-// row is a grid item, and grid items default to `min-width: auto`, so a long
-// nowrap title pinned the row wider than the pane: the enable/disable Switch
-// and the delete control were clipped off the right edge and the next-run
-// label was cut mid-word (#91623, #89534). Closing the pane with its ✕ also
-// remembered the dismissal forever — re-entering Bot Mode never brought the
-// pane back (#102224).
-
-type Page = MockBackendFixture['page']
-
-const LONG_TITLE = '[bot:alpha] Weekly research digest with a deliberately long routine title that overflows'
-
-let fixture: MockBackendFixture | null = null
-let alphaHome = ''
-
-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()
-}
-
-async function openSessions(page: Page): Promise<void> {
- const tab = page
- .getByRole('button', { name: /^sessions$/i })
- .or(page.getByRole('tab', { name: /^sessions$/i }))
- .first()
-
- await tab.click()
-}
-
-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
- }
- }
- }
-}
-
-async function seedBot(hermesHome: string, mockUrl: string, name: string): Promise<string> {
- 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()
- }
-
- return dir
-}
-
-/** A real cron job in the profile's own cron store, written by the real store code. */
-function seedRoutine(profileHome: string, title: string): void {
- const python = path.resolve(process.cwd(), '../../venv/bin/python')
- const repoRoot = path.resolve(process.cwd(), '../..')
-
- const script = [
- 'from cron.jobs import create_job',
- `create_job(name=${JSON.stringify(title)}, schedule='every 4 days', prompt='say hello')`
- ].join('\n')
-
- execFileSync(python, ['-c', script], {
- cwd: repoRoot,
- env: { ...process.env, HERMES_HOME: profileHome },
- stdio: 'pipe'
- })
-}
-
-function readJobs(profileHome: string): Array<{ enabled?: boolean; name?: string; state?: string }> {
- const raw = JSON.parse(fs.readFileSync(path.join(profileHome, 'cron', 'jobs.json'), 'utf8'))
-
- return Array.isArray(raw) ? raw : (raw.jobs ?? [])
-}
-
-async function openAlphaChat(page: Page): Promise<void> {
- await openBots(page)
-
- const alphaRow = page
- .getByRole('button', { name: /^alpha\b/i })
- .filter({ visible: true })
- .first()
-
- await expect(alphaRow).toBeVisible({ timeout: 30_000 })
- await openUntil(
- () => alphaRow.click(),
- () =>
- expect(page.getByText('Hello alpha', { exact: true }).filter({ visible: true }).first()).toBeVisible({
- timeout: 45_000
- })
- )
-}
-
-function routinesTab(page: Page) {
- return page.locator('[data-tree-tab="hermes-bots:routines"]').filter({ visible: true }).first()
-}
-
-/** Expand the collapsed right-edge Scheduled jobs tab (a no-op when the pane is already open); resolve the row. */
-async function expandRoutines(page: Page) {
- const row = page
- .getByRole('button', { name: /Weekly research digest/ })
- .filter({ visible: true })
- .first()
-
- if (!(await row.isVisible())) {
- const tab = routinesTab(page)
- await expect(tab).toBeVisible({ timeout: 30_000 })
- await tab.click()
- }
-
- await expect(row).toBeVisible({ timeout: 30_000 })
- await page.waitForTimeout(2_500)
- await expect(row).toBeVisible()
-
- return row
-}
-
-test.beforeAll(async () => {
- const mock = await startMockServer()
- const sandbox = createSandbox('bots-routines')
- writeMockProviderConfig(sandbox.hermesHome, mock.url)
- writeEnvFile(sandbox.hermesHome)
- alphaHome = await seedBot(sandbox.hermesHome, mock.url, 'alpha')
- seedRoutine(alphaHome, LONG_TITLE)
-
- 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 long routine title never pushes the Switch, delete control or next-run label out of the 250px pane', async ({}, testInfo) => {
- test.setTimeout(300_000)
- const page = fixture!.page
-
- await openAlphaChat(page)
- const row = await expandRoutines(page)
- await page.screenshot({ path: testInfo.outputPath('routines-pane.png') })
-
- // Geometry against the pane's own scroll container, not body text: the row
- // is a grid item, so its intrinsic width is what pins the controls off-edge.
- const geometry = await row.evaluate(button => {
- const card = button.parentElement!.parentElement as HTMLElement
- const scroller = card.closest<HTMLElement>('.overflow-y-auto')!
- const paneRect = scroller.getBoundingClientRect()
-
- const rect = (el: Element | null) => {
- const r = el!.getBoundingClientRect()
-
- return { left: r.left, right: r.right, width: r.width }
- }
-
- const nextRun = [...card.querySelectorAll<HTMLElement>('span')].find(s => /^next/i.test(s.textContent ?? ''))!
- const title = button.querySelector<HTMLElement>('span.truncate')!
-
- return {
- card: rect(card),
- pane: rect(scroller),
- switch: rect(card.querySelector('[role="switch"]')),
- trash: rect(card.querySelector('button[aria-label]')),
- nextRun: { ...rect(nextRun), clipped: nextRun.scrollWidth > nextRun.clientWidth + 1, text: nextRun.textContent },
- titleEllipsized: title.scrollWidth > title.clientWidth,
- paneRight: paneRect.right
- }
- })
-
-
- expect.soft(geometry.card.right).toBeLessThanOrEqual(geometry.pane.right + 1)
- expect.soft(geometry.switch.right).toBeLessThanOrEqual(geometry.pane.right + 1)
- expect.soft(geometry.trash.right).toBeLessThanOrEqual(geometry.pane.right + 1)
- expect.soft(geometry.nextRun.right).toBeLessThanOrEqual(geometry.pane.right + 1)
- expect.soft(geometry.nextRun.clipped).toBe(false)
- expect.soft(geometry.nextRun.text).toMatch(/next: in \d+ days?/i)
- // The title is the one thing that MAY be cut, and it must be cut with an ellipsis.
- expect.soft(geometry.titleEllipsized).toBe(true)
-
- await test.step("clicking the row's Switch toggles the job in place — the pane stays, jobs.json flips (#95031)", async () => {
- const toggle = row.locator('xpath=..').getByRole('switch')
- await expect(toggle).toBeVisible()
- expect(readJobs(alphaHome)[0]?.enabled).not.toBe(false)
-
- await toggle.click()
-
- await expect.poll(() => readJobs(alphaHome)[0]?.enabled, { timeout: 30_000 }).toBe(false)
- await expect(row).toBeVisible()
- await expect(page.getByText(/Open this bot's continuous chat/i)).toHaveCount(0)
- await page.screenshot({ path: testInfo.outputPath('routines-pane-toggled.png') })
- })
-
- await test.step('closing Scheduled jobs with ✕ is recoverable — leaving and re-entering Bot Mode brings the pane back (#102224)', async () => {
- const tab = page.locator('[data-tree-tab="hermes-bots:routines"]').first()
- await expect(tab).toBeVisible({ timeout: 30_000 })
- await tab.hover()
- const closer = tab.getByRole('button', { name: /^close$/i }).first()
- await closer.click({ force: true })
- await page.waitForTimeout(1_500)
- await expect(page.getByRole('button', { name: /Weekly research digest/ })).toHaveCount(0, { timeout: 15_000 })
- await page.screenshot({ path: testInfo.outputPath('routines-closed.png') })
-
- await openSessions(page)
- await page.waitForTimeout(1_000)
- await openAlphaChat(page)
- await page.waitForTimeout(2_000)
- await page.screenshot({ path: testInfo.outputPath('routines-restored.png') })
-
- await expect(page.locator('[data-tree-tab="hermes-bots:routines"]').first()).toBeVisible({ timeout: 30_000 })
- })
-})
diff --git a/apps/desktop/e2e/bot-row-open-recent-session.spec.ts b/apps/desktop/e2e/bot-row-open-recent-session.spec.ts
deleted file mode 100644
index ff5cae467a7..00000000000
--- a/apps/desktop/e2e/bot-row-open-recent-session.spec.ts
+++ /dev/null
@@ -1,119 +0,0 @@
-import fs from 'node:fs'
-import path from 'node:path'
-
-import { startMockServer } from '../../../tests-js/scripts/mock-server'
-
-import {
- buildAppEnv,
- createSandbox,
- launchDesktop,
- type MockBackendFixture,
- waitForAppReady,
- writeEnvFile,
- writeMockProviderConfig
-} from './fixtures'
-import { RealSessionBuilder } from './real-session-builder'
-import { expect, test } from './test'
-
-// Right-click a bot row → "Open recent session" opens the bot's most recently
-// active ordinary session as a tab in its workspace, while the row's left click
-// keeps landing on the canonical Bot Chat (hermes-agent#93054).
-
-type Page = MockBackendFixture['page']
-
-let fixture: MockBackendFixture | null = null
-
-// BOT_RECENT_SESSION_SCREENSHOT_DIR=<dir> saves full-window captures at the
-// key states — PR evidence; never part of the assertions.
-async function capture(page: Page, name: string): Promise<void> {
- const dir = process.env.BOT_RECENT_SESSION_SCREENSHOT_DIR
-
- if (!dir) {
- return
- }
-
- fs.mkdirSync(dir, { recursive: true })
- await page.screenshot({ path: path.join(dir, `${name}.png`) })
-}
-
-const RECENT_TITLE = 'Deploy notes'
-
-test.beforeAll(async () => {
- const mock = await startMockServer()
- const sandbox = createSandbox('bots-recent-session')
- writeMockProviderConfig(sandbox.hermesHome, mock.url)
- writeEnvFile(sandbox.hermesHome)
-
- const dir = path.join(sandbox.hermesHome, 'profiles', 'alpha')
- fs.mkdirSync(dir, { recursive: true })
- writeMockProviderConfig(dir, mock.url)
- writeEnvFile(dir)
- const builder = await RealSessionBuilder.start(dir)
-
- try {
- // The canonical chat first, then an ordinary session so the latter is the
- // profile's newest listed conversation.
- await builder.createSession({ title: 'Bot Chat', turns: ['Hello alpha'] })
- await builder.createSession({ title: RECENT_TITLE, turns: ['Where are we on the deploy?'] })
- } finally {
- await builder.close()
- }
-
- 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('the bot row menu opens the most recent session as a tab beside the Bot Chat', async () => {
- test.setTimeout(300_000)
- const page = fixture!.page
-
- 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()
- const row = page.locator('[data-slot="bots-roster"] [data-roster-key="local::alpha"]')
- await expect(row).toBeVisible({ timeout: 30_000 })
-
- // The row click is unchanged: the canonical Bot Chat opens, captioned with the bot's name.
- await row.click()
- const botChatTab = page.getByRole('tab', { name: /^Alpha\b/ })
- await expect(botChatTab).toBeVisible({ timeout: 60_000 })
- await expect(page.getByRole('tab', { name: new RegExp(`^${RECENT_TITLE}\\b`) })).toHaveCount(0)
- await capture(page, '1-row-click-opens-bot-chat')
-
- await row.click({ button: 'right' })
- const item = page.getByRole('menuitem', { name: 'Open recent session' })
- await expect(item).toBeVisible()
- await expect(item).toBeEnabled()
- await capture(page, '2-row-menu-open-recent-session')
- await item.click()
-
- const recentTab = page.getByRole('tab', { name: new RegExp(`^${RECENT_TITLE}\\b`) })
- await expect(recentTab).toBeVisible({ timeout: 60_000 })
- await expect(recentTab).toHaveAttribute('aria-selected', 'true')
- // A tab beside the Bot Chat, not in its place.
- await expect(botChatTab).toBeVisible()
- await expect(page.getByText('Where are we on the deploy?').first()).toBeVisible({ timeout: 60_000 })
- await capture(page, '3-recent-session-tab-open')
-})
diff --git a/apps/desktop/e2e/bot-tile-ignores-ambient-composer-model.spec.ts b/apps/desktop/e2e/bot-tile-ignores-ambient-composer-model.spec.ts
deleted file mode 100644
index 5f1a95fc896..00000000000
--- a/apps/desktop/e2e/bot-tile-ignores-ambient-composer-model.spec.ts
+++ /dev/null
@@ -1,169 +0,0 @@
-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 '../../../tests-js/scripts/mock-server'
-import { RealSessionBuilder } from './real-session-builder'
-import { expect, test } from './test'
-
-// A manual model pick in the composer is sticky for ordinary new chats. A `+`
-// chat opened beside a bot in Bot Mode targets that bot's profile without
-// switching the window's ambient composer, so a pick made for some other open
-// session must NOT ride into the bot's session.create: the bot profile's
-// configured default model is what the new chat's inference request carries
-// (#95264).
-
-type Page = MockBackendFixture['page']
-
-const AMBIENT_PICK = 'ambient-pick-model'
-
-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()
-}
-
-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)
-}
-
-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
- }
- }
- }
-}
-
-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({ extraModels: [AMBIENT_PICK] })
- const sandbox = createSandbox('bot-tile-model')
- writeMockProviderConfig(sandbox.hermesHome, mock.url)
- writeEnvFile(sandbox.hermesHome)
- await seedBot(sandbox.hermesHome, mock.url, 'alpha')
-
- 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's `+` chat runs on the bot profile's model, not the ambient composer pick", async ({}, testInfo) => {
- test.setTimeout(300_000)
- const page = fixture!.page
- const mock = fixture!.mock
-
- await openBots(page)
-
- const alphaRow = page
- .getByRole('button', { name: /^alpha\b/i })
- .filter({ visible: true })
- .first()
- await expect(alphaRow).toBeVisible({ timeout: 30_000 })
- await openUntil(
- () => alphaRow.click(),
- () =>
- expect(page.getByText('Hello alpha', { exact: true }).filter({ visible: true }).first()).toBeVisible({
- timeout: 45_000
- })
- )
-
- await settle(page, 15_000)
-
- // A manual pick while the bot's canonical chat is open: the window's ambient
- // composer now holds a model that is NOT the profile default. Rows are
- // hover-submenu triggers (reasoning/fast edit); Enter on the row commits.
- await page
- .getByRole('button', { name: /^Model ·/ })
- .first()
- .click()
- await page.getByRole('textbox', { name: 'Search models' }).fill('ambient pick')
- const row = page.getByRole('menuitem', { name: /^Ambient Pick Model/ }).first()
- await expect(row).toBeVisible()
- await row.focus()
- await page.keyboard.press('Enter')
- await expect(page.getByRole('button', { name: /^Model ·/ }).first()).toHaveAccessibleName(new RegExp(AMBIENT_PICK), {
- timeout: 15_000
- })
- await page.screenshot({ path: testInfo.outputPath('bot-chat-manual-pick.png') })
-
- // `+` beside the bot: a fresh bots-workspace tile for alpha.
- const before = mock.receivedModels.length
- await page.keyboard.press('Control+t')
- await settle(page)
- 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(MOCK_REPLY).filter({ visible: true }).first()).toBeVisible({ timeout: 60_000 })
- await page.screenshot({ path: testInfo.outputPath('bot-tile-after-turn.png') })
-
- await expect.poll(() => mock.receivedModels.length, { timeout: 15_000 }).toBeGreaterThan(before)
- const models = mock.receivedModels.slice(before)
- // The bot profile's configured default (config.yaml `model.default`), never
- // the window's manual composer pick.
- expect(models).not.toContain(AMBIENT_PICK)
- expect(models).toContain('mock-model')
-})
diff --git a/apps/desktop/e2e/chat.spec.ts b/apps/desktop/e2e/chat.spec.ts
index 13c2168d21d..83c2cb8cc49 100644
--- a/apps/desktop/e2e/chat.spec.ts
+++ b/apps/desktop/e2e/chat.spec.ts
@@ -91,10 +91,6 @@ test.describe('chat interaction with mock backend', () => {
const composer = page.locator('[contenteditable="true"]').first()
const primary = page.locator('[data-slot="composer-root"] button[type="submit"]')
const queue = page.locator('[data-slot="composer-root"] button[aria-label="Queue message"]')
- const dictation = page.locator('[data-slot="composer-root"] button[aria-label="Voice dictation"]')
- const speakReplies = page.locator(
- '[data-slot="composer-root"] button[aria-label="Read replies aloud"], [data-slot="composer-root"] button[aria-label="Stop reading replies aloud"]'
- )
await composer.click()
await composer.type(BLOCKING_CLARIFY_TRIGGER)
@@ -102,7 +98,6 @@ test.describe('chat interaction with mock backend', () => {
await page.getByText(BLOCKING_CLARIFY_QUESTION).waitFor({ state: 'visible', timeout: 30_000 })
await expect(primary).toHaveAttribute('aria-label', 'Stop')
- await expect(primary.locator('span')).toHaveClass(/bg-current/)
await composer.click()
await composer.type('please answer tersely')
@@ -110,21 +105,8 @@ test.describe('chat interaction with mock backend', () => {
// affordance mid-turn — steer is routed through the submit engine, not a
// separate labeled button. Queue remains the explicit secondary action.
await expect(primary).toHaveAttribute('aria-label', 'Send')
- await expect(dictation).toBeVisible()
- await expect(speakReplies).toBeVisible()
await expect(queue).toBeVisible()
- await expect(queue.locator('svg.tabler-icon-layers-intersect-2')).toBeVisible()
- const controlLabels = await page
- .locator('[data-slot="composer-root"] button')
- .evaluateAll(buttons => buttons.map(button => button.getAttribute('aria-label')))
- const speakRepliesIndex = controlLabels.findIndex(
- label => label === 'Read replies aloud' || label === 'Stop reading replies aloud'
- )
- expect(controlLabels.indexOf('Voice dictation')).toBeLessThan(speakRepliesIndex)
- expect(speakRepliesIndex).toBeLessThan(controlLabels.indexOf('Queue message'))
- expect(controlLabels.indexOf('Queue message')).toBeLessThan(controlLabels.indexOf('Send'))
await page.screenshot({ path: testInfo.outputPath('busy-composer-steer.png') })
- await expect(primary.locator('.codicon-arrow-up')).toBeVisible()
await queue.click()
await expect(primary).toHaveAttribute('aria-label', 'Stop')
diff --git a/apps/desktop/e2e/connectors.spec.ts b/apps/desktop/e2e/connectors.spec.ts
deleted file mode 100644
index 1fb15fe8f56..00000000000
--- a/apps/desktop/e2e/connectors.spec.ts
+++ /dev/null
@@ -1,38 +0,0 @@
-import { expect, test } from './test'
-import { createSandbox, buildAppEnv, launchDesktop } from './fixtures'
-
-const GMAIL = 'Gmail'
-const CALENDAR = 'Google Calendar'
-
-test.describe('flagged connector onboarding', () => {
- test('shows the optional connector controls in a fresh flagged session', async () => {
- const sandbox = createSandbox('connectors-ui')
- const { app, page } = await launchDesktop(buildAppEnv(sandbox, {
- HERMES_GUEST_ONBOARDING: '1'
- }))
-
- try {
- await expect(page.getByText('Connect your apps')).toBeVisible({ timeout: 90_000 })
- await expect(page.getByText(/Connecting is optional/i)).toBeVisible()
- await expect(page.getByRole('button', { name: 'Connect', exact: true }).first()).toBeVisible()
- await expect(page.getByRole('button', { name: 'Not now', exact: true }).first()).toBeVisible()
- await expect(page.getByText(GMAIL)).toBeVisible()
- await expect(page.getByText(CALENDAR)).toBeVisible()
- } finally {
- await app.close().catch(() => undefined)
- sandbox.cleanup()
- }
- })
-
- test('keeps the default surface free of connector authorization controls', async () => {
- const sandbox = createSandbox('connectors-off')
- const { app, page } = await launchDesktop(buildAppEnv(sandbox))
-
- try {
- await expect(page.locator('[data-connector-offer]')).toHaveCount(0)
- } finally {
- await app.close().catch(() => undefined)
- sandbox.cleanup()
- }
- })
-})
diff --git a/apps/desktop/e2e/context-menu-editables.spec.ts b/apps/desktop/e2e/context-menu-editables.spec.ts
deleted file mode 100644
index 5f0c3787ab1..00000000000
--- a/apps/desktop/e2e/context-menu-editables.spec.ts
+++ /dev/null
@@ -1,123 +0,0 @@
-/**
- * Context-menu edit verbs on real editables — the regressions jsdom cannot
- * catch, exercised against the real renderer (real radix focus trap, real
- * React unmount timing, real selection).
- *
- * The class under test: "Select all" from the app context menu must act on
- * the FIELD the menu was opened on, never on the surrounding transcript.
- * The first fix (focus-restore before dispatch) passed unit tests and still
- * failed live because the radix trap steals focus back; the second fix runs
- * selection renderer-side after the trap unmounts. These tests pin the
- * observable outcome, not the mechanism.
- *
- * Menu items are addressed by accessible-name PREFIX (`/^Copy/`): the name
- * includes the shortcut suffix ("Copy Ctrl+V" / "Copy ⌘V"), which is also
- * host-dependent.
- */
-
-import { type MockBackendFixture, setupMockBackend, waitForAppReady } from './fixtures'
-import { expect, test } from './test'
-
-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('select all from the composer context menu selects the draft, not the chat', async () => {
- const page = fixture!.page
- const composer = page.locator('[data-slot="composer-rich-input"]').first()
-
- // Put a message into the transcript so there is chat text a document-wide
- // select-all WOULD grab — the bug this test exists to catch. Wait for the
- // mock reply to COMPLETE: while the turn is busy the composer is in its
- // steer shape and a typed draft does not land in it.
- await composer.click()
- await composer.pressSequentially('transcript anchor message')
- await page.keyboard.press('Enter')
- await page.waitForFunction(() => (document.body.textContent ?? '').includes('mock inference server'), undefined, {
- timeout: 60_000
- })
-
- // Draft text in the composer, then right-click it.
- await composer.click()
- await composer.pressSequentially('draft under selection')
- await composer.click({ button: 'right' })
-
- const selectAll = page.getByRole('menuitem', { name: /^Select all/ })
-
- await selectAll.waitFor({ state: 'visible', timeout: 10_000 })
- await selectAll.click()
-
- // The selection must live inside the composer and cover exactly the draft.
- await expect
- .poll(
- () =>
- page.evaluate(() => {
- const selection = window.getSelection()
- const editable = document.querySelector('[data-slot="composer-rich-input"]')
-
- if (!selection || selection.rangeCount === 0 || !editable) {
- return { inside: false, text: '' }
- }
-
- return {
- inside: editable.contains(selection.getRangeAt(0).commonAncestorContainer),
- text: selection.toString()
- }
- }),
- { timeout: 10_000 }
- )
- .toEqual({ inside: true, text: 'draft under selection' })
-
- // Clear the draft so later tests start clean.
- await page.keyboard.press('Delete')
-})
-
-test('cut, copy, and select all gray out in an empty composer', async () => {
- const page = fixture!.page
- const composer = page.locator('[data-slot="composer-rich-input"]').first()
-
- await composer.click()
- await composer.click({ button: 'right' })
-
- const selectAll = page.getByRole('menuitem', { name: /^Select all/ })
-
- await selectAll.waitFor({ state: 'visible', timeout: 10_000 })
-
- await expect(selectAll).toHaveAttribute('data-disabled', /.*/)
- await expect(page.getByRole('menuitem', { name: /^Cut/ })).toHaveAttribute('data-disabled', /.*/)
- await expect(page.getByRole('menuitem', { name: /^Copy/ })).toHaveAttribute('data-disabled', /.*/)
-
- await page.keyboard.press('Escape')
-})
-
-test('paste enables when the clipboard holds text', async () => {
- const page = fixture!.page
- const composer = page.locator('[data-slot="composer-rich-input"]').first()
-
- // The empty-clipboard branch stays in the unit suite: the e2e app shares
- // the SYSTEM clipboard, and writeText('') does not reliably clear it.
- await page.evaluate(() =>
- (
- window as unknown as { hermesDesktop?: { writeClipboard?: (text: string) => Promise<boolean> } }
- ).hermesDesktop?.writeClipboard?.('clipboard payload')
- )
- await composer.click()
- await composer.click({ button: 'right' })
-
- const paste = page.getByRole('menuitem', { name: /^Paste/ })
-
- await paste.waitFor({ state: 'visible', timeout: 10_000 })
-
- // The clipboard probe is an async IPC — the item enables when it lands.
- await expect.poll(() => paste.getAttribute('data-disabled'), { timeout: 10_000 }).toBeNull()
-
- await page.keyboard.press('Escape')
-})
diff --git a/apps/desktop/e2e/electron-binary.unit.test.ts b/apps/desktop/e2e/electron-binary.unit.test.ts
index c33d8dd49d4..839151c542e 100644
--- a/apps/desktop/e2e/electron-binary.unit.test.ts
+++ b/apps/desktop/e2e/electron-binary.unit.test.ts
@@ -2,23 +2,12 @@ import * as path from 'node:path'
import { describe, expect, it } from 'vitest'
-import { electronBinaryName, electronDistCandidates, pathLookupCommand } from './electron-binary'
+import { electronDistCandidates, pathLookupCommand } from './electron-binary'
// Platform is a parameter everywhere below rather than read from
// process.platform, so the Windows rules are pinned on the Linux CI runner too.
// Reading the real platform would leave every Windows-only rule untested.
-describe('electronBinaryName', () => {
- it('asks for electron.exe on Windows', () => {
- expect(electronBinaryName('win32')).toBe('electron.exe')
- })
-
- it('asks for a bare electron everywhere else', () => {
- expect(electronBinaryName('linux')).toBe('electron')
- expect(electronBinaryName('darwin')).toBe('electron')
- })
-})
-
describe('electronDistCandidates', () => {
const desktop = path.join('repo', 'apps', 'desktop')
const repo = 'repo'
diff --git a/apps/desktop/e2e/fleet-profile-rail.spec.ts b/apps/desktop/e2e/fleet-profile-rail.spec.ts
index 4303b90cd51..9817c9df50b 100644
--- a/apps/desktop/e2e/fleet-profile-rail.spec.ts
+++ b/apps/desktop/e2e/fleet-profile-rail.spec.ts
@@ -279,10 +279,6 @@ test.describe('fleet profile rail — two registered gateways', () => {
[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')
})
@@ -313,23 +309,6 @@ test.describe('fleet profile rail — two registered gateways', () => {
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' })
diff --git a/apps/desktop/e2e/glass-surfaces.spec.ts b/apps/desktop/e2e/glass-surfaces.spec.ts
deleted file mode 100644
index e346e3f8bcc..00000000000
--- a/apps/desktop/e2e/glass-surfaces.spec.ts
+++ /dev/null
@@ -1,350 +0,0 @@
-import * as fs from 'node:fs/promises'
-import * as os from 'node:os'
-import * as path from 'node:path'
-
-import { expect, test } from '@playwright/test'
-import { createServer, type ViteDevServer } from 'vite'
-
-const desktop = path.resolve(import.meta.dirname, '..')
-let server: ViteDevServer
-let scratch: string
-let url: string
-
-test.beforeAll(async () => {
- scratch = await fs.mkdtemp(path.join(os.tmpdir(), 'hermes-glass-'))
- // Match the existing component-browser fixtures without sharing Vite's cache.
- Object.assign(globalThis, { __dirname: desktop })
- server = await createServer({
- root: desktop,
- configFile: path.join(desktop, 'vite.config.ts'),
- configLoader: 'runner',
- cacheDir: path.join(scratch, 'node_modules/.vite'),
- server: { host: '127.0.0.1', port: 0, strictPort: false },
- optimizeDeps: { entries: ['scripts/fixtures/glass-surfaces.html'] }
- })
- await server.listen()
- url = `${server.resolvedUrls!.local[0]}scripts/fixtures/glass-surfaces.html`
-})
-
-test.afterAll(async () => {
- await server?.close()
-
- if (scratch) {
- await fs.rm(scratch, { recursive: true, force: true })
- }
-})
-
-test('glass tabs fade the label beneath the close button without repainting the field', async ({ page }) => {
- await page.goto(url)
- const tab = page.getByTestId('active-tab')
- const close = tab.getByRole('button', { name: 'Close', exact: true })
- await expect(tab).toBeVisible()
-
- for (const id of ['active-tab', 'idle-tab', 'fixed-tab']) {
- expect(await page.getByTestId(id).evaluate(el => getComputedStyle(el).backgroundColor)).toBe('rgba(0, 0, 0, 0)')
- }
-
- const bounds = await tab.boundingBox()
- await tab.hover()
- await expect(close).toBeVisible()
- expect(await close.evaluate(el => getComputedStyle(el).backgroundColor)).toBe('rgba(0, 0, 0, 0)')
-
- const mask = await tab.getByText('A long session title', { exact: false }).evaluate(el => {
- const masks = []
-
- for (let node: Element | null = el; node && !node.hasAttribute('data-testid'); node = node.parentElement) {
- masks.push(getComputedStyle(node).maskImage)
- }
-
- return masks.find(value => value !== 'none')
- })
-
- expect(mask).toContain('linear-gradient')
- expect(await tab.boundingBox()).toEqual(bounds)
-
- // Paint a continuous marker through the real label slot to test the mask's
- // pixels, not just the existence of a gradient. The close glyph is hidden so
- // its paint cannot be mistaken for label bleed-through.
- const sample = await tab.evaluate(el => {
- const content = el.querySelector<HTMLElement>('.pane-tab-content')!
- const button = el.querySelector<HTMLButtonElement>('button[aria-label="Close"]')!
- content.style.background = '#ff0000'
- button.style.visibility = 'hidden'
- const bounds = content.getBoundingClientRect()
- const closeBounds = button.getBoundingClientRect()
-
- return {
- y: Math.floor(bounds.top + 2),
- solid: Math.floor(bounds.left + 2),
- fade: Math.floor(closeBounds.left - 7),
- covered: Math.floor(closeBounds.left + 3)
- }
- })
-
- await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))))
- const pixels = await page.screenshot({ omitBackground: true, path: test.info().outputPath('masked-tab.png') })
-
- const alpha = await page.evaluate(
- async ({ image, points }) => {
- const img = new Image()
- img.src = image
- await img.decode()
- const canvas = document.createElement('canvas')
- canvas.width = img.width
- canvas.height = img.height
- const context = canvas.getContext('2d')!
- context.drawImage(img, 0, 0)
-
- return [points.solid, points.fade, points.covered].map(x => context.getImageData(x, points.y, 1, 1).data[3])
- },
- { image: `data:image/png;base64,${pixels.toString('base64')}`, points: sample }
- )
-
- expect(alpha[0]).toBeGreaterThan(alpha[1])
- expect(alpha[1]).toBeGreaterThan(alpha[2])
- expect(alpha[2]).toBeLessThan(128)
- await tab.evaluate(el => {
- el.querySelector<HTMLElement>('.pane-tab-content')!.style.removeProperty('background')
- el.querySelector<HTMLButtonElement>('button[aria-label="Close"]')!.style.removeProperty('visibility')
- })
- // The active underline remains on the tab itself, without a second stroke
- // on the close button increasing its opacity.
- expect(await tab.evaluate(el => getComputedStyle(el).boxShadow)).toContain('inset')
- await close.click()
- await expect(page.locator('body')).toHaveAttribute('data-closed', 'true')
- await expect(page.locator('body')).not.toHaveAttribute('data-activated', 'true')
-
- for (const id of ['idle-tab', 'short-tab', 'selected-tab']) {
- const sampleTab = page.getByTestId(id)
- const before = await sampleTab.boundingBox()
- await sampleTab.hover()
- const content = sampleTab.locator('.pane-tab-content')
- expect(await content.evaluate(el => getComputedStyle(el).maskImage)).toContain('linear-gradient')
- expect(await sampleTab.boundingBox()).toEqual(before)
- expect(
- await sampleTab
- .getByRole('button', { name: 'Close', exact: true })
- .evaluate(el => getComputedStyle(el).backgroundColor)
- ).toBe('rgba(0, 0, 0, 0)')
- }
-
- // Glass scope and tint do not affect the fade. Solid mode still honors each
- // tab's surface token instead of becoming unconditionally transparent.
- await page.evaluate(() => {
- document.documentElement.setAttribute('data-hermes-glass-scope', 'sidebar')
- document.documentElement.style.setProperty('--translucency-glass-keep', '85%')
- })
- expect(await tab.evaluate(el => getComputedStyle(el).backgroundColor)).toBe('rgba(0, 0, 0, 0)')
- await page.evaluate(() => document.documentElement.removeAttribute('data-hermes-glass'))
- expect(await tab.evaluate(el => getComputedStyle(el).backgroundColor)).not.toBe('rgba(0, 0, 0, 0)')
- await tab.hover()
- expect(await tab.locator('.pane-tab-content').evaluate(el => getComputedStyle(el).maskImage)).toContain(
- 'linear-gradient'
- )
-})
-
-test('sticky prompts clip scrolling replies without an opaque backing', async ({ page }) => {
- await page.goto(url)
- const transcript = page.getByTestId('first-transcript')
- const viewport = transcript.locator('[data-slot="aui_thread-viewport"]')
- const prompt = transcript.locator('[data-slot="aui_user-message-root"]').first()
- await expect(prompt).toBeAttached()
- await viewport.evaluate(el => {
- el.scrollTop = 0
- })
- await expect.poll(() => viewport.evaluate(el => el.scrollTop)).toBe(0)
- expect(await prompt.evaluate(el => getComputedStyle(el).backgroundColor)).toBe('rgba(0, 0, 0, 0)')
- await page.evaluate(() => document.documentElement.style.setProperty('--user-bubble-keep', '0%'))
-
- await viewport.evaluate(el => {
- el.scrollTop = 300
- })
- await expect.poll(() => viewport.evaluate(el => el.scrollTop)).toBe(300)
-
- const points = await prompt.evaluate(el => {
- const rect = el.getBoundingClientRect()
- const viewport = el.closest('[data-slot="aui_thread-viewport"]')!.getBoundingClientRect()
-
- return {
- x: Math.floor(rect.left + rect.width / 2),
- gap: Math.floor(viewport.top + 1),
- hidden: Math.floor(rect.top + 8),
- visible: Math.ceil(rect.bottom + 5)
- }
- })
-
- await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))))
- const image = await page.screenshot({ omitBackground: true, path: test.info().outputPath('sticky-mask.png') })
-
- const colors = await page.evaluate(
- async ({ image, points }) => {
- const bitmap = new Image()
- bitmap.src = image
- await bitmap.decode()
- const canvas = document.createElement('canvas')
- canvas.width = bitmap.width
- canvas.height = bitmap.height
- const context = canvas.getContext('2d')!
- context.drawImage(bitmap, 0, 0)
-
- return [points.gap, points.hidden, points.visible].map(y =>
- Array.from(context.getImageData(points.x, y, 1, 1).data)
- )
- },
- { image: `data:image/png;base64,${image.toString('base64')}`, points }
- )
-
- expect(colors[0][3]).toBeLessThan(128)
- expect(colors[1][3]).toBeLessThan(128)
- expect(colors[2]).toEqual([255, 0, 0, 255])
-
- const clipEdge = () =>
- transcript
- .locator('[data-slot="aui_assistant-message-root"]')
- .first()
- .evaluate(el => {
- const rect = el.getBoundingClientRect()
- const clip = Number.parseFloat(getComputedStyle(el).getPropertyValue('--sticky-prompt-clip'))
-
- const prompt = el
- .closest('[data-slot="aui_message-group"]')!
- .querySelector('[data-slot="aui_user-message-root"]')!
-
- return Math.abs(rect.top + clip - prompt.getBoundingClientRect().bottom)
- })
-
- await expect.poll(clipEdge).toBeLessThan(1)
-
- const clips = await page.evaluate(async () => {
- const transcript = document.querySelector('[data-testid="first-transcript"]')!
- const reply = transcript.querySelector<HTMLElement>('[data-slot="aui_assistant-message-root"]')!
- const read = () => getComputedStyle(reply).clipPath
- const before = read()
- document.querySelector<HTMLButtonElement>('[data-testid="first-transcript-append"]')!.click()
- const samples = [read()]
-
- for (let i = 0; i < 3; i++) {
- await new Promise(requestAnimationFrame)
- samples.push(read())
- }
-
- return { before, samples }
- })
-
- expect(clips.before).not.toBe('none')
- expect(clips.samples.every(value => value !== 'none')).toBe(true)
-
- // Expanding a pinned prompt must move the clip without needing a scroll.
- await prompt.getByRole('button').click()
- await expect.poll(() => prompt.getByRole('button').evaluate(el => el.getBoundingClientRect().height)).toBe(140)
- await expect.poll(clipEdge).toBeLessThan(1)
-
- // A larger secondary-window titlebar offset moves both the sticky and clip.
- await viewport.evaluate(el => el.style.setProperty('--sticky-human-top', '55px'))
- await viewport.evaluate(el => {
- el.scrollTop = 301
- })
- await expect.poll(clipEdge).toBeLessThan(1)
-
- // Scroll back through attachments and out of the pinned state. Nothing may
- // remain clipped, and the other pane's independently pinned reply is intact.
- await viewport.evaluate(el => el.style.removeProperty('--sticky-human-top'))
- await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))))
- await viewport.evaluate(el => {
- el.scrollTop = 0
- })
- await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))))
- await expect.poll(() => transcript.locator('[data-sticky-prompt-clip]').count()).toBe(0)
- await expect(transcript.getByTestId('attachment').first()).toBeVisible()
- const other = page.getByTestId('second-transcript')
- expect(await other.locator('[data-slot="aui_thread-viewport"]').evaluate(el => el.scrollTop)).toBeGreaterThan(0)
- expect(await other.locator('[data-sticky-prompt-clip]').count()).toBeGreaterThan(0)
-
- // Enter another turn via a large jump (including virtualized history), then
- // return: stale clip styles must leave the previous turn.
- await viewport.evaluate(el => {
- el.scrollTop = 1400
- })
- await expect.poll(() => transcript.locator('[data-sticky-prompt-clip]').count()).toBeGreaterThan(0)
- await viewport.evaluate(el => {
- el.scrollTop = 0
- })
- await expect.poll(() => transcript.locator('[data-sticky-prompt-clip]').count()).toBe(0)
-
- // A standalone reply can still occupy the gap below a secondary titlebar
- // when the following prompt pins. It must be clipped across group boundaries.
- await page.goto(`${url}?preceding`)
- const gapViewport = page.getByTestId('first-transcript').locator('[data-slot="aui_thread-viewport"]')
- await gapViewport.locator('[data-slot="aui_user-message-root"]').first().waitFor({ state: 'attached' })
- await gapViewport.evaluate(el => {
- el.scrollTop = 0
- })
- await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))))
-
- const gapScroll = await gapViewport.evaluate(el => {
- el.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true }))
- el.style.setProperty('--sticky-human-top', '55px')
- const group = el.querySelector('[data-slot="aui_user-message-root"]')!.closest('[data-slot="aui_message-group"]')!
- const target = el.scrollTop + group.getBoundingClientRect().top - el.getBoundingClientRect().top - 45
- el.scrollTop = target
-
- return el.scrollTop
- })
-
- await expect.poll(() => gapViewport.evaluate(el => el.scrollTop)).toBe(gapScroll)
- await page.evaluate(() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve))))
-
- const gapClear = () =>
- gapViewport.evaluate(el => {
- const previous = el.querySelector('[data-slot="aui_assistant-message-root"]')!
- const bounds = el.getBoundingClientRect()
- const x = bounds.left + bounds.width / 2
- const hit = document.elementFromPoint(x, bounds.top + 34)
-
- return { hidden: !previous.contains(hit), clip: getComputedStyle(previous).clipPath }
- })
-
- await expect.poll(async () => (await gapClear()).hidden).toBe(true)
- expect((await gapClear()).clip).not.toBe('none')
-
- // Exercise the production message/edit components as well as the colored
- // clipping markers. Editing replaces the prompt with a display:contents root.
- await page.goto(`${url}?real`)
- const realViewport = page.getByTestId('first-transcript').locator('[data-slot="aui_thread-viewport"]')
- await realViewport.locator('[data-slot="aui_assistant-message-root"]').first().waitFor()
- await realViewport
- .locator('[data-slot="aui_assistant-message-root"]')
- .first()
- .evaluate(el => {
- el.style.height = '900px'
- })
- await realViewport.evaluate(el => {
- el.scrollTop = 300
- })
- const realPrompt = realViewport.locator('[data-slot="aui_user-message-root"]').first()
- await realPrompt.getByRole('button', { name: 'Edit message', exact: true }).click()
- const editor = realViewport.getByRole('textbox', { name: 'Edit message', exact: true })
- await expect(editor).toBeVisible()
- await editor.fill('Expanded editable prompt\n'.repeat(8))
- await realViewport.evaluate(el => {
- el.scrollTop = 400
- })
- await expect
- .poll(() =>
- realViewport
- .locator('[data-slot="aui_assistant-message-root"]')
- .first()
- .evaluate(el => {
- const prompt = el
- .closest('[data-slot="aui_message-group"]')!
- .querySelector('[data-slot="aui_user-message-root"]')!
-
- return Math.abs(
- el.getBoundingClientRect().top +
- Number.parseFloat(getComputedStyle(el).getPropertyValue('--sticky-prompt-clip')) -
- prompt.getBoundingClientRect().bottom
- )
- })
- )
- .toBeLessThan(1)
-})
diff --git a/apps/desktop/e2e/glyph-spinner.spec.ts b/apps/desktop/e2e/glyph-spinner.spec.ts
deleted file mode 100644
index c7228eafd63..00000000000
--- a/apps/desktop/e2e/glyph-spinner.spec.ts
+++ /dev/null
@@ -1,227 +0,0 @@
-/**
- * E2E contract for the compositor-only GlyphSpinner.
- *
- * The spinner's whole reason for existing in this shape is a CSS animation:
- * every frame is in the DOM from mount and a `transform` keyframes animation
- * scrolls between them, so there is no JS timer and no per-tick DOM mutation
- * scheduling document-scale style recalculation.
- *
- * None of that is observable in jsdom — it has no animation engine, no
- * cascade resolution for `steps()`, and no `Element.getAnimations()`. The
- * jsdom suite (src/components/ui/glyph-spinner.test.tsx) therefore pins the
- * DATA and WIRING, and this spec pins the RENDERED BEHAVIOUR in a real
- * browser, which is the only place the stylesheet actually runs.
- *
- * This replaces three tests that asserted on the TEXT of the stylesheet.
- * Reading source in a test is banned outright (AGENTS.md) and those tests
- * proved the point: a var()-fallback edit that changed no rendered pixel
- * broke one of them, while none of them had ever executed the CSS.
- *
- * Prerequisite: `npm run build` must have been run so dist/ exists.
- */
-
-import { expect, type Page, test } from '@playwright/test'
-
-import { type MockBackendFixture, setupMockBackend, waitForAppReady } from './fixtures'
-
-/* Scope to a spinner that is actually RUNNING. Turns from earlier tests in
- * this file leave parked spinners mounted (kept-alive panes, swap overlays
- * hold them with data-paused='true'), and document.querySelector returns the
- * FIRST strip in the DOM — a stale parked one once two turns have run. */
-const STRIP = '.glyph-spinner:not([data-paused="true"]) .glyph-spinner__strip'
-
-/** Prompt the mock server holds open so the spinner runs for the whole file. */
-const SPINNER_PROMPT = 'E2E_GLYPH_SPINNER_HOLD'
-
-/**
- * Get a RUNNING frame strip into the DOM deterministically.
- *
- * A turn is sent so the app is genuinely busy (the mock server holds the
- * stream open), but which surface mounts a spinner mid-turn is app policy
- * that has changed before and will again — the transcript, status stack and
- * swap overlay all park/unmount theirs at different moments, which made this
- * spec racy. The contract under test is the STYLESHEET (steps() animation,
- * layer promotion, the data-paused and global pause gates), and that CSS is
- * driven entirely by the `data-paused` attribute — the same attribute the
- * parked assertions below already toggle. So: wait for any mounted spinner
- * (the ChatSwapOverlay keeps one mounted, parked, after boot), then unpark it
- * and assert against the running animation.
- */
-async function mountSpinner(page: Page): Promise<void> {
- if (await page.locator(STRIP).count()) {
- return
- }
-
- const composer = page.locator('[contenteditable="true"]').first()
- await composer.waitFor({ state: 'visible', timeout: 10_000 })
- await composer.click()
- await composer.type(SPINNER_PROMPT, { delay: 10 })
- await page.keyboard.press('Enter')
-
- await page.waitForSelector('.glyph-spinner__strip', { state: 'attached', timeout: 20_000 })
- await page.evaluate(() => {
- for (const el of document.querySelectorAll('.glyph-spinner[data-paused]')) {
- el.removeAttribute('data-paused')
- }
- })
- await page.waitForSelector(STRIP, { state: 'attached', timeout: 20_000 })
-}
-
-test.describe('GlyphSpinner (compositor animation)', () => {
- let fixture: MockBackendFixture
-
- test.beforeAll(async () => {
- fixture = await setupMockBackend({
- mockServer: { holdFirstStreamForPrompt: SPINNER_PROMPT },
- })
- await waitForAppReady(fixture)
- })
-
- test.afterAll(async () => {
- fixture?.mock.releaseHeldStream()
- await fixture?.cleanup()
- })
-
- test('animates with a steps() transform keyframes animation, one step per frame', async () => {
- const { page } = fixture
- await mountSpinner(page)
-
- const observed = await page.evaluate(strip => {
- const el = document.querySelector<HTMLElement>(strip)
-
- if (!el) {
- throw new Error('no frame strip in the DOM')
- }
-
- const style = getComputedStyle(el)
- const animations = el.getAnimations()
-
- return {
- frameCount: el.querySelectorAll('.glyph-spinner__frame').length,
- timingFunction: style.animationTimingFunction,
- iterationCount: style.animationIterationCount,
- durationMs: animations[0]?.effect?.getTiming().duration ?? null,
- names: animations.map(a => (a as CSSAnimation).animationName),
- // A percentage translate makes the animation layout-dependent, which
- // Chromium refuses to composite. Read the engine's own keyframes: a
- // revert to translateY(-100%) shows up here, while the computed
- // `style.transform` always serializes to a matrix and can't tell.
- travel: ((animations[0]?.effect as KeyframeEffect | undefined)?.getKeyframes() ?? [])
- .map(k => String((k as Keyframe & { transform?: string }).transform ?? ''))
- .join(' | ')
- }
- }, STRIP)
-
- // The strip carries every frame; `steps(N)` parks on each one in turn.
- expect(observed.frameCount).toBeGreaterThan(1)
- // Chromium has serialized jump-end as both `steps(N)` and `steps(N, end)`.
- expect(observed.timingFunction).toMatch(new RegExp(`^steps\\(${observed.frameCount}\\b`))
- expect(observed.iterationCount).toBe('infinite')
- expect(observed.names).toContain('glyph-spinner-advance')
- // One full cycle is frames x interval, so the duration must be a positive
- // multiple of the frame count — not the single-frame interval.
- expect(observed.durationMs).toBeGreaterThan(0)
- // Length-typed travel, never a percentage: `translateY(-100%)` would keep
- // the animation off the compositor. Chromium has serialized the resolved
- // keyframe both as the authored `calc(...)` and as an absolute `...px`
- // length depending on version — accept any length, reject percentages.
- expect(observed.travel).toMatch(/calc\(|px\)/)
- expect(observed.travel).not.toContain('%')
- })
-
- test('is promoted to a layer while running, and neither animates nor holds a layer when parked', async () => {
- const { page } = fixture
- await mountSpinner(page)
-
- const running = await page.evaluate(strip => {
- const el = document.querySelector<HTMLElement>(strip)!
-
- return {
- playState: getComputedStyle(el).animationPlayState,
- willChange: getComputedStyle(el).willChange
- }
- }, STRIP)
-
- expect(running.playState).toBe('running')
- // Scoped to active spinners — a permanently promoted layer per parked
- // spinner is pure memory at fan-out breadth.
- expect(running.willChange).toBe('transform')
-
- // 1. The per-spinner gate: a kept-alive but inactive pane, or an explicit
- // `paused` prop (ChatSwapOverlay's fade-out).
- const parked = await page.evaluate(strip => {
- const el = document.querySelector<HTMLElement>(strip)!
- const viewport = el.closest<HTMLElement>('.glyph-spinner')!
- const previous = viewport.getAttribute('data-paused')
-
- viewport.setAttribute('data-paused', 'true')
-
- const state = {
- playState: getComputedStyle(el).animationPlayState,
- willChange: getComputedStyle(el).willChange
- }
-
- if (previous === null) {
- viewport.removeAttribute('data-paused')
- } else {
- viewport.setAttribute('data-paused', previous)
- }
-
- return state
- }, STRIP)
-
- expect(parked.playState).toBe('paused')
- expect(parked.willChange).toBe('auto')
-
- // 2. The global gate: window minimize / document-hidden, which
- // main.tsx drives by arming this attribute on the root. Visible windows
- // keep animating even when another app has focus.
- const globallyPaused = await page.evaluate(strip => {
- const root = document.documentElement
- const had = root.hasAttribute('data-renderer-animations-paused')
-
- root.setAttribute('data-renderer-animations-paused', '')
- const playState = getComputedStyle(document.querySelector<HTMLElement>(strip)!).animationPlayState
-
- if (!had) {
- root.removeAttribute('data-renderer-animations-paused')
- }
-
- return playState
- }, STRIP)
-
- expect(globallyPaused).toBe('paused')
- })
-
- test('advances in discrete frames and creates no timer-driven DOM churn', async () => {
- const { page } = fixture
- await mountSpinner(page)
-
- // Sample the resolved transform across one full cycle. A steps() animation
- // holds each value for a whole interval and jumps between them, so the
- // distinct values it visits must be bounded by the frame count — a linear
- // animation would produce a new value on every sample.
- const sampled = await page.evaluate(async strip => {
- const el = document.querySelector<HTMLElement>(strip)!
- const frames = el.querySelectorAll('.glyph-spinner__frame').length
- const duration = Number(el.getAnimations()[0]?.effect?.getTiming().duration ?? 0)
- const seen = new Set<string>()
- const textAtStart = el.textContent
-
- const deadline = performance.now() + duration
-
- while (performance.now() < deadline) {
- seen.add(getComputedStyle(el).transform)
- await new Promise(resolve => requestAnimationFrame(() => resolve(null)))
- }
-
- return { distinct: seen.size, frames, textUnchanged: el.textContent === textAtStart }
- }, STRIP)
-
- expect(sampled.distinct).toBeGreaterThan(1)
- expect(sampled.distinct).toBeLessThanOrEqual(sampled.frames + 1)
- // The old implementation rewrote textContent ~12x/second. Nothing may
- // mutate the DOM as this animates — that mutation is the whole incident.
- expect(sampled.textUnchanged).toBe(true)
- })
-})
diff --git a/apps/desktop/e2e/group-approval-click-submits.spec.ts b/apps/desktop/e2e/group-approval-click-submits.spec.ts
deleted file mode 100644
index 9c78e413c43..00000000000
--- a/apps/desktop/e2e/group-approval-click-submits.spec.ts
+++ /dev/null
@@ -1,128 +0,0 @@
-import { APPROVAL_COMMAND_TRIGGER, MOCK_REPLY } from '../../../tests-js/scripts/mock-server'
-
-import { type MockBackendFixture, setupMockBackend, waitForAppReady } from './fixtures'
-import { expect, test } from './test'
-
-// #91706: a command-approval card in a Bot Mode group room could highlight
-// the clicked choice but never send it — the footer "Respond" button was
-// off-screen or covered, so the member's hidden session stayed blocked until
-// the approval expired. Approvals are a closed choice set: the click IS the
-// answer. Driven against the real Electron app, a real gateway with
-// `approvals: mode: "manual"`, and mock inference that runs a gated
-// `rm -rf` through the real terminal tool.
-
-const ROOM = 'Programmer, Reviewer'
-let fixture: MockBackendFixture | null = null
-
-async function openBots(page: MockBackendFixture['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()
-}
-
-async function createAgent(page: MockBackendFixture['page'], name: string, title: string): Promise<void> {
- await page.getByRole('button', { name: 'New bot or group chat' }).click()
- await page.getByRole('menuitem', { name: 'New Bot' }).click()
-
- const dialog = page.getByRole('dialog', { name: 'New Bot' })
- await dialog.getByPlaceholder('inbox-triage').fill(name)
- await dialog.getByPlaceholder('Inbox Triage').fill(title)
- await dialog.getByRole('button', { name: 'Create Bot' }).click()
- await expect(dialog).toBeHidden({ timeout: 30_000 })
- await expect(page.getByRole('button', { name: new RegExp(`^${title}\\b`) }).first()).toBeVisible({ timeout: 30_000 })
-}
-
-async function createRoom(page: MockBackendFixture['page']) {
- await openBots(page)
- await createAgent(page, 'programmer', 'Programmer')
- await createAgent(page, 'reviewer', 'Reviewer')
-
- await page.getByRole('button', { name: 'New bot or group chat' }).click()
- await page.getByRole('menuitem', { name: 'New Group Chat' }).click()
-
- const dialog = page.getByRole('dialog', { name: 'New Group Chat' })
-
- for (const title of ['Programmer', 'Reviewer']) {
- await dialog.getByText(title, { exact: true }).locator('xpath=ancestor::label').getByRole('checkbox').click()
- }
-
- await dialog.getByRole('textbox', { name: 'Group name' }).fill(ROOM)
- await dialog.getByRole('button', { name: 'Create Group (2)' }).click()
-
- const groupTab = page.getByRole('tab', { name: new RegExp(`${ROOM} Close`) })
- const groupComposer = page.getByRole('textbox', { name: `Message ${ROOM}` }).filter({ visible: true })
- await expect(groupTab).toBeVisible({ timeout: 20_000 })
- await expect(groupTab).toHaveAttribute('aria-selected', 'true')
- await expect(groupComposer).toBeVisible()
-
- return groupComposer
-}
-
-test.beforeEach(async () => {
- fixture = await setupMockBackend({ extraConfig: 'approvals:\n mode: "manual"\n' })
- await waitForAppReady(fixture, 120_000)
-})
-
-test.afterEach(async () => {
- await fixture?.cleanup()
- fixture = null
-})
-
-test('clicking an approval choice in a group room submits it (#91706)', async () => {
- test.setTimeout(240_000)
- const page = fixture!.page
- // Count approval.respond frames on the real gateway socket.
- await page.evaluate(() => {
- const send = WebSocket.prototype.send
-
- ;(window as any).__approvalResponds = [] as string[]
-
- WebSocket.prototype.send = function (data) {
- const frame = JSON.parse(String(data))
-
- if (frame.method === 'approval.respond') {
- ;(window as any).__approvalResponds.push(JSON.stringify(frame.params))
- }
-
- return send.call(this, data)
- }
- })
- const groupComposer = await createRoom(page)
-
- await groupComposer.fill(`@programmer ${APPROVAL_COMMAND_TRIGGER}`)
- await groupComposer.press('Enter')
-
- // The member's gated terminal command surfaces as an approval card in the
- // ROOM. Assert inside the room's own card: the same approval also reaches
- // the Desktop's session-level approval surface, and a build that switches
- // tabs on it would otherwise fail here on visibility instead of on the
- // contract below (the click must be the submit).
- const groupTab = page.getByRole('tab', { name: new RegExp(`${ROOM} Close`) })
- const card = page.getByText(/wants to run a command/).locator('xpath=..')
- const once = card.getByRole('button', { name: 'once', exact: true })
-
- await expect(async () => {
- if ((await groupTab.getAttribute('aria-selected')) !== 'true') {
- await groupTab.click()
- }
-
- await expect(card).toBeVisible({ timeout: 5_000 })
- }).toPass({ timeout: 90_000 })
- await expect(once).toBeVisible()
- console.log('APPROVAL CARD: visible; responds so far =', await page.evaluate(() => (window as any).__approvalResponds.length))
- await page.screenshot({ path: test.info().outputPath('approval-card.png') })
-
- await once.click()
-
- // One approval.respond leaves the Desktop for the click itself — no second
- // "Respond" click required (there is none to click for approvals).
- await expect.poll(() => page.evaluate(() => (window as any).__approvalResponds.length), { timeout: 15_000 }).toBe(1)
- await expect(card.getByRole('button', { name: 'Respond', exact: true })).toHaveCount(0)
- expect(await page.evaluate(() => (window as any).__approvalResponds[0])).toContain('once')
-
- // The blocked member resumes: the command runs and its reply lands in the room.
- await expect(page.getByText(MOCK_REPLY, { exact: true }).first()).toBeVisible({ timeout: 90_000 })
- await expect(once).toHaveCount(0)
- console.log('APPROVAL: submitted on click; responds =', await page.evaluate(() => (window as any).__approvalResponds))
- await page.screenshot({ path: test.info().outputPath('approval-after.png') })
-})
diff --git a/apps/desktop/e2e/group-chat-code-block-and-media.spec.ts b/apps/desktop/e2e/group-chat-code-block-and-media.spec.ts
deleted file mode 100644
index 945e52e913d..00000000000
--- a/apps/desktop/e2e/group-chat-code-block-and-media.spec.ts
+++ /dev/null
@@ -1,172 +0,0 @@
-import fs from 'node:fs'
-import os from 'node:os'
-import path from 'node:path'
-
-import { type MockBackendFixture, setupMockBackend, waitForAppReady } from './fixtures'
-import { expect, test } from './test'
-
-// A bot's group-chat reply was rendered through raw Streamdown, whose stock
-// code block lays its header and body out as inline siblings: the code body
-// sat shifted right by the header's width and the wrapper's overflow-hidden
-// clipped the tail with no scrollbar (#91878). The same raw path never ran the
-// Desktop's `MEDIA:` transform, so a bot's `MEDIA:/path/file.png` showed as
-// a plain path instead of an inline image/player (#93728). Group replies now
-// go through the same message renderer as the 1:1 chat.
-
-const SHOT_DIR = path.join(os.tmpdir(), 'batchbots/panes-layout-cron-tile/shots')
-// One unbroken 600+ char token: it cannot wrap, so it MUST overflow the
-// message column — the probe asserts that overflow exists before asserting
-// nothing clips it (a line that fits proves nothing about #91878).
-const LONG_LINE = `const veryLongIdentifierNameForTheGroupChatCodeBlockRepro_${'x'.repeat(600)} = 1`
-// 1x1 PNG.
-const PNG_BASE64 = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg=='
-
-let fixture: MockBackendFixture | null = null
-let mediaPath = ''
-
-function codeReply(): string {
- return ['Here is the draft:', '', '```ts', LONG_LINE, 'export {}', '```', '', `MEDIA:${mediaPath}`].join('\n')
-}
-
-async function openBots(page: MockBackendFixture['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()
-}
-
-async function createAgent(page: MockBackendFixture['page'], name: string, title: string): Promise<void> {
- await page.getByRole('button', { name: 'New bot or group chat' }).click()
- await page.getByRole('menuitem', { name: 'New Bot' }).click()
-
- const dialog = page.getByRole('dialog', { name: 'New Bot' })
- await dialog.getByPlaceholder('inbox-triage').fill(name)
- await dialog.getByPlaceholder('Inbox Triage').fill(title)
- await dialog.getByRole('button', { name: 'Create Bot' }).click()
- await expect(dialog).toBeHidden({ timeout: 30_000 })
- await expect(page.getByRole('button', { name: new RegExp(`^${title}\\b`) }).first()).toBeVisible({ timeout: 30_000 })
-}
-
-async function createRoom(page: MockBackendFixture['page']) {
- await openBots(page)
- await createAgent(page, 'writer', 'Writer')
- await createAgent(page, 'editor', 'Editor')
-
- await page.getByRole('button', { name: 'New bot or group chat' }).click()
- await page.getByRole('menuitem', { name: 'New Group Chat' }).click()
-
- const dialog = page.getByRole('dialog', { name: 'New Group Chat' })
-
- for (const title of ['Writer', 'Editor']) {
- await dialog.getByText(title, { exact: true }).locator('xpath=ancestor::label').getByRole('checkbox').click()
- }
-
- await dialog.getByRole('textbox', { name: 'Group name' }).fill('Writer, Editor')
- await dialog.getByRole('button', { name: 'Create Group (2)' }).click()
-
- const composer = page.getByRole('textbox', { name: 'Message Writer, Editor' }).filter({ visible: true })
- await expect(composer).toBeVisible({ timeout: 20_000 })
-
- return composer
-}
-
-test.beforeEach(async () => {
- fixture = await setupMockBackend({
- mockServer: {
- replyForPrompt: prompt => (prompt.includes('CODE_BLOCK_REPRO') ? codeReply() : 'ok')
- }
- })
- mediaPath = path.join(fixture.sandbox.hermesHome, 'group-media.png')
- fs.writeFileSync(mediaPath, Buffer.from(PNG_BASE64, 'base64'))
- fs.mkdirSync(SHOT_DIR, { recursive: true })
- await waitForAppReady(fixture, 120_000)
-})
-
-test.afterEach(async () => {
- await fixture?.cleanup()
- fixture = null
-})
-
-test('a group reply renders its code block inside the message and its MEDIA: line as inline media', async () => {
- test.setTimeout(300_000)
- const page = fixture!.page
- const composer = await createRoom(page)
-
- await composer.fill('@writer CODE_BLOCK_REPRO')
- await composer.press('Enter')
-
- // A bot created moments ago runs its intro turn in the background; when it
- // lands, the roster fronts that bot's chat tab and yanks the center away
- // from the room. Re-select the room and read the reply from a room body.
- const roomTab = page.getByRole('tab', { name: /Writer, Editor Close/ })
-
- const code = page
- .locator('[data-selectable-text="true"]')
- .getByText(/veryLongIdentifierNameForTheGroupChatCodeBlockRepro/)
- .filter({ visible: true })
- .first()
-
- await expect(async () => {
- if ((await roomTab.getAttribute('aria-selected')) !== 'true') {
- await roomTab.click()
- }
-
- await expect(code).toBeVisible({ timeout: 5_000 })
- }).toPass({ timeout: 90_000 })
- await expect(page.getByRole('button', { name: 'Stop', exact: true })).toHaveCount(0, { timeout: 60_000 })
- await page.screenshot({ path: path.join(SHOT_DIR, 'group-chat-code-media.png') })
-
- const geometry = await code.evaluate(el => {
- const body = el.closest<HTMLElement>('[data-selectable-text="true"]')!
- const bodyRect = body.getBoundingClientRect()
- const pre = el.closest('pre') ?? el
- const preRect = pre.getBoundingClientRect()
- // Every box between the code text and the message body: a box whose
- // content is wider than itself must scroll, never clip — that is the
- // "cut off with no horizontal scrollbar" the report describes.
- const chain: Array<{ tag: string; overflowX: string; scrollWidth: number; clientWidth: number }> = []
- let node: HTMLElement | null = el as HTMLElement
-
- while (node && node !== body.parentElement) {
- chain.push({
- tag: node.tagName.toLowerCase(),
- overflowX: getComputedStyle(node).overflowX,
- scrollWidth: node.scrollWidth,
- clientWidth: node.clientWidth
- })
- node = node.parentElement
- }
-
- const clippedWithoutScroll = chain.filter(
- box => box.scrollWidth > box.clientWidth + 1 && !['auto', 'scroll'].includes(box.overflowX)
- )
-
- const scrollingPre = chain.find(
- box => box.tag === 'pre' && box.scrollWidth > box.clientWidth + 1 && ['auto', 'scroll'].includes(box.overflowX)
- )
-
- return {
- body: { left: bodyRect.left, right: bodyRect.right },
- pre: { left: preRect.left, right: preRect.right, width: preRect.width },
- chain,
- clippedWithoutScroll,
- scrollingPre,
- rawMedia: body.textContent?.includes('MEDIA:') ?? false,
- inlineMedia: Boolean(body.querySelector('img, audio, video'))
- }
- })
-
- console.log('GROUP CODE BLOCK GEOMETRY', JSON.stringify(geometry))
- // The fixture really overflows and the code block scrolls to show it...
- expect.soft(geometry.scrollingPre).toBeDefined()
- // ...while staying inside the message column...
- expect.soft(geometry.pre.right).toBeLessThanOrEqual(geometry.body.right + 1)
- // ...and no box between the code and the message clips text it cannot scroll.
- expect.soft(geometry.clippedWithoutScroll).toEqual([])
- // MEDIA: renders as media, never as the raw directive.
- expect.soft(geometry.rawMedia).toBe(false)
- expect.soft(geometry.inlineMedia).toBe(true)
-})
diff --git a/apps/desktop/e2e/group-composer-auto-grow.spec.ts b/apps/desktop/e2e/group-composer-auto-grow.spec.ts
deleted file mode 100644
index 009ab7bb579..00000000000
--- a/apps/desktop/e2e/group-composer-auto-grow.spec.ts
+++ /dev/null
@@ -1,151 +0,0 @@
-import fs from 'node:fs'
-import path from 'node:path'
-
-import { startMockServer } from '../../../tests-js/scripts/mock-server'
-
-import {
- buildAppEnv,
- createSandbox,
- launchDesktop,
- type MockBackendFixture,
- waitForAppReady,
- writeEnvFile,
- writeMockProviderConfig
-} from './fixtures'
-import { RealSessionBuilder } from './real-session-builder'
-import { expect, test } from './test'
-
-// The group-room composer starts as one compact row, grows with wrapped text
-// and newlines so a long brief can be read back while drafting, and stops at
-// min(50vh, 24rem) — past that the textarea scrolls internally so the room
-// transcript keeps its space (hermes-agent#95300).
-
-type Page = MockBackendFixture['page']
-
-let fixture: MockBackendFixture | null = null
-
-// GROUP_COMPOSER_SCREENSHOT_DIR=<dir> saves full-window captures at the key
-// states — PR evidence; never part of the assertions.
-async function capture(page: Page, name: string): Promise<void> {
- const dir = process.env.GROUP_COMPOSER_SCREENSHOT_DIR
-
- if (!dir) {
- return
- }
-
- fs.mkdirSync(dir, { recursive: true })
- await page.screenshot({ path: path.join(dir, `${name}.png`) })
-}
-
-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()
- }
-}
-
-const ROOM = 'Standup'
-
-test.beforeAll(async () => {
- const mock = await startMockServer()
- const sandbox = createSandbox('bots-group-composer')
- writeMockProviderConfig(sandbox.hermesHome, mock.url)
- writeEnvFile(sandbox.hermesHome)
-
- for (const name of ['alpha', 'beta']) {
- await seedBot(sandbox.hermesHome, mock.url, name)
- }
-
- 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('the group composer grows with a long prompt and stops at the viewport cap', async () => {
- test.setTimeout(300_000)
- const page = fixture!.page
-
- 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()
- await expect(page.locator('[data-roster-key="local::alpha"]')).toBeVisible({ timeout: 30_000 })
-
- await page.getByRole('button', { name: 'New bot or group chat' }).click()
- await page.getByRole('menuitem', { name: 'New Group Chat' }).click()
- const dialog = page.getByRole('dialog', { name: 'New Group Chat' })
-
- for (const name of ['Alpha @alpha', 'Beta @beta']) {
- await dialog.getByRole('checkbox', { name }).click()
- }
-
- await dialog.getByRole('textbox', { name: 'Group name' }).fill(ROOM)
- await dialog.getByRole('button', { name: 'Create Group (2)' }).click()
- await expect(dialog).toBeHidden({ timeout: 30_000 })
-
- const composer = page.getByRole('textbox', { name: `Message ${ROOM}` }).filter({ visible: true })
- await expect(composer).toBeVisible({ timeout: 30_000 })
-
- const metrics = () =>
- composer.evaluate(el => {
- const box = el.getBoundingClientRect()
-
- return { height: Math.round(box.height), scrollHeight: el.scrollHeight, clientHeight: el.clientHeight }
- })
-
- const empty = await metrics()
- await capture(page, '1-composer-empty')
-
- // Eight explicit lines: the box must grow well past the single row.
- const brief = Array.from({ length: 8 }, (_, i) => `Brief line ${i + 1}: agree on the release checklist item`).join('\n')
- await composer.fill(brief)
- const grown = await metrics()
- await capture(page, '2-composer-eight-lines')
- expect(grown.height).toBeGreaterThan(empty.height * 3)
- // Content fits: nothing to scroll yet.
- expect(grown.scrollHeight).toBeLessThanOrEqual(grown.clientHeight + 1)
-
- // Far more than fits: growth stops at min(50vh, 24rem) and the text
- // scrolls inside the box instead of taking over the room.
- await composer.fill(Array.from({ length: 80 }, (_, i) => `Line ${i + 1}`).join('\n'))
- const capped = await metrics()
- await capture(page, '3-composer-capped-scrolls')
- const viewport = page.viewportSize() ?? (await page.evaluate(() => ({ height: window.innerHeight, width: 0 })))
- const cap = Math.min(viewport.height / 2, 24 * 16)
- expect(capped.height).toBeLessThanOrEqual(cap + 1)
- expect(capped.height).toBeGreaterThanOrEqual(grown.height)
- expect(capped.scrollHeight).toBeGreaterThan(capped.clientHeight + 40)
-
- // Enter still sends (not a newline): the composer empties back to one row.
- await composer.fill('@alpha hello there')
- await composer.press('Enter')
- await expect.poll(async () => (await metrics()).height).toBe(empty.height)
-})
diff --git a/apps/desktop/e2e/group-create-gate-remote-roster.spec.ts b/apps/desktop/e2e/group-create-gate-remote-roster.spec.ts
deleted file mode 100644
index 917144f563b..00000000000
--- a/apps/desktop/e2e/group-create-gate-remote-roster.spec.ts
+++ /dev/null
@@ -1,216 +0,0 @@
-/**
- * E2E: the New Group Chat menu gate with one local bot plus remote-connection
- * bots (#101543). "This device" is the Electron-managed local backend with
- * only its `default` profile; "Homelab" is a REAL second `hermes serve`
- * registered as a remote URL connection. The gate must count the same
- * selectable set the dialog seats — bots from every registered connection —
- * so 1 local + 1 remote enables New Group Chat and the room can be created.
- */
-
-import { type ChildProcess, spawn, spawnSync } from 'node:child_process'
-import * as fs from 'node:fs'
-import * as net from 'node:net'
-import * as os from 'node:os'
-import * as path from 'node:path'
-
-import { startMockServer } from '../../../tests-js/scripts/mock-server'
-
-import {
- buildAppEnv,
- createSandbox,
- launchDesktop,
- type MockBackendFixture,
- type Sandbox,
- waitForAppReady,
- writeEnvFile,
- writeMockProviderConfig,
-} from './fixtures'
-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-group-gate-homelab-token'
-const SHOTS = path.join(os.tmpdir(), 'batchbots/group-identity-members/shots')
-
-interface RemoteGateway {
- url: string
- close: () => Promise<void>
-}
-
-/** The worktree's own backend: `python -m hermes_cli.main` from the repo root
- * (the venv's `hermes` console script resolves the package it was installed
- * from, which need not be this checkout). */
-function hermesCommand(): { bin: string; args: string[] } {
- const venvPython = path.join(REPO_ROOT, '.venv', 'bin', 'python')
-
- if (fs.existsSync(venvPython)) {
- return { bin: venvPython, args: ['-m', 'hermes_cli.main'] }
- }
-
- const result = spawnSync('which', ['hermes'], { encoding: 'utf8' })
-
- if (result.status === 0 && result.stdout.trim()) {
- return { bin: result.stdout.trim(), args: [] }
- }
-
- throw new Error('hermes backend 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))
- })
- })
-}
-
-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')
- }
-}
-
-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 hermes = hermesCommand()
-
- const child: ChildProcess = spawn(hermes.bin, [...hermes.args, '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, PYTHONPATH: REPO_ROOT },
- 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,
- 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 },
- )
-}
-
-const roster = (page: Page) => page.locator('[data-slot="bots-roster"]')
-
-test.describe('New Group Chat gate — one local bot plus remote-connection bots', () => {
- 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('group-gate')
- writeMockProviderConfig(sandbox.hermesHome, mock.url)
- writeEnvFile(sandbox.hermesHome)
- // This device: ONLY its primary `default` profile. Homelab: default + inbox (rendered title-cased, "Inbox").
- remote = await startRemoteGateway(sandbox.root, mock.url, ['inbox'])
- writeConnectionsRegistry(sandbox, remote.url)
- ;({ app, page } = await launchDesktop(buildAppEnv(sandbox)))
- await waitForAppReady({ app, page } as MockBackendFixture, 120_000)
- await expect(page.locator('[data-slot="statusbar"]').getByText('ready', { exact: true })).toBeVisible({ timeout: 120_000 })
- })
-
- test.afterAll(async () => {
- await app?.close().catch(() => undefined)
- await remote?.close()
- await mock?.close()
- sandbox?.cleanup()
- })
-
- test('the menu entry enables and the dialog seats the remote bot', async () => {
- test.setTimeout(240_000)
- 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()
- // Precondition: exactly one local bot, and the remote bots have arrived.
- await expect(roster(page).locator(`[data-roster-key="${REMOTE_ID}::inbox"]`)).toBeVisible({ timeout: 90_000 })
- await expect(roster(page).locator('[data-roster-key^="local::"]')).toHaveCount(1)
-
- await page.getByRole('button', { name: 'New bot or group chat' }).click()
- const entry = page.getByRole('menuitem', { name: 'New Group Chat' })
- await expect(entry).toBeVisible()
- await page.screenshot({ path: `${SHOTS}/group-create-gate-menu.png` })
- await expect(entry).toBeEnabled()
- await entry.click()
-
- const dialog = page.getByRole('dialog', { name: 'New Group Chat' })
- await expect(dialog).toBeVisible()
- await dialog.getByText('Hermes', { exact: true }).first().locator('xpath=ancestor::label').getByRole('checkbox').click()
- await dialog.getByText('Inbox', { exact: true }).first().locator('xpath=ancestor::label').getByRole('checkbox').click()
- await expect(dialog.getByRole('button', { name: 'Create Group (2)' })).toBeEnabled()
- await page.screenshot({ path: `${SHOTS}/group-create-gate-dialog.png` })
- })
-})
diff --git a/apps/desktop/e2e/group-handoff-to-primary-bot.spec.ts b/apps/desktop/e2e/group-handoff-to-primary-bot.spec.ts
deleted file mode 100644
index dac04f545a1..00000000000
--- a/apps/desktop/e2e/group-handoff-to-primary-bot.spec.ts
+++ /dev/null
@@ -1,164 +0,0 @@
-import { readFileSync } from 'node:fs'
-import { join } from 'node:path'
-
-import { type MockBackendFixture, setupMockBackend, waitForAppReady } from './fixtures'
-import { expect, test } from './test'
-
-// #100406: in a Bot Mode group room a teammate's `@hermes` handoff must give
-// the primary profile (internal name `default`) its turn, exactly like
-// `@hermes → @code-farmer` already does. The live roster stamps the primary
-// row's handle as the bare profile id ("default"), and the mention parser let
-// that stamped handle shadow the `@hermes` alias — so the room settled with
-// Hermes never driven. The mock inference server scripts each member's line
-// from the user's send (`E2E_SAY(<handle>)[…]`), so the assertion is on the
-// persisted room log: an entry authored by `default` saying "B".
-
-let fixture: MockBackendFixture | null = null
-
-type Page = MockBackendFixture['page']
-
-interface RoomLogEntry {
- from?: { kind?: string; name?: string }
- text?: string
-}
-
-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()
-}
-
-async function createAgent(page: Page, name: string, title: string): Promise<void> {
- await page.getByRole('button', { name: 'New bot or group chat' }).click()
- await page.getByRole('menuitem', { name: 'New Bot' }).click()
-
- const dialog = page.getByRole('dialog', { name: 'New Bot' })
- await dialog.getByPlaceholder('inbox-triage').fill(name)
- await dialog.getByPlaceholder('Inbox Triage').fill(title)
- await dialog.getByRole('button', { name: 'Create Bot' }).click()
- await expect(dialog).toBeHidden({ timeout: 30_000 })
- await expect(page.getByRole('button', { name: new RegExp(`^${title}\\b`) }).first()).toBeVisible({ timeout: 30_000 })
-}
-
-/** The plugin's persisted room log (`hermes.plugin.hermes-bots.group-chats`). */
-async function roomLog(page: Page, group: string): Promise<RoomLogEntry[]> {
- return page.evaluate(name => {
- const raw = window.localStorage.getItem('hermes.plugin.hermes-bots.group-chats')
- const rooms = raw ? (JSON.parse(raw) as Record<string, { log?: RoomLogEntry[] }>) : {}
-
- return rooms[name]?.log ?? []
- }, group)
-}
-
-test.beforeAll(async () => {
- fixture = await setupMockBackend()
- await waitForAppReady(fixture, 120_000)
-})
-
-// Playwright requires an object-destructured fixture argument.
-// eslint-disable-next-line no-empty-pattern
-test.afterEach(async ({}, info) => {
- if (!fixture) {
- return
- }
-
- await info.attach('room-log', {
- body: JSON.stringify(await roomLog(fixture.page, 'Hermes, Code Farmer'), null, 2),
- contentType: 'application/json'
- })
- await info.attach('native-window', { body: await fixture.page.screenshot(), contentType: 'image/png' })
- await info.attach('runtime-source', {
- body: JSON.stringify(
- await fixture.app.evaluate(() => ({
- cwd: process.cwd(),
- argv: process.argv,
- root: process.env.HERMES_DESKTOP_HERMES_ROOT,
- home: process.env.HERMES_HOME
- })),
- null,
- 2
- ),
- contentType: 'application/json'
- })
- await info.attach('desktop-log', {
- body: readFileSync(join(fixture.sandbox.hermesHome, 'logs/desktop.log')),
- contentType: 'text/plain'
- })
-})
-
-test.afterAll(async () => {
- await fixture?.cleanup()
- fixture = null
-})
-
-test('a teammate handing off with @hermes drives the primary profile', async () => {
- test.setTimeout(420_000)
- const page = fixture!.page
- const group = 'Hermes, Code Farmer'
-
- await openBots(page)
- await createAgent(page, 'code-farmer', 'Code Farmer')
-
- await page.getByRole('button', { name: 'New bot or group chat' }).click()
- await page.getByRole('menuitem', { name: 'New Group Chat' }).click()
-
- const dialog = page.getByRole('dialog', { name: 'New Group Chat' })
-
- for (const title of ['Hermes', 'Code Farmer']) {
- await dialog.getByText(title, { exact: true }).locator('xpath=ancestor::label').getByRole('checkbox').click()
- }
-
- await dialog.getByRole('textbox', { name: 'Group name' }).fill(group)
- await dialog.getByRole('button', { name: 'Create Group (2)' }).click()
-
- const composer = page.getByRole('textbox', { name: `Message ${group}` }).filter({ visible: true })
- await expect(composer).toBeVisible({ timeout: 20_000 })
-
- // Only Code Farmer is addressed by the user. Its scripted reply hands off
- // to @hermes; Hermes' scripted reply is "B". Neither script token carries
- // a literal `@`, so the user send itself never mentions Hermes.
- await composer.fill(
- '@code-farmer Please reply with one line only. ' +
- 'E2E_SAY(code-farmer)[{at}hermes Please reply with the letter B.] E2E_SAY(hermes)[B]'
- )
- await composer.press('Enter')
-
- // Code Farmer's handoff line lands first (the reverse direction is not in
- // question); then the room must NOT settle without Hermes' turn.
- await expect
- .poll(
- async () =>
- (await roomLog(page, group)).some(e => e.from?.name === 'code-farmer' && /@hermes/.test(e.text || '')),
- {
- timeout: 180_000
- }
- )
- .toBe(true)
-
- await expect
- .poll(
- async () => (await roomLog(page, group)).some(e => e.from?.name === 'default' && (e.text || '').trim() === 'B'),
- {
- timeout: 180_000,
- message: 'the primary profile (default / @hermes) never took its turn after being @mentioned by a teammate'
- }
- )
- .toBe(true)
-
- // And the transcript shows the handoff answered.
- await expect(page.getByText('B', { exact: true }).filter({ visible: true }).first()).toBeVisible()
-
- await composer.fill(
- '@hermes Begin the reverse handoff. E2E_SAY(hermes)[{at}code-farmer Reply with D.] E2E_SAY(code-farmer)[D]'
- )
- await composer.press('Enter')
- await expect
- .poll(async () => (await roomLog(page, group)).some(e => e.from?.name === 'code-farmer' && e.text?.trim() === 'D'), {
- timeout: 180_000
- })
- .toBe(true)
-})
diff --git a/apps/desktop/e2e/group-hold-directive.spec.ts b/apps/desktop/e2e/group-hold-directive.spec.ts
deleted file mode 100644
index 1ba3add4b1e..00000000000
--- a/apps/desktop/e2e/group-hold-directive.spec.ts
+++ /dev/null
@@ -1,150 +0,0 @@
-import { MOCK_REPLY } from '../../../tests-js/scripts/mock-server'
-
-import { type MockBackendFixture, setupMockBackend, waitForAppReady } from './fixtures'
-import { expect, test } from './test'
-
-// Sticky Stop holds (#93129) are set and released by the hold classifier in
-// group-rounds.ts. Two community reports against it:
-// #103893 — a German room's filler word ("@impl go, das ist halt ein Test")
-// held the mentioned bot on every resend;
-// #97740 — a room stopped with the Stop button stayed silent for "@all <task>"
-// because only the literal "@all resume" released the holds.
-// Both are asserted against the real Electron app + real gateway + mock
-// inference: the member's prompt must reach the provider, and the persisted
-// room record must carry no hold.
-
-const ROOM = 'Programmer, Reviewer'
-const FIRST_REPLY = 'FIRST_REPLY: initial work completed'
-let fixture: MockBackendFixture | null = null
-
-async function roomHolds(page: MockBackendFixture['page']) {
- return page.evaluate(name => {
- const rooms = JSON.parse(localStorage.getItem('hermes.plugin.hermes-bots.group-chats') || '{}')
-
- return Object.keys(rooms[name]?.holds || {})
- }, ROOM)
-}
-
-async function openBots(page: MockBackendFixture['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()
-}
-
-async function createAgent(page: MockBackendFixture['page'], name: string, title: string): Promise<void> {
- await page.getByRole('button', { name: 'New bot or group chat' }).click()
- await page.getByRole('menuitem', { name: 'New Bot' }).click()
-
- const dialog = page.getByRole('dialog', { name: 'New Bot' })
- await dialog.getByPlaceholder('inbox-triage').fill(name)
- await dialog.getByPlaceholder('Inbox Triage').fill(title)
- await dialog.getByRole('button', { name: 'Create Bot' }).click()
- await expect(dialog).toBeHidden({ timeout: 30_000 })
- await expect(page.getByRole('button', { name: new RegExp(`^${title}\\b`) }).first()).toBeVisible({ timeout: 30_000 })
-}
-
-async function createRoom(page: MockBackendFixture['page']) {
- await openBots(page)
- await createAgent(page, 'programmer', 'Programmer')
- await createAgent(page, 'reviewer', 'Reviewer')
-
- await page.getByRole('button', { name: 'New bot or group chat' }).click()
- await page.getByRole('menuitem', { name: 'New Group Chat' }).click()
-
- const dialog = page.getByRole('dialog', { name: 'New Group Chat' })
-
- for (const title of ['Programmer', 'Reviewer']) {
- await dialog.getByText(title, { exact: true }).locator('xpath=ancestor::label').getByRole('checkbox').click()
- }
-
- await dialog.getByRole('textbox', { name: 'Group name' }).fill(ROOM)
- await dialog.getByRole('button', { name: 'Create Group (2)' }).click()
-
- const groupTab = page.getByRole('tab', { name: new RegExp(`${ROOM} Close`) })
- const groupComposer = page.getByRole('textbox', { name: `Message ${ROOM}` }).filter({ visible: true })
- await expect(groupTab).toBeVisible({ timeout: 20_000 })
- await expect(groupTab).toHaveAttribute('aria-selected', 'true')
- await expect(groupComposer).toBeVisible()
-
- return groupComposer
-}
-
-/** A bot created moments ago runs its intro turn in the background; when it
- * lands, the roster fronts that bot's chat tab and yanks the center away from
- * the room. Re-select the room before reading room content. */
-async function showRoom(page: MockBackendFixture['page']) {
- const groupTab = page.getByRole('tab', { name: new RegExp(`${ROOM} Close`) })
-
- if ((await groupTab.getAttribute('aria-selected')) !== 'true') {
- await groupTab.click()
- }
-}
-
-test.beforeEach(async () => {
- fixture = await setupMockBackend({ mockServer: {
- holdFirstCompletionContaining: 'LANE_H_FIRST',
- replyForPrompt: prompt => prompt.includes('LANE_H_FIRST') ? FIRST_REPLY : MOCK_REPLY
- } })
- await waitForAppReady(fixture, 120_000)
-})
-
-test.afterEach(async () => {
- await fixture?.cleanup()
- fixture = null
-})
-
-test('a distant German filler word does not hold the mentioned bot (#103893)', async () => {
- test.setTimeout(240_000)
- const page = fixture!.page
- const groupComposer = await createRoom(page)
-
- await groupComposer.fill('@programmer go, das ist halt ein Test LANE_H_GERMAN')
- await groupComposer.press('Enter')
-
- // The bot was addressed: its turn prompt must reach the provider ...
- await expect.poll(() => fixture!.mock.receivedPrompts.some(p => p.includes('LANE_H_GERMAN')), { timeout: 60_000 }).toBe(true)
- // ... and the persisted room record must not carry a hold for it.
- expect(await roomHolds(page)).toEqual([])
- await expect(async () => {
- await showRoom(page)
- await expect(page.getByText(MOCK_REPLY, { exact: true }).first()).toBeVisible({ timeout: 5_000 })
- }).toPass({ timeout: 60_000 })
- await expect(page.locator('[data-slot="group-hold-status"]')).toHaveCount(0)
- console.log('GERMAN FILLER: prompt delivered, holds =', JSON.stringify(await roomHolds(page)))
- await page.screenshot({ path: test.info().outputPath('german-filler-after.png') })
-})
-
-test('@all with a task re-engages a room the user stopped (#97740)', async () => {
- test.setTimeout(240_000)
- const page = fixture!.page
- const groupComposer = await createRoom(page)
-
- await groupComposer.fill('@programmer LANE_H_FIRST')
- await groupComposer.press('Enter')
- await fixture!.mock.waitForHeldCompletion()
- await expect(async () => {
- await showRoom(page)
- await page.getByRole('button', { name: 'Stop', exact: true }).click({ timeout: 5_000 })
- }).toPass({ timeout: 60_000 })
- fixture!.mock.releaseHeldStream()
- await expect(page.getByRole('button', { name: 'Stop', exact: true })).toHaveCount(0)
- // Stop holds every member durably.
- await expect.poll(() => roomHolds(page)).toHaveLength(2)
- // The durable room status (#99094) names the held members.
- await expect(page.locator('[data-slot="group-hold-status"]')).toBeVisible()
- console.log('STOPPED: holds =', JSON.stringify(await roomHolds(page)))
- await page.screenshot({ path: test.info().outputPath('all-task-stopped.png') })
-
- // No "resume" anywhere: addressing the whole room is the release.
- await groupComposer.fill('@all LANE_H_ALLTASK tell me a joke each')
- await groupComposer.press('Enter')
- await expect.poll(() => fixture!.mock.receivedPrompts.filter(p => p.includes('LANE_H_ALLTASK')).length, { timeout: 90_000 }).toBeGreaterThanOrEqual(2)
- expect(await roomHolds(page)).toEqual([])
- await expect(async () => {
- await showRoom(page)
- await expect(page.getByText(MOCK_REPLY, { exact: true }).first()).toBeVisible({ timeout: 5_000 })
- }).toPass({ timeout: 60_000 })
- await expect(page.locator('[data-slot="group-hold-status"]')).toHaveCount(0)
- console.log('@all TASK: prompts delivered to', fixture!.mock.receivedPrompts.filter(p => p.includes('LANE_H_ALLTASK')).length, 'members; holds =', JSON.stringify(await roomHolds(page)))
- await page.screenshot({ path: test.info().outputPath('all-task-after.png') })
-})
diff --git a/apps/desktop/e2e/group-member-backend-failure.spec.ts b/apps/desktop/e2e/group-member-backend-failure.spec.ts
deleted file mode 100644
index 9d03acf1ed7..00000000000
--- a/apps/desktop/e2e/group-member-backend-failure.spec.ts
+++ /dev/null
@@ -1,109 +0,0 @@
-import { PROVIDER_FAILURE_TRIGGER } from '../../../tests-js/scripts/mock-server'
-
-import { type MockBackendFixture, setupMockBackend, waitForAppReady } from './fixtures'
-import { expect, test } from './test'
-
-// #92760 "thinks then never speaks": when a member's backend fails the turn
-// (bad credentials, provider refusal), the gateway keeps the failed turn under
-// `session.resume.inflight` as `{ status: 'error' }` so a reconnecting client
-// can rebuild the error bubble. The room engine read that truthy object as
-// "still working" and kept extending the member's deadline toward the
-// 20-minute cap — the user saw a bot thinking forever with no error anywhere.
-// Real Electron + real gateway; the mock provider answers the member with a
-// non-retryable 401.
-
-const ROOM = 'Programmer, Reviewer'
-let fixture: MockBackendFixture | null = null
-
-async function openBots(page: MockBackendFixture['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()
-}
-
-async function createAgent(page: MockBackendFixture['page'], name: string, title: string): Promise<void> {
- await page.getByRole('button', { name: 'New bot or group chat' }).click()
- await page.getByRole('menuitem', { name: 'New Bot' }).click()
-
- const dialog = page.getByRole('dialog', { name: 'New Bot' })
- await dialog.getByPlaceholder('inbox-triage').fill(name)
- await dialog.getByPlaceholder('Inbox Triage').fill(title)
- await dialog.getByRole('button', { name: 'Create Bot' }).click()
- await expect(dialog).toBeHidden({ timeout: 30_000 })
- await expect(page.getByRole('button', { name: new RegExp(`^${title}\\b`) }).first()).toBeVisible({ timeout: 30_000 })
-}
-
-async function createRoom(page: MockBackendFixture['page']) {
- await openBots(page)
- await createAgent(page, 'programmer', 'Programmer')
- await createAgent(page, 'reviewer', 'Reviewer')
-
- await page.getByRole('button', { name: 'New bot or group chat' }).click()
- await page.getByRole('menuitem', { name: 'New Group Chat' }).click()
-
- const dialog = page.getByRole('dialog', { name: 'New Group Chat' })
-
- for (const title of ['Programmer', 'Reviewer']) {
- await dialog.getByText(title, { exact: true }).locator('xpath=ancestor::label').getByRole('checkbox').click()
- }
-
- await dialog.getByRole('textbox', { name: 'Group name' }).fill(ROOM)
- await dialog.getByRole('button', { name: 'Create Group (2)' }).click()
-
- const groupTab = page.getByRole('tab', { name: new RegExp(`${ROOM} Close`) })
- const groupComposer = page.getByRole('textbox', { name: `Message ${ROOM}` }).filter({ visible: true })
- await expect(groupTab).toBeVisible({ timeout: 20_000 })
- await expect(groupTab).toHaveAttribute('aria-selected', 'true')
- await expect(groupComposer).toBeVisible()
-
- return groupComposer
-}
-
-test.beforeEach(async () => {
- fixture = await setupMockBackend()
- await waitForAppReady(fixture, 120_000)
-})
-
-test.afterEach(async () => {
- await fixture?.cleanup()
- fixture = null
-})
-
-test('a member whose backend fails the turn is reported at once, not read as busy (#92760)', async () => {
- test.setTimeout(240_000)
- const page = fixture!.page
- const groupComposer = await createRoom(page)
-
- await groupComposer.fill(`@programmer ${PROVIDER_FAILURE_TRIGGER}`)
- await groupComposer.press('Enter')
- await expect.poll(() => fixture!.mock.receivedPrompts.some(p => p.includes(PROVIDER_FAILURE_TRIGGER)), { timeout: 60_000 }).toBe(true)
-
- // The gateway has failed the turn; the room must say so within the base
- // turn timeout instead of extending the deadline on the retained snapshot.
- const activity = page.getByRole('button', { name: /^Activity/ })
- const groupTab = page.getByRole('tab', { name: new RegExp(`${ROOM} Close`) })
-
- await expect(async () => {
- // A just-created bot's background intro turn can front that bot's chat
- // tab and yank the center away from the room; re-select the room first.
- if ((await groupTab.getAttribute('aria-selected')) !== 'true') {
- await groupTab.click()
- }
-
- await expect(activity).toContainText('Programmer hit an error', { timeout: 5_000 })
- }).toPass({ timeout: 120_000 })
- // #117366: the row names the cause, not just the fact — the raw error's
- // first line rides along so a stopped backend and a provider refusal differ.
- await expect(activity).toContainText(/Programmer hit an error — \S+/)
- await expect(page.getByRole('button', { name: 'Stop', exact: true })).toHaveCount(0, { timeout: 30_000 })
-
- const room = await page.evaluate(name => {
- const rooms = JSON.parse(localStorage.getItem('hermes.plugin.hermes-bots.group-chats') || '{}')
-
- return { stranded: Object.keys(rooms[name]?.stranded || {}), running: Boolean(rooms[name]?.running) }
- }, ROOM)
-
- expect(room.stranded).toEqual([])
- console.log('RETAINED FAILURE: activity =', await activity.textContent(), 'room =', JSON.stringify(room))
- await page.screenshot({ path: test.info().outputPath('retained-failure-after.png') })
-})
diff --git a/apps/desktop/e2e/group-prompt-renamed-primary-handle.spec.ts b/apps/desktop/e2e/group-prompt-renamed-primary-handle.spec.ts
deleted file mode 100644
index 9b4bf36a5f7..00000000000
--- a/apps/desktop/e2e/group-prompt-renamed-primary-handle.spec.ts
+++ /dev/null
@@ -1,157 +0,0 @@
-import { readFileSync, writeFileSync } from 'node:fs'
-import { join } from 'node:path'
-
-import {
- buildAppEnv,
- createSandbox,
- launchDesktop,
- type MockBackendFixture,
- waitForAppReady,
- writeEnvFile,
- writeMockProviderConfig
-} from './fixtures'
-import { startMockServer } from '../../../tests-js/scripts/mock-server'
-import { expect, test } from './test'
-
-// The primary profile (`default`) renamed to a Bot Mode title ("Bobby") is
-// addressed by the roster, autocomplete and mention routing as @bobby — but the
-// group-turn prompt introduced it to itself as @hermes, so a member told
-// "You are @hermes" read `@bobby …` as a message for someone else and passed.
-// The mock inference server scripts a member's line by the `You are @<handle>`
-// opener, so the assertion is exactly that mismatch: with a script for
-// `bobby`, the renamed primary must answer (the persisted room log carries an
-// entry authored by `default`), not settle silently.
-
-let fixture: MockBackendFixture | null = null
-
-type Page = MockBackendFixture['page']
-
-interface RoomLogEntry {
- from?: { kind?: string; name?: string }
- text?: string
-}
-
-const GROUP = 'Bobby, Code Farmer'
-
-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()
-}
-
-async function createAgent(page: Page, name: string, title: string): Promise<void> {
- await page.getByRole('button', { name: 'New bot or group chat' }).click()
- await page.getByRole('menuitem', { name: 'New Bot' }).click()
-
- const dialog = page.getByRole('dialog', { name: 'New Bot' })
- await dialog.getByPlaceholder('inbox-triage').fill(name)
- await dialog.getByPlaceholder('Inbox Triage').fill(title)
- await dialog.getByRole('button', { name: 'Create Bot' }).click()
- await expect(dialog).toBeHidden({ timeout: 30_000 })
- await expect(page.getByRole('button', { name: new RegExp(`^${title}\\b`) }).first()).toBeVisible({ timeout: 30_000 })
-}
-
-async function roomLog(page: Page, group: string): Promise<RoomLogEntry[]> {
- return page.evaluate(name => {
- const raw = window.localStorage.getItem('hermes.plugin.hermes-bots.group-chats')
- const rooms = raw ? (JSON.parse(raw) as Record<string, { log?: RoomLogEntry[] }>) : {}
-
- return rooms[name]?.log ?? []
- }, group)
-}
-
-test.beforeAll(async () => {
- const mock = await startMockServer()
- const sandbox = createSandbox('renamed-primary')
- writeMockProviderConfig(sandbox.hermesHome, mock.url)
- writeEnvFile(sandbox.hermesHome)
- // The primary profile carries a Bot Mode title — what `hermes profile rename`
- // / the Edit Profile dialog persist into profile.yaml's ui_meta.
- writeFileSync(
- join(sandbox.hermesHome, 'profile.yaml'),
- 'ui_meta:\n hermes-bots:\n title: Bobby\n shape: circle\n color: "#4f8"\n',
- 'utf8'
- )
-
- 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)
-})
-
-// eslint-disable-next-line no-empty-pattern
-test.afterEach(async ({}, info) => {
- if (!fixture) {
- return
- }
-
- await info.attach('room-log', {
- body: JSON.stringify(await roomLog(fixture.page, GROUP), null, 2),
- contentType: 'application/json'
- })
- await info.attach('native-window', { body: await fixture.page.screenshot(), contentType: 'image/png' })
- await info.attach('desktop-log', {
- body: readFileSync(join(fixture.sandbox.hermesHome, 'logs/desktop.log')),
- contentType: 'text/plain'
- })
-})
-
-test.afterAll(async () => {
- await fixture?.cleanup()
- fixture = null
-})
-
-test('a renamed primary bot is addressed by its own @tag in the group-turn prompt', async () => {
- test.setTimeout(420_000)
- const page = fixture!.page
-
- await openBots(page)
- await expect(page.getByRole('button', { name: /^Bobby\b/ }).first()).toBeVisible({ timeout: 30_000 })
- await createAgent(page, 'code-farmer', 'Code Farmer')
-
- await page.getByRole('button', { name: 'New bot or group chat' }).click()
- await page.getByRole('menuitem', { name: 'New Group Chat' }).click()
-
- const dialog = page.getByRole('dialog', { name: 'New Group Chat' })
-
- for (const title of ['Bobby', 'Code Farmer']) {
- await dialog.getByText(title, { exact: true }).locator('xpath=ancestor::label').getByRole('checkbox').click()
- }
-
- await dialog.getByRole('textbox', { name: 'Group name' }).fill(GROUP)
- await dialog.getByRole('button', { name: 'Create Group (2)' }).click()
-
- const composer = page.getByRole('textbox', { name: `Message ${GROUP}` }).filter({ visible: true })
- await expect(composer).toBeVisible({ timeout: 20_000 })
-
- // Only the renamed primary is addressed, by its friendly tag. Its scripted
- // line is keyed to `bobby`: the member only speaks when its turn prompt
- // introduces it as @bobby (the control, code-farmer, is scripted too so a
- // wrong-handle prompt cannot be mistaken for an idle room).
- await composer.fill('@bobby Please reply with one line only. E2E_SAY(bobby)[B] E2E_SAY(code-farmer)[C]')
- await composer.press('Enter')
-
- await expect
- .poll(async () => (await roomLog(page, GROUP)).some(e => e.from?.name === 'default' && (e.text || '').trim() === 'B'), {
- timeout: 180_000,
- message: 'the renamed primary (default / Bobby) was introduced to itself as @hermes and never answered @bobby'
- })
- .toBe(true)
-
- await expect(page.getByText('B', { exact: true }).filter({ visible: true }).first()).toBeVisible()
-})
diff --git a/apps/desktop/e2e/group-room-member-editing.spec.ts b/apps/desktop/e2e/group-room-member-editing.spec.ts
deleted file mode 100644
index 2dad2a4213f..00000000000
--- a/apps/desktop/e2e/group-room-member-editing.spec.ts
+++ /dev/null
@@ -1,152 +0,0 @@
-import os from 'node:os'
-import path from 'node:path'
-
-import { type MockBackendFixture, setupMockBackend, waitForAppReady } from './fixtures'
-import { expect, test } from './test'
-
-// #91329 / #110736 — membership of an EXISTING room is editable from Group
-// settings: the picker pre-checks the current seats, Save rewrites both
-// membership sources the room reads (each local Bot's groups[] metadata and
-// the room's durable member descriptors), and the next unaddressed send seats
-// exactly the saved roster — the removed Bot never takes a turn again.
-
-const ROOM = 'Programmer, Reviewer'
-const SHOTS = path.join(os.tmpdir(), 'batchbots/features-groups-ui/shots')
-let fixture: MockBackendFixture | null = null
-
-type Page = MockBackendFixture['page']
-
-async function durableMembers(page: Page) {
- return page.evaluate(room => {
- const rooms = JSON.parse(localStorage.getItem('hermes.plugin.hermes-bots.group-chats') || '{}')
-
- return ((rooms[room]?.members || []) as { name: string }[]).map(member => member.name).sort()
- }, ROOM)
-}
-
-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()
-}
-
-async function createAgent(page: Page, name: string, title: string): Promise<void> {
- await page.getByRole('button', { name: 'New bot or group chat' }).click()
- await page.getByRole('menuitem', { name: 'New Bot' }).click()
-
- const dialog = page.getByRole('dialog', { name: 'New Bot' })
- await dialog.getByPlaceholder('inbox-triage').fill(name)
- await dialog.getByPlaceholder('Inbox Triage').fill(title)
- await dialog.getByRole('button', { name: 'Create Bot' }).click()
- await expect(dialog).toBeHidden({ timeout: 30_000 })
- await expect(page.getByRole('button', { name: new RegExp(`^${title}\\b`) }).first()).toBeVisible({ timeout: 30_000 })
-}
-
-async function createRoom(page: Page) {
- await openBots(page)
- await createAgent(page, 'programmer', 'Programmer')
- await createAgent(page, 'reviewer', 'Reviewer')
- await createAgent(page, 'planner', 'Planner')
-
- await page.getByRole('button', { name: 'New bot or group chat' }).click()
- await page.getByRole('menuitem', { name: 'New Group Chat' }).click()
-
- const dialog = page.getByRole('dialog', { name: 'New Group Chat' })
-
- for (const title of ['Programmer', 'Reviewer']) {
- await dialog.getByText(title, { exact: true }).locator('xpath=ancestor::label').getByRole('checkbox').click()
- }
-
- await dialog.getByRole('textbox', { name: 'Group name' }).fill(ROOM)
- await dialog.getByRole('button', { name: 'Create Group (2)' }).click()
-
- return frontRoom(page)
-}
-
-/** A just-created Bot's canonical Bot Chat hydrates late and can front its
- * "Draft" tab over the room tab; bring the room back before typing into it. */
-async function frontRoom(page: Page) {
- const tab = page.getByRole('tab', { name: ROOM }).first()
- await expect(tab).toBeVisible({ timeout: 20_000 })
-
- if ((await tab.getAttribute('aria-selected')) !== 'true') {
- await tab.click()
- }
-
- const composer = page.getByRole('textbox', { name: `Message ${ROOM}` }).filter({ visible: true })
- await expect(composer).toBeVisible({ timeout: 20_000 })
-
- return composer
-}
-
-test.beforeEach(async () => {
- fixture = await setupMockBackend({ mockServer: {} })
- await waitForAppReady(fixture, 120_000)
-})
-
-test.afterEach(async () => {
- await fixture?.cleanup()
- fixture = null
-})
-
-test('Group settings edits the room roster and the next round seats only the saved members', async () => {
- test.setTimeout(300_000)
- const page = fixture!.page
- await createRoom(page)
-
- expect(await durableMembers(page)).toEqual(['programmer', 'reviewer'])
-
- // Group settings → Manage members: the checklist opens pre-checked.
- await page.getByRole('button', { name: `Group settings for ${ROOM}` }).click()
- await page.getByRole('dialog', { name: 'Group settings' }).getByRole('button', { name: /^Manage members \(2\)/ }).click()
-
- const picker = page.getByRole('dialog', { name: 'Manage members' })
- await expect(picker).toBeVisible()
- const row = (title: string) => picker.getByRole('checkbox').filter({ hasText: title })
- await expect(row('Programmer')).toHaveAttribute('aria-checked', 'true')
- await expect(row('Reviewer')).toHaveAttribute('aria-checked', 'true')
- await expect(row('Planner')).toHaveAttribute('aria-checked', 'false')
- await page.screenshot({ path: `${SHOTS}/member-picker-open.png` })
-
- // Cancel changes nothing.
- await row('Planner').click()
- await picker.getByRole('button', { name: 'Cancel' }).click()
- await expect(picker).toBeHidden()
- expect(await durableMembers(page)).toEqual(['programmer', 'reviewer'])
-
- // Header door → swap Reviewer for Planner → Save.
- await page.getByRole('button', { name: 'Manage group members' }).click()
- await expect(row('Planner')).toHaveAttribute('aria-checked', 'false')
- await row('Planner').click()
- await row('Reviewer').click()
- await page.screenshot({ path: `${SHOTS}/member-picker-edited.png` })
- await picker.getByRole('button', { name: 'Save members' }).click()
- await expect(picker).toBeHidden()
-
- // Storage truth: the durable descriptors carry the new roster …
- await expect.poll(() => durableMembers(page)).toEqual(['planner', 'programmer'])
- // … and so does each local Bot's groups[] metadata (the plugin's meta snapshot).
- await expect.poll(() => page.evaluate(room => {
- const meta = JSON.parse(localStorage.getItem('hermes.plugin.hermes-bots.bot-meta-v2') || '{}')
-
- return Object.entries(meta as Record<string, any>)
- .filter(([, value]) => (value?.groups || []).includes(room))
- .map(([key]) => key.split('::').pop())
- .sort()
- }, ROOM), { timeout: 30_000 }).toEqual(['planner', 'programmer'])
-
- // An unaddressed send seats exactly the saved roster.
- const groupComposer = await frontRoom(page)
- await groupComposer.fill('ROOM_EDIT_ROUND who is here?')
- await groupComposer.press('Enter')
- await expect.poll(() => fixture!.mock.receivedPrompts.filter(p => p.includes('ROOM_EDIT_ROUND')).length, { timeout: 90_000 }).toBeGreaterThanOrEqual(2)
- await expect(page.getByRole('button', { name: 'Stop', exact: true })).toHaveCount(0, { timeout: 90_000 })
-
- const speakers = fixture!.mock.receivedPrompts
- .filter(p => p.includes('ROOM_EDIT_ROUND'))
- .map(p => /You are @([a-z0-9_-]+)/.exec(p)?.[1])
- console.log('ROUND SPEAKERS after roster edit:', JSON.stringify(speakers))
- expect(new Set(speakers)).toEqual(new Set(['programmer', 'planner']))
- expect(speakers).not.toContain('reviewer')
- await page.screenshot({ path: `${SHOTS}/member-picker-after-round.png` })
-})
diff --git a/apps/desktop/e2e/group-to-local-bot-handoff.spec.ts b/apps/desktop/e2e/group-to-local-bot-handoff.spec.ts
deleted file mode 100644
index 2f863d144fe..00000000000
--- a/apps/desktop/e2e/group-to-local-bot-handoff.spec.ts
+++ /dev/null
@@ -1,80 +0,0 @@
-import { type MockBackendFixture, setupMockBackend, waitForAppReady } from './fixtures'
-import { expect, test } from './test'
-
-let fixture: MockBackendFixture | null = null
-
-async function openBots(page: MockBackendFixture['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()
-}
-
-async function createAgent(page: MockBackendFixture['page'], name: string, title: string): Promise<void> {
- await page.getByRole('button', { name: 'New bot or group chat' }).click()
- await page.getByRole('menuitem', { name: 'New Bot' }).click()
-
- const dialog = page.getByRole('dialog', { name: 'New Bot' })
- await dialog.getByPlaceholder('inbox-triage').fill(name)
- await dialog.getByPlaceholder('Inbox Triage').fill(title)
- await dialog.getByRole('button', { name: 'Create Bot' }).click()
- await expect(dialog).toBeHidden({ timeout: 30_000 })
- await expect(page.getByRole('button', { name: new RegExp(`^${title}\\b`) }).first()).toBeVisible({ timeout: 30_000 })
-}
-
-test.beforeAll(async () => {
- fixture = await setupMockBackend()
- await waitForAppReady(fixture, 120_000)
-})
-
-test.afterAll(async () => {
- await fixture?.cleanup()
- fixture = null
-})
-
-test('local bot replaces an open group main workspace', async () => {
- test.setTimeout(240_000)
- const page = fixture!.page
-
- await openBots(page)
- await createAgent(page, 'programmer', 'Programmer')
- await createAgent(page, 'reviewer', 'Reviewer')
-
- await page.getByRole('button', { name: 'New bot or group chat' }).click()
- await page.getByRole('menuitem', { name: 'New Group Chat' }).click()
-
- const dialog = page.getByRole('dialog', { name: 'New Group Chat' })
-
- for (const title of ['Programmer', 'Reviewer']) {
- await dialog.getByText(title, { exact: true }).locator('xpath=ancestor::label').getByRole('checkbox').click()
- }
-
- await dialog.getByRole('textbox', { name: 'Group name' }).fill('Programmer, Reviewer')
- await dialog.getByRole('button', { name: 'Create Group (2)' }).click()
-
- const groupTab = page.getByRole('tab', { name: /Programmer, Reviewer Close/ })
- const groupComposer = page.getByRole('textbox', { name: 'Message Programmer, Reviewer' }).filter({ visible: true })
- await expect(groupTab).toBeVisible({ timeout: 20_000 })
- await expect(groupTab).toHaveAttribute('aria-selected', 'true')
- await expect(groupComposer).toBeVisible()
-
- const programmer = page.getByRole('button', { name: /^Programmer\b/ }).filter({ visible: true }).first()
- await programmer.click()
-
- // The bot's canonical chat opens INTO the main workspace pane (post
- // design-system rework); as the lone pane in the zone it renders chromeless
- // — no "Bot Chat" tab exists until a second pane joins the strip. The
- // handoff is observed by the group surfaces leaving and the bot's chat
- // (here a fresh one: its empty-state splash asks for a first message)
- // taking the main workspace. The first open also spawns the bot's own
- // backend, so give the "Loading session" phase a real chance to clear.
- await expect(page.getByText('Say something to get started.').filter({ visible: true })).toBeVisible({
- timeout: 120_000
- })
- await expect(groupTab).toHaveCount(0)
- await expect(groupComposer).toHaveCount(0)
- // No "Waking up…" assertion: the mock backend can keep a bot's wake notice
- // around indefinitely (see bot-mode-row-click-mirrors-registry's settle()),
- // so its presence no longer distinguishes a stranded handoff. The splash
- // and composer above are the proof the bot's chat took the workspace.
- await expect(page.locator('[data-slot="composer-root"] [contenteditable="true"]').filter({ visible: true }).first()).toBeVisible()
-})
diff --git a/apps/desktop/e2e/group-transcript-mentions-reply-to.spec.ts b/apps/desktop/e2e/group-transcript-mentions-reply-to.spec.ts
deleted file mode 100644
index 54225fe50ff..00000000000
--- a/apps/desktop/e2e/group-transcript-mentions-reply-to.spec.ts
+++ /dev/null
@@ -1,135 +0,0 @@
-import os from 'node:os'
-import path from 'node:path'
-
-import { type MockBackendFixture, setupMockBackend, waitForAppReady } from './fixtures'
-import { expect, test } from './test'
-
-// #91359 / #89883 — group-room transcript affordances:
-// - a recognized @mention in a sent message renders as an inline reference
-// (`.ref[data-ref=agent|human|broadcast]`); unknown @tokens stay prose;
-// - a bot's message carries "Reply to <bot>", which seeds `@tag ` into the
-// room composer so the next send routes to that member only.
-
-const ROOM = 'Programmer, Reviewer'
-const SHOTS = path.join(os.tmpdir(), 'batchbots/features-groups-ui/shots')
-let fixture: MockBackendFixture | null = null
-
-type Page = MockBackendFixture['page']
-
-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()
-}
-
-async function createAgent(page: Page, name: string, title: string): Promise<void> {
- await page.getByRole('button', { name: 'New bot or group chat' }).click()
- await page.getByRole('menuitem', { name: 'New Bot' }).click()
-
- const dialog = page.getByRole('dialog', { name: 'New Bot' })
- await dialog.getByPlaceholder('inbox-triage').fill(name)
- await dialog.getByPlaceholder('Inbox Triage').fill(title)
- await dialog.getByRole('button', { name: 'Create Bot' }).click()
- await expect(dialog).toBeHidden({ timeout: 30_000 })
- await expect(page.getByRole('button', { name: new RegExp(`^${title}\\b`) }).first()).toBeVisible({ timeout: 30_000 })
-}
-
-async function createRoom(page: Page) {
- await openBots(page)
- await createAgent(page, 'programmer', 'Programmer')
- await createAgent(page, 'reviewer', 'Reviewer')
-
- await page.getByRole('button', { name: 'New bot or group chat' }).click()
- await page.getByRole('menuitem', { name: 'New Group Chat' }).click()
-
- const dialog = page.getByRole('dialog', { name: 'New Group Chat' })
-
- for (const title of ['Programmer', 'Reviewer']) {
- await dialog.getByText(title, { exact: true }).locator('xpath=ancestor::label').getByRole('checkbox').click()
- }
-
- await dialog.getByRole('textbox', { name: 'Group name' }).fill(ROOM)
- await dialog.getByRole('button', { name: 'Create Group (2)' }).click()
-
- const groupComposer = page.getByRole('textbox', { name: `Message ${ROOM}` }).filter({ visible: true })
- await expect(groupComposer).toBeVisible({ timeout: 20_000 })
-
- return groupComposer
-}
-
-test.beforeEach(async () => {
- fixture = await setupMockBackend({ mockServer: {} })
- await waitForAppReady(fixture, 120_000)
-})
-
-test.afterEach(async () => {
- await fixture?.cleanup()
- fixture = null
-})
-
-test('mentions render as inline references and Reply-to seeds the composer', async () => {
- test.setTimeout(300_000)
- const page = fixture!.page
- const groupComposer = await createRoom(page)
-
- await groupComposer.fill('@programmer MENTION_RENDER check this, then @user decides; not [email protected] and not @nobody')
- await groupComposer.press('Enter')
-
- // The sent user line: exactly the routed bot and the human token are refs.
- // A bot created moments ago runs its intro turn in the background; when it
- // lands, the roster fronts that bot's chat tab and yanks the center away
- // from the room. Re-select the room and read the line from a room body.
- const roomTab = page.getByRole('tab', { name: new RegExp(`${ROOM} Close`) })
-
- const sent = page
- .locator('[data-selectable-text="true"]')
- .getByText(/MENTION_RENDER check this/)
- .filter({ visible: true })
- .first()
-
- await expect(async () => {
- if ((await roomTab.getAttribute('aria-selected')) !== 'true') {
- await roomTab.click()
- }
-
- await expect(sent).toBeVisible({ timeout: 5_000 })
- }).toPass({ timeout: 60_000 })
- await expect(sent.locator('.ref[data-ref="agent"]')).toHaveText('@programmer')
- await expect(sent.locator('.ref[data-ref="human"]')).toHaveText('@user')
- // Only the two mention refs carry `data-ref`; the e-mail address renders
- // as the shell's ordinary (also `.ref`-styled) mailto link, not a mention.
- await expect(sent.locator('.ref[data-ref]')).toHaveCount(2)
- await expect(sent).toContainText('@nobody')
-
- // The mock reply from programmer arrives; its hover action targets that bot.
- await expect(page.getByRole('button', { name: 'Stop', exact: true })).toHaveCount(0, { timeout: 90_000 })
- const replyButton = page.getByRole('button', { name: 'Reply to Programmer' }).first()
-
- await expect(async () => {
- if ((await roomTab.getAttribute('aria-selected')) !== 'true') {
- await roomTab.click()
- }
-
- await expect(replyButton).toBeAttached({ timeout: 5_000 })
- }).toPass({ timeout: 60_000 })
- await sent.hover()
- await page.screenshot({ path: `${SHOTS}/mention-refs.png` })
-
- await groupComposer.fill('')
- await replyButton.click({ force: true })
- await expect(groupComposer).toHaveValue('@programmer ')
- await page.screenshot({ path: `${SHOTS}/reply-to-seeded.png` })
-
- // Idempotent: a second click never doubles the tag.
- await replyButton.click({ force: true })
- await expect(groupComposer).toHaveValue('@programmer ')
-
- // Storage truth: the stored text is untouched by rendering.
- const stored = await page.evaluate(room => {
- const rooms = JSON.parse(localStorage.getItem('hermes.plugin.hermes-bots.group-chats') || '{}')
-
- return (rooms[room]?.log || []).map((entry: any) => entry.text)[0]
- }, ROOM)
-
- expect(stored).toBe('@programmer MENTION_RENDER check this, then @user decides; not [email protected] and not @nobody')
-})
diff --git a/apps/desktop/e2e/group-transcript-owner-meta.spec.ts b/apps/desktop/e2e/group-transcript-owner-meta.spec.ts
deleted file mode 100644
index 9743890622e..00000000000
--- a/apps/desktop/e2e/group-transcript-owner-meta.spec.ts
+++ /dev/null
@@ -1,139 +0,0 @@
-import os from 'node:os'
-import path from 'node:path'
-
-import { MOCK_REPLY } from '../../../tests-js/scripts/mock-server'
-
-import { type MockBackendFixture, setupMockBackend, waitForAppReady } from './fixtures'
-import { expect, test } from './test'
-
-// Group Chat identity follows the OWNER-qualified bot meta (#96432, #101382,
-// #102294, #94869): bot meta is persisted under `connectionId::profile`
-// (botMetaKey), while the transcript speaker row and the Activity feed used
-// to probe the bare profile name — a stale v1 relic at best, nothing for a
-// remote or renamed bot at worst. Re-titling a member after the room exists
-// is the single-gateway form of the bug: the roster repaints, the room does
-// not. The room log itself is untouched by this — only presentation moves.
-
-const ROOM = 'Ops Room'
-const NEW_TITLE = 'Infra Ops'
-const SHOTS = path.join(os.tmpdir(), 'batchbots/group-identity-members/shots')
-let fixture: MockBackendFixture | null = null
-
-type Page = MockBackendFixture['page']
-
-const roster = (page: Page) => page.locator('[data-slot="bots-roster"]')
-const botRow = (page: Page, name: string) => roster(page).locator(`[data-roster-key="local::${name}"]`)
-const speakerLabels = (page: Page) => page.locator('button[title="Show full handle"]')
-
-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()
-}
-
-async function createAgent(page: Page, name: string, title: string): Promise<void> {
- await page.getByRole('button', { name: 'New bot or group chat' }).click()
- await page.getByRole('menuitem', { name: 'New Bot' }).click()
- const dialog = page.getByRole('dialog', { name: 'New Bot' })
- await dialog.getByPlaceholder('inbox-triage').fill(name)
- await dialog.getByPlaceholder('Inbox Triage').fill(title)
- await dialog.getByRole('button', { name: 'Create Bot' }).click()
- await expect(dialog).toBeHidden({ timeout: 30_000 })
- await expect(botRow(page, name)).toBeVisible({ timeout: 30_000 })
-}
-
-async function createRoom(page: Page) {
- await openBots(page)
- await createAgent(page, 'programmer', 'Programmer')
- await createAgent(page, 'reviewer', 'Reviewer')
- await page.getByRole('button', { name: 'New bot or group chat' }).click()
- await page.getByRole('menuitem', { name: 'New Group Chat' }).click()
- const dialog = page.getByRole('dialog', { name: 'New Group Chat' })
-
- for (const title of ['Programmer', 'Reviewer']) {
- await dialog.getByText(title, { exact: true }).locator('xpath=ancestor::label').getByRole('checkbox').click()
- }
-
- await dialog.getByRole('textbox', { name: 'Group name' }).fill(ROOM)
- await dialog.getByRole('button', { name: 'Create Group (2)' }).click()
-
- return frontRoom(page)
-}
-
-/** A just-created Bot's canonical Bot Chat hydrates late and can front its
- * "Draft" tab over the room tab; bring the room back before typing into it. */
-async function frontRoom(page: Page) {
- const tab = page.getByRole('tab', { name: ROOM }).first()
- await expect(tab).toBeVisible({ timeout: 20_000 })
-
- if ((await tab.getAttribute('aria-selected')) !== 'true') {
- await tab.click()
- }
-
- const composer = page.getByRole('textbox', { name: `Message ${ROOM}` }).filter({ visible: true })
- await expect(composer).toBeVisible({ timeout: 20_000 })
-
- return composer
-}
-
-async function storedMeta(page: Page) {
- return page.evaluate(() => {
- const meta = JSON.parse(localStorage.getItem('hermes.plugin.hermes-bots.bot-meta-v2') || '{}')
-
- return { bare: meta.programmer?.title ?? null, routed: meta['local::programmer']?.title ?? null }
- })
-}
-
-test.beforeEach(async () => {
- fixture = await setupMockBackend({ mockServer: { replyForPrompt: () => MOCK_REPLY } })
- await waitForAppReady(fixture, 120_000)
-})
-
-test.afterEach(async () => {
- await fixture?.cleanup()
- fixture = null
-})
-
-test('a re-titled member is re-labelled in the room transcript and Activity feed', async () => {
- test.setTimeout(300_000)
- const page = fixture!.page
- await createRoom(page)
-
- const composer = await frontRoom(page)
- await composer.fill('@programmer hello')
- await composer.press('Enter')
- await expect(page.getByText(MOCK_REPLY, { exact: true }).first()).toBeVisible({ timeout: 90_000 })
- await expect(speakerLabels(page).first()).toHaveText('Programmer')
- await expect(page.getByRole('button', { name: 'Stop', exact: true })).toHaveCount(0)
-
- // Re-title the member through the real Edit dialog. The write lands on the
- // route-qualified key (`local::programmer`); the bare-name relic keeps the
- // old title — exactly the two-slot store reporters found in leveldb.
- await botRow(page, 'programmer').click({ button: 'right' })
- await page.getByRole('menuitem', { name: 'Edit…' }).click()
- const edit = page.getByRole('dialog', { name: 'Edit profile' })
- await expect(edit).toBeVisible({ timeout: 30_000 })
- // The Title input's placeholder is the bot's current display name.
- await edit.getByPlaceholder('Programmer').fill(NEW_TITLE)
- await edit.getByRole('button', { name: 'Save' }).click()
- await expect(edit).toBeHidden({ timeout: 30_000 })
- await expect(botRow(page, 'programmer')).toContainText(NEW_TITLE, { timeout: 30_000 })
- await expect.poll(async () => (await storedMeta(page)).routed, { timeout: 15_000 }).toBe(NEW_TITLE)
- expect((await storedMeta(page)).bare).toBe('Programmer')
-
- // The room must show the same identity the roster does.
- await expect(speakerLabels(page).first()).toHaveText(NEW_TITLE, { timeout: 15_000 })
- await page.getByRole('button', { name: /^Activity/ }).click()
- await expect(page.getByText(`${NEW_TITLE} replied`, { exact: true })).toBeVisible({ timeout: 15_000 })
- await expect(page.getByText('Programmer replied', { exact: true })).toHaveCount(0)
- await page.screenshot({ path: `${SHOTS}/group-transcript-owner-meta-after.png` })
-
- // Control: the user's own lines never pick up bot meta, and the durable
- // room log still stores the profile id, not the title.
- await expect(page.getByText('You', { exact: true }).first()).toBeVisible()
- const logFrom = await page.evaluate(
- room => (JSON.parse(localStorage.getItem('hermes.plugin.hermes-bots.group-chats') || '{}')[room]?.log || []).map((entry: any) => entry.from.name),
- ROOM
- )
- expect(logFrom).toEqual(['You', 'programmer'])
-})
diff --git a/apps/desktop/e2e/hosted-room-backend-continuity.spec.ts b/apps/desktop/e2e/hosted-room-backend-continuity.spec.ts
deleted file mode 100644
index 9669f8f0e88..00000000000
--- a/apps/desktop/e2e/hosted-room-backend-continuity.spec.ts
+++ /dev/null
@@ -1,191 +0,0 @@
-import { execSync } from 'node:child_process'
-import fs from 'node:fs'
-import path from 'node:path'
-
-import {
- buildAppEnv,
- createSandbox,
- launchDesktop,
- type MockBackendFixture,
- waitForAppReady,
- writeEnvFile,
- writeMockProviderConfig
-} from './fixtures'
-import { startMockServer } from '../../../tests-js/scripts/mock-server'
-import { expect, test } from './test'
-
-// Hosted Group Chat rooms live in the gateway, and the Desktop's own `hermes serve` backend runs
-// a room worker. A member turn used to keep the profile's `bot_room` active-session slot for the
-// life of the backend process, so a second room worker on the same home (the messaging gateway
-// beside Desktop serve) was refused every turn once the driver lease flipped (#106847). Asserted
-// against the REAL Electron app's spawned backend over its JSON-RPC socket plus storage truth
-// (`profiles/<member>/runtime/active_sessions.json`).
-
-type Page = MockBackendFixture['page']
-
-
-let fixture: MockBackendFixture | null = null
-let rpc: Rpc | null = null
-
-function seedProfile(hermesHome: string, mockUrl: string, name: string): void {
- const dir = path.join(hermesHome, 'profiles', name)
- fs.mkdirSync(dir, { recursive: true })
- writeMockProviderConfig(dir, mockUrl)
- writeEnvFile(dir)
-}
-
-/** Locate the Electron-spawned `hermes serve` backend for this sandbox: its port and session token. */
-function findBackend(hermesHome: string): { port: number; token: string; pid: number } {
- const pids = execSync(`pgrep -f "serve --host 127.0.0.1 --port 0" || true`, { encoding: 'utf8' })
- .split('\n')
- .map(s => s.trim())
- .filter(Boolean)
- for (const pidText of pids) {
- const pid = Number(pidText)
- let environ = ''
- try {
- environ = fs.readFileSync(`/proc/${pid}/environ`, 'latin1')
- } catch {
- continue
- }
- const vars = new Map(environ.split('\0').map(kv => [kv.slice(0, kv.indexOf('=')), kv.slice(kv.indexOf('=') + 1)]))
- if (vars.get('HERMES_HOME') !== hermesHome) {
- continue
- }
- const token = vars.get('HERMES_DASHBOARD_SESSION_TOKEN') ?? ''
- // The backend inherits Electron's remote-debugging socket fd too; the serve port is the listener
- // that only the hermes process holds.
- const listen = execSync(`ss -ltnp | grep "pid=${pid}," | grep -v electron || true`, { encoding: 'utf8' })
- const port = Number(/127\.0\.0\.1:(\d+)/.exec(listen)?.[1] ?? 0)
- if (token && port) {
- return { port, token, pid }
- }
- }
- throw new Error(`no hermes serve backend found for ${hermesHome} (pids: ${pids.join(',')})`)
-}
-
-/** Minimal JSON-RPC client over the backend's /api/ws (Node's global WebSocket; no Origin header is sent,
- * which the loopback backend accepts — the session token is the auth boundary). */
-class Rpc {
- private ws: WebSocket
- private id = 0
- private ready: Promise<void>
-
- constructor(port: number, token: string) {
- this.ws = new WebSocket(`ws://127.0.0.1:${port}/api/ws?token=${token}`)
- this.ready = new Promise((resolve, reject) => {
- this.ws.addEventListener('open', () => resolve(), { once: true })
- this.ws.addEventListener('error', () => reject(new Error(`ws upgrade to 127.0.0.1:${port} failed`)), { once: true })
- })
- }
-
- async call(method: string, params: Record<string, unknown> = {}): Promise<any> {
- await this.ready
- const id = `e2e-${++this.id}`
- return new Promise((resolve, reject) => {
- const onMessage = (event: MessageEvent) => {
- const frame = JSON.parse(String(event.data))
- if (frame.id === id) {
- this.ws.removeEventListener('message', onMessage)
- resolve(frame)
- }
- }
- this.ws.addEventListener('message', onMessage)
- this.ws.addEventListener('error', () => reject(new Error(`ws error during ${method}`)), { once: true })
- this.ws.send(JSON.stringify({ jsonrpc: '2.0', id, method, params }))
- })
- }
-
- close(): void {
- this.ws.close()
- }
-}
-
-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()
-}
-
-test.beforeAll(async () => {
- const mock = await startMockServer()
- const sandbox = createSandbox('hosted-rooms-backend')
- writeMockProviderConfig(sandbox.hermesHome, mock.url)
- writeEnvFile(sandbox.hermesHome)
- seedProfile(sandbox.hermesHome, mock.url, 'sentinel')
- seedProfile(sandbox.hermesHome, mock.url, 'friday')
-
- const { app, page } = await launchDesktop(buildAppEnv(sandbox))
- fixture = {
- app,
- page,
- mock,
- mockUrl: mock.url,
- sandbox,
- cleanup: async () => {
- rpc?.close()
- await app.close().catch(() => undefined)
- await mock.close()
- sandbox.cleanup()
- }
- }
- await waitForAppReady(fixture, 120_000)
- const backend = findBackend(sandbox.hermesHome)
- rpc = new Rpc(backend.port, backend.token)
-})
-
-test.afterAll(async () => {
- await fixture?.cleanup()
- fixture = null
-})
-
-test("a hosted room turn driven by the Desktop backend releases the member's bot_room slot (#106847)", async () => {
- test.setTimeout(300_000)
- const page = fixture!.page
- const created = await rpc!.call('groups.create', {
- room_id: 'r-slot',
- name: 'Slot probe',
- members: [
- { member_id: 'm-sentinel', profile: 'sentinel', handle: 'sentinel' },
- { member_id: 'm-friday', profile: 'friday', handle: 'friday' }
- ]
- })
- expect(created.error, JSON.stringify(created.error)).toBeUndefined()
- const sent = await rpc!.call('groups.send', {
- room_id: 'r-slot',
- event_id: 'u1',
- payload: { text: '@sentinel say hello', thread_id: 't1' }
- })
- expect(sent.error, JSON.stringify(sent.error)).toBeUndefined()
-
- const kinds = async () => {
- const log = await rpc!.call('groups.log', { room_id: 'r-slot', since_seq: 0, limit: 50 })
- return log.result.events.map((event: any) => event.kind) as string[]
- }
- await expect.poll(kinds, { timeout: 180_000, intervals: [1_000] }).toContain('message.member')
- await expect
- .poll(kinds, { timeout: 60_000, intervals: [1_000] })
- .toContain('room.activity')
-
- const slotsPath = path.join(fixture!.sandbox.hermesHome, 'profiles', 'sentinel', 'runtime', 'active_sessions.json')
- const botRoomSlots = () => {
- if (!fs.existsSync(slotsPath)) {
- return []
- }
- const entries = JSON.parse(fs.readFileSync(slotsPath, 'utf8')).entries ?? []
- return entries.filter((entry: any) => entry.surface === 'bot_room')
- }
- // The slot is claimed for the turn and must be gone once the turn settled — on the pre-fix build it
- // stays (updated_at === started_at) until the backend process exits.
- await expect.poll(botRoomSlots, { timeout: 20_000, intervals: [500] }).toEqual([])
-
- // Rendered surface control: the Desktop Bots pane is healthy alongside the backend-driven room.
- await openBots(page)
- await expect(page.getByRole('button', { name: /^sentinel\b/i }).filter({ visible: true }).first()).toBeVisible({
- timeout: 30_000
- })
- await page.screenshot({ path: 'test-results/hosted-rooms-backend-bots-pane.png' })
-})
diff --git a/apps/desktop/e2e/hosted-room-legacy-store-migration.spec.ts b/apps/desktop/e2e/hosted-room-legacy-store-migration.spec.ts
deleted file mode 100644
index 5fd76340334..00000000000
--- a/apps/desktop/e2e/hosted-room-legacy-store-migration.spec.ts
+++ /dev/null
@@ -1,180 +0,0 @@
-import { execFileSync, execSync } from 'node:child_process'
-import fs from 'node:fs'
-import path from 'node:path'
-
-import {
- buildAppEnv,
- createSandbox,
- launchDesktop,
- type MockBackendFixture,
- waitForAppReady,
- writeEnvFile,
- writeMockProviderConfig
-} from './fixtures'
-import { startMockServer } from '../../../tests-js/scripts/mock-server'
-import { expect, test } from './test'
-
-// Hosted Group Chat rooms live in the gateway, and the Desktop's own `hermes serve` backend runs
-// a room worker. The room store moved from the root state.db to shared-state.db without carrying
-// the rows across, so every room from before that upgrade answered "hosted room not found"
-// (#109775). Asserted against the REAL Electron app's spawned backend over its JSON-RPC socket,
-// with the pre-upgrade layout seeded on disk by the store's own writers.
-
-const REPO_ROOT = path.resolve(import.meta.dirname, '..', '..', '..')
-const PYTHON = process.env.HERMES_DESKTOP_PYTHON ?? path.join(REPO_ROOT, 'venv', 'bin', 'python')
-
-let fixture: MockBackendFixture | null = null
-let rpc: Rpc | null = null
-
-function seedProfile(hermesHome: string, mockUrl: string, name: string): void {
- const dir = path.join(hermesHome, 'profiles', name)
- fs.mkdirSync(dir, { recursive: true })
- writeMockProviderConfig(dir, mockUrl)
- writeEnvFile(dir)
-}
-
-/** Write a room + one user event into the PRE-isolation layout (root state.db) with the store's own writers. */
-function seedLegacyRoom(hermesHome: string): void {
- const script = `
-import sys
-from pathlib import Path
-from gateway import hosted_rooms
-legacy = Path(sys.argv[1]) / "state.db"
-hosted_rooms.create_room(legacy, room_id="oldroom", name="Pre-split room",
- members=[{"member_id": "m-sentinel", "profile": "sentinel", "handle": "sentinel"},
- {"member_id": "m-friday", "profile": "friday", "handle": "friday"}],
- authority_gateway_id="legacy", now=10)
-hosted_rooms.append_event(legacy, room_id="oldroom", event_id="user:u1", kind="message.user",
- actor={"kind": "user", "id": "desktop"}, payload={"text": "hello from before the upgrade", "thread_id": "t1"},
- authority_gateway_id="legacy", authority_epoch=1, now=11)
-print([r["room_id"] for r in hosted_rooms.list_rooms(legacy)])
-`
- const out = execFileSync(PYTHON, ['-c', script, hermesHome], {
- cwd: REPO_ROOT,
- env: { ...process.env, PYTHONPATH: REPO_ROOT },
- encoding: 'utf8'
- })
- if (!out.includes('oldroom')) {
- throw new Error(`legacy seed failed: ${out}`)
- }
-}
-
-/** Locate the Electron-spawned `hermes serve` backend for this sandbox: its port and session token. */
-function findBackend(hermesHome: string): { port: number; token: string; pid: number } {
- const pids = execSync(`pgrep -f "serve --host 127.0.0.1 --port 0" || true`, { encoding: 'utf8' })
- .split('\n')
- .map(s => s.trim())
- .filter(Boolean)
- for (const pidText of pids) {
- const pid = Number(pidText)
- let environ = ''
- try {
- environ = fs.readFileSync(`/proc/${pid}/environ`, 'latin1')
- } catch {
- continue
- }
- const vars = new Map(environ.split('\0').map(kv => [kv.slice(0, kv.indexOf('=')), kv.slice(kv.indexOf('=') + 1)]))
- if (vars.get('HERMES_HOME') !== hermesHome) {
- continue
- }
- const token = vars.get('HERMES_DASHBOARD_SESSION_TOKEN') ?? ''
- // The backend inherits Electron's remote-debugging socket fd too; the serve port is the listener
- // that only the hermes process holds.
- const listen = execSync(`ss -ltnp | grep "pid=${pid}," | grep -v electron || true`, { encoding: 'utf8' })
- const port = Number(/127\.0\.0\.1:(\d+)/.exec(listen)?.[1] ?? 0)
- if (token && port) {
- return { port, token, pid }
- }
- }
- throw new Error(`no hermes serve backend found for ${hermesHome} (pids: ${pids.join(',')})`)
-}
-
-/** Minimal JSON-RPC client over the backend's /api/ws (Node's global WebSocket; no Origin header is sent,
- * which the loopback backend accepts — the session token is the auth boundary). */
-class Rpc {
- private ws: WebSocket
- private id = 0
- private ready: Promise<void>
-
- constructor(port: number, token: string) {
- this.ws = new WebSocket(`ws://127.0.0.1:${port}/api/ws?token=${token}`)
- this.ready = new Promise((resolve, reject) => {
- this.ws.addEventListener('open', () => resolve(), { once: true })
- this.ws.addEventListener('error', () => reject(new Error(`ws upgrade to 127.0.0.1:${port} failed`)), { once: true })
- })
- }
-
- async call(method: string, params: Record<string, unknown> = {}): Promise<any> {
- await this.ready
- const id = `e2e-${++this.id}`
- return new Promise((resolve, reject) => {
- const onMessage = (event: MessageEvent) => {
- const frame = JSON.parse(String(event.data))
- if (frame.id === id) {
- this.ws.removeEventListener('message', onMessage)
- resolve(frame)
- }
- }
- this.ws.addEventListener('message', onMessage)
- this.ws.addEventListener('error', () => reject(new Error(`ws error during ${method}`)), { once: true })
- this.ws.send(JSON.stringify({ jsonrpc: '2.0', id, method, params }))
- })
- }
-
- close(): void {
- this.ws.close()
- }
-}
-
-test.beforeAll(async () => {
- const mock = await startMockServer()
- const sandbox = createSandbox('hosted-rooms-backend')
- writeMockProviderConfig(sandbox.hermesHome, mock.url)
- writeEnvFile(sandbox.hermesHome)
- seedProfile(sandbox.hermesHome, mock.url, 'sentinel')
- seedProfile(sandbox.hermesHome, mock.url, 'friday')
- seedLegacyRoom(sandbox.hermesHome)
- expect(fs.existsSync(path.join(sandbox.hermesHome, 'shared-state.db'))).toBe(false)
-
- const { app, page } = await launchDesktop(buildAppEnv(sandbox))
- fixture = {
- app,
- page,
- mock,
- mockUrl: mock.url,
- sandbox,
- cleanup: async () => {
- rpc?.close()
- await app.close().catch(() => undefined)
- await mock.close()
- sandbox.cleanup()
- }
- }
- await waitForAppReady(fixture, 120_000)
- const backend = findBackend(sandbox.hermesHome)
- rpc = new Rpc(backend.port, backend.token)
-})
-
-test.afterAll(async () => {
- await fixture?.cleanup()
- fixture = null
-})
-
-test('rooms from before the shared-state.db split are still reachable from the Desktop backend (#109775)', async () => {
- test.setTimeout(300_000)
- const caps = await rpc!.call('groups.capabilities')
- expect(caps.result?.driver).toBe(true)
-
- const listed = await rpc!.call('groups.list')
- expect(listed.result?.rooms.map((room: any) => room.room_id)).toContain('oldroom')
-
- const state = await rpc!.call('groups.state', { room_id: 'oldroom' })
- expect(state.error, JSON.stringify(state.error)).toBeUndefined()
- expect(state.result.room.latest_seq).toBe(1)
-
- const log = await rpc!.call('groups.log', { room_id: 'oldroom', since_seq: 0, limit: 20 })
- expect(log.result.events.map((event: any) => event.kind)).toEqual(['message.user'])
- // Storage truth: the store now lives in shared-state.db and the legacy file was left intact.
- expect(fs.existsSync(path.join(fixture!.sandbox.hermesHome, 'shared-state.db'))).toBe(true)
- expect(fs.existsSync(path.join(fixture!.sandbox.hermesHome, 'state.db'))).toBe(true)
-})
diff --git a/apps/desktop/e2e/interface-mode.spec.ts b/apps/desktop/e2e/interface-mode.spec.ts
deleted file mode 100644
index 8b839ed11cc..00000000000
--- a/apps/desktop/e2e/interface-mode.spec.ts
+++ /dev/null
@@ -1,115 +0,0 @@
-/**
- * E2E: Interface mode round trip against a real backend.
- *
- * Simple is a resolver input, not a preference writer. The scenario walks the
- * Advanced → Simple → Advanced loop from the layout editor and asserts what an
- * install would notice: the instrumentation leaves (titlebar tools beyond
- * Settings + Layout editor, the statusbar, the machinery rows in the sidebar),
- * the one-key reveal still opens the terminal for the session, and on the way
- * back shared preferences remain byte-identical. Arrangement records belong
- * to each mode and are covered by the layout-memory regression suite.
- *
- * Prerequisite: `npm run build` must have been run so dist/ exists.
- */
-import { type MockBackendFixture, setupMockBackend, waitForAppReady } from './fixtures'
-import { expect, test } from './test'
-
-const MODE_KEY = 'hermes.desktop.interfaceMode.v1'
-// The E2E contract names only arrangement keys; importing renderer stores here
-// couples the Playwright process to the app's browser-only module graph.
-const ARRANGEMENT_KEYS = [
- 'hermes.desktop.floatingPanes.v1',
- 'hermes.desktop.layoutTree.v2',
- 'hermes.desktop.layoutPreset.active',
- 'hermes.desktop.paneStates.v1',
- 'hermes.desktop.dismissedPanes.v1',
- 'hermes.desktop.paneShare.v1',
- 'hermes.desktop.hiddenStripTabs.v1',
- 'hermes.desktop.userPlacedPanes.v1',
- 'hermes.desktop.panesFlipped',
- 'hermes.desktop.collapsedTreeSides.v1'
-]
-
-let fixture: MockBackendFixture | null = null
-
-test.beforeAll(async () => {
- fixture = await setupMockBackend()
- await waitForAppReady(fixture)
-})
-
-test.afterAll(async () => {
- await fixture?.cleanup()
- fixture = null
-})
-
-/** Shared preferences exclude the mode selector and its arrangement records. */
-async function preferenceSnapshot(page: MockBackendFixture['page']): Promise<Record<string, string>> {
- return page.evaluate(
- ({ modeKey, layoutKeys }) => {
- const arrangement = new Set(layoutKeys.flatMap(key => [key, `${key}.simple`]))
- arrangement.add('hermes.desktop.layoutModeScopes.v1')
- const out: Record<string, string> = {}
- for (let i = 0; i < window.localStorage.length; i += 1) {
- const key = window.localStorage.key(i)
- if (key && key.startsWith('hermes.desktop.') && key !== modeKey && !arrangement.has(key)) {
- out[key] = window.localStorage.getItem(key) ?? ''
- }
- }
- return out
- },
- { modeKey: MODE_KEY, layoutKeys: ARRANGEMENT_KEYS }
- )
-}
-
-async function pickMode(page: MockBackendFixture['page'], mode: 'Simple' | 'Advanced'): Promise<void> {
- await page.getByRole('button', { name: 'Layout editor', exact: true }).click()
- const card = page.getByRole('button', { name: new RegExp(`^${mode}\\b`) })
- await expect(card).toBeVisible()
- await card.click()
- await expect(card).toHaveAttribute('aria-pressed', 'true')
- await page.getByRole('button', { name: 'Done', exact: true }).click()
-}
-
-test('Simple hides the machinery, keeps the doors, and leaves preferences untouched on the way back', async () => {
- const page = fixture!.page
- const appControls = page.getByRole('toolbar', { name: 'App controls' }).or(page.locator('[aria-label="App controls"]')).first()
-
- // Advanced (default): the usual chrome, and no mode record on disk.
- await expect(appControls.getByRole('button', { name: 'HUD mode', exact: true })).toBeVisible()
- await expect(page.locator('[data-slot="statusbar"]')).toBeVisible()
- expect(await page.evaluate((key: string) => window.localStorage.getItem(key), MODE_KEY)).toBeNull()
-
- const before = await preferenceSnapshot(page)
-
- await pickMode(page, 'Simple')
-
- // Titlebar: only Settings and the layout editor remain among the app actions.
- await expect(appControls.getByRole('button', { name: 'HUD mode', exact: true })).toHaveCount(0)
- await expect(appControls.getByRole('button', { name: 'Swap sidebar sides', exact: true })).toHaveCount(0)
- await expect(page.getByRole('button', { name: 'Open settings', exact: true })).toBeVisible()
- await expect(page.getByRole('button', { name: 'Layout editor', exact: true })).toBeVisible()
-
- // Statusbar and the sidebar's machinery rows are gone; the conversation isn't.
- await expect(page.locator('[data-slot="statusbar"]')).toHaveCount(0)
- await expect(page.getByRole('button', { name: /^Scheduled jobs/ })).toHaveCount(0)
- await expect(page.getByRole('button', { name: /^Capabilities/ })).toBeVisible()
- await expect(page.locator('textarea, [contenteditable="true"]').first()).toBeVisible()
-
- // Simple is a default, not a lock: the terminal reveal still answers for the session.
- await expect(page.locator('[data-terminal]').first()).toBeHidden()
- await page.keyboard.press('Control+`')
- await expect(page.locator('[data-terminal]').first()).toBeVisible()
-
- // Mode selection may save arrangements, never the shared preferences.
- expect(await page.evaluate((key: string) => window.localStorage.getItem(key), MODE_KEY)).not.toBeNull()
- expect(await preferenceSnapshot(page)).toEqual(before)
-
- await pickMode(page, 'Advanced')
-
- // Advanced is back and the session-only reveal has not changed shared preferences.
- await expect(appControls.getByRole('button', { name: 'HUD mode', exact: true })).toBeVisible()
- await expect(page.locator('[data-slot="statusbar"]')).toBeVisible()
- await expect(page.locator('[data-terminal]').first()).toBeHidden()
- expect(await page.evaluate((key: string) => window.localStorage.getItem(key), MODE_KEY)).toBeNull()
- expect(await preferenceSnapshot(page)).toEqual(before)
-})
diff --git a/apps/desktop/e2e/large-session-resume.spec.ts b/apps/desktop/e2e/large-session-resume.spec.ts
index 4dfaaa7d922..5ce6c915628 100644
--- a/apps/desktop/e2e/large-session-resume.spec.ts
+++ b/apps/desktop/e2e/large-session-resume.spec.ts
@@ -195,21 +195,6 @@ test.describe('large session resume', () => {
await assertUnchangedResume(fixture.page, testInfo)
})
- test('fast resume of an unchanged session has one user row and bounded transcript paints', async ({}, testInfo) => {
- // Known RED: a rapid warm resume rebuilds the transcript three times
- // (28 → 53 → 53 DOM additions) instead of the two-paint budget. Keep the
- // regression visible without making unrelated desktop work fail CI.
- test.fixme(true, 'Fast warm resume has an unresolved third transcript rebuild')
-
- fixture = await setupSeededDesktop()
- await waitForAppReady(fixture, 120_000)
-
- await openSeededSession(fixture.page)
- await openNewSession(fixture.page)
- await startPaintObserver(fixture.page)
- await assertUnchangedResume(fixture.page, testInfo)
- })
-
for (const resumeKind of ['fast', 'cold'] as const) {
test(`${resumeKind} resume keeps background inference attached without duplicate messages`, async ({}, testInfo) => {
fixture = await setupSeededDesktop({ holdFirstStreamForPrompt: BACKGROUND_PROMPT })
diff --git a/apps/desktop/e2e/launch-packaged-app.spec.ts b/apps/desktop/e2e/launch-packaged-app.spec.ts
deleted file mode 100644
index d52b261a3bb..00000000000
--- a/apps/desktop/e2e/launch-packaged-app.spec.ts
+++ /dev/null
@@ -1,177 +0,0 @@
-import { expect, test } from './test'
-
-import {
- PACKAGED_BINARY_PATH,
- type PackagedAppFixture,
- packagedBinaryExists,
- setupPackagedApp,
-} from './fixtures'
-import { expectVisualSnapshot } from './visual-snapshot'
-
-/**
- * E2E smoke tests for the packaged Hermes desktop app.
- *
- * Launches the real packaged Electron binary (produced by `npm run pack` →
- * `electron-builder --dir`) with BOOT_FAKE=1 and full sandbox isolation
- * (credential stripping, isolated HERMES_HOME + userData, unique app name).
- *
- * Skips if the packaged binary doesn't exist — run `npm run pack` first.
- */
-
-let fixture: PackagedAppFixture | null = null
-
-test.beforeAll(async () => {
- test.skip(
- !packagedBinaryExists(),
- `Built app binary not found: ${PACKAGED_BINARY_PATH}. Run 'npm run pack' first.`,
- )
-
- fixture = await setupPackagedApp()
-})
-
-test.afterAll(async () => {
- await fixture?.cleanup()
- fixture = null
-})
-
-test('window opens with the Hermes title', async () => {
- const title = await fixture!.page.title()
- expect(title).toContain('Hermes')
-})
-
-test('renderer loads and shows DOM content', async () => {
- const page = fixture!.page
- await page.waitForSelector('#root', { state: 'attached', timeout: 30_000 })
- const childCount = await page.locator('#root > *').count()
- expect(childCount).toBeGreaterThan(0)
-})
-
-test('boots to the app UI, not the QueryClient error boundary (#95560)', async () => {
- const page = fixture!.page
- await page.waitForSelector('#root', { state: 'attached', timeout: 30_000 })
-
- // Wait until the root has real content (boot overlay fades, app paints) —
- // the error boundary also paints, so assert on its absence explicitly.
- await page.waitForFunction(
- () => (document.getElementById('root')?.textContent ?? '').trim().length > 0,
- undefined,
- { timeout: 60_000 },
- )
-
- const text = await page.locator('#root').textContent()
- // The #95560 crash: a duplicate @tanstack/react-query runtime made the
- // QueryClientProvider's context invisible to useQuery, so the app hit the
- // error boundary at launch. Neither the boundary headline nor the throw
- // message may appear on a healthy boot.
- expect(text).not.toContain('No QueryClient set')
- expect(text).not.toContain('Something broke in the interface')
-})
-
-test('HUD composer remains fully inside the transparent window', async () => {
- const hudPagePromise = fixture!.app.waitForEvent('window')
-
- await fixture!.page.evaluate(() =>
- (window as typeof window & {
- hermesDesktop?: { hud?: { open: (options: { sessionId: null }) => Promise<void> } }
- }).hermesDesktop?.hud?.open({ sessionId: null })
- )
-
- const hudPage = await hudPagePromise
- await hudPage.waitForSelector('[data-slot="composer-rich-input"]', { state: 'visible' })
-
- const geometry = await hudPage.evaluate(() => {
- const dock = document.querySelector<HTMLElement>('[data-slot="composer-dock"]')
- const input = document.querySelector<HTMLElement>('[data-slot="composer-rich-input"]')
-
- if (!dock || !input) {
- throw new Error('HUD composer did not render')
- }
-
- const dockRect = dock.getBoundingClientRect()
- const inputRect = input.getBoundingClientRect()
-
- return {
- viewportWidth: window.innerWidth,
- viewportHeight: window.innerHeight,
- dockLeft: dockRect.left,
- dockRight: dockRect.right,
- dockTop: dockRect.top,
- dockBottom: dockRect.bottom,
- inputLeft: inputRect.left,
- inputRight: inputRect.right,
- inputTop: inputRect.top,
- inputBottom: inputRect.bottom,
- // The bug class this guards: a build-time CSS optimization folding the
- // dock's identity `translate` override into `transform`, leaving
- // Tailwind's standalone `translate: -50%` live and shifting the dock
- // half a window off-screen. Surface the computed value so a failure
- // says WHY the dock moved, not just that it did.
- dockTranslate: getComputedStyle(dock).translate,
- }
- })
-
- // Horizontal containment — the composer shifted half a window left when the
- // standalone `translate: -50%` survived optimization (#82214, #82233).
- expect(geometry.dockLeft).toBeGreaterThanOrEqual(0)
- expect(geometry.inputLeft).toBeGreaterThanOrEqual(0)
- expect(geometry.dockRight).toBeLessThanOrEqual(geometry.viewportWidth)
- expect(geometry.inputRight).toBeLessThanOrEqual(geometry.viewportWidth)
-
- // Vertical containment — the toolbar/transcript clipping reported on
- // Windows (#82203) and macOS (#82214) is the same "composer escapes the
- // window" class on the other axis.
- expect(geometry.dockTop).toBeGreaterThanOrEqual(0)
- expect(geometry.inputTop).toBeGreaterThanOrEqual(0)
- expect(geometry.dockBottom).toBeLessThanOrEqual(geometry.viewportHeight)
- expect(geometry.inputBottom).toBeLessThanOrEqual(geometry.viewportHeight)
-
- // The dock's centering translate must be fully neutralized. Any live
- // percentage translate means the HUD override lost to the app's centering.
- // (Computed `translate` keeps percentages as-is, so this is assertable;
- // computed `transform` resolves to a matrix and is covered by the
- // geometric containment checks above.)
- expect(geometry.dockTranslate ?? 'none').not.toContain('%')
-
- await hudPage.close()
-})
-
-test('boot progress overlay fades out or shows error state', async () => {
- const page = fixture!.page
- await page.waitForFunction(
- () => {
- const root = document.getElementById('root')
-
- if (!root) {
- return false
- }
-
- const text = root.textContent ?? ''
-
- // Error path: boot failure overlay renders an error message.
- if (text.includes('error') || text.includes('Error') || text.includes('failed')) {
- return true
- }
-
- // Success path: overlay disappears and the app renders. If there's
- // no "boot" / "starting" / "installing" text visible, boot has
- // completed (either to the main UI or to onboarding).
- const bootIndicators = ['starting', 'resolving', 'spawning', 'waiting', 'installing']
- const lower = text.toLowerCase()
-
- return !bootIndicators.some((word) => lower.includes(word))
- },
- undefined,
- { timeout: 60_000 },
- )
-})
-
-test('can capture a screenshot for the CI artifact', async () => {
- if (!fixture) {
- test.skip(true, 'Previous test failed — no app running')
-
- return
- }
-
- // Visual snapshot — won't fail on diff, just logs + generates diff image
- await expectVisualSnapshot(fixture!.page, { name: 'packaged-app-booted', timeout: 10_000, app: fixture!.app })
-})
diff --git a/apps/desktop/e2e/mock-backend-setup.spec.ts b/apps/desktop/e2e/mock-backend-setup.spec.ts
deleted file mode 100644
index 5bf9d112fb1..00000000000
--- a/apps/desktop/e2e/mock-backend-setup.spec.ts
+++ /dev/null
@@ -1,87 +0,0 @@
-/**
- * E2E tests asserting the mock backend gets the app past the setup/onboarding
- * screen.
- *
- * The mock backend fixture writes a config.yaml with a pre-configured mock
- * provider pointing at a mock inference server. When the app boots, the
- * runtime readiness check should detect the working provider and dismiss the
- * onboarding overlay — landing straight on the chat UI without ever showing
- * the "Let's get you setup with Hermes Agent" screen.
- *
- * If these tests fail, the mock backend config isn't getting the app past
- * onboarding — the chat interaction tests (chat.spec.ts) will also fail
- * because the composer is blocked by the setup overlay.
- *
- * Prerequisite: `npm run build` must have been run so dist/ exists.
- */
-
-import { expect, test } from './test'
-
-import {
- type MockBackendFixture,
- setupMockBackend,
- waitForAppReady,
-} from './fixtures'
-import { expectVisualSnapshot } from './visual-snapshot'
-
-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('mock backend gets past setup screen', () => {
- test('onboarding overlay is not shown', async () => {
- const page = fixture!.page
-
- // The onboarding overlay renders "Let's get you setup with Hermes Agent"
- // when the runtime check fails to find a working provider. With the mock
- // backend configured, the runtime check should pass and the overlay
- // returns null — this text should NOT be present in the DOM.
- await page.waitForFunction(
- () => {
- const text = document.body.textContent ?? ''
-
- return !text.includes("Let's get you setup")
- },
- undefined,
- { timeout: 30_000 },
- )
- })
-
- test('chat composer is visible', async () => {
- const page = fixture!.page
-
- // The composer (contenteditable div) should be visible and not blocked
- // by the onboarding overlay. If the first test passed, the overlay is
- // gone and the composer is the primary interactive surface.
- const composer = page.locator('[contenteditable="true"]').first()
- await expect(composer).toBeVisible()
- })
-
- test('can type into the composer', async () => {
- const page = fixture!.page
-
- // If the setup overlay is truly gone, the composer accepts input.
- const composer = page.locator('[contenteditable="true"]').first()
- await composer.click()
- await composer.type('hello mock backend', { delay: 20 })
-
- // Verify the typed text appears in the DOM.
- await page.waitForFunction(
- () => (document.body.textContent ?? '').includes('hello mock backend'),
- undefined,
- { timeout: 10_000 },
- )
- })
-
- test('screenshot shows chat UI without setup screen', async () => {
- await expectVisualSnapshot(fixture!.page, { name: 'mock-backend-chat-ready', app: fixture!.app })
- })
-})
diff --git a/apps/desktop/e2e/onboarding-settings.spec.ts b/apps/desktop/e2e/onboarding-settings.spec.ts
deleted file mode 100644
index 6fe1253cdb5..00000000000
--- a/apps/desktop/e2e/onboarding-settings.spec.ts
+++ /dev/null
@@ -1,82 +0,0 @@
-import { readFileSync, unlinkSync, writeFileSync } from 'node:fs'
-import { createRequire } from 'node:module'
-import path from 'node:path'
-
-import { buildAppEnv, createSandbox, launchDesktop, setupNoProvider } from './fixtures'
-import { type ElectronApplication, expect, type Page, test } from './test'
-
-const { prepareWindowForInput } = createRequire(import.meta.url)(
- '../../../tests/install/e2e-assets/window-input.cjs',
-) as { prepareWindowForInput: (app: ElectronApplication, page: Page) => Promise<void> }
-
-test('input setup survives a fresh-install zoom restore before onboarding', async () => {
- const sandbox = createSandbox('cold-input')
- unlinkSync(path.join(sandbox.userDataDir, 'zoom-state.json'))
- writeFileSync(path.join(sandbox.hermesHome, 'config.yaml'), '# no provider\n', 'utf8')
- let app: ElectronApplication | undefined
-
- try {
- const launched = await launchDesktop(buildAppEnv(sandbox))
- app = launched.app
- const page = launched.page
- await page.waitForSelector('button', { state: 'attached' })
- await prepareWindowForInput(app, page)
- const later = page.getByRole('button', { name: /choose a provider later/i })
- await expect(later).toBeVisible({ timeout: 60_000 })
- const appWindow = await app.browserWindow(page)
- await appWindow.evaluate(win => win.emit('focus'))
- await expect.poll(() => appWindow.evaluate(win => win.webContents.getZoomFactor())).toBeCloseTo(1)
- await later.click({ timeout: 5_000 })
- await expect(later).toBeHidden()
- } finally {
- await app?.close().catch(() => undefined)
- sandbox.cleanup()
- }
-})
-
-// Exercise the install driver's input setup against the real renderer/backend,
-// with no installer, update, credentials, or live user data.
-for (const lifecycleEvent of ['focus', 'navigation'] as const) {
- test(`onboarding input zoom survives ${lifecycleEvent} and opens Settings`, async () => {
- const fixture = await setupNoProvider()
- const { app, page, sandbox } = fixture
-
- try {
- await prepareWindowForInput(app, page)
- const later = page.getByRole('button', { name: /choose a provider later/i })
- await expect(later).toBeVisible({ timeout: 60_000 })
- const zoomFile = path.join(sandbox.userDataDir, 'zoom-state.json')
- const savedLevel = () => JSON.parse(readFileSync(zoomFile, 'utf8')).zoomLevel as number
- await page.evaluate(() => {
- const desktop = (window as unknown as { hermesDesktop: { zoom: { setPercent: (percent: number) => void } } }).hermesDesktop
- desktop.zoom.setPercent(90)
- })
- await expect.poll(savedLevel).toBeCloseTo(Math.log(0.9) / Math.log(1.2))
-
- await prepareWindowForInput(app, page)
- const appWindow = await app.browserWindow(page)
-
- // The same lifecycle callback that fires when another window takes focus
- // must restore our input scale, not the original 90% preference.
- if (lifecycleEvent === 'focus') {
- await appWindow.evaluate(win => win.emit('focus'))
- } else {
- await page.evaluate(() => { window.location.hash = '#/settings' })
- }
-
- await expect.poll(() => appWindow.evaluate(win => win.webContents.getZoomFactor())).toBeCloseTo(1)
- expect(savedLevel()).toBe(0)
- await later.click({ timeout: 5_000 })
- await expect(later).toBeHidden()
-
- if (lifecycleEvent === 'navigation') {
- await page.evaluate(() => { window.location.hash = '#/' })
- }
-
- await page.getByRole('button', { name: 'Open settings', exact: true }).click({ timeout: 5_000 })
- await expect(page).toHaveURL(/settings/)
- } finally {
- await fixture.cleanup()
- }
- })
-}
diff --git a/apps/desktop/e2e/onboarding.spec.ts b/apps/desktop/e2e/onboarding.spec.ts
index 3c0afa0ecec..7e4d1cadb16 100644
--- a/apps/desktop/e2e/onboarding.spec.ts
+++ b/apps/desktop/e2e/onboarding.spec.ts
@@ -9,7 +9,7 @@
* Prerequisite: `npm run build` must have been run so dist/ exists.
*/
-import { expect, test } from './test'
+import { test } from './test'
import {
type NoProviderFixture,
@@ -35,35 +35,6 @@ test.describe('onboarding with no provider configured', () => {
await waitForOnboarding(fixture.page, 90_000)
})
- test('onboarding shows provider options or API key form', async () => {
- if (!fixture) {
- test.skip(true, 'Previous test failed — no app running')
-
- return
- }
-
- const page = fixture.page
-
- // The onboarding overlay should contain provider-related text.
- // It might show OAuth providers, an API key form, or a "choose later"
- // link. Verify at least one of these is visible.
- const rootText = await page.evaluate(() => {
- const root = document.getElementById('root')
-
- return root?.textContent ?? ''
- })
-
- const hasProviderText =
- rootText.includes('provider') ||
- rootText.includes('Provider') ||
- rootText.includes('API key') ||
- rootText.includes('Sign in') ||
- rootText.includes('OpenRouter') ||
- rootText.includes('OpenAI')
-
- expect(hasProviderText).toBe(true)
- })
-
test('screenshot of onboarding overlay', async () => {
if (!fixture) {
test.skip(true, 'Previous test failed — no app running')
diff --git a/apps/desktop/e2e/right-pane.spec.ts b/apps/desktop/e2e/right-pane.spec.ts
deleted file mode 100644
index 5447955f452..00000000000
--- a/apps/desktop/e2e/right-pane.spec.ts
+++ /dev/null
@@ -1,138 +0,0 @@
-import { test, expect } from './test'
-
-import {
- type MockBackendFixture,
- setupMockBackend,
- waitForAppReady,
-} from './fixtures'
-
-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('persistent terminal overlay follows the pane after split dragging', async () => {
- const page = fixture!.page
-
- await page.keyboard.press('Control+`')
- await page.locator('[data-terminal-slot]').waitFor({ state: 'visible', timeout: 30_000 })
- await page.locator('[data-persistent-terminal] .xterm').waitFor({ state: 'visible', timeout: 30_000 })
-
- const result = await page.evaluate(async () => {
- const slot = document.querySelector('[data-terminal-slot]')
- const overlay = document.querySelector('[data-persistent-terminal]')
-
- if (!slot || !overlay) {
- return { drift: -1, moved: 0, target: false }
- }
-
- const before = slot.getBoundingClientRect()
- const target = [...document.querySelectorAll<HTMLElement>('[role="separator"]')]
- .map(element => {
- const box = element.getBoundingClientRect()
- const horizontal = box.width > box.height
- const center = horizontal
- ? (box.top + box.bottom) / 2
- : (box.left + box.right) / 2
- const sides = horizontal
- ? [before.top, before.bottom]
- : [before.left, before.right]
-
- return {
- element,
- box,
- horizontal,
- score: Math.min(...sides.map(side => Math.abs(center - side))),
- }
- })
- .filter(item => item.box.width > 0 && item.box.height > 0)
- .sort((a, b) => a.score - b.score)[0]
-
- if (!target) {
- return { drift: -1, moved: 0, target: false }
- }
-
- const x = target.box.left + target.box.width / 2
- const y0 = target.box.top + target.box.height / 2
- const nearestSide = target.horizontal
- ? Math.abs(y0 - before.top) < Math.abs(y0 - before.bottom)
- ? 'top'
- : 'bottom'
- : Math.abs(x - before.left) < Math.abs(x - before.right)
- ? 'left'
- : 'right'
- const deltaX = nearestSide === 'left' ? -1 : nearestSide === 'right' ? 1 : 0
- const deltaY = nearestSide === 'top' ? -1 : nearestSide === 'bottom' ? 1 : 0
- let currentX = x
- let y = y0
- const pointer = {
- bubbles: true,
- cancelable: true,
- pointerId: 71,
- pointerType: 'mouse',
- isPrimary: true,
- button: 0,
- buttons: 1,
- }
-
- target.element.dispatchEvent(
- new PointerEvent('pointerdown', { ...pointer, clientX: x, clientY: y }),
- )
-
- for (let index = 0; index < 24; index += 1) {
- currentX += deltaX
- y += deltaY
- window.dispatchEvent(
- new PointerEvent('pointermove', {
- ...pointer,
- clientX: currentX,
- clientY: y,
- }),
- )
- await new Promise<void>(resolve => requestAnimationFrame(() => resolve()))
- }
-
- window.dispatchEvent(
- new PointerEvent('pointerup', {
- ...pointer,
- buttons: 0,
- clientX: currentX,
- clientY: y,
- }),
- )
- await new Promise<void>(resolve => setTimeout(resolve, 350))
- await new Promise<void>(resolve =>
- requestAnimationFrame(() => requestAnimationFrame(() => resolve())),
- )
-
- const next = slot.getBoundingClientRect()
- const fixed = overlay.getBoundingClientRect()
-
- return {
- drift: Math.max(
- Math.abs(next.top - fixed.top),
- Math.abs(next.left - fixed.left),
- Math.abs(next.width - fixed.width),
- Math.abs(next.height - fixed.height),
- ),
- moved: Math.max(
- Math.abs(next.top - before.top),
- Math.abs(next.left - before.left),
- Math.abs(next.width - before.width),
- Math.abs(next.height - before.height),
- ),
- target: true,
- }
- })
-
- expect(result.target).toBe(true)
- expect(result.moved).toBeGreaterThan(10)
- expect(result.drift).toBeLessThanOrEqual(1)
-})
diff --git a/apps/desktop/e2e/settings-scope-chips-bot-title.spec.ts b/apps/desktop/e2e/settings-scope-chips-bot-title.spec.ts
deleted file mode 100644
index 32e11c2fea5..00000000000
--- a/apps/desktop/e2e/settings-scope-chips-bot-title.spec.ts
+++ /dev/null
@@ -1,90 +0,0 @@
-import fs from 'node:fs'
-import path from 'node:path'
-
-import {
- buildAppEnv,
- createSandbox,
- launchDesktop,
- type MockBackendFixture,
- waitForAppReady,
- writeEnvFile,
- writeMockProviderConfig
-} from './fixtures'
-import { startMockServer } from '../../../tests-js/scripts/mock-server'
-import { expect, test } from './test'
-
-// Settings' "Applies to" chips named every profile by its canonical slug
-// (`alpha`, `beta`) while the Bots roster called the same agents by their Bot
-// title / display name (#109686). The chip must read the presentation name the
-// rest of the app uses; the slug stays the identity underneath.
-
-let fixture: MockBackendFixture | null = null
-
-function seedProfile(hermesHome: string, mockUrl: string, name: string, profileYaml: string): void {
- const dir = path.join(hermesHome, 'profiles', name)
- fs.mkdirSync(dir, { recursive: true })
- writeMockProviderConfig(dir, mockUrl)
- writeEnvFile(dir)
- fs.writeFileSync(path.join(dir, 'profile.yaml'), profileYaml, 'utf8')
-}
-
-test.beforeAll(async () => {
- const mock = await startMockServer()
- const sandbox = createSandbox('settings-chips')
- writeMockProviderConfig(sandbox.hermesHome, mock.url)
- writeEnvFile(sandbox.hermesHome)
- // A Bot Mode bot: the roster shows ui_meta['hermes-bots'].title.
- seedProfile(sandbox.hermesHome, mock.url, 'alpha', 'ui_meta:\n hermes-bots:\n title: Atlas Prime\n')
- // A renamed profile: `hermes profile rename` writes display_name.
- seedProfile(sandbox.hermesHome, mock.url, 'beta', 'display_name: Beacon\n')
-
- 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('Settings "Applies to" chips read the Bot title / display name, not the slug', async () => {
- test.setTimeout(300_000)
- const page = fixture!.page
-
- await page.evaluate(() => {
- window.location.hash = '#/settings'
- })
-
- // Chips carry their label as visible text (the profile rail's avatars only
- // carry it as aria-label), so filter by text to target the Settings strip.
- const chip = (label: string) => page.getByRole('button', { name: label, exact: true }).filter({ hasText: label })
- await expect(chip('Atlas Prime').first()).toBeVisible({ timeout: 60_000 })
- await expect(chip('Beacon').first()).toBeVisible({ timeout: 15_000 })
- // The slug is the identity, never the label.
- await expect(chip('alpha')).toHaveCount(0)
- await expect(chip('beta')).toHaveCount(0)
- // The root profile keeps its slug when it has neither title nor display name (control).
- await expect(chip('default').first()).toBeVisible()
-
- // Selecting by presentation label still scopes by the canonical slug: the
- // "applies to" note names the target by the same label as its chip.
- await chip('Atlas Prime').first().click()
- const note = page.getByRole('status').filter({ hasText: 'Atlas Prime' }).first()
- await expect(note).toBeVisible({ timeout: 10_000 })
- await expect(note).not.toContainText('alpha')
-
- await page.screenshot({ path: 'test-results/settings-scope-chips-bot-title.png' })
-})
diff --git a/apps/desktop/e2e/task-panel-clearance.spec.ts b/apps/desktop/e2e/task-panel-clearance.spec.ts
deleted file mode 100644
index e6bcf6eb064..00000000000
--- a/apps/desktop/e2e/task-panel-clearance.spec.ts
+++ /dev/null
@@ -1,145 +0,0 @@
-/**
- * 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 '../../../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 --git a/apps/desktop/e2e/tile-unread-bug.spec.ts b/apps/desktop/e2e/tile-unread-bug.spec.ts
deleted file mode 100644
index c242ef3461f..00000000000
--- a/apps/desktop/e2e/tile-unread-bug.spec.ts
+++ /dev/null
@@ -1,274 +0,0 @@
-/**
- * E2E tests for the tile-unread bug — two scenarios:
- *
- * 1. TAB (stacked, not visible) — a session opened as a tab via ⌃-click is
- * NOT visible on screen. When it finishes, the green "unread" dot IS
- * correct — the user isn't looking at it. This test PASSES.
- *
- * 2. SPLIT (side-by-side, visible) — a session dragged to the edge of the
- * workspace zone opens as a split tile, visible on screen at the same time
- * as the main session. When it finishes, it should NOT get the green
- * "unread" dot — the user is looking right at it. This test FAILS until
- * the fix in session-states.ts:174 lands (the unread check only compares
- * against $selectedStoredSessionId and ignores $sessionTiles).
- *
- * Prerequisite: `npm run build` must have been run so dist/ exists.
- */
-
-import { expect, test } from '@playwright/test'
-
-import {
- type MockBackendFixture,
- setupMockBackend,
- waitForAppReady,
-} from './fixtures'
-import {
- type BackgroundReleaseHandle,
- createBackgroundReleaseHandle,
- restartMockServer,
- SIDEBAR_CROSS_TEXTS,
-} from '../../../tests-js/scripts/mock-server'
-
-/** Finished-unread dot aria-label. */
-const UNREAD_DOT_LABEL = 'Finished — unread'
-/** Background-running dot aria-label. */
-const BG_DOT_LABEL = 'Background task running'
-/** Foreground turn-running dot aria-label. */
-const SESSION_RUNNING_DOT_LABEL = 'Session running'
-
-/**
- * The auto-title auxiliary call hits the SAME mock provider as the chat turn,
- * and its request carries the user's message — trigger keyword included. The
- * mock's trigger matching is text-based, so the title call consumes a script
- * index: the real chat turn then gets turn 2 (final answer, NO tool calls),
- * the background process is never spawned, and the bg dot never appears.
- * Whether that happens depends on which request lands first — the CI flake
- * this spec had. Disable auto-title so script indices line up with real chat
- * turns (same fix as interim-messages.spec.ts).
- */
-const DISABLE_AUTO_TITLE = 'auxiliary:\n title_generation:\n enabled: false'
-
-/** Locate a session's sidebar row by its preview text. */
-function sessionRow(page: import('@playwright/test').Page, text: string) {
- return page.locator('[data-slot="sidebar"] button').filter({ hasText: text }).first()
-}
-
-/** Common setup: start a turn with a held bg process + subagent, wait for
- * the turn to complete, then switch to a new session so the first session is
- * no longer $selectedStoredSessionId (required before opening a tile). */
-async function startTurnAndSwitchAway(page: import('@playwright/test').Page) {
- // Send E2E_SIDEBAR_CROSS — starts a turn with sleep 5 + subagent.
- const composer = page.locator('[contenteditable="true"]').first()
- await composer.waitFor({ state: 'visible', timeout: 10_000 })
- await composer.click()
- await composer.type('E2E_SIDEBAR_CROSS', { delay: 20 })
- await page.keyboard.press('Enter')
-
- // Wait for the user's message to appear.
- await page.waitForFunction(
- () => (document.body.textContent ?? '').includes('E2E_SIDEBAR_CROSS'),
- undefined,
- { timeout: 15_000 },
- )
-
- // NOTE: while the turn is busy the dot-state priority paints the session as
- // "working" ('Session running'), which OUTRANKS the background claim — the
- // 'Background task running' dot only appears once the turn completes while
- // the (sentinel-held) process is still alive. Polling for the bg dot mid-turn
- // races the turn length (two model trips + a real subagent spawn) against
- // the poll budget, which is exactly the flake this spec had on CI. So: wait
- // for the turn to END first, then assert the bg dot as a stable state.
-
- // The final answer text streams before message.complete, so text visibility
- // alone is not a completion barrier. Wait for the foreground-running state
- // to clear before asserting the background-process state.
- await page.waitForFunction(
- (text) => (document.body.textContent ?? '').includes(text),
- SIDEBAR_CROSS_TEXTS.finalText,
- { timeout: 90_000 },
- )
- await expect
- .poll(
- () => page.locator(`[aria-label="${SESSION_RUNNING_DOT_LABEL}"]`).count(),
- { timeout: 30_000, message: 'session running dot should disappear after turn completes' },
- )
- .toBe(0)
-
- // The background dot must be visible now: the turn is done but the process
- // is held open by the sentinel, so this is a stable state rather than a
- // window we have to catch in time. Poll rather than sampling once — the
- // dot flip is event-driven off the busy=false publish and can land a tick
- // after the running dot clears.
- await expect
- .poll(
- () => page.locator(`[aria-label="${BG_DOT_LABEL}"]`).count(),
- { timeout: 30_000, message: 'background dot should be visible after turn completes' },
- )
- .toBeGreaterThan(0)
-
- // Switch to a new session — session A is no longer $selectedStoredSessionId.
- // This is required: openSessionTile bails if the session is already selected.
- await page.locator('button:has-text("New session")').first().click()
- await page.waitForTimeout(2000)
-}
-
-/** Release the held background process, then wait for its dot to clear. */
-async function waitForBgProcessToFinish(
- page: import('@playwright/test').Page,
- release?: BackgroundReleaseHandle,
-) {
- release?.release()
- await expect
- .poll(
- () => page.locator(`[aria-label="${BG_DOT_LABEL}"]`).count(),
- { timeout: 30_000, message: 'background dot should disappear after process finishes' },
- )
- .toBe(0)
-}
-
-// ────────────────────────────────────────────────────────────────────────
-// Test 1: TAB (not visible) — unread dot IS correct (PASSES)
-// ────────────────────────────────────────────────────────────────────────
-
-test.describe('sidebar states — tab (hidden) unread is correct', () => {
- test.describe.configure({ mode: 'serial' })
-
- let fixture: MockBackendFixture
- const bgRelease = createBackgroundReleaseHandle()
-
- test.beforeAll(async () => {
- restartMockServer()
- fixture = await setupMockBackend({
- extraConfig: DISABLE_AUTO_TITLE,
- mockServer: { backgroundReleasePath: bgRelease.path },
- })
- await waitForAppReady(fixture, 120_000)
- })
-
- test.afterAll(async () => {
- bgRelease.release()
- await fixture?.cleanup()
- bgRelease.cleanup()
- })
-
- test('session opened as a tab (not visible) correctly gets unread dot', async () => {
- const page = fixture.page
-
- await startTurnAndSwitchAway(page)
-
- // Evidence: session A is in the background (bg dot in sidebar).
- await page.screenshot({ path: 'test-results/tile-bug-tab-switched-away.png' })
-
- // ⌃-click opens the session as a TAB (center dock = stacked, not visible
- // unless it's the active tab). The session is NOT on screen.
- //
- // With auto-title disabled the sidebar row is titled by the user's
- // message (the trigger keyword), not the assistant's final text.
- const row = sessionRow(page, 'E2E_SIDEBAR_CROSS')
- await row.click({ modifiers: ['Control'] })
- await page.waitForTimeout(2000)
-
- // Evidence: the tab is open but the session is not visible on screen.
- await page.screenshot({ path: 'test-results/tile-bug-tab-opened.png' })
-
- await waitForBgProcessToFinish(page, bgRelease)
-
- // A tab that's not the active tab IS hidden — the unread dot is correct.
- // The user is NOT looking at it, so marking it "unread" is right.
- //
- // Poll rather than sampling once: "finished-unread" is an event-driven
- // transition that lands slightly after the running dot clears, and with a
- // released (rather than slowly-expiring) process there is no incidental
- // slack between the two. Same reasoning as the cross-session spec.
- await expect
- .poll(
- () => page.locator(`[aria-label="${UNREAD_DOT_LABEL}"]`).count(),
- { timeout: 30_000, message: 'hidden tab should be marked unread' },
- )
- .toBeGreaterThan(0)
-
- await page.screenshot({ path: 'test-results/tile-bug-tab-unread-correct.png' })
- })
-})
-
-// ────────────────────────────────────────────────────────────────────────
-// Test 2: SPLIT (visible) — unread dot is WRONG (FAILS until fix)
-// ────────────────────────────────────────────────────────────────────────
-
-test.describe.skip('sidebar states — split (visible) unread bug (RED)', () => {
- test.describe.configure({ mode: 'serial' })
-
- let fixture: MockBackendFixture
- const bgRelease = createBackgroundReleaseHandle()
-
- test.beforeAll(async () => {
- restartMockServer()
- fixture = await setupMockBackend({
- extraConfig: DISABLE_AUTO_TITLE,
- mockServer: { backgroundReleasePath: bgRelease.path },
- })
- await waitForAppReady(fixture, 120_000)
- })
-
- test.afterAll(async () => {
- bgRelease.release()
- await fixture?.cleanup()
- bgRelease.cleanup()
- })
-
- test('session visible in a split tile does NOT get unread dot when it finishes', async () => {
- const page = fixture.page
-
- await startTurnAndSwitchAway(page)
-
- // Evidence: session A is in the background (bg dot in sidebar).
- await page.screenshot({ path: 'test-results/tile-bug-split-switched-away.png' })
-
- // Drag the session row from the sidebar to the right edge of the workspace
- // zone to create a SPLIT (side-by-side) tile. This triggers the real
- // startSessionDrag → onCommit → openSessionTile(id, 'right', anchor) path.
- // With auto-title disabled the sidebar row is titled by the user's message.
- const row = sessionRow(page, 'E2E_SIDEBAR_CROSS')
- const rowBox = await row.boundingBox()
- expect(rowBox, 'session row must be visible').not.toBeNull()
-
- // Find the workspace zone — the main chat area. We drop on its right edge.
- const workspace = page.locator('[data-session-anchor="workspace"]')
- const wsBox = await workspace.boundingBox()
- expect(wsBox, 'workspace zone must be visible').not.toBeNull()
-
- // Drag from the session row to the right edge of the workspace.
- // The drag-session's subZonePosition resolves a right-edge drop as 'right'
- // (a split dock), not 'center' (which would be a composer link).
- await page.mouse.move(rowBox!.x + rowBox!.width / 2, rowBox!.y + rowBox!.height / 2)
- await page.mouse.down()
- // Move in steps so the drag-session's pointermove handler tracks the
- // position and resolves the drop zone (a single jump can miss the
- // threshold/engage logic).
- const targetX = wsBox!.x + wsBox!.width - 20
- const targetY = wsBox!.y + wsBox!.height / 2
- const steps = 10
- for (let i = 1; i <= steps; i++) {
- const x = rowBox!.x + rowBox!.width / 2 + (targetX - (rowBox!.x + rowBox!.width / 2)) * (i / steps)
- const y = rowBox!.y + rowBox!.height / 2 + (targetY - (rowBox!.y + rowBox!.height / 2)) * (i / steps)
- await page.mouse.move(x, y)
- await page.waitForTimeout(30)
- }
- await page.mouse.up()
- await page.waitForTimeout(2000)
-
- // Evidence: the split tile is now open side-by-side — both sessions visible.
- await page.screenshot({ path: 'test-results/tile-bug-split-opened.png' })
-
- await waitForBgProcessToFinish(page, bgRelease)
-
- // THE BUG: the session visible in the split tile should NOT have the green
- // "finished unread" dot — the user is looking right at it. This assertion
- // FAILS until the fix in session-states.ts:174 lands.
- const unreadCount = await page.locator(`[aria-label="${UNREAD_DOT_LABEL}"]`).count()
- expect(unreadCount, 'session visible in a split tile should NOT be marked unread').toBe(0)
-
- // Evidence: the green dot should NOT be here — this screenshot shows the bug.
- await page.screenshot({ path: 'test-results/tile-bug-split-unread-should-not-exist.png' })
- })
-})
diff --git a/apps/desktop/e2e/warm-resume-jitter.spec.ts b/apps/desktop/e2e/warm-resume-jitter.spec.ts
index 83f9fb3646d..c0822ed9fb8 100644
--- a/apps/desktop/e2e/warm-resume-jitter.spec.ts
+++ b/apps/desktop/e2e/warm-resume-jitter.spec.ts
@@ -23,9 +23,9 @@
* adding/removing nodes (same keys → in-place prop update → no
* MutationObserver burst), but `$messages` was still set twice.
*
- * The test passes when bursts === 1 AND reconciles === 0.
* The sidebar "+" keeps the session warm in another tab. Its reactivation
- * follows the same contract: one additive paint and zero reconciles.
+ * must not rebuild the kept-alive transcript: zero additive bursts and zero
+ * reconciles.
*
* Prerequisite: `npm run build` must have been run so dist/ exists.
*/
@@ -299,12 +299,6 @@ async function waitForActiveTranscriptWithoutText(
)
}
-/** Replace the primary surface with a draft while retaining its warm cache. */
-async function openFreshDraft(page: import('@playwright/test').Page, priorText: string): Promise<void> {
- await page.keyboard.press(process.platform === 'darwin' ? 'Meta+N' : 'Control+N')
- await waitForActiveTranscriptWithoutText(page, priorText)
-}
-
/** Stack an empty tab while leaving the current transcript mounted and warm. */
async function openNewSessionTab(page: import('@playwright/test').Page, priorText: string): Promise<void> {
await page.locator('[data-slot="sidebar"] button[aria-label="New session"]').first().click()
@@ -353,22 +347,6 @@ function assertNoRepaint(result: { bursts: number; mutations: number; timeline:
).toBe(0)
}
-/** Assert the render counter shows exactly one paint with no re-renders. */
-function assertNoJitter(result: { bursts: number; mutations: number; timeline: number[]; reconciles: number } | null): void {
- expect(result, 'MutationObserver should have recorded render data').toBeTruthy()
- expect(
- result!.bursts,
- `Expected 1 additive render burst (single paint), but got ${result!.bursts} bursts. ` +
- `Mutation timeline: ${JSON.stringify(result!.timeline)}.`,
- ).toBe(1)
- expect(
- result!.reconciles,
- `Expected 0 reconciles (no re-render after initial paint), but got ${result!.reconciles}. ` +
- `This means the warm-route resume re-rendered the transcript after the initial paint ` +
- `— the "warm resume jitter" bug is present.`,
- ).toBe(0)
-}
-
test('tab reactivation preserves the mounted transcript without repainting', async ({}, testInfo) => {
const page = fixture!.page
@@ -409,69 +387,3 @@ test('tab reactivation preserves the mounted transcript without repainting', asy
await page.screenshot({ path: testInfo.outputPath('warm-resume-idle.png') })
assertNoRepaint(result)
})
-
-test('warm-route resume after background inference completes (no jitter)', async ({}, testInfo) => {
- test.fixme(
- true,
- 'Warm resume repaints after inference: expected one additive burst, got two ([18,1]).',
- )
-
- const page = fixture!.page
- const { mock } = fixture!
-
- // Wait for the sidebar to populate with our seeded session.
- const sessionRow = page
- .locator('[data-slot="sidebar"] button')
- .filter({ hasText: SESSION_TITLE })
- .first()
- await sessionRow.waitFor({ state: 'visible', timeout: 60_000 })
-
- // Step 1: Cold resume — populate the warm cache.
- await sessionRow.click()
- await waitForActiveTranscriptText(page, FIRST_USER_MSG)
- await page.waitForTimeout(2_000)
-
- // Step 2: Send a message — triggers inference via the mock server.
- const PROMPT = 'E2E post-inference warm resume test prompt'
- const composer = page.locator('[contenteditable="true"]').first()
- await composer.click()
- await composer.type(PROMPT, { delay: 10 })
- await page.keyboard.press('Enter')
-
- // Wait for the mock response to appear in the transcript, confirming
- // the turn completed and message.complete fired (which updates the warm
- // cache via updateSessionState).
- await waitForActiveTranscriptText(page, 'mock inference server', 60_000)
- // Extra settle for message.complete → updateSessionState → cache write.
- await page.waitForTimeout(2_000)
-
- // Verify the prompt was received by the mock server.
- expect(mock.receivedPrompts).toContain(PROMPT)
-
- // Step 3: Replace the primary chat; the warm cache retains the updated messages.
- await openFreshDraft(page, PROMPT)
- await page.waitForTimeout(500)
-
- // Step 4: Install render counter, click back (warm resume), wait, assert.
- await installRenderCounter(page)
- await sessionRow.click()
-
- // Wait for the transcript to reappear — the warm cache should already
- // have the completed turn (updated by message.complete events).
- await waitForActiveTranscriptText(page, FIRST_USER_MSG)
-
- // Wait for at least 1 burst, then settle.
- await page.waitForFunction(
- () => {
- const w = window as unknown as { __RENDER_COUNT__?: { bursts: number } }
- return Boolean(w.__RENDER_COUNT__ && w.__RENDER_COUNT__.bursts > 0)
- },
- undefined,
- { timeout: 10_000 },
- )
- await page.waitForTimeout(2_000)
-
- const result = await readRenderCount(page)
- await page.screenshot({ path: testInfo.outputPath('warm-resume-post-inference.png') })
- assertNoJitter(result)
-})
diff --git a/apps/desktop/e2e/worktree-branch-status.spec.ts b/apps/desktop/e2e/worktree-branch-status.spec.ts
deleted file mode 100644
index 66c821a7bc8..00000000000
--- a/apps/desktop/e2e/worktree-branch-status.spec.ts
+++ /dev/null
@@ -1,243 +0,0 @@
-import { execFileSync } from 'node:child_process'
-import * as fs from 'node:fs'
-import * as path from 'node:path'
-
-import {
- buildAppEnv,
- createSandbox,
- launchDesktop,
- type MockBackendFixture,
- waitForAppReady,
- writeEnvFile,
- writeMockProviderConfig,
-} from './fixtures'
-import { startMockServer } from '../../../tests-js/scripts/mock-server'
-import { expect, test } from './test'
-import { expectVisualSnapshot } from './visual-snapshot'
-
-const BRANCH_NAME = 'e2e-composer-branch'
-
-/**
- * Enough branches to make both the base-branch popover and the convert-branch
- * list taller than their default height. That is the condition in which the
- * dialog's own scroll box clips the popover, and that regression is what the
- * visual snapshots here guard against.
- */
-const EXTRA_BRANCHES = [
- 'feature/alpha-one',
- 'feature/beta-two',
- 'feature/gamma-three',
- 'fix/delta-four',
- 'fix/epsilon-five',
- 'chore/zeta-six',
- 'chore/eta-seven',
- 'spike/theta-eight',
- 'spike/iota-nine',
- 'release/kappa-ten',
-]
-
-function createGitRepo(root: string): string {
- const repo = path.join(root, 'repo')
-
- fs.mkdirSync(repo, { recursive: true })
- execFileSync('git', ['init', '--initial-branch=main'], { cwd: repo })
- execFileSync('git', ['config', 'user.email', '[email protected]'], { cwd: repo })
- execFileSync('git', ['config', 'user.name', 'Hermes E2E'], { cwd: repo })
- fs.writeFileSync(path.join(repo, 'README.md'), '# E2E repo\n', 'utf8')
- execFileSync('git', ['add', 'README.md'], { cwd: repo })
- execFileSync('git', ['commit', '-m', 'initial'], { cwd: repo })
-
- for (const branch of EXTRA_BRANCHES) {
- execFileSync('git', ['branch', branch], { cwd: repo })
- }
-
- return repo
-}
-
-function configureRepoCwd(hermesHome: string, mockUrl: string, repo: string): void {
- writeMockProviderConfig(hermesHome, mockUrl)
- fs.appendFileSync(path.join(hermesHome, 'config.yaml'), `\nterminal:\n cwd: ${repo}\n`, 'utf8')
- writeEnvFile(hermesHome)
-}
-
-let fixture: MockBackendFixture | null = null
-
-/** A dialog renders as `[data-slot="dialog-content"]` (components/ui/dialog.tsx). */
-const DIALOG = '[data-slot="dialog-content"]'
-
-/** Open the worktree dialog with the global ⌘⇧B / ctrl+shift+B hotkey. */
-async function openWorktreeDialog(): Promise<void> {
- const page = fixture!.page
- await page.keyboard.press('Control+Shift+B')
- await expect(page.locator(DIALOG)).toBeVisible()
-}
-
-/** Close the open dialog and wait until it leaves the DOM. */
-async function closeDialog(): Promise<void> {
- const page = fixture!.page
- await page.keyboard.press('Escape')
- await expect(page.locator(DIALOG)).toHaveCount(0)
-}
-
-test.beforeAll(async () => {
- const sandbox = createSandbox('worktree-branch-status')
- const repo = createGitRepo(sandbox.root)
- const mock = await startMockServer()
-
- configureRepoCwd(sandbox.hermesHome, mock.url, repo)
-
- 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)
-
- // The coding rail, and thus the ⌘⇧B worktree dialog, mounts only after the
- // session resolves a cwd that holds a repo. This happens on the first turn.
- const composer = page.locator('[contenteditable="true"]').first()
- await composer.click()
- await composer.type('create a repo-backed e2e session', { delay: 2 })
- await page.keyboard.press('Enter')
- await page.waitForFunction(
- prompt => (document.querySelector('[data-slot="aui_thread-viewport"]')?.textContent ?? '').includes(prompt),
- 'create a repo-backed e2e session',
- { timeout: 15_000 },
- )
- await expect(page.locator('.coding-status-bar')).toContainText('main')
-})
-
-test.afterAll(async () => {
- await fixture?.cleanup()
- fixture = null
-})
-
-test('worktree dialog renders the base-branch picker over the dialog, not clipped by it', async () => {
- const page = fixture!.page
-
- await openWorktreeDialog()
-
- // Open the base-branch combobox. With 11 branches, the list is taller than
- // the space below the trigger. A popover that portals into the dialog's
- // `overflow-y-auto` box is therefore cut off. This snapshot catches that bug.
- await page.getByRole('button', { name: /branch off/i }).click()
- await expect(page.getByPlaceholder('Search branches…')).toBeVisible()
- await expect(page.getByRole('option', { name: 'feature/alpha-one' })).toBeVisible()
-
- await expectVisualSnapshot(page, { name: 'worktree-dialog-base-branch-picker', app: fixture!.app })
-
- // This check does not depend on pixels: the dialog's scroll box must not crop
- // the painted box of the popover. Measure the geometry, so a headless run
- // fails on this regression before a person looks at a diff image.
- const clipped = await page.evaluate(() => {
- const popover = document.querySelector('[data-slot="popover-content"]')
- const dialog = document.querySelector('[data-slot="dialog-content"]')
-
- if (!popover || !dialog) {
- return { reason: 'missing', clipped: true }
- }
-
- const p = popover.getBoundingClientRect()
- const d = dialog.getBoundingClientRect()
- const scrolls = window.getComputedStyle(dialog).overflowY
-
- return {
- reason: 'measured',
- // Only a clipping ancestor can crop the popover. The popover is cut when
- // the dialog scrolls its overflow AND the popover goes past the box of
- // the dialog.
- clipped: (scrolls === 'auto' || scrolls === 'scroll' || scrolls === 'hidden') &&
- (p.bottom > d.bottom + 1 || p.top < d.top - 1 || p.right > d.right + 1 || p.left < d.left - 1),
- }
- })
-
- expect(clipped.clipped, `base-branch popover is clipped by the dialog (${clipped.reason})`).toBe(false)
-
- await page.keyboard.press('Escape')
- await closeDialog()
-})
-
-test('worktree dialog convert-an-existing-branch sub-view lists the repo branches', async () => {
- const page = fixture!.page
-
- await openWorktreeDialog()
- await page.getByRole('button', { name: 'Convert an existing branch' }).click()
-
- await expect(page.getByPlaceholder('Search branches…')).toBeVisible()
- await expect(page.getByRole('option', { name: /feature\/alpha-one/ })).toBeVisible()
-
- await expectVisualSnapshot(page, { name: 'worktree-dialog-convert-branch', app: fixture!.app })
-
- await closeDialog()
-})
-
-test('creating a branch with ctrl-shift-b updates the composer git-status branch and leaves no dialog behind', async ({}, testInfo) => {
- const page = fixture!.page
- const codingRow = page.locator('.coding-status-bar')
-
- await openWorktreeDialog()
- // Exactly one dialog instance. A second dialog here, hidden or empty, is the
- // symptom of the double-open bug.
- await expect(page.locator(DIALOG)).toHaveCount(1)
-
- const branchInput = page.locator('input[placeholder="e.g. my-feature"]').first()
- await expect(branchInput).toBeVisible()
- await branchInput.fill(BRANCH_NAME)
- // Select a base branch, so this test uses the same path as the user: open the
- // picker, select a branch, then submit. It does not use the default value.
- // The keyboard drives this step. The dialog still clips the popover, so a
- // mouse click on an option is not reliable until that bug is corrected. The
- // double-open check below is therefore independent of the clipping bug.
- await page.getByRole('button', { name: /branch off/i }).click()
- await page.getByPlaceholder('Search branches…').fill('main')
- await expect(page.getByRole('option', { name: 'main' }).first()).toBeVisible()
- await page.keyboard.press('Enter')
- await expect(page.locator('[data-slot="popover-content"]')).toHaveCount(0)
-
- await page.getByRole('button', { name: 'New worktree' }).click()
-
- await expect(codingRow).toContainText(BRANCH_NAME, { timeout: 15_000 })
-
- // The dialog must close and stay closed. No empty second dialog can remain
- // after the new worktree session starts.
- await expect(page.locator(DIALOG)).toHaveCount(0)
- await page.waitForTimeout(2000)
- await expect(page.locator(DIALOG)).toHaveCount(0)
-
- await page.screenshot({ path: testInfo.outputPath('composer-branch-after-create.png') })
-})
-
-test('ctrl-shift-b opens exactly one worktree dialog when a second composer is on screen', async ({}, testInfo) => {
- const page = fixture!.page
-
- // ⌘T / ctrl+T stacks a second session tile. That gives a second live composer
- // and therefore a second coding rail. Each rail mounted its own
- // WorktreeDialog, and each rail subscribed to the same global token. One
- // keypress therefore opened two stacked dialogs, and the dialog the user
- // dismissed showed an identical empty one behind it. One mount in the sidebar
- // makes that impossible by structure.
- await page.keyboard.press('Control+T')
- await expect(page.locator('.coding-status-bar')).toHaveCount(2, { timeout: 20_000 })
-
- await page.keyboard.press('Control+Shift+B')
- await expect(page.locator(DIALOG).first()).toBeVisible()
- // Wait: let the effect of every subscriber flush before the count.
- await page.waitForTimeout(500)
-
- const count = await page.locator(DIALOG).count()
- await page.screenshot({ path: testInfo.outputPath('worktree-dialog-two-composers.png') })
-
- expect(count, 'one hotkey press must open exactly one worktree dialog').toBe(1)
-
- // A dismissal then leaves nothing behind.
- await closeDialog()
-})
diff --git a/apps/desktop/e2e/zoom-preservation.spec.ts b/apps/desktop/e2e/zoom-preservation.spec.ts
deleted file mode 100644
index 9684bb3bfc8..00000000000
--- a/apps/desktop/e2e/zoom-preservation.spec.ts
+++ /dev/null
@@ -1,87 +0,0 @@
-/**
- * E2E regression: in-page route navigation must preserve the chosen UI scale.
- *
- * Desktop is a HashRouter over one file:// document, so every route is a
- * distinct URL to Chromium's per-URL zoom store, and a route with no record of
- * its own resolves to the host default (100%). In-page navigation fires no load
- * or window event, so nothing re-asserted the persisted level: switching
- * sessions dropped the window to 100% while Appearance kept reading the chosen
- * scale (#48658, #38854, #79863).
- *
- * Prerequisite: `npm run build` must have been run so dist/ exists.
- */
-
-import { type MockBackendFixture, setupMockBackend, waitForAppReady } from './fixtures'
-import { expect, test } from './test'
-
-const SCALE = 110
-
-let fixture: MockBackendFixture | null = null
-
-async function readZoomPercent(): Promise<number> {
- return fixture!.page.evaluate(async () => {
- const desktop = window as unknown as {
- hermesDesktop: { zoom: { get: () => Promise<{ percent: number }> } }
- }
-
- return (await desktop.hermesDesktop.zoom.get()).percent
- })
-}
-
-async function setZoomPercent(percent: number): Promise<void> {
- await fixture!.page.evaluate(target => {
- const desktop = window as unknown as {
- hermesDesktop: { zoom: { setPercent: (percent: number) => void } }
- }
-
- desktop.hermesDesktop.zoom.setPercent(target)
- }, percent)
- await expect.poll(readZoomPercent).toBe(percent)
-}
-
-async function gotoRoute(route: string): Promise<void> {
- const page = fixture!.page
-
- await page.evaluate(target => {
- window.location.hash = target
- }, route)
- await page.waitForFunction(target => window.location.hash === `#${target}`, route)
-}
-
-test.beforeAll(async () => {
- fixture = await setupMockBackend()
- await waitForAppReady(fixture, 120_000)
-})
-
-test.afterAll(async () => {
- await fixture?.cleanup()
- fixture = null
-})
-
-test('a non-default UI scale survives navigation to never-zoomed routes', async () => {
- await setZoomPercent(SCALE)
-
- // Routes Chromium has no zoom record for — what opening a new session looks
- // like to the per-URL store. Pre-fix, the first hop reports 100%.
- const fresh = `/e2e-zoom-${Date.now()}`
-
- for (const route of [`${fresh}-one`, `${fresh}-two`, '/settings?tab=config%3Aappearance']) {
- await gotoRoute(route)
- await expect.poll(readZoomPercent, { message: `UI scale after navigating to ${route}` }).toBe(SCALE)
- }
-})
-
-test('Cmd/Ctrl+N preserves a non-default UI scale', async () => {
- const page = fixture!.page
-
- await gotoRoute('/settings')
- await setZoomPercent(SCALE)
-
- await page.evaluate(() => {
- ;(document.activeElement as HTMLElement | null)?.blur()
- })
- await page.keyboard.press(process.platform === 'darwin' ? 'Meta+N' : 'Control+N')
- await page.waitForFunction(() => window.location.hash === '#/')
-
- await expect.poll(readZoomPercent).toBe(SCALE)
-})
diff --git a/apps/desktop/electron/api-transport.test.ts b/apps/desktop/electron/api-transport.test.ts
index bc7fea0ecf3..d7ab264b7d3 100644
--- a/apps/desktop/electron/api-transport.test.ts
+++ b/apps/desktop/electron/api-transport.test.ts
@@ -18,7 +18,6 @@ import { afterAll, describe, expect, it } from 'vitest'
import {
destroyKeepaliveAgents,
- downloadAgentFor,
htmlResponseError,
httpStatusError,
isIdempotentMethod,
@@ -218,16 +217,6 @@ describe('withRetry', () => {
})
})
-describe('keep-alive agent pools', () => {
- it('separates JSON and download pools per protocol', () => {
- expect(jsonAgentFor('http:')).not.toBe(jsonAgentFor('https:'))
- expect(jsonAgentFor('http:')).not.toBe(downloadAgentFor('http:'))
- expect(jsonAgentFor('https:')).not.toBe(downloadAgentFor('https:'))
- // Stable across calls (a real pool, not a factory).
- expect(jsonAgentFor('http:')).toBe(jsonAgentFor('http:'))
- })
-})
-
// ---------------------------------------------------------------------------
// LIVE transport tests against real misbehaving HTTP servers.
// ---------------------------------------------------------------------------
@@ -362,26 +351,6 @@ describe('live: POST reset after server-side processing', () => {
server.close()
}
}, 20_000)
-
- it('sanity: an identical GET-shaped retry WOULD have re-hit the server', async () => {
- // Companion proof that the verb gate (not luck) is what kept posts === 1:
- // the same reset-after-processing server sees multiple hits under GET.
- let gets = 0
-
- const server = http.createServer(req => {
- gets += 1
- req.socket.resetAndDestroy()
- })
-
- const base = await listen(server)
-
- try {
- await expect(retriedJsonGet(`${base}/api/thing`)).rejects.toThrow()
- expect(gets).toBeGreaterThan(1) // retried — proves the machinery fires
- } finally {
- server.close()
- }
- }, 20_000)
})
describe('httpStatusError', () => {
diff --git a/apps/desktop/electron/app-icon.test.ts b/apps/desktop/electron/app-icon.test.ts
index 1351f324ac2..1be8c572d52 100644
--- a/apps/desktop/electron/app-icon.test.ts
+++ b/apps/desktop/electron/app-icon.test.ts
@@ -17,13 +17,7 @@ import { appIconCandidates, decodingFileProbe, resolveAppIcon } from './app-icon
test('resolveAppIcon skips an existing but undecodable candidate', () => {
// First candidate "exists" (probe says true) but does not decode; second
// decodes. The resolver must return the second, not the first.
- const probeCalls: string[] = []
-
- const probe = (p: string) => {
- probeCalls.push(p)
-
- return p !== '/packaged/app.asar/public/apple-touch-icon.png'
- }
+ const probe = (p: string) => p !== '/packaged/app.asar/public/apple-touch-icon.png'
const picked = resolveAppIcon(
['/packaged/app.asar/public/apple-touch-icon.png', '/packaged/app.asar/dist/apple-touch-icon.png'],
@@ -31,10 +25,6 @@ test('resolveAppIcon skips an existing but undecodable candidate', () => {
)
assert.equal(picked, '/packaged/app.asar/dist/apple-touch-icon.png')
- assert.deepEqual(probeCalls, [
- '/packaged/app.asar/public/apple-touch-icon.png',
- '/packaged/app.asar/dist/apple-touch-icon.png'
- ])
})
test('resolveAppIcon returns undefined when every candidate fails the probe', () => {
@@ -52,20 +42,6 @@ test('decodingFileProbe rejects a missing file', () => {
assert.equal(decodingFileProbe(missing), false)
})
-test('decodingFileProbe rejects an existing but empty (0-byte) file', () => {
- const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'hermes-icon-'))
- const empty = path.join(dir, 'apple-touch-icon.png')
- fs.writeFileSync(empty, Buffer.alloc(0))
-
- try {
- // 0 bytes exist but decode to an empty image — and without electron in
- // the test runtime the require itself fails. Both paths must be false.
- assert.equal(decodingFileProbe(empty), false)
- } finally {
- fs.rmSync(dir, { recursive: true, force: true })
- }
-})
-
test('decodingFileProbe rejects a directory', () => {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'hermes-icon-dir-'))
@@ -97,16 +73,11 @@ test('appIconCandidates keeps the documented precedence ladder', () => {
unpackedPathFor: p => `${p}\\unpacked`
})
- assert.equal(win.length, 5)
- assert.equal(win.filter(c => c.endsWith('.ico')).length, 2)
+ const isIco = win.map(c => c.endsWith('.ico'))
+ assert.ok(isIco.lastIndexOf(true) < isIco.indexOf(false), 'every .ico rung precedes the PNG ladder')
assert.equal(
win[0],
path.join('C:\\resources', 'icon.ico'),
'resources/ icon.ico is the highest-precedence Windows rung'
)
- assert.equal(
- win.filter(c => c.endsWith('apple-touch-icon.png')).length,
- 3,
- 'all three PNG rungs remain after the ico rungs'
- )
})
diff --git a/apps/desktop/electron/backend-claim.test.ts b/apps/desktop/electron/backend-claim.test.ts
index 4a5273ee1f2..0b2555b86a2 100644
--- a/apps/desktop/electron/backend-claim.test.ts
+++ b/apps/desktop/electron/backend-claim.test.ts
@@ -6,7 +6,6 @@ import { test } from 'vitest'
import {
claimDecision,
createBackendOutputTail,
- DEFAULT_OUTPUT_TAIL_LIMIT,
formatBackendExitLine,
isPidOnlyStartMarker,
pidOnlyStartMarker,
@@ -53,12 +52,6 @@ test('probeStartMarker converts a probe throw into { ok: false, reason }', async
assert.deepEqual(probe, { ok: false, reason: 'PowerShell 5.1 cold start exceeded budget' })
})
-test('probeStartMarker passes a successful marker through', async () => {
- const probe = await probeStartMarker(4242, async pid => `linux:${pid}`)
-
- assert.deepEqual(probe, { ok: true, startMarker: 'linux:4242' })
-})
-
// --- real probe: drives the actual OS helper (PowerShell on the Windows lane) ---
test('processStartMarker resolves a real marker for the current process', async () => {
@@ -80,7 +73,6 @@ test('a missing PID is classified as ESRCH so reapOrphans can drop the record',
test('pidOnlyStartMarker round-trips through isPidOnlyStartMarker', () => {
const marker = pidOnlyStartMarker(4242)
- assert.equal(marker, 'pid-only:4242')
assert.equal(isPidOnlyStartMarker(marker), true)
assert.equal(isPidOnlyStartMarker('linux:12345'), false)
assert.equal(isPidOnlyStartMarker(undefined), false)
@@ -98,15 +90,6 @@ test('output tail keeps only the most recent bytes once past the limit', () => {
assert.equal(tail.text().length, 16)
})
-test('output tail default limit is ~8KB', () => {
- const tail = createBackendOutputTail()
-
- tail.append('x'.repeat(DEFAULT_OUTPUT_TAIL_LIMIT + 500))
-
- assert.equal(tail.text().length, DEFAULT_OUTPUT_TAIL_LIMIT)
- assert.equal(DEFAULT_OUTPUT_TAIL_LIMIT, 8192)
-})
-
test('output tail interleaves stdout and stderr attached from spawn time', () => {
const child = { stderr: new EventEmitter(), stdout: new EventEmitter() }
const tail = createBackendOutputTail(64)
@@ -119,15 +102,6 @@ test('output tail interleaves stdout and stderr attached from spawn time', () =>
assert.match(tail.text(), /ModuleNotFoundError/)
})
-test('describe() is empty when nothing was captured, formatted when output exists', () => {
- const tail = createBackendOutputTail(64)
-
- assert.equal(tail.describe(), '')
-
- tail.append('Traceback (most recent call last):\n')
- assert.match(tail.describe(), /^\nRecent backend output:\nTraceback/)
-})
-
test('attach tolerates a child with missing stdio streams', () => {
const tail = createBackendOutputTail(64)
diff --git a/apps/desktop/electron/backend-command.test.ts b/apps/desktop/electron/backend-command.test.ts
index 2746ce78daf..8d38a0ed427 100644
--- a/apps/desktop/electron/backend-command.test.ts
+++ b/apps/desktop/electron/backend-command.test.ts
@@ -4,28 +4,10 @@ import { test } from 'vitest'
import { dashboardFallbackArgs, serveBackendArgs, sourceDeclaresServe } from './backend-command'
-test('serveBackendArgs builds a headless serve invocation', () => {
- assert.deepEqual(serveBackendArgs(), ['serve', '--host', '127.0.0.1', '--port', '0'])
-})
-
test('serveBackendArgs pins a profile when provided', () => {
assert.deepEqual(serveBackendArgs('worker'), ['--profile', 'worker', 'serve', '--host', '127.0.0.1', '--port', '0'])
})
-test('dashboardFallbackArgs rewrites serve -> dashboard --no-open, keeping the -m prefix', () => {
- const serve = ['-m', 'hermes_cli.main', 'serve', '--host', '127.0.0.1', '--port', '0']
- assert.deepEqual(dashboardFallbackArgs(serve), [
- '-m',
- 'hermes_cli.main',
- 'dashboard',
- '--no-open',
- '--host',
- '127.0.0.1',
- '--port',
- '0'
- ])
-})
-
test('dashboardFallbackArgs preserves a --profile flag ahead of serve', () => {
const serve = ['-m', 'hermes_cli.main', '--profile', 'worker', 'serve', '--host', '127.0.0.1', '--port', '0']
assert.deepEqual(dashboardFallbackArgs(serve), [
@@ -46,7 +28,6 @@ test('dashboardFallbackArgs is a no-op (copy) when there is no serve token', ()
const args = ['-m', 'hermes_cli.main', 'dashboard', '--no-open']
const out = dashboardFallbackArgs(args)
assert.deepEqual(out, args)
- assert.notEqual(out, args, 'should return a copy, not the same reference')
})
test('sourceDeclaresServe detects the serve subparser registration', () => {
diff --git a/apps/desktop/electron/backend-dial-claim.test.ts b/apps/desktop/electron/backend-dial-claim.test.ts
index b80de962482..72c6b55cb21 100644
--- a/apps/desktop/electron/backend-dial-claim.test.ts
+++ b/apps/desktop/electron/backend-dial-claim.test.ts
@@ -1,16 +1,9 @@
-import fs from 'node:fs'
-import path from 'node:path'
-import { fileURLToPath } from 'node:url'
-
import { describe, expect, it, vi } from 'vitest'
import { BackendDialClaims } from './backend-dial-claim'
import { backendScopeKey, parseBackendScopeKey } from './connection-registry'
import { resolveDesktopConnectionRequest } from './desktop-profile'
-const here = path.dirname(fileURLToPath(import.meta.url))
-const mainSource = fs.readFileSync(path.join(here, 'main.ts'), 'utf8').replace(/\r\n/g, '\n')
-
describe('BackendDialClaims (#90812)', () => {
it('coalesces two concurrent dials for the same (connectionId, profile) onto ONE backend spawn', async () => {
const claims = new BackendDialClaims()
@@ -123,7 +116,7 @@ describe('parseBackendScopeKey (#90812/#93910)', () => {
})
})
-describe('main.ts wiring for #90812', () => {
+describe('resolved window routes share one dial claim (#90812)', () => {
it.each([null, 'office-ssh'])(
'coalesces resolved window routes without absorbing a same-named source (%s)',
async connectionId => {
@@ -146,65 +139,4 @@ describe('main.ts wiring for #90812', () => {
expect(other).toHaveBeenCalledTimes(1)
}
)
-
- // The four IPC/probe surfaces below call ensureRegistryBackend()/ensureBackend()
- // directly, bypassing backendDialClaims entirely — so a renderer's guarded
- // reconnect dial and one of these can independently race the SAME
- // ensureRegistryBackend() await-before-pool-check window (main.ts) and each
- // bootstrap its own SSH tunnel / remote dashboard for the same
- // (connectionId, profile) scope.
-
- it('routes a media-stream connection resolve through the single-owner claim', () => {
- const handlerStart = mainSource.indexOf('resolveRemoteConnection: ({ connectionId, profile }) =>')
- expect(handlerStart).toBeGreaterThan(-1)
- const body = mainSource.slice(handlerStart, handlerStart + 300)
-
- expect(body).toContain('backendDialClaims.run(backendScopeKey(connectionId, profile)')
- expect(body).toContain('ensureRegistryBackend(connectionId, profile)')
- expect(body).toContain('ensureBackend(profile)')
- })
-
- it('routes a terminal-pane backend resolve through the single-owner claim on both the registry and local branches', () => {
- const handlerStart = mainSource.indexOf('async function ensureTerminalBackend(webContentsId: number) {')
- expect(handlerStart).toBeGreaterThan(-1)
- const body = mainSource.slice(handlerStart, handlerStart + 900)
-
- expect(body).toContain('backendDialClaims.run(backendScopeKey(windowRoute.connectionId, windowRoute.profile)')
- expect(body).toContain('ensureRegistryBackend(windowRoute.connectionId, windowRoute.profile)')
- expect(body).toContain('backendDialClaims.run(backendScopeKey(null, profile)')
- expect(body).toContain('ensureBackend(profile)')
- })
-
- it('routes the roster-enumeration probe through the single-owner claim', () => {
- const handlerStart = mainSource.indexOf('async function enumerateRegistryAgentSources')
- expect(handlerStart).toBeGreaterThan(-1)
- // The ssh branch grew (it now carries the install id learned by the
- // inventory probe) — keep the scan window comfortably past the dial.
- const body = mainSource.slice(handlerStart, handlerStart + 4_500)
-
- expect(body).toContain('backendDialClaims.run(backendScopeKey(connection.id, null)')
- expect(body).toContain('ensureRegistryBackend(connection.id, null)')
- expect(body).toContain("getJsonForBackend(descriptor, '/api/profiles'")
- })
-
- it('routes the connections update-all dispatch through the single-owner claim', () => {
- const handlerStart = mainSource.indexOf("ipcMain.handle('hermes:connections:update-all',")
- expect(handlerStart).toBeGreaterThan(-1)
- // The handler grew on main (renderer-side exclusions + the managed-SSH
- // dispatch branch) — keep the scan window comfortably past the dial.
- const body = mainSource.slice(handlerStart, handlerStart + 3_000)
-
- expect(body).toContain('backendDialClaims.run(backendScopeKey(connection.id, null)')
- expect(body).toContain('ensureRegistryBackend(connection.id, null)')
- expect(body).toContain("postJsonForBackend(descriptor, '/api/hermes/update'")
- })
-
- it('routes every registry-scoped REST dispatch (hermes:api) through the single-owner claim', () => {
- const handlerStart = mainSource.indexOf('async function dispatchRegistryApiRequest(')
- expect(handlerStart).toBeGreaterThan(-1)
- const body = mainSource.slice(handlerStart, handlerStart + 1_000)
-
- expect(body).toContain('backendDialClaims.run(backendScopeKey(registryConnectionId, routeProfile)')
- expect(body).toContain("ensureRegistryBackend(registryConnectionId, routeProfile, '', { spawnPriority })")
- })
})
diff --git a/apps/desktop/electron/backend-health.test.ts b/apps/desktop/electron/backend-health.test.ts
index 144cdd9b61c..9ebff185a1f 100644
--- a/apps/desktop/electron/backend-health.test.ts
+++ b/apps/desktop/electron/backend-health.test.ts
@@ -406,7 +406,7 @@ test('isNousCloudAgentUrl detects cloud agent hosts', () => {
assert.equal(isNousCloudAgentUrl('not-a-url'), false)
})
-test('waitForHermesReady surfaces actionable error for cloud agent 503', async () => {
+test('waitForHermesReady classifies a persistent cloud agent 503 as cloud-backend-down', async () => {
let attempts = 0
const currentTime = { value: 0 }
@@ -434,10 +434,6 @@ test('waitForHermesReady surfaces actionable error for cloud agent 503', async (
})
assert.fail('should have thrown')
} catch (error: any) {
- assert.ok(error.message.includes('Nous Cloud agent'), `unexpected message: ${error.message}`)
- assert.ok(error.message.includes('503'), `should mention status code: ${error.message}`)
- assert.ok(error.message.includes('portal.nousresearch.com'), `should mention portal: ${error.message}`)
- assert.ok(error.message.includes('discord.gg/NousResearch'), `should mention Discord: ${error.message}`)
assert.equal(error.isCloudBackendDown, true)
assert.equal(error.statusCode, 503)
assert.ok(attempts > 1, 'should have retried before failing')
@@ -467,8 +463,6 @@ test('waitForHermesReady does not cloud-wrap non-cloud 503 errors', async () =>
})
assert.fail('should have thrown')
} catch (error: any) {
- // Non-cloud URLs get the generic message
- assert.ok(error.message.includes('did not become ready'), `unexpected message: ${error.message}`)
assert.equal(error.isCloudBackendDown, undefined)
}
})
@@ -516,7 +510,6 @@ test('makeNousCloudBackendDownError produces the Cloud shape and preserves cause
assert.equal((result as any).isCloudBackendDown, true)
assert.equal((result as any).statusCode, 503)
assert.equal((result as any).cause, err)
- assert.ok(result?.message.includes('Nous Cloud agent ares-3009.agents.nousresearch.com is down'))
})
test('makeNousCloudBackendDownError returns null for a Cloud 401 (routes to reauth)', () => {
diff --git a/apps/desktop/electron/backend-probes.test.ts b/apps/desktop/electron/backend-probes.test.ts
index fae2cddf3f2..cda96bd41f9 100644
--- a/apps/desktop/electron/backend-probes.test.ts
+++ b/apps/desktop/electron/backend-probes.test.ts
@@ -17,8 +17,6 @@ import {
canImportHermesCli,
DEFAULT_PROBE_TIMEOUT_MS,
execProbe,
- hermesRuntimeImportProbe,
- PROBE_TIMEOUT_MS,
resolveProbeTimeoutMs,
shouldTrustHermesOverride,
verifyHermesCli
@@ -98,16 +96,6 @@ test('canImportHermesCli returns false when binary does not exist', async () =>
assert.equal(await canImportHermesCli(ghost), false)
})
-test('hermes runtime import probe checks config dependencies', () => {
- const probe = hermesRuntimeImportProbe()
- assert.match(probe, /\bimport yaml\b/)
- // dotenv is the first third-party import on the CLI boot path
- // (hermes_cli/env_loader.py); a mid-update venv missing python-dotenv
- // passed the old probe and produced an unrecoverable boot loop.
- assert.match(probe, /\bimport dotenv\b/)
- assert.match(probe, /\bimport hermes_cli\.config\b/)
-})
-
test('explicit Hermes override is authoritative', () => {
assert.equal(shouldTrustHermesOverride('/nix/store/abc/bin/hermes'), true)
})
@@ -151,21 +139,6 @@ test('verifyHermesCli returns true when --version exits 0', async () => {
}
})
-test('verifyHermesCli swallows timeouts (does not throw)', async () => {
- // We can't easily provoke a real hang in CI without slowing the
- // suite, but we CAN confirm that an invocation that DOES throw
- // (because the binary is missing) returns false rather than
- // propagating. Same code path the timeout case takes.
- assert.equal(await verifyHermesCli('/definitely/not/a/real/binary/anywhere'), false)
-})
-
-test('default probe timeout is 15s (not the old 5s death-loop value)', () => {
- assert.equal(DEFAULT_PROBE_TIMEOUT_MS, 15_000)
- // Module constant uses process.env at load time; with no override it
- // matches the default (tests run without HERMES_PROBE_TIMEOUT_MS).
- assert.equal(PROBE_TIMEOUT_MS, DEFAULT_PROBE_TIMEOUT_MS)
-})
-
test('resolveProbeTimeoutMs honours HERMES_PROBE_TIMEOUT_MS', () => {
assert.equal(resolveProbeTimeoutMs({}), DEFAULT_PROBE_TIMEOUT_MS)
assert.equal(resolveProbeTimeoutMs({ HERMES_PROBE_TIMEOUT_MS: '30000' }), 30_000)
diff --git a/apps/desktop/electron/backend-python-coherence.test.ts b/apps/desktop/electron/backend-python-coherence.test.ts
deleted file mode 100644
index a40734ee2aa..00000000000
--- a/apps/desktop/electron/backend-python-coherence.test.ts
+++ /dev/null
@@ -1,114 +0,0 @@
-import assert from 'node:assert/strict'
-import fs from 'node:fs'
-import path from 'node:path'
-import { fileURLToPath } from 'node:url'
-
-import { test } from 'vitest'
-
-// ── Regression guard: backend interpreter / site-packages coherence ─────────
-//
-// Live repro (2026-08-23, macOS dev run): the checkout had BOTH venvs —
-// .venv/ → Python 3.12 (dev tooling)
-// venv/ → Python 3.11 (the CLI install venv, owns the real deps)
-//
-// findPythonForRoot() prefers `.venv/bin/python` (3.12), but
-// createPythonBackend() hardcodes `venvRoot = path.join(root, 'venv')` and
-// puts venv/lib/python3.11/site-packages on PYTHONPATH. The 3.12 interpreter
-// then imports 3.11-compiled native wheels and dies on the FIRST import:
-// ImportError: No module named 'pydantic_core._pydantic_core'
-// → backend exits(1) before ready → "Gateway offline" → renderer falls back
-// to a dead 127.0.0.1:9119 and every profile fails to activate.
-//
-// The invariant these tests pin down: the venv whose interpreter is selected
-// and the venv whose site-packages go on PYTHONPATH must be THE SAME venv.
-// One resolver must own that decision (AGENTS.md "observable ladder" rule 6).
-
-const here = path.dirname(fileURLToPath(import.meta.url))
-const mainTsSource = fs.readFileSync(path.join(here, 'main.ts'), 'utf8')
-
-function extractFunction(source: string, name: string): string {
- const start = source.indexOf(`function ${name}(`)
- assert.notEqual(start, -1, `function ${name} not found in main.ts`)
-
- // Slice to the next top-level `function ` declaration — crude but stable
- // for the flat function layout main.ts uses.
- const rest = source.slice(start)
- const next = rest.slice(1).search(/\nfunction /)
-
- return next === -1 ? rest : rest.slice(0, next + 1)
-}
-
-test('findPythonForRoot preference order includes .venv before venv (context for the coherence tests)', () => {
- const fn = extractFunction(mainTsSource, 'findPythonForRoot')
- const venvIdx = fn.indexOf("'.venv'")
- const plainIdx = fn.indexOf("'venv'")
-
- assert.notEqual(venvIdx, -1, 'expected findPythonForRoot to probe .venv')
- assert.notEqual(plainIdx, -1, 'expected findPythonForRoot to probe venv')
- assert.ok(
- venvIdx < plainIdx,
- '.venv is probed before venv — this ordering is what the hardcoded venvRoot below disagrees with'
- )
-})
-
-// Fixed: createPythonBackend derives venvRoot from the selected interpreter
-// via venvRootForPython(python, root), falling back to root/venv only for a
-// system python. This test guards against re-hardcoding the venv path.
-test('createPythonBackend derives venvRoot from the selected interpreter, not a hardcoded venv path', () => {
- const fn = extractFunction(mainTsSource, 'createPythonBackend')
-
- // The buggy shape: interpreter picked by findPythonForRoot (may be .venv),
- // while venvRoot/PYTHONPATH is unconditionally root/venv.
- const hardcodesVenv = /venvRoot\s*=\s*path\.join\(root,\s*'venv'\)/.test(fn)
- const derivesFromPython = /findPythonForRoot|python/.test(fn) && !hardcodesVenv
-
- assert.ok(
- derivesFromPython,
- 'createPythonBackend hardcodes venvRoot=path.join(root, "venv") while findPythonForRoot may select .venv/bin/python — ' +
- 'a root with both venvs gets a 3.12 interpreter with 3.11 site-packages on PYTHONPATH and crashes on the first native import'
- )
-})
-
-// Pure-logic mirror of the same invariant, testable without main.ts exports:
-// given a root where BOTH .venv and venv exist, whatever venv the interpreter
-// came from must be the venv used for site-packages. This encodes the fix's
-// contract so the implementation can be extracted against it later.
-export function coherentVenvRootForPython(pythonPath: string, root: string): string | null {
- // The venv root is the directory two levels up from <venv>/bin/python
- // (Scripts/python.exe on Windows). A system interpreter (outside `root`)
- // is NOT a venv — pairing it with any venv's site-packages needs the same
- // version check, so it returns null here.
- const posix = pythonPath.match(/^(.*)\/bin\/python[0-9.]*$/)
- const win = pythonPath.match(/^(.*)[\\/]Scripts[\\/]python\.exe$/i)
- const candidate = posix?.[1] ?? win?.[1] ?? null
-
- if (!candidate) {
- return null
- }
-
- const normalizedRoot = root.replace(/\\/g, '/').replace(/\/+$/, '')
- const normalizedCandidate = candidate.replace(/\\/g, '/')
-
- return normalizedCandidate.startsWith(`${normalizedRoot}/`) ? candidate : null
-}
-
-test('coherentVenvRootForPython maps a selected interpreter back to ITS venv root', () => {
- assert.equal(coherentVenvRootForPython('/repo/.venv/bin/python', '/repo'), '/repo/.venv')
- assert.equal(coherentVenvRootForPython('/repo/venv/bin/python', '/repo'), '/repo/venv')
- assert.equal(coherentVenvRootForPython('C:\\repo\\venv\\Scripts\\python.exe', 'C:\\repo'), 'C:\\repo\\venv')
- assert.equal(coherentVenvRootForPython('/usr/bin/python3', '/repo'), null)
-})
-
-test('dual-venv root: site-packages must come from the venv that owns the selected interpreter', () => {
- // Simulates the live repro: interpreter resolved to .venv (3.12), so the
- // ONLY coherent venvRoot for PYTHONPATH is .venv — never the sibling venv.
- const selected = '/repo/.venv/bin/python'
- const venvRoot = coherentVenvRootForPython(selected, '/repo')
-
- assert.equal(venvRoot, '/repo/.venv')
- assert.notEqual(
- venvRoot,
- '/repo/venv',
- 'pairing a .venv interpreter with venv/ site-packages is the crash from the live repro'
- )
-})
diff --git a/apps/desktop/electron/backend-ready.test.ts b/apps/desktop/electron/backend-ready.test.ts
index 8a1079b00af..9a412c6ad19 100644
--- a/apps/desktop/electron/backend-ready.test.ts
+++ b/apps/desktop/electron/backend-ready.test.ts
@@ -121,14 +121,6 @@ test('rejects on a child error event', async () => {
await assert.rejects(p, /spawn ENOENT/)
})
-test('rejects with the timeout message after the deadline', async () => {
- const child = makeFakeChild()
- await assert.rejects(
- waitForDashboardPort(child, 20),
- /Timed out waiting for Hermes backend port announcement \(20ms\)/
- )
-})
-
test('a late announcement after timeout does not throw (listeners torn down)', async () => {
const child = makeFakeChild()
await assert.rejects(waitForDashboardPort(child, 20), /Timed out/)
@@ -247,20 +239,6 @@ test('exit-before-announcement error carries the buffered output tail (ready-fil
await assert.rejects(wait, /exited before port announcement \(SIGSEGV\)[\s\S]*Traceback/)
})
-test('exit-before-announcement error stays clean when no output was buffered', async () => {
- const child = makeFakeChild()
-
- const wait = waitForDashboardPortAnnouncement(child, {})
-
- child.emit('exit', 137, null)
-
- await assert.rejects(wait, error => {
- assert.match((error as Error).message, /exited before port announcement \(137\)$/)
-
- return true
- })
-})
-
// ---------------------------------------------------------------------------
// bufferedOutput (#60323): a sentinel consumed BEFORE the wait attaches must
// still resolve. main.ts attaches an output tail at spawn, then awaits
diff --git a/apps/desktop/electron/backend-release-gate.windows-live.test.ts b/apps/desktop/electron/backend-release-gate.windows-live.test.ts
deleted file mode 100644
index 3c188258507..00000000000
--- a/apps/desktop/electron/backend-release-gate.windows-live.test.ts
+++ /dev/null
@@ -1,146 +0,0 @@
-/**
- * backend-release-gate.windows-live.test.ts
- *
- * LIVE Windows E2E for the #74805 unlock gate: real spawned processes, the
- * REAL isPidAliveWindows probe against the live process table, real
- * taskkill — no fake clocks, no fake tables. Runs only on win32 (the
- * ephemeral wine2e lane); skipped everywhere else.
- *
- * This is the platform half of the proof: the unit suite pins the gate's
- * decision logic on a fake table; this file proves the two real-world
- * premises the fix rests on:
- * 1. taskkill /T /F returns while the killed process is still enumerable
- * (the race window exists), and
- * 2. the gate, wired to the real probes, dwells through that window and
- * only passes once the PID has genuinely left the table.
- */
-
-import { execFileSync, spawn } from 'node:child_process'
-
-import { describe, expect, it } from 'vitest'
-
-import { isPidAliveWindows, waitForBackendRelease } from './backend-release-gate'
-
-const isWindows = process.platform === 'win32'
-
-function spawnSleeper(): { pid: number; kill: () => void } {
- // A real python if available (mirrors the backend shape), else powershell.
- const child = spawn('powershell', ['-NoProfile', '-Command', 'Start-Sleep -Seconds 300'], { stdio: 'ignore' })
-
- if (!child.pid) {
- throw new Error('sleeper failed to spawn')
- }
-
- return {
- pid: child.pid,
- kill: () => {
- try {
- child.kill()
- } catch {
- /* already gone */
- }
- }
- }
-}
-
-function taskkillTree(pid: number): void {
- try {
- execFileSync('taskkill', ['/PID', String(pid), '/T', '/F'], { stdio: 'ignore' })
- } catch {
- /* already gone */
- }
-}
-
-describe.skipIf(!isWindows)('waitForBackendRelease — live Windows (#74805)', () => {
- it('isPidAliveWindows tracks a real process through spawn and exit', async () => {
- const sleeper = spawnSleeper()
-
- expect(isPidAliveWindows(sleeper.pid)).toBe(true)
-
- taskkillTree(sleeper.pid)
-
- // Poll until the table retires the PID (bounded).
- const deadline = Date.now() + 10000
-
- while (isPidAliveWindows(sleeper.pid) && Date.now() < deadline) {
- await new Promise(r => setTimeout(r, 100))
- }
-
- expect(isPidAliveWindows(sleeper.pid)).toBe(false)
- })
-
- it('the gate dwells until a real killed PID leaves the live process table', async () => {
- const sleeper = spawnSleeper()
- const logs: string[] = []
- let firstAliveCheck: boolean | null = null
-
- // Fire the real taskkill and IMMEDIATELY enter the gate — the #74805
- // shape. The shim probe reads unlocked throughout (the serve backend
- // never held it); only the PID exit-wait can hold the gate closed.
- taskkillTree(sleeper.pid)
-
- const result = await waitForBackendRelease(
- [sleeper.pid],
- {
- isShimLocked: () => false,
- isPidAlive: pid => {
- const alive = isPidAliveWindows(pid)
-
- if (firstAliveCheck === null) {
- firstAliveCheck = alive
- }
-
- return alive
- },
- collectStragglerPids: () => [],
- killProcessTree: taskkillTree,
- sleep: ms => new Promise(r => setTimeout(r, ms)),
- now: () => Date.now(),
- log: line => logs.push(line)
- },
- 'live-e2e'
- )
-
- expect(result.unlocked).toBe(true)
- // The gate resolved only after the real PID left the real table:
- expect(isPidAliveWindows(sleeper.pid)).toBe(false)
- expect(result.lingeringPids).toEqual([])
- // Record whether the race window was observable on this runner (taskkill
- // returned while the PID was still enumerable). Informational: fast
- // runners can retire tiny process trees before our first check, but the
- // gate's correctness (above) does not depend on winning that race.
- logs.push(`race-window-observed=${firstAliveCheck}`)
-
- expect(logs.some(l => l.includes('safe to proceed'))).toBe(true)
- })
-
- it('a live foreign holder keeps the gate closed until the deadline', async () => {
- const holder = spawnSleeper()
-
- try {
- const result = await waitForBackendRelease(
- [holder.pid],
- {
- // Simulates the shim held by a process we did NOT kill — the gate
- // must fail closed rather than hand off over a live holder.
- isShimLocked: () => true,
- isPidAlive: isPidAliveWindows,
- collectStragglerPids: () => [],
- killProcessTree: () => {
- /* nothing else to kill */
- },
- sleep: ms => new Promise(r => setTimeout(r, ms)),
- now: () => Date.now(),
- log: () => {}
- },
- 'live-e2e',
- 2000
- )
-
- expect(result.unlocked).toBe(false)
- expect(result.lingeringPids).toEqual([holder.pid])
- } finally {
- taskkillTree(holder.pid)
- }
- })
-})
diff --git a/apps/desktop/electron/backend-start-failure.test.ts b/apps/desktop/electron/backend-start-failure.test.ts
index b3c12477874..ea2261db16f 100644
--- a/apps/desktop/electron/backend-start-failure.test.ts
+++ b/apps/desktop/electron/backend-start-failure.test.ts
@@ -30,13 +30,6 @@ test('never latches a supervisor-owned respawn failure (it has its own bounded c
assert.equal(shouldLatchBackendStartFailure({ attemptedRemote: false, supervisorRecovery: false }), true)
})
-test('the two branches are mutually exclusive (a failure either latches or stays retryable)', () => {
- for (const attemptedRemote of [true, false]) {
- const latched = shouldLatchBackendStartFailure({ attemptedRemote })
- assert.equal(latched, !attemptedRemote)
- }
-})
-
test('latches a CONFIRMED remote reauth failure so the overlay stays clickable', () => {
// Without this the non-latching remote path re-runs startHermes on every
// getConnection/api call, re-emits running:true, and the overlay hides
diff --git a/apps/desktop/electron/bootstrap-failure-copy.test.ts b/apps/desktop/electron/bootstrap-failure-copy.test.ts
deleted file mode 100644
index 64dc037a130..00000000000
--- a/apps/desktop/electron/bootstrap-failure-copy.test.ts
+++ /dev/null
@@ -1,40 +0,0 @@
-import assert from 'node:assert/strict'
-
-import { test } from 'vitest'
-
-import { bootstrapStageLabel, describeBootstrapFailure, missingInstallPartMessage } from './bootstrap-failure-copy'
-
-test('known stage names get everyday labels; unknown ones are humanized', () => {
- assert.equal(bootstrapStageLabel('venv'), 'Python environment')
- assert.equal(bootstrapStageLabel('system-packages'), 'System packages')
- assert.equal(bootstrapStageLabel('some-new_stage'), 'Some new stage')
- assert.equal(bootstrapStageLabel(null), null)
-})
-
-test('lead sentence is plain and actionable; raw error is confined to the Details line', () => {
- const raw = "install.ps1 exited 1: spawn ENOENT (stage 'venv')"
- const message = describeBootstrapFailure('venv', raw)
- const [lead, ...rest] = message.split('\n')
-
- assert.match(lead, /'Python environment' step/)
- assert.match(lead, /Reload and retry/)
- assert.match(lead, /open the logs/)
- assert.doesNotMatch(lead, /bootstrap|stage|venv|ENOENT|exited|desktop\.log/)
- assert.equal(rest.join('\n'), `Details: ${raw}`)
-})
-
-test('missing stage and missing error still produce a complete message', () => {
- const message = describeBootstrapFailure(null, undefined)
-
- assert.match(message, /^Setting up Hermes stopped before it could finish\./)
- assert.match(message, /\nDetails: unknown error$/)
-})
-
-test('missing-install-part copy names Repair install and keeps the path in Details', () => {
- const message = missingInstallPartMessage('Python environment missing at /home/me/.hermes/venv')
- const [lead, details] = message.split('Details: ')
-
- assert.match(lead, /Repair install/)
- assert.doesNotMatch(lead, /venv|install\.ps1|\//)
- assert.equal(details, 'Python environment missing at /home/me/.hermes/venv')
-})
diff --git a/apps/desktop/electron/bootstrap-platform.test.ts b/apps/desktop/electron/bootstrap-platform.test.ts
index 3c736e70173..2ca517fb51b 100644
--- a/apps/desktop/electron/bootstrap-platform.test.ts
+++ b/apps/desktop/electron/bootstrap-platform.test.ts
@@ -3,7 +3,6 @@ import assert from 'node:assert/strict'
import { test } from 'vitest'
import {
- bundledRuntimeImportCheck,
detectRemoteDisplay,
isWindowsBinaryPathInWsl,
isWslEnvironment,
@@ -27,12 +26,6 @@ test('isWindowsBinaryPathInWsl blocks Windows binary types on WSL', () => {
assert.equal(isWindowsBinaryPathInWsl('/mnt/c/Tools/hermes.exe', { isWsl: false }), false)
})
-test('bundledRuntimeImportCheck selects platform-specific import checks', () => {
- assert.equal(bundledRuntimeImportCheck('win32'), 'import fastapi, uvicorn, winpty')
- assert.equal(bundledRuntimeImportCheck('darwin'), 'import fastapi, uvicorn, ptyprocess')
- assert.equal(bundledRuntimeImportCheck('linux'), 'import fastapi, uvicorn, ptyprocess')
-})
-
test('detectRemoteDisplay keeps GPU on for local sessions', () => {
// Plain local X11, Wayland, native Windows, native macOS — no remote signal.
assert.equal(detectRemoteDisplay({ env: { DISPLAY: ':0' }, platform: 'linux' }), null)
diff --git a/apps/desktop/electron/bootstrap-repair-guard.test.ts b/apps/desktop/electron/bootstrap-repair-guard.test.ts
index e1a7a1ecf3d..90db9518b51 100644
--- a/apps/desktop/electron/bootstrap-repair-guard.test.ts
+++ b/apps/desktop/electron/bootstrap-repair-guard.test.ts
@@ -12,18 +12,6 @@ test('first soft attempt with alive backend returns soft restart', () => {
assert.equal(decision.hardReinstall, false)
assert.equal(decision.attempt, 1)
- assert.match(decision.reason, /still alive/)
- assert.match(decision.reason, /1\/3/)
-})
-
-test('first attempt with dead backend still returns soft restart', () => {
- const decision = decideBootstrapRepair({
- attempt: 1,
- primaryBackendAlive: false
- })
-
- assert.equal(decision.hardReinstall, false)
- assert.match(decision.reason, /has exited/)
})
test('soft restart budget exhausts at maxSoftAttempts+1 and escalates', () => {
@@ -35,7 +23,6 @@ test('soft restart budget exhausts at maxSoftAttempts+1 and escalates', () => {
assert.equal(decision.hardReinstall, true)
assert.equal(decision.attempt, 4)
- assert.match(decision.reason, /exceeds soft-restart budget/)
})
test('attempt exactly at maxSoftAttempts is still soft', () => {
@@ -67,16 +54,6 @@ test('custom maxSoftAttempts is honored', () => {
assert.equal(hard.hardReinstall, true)
})
-test('default maxSoftAttempts is 3', () => {
- // Probe the default indirectly: attempt 4 with no override must escalate.
- const decision = decideBootstrapRepair({
- attempt: 4,
- primaryBackendAlive: true
- })
-
- assert.equal(decision.hardReinstall, true)
-})
-
test('fractional or zero attempts are clamped to 1', () => {
const zeroDecision = decideBootstrapRepair({
attempt: 0,
@@ -94,16 +71,3 @@ test('fractional or zero attempts are clamped to 1', () => {
assert.equal(fractionalDecision.attempt, 2)
assert.equal(fractionalDecision.hardReinstall, false)
})
-
-test('alive=false on a high attempt number still escalates (defense in depth)', () => {
- // A dead backend should normally be handled by the renderer before it
- // reaches the repair path, but if it does reach us with a high attempt
- // count we still escalate — never silently keep soft-restarting.
- const decision = decideBootstrapRepair({
- attempt: 5,
- maxSoftAttempts: 3,
- primaryBackendAlive: false
- })
-
- assert.equal(decision.hardReinstall, true)
-})
diff --git a/apps/desktop/electron/bootstrap-runner-git-binary.test.ts b/apps/desktop/electron/bootstrap-runner-git-binary.test.ts
deleted file mode 100644
index fa73a97c1ee..00000000000
--- a/apps/desktop/electron/bootstrap-runner-git-binary.test.ts
+++ /dev/null
@@ -1,21 +0,0 @@
-import assert from 'node:assert/strict'
-import type * as ChildProcess from 'node:child_process'
-
-import { test, vi } from 'vitest'
-
-const execFileSyncMock = vi.fn((..._args: unknown[]) => 'abcdef1234567890\n')
-
-vi.mock('node:child_process', async importOriginal => ({
- ...(await importOriginal<typeof ChildProcess>()),
- execFileSync: execFileSyncMock
-}))
-
-test('resolveCheckoutHead runs the probed git binary, not the first PATH hit (#114718)', async () => {
- // The bootstrap marker pin used a bare `git`, which on the reported Mac is
- // an Intel-only /usr/local/bin/git that fails at spawn, silently dropping
- // the real pin. main.ts now passes the binary it already probed.
- const { resolveCheckoutHead } = await import('./bootstrap-runner')
-
- assert.equal(resolveCheckoutHead('/repo', { gitBinary: '/usr/bin/git' }), 'abcdef1234567890')
- assert.equal(execFileSyncMock.mock.calls[0]?.[0], '/usr/bin/git')
-})
diff --git a/apps/desktop/electron/bootstrap-runner.test.ts b/apps/desktop/electron/bootstrap-runner.test.ts
index 5cc6f92f231..cc5eb5e99df 100644
--- a/apps/desktop/electron/bootstrap-runner.test.ts
+++ b/apps/desktop/electron/bootstrap-runner.test.ts
@@ -180,10 +180,6 @@ test('resolveInstallScript downloads fallback stamps by branch instead of zero c
assert.equal(result.source, 'download')
assert.equal(result.commit, null)
assert.equal(result.path, cachedScriptPath(home, 'fallback-main'))
- assert.ok(
- logs.some(ev => /fallback, unpinned/.test(ev.line || '')),
- 'emits an unpinned fallback log line'
- )
} finally {
fs.rmSync(home, { recursive: true, force: true })
}
@@ -242,10 +238,6 @@ test('resolveInstallScript falls back to the installed agent checkout on a 404',
// It should have copied the installer into the bootstrap cache.
assert.equal(result.path, cachedScriptPath(home, commit))
assert.ok(fs.existsSync(result.path), 'fallback script copied into cache')
- assert.ok(
- logs.some(ev => /falling back to installed agent/.test(ev.line || '')),
- 'emits a fallback log line'
- )
} finally {
fs.rmSync(home, { recursive: true, force: true })
}
diff --git a/apps/desktop/electron/bundle-skew.test.ts b/apps/desktop/electron/bundle-skew.test.ts
index cbf3453f5a2..46a421d4a80 100644
--- a/apps/desktop/electron/bundle-skew.test.ts
+++ b/apps/desktop/electron/bundle-skew.test.ts
@@ -59,14 +59,6 @@ describe('detectBundleSkew', () => {
expect(result).toEqual({ desktopCommitsBehind: 3, outOfSync: true })
})
- it('counts only commits that touch runtime desktop paths', async () => {
- const { calls, git } = gitAnswering({ 'merge-base': { code: 0 }, 'rev-list': { stdout: '0' } })
-
- await detectBundleSkew(STAMP, git, REPO)
-
- expect(calls[1]).toEqual(['rev-list', '--count', `${STAMP.commit}..HEAD`, '--', ...RUNTIME_PATHS])
- })
-
it('is quiet when no desktop commits follow the stamp', async () => {
const result = await detectBundleSkew(STAMP, gitCounting('0\n'), REPO)
@@ -131,30 +123,6 @@ describe('detectBundleSkew', () => {
})
})
- it('does not consult the commit count once ancestry is refused', async () => {
- const { calls, git } = gitAnswering({
- 'merge-base': { code: 1 },
- 'rev-list': { stdout: '9999\n' }
- })
-
- await detectBundleSkew(STAMP, git, REPO)
-
- expect(calls.map(args => args[0])).toEqual(['merge-base'])
- })
-
- it('asks about ancestry before counting, against the same stamp', async () => {
- const { calls, git } = gitAnswering({
- 'merge-base': { code: 0 },
- 'rev-list': { stdout: '2\n' }
- })
-
- const result = await detectBundleSkew(STAMP, git, REPO)
-
- expect(calls[0]).toEqual(['merge-base', '--is-ancestor', STAMP.commit, 'HEAD'])
- expect(calls[1]?.[0]).toBe('rev-list')
- expect(result).toEqual({ desktopCommitsBehind: 2, outOfSync: true })
- })
-
it('is quiet when git cannot answer the ancestry question at all', async () => {
const { git } = gitAnswering({
'merge-base': { code: 128 },
diff --git a/apps/desktop/electron/command-screenshot-monitor.test.ts b/apps/desktop/electron/command-screenshot-monitor.test.ts
index 2442eeae212..f624b406882 100644
--- a/apps/desktop/electron/command-screenshot-monitor.test.ts
+++ b/apps/desktop/electron/command-screenshot-monitor.test.ts
@@ -1,9 +1,6 @@
import assert from 'node:assert/strict'
-import { execFileSync, spawn as nodeSpawn, type SpawnOptions, spawnSync } from 'node:child_process'
+import { type SpawnOptions } from 'node:child_process'
import { EventEmitter } from 'node:events'
-import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'
-import { tmpdir } from 'node:os'
-import { resolve } from 'node:path'
import { PassThrough } from 'node:stream'
import { test, vi } from 'vitest'
@@ -127,188 +124,3 @@ test('stopping from the starting callback cancels the child before it can become
child.emit('close', 0, null)
assert.deepEqual(statuses, [{ type: 'starting' }, { type: 'stopped' }])
})
-
-test.skipIf(process.platform !== 'darwin')(
- 'native state machine requires distinct keys, a clean chord and full release',
- () => {
- const dir = mkdtempSync(resolve(tmpdir(), 'hermes-command-monitor-test-'))
-
- try {
- const fixture = resolve(dir, 'gesture.m')
- const binary = resolve(dir, 'gesture')
- // Compile the real state machine; no posted input events, screen pixels or TCC prompts.
- writeFileSync(
- fixture,
- `
-#define COMMAND_SCREENSHOT_MONITOR_TEST 1
-#include "${resolve(import.meta.dirname, 'native/command-screenshot-monitor.m')}"
-#include <assert.h>
-static const CGEventFlags L = kCGEventFlagMaskCommand | NX_DEVICELCMDKEYMASK;
-static const CGEventFlags R = kCGEventFlagMaskCommand | NX_DEVICERCMDKEYMASK;
-static const CGEventFlags B = kCGEventFlagMaskCommand | NX_DEVICELCMDKEYMASK | NX_DEVICERCMDKEYMASK;
-static bool flags(CommandGesture *s, CGKeyCode key, CGEventFlags f) {
- return CommandGestureUpdate(s, kCGEventFlagsChanged, key, f, false);
-}
-int main(void) { @autoreleasepool {
- CommandGesture s = {0};
- assert(!flags(&s, 55, L));
- assert(!flags(&s, 55, L)); // duplicate left Command is not the right Command
- assert(flags(&s, 54, B)); // capture immediately on the second physical press
- assert(!flags(&s, 54, L));
- assert(!flags(&s, 54, B));
- assert(!flags(&s, 54, L)); // one release does not re-arm
- assert(!flags(&s, 55, 0));
- assert(!flags(&s, 54, R));
- assert(flags(&s, 55, B));
- assert(!flags(&s, 55, R));
- assert(!flags(&s, 54, 0));
- for (int phase = 0; phase < 2; phase++) {
- s = (CommandGesture){0};
- if (phase == 0) CommandGestureUpdate(&s, kCGEventKeyDown, 0, 0, false);
- flags(&s, 55, L);
- if (phase == 1) CommandGestureUpdate(&s, kCGEventKeyDown, 0, L, false);
- assert(!flags(&s, 54, B));
- CommandGestureUpdate(&s, kCGEventKeyUp, 0, B, false);
- assert(!flags(&s, 54, L));
- assert(!flags(&s, 55, 0));
- flags(&s, 55, L);
- assert(flags(&s, 54, B));
- assert(!flags(&s, 54, L));
- flags(&s, 55, 0);
- }
- s = (CommandGesture){0};
- flags(&s, 55, L);
- CommandGestureUpdate(&s, kCGEventKeyUp, 0, L, false); // key was held before startup
- assert(!flags(&s, 54, B));
- s = (CommandGesture){0};
- flags(&s, 55, L);
- assert(flags(&s, 54, B));
- assert(!flags(&s, 54, B)); // repeat while held never triggers again
- assert(!CommandGestureUpdate(&s, kCGEventKeyDown, 0, B, true));
- assert(!flags(&s, 54, L)); // later keys cannot retroactively cancel the capture
- CGEventFlags modifiers[] = { kCGEventFlagMaskShift, kCGEventFlagMaskControl,
- kCGEventFlagMaskAlternate, kCGEventFlagMaskSecondaryFn, kCGEventFlagMaskAlphaShift };
- for (unsigned i = 0; i < sizeof(modifiers) / sizeof(*modifiers); i++) {
- s = (CommandGesture){0};
- flags(&s, 55, L | modifiers[i]);
- assert(!flags(&s, 54, B | modifiers[i]));
- flags(&s, 56, B);
- assert(!flags(&s, 54, L));
- assert(!flags(&s, 55, 0));
- }
- s = (CommandGesture){0};
- flags(&s, 55, kCGEventFlagMaskCommand);
- flags(&s, 54, kCGEventFlagMaskCommand);
- assert(!flags(&s, 54, 0)); // aggregate flags cannot prove two physical keys
- s = (CommandGesture){0};
- flags(&s, 54, B); // starting in the middle of a held chord must not arm
- assert(!flags(&s, 54, L));
- NSDictionary *(^window)(int, int, int, bool, double) = ^NSDictionary *(int wid, int pid, int layer, bool visible, double width) {
- return @{ (id)kCGWindowNumber: @(wid), (id)kCGWindowOwnerPID: @(pid),
- (id)kCGWindowLayer: @(layer), (id)kCGWindowIsOnscreen: @(visible), (id)kCGWindowAlpha: @1,
- (id)kCGWindowBounds: @{ @"X": @0, @"Y": @0, @"Width": @(width), @"Height": @200 } };
- };
- NSArray *windows = @[window(1, 42, 20, true, 100), window(2, 90, 0, true, 100),
- window(3, 42, 0, false, 100), window(4, 42, 0, true, 0),
- window(5, 42, 0, true, 300), window(6, 42, 0, true, 400)];
- NSDictionary *capture = CommandCaptureWindow(windows, 42);
- assert([capture[@"windowId"] intValue] == 5);
- assert([capture[@"width"] intValue] == 300 && [capture[@"height"] intValue] == 200);
- assert(CommandCaptureWindow(windows, 123) == nil); // never capture another app or a display
- assert(CommandCaptureWindow(windows, 0) == nil);
- puts("native gesture assertions passed");
-} return 0; }
-`
- )
- execFileSync(
- 'xcrun',
- ['clang', '-fobjc-arc', '-fblocks', '-framework', 'Cocoa', '-framework', 'CoreGraphics', fixture, '-o', binary],
- { timeout: 30_000 }
- )
- assert.equal(
- execFileSync(binary, [], { encoding: 'utf8', timeout: 5_000 }).trim(),
- 'native gesture assertions passed'
- )
- } finally {
- rmSync(dir, { recursive: true, force: true })
- }
- },
- 40_000
-)
-
-test.skipIf(process.platform !== 'darwin')(
- 'builds a universal helper with a read-only permission check and real controller lifecycle',
- async () => {
- const dir = mkdtempSync(resolve(tmpdir(), 'hermes-command-monitor-build-'))
-
- try {
- const script = resolve(import.meta.dirname, '../scripts/build-command-screenshot-monitor.mjs')
- execFileSync(process.execPath, [script, '--out-dir', resolve(dir, 'dist')], { timeout: 60_000 })
- const binary = resolveCommandScreenshotMonitorPath(dir)
-
- const architectures = execFileSync('xcrun', ['lipo', '-archs', binary], { encoding: 'utf8' })
- .trim()
- .split(/\s+/)
- .sort()
-
- assert.deepEqual(architectures, ['arm64', 'x86_64'])
- const result = spawnSync(binary, ['--check'], { encoding: 'utf8', timeout: 5_000 })
- assert.equal(result.error, undefined)
- assert.equal(result.stderr, '')
- const permission = JSON.parse(result.stdout)
- assert.deepEqual(
- permission,
- result.status === 0 ? { type: 'ready' } : { type: 'error', code: 'permission-required' }
- )
- assert.ok(result.status === 0 || result.status === 2)
- const invalid = spawnSync(binary, ['--check', '--request-permission'], { encoding: 'utf8', timeout: 5_000 })
- assert.equal(invalid.status, 64)
- assert.deepEqual(JSON.parse(invalid.stdout), { type: 'error', code: 'unavailable' })
- let closed: Promise<NodeJS.Signals | null> | undefined
-
- const monitor = new CommandScreenshotMonitor({
- appPath: dir,
- spawn: (command, args, options) => {
- const child = nodeSpawn(command, args, options)
- closed = new Promise(settle => child.once('close', (_code, signal) => settle(signal)))
-
- return child
- }
- })
-
- const statuses: CommandScreenshotStatus[] = []
-
- const terminal = await new Promise<CommandScreenshotStatus>((settle, reject) => {
- const timeout = setTimeout(() => {
- monitor.stop()
- reject(new Error('real monitor did not settle'))
- }, 10_000)
-
- monitor.start(
- () => {},
- status => {
- statuses.push(status)
-
- if (status.type === 'ready' || status.type === 'error') {
- clearTimeout(timeout)
- settle(status)
- }
- }
- )
- })
-
- assert.equal(statuses[0].type, 'starting')
-
- if (permission.type === 'error') {
- assert.deepEqual(terminal, permission)
- }
-
- monitor.stop()
- assert.ok(closed)
- assert.notEqual(await closed, 'SIGKILL') // the real helper exits without escalation
- } finally {
- rmSync(dir, { recursive: true, force: true })
- }
- },
- 75_000
-)
diff --git a/apps/desktop/electron/command-screenshot.test.ts b/apps/desktop/electron/command-screenshot.test.ts
deleted file mode 100644
index 64acadb495e..00000000000
--- a/apps/desktop/electron/command-screenshot.test.ts
+++ /dev/null
@@ -1,143 +0,0 @@
-import { EventEmitter } from 'node:events'
-import { mkdtemp, readFile, rm } from 'node:fs/promises'
-import os from 'node:os'
-import path from 'node:path'
-
-import { afterEach, describe, expect, it, vi } from 'vitest'
-
-const native = vi.hoisted(() => ({ start: vi.fn(), stop: vi.fn() }))
-
-const electron = vi.hoisted(() => ({
- handlers: new Map(),
- windows: [] as any[],
- focused: null as any,
- screenPermission: 'granted',
- directory: ''
-}))
-
-vi.mock('./command-screenshot-monitor', () => ({
- CommandScreenshotMonitor: class {
- start = native.start
- stop = native.stop
- }
-}))
-vi.mock('electron', async () => {
- const { EventEmitter } = await import('node:events')
- const ipcMain = new EventEmitter() as any
- ipcMain.handle = (channel: string, handler: unknown) => electron.handlers.set(channel, handler)
- ipcMain.removeHandler = (channel: string) => electron.handlers.delete(channel)
-
- return {
- app: Object.assign(new EventEmitter(), { getPath: () => electron.directory, getAppPath: () => '/app' }),
- ipcMain,
- BrowserWindow: {
- fromWebContents: (wc: unknown) => electron.windows.find(win => win.webContents === wc),
- getFocusedWindow: () => electron.focused,
- getAllWindows: () => electron.windows
- },
- desktopCapturer: {
- getSources: vi.fn(async () => [
- { id: 'window:42:0', thumbnail: { isEmpty: () => false, toPNG: () => new Uint8Array([1]) } }
- ])
- },
- systemPreferences: { getMediaAccessStatus: () => electron.screenPermission },
- shell: { openExternal: vi.fn() }
- }
-})
-
-import { app, desktopCapturer, ipcMain } from 'electron'
-
-import { installCommandScreenshot } from './command-screenshot'
-
-const cleanups: (() => void)[] = []
-afterEach(async () => {
- cleanups.splice(0).forEach(fn => fn())
- await rm(electron.directory, { recursive: true, force: true })
- electron.windows = []
- electron.focused = null
- electron.screenPermission = 'granted'
- vi.clearAllMocks()
-})
-
-function window(id: number, url = 'http://127.0.0.1:5174/') {
- const frame = { url }
-
- const wc = Object.assign(new EventEmitter(), {
- id,
- mainFrame: frame,
- getURL: () => url,
- isDestroyed: () => false,
- send: vi.fn()
- })
-
- const win = { webContents: wc, isDestroyed: () => false }
- electron.windows.push(win)
-
- return { win, event: { sender: wc, senderFrame: frame }, wc }
-}
-
-async function setup() {
- electron.directory = await mkdtemp(path.join(os.tmpdir(), 'hermes-screenshot-'))
- cleanups.push(installCommandScreenshot({ rendererUrl: 'http://127.0.0.1:5174/' }))
-}
-
-const call = (channel: string, event: unknown, ...args: unknown[]) =>
- electron.handlers.get(`hermes:screenshot:${channel}`)(event, ...args)
-
-describe.skipIf(process.platform !== 'darwin')('Command screenshot native bridge', () => {
- it('persists opt-in, routes to the last focused subscribed window while backgrounded, and revokes on disable', async () => {
- await setup()
- const first = window(1)
- const second = window(2)
- expect(await call('settings:get', first.event)).toEqual({ enabled: false, state: 'disabled' })
- expect(native.start).not.toHaveBeenCalled()
- ipcMain.emit('subscribe', first.event) // unrelated IPC grants nothing
- ipcMain.emit('hermes:screenshot:subscribe', first.event, true)
- ipcMain.emit('hermes:screenshot:subscribe', second.event, true)
- app.emit('browser-window-focus', {}, second.win)
- electron.focused = null
- await call('settings:set', first.event, true)
- expect(JSON.parse(await readFile(path.join(electron.directory, 'screenshot.json'), 'utf8'))).toEqual({
- enabled: true
- })
- const [capture, status] = native.start.mock.calls.at(-1)!
- status({ type: 'ready' })
- capture({ type: 'capture', windowId: 42, width: 600, height: 400 })
- const requests = second.wc.send.mock.calls.filter(([channel]) => channel === 'hermes:screenshot:request')
- expect(requests).toHaveLength(1)
- expect(first.wc.send.mock.calls.some(([channel]) => channel === 'hermes:screenshot:request')).toBe(false)
- expect(await call('capture', first.event, requests[0]![1])).toEqual({ ok: false, reason: 'expired' })
- await call('settings:set', second.event, false)
- expect(await call('capture', second.event, requests[0]![1])).toEqual({ ok: false, reason: 'expired' })
- expect(native.stop).toHaveBeenCalled()
-
- for (let i = 0; i < 3; i += 1) {
- ipcMain.emit('hermes:screenshot:subscribe', second.event, false)
- ipcMain.emit('hermes:screenshot:subscribe', second.event, true)
- }
-
- expect(second.wc.listenerCount('destroyed')).toBe(1)
- ipcMain.emit('hermes:screenshot:subscribe', second.event, false)
- expect(second.wc.listenerCount('destroyed')).toBe(0)
- })
-
- it('rejects guest/foreign frames and reports denied screen access rather than ready', async () => {
- await setup()
- const trusted = window(3)
- const foreign = window(4, 'https://example.org/')
- await expect(call('settings:set', foreign.event, true)).rejects.toThrow()
- await expect(
- call('settings:set', { ...trusted.event, senderFrame: { url: 'https://example.org/' } }, true)
- ).rejects.toThrow()
- expect(native.start).not.toHaveBeenCalled()
- electron.screenPermission = 'denied'
- await call('settings:set', trusted.event, true)
- native.start.mock.calls.at(-1)![1]({ type: 'ready' })
- expect(desktopCapturer.getSources).toHaveBeenCalledWith({
- types: ['window'],
- thumbnailSize: { width: 1, height: 1 },
- fetchWindowIcons: false
- })
- expect(await call('settings:get', trusted.event)).toEqual({ enabled: true, state: 'screen-permission' })
- })
-})
diff --git a/apps/desktop/electron/connection-apply.test.ts b/apps/desktop/electron/connection-apply.test.ts
index e19e90b4a24..420acfdf958 100644
--- a/apps/desktop/electron/connection-apply.test.ts
+++ b/apps/desktop/electron/connection-apply.test.ts
@@ -18,37 +18,34 @@ function deferred() {
}
describe('applyConnectionChange', () => {
- it.each([['SSH A to SSH B'], ['SSH to Cloud'], ['Cloud to SSH']])(
- 'serializes %s behind bootstrap rollback before teardown and apply',
- async () => {
- const gate = deferred()
- const events: string[] = []
-
- const run = applyConnectionChange({
- cancelAndWait: async () => {
- events.push('cancel')
- await gate.promise
- events.push('drained')
- },
- isPrimary: true,
- scope: '',
- sendApplied: () => events.push('applied'),
- stopPool: vi.fn(),
- teardownPrimary: async () => {
- events.push('primary')
- },
- teardownSsh: async () => {
- events.push('ssh')
- }
- })
+ it('serializes a connection switch behind bootstrap rollback before teardown and apply', async () => {
+ const gate = deferred()
+ const events: string[] = []
- await Promise.resolve()
- expect(events).toEqual(['cancel'])
- gate.resolve()
- await run
- expect(events).toEqual(['cancel', 'drained', 'ssh', 'primary', 'applied'])
- }
- )
+ const run = applyConnectionChange({
+ cancelAndWait: async () => {
+ events.push('cancel')
+ await gate.promise
+ events.push('drained')
+ },
+ isPrimary: true,
+ scope: '',
+ sendApplied: () => events.push('applied'),
+ stopPool: vi.fn(),
+ teardownPrimary: async () => {
+ events.push('primary')
+ },
+ teardownSsh: async () => {
+ events.push('ssh')
+ }
+ })
+
+ await Promise.resolve()
+ expect(events).toEqual(['cancel'])
+ gate.resolve()
+ await run
+ expect(events).toEqual(['cancel', 'drained', 'ssh', 'primary', 'applied'])
+ })
it('tears down only a non-primary scope without applying the primary connection', async () => {
const events: string[] = []
diff --git a/apps/desktop/electron/connection-config.test.ts b/apps/desktop/electron/connection-config.test.ts
index 47f530509be..98cc815e583 100644
--- a/apps/desktop/electron/connection-config.test.ts
+++ b/apps/desktop/electron/connection-config.test.ts
@@ -17,7 +17,6 @@ import { test } from 'vitest'
import { makeNousCloudBackendDownError } from './backend-health'
import {
apiRequestRegistryConnectionId,
- AT_COOKIE_VARIANTS,
authModeFromStatus,
buildGatewayWsUrl,
buildGatewayWsUrlWithTicket,
@@ -45,7 +44,6 @@ import {
resolveProfileBackendRoute,
resolveRemoteSshDashboardProfile,
resolveTestWsUrl,
- RT_COOKIE_VARIANTS,
sanitizeRemoteHeaderValue,
savedProfileSsh,
tokenPreview,
@@ -1188,14 +1186,6 @@ test('cookiesHaveSession handles non-arrays', () => {
assert.equal(cookiesHaveSession([]), false)
})
-test('AT_COOKIE_VARIANTS covers all three deploy shapes', () => {
- assert.deepEqual(AT_COOKIE_VARIANTS, ['__Host-hermes_session_at', '__Secure-hermes_session_at', 'hermes_session_at'])
-})
-
-test('RT_COOKIE_VARIANTS covers all three deploy shapes', () => {
- assert.deepEqual(RT_COOKIE_VARIANTS, ['__Host-hermes_session_rt', '__Secure-hermes_session_rt', 'hermes_session_rt'])
-})
-
// --- cookiesHaveLiveSession (AT or RT — the connectivity check) ---
test('cookiesHaveLiveSession is true for a live access-token cookie', () => {
@@ -1430,20 +1420,6 @@ test('gatewayTicketFailure preserves a structured 503 statusCode as a transport
assert.equal((wrapped as any).cause, source)
})
-test('gatewayTicketFailure keeps 401 and 403 as reauth with needsOauthLogin', () => {
- for (const code of [401, 403]) {
- const source = new Error(`HTTP ${code}`) as any
- source.statusCode = code
-
- const wrapped = gatewayTicketFailure(source, 'auth message', 'transport message')
-
- assert.equal(wrapped.message, 'auth message')
- assert.equal((wrapped as any).needsOauthLogin, true)
- assert.equal((wrapped as any).statusCode, code)
- assert.equal((wrapped as any).cause, source)
- }
-})
-
test('gatewayTicketFailure only copies an integer statusCode, not a message prefix', () => {
// A legacy "503: ..." message carries no structured statusCode; the Cloud
// classifier (makeNousCloudBackendDownError) handles the prefix at the mint
@@ -1473,7 +1449,6 @@ test('OAuth ticket-mint 503 surfaces the Cloud-down error (startup boundary)', (
if (cloudError !== null) {
assert.equal((cloudError as any).isCloudBackendDown, true)
assert.equal((cloudError as any).statusCode, 503)
- assert.ok(cloudError.message.includes('Nous Cloud agent ares-3009.agents.nousresearch.com is down'))
return
}
diff --git a/apps/desktop/electron/connection-registry.test.ts b/apps/desktop/electron/connection-registry.test.ts
index 438e9146150..de49aba630f 100644
--- a/apps/desktop/electron/connection-registry.test.ts
+++ b/apps/desktop/electron/connection-registry.test.ts
@@ -125,42 +125,6 @@ test('labelSlug kebab-cases and never returns empty for non-empty input', () =>
assert.equal(labelSlug('!!!'), 'connection')
})
-test('registry SSH fingerprint failures name the connection and ssh -G step', async () => {
- const registry = migrateV1ToRegistry({
- mode: 'ssh',
- remote: { mode: 'ssh', host: 'build-host', user: 'alice' },
- profiles: {}
- })
-
- const source = registry.connections.find(connection => connection.id === registry.primary)!
-
- const cause = new Error('spawn ssh ENOENT')
-
- source.label = 'Build box'
-
- await assert.rejects(
- reuseMatchingPrimarySshBackend({
- connectionId: registry.primary,
- effectiveFingerprint: async () => {
- throw cause
- },
- ensurePrimary: async () => ({ mode: 'remote', remoteKind: 'ssh' }),
- profile: 'default',
- registry,
- source
- }),
- error => {
- assert.equal(
- (error as Error).message,
- `Could not resolve effective SSH config for connection "Build box" (${source.id}) via ssh -G: spawn ssh ENOENT`
- )
- assert.equal((error as Error).cause, cause)
-
- return true
- }
- )
-})
-
test('matching primary/default SSH route reuses the existing descriptor once', async () => {
const registry = migrateV1ToRegistry({
mode: 'ssh',
diff --git a/apps/desktop/electron/crash-forensics.test.ts b/apps/desktop/electron/crash-forensics.test.ts
index ea53493b4c1..59a867ff477 100644
--- a/apps/desktop/electron/crash-forensics.test.ts
+++ b/apps/desktop/electron/crash-forensics.test.ts
@@ -49,7 +49,7 @@ describe('installCrashForensics', () => {
listeners.get('uncaughtException')?.(error)
- expect(log).toHaveBeenCalledWith('[main] Uncaught exception: Error: renderer gone\n at main')
+ expect(log).toHaveBeenCalledWith(expect.stringContaining('Error: renderer gone\n at main'))
expect(flush).toHaveBeenCalledTimes(1)
})
@@ -58,13 +58,7 @@ describe('installCrashForensics', () => {
listeners.get('unhandledRejection')?.('gateway ticket mint failed')
- expect(log).toHaveBeenCalledWith('[main] Unhandled rejection: gateway ticket mint failed')
+ expect(log).toHaveBeenCalledWith(expect.stringContaining('gateway ticket mint failed'))
expect(flush).toHaveBeenCalledTimes(1)
})
-
- it('registers both handlers', () => {
- const { listeners } = harness()
-
- expect([...listeners.keys()].sort()).toEqual(['uncaughtException', 'unhandledRejection'])
- })
})
diff --git a/apps/desktop/electron/dashboard-token.test.ts b/apps/desktop/electron/dashboard-token.test.ts
index e0a45eb36cc..880e3b3a7c1 100644
--- a/apps/desktop/electron/dashboard-token.test.ts
+++ b/apps/desktop/electron/dashboard-token.test.ts
@@ -52,7 +52,6 @@ test('resolveServedDashboardToken uses the served token and logs when it differs
assert.equal(token, 'served-token')
assert.equal(logs.length, 1)
- assert.match(logs[0], /served a different session token/)
})
test('resolveServedDashboardToken falls back when the served HTML has no token', async () => {
@@ -66,17 +65,6 @@ test('resolveServedDashboardToken falls back when the served HTML has no token',
assert.equal(token, 'spawn-token')
})
-test('resolveServedDashboardToken does not log when served token matches fallback', async () => {
- const token = await resolveServedDashboardToken('http://127.0.0.1:9120', 'same-token', {
- fetchText: async () => '<script>window.__HERMES_SESSION_TOKEN__="same-token";</script>',
- rememberLog: () => {
- throw new Error('should not log when token already matches')
- }
- })
-
- assert.equal(token, 'same-token')
-})
-
test('resolveServedDashboardToken propagates fetch errors so callers can fall back explicitly', async () => {
await assert.rejects(
() =>
diff --git a/apps/desktop/electron/desktop-electron-pin.test.ts b/apps/desktop/electron/desktop-electron-pin.test.ts
index 1428003d3ec..8ffb3f0e95a 100644
--- a/apps/desktop/electron/desktop-electron-pin.test.ts
+++ b/apps/desktop/electron/desktop-electron-pin.test.ts
@@ -33,10 +33,6 @@ const REPO_ROOT = path.resolve(__dirname, '..', '..', '..')
const DESKTOP_PKG = path.join(REPO_ROOT, 'apps', 'desktop', 'package.json')
const ROOT_LOCK = path.join(REPO_ROOT, 'package-lock.json')
-// An exact semver: digits.digits.digits with an optional prerelease/build tag,
-// but NO range operators (^ ~ > < = * x || spaces || -range).
-const EXACT_SEMVER = /^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/
-
function desktopPkg(): Record<string, unknown> {
assert.ok(fs.existsSync(DESKTOP_PKG), `missing ${DESKTOP_PKG}`)
@@ -56,17 +52,6 @@ function electronSpec(pkg: Record<string, unknown>): string {
assert.fail('electron is not listed in apps/desktop dependencies')
}
-test('electron dependency is exactly pinned', () => {
- const spec = electronSpec(desktopPkg())
- assert.match(
- spec,
- EXACT_SEMVER,
- `electron must be pinned to an exact version, got "${spec}". ` +
- 'A range (^/~) lets npm ci resolve a newer Electron whose postinstall ' +
- 'may differ from the one the build was validated against.'
- )
-})
-
test('electron dependency matches build.electronVersion', () => {
const pkg = desktopPkg()
const spec = electronSpec(pkg)
diff --git a/apps/desktop/electron/desktop-log-line.test.ts b/apps/desktop/electron/desktop-log-line.test.ts
index 4adca4c29df..8c1e5a266e4 100644
--- a/apps/desktop/electron/desktop-log-line.test.ts
+++ b/apps/desktop/electron/desktop-log-line.test.ts
@@ -13,10 +13,4 @@ describe('formatDesktopLogLine', () => {
/^\[\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z\] \[hermes\] \[boot\] Resolving Hermes backend$/
)
})
-
- it('keeps the message verbatim after the prefix', () => {
- const line = formatDesktopLogLine('Hermes backend exited (0)')
-
- expect(line).toMatch(/^\[\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z\] \[hermes\] Hermes backend exited \(0\)$/)
- })
})
diff --git a/apps/desktop/electron/desktop-plugin-install.test.ts b/apps/desktop/electron/desktop-plugin-install.test.ts
index e7bb67e9b00..f455cc9826e 100644
--- a/apps/desktop/electron/desktop-plugin-install.test.ts
+++ b/apps/desktop/electron/desktop-plugin-install.test.ts
@@ -9,7 +9,6 @@ import {
desktopPluginFolderName,
detectPluginComponents,
findDesktopEntry,
- repoNameFromUrl,
resolvePluginGitUrl,
resolveSubdirWithin
} from './desktop-plugin-install'
@@ -43,12 +42,6 @@ describe('resolvePluginGitUrl', () => {
})
})
-describe('repoNameFromUrl', () => {
- it('strips .git suffix', () => {
- expect(repoNameFromUrl('https://github.com/o/my-plugin.git')).toBe('my-plugin')
- })
-})
-
describe('desktopPluginFolderName', () => {
it('uses the repo name for a root-level plugin, not the clone path', () => {
expect(desktopPluginFolderName('https://github.com/o/my-plugin.git', null)).toBe('my-plugin')
diff --git a/apps/desktop/electron/desktop-plugins-root.test.ts b/apps/desktop/electron/desktop-plugins-root.test.ts
index 9bb08a2a1af..086c439e61a 100644
--- a/apps/desktop/electron/desktop-plugins-root.test.ts
+++ b/apps/desktop/electron/desktop-plugins-root.test.ts
@@ -117,7 +117,7 @@ describe('reconcileUnifiedDesktopHalves', () => {
try {
expect(await reconcileUnifiedDesktopHalves(home, appRoot)).toEqual([path.join(appRoot, 'good')])
- expect(warn).toHaveBeenCalledWith(expect.stringContaining('skipping unreadable package denied'))
+ expect(warn).toHaveBeenCalled()
} finally {
warn.mockRestore()
fs.chmodSync(denied, 0o600)
@@ -142,7 +142,7 @@ describe('reconcileUnifiedDesktopHalves', () => {
try {
expect(await reconcileUnifiedDesktopHalves(home, appRoot)).toEqual([])
expect(fs.existsSync(path.join(appRoot, 'denied'))).toBe(true)
- expect(warn).toHaveBeenCalledWith(expect.stringContaining('unreadable package denied'))
+ expect(warn).toHaveBeenCalled()
} finally {
warn.mockRestore()
fs.chmodSync(denied, 0o700)
diff --git a/apps/desktop/electron/desktop-uninstall.test.ts b/apps/desktop/electron/desktop-uninstall.test.ts
index 6d296ee1db9..8cbbd634b7b 100644
--- a/apps/desktop/electron/desktop-uninstall.test.ts
+++ b/apps/desktop/electron/desktop-uninstall.test.ts
@@ -20,27 +20,16 @@ import {
modeRemovesUserData,
resolveRemovableAppPath,
shouldRemoveAppBundle,
- UNINSTALL_MODES,
uninstallArgsForMode
} from './desktop-uninstall'
// --- uninstallArgsForMode ---
-test('uninstallArgsForMode maps each mode to the module-runner argv', () => {
- assert.deepEqual(uninstallArgsForMode('gui'), ['-m', 'hermes_cli.uninstall', '--mode', 'gui'])
- assert.deepEqual(uninstallArgsForMode('lite'), ['-m', 'hermes_cli.uninstall', '--mode', 'lite'])
- assert.deepEqual(uninstallArgsForMode('full'), ['-m', 'hermes_cli.uninstall', '--mode', 'full'])
-})
-
test('uninstallArgsForMode throws on an unknown mode (no silent full wipe)', () => {
assert.throws(() => uninstallArgsForMode('nuke'), /Unknown uninstall mode/)
assert.throws(() => uninstallArgsForMode(''), /Unknown uninstall mode/)
})
-test('UNINSTALL_MODES lists exactly the three supported modes', () => {
- assert.deepEqual([...UNINSTALL_MODES].sort(), ['full', 'gui', 'lite'])
-})
-
// --- modeRemovesAgent / modeRemovesUserData ---
test('mode predicates classify what each mode removes', () => {
@@ -137,8 +126,6 @@ test('buildPosixCleanupScript waits for the PID, runs the uninstall module, remo
assert.match(script, /^#!\/bin\/bash/)
assert.match(script, /pid=4321/)
assert.match(script, /kill -0 "\$pid"/)
- // bounded wait (~30s), not unbounded
- assert.match(script, /seq 1 60/)
assert.match(script, /'-m' 'hermes_cli\.uninstall' '--mode' 'gui'/)
assert.match(script, /rm -rf '\/opt\/hermes\/linux-unpacked'/)
assert.match(script, /export HERMES_HOME='\/home\/x\/\.hermes'/)
@@ -227,7 +214,6 @@ test('buildWindowsCleanupScript waits (bounded) for PID, runs uninstall, rmdir b
// Bounded wait-loop (no infinite loop), whole-token PID match (no substring).
assert.match(script, /if %waited% geq 60 goto waited_done/)
assert.match(script, /findstr \/r \/c:" %PID% "/)
- assert.doesNotMatch(script, /find "%PID%"/) // the old substring-prone form is gone
// Removal is a retry loop (Windows releases dir handles lazily).
assert.match(script, /:rmloop/)
assert.match(script, /rmdir \/s \/q "C:\\Users\\x\\AppData\\Local\\Programs\\Hermes" >nul 2>&1/)
diff --git a/apps/desktop/electron/dev-cdp.test.ts b/apps/desktop/electron/dev-cdp.test.ts
index f86aa9db304..dbb0d12a1fc 100644
--- a/apps/desktop/electron/dev-cdp.test.ts
+++ b/apps/desktop/electron/dev-cdp.test.ts
@@ -19,12 +19,6 @@ test('a dev-server run opens the default port with no opt-in', () => {
assert.deepEqual(resolveDevCdpPort(devRun), { port: DEFAULT_PORT, reason: null })
})
-test('the default matches what the scripts/ tooling reaches for', () => {
- // scripts/eval.mjs and scripts/perf/lib/cdp.mjs both default here; if this
- // drifts, `node scripts/eval.mjs ...` stops finding a live renderer.
- assert.equal(DEFAULT_PORT, 9222)
-})
-
test('a packaged build never opens the port, however loudly the env asks', () => {
const decision = resolveDevCdpPort({ ...devRun, env: { HERMES_DESKTOP_CDP_PORT: '9222' }, isPackaged: true })
diff --git a/apps/desktop/electron/event-dedupe.test.ts b/apps/desktop/electron/event-dedupe.test.ts
index c27096796be..7ec52b20a67 100644
--- a/apps/desktop/electron/event-dedupe.test.ts
+++ b/apps/desktop/electron/event-dedupe.test.ts
@@ -27,15 +27,6 @@ test('re-fires once the window elapses', () => {
assert.equal(isDup('turnDone:s1', 1000), false, 'window elapsed → fires again')
})
-test('prunes stale keys so the map cannot grow unbounded', () => {
- const isDup = createEventDeduper(1000)
-
- for (let i = 0; i < 100; i += 1) {
- // Each far-apart key is pruned before the next, so none linger as duplicates.
- assert.equal(isDup(`turnDone:s${i}`, i * 2000), false)
- }
-})
-
// #99717: the hidden app window under an open HUD claims the same reply late.
test('a spoken reply stays claimed long after the tick window, a beep does not', () => {
const owns = createAmbientClaimArbiter(1000)
diff --git a/apps/desktop/electron/find-in-page.test.ts b/apps/desktop/electron/find-in-page.test.ts
index d1fc8c7feb8..3c3db5c355f 100644
--- a/apps/desktop/electron/find-in-page.test.ts
+++ b/apps/desktop/electron/find-in-page.test.ts
@@ -106,12 +106,6 @@ describe('formatFoundInPage', () => {
})
describe('performFind', () => {
- test('forwards the query and options to webContents.findInPage', () => {
- const wc = makeFakeWebContents()
- performFind(asWC(wc), 'hello', { forward: true, findNext: false })
- assert.deepEqual(wc.calls.find, [{ query: 'hello', options: { forward: true, findNext: false } }])
- })
-
test('defaults forward to true when omitted', () => {
const wc = makeFakeWebContents()
performFind(asWC(wc), 'x', { findNext: true })
@@ -213,13 +207,6 @@ describe('installFoundInPageForwarder', () => {
assert.deepEqual(wc.calls.send, [{ channel: 'hermes:found-in-page', payload: { activeMatchOrdinal: 2, count: 5 } }])
})
- test('handles missing fields without throwing', () => {
- const wc = makeFakeWebContents()
- installFoundInPageForwarder(asWC(wc))
- wc.emit('found-in-page', {}, {})
- assert.deepEqual(wc.calls.send, [{ channel: 'hermes:found-in-page', payload: { activeMatchOrdinal: 0, count: 0 } }])
- })
-
test('skips send when webContents is destroyed at fire time', () => {
const wc = makeFakeWebContents()
installFoundInPageForwarder(asWC(wc))
diff --git a/apps/desktop/electron/first-run-setup-main-process.test.ts b/apps/desktop/electron/first-run-setup-main-process.test.ts
index ba453ba3a38..238d75cb1cd 100644
--- a/apps/desktop/electron/first-run-setup-main-process.test.ts
+++ b/apps/desktop/electron/first-run-setup-main-process.test.ts
@@ -82,16 +82,9 @@ test('a first-run bootstrap-needed remote apply connects without ensuring or boo
kind: 'remote',
connection: { ...candidateRemote, mode: 'remote' }
})
- assert.deepEqual(resolveRemote.mock.calls, [[], []])
- assert.deepEqual(connectRemote.mock.calls, [[candidateRemote]])
- assert.deepEqual(waitForLocalStart.mock.calls, [[]])
- assert.deepEqual(prepareLocalBackend.mock.calls, [[]])
assert.equal(ensureLocalRuntime.mock.calls.length, 0)
assert.equal(runBootstrap.mock.calls.length, 0)
- assert.deepEqual(cancelSshBootstrap.mock.calls, [['']])
- assert.deepEqual(teardownSsh.mock.calls, [['']])
assert.equal(teardownPrimaryBackend.mock.calls.length, 0)
- assert.equal(clearLocalBootstrapFailure.mock.calls.length, 1)
assert.equal(notifyConnectionApplied.mock.calls.length, 0)
})
diff --git a/apps/desktop/electron/fs-ipc.test.ts b/apps/desktop/electron/fs-ipc.test.ts
index d985612caf8..9c25c461d60 100644
--- a/apps/desktop/electron/fs-ipc.test.ts
+++ b/apps/desktop/electron/fs-ipc.test.ts
@@ -69,19 +69,6 @@ describe('hermes:fs:reveal', () => {
expect(electron.showItemInFolder).not.toHaveBeenCalled()
})
- it('reports false for a path that is not on this computer, and only shows one that is', async () => {
- const here = path.join(scratch, 'notes.md')
-
- fs.writeFileSync(here, 'x')
-
- await expect(reveal('/home/hermes/.hermes/attachments/report.zip')).resolves.toBe(false)
- expect(electron.showItemInFolder).not.toHaveBeenCalled()
-
- await expect(reveal(here)).resolves.toBe(true)
- expect(electron.showItemInFolder).toHaveBeenCalledTimes(1)
- expect(electron.showItemInFolder).toHaveBeenCalledWith(here)
- })
-
// The renderer may hand over a tilde path; the existence check runs on the
// expanded path, and the expanded path is what the file manager is shown.
it('expands a tilde path before checking and revealing it', async () => {
diff --git a/apps/desktop/electron/fs-read-dir.test.ts b/apps/desktop/electron/fs-read-dir.test.ts
index c77e60434ec..69171fe691b 100644
--- a/apps/desktop/electron/fs-read-dir.test.ts
+++ b/apps/desktop/electron/fs-read-dir.test.ts
@@ -185,40 +185,6 @@ test('readDirForIpc marks a symlink to a directory as a directory', async t => {
}
})
-test('readDirForIpc marks a Windows junction to a directory as a directory', async t => {
- if (process.platform !== 'win32') {
- t.skip('junctions are a Windows-specific symlink type')
-
- return
- }
-
- const root = mkTmpDir()
-
- try {
- fs.mkdirSync(path.join(root, 'actual-dir'))
-
- try {
- fs.symlinkSync(path.join(root, 'actual-dir'), path.join(root, 'junction-dir'), 'junction')
- } catch (error) {
- if (error?.code === 'EPERM' || error?.code === 'EACCES') {
- t.skip(`junction creation is not permitted on this platform (${error.code})`)
-
- return
- }
-
- throw error
- }
-
- const result = await readDirForIpc(root)
- const junction = result.entries.find(entry => entry.name === 'junction-dir')
-
- assert.equal(result.error, undefined)
- assert.equal(junction?.isDirectory, true)
- } finally {
- fs.rmSync(root, { recursive: true, force: true })
- }
-})
-
test('readDirForIpc allows expanding symlink or junction directories outside the project root', async t => {
const root = mkTmpDir()
const outside = mkTmpDir()
diff --git a/apps/desktop/electron/gateway-file-download-transport.test.ts b/apps/desktop/electron/gateway-file-download-transport.test.ts
deleted file mode 100644
index b245165cbf0..00000000000
--- a/apps/desktop/electron/gateway-file-download-transport.test.ts
+++ /dev/null
@@ -1,71 +0,0 @@
-/**
- * Wiring coverage for the main.ts gateway download transports. These functions
- * pull in main-process singletons (https/http, electronNet, the OAuth session,
- * the save dialog), so we assert on their source shape — the same approach as
- * oauth-session-request.test.ts — while gateway-file-download.test.ts unit-tests
- * the extracted streaming/decoding logic behaviorally.
- */
-
-import assert from 'node:assert/strict'
-import fs from 'node:fs'
-import path from 'node:path'
-import { fileURLToPath } from 'node:url'
-
-import { test } from 'vitest'
-
-const __dirname = path.dirname(fileURLToPath(import.meta.url))
-const source = fs.readFileSync(path.join(__dirname, 'main.ts'), 'utf8')
-
-function extract(startMarker: string, endMarker: string): string {
- const start = source.indexOf(startMarker)
- assert.notEqual(start, -1, `${startMarker} should exist`)
- const end = source.indexOf(endMarker, start + startMarker.length)
- assert.notEqual(end, -1, `boundary after ${startMarker} should exist`)
-
- return source.slice(start, end)
-}
-
-test('token transport streams to disk instead of buffering the whole body', () => {
- const fn = extract('function downloadViaTokenToFile', '\nfunction ')
-
- // Delegates byte-moving to the streaming finalizer...
- assert.match(fn, /finalizeGatewayDownload\(/)
- // ...and must NOT accumulate the full response before writing.
- assert.doesNotMatch(fn, /Buffer\.concat/)
- assert.doesNotMatch(fn, /chunks\.push/)
- // Idle timeout is dropped once headers arrive so the dialog/stream isn't killed.
- assert.match(fn, /setTimeout\(0\)/)
-})
-
-test('oauth transport streams to disk instead of buffering the whole body', () => {
- const fn = extract('function downloadViaOauthSessionToFile', '\nasync function finalizeGatewayDownload')
-
- assert.match(fn, /electronNet\.request/)
- assert.match(fn, /finalizeGatewayDownload\(/)
- assert.doesNotMatch(fn, /Buffer\.concat/)
- assert.doesNotMatch(fn, /chunks\.push/)
-})
-
-test('finalizeGatewayDownload prompts a save dialog then streams the response', () => {
- const fn = extract('async function finalizeGatewayDownload', '\nfunction readGatewayErrorText')
-
- assert.match(fn, /dialog\.showSaveDialog/)
- assert.match(fn, /pumpStreamToFile\(/)
- // Production deps come from one place so the streaming save and the data-URL
- // fallback share the exclusive-create + rename contract (#96597).
- assert.match(fn, /fsPumpDeps\(\)/)
- assert.doesNotMatch(fn, /fs\.createWriteStream/)
- // HTTP errors carry their status so a 404 can trigger the fallback.
- assert.match(fn, /throw httpStatusError\(statusCode, /)
-})
-
-test('data-URL fallback writes through the same failure-atomic primitive, never writeFile in place', () => {
- const fn = extract('async function saveGatewayFileViaDataUrl', '\n// Mint a single-use WS ticket')
-
- assert.match(fn, /dialog\.showSaveDialog/)
- assert.match(fn, /writeBufferToFile\(/)
- assert.match(fn, /fsPumpDeps\(\)/)
- // A direct writeFile truncates an existing destination before the write
- // completes; a mid-write failure would destroy it (#96597).
- assert.doesNotMatch(fn, /fs\.promises\.writeFile/)
-})
diff --git a/apps/desktop/electron/gateway-file-download.test.ts b/apps/desktop/electron/gateway-file-download.test.ts
index 7683d0192f5..337c8ac13c4 100644
--- a/apps/desktop/electron/gateway-file-download.test.ts
+++ b/apps/desktop/electron/gateway-file-download.test.ts
@@ -135,27 +135,6 @@ test('downloadTempPath stays beside the destination with a short, random per-cal
assert.ok(path.basename(downloadTempPath(longName)).length < 40)
})
-test('pumpStreamToFile streams chunks into a sibling temp file, then renames it onto the destination', async () => {
- const res = new FakeResponse()
- const ws = new FakeWriteStream()
- const { deps, opened, renamed, unlinked } = recordingDeps(ws)
-
- const promise = pumpStreamToFile(res as never, '/tmp/out.bin', deps)
-
- res.emit('data', Buffer.from('abc'))
- res.emit('data', Buffer.from('def'))
- res.emit('end')
-
- await promise
-
- assert.equal(Buffer.concat(ws.chunks).toString('utf8'), 'abcdef')
- assert.equal(ws.ended, true)
- assert.equal(opened.length, 1)
- assertTempPathBeside(opened[0], '/tmp/out.bin')
- assert.deepEqual(renamed, [[opened[0], '/tmp/out.bin']])
- assert.deepEqual(unlinked, []) // success -> no cleanup
-})
-
test('pumpStreamToFile waits for the descriptor to close before renaming when the stream supports close()', async () => {
const res = new FakeResponse()
const order: string[] = []
@@ -258,60 +237,6 @@ test('pumpStreamToFile waits for the write stream to close before unlinking the
assert.deepEqual(unlinked, [opened[0]])
})
-// Ownership gate: an exclusive create can fail BEFORE this pump owns anything at
-// the temp path (EEXIST on a collision). Cleanup must not unlink a file it did
-// not create, or the destructive class moves from the destination to the temp
-// name.
-test('pumpStreamToFile never unlinks a temp path it did not create when the exclusive open fails', async () => {
- const res = new FakeResponse()
- const ws = new FakeWriteStream([], { opens: false })
- const { deps, opened, renamed, unlinked } = recordingDeps(ws)
-
- const promise = pumpStreamToFile(res as never, '/tmp/out.bin', deps)
-
- const eexist: any = new Error("EEXIST: file already exists, open '/tmp/.hermes-download-deadbeef.part'")
-
- eexist.code = 'EEXIST'
- ws.emit('error', eexist)
-
- await assert.rejects(promise, /EEXIST/)
- assert.equal(opened.length, 1, 'one create attempt')
- assert.deepEqual(unlinked, [], 'the colliding file belongs to someone else and must survive')
- assert.deepEqual(renamed, [])
- assert.equal(res.destroyed, true)
-})
-
-test('pumpStreamToFile honours tempPathFor so a regression can pin the temp path', async () => {
- const res = new FakeResponse()
- const ws = new FakeWriteStream()
- const { deps, opened, renamed } = recordingDeps(ws)
-
- deps.tempPathFor = () => '/tmp/pinned.part'
-
- const promise = pumpStreamToFile(res as never, '/tmp/out.bin', deps)
-
- res.emit('data', Buffer.from('abc'))
- res.emit('end')
-
- await promise
-
- assert.deepEqual(opened, ['/tmp/pinned.part'])
- assert.deepEqual(renamed, [['/tmp/pinned.part', '/tmp/out.bin']])
-})
-
-test('writeBufferToFile streams the buffer through the same temp-then-rename contract', async () => {
- const ws = new FakeWriteStream()
- const { deps, opened, renamed, unlinked } = recordingDeps(ws)
-
- await writeBufferToFile(Buffer.from('whole body'), '/tmp/out.bin', deps)
-
- assert.equal(Buffer.concat(ws.chunks).toString('utf8'), 'whole body')
- assert.equal(opened.length, 1)
- assertTempPathBeside(opened[0], '/tmp/out.bin')
- assert.deepEqual(renamed, [[opened[0], '/tmp/out.bin']])
- assert.deepEqual(unlinked, [])
-})
-
test('writeBufferToFile leaves the destination untouched when the write fails after open', async () => {
// fs.WriteStream surfaces a write failure before 'finish', never after, so
// the fake errors from write() itself.
@@ -333,42 +258,6 @@ test('writeBufferToFile leaves the destination untouched when the write fails af
assert.deepEqual(renamed, [])
})
-// Regression for #96597: opening the destination directly truncated it as soon
-// as the stream opened, and the error path then unlinked it — so a gateway
-// hiccup mid-download destroyed a pre-existing file the user had chosen to
-// overwrite. The destination must be neither opened nor removed on failure.
-test('pumpStreamToFile leaves a pre-existing destination untouched when the response fails mid-stream', async () => {
- const res = new FakeResponse()
- const ws = new FakeWriteStream()
- const { deps, opened, renamed, unlinked } = recordingDeps(ws)
-
- const promise = pumpStreamToFile(res as never, '/tmp/out.bin', deps)
-
- res.emit('data', Buffer.from('abc'))
- res.emit('error', new Error('socket hang up'))
-
- await assert.rejects(promise, /socket hang up/)
- assert.ok(!opened.includes('/tmp/out.bin'), 'destination must not be opened (and truncated) before the body lands')
- assert.ok(!unlinked.includes('/tmp/out.bin'), 'destination must not be removed on failure')
- assert.deepEqual(unlinked, [opened[0]])
- assert.deepEqual(renamed, [])
-})
-
-test('pumpStreamToFile removes the temp file and rejects when the final rename fails', async () => {
- const res = new FakeResponse()
- const ws = new FakeWriteStream()
- const { deps, opened, unlinked } = recordingDeps(ws, { renameError: new Error('EPERM: destination locked') })
-
- const promise = pumpStreamToFile(res as never, '/tmp/out.bin', deps)
-
- res.emit('data', Buffer.from('abc'))
- res.emit('end')
-
- await assert.rejects(promise, /destination locked/)
- assert.deepEqual(unlinked, [opened[0]], 'the temp file must not be left behind after a failed rename')
- assert.ok(!unlinked.includes('/tmp/out.bin'))
-})
-
test('parseDataUrlToBuffer decodes base64 payloads', () => {
const buffer = parseDataUrlToBuffer('data:text/markdown;base64,IyByZXBvcnQ=')
diff --git a/apps/desktop/electron/gateway-stop-before-update.test.ts b/apps/desktop/electron/gateway-stop-before-update.test.ts
index 91c6275ae20..400addbd397 100644
--- a/apps/desktop/electron/gateway-stop-before-update.test.ts
+++ b/apps/desktop/electron/gateway-stop-before-update.test.ts
@@ -2,11 +2,7 @@ import assert from 'node:assert/strict'
import { test } from 'vitest'
-import {
- GATEWAY_STOP_TIMEOUT_MS,
- startGatewaysAfterUpdateAbort,
- stopGatewayBeforeUpdate
-} from './gateway-stop-before-update'
+import { startGatewaysAfterUpdateAbort, stopGatewayBeforeUpdate } from './gateway-stop-before-update'
const CLI = 'C:\\Users\\x\\hermes\\hermes-agent\\venv\\Scripts\\hermes.exe'
const HOME = 'C:\\Users\\x\\hermes'
@@ -79,25 +75,6 @@ test('Windows with failing CLI returns false (best-effort, never throws)', () =>
assert.equal(ran, false)
})
-test('passes a generous timeout with hidden console (taskkill window suppression)', () => {
- let seenOptions: unknown
- stopGatewayBeforeUpdate(CLI, HOME, {
- isWindows: true,
- existsSync: () => true,
- execFileSync: ((_c: string, _a: string[], options: unknown) => {
- seenOptions = options
-
- return Buffer.from('')
- }) as never
- })
- assert.deepEqual(seenOptions, {
- timeout: GATEWAY_STOP_TIMEOUT_MS,
- windowsHide: true,
- stdio: 'ignore',
- encoding: 'utf8'
- })
-})
-
test('abort-path counterpart invokes "gateway start --all" (drain-semantics restore)', () => {
let seenArgs: string[] = []
diff --git a/apps/desktop/electron/git-review-ops.test.ts b/apps/desktop/electron/git-review-ops.test.ts
index 9880b53ab33..c1c28303578 100644
--- a/apps/desktop/electron/git-review-ops.test.ts
+++ b/apps/desktop/electron/git-review-ops.test.ts
@@ -38,26 +38,6 @@ test('gitFor accepts an internally resolved git binary path containing spaces',
assert.doesNotThrow(() => gitFor(process.cwd(), 'C:\\Program Files\\Git\\cmd\\git.exe'))
})
-test('gitFor runs git through a spaced binary path', async () => {
- if (process.platform !== 'win32') {
- return
- }
-
- const gitBin = path.join(process.env.ProgramFiles || String.raw`C:\Program Files`, 'Git', 'cmd', 'git.exe')
-
- if (!fs.existsSync(gitBin)) {
- return
- }
-
- const repo = makeRepo()
-
- fs.writeFileSync(path.join(repo, 'changed.txt'), 'review me\n')
-
- const status = await gitFor(repo, gitBin).status()
-
- assert.equal(status.not_added.includes('changed.txt'), true)
-})
-
test('resolveRenamePath: simple rename resolves to the new path', () => {
assert.equal(resolveRenamePath('old.ts => new.ts'), 'new.ts')
})
diff --git a/apps/desktop/electron/github-api-auth.test.ts b/apps/desktop/electron/github-api-auth.test.ts
index ffc67e2c2a4..a441662097f 100644
--- a/apps/desktop/electron/github-api-auth.test.ts
+++ b/apps/desktop/electron/github-api-auth.test.ts
@@ -3,7 +3,6 @@ import assert from 'node:assert/strict'
import { beforeEach, test } from 'vitest'
import {
- describeGitHubCredentialSource,
findGhCli,
forgetGhCliToken,
GH_CLI_TIMEOUT_MS,
@@ -167,8 +166,3 @@ test('gh rung: argv-only spawn, stdin closed, bounded, cached for the process, a
)
assert.equal(logged.calls.length, 1)
})
-
-test('the rejected-credential log line names the source, never the token', () => {
- assert.match(describeGitHubCredentialSource('env'), /GITHUB_TOKEN \/ GH_TOKEN/)
- assert.match(describeGitHubCredentialSource('gh-cli'), /gh auth token/)
-})
diff --git a/apps/desktop/electron/hardening.test.ts b/apps/desktop/electron/hardening.test.ts
index 6ba1ebc40a0..6cc1a7f3545 100644
--- a/apps/desktop/electron/hardening.test.ts
+++ b/apps/desktop/electron/hardening.test.ts
@@ -2,7 +2,7 @@ import assert from 'node:assert/strict'
import fs from 'node:fs'
import os from 'node:os'
import path from 'node:path'
-import { fileURLToPath, pathToFileURL } from 'node:url'
+import { pathToFileURL } from 'node:url'
import { test } from 'vitest'
@@ -86,11 +86,6 @@ test('clampDataUrlReadMaxMb defaults and bounds the attach size preference', ()
assert.equal(dataUrlReadMaxBytesFromMb(16), 16 * 1024 * 1024)
})
-test('attachment upload cap is bounded above the preview default', () => {
- assert.equal(ATTACHMENT_UPLOAD_DEFAULT_MAX_BYTES, 256 * 1024 * 1024)
- assert.ok(ATTACHMENT_UPLOAD_DEFAULT_MAX_BYTES > dataUrlReadMaxBytesFromMb(DATA_URL_READ_DEFAULT_MAX_MB))
-})
-
test('attachment data URL helper reads bytes above the preview default without changing that limit', async () => {
const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'hermes-desktop-large-attachment-'))
const source = path.join(tempDir, 'large.bin')
@@ -972,161 +967,6 @@ test('resolveDirectoryForIpc accepts directory symlinks or junctions', async ()
}
})
-// main.ts has no module.exports, so the wiring of the extracted keyring-less
-// helpers into the main process follows the repo's source-assertion pattern
-// (see windows-hermes-resolution.test.ts). These pin the propagation the PR
-// reviewer flagged as untested: the connection-config IPC path forwarding
-// allowPlainTextToken through resolvePersistedRemoteToken, and the whenReady
-// --password-store=basic startup branch.
-const __dirname = path.dirname(fileURLToPath(import.meta.url))
-
-function readMain() {
- return fs.readFileSync(path.join(__dirname, 'main.ts'), 'utf8').replace(/\r\n/g, '\n')
-}
-
-test('registry JSON helpers retain native OAuth bearer authentication', () => {
- const source = readMain()
- const postStart = source.indexOf('async function postJsonForBackend(')
- const fetchStart = source.indexOf('async function fetchJsonForBackend(', postStart)
- const helpers = source.slice(postStart, fetchStart)
-
- assert.notEqual(postStart, -1)
- assert.notEqual(fetchStart, -1)
- assert.match(
- helpers,
- /return fetchJsonForBackend\(descriptor, path, \{ \.\.\.opts, body: body \?\? \{\}, method: 'POST' \}\)/
- )
- assert.match(helpers, /return fetchJsonForBackend\(descriptor, path, opts\)/)
- assert.doesNotMatch(helpers, /fetchJsonViaOauthSession/)
-})
-
-test('coerceDesktopConnectionConfig routes token persistence through resolvePersistedRemoteToken', () => {
- const source = readMain()
- const fnStart = source.indexOf('function coerceDesktopConnectionConfig(')
- assert.notEqual(fnStart, -1, 'coerceDesktopConnectionConfig must exist in main.ts')
- const fnEnd = source.indexOf('\nfunction ', fnStart + 1)
- const body = source.slice(fnStart, fnEnd === -1 ? undefined : fnEnd)
-
- assert.match(
- body,
- /const nextToken = resolvePersistedRemoteToken\(\{/,
- 'the persist decision must go through the shared hardening helper'
- )
- // The opt-in must be forwarded RAW (no `=== true` at the call site): the
- // helper owns the strict coercion so it is asserted in exactly one place.
- assert.match(
- body,
- /allowPlainText: input\.allowPlainTextToken\b/,
- 'allowPlainTextToken must reach the helper so the IPC opt-in propagates'
- )
- assert.doesNotMatch(
- body,
- /allowPlainText: input\.allowPlainTextToken === true/,
- 'the strict coercion must live in the helper, not be duplicated at the call site'
- )
- assert.match(body, /encryptSecret: encryptDesktopSecret\b/, 'the helper must encrypt via encryptDesktopSecret')
-})
-
-test('connection-config save and apply IPC handlers route payloads through coerceDesktopConnectionConfig', () => {
- const source = readMain()
-
- for (const channel of ['hermes:connection-config:save', 'hermes:connection-config:apply']) {
- const handlerStart = source.indexOf(`ipcMain.handle('${channel}'`)
- assert.notEqual(handlerStart, -1, `${channel} handler must exist`)
- const handlerBody = source.slice(handlerStart, handlerStart + 400)
- assert.match(
- handlerBody,
- /coerceDesktopConnectionConfig\(payload(?:, previousConfig)?\)/,
- `${channel} must coerce its payload (the propagation seam) before persisting`
- )
- }
-})
-
-test('whenReady enables basic password-store encryption before createWindow', () => {
- const source = readMain()
- const enableIndex = source.indexOf('enableBasicPasswordStoreEncryption({')
- assert.notEqual(enableIndex, -1, 'whenReady must call enableBasicPasswordStoreEncryption')
-
- const call = source.slice(enableIndex, enableIndex + 240)
- assert.match(call, /platform: process\.platform/, 'the real platform must be forwarded')
- assert.match(
- call,
- /passwordStoreSwitch: app\.commandLine\.getSwitchValue\('password-store'\)/,
- 'the real --password-store switch value must be forwarded'
- )
- assert.match(call, /safeStorageApi: safeStorage/, 'the real safeStorage must be forwarded')
-
- // Ordering matters: the switch must take effect before anything touches
- // safeStorage, so the enable call must precede the first createWindow().
- const createWindowIndex = source.indexOf('createWindow()', enableIndex)
- assert.notEqual(createWindowIndex, -1, 'whenReady must call createWindow after enabling encryption')
- assert.ok(
- enableIndex < createWindowIndex,
- 'enableBasicPasswordStoreEncryption must run before createWindow() so the switch is applied first'
- )
-})
-
-test('sanitizeDesktopConnectionConfig exposes secureTokenStorage and remoteTokenPlainText', () => {
- const source = readMain()
- const fnStart = source.indexOf('async function sanitizeDesktopConnectionConfig(')
- assert.notEqual(fnStart, -1, 'sanitizeDesktopConnectionConfig must exist in main.ts')
- const fnEnd = source.indexOf('\nfunction ', fnStart + 1)
- const body = source.slice(fnStart, fnEnd === -1 ? undefined : fnEnd)
-
- const returnIndex = body.indexOf('return {')
- assert.notEqual(returnIndex, -1, 'sanitizeDesktopConnectionConfig must return a sanitized object')
- const returned = body.slice(returnIndex)
- assert.match(returned, /\bsecureTokenStorage\b/, 'the renderer needs the secure-storage availability signal')
- assert.match(returned, /\bremoteTokenPlainText\b/, 'the renderer needs the plain-text token signal')
-})
-
-// #117269: the plain-text signal must be gated on the machine actually being
-// unable to secure the token — an inline encoding check would warn every
-// keychain-opt-out user, whose chosen mode is plain text. The signal flows
-// through resolveRemoteTokenPlainText (behavior tests above); this pins the
-// main-process wiring so the gate cannot be dropped at the call site.
-test('sanitizeDesktopConnectionConfig routes remoteTokenPlainText through the gated helper', () => {
- const source = readMain()
- const fnStart = source.indexOf('async function sanitizeDesktopConnectionConfig(')
- assert.notEqual(fnStart, -1, 'sanitizeDesktopConnectionConfig must exist in main.ts')
- const fnEnd = source.indexOf('\nfunction ', fnStart + 1)
- const body = source.slice(fnStart, fnEnd === -1 ? undefined : fnEnd)
-
- assert.match(
- body,
- /const remoteTokenPlainText = resolveRemoteTokenPlainText\(\{/,
- 'remoteTokenPlainText must be computed by resolveRemoteTokenPlainText (gated on secure storage) (#117269)'
- )
-})
-
-// #95393: connections.save succeeded but the switcher menu (renderer
-// $connectionsRegistry snapshot) never refreshed until reload. The registry
-// push (broadcastConnectionsChanged) fired only on the dial-material-edit
-// branch, so a brand-new connection or a label rename never reached other
-// windows — or the switcher's onChanged re-pull. Mirrors the live repro at
-// /tmp/mg-ab/w2_95393.py: save → menu (no reload) must include the new row.
-test('saveRegistryConnection republishes the registry to renderers on EVERY successful save (#95393)', () => {
- const source = readMain()
- const fnStart = source.indexOf('async function saveRegistryConnection(')
- assert.notEqual(fnStart, -1, 'saveRegistryConnection must exist in main.ts')
- const fnEnd = source.indexOf('\nasync function ', fnStart + 1)
- const body = source.slice(fnStart, fnEnd === -1 ? undefined : fnEnd)
-
- // The dial-material edit branch keeps its dispose+redial semantics…
- assert.match(
- body,
- /broadcastConnectionsChanged\(\{ connectionId: entry\.id, reason: 'updated' \}\)/,
- 'a dial-material edit must still push the dispose+redial signal'
- )
- // …and every OTHER save (new connection, label rename) must still push a
- // registry refresh, or the switcher menu paints stale until reload.
- assert.match(
- body,
- /broadcastConnectionsChanged\(\{ connectionId: entry\.id, reason: 'saved' \}\)/,
- 'a non-dial-material save must republish the registry snapshot (#95393)'
- )
-})
-
// ---------------------------------------------------------------------------
// homeRelativeAttachmentCandidates (#115609)
// ---------------------------------------------------------------------------
diff --git a/apps/desktop/electron/hud-game-overlay.test.ts b/apps/desktop/electron/hud-game-overlay.test.ts
index 262c99e23af..3b8626ee57d 100644
--- a/apps/desktop/electron/hud-game-overlay.test.ts
+++ b/apps/desktop/electron/hud-game-overlay.test.ts
@@ -8,7 +8,6 @@ import {
findFullscreenAppAnywhere,
gameOverlayStateFor,
INACTIVE_GAME_OVERLAY,
- isShellWindow,
startHudGameOverlayWatch
} from './hud-game-overlay'
import type { GameOverlayState } from './hud-game-overlay'
@@ -32,10 +31,6 @@ const desktopShell = win({ app: 'Windows Explorer', bounds: { ...DISPLAY }, id:
// ─── coversDisplay ───────────────────────────────────────────────────────
-test('display-sized bounds cover the display', () => {
- assert.equal(coversDisplay({ ...DISPLAY }, DISPLAY), true)
-})
-
test('DPI rounding and the 1px-oversize trick stay within the epsilon', () => {
assert.equal(coversDisplay({ x: -1, y: -1, width: 2562, height: 1442 }, DISPLAY), true)
assert.equal(coversDisplay({ x: 1, y: 1, width: 2558, height: 1438 }, DISPLAY), true)
@@ -51,16 +46,6 @@ test('a fullscreen window on ANOTHER display does not cover this one', () => {
// ─── isShellWindow ───────────────────────────────────────────────────────
-test('desktop shells are recognized, real apps are not', () => {
- for (const app of ['Windows Explorer', 'explorer.exe', 'Program Manager', 'Finder', 'Dock', 'gnome-shell']) {
- assert.equal(isShellWindow(app), true, app)
- }
-
- for (const app of ['Balatro', 'Explorer of the Deep', 'Firefox', '']) {
- assert.equal(isShellWindow(app), false, app)
- }
-})
-
// ─── detectFullscreenApp ─────────────────────────────────────────────────
test('fullscreen game under the HUD is detected', () => {
@@ -97,10 +82,6 @@ test('a window intersecting only another display does not veto', () => {
assert.equal(detectFullscreenApp([otherDisplayWin, fullscreenGame], SELF_PID, DISPLAY)?.app, 'Balatro')
})
-test('empty desktop: nothing to detect', () => {
- assert.equal(detectFullscreenApp([hudWindow], SELF_PID, DISPLAY), null)
-})
-
test('gameOverlayStateFor maps detection to the pushed state shape', () => {
assert.deepEqual(gameOverlayStateFor([fullscreenGame], SELF_PID, DISPLAY), { active: true, app: 'Balatro' })
assert.deepEqual(gameOverlayStateFor([hudWindow], SELF_PID, DISPLAY), INACTIVE_GAME_OVERLAY)
diff --git a/apps/desktop/electron/hud-geometry.test.ts b/apps/desktop/electron/hud-geometry.test.ts
index 28a8d9c05a1..d9e0b49eeb6 100644
--- a/apps/desktop/electron/hud-geometry.test.ts
+++ b/apps/desktop/electron/hud-geometry.test.ts
@@ -2,15 +2,17 @@ import assert from 'node:assert/strict'
import { test } from 'vitest'
-import { applyHudResetBounds, defaultHudBounds, normalizeHudResizeBounds } from './hud-geometry'
+import { applyHudResetBounds, defaultHudBounds, HUD_HEIGHT, HUD_WIDTH, normalizeHudResizeBounds } from './hud-geometry'
-test('defaultHudBounds restores the standard centered bottom layout', () => {
- assert.deepEqual(defaultHudBounds({ x: 0, y: 25, width: 1440, height: 875 }), {
- x: 410,
- y: 508,
- width: 620,
- height: 320
- })
+test('defaultHudBounds restores the standard size, centered near the bottom of the work area', () => {
+ const area = { x: 0, y: 25, width: 1440, height: 875 }
+ const bounds = defaultHudBounds(area)
+
+ assert.equal(bounds.width, HUD_WIDTH)
+ assert.equal(bounds.height, HUD_HEIGHT)
+ assert.equal(bounds.x! - area.x, area.x + area.width - (bounds.x! + bounds.width))
+ assert.ok(bounds.y! + bounds.height <= area.y + area.height)
+ assert.ok(bounds.y! > area.y + area.height / 2)
})
test('defaultHudBounds fits the default layout to a small work area', () => {
@@ -23,7 +25,7 @@ test('defaultHudBounds fits the default layout to a small work area', () => {
})
test('defaultHudBounds keeps the spawn fallback when no display is available', () => {
- assert.deepEqual(defaultHudBounds(), { x: undefined, y: undefined, width: 620, height: 320 })
+ assert.deepEqual(defaultHudBounds(), { x: undefined, y: undefined, width: HUD_WIDTH, height: HUD_HEIGHT })
})
test('applyHudResetBounds restores the resize lock and reports native failure', () => {
diff --git a/apps/desktop/electron/hud-modifier-native.test.ts b/apps/desktop/electron/hud-modifier-native.test.ts
deleted file mode 100644
index 6f887c334a2..00000000000
--- a/apps/desktop/electron/hud-modifier-native.test.ts
+++ /dev/null
@@ -1,103 +0,0 @@
-import assert from 'node:assert/strict'
-import { execFileSync, spawnSync } from 'node:child_process'
-import { mkdtempSync, rmSync } from 'node:fs'
-import { tmpdir } from 'node:os'
-import { resolve } from 'node:path'
-
-import { test } from 'vitest'
-
-import { HudModifierMonitor, type HudModifierStatus, resolveHudModifierMonitorPath } from './hud-modifier-monitor'
-
-test.skipIf(process.platform !== 'darwin')(
- 'executes native gesture adapters and real controller without posting input',
- async () => {
- const dir = mkdtempSync(resolve(tmpdir(), 'hermes-hud-native-'))
- const native = resolve(import.meta.dirname, 'native')
-
- try {
- const gesture = resolve(dir, 'gesture')
- execFileSync('xcrun', [
- '--sdk',
- 'macosx',
- 'clang',
- '-std=c11',
- '-Wall',
- '-Wextra',
- '-Werror',
- resolve(native, 'hud-modifier-gesture.test.c'),
- '-o',
- gesture
- ])
- assert.match(execFileSync(gesture, [], { encoding: 'utf8', timeout: 5_000 }), /assertions passed/)
- const adapter = resolve(dir, 'adapter')
- execFileSync('xcrun', [
- '--sdk',
- 'macosx',
- 'clang',
- '-fobjc-arc',
- '-fblocks',
- '-Wall',
- '-Wextra',
- '-Werror',
- '-framework',
- 'Cocoa',
- '-framework',
- 'CoreGraphics',
- resolve(native, 'hud-modifier-monitor.test.m'),
- '-o',
- adapter
- ])
- assert.match(execFileSync(adapter, [], { encoding: 'utf8', timeout: 5_000 }), /assertions passed/)
- execFileSync(
- process.execPath,
- [resolve(import.meta.dirname, '../scripts/build-hud-modifier-monitor.mjs'), '--out-dir', resolve(dir, 'dist')],
- { timeout: 60_000 }
- )
- const binary = resolveHudModifierMonitorPath(dir)
- assert.deepEqual(
- execFileSync('xcrun', ['lipo', '-archs', binary], { encoding: 'utf8' }).trim().split(/\s+/).sort(),
- ['arm64', 'x86_64']
- )
- const check = spawnSync(binary, ['--check'], { encoding: 'utf8', timeout: 5_000 })
- assert.equal(check.error, undefined)
- assert.equal(check.stderr, '')
- assert.ok(check.status === 0 || check.status === 2)
- const permission = JSON.parse(check.stdout)
- assert.deepEqual(
- permission,
- check.status === 0 ? { type: 'ready' } : { type: 'error', code: 'permission-required' }
- )
- const invalid = spawnSync(binary, ['--check', '--request-permission'], { encoding: 'utf8', timeout: 5_000 })
- assert.equal(invalid.status, 64)
- assert.deepEqual(JSON.parse(invalid.stdout), { type: 'error', code: 'unavailable' })
- const statuses: HudModifierStatus[] = []
- const monitor = new HudModifierMonitor({ appPath: dir })
-
- try {
- const status = await new Promise<HudModifierStatus>((settle, reject) => {
- const timer = setTimeout(() => reject(new Error('native helper did not settle')), 10_000)
- monitor.start(
- () => {},
- value => {
- statuses.push(value)
-
- if (value.type === 'ready' || value.type === 'error') {
- clearTimeout(timer)
- settle(value)
- }
- }
- )
- })
-
- assert.equal(statuses[0].type, 'starting')
- assert.deepEqual(status, permission)
- console.info(`HUD native check: ${JSON.stringify(status)}; no input posted`)
- } finally {
- monitor.stop()
- }
- } finally {
- rmSync(dir, { recursive: true, force: true })
- }
- },
- 75_000
-)
diff --git a/apps/desktop/electron/managed-ssh-update.test.ts b/apps/desktop/electron/managed-ssh-update.test.ts
index 9f224029316..5650cd9ecdc 100644
--- a/apps/desktop/electron/managed-ssh-update.test.ts
+++ b/apps/desktop/electron/managed-ssh-update.test.ts
@@ -259,27 +259,6 @@ test('update-all deduplicates the same recovery scope and keeps primary preceden
)
})
-test('POSIX managed launcher is detached, correlation-scoped, and never publishes handoff exit 75', () => {
- const command = buildPosixManagedUpdateLaunch(
- {
- ssh: { exec: async () => '' },
- platform: 'Linux',
- hermesPath: '~/.local/bin/hermes',
- hermesHome: '~/.hermes'
- },
- CORRELATION
- )
-
- assert.match(command, /setsid/)
- assert.match(command, /update --yes/)
- assert.doesNotMatch(command, /update --yes --gateway/)
- assert.match(command, new RegExp(`HERMES_UPDATE_CORRELATION_ID=.*${CORRELATION}`))
- assert.match(command, /\[ "\$rc" -ne 75 \]/)
- assert.match(command, new RegExp(`\\.update_exit_code\\.${CORRELATION}`))
- assert.match(command, new RegExp(`\\.update_launch_intent\\.${CORRELATION}`))
- assert.match(command, /while \[ ! -e/)
-})
-
test('POSIX managed launcher executes the updater command and atomically publishes its status', async () => {
const home = await mkdtemp(path.join(os.tmpdir(), 'hermes-managed-launch-'))
diff --git a/apps/desktop/electron/mcp-oauth-callback-ipc.test.ts b/apps/desktop/electron/mcp-oauth-callback-ipc.test.ts
index 8878f936871..b13be2e00d6 100644
--- a/apps/desktop/electron/mcp-oauth-callback-ipc.test.ts
+++ b/apps/desktop/electron/mcp-oauth-callback-ipc.test.ts
@@ -47,7 +47,6 @@ test('listen binds a loopback listener and wait resolves with the redirect param
const res = await fetch(`${redirectUri}?code=abc123&state=st-1`)
assert.equal(res.status, 200)
- assert.match(await res.text(), /return to Hermes/)
const result = await waitPromise
diff --git a/apps/desktop/electron/native-token-store.test.ts b/apps/desktop/electron/native-token-store.test.ts
index 12eff080f9f..9782706305c 100644
--- a/apps/desktop/electron/native-token-store.test.ts
+++ b/apps/desktop/electron/native-token-store.test.ts
@@ -123,23 +123,6 @@ test('the loaded set is accepted by the stored-token parsing boundary', () => {
assert.deepEqual(parseStoredTokenSet(loaded), loaded)
})
-test('the persisted payload is what broke the old reload path (#73271)', () => {
- const first = createFakeDisk()
-
- persistNativeTokenSet(GATEWAY, TOKENS, first.io)
-
- const restarted = createFakeDisk(first.fileText())
- const secret = JSON.parse(restarted.fileText()!)[GATEWAY]
- const decrypted = JSON.parse(restarted.io.decrypt(secret))
-
- // The old code passed exactly this object to parseTokenResponse(). A
- // normalized set has no snake_case access_token, so every launch threw and
- // the user was shown as signed out...
- assert.throws(() => parseTokenResponse(decrypted), /missing access_token/i)
- // ...while the real load path reads the same bytes successfully.
- assert.deepEqual(loadNativeTokenSet(GATEWAY, restarted.io), TOKENS)
-})
-
test('the full login-to-restart sequence keeps the two parser boundaries apart', () => {
// Login: the gateway answers /auth/native/token in snake_case, and only
// parseTokenResponse() understands that shape.
@@ -273,17 +256,6 @@ test('a decrypted blob missing accessToken is rejected, not half-restored', () =
assert.match(disk.logs[0], /missing accessToken/i)
})
-test('a non-Error decryption failure keeps its detail in the log', () => {
- const disk = createFakeDisk(JSON.stringify({ [GATEWAY]: { encoding: 'safeStorage', value: 'AAAA' } }), {
- decrypt: () => {
- throw 'keychain exploded'
- }
- })
-
- assert.equal(loadNativeTokenSet(GATEWAY, disk.io), null)
- assert.match(disk.logs[0], /keychain exploded/)
-})
-
test('an unwritable store file is logged rather than thrown', () => {
const disk = createFakeDisk(null, {
writeStoreText: () => {
@@ -295,19 +267,6 @@ test('an unwritable store file is logged rather than thrown', () => {
assert.match(disk.logs[0], /failed to persist tokens: EACCES/)
})
-test('a non-Error write failure keeps its detail in the log', () => {
- const disk = createFakeDisk(null, {
- writeStoreText: () => {
- throw 'disk went away'
- }
- })
-
- // `(error as Error).message` on a thrown string reads as undefined and loses
- // the only diagnostic there was.
- assert.doesNotThrow(() => persistNativeTokenSet(GATEWAY, TOKENS, disk.io))
- assert.equal(disk.logs[0], '[native-oauth] failed to persist tokens: disk went away')
-})
-
test('an unusable keychain fails the write loudly and writes nothing', () => {
const existing = createFakeDisk()
diff --git a/apps/desktop/electron/native/hud-modifier-gesture.test.c b/apps/desktop/electron/native/hud-modifier-gesture.test.c
deleted file mode 100644
index 08e56068e09..00000000000
--- a/apps/desktop/electron/native/hud-modifier-gesture.test.c
+++ /dev/null
@@ -1,59 +0,0 @@
-#include "hud-modifier-gesture.h"
-#include <assert.h>
-#include <stdio.h>
-
-int main(void) {
- // Either press/release ordering is valid, but neither first release summons.
- for (unsigned first = 1; first <= 2; first++) {
- for (unsigned last = 1; last <= 2; last++) {
- HudModifierGesture s = {0};
- assert(!HudModifierUpdate(&s, first, false, false, 10));
- assert(!HudModifierUpdate(&s, 3, false, false, 20));
- assert(!HudModifierUpdate(&s, last, false, false, 30));
- assert(HudModifierUpdate(&s, 0, false, false, 40));
- assert(!HudModifierUpdate(&s, 0, false, false, 50));
- }
- }
- // A foreign event at any phase permanently cancels this attempt, even if
- // the foreign key/button is released before the target modifiers.
- for (int phase = 0; phase < 3; phase++) {
- HudModifierGesture s = {0};
- HudModifierUpdate(&s, 1, false, phase == 0, 10);
- HudModifierUpdate(&s, 3, false, phase == 1, 20);
- HudModifierUpdate(&s, 2, false, phase == 2, 30);
- assert(!HudModifierUpdate(&s, 0, false, false, 40));
- HudModifierUpdate(&s, 1, false, false, 50);
- HudModifierUpdate(&s, 3, false, false, 60);
- HudModifierUpdate(&s, 2, false, false, 70);
- assert(HudModifierUpdate(&s, 0, false, false, 80));
- }
- // Extra modifiers, held keys/buttons, and partial-release re-press cannot arm.
- for (int kind = 0; kind < 3; kind++) {
- HudModifierGesture s = {0};
- HudModifierUpdate(&s, 1, kind == 1, false, 10);
- HudModifierUpdate(&s, kind == 0 ? 7 : 3, kind == 1, false, 20);
- if (kind == 0) HudModifierUpdate(&s, 3, false, false, 25);
- HudModifierUpdate(&s, 2, false, false, 30);
- if (kind == 2) {
- HudModifierUpdate(&s, 3, false, false, 35);
- HudModifierUpdate(&s, 2, false, false, 36);
- }
- assert(!HudModifierUpdate(&s, 0, false, false, 40));
- }
- for (unsigned initial = 1; initial <= 3; initial++) {
- HudModifierGesture s = {0};
- HudModifierUpdate(&s, initial, true, true, 0);
- HudModifierUpdate(&s, 3, false, false, 10);
- HudModifierUpdate(&s, 2, false, false, 20);
- assert(!HudModifierUpdate(&s, 0, false, false, 30));
- }
- for (uint64_t duration = 500; duration <= 501; duration++) {
- HudModifierGesture s = {0};
- HudModifierUpdate(&s, 1, false, false, 10);
- HudModifierUpdate(&s, 3, false, false, 20);
- HudModifierUpdate(&s, 2, false, false, 30);
- assert(HudModifierUpdate(&s, 0, false, false, 10 + duration) == (duration == 500));
- }
- puts("native modifier gesture assertions passed");
- return 0;
-}
diff --git a/apps/desktop/electron/native/hud-modifier-gesture.test.cs b/apps/desktop/electron/native/hud-modifier-gesture.test.cs
deleted file mode 100644
index 04899a4b55c..00000000000
--- a/apps/desktop/electron/native/hud-modifier-gesture.test.cs
+++ /dev/null
@@ -1,42 +0,0 @@
-using System;
-
-internal static class HudModifierGestureTests
-{
- private static void Check(bool expected, params uint[] modifiers)
- {
- HudModifierGesture gesture = new HudModifierGesture();
- bool summoned = false;
- for (int i = 0; i < modifiers.Length; i++)
- summoned |= gesture.Update(modifiers[i], false, false, i * 30);
- if (summoned != expected) throw new Exception("Unexpected gesture result");
- }
-
- private static void Reject(bool held, bool interrupted, long release)
- {
- HudModifierGesture gesture = new HudModifierGesture();
- gesture.Update(1, false, false, 0);
- gesture.Update(3, held, interrupted, 30);
- gesture.Update(2, false, false, 60);
- if (gesture.Update(0, false, false, release)) throw new Exception("Interrupted/long gesture summoned");
- // A rejected chord cannot poison the next clean tap.
- gesture.Update(2, false, false, 1000);
- gesture.Update(3, false, false, 1030);
- gesture.Update(1, false, false, 1060);
- if (!gesture.Update(0, false, false, 1090)) throw new Exception("Clean retry did not summon");
- }
-
- private static int Main()
- {
- Check(true, 1, 3, 2, 0);
- Check(true, 2, 3, 1, 0);
- Check(false, 1, 0);
- Check(false, 3, 1, 0); // Startup-held chord.
- Check(false, 1, 3, 1, 3, 2, 0); // Re-press during release.
- Check(false, 1, 7, 3, 1, 0); // AltGr, extra modifiers, both Ctrl keys.
- Reject(true, false, 90); // Another key or a held mouse button.
- Reject(false, true, 90); // Repeat, click, wheel, or duplicate transition.
- Reject(false, false, 501);
- Console.WriteLine("gesture contracts passed");
- return 0;
- }
-}
diff --git a/apps/desktop/electron/native/hud-modifier-monitor.test.m b/apps/desktop/electron/native/hud-modifier-monitor.test.m
deleted file mode 100644
index 8538e6d4c8c..00000000000
--- a/apps/desktop/electron/native/hud-modifier-monitor.test.m
+++ /dev/null
@@ -1,61 +0,0 @@
-#define HUD_MODIFIER_MONITOR_TEST 1
-#include "hud-modifier-monitor.m"
-#include <assert.h>
-
-static CGEventFlags command = kCGEventFlagMaskCommand | NX_DEVICELCMDKEYMASK;
-static CGEventFlags option = kCGEventFlagMaskAlternate | NX_DEVICELALTKEYMASK;
-static bool flags(HudMacState *s, CGKeyCode key, CGEventFlags f, uint64_t ms) {
- return HudMacUpdate(s, kCGEventFlagsChanged, key, f, false, 0, ms);
-}
-static void begin(HudMacState *s) {
- assert(!flags(s, 55, command, 10));
- assert(!flags(s, 58, command | option, 20));
-}
-static bool release(HudMacState *s) {
- assert(!flags(s, 55, option, 30));
- return flags(s, 58, 0, 40);
-}
-int main(void) { @autoreleasepool {
- HudMacState s = {0};
- begin(&s);
- assert(release(&s));
- CGEventType interruptions[] = { kCGEventKeyDown, kCGEventKeyUp,
- kCGEventLeftMouseDown, kCGEventLeftMouseUp, kCGEventRightMouseDown,
- kCGEventOtherMouseDown, kCGEventScrollWheel, kCGEventLeftMouseDragged,
- kCGEventRightMouseDragged, kCGEventOtherMouseDragged };
- for (unsigned i = 0; i < sizeof(interruptions) / sizeof(*interruptions); i++) {
- s = (HudMacState){0};
- begin(&s);
- assert(!HudMacUpdate(&s, interruptions[i], 0, command | option, false, 0, 25));
- assert(!release(&s));
- }
- s = (HudMacState){0}; begin(&s);
- assert(!HudMacUpdate(&s, kCGEventKeyDown, 0, command | option, true, 0, 25));
- assert(!release(&s));
- s = (HudMacState){0}; begin(&s);
- assert(!flags(&s, 56, command | option | kCGEventFlagMaskShift, 25));
- assert(!flags(&s, 56, command | option, 26));
- assert(!release(&s));
- s = (HudMacState){0}; begin(&s);
- assert(!flags(&s, 54, command | option | NX_DEVICERCMDKEYMASK, 25));
- assert(!release(&s));
- // Plain pointer movement is harmless; drag/click/wheel was tested above.
- s = (HudMacState){0}; begin(&s);
- assert(!HudMacUpdate(&s, kCGEventMouseMoved, 0, command | option, false, 0, 25));
- assert(release(&s));
- // Snapshots of a held key, mouse, or chord cannot authorize a release.
- s = (HudMacState){0}; s.keys[0] = true; s.heldKeys = 1;
- begin(&s); assert(!release(&s));
- s = (HudMacState){0}; s.buttons = 1;
- begin(&s); assert(!release(&s));
- s = (HudMacState){0};
- HudModifierUpdate(&s.gesture, 3, true, true, 0);
- assert(!release(&s));
- // Two Command keys retain their independent screenshot meaning.
- s = (HudMacState){0};
- assert(!flags(&s, 55, command, 10));
- assert(!flags(&s, 54, command | NX_DEVICERCMDKEYMASK, 20));
- assert(!flags(&s, 54, command, 30));
- assert(!flags(&s, 55, 0, 40));
- puts("native macOS event adapter assertions passed");
-} return 0; }
diff --git a/apps/desktop/electron/native/hud-modifier-windows.test.mjs b/apps/desktop/electron/native/hud-modifier-windows.test.mjs
deleted file mode 100644
index d42155469f1..00000000000
--- a/apps/desktop/electron/native/hud-modifier-windows.test.mjs
+++ /dev/null
@@ -1,87 +0,0 @@
-import assert from 'node:assert/strict'
-import { execFile, spawn } from 'node:child_process'
-import { once } from 'node:events'
-import { mkdtempSync, rmSync } from 'node:fs'
-import { tmpdir } from 'node:os'
-import { join } from 'node:path'
-import { promisify } from 'node:util'
-import { test } from 'node:test'
-import { fileURLToPath } from 'node:url'
-
-import { buildHudModifierMonitor, resolveWindowsFrameworkCompiler } from '../../scripts/build-hud-modifier-monitor.mjs'
-
-// Run on Windows, without a developer compiler on PATH, using the real Node
-// pipe transport. No input is synthesized and no user desktop is controlled.
-test('Windows builds and starts its HUD helper without Clang or a developer SDK', {
- skip: process.platform !== 'win32', timeout: 60_000
-}, async () => {
- const distDir = mkdtempSync(join(tmpdir(), 'hud-windows-'))
- const path = process.env.PATH
- const cc = process.env.CC
- let child
- try {
- process.env.PATH = ''
- process.env.CC = 'hermes-test-no-native-compiler'
- let binary
- try {
- binary = buildHudModifierMonitor({ distDir })
- } finally {
- process.env.PATH = path
- if (cc === undefined) delete process.env.CC
- else process.env.CC = cc
- }
- assert.ok(binary, 'A Windows build must include a working HUD helper, not silently skip it')
- const check = await promisify(execFile)(binary, ['--check'], { timeout: 15_000, windowsHide: true })
- assert.equal(JSON.parse(check.stdout.trim()).type, 'ready')
- child = spawn(binary, [], { windowsHide: true, stdio: ['pipe', 'pipe', 'pipe'] })
- const exited = once(child, 'exit')
- exited.catch(() => {})
- await new Promise((resolve, reject) => {
- let output = ''
- const timer = setTimeout(() => reject(new Error('HUD helper did not become ready')), 15_000)
- child.once('error', error => { clearTimeout(timer); reject(error) })
- child.once('exit', (code, signal) => {
- clearTimeout(timer)
- reject(new Error(`HUD helper exited before readiness: ${code}/${signal}`))
- })
- child.stdout.on('data', chunk => {
- output += chunk.toString()
- if (output.includes('\n')) {
- clearTimeout(timer)
- try {
- assert.equal(JSON.parse(output.trim()).type, 'ready')
- resolve()
- } catch (error) { reject(error) }
- }
- })
- })
- child.stdin.end()
- assert.deepEqual(await exited, [0, null], 'stdin EOF must release the listener and exit')
- } finally {
- if (child?.pid && child.exitCode === null) {
- const closed = once(child, 'close')
- child.kill()
- await closed
- }
- rmSync(distDir, { recursive: true, force: true })
- }
-})
-
-test('Windows gesture rejects ordinary shortcuts and recovers for the next tap', {
- skip: process.platform !== 'win32', timeout: 30_000
-}, async () => {
- const dir = mkdtempSync(join(tmpdir(), 'hud-gesture-'))
- const exe = join(dir, 'gesture.exe')
- const run = promisify(execFile)
- try {
- await run(resolveWindowsFrameworkCompiler(), [
- '/nologo', '/target:exe', '/warnaserror+', `/out:${exe}`,
- fileURLToPath(new URL('./hud-modifier-gesture.cs', import.meta.url)),
- fileURLToPath(new URL('./hud-modifier-gesture.test.cs', import.meta.url))
- ], { windowsHide: true })
- const result = await run(exe, [], { windowsHide: true })
- assert.equal(result.stdout.trim(), 'gesture contracts passed')
- } finally {
- rmSync(dir, { recursive: true, force: true })
- }
-})
diff --git a/apps/desktop/electron/plugin-compat-notice.test.ts b/apps/desktop/electron/plugin-compat-notice.test.ts
index 0387333d816..ff32bd6509e 100644
--- a/apps/desktop/electron/plugin-compat-notice.test.ts
+++ b/apps/desktop/electron/plugin-compat-notice.test.ts
@@ -43,24 +43,6 @@ test('no report file → no notice', () => {
assert.equal(pendingNotice(tmp(), tmp()), null)
})
-test('report → one notice naming the plugins and the date, with no config keys or CLI commands', () => {
- const home = tmp()
- fs.writeFileSync(path.join(home, REPORT_FILE), JSON.stringify(REPORT))
- const n = pendingNotice(home, tmp())
- assert.ok(n)
- assert.equal(n.title, 'Some plugins need an update')
- assert.match(n.message, /stop working on 2026-09-14: alpha, beta\./)
- assert.match(
- n.detail,
- /• alpha — 1 import \(e\.g\. tools\.web_tools\.prefers_gateway → tools\.tool_backend_helpers\.prefers_gateway\)/
- )
- assert.match(n.detail, /• beta — 2 imports/)
-
- for (const text of [n.title, n.message, n.detail]) {
- assert.doesNotMatch(text, /config\.yaml|hermes plugins compat|allow_deprecated_imports|module path/)
- }
-})
-
test('dismissal is remembered for the same report and forgotten for a different one', () => {
const home = tmp()
const userData = tmp()
@@ -82,14 +64,11 @@ test('dismissal is remembered for the same report and forgotten for a different
assert.ok(second)
assert.notEqual(second.key, first.key)
- // the date passing (plugins now disabled) is new information too, with different wording
+ // the date passing (plugins now disabled) is new information too
const disabled = { ...REPORT, in_effect: true }
fs.writeFileSync(path.join(home, REPORT_FILE), JSON.stringify(disabled))
const third = pendingNotice(home, userData)
assert.ok(third)
- assert.equal(third.title, 'Some plugins were turned off')
- assert.match(third.message, /were turned off: alpha, beta\. Hermes works normally without them\./)
- assert.doesNotMatch(third.detail, /config\.yaml|hermes plugins compat|allow_deprecated_imports/)
assert.notEqual(reportKey(disabled as any), reportKey(REPORT as any))
})
diff --git a/apps/desktop/electron/pool-limits.test.ts b/apps/desktop/electron/pool-limits.test.ts
index 5aff45f0883..ca5c6e8b389 100644
--- a/apps/desktop/electron/pool-limits.test.ts
+++ b/apps/desktop/electron/pool-limits.test.ts
@@ -40,7 +40,7 @@ describe('clampPoolLimits', () => {
})
it('clamps absurdly high backend counts', () => {
- expect(clampPoolLimits({ maxBackends: 10_000 }).maxBackends).toBeLessThanOrEqual(64)
+ expect(clampPoolLimits({ maxBackends: 10_000 }).maxBackends).toBe(POOL_LIMITS_BOUNDS.maxBackendsMax)
})
it('clamps idleMs to the shared ceiling (7 days)', () => {
diff --git a/apps/desktop/electron/pool-spawn-coordinator.test.ts b/apps/desktop/electron/pool-spawn-coordinator.test.ts
index 22c7e844b71..121a902c9bc 100644
--- a/apps/desktop/electron/pool-spawn-coordinator.test.ts
+++ b/apps/desktop/electron/pool-spawn-coordinator.test.ts
@@ -1,8 +1,4 @@
import assert from 'node:assert/strict'
-import { spawn } from 'node:child_process'
-import fs from 'node:fs'
-import path from 'node:path'
-import { fileURLToPath } from 'node:url'
import { test } from 'vitest'
@@ -125,54 +121,6 @@ test('a queued start times out with a clear error and frees its queue position',
assert.equal(coordinator.activeCount, 0)
})
-test('100 real child processes never exceed twelve simultaneous local slots', async () => {
- const limit = 12
- const coordinator = new LocalBackendSpawnCoordinator(limit)
- const livePids = new Set<number>()
- let completedChildren = 0
- let maxLive = 0
-
- await Promise.all(
- Array.from({ length: 100 }, async (_, index) => {
- const release = await coordinator.acquire(`real-profile-${index}`)
-
- try {
- const child = spawn(process.execPath, ['-e', 'setTimeout(() => {}, 40)'], {
- stdio: 'ignore'
- })
-
- assert.ok(child.pid)
- livePids.add(child.pid)
- maxLive = Math.max(maxLive, livePids.size)
-
- await new Promise<void>((resolve, reject) => {
- child.once('error', reject)
- child.once('exit', code => {
- if (code === 0) {
- resolve()
- } else {
- reject(new Error(`child ${child.pid} exited with ${code}`))
- }
- })
- })
-
- completedChildren += 1
- livePids.delete(child.pid)
- } finally {
- release()
- }
- })
- )
-
- // Windows may recycle a PID after a short-lived child exits; completion
- // count, not PID uniqueness, is the invariant this concurrency test owns.
- assert.equal(completedChildren, 100)
- assert.equal(maxLive, limit)
- assert.equal(livePids.size, 0)
- assert.equal(coordinator.activeCount, 0)
- assert.equal(coordinator.queuedCount, 0)
-})
-
test('failed start keeps its slot until the child has actually exited', async () => {
const coordinator = new LocalBackendSpawnCoordinator(1)
const childExit = deferred()
@@ -517,43 +465,3 @@ test('promoting a queued background waiter lets it take the reserved foreground
bg2()
assert.equal(coordinator.activeCount, 0)
})
-
-// ── main.ts wiring ──────────────────────────────────────────────────────────
-// The coordinator is only as good as the timeout main.ts hands it. A queued
-// ticket that outlives the renderer's backend-boot budget holds the pool key
-// hostage: the renderer has already reported "backend didn't come up", and
-// every later click on that profile joins the stale wait instead of failing
-// fast with a reason.
-{
- const here = path.dirname(fileURLToPath(import.meta.url))
- const mainSource = fs.readFileSync(path.join(here, 'main.ts'), 'utf8').replace(/\r\n/g, '\n')
-
- const withTimeoutSource = fs
- .readFileSync(path.join(here, '..', 'src', 'lib', 'with-timeout.ts'), 'utf8')
- .replace(/\r\n/g, '\n')
-
- test('main.ts bounds the slot wait below the renderer backend-boot budget', () => {
- const slotWait = Number(/const POOL_SLOT_WAIT_MS = ([\d_]+)/.exec(mainSource)?.[1]?.replace(/_/g, ''))
-
- const bootBudget = Number(
- /export const BACKEND_BOOT_WAIT_TIMEOUT_MS = ([\d_]+)/.exec(withTimeoutSource)?.[1]?.replace(/_/g, '')
- )
-
- assert.ok(Number.isFinite(slotWait) && slotWait > 0, 'POOL_SLOT_WAIT_MS must be a literal in main.ts')
- assert.ok(Number.isFinite(bootBudget), 'BACKEND_BOOT_WAIT_TIMEOUT_MS must be a literal')
- assert.ok(slotWait < bootBudget, `slot wait ${slotWait}ms must be below the boot budget ${bootBudget}ms`)
- assert.match(
- mainSource,
- /localBackendSpawnCoordinator\.request\(poolKey, \{\s*timeoutMs: POOL_SLOT_WAIT_MS,\s*priority: spawnPriority\s*\}\)/
- )
- assert.doesNotMatch(mainSource, /request\(poolKey, \{ timeoutMs: POOL_IDLE_MS \}\)/)
- })
-
- test('main.ts pushes the live pool max into the coordinator when the preference changes', () => {
- // Pool sizing is a live device preference (#92581); the hard cap must
- // follow it, otherwise raising the max in Settings would leave spawns
- // queued behind the launch-time value.
- assert.match(mainSource, /new LocalBackendSpawnCoordinator\(poolLimits\.maxBackends\)/)
- assert.match(mainSource, /localBackendSpawnCoordinator\.setLimit\(poolLimits\.maxBackends\)/)
- })
-}
diff --git a/apps/desktop/electron/power-resume-remote-revalidation.test.ts b/apps/desktop/electron/power-resume-remote-revalidation.test.ts
index 7da53d4cc11..661aec9b0bb 100644
--- a/apps/desktop/electron/power-resume-remote-revalidation.test.ts
+++ b/apps/desktop/electron/power-resume-remote-revalidation.test.ts
@@ -1,7 +1,3 @@
-import fs from 'node:fs'
-import path from 'node:path'
-import { fileURLToPath } from 'node:url'
-
import { describe, expect, it, vi } from 'vitest'
import {
@@ -11,9 +7,6 @@ import {
revalidateSuspectPooledRemoteBackends
} from './remote-liveness'
-const here = path.dirname(fileURLToPath(import.meta.url))
-const mainSource = fs.readFileSync(path.join(here, 'main.ts'), 'utf8').replace(/\r\n/g, '\n')
-
describe('revalidateSuspectPooledRemoteBackends (#93910)', () => {
const descriptor = (baseUrl: string) => ({ baseUrl, mode: 'remote' })
@@ -258,38 +251,3 @@ describe('attachPowerResumeRemoteRevalidation (#93910)', () => {
expect(revalidate).toHaveBeenCalledTimes(2)
})
})
-
-describe('main.ts wiring for #93910', () => {
- it('registers the suspect-pool revalidation on powerMonitor resume/unlock', () => {
- const fnStart = mainSource.indexOf('function registerPowerResumeListeners()')
- expect(fnStart).toBeGreaterThan(-1)
- const body = mainSource.slice(fnStart, mainSource.indexOf('\nfunction ', fnStart + 1))
-
- expect(body).toContain('attachPowerResumeRemoteRevalidation(')
- expect(body).toContain('revalidateSuspectPoolAfterResume()')
- })
-
- it('drives suspect revalidation through the shared coordinator, teardown and claimed re-dial primitives', () => {
- const fnStart = mainSource.indexOf('function revalidateSuspectPoolAfterResume()')
- expect(fnStart).toBeGreaterThan(-1)
- const body = mainSource.slice(fnStart, fnStart + 2_500)
-
- expect(body).toContain('remoteRevalidation.run(')
- expect(body).toContain('revalidateSuspectPooledRemoteBackends({')
- expect(body).toContain('stopPoolBackend(')
- expect(body).toContain('sshBootstrapCoordinator.cancelAndWait(')
- expect(body).toContain('teardownSshConnection(')
- expect(body).toContain('redialPoolBackendAfterResume')
- expect(body).toContain('tracker: remoteLiveness')
- })
-
- it('re-dials a retired pool key through the single-owner dial claim', () => {
- const fnStart = mainSource.indexOf('function redialPoolBackendAfterResume(')
- expect(fnStart).toBeGreaterThan(-1)
- const body = mainSource.slice(fnStart, fnStart + 1_200)
-
- expect(body).toContain('parseBackendScopeKey(')
- expect(body).toContain('backendDialClaims.run(')
- expect(body).toContain('ensureRegistryBackend(')
- })
-})
diff --git a/apps/desktop/electron/power-save.test.ts b/apps/desktop/electron/power-save.test.ts
index 97725e0ed01..52e797e0209 100644
--- a/apps/desktop/electron/power-save.test.ts
+++ b/apps/desktop/electron/power-save.test.ts
@@ -48,11 +48,4 @@ describe('createKeepAwake', () => {
expect(blocker.start).toHaveBeenCalledTimes(2)
expect(keepAwake.isActive()).toBe(true)
})
-
- it('honors a custom blocker type', () => {
- const { blocker } = fakeBlocker()
- createKeepAwake(blocker, 'prevent-display-sleep').set(true)
-
- expect(blocker.start).toHaveBeenCalledWith('prevent-display-sleep')
- })
})
diff --git a/apps/desktop/electron/profile-delete-routing.test.ts b/apps/desktop/electron/profile-delete-routing.test.ts
index a63e864bc96..2ef4720e318 100644
--- a/apps/desktop/electron/profile-delete-routing.test.ts
+++ b/apps/desktop/electron/profile-delete-routing.test.ts
@@ -85,10 +85,6 @@ test('resolveRouteProfile passes the requested profile through when nothing was
assert.equal(resolveRouteProfile(null, 'other-profile'), 'other-profile')
})
-test('resolveRouteProfile passes through undefined when nothing was torn down and no profile was requested', () => {
- assert.equal(resolveRouteProfile(null, undefined), undefined)
-})
-
// ---------------------------------------------------------------------------
// ProfileDeletionGate / localProfilePoolKeys
// ---------------------------------------------------------------------------
diff --git a/apps/desktop/electron/profile-session-routing.test.ts b/apps/desktop/electron/profile-session-routing.test.ts
index 7cf49c76bd5..06ec8f158f1 100644
--- a/apps/desktop/electron/profile-session-routing.test.ts
+++ b/apps/desktop/electron/profile-session-routing.test.ts
@@ -42,7 +42,7 @@ test('remote sidebar slices preserve the explicit all-profiles scope', () => {
)
})
-test('remote sidebar slices fall back to the all-profiles scope and default limits', () => {
+test('remote sidebar slices fall back to the all-profiles scope', () => {
for (const searchParams of [new URLSearchParams(), new URLSearchParams({ recents_profile: ' ' })]) {
const slices = buildSidebarSessionSliceParams(searchParams)
@@ -50,9 +50,6 @@ test('remote sidebar slices fall back to the all-profiles scope and default limi
Object.values(slices).map(params => params.get('profile')),
['all', 'all', 'all']
)
- assert.equal(slices.recents.get('limit'), '20')
- assert.equal(slices.cron.get('limit'), '50')
- assert.equal(slices.messaging.get('limit'), '100')
}
})
diff --git a/apps/desktop/electron/quit-guard.test.ts b/apps/desktop/electron/quit-guard.test.ts
index 8888f99b40f..fdef3c5b051 100644
--- a/apps/desktop/electron/quit-guard.test.ts
+++ b/apps/desktop/electron/quit-guard.test.ts
@@ -38,7 +38,6 @@ test('quitPromptFor names the running chats', () => {
const prompt = quitPromptFor({ count: 2, titles: ['Fix login', 'Ship docs'] }, false)
assert.ok(prompt)
- assert.equal(prompt.message, 'Hermes is still working on 2 chats.')
assert.ok(prompt.detail.includes('• Fix login'))
assert.ok(prompt.detail.includes('• Ship docs'))
})
@@ -47,16 +46,7 @@ test('quitPromptFor summarizes past the list cap and counts untitled work', () =
const prompt = quitPromptFor({ count: 9, titles: ['a', 'b', 'c', 'd', 'e', 'f'] }, false)
assert.ok(prompt)
- assert.equal(prompt.message, 'Hermes is still working on 9 chats.')
assert.ok(prompt.detail.includes('• d'))
assert.ok(!prompt.detail.includes('• e'))
assert.ok(prompt.detail.includes('• 5 more'))
})
-
-test('quitPromptFor speaks singular for one chat', () => {
- const prompt = quitPromptFor({ count: 1, titles: [] }, false)
-
- assert.ok(prompt)
- assert.equal(prompt.message, 'Hermes is still working on 1 chat.')
- assert.ok(prompt.detail.includes('mid-turn'))
-})
diff --git a/apps/desktop/electron/registry-primary-profile-scope.test.ts b/apps/desktop/electron/registry-primary-profile-scope.test.ts
deleted file mode 100644
index 36d60077c2d..00000000000
--- a/apps/desktop/electron/registry-primary-profile-scope.test.ts
+++ /dev/null
@@ -1,37 +0,0 @@
-import fs from 'node:fs'
-import path from 'node:path'
-import { fileURLToPath } from 'node:url'
-
-import { describe, expect, it } from 'vitest'
-
-import { pathForRegistryBackendRequest } from './connection-config'
-
-const here = path.dirname(fileURLToPath(import.meta.url))
-const mainSource = fs.readFileSync(path.join(here, 'main.ts'), 'utf8').replace(/\r\n/g, '\n')
-
-describe('primary-remote descriptor reuse keeps profile scope', () => {
- it('scopes a shared-remote request with ?profile=<profile>', () => {
- expect(pathForRegistryBackendRequest('/api/skills', 'acme', { sharedRemote: true })).toBe(
- '/api/skills?profile=acme'
- )
- })
-
- it('does not add a profile query when the backend is not shared-remote', () => {
- // An isolated backend owns one profile; the router must not invent a scope.
- expect(pathForRegistryBackendRequest('/api/skills', 'acme', { sharedRemote: false, remoteProfile: null })).toBe(
- '/api/skills'
- )
- })
-
- it('marks the reused primary-remote descriptor sharedRemote so the router scopes it', () => {
- const branchStart = mainSource.indexOf("if (id === registry.primary && source.kind !== 'local'")
- expect(branchStart).toBeGreaterThan(-1)
- const branch = mainSource.slice(branchStart, branchStart + 800)
-
- // The reuse branch must decorate the ambient primary descriptor with
- // sharedRemote: true, matching the explicit shared-remote connection path.
- expect(branch).toContain('const primaryDescriptor = await ensureBackend(profile, { passive })')
- expect(branch).toContain('registrySourceOwnsPrimaryBackend(registry, id, primaryDescriptor)')
- expect(branch).toContain('sharedRemote: true')
- })
-})
diff --git a/apps/desktop/electron/remote-lifecycle.test.ts b/apps/desktop/electron/remote-lifecycle.test.ts
index 9a8c0ba87c3..3c39f1becd2 100644
--- a/apps/desktop/electron/remote-lifecycle.test.ts
+++ b/apps/desktop/electron/remote-lifecycle.test.ts
@@ -829,54 +829,6 @@ test('buildSpawnCommand is headless serve, detached, token not in argv', () => {
assert.ok(!cmd.includes('HERMES_DASHBOARD_SESSION_TOKEN'), 'token env var must not appear')
})
-test('buildSpawnCommand always uses serve (legacy dashboard path removed)', () => {
- const cmd = buildSpawnCommand('/x/hermes', 'work', { logPath: spawnLogPath(OWNERSHIP_ID, SPAWN_NONCE) })
- assert.match(cmd, /serve --isolated/)
- assert.match(cmd, /--host 127\.0\.0\.1 --port 0/)
- assert.doesNotMatch(cmd, /dashboard/)
- assert.doesNotMatch(cmd, /--skip-build/)
- assert.match(cmd, /setsid/)
-})
-
-test('buildSpawnCommand atomically reserves the ownership slot through spawn and lock publication', () => {
- const cmd = buildSpawnCommand('/x/hermes', 'work', {
- hermesHome: '~/.hermes',
- logPath: spawnLogPath(OWNERSHIP_ID, SPAWN_NONCE),
- ownershipId: OWNERSHIP_ID,
- reservationNonce: SPAWN_NONCE,
- spawnNonce: SPAWN_NONCE,
- tokenFilePath: spawnTokenPath(OWNERSHIP_ID, SPAWN_NONCE),
- lockMetadata: {
- ownershipId: OWNERSHIP_ID,
- spawnNonce: SPAWN_NONCE,
- port: 0,
- profile: 'work',
- hermesPath: '/x/hermes',
- hermesHome: '~/.hermes',
- logPath: spawnLogPath(OWNERSHIP_ID, SPAWN_NONCE),
- tokenFingerprint: fingerprintToken('stored-token'),
- protocolVersion: PROTOCOL_VERSION,
- startedAt: '2026-07-14T00:00:00.000Z'
- }
- })
-
- assert.ok(cmd.includes('.connect.lock'))
- assert.ok(cmd.includes('.hermes-update-in-progress.mutex'))
- assert.match(cmd, /fcntl\.flock\(fd,fcntl\.LOCK_EX\)/)
- assert.match(cmd, /os\.O_CLOEXEC/)
- assert.match(
- cmd,
- /subprocess\.run\(\["sh","-c",payload,"hermes-update-mutex",str\(fd\)\],pass_fds=\(fd,\),check=False\)/
- )
- assert.doesNotMatch(cmd, /os\.set_inheritable\(fd,True\)/)
- assert.match(cmd, /hermes-update-child "\$1"/)
- assert.match(cmd, /eval "exec \$1>&-"/)
- assert.ok(cmd.includes('backend.lock.json'))
- assert.match(cmd, /lock_json/)
- assert.match(cmd, /trap .*rm -rf/)
- assert.ok(cmd.indexOf('lock_json') > cmd.indexOf('serve --isolated'))
-})
-
test.skipIf(process.platform === 'win32')('detached backend does not inherit the update mutex descriptor', async () => {
const directory = await mkdtemp(path.join(os.tmpdir(), 'hermes-update-mutex-'))
const hermesPath = path.join(directory, 'hermes')
@@ -946,20 +898,6 @@ test('spawnRemoteDashboard returns exact ownership artifacts', async () => {
assert.equal(logPath, spawnLogPath(OWNERSHIP_ID, spawnNonce))
})
-test('spawnRemoteDashboard always spawns serve (legacy dashboard path removed)', async () => {
- const ssh = fakeSsh([
- [/grep -q ssh-session-token-file/, 'YES\n'],
- [/python3 -c/, ''],
- [/printf '%s\\n'/, ''],
- [/setsid|nohup/, '4242\n']
- ])
-
- await spawnRemoteDashboard(ssh, { hermesPath: '/x/hermes', profile: '', token: 'tk', ownershipId: OWNERSHIP_ID })
- const spawn = ssh.calls.find(c => /setsid|nohup/.test(c))
- assert.match(spawn, /serve --isolated/)
- assert.doesNotMatch(spawn, /\bdashboard\b/)
-})
-
test('READY_RE accepts both serve and dashboard sentinels', () => {
assert.equal(READY_RE.exec('HERMES_BACKEND_READY port=4321')?.[1], '4321')
assert.equal(READY_RE.exec('HERMES_DASHBOARD_READY port=8765')?.[1], '8765')
@@ -1322,7 +1260,7 @@ test('managed update drain rechecks the POSIX ownership record before signalling
)
})
-test('managed update drain refuses Darwin termination because PID signals cannot be atomically bound', async () => {
+test('managed update drain never falls back to a bare kill when the identity-bound signal is refused', async () => {
const lock = ownedLock()
const rawLock = JSON.stringify(lock)
@@ -1340,12 +1278,6 @@ test('managed update drain refuses Darwin termination because PID signals cannot
false,
'the final signal must stay inside the identity-checking helper'
)
- const termination = ssh.calls.find(command => command.includes('identity_before_signal'))
- const darwinStart = termination.indexOf('if (sys.platform=="darwin"):')
- const darwinEnd = termination.indexOf('\n try:', darwinStart)
- const darwinGuard = termination.slice(darwinStart, darwinEnd)
- assert.match(darwinGuard, /DARWIN_UNAVAILABLE/)
- assert.doesNotMatch(darwinGuard, /os\.kill\(pid,signal\.SIGTERM\)/)
})
test('connect() respawns when the dashboard is wedged (alive pid, probe fails)', async () => {
@@ -1495,12 +1427,6 @@ test('expandRemotePath preserves spaces as data', () => {
assert.ok(result.includes('my project'), 'spaces must be preserved, not split')
})
-test('buildSpawnCommand does not embed the token in the command string', () => {
- const cmd = buildSpawnCommand('/x/hermes', 'work', { logPath: spawnLogPath(OWNERSHIP_ID, SPAWN_NONCE) })
- assert.ok(!cmd.includes('super_secret_token_value'), 'token must not appear in the spawn command')
- assert.ok(!cmd.includes('HERMES_DASHBOARD_SESSION_TOKEN'), 'env var name must not appear')
-})
-
test('buildSpawnCommand includes --ssh-session-token-file when tokenFilePath is provided', () => {
const cmd = buildSpawnCommand('/x/hermes', 'work', {
tokenFilePath: `~/.hermes/desktop-ssh/${OWNERSHIP_ID}/${SPAWN_NONCE}.token`,
@@ -1512,81 +1438,6 @@ test('buildSpawnCommand includes --ssh-session-token-file when tokenFilePath is
assert.match(cmd, /\.hermes\/desktop-ssh\//)
})
-test('buildSpawnCommand always uses serve, never dashboard', () => {
- const cmd = buildSpawnCommand('/x/hermes', '', { logPath: spawnLogPath(OWNERSHIP_ID, SPAWN_NONCE) })
- assert.match(cmd, /serve --isolated/)
- assert.doesNotMatch(cmd, /\bdashboard\b/)
- assert.doesNotMatch(cmd, /--skip-build/)
- assert.doesNotMatch(cmd, /--no-open/)
-})
-
-test('buildSpawnCommand raises the SSH child file limit before execing Hermes', () => {
- const cmd = buildSpawnCommand('/x/hermes', '', { logPath: spawnLogPath(OWNERSHIP_ID, SPAWN_NONCE) })
- assert.match(cmd, /ulimit -n 65536 2>\/dev\/null \|\| true; exec env HERMES_DESKTOP=1/)
- assert.ok(cmd.indexOf('ulimit -n 65536') < cmd.indexOf('serve --isolated'))
-})
-
-test('buildSpawnCommand payload variables keep $HOME expandable (no double quoting)', () => {
- const cmd = buildSpawnCommand('/x/hermes', 'work', {
- hermesHome: '~/.hermes',
- logPath: spawnLogPath(OWNERSHIP_ID, SPAWN_NONCE),
- ownershipId: OWNERSHIP_ID,
- reservationNonce: SPAWN_NONCE,
- spawnNonce: SPAWN_NONCE,
- tokenFilePath: spawnTokenPath(OWNERSHIP_ID, SPAWN_NONCE),
- lockMetadata: { ownershipId: OWNERSHIP_ID, spawnNonce: SPAWN_NONCE }
- })
-
- // expandRemotePath() emits "$HOME"'/…' — a fragment the shell expands at
- // assignment. Wrapping it in shq() again stores the quote characters in
- // the variable, so mkdir "$reservation" creates (or fails on) a literal
- // "$HOME" path and the reservation loop spins forever holding the mutex.
- for (const name of ['reservation', 'lock', 'owner_file']) {
- assert.match(cmd, new RegExp(`${name}="\\$HOME"`), `${name}= must start with an expandable "$HOME"`)
- assert.doesNotMatch(cmd, new RegExp(`${name}='`), `${name}= must not be re-quoted`)
- }
-})
-
-test('buildSpawnCommand lockfile publication is POSIX sh (no bash substitution)', () => {
- const cmd = buildSpawnCommand('/x/hermes', 'work', {
- hermesHome: '~/.hermes',
- logPath: spawnLogPath(OWNERSHIP_ID, SPAWN_NONCE),
- ownershipId: OWNERSHIP_ID,
- reservationNonce: SPAWN_NONCE,
- spawnNonce: SPAWN_NONCE,
- tokenFilePath: spawnTokenPath(OWNERSHIP_ID, SPAWN_NONCE),
- lockMetadata: { ownershipId: OWNERSHIP_ID, pid: '__PID__' }
- })
-
- // ${var//pat/rep} is bash-only; dash aborts the payload on it AFTER the
- // serve was spawned, so the client sees an unknown failure, deletes the
- // token file, and orphans the backend.
- assert.doesNotMatch(cmd, /\$\{lock_json\/\//, 'must not use ${var//} substitution under sh')
- assert.ok(cmd.includes('sed "s/__PID__/${child}/"'), 'pid substitution must use sed')
-})
-
-test('buildSpawnCommand scopes umask 077 to the mkdir subshell (no leak into serve)', () => {
- const cmd = buildSpawnCommand('/x/hermes', 'work', {
- hermesHome: '~/.hermes',
- logPath: spawnLogPath(OWNERSHIP_ID, SPAWN_NONCE),
- ownershipId: OWNERSHIP_ID,
- reservationNonce: SPAWN_NONCE,
- spawnNonce: SPAWN_NONCE,
- tokenFilePath: spawnTokenPath(OWNERSHIP_ID, SPAWN_NONCE),
- lockMetadata: { ownershipId: OWNERSHIP_ID, pid: '__PID__' }
- })
-
- // umask 077 must apply only to the reservation-parent mkdir. A bare
- // umask call at the top level leaks 077 into the rest of the payload,
- // so the detached setsid backend inherits 077 instead of the login umask.
- assert.ok(cmd.includes('(umask 077 && mkdir -p'), 'umask 077 must be scoped to a mkdir subshell')
- assert.doesNotMatch(cmd, /(^|[^(])umask 077/, 'no bare umask 077 may leak into the spawn chain')
- assert.ok(
- cmd.indexOf('(umask 077') < cmd.indexOf('serve --isolated'),
- 'scoped mkdir must still precede the serve spawn'
- )
-})
-
test('spawnRemoteDashboard removes a token file when upload reporting fails', async () => {
const failure = new Error('channel closed')
diff --git a/apps/desktop/electron/remote-reauth-latch.test.ts b/apps/desktop/electron/remote-reauth-latch.test.ts
index 262e4b9978c..b6919a0ec21 100644
--- a/apps/desktop/electron/remote-reauth-latch.test.ts
+++ b/apps/desktop/electron/remote-reauth-latch.test.ts
@@ -24,7 +24,6 @@ import { httpStatusError } from './api-transport'
import { isReauthRequiredError } from './backend-health'
import { isRetryableRemoteBootFailure, shouldLatchRemoteReauthFailure } from './backend-start-failure'
import { gatewayTicketFailure, isGatewayAuthRejection, withTransientRetries } from './connection-config'
-import { shouldRotateNativeTokenAfterRejection } from './native-auth-decisions'
// --- composition: the real modules, in production order ------------------
@@ -70,31 +69,3 @@ test('FIX #95701: a native-bearer 401 is a confirmed, non-retryable reauth rejec
'the boot progress must be non-retryable so the renderer never re-drives the boot'
)
})
-
-test('FIX #95701: the pre-fix error shape is exactly what made the rejection look transient', async () => {
- // A "401: ..." message with no structured statusCode — what fetchJson used
- // to throw. Every classifier below is shape-based on purpose, so this is
- // the regression the structured error prevents.
- const anonymous = new Error('401: {"error":"session_expired"}')
-
- assert.equal(isGatewayAuthRejection(anonymous), false)
- assert.equal(shouldRotateNativeTokenAfterRejection(anonymous), false)
-
- let attempts = 0
-
- await withTransientRetries(
- async () => {
- attempts += 1
- throw anonymous
- },
- { attempts: 3, sleep: async () => {} }
- ).catch(() => undefined)
-
- assert.equal(attempts, 3, 'an anonymous 401 was retried like a transport blip')
-
- const wrapped = gatewayTicketFailure(anonymous, 'auth copy', 'transport copy')
-
- assert.equal(wrapped.message, 'transport copy')
- assert.equal(isReauthRequiredError(wrapped), false)
- assert.equal(isRetryableRemoteBootFailure({ attemptedRemote: true, isReauth: isReauthRequiredError(wrapped) }), true)
-})
diff --git a/apps/desktop/electron/renderer-bundle.test.ts b/apps/desktop/electron/renderer-bundle.test.ts
index 827d6418873..b4c763a1b46 100644
--- a/apps/desktop/electron/renderer-bundle.test.ts
+++ b/apps/desktop/electron/renderer-bundle.test.ts
@@ -95,15 +95,6 @@ test('missingRendererAssets: torn generation names the dangling chunk', () => {
assert.deepEqual(missingRendererAssets(INDEX_PATH, deps), ['/assets/shiki-block-COiz1pEN.js'])
})
-test('missingRendererAssets: a fully torn copy lists every referenced module', () => {
- const deps = depsFor(INDEX_DIR, INDEX_HTML, [])
-
- assert.deepEqual(missingRendererAssets(INDEX_PATH, deps), [
- '/assets/index-a1b2c3.js',
- '/assets/shiki-block-COiz1pEN.js'
- ])
-})
-
test('missingRendererAssets: existence is checked relative to the index dir, per copy', () => {
// The same module name present next to one index but not the other is how a
// split app.asar vs app.asar.unpacked package presents: one copy is intact,
@@ -133,12 +124,6 @@ test('missingRendererAssets: an unreadable index is not treated as torn', () =>
assert.deepEqual(missingRendererAssets(INDEX_PATH, deps), [])
})
-test('missingRendererAssets: an index naming nothing checkable is not torn', () => {
- const deps = depsFor(INDEX_DIR, '<html><body>static shell, no modules</body></html>', [])
-
- assert.deepEqual(missingRendererAssets(INDEX_PATH, deps), [])
-})
-
// ---------------------------------------------------------------------------
// Lazy-chunk (__vite__mapDeps) awareness — #93479. index.html only names the
// boot-critical modules; the chunks behind React.lazy() routes (syntax-diff-*,
@@ -237,22 +222,3 @@ test('missingRendererAssets: walks transitive map-deps without looping on cycles
assert.deepEqual(missingRendererAssets(INDEX_PATH, deps), ['assets/level-two-bbb.js'])
})
-
-test('missingRendererAssets: a lazy-chunk-torn copy loses to an intact copy end to end', () => {
- // The resolver contract: the same generation check that orders app.asar vs
- // app.asar.unpacked must now see lazy-chunk tears too, so a torn candidate
- // is skipped instead of shipping a delayed "Failed to fetch dynamically
- // imported module" crash.
- const files = {
- 'index.html': GRAPH_INDEX_HTML,
- 'assets/index-a1b2c3.js': ENTRY_JS,
- 'assets/shiki-block-COiz1pEN.js': '// present',
- 'assets/mermaid-embed-Cq7Xw2aa.js': '// present'
- }
-
- const torn = graphDepsFor(INDEX_DIR, files)
- const intact = graphDepsFor(INDEX_DIR, { ...files, 'assets/syntax-diff-Bo0962zh.js': '// present' })
-
- assert.notDeepEqual(missingRendererAssets(INDEX_PATH, torn), [])
- assert.deepEqual(missingRendererAssets(INDEX_PATH, intact), [])
-})
diff --git a/apps/desktop/electron/renderer-load-error-page.test.ts b/apps/desktop/electron/renderer-load-error-page.test.ts
index 93d3f297045..e2b60113458 100644
--- a/apps/desktop/electron/renderer-load-error-page.test.ts
+++ b/apps/desktop/electron/renderer-load-error-page.test.ts
@@ -12,13 +12,11 @@ test('error page names the failure and carries a Reload button', () => {
repairHint: 'hermes desktop --force-build'
})
- assert.match(html, /Hermes couldn.t start the desktop UI/)
assert.match(html, /incomplete after the last update \(2 missing file\(s\)\)/)
assert.match(html, /-6/)
assert.match(html, /assets\/app-C0ffee\.js/)
assert.match(html, /assets\/shiki-block-DeadBeef\.js/)
assert.match(html, /hermes desktop --force-build/)
- assert.match(html, /Reload/)
assert.match(html, /location\.reload\(\)/)
})
@@ -61,23 +59,6 @@ test('reloadUrl cannot break out of the inline script block', () => {
assert.match(html, /\\u003cscript\\u003ealert/)
})
-test('a custom title overrides the default heading', () => {
- const html = buildRendererLoadErrorPage({
- title: 'Hermes desktop UI was terminated',
- errorDescription: 'The UI process was terminated unexpectedly (reason: killed).'
- })
-
- assert.match(html, /Hermes desktop UI was terminated/)
- assert.doesNotMatch(html, /Hermes couldn.t start the desktop UI/)
-})
-
-test('error page renders without any details', () => {
- const html = buildRendererLoadErrorPage()
-
- assert.match(html, /The desktop renderer failed to load\./)
- assert.match(html, /Reload/)
-})
-
test('loadRendererLoadErrorPage loads a data: URL and swallows loadURL rejections', async () => {
const loads: string[] = []
diff --git a/apps/desktop/electron/renderer-log.test.ts b/apps/desktop/electron/renderer-log.test.ts
index a02caccf01d..51400202273 100644
--- a/apps/desktop/electron/renderer-log.test.ts
+++ b/apps/desktop/electron/renderer-log.test.ts
@@ -68,11 +68,4 @@ describe('formatRendererBoundaryReport', () => {
expect(report).toContain('[renderer crash:unknown] [error-boundary:unknown]')
expect(report.length).toBeLessThan(7_000)
})
-
- it('omits the stack block when there is no component stack', () => {
- const report = formatRendererBoundaryReport('main', 'root', 'boom', '')
-
- expect(report).toBe('[renderer crash:main] [error-boundary:root] boom')
- expect(report).not.toContain('\n')
- })
})
diff --git a/apps/desktop/electron/select-runnable-binary.test.ts b/apps/desktop/electron/select-runnable-binary.test.ts
index cdc0df32027..14f27439fb7 100644
--- a/apps/desktop/electron/select-runnable-binary.test.ts
+++ b/apps/desktop/electron/select-runnable-binary.test.ts
@@ -63,7 +63,7 @@ test.each([
// bare `errno: -86` with no `code` — "spawn Unknown system error -86".
name: 'EBADARCH via errno -86 names the binary and the CPU-type cause',
error: { errno: -86, syscall: 'spawn', message: 'spawn Unknown system error -86' },
- expected: /Git on this computer cannot run \(\/usr\/local\/bin\/git: Bad CPU type in executable\)/
+ expected: /\/usr\/local\/bin\/git.*Bad CPU type/
},
{
name: 'ENOENT reads as a missing binary',
diff --git a/apps/desktop/electron/ssh-connection.test.ts b/apps/desktop/electron/ssh-connection.test.ts
index fe277e9b73b..3a05901045e 100644
--- a/apps/desktop/electron/ssh-connection.test.ts
+++ b/apps/desktop/electron/ssh-connection.test.ts
@@ -24,7 +24,6 @@ import {
runSsh,
SSH_ERROR,
SshConnection,
- sshErrorMessage,
stopTunnelChild,
target,
validateSshTarget,
@@ -210,12 +209,6 @@ test('classifySshError detects unreachable', () => {
assert.equal(classifySshError('connect to host x port 22: Connection refused'), SSH_ERROR.UNREACHABLE)
})
-test('sshErrorMessage gives actionable guidance for auth and host-key-change', () => {
- const conn = { user: 'me', host: 'box', port: 22 }
- assert.match(sshErrorMessage(SSH_ERROR.AUTH_FAILED, conn, 'Permission denied'), /ssh-agent|ssh-add|IdentityFile/)
- assert.match(sshErrorMessage(SSH_ERROR.HOST_KEY_CHANGED, conn, 'CHANGED'), /ssh-keygen -R box/)
-})
-
// A fake child process that emits a scripted result on next tick.
function fakeChild({ code = 0, stdout = '', stderr = '', errorEvent = null, hang = false }: any = {}) {
const child: any = new EventEmitter()
@@ -1104,10 +1097,7 @@ test('withRemoteTimeout kills a hung probe remotely instead of orphaning it (#11
// Shape: POSIX watchdog — macOS remotes have no GNU `timeout`.
const wrapped = withRemoteTimeout('hermes --version 2>&1', 15)
- assert.ok(wrapped.includes('sleep 15'), 'watchdog duration honored')
- assert.ok(wrapped.includes('kill -9'), 'watchdog kills the hung child remotely')
assert.ok(!/(^|[ ;(])timeout[ ;]/.test(wrapped), 'no GNU timeout dependency')
- assert.ok(wrapped.endsWith('exit $__htrc'), 'inner exit code propagated')
assert.ok(
withRemoteTimeout('true').includes(`sleep ${REMOTE_PROBE_TIMEOUT_SECS}`),
'defaults to REMOTE_PROBE_TIMEOUT_SECS'
diff --git a/apps/desktop/electron/titlebar-overlay-width.test.ts b/apps/desktop/electron/titlebar-overlay-width.test.ts
index 72aa8e2e87a..a7b6b99dce8 100644
--- a/apps/desktop/electron/titlebar-overlay-width.test.ts
+++ b/apps/desktop/electron/titlebar-overlay-width.test.ts
@@ -60,19 +60,6 @@ test('macOS keeps its height-only traffic-light overlay', () => {
)
})
-test('native overlays fall back to the active theme color', () => {
- assert.deepEqual(titleBarOverlayOptions({ platform: 'windows', foreground: null, dark: true }), {
- color: undefined,
- height: 0,
- symbolColor: '#f7f7f7'
- })
- assert.deepEqual(titleBarOverlayOptions({ platform: 'linux', foreground: null, dark: false }), {
- color: undefined,
- height: 0,
- symbolColor: '#242424'
- })
-})
-
test('plain Linux paints the WCO too, so it reserves the fallback width', () => {
// Regression #53185: re-enabling the overlay on plain Linux (KDE/GNOME)
// without reserving its width left the native min/max/close buttons painting
@@ -86,10 +73,6 @@ test('macOS uses traffic lights, not a WCO overlay, so it reserves nothing', ()
assert.equal(nativeOverlayWidth({ isMac: true }), 0)
})
-test('the fallback width is a sane positive pixel value', () => {
- assert.ok(Number.isInteger(OVERLAY_FALLBACK_WIDTH) && OVERLAY_FALLBACK_WIDTH > 0)
-})
-
test('pre-Tahoe keeps the full titlebar overlay height', () => {
assert.equal(macTitleBarOverlayHeight({ darwinMajor: MACOS_TAHOE_DARWIN_MAJOR - 1, titlebarHeight: 34 }), 34)
})
diff --git a/apps/desktop/electron/translucency.test.ts b/apps/desktop/electron/translucency.test.ts
index d525c7c864a..7ae03c8e0b1 100644
--- a/apps/desktop/electron/translucency.test.ts
+++ b/apps/desktop/electron/translucency.test.ts
@@ -67,14 +67,6 @@ const glass = (intensity: number, material: GlassMaterial = DEFAULT_GLASS_MATERI
scope: DEFAULT_GLASS_SCOPE
})
-describe('lever bounds', () => {
- it('keeps the bounds and floor stable so persisted settings survive upgrades', () => {
- expect(TRANSLUCENCY_MIN).toBe(0)
- expect(TRANSLUCENCY_MAX).toBe(100)
- expect(TRANSLUCENCY_OPACITY_FLOOR).toBe(0.3)
- })
-})
-
describe('clampIntensity', () => {
it('clamps to the lever bounds and rounds to a whole percent', () => {
expect(clampIntensity(-5)).toBe(TRANSLUCENCY_MIN)
@@ -279,14 +271,6 @@ describe('hudFrostFor', () => {
expect(hudFrostFor(glass(0, 'header'), true)).toEqual({ vibrancy: null, backgroundMaterial: 'none' })
})
- // Unlike a chat window, which keeps 'sidebar' under its titlebar band in
- // every non-glass state. Pinning this is what stops someone "fixing" the
- // null into a resting material and painting the slab back.
- it('resolves off to no material at all, not to a resting one', () => {
- expect(hudFrostFor(clear(60), true).vibrancy).toBeNull()
- expect(vibrancyFor(clear(60))).toBe('sidebar')
- })
-
// The tint is painted by the renderer, exactly as it is for a chat window —
// dragging it must not re-issue setVibrancy, whose 150ms animation restarts
// on every call and never lets the material settle.
@@ -332,14 +316,6 @@ describe('backgroundMaterialFor', () => {
expect(backgroundMaterialFor(glass(60, 'titlebar'))).toBe('mica')
})
- // Windows 11 has three system materials for four rungs, so the two heaviest
- // land on mica. The mapping stays total — a saved 'header' still resolves —
- // and the picker drops the duplicate instead (see glassMaterialsFor).
- it('collapses Glare onto mica with Bright', () => {
- expect(backgroundMaterialFor(glass(60, 'header'))).toBe('mica')
- expect(backgroundMaterialFor(glass(60, 'header'))).toBe(backgroundMaterialFor(glass(60, 'titlebar')))
- })
-
it('resolves every shipped rung to a real system material', () => {
for (const material of GLASS_MATERIALS) {
expect(WINDOWS_BACKGROUND_MATERIALS, material).toContain(backgroundMaterialFor(glass(60, material)))
@@ -359,14 +335,6 @@ describe('translucencySupportedOn', () => {
expect(translucencySupportedOn('linux')).toBe(false)
expect(translucencySupportedOn('freebsd')).toBe(false)
})
-
- // Win10 loses glass but keeps clear, so the row must survive there.
- it('stays on for a Windows build too old for glass', () => {
- const oldWindows = `10.0.${WINDOWS_GLASS_MIN_BUILD - 1}`
-
- expect(glassSupportedOn('win32', oldWindows)).toBe(false)
- expect(translucencySupportedOn('win32')).toBe(true)
- })
})
describe('the frost rungs a platform offers', () => {
@@ -634,12 +602,6 @@ describe('the defaults a fresh profile lands on', () => {
expect(defaultTranslucencyState('dark', false, false).mode).toBe('clear')
})
- it('keeps tint consistent across appearances and platforms', () => {
- for (const values of [mac('light'), mac('dark'), win('light'), win('dark')]) {
- expect(values.intensity).toBe(mac('light').intensity)
- }
- })
-
it('keeps the content column opaque at the native level', () => {
for (const values of [mac('light'), mac('dark'), win('light'), win('dark')]) {
expect(windowOpacityFor({ ...values, mode: 'glass' })).toBe(1)
diff --git a/apps/desktop/scripts/fixtures/glass-surfaces.html b/apps/desktop/scripts/fixtures/glass-surfaces.html
deleted file mode 100644
index 89654c1915c..00000000000
--- a/apps/desktop/scripts/fixtures/glass-surfaces.html
+++ /dev/null
@@ -1,3 +0,0 @@
-<!doctype html>
-<html lang="en"><head><meta charset="UTF-8"><title>Glass surface regression fixture</title></head>
-<body><div id="root"></div><script type="module" src="./glass-surfaces.tsx"></script></body></html>
diff --git a/apps/desktop/scripts/fixtures/glass-surfaces.tsx b/apps/desktop/scripts/fixtures/glass-surfaces.tsx
deleted file mode 100644
index 9ca707af52f..00000000000
--- a/apps/desktop/scripts/fixtures/glass-surfaces.tsx
+++ /dev/null
@@ -1,160 +0,0 @@
-import '@/styles.css'
-
-import {
- AssistantRuntimeProvider,
- MessagePrimitive,
- type ThreadMessage,
- useExternalStoreRuntime
-} from '@assistant-ui/react'
-import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
-import { useState } from 'react'
-import { flushSync } from 'react-dom'
-import { createRoot } from 'react-dom/client'
-import { MemoryRouter } from 'react-router'
-
-import { Thread } from '@/components/assistant-ui/thread'
-import { ThreadMessageList } from '@/components/assistant-ui/thread/list'
-import { StickyHumanMessageContainer, USER_BUBBLE_BASE_CLASS } from '@/components/assistant-ui/thread/user-message'
-import { PaneTab, PaneTabLabel, PaneTabStrip } from '@/components/ui/pane-tab'
-import { RootTooltipProvider } from '@/components/ui/tooltip'
-import { I18nProvider } from '@/i18n'
-
-// Real primitives and stylesheet; only the sample labels and glass inputs are fixtures.
-const root = document.documentElement
-root.classList.add('dark')
-root.setAttribute('data-hermes-glass', '')
-root.setAttribute('data-hermes-glass-scope', 'window')
-root.style.setProperty('--translucency-glass-keep', '40%')
-
-const messages = Array.from({ length: 6 }, (_, turn) => [
- {
- id: `user-${turn}`,
- role: 'user',
- attachments: [],
- createdAt: new Date(0),
- content: [{ type: 'text', text: `Prompt ${turn}` }],
- metadata: { custom: {} }
- },
- {
- id: `assistant-${turn}`,
- role: 'assistant',
- createdAt: new Date(0),
- content: [{ type: 'text', text: `Reply ${turn}` }],
- status: { type: 'complete', reason: 'stop' },
- metadata: { custom: {}, unstable_state: null, unstable_annotations: [], unstable_data: [], steps: [] }
- }
-]).flat() as ThreadMessage[]
-
-function User() {
- const [expanded, setExpanded] = useState(false)
-
- return (
- <StickyHumanMessageContainer
- attachments={
- <div data-testid="attachment" style={{ height: 40 }}>
- Attachment
- </div>
- }
- >
- <button
- className={USER_BUBBLE_BASE_CLASS}
- onClick={() => setExpanded(value => !value)}
- style={{ height: expanded ? 140 : 48 }}
- >
- A user prompt — click to change its height
- </button>
- </StickyHumanMessageContainer>
- )
-}
-
-function Assistant() {
- return (
- <MessagePrimitive.Root data-slot="aui_assistant-message-root">
- <div data-testid="reply-marker" style={{ height: 900, background: '#ff0000' }}>
- Scrolling reply
- </div>
- </MessagePrimitive.Root>
- )
-}
-
-const components = { UserMessage: User, AssistantMessage: Assistant }
-
-function Transcript({ id }: { id: string }) {
- const [currentMessages, setMessages] = useState(() =>
- new URLSearchParams(location.search).has('preceding')
- ? ([{ ...messages[1], id: 'standalone' }, ...messages] as ThreadMessage[])
- : messages
- )
-
- const runtime = useExternalStoreRuntime<ThreadMessage>({
- messages: currentMessages,
- isRunning: false,
- onNew: async () => {},
- onEdit: async () => {}
- })
-
- const realMessages = new URLSearchParams(location.search).has('real')
-
- return (
- <AssistantRuntimeProvider runtime={runtime}>
- <div>
- <button
- data-testid={`${id}-append`}
- onClick={() =>
- flushSync(() =>
- setMessages(previous => [
- ...previous,
- { ...messages[1], id: `appended-${previous.length}` } as ThreadMessage
- ])
- )
- }
- >
- Append reply
- </button>
- <div data-testid={id} style={{ height: 430, width: 480 }}>
- {realMessages ? <Thread sessionKey={id} /> : <ThreadMessageList components={components} sessionKey={id} />}
- </div>
- </div>
- </AssistantRuntimeProvider>
- )
-}
-
-createRoot(document.getElementById('root')!).render(
- <QueryClientProvider client={new QueryClient()}>
- <I18nProvider>
- <RootTooltipProvider>
- <MemoryRouter>
- <div style={{ padding: 40 }}>
- <PaneTabStrip>
- <PaneTab
- active
- data-testid="active-tab"
- onClose={() => document.body.setAttribute('data-closed', 'true')}
- >
- <PaneTabLabel as="button" onClick={() => document.body.setAttribute('data-activated', 'true')}>
- A long session title that reaches underneath the close button
- </PaneTabLabel>
- </PaneTab>
- <PaneTab data-testid="idle-tab" dirty onClose={() => {}}>
- <PaneTabLabel>Another long session title with unsaved changes</PaneTabLabel>
- </PaneTab>
- <PaneTab data-testid="fixed-tab">
- <PaneTabLabel>Sessions</PaneTabLabel>
- </PaneTab>
- <PaneTab data-testid="short-tab" onClose={() => {}}>
- <PaneTabLabel>X</PaneTabLabel>
- </PaneTab>
- <PaneTab data-testid="selected-tab" onClose={() => {}} selected>
- <PaneTabLabel>Selected</PaneTabLabel>
- </PaneTab>
- </PaneTabStrip>
- <div style={{ display: 'flex', gap: 30, marginTop: 40 }}>
- <Transcript id="first-transcript" />
- <Transcript id="second-transcript" />
- </div>
- </div>
- </MemoryRouter>
- </RootTooltipProvider>
- </I18nProvider>
- </QueryClientProvider>
-)