The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(desktop): carry the browser host renderer from #93508
Bear Huddleston7ac4cf552c28
diff --git a/apps/desktop/DESIGN.md b/apps/desktop/DESIGN.mdindex 3026147da07..80acbd115b1 100644--- a/apps/desktop/DESIGN.md+++ b/apps/desktop/DESIGN.md@@ -180,6 +180,7 @@ inline affordance — "Change", "Open logs").that sit inside a heading/sentence; replaces `h-auto px-0 py-0`), `micro`(status-stack/table-footers), and the icon family `icon` / `icon-xs` /`icon-sm` / `icon-lg` / `icon-titlebar`.+`touch` provides a 44px minimum target for compact mobile navigation.**Tooltips only when hover teaches something new.** `<Tip>` is for discovery,not a tax on every icon. Ask: does hover reveal something the user cannot@@ -269,6 +270,16 @@ blurred backdrop.## Layout+Composer controls retain 44px targets on coarse-pointer surfaces. Collapse+stages budget the actual control-size token; below the two-target width budget,+the context menu and Send occupy separate rows rather than clipping or shrinking.+The voice engine split-button uses `--composer-voice-menu-size`: compact on+desktop, matching `--composer-control-size` on touch surfaces.+Narrow browser touch layouts show the current session tab with an open-tab+count. Its menu exposes every tab, while the new-tab action remains beside it.+Outside taps dismiss narrow sidebar overlays; cancelled or scrolling gestures+do not. Touch transcript gestures select a pane without focusing its composer.+- **Gutters:** `PAGE_INSET_X` (`src/app/layout-constants.ts`) for page sidepadding; `PAGE_INSET_NEG_X` to bleed a child to the edge. Don't hardcode`px-6`/`px-8` on pages.diff --git a/apps/desktop/electron/external-open.ts b/apps/desktop/electron/external-open.tsindex 8e063185941..26c1515923d 100644--- a/apps/desktop/electron/external-open.ts+++ b/apps/desktop/electron/external-open.ts@@ -15,6 +15,8 @@import type { ChildProcess, SpawnOptions } from 'node:child_process'+import { externalUrlTarget } from '../../shared/src/external-url'+import { absolutizeProtocolRelativeUrl, looksLikeLocalFilesystemPath } from './local-filesystem-path'export type ExternalOpenResult =@@ -68,8 +70,6 @@ export interface ExternalOpenDeps {log: (line: string) => void}-const SUPPORTED_WEB = ['http:', 'https:', 'mailto:']-export function externalOpenErrorMessage(error: unknown): string {return error instanceof Error ? error.message : String(error)}@@ -110,17 +110,15 @@ export async function openExternalUrl(rawUrl: string, deps: ExternalOpenDeps): Preturn { ok: true }}- let parsed: URL+ const target = externalUrlTarget(raw)- try {- parsed = new URL(raw)- } catch {+ if (!target) {return { ok: false, reason: 'invalid' }}- if (parsed.protocol === 'file:') {+ if (target.kind === 'file') {try {- await deps.openFile(raw)+ await deps.openFile(target.url)} catch {// main's openFile handles its own fallback; never surfaced here}@@ -128,11 +126,7 @@ export async function openExternalUrl(rawUrl: string, deps: ExternalOpenDeps): Preturn { ok: true }}- if (!SUPPORTED_WEB.includes(parsed.protocol)) {- return { ok: false, reason: 'invalid' }- }-- const url = parsed.toString()+ const { url } = targetif (deps.isWsl) {return openViaWsl(url, deps)diff --git a/apps/desktop/index.html b/apps/desktop/index.htmlindex f78219623d4..3dffd60a8b3 100644--- a/apps/desktop/index.html+++ b/apps/desktop/index.html@@ -2,7 +2,7 @@<html lang="en"><head><meta charset="UTF-8" />- <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0, interactive-widget=resizes-content" /><meta name="color-scheme" content="light dark" /><meta name="theme-color" content="#0a0a0a" /><link rel="icon" type="image/png" sizes="180x180" href="/apple-touch-icon.png" />diff --git a/apps/desktop/package.json b/apps/desktop/package.jsonindex b8e33c34636..f9d0c428587 100644--- a/apps/desktop/package.json+++ b/apps/desktop/package.json@@ -27,8 +27,10 @@"profile:main": "tsc --build tsconfig.electron.json && wait-on http://127.0.0.1:5174 && node scripts/bundle-electron-main.mjs --dev && cross-env XCURSOR_SIZE=24 HERMES_DESKTOP_DEV_SERVER=http://127.0.0.1:5174 electron --inspect=9229 .","profile:main:cpu": "tsc --build tsconfig.electron.json && wait-on http://127.0.0.1:5174 && node scripts/bundle-electron-main.mjs --dev && cross-env XCURSOR_SIZE=24 NODE_OPTIONS=--cpu-prof HERMES_DESKTOP_DEV_SERVER=http://127.0.0.1:5174 electron .","start": "npm run build && electron .",+ "build:webapp": "node scripts/build-webapp.mjs","build": "node scripts/build.mjs","i18n:keys": "node scripts/i18n-keys.mjs",+ "smoke:browser-host": "node scripts/smoke-browser-host.mjs","prebuilder": "node scripts/patch-electron-builder-mac-binary.mjs","builder": "node scripts/run-electron-builder.mjs","pack": "npm run build && npm run builder -- --dir --publish never",diff --git a/apps/desktop/scripts/build-webapp.mjs b/apps/desktop/scripts/build-webapp.mjsnew file mode 100644index 00000000000..43682ca4a3f--- /dev/null+++ b/apps/desktop/scripts/build-webapp.mjs@@ -0,0 +1,63 @@+// npm's source-development composition for the browser-hosted renderer.+//+// Dependencies are installed into a private workspace, never the checkout:+// npm ci would prune the native Desktop install (node-pty, Electron), and+// headless hosts have no toolchain for its lifecycle scripts. The workspace+// mirrors exactly the inputs the Webapp receipt covers and keeps its+// node_modules between builds, so npm ci reruns only when the lock changes.+import { copyFileSync, existsSync, mkdirSync, readFileSync, rmSync } from 'node:fs'+import { dirname, join, resolve } from 'node:path'+import { parseArgs } from 'node:util'+import { isMain, repoRoot } from '../../../scripts/build/frontend-common.mjs'+import { sourceEntries } from '../../../scripts/build/freshness.mjs'+import { prepareNodeDependencies } from '../../../scripts/build/node-deps.mjs'+import { buildWebapp } from '../../../scripts/build/webapp.mjs'++/** Make the workspace hash exactly like the checkout for the Webapp product. */+export function mirrorWebappInputs(source, workspace) {+ const wanted = new Map(sourceEntries(source, 'webapp').map(({ name, kind }) => [name, kind]))+ // Children before parents. Generated trees (node_modules) are never listed, so never removed.+ for (const { name, kind } of sourceEntries(workspace, 'webapp').reverse()) {+ if (wanted.get(name) !== kind) rmSync(join(workspace, name), { recursive: true, force: true })+ }+ for (const [name, kind] of wanted) {+ const target = join(workspace, name)+ // Loose inputs such as pm/lock.json have no listed parent directory.+ mkdirSync(kind === 'directory' ? target : dirname(target), { recursive: true })+ if (kind === 'file') copyFileSync(join(source, name), target)+ }+ // npm ci validates the whole locked workspace graph, so every workspace+ // manifest must exist even though only Desktop and shared are compiled.+ const lock = JSON.parse(readFileSync(join(source, 'package-lock.json'), 'utf8'))+ for (const entry of Object.values(lock.packages || {})) {+ const manifest = entry.link && join(entry.resolved, 'package.json')+ if (!manifest || !existsSync(join(source, manifest))) continue+ mkdirSync(dirname(join(workspace, manifest)), { recursive: true })+ copyFileSync(join(source, manifest), join(workspace, manifest))+ }+}++export async function buildSourceWebapp({+ source = repoRoot, workspace, install = true, prepare = prepareNodeDependencies,+} = {}) {+ source = resolve(source)+ workspace = resolve(workspace ?? join(source, '.build/webapp-workspace'))+ mkdirSync(workspace, { recursive: true })+ mirrorWebappInputs(source, workspace)+ prepare({+ source: workspace, workspaces: ['apps/desktop'], reuse: true, install,+ env: { ...process.env, npm_config_ignore_scripts: 'true' },+ })+ return buildWebapp({ source, workspace, out: join(source, 'apps/desktop/dist-webapp') })+}++if (isMain(import.meta.url)) {+ try {+ const { values } = parseArgs({ options: { 'no-install': { type: 'boolean', default: false } } })+ const result = await buildSourceWebapp({ install: !values['no-install'] })+ console.log(`built ${result.index}`)+ } catch (error) {+ console.error(error)+ process.exitCode = 1+ }+}diff --git a/apps/desktop/scripts/perf/lib/cdp.mjs b/apps/desktop/scripts/perf/lib/cdp.mjsindex edba451ddcf..30fa5841d87 100644--- a/apps/desktop/scripts/perf/lib/cdp.mjs+++ b/apps/desktop/scripts/perf/lib/cdp.mjs@@ -1,4 +1,4 @@-// The one Chrome DevTools Protocol client for the desktop perf harness.+// The one Chrome DevTools Protocol client for desktop scripts.//// Before this, every measure-*/profile-* script shipped its own copy-pasted// `CDP` class (four subtly different implementations), its own `/json` vs@@ -21,6 +21,17 @@ export const SELECTORS = {const sleep = ms => new Promise(resolve => setTimeout(resolve, ms))+async function websocketMessageText(data) {+ if (typeof data === 'string') return data+ if (typeof Blob !== 'undefined' && data instanceof Blob) return data.text()+ if (data instanceof ArrayBuffer) return new TextDecoder().decode(data)+ if (ArrayBuffer.isView(data)) {+ return new TextDecoder().decode(new Uint8Array(data.buffer, data.byteOffset, data.byteLength))+ }++ return data.toString('utf8')+}+/*** Poll the CDP HTTP endpoint until a page target is available.* @param {object} [opts]@@ -62,18 +73,38 @@ export class CDP {this.listeners = new Map()}- static async open(url) {+ static async open(url, { timeoutMs = 10_000 } = {}) {const ws = new WebSocket(url)await new Promise((resolve, reject) => {- ws.addEventListener('open', resolve, { once: true })- ws.addEventListener('error', reject, { once: true })+ const cleanup = () => {+ clearTimeout(timeout)+ ws.removeEventListener('open', opened)+ ws.removeEventListener('error', failed)+ }+ const opened = () => {+ cleanup()+ resolve()+ }+ const failed = () => {+ cleanup()+ reject(new Error('CDP websocket failed to open'))+ }+ const timeout = setTimeout(() => {+ cleanup()+ ws.close()+ reject(new Error('CDP websocket open timeout'))+ }, timeoutMs)++ timeout.unref?.()+ ws.addEventListener('open', opened, { once: true })+ ws.addEventListener('error', failed, { once: true })})const cdp = new CDP(ws)- ws.addEventListener('message', ev => {- const m = JSON.parse(typeof ev.data === 'string' ? ev.data : ev.data.toString('utf8'))+ ws.addEventListener('message', async ev => {+ const m = JSON.parse(await websocketMessageText(ev.data))if (m.id != null && cdp.pending.has(m.id)) {const { resolve, reject } = cdp.pending.get(m.id)@@ -110,6 +141,10 @@ export class CDP {}send(method, params = {}) {+ if (this.ws.readyState !== WebSocket.OPEN) {+ return Promise.reject(new Error(`CDP websocket is not open for ${method}`))+ }+const id = ++this.idreturn new Promise((resolve, reject) => {@@ -124,11 +159,42 @@ export class CDP {}this.listeners.get(method).push(handler)++ return () => {+ const handlers = this.listeners.get(method)++ if (!handlers) return+ const index = handlers.indexOf(handler)++ if (index >= 0) handlers.splice(index, 1)+ if (handlers.length === 0) this.listeners.delete(method)+ }+ }++ waitFor(method, timeoutMs = 30_000) {+ return new Promise((resolve, reject) => {+ const unsubscribe = this.on(method, params => {+ clearTimeout(timeout)+ unsubscribe()+ resolve(params)+ })+ const timeout = setTimeout(() => {+ unsubscribe()+ reject(new Error(`timed out waiting for CDP event ${method}`))+ }, timeoutMs)++ timeout.unref?.()+ })}/** Evaluate an expression in the page and return its value (awaits promises). */- async eval(expression) {- const r = await this.send('Runtime.evaluate', { expression, returnByValue: true, awaitPromise: true })+ async eval(expression, options = {}) {+ const r = await this.send('Runtime.evaluate', {+ expression,+ returnByValue: true,+ awaitPromise: true,+ ...options+ })if (r.exceptionDetails) {throw new Error(r.exceptionDetails.exception?.description || r.exceptionDetails.text || 'eval failed')diff --git a/apps/desktop/scripts/smoke-browser-host.mjs b/apps/desktop/scripts/smoke-browser-host.mjsnew file mode 100644index 00000000000..0315ee1a26e--- /dev/null+++ b/apps/desktop/scripts/smoke-browser-host.mjs@@ -0,0 +1,475 @@+#!/usr/bin/env node++import { existsSync, mkdtempSync, rmSync } from 'node:fs'+import { createServer } from 'node:net'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { spawn, spawnSync } from 'node:child_process'+import process from 'node:process'++import { CDP, sleep } from './perf/lib/cdp.mjs'++const url = process.env.HERMES_BROWSER_HOST_URL || process.argv[2] || 'http://127.0.0.1:9119/'+// Navigation keeps the private launch fragment; HTTP responses never contain it.+const documentUrl = new URL(url)+documentUrl.hash = ''+const allowGatewayFailure = process.env.HERMES_BROWSER_ALLOW_GATEWAY_FAILURE === '1'+const requireTerminal = process.env.HERMES_BROWSER_REQUIRE_TERMINAL === '1'+// A cold Webapp starts the profile's gateway on the first ticket mint, so its relayed socket can open+// long after the shell paints (the renderer allows the mint 75 s).+const GATEWAY_SOCKET_TIMEOUT_MS = 90_000++function findExecutable() {+ const explicit = process.env.HERMES_BROWSER_EXECUTABLE?.trim()+ if (explicit) return explicit++ const candidates =+ process.platform === 'win32'+ ? [+ 'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe',+ 'C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe',+ 'C:\\Program Files\\Microsoft\\Edge\\Application\\msedge.exe'+ ]+ : ['chromium-browser', 'chromium', 'google-chrome', 'google-chrome-stable']++ for (const candidate of candidates) {+ if (candidate.includes('\\') && existsSync(candidate)) return candidate+ if (!candidate.includes('\\')) {+ const found = spawnSync('sh', ['-lc', `command -v ${candidate}`], { encoding: 'utf8' })+ const path = found.status === 0 ? found.stdout.trim() : ''+ if (path) return path+ }+ }++ throw new Error('No Chromium-compatible browser found; set HERMES_BROWSER_EXECUTABLE')+}++const ignoredConsoleError = text =>+ text.includes("Blocked call to navigator.vibrate because user hasn't tapped") ||+ (allowGatewayFailure && text.includes('WebSocket connection to'))++async function freePort() {+ const server = createServer()+ await new Promise((resolve, reject) => {+ server.once('error', reject)+ server.listen(0, '127.0.0.1', resolve)+ })+ const address = server.address()+ const port = typeof address === 'object' && address ? address.port : 0+ await new Promise(resolve => server.close(resolve))+ if (!port) throw new Error('could not allocate a Chromium debugging port')+ return port+}++async function waitForJson(endpoint, browser, stderrTail, timeoutMs = 15_000) {+ const deadline = Date.now() + timeoutMs+ let lastError+ while (Date.now() < deadline) {+ if (browser.exitCode !== null) {+ throw new Error(`Chromium exited during startup (${browser.exitCode})\n${stderrTail()}`)+ }+ try {+ const response = await fetch(endpoint)+ if (response.ok) return await response.json()+ lastError = new Error(`HTTP ${response.status}`)+ } catch (error) {+ lastError = error+ }+ await sleep(100)+ }+ throw new Error(`Chromium DevTools endpoint did not become ready: ${lastError || 'timeout'}\n${stderrTail()}`)+}++async function createTarget(debugPort) {+ const endpoint = `http://127.0.0.1:${debugPort}/json/new?${encodeURIComponent('about:blank')}`+ const response = await fetch(endpoint, { method: 'PUT' })+ if (!response.ok) throw new Error(`failed to create Chromium target: HTTP ${response.status}`)+ return await response.json()+}++function consoleText(params) {+ return (params.args || [])+ .map(arg => {+ if (Object.hasOwn(arg, 'value')) return typeof arg.value === 'string' ? arg.value : JSON.stringify(arg.value)+ return arg.description || arg.type || ''+ })+ .join(' ')+}++const stateExpression = `(() => {+ const requiredBridgeMethods = [+ 'api',+ 'getAgentRoster',+ 'getConnection',+ 'getConnectionFor',+ 'getGatewayWsUrlFor',+ 'getProfileRoutes',+ 'getRecentLogs',+ 'normalizePreviewTarget',+ 'readDir',+ 'readFileText',+ 'revealLogs',+ 'saveClipboardImage',+ 'watchPreviewFile'+ ]+ const text = document.body.innerText || ''+ return {+ authRequired: window.__HERMES_AUTH_REQUIRED__ === true,+ bodyScrollWidth: document.body.scrollWidth,+ bridge: Boolean(window.hermesDesktop),+ clientWidth: document.documentElement.clientWidth,+ desktopBootFailed: text.includes('Desktop boot failed'),+ host: document.documentElement.dataset.hermesDesktopHost || '',+ requiredBridgeMethods: requiredBridgeMethods.every(key => typeof window.hermesDesktop?.[key] === 'function'),+ rootError: text.includes('Something broke in the interface'),+ scrollWidth: document.documentElement.scrollWidth,+ privateSession: window.__HERMES_UI_SURFACE__ === 'webapp',+ title: document.title+ }+})()`++const terminalExpression = `(async () => {+ const terminal = window.hermesDesktop?.terminal+ if (!terminal) return { error: 'terminal bridge missing', ok: false, skipped: false }+ let session+ try {+ session = await terminal.start({ cols: 48, rows: 16 })+ let output = ''+ const stop = terminal.onData(session.id, chunk => { output += chunk })+ await terminal.resize(session.id, { cols: 52, rows: 18 })+ const deadline = Date.now() + 8000+ while (!output && Date.now() < deadline) {+ await new Promise(resolve => setTimeout(resolve, 50))+ }+ const cwd = await terminal.cwd(session.id)+ stop()+ await terminal.dispose(session.id)+ const fatalOutput = [+ 'Chat unavailable:',+ 'Chat failed to start:',+ 'Terminal unavailable:',+ 'Terminal failed to start:',+ 'Pseudo-terminal support is unavailable',+ 'ModuleNotFoundError:',+ 'Traceback (most recent call last)'+ ].find(marker => output.includes(marker))+ const hostShellStarted = session.shell !== 'hermes-tui' && Boolean(output)+ return {+ cwd,+ error: fatalOutput+ ? 'host shell startup error: ' + fatalOutput+ : hostShellStarted+ ? undefined+ : 'host shell did not produce PTY output',+ ok: hostShellStarted && !fatalOutput,+ outputTail: output.slice(-800),+ shell: session.shell,+ skipped: false+ }+ } catch (error) {+ if (session?.id) await terminal.dispose(session.id).catch(() => undefined)+ return { error: error instanceof Error ? error.message : String(error), ok: false, skipped: false }+ }+})()`++const htmlSandboxExpression = `(async () => {+ const bridge = window.hermesDesktop+ if (!bridge?.saveImageBuffer) return { error: 'buffer bridge missing', ok: false }+ const marker = 'hermesSandboxEscape'+ delete document.documentElement.dataset[marker]+ const attack = '<script>try{top.document.documentElement.dataset.' + marker + '="escaped"}catch(_error){}</script>'+ const url = await bridge.saveImageBuffer(new TextEncoder().encode(attack), '.html')+ const frame = document.createElement('iframe')+ frame.hidden = true+ const loaded = new Promise(resolve => {+ frame.addEventListener('load', resolve, { once: true })+ setTimeout(resolve, 2000)+ })+ frame.src = url+ document.body.appendChild(frame)+ await loaded+ await new Promise(resolve => setTimeout(resolve, 200))+ const escaped = document.documentElement.dataset[marker] === 'escaped'+ frame.remove()+ URL.revokeObjectURL(url)+ delete document.documentElement.dataset[marker]+ return { escaped, ok: !escaped }+})()`++const layoutExpression = `(async () => {+ const visible = element => {+ if (!(element instanceof HTMLElement)) return false+ const rect = element.getBoundingClientRect()+ const style = getComputedStyle(element)+ return rect.width > 0 && rect.height > 0 && style.display !== 'none' && style.visibility !== 'hidden'+ }+ const button = label => [...document.querySelectorAll('button')].find(item =>+ item.getAttribute('aria-label') === label || item.textContent?.trim() === label+ )+ const editor = button('Layout editor')+ if (!editor) return { error: 'layout editor button missing', ok: false }+ editor.click()+ await new Promise(resolve => setTimeout(resolve, 100))+ const quad = button('Quad')+ if (!quad) return { error: 'Quad preset button missing', ok: false }+ quad.click()+ await new Promise(resolve => setTimeout(resolve, 100))+ const done = button('Done')+ if (!done) return { error: 'Done button missing', ok: false }+ done.click()+ const read = () => {+ const files = document.querySelector('[data-tree-tab="files"]')+ const review = document.querySelector('[aria-label="Review"]')+ const terminal = document.querySelector('[data-tree-tab="terminal"]')+ return {+ editModeClosed: !button('Done'),+ files: visible(files),+ review: visible(review),+ terminal: visible(terminal)+ }+ }+ const deadline = Date.now() + 3000+ let state = read()+ while (!(state.editModeClosed && state.files && state.review && state.terminal) && Date.now() < deadline) {+ await new Promise(resolve => setTimeout(resolve, 50))+ state = read()+ }+ const activePreset = localStorage.getItem('hermes.desktop.layoutPreset.active')+ return {+ activePreset,+ ...state,+ ok: activePreset === 'quad' && state.editModeClosed && state.files && state.review && state.terminal+ }+})()`++const mobileViewportExpression = `(() => {+ const visibleBottom = document.documentElement.clientHeight+ const bottom = selector => document.querySelector(selector)?.getBoundingClientRect().bottom ?? null+ const shellBottom = bottom('[data-contrib-shell]')+ const sidebarBottom = bottom('[data-slot="sidebar-wrapper"]')+ const composerBottom = bottom('[data-slot="composer-dock"]')+ const contained = value => typeof value === 'number' && value <= visibleBottom + 1+ return {+ composerBottom,+ ok: contained(shellBottom) && contained(sidebarBottom) && contained(composerBottom),+ shellBottom,+ sidebarBottom,+ visibleBottom+ }+})()`++const executable = findExecutable()+const debugPort = await freePort()+const profile = mkdtempSync(join(tmpdir(), 'hermes-browser-smoke-'))+const stderrChunks = []+const browser = spawn(+ executable,+ [+ '--headless=new',+ '--disable-dev-shm-usage',+ '--remote-debugging-address=127.0.0.1',+ `--remote-debugging-port=${debugPort}`,+ `--user-data-dir=${profile}`,+ 'about:blank'+ ],+ { stdio: ['ignore', 'ignore', 'pipe'] }+)+browser.stderr?.on('data', chunk => {+ stderrChunks.push(Buffer.from(chunk))+ while (stderrChunks.reduce((sum, item) => sum + item.length, 0) > 24_000) stderrChunks.shift()+})+const stderrTail = () => Buffer.concat(stderrChunks).toString('utf8').slice(-24_000)++let browserControl = null++try {+ const browserVersion = await waitForJson(`http://127.0.0.1:${debugPort}/json/version`, browser, stderrTail)+ if (browserVersion?.webSocketDebuggerUrl) {+ browserControl = await CDP.open(browserVersion.webSocketDebuggerUrl)+ }++ for (const viewport of [+ { width: 844, height: 390, mobile: true, smallViewportHeightDifference: 120 },+ { width: 1280, height: 800 },+ { width: 390, height: 844 },+ { width: 320, height: 568 }+ ]) {+ const target = await createTarget(debugPort)+ const client = await CDP.open(target.webSocketDebuggerUrl)+ const evaluate = expression => client.eval(expression, { userGesture: true })++ const consoleErrors = []+ const pageErrors = []+ const failedRequests = []+ const requestUrls = new Map()+ let httpStatus = null++ client.on('Runtime.consoleAPICalled', params => {+ if (params.type !== 'error') return+ const text = consoleText(params)+ if (!ignoredConsoleError(text)) consoleErrors.push(text)+ })+ client.on('Runtime.exceptionThrown', params => {+ const error = params.exceptionDetails?.exception?.description || params.exceptionDetails?.text || 'page exception'+ pageErrors.push(error)+ })+ client.on('Network.requestWillBeSent', params => {+ requestUrls.set(params.requestId, params.request?.url || '')+ })+ const gatewaySockets = []+ client.on('Network.webSocketCreated', params => {+ if (String(params.url || '').includes('/api/ws')) gatewaySockets.push(new URL(params.url))+ })+ client.on('Network.responseReceived', params => {+ if (params.type === 'Document' && params.response?.url === documentUrl.href) httpStatus = params.response.status+ })+ client.on('Network.loadingFailed', params => {+ const requestUrl = requestUrls.get(params.requestId) || ''+ if (allowGatewayFailure && requestUrl.includes('/api/ws')) return+ failedRequests.push(`${requestUrl || params.requestId} (${params.errorText || 'request failed'})`)+ })++ await Promise.all([client.send('Page.enable'), client.send('Runtime.enable'), client.send('Network.enable')])+ await client.send('Emulation.setDeviceMetricsOverride', {+ width: viewport.width,+ height: viewport.height,+ deviceScaleFactor: 1,+ mobile: viewport.mobile ?? false+ })+ const domReady = client.waitFor('Page.domContentEventFired', 30_000)+ await client.send('Page.navigate', { url })+ await domReady+ await sleep(4_000)+ const socketDeadline = Date.now() + GATEWAY_SOCKET_TIMEOUT_MS+ while (+ !allowGatewayFailure &&+ !gatewaySockets.some(socket => socket.searchParams.has('native_dial')) &&+ Date.now() < socketDeadline+ )+ await sleep(250)++ // Mobile browser controls shrink the small viewport without changing the+ // legacy 100vh size. Apply this after navigation so Chromium recalculates+ // the live top-level frame.+ if (viewport.smallViewportHeightDifference) {+ await client.send('Emulation.setSmallViewportHeightDifferenceOverride', {+ difference: viewport.smallViewportHeightDifference+ })+ await sleep(100)+ }++ const state = await evaluate(stateExpression)+ const authenticated = await evaluate(`(async () => {+ try {+ await window.hermesDesktop.api({ path: '/api/profiles' })+ return true+ } catch { return false }+ })()`)+ let htmlSandboxState = { skipped: true }+ let layoutState = { skipped: true }+ let mobileViewportState = { skipped: true }+ let terminalState = { skipped: true }+ if (viewport.width === 1280) htmlSandboxState = await evaluate(htmlSandboxExpression)+ if (viewport.width === 1280) layoutState = await evaluate(layoutExpression)+ if (viewport.smallViewportHeightDifference) mobileViewportState = await evaluate(mobileViewportExpression)+ if (requireTerminal && viewport.width === 1280) terminalState = await evaluate(terminalExpression)++ const failures = []+ if (httpStatus === null || httpStatus >= 400) failures.push(`HTTP ${httpStatus ?? 'no response'}`)+ if (state.host !== 'browser' || !state.bridge) failures.push('browser Desktop bridge did not install')+ if (!state.authRequired && !state.privateSession) {+ failures.push('browser auth bootstrap was not injected')+ }+ if (!authenticated) failures.push('browser Desktop API authentication failed')+ if (!state.requiredBridgeMethods) failures.push('required browser Desktop bridge methods are missing')+ if (state.rootError) failures.push('renderer reached its root error boundary')+ if (!allowGatewayFailure && state.desktopBootFailed)+ failures.push('Desktop could not connect to the Hermes gateway')+ // The Webapp relays the browser to its profile's gateway: the live socket speaks the canonical+ // contract (native_dial) and never carries the session token.+ if (!allowGatewayFailure && state.privateSession) {+ if (!gatewaySockets.some(socket => socket.searchParams.has('native_dial')))+ failures.push(`Webapp gateway socket is not the canonical relay: ${gatewaySockets.map(String).join(', ') || 'none'}`)+ if (gatewaySockets.some(socket => socket.searchParams.has('token')))+ failures.push('Webapp gateway socket carried the session token in its URL')+ }+ if (viewport.width === 1280 && !layoutState.ok) {+ failures.push(`configured layout reverted after leaving edit mode: ${JSON.stringify(layoutState)}`)+ }+ if (viewport.width === 1280 && !htmlSandboxState.ok) {+ failures.push(`browser HTML artifact escaped its sandbox: ${JSON.stringify(htmlSandboxState)}`)+ }+ if (+ viewport.smallViewportHeightDifference &&+ mobileViewportState.visibleBottom !== viewport.height - viewport.smallViewportHeightDifference+ ) {+ failures.push(`mobile viewport emulation did not shrink the visible page: ${JSON.stringify(mobileViewportState)}`)+ }+ if (viewport.smallViewportHeightDifference && !mobileViewportState.ok) {+ failures.push(`mobile browser controls cover the app shell: ${JSON.stringify(mobileViewportState)}`)+ }+ if (requireTerminal && viewport.width === 1280 && !terminalState.ok) {+ failures.push(+ `browser Desktop host terminal failed: ${terminalState.error || terminalState.outputTail || 'marker missing'}`+ )+ }+ if (state.scrollWidth > state.clientWidth || state.bodyScrollWidth > state.clientWidth) {+ failures.push(+ `horizontal overflow: viewport=${state.clientWidth}, html=${state.scrollWidth}, body=${state.bodyScrollWidth}`+ )+ }+ failures.push(...pageErrors.map(error => `pageerror: ${error}`))+ failures.push(...consoleErrors.map(error => `console: ${error}`))+ failures.push(...failedRequests.map(error => `request: ${error}`))++ console.log(+ JSON.stringify(+ { authenticated, failures, htmlSandboxState, http: httpStatus, layoutState, mobileViewportState, state, terminalState, viewport },+ null,+ 2+ )+ )+ try {+ await client.send('Page.close')+ } catch {+ /* target may already be closing */+ }+ client.close()++ if (failures.length) {+ process.exitCode = 1+ break+ }+ }+} finally {+ // Ask Chromium to shut down through its own browser-level CDP endpoint first.+ // This lets profile writers and helper processes flush before we remove the+ // temporary user-data-dir. Chromium exposed a real ENOTEMPTY race when+ // the smoke killed Chromium and immediately called rmSync despite all UX+ // assertions already passing.+ if (browserControl) {+ try {+ await browserControl.send('Browser.close')+ } catch {+ /* Chromium may close the control socket before acknowledging Browser.close */+ }+ browserControl.close()+ }++ const hasExited = () => browser.exitCode !== null || browser.signalCode !== null+ const waitForExit = async timeoutMs => {+ if (hasExited()) return true+ await Promise.race([new Promise(resolve => browser.once('exit', resolve)), sleep(timeoutMs)])+ return hasExited()+ }++ if (!(await waitForExit(3_000))) {+ browser.kill('SIGTERM')+ if (!(await waitForExit(3_000))) {+ browser.kill('SIGKILL')+ await waitForExit(3_000)+ }+ }++ rmSync(profile, { recursive: true, force: true, maxRetries: 12, retryDelay: 125 })+}diff --git a/apps/desktop/src/app/chat/composer/composer-utils.ts b/apps/desktop/src/app/chat/composer/composer-utils.tsindex cfb58acef07..108b8964fff 100644--- a/apps/desktop/src/app/chat/composer/composer-utils.ts+++ b/apps/desktop/src/app/chat/composer/composer-utils.ts@@ -39,7 +39,9 @@ export const COMPOSER_FOLD_VOICE_PX = 260// even with voice folded the row still costs ~150, so the last rung drops the// pill AND the voice menu. Both stay reachable — the model by hotkey and the// full picker, dictation from any wider pane — and Send fits with room to-// spare at any width the layout tree allows (~74 all-in).+// spare for compact desktop targets (~74 all-in). useComposerMetrics budgets+// larger touch tokens separately and puts menu/Send on separate rows below+// the two-target floor, retaining their 44px hit areas.export const COMPOSER_MINIMAL_PX = 180// A single editor line is ~28px (--composer-input-min-height 1.625rem + 0.5remdiff --git a/apps/desktop/src/app/chat/composer/controls.tsx b/apps/desktop/src/app/chat/composer/controls.tsxindex 5444cce0efe..c82815a139d 100644--- a/apps/desktop/src/app/chat/composer/controls.tsx+++ b/apps/desktop/src/app/chat/composer/controls.tsx@@ -24,6 +24,10 @@ import { VoiceMenu } from './voice-menu'// for these here, and the row is where they read as belonging.export { ACTIVE_ICON_BTN, GHOST_ICON_BTN, ICON_BTN, PRIMARY_ICON_BTN } from './control-classes'+// iOS fires mousedown after touchend, and its default blurs the editor before+// submit runs. Keep focus where it was so a send leaves the keyboard as it was.+const keepEditorFocus = (event: { preventDefault: () => void }) => event.preventDefault()+interface ConversationProps {active: booleanlevel: number@@ -124,7 +128,10 @@ export function ComposerControls({)return (- <div className="flex min-w-0 shrink items-center gap-(--composer-control-gap)">+ <div+ className="flex min-w-0 shrink items-center justify-end gap-(--composer-control-gap)"+ style={{ flexWrap: minimal ? 'wrap' : undefined }}+ >{minimal ? null : (<>{hideModelPill ? null : (@@ -144,6 +151,7 @@ export function ComposerControls({className={GHOST_ICON_BTN}disabled={disabled}onClick={onQueue}+ onMouseDown={keepEditorFocus}size="icon"type="button"variant="ghost"@@ -170,6 +178,7 @@ export function ComposerControls({className={PRIMARY_ICON_BTN}disabled={disabled || !canSubmit}onClick={() => recordAction(showStop ? 'composer.cancel' : 'composer.send', 'click')}+ onMouseDown={keepEditorFocus}type="submit">{showStop ? (diff --git a/apps/desktop/src/app/chat/composer/floating-target-media.test.ts b/apps/desktop/src/app/chat/composer/floating-target-media.test.tsnew file mode 100644index 00000000000..8ec36c9196f--- /dev/null+++ b/apps/desktop/src/app/chat/composer/floating-target-media.test.ts@@ -0,0 +1,53 @@+// @vitest-environment jsdom+import { afterEach, expect, it, vi } from 'vitest'++import { registerFloatingComposer } from './floating-target'+import { focusComposerInput } from './focus'++let unregister: (() => void) | undefined++afterEach(() => {+ unregister?.()+ unregister = undefined+ globalThis.document.body.innerHTML = ''+ globalThis.window.getSelection()?.removeAllRanges()+ vi.useRealTimers()+})++it.each(['audio', 'video'])('leaves native %s focus with the media controls until a new composer request', tag => {+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout', 'requestAnimationFrame', 'cancelAnimationFrame'] })+ const surface = globalThis.document.createElement('div')+ surface.dataset.chatSurface = ''+ surface.dataset.composerSurfaceId = 'media-owner'+ const media = globalThis.document.createElement(tag)+ media.setAttribute('controls', '')+ media.tabIndex = 0+ const host = globalThis.document.createElement('div')+ host.dataset.composerOwner = 'media-owner'+ const editor = globalThis.document.createElement('div')+ editor.dataset.slot = 'composer-rich-input'+ editor.tabIndex = 0+ host.append(editor)+ surface.append(media, host)+ globalThis.document.body.append(surface)+ unregister = registerFloatingComposer('media-owner', { groupId: 'media-group', target: 'main' })+ const focusin = vi.fn()+ surface.addEventListener('focusin', focusin)++ // Moving directly from a blurred composer to the native controls queues+ // composer retries before the same pointer gesture gives media focus.+ media.dispatchEvent(new PointerEvent('pointermove', { bubbles: true, pointerType: 'mouse', buttons: 0, clientX: 50, clientY: 61 }))+ expect(globalThis.document.activeElement).toBe(editor)+ focusin.mockClear()+ media.focus()+ expect(globalThis.document.activeElement).toBe(media)+ expect(focusin).toHaveBeenCalledTimes(1)+ vi.runAllTimers()+ expect(globalThis.document.activeElement).toBe(media)+ media.dispatchEvent(new PointerEvent('pointermove', { bubbles: true, pointerType: 'mouse', buttons: 0, clientX: 52, clientY: 63 }))+ expect(globalThis.document.activeElement).toBe(media)++ focusComposerInput(editor)+ vi.runAllTimers()+ expect(globalThis.document.activeElement).toBe(editor)+})diff --git a/apps/desktop/src/app/chat/composer/floating-target-selection-guard.test.ts b/apps/desktop/src/app/chat/composer/floating-target-selection-guard.test.tsindex bc8d5edf04d..830db105938 100644--- a/apps/desktop/src/app/chat/composer/floating-target-selection-guard.test.ts+++ b/apps/desktop/src/app/chat/composer/floating-target-selection-guard.test.ts@@ -87,4 +87,19 @@ describe('floating composer focus-follow vs transcript selection', () => {expect(document.activeElement).toBe(editor)})++ it.each(['touch', 'pen'])('keeps %s transcript gestures from focusing the composer', pointerType => {+ const { button, editor } = mount()+ unregister = registerFloatingComposer('surface-1', { groupId: 'g1', target: 'main' })++ button.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true, pointerType, clientX: 12, clientY: 20 }))+ button.dispatchEvent(new PointerEvent('pointermove', { bubbles: true, pointerType, buttons: 0, clientX: 13, clientY: 21 }))+ button.dispatchEvent(new PointerEvent('pointerup', { bubbles: true, pointerType }))+ expect(document.activeElement).not.toBe(editor)++ // Native focus from an intentional input tap must still be accepted.+ editor.dispatchEvent(new PointerEvent('pointerdown', { bubbles: true, pointerType }))+ editor.focus()+ expect(document.activeElement).toBe(editor)+ })})diff --git a/apps/desktop/src/app/chat/composer/floating-target.ts b/apps/desktop/src/app/chat/composer/floating-target.tsindex d1b55808f8b..34d8cd884da 100644--- a/apps/desktop/src/app/chat/composer/floating-target.ts+++ b/apps/desktop/src/app/chat/composer/floating-target.ts@@ -2,6 +2,7 @@ import { flushSync } from 'react-dom'import { $activeTreeGroup, $hoveredTreeGroup, noteActiveTreeGroup } from '@/components/pane-shell/tree/store'import { isEditableTarget, OVERLAY_SURFACE } from '@/lib/keybinds/combo'+import { isTouchInteraction } from '@/lib/touch-interaction'import { $composerPopout } from '@/store/composer-popout'import { $floatingComposerOwner, type FloatingComposerOwner } from './floating-state'@@ -87,7 +88,7 @@ function selectionOutsideComposer(): boolean {function focusSelectedComposer() {const owner = $floatingComposerOwner.get()- if (!owner || selectionOutsideComposer() || inFloatingLayer(document.activeElement)) {+ if (!owner || isTouchInteraction() || selectionOutsideComposer() || inFloatingLayer(document.activeElement)) {return}@@ -187,7 +188,7 @@ function trackPointer(event: PointerEvent) {active.dataset.slot === 'composer-rich-input' &&active.closest<HTMLElement>('[data-composer-owner]')?.dataset.composerOwner === id- if (event.type === 'pointermove' && !alreadyTyping && !keepsOwnFocus(active)) {+ if (event.type === 'pointermove' && !isTouchInteraction(event) && !alreadyTyping && !keepsOwnFocus(active)) {focusSelectedComposer()}}@@ -218,7 +219,7 @@ function trackFocus(event: FocusEvent) {// A delayed focus/restore isn't a navigation gesture. A clicked control,// keyboard Tab, or the inline edit opened by a bubble click still keeps its// normal focus, without redirecting to the input.- if (keyboardNavigation || keepsOwnFocus(target) || (pointerDownTarget && target.contains(pointerDownTarget))) {+ if (isTouchInteraction() || keyboardNavigation || keepsOwnFocus(target) || (pointerDownTarget && target.contains(pointerDownTarget))) {flushSync(() => selectSurface(id))} else {// A refused redirect leaves focus where it landed: that element's focusindiff --git a/apps/desktop/src/app/chat/composer/focus.ts b/apps/desktop/src/app/chat/composer/focus.tsindex 3c7f5a20da8..fe0a112409e 100644--- a/apps/desktop/src/app/chat/composer/focus.ts+++ b/apps/desktop/src/app/chat/composer/focus.ts@@ -764,9 +764,20 @@ export const focusComposerInput = (el: HTMLElement | null) => {el.focus({ preventScroll: true })}+ const retry = () => {+ // A native media control may take focus after the initial pointer move.+ // Its newer focus wins over these queued retries; a fresh explicit+ // composer request still gets the synchronous focus call below.+ if (document.activeElement instanceof HTMLMediaElement) {+ return+ }++ focus()+ }+focus()- window.requestAnimationFrame(focus)- window.setTimeout(focus, 0)+ window.requestAnimationFrame(retry)+ window.setTimeout(retry, 0)}/** Drop focus from the main composer input (status-stack chrome, sidebar, etc.).diff --git a/apps/desktop/src/app/chat/composer/hooks/use-composer-draft.test.tsx b/apps/desktop/src/app/chat/composer/hooks/use-composer-draft.test.tsxindex fccec70b547..814e5e2537c 100644--- a/apps/desktop/src/app/chat/composer/hooks/use-composer-draft.test.tsx+++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-draft.test.tsx@@ -1,6 +1,6 @@import { act, cleanup, render, waitFor } from '@testing-library/react'import { useLayoutEffect } from 'react'-import { afterEach, describe, expect, it, vi } from 'vitest'+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { PaneVisibleContext } from '@/components/pane-shell/pane-visibility'import {@@ -173,7 +173,19 @@ describe('useComposerDraft — attachment scope stays coherent with the committe})it('carries a pre-session draft onto the session the fresh chat is re-homed to, before its runtime id is known', () => {- const preSessionAttachment: ComposerAttachment = { id: 'file:new', kind: 'file', label: 'new.txt' }+ const preSessionAttachment: ComposerAttachment = {+ id: 'file:new',+ kind: 'file',+ label: 'new.txt',+ path: '/srv/hermes/profiles/owner/uploads/new.txt',+ stagedUpload: {+ install_id: '11111111111111111111111111111111',+ path: '/srv/hermes/profiles/owner/uploads/new.txt',+ profile_home: '/srv/hermes/profiles/owner'+ },+ titlePreview: 'Pasted text used to title the new session'+ }+stashSessionDraft(null, 'do not lose this draft', [preSessionAttachment])const { rerender } = render(@@ -796,3 +808,57 @@ describe('useComposerDraft — a hidden keep-alive tab never auto-focuses its coforeground.editor.remove()})})++describe('useComposerDraft — touch never re-enters the editor on its own', () => {+ let draft!: ReturnType<typeof useComposerDraft>++ function TouchDraft({ disabled = false, sessionId }: { disabled?: boolean; sessionId: string }) {+ draft = useComposerDraft({+ activeQueueSessionKey: sessionId,+ focusKey: null,+ inputDisabled: disabled,+ queueEditRef: { current: null },+ sessionId+ })++ return <div contentEditable data-slot="composer-rich-input" ref={draft.editorRef} tabIndex={0} />+ }++ beforeEach(() => {+ vi.stubGlobal('matchMedia', vi.fn().mockReturnValue({ matches: true }))+ })++ afterEach(() => {+ cleanup()+ clearSessionDraft('touch-focus')+ clearSessionDraft('touch-clear')+ mainComposerScope.clear()+ markActiveComposer('main')+ vi.unstubAllGlobals()+ })++ it('keeps touch mount and turn completion from focusing the editor while accepting deliberate focus', () => {+ const { rerender } = render(<TouchDraft sessionId="touch-focus" />)+ expect(globalThis.document.activeElement).not.toBe(draft.editorRef.current)+ rerender(<TouchDraft disabled={true} sessionId="touch-focus" />)+ rerender(<TouchDraft sessionId="touch-focus" />)+ expect(globalThis.document.activeElement).not.toBe(draft.editorRef.current)+ act(() => draft.focusInput())+ expect(globalThis.document.activeElement).toBe(draft.editorRef.current)+ })++ // iOS treats a selection placed in a contenteditable during a tap as focus,+ // so clearing after Send must not put the caret back into a blurred editor.+ it('on touch, clears a sent draft without re-entering an editor whose keyboard was put away', () => {+ render(<TouchDraft sessionId="touch-clear" />)+ expect(getActiveComposer()).toBe('main')+ window.getSelection()?.removeAllRanges()++ act(() => draft.clearDraft())+ expect(window.getSelection()?.rangeCount).toBe(0)++ act(() => draft.focusInput())+ act(() => draft.clearDraft())+ expect(draft.editorRef.current?.contains(window.getSelection()?.anchorNode ?? null)).toBe(true)+ })+})diff --git a/apps/desktop/src/app/chat/composer/hooks/use-composer-draft.ts b/apps/desktop/src/app/chat/composer/hooks/use-composer-draft.tsindex f88f2267913..7550ceddc02 100644--- a/apps/desktop/src/app/chat/composer/hooks/use-composer-draft.ts+++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-draft.ts@@ -4,6 +4,7 @@ import { type RefObject, useCallback, useEffect, useLayoutEffect, useRef, useStaimport { isElementInHiddenPane } from '@/components/pane-shell/pane-visibility'import { sanitizeComposerInput } from '@/lib/composer-input-sanitize'+import { isTouchInteraction } from '@/lib/touch-interaction'import { useStoreSelector } from '@/lib/use-session-slice'import {adoptGoneSessionDraft,@@ -238,9 +239,15 @@ export function useComposerDraft({// stack, so tiles, pop-outs, and secondary windows still auto-focus.useEffect(() => {if (!inputDisabled && paneVisible && !floating) {- focusInput()+ // A tab becoming visible or a turn finishing is not a request to open+ // a phone keyboard. Explicit focus requests below still focus normally.+ if (isTouchInteraction()) {+ markActiveComposer(target)+ } else {+ focusInput()+ }}- }, [floating, focusInput, focusKey, inputDisabled, paneVisible])+ }, [floating, focusInput, focusKey, inputDisabled, paneVisible, target])const previousFocusRequest = useRef(focusRequestId)// eslint-disable-next-line no-restricted-syntax -- handled request token, not a mirrored atom@@ -404,7 +411,14 @@ export function useComposerDraft({if (editorRef.current) {renderComposerContents(editorRef.current, '')- if (visibleRef.current && getActiveComposer() === target && !isElementInHiddenPane(editorRef.current)) {+ // A caret placed inside a send tap focuses the editor, and on a phone+ // raises the keyboard the user put away. Touch keeps it only if focused.+ if (+ visibleRef.current &&+ getActiveComposer() === target &&+ !isElementInHiddenPane(editorRef.current) &&+ (!isTouchInteraction() || editorRef.current.contains(document.activeElement))+ ) {placeCaretEnd(editorRef.current)}}diff --git a/apps/desktop/src/app/chat/composer/hooks/use-composer-metrics.test.tsx b/apps/desktop/src/app/chat/composer/hooks/use-composer-metrics.test.tsxindex da9661c0fc0..a5e8ba864cb 100644--- a/apps/desktop/src/app/chat/composer/hooks/use-composer-metrics.test.tsx+++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-metrics.test.tsx@@ -4,6 +4,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { COMPOSER_HEIGHT_VAR, COMPOSER_SURFACE_HEIGHT_VAR } from '@/app/chat/surface-vars'+import { COMPOSER_MINIMAL_PX } from '../composer-utils'+import { useComposerMetrics } from './use-composer-metrics'vi.mock('@assistant-ui/react', () => ({@@ -56,18 +58,35 @@ const sized =ref.current = node}-function Harness({ dockHeight, surfaceHeight }: { dockHeight: number; surfaceHeight: number }) {+function Harness({+ dockHeight,+ surfaceHeight,+ width = 640+}: {+ dockHeight: number+ surfaceHeight: number+ width?: number+}) {const composerDockRef = useRef<HTMLDivElement | null>(null)const composerRef = useRef<HTMLFormElement | null>(null)const composerSurfaceRef = useRef<HTMLDivElement | null>(null)const editorRef = useRef<HTMLDivElement | null>(null)- useComposerMetrics({ composerDockRef, composerRef, composerSurfaceRef, editorRef, poppedOut: false })+ const fit = useComposerMetrics({ composerDockRef, composerRef, composerSurfaceRef, editorRef, poppedOut: false })return (<div data-chat-surface=""><div ref={sized(composerDockRef, dockHeight)}>- <form ref={composerRef}>+ <form+ ref={node => {+ composerRef.current = node++ if (node) {+ node.getBoundingClientRect = () => ({ width, height: surfaceHeight }) as DOMRect+ }+ }}+ >+ <output data-testid="fit">{JSON.stringify(fit)}</output><div ref={sized(composerSurfaceRef, surfaceHeight)}><div ref={editorRef} /></div>@@ -90,6 +109,35 @@ describe('useComposerMetrics — published clearance survives an effect replay',vi.unstubAllGlobals()})+ it('uses a single control column below the two-touch-target budget', () => {+ vi.spyOn(window, 'getComputedStyle').mockReturnValue({ getPropertyValue: () => '44px' } as unknown as CSSStyleDeclaration)+ const { getByTestId } = render(<Harness dockHeight={200} surfaceHeight={120} width={80} />)+ expect(JSON.parse(getByTestId('fit').textContent!)).toMatchObject({ minimal: true, singleColumn: true })+ vi.restoreAllMocks()+ })++ it('collapses extra controls earlier when touch targets consume more width', () => {+ const minimalAt = (controlPx: number) => {+ const style = vi.spyOn(window, 'getComputedStyle').mockReturnValue({+ getPropertyValue: (name: string) => (name === '--composer-control-size' ? `${controlPx}px` : '')+ } as unknown as CSSStyleDeclaration)++ // Just past the point where desktop-size controls still fit.+ const { getByTestId, unmount } = render(+ <Harness dockHeight={200} surfaceHeight={120} width={COMPOSER_MINIMAL_PX + 1} />+ )++ const { minimal } = JSON.parse(getByTestId('fit').textContent!) as { minimal: boolean }+ unmount()+ style.mockRestore()++ return minimal+ }++ expect(minimalAt(24)).toBe(false)+ expect(minimalAt(44)).toBe(true)+ })+it('republishes the dock height after StrictMode replays the cleanup', () => {// StrictMode replays every effect: mount → cleanup → mount. The cleanup// clears the surface vars; the replayed measurement must write them backdiff --git a/apps/desktop/src/app/chat/composer/hooks/use-composer-metrics.ts b/apps/desktop/src/app/chat/composer/hooks/use-composer-metrics.tsindex 644f0a30367..3300046aece 100644--- a/apps/desktop/src/app/chat/composer/hooks/use-composer-metrics.ts+++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-metrics.ts@@ -32,19 +32,31 @@ export interface ComposerFit {foldVoice: booleanminimal: booleantight: boolean+ singleColumn: boolean}-const ROOMY: ComposerFit = { compactPill: false, foldVoice: false, minimal: false, tight: false }+const ROOMY: ComposerFit = { compactPill: false, foldVoice: false, minimal: false, tight: false, singleColumn: false }-const fitForWidth = (width: number): ComposerFit => ({- compactPill: width < COMPOSER_COMPACT_PILL_PX,- foldVoice: width < COMPOSER_FOLD_VOICE_PX,- minimal: width < COMPOSER_MINIMAL_PX,- tight: width < COMPOSER_STACK_BREAKPOINT_PX-})+const fitForWidth = (width: number, controlSize: number): ComposerFit => {+ const growth = Math.max(0, controlSize - 24)++ return {+ compactPill: width < COMPOSER_COMPACT_PILL_PX + growth * 5,+ foldVoice: width < COMPOSER_FOLD_VOICE_PX + growth * 5,+ minimal: width < COMPOSER_MINIMAL_PX + growth * 3,+ tight: width < COMPOSER_STACK_BREAKPOINT_PX + growth * 5,+ // Two buttons + gap + surface padding + border. At the 80px pane floor+ // touch controls keep their hit size by occupying separate rows.+ singleColumn: width < controlSize * 2 + 24+ }+}const sameFit = (a: ComposerFit, b: ComposerFit) =>- a.compactPill === b.compactPill && a.foldVoice === b.foldVoice && a.minimal === b.minimal && a.tight === b.tight+ a.compactPill === b.compactPill &&+ a.foldVoice === b.foldVoice &&+ a.minimal === b.minimal &&+ a.tight === b.tight &&+ a.singleColumn === b.singleColumninterface UseComposerMetricsResult extends ComposerFit {stacked: boolean@@ -130,7 +142,13 @@ export function useComposerMetrics({const surfaceHeight = composerSurfaceRef.current?.getBoundingClientRect().heightif (width > 0) {- const nextFit = fitForWidth(width)+ const token = getComputedStyle(composer).getPropertyValue('--composer-control-size').trim()++ const size =+ parseFloat(token) *+ (token.endsWith('rem') ? parseFloat(getComputedStyle(document.documentElement).fontSize) : 1)++ const nextFit = fitForWidth(width, Number.isFinite(size) ? size : 24)if (!sameFit(nextFit, lastFitRef.current)) {lastFitRef.current = nextFit@@ -231,6 +249,7 @@ export function useComposerMetrics({foldVoice: fit.foldVoice || fit.minimal,minimal: fit.minimal,stacked: expanded || fit.tight,- tight: fit.tight+ tight: fit.tight,+ singleColumn: fit.singleColumn}}diff --git a/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.test.tsx b/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.test.tsxindex f56d2f4c6ac..0bb73681704 100644--- a/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.test.tsx+++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.test.tsx@@ -66,6 +66,7 @@ function renderSubmitHook({editor.dataset.slot = 'composer-rich-input'editor.textContent = textconst editorRef = { current: editor }+ const focusInput = vi.fn()const loadIntoComposer = vi.fn()const stashAt = vi.fn()const onCancel = vi.fn()@@ -122,7 +123,7 @@ function renderSubmitHook({drainNextQueued: vi.fn(async () => false),editorRef,exitQueuedEdit: vi.fn(() => false),- focusInput: vi.fn(),+ focusInput,inputDisabled,loadIntoComposer,onCancel,@@ -143,6 +144,8 @@ function renderSubmitHook({loadIntoComposer,stashAt,clearDraft,+ editor,+ focusInput,hook,onCancel,onSteer,@@ -593,6 +596,39 @@ describe('useComposerSubmit busy-turn routing', () => {})})+describe('useComposerSubmit keyboard after send', () => {+ afterEach(() => {+ cleanup()+ window.document.body.replaceChildren()+ vi.unstubAllGlobals()+ })++ // iOS raises the keyboard for a focus() inside the Send tap, covering the+ // reply just as it starts streaming.+ it.each([+ ['desktop', false, false, 1],+ ['touch with the keyboard up', true, true, 1],+ ['touch with the keyboard put away', true, false, 0]+ ])('refocuses the composer after a send on %s', async (_case, touch, editorFocused, focusCalls) => {+ vi.stubGlobal(+ 'matchMedia',+ vi.fn().mockReturnValue({ addEventListener: vi.fn(), matches: touch, removeEventListener: vi.fn() })+ )+ const { editor, focusInput, hook, onSubmit } = renderSubmitHook({ text: 'hello' })+ editor.tabIndex = 0+ window.document.body.append(editor)++ if (editorFocused) {+ editor.focus()+ }++ await act(async () => hook.result.current.submitDraft())++ expect(onSubmit).toHaveBeenCalledOnce()+ expect(focusInput).toHaveBeenCalledTimes(focusCalls)+ })+})+describe('useComposerSubmit with a clarify parked on the session', () => {// The clarify is a live server→client request: skipping it answers that// request frame (`{}`), not a `clarify.respond` RPC.diff --git a/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.ts b/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.tsindex dd1f256f25f..26ffde61ae7 100644--- a/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.ts+++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-submit.ts@@ -6,6 +6,7 @@ import { translateNow, useI18n } from '@/i18n'import { isSlashCommandText } from '@/lib/chat-runtime'import { isSideTaskSlashCommand } from '@/lib/desktop-slash-commands'import { triggerHaptic } from '@/lib/haptics'+import { isTouchInteraction } from '@/lib/touch-interaction'import type { BusyInputMode } from '@/store/busy-input-mode'import { hasClarifyRequest, skipClarifyRequest } from '@/store/clarify'import {@@ -247,6 +248,16 @@ export function useComposerSubmit({[activeQueueSessionKeyRef, inputDisabled, paneVisible, scope.target, sessionId, surfaceId])+ // A phone keyboard the user put away stays down after a send, so the reply+ // is readable; desktop always returns the caret to the composer.+ const editorHasFocus = () => Boolean(editorRef.current?.contains(document.activeElement))++ const refocusAfterSend = (editorHadFocus: boolean) => {+ if (editorHadFocus || !isTouchInteraction()) {+ focusInput()+ }+ }+// Returns false when the submit was refused and must not refocus the input.const submitWhileBusy = (text: string, payloadPresent: boolean, blockingPrompt: boolean) => {// Slash commands should execute immediately even while the agent is@@ -341,7 +352,6 @@ export function useComposerSubmit({triggerHaptic('submit')resetBrowseState(sessionId)clearDraft()- focusInput()return 'answered'}@@ -383,6 +393,8 @@ export function useComposerSubmit({return}+ const editorHadFocus = editorHasFocus()+// Source the text from the DOM editor, not React state. The AUI composer// state (`draft`) and the derived `hasComposerPayload` lag the DOM by a// render, so on fast typing or IME composition the final keystroke(s) may@@ -415,6 +427,8 @@ export function useComposerSubmit({const parked = answerParkedCardWithDraft(text, payloadPresent)if (parked === 'answered') {+ refocusAfterSend(editorHadFocus)+return}@@ -448,7 +462,7 @@ export function useComposerSubmit({dispatchSubmit(text, submittedAttachments, undefined, retry && { submission_id: retry.id })}- focusInput()+ refocusAfterSend(editorHadFocus)}// Redirect the live turn with a correction. The gateway either restarts the@@ -527,8 +541,9 @@ export function useComposerSubmit({return}+ const editorHadFocus = editorHasFocus()queueCurrentDraft()- focusInput()+ refocusAfterSend(editorHadFocus)}return { dispatchSubmit, queueDraft, steerDraft, submitDraft }diff --git a/apps/desktop/src/app/chat/composer/index.tsx b/apps/desktop/src/app/chat/composer/index.tsxindex aee9bf96c50..d71c45201cb 100644--- a/apps/desktop/src/app/chat/composer/index.tsx+++ b/apps/desktop/src/app/chat/composer/index.tsx@@ -119,6 +119,19 @@ import {} from './url-refs'import { VoiceActivity, VoicePlaybackActivity } from './voice-activity'+/** Grid areas for the menu / input / controls row: one row when roomy, input+ * above menu + controls when stacked, and one area per row once two touch-size+ * controls no longer fit side by side. */+function controlRowGridClass(singleColumn: boolean, stacked: boolean): string {+ if (singleColumn) {+ return 'grid-cols-[minmax(0,1fr)] gap-(--composer-row-gap) [grid-template-areas:"input"_"menu"_"controls"]'+ }++ return stacked+ ? 'grid-cols-[auto_1fr] gap-(--composer-row-gap) [grid-template-areas:"input_input"_"menu_controls"]'+ : 'grid-cols-[auto_1fr_auto] items-center gap-(--composer-control-gap) [grid-template-areas:"menu_input_controls"]'+}+export function ChatBar({busy,cwd,@@ -390,7 +403,7 @@ export function ChatBar({return onCancel()}, [activeQueueSessionKeyRef, onCancel])- const { compactPill, foldVoice, minimal, stacked } = useComposerMetrics({+ const { compactPill, foldVoice, minimal, stacked, singleColumn } = useComposerMetrics({composerDockRef,composerRef,composerSurfaceRef,@@ -1494,14 +1507,7 @@ export function ChatBar({<VoicePlaybackActivity />{queueEdit && editingQueuedPrompt && <QueuedEditBanner onExit={exitQueuedEdit} />}{attachments.length > 0 && <AttachmentList attachments={attachments} onRemove={onRemoveAttachment} />}- <div- className={cn(- 'grid w-full',- stacked- ? 'grid-cols-[auto_1fr] gap-(--composer-row-gap) [grid-template-areas:"input_input"_"menu_controls"]'- : 'grid-cols-[auto_1fr_auto] items-center gap-(--composer-control-gap) [grid-template-areas:"menu_input_controls"]'- )}- >+ <div className={cn('grid w-full', controlRowGridClass(singleColumn, stacked))}><div className="flex translate-y-[3px] items-start gap-(--composer-control-gap) self-start [grid-area:menu]">{contextMenu}<ContribSlot area={COMPOSER_AREAS.leading} />diff --git a/apps/desktop/src/app/chat/composer/start-voice-button.tsx b/apps/desktop/src/app/chat/composer/start-voice-button.tsxindex 888add695ad..ac86c460133 100644--- a/apps/desktop/src/app/chat/composer/start-voice-button.tsx+++ b/apps/desktop/src/app/chat/composer/start-voice-button.tsx@@ -56,7 +56,7 @@ export function StartVoiceButton({<DropdownMenuTrigger asChild><Buttonaria-label={t.composer.voiceEngine}- className={cn(GHOST_ICON_BTN, 'w-5 rounded-l-none p-0')}+ className={cn(GHOST_ICON_BTN, 'w-(--composer-voice-menu-size) rounded-l-none p-0')}disabled={disabled}size="icon"type="button"diff --git a/apps/desktop/src/app/chat/hooks/use-composer-actions.ts b/apps/desktop/src/app/chat/hooks/use-composer-actions.tsindex 74d57f04612..b0e87b8500a 100644--- a/apps/desktop/src/app/chat/hooks/use-composer-actions.ts+++ b/apps/desktop/src/app/chat/hooks/use-composer-actions.ts@@ -20,7 +20,7 @@ import {setComposerTerminalSelection,updateComposerAttachment} from '@/store/composer'-import { notify, notifyError } from '@/store/notifications'+import { notify, notifyError, readableError } from '@/store/notifications'import type { ImageDetachResponse } from '../../types'@@ -109,6 +109,37 @@ export interface DroppedFile {url?: string}+/** Resolve a native drop to a host-visible path, staging browser File bytes+ * when the shell cannot expose a native filesystem path. Shared by both the+ * main composer and message-edit composer so neither silently drops files.+ * Empty when there is nothing to stage; a rejected stage keeps the server's+ * or a proxy's reason (an nginx 413) for the caller to report. */+export async function stageDroppedFilePath(candidate: DroppedFile): Promise<string> {+ if (candidate.path) {+ return candidate.path+ }++ if (!candidate.file || !window.hermesDesktop?.stageFileForAttach) {+ return ''+ }++ return window.hermesDesktop.stageFileForAttach(candidate.file)+}++/** Stage a drop for the main composer's chips. A rejected stage keeps its+ * reason in the failure the drop warning shows, not a bare "Could not attach". */+async function stageDropForChip(candidate: DroppedFile, label: string): Promise<{ failure: string; path: string }> {+ const failure = `Could not attach ${label}`++ try {+ return { failure, path: await stageDroppedFilePath(candidate) }+ } catch (error) {+ const reason = readableError(error, '').message++ return { failure: reason ? `${failure}: ${reason}` : failure, path: '' }+ }+}+/** MIME emitted by in-app drag sources (project tree, gutter line numbers).* Payload is JSON `{ path; isDirectory?; line?; lineEnd? }[]`. */export const HERMES_PATHS_MIME = 'application/x-hermes-paths'@@ -414,7 +445,21 @@ export function useComposerActions({* attach paths funnel through here. */const attachToMain = useCallback((attachment: ComposerAttachment) => {- scope.add(attachment)+ const stagedUpload =+ attachment.kind === 'file' && attachment.path+ ? window.hermesDesktop?.getStagedFileForAttach?.(attachment.path)+ : undefined++ const displayName =+ attachment.kind === 'file' && attachment.path && attachment.label === pathLabel(attachment.path)+ ? window.hermesDesktop?.getStagedFileDisplayName?.(attachment.path)+ : undefined++ scope.add({+ ...attachment,+ ...(stagedUpload ? { stagedUpload } : {}),+ ...(displayName ? { label: displayName } : {})+ })requestComposerFocus(scope.target)},[scope]@@ -811,13 +856,16 @@ export function useComposerActions({continue}- if (filePath && attachContextFilePath(filePath)) {+ // The resolved native path wins; with none, the File bytes are staged.+ const staged = await stageDropForChip({ ...candidate, path: filePath }, file.name || 'file')++ if (staged.path && attachContextFilePath(staged.path)) {attached = truecontinue}- lastFailure = `Could not attach ${file.name || 'file'}`+ lastFailure = staged.failure}if (!attached && lastFailure) {diff --git a/apps/desktop/src/app/chat/right-rail/preview-artifact.test.tsx b/apps/desktop/src/app/chat/right-rail/preview-artifact.test.tsxindex 8c8aff2047d..cd9d8b256c3 100644--- a/apps/desktop/src/app/chat/right-rail/preview-artifact.test.tsx+++ b/apps/desktop/src/app/chat/right-rail/preview-artifact.test.tsx@@ -1,4 +1,4 @@-import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'import { afterEach, describe, expect, it, vi } from 'vitest'import { $artifactRegistry, $artifactVersionSelection, artifactPreviewTarget, upsertArtifact } from '@/store/artifacts'@@ -28,6 +28,7 @@ describe('ArtifactPreview', () => {cleanup()$artifactRegistry.set({})$artifactVersionSelection.set({})+ Reflect.deleteProperty(window, 'hermesDesktop')})it('renders html in a scripts-only sandboxed frame the parent app is unreachable from', async () => {@@ -42,6 +43,23 @@ describe('ArtifactPreview', () => {expect(frame.getAttribute('sandbox')).not.toContain('same-origin')})+ it('opens a browser-hosted HTML blob without corrupting it as a file URL', async () => {+ const openPreviewInBrowser = vi.fn().mockResolvedValue(undefined)+ window.hermesDesktop = {+ openExternal: vi.fn().mockResolvedValue(undefined),+ openPreviewInBrowser,+ saveImageBuffer: vi.fn().mockResolvedValue('blob:http://localhost/artifact')+ } as never+ const { artifactId } = register('Dashboard', 'html', '<h1>Hi</h1>')+ await renderArtifact(artifactId)++ fireEvent.click(screen.getByRole('button', { name: /open in browser/i }))++ await waitFor(() => {+ expect(openPreviewInBrowser).toHaveBeenCalledWith('blob:http://localhost/artifact')+ })+ })+it('strips scripts out of svg before it renders inline', async () => {const { artifactId } = register('Logo',diff --git a/apps/desktop/src/app/chat/right-rail/preview-artifact.tsx b/apps/desktop/src/app/chat/right-rail/preview-artifact.tsxindex 4322a985962..278bcfd1bc0 100644--- a/apps/desktop/src/app/chat/right-rail/preview-artifact.tsx+++ b/apps/desktop/src/app/chat/right-rail/preview-artifact.tsx@@ -8,6 +8,7 @@ import { useI18n } from '@/i18n'import { artifactDownloadName, type ArtifactKind } from '@/lib/artifact-detect'import { downloadTextFile } from '@/lib/download-text'import { ChevronLeft, ChevronRight, Download, ExternalLink } from '@/lib/icons'+import { pathToFileUrl } from '@/lib/local-preview'import { $artifactRegistry, $artifactVersionSelection, findArtifact, selectArtifactVersion } from '@/store/artifacts'import { notifyError } from '@/store/notifications'import type { PreviewTarget } from '@/store/preview'@@ -60,7 +61,7 @@ async function openHtmlInBrowser(content: string): Promise<void> {throw new Error('Could not write artifact file')}- const fileUrl = `file://${path.startsWith('/') ? '' : '/'}${path.replace(/\\/g, '/')}`+ const fileUrl = pathToFileUrl(path)if (bridge.openPreviewInBrowser) {await bridge.openPreviewInBrowser(fileUrl)diff --git a/apps/desktop/src/app/chat/right-rail/preview-browser-frame-hint.tsx b/apps/desktop/src/app/chat/right-rail/preview-browser-frame-hint.tsxnew file mode 100644index 00000000000..a665cac2dd5--- /dev/null+++ b/apps/desktop/src/app/chat/right-rail/preview-browser-frame-hint.tsx@@ -0,0 +1,38 @@+import { Button } from '@/components/ui/button'+import { Tip } from '@/components/ui/tooltip'+import { useI18n } from '@/i18n'+import { ExternalLink } from '@/lib/icons'+import { openPreviewTargetInBrowser } from '@/lib/local-preview'+import { notifyError } from '@/store/notifications'+import type { PreviewTarget } from '@/store/preview'++interface PreviewBrowserFrameHintProps {+ target: PreviewTarget+}++/** Above the browser-hosted preview iframe. Framing denials can still fire+ * load, and cross-origin navigation is private to the frame, so the pane+ * cannot tell a blocked page from a loaded one: always offer the original URL. */+export function PreviewBrowserFrameHint({ target }: PreviewBrowserFrameHintProps) {+ const { t } = useI18n()+ const copy = t.preview.web++ return (+ <div className="pointer-events-auto flex flex-wrap items-center gap-x-3 gap-y-1 px-3 py-2 text-xs text-(--ui-text-secondary)">+ <p className="min-w-0 flex-1">{copy.embeddedPreviewHint}</p>+ <Tip label={copy.openTarget(target.url)}>+ <Button+ onClick={() =>+ void openPreviewTargetInBrowser(target).catch(error => notifyError(error, t.preview.unavailable))+ }+ size="xs"+ type="button"+ variant="secondary"+ >+ <ExternalLink />+ {t.preview.openInBrowser}+ </Button>+ </Tip>+ </div>+ )+}diff --git a/apps/desktop/src/app/chat/right-rail/preview-browser-frame.ts b/apps/desktop/src/app/chat/right-rail/preview-browser-frame.tsnew file mode 100644index 00000000000..47b5387683a--- /dev/null+++ b/apps/desktop/src/app/chat/right-rail/preview-browser-frame.ts@@ -0,0 +1,84 @@+/**+ * Browser-hosted Desktop has no Electron `<webview>`, so a live web preview+ * mounts a sandboxed iframe instead. The frame is opaque to this renderer+ * (no console, history, page reader, or input channel); the pane only+ * navigates it.+ */++import type { RefObject } from 'react'++/** The navigation calls the pane makes on its live preview surface — an+ * Electron webview or the browser-hosted iframe. */+export interface PreviewNavigationSurface {+ loadURL?: (url: string) => Promise<void>+ reload?: () => void+}++export interface BrowserPreviewFrameOptions {+ host: HTMLElement+ navigationRef: RefObject<PreviewNavigationSurface | null>+ /** The frame reported a load failure for `url`. */+ onError: (url: string) => void+ setCurrentUrl: (url: string) => void+ setLoading: (loading: boolean) => void+ url: string+}++/** Mount the frame into `host` and publish it as the pane's navigation+ * surface. Returns the mount effect's cleanup. */+export function mountBrowserPreviewFrame({+ host,+ navigationRef,+ onError,+ setCurrentUrl,+ setLoading,+ url+}: BrowserPreviewFrameOptions): () => void {+ const frame = document.createElement('iframe')+ frame.className = 'flex h-full w-full flex-1 border-0 bg-transparent'+ frame.referrerPolicy = 'no-referrer'+ frame.setAttribute('sandbox', 'allow-forms allow-scripts')+ // Browser-hosted previews deliberately grant no camera, microphone, or+ // clipboard capability. Fullscreen is the only delegated permission.+ frame.setAttribute('allow', 'fullscreen')+ frame.src = url++ const navigation: PreviewNavigationSurface = {+ loadURL: async next => {+ frame.src = next+ setCurrentUrl(next)+ setLoading(true)+ },+ reload: () => {+ const current = frame.src+ frame.src = 'about:blank'+ frame.src = current+ setLoading(true)+ }+ }++ const onLoad = () => {+ setCurrentUrl(frame.src)+ setLoading(false)+ }++ const onFrameError = () => {+ onError(frame.src || url)+ setLoading(false)+ }++ frame.addEventListener('load', onLoad)+ frame.addEventListener('error', onFrameError)+ host.appendChild(frame)+ navigationRef.current = navigation++ return () => {+ if (navigationRef.current === navigation) {+ navigationRef.current = null+ }++ frame.removeEventListener('load', onLoad)+ frame.removeEventListener('error', onFrameError)+ frame.remove()+ }+}diff --git a/apps/desktop/src/app/chat/right-rail/preview-drive-channels.ts b/apps/desktop/src/app/chat/right-rail/preview-drive-channels.tsnew file mode 100644index 00000000000..8a4ad7df6da--- /dev/null+++ b/apps/desktop/src/app/chat/right-rail/preview-drive-channels.ts@@ -0,0 +1,80 @@+/**+ * The channels the agent acts on a live preview page through, published per+ * tab while the pane's surface is an Electron `<webview>`: the script runner+ * and the trusted-input channel (preview-act.ts drives the page with both).+ * The browser-hosted iframe is opaque to this renderer, so it publishes none.+ */++import { type RefObject, useEffect } from 'react'++import { isElementInHiddenPane } from '@/components/pane-shell/pane-visibility'++import { type PreviewInputEvent, registerPreviewInput, toWebviewInputSpace } from './preview-input'+import { registerPreviewScriptRunner } from './preview-script-runner'++export type PreviewDriveGuest = HTMLElement & {+ executeJavaScript?: (code: string) => Promise<unknown>+ getZoomFactor?: () => number+ sendInputEvent?: (event: PreviewInputEvent) => void+}++export function usePreviewDriveChannels(+ webviewRef: RefObject<null | PreviewDriveGuest>,+ tabId: string | undefined,+ usesWebview: boolean+) {+ // Publish the SCRIPT runner for this tab: the one channel into the guest+ // page, shared by the tour tool (injected driver.js walkthroughs) and the+ // drive_preview tool (clicking, typing, scrolling the page the user sees).+ useEffect(() => {+ if (!usesWebview || !tabId) {+ return+ }++ return registerPreviewScriptRunner(tabId, async code => {+ const webview = webviewRef.current++ if (!webview?.executeJavaScript) {+ throw new Error('preview webview is not ready')+ }++ return webview.executeJavaScript(code)+ })+ }, [tabId, usesWebview, webviewRef])++ // Publish the INPUT channel for this tab. Same idea as the script runner, but+ // it carries real Chromium input rather than script — the agent's clicks and+ // keystrokes arrive as trusted events, so the page hovers, focuses and reacts+ // exactly as it would under a human hand.+ useEffect(() => {+ if (!usesWebview || !tabId) {+ return+ }++ return registerPreviewInput(tabId, {+ focus: () => {+ const webview = webviewRef.current++ // Trusted input still reaches the guest while hidden. Focusing the+ // webview element would steal the host's composer focus even when inert.+ if (webview && !isElementInHiddenPane(webview)) {+ webview.focus?.()+ }+ },+ send: event => {+ const webview = webviewRef.current++ // Never optional-chain this call away: a missing method would make every+ // agent click a silent no-op that still reports success, because the+ // overlay and the read-back both run on the separate script channel.+ if (typeof webview?.sendInputEvent !== 'function') {+ throw new Error('preview webview cannot take input events')+ }++ // The guest keeps its own (per-host) zoom, which the act engine's CSS+ // measurements do not include — ask the webview, not the window.+ webview.sendInputEvent(toWebviewInputSpace(event, webview.getZoomFactor?.()))+ }+ })+ }, [tabId, usesWebview, webviewRef])+}diff --git a/apps/desktop/src/app/chat/right-rail/preview-pane.test.tsx b/apps/desktop/src/app/chat/right-rail/preview-pane.test.tsxindex d5f0cd7bd20..cb5648ee8dd 100644--- a/apps/desktop/src/app/chat/right-rail/preview-pane.test.tsx+++ b/apps/desktop/src/app/chat/right-rail/preview-pane.test.tsx@@ -2,14 +2,19 @@ import { act, cleanup, fireEvent, render, waitFor } from '@testing-library/reactimport { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { onComposerAttachImagesRequest } from '@/app/chat/composer/focus'-import { PaneVisibleContext } from '@/components/pane-shell/pane-visibility'+import { PANE_HIDDEN_ATTR, PaneVisibleContext } from '@/components/pane-shell/pane-visibility'import { setTreePaneParked } from '@/components/pane-shell/tree/parked-panes'+import { $rightRailActiveTabId } from '@/store/layout'import { $previewTabs, closeRightRail, openPreview, previewTabId } from '@/store/preview'import { $connection, $selectedStoredSessionId } from '@/store/session'import { PreviewTilePane } from './preview'import { forgetPreviewConsole, previewConsoleState } from './preview-console-store'+import { activePreviewInput } from './preview-input'+import { activePreviewNav } from './preview-nav'import { PreviewPane } from './preview-pane'+import { readActivePreview } from './preview-reader'+import { activePreviewScriptRunner } from './preview-script-runner'// The consent dialog has its own test file and needs a QueryClientProvider;// these tests exercise the pane's console/watch/webview wiring, not the@@ -45,6 +50,9 @@ describe('PreviewPane console state', () => {afterEach(() => {cleanup()+ globalThis.document.documentElement.removeAttribute('data-hermes-desktop-host')+ $previewTabs.set([])+ $rightRailActiveTabId.set(null)$connection.set(null)$selectedStoredSessionId.set(null)vi.unstubAllGlobals()@@ -123,6 +131,149 @@ describe('PreviewPane console state', () => {forgetPreviewConsole(tabId)})+ it('uses a capability-minimal sandboxed iframe in browser-hosted Desktop', async () => {+ globalThis.document.documentElement.dataset.hermesDesktopHost = 'browser'++ const target = {+ kind: 'url' as const,+ label: 'Preview',+ source: 'https://example.com',+ url: 'https://example.com'+ }++ const tabId = 'url:https://example.com' as const++ $previewTabs.set([{ id: tabId, target }])+ $rightRailActiveTabId.set(tabId)++ const rendered = render(<PreviewPane tabId={tabId} target={target} />)++ const frame = rendered.container.querySelector('iframe')++ expect(frame).toBeInstanceOf(HTMLIFrameElement)+ expect(rendered.container.querySelector('webview')).toBeNull()+ const sandbox = new Set(frame!.getAttribute('sandbox')!.split(/\s+/))+ expect(sandbox.has('allow-forms')).toBe(true)+ expect(sandbox.has('allow-scripts')).toBe(true)+ expect(sandbox.has('allow-popups')).toBe(false)+ expect(sandbox.has('allow-popups-to-escape-sandbox')).toBe(false)+ expect(sandbox.has('allow-top-navigation')).toBe(false)+ expect(sandbox.has('allow-same-origin')).toBe(false)+ expect(frame?.getAttribute('allow')).toBe('fullscreen')+ expect(frame?.getAttribute('allow')).not.toMatch(/camera|clipboard|microphone/)+ expect(rendered.container.querySelector('[data-preview-browser]')).toBeNull()+ expect(rendered.queryByRole('textbox', { name: 'Address' })).toBeNull()+ expect(rendered.queryByRole('button', { name: 'Back' })).toBeNull()+ expect(rendered.queryByRole('button', { name: /DevTools/i })).toBeNull()+ expect(rendered.queryByRole('button', { name: /console/i })).toBeNull()+ expect(activePreviewNav()).toBeNull()+ expect(activePreviewScriptRunner()).toBeNull()+ expect(activePreviewInput()).toBeNull()+ await expect(readActivePreview()).resolves.toMatchObject({+ text: '',+ url: 'https://example.com'+ })+ })++ it('reuses the browser iframe when a tab navigates to another target URL', () => {+ globalThis.document.documentElement.dataset.hermesDesktopHost = 'browser'++ const target = {+ kind: 'url' as const,+ label: 'Preview',+ source: 'https://example.com/one',+ url: 'https://example.com/one'+ }++ const rendered = render(<PreviewPane tabId="reuse-browser-frame" target={target} />)+ const frame = rendered.container.querySelector('iframe')!+ const sandbox = frame.getAttribute('sandbox')+ fireEvent.load(frame)++ rendered.rerender(+ <PreviewPane+ tabId="reuse-browser-frame"+ target={{ ...target, source: 'https://example.com/two', url: 'https://example.com/two' }}+ />+ )++ expect(rendered.container.querySelector('iframe')).toBe(frame)+ expect(frame.src).toBe('https://example.com/two')+ // Navigating never widens the sandbox the capability test above pins.+ expect(sandbox).toBeTruthy()+ expect(frame.getAttribute('sandbox')).toBe(sandbox)+ expect(rendered.container.querySelector('webview')).toBeNull()+ })++ it('keeps native guest input available while hidden without focusing the guest', () => {+ const target = {+ kind: 'url' as const,+ label: 'Preview',+ source: 'https://example.com',+ url: 'https://example.com'+ }++ const tabId = 'url:https://example.com' as const++ $previewTabs.set([{ id: tabId, target }])+ $rightRailActiveTabId.set(tabId)+ const rendered = render(<PreviewPane tabId={tabId} target={target} />)+ const webview = rendered.container.querySelector('webview') as HTMLElement+ const focus = vi.spyOn(webview, 'focus')+ const sendInputEvent = vi.fn()+ Object.assign(webview, { sendInputEvent })++ const input = activePreviewInput()!+ input.focus()+ expect(focus).toHaveBeenCalledOnce()+ focus.mockClear()++ rendered.container.setAttribute(PANE_HIDDEN_ATTR, '')+ expect(activePreviewInput()).toBe(input)+ input.focus()+ const event = { type: 'mouseMove' as const, x: 12, y: 34 }+ input.send(event)+ expect(focus).not.toHaveBeenCalled()+ expect(sendInputEvent).toHaveBeenCalledExactlyOnceWith(event)+ expect(rendered.container.querySelector('webview')).toBe(webview)++ rendered.container.removeAttribute(PANE_HIDDEN_ATTR)+ input.focus()+ expect(focus).toHaveBeenCalledOnce()+ })++ it('keeps the original URL available outside an embedded browser preview after loading', () => {+ globalThis.document.documentElement.dataset.hermesDesktopHost = 'browser'+ const openPreviewInBrowser = vi.fn(async () => undefined)+ vi.stubGlobal('hermesDesktop', { openPreviewInBrowser })++ const target = {+ kind: 'url' as const,+ label: 'Preview',+ source: 'https://example.com/original',+ url: 'https://example.com/original'+ }++ const rendered = render(<PreviewPane embedded target={target} />)++ // Browsers also fire load when framing is denied. Recovery must stay+ // available without guessing whether the frame loaded successfully.+ fireEvent.load(rendered.container.querySelector('iframe')!)+ expect(openPreviewInBrowser).not.toHaveBeenCalled()++ fireEvent.click(rendered.getByRole('button', { name: 'Open in browser' }))+ expect(openPreviewInBrowser).toHaveBeenCalledExactlyOnceWith(target.url)++ const nextTarget = { ...target, source: 'https://example.org/next', url: 'https://example.org/next' }+ rendered.rerender(<PreviewPane embedded target={nextTarget} />)+ fireEvent.load(rendered.container.querySelector('iframe')!)+ expect(openPreviewInBrowser).toHaveBeenCalledTimes(1)++ fireEvent.click(rendered.getByRole('button', { name: 'Open in browser' }))+ expect(openPreviewInBrowser).toHaveBeenCalledTimes(2)+ expect(openPreviewInBrowser).toHaveBeenLastCalledWith(nextTarget.url)+ })+// The bar is chrome for a LIVE page. A file peek, an artifact, and remote// HTML in a sandboxed iframe have no webview to navigate.it('shows the browser bar only for a live webview preview', async () => {diff --git a/apps/desktop/src/app/chat/right-rail/preview-pane.tsx b/apps/desktop/src/app/chat/right-rail/preview-pane.tsxindex 0d47b089ee4..0f1f09b4d94 100644--- a/apps/desktop/src/app/chat/right-rail/preview-pane.tsx+++ b/apps/desktop/src/app/chat/right-rail/preview-pane.tsx@@ -9,13 +9,13 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react'import { requestComposerAttachImages, requestComposerFocus, requestComposerInsert } from '@/app/chat/composer/focus'import { openGuestContextMenu } from '@/app/context-menu/store'import { PanelEmpty } from '@/app/overlays/panel'-import { isElementInHiddenPane } from '@/components/pane-shell/pane-visibility'import { Tip } from '@/components/ui/tooltip'import { type Translations, useI18n } from '@/i18n'import { isDesktopFsRemoteMode, isReadFileErrorResult } from '@/lib/desktop-fs'import { guardGuestPointers } from '@/lib/guest-pointer-guard'import { isLoopbackPreviewUrl, openPreviewTargetInBrowser, remoteHtmlPreviewDocument } from '@/lib/local-preview'import { isRemoteGateway } from '@/lib/media'+import { isBrowserHostedDesktop } from '@/lib/platform'import {addAnnotatePin,beginAnnotateMode,@@ -60,6 +60,8 @@ import {} from './preview-annotate-host'import { ArtifactPreview } from './preview-artifact'import { PreviewBrowserBar } from './preview-browser-bar'+import { mountBrowserPreviewFrame, type PreviewNavigationSurface } from './preview-browser-frame'+import { PreviewBrowserFrameHint } from './preview-browser-frame-hint'import {clampConsoleHeight,compactUrl,@@ -69,38 +71,37 @@ import {} from './preview-console'import { type ConsoleEntry } from './preview-console-state'import { previewConsoleState } from './preview-console-store'+import { usePreviewDriveChannels } from './preview-drive-channels'import { LocalFilePreview, PreviewEmptyState, PreviewModeSwitcher } from './preview-file'import { usePreviewGuestOffscreen } from './preview-guest-offscreen'-import { type PreviewInputEvent, registerPreviewInput, toWebviewInputSpace } from './preview-input'+import { type PreviewInputEvent } from './preview-input'import { PREVIEW_BROWSER_ATTR, registerPreviewNav } from './preview-nav'import { registerPreviewPageReader } from './preview-reader'-import { registerPreviewScriptRunner } from './preview-script-runner'import { RealProfileConsentDialog } from './real-profile-consent-dialog'-type PreviewWebview = HTMLElement & {- canGoBack?: () => boolean- canGoForward?: () => boolean- closeDevTools?: () => void- copy?: () => void- cut?: () => void- executeJavaScript?: (code: string) => Promise<unknown>- getTitle?: () => string- getURL?: () => string- getWebContentsId?: () => number- goBack?: () => void- goForward?: () => void- inspectElement?: (x: number, y: number) => void- isDevToolsOpened?: () => boolean- loadURL?: (url: string) => Promise<void>- openDevTools?: () => void- paste?: () => void- reload?: () => void- reloadIgnoringCache?: () => void- replaceMisspelling?: (word: string) => void- selectAll?: () => void- sendInputEvent?: (event: PreviewInputEvent) => void- getZoomFactor?: () => number-}+type PreviewWebview = HTMLElement &+ PreviewNavigationSurface & {+ canGoBack?: () => boolean+ canGoForward?: () => boolean+ closeDevTools?: () => void+ copy?: () => void+ cut?: () => void+ executeJavaScript?: (code: string) => Promise<unknown>+ getTitle?: () => string+ getURL?: () => string+ getWebContentsId?: () => number+ goBack?: () => void+ goForward?: () => void+ inspectElement?: (x: number, y: number) => void+ isDevToolsOpened?: () => boolean+ openDevTools?: () => void+ paste?: () => void+ reloadIgnoringCache?: () => void+ replaceMisspelling?: (word: string) => void+ selectAll?: () => void+ sendInputEvent?: (event: PreviewInputEvent) => void+ getZoomFactor?: () => number+ }/** Electron throws if getURL/getTitle run before attach + dom-ready, or after* the guest has been removed. Optional chaining does not help — the method@@ -116,6 +117,17 @@ function guestPage(webview: PreviewWebview | null | undefined, fallbackUrl = '')}}+/** The live surface a web preview mounts: Electron's `<webview>`, or a plain+ * iframe when Desktop is served to a browser, which has no webview tag.+ * Remote HTML renders from its data URL instead, so it gets neither. */+function webPreviewSurface(isWebPreview: boolean, isRemoteHtml: boolean): 'iframe' | 'webview' | null {+ if (!isWebPreview || isRemoteHtml) {+ return null+ }++ return isBrowserHostedDesktop() ? 'iframe' : 'webview'+}+/** The raw Chromium params riding the webview tag's `context-menu` event. */interface GuestContextMenuParams {dictionarySuggestions?: string[]@@ -274,6 +286,7 @@ export function PreviewPane({const hostRef = useRef<HTMLDivElement | null>(null)const lastReloadRequestRef = useRef(reloadRequest)const lastRestartEventRef = useRef('')+ const navigationRef = useRef<PreviewNavigationSurface | null>(null)const previewContentRef = useRef<HTMLDivElement | null>(null)const webviewRef = useRef<PreviewWebview | null>(null)const noteGuestReady = usePreviewGuestOffscreen(webviewRef, tabId)@@ -349,6 +362,10 @@ export function PreviewPane({const isRemoteHtml = isRemoteHtmlTarget && renderMode !== 'source' && Boolean(target.dataUrl)+ const webSurface = webPreviewSurface(isWebPreview, isRemoteHtml)+ const usesBrowserIframe = webSurface === 'iframe'+ const usesWebview = webSurface === 'webview'+const remoteHtmlDocument = useMemo(() => (isRemoteHtml ? remoteHtmlPreviewDocument(target.dataUrl!) : null),[isRemoteHtml, target.dataUrl]@@ -438,7 +455,7 @@ export function PreviewPane({if (webviewRef.current?.reloadIgnoringCache) {webviewRef.current.reloadIgnoringCache()} else {- webviewRef.current?.reload?.()+ navigationRef.current?.reload?.()}}, [isWebPreview])@@ -763,7 +780,7 @@ export function PreviewPane({// rejected load is a real navigation failure the user has to see —// `did-fail-load` doesn't fire for every rejection (a bad scheme// rejects outright).- webviewRef.current?.loadURL?.(reached)+ navigationRef.current?.loadURL?.(reached)).catch((error: unknown) => {setLoadError({@@ -826,19 +843,19 @@ export function PreviewPane({// button over the frame). A gesture made INSIDE the page is answered by main// against the focused guest — this renderer can't see into a webview.useEffect(() => {- if (!isWebPreview || isRemoteHtml || !tabId) {+ if (!usesWebview || !tabId) {return}return registerPreviewNav(tabId, { back: goBack, forward: goForward, reload: reloadPreview })- }, [goBack, goForward, isRemoteHtml, isWebPreview, reloadPreview, tabId])+ }, [goBack, goForward, reloadPreview, tabId, usesWebview])// Publish the PAGE reader for this tab (the read_preview tool): extract the// rendered page's title + visible text from the webview. innerText (not// textContent) so hidden nodes and script/style bodies stay out, matching// what the user actually sees.useEffect(() => {- if (!isWebPreview || !tabId) {+ if (!usesWebview || !tabId) {return}@@ -856,62 +873,9 @@ export function PreviewPane({...guestPage(webview)}})- }, [isWebPreview, tabId])-- // Publish the SCRIPT runner for this tab: the one channel into the guest- // page, shared by the tour tool (injected driver.js walkthroughs) and the- // drive_preview tool (clicking, typing, scrolling the page the user sees).- useEffect(() => {- if (!isWebPreview || !tabId) {- return- }-- return registerPreviewScriptRunner(tabId, async code => {- const webview = webviewRef.current-- if (!webview?.executeJavaScript) {- throw new Error('preview webview is not ready')- }-- return webview.executeJavaScript(code)- })- }, [isWebPreview, tabId])-- // Publish the INPUT channel for this tab. Same idea as the script runner, but- // it carries real Chromium input rather than script — the agent's clicks and- // keystrokes arrive as trusted events, so the page hovers, focuses and reacts- // exactly as it would under a human hand.- useEffect(() => {- if (!isWebPreview || isRemoteHtml || !tabId) {- return- }-- return registerPreviewInput(tabId, {- focus: () => {- const webview = webviewRef.current-- // Trusted input still reaches the guest while hidden. Focusing the- // webview element would steal the host's composer focus even when inert.- if (webview && !isElementInHiddenPane(webview)) {- webview.focus?.()- }- },- send: event => {- const webview = webviewRef.current-- // Never optional-chain this call away: a missing method would make every- // agent click a silent no-op that still reports success, because the- // overlay and the read-back both run on the separate script channel.- if (typeof webview?.sendInputEvent !== 'function') {- throw new Error('preview webview cannot take input events')- }+ }, [tabId, usesWebview])- // The guest keeps its own (per-host) zoom, which the act engine's CSS- // measurements do not include — ask the webview, not the window.- webview.sendInputEvent(toWebviewInputSpace(event, webview.getZoomFactor?.()))- }- })- }, [isRemoteHtml, isWebPreview, tabId])+ usePreviewDriveChannels(webviewRef, tabId, usesWebview)// eslint-disable-next-line no-restricted-syntax -- legitimate non-atom ref write (see eslint rule comment)useEffect(() => {@@ -1119,6 +1083,7 @@ export function PreviewPane({const initialUrl = targetUrlRef.currenthost.replaceChildren()+ navigationRef.current = nullwebviewRef.current = nullsetCurrentUrl(initialUrl)setDevtoolsOpen(false)@@ -1133,6 +1098,19 @@ export function PreviewPane({return}+ // A browser host has no `<webview>` tag: past the guard above, this is+ // exactly `usesBrowserIframe`, so the iframe mounts instead.+ if (isBrowserHostedDesktop()) {+ return mountBrowserPreviewFrame({+ host,+ navigationRef,+ onError: url => setLoadError({ description: copy.unreachableDescription, url }),+ setCurrentUrl,+ setLoading,+ url: initialUrl+ })+ }+const webview = document.createElement('webview') as PreviewWebview// A page with no background of its own shows white, as in a browser and the remote HTML frame below.webview.className = 'flex h-full w-full flex-1 bg-white'@@ -1367,10 +1345,20 @@ export function PreviewPane({webview.addEventListener('dom-ready', armPrintGuard)webview.addEventListener('dom-ready', noteGuestReady)host.appendChild(webview)+ navigationRef.current = webviewwebviewRef.current = webviewreturn () => {annotateLoopRef.current += 1++ if (navigationRef.current === webview) {+ navigationRef.current = null+ }++ if (webviewRef.current === webview) {+ webviewRef.current = null+ }+webview.removeEventListener('console-message', onConsole)webview.removeEventListener('ipc-message', onGuestExternal)webview.removeEventListener('context-menu', onGuestContextMenu)@@ -1401,9 +1389,9 @@ export function PreviewPane({return}- const webview = webviewRef.current+ const navigation = navigationRef.current- if (!webview?.loadURL) {+ if (!navigation?.loadURL) {return}@@ -1427,7 +1415,7 @@ export function PreviewPane({setHistory({ back: false, forward: false })setLoading(true)setCurrentUrl(nextUrl)- void webview.loadURL?.(nextUrl)?.catch((error: unknown) => {+ void navigation.loadURL?.(nextUrl)?.catch((error: unknown) => {setLoadError({description: error instanceof Error ? error.message : copy.unreachableDescription,url: nextUrl@@ -1445,7 +1433,7 @@ export function PreviewPane({// guest page gets its own via `app-command` in main), and unhandled they// walk the HOST document's history.onMouseDown={event => {- if (event.button !== 3 && event.button !== 4) {+ if (!usesWebview || (event.button !== 3 && event.button !== 4)) {return}@@ -1457,7 +1445,7 @@ export function PreviewPane({goForward()}}}- {...(isWebPreview && !isRemoteHtml && tabId ? { [PREVIEW_BROWSER_ATTR]: tabId } : {})}+ {...(usesWebview && tabId ? { [PREVIEW_BROWSER_ATTR]: tabId } : {})}><div className="flex min-h-0 flex-1 flex-col overflow-hidden">{!embedded && (@@ -1491,7 +1479,9 @@ export function PreviewPane({/>)}- {isWebPreview && !isRemoteHtml && (+ {usesBrowserIframe && !isBlankPage && <PreviewBrowserFrameHint target={target} />}++ {usesWebview && (<PreviewBrowserBarannotateMode={annotate.mode}canGoBack={history.back}@@ -1592,7 +1582,7 @@ export function PreviewPane({/>) : null}- {isWebPreview && !isRemoteHtml && consoleOpen && (+ {usesWebview && consoleOpen && (<PreviewConsolePanelconsoleBodyRef={consoleBodyRef}consoleShouldStickRef={consoleShouldStickRef}diff --git a/apps/desktop/src/app/chat/session-tile-actions.ts b/apps/desktop/src/app/chat/session-tile-actions.tsindex 6920d24f161..1a55f969ac2 100644--- a/apps/desktop/src/app/chat/session-tile-actions.ts+++ b/apps/desktop/src/app/chat/session-tile-actions.ts@@ -273,6 +273,7 @@ export function useSessionTileActions({ requestGateway, runtimeId, scope, storedpath: next.path,mime: next.mime,refText: next.refText,+ stagedUpload: next.stagedUpload,uploadState: next.uploadState})} else {diff --git a/apps/desktop/src/app/chat/sidebar/profile-dropdown-switcher.tsx b/apps/desktop/src/app/chat/sidebar/profile-dropdown-switcher.tsxindex 57857f5af8e..d9f8b6f076c 100644--- a/apps/desktop/src/app/chat/sidebar/profile-dropdown-switcher.tsx+++ b/apps/desktop/src/app/chat/sidebar/profile-dropdown-switcher.tsx@@ -1,3 +1,4 @@+import { LOCAL_CONNECTION_ID } from '@hermes/shared'import { useStore } from '@nanostores/react'import { useEffect, useMemo, useRef, useState } from 'react'import { useNavigate } from 'react-router'@@ -51,17 +52,19 @@ import { PROFILES_ROUTE } from '../../routes'import { FleetGatewayMenuGroup } from './fleet-gateway-menu-group'import { buildRestGroups, type FleetAgent, fleetRouteKey } from './fleet-rail'import { useLocalDeviceSwitch } from './local-device-switch'+import { ProfileLaunchContextMenu } from './profile-launch-menu'import { useFleetRoster } from './use-fleet-roster'import { useProfilePrewarm } from './use-profile-prewarm'+import { useProfileRailRefreshOnActive } from './use-profile-rail-refresh-on-active'/*** The profile picker that sits beside the gateway switcher in the statusbar* while the colored rail is hidden — the same choices the rail offers (this* gateway's profiles, every other gateway's agents in fleet mode, new / import- * / manage) in a dropdown that reads like its neighbour. The rail keeps the- * gestures that need squares (drag-order, hold-to-recolor); this is the- * plain-dropdown door for people who run profiles as bots and don't want a- * strip of them.+ * / manage, right-click open-in-new-window / set-as-default) in a dropdown that+ * reads like its neighbour. The rail keeps the gestures that need squares+ * (drag-order, hold-to-recolor); this is the plain-dropdown door for people who+ * run profiles as bots and don't want a strip of them.*/export function ProfileSwitcher({ compact = false }: { compact?: boolean }) {const { t } = useI18n()@@ -81,6 +84,8 @@ export function ProfileSwitcher({ compact = false }: { compact?: boolean }) {const { dialog: localDeviceDialog, request: requestLocalDevice } = useLocalDeviceSwitch()useFleetRoster(multipleConnections)+ // Stands in for the rail, so it keeps the list fresh the same way.+ useProfileRailRefreshOnActive()// The `profile.create` hotkey bumps this request atom; the rail answers it// while mounted, so with the rail hidden this picker owns the dialog instead.@@ -105,6 +110,9 @@ export function ProfileSwitcher({ compact = false }: { compact?: boolean }) {[activeConnectionId, connections, multipleConnections, order, roster])+ // Launch actions name the route a pick would dial, as the rail's squares do:+ // named profiles on This device keep the legacy door (per-profile overrides).+ const namedConnectionId = activeConnectionId === LOCAL_CONNECTION_ID ? null : activeConnectionIdconst activeKey = normalizeProfileKey(gatewayProfile)const defaultProfile = profiles.find(profile => profile.is_default)@@ -207,6 +215,7 @@ export function ProfileSwitcher({ compact = false }: { compact?: boolean }) {{ordered.map(profile => (<ProfileItemcolor={resolveProfileColor(profile.name, colors)}+ connectionId={profile.is_default ? activeConnectionId : namedConnectionId}isDefault={profile.is_default}key={profile.name}label={profileLabel(profile)}@@ -230,6 +239,16 @@ export function ProfileSwitcher({ compact = false }: { compact?: boolean }) {key={group.connectionId}onSelect={switchToRest}slot="profile-switcher-gateway"+ wrapRow={(row, agent, label) => (+ <ProfileLaunchContextMenu+ connectionId={agent.connectionId}+ key={agent.profile}+ label={label}+ profile={agent.profile}+ >+ {row}+ </ProfileLaunchContextMenu>+ )}/>))}<DropdownMenuSeparator />@@ -262,31 +281,31 @@ export function ProfileSwitcher({ compact = false }: { compact?: boolean }) {)}-function ProfileItem({- color,- isDefault,- label,- name-}: {+interface ProfileItemProps {color: null | string+ connectionId: null | stringisDefault: booleanlabel: stringname: string-}) {+}++function ProfileItem({ color, connectionId, isDefault, label, name }: ProfileItemProps) {const { cancelPrewarm, notePointerMove, startPrewarm } = useProfilePrewarm(name, prewarmProfilePick)return (- <DropdownMenuRadioItem- className="min-w-0"- onPointerEnter={startPrewarm}- onPointerLeave={cancelPrewarm}- onPointerMove={notePointerMove}- value={name}- >- <span className="flex min-w-0 items-center gap-1.5">- <ProfileGlyph aria-hidden="true" color={color} isDefault={isDefault} name={name} />- <span className="truncate">{label}</span>- </span>- </DropdownMenuRadioItem>+ <ProfileLaunchContextMenu connectionId={connectionId} label={label} profile={name}>+ <DropdownMenuRadioItem+ className="min-w-0"+ onPointerEnter={startPrewarm}+ onPointerLeave={cancelPrewarm}+ onPointerMove={notePointerMove}+ value={name}+ >+ <span className="flex min-w-0 items-center gap-1.5">+ <ProfileGlyph aria-hidden="true" color={color} isDefault={isDefault} name={name} />+ <span className="truncate">{label}</span>+ </span>+ </DropdownMenuRadioItem>+ </ProfileLaunchContextMenu>)}diff --git a/apps/desktop/src/app/chat/sidebar/profile-switcher.tsx b/apps/desktop/src/app/chat/sidebar/profile-switcher.tsxindex 33ed7848cdc..4f0a2ba35b8 100644--- a/apps/desktop/src/app/chat/sidebar/profile-switcher.tsx+++ b/apps/desktop/src/app/chat/sidebar/profile-switcher.tsx@@ -50,6 +50,7 @@ import { type Translations, useI18n } from '@/i18n'import { sortConnectionsForDisplay } from '@/lib/connection-display'import { triggerHaptic } from '@/lib/haptics'import { Loader2 } from '@/lib/icons'+import { isBrowserHostedDesktop } from '@/lib/platform'import { PROFILE_SWATCHES, profileColorSoft, resolveProfileColor } from '@/lib/profile-color'import { profileShortLabel } from '@/lib/profile-short-label'import {@@ -118,6 +119,16 @@ const RAIL_GAP = 4 // px — matches gap-1 between squares.// menu. Drag-reorder and long-press-recolor live only on the squares path.const PROFILE_DROPDOWN_THRESHOLD = 13+// The Webapp always takes the dropdown: squares are a native-window gesture+// surface (drag, hold-to-recolor), and in a browser tab they read as chrome.+const ALWAYS_CONDENSED = isBrowserHostedDesktop()++// The threshold counts the whole fleet: fourteen squares are fourteen squares+// wherever they live.+function railCondensed(profileCount: number, restGroups: readonly FleetGroup[]): boolean {+ return ALWAYS_CONDENSED || profileCount + countRestAgents(restGroups) > PROFILE_DROPDOWN_THRESHOLD+}+// #91710: a profile that finished (or blocked, or is still working) while// another was selected carries an indicator on its rail square and dropdown// row. It paints the session status dot's own class for the same state, so a@@ -278,9 +289,7 @@ export function ProfileRail() {// Too many profiles for the square strip → collapse to the select. Declared// ahead of the wheel effect, which re-binds when the strip mounts/unmounts.- // The threshold counts the whole fleet: fourteen squares are fourteen- // squares wherever they live.- const condensed = profiles.length + countRestAgents(restGroups) > PROFILE_DROPDOWN_THRESHOLD+ const condensed = railCondensed(profiles.length, restGroups)const measureScroll = useCallback(() => {const el = scrollRef.currentdiff --git a/apps/desktop/src/app/context-menu/app-context-menu.test.tsx b/apps/desktop/src/app/context-menu/app-context-menu.test.tsxindex 82b40bde0f4..b22ec81f7d6 100644--- a/apps/desktop/src/app/context-menu/app-context-menu.test.tsx+++ b/apps/desktop/src/app/context-menu/app-context-menu.test.tsx@@ -1,4 +1,4 @@-import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'+import { cleanup, createEvent, fireEvent, render, screen, waitFor } from '@testing-library/react'import { MemoryRouter } from 'react-router'import { afterEach, describe, expect, it, vi } from 'vitest'@@ -24,7 +24,7 @@ const desktopWindow = window as unknown as { hermesDesktop?: Window['hermesDesktfunction installBridge(partial: Partial<Window['hermesDesktop']> = {}) {desktopWindow.hermesDesktop = {openExternal: vi.fn().mockResolvedValue(undefined),- writeClipboard: vi.fn().mockResolvedValue(undefined),+ writeClipboard: vi.fn().mockResolvedValue(true),...partial} as unknown as Window['hermesDesktop']}@@ -52,7 +52,9 @@ afterEach(() => {closeRightRail()cleanup()vi.restoreAllMocks()+ vi.unstubAllGlobals()document.body.innerHTML = ''+ delete window.document.documentElement.dataset.hermesDesktopHostdelete desktopWindow.hermesDesktop})@@ -94,6 +96,147 @@ describe('resolveDomTarget', () => {})describe('AppContextMenu', () => {+ it('leaves explicit row menus available on touch devices', () => {+ installBridge()+ window.document.documentElement.dataset.hermesDesktopHost = 'browser'+ vi.stubGlobal('matchMedia', vi.fn().mockReturnValue({ matches: true }))+ mountMenu()+ const host = attach('<div data-slot="context-menu-trigger">Profile row</div>')+ const rowMenu = vi.fn()+ host.addEventListener('contextmenu', rowMenu)+ fireEvent.contextMenu(host.firstElementChild!)+ expect(rowMenu).toHaveBeenCalledTimes(1)+ expect($contextMenu.get()).toBeNull()+ })+ it.each([+ ['message text', '<div data-slot="aui_assistant-message-content"><p>selectable content</p></div>', 'p'],+ ['a link', '<a href="https://example.com">selectable content</a>', 'a'],+ ['an editable', '<textarea>selectable content</textarea>', 'textarea']+ ])('preserves native touch long-press on %s before text selection exists', (_name, content, tag) => {+ installBridge()+ window.document.documentElement.dataset.hermesDesktopHost = 'browser'+ vi.stubGlobal('matchMedia', vi.fn().mockReturnValue({ matches: true }))+ mountMenu()++ const host = attach(`<div data-zone-body="test" data-slot="context-menu-trigger">${content}</div>`)++ const fallback = vi.fn()+ host.addEventListener('contextmenu', fallback)+ const event = createEvent.contextMenu(host.querySelector(tag)!, { bubbles: true, cancelable: true })+ fireEvent(host.querySelector(tag)!, event)+ expect(event.defaultPrevented).toBe(false)+ expect(fallback).not.toHaveBeenCalled()+ expect($contextMenu.get()).toBeNull()+ })+ describe.each(['browser', 'electron'])('%s host gesture ownership', hostKind => {+ it.each([+ ['chrome', '<p>plain chrome</p>', 'Settings'],+ ['terminal', '<div data-terminal=""><canvas></canvas></div>', 'Select all']+ ])('opens only the app menu for %s, preserving Electron native facts', async (_kind, html, label) => {+ installBridge()+ window.document.documentElement.dataset.hermesDesktopHost = hostKind+ mountMenu()+ const host = attach(html)+ const terminal = host.querySelector('[data-terminal]')++ const unregister = terminal+ ? registerTerminalContextMenu(terminal, {+ getSelection: () => '',+ paste: null,+ reload: vi.fn(),+ selectAll: vi.fn(),+ wordErase: null+ })+ : undefined++ const target = host.querySelector('canvas') ?? host.firstElementChild!+ const onTarget = vi.fn()++ target.addEventListener('contextmenu', onTarget)+ const event = createEvent.contextMenu(target)++ try {+ fireEvent(target, event)++ expect(await screen.findByText(label)).toBeTruthy()+ expect(onTarget).not.toHaveBeenCalled()+ expect(event.defaultPrevented).toBe(hostKind === 'browser')+ } finally {+ unregister?.()+ }+ })+ })++ // The skip-marked and radix-surface tests below cover these markers in+ // Electron; in the Webapp a late marker check would also cancel the native menu.+ it.each([HERMES_CONTEXT_MENU_TRIGGER_ATTR, 'data-slot="context-menu-trigger"', 'data-context-menu-skip'])(+ 'leaves the gesture untouched in the browser Webapp for a surface owning %s',+ marker => {+ installBridge()+ window.document.documentElement.dataset.hermesDesktopHost = 'browser'+ mountMenu()+ const host = attach(`<div ${marker}><span>owned surface</span></div>`)+ const target = host.querySelector('span')!+ const onTarget = vi.fn()++ target.addEventListener('contextmenu', onTarget)+ const event = createEvent.contextMenu(target)++ fireEvent(target, event)++ expect($contextMenu.get()).toBeNull()+ expect(onTarget).toHaveBeenCalledOnce()+ expect(event.defaultPrevented).toBe(false)+ }+ )++ it('leaves native media context menus untouched in the browser Webapp', () => {+ installBridge()+ window.document.documentElement.dataset.hermesDesktopHost = 'browser'+ mountMenu()+ const host = attach('<audio controls></audio>')+ const target = host.firstElementChild!+ const onTarget = vi.fn()++ target.addEventListener('contextmenu', onTarget)+ const event = createEvent.contextMenu(target)++ fireEvent(target, event)++ expect($contextMenu.get()).toBeNull()+ expect(onTarget).toHaveBeenCalledOnce()+ expect(event.defaultPrevented).toBe(false)+ })++ it('detects native media through the composed path', () => {+ installBridge()+ window.document.documentElement.dataset.hermesDesktopHost = 'browser'+ mountMenu()+ const host = attach('<div><video controls></video></div>')+ const target = host.firstElementChild!+ const video = target.firstElementChild!+ const event = createEvent.contextMenu(target)++ Object.defineProperty(event, 'composedPath', { value: () => [video, target, host, document.body, document] })+ fireEvent(target, event)++ expect($contextMenu.get()).toBeNull()+ expect(event.defaultPrevented).toBe(false)+ })++ it('keeps native media gestures unprevented in Electron', async () => {+ installBridge()+ window.document.documentElement.dataset.hermesDesktopHost = 'electron'+ mountMenu()+ const electronHost = attach('<video controls></video>')+ const electronEvent = createEvent.contextMenu(electronHost.firstElementChild!)++ fireEvent(electronHost.firstElementChild!, electronEvent)++ expect(await screen.findByText('Settings')).toBeTruthy()+ expect(electronEvent.defaultPrevented).toBe(false)+ })+it('opens the link menu on a chat link right-click', async () => {installBridge()mountMenu()@@ -160,7 +303,7 @@ describe('AppContextMenu', () => {it('offers the resolved copy only for loopback links on a remote gateway', async () => {$connection.set({ mode: 'remote' } as never)const reachPreviewUrl = vi.fn(async () => 'http://127.0.0.1:45173/')- const writeClipboard = vi.fn().mockResolvedValue(undefined)+ const writeClipboard = vi.fn().mockResolvedValue(true)installBridge({reachPreviewUrl: reachPreviewUrl as unknown as Window['hermesDesktop']['reachPreviewUrl'],diff --git a/apps/desktop/src/app/context-menu/app-context-menu.tsx b/apps/desktop/src/app/context-menu/app-context-menu.tsxindex e747313eb4f..27dcf7abe2a 100644--- a/apps/desktop/src/app/context-menu/app-context-menu.tsx+++ b/apps/desktop/src/app/context-menu/app-context-menu.tsx@@ -8,7 +8,6 @@ import { openStarMapNodeMenuFor } from '@/app/starmap/context-menu-handle'import { DROPDOWN_KIT } from '@/components/ui/actions-menu'import { Codicon } from '@/components/ui/codicon'import { HERMES_CONTEXT_MENU_TRIGGER_ATTR } from '@/components/ui/context-menu'-import { writeClipboardText } from '@/components/ui/copy-button'import {DropdownMenu,DropdownMenuContent,@@ -19,10 +18,13 @@ import {} from '@/components/ui/dropdown-menu'import { useContributions } from '@/contrib/react/use-contributions'import { type Translations, useI18n } from '@/i18n'+import { writeClipboardText } from '@/lib/clipboard'import { hostPathLabel, hudForcesNativeLinks, normalizeExternalUrl, openExternalLink } from '@/lib/external-link'import { formatCombo } from '@/lib/keybinds/combo'import { isRemoteGateway } from '@/lib/media'+import { isBrowserHostedDesktop } from '@/lib/platform'import { reachablePreviewUrl } from '@/lib/preview-reach'+import { isBrowserOwnedTouch } from '@/lib/touch-interaction'import { openPreview } from '@/store/preview'import { type ComposerMenuRow, resolveComposerMenuSections } from './composer-menu'@@ -55,6 +57,22 @@ const EDIT_SHORTCUTS = {selectAll: formatCombo('mod+a')} as const+function isNativeMediaContextMenu(event: MouseEvent): boolean {+ const path = typeof event.composedPath === 'function' ? event.composedPath() : []++ return [event.target, ...path].some(target => target instanceof HTMLMediaElement)+}++/** Take a gesture the app menu answers away from other renderer handlers,+ * cancelling the browser's native menu only where it would open alongside. */+function claimContextMenuGesture(event: MouseEvent) {+ if (isBrowserHostedDesktop()) {+ event.preventDefault()+ }++ event.stopPropagation()+}+function isLoopbackUrl(url: string): boolean {try {return LOOPBACK_HOST_RE.test(new URL(url).hostname)@@ -578,13 +596,20 @@ export function AppContextMenu() {)useEffect(() => {- // stopPropagation beats other renderer handlers; preventDefault is never- // called because Chromium emits the main-process context-menu event (the- // spellcheck + image-coordinate source) only for unprevented gestures —- // and with no Menu.popup anywhere, "default" means no menu at all.+ // Electron needs unprevented gestures for main-process spellcheck and+ // image coordinates. Webapp must cancel the browser's native menu when+ // we own the gesture, or it opens alongside the app menu.const onContextMenu = (event: MouseEvent) => {const element = event.target instanceof Element ? event.target : null+ // Stop pane/row fallback menus without cancelling the native menu.+ // Explicit app actions live in More.+ if (isBrowserOwnedTouch(event)) {+ event.stopPropagation()++ return+ }+const trigger = element?.closest(`[${HERMES_CONTEXT_MENU_TRIGGER_ATTR}], [data-slot="context-menu-trigger"]`)// Only the pane-body wrapper is a fallback menu. Explicit row, tab and@@ -593,6 +618,14 @@ export function AppContextMenu() {return}+ // Browser-owned media controls need their native context menu, including+ // save and picture-in-picture actions. Chromium can retarget a control+ // hit through the media element's UA shadow tree, so inspect the whole+ // composed path instead of relying only on event.target.+ if (isBrowserHostedDesktop() && isNativeMediaContextMenu(event)) {+ return+ }+// The Star Map owns node hits, but empty canvas space still reaches the// shell fallback below. A canvas-wide opt-out would lose that fallback.if (openStarMapNodeMenuFor(element, event.clientX, event.clientY)) {@@ -607,7 +640,7 @@ export function AppContextMenu() {const terminal = terminalMenuHandleFor(element)if (terminal) {- event.stopPropagation()+ claimContextMenuGesture(event)openTerminalContextMenu(event.clientX, event.clientY, terminal)return@@ -638,7 +671,7 @@ export function AppContextMenu() {return}- event.stopPropagation()+ claimContextMenuGesture(event)openDomContextMenu(event.clientX, event.clientY, target)}diff --git a/apps/desktop/src/app/context-menu/pane-context-menu.test.tsx b/apps/desktop/src/app/context-menu/pane-context-menu.test.tsxindex 672bb6a3898..2996502b5f6 100644--- a/apps/desktop/src/app/context-menu/pane-context-menu.test.tsx+++ b/apps/desktop/src/app/context-menu/pane-context-menu.test.tsx@@ -22,7 +22,7 @@ function setup() {})Object.defineProperty(window, 'hermesDesktop', {configurable: true,- value: { writeClipboard: vi.fn().mockResolvedValue(undefined) }+ value: { writeClipboard: vi.fn().mockResolvedValue(true) }})render(<MemoryRouter>diff --git a/apps/desktop/src/app/contrib/controller.tsx b/apps/desktop/src/app/contrib/controller.tsxindex 427c81f97c9..55c2b83e54f 100644--- a/apps/desktop/src/app/contrib/controller.tsx+++ b/apps/desktop/src/app/contrib/controller.tsx@@ -807,7 +807,7 @@ export function ContribController() {return (<SidebarProvider- className="h-screen min-h-0 flex-col bg-background"+ className="h-full min-h-0 flex-col bg-background"onOpenChange={setSidebarOpen}open={sidebarOpen}style={{ '--sidebar-width': '100%' } as CSSProperties}@@ -818,7 +818,7 @@ export function ContribController() {run in every window kind, so each shell mounts it. */}<PluginPreviewConsentDialog /><div- className="flex h-screen min-h-0 w-screen flex-col bg-(--ui-bg-chrome) text-(--ui-text-primary)"+ className="flex h-full min-h-0 w-screen flex-col bg-(--ui-bg-chrome) text-(--ui-text-primary)"// Window-glass hook: this div and the sidebar-wrapper above it are// the app shell's two full-window opaque painters; the// [data-hermes-glass] rules in styles.css clear them so the tintdiff --git a/apps/desktop/src/app/contrib/hooks/use-quick-entry-bridge.ts b/apps/desktop/src/app/contrib/hooks/use-quick-entry-bridge.tsindex e0ead6a2214..0d5fb4d66c4 100644--- a/apps/desktop/src/app/contrib/hooks/use-quick-entry-bridge.ts+++ b/apps/desktop/src/app/contrib/hooks/use-quick-entry-bridge.ts@@ -106,7 +106,7 @@ export function useQuickEntryBridge({ submitText, submitTextToNewSession }: Quic}acknowledged = true- window.hermesDesktop?.quickEntry.ackSubmit(correlationId, result)+ window.hermesDesktop?.quickEntry?.ackSubmit(correlationId, result)}if (target === QUICK_TARGET_NEW) {diff --git a/apps/desktop/src/app/contrib/wiring.tsx b/apps/desktop/src/app/contrib/wiring.tsxindex 954975fa63a..21b6b4345b9 100644--- a/apps/desktop/src/app/contrib/wiring.tsx+++ b/apps/desktop/src/app/contrib/wiring.tsx@@ -153,9 +153,11 @@ import {titlebarControlsPosition,titlebarControlsYNudge,titlebarToolsRightCss,- titlebarToolsWidthCss+ titlebarToolsWidthCss,+ TOUCH_TITLEBAR_HEIGHT} from '../shell/titlebar'import { TitlebarControls } from '../shell/titlebar-controls'+import { useTouchTitlebar } from '../shell/use-touch-titlebar'import { WslgWindowControls } from '../shell/wslg-window-controls'import { UpdatesOverlay } from '../updates-overlay'@@ -302,6 +304,23 @@ function useRecoveryRequestToasts(): void {}, [cronReviewRequest, navigate])}+// Where the fixed titlebar clusters sit (the same vars AppShell sets). Browser+// touch chrome pins them flush in its 44px band, at touch-target size.+function useTitlebarControlsVars(controlsPos: { left: number; top: number }): CSSProperties {+ const touchTitlebar = useTouchTitlebar()++ return {+ '--titlebar-controls-left': `${controlsPos.left}px`,+ '--titlebar-controls-top': `${touchTitlebar ? 0 : controlsPos.top}px`,+ ...(touchTitlebar+ ? {+ '--titlebar-control-size': `${TOUCH_TITLEBAR_HEIGHT}px`,+ '--titlebar-control-height': `${TOUCH_TITLEBAR_HEIGHT}px`+ }+ : {})+ } as CSSProperties+}+export function ContribWiring({ children }: { children: ReactNode }) {const queryClient = useQueryClient()const location = useLocation()@@ -1216,6 +1235,7 @@ export function ContribWiring({ children }: { children: ReactNode }) {const rightTitlebarTools = useTitlebarToolContributions('right')const connection = useStore($connection)const controlsPos = titlebarControlsPosition(connection?.windowButtonPosition, Boolean(connection?.isFullscreen))+ const controlsVars = useTitlebarControlsVars(controlsPos)// Windows/WSLg reserve native min/max/close on the right (AppShell parity:// prefer the live WCO measurement, fall back to the static reservation).const measuredOverlayWidth = useWindowControlsOverlayWidth()@@ -1255,8 +1275,7 @@ export function ContribWiring({ children }: { children: ReactNode }) {className="contents"style={{- '--titlebar-controls-left': `${controlsPos.left}px`,- '--titlebar-controls-top': `${controlsPos.top}px`,+ ...controlsVars,'--titlebar-controls-width': leftToolsWidth,'--titlebar-controls-y-nudge': titlebarControlsYNudge(titlebarChrome),'--titlebar-tools-right': titlebarToolsRight,diff --git a/apps/desktop/src/app/gateway/hooks/use-gateway-boot.test.tsx b/apps/desktop/src/app/gateway/hooks/use-gateway-boot.test.tsxindex c700f88a49a..daeac6dee40 100644--- a/apps/desktop/src/app/gateway/hooks/use-gateway-boot.test.tsx+++ b/apps/desktop/src/app/gateway/hooks/use-gateway-boot.test.tsx@@ -287,7 +287,7 @@ async function flushAsync() {it('loads and tracks saved gateways without mounting the statusbar or Settings', async () => {const desktop = fakeDesktop()const bootFetch = deferred<void>()- type Listener = Parameters<NonNullable<Window['hermesDesktop']['connections']['onChanged']>>[0]+ type Listener = Parameters<NonNullable<NonNullable<Window['hermesDesktop']['connections']>['onChanged']>>[0]const listeners = new Set<Listener>()let registry: DesktopConnectionsRegistry = {diff --git a/apps/desktop/src/app/right-sidebar/terminal/cwd-tracking.ts b/apps/desktop/src/app/right-sidebar/terminal/cwd-tracking.tsnew file mode 100644index 00000000000..ca0fc5e481d--- /dev/null+++ b/apps/desktop/src/app/right-sidebar/terminal/cwd-tracking.ts@@ -0,0 +1,106 @@+import type { Terminal } from '@xterm/xterm'+import type { RefObject } from 'react'++import { updateTerminalRestoreCwd } from './terminals'++type TerminalApi = Window['hermesDesktop']['terminal']++// Minimum gap between main-side PTY cwd probes. The probe spawns lsof on macOS,+// so keep it well throttled — cwd only changes on a `cd`, which the reporter+// already reads off the next output snapshot anyway.+const CWD_PROBE_THROTTLE_MS = 2000++// Parse a working directory out of a cwd-reporting OSC payload. Covers OSC 7+// (`file://host/path`, emitted by many bash/zsh integrations) and OSC 9;9+// (`9;<path>`, ConEmu/Windows-Terminal style some PowerShell profiles emit).+// Returns null for anything unrecognized so callers can ignore it.+export function parseOscCwd(code: 7 | 9, payload: string): string | null {+ if (code === 9) {+ // OSC 9;9;<path> — the leading "9;" selects the cwd sub-command.+ if (!payload.startsWith('9;')) {+ return null+ }++ const raw = payload.slice(2).trim().replace(/^"|"$/g, '')++ return raw || null+ }++ // OSC 7 — a file URI. Strip the scheme + authority and percent-decode.+ const match = /^file:\/\/[^/]*(\/.*)$/.exec(payload.trim())++ if (!match) {+ return null+ }++ let raw = match[1]++ try {+ raw = decodeURIComponent(raw)+ } catch {+ // Keep the undecoded path if it isn't valid percent-encoding.+ }++ // Windows file URIs carry a leading slash before the drive (`/C:/Users`).+ const windows = /^\/[A-Za-z]:[\\/]/.exec(raw)++ return (windows ? raw.slice(1) : raw) || null+}++interface TerminalCwdTrackerOptions {+ getSessionId: () => string | null+ /** Latest cwd seen this session; de-dupes redundant store writes and seeds+ * the cwd a retried shell starts in. */+ lastObservedCwdRef: RefObject<string | null>+ term: Terminal+ terminalApi: TerminalApi+}++// Track the shell's working directory so a reopened tab restarts where the+// user last `cd`'d. Two independent signals feed it: cwd-reporting OSC+// sequences (immediate, for shells configured to emit them) and a periodic+// PTY cwd probe on the main side (shell-agnostic on POSIX). The store+// updater de-dupes, so both feeding it is harmless.+export function trackTerminalCwd(+ id: string,+ { getSessionId, lastObservedCwdRef, term, terminalApi }: TerminalCwdTrackerOptions+): { dispose: () => void; probe: () => void } {+ const recordCwd = (next: string | null | undefined) => {+ const value = (next ?? '').trim()++ if (!value || value === lastObservedCwdRef.current) {+ return+ }++ lastObservedCwdRef.current = value+ updateTerminalRestoreCwd(id, value)+ }++ const cwdOscHandlers = ([7, 9] as const).map(code =>+ term.parser.registerOscHandler(code, payload => {+ recordCwd(parseOscCwd(code, payload))++ return false // let the sequence propagate; we only observe it+ })+ )++ let cwdProbeAt = 0++ const probeCwd = () => {+ const sessionId = getSessionId()++ if (!sessionId || !terminalApi.cwd || Date.now() - cwdProbeAt < CWD_PROBE_THROTTLE_MS) {+ return+ }++ cwdProbeAt = Date.now()+ void terminalApi+ .cwd(sessionId)+ .then(recordCwd)+ .catch(() => {+ // Best-effort: no cwd probe on this platform (e.g. Windows).+ })+ }++ return { dispose: () => cwdOscHandlers.forEach(handler => handler.dispose()), probe: probeCwd }+}diff --git a/apps/desktop/src/app/right-sidebar/terminal/revive-buffer.test.ts b/apps/desktop/src/app/right-sidebar/terminal/revive-buffer.test.tsindex 9e02179368e..11dddb24f6c 100644--- a/apps/desktop/src/app/right-sidebar/terminal/revive-buffer.test.ts+++ b/apps/desktop/src/app/right-sidebar/terminal/revive-buffer.test.ts@@ -1,6 +1,7 @@import { describe, expect, it } from 'vitest'-import { cleanReviveSnapshot, isIdlePromptOnly, parseOscCwd } from './use-terminal-session'+import { parseOscCwd } from './cwd-tracking'+import { cleanReviveSnapshot, isIdlePromptOnly } from './revive-snapshot'// A default-PowerShell idle prompt: no blank-line separator before it.const PS_PROMPT = 'PS C:\\Users\\Aleksandr>'diff --git a/apps/desktop/src/app/right-sidebar/terminal/revive-history.ts b/apps/desktop/src/app/right-sidebar/terminal/revive-history.tsnew file mode 100644index 00000000000..dd84f48e243--- /dev/null+++ b/apps/desktop/src/app/right-sidebar/terminal/revive-history.ts@@ -0,0 +1,52 @@+import type { Terminal } from '@xterm/xterm'++export interface ReviveHistory {+ isReplaying: () => boolean+ /** Settles once the restored history (if any) has been written. */+ ready: Promise<void>+ /** Idempotent; skipped when the server owns the shell and replays it. */+ restore: () => void+}++// Replay last session's scrollback before the fresh shell boots. The process+// is NOT revived — a new shell starts one line below the restored history.+// Stripping the boot gap still applies to the live shell output that follows,+// so the fresh prompt lands flush under the restored block.+export function createReviveHistory(term: Terminal, reviveBuffer: string, isPersistent: () => boolean): ReviveHistory {+ let markHistoryReady: () => void = () => undefined+ // Parser replies to queries inside the replayed bytes are not user input.+ let replaying = false++ const historyReady = new Promise<void>(resolve => {+ markHistoryReady = resolve+ })++ // Browser capability is negotiated by start metadata. Delay local history+ // until then, otherwise the server replay would duplicate it.+ let historyRestored = false++ const restoreHistory = () => {+ if (historyRestored) {+ return+ }++ historyRestored = true++ if (reviveBuffer && !isPersistent()) {+ replaying = true+ term.write(reviveBuffer)+ term.write('\r\n', () => {+ replaying = false+ markHistoryReady()+ })+ } else {+ markHistoryReady()+ }+ }++ return {+ isReplaying: () => replaying,+ ready: historyReady,+ restore: restoreHistory+ }+}diff --git a/apps/desktop/src/app/right-sidebar/terminal/revive-snapshot.ts b/apps/desktop/src/app/right-sidebar/terminal/revive-snapshot.tsnew file mode 100644index 00000000000..ea264881643--- /dev/null+++ b/apps/desktop/src/app/right-sidebar/terminal/revive-snapshot.ts@@ -0,0 +1,187 @@+// Revive-buffer text handling for the GUI terminal: the ANSI escape scanner the+// boot-gap stripper and snapshot cleanup share, and the pure functions that+// decide which part of a serialized buffer is persisted for relaunch restore.++// How many scrollback lines to serialize for relaunch restore. Mirrors VS Code's+// terminal.integrated.persistentSessionScrollback default; the store caps the+// resulting string so a long line-wrapped buffer can't blow the storage budget.+export const PERSISTENT_SESSION_SCROLLBACK = 200++function readEscapeSequence(data: string, index: number) {+ if (data.charCodeAt(index) !== 0x1b || index + 1 >= data.length) {+ return null+ }++ const kind = data[index + 1]++ if (kind === '[') {+ for (let i = index + 2; i < data.length; i += 1) {+ const code = data.charCodeAt(i)++ if (code >= 0x40 && code <= 0x7e) {+ return data.slice(index, i + 1)+ }+ }+ }++ if (kind === ']') {+ for (let i = index + 2; i < data.length; i += 1) {+ if (data.charCodeAt(i) === 0x07) {+ return data.slice(index, i + 1)+ }++ if (data.charCodeAt(i) === 0x1b && data[i + 1] === '\\') {+ return data.slice(index, i + 2)+ }+ }+ }++ // Character-set and other short ESC forms are three bytes (e.g. ESC ( B).+ // Treating only ESC+( as a sequence leaves the final selector ("B") as+ // printable text, which disarms the initial prompt-gap stripper before it can+ // eat the shell's leading newline.+ if (['(', ')', '*', '+', '-', '.', '/'].includes(kind) && index + 2 < data.length) {+ return data.slice(index, index + 3)+ }++ return data.slice(index, Math.min(index + 2, data.length))+}++function stripEscapeSequences(data: string) {+ let index = 0+ let text = ''++ while (index < data.length) {+ const sequence = readEscapeSequence(data, index)++ if (sequence) {+ index += sequence.length+ } else {+ text += data[index]+ index += 1+ }+ }++ return text+}++// Keep only the ANSI escape sequences from a chunk, dropping printable text. Lets+// us apply control codes (e.g. a clear-screen) while discarding boot spacers and+// zsh's reverse-video "%" partial-line marker.+function keepEscapeSequences(data: string) {+ let index = 0+ let out = ''++ while (index < data.length) {+ if (data.charCodeAt(index) === 0x1b) {+ const sequence = readEscapeSequence(data, index)++ if (sequence) {+ out += sequence+ index += sequence.length++ continue+ }+ }++ index += 1+ }++ return out+}++function stripInitialPromptGap(data: string) {+ let index = 0+ let prefix = ''++ while (index < data.length) {+ const sequence = readEscapeSequence(data, index)++ if (sequence) {+ prefix += sequence+ index += sequence.length+ } else if (data[index] === '\r' || data[index] === '\n') {+ index += 1+ } else {+ return prefix + data.slice(index)+ }+ }++ return prefix+}++// While armed, strip leading blank rows so the first prompt lands at the very+// top (no starship `add_newline` gap). Returns the text to write, or null to+// write nothing. This only filters renderer output: never inject Ctrl-L or+// other cleanup keystrokes into the user's shell.+export function createBootGapFilter(): (data: string) => string | null {+ let stripLeading = true++ return data => {+ if (!stripLeading) {+ return data+ }++ const next = stripInitialPromptGap(data)+ const visible = stripEscapeSequences(next).replace(/[\s%]/g, '')++ if (!visible) {+ // Spacer / lone clear-screen / zsh `%` marker: apply control codes but+ // drop the blank text and stay armed so the prompt still lands at top.+ return keepEscapeSequences(next) || null+ }++ stripLeading = false++ return next+ }+}++// A row's content with ANSI escapes and all whitespace stripped — '' for a+// spacer / prompt-gap / zsh `%` marker row.+const visibleText = (line: string) => stripEscapeSequences(line).replace(/[\s%]/g, '')++// Trim the shell's trailing idle prompt from a serialized snapshot before it's+// persisted. Without it, the saved buffer ends in the old prompt, so the next+// launch replays it directly above the fresh shell's prompt ("double bar").+//+// An interactive shell always reprints its prompt after a command finishes, so+// the tail of an idle buffer is the prompt, never real history. Two prompt+// shapes exist:+// - Spaced/multi-line (starship add_newline, powerline): a blank line sits+// just above the prompt, so the short block after the last blank is dropped.+// - Single-line (default PowerShell `PS C:\..>`, bash `user@host:~$`): no blank+// separator, so the final line itself is the prompt and is dropped.+// The fresh shell reprints the current prompt on boot either way, so only the+// redundant idle prompt is removed — command output is preserved.+export function cleanReviveSnapshot(serialized: string): string {+ const lines = serialized.split(/\r?\n/)++ while (lines.length && !visibleText(lines[lines.length - 1])) {+ lines.pop()+ }++ if (lines.length === 0) {+ return ''+ }++ const lastBlank = lines.findLastIndex(line => !visibleText(line))+ const spacedPrompt = lastBlank >= 0 && lines.length - 1 - lastBlank <= 3++ // Spaced prompt (starship/powerline): drop the block after the blank+ // separator. Otherwise the last line is the single-line prompt itself.+ lines.length = spacedPrompt ? lastBlank : lines.length - 1++ return lines.join('\r\n')+}++// True when a revive buffer holds no real scrollback: empty, or only repeats of+// one line (the idle prompt). This is the idle-accumulation signature (#61572) —+// each relaunch replayed the saved prompt(s) and the fresh shell printed one more+// below, growing the tab by a line per cycle. Real sessions vary (prompt ++// command + output), so genuine short histories are never mistaken for idle.+export function isIdlePromptOnly(serialized: string): boolean {+ const lines = serialized.split(/\r?\n/).map(visibleText).filter(Boolean)++ return lines.length === 0 || lines.every(line => line === lines[0])+}diff --git a/apps/desktop/src/app/right-sidebar/terminal/snapshot-persister.ts b/apps/desktop/src/app/right-sidebar/terminal/snapshot-persister.tsnew file mode 100644index 00000000000..9b0b6443edc--- /dev/null+++ b/apps/desktop/src/app/right-sidebar/terminal/snapshot-persister.ts@@ -0,0 +1,94 @@+import type { SerializeAddon } from '@xterm/addon-serialize'++import { cleanReviveSnapshot, isIdlePromptOnly, PERSISTENT_SESSION_SCROLLBACK } from './revive-snapshot'+import { updateTerminalReviveBuffer } from './terminals'++// Leading-edge throttle window for capturing history. The first output after an+// idle gap persists almost immediately (so `cmd; quit` is on disk before the+// renderer tears down), then at most once per window while output streams.+const SNAPSHOT_THROTTLE_MS = 750++interface SnapshotPersisterOptions {+ hasSessionActivity: () => boolean+ isDisposed: () => boolean+ /** Server-owned shells replay their own history; nothing to persist here. */+ isPersistent: () => boolean+ /** Refresh the persisted cwd after each capture (throttled by the tracker). */+ probeCwd: () => void+ /** The revive buffer replayed at mount; cleared on an idle session when it holds only prompts. */+ reviveBuffer: string+ serialize: SerializeAddon+}++// Capture the buffer on a leading-edge throttle and persist synchronously via+// the store. No unload hook: by the time the user quits, a recent snapshot is+// already on disk (the prior beforeunload-based attempt lost the last output).+export function createSnapshotPersister(+ id: string,+ { hasSessionActivity, isDisposed, isPersistent, probeCwd, reviveBuffer, serialize }: SnapshotPersisterOptions+): { cancel: () => void; schedule: () => void } {+ let snapshotTimer = 0+ let lastSnapshotAt = 0++ const persistSnapshot = () => {+ if (isDisposed() || isPersistent()) {+ return+ }++ lastSnapshotAt = Date.now()++ // No user input this session: never re-serialize. The live buffer now holds+ // the replayed history plus a fresh boot prompt, and re-saving that is+ // exactly what grew idle tabs by one prompt line per relaunch (#61572).+ // If the buffer we loaded carried no real scrollback (empty, or only a+ // repeated prompt), clear it so the next launch shows a single fresh prompt+ // and any pre-existing accumulation heals. Otherwise leave the prior+ // snapshot untouched so real history from an earlier active session+ // survives an idle reopen instead of being overwritten.+ if (!hasSessionActivity()) {+ if (isIdlePromptOnly(reviveBuffer)) {+ updateTerminalReviveBuffer(id, '')+ }++ return+ }++ try {+ const snapshot = serialize.serialize({ scrollback: PERSISTENT_SESSION_SCROLLBACK })+ updateTerminalReviveBuffer(id, cleanReviveSnapshot(snapshot))+ } catch {+ // Best-effort restore: never let serialization break a live terminal.+ }++ // A user command may have `cd`'d; refresh the persisted cwd (throttled).+ probeCwd()+ }++ const scheduleSnapshot = () => {+ if (snapshotTimer) {+ return+ }++ const elapsed = Date.now() - lastSnapshotAt++ if (elapsed >= SNAPSHOT_THROTTLE_MS) {+ persistSnapshot()++ return+ }++ snapshotTimer = window.setTimeout(() => {+ snapshotTimer = 0+ persistSnapshot()+ }, SNAPSHOT_THROTTLE_MS - elapsed)+ }++ return {+ cancel: () => {+ if (snapshotTimer) {+ window.clearTimeout(snapshotTimer)+ }+ },+ schedule: scheduleSnapshot+ }+}diff --git a/apps/desktop/src/app/right-sidebar/terminal/terminal-drop.ts b/apps/desktop/src/app/right-sidebar/terminal/terminal-drop.tsnew file mode 100644index 00000000000..da7634b1747--- /dev/null+++ b/apps/desktop/src/app/right-sidebar/terminal/terminal-drop.ts@@ -0,0 +1,151 @@+import type { Terminal } from '@xterm/xterm'++import { triggerHaptic } from '@/lib/haptics'++type TerminalApi = Window['hermesDesktop']['terminal']++const HERMES_PATHS_MIME = 'application/x-hermes-paths'++function transferHasDropCandidates(t: DataTransfer): boolean {+ if (t.types?.includes(HERMES_PATHS_MIME)) {+ return true+ }++ if ((t.files?.length ?? 0) > 0) {+ return true+ }++ for (let i = 0; i < (t.items?.length ?? 0); i += 1) {+ if (t.items[i]?.kind === 'file') {+ return true+ }+ }++ return false+}++function collectDroppedPaths(t: DataTransfer): string[] {+ const seen = new Set<string>()++ const push = (value: unknown) => {+ if (typeof value !== 'string') {+ return+ }++ const path = value.trim()++ if (path) {+ seen.add(path)+ }+ }++ try {+ const raw = t.getData(HERMES_PATHS_MIME)++ if (raw) {+ for (const entry of JSON.parse(raw) as { path?: unknown }[]) {+ push(entry?.path)+ }+ }+ } catch {+ // Malformed in-app drag payload — fall through to OS files.+ }++ const getPath = window.hermesDesktop?.getPathForFile++ const addFile = (file: File | null) => {+ if (!file || !getPath) {+ return+ }++ try {+ push(getPath(file))+ } catch {+ // File handle unavailable.+ }+ }++ for (let i = 0; i < (t.files?.length ?? 0); i += 1) {+ addFile(t.files.item(i))+ }++ for (let i = 0; i < (t.items?.length ?? 0); i += 1) {+ const item = t.items[i]++ if (item?.kind === 'file') {+ addFile(item.getAsFile())+ }+ }++ return [...seen]+}++function quotePathForShell(path: string, shellName: string): string {+ const shell = shellName.toLowerCase()++ if (shell.includes('powershell') || shell.includes('pwsh')) {+ return `'${path.replace(/'/g, "''")}'`+ }++ if (shell.includes('cmd')) {+ return `"${path.replace(/"/g, '""')}"`+ }++ return `'${path.replace(/'/g, "'\\''")}'`+}++interface TerminalDropOptions {+ getSessionId: () => string | null+ getShellName: () => string+ markActivity: () => void+ term: Terminal+ terminalApi: TerminalApi+}++// Dropping files (from the OS or the app's file trees) types their shell-quoted+// paths at the prompt, like a native terminal. Returns the listener teardown.+export function bindTerminalDrop(+ host: HTMLElement,+ { getSessionId, getShellName, markActivity, term, terminalApi }: TerminalDropOptions+): () => void {+ const onDragOver = (e: DragEvent) => {+ if (!e.dataTransfer || !transferHasDropCandidates(e.dataTransfer)) {+ return+ }++ e.preventDefault()+ e.stopPropagation()+ e.dataTransfer.dropEffect = 'copy'+ }++ const onDrop = (e: DragEvent) => {+ const id = getSessionId()++ if (!id || !e.dataTransfer || !transferHasDropCandidates(e.dataTransfer)) {+ return+ }++ e.preventDefault()+ e.stopPropagation()+ const paths = collectDroppedPaths(e.dataTransfer)++ if (!paths.length) {+ return+ }++ markActivity()+ void terminalApi.write(id, `${paths.map(p => quotePathForShell(p, getShellName())).join(' ')} `)+ term.focus()+ triggerHaptic('selection')+ }++ host.addEventListener('dragenter', onDragOver)+ host.addEventListener('dragover', onDragOver)+ host.addEventListener('drop', onDrop)++ return () => {+ host.removeEventListener('dragenter', onDragOver)+ host.removeEventListener('dragover', onDragOver)+ host.removeEventListener('drop', onDrop)+ }+}diff --git a/apps/desktop/src/app/right-sidebar/terminal/terminal-input-bindings.test.ts b/apps/desktop/src/app/right-sidebar/terminal/terminal-input-bindings.test.tsnew file mode 100644index 00000000000..b203a96328d--- /dev/null+++ b/apps/desktop/src/app/right-sidebar/terminal/terminal-input-bindings.test.ts@@ -0,0 +1,36 @@+import type { Terminal } from '@xterm/xterm'+import { expect, it, vi } from 'vitest'++import { terminalMenuHandleFor } from './terminal-context-menu'+import { bindTerminalClipboard } from './terminal-input-bindings'++it('routes word erase only to a live shell and releases the context-menu handle on cleanup', () => {+ const host = document.createElement('div')+ host.setAttribute('data-terminal', '')++ const term = {+ attachCustomKeyEventHandler: vi.fn(),+ getSelection: () => '',+ selectAll: vi.fn()+ } as unknown as Terminal++ const markActivity = vi.fn()+ const writeInput = vi.fn()+ let hasSession = true+ const dispose = bindTerminalClipboard(term, host, markActivity, writeInput, () => hasSession)+ const handle = terminalMenuHandleFor(host)!++ expect(handle.wordErase?.()).toBe(true)+ expect(writeInput).toHaveBeenCalledExactlyOnceWith('\x17')+ expect(markActivity).toHaveBeenCalledOnce()++ hasSession = false+ expect(handle.wordErase?.()).toBe(false)+ expect(writeInput).toHaveBeenCalledTimes(1)++ hasSession = true+ expect(handle.wordErase?.()).toBe(true)+ expect(writeInput).toHaveBeenCalledTimes(2)+ dispose()+ expect(terminalMenuHandleFor(host)).toBeNull()+})diff --git a/apps/desktop/src/app/right-sidebar/terminal/terminal-input-bindings.ts b/apps/desktop/src/app/right-sidebar/terminal/terminal-input-bindings.tsnew file mode 100644index 00000000000..45e86efb0ec--- /dev/null+++ b/apps/desktop/src/app/right-sidebar/terminal/terminal-input-bindings.ts@@ -0,0 +1,123 @@+import type { Terminal } from '@xterm/xterm'++import { writeClipboardText } from '@/lib/clipboard'+import { triggerHaptic } from '@/lib/haptics'++import { terminalClipboardIntent } from './clipboard'+import { isMacPlatform } from './selection'+import { registerTerminalContextMenu } from './terminal-context-menu'++// `onData` also carries xterm-generated replies to DSR/CPR/DA queries during+// shell startup. Treat only real key events (plus explicit paste/drop/inject+// paths) as user activity, or an untouched refresh re-saves boot rows.+export function bindTerminalActivity(term: Terminal, host: HTMLElement, markActivity: () => void): () => void {+ const keyDisposable = term.onKey(markActivity)++ const onPointerActivity = (event: PointerEvent) => {+ if (event.button === 1 || term.modes.mouseTrackingMode !== 'none') {+ markActivity()+ }+ }++ const onWheelActivity = () => {+ if (term.modes.mouseTrackingMode !== 'none') {+ markActivity()+ }+ }++ host.addEventListener('beforeinput', markActivity)+ host.addEventListener('compositionstart', markActivity)+ host.addEventListener('pointerdown', onPointerActivity)+ host.addEventListener('wheel', onWheelActivity)++ return () => {+ keyDisposable.dispose()+ host.removeEventListener('beforeinput', markActivity)+ host.removeEventListener('compositionstart', markActivity)+ host.removeEventListener('pointerdown', onPointerActivity)+ host.removeEventListener('wheel', onWheelActivity)+ }+}++// Right-click menu, the focus-routed Ctrl/Cmd+R, and copy/paste chords. Paste+// and ^R count as session activity. Returns the context-menu registration teardown.+export function bindTerminalClipboard(+ term: Terminal,+ host: HTMLElement,+ markActivity: () => void,+ writeInput: (data: string) => void,+ hasSession: () => boolean+): () => void {+ // The app context menu resolves right-clicks on this host through the+ // registered handle: xterm's selection is not a DOM selection, so the+ // DOM resolver would see nothing here. The same handle answers the+ // focus-routed Ctrl/Cmd+R: main claimed the keystroke, so re-deliver the+ // ^R byte to the PTY ourselves (#96482).+ const unregisterContextMenu = registerTerminalContextMenu(host, {+ getSelection: () => term.getSelection(),+ paste: text => {+ markActivity()+ term.focus()+ term.paste(text)+ },+ reload: () => {+ markActivity()+ writeInput('\x12')+ },+ selectAll: () => term.selectAll(),+ // Main claimed the close-tab chord; preserve readline word erase while+ // the shell is alive, and let the caller close a disconnected tab.+ wordErase: () => {+ markActivity()++ if (!hasSession()) {+ return false+ }++ writeInput('\x17')++ return true+ }+ })++ // Copy/paste chords. Returning false stops xterm from also sending the key+ // to the PTY; every path that doesn't copy or paste returns true, so plain+ // Ctrl+C with no selection still interrupts the running process.+ term.attachCustomKeyEventHandler(event => {+ const intent = terminalClipboardIntent(event, {+ hasSelection: Boolean(term.getSelection()),+ isMac: isMacPlatform()+ })++ if (!intent) {+ return true+ }++ event.preventDefault()++ if (intent === 'copy') {+ const text = term.getSelection()+ // Write through the main process: the renderer's clipboard API throws+ // "Write permission denied" whenever the document isn't focused.+ void writeClipboardText(text).catch(() => {+ // Clipboard unavailable — the selection stays put so the user can retry.+ })+ term.clearSelection()+ triggerHaptic('selection')++ return false+ }+ void (async () => {+ const text = (await window.hermesDesktop?.readClipboard?.()) ?? ''++ if (text) {+ markActivity()+ term.paste(text)+ }+ })()++ return false+ })++ return unregisterContextMenu+}diff --git a/apps/desktop/src/app/right-sidebar/terminal/terminal-session-attempt.ts b/apps/desktop/src/app/right-sidebar/terminal/terminal-session-attempt.tsnew file mode 100644index 00000000000..52ff947ae42--- /dev/null+++ b/apps/desktop/src/app/right-sidebar/terminal/terminal-session-attempt.ts@@ -0,0 +1,283 @@+import type { Terminal } from '@xterm/xterm'+import type { RefObject } from 'react'++import type { HermesTerminalSession } from '@/global'++import { $terminals, markTerminalPersistent, removeExitedTerminal } from './terminals'++type TerminalApi = Window['hermesDesktop']['terminal']++export type TerminalStatus = 'closed' | 'open' | 'starting' | 'reconnecting'++// Status line written when a persistent PTY stream ends, keyed by exit signal.+const TERMINAL_EXIT_MESSAGES: Record<string, string> = {+ disconnected: 'Terminal disconnected. Press Enter to reconnect to the same shell.',+ expired: 'Terminal expired or exited. Press Enter to create a new shell.',+ superseded: 'Terminal is attached in another window. Press Enter to take it back.',+ denied: 'Terminal access denied. Check your sign-in and profile, then press Enter to retry.',+ capacity: 'Terminal capacity reached. Close another terminal, then press Enter to retry.'+}++// True once the page/app is tearing down (Cmd+Q, Alt+F4, window close, reload).+// App quit kills the PTYs from the main process, which fires onExit in the+// renderer — but React skips effect cleanups on teardown, so the per-instance+// `disposed` flag never flips. Without this guard those teardown exits would call+// closeTerminal() and wipe the persisted terminal list right before relaunch+// reads it. A real `exit`/Ctrl-D still closes the tab (flag stays false).+let appTearingDown = false++if (typeof window !== 'undefined') {+ const markTearingDown = () => {+ appTearingDown = true+ }++ window.addEventListener('pagehide', markTearingDown)+ window.addEventListener('beforeunload', markTearingDown)+ window.addEventListener('pageshow', () => {+ appTearingDown = false+ })+}++interface SessionAttemptOptions {+ isDisposed: () => boolean+ /** True while restored local history is parsing; its query replies must not reach the shell. */+ isReplayingHistory: () => boolean+ /** The attempt adopted a live session: seed size, shell name and selection. */+ onStarted: (session: HermesTerminalSession) => void+ /** Cwd for the next shell; read at each start so a retry follows a `cd`. */+ resolveCwd: () => string+ /** Runs once start metadata says whether the server replays history itself. */+ restoreHistory: () => void+ sessionIdRef: RefObject<string | null>+ setStatus: (status: TerminalStatus) => void+ term: Terminal+ terminalApi: TerminalApi+ /** Live output of a renderer-owned (non-persistent) shell. */+ writeOutput: (data: string) => void+}++export interface SessionAttemptController {+ /** Keystrokes and xterm replies from `term.onData`. */+ input: (data: string) => void+ /** Whether the current shell is server-owned (replayed and resumed by the server). */+ isPersistent: () => boolean+ /** Release the current attempt: unsubscribe, then detach or dispose its shell. */+ release: () => void+ start: () => void+}++// One shell attachment per terminal tab at a time. Each start supersedes the+// previous attempt; an attempt that fails, disconnects or loses its persistent+// stream arms Enter to start (or resume) the next one in the same scrollback.+export function createSessionAttemptController(+ id: string,+ {+ isDisposed,+ isReplayingHistory,+ onStarted,+ resolveCwd,+ restoreHistory,+ sessionIdRef,+ setStatus,+ term,+ terminalApi,+ writeOutput+ }: SessionAttemptOptions+): SessionAttemptController {+ let persistent = Boolean($terminals.get().find(tab => tab.id === id)?.persistent)+ let resumeOnly = persistent+ let replayWrites = 0+ let retrySession: (() => void) | null = null+ let cleanupAttempt: (() => void) | null = null++ const startSession = () => {+ cleanupAttempt?.()+ let current = true+ let attemptSessionId: string | null = null++ const releaseSession = (sid: string) =>+ persistent && terminalApi.detach ? terminalApi.detach(sid) : terminalApi.dispose(sid)++ const subscriptions: Array<() => void> = []++ const release = () => {+ current = false+ subscriptions.splice(0).forEach(unsubscribe => unsubscribe())++ if (attemptSessionId) {+ const sid = attemptSessionId+ attemptSessionId = null++ if (sessionIdRef.current === sid) {+ sessionIdRef.current = null+ }++ void releaseSession(sid)+ }+ }++ cleanupAttempt = release++ // Arm Enter to start (or resume) the next attempt in the same scrollback.+ const armRetry = (message: string) => {+ setStatus('closed')+ retrySession = startSession+ term.write(`${message}\r\n`)+ }++ void terminalApi+ // Prefer the last observed cwd so retry/relaunch stays in the same directory.+ .start({ cols: term.cols, cwd: resolveCwd(), rows: term.rows, restoreKey: id, resumeOnly })+ .then(async session => {+ persistent = Boolean(session.persistent)+ resumeOnly = persistent++ if (persistent) {+ markTerminalPersistent(id)+ }++ if (isDisposed() || !current) {+ void releaseSession(session.id)++ return+ }++ restoreHistory()+ attemptSessionId = session.id+ sessionIdRef.current = session.id+ onStarted(session)++ subscriptions.push(+ terminalApi.onData(session.id, (data, options) => {+ if (!current || isDisposed()) {+ return+ }++ if (options?.replay) {+ ++replayWrites+ term.write(data, () => {+ --replayWrites+ })+ } else if (persistent) {+ term.write(data)+ } else {+ writeOutput(data)+ }+ }),+ terminalApi.onExit(session.id, exit => {+ if (!current || isDisposed() || appTearingDown) {+ return+ }++ release()++ if (persistent && exit.signal) {+ resumeOnly = exit.signal !== 'expired'+ armRetry(+ `\r\n${TERMINAL_EXIT_MESSAGES[exit.signal] || 'Terminal disconnected. Press Enter to reconnect.'}`+ )++ return+ }++ if (exit.signal === 'disconnected') {+ armRetry('\r\nTerminal disconnected. Press Enter to start a new shell; scrollback is preserved.')++ return+ }++ // Only a current process exit removes the persisted tab.+ removeExitedTerminal(id)+ })+ )++ if (persistent && terminalApi.onState) {+ subscriptions.push(+ terminalApi.onState(session.id, state => {+ if (!current || isDisposed() || appTearingDown) {+ return+ }++ setStatus(state === 'disconnected' ? 'closed' : state)++ if (state === 'reconnecting') {+ term.write('\r\nTerminal disconnected. Reconnecting to the same shell…\r\n')+ }+ })+ )+ }++ // onExit may replay a buffered exit before returning its unsubscribe.+ if (!current) {+ release()++ return+ }++ const attached = await terminalApi.attach(session.id)++ if (!attached) {+ throw new Error('Terminal session disappeared before its output stream attached')+ }++ if (isDisposed() || !current) {+ return+ }++ if (!persistent) {+ setStatus('open')+ }++ window.requestAnimationFrame(() => {+ if (current && !isDisposed()) {+ term.clearSelection()+ }+ })+ })+ .catch(error => {+ if (isDisposed() || !current) {+ return+ }++ release()+ const expired = error && typeof error === 'object' && 'signal' in error && error.signal === 'expired'++ if (expired) {+ resumeOnly = false+ armRetry(TERMINAL_EXIT_MESSAGES.expired)+ } else {+ armRetry(+ `Terminal failed to start: ${error instanceof Error ? error.message : String(error)}. Press Enter to retry.`+ )+ }+ })+ }++ const input = (data: string) => {+ if (replayWrites || isReplayingHistory()) {+ return+ }++ const sessionId = sessionIdRef.current++ if (!sessionId && retrySession && data === '\r') {+ const retry = retrySession+ retrySession = null+ setStatus('starting')+ retry()++ return+ }++ if (sessionId) {+ void terminalApi.write(sessionId, data)+ }+ }++ return {+ input,+ isPersistent: () => persistent,+ release: () => cleanupAttempt?.(),+ start: startSession+ }+}diff --git a/apps/desktop/src/app/right-sidebar/terminal/terminals.ts b/apps/desktop/src/app/right-sidebar/terminal/terminals.tsindex f7035709d57..05af1ff0ebf 100644--- a/apps/desktop/src/app/right-sidebar/terminal/terminals.ts+++ b/apps/desktop/src/app/right-sidebar/terminal/terminals.ts@@ -3,6 +3,7 @@ import type { Terminal } from '@xterm/xterm'import { atom, computed } from 'nanostores'import { readKey, writeKey } from '@/lib/storage'+import { notifyError } from '@/store/notifications'import { $currentCwd } from '@/store/session'import { setTerminalTakeover } from '../store'@@ -126,6 +127,8 @@ export interface TerminalEntry {* revived — a fresh shell starts beneath the restored buffer. Captured live* for user tabs only; agent mirrors stay runtime-only. */reviveBuffer?: string+ /** A server shell was created for this tab; restoration must never respawn it. */+ persistent?: boolean/** `user` = interactive PTY shell. `agent` = read-only mirror of an agent* background process (`terminal(background=true)`), keyed by `procId`. */kind: 'user' | 'agent'@@ -138,6 +141,8 @@ interface PersistedTerminalEntry {id: stringrestoreCwd?: stringreviveBuffer?: string+ /** A server shell was created for this tab; restoration must never respawn it. */+ persistent?: booleantitle: string}@@ -175,6 +180,7 @@ function sanitizePersistedTerminal(value: unknown): PersistedTerminalEntry | nulid,...(restoreCwd ? { restoreCwd } : {}),...(reviveBuffer ? { reviveBuffer } : {}),+ ...(record.persistent === true ? { persistent: true } : {}),title: title || 'Terminal'}}@@ -223,6 +229,7 @@ function persistTerminals(list: readonly TerminalEntry[], activeTerminalId: nullid: term.id,...(term.restoreCwd ? { restoreCwd: term.restoreCwd } : {}),...(term.reviveBuffer ? { reviveBuffer: term.reviveBuffer } : {}),+ ...(term.persistent ? { persistent: true } : {}),title: term.title}))@@ -376,9 +383,30 @@ export function cycleTerminal(direction: 1 | -1): void {$activeTerminalId.set(list[(current + direction + list.length) % list.length].id)}+const closingTerminals = new Set<string>()+/** Drop a terminal. Focus slides to the neighbor that fills its slot; closing* the last one closes the whole pane. */export function closeTerminal(id: string): void {+ const entry = $terminals.get().find(term => term.id === id)+ const closeSaved = window.hermesDesktop?.terminal?.closeSaved++ if (entry?.kind !== 'user' || !closeSaved) {+ removeExitedTerminal(id)++ return+ }++ if (closingTerminals.has(id)) {return}+ closingTerminals.add(id)+ // Keep the tab and its resume handle until the server confirms termination.+ void closeSaved(id).then(closed => {+ if (!closed) {throw new Error('Terminal close was not confirmed; retry closing this tab')}+ removeExitedTerminal(id)+ }).catch(error => notifyError(error, 'Could not close terminal')).finally(() => closingTerminals.delete(id))+}++export function removeExitedTerminal(id: string): void {const list = $terminals.get()const index = list.findIndex(term => term.id === id)@@ -424,33 +452,31 @@ export function closeActiveTerminal(): void {}export function closeAllTerminals(): void {- if ($terminals.get().length === 0) {- return- }-- $terminals.set([])- $activeTerminalId.set(null)- setTerminalTakeover(false)+ $terminals.get().forEach(term => closeTerminal(term.id))}export function closeOtherTerminals(id: string): void {const keep = $terminals.get().find(term => term.id === id)if (keep) {- $terminals.set([keep])+ $terminals.get().filter(term => term.id !== id).forEach(term => closeTerminal(term.id))$activeTerminalId.set(keep.id)}}-/** Record the latest serialized scrollback for a tab so it can be replayed on- * the next launch. Oversized buffers are tail-trimmed to stay under the storage- * budget; only user tabs ever carry one. */+/** Server replay replaces renderer-only history once persistence is negotiated. */+export function markTerminalPersistent(id: string): void {+ $terminals.set($terminals.get().map(term =>+ term.id === id ? { ...term, persistent: true, reviveBuffer: undefined } : term+ ))+}+export function updateTerminalReviveBuffer(id: string, reviveBuffer: string): void {const capped =reviveBuffer.length > MAX_REVIVE_BUFFER_CHARS ? reviveBuffer.slice(-MAX_REVIVE_BUFFER_CHARS) : reviveBuffer$terminals.set(- $terminals.get().map(term => (term.id === id && term.kind === 'user' ? { ...term, reviveBuffer: capped } : term))+ $terminals.get().map(term => (term.id === id && term.kind === 'user' && !term.persistent ? { ...term, reviveBuffer: capped } : term)))}diff --git a/apps/desktop/src/app/right-sidebar/terminal/use-agent-terminal.ts b/apps/desktop/src/app/right-sidebar/terminal/use-agent-terminal.tsindex 11fde1b2fcb..45ab443e875 100644--- a/apps/desktop/src/app/right-sidebar/terminal/use-agent-terminal.ts+++ b/apps/desktop/src/app/right-sidebar/terminal/use-agent-terminal.ts@@ -4,7 +4,7 @@ import { WebglAddon } from '@xterm/addon-webgl'import { Terminal } from '@xterm/xterm'import { useEffect, useRef } from 'react'-import { writeClipboardText } from '@/components/ui/copy-button'+import { writeClipboardText } from '@/lib/clipboard'import { triggerHaptic } from '@/lib/haptics'import { useTheme } from '@/themes/context'diff --git a/apps/desktop/src/app/right-sidebar/terminal/use-terminal-font.ts b/apps/desktop/src/app/right-sidebar/terminal/use-terminal-font.tsindex 01aa07b1993..bfbed85c8df 100644--- a/apps/desktop/src/app/right-sidebar/terminal/use-terminal-font.ts+++ b/apps/desktop/src/app/right-sidebar/terminal/use-terminal-font.ts@@ -8,7 +8,7 @@ import { $terminalFontFamily, applyTerminalFontFamily, resolveTerminalFontFamilyimport { redrawAllTerminals } from './terminals'interface TerminalFontControllerOptions {- fitRef: RefObject<((visible: boolean) => void) | null>+ fitRef: RefObject<(() => void) | null>termRef: RefObject<Terminal | null>webglRef: RefObject<WebglAddon | null>}@@ -39,7 +39,7 @@ export function useTerminalFontController({ fitRef, termRef, webglRef }: Terminavoid applyTerminalFontFamily({clearTextureAtlas: () => webglRef.current?.clearTextureAtlas(),- fit: () => fitRef.current?.(true),+ fit: () => fitRef.current?.(),fontFamily,isCurrent: () => !cancelled && generationRef.current === generation,termdiff --git a/apps/desktop/src/app/right-sidebar/terminal/use-terminal-session.test.tsx b/apps/desktop/src/app/right-sidebar/terminal/use-terminal-session.test.tsxnew file mode 100644index 00000000000..bc854c2bd0d--- /dev/null+++ b/apps/desktop/src/app/right-sidebar/terminal/use-terminal-session.test.tsx@@ -0,0 +1,311 @@+import { act, cleanup, render, screen, waitFor } from '@testing-library/react'+import { afterEach, beforeEach, expect, it, vi } from 'vitest'++import { installBrowserDesktopBridge } from '@/lib/browser-desktop-bridge'+import { clearWebappSession, seedWebappSession } from '@/test/webapp-session'++import { $terminals, closeAllTerminals, closeOtherTerminals, createTerminal, updateTerminalReviveBuffer } from './terminals'+import { useTerminalSession } from './use-terminal-session'++const emulator = vi.hoisted(() => ({+ input: (_data: string) => {},+ output: '',+ latestFontFamilyRef: { current: 'monospace' },+ mountedRef: { current: false }+}))++vi.mock('@xterm/xterm', () => ({+ Terminal: class {+ options: Record<string, unknown>+ cols = 80+ rows = 24+ unicode = { activeVersion: '11' }+ modes = { mouseTrackingMode: 'none' }+ buffer = { active: { type: 'normal' } }+ parser = { registerOscHandler: () => ({ dispose() {} }) }+ constructor(options: Record<string, unknown>) {+ this.options = options+ }+ loadAddon() {}+ open() {}+ focus() {}+ dispose() {}+ refresh() {}+ clearSelection() {}+ getSelection() {+ return ''+ }+ hasSelection() {+ return false+ }+ registerMarker() {+ return { line: 0, dispose() {} }+ }+ onKey() {+ return { dispose() {} }+ }+ onData(callback: (data: string) => void) {+ emulator.input = callback++ return { dispose() {} }+ }+ onSelectionChange() {+ return { dispose() {} }+ }+ attachCustomKeyEventHandler() {}+ write(data: string, callback?: () => void) {+ if (data === '\u001bc') {emulator.output = ''}++ if (data.includes('\u001b[6n')) {emulator.input('\u001b[1;1R')}+ emulator.output += data+ callback?.()+ }+ }+}))+vi.mock('@xterm/addon-fit', () => ({+ FitAddon: class {+ fit() {}+ }+}))+vi.mock('@xterm/addon-serialize', () => ({ SerializeAddon: class {} }))+vi.mock('@xterm/addon-unicode11', () => ({ Unicode11Addon: class {} }))+vi.mock('@xterm/addon-webgl', () => ({+ WebglAddon: class {+ onContextLoss() {}+ clearTextureAtlas() {}+ }+}))+vi.mock('./links', () => ({ terminalLinkHandler: {}, terminalWebLinksAddon: () => ({}) }))+vi.mock('./buffer', () => ({ makeTerminalReader: () => () => '', registerTerminalReader: () => () => {} }))+vi.mock('./terminal-context-menu', () => ({ registerTerminalContextMenu: () => () => {} }))+vi.mock('./terminal-font', () => ({ prepareTerminalFontFamily: async () => 'monospace' }))+vi.mock('./use-terminal-font', () => ({ useTerminalFontController: () => emulator }))+vi.mock('@/themes/context', () => ({ useTheme: () => ({ renderedMode: 'dark', theme: {}, themeName: 'test' }) }))++class Socket {+ static OPEN = 1+ static instances: Socket[] = []+ static persistent = false+ url: URL+ sent: string[] = []+ readyState = 1+ onmessage: ((event: MessageEvent) => void) | null = null+ onclose: ((event: CloseEvent) => void) | null = null+ constructor(url: string | URL) {+ this.url = new URL(url)+ Socket.instances.push(this)+ queueMicrotask(() => {+ const metadata = Socket.persistent+ ? { shell: 'fish', cwd: '/work', terminalId: this.url.searchParams.get('attach') || `shell-${Socket.instances.length}`, closed: this.url.searchParams.get('action') === 'close' }+ : { shell: 'fish' }++ this.onmessage?.({ data: '\u0000HERMES_TERMINAL_META:' + JSON.stringify(metadata) } as MessageEvent)++ if ('closed' in metadata && metadata.closed) {this.close()}+ })+ }+ send(data: string) { this.sent.push(data) }+ close(code = 1000, reason = '') {+ this.readyState = 3+ this.onclose?.(new CloseEvent('close', { code, reason }))+ }+ output(data: string) {+ this.onmessage?.({ data } as MessageEvent)+ }+}++// Real scrollback (a command and its output): main's idle-prompt heuristic would clear a lone line.+const SAVED_HISTORY = '$ echo saved history\r\nsaved history'++function Harness({ id }: { id: string }) {+ const { hostRef, status } = useTerminalSession({+ id,+ cwd: '/work',+ active: false,+ reviveBuffer: SAVED_HISTORY,+ onAddSelectionToChat: () => {}+ })++ return (+ <>+ <span>{status}</span>+ <div ref={hostRef} />+ </>+ )+}++beforeEach(() => {+ window.dispatchEvent(new PageTransitionEvent('pageshow'))+ localStorage.clear()+})++afterEach(() => {+ cleanup()+ window.dispatchEvent(new Event('beforeunload'))+ Reflect.deleteProperty(window, 'hermesDesktop')+ clearWebappSession()+ $terminals.set([])+ Socket.instances = []+ Socket.persistent = false+ emulator.output = ''+ vi.unstubAllGlobals()+ vi.restoreAllMocks()+})++it.each([1006, 1000])('retains the saved tab on transport loss (%s) and lets Enter recover in the same scrollback', async code => {+ seedWebappSession('test-token')+ vi.stubGlobal('WebSocket', Socket)+ installBrowserDesktopBridge()+ const id = createTerminal('/work')+ updateTerminalReviveBuffer(id, SAVED_HISTORY)+ render(<Harness id={id} />)+ await waitFor(() => expect(screen.getByText('open')).toBeTruthy())+ const first = Socket.instances[0]+ act(() => {+ first.output('live output')+ first.close(code)+ })+ expect($terminals.get().find(tab => tab.id === id)?.reviveBuffer).toBe(SAVED_HISTORY)+ expect(screen.getByText('closed')).toBeTruthy()+ expect(emulator.output).toMatch(/disconnected.*Enter/i)+ const prior = emulator.output+ act(() => emulator.input('\r'))+ await waitFor(() => expect(screen.getByText('open')).toBeTruthy())+ expect(Socket.instances).toHaveLength(2)+ expect(emulator.output.startsWith(prior)).toBe(true)+ expect(emulator.output).toContain('saved history')+ expect(emulator.output).toContain('live output')+ act(() => Socket.instances[1].close(4410, 'shell exited'))+ expect($terminals.get().some(tab => tab.id === id)).toBe(false)+})++it.each(['attach', 'disconnect'])('cleans up the %s attempt before retry and ignores its late exit', async failure => {+ seedWebappSession('test-token')+ vi.stubGlobal('WebSocket', Socket)+ installBrowserDesktopBridge()+ const api = window.hermesDesktop!.terminal!+ const listeners = new Set<symbol>()+ const exits: Array<Parameters<typeof api.onExit>[1]> = []+ const onData = api.onData.bind(api)+ const onExit = api.onExit.bind(api)+ vi.spyOn(api, 'onData').mockImplementation((sid, callback) => {+ const key = Symbol()+ listeners.add(key)+ const unsubscribe = onData(sid, callback)++ return () => { listeners.delete(key); unsubscribe() }+ })+ vi.spyOn(api, 'onExit').mockImplementation((sid, callback) => {+ const key = Symbol()+ listeners.add(key)+ exits.push(callback)+ const unsubscribe = onExit(sid, callback)++ return () => { listeners.delete(key); unsubscribe() }+ })+ const dispose = vi.spyOn(api, 'dispose')++ if (failure === 'attach') {+ vi.spyOn(api, 'attach').mockRejectedValueOnce(new Error('attach failed'))+ }++ const id = createTerminal('/work')+ const view = render(<Harness id={id} />)++ if (failure === 'disconnect') {+ await waitFor(() => expect(screen.getByText('open')).toBeTruthy())+ act(() => Socket.instances[0].close(1006))+ }++ await waitFor(() => expect(screen.getByText('closed')).toBeTruthy())+ expect(listeners.size).toBe(0)+ expect(dispose).toHaveBeenCalledTimes(1)+ expect(Socket.instances[0].readyState).toBe(3)+ act(() => emulator.input('\r'))+ await waitFor(() => expect(screen.getByText('open')).toBeTruthy())+ expect(listeners.size).toBe(2)+ act(() => exits[0]({ code: 0, signal: null }))+ expect($terminals.get().some(tab => tab.id === id)).toBe(true)+ expect(screen.getByText('open')).toBeTruthy()+ act(() => exits[1]({ code: 0, signal: null }))+ expect($terminals.get().some(tab => tab.id === id)).toBe(false)+ expect(dispose).toHaveBeenCalledTimes(2) // Release the exited session before React unmounts.+ view.unmount()+ expect(dispose).toHaveBeenCalledTimes(2)+ expect(listeners.size).toBe(0)+ vi.restoreAllMocks()+})++it('replays server history once, suppresses parser replies, and detaches on remount', async () => {+ seedWebappSession('test-token')+ Socket.persistent = true+ vi.stubGlobal('WebSocket', Socket)+ installBrowserDesktopBridge()+ const api = window.hermesDesktop!.terminal+ const detach = vi.spyOn(api, 'detach')+ const dispose = vi.spyOn(api, 'dispose')+ const id = createTerminal('/work')+ updateTerminalReviveBuffer(id, SAVED_HISTORY)+ const firstView = render(<Harness id={id} />)+ await waitFor(() => expect(screen.getByText('open')).toBeTruthy())+ expect(emulator.output).not.toContain('saved history')+ expect($terminals.get()[0].persistent).toBe(true)+ // Creation can already have a buffered DA/DSR query; an empty snapshot has+ // no marker, so only the first frame is conservative, not all future output.+ act(() => Socket.instances[0].output('startup history\u001b[6n'))+ expect(Socket.instances[0].sent).toEqual([])+ act(() => Socket.instances[0].output('live query\u001b[6n'))+ expect(Socket.instances[0].sent).toEqual(['\u001b[1;1R'])+ firstView.unmount()+ expect(detach).toHaveBeenCalledTimes(1)+ expect(dispose).not.toHaveBeenCalled()+ render(<Harness id={id} />)+ await waitFor(() => expect(screen.getByText('open')).toBeTruthy())+ const second = Socket.instances[1]+ expect(second.url.searchParams.get('attach')).toBe('shell-1')+ act(() => second.output('history\u001b[6n'))+ expect(second.sent).toEqual(['\u001b[RESIZE:80;24]'])+ act(() => second.output('live query\u001b[6n'))+ expect(second.sent).toEqual(['\u001b[RESIZE:80;24]', '\u001b[1;1R'])+ act(() => second.close(4410))+ expect(screen.getByText('closed')).toBeTruthy()+ expect(emulator.output).toContain('Press Enter to create a new shell')+ expect($terminals.get().some(tab => tab.id === id)).toBe(true)+ expect(Socket.instances).toHaveLength(2)+ act(() => emulator.input('\r'))+ await waitFor(() => expect(screen.getByText('open')).toBeTruthy())+ expect(Socket.instances[2].url.searchParams.has('attach')).toBe(false)+})++it('close others and close all terminate mounted and unmounted persisted shells', async () => {+ seedWebappSession('test-token')+ Socket.persistent = true+ vi.stubGlobal('WebSocket', Socket)+ installBrowserDesktopBridge()+ const api = window.hermesDesktop!.terminal+ const kept = createTerminal('/work')+ const other = createTerminal('/work')+ const session = await api.start({ cwd: '/work', restoreKey: other })+ await api.detach!(session.id)+ render(<Harness id={kept} />)+ await waitFor(() => expect(screen.getByText('open')).toBeTruthy())+ act(() => closeOtherTerminals(kept))+ await waitFor(() => expect($terminals.get().map(tab => tab.id)).toEqual([kept]))+ act(() => closeAllTerminals())+ await waitFor(() => expect($terminals.get()).toEqual([]))+ const closes = Socket.instances.filter(socket => socket.url.searchParams.get('action') === 'close')+ expect(closes.map(socket => socket.url.searchParams.get('attach')).sort()).toEqual(['shell-1', 'shell-2'])+})++it('preserves saved tabs when page unload closes the browser socket', async () => {+ seedWebappSession('test-token')+ vi.stubGlobal('WebSocket', Socket)+ installBrowserDesktopBridge()+ const id = createTerminal('/work')+ updateTerminalReviveBuffer(id, SAVED_HISTORY)+ render(<Harness id={id} />)+ await waitFor(() => expect(screen.getByText('open')).toBeTruthy())+ act(() => window.dispatchEvent(new Event('beforeunload')))+ expect(Socket.instances[0].readyState).toBe(3)+ expect($terminals.get().find(tab => tab.id === id)?.reviveBuffer).toBe(SAVED_HISTORY)+})diff --git a/apps/desktop/src/app/right-sidebar/terminal/use-terminal-session.ts b/apps/desktop/src/app/right-sidebar/terminal/use-terminal-session.tsindex 41dff61df0a..0110eed5685 100644--- a/apps/desktop/src/app/right-sidebar/terminal/use-terminal-session.ts+++ b/apps/desktop/src/app/right-sidebar/terminal/use-terminal-session.ts@@ -6,7 +6,6 @@ import { Terminal } from '@xterm/xterm'import { useCallback, useEffect, useMemo, useRef, useState } from 'react'import type { CSSProperties } from 'react'-import { writeClipboardText } from '@/components/ui/copy-button'import { triggerHaptic } from '@/lib/haptics'import { isComposerChord } from '@/lib/keybinds/chords'import { $previewTarget } from '@/store/preview'@@ -15,61 +14,27 @@ import { useTheme } from '@/themes/context'import { $terminalInjection } from '../store'import { makeTerminalReader, registerTerminalReader } from './buffer'-import { mirrorSelection, terminalClipboardIntent } from './clipboard'+import { mirrorSelection } from './clipboard'+import { trackTerminalCwd } from './cwd-tracking'import { terminalLinkHandler, terminalWebLinksAddon } from './links'+import { createReviveHistory } from './revive-history'+import { createBootGapFilter } from './revive-snapshot'import {- isMacPlatform,resolveSurfaceColor,shouldOwnAddSelectionShortcut,terminalSelectionAnchor,terminalSelectionLabel,terminalTheme} from './selection'-import { registerTerminalContextMenu } from './terminal-context-menu'+import { createSnapshotPersister } from './snapshot-persister'+import { bindTerminalDrop } from './terminal-drop'import { prepareTerminalFontFamily } from './terminal-font'-import {- closeTerminal,- redrawAllTerminals,- registerWebglRefresh,- updateTerminalRestoreCwd,- updateTerminalReviveBuffer-} from './terminals'+import { bindTerminalActivity, bindTerminalClipboard } from './terminal-input-bindings'+import { createSessionAttemptController } from './terminal-session-attempt'+import type { TerminalStatus } from './terminal-session-attempt'+import { redrawAllTerminals, registerWebglRefresh } from './terminals'import { useTerminalFontController } from './use-terminal-font'-// How many scrollback lines to serialize for relaunch restore. Mirrors VS Code's-// terminal.integrated.persistentSessionScrollback default; the store caps the-// resulting string so a long line-wrapped buffer can't blow the storage budget.-const PERSISTENT_SESSION_SCROLLBACK = 200--// Leading-edge throttle window for capturing history. The first output after an-// idle gap persists almost immediately (so `cmd; quit` is on disk before the-// renderer tears down), then at most once per window while output streams.-const SNAPSHOT_THROTTLE_MS = 750--// Minimum gap between main-side PTY cwd probes. The probe spawns lsof on macOS,-// so keep it well throttled — cwd only changes on a `cd`, which the reporter-// already reads off the next output snapshot anyway.-const CWD_PROBE_THROTTLE_MS = 2000--// True once the page/app is tearing down (Cmd+Q, Alt+F4, window close, reload).-// App quit kills the PTYs from the main process, which fires onExit in the-// renderer — but React skips effect cleanups on teardown, so the per-instance-// `disposed` flag never flips. Without this guard those teardown exits would call-// closeTerminal() and wipe the persisted terminal list right before relaunch-// reads it. A real `exit`/Ctrl-D still closes the tab (flag stays false).-let appTearingDown = false--if (typeof window !== 'undefined') {- const markTearingDown = () => {- appTearingDown = true- }-- window.addEventListener('pagehide', markTearingDown)- window.addEventListener('beforeunload', markTearingDown)-}--type TerminalStatus = 'closed' | 'open' | 'starting'-// ⌘/Ctrl+L is a global shortcut, so a text selection in the file preview pane// lands in this handler with no xterm selection. Label those with the previewed// file's name instead of the shell, so the composer ref reads as a file quote@@ -81,160 +46,6 @@ function previewSelectionLabel(): string {return source.split(/[\\/]/).filter(Boolean).pop() || target?.label?.trim() || ''}-const HERMES_PATHS_MIME = 'application/x-hermes-paths'--function readEscapeSequence(data: string, index: number) {- if (data.charCodeAt(index) !== 0x1b || index + 1 >= data.length) {- return null- }-- const kind = data[index + 1]-- if (kind === '[') {- for (let i = index + 2; i < data.length; i += 1) {- const code = data.charCodeAt(i)-- if (code >= 0x40 && code <= 0x7e) {- return data.slice(index, i + 1)- }- }- }-- if (kind === ']') {- for (let i = index + 2; i < data.length; i += 1) {- if (data.charCodeAt(i) === 0x07) {- return data.slice(index, i + 1)- }-- if (data.charCodeAt(i) === 0x1b && data[i + 1] === '\\') {- return data.slice(index, i + 2)- }- }- }-- // Character-set and other short ESC forms are three bytes (e.g. ESC ( B).- // Treating only ESC+( as a sequence leaves the final selector ("B") as- // printable text, which disarms the initial prompt-gap stripper before it can- // eat the shell's leading newline.- if (['(', ')', '*', '+', '-', '.', '/'].includes(kind) && index + 2 < data.length) {- return data.slice(index, index + 3)- }-- return data.slice(index, Math.min(index + 2, data.length))-}--function stripEscapeSequences(data: string) {- let index = 0- let text = ''-- while (index < data.length) {- const sequence = readEscapeSequence(data, index)-- if (sequence) {- index += sequence.length- } else {- text += data[index]- index += 1- }- }-- return text-}--// Keep only the ANSI escape sequences from a chunk, dropping printable text. Lets-// us apply control codes (e.g. a clear-screen) while discarding boot spacers and-// zsh's reverse-video "%" partial-line marker.-function keepEscapeSequences(data: string) {- let index = 0- let out = ''-- while (index < data.length) {- if (data.charCodeAt(index) === 0x1b) {- const sequence = readEscapeSequence(data, index)-- if (sequence) {- out += sequence- index += sequence.length-- continue- }- }-- index += 1- }-- return out-}--function stripInitialPromptGap(data: string) {- let index = 0- let prefix = ''-- while (index < data.length) {- const sequence = readEscapeSequence(data, index)-- if (sequence) {- prefix += sequence- index += sequence.length- } else if (data[index] === '\r' || data[index] === '\n') {- index += 1- } else {- return prefix + data.slice(index)- }- }-- return prefix-}--// A row's content with ANSI escapes and all whitespace stripped — '' for a-// spacer / prompt-gap / zsh `%` marker row.-const visibleText = (line: string) => stripEscapeSequences(line).replace(/[\s%]/g, '')--// Trim the shell's trailing idle prompt from a serialized snapshot before it's-// persisted. Without it, the saved buffer ends in the old prompt, so the next-// launch replays it directly above the fresh shell's prompt ("double bar").-//-// An interactive shell always reprints its prompt after a command finishes, so-// the tail of an idle buffer is the prompt, never real history. Two prompt-// shapes exist:-// - Spaced/multi-line (starship add_newline, powerline): a blank line sits-// just above the prompt, so the short block after the last blank is dropped.-// - Single-line (default PowerShell `PS C:\..>`, bash `user@host:~$`): no blank-// separator, so the final line itself is the prompt and is dropped.-// The fresh shell reprints the current prompt on boot either way, so only the-// redundant idle prompt is removed — command output is preserved.-export function cleanReviveSnapshot(serialized: string): string {- const lines = serialized.split(/\r?\n/)-- while (lines.length && !visibleText(lines[lines.length - 1])) {- lines.pop()- }-- if (lines.length === 0) {- return ''- }-- const lastBlank = lines.findLastIndex(line => !visibleText(line))- const spacedPrompt = lastBlank >= 0 && lines.length - 1 - lastBlank <= 3-- // Spaced prompt (starship/powerline): drop the block after the blank- // separator. Otherwise the last line is the single-line prompt itself.- lines.length = spacedPrompt ? lastBlank : lines.length - 1-- return lines.join('\r\n')-}--// True when a revive buffer holds no real scrollback: empty, or only repeats of-// one line (the idle prompt). This is the idle-accumulation signature (#61572) —-// each relaunch replayed the saved prompt(s) and the fresh shell printed one more-// below, growing the tab by a line per cycle. Real sessions vary (prompt +-// command + output), so genuine short histories are never mistaken for idle.-export function isIdlePromptOnly(serialized: string): boolean {- const lines = serialized.split(/\r?\n/).map(visibleText).filter(Boolean)-- return lines.length === 0 || lines.every(line => line === lines[0])-}-interface UseTerminalSessionOptions {/** Renderer-side terminal id (the tab handle), used to key the agent reader. */id: string@@ -251,43 +62,6 @@ interface UseTerminalSessionOptions {onShell?: (shell: string) => void}-// Parse a working directory out of a cwd-reporting OSC payload. Covers OSC 7-// (`file://host/path`, emitted by many bash/zsh integrations) and OSC 9;9-// (`9;<path>`, ConEmu/Windows-Terminal style some PowerShell profiles emit).-// Returns null for anything unrecognized so callers can ignore it.-export function parseOscCwd(code: 7 | 9, payload: string): string | null {- if (code === 9) {- // OSC 9;9;<path> — the leading "9;" selects the cwd sub-command.- if (!payload.startsWith('9;')) {- return null- }-- const raw = payload.slice(2).trim().replace(/^"|"$/g, '')-- return raw || null- }-- // OSC 7 — a file URI. Strip the scheme + authority and percent-decode.- const match = /^file:\/\/[^/]*(\/.*)$/.exec(payload.trim())-- if (!match) {- return null- }-- let raw = match[1]-- try {- raw = decodeURIComponent(raw)- } catch {- // Keep the undecoded path if it isn't valid percent-encoding.- }-- // Windows file URIs carry a leading slash before the drive (`/C:/Users`).- const windows = /^\/[A-Za-z]:[\\/]/.exec(raw)-- return (windows ? raw.slice(1) : raw) || null-}-// Bind the palette to the live skin surface so the terminal blends with the app// (and the contrast clamp has a real background to work against).function withSurface(theme: ReturnType<typeof terminalTheme>) {@@ -296,94 +70,6 @@ function withSurface(theme: ReturnType<typeof terminalTheme>) {return { ...theme, background: surface, cursorAccent: surface }}-function transferHasDropCandidates(t: DataTransfer): boolean {- if (t.types?.includes(HERMES_PATHS_MIME)) {- return true- }-- if ((t.files?.length ?? 0) > 0) {- return true- }-- for (let i = 0; i < (t.items?.length ?? 0); i += 1) {- if (t.items[i]?.kind === 'file') {- return true- }- }-- return false-}--function collectDroppedPaths(t: DataTransfer): string[] {- const seen = new Set<string>()-- const push = (value: unknown) => {- if (typeof value !== 'string') {- return- }-- const path = value.trim()-- if (path) {- seen.add(path)- }- }-- try {- const raw = t.getData(HERMES_PATHS_MIME)-- if (raw) {- for (const entry of JSON.parse(raw) as { path?: unknown }[]) {- push(entry?.path)- }- }- } catch {- // Malformed in-app drag payload — fall through to OS files.- }-- const getPath = window.hermesDesktop?.getPathForFile-- const addFile = (file: File | null) => {- if (!file || !getPath) {- return- }-- try {- push(getPath(file))- } catch {- // File handle unavailable.- }- }-- for (let i = 0; i < (t.files?.length ?? 0); i += 1) {- addFile(t.files.item(i))- }-- for (let i = 0; i < (t.items?.length ?? 0); i += 1) {- const item = t.items[i]-- if (item?.kind === 'file') {- addFile(item.getAsFile())- }- }-- return [...seen]-}--function quotePathForShell(path: string, shellName: string): string {- const shell = shellName.toLowerCase()-- if (shell.includes('powershell') || shell.includes('pwsh')) {- return `'${path.replace(/'/g, "''")}'`- }-- if (shell.includes('cmd')) {- return `"${path.replace(/"/g, '""')}"`- }-- return `'${path.replace(/'/g, "'\\''")}'`-}-export function useTerminalSession({id,cwd,@@ -573,196 +259,78 @@ export function useTerminalSession({term.loadAddon(terminalWebLinksAddon())term.unicode.activeVersion = '11'- // Replay last session's scrollback before the fresh shell boots. The process- // is NOT revived — a new shell starts one line below the restored history.- // Stripping the boot gap still applies to the live shell output that follows,- // so the fresh prompt lands flush under the restored block.- const initialReviveBuffer = initialReviveBufferRef.current-- if (initialReviveBuffer) {- term.write(initialReviveBuffer)- term.write('\r\n')- }-- // Track the shell's working directory so a reopened tab restarts where the- // user last `cd`'d. Two independent signals feed it: cwd-reporting OSC- // sequences (immediate, for shells configured to emit them) and a periodic- // PTY cwd probe on the main side (shell-agnostic on POSIX). The store- // updater de-dupes, so both feeding it is harmless.- const recordCwd = (next: string | null | undefined) => {- const value = (next ?? '').trim()-- if (!value || value === lastObservedCwdRef.current) {- return- }-- lastObservedCwdRef.current = value- updateTerminalRestoreCwd(id, value)- }-- const cwdOscHandlers = ([7, 9] as const).map(code =>- term.parser.registerOscHandler(code, payload => {- recordCwd(parseOscCwd(code, payload))-- return false // let the sequence propagate; we only observe it- })- )-- cleanup.push(() => cwdOscHandlers.forEach(handler => handler.dispose()))-- let cwdProbeAt = 0-- const probeCwd = () => {- const sessionId = sessionIdRef.current-- if (!sessionId || !terminalApi.cwd || Date.now() - cwdProbeAt < CWD_PROBE_THROTTLE_MS) {- return- }-- cwdProbeAt = Date.now()- void terminalApi- .cwd(sessionId)- .then(recordCwd)- .catch(() => {- // Best-effort: no cwd probe on this platform (e.g. Windows).- })- }-- // Capture the buffer on a leading-edge throttle and persist synchronously via- // the store. No unload hook: by the time the user quits, a recent snapshot is- // already on disk (the prior beforeunload-based attempt lost the last output).- let snapshotTimer = 0- let lastSnapshotAt = 0+ const stripBootGap = createBootGapFilter()- const persistSnapshot = () => {- if (disposed) {- return- }-- lastSnapshotAt = Date.now()-- // No user input this session: never re-serialize. The live buffer now holds- // the replayed history plus a fresh boot prompt, and re-saving that is- // exactly what grew idle tabs by one prompt line per relaunch (#61572).- // If the buffer we loaded carried no real scrollback (empty, or only a- // repeated prompt), clear it so the next launch shows a single fresh prompt- // and any pre-existing accumulation heals. Otherwise leave the prior- // snapshot untouched so real history from an earlier active session- // survives an idle reopen instead of being overwritten.- if (!hasSessionActivityRef.current) {- if (isIdlePromptOnly(initialReviveBufferRef.current ?? '')) {- updateTerminalReviveBuffer(id, '')+ // Created first because history replay and snapshots read whether its shell+ // is server-persistent; its callbacks only run once start() is called.+ const session = createSessionAttemptController(id, {+ isDisposed: () => disposed,+ isReplayingHistory: () => history.isReplaying(),+ onStarted: started => {+ lastSentSize = { cols: term.cols, rows: term.rows }+ shellNameRef.current = started.shell || 'shell'+ setShellName(started.shell || 'shell')+ onShellRef.current?.(started.shell || 'shell')++ const initial = term.hasSelection() ? term.getSelection() : ''+ selectionRef.current = initial+ selectionLabelRef.current = initial ? terminalSelectionLabel(term, shellNameRef.current, initial) : ''+ },+ resolveCwd: () => lastObservedCwdRef.current || initialRestoreCwdRef.current || cwd,+ restoreHistory: () => history.restore(),+ sessionIdRef,+ setStatus,+ term,+ terminalApi,+ writeOutput: data => {+ const text = stripBootGap(data)++ if (text !== null) {+ term.write(text, snapshots.schedule)}-- return- }-- try {- const snapshot = serialize.serialize({ scrollback: PERSISTENT_SESSION_SCROLLBACK })- updateTerminalReviveBuffer(id, cleanReviveSnapshot(snapshot))- } catch {- // Best-effort restore: never let serialization break a live terminal.- }-- // A user command may have `cd`'d; refresh the persisted cwd (throttled).- probeCwd()- }-- const scheduleSnapshot = () => {- if (snapshotTimer) {- return- }-- const elapsed = Date.now() - lastSnapshotAt-- if (elapsed >= SNAPSHOT_THROTTLE_MS) {- persistSnapshot()-- return- }-- snapshotTimer = window.setTimeout(() => {- snapshotTimer = 0- persistSnapshot()- }, SNAPSHOT_THROTTLE_MS - elapsed)- }-- cleanup.push(() => {- if (snapshotTimer) {- window.clearTimeout(snapshotTimer)}})- const onDragOver = (e: DragEvent) => {- if (!e.dataTransfer || !transferHasDropCandidates(e.dataTransfer)) {- return- }+ const initialReviveBuffer = initialReviveBufferRef.current ?? ''+ const history = createReviveHistory(term, initialReviveBuffer, session.isPersistent)- e.preventDefault()- e.stopPropagation()- e.dataTransfer.dropEffect = 'copy'+ if (!terminalApi.detach) {+ history.restore()}- const onDrop = (e: DragEvent) => {- const id = sessionIdRef.current+ const cwdTracker = trackTerminalCwd(id, {+ getSessionId: () => sessionIdRef.current,+ lastObservedCwdRef,+ term,+ terminalApi+ })- if (!id || !e.dataTransfer || !transferHasDropCandidates(e.dataTransfer)) {- return- }+ cleanup.push(cwdTracker.dispose)- e.preventDefault()- e.stopPropagation()- const paths = collectDroppedPaths(e.dataTransfer)+ const snapshots = createSnapshotPersister(id, {+ hasSessionActivity: () => hasSessionActivityRef.current,+ isDisposed: () => disposed,+ isPersistent: session.isPersistent,+ probeCwd: cwdTracker.probe,+ reviveBuffer: initialReviveBuffer,+ serialize+ })- if (!paths.length) {- return- }+ cleanup.push(snapshots.cancel)+ const markActivity = () => {hasSessionActivityRef.current = true- void terminalApi.write(id, `${paths.map(p => quotePathForShell(p, shellNameRef.current)).join(' ')} `)- term.focus()- triggerHaptic('selection')}- host.addEventListener('dragenter', onDragOver)- host.addEventListener('dragover', onDragOver)- host.addEventListener('drop', onDrop)- cleanup.push(() => {- host.removeEventListener('dragenter', onDragOver)- host.removeEventListener('dragover', onDragOver)- host.removeEventListener('drop', onDrop)- })-- // While armed, strip leading blank rows so the first prompt lands at the- // very top (no starship `add_newline` gap). Do this only on renderer output:- // never inject Ctrl-L or other cleanup keystrokes into the user's shell.- let stripLeading = true-- const armedWrite = (data: string) => {- if (!stripLeading) {- term.write(data)-- return- }-- const next = stripInitialPromptGap(data)- const visible = stripEscapeSequences(next).replace(/[\s%]/g, '')-- if (!visible) {- // Spacer / lone clear-screen / zsh `%` marker: apply control codes but- // drop the blank text and stay armed so the prompt still lands at top.- const controls = keepEscapeSequences(next)-- if (controls) {- term.write(controls)- }-- return- }-- stripLeading = false- term.write(next)- }+ cleanup.push(+ bindTerminalDrop(host, {+ getSessionId: () => sessionIdRef.current,+ getShellName: () => shellNameRef.current,+ markActivity,+ term,+ terminalApi+ })+ )const fitAndResize = () => {if (disposed || !host.isConnected || host.clientWidth <= 0 || host.clientHeight <= 0) {@@ -775,11 +343,11 @@ export function useTerminalSession({return}- const id = sessionIdRef.current+ const sessionId = sessionIdRef.current- if (id && (lastSentSize?.cols !== term.cols || lastSentSize?.rows !== term.rows)) {+ if (sessionId && (lastSentSize?.cols !== term.cols || lastSentSize?.rows !== term.rows)) {lastSentSize = { cols: term.cols, rows: term.rows }- void terminalApi.resize(id, { cols: term.cols, rows: term.rows })+ void terminalApi.resize(sessionId, { cols: term.cols, rows: term.rows })}}@@ -814,14 +382,9 @@ export function useTerminalSession({}})- const dataDisposable = term.onData(data => {- hasSessionActivityRef.current = true- const id = sessionIdRef.current+ cleanup.push(bindTerminalActivity(term, host, markActivity))- if (id) {- void terminalApi.write(id, data)- }- })+ const dataDisposable = term.onData(session.input)cleanup.push(() => dataDisposable.dispose())@@ -839,150 +402,7 @@ export function useTerminalSession({cleanup.push(() => selectionDisposable.dispose())- // The app context menu resolves right-clicks on this host through the- // registered handle: xterm's selection is not a DOM selection, so the- // DOM resolver would see nothing here. The same handle answers the- // focus-routed Ctrl/Cmd+R: main claimed the keystroke, so re-deliver the- // ^R byte to the PTY ourselves (#96482).- cleanup.push(- registerTerminalContextMenu(host, {- getSelection: () => term.getSelection(),- paste: text => {- hasSessionActivityRef.current = true- term.focus()- term.paste(text)- },- reload: () => {- hasSessionActivityRef.current = true- const sessionId = sessionIdRef.current-- if (sessionId) {- void terminalApi.write(sessionId, '\x12')- }- },- selectAll: () => term.selectAll(),- // The close-tab chord main claimed over this terminal is the shell's- // word erase: re-deliver the ^W byte instead of closing the pane- // (#65457). False when the session is gone, so the caller closes.- wordErase: () => {- hasSessionActivityRef.current = true- const sessionId = sessionIdRef.current-- if (!sessionId) {- return false- }-- void terminalApi.write(sessionId, '\x17')-- return true- }- })- )-- // Copy/paste chords. Returning false stops xterm from also sending the key- // to the PTY; every path that doesn't copy or paste returns true, so plain- // Ctrl+C with no selection still interrupts the running process.- term.attachCustomKeyEventHandler(event => {- const intent = terminalClipboardIntent(event, {- hasSelection: Boolean(term.getSelection()),- isMac: isMacPlatform()- })-- if (!intent) {- return true- }-- event.preventDefault()-- if (intent === 'copy') {- const text = term.getSelection()- // Write through the main process: the renderer's clipboard API throws- // "Write permission denied" whenever the document isn't focused.- void writeClipboardText(text).catch(() => {- // Clipboard unavailable — the selection stays put so the user can retry.- })- term.clearSelection()- triggerHaptic('selection')-- return false- }- void (async () => {- const text = (await window.hermesDesktop?.readClipboard?.()) ?? ''-- if (text) {- hasSessionActivityRef.current = true- term.paste(text)- }- })()-- return false- })-- const startSession = () =>- void terminalApi- // Prefer the prior session's last cwd so a reopened tab lands where the- // user last `cd`'d; the main side falls back to the launch cwd (then- // home) if that dir no longer exists.- .start({ cols: term.cols, cwd: initialRestoreCwdRef.current || cwd, rows: term.rows })- .then(async session => {- if (disposed) {- void terminalApi.dispose(session.id)-- return- }-- sessionIdRef.current = session.id- lastSentSize = { cols: term.cols, rows: term.rows }- shellNameRef.current = session.shell || 'shell'- setShellName(session.shell || 'shell')- onShellRef.current?.(session.shell || 'shell')-- const initial = term.hasSelection() ? term.getSelection() : ''- selectionRef.current = initial- selectionLabelRef.current = initial ? terminalSelectionLabel(term, shellNameRef.current, initial) : ''-- cleanup.push(- terminalApi.onData(session.id, data => {- armedWrite(data)- scheduleSnapshot()- }),- terminalApi.onExit(session.id, () => {- // Shell exited (`exit` / Ctrl-D / crash) — drop the tab like a real- // terminal. closeTerminal hides the pane when it's the last one.- // Skip if we're tearing down (cleanup disposes the PTY) OR the app- // is quitting/reloading: on quit the main process kills every PTY,- // firing this exit, but React skips the cleanup so `disposed` stays- // false — running closeTerminal here would wipe the persisted tabs- // right before relaunch restores them.- if (!disposed && !appTearingDown) {- // Release the main-side session explicitly instead of relying- // on the unmount cleanup's timing — the exit→unmount hop is- // async, and a teardown in between would skip dispose and leak- // the PTY (#128942). The cleanup's later dispose is a no-op.- void terminalApi.dispose(session.id)- closeTerminal(id)- }- })- )-- const attached = await terminalApi.attach(session.id)-- if (!attached) {- throw new Error('Terminal session disappeared before its output stream attached')- }-- setStatus('open')-- window.requestAnimationFrame(() => {- fitAndResize()- term.clearSelection() // drop any selection painted over transient boot rows- term.focus()- })- })- .catch(error => {- setStatus('closed')- term.write(`Terminal failed to start: ${error instanceof Error ? error.message : String(error)}\r\n`)- })+ cleanup.push(bindTerminalClipboard(term, host, markActivity, session.input, () => Boolean(sessionIdRef.current)))// Open + fit + start only once webfonts settle. Fitting with fallback metrics// picks the wrong row count, the shell boots at that size, then the real font@@ -1038,7 +458,11 @@ export function useTerminalSession({cleanup.push(registerWebglRefresh(term, () => webglRef.current))fitAndResize()- startSession()+ void (terminalApi.detach ? Promise.resolve() : history.ready).then(() => {+ if (!disposed && host.isConnected) {+ session.start()+ }+ })}void prepareTerminalFontFamily(@@ -1088,16 +512,10 @@ export function useTerminalSession({disposed = truemountedRef.current = falsecancelMountWatch()+ session.release()cleanup.forEach(run => run())fitRef.current = null- const id = sessionIdRef.current- sessionIdRef.current = null-- if (id) {- void terminalApi.dispose(id)- }-term.dispose()termRef.current = nullwebglRef.current = null@@ -1107,7 +525,7 @@ export function useTerminalSession({}// `id` is stable for the instance's life (keyed by tab id), so listing it// doesn't re-create the shell — it just satisfies the deps check for the- // closeTerminal(id) call in onExit.+ // store writes keyed by it.}, [addSelectionToChat, cwd, id, latestFontFamilyRef, mountedRef])useEffect(() => {@@ -1151,7 +569,8 @@ export function useTerminalSession({// full redraw against the live buffer, then focus. The atlas is shared across// every terminal with the same render config, so rebuild ALL of them (see// redrawAllTerminals) — refreshing only this one leaves its siblings drawing- // from wiped atlas pages.+ // from wiped atlas pages. Also covers the first open: status flips to 'open'+ // once the shell attaches.useEffect(() => {if (!active || status !== 'open') {returndiff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/browser-manage-refusal.ts b/apps/desktop/src/app/session/hooks/use-prompt-actions/browser-manage-refusal.tsnew file mode 100644index 00000000000..56bc60145c6--- /dev/null+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/browser-manage-refusal.ts@@ -0,0 +1,9 @@+import { isBrowserHostedDesktop } from '@/lib/platform'++// A remote connection refuses /browser connect|disconnect: both drive the CDP+// connection inside the gateway process. The Webapp is always remote and has no+// local gateway to switch to, so it names the machine the command acts on instead.+export const remoteBrowserManageRefusal = (action: 'connect' | 'disconnect'): string =>+ isBrowserHostedDesktop()+ ? `/browser ${action} isn't available in the Webapp — it manages a Chromium-family browser on the machine running Hermes. Run it from Hermes Desktop or the CLI on that machine.`+ : '/browser connect manages a Chromium-family browser on the gateway host — only available when connected to a local gateway.'diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/index.ts b/apps/desktop/src/app/session/hooks/use-prompt-actions/index.tsindex 9ce6802945b..a38707fd496 100644--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/index.ts+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/index.ts@@ -133,7 +133,19 @@ export async function uploadComposerAttachment(const path = attachment.path ?? ''const label = attachment.label || pathLabel(path)- const uploadBytes = remote || attachmentPathNeedsUpload(path, backendCwd, terminalBackend)++ // Edit-message drops bypass the main composer store, so also resolve their+ // source descriptor here. Absence means an older browser backend/native file+ // and retains the existing byte-upload rules.+ const stagedUpload = attachment.kind === 'file'+ ? attachment.stagedUpload ?? window.hermesDesktop?.getStagedFileForAttach?.(path)+ : undefined++ if (stagedUpload && stagedUpload.path !== path) {+ throw new Error(`Could not attach ${label}: staged source changed; select the file again`)+ }++ const uploadBytes = !stagedUpload && (remote || attachmentPathNeedsUpload(path, backendCwd, terminalBackend))if (attachment.kind === 'image' && serverOwnsComposerQueue(storedSessionId ?? opts.sessionId)) {// Pin HTTP to the same owner before the native byte read yields. Images@@ -196,9 +208,12 @@ export async function uploadComposerAttachment(const result = await requestGateway<FileAttachResponse>('file.attach', {name: label,- path,session_id: liveSessionId,- ...(fileDataUrl ? { data_url: fileDataUrl } : {})+ // Omit path as well as bytes for the provenance-aware branch: an older+ // RPC implementation must reject it rather than ignore source ownership.+ ...(stagedUpload+ ? { staged_upload: stagedUpload }+ : { path, ...(fileDataUrl ? { data_url: fileDataUrl } : {}) })})if (!result.attached || !result.ref_text) {@@ -209,6 +224,7 @@ export async function uploadComposerAttachment(...attachment,attachedSessionId: liveSessionId,refText: result.ref_text,+ ...(stagedUpload ? { stagedUpload } : {}),uploadState: undefined}}@@ -462,6 +478,7 @@ export function usePromptActions({path: nextAttachment.path,mime: nextAttachment.mime,refText: nextAttachment.refText,+ stagedUpload: nextAttachment.stagedUpload,uploadState: nextAttachment.uploadState})} else {diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/slash.ts b/apps/desktop/src/app/session/hooks/use-prompt-actions/slash.tsindex 58e92552947..dad675337e2 100644--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/slash.ts+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/slash.ts@@ -69,6 +69,7 @@ import type {SlashExecResponse} from '../../../types'+import { remoteBrowserManageRefusal } from './browser-manage-refusal'import { adoptPreparedSubmission, preparedSubmissionKey } from './prepared-submissions'import { queueKickoffIfSessionBusy } from './queue-if-busy'import { resolveTargetSessionId } from './resolve-target-session'@@ -1335,9 +1336,7 @@ export function useSlashCommand(deps: SlashCommandDeps) {}if ((cmdAction === 'connect' || cmdAction === 'disconnect') && $connection.get()?.mode === 'remote') {- renderSlashOutput(- '/browser connect manages a Chromium-family browser on the gateway host — only available when connected to a local gateway.'- )+ renderSlashOutput(remoteBrowserManageRefusal(cmdAction))return}diff --git a/apps/desktop/src/app/settings/cloud-team-change.ts b/apps/desktop/src/app/settings/cloud-team-change.tsindex 66380c077fa..dae242b3ae6 100644--- a/apps/desktop/src/app/settings/cloud-team-change.ts+++ b/apps/desktop/src/app/settings/cloud-team-change.ts@@ -21,6 +21,14 @@ export async function reconnectMovedCloudAgent(org: string,isCurrent: () => boolean): Promise<boolean> {+ const connections = desktop.connections++ // Browser-hosted Desktop has no native registry. Do not log it out while+ // attempting a reconnect whose new ownership cannot be saved.+ if (!connections) {+ return false+ }+const { url } = connectionawait desktop.oauthLogoutConnectionConfig(url)@@ -34,7 +42,7 @@ export async function reconnectMovedCloudAgent(return false}- await desktop.connections.save({+ await connections.save({id: connection.id,kind: 'cloud',label: connection.label,diff --git a/apps/desktop/src/app/settings/connections-registry.test.tsx b/apps/desktop/src/app/settings/connections-registry.test.tsxindex 4c80a0c3b1a..c9acb13e418 100644--- a/apps/desktop/src/app/settings/connections-registry.test.tsx+++ b/apps/desktop/src/app/settings/connections-registry.test.tsx@@ -84,7 +84,7 @@ describe('ConnectionsRegistrySection', () => {const applyConnectionConfig = vi.fn()const select = vi.fn()Object.assign(window.hermesDesktop, { applyConnectionConfig })- Object.assign(window.hermesDesktop.connections, { select })+ Object.assign(window.hermesDesktop.connections!, { select })render(<ConnectionsRegistrySection />)fireEvent.click(await screen.findByRole('button', { name: 'Edit' }))const values = screen.getAllByPlaceholderText('Saved — leave blank to keep')diff --git a/apps/desktop/src/app/settings/gateway-settings.test.tsx b/apps/desktop/src/app/settings/gateway-settings.test.tsxindex dd722857afc..72c23d7bcac 100644--- a/apps/desktop/src/app/settings/gateway-settings.test.tsx+++ b/apps/desktop/src/app/settings/gateway-settings.test.tsx@@ -2,11 +2,14 @@ import { GatewayReauthRequiredError } from '@hermes/shared'import { act, cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'+import { installBrowserDesktopBridge } from '@/lib/browser-desktop-bridge'import { $notifications } from '@/store/notifications'import { deferred } from '@/test/deferred'+import { clearWebappSession, seedWebappSession } from '@/test/webapp-session'// Collect the component graph before the behavioral test deadline starts.import { GatewaySettings } from './gateway-settings'+import { SETTING_IDS, settingElementId } from './settings-manifest'const { registry, activeId, selectConnection } = vi.hoisted(() => ({registry: { value: null as any },@@ -57,6 +60,8 @@ const localConnection = {}beforeEach(() => {+ registry.value = null+ selectConnection.mockReset().mockResolvedValue(undefined)getConnectionConfig.mockResolvedValue(localConnection)saveConnectionConfig.mockResolvedValue(localConnection)cloudStatus.mockResolvedValue({ portalBaseUrl: 'https://portal.nousresearch.com', signedIn: true })@@ -76,6 +81,11 @@ beforeEach(() => {afterEach(() => {cleanup()+ Reflect.deleteProperty(window, '__HERMES_AUTH_REQUIRED__')+ Reflect.deleteProperty(window, 'hermesDesktop')+ window.document.documentElement.removeAttribute('data-hermes-desktop-host')+ vi.unstubAllGlobals()+ vi.restoreAllMocks()vi.clearAllMocks()})@@ -413,6 +423,62 @@ describe('GatewaySettings', () => {})})+ // The Webapp is served by one Hermes host and can only reach that host, so no+ // mode switch, Cloud sign-in or saved connection can act there. What applies+ // is which host this is and, behind the sign-in gate, signing out of it.+ describe('in the Webapp', () => {+ // A gated host signs its browser in with a cookie; an unauthenticated one through its private launch link.+ const installWebapp = (credential: 'gated' | 'launch-link') => {+ Reflect.deleteProperty(window, 'hermesDesktop')++ if (credential === 'gated') {+ Object.assign(window, { __HERMES_AUTH_REQUIRED__: true })+ } else {+ seedWebappSession('served-token')+ }++ const fetchMock = vi.fn().mockResolvedValue(new Response('', { status: 200 }))+ vi.stubGlobal('fetch', fetchMock)+ expect(installBrowserDesktopBridge()).toBe(true)++ return fetchMock+ }++ afterEach(() => {+ Reflect.deleteProperty(window, '__HERMES_AUTH_REQUIRED__')+ clearWebappSession()+ })++ it.each([false, true])('offers the serving host and its sign-out only (embedded: %s)', async embedded => {+ const fetchMock = installWebapp('gated')+ const toLogin = vi.fn((event: Event) => event.preventDefault())+ window.addEventListener('hermes:browser-reauth-required', toLogin, { once: true })++ render(<GatewaySettings embedded={embedded} />)++ const signOut = await screen.findByRole('button', { name: 'Sign out' })+ expect(screen.getByText(window.location.origin)).toBeTruthy()+ expect(screen.getAllByRole('button')).toEqual([signOut])+ expect(fetchMock).not.toHaveBeenCalled()++ fireEvent.click(signOut)++ await waitFor(() => expect(toLogin).toHaveBeenCalledTimes(1))+ const [requestUrl, init] = fetchMock.mock.calls[0] as [URL, RequestInit]+ expect(requestUrl.pathname).toBe('/auth/logout')+ expect(init.method).toBe('POST')+ })++ it('has nothing to sign out of on a launch-link host', async () => {+ installWebapp('launch-link')++ render(<GatewaySettings />)++ expect(await screen.findByText(window.location.origin)).toBeTruthy()+ expect(screen.queryAllByRole('button')).toEqual([])+ })+ })+it('loads the machine-level connection config (no profile scoping)', async () => {render(<GatewaySettings />)expect(await screen.findByText('Local gateway')).toBeTruthy()@@ -426,6 +492,26 @@ describe('GatewaySettings', () => {expect(screen.queryByText('Applies to')).toBeNull()expect(screen.queryByText('All profiles')).toBeNull()expect(screen.queryByText('Use default gateway')).toBeNull()++ // Browser-host mode has no native secret store, so a bridge without that+ // capability must not advertise a keychain toggle that cannot work.+ expect(screen.queryByText('Encrypt saved secrets with the OS keychain')).toBeNull()+ }, 30_000)++ it('keeps native keychain encryption writable at its settings deep-link target', async () => {+ const setSecretStorageEncryption = vi.fn().mockResolvedValue({ on: true })+ Object.assign(window.hermesDesktop, {+ getSecretStorageEncryption: vi.fn().mockResolvedValue({ on: false }),+ setSecretStorageEncryption+ })++ render(<GatewaySettings />)+ const toggle = await screen.findByRole('switch', { name: 'Encrypt saved secrets with the OS keychain' })+ const target = window.document.getElementById(settingElementId(SETTING_IDS.gateway.keychainEncryption))+ expect(target?.contains(toggle)).toBe(true)+ fireEvent.click(toggle)+ await waitFor(() => expect(setSecretStorageEncryption).toHaveBeenCalledExactlyOnceWith(true))+ expect(toggle.getAttribute('aria-checked')).toBe('true')})// A saved cloud connection on a local-primary device has exactly onediff --git a/apps/desktop/src/app/settings/gateway-settings.tsx b/apps/desktop/src/app/settings/gateway-settings.tsxindex 63a0b3930ac..b9862d8f5b1 100644--- a/apps/desktop/src/app/settings/gateway-settings.tsx+++ b/apps/desktop/src/app/settings/gateway-settings.tsx@@ -31,6 +31,7 @@ import {RefreshCw,Terminal} from '@/lib/icons'+import { isBrowserHostedDesktop } from '@/lib/platform'import { coerceRemoteUrlScheme } from '@/lib/remote-url'import { selectableCardClass } from '@/lib/selectable-card'import { cn } from '@/lib/utils'@@ -46,11 +47,13 @@ import { notify, notifyError, readableError } from '@/store/notifications'import { cloudTeamChanged, reconnectMovedCloudAgent } from './cloud-team-change'import { ConnectionsRegistrySection } from './connections-registry'import { CONTROL_TEXT } from './constants'+import { KeychainEncryptionSetting, useKeychainEncryption } from './keychain-encryption-setting'import { ManagedUpdatesSection } from './managed-updates-section'-import { EmptyState, ListRow, Pill, SettingsContent, SettingsSkeleton, ToggleRow } from './primitives'+import { EmptyState, ListRow, Pill, SettingsContent, SettingsSkeleton } from './primitives'import { SETTING_IDS, settingElementId } from './settings-manifest'import { enrichSelectedSshHost, selectSshHost } from './ssh-host-selection'import { useSettingDeepLink } from './use-setting-deep-link'+import { WebappGatewaySettings } from './webapp-gateway-settings'type Mode = 'local' | 'remote' | 'cloud' | 'ssh'type AuthMode = 'oauth' | 'token'@@ -174,6 +177,10 @@ interface GatewaySettingsProps {export function GatewaySettings({ embedded = false, subpage }: GatewaySettingsProps = {}) {useSettingDeepLink('gateway', page => subpage === undefined || page === subpage)+ if (isBrowserHostedDesktop()) {+ return <WebappGatewaySettings embedded={embedded} />+ }+// Recovery always keeps the complete connection form, regardless of a// settings destination. Other tasks never mount that form or its probes.if (!embedded && subpage === 'devices') {@@ -286,45 +293,9 @@ function GatewayConnectionSettings({ embedded, standalone }: { embedded: booleanvoid refreshConnectionsRegistry().catch(err => notifyError(err, g.failedLoad))}, [g.failedLoad])- // Opt-in OS-keychain encryption for stored gateway secrets. Read lazily via- // IPC (never touches the keychain); flipping it re-encodes stored secrets- // in the main process and can legitimately prompt for keychain access.- const [keychainEncryption, setKeychainEncryptionState] = useState(false)- const [keychainEncryptionBusy, setKeychainEncryptionBusy] = useState(false)-- useEffect(() => {- let cancelled = false-- void window.hermesDesktop- ?.getSecretStorageEncryption?.()- .then(res => {- if (!cancelled && res) {- setKeychainEncryptionState(res.on === true)- }- })- .catch(() => {})-- return () => {- cancelled = true- }- }, [])-- const setKeychainEncryption = async (on: boolean) => {- setKeychainEncryptionBusy(true)- // Optimistic paint; the IPC result (or a failure rollback) gets the last word.- setKeychainEncryptionState(on)-- try {- const res = await window.hermesDesktop.setSecretStorageEncryption(on)-- setKeychainEncryptionState(res?.on === true)- } catch (err) {- setKeychainEncryptionState(!on)- notifyError(err, g.keychainEncryptionFailed)- } finally {- setKeychainEncryptionBusy(false)- }- }+ // Read here rather than in the row, so the flag is in hand by the time the+ // loading skeleton gives way and the toggle paints its real state.+ const keychainEncryption = useKeychainEncryption()const acceptSavedConfig = (config: GatewaySettingsState): void => {const normalized = normalizeGatewaySettingsState(config)@@ -1487,14 +1458,7 @@ function GatewayConnectionSettings({ embedded, standalone }: { embedded: boolean{embedded ? null : (<div className="mt-6 grid gap-1">- <ToggleRow- checked={keychainEncryption}- description={g.keychainEncryptionDesc}- disabled={keychainEncryptionBusy}- id={settingElementId(SETTING_IDS.gateway.keychainEncryption)}- label={g.keychainEncryptionTitle}- onChange={on => void setKeychainEncryption(on)}- />+ <KeychainEncryptionSetting keychain={keychainEncryption} /><ListRowaction={<Button onClick={() => void window.hermesDesktop?.revealLogs()} size="sm" variant="textStrong">diff --git a/apps/desktop/src/app/settings/keychain-encryption-setting.tsx b/apps/desktop/src/app/settings/keychain-encryption-setting.tsxnew file mode 100644index 00000000000..3dd26efb811--- /dev/null+++ b/apps/desktop/src/app/settings/keychain-encryption-setting.tsx@@ -0,0 +1,96 @@+import { useEffect, useState } from 'react'++import { useI18n } from '@/i18n'+import { notifyError } from '@/store/notifications'++import { ToggleRow } from './primitives'+import { SETTING_IDS, settingElementId } from './settings-manifest'++export interface KeychainEncryption {+ busy: boolean+ on: boolean+ set: (on: boolean) => Promise<void>+ /** Both IPC halves exist; the browser host's bridge has neither. */+ supported: boolean+}++/**+ * Opt-in OS-keychain encryption for stored gateway secrets. Read lazily via+ * IPC (never touches the keychain); flipping it re-encodes stored secrets in+ * the main process and can legitimately prompt for keychain access.+ */+export function useKeychainEncryption(): KeychainEncryption {+ const { t } = useI18n()+ const g = t.settings.gateway+ const [keychainEncryption, setKeychainEncryptionState] = useState(false)+ const [keychainEncryptionBusy, setKeychainEncryptionBusy] = useState(false)++ useEffect(() => {+ let cancelled = false++ void window.hermesDesktop+ ?.getSecretStorageEncryption?.()+ .then(res => {+ if (!cancelled && res) {+ setKeychainEncryptionState(res.on === true)+ }+ })+ .catch(() => {})++ return () => {+ cancelled = true+ }+ }, [])++ const setKeychainEncryption = async (on: boolean) => {+ const setEncryption = window.hermesDesktop?.setSecretStorageEncryption++ if (!setEncryption) {+ return+ }++ setKeychainEncryptionBusy(true)+ // Optimistic paint; the IPC result (or a failure rollback) gets the last word.+ setKeychainEncryptionState(on)++ try {+ const res = await setEncryption(on)++ setKeychainEncryptionState(res?.on === true)+ } catch (err) {+ setKeychainEncryptionState(!on)+ notifyError(err, g.keychainEncryptionFailed)+ } finally {+ setKeychainEncryptionBusy(false)+ }+ }++ return {+ busy: keychainEncryptionBusy,+ on: keychainEncryption,+ set: setKeychainEncryption,+ supported:+ typeof window.hermesDesktop?.getSecretStorageEncryption === 'function' &&+ typeof window.hermesDesktop?.setSecretStorageEncryption === 'function'+ }+}++export function KeychainEncryptionSetting({ keychain }: { keychain: KeychainEncryption }) {+ const { t } = useI18n()+ const g = t.settings.gateway++ if (!keychain.supported) {+ return null+ }++ return (+ <ToggleRow+ checked={keychain.on}+ description={g.keychainEncryptionDesc}+ disabled={keychain.busy}+ id={settingElementId(SETTING_IDS.gateway.keychainEncryption)}+ label={g.keychainEncryptionTitle}+ onChange={on => void keychain.set(on)}+ />+ )+}diff --git a/apps/desktop/src/app/settings/other-subpages.ts b/apps/desktop/src/app/settings/other-subpages.tsindex 8fd3cc425bd..ca4a1e25b34 100644--- a/apps/desktop/src/app/settings/other-subpages.ts+++ b/apps/desktop/src/app/settings/other-subpages.ts@@ -1,11 +1,19 @@+import { isBrowserHostedDesktop } from '@/lib/platform'++import type { SettingsSubpage } from './subpages'++// Gateway tasks and search rows that only native Desktop can act on; the Webapp's+// Gateways page is just its serving host (see WebappGatewaySettings).+export const nativeHostOnly = () => !isBrowserHostedDesktop()+// Pages with separate tasks expose content-only subpages. Billing keeps its// existing capability-gated bview=overview|plans flow rather than adding a// second route parameter that could disagree with a pending financial action.-export const OTHER_SUBPAGES: Record<string, { id: string; labelKey: string }[]> = {+export const OTHER_SUBPAGES: Record<string, SettingsSubpage[]> = {gateway: [- { id: 'connection', labelKey: 'gatewayConnection' },- { id: 'devices', labelKey: 'gatewayDevices' },- { id: 'managed-updates', labelKey: 'gatewayManagedUpdates' }+ { id: 'connection', labelKey: 'gatewayConnection', available: nativeHostOnly },+ { id: 'devices', labelKey: 'gatewayDevices', available: nativeHostOnly },+ { id: 'managed-updates', labelKey: 'gatewayManagedUpdates', available: nativeHostOnly }],keybinds: [{ id: 'shortcuts', labelKey: 'keyboardShortcuts' },diff --git a/apps/desktop/src/app/settings/sessions-settings.test.tsx b/apps/desktop/src/app/settings/sessions-settings.test.tsxindex 3a7eb077859..e2a2781cac4 100644--- a/apps/desktop/src/app/settings/sessions-settings.test.tsx+++ b/apps/desktop/src/app/settings/sessions-settings.test.tsx@@ -26,6 +26,13 @@ vi.mock('@/store/sidebar-archive', async importOriginal => ({listEveryArchivedSession}))+const selectDesktopPaths = vi.hoisted(() => vi.fn())++vi.mock('@/lib/desktop-fs', async importOriginal => ({+ ...(await importOriginal<Record<string, unknown>>()),+ selectDesktopPaths+}))+const archivedMatrixSession = {archived: true,ended_at: null,@@ -66,3 +73,32 @@ describe('SessionsSettings unarchive', () => {expect($sessions.get()).toEqual([])})})++describe('SessionsSettings default directory in a browser tab', () => {+ afterEach(() => {+ delete document.documentElement.dataset.hermesDesktopHost+ Reflect.deleteProperty(window, 'hermesDesktop')+ })++ it('picks through the server folder browser instead of the native dialog', async () => {+ document.documentElement.dataset.hermesDesktopHost = 'browser'++ const settings = {+ getDefaultProjectDir: vi.fn().mockResolvedValue({ defaultLabel: 'Server workspace', dir: null, resolvedCwd: '' }),+ pickDefaultProjectDir: vi.fn().mockResolvedValue({ canceled: true, dir: null }),+ setDefaultProjectDir: vi.fn(async (dir: null | string) => ({ dir }))+ }++ Object.assign(window, { hermesDesktop: { settings } })+ selectDesktopPaths.mockReset().mockResolvedValue(['/srv/work'])++ render(<SessionsSettings subpage="default-directory" />)+ const button = await screen.findByRole('button', { name: en.common.choose })++ await act(async () => fireEvent.click(button))++ await waitFor(() => expect(settings.setDefaultProjectDir).toHaveBeenCalledWith('/srv/work'))+ expect(selectDesktopPaths).toHaveBeenCalledWith(expect.objectContaining({ directories: true }))+ expect(settings.pickDefaultProjectDir).not.toHaveBeenCalled()+ })+})diff --git a/apps/desktop/src/app/settings/sessions-settings.tsx b/apps/desktop/src/app/settings/sessions-settings.tsxindex 9a3a417ca71..359c8353b27 100644--- a/apps/desktop/src/app/settings/sessions-settings.tsx+++ b/apps/desktop/src/app/settings/sessions-settings.tsx@@ -14,10 +14,12 @@ import {} from '@/hermes'import { useI18n } from '@/i18n'import { sessionTitle } from '@/lib/chat-runtime'+import { selectDesktopPaths } from '@/lib/desktop-fs'import { pathLeaf } from '@/lib/display-path'import { triggerHaptic } from '@/lib/haptics'import { Archive, ArchiveOff, FolderOpen, Loader2, Trash2 } from '@/lib/icons'import { purgeInFlightTurnJournals } from '@/lib/inflight-turn-journal'+import { isBrowserHostedDesktop } from '@/lib/platform'import { confirm } from '@/store/confirm'import { notify, notifyError } from '@/store/notifications'import { applyConfiguredDefaultProjectDir, ensureDefaultWorkspaceCwd } from '@/store/session'@@ -370,9 +372,13 @@ function DefaultProjectDirSetting() {setBusy(true)try {- const picked = await settings.pickDefaultProjectDir()+ // A browser tab has no native dialog for the server's disk: pick through the server+ // folder browser Projects already use.+ const picked = isBrowserHostedDesktop()+ ? { dir: (await selectDesktopPaths({ defaultPath: dir ?? undefined, directories: true }))[0] ?? null }+ : await settings.pickDefaultProjectDir()- if (picked.canceled || !picked.dir) {+ if (!picked.dir) {return}@@ -385,7 +391,7 @@ function DefaultProjectDirSetting() {} finally {setBusy(false)}- }, [s])+ }, [dir, s])const clear = useCallback(async () => {const settings = window.hermesDesktop?.settingsdiff --git a/apps/desktop/src/app/settings/settings-manifest.ts b/apps/desktop/src/app/settings/settings-manifest.tsindex 9a0ad4909fa..a6bd6ef8496 100644--- a/apps/desktop/src/app/settings/settings-manifest.ts+++ b/apps/desktop/src/app/settings/settings-manifest.ts@@ -4,6 +4,7 @@ import { canUseQuickEntry } from '@/store/quick-entry'import { TRANSLUCENCY_SUPPORTED } from '@/store/translucency'import type { AppearanceSubpageId } from './appearance-subpages'+import { nativeHostOnly } from './other-subpages'import type { SettingsView } from './types'interface SettingCopy {@@ -234,11 +235,13 @@ export const SETTINGS_MANIFEST = {},gateway: {connectionMode: {+ available: nativeHostOnly,subpage: 'connection',keywords: ['gateway', 'connection', 'local', 'cloud', 'remote', 'ssh', 'url', 'token', 'host', 'port', 'key'],copy: t => ({ label: t.settings.gateway.modeTitle, description: t.settings.gateway.intro })},keychainEncryption: {+ available: nativeHostOnly,subpage: 'connection',keywords: ['keychain', 'encrypt', 'secrets', 'secure storage', 'plain text'],copy: t => ({@@ -247,6 +250,7 @@ export const SETTINGS_MANIFEST = {})},diagnostics: {+ available: nativeHostOnly,subpage: 'connection',keywords: ['diagnostics', 'logs', 'debug', 'report', 'troubleshoot'],copy: t => ({ label: t.settings.gateway.diagnostics, description: t.settings.gateway.diagnosticsDesc })diff --git a/apps/desktop/src/app/settings/subpages.test.ts b/apps/desktop/src/app/settings/subpages.test.tsindex 7efbf898910..3d7346d5c43 100644--- a/apps/desktop/src/app/settings/subpages.test.ts+++ b/apps/desktop/src/app/settings/subpages.test.ts@@ -44,6 +44,24 @@ describe('settings subpage routing', () => {}})+ // The Webapp's Gateways page is one view of its serving host: no native-only+ // child page to land on and no search hit that would scroll to nothing.+ it('gives the Webapp Gateways page no native-only children or search rows', () => {+ const nativeChildren = settingsSubpages('gateway').length+ window.document.documentElement.dataset.hermesDesktopHost = 'browser'++ try {+ expect(settingsSubpages('gateway')).toEqual([])+ expect(resolveSettingsSubpage('gateway', new URLSearchParams({ page: 'devices' }))).toBeUndefined()+ expect(settingSearchTargets(TRANSLATIONS.en).filter(target => target.view === 'gateway')).toEqual([])+ } finally {+ window.document.documentElement.removeAttribute('data-hermes-desktop-host')+ }++ expect(settingsSubpages('gateway')).toHaveLength(nativeChildren)+ expect(nativeChildren).toBeGreaterThan(0)+ })+it('gives every settings group its own nav label in every locale', () => {for (const locale of Object.values(TRANSLATIONS)) {const nav: Record<string, string> = locale.settings.navdiff --git a/apps/desktop/src/app/settings/subpages.ts b/apps/desktop/src/app/settings/subpages.tsindex 7528c61ae65..2d09022b2e1 100644--- a/apps/desktop/src/app/settings/subpages.ts+++ b/apps/desktop/src/app/settings/subpages.ts@@ -39,6 +39,8 @@ import type { SettingsView } from './types'export interface SettingsSubpage {id: stringlabelKey: string+ /** Hidden when this returns false (e.g. a native-only task in the Webapp). */+ available?: () => boolean}const SUBPAGE_ICONS: Record<string, IconComponent> = {@@ -102,7 +104,7 @@ export function settingsSubpages(view: SettingsView): readonly SettingsSubpage[]return CONFIG_SUBPAGES[view.slice('config:'.length)] ?? []}- return OTHER_SUBPAGES[view] ?? []+ return (OTHER_SUBPAGES[view] ?? []).filter(page => page.available?.() ?? true)}/** Shared by search serialization and saved links that predate subpages. */diff --git a/apps/desktop/src/app/settings/webapp-gateway-settings.tsx b/apps/desktop/src/app/settings/webapp-gateway-settings.tsxnew file mode 100644index 00000000000..0f605641dde--- /dev/null+++ b/apps/desktop/src/app/settings/webapp-gateway-settings.tsx@@ -0,0 +1,84 @@+import { useEffect, useState } from 'react'++import { Button } from '@/components/ui/button'+import { useI18n } from '@/i18n'+import { Check, Loader2 } from '@/lib/icons'+import { notifyError } from '@/store/notifications'++import { ListRow, Pill, SettingsContent } from './primitives'++interface ServingHost {+ signedIn: boolean+ url: string+}++/**+ * Gateways in the Webapp. The page is served by one Hermes host and can only+ * talk to it, so the native connection controls (mode, Cloud, saved+ * connections, logs) have nothing to act on. What does apply is which host+ * this is and, behind the sign-in gate, signing out of it.+ */+export function WebappGatewaySettings({ embedded }: { embedded: boolean }) {+ const { t } = useI18n()+ const g = t.settings.gateway+ const [host, setHost] = useState<null | ServingHost>(null)+ const [signingOut, setSigningOut] = useState(false)++ useEffect(() => {+ let cancelled = false++ void window.hermesDesktop+ .getConnectionConfig(null)+ .then(config => {+ if (!cancelled) {+ setHost({+ signedIn: config.remoteAuthMode === 'oauth' && config.remoteOauthConnected,+ url: config.remoteUrl+ })+ }+ })+ .catch(err => notifyError(err, g.failedLoad))++ return () => void (cancelled = true)+ }, [g.failedLoad])++ // Success leaves the page for the login screen, so only a failure re-arms.+ const signOut = async (url: string) => {+ setSigningOut(true)++ try {+ await window.hermesDesktop.oauthLogoutConnectionConfig(url)+ } catch (err) {+ notifyError(err, g.signOutFailed)+ setSigningOut(false)+ }+ }++ return (+ <SettingsContent bare={embedded}>+ {host ? (+ <ListRow+ action={+ host.signedIn ? (+ <div className="flex items-center gap-2">+ <Pill tone="primary">+ <Check className="size-3" />+ {g.signedIn}+ </Pill>+ <Button disabled={signingOut} onClick={() => void signOut(host.url)} variant="outline">+ {signingOut ? <Loader2 className="animate-spin" /> : null}+ {g.signOut}+ </Button>+ </div>+ ) : null+ }+ description={host.url}+ title={g.webappHostTitle}+ />+ ) : null}+ <p className="mt-2 max-w-2xl text-[length:var(--conversation-caption-font-size)] leading-(--conversation-caption-line-height) text-(--ui-text-tertiary)">+ {g.webappHostDesc}+ </p>+ </SettingsContent>+ )+}diff --git a/apps/desktop/src/app/shell/titlebar-controls.test.tsx b/apps/desktop/src/app/shell/titlebar-controls.test.tsxindex 9a2fb6a42da..bf33b99b8a4 100644--- a/apps/desktop/src/app/shell/titlebar-controls.test.tsx+++ b/apps/desktop/src/app/shell/titlebar-controls.test.tsx@@ -1,11 +1,16 @@// @vitest-environment jsdom-import { act, cleanup, render, screen, within } from '@testing-library/react'+import { act, cleanup, fireEvent, render, screen, within } from '@testing-library/react'import { useEffect } from 'react'import { MemoryRouter, useNavigate } from 'react-router'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { PANE_TOGGLE_REVEAL_EVENT } from '@/components/pane-shell'+import { $narrowOverlayPaneIds } from '@/components/pane-shell/narrow-overlay-state'+import { $narrowViewport } from '@/components/pane-shell/tree/store'import { registry } from '@/contrib/registry'import { I18nProvider } from '@/i18n'+import { CHAT_SIDEBAR_PANE_ID } from '@/store/layout'+import { REVIEW_PANE_ID } from '@/store/review'import { setTitlebarAppActionsSide } from '@/store/titlebar-app-actions'import { ROUTES_AREA } from '../routes'@@ -188,9 +193,63 @@ describe('TitlebarControls fixed clusters', () => {})describe('titlebar app-action cluster', () => {+ beforeEach(() => {+ vi.stubGlobal('hermesDesktop', { ...window.hermesDesktop, hud: { open: vi.fn() } })+ })+afterEach(() => {+ $narrowViewport.set(false)+ $narrowOverlayPaneIds.set(new Set())setTitlebarAppActionsSide('right')cleanup()+ vi.unstubAllGlobals()+ })++ it('names the narrow sidebar action from its visible overlay, not docked state', () => {+ $narrowViewport.set(true)+ renderControls('/')+ const left = screen.getByLabelText('Window controls')+ expect(within(left).getByRole('button', { name: 'Show sidebar' }).getAttribute('aria-expanded')).toBe('false')+ act(() => $narrowOverlayPaneIds.set(new Set([CHAT_SIDEBAR_PANE_ID])))+ expect(within(left).getByRole('button', { name: 'Hide sidebar' }).getAttribute('aria-expanded')).toBe('true')+ act(() => $narrowOverlayPaneIds.set(new Set()))+ expect(within(left).getByRole('button', { name: 'Show sidebar' })).toBeTruthy()+ })++ it('explicitly closes a visible overlay rather than pinning a hover reveal', () => {+ vi.stubGlobal(+ 'matchMedia',+ vi.fn().mockReturnValue({ matches: true, addEventListener: vi.fn(), removeEventListener: vi.fn() })+ )+ $narrowViewport.set(true)+ $narrowOverlayPaneIds.set(new Set([CHAT_SIDEBAR_PANE_ID]))+ const intents: unknown[] = []+ const listener = (event: Event) => intents.push((event as CustomEvent).detail)+ window.addEventListener(PANE_TOGGLE_REVEAL_EVENT, listener)++ try {+ renderControls('/')+ fireEvent.click(screen.getByRole('button', { name: 'Hide sidebar' }))+ expect(intents).toEqual([{ id: CHAT_SIDEBAR_PANE_ID, mode: 'close' }])+ } finally {+ window.removeEventListener(PANE_TOGGLE_REVEAL_EVENT, listener)+ }+ })++ it('hides a review-only right sidebar instead of opening files', () => {+ $narrowViewport.set(true)+ $narrowOverlayPaneIds.set(new Set([REVIEW_PANE_ID]))+ const intents: unknown[] = []+ const listener = (event: Event) => intents.push((event as CustomEvent).detail)+ window.addEventListener(PANE_TOGGLE_REVEAL_EVENT, listener)++ try {+ renderControls('/')+ fireEvent.click(screen.getByRole('button', { name: 'Hide right sidebar' }))+ expect(intents).toEqual([{ id: 'review', mode: 'close' }])+ } finally {+ window.removeEventListener(PANE_TOGGLE_REVEAL_EVENT, listener)+ }})it('moves settings, layout, and HUD to the left when the appearance setting says left', () => {@@ -205,4 +264,18 @@ describe('titlebar app-action cluster', () => {expect(within(left).getByLabelText('HUD mode')).toBeTruthy()expect(within(right).queryByLabelText('Open settings')).toBeNull()})++ it('keeps HUD hidden in the browser on either app-action side', () => {+ vi.stubGlobal('hermesDesktop', { ...window.hermesDesktop, hud: undefined })+ renderControls('/')++ expect(screen.queryByLabelText('HUD mode')).toBeNull()+ expect(screen.getByLabelText('Open settings')).toBeTruthy()++ // Each side assembles its own cluster, so the move must keep the filter.+ act(() => setTitlebarAppActionsSide('left'))+ expect(screen.queryByLabelText('HUD mode')).toBeNull()+ expect(within(screen.getByLabelText('Window controls')).getByLabelText('Open settings')).toBeTruthy()+ expect(screen.getByLabelText('Layout editor')).toBeTruthy()+ })})diff --git a/apps/desktop/src/app/shell/titlebar-controls.tsx b/apps/desktop/src/app/shell/titlebar-controls.tsxindex a5d90022576..c4863fd3eb5 100644--- a/apps/desktop/src/app/shell/titlebar-controls.tsx+++ b/apps/desktop/src/app/shell/titlebar-controls.tsx@@ -4,7 +4,10 @@ import { type ComponentProps, type MouseEvent, type ReactNode, useEffect, useStaimport { useLocation, useNavigate } from 'react-router'import { hudTargetSessionId } from '@/app/hud/handoff'+import { PANE_TOGGLE_REVEAL_EVENT } from '@/components/pane-shell'import { toggleLayoutEditMode } from '@/components/pane-shell/edit-mode'+import { $narrowOverlayPaneIds } from '@/components/pane-shell/narrow-overlay-state'+import { $narrowViewport } from '@/components/pane-shell/tree/store'import { resetLayoutTree } from '@/components/pane-shell/tree/store'import { Badge } from '@/components/ui/badge'import { Button } from '@/components/ui/button'@@ -16,16 +19,19 @@ import { triggerHaptic } from '@/lib/haptics'import { formatModifierToken } from '@/lib/keybinds/combo'import { cn } from '@/lib/utils'import { recordAction } from '@/store/desktop-metrics'-import { toggleHud } from '@/store/hud'+import { canUseHud, toggleHud } from '@/store/hud'import { $interfaceMode, shownInMode, type Tiered } from '@/store/interface-mode'import {$fileBrowserOpen,$leftSideOpen,$panesFlipped,+ CHAT_SIDEBAR_PANE_ID,+ FILE_BROWSER_PANE_ID,toggleLeftSide,togglePanesFlipped,toggleRightSide} from '@/store/layout'+import { REVIEW_PANE_ID } from '@/store/review'import { $unreadSessionCount } from '@/store/session-dot-state'import { $titlebarAppActionsSide, TITLEBAR_FIXED_TOOLS } from '@/store/titlebar-app-actions'@@ -44,6 +50,7 @@ export interface TitlebarTool extends Tiered {id: stringlabel: stringactive?: boolean+ expanded?: booleanclassName?: stringdisabled?: booleanhidden?: boolean@@ -141,6 +148,8 @@ export function TitlebarControls({ leftTools = [], tools = [], onOpenSettings }:const modHeld = useModifierHeld()const fileBrowserOpen = useStore($fileBrowserOpen)const leftSideOpen = useStore($leftSideOpen)+ const narrow = useStore($narrowViewport)+ const overlayPanes = useStore($narrowOverlayPaneIds)const panesFlipped = useStore($panesFlipped)const unreadCount = useStore($unreadSessionCount)const appActionsSide = useStore($titlebarAppActionsSide)@@ -164,21 +173,34 @@ export function TitlebarControls({ leftTools = [], tools = [], onOpenSettings }:// from the live tree (see toggleLeftSide / toggleRightSide) — the browser// column, the sessions column, whatever is physically left / right. Never an// active highlight — plain show/hide affordances.- const leftEdge = { open: leftSideOpen, toggle: toggleLeftSide }- const rightEdge = { open: fileBrowserOpen, toggle: toggleRightSide }+ const leftEdge = { open: narrow ? overlayPanes.has(CHAT_SIDEBAR_PANE_ID) : leftSideOpen, toggle: toggleLeftSide }+ const rightOverlayId = overlayPanes.has(REVIEW_PANE_ID) ? REVIEW_PANE_ID : FILE_BROWSER_PANE_ID+ const rightEdge = { open: narrow ? overlayPanes.has(rightOverlayId) : fileBrowserOpen, toggle: toggleRightSide }const leftLabel = leftEdge.open ? t.titlebar.hideSidebar : t.titlebar.showSidebarconst rightLabel = rightEdge.open ? t.titlebar.hideRightSidebar : t.titlebar.showRightSidebar+ // A visible hover reveal is not pinned: generic toggle would pin it rather+ // than perform the labelled Hide action. Titlebar verbs are explicit;+ // keyboard toggles retain their hover-to-pin behavior.+ const toggleEdge = (id: string, open: boolean, toggleDocked: () => void) => {+ if (narrow) {+ window.dispatchEvent(new CustomEvent(PANE_TOGGLE_REVEAL_EVENT, { detail: { id, mode: open ? 'close' : 'open' } }))+ } else {+ toggleDocked()+ }+ }+const sidebarTool: TitlebarTool = {...TITLEBAR_FIXED_TOOLS.sidebar,actionId: 'view.toggleSidebar',badge: panesFlipped ? undefined : unreadBadge,icon: <TitlebarIcon name="layout-sidebar-left" />,id: 'sidebar',+ expanded: leftEdge.open,label: `${leftLabel}${panesFlipped ? '' : unreadHint}`,onSelect: () => {triggerHaptic('tap')- leftEdge.toggle()+ toggleEdge(CHAT_SIDEBAR_PANE_ID, leftEdge.open, leftEdge.toggle)}}@@ -200,10 +222,11 @@ export function TitlebarControls({ leftTools = [], tools = [], onOpenSettings }:badge: panesFlipped ? unreadBadge : undefined,icon: <TitlebarIcon name="layout-sidebar-right" />,id: 'right-sidebar',+ expanded: rightEdge.open,label: `${rightLabel}${panesFlipped ? unreadHint : ''}`,onSelect: () => {triggerHaptic('tap')- rightEdge.toggle()+ toggleEdge(rightOverlayId, rightEdge.open, rightEdge.toggle)},tour: 'right-pane-toggle'}@@ -250,6 +273,7 @@ export function TitlebarControls({ leftTools = [], tools = [], onOpenSettings }:// crowds the ⌘⇧H hint off the tooltip. Label only — the hint is appended// from the action registry, same as every other tool here.actionId: 'view.toggleHud',+ hidden: !canUseHud(),icon: <TitlebarIcon name="comment-discussion" />,id: 'hud',label: t.titlebar.enterHud,@@ -390,6 +414,7 @@ function TitlebarToolButton({ navigate, tool }: { navigate: ReturnType<typeof usreturn (<Tip label={tooltipLabel} placement="toolbar"><Button+ aria-expanded={tool.expanded}aria-label={tool.label}aria-pressed={tool.active ?? undefined}className={className}diff --git a/apps/desktop/src/app/shell/titlebar.ts b/apps/desktop/src/app/shell/titlebar.tsindex 83201088c6d..d7aef100394 100644--- a/apps/desktop/src/app/shell/titlebar.ts+++ b/apps/desktop/src/app/shell/titlebar.ts@@ -1,6 +1,9 @@import type { HermesConnection } from '@/global'export const TITLEBAR_HEIGHT = 34+/** Browser touch chrome: the band (and the controls flush in it) are 44px+ * touch targets, not Electron's compact band. */+export const TOUCH_TITLEBAR_HEIGHT = 44/** Permanent native drag target beside a top-edge tab strip. */export const TITLEBAR_DRAG_HANDLE_WIDTH = 48export const MACOS_TRAFFIC_LIGHTS_HEIGHT = 14diff --git a/apps/desktop/src/app/shell/use-touch-titlebar.ts b/apps/desktop/src/app/shell/use-touch-titlebar.tsnew file mode 100644index 00000000000..853d9b84ce2--- /dev/null+++ b/apps/desktop/src/app/shell/use-touch-titlebar.ts@@ -0,0 +1,15 @@+import { TITLEBAR_HEIGHT, TOUCH_TITLEBAR_HEIGHT } from '@/app/shell/titlebar'+import { useMediaQuery } from '@/hooks/use-media-query'+import { isBrowserHostedDesktop } from '@/lib/platform'+import { TOUCH_POINTER_QUERY } from '@/lib/touch-interaction'++/** Browser touch chrome needs a 44px band, not Electron's compact 34px band. */+export function useTouchTitlebar(): boolean {+ const touch = useMediaQuery(TOUCH_POINTER_QUERY)++ return isBrowserHostedDesktop() && touch+}++export function useTitlebarHeight(): number {+ return useTouchTitlebar() ? TOUCH_TITLEBAR_HEIGHT : TITLEBAR_HEIGHT+}diff --git a/apps/desktop/src/app/updates-overlay.tsx b/apps/desktop/src/app/updates-overlay.tsxindex dad9802d609..65501aa4a8b 100644--- a/apps/desktop/src/app/updates-overlay.tsx+++ b/apps/desktop/src/app/updates-overlay.tsx@@ -7,7 +7,7 @@ import { settingsSearchTargetQuery } from '@/app/settings/settings-search'import { BrandMark } from '@/components/brand-mark'import { SyncStatusCard } from '@/components/sync-status-card'import { Button } from '@/components/ui/button'-import { CopyButton, writeClipboardText } from '@/components/ui/copy-button'+import { CopyButton } from '@/components/ui/copy-button'import {Dialog,DialogContent,@@ -28,6 +28,7 @@ import type {UpdaterMechanismClient} from '@/global'import { useI18n } from '@/i18n'+import { writeClipboardText } from '@/lib/clipboard'import { buildCommitChangelog, type CommitGroup, formatFullChangelogText } from '@/lib/commit-changelog'import { AlertCircle, Check, Copy, ExternalLink, Terminal } from '@/lib/icons'import { resolveUpdateCopy, rollbackRelease, type UpdateTarget } from '@/lib/update-copy'diff --git a/apps/desktop/src/components/assistant-ui/markdown-text.media.test.tsx b/apps/desktop/src/components/assistant-ui/markdown-text.media.test.tsxindex 946e240678d..bdc6ed13b06 100644--- a/apps/desktop/src/components/assistant-ui/markdown-text.media.test.tsx+++ b/apps/desktop/src/components/assistant-ui/markdown-text.media.test.tsx@@ -1,4 +1,4 @@-import { cleanup, render, screen, waitFor } from '@testing-library/react'+import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { $connection } from '@/store/session'@@ -80,6 +80,55 @@ describe('MarkdownImage media routing', () => {})})+// Webapp audio/video play from stream-ticket URLs that expire. An element+// that already loaded needs a fresh ticket for its next range request (a seek,+// or play after a long pause) instead of degrading to "Open file" for good.+describe('MarkdownImage stream-ticket renewal', () => {+ const mint = vi.fn()+ let originalDesktop: typeof window.hermesDesktop++ const audioSrc = (container: HTMLElement) => container.querySelector('audio')?.getAttribute('src')++ beforeEach(() => {+ let minted = 0++ mint.mockReset().mockImplementation(async () => `https://hermes.test/api/files/stream?ticket=t${++minted}`)+ originalDesktop = window.hermesDesktop+ Object.defineProperty(window, 'hermesDesktop', { configurable: true, value: { getGatewayFileStreamUrl: mint } })+ })++ afterEach(() => {+ cleanup()+ Object.defineProperty(window, 'hermesDesktop', { configurable: true, value: originalDesktop })+ })++ it('re-mints the source after a loaded element errors and resumes where it stopped', async () => {+ const { container } = render(<MarkdownImage alt="note" src="/srv/media/note.mp3" />)++ await waitFor(() => expect(audioSrc(container)).toBe('https://hermes.test/api/files/stream?ticket=t1'))+ const audio = container.querySelector('audio')!+ fireEvent.loadedMetadata(audio)+ audio.currentTime = 42+ fireEvent.error(audio)++ await waitFor(() => expect(audioSrc(container)).toBe('https://hermes.test/api/files/stream?ticket=t2'))+ audio.currentTime = 0+ fireEvent.loadedMetadata(audio)+ expect(audio.currentTime).toBe(42)+ expect(screen.queryByText('Open audio file')).toBeNull()+ })++ it('offers the file instead when a source fails before it ever loads', async () => {+ const { container } = render(<MarkdownImage alt="note" src="/srv/media/note.mp3" />)++ await waitFor(() => expect(audioSrc(container)).toBe('https://hermes.test/api/files/stream?ticket=t1'))+ fireEvent.error(container.querySelector('audio')!)++ expect(await screen.findByText('Open audio file')).toBeTruthy()+ expect(mint).toHaveBeenCalledTimes(1)+ })+})+describe('MessageTextContent MEDIA directives', () => {afterEach(cleanup)diff --git a/apps/desktop/src/components/assistant-ui/markdown-text.tsx b/apps/desktop/src/components/assistant-ui/markdown-text.tsxindex 307f29ab4e6..956e5d58445 100644--- a/apps/desktop/src/components/assistant-ui/markdown-text.tsx+++ b/apps/desktop/src/components/assistant-ui/markdown-text.tsx@@ -28,6 +28,7 @@ import { ZoomableImage } from '@/components/chat/zoomable-image'import { ErrorBoundary } from '@/components/error-boundary'import { useContributions } from '@/contrib'import { useMediaImage } from '@/hooks/use-media-image'+import { useMediaPlaybackSrc } from '@/hooks/use-media-playback-src'import { detectArtifact } from '@/lib/artifact-detect'import { renderMediaTags } from '@/lib/chat-messages/parts'import { normalizeExternalUrl, openExternalLink, PrettyLink } from '@/lib/external-link'@@ -43,7 +44,6 @@ import {mediaKind,mediaName,mediaPathFromMarkdownHref,- resolveMediaPlaybackSrc,validImageDimensions} from '@/lib/media'import { previewTargetFromMarkdownHref } from '@/lib/preview-targets'@@ -172,59 +172,22 @@ function MediaAttachment({ path }: { path: string }) {}function MediaPlaybackAttachment({ path }: { path: string }) {- const [src, setSrc] = useState('')- const [failed, setFailed] = useState(false)+ const { failed, kind, onError, onLoadedMetadata, src } = useMediaPlaybackSrc(path)const { open, openFailed } = useOpenMediaFile(path)- const kind = mediaKind(path)const name = mediaName(path)- useEffect(() => {- let cancelled = false- let objectUrl = ''-- setFailed(false)- setSrc('')-- if (kind === 'file') {- setFailed(true)-- return () => {- cancelled = true- }- }-- void resolveMediaPlaybackSrc(path)- .then(value => {- if (value.startsWith('blob:')) {- objectUrl = value- }-- if (!cancelled) {- setSrc(value)- } else if (objectUrl) {- URL.revokeObjectURL(objectUrl)- }- })- .catch(() => {- if (!cancelled) {- setFailed(true)- }- })-- return () => {- cancelled = true-- if (objectUrl) {- URL.revokeObjectURL(objectUrl)- }- }- }, [kind, path])-if (kind === 'audio' && src) {return (<span className="my-3 block max-w-md rounded-xl border border-(--ui-stroke-tertiary) bg-muted/35 p-3"><span className="mb-2 block truncate text-xs font-medium text-muted-foreground">{name}</span>- <audio className="block w-full" controls onError={() => setFailed(true)} preload="metadata" src={src} />+ <audio+ className="block w-full"+ controls+ onError={onError}+ onLoadedMetadata={onLoadedMetadata}+ preload="metadata"+ src={src}+ />{failed && <OpenMediaButton kind="audio" path={path} />}</span>)@@ -237,7 +200,8 @@ function MediaPlaybackAttachment({ path }: { path: string }) {<TranscriptVideoclassName="block max-h-112 w-full rounded-lg bg-black"controls- onError={() => setFailed(true)}+ onError={onError}+ onLoadedMetadata={onLoadedMetadata}src={src}/>{failed && <OpenMediaButton kind="video" path={path} />}diff --git a/apps/desktop/src/components/assistant-ui/thread/assistant-message.test.tsx b/apps/desktop/src/components/assistant-ui/thread/assistant-message.test.tsxindex c2cfe5ccde2..92fc47c38a5 100644--- a/apps/desktop/src/components/assistant-ui/thread/assistant-message.test.tsx+++ b/apps/desktop/src/components/assistant-ui/thread/assistant-message.test.tsx@@ -11,6 +11,7 @@ import { afterEach, describe, expect, it, vi } from 'vitest'import { en } from '@/i18n/en'import type { ErrorCardCopy } from '@/i18n/types'+import { $touchPointer } from '@/lib/touch-interaction'import { $displayTimestamps } from '@/store/display-timestamps'import { $activeSessionId } from '@/store/session'import { type SessionTileDelegate, setSessionTileDelegate } from '@/store/session-states'@@ -56,6 +57,9 @@ afterEach(() => {requestFreshSession.mockClear()startManualProviderOAuth.mockClear()requestModelMenuToggle.mockReset().mockReturnValue(true)+ $displayTimestamps.set(true)+ $touchPointer.set(false)+ vi.unstubAllGlobals()})function userMessage(): ThreadMessage {@@ -178,27 +182,113 @@ function LocationProbe() {function Harness({assistant = assistantMessage(),onBranchInNewChat,- onReload+ onCancel,+ onRestoreToMessage,+ onReload,+ isRunning = false,+ isDisabled = false}: {assistant?: ThreadMessageonBranchInNewChat?: (messageId: string) => void+ onCancel?: () => void+ onRestoreToMessage?: (messageId: string) => voidonReload?: () => Promise<void>+ isRunning?: boolean+ isDisabled?: boolean}) {const runtime = useExternalStoreRuntime<ThreadMessage>({messages: [userMessage(), assistant],- isRunning: false,+ isRunning,+ isDisabled,onNew: async () => {},...(onReload ? { onReload } : {})})return (<AssistantRuntimeProvider runtime={runtime}>- <Thread onBranchInNewChat={onBranchInNewChat} />+ <Thread onBranchInNewChat={onBranchInNewChat} onCancel={onCancel} onRestoreToMessage={onRestoreToMessage} /></AssistantRuntimeProvider>)}+describe('merged hover timestamps and touch actions', () => {+ it('shows both hover times without Stop or Restore and suppresses them with timeline timestamps', async () => {+ $displayTimestamps.set(false)+ const { container } = render(<Harness />)+ await screen.findByText('done')++ const hoverTimes = Array.from(container.querySelectorAll('time'))++ expect(hoverTimes.map(time => time.dateTime)).toEqual([+ createdAt.toISOString(),+ new Date(completedAt * 1000).toISOString()+ ])+ expect(container.querySelector('.aui-message-actions-desktop time')).toBeTruthy()++ act(() => $displayTimestamps.set(true))+ expect(hoverTimes.every(time => !time.isConnected)).toBe(true)+ expect(container.querySelector('[data-slot="timeline-timestamp"]')).toBeTruthy()+ })++ it('mounts the touch More menu only while the pointer is coarse', async () => {+ render(<Harness />)+ await screen.findByText('done')+ expect(screen.queryByRole('button', { name: 'More actions' })).toBeNull()++ act(() => $touchPointer.set(true))+ expect(screen.getByRole('button', { name: 'More actions' })).toBeTruthy()+ })++ it.each([true, false])('keeps the touch Stop/Restore action correct while running=%s', async isRunning => {+ $touchPointer.set(true)+ $displayTimestamps.set(false)+ const onCancel = vi.fn()+ const onRestoreToMessage = vi.fn()+ render(<Harness isRunning={isRunning} onCancel={onCancel} onRestoreToMessage={onRestoreToMessage} />)++ const action = await screen.findByRole('button', {+ name: isRunning ? en.assistant.thread.stop : en.assistant.thread.restoreCheckpoint+ })++ expect(action.parentElement?.querySelector('time')).toBeNull()+ fireEvent.click(action)++ if (isRunning) {+ expect(onCancel).toHaveBeenCalledTimes(1)+ expect(onRestoreToMessage).not.toHaveBeenCalled()+ } else {+ expect(await screen.findByRole('dialog')).toBeTruthy()+ fireEvent.click(screen.getByRole('button', { name: en.assistant.thread.restoreConfirm }))+ expect(onRestoreToMessage).toHaveBeenCalledWith('user-1', expect.objectContaining({ text: 'question one' }))+ expect(onCancel).not.toHaveBeenCalled()+ }+ })+})+describe('AssistantMessage branch button visibility (bug #2 fix)', () => {+ it('reloads once from either desktop or touch Refresh', async () => {+ $touchPointer.set(true)+ const onReload = vi.fn(async () => {})+ render(<Harness onReload={onReload} />)+ fireEvent.click(await screen.findByRole('button', { name: 'Refresh' }))+ await waitFor(() => expect(onReload).toHaveBeenCalledTimes(1))+ onReload.mockClear()+ fireEvent.pointerDown(screen.getByRole('button', { name: 'More actions' }), { button: 0, pointerType: 'touch' })+ fireEvent.click(await screen.findByRole('menuitem', { name: 'Refresh' }))+ await waitFor(() => expect(onReload).toHaveBeenCalledTimes(1))+ })++ it.each([{ isRunning: true }, { isDisabled: true }])('guards both Refresh surfaces with %j', async state => {+ $touchPointer.set(true)+ const onReload = vi.fn(async () => {})+ render(<Harness onReload={onReload} {...state} />)+ expect((await screen.findByRole('button', { name: 'Refresh' })).hasAttribute('disabled')).toBe(true)+ fireEvent.pointerDown(screen.getByRole('button', { name: 'More actions' }), { button: 0, pointerType: 'touch' })+ const refresh = await screen.findByRole('menuitem', { name: 'Refresh' })+ expect(refresh.getAttribute('aria-disabled')).toBe('true')+ fireEvent.click(refresh)+ expect(onReload).not.toHaveBeenCalled()+ })it('shows the Branch in new chat button when a handler is provided (open chat)', async () => {render(<Harness onBranchInNewChat={() => undefined} />)@@ -215,6 +305,20 @@ describe('AssistantMessage branch button visibility (bug #2 fix)', () => {expect(screen.queryByRole('button', { name: 'Branch in new chat' })).toBeNull()})++ it('reaches Branch in new chat from the touch More menu', async () => {+ $touchPointer.set(true)+ render(<Harness onBranchInNewChat={() => undefined} />)++ await screen.findByText('done')++ fireEvent.pointerDown(screen.getByRole('button', { name: 'More actions' }), {+ button: 0,+ pointerType: 'touch'+ })++ expect(await screen.findByRole('menuitem', { name: 'Branch in new chat' })).toBeTruthy()+ })})describe('stopped reply marker', () => {diff --git a/apps/desktop/src/components/assistant-ui/thread/assistant-message.tsx b/apps/desktop/src/components/assistant-ui/thread/assistant-message.tsxindex f5904a1722d..ca7a313bb25 100644--- a/apps/desktop/src/components/assistant-ui/thread/assistant-message.tsx+++ b/apps/desktop/src/components/assistant-ui/thread/assistant-message.tsx@@ -1,3 +1,4 @@+import { useActionBarReload } from '@assistant-ui/core/react'import {ActionBarPrimitive,BranchPickerPrimitive,@@ -37,6 +38,8 @@ import { isApprovalActivity, isCurrentTurnMessage } from '@/components/assistantimport { TooltipIconButton } from '@/components/assistant-ui/tooltip-icon-button'import { formatElapsed } from '@/components/chat/activity-timer'import { PreviewAttachment } from '@/components/chat/preview-attachment'+import { ActionsMenu, renderActionItem } from '@/components/ui/actions-menu'+import { Button } from '@/components/ui/button'import { Codicon } from '@/components/ui/codicon'import { CopyButton } from '@/components/ui/copy-button'import { useI18n } from '@/i18n'@@ -58,6 +61,7 @@ import {GitForkIcon,KeyRound,Loader2Icon,+ MoreHorizontal,RefreshCwIcon,SmilePlusIcon,Upload,@@ -66,6 +70,7 @@ import {} from '@/lib/icons'import { extractPreviewTargets } from '@/lib/preview-targets'import { markAssistantIdSpoken } from '@/lib/spoken-reply'+import { $touchPointer } from '@/lib/touch-interaction'import { useEnterAnimation } from '@/lib/use-enter-animation'import { cn } from '@/lib/utils'import { playSpeechText, stopVoicePlayback } from '@/lib/voice-playback'@@ -1141,6 +1146,85 @@ const ErrorRecoveryActions: FC = () => {)}+interface ReadAloudActionState {+ disabled: boolean+ isPreparing: boolean+ isSpeaking: boolean+ menuLabel: string+ onActivate: (event?: { shiftKey?: boolean }) => void+ tooltip: string+}++function useReadAloudAction({+ fullResponseAvailable,+ getFullText,+ getText,+ messageId+}: {+ fullResponseAvailable: boolean+ getFullText: () => string+ getText: () => string+ messageId: string+}): ReadAloudActionState {+ const { t } = useI18n()+ const copy = t.assistant.thread+ const voicePlayback = useStore($voicePlayback)+ const view = useSessionView()+ const sessionId = useStore(view.$runtimeId)+ // A Bot chat's session owns its own (connection, profile) → its own TTS voice.+ const { connectionId, profile } = useComposerScope()++ const readAloudStatus =+ voicePlayback.source === 'read-aloud' && voicePlayback.messageId === messageId ? voicePlayback.status : 'idle'++ const isPreparing = readAloudStatus === 'preparing'+ const isSpeaking = readAloudStatus === 'speaking'+ const anyPlaybackActive = voicePlayback.status !== 'idle'++ // Default reads the current reply only; Shift-click reads the whole response+ // group — the read-aloud mirror of the two copy scopes (#118864).+ const read = useCallback(+ async (full: boolean) => {+ const text = full ? getFullText() : getText()++ if (!text || $voicePlayback.get().status !== 'idle') {+ return+ }++ try {+ await playSpeechText(text, { connectionId, messageId, profile, source: 'read-aloud' })+ markAssistantIdSpoken(sessionId, view.$messages.get(), messageId)+ } catch (error) {+ notifyError(error, copy.readAloudFailed)+ }+ },+ [connectionId, copy.readAloudFailed, getFullText, getText, messageId, profile, sessionId, view.$messages]+ )++ const onActivate = useCallback(+ (event?: { shiftKey?: boolean }) => {+ triggerHaptic('selection')+ void (isSpeaking ? stopVoicePlayback() : read(Boolean(event?.shiftKey)))+ },+ [isSpeaking, read]+ )++ return {+ disabled: isPreparing || (!isSpeaking && anyPlaybackActive),+ isPreparing,+ isSpeaking,+ menuLabel: isSpeaking ? copy.stopReading : copy.readAloud,+ onActivate,+ tooltip: isPreparing+ ? copy.preparingAudio+ : isSpeaking+ ? copy.stopReading+ : fullResponseAvailable+ ? `${copy.readAloud} (${copy.readAloudFullResponseHint})`+ : copy.readAloud+ }+}+const AssistantActionBar: FC<MessageActionProps & { durationS?: number }> = ({durationS,fullResponseAvailable,@@ -1151,10 +1235,29 @@ const AssistantActionBar: FC<MessageActionProps & { durationS?: number }> = ({}) => {const { t } = useI18n()const copy = t.assistant.thread+ const { reload: reloadMessage, disabled: reloadDisabled } = useActionBarReload()+ const touch = useStore($touchPointer)const [pickerOpen, setPickerOpen] = useState(false)const { enabled: reactionsEnabled, react, reactions: shownReactions } = useMessageReactions(messageId, 'assistant')+ const readAloud = useReadAloudAction({+ fullResponseAvailable,+ getFullText: getFullResponseText,+ getText: getMessageText,+ messageId+ })++ const reload = useCallback(() => {+ if (reloadDisabled) {+ return+ }++ triggerHaptic('submit')+ recordAction(DESKTOP_BUTTON_ACTIONS.messageRetry, 'click')+ reloadMessage()+ }, [reloadDisabled, reloadMessage])+const pickEmoji = useCallback((emoji: null | string) => {setPickerOpen(false)@@ -1163,6 +1266,23 @@ const AssistantActionBar: FC<MessageActionProps & { durationS?: number }> = ({[react])+ const branchInNewChat = onBranchInNewChat+ ? () => {+ triggerHaptic('selection')+ onBranchInNewChat(messageId)+ }+ : undefined++ const copyButton = (+ <CopyButton+ appearance="icon"+ buttonSize="icon"+ label={copy.copy}+ onCopied={() => recordAction(DESKTOP_BUTTON_ACTIONS.messageCopy, 'click')}+ text={getMessageText}+ />+ )+return (<div className="relative flex w-full shrink-0 items-center justify-end gap-1.5">{durationS !== undefined && (@@ -1187,45 +1307,68 @@ const AssistantActionBar: FC<MessageActionProps & { durationS?: number }> = ({}data-slot="aui_msg-actions">- <MessageHoverTime className="mr-1 px-0.5" />- {onBranchInNewChat && (- <TooltipIconButton- onClick={() => {- triggerHaptic('selection')- onBranchInNewChat(messageId)- }}- tooltip={copy.branchNewChat}- >- <GitForkIcon className="size-3.5" />- </TooltipIconButton>- )}- <CopyButton- appearance="icon"- buttonSize="icon"- label={copy.copy}- onCopied={() => recordAction(DESKTOP_BUTTON_ACTIONS.messageCopy, 'click')}- text={getMessageText}- />- {fullResponseAvailable && (- <CopyButton appearance="icon" buttonSize="icon" label={copy.copyFullResponse} text={getFullResponseText} />- )}- <ReadAloudButton- fullResponseAvailable={fullResponseAvailable}- getFullText={getFullResponseText}- getText={getMessageText}- messageId={messageId}- />- <ActionBarPrimitive.Reload asChild>- <TooltipIconButton- onClick={() => {- triggerHaptic('submit')- recordAction(DESKTOP_BUTTON_ACTIONS.messageRetry, 'click')- }}- tooltip={copy.refresh}- >+ <div className="aui-message-actions-desktop flex items-center justify-end gap-1.5">+ <MessageHoverTime className="mr-1 px-0.5" />+ {branchInNewChat && (+ <TooltipIconButton onClick={branchInNewChat} tooltip={copy.branchNewChat}>+ <GitForkIcon className="size-3.5" />+ </TooltipIconButton>+ )}+ {copyButton}+ {fullResponseAvailable && (+ <CopyButton appearance="icon" buttonSize="icon" label={copy.copyFullResponse} text={getFullResponseText} />+ )}+ <ReadAloudButton action={readAloud} />+ <TooltipIconButton disabled={reloadDisabled} onClick={reload} tooltip={copy.refresh}><RefreshCwIcon className="size-3.5" /></TooltipIconButton>- </ActionBarPrimitive.Reload>+ </div>+ {/* Mounted only on touch: each Radix menu root adds a document key+ listener, and the CSS already hides this cluster everywhere else. */}+ {touch && (+ <div className="aui-message-actions-touch items-center justify-end gap-1">+ {copyButton}+ <ActionsMenu+ ariaLabel={copy.moreActions}+ items={kit => (+ <>+ {branchInNewChat &&+ renderActionItem(kit, {+ icon: 'git-branch',+ key: 'branch',+ label: copy.branchNewChat,+ onSelect: branchInNewChat+ })}+ {fullResponseAvailable && (+ <CopyButton+ appearance={kit.copyAppearance}+ label={copy.copyFullResponse}+ text={getFullResponseText}+ />+ )}+ {renderActionItem(kit, {+ iconNode: <AudioLines className="size-3.5" />,+ key: 'read-aloud',+ label: readAloud.menuLabel,+ onSelect: () => readAloud.onActivate(),+ disabled: readAloud.disabled+ })}+ {renderActionItem(kit, {+ iconNode: <RefreshCwIcon className="size-3.5" />,+ key: 'refresh',+ label: copy.refresh,+ disabled: reloadDisabled,+ onSelect: reload+ })}+ </>+ )}+ >+ <Button aria-label={copy.moreActions} size="icon" type="button" variant="ghost">+ <MoreHorizontal className="size-3.5" />+ </Button>+ </ActionsMenu>+ </div>+ )}</ActionBarPrimitive.Root>{/* ONE slot, Slack-style: the picker trigger and the landed reaction arethe same element, so reacting never shifts layout. Empty → ☺, hidden@@ -1267,66 +1410,12 @@ const AssistantActionBar: FC<MessageActionProps & { durationS?: number }> = ({)}-const ReadAloudButton: FC<{- fullResponseAvailable: boolean- getFullText: () => string- getText: () => string- messageId: string-}> = ({ fullResponseAvailable, getFullText, getText, messageId }) => {- const { t } = useI18n()- const copy = t.assistant.thread- const voicePlayback = useStore($voicePlayback)- const view = useSessionView()- const sessionId = useStore(view.$runtimeId)- // A Bot chat's session owns its own (connection, profile) → its own TTS voice.- const { connectionId, profile } = useComposerScope()-- const readAloudStatus =- voicePlayback.source === 'read-aloud' && voicePlayback.messageId === messageId ? voicePlayback.status : 'idle'-- const isPreparing = readAloudStatus === 'preparing'- const isSpeaking = readAloudStatus === 'speaking'- const anyPlaybackActive = voicePlayback.status !== 'idle'- const Icon = isPreparing ? Loader2Icon : isSpeaking ? VolumeXIcon : AudioLines-- const tooltip = isPreparing- ? copy.preparingAudio- : isSpeaking- ? copy.stopReading- : fullResponseAvailable- ? `${copy.readAloud} (${copy.readAloudFullResponseHint})`- : copy.readAloud-- // Default reads the current reply only; Shift-click reads the whole response- // group — the read-aloud mirror of the two copy scopes (#118864).- const read = useCallback(- async (full: boolean) => {- const text = full ? getFullText() : getText()-- if (!text || $voicePlayback.get().status !== 'idle') {- return- }-- try {- await playSpeechText(text, { connectionId, messageId, profile, source: 'read-aloud' })- markAssistantIdSpoken(sessionId, view.$messages.get(), messageId)- } catch (error) {- notifyError(error, copy.readAloudFailed)- }- },- [connectionId, copy.readAloudFailed, getFullText, getText, messageId, profile, sessionId, view.$messages]- )+const ReadAloudButton: FC<{ action: ReadAloudActionState }> = ({ action }) => {+ const Icon = action.isPreparing ? Loader2Icon : action.isSpeaking ? VolumeXIcon : AudioLinesreturn (- <TooltipIconButton- disabled={isPreparing || (!isSpeaking && anyPlaybackActive)}- onClick={event => {- triggerHaptic('selection')- void (isSpeaking ? stopVoicePlayback() : read(event.shiftKey))- }}- tooltip={tooltip}- >- <Icon className={cn('size-3.5', isPreparing && 'animate-spin')} />+ <TooltipIconButton disabled={action.disabled} onClick={action.onActivate} tooltip={action.tooltip}>+ <Icon className={cn('size-3.5', action.isPreparing && 'animate-spin')} /></TooltipIconButton>)}diff --git a/apps/desktop/src/components/assistant-ui/thread/double-click-reaction.test.tsx b/apps/desktop/src/components/assistant-ui/thread/double-click-reaction.test.tsxindex 67a7016b7f5..15b813881b4 100644--- a/apps/desktop/src/components/assistant-ui/thread/double-click-reaction.test.tsx+++ b/apps/desktop/src/components/assistant-ui/thread/double-click-reaction.test.tsx@@ -43,6 +43,8 @@ beforeEach(() => {afterEach(() => {cleanup()+ vi.restoreAllMocks()+ vi.unstubAllGlobals()})describe('isTapbackDoubleClick', () => {@@ -67,6 +69,26 @@ describe('isTapbackDoubleClick', () => {})describe('double-click to heart an assistant message', () => {+ it('leaves touch double-tap selection intact instead of claiming it as a reaction', async () => {+ vi.stubGlobal(+ 'matchMedia',+ vi.fn((query: string) => ({+ matches: query.includes('pointer'),+ addEventListener: vi.fn(),+ removeEventListener: vi.fn()+ }))+ )+ $reactionsEnabled.set(true)+ render(<Harness />)+ const text = await screen.findByText('done')+ const range = document.createRange()+ range.selectNodeContents(text)+ window.getSelection()!.addRange(range)+ fireEvent.doubleClick(text, { detail: 2 })+ expect(window.getSelection()!.toString()).toBe('done')+ expect($localReactions.get()['assistant-1']).toBeUndefined()+ window.getSelection()!.removeAllRanges()+ })it('hearts the message, and a second double-click retracts it', async () => {$reactionsEnabled.set(true)render(<Harness />)diff --git a/apps/desktop/src/components/assistant-ui/thread/response-copy-scope.test.tsx b/apps/desktop/src/components/assistant-ui/thread/response-copy-scope.test.tsxindex 16970137527..33e23aa66f1 100644--- a/apps/desktop/src/components/assistant-ui/thread/response-copy-scope.test.tsx+++ b/apps/desktop/src/components/assistant-ui/thread/response-copy-scope.test.tsx@@ -9,6 +9,7 @@ import { afterEach, beforeEach, expect, it, vi } from 'vitest'import { toChatMessages } from '@/lib/chat-messages'import { toRuntimeMessage } from '@/lib/chat-runtime'+import { $touchPointer } from '@/lib/touch-interaction'import type { SessionMessage } from '@/types/hermes'import { stubThreadEnvironment, ThreadRuntime } from '../test-utils'@@ -18,6 +19,7 @@ import { Thread } from '.'beforeEach(stubThreadEnvironment)afterEach(() => {cleanup()+ $touchPointer.set(false)vi.unstubAllGlobals()})@@ -47,15 +49,20 @@ function renderThread() {return { clipboard, ...rendered }}-it('default Copy reads only the tail reply, not the whole response group', async () => {- const { clipboard, container } = renderThread()+it.each(['desktop', 'touch'])(+ 'default %s Copy reads only the tail reply, not the whole response group',+ async surface => {+ $touchPointer.set(surface === 'touch')+ const { clipboard, container } = renderThread()- await waitFor(() => expect(container.textContent).toContain('The deployment is verified.'))- const actions = container.querySelector('[data-slot="aui_msg-actions"]') as HTMLElement- fireEvent.click(within(actions).getByRole('button', { name: /^copy$/i }))+ await waitFor(() => expect(container.textContent).toContain('The deployment is verified.'))+ const actions = container.querySelector('[data-slot="aui_msg-actions"]') as HTMLElement+ const surfaceActions = actions.querySelector(`.aui-message-actions-${surface}`) as HTMLElement+ fireEvent.click(within(surfaceActions).getByRole('button', { name: /^copy$/i }))- await waitFor(() => expect(clipboard.writeText).toHaveBeenLastCalledWith('The deployment is verified.'))-})+ await waitFor(() => expect(clipboard.writeText).toHaveBeenLastCalledWith('The deployment is verified.'))+ }+)it('Copy full response reads every assistant text segment in the group', async () => {const { clipboard, container } = renderThread()@@ -69,25 +76,31 @@ it('Copy full response reads every assistant text segment in the group', async ()})-it('a solo reply copies its own text and offers no separate full-response button', async () => {- const storedSolo: SessionMessage[] = [- { role: 'user', content: 'Hi', timestamp: 1 },- { role: 'assistant', content: 'Hello there.', timestamp: 2 }- ]-- const clipboard = { writeText: vi.fn().mockResolvedValue(undefined) }- vi.stubGlobal('navigator', { ...navigator, clipboard })-- const { container } = render(- <ThreadRuntime messages={toChatMessages(storedSolo).map(toRuntimeMessage)}>- <Thread />- </ThreadRuntime>- )-- await waitFor(() => expect(container.textContent).toContain('Hello there.'))- const actions = container.querySelector('[data-slot="aui_msg-actions"]') as HTMLElement- fireEvent.click(within(actions).getByRole('button', { name: /^copy$/i }))- await waitFor(() => expect(clipboard.writeText).toHaveBeenLastCalledWith('Hello there.'))- // The two scopes are identical on a solo reply, so only the default Copy exists.- expect(within(actions).queryByRole('button', { name: /copy full response/i })).toBeNull()-})+it.each(['desktop', 'touch'])(+ 'a solo reply copies its own text through %s actions and offers no full-response button',+ async surface => {+ $touchPointer.set(surface === 'touch')++ const storedSolo: SessionMessage[] = [+ { role: 'user', content: 'Hi', timestamp: 1 },+ { role: 'assistant', content: 'Hello there.', timestamp: 2 }+ ]++ const clipboard = { writeText: vi.fn().mockResolvedValue(undefined) }+ vi.stubGlobal('navigator', { ...navigator, clipboard })++ const { container } = render(+ <ThreadRuntime messages={toChatMessages(storedSolo).map(toRuntimeMessage)}>+ <Thread />+ </ThreadRuntime>+ )++ await waitFor(() => expect(container.textContent).toContain('Hello there.'))+ const actions = container.querySelector('[data-slot="aui_msg-actions"]') as HTMLElement+ const surfaceActions = actions.querySelector(`.aui-message-actions-${surface}`) as HTMLElement+ fireEvent.click(within(surfaceActions).getByRole('button', { name: /^copy$/i }))+ await waitFor(() => expect(clipboard.writeText).toHaveBeenLastCalledWith('Hello there.'))+ // The two scopes are identical on a solo reply, so only the default Copy exists.+ expect(within(actions).queryByRole('button', { name: /copy full response/i })).toBeNull()+ }+)diff --git a/apps/desktop/src/components/assistant-ui/thread/response-group.test.tsx b/apps/desktop/src/components/assistant-ui/thread/response-group.test.tsxindex 19064661fa4..f77cac0fc8c 100644--- a/apps/desktop/src/components/assistant-ui/thread/response-group.test.tsx+++ b/apps/desktop/src/components/assistant-ui/thread/response-group.test.tsx@@ -59,8 +59,9 @@ it('keeps background continuations in one response with one action bar and the o).toEqual([messages[1]!.id, messages[3]!.id])const actions = container.querySelector('[data-slot="aui_msg-actions"]') as HTMLElement// Default Copy reads only the tail reply; the full-response scope is a- // separate explicit action (#118864).- fireEvent.click(within(actions).getByRole('button', { name: /^copy$/i }))+ // separate explicit action (#118864). Each input-mode lane is covered in+ // response-copy-scope.test.tsx.+ fireEvent.click(within(actions).getAllByRole('button', { name: /^copy$/i })[0]!)await waitFor(() => expect(clipboard.writeText).toHaveBeenLastCalledWith('The deployment is verified.'))fireEvent.click(within(actions).getByRole('button', { name: /copy full response/i }))await waitFor(() =>diff --git a/apps/desktop/src/components/assistant-ui/thread/use-message-reactions.ts b/apps/desktop/src/components/assistant-ui/thread/use-message-reactions.tsindex 2578812a238..6c6f2c950ba 100644--- a/apps/desktop/src/components/assistant-ui/thread/use-message-reactions.ts+++ b/apps/desktop/src/components/assistant-ui/thread/use-message-reactions.ts@@ -6,6 +6,7 @@ import { type MouseEvent, useCallback } from 'react'import { useSessionView } from '@/app/chat/session-view'import type { ChatMessage } from '@/lib/chat-messages'import { triggerHaptic } from '@/lib/haptics'+import { isTouchInteraction } from '@/lib/touch-interaction'import { activeGatewayConnectionId } from '@/store/gateway'import { $activeGatewayProfile } from '@/store/profile'import { QUICK_REACTIONS, toggleMessageReaction } from '@/store/reactions'@@ -144,7 +145,7 @@ export function useTapbackDoubleClick(const onDoubleClick = useCallback((event: MouseEvent<HTMLElement>) => {- if (!isTapbackDoubleClick(event)) {+ if (isTouchInteraction(event.nativeEvent) || !isTapbackDoubleClick(event)) {return}diff --git a/apps/desktop/src/components/assistant-ui/thread/user-edit-composer.tsx b/apps/desktop/src/components/assistant-ui/thread/user-edit-composer.tsxindex ea84ea5315e..0404c80ccf5 100644--- a/apps/desktop/src/components/assistant-ui/thread/user-edit-composer.tsx+++ b/apps/desktop/src/components/assistant-ui/thread/user-edit-composer.tsx@@ -55,7 +55,8 @@ import {extractDroppedFiles,HERMES_PATHS_MIME,isImagePath,- partitionDroppedFiles+ partitionDroppedFiles,+ stageDroppedFilePath} from '@/app/chat/hooks/use-composer-actions'import { uploadComposerAttachment } from '@/app/session/hooks/use-prompt-actions'import { hermesDirectiveFormatter } from '@/components/assistant-ui/directive-text'@@ -475,16 +476,17 @@ export const UserEditComposer: FC<UserEditComposerProps> = ({ cwd, gateway, sessconst refs: InlineRefInput[] = []for (const candidate of osDrops) {- const path = candidate.path || ''+ try {+ // A rejected stage carries the server's or a proxy's reason (an nginx 413).+ const path = await stageDroppedFilePath(candidate)- if (!path) {- continue- }+ if (!path) {+ continue+ }- const kind: ComposerAttachment['kind'] =- candidate.file?.type.startsWith('image/') || isImagePath(candidate.file?.name || path) ? 'image' : 'file'+ const kind: ComposerAttachment['kind'] =+ candidate.file?.type.startsWith('image/') || isImagePath(candidate.file?.name || path) ? 'image' : 'file'- try {const uploaded = await uploadComposerAttachment({ detail: path, id: attachmentId(kind, path), kind, label: pathLabel(path), path },{ backendCwd: cwd, remote, requestGateway, sessionId, terminalBackend: $terminalBackend.get() }diff --git a/apps/desktop/src/components/assistant-ui/thread/user-message-edit-drop-staging.test.tsx b/apps/desktop/src/components/assistant-ui/thread/user-message-edit-drop-staging.test.tsxnew file mode 100644index 00000000000..1281ced3207--- /dev/null+++ b/apps/desktop/src/components/assistant-ui/thread/user-message-edit-drop-staging.test.tsx@@ -0,0 +1,86 @@+// An OS drop into the message-edit composer that the shell cannot expose as a+// native path is staged as File bytes (the Webapp bridge uploads it). When that+// staging is rejected, the reason the server or a proxy gave (an nginx 413, a+// 502) must reach the user; the drop used to vanish without a word.+import {+ type AppendMessage,+ AssistantRuntimeProvider,+ ExportedMessageRepository,+ type ThreadMessage+} from '@assistant-ui/react'+import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'+import { afterEach, describe, expect, it, vi } from 'vitest'++import type { HermesGateway } from '@/hermes'+import { useIncrementalExternalStoreRuntime } from '@/lib/incremental-external-store-runtime'+import { $notifications, clearNotifications } from '@/store/notifications'++import { assistantMessage, stubThreadEnvironment, stubThreadViewportSize, userMessage } from '../test-utils'++import { Thread } from '.'++stubThreadEnvironment()+stubThreadViewportSize()++const UPLOAD_413 = 'File upload failed (413): the file is larger than the server or a proxy in front of it accepts'++afterEach(() => {+ cleanup()+ clearNotifications()+ Reflect.deleteProperty(window, 'hermesDesktop')+})++function Harness({ gateway }: { gateway: HermesGateway }) {+ const repository = ExportedMessageRepository.fromArray([userMessage(), assistantMessage()])++ const runtime = useIncrementalExternalStoreRuntime<ThreadMessage>({+ messageRepository: repository,+ isRunning: false,+ setMessages: () => {},+ onNew: async () => {},+ onEdit: async (_message: AppendMessage) => {},+ onCancel: async () => {},+ onReload: async () => {}+ })++ return (+ <AssistantRuntimeProvider runtime={runtime}>+ <Thread cwd="/workspace" gateway={gateway} sessionId="session-1" />+ </AssistantRuntimeProvider>+ )+}++// A browser drop: a File with no native path (the Webapp shell has no getPathForFile).+function fileDrop(file: File) {+ return {+ files: { item: (index: number) => (index === 0 ? file : null), length: 1 },+ getData: () => '',+ items: [{ getAsFile: () => file, kind: 'file', webkitGetAsEntry: () => null }],+ types: ['Files']+ }+}++describe('edit composer drop staging failures', () => {+ it('reports why a dropped file could not be staged', async () => {+ const stageFileForAttach = vi.fn(async () => {+ throw new Error(UPLOAD_413)+ })++ Object.defineProperty(window, 'hermesDesktop', { configurable: true, value: { stageFileForAttach } })+ const request = vi.fn(async () => ({}))+ render(<Harness gateway={{ request } as unknown as HermesGateway} />)++ fireEvent.click(await screen.findByRole('button', { name: 'Edit message' }))+ const editor = await screen.findByRole('textbox', { name: 'Edit message' })++ await act(async () => {+ fireEvent.drop(editor, { dataTransfer: fileDrop(new File(['payload'], 'notes.txt', { type: 'text/plain' })) })+ })++ await waitFor(() => expect(stageFileForAttach).toHaveBeenCalledOnce())+ await waitFor(() =>+ expect($notifications.get()).toEqual([expect.objectContaining({ kind: 'error', message: UPLOAD_413 })])+ )+ expect(request).not.toHaveBeenCalledWith('file.attach', expect.anything())+ })+})diff --git a/apps/desktop/src/components/assistant-ui/thread/user-message-edit-gesture.test.tsx b/apps/desktop/src/components/assistant-ui/thread/user-message-edit-gesture.test.tsxindex 2007730c8e2..2bf359543ae 100644--- a/apps/desktop/src/components/assistant-ui/thread/user-message-edit-gesture.test.tsx+++ b/apps/desktop/src/components/assistant-ui/thread/user-message-edit-gesture.test.tsx@@ -8,6 +8,7 @@ import { act, cleanup, fireEvent, render, screen, waitFor } from '@testing-libraimport { afterEach, describe, expect, it, vi } from 'vitest'import { useIncrementalExternalStoreRuntime } from '@/lib/incremental-external-store-runtime'+import { $touchPointer } from '@/lib/touch-interaction'import { assistantMessage, stubThreadEnvironment, stubThreadViewportSize, userMessage } from '../test-utils'@@ -16,6 +17,9 @@ stubThreadEnvironment()afterEach(() => {cleanup()+ $touchPointer.set(false)+ vi.restoreAllMocks()+ vi.unstubAllGlobals()})stubThreadViewportSize()@@ -56,6 +60,16 @@ function Harness({ onEdit }: { onEdit: (message: AppendMessage) => Promise<void>// it. Capture process-level uncaught exceptions for the duration of the gesture// instead — an unguarded throw registers here and fails the test.describe('edit send arrow — macOS click gesture (blur races cancel)', () => {+ it('keeps touch prose outside the edit button and requires explicit Edit', async () => {+ $touchPointer.set(true)+ render(<Harness onEdit={vi.fn(async () => {})} />)+ const text = await screen.findByText('edit me please')+ expect(text.closest('button, [role="button"]')).toBeNull()+ fireEvent.click(text)+ expect(screen.queryByRole('textbox', { name: 'Edit message' })).toBeNull()+ fireEvent.click(screen.getByRole('button', { name: 'Edit message' }))+ expect(await screen.findByRole('textbox', { name: 'Edit message' })).toBeTruthy()+ })it('sends without an uncaught "Composer is not available" when the arrow-click blurs the editor', async () => {const uncaught: unknown[] = []diff --git a/apps/desktop/src/components/assistant-ui/thread/user-message.tsx b/apps/desktop/src/components/assistant-ui/thread/user-message.tsxindex 9e35f85a85b..ec5de7415be 100644--- a/apps/desktop/src/components/assistant-ui/thread/user-message.tsx+++ b/apps/desktop/src/components/assistant-ui/thread/user-message.tsx@@ -1,4 +1,5 @@import { ActionBarPrimitive, BranchPickerPrimitive, MessagePrimitive, useAuiState } from '@assistant-ui/react'+import { useStore } from '@nanostores/react'import { type FC, type ReactNode, useCallback, useEffect, useRef, useState } from 'react'import { DirectiveContent } from '@/components/assistant-ui/directive-text'@@ -16,6 +17,7 @@ import { MessageTimelineTimestamp } from '@/components/assistant-ui/thread/timelimport { type RestoreMessageTarget } from '@/components/assistant-ui/thread/types'import { useMessageReactions } from '@/components/assistant-ui/thread/use-message-reactions'import { UserMessageText } from '@/components/assistant-ui/thread/user-message-text'+import { Button } from '@/components/ui/button'import { Codicon } from '@/components/ui/codicon'import { Tip } from '@/components/ui/tooltip'import { useResizeObserver } from '@/hooks/use-resize-observer'@@ -23,6 +25,7 @@ import { useI18n } from '@/i18n'import { triggerHaptic } from '@/lib/haptics'import { StopFilled } from '@/lib/icons'import { LruCache } from '@/lib/lru-cache'+import { $touchPointer } from '@/lib/touch-interaction'import { cn } from '@/lib/utils'import { $gateway } from '@/store/gateway'import { notifyThreadEditOpen } from '@/store/thread-scroll'@@ -254,8 +257,12 @@ interface UserBubbleActionsProps {runtimeUserOrdinal: RestoreMessageTarget['userOrdinal']showRestore: booleanshowStop: boolean+ touch: boolean}+/** Bottom-right cluster: when it was sent, then Stop or Restore. Its fill+ * masks the last line's tail while shown. Touch has no hover, so Stop/Restore+ * stay visible there and a cluster with neither is not rendered. */const UserBubbleActions: FC<UserBubbleActionsProps> = ({fullText,messageId,@@ -263,17 +270,29 @@ const UserBubbleActions: FC<UserBubbleActionsProps> = ({onRequestRestoreConfirm,runtimeUserOrdinal,showRestore,- showStop+ showStop,+ touch}) => {const copy = useI18n().t.assistant.thread+ if (touch && !showStop && !showRestore) {+ return null+ }+return (- <>- <MessageHoverTime className={cn(!showStop && !showRestore && 'pr-0.5')} />+ <div+ className={cn(+ 'pointer-events-none absolute right-2 bottom-2 z-10 flex items-center gap-1 rounded-md bg-(--dt-user-bubble) pl-1 transition-opacity',+ touch+ ? 'opacity-100'+ : 'opacity-0 group-hover/user-message:opacity-100 group-hover/user-message:transition-none group-focus-within/user-message:opacity-100'+ )}+ >+ {!touch && <MessageHoverTime className={cn(!showStop && !showRestore && 'pr-0.5')} />}{showStop ? (<buttonaria-label={copy.stop}- className={cn('pointer-events-auto size-5', USER_ACTION_ICON_BUTTON_CLASS)}+ className={cn('pointer-events-auto', touch ? 'size-11' : 'size-5', USER_ACTION_ICON_BUTTON_CLASS)}onClick={event => {event.preventDefault()event.stopPropagation()@@ -287,7 +306,7 @@ const UserBubbleActions: FC<UserBubbleActionsProps> = ({<Tip label={copy.restoreFromHere}><buttonaria-label={copy.restoreCheckpoint}- className={cn('pointer-events-auto size-6', USER_ACTION_ICON_BUTTON_CLASS)}+ className={cn('pointer-events-auto', touch ? 'size-11' : 'size-6', USER_ACTION_ICON_BUTTON_CLASS)}onClick={event => {event.preventDefault()event.stopPropagation()@@ -307,16 +326,107 @@ const UserBubbleActions: FC<UserBubbleActionsProps> = ({</button></Tip>) : null}+ </div>+ )+}++interface TouchUserBubbleProps {+ children: ReactNode+ className: string+ editable: boolean+ showRestore: boolean+ showStop: boolean+}++/** Touch bubble: the prose stays plain selectable text, so a long press keeps+ * the platform's selection handles and Copy, and editing is an explicit button+ * below it instead of a tap on the bubble. The Edit row leaves room for the+ * Stop/Restore cluster pinned over its end. */+function TouchUserBubble({ children, className, editable, showRestore, showStop }: TouchUserBubbleProps) {+ const copy = useI18n().t.assistant.thread++ return (+ <>+ <div className={cn(className, 'cursor-text')} data-selectable-text="true">+ {children}+ </div>+ <div className={cn('flex justify-end', (showStop || showRestore) && 'pr-11')}>+ {editable && (+ <ActionBarPrimitive.Edit asChild>+ <Button+ aria-label={copy.editMessage}+ data-slot="aui_user-touch-edit"+ onClick={notifyThreadEditOpen}+ size="icon"+ variant="ghost"+ >+ <Codicon name="edit" />+ </Button>+ </ActionBarPrimitive.Edit>+ )}+ </div></>)}+/** Sticky human bubbles clamp to ~2 lines with a soft fade so a long prompt+ * doesn't dominate the viewport while the response streams underneath; the+ * clamp lifts on hover / focus (see styles.css). We measure the *unclamped*+ * inner wrapper so the ResizeObserver only fires on real content / width+ * changes, not on every frame while the outer max-height animates open.+ * Touch has no hover to lift it, so a touch bubble is never clamped. */+function useUserBubbleClamp(readOnly: boolean, touch: boolean) {+ const clampInnerRef = useRef<HTMLDivElement | null>(null)+ const [bodyClamped, setBodyClamped] = useState(false)+ const lastClampHeightRef = useRef(-1)+ const lineHeightRef = useRef(0)+ const [expanded, setExpanded] = useState(false)+ const clampActive = !touch && !(readOnly && expanded)++ const measureClamp = useCallback((entries: readonly ResizeObserverEntry[]) => {+ const inner = clampInnerRef.current+ const outer = inner?.parentElement++ if (!inner || !outer) {+ return+ }++ // Prefer the size the ResizeObserver already computed — reading+ // `scrollHeight` outside RO timing forces a synchronous layout, and with+ // many user bubbles observed at once those reads interleave with the+ // style write below into a read-write-read reflow cascade.+ const entryHeight = entries.find(entry => entry.target === inner)?.borderBoxSize?.[0]?.blockSize+ const fullHeight = Math.ceil(entryHeight ?? inner.scrollHeight)++ if (fullHeight === lastClampHeightRef.current) {+ return+ }++ lastClampHeightRef.current = fullHeight++ // Line-height is stable for the life of the bubble (font settings don't+ // change under it) — resolve the computed style once.+ if (!lineHeightRef.current) {+ const styles = getComputedStyle(inner)+ lineHeightRef.current = parseFloat(styles.lineHeight) || 1.5 * parseFloat(styles.fontSize) || 20+ }++ outer.style.setProperty('--human-msg-full', `${fullHeight}px`)+ setBodyClamped(fullHeight > lineHeightRef.current * 2 + 1)+ }, [])++ useResizeObserver(measureClamp, clampInnerRef)++ return { bodyClamped, clampActive, clampInnerRef, expanded, setExpanded }+}+export const UserMessage: FC<{onCancel?: () => Promise<void> | voidonRequestRestoreConfirm?: (messageId: string, target: RestoreMessageTarget) => void}> = ({ onCancel, onRequestRestoreConfirm }) => {const { t } = useI18n()const copy = t.assistant.thread+ const touch = useStore($touchPointer)const messageId = useAuiState(s => s.message.id)const content = useAuiState(s => s.message.content)const messageText = messageContentText(content)@@ -353,56 +463,11 @@ export const UserMessage: FC<{[react])- // Sticky human bubbles clamp to ~2 lines with a soft fade so a long prompt- // doesn't dominate the viewport while the response streams underneath; the- // clamp lifts on hover / focus (see styles.css). We measure the *unclamped*- // inner wrapper so the ResizeObserver only fires on real content / width- // changes, not on every frame while the outer max-height animates open.- const clampInnerRef = useRef<HTMLDivElement | null>(null)- const [bodyClamped, setBodyClamped] = useState(false)- const lastClampHeightRef = useRef(-1)- const lineHeightRef = useRef(0)-// Watch windows spectate a subagent run driven elsewhere — prompts can't be// edited, restored, or stopped from here. The bubble stays a button that// toggles the 2-line clamp so long prompts are still fully readable.const readOnly = isWatchWindow()- const [expanded, setExpanded] = useState(false)- const clampActive = !(readOnly && expanded)-- const measureClamp = useCallback((entries: readonly ResizeObserverEntry[]) => {- const inner = clampInnerRef.current- const outer = inner?.parentElement-- if (!inner || !outer) {- return- }-- // Prefer the size the ResizeObserver already computed — reading- // `scrollHeight` outside RO timing forces a synchronous layout, and with- // many user bubbles observed at once those reads interleave with the- // style write below into a read-write-read reflow cascade.- const entryHeight = entries.find(entry => entry.target === inner)?.borderBoxSize?.[0]?.blockSize- const fullHeight = Math.ceil(entryHeight ?? inner.scrollHeight)-- if (fullHeight === lastClampHeightRef.current) {- return- }-- lastClampHeightRef.current = fullHeight-- // Line-height is stable for the life of the bubble (font settings don't- // change under it) — resolve the computed style once.- if (!lineHeightRef.current) {- const styles = getComputedStyle(inner)- lineHeightRef.current = parseFloat(styles.lineHeight) || 1.5 * parseFloat(styles.fontSize) || 20- }-- outer.style.setProperty('--human-msg-full', `${fullHeight}px`)- setBodyClamped(fullHeight > lineHeightRef.current * 2 + 1)- }, [])-- useResizeObserver(measureClamp, clampInnerRef)+ const { bodyClamped, clampActive, clampInnerRef, expanded, setExpanded } = useUserBubbleClamp(readOnly, touch)// Injected background-process notification, not a human prompt — render the// compact system-style notice (after all hooks above have run).@@ -505,13 +570,13 @@ export const UserMessage: FC<{// menu, and this handler's selection guard keeps ⌘C flows.data-context-menu-skip=""onContextMenu={- // Right-click is the desktop stand-in for iOS touch-and-hold —- // but only when there's nothing selected. A live highlight- // keeps the native Copy menu (and ⌘C) instead of the picker.+ // Right-click is the desktop reaction gesture. Touch surfaces+ // leave long-press entirely to the platform so selection+ // handles and Copy are never replaced by the picker.readOnly || !reactionsEnabled? undefined: event => {- if (hasTextSelection()) {+ if (hasTextSelection() || touch) {return}@@ -520,7 +585,16 @@ export const UserMessage: FC<{}}>- {readOnly ? (+ {touch ? (+ <TouchUserBubble+ className={bubbleClassName}+ editable={!readOnly}+ showRestore={showRestore}+ showStop={showStop}+ >+ {bubbleContent}+ </TouchUserBubble>+ ) : readOnly ? (// Spectator transcript: clicking only toggles the clamp so the// full prompt is readable — never opens an edit composer.<button@@ -572,19 +646,16 @@ export const UserMessage: FC<{</button></ActionBarPrimitive.Edit>)}- {/* Hover cluster, bottom-right: when it was sent, then Stop or- Restore. Its fill masks the last line's tail while shown. */}- <div className="pointer-events-none absolute right-2 bottom-2 z-10 flex items-center gap-1 rounded-md bg-(--dt-user-bubble) pl-1 opacity-0 transition-opacity group-hover/user-message:opacity-100 group-hover/user-message:transition-none group-focus-within/user-message:opacity-100">- <UserBubbleActions- fullText={messageText}- messageId={messageId}- onCancel={onCancel}- onRequestRestoreConfirm={onRequestRestoreConfirm}- runtimeUserOrdinal={runtimeUserOrdinal}- showRestore={showRestore}- showStop={showStop}- />- </div>+ <UserBubbleActions+ fullText={messageText}+ messageId={messageId}+ onCancel={onCancel}+ onRequestRestoreConfirm={onRequestRestoreConfirm}+ runtimeUserOrdinal={runtimeUserOrdinal}+ showRestore={showRestore}+ showStop={showStop}+ touch={touch}+ /></div></ReactionPicker>{/* Below the bubble, same register as the assistant action row:diff --git a/apps/desktop/src/components/chat/code-card.tsx b/apps/desktop/src/components/chat/code-card.tsxindex 880413801a2..00bd0d1507c 100644--- a/apps/desktop/src/components/chat/code-card.tsx+++ b/apps/desktop/src/components/chat/code-card.tsx@@ -36,7 +36,7 @@ function CodeCardBody({ className, ...props }: React.ComponentProps<'div'>) {return (<divclassName={cn(- 'font-mono text-[length:calc(0.7rem*var(--conversation-text-scale,1))] leading-relaxed text-foreground/90 [&_pre]:m-0 [&_pre]:overflow-x-auto [&_pre]:scrollbar-overlay [&_pre]:bg-transparent! [&_pre]:px-2 [&_pre]:py-1.5 [&_pre]:font-mono [&_pre]:leading-relaxed',+ 'font-mono text-[length:calc(0.7rem*var(--conversation-text-scale,1))] leading-relaxed text-foreground/90 [&_pre]:m-0 [&_pre]:min-w-max [&_pre]:overflow-x-auto [&_pre]:scrollbar-overlay [&_pre]:bg-transparent! [&_pre]:px-2 [&_pre]:py-1.5 [&_pre]:font-mono [&_pre]:leading-relaxed',className)}data-slot="code-card-body"diff --git a/apps/desktop/src/components/chat/expandable-block.test.tsx b/apps/desktop/src/components/chat/expandable-block.test.tsxindex 4d232fff979..371c788aeb0 100644--- a/apps/desktop/src/components/chat/expandable-block.test.tsx+++ b/apps/desktop/src/components/chat/expandable-block.test.tsx@@ -11,6 +11,9 @@ class TestResizeObserver {observe(target: Element) {Object.defineProperty(target, 'scrollHeight', { configurable: true, value: 400 })+ Object.defineProperty(target, 'clientWidth', { configurable: true, value: 200 })+ Object.defineProperty(target, 'scrollWidth', { configurable: true, value: 400 })+ Object.defineProperty(target, 'scrollLeft', { configurable: true, writable: true, value: 0 })this.callback([{ target } as ResizeObserverEntry], this as unknown as ResizeObserver)}@@ -40,4 +43,32 @@ describe('ExpandableBlock', () => {expect(screen.getByRole('button', { name: 'Collapse' }).getAttribute('aria-expanded')).toBe('true')})++ it('shows a non-blocking horizontal cue until a wide block reaches its end', () => {+ vi.stubGlobal('ResizeObserver', TestResizeObserver)++ render(+ <ExpandableBlock>+ <pre data-testid="content">{'wide line\n'.repeat(2)}</pre>+ </ExpandableBlock>+ )++ const scroller = screen.getByTestId('content').parentElement!++ expect(scroller.getAttribute('data-horizontal-overflow')).toBe('')+ expect(+ screen+ .getByTestId('content')+ .parentElement?.parentElement?.querySelector('[data-slot="expandable-horizontal-fade"]')+ ).not.toBeNull()++ scroller.scrollLeft = 200+ fireEvent.scroll(scroller)++ expect(+ screen+ .getByTestId('content')+ .parentElement?.parentElement?.querySelector('[data-slot="expandable-horizontal-fade"]')+ ).toBeNull()+ })})diff --git a/apps/desktop/src/components/chat/expandable-block.tsx b/apps/desktop/src/components/chat/expandable-block.tsxindex e49ed29712a..89a1474dc35 100644--- a/apps/desktop/src/components/chat/expandable-block.tsx+++ b/apps/desktop/src/components/chat/expandable-block.tsx@@ -15,6 +15,8 @@ export function ExpandableBlock({ children, className }: ExpandableBlockProps) {const innerRef = useRef<HTMLDivElement>(null)const [expanded, setExpanded] = useState(false)const [overflowing, setOverflowing] = useState(false)+ const [horizontalOverflowing, setHorizontalOverflowing] = useState(false)+ const [horizontalAtEnd, setHorizontalAtEnd] = useState(false)// Measure inside ResizeObserver timing only (layout is clean there). A// synchronous mount-time scrollHeight read forces a reflow per instance,@@ -24,9 +26,23 @@ export function ExpandableBlock({ children, className }: ExpandableBlockProps) {if (el) {setOverflowing(el.scrollHeight > 121)+ const hasHorizontalOverflow = el.scrollWidth > el.clientWidth + 1++ setHorizontalOverflowing(hasHorizontalOverflow)+ setHorizontalAtEnd(!hasHorizontalOverflow || el.scrollLeft + el.clientWidth >= el.scrollWidth - 1)}}, [])+ const handleScroll = useCallback(() => {+ const el = innerRef.current++ if (!el || !horizontalOverflowing) {+ return+ }++ setHorizontalAtEnd(el.scrollLeft + el.clientWidth >= el.scrollWidth - 1)+ }, [horizontalOverflowing])+useResizeObserver(measure, innerRef)return (@@ -39,10 +55,19 @@ export function ExpandableBlock({ children, className }: ExpandableBlockProps) {expanded ? 'max-h-[40dvh]' : 'max-h-[7.5rem]',className)}+ data-horizontal-overflow={horizontalOverflowing ? '' : undefined}+ onScroll={handleScroll}ref={innerRef}>{children}</div>+ {horizontalOverflowing && !horizontalAtEnd && (+ <div+ aria-hidden+ className="pointer-events-none absolute inset-y-0 right-0 w-5 bg-linear-to-l from-[var(--expandable-fade-from,var(--ui-chat-surface-background))] to-transparent"+ data-slot="expandable-horizontal-fade"+ />+ )}{overflowing && (// The fade is a pure overflow cue and must not intercept pointer events:// it spans the full bottom edge (over the horizontal scrollbar of a widediff --git a/apps/desktop/src/components/chat/generated-image-result.tsx b/apps/desktop/src/components/chat/generated-image-result.tsxindex 5ae4384c4b4..0aeca92b7ed 100644--- a/apps/desktop/src/components/chat/generated-image-result.tsx+++ b/apps/desktop/src/components/chat/generated-image-result.tsx@@ -8,8 +8,15 @@ import { useImageDownload } from '@/hooks/use-image-download'import { useMediaImage } from '@/hooks/use-media-image'import { useI18n } from '@/i18n'import { generatedImageDimensionsFromResult, generatedImageFromResult } from '@/lib/generated-images'-import { mediaExternalUrl, mediaName } from '@/lib/media'+import {+ downloadGatewayMediaFile,+ isFileMediaPath,+ isRemoteGateway,+ mediaExternalUrl,+ mediaName+} from '@/lib/media'import { cn } from '@/lib/utils'+import { notifyError } from '@/store/notifications'// A hint is only a placeholder shape, not a promise about the delivered image.const ASPECT_HINTS: Record<string, number> = {@@ -57,7 +64,15 @@ export const GeneratedImage: FC<{ aspectRatio?: string; result?: unknown }> = ({href="#"onClick={event => {event.preventDefault()- void window.hermesDesktop?.openExternal(mediaExternalUrl(image))++ // A gateway file saves through the host bridge, like every other+ // remote media open: its URL form carries the connection token,+ // which must never land in a browser's history.+ if (isRemoteGateway() && isFileMediaPath(image)) {+ void downloadGatewayMediaFile(image).catch(error => notifyError(error, copy.imageDownloadFailed))+ } else {+ void window.hermesDesktop?.openExternal(mediaExternalUrl(image))+ }}}>{copy.openImage}: {mediaName(image)}diff --git a/apps/desktop/src/components/chat/shiki-highlighter.tsx b/apps/desktop/src/components/chat/shiki-highlighter.tsxindex 62f81a3739b..2fad07a0e80 100644--- a/apps/desktop/src/components/chat/shiki-highlighter.tsx+++ b/apps/desktop/src/components/chat/shiki-highlighter.tsx@@ -198,7 +198,7 @@ export const SyntaxHighlighter: FC<HermesSyntaxHighlighterProps> = ({/><CodeCardBody className="[&_pre]:px-3 [&_pre]:py-2.5"><ExpandableBlock>- <Pre className="aui-shiki m-0 overflow-hidden bg-transparent p-0">+ <Pre className="aui-shiki m-0 bg-transparent p-0">{plain ? (<PlainCode code={content} />) : (diff --git a/apps/desktop/src/components/chat/transcript-video.test.tsx b/apps/desktop/src/components/chat/transcript-video.test.tsxindex c1f67e39ca4..4230e7a3f22 100644--- a/apps/desktop/src/components/chat/transcript-video.test.tsx+++ b/apps/desktop/src/components/chat/transcript-video.test.tsx@@ -17,6 +17,19 @@ describe('video playback speed preference', () => {afterEach(cleanup)+ it('requests inline playback without removing native controls or caller overrides', async () => {+ const { TranscriptVideo } = await loadComponent()+ const { container, rerender } = render(<TranscriptVideo controls src="file:///tmp/mobile.mp4" />)+ const video = container.querySelector('video')!++ expect(video.playsInline).toBe(true)+ expect(video.controls).toBe(true)++ rerender(<TranscriptVideo controls playsInline={false} src="file:///tmp/mobile.mp4" />)+ expect(video.playsInline).toBe(false)+ expect(video.controls).toBe(true)+ })+it('persists a user rate change and seeds the next player from it', async () => {const { TranscriptVideo } = await loadComponent()const { container } = render(<TranscriptVideo src="file:///tmp/clip.mp4" />)diff --git a/apps/desktop/src/components/chat/transcript-video.tsx b/apps/desktop/src/components/chat/transcript-video.tsxindex 65ec41b82e6..7ba3f76dd10 100644--- a/apps/desktop/src/components/chat/transcript-video.tsx+++ b/apps/desktop/src/components/chat/transcript-video.tsx@@ -104,5 +104,6 @@ export function TranscriptVideo(props: ComponentProps<'video'>) {}}, [])- return <video onRateChange={onRateChange} ref={videoRef} {...props} preload={props.preload ?? 'none'} />+ // iPhone otherwise takes a transcript clip fullscreen when playback starts.+ return <video onRateChange={onRateChange} playsInline ref={videoRef} {...props} preload={props.preload ?? 'none'} />}diff --git a/apps/desktop/src/components/pane-shell/narrow-overlay-state.ts b/apps/desktop/src/components/pane-shell/narrow-overlay-state.tsnew file mode 100644index 00000000000..8d7da2cf272--- /dev/null+++ b/apps/desktop/src/components/pane-shell/narrow-overlay-state.ts@@ -0,0 +1,5 @@+import { atom } from 'nanostores'++/** Transient visible overlay pane ids (including aliases and zone mates).+ * Docked/persisted open flags do not describe the narrow overlay. */+export const $narrowOverlayPaneIds = atom<ReadonlySet<string>>(new Set())diff --git a/apps/desktop/src/components/pane-shell/tree/renderer/compact-tab-picker.test.tsx b/apps/desktop/src/components/pane-shell/tree/renderer/compact-tab-picker.test.tsxnew file mode 100644index 00000000000..d7355213f5c--- /dev/null+++ b/apps/desktop/src/components/pane-shell/tree/renderer/compact-tab-picker.test.tsx@@ -0,0 +1,114 @@+import { useStore } from '@nanostores/react'+import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'+import { MemoryRouter } from 'react-router'+import { afterEach, beforeEach, expect, it, vi } from 'vitest'++import { registry } from '@/contrib/registry'+import { stubMenuDomApis, stubResizeObserver } from '@/test/jsdom'++import { $layoutEditMode } from '../../edit-mode'+import { group } from '../model'+import { $layoutTree, $narrowViewport, $newSessionTabAction } from '../store'++import { TreeGroup } from './tree-group'++const ids = ['workspace', 'session-tile:second', 'session-tile:third']+const disposers: (() => void)[] = []++function Host({ topEdge = false }: { topEdge?: boolean }) {+ const node = useStore($layoutTree)++ return <MemoryRouter>{node?.type === 'group' && <TreeGroup node={node} topEdge={topEdge} />}</MemoryRouter>+}++beforeEach(() => {+ stubResizeObserver()+ stubMenuDomApis()+ vi.stubGlobal('CSS', { escape: (value: string) => value })+ globalThis.document.documentElement.dataset.hermesDesktopHost = 'browser'+ vi.stubGlobal('matchMedia', vi.fn().mockReturnValue({ matches: true, addEventListener: vi.fn(), removeEventListener: vi.fn() }))+ ids.forEach((id, i) => disposers.push(registry.register({+ area: 'panes', id, title: `Session ${i + 1}`, data: { placement: 'main' },+ render: () => <input aria-label={`Draft ${i + 1}`} defaultValue="" />+ })))+ $layoutTree.set({ ...group(ids), active: ids[0], tabStrip: 'always' })+ $narrowViewport.set(true)+})++afterEach(() => {+ cleanup()+ disposers.splice(0).forEach(dispose => dispose())+ $layoutTree.set(null)+ $narrowViewport.set(false)+ $newSessionTabAction.set(null)+ $layoutEditMode.set(false)+ delete globalThis.document.documentElement.dataset.hermesDesktopHost+ vi.restoreAllMocks()+ vi.unstubAllGlobals()+})++it('exposes every phone tab and changes the active pane without discarding its draft or siblings', () => {+ render(<Host />)+ fireEvent.change(screen.getByRole('textbox', { name: 'Draft 1' }), { target: { value: 'keep this draft' } })+ fireEvent.pointerDown(screen.getByRole('button', { name: '3 tabs Session 1' }), { button: 0, pointerType: 'mouse', ctrlKey: false })+ expect(screen.getAllByRole('menuitemradio')).toHaveLength(ids.length)+ fireEvent.click(screen.getByRole('menuitemradio', { name: 'Session 3' }))+ expect($layoutTree.get()).toMatchObject({ active: ids[2], panes: ids })++ fireEvent.pointerDown(screen.getByRole('button', { name: '3 tabs Session 3' }), { button: 0, pointerType: 'mouse', ctrlKey: false })+ fireEvent.click(screen.getByRole('menuitemradio', { name: 'Session 1' }))+ expect((screen.getByRole('textbox', { name: 'Draft 1' }) as HTMLInputElement).value).toBe('keep this draft')+ expect($layoutTree.get()).toMatchObject({ active: ids[0], panes: ids })+})++it('keeps the normal strip on wider layouts', () => {+ act(() => $narrowViewport.set(false))+ const { container } = render(<Host />)+ expect(container.querySelector('[data-slot="compact-tab-picker"]')).toBeNull()+ expect(container.querySelectorAll('[data-tree-tab]')).toHaveLength(ids.length)+})++it('reserves a separate touch row for phone tabs even when the titlebar reports spare space', () => {+ vi.spyOn(HTMLElement.prototype, 'getBoundingClientRect').mockImplementation(function (this: HTMLElement) {+ if (this.dataset.titlebarCluster === 'left') {+ return new DOMRect(14, 0, 44, 44)+ }++ if (this.dataset.titlebarCluster === 'right') {+ return new DOMRect(242, 0, 176, 44)+ }++ return new DOMRect(0, 0, 430, 844)+ })+ $layoutTree.set({ ...group([ids[0]]), active: ids[0], tabStrip: 'always' })+ const newTab = vi.fn()+ $newSessionTabAction.set(newTab)+ const { container } = render(<><div data-titlebar-cluster="left" /><div data-titlebar-cluster="right" /><Host topEdge /></>)+ const header = container.querySelector<HTMLElement>('[data-panel-header]')!+ const height = () => parseFloat(header.style.height)++ // The chrome leaves 148px, but the drag handle and new-tab target consume+ // 92px of it. The picker needs its own row to keep its label and glyphs apart.+ const touchHeader = height()+ expect(screen.getByRole('button', { name: '1 tab Session 1' })).toBeTruthy()+ fireEvent.click(screen.getByRole('button', { name: 'New session tab' }))+ expect(newTab).toHaveBeenCalledOnce()++ // The edit veil starts below the taller header instead of covering the picker.+ const zone = header.parentElement!+ const before = new Set(zone.children)+ act(() => $layoutEditMode.set(true))+ const veils = [...zone.children].filter(child => !before.has(child)) as HTMLElement[]+ expect(veils).toHaveLength(1)+ expect(veils[0]!.style.top).toBe(header.style.height)+ act(() => $layoutEditMode.set(false))++ act(() => $narrowViewport.set(false))+ expect(height()).toBeLessThan(touchHeader)+ expect(container.querySelector('[data-slot="compact-tab-picker"]')).toBeNull()++ delete globalThis.document.documentElement.dataset.hermesDesktopHost+ act(() => $narrowViewport.set(true))+ expect(height()).toBeLessThan(touchHeader)+ expect(container.querySelector('[data-slot="compact-tab-picker"]')).toBeNull()+})diff --git a/apps/desktop/src/components/pane-shell/tree/renderer/compact-tab-picker.tsx b/apps/desktop/src/components/pane-shell/tree/renderer/compact-tab-picker.tsxnew file mode 100644index 00000000000..073908a1cd0--- /dev/null+++ b/apps/desktop/src/components/pane-shell/tree/renderer/compact-tab-picker.tsx@@ -0,0 +1,72 @@+import { type ReactNode, useId } from 'react'++import { Button } from '@/components/ui/button'+import { Codicon } from '@/components/ui/codicon'+import {+ DropdownMenu,+ DropdownMenuContent,+ DropdownMenuItem,+ DropdownMenuRadioGroup,+ DropdownMenuRadioItem,+ DropdownMenuSeparator,+ DropdownMenuTrigger+} from '@/components/ui/dropdown-menu'+import { useI18n } from '@/i18n'++interface CompactTabPickerProps {+ activeId: string+ tabs: { id: string; title: string; label?: ReactNode }[]+ onSelect: (id: string) => void+ onClose?: () => void+ newTab: { label: string; onSelect: () => void } | null+}++/** A phone's strip shows its current tab and a count; every open tab stays+ * reachable without a hidden horizontal drag gesture. */+export function CompactTabPicker({ activeId, tabs, onSelect, onClose, newTab }: CompactTabPickerProps) {+ const { t } = useI18n()+ const labelId = useId()+ const countId = useId()+ const active = tabs.find(tab => tab.id === activeId)+ const count = t.zones.tabCount(tabs.length)++ return (+ <div className="flex min-w-0 flex-1 items-stretch" onPointerDown={event => event.stopPropagation()}>+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button+ aria-labelledby={`${countId} ${labelId}`}+ className="min-w-0 flex-1 justify-between"+ data-slot="compact-tab-picker"+ size="touch"+ variant="ghost"+ >+ <span className="truncate" id={labelId}>{active?.label ?? active?.title}</span>+ <span className="shrink-0 text-xs text-muted-foreground" id={countId}>{count}</span>+ <Codicon name="chevron-down" />+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="start" className="max-w-[calc(100vw-1rem)] min-w-56" side="bottom">+ <DropdownMenuRadioGroup onValueChange={onSelect} value={activeId}>+ {tabs.map(tab => (+ <DropdownMenuRadioItem className="min-h-11" key={tab.id} value={tab.id}>+ <span className="min-w-0 whitespace-normal break-words">{tab.label ?? tab.title}</span>+ </DropdownMenuRadioItem>+ ))}+ </DropdownMenuRadioGroup>+ {onClose && (+ <>+ <DropdownMenuSeparator />+ <DropdownMenuItem className="min-h-11" onSelect={onClose}>{t.common.close}</DropdownMenuItem>+ </>+ )}+ </DropdownMenuContent>+ </DropdownMenu>+ {newTab && (+ <Button aria-label={newTab.label} onClick={newTab.onSelect} size="touch" variant="ghost">+ <Codicon name="add" />+ </Button>+ )}+ </div>+ )+}diff --git a/apps/desktop/src/components/pane-shell/tree/renderer/narrow-overlays.test.tsx b/apps/desktop/src/components/pane-shell/tree/renderer/narrow-overlays.test.tsxindex 0fb7cdc1d28..547cbb372d4 100644--- a/apps/desktop/src/components/pane-shell/tree/renderer/narrow-overlays.test.tsx+++ b/apps/desktop/src/components/pane-shell/tree/renderer/narrow-overlays.test.tsx@@ -2,6 +2,7 @@ import { act, cleanup, fireEvent, render } from '@testing-library/react'import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'import { PANE_TOGGLE_REVEAL_EVENT } from '@/components/pane-shell'+import { $narrowOverlayPaneIds } from '@/components/pane-shell/narrow-overlay-state'import { registry } from '@/contrib/registry'import { $paneStates, setPaneWidthOverride } from '@/store/panes'import { $connection } from '@/store/session'@@ -40,7 +41,12 @@ beforeEach(() => {window.localStorage.clear()$hiddenTreePanes.set(new Set())- registerPane('sessions', 'sessions', { collapsible: true, placement: 'left', width: '237px' }, 'session rows')+ registerPane(+ 'sessions',+ 'sessions',+ { collapsible: true, placement: 'left', width: '237px', revealAliases: ['chat-sidebar'] },+ 'session rows'+ )registerPane('bots', 'Bots', { collapsible: true, placement: 'left', width: '260px' }, 'bot roster')registerPane('workspace', 'workspace', { placement: 'main', uncloseable: true }, 'chat')@@ -54,6 +60,8 @@ afterEach(() => {$layoutTree.set(null)$connection.set(null)vi.restoreAllMocks()+ vi.unstubAllGlobals()+ delete window.document.documentElement.dataset.hermesDesktopHostdelete (window as unknown as { hermesDesktop?: unknown }).hermesDesktopdisposers.splice(0).forEach(dispose => dispose())})@@ -67,6 +75,66 @@ const revealPane = (id: string) => {const overlayTab = (paneId: string) => document.querySelector<HTMLElement>(`[data-narrow-overlay-tab="${paneId}"]`)describe('narrow overlay of a stacked zone', () => {+ it('dismisses an outside tap while preserving inside controls and cancelled gestures', () => {+ render(<NarrowOverlays />)+ revealPane('sessions')+ fireEvent.pointerDown(overlayTab('bots')!, { button: 0 })+ expect(overlayTab('bots')?.getAttribute('aria-selected')).toBe('true')++ const backdrop = globalThis.document.querySelector<HTMLElement>('[data-narrow-overlay-backdrop]')!+ expect(backdrop).not.toBeNull()+ fireEvent.pointerDown(backdrop, { pointerId: 1, button: 0, clientX: 300, clientY: 200 })+ fireEvent.pointerCancel(backdrop, { pointerId: 1 })+ fireEvent.pointerUp(backdrop, { pointerId: 1, button: 0, clientX: 300, clientY: 200 })+ expect(overlayTab('bots')).not.toBeNull()++ fireEvent.pointerDown(backdrop, { pointerId: 2, button: 0, clientX: 300, clientY: 200 })+ fireEvent.pointerUp(backdrop, { pointerId: 2, button: 0, clientX: 300, clientY: 200 })+ expect(globalThis.document.querySelector('[data-narrow-overlay]')).toBeNull()+ expect($narrowOverlayPaneIds.get().size).toBe(0)+ })++ it('closes the visible zone mate through the sessions sidebar alias', () => {+ const { queryByTestId } = render(<NarrowOverlays />)+ revealPane('bots')+ expect(queryByTestId('bots-body')).toBeTruthy()+ act(() =>+ window.dispatchEvent(new CustomEvent(PANE_TOGGLE_REVEAL_EVENT, { detail: { id: 'chat-sidebar', mode: 'close' } }))+ )+ expect(queryByTestId('bots-body')).toBeNull()+ expect($narrowOverlayPaneIds.get().size).toBe(0)+ })+ it('publishes visible zone mates and clears them when Escape closes the overlay', () => {+ const view = render(<NarrowOverlays />)+ expect($narrowOverlayPaneIds.get().size).toBe(0)+ revealPane('sessions')+ expect([...$narrowOverlayPaneIds.get()]).toEqual(expect.arrayContaining(['sessions', 'bots', 'chat-sidebar']))+ fireEvent.keyDown(window, { key: 'Escape' })+ expect($narrowOverlayPaneIds.get().size).toBe(0)+ revealPane('bots')+ view.unmount()+ expect($narrowOverlayPaneIds.get().size).toBe(0)+ })++ it('reserves the browser touch titlebar above overlay tabs', () => {+ window.document.documentElement.dataset.hermesDesktopHost = 'browser'++ const overlayInset = (touch: boolean) => {+ vi.stubGlobal(+ 'matchMedia',+ vi.fn().mockReturnValue({ matches: touch, addEventListener: vi.fn(), removeEventListener: vi.fn() })+ )+ const { container, unmount } = render(<NarrowOverlays />)+ revealPane('sessions')+ const inset = parseFloat(container.querySelector<HTMLElement>('[data-narrow-overlay]')!.style.paddingTop)+ unmount()++ return inset+ }++ // The touch titlebar is taller than the pointer one; the tabs clear it.+ expect(overlayInset(true)).toBeGreaterThan(overlayInset(false))+ })it('mirrors the zone tab strip so every stacked collapsible stays reachable', () => {const { getByTestId, queryByTestId } = render(<NarrowOverlays />)diff --git a/apps/desktop/src/components/pane-shell/tree/renderer/narrow-overlays.tsx b/apps/desktop/src/components/pane-shell/tree/renderer/narrow-overlays.tsxindex df98f5e9c41..db284cab942 100644--- a/apps/desktop/src/components/pane-shell/tree/renderer/narrow-overlays.tsx+++ b/apps/desktop/src/components/pane-shell/tree/renderer/narrow-overlays.tsx@@ -9,17 +9,20 @@import { useStore } from '@nanostores/react'import { type MouseEventHandler, useCallback, useEffect, useMemo, useRef, useState } from 'react'+import { useTitlebarHeight } from '@/app/shell/use-touch-titlebar'import { PaneTab, PaneTabLabel, PaneTabStrip } from '@/components/ui/pane-tab'import { ContribBoundary, ContribRender } from '@/contrib/react/boundary'import { useContributions } from '@/contrib/react/use-contributions'import type { Contribution } from '@/contrib/types'import { ESCAPE_PRIORITY, isTopEscapeLayer, pushEscapeLayer } from '@/lib/escape-layers'+import { isBrowserHostedDesktop } from '@/lib/platform'import { cn } from '@/lib/utils'import { $chatOnboardingSolo } from '@/store/onboarding-intro'import { $paneStates } from '@/store/panes'import { PANE_TOGGLE_REVEAL_EVENT } from '../..'import { useWindowControlsOverlap } from '../../geometry'+import { $narrowOverlayPaneIds } from '../../narrow-overlay-state'import { NO_PANE_GROUP } from '../../pane-visibility'import { allPaneIds, findGroupOfPane, type LayoutNode } from '../model'import { $hiddenTreePanes, $layoutTree, $narrowViewport } from '../store'@@ -46,6 +49,7 @@ export function narrowOverlayWidth(ctx: TrackContext, tree: LayoutNode | null, r}export function NarrowOverlays() {+ const titlebarHeight = useTitlebarHeight()const narrow = useStore($narrowViewport)const solo = useStore($chatOnboardingSolo)const tree = useStore($layoutTree)@@ -61,6 +65,7 @@ export function NarrowOverlays() {// the same way a docked zone does (TreeGroup's wcOverlap -> paddingTop plus// an absolute drag-region spacer so the band stays a window-drag target).const overlayRef = useRef<HTMLDivElement>(null)+ const outsidePress = useRef<{ id: number; x: number; y: number } | null>(null)const wcOverlap = useWindowControlsOverlap(overlayRef, reveal !== null)const onMouseLeave = useCallback<MouseEventHandler<HTMLDivElement>>(event => {@@ -92,6 +97,15 @@ export function NarrowOverlays() {const collapsiblesRef = useRef(collapsibles)collapsiblesRef.current = collapsibles+ useEffect(() => {+ const active = narrow && !solo && reveal ? collapsibles.find(p => p.id === reveal.id) : undefined+ const zone = active && tree ? findGroupOfPane(tree, active.id) : null+ const visible = active ? collapsibles.filter(p => (zone ? zone.panes.includes(p.id) : p.id === active.id)) : []+ $narrowOverlayPaneIds.set(new Set(visible.flatMap(p => [p.id, ...(paneChrome(p).revealAliases ?? [])])))++ return () => $narrowOverlayPaneIds.set(new Set())+ }, [narrow, solo, reveal, collapsibles, tree])+// ⌘B / ⌘G's narrow branch dispatches the app's toggle-reveal event with the// REAL pane id — accept those via each contribution's revealAliases.useEffect(() => {@@ -124,7 +138,10 @@ export function NarrowOverlays() {}if (mode === 'close') {- return current?.id === match.id ? null : current+ const currentTree = $layoutTree.get()+ const targetZone = currentTree ? findGroupOfPane(currentTree, match.id) : null++ return current && (current.id === match.id || targetZone?.panes.includes(current.id)) ? null : current}return current?.id === match.id && current.pinned ? null : { id: match.id, pinned: true }@@ -187,6 +204,42 @@ export function NarrowOverlays() {return (<>+ {revealed && (+ <div+ aria-hidden="true"+ className="absolute inset-0 z-30"+ data-narrow-overlay-backdrop=""+ onPointerCancel={() => {+ outsidePress.current = null+ }}+ onPointerDown={event => {+ if (event.button === 0 && isTopEscapeLayer(ESCAPE_PRIORITY.narrowOverlay)) {+ // Dismissal must not focus the transcript or input underneath.+ event.preventDefault()+ outsidePress.current = { id: event.pointerId, x: event.clientX, y: event.clientY }+ }+ }}+ onPointerLeave={() => {+ outsidePress.current = null+ }}+ onPointerMove={event => {+ const press = outsidePress.current++ if (press && Math.hypot(event.clientX - press.x, event.clientY - press.y) > 8) {+ outsidePress.current = null+ }+ }}+ onPointerUp={event => {+ const press = outsidePress.current+ outsidePress.current = null++ if (press?.id === event.pointerId && isTopEscapeLayer(ESCAPE_PRIORITY.narrowOverlay)) {+ event.preventDefault()+ setReveal(null)+ }+ }}+ />+ )}{/* Hover-intent strips on each edge that has a collapsed pane. */}{sides.map(side => (<div@@ -223,7 +276,11 @@ export function NarrowOverlays() {// (macOS traffic lights); the spacer above keeps that band// draggable, mirroring TreeGroup's reservation.style={{- paddingTop: wcOverlap ? wcOverlap.y + wcOverlap.height : undefined,+ paddingTop: isBrowserHostedDesktop()+ ? titlebarHeight+ : wcOverlap+ ? wcOverlap.y + wcOverlap.height+ : undefined,width: `min(${overlayWidth}, 85vw)`}}>diff --git a/apps/desktop/src/components/pane-shell/tree/renderer/tree-group.test.tsx b/apps/desktop/src/components/pane-shell/tree/renderer/tree-group.test.tsxindex 6569e362f14..def5ce9a3c0 100644--- a/apps/desktop/src/components/pane-shell/tree/renderer/tree-group.test.tsx+++ b/apps/desktop/src/components/pane-shell/tree/renderer/tree-group.test.tsx@@ -58,6 +58,8 @@ afterEach(() => {container = nulldisposePane = nullglobalThis.document.querySelectorAll('[data-titlebar-cluster]').forEach(element => element.remove())+ delete globalThis.document.documentElement.dataset.hermesDesktopHost+ vi.useRealTimers()vi.restoreAllMocks()vi.unstubAllGlobals()})@@ -362,4 +364,46 @@ describe('TreeGroup', () => {expect(screen.getByRole('menuitem', { name: /settings/i })).toBeTruthy()expect(screen.getByRole('menuitem', { name: /update/i })).toBeTruthy()})++ // iOS Safari sends no contextmenu for a touch hold on text; Radix opens the+ // body menu from its own pointer timer, over the native selection callout.+ it('leaves a browser touch hold on message text to the browser, but not on pane chrome', () => {+ vi.useFakeTimers()+ disposePane = registry.register({+ area: 'panes',+ data: { height: '12rem' },+ id: 'terminal',+ render: () => (+ <div>+ <span>Pane chrome</span>+ <div data-slot="aui_assistant-message-content">+ <p>Reply text</p>+ </div>+ </div>+ ),+ title: 'Terminal'+ })+ vi.stubGlobal('CSS', { escape: (value: string) => value })+ vi.stubGlobal(+ 'matchMedia',+ vi.fn().mockReturnValue({ addEventListener: vi.fn(), matches: true, removeEventListener: vi.fn() })+ )+ stubMenuDomApis()+ globalThis.document.documentElement.dataset.hermesDesktopHost = 'browser'++ render(<TreeGroup node={terminalGroup(false)} parentAxis="column" />)++ const hold = (target: Element) =>+ act(() => {+ fireEvent.pointerDown(target, { button: 0, pointerType: 'touch' })+ vi.advanceTimersByTime(800)+ fireEvent.pointerUp(target, { button: 0, pointerType: 'touch' })+ })++ hold(screen.getByText('Reply text'))+ expect(screen.queryByRole('menu')).toBeNull()++ hold(screen.getByText('Pane chrome'))+ expect(screen.getAllByRole('menuitem', { name: /close/i }).length).toBeGreaterThan(0)+ })})diff --git a/apps/desktop/src/components/pane-shell/tree/renderer/tree-group.tsx b/apps/desktop/src/components/pane-shell/tree/renderer/tree-group.tsxindex e874ed66abb..e87cb6f14cc 100644--- a/apps/desktop/src/components/pane-shell/tree/renderer/tree-group.tsx+++ b/apps/desktop/src/components/pane-shell/tree/renderer/tree-group.tsx@@ -10,10 +10,20 @@*/import { useStore } from '@nanostores/react'-import { type CSSProperties, Fragment, type ReactNode, type RefObject, useEffect, useRef, useState } from 'react'+import {+ type ComponentProps,+ type CSSProperties,+ Fragment,+ type ReactNode,+ type PointerEvent as ReactPointerEvent,+ type RefObject,+ useEffect,+ useRef,+ useState+} from 'react'import { ShellMenuItems } from '@/app/context-menu/shell-menu-items'-import { TITLEBAR_DRAG_HANDLE_WIDTH, TITLEBAR_HEIGHT } from '@/app/shell/titlebar'+import { TITLEBAR_DRAG_HANDLE_WIDTH } from '@/app/shell/titlebar'import { ActionsContextMenu, type MenuKit, renderActionItem } from '@/components/ui/actions-menu'import { Codicon } from '@/components/ui/codicon'import { DecodeText } from '@/components/ui/decode-text'@@ -31,6 +41,7 @@ import { ContribBoundary, ContribRender } from '@/contrib/react/boundary'import { useContributions } from '@/contrib/react/use-contributions'import { useI18n } from '@/i18n'import { useKeybindHint } from '@/lib/keybinds/use-keybind-hint'+import { isBrowserOwnedTouch } from '@/lib/touch-interaction'import { cn } from '@/lib/utils'import { closeAllOpenSessionTiles, setZoneParkedTiles } from '@/store/session-states'@@ -84,6 +95,7 @@ import {toggleTabSelected} from '../tab-selection'+import { CompactTabPicker } from './compact-tab-picker'import { startPaneDrag } from './drag-session'import { KeepAlivePaneSlot, useStablePaneHosts } from './keep-alive-panes'import { PaneBody } from './pane-body'@@ -91,6 +103,7 @@ import { usePanelTitlebar } from './panel-titlebar'import { tabStripVisibleForZone } from './strip-visibility'import { useActiveTabVisible } from './tab-strip-scroll'import { paneChrome } from './track-model'+import { useZoneHeaderLayout } from './zone-header-layout'/** Right-click zone menu: the tab verbs (close this / others / to the right /* all) plus the strip's own chrome toggles. Same items and icons as a session@@ -98,6 +111,7 @@ import { paneChrome } from './track-model'* a pane with no domain menu of its own (the file tree, a terminal, the main* tab on a fresh draft) falls through to this one. */function ZoneMenu({+ allowOpen,children,closable,includeAppActions = false,@@ -109,6 +123,7 @@ function ZoneMenu({tabMenuPrefix,targetPane}: {+ allowOpen?: () => booleanchildren: ReactNodeincludeAppActions?: boolean/** The pane the menu closes (the right-clicked chip / the active pane);@@ -232,12 +247,114 @@ function ZoneMenu({// `w-40` clips the spelled-out chord (`Ctrl+Alt+T`) under the menu's// overflow-x-hidden. Size to the row; `min-w-40` keeps the short rows.return (- <ActionsContextMenu contentClassName="w-max min-w-40" items={items}>+ <ActionsContextMenu allowOpen={allowOpen} contentClassName="w-max min-w-40" items={items}>{children}</ActionsContextMenu>)}+type ZoneMenuProps = ComponentProps<typeof ZoneMenu>++interface ZoneBodyMenuProps extends Omit<ZoneMenuProps, 'allowOpen' | 'includeAppActions'> {+ label: string+}++/** The body's zone menu, app actions included. A touch hold on message text,+ * an editable, a link or media keeps the browser's selection/paste callout;+ * the hold opens this menu only on plain pane chrome. */+function ZoneBodyMenu({ children, label, ...menu }: ZoneBodyMenuProps) {+ // Whether the touch now down landed on browser-owned body content.+ const touchOwnedByBrowser = useRef(false)++ return (+ <ZoneMenu {...menu} allowOpen={() => !touchOwnedByBrowser.current} includeAppActions>+ <div+ aria-label={label}+ data-zone-body={menu.nodeId}+ onPointerCancel={() => void (touchOwnedByBrowser.current = false)}+ onPointerDown={event => void (touchOwnedByBrowser.current = isBrowserOwnedTouch(event.nativeEvent))}+ onPointerUp={() => void (touchOwnedByBrowser.current = false)}+ style={{ display: 'contents' }}+ >+ {children}+ </div>+ </ZoneMenu>+ )+}++interface EditVeilProps extends Omit<ZoneMenuProps, 'children'> {+ label: string+ onPointerDown: (event: ReactPointerEvent<HTMLDivElement>) => void+ /** Where the zone's header ends. */+ top: number+}++/** The edit-mode drag veil over a zone's body, carrying the zone menu. */+function EditVeil({ label, onPointerDown, top, ...menu }: EditVeilProps) {+ return (+ <ZoneMenu {...menu}>+ <div+ // z-50: pane CONTENT may carry its own stacked chrome (the+ // terminal rail is z-40) — the edit veil must cover all of it.+ // The scrim mixes the accent over the CHROME BG (not transparent)+ // so it properly dims content in dark themes instead of leaving a+ // barely-tinted wash; the light blur reads as "edit mode" the same+ // way the zone editor's backdrop does.+ className="absolute inset-x-0 bottom-0 z-50 flex cursor-grab items-center justify-center outline-1 -outline-offset-2 outline-dashed backdrop-blur-[2px]"+ onPointerDown={onPointerDown}+ style={{+ top,+ background:+ 'color-mix(in srgb, var(--ui-accent) 6%, color-mix(in srgb, var(--ui-bg-chrome) 55%, transparent))',+ outlineColor: 'color-mix(in srgb, var(--ui-accent) 55%, transparent)'+ }}+ >+ <span className="flex max-w-[calc(100%-1rem)] items-center gap-1.5 rounded-md border border-(--ui-stroke-secondary) bg-popover px-2 py-1 text-[0.64rem] font-semibold uppercase tracking-[0.16em] text-(--ui-text-secondary)">+ <Codicon className="shrink-0" name="gripper" size="0.8125rem" />+ <span className="min-w-0 truncate">{label}</span>+ </span>+ </div>+ </ZoneMenu>+ )+}++type CompactTabPickerProps = ComponentProps<typeof CompactTabPicker>++interface CompactZoneTabsProps extends Pick<CompactTabPickerProps, 'activeId' | 'newTab' | 'tabs'> {+ belowControls: boolean+ /** The active tab takes Close (see TreeGroup's `closeableTab`). */+ closeable: boolean+ node: GroupNode+}++/** A narrow touch zone's tab row: the picker in place of the scrolling strip.+ * Picking a tab is a strip tap, so a minimized zone restores first. */+function CompactZoneTabs({ activeId, belowControls, closeable, newTab, node, tabs }: CompactZoneTabsProps) {+ return (+ <div+ className={cn('flex min-w-0 flex-1', belowControls && 'absolute inset-x-0 bottom-0')}+ data-zone-tabstrip={node.id}+ onPointerDownCapture={() => noteActiveTreeGroup(node.id)}+ >+ <CompactTabPicker+ activeId={activeId}+ newTab={node.minimized ? null : newTab}+ onClose={closeable ? () => closeTabPane(activeId) : undefined}+ onSelect={paneId => {+ clearTabSelection()++ if (node.minimized) {+ restoreTreePane(paneId)+ }++ activateTreePane(node.id, paneId)+ }}+ tabs={tabs}+ />+ </div>+ )+}+export function TreeGroup({node,parentAxis,@@ -309,8 +426,15 @@ export function TreeGroup({const active = paneFor(activeId)const isEmpty = shown.length === 0const sidebarGroup = !node.panes.some(id => id === 'workspace' || paneChrome(paneFor(id)).placement === 'main')- const tabsBelowControls = topEdge && (sidebarGroup || measuredBelowControls)- const tabsInTitlebar = topEdge && !tabsBelowControls++ const { compactTabs, tabStripHeight, tabsBelowControls, tabsInTitlebar, titlebarHeight } = useZoneHeaderLayout({+ measuredBelowControls,+ narrow,+ shown,+ sidebarGroup,+ topEdge+ })+const pageHeader = paneChrome(active).headerContent// What the strip's "+" makes. The pane you are LOOKING AT answers first (a@@ -409,11 +533,13 @@ export function TreeGroup({const headerVisible =!isEmpty && !verticalCollapse && (Boolean(node.minimized) || stripVisible || Boolean(pageHeader))+ const topHeaderHeight = titlebarHeight + (tabsBelowControls && headerVisible ? tabStripHeight : 0)+// Keep the activated tab — and, on the last one, the trailing "+" — inside// the strip's scroll window. Opening a tab past the right edge otherwise// left both the new tab and the button that made it out of view.useActiveTabVisible(tabsRef, activeId, {- enabled: headerVisible,+ enabled: headerVisible && !compactTabs,last: shown[shown.length - 1] === activeId,tabCount: shown.length})@@ -501,7 +627,7 @@ export function TreeGroup({wcOverlap? { paddingTop: wcOverlap.y + wcOverlap.height }: topEdge && verticalCollapse- ? { paddingTop: TITLEBAR_HEIGHT }+ ? { paddingTop: titlebarHeight }: undefined}>@@ -565,7 +691,7 @@ export function TreeGroup({<divclassName="relative flex min-w-0 shrink-0 bg-(--ui-sidebar-surface-background)"data-panel-header=""- style={topEdge ? { height: TITLEBAR_HEIGHT + (tabsBelowControls && headerVisible ? 28 : 0) } : undefined}+ style={topEdge ? { height: topHeaderHeight } : undefined}>{topEdge && (<div aria-hidden="true" className="shrink-0" style={{ width: 'var(--panel-titlebar-left, 100%)' }} />@@ -580,6 +706,15 @@ export function TreeGroup({><PaneTab active>{pageHeader()}</PaneTab></div>+ ) : headerVisible && compactTabs ? (+ <CompactZoneTabs+ activeId={activeId}+ belowControls={tabsBelowControls}+ closeable={closeableTab(activeId)}+ newTab={newTab}+ node={node}+ tabs={shown.map(id => ({ id, label: tabLabel(id), title: tabText(id) }))}+ />) : headerVisible ? (<ZoneMenu {...zoneMenu}><PaneTabStrip@@ -773,7 +908,7 @@ export function TreeGroup({)}data-window-drag-handle=""style={{- height: TITLEBAR_HEIGHT,+ height: titlebarHeight,width: headerVisible && tabsInTitlebar ? TITLEBAR_DRAG_HANDLE_WIDTH : undefined}}/>@@ -799,15 +934,9 @@ export function TreeGroup({wrap={!isEmpty? body => (- <ZoneMenu {...zoneMenu} includeAppActions>- <div- aria-label={t.zones.zoneMenuLabel(String(tabLabel(activeId)))}- data-zone-body={node.id}- style={{ display: 'contents' }}- >- {body}- </div>- </ZoneMenu>+ <ZoneBodyMenu {...zoneMenu} label={t.zones.zoneMenuLabel(String(tabLabel(activeId)))}>+ {body}+ </ZoneBodyMenu>): undefined}@@ -879,29 +1008,12 @@ export function TreeGroup({starts below the header so tabs/headers stay directly interactive(drag any tab, right-click for the zone menu). */}{editMode && !dragging && !isEmpty && !node.minimized && (- <ZoneMenu {...zoneMenu}>- <div- // z-50: pane CONTENT may carry its own stacked chrome (the- // terminal rail is z-40) — the edit veil must cover all of it.- // The scrim mixes the accent over the CHROME BG (not transparent)- // so it properly dims content in dark themes instead of leaving a- // barely-tinted wash; the light blur reads as "edit mode" the same- // way the zone editor's backdrop does.- className="absolute inset-x-0 bottom-0 z-50 flex cursor-grab items-center justify-center outline-1 -outline-offset-2 outline-dashed backdrop-blur-[2px]"- onPointerDown={e => startPaneDrag(activeId, e, undefined, undefined, tabText(activeId))}- style={{- top: topEdge ? TITLEBAR_HEIGHT + (tabsBelowControls && headerVisible ? 28 : 0) : headerVisible ? 28 : 0,- background:- 'color-mix(in srgb, var(--ui-accent) 6%, color-mix(in srgb, var(--ui-bg-chrome) 55%, transparent))',- outlineColor: 'color-mix(in srgb, var(--ui-accent) 55%, transparent)'- }}- >- <span className="flex max-w-[calc(100%-1rem)] items-center gap-1.5 rounded-md border border-(--ui-stroke-secondary) bg-popover px-2 py-1 text-[0.64rem] font-semibold uppercase tracking-[0.16em] text-(--ui-text-secondary)">- <Codicon className="shrink-0" name="gripper" size="0.8125rem" />- <span className="min-w-0 truncate">{tabText(activeId)}</span>- </span>- </div>- </ZoneMenu>+ <EditVeil+ {...zoneMenu}+ label={tabText(activeId)}+ onPointerDown={e => startPaneDrag(activeId, e, undefined, undefined, tabText(activeId))}+ top={topEdge ? topHeaderHeight : headerVisible ? tabStripHeight : 0}+ />)}{/* FancyZones drop overlay — its own component so the per-frame dropdiff --git a/apps/desktop/src/components/pane-shell/tree/renderer/zone-header-layout.ts b/apps/desktop/src/components/pane-shell/tree/renderer/zone-header-layout.tsnew file mode 100644index 00000000000..c73e042c4f7--- /dev/null+++ b/apps/desktop/src/components/pane-shell/tree/renderer/zone-header-layout.ts@@ -0,0 +1,54 @@+import { TITLEBAR_HEIGHT, TOUCH_TITLEBAR_HEIGHT } from '@/app/shell/titlebar'+import { useTouchTitlebar } from '@/app/shell/use-touch-titlebar'++import { isSessionStripPane } from '../store'++/** The desktop tab strip's row (`h-7`). */+const TAB_STRIP_HEIGHT = 28++interface ZoneHeaderLayoutInput {+ /** The titlebar measured too little room beside its controls for the tabs. */+ measuredBelowControls: boolean+ narrow: boolean+ shown: readonly string[]+ /** No workspace or main pane in the zone. */+ sidebarGroup: boolean+ topEdge: boolean+}++export interface ZoneHeaderLayout {+ /** A narrow touch zone holding session tabs swaps the scrolling strip for+ * the compact picker. */+ compactTabs: boolean+ tabStripHeight: number+ /** A top-edge zone's tabs take their own row under the window controls. */+ tabsBelowControls: boolean+ /** A top-edge zone's tabs share the titlebar band with the controls. */+ tabsInTitlebar: boolean+ titlebarHeight: number+}++/** Where a zone's tabs sit relative to the window titlebar, and how tall the+ * titlebar band and the tab row are. */+export function useZoneHeaderLayout({+ measuredBelowControls,+ narrow,+ shown,+ sidebarGroup,+ topEdge+}: ZoneHeaderLayoutInput): ZoneHeaderLayout {+ const touchTitlebar = useTouchTitlebar()+ const compactTabs = touchTitlebar && narrow && shown.some(isSessionStripPane)+ // The compact picker needs a full touch row: the titlebar's fit threshold+ // also has to accommodate the drag handle and the separate new-tab target.+ const tabsBelowControls = topEdge && (compactTabs || sidebarGroup || measuredBelowControls)++ return {+ compactTabs,+ // The compact tab row is a touch target the same height as the touch band.+ tabStripHeight: compactTabs ? TOUCH_TITLEBAR_HEIGHT : TAB_STRIP_HEIGHT,+ tabsBelowControls,+ tabsInTitlebar: topEdge && !tabsBelowControls,+ titlebarHeight: touchTitlebar ? TOUCH_TITLEBAR_HEIGHT : TITLEBAR_HEIGHT+ }+}diff --git a/apps/desktop/src/components/pane-shell/tree/side-collapse-persistence.test.ts b/apps/desktop/src/components/pane-shell/tree/side-collapse-persistence.test.tsnew file mode 100644index 00000000000..e0b104673d1--- /dev/null+++ b/apps/desktop/src/components/pane-shell/tree/side-collapse-persistence.test.ts@@ -0,0 +1,193 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'++import { LAYOUT_KEYS } from '@/lib/layout-persistence'++/** Re-import real stores over the same storage, as a page refresh does. The+ * workspace is available; Files keeps its own toggle, independent of its side. */+async function boot() {+ vi.resetModules()+ const tree = await import('./store')+ const model = await import('./model')+ const layout = await import('@/store/layout')+ const terminal = await import('@/app/right-sidebar/store')+ const { registry } = await import('@/contrib/registry')+ const { DEFAULT_TREE } = await import('@/app/contrib/layout-presets')++ for (const [id, placement] of [+ ['sessions', 'left'],+ ['workspace', 'main'],+ ['files', 'right'],+ ['review', 'right'],+ ['terminal', 'bottom']+ ]) {+ registry.register({ id, area: 'panes', title: id, data: { placement }, render: () => null })+ }++ tree.declareDefaultTree(DEFAULT_TREE)+ tree.bindTreeSideVisibility('left', layout.$sidebarOpen, layout.setSidebarOpen)+ tree.bindTreeSideVisibility('right', layout.$fileBrowserOpen, layout.setFileBrowserOpen)+ tree.bindPaneVisibility(+ 'files',+ layout.$fileBrowserOpen,+ () => layout.setFileBrowserOpen(false),+ () => layout.setFileBrowserOpen(true)+ )+ tree.bindToolPaneCollapse(+ 'terminal',+ terminal.$terminalTakeover,+ () => terminal.setTerminalTakeover(false),+ () => terminal.setTerminalTakeover(true)+ )++ return { tree, model, layout, terminal }+}++describe('side visibility survives a page refresh independently of Files', () => {+ beforeEach(() => {+ window.localStorage.clear()+ window.history.replaceState(null, '', '/')+ vi.resetModules()+ })++ // Each simulated refresh re-imports the stores cold (vi.resetModules): about 5 s alone, more under a full run.+ it('restores the last presentation without revealing hidden, minimized or inactive panes', async () => {+ let state = await boot()+ // An old installation without a side record still uses its chrome default.+ expect(state.tree.$collapsedTreeSides.get().has('right')).toBe(true)+ state.tree.togglePaneVisible('terminal')++ async function refresh(expectSameTree = true) {+ const before = structuredClone(state.tree.$layoutTree.get())+ state.tree.persistTree()+ state = await boot()++ if (expectSameTree) {+ expect(state.tree.$layoutTree.get()).toEqual(before)+ }++ expect(state.layout.$fileBrowserOpen.get()).toBe(false)+ expect(state.tree.$hiddenTreePanes.get().has('files')).toBe(true)+ }++ expect(state.terminal.$terminalTakeover.get()).toBe(true)+ expect(state.tree.$collapsedTreeSides.get().has('right')).toBe(false)+ await refresh()+ // Regression: boot used Files=false to hide the whole right column, even+ // though both the open terminal flag and its complete tree survived.+ expect(state.tree.$collapsedTreeSides.get().has('right')).toBe(false)+ expect(state.tree.isPaneVisible('terminal')).toBe(true)++ state.tree.setTreeGroupMinimized('grp-terminal', true)+ await refresh()+ expect(state.terminal.$terminalTakeover.get()).toBe(true)+ expect(state.tree.isPaneVisible('terminal')).toBe(false)+ expect(state.tree.$collapsedTreeSides.get().has('right')).toBe(false)++ state.tree.restoreTreePane('terminal')+ state.tree.moveTreePane('review', { groupId: 'grp-terminal', pos: 'center' })+ state.tree.activateTreePane('grp-terminal', 'review')+ await refresh()+ expect(state.terminal.$terminalTakeover.get()).toBe(true)+ expect(state.tree.isPaneVisible('review')).toBe(true)+ expect(state.tree.isPaneVisible('terminal')).toBe(false)++ // Explicit side hide wins even while an open terminal owns the active tab.+ state.tree.restoreTreePane('terminal')+ state.layout.setFileBrowserOpen(false)+ await refresh()+ expect(state.tree.$collapsedTreeSides.get().has('right')).toBe(true)+ expect(state.terminal.$terminalTakeover.get()).toBe(true)+ expect(state.tree.isPaneVisible('terminal')).toBe(false)++ state.tree.togglePaneVisible('terminal')+ expect(state.tree.isPaneVisible('terminal')).toBe(true)+ state.tree.closeToolPane('terminal')+ // Default declaration can re-adopt the id, but its dismissal must remain.+ await refresh(false)+ expect(state.tree.$dismissedPanes.get().has('terminal')).toBe(true)+ expect(state.terminal.$terminalTakeover.get()).toBe(false)+ expect(state.tree.isPaneVisible('terminal')).toBe(false)++ // Pop-outs share localStorage, but must not inherit or overwrite the+ // primary layout's sides. Keep the Files default opposite the saved side.+ state.tree.setTreeSideCollapsed('right', false)+ state.tree.setTreeSideCollapsed('left', true)+ const sidesKey = LAYOUT_KEYS.collapsed+ const savedSides = window.localStorage.getItem(sidesKey)++ for (const win of ['secondary', 'browser']) {+ window.history.replaceState(null, '', `/?win=${win}`)+ const auxiliary = await boot()+ expect(auxiliary.tree.$collapsedTreeSides.get().has('right')).toBe(true)+ expect(auxiliary.tree.$collapsedTreeSides.get().has('left')).toBe(false)+ auxiliary.tree.setTreeSideCollapsed('right', true)+ auxiliary.tree.setTreeSideCollapsed('left', false)+ expect(window.localStorage.getItem(sidesKey)).toBe(savedSides)+ }++ window.history.replaceState(null, '', '/')+ state = await boot()+ expect(state.tree.$collapsedTreeSides.get().has('right')).toBe(false)+ expect(state.tree.$collapsedTreeSides.get().has('left')).toBe(true)++ // Invalid storage falls back to this mode's chrome defaults.+ const malformed = JSON.stringify(['left', 'invalid-side'])+ window.localStorage.setItem(sidesKey, malformed)+ state = await boot()+ expect(state.tree.$collapsedTreeSides.get().has('left')).toBe(false)+ expect(state.tree.$collapsedTreeSides.get().has('right')).toBe(true)+ }, 30_000)++ it('toggles an ancestor-hidden pane on the first press and keeps unrelated zones visible', async () => {+ const { tree, model, layout, terminal } = await boot()+ tree.togglePaneVisible('terminal')+ const $visible = tree.$paneVisible('terminal')+ const changes: boolean[] = []+ const unlisten = $visible.subscribe(value => changes.push(value))++ try {+ expect($visible.get()).toBe(true)+ layout.setFileBrowserOpen(false)+ expect(terminal.$terminalTakeover.get()).toBe(true)+ expect(tree.isPaneVisible('terminal')).toBe(false)+ expect($visible.get()).toBe(false)+ expect(changes).toEqual([true, false])+ expect(tree.isPaneVisible('workspace')).toBe(true)+ expect(tree.isPaneVisible('sessions')).toBe(true)++ tree.togglePaneVisible('terminal')+ expect(tree.isPaneVisible('terminal')).toBe(true)+ expect($visible.get()).toBe(true)+ expect(layout.$fileBrowserOpen.get()).toBe(false)+ tree.togglePaneVisible('terminal')+ expect(tree.isPaneVisible('terminal')).toBe(false)+ expect(terminal.$terminalTakeover.get()).toBe(false)++ // The same predicate follows physical position after a layout flip.+ tree.restoreTreePane('terminal')+ tree.mirrorLayoutTree()+ layout.setSidebarOpen(false)+ expect(tree.treeSideOfPane('terminal')).toBe('left')+ expect(tree.isPaneVisible('terminal')).toBe(false)+ tree.togglePaneVisible('terminal')+ expect(tree.isPaneVisible('terminal')).toBe(true)+ expect(layout.$sidebarOpen.get()).toBe(false)++ // A terminal below the root row is not owned by either sidebar.+ tree.applyTree(+ model.split('column', [+ model.split('row', [model.group(['sessions']), model.group(['workspace']), model.group(['files', 'review'])]),+ model.group(['terminal'])+ ]),+ 'terminal-deck'+ )+ layout.setFileBrowserOpen(false)+ layout.setSidebarOpen(false)+ expect(tree.treeSideOfPane('terminal')).toBeNull()+ expect(tree.isPaneVisible('terminal')).toBe(true)+ expect(tree.isPaneVisible('workspace')).toBe(true)+ } finally {+ unlisten()+ }+ })+})diff --git a/apps/desktop/src/components/pane-shell/tree/store.ts b/apps/desktop/src/components/pane-shell/tree/store.tsindex d838c96cb81..3ed5e4815cc 100644--- a/apps/desktop/src/components/pane-shell/tree/store.ts+++ b/apps/desktop/src/components/pane-shell/tree/store.ts@@ -1076,11 +1076,9 @@ export const $collapsedTreeSides = modeLayout.atom<ReadonlySet<TreeSide>>(LAYOUT})const hasPersistedSides = modeLayout.has(LAYOUT_KEYS.collapsed)-// Side visibility is DERIVED from an app store (the binding owns persistence-// + button state). Reveals un-collapse the column directly instead of writing-// back through the setter — the right side's store IS the file tree's toggle,-// so a neighbour's reveal must not press it. Layout reset still reopens every-// side through its setter, because there the toggles SHOULD move.+// Side visibility persists separately from the bound pane's toggle: revealing+// a neighbour opens the column without opening Files. Chrome changes still+// drive the side; layout reset reopens through the setter too.const sideOpeners: Partial<Record<TreeSide, (open: boolean) => void>> = {}const sideVisibility: Partial<Record<TreeSide, () => boolean>> = {}@@ -1199,7 +1197,7 @@ function restoreDismissedSidePanes(side: TreeSide) {}}-/** Bind a side's visibility to an app store (mirror of bindPaneVisibility). */+/** Restore the side quietly; only later chrome changes are reveal/hide intent. */export function bindTreeSideVisibility(side: TreeSide,$open: { get(): boolean; listen(fn: (open: boolean) => void): void },@@ -1972,7 +1970,7 @@ export function restoreTreePane(paneId: string) {revealTreePane(paneId)}-/** Is a pane actually ON SCREEN? In the tree, not dismissed, not chrome+/** Is a pane actually ON SCREEN? In the tree, not dismissed, not chrome/side* hidden, its zone un-minimized, and holding its stack's active slot.* True for every pane class — tool panels and hide-style panes alike. */export function isPaneVisible(paneId: string): boolean {@@ -1981,11 +1979,13 @@ export function isPaneVisible(paneId: string): boolean {}const group = paneGroup(paneId)+ const side = treeSideOfPane(paneId)- return Boolean(group && !group.minimized && group.active === paneId)+ return Boolean(group && !group.minimized && group.active === paneId && !(side && $collapsedTreeSides.get().has(side)))}const paneVisibleCache = new Map<string, ReadableAtom<boolean>>()+const paneVisibleStores = [$layoutTree, $dismissedPanes, $hiddenTreePanes, $collapsedTreeSides]/** Reactive `isPaneVisible` for chrome that renders an on/off affordance* (the statusbar's terminal button). Memoized per pane id so `useStore`@@ -1994,7 +1994,7 @@ export function $paneVisible(paneId: string): ReadableAtom<boolean> {let cached = paneVisibleCache.get(paneId)if (!cached) {- cached = computed([$layoutTree, $dismissedPanes, $hiddenTreePanes], () => isPaneVisible(paneId))+ cached = computed(paneVisibleStores, () => isPaneVisible(paneId))paneVisibleCache.set(paneId, cached)}diff --git a/apps/desktop/src/components/ui/actions-menu.tsx b/apps/desktop/src/components/ui/actions-menu.tsxindex 2f02f304869..c334ac693bb 100644--- a/apps/desktop/src/components/ui/actions-menu.tsx+++ b/apps/desktop/src/components/ui/actions-menu.tsx@@ -1,4 +1,5 @@import type * as React from 'react'+import { useState } from 'react'import { Codicon } from '@/components/ui/codicon'import {@@ -160,6 +161,9 @@ interface ActionsContextMenuProps {contentClassName?: string/** Skip the wrapper (render children bare) — e.g. nothing is actionable yet. */disabled?: boolean+ /** Vetoes an open request, e.g. a touch hold the browser owns. Radix opens+ * on a touch hold from pointer timers, with no contextmenu event to stop. */+ allowOpen?: () => booleanonCloseAutoFocus?: (event: Event) => void}@@ -168,6 +172,7 @@ interface ActionsContextMenuProps {* kebab's `items` render function so both surfaces mirror each other.*/export function ActionsContextMenu({+ allowOpen,ariaLabel,children,contentClassName,@@ -175,12 +180,14 @@ export function ActionsContextMenu({items,onCloseAutoFocus}: ActionsContextMenuProps) {+ const [open, setOpen] = useState(false)+if (disabled) {return <>{children}</>}return (- <ContextMenu>+ <ContextMenu onOpenChange={next => setOpen(next && (allowOpen?.() ?? true))} open={open}><ContextMenuTrigger asChild>{children}</ContextMenuTrigger><ContextMenuContent aria-label={ariaLabel} className={contentClassName} onCloseAutoFocus={onCloseAutoFocus}><ActionItems items={items} kit={CONTEXT_KIT} />diff --git a/apps/desktop/src/components/ui/button.tsx b/apps/desktop/src/components/ui/button.tsxindex c786df58be6..281cd4ed0dd 100644--- a/apps/desktop/src/components/ui/button.tsx+++ b/apps/desktop/src/components/ui/button.tsx@@ -48,6 +48,7 @@ const buttonVariants = cva(xs: "gap-1 px-2 py-0.5 text-[0.6875rem] leading-4 has-[>svg]:px-1.5 [&_svg:not([class*='size-'])]:size-3",sm: 'px-2.5 py-1 has-[>svg]:px-2',lg: 'px-5 py-2 text-sm leading-5 has-[>svg]:px-4',+ touch: 'min-h-11 min-w-11 px-3 py-2 text-sm',// Flush inline text action — no box padding/height. Pair with text/link// variants when the button must sit inline in a heading or sentence// (replaces ad-hoc `h-auto px-0 py-0` overrides).diff --git a/apps/desktop/src/components/ui/copy-button.tsx b/apps/desktop/src/components/ui/copy-button.tsxindex cee6edcde88..8f31dbc9532 100644--- a/apps/desktop/src/components/ui/copy-button.tsx+++ b/apps/desktop/src/components/ui/copy-button.tsx@@ -5,6 +5,7 @@ import { ContextMenuItem } from '@/components/ui/context-menu'import { DropdownMenuItem } from '@/components/ui/dropdown-menu'import { Tip } from '@/components/ui/tooltip'import { useI18n } from '@/i18n'+import { writeClipboardText } from '@/lib/clipboard'import { triggerHaptic } from '@/lib/haptics'import { Check, Copy, X } from '@/lib/icons'import { cn } from '@/lib/utils'@@ -14,26 +15,6 @@ type CopyButtonAppearance = 'button' | 'icon' | 'inline' | 'menu-item' | 'contextype CopyStatus = 'copied' | 'error' | 'idle'const COPIED_RESET_MS = 1_500-export async function writeClipboardText(text: string) {- if (!text) {- return- }-- if (window.hermesDesktop?.writeClipboard) {- await window.hermesDesktop.writeClipboard(text)-- return- }-- if (navigator.clipboard?.writeText) {- await navigator.clipboard.writeText(text)-- return- }-- throw new Error('Clipboard API is unavailable')-}-export interface CopyButtonProps {appearance?: CopyButtonAppearancebuttonSize?: React.ComponentProps<typeof Button>['size']diff --git a/apps/desktop/src/global.d.ts b/apps/desktop/src/global.d.tsindex f4a4ff20bb9..6dbbe346151 100644--- a/apps/desktop/src/global.d.ts+++ b/apps/desktop/src/global.d.ts@@ -85,7 +85,7 @@ declare global {) => Promise<{ ok: boolean; error?: string }>// Resume this session in the user's own terminal emulator (`hermes --tui// --resume <id>`) — the external terminal, not the in-app pane.- openSessionInTerminal: (+ openSessionInTerminal?: (sessionId: string,opts?: { cwd?: string; profile?: string }) => Promise<{ ok: boolean; error?: string }>@@ -96,7 +96,7 @@ declare global {// Pop the in-app Browser (webview + address bar) into its own OS window.// `tabId` is the `$previewTabs` id; closing the window fires// `onBrowserPopoutClosed` so the caller can dock the tab again.- openBrowserWindow: (tabId: string) => Promise<{ ok: boolean; error?: string }>+ openBrowserWindow?: (tabId: string) => Promise<{ ok: boolean; error?: string }>// Cross-window renderer relay (pop-out Browser ↔ chat windows). Electron// main relays opaque payloads to the other Hermes renderer windows;// renderer code keeps the destination exact and rejects anything not@@ -105,7 +105,7 @@ declare global {send: (payload: unknown) => voidonMessage: (callback: (payload: unknown) => void) => () => void}- onBrowserPopoutClosed: (callback: (tabId: string) => void) => () => void+ onBrowserPopoutClosed?: (callback: (tabId: string) => void) => () => void// Claim a one-shot cross-window ambient cue (turn-end sound / spoken// reply). Resolves true for the first window to claim a key, false for// peers — so N open windows don't all fire the same cue.@@ -129,7 +129,7 @@ declare global {// The pop-out pet overlay: a transparent always-on-top window hosting only// the mascot. The main renderer drives it (open/close/drag + state push);// the overlay sends control messages back (pop-in, composer submit).- petOverlay: {+ petOverlay?: {open: (request: PetOverlayOpenRequest) => Promise<{ ok: boolean; bounds?: PetOverlayBounds }>close: () => Promise<{ ok: boolean }>setBounds: (bounds: PetOverlayBounds) => void@@ -176,7 +176,7 @@ declare global {// shortcut registration + the persisted preference (it must restore the// shortcut on a cold launch without the renderer visiting Settings), so// the renderer reads/writes it here and adopts the authoritative reply.- quickEntry: {+ quickEntry?: {getSettings: () => Promise<QuickEntryStatus>// Returns the resulting state — including `registered: false` +// `error: 'taken'` when another app already owns the chord, so a failed@@ -216,11 +216,11 @@ declare global {// Opt-in OS-keychain encryption for stored gateway secrets (default// off). `get` never touches the OS keychain; `set` re-encodes stored// secrets and can throw when the keychain is unusable.- getSecretStorageEncryption: () => Promise<{ on: boolean }>- setSecretStorageEncryption: (on: boolean) => Promise<{ on: boolean }>+ getSecretStorageEncryption?: () => Promise<{ on: boolean }>+ setSecretStorageEncryption?: (on: boolean) => Promise<{ on: boolean }>// v2 multi-connection registry: named agent sources, all persisted// together (local + any number of remote/cloud/ssh instances).- connections: {+ connections?: {list: () => Promise<DesktopConnectionsRegistry>save: (payload: DesktopRegistryConnectionInput@@ -337,6 +337,12 @@ declare global {path?: stringsaved: boolean}>+ /** Browser media elements need an authenticated HTTP source, not Electron's custom protocol. */+ getGatewayFileStreamUrl?: (payload: {+ connectionId?: null | string+ path: string+ profile?: null | string+ }) => Promise<string>saveImageFromUrl: (url: string) => Promise<boolean>/** Edit verb against the window's focused element (the custom context* menu's Cut/Copy/Paste/Select all). */@@ -367,6 +373,13 @@ declare global {savePastedText: (text: string) => Promise<string>saveClipboardImage: () => Promise<string>getPathForFile: (file: File) => string+ /** Browser-hosted drag/drop stages File bytes in authenticated,+ * profile-scoped host storage. Native shells already expose real paths. */+ stageFileForAttach?: (file: File) => Promise<string>+ /** Source ownership returned when this browser stages a file on its host. */+ getStagedFileForAttach?: (path: string) => HermesStagedUpload | undefined+ /** Browser-picked display name; never replaces the host path or source identity. */+ getStagedFileDisplayName?: (path: string) => string | undefinednormalizePreviewTarget: (target: string, baseDir?: string) => Promise<HermesPreviewTarget | null>/** Resolves to `HermesReadFileErrorResult` when the watched file was* already gone at call time (a restored tab probing a deleted path) —@@ -583,11 +596,22 @@ declare global {* only; null on Windows or when unavailable). Used to reopen a tab* where the user last `cd`'d. */cwd: (id: string) => Promise<string | null>+ /** Explicit close: terminate the shell, including a disconnected attachment. */dispose: (id: string) => Promise<boolean>- onData: (id: string, callback: (payload: string) => void) => () => void+ /** Browser cleanup releases the viewer without terminating its shell. */+ detach?: (id: string) => Promise<boolean>+ closeSaved?: (restoreKey: string) => Promise<boolean>+ onState?: (id: string, callback: (state: HermesTerminalState) => void) => () => void+ onData: (id: string, callback: (payload: string, options?: { replay: boolean }) => void) => () => voidonExit: (id: string, callback: (payload: HermesTerminalExit) => void) => () => voidresize: (id: string, size: { cols: number; rows: number }) => Promise<boolean>- start: (options?: { cols?: number; cwd?: string; rows?: number }) => Promise<HermesTerminalSession>+ start: (options?: {+ cols?: number+ cwd?: string+ rows?: number+ restoreKey?: string+ resumeOnly?: boolean+ }) => Promise<HermesTerminalSession>write: (id: string, data: string) => Promise<boolean>}reachPreviewUrl?: (url: string) => Promise<string>@@ -708,7 +732,7 @@ declare global {// Main-process `before-input-event` forwards Ctrl/Cmd+F here so the// renderer can still open the FindBar when the OS compositor has// already grabbed the chord (#81727, e.g. Pop!_OS / GNOME).- onOpenFindBarRequested: (callback: () => void) => () => void+ onOpenFindBarRequested?: (callback: () => void) => () => void}}}@@ -746,10 +770,14 @@ export interface DesktopMarketplaceThemeResult {themes: DesktopMarketplaceThemeFile[]}+export type HermesTerminalState = 'open' | 'reconnecting' | 'disconnected'+export interface HermesTerminalSession {cwd: stringid: stringshell: string+ /** Server-owned process and replay; do not restore renderer scrollback. */+ persistent?: boolean}export interface HermesTerminalExit {@@ -1261,6 +1289,9 @@ export interface DesktopRosterAgent {export interface DesktopAgentRoster {agents: DesktopRosterAgent[]+ /** Registry source whose agents are already represented by the active+ * gateway's rich profiles.list rows; mergers annotate instead of duplicate. */+ primaryConnectionId?: stringsources: {connectionId: stringlabel: string@@ -1761,6 +1792,13 @@ export interface HermesPreviewFileChanged {url: string}+/** Backend-provided source identity, not an authorization token. */+export interface HermesStagedUpload {+ install_id: string+ path: string+ profile_home: string+}+export interface HermesSelectPathsOptions {title?: stringdefaultPath?: stringdiff --git a/apps/desktop/src/hooks/use-image-download.ts b/apps/desktop/src/hooks/use-image-download.tsindex dbaecf30aad..ad074ee9032 100644--- a/apps/desktop/src/hooks/use-image-download.ts+++ b/apps/desktop/src/hooks/use-image-download.ts@@ -1,50 +1,9 @@import { useCallback, useState } from 'react'import { useI18n } from '@/i18n'+import { downloadBlob, downloadFilename, imageFilename } from '@/lib/download'import { notify, notifyError } from '@/store/notifications'-const MIME_EXTENSIONS: Record<string, string> = {- 'image/bmp': '.bmp',- 'image/gif': '.gif',- 'image/jpeg': '.jpg',- 'image/png': '.png',- 'image/svg+xml': '.svg',- 'image/webp': '.webp'-}--const KNOWN_IMAGE_EXTENSION_RE = /\.(?:apng|avif|bmp|gif|ico|jpe?g|png|svg|tiff?|webp)$/i--export function imageFilename(src?: string): string {- if (!src) {- return 'image'- }-- try {- return new URL(src, window.location.href).pathname.split('/').filter(Boolean).pop() || 'image'- } catch {- return src.split(/[\\/]/).filter(Boolean).pop() || 'image'- }-}--/** Filename for a browser-anchor download. Generated-image URLs (fal.media- * etc.) often end in an extensionless content hash — without an extension the- * OS save dialog shows "All Files" and the saved file won't open by- * double-click, so append one derived from the blob's MIME type. */-export function downloadFilename(src: string, mimeType?: string): string {- const base = imageFilename(src)-- if (KNOWN_IMAGE_EXTENSION_RE.test(base)) {- return base- }-- const type = String(mimeType || '')- .split(';')[0]- .trim()- .toLowerCase()-- return `${base}${MIME_EXTENSIONS[type] || '.png'}`-}-function isMissingIpcHandler(error: unknown): boolean {const message = error instanceof Error ? error.message : typeof error === 'string' ? error : ''@@ -59,15 +18,7 @@ async function startBrowserDownload(src: string) {}const blob = await response.blob()- const blobUrl = URL.createObjectURL(blob)- const link = document.createElement('a')- link.href = blobUrl- link.download = downloadFilename(src, blob.type)- link.rel = 'noopener noreferrer'- document.body.appendChild(link)- link.click()- link.remove()- window.setTimeout(() => URL.revokeObjectURL(blobUrl), 30_000)+ downloadBlob(blob, downloadFilename(src, blob.type))}/** Save an image to disk via the desktop IPC bridge, falling back to a browserdiff --git a/apps/desktop/src/hooks/use-media-playback-src.expiry.test.tsx b/apps/desktop/src/hooks/use-media-playback-src.expiry.test.tsxnew file mode 100644index 00000000000..fdb77eaa6c6--- /dev/null+++ b/apps/desktop/src/hooks/use-media-playback-src.expiry.test.tsx@@ -0,0 +1,104 @@+import { fireEvent, render, screen, waitFor } from '@testing-library/react'+import { afterEach, beforeEach, expect, it, type MockInstance, vi } from 'vitest'++import type * as Media from '@/lib/media'+import { resolveMediaPlaybackSrc } from '@/lib/media'++import { useMediaPlaybackSrc } from './use-media-playback-src'++vi.mock('@/lib/media', async importOriginal => ({+ ...(await importOriginal<typeof Media>()),+ resolveMediaPlaybackSrc: vi.fn()+}))++const resolve = vi.mocked(resolveMediaPlaybackSrc)++function Player({ path }: { path: string }) {+ const { failed, onError, onLoadedMetadata, src } = useMediaPlaybackSrc(path)++ return (+ <>+ {src && <video data-testid="video" onError={onError} onLoadedMetadata={onLoadedMetadata} preload="none" src={src} />}+ {failed && <span>failed</span>}+ </>+ )+}++const video = () => screen.getByTestId('video') as HTMLVideoElement++function pressPlay(element: HTMLVideoElement) {+ Object.defineProperty(element, 'paused', { configurable: true, value: false })+}++let play: MockInstance<HTMLMediaElement['play']>++beforeEach(() => {+ let minted = 0+ resolve.mockImplementation(async () => `http://127.0.0.1/api/files/stream?ticket=t${++minted}`)+ play = vi.spyOn(HTMLMediaElement.prototype, 'play').mockResolvedValue(undefined)+})++afterEach(() => {+ vi.restoreAllMocks()+ resolve.mockReset()+})++it('a video whose ticket expired before its first play gets a fresh ticket and plays', async () => {+ render(<Player path="/srv/clip.mp4" />)+ await waitFor(() => expect(video().getAttribute('src')).toMatch(/ticket=t1$/))++ pressPlay(video())+ fireEvent.error(video())++ await waitFor(() => expect(video().getAttribute('src')).toMatch(/ticket=t2$/))+ expect(screen.queryByText('failed')).toBeNull()+ await waitFor(() => expect(play).toHaveBeenCalledTimes(1))+})++it('a fresh source that also fails before loading is a real failure', async () => {+ render(<Player path="/srv/clip.mp4" />)+ await waitFor(() => expect(video().getAttribute('src')).toMatch(/ticket=t1$/))++ fireEvent.error(video())+ await waitFor(() => expect(video().getAttribute('src')).toMatch(/ticket=t2$/))+ fireEvent.error(video())++ await screen.findByText('failed')+ expect(resolve).toHaveBeenCalledTimes(2)+ expect(video().getAttribute('src')).toMatch(/ticket=t2$/)+})++it('a paused video gets its fresh ticket without being started', async () => {+ render(<Player path="/srv/clip.mp4" />)+ await waitFor(() => expect(video().getAttribute('src')).toMatch(/ticket=t1$/))++ fireEvent.error(video())++ await waitFor(() => expect(video().getAttribute('src')).toMatch(/ticket=t2$/))+ expect(play).not.toHaveBeenCalled()+})++it('a source that loaded and later expired is re-resolved', async () => {+ render(<Player path="/srv/clip.mp4" />)+ await waitFor(() => expect(video().getAttribute('src')).toMatch(/ticket=t1$/))+ fireEvent.loadedMetadata(video())+ fireEvent.error(video())+ await waitFor(() => expect(video().getAttribute('src')).toMatch(/ticket=t2$/))++ fireEvent.loadedMetadata(video())+ fireEvent.error(video())++ await waitFor(() => expect(video().getAttribute('src')).toMatch(/ticket=t3$/))+ expect(screen.queryByText('failed')).toBeNull()+})++it('a blob source never retries', async () => {+ resolve.mockImplementation(async () => 'blob:http://127.0.0.1/clip')+ render(<Player path="/srv/clip.mp4" />)+ await waitFor(() => expect(video().getAttribute('src')).toBe('blob:http://127.0.0.1/clip'))++ fireEvent.error(video())++ await screen.findByText('failed')+ expect(resolve).toHaveBeenCalledTimes(1)+})diff --git a/apps/desktop/src/hooks/use-media-playback-src.owner.test.tsx b/apps/desktop/src/hooks/use-media-playback-src.owner.test.tsxnew file mode 100644index 00000000000..0c2855344ab--- /dev/null+++ b/apps/desktop/src/hooks/use-media-playback-src.owner.test.tsx@@ -0,0 +1,58 @@+import { LOCAL_CONNECTION_ID } from '@hermes/shared'+import { renderHook, waitFor } from '@testing-library/react'+import type { ReactNode } from 'react'+import { afterEach, expect, it, vi } from 'vitest'++import { setApiRequestConnection, setApiRequestProfile } from '@/api/client'+import { ComposerScopeProvider, MAIN_COMPOSER_SCOPE } from '@/app/chat/composer/scope'+import { installBrowserDesktopBridge } from '@/lib/browser-desktop-bridge'+import { $connection } from '@/store/session'+import { clearWebappSession, seedWebappSession } from '@/test/webapp-session'++import { useMediaPlaybackSrc } from './use-media-playback-src'++const win = window++afterEach(() => {+ clearWebappSession()+ Reflect.deleteProperty(win, 'hermesDesktop')+ setApiRequestConnection(null)+ setApiRequestProfile(null)+ $connection.set(null)+ window.dispatchEvent(new Event('beforeunload'))+ vi.unstubAllGlobals()+ vi.restoreAllMocks()+})++it.each([+ { expected: 'foreground', name: 'main thread (control)', scope: MAIN_COMPOSER_SCOPE },+ {+ expected: 'tile-owner',+ name: 'background tile',+ scope: { ...MAIN_COMPOSER_SCOPE, connectionId: LOCAL_CONNECTION_ID, profile: 'tile-owner', target: 'tile:t' as const }+ }+])('a transcript video streams on its scope owner: $name', async ({ expected, scope }) => {+ seedWebappSession('served-token')++ vi.stubGlobal(+ 'fetch',+ vi.fn(async (input: URL) =>+ input.pathname === '/api/files/ticket'+ ? new Response(JSON.stringify({ ticket: 'scope-ticket' }), { status: 200 })+ : new Response('{}', { status: 404 })+ )+ )+ expect(installBrowserDesktopBridge()).toBe(true)+ setApiRequestConnection(LOCAL_CONNECTION_ID)+ setApiRequestProfile('foreground')+ $connection.set({ connectionId: LOCAL_CONNECTION_ID, mode: 'remote', profile: 'foreground' } as never)++ const wrapper = ({ children }: { children: ReactNode }) => (+ <ComposerScopeProvider value={scope}>{children}</ComposerScopeProvider>+ )++ const { result } = renderHook(() => useMediaPlaybackSrc('/srv/tile-owner/clip.mp4'), { wrapper })++ await waitFor(() => expect(result.current.src).not.toBe(''))+ expect(new URL(result.current.src).searchParams.get('profile')).toBe(expected)+})diff --git a/apps/desktop/src/hooks/use-media-playback-src.ts b/apps/desktop/src/hooks/use-media-playback-src.tsnew file mode 100644index 00000000000..ece3b29bb68--- /dev/null+++ b/apps/desktop/src/hooks/use-media-playback-src.ts@@ -0,0 +1,166 @@+import { type SyntheticEvent, useCallback, useEffect, useMemo, useRef, useState } from 'react'++import { useComposerScope } from '@/app/chat/composer/scope'+import { mediaKind, resolveMediaPlaybackSrc } from '@/lib/media'++type PlaybackEvent = SyntheticEvent<HTMLAudioElement | HTMLVideoElement>++interface ResumePoint {+ element: HTMLAudioElement | HTMLVideoElement+ paused: boolean+ src: string+ time: number+}++/** The playable source for a transcript audio/video attachment.+ *+ * Webapp sources are stream-ticket URLs that expire, and the element needs a+ * valid one for every later range request (a seek, or play after a long+ * pause). A video fetches nothing until it is played, so its first ticket can+ * expire unused. So a source that has loaded, or that waited unfetched, is+ * re-resolved on its next error and playback resumes where it stopped. Any+ * other source that fails before it loads, or one that resolves to the same+ * URL again, is a real failure. */+export function useMediaPlaybackSrc(path: string) {+ const kind = mediaKind(path)+ const scope = useComposerScope()++ // A transcript in a background tile streams through the tile's owner, not the foreground.+ const owner = useMemo(+ () => (scope.connectionId || scope.profile ? { connectionId: scope.connectionId, profile: scope.profile } : undefined),+ [scope.connectionId, scope.profile]+ )++ const [media, setMedia] = useState({ failed: false, path, src: '' })+ const loadedSrc = useRef('')+ // Minted for a source that failed before it ever loaded; it gets no retry of its own.+ const retriedSrc = useRef('')+ const resume = useRef<null | ResumePoint>(null)++ useEffect(() => {+ let cancelled = false+ let objectUrl = ''++ setMedia({ failed: kind === 'file', path, src: '' })++ if (kind === 'file') {+ return+ }++ void resolveMediaPlaybackSrc(path, owner)+ .then(value => {+ if (value.startsWith('blob:')) {+ objectUrl = value+ }++ if (!cancelled) {+ setMedia({ failed: false, path, src: value })+ } else if (objectUrl) {+ URL.revokeObjectURL(objectUrl)+ }+ })+ .catch(() => {+ if (!cancelled) {+ setMedia({ failed: true, path, src: '' })+ }+ })++ return () => {+ cancelled = true++ if (objectUrl) {+ URL.revokeObjectURL(objectUrl)+ }+ }+ }, [kind, owner, path])++ const onLoadedMetadata = useCallback((event: PlaybackEvent) => {+ const element = event.currentTarget+ const loaded = element.getAttribute('src') ?? ''+ const point = resume.current+ loadedSrc.current = loaded++ if (point?.src !== loaded) {+ return+ }++ resume.current = null+ element.currentTime = point.time++ if (!point.paused) {+ void element.play().catch(() => {+ // Resuming without a fresh gesture can be refused; the position is restored.+ })+ }+ }, [])++ const onError = useCallback(+ (event: PlaybackEvent) => {+ const element = event.currentTarget+ const failing = element.getAttribute('src') ?? ''++ const fail = () =>+ setMedia(current => (current.src === failing ? { ...current, failed: true } : current))++ const neverLoaded = loadedSrc.current !== failing+ // A source that never loaded can only have expired if its element waited to fetch it+ // (preload="none" until played); it gets one fresh ticket. Blob sources never expire.+ const realFailure = neverLoaded && (element.preload !== 'none' || retriedSrc.current === failing)++ if (failing.startsWith('blob:') || realFailure) {+ fail()++ return+ }++ const point = { element, paused: element.paused, time: element.currentTime }++ void resolveMediaPlaybackSrc(path, owner)+ .then(fresh => {+ if (fresh === failing || fresh.startsWith('blob:')) {+ if (fresh !== failing) {+ URL.revokeObjectURL(fresh)+ }++ fail()++ return+ }++ if (neverLoaded) {+ retriedSrc.current = fresh+ }++ resume.current = { ...point, src: fresh }+ setMedia(current => (current.src === failing ? { ...current, src: fresh } : current))+ })+ .catch(fail)+ },+ [owner, path]+ )++ // An element with preload="none" fetches nothing for a new source until asked, so one+ // that was playing is asked again; onLoadedMetadata then restores the position.+ useEffect(() => {+ const point = resume.current++ if (!point || point.paused || point.src !== media.src || point.element.preload !== 'none') {+ return+ }++ void point.element.play().catch(() => {+ // Without the user's gesture still active the browser can refuse; Play works again.+ })+ }, [media.src])++ // Never paint the previous path's source while the new one resolves.+ const current = media.path === path++ return {+ failed: current ? media.failed : kind === 'file',+ kind,+ onError,+ onLoadedMetadata,+ src: current ? media.src : ''+ }+}diff --git a/apps/desktop/src/i18n/ar_artifacts.ts b/apps/desktop/src/i18n/ar_artifacts.tsindex 9876dc7c0e2..488445271f6 100644--- a/apps/desktop/src/i18n/ar_artifacts.ts+++ b/apps/desktop/src/i18n/ar_artifacts.ts@@ -114,6 +114,7 @@ export const arArtifacts = {sentMessage: count => `أُضيف ${count} ${count === 1 ? 'إدخال سجل' : 'إدخالات سجل'} إلى المُنشئ`},web: {+ embeddedPreviewHint: 'تمنع بعض المواقع المعاينات المضمّنة. افتح الصفحة الأصلية في علامة تبويب بالمتصفح.',appFailedToBoot: 'فشل إقلاع تطبيق المعاينة',serverNotFound: 'الخادم غير موجود',remoteLoopback:diff --git a/apps/desktop/src/i18n/ar_settings.ts b/apps/desktop/src/i18n/ar_settings.tsindex b4abecce802..bb8d35dcc1b 100644--- a/apps/desktop/src/i18n/ar_settings.ts+++ b/apps/desktop/src/i18n/ar_settings.ts@@ -646,6 +646,9 @@ export const arSettings = {loading: 'جار تحميل إعدادات البوابة...',unavailableTitle: 'إعدادات البوابة غير متاحة',unavailableDesc: 'جسر IPC في سطح المكتب لا يوفّر إعدادات البوابة.',+ webappHostTitle: 'مضيف Hermes',+ webappHostDesc:+ 'يستخدم Webapp دائمًا مضيف Hermes الذي يقدّمه. لتبديل البوابة أو تسجيل الدخول إلى Hermes Cloud أو إدارة الاتصالات المحفوظة، استخدم تطبيق Hermes Desktop.',title: 'اتصال البوابة',envOverride: 'تجاوز من البيئة',intro:diff --git a/apps/desktop/src/i18n/de.ts b/apps/desktop/src/i18n/de.tsindex 35c882893aa..2349812799e 100644--- a/apps/desktop/src/i18n/de.ts+++ b/apps/desktop/src/i18n/de.ts@@ -8,6 +8,7 @@ import { deConnectorCard } from './de_connector_card'import { deErrorCodes } from './de_error_codes'import { deErrorLayers } from './de_error_layers'import { deFirstRun } from './de_first_run'+import { deGatewayHost } from './de_gateway_host'import { deLocalModels } from './de_local_models'import { deModelMenu } from './de_model_menu'import { deModelSettings } from './de_model_settings'@@ -16,6 +17,7 @@ import { deNotifications } from './de_notifications'import { deOnboarding } from './de_onboarding'import { dePluginPreviewAccess } from './de_plugin_preview_access'import { dePluginUpdate } from './de_plugin_update'+import { dePreviewWeb } from './de_preview_web'import { deProjects } from './de_projects'import { deSharedMetrics } from './de_shared_metrics'import { deThemePicker } from './de_theme_picker'@@ -1680,8 +1682,7 @@ export const deOverrides = {},gateway: {loading: 'Gateway-Einstellungen werden geladen…',- unavailableTitle: 'Gateway-Einstellungen nicht verfügbar',- unavailableDesc: 'Die Desktop-IPC-Brücke stellt keine Gateway-Einstellungen bereit.',+ ...deGatewayHost,title: 'Gateway-Verbindung',envOverride: 'ENV-Überschreibung',intro:@@ -4716,60 +4717,7 @@ export const deOverrides = {sentTitle: 'An Chat gesendet',sentMessage: count => `Einträge aus dem Log (${count}) wurden zum Composer hinzugefügt`},- web: {- appFailedToBoot: 'Die Vorschau-App konnte nicht gestartet werden',- serverNotFound: 'Server nicht gefunden',- remoteLoopback:- 'Diese Adresse verweist auf den Rechner, auf dem Ihr Agent läuft – nicht auf diesen. Das Browserfenster lädt Seiten lokal, daher braucht ein entfernter Entwicklungsserver eine Portweiterleitung oder einen erreichbaren Hostnamen.',- failedToLoad: 'Vorschau konnte nicht geladen werden',- tryAgain: 'Nochmal versuchen',- restarting: 'Hermes wird neu gestartet …',- askRestart: 'Hermes bitten, den Server neu zu starten',- lookingRestart: taskId => `Hermes sucht nach einem Vorschau-Server zum Neustarten (${taskId})`,- restartingTitle: 'Vorschau-Server wird neu gestartet',- restartingMessage: 'Hermes arbeitet im Hintergrund. Beobachte im Fortschritt die Vorschau-Konsole.',- startRestartFailed: message => `Server-Neustart konnte nicht gestartet werden: ${message}`,- restartFailed: 'Server-Neustart fehlgeschlagen',- hideConsole: 'Vorschau-Konsole ausblenden',- showConsole: 'Vorschau-Konsole anzeigen',- hideDevTools: 'Vorschau-DevTools ausblenden',- openDevTools: 'Vorschau-DevTools öffnen',- goBack: 'Zurück',- goForward: 'Vor',- reload: 'Seite neu laden',- address: 'Adresse',- addressPlaceholder: 'Adresse eingeben',- blankPageBody: 'Geben Sie oben eine Adresse ein, um zu browsen, oder bitten Sie Hermes, eine Seite zu öffnen.',- finishedRestarting: message => `Hermes hat den Vorschau-Server neu gestartet${message ? `: ${message}` : ''}`,- failedRestarting: message => `Server-Neustart fehlgeschlagen: ${message}`,- unknownError: 'unbekannter Fehler',- restartedTitle: 'Vorschau-Server neu gestartet',- reloadingNow: 'Die Vorschau wird jetzt neu geladen.',- restartFailedTitle: 'Vorschau-Neustart fehlgeschlagen',- restartFailedMessage: 'Hermes konnte den Server nicht neu starten.',- stillWorking:- 'Hermes arbeitet noch, aber es ist noch kein Ergebnis des Neustarts eingetroffen. Der Server-Befehl läuft möglicherweise im Vordergrund.',- workspaceReloading: 'Arbeitsbereich geändert, Vorschau wird neu geladen',- fileChanged: url => `Datei geändert, Vorschau wird neu geladen: ${url}`,- filesChanged: (count, url) => `${count} Dateiänderungen, Vorschau wird neu geladen: ${url}`,- watchFailed: message => `Vorschau-Datei konnte nicht überwacht werden: ${message}`,- moduleMimeDescription:- 'Modul-Skripte werden mit dem falschen MIME-Typ ausgeliefert. Das bedeutet meist, dass ein statischer Datei-Server eine Vite/React-App ausliefert statt des Projekt-Entwicklungs-Servers.',- loadFailedConsole: (code, message) => `Laden fehlgeschlagen${code ? ` (${code})` : ''}: ${message}`,- unreachableDescription: 'Die Vorschau-Seite konnte nicht erreicht werden.',- openTarget: url => `${url} öffnen`,- fallbackTitle: 'Vorschau',- annotate: 'Annotieren',- annotateOn: 'Annotation beenden',- annotateNeedPage: 'Öffnen Sie zuerst eine Seite im In-App-Browser.',- annotateFailed: 'Annotationsmodus konnte nicht gestartet werden',- commenting: 'Kommentieren',- addComments: count => (count === 1 ? '1 Kommentar hinzufügen' : `${count} Kommentare hinzufügen`),- commentPlaceholder: 'Kommentar hinzufügen …',- commentTitle: n => `Kommentar ${n}`,- saveComment: 'Speichern',- cancelComment: 'Kommentar abbrechen'- }+ web: dePreviewWeb},interfaceMode: {title: 'Oberflächenmodus',diff --git a/apps/desktop/src/i18n/de_gateway_host.ts b/apps/desktop/src/i18n/de_gateway_host.tsnew file mode 100644index 00000000000..68ed6da4fb8--- /dev/null+++ b/apps/desktop/src/i18n/de_gateway_host.ts@@ -0,0 +1,10 @@+import type { GatewayHostTranslations } from './types_gateway_host'++// Settings → Gateways copy where the connection cannot change, spread into de.ts.+export const deGatewayHost: GatewayHostTranslations = {+ unavailableTitle: 'Gateway-Einstellungen nicht verfügbar',+ unavailableDesc: 'Die Desktop-IPC-Brücke stellt keine Gateway-Einstellungen bereit.',+ webappHostTitle: 'Hermes-Host',+ webappHostDesc:+ 'Die Webapp nutzt immer den Hermes-Host, der sie ausliefert. Um das Gateway zu wechseln, sich bei Hermes Cloud anzumelden oder gespeicherte Verbindungen zu verwalten, verwenden Sie die Hermes-Desktop-App.'+}diff --git a/apps/desktop/src/i18n/de_preview_web.ts b/apps/desktop/src/i18n/de_preview_web.tsnew file mode 100644index 00000000000..e5048a10862--- /dev/null+++ b/apps/desktop/src/i18n/de_preview_web.ts@@ -0,0 +1,61 @@+import type { TranslationOverride } from '@hermes/shared/i18n'++import type { Translations } from './types'++// The in-app browser pane's copy (`preview.web`), composed by de.ts.+export const dePreviewWeb: TranslationOverride<Translations['preview']['web']> = {+ embeddedPreviewHint:+ 'Manche Websites blockieren eingebettete Vorschauen. Öffne die Originalseite in einem Browser-Tab.',+ appFailedToBoot: 'Die Vorschau-App konnte nicht gestartet werden',+ serverNotFound: 'Server nicht gefunden',+ remoteLoopback:+ 'Diese Adresse verweist auf den Rechner, auf dem Ihr Agent läuft – nicht auf diesen. Das Browserfenster lädt Seiten lokal, daher braucht ein entfernter Entwicklungsserver eine Portweiterleitung oder einen erreichbaren Hostnamen.',+ failedToLoad: 'Vorschau konnte nicht geladen werden',+ tryAgain: 'Nochmal versuchen',+ restarting: 'Hermes wird neu gestartet …',+ askRestart: 'Hermes bitten, den Server neu zu starten',+ lookingRestart: taskId => `Hermes sucht nach einem Vorschau-Server zum Neustarten (${taskId})`,+ restartingTitle: 'Vorschau-Server wird neu gestartet',+ restartingMessage: 'Hermes arbeitet im Hintergrund. Beobachte im Fortschritt die Vorschau-Konsole.',+ startRestartFailed: message => `Server-Neustart konnte nicht gestartet werden: ${message}`,+ restartFailed: 'Server-Neustart fehlgeschlagen',+ hideConsole: 'Vorschau-Konsole ausblenden',+ showConsole: 'Vorschau-Konsole anzeigen',+ hideDevTools: 'Vorschau-DevTools ausblenden',+ openDevTools: 'Vorschau-DevTools öffnen',+ goBack: 'Zurück',+ goForward: 'Vor',+ reload: 'Seite neu laden',+ address: 'Adresse',+ addressPlaceholder: 'Adresse eingeben',+ blankPageBody: 'Geben Sie oben eine Adresse ein, um zu browsen, oder bitten Sie Hermes, eine Seite zu öffnen.',+ finishedRestarting: message => `Hermes hat den Vorschau-Server neu gestartet${message ? `: ${message}` : ''}`,+ failedRestarting: message => `Server-Neustart fehlgeschlagen: ${message}`,+ unknownError: 'unbekannter Fehler',+ restartedTitle: 'Vorschau-Server neu gestartet',+ reloadingNow: 'Die Vorschau wird jetzt neu geladen.',+ restartFailedTitle: 'Vorschau-Neustart fehlgeschlagen',+ restartFailedMessage: 'Hermes konnte den Server nicht neu starten.',+ stillWorking:+ 'Hermes arbeitet noch, aber es ist noch kein Ergebnis des Neustarts eingetroffen. Der Server-Befehl läuft möglicherweise im Vordergrund.',+ workspaceReloading: 'Arbeitsbereich geändert, Vorschau wird neu geladen',+ fileChanged: url => `Datei geändert, Vorschau wird neu geladen: ${url}`,+ filesChanged: (count, url) => `${count} Dateiänderungen, Vorschau wird neu geladen: ${url}`,+ watchFailed: message => `Vorschau-Datei konnte nicht überwacht werden: ${message}`,+ moduleMimeDescription:+ 'Modul-Skripte werden mit dem falschen MIME-Typ ausgeliefert. Das bedeutet meist, dass ein statischer Datei-Server eine Vite/React-App ausliefert statt des Projekt-Entwicklungs-Servers.',+ loadFailedConsole: (code, message) => `Laden fehlgeschlagen${code ? ` (${code})` : ''}: ${message}`,+ unreachableDescription: 'Die Vorschau-Seite konnte nicht erreicht werden.',+ openTarget: url => `${url} öffnen`,+ fallbackTitle: 'Vorschau',+ annotate: 'Annotieren',+ annotateOn: 'Annotation beenden',+ annotateNeedPage: 'Öffnen Sie zuerst eine Seite im In-App-Browser.',+ annotateFailed: 'Annotationsmodus konnte nicht gestartet werden',+ commenting: 'Kommentieren',+ addComments: count => (count === 1 ? '1 Kommentar hinzufügen' : `${count} Kommentare hinzufügen`),+ commentPlaceholder: 'Kommentar hinzufügen …',+ commentTitle: n => `Kommentar ${n}`,+ saveComment: 'Speichern',+ cancelComment: 'Kommentar abbrechen'+}diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.tsindex 05b28a94559..c17158cbad8 100644--- a/apps/desktop/src/i18n/en.ts+++ b/apps/desktop/src/i18n/en.ts@@ -14,6 +14,7 @@ import { enErrorCodes } from './en_error_codes'import { enErrorLayers } from './en_error_layers'import { enExternalOpenFailed } from './en_external_open'import { enFirstRun } from './en_first_run'+import { enGatewayHost } from './en_gateway_host'import { enLocalModels } from './en_local_models'import { enModelMenu } from './en_model_menu'import { enModelSettings } from './en_model_settings'@@ -22,6 +23,7 @@ import { enNotifications } from './en_notifications'import { enOnboarding } from './en_onboarding'import { enPluginPreviewAccess } from './en_plugin_preview_access'import { enPluginUpdate } from './en_plugin_update'+import { enPreviewWeb } from './en_preview_web'import { enProjects } from './en_projects'import { enSharedMetrics } from './en_shared_metrics'import { enThemePicker } from './en_theme_picker'@@ -1340,9 +1342,7 @@ export const en: Translations = {},gateway: {loading: 'Loading gateway settings...',- unavailableTitle: 'Gateway settings unavailable',- unavailableDesc:- 'Connection settings can only be changed from the Hermes Desktop app on the computer running it.',+ ...enGatewayHost,title: 'Gateway Connection',envOverride: 'env override',intro:@@ -4294,60 +4294,7 @@ export const en: Translations = {sentTitle: 'Sent to chat',sentMessage: count => `${count} log entr${count === 1 ? 'y' : 'ies'} added to composer`},- web: {- appFailedToBoot: 'Preview app failed to boot',- serverNotFound: 'Server not found',- remoteLoopback:- 'This address points at the machine running your agent, not this one. The browser pane loads pages locally, so a remote dev server needs a port forward or a reachable hostname.',- failedToLoad: 'Preview failed to load',- tryAgain: 'Try again',- restarting: 'Hermes is restarting...',- askRestart: 'Ask Hermes to restart the server',- lookingRestart: taskId => `Hermes is looking for a preview server to restart (${taskId})`,- restartingTitle: 'Restarting preview server',- restartingMessage: 'Hermes is working in the background. Watch the preview console for progress.',- startRestartFailed: message => `Could not start server restart: ${message}`,- restartFailed: 'Server restart failed',- hideConsole: 'Hide preview console',- showConsole: 'Show preview console',- hideDevTools: 'Hide preview DevTools',- openDevTools: 'Open preview DevTools',- goBack: 'Back',- goForward: 'Forward',- reload: 'Reload page',- address: 'Address',- addressPlaceholder: 'Enter address',- blankPageBody: 'Type an address above to browse, or ask Hermes to open a page.',- finishedRestarting: message => `Hermes finished restarting the preview server${message ? `: ${message}` : ''}`,- failedRestarting: message => `Server restart failed: ${message}`,- unknownError: 'unknown error',- restartedTitle: 'Preview server restarted',- reloadingNow: 'Reloading the preview now.',- restartFailedTitle: 'Preview restart failed',- restartFailedMessage: 'Hermes could not restart the server.',- stillWorking:- 'Hermes is still working, but no restart result has arrived yet. The server command may be running in the foreground.',- workspaceReloading: 'Workspace changed, reloading preview',- fileChanged: url => `File changed, reloading preview: ${url}`,- filesChanged: (count, url) => `${count} file changes, reloading preview: ${url}`,- watchFailed: message => `Could not watch preview file: ${message}`,- moduleMimeDescription:- 'Module scripts are being served with the wrong MIME type. This usually means a static file server is serving a Vite/React app instead of the project dev server.',- loadFailedConsole: (code, message) => `Load failed${code ? ` (${code})` : ''}: ${message}`,- unreachableDescription: 'The preview page could not be reached.',- openTarget: url => `Open ${url}`,- fallbackTitle: 'Preview',- annotate: 'Annotate',- annotateOn: 'Stop annotating',- annotateNeedPage: 'Open a page in the in-app browser first.',- annotateFailed: 'Could not start annotation mode',- commenting: 'Commenting',- addComments: count => (count === 1 ? 'Add 1 comment' : `Add ${count} comments`),- commentPlaceholder: 'Add a comment...',- commentTitle: n => `Comment ${n}`,- saveComment: 'Save',- cancelComment: 'Cancel comment'- }+ web: enPreviewWeb},interfaceMode: {@@ -4411,7 +4358,7 @@ export const en: Translations = {saveApply: 'Save & apply',notExpressible: 'this arrangement interlocks (pinwheel) — not expressible as nested splits yet',zoneCount: count => `${count} zones`,- tabCount: count => `${count} tabs`+ tabCount: count => `${count} tab${count === 1 ? '' : 's'}`},contextMenu: {diff --git a/apps/desktop/src/i18n/en_gateway_host.ts b/apps/desktop/src/i18n/en_gateway_host.tsnew file mode 100644index 00000000000..be00b2a3037--- /dev/null+++ b/apps/desktop/src/i18n/en_gateway_host.ts@@ -0,0 +1,10 @@+import type { GatewayHostTranslations } from './types_gateway_host'++// Settings → Gateways copy where the connection cannot change, spread into en.ts.+export const enGatewayHost: GatewayHostTranslations = {+ unavailableTitle: 'Gateway settings unavailable',+ unavailableDesc: 'Connection settings can only be changed from the Hermes Desktop app on the computer running it.',+ webappHostTitle: 'Hermes host',+ webappHostDesc:+ 'The Webapp always uses the Hermes host that serves it. To switch gateways, sign in to Hermes Cloud or manage saved connections, use the Hermes Desktop app.'+}diff --git a/apps/desktop/src/i18n/en_preview_web.ts b/apps/desktop/src/i18n/en_preview_web.tsnew file mode 100644index 00000000000..65b87360f96--- /dev/null+++ b/apps/desktop/src/i18n/en_preview_web.ts@@ -0,0 +1,58 @@+import type { Translations } from './types'++// The in-app browser pane's copy (`preview.web`), composed by en.ts.+export const enPreviewWeb: Translations['preview']['web'] = {+ embeddedPreviewHint: 'Some sites block embedded previews. Open the original page in a browser tab.',+ appFailedToBoot: 'Preview app failed to boot',+ serverNotFound: 'Server not found',+ remoteLoopback:+ 'This address points at the machine running your agent, not this one. The browser pane loads pages locally, so a remote dev server needs a port forward or a reachable hostname.',+ failedToLoad: 'Preview failed to load',+ tryAgain: 'Try again',+ restarting: 'Hermes is restarting...',+ askRestart: 'Ask Hermes to restart the server',+ lookingRestart: taskId => `Hermes is looking for a preview server to restart (${taskId})`,+ restartingTitle: 'Restarting preview server',+ restartingMessage: 'Hermes is working in the background. Watch the preview console for progress.',+ startRestartFailed: message => `Could not start server restart: ${message}`,+ restartFailed: 'Server restart failed',+ hideConsole: 'Hide preview console',+ showConsole: 'Show preview console',+ hideDevTools: 'Hide preview DevTools',+ openDevTools: 'Open preview DevTools',+ goBack: 'Back',+ goForward: 'Forward',+ reload: 'Reload page',+ address: 'Address',+ addressPlaceholder: 'Enter address',+ blankPageBody: 'Type an address above to browse, or ask Hermes to open a page.',+ finishedRestarting: message => `Hermes finished restarting the preview server${message ? `: ${message}` : ''}`,+ failedRestarting: message => `Server restart failed: ${message}`,+ unknownError: 'unknown error',+ restartedTitle: 'Preview server restarted',+ reloadingNow: 'Reloading the preview now.',+ restartFailedTitle: 'Preview restart failed',+ restartFailedMessage: 'Hermes could not restart the server.',+ stillWorking:+ 'Hermes is still working, but no restart result has arrived yet. The server command may be running in the foreground.',+ workspaceReloading: 'Workspace changed, reloading preview',+ fileChanged: url => `File changed, reloading preview: ${url}`,+ filesChanged: (count, url) => `${count} file changes, reloading preview: ${url}`,+ watchFailed: message => `Could not watch preview file: ${message}`,+ moduleMimeDescription:+ 'Module scripts are being served with the wrong MIME type. This usually means a static file server is serving a Vite/React app instead of the project dev server.',+ loadFailedConsole: (code, message) => `Load failed${code ? ` (${code})` : ''}: ${message}`,+ unreachableDescription: 'The preview page could not be reached.',+ openTarget: url => `Open ${url}`,+ fallbackTitle: 'Preview',+ annotate: 'Annotate',+ annotateOn: 'Stop annotating',+ annotateNeedPage: 'Open a page in the in-app browser first.',+ annotateFailed: 'Could not start annotation mode',+ commenting: 'Commenting',+ addComments: count => (count === 1 ? 'Add 1 comment' : `Add ${count} comments`),+ commentPlaceholder: 'Add a comment...',+ commentTitle: n => `Comment ${n}`,+ saveComment: 'Save',+ cancelComment: 'Cancel comment'+}diff --git a/apps/desktop/src/i18n/es.ts b/apps/desktop/src/i18n/es.tsindex cb14b277731..d906e8fb6f4 100644--- a/apps/desktop/src/i18n/es.ts+++ b/apps/desktop/src/i18n/es.ts@@ -9,6 +9,7 @@ import { esConnectorCard } from './es_connector_card'import { esErrorCodes } from './es_error_codes'import { esErrorLayers } from './es_error_layers'import { esFirstRun } from './es_first_run'+import { esGatewayHost } from './es_gateway_host'import { esLocalModels } from './es_local_models'import { esModelMenu } from './es_model_menu'import { esModelSettings } from './es_model_settings'@@ -17,6 +18,7 @@ import { esNotifications } from './es_notifications'import { esOnboarding } from './es_onboarding'import { esPluginPreviewAccess } from './es_plugin_preview_access'import { esPluginUpdate } from './es_plugin_update'+import { esPreviewWeb } from './es_preview_web'import { esProjects } from './es_projects'import { esSharedMetrics } from './es_shared_metrics'import { esThemePicker } from './es_theme_picker'@@ -1678,9 +1680,7 @@ export const esOverrides = {},gateway: {loading: 'Cargando ajustes del gateway...',- unavailableTitle: 'Ajustes del gateway no disponibles',- unavailableDesc:- 'Los ajustes de conexión solo se pueden cambiar desde la app Hermes Desktop en el equipo que la ejecuta.',+ ...esGatewayHost,title: 'Conexión del gateway',envOverride: 'anulación de entorno',intro:@@ -4701,62 +4701,7 @@ export const esOverrides = {sentMessage: count =>`${count} ${count === 1 ? 'entrada de registro añadida' : 'entradas de registro añadidas'} al compositor`},- web: {- appFailedToBoot: 'La app de vista previa no arrancó',- serverNotFound: 'Servidor no encontrado',- remoteLoopback:- 'Esta dirección apunta al equipo que ejecuta tu agente, no a este. El panel del navegador carga las páginas localmente, así que un servidor de desarrollo remoto necesita un reenvío de puertos o un nombre de host accesible.',- failedToLoad: 'No se pudo cargar la vista previa',- tryAgain: 'Intentar de nuevo',- restarting: 'Hermes se está reiniciando...',- askRestart: 'Pedir a Hermes que reinicie el servidor',- lookingRestart: taskId => `Hermes está buscando un servidor de vista previa para reiniciar (${taskId})`,- restartingTitle: 'Reiniciando servidor de vista previa',- restartingMessage:- 'Hermes está trabajando en segundo plano. Mira la consola de vista previa para ver el progreso.',- startRestartFailed: message => `No se pudo iniciar el reinicio del servidor: ${message}`,- restartFailed: 'Falló el reinicio del servidor',- hideConsole: 'Ocultar consola de vista previa',- showConsole: 'Mostrar consola de vista previa',- hideDevTools: 'Ocultar DevTools de vista previa',- openDevTools: 'Abrir DevTools de vista previa',- goBack: 'Atrás',- goForward: 'Adelante',- reload: 'Recargar página',- address: 'Dirección',- addressPlaceholder: 'Introduce una dirección',- blankPageBody: 'Escribe una dirección arriba para navegar o pide a Hermes que abra una página.',- finishedRestarting: message =>- `Hermes terminó de reiniciar el servidor de vista previa${message ? `: ${message}` : ''}`,- failedRestarting: message => `Falló el reinicio del servidor: ${message}`,- unknownError: 'error desconocido',- restartedTitle: 'Servidor de vista previa reiniciado',- reloadingNow: 'Recargando la vista previa ahora.',- restartFailedTitle: 'Falló el reinicio de la vista previa',- restartFailedMessage: 'Hermes no pudo reiniciar el servidor.',- stillWorking:- 'Hermes sigue trabajando, pero aún no llegó ningún resultado de reinicio. Puede que el comando del servidor siga en primer plano.',- workspaceReloading: 'El espacio de trabajo cambió, recargando vista previa',- fileChanged: url => `Archivo cambiado, recargando vista previa: ${url}`,- filesChanged: (count, url) => `${count} cambios de archivo, recargando vista previa: ${url}`,- watchFailed: message => `No se pudo vigilar el archivo de vista previa: ${message}`,- moduleMimeDescription:- 'Los scripts de módulo se están sirviendo con el tipo MIME incorrecto. Normalmente significa que un servidor de archivos estáticos sirve una app Vite/React en lugar del dev server del proyecto.',- loadFailedConsole: (code, message) => `Carga fallida${code ? ` (${code})` : ''}: ${message}`,- unreachableDescription: 'No se pudo acceder a la página de vista previa.',- openTarget: url => `Abrir ${url}`,- fallbackTitle: 'Vista previa',- annotate: 'Anotar',- annotateOn: 'Dejar de anotar',- annotateNeedPage: 'Primero abre una página en el navegador integrado.',- annotateFailed: 'No se pudo iniciar el modo de anotación',- commenting: 'Comentando',- addComments: (count: number) => (count === 1 ? 'Añadir 1 comentario' : `Añadir ${count} comentarios`),- commentPlaceholder: 'Añade un comentario...',- commentTitle: (n: number) => `Comentario ${n}`,- saveComment: 'Guardar',- cancelComment: 'Cancelar comentario'- }+ web: esPreviewWeb},interfaceMode: {title: 'Modo de interfaz',diff --git a/apps/desktop/src/i18n/es_gateway_host.ts b/apps/desktop/src/i18n/es_gateway_host.tsnew file mode 100644index 00000000000..7f0ec80a3a1--- /dev/null+++ b/apps/desktop/src/i18n/es_gateway_host.ts@@ -0,0 +1,11 @@+import type { GatewayHostTranslations } from './types_gateway_host'++// Settings → Gateways copy where the connection cannot change, spread into es.ts.+export const esGatewayHost: GatewayHostTranslations = {+ unavailableTitle: 'Ajustes del gateway no disponibles',+ unavailableDesc:+ 'Los ajustes de conexión solo se pueden cambiar desde la app Hermes Desktop en el equipo que la ejecuta.',+ webappHostTitle: 'Host de Hermes',+ webappHostDesc:+ 'La Webapp siempre usa el host de Hermes que la sirve. Para cambiar de gateway, iniciar sesión en Hermes Cloud o gestionar conexiones guardadas, usa la app Hermes Desktop.'+}diff --git a/apps/desktop/src/i18n/es_preview_web.ts b/apps/desktop/src/i18n/es_preview_web.tsnew file mode 100644index 00000000000..064d7cd0969--- /dev/null+++ b/apps/desktop/src/i18n/es_preview_web.ts@@ -0,0 +1,62 @@+import type { TranslationOverride } from '@hermes/shared/i18n'++import type { Translations } from './types'++// The in-app browser pane's copy (`preview.web`), composed by es.ts.+export const esPreviewWeb: TranslationOverride<Translations['preview']['web']> = {+ embeddedPreviewHint:+ 'Algunos sitios bloquean las vistas previas incrustadas. Abre la página original en una pestaña del navegador.',+ appFailedToBoot: 'La app de vista previa no arrancó',+ serverNotFound: 'Servidor no encontrado',+ remoteLoopback:+ 'Esta dirección apunta al equipo que ejecuta tu agente, no a este. El panel del navegador carga las páginas localmente, así que un servidor de desarrollo remoto necesita un reenvío de puertos o un nombre de host accesible.',+ failedToLoad: 'No se pudo cargar la vista previa',+ tryAgain: 'Intentar de nuevo',+ restarting: 'Hermes se está reiniciando...',+ askRestart: 'Pedir a Hermes que reinicie el servidor',+ lookingRestart: taskId => `Hermes está buscando un servidor de vista previa para reiniciar (${taskId})`,+ restartingTitle: 'Reiniciando servidor de vista previa',+ restartingMessage: 'Hermes está trabajando en segundo plano. Mira la consola de vista previa para ver el progreso.',+ startRestartFailed: message => `No se pudo iniciar el reinicio del servidor: ${message}`,+ restartFailed: 'Falló el reinicio del servidor',+ hideConsole: 'Ocultar consola de vista previa',+ showConsole: 'Mostrar consola de vista previa',+ hideDevTools: 'Ocultar DevTools de vista previa',+ openDevTools: 'Abrir DevTools de vista previa',+ goBack: 'Atrás',+ goForward: 'Adelante',+ reload: 'Recargar página',+ address: 'Dirección',+ addressPlaceholder: 'Introduce una dirección',+ blankPageBody: 'Escribe una dirección arriba para navegar o pide a Hermes que abra una página.',+ finishedRestarting: message =>+ `Hermes terminó de reiniciar el servidor de vista previa${message ? `: ${message}` : ''}`,+ failedRestarting: message => `Falló el reinicio del servidor: ${message}`,+ unknownError: 'error desconocido',+ restartedTitle: 'Servidor de vista previa reiniciado',+ reloadingNow: 'Recargando la vista previa ahora.',+ restartFailedTitle: 'Falló el reinicio de la vista previa',+ restartFailedMessage: 'Hermes no pudo reiniciar el servidor.',+ stillWorking:+ 'Hermes sigue trabajando, pero aún no llegó ningún resultado de reinicio. Puede que el comando del servidor siga en primer plano.',+ workspaceReloading: 'El espacio de trabajo cambió, recargando vista previa',+ fileChanged: url => `Archivo cambiado, recargando vista previa: ${url}`,+ filesChanged: (count, url) => `${count} cambios de archivo, recargando vista previa: ${url}`,+ watchFailed: message => `No se pudo vigilar el archivo de vista previa: ${message}`,+ moduleMimeDescription:+ 'Los scripts de módulo se están sirviendo con el tipo MIME incorrecto. Normalmente significa que un servidor de archivos estáticos sirve una app Vite/React en lugar del dev server del proyecto.',+ loadFailedConsole: (code, message) => `Carga fallida${code ? ` (${code})` : ''}: ${message}`,+ unreachableDescription: 'No se pudo acceder a la página de vista previa.',+ openTarget: url => `Abrir ${url}`,+ fallbackTitle: 'Vista previa',+ annotate: 'Anotar',+ annotateOn: 'Dejar de anotar',+ annotateNeedPage: 'Primero abre una página en el navegador integrado.',+ annotateFailed: 'No se pudo iniciar el modo de anotación',+ commenting: 'Comentando',+ addComments: (count: number) => (count === 1 ? 'Añadir 1 comentario' : `Añadir ${count} comentarios`),+ commentPlaceholder: 'Añade un comentario...',+ commentTitle: (n: number) => `Comentario ${n}`,+ saveComment: 'Guardar',+ cancelComment: 'Cancelar comentario'+}diff --git a/apps/desktop/src/i18n/fr.ts b/apps/desktop/src/i18n/fr.tsindex cd089f49f04..539bcc970b1 100644--- a/apps/desktop/src/i18n/fr.ts+++ b/apps/desktop/src/i18n/fr.ts@@ -9,6 +9,7 @@ import { frConnectorCard } from './fr_connector_card'import { frErrorCodes } from './fr_error_codes'import { frErrorLayers } from './fr_error_layers'import { frFirstRun } from './fr_first_run'+import { frGatewayHost } from './fr_gateway_host'import { frLocalModels } from './fr_local_models'import { frModelMenu } from './fr_model_menu'import { frModelSettings } from './fr_model_settings'@@ -17,6 +18,7 @@ import { frNotifications } from './fr_notifications'import { frOnboarding } from './fr_onboarding'import { frPluginPreviewAccess } from './fr_plugin_preview_access'import { frPluginUpdate } from './fr_plugin_update'+import { frPreviewWeb } from './fr_preview_web'import { frProjects } from './fr_projects'import { frSharedMetrics } from './fr_shared_metrics'import { frThemePicker } from './fr_theme_picker'@@ -1684,8 +1686,7 @@ export const frOverrides = {},gateway: {loading: 'Chargement des paramètres du gateway...',- unavailableTitle: 'Paramètres du gateway indisponibles',- unavailableDesc: "Le pont IPC du desktop n'expose pas les paramètres du gateway.",+ ...frGatewayHost,title: 'Connexion au gateway',envOverride: "remplacement par variable d'environnement",intro:@@ -4723,61 +4724,7 @@ export const frOverrides = {sentTitle: 'Envoyé à la conversation',sentMessage: count => `Ajout au compositeur : ${count} message${count === 1 ? '' : 's'} de console`},- web: {- appFailedToBoot: "Échec du démarrage de l'application d'aperçu",- serverNotFound: 'Serveur non trouvé',- remoteLoopback:- "Cette adresse pointe vers la machine qui exécute votre agent, pas vers celle-ci. Le panneau du navigateur charge les pages localement ; un serveur de développement distant nécessite donc une redirection de port ou un nom d'hôte accessible.",- failedToLoad: "Échec du chargement de l'aperçu",- tryAgain: 'Réessayer',- restarting: 'Hermes redémarre...',- askRestart: 'Demander à Hermes de redémarrer le serveur',- lookingRestart: taskId => `Hermes recherche un serveur d'aperçu à redémarrer (${taskId})`,- restartingTitle: "Redémarrage du serveur d'aperçu",- restartingMessage: "Hermes travaille en arrière-plan. Surveillez la console d'aperçu pour suivre la progression.",- startRestartFailed: message => `Impossible de démarrer le redémarrage du serveur : ${message}`,- restartFailed: 'Échec du redémarrage du serveur',- hideConsole: "Masquer la console d'aperçu",- showConsole: "Afficher la console d'aperçu",- hideDevTools: "Masquer les outils de développement d'aperçu",- openDevTools: "Ouvrir les outils de développement d'aperçu",- goBack: 'Retour',- goForward: 'Suivant',- reload: 'Recharger la page',- address: 'Adresse',- addressPlaceholder: 'Saisir une adresse',- blankPageBody: "Saisissez une adresse ci-dessus pour naviguer, ou demandez à Hermes d'ouvrir une page.",- finishedRestarting: message =>- `Hermes a terminé le redémarrage du serveur d'aperçu${message ? `: ${message}` : ''}`,- failedRestarting: message => `Échec du redémarrage du serveur : ${message}`,- unknownError: 'erreur inconnue',- restartedTitle: "Serveur d'aperçu redémarré",- reloadingNow: "Rechargement de l'aperçu maintenant.",- restartFailedTitle: "Échec du redémarrage de l'aperçu",- restartFailedMessage: "Hermes n'a pas pu redémarrer le serveur.",- stillWorking:- "Hermes travaille toujours, mais aucun résultat de redémarrage n'est arrivé. La commande du serveur peut être en cours d'exécution au premier plan.",- workspaceReloading: "Espace de travail modifié, rechargement de l'aperçu",- fileChanged: url => `Fichier modifié, rechargement de l'aperçu : ${url}`,- filesChanged: (count, url) => `${count} modifications de fichier, rechargement de l'aperçu : ${url}`,- watchFailed: message => `Impossible de surveiller le fichier d'aperçu : ${message}`,- moduleMimeDescription:- "Les scripts de module sont servis avec le mauvais type MIME. Cela signifie généralement qu'un serveur de fichiers statiques sert une application Vite/React au lieu du serveur de développement du projet.",- loadFailedConsole: (code, message) => `Échec du chargement${code ? ` (${code})` : ''} : ${message}`,- unreachableDescription: "La page d'aperçu n'a pas pu être atteinte.",- openTarget: url => `Ouvrir ${url}`,- fallbackTitle: 'Aperçu',- annotate: 'Annoter',- annotateOn: "Arrêter l'annotation",- annotateNeedPage: "Ouvrez d'abord une page dans le navigateur intégré.",- annotateFailed: "Impossible de démarrer le mode d'annotation",- commenting: 'Ajout de commentaires',- addComments: count => (count === 1 ? 'Ajouter 1 commentaire' : `Ajouter ${count} commentaires`),- commentPlaceholder: 'Ajouter un commentaire...',- commentTitle: n => `Commentaire ${n}`,- saveComment: 'Enregistrer',- cancelComment: 'Annuler le commentaire'- }+ web: frPreviewWeb},interfaceMode: {title: 'Mode d’interface',diff --git a/apps/desktop/src/i18n/fr_gateway_host.ts b/apps/desktop/src/i18n/fr_gateway_host.tsnew file mode 100644index 00000000000..efca00f3e0a--- /dev/null+++ b/apps/desktop/src/i18n/fr_gateway_host.ts@@ -0,0 +1,10 @@+import type { GatewayHostTranslations } from './types_gateway_host'++// Settings → Gateways copy where the connection cannot change, spread into fr.ts.+export const frGatewayHost: GatewayHostTranslations = {+ unavailableTitle: 'Paramètres du gateway indisponibles',+ unavailableDesc: "Le pont IPC du desktop n'expose pas les paramètres du gateway.",+ webappHostTitle: 'Hôte Hermes',+ webappHostDesc:+ "La Webapp utilise toujours l'hôte Hermes qui la sert. Pour changer de gateway, vous connecter à Hermes Cloud ou gérer les connexions enregistrées, utilisez l'application Hermes Desktop."+}diff --git a/apps/desktop/src/i18n/fr_preview_web.ts b/apps/desktop/src/i18n/fr_preview_web.tsnew file mode 100644index 00000000000..ecb2611441a--- /dev/null+++ b/apps/desktop/src/i18n/fr_preview_web.ts@@ -0,0 +1,61 @@+import type { TranslationOverride } from '@hermes/shared/i18n'++import type { Translations } from './types'++// The in-app browser pane's copy (`preview.web`), composed by fr.ts.+export const frPreviewWeb: TranslationOverride<Translations['preview']['web']> = {+ embeddedPreviewHint:+ "Certains sites bloquent les aperçus intégrés. Ouvrez la page d'origine dans un onglet du navigateur.",+ appFailedToBoot: "Échec du démarrage de l'application d'aperçu",+ serverNotFound: 'Serveur non trouvé',+ remoteLoopback:+ "Cette adresse pointe vers la machine qui exécute votre agent, pas vers celle-ci. Le panneau du navigateur charge les pages localement ; un serveur de développement distant nécessite donc une redirection de port ou un nom d'hôte accessible.",+ failedToLoad: "Échec du chargement de l'aperçu",+ tryAgain: 'Réessayer',+ restarting: 'Hermes redémarre...',+ askRestart: 'Demander à Hermes de redémarrer le serveur',+ lookingRestart: taskId => `Hermes recherche un serveur d'aperçu à redémarrer (${taskId})`,+ restartingTitle: "Redémarrage du serveur d'aperçu",+ restartingMessage: "Hermes travaille en arrière-plan. Surveillez la console d'aperçu pour suivre la progression.",+ startRestartFailed: message => `Impossible de démarrer le redémarrage du serveur : ${message}`,+ restartFailed: 'Échec du redémarrage du serveur',+ hideConsole: "Masquer la console d'aperçu",+ showConsole: "Afficher la console d'aperçu",+ hideDevTools: "Masquer les outils de développement d'aperçu",+ openDevTools: "Ouvrir les outils de développement d'aperçu",+ goBack: 'Retour',+ goForward: 'Suivant',+ reload: 'Recharger la page',+ address: 'Adresse',+ addressPlaceholder: 'Saisir une adresse',+ blankPageBody: "Saisissez une adresse ci-dessus pour naviguer, ou demandez à Hermes d'ouvrir une page.",+ finishedRestarting: message => `Hermes a terminé le redémarrage du serveur d'aperçu${message ? `: ${message}` : ''}`,+ failedRestarting: message => `Échec du redémarrage du serveur : ${message}`,+ unknownError: 'erreur inconnue',+ restartedTitle: "Serveur d'aperçu redémarré",+ reloadingNow: "Rechargement de l'aperçu maintenant.",+ restartFailedTitle: "Échec du redémarrage de l'aperçu",+ restartFailedMessage: "Hermes n'a pas pu redémarrer le serveur.",+ stillWorking:+ "Hermes travaille toujours, mais aucun résultat de redémarrage n'est arrivé. La commande du serveur peut être en cours d'exécution au premier plan.",+ workspaceReloading: "Espace de travail modifié, rechargement de l'aperçu",+ fileChanged: url => `Fichier modifié, rechargement de l'aperçu : ${url}`,+ filesChanged: (count, url) => `${count} modifications de fichier, rechargement de l'aperçu : ${url}`,+ watchFailed: message => `Impossible de surveiller le fichier d'aperçu : ${message}`,+ moduleMimeDescription:+ "Les scripts de module sont servis avec le mauvais type MIME. Cela signifie généralement qu'un serveur de fichiers statiques sert une application Vite/React au lieu du serveur de développement du projet.",+ loadFailedConsole: (code, message) => `Échec du chargement${code ? ` (${code})` : ''} : ${message}`,+ unreachableDescription: "La page d'aperçu n'a pas pu être atteinte.",+ openTarget: url => `Ouvrir ${url}`,+ fallbackTitle: 'Aperçu',+ annotate: 'Annoter',+ annotateOn: "Arrêter l'annotation",+ annotateNeedPage: "Ouvrez d'abord une page dans le navigateur intégré.",+ annotateFailed: "Impossible de démarrer le mode d'annotation",+ commenting: 'Ajout de commentaires',+ addComments: count => (count === 1 ? 'Ajouter 1 commentaire' : `Ajouter ${count} commentaires`),+ commentPlaceholder: 'Ajouter un commentaire...',+ commentTitle: n => `Commentaire ${n}`,+ saveComment: 'Enregistrer',+ cancelComment: 'Annuler le commentaire'+}diff --git a/apps/desktop/src/i18n/ja.ts b/apps/desktop/src/i18n/ja.tsindex b79975b60ae..5b4c66d2954 100644--- a/apps/desktop/src/i18n/ja.ts+++ b/apps/desktop/src/i18n/ja.ts@@ -10,6 +10,7 @@ import { jaConnectors } from './ja_connectors'import { jaErrorCodes } from './ja_error_codes'import { jaErrorLayers } from './ja_error_layers'import { jaFirstRun } from './ja_first_run'+import { jaGatewayHost } from './ja_gateway_host'import { jaLocalModels } from './ja_local_models'import { jaModelMenu } from './ja_model_menu'import { jaModelSettings } from './ja_model_settings'@@ -18,6 +19,7 @@ import { jaNotifications } from './ja_notifications'import { jaOnboarding } from './ja_onboarding'import { jaPluginPreviewAccess } from './ja_plugin_preview_access'import { jaPluginSettings, jaPluginsTab } from './ja_plugins'+import { jaPreviewWeb } from './ja_preview_web'import { jaProjects } from './ja_projects'import { jaSharedMetrics } from './ja_shared_metrics'import { jaThemePicker } from './ja_theme_picker'@@ -984,8 +986,7 @@ export const jaOverrides = {},gateway: {loading: 'ゲートウェイ設定を読み込み中...',- unavailableTitle: 'ゲートウェイ設定は利用できません',- unavailableDesc: 'デスクトップ IPC ブリッジはゲートウェイ設定を公開していません。',+ ...jaGatewayHost,title: 'ゲートウェイ接続',envOverride: 'env オーバーライド',intro:@@ -3135,51 +3136,7 @@ export const jaOverrides = {sentTitle: 'チャットに送信しました',sentMessage: count => `${count} 件のログエントリーがコンポーザーに追加されました`},- web: {- appFailedToBoot: 'プレビューアプリの起動に失敗しました',- serverNotFound: 'サーバーが見つかりません',- remoteLoopback:- 'このアドレスはエージェントを実行しているマシンを指しており、このマシンではありません。ブラウザペインはページをローカルで読み込むため、リモートの開発サーバーにはポート転送か到達可能なホスト名が必要です。',- failedToLoad: 'プレビューの読み込みに失敗しました',- tryAgain: '再試行',- restarting: 'Hermes を再起動中...',- askRestart: 'Hermes にサーバーの再起動を依頼',- lookingRestart: taskId => `Hermes は再起動するプレビューサーバーを検索中です (${taskId})`,- restartingTitle: 'プレビューサーバーを再起動中',- restartingMessage: 'Hermes はバックグラウンドで作業中です。進捗はプレビューコンソールで確認してください。',- startRestartFailed: message => `サーバー再起動を開始できませんでした: ${message}`,- restartFailed: 'サーバーの再起動に失敗しました',- hideConsole: 'プレビューコンソールを非表示',- showConsole: 'プレビューコンソールを表示',- hideDevTools: 'プレビュー DevTools を非表示',- openDevTools: 'プレビュー DevTools を開く',- goBack: '戻る',- goForward: '進む',- reload: 'ページを再読み込み',- address: 'アドレス',- addressPlaceholder: 'アドレスを入力',- blankPageBody: '上のアドレス欄に入力するか、Hermes にページを開くよう頼んでください。',- finishedRestarting: message =>- `Hermes がプレビューサーバーの再起動を完了しました${message ? `: ${message}` : ''}`,- failedRestarting: message => `サーバーの再起動に失敗しました: ${message}`,- unknownError: '不明なエラー',- restartedTitle: 'プレビューサーバーが再起動しました',- reloadingNow: 'プレビューを再読み込み中です。',- restartFailedTitle: 'プレビューの再起動に失敗しました',- restartFailedMessage: 'Hermes がサーバーを再起動できませんでした。',- stillWorking:- 'Hermes はまだ作業中ですが、再起動の結果がまだ届いていません。サーバーコマンドがフォアグラウンドで実行されている可能性があります。',- workspaceReloading: 'ワークスペースが変更され、プレビューを再読み込み中',- fileChanged: url => `ファイルが変更され、プレビューを再読み込み中: ${url}`,- filesChanged: (count, url) => `${count} 件のファイルが変更され、プレビューを再読み込み中: ${url}`,- watchFailed: message => `プレビューファイルを監視できませんでした: ${message}`,- moduleMimeDescription:- 'モジュールスクリプトが間違った MIME タイプで提供されています。通常、静的ファイルサーバーがプロジェクトの開発サーバーの代わりに Vite/React アプリを提供していることを意味します。',- loadFailedConsole: (code, message) => `読み込みに失敗しました${code ? ` (${code})` : ''}: ${message}`,- unreachableDescription: 'プレビューページに到達できませんでした。',- openTarget: url => `${url} を開く`,- fallbackTitle: 'プレビュー'- }+ web: jaPreviewWeb},interfaceMode: {diff --git a/apps/desktop/src/i18n/ja_gateway_host.ts b/apps/desktop/src/i18n/ja_gateway_host.tsnew file mode 100644index 00000000000..12cf15f3951--- /dev/null+++ b/apps/desktop/src/i18n/ja_gateway_host.ts@@ -0,0 +1,10 @@+import type { GatewayHostTranslations } from './types_gateway_host'++// Settings → Gateways copy where the connection cannot change, spread into ja.ts.+export const jaGatewayHost: GatewayHostTranslations = {+ unavailableTitle: 'ゲートウェイ設定は利用できません',+ unavailableDesc: 'デスクトップ IPC ブリッジはゲートウェイ設定を公開していません。',+ webappHostTitle: 'Hermes ホスト',+ webappHostDesc:+ 'Webapp は常に配信元の Hermes ホストを使用します。ゲートウェイの切り替え、Hermes Cloud へのサインイン、保存済み接続の管理は Hermes Desktop アプリで行ってください。'+}diff --git a/apps/desktop/src/i18n/ja_preview_web.ts b/apps/desktop/src/i18n/ja_preview_web.tsnew file mode 100644index 00000000000..d618fbc8222--- /dev/null+++ b/apps/desktop/src/i18n/ja_preview_web.ts@@ -0,0 +1,50 @@+import type { TranslationOverride } from '@hermes/shared/i18n'++import type { Translations } from './types'++// The in-app browser pane's copy (`preview.web`), composed by ja.ts.+export const jaPreviewWeb: TranslationOverride<Translations['preview']['web']> = {+ embeddedPreviewHint: '埋め込みプレビューを許可しないサイトもあります。元のページをブラウザーのタブで開いてください。',+ appFailedToBoot: 'プレビューアプリの起動に失敗しました',+ serverNotFound: 'サーバーが見つかりません',+ remoteLoopback:+ 'このアドレスはエージェントを実行しているマシンを指しており、このマシンではありません。ブラウザペインはページをローカルで読み込むため、リモートの開発サーバーにはポート転送か到達可能なホスト名が必要です。',+ failedToLoad: 'プレビューの読み込みに失敗しました',+ tryAgain: '再試行',+ restarting: 'Hermes を再起動中...',+ askRestart: 'Hermes にサーバーの再起動を依頼',+ lookingRestart: taskId => `Hermes は再起動するプレビューサーバーを検索中です (${taskId})`,+ restartingTitle: 'プレビューサーバーを再起動中',+ restartingMessage: 'Hermes はバックグラウンドで作業中です。進捗はプレビューコンソールで確認してください。',+ startRestartFailed: message => `サーバー再起動を開始できませんでした: ${message}`,+ restartFailed: 'サーバーの再起動に失敗しました',+ hideConsole: 'プレビューコンソールを非表示',+ showConsole: 'プレビューコンソールを表示',+ hideDevTools: 'プレビュー DevTools を非表示',+ openDevTools: 'プレビュー DevTools を開く',+ goBack: '戻る',+ goForward: '進む',+ reload: 'ページを再読み込み',+ address: 'アドレス',+ addressPlaceholder: 'アドレスを入力',+ blankPageBody: '上のアドレス欄に入力するか、Hermes にページを開くよう頼んでください。',+ finishedRestarting: message => `Hermes がプレビューサーバーの再起動を完了しました${message ? `: ${message}` : ''}`,+ failedRestarting: message => `サーバーの再起動に失敗しました: ${message}`,+ unknownError: '不明なエラー',+ restartedTitle: 'プレビューサーバーが再起動しました',+ reloadingNow: 'プレビューを再読み込み中です。',+ restartFailedTitle: 'プレビューの再起動に失敗しました',+ restartFailedMessage: 'Hermes がサーバーを再起動できませんでした。',+ stillWorking:+ 'Hermes はまだ作業中ですが、再起動の結果がまだ届いていません。サーバーコマンドがフォアグラウンドで実行されている可能性があります。',+ workspaceReloading: 'ワークスペースが変更され、プレビューを再読み込み中',+ fileChanged: url => `ファイルが変更され、プレビューを再読み込み中: ${url}`,+ filesChanged: (count, url) => `${count} 件のファイルが変更され、プレビューを再読み込み中: ${url}`,+ watchFailed: message => `プレビューファイルを監視できませんでした: ${message}`,+ moduleMimeDescription:+ 'モジュールスクリプトが間違った MIME タイプで提供されています。通常、静的ファイルサーバーがプロジェクトの開発サーバーの代わりに Vite/React アプリを提供していることを意味します。',+ loadFailedConsole: (code, message) => `読み込みに失敗しました${code ? ` (${code})` : ''}: ${message}`,+ unreachableDescription: 'プレビューページに到達できませんでした。',+ openTarget: url => `${url} を開く`,+ fallbackTitle: 'プレビュー'+}diff --git a/apps/desktop/src/i18n/ru.ts b/apps/desktop/src/i18n/ru.tsindex 68763dd2504..a85f52d51f6 100644--- a/apps/desktop/src/i18n/ru.ts+++ b/apps/desktop/src/i18n/ru.ts@@ -8,6 +8,7 @@ import { ruClarify } from './ru_clarify'import { ruConnectors } from './ru_connectors'import { ruErrorCodes } from './ru_error_codes'import { ruFirstRun } from './ru_first_run'+import { ruGatewayHost } from './ru_gateway_host'import { ruModelMenu } from './ru_model_menu'import { ruModelSettings } from './ru_model_settings'import { ruNotices } from './ru_notices'@@ -15,32 +16,13 @@ import { ruNotifications } from './ru_notifications'import { ruOnboarding } from './ru_onboarding'import { ruPluginPreviewAccess } from './ru_plugin_preview_access'import { ruPluginSettings, ruPluginsTab } from './ru_plugins'+import { RU_NOUN, RU_PLURAL } from './ru_plural'+import { ruPreviewWeb } from './ru_preview_web'import { ruProjects } from './ru_projects'import { ruSharedMetrics } from './ru_shared_metrics'import { ruThemePicker } from './ru_theme_picker'import { ruUpdateChannel } from './ru_update_channel'-// RU_PLURAL: (count, one, few, many) — русские формы сущ. падежа-// RU_NOUN: (count, one, few, many) — формы род. множественного-// count может быть number или string (часть подписей en.ts передаёт строки)-const ruNum = (count: number | string) => (typeof count === 'string' ? Number(count) || 0 : count)--const RU_PLURAL = (count: number | string, one: string, few: string, many: string) => {- const c = ruNum(count)- const n = Math.abs(c) % 10- const nn = Math.abs(c) % 100-- return n === 1 && nn !== 11 ? one : n >= 2 && n <= 4 && (nn < 12 || nn > 14) ? few : many-}--const RU_NOUN = (count: number | string, one: string, few: string, many: string) => {- const c = ruNum(count)- const n = Math.abs(c) % 10- const nn = Math.abs(c) % 100-- return n === 1 && nn !== 11 ? one : n >= 2 && n <= 4 && (nn < 12 || nn > 14) ? few : many-}-export const ruOverrides = {catalog: ruCatalog,connectors: ruConnectors.connectors,@@ -1079,8 +1061,7 @@ export const ruOverrides = {},gateway: {loading: 'Загрузка настроек шлюза…',- unavailableTitle: 'Настройки шлюза недоступны',- unavailableDesc: 'IPC-мост приложения не предоставляет настройки шлюза.',+ ...ruGatewayHost,title: 'Подключение шлюза',envOverride: 'переопределение переменными окружения',intro:@@ -3404,51 +3385,7 @@ export const ruOverrides = {sentMessage: count =>`${count} ${RU_NOUN(count, 'запись лога', 'записи лога', 'записей лога')} добавлено в композер`},- web: {- appFailedToBoot: 'Приложение предпросмотра не запустилось',- serverNotFound: 'Сервер не найден',- remoteLoopback:- 'Этот адрес указывает на машину, на которой работает ваш агент, а не на эту. Панель браузера загружает страницы локально, поэтому для удалённого dev-сервера нужен порт-форвардинг или доступный hostname.',- failedToLoad: 'Не удалось загрузить предпросмотр',- tryAgain: 'Попробовать снова',- restarting: 'Hermes перезапускается...',- askRestart: 'Попросить Hermes перезапустить сервер',- lookingRestart: taskId => `Hermes ищет сервер предпросмотра для перезапуска (${taskId})`,- restartingTitle: 'Перезапуск сервера предпросмотра',- restartingMessage: 'Hermes работает в фоне. Следите за прогрессом в консоли предпросмотра.',- startRestartFailed: message => `Не удалось запустить перезапуск сервера: ${message}`,- restartFailed: 'Перезапуск сервера не удался',- hideConsole: 'Скрыть консоль предпросмотра',- showConsole: 'Показать консоль предпросмотра',- hideDevTools: 'Скрыть DevTools предпросмотра',- openDevTools: 'Открыть DevTools предпросмотра',- goBack: 'Назад',- goForward: 'Вперёд',- reload: 'Перезагрузить страницу',- address: 'Адрес',- addressPlaceholder: 'Введите адрес',- blankPageBody: 'Введите адрес выше, чтобы просматривать, или попросите Hermes открыть страницу.',- finishedRestarting: message => `Hermes завершил перезапуск сервера предпросмотра${message ? `: ${message}` : ''}`,- failedRestarting: message => `Перезапуск сервера не удался: ${message}`,- unknownError: 'неизвестная ошибка',- restartedTitle: 'Сервер предпросмотра перезапущен',- reloadingNow: 'Перезагружаем предпросмотр.',- restartFailedTitle: 'Перезапуск предпросмотра не удался',- restartFailedMessage: 'Hermes не смог перезапустить сервер.',- stillWorking:- 'Hermes всё ещё работает, но результата перезапуска пока нет. Команда сервера может выполняться в foreground.',- workspaceReloading: 'Рабочее пространство изменилось, перезагружаем предпросмотр',- fileChanged: url => `Файл изменился, перезагружаем предпросмотр: ${url}`,- filesChanged: (count, url) =>- `${count} ${RU_NOUN(count, 'изменение файла', 'изменения файла', 'изменений файла')}, перезагружаем предпросмотр: ${url}`,- watchFailed: message => `Не удалось отслеживать файл предпросмотра: ${message}`,- moduleMimeDescription:- 'Модульные скрипты раздаются с неверным MIME-типом. Обычно это значит, что статический файл-сервер раздаёт Vite/React-приложение вместо dev-сервера проекта.',- loadFailedConsole: (code, message) => `Не удалось загрузить${code ? ` (${code})` : ''}: ${message}`,- unreachableDescription: 'Страница предпросмотра недоступна.',- openTarget: url => `Открыть ${url}`,- fallbackTitle: 'Предпросмотр'- }+ web: ruPreviewWeb},interfaceMode: {title: 'Режим интерфейса',diff --git a/apps/desktop/src/i18n/ru_gateway_host.ts b/apps/desktop/src/i18n/ru_gateway_host.tsnew file mode 100644index 00000000000..8d9c5645c54--- /dev/null+++ b/apps/desktop/src/i18n/ru_gateway_host.ts@@ -0,0 +1,10 @@+import type { GatewayHostTranslations } from './types_gateway_host'++// Settings → Gateways copy where the connection cannot change, spread into ru.ts.+export const ruGatewayHost: GatewayHostTranslations = {+ unavailableTitle: 'Настройки шлюза недоступны',+ unavailableDesc: 'IPC-мост приложения не предоставляет настройки шлюза.',+ webappHostTitle: 'Хост Hermes',+ webappHostDesc:+ 'Webapp всегда использует хост Hermes, который его обслуживает. Чтобы сменить шлюз, войти в Hermes Cloud или управлять сохранёнными подключениями, используйте приложение Hermes Desktop.'+}diff --git a/apps/desktop/src/i18n/ru_plural.ts b/apps/desktop/src/i18n/ru_plural.tsnew file mode 100644index 00000000000..e9461a241ac--- /dev/null+++ b/apps/desktop/src/i18n/ru_plural.ts@@ -0,0 +1,21 @@+// Shared by ru.ts and its sibling overlays.+// RU_PLURAL: (count, one, few, many) — русские формы сущ. падежа+// RU_NOUN: (count, one, few, many) — формы род. множественного+// count может быть number или string (часть подписей en.ts передаёт строки)+const ruNum = (count: number | string) => (typeof count === 'string' ? Number(count) || 0 : count)++export const RU_PLURAL = (count: number | string, one: string, few: string, many: string) => {+ const c = ruNum(count)+ const n = Math.abs(c) % 10+ const nn = Math.abs(c) % 100++ return n === 1 && nn !== 11 ? one : n >= 2 && n <= 4 && (nn < 12 || nn > 14) ? few : many+}++export const RU_NOUN = (count: number | string, one: string, few: string, many: string) => {+ const c = ruNum(count)+ const n = Math.abs(c) % 10+ const nn = Math.abs(c) % 100++ return n === 1 && nn !== 11 ? one : n >= 2 && n <= 4 && (nn < 12 || nn > 14) ? few : many+}diff --git a/apps/desktop/src/i18n/ru_preview_web.ts b/apps/desktop/src/i18n/ru_preview_web.tsnew file mode 100644index 00000000000..37576d27e2f--- /dev/null+++ b/apps/desktop/src/i18n/ru_preview_web.ts@@ -0,0 +1,53 @@+import type { TranslationOverride } from '@hermes/shared/i18n'++import { RU_NOUN } from './ru_plural'+import type { Translations } from './types'++// The in-app browser pane's copy (`preview.web`), composed by ru.ts.+export const ruPreviewWeb: TranslationOverride<Translations['preview']['web']> = {+ embeddedPreviewHint:+ 'Некоторые сайты блокируют встроенный предпросмотр. Откройте исходную страницу во вкладке браузера.',+ appFailedToBoot: 'Приложение предпросмотра не запустилось',+ serverNotFound: 'Сервер не найден',+ remoteLoopback:+ 'Этот адрес указывает на машину, на которой работает ваш агент, а не на эту. Панель браузера загружает страницы локально, поэтому для удалённого dev-сервера нужен порт-форвардинг или доступный hostname.',+ failedToLoad: 'Не удалось загрузить предпросмотр',+ tryAgain: 'Попробовать снова',+ restarting: 'Hermes перезапускается...',+ askRestart: 'Попросить Hermes перезапустить сервер',+ lookingRestart: taskId => `Hermes ищет сервер предпросмотра для перезапуска (${taskId})`,+ restartingTitle: 'Перезапуск сервера предпросмотра',+ restartingMessage: 'Hermes работает в фоне. Следите за прогрессом в консоли предпросмотра.',+ startRestartFailed: message => `Не удалось запустить перезапуск сервера: ${message}`,+ restartFailed: 'Перезапуск сервера не удался',+ hideConsole: 'Скрыть консоль предпросмотра',+ showConsole: 'Показать консоль предпросмотра',+ hideDevTools: 'Скрыть DevTools предпросмотра',+ openDevTools: 'Открыть DevTools предпросмотра',+ goBack: 'Назад',+ goForward: 'Вперёд',+ reload: 'Перезагрузить страницу',+ address: 'Адрес',+ addressPlaceholder: 'Введите адрес',+ blankPageBody: 'Введите адрес выше, чтобы просматривать, или попросите Hermes открыть страницу.',+ finishedRestarting: message => `Hermes завершил перезапуск сервера предпросмотра${message ? `: ${message}` : ''}`,+ failedRestarting: message => `Перезапуск сервера не удался: ${message}`,+ unknownError: 'неизвестная ошибка',+ restartedTitle: 'Сервер предпросмотра перезапущен',+ reloadingNow: 'Перезагружаем предпросмотр.',+ restartFailedTitle: 'Перезапуск предпросмотра не удался',+ restartFailedMessage: 'Hermes не смог перезапустить сервер.',+ stillWorking:+ 'Hermes всё ещё работает, но результата перезапуска пока нет. Команда сервера может выполняться в foreground.',+ workspaceReloading: 'Рабочее пространство изменилось, перезагружаем предпросмотр',+ fileChanged: url => `Файл изменился, перезагружаем предпросмотр: ${url}`,+ filesChanged: (count, url) =>+ `${count} ${RU_NOUN(count, 'изменение файла', 'изменения файла', 'изменений файла')}, перезагружаем предпросмотр: ${url}`,+ watchFailed: message => `Не удалось отслеживать файл предпросмотра: ${message}`,+ moduleMimeDescription:+ 'Модульные скрипты раздаются с неверным MIME-типом. Обычно это значит, что статический файл-сервер раздаёт Vite/React-приложение вместо dev-сервера проекта.',+ loadFailedConsole: (code, message) => `Не удалось загрузить${code ? ` (${code})` : ''}: ${message}`,+ unreachableDescription: 'Страница предпросмотра недоступна.',+ openTarget: url => `Открыть ${url}`,+ fallbackTitle: 'Предпросмотр'+}diff --git a/apps/desktop/src/i18n/types.ts b/apps/desktop/src/i18n/types.tsindex ad53e33323e..b16c3b890a8 100644--- a/apps/desktop/src/i18n/types.ts+++ b/apps/desktop/src/i18n/types.ts@@ -19,6 +19,7 @@ import type { ConnectorAccountsTranslations, ConnectorCardTranslations } from '.import type { GatewayGroupOpenCopy, SkillDeepLinkCopy } from './types_deep_links'import type { ExternalOpenFailedCopy } from './types_external_open'import type { FirstRunCopy } from './types_first_run'+import type { GatewayHostTranslations } from './types_gateway_host'import type { ModelMenuTranslations } from './types_model_menu'import type { ModelSettingsTranslations } from './types_model_settings'import type { NoticeTranslations } from './types_notices'@@ -1129,10 +1130,8 @@ catalog: CatalogTranslationsscopesRestored: (profiles: string) => stringscopeNotRestored: (profile: string, error: string) => string}- gateway: {+ gateway: GatewayHostTranslations & {loading: string- unavailableTitle: string- unavailableDesc: stringtitle: stringenvOverride: stringintro: string@@ -3762,6 +3761,7 @@ catalog: CatalogTranslationssentMessage: (count: number) => string}web: {+ embeddedPreviewHint: stringappFailedToBoot: stringserverNotFound: stringremoteLoopback: stringdiff --git a/apps/desktop/src/i18n/types_gateway_host.ts b/apps/desktop/src/i18n/types_gateway_host.tsnew file mode 100644index 00000000000..779a28e31dd--- /dev/null+++ b/apps/desktop/src/i18n/types_gateway_host.ts@@ -0,0 +1,9 @@+// Settings → Gateways copy for a renderer that cannot change its connection: a Desktop whose+// bridge exposes no gateway settings, and the Webapp, bound to the host that serves it.+// `Translations['settings']['gateway']` spreads this in.+export interface GatewayHostTranslations {+ unavailableTitle: string+ unavailableDesc: string+ webappHostTitle: string+ webappHostDesc: string+}diff --git a/apps/desktop/src/i18n/zh-hant_artifacts.ts b/apps/desktop/src/i18n/zh-hant_artifacts.tsindex a8928fd8809..24bbebfa12e 100644--- a/apps/desktop/src/i18n/zh-hant_artifacts.ts+++ b/apps/desktop/src/i18n/zh-hant_artifacts.ts@@ -116,6 +116,7 @@ export const zhHantArtifacts = {sentMessage: count => `已將 ${count} 條記錄新增至輸入框`},web: {+ embeddedPreviewHint: '部分網站不允許嵌入式預覽。請在瀏覽器分頁中開啟原始頁面。',appFailedToBoot: '預覽應用程式啟動失敗',serverNotFound: '找不到伺服器',remoteLoopback:diff --git a/apps/desktop/src/i18n/zh-hant_settings.ts b/apps/desktop/src/i18n/zh-hant_settings.tsindex 467cca6dbbc..06ed52615e6 100644--- a/apps/desktop/src/i18n/zh-hant_settings.ts+++ b/apps/desktop/src/i18n/zh-hant_settings.ts@@ -869,6 +869,9 @@ export const zhHantSettings = {loading: '正在載入閘道設定...',unavailableTitle: '閘道設定不可用',unavailableDesc: '桌面 IPC 橋接器未公開閘道設定。',+ webappHostTitle: 'Hermes 主機',+ webappHostDesc:+ 'Webapp 一律使用提供它的 Hermes 主機。如需切換閘道、登入 Hermes Cloud 或管理已儲存的連線,請使用 Hermes Desktop 應用程式。',title: '閘道連線',envOverride: '環境變數覆寫',intro:diff --git a/apps/desktop/src/i18n/zh.ts b/apps/desktop/src/i18n/zh.tsindex 4c89aea3cf7..18c168f528a 100644--- a/apps/desktop/src/i18n/zh.ts+++ b/apps/desktop/src/i18n/zh.ts@@ -9,6 +9,7 @@ import { zhConnectorCard } from './zh_connector_card'import { zhErrorCodes } from './zh_error_codes'import { zhErrorLayers } from './zh_error_layers'import { zhFirstRun } from './zh_first_run'+import { zhGatewayHost } from './zh_gateway_host'import { zhLocalModels } from './zh_local_models'import { zhModelMenu } from './zh_model_menu'import { zhModelSettings } from './zh_model_settings'@@ -17,6 +18,7 @@ import { zhNotifications } from './zh_notifications'import { zhOnboarding } from './zh_onboarding'import { zhPluginPreviewAccess } from './zh_plugin_preview_access'import { zhPluginUpdate } from './zh_plugin_update'+import { zhPreviewWeb } from './zh_preview_web'import { zhProjects } from './zh_projects'import { zhSharedMetrics } from './zh_shared_metrics'import { zhThemePicker } from './zh_theme_picker'@@ -1384,8 +1386,7 @@ export const zhOverrides = {},gateway: {loading: '正在加载网关设置...',- unavailableTitle: '网关设置不可用',- unavailableDesc: '桌面 IPC 桥未暴露网关设置。',+ ...zhGatewayHost,title: '网关连接',envOverride: '环境变量覆盖',intro:@@ -4135,59 +4136,7 @@ export const zhOverrides = {sentTitle: '已发送到对话',sentMessage: count => `已将 ${count} 条日志添加到输入框`},- web: {- appFailedToBoot: '预览应用启动失败',- serverNotFound: '未找到服务器',- remoteLoopback:- '该地址指向运行代理的那台机器,而不是本机。浏览器面板在本地加载页面,因此远程开发服务器需要端口转发或可访问的主机名。',- failedToLoad: '预览加载失败',- tryAgain: '重试',- restarting: 'Hermes 正在重启...',- askRestart: '让 Hermes 重启服务器',- lookingRestart: taskId => `Hermes 正在查找要重启的预览服务器 (${taskId})`,- restartingTitle: '正在重启预览服务器',- restartingMessage: 'Hermes 正在后台工作。可在预览控制台查看进度。',- startRestartFailed: message => `无法启动服务器重启:${message}`,- restartFailed: '服务器重启失败',- hideConsole: '隐藏预览控制台',- showConsole: '显示预览控制台',- hideDevTools: '隐藏预览 DevTools',- openDevTools: '打开预览 DevTools',- goBack: '后退',- goForward: '前进',- reload: '重新加载页面',- address: '地址',- addressPlaceholder: '输入地址',- blankPageBody: '在上方输入地址开始浏览,或让 Hermes 打开一个页面。',- finishedRestarting: message => `Hermes 已完成预览服务器重启${message ? `: ${message}` : ''}`,- failedRestarting: message => `服务器重启失败:${message}`,- unknownError: '未知错误',- restartedTitle: '预览服务器已重启',- reloadingNow: '正在重新加载预览。',- restartFailedTitle: '预览重启失败',- restartFailedMessage: 'Hermes 无法重启服务器。',- stillWorking: 'Hermes 仍在工作,但还没有收到重启结果。服务器命令可能正在前台运行。',- workspaceReloading: '工作区已变更,正在重新加载预览',- fileChanged: url => `文件已变更,正在重新加载预览:${url}`,- filesChanged: (count, url) => `${count} 个文件变更,正在重新加载预览:${url}`,- watchFailed: message => `无法监听预览文件:${message}`,- moduleMimeDescription:- '模块脚本使用了错误的 MIME 类型。这通常表示静态文件服务器正在服务 Vite/React 应用,而不是项目开发服务器。',- loadFailedConsole: (code, message) => `加载失败${code ? ` (${code})` : ''}: ${message}`,- unreachableDescription: '无法访问预览页面。',- openTarget: url => `打开 ${url}`,- fallbackTitle: '预览',- annotate: '标注',- annotateOn: '停止标注',- annotateNeedPage: '请先在内置浏览器中打开页面。',- annotateFailed: '无法开始标注',- commenting: '标注中',- addComments: count => (count === 1 ? '添加 1 条批注' : `添加 ${count} 条批注`),- commentPlaceholder: '添加批注…',- commentTitle: n => `批注 ${n}`,- saveComment: '保存',- cancelComment: '取消批注'- }+ web: zhPreviewWeb},interfaceMode: {diff --git a/apps/desktop/src/i18n/zh_gateway_host.ts b/apps/desktop/src/i18n/zh_gateway_host.tsnew file mode 100644index 00000000000..bd36d12a2c2--- /dev/null+++ b/apps/desktop/src/i18n/zh_gateway_host.ts@@ -0,0 +1,10 @@+import type { GatewayHostTranslations } from './types_gateway_host'++// Settings → Gateways copy where the connection cannot change, spread into zh.ts.+export const zhGatewayHost: GatewayHostTranslations = {+ unavailableTitle: '网关设置不可用',+ unavailableDesc: '桌面 IPC 桥未暴露网关设置。',+ webappHostTitle: 'Hermes 主机',+ webappHostDesc:+ 'Webapp 始终使用提供它的 Hermes 主机。如需切换网关、登录 Hermes Cloud 或管理已保存的连接,请使用 Hermes Desktop 应用。'+}diff --git a/apps/desktop/src/i18n/zh_preview_web.ts b/apps/desktop/src/i18n/zh_preview_web.tsnew file mode 100644index 00000000000..4173bfbef80--- /dev/null+++ b/apps/desktop/src/i18n/zh_preview_web.ts@@ -0,0 +1,59 @@+import type { TranslationOverride } from '@hermes/shared/i18n'++import type { Translations } from './types'++// The in-app browser pane's copy (`preview.web`), composed by zh.ts.+export const zhPreviewWeb: TranslationOverride<Translations['preview']['web']> = {+ embeddedPreviewHint: '部分网站不允许嵌入式预览。请在浏览器标签页中打开原始页面。',+ appFailedToBoot: '预览应用启动失败',+ serverNotFound: '未找到服务器',+ remoteLoopback:+ '该地址指向运行代理的那台机器,而不是本机。浏览器面板在本地加载页面,因此远程开发服务器需要端口转发或可访问的主机名。',+ failedToLoad: '预览加载失败',+ tryAgain: '重试',+ restarting: 'Hermes 正在重启...',+ askRestart: '让 Hermes 重启服务器',+ lookingRestart: taskId => `Hermes 正在查找要重启的预览服务器 (${taskId})`,+ restartingTitle: '正在重启预览服务器',+ restartingMessage: 'Hermes 正在后台工作。可在预览控制台查看进度。',+ startRestartFailed: message => `无法启动服务器重启:${message}`,+ restartFailed: '服务器重启失败',+ hideConsole: '隐藏预览控制台',+ showConsole: '显示预览控制台',+ hideDevTools: '隐藏预览 DevTools',+ openDevTools: '打开预览 DevTools',+ goBack: '后退',+ goForward: '前进',+ reload: '重新加载页面',+ address: '地址',+ addressPlaceholder: '输入地址',+ blankPageBody: '在上方输入地址开始浏览,或让 Hermes 打开一个页面。',+ finishedRestarting: message => `Hermes 已完成预览服务器重启${message ? `: ${message}` : ''}`,+ failedRestarting: message => `服务器重启失败:${message}`,+ unknownError: '未知错误',+ restartedTitle: '预览服务器已重启',+ reloadingNow: '正在重新加载预览。',+ restartFailedTitle: '预览重启失败',+ restartFailedMessage: 'Hermes 无法重启服务器。',+ stillWorking: 'Hermes 仍在工作,但还没有收到重启结果。服务器命令可能正在前台运行。',+ workspaceReloading: '工作区已变更,正在重新加载预览',+ fileChanged: url => `文件已变更,正在重新加载预览:${url}`,+ filesChanged: (count, url) => `${count} 个文件变更,正在重新加载预览:${url}`,+ watchFailed: message => `无法监听预览文件:${message}`,+ moduleMimeDescription:+ '模块脚本使用了错误的 MIME 类型。这通常表示静态文件服务器正在服务 Vite/React 应用,而不是项目开发服务器。',+ loadFailedConsole: (code, message) => `加载失败${code ? ` (${code})` : ''}: ${message}`,+ unreachableDescription: '无法访问预览页面。',+ openTarget: url => `打开 ${url}`,+ fallbackTitle: '预览',+ annotate: '标注',+ annotateOn: '停止标注',+ annotateNeedPage: '请先在内置浏览器中打开页面。',+ annotateFailed: '无法开始标注',+ commenting: '标注中',+ addComments: count => (count === 1 ? '添加 1 条批注' : `添加 ${count} 条批注`),+ commentPlaceholder: '添加批注…',+ commentTitle: n => `批注 ${n}`,+ saveComment: '保存',+ cancelComment: '取消批注'+}diff --git a/apps/desktop/src/lib/base64.test.ts b/apps/desktop/src/lib/base64.test.tsnew file mode 100644index 00000000000..1e6f22d8018--- /dev/null+++ b/apps/desktop/src/lib/base64.test.ts@@ -0,0 +1,12 @@+import { describe, expect, it } from 'vitest'++import { bytesToBase64 } from './base64'++describe('bytesToBase64', () => {+ it('encodes ArrayBuffer and Uint8Array inputs through the same path', () => {+ const bytes = new Uint8Array([0x89, 0x50, 0x4e, 0x47])++ expect(bytesToBase64(bytes)).toBe('iVBORw==')+ expect(bytesToBase64(bytes.buffer)).toBe('iVBORw==')+ })+})diff --git a/apps/desktop/src/lib/base64.ts b/apps/desktop/src/lib/base64.tsnew file mode 100644index 00000000000..d4fc9302485--- /dev/null+++ b/apps/desktop/src/lib/base64.ts@@ -0,0 +1,23 @@+const BASE64_CHUNK_SIZE = 0x8000++export function bytesToBase64(value: ArrayBuffer | Uint8Array): string {+ const bytes = value instanceof Uint8Array ? value : new Uint8Array(value)+ let binary = ''++ for (let offset = 0; offset < bytes.length; offset += BASE64_CHUNK_SIZE) {+ binary += String.fromCharCode(...bytes.subarray(offset, offset + BASE64_CHUNK_SIZE))+ }++ return btoa(binary)+}++/** `data:<blob.type>;base64,…`, read asynchronously and encoded natively, without+ * the JS binary string `bytesToBase64` builds; use it for large payloads. */+export function blobToDataUrl(blob: Blob): Promise<string> {+ return new Promise((resolve, reject) => {+ const reader = new FileReader()+ reader.onload = () => resolve(String(reader.result))+ reader.onerror = () => reject(reader.error)+ reader.readAsDataURL(blob)+ })+}diff --git a/apps/desktop/src/lib/browser-bridge-stubs.ts b/apps/desktop/src/lib/browser-bridge-stubs.tsnew file mode 100644index 00000000000..831c5d4bf2c--- /dev/null+++ b/apps/desktop/src/lib/browser-bridge-stubs.ts@@ -0,0 +1,135 @@+import type { DesktopBootProgress, DesktopBootstrapState } from '@/global'++function noopUnsubscribe(): () => void {+ return () => undefined+}++function readyBootProgress(): DesktopBootProgress {+ return {+ error: null,+ fakeMode: false,+ message: 'Hermes browser-hosted desktop is ready',+ phase: 'runtime.ready',+ progress: 100,+ running: false,+ timestamp: Date.now()+ }+}++function readyBootstrapState(): DesktopBootstrapState {+ return {+ active: false,+ // A browser host never runs an in-app bundled payload.+ bundled: false,+ completedAt: Date.now(),+ error: null,+ log: [],+ manifest: null,+ setupChoice: null,+ stages: {},+ startedAt: null,+ unsupportedPlatform: null+ }+}++function browserUnsupported(feature: string): Error {+ return new Error(`${feature} is not available in the browser-hosted Desktop`)+}++// Bridge members that need no per-install state: native-only capabilities+// answered with a fixed browser result, a refusal, or a no-op.+export const BROWSER_BRIDGE_STUBS = {+ applyConnectionConfig: async () => {+ throw browserUnsupported('Gateway reconfiguration')+ },+ cancelBootstrap: async () => ({ cancelled: false, ok: true }),+ // Rendering an untrusted link must not contact its destination. PrettyLink+ // uses the URL slug when no title is available; Electron keeps its resolver.+ fetchLinkTitle: async () => '',+ claimAmbientCue: async () => true,+ cloud: {+ agentSignIn: async (dashboardUrl: string) => ({ baseUrl: dashboardUrl, connected: false }),+ discover: async () => ({ agents: [] }),+ login: async () => ({ ok: false, portalBaseUrl: '', signedIn: false }),+ logout: async () => ({ ok: true, portalBaseUrl: '', signedIn: false }),+ status: async () => ({ portalBaseUrl: '', signedIn: false })+ },+ continueBootstrapLocal: async () => ({ ok: true }),+ getBootProgress: async () => readyBootProgress(),+ getBootstrapState: async () => readyBootstrapState(),+ getRecentLogs: async () => ({ lines: [], path: '' }),+ // Venv/plugin receipts live on the server host; a browser tab has none of its own.+ getSyncStatus: async () => null,+ getRemoteDisplayReason: async () => 'Browser-hosted Desktop uses this server as its backend',+ windowControls: {+ custom: false,+ minimize: () => { throw browserUnsupported('Native window controls') },+ toggleMaximize: () => { throw browserUnsupported('Native window controls') },+ close: () => { throw browserUnsupported('Native window controls') }+ },+ getPathForFile: () => '',+ normalizePreviewTarget: async () => null,+ onBackendExit: noopUnsubscribe,+ onBootProgress: noopUnsubscribe,+ onBootstrapEvent: noopUnsubscribe,+ onFoundInPage: noopUnsubscribe,+ onPreviewFileChanged: noopUnsubscribe,+ probeConnectionConfig: async (remoteUrl: string) => ({+ authMode: 'unknown' as const,+ baseUrl: remoteUrl,+ error: 'Gateway reconfiguration is unavailable in browser-hosted Desktop',+ providers: [],+ reachable: false,+ version: null+ }),+ revealLogs: async () => ({+ error: 'Native log reveal is unavailable in browser-hosted Desktop',+ ok: false,+ path: ''+ }),+ repairBootstrap: async () => ({ ok: true }),+ resetBootstrap: async () => ({ ok: true }),+ revalidateConnection: async () => ({ ok: true, rebuilt: false }),+ saveConnectionConfig: async () => {+ throw browserUnsupported('Gateway reconfiguration')+ },+ sanitizeWorkspaceCwd: async (cwd?: null | string) => ({ cwd: cwd || '', sanitized: false }),+ sshConfigHosts: async () => ({ hosts: [] }),+ sshResolveHost: async () => ({ hostname: null, identityFile: null, port: null, user: null }),+ stopFindInPage: async () => undefined,+ stopPreviewFileWatch: async () => true,+ themes: {+ fetchMarketplace: async (id: string) => ({ displayName: id, extensionId: id, themes: [] }),+ searchMarketplace: async () => []+ },+ uninstall: {+ openAppsSettings: async () => undefined,+ run: async () => ({ error: 'Run `hermes uninstall` on the server host', ok: false }),+ summary: async () => ({+ agent_installed: true,+ // Package removal belongs to the server host, never this browser tab.+ code_removal_allowed: false,+ gui_installed: true,+ hermes_home: '',+ // No OS package owns a browser tab either: About shows no uninstall section.+ native_removal_instructions: null,+ packaged_app_paths: [],+ platform: 'browser',+ source_built_artifacts: [],+ userdata_dir: '',+ userdata_exists: true+ })+ },+ // Update holds are an Electron boot state; a browser boot never reports one.+ updateHold: {+ quit: async () => ({ ok: false }),+ recheck: async () => ({ ok: false }),+ startAnyway: async () => ({ ok: false })+ },+ updates: {+ apply: async () => ({ command: 'hermes update', manual: true, message: 'Run `hermes update` on the server host', ok: false }),+ check: async () => ({ message: 'Use `hermes update` on the server host', reason: 'browser-hosted', supported: false }),+ onProgress: noopUnsubscribe+ },+ watchPreviewFile: async (url: string) => ({ id: `browser:${url}`, path: url })+} satisfies Partial<Window['hermesDesktop']>diff --git a/apps/desktop/src/lib/browser-clipboard.ts b/apps/desktop/src/lib/browser-clipboard.tsnew file mode 100644index 00000000000..854e04f2fbd--- /dev/null+++ b/apps/desktop/src/lib/browser-clipboard.ts@@ -0,0 +1,47 @@+import { IMAGE_EXTENSION_BY_MIME } from '@/lib/browser-uploads'++interface BrowserClipboardOptions {+ /** Stores clipboard image bytes where the agent can read them. */+ saveBuffer: (data: ArrayBuffer | Uint8Array, ext: string) => Promise<string>+}++export function createBrowserClipboardBridge({+ saveBuffer+}: BrowserClipboardOptions): Pick<Window['hermesDesktop'], 'readClipboard' | 'saveClipboardImage' | 'writeClipboard'> {+ // Bound at install: installClipboardShim later routes navigator.clipboard.writeText+ // through writeClipboard, so a late lookup would call itself.+ const nativeWriteClipboard = navigator.clipboard?.writeText?.bind(navigator.clipboard)++ return {+ readClipboard: async () => navigator.clipboard?.readText?.() || '',+ saveClipboardImage: async () => {+ const clipboard = navigator.clipboard as Clipboard & {+ read?: () => Promise<ClipboardItems>+ }++ if (!clipboard?.read) {return ''}++ const items = await clipboard.read()++ for (const item of items) {+ const mimeType = item.types.find(type => type.startsWith('image/'))++ if (!mimeType) {continue}++ const blob = await item.getType(mimeType)+ const extension = IMAGE_EXTENSION_BY_MIME[mimeType] || '.png'++ return saveBuffer(await blob.arrayBuffer(), extension)+ }++ return ''+ },+ writeClipboard: async (text: string) => {+ if (!nativeWriteClipboard) {return false}++ await nativeWriteClipboard(text)++ return true+ }+ }+}diff --git a/apps/desktop/src/lib/browser-connection.ts b/apps/desktop/src/lib/browser-connection.tsnew file mode 100644index 00000000000..d499ccf6a5c--- /dev/null+++ b/apps/desktop/src/lib/browser-connection.ts@@ -0,0 +1,205 @@+import { LOCAL_CONNECTION_ID } from '@hermes/shared'++import type { HermesApiRequest, HermesConnection } from '@/global'+import { WEBAPP_LAUNCH_REQUIRED } from '@/lib/browser-launch-session'+import {+ type BrowserBootstrap,+ BrowserReauthRequiredError,+ endpointUrl,+ gatewaySocketUrl,+ gatewayWebsocketUrl,+ navigateToBrowserLogin+} from '@/lib/browser-transport'+import { windowProfileOverride } from '@/store/windows'++/** The serving origin is the only connection a browser-hosted Desktop has. */+export function requireBrowserConnection(connectionId?: null | string): void {+ const requested = connectionId?.trim() || LOCAL_CONNECTION_ID++ if (requested !== LOCAL_CONNECTION_ID) {+ throw new Error(`No connection with id "${requested}"`)+ }+}++function connectionFor(bootstrap: BrowserBootstrap, profile?: null | string): HermesConnection {+ if (!bootstrap.authRequired && !bootstrap.token) {throw new Error(WEBAPP_LAUNCH_REQUIRED)}++ const baseUrl = `${window.location.origin}${bootstrap.basePath}`++ return {+ authMode: bootstrap.authRequired ? 'oauth' : 'token',+ baseUrl,+ isFullscreen: Boolean(document.fullscreenElement),+ logs: [],+ mode: 'remote',+ nativeOverlayWidth: 0,+ profile: profile || undefined,+ remoteHost: window.location.host,+ remoteKind: 'url',+ sharedPrimary: Boolean(profile),+ source: 'settings',+ token: bootstrap.token,+ windowButtonPosition: null,+ // The serving gateway's canonical socket: credential-free here, every dial mints its own+ // ticket (getGatewayWsUrl). `native_dial` selects the canonical contract.+ wsUrl: gatewaySocketUrl(bootstrap, profile)+ }+}++function browserConnectionConfig(bootstrap: BrowserBootstrap, profile?: null | string) {+ return {+ cloudOrg: '',+ envOverride: false,+ mode: 'remote' as const,+ profile: profile || null,+ remoteAuthMode: bootstrap.authRequired ? ('oauth' as const) : ('token' as const),+ remoteOauthConnected: bootstrap.authRequired,+ remoteTokenPlainText: false,+ remoteTokenPreview: null,+ remoteTokenSet: Boolean(bootstrap.token),+ secureTokenStorage: false,+ remoteUrl: `${window.location.origin}${bootstrap.basePath}`,+ sshHost: '',+ sshKeyPath: '',+ sshPort: null,+ sshRemoteHermesPath: '',+ sshRemoteProfile: '',+ sshUser: ''+ }+}++interface BrowserConnectionOptions {+ api: <T>(request: HermesApiRequest) => Promise<T>+ bootstrap: BrowserBootstrap+}++/** Connection, gateway socket, roster and sign-in members, all bound to the serving origin. */+export function createBrowserConnectionBridge({ api, bootstrap }: BrowserConnectionOptions): Pick<+ Window['hermesDesktop'],+ | 'getAgentRoster'+ | 'getConnection'+ | 'getConnectionConfig'+ | 'getConnectionFor'+ | 'getGatewayWsUrl'+ | 'getGatewayWsUrlFor'+ | 'getProfileRoutes'+ | 'oauthLoginConnectionConfig'+ | 'oauthLogoutConnectionConfig'+ | 'testConnectionConfig'+> {+ // The window's own backend is the profile this tab booted on. A live switch+ // rewrites `?profile=` so a reload lands where the user is, but reconnecting+ // the window's primary socket must not follow it onto another profile.+ const windowProfile = windowProfileOverride()++ const getGatewayWsUrl = async (profile?: null | string) => {+ try {+ return {+ ok: true as const,+ wsUrl: await gatewayWebsocketUrl(bootstrap, profile)+ }+ } catch (error) {+ if (error instanceof BrowserReauthRequiredError) {+ return {+ error: error.message,+ needsOauthLogin: true,+ ok: false as const+ }+ }++ throw error+ }+ }++ const getProfiles = async () => {+ const result = await api<{ profiles?: { name?: string }[] }>({ path: '/api/profiles' })++ return [...new Set((result.profiles || []).map(profile => String(profile.name || '').trim()).filter(Boolean))]+ }++ return {+ getAgentRoster: async () => {+ const profiles = await getProfiles()+ const connectionLabel = window.location.host++ return {+ agents: profiles.map(profile => ({+ connectionId: LOCAL_CONNECTION_ID,+ connectionKind: 'local' as const,+ connectionLabel,+ handle: profile === 'default' ? 'hermes' : profile,+ profile,+ targetProfile: profile+ })),+ primaryConnectionId: LOCAL_CONNECTION_ID,+ sources: [{+ connectionId: LOCAL_CONNECTION_ID,+ kind: 'local' as const,+ label: connectionLabel,+ reachable: true+ }]+ }+ },+ // Reconnect belongs to the window, not whichever secondary profile is active.+ // Explicit null still selects the default backend.+ getConnection: async (profile: null | string = windowProfile) => connectionFor(bootstrap, profile),+ getConnectionConfig: async (profile?: null | string) => browserConnectionConfig(bootstrap, profile),+ getConnectionFor: async (payload: { connectionId?: null | string; profile?: null | string }) => {+ requireBrowserConnection(payload.connectionId)++ return {+ ...connectionFor(bootstrap, payload.profile),+ connectionId: LOCAL_CONNECTION_ID,+ registryScoped: true,+ sharedPrimary: false,+ sharedRemote: Boolean(payload.profile)+ }+ },+ getGatewayWsUrl,+ getGatewayWsUrlFor: async (payload: { connectionId?: null | string; profile?: null | string }) => {+ requireBrowserConnection(payload.connectionId)++ return getGatewayWsUrl(payload.profile)+ },+ getProfileRoutes: async (profiles: string[]) => {+ const available = new Set(await getProfiles())++ return [...new Set(profiles.map(profile => profile.trim() || 'default'))]+ .filter(profile => available.has(profile))+ .map(profile => ({+ connectionId: LOCAL_CONNECTION_ID,+ mode: 'local' as const,+ profile,+ targetProfile: profile+ }))+ },+ oauthLoginConnectionConfig: async (remoteUrl: string) => {+ const target = new URL(`${bootstrap.basePath}/login`, window.location.origin)+ target.searchParams.set('next', `${window.location.pathname}${window.location.search}${window.location.hash}`)+ navigateToBrowserLogin(new BrowserReauthRequiredError('Sign in required', target.href))++ return { baseUrl: remoteUrl, connected: false, ok: false }+ },+ oauthLogoutConnectionConfig: async () => {+ const response = await fetch(endpointUrl('/auth/logout', bootstrap.basePath), {+ credentials: 'same-origin',+ method: 'POST'+ })++ if (!response.ok) {+ throw new Error(`Sign out failed (${response.status})`)+ }++ const login = new URL(`${bootstrap.basePath}/login`, window.location.origin)+ navigateToBrowserLogin(new BrowserReauthRequiredError('Signed out', login.href))++ return { connected: false, ok: true }+ },+ testConnectionConfig: async () => ({+ baseUrl: `${window.location.origin}${bootstrap.basePath}`,+ ok: true,+ reachable: true,+ version: null+ })+ }+}diff --git a/apps/desktop/src/lib/browser-desktop-bridge-install.ts b/apps/desktop/src/lib/browser-desktop-bridge-install.tsnew file mode 100644index 00000000000..98c0226f44c--- /dev/null+++ b/apps/desktop/src/lib/browser-desktop-bridge-install.ts@@ -0,0 +1,6 @@+import { installBrowserDesktopBridge } from './browser-desktop-bridge'+import { installBrowserViewport } from './browser-viewport'++if (typeof window !== 'undefined' && installBrowserDesktopBridge()) {+ installBrowserViewport()+}diff --git a/apps/desktop/src/lib/browser-desktop-bridge-ownership-download.test.ts b/apps/desktop/src/lib/browser-desktop-bridge-ownership-download.test.tsnew file mode 100644index 00000000000..daf4b545f63--- /dev/null+++ b/apps/desktop/src/lib/browser-desktop-bridge-ownership-download.test.ts@@ -0,0 +1,262 @@+import { afterEach, expect, it, vi } from 'vitest'++import { setApiRequestConnection, setApiRequestProfile } from '@/api/client'+import { $notifications, clearNotifications } from '@/store/notifications'+import { $connection } from '@/store/session'+import { clearWebappSession, seedWebappSession } from '@/test/webapp-session'++import { installBrowserDesktopBridge } from './browser-desktop-bridge'+import { BROWSER_IMAGE_DOWNLOAD_MAX_BYTES, BROWSER_IMAGE_DOWNLOAD_TIMEOUT_MS } from './browser-image-download'+import { captureGatewayFileDownload } from './media'++it('keeps a captured download on its owning browser profile after a foreground switch', async () => {+ seedWebappSession('served-token')++ const fetchMock = vi.fn(async (input: URL, _init?: RequestInit) =>+ input.pathname === '/api/files/ticket'+ ? new Response(JSON.stringify({ ticket: 'file-ticket' }), { status: 200 })+ : new Response(null, { status: 200 })+ )++ vi.stubGlobal('fetch', fetchMock)+ const downloads: HTMLAnchorElement[] = []+ vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(function (this: HTMLAnchorElement) {+ downloads.push(this)+ })+ expect(installBrowserDesktopBridge()).toBe(true)+ setApiRequestConnection('local')+ setApiRequestProfile('file-owner')+ const download = captureGatewayFileDownload()+ setApiRequestProfile('foreground')+ $connection.set({ connectionId: 'local', mode: 'remote', profile: 'foreground' } as never)++ await download('file://nas/share/report.pdf', 'report.pdf')++ const [requestUrl, init] = fetchMock.mock.calls[0] as [URL, RequestInit]+ expect(init.method).toBe('HEAD')+ expect(requestUrl.searchParams.get('profile')).toBe('file-owner')+ expect(requestUrl.searchParams.get('path')).toBe('file://nas/share/report.pdf')+ expect(downloads).toHaveLength(1)+ const url = new URL(downloads[0].href)+ expect(url.searchParams.get('profile')).toBe('file-owner')+ expect(url.searchParams.get('path')).toBe('file://nas/share/report.pdf')+ expect(url.searchParams.get('ticket')).toBe('file-ticket')+ expect(JSON.parse(String(fetchMock.mock.calls[1][1]?.body))).toMatchObject({ profile: 'file-owner' })+ expect(downloads[0].download).toBe('report.pdf')+})++it.each([+ { name: 'exact byte ceiling', oversized: false, declaredLength: null },+ { name: 'oversized without Content-Length', oversized: true, declaredLength: null },+ { name: 'oversized with understated Content-Length', oversized: true, declaredLength: '1' }+])('bounds external image streams: $name', async ({ oversized, declaredLength }) => {+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })+ seedWebappSession('served-token')+ const limit = BROWSER_IMAGE_DOWNLOAD_MAX_BYTES+ const total = oversized ? 48 * 1024 * 1024 : limit+ let produced = 0+ const cancel = vi.fn()++ const body = new ReadableStream<Uint8Array>({+ pull(controller) {+ if (produced === total) {+ controller.close()++ return+ }++ const size = Math.min(total - produced, produced === limit ? 1 : 64 * 1024)+ controller.enqueue(new Uint8Array(size).fill(produced === 0 ? 7 : 9))+ produced += size+ },+ cancel+ }, { highWaterMark: 0 })++ const headers = new Headers({ 'content-type': 'image/png' })++ if (declaredLength !== null) {headers.set('content-length', declaredLength)}+ const response = new Response(body, { headers })+ const fetchMock = vi.fn().mockResolvedValue(response)+ vi.stubGlobal('fetch', fetchMock)+ const objectUrl = `blob:${window.location.origin}/download`+ const create = vi.spyOn(URL, 'createObjectURL').mockReturnValue(objectUrl)+ const revoke = vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => undefined)+ const clicked: string[] = []+ vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(function (this: HTMLAnchorElement) {+ clicked.push(this.href)+ })+ expect(installBrowserDesktopBridge()).toBe(true)+ await expect(win.hermesDesktop.saveImageFromUrl('https://images.example/image.png')).resolves.toBe(!oversized)+ const [url, init] = fetchMock.mock.calls[0] as [URL, RequestInit]+ expect(String(url)).toBe('https://images.example/image.png')+ expect(init.credentials).toBe('omit')+ expect(init.mode).toBe('cors')+ expect([...new Headers(init.headers)]).toEqual([])+ expect(body.locked).toBe(false)++ if (oversized) {+ expect(produced).toBe(limit + 1)+ expect(init.signal?.aborted).toBe(true)+ expect(cancel).toHaveBeenCalledOnce()+ expect(create).not.toHaveBeenCalled()+ expect(clicked).toEqual([])+ expect($notifications.get().at(-1)).toMatchObject({+ kind: 'error', title: 'Download failed', message: expect.stringMatching(/exceeds.*MiB/i)+ })+ } else {+ expect(produced).toBe(limit)+ expect(init.signal?.aborted).toBe(false)+ expect(cancel).not.toHaveBeenCalled()+ expect(clicked).toEqual([objectUrl])+ const image = create.mock.calls[0][0] as Blob+ expect(image.size).toBe(limit)+ expect(image.type).toBe('image/png')++ const bytes = await new Promise<ArrayBuffer>((resolve, reject) => {+ const reader = new FileReader()+ reader.onload = () => resolve(reader.result as ArrayBuffer)+ reader.onerror = () => reject(reader.error)+ reader.readAsArrayBuffer(image)+ })++ const content = new Uint8Array(bytes)+ expect(content[0]).toBe(7)+ expect(content[64 * 1024]).toBe(9)+ expect(content.at(-1)).toBe(9)+ await vi.runOnlyPendingTimersAsync()+ expect(init.signal?.aborted).toBe(false)+ expect(revoke).toHaveBeenCalledWith(objectUrl)+ }++ const directUrls = [`${window.location.origin}/same-origin.png`, 'blob:https://images.example/local', 'data:image/png;base64,AA==']++ for (const directUrl of directUrls) {+ await expect(win.hermesDesktop.saveImageFromUrl(directUrl)).resolves.toBe(true)+ }++ expect(clicked.slice(-directUrls.length)).toEqual(directUrls)+ expect(fetchMock).toHaveBeenCalledTimes(1)+})++it.each(['headers', 'body'])('times out stalled image %s within one whole-download deadline', async phase => {+ vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] })+ seedWebappSession('served-token')+ // Cancellation itself must not extend the deadline.+ const cancel = vi.fn(() => new Promise<void>(() => undefined))++ const body = new ReadableStream<Uint8Array>({+ start(controller) {controller.enqueue(new Uint8Array([7]))},+ cancel+ })++ const response = new Response(body, { headers: { 'content-type': 'image/png' } })++ const fetchMock = vi.fn((_url: URL, init: RequestInit) => new Promise<Response>((resolve, reject) => {+ init.signal?.addEventListener('abort', () => reject(init.signal?.reason), { once: true })++ if (phase === 'body') {+ window.setTimeout(() => resolve(response), BROWSER_IMAGE_DOWNLOAD_TIMEOUT_MS / 2)+ }+ }))++ vi.stubGlobal('fetch', fetchMock)+ const click = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => undefined)+ const create = vi.spyOn(URL, 'createObjectURL')+ expect(installBrowserDesktopBridge()).toBe(true)+ let saved: boolean | undefined+ void win.hermesDesktop.saveImageFromUrl('https://images.example/slow.png').then(result => {saved = result})+ const signal = fetchMock.mock.calls[0][1].signal+ await vi.advanceTimersByTimeAsync(BROWSER_IMAGE_DOWNLOAD_TIMEOUT_MS - 1)+ expect(saved).toBeUndefined()+ await vi.advanceTimersByTimeAsync(1)+ expect(saved).toBe(false)+ expect(signal?.aborted).toBe(true)+ expect(body.locked).toBe(false)+ expect(cancel).toHaveBeenCalledTimes(phase === 'body' ? 1 : 0)+ expect($notifications.get().at(-1)).toMatchObject({+ kind: 'error', title: 'Download failed', message: expect.stringMatching(/timed out/i)+ })+ expect(click).not.toHaveBeenCalled()+ expect(create).not.toHaveBeenCalled()+})++it('names a fetched cross-origin image after its URL, not the blob URL that carries it', async () => {+ seedWebappSession('served-token')+ const response = new Response(new Uint8Array([7]), { headers: { 'content-type': 'image/webp' } })+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(response))+ vi.spyOn(URL, 'createObjectURL').mockReturnValue(`blob:${window.location.origin}/7f3e9c1a`)+ vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => undefined)+ const names: string[] = []+ vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(function (this: HTMLAnchorElement) {+ names.push(this.download)+ })+ expect(installBrowserDesktopBridge()).toBe(true)++ await expect(win.hermesDesktop.saveImageFromUrl('https://v3.fal.media/files/x/MKZV6h-RrKLV')).resolves.toBe(true)+ await expect(win.hermesDesktop.saveImageFromUrl(`${window.location.origin}/api/media/a.png`)).resolves.toBe(true)++ // The same-origin route stays unnamed so the server's Content-Disposition wins.+ expect(names).toEqual(['MKZV6h-RrKLV.webp', ''])+})++it('surfaces CORS and HTTP download failures without clicking a navigation link', async () => {+ seedWebappSession('served-token')++ const cancel = vi.fn()+ const deniedBody = new ReadableStream<Uint8Array>({ cancel })++ const fetchMock = vi.fn().mockRejectedValueOnce(new TypeError('Failed to fetch'))+ .mockResolvedValueOnce(new Response(deniedBody, { status: 403 }))++ vi.stubGlobal('fetch', fetchMock)+ const click = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(() => undefined)+ expect(installBrowserDesktopBridge()).toBe(true)++ for (const suffix of ['cors.png', 'denied.png']) {+ await expect(win.hermesDesktop.saveImageFromUrl(`https://images.example/${suffix}`)).resolves.toBe(false)+ expect($notifications.get().at(-1)).toMatchObject({ kind: 'error', title: 'Download failed' })+ }++ expect(click).not.toHaveBeenCalled()+ expect(cancel).toHaveBeenCalledOnce()+ expect(deniedBody.locked).toBe(false)++ for (const [, init] of fetchMock.mock.calls as [URL, RequestInit][]) {+ expect(init.signal?.aborted).toBe(true)+ }++ clearNotifications()+})++const win = window++afterEach(() => {+ clearWebappSession()+ Reflect.deleteProperty(win, 'hermesDesktop')+ document.documentElement.removeAttribute('data-hermes-desktop-host')+ window.history.replaceState(null, '', '/#/')+ setApiRequestConnection(null)+ setApiRequestProfile(null)+ $connection.set(null)+ clearNotifications()+ window.dispatchEvent(new Event('beforeunload'))+ vi.clearAllTimers()+ vi.useRealTimers()+ vi.unstubAllGlobals()+ vi.restoreAllMocks()+})++it('reconnects the window owner rather than the active secondary profile', async () => {+ seedWebappSession('served-token')+ window.history.replaceState(null, '', '/?profile=window-owner#/session')+ expect(installBrowserDesktopBridge()).toBe(true)+ const initial = await win.hermesDesktop.getConnection('window-owner')+ $connection.set({ profile: 'active-secondary' } as never)+ const reconnect = await win.hermesDesktop.getConnection()+ expect(reconnect.profile).toBe(initial.profile)+ expect(new URL(reconnect.wsUrl).searchParams.get('profile')).toBe('window-owner')+ const explicitDefault = await win.hermesDesktop.getConnection(null)+ expect(new URL(explicitDefault.wsUrl).searchParams.has('profile')).toBe(false)+ const namedDefault = await win.hermesDesktop.getConnection('default')+ expect(new URL(namedDefault.wsUrl).searchParams.get('profile')).toBe('default')+})diff --git a/apps/desktop/src/lib/browser-desktop-bridge-ownership-media.test.ts b/apps/desktop/src/lib/browser-desktop-bridge-ownership-media.test.tsnew file mode 100644index 00000000000..e91d314f275--- /dev/null+++ b/apps/desktop/src/lib/browser-desktop-bridge-ownership-media.test.ts@@ -0,0 +1,93 @@+import { LOCAL_CONNECTION_ID } from '@hermes/shared'+import { afterEach, expect, it, vi } from 'vitest'++import { setApiRequestConnection, setApiRequestProfile } from '@/api/client'+import { $connection } from '@/store/session'+import { clearWebappSession, seedWebappSession } from '@/test/webapp-session'++import { installBrowserDesktopBridge } from './browser-desktop-bridge'+import { resolveMediaDisplaySrc, resolveMediaPlaybackSrc } from './media'++const win = window++// Each served profile's backend answers for its own roots: the shared path holds+// different bytes per profile, and only the tile owner's backend admits its outputs dir.+const BACKENDS: Record<string, Record<string, string>> = {+ foreground: { '/srv/shared/shot.png': 'data:image/png;base64,Rk9SRUdST1VORA==' },+ 'tile-owner': {+ '/srv/shared/shot.png': 'data:image/png;base64,T1dORVI=',+ '/srv/tile-owner/outputs/plot.png': 'data:image/png;base64,UExPVA=='+ }+}++afterEach(() => {+ clearWebappSession()+ Reflect.deleteProperty(win, 'hermesDesktop')+ document.documentElement.removeAttribute('data-hermes-desktop-host')+ setApiRequestConnection(null)+ setApiRequestProfile(null)+ $connection.set(null)+ window.dispatchEvent(new Event('beforeunload'))+ vi.unstubAllGlobals()+ vi.restoreAllMocks()+})++it.each([+ { name: 'foreground tile (control)', owner: 'foreground', path: '/srv/shared/shot.png' },+ { name: 'background tile, same path with other bytes', owner: 'tile-owner', path: '/srv/shared/shot.png' },+ { name: 'background tile, path only its backend admits', owner: 'tile-owner', path: '/srv/tile-owner/outputs/plot.png' }+])('reads local-connection media on the owning browser profile: $name', async ({ owner, path }) => {+ seedWebappSession('served-token')++ const fetchMock = vi.fn(async (input: URL, _init?: RequestInit) => {+ const dataUrl = BACKENDS[input.searchParams.get('profile') || '']?.[input.searchParams.get('path') || '']++ return dataUrl+ ? new Response(JSON.stringify({ dataUrl }), { status: 200 })+ : new Response(JSON.stringify({ detail: 'Path is outside the allowed roots' }), { status: 403 })+ })++ vi.stubGlobal('fetch', fetchMock)+ expect(installBrowserDesktopBridge()).toBe(true)+ // The user switched the page to another profile; the tile kept its captured owner.+ setApiRequestConnection(LOCAL_CONNECTION_ID)+ setApiRequestProfile('foreground')+ $connection.set({ connectionId: LOCAL_CONNECTION_ID, mode: 'remote', profile: 'foreground' } as never)++ await expect(resolveMediaDisplaySrc(`file://${path}`, { connectionId: LOCAL_CONNECTION_ID, profile: owner })).resolves.toBe(+ BACKENDS[owner][path]+ )+ const [requestUrl] = fetchMock.mock.calls.at(-1) as [URL, RequestInit]+ expect(requestUrl.pathname).toBe('/api/fs/read-data-url')+ expect(requestUrl.searchParams.get('profile')).toBe(owner)+})++it.each(['clip.mp3', 'clip.mp4'])('streams background-tile %s through the owning browser profile', async file => {+ seedWebappSession('served-token')++ const ticketProfiles: unknown[] = []++ const fetchMock = vi.fn(async (input: URL, init?: RequestInit) => {+ if (input.pathname === '/api/files/ticket') {+ ticketProfiles.push(JSON.parse(String(init?.body ?? '{}')).profile)++ return new Response(JSON.stringify({ ticket: 'owner-ticket' }), { status: 200 })+ }++ return new Response('{}', { status: 404 })+ })++ vi.stubGlobal('fetch', fetchMock)+ expect(installBrowserDesktopBridge()).toBe(true)+ setApiRequestConnection(LOCAL_CONNECTION_ID)+ setApiRequestProfile('foreground')+ $connection.set({ connectionId: LOCAL_CONNECTION_ID, mode: 'remote', profile: 'foreground' } as never)++ const src = await resolveMediaPlaybackSrc(`/srv/tile-owner/${file}`, {+ connectionId: LOCAL_CONNECTION_ID,+ profile: 'tile-owner'+ })++ expect(ticketProfiles).toEqual(['tile-owner'])+ expect(new URL(src).searchParams.get('profile')).toBe('tile-owner')+})diff --git a/apps/desktop/src/lib/browser-desktop-bridge-settings.test.ts b/apps/desktop/src/lib/browser-desktop-bridge-settings.test.tsnew file mode 100644index 00000000000..70cc2eed268--- /dev/null+++ b/apps/desktop/src/lib/browser-desktop-bridge-settings.test.ts@@ -0,0 +1,62 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++import { $connection } from '@/store/session'+import { clearWebappSession, seedWebappSession } from '@/test/webapp-session'++import { installBrowserDesktopBridge } from './browser-desktop-bridge'++type BootstrapWindow = Window & { __HERMES_BASE_PATH__?: string; }+const win = window as unknown as BootstrapWindow++/** A fresh page load: the bridge is rebuilt from scratch, only storage survives. */+function reload(basePath = '') {+ Reflect.deleteProperty(win, 'hermesDesktop')+ win.__HERMES_BASE_PATH__ = basePath+ expect(installBrowserDesktopBridge()).toBe(true)++ return win.hermesDesktop!.settings+}++function onProfile(profile: string) {+ $connection.set({ ...($connection.get() ?? {}), profile } as NonNullable<ReturnType<typeof $connection.get>>)+}++beforeEach(() => {+ seedWebappSession('served-token')+ localStorage.clear()+})++afterEach(() => {+ Reflect.deleteProperty(win, 'hermesDesktop')+ delete win.__HERMES_BASE_PATH__+ clearWebappSession()+ $connection.set(null)+ localStorage.clear()+ vi.restoreAllMocks()+})++describe('browser default project folder', () => {+ it('keeps a chosen folder across reloads, per hosted gateway and profile, until cleared', async () => {+ onProfile('work')+ await expect(reload('/first').setDefaultProjectDir('/srv/repos/app')).resolves.toEqual({ dir: '/srv/repos/app' })++ expect((await reload('/first').getDefaultProjectDir()).dir).toBe('/srv/repos/app')+ // Another gateway on this origin, or another profile, browses a different machine's folders.+ expect((await reload('/second').getDefaultProjectDir()).dir).toBeNull()+ onProfile('ssh-box')+ expect((await reload('/first').getDefaultProjectDir()).dir).toBeNull()++ onProfile('work')+ await reload('/first').setDefaultProjectDir(null)+ expect((await reload('/first').getDefaultProjectDir()).dir).toBeNull()+ })++ it('rejects a choice this browser cannot keep instead of reporting it saved', async () => {+ vi.spyOn(localStorage, 'setItem').mockImplementation(() => {+ throw new Error('storage denied')+ })++ await expect(reload().setDefaultProjectDir('/srv/repos/app')).rejects.toThrow()+ expect((await reload().getDefaultProjectDir()).dir).toBeNull()+ })+})diff --git a/apps/desktop/src/lib/browser-desktop-bridge-zoom.test.ts b/apps/desktop/src/lib/browser-desktop-bridge-zoom.test.tsnew file mode 100644index 00000000000..cf10f8cf65a--- /dev/null+++ b/apps/desktop/src/lib/browser-desktop-bridge-zoom.test.ts@@ -0,0 +1,76 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++import { clearWebappSession, seedWebappSession } from '@/test/webapp-session'++import { installBrowserDesktopBridge } from './browser-desktop-bridge'+import { createBrowserZoom } from './browser-zoom'++const win = window++beforeEach(() => {+ seedWebappSession('served-token')+ localStorage.clear()+ vi.stubGlobal('devicePixelRatio', 1.5)+})++afterEach(() => {+ Reflect.deleteProperty(win, 'hermesDesktop')+ clearWebappSession()+ document.documentElement.style.removeProperty('zoom')+ delete document.documentElement.dataset.hermesDesktopHost+ localStorage.clear()+ vi.unstubAllGlobals()+})++describe('browser UI scale', () => {+ it('reports app scale independently of display density and applies preset changes before notifying', async () => {+ expect(installBrowserDesktopBridge()).toBe(true)+ const zoom = win.hermesDesktop!.zoom!+ expect((await zoom.get()).percent).toBe(100)++ const onChanged = vi.fn(({ percent }: { percent: number }) => {+ expect(Number(document.documentElement.style.zoom)).toBe(percent / 100)+ })++ const stop = zoom.onChanged(onChanged)+ zoom.setPercent(150)++ expect((await zoom.get()).percent).toBe(150)+ expect(document.documentElement.style.zoom).toBe('1.5')+ expect(onChanged).toHaveBeenCalledWith(expect.objectContaining({ percent: 150 }))+ stop()+ zoom.setPercent(125)+ expect(onChanged).toHaveBeenCalledTimes(1)+ })++ it('restores app scale on reload without sharing it across hosted base paths', async () => {+ createBrowserZoom('/first').setPercent(150)+ const restored = createBrowserZoom('/first')+ expect((await restored.get()).percent).toBe(150)+ expect(document.documentElement.style.zoom).toBe('1.5')+ expect(restored.factor!()).toBe(1.5)+ expect((await createBrowserZoom('/second').get()).percent).toBe(100)+ })++ it('keeps scaling usable when storage is blocked and rejects invalid scale inputs', async () => {+ vi.spyOn(localStorage, 'getItem').mockImplementation(() => {+ throw new Error('storage denied')+ })+ vi.spyOn(localStorage, 'setItem').mockImplementation(() => {+ throw new Error('storage denied')+ })+ const zoom = createBrowserZoom('')+ const resized = vi.fn()+ window.addEventListener('resize', resized)+ zoom.setPercent(175)+ expect(document.documentElement.style.zoom).toBe('1.75')+ expect((await zoom.get()).percent).toBe(175)+ expect(resized).toHaveBeenCalledTimes(1)+ window.removeEventListener('resize', resized)+ zoom.setPercent(Number.NaN)+ expect((await zoom.get()).percent).toBe(100)+ zoom.setPercent(-10)+ expect((await zoom.get()).percent).toBe(100)+ vi.restoreAllMocks()+ })+})diff --git a/apps/desktop/src/lib/browser-desktop-bridge.test.ts b/apps/desktop/src/lib/browser-desktop-bridge.test.tsnew file mode 100644index 00000000000..ffca13a99a1--- /dev/null+++ b/apps/desktop/src/lib/browser-desktop-bridge.test.ts@@ -0,0 +1,1038 @@+import { afterEach, describe, expect, it, vi } from 'vitest'++import { reconnectMovedCloudAgent } from '@/app/settings/cloud-team-change'+import { $connection } from '@/store/session'+import { clearWebappSession, seedWebappSession } from '@/test/webapp-session'++import { installBrowserDesktopBridge } from './browser-desktop-bridge'+import { desktopGit } from './desktop-git'+import { openLink } from './external-link'+import { downloadGatewayMediaFile, resolveMediaPlaybackSrc } from './media'++type MutableWindow = Window & {+ __HERMES_AUTH_REQUIRED__?: boolean+ __HERMES_BASE_PATH__?: string+ hermesDesktop?: Window['hermesDesktop']+}++const mutableWindow = () => window as unknown as MutableWindow++afterEach(() => {+ const win = mutableWindow()+ delete win.__HERMES_AUTH_REQUIRED__+ delete win.__HERMES_BASE_PATH__+ clearWebappSession()+ Reflect.deleteProperty(win, 'hermesDesktop')+ document.documentElement.removeAttribute('data-hermes-desktop-host')+ Reflect.deleteProperty(navigator, 'clipboard')+ window.history.replaceState(null, '', '/#/')+ $connection.set(null)+ vi.unstubAllGlobals()+ vi.restoreAllMocks()+})++describe('browser-hosted Desktop bridge', () => {+ it('does not make network requests to resolve link titles', async () => {+ seedWebappSession('served-token')+ const fetchMock = vi.fn().mockResolvedValue(new Response('<title>Untrusted title</title>'))+ vi.stubGlobal('fetch', fetchMock)+ expect(installBrowserDesktopBridge()).toBe(true)++ await expect(mutableWindow().hermesDesktop!.fetchLinkTitle('https://example.com/some-article')).resolves.toBe('')+ expect(fetchMock).not.toHaveBeenCalled()+ })++ it('refuses cloud-team reconnection without a native connection registry', async () => {+ seedWebappSession('served-token')+ const fetchMock = vi.fn()+ vi.stubGlobal('fetch', fetchMock)+ expect(installBrowserDesktopBridge()).toBe(true)+ const desktop = mutableWindow().hermesDesktop!+ const logout = vi.spyOn(desktop, 'oauthLogoutConnectionConfig')+ const signIn = vi.spyOn(desktop.cloud, 'agentSignIn')++ await expect(reconnectMovedCloudAgent(desktop, {+ id: 'cloud-agent',+ kind: 'cloud',+ label: 'Cloud agent',+ url: 'https://agent.example.com',+ authMode: 'oauth',+ org: 'old-team',+ tokenSet: false,+ tokenPreview: null+ }, 'new-team', () => true)).resolves.toBe(false)+ expect(logout).not.toHaveBeenCalled()+ expect(signIn).not.toHaveBeenCalled()+ expect(fetchMock).not.toHaveBeenCalled()+ })++ it('does not replace the Electron preload bridge', () => {+ const win = mutableWindow()+ const existing = { api: vi.fn() } as unknown as Window['hermesDesktop']+ seedWebappSession('served-token')+ win.hermesDesktop = existing++ expect(installBrowserDesktopBridge()).toBe(false)+ expect(win.hermesDesktop).toBe(existing)+ })++ it('requires the server-injected session token', () => {+ expect(installBrowserDesktopBridge()).toBe(false)+ expect(mutableWindow().hermesDesktop).toBeUndefined()+ })++ it('installs behind the authenticated non-loopback server gate without exposing a token', async () => {+ const win = mutableWindow()+ win.__HERMES_AUTH_REQUIRED__ = true+ win.__HERMES_BASE_PATH__ = '/hermes'++ const fetchMock = vi.fn().mockResolvedValue(+ new Response(JSON.stringify({ ok: true }), {+ headers: { 'content-type': 'application/json' },+ status: 200+ })+ )++ vi.stubGlobal('fetch', fetchMock)++ expect(installBrowserDesktopBridge()).toBe(true)+ await win.hermesDesktop!.api({ path: '/api/status' })++ const [requestUrl, init] = fetchMock.mock.calls[0] as [URL, RequestInit]+ expect(requestUrl.pathname).toBe('/hermes/api/status')+ expect(init.credentials).toBe('same-origin')+ expect(new Headers(init.headers).has('X-Hermes-Session-Token')).toBe(false)++ const connection = await win.hermesDesktop!.getConnection()+ expect(connection.authMode).toBe('oauth')+ expect(connection.mode).toBe('remote')+ expect(connection.token).toBe('')+ // The serving gateway's canonical socket: no credential in the descriptor.+ const ws = new URL(connection.wsUrl)+ expect(ws.pathname).toBe('/hermes/api/ws')+ expect(ws.searchParams.get('native_dial')).toBe('browser')+ expect(ws.searchParams.has('ticket') || ws.searchParams.has('token')).toBe(false)+ })++ // About renders `Version <appVersion>` / `v<appVersion>`: it must carry the+ // serving host's release, never a host-kind label.+ it('reports the serving host version, unknown when the host cannot say', async () => {+ const win = mutableWindow()+ win.__HERMES_AUTH_REQUIRED__ = true+ win.__HERMES_BASE_PATH__ = '/hermes'++ const fetchMock = vi+ .fn()+ .mockResolvedValueOnce(new Response(JSON.stringify({ displayVersion: '0.21.5+1913', version: '0.21.5' })))+ .mockRejectedValueOnce(new Error('offline'))++ vi.stubGlobal('fetch', fetchMock)+ expect(installBrowserDesktopBridge()).toBe(true)++ await expect(win.hermesDesktop!.getVersion()).resolves.toMatchObject({ appVersion: '0.21.5+1913' })+ expect((fetchMock.mock.calls[0] as [URL])[0].pathname).toBe('/hermes/api/health')+ // '' is About's "version unavailable" state.+ await expect(win.hermesDesktop!.getVersion()).resolves.toMatchObject({ appVersion: '' })+ })++ it('mints a fresh gateway ticket for each WebSocket dial', async () => {+ const win = mutableWindow()+ win.__HERMES_AUTH_REQUIRED__ = true+ win.__HERMES_BASE_PATH__ = '/hermes'++ const fetchMock = vi+ .fn()+ .mockResolvedValueOnce(new Response(JSON.stringify({ ticket: 'ticket-one' }), { status: 200 }))+ .mockResolvedValueOnce(new Response(JSON.stringify({ ticket: 'ticket-two' }), { status: 200 }))++ vi.stubGlobal('fetch', fetchMock)++ expect(installBrowserDesktopBridge()).toBe(true)++ const first = await win.hermesDesktop!.getGatewayWsUrl('worker-a')+ const second = await win.hermesDesktop!.getGatewayWsUrlFor!({ connectionId: 'local', profile: 'worker-a' })++ const wsUrl = (result: typeof first) =>+ typeof result === 'string' ? result : result.ok ? result.wsUrl : ''++ const firstUrl = new URL(wsUrl(first))+ const secondUrl = new URL(wsUrl(second))+ expect(firstUrl.pathname).toBe('/hermes/api/ws')+ // native_dial: the client speaks the gateway's canonical contract and moves the ticket into+ // the socket's subprotocol.+ expect(firstUrl.searchParams.get('native_dial')).toBe('browser')+ expect(firstUrl.searchParams.get('ticket')).toBe('ticket-one')+ expect(firstUrl.searchParams.has('token')).toBe(false)+ expect(firstUrl.searchParams.get('profile')).toBe('worker-a')+ expect(secondUrl.searchParams.get('ticket')).toBe('ticket-two')+ expect(fetchMock).toHaveBeenCalledTimes(2)+ const minted = fetchMock.mock.calls.map(([url]) => url as URL)+ expect(minted.every(url => url.pathname === '/hermes/api/webapp/gateway-ticket')).toBe(true)+ expect(minted.every(url => url.searchParams.get('profile') === 'worker-a')).toBe(true)+ expect(fetchMock.mock.calls.every(([, init]) => init?.method === 'POST')).toBe(true)+ expect(fetchMock.mock.calls.every(([, init]) => init?.credentials === 'same-origin')).toBe(true)+ })++ it('returns an actionable reauth result when the gated cookie expires', async () => {+ const win = mutableWindow()+ win.__HERMES_AUTH_REQUIRED__ = true+ win.__HERMES_BASE_PATH__ = '/hermes'+ let loginUrl = ''+ window.addEventListener(+ 'hermes:browser-reauth-required',+ event => {+ event.preventDefault()+ loginUrl = String((event as CustomEvent<{ loginUrl?: string }>).detail.loginUrl || '')+ },+ { once: true }+ )+ vi.stubGlobal(+ 'fetch',+ vi.fn().mockResolvedValue(+ new Response(+ JSON.stringify({+ error: 'session_expired',+ login_url: '/hermes/login?next=%2Fapi%2Fauth%2Fws-ticket'+ }),+ { status: 401 }+ )+ )+ )++ expect(installBrowserDesktopBridge()).toBe(true)++ await expect(win.hermesDesktop!.getGatewayWsUrl('worker-a')).resolves.toMatchObject({+ error: expect.stringContaining('session_expired'),+ needsOauthLogin: true,+ ok: false+ })+ expect(new URL(loginUrl).pathname).toBe('/hermes/login')+ })++ it('signs out through the server before navigating to the gated login page', async () => {+ const win = mutableWindow()+ win.__HERMES_AUTH_REQUIRED__ = true+ win.__HERMES_BASE_PATH__ = '/hermes'+ let loginUrl = ''+ window.addEventListener(+ 'hermes:browser-reauth-required',+ event => {+ event.preventDefault()+ loginUrl = String((event as CustomEvent<{ loginUrl?: string }>).detail.loginUrl || '')+ },+ { once: true }+ )+ const fetchMock = vi.fn().mockResolvedValue(new Response('', { status: 200 }))+ vi.stubGlobal('fetch', fetchMock)++ expect(installBrowserDesktopBridge()).toBe(true)+ await expect(win.hermesDesktop!.oauthLogoutConnectionConfig(window.location.origin)).resolves.toEqual({+ connected: false,+ ok: true+ })++ const [requestUrl, init] = fetchMock.mock.calls[0] as [URL, RequestInit]+ expect(requestUrl.pathname).toBe('/hermes/auth/logout')+ expect(init.method).toBe('POST')+ expect(init.credentials).toBe('same-origin')+ expect(new URL(loginUrl).pathname).toBe('/hermes/login')+ })++ it('does not advertise Electron-only capabilities in browser-host mode', () => {+ const win = mutableWindow()+ seedWebappSession('served-token')++ expect(installBrowserDesktopBridge()).toBe(true)+ expect(win.hermesDesktop?.openBrowserWindow).toBeUndefined()+ expect(win.hermesDesktop?.onBrowserPopoutClosed).toBeUndefined()+ expect(win.hermesDesktop?.getSecretStorageEncryption).toBeUndefined()+ expect(win.hermesDesktop?.setSecretStorageEncryption).toBeUndefined()+ expect(win.hermesDesktop?.openSessionInTerminal).toBeUndefined()+ expect(win.hermesDesktop?.connections).toBeUndefined()+ expect(win.hermesDesktop?.onOpenFindBarRequested).toBeUndefined()+ expect(win.hermesDesktop?.petOverlay).toBeUndefined()+ expect(win.hermesDesktop?.quickEntry).toBeUndefined()+ })++ it('disables native window controls and rejects their operations without side effects', () => {+ const win = mutableWindow()+ seedWebappSession('served-token')+ const fetchMock = vi.fn()+ const closeMock = vi.spyOn(window, 'close').mockImplementation(() => undefined)+ vi.stubGlobal('fetch', fetchMock)++ expect(installBrowserDesktopBridge()).toBe(true)+ const controls = win.hermesDesktop!.windowControls+ expect(controls.custom).toBe(false)++ for (const operation of [controls.minimize, controls.toggleMaximize, controls.close]) {+ expect(operation).toThrow()+ }++ expect(fetchMock).not.toHaveBeenCalled()+ expect(closeMock).not.toHaveBeenCalled()+ })++ it('keeps clipboard writes on the browser-native method captured before renderer shims', async () => {+ const win = mutableWindow()+ seedWebappSession('served-token')+ const nativeWriteText = vi.fn().mockResolvedValue(undefined)+ const laterShim = vi.fn().mockRejectedValue(new Error('recursive clipboard shim'))+ Object.defineProperty(navigator, 'clipboard', {+ configurable: true,+ value: { writeText: nativeWriteText }+ })++ expect(installBrowserDesktopBridge()).toBe(true)+ Object.defineProperty(navigator.clipboard, 'writeText', {+ configurable: true,+ value: laterShim+ })++ await expect(win.hermesDesktop!.writeClipboard('payload')).resolves.toBe(true)+ expect(nativeWriteText).toHaveBeenCalledWith('payload')+ expect(laterShim).not.toHaveBeenCalled()+ })++ it('remembers the selected browser profile in the launch URL without losing its route', async () => {+ const win = mutableWindow()+ seedWebappSession('served-token')+ window.history.replaceState(null, '', '/hermes?view=chat#/session-1')++ expect(installBrowserDesktopBridge()).toBe(true)+ await expect(win.hermesDesktop!.profile.remember(' research ')).resolves.toEqual({ profile: 'research' })++ let url = new URL(window.location.href)+ expect(url.pathname).toBe('/hermes')+ expect(url.searchParams.get('view')).toBe('chat')+ expect(url.searchParams.get('profile')).toBe('research')+ expect(url.hash).toBe('#/session-1')++ // Default is written out: a bare URL boots on the origin's saved default.+ await expect(win.hermesDesktop!.profile.remember('default')).resolves.toEqual({ profile: 'default' })+ url = new URL(window.location.href)+ expect(url.searchParams.get('profile')).toBe('default')+ expect(url.hash).toBe('#/session-1')++ await win.hermesDesktop!.profile.remember(null)+ expect(new URL(window.location.href).searchParams.has('profile')).toBe(false)+ })++ it('opens session windows on the owning profile HashRouter route with spectator flags before the hash', async () => {+ const win = mutableWindow()+ // A gated host opens the window directly; a launch-link tab hands it a session first.+ win.__HERMES_AUTH_REQUIRED__ = true+ window.history.replaceState(null, '', '/?profile=work#/existing')+ const open = vi.spyOn(window, 'open').mockImplementation(() => null)++ expect(installBrowserDesktopBridge()).toBe(true)+ await expect(+ win.hermesDesktop!.openSessionWindow('session / 1', { profile: 'research', watch: true })+ ).resolves.toEqual({ ok: true })++ const [rawUrl, target, features] = open.mock.calls[0]+ const url = new URL(String(rawUrl))+ expect(url.searchParams.get('profile')).toBe('research')+ expect(url.searchParams.get('win')).toBe('secondary')+ expect(url.searchParams.get('watch')).toBe('1')+ expect(url.hash).toBe('#/session%20%2F%201')+ expect(target).toBe('_blank')+ expect(features).toBe('noopener,noreferrer')+ })++ it('hands only the schemes Electron opens externally to window.open', async () => {+ seedWebappSession('served-token')+ const open = vi.spyOn(window, 'open').mockImplementation(() => null)++ expect(installBrowserDesktopBridge()).toBe(true)+ const desktop = mutableWindow().hermesDesktop!+ const openers = [desktop.openExternal, desktop.openPreviewInBrowser!]++ // Chat links reach the bridge through the same handoff as a user's click.+ openLink('javascript:alert(document.cookie)')++ for (const url of [+ 'javascript:alert(1)',+ ' JavaScript:alert(1)',+ 'data:text/html,<script>alert(1)</script>',+ 'vbscript:msgbox(1)',+ 'hermes-media://stream/%2Fetc%2Fpasswd',+ 'file:///etc/passwd',+ 'not a url'+ ]) {+ for (const opener of openers) {await opener(url)}+ }++ expect(open).not.toHaveBeenCalled()++ for (const url of ['https://example.com/a b', 'http://127.0.0.1:3000/', 'mailto:[email protected]']) {+ for (const opener of openers) {await opener(url)}+ }++ expect(open.mock.calls).toEqual(+ ['https://example.com/a%20b', 'http://127.0.0.1:3000/', 'mailto:[email protected]'].flatMap(url => [+ [url, '_blank', 'noopener,noreferrer'],+ [url, '_blank', 'noopener,noreferrer']+ ])+ )+ })++ it.each([+ { expectedProfile: 'work', name: 'absent', opts: undefined },+ { expectedProfile: 'work', name: 'undefined', opts: { profile: undefined } },+ { expectedProfile: 'work', name: 'null', opts: { profile: null } },+ { expectedProfile: 'work', name: 'blank', opts: { profile: ' ' } },+ { expectedProfile: 'default', name: 'default', opts: { profile: 'default' } },+ { expectedProfile: 'research', name: 'trimmed non-default', opts: { profile: ' research ' } }+ ])('resolves a $name session-window profile against the ambient launch URL', async ({ expectedProfile, opts }) => {+ const win = mutableWindow()+ // A gated host opens the window directly; a launch-link tab hands it a session first.+ win.__HERMES_AUTH_REQUIRED__ = true+ window.history.replaceState(null, '', '/?profile=work#/existing')+ const open = vi.spyOn(window, 'open').mockImplementation(() => null)++ expect(installBrowserDesktopBridge()).toBe(true)+ await expect(win.hermesDesktop!.openSessionWindow('session-1', opts)).resolves.toEqual({ ok: true })++ const [rawUrl] = open.mock.calls[0]+ expect(new URL(String(rawUrl)).searchParams.get('profile')).toBe(expectedProfile)+ })++ it('exposes one same-origin registry source for Bot profile routing', async () => {+ const win = mutableWindow()+ win.__HERMES_BASE_PATH__ = '/hermes'+ seedWebappSession('served-token')+ vi.stubGlobal(+ 'fetch',+ vi.fn().mockImplementation(async (url: URL) =>+ new Response(+ JSON.stringify(+ url.pathname.endsWith('/api/webapp/gateway-ticket')+ ? { ticket: 'research-ticket' }+ : { profiles: [{ name: 'default' }, { name: 'research' }] }+ ),+ { status: 200 }+ )+ )+ )++ expect(installBrowserDesktopBridge()).toBe(true)++ await expect(win.hermesDesktop!.getProfileRoutes?.(['default', 'research', 'deleted'])).resolves.toEqual([+ { connectionId: 'local', mode: 'local', profile: 'default', targetProfile: 'default' },+ { connectionId: 'local', mode: 'local', profile: 'research', targetProfile: 'research' }+ ])+ await expect(win.hermesDesktop!.getAgentRoster?.()).resolves.toMatchObject({+ agents: [+ { connectionId: 'local', connectionKind: 'local', handle: 'hermes', profile: 'default' },+ { connectionId: 'local', connectionKind: 'local', handle: 'research', profile: 'research' }+ ],+ primaryConnectionId: 'local',+ sources: [{ connectionId: 'local', kind: 'local', reachable: true }]+ })++ const connection = await win.hermesDesktop!.getConnectionFor?.({ connectionId: 'local', profile: 'research' })+ expect(connection).toMatchObject({+ connectionId: 'local',+ mode: 'remote',+ profile: 'research',+ registryScoped: true,+ sharedRemote: true+ })++ const result = await win.hermesDesktop!.getGatewayWsUrlFor?.({ connectionId: 'local', profile: 'research' })+ const wsUrl = typeof result === 'string' ? result : result?.ok ? result.wsUrl : ''+ expect(new URL(wsUrl).searchParams.get('profile')).toBe('research')+ await expect(+ win.hermesDesktop!.getConnectionFor?.({ connectionId: 'another-host', profile: 'research' })+ ).rejects.toThrow('No connection with id "another-host"')+ })++ it('maps REST requests to the loopback API with token and profile scoping', async () => {+ const win = mutableWindow()+ win.__HERMES_BASE_PATH__ = '/hermes'+ seedWebappSession('served-token')++ const fetchMock = vi.fn().mockResolvedValue(+ new Response(JSON.stringify({ ok: true }), {+ headers: { 'content-type': 'application/json' },+ status: 200+ })+ )++ vi.stubGlobal('fetch', fetchMock)++ expect(installBrowserDesktopBridge()).toBe(true)++ await win.hermesDesktop!.api({+ path: '/api/config?view=desktop',+ profile: 'worker-a'+ })++ const [requestUrl, init] = fetchMock.mock.calls[0] as [URL, RequestInit]+ expect(requestUrl.pathname).toBe('/hermes/api/config')+ expect(requestUrl.searchParams.get('view')).toBe('desktop')+ expect(requestUrl.searchParams.get('profile')).toBe('worker-a')+ expect(new Headers(init.headers).get('X-Hermes-Session-Token')).toBe('served-token')+ })++ it('routes Git through the browser transport and resolves the profile at call time', async () => {+ const win = mutableWindow()+ win.__HERMES_BASE_PATH__ = '/hermes'+ seedWebappSession('served-token')+ $connection.set({ profile: 'launch-profile' } as never)++ const worktrees = [{ branch: 'main', detached: false, isMain: true, locked: false, path: '/srv/my repo' }]++ const fetchMock = vi+ .fn()+ .mockResolvedValueOnce(new Response(JSON.stringify({ worktrees }), { status: 200 }))+ .mockResolvedValueOnce(new Response(JSON.stringify({ diff: 'working diff' }), { status: 200 }))+ .mockResolvedValueOnce(new Response(JSON.stringify({ ok: true }), { status: 200 }))++ vi.stubGlobal('fetch', fetchMock)+ expect(installBrowserDesktopBridge()).toBe(true)+ const git = desktopGit()!++ await expect(git.worktreeList('/srv/my repo')).resolves.toEqual(worktrees)+ const [listUrl, listInit] = fetchMock.mock.calls[0] as [URL, RequestInit]+ expect(listUrl.pathname).toBe('/hermes/api/git/worktrees')+ expect(listUrl.searchParams.get('path')).toBe('/srv/my repo')+ expect(listUrl.searchParams.get('profile')).toBe('launch-profile')+ expect(new Headers(listInit.headers).get('X-Hermes-Session-Token')).toBe('served-token')++ $connection.set({ profile: 'active-profile' } as never)+ await expect(git.review.diff('/srv/my repo', 'a b.txt', 'uncommitted', null, false)).resolves.toBe(+ 'working diff'+ )+ const [diffUrl] = fetchMock.mock.calls[1] as [URL, RequestInit]+ expect(diffUrl.searchParams.get('profile')).toBe('active-profile')+ expect(diffUrl.searchParams.get('file')).toBe('a b.txt')+ expect(diffUrl.searchParams.get('staged')).toBe('false')+ expect(diffUrl.searchParams.has('base')).toBe(false)++ await git.review.stage('/srv/my repo', '')+ const [stageUrl, stageInit] = fetchMock.mock.calls[2] as [URL, RequestInit]+ expect(stageUrl.pathname).toBe('/hermes/api/git/review/stage')+ expect(stageUrl.searchParams.get('profile')).toBe('active-profile')+ expect(stageInit.method).toBe('POST')+ expect(JSON.parse(String(stageInit.body))).toEqual({ file: null, path: '/srv/my repo' })++ const requestCount = fetchMock.mock.calls.length+ await expect(git.scanRepos(['/srv'])).resolves.toEqual([])+ expect(fetchMock).toHaveBeenCalledTimes(requestCount)+ })++ it('keeps recovery and filesystem bridge methods safe in browser mode', async () => {+ const win = mutableWindow()+ seedWebappSession('served-token')+ $connection.set({ profile: 'active-files' } as never)++ const fetchMock = vi.fn().mockResolvedValue(+ new Response(JSON.stringify({ path: '/tmp/example.txt', text: 'hello' }), { status: 200 })+ )++ vi.stubGlobal('fetch', fetchMock)++ expect(installBrowserDesktopBridge()).toBe(true)++ expect(await win.hermesDesktop!.getRecentLogs()).toEqual({ lines: [], path: '' })+ expect((await win.hermesDesktop!.revealLogs()).ok).toBe(false)+ expect(await win.hermesDesktop!.readFileText('/tmp/example.txt')).toMatchObject({ text: 'hello' })++ const [requestUrl, init] = fetchMock.mock.calls[0] as [URL, RequestInit]+ expect(requestUrl.pathname).toBe('/api/fs/read-text')+ expect(requestUrl.searchParams.get('path')).toBe('/tmp/example.txt')+ expect(requestUrl.searchParams.get('profile')).toBe('active-files')+ expect(new Headers(init.headers).get('X-Hermes-Session-Token')).toBe('served-token')+ })++ // Downloads and media elements cannot send the session header, and the+ // session token grants host shells: it must never appear in their URLs+ // (download history, "Copy video address"). Token sessions carry a ticket+ // minted for that exact route and query instead.+ const fileTicketFetch = (headStatus = 200) =>+ vi.fn(async (input: URL, init?: RequestInit) => {+ if (input.pathname.endsWith('/api/files/ticket')) {+ const { route, ...query } = JSON.parse(String(init?.body)) as Record<string, string>+ const scope = new URLSearchParams(query)+ scope.sort()++ return new Response(JSON.stringify({ ticket: `ticket:${route}:${scope}` }), { status: 200 })+ }++ return new Response(null, { status: headStatus })+ })++ const ticketFor = (url: URL, route: string) => {+ const query = new URLSearchParams(url.search)+ query.delete('ticket')+ query.sort()++ return `ticket:${route}:${query}`+ }++ const carriesToken = (url: URL, token: string) =>+ Boolean(token) && [...url.searchParams.entries()].some(entry => entry.join('=').includes(token))++ it.each(['token', 'cookie'])('downloads browser files with %s auth on the original profile', async auth => {+ const win = mutableWindow()+ const token = auth === 'token' ? 'served / token' : ''+ win.__HERMES_BASE_PATH__ = '/hermes'++ if (auth === 'cookie') {+ win.__HERMES_AUTH_REQUIRED__ = true+ } else {+ seedWebappSession(token)+ }++ const fetchMock = fileTicketFetch()+ vi.stubGlobal('fetch', fetchMock)+ const downloads: HTMLAnchorElement[] = []+ vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(function (this: HTMLAnchorElement) {+ downloads.push(this)+ })++ expect(installBrowserDesktopBridge()).toBe(true)+ $connection.set(await win.hermesDesktop!.getConnectionFor!({ connectionId: 'local', profile: 'research' }))++ const pending = downloadGatewayMediaFile('file:///srv/reports/a%20b.pdf', {+ sessionId: 'origin-session', profile: 'research'+ })++ $connection.set({ mode: 'remote', profile: 'switched-profile' } as never)+ await expect(pending).resolves.toMatchObject({ saved: true })++ const [requestUrl, init] = fetchMock.mock.calls[0] as [URL, RequestInit]+ expect(requestUrl.pathname).toBe('/hermes/api/files/download')+ expect(requestUrl.searchParams.get('path')).toBe('file:///srv/reports/a%20b.pdf')+ expect(requestUrl.searchParams.get('profile')).toBe('research')+ expect(requestUrl.searchParams.get('session_id')).toBe('origin-session')+ expect(init.method).toBe('HEAD')+ expect(init.credentials).toBe('same-origin')+ expect(new Headers(init.headers).get('X-Hermes-Session-Token')).toBe(token || null)+ expect(downloads).toHaveLength(1)+ const url = new URL(downloads[0].href)+ expect(url.origin).toBe(window.location.origin)+ expect(url.pathname).toBe(requestUrl.pathname)+ expect(url.searchParams.get('path')).toBe(requestUrl.searchParams.get('path'))+ expect(url.searchParams.get('profile')).toBe('research')+ expect(url.searchParams.get('session_id')).toBe('origin-session')+ expect(carriesToken(url, token)).toBe(false)+ expect(url.searchParams.get('ticket')).toBe(token ? ticketFor(url, 'download') : null)+ expect(downloads[0].download).toBe('a b.pdf')+ expect(downloads[0].isConnected).toBe(false)++ fetchMock.mockImplementation(async () => new Response(null, { status: 404 }))+ await expect(downloadGatewayMediaFile('/srv/missing.pdf')).rejects.toThrow('404')+ await expect(win.hermesDesktop!.saveGatewayFile!({+ connectionId: 'another-host', path: '/srv/reports/a b.pdf'+ })).rejects.toThrow('No connection with id "another-host"')+ expect(downloads).toHaveLength(1)+ })++ it.each(['token', 'cookie'])('streams browser audio/video over HTTP with %s auth', async auth => {+ const win = mutableWindow()+ const token = auth === 'token' ? 'served / token' : ''+ win.__HERMES_BASE_PATH__ = '/hermes'++ if (auth === 'cookie') {+ win.__HERMES_AUTH_REQUIRED__ = true+ } else {+ seedWebappSession(token)+ }++ const fetchMock = fileTicketFetch()+ vi.stubGlobal('fetch', fetchMock)++ expect(installBrowserDesktopBridge()).toBe(true)+ $connection.set(await win.hermesDesktop!.getConnectionFor!({ connectionId: 'local', profile: 'research' }))++ for (const path of [+ '/srv/a b.mp4',+ 'file:///srv/voice%20memo.m4a',+ 'C:/Users/Alice/video.mp4',+ 'file:///C:/Users/Alice/video%20clip.mp4',+ 'file://nas/share/video%20clip.mp4'+ ]) {+ const url = new URL(await resolveMediaPlaybackSrc(path))+ expect(url.origin).toBe(window.location.origin)+ expect(url.pathname).toBe('/hermes/api/files/stream')+ expect.soft(url.searchParams.get('path'), path).toBe(path)+ expect(url.searchParams.get('profile')).toBe('research')+ expect(carriesToken(url, token)).toBe(false)+ expect(url.searchParams.get('ticket')).toBe(token ? ticketFor(url, 'stream') : null)+ }++ await expect(resolveMediaPlaybackSrc('https://cdn.example.com/video.mp4')).resolves.toBe(+ 'https://cdn.example.com/video.mp4'+ )++ for (const [input, init] of fetchMock.mock.calls as [URL, RequestInit][]) {+ expect(input.pathname).toBe('/hermes/api/files/ticket')+ expect(new Headers(init.headers).get('X-Hermes-Session-Token')).toBe(token)+ }++ expect(fetchMock).toHaveBeenCalledTimes(token ? 5 : 0)+ })++ it('persists browser image bytes through the existing chat upload API', async () => {+ const win = mutableWindow()+ seedWebappSession('served-token')+ $connection.set({ profile: 'active-images' } as never)++ const fetchMock = vi.fn().mockResolvedValue(+ new Response(JSON.stringify({ path: '/srv/hermes/images/upload.png' }), {+ status: 200+ })+ )++ vi.stubGlobal('fetch', fetchMock)++ expect(installBrowserDesktopBridge()).toBe(true)++ const path = await win.hermesDesktop!.saveImageBuffer(+ new Uint8Array([0x89, 0x50, 0x4e, 0x47]),+ '.png'+ )++ expect(path).toBe('/srv/hermes/images/upload.png')+ const [requestUrl, init] = fetchMock.mock.calls[0] as [URL, RequestInit]+ expect(requestUrl.pathname).toBe('/api/chat/image-upload')+ expect(requestUrl.searchParams.get('profile')).toBe('active-images')+ const payload = JSON.parse(String(init.body)) as { data_url: string; filename: string }+ expect(payload.filename).toBe('desktop-upload.png')+ expect(payload.data_url).toBe('data:image/png;base64,iVBORw==')+ })++ it('stages user-selected browser files on the host before returning paths', async () => {+ const win = mutableWindow()+ seedWebappSession('served-token')+ $connection.set({ profile: 'active-profile' } as never)++ const fetchMock = vi.fn().mockResolvedValue(+ new Response(JSON.stringify({ path: '/srv/hermes/uploads/notes.txt' }), {+ headers: { 'content-type': 'application/json' },+ status: 200+ })+ )++ vi.stubGlobal('fetch', fetchMock)+ vi.spyOn(HTMLInputElement.prototype, 'click').mockImplementation(function (this: HTMLInputElement) {+ Object.defineProperty(this, 'files', {+ configurable: true,+ value: [new File(['hello'], 'notes.txt', { type: 'text/plain' })]+ })+ this.dispatchEvent(new Event('change'))+ })++ expect(installBrowserDesktopBridge()).toBe(true)++ const paths = await win.hermesDesktop!.selectPaths({+ filters: [{ extensions: ['txt'], name: 'Text' }],+ multiple: true,+ profile: 'explicit-file-profile'+ })++ expect(paths).toEqual(['/srv/hermes/uploads/notes.txt'])+ const [requestUrl, init] = fetchMock.mock.calls[0] as [URL, RequestInit]+ expect(requestUrl.pathname).toBe('/api/chat/file-upload')+ expect(requestUrl.searchParams.get('profile')).toBe('explicit-file-profile')+ expect(init.method).toBe('POST')+ expect(init.credentials).toBe('same-origin')+ expect(new Headers(init.headers).get('X-Hermes-Session-Token')).toBe('served-token')+ expect((init.body as FormData).get('file')).toBeInstanceOf(File)+ expect(document.querySelector('input[type="file"]')).toBeNull()+ })++ it('stages dropped browser file bytes before returning a host attachment path', async () => {+ const win = mutableWindow()+ seedWebappSession('served-token')+ $connection.set({ profile: 'drop-profile' } as never)++ const fetchMock = vi.fn().mockResolvedValue(+ new Response(JSON.stringify({ path: '/srv/hermes/uploads/drop.txt' }), { status: 200 })+ )++ vi.stubGlobal('fetch', fetchMock)++ expect(installBrowserDesktopBridge()).toBe(true)+ const file = new File(['dropped'], 'drop.txt', { type: 'text/plain' })++ await expect(win.hermesDesktop!.stageFileForAttach?.(file)).resolves.toBe('/srv/hermes/uploads/drop.txt')+ const [requestUrl, init] = fetchMock.mock.calls[0] as [URL, RequestInit]+ expect(requestUrl.pathname).toBe('/api/chat/file-upload')+ expect(requestUrl.searchParams.get('profile')).toBe('drop-profile')+ const stagedFile = (init.body as FormData).get('file') as File+ expect(stagedFile).toBeInstanceOf(File)+ expect(stagedFile.name).toBe('drop.txt')+ expect(stagedFile.size).toBe(file.size)+ expect(stagedFile.type).toBe('text/plain')+ })++ it('stages non-image buffers as browser-local object URLs', async () => {+ const win = mutableWindow()+ seedWebappSession('served-token')+ const createObjectURL = vi.fn((_blob: Blob | MediaSource) => 'blob:http://127.0.0.1:9119/preview')+ vi.spyOn(URL, 'createObjectURL').mockImplementation(createObjectURL)+ const revoke = vi.spyOn(URL, 'revokeObjectURL').mockImplementation(() => {})+ const open = vi.spyOn(window, 'open').mockReturnValue(null)++ expect(installBrowserDesktopBridge()).toBe(true)++ const staged = await win.hermesDesktop!.saveImageBuffer(+ new TextEncoder().encode('<h1>preview</h1>'),+ '.html'+ )++ expect(staged).toBe('blob:http://127.0.0.1:9119/preview')+ expect(createObjectURL).toHaveBeenCalledTimes(1)+ const [blob] = createObjectURL.mock.calls[0]+ expect(blob).toBeInstanceOf(Blob)+ const wrapper = await (blob as Blob).text()++ expect(wrapper).toContain('sandbox="allow-scripts"')+ expect(wrapper).not.toContain('allow-same-origin')+ expect(wrapper).not.toContain('<h1>preview</h1>')+ expect(wrapper).toContain('data:text/html;charset=utf-8;base64,PGgxPnByZXZpZXc8L2gxPg==')++ await win.hermesDesktop!.openPreviewInBrowser!(staged)+ expect(open).toHaveBeenCalledExactlyOnceWith(staged, '_blank', 'noopener,noreferrer')+ open.mockClear()+ await win.hermesDesktop!.openPreviewInBrowser!('blob:http://127.0.0.1:9119/unowned')+ await win.hermesDesktop!.openExternal(staged)+ expect(open).not.toHaveBeenCalled()+ window.dispatchEvent(new Event('beforeunload'))+ expect(revoke).toHaveBeenCalledWith(staged)+ await win.hermesDesktop!.openPreviewInBrowser!(staged)+ expect(open).not.toHaveBeenCalled()+ })++ it('rejects API paths that escape the Webapp origin', async () => {+ const win = mutableWindow()+ seedWebappSession('served-token')+ const fetchMock = vi.fn()+ vi.stubGlobal('fetch', fetchMock)++ expect(installBrowserDesktopBridge()).toBe(true)++ await expect(win.hermesDesktop!.api?.({ path: '//attacker.example/collect' })).rejects.toThrow(+ 'must remain on the Webapp origin'+ )+ expect(fetchMock).not.toHaveBeenCalled()+ })++ it('rejects API paths that escape the configured base path', async () => {+ const win = mutableWindow()+ win.__HERMES_BASE_PATH__ = '/hermes'+ seedWebappSession('served-token')+ const fetchMock = vi.fn()+ vi.stubGlobal('fetch', fetchMock)++ expect(installBrowserDesktopBridge()).toBe(true)++ await expect(win.hermesDesktop!.api?.({ path: '/../collect' })).rejects.toThrow(+ 'must remain inside the configured base path'+ )+ expect(fetchMock).not.toHaveBeenCalled()+ })++ it('maps the browser-hosted terminal rail onto an authenticated host-shell PTY socket', async () => {+ const win = mutableWindow()+ win.__HERMES_BASE_PATH__ = '/hermes'+ seedWebappSession('served-token')+ $connection.set({ profile: 'active-terminal' } as never)++ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(JSON.stringify({ ok: true }), { status: 200 })))++ class FakeWebSocket {+ static readonly CONNECTING = 0+ static readonly OPEN = 1+ static readonly CLOSING = 2+ static readonly CLOSED = 3+ static instances: FakeWebSocket[] = []+ binaryType = ''+ onclose: ((event: CloseEvent) => void) | null = null+ onerror: (() => void) | null = null+ onmessage: ((event: MessageEvent) => void) | null = null+ onopen: (() => void) | null = null+ readyState = FakeWebSocket.CONNECTING+ sent: string[] = []+ readonly url: string++ constructor(url: string | URL) {+ this.url = String(url)+ FakeWebSocket.instances.push(this)+ queueMicrotask(() => {+ this.readyState = FakeWebSocket.OPEN+ this.onopen?.()+ this.onmessage?.({+ data: '\u0000HERMES_TERMINAL_META:{"shell":"powershell.exe"}'+ } as MessageEvent)+ })+ }++ close(code = 1000, reason = '') {+ this.readyState = FakeWebSocket.CLOSED+ this.onclose?.(new CloseEvent('close', { code, reason }))+ }++ send(data: string) {+ this.sent.push(data)+ }++ emitBytes(text: string) {+ this.emitRaw(new TextEncoder().encode(text))+ }++ emitRaw(bytes: Uint8Array) {+ this.onmessage?.({ data: bytes.buffer } as MessageEvent)+ }+ }++ vi.stubGlobal('WebSocket', FakeWebSocket)+ expect(installBrowserDesktopBridge()).toBe(true)++ const session = await win.hermesDesktop!.terminal.start({ cols: 42, cwd: '/work', rows: 13 })+ const socket = FakeWebSocket.instances[0]!+ const url = new URL(socket.url)+ expect(session).toMatchObject({ cwd: '/work', shell: 'powershell.exe' })+ await expect(win.hermesDesktop!.terminal.attach(session.id)).resolves.toBe(true)+ await expect(win.hermesDesktop!.terminal.attach('missing-terminal')).resolves.toBe(false)+ expect(url.pathname).toBe('/hermes/api/host-terminal')+ expect(url.searchParams.get('token')).toBe('served-token')+ expect(url.searchParams.get('profile')).toBe('active-terminal')+ expect(url.searchParams.get('cwd')).toBe('/work')+ expect(url.searchParams.get('cols')).toBe('42')+ expect(url.searchParams.get('rows')).toBe('13')++ const output = vi.fn()+ const exited = vi.fn()+ const stopData = win.hermesDesktop!.terminal.onData(session.id, output)+ const stopExit = win.hermesDesktop!.terminal.onExit(session.id, exited)+ socket.emitBytes('hello from host shell')+ await Promise.resolve()+ expect(output).toHaveBeenCalledWith('hello from host shell')++ const multibyte = new TextEncoder().encode('😀')+ socket.emitRaw(multibyte.slice(0, 2))+ socket.emitRaw(multibyte.slice(2))+ expect(output).toHaveBeenCalledWith('😀')+ expect(output).not.toHaveBeenCalledWith(expect.stringContaining('�'))++ await expect(win.hermesDesktop!.terminal.write(session.id, 'hello\r')).resolves.toBe(true)+ await expect(win.hermesDesktop!.terminal.resize(session.id, { cols: 80, rows: 24 })).resolves.toBe(true)+ expect(socket.sent).toEqual(['hello\r', '\u001b[RESIZE:80;24]'])+ await expect(win.hermesDesktop!.terminal.cwd(session.id)).resolves.toBeNull()++ socket.close(4410, 'shell exited')+ expect(exited).toHaveBeenCalledWith({ code: null, signal: null })+ stopData()+ stopExit()+ await expect(win.hermesDesktop!.terminal.dispose(session.id)).resolves.toBe(true)+ })++ it('buffers early host-shell output until Desktop registers its terminal data listener', async () => {+ const win = mutableWindow()+ seedWebappSession('served-token')+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(JSON.stringify({ ok: true }), { status: 200 })))++ class PromptWebSocket {+ static readonly OPEN = 1+ binaryType = ''+ onclose: ((event: CloseEvent) => void) | null = null+ onerror: (() => void) | null = null+ onmessage: ((event: MessageEvent) => void) | null = null+ onopen: (() => void) | null = null+ readyState = 0++ constructor(_url: string | URL) {+ queueMicrotask(() => {+ this.readyState = PromptWebSocket.OPEN+ this.onopen?.()+ this.onmessage?.({+ data: '\u0000HERMES_TERMINAL_META:{"shell":"fish"}'+ } as MessageEvent)+ const bytes = new TextEncoder().encode('host shell ready')+ this.onmessage?.({ data: bytes.buffer } as MessageEvent)+ })+ }++ close() {+ this.readyState = 3+ }++ send(_data: string) {}+ }++ vi.stubGlobal('WebSocket', PromptWebSocket)+ expect(installBrowserDesktopBridge()).toBe(true)+ const session = await win.hermesDesktop!.terminal.start({ cwd: '/home' })+ expect(session.shell).toBe('fish')+ const output = vi.fn()+ win.hermesDesktop!.terminal.onData(session.id, output)+ await Promise.resolve()+ expect(output).toHaveBeenCalledWith('host shell ready')+ })++ it('exposes a profile-scoped gateway URL for Desktop boot', async () => {+ const win = mutableWindow()+ seedWebappSession('served-token')++ expect(installBrowserDesktopBridge()).toBe(true)++ const connection = await win.hermesDesktop!.getConnection('worker-a')+ const ws = new URL(connection.wsUrl)+ expect(connection.mode).toBe('remote')+ expect(connection.profile).toBe('worker-a')+ expect(ws.pathname).toBe('/api/ws')+ expect(ws.searchParams.get('native_dial')).toBe('browser')+ // The session token never rides the socket URL: every dial mints its own one-use ticket.+ expect(ws.searchParams.has('token')).toBe(false)+ expect(ws.searchParams.get('profile')).toBe('worker-a')+ })++ // The serving gateway mints the ticket itself, so there is no gateway to start and no verdict to+ // translate: a failed mint is reported as the route answered it.+ it("reports a failed mint as the route's own answer", async () => {+ const win = mutableWindow()+ seedWebappSession('served-token')+ vi.stubGlobal(+ 'fetch',+ vi.fn().mockResolvedValue(new Response('{"detail":"gateway unavailable"}', { status: 503 }))+ )++ expect(installBrowserDesktopBridge()).toBe(true)++ await expect(win.hermesDesktop!.getGatewayWsUrl('worker-a')).rejects.toThrow(+ '503: {"detail":"gateway unavailable"}'+ )+ })++ it('bounds the ticket mint by the ordinary request timeout, not a gateway cold start', async () => {+ vi.useFakeTimers()++ try {+ const win = mutableWindow()+ seedWebappSession('served-token')+ vi.stubGlobal(+ 'fetch',+ vi.fn().mockImplementation(+ (_url: URL, init: RequestInit) =>+ new Promise((_resolve, reject) =>+ init.signal?.addEventListener('abort', () => reject(new DOMException('aborted', 'AbortError')))+ )+ )+ )++ expect(installBrowserDesktopBridge()).toBe(true)++ const minted = win.hermesDesktop!.getGatewayWsUrl('worker-a')+ const settled = expect(minted).rejects.toThrow('aborted')+ await vi.advanceTimersByTimeAsync(30_000)+ await settled+ } finally {+ vi.useRealTimers()+ }+ })+})diff --git a/apps/desktop/src/lib/browser-desktop-bridge.ts b/apps/desktop/src/lib/browser-desktop-bridge.tsnew file mode 100644index 00000000000..001eb34a42b--- /dev/null+++ b/apps/desktop/src/lib/browser-desktop-bridge.ts@@ -0,0 +1,143 @@+import { externalUrlTarget } from '@hermes/shared'++import type { HermesApiRequest } from '@/global'+import { BROWSER_BRIDGE_STUBS } from '@/lib/browser-bridge-stubs'+import { createBrowserClipboardBridge } from '@/lib/browser-clipboard'+import { createBrowserConnectionBridge } from '@/lib/browser-connection'+import { createBrowserFilesBridge } from '@/lib/browser-files'+import { watchWebappLaunchLink } from '@/lib/browser-launch-session'+import { createBrowserProfileBridge } from '@/lib/browser-profile'+import { createBrowserSettings } from '@/lib/browser-settings'+import { createBrowserTerminal } from '@/lib/browser-terminal'+import { authenticatedWebsocketUrl, browserApi, browserBootstrap } from '@/lib/browser-transport'+import { createBrowserUploadsBridge } from '@/lib/browser-uploads'+import { createBrowserWindowOpener, sessionWindowTarget } from '@/lib/browser-window'+import { createBrowserZoom } from '@/lib/browser-zoom'+import { $connection } from '@/store/session'+import { windowProfileOverride } from '@/store/windows'++import { resolveGatewayVersion } from '../../electron/gateway-version'++/**+ * Install a capability-limited Desktop bridge when the real renderer is served+ * directly by Hermes' authenticated web server.+ *+ * Electron remains authoritative everywhere it exists: no injected dashboard+ * token means this is a normal Vite/Electron renderer, and an existing preload+ * bridge is never replaced. Browser-hosted mode maps the Desktop's backend+ * contract onto the same-origin /api + /api/ws surface and deliberately exposes+ * only safe browser equivalents for machine-level capabilities.+ */+export function installBrowserDesktopBridge(): boolean {+ if (window.hermesDesktop) {return false}++ const bootstrap = browserBootstrap()++ if (!bootstrap) {return false}++ if (bootstrap.privateSession) {+ watchWebappLaunchLink(() => window.location.reload())+ }++ const api = <T>(request: HermesApiRequest) => browserApi<T>(bootstrap, request)++ const currentProfile = () => $connection.get()?.profile?.trim() || windowProfileOverride()++ const objectUrls = new Set<string>()+ const previewUrls = new Set<string>()++ window.addEventListener(+ 'beforeunload',+ () => {+ objectUrls.forEach(url => URL.revokeObjectURL(url))+ objectUrls.clear()+ previewUrls.clear()+ },+ { once: true }+ )++ const openWindow = createBrowserWindowOpener({+ api,+ basePath: bootstrap.basePath,+ privateSession: bootstrap.privateSession+ })++ // Electron's opener rule: agent- or tool-supplied links must not run script+ // or custom schemes on this origin, whose cookie authenticates the API. A+ // `file:` URL names the server's disk, and this browser cannot open it.+ const openExternal = async (url: string) => {+ const target = externalUrlTarget(url)++ if (target?.kind === 'web') {window.open(target.url, '_blank', 'noopener,noreferrer')}+ }++ const uploads = createBrowserUploadsBridge({ api, bootstrap, currentProfile, objectUrls, previewUrls })++ const bridge: Window['hermesDesktop'] = {+ ...BROWSER_BRIDGE_STUBS,+ ...createBrowserClipboardBridge({ saveBuffer: uploads.saveImageBuffer }),+ ...createBrowserConnectionBridge({ api, bootstrap }),+ ...createBrowserFilesBridge({ api, bootstrap, currentProfile }),+ ...uploads,+ api,+ // This renderer is built from the serving checkout, so its version is the+ // server's, read the way native Desktop reads its runtime's.+ getVersion: async () => ({+ appVersion: await resolveGatewayVersion(path => api({ path, timeoutMs: 5000 })),+ electronVersion: '',+ hermesRoot: '',+ nodeVersion: '',+ platform: 'browser'+ }),+ findInPage: async (query: string) => {+ const find = (window as Window & { find?: (value: string) => boolean }).find++ return { count: query && find?.call(window, query) ? 1 : 0 }+ },+ notify: async ({ title, body }: { title?: string; body?: string }) => {+ if (!('Notification' in window)) {return false}++ if (Notification.permission === 'default') {await Notification.requestPermission()}++ if (Notification.permission !== 'granted') {return false}+ new Notification(title || 'Hermes', { body })++ return true+ },+ openExternal,+ openPreviewInBrowser: async url => {+ // Only this install's sandbox wrappers may open as same-origin blobs.+ if (previewUrls.has(url)) {+ window.open(url, '_blank', 'noopener,noreferrer')+ } else {+ await openExternal(url)+ }+ },+ openSessionWindow: async (sessionId, opts) => {+ const target = sessionWindowTarget(window.location.href, sessionId, opts)++ return target ? openWindow(target) : { error: 'invalid_session_id', ok: false }+ },+ settings: createBrowserSettings({ basePath: bootstrap.basePath, currentProfile }),+ requestMicrophoneAccess: async () => {+ if (!navigator.mediaDevices?.getUserMedia) {return false}+ const stream = await navigator.mediaDevices.getUserMedia({ audio: true })+ stream.getTracks().forEach(track => track.stop())++ return true+ },+ terminal: createBrowserTerminal({+ basePath: bootstrap.basePath,+ currentProfile,+ websocketUrl: profile => authenticatedWebsocketUrl(bootstrap, '/api/host-terminal', profile),+ defaultCwd: async profile => (await api<{ cwd?: string }>({ path: '/api/fs/default-cwd', profile })).cwd || ''+ }),+ ...createBrowserProfileBridge({ basePath: bootstrap.basePath, currentProfile, openWindow }),+ zoom: createBrowserZoom(bootstrap.basePath)+ }++ window.hermesDesktop = bridge+ document.documentElement.dataset.hermesDesktopHost = 'browser'++ return true+}diff --git a/apps/desktop/src/lib/browser-files.ts b/apps/desktop/src/lib/browser-files.tsnew file mode 100644index 00000000000..2b35a072453--- /dev/null+++ b/apps/desktop/src/lib/browser-files.ts@@ -0,0 +1,106 @@+import type { HermesApiRequest } from '@/global'+import { translateNow } from '@/i18n'+import { requireBrowserConnection } from '@/lib/browser-connection'+import { fetchBrowserImage } from '@/lib/browser-image-download'+import { type BrowserBootstrap, fileEndpointUrl } from '@/lib/browser-transport'+import { clickDownloadLink, downloadBlob, downloadFilename } from '@/lib/download'+import { notifyError } from '@/store/notifications'++function queryPath(route: string, values: Record<string, boolean | null | string | undefined>) {+ const query = new URLSearchParams()++ for (const [key, value] of Object.entries(values)) {+ if (value !== null && value !== undefined) {query.set(key, String(value))}+ }++ return `${route}?${query.toString()}`+}++interface BrowserFilesOptions {+ api: <T>(request: HermesApiRequest) => Promise<T>+ bootstrap: BrowserBootstrap+ currentProfile: () => string | null+}++/** Server files reach the page through /api/fs reads and ticketed download/stream URLs. */+export function createBrowserFilesBridge({+ api,+ bootstrap,+ currentProfile+}: BrowserFilesOptions): Pick<+ Window['hermesDesktop'],+ | 'getGatewayFileStreamUrl'+ | 'readDir'+ | 'readFileDataUrl'+ | 'readFileDataUrlForAttach'+ | 'readFileText'+ | 'saveGatewayFile'+ | 'saveImageFromUrl'+> {+ const fsGet = <T>(route: string, path: string) =>+ api<T>({ path: queryPath(`/api/fs/${route}`, { path }), profile: currentProfile() })++ const readDataUrl = async (path: string) => (await fsGet<{ dataUrl: string }>('read-data-url', path)).dataUrl++ const downloadUrl = async (url: string, filename = '') => {+ const target = new URL(url, window.location.href)++ // Cross-origin anchors ignore download and navigate the current tab.+ // Fetch without Hermes credentials; CORS denial must not fall back to navigation.+ if (target.origin !== window.location.origin && !['blob:', 'data:'].includes(target.protocol)) {+ const image = await fetchBrowserImage(target)++ // A blob URL carries no name of its own; unnamed, the file saves as its UUID.+ downloadBlob(image, filename || downloadFilename(target.href, image.type))+ } else {+ // An empty name lets the server's Content-Disposition name gateway files.+ clickDownloadLink(target.href, filename)+ }++ return true+ }++ return {+ getGatewayFileStreamUrl: async payload => {+ requireBrowserConnection(payload.connectionId)++ return (await fileEndpointUrl(bootstrap, 'stream', {+ path: payload.path,+ profile: payload.profile ?? currentProfile()+ })).href+ },+ readDir: (path: string) =>+ fsGet<Awaited<ReturnType<Window['hermesDesktop']['readDir']>>>('list', path),+ readFileDataUrl: readDataUrl,+ readFileDataUrlForAttach: readDataUrl,+ readFileText: (path: string) =>+ fsGet<Awaited<ReturnType<Window['hermesDesktop']['readFileText']>>>('read-text', path),+ saveGatewayFile: async payload => {+ requireBrowserConnection(payload.connectionId)+ const query = { path: payload.path, profile: payload.profile ?? currentProfile(), session_id: payload.sessionId }++ // Validate before handing the transfer to the browser so missing or+ // denied files surface in the chat without navigating away. HEAD keeps+ // large downloads out of renderer memory.+ await api({+ method: 'HEAD',+ path: queryPath('/api/files/download', { path: query.path, session_id: query.session_id }),+ profile: query.profile+ })++ return {+ saved: await downloadUrl((await fileEndpointUrl(bootstrap, 'download', query)).href, payload.suggestedName)+ }+ },+ saveImageFromUrl: async (url: string) => {+ try {+ return await downloadUrl(url)+ } catch (error) {+ // Context-menu consumers fire and forget; surface failures here.+ notifyError(error, translateNow('fileMenu.downloadFailed'))++ return false+ }+ }+ }+}diff --git a/apps/desktop/src/lib/browser-image-download.ts b/apps/desktop/src/lib/browser-image-download.tsnew file mode 100644index 00000000000..760932e97a9--- /dev/null+++ b/apps/desktop/src/lib/browser-image-download.ts@@ -0,0 +1,58 @@+// Match the image attachment byte budget without limiting browser-managed files.+export const BROWSER_IMAGE_DOWNLOAD_MAX_BYTES = 25 * 1024 * 1024+export const BROWSER_IMAGE_DOWNLOAD_TIMEOUT_MS = 30_000++/** Fetch only cross-origin images here; gateway files stay browser-managed. */+export async function fetchBrowserImage(url: URL): Promise<Blob> {+ const controller = new AbortController()+ let reader: ReadableStreamDefaultReader<Uint8Array> | undefined+ let timer: number | undefined++ const deadline = new Promise<never>((_, reject) => {+ timer = window.setTimeout(() => {+ reject(new Error('Image download timed out after 30 seconds. Try again or open the image in a separate tab.'))+ }, BROWSER_IMAGE_DOWNLOAD_TIMEOUT_MS)+ })++ const download = async () => {+ const response = await fetch(url, { credentials: 'omit', mode: 'cors', signal: controller.signal })+ controller.signal.throwIfAborted()+ reader = response.body?.getReader()++ if (!response.ok) {throw new Error(`Image download failed (${response.status})`)}++ if (!reader) {throw new Error('Image download has no readable body. Try opening the image in a separate tab.')}++ const chunks: Uint8Array<ArrayBuffer>[] = []+ let received = 0++ while (true) {+ const { done, value } = await reader.read()+ controller.signal.throwIfAborted()++ if (done) {break}+ received += value.byteLength++ // Content-Length may be absent, incorrect, or describe compressed bytes.+ if (received > BROWSER_IMAGE_DOWNLOAD_MAX_BYTES) {+ throw new Error('Image download exceeds 25 MiB. Open the image in a separate tab to save it.')+ }++ chunks.push(value.slice())+ }++ return new Blob(chunks, { type: response.headers.get('content-type') || '' })+ }++ try {+ return await Promise.race([download(), deadline])+ } catch (error) {+ // Do not wait for a stalled cancellation handshake before reporting failure.+ void reader?.cancel(error).catch(() => undefined)+ controller.abort(error)+ throw error+ } finally {+ window.clearTimeout(timer)+ reader?.releaseLock()+ }+}diff --git a/apps/desktop/src/lib/browser-launch-session.test.ts b/apps/desktop/src/lib/browser-launch-session.test.tsnew file mode 100644index 00000000000..6d0f4b5d4ae--- /dev/null+++ b/apps/desktop/src/lib/browser-launch-session.test.ts@@ -0,0 +1,176 @@+import { afterEach, expect, it, vi } from 'vitest'++import { installBrowserDesktopBridge } from './browser-desktop-bridge'+import { consumeWebappSession, watchWebappLaunchLink } from './browser-launch-session'++const win = window as Window & {+ __HERMES_UI_SURFACE__?: string+ __HERMES_BASE_PATH__?: string+ __HERMES_AUTH_REQUIRED__?: boolean+}++afterEach(() => {+ window.dispatchEvent(new Event('beforeunload'))+ Reflect.deleteProperty(window, 'hermesDesktop')+ delete win.__HERMES_UI_SURFACE__+ delete win.__HERMES_BASE_PATH__+ delete win.__HERMES_AUTH_REQUIRED__+ sessionStorage.clear()+ localStorage.clear()+ window.history.replaceState(null, '', '/')+ vi.unstubAllGlobals()+ vi.restoreAllMocks()+})++it('uses one private session for REST, RPC and terminal across reload without losing the profile', async () => {+ const token = 'a'.repeat(43)+ win.__HERMES_UI_SURFACE__ = 'webapp'+ win.__HERMES_BASE_PATH__ = '/one'+ window.history.replaceState(null, '', `/one/?profile=coder#hermes-session=${token}`)+ const urls: URL[] = []++ class Socket {+ onmessage: ((event: { data: string }) => void) | null = null+ constructor(url: URL) {+ urls.push(new URL(url))+ queueMicrotask(() => this.onmessage?.({ data: '\0HERMES_TERMINAL_META:{"terminalId":"shell","pid":1,"cwd":"/work","shell":"sh","reconnected":false}' }))+ }+ close() {}+ }++ vi.stubGlobal('WebSocket', Socket)++ const fetchMock = vi.fn().mockImplementation(async (url: URL) =>+ new Response(url.pathname.endsWith('/api/webapp/gateway-ticket') ? '{"ticket":"rpc-ticket"}' : '{"ok":true}', { status: 200 })+ )++ vi.stubGlobal('fetch', fetchMock)+ expect(installBrowserDesktopBridge()).toBe(true)+ expect(window.location.hash).toBe('')+ expect(window.location.search).toBe('?profile=coder')+ const desktop = window.hermesDesktop!+ await desktop.api({ path: '/api/fs/read-text' })+ expect(new Headers(fetchMock.mock.calls[0][1].headers).get('X-Hermes-Session-Token')).toBe(token)+ expect((await desktop.getConnection()).token).toBe(token)+ // RPC: the gateway socket's one-use ticket is minted over REST with the same private session;+ // the session token itself never rides a socket URL.+ expect(new URL((await desktop.getConnection()).wsUrl).searchParams.has('token')).toBe(false)+ // As the boot dial does (resolveGatewayWsUrl): mint for the descriptor's own profile.+ const rpc = await desktop.getGatewayWsUrl((await desktop.getConnection()).profile)+ const rpcUrl = new URL(typeof rpc === 'string' ? rpc : rpc.ok ? rpc.wsUrl : '')+ expect(rpcUrl.searchParams.get('ticket')).toBe('rpc-ticket')+ expect(rpcUrl.searchParams.get('profile')).toBe('coder')+ const mint = fetchMock.mock.calls.find(([url]) => (url as URL).pathname === '/one/api/webapp/gateway-ticket')!+ expect(new Headers(mint[1].headers).get('X-Hermes-Session-Token')).toBe(token)+ await desktop.terminal.start({ cwd: '/work' })+ expect(urls[0].pathname).toBe('/one/api/host-terminal')+ expect(urls[0].searchParams.get('token')).toBe(token)+ window.dispatchEvent(new Event('beforeunload'))+ Reflect.deleteProperty(window, 'hermesDesktop')+ window.history.replaceState(null, '', '/one/?profile=coder#/settings')+ expect(installBrowserDesktopBridge()).toBe(true)+ expect((await window.hermesDesktop!.getConnection()).token).toBe(token)+ expect(window.location.hash).toBe('#/settings')+ expect(consumeWebappSession('/other')).toBe('')+ expect(Object.values(localStorage)).not.toContain(token)+})++it('fails closed with actionable launch instructions in a fresh tab and ignores local grants under OAuth', async () => {+ win.__HERMES_UI_SURFACE__ = 'webapp'+ const fetchMock = vi.fn()+ vi.stubGlobal('fetch', fetchMock)+ expect(installBrowserDesktopBridge()).toBe(true)+ await expect(window.hermesDesktop!.getConnection()).rejects.toThrow('private launch link')+ await expect(window.hermesDesktop!.api({ path: '/api/fs/read-text' })).rejects.toThrow('private launch link')+ expect(fetchMock).not.toHaveBeenCalled()+ window.dispatchEvent(new Event('beforeunload'))+ Reflect.deleteProperty(window, 'hermesDesktop')+ window.history.replaceState(null, '', `/#hermes-session=${'b'.repeat(43)}`)+ expect(consumeWebappSession('')).toHaveLength(43)+ window.history.replaceState(null, '', '/#hermes-session=invalid')+ expect(consumeWebappSession('')).toBe('')+ expect(consumeWebappSession('')).toBe('')+ win.__HERMES_AUTH_REQUIRED__ = true+ expect(installBrowserDesktopBridge()).toBe(true)+ expect((await window.hermesDesktop!.getConnection()).authMode).toBe('oauth')+ expect((await window.hermesDesktop!.getConnection()).token).toBe('')+})++it('reloads for a pasted launch fragment but not HashRouter navigation', () => {+ const reload = vi.fn()+ watchWebappLaunchLink(reload)+ window.history.replaceState(null, '', '/#/settings')+ window.dispatchEvent(new HashChangeEvent('hashchange'))+ expect(reload).not.toHaveBeenCalled()+ const fragment = `#hermes-session=${'c'.repeat(43)}`+ window.history.replaceState(null, '', `/${fragment}`)+ window.dispatchEvent(new HashChangeEvent('hashchange'))+ expect(reload).toHaveBeenCalledOnce()+ expect(window.location.hash).toBe(fragment)+ window.dispatchEvent(new Event('beforeunload'))+ window.dispatchEvent(new HashChangeEvent('hashchange'))+ expect(reload).toHaveBeenCalledOnce()+})++it.each(['window', 'session'] as const)('hands off a private %s through a one-use ticket without sharing its session token', async kind => {+ const token = 'a'.repeat(43)+ const ticket = 'b'.repeat(43)+ win.__HERMES_UI_SURFACE__ = 'webapp'+ win.__HERMES_BASE_PATH__ = '/one'+ window.history.replaceState(null, '', `/one/?profile=coder#hermes-session=${token}`)+ const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({ ticket })))+ vi.stubGlobal('fetch', fetchMock)++ class Channel {+ static current: Channel+ onmessage: ((event: { data: unknown }) => void) | null = null+ constructor(readonly name: string) { Channel.current = this }+ postMessage = vi.fn(() => queueMicrotask(() => this.onmessage?.({ data: { type: 'done' } })))+ close = vi.fn()+ }+ vi.stubGlobal('BroadcastChannel', Channel)+ const open = vi.spyOn(window, 'open').mockReturnValue(null)+ expect(installBrowserDesktopBridge()).toBe(true)++ const pending = kind === 'window'+ ? window.hermesDesktop.openWindow({ connectionId: 'local', profile: 'research' })+ : window.hermesDesktop.openSessionWindow('session / 1', { profile: 'research', watch: true })++ // The window opens before any await, preserving the browser user gesture.+ expect(open).toHaveBeenCalledOnce()+ expect(fetchMock).not.toHaveBeenCalled()+ Channel.current.onmessage?.({ data: { type: 'ready' } })+ await pending++ expect(fetchMock).toHaveBeenCalledOnce()+ const [url, init] = fetchMock.mock.calls[0] as [URL, RequestInit]+ expect(url.pathname).toBe('/one/api/webapp/window-ticket')+ expect(init.method).toBe('POST')+ expect(new Headers(init.headers).get('X-Hermes-Session-Token')).toBe(token)+ expect(open).toHaveBeenCalledOnce()+ const [opened, target, features] = open.mock.calls[0]+ const child = new URL(String(opened))+ expect(child.origin).toBe(window.location.origin)+ expect(child.pathname).toBe('/one/webapp/window')+ expect(child.search).toBe('')+ const handoff = new URLSearchParams(child.hash.slice(1))+ expect(Channel.current.name).toBe(`hermes.webapp.window:${handoff.get('channel')}`)+ expect(Channel.current.postMessage).toHaveBeenCalledWith({ ticket })+ expect(Channel.current.close).toHaveBeenCalledOnce()+ expect(handoff.get('query')).toContain('profile=research')+ expect(handoff.get('route')).toBe(kind === 'window' ? '/' : '/session%20%2F%201')+ expect(handoff.get('query')?.includes('watch=1')).toBe(kind === 'session')+ expect([target, features]).toEqual(['_blank', 'noopener,noreferrer'])+ expect(String(opened)).not.toContain(token)+ expect(String(opened)).not.toContain(ticket)+ expect(window.location.search).toBe('?profile=coder')+ expect(Object.values(localStorage)).not.toContain(token)++ fetchMock.mockResolvedValueOnce(new Response('Unauthorized', { status: 401 }))+ open.mockClear()+ const failed = window.hermesDesktop.openWindow()+ Channel.current.onmessage?.({ data: { type: 'ready' } })+ await expect(failed).rejects.toThrow()+ expect(Channel.current.postMessage).toHaveBeenCalledWith({ error: expect.any(String) })+ expect(Channel.current.close).toHaveBeenCalledOnce()+})diff --git a/apps/desktop/src/lib/browser-launch-session.ts b/apps/desktop/src/lib/browser-launch-session.tsnew file mode 100644index 00000000000..fb634ea7b40--- /dev/null+++ b/apps/desktop/src/lib/browser-launch-session.ts@@ -0,0 +1,39 @@+const FRAGMENT_KEY = 'hermes-session'++export const WEBAPP_LAUNCH_REQUIRED = 'Open the private launch link printed by hermes webapp in this tab. If the gateway restarted or the link is lost, run hermes webapp again to get a new link. Keep the link private: it grants host access.'++/** Pasting the launch link over a bare URL is a same-document navigation. */+export function watchWebappLaunchLink(reload: () => void): void {+ const onHash = () => {+ // Leave the fragment intact: startup consumes it even if storage is disabled.+ if (window.location.hash.startsWith(`#${FRAGMENT_KEY}=`)) {reload()}+ }++ window.addEventListener('hashchange', onHash)+ window.addEventListener('beforeunload', () => window.removeEventListener('hashchange', onHash), { once: true })+}++/** Where this tab keeps its launch-link grant for the Webapp at ``basePath`` on this origin. */+export function webappSessionKey(basePath: string): string {+ return `hermes.webapp.session.v1:${JSON.stringify([window.location.origin, basePath])}`+}++/** HTTP never supplies this credential; reloads keep only this tab's grant. */+export function consumeWebappSession(basePath: string): string {+ const key = webappSessionKey(basePath)++ // HashRouter owns other fragments; don't parse/rewrite its route on reload.+ if (window.location.hash.startsWith(`#${FRAGMENT_KEY}=`)) {+ const supplied = new URLSearchParams(window.location.hash.slice(1)).getAll(FRAGMENT_KEY)+ window.history.replaceState(window.history.state, '', `${window.location.pathname}${window.location.search}`)+ const token = supplied.length === 1 && /^[A-Za-z0-9_-]{43}$/.test(supplied[0]) ? supplied[0] : ''++ try {+ if (token) {sessionStorage.setItem(key, token)} else {sessionStorage.removeItem(key)}+ } catch { /* Storage may be disabled; the current page can still use its link. */ }++ return token+ }++ try { return sessionStorage.getItem(key) || '' } catch { return '' }+}diff --git a/apps/desktop/src/lib/browser-profile.test.ts b/apps/desktop/src/lib/browser-profile.test.tsnew file mode 100644index 00000000000..3ebe8d21ebd--- /dev/null+++ b/apps/desktop/src/lib/browser-profile.test.ts@@ -0,0 +1,103 @@+import { afterEach, beforeEach, expect, it, vi } from 'vitest'++import { $connection } from '@/store/session'+import { clearWebappSession, seedWebappSession } from '@/test/webapp-session'++import { installBrowserDesktopBridge } from './browser-desktop-bridge'++const bootstrap = window as Window & {+ __HERMES_AUTH_REQUIRED__?: boolean+ __HERMES_BASE_PATH__?: string+}++beforeEach(() => {+ window.localStorage.clear()+ bootstrap.__HERMES_BASE_PATH__ = '/hermes'+ seedWebappSession('test-session')+ window.history.replaceState(null, '', '/hermes?profile=active#/session-1')+})++afterEach(() => {+ Reflect.deleteProperty(window, 'hermesDesktop')+ delete bootstrap.__HERMES_AUTH_REQUIRED__+ delete bootstrap.__HERMES_BASE_PATH__+ clearWebappSession()+ document.documentElement.removeAttribute('data-hermes-desktop-host')+ window.localStorage.clear()+ window.history.replaceState(null, '', '/#/')+ $connection.set(null)+ vi.restoreAllMocks()+})++it('persists the default separately from the active chat and synchronizes only the same server across tabs', async () => {+ expect(installBrowserDesktopBridge()).toBe(true)+ const profile = window.hermesDesktop.profile+ const originalUrl = window.location.href+ const changed = vi.fn()+ const unsubscribe = profile.onDefaultChanged(changed)+ const route = { connectionId: 'local', profile: 'research' }++ await expect(profile.setDefault(route)).resolves.toEqual(route)+ expect(window.location.href).toBe(originalUrl)+ await expect(profile.get()).resolves.toEqual({ profile: 'active' })+ expect(changed).toHaveBeenLastCalledWith(route)+ await profile.remember('work')+ await expect(profile.getDefault()).resolves.toEqual(route)++ Reflect.deleteProperty(window, 'hermesDesktop')+ expect(installBrowserDesktopBridge()).toBe(true)+ await expect(window.hermesDesktop.profile.getDefault()).resolves.toEqual(route)+ Reflect.deleteProperty(window, 'hermesDesktop')+ bootstrap.__HERMES_BASE_PATH__ = '/another-server'+ expect(installBrowserDesktopBridge()).toBe(true)+ await expect(window.hermesDesktop.profile.getDefault()).resolves.toBeNull()++ const key = window.localStorage.key(0)!+ const updated = { ...route, profile: 'review' }+ window.localStorage.setItem(key, JSON.stringify(updated))+ const storageEvent = () => Object.assign(new Event('storage'), { key, storageArea: window.localStorage })+ window.dispatchEvent(storageEvent())+ expect(changed).toHaveBeenLastCalledWith(updated)+ unsubscribe()+ changed.mockClear()+ window.dispatchEvent(storageEvent())+ expect(changed).not.toHaveBeenCalled()+})++it('opens the requested profile on this host without carrying another session or spectator flags', async () => {+ // A gated host opens the window directly; a launch-link tab hands it a session first.+ bootstrap.__HERMES_AUTH_REQUIRED__ = true+ window.history.replaceState(null, '', '/hermes?profile=active&win=secondary&watch=1#/session-1')+ const open = vi.spyOn(window, 'open').mockImplementation(() => null)+ expect(installBrowserDesktopBridge()).toBe(true)++ const originalUrl = window.location.href+ await window.hermesDesktop.openWindow()+ const peer = new URL(String(open.mock.calls[0][0]))+ expect(peer.searchParams.get('profile')).toBe('active')+ expect(peer.searchParams.has('watch')).toBe(false)+ expect(peer.searchParams.has('win')).toBe(false)+ expect(peer.hash).toBe('#/')+ expect(window.location.href).toBe(originalUrl)+ open.mockClear()++ await window.hermesDesktop.openWindow({ connectionId: 'local', profile: 'research' })+ const target = new URL(String(open.mock.calls[0][0]))+ expect(target.origin).toBe(window.location.origin)+ expect(target.pathname).toBe('/hermes')+ expect(target.searchParams.get('profile')).toBe('research')+ expect(target.searchParams.has('watch')).toBe(false)+ expect(target.searchParams.has('win')).toBe(false)+ expect(target.hash).toBe('#/')++ await window.hermesDesktop.openWindow({ connectionId: null, profile: 'default' })+ expect(new URL(String(open.mock.calls[1][0])).searchParams.get('profile')).toBe('default')+ open.mockClear()+ await expect(window.hermesDesktop.openWindow({ connectionId: 'another-host', profile: 'research' })).rejects.toThrow(+ 'No connection with id'+ )+ await expect(+ window.hermesDesktop.profile.setDefault({ connectionId: 'another-host', profile: 'research' })+ ).rejects.toThrow('No connection with id')+ expect(open).not.toHaveBeenCalled()+})diff --git a/apps/desktop/src/lib/browser-profile.ts b/apps/desktop/src/lib/browser-profile.tsnew file mode 100644index 00000000000..2aead968a63--- /dev/null+++ b/apps/desktop/src/lib/browser-profile.ts@@ -0,0 +1,114 @@+import type { DesktopProfileRoute } from '@/global'+import { requireBrowserConnection } from '@/lib/browser-connection'++import { readJson } from './storage'++interface BrowserProfileOptions {+ basePath: string+ currentProfile: () => string | null+ openWindow: (target: URL) => Promise<{ ok: true }>+}++// A tab without `?profile=` boots on this origin's saved default, so a named+// profile — Default included — is always written out; only null clears it.+function setUrlProfile(url: URL, profile: string | null): void {+ if (profile) {+ url.searchParams.set('profile', profile)+ } else {+ url.searchParams.delete('profile')+ }+}++export function createBrowserProfileBridge({+ basePath,+ currentProfile,+ openWindow+}: BrowserProfileOptions): Pick<Window['hermesDesktop'], 'openWindow' | 'profile'> {+ // localStorage supplies origin isolation; the base path separates colocated servers.+ const storageKey = `hermes:webapp:default-profile:${basePath || '/'}`+ const listeners = new Set<(route: DesktopProfileRoute | null) => void>()++ const requireRoute = (value: unknown): DesktopProfileRoute => {+ if (!value || typeof value !== 'object') {+ throw new Error('A profile route is required.')+ }++ const { connectionId, profile } = value as Record<string, unknown>++ if (typeof profile !== 'string' || !/^[a-z0-9][a-z0-9_-]{0,63}$/.test(profile)) {+ throw new Error('Invalid profile name.')+ }++ if (connectionId !== null && typeof connectionId !== 'string') {+ throw new Error('Invalid connection id.')+ }++ requireBrowserConnection(connectionId)++ return { connectionId, profile }+ }++ const readDefault = (): DesktopProfileRoute | null => {+ try {+ return requireRoute(readJson(storageKey))+ } catch {+ return null+ }+ }++ const remember = async (profile: string | null) => {+ const selected = profile?.trim() || null+ const url = new URL(window.location.href)+ setUrlProfile(url, selected)+ window.history.replaceState(null, '', `${url.pathname}${url.search}${url.hash}`)++ return { profile: selected }+ }++ return {+ openWindow: async options => {+ const url = new URL(window.location.href)+ setUrlProfile(url, options === undefined ? currentProfile() : requireRoute(options).profile)++ url.searchParams.delete('win')+ url.searchParams.delete('watch')+ url.hash = '/'++ return openWindow(url)+ },+ profile: {+ get: async () => ({ profile: currentProfile() }),+ getDefault: async () => readDefault(),+ setDefault: async value => {+ const route = requireRoute(value)+ window.localStorage.setItem(storageKey, JSON.stringify(route))+ listeners.forEach(listener => listener(route))++ return route+ },+ onDefaultChanged: callback => {+ listeners.add(callback)++ const onStorage = (event: StorageEvent) => {+ if (event.storageArea === window.localStorage && (event.key === storageKey || event.key === null)) {+ callback(readDefault())+ }+ }++ window.addEventListener('storage', onStorage)++ return () => {+ listeners.delete(callback)+ window.removeEventListener('storage', onStorage)+ }+ },+ remember,+ set: async profile => {+ const result = await remember(profile)+ window.location.reload()++ return result+ }+ }+ }+}diff --git a/apps/desktop/src/lib/browser-settings.ts b/apps/desktop/src/lib/browser-settings.tsnew file mode 100644index 00000000000..87a93e32949--- /dev/null+++ b/apps/desktop/src/lib/browser-settings.ts@@ -0,0 +1,44 @@+import { readKey } from './storage'++interface BrowserSettingsOptions {+ basePath: string+ currentProfile: () => null | string+}++/**+ * The default project folder for new chats, kept in this origin's storage.+ *+ * Electron keeps it in userData; a browser tab has only localStorage. The+ * folder names a path on the machine the profile's workspace browses (this+ * host, or an SSH machine), so the key is scoped to the hosted gateway and the+ * profile. A write that storage refuses rejects, so Settings reports the+ * failure instead of a choice that is gone on the next load.+ */+export function createBrowserSettings({+ basePath,+ currentProfile+}: BrowserSettingsOptions): Window['hermesDesktop']['settings'] {+ const key = () =>+ `hermes:browser:default-project-dir:${JSON.stringify([basePath || '/', currentProfile()?.trim() || 'default'])}`++ return {+ getDefaultProjectDir: async () => ({+ defaultLabel: 'Server workspace',+ dir: readKey(key())?.trim() || null,+ resolvedCwd: ''+ }),+ // The browser picks through the server folder browser (sessions-settings.tsx).+ pickDefaultProjectDir: async () => ({ canceled: true, dir: null }),+ setDefaultProjectDir: async (dir: null | string) => {+ const next = dir?.trim() || null++ if (next) {+ window.localStorage.setItem(key(), next)+ } else {+ window.localStorage.removeItem(key())+ }++ return { dir: next }+ }+ }+}diff --git a/apps/desktop/src/lib/browser-staged-attachments.test.ts b/apps/desktop/src/lib/browser-staged-attachments.test.tsnew file mode 100644index 00000000000..45ef04ede90--- /dev/null+++ b/apps/desktop/src/lib/browser-staged-attachments.test.ts@@ -0,0 +1,336 @@+import { act, cleanup, renderHook } from '@testing-library/react'+import { afterEach, describe, expect, it, vi } from 'vitest'++import { stageDroppedFilePath, useComposerActions } from '@/app/chat/hooks/use-composer-actions'+import { uploadComposerAttachment } from '@/app/session/hooks/use-prompt-actions'+import type { HermesStagedUpload } from '@/global'+import {+ $composerAttachments, clearSessionDraft, type ComposerAttachment, stashSessionDraft, takeSessionDraft+} from '@/store/composer'+import { $notifications, clearNotifications } from '@/store/notifications'+import { $connection, $sessions } from '@/store/session'+import { clearWebappSession, seedWebappSession } from '@/test/webapp-session'++import { installBrowserDesktopBridge } from './browser-desktop-bridge'++const source: HermesStagedUpload = {+ install_id: '11111111111111111111111111111111',+ path: '/srv/hermes/profiles/owner/uploads/web-123-notes.txt',+ profile_home: '/srv/hermes/profiles/owner'+}++const sourceName = source.path.split('/').pop()!+const refText = '@file:/srv/hermes/profiles/owner/attachments/web-123-notes.txt'+const file = () => new File(['payload'], 'notes.txt', { type: 'text/plain' })+const pastedText = 'Pasted notes\nこんにちは 🌍'++const rawAttachment = (path = source.path): ComposerAttachment => ({+ id: `file:${path}`, kind: 'file', label: path.split('/').pop() || path, path+})++const attached = () => ({ attached: true, ref_text: refText, uploaded: true })++async function installBrowser(withProvenance = true) {+ Reflect.deleteProperty(window, 'hermesDesktop')+ seedWebappSession('test-token')++ const fetchMock = vi.fn(async (input: RequestInfo | URL, init?: RequestInit) => {+ const url = new URL(String(input), window.location.origin)++ if (url.pathname === '/api/chat/file-upload' && init?.method === 'POST') {+ return new Response(JSON.stringify({+ path: source.path,+ ...(withProvenance ? { staged_upload: source } : {})+ }))+ }++ if (url.pathname === '/api/fs/read-data-url') {+ return new Response(JSON.stringify({ dataUrl: 'data:text/plain;base64,cGF5bG9hZA==' }))+ }++ throw new Error(`Unexpected fetch: ${url}`)+ })++ vi.stubGlobal('fetch', fetchMock)+ expect(installBrowserDesktopBridge()).toBe(true)+ $connection.set(await window.hermesDesktop.getConnection('owner'))++ return fetchMock+}++afterEach(() => {+ cleanup()+ clearNotifications()+ $composerAttachments.set([])+ clearSessionDraft('staged-attachment-contract')+ $sessions.set([])+ $connection.set(null)+ Reflect.deleteProperty(window, 'hermesDesktop')+ clearWebappSession()+ document.documentElement.removeAttribute('data-hermes-desktop-host')+ vi.unstubAllGlobals()+ vi.restoreAllMocks()+})++describe('browser staged attachment transport', () => {+ it('keeps the picked filename readable while retaining the exact staged source identity', async () => {+ await installBrowser()++ const { result } = renderHook(() => useComposerActions({+ activeSessionId: null, currentCwd: '/workspace', requestGateway: vi.fn()+ }))++ vi.spyOn(HTMLInputElement.prototype, 'click').mockImplementation(function (this: HTMLInputElement) {+ Object.defineProperty(this, 'files', { configurable: true, value: [file()] })+ this.dispatchEvent(new Event('change'))+ })++ await act(async () => { await result.current.pickContextPaths('file') })+ const picked = $composerAttachments.get()[0]!++ expect(picked.label).toBe('notes.txt')+ expect(picked.path).toBe(source.path)+ expect(picked.stagedUpload).toEqual(source)+ stashSessionDraft('staged-attachment-contract', 'draft', [picked])+ expect(takeSessionDraft('staged-attachment-contract').attachments[0]?.label).toBe('notes.txt')+ })++ it.each(['picker', 'drop', 'paste', 'edit-message drop'] as const)(+ '%s sends provenance to the owning gateway without downloading or retransmitting bytes',+ async flow => {+ const fetchMock = await installBrowser()+ let attachment: ComposerAttachment++ if (flow === 'edit-message drop') {+ // This is the actual edit-composer chain; it bypasses the main chip store.+ const path = await stageDroppedFilePath({ file: file(), path: '' })+ attachment = rawAttachment(path)+ } else {+ const { result } = renderHook(() => useComposerActions({+ activeSessionId: null,+ currentCwd: '/workspace',+ requestGateway: vi.fn()+ }))++ if (flow === 'picker') {+ vi.spyOn(HTMLInputElement.prototype, 'click').mockImplementation(function (this: HTMLInputElement) {+ Object.defineProperty(this, 'files', { configurable: true, value: [file()] })+ this.dispatchEvent(new Event('change'))+ })+ await act(async () => { await result.current.pickContextPaths('file') })+ } else if (flow === 'paste') {+ await act(async () => { await result.current.attachPastedText(pastedText) })+ } else {+ await act(async () => { await result.current.attachDroppedItems([{ file: file(), path: '' }]) })+ }++ expect($composerAttachments.get()[0]?.stagedUpload).toEqual(source)+ // A restored draft must not rely on the browser bridge's transient map.+ stashSessionDraft('staged-attachment-contract', 'draft', $composerAttachments.get())+ attachment = takeSessionDraft('staged-attachment-contract').attachments[0]!+ window.hermesDesktop.getStagedFileForAttach = () => undefined+ }++ // The supplied requester can be an explicitly routed tile/edit owner.+ // Changing the foreground profile must not retarget the attachment.+ $connection.set({ ...$connection.get()!, profile: 'foreground-other' })+ const requestGateway = vi.fn(async () => attached() as never)++ const result = await uploadComposerAttachment(attachment, {+ backendCwd: '/workspace', remote: true, requestGateway,+ sessionId: 'owner-runtime', terminalBackend: 'docker'+ })++ expect(requestGateway).toHaveBeenCalledWith('file.attach', {+ name: attachment.label, session_id: 'owner-runtime', staged_upload: source+ })+ expect(result.refText).toBe(refText)+ expect(result.stagedUpload).toEqual(source)+ expect(fetchMock).toHaveBeenCalledTimes(1)+ const [input, init] = fetchMock.mock.calls[0]+ const uploadUrl = new URL(String(input))+ expect(uploadUrl.pathname).toBe('/api/chat/file-upload')+ expect(uploadUrl.searchParams.get('profile')).toBe('owner')++ if (flow === 'paste') {+ const uploadedFile = (init?.body as FormData).get('file') as File+ expect(uploadedFile.name).toMatch(/\.txt$/)+ expect(uploadedFile.type).toBe('text/plain')++ const uploadedText = await new Promise((resolve, reject) => {+ const reader = new FileReader()+ reader.onload = () => resolve(reader.result)+ reader.onerror = () => reject(reader.error)+ reader.readAsText(uploadedFile)+ })++ expect(uploadedText).toBe(pastedText)+ }+ }+ )++ it('keeps source ownership for multiple occurrences of the same staged path', async () => {+ const fetchMock = await installBrowser()+ await stageDroppedFilePath({ file: file(), path: '' })+ const requestGateway = vi.fn(async () => attached() as never)++ for (const sessionId of ['first-composer', 'second-composer']) {+ const result = await uploadComposerAttachment(rawAttachment(), {+ remote: true, requestGateway, sessionId+ })++ expect(result.stagedUpload).toEqual(source)+ }++ expect(requestGateway).toHaveBeenCalledTimes(2)+ expect(fetchMock).toHaveBeenCalledTimes(1)+ })++ it('retains the legacy byte transport when an older upload endpoint supplies only a path', async () => {+ const fetchMock = await installBrowser(false)+ const path = await stageDroppedFilePath({ file: file(), path: '' })+ const requestGateway = vi.fn(async () => attached() as never)+ await uploadComposerAttachment(rawAttachment(path), {+ remote: true, requestGateway, sessionId: 'runtime'+ })+ expect(requestGateway).toHaveBeenCalledWith('file.attach', {+ name: sourceName, path, session_id: 'runtime', data_url: 'data:text/plain;base64,cGF5bG9hZA=='+ })+ expect(fetchMock).toHaveBeenCalledTimes(2)+ })++ it('retries a failed attach from the same source without another upload or download', async () => {+ const fetchMock = await installBrowser()+ const path = await stageDroppedFilePath({ file: file(), path: '' })+ const attachment = { ...rawAttachment(path), stagedUpload: source }++ const requestGateway = vi.fn()+ .mockRejectedValueOnce(new Error('temporary write failure'))+ .mockResolvedValueOnce(attached())++ const opts = { remote: true, requestGateway, sessionId: 'runtime' }+ await expect(uploadComposerAttachment(attachment, opts)).rejects.toThrow('temporary write failure')+ expect(attachment.stagedUpload).toEqual(source)+ expect(attachment.attachedSessionId).toBeUndefined()+ await expect(uploadComposerAttachment(attachment, opts)).resolves.toMatchObject({ refText })+ expect(fetchMock).toHaveBeenCalledTimes(1)+ expect(requestGateway.mock.calls.every(([, params]) => params.staged_upload === source)).toBe(true)+ })++ it('keeps provenance through the existing session-not-found recovery', async () => {+ const fetchMock = await installBrowser()+ await stageDroppedFilePath({ file: file(), path: '' })+ $sessions.set([{ id: 'stored-upload-recovery', profile: 'owner' }] as never)+ let first = true++ const requestGateway = vi.fn(async (method: string) => {+ if (method === 'session.resume') { return { session_id: 'new-runtime' } as never }++ if (first) { first = false; throw new Error('session not found') }++ return attached() as never+ })++ const recovered = vi.fn()++ const result = await uploadComposerAttachment(rawAttachment(), {+ remote: true, requestGateway, sessionId: 'old-runtime', storedSessionId: 'stored-upload-recovery',+ onSessionRecovered: recovered+ })++ expect(result.attachedSessionId).toBe('new-runtime')+ expect(recovered).toHaveBeenCalledWith('new-runtime')+ expect(requestGateway).toHaveBeenLastCalledWith('file.attach', {+ name: sourceName, session_id: 'new-runtime', staged_upload: source+ })+ expect(fetchMock).toHaveBeenCalledTimes(1)+ })++ it.each(['another Hermes backend', 'Profile not found'])(+ 'does not replace an authoritative %s rejection with a byte-upload fallback',+ async message => {+ const fetchMock = await installBrowser()+ await stageDroppedFilePath({ file: file(), path: '' })+ const requestGateway = vi.fn().mockRejectedValue(new Error(message))+ await expect(uploadComposerAttachment(rawAttachment(), {+ remote: true, requestGateway, sessionId: 'runtime'+ })).rejects.toThrow(message)+ expect(requestGateway).toHaveBeenCalledTimes(1)+ expect(fetchMock).toHaveBeenCalledTimes(1)+ }+ )++ // Behind nginx's default 1 MiB client_max_body_size a pick or paste gets+ // nginx's HTML 413 page, and a down backend a proxy's 502: neither is JSON.+ it.each([+ {+ body: '<html><head><title>413 Request Entity Too Large</title></head><body>nginx</body></html>',+ message: /\(413\).*larger than/,+ status: 413+ },+ { body: '<html><body><h1>502 Bad Gateway</h1></body></html>', message: /\(502\)/, status: 502 },+ { body: JSON.stringify({ detail: 'Upload request is too large' }), message: /^Upload request is too large$/, status: 413 }+ ])('reports a $status upload failure from its status or server detail', async ({ body, message, status }) => {+ seedWebappSession('test-token')+ vi.stubGlobal('fetch', vi.fn(async () => new Response(body, { status })))+ expect(installBrowserDesktopBridge()).toBe(true)++ for (const stage of [+ () => window.hermesDesktop.stageFileForAttach!(file()),+ () => window.hermesDesktop.savePastedText(pastedText)+ ]) {+ const failure: unknown = await stage().catch((error: unknown) => error)+ expect(failure).toBeInstanceOf(Error)+ expect(failure).not.toBeInstanceOf(SyntaxError)+ expect((failure as Error).message).toMatch(message)+ }+ })++ it('names the staging failure in the drop warning instead of a bare "Could not attach"', async () => {+ seedWebappSession('test-token')+ const nginx413 = '<html><head><title>413 Request Entity Too Large</title></head><body>nginx</body></html>'+ vi.stubGlobal(+ 'fetch',+ vi.fn(async () => new Response(nginx413, { status: 413 }))+ )+ expect(installBrowserDesktopBridge()).toBe(true)++ const { result } = renderHook(() =>+ useComposerActions({ activeSessionId: null, currentCwd: '/workspace', requestGateway: vi.fn() })+ )++ let attached = true++ await act(async () => {+ attached = await result.current.attachDroppedItems([{ file: file(), path: '' }])+ })++ expect(attached).toBe(false)+ expect($composerAttachments.get()).toEqual([])+ expect($notifications.get()).toEqual([+ expect.objectContaining({+ kind: 'warning',+ message: expect.stringMatching(/notes\.txt.*\(413\): the file is larger than the server or a proxy/)+ })+ ])+ })++ it.each([+ { remote: false, terminalBackend: 'local', upload: false },+ { remote: true, terminalBackend: 'local', upload: true },+ { remote: false, terminalBackend: 'docker', upload: true }+ ])('preserves native attachment transport: %j', async ({ remote, terminalBackend, upload }) => {+ const readFileDataUrl = vi.fn(async () => 'data:text/plain;base64,cGF5bG9hZA==')+ Object.defineProperty(window, 'hermesDesktop', { configurable: true, value: { readFileDataUrl } })+ const requestGateway = vi.fn(async () => attached() as never)+ const path = '/native/notes.txt'+ await uploadComposerAttachment(rawAttachment(path), {+ remote, terminalBackend, requestGateway, sessionId: 'runtime'+ })+ expect(readFileDataUrl).toHaveBeenCalledTimes(upload ? 1 : 0)+ expect(requestGateway).toHaveBeenCalledWith('file.attach', {+ name: 'notes.txt', path, session_id: 'runtime',+ ...(upload ? { data_url: 'data:text/plain;base64,cGF5bG9hZA==' } : {})+ })+ })+})diff --git a/apps/desktop/src/lib/browser-terminal.test.ts b/apps/desktop/src/lib/browser-terminal.test.tsnew file mode 100644index 00000000000..dfd243e4ebc--- /dev/null+++ b/apps/desktop/src/lib/browser-terminal.test.ts@@ -0,0 +1,250 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++import { $connection } from '@/store/session'++import { installBrowserDesktopBridge } from './browser-desktop-bridge'++const META = '\u0000HERMES_TERMINAL_META:'++class Socket {+ static OPEN = 1+ static instances: Socket[] = []+ static reply = (socket: Socket) => socket.metadata()+ readyState = 1+ binaryType = ''+ onmessage: ((event: MessageEvent) => void) | null = null+ onclose: ((event: CloseEvent) => void) | null = null+ onerror: (() => void) | null = null+ sent: string[] = []+ url: URL++ constructor(url: string | URL) {+ this.url = new URL(url)+ Socket.instances.push(this)+ queueMicrotask(() => Socket.reply(this))+ }++ metadata(extra: Record<string, unknown> = {}) {+ this.onmessage?.({ data: META + JSON.stringify({+ shell: 'bash', cwd: '/original', terminalId: 'opaque-server-id', retentionSeconds: 900,+ reconnected: this.url.searchParams.has('attach'), ...extra+ }) } as MessageEvent)+ }++ output(text: string) {+ this.onmessage?.({ data: new TextEncoder().encode(text).buffer } as MessageEvent)+ }++ close(code = 1000, reason = '') {+ this.readyState = 3+ this.onclose?.(new CloseEvent('close', { code, reason }))+ }++ send(data: string) { this.sent.push(data) }+}++function install() {+ Reflect.deleteProperty(window, 'hermesDesktop')+ Object.assign(window, { __HERMES_AUTH_REQUIRED__: true, __HERMES_BASE_PATH__: '/one' })+ installBrowserDesktopBridge()++ return window.hermesDesktop!.terminal+}++beforeEach(() => {+ localStorage.clear()+ vi.useFakeTimers()+ Socket.instances = []+ Socket.reply = socket => socket.metadata()+ vi.stubGlobal('WebSocket', Socket)+ let tickets = 0+ vi.stubGlobal('fetch', vi.fn(async () => new Response(JSON.stringify({ ticket: `fresh-${++tickets}` }))))+ $connection.set({ profile: 'original' } as never)+})++afterEach(() => {+ window.dispatchEvent(new Event('beforeunload'))+ Reflect.deleteProperty(window, 'hermesDesktop')+ Reflect.deleteProperty(window, '__HERMES_AUTH_REQUIRED__')+ Reflect.deleteProperty(window, '__HERMES_BASE_PATH__')+ $connection.set(null)+ vi.useRealTimers()+ vi.unstubAllGlobals()+ vi.restoreAllMocks()+ localStorage.clear()+})++describe('persistent browser terminals', () => {+ it('consumes an empty replay frame without suppressing the first live output', async () => {+ const api = install()+ const session = await api.start({ cwd: '/original', restoreKey: 'empty-history' })+ const output = vi.fn()+ api.onData(session.id, output)+ Socket.instances[0].output('')+ Socket.instances[0].output('\u001b[6n')+ expect(output).toHaveBeenCalledExactlyOnceWith('\u001b[6n')+ })++ it('reattaches the saved tab after reload to its captured profile, not the newly active one', async () => {+ const firstApi = install()+ await firstApi.start({ cwd: '/original', restoreKey: 'tab-one' })+ window.dispatchEvent(new Event('beforeunload'))+ $connection.set({ profile: 'other' } as never)+ const secondApi = install()+ const session = await secondApi.start({ cwd: '/other', restoreKey: 'tab-one' })+ const socket = Socket.instances.at(-1)!+ expect(socket.url.searchParams.get('attach')).toBe('opaque-server-id')+ expect(socket.url.searchParams.get('profile')).toBe('original')+ expect(session.cwd).toBe('/original')+ expect(socket.url.searchParams.get('ticket')).not.toBe(Socket.instances[0].url.searchParams.get('ticket'))+ expect(Socket.instances.some(s => s.url.searchParams.get('action') === 'close')).toBe(false)+ })++ it('automatically reconnects without reporting exit, resets before replay, and does not send input offline', async () => {+ const api = install()+ const session = await api.start({ cwd: '/original', restoreKey: 'tab-one' })+ const output = vi.fn()+ const exit = vi.fn()+ api.onData(session.id, output)+ api.onExit(session.id, exit)+ Socket.instances[0].output('before')+ Socket.instances[0].close(1006)+ await expect(api.write(session.id, 'dangerous command\r')).resolves.toBe(false)+ await api.resize(session.id, { cols: 97, rows: 31 })+ await vi.advanceTimersByTimeAsync(1000)+ expect(Socket.instances).toHaveLength(2)+ const resumed = Socket.instances[1]+ expect(resumed.url.searchParams.get('attach')).toBe('opaque-server-id')+ expect(resumed.url.searchParams.get('cols')).toBe('97')+ expect(resumed.sent).toContain('\u001b[RESIZE:97;31]')+ resumed.output('before\r\nafter')+ const frames = output.mock.calls.map(([data]) => data as string)+ expect(frames.at(-2)).toContain('\u001bc')+ expect(frames.at(-1)).toBe('before\r\nafter')+ expect(exit).not.toHaveBeenCalled()+ expect(resumed.sent.join('')).not.toContain('dangerous command')+ expect(resumed.sent.join('')).not.toContain('\u000c')+ })++ it('closes explicitly with a fresh authenticated request even while disconnected', async () => {+ const api = install()+ const session = await api.start({ cwd: '/original', restoreKey: 'tab-one' })+ Socket.instances[0].close(1006)++ Socket.reply = socket => {+ socket.metadata({ closed: true })+ socket.close()+ }++ await expect(api.dispose(session.id)).resolves.toBe(true)+ const close = Socket.instances.at(-1)!+ expect(close.url.searchParams.get('action')).toBe('close')+ expect(close.url.searchParams.get('attach')).toBe('opaque-server-id')+ expect(close.url.searchParams.get('profile')).toBe('original')+ await vi.advanceTimersByTimeAsync(30_000)+ expect(Socket.instances).toHaveLength(2)+ expect(localStorage.length).toBe(0)+ })++ it('stops on supersession rather than fighting the other tab, and retains the resume identity', async () => {+ const api = install()+ const session = await api.start({ cwd: '/original', restoreKey: 'tab-one' })+ const exit = vi.fn()+ api.onExit(session.id, exit)+ Socket.instances[0].close(4409)+ await vi.advanceTimersByTimeAsync(30_000)+ expect(Socket.instances).toHaveLength(1)+ expect(exit).toHaveBeenCalledWith({ code: null, signal: 'superseded' })+ expect(localStorage.length).toBe(1)+ })++ it('reports expired resumes without silently creating a replacement shell', async () => {+ const api = install()+ const session = await api.start({ cwd: '/original', restoreKey: 'tab-one' })+ const exit = vi.fn()+ api.onExit(session.id, exit)+ Socket.instances[0].close(1006)+ Socket.reply = socket => socket.close(4410, 'Terminal expired')+ await vi.advanceTimersByTimeAsync(30_000)+ expect(Socket.instances).toHaveLength(2)+ expect(exit).toHaveBeenCalledWith({ code: null, signal: 'expired' })+ expect(localStorage.length).toBe(0)+ })++ it('never retries denied attachments or silently adopts the active profile', async () => {+ const api = install()+ const session = await api.start({ cwd: '/original', restoreKey: 'tab-one' })+ Socket.instances[0].close(1006)+ const exit = vi.fn()+ api.onExit(session.id, exit)+ $connection.set({ profile: 'other' } as never)+ Socket.reply = socket => socket.close(4403)+ await vi.advanceTimersByTimeAsync(30_000)+ expect(Socket.instances).toHaveLength(2)+ expect(exit).toHaveBeenCalledWith({ code: null, signal: 'denied' })+ expect(Socket.instances[1].url.searchParams.get('profile')).toBe('original')+ })++ it('bounds network retries and resumes after bfcache without duplicating viewers', async () => {+ const api = install()+ const session = await api.start({ cwd: '/original', restoreKey: 'tab-one' })+ const state = vi.fn()+ const exit = vi.fn()+ api.onState!(session.id, state)+ api.onExit(session.id, exit)+ window.dispatchEvent(new Event('beforeunload'))+ window.dispatchEvent(new PageTransitionEvent('pagehide', { persisted: true }))+ await vi.advanceTimersByTimeAsync(30_000)+ expect(Socket.instances).toHaveLength(1)+ window.dispatchEvent(new PageTransitionEvent('pageshow', { persisted: true }))+ await vi.advanceTimersByTimeAsync(1000)+ expect(Socket.instances).toHaveLength(2)+ expect(Socket.instances[1].url.searchParams.get('attach')).toBe('opaque-server-id')+ Socket.reply = socket => socket.close(1006)+ Socket.instances[1].close(1006)+ await vi.advanceTimersByTimeAsync(120_000)+ expect(state).toHaveBeenCalledWith('reconnecting')+ expect(state).toHaveBeenLastCalledWith('disconnected')+ expect(exit).toHaveBeenCalledWith({ code: null, signal: 'disconnected' })+ const attempts = Socket.instances.length+ expect(attempts).toBeLessThanOrEqual(7)+ await vi.advanceTimersByTimeAsync(120_000)+ expect(Socket.instances).toHaveLength(attempts)+ expect(Socket.instances.slice(1).every(socket => socket.url.searchParams.has('attach'))).toBe(true)+ })++ it('waits for close acknowledgement and preserves the handle on a denied close', async () => {+ const api = install()+ await api.start({ cwd: '/original', restoreKey: 'tab-one' })+ Socket.reply = socket => socket.close(4403)+ await expect(api.closeSaved!('tab-one')).rejects.toThrow(/close/i)+ expect(localStorage.length).toBe(1)++ Socket.reply = socket => { socket.metadata({ closed: true }); socket.close() }+ await expect(api.closeSaved!('tab-one')).resolves.toBe(true)+ expect(localStorage.length).toBe(0)+ })++ it('does not redial a late auth ticket after detach', async () => {+ const api = install()+ const session = await api.start({ cwd: '/original', restoreKey: 'tab-one' })+ let finishTicket!: (response: Response) => void+ vi.stubGlobal('fetch', vi.fn(() => new Promise<Response>(resolve => { finishTicket = resolve })))+ Socket.instances[0].close(1006)+ await vi.advanceTimersByTimeAsync(1000)+ await api.detach!(session.id)+ finishTicket(new Response(JSON.stringify({ ticket: 'late' })))+ await vi.advanceTimersByTimeAsync(30_000)+ expect(Socket.instances).toHaveLength(1)+ })++ it('does not share persisted terminals between installations behind different proxy prefixes', async () => {+ await install().start({ cwd: '/original', restoreKey: 'tab-one' })+ window.dispatchEvent(new Event('beforeunload'))+ Reflect.deleteProperty(window, 'hermesDesktop')+ Object.assign(window, { __HERMES_BASE_PATH__: '/two' })+ installBrowserDesktopBridge()+ await window.hermesDesktop!.terminal.start({ cwd: '/original', restoreKey: 'tab-one' })+ expect(Socket.instances.at(-1)!.url.searchParams.has('attach')).toBe(false)+ })+})diff --git a/apps/desktop/src/lib/browser-terminal.ts b/apps/desktop/src/lib/browser-terminal.tsnew file mode 100644index 00000000000..7042ba881d3--- /dev/null+++ b/apps/desktop/src/lib/browser-terminal.ts@@ -0,0 +1,544 @@+import { isStableOpen, reconnectBackoffDelayMs } from '@hermes/shared'++import type { HermesTerminalExit, HermesTerminalSession, HermesTerminalState } from '@/global'++import { readJson, writeJson } from './storage'++type TerminalApi = Window['hermesDesktop']['terminal']+type DataListener = Parameters<TerminalApi['onData']>[1]++interface SavedTerminal {+ terminalId: string+ profile: string | null+}++interface BrowserTerminalOptions {+ basePath: string+ currentProfile: () => string | null+ websocketUrl: (profile: string | null) => Promise<string>+ defaultCwd: (profile: string | null) => Promise<string>+}++interface TerminalState {+ id: string+ restoreKey?: string+ profile: string | null+ terminalId?: string+ cwd: string+ shell: string+ cols: number+ rows: number+ socket: WebSocket | null+ generation: number+ stopped: boolean+ status: HermesTerminalState+ retry: number+ retryTimer: number+ openedAt: number | null+ cancelDial?: () => void+ started?: Promise<HermesTerminalSession>+ pendingData: Array<{ data: string; replay: boolean }>+ dataListeners: Set<DataListener>+ exit: HermesTerminalExit | null+ exitListeners: Set<(exit: HermesTerminalExit) => void>+ stateListeners: Set<(state: HermesTerminalState) => void>+}++const META = '\u0000HERMES_TERMINAL_META:'+const MAX_RETRIES = 5+const RETRY_BACKOFF = { baseDelayMs: 500, capMs: 8000 }+const START_TIMEOUT = 10_000+const CLOSE_SIGNALS: Record<number, string> = { 4403: 'denied', 4409: 'superseded', 4410: 'expired', 1013: 'capacity' }++class TerminalConnectionError extends Error {+ constructor(message: string, readonly signal = 'disconnected') {+ super(message)+ }+}++/** Only an attachment that stayed up resets the retry ladder (shared stable-open rule). */+function settleOpen(state: TerminalState): void {+ if (isStableOpen(state.openedAt)) {state.retry = 0}+ state.openedAt = null+}++async function closeSavedShell(saved: SavedTerminal, websocketUrl: BrowserTerminalOptions['websocketUrl']): Promise<boolean> {+ const url = new URL(await websocketUrl(saved.profile))+ url.searchParams.set('attach', saved.terminalId)+ url.searchParams.set('action', 'close')+ const socket = new WebSocket(url)++ return new Promise((resolve, reject) => {+ let acknowledged = false++ const timer = window.setTimeout(() => {+ socket.onclose = null+ socket.onmessage = null+ socket.close(1000, 'close timeout')+ reject(new Error('Terminal close timed out; retry closing this tab'))+ }, START_TIMEOUT)++ socket.onmessage = event => {+ if (typeof event.data !== 'string' || !event.data.startsWith(META)) {return}++ try {+ const meta = JSON.parse(event.data.slice(META.length)) as { closed?: boolean; terminalId?: string }+ acknowledged = meta.closed === true && meta.terminalId === saved.terminalId+ } catch { /* A close is confirmed only by valid metadata and normal closure. */ }+ }++ socket.onerror = () => {+ window.clearTimeout(timer)+ reject(new Error('Terminal close failed to connect; retry closing this tab'))+ }++ socket.onclose = event => {+ window.clearTimeout(timer)++ if (event.code === 1000 && acknowledged) {resolve(true)} else {+ reject(new Error(event.reason || 'Terminal close was not confirmed; retry closing this tab'))+ }+ }+ })+}++interface DialContext {+ websocketUrl: BrowserTerminalOptions['websocketUrl']+ storageKey: (key: string) => string+ isPaused: () => boolean+ stopSocket: (state: TerminalState) => void+ emitData: (state: TerminalState, data: string, replay?: boolean) => void+ setStatus: (state: TerminalState, status: HermesTerminalState) => void+ forget: (state: TerminalState) => void+ finish: (state: TerminalState, signal: string | null) => void+ reconnect: (state: TerminalState) => void+}++async function dialTerminal(state: TerminalState, context: DialContext): Promise<HermesTerminalSession> {+ const { stopSocket, emitData, setStatus, forget, finish, reconnect } = context+ stopSocket(state)+ const generation = ++state.generation+ const url = new URL(await context.websocketUrl(state.profile))++ if (generation !== state.generation || context.isPaused() || state.stopped) {+ throw new TerminalConnectionError('Terminal attachment cancelled')+ }++ url.searchParams.set('cols', String(state.cols))+ url.searchParams.set('rows', String(state.rows))++ if (state.cwd) {url.searchParams.set('cwd', state.cwd)}++ if (state.terminalId) {url.searchParams.set('attach', state.terminalId)}+ const resuming = Boolean(state.terminalId)+ const socket = state.socket = new WebSocket(url)+ socket.binaryType = 'arraybuffer'+ const decoder = new TextDecoder()++ return new Promise((resolve, reject) => {+ let settled = false+ let handshakeComplete = false+ let replayNext = false+ const current = () => state.generation === generation && !context.isPaused() && !state.stopped++ const fail = (error: Error) => {+ if (settled) {return}+ settled = true+ window.clearTimeout(timer)+ state.cancelDial = undefined+ reject(error)+ }++ const timer = window.setTimeout(() => {+ fail(new TerminalConnectionError('Host terminal did not provide startup metadata'))+ socket.onclose = null+ socket.close(1000, 'startup timeout')+ }, START_TIMEOUT)++ state.cancelDial = () => fail(new TerminalConnectionError('Terminal attachment cancelled'))++ const output = (data: string) => {+ if (!current()) {return}+ emitData(state, data, replayNext)+ replayNext = false+ }++ socket.onmessage = event => {+ if (!current()) {return}++ if (typeof event.data === 'string' && event.data.startsWith(META)) {+ try {+ const meta = JSON.parse(event.data.slice(META.length)) as {+ shell?: string; cwd?: string; terminalId?: string; reconnected?: boolean; truncated?: boolean+ }++ if (typeof meta.shell !== 'string' || !meta.shell.trim()) {+ throw new Error('Host terminal returned an empty shell identity')+ }++ if (resuming && meta.terminalId !== state.terminalId) {+ throw new Error('Host terminal did not resume the requested shell')+ }++ state.shell = meta.shell++ if (typeof meta.cwd === 'string') {state.cwd = meta.cwd}++ if (typeof meta.terminalId === 'string' && meta.terminalId) {+ state.terminalId = meta.terminalId+ // The first binary frame is the snapshot, including an empty frame+ // when there is no history. Suppress replies only while parsing it.+ replayNext = true++ if (state.restoreKey) {+ writeJson(context.storageKey(state.restoreKey), { terminalId: state.terminalId, profile: state.profile })+ }++ if (resuming) {+ // Rebuild this xterm from the server tail, never append a second copy.+ state.pendingData = []+ emitData(state, '\u001bc' + (meta.truncated ? '[Earlier terminal output was trimmed from the retained history]\r\n' : ''), true)+ }+ }++ handshakeComplete = true++ // Resume query dimensions do not resize an existing server PTY.+ if (resuming) {socket.send(`\u001b[RESIZE:${state.cols};${state.rows}]`)}+ setStatus(state, 'open')+ state.openedAt = Date.now()++ if (!settled) {+ settled = true+ window.clearTimeout(timer)+ state.cancelDial = undefined+ resolve({ id: state.id, cwd: state.cwd, shell: state.shell, persistent: Boolean(state.terminalId) })+ }+ } catch (error) {+ fail(error instanceof Error ? error : new Error('Host terminal returned invalid startup metadata'))+ socket.close(1000, 'invalid metadata')+ }++ return+ }++ if (typeof event.data === 'string') {+ output(event.data)+ } else if (event.data instanceof Blob) {+ void event.data.arrayBuffer().then(buffer => {+ if (current()) {output(decoder.decode(buffer, { stream: true }))}+ })+ } else {+ output(decoder.decode(event.data as ArrayBuffer, { stream: true }))+ }+ }++ socket.onerror = () => {+ if (!settled) {fail(new TerminalConnectionError('Host terminal WebSocket failed to connect'))}+ }++ socket.onclose = event => {+ if (!current()) {return}+ settleOpen(state)+ const signal = CLOSE_SIGNALS[event.code] ?? 'disconnected'++ if (signal === 'expired') {forget(state)}++ if (!handshakeComplete) {+ fail(new TerminalConnectionError(event.reason || `Host terminal closed (${event.code})`, signal))++ return+ }++ emitData(state, decoder.decode())++ if (!state.terminalId) {+ finish(state, event.code === 4410 ? null : 'disconnected')+ } else if (signal !== 'disconnected') {+ finish(state, signal)+ } else {+ reconnect(state)+ }+ }+ })+}++/** A renderer attachment is disposable; only explicit tab close kills its shell. */+export function createBrowserTerminal(options: BrowserTerminalOptions): TerminalApi {+ const terminals = new Map<string, TerminalState>()+ let sequence = 0+ let paused = false+ const storageKey = (key: string) => `hermes.webapp.terminal.v1:${JSON.stringify([window.location.origin, options.basePath, key])}`++ const load = (key?: string): SavedTerminal | null => {+ const saved = key ? readJson<SavedTerminal>(storageKey(key)) : null++ return saved && typeof saved.terminalId === 'string' && saved.terminalId.length > 0 &&+ (saved.profile === null || typeof saved.profile === 'string') ? saved : null+ }++ const forget = (state: Pick<TerminalState, 'restoreKey'> & { terminalId?: string }) => {+ if (state.restoreKey && (!state.terminalId || load(state.restoreKey)?.terminalId === state.terminalId)) {+ writeJson(storageKey(state.restoreKey), null)+ }+ }++ const setStatus = (state: TerminalState, status: HermesTerminalState) => {+ if (state.status === status) {return}+ state.status = status+ state.stateListeners.forEach(listener => listener(status))+ }++ const emitData = (state: TerminalState, data: string, replay = false) => {+ if (!data) {return}++ if (!state.dataListeners.size) {+ state.pendingData.push({ data, replay })+ // A snapshot is at most 1 MiB; leave space for live output before subscribe.+ let size = state.pendingData.reduce((total, frame) => total + frame.data.length, 0)++ while (size > 2 * 1024 * 1024 && state.pendingData.length > 1) {+ size -= state.pendingData.shift()!.data.length+ }++ return+ }++ state.dataListeners.forEach(listener => replay ? listener(data, { replay }) : listener(data))+ }++ const stopSocket = (state: TerminalState) => {+ ++state.generation+ window.clearTimeout(state.retryTimer)+ settleOpen(state)+ state.cancelDial?.()+ state.cancelDial = undefined+ const socket = state.socket+ state.socket = null++ if (socket) {+ socket.onclose = null+ socket.onerror = null+ socket.onmessage = null+ socket.close(1000, 'detached')+ }+ }++ const finish = (state: TerminalState, signal: string | null) => {+ state.stopped = true+ window.clearTimeout(state.retryTimer)+ setStatus(state, 'disconnected')+ state.exit = { code: null, signal }+ state.exitListeners.forEach(listener => listener(state.exit!))+ }++ const reconnect = (state: TerminalState) => {+ if (paused || state.stopped) {return}++ if (!state.terminalId || state.retry >= MAX_RETRIES) {+ finish(state, 'disconnected')++ return+ }++ setStatus(state, 'reconnecting')+ state.retryTimer = window.setTimeout(() => {+ const attempt = dial(state)+ const generation = state.generation+ void attempt.catch(error => {+ if (paused || state.stopped || generation !== state.generation) {return}+ stopSocket(state)++ if (error instanceof TerminalConnectionError && error.signal !== 'disconnected') {+ finish(state, error.signal)+ } else {+ reconnect(state)+ }+ })+ }, reconnectBackoffDelayMs(state.retry++, RETRY_BACKOFF))+ }++ const dial = (state: TerminalState) => dialTerminal(state, {+ websocketUrl: options.websocketUrl, storageKey, isPaused: () => paused, stopSocket, emitData, setStatus, forget, finish, reconnect+ })++ const detach = async (id: string) => {+ const state = terminals.get(id)++ if (!state) {return false}+ state.stopped = true+ stopSocket(state)+ terminals.delete(id)++ return true+ }++ const dispose = async (id: string) => {+ const state = terminals.get(id)++ if (!state) {return false}+ // Closing a tab during startup must wait for its server-minted identity.+ await state.started?.catch(() => undefined)+ state.stopped = true+ stopSocket(state)++ try {+ if (state.terminalId) {await closeSavedShell({ terminalId: state.terminalId, profile: state.profile }, options.websocketUrl)}+ } catch (error) {+ finish(state, 'disconnected')+ throw error+ }++ forget(state)+ terminals.delete(id)++ return true+ }++ const pause = () => {+ paused = true+ terminals.forEach(state => {+ stopSocket(state)++ if (!state.stopped) {setStatus(state, 'reconnecting')}+ })+ }++ const resume = (event: PageTransitionEvent) => {+ if (!event.persisted || !paused || window.hermesDesktop?.terminal !== api) {return}+ paused = false+ terminals.forEach(state => {+ if (state.stopped) {return}++ if (state.terminalId) {reconnect(state)} else {finish(state, 'disconnected')}+ })+ }++ window.addEventListener('beforeunload', pause)+ window.addEventListener('pagehide', pause)+ window.addEventListener('pageshow', resume)++ const api: TerminalApi = {+ attach: async id => {+ const state = terminals.get(id)++ return Boolean(state && !state.stopped && (state.terminalId || state.socket?.readyState === WebSocket.OPEN))+ },+ // OSC output owns live cwd; returning the launch cwd here would clobber it.+ cwd: async () => null,+ detach,+ dispose,+ closeSaved: async restoreKey => {+ const state = [...terminals.values()].find(state => state.restoreKey === restoreKey)++ if (state) {return dispose(state.id)}+ const saved = load(restoreKey)++ if (saved) {await closeSavedShell(saved, options.websocketUrl)}+ forget({ restoreKey })++ return true+ },+ onData: (id, callback) => {+ const state = terminals.get(id)++ if (!state) {return () => undefined}+ state.dataListeners.add(callback)+ const pending = state.pendingData.splice(0)++ if (pending.length) {queueMicrotask(() => {+ if (state.dataListeners.has(callback)) {pending.forEach(frame => frame.replay ? callback(frame.data, { replay: true }) : callback(frame.data))}+ })}++ return () => { state.dataListeners.delete(callback) }+ },+ onExit: (id, callback) => {+ const state = terminals.get(id)++ if (!state) {return () => undefined}+ state.exitListeners.add(callback)++ if (state.exit) {queueMicrotask(() => { if (state.exitListeners.has(callback)) {callback(state.exit!)} })}++ return () => { state.exitListeners.delete(callback) }+ },+ onState: (id, callback) => {+ const state = terminals.get(id)++ if (!state) {return () => undefined}+ state.stateListeners.add(callback)+ callback(state.status)++ return () => { state.stateListeners.delete(callback) }+ },+ resize: async (id, size) => {+ const state = terminals.get(id)++ if (!state) {return false}+ state.cols = Math.max(1, Math.round(size.cols))+ state.rows = Math.max(1, Math.round(size.rows))++ if (state.status !== 'open' || state.socket?.readyState !== WebSocket.OPEN) {return false}+ state.socket.send(`\u001b[RESIZE:${state.cols};${state.rows}]`)++ return true+ },+ start: async startOptions => {+ const existing = startOptions?.restoreKey+ ? [...terminals.values()].find(state => state.restoreKey === startOptions.restoreKey) : undefined++ if (existing) {+ // StrictMode/remount can overlap startup before a capability is minted.+ // Serialize those starts so a single tab cannot spawn two shells.+ await existing.started?.catch(() => undefined)+ await detach(existing.id)+ }++ const saved = load(startOptions?.restoreKey)++ if (startOptions?.resumeOnly && !saved) {+ throw new TerminalConnectionError('Terminal expired; press Enter to create a new shell', 'expired')+ }++ const state: TerminalState = {+ id: `browser-${Date.now().toString(36)}-${++sequence}`,+ restoreKey: startOptions?.restoreKey,+ profile: saved ? saved.profile : options.currentProfile(),+ terminalId: saved?.terminalId,+ cwd: startOptions?.cwd || '', shell: 'host-shell',+ cols: Math.max(2, Math.round(startOptions?.cols || 80)),+ rows: Math.max(2, Math.round(startOptions?.rows || 24)),+ socket: null, generation: 0, stopped: false, status: 'reconnecting',+ retry: 0, retryTimer: 0, openedAt: null, pendingData: [],+ dataListeners: new Set(), exit: null, exitListeners: new Set(), stateListeners: new Set()+ }++ terminals.set(state.id, state)+ state.started = (async () => {+ if (!state.cwd && !saved) {+ state.cwd = await options.defaultCwd(state.profile).catch(() => '')+ }++ return dial(state)+ })()++ try {+ return await state.started+ } catch (error) {+ stopSocket(state)+ terminals.delete(state.id)+ throw error+ }+ },+ write: async (id, data) => {+ const state = terminals.get(id)++ if (!state || state.stopped || state.status !== 'open' || state.socket?.readyState !== WebSocket.OPEN) {return false}+ state.socket.send(data)++ return true+ }+ }++ return api+}diff --git a/apps/desktop/src/lib/browser-transport.ts b/apps/desktop/src/lib/browser-transport.tsnew file mode 100644index 00000000000..d14b5c7ea76--- /dev/null+++ b/apps/desktop/src/lib/browser-transport.ts@@ -0,0 +1,319 @@+import { buildHermesWebSocketUrl, normalizeBasePath } from '@hermes/shared'++import type { HermesApiRequest } from '@/global'+import { consumeWebappSession, WEBAPP_LAUNCH_REQUIRED } from '@/lib/browser-launch-session'+import { type BrowserHostGlobals, hasBrowserHostBootstrap } from '@/lib/platform'++export interface BrowserBootstrap {+ authRequired: boolean+ basePath: string+ /** Webapp on an unauthenticated bind: the operator's launch link is the only credential source. */+ privateSession: boolean+ token: string+}++const SESSION_HEADER = 'X-Hermes-Session-Token'+const DEFAULT_TIMEOUT_MS = 30_000+const REAUTH_EVENT = 'hermes:browser-reauth-required'++export class BrowserReauthRequiredError extends Error {+ readonly loginUrl: string+ readonly needsOauthLogin = true++ constructor(message: string, loginUrl: string) {+ super(message)+ this.name = 'BrowserReauthRequiredError'+ this.loginUrl = loginUrl+ }+}++export function browserBootstrap(): BrowserBootstrap | null {+ if (!hasBrowserHostBootstrap()) {return null}++ const win = window as Window & BrowserHostGlobals+ const authRequired = win.__HERMES_AUTH_REQUIRED__ === true+ const basePath = normalizeBasePath(win.__HERMES_BASE_PATH__)+ const privateSession = !authRequired && win.__HERMES_UI_SURFACE__ === 'webapp'+ const token = privateSession ? consumeWebappSession(basePath) : ''++ return {+ authRequired,+ basePath,+ privateSession,+ token+ }+}++export function endpointUrl(path: string, basePath: string, profile?: null | string): URL {+ const suffix = path.startsWith('/') ? path : `/${path}`+ const normalizedBase = normalizeBasePath(basePath)+ const url = new URL(`${normalizedBase}${suffix}`, window.location.origin)++ if (url.origin !== window.location.origin) {+ throw new Error('Hermes API paths must remain on the Webapp origin')+ }++ if (+ normalizedBase &&+ url.pathname !== normalizedBase &&+ !url.pathname.startsWith(`${normalizedBase}/`)+ ) {+ throw new Error('Hermes API paths must remain inside the configured base path')+ }++ if (profile && !url.searchParams.has('profile')) {+ url.searchParams.set('profile', profile)+ }++ return url+}++export function websocketUrl(+ basePath: string,+ path: string,+ credential: { ticket?: string; token?: string },+ profile?: null | string+): string {+ const authParam = credential.ticket+ ? (['ticket', credential.ticket] as const)+ : credential.token+ ? (['token', credential.token] as const)+ : undefined++ return buildHermesWebSocketUrl({+ authParam,+ basePath,+ params: profile ? { profile } : undefined,+ path+ })+}++function reauthError(+ bootstrap: BrowserBootstrap,+ response: Response,+ text: string+): BrowserReauthRequiredError | null {+ if (!bootstrap.authRequired || response.status !== 401) {return null}++ let payload: { detail?: unknown; error?: unknown; login_url?: unknown } = {}++ try {+ payload = JSON.parse(text) as typeof payload+ } catch {+ return null+ }++ if (+ !['session_expired', 'unauthenticated'].includes(String(payload.error || '')) ||+ typeof payload.login_url !== 'string'+ ) {+ return null+ }++ let target: URL++ try {+ target = new URL(payload.login_url, window.location.origin)+ } catch {+ return null+ }++ if (target.origin !== window.location.origin) {return null}++ return new BrowserReauthRequiredError(+ `${String(payload.error)}: ${String(payload.detail || 'Unauthorized')}`,+ target.href+ )+}++export function navigateToBrowserLogin(error: BrowserReauthRequiredError): void {+ const event = new CustomEvent(REAUTH_EVENT, {+ cancelable: true,+ detail: { loginUrl: error.loginUrl }+ })++ if (window.dispatchEvent(event)) {window.location.assign(error.loginUrl)}+}++interface BrowserFetchRequest {+ body?: BodyInit+ headers?: HeadersInit+ method?: string+ path: string+ profile?: null | string+ timeoutMs?: number+}++export async function browserFetch(+ bootstrap: BrowserBootstrap,+ request: BrowserFetchRequest+): Promise<{ response: Response; text: string }> {+ if (!bootstrap.authRequired && !bootstrap.token) {throw new Error(WEBAPP_LAUNCH_REQUIRED)}++ const controller = request.timeoutMs === undefined ? null : new AbortController()+ const timeout = controller ? window.setTimeout(() => controller.abort(), request.timeoutMs) : null+ const headers = new Headers(request.headers)++ if (bootstrap.token) {headers.set(SESSION_HEADER, bootstrap.token)}++ try {+ const response = await fetch(endpointUrl(request.path, bootstrap.basePath, request.profile), {+ body: request.body,+ credentials: 'same-origin',+ headers,+ method: request.method || 'GET',+ signal: controller?.signal+ })++ const text = await response.text()++ if (!response.ok) {+ if (!bootstrap.authRequired && response.status === 401) {throw new Error(WEBAPP_LAUNCH_REQUIRED)}++ const authError = reauthError(bootstrap, response, text)++ if (authError) {+ navigateToBrowserLogin(authError)+ throw authError+ }+ }++ return { response, text }+ } finally {+ if (timeout !== null) {window.clearTimeout(timeout)}+ }+}++export async function browserApi<T>(bootstrap: BrowserBootstrap, request: HermesApiRequest): Promise<T> {+ const headers = new Headers()+ let body: BodyInit | undefined++ if (request.upload) {+ const form = new FormData()++ const blob = new Blob([request.upload.bytes], {+ type: request.upload.contentType || 'application/octet-stream'+ })++ form.append('file', blob, request.upload.filename || 'file')+ body = form+ } else if (request.body !== undefined) {+ headers.set('Content-Type', 'application/json')+ body = JSON.stringify(request.body)+ }++ const { response, text } = await browserFetch(bootstrap, {+ body,+ headers,+ method: request.method,+ path: request.path,+ profile: request.profile,+ timeoutMs: request.timeoutMs ?? DEFAULT_TIMEOUT_MS+ })++ if (!response.ok) {+ throw new Error(`${response.status}: ${text || response.statusText}`)+ }++ if (!text) {return null as T}++ if (/^\s*<(?:!doctype|html)/i.test(text)) {+ throw new Error(`Hermes API returned HTML for ${request.path}`)+ }++ return JSON.parse(text) as T+}++export interface FileEndpointQuery {+ path: string+ profile?: null | string+ session_id?: string+}++/**+ * URL for a download link or media element, which cannot send the session+ * header. Gated hosts authenticate it with the same-origin cookie. A token+ * session mints a ticket bound to this exact route and query: the session+ * token grants host shells, so it must never reach download history or a+ * copyable media address.+ */+export async function fileEndpointUrl(+ bootstrap: BrowserBootstrap,+ route: 'download' | 'stream',+ query: FileEndpointQuery+): Promise<URL> {+ const params = Object.fromEntries(Object.entries(query).filter(([, value]) => value)) as Record<string, string>+ const url = endpointUrl(`/api/files/${route}`, bootstrap.basePath)++ Object.entries(params).forEach(([key, value]) => url.searchParams.set(key, value))++ if (bootstrap.token) {+ const result = await browserApi<null | { ticket?: string }>(bootstrap, {+ body: { ...params, route },+ method: 'POST',+ path: '/api/files/ticket'+ })++ const ticket = String(result?.ticket || '')++ if (!ticket) {throw new Error('Hermes did not return a file ticket')}+ url.searchParams.set('ticket', ticket)+ }++ return url+}++/**+ * The live socket to the gateway serving this page. Every dial mints its own one-use ticket on the+ * same origin; a failed mint is the reason to show. `native_dial` makes the client speak the+ * gateway's canonical contract and move the ticket into the socket's subprotocol.+ */+export async function gatewayWebsocketUrl(bootstrap: BrowserBootstrap, profile?: null | string): Promise<string> {+ const result = await browserApi<null | { ticket?: string }>(bootstrap, {+ method: 'POST',+ path: '/api/webapp/gateway-ticket',+ profile+ })++ const ticket = String(result?.ticket || '').trim()++ if (!ticket) {+ throw new Error('Hermes did not return a gateway ticket')+ }++ const url = new URL(gatewaySocketUrl(bootstrap, profile))+ url.searchParams.set('ticket', ticket)++ return url.toString()+}++/** The credential-free canonical socket URL a browser connection descriptor reports. */+export function gatewaySocketUrl(bootstrap: BrowserBootstrap, profile?: null | string): string {+ const url = new URL(websocketUrl(bootstrap.basePath, '/api/ws', {}, profile))+ url.searchParams.set('native_dial', 'browser')++ return url.toString()+}++export async function authenticatedWebsocketUrl(+ bootstrap: BrowserBootstrap,+ path: '/api/host-terminal',+ profile?: null | string+): Promise<string> {+ if (!bootstrap.authRequired) {+ if (!bootstrap.token) {throw new Error(WEBAPP_LAUNCH_REQUIRED)}++ return websocketUrl(bootstrap.basePath, path, { token: bootstrap.token }, profile)+ }++ const result = await browserApi<{ ticket?: string }>(bootstrap, {+ method: 'POST',+ path: '/api/auth/ws-ticket'+ })++ const ticket = String(result.ticket || '').trim()++ if (!ticket) {throw new Error('Hermes did not return a WebSocket ticket')}++ return websocketUrl(bootstrap.basePath, path, { ticket }, profile)+}diff --git a/apps/desktop/src/lib/browser-uploads.ts b/apps/desktop/src/lib/browser-uploads.tsnew file mode 100644index 00000000000..57216f85455--- /dev/null+++ b/apps/desktop/src/lib/browser-uploads.ts@@ -0,0 +1,243 @@+import type { HermesApiRequest, HermesSelectPathsOptions, HermesStagedUpload } from '@/global'+import { blobToDataUrl, bytesToBase64 } from '@/lib/base64'+import { type BrowserBootstrap, browserFetch } from '@/lib/browser-transport'++const STAGED_UPLOAD_CACHE_LIMIT = 256++const IMAGE_MIME_BY_EXTENSION: Record<string, string> = {+ '.bmp': 'image/bmp',+ '.gif': 'image/gif',+ '.jpeg': 'image/jpeg',+ '.jpg': 'image/jpeg',+ '.png': 'image/png',+ '.tif': 'image/tiff',+ '.tiff': 'image/tiff',+ '.webp': 'image/webp'+}++export const IMAGE_EXTENSION_BY_MIME: Record<string, string> = Object.fromEntries(+ Object.entries(IMAGE_MIME_BY_EXTENSION).map(([extension, mime]) => [mime, extension])+)++function normalizedExtension(value: string): string {+ const clean = String(value || '').trim().toLowerCase()++ if (!clean) {return ''}++ return clean.startsWith('.') ? clean : `.${clean}`+}++// Chips retain their own descriptors. Bound the string-path compatibility+// caches without consuming lookups shared by multiple attachment occurrences.+function rememberBounded<K, V>(cache: Map<K, V>, key: K, value: V): void {+ cache.set(key, value)++ if (cache.size > STAGED_UPLOAD_CACHE_LIMIT) {+ const oldest = cache.keys().next().value++ if (oldest !== undefined) {+ cache.delete(oldest)+ }+ }+}++function sandboxedHtmlBlob(bytes: Uint8Array): Blob {+ const source = `data:text/html;charset=utf-8;base64,${bytesToBase64(bytes)}`++ const wrapper = [+ '<!doctype html>',+ '<html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">',+ '<style>html,body,iframe{box-sizing:border-box;width:100%;height:100%;margin:0;border:0}</style>',+ '</head><body>',+ `<iframe sandbox="allow-scripts" referrerpolicy="no-referrer" src="${source}"></iframe>`,+ '</body></html>'+ ].join('')++ return new Blob([wrapper], { type: 'text/html;charset=utf-8' })+}++interface StageResponse {+ detail?: unknown+ path?: string+ staged_upload?: HermesStagedUpload+}++/** A proxy's own error page (nginx's 413, a 502/504) is HTML, not the server's JSON. */+function stageResponse(text: string): StageResponse {+ try {+ const value: unknown = JSON.parse(text)++ return value && typeof value === 'object' ? (value as StageResponse) : {}+ } catch {+ return {}+ }+}++function uploadFailure(status: number, detail: unknown): string {+ if (typeof detail === 'string' && detail) {return detail}++ return status === 413+ ? 'File upload failed (413): the file is larger than the server or a proxy in front of it accepts'+ : `File upload failed (${status})`+}++type OnStaged = (path: string, name: string, staged?: HermesStagedUpload) => void++async function stageBrowserFile(+ bootstrap: BrowserBootstrap,+ file: File,+ profile: null | string,+ onStaged: OnStaged+): Promise<string> {+ const form = new FormData()+ form.append('file', file, file.name || 'attachment')++ const { response, text } = await browserFetch(bootstrap, {+ body: form,+ method: 'POST',+ path: '/api/chat/file-upload',+ profile+ })++ const payload = stageResponse(text)++ if (!response.ok || !payload.path) {+ throw new Error(uploadFailure(response.status, payload.detail))+ }++ onStaged(payload.path, file.name, payload.staged_upload)++ return payload.path+}++function selectBrowserFiles(+ bootstrap: BrowserBootstrap,+ options: HermesSelectPathsOptions | undefined,+ fallbackProfile: null | string,+ onStaged: OnStaged+): Promise<string[]> {+ if (options?.directories) {return Promise.resolve([])}++ return new Promise<string[]>((resolve, reject) => {+ const input = document.createElement('input')+ input.type = 'file'+ input.multiple = Boolean(options?.multiple)+ input.style.display = 'none'++ const extensions = (options?.filters || []).flatMap(filter => filter.extensions || [])++ if (extensions.length) {+ input.accept = extensions.map(extension => `.${extension.replace(/^\./, '')}`).join(',')+ }++ const finish = () => input.remove()+ input.addEventListener(+ 'cancel',+ () => {+ finish()+ resolve([])+ },+ { once: true }+ )+ input.addEventListener(+ 'change',+ () => {+ const files = Array.from(input.files || [])+ finish()++ const profile = options?.profile?.trim() || fallbackProfile || null++ void Promise.all(files.map(file => stageBrowserFile(bootstrap, file, profile, onStaged))).then(resolve, reject)+ },+ { once: true }+ )+ document.body.append(input)+ input.click()+ })+}++interface BrowserUploadsOptions {+ api: <T>(request: HermesApiRequest) => Promise<T>+ bootstrap: BrowserBootstrap+ currentProfile: () => string | null+ /** Blob URLs handed to the page; the installer revokes them on unload. */+ objectUrls: Set<string>+ /** Only sandbox-wrapped HTML is eligible for the preview opener. */+ previewUrls: Set<string>+}++/** Browser bytes become server-side files the agent can read: images, drops, pastes, picks. */+export function createBrowserUploadsBridge({+ api,+ bootstrap,+ currentProfile,+ objectUrls,+ previewUrls+}: BrowserUploadsOptions): Pick<+ Window['hermesDesktop'],+ 'getStagedFileDisplayName' | 'getStagedFileForAttach' | 'saveImageBuffer' | 'savePastedText' | 'selectPaths' | 'stageFileForAttach'+> {+ const displayNames = new Map<string, string>()+ const stagedUploads = new Map<string, HermesStagedUpload>()++ const rememberStaged: OnStaged = (path, name, staged) => {+ // Keep the existing string-path bridge for pickers and drops. Composer chips+ // carry this small source descriptor so draft cloning and retries retain it.+ if (staged?.path === path) {+ rememberBounded(stagedUploads, path, staged)+ }++ rememberBounded(displayNames, path, name)+ }++ const saveBuffer = async (data: ArrayBuffer | Uint8Array, ext: string) => {+ const source = data instanceof Uint8Array ? data : new Uint8Array(data)+ const bytes = new Uint8Array(source.byteLength)+ bytes.set(source)++ const extension = normalizedExtension(ext)+ const imageMime = IMAGE_MIME_BY_EXTENSION[extension]++ if (imageMime) {+ // Route by the profile active at the paste, not after the encode.+ const profile = currentProfile()+ const dataUrl = await blobToDataUrl(new Blob([bytes], { type: imageMime }))++ const uploaded = await api<{ path?: string }>({+ body: {+ data_url: dataUrl,+ filename: `desktop-upload${extension}`+ },+ method: 'POST',+ path: '/api/chat/image-upload',+ profile+ })++ return uploaded.path || ''+ }++ const isHtml = extension === '.htm' || extension === '.html'++ const blob = isHtml+ ? sandboxedHtmlBlob(bytes)+ : new Blob([bytes.buffer], { type: 'application/octet-stream' })++ const url = URL.createObjectURL(blob)+ objectUrls.add(url)++ if (isHtml) { previewUrls.add(url) }++ return url+ }++ return {+ getStagedFileDisplayName: (path: string) => displayNames.get(path),+ getStagedFileForAttach: (path: string) => stagedUploads.get(path),+ saveImageBuffer: saveBuffer,+ savePastedText: (text: string) => stageBrowserFile(+ bootstrap, new File([text], 'pasted.txt', { type: 'text/plain' }), currentProfile(), rememberStaged+ ),+ selectPaths: options => selectBrowserFiles(bootstrap, options, currentProfile(), rememberStaged),+ stageFileForAttach: (file: File) => stageBrowserFile(bootstrap, file, currentProfile(), rememberStaged)+ }+}diff --git a/apps/desktop/src/lib/browser-viewport.test.ts b/apps/desktop/src/lib/browser-viewport.test.tsnew file mode 100644index 00000000000..48e13675ece--- /dev/null+++ b/apps/desktop/src/lib/browser-viewport.test.ts@@ -0,0 +1,143 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++import { installBrowserViewport } from './browser-viewport'++let dispose: (() => void) | undefined+let root: HTMLDivElement+let viewport: EventTarget & { height: number; offsetTop: number; scale: number }+let frames: Map<number, FrameRequestCallback>+let nextFrame: number++const flush = () => {+ const pending = [...frames.values()]+ frames.clear()+ pending.forEach(callback => callback(0))+}++const resize = (height: number, offsetTop = 0, scale = 1) => {+ Object.assign(viewport, { height, offsetTop, scale })+ viewport.dispatchEvent(new Event('resize'))+ viewport.dispatchEvent(new Event('scroll'))+ flush()+}++beforeEach(() => {+ root = document.createElement('div')+ root.id = 'root'+ document.body.append(root)+ document.documentElement.dataset.hermesDesktopHost = 'browser'+ viewport = Object.assign(new EventTarget(), { height: 800, offsetTop: 0, scale: 1 })+ frames = new Map()+ nextFrame = 0+ vi.stubGlobal('innerHeight', 800)+ vi.stubGlobal('visualViewport', viewport)+ vi.stubGlobal('requestAnimationFrame', (callback: FrameRequestCallback) => {+ const id = ++nextFrame+ frames.set(id, callback)++ return id+ })+ vi.stubGlobal('cancelAnimationFrame', (id: number) => frames.delete(id))+})++afterEach(() => {+ dispose?.()+ dispose = undefined+ root.remove()+ document.documentElement.removeAttribute('data-hermes-desktop-host')+ document.documentElement.style.removeProperty('zoom')+ vi.unstubAllGlobals()+})++describe('browser visible viewport', () => {+ it('fits a keyboard and its pan at UI scale, without changing focus, pinch layout, or closed-keyboard layout', () => {+ const editor = document.createElement('textarea')+ editor.value = 'first line\nsecond line'+ root.append(editor)+ editor.focus()+ dispose = installBrowserViewport()+ expect(root.hasAttribute('data-browser-viewport')).toBe(false)++ resize(460, 25)+ expect(root.style.getPropertyValue('--browser-viewport-height')).toBe('460px')+ expect(root.style.getPropertyValue('--browser-viewport-top')).toBe('25px')+ expect(document.activeElement).toBe(editor)+ expect(editor.value).toBe('first line\nsecond line')++ resize(230, 90, 2)+ expect(root.style.getPropertyValue('--browser-viewport-height')).toBe('460px')+ expect(root.style.getPropertyValue('--browser-viewport-top')).toBe('25px')+ // Closing/reopening the keyboard while still pinched changes available+ // space, not the user's zoom. It must not leave the old keyboard inset.+ resize(400, 90, 2)+ expect(root.hasAttribute('data-browser-viewport')).toBe(false)+ resize(230, 90, 2)+ expect(root.style.getPropertyValue('--browser-viewport-height')).toBe('460px')+ expect(root.style.getPropertyValue('--browser-viewport-top')).toBe('0px')++ document.documentElement.style.zoom = '1.25'+ resize(460, 25)+ expect(root.style.getPropertyValue('--browser-viewport-height')).toBe('368px')+ expect(root.style.getPropertyValue('--browser-viewport-top')).toBe('20px')+ editor.blur()+ resize(500, 0)+ expect(document.activeElement).not.toBe(editor)+ expect(root.hasAttribute('data-browser-viewport')).toBe(true)++ // Rotation/layout-resizing browsers already made room for the keyboard.+ vi.stubGlobal('innerHeight', 500)+ window.dispatchEvent(new Event('resize'))+ flush()+ expect(root.hasAttribute('data-browser-viewport')).toBe(false)+ expect(root.style.getPropertyValue('--browser-viewport-height')).toBe('')+ vi.stubGlobal('innerHeight', 800)+ resize(800)+ expect(root.hasAttribute('data-browser-viewport')).toBe(false)+ expect(editor.value).toBe('first line\nsecond line')+ })++ it('leaves a focus-zoomed iOS keyboard to Safari, whose innerHeight is the visible area', () => {+ vi.stubGlobal('innerHeight', 714)+ viewport.height = 714+ dispose = installBrowserViewport()++ // Measured in iOS 26.5 Safari: focusing a 14.3px field zooms 402/359 and+ // Safari scrolls 353px to it; innerHeight follows the visible height.+ vi.stubGlobal('innerHeight', 361)+ resize(361, 353, 402 / 359)+ expect(root.hasAttribute('data-browser-viewport')).toBe(false)++ // Keyboard dismissed while the zoom remains.+ vi.stubGlobal('innerHeight', 638)+ resize(638, 76, 402 / 359)+ expect(root.hasAttribute('data-browser-viewport')).toBe(false)+ })++ it('leaves native/missing-API hosts alone and releases coalesced listeners and layout on teardown', () => {+ document.documentElement.removeAttribute('data-hermes-desktop-host')+ installBrowserViewport()()+ resize(400)+ expect(root.hasAttribute('data-browser-viewport')).toBe(false)+ expect(frames.size).toBe(0)++ document.documentElement.dataset.hermesDesktopHost = 'browser'+ vi.stubGlobal('visualViewport', null)+ installBrowserViewport()()+ expect(root.hasAttribute('data-browser-viewport')).toBe(false)+ vi.stubGlobal('visualViewport', viewport)+ dispose = installBrowserViewport()+ expect(root.hasAttribute('data-browser-viewport')).toBe(true)+ viewport.dispatchEvent(new Event('resize'))+ viewport.dispatchEvent(new Event('scroll'))+ window.dispatchEvent(new Event('resize'))+ expect(frames.size).toBe(1)+ dispose()+ expect(frames.size).toBe(0)+ resize(300)+ window.dispatchEvent(new Event('resize'))+ flush()+ expect(root.hasAttribute('data-browser-viewport')).toBe(false)+ expect(root.style.getPropertyValue('--browser-viewport-top')).toBe('')+ expect(frames.size).toBe(0)+ })+})diff --git a/apps/desktop/src/lib/browser-viewport.ts b/apps/desktop/src/lib/browser-viewport.tsnew file mode 100644index 00000000000..1697e3d3571--- /dev/null+++ b/apps/desktop/src/lib/browser-viewport.ts@@ -0,0 +1,84 @@+/** Fit the browser app to the visible area when a keyboard leaves layout height+ * unchanged. `interactive-widget=resizes-content` handles supporting browsers;+ * VisualViewport covers the others. Pan/zoom stays with the browser: a pinch+ * must not turn its smaller visible area into a smaller application layout.+ */+export function installBrowserViewport(): () => void {+ const viewport = window.visualViewport+ const root = document.getElementById('root')++ if (!viewport || !root || document.documentElement.dataset.hermesDesktopHost !== 'browser') {+ return () => {}+ }++ let frame = 0+ let unzoomedTop = 0++ const reset = () => {+ root.removeAttribute('data-browser-viewport')+ root.style.removeProperty('--browser-viewport-height')+ root.style.removeProperty('--browser-viewport-top')+ }++ const update = () => {+ frame = 0++ // Remove pinch magnification from the height, so opening/closing the+ // keyboard still updates available space while zoomed. No focus(),+ // scrollIntoView(), or browser zoom changes here.+ const height = viewport.height * viewport.scale++ if (!Number.isFinite(height) || height <= 0) {+ return+ }++ // iOS Safari reports the visible area as innerHeight, zoomed or not, and+ // scrolls the focused field into view itself. Fitting the shell under that+ // scroll would shrink the app out of the visible area.+ if (Math.abs(viewport.height - window.innerHeight) < 1) {+ unzoomedTop = 0+ reset()++ return+ }++ // Offset during a pinch belongs to the user's pan, not the app shell.+ if (Math.abs(viewport.scale - 1) < 0.01) {+ unzoomedTop = Math.max(0, viewport.offsetTop)+ }++ const top = Math.min(unzoomedTop, Math.max(0, window.innerHeight - height))++ if (Math.abs(height - window.innerHeight) < 1 && top < 1) {+ unzoomedTop = 0+ reset()++ return+ }++ // Hermes' UI scale is CSS zoom on <html>, separate from pinch zoom.+ const zoom = Number.parseFloat(getComputedStyle(document.documentElement).zoom) || 1+ root.style.setProperty('--browser-viewport-height', `${height / zoom}px`)+ root.style.setProperty('--browser-viewport-top', `${top / zoom}px`)+ root.setAttribute('data-browser-viewport', '')+ }++ const schedule = () => {+ if (!frame) {+ frame = requestAnimationFrame(update)+ }+ }++ viewport.addEventListener('resize', schedule)+ viewport.addEventListener('scroll', schedule)+ window.addEventListener('resize', schedule)+ update()++ return () => {+ cancelAnimationFrame(frame)+ viewport.removeEventListener('resize', schedule)+ viewport.removeEventListener('scroll', schedule)+ window.removeEventListener('resize', schedule)+ reset()+ }+}diff --git a/apps/desktop/src/lib/browser-window.ts b/apps/desktop/src/lib/browser-window.tsnew file mode 100644index 00000000000..7a72df971be--- /dev/null+++ b/apps/desktop/src/lib/browser-window.ts@@ -0,0 +1,96 @@+import type { HermesApiRequest } from '@/global'++interface BrowserWindowOptions {+ api: <T>(request: HermesApiRequest) => Promise<T>+ basePath: string+ privateSession: boolean+}++/** Open synchronously in the user gesture; never rely on an opener/storage copy. */+export function createBrowserWindowOpener({ api, basePath, privateSession }: BrowserWindowOptions) {+ return (target: URL): Promise<{ ok: true }> => {+ if (!privateSession) {+ window.open(target.href, '_blank', 'noopener,noreferrer')++ return Promise.resolve({ ok: true })+ }++ const id = crypto.randomUUID()+ const channel = new BroadcastChannel(`hermes.webapp.window:${id}`)+ const launch = new URL(`${basePath}/webapp/window`, window.location.origin)+ launch.hash = new URLSearchParams({ channel: id, query: target.search, route: target.hash.slice(1) }).toString()++ return new Promise((resolve, reject) => {+ let minting = false+ let settled = false++ const finish = (error?: Error) => {+ if (settled) {return}+ settled = true+ window.clearTimeout(timeout)+ channel.close()++ if (error) {reject(error)} else {resolve({ ok: true })}+ }++ const timeout = window.setTimeout(() => finish(new Error('Webapp window did not open. Allow popups for this site and try again.')), 30_000)++ channel.onmessage = event => {+ if (settled) {return}++ if (event.data?.type === 'ready' && !minting) {+ minting = true+ void api<{ ticket: string }>({ method: 'POST', path: '/api/webapp/window-ticket' }).then(({ ticket }) => {+ if (settled) {return}+ channel.postMessage({ ticket })+ }).catch(error => {+ if (settled) {return}+ channel.postMessage({ error: 'Could not authorize this window. Try opening it again from the original tab.' })+ finish(error instanceof Error ? error : new Error(String(error)))+ })+ } else if (event.data?.type === 'done') {+ finish()+ } else if (event.data?.type === 'error') {+ finish(new Error('Could not authorize the Webapp window. Try opening it again.'))+ }+ }++ try {+ window.open(launch.href, '_blank', 'noopener,noreferrer')+ } catch (error) {+ finish(error instanceof Error ? error : new Error(String(error)))+ }+ })+ }+}++/** The secondary-window URL showing one session, or null for an empty session id. */+export function sessionWindowTarget(+ currentHref: string,+ sessionId: string,+ opts?: { profile?: null | string; watch?: boolean }+): URL | null {+ const id = sessionId.trim()++ if (!id) {return null}+ const target = new URL(currentHref)+ target.searchParams.set('win', 'secondary')++ // Written out even for Default: without `?profile=` the window boots on+ // this origin's saved default, which may be another profile.+ const profile = opts?.profile?.trim()++ if (profile) {+ target.searchParams.set('profile', profile)+ }++ if (opts?.watch) {+ target.searchParams.set('watch', '1')+ } else {+ target.searchParams.delete('watch')+ }++ target.hash = `/${encodeURIComponent(id)}`++ return target+}diff --git a/apps/desktop/src/lib/browser-zoom.ts b/apps/desktop/src/lib/browser-zoom.tsnew file mode 100644index 00000000000..baa5e6f6259--- /dev/null+++ b/apps/desktop/src/lib/browser-zoom.ts@@ -0,0 +1,45 @@+import { readKey, writeKey } from './storage'++type ZoomState = { level: number; percent: number }++/** App scale is independent of browser zoom and monitor pixel density. */+export function createBrowserZoom(basePath: string): NonNullable<Window['hermesDesktop']['zoom']> {+ const storageKey = `hermes:browser:ui-scale:${basePath || '/'}`+ const listeners = new Set<(state: ZoomState) => void>()+ let percent = 100++ const normalize = (value: number) =>+ Number.isFinite(value) && value > 0 ? Math.round(Math.min(200, Math.max(50, value))) : 100++ const state = (): ZoomState => ({ level: Math.log(percent / 100) / Math.log(1.2), percent })++ const apply = (value: number) => {+ percent = normalize(value)+ document.documentElement.style.zoom = String(percent / 100)+ }++ // Private browsing can deny storage; the current tab can still scale.+ apply(Number(readKey(storageKey)) || 100)++ const setPercent = (value: number) => {+ apply(value)+ // Keep the applied value even when persistence is unavailable.+ writeKey(storageKey, String(percent))+ listeners.forEach(callback => callback(state()))+ // Layout consumers such as terminal fit need to remeasure at the new scale.+ window.dispatchEvent(new Event('resize'))+ }++ return {+ get: async () => state(),+ factor: () => percent / 100,+ onChanged: callback => {+ listeners.add(callback)++ return () => {+ listeners.delete(callback)+ }+ },+ setPercent+ }+}diff --git a/apps/desktop/src/lib/clipboard.test.ts b/apps/desktop/src/lib/clipboard.test.tsnew file mode 100644index 00000000000..e2caae6e7d6--- /dev/null+++ b/apps/desktop/src/lib/clipboard.test.ts@@ -0,0 +1,80 @@+import { afterEach, describe, expect, it, vi } from 'vitest'++import { createBrowserClipboardBridge } from './browser-clipboard'+import { installClipboardShim, writeClipboardText } from './clipboard'++const desktopWindow = window as unknown as { hermesDesktop?: Window['hermesDesktop'] }++function installClipboard(writeText: (text: string) => Promise<void>) {+ Object.defineProperty(navigator, 'clipboard', {+ configurable: true,+ value: { writeText }+ })+}++afterEach(() => {+ Reflect.deleteProperty(desktopWindow, 'hermesDesktop')+ Reflect.deleteProperty(navigator, 'clipboard')+ vi.restoreAllMocks()+ delete document.documentElement.dataset.hermesDesktopHost+})++describe('installClipboardShim', () => {+ it('keeps a successful native write on the trusted path', async () => {+ const nativeWrite = vi.fn().mockResolvedValue(undefined)+ const ipcWrite = vi.fn().mockResolvedValue(true)+ installClipboard(nativeWrite)+ desktopWindow.hermesDesktop = { writeClipboard: ipcWrite } as unknown as Window['hermesDesktop']++ installClipboardShim()+ await navigator.clipboard.writeText('payload')++ expect(nativeWrite).toHaveBeenCalledWith('payload')+ expect(ipcWrite).not.toHaveBeenCalled()+ })++ it('uses Electron IPC only after the native write fails', async () => {+ const nativeWrite = vi.fn().mockRejectedValue(new Error('lost focus'))+ const ipcWrite = vi.fn().mockResolvedValue(true)+ installClipboard(nativeWrite)+ desktopWindow.hermesDesktop = { writeClipboard: ipcWrite } as unknown as Window['hermesDesktop']++ installClipboardShim()+ await navigator.clipboard.writeText('payload')++ expect(nativeWrite).toHaveBeenCalledWith('payload')+ expect(ipcWrite).toHaveBeenCalledWith('payload')+ })+})++describe('writeClipboardText', () => {+ it('attempts native and IPC once when an installed Electron shim fails', async () => {+ const nativeWrite = vi.fn().mockRejectedValue(new Error('lost focus'))+ const bridgeWrite = vi.fn().mockResolvedValue(false)+ installClipboard(nativeWrite)+ desktopWindow.hermesDesktop = { writeClipboard: bridgeWrite } as unknown as Window['hermesDesktop']+ installClipboardShim()+ await expect(writeClipboardText('payload')).rejects.toThrow()+ expect(nativeWrite).toHaveBeenCalledTimes(1)+ expect(bridgeWrite).toHaveBeenCalledTimes(1)+ })++ it('does not retry the same native API through the installed browser bridge', async () => {+ const nativeWrite = vi.fn().mockRejectedValue(new Error('permission denied'))+ installClipboard(nativeWrite)+ document.documentElement.dataset.hermesDesktopHost = 'browser'+ desktopWindow.hermesDesktop = createBrowserClipboardBridge({+ saveBuffer: async () => ''+ }) as Window['hermesDesktop']+ installClipboardShim()+ await expect(writeClipboardText('payload')).rejects.toThrow('permission denied')+ expect(nativeWrite).toHaveBeenCalledTimes(1)+ })++ it('reports an unavailable bridge as a failed copy', async () => {+ const bridgeWrite = vi.fn().mockResolvedValue(false)+ desktopWindow.hermesDesktop = { writeClipboard: bridgeWrite } as unknown as Window['hermesDesktop']++ await expect(writeClipboardText('payload')).rejects.toThrow('Clipboard write is unavailable')+ })+})diff --git a/apps/desktop/src/lib/clipboard.ts b/apps/desktop/src/lib/clipboard.tsindex ad5117ebc0b..f95cac59a77 100644--- a/apps/desktop/src/lib/clipboard.ts+++ b/apps/desktop/src/lib/clipboard.ts@@ -1,27 +1,53 @@-// Routes `navigator.clipboard.writeText` through Electron IPC, since the-// renderer's clipboard API throws "Write permission denied" whenever the-// document loses focus (e.g. clicking a portaled Radix dropdown). The IPC-// path runs in the main process and is unconditional.+import { isBrowserHostedDesktop } from '@/lib/platform'-export function installClipboardShim() {- const ipc = window.hermesDesktop?.writeClipboard+// Primitives and CopyButton enter one policy, never nested fallback retries.+const nativeWrites = new WeakMap<Clipboard, Clipboard['writeText'] | undefined>()- if (!ipc || !navigator.clipboard) {+export async function writeClipboardText(text: string) {+ if (!text) {return}- const native = navigator.clipboard.writeText?.bind(navigator.clipboard)+ const clipboard = navigator.clipboard++ const native =+ clipboard && (nativeWrites.has(clipboard) ? nativeWrites.get(clipboard) : clipboard.writeText?.bind(clipboard))- const writeText = async (text: string) => {+ // The browser bridge calls the same native API, not an independent fallback.+ const ipc = isBrowserHostedDesktop() ? undefined : window.hermesDesktop?.writeClipboard++ if (native) {try {- await ipc(text)- } catch {- await native?.(text)+ await native(text)++ return+ } catch (error) {+ if (!ipc) {+ throw error+ }}}+ if (!ipc) {+ throw new Error('Clipboard API is unavailable')+ }++ if (!(await ipc(text))) {+ throw new Error('Clipboard write is unavailable')+ }+}++export function installClipboardShim() {+ const clipboard = navigator.clipboard++ if (!window.hermesDesktop?.writeClipboard || !clipboard || nativeWrites.has(clipboard)) {+ return+ }++ nativeWrites.set(clipboard, clipboard.writeText?.bind(clipboard))+try {- Object.defineProperty(navigator.clipboard, 'writeText', { configurable: true, value: writeText, writable: true })+ Object.defineProperty(clipboard, 'writeText', { configurable: true, value: writeClipboardText, writable: true })} catch {// Browser refused override; primitives keep using the native API.}diff --git a/apps/desktop/src/lib/desktop-fs.test.ts b/apps/desktop/src/lib/desktop-fs.test.tsindex edccb471591..9618ebff66a 100644--- a/apps/desktop/src/lib/desktop-fs.test.ts+++ b/apps/desktop/src/lib/desktop-fs.test.ts@@ -17,6 +17,7 @@ import {selectDesktopPaths,setDesktopFsRemotePicker} from './desktop-fs'+import { isBrowserHostedDesktop } from './platform'const readDir = vi.fn(async () => ({ entries: [{ name: 'local', path: '/local', isDirectory: true }] }))const readFileText = vi.fn(async (): Promise<unknown> => ({ path: '/local/file.txt', text: 'local', byteSize: 5 }))@@ -74,6 +75,7 @@ describe('desktop filesystem facade', () => {stubBridge()$connection.set(null)setApiRequestConnection(null)+ delete document.documentElement.dataset.hermesDesktopHost})afterEach(() => {@@ -81,6 +83,7 @@ describe('desktop filesystem facade', () => {vi.clearAllMocks()$connection.set(null)setApiRequestConnection(null)+ delete document.documentElement.dataset.hermesDesktopHostsetDesktopFsRemotePicker(null)})@@ -103,6 +106,26 @@ describe('desktop filesystem facade', () => {expect(api).not.toHaveBeenCalled()})+ it('treats browser-hosted local Desktop as backend filesystem mode', async () => {+ $connection.set({ mode: 'local', profile: 'phone' } as never)+ document.documentElement.dataset.hermesDesktopHost = 'browser'+ const remoteSelect = vi.fn(async () => ['/backend/project'])+ setDesktopFsRemotePicker({ selectPaths: remoteSelect })++ expect(isBrowserHostedDesktop()).toBe(true)+ await expect(readDesktopDir('/backend')).resolves.toMatchObject({ entries: [{ name: 'remote' }] })+ await expect(desktopDefaultCwd()).resolves.toEqual({ cwd: '/backend/project', branch: 'main' })+ await expect(selectDesktopPaths({ defaultPath: '/backend', directories: true })).resolves.toEqual([+ '/backend/project'+ ])++ expect(api).toHaveBeenCalledWith({ path: '/api/fs/list?path=%2Fbackend', profile: 'phone' })+ expect(api).toHaveBeenCalledWith({ path: '/api/fs/default-cwd', profile: 'phone' })+ expect(remoteSelect).toHaveBeenCalledWith({ defaultPath: '/backend', directories: true, multiple: false })+ expect(readDir).not.toHaveBeenCalled()+ expect(selectPaths).not.toHaveBeenCalled()+ })+it('routes filesystem reads through authenticated backend REST in remote mode', async () => {$connection.set({ mode: 'remote' } as never)diff --git a/apps/desktop/src/lib/desktop-fs.ts b/apps/desktop/src/lib/desktop-fs.tsindex 82620029f7c..fc53855f974 100644--- a/apps/desktop/src/lib/desktop-fs.ts+++ b/apps/desktop/src/lib/desktop-fs.ts@@ -7,6 +7,7 @@ import type {HermesSelectPathsOptions} from '@/global'import { translateNow } from '@/i18n'+import { isBrowserHostedDesktop } from '@/lib/platform'import { $connection } from '@/store/session'export interface DesktopFsRemotePicker {@@ -44,7 +45,7 @@ export function desktopFsCacheKey(connection: HermesConnection | null = $connect}export function isDesktopFsRemoteMode() {- return $connection.get()?.mode === 'remote'+ return $connection.get()?.mode === 'remote' || isBrowserHostedDesktop()}// Active profile for FS/git REST calls. Without it the Electron api bridgediff --git a/apps/desktop/src/lib/desktop-git.ts b/apps/desktop/src/lib/desktop-git.tsindex 42982147497..4b2513cb994 100644--- a/apps/desktop/src/lib/desktop-git.ts+++ b/apps/desktop/src/lib/desktop-git.ts@@ -77,11 +77,11 @@ const remoteGit: GitBridge = {(await gitGet<{ diff: string }>('review/diff', { base: baseRef, file: filePath, path: repoPath, scope, staged })).diff,- stage: (repoPath, filePath) => gitPost('review/stage', { file: filePath ?? null, path: repoPath }),+ stage: (repoPath, filePath) => gitPost('review/stage', { file: filePath || null, path: repoPath }),- unstage: (repoPath, filePath) => gitPost('review/unstage', { file: filePath ?? null, path: repoPath }),+ unstage: (repoPath, filePath) => gitPost('review/unstage', { file: filePath || null, path: repoPath }),- revert: (repoPath, filePath) => gitPost('review/revert', { file: filePath ?? null, path: repoPath }),+ revert: (repoPath, filePath) => gitPost('review/revert', { file: filePath || null, path: repoPath }),revParse: async (repoPath, ref) =>(await gitGet<{ sha: null | string }>('review/rev-parse', { path: repoPath, ref })).sha,diff --git a/apps/desktop/src/lib/download-text.ts b/apps/desktop/src/lib/download-text.tsindex 3e9091fcd64..2f46045d234 100644--- a/apps/desktop/src/lib/download-text.ts+++ b/apps/desktop/src/lib/download-text.ts@@ -1,16 +1,6 @@-/** Save generated text content to a file via a blob download. Electron's- * default will-download behavior shows the OS save dialog, so this works- * without a dedicated IPC handler (same pattern as use-image-download's- * browser fallback). */-export function downloadTextFile(name: string, content: string, mimeType = 'text/plain') {- const blobUrl = URL.createObjectURL(new Blob([content], { type: `${mimeType};charset=utf-8` }))- const link = document.createElement('a')+import { downloadBlob } from '@/lib/download'- link.href = blobUrl- link.download = name- link.rel = 'noopener noreferrer'- document.body.appendChild(link)- link.click()- link.remove()- window.setTimeout(() => URL.revokeObjectURL(blobUrl), 30_000)+/** Save generated text content to a file via a blob download. */+export function downloadTextFile(name: string, content: string, mimeType = 'text/plain') {+ downloadBlob(new Blob([content], { type: `${mimeType};charset=utf-8` }), name)}diff --git a/apps/desktop/src/hooks/use-image-download.test.ts b/apps/desktop/src/lib/download.test.tssimilarity index 96%rename from apps/desktop/src/hooks/use-image-download.test.tsrename to apps/desktop/src/lib/download.test.tsindex 10b727aff10..0b1dd755a0c 100644--- a/apps/desktop/src/hooks/use-image-download.test.ts+++ b/apps/desktop/src/lib/download.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from 'vitest'-import { downloadFilename, imageFilename } from './use-image-download'+import { downloadFilename, imageFilename } from './download'describe('imageFilename', () => {it('takes the last path segment of a URL', () => {diff --git a/apps/desktop/src/lib/download.ts b/apps/desktop/src/lib/download.tsnew file mode 100644index 00000000000..a397e001771--- /dev/null+++ b/apps/desktop/src/lib/download.ts@@ -0,0 +1,66 @@+const MIME_EXTENSIONS: Record<string, string> = {+ 'image/bmp': '.bmp',+ 'image/gif': '.gif',+ 'image/jpeg': '.jpg',+ 'image/png': '.png',+ 'image/svg+xml': '.svg',+ 'image/webp': '.webp'+}++const KNOWN_IMAGE_EXTENSION_RE = /\.(?:apng|avif|bmp|gif|ico|jpe?g|png|svg|tiff?|webp)$/i++// The download manager may resolve the blob URL after click() returns, so+// release it only once the transfer has had ample time to start.+const BLOB_URL_TTL_MS = 60_000++export function imageFilename(src?: string): string {+ if (!src) {+ return 'image'+ }++ try {+ return new URL(src, window.location.href).pathname.split('/').filter(Boolean).pop() || 'image'+ } catch {+ return src.split(/[\\/]/).filter(Boolean).pop() || 'image'+ }+}++/** Filename for a browser-anchor download. Generated-image URLs (fal.media+ * etc.) often end in an extensionless content hash — without an extension the+ * OS save dialog shows "All Files" and the saved file won't open by+ * double-click, so append one derived from the blob's MIME type. */+export function downloadFilename(src: string, mimeType?: string): string {+ const base = imageFilename(src)++ if (KNOWN_IMAGE_EXTENSION_RE.test(base)) {+ return base+ }++ const type = String(mimeType || '')+ .split(';')[0]+ .trim()+ .toLowerCase()++ return `${base}${MIME_EXTENSIONS[type] || '.png'}`+}++/** Hand `href` to the browser's download manager. An empty `filename` lets the+ * response's Content-Disposition (or the URL) name the file. */+export function clickDownloadLink(href: string, filename: string): void {+ const link = document.createElement('a')+ link.href = href+ link.download = filename+ link.rel = 'noopener noreferrer'+ link.style.display = 'none'+ document.body.append(link)+ link.click()+ link.remove()+}++/** Save in-memory bytes as `filename`. Electron's default will-download+ * behavior shows the OS save dialog, so this needs no dedicated IPC handler. */+export function downloadBlob(blob: Blob, filename: string): void {+ const url = URL.createObjectURL(blob)+ clickDownloadLink(url, filename)+ window.setTimeout(() => URL.revokeObjectURL(url), BLOB_URL_TTL_MS)+}diff --git a/apps/desktop/src/lib/external-link.test.tsx b/apps/desktop/src/lib/external-link.test.tsxindex e7d669b5d44..ab1fdb4b4ac 100644--- a/apps/desktop/src/lib/external-link.test.tsx+++ b/apps/desktop/src/lib/external-link.test.tsx@@ -42,6 +42,7 @@ function installTitleBridge(title: string) {afterEach(() => {__resetLinkTitleCache()closeRightRail()+ globalThis.document.documentElement.removeAttribute('data-hermes-desktop-host')setAlwaysExternalLinks(false)vi.restoreAllMocks()cleanup()@@ -121,9 +122,9 @@ describe('external link helpers', () => {expect(bridge).toHaveBeenCalledTimes(1)})- // A web link belongs in the in-app browser now; the OS browser is the- // ⌘/Ctrl-click escape hatch.- it('opens a web link in the in-app browser', async () => {+ // In Electron a web link belongs in the in-app browser; the OS browser is the+ // ⌘/Ctrl-click escape hatch. The connection mode does not change that.+ it('opens an Electron web link in-app', async () => {const openExternal = vi.fn().mockResolvedValue(undefined)installDesktopBridge({ openExternal: openExternal as unknown as Window['hermesDesktop']['openExternal'] })@@ -135,6 +136,23 @@ describe('external link helpers', () => {await waitFor(() => expect($previewTabs.get().at(-1)?.target.url).toBe('https://example.com/path/to/resource'))})+ it.each([false, true])(+ 'opens a Webapp web link synchronously without adding a preview when always external is %s',+ alwaysExternal => {+ globalThis.document.documentElement.dataset.hermesDesktopHost = 'browser'+ setAlwaysExternalLinks(alwaysExternal)+ const openExternal = vi.fn().mockResolvedValue(undefined)+ installDesktopBridge({ openExternal })++ render(<ExternalLink href="https://example.com/path/to/resource">Example link</ExternalLink>)++ fireEvent.click(screen.getByRole('link', { name: 'Example link' }))++ expect(openExternal).toHaveBeenCalledExactlyOnceWith('https://example.com/path/to/resource')+ expect($previewTabs.get()).toHaveLength(0)+ }+ )+// Platform-specific on purpose (same rule as terminal links / middle-click):// ⌘ on macOS, Ctrl elsewhere. The suite runs as non-mac.it('escapes to the OS browser on the platform open-elsewhere modifier', () => {@@ -149,7 +167,7 @@ describe('external link helpers', () => {expect($previewTabs.get()).toHaveLength(0)})- it('sends a plain click to the OS browser when "always external" is on', () => {+ it('sends an Electron plain click to the OS browser when always external is on', () => {const openExternal = vi.fn().mockResolvedValue(undefined)installDesktopBridge({ openExternal: openExternal as unknown as Window['hermesDesktop']['openExternal'] })setAlwaysExternalLinks(true)@@ -158,7 +176,7 @@ describe('external link helpers', () => {fireEvent.click(screen.getByRole('link', { name: 'Example link' }))- expect(openExternal).toHaveBeenCalledWith('https://example.com/path/to/resource')+ expect(openExternal).toHaveBeenCalledExactlyOnceWith('https://example.com/path/to/resource')expect($previewTabs.get()).toHaveLength(0)})diff --git a/apps/desktop/src/lib/external-link.tsx b/apps/desktop/src/lib/external-link.tsxindex 42f77a470e4..c33687e0a41 100644--- a/apps/desktop/src/lib/external-link.tsx+++ b/apps/desktop/src/lib/external-link.tsx@@ -3,6 +3,7 @@ import { useEffect, useMemo, useState } from 'react'import { ArrowUpRight } from '@/lib/icons'import { IS_MAC } from '@/lib/keybinds/combo'+import { isBrowserHostedDesktop } from '@/lib/platform'import { $alwaysExternalLinks } from '@/store/external-links'import { resolveBrandIcon } from './brand-icon'@@ -247,10 +248,12 @@ export function hudForcesNativeLinks(search = typeof window === 'undefined' ? ''/*** Where a link the user clicked should open.*- * A web page opens in the in-app browser — that pane exists so reading a doc+ * In Electron, a web page opens in the in-app browser — that pane exists so reading a doc* doesn't cost a context switch out of Hermes, and it is the surface the agent* can see. ⌘/Ctrl-click (or middle-click) escapes to the real browser, which is* where you go for anything needing your logged-in session or a password.+ * Webapp links open in a browser tab by default because sites often reject+ * embedded pages. Keep that handoff synchronous so it retains the click gesture.** Everything that ISN'T a web page — `mailto:`, `file:`, a custom scheme — has* no business in the webview and always hands off to the OS. The HUD has no@@ -266,6 +269,7 @@ export function openLink(href: string, options: { native?: boolean } = {}): voidif (options.native ||+ isBrowserHostedDesktop() ||$alwaysExternalLinks.get() ||isConnectorAuthorizationLink(target) ||hudForcesNativeLinks() ||diff --git a/apps/desktop/src/lib/gateway-ws-url.test.ts b/apps/desktop/src/lib/gateway-ws-url.test.tsindex 32b049cf6a1..75af31dcef2 100644--- a/apps/desktop/src/lib/gateway-ws-url.test.ts+++ b/apps/desktop/src/lib/gateway-ws-url.test.ts@@ -172,6 +172,33 @@ describe('resolveGatewayWsUrl', () => {await expect(resolveGatewayWsUrl({}, { wsUrl: tokenConn.wsUrl })).resolves.toBe(tokenConn.wsUrl)})})++ // A native dial (local Electron's gateway, the Webapp's serving gateway) carries no credential in+ // its descriptor: every dial needs a fresh ticket, so a failed mint is the reason to show, never a+ // fallback to a URL that can only fail later without one.+ describe('native dial', () => {+ const nativeConn = { authMode: 'token' as const, wsUrl: 'ws://host/api/ws?native_dial=browser' }++ it("surfaces the mint's own failure instead of dialing the credential-free URL", async () => {+ const cause = new Error('503: gateway unavailable')+ const getGatewayWsUrl = vi.fn().mockRejectedValue(cause)++ await expect(resolveGatewayWsUrl({ getGatewayWsUrl }, nativeConn)).rejects.toBe(cause)+ })++ it('surfaces a structured mint refusal', async () => {+ const getGatewayWsUrl = vi.fn().mockResolvedValue({ error: 'gateway incompatible', ok: false })++ await expect(resolveGatewayWsUrl({ getGatewayWsUrl }, nativeConn)).rejects.toThrow('gateway incompatible')+ })++ it('dials the freshly ticketed URL', async () => {+ const fresh = 'ws://host/api/ws?native_dial=browser&ticket=t'+ const getGatewayWsUrl = vi.fn().mockResolvedValue(fresh)++ await expect(resolveGatewayWsUrl({ getGatewayWsUrl }, nativeConn)).resolves.toBe(fresh)+ })+ })})describe('isGatewayReauthRequired', () => {diff --git a/apps/desktop/src/lib/local-preview.test.ts b/apps/desktop/src/lib/local-preview.test.tsindex 1dcdc180961..36baae2cb02 100644--- a/apps/desktop/src/lib/local-preview.test.ts+++ b/apps/desktop/src/lib/local-preview.test.ts@@ -133,6 +133,17 @@ describe('remote HTML previews', () => {expect(openPreviewInBrowser).toHaveBeenCalledWith('file:///tmp/report%20%231%3F.html')})+ it('passes browser blob staging URLs through unchanged', async () => {+ const dataUrl = `data:text/html;base64,${btoa('<h1>remote</h1>')}`+ const saveImageBuffer = vi.fn(async () => 'blob:http://127.0.0.1:9119/preview')+ const openPreviewInBrowser = vi.fn(async () => undefined)+ window.hermesDesktop = { openPreviewInBrowser, saveImageBuffer } as never++ await openPreviewTargetInBrowser({ ...remoteTarget, dataUrl })++ expect(openPreviewInBrowser).toHaveBeenCalledWith('blob:http://127.0.0.1:9119/preview')+ })+it('serializes UNC staging paths as file URLs', async () => {const dataUrl = `data:text/html;base64,${btoa('<h1>remote</h1>')}`const saveImageBuffer = vi.fn(async () => '\\\\server\\share\\report #1.html')diff --git a/apps/desktop/src/lib/local-preview.ts b/apps/desktop/src/lib/local-preview.tsindex 99e9875c8e2..f12a34f73e7 100644--- a/apps/desktop/src/lib/local-preview.ts+++ b/apps/desktop/src/lib/local-preview.ts@@ -85,7 +85,11 @@ function joinPath(base: string, rel: string) {return `${root}${parts.join('/')}`}-function pathToFileUrl(path: string) {+export function pathToFileUrl(path: string) {+ if (/^(?:blob:|data:|https?:)/i.test(path)) {+ return path+ }+const isWindowsUnc = path.startsWith('\\\\')const normalized = isWindowsUnc || /^[a-z]:[\\/]/i.test(path) ? path.replace(/\\/g, '/') : pathdiff --git a/apps/desktop/src/lib/media.ts b/apps/desktop/src/lib/media.tsindex 288c56f4670..e235301920c 100644--- a/apps/desktop/src/lib/media.ts+++ b/apps/desktop/src/lib/media.ts@@ -5,6 +5,7 @@ import type { HermesConnection } from '@/global'import { translateNow } from '@/i18n'import { desktopFsCacheKey, isReadFileErrorResult, readDesktopFileDataUrl } from '@/lib/desktop-fs'import { LruCache } from '@/lib/lru-cache'+import { isBrowserHostedDesktop } from '@/lib/platform'import { capitalize } from '@/lib/text'import { notify, notifyError } from '@/store/notifications'import { $connection } from '@/store/session'@@ -116,8 +117,14 @@ export async function resolveMediaDisplaySrc(path: string, owner?: OwnerScope):// An explicit local owner is this device, even with a remote foreground.// Keep the native reader and its configured size cap; the backend preview- // endpoint has a separate fixed limit.- if (owner?.connectionId === LOCAL_CONNECTION_ID && window.hermesDesktop?.readFileDataUrl) {+ // endpoint has a separate fixed limit. A browser page's local connection is+ // the serving backend instead, whose bridge reads follow the foreground+ // profile; it takes the owner-pinned read below.+ if (+ owner?.connectionId === LOCAL_CONNECTION_ID &&+ !isBrowserHostedDesktop() &&+ window.hermesDesktop?.readFileDataUrl+ ) {const dataUrl = await window.hermesDesktop.readFileDataUrl(filePathFromMediaPath(path))if (isReadFileErrorResult(dataUrl)) {@@ -230,19 +237,30 @@ export function rememberMediaImageFailure(key: string): void {}// Audio/video need a seekable source instead of a whole-file data URL. Keep-// remote URLs untouched and route filesystem paths through the Electron media-// protocol. Its main-process handler reads local files directly or proxies a-// remote gateway with the connection's bearer/cookie/token authentication.-export async function resolveMediaPlaybackSrc(path: string): Promise<string> {+// remote URLs untouched. The Webapp supplies an authenticated HTTP source;+// Electron's media protocol reads local files or proxies remote gateways.+export async function resolveMediaPlaybackSrc(path: string, owner?: OwnerScope): Promise<string> {if (isInlineMediaSrc(path)) {return path}if (window.hermesDesktop && ['audio', 'video'].includes(mediaKind(path))) {+ if (window.hermesDesktop.getGatewayFileStreamUrl) {+ const conn = $connection.get()++ // A tile keeps its owner's profile for every ticket, renewals included, as its image reads do.+ return window.hermesDesktop.getGatewayFileStreamUrl({+ connectionId: owner?.connectionId || conn?.connectionId,+ // The gateway OS owns file-URI conversion, including drive letters and UNC hosts.+ path,+ profile: owner?.profile || conn?.profile+ })+ }+return isRemoteGateway() ? mediaGatewayStreamUrl(path) : mediaStreamUrl(path)}- return resolveMediaDisplaySrc(path)+ return resolveMediaDisplaySrc(path, owner)}// Resolve a media path to a URL the shell can open. Remote mode rewrites@@ -376,11 +394,11 @@ export interface GatewayFileOrigin {suggestedName?: string}-// Replacement for opening gateway-local file paths with file://. The file lives-// on the gateway, so ask the Electron main process to fetch the bytes through-// the authenticated backend connection and save them locally. This avoids-// browser/OS downloads losing OAuth cookies and avoids the data-URL cap used by-// preview endpoints. Every renderer gateway-file save resolves its backend here.+// Replacement for opening gateway-local file paths with file://. The host bridge+// handles authentication and saving: Electron uses its native save dialog, while+// the Webapp uses the browser's download manager. Neither path loads the file+// through the capped data-URL preview endpoint. Every renderer gateway-file save+// resolves its backend here.export async function downloadGatewayMediaFile(path: string,origin: GatewayFileOrigin = {}diff --git a/apps/desktop/src/lib/platform.test.ts b/apps/desktop/src/lib/platform.test.tsnew file mode 100644index 00000000000..577b585f4b3--- /dev/null+++ b/apps/desktop/src/lib/platform.test.ts@@ -0,0 +1,50 @@+// @vitest-environment jsdom+import { beforeEach, describe, expect, it } from 'vitest'++import { isBrowserHostedDesktop } from './platform'++type HostWindow = Window & {+ __HERMES_AUTH_REQUIRED__?: boolean+ __HERMES_SESSION_TOKEN__?: string+ __HERMES_UI_SURFACE__?: string+}++describe('isBrowserHostedDesktop', () => {+ beforeEach(() => {+ document.documentElement.removeAttribute('data-hermes-desktop-host')+ const win = window as HostWindow+ delete win.__HERMES_SESSION_TOKEN__+ delete win.__HERMES_AUTH_REQUIRED__+ delete win.__HERMES_UI_SURFACE__+ })++ it('recognizes the browser-hosted renderer marker', () => {+ document.documentElement.dataset.hermesDesktopHost = 'browser'+ expect(isBrowserHostedDesktop()).toBe(true)+ })++ it('recognizes a gated host before the bridge marker is written', () => {+ ;(window as HostWindow).__HERMES_AUTH_REQUIRED__ = true+ expect(isBrowserHostedDesktop()).toBe(true)+ })++ // The Webapp surface is served without an injected token; the bridge still+ // installs for it, so the pre-marker check must agree.+ it('recognizes the tokenless Webapp surface before the bridge marker is written', () => {+ ;(window as HostWindow).__HERMES_UI_SURFACE__ = 'webapp'+ expect(isBrowserHostedDesktop()).toBe(true)+ })++ // Nothing serves this renderer to a browser with only an injected dashboard token, and such a page+ // has no gateway route (the ticket route is the Webapp's): it must not install a bridge that can+ // never connect.+ it('does not treat a bare injected session token as a browser host', () => {+ ;(window as HostWindow).__HERMES_SESSION_TOKEN__ = 'served-token'+ expect(isBrowserHostedDesktop()).toBe(false)+ })++ it('does not treat Electron as browser-hosted', () => {+ document.documentElement.dataset.hermesDesktopHost = 'electron'+ expect(isBrowserHostedDesktop()).toBe(false)+ })+})diff --git a/apps/desktop/src/lib/platform.ts b/apps/desktop/src/lib/platform.tsindex 11fbe3341dc..435d7ba2501 100644--- a/apps/desktop/src/lib/platform.ts+++ b/apps/desktop/src/lib/platform.ts@@ -20,3 +20,36 @@ export const isWindowsPlatform = (): boolean =>export const isLinuxPlatform = (): boolean =>typeof navigator !== 'undefined' && /linux/i.test(navigator.platform || navigator.userAgent || '')++/** Globals the Hermes web server injects into the page it serves. */+export interface BrowserHostGlobals {+ __HERMES_AUTH_REQUIRED__?: boolean+ __HERMES_BASE_PATH__?: string+ __HERMES_UI_SURFACE__?: string+}++/**+ * The server served this page as the browser-hosted Desktop: a gated host+ * (cookie auth) or the Webapp surface (its session arrives by launch link).+ * The browser bridge installs on exactly this predicate. An injected session+ * token alone is not one: nothing serves this renderer that way, and the only+ * gateway route it could use is the Webapp's.+ */+export function hasBrowserHostBootstrap(): boolean {+ const win = window as Window & BrowserHostGlobals++ return win.__HERMES_AUTH_REQUIRED__ === true || win.__HERMES_UI_SURFACE__ === 'webapp'+}++/** Renderer host, independent of the OS or the gateway's connection mode. */+export function isBrowserHostedDesktop() {+ if (typeof document === 'undefined') {+ return false+ }++ // The bridge writes the marker once it installs. During static module+ // evaluation, use the browser bootstrap globals too; otherwise an OS check+ // can classify a browser page as native before the marker is written.+ return document.documentElement.dataset.hermesDesktopHost === 'browser' ||+ (!window.hermesDesktop && hasBrowserHostBootstrap())+}diff --git a/apps/desktop/src/lib/touch-interaction.test.ts b/apps/desktop/src/lib/touch-interaction.test.tsnew file mode 100644index 00000000000..18c675bf459--- /dev/null+++ b/apps/desktop/src/lib/touch-interaction.test.ts@@ -0,0 +1,28 @@+import { afterEach, describe, expect, it, vi } from 'vitest'++import { isTouchInteraction } from './touch-interaction'++afterEach(() => vi.unstubAllGlobals())++describe('touch input ownership', () => {+ it('uses coarse capability only when the event has no input evidence', () => {+ vi.stubGlobal('matchMedia', vi.fn().mockReturnValue({ matches: true }))+ expect(isTouchInteraction(new Event('contextmenu'))).toBe(true)+ expect(isTouchInteraction(Object.assign(new Event('contextmenu'), { pointerType: 'mouse' }))).toBe(false)+ expect(+ isTouchInteraction(Object.assign(new Event('contextmenu'), { sourceCapabilities: { firesTouchEvents: false } }))+ ).toBe(false)+ })++ it('recognizes touch and pen on a hybrid device', () => {+ vi.stubGlobal('matchMedia', vi.fn().mockReturnValue({ matches: false }))++ for (const pointerType of ['touch', 'pen']) {+ expect(isTouchInteraction(Object.assign(new Event('contextmenu'), { pointerType }))).toBe(true)+ }++ expect(+ isTouchInteraction(Object.assign(new Event('dblclick'), { sourceCapabilities: { firesTouchEvents: true } }))+ ).toBe(true)+ })+})diff --git a/apps/desktop/src/lib/touch-interaction.ts b/apps/desktop/src/lib/touch-interaction.tsnew file mode 100644index 00000000000..255e0fa1705--- /dev/null+++ b/apps/desktop/src/lib/touch-interaction.ts@@ -0,0 +1,45 @@+import { atom } from 'nanostores'++import { matchesQuery } from '@/hooks/use-media-query'+import { isBrowserHostedDesktop } from '@/lib/platform'++export const TOUCH_POINTER_QUERY = '(hover: none), (pointer: coarse)'++// One listener shared by every transcript bubble instead of a media-query hook+// per bubble. Guarded like `$narrowViewport`: jsdom and node test envs have no+// `matchMedia`.+const touchPointerQuery = typeof window !== 'undefined' ? window.matchMedia?.(TOUCH_POINTER_QUERY) : undefined++/** Coarse-pointer / no-hover surface, the same query the touch CSS keys on. */+export const $touchPointer = atom(Boolean(touchPointerQuery?.matches))++touchPointerQuery?.addEventListener('change', event => $touchPointer.set(event.matches))++const BROWSER_OWNED_TOUCH_TARGET =+ '[data-slot="aui_user-message-root"], [data-slot="aui_assistant-message-content"], [data-slot="aui_system-message-root"], [data-selectable-text="true"], input, textarea, [contenteditable]:not([contenteditable="false"]), a[href], img, video, audio'++/** A browser-host touch on text, editables, links or media: its long-press+ * belongs to the browser/OS (selection, paste, link and media callouts),+ * including the interval before selection handles exist. */+export function isBrowserOwnedTouch(event: Event): boolean {+ const element = event.target instanceof Element ? event.target : null++ return Boolean(isBrowserHostedDesktop() && element?.closest(BROWSER_OWNED_TOUCH_TARGET) && isTouchInteraction(event))+}++/** Context-menu/double-click events are not PointerEvents in every browser.+ * Prefer actual input evidence, then WebKit's coarse-pointer capability. */+export function isTouchInteraction(event?: Event): boolean {+ const input = event as+ (Event & { pointerType?: string; sourceCapabilities?: { firesTouchEvents?: boolean } }) | undefined++ if (input?.pointerType) {+ return input.pointerType === 'touch' || input.pointerType === 'pen'+ }++ if (input?.sourceCapabilities) {+ return input.sourceCapabilities.firesTouchEvents === true+ }++ return matchesQuery(TOUCH_POINTER_QUERY)+}diff --git a/apps/desktop/src/lib/wake-client-capture.ts b/apps/desktop/src/lib/wake-client-capture.tsindex 2ecab5d6220..dabc818169d 100644--- a/apps/desktop/src/lib/wake-client-capture.ts+++ b/apps/desktop/src/lib/wake-client-capture.ts@@ -7,6 +7,8 @@* runs server-side without requiring a server sound device.*/+import { bytesToBase64 } from './base64'+const TARGET_RATE = 16_000const DEFAULT_FRAME = 1280 // 80 ms @ 16 kHz — matches tools/wake_word.py@@ -89,18 +91,6 @@ function floatToInt16LE(input: Float32Array): ArrayBuffer {return buf}-function bytesToBase64(buf: ArrayBuffer): string {- const bytes = new Uint8Array(buf)- let binary = ''- const chunk = 0x8000-- for (let i = 0; i < bytes.length; i += chunk) {- binary += String.fromCharCode(...bytes.subarray(i, i + chunk))- }-- return btoa(binary)-}-/*** Start streaming the default microphone to `wake.feed`.* Returns a handle whose `stop()` ends tracks + audio graph.diff --git a/apps/desktop/src/main.tsx b/apps/desktop/src/main.tsxindex 4ef94636b9a..1e7f8d9d5ed 100644--- a/apps/desktop/src/main.tsx+++ b/apps/desktop/src/main.tsx@@ -1,4 +1,7 @@import './styles.css'+// Install the loopback browser host before any store/App modules evaluate.+// Electron preload remains authoritative when its bridge already exists.+import './lib/browser-desktop-bridge-install'// Side-effect: reports in-flight turns to the main process for the quit guard.import './store/active-work'// Side-effect: mirrors the machine's AC/battery state for poll demotion.@@ -34,6 +37,7 @@ import { installClipboardShim } from './lib/clipboard'import { queryClient } from './lib/query-client'import { installRendererAnimationPauseState } from './lib/renderer-loop-pause'import { installSelectionCopyColorGuard } from './lib/selection-copy-colors'+import { installBrowserTabTitle } from './store/browser-tab-title'import { ThemeProvider } from './themes/context'installClipboardShim()@@ -41,6 +45,8 @@ installClipboardShim()// theme's computed colors inlined; without this guard a dark-theme selection// pastes as near-white text into light-background targets.installSelectionCopyColorGuard()+// Browser host only: the tab carries session status while the user is away.+installBrowserTabTitle()// The perf probe ships in dev, and in a production build ONLY when explicitly// opted in (VITE_PERF_PROBE=1) — this lets the perf harness measure a real,diff --git a/apps/desktop/src/store/browser-tab-title.test.ts b/apps/desktop/src/store/browser-tab-title.test.tsnew file mode 100644index 00000000000..761b1a80922--- /dev/null+++ b/apps/desktop/src/store/browser-tab-title.test.ts@@ -0,0 +1,115 @@+import { afterEach, beforeEach, describe, expect, it } from 'vitest'++import { createClientSessionState } from '@/lib/chat-runtime'+import type { SessionInfo } from '@/types/hermes'++import { makeSessionInfo } from '../test/session-info'++import { type BrowserTabStatus, browserTabTitle, installBrowserTabTitle } from './browser-tab-title'+import { $selectedStoredSessionId, $sessions, $unreadFinishedSessionIds, setSessions } from './session'+import { clearAllSessionStates, publishSessionState } from './session-states'+import { $sessionSeenCounts, $unreadFinishedMarkers } from './session-unread'++const row = (over: Partial<SessionInfo>): SessionInfo => makeSessionInfo({ message_count: 3, ...over })++const state = (storedId: string, over: { busy?: boolean; needsInput?: boolean } = {}) => ({+ ...createClientSessionState(storedId),+ ...over+})++const tabTitle = (over: Partial<BrowserTabStatus> = {}) =>+ browserTabTitle({ caption: 'Fix login', needsInput: false, unread: 0, working: false, ...over })++let uninstall = () => {}++function reset() {+ uninstall()++ uninstall = () => {}+ clearAllSessionStates()+ $sessions.set([])+ $selectedStoredSessionId.set(null)+ $sessionSeenCounts.set({})+ $unreadFinishedMarkers.set({})+ $unreadFinishedSessionIds.set([])+ delete document.documentElement.dataset.hermesDesktopHost+ document.title = 'Hermes'+}++describe('browserTabTitle', () => {+ it('lets a blocking prompt speak over a running turn, behind the unread count', () => {+ const idle = tabTitle()+ const working = tabTitle({ working: true })+ const blocked = tabTitle({ needsInput: true, working: true })++ expect(idle).toContain('Fix login')+ // Each status marks the front of the idle title; a blocking prompt replaces+ // the running mark rather than joining it.+ expect(working).not.toBe(idle)+ expect(working.endsWith(idle)).toBe(true)+ expect(blocked).not.toBe(working)+ expect(blocked.endsWith(idle)).toBe(true)+ expect(blocked).toBe(tabTitle({ needsInput: true }))++ const counted = tabTitle({ needsInput: true, unread: 2 })+ expect(counted.endsWith(blocked)).toBe(true)+ expect(counted.slice(0, -blocked.length)).toContain('2')++ // Without a caption the title falls back to the app name alone.+ const bare = tabTitle({ caption: '' })+ expect(bare).not.toBe('')+ expect(idle.endsWith(bare)).toBe(true)+ expect(tabTitle({ caption: '', unread: 1 }).endsWith(bare)).toBe(true)+ })+})++describe('installBrowserTabTitle', () => {+ beforeEach(reset)+ afterEach(reset)++ it('follows the focused session and background status in a browser host', () => {+ document.documentElement.dataset.hermesDesktopHost = 'browser'+ setSessions([row({ id: 's1', title: 'Fix login' }), row({ id: 's2', profile: 'writer', title: 'Draft essay' })])+ $selectedStoredSessionId.set('s1')+ uninstall = installBrowserTabTitle()++ expect(document.title).toBe(tabTitle())++ publishSessionState('r1', state('s1', { busy: true }))+ expect(document.title).toBe(tabTitle({ working: true }))++ // Another session blocks on an approval: the whole window needs the user.+ publishSessionState('r2', state('s2', { busy: true, needsInput: true }))+ expect(document.title).toBe(tabTitle({ needsInput: true, working: true }))++ // It finishes unwatched; the focused turn ends too, while being looked at.+ publishSessionState('r2', state('s2'))+ publishSessionState('r1', state('s1'))+ expect(document.title).toBe(tabTitle({ unread: 1 }))++ // Opening it reads it; a non-default profile names its owner.+ $selectedStoredSessionId.set('s2')+ $unreadFinishedSessionIds.set([])+ // Nothing is left to mark ahead of the caption, which names the owner.+ expect(document.title.startsWith('Draft essay')).toBe(true)+ expect(document.title).toContain('writer')+ })++ it('never puts unsent or untitled text in the tab', () => {+ document.documentElement.dataset.hermesDesktopHost = 'browser'+ setSessions([row({ id: 's1', preview: 'my bank password is', title: null })])+ $selectedStoredSessionId.set('s1')+ uninstall = installBrowserTabTitle()++ expect(document.title).toBe('Hermes')+ })++ it('leaves the native window title alone', () => {+ setSessions([row({ id: 's1', title: 'Fix login' })])+ $selectedStoredSessionId.set('s1')+ uninstall = installBrowserTabTitle()+ publishSessionState('r1', state('s1', { busy: true }))++ expect(document.title).toBe('Hermes')+ })+})diff --git a/apps/desktop/src/store/browser-tab-title.ts b/apps/desktop/src/store/browser-tab-title.tsnew file mode 100644index 00000000000..ddd6d5f7652--- /dev/null+++ b/apps/desktop/src/store/browser-tab-title.ts@@ -0,0 +1,95 @@+/**+ * The browser tab title of the browser-hosted Desktop (Webapp).+ *+ * In a browser the tab strip is the one surface that stays visible while the+ * user is in another tab or app, so the title carries the same signals the+ * sidebar dots and titlebar badge do, ahead of the focused session's name:+ *+ * (2) ⚠ Fix the flaky test · Hermes+ *+ * a count of unread finished sessions, then one mark — `⚠` when anything is+ * blocked on the user, else `●` while a turn runs — then the session.+ *+ * Browser-hosted only: Electron mirrors `document.title` into the native window+ * title, which is a separate decision. Unsent drafts never name the tab — their+ * text is composer content, and a title lands in browser history and synced+ * tab lists.+ */++import { computed } from 'nanostores'++import { $workspaceOwnerLabels, workspaceOwnerTitle } from '@/components/pane-shell/workspace-scope'+import { isBrowserHostedDesktop } from '@/lib/platform'++import { normalizeProfileKey } from './profile'+import { $sessions, sessionMatchesStoredId } from './session'+import { $unreadSessionCount } from './session-dot-state'+import { $focusedStoredSessionId } from './session-focus'+import { $attentionSessionIds, $sessionTiles, $workingSessionIds } from './session-states'++const APP_NAME = 'Hermes'++export interface BrowserTabStatus {+ /** The focused session's name, or empty when it has none yet. */+ caption: string+ /** Some session in this window is blocked on an approval or an answer. */+ needsInput: boolean+ /** Listed sessions holding a finished turn the user has not opened. */+ unread: number+ /** Some session in this window has a turn running. */+ working: boolean+}++export function browserTabTitle({ caption, needsInput, unread, working }: BrowserTabStatus): string {+ // A blocking prompt is the only state that needs the user, so it speaks over+ // a running turn rather than beside it.+ const mark = needsInput ? '⚠' : working ? '●' : ''+ const name = caption ? `${caption} · ${APP_NAME}` : APP_NAME++ return [unread > 0 ? `(${unread})` : '', mark, name].filter(Boolean).join(' ')+}++const $focusedCaption = computed(+ [$focusedStoredSessionId, $sessions, $sessionTiles, $workspaceOwnerLabels],+ (focused, sessions, tiles) => {+ if (!focused) {+ return ''+ }++ const row = sessions.find(session => sessionMatchesStoredId(session, focused))+ const tile = tiles.find(candidate => candidate.storedSessionId === focused)+ // Hidden relationship chats (canonical Bot Chats) are absent from the list;+ // their tab keeps a stable title, which the owner label then replaces.+ const title = row?.title?.trim() || tile?.workspaceTabTitle || ''++ if (!title) {+ return ''+ }++ const caption = workspaceOwnerTitle(title, tile)+ const profile = normalizeProfileKey(row?.profile ?? tile?.ownerProfile)++ // A bot's own name already says whose chat this is.+ return caption === title && profile !== 'default' ? `${caption} — ${profile}` : caption+ }+)++const $browserTabTitle = computed(+ [$focusedCaption, $attentionSessionIds, $workingSessionIds, $unreadSessionCount],+ (caption, attention, working, unread) =>+ browserTabTitle({ caption, needsInput: attention.length > 0, unread, working: working.length > 0 })+)++/** Keep the tab title in step with session status. A no-op outside a browser+ * host; returns the unsubscribe. */+export function installBrowserTabTitle(): () => void {+ if (typeof document === 'undefined' || !isBrowserHostedDesktop()) {+ return () => {}+ }++ return $browserTabTitle.subscribe(title => {+ if (document.title !== title) {+ document.title = title+ }+ })+}diff --git a/apps/desktop/src/store/composer-queue-owner.test.ts b/apps/desktop/src/store/composer-queue-owner.test.tsnew file mode 100644index 00000000000..b73833d4fa1--- /dev/null+++ b/apps/desktop/src/store/composer-queue-owner.test.ts@@ -0,0 +1,27 @@+import { afterEach, describe, expect, it } from 'vitest'++import type { HermesConnection } from '@/global'++import { serverOwnsComposerQueue } from './composer-queue'+import { $connection } from './session'++const browser = (wsUrl: string) => ({ mode: 'remote', wsUrl }) as HermesConnection++afterEach(() => $connection.set(null))++// The browser-hosted Desktop attaches to the canonical socket of the gateway serving it: its+// owner admits queued input into the durable FIFO, so the composer must hand its queue to the+// server exactly as local Electron does, not keep a renderer-local queue the owner never sees.+describe('composer queue ownership for the browser-hosted Desktop', () => {+ it('belongs to the gateway when the window dials its canonical socket', () => {+ $connection.set(browser('wss://host.example/api/ws?profile=work&native_dial=browser'))++ expect(serverOwnsComposerQueue('a-session-with-no-recorded-owner')).toBe(true)+ })++ it('stays in the renderer for a backend still on the legacy contract', () => {+ $connection.set(browser('wss://host.example/api/ws?token=served-token'))++ expect(serverOwnsComposerQueue('a-session-with-no-recorded-owner')).toBe(false)+ })+})diff --git a/apps/desktop/src/store/composer.ts b/apps/desktop/src/store/composer.tsindex 2c4c553b281..f2a312f380d 100644--- a/apps/desktop/src/store/composer.ts+++ b/apps/desktop/src/store/composer.ts@@ -1,5 +1,6 @@import { atom } from 'nanostores'+import type { HermesStagedUpload } from '@/global'import { deriveDraftTitle } from '@/lib/draft-title'import { triggerHaptic } from '@/lib/haptics'import { persistString, storedString } from '@/lib/storage'@@ -70,6 +71,8 @@ export interface ComposerAttachment {/** Downscaled data URL for the attachment card and optimistic bubble only. */thumbnailUrl?: stringpath?: string+ /** Ownership of browser-staged bytes; survives failed uploads and draft clones. */+ stagedUpload?: HermesStagedUpload/** Validated MIME returned by canonical owner staging. */mime?: string/** Bounded source text from a Hermes-generated large paste, sent only to the title path. */diff --git a/apps/desktop/src/store/profile-rail-prefs.test.tsx b/apps/desktop/src/store/profile-rail-prefs.test.tsxnew file mode 100644index 00000000000..2f9b83ca838--- /dev/null+++ b/apps/desktop/src/store/profile-rail-prefs.test.tsx@@ -0,0 +1,127 @@+// @vitest-environment jsdom+import { act, cleanup, render, renderHook } from '@testing-library/react'+import { MemoryRouter } from 'react-router'+import { afterAll, afterEach, beforeAll, describe, expect, it, vi } from 'vitest'++// Switching profiles has exactly one door at a time: the rail at the sidebar+// foot, or the statusbar picker beside the gateway switcher when the user hides+// the rail. The Webapp (browser-hosted Desktop) always draws the rail as its+// dropdown, never the squares; native Desktop keeps the squares until the+// dropdown threshold. The host is fixed per page load, so each case loads a+// fresh module graph after declaring its host — in a hook, whose timeout+// absorbs the cold sidebar/statusbar import.++type SurfaceWindow = Window & { __HERMES_UI_SURFACE__?: string }++const noop = () => {}++const noopAsync = async () => {}++afterEach(() => {+ cleanup()+ localStorage.clear()+})++async function importHost(webapp: boolean) {+ if (webapp) {+ ;(window as SurfaceWindow).__HERMES_UI_SURFACE__ = 'webapp'+ }++ vi.resetModules()++ const [{ ChatSidebar }, { SidebarProvider }, { useStatusbarItems }, { group }, { $layoutTree }, prefs] =+ await Promise.all([+ import('@/app/chat/sidebar'),+ import('@/components/ui/sidebar'),+ import('@/app/shell/hooks/use-statusbar-items'),+ import('@/components/pane-shell/tree/model'),+ import('@/components/pane-shell/tree/store'),+ import('@/store/profile-rail-prefs')+ ])++ return { $layoutTree, ChatSidebar, group, prefs, SidebarProvider, useStatusbarItems }+}++type HostModules = Awaited<ReturnType<typeof importHost>>++function renderDoors({ $layoutTree, ChatSidebar, group, SidebarProvider, useStatusbarItems }: HostModules) {+ // The sessions pane is on screen: both doors live with it.+ $layoutTree.set(group(['sessions'], { active: 'sessions', id: 'sessions-group' }))++ const sidebar = render(+ <MemoryRouter>+ <SidebarProvider>+ <ChatSidebar+ currentView="chat"+ onArchiveSession={noop}+ onBranchSession={noop}+ onDeleteSession={noop}+ onLoadMoreSessions={noop}+ onManageCronJob={noop}+ onNavigate={noop}+ onNewSessionInWorkspace={noop}+ onNewSessionSplit={noop}+ onResumeSession={noop}+ onRetrySessions={noopAsync}+ onTriggerCronJob={noopAsync}+ />+ </SidebarProvider>+ </MemoryRouter>+ )++ const statusbar = renderHook(+ () =>+ useStatusbarItems({+ agentsOpen: false,+ changeSessionCwd: noopAsync,+ chatOpen: true,+ commandCenterOpen: false,+ extraLeftItems: [],+ extraRightItems: [],+ freshDraftReady: false,+ gatewayState: 'ready',+ inferenceStatus: null,+ openAgents: noop,+ openCommandCenterSection: noop,+ requestGateway: async () => undefined as never,+ statusSnapshot: null,+ toggleCommandCenter: noop+ }),+ { wrapper: MemoryRouter }+ )++ const doors = () => ({+ dropdown: sidebar.container.querySelector('[data-slot="profile-dropdown"]') !== null,+ picker: statusbar.result.current.leftStatusbarItems.some(item => item.id === 'profile-switcher' && !item.hidden),+ rail: sidebar.container.querySelector('[data-slot="profile-rail"]') !== null+ })++ return doors+}++describe.each([+ { host: 'Webapp', webapp: true, dropdown: true },+ { host: 'native Desktop', webapp: false, dropdown: false }+])('$host', ({ dropdown, webapp }) => {+ let host: HostModules++ beforeAll(async () => {+ host = await importHost(webapp)+ })++ afterAll(() => {+ delete (window as SurfaceWindow).__HERMES_UI_SURFACE__+ vi.resetModules()+ })++ it('keeps exactly one profile door, the Webapp as a dropdown', () => {+ const doors = renderDoors(host)++ // The rail stays at the sidebar foot whether or not the statusbar is shown.+ expect(doors()).toEqual({ dropdown, picker: false, rail: true })++ // Hiding the rail hands the door to the statusbar picker on either host.+ act(() => host.prefs.toggleProfileRailVisible())+ expect(doors()).toEqual({ dropdown: false, picker: true, rail: false })+ })+})diff --git a/apps/desktop/src/store/profile-select-webapp.test.ts b/apps/desktop/src/store/profile-select-webapp.test.tsnew file mode 100644index 00000000000..fe73d532d52--- /dev/null+++ b/apps/desktop/src/store/profile-select-webapp.test.ts@@ -0,0 +1,80 @@+import { atom } from 'nanostores'+import { afterEach, beforeEach, expect, it, vi } from 'vitest'++import { clearWebappSession, seedWebappSession } from '@/test/webapp-session'++// A live profile switch in a Webapp tab is recorded in THAT tab's URL, so a+// reload lands on the profile the user is in, and a generic New session+// follows it. It is not the origin's saved default (only "Set as default"+// writes that), no other tab hears about it, and the tab's own backend — the+// one its primary socket reconnects to — stays the profile it booted on.++const ensureGatewayForProfile = vi.fn(async (_profile: string) => undefined)+const ensureGatewayForAgent = vi.fn(async (_connectionId: null | string, _profile: string) => true)+const activeGatewayConnectionId = vi.fn<() => null | string>(() => null)++vi.mock('@/store/gateway', () => ({+ $gateway: atom<unknown>({ id: 'live-socket' }),+ activeGatewayConnectionId,+ activeGatewayProfileKey: () => ensureGatewayForProfile.mock.lastCall?.[0] ?? $activeGatewayProfile.get(),+ ensureGatewayForAgent,+ ensureGatewayForProfile,+ openGatewayForProfile: vi.fn(async () => undefined)+}))+vi.mock('@/hermes', () => ({+ getProfiles: vi.fn(async () => ({ profiles: [] })),+ setApiRequestProfile: vi.fn()+}))+vi.mock('@/lib/query-client', () => ({ invalidateProfileScopedQueries: vi.fn() }))+vi.mock('@/store/starmap', () => ({ reloadOpenStarmapGraph: vi.fn(), resetStarmapGraph: vi.fn() }))++const { $activeGatewayProfile, selectProfile } = await import('./profile')+const { installBrowserDesktopBridge } = await import('@/lib/browser-desktop-bridge')++const bootstrap = window as Window & { __HERMES_BASE_PATH__?: string; }+const savedDefault = { connectionId: 'local', profile: 'research' }+const urlProfile = () => new URLSearchParams(window.location.search).get('profile')++beforeEach(async () => {+ bootstrap.__HERMES_BASE_PATH__ = '/hermes'+ seedWebappSession('served-token')+ window.history.replaceState(null, '', '/hermes?profile=arrived#/')+ expect(installBrowserDesktopBridge()).toBe(true)+ await window.hermesDesktop.profile.setDefault(savedDefault)+ $activeGatewayProfile.set('arrived')+})++afterEach(() => {+ Reflect.deleteProperty(window, 'hermesDesktop')+ delete bootstrap.__HERMES_BASE_PATH__+ clearWebappSession()+ document.documentElement.removeAttribute('data-hermes-desktop-host')+ window.localStorage.clear()+ window.history.replaceState(null, '', '/#/')+ vi.clearAllMocks()+})++// A tab that booted on the saved default dials it as the registry `local`+// route; it is still this tab's only source.+it.each([+ { boot: 'its URL', source: null },+ { boot: 'the saved default route', source: 'local' }+])('records a live switch in the tab that booted on $boot, and only there', async ({ source }) => {+ activeGatewayConnectionId.mockReturnValue(source)+ const defaultChanged = vi.fn()+ const unsubscribe = window.hermesDesktop.profile.onDefaultChanged(defaultChanged)++ selectProfile('ops')+ await vi.waitFor(() => expect(urlProfile()).toBe('ops'))++ // Default is written out, not dropped: a bare URL would boot the saved default.+ selectProfile('default')+ await vi.waitFor(() => expect(urlProfile()).toBe('default'))++ expect(window.location.pathname).toBe('/hermes')+ expect(window.location.hash).toBe('#/')+ await expect(window.hermesDesktop.profile.getDefault()).resolves.toEqual(savedDefault)+ expect(defaultChanged).not.toHaveBeenCalled()+ await expect(window.hermesDesktop.getConnection()).resolves.toMatchObject({ profile: 'arrived' })+ unsubscribe()+})diff --git a/apps/desktop/src/store/profile.ts b/apps/desktop/src/store/profile.tsindex d5c61bec0e7..b570b856c81 100644--- a/apps/desktop/src/store/profile.ts+++ b/apps/desktop/src/store/profile.ts@@ -3,6 +3,7 @@ import { atom, batch, computed } from 'nanostores'import type { HermesConnection } from '@/global'import { getProfiles, hermesApi, setApiRequestProfile, STARTUP_REQUEST_TIMEOUT_MS } from '@/hermes'+import { isBrowserHostedDesktop } from '@/lib/platform'import { sortByProfileOrder as sortProfilesByOrder } from '@/lib/profile-order'import { invalidateProfileScopedQueries } from '@/lib/query-client'import {@@ -991,13 +992,9 @@ export function selectProfile(name: string): void {//// The profile rail is a live workspace switch, so it must not call// profile.set() and reload the window. Once activation succeeds, remember- // the selection for the next Desktop launch through the persistence-only- // IPC instead (#79886). Registry-source picks name ANOTHER source's- // profiles, so only a primary-backend activation updates the startup- // preference.- const onPrimary = activeGatewayConnectionId() == null-- const shouldRememberStartupProfile = onPrimary ? isLocalDesktopProfile(target) : Promise.resolve(false)+ // the selection for the next launch through the persistence-only bridge+ // call instead (#79886). Decided now: the source is the one picked from.+ const shouldRememberStartupProfile = remembersProfilePick(target)void Promise.all([activateOnCurrentSource(target), shouldRememberStartupProfile]).then(([, shouldRemember]) => {@@ -1014,6 +1011,22 @@ export function selectProfile(name: string): void {})}+// Whether a pick becomes the profile this window starts in next time.+// Electron: only a primary-backend pick of a local profile. Registry-source+// picks name ANOTHER source's profiles, and a per-profile ssh/remote/cloud+// override must never replace the local Desktop startup profile.+// Webapp: every pick. A browser tab has one source, the serving origin — its+// descriptor always reads `remote`, and a default-route boot names it `local`+// — and its startup profile is the tab's own `?profile=`, which `remember`+// rewrites in place. The per-origin default and other tabs are untouched.+function remembersProfilePick(target: string): Promise<boolean> {+ if (isBrowserHostedDesktop()) {+ return Promise.resolve(true)+ }++ return activeGatewayConnectionId() == null ? isLocalDesktopProfile(target) : Promise.resolve(false)+}+// Resolve persistence from the saved per-profile Desktop route, rather than the// live backend descriptor. A descriptor lookup is intentionally best-effort:// failure must not discard a successful local selection's startup preference.diff --git a/apps/desktop/src/store/quick-entry.test.ts b/apps/desktop/src/store/quick-entry.test.tsindex 536d439640a..f7406222b90 100644--- a/apps/desktop/src/store/quick-entry.test.ts+++ b/apps/desktop/src/store/quick-entry.test.ts@@ -1,15 +1,20 @@-import { describe, expect, it } from 'vitest'+import { afterEach, describe, expect, it, vi } from 'vitest'import {+ $quickEntry,+ canUseQuickEntry,initialQuickComposerState,+ loadQuickEntrySettings,QUICK_TARGET_CURRENT,QUICK_TARGET_NEW,type QuickComposerEvent,quickComposerReducer,type QuickComposerState,quickEntryResultEvent,+ type QuickEntryStatus,type QuickEntrySubmitPayload,- type QuickEntrySubmitResult+ type QuickEntrySubmitResult,+ saveQuickEntrySettings} from './quick-entry'// Drive the reducer like the window does, collecting every send it asked for.@@ -454,3 +459,52 @@ describe('quickComposerReducer', () => {expect(state.error).toBe('first failed')})})++describe('Quick Entry settings bridge', () => {+ const desktopWindow = window as unknown as { hermesDesktop?: Window['hermesDesktop'] }+ const initialHermesDesktop = desktopWindow.hermesDesktop+ const initialState = $quickEntry.get()++ const status = (shortcut: string): QuickEntryStatus => ({ enabled: true, error: null, registered: true, shortcut })++ afterEach(() => {+ if (initialHermesDesktop) {+ desktopWindow.hermesDesktop = initialHermesDesktop+ } else {+ delete desktopWindow.hermesDesktop+ }++ $quickEntry.set(initialState)+ })++ it('reads and writes through the bridge, adopting its reply and rolling back a failed write', async () => {+ const getSettings = vi.fn().mockResolvedValue(status('Alt+Space'))++ const setSettings = vi+ .fn()+ .mockResolvedValueOnce({ ...status('Alt+K'), error: 'taken', registered: false })+ .mockRejectedValueOnce(new Error('ipc closed'))++ desktopWindow.hermesDesktop = { quickEntry: { getSettings, setSettings } } as unknown as Window['hermesDesktop']++ expect(canUseQuickEntry()).toBe(true)+ await loadQuickEntrySettings()+ expect($quickEntry.get()).toMatchObject({ registered: true, shortcut: 'Alt+Space' })+ await saveQuickEntrySettings({ shortcut: 'Alt+K' })+ expect(setSettings).toHaveBeenCalledWith({ shortcut: 'Alt+K' })+ expect($quickEntry.get()).toMatchObject({ error: 'taken', registered: false, shortcut: 'Alt+K' })+ const adopted = $quickEntry.get()+ await saveQuickEntrySettings({ enabled: false })+ expect($quickEntry.get()).toBe(adopted)+ })++ it('changes nothing where the shell has no Quick Entry bridge', async () => {+ delete desktopWindow.hermesDesktop+ const before = $quickEntry.get()++ expect(canUseQuickEntry()).toBe(false)+ await loadQuickEntrySettings()+ await saveQuickEntrySettings({ enabled: false })+ expect($quickEntry.get()).toBe(before)+ })+})diff --git a/apps/desktop/src/store/quick-entry.ts b/apps/desktop/src/store/quick-entry.tsindex 03838a9c253..d77f76efcd1 100644--- a/apps/desktop/src/store/quick-entry.ts+++ b/apps/desktop/src/store/quick-entry.ts@@ -57,19 +57,31 @@ function applyStatus(status: QuickEntryStatus | undefined): void {})}+type QuickEntryBridge = NonNullable<Window['hermesDesktop']['quickEntry']>++/** The shell's Quick Entry settings call, or undefined where there is none+ * (outside Electron, the Webapp's bridge). */+function quickEntrySettingsCall<K extends 'getSettings' | 'setSettings'>(name: K): QuickEntryBridge[K] | undefined {+ const call = typeof window === 'undefined' ? undefined : window.hermesDesktop?.quickEntry?.[name]++ return typeof call === 'function' ? call : undefined+}+/** True when the shell exposes the Quick Entry capability (desktop only). */export function canUseQuickEntry(): boolean {- return typeof window !== 'undefined' && typeof window.hermesDesktop?.quickEntry?.getSettings === 'function'+ return quickEntrySettingsCall('getSettings') !== undefined}/** Read the live registration state into the store (Settings mount). */export async function loadQuickEntrySettings(): Promise<void> {- if (!canUseQuickEntry()) {+ const getSettings = quickEntrySettingsCall('getSettings')++ if (!getSettings) {return}try {- applyStatus(await window.hermesDesktop.quickEntry.getSettings())+ applyStatus(await getSettings())} catch {// A failed read leaves the store as-is; the row keeps its last known copy.}@@ -81,7 +93,9 @@ export async function loadQuickEntrySettings(): Promise<void> {* instead of a silently-lost setting.*/export async function saveQuickEntrySettings(patch: { enabled?: boolean; shortcut?: string }): Promise<void> {- if (!canUseQuickEntry()) {+ const setSettings = quickEntrySettingsCall('setSettings')++ if (!setSettings) {return}@@ -91,7 +105,7 @@ export async function saveQuickEntrySettings(patch: { enabled?: boolean; shortcu$quickEntry.set({ ...previous, ...patch, registered: previous.registered })try {- applyStatus(await window.hermesDesktop.quickEntry.setSettings(patch))+ applyStatus(await setSettings(patch))} catch {$quickEntry.set(previous)}diff --git a/apps/desktop/src/store/translucency-browser.test.ts b/apps/desktop/src/store/translucency-browser.test.tsnew file mode 100644index 00000000000..81b640a11fc--- /dev/null+++ b/apps/desktop/src/store/translucency-browser.test.ts@@ -0,0 +1,39 @@+// @vitest-environment jsdom+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++const desktopWindow = window as unknown as { hermesDesktop?: Partial<Window['hermesDesktop']> }++// The bridge reports native capability as a fact, so no host OS is faked.+async function loadTranslucency(host: 'browser' | 'electron') {+ document.documentElement.dataset.hermesDesktopHost = host+ desktopWindow.hermesDesktop = { glassSupported: true, translucencySupported: true }+ vi.resetModules()++ return import('@/store/translucency')+}++describe('browser translucency capability', () => {+ beforeEach(() => {+ localStorage.clear()+ document.documentElement.removeAttribute('data-hermes-desktop-host')+ })++ afterEach(() => {+ Reflect.deleteProperty(desktopWindow, 'hermesDesktop')+ vi.restoreAllMocks()+ vi.resetModules()+ })++ it('disables native window translucency in the browser host even when the bridge reports support', async () => {+ const translucency = await loadTranslucency('browser')++ expect(translucency.GLASS_SUPPORTED).toBe(false)+ expect(translucency.TRANSLUCENCY_SUPPORTED).toBe(false)+ })++ it('retains native capability detection outside the browser host', async () => {+ const translucency = await loadTranslucency('electron')++ expect(translucency.TRANSLUCENCY_SUPPORTED).toBe(true)+ })+})diff --git a/apps/desktop/src/store/translucency.ts b/apps/desktop/src/store/translucency.tsindex c9cc7667bfd..a2a665bc755 100644--- a/apps/desktop/src/store/translucency.ts+++ b/apps/desktop/src/store/translucency.ts@@ -45,7 +45,7 @@ import {} from '@hermes/shared/translucency'import { atom, computed } from 'nanostores'-import { isMacPlatform, isWindowsPlatform } from '@/lib/platform'+import { isBrowserHostedDesktop, isMacPlatform, isWindowsPlatform } from '@/lib/platform'import { readJson, writeJson } from '@/lib/storage'export {@@ -68,10 +68,12 @@ export type { Appearance }* Mac or Windows — which is why this file pins `navigator.platform` before* import.*/+/** Browser-hosted Desktop has no native window material or opacity surface. */export const GLASS_SUPPORTED =- typeof window !== 'undefined' && typeof window.hermesDesktop?.glassSupported === 'boolean'+ !isBrowserHostedDesktop() &&+ (typeof window !== 'undefined' && typeof window.hermesDesktop?.glassSupported === 'boolean'? window.hermesDesktop.glassSupported- : isMacPlatform() || isWindowsPlatform()+ : isMacPlatform() || isWindowsPlatform())/*** Whether the setting is worth showing at all. Linux has neither half —@@ -79,9 +81,10 @@ export const GLASS_SUPPORTED =* Settings hides the row rather than offering a lever that does nothing.*/export const TRANSLUCENCY_SUPPORTED =- typeof window !== 'undefined' && typeof window.hermesDesktop?.translucencySupported === 'boolean'+ !isBrowserHostedDesktop() &&+ (typeof window !== 'undefined' && typeof window.hermesDesktop?.translucencySupported === 'boolean'? window.hermesDesktop.translucencySupported- : isMacPlatform() || isWindowsPlatform()+ : isMacPlatform() || isWindowsPlatform())/** Windows collapses the frost ladder — see `glassMaterialsFor`. */export const GLASS_IS_WINDOWS = GLASS_SUPPORTED && !isMacPlatform()diff --git a/apps/desktop/src/store/windows.test.ts b/apps/desktop/src/store/windows.test.tsindex c690cb213d7..fccb2caad75 100644--- a/apps/desktop/src/store/windows.test.ts+++ b/apps/desktop/src/store/windows.test.ts@@ -3,11 +3,14 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'import { $activeGatewayProfile } from './profile'import { $sessions } from './session'import {+ canOpenBrowserWindow,+ canOpenSessionInTerminal,isPeerInstanceWindow,isProfilePinnedWindow,openBrowserInNewWindow,openNewWindow,- openSessionInNewWindow+ openSessionInNewWindow,+ openSessionInTerminal} from './windows'const desktopWindow = window as unknown as { hermesDesktop?: Window['hermesDesktop'] }@@ -150,6 +153,7 @@ describe('openBrowserInNewWindow', () => {it('returns false when the bridge is absent', async () => {delete desktopWindow.hermesDesktop+ expect(canOpenBrowserWindow()).toBe(false)expect(await openBrowserInNewWindow('tab-1')).toBe(false)expect(notifyError).not.toHaveBeenCalled()})@@ -158,6 +162,7 @@ describe('openBrowserInNewWindow', () => {const open = vi.fn().mockResolvedValue({ ok: true })installBridge(undefined, undefined, open)+ expect(canOpenBrowserWindow()).toBe(true)expect(await openBrowserInNewWindow('tab-1')).toBe(true)expect(open).toHaveBeenCalledWith('tab-1')expect(notifyError).not.toHaveBeenCalled()@@ -177,3 +182,23 @@ describe('openBrowserInNewWindow', () => {expect(notifyError).toHaveBeenCalledTimes(1)})})++describe('openSessionInTerminal', () => {+ it('hands a session to the bridge, and is a no-op without one or without a session id', async () => {+ const open = vi.fn().mockResolvedValue({ ok: true })+ desktopWindow.hermesDesktop = { openSessionInTerminal: open } as unknown as Window['hermesDesktop']++ expect(canOpenSessionInTerminal()).toBe(true)+ await openSessionInTerminal('', { cwd: '/work' })+ expect(open).not.toHaveBeenCalled()+ await openSessionInTerminal('s1', { cwd: '/work', profile: 'work' })+ expect(open).toHaveBeenCalledWith('s1', { cwd: '/work', profile: 'work' })++ delete desktopWindow.hermesDesktop++ expect(canOpenSessionInTerminal()).toBe(false)+ await openSessionInTerminal('s1')+ expect(open).toHaveBeenCalledTimes(1)+ expect(notifyError).not.toHaveBeenCalled()+ })+})diff --git a/apps/desktop/src/store/windows.ts b/apps/desktop/src/store/windows.tsindex b46d5b4247a..c81bd6730cc 100644--- a/apps/desktop/src/store/windows.ts+++ b/apps/desktop/src/store/windows.ts@@ -179,16 +179,34 @@ export function canOpenNewWindow(): boolean {return typeof window !== 'undefined' && typeof window.hermesDesktop?.openWindow === 'function'}+type DesktopBridge = Window['hermesDesktop']++// The shell's call that pops the in-app Browser into its own OS window, or+// undefined where there is none (outside Electron, the Webapp's bridge).+function browserWindowOpener(): DesktopBridge['openBrowserWindow'] {+ const open = typeof window === 'undefined' ? undefined : window.hermesDesktop?.openBrowserWindow++ return typeof open === 'function' ? open : undefined+}++// The shell's call that hands a session to the user's own terminal emulator,+// or undefined where there is none (outside Electron, the Webapp's bridge).+function sessionTerminalOpener(): DesktopBridge['openSessionInTerminal'] {+ const open = typeof window === 'undefined' ? undefined : window.hermesDesktop?.openSessionInTerminal++ return typeof open === 'function' ? open : undefined+}+// True when the shell can pop the in-app Browser into its own OS window.export function canOpenBrowserWindow(): boolean {- return typeof window !== 'undefined' && typeof window.hermesDesktop?.openBrowserWindow === 'function'+ return browserWindowOpener() !== undefined}// True when the shell can hand a session to the user's own terminal emulator.// Desktop-only, and a REMOTE connection is excluded by the caller: the terminal// we'd open is on this machine, but the session lives on the remote host.export function canOpenSessionInTerminal(): boolean {- return typeof window !== 'undefined' && typeof window.hermesDesktop?.openSessionInTerminal === 'function'+ return sessionTerminalOpener() !== undefined}type WindowOpenResult = { ok: boolean; error?: string } | undefined@@ -267,11 +285,13 @@ export async function openNewWindow(route?: { connectionId: null | string; profi/** Pop the in-app Browser into its own OS window. Returns whether the* window opened so the caller can dock the tab again on failure. */export async function openBrowserInNewWindow(tabId: string): Promise<boolean> {- if (!tabId || !canOpenBrowserWindow()) {+ const openBrowserWindow = browserWindowOpener()++ if (!tabId || !openBrowserWindow) {return false}- return runWindowOpen(() => window.hermesDesktop.openBrowserWindow(tabId), 'Could not pop out browser')+ return runWindowOpen(() => openBrowserWindow(tabId), 'Could not pop out browser')}// Resume a session in the user's own terminal emulator, running the TUI there.@@ -281,12 +301,11 @@ export async function openSessionInTerminal(sessionId: string,opts?: { cwd?: string; profile?: string }): Promise<void> {- if (!sessionId || !canOpenSessionInTerminal()) {+ const openInTerminal = sessionTerminalOpener()++ if (!sessionId || !openInTerminal) {return}- await runWindowOpen(- () => window.hermesDesktop.openSessionInTerminal(sessionId, opts),- 'Could not open chat in a terminal'- )+ await runWindowOpen(() => openInTerminal(sessionId, opts), 'Could not open chat in a terminal')}diff --git a/apps/desktop/src/styles.css b/apps/desktop/src/styles.cssindex c7cba78cea9..06a7d94eee5 100644--- a/apps/desktop/src/styles.css+++ b/apps/desktop/src/styles.css@@ -542,6 +542,7 @@--composer-width: 100%;--composer-control-size: 1.5rem;--composer-control-primary-size: 1.625rem;+ --composer-voice-menu-size: 1.25rem;--composer-control-gap: 0.25rem;--composer-row-gap: 0.25rem;--composer-ring-strength: 1;@@ -844,6 +845,29 @@}}+/* Touch surfaces need a real finger-sized control lane. Keep desktop's+ compact 24/26px rhythm, but promote the same composer actions to the 44px+ minimum recommended for coarse pointers without adding a second+ mobile-only component. */+@media (hover: none), (pointer: coarse) {+ :root {+ --composer-control-size: 2.75rem;+ --composer-control-primary-size: 2.75rem;+ --composer-voice-menu-size: var(--composer-control-size);+ }++ /* iOS Safari zooms the page into any focused text field under 16px and+ stays zoomed after the keyboard closes. Browser hosts floor text entry+ there; a larger chat-text scale still wins in the composer. */+ html[data-hermes-desktop-host='browser'] :is(input, textarea, select) {+ font-size: max(16px, 1em);+ }++ html[data-hermes-desktop-host='browser'] [data-slot='composer-rich-input'] {+ font-size: max(16px, var(--conversation-text-font-size));+ }+}+.dither {background: repeating-conic-gradient(currentColor 0% 25%, transparent 0% 50%) 0 0 / 0.125rem 0.125rem;}@@ -1443,6 +1467,9 @@ textarea,[contenteditable]:not([contenteditable='false']),[data-slot='aui_user-message-root'],[data-slot='aui_assistant-message-content'],+[data-slot='aui_assistant-message-content'] p,+[data-slot='aui_assistant-message-content'] pre,+[data-slot='aui_assistant-message-content'] code,[data-slot='aui_system-message-root'],[data-selectable-text='true'],[data-selectable-text='true'] * {@@ -1465,6 +1492,13 @@ button,user-select: text;}+[data-slot='aui_user-message-root'] [data-slot='aui_user-touch-edit'] {+ -webkit-user-select: none;+ user-select: none;+ min-width: 44px;+ min-height: 44px;+}+img,picture,video,@@ -2527,6 +2561,45 @@ button[data-slot='aui_msg-reactions'] svg {height: 0.875rem;}+/* Hover reveals are useful on desktop, but a coarse pointer needs a stable+ action lane. Keep the rich desktop row intact and expose a compact Copy ++ More pair on touch surfaces; the buttons themselves get the 44px hit box+ while the glyphs retain the existing quiet 14px scale. */+.aui-message-actions-touch {+ display: none;+}++@media (hover: none), (pointer: coarse) {+ [data-slot='aui_msg-actions'] {+ opacity: 1;+ pointer-events: auto;+ }++ [data-slot='aui_msg-actions'] .aui-message-actions-desktop {+ display: none;+ }++ [data-slot='aui_msg-actions'] .aui-message-actions-touch {+ display: flex;+ }++ [data-slot='aui_msg-actions'] .aui-message-actions-touch button {+ min-width: 2.75rem;+ min-height: 2.75rem;+ }++ button[data-slot='aui_msg-reactions'] {+ min-width: 2.75rem;+ min-height: 2.75rem;+ opacity: 0.5;+ pointer-events: auto;+ }++ button[data-slot='aui_msg-reactions'][data-reacted] {+ opacity: 1;+ }+}+/* Re-declare the clearance calc on every chat surface. `:root` computes itonce against the ROOT measurement, so scoping only the input would leaveevery thread reading the same substituted value. Redeclaring here makes each@@ -3876,6 +3949,22 @@ html[data-hud-window] [data-slot='popover-content'] {display: none;}+/* CSS zoom scales viewport units too; browser shells must fit their parent. */+html[data-hermes-desktop-host='browser'] #root[data-browser-viewport] {+ position: relative;+ top: var(--browser-viewport-top);+ height: var(--browser-viewport-height);+}++html[data-hermes-desktop-host='browser'] [data-contrib-shell] {+ width: 100%;+ height: 100%;+}++html[data-hermes-desktop-host='browser'] [data-slot='sidebar-container'] {+ height: 100%;+}+/* Keep-alive hidden panes (see pane-visibility.ts) hide with `visibility:hidden` so the layout box — and with it scroll positions — survives a tabround-trip. But `visibility` is inherited-and-overridable: third-partydiff --git a/apps/desktop/src/test/webapp-session.ts b/apps/desktop/src/test/webapp-session.tsnew file mode 100644index 00000000000..5b136d98eef--- /dev/null+++ b/apps/desktop/src/test/webapp-session.ts@@ -0,0 +1,24 @@+import { normalizeBasePath } from '@hermes/shared'++import { webappSessionKey } from '@/lib/browser-launch-session'++type WebappWindow = Window & { __HERMES_BASE_PATH__?: string; __HERMES_UI_SURFACE__?: string }++/**+ * A Webapp tab after its private launch link, on an unauthenticated bind: the browser host's only+ * credential, as `consumeWebappSession` reads it back. Seeds the grant for the base path the window+ * carries at call time, so set `__HERMES_BASE_PATH__` first.+ */+export function seedWebappSession(token: string): void {+ const win = window as WebappWindow+ win.__HERMES_UI_SURFACE__ = 'webapp'+ sessionStorage.setItem(webappSessionKey(normalizeBasePath(win.__HERMES_BASE_PATH__)), token)+}++export function clearWebappSession(): void {+ delete (window as WebappWindow).__HERMES_UI_SURFACE__++ for (const key of Object.keys(sessionStorage)) {+ if (key.startsWith('hermes.webapp.session.v1:')) {sessionStorage.removeItem(key)}+ }+}diff --git a/apps/desktop/tsconfig.electron.json b/apps/desktop/tsconfig.electron.jsonindex c8ed7be2616..8f0a2964cb7 100644--- a/apps/desktop/tsconfig.electron.json+++ b/apps/desktop/tsconfig.electron.json@@ -17,6 +17,6 @@"rootDir": "..","outDir": "build/electron-types"},- "include": ["electron", "product-identity.cjs", "product-identity.d.cts", "update-feed.cjs", "update-feed.d.cts", "../shared/src/ansi.ts", "../shared/src/data-url-read-max.ts", "../shared/src/translucency.ts"],+ "include": ["electron", "product-identity.cjs", "product-identity.d.cts", "update-feed.cjs", "update-feed.d.cts", "../shared/src/ansi.ts", "../shared/src/data-url-read-max.ts", "../shared/src/external-url.ts", "../shared/src/translucency.ts"],"exclude": ["src", "electron/**/*.e2e.mts"]}diff --git a/apps/desktop/vite.config.ts b/apps/desktop/vite.config.tsindex 68cb9510dcb..ec2fd425daa 100644--- a/apps/desktop/vite.config.ts+++ b/apps/desktop/vite.config.ts@@ -18,7 +18,10 @@ function compilerPreset() {* lockfile and this config (the preset and its filter) pin the toolchain it keys on. The* cache lives under node_modules: ignored, and outside every freshness hash. */async function cachedCompilerPass(command: string) {- return withCompilerCache(await babel({ presets: [compilerPreset()] }), {+ // Babel resolves the compiler preset's plugin from its cwd. Pin it here: the+ // Webapp build runs Vite from the checkout root, which a fresh clone leaves+ // without node_modules (its dependencies live in the private workspace).+ return withCompilerCache(await babel({ cwd: __dirname, presets: [compilerPreset()] }), {command,cacheRoot: path.join(__dirname, 'node_modules/.cache/hermes-react-compiler'),base: __dirname,diff --git a/apps/shared/src/external-url.ts b/apps/shared/src/external-url.tsnew file mode 100644index 00000000000..e6501f7f012--- /dev/null+++ b/apps/shared/src/external-url.ts@@ -0,0 +1,39 @@+/**+ * Which URLs Desktop hands to a browser when asked to open something+ * externally. Electron's `openExternalUrl` (shell.openExternal) and the+ * browser-hosted bridge (window.open) share this one rule, so an agent- or+ * tool-supplied `javascript:` or custom-scheme link is refused on both hosts.+ *+ * `file:` is its own kind: only a host with a local file opener may act on it.+ */++const WEB_PROTOCOLS = new Set(['http:', 'https:', 'mailto:'])++export interface ExternalUrlTarget {+ kind: 'file' | 'web'+ /** `web`: the normalized URL. `file`: the trimmed input, left for the host's file opener to parse. */+ url: string+}++/** Classify an external URL; null for empty, malformed or unsupported-scheme input. */+export function externalUrlTarget(rawUrl: string): ExternalUrlTarget | null {+ const raw = String(rawUrl || '').trim()++ if (!raw) {+ return null+ }++ let parsed: URL++ try {+ parsed = new URL(raw)+ } catch {+ return null+ }++ if (parsed.protocol === 'file:') {+ return { kind: 'file', url: raw }+ }++ return WEB_PROTOCOLS.has(parsed.protocol) ? { kind: 'web', url: parsed.toString() } : null+}diff --git a/apps/shared/src/index.ts b/apps/shared/src/index.tsindex 3bf687a2663..87dc2408dc8 100644--- a/apps/shared/src/index.ts+++ b/apps/shared/src/index.ts@@ -61,6 +61,7 @@ export {DATA_URL_READ_MAX_MAX_MB,DATA_URL_READ_MIN_MAX_MB} from './data-url-read-max'+export { type ExternalUrlTarget, externalUrlTarget } from './external-url'export { compactNumber } from './format'export { type FuzzyMatch, fuzzyRank, fuzzyScore, fuzzyScoreMulti, type RankedItem } from './fuzzy'export * from './gateway-events'@@ -202,6 +203,7 @@ export {type GatewayWsUrlResult,type HermesWebSocketUrlOptions,isGatewayReauthRequired,+ normalizeBasePath,resolveGatewayWsUrl,type ResolveGatewayWsUrlDeps,type WebSocketAuthParamdiff --git a/apps/shared/src/websocket-url.ts b/apps/shared/src/websocket-url.tsindex 24592c4642b..9c4e1a3e32c 100644--- a/apps/shared/src/websocket-url.ts+++ b/apps/shared/src/websocket-url.ts@@ -78,8 +78,18 @@ export async function resolveGatewayWsUrl(deps: ResolveGatewayWsUrlDeps, conn: G}}+ // A native dial's descriptor URL carries no credential of its own, so a failed mint IS the answer+ // (a gateway that cannot attach says why); falling back to that URL only fails later, nameless.+ const nativeDial = hasNativeDial(conn.wsUrl)+if (mint) {- const fresh = await mint(profile).catch(() => null)+ const fresh = await mint(profile).catch((error: unknown) => {+ if (nativeDial) {+ throw error+ }++ return null+ })if (typeof fresh === 'string') {return fresh@@ -88,11 +98,23 @@ export async function resolveGatewayWsUrl(deps: ResolveGatewayWsUrlDeps, conn: Gif (fresh?.ok) {return fresh.wsUrl}++ if (fresh && nativeDial) {+ throw new Error(fresh.error || 'Could not mint a gateway WebSocket ticket.')+ }}return conn.wsUrl}+function hasNativeDial(wsUrl: string): boolean {+ try {+ return new URL(wsUrl).searchParams.has('native_dial')+ } catch {+ return false+ }+}+export type WebSocketAuthParam = readonly [name: string, value: string]export interface HermesWebSocketUrlOptions {@@ -118,7 +140,7 @@ function readWindowLocation(): { host: string; protocol: string } {return { host: window.location.host, protocol: window.location.protocol }}-function normalizeBasePath(basePath: string | undefined): string {+export function normalizeBasePath(basePath: string | undefined): string {if (!basePath) {return ''}diff --git a/tests-js/product-builders.test.mjs b/tests-js/product-builders.test.mjsindex 253b96370c5..e53d868591d 100644--- a/tests-js/product-builders.test.mjs+++ b/tests-js/product-builders.test.mjs@@ -369,3 +369,108 @@ test('TUI freshness invalidates source, configuration and compiler inputs and dawriteFileSync(entry, 'damaged output')expect(current()).toBe(false)})++test('a browser renderer publish never invalidates the native Desktop inputs', async () => {+ const { sourceHash } = await import('../scripts/build/freshness.mjs')+ const source = fixture()+ put(source, 'apps/desktop/package.json', '{}')+ put(source, 'apps/desktop/src/main.ts', 'export {}')+ const before = sourceHash(source, 'desktop')+ put(source, 'apps/desktop/dist-webapp/index.html', 'browser renderer')+ put(source, 'apps/desktop/.dist-webapp-build-1/product/index.html', 'staged renderer')+ expect(sourceHash(source, 'desktop')).toBe(before)+ put(source, 'apps/desktop/src/main.ts', 'export const changed = true')+ expect(sourceHash(source, 'desktop')).not.toBe(before)+})++function webappSource(source) {+ put(source, 'package.json', JSON.stringify({ private: true, type: 'module', workspaces: ['apps/*', 'web'] }))+ put(source, 'package-lock.json', JSON.stringify({ lockfileVersion: 3, packages: {+ '': { workspaces: ['apps/*', 'web'] },+ 'apps/desktop': { name: 'desktop' }, 'apps/shared': { name: 'shared' }, web: { name: 'web' },+ 'node_modules/desktop': { link: true, resolved: 'apps/desktop' },+ 'node_modules/shared': { link: true, resolved: 'apps/shared' },+ 'node_modules/web': { link: true, resolved: 'web' },+ } }))+ put(source, '.npmrc', 'engine-strict=true\n')+ put(source, 'apps/desktop/package.json', '{"name":"desktop","type":"module"}')+ put(source, 'apps/desktop/index.html', '<html><body><script type="module" src="/src/main.ts"></script></body></html>')+ put(source, 'apps/desktop/src/main.ts', 'import { answer } from "../../shared/src/value"; document.body.textContent = answer;')+ put(source, 'apps/shared/package.json', '{"name":"shared"}')+ put(source, 'apps/shared/src/value.ts', 'export const answer: string = "browser renderer";')+ put(source, 'web/package.json', '{"name":"web"}')+}++test('the Webapp receipt certifies its checkout inputs, not the workspace it compiled in', async () => {+ const { productCurrent } = await import('../scripts/build/freshness.mjs')+ const { buildWebapp } = await import('../scripts/build/webapp.mjs')+ const { mirrorWebappInputs } = await import('../apps/desktop/scripts/build-webapp.mjs')+ const base = fixture()+ const source = path.join(base, 'source')+ const workspace = path.join(base, 'workspace')+ const out = path.join(source, 'apps/desktop/dist-webapp')+ webappSource(source)+ // Only the private workspace has installed dependencies.+ dependency(workspace, '', 'vite')+ const build = async () => {+ mirrorWebappInputs(source, workspace)+ await buildWebapp({ source, workspace, out })+ }+ const current = () => productCurrent({ source, product: 'webapp', out })+ await build()+ expect(current()).toBe(true)+ expect(readFileSync(path.join(out, 'index.html'), 'utf8')).toContain('<script')+ // Other products' sources, native outputs and release metadata never rebuild the renderer.+ for (const name of ['web/src/unrelated.ts', 'pyproject.toml', 'assets/icon.svg', 'apps/desktop/dist/index.html', 'scripts/build/tui.mjs']) {+ put(source, name, 'not a Webapp input')+ expect(current(), name).toBe(true)+ }+ for (const [input, content] of [+ ['apps/shared/src/value.ts', 'export const answer: string = "edited shared";'],+ ['apps/desktop/src/main.ts', 'document.body.textContent = "edited desktop";'],+ ['package-lock.json', readFileSync(path.join(source, 'package-lock.json'), 'utf8').replace('"lockfileVersion":3', '"lockfileVersion":3,"requires":true')],+ ['.npmrc', 'engine-strict=false\n'],+ ['pm/lock.json', '{}'],+ ['scripts/build/webapp.mjs', '// compiler changed'],+ ]) {+ put(source, input, content)+ expect(current(), input).toBe(false)+ await build()+ expect(current(), `rebuilt after ${input}`).toBe(true)+ }+ // A workspace that no longer mirrors the checkout must not publish under a current receipt.+ put(workspace, 'apps/desktop/src/main.ts', 'document.body.textContent = "stale mirror";')+ await expect(buildWebapp({ source, workspace, out })).rejects.toThrow(/does not match/)+ expect(current()).toBe(true)+ writeFileSync(path.join(out, 'index.html'), 'damaged output')+ expect(current()).toBe(false)+}, 60_000)++test('Webapp builds install privately and never disturb the native Desktop installation', async () => {+ const { buildSourceWebapp } = await import('../apps/desktop/scripts/build-webapp.mjs')+ const base = fixture()+ const source = path.join(base, 'source')+ const workspace = path.join(base, 'workspace')+ webappSource(source)+ put(source, 'node_modules/electron/dist/electron', 'native install')+ put(source, 'apps/desktop/dist/index.html', 'native renderer')+ put(source, 'apps/desktop/src/removed-later.ts', 'export {}')+ const installs = []+ const prepare = options => {+ installs.push(options.install)+ expect(options.source).toBe(workspace)+ expect(options.env.npm_config_ignore_scripts).toBe('true')+ // npm ci validates the whole locked graph, not only the compiled workspaces.+ expect(existsSync(path.join(workspace, 'web/package.json'))).toBe(true)+ if (!existsSync(path.join(workspace, 'node_modules/vite'))) dependency(workspace, '', 'vite')+ }+ await buildSourceWebapp({ source, workspace, prepare, install: false })+ rmSync(path.join(source, 'apps/desktop/src/removed-later.ts'))+ await buildSourceWebapp({ source, workspace, prepare })+ expect(installs).toEqual([false, true])+ expect(existsSync(path.join(workspace, 'apps/desktop/src/removed-later.ts'))).toBe(false)+ expect(existsSync(path.join(workspace, 'node_modules/vite/package.json'))).toBe(true)+ expect(readFileSync(path.join(source, 'node_modules/electron/dist/electron'), 'utf8')).toBe('native install')+ expect(readFileSync(path.join(source, 'apps/desktop/dist/index.html'), 'utf8')).toBe('native renderer')+ expect(existsSync(path.join(source, 'apps/desktop/dist-webapp/hermes-build.json'))).toBe(true)+}, 60_000)