The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fmt(js): `npm run fix` on merge (#118250)
hermes-seaeye[bot]bc655bfb40ff
diff --git a/apps/desktop/electron/api-transport.test.ts b/apps/desktop/electron/api-transport.test.tsindex 1ad2448565f..bc7fea0ecf3 100644--- a/apps/desktop/electron/api-transport.test.ts+++ b/apps/desktop/electron/api-transport.test.ts@@ -418,7 +418,9 @@ describe('htmlResponseError', () => {expect(redirected).toContain('to https://sso.example.com/login?next=%2Fapi%2Fprofiles')expect(redirected).toMatch(/authentication proxy/)expect(redirected).not.toContain('endpoint is likely missing')- expect(htmlResponseError('https://gateway.example.com/api/profiles', 307).message).toMatch(/redirected \(status 307\)\. This is usually/)+ expect(htmlResponseError('https://gateway.example.com/api/profiles', 307).message).toMatch(+ /redirected \(status 307\)\. This is usually/+ )expect(htmlResponseError('https://gateway.example.com/api/missing', 200).message).toContain('endpoint is likely missing')@@ -437,6 +439,8 @@ describe('htmlResponseError', () => {expect(message).not.toMatch(/authentication proxy/)}- expect(htmlResponseError('https://gateway.example.com/api/profiles', 302, 'https://gateway.example.com/login').message).toMatch(/authentication proxy/)+ expect(+ htmlResponseError('https://gateway.example.com/api/profiles', 302, 'https://gateway.example.com/login').message+ ).toMatch(/authentication proxy/)})})diff --git a/apps/desktop/electron/backend-claim.test.ts b/apps/desktop/electron/backend-claim.test.tsindex 2572e15ee4f..4a5273ee1f2 100644--- a/apps/desktop/electron/backend-claim.test.ts+++ b/apps/desktop/electron/backend-claim.test.ts@@ -145,10 +145,16 @@ test('exit line carries the buffered tail next to the exit code, preferring theformatBackendExitLine('Ignoring stale Hermes backend exit', 1, null, tail),'Ignoring stale Hermes backend exit (1)\nRecent backend output:\nTraceback (most recent call last):')- assert.equal(formatBackendExitLine('Hermes backend exited', null, 'SIGTERM', tail), 'Hermes backend exited (SIGTERM)\nRecent backend output:\nTraceback (most recent call last):')+ assert.equal(+ formatBackendExitLine('Hermes backend exited', null, 'SIGTERM', tail),+ 'Hermes backend exited (SIGTERM)\nRecent backend output:\nTraceback (most recent call last):'+ )})test('exit line stays byte-identical to the legacy shape when the tail is empty or missing', () => {- assert.equal(formatBackendExitLine('Hermes backend exited', 0, null, createBackendOutputTail(64)), 'Hermes backend exited (0)')+ assert.equal(+ formatBackendExitLine('Hermes backend exited', 0, null, createBackendOutputTail(64)),+ 'Hermes backend exited (0)'+ )assert.equal(formatBackendExitLine('Hermes backend exited', 1, null, null), 'Hermes backend exited (1)')})diff --git a/apps/desktop/electron/backend-discovery.test.ts b/apps/desktop/electron/backend-discovery.test.tsindex b9c755a2e39..be5e56e8e2d 100644--- a/apps/desktop/electron/backend-discovery.test.ts+++ b/apps/desktop/electron/backend-discovery.test.ts@@ -39,8 +39,7 @@ test('a running backend record makes startup attach and spawn zero processes', aconst setup = await runPrimaryBackendStartup({assertCurrentAttempt: () => {},- attachHostBackend: () =>- attachToHostBackend({ isolated: false, ledgerPath: '/ledger.json' }, attachDeps(LEDGER)),+ attachHostBackend: () => attachToHostBackend({ isolated: false, ledgerPath: '/ledger.json' }, attachDeps(LEDGER)),connectRemote: async () => ({ mode: 'remote' }),ensureLocalRuntime: async backend => backend,prepareLocalBackend: () => {diff --git a/apps/desktop/electron/backend-discovery.ts b/apps/desktop/electron/backend-discovery.tsindex b8ea59dbe2a..bf860c6abd9 100644--- a/apps/desktop/electron/backend-discovery.ts+++ b/apps/desktop/electron/backend-discovery.ts@@ -30,8 +30,7 @@ export interface HostBackendRecord {}export type SpawnOrAttachDecision =- | { action: 'attach'; record: HostBackendRecord }- | { action: 'spawn'; reason: 'isolated' | 'no-running-backend' }+ { action: 'attach'; record: HostBackendRecord } | { action: 'spawn'; reason: 'isolated' | 'no-running-backend' }/** Filename the CLI writes under the machine Hermes root. */export const SPAWN_LEDGER_FILENAME = 'spawn-ledger.json'diff --git a/apps/desktop/electron/backend-probes.test.ts b/apps/desktop/electron/backend-probes.test.tsindex 950ff81532a..fae2cddf3f2 100644--- a/apps/desktop/electron/backend-probes.test.ts+++ b/apps/desktop/electron/backend-probes.test.ts@@ -34,8 +34,8 @@ const NODE_BIN = process.execPathtest('execProbe keeps the parent event loop available to the child', async () => {let unexpectedSocketError: Error | undefined- const server = net.createServer((socket) => {- socket.on('error', (error) => {+ const server = net.createServer(socket => {+ socket.on('error', error => {// A successful child exits immediately after reading the sentinel. On// Windows that peer close can surface as ECONNRESET on the server side.if ((error as NodeJS.ErrnoException).code !== 'ECONNRESET') {@@ -71,7 +71,7 @@ test('execProbe keeps the parent event loop available to the child', async () =>})} finally {await new Promise<void>((resolve, reject) => {- server.close((error) => (error ? reject(error) : resolve()))+ server.close(error => (error ? reject(error) : resolve()))})}diff --git a/apps/desktop/electron/bootstrap-runner.ts b/apps/desktop/electron/bootstrap-runner.tsindex 377d07249a7..a8d818e855c 100644--- a/apps/desktop/electron/bootstrap-runner.ts+++ b/apps/desktop/electron/bootstrap-runner.ts@@ -746,7 +746,9 @@ async function fetchManifest({// the installer's colour/OSC bytes here too (#112675).const tail = stripAnsi(result.stderr || result.stdout).trim()- throw new Error(`${isPosix ? 'install.sh --manifest' : 'install.ps1 -Manifest'} failed: exit ${result.code}\n${tail}`)+ throw new Error(+ `${isPosix ? 'install.sh --manifest' : 'install.ps1 -Manifest'} failed: exit ${result.code}\n${tail}`+ )}// The manifest is the LAST JSON line on stdout (install.ps1 may printdiff --git a/apps/desktop/electron/cloud-discovery.test.ts b/apps/desktop/electron/cloud-discovery.test.tsindex 7284f70824f..7004a875cfa 100644--- a/apps/desktop/electron/cloud-discovery.test.ts+++ b/apps/desktop/electron/cloud-discovery.test.ts@@ -16,10 +16,12 @@ test('a stale team falls back once to current memberships; unrelated failures rerequests.push(req.url!)const scoped = req.url!.includes('?org=')res.writeHead(scoped ? status : fallbackStatus, { 'Content-Type': 'application/json' })+const body =fallbackStatus === 200? { agents: [], org: { id: 'new-team' } }: { error: 'org_selection_required', orgs: [{ id: 'new-team' }] }+res.end(JSON.stringify(scoped ? { error } : body))})diff --git a/apps/desktop/electron/command-screenshot-capture.test.ts b/apps/desktop/electron/command-screenshot-capture.test.tsindex 83d9b2750cd..c5bfaad1d3d 100644--- a/apps/desktop/electron/command-screenshot-capture.test.ts+++ b/apps/desktop/electron/command-screenshot-capture.test.ts@@ -22,7 +22,11 @@ describe('Command screenshot capture', () => {expect(await capture.take(8, request)).toEqual({ ok: false, reason: 'expired' })expect(sources).not.toHaveBeenCalled()expect(await capture.take(7, request)).toEqual({ ok: true, png })- expect(sources).toHaveBeenCalledWith({ types: ['window'], thumbnailSize: { width: 2400, height: 1600 }, fetchWindowIcons: false })+ expect(sources).toHaveBeenCalledWith({+ types: ['window'],+ thumbnailSize: { width: 2400, height: 1600 },+ fetchWindowIcons: false+ })expect(await capture.take(7, request)).toEqual({ ok: false, reason: 'expired' })sources.mockResolvedValue([{ id: 'window:99:0', thumbnail: { isEmpty: () => false, toPNG: () => png } }])@@ -37,6 +41,7 @@ describe('Command screenshot capture', () => {permission.mockReturnValue(true)vi.useFakeTimers()+try {const expired = capture.request(7, window)!vi.advanceTimersByTime(6000)@@ -46,7 +51,12 @@ describe('Command screenshot capture', () => {}let finish!: (value: Awaited<ReturnType<typeof sources>>) => void- sources.mockImplementation(() => new Promise(resolve => { finish = resolve }))+ sources.mockImplementation(+ () =>+ new Promise(resolve => {+ finish = resolve+ })+ )const pending = capture.take(7, capture.request(7, window)!)expect(capture.request(7, window)).toBeNull()capture.clear()diff --git a/apps/desktop/electron/command-screenshot-capture.ts b/apps/desktop/electron/command-screenshot-capture.tsindex 0d108ad48d7..b7fcd099936 100644--- a/apps/desktop/electron/command-screenshot-capture.ts+++ b/apps/desktop/electron/command-screenshot-capture.ts@@ -62,6 +62,7 @@ export function createScreenshotCapture({ getSources, hasScreenPermission }: Cap// Retina detail, bounded for very large windows. No display fallback:// sharing the desktop would expose content the gesture did not select.const scale = Math.min(2, 4096 / Math.max(window.width, window.height))+const sources = await getSources({types: ['window'],thumbnailSize: { width: Math.ceil(window.width * scale), height: Math.ceil(window.height * scale) },@@ -72,7 +73,9 @@ export function createScreenshotCapture({ getSources, hasScreenPermission }: Capreturn { ok: false, reason: 'expired' }}- const source = sources.find(item => item.id.split(':')[0] === 'window' && item.id.split(':')[1] === String(window.windowId))+ const source = sources.find(+ item => item.id.split(':')[0] === 'window' && item.id.split(':')[1] === String(window.windowId)+ )if (!source || source.thumbnail.isEmpty()) {return { ok: false, reason: 'unavailable' }diff --git a/apps/desktop/electron/command-screenshot-monitor.test.ts b/apps/desktop/electron/command-screenshot-monitor.test.tsindex 2eb7d15eb85..44c8cc398e0 100644--- a/apps/desktop/electron/command-screenshot-monitor.test.ts+++ b/apps/desktop/electron/command-screenshot-monitor.test.ts@@ -12,7 +12,7 @@ import {type CommandScreenshotCapture,CommandScreenshotMonitor,type CommandScreenshotStatus,- resolveCommandScreenshotMonitorPath,+ resolveCommandScreenshotMonitorPath} from './command-screenshot-monitor'class FakeChild extends EventEmitter {@@ -27,14 +27,22 @@ test('launches the unpacked helper without prompting and delivers only validatedconst spawn = vi.fn((_command: string, _args: string[], _options: SpawnOptions) => child)const captures: CommandScreenshotCapture[] = []const statuses: CommandScreenshotStatus[] = []+const monitor = new CommandScreenshotMonitor({- platform: 'darwin', appPath: '/Applications/Hermes.app/Contents/Resources/app.asar', spawn,+ platform: 'darwin',+ appPath: '/Applications/Hermes.app/Contents/Resources/app.asar',+ spawn})- monitor.start(value => captures.push(value), value => statuses.push(value))++ monitor.start(+ value => captures.push(value),+ value => statuses.push(value)+ )assert.equal(spawn.mock.calls.length, 1)assert.deepEqual(spawn.mock.calls[0], ['/Applications/Hermes.app/Contents/Resources/app.asar.unpacked/dist/native/command-screenshot-monitor',- [], { stdio: ['pipe', 'pipe', 'ignore'], shell: false, detached: false, windowsHide: true },+ [],+ { stdio: ['pipe', 'pipe', 'ignore'], shell: false, detached: false, windowsHide: true }])child.stdout.write('{"type":"capture","windowId":2,"width":100,"height":200}\n')assert.deepEqual(captures, []) // No capture until readiness is established.@@ -55,21 +63,34 @@ test('launches the unpacked helper without prompting and delivers only validatedtest('bounds startup and termination, preserves permission failures, and isolates restarts', () => {vi.useFakeTimers()+try {const first = new FakeChild()const second = new FakeChild()const spawn = vi.fn().mockReturnValueOnce(first).mockReturnValueOnce(second)const statuses: CommandScreenshotStatus[] = []const captures: CommandScreenshotCapture[] = []+const monitor = new CommandScreenshotMonitor({- platform: 'darwin', spawn, startupTimeoutMs: 100, stopTimeoutMs: 50,+ platform: 'darwin',+ spawn,+ startupTimeoutMs: 100,+ stopTimeoutMs: 50})- monitor.start(value => captures.push(value), value => statuses.push(value), true)++ monitor.start(+ value => captures.push(value),+ value => statuses.push(value),+ true+ )assert.deepEqual(spawn.mock.calls[0][1], ['--request-permission'])first.stdout.write('{"type":"error","code":"permission-required"}\n')assert.deepEqual(statuses.at(-1), { type: 'error', code: 'permission-required' })assert.equal(first.stdin.writableEnded, true)- monitor.start(value => captures.push(value), value => statuses.push(value))+ monitor.start(+ value => captures.push(value),+ value => statuses.push(value)+ )first.stdout.write('{"type":"ready"}\n{"type":"capture","windowId":1,"width":1,"height":1}\n')assert.deepEqual(captures, [])vi.advanceTimersByTime(50)@@ -91,25 +112,34 @@ test('stopping from the starting callback cancels the child before it can becomeconst child = new FakeChild()const statuses: CommandScreenshotStatus[] = []const monitor = new CommandScreenshotMonitor({ platform: 'darwin', spawn: () => child })- monitor.start(() => assert.fail('stopped monitor delivered a capture'), status => {- statuses.push(status)- if (status.type === 'starting') {- monitor.stop()+ monitor.start(+ () => assert.fail('stopped monitor delivered a capture'),+ status => {+ statuses.push(status)++ if (status.type === 'starting') {+ monitor.stop()+ }}- })+ )assert.equal(child.kill.mock.calls[0]?.[0], 'SIGTERM')child.stdout.write('{"type":"ready"}\n')child.emit('close', 0, null)assert.deepEqual(statuses, [{ type: 'starting' }, { type: 'stopped' }])})-test.skipIf(process.platform !== 'darwin')('native state machine requires distinct keys, a clean chord and full release', () => {- const dir = mkdtempSync(resolve(tmpdir(), 'hermes-command-monitor-test-'))- try {- const fixture = resolve(dir, 'gesture.m')- const binary = resolve(dir, 'gesture')- // Compile the real state machine; no posted input events, screen pixels or TCC prompts.- writeFileSync(fixture, `+test.skipIf(process.platform !== 'darwin')(+ 'native state machine requires distinct keys, a clean chord and full release',+ () => {+ const dir = mkdtempSync(resolve(tmpdir(), 'hermes-command-monitor-test-'))++ try {+ const fixture = resolve(dir, 'gesture.m')+ const binary = resolve(dir, 'gesture')+ // Compile the real state machine; no posted input events, screen pixels or TCC prompts.+ writeFileSync(+ fixture,+ `#define COMMAND_SCREENSHOT_MONITOR_TEST 1#include "${resolve(import.meta.dirname, 'native/command-screenshot-monitor.m')}"#include <assert.h>@@ -188,60 +218,94 @@ int main(void) { @autoreleasepool {assert(CommandCaptureWindow(windows, 0) == nil);puts("native gesture assertions passed");} return 0; }-`)- execFileSync('xcrun', ['clang', '-fobjc-arc', '-fblocks', '-framework', 'Cocoa', '-framework', 'CoreGraphics', fixture, '-o', binary], { timeout: 30_000 })- assert.equal(execFileSync(binary, [], { encoding: 'utf8', timeout: 5_000 }).trim(), 'native gesture assertions passed')- } finally {- rmSync(dir, { recursive: true, force: true })- }-}, 40_000)+`+ )+ execFileSync(+ 'xcrun',+ ['clang', '-fobjc-arc', '-fblocks', '-framework', 'Cocoa', '-framework', 'CoreGraphics', fixture, '-o', binary],+ { timeout: 30_000 }+ )+ assert.equal(+ execFileSync(binary, [], { encoding: 'utf8', timeout: 5_000 }).trim(),+ 'native gesture assertions passed'+ )+ } finally {+ rmSync(dir, { recursive: true, force: true })+ }+ },+ 40_000+)-test.skipIf(process.platform !== 'darwin')('builds a universal helper with a read-only permission check and real controller lifecycle', async () => {- const dir = mkdtempSync(resolve(tmpdir(), 'hermes-command-monitor-build-'))- try {- const script = resolve(import.meta.dirname, '../scripts/build-command-screenshot-monitor.mjs')- execFileSync(process.execPath, [script, '--out-dir', resolve(dir, 'dist')], { timeout: 60_000 })- const binary = resolveCommandScreenshotMonitorPath(dir)- const architectures = execFileSync('xcrun', ['lipo', '-archs', binary], { encoding: 'utf8' }).trim().split(/\s+/).sort()- assert.deepEqual(architectures, ['arm64', 'x86_64'])- const result = spawnSync(binary, ['--check'], { encoding: 'utf8', timeout: 5_000 })- assert.equal(result.error, undefined)- assert.equal(result.stderr, '')- const permission = JSON.parse(result.stdout)- assert.deepEqual(permission, result.status === 0- ? { type: 'ready' } : { type: 'error', code: 'permission-required' })- assert.ok(result.status === 0 || result.status === 2)- const invalid = spawnSync(binary, ['--check', '--request-permission'], { encoding: 'utf8', timeout: 5_000 })- assert.equal(invalid.status, 64)- assert.deepEqual(JSON.parse(invalid.stdout), { type: 'error', code: 'unavailable' })- let closed: Promise<NodeJS.Signals | null> | undefined- const monitor = new CommandScreenshotMonitor({- appPath: dir,- spawn: (command, args, options) => {- const child = nodeSpawn(command, args, options)- closed = new Promise(settle => child.once('close', (_code, signal) => settle(signal)))- return child- },- })- const statuses: CommandScreenshotStatus[] = []- const terminal = await new Promise<CommandScreenshotStatus>((settle, reject) => {- const timeout = setTimeout(() => { monitor.stop(); reject(new Error('real monitor did not settle')) }, 10_000)- monitor.start(() => {}, status => {- statuses.push(status)- if (status.type === 'ready' || status.type === 'error') {- clearTimeout(timeout)- settle(status)+test.skipIf(process.platform !== 'darwin')(+ 'builds a universal helper with a read-only permission check and real controller lifecycle',+ async () => {+ const dir = mkdtempSync(resolve(tmpdir(), 'hermes-command-monitor-build-'))++ try {+ const script = resolve(import.meta.dirname, '../scripts/build-command-screenshot-monitor.mjs')+ execFileSync(process.execPath, [script, '--out-dir', resolve(dir, 'dist')], { timeout: 60_000 })+ const binary = resolveCommandScreenshotMonitorPath(dir)+ const architectures = execFileSync('xcrun', ['lipo', '-archs', binary], { encoding: 'utf8' })+ .trim()+ .split(/\s+/)+ .sort()+ assert.deepEqual(architectures, ['arm64', 'x86_64'])+ const result = spawnSync(binary, ['--check'], { encoding: 'utf8', timeout: 5_000 })+ assert.equal(result.error, undefined)+ assert.equal(result.stderr, '')+ const permission = JSON.parse(result.stdout)+ assert.deepEqual(+ permission,+ result.status === 0 ? { type: 'ready' } : { type: 'error', code: 'permission-required' }+ )+ assert.ok(result.status === 0 || result.status === 2)+ const invalid = spawnSync(binary, ['--check', '--request-permission'], { encoding: 'utf8', timeout: 5_000 })+ assert.equal(invalid.status, 64)+ assert.deepEqual(JSON.parse(invalid.stdout), { type: 'error', code: 'unavailable' })+ let closed: Promise<NodeJS.Signals | null> | undefined++ const monitor = new CommandScreenshotMonitor({+ appPath: dir,+ spawn: (command, args, options) => {+ const child = nodeSpawn(command, args, options)+ closed = new Promise(settle => child.once('close', (_code, signal) => settle(signal)))++ return child}})- })- assert.equal(statuses[0].type, 'starting')- if (permission.type === 'error') {- assert.deepEqual(terminal, permission)++ const statuses: CommandScreenshotStatus[] = []++ const terminal = await new Promise<CommandScreenshotStatus>((settle, reject) => {+ const timeout = setTimeout(() => {+ monitor.stop()+ reject(new Error('real monitor did not settle'))+ }, 10_000)+ monitor.start(+ () => {},+ status => {+ statuses.push(status)++ if (status.type === 'ready' || status.type === 'error') {+ clearTimeout(timeout)+ settle(status)+ }+ }+ )+ })++ assert.equal(statuses[0].type, 'starting')++ if (permission.type === 'error') {+ assert.deepEqual(terminal, permission)+ }++ monitor.stop()+ assert.ok(closed)+ assert.notEqual(await closed, 'SIGKILL') // the real helper exits without escalation+ } finally {+ rmSync(dir, { recursive: true, force: true })}- monitor.stop()- assert.ok(closed)- assert.notEqual(await closed, 'SIGKILL') // the real helper exits without escalation- } finally {- rmSync(dir, { recursive: true, force: true })- }-}, 75_000)+ },+ 75_000+)diff --git a/apps/desktop/electron/command-screenshot-monitor.ts b/apps/desktop/electron/command-screenshot-monitor.tsindex 2e7436d258d..a53e519f906 100644--- a/apps/desktop/electron/command-screenshot-monitor.ts+++ b/apps/desktop/electron/command-screenshot-monitor.ts@@ -11,8 +11,7 @@ export interface CommandScreenshotCapture extends ScreenshotWindow {}export type CommandScreenshotStatus =- | { type: 'starting' | 'ready' | 'stopped' }- | { type: 'error'; code: 'permission-required' | 'unavailable' }+ { type: 'starting' | 'ready' | 'stopped' } | { type: 'error'; code: 'permission-required' | 'unavailable' }interface MonitorChild extends EventEmitter {stdin: Writable | null@@ -29,39 +28,56 @@ interface MonitorOptions {}export function resolveCommandScreenshotMonitorPath(- appPath = resolve(dirname(fileURLToPath(import.meta.url)), '..'),+ appPath = resolve(dirname(fileURLToPath(import.meta.url)), '..')): string {// Executables cannot run inside ASAR. dist/** is already explicitly unpacked.- return resolve(appPath, 'dist/native/command-screenshot-monitor')- .replace(/\.asar(?=[/\\])/g, '.asar.unpacked')+ return resolve(appPath, 'dist/native/command-screenshot-monitor').replace(/\.asar(?=[/\\])/g, '.asar.unpacked')}function parseMessage(line: string): CommandScreenshotCapture | CommandScreenshotStatus | null {let value: unknown+try {value = JSON.parse(line)} catch {return null}+if (!value || typeof value !== 'object') {return null}+const message = value as Record<string, unknown>+if (message.type === 'ready') {return { type: 'ready' }}+if (message.type === 'error' && (message.code === 'permission-required' || message.code === 'unavailable')) {return { type: 'error', code: message.code }}+if (message.type !== 'capture') {return null}+const { windowId, width, height } = message- if (typeof windowId !== 'number' || !Number.isInteger(windowId) || windowId <= 0 || windowId > 0xffffffff- || typeof width !== 'number' || !Number.isFinite(width) || width <= 0- || typeof height !== 'number' || !Number.isFinite(height) || height <= 0) {++ if (+ typeof windowId !== 'number' ||+ !Number.isInteger(windowId) ||+ windowId <= 0 ||+ windowId > 0xffffffff ||+ typeof width !== 'number' ||+ !Number.isFinite(width) ||+ width <= 0 ||+ typeof height !== 'number' ||+ !Number.isFinite(height) ||+ height <= 0+ ) {return null}+return { type: 'capture', windowId, width, height }}@@ -75,41 +91,53 @@ export class CommandScreenshotMonitor {start(onCapture: (capture: CommandScreenshotCapture) => void,onStatus: (status: CommandScreenshotStatus) => void,- requestPermission = false,+ requestPermission = false): void {this.stop()+if ((this.options.platform ?? process.platform) !== 'darwin') {onStatus({ type: 'error', code: 'unavailable' })+return}+let child: MonitorChild+try {- child = (this.options.spawn ?? nodeSpawn)(resolveCommandScreenshotMonitorPath(this.options.appPath),+ child = (this.options.spawn ?? nodeSpawn)(+ resolveCommandScreenshotMonitorPath(this.options.appPath),requestPermission ? ['--request-permission'] : [],- { stdio: ['pipe', 'pipe', 'ignore'], shell: false, detached: false, windowsHide: true })+ { stdio: ['pipe', 'pipe', 'ignore'], shell: false, detached: false, windowsHide: true }+ )} catch {onStatus({ type: 'error', code: 'unavailable' })+return}+let ready = falselet active = truelet pending = ''let killTimer: ReturnType<typeof setTimeout> | undefinedconst startupTimer = setTimeout(() => fail(), this.options.startupTimeoutMs ?? (requestPermission ? 60_000 : 5_000))startupTimer.unref()+const dispose = () => {active = falsepending = ''clearTimeout(startupTimer)child.stdout?.removeListener('data', onData)+if (this.cleanup === stop) {this.cleanup = undefined}}+const terminate = (status: CommandScreenshotStatus) => {if (!active) {return}+dispose()child.stdin?.end() // EOF also stops the helper if the parent exits unexpectedly.child.kill('SIGTERM')@@ -117,34 +145,47 @@ export class CommandScreenshotMonitor {killTimer.unref()onStatus(status)}+const fail = () => terminate({ type: 'error', code: 'unavailable' })+const onData = (chunk: Buffer | string) => {if (!active) {return}+if (chunk.length > 65_536) {fail()+return}+pending += chunk.toString()const lines = pending.split('\n')pending = lines.pop() ?? ''+if (pending.length > 4_096) {fail()+return}+for (const line of lines) {if (!active) {break}+if (line.length > 4_096) {fail()+break}+const message = parseMessage(line)+if (!message) {continue}+if (message.type === 'capture') {if (ready) {onCapture(message)@@ -158,6 +199,7 @@ export class CommandScreenshotMonitor {}}}+const onClose = () => {const unexpected = activedispose()@@ -166,10 +208,12 @@ export class CommandScreenshotMonitor {child.removeListener('error', fail)child.stdin?.removeListener('error', fail)child.stdout?.removeListener('error', fail)+if (unexpected) {onStatus({ type: 'error', code: 'unavailable' })}}+const stop = () => terminate({ type: 'stopped' })this.cleanup = stopchild.stdout?.on('data', onData)@@ -178,6 +222,7 @@ export class CommandScreenshotMonitor {child.once('close', onClose)child.on('error', fail)onStatus({ type: 'starting' })+if (!child.stdout || !child.stdin) {fail()}diff --git a/apps/desktop/electron/command-screenshot-types.ts b/apps/desktop/electron/command-screenshot-types.tsindex fbce4224d58..dc862b4e36e 100644--- a/apps/desktop/electron/command-screenshot-types.ts+++ b/apps/desktop/electron/command-screenshot-types.ts@@ -10,8 +10,7 @@ export interface ScreenshotWindow {}export type ScreenshotResult =- | { ok: true; png: Uint8Array }- | { ok: false; reason: 'expired' | 'screen-permission' | 'unavailable' }+ { ok: true; png: Uint8Array } | { ok: false; reason: 'expired' | 'screen-permission' | 'unavailable' }export interface ScreenshotApi {getSettings(): Promise<ScreenshotStatus>diff --git a/apps/desktop/electron/command-screenshot.test.ts b/apps/desktop/electron/command-screenshot.test.tsindex 06245a2348d..85bd1a6bba0 100644--- a/apps/desktop/electron/command-screenshot.test.ts+++ b/apps/desktop/electron/command-screenshot.test.ts@@ -6,8 +6,19 @@ import path from 'node:path'import { afterEach, describe, expect, it, vi } from 'vitest'const native = vi.hoisted(() => ({ start: vi.fn(), stop: vi.fn() }))-const electron = vi.hoisted(() => ({ handlers: new Map(), windows: [] as any[], focused: null as any, screenPermission: 'granted', directory: '' }))-vi.mock('./command-screenshot-monitor', () => ({ CommandScreenshotMonitor: class { start = native.start; stop = native.stop } }))+const electron = vi.hoisted(() => ({+ handlers: new Map(),+ windows: [] as any[],+ focused: null as any,+ screenPermission: 'granted',+ directory: ''+}))+vi.mock('./command-screenshot-monitor', () => ({+ CommandScreenshotMonitor: class {+ start = native.start+ stop = native.stop+ }+}))vi.mock('electron', async () => {const { EventEmitter } = await import('node:events')const ipcMain = new EventEmitter() as any@@ -22,7 +33,11 @@ vi.mock('electron', async () => {getFocusedWindow: () => electron.focused,getAllWindows: () => electron.windows},- desktopCapturer: { getSources: vi.fn(async () => [{ id: 'window:42:0', thumbnail: { isEmpty: () => false, toPNG: () => new Uint8Array([1]) } }]) },+ desktopCapturer: {+ getSources: vi.fn(async () => [+ { id: 'window:42:0', thumbnail: { isEmpty: () => false, toPNG: () => new Uint8Array([1]) } }+ ])+ },systemPreferences: { getMediaAccessStatus: () => electron.screenPermission },shell: { openExternal: vi.fn() }}@@ -44,7 +59,13 @@ afterEach(async () => {function window(id: number, url = 'http://127.0.0.1:5174/') {const frame = { url }- const wc = Object.assign(new EventEmitter(), { id, mainFrame: frame, getURL: () => url, isDestroyed: () => false, send: vi.fn() })+ const wc = Object.assign(new EventEmitter(), {+ id,+ mainFrame: frame,+ getURL: () => url,+ isDestroyed: () => false,+ send: vi.fn()+ })const win = { webContents: wc, isDestroyed: () => false }electron.windows.push(win)@@ -56,7 +77,8 @@ async function setup() {cleanups.push(installCommandScreenshot({ rendererUrl: 'http://127.0.0.1:5174/' }))}-const call = (channel: string, event: unknown, ...args: unknown[]) => electron.handlers.get(`hermes:screenshot:${channel}`)(event, ...args)+const call = (channel: string, event: unknown, ...args: unknown[]) =>+ electron.handlers.get(`hermes:screenshot:${channel}`)(event, ...args)describe.skipIf(process.platform !== 'darwin')('Command screenshot native bridge', () => {it('persists opt-in, routes to the last focused subscribed window while backgrounded, and revokes on disable', async () => {@@ -71,7 +93,9 @@ describe.skipIf(process.platform !== 'darwin')('Command screenshot native bridgeapp.emit('browser-window-focus', {}, second.win)electron.focused = nullawait call('settings:set', first.event, true)- expect(JSON.parse(await readFile(path.join(electron.directory, 'screenshot.json'), 'utf8'))).toEqual({ enabled: true })+ expect(JSON.parse(await readFile(path.join(electron.directory, 'screenshot.json'), 'utf8'))).toEqual({+ enabled: true+ })const [capture, status] = native.start.mock.calls.at(-1)!status({ type: 'ready' })capture({ type: 'capture', windowId: 42, width: 600, height: 400 })@@ -82,10 +106,12 @@ describe.skipIf(process.platform !== 'darwin')('Command screenshot native bridgeawait call('settings:set', second.event, false)expect(await call('capture', second.event, requests[0]![1])).toEqual({ ok: false, reason: 'expired' })expect(native.stop).toHaveBeenCalled()+for (let i = 0; i < 3; i += 1) {ipcMain.emit('hermes:screenshot:subscribe', second.event, false)ipcMain.emit('hermes:screenshot:subscribe', second.event, true)}+expect(second.wc.listenerCount('destroyed')).toBe(1)ipcMain.emit('hermes:screenshot:subscribe', second.event, false)expect(second.wc.listenerCount('destroyed')).toBe(0)@@ -96,13 +122,17 @@ describe.skipIf(process.platform !== 'darwin')('Command screenshot native bridgeconst trusted = window(3)const foreign = window(4, 'https://example.org/')await expect(call('settings:set', foreign.event, true)).rejects.toThrow()- await expect(call('settings:set', { ...trusted.event, senderFrame: { url: 'https://example.org/' } }, true)).rejects.toThrow()+ await expect(+ call('settings:set', { ...trusted.event, senderFrame: { url: 'https://example.org/' } }, true)+ ).rejects.toThrow()expect(native.start).not.toHaveBeenCalled()electron.screenPermission = 'denied'await call('settings:set', trusted.event, true)native.start.mock.calls.at(-1)expect(desktopCapturer.getSources).toHaveBeenCalledWith({- types: ['window'], thumbnailSize: { width: 1, height: 1 }, fetchWindowIcons: false+ types: ['window'],+ thumbnailSize: { width: 1, height: 1 },+ fetchWindowIcons: false})expect(await call('settings:get', trusted.event)).toEqual({ enabled: true, state: 'screen-permission' })})diff --git a/apps/desktop/electron/command-screenshot.ts b/apps/desktop/electron/command-screenshot.tsindex 6a2088ff12b..782eaa50e41 100644--- a/apps/desktop/electron/command-screenshot.ts+++ b/apps/desktop/electron/command-screenshot.ts@@ -18,7 +18,10 @@ export function installCommandScreenshot({ rendererUrl }: { rendererUrl: stringconst expectedUrl = new URL(rendererUrl)const monitor = new CommandScreenshotMonitor({ appPath: app.getAppPath() })const hasScreenPermission = () => systemPreferences.getMediaAccessStatus('screen') === 'granted'- const capture = createScreenshotCapture({ hasScreenPermission, getSources: options => desktopCapturer.getSources(options) })+ const capture = createScreenshotCapture({+ hasScreenPermission,+ getSources: options => desktopCapturer.getSources(options)+ })const recipients = new Map<number, () => void>()let lastRecipient: BrowserWindow | null = nulllet enabled = false@@ -34,7 +37,11 @@ export function installCommandScreenshot({ rendererUrl }: { rendererUrl: stringconst status = (): ScreenshotStatus => ({enabled,- state: !enabled ? 'disabled' : monitorState === 'ready' && !hasScreenPermission() ? 'screen-permission' : monitorState+ state: !enabled+ ? 'disabled'+ : monitorState === 'ready' && !hasScreenPermission()+ ? 'screen-permission'+ : monitorState})const trustedWindow = (event: IpcMainEvent | IpcMainInvokeEvent): BrowserWindow | null => {@@ -47,7 +54,11 @@ export function installCommandScreenshot({ rendererUrl }: { rendererUrl: stringtry {const url = new URL(event.senderFrame.url)- return url.protocol === expectedUrl.protocol && url.host === expectedUrl.host && url.pathname === expectedUrl.pathname ? win : null+ return url.protocol === expectedUrl.protocol &&+ url.host === expectedUrl.host &&+ url.pathname === expectedUrl.pathname+ ? win+ : null} catch {return null}@@ -63,35 +74,44 @@ export function installCommandScreenshot({ rendererUrl }: { rendererUrl: stringconst start = (requestPermission = false) => {const current = ++generation- monitor.start(window => {- if (disposed || !enabled || current !== generation) {- return- }+ monitor.start(+ window => {+ if (disposed || !enabled || current !== generation) {+ return+ }- // Retain the last Hermes chat window when another application takes focus.- // Closing it cancels this destination; never silently pick another chat.- const focused = BrowserWindow.getFocusedWindow()- const recipient = focused && recipients.has(focused.webContents.id) ? focused : lastRecipient+ // Retain the last Hermes chat window when another application takes focus.+ // Closing it cancels this destination; never silently pick another chat.+ const focused = BrowserWindow.getFocusedWindow()+ const recipient = focused && recipients.has(focused.webContents.id) ? focused : lastRecipient- if (!recipient || recipient.isDestroyed() || !recipients.has(recipient.webContents.id)) {- return- }+ if (!recipient || recipient.isDestroyed() || !recipients.has(recipient.webContents.id)) {+ return+ }- const requestId = capture.request(recipient.webContents.id, window)+ const requestId = capture.request(recipient.webContents.id, window)- if (requestId) {- recipient.webContents.send('hermes:screenshot:request', requestId)- }- }, result => {- if (disposed || current !== generation) {- return- }+ if (requestId) {+ recipient.webContents.send('hermes:screenshot:request', requestId)+ }+ },+ result => {+ if (disposed || current !== generation) {+ return+ }- monitorState = result.type === 'error'- ? result.code === 'permission-required' ? 'input-permission' : 'unavailable'- : result.type === 'stopped' ? 'disabled' : result.type- publish()- }, requestPermission)+ monitorState =+ result.type === 'error'+ ? result.code === 'permission-required'+ ? 'input-permission'+ : 'unavailable'+ : result.type === 'stopped'+ ? 'disabled'+ : result.type+ publish()+ },+ requestPermission+ )}const onFocus = (_event: unknown, win: BrowserWindow) => {@@ -110,12 +130,15 @@ export function installCommandScreenshot({ rendererUrl }: { rendererUrl: stringif (subscribed === true) {if (!recipients.has(event.sender.id)) {const id = event.sender.id+const onDestroyed = () => {recipients.delete(id)+if (lastRecipient === win) {lastRecipient = null}}+event.sender.once('destroyed', onDestroyed)recipients.set(id, () => event.sender.removeListener('destroyed', onDestroyed))}@@ -126,6 +149,7 @@ export function installCommandScreenshot({ rendererUrl }: { rendererUrl: string} else if (subscribed === false) {recipients.get(event.sender.id)?.()recipients.delete(event.sender.id)+if (lastRecipient === win) {lastRecipient = null}@@ -133,6 +157,7 @@ export function installCommandScreenshot({ rendererUrl }: { rendererUrl: string}const channels: string[] = []+const handle = (name: string, callback: (event: IpcMainInvokeEvent, value: unknown) => unknown) => {const channel = `hermes:screenshot:${name}`channels.push(channel)@@ -162,11 +187,14 @@ export function installCommandScreenshot({ rendererUrl }: { rendererUrl: stringif (enabled) {start(true)+if (!hasScreenPermission()) {// Zero-size thumbnails skip content capture and may never request TCC// consent. Request the smallest thumbnail only on explicit opt-in;// discard it rather than retaining or attaching permission-probe pixels.- await desktopCapturer.getSources({ types: ['window'], thumbnailSize: { width: 1, height: 1 }, fetchWindowIcons: false }).catch(() => undefined)+ await desktopCapturer+ .getSources({ types: ['window'], thumbnailSize: { width: 1, height: 1 }, fetchWindowIcons: false })+ .catch(() => undefined)}} else {monitorState = 'disabled'@@ -178,6 +206,7 @@ export function installCommandScreenshot({ rendererUrl }: { rendererUrl: string})handle('capture', async (event, requestId) => {const result = await capture.take(event.sender.id, requestId)+if (result.ok === false && result.reason === 'screen-permission') {publish()}@@ -186,9 +215,11 @@ export function installCommandScreenshot({ rendererUrl }: { rendererUrl: string})handle('permission', async (_event, kind) => {const pane = kind === 'input' ? 'Privacy_ListenEvent' : kind === 'screen' ? 'Privacy_ScreenCapture' : null+if (!pane) {throw new Error('Unknown screenshot permission')}+await shell.openExternal(`x-apple.systempreferences:com.apple.preference.security?${pane}`)})ipcMain.on('hermes:screenshot:subscribe', onSubscribe)@@ -208,6 +239,7 @@ export function installCommandScreenshot({ rendererUrl }: { rendererUrl: string}app.once('will-quit', dispose)+if (enabled) {start()}diff --git a/apps/desktop/electron/connection-caches.ts b/apps/desktop/electron/connection-caches.tsindex 4f0a1b295b4..ac02b2aa49a 100644--- a/apps/desktop/electron/connection-caches.ts+++ b/apps/desktop/electron/connection-caches.ts@@ -24,11 +24,7 @@ export const sshInventoryAttemptedAt = new Map<string, number>()*/export const connectionInstallIds = new Map<string, { id?: string; ts: number }>()-const CONNECTION_SCOPED_CACHES: Map<string, unknown>[] = [- sshRosterCache,- sshInventoryAttemptedAt,- connectionInstallIds-]+const CONNECTION_SCOPED_CACHES: Map<string, unknown>[] = [sshRosterCache, sshInventoryAttemptedAt, connectionInstallIds]/*** Forget everything cached about a connection id. Call whenever that id stops naming the machinediff --git a/apps/desktop/electron/desktop-plugin-remove.test.ts b/apps/desktop/electron/desktop-plugin-remove.test.tsindex 8ee979e6898..f738dc8e1b0 100644--- a/apps/desktop/electron/desktop-plugin-remove.test.ts+++ b/apps/desktop/electron/desktop-plugin-remove.test.ts@@ -48,7 +48,15 @@ describe('removeDesktopPlugin', () => {write(path.join(home, 'config.yaml'), 'model: x')write(path.join(root, 'hello', 'plugin.js'), 'export default {}')- for (const name of ['../config.yaml', '..', '.', '', 'hello/plugin.js', `..${path.sep}config.yaml`, path.join(root, 'hello')]) {+ for (const name of [+ '../config.yaml',+ '..',+ '.',+ '',+ 'hello/plugin.js',+ `..${path.sep}config.yaml`,+ path.join(root, 'hello')+ ]) {const result = await removeDesktopPlugin(root, name)expect(result.ok, name).toBe(false)diff --git a/apps/desktop/electron/desktop-plugins-root.test.ts b/apps/desktop/electron/desktop-plugins-root.test.tsindex c137b131b6f..9bb08a2a1af 100644--- a/apps/desktop/electron/desktop-plugins-root.test.ts+++ b/apps/desktop/electron/desktop-plugins-root.test.ts@@ -202,6 +202,7 @@ describe('reconcileUnifiedDesktopHalves', () => {const appRoot = path.join(home, 'desktop-plugins')const packageDir = path.join(home, 'plugins', 'media')write(path.join(packageDir, 'desktop', 'plugin.js'), 'package half')+// Simulate a copy that dies partway: the destination already holds a marker-less// partial tree when the failure surfaces. A direct copy into the final target would// leave that half-tree behind; the staged copy must never let it reach `<appRoot>/media`.diff --git a/apps/desktop/electron/desktop-profile.test.ts b/apps/desktop/electron/desktop-profile.test.tsindex 4d6603eb279..9cb528e61d5 100644--- a/apps/desktop/electron/desktop-profile.test.ts+++ b/apps/desktop/electron/desktop-profile.test.ts@@ -17,6 +17,7 @@ test('failed authoritative writes leave the previous default and listeners untouconst root = fs.mkdtempSync(path.join(os.tmpdir(), 'desktop-profile-write-'))const target = path.join(root, 'active-profile.json')const changes: unknown[] = []+const preferences = createDesktopProfilePreferences(target, {onDefaultChanged: route => changes.push(route),validateRoute: route => {@@ -29,6 +30,7 @@ test('failed authoritative writes leave the previous default and listeners untoutry {const original = { connectionId: null, profile: 'work' }preferences.setDefault(original)+for (const invalid of [null,{},@@ -38,6 +40,7 @@ test('failed authoritative writes leave the previous default and listeners untouassert.throws(() => preferences.setDefault(invalid))assert.deepEqual(preferences.getDefault(), original)}+fs.mkdirSync(`${target}.tmp`)assert.throws(() => preferences.setDefault({ connectionId: 'remote', profile: 'personal' }))assert.deepEqual(preferences.getDefault(), original)@@ -96,6 +99,7 @@ test('boot and reconnect retain the window route rather than a later global defaprofile: route.profile})}+assert.deepEqual(resolveDesktopConnectionRequest('other', routeA, 'last-used'), {connectionId: null,profile: 'other'diff --git a/apps/desktop/electron/github-api-auth.test.ts b/apps/desktop/electron/github-api-auth.test.tsindex 506b6cb4f35..50987721754 100644--- a/apps/desktop/electron/github-api-auth.test.ts+++ b/apps/desktop/electron/github-api-auth.test.ts@@ -87,7 +87,11 @@ test('gh is found in the GUI-safe install locations a minimal launch PATH omits'assert.equal(macos, brewGh)const winGh = 'C:\\Program Files\\GitHub CLI\\gh.exe'- const windows = findGhCli({ Path: 'C:\\Windows\\System32', ProgramFiles: 'C:\\Program Files' }, 'win32', p => p === winGh)+ const windows = findGhCli(+ { Path: 'C:\\Windows\\System32', ProgramFiles: 'C:\\Program Files' },+ 'win32',+ p => p === winGh+ )assert.equal(windows, winGh)@@ -96,7 +100,10 @@ test('gh is found in the GUI-safe install locations a minimal launch PATH omits'const both = findGhCli({ PATH: '/usr/local/bin' }, 'darwin', p => p === pathGh || p === brewGh)assert.equal(both, pathGh)- assert.equal(findGhCli({ PATH: '/usr/bin' }, 'linux', () => false), null)+ assert.equal(+ findGhCli({ PATH: '/usr/bin' }, 'linux', () => false),+ null+ )})test('gh rung: argv-only spawn, stdin closed, bounded, cached for the process, and after the env rung', async () => {@@ -136,18 +143,27 @@ test('gh rung: argv-only spawn, stdin closed, bounded, cached for the process, aforgetGhCliToken()const loggedOut = fakeExecFile({ error: Object.assign(new Error('exit 1'), { code: 1 }), stdout: '' })- assert.equal(await resolveGitHubCredential({ env, platform: 'darwin', exists, execFileFn: loggedOut.execFileFn }), null)+ assert.equal(+ await resolveGitHubCredential({ env, platform: 'darwin', exists, execFileFn: loggedOut.execFileFn }),+ null+ )// "none" is not cached: a `gh auth login` after launch is picked up by the next check without a restart.const nowLogged = fakeExecFile({ stdout: 'gho_after_login\n' })- assert.deepEqual(await resolveGitHubCredential({ env, platform: 'darwin', exists, execFileFn: nowLogged.execFileFn }), {- token: 'gho_after_login',- source: 'gh-cli'- })+ assert.deepEqual(+ await resolveGitHubCredential({ env, platform: 'darwin', exists, execFileFn: nowLogged.execFileFn }),+ {+ token: 'gho_after_login',+ source: 'gh-cli'+ }+ )forgetGhCliToken()- assert.equal(await resolveGitHubCredential({ env, platform: 'darwin', exists: () => false, execFileFn: logged.execFileFn }), null)+ assert.equal(+ await resolveGitHubCredential({ env, platform: 'darwin', exists: () => false, execFileFn: logged.execFileFn }),+ null+ )assert.equal(logged.calls.length, 1)})diff --git a/apps/desktop/electron/github-api-auth.ts b/apps/desktop/electron/github-api-auth.tsindex ab3eaa60f6c..09884e605df 100644--- a/apps/desktop/electron/github-api-auth.ts+++ b/apps/desktop/electron/github-api-auth.ts@@ -208,7 +208,9 @@ export function githubApiHeaders(base: Record<string, string>, token?: string |* before credentials were wired in. Anonymous 401s and every other status are* not the token's fault and are surfaced as-is.*/-export function githubTokenRejected(error: { statusCode?: number; authenticated?: boolean } | null | undefined): boolean {+export function githubTokenRejected(+ error: { statusCode?: number; authenticated?: boolean } | null | undefined+): boolean {return error?.statusCode === 401 && error?.authenticated === true}diff --git a/apps/desktop/electron/hardening.test.ts b/apps/desktop/electron/hardening.test.tsindex 78dbeb13c5c..6ba1ebc40a0 100644--- a/apps/desktop/electron/hardening.test.ts+++ b/apps/desktop/electron/hardening.test.ts@@ -1155,7 +1155,10 @@ test('homeRelativeAttachmentCandidates normalizes Windows backslashes before joi})test('homeRelativeAttachmentCandidates returns nothing for an absolute path', () => {- assert.deepEqual(homeRelativeAttachmentCandidates('/already/absolute/foo.xlsx', '/Users/alice', '/Users/alice/.hermes'), [])+ assert.deepEqual(+ homeRelativeAttachmentCandidates('/already/absolute/foo.xlsx', '/Users/alice', '/Users/alice/.hermes'),+ []+ )})test('homeRelativeAttachmentCandidates returns nothing for a file: URL', () => {diff --git a/apps/desktop/electron/link-title-wall.test.ts b/apps/desktop/electron/link-title-wall.test.tsindex abfd3217567..0b8d31f0ace 100644--- a/apps/desktop/electron/link-title-wall.test.ts+++ b/apps/desktop/electron/link-title-wall.test.ts@@ -29,10 +29,34 @@ test('a proven sign-in wall never escalates to the hidden renderer', async () =>// The three measured shapes of the wall are all proven from the curl tier:// arrival URL (Apps Script → www.google.com/a/<domain>/ServiceLogin), sign-in// title (Drive → accounts.google.com), and markup (a Doc that stays on its host).- assert.equal(isAuthWall({ body: '', effectiveUrl: 'https://www.google.com/a/x.org/ServiceLogin?c=1', title: '' }), true)- assert.equal(isAuthWall({ body: '', effectiveUrl: 'https://accounts.google.com/v3/signin/identifier', title: 'Google Drive: Sign-in' }), true)- assert.equal(isAuthWall({ body: '<a href="https://accounts.google.com/ServiceLogin">', effectiveUrl: 'https://docs.google.com/document/d/1/edit', title: '' }), true)- assert.equal(isAuthWall({ body: '<title>Q3 plan</title>', effectiveUrl: 'https://docs.google.com/document/d/1/pub', title: 'Q3 plan' }), false)+ assert.equal(+ isAuthWall({ body: '', effectiveUrl: 'https://www.google.com/a/x.org/ServiceLogin?c=1', title: '' }),+ true+ )+ assert.equal(+ isAuthWall({+ body: '',+ effectiveUrl: 'https://accounts.google.com/v3/signin/identifier',+ title: 'Google Drive: Sign-in'+ }),+ true+ )+ assert.equal(+ isAuthWall({+ body: '<a href="https://accounts.google.com/ServiceLogin">',+ effectiveUrl: 'https://docs.google.com/document/d/1/edit',+ title: ''+ }),+ true+ )+ assert.equal(+ isAuthWall({+ body: '<title>Q3 plan</title>',+ effectiveUrl: 'https://docs.google.com/document/d/1/pub',+ title: 'Q3 plan'+ }),+ false+ )})test('an ordinary title-less page still escalates to the hidden renderer', async () => {diff --git a/apps/desktop/electron/linux-crash-diagnostics.test.ts b/apps/desktop/electron/linux-crash-diagnostics.test.tsindex 8a31f1d6c94..50b518da1f4 100644--- a/apps/desktop/electron/linux-crash-diagnostics.test.ts+++ b/apps/desktop/electron/linux-crash-diagnostics.test.ts@@ -3,11 +3,7 @@ import path from 'node:path'import { test } from 'vitest'-import {- CHROMIUM_LOG_FILENAME,- enableLinuxCrashDiagnostics,- linuxCrashDiagnostics-} from './linux-crash-diagnostics'+import { CHROMIUM_LOG_FILENAME, enableLinuxCrashDiagnostics, linuxCrashDiagnostics } from './linux-crash-diagnostics'// Regression for #100573: the Linux shell died with SIGTRAP at Chromium's// shared fatal-handler address and no launcher kept the FATAL message. Thediff --git a/apps/desktop/electron/log-rotation.test.ts b/apps/desktop/electron/log-rotation.test.tsindex 948a06e842d..985f5f47217 100644--- a/apps/desktop/electron/log-rotation.test.ts+++ b/apps/desktop/electron/log-rotation.test.ts@@ -58,10 +58,7 @@ test('an under-cap or absent active log is left alone', () => {const touched: string[] = []const truncate = (f: string) => touched.push(f)- assert.equal(- reclaimActiveLogIfOversized('/logs/x.log', { size: () => LOG_MAX_BYTES - 1, truncate }),- false- )+ assert.equal(reclaimActiveLogIfOversized('/logs/x.log', { size: () => LOG_MAX_BYTES - 1, truncate }), false)assert.equal(reclaimActiveLogIfOversized('/logs/x.log', { size: () => null, truncate }), false)assert.deepEqual(touched, [])})diff --git a/apps/desktop/electron/main.ts b/apps/desktop/electron/main.tsindex 0ba2a1f9567..037e7deb569 100644--- a/apps/desktop/electron/main.ts+++ b/apps/desktop/electron/main.ts@@ -255,7 +255,12 @@ import {tightenSecretFileMode,writeSecretFileAtomic} from './hardening'-import { type AttachedBackend, attachOrReserveSpawn, spawnLedgerPath, type SpawnReservation } from './host-backend-attach'+import {+ type AttachedBackend,+ attachOrReserveSpawn,+ spawnLedgerPath,+ type SpawnReservation+} from './host-backend-attach'import { requestHudClose } from './hud-close'import { cursorPointInWindow } from './hud-cursor'import { startHudGameOverlayWatch } from './hud-game-overlay'@@ -269,11 +274,7 @@ import { resolveHudWindowing } from './hud-windowing'import { createIntroRevealWindowController } from './intro-reveal-window'import { isAuthWall, resolveLinkTitle } from './link-title-wall'import { createLinkTitleWindow, guardLinkTitleSession, readLinkTitleWindowTitle } from './link-title-window'-import {- CHROMIUM_LOG_FILENAME,- enableLinuxCrashDiagnostics,- linuxCrashDiagnostics-} from './linux-crash-diagnostics'+import { CHROMIUM_LOG_FILENAME, enableLinuxCrashDiagnostics, linuxCrashDiagnostics } from './linux-crash-diagnostics'import { notifyLauncherWindowRevealed } from './linux-launcher-ready'import { createLocalBackendLifecycle, waitForTeardown } from './local-backend-lifecycle'import { ACTIVE_LOG_POLL_MS, planLogRotation, reclaimActiveLogIfOversized } from './log-rotation'@@ -912,7 +913,9 @@ const HERMES_HOME = resolveHermesHome()app.commandLine.appendSwitch(planned.name, planned.value)}- console.log(`[hermes] desktop launch switch from config.yaml: --${planned.name}${planned.value === undefined ? '' : `=${planned.value}`}`)+ console.log(+ `[hermes] desktop launch switch from config.yaml: --${planned.name}${planned.value === undefined ? '' : `=${planned.value}`}`+ )}}@@ -993,16 +996,12 @@ const CRASH_DIAGNOSTICS_LOGS_DIR = path.dirname(DESKTOP_LOG_PATH)const CRASH_DIAGNOSTICS = linuxCrashDiagnostics(CRASH_DIAGNOSTICS_LOGS_DIR)const CHROMIUM_LOG_PATH = path.join(CRASH_DIAGNOSTICS_LOGS_DIR, CHROMIUM_LOG_FILENAME)-enableLinuxCrashDiagnostics(- CRASH_DIAGNOSTICS,- CRASH_DIAGNOSTICS_LOGS_DIR,- {- ensureLogsDir: dir => fs.mkdirSync(dir, { recursive: true }),- reclaimChromiumLog: file => rotateLogIfNeededSync(file),- appendSwitch: (name, value) => app.commandLine.appendSwitch(name, value),- startCrashReporter: options => crashReporter.start(options)- }-)+enableLinuxCrashDiagnostics(CRASH_DIAGNOSTICS, CRASH_DIAGNOSTICS_LOGS_DIR, {+ ensureLogsDir: dir => fs.mkdirSync(dir, { recursive: true }),+ reclaimChromiumLog: file => rotateLogIfNeededSync(file),+ appendSwitch: (name, value) => app.commandLine.appendSwitch(name, value),+ startCrashReporter: options => crashReporter.start(options)+})const BOOT_FAKE_MODE = process.env.HERMES_DESKTOP_BOOT_FAKE === '1'const BOOT_FAKE_ERROR = process.env.HERMES_DESKTOP_BOOT_FAKE_ERROR || ''@@ -1278,7 +1277,8 @@ function getTitleBarOverlayOptions() {darwinMajor: DARWIN_MAJOR,titlebarHeight: TITLEBAR_HEIGHT,color: TITLEBAR_OVERLAY_COLOR,- foreground: rendererTitleBarTheme && isHexColor(rendererTitleBarTheme.foreground) ? rendererTitleBarTheme.foreground : null,+ foreground:+ rendererTitleBarTheme && isHexColor(rendererTitleBarTheme.foreground) ? rendererTitleBarTheme.foreground : null,dark: nativeTheme.shouldUseDarkColors})}@@ -3665,9 +3665,7 @@ function repairMacUpdaterHelper(updater) {function venvHermesShimPath(updateRoot) {const venvDir = resolveVenvDir(updateRoot)- return IS_WINDOWS- ? path.join(venvDir, 'Scripts', 'hermes.exe')- : path.join(venvDir, 'bin', 'hermes')+ return IS_WINDOWS ? path.join(venvDir, 'Scripts', 'hermes.exe') : path.join(venvDir, 'bin', 'hermes')}// Best-effort lock probe mirroring the Rust updater's is_locked(): a running@@ -4433,12 +4431,14 @@ async function applyUpdates(opts: { stopSafeBlockers?: boolean } = {}) {'-RelaunchExe',process.execPath]+// Same remote-ownership rule as the posix hand-off (#117529): a// remote-served Desktop must not let the update (re)start a local// messaging gateway that competes with the remote host's polling.if (globalRemoteActive()) {wrappedArgs.push('-NoGateway')}+const wrapped = wrapHandoffForDetachedConsole(scriptHandoff, wrappedArgs)child = spawnUpdaterProcess(wrapped.command, wrapped.args, {@@ -4823,6 +4823,7 @@ async function applyUpdatesPosixHandoff(opts: any) {}const args = [...handoff.args, '--install-root', updateRoot, '--branch', branch, '--desktop-pid', String(process.pid)]+// A remote-served Desktop owns no local messaging gateway: `hermes update// --gateway` would (re)start one here anyway, and with the same channel// credentials as the remote host it becomes a competing long-poll consumer@@ -4830,6 +4831,7 @@ async function applyUpdatesPosixHandoff(opts: any) {if (globalRemoteActive()) {args.push('--no-gateway')}+const updateStartedAt = Math.floor(Date.now() / 1000)// Relaunch target: the running .app bundle on mac (script swaps the@@ -6278,13 +6280,12 @@ function fetchLinkTitle(rawUrl) {curl: () => fetchHtmlTitleWithCurl(url),renderer: () => fetchHtmlTitleWithRenderer(url),url- })- .then(clean => {- cacheTitle(key, clean)- titleInflight.delete(key)+ }).then(clean => {+ cacheTitle(key, clean)+ titleInflight.delete(key)- return clean- })+ return clean+ })titleInflight.set(key, pending)@@ -8674,14 +8675,15 @@ function resolvePortalBaseUrl() {return String(raw).trim().replace(/\/+$/, '')}-const { hasLivePortalSession, hasPortalAccessToken, renewPortalAccessSilently, openPortalLoginWindow } = createPortalSession({- isReady: () => app.isReady(),- getOauthSession,- resolvePortalBaseUrl,- warmOauthCookieStore,- createWindow: options => new BrowserWindow(options),- rememberLog-})+const { hasLivePortalSession, hasPortalAccessToken, renewPortalAccessSilently, openPortalLoginWindow } =+ createPortalSession({+ isReady: () => app.isReady(),+ getOauthSession,+ resolvePortalBaseUrl,+ warmOauthCookieStore,+ createWindow: options => new BrowserWindow(options),+ rememberLog+ })// Discover the hosted (Hermes Cloud) agents the signed-in user can see. Calls// the NAS trimmed-summary endpoint over the partition-bound net, so the portal@@ -8714,10 +8716,13 @@ async function discoverCloudAgents(org?: string) {const fetchAgents = () =>discoverWithTeamFallback(selectedOrg =>- fetchJsonViaOauthSession(`${portalBaseUrl}/api/agents${selectedOrg ? `?org=${encodeURIComponent(selectedOrg)}` : ''}`, {- method: 'GET',- timeoutMs: 15_000- }),+ fetchJsonViaOauthSession(+ `${portalBaseUrl}/api/agents${selectedOrg ? `?org=${encodeURIComponent(selectedOrg)}` : ''}`,+ {+ method: 'GET',+ timeoutMs: 15_000+ }+ ),org)@@ -12418,9 +12423,7 @@ function startPoolIdleReaper() {if (now - (entry.lastActiveAt || 0) > poolIdleMs()) {// Remote descriptors hold no child/slot. Local children require the// same admission authority as foreground and LRU reclamation.- const retiring = entry.process- ? poolRetirer.retireIdle(profile, poolIdleMs())- : stopPoolBackend(profile)+ const retiring = entry.process ? poolRetirer.retireIdle(profile, poolIdleMs()) : stopPoolBackend(profile)void retiring.catch(error => rememberLog(`Pool idle retirement failed: ${String(error)}`))}@@ -15346,7 +15349,10 @@ ipcMain.handle('hermes:connection:for', async (_event, payload) => {const id = String(connectionId || '').trim() || registry.primaryconst spawnPriority = spawnPriorityFrom(priority)- return connectDesktopProfileRoute({ connectionId: id, profile: String(profile ?? '').trim() || 'default' }, spawnPriority)+ return connectDesktopProfileRoute(+ { connectionId: id, profile: String(profile ?? '').trim() || 'default' },+ spawnPriority+ )})const windowConnectionRoutes = new WindowConnectionRouteRegistry()@@ -18702,8 +18708,7 @@ function heldQuitForActiveWork(event: Electron.Event): boolean {// A hidden aux window must never parent the quit prompt: the dialog would// be invisible and the held quit unanswerable (#116376 §E).- const parent =- BrowserWindow.getFocusedWindow() ?? BrowserWindow.getAllWindows().find(window => window.isVisible())+ const parent = BrowserWindow.getFocusedWindow() ?? BrowserWindow.getAllWindows().find(window => window.isVisible())if (!prompt || !parent || parent.isDestroyed()) {return falsediff --git a/apps/desktop/electron/notification-ipc.test.ts b/apps/desktop/electron/notification-ipc.test.tsindex 9d857244724..e72173704a7 100644--- a/apps/desktop/electron/notification-ipc.test.ts+++ b/apps/desktop/electron/notification-ipc.test.ts@@ -45,8 +45,15 @@ it('returns native clicks and approval actions to the emitting window, not the pconst source = windowStub()host.fromWebContents.mockReturnValue(source)const focusWindow = vi.fn()- registerNativeNotifications({ getMainWindow: () => primary as unknown as BrowserWindow, focusWindow, platform: 'darwin' })- const notify = host.handle.mock.calls[0][1] as (event: IpcMainInvokeEvent, payload: HermesNotification) => Promise<boolean>+ registerNativeNotifications({+ getMainWindow: () => primary as unknown as BrowserWindow,+ focusWindow,+ platform: 'darwin'+ })+ const notify = host.handle.mock.calls[0][1] as (+ event: IpcMainInvokeEvent,+ payload: HermesNotification+ ) => Promise<boolean>const payload = {kind: 'approval',@@ -85,8 +92,15 @@ it('delivers plugin callbacks to their source and falls back only for navigationconst source = windowStub()host.fromWebContents.mockReturnValue(source)const focusWindow = vi.fn()- registerNativeNotifications({ getMainWindow: () => primary as unknown as BrowserWindow, focusWindow, platform: 'darwin' })- const notify = host.handle.mock.calls[0][1] as (event: IpcMainInvokeEvent, payload: HermesNotification) => Promise<boolean>+ registerNativeNotifications({+ getMainWindow: () => primary as unknown as BrowserWindow,+ focusWindow,+ platform: 'darwin'+ })+ const notify = host.handle.mock.calls[0][1] as (+ event: IpcMainInvokeEvent,+ payload: HermesNotification+ ) => Promise<boolean>await notify({ sender: source.webContents } as unknown as IpcMainInvokeEvent, {kind: 'plugin',notifyId: 'source-callback',diff --git a/apps/desktop/electron/notification-ipc.ts b/apps/desktop/electron/notification-ipc.tsindex ae5ce080284..2c784ec2a2e 100644--- a/apps/desktop/electron/notification-ipc.ts+++ b/apps/desktop/electron/notification-ipc.ts@@ -34,6 +34,7 @@ export function registerNativeNotifications({// Peer renderers share one OS notification for the same event.const key = `${payload?.kind ?? ''}:${payload?.sessionId ?? payload?.tag ?? ''}`+if (isDuplicateNotification(key)) {return deliveries.get(key) ?? false}diff --git a/apps/desktop/electron/notification-linux.test.ts b/apps/desktop/electron/notification-linux.test.tsindex 6ebdcb93d16..381d5756c06 100644--- a/apps/desktop/electron/notification-linux.test.ts+++ b/apps/desktop/electron/notification-linux.test.ts@@ -32,6 +32,7 @@ import { registerNativeNotifications } from './notification-ipc'function setup(alreadyRunning = false) {host.handle.mockClear()+const connection = Object.assign(new EventEmitter(), {stream: { destroy: vi.fn(() => connection.emit('close')), unref: vi.fn() }})@@ -44,6 +45,7 @@ function setup(alreadyRunning = false) {const calls: Message[] = []const failures = new Map<string, string>()+const replaceOwner = () => {const old = ownerowner = ':1.21'@@ -70,12 +72,16 @@ function setup(alreadyRunning = false) {// is answered with an error, not routed to the new owner.if (message.destination?.startsWith(':') && message.destination !== owner) {reject(Object.assign(new Error('no such name'), { dbusName: 'org.freedesktop.DBus.Error.NameHasNoOwner' }))+return}+if (failures.has(message.member ?? '')) {reject(Object.assign(new Error('fixture failure'), { dbusName: failures.get(message.member ?? '') }))+return}+if (message.member === stalled) {const fail = () => reject(new Error('service unavailable'))@@ -90,15 +96,19 @@ function setup(alreadyRunning = false) {if (message.member === 'GetNameOwner' && !activated) {reject(Object.assign(new Error('no owner'), { dbusName: 'org.freedesktop.DBus.Error.NameHasNoOwner' }))+return}+if (message.member === 'StartServiceByName') {if (alreadyRunning) {reject(Object.assign(new Error('no activation file'), { dbusName: 'org.freedesktop.DBus.Error.ServiceUnknown' }))+return}+activated = true}@@ -116,7 +126,9 @@ function setup(alreadyRunning = false) {if (callback) {callback(null, value)}+resolve(value)+if (message.member === 'GetNameOwner' && raceOwnerReply) {raceOwnerReply = falsereplaceOwner() // Reply followed by owner replacement in the same read batch.@@ -135,6 +147,7 @@ function setup(alreadyRunning = false) {const source = { isDestroyed: vi.fn(() => false), webContents: { send: vi.fn() } }host.fromWebContents.mockReturnValue(source)const focusWindow = vi.fn()+const { dispose } = registerNativeNotifications({getMainWindow: () => primary as unknown as BrowserWindow,focusWindow,@@ -192,155 +205,146 @@ afterEach(() => {vi.unstubAllEnvs()})-it(- 'bounds failed delivery without dropping older callbacks, and retries only on a later request',- async () => {- const unavailable = setup()- unavailable.fail('StartServiceByName', 'org.freedesktop.DBus.Error.ServiceUnknown')- expect(await unavailable.notify({ tag: 'test' })).toBe(false)- expect(await unavailable.notify({ tag: 'test' })).toBe(false)- expect(unavailable.calls.filter(call => call.member === 'StartServiceByName')).toHaveLength(1)- unavailable.connection.emit('close')-- // libnotify's getenv guard disables actions even for an empty value.- vi.stubEnv('ELECTRON_USE_UBUNTU_NOTIFIER', '')- const unity = setup(true)- expect(await unity.notify({ tag: 'unity', actions: [{ id: 'ok', text: 'OK' }] })).toBe(true)- expect(unity.calls.find(call => call.member === 'Notify')?.body?.[5]).toEqual([])- unity.connection.emit('close')- vi.stubEnv('ELECTRON_USE_UBUNTU_NOTIFIER', undefined)-- for (const method of ['Hello', 'AddMatch', 'StartServiceByName', 'GetNameOwner', 'GetCapabilities']) {- const startup = setup()- startup.stall(method)- const attempt = startup.notify({ tag: method })- await vi.advanceTimersByTimeAsync(6000)- expect(await attempt).toBe(false)- await vi.advanceTimersByTimeAsync(11000)- startup.stall('')- expect(await startup.notify({ tag: 'startup-recovered' })).toBe(true)- startup.connection.emit('close')- }+it('bounds failed delivery without dropping older callbacks, and retries only on a later request', async () => {+ const unavailable = setup()+ unavailable.fail('StartServiceByName', 'org.freedesktop.DBus.Error.ServiceUnknown')+ expect(await unavailable.notify({ tag: 'test' })).toBe(false)+ expect(await unavailable.notify({ tag: 'test' })).toBe(false)+ expect(unavailable.calls.filter(call => call.member === 'StartServiceByName')).toHaveLength(1)+ unavailable.connection.emit('close')++ // libnotify's getenv guard disables actions even for an empty value.+ vi.stubEnv('ELECTRON_USE_UBUNTU_NOTIFIER', '')+ const unity = setup(true)+ expect(await unity.notify({ tag: 'unity', actions: [{ id: 'ok', text: 'OK' }] })).toBe(true)+ expect(unity.calls.find(call => call.member === 'Notify')?.body?.[5]).toEqual([])+ unity.connection.emit('close')+ vi.stubEnv('ELECTRON_USE_UBUNTU_NOTIFIER', undefined)- const h = setup()- expect(await h.notify({ tag: 'old', focusSessionId: 'old-session' })).toBe(true)- expect(h.calls.some(call => call.member === 'StartServiceByName')).toBe(true)- const oldId = h.lastId()- h.stall('Notify')- const pending = h.notify({ tag: 'stalled' })- const duplicate = h.notify({ tag: 'stalled' })+ for (const method of ['Hello', 'AddMatch', 'StartServiceByName', 'GetNameOwner', 'GetCapabilities']) {+ const startup = setup()+ startup.stall(method)+ const attempt = startup.notify({ tag: method })await vi.advanceTimersByTimeAsync(6000)- expect(await pending).toBe(false)- expect(await duplicate).toBe(false)- const attempts = h.calls.length- expect(await h.notify({ tag: 'cooldown' })).toBe(false)- expect(h.calls).toHaveLength(attempts)- h.signal('ActionInvoked', [oldId, 'default'])- expect(h.source.webContents.send).toHaveBeenCalledWith('hermes:focus-session', 'old-session')- const afterConsumption = h.calls.length+ expect(await attempt).toBe(false)await vi.advanceTimersByTimeAsync(11000)- expect(h.calls).toHaveLength(afterConsumption) // No automatic replay of an ambiguous Notify.- h.stall('')- expect(await h.notify({ tag: 'recovered' })).toBe(true)- h.stall('CloseNotification')- const closesBeforeExpiry = h.calls.filter(call => call.member === 'CloseNotification').length- await vi.advanceTimersByTimeAsync(10 * 60_000 + 6000)- expect(h.calls.filter(call => call.member === 'CloseNotification')).toHaveLength(closesBeforeExpiry + 1)- h.connection.emit('close')- }-)--it(- 'releases naturally closed notifications while retaining other click targets',- async () => {- const h = setup(true)- expect(await h.notify({ tag: 'closed', focusSessionId: 'closed-session' })).toBe(true)- const closedId = h.lastId()- expect(await h.notify({ tag: 'active', focusSessionId: 'active-session' })).toBe(true)- const activeId = h.lastId()- await vi.advanceTimersByTimeAsync(1100)- const timersBeforeClose = vi.getTimerCount()-- h.signal('NotificationClosed', [closedId, 2], ':1.666')- expect(vi.getTimerCount()).toBe(timersBeforeClose)- h.signal('NotificationClosed', [closedId, 2])- expect(vi.getTimerCount()).toBe(timersBeforeClose - 1)- h.signal('ActionInvoked', [closedId, 'default'])- expect(h.source.webContents.send).not.toHaveBeenCalled()-- h.signal('ActionInvoked', [activeId, 'default'])- expect(h.source.webContents.send).toHaveBeenCalledWith('hermes:focus-session', 'active-session')- expect(vi.getTimerCount()).toBe(0)- h.connection.emit('close')+ startup.stall('')+ expect(await startup.notify({ tag: 'startup-recovered' })).toBe(true)+ startup.connection.emit('close')}-)--it(- 'preserves activation, dedupe and source ownership while fencing daemon ID reuse',- async () => {- const race = setup(true)- race.raceOwnerReply()- expect(await race.notify({ tag: 'obsolete-owner', focusSessionId: 'must-not-open' })).toBe(false)- expect(race.calls.filter(call => call.member === 'Notify')).toHaveLength(0)- // A daemon swap is not a daemon failure: the next notification goes to the- // new owner right away instead of sitting out the failure cooldown.- expect(await race.notify({ tag: 'after-race' })).toBe(true)- expect(race.calls.filter(call => call.member === 'Notify')).toHaveLength(1)- race.connection.emit('close')-- const h = setup(true)-- const payload = {- kind: 'approval',- sessionId: 'runtime',- focusSessionId: 'stored',- silent: true,- actions: [- { id: 'approve', text: 'Approve' },- { id: 'reject', text: 'Reject' }- ]- }- expect(await h.notify(payload)).toBe(true)- const firstId = h.lastId()- expect(await h.notify(payload)).toBe(true)- expect(h.calls.filter(call => call.member === 'Notify')).toHaveLength(1)- h.signal('ActionInvoked', [firstId, '1'], ':1.666')- expect(h.source.webContents.send).not.toHaveBeenCalled()- h.fail('CloseNotification', 'org.freedesktop.DBus.Error.InvalidArgs')- h.signal('ActionInvoked', [firstId, '1'])- expect(h.source.webContents.send).toHaveBeenCalledWith('hermes:notification-action', {- sessionId: 'runtime',- actionId: 'reject'- })- expect(h.primary.webContents.send).not.toHaveBeenCalled()- await vi.advanceTimersByTimeAsync(0)- expect(await h.notify({ tag: 'plugin', notifyId: 'source-callback', activate: '/plugin' })).toBe(true)- const pluginId = h.lastId()- h.source.isDestroyed.mockReturnValue(true)- h.signal('ActionInvoked', [pluginId, 'default'])- expect(h.primary.webContents.send).toHaveBeenCalledWith('hermes:notification-activate', {- activate: '/plugin',- notifyId: undefined,- tag: 'plugin'- })- h.connection.emit('close')-- const reused = setup(true)- expect(await reused.notify({ tag: 'old-owner', focusSessionId: 'must-not-open' })).toBe(true)- const retainedId = reused.lastId()- reused.replaceOwner()- expect(await reused.notify({ tag: 'new-owner', focusSessionId: 'new-session' })).toBe(true)- expect(reused.lastId()).toBe(retainedId)- reused.signal('ActionInvoked', [retainedId, 'default'], ':1.20')- expect(reused.source.webContents.send).not.toHaveBeenCalled()- reused.signal('ActionInvoked', [retainedId, 'default'])- expect(reused.source.webContents.send).toHaveBeenCalledWith('hermes:focus-session', 'new-session')-- // Quit teardown closes the bus; a delivered notification's callbacks die with it.- reused.dispose()- expect(reused.connection.stream.destroy).toHaveBeenCalled()- reused.signal('ActionInvoked', [retainedId, 'default'])- expect(reused.source.webContents.send).toHaveBeenCalledTimes(1)+ const h = setup()+ expect(await h.notify({ tag: 'old', focusSessionId: 'old-session' })).toBe(true)+ expect(h.calls.some(call => call.member === 'StartServiceByName')).toBe(true)+ const oldId = h.lastId()+ h.stall('Notify')+ const pending = h.notify({ tag: 'stalled' })+ const duplicate = h.notify({ tag: 'stalled' })+ await vi.advanceTimersByTimeAsync(6000)+ expect(await pending).toBe(false)+ expect(await duplicate).toBe(false)+ const attempts = h.calls.length+ expect(await h.notify({ tag: 'cooldown' })).toBe(false)+ expect(h.calls).toHaveLength(attempts)+ h.signal('ActionInvoked', [oldId, 'default'])+ expect(h.source.webContents.send).toHaveBeenCalledWith('hermes:focus-session', 'old-session')+ const afterConsumption = h.calls.length+ await vi.advanceTimersByTimeAsync(11000)+ expect(h.calls).toHaveLength(afterConsumption) // No automatic replay of an ambiguous Notify.+ h.stall('')+ expect(await h.notify({ tag: 'recovered' })).toBe(true)+ h.stall('CloseNotification')+ const closesBeforeExpiry = h.calls.filter(call => call.member === 'CloseNotification').length+ await vi.advanceTimersByTimeAsync(10 * 60_000 + 6000)+ expect(h.calls.filter(call => call.member === 'CloseNotification')).toHaveLength(closesBeforeExpiry + 1)+ h.connection.emit('close')+})++it('releases naturally closed notifications while retaining other click targets', async () => {+ const h = setup(true)+ expect(await h.notify({ tag: 'closed', focusSessionId: 'closed-session' })).toBe(true)+ const closedId = h.lastId()+ expect(await h.notify({ tag: 'active', focusSessionId: 'active-session' })).toBe(true)+ const activeId = h.lastId()+ await vi.advanceTimersByTimeAsync(1100)+ const timersBeforeClose = vi.getTimerCount()++ h.signal('NotificationClosed', [closedId, 2], ':1.666')+ expect(vi.getTimerCount()).toBe(timersBeforeClose)+ h.signal('NotificationClosed', [closedId, 2])+ expect(vi.getTimerCount()).toBe(timersBeforeClose - 1)+ h.signal('ActionInvoked', [closedId, 'default'])+ expect(h.source.webContents.send).not.toHaveBeenCalled()++ h.signal('ActionInvoked', [activeId, 'default'])+ expect(h.source.webContents.send).toHaveBeenCalledWith('hermes:focus-session', 'active-session')+ expect(vi.getTimerCount()).toBe(0)+ h.connection.emit('close')+})++it('preserves activation, dedupe and source ownership while fencing daemon ID reuse', async () => {+ const race = setup(true)+ race.raceOwnerReply()+ expect(await race.notify({ tag: 'obsolete-owner', focusSessionId: 'must-not-open' })).toBe(false)+ expect(race.calls.filter(call => call.member === 'Notify')).toHaveLength(0)+ // A daemon swap is not a daemon failure: the next notification goes to the+ // new owner right away instead of sitting out the failure cooldown.+ expect(await race.notify({ tag: 'after-race' })).toBe(true)+ expect(race.calls.filter(call => call.member === 'Notify')).toHaveLength(1)+ race.connection.emit('close')++ const h = setup(true)++ const payload = {+ kind: 'approval',+ sessionId: 'runtime',+ focusSessionId: 'stored',+ silent: true,+ actions: [+ { id: 'approve', text: 'Approve' },+ { id: 'reject', text: 'Reject' }+ ]}-)++ expect(await h.notify(payload)).toBe(true)+ const firstId = h.lastId()+ expect(await h.notify(payload)).toBe(true)+ expect(h.calls.filter(call => call.member === 'Notify')).toHaveLength(1)+ h.signal('ActionInvoked', [firstId, '1'], ':1.666')+ expect(h.source.webContents.send).not.toHaveBeenCalled()+ h.fail('CloseNotification', 'org.freedesktop.DBus.Error.InvalidArgs')+ h.signal('ActionInvoked', [firstId, '1'])+ expect(h.source.webContents.send).toHaveBeenCalledWith('hermes:notification-action', {+ sessionId: 'runtime',+ actionId: 'reject'+ })+ expect(h.primary.webContents.send).not.toHaveBeenCalled()+ await vi.advanceTimersByTimeAsync(0)+ expect(await h.notify({ tag: 'plugin', notifyId: 'source-callback', activate: '/plugin' })).toBe(true)+ const pluginId = h.lastId()+ h.source.isDestroyed.mockReturnValue(true)+ h.signal('ActionInvoked', [pluginId, 'default'])+ expect(h.primary.webContents.send).toHaveBeenCalledWith('hermes:notification-activate', {+ activate: '/plugin',+ notifyId: undefined,+ tag: 'plugin'+ })+ h.connection.emit('close')++ const reused = setup(true)+ expect(await reused.notify({ tag: 'old-owner', focusSessionId: 'must-not-open' })).toBe(true)+ const retainedId = reused.lastId()+ reused.replaceOwner()+ expect(await reused.notify({ tag: 'new-owner', focusSessionId: 'new-session' })).toBe(true)+ expect(reused.lastId()).toBe(retainedId)+ reused.signal('ActionInvoked', [retainedId, 'default'], ':1.20')+ expect(reused.source.webContents.send).not.toHaveBeenCalled()+ reused.signal('ActionInvoked', [retainedId, 'default'])+ expect(reused.source.webContents.send).toHaveBeenCalledWith('hermes:focus-session', 'new-session')++ // Quit teardown closes the bus; a delivered notification's callbacks die with it.+ reused.dispose()+ expect(reused.connection.stream.destroy).toHaveBeenCalled()+ reused.signal('ActionInvoked', [retainedId, 'default'])+ expect(reused.source.webContents.send).toHaveBeenCalledTimes(1)+})diff --git a/apps/desktop/electron/notification-linux.ts b/apps/desktop/electron/notification-linux.tsindex fe8de2f4842..93db5dcd0f9 100644--- a/apps/desktop/electron/notification-linux.ts+++ b/apps/desktop/electron/notification-linux.ts@@ -55,12 +55,14 @@ export function createLinuxNotifications() {if (connection !== state) {return}+connection = undefinedstate.generation++for (const item of state.live.values()) {item.receive('failed', undefined)}+state.live.clear()bus.connection.stream.destroy()}@@ -92,6 +94,7 @@ export function createLinuxNotifications() {if (message.path !== PATH || message.interface !== SERVICE || !message.member) {return}+const [id, value] = message.body ?? []state.live.get(`${message.sender}:${id}`)?.receive(message.member, value)})@@ -99,6 +102,7 @@ export function createLinuxNotifications() {const startup = new AbortController()const timer = setTimeout(() => startup.abort(), DELIVERY_TIMEOUT_MS)const options = { signal: startup.signal, timeout: DELIVERY_TIMEOUT_MS }+try {bus.name = await bus.invokeDbus<string>({ member: 'Hello' }, options)@@ -131,6 +135,7 @@ export function createLinuxNotifications() {if (delivered) {delivered.state.live.delete(`${delivered.owner}:${delivered.id}`)}+delivered = undefined}@@ -142,6 +147,7 @@ export function createLinuxNotifications() {if (!target) {return}+const { state, owner, id } = target// The retention timer must never re-enter synchronous libnotify either.void state.bus@@ -181,6 +187,7 @@ export function createLinuxNotifications() {const state = connect()await state.readyconst { bus } = state+const getOwner = () =>new Promise<{ owner: string; generation: number }>((resolve, reject) => {bus.invokeDbus(@@ -190,19 +197,23 @@ export function createLinuxNotifications() {if (error) {return reject(error)}+// Snapshot before another message in this read batch can replace the// owner. An await followed by reading generation pairs stale/new data.resolve({ owner, generation: state.generation })})})+let destination: { owner: string; generation: number }+try {destination = await getOwner()} catch (error) {if ((error as { dbusName?: string })?.dbusName !== 'org.freedesktop.DBus.Error.NameHasNoOwner') {throw error}+// A running daemon need not have an activation file, but an unowned// activatable service is healthy too. Never make this an owner-only guard.await bus.invokeDbus({ member: 'StartServiceByName', signature: 'su', body: [SERVICE, 0] }, callOptions)@@ -211,6 +222,7 @@ export function createLinuxNotifications() {const { owner, generation } = destinationaddressed = { state, generation }+if (state.generation !== generation) {throw new Error('Notification owner changed during lookup')}@@ -261,6 +273,7 @@ export function createLinuxNotifications() {if (state.generation !== generation) {return reject(new Error('Notification owner changed during delivery'))}+if (!Number.isInteger(id) || id <= 0) {return reject(new Error(`Notify returned an invalid id: ${String(id)}`))}@@ -304,6 +317,7 @@ export function createLinuxNotifications() {if (!addressed || addressed.state.generation === addressed.generation) {retryAfter = Date.now() + RETRY_COOLDOWN_MS}+release()notification.emit('failed')diff --git a/apps/desktop/electron/pool-reclamation.test.ts b/apps/desktop/electron/pool-reclamation.test.tsindex 80df7a891d3..38b374e430a 100644--- a/apps/desktop/electron/pool-reclamation.test.ts+++ b/apps/desktop/electron/pool-reclamation.test.ts@@ -24,15 +24,18 @@ function harness() {return prepare(key)},commit: async () => true,- cancel: async key => { cancelled.push(key) },- stopBackend: key => new Promise<void>(resolve => {- stopped.push(key)- pool.delete(key)- exits.set(key, () => {- releases.get(key)?.()- resolve()+ cancel: async key => {+ cancelled.push(key)+ },+ stopBackend: key =>+ new Promise<void>(resolve => {+ stopped.push(key)+ pool.delete(key)+ exits.set(key, () => {+ releases.get(key)?.()+ resolve()+ })})- }),})async function seed() {@@ -42,8 +45,20 @@ function harness() {}}- return { coordinator, pool, releases, exits, stopped, cancelled, prepared, retirer, seed,- setPrepare: (fn: typeof prepare) => { prepare = fn } }+ return {+ coordinator,+ pool,+ releases,+ exits,+ stopped,+ cancelled,+ prepared,+ retirer,+ seed,+ setPrepare: (fn: typeof prepare) => {+ prepare = fn+ }+ }}test('reclamation sequences every foreground waiter, including an already queued background promotion', async () => {@@ -53,8 +68,16 @@ test('reclamation sequences every foreground waiter, including an already queuedconst second = h.coordinator.request('e', { priority: 'background' })second.promote('foreground')let granted = 0- void first.acquired.then(() => { granted += 1 }).catch(() => undefined)- void second.acquired.then(() => { granted += 1 }).catch(() => undefined)+ void first.acquired+ .then(() => {+ granted += 1+ })+ .catch(() => undefined)+ void second.acquired+ .then(() => {+ granted += 1+ })+ .catch(() => undefined)try {await vi.waitFor(() => assert.deepEqual(h.stopped, ['a']), { timeout: 2000 })@@ -83,7 +106,12 @@ test('withdrawn demand or replaced candidates cancel prepared authority withoutconst h = harness()await h.seed()let finishPrepare!: (value: string) => void- h.setPrepare(() => new Promise(resolve => { finishPrepare = resolve }))+ h.setPrepare(+ () =>+ new Promise(resolve => {+ finishPrepare = resolve+ })+ )const ticket = h.coordinator.request('d', { priority: 'foreground' })void ticket.acquired.catch(() => undefined)diff --git a/apps/desktop/electron/pool-retire-http.ts b/apps/desktop/electron/pool-retire-http.tsindex c102906213b..551f43d021f 100644--- a/apps/desktop/electron/pool-retire-http.ts+++ b/apps/desktop/electron/pool-retire-http.ts@@ -24,11 +24,11 @@ export function createPoolRetirementClient(requestJson: RequestJson) {}try {- return await requestJson(`http://127.0.0.1:${entry.port}/api/health/retirement`, entry.token, {+ return (await requestJson(`http://127.0.0.1:${entry.port}/api/health/retirement`, entry.token, {method: 'POST',body: { action, ...(token ? { token } : {}) },- timeoutMs: 3000,- }) as RetirementReply | null+ timeoutMs: 3000+ })) as RetirementReply | null} catch {// An older runtime, transport failure or unreadable reply grants no// authority. Prepared permits expire; committed ones remain recoverable@@ -42,12 +42,13 @@ export function createPoolRetirementClient(requestJson: RequestJson) {const reply = await request(entry, 'prepare')return reply?.ok === true && reply.idle === true && typeof reply.token === 'string' && reply.token- ? reply.token : null+ ? reply.token+ : null},commit: async (_key: string, entry: PoolBackend, token: string): Promise<boolean> =>(await request(entry, 'commit', token))?.ok === true,cancel: async (_key: string, entry: PoolBackend, token: string): Promise<void> => {await request(entry, 'cancel', token)- },+ }}}diff --git a/apps/desktop/electron/pool-retire.test.ts b/apps/desktop/electron/pool-retire.test.tsindex 0fbf63c5a0d..d9cf2f243b0 100644--- a/apps/desktop/electron/pool-retire.test.ts+++ b/apps/desktop/electron/pool-retire.test.ts@@ -18,9 +18,13 @@ test('idle and LRU retirement require backend authority, unchanged identity andpool,coordinator: new LocalBackendSpawnCoordinator(3),prepare: async () => {- if (outcome === 'replaced') {pool.set('a', { process: {}, lastActiveAt: 1 })}+ if (outcome === 'replaced') {+ pool.set('a', { process: {}, lastActiveAt: 1 })+ }- if (outcome === 'fresh') {entry.lastActiveAt = Date.now()}+ if (outcome === 'fresh') {+ entry.lastActiveAt = Date.now()+ }return outcome === 'busy' || outcome === 'unknown' ? null : 'permit'},@@ -29,20 +33,35 @@ test('idle and LRU retirement require backend authority, unchanged identity andreturn outcome !== 'expired'},- cancel: async key => { cancelled.push(key) },- onRetiring: () => { events.push('park') },- stopBackend: async key => { events.push('stop'); stopped.push(key); pool.delete(key) },+ cancel: async key => {+ cancelled.push(key)+ },+ onRetiring: () => {+ events.push('park')+ },+ stopBackend: async key => {+ events.push('stop')+ stopped.push(key)+ pool.delete(key)+ }})try {- if (path === 'idle') {await retirer.retireIdle('a', 1000)}- else {await retirer.evictTo(0, 1000)}+ if (path === 'idle') {+ await retirer.retireIdle('a', 1000)+ } else {+ await retirer.evictTo(0, 1000)+ }assert.deepEqual(stopped, outcome === 'idle' ? ['a'] : [], `${path}: ${outcome}`)- if (outcome === 'idle') {assert.deepEqual(events, ['commit', 'park', 'stop'])}+ if (outcome === 'idle') {+ assert.deepEqual(events, ['commit', 'park', 'stop'])+ }- if (['expired', 'replaced', 'fresh'].includes(outcome)) {assert.deepEqual(cancelled, ['a'])}+ if (['expired', 'replaced', 'fresh'].includes(outcome)) {+ assert.deepEqual(cancelled, ['a'])+ }} finally {retirer.dispose()}@@ -56,8 +75,11 @@ test('candidate selection excludes processless descriptors, renderer-leased work['old', { process: {}, lastActiveAt: 1 }],['busy', { process: {}, lastActiveAt: 0, activeTurn: true }],['descriptor', { process: null }],- ['target', { process: {}, lastActiveAt: 0 }],+ ['target', { process: {}, lastActiveAt: 0 }]])- assert.deepEqual(selectRetirementCandidates(pool, new Set(['target'])).map(([key]) => key), ['old', 'fresh'])+ assert.deepEqual(+ selectRetirementCandidates(pool, new Set(['target'])).map(([key]) => key),+ ['old', 'fresh']+ )})diff --git a/apps/desktop/electron/pool-retire.ts b/apps/desktop/electron/pool-retire.tsindex 276910d6687..285fd0aff05 100644--- a/apps/desktop/electron/pool-retire.ts+++ b/apps/desktop/electron/pool-retire.ts@@ -47,8 +47,8 @@ export function createPoolRetirer<E extends PoolRetireEntry>(deps: PoolRetirerDereturn result}- const needsCapacity = () => !disposed && deps.coordinator.foregroundWaiters.size > 0 &&- deps.coordinator.activeCount >= deps.coordinator.limit+ const needsCapacity = () =>+ !disposed && deps.coordinator.foregroundWaiters.size > 0 && deps.coordinator.activeCount >= deps.coordinator.limitasync function retire(key: string, entry: E, needed: () => boolean): Promise<boolean> {const eligible = () => !disposed && deps.pool.get(key) === entry && entry.activeTurn !== true && needed()@@ -122,16 +122,18 @@ export function createPoolRetirer<E extends PoolRetireEntry>(deps: PoolRetirerDeclearTimeout(retry)scheduled = true- void enqueue(reclaim).catch(report).finally(() => {- scheduled = false-- // Busy work may finish without a renderer touch (cron / side agents).- // The coordinator's existing ticket deadline bounds these retries.- if (needsCapacity()) {- retry = setTimeout(wake, 1000)- retry.unref?.()- }- })+ void enqueue(reclaim)+ .catch(report)+ .finally(() => {+ scheduled = false++ // Busy work may finish without a renderer touch (cron / side agents).+ // The coordinator's existing ticket deadline bounds these retries.+ if (needsCapacity()) {+ retry = setTimeout(wake, 1000)+ retry.unref?.()+ }+ })}const unsubscribe = deps.coordinator.onChange(wake)@@ -145,27 +147,29 @@ export function createPoolRetirer<E extends PoolRetireEntry>(deps: PoolRetirerDethrow new Error(`Backend for "${key}" was retired; open it explicitly to reconnect.`)}},- retireIdle: (key: string, idleMs: number) => enqueue(async () => {- const entry = deps.pool.get(key)-- return entry ? retire(key, entry, () => Date.now() - (entry.lastActiveAt || 0) > idleMs) : false- }),- evictTo: (keep: number, freshMs: number) => enqueue(async () => {- const retired: string[] = []- const overCap = () => [...deps.pool.values()].filter(entry => entry.process).length > Math.max(0, keep)-- for (const [key, entry] of selectRetirementCandidates(deps.pool, deps.coordinator.foregroundWaiters)) {- if (await retire(key, entry, () => overCap() && Date.now() - (entry.lastActiveAt || 0) > freshMs)) {- retired.push(key)+ retireIdle: (key: string, idleMs: number) =>+ enqueue(async () => {+ const entry = deps.pool.get(key)++ return entry ? retire(key, entry, () => Date.now() - (entry.lastActiveAt || 0) > idleMs) : false+ }),+ evictTo: (keep: number, freshMs: number) =>+ enqueue(async () => {+ const retired: string[] = []+ const overCap = () => [...deps.pool.values()].filter(entry => entry.process).length > Math.max(0, keep)++ for (const [key, entry] of selectRetirementCandidates(deps.pool, deps.coordinator.foregroundWaiters)) {+ if (await retire(key, entry, () => overCap() && Date.now() - (entry.lastActiveAt || 0) > freshMs)) {+ retired.push(key)+ }}- }- return retired- }),+ return retired+ }),dispose: () => {disposed = trueclearTimeout(retry)unsubscribe()- },+ }}}diff --git a/apps/desktop/electron/pool-retirement-live-fixture/main.ts b/apps/desktop/electron/pool-retirement-live-fixture/main.tsindex c0fb81509e9..238500b9dc4 100644--- a/apps/desktop/electron/pool-retirement-live-fixture/main.ts+++ b/apps/desktop/electron/pool-retirement-live-fixture/main.ts@@ -10,7 +10,11 @@ import { app, BrowserWindow, ipcMain } from 'electron'import { stopBackendChild, waitForBackendExit } from '../backend-child'import { createPoolRetirer } from '../pool-retire'import { createPoolRetirementClient } from '../pool-retire-http'-import { LocalBackendSpawnCoordinator, type LocalBackendSpawnRequest, registerLocalBackendExitFinalizer } from '../pool-spawn-coordinator'+import {+ LocalBackendSpawnCoordinator,+ type LocalBackendSpawnRequest,+ registerLocalBackendExitFinalizer+} from '../pool-spawn-coordinator'interface Resident {process: ChildProcessWithoutNullStreams@@ -56,17 +60,25 @@ let window: BrowserWindow | undefinedlet descriptorCalls = 0let rendererParking: { parked: Record<string, string[]>; redials: number; open: number } | undefined-const stopDeps = { forceKillProcessTree: () => { throw new Error('POSIX fixture only') } }+const stopDeps = {+ forceKillProcessTree: () => {+ throw new Error('POSIX fixture only')+ }+}const record = (event: string, key?: string, details: Record<string, unknown> = {}) => {receipts.push({ event, key, active: coordinator.activeCount, live: live.size, ...details })}const alive = (pid: number) => {- try { process.kill(pid, 0);+ try {+ process.kill(pid, 0)- return true } catch (error) {- if ((error as NodeJS.ErrnoException).code === 'ESRCH') {return false}+ return true+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code === 'ESRCH') {+ return false+ }throw error}}@@ -74,9 +86,11 @@ const alive = (pid: number) => {async function until(description: string, predicate: () => boolean | Promise<boolean>, timeoutMs = 30_000) {const deadline = Date.now() + timeoutMs- while (!await predicate()) {+ while (!(await predicate())) {if (Date.now() > deadline) {- throw new Error(`Timed out: ${description}\n${JSON.stringify(receipts)}\n${[...children].map(([key, entry]) => `${key}: ${entry.output}`).join('\n')}`)+ throw new Error(+ `Timed out: ${description}\n${JSON.stringify(receipts)}\n${[...children].map(([key, entry]) => `${key}: ${entry.output}`).join('\n')}`+ )}await delay(30)@@ -85,23 +99,32 @@ async function until(description: string, predicate: () => boolean | Promise<booasync function http(entry: Resident, route: string, body?: Record<string, string>, token = entry.token) {const response = await fetch(`http://127.0.0.1:${entry.port}${route}`, {- method: body ? 'POST' : 'GET', headers: {- 'Content-Type': 'application/json', ...(token ? { 'X-Hermes-Session-Token': token } : {}),- }, ...(body ? { body: JSON.stringify(body) } : {}), signal: AbortSignal.timeout(5000),+ method: body ? 'POST' : 'GET',+ headers: {+ 'Content-Type': 'application/json',+ ...(token ? { 'X-Hermes-Session-Token': token } : {})+ },+ ...(body ? { body: JSON.stringify(body) } : {}),+ signal: AbortSignal.timeout(5000)})- return { status: response.status, body: await response.json() as Record<string, unknown> }+ return { status: response.status, body: (await response.json()) as Record<string, unknown> }}const client = createPoolRetirementClient(async (url, token, options) => {- const response = await fetch(url, { method: options.method,+ const response = await fetch(url, {+ method: options.method,headers: { 'X-Hermes-Session-Token': token, 'Content-Type': 'application/json' },- body: JSON.stringify(options.body), signal: AbortSignal.timeout(options.timeoutMs) })+ body: JSON.stringify(options.body),+ signal: AbortSignal.timeout(options.timeoutMs)+ })- const reply = await response.json() as Record<string, unknown>+ const reply = (await response.json()) as Record<string, unknown>record('http', undefined, { action: options.body.action, status: response.status, ok: reply.ok, idle: reply.idle })- if (!response.ok) {throw new Error(`Retirement HTTP ${response.status}: ${JSON.stringify(reply)}`)}+ if (!response.ok) {+ throw new Error(`Retirement HTTP ${response.status}: ${JSON.stringify(reply)}`)+ }return reply})@@ -113,24 +136,46 @@ async function spawnResident(key: string, release: () => void): Promise<Residentconst token = randomUUID()const child = spawn(python, ['-u', join(fixture, 'serve.py'), repo, key], {- cwd: join(root, key), detached: true, stdio: 'pipe',- env: { ...process.env, HOME: join(root, key), USERPROFILE: join(root, key), HERMES_HOME: home,- HERMES_DESKTOP: '1', HERMES_SERVE_HEADLESS: '1', HERMES_DASHBOARD_SESSION_TOKEN: token,- PYTHONUNBUFFERED: '1', PYTHONDONTWRITEBYTECODE: '1', PYTHONNOUSERSITE: '1',+ cwd: join(root, key),+ detached: true,+ stdio: 'pipe',+ env: {+ ...process.env,+ HOME: join(root, key),+ USERPROFILE: join(root, key),+ HERMES_HOME: home,+ HERMES_DESKTOP: '1',+ HERMES_SERVE_HEADLESS: '1',+ HERMES_DASHBOARD_SESSION_TOKEN: token,+ PYTHONUNBUFFERED: '1',+ PYTHONDONTWRITEBYTECODE: '1',+ PYTHONNOUSERSITE: '1'// Environment contains only the launch allowlist and fixture values.- },+ }})- const entry: Resident = { process: child, home,- token, port: null, activeTurn: false,+ const entry: Resident = {+ process: child,+ home,+ token,+ port: null,+ activeTurn: false,// All residents are renderer-occupied/recent; backend-only work is the authority.- lastActiveAt: Date.now(), output: '' }+ lastActiveAt: Date.now(),+ output: ''+ }children.set(key, entry)pool.set(key, entry)- child.on('error', error => { entry.output += String(error) })- child.stdout.on('data', chunk => { entry.output += String(chunk) })- child.stderr.on('data', chunk => { entry.output += String(chunk) })+ child.on('error', error => {+ entry.output += String(error)+ })+ child.stdout.on('data', chunk => {+ entry.output += String(chunk)+ })+ child.stderr.on('data', chunk => {+ entry.output += String(chunk)+ })child.once('exit', (code, signal) => {live.delete(child.pid!)record('exit', key, { pid: child.pid, code, signal })@@ -141,20 +186,31 @@ async function spawnResident(key: string, release: () => void): Promise<Resident})await new Promise<void>((resolveSpawn, reject) => {child.once('spawn', resolveSpawn)- child.once('error', error => { release(); reject(error) })+ child.once('error', error => {+ release()+ reject(error)+ })})live.add(child.pid!)maxLiveServeChildren = Math.max(maxLiveServeChildren, live.size)record('spawn', key, { pid: child.pid })assert.ok(live.size <= coordinator.limit, 'Live OS children exceeded the pool cap')- await until(`${key} HERMES_BACKEND_READY`, () => {- if (child.exitCode !== null || child.signalCode !== null) {throw new Error(`${key} exited before ready:\n${entry.output}`)}- const match = entry.output.match(/HERMES_BACKEND_READY[^\n]*port=(\d+)/)+ await until(+ `${key} HERMES_BACKEND_READY`,+ () => {+ if (child.exitCode !== null || child.signalCode !== null) {+ throw new Error(`${key} exited before ready:\n${entry.output}`)+ }+ const match = entry.output.match(/HERMES_BACKEND_READY[^\n]*port=(\d+)/)- if (match) {entry.port = Number(match[1])}+ if (match) {+ entry.port = Number(match[1])+ }- return Boolean(match)- }, 60_000)+ return Boolean(match)+ },+ 60_000+ )record('ready', key, { pid: child.pid, port: entry.port })return entry@@ -187,20 +243,36 @@ async function run() {const entry = children.get(key)assert.ok(entry?.port, `No real backend for ${key}`)- return { mode: 'local', authMode: 'token', profile: key, token: entry.token,+ return {+ mode: 'local',+ authMode: 'token',+ profile: key,+ token: entry.token,baseUrl: `http://127.0.0.1:${entry.port}`,- wsUrl: `ws://127.0.0.1:${entry.port}/api/ws?token=${encodeURIComponent(entry.token)}` }+ wsUrl: `ws://127.0.0.1:${entry.port}/api/ws?token=${encodeURIComponent(entry.token)}`+ }+ })+ window = new BrowserWindow({+ show: false,+ webPreferences: {+ preload: join(root, 'preload.cjs'),+ contextIsolation: true,+ nodeIntegration: false,+ sandbox: true,+ backgroundThrottling: false+ }})- window = new BrowserWindow({ show: false, webPreferences: {- preload: join(root, 'preload.cjs'), contextIsolation: true, nodeIntegration: false,- sandbox: true, backgroundThrottling: false,- } })await window.loadFile(join(root, 'renderer.html'))- assert.equal(await window.webContents.executeJavaScript('window.poolRetirementRenderer.open()'), 4,- 'Real renderer opens legacy and registry WebSockets for both idle children')+ assert.equal(+ await window.webContents.executeJavaScript('window.poolRetirementRenderer.open()'),+ 4,+ 'Real renderer opens legacy and registry WebSockets for both idle children'+ )const dialsBeforeRetirement = descriptorCalls- retirer = createPoolRetirer<Resident>({ pool, coordinator,+ retirer = createPoolRetirer<Resident>({+ pool,+ coordinator,prepare: async (key, entry) => {const token = await client.prepare(key, entry)record(token ? 'prepared' : 'busy', key)@@ -212,8 +284,11 @@ async function run() {if (committed) {assert.equal(await client.prepare(key, entry), token, 'A lost commit reply must recover the committed permit')- assert.equal((await http(entry, '/api/health/retirement', { action: 'cancel', token })).body.ok, false,- 'Committed retirement cannot reopen admission')+ assert.equal(+ (await http(entry, '/api/health/retirement', { action: 'cancel', token })).body.ok,+ false,+ 'Committed retirement cannot reopen admission'+ )record('committed', key)}@@ -242,7 +317,9 @@ async function run() {await exitassert.equal(alive(entry.process.pid!), false)},- log: message => { errors.push(message) },+ log: message => {+ errors.push(message)+ }})const direct = coordinator.request('foreground-d', { timeoutMs: 45_000, priority: 'foreground' })const promoted = coordinator.request('promoted-e', { timeoutMs: 45_000, priority: 'background' })@@ -252,19 +329,30 @@ async function run() {assert.equal(promoted.promote('foreground'), true)assert.deepEqual([...coordinator.foregroundWaiters], ['foreground-d', 'promoted-e'])record('waiters', undefined, { keys: [...coordinator.foregroundWaiters] })- await Promise.all(([['foreground-d', direct], ['promoted-e', promoted]] as const).map(async ([name, ticket]) => {- const release = await ticket.acquired- opened.push(name)- record('acquired', name)- await spawnResident(name, release)- }))+ await Promise.all(+ (+ [+ ['foreground-d', direct],+ ['promoted-e', promoted]+ ] as const+ ).map(async ([name, ticket]) => {+ const release = await ticket.acquired+ opened.push(name)+ record('acquired', name)+ await spawnResident(name, release)+ })+ )assert.deepEqual(errors, [])assert.deepEqual(retired, ['idle-a', 'idle-b'])assert.equal(coordinator.queuedCount, 0)assert.equal(coordinator.activeCount, 3)- for (const [oldKey, newKey] of [['idle-a', 'foreground-d'], ['idle-b', 'promoted-e']]) {- const index = (event: string, key: string) => receipts.findIndex(receipt => receipt.event === event && receipt.key === key)+ for (const [oldKey, newKey] of [+ ['idle-a', 'foreground-d'],+ ['idle-b', 'promoted-e']+ ]) {+ const index = (event: string, key: string) =>+ receipts.findIndex(receipt => receipt.event === event && receipt.key === key)assert.ok(index('committed', oldKey) < index('park', oldKey))assert.ok(index('park', oldKey) < index('signal', oldKey))assert.ok(index('signal', oldKey) < index('shutdown-held', oldKey))@@ -277,7 +365,10 @@ async function run() {assert.ok(receipts.filter(receipt => receipt.event === 'release').every(receipt => receipt.osAlive === false))assert.ok(alive(cron.process.pid!) && alive(cronPid))assert.equal((await http(cron, '/api/health/idle')).body.idle, false)- await until('cron made progress after reclamation', () => readFileSync(join(cron.home, 'cron-heartbeat'), 'utf8') !== heartbeat)+ await until(+ 'cron made progress after reclamation',+ () => readFileSync(join(cron.home, 'cron-heartbeat'), 'utf8') !== heartbeat+ )assert.equal(retired.includes('cron-busy'), false)busyCronSurvived = trueconst parked = await window.webContents.executeJavaScript('window.poolRetirementRenderer.wake()')@@ -288,21 +379,32 @@ async function run() {assert.equal(rendererParking?.redials, 0, 'Socket close and wake sweeps must not redial parked scopes')record('renderer-parked', undefined, rendererParking)writeFileSync(join(cron.home, 'finish-cron'), '')- await until('real cron completed and released backend activity', async () =>- existsSync(join(cron.home, 'cron-finished')) && !alive(cronPid) && (await http(cron, '/api/health/idle')).body.idle === true)+ await until(+ 'real cron completed and released backend activity',+ async () =>+ existsSync(join(cron.home, 'cron-finished')) &&+ !alive(cronPid) &&+ (await http(cron, '/api/health/idle')).body.idle === true+ )record('cron-completed', 'cron-busy', { pid: cronPid })}async function finish(error?: unknown) {- if (finishing) {return}+ if (finishing) {+ return+ }finishing = trueretirer?.dispose()- for (const ticket of tickets) {ticket.cancel()}+ for (const ticket of tickets) {+ ticket.cancel()+ }let cleanupError: unknowntry {- if (window && !window.isDestroyed()) {window.destroy()}+ if (window && !window.isDestroyed()) {+ window.destroy()+ }for (const entry of children.values()) {writeFileSync(join(entry.home, 'finish-cron'), '')@@ -313,28 +415,56 @@ async function finish(error?: unknown) {if (cron && existsSync(join(cron.home, 'cron-started'))) {const pid = JSON.parse(readFileSync(join(cron.home, 'cron-started'), 'utf8')).pid as number- await until('cron script cleanup', () => !alive(pid), 5000).catch(() => { process.kill(pid, 'SIGKILL') })+ await until('cron script cleanup', () => !alive(pid), 5000).catch(() => {+ process.kill(pid, 'SIGKILL')+ })}- await Promise.all([...children.values()].map(async entry => {- stopBackendChild(entry.process, stopDeps)- await waitForBackendExit(entry.process, stopDeps, 5000)- }))+ await Promise.all(+ [...children.values()].map(async entry => {+ stopBackendChild(entry.process, stopDeps)+ await waitForBackendExit(entry.process, stopDeps, 5000)+ })+ )assert.equal(live.size, 0)assert.equal(coordinator.activeCount, 0)- } catch (caught) { cleanupError = caught }+ } catch (caught) {+ cleanupError = caught+ }const failure = error || cleanupError- writeFileSync(join(root, 'result.json'), JSON.stringify({- ok: !failure, error: failure ? String((failure as Error).stack || failure) : undefined,- cleanupError: cleanupError ? String(cleanupError) : undefined, cleanedUp: !cleanupError,- electronVersion: process.versions.electron, processType: process.type,- capacity: coordinator.limit, maxLiveServeChildren, retired, opened, busyCronSurvived,- rendererParking, receipts,- ...(failure ? { backendOutput: Object.fromEntries([...children].map(([key, entry]) => [key, entry.output])) } : {}),- }, null, 2))+ writeFileSync(+ join(root, 'result.json'),+ JSON.stringify(+ {+ ok: !failure,+ error: failure ? String((failure as Error).stack || failure) : undefined,+ cleanupError: cleanupError ? String(cleanupError) : undefined,+ cleanedUp: !cleanupError,+ electronVersion: process.versions.electron,+ processType: process.type,+ capacity: coordinator.limit,+ maxLiveServeChildren,+ retired,+ opened,+ busyCronSurvived,+ rendererParking,+ receipts,+ ...(failure+ ? { backendOutput: Object.fromEntries([...children].map(([key, entry]) => [key, entry.output])) }+ : {})+ },+ null,+ 2+ )+ )app.exit(failure ? 1 : 0)}-process.once('SIGTERM', () => { void finish(new Error('Native fixture interrupted')) })-app.whenReady().then(run).then(() => finish(), finish)+process.once('SIGTERM', () => {+ void finish(new Error('Native fixture interrupted'))+})+app+ .whenReady()+ .then(run)+ .then(() => finish(), finish)diff --git a/apps/desktop/electron/pool-retirement-live-fixture/preload.ts b/apps/desktop/electron/pool-retirement-live-fixture/preload.tsindex fed40a8f8ec..c3cf5a8380c 100644--- a/apps/desktop/electron/pool-retirement-live-fixture/preload.ts+++ b/apps/desktop/electron/pool-retirement-live-fixture/preload.ts@@ -3,10 +3,10 @@ import { contextBridge, ipcRenderer } from 'electron'// Deliberate fixture IPC only; the renderer still uses production gateway/WS code.contextBridge.exposeInMainWorld('hermesDesktop', {getConnection: (profile: string) => ipcRenderer.invoke('retirement-fixture:descriptor', profile),- getConnectionFor: ({ profile }: { profile: string }) => ipcRenderer.invoke('retirement-fixture:descriptor', profile),+ getConnectionFor: ({ profile }: { profile: string }) => ipcRenderer.invoke('retirement-fixture:descriptor', profile)})contextBridge.exposeInMainWorld('retirementFixture', {onRetiring: (handler: (key: string) => void) => {ipcRenderer.on('retirement-fixture:retiring', (_event, key: string) => handler(key))- },+ }})diff --git a/apps/desktop/electron/pool-retirement-live-fixture/vitest.config.ts b/apps/desktop/electron/pool-retirement-live-fixture/vitest.config.tsindex 1bce7a7ef0c..24bde95e213 100644--- a/apps/desktop/electron/pool-retirement-live-fixture/vitest.config.ts+++ b/apps/desktop/electron/pool-retirement-live-fixture/vitest.config.ts@@ -5,5 +5,5 @@ import { defineConfig } from 'vitest/config'// Targeted native seam proof: no unrelated renderer Vite plugins or full app build.export default defineConfig({root: fileURLToPath(new URL('../../', import.meta.url)),- test: { environment: 'node', include: ['electron/pool-retirement-live.test.ts'] },+ test: { environment: 'node', include: ['electron/pool-retirement-live.test.ts'] }})diff --git a/apps/desktop/electron/pool-retirement-live.test.ts b/apps/desktop/electron/pool-retirement-live.test.tsindex 5479ee37c6b..84d783c18c3 100644--- a/apps/desktop/electron/pool-retirement-live.test.ts+++ b/apps/desktop/electron/pool-retirement-live.test.ts@@ -23,20 +23,39 @@ function isolatedEnv(root: string): NodeJS.ProcessEnv {// Allowlist rather than trying to enumerate provider secrets and overrides.for (const name of ['PATH', 'SystemRoot', 'WINDIR', 'DISPLAY', 'WAYLAND_DISPLAY', 'XDG_RUNTIME_DIR']) {- if (process.env[name]) {env[name] = process.env[name]}+ if (process.env[name]) {+ env[name] = process.env[name]+ }}- return { ...env, HOME: root, USERPROFILE: root, HERMES_HOME: join(root, '.hermes'),- XDG_CONFIG_HOME: join(root, 'config'), XDG_CACHE_HOME: join(root, 'cache'),- TMPDIR: root, TEMP: root, TMP: root, TZ: 'UTC', LANG: 'C.UTF-8',- HERMES_DESKTOP_CDP_PORT: 'off', HERMES_DESKTOP_USER_DATA_DIR: join(root, 'user-data') }+ return {+ ...env,+ HOME: root,+ USERPROFILE: root,+ HERMES_HOME: join(root, '.hermes'),+ XDG_CONFIG_HOME: join(root, 'config'),+ XDG_CACHE_HOME: join(root, 'cache'),+ TMPDIR: root,+ TEMP: root,+ TMP: root,+ TZ: 'UTC',+ LANG: 'C.UTF-8',+ HERMES_DESKTOP_CDP_PORT: 'off',+ HERMES_DESKTOP_USER_DATA_DIR: join(root, 'user-data')+ }}function waitForExit(child: ChildProcess, timeoutMs: number): Promise<number | null> {return new Promise((resolveExit, reject) => {const timer = setTimeout(() => reject(new Error('Native retirement fixture timed out')), timeoutMs)- child.once('error', error => { clearTimeout(timer); reject(error) })- child.once('exit', code => { clearTimeout(timer); resolveExit(code) })+ child.once('error', error => {+ clearTimeout(timer)+ reject(error)+ })+ child.once('exit', code => {+ clearTimeout(timer)+ resolveExit(code)+ })})}@@ -45,7 +64,7 @@ test.skipIf(process.env.HERMES_TEST_REAL_SERVE !== '1' || process.platform === 'async () => {const python = process.env.HERMES_TEST_PYTHONassert.ok(python && existsSync(python), 'Set HERMES_TEST_PYTHON to an installed Hermes Python environment')- const electron = process.env.HERMES_TEST_ELECTRON || require('electron') as string+ const electron = process.env.HERMES_TEST_ELECTRON || (require('electron') as string)assert.ok(existsSync(electron), 'HERMES_TEST_ELECTRON must name a real native Electron executable')const root = mkdtempSync(join(tmpdir(), 'hermes-pool-retirement-live-'))const resultPath = join(root, 'result.json')@@ -55,21 +74,48 @@ test.skipIf(process.env.HERMES_TEST_REAL_SERVE !== '1' || process.platform === 'try {mkdirSync(join(root, '.hermes'))const bundle = join(root, 'main.cjs')- await build({ entryPoints: [join(fixture, 'main.ts')], outfile: bundle,- bundle: true, platform: 'node', format: 'cjs', target: 'node22', external: ['electron'] })- await build({ entryPoints: [join(fixture, 'preload.ts')], outfile: join(root, 'preload.cjs'),- bundle: true, platform: 'node', format: 'cjs', external: ['electron'] })- await build({ entryPoints: [join(desktop, 'src/test/pool-retirement-renderer.ts')], outfile: join(root, 'renderer.js'),- bundle: true, platform: 'browser', format: 'iife',+ await build({+ entryPoints: [join(fixture, 'main.ts')],+ outfile: bundle,+ bundle: true,+ platform: 'node',+ format: 'cjs',+ target: 'node22',+ external: ['electron']+ })+ await build({+ entryPoints: [join(fixture, 'preload.ts')],+ outfile: join(root, 'preload.cjs'),+ bundle: true,+ platform: 'node',+ format: 'cjs',+ external: ['electron']+ })+ await build({+ entryPoints: [join(desktop, 'src/test/pool-retirement-renderer.ts')],+ outfile: join(root, 'renderer.js'),+ bundle: true,+ platform: 'browser',+ format: 'iife',alias: { '@': join(desktop, 'src'), '@hermes/shared': join(repo, 'apps/shared/src') },- define: { 'import.meta.env': '{}', 'import.meta.hot': 'undefined' } })- writeFileSync(join(root, 'renderer.html'), '<!doctype html><meta charset="utf-8"><title>Retirement seam fixture</title><script src="./renderer.js"></script>')+ define: { 'import.meta.env': '{}', 'import.meta.hot': 'undefined' }+ })+ writeFileSync(+ join(root, 'renderer.html'),+ '<!doctype html><meta charset="utf-8"><title>Retirement seam fixture</title><script src="./renderer.js"></script>'+ )child = spawn(electron, [bundle, root, repo, python, fixture], {- cwd: root, env: isolatedEnv(root), stdio: ['ignore', 'pipe', 'pipe'],+ cwd: root,+ env: isolatedEnv(root),+ stdio: ['ignore', 'pipe', 'pipe']})// Capture the OS handle now; do not ask a disposed Electron dispatcher after quit.- child.stdout!.on('data', chunk => { output += String(chunk) })- child.stderr!.on('data', chunk => { output += String(chunk) })+ child.stdout!.on('data', chunk => {+ output += String(chunk)+ })+ child.stderr!.on('data', chunk => {+ output += String(chunk)+ })const code = await waitForExit(child, 180_000)assert.ok(existsSync(resultPath), `No native result (exit ${code}):\n${output}`)const result = JSON.parse(readFileSync(resultPath, 'utf8'))@@ -97,5 +143,6 @@ test.skipIf(process.env.HERMES_TEST_REAL_SERVE !== '1' || process.platform === 'rmSync(root, { recursive: true, force: true })}- }, 210_000,+ },+ 210_000)diff --git a/apps/desktop/electron/pool-spawn-coordinator.ts b/apps/desktop/electron/pool-spawn-coordinator.tsindex 48d0f792154..104b9c6428b 100644--- a/apps/desktop/electron/pool-spawn-coordinator.ts+++ b/apps/desktop/electron/pool-spawn-coordinator.ts@@ -160,7 +160,9 @@ export class LocalBackendSpawnCoordinator {onChange(listener: () => void): () => void {this.#listeners.add(listener)- return () => { this.#listeners.delete(listener) }+ return () => {+ this.#listeners.delete(listener)+ }}#changed(): void {diff --git a/apps/desktop/electron/pool-stop.test.ts b/apps/desktop/electron/pool-stop.test.tsindex b1024f4de2f..ae46f177ad0 100644--- a/apps/desktop/electron/pool-stop.test.ts+++ b/apps/desktop/electron/pool-stop.test.ts@@ -151,9 +151,11 @@ test('afterStop holds inFlight until extra teardown finishes (process-less SSH)'const pool = new Map<string, PoolStopEntry>()const events: string[] = []let releaseAfter: (() => void) | undefined+const afterGate = new Promise<void>(resolve => {releaseAfter = resolve})+const stopper = createPoolStopper({pool,stopChild: () => {@@ -178,6 +180,7 @@ test('afterStop holds inFlight until extra teardown finishes (process-less SSH)'assert.deepEqual(events, ['stop', 'exit', 'after-start'])let spawned = false+const respawn = (async () => {const dying = stopper.inFlight('ssh')@@ -225,11 +228,15 @@ test('a respawn can await the in-flight stop before reusing the key', async () =test('failed teardown blocks same-profile respawn until the actual late exit', async () => {const child = Object.assign(new EventEmitter(), { exitCode: null, signalCode: null })const pool = new Map([['profile', { process: child }]])+const stopper = createPoolStopper({pool,stopChild: () => {},- waitForExit: async () => { throw new Error('child did not exit') }+ waitForExit: async () => {+ throw new Error('child did not exit')+ }})+const stopping = stopper.stop('profile')await assert.rejects(stopping, /did not exit/)diff --git a/apps/desktop/electron/pool-stop.ts b/apps/desktop/electron/pool-stop.tsindex 047974dcb68..cc124906061 100644--- a/apps/desktop/electron/pool-stop.ts+++ b/apps/desktop/electron/pool-stop.ts@@ -78,9 +78,11 @@ export function createPoolStopper(deps: PoolStopperDeps): PoolStopper {stops.delete(key)}}+const stopping = (async () => {deps.stopChild(entry.process)await deps.waitForExit(entry.process)+if (deps.afterStop) {await deps.afterStop(key)}diff --git a/apps/desktop/electron/portal-session-live-fixture/main.ts b/apps/desktop/electron/portal-session-live-fixture/main.tsindex 23d7b648400..930ae2fc2ff 100644--- a/apps/desktop/electron/portal-session-live-fixture/main.ts+++ b/apps/desktop/electron/portal-session-live-fixture/main.ts@@ -122,7 +122,10 @@ async function run() {await jar.cookies.remove(base, accessName())mode = 'renew'const before = refreshes- const [first, second] = await Promise.all([portal.renewPortalAccessSilently(), portal.renewPortalAccessSilently()])+ const [first, second] = await Promise.all([+ portal.renewPortalAccessSilently(),+ portal.renewPortalAccessSilently()+ ])assert.equal(first, true)assert.equal(second, true)assert.equal(refreshes, before + 1)@@ -192,7 +195,9 @@ async function run() {assert.equal(await portal.renewPortalAccessSilently(), false)console.log('PORTAL_SESSION_LIVE_OK')} finally {- for (const window of BrowserWindow.getAllWindows()) {window.destroy()}+ for (const window of BrowserWindow.getAllWindows()) {+ window.destroy()+ }server.closeAllConnections()await new Promise<void>(resolve => server.close(() => resolve()))}diff --git a/apps/desktop/electron/portal-session-live.test.ts b/apps/desktop/electron/portal-session-live.test.tsindex 1fd3ad65751..67d6fc6204e 100644--- a/apps/desktop/electron/portal-session-live.test.ts+++ b/apps/desktop/electron/portal-session-live.test.ts@@ -19,7 +19,10 @@ const displayPrefix = (() => {return []}- const xvfbRun = (process.env.PATH ?? '').split(delimiter).map(dir => join(dir, 'xvfb-run')).find(existsSync)+ const xvfbRun = (process.env.PATH ?? '')+ .split(delimiter)+ .map(dir => join(dir, 'xvfb-run'))+ .find(existsSync)return xvfbRun ? [xvfbRun, '-a'] : null})()@@ -42,7 +45,9 @@ test.skipIf(displayPrefix === null)(const env: NodeJS.ProcessEnv = {}for (const name of ['PATH', 'SystemRoot', 'WINDIR', 'DISPLAY', 'WAYLAND_DISPLAY', 'XDG_RUNTIME_DIR']) {- if (process.env[name]) {env[name] = process.env[name]}+ if (process.env[name]) {+ env[name] = process.env[name]+ }}const electron: string = createRequire(import.meta.url)('electron')@@ -66,7 +71,9 @@ test.skipIf(displayPrefix === null)(// execFile's rejection carries only "Command failed"; Electron's real// reason (sandbox abort, missing libs, fixture assertion) is on stderr.const { stderr = '', stdout: partial = '' } = error as { stderr?: string; stdout?: string }- throw new Error(`Electron fixture failed.\n--- stdout ---\n${partial}\n--- stderr ---\n${stderr}`, { cause: error })+ throw new Error(`Electron fixture failed.\n--- stdout ---\n${partial}\n--- stderr ---\n${stderr}`, {+ cause: error+ })}expect(stdout).toContain('PORTAL_SESSION_LIVE_OK')diff --git a/apps/desktop/electron/pre-update-backup-config.test.ts b/apps/desktop/electron/pre-update-backup-config.test.tsindex 9d2ead15fa2..1c9391e1a01 100644--- a/apps/desktop/electron/pre-update-backup-config.test.ts+++ b/apps/desktop/electron/pre-update-backup-config.test.ts@@ -25,6 +25,7 @@ describe('readPreUpdateBackupEnabled', () => {['an environment-expanded off alias', '"off"', false]])('uses the effective config result for %s', async (_name, stdout, expected) => {const run = vi.fn().mockResolvedValue({ stdout })+const runtime = {command: '/runtime/python',args: ['-m', 'hermes_cli.main', 'config', 'get', 'updates.pre_update_backup', '--json'],diff --git a/apps/desktop/electron/preload.ts b/apps/desktop/electron/preload.tsindex 60df919d57e..844f20a1d41 100644--- a/apps/desktop/electron/preload.ts+++ b/apps/desktop/electron/preload.ts@@ -182,33 +182,39 @@ contextBridge.exposeInMainWorld('hermesDesktop', {}},// macOS native screenshot gesture; captures require a main-issued request.- screenshot: process.platform === 'darwin' ? {- getSettings: () => ipcRenderer.invoke('hermes:screenshot:settings:get'),- setEnabled: enabled => ipcRenderer.invoke('hermes:screenshot:settings:set', enabled),- openPermissionSettings: kind => ipcRenderer.invoke('hermes:screenshot:permission', kind),- capture: requestId => ipcRenderer.invoke('hermes:screenshot:capture', requestId),- onStatus: callback => {- const listener = (_event, status) => callback(status)- ipcRenderer.on('hermes:screenshot:status', listener)-- return () => ipcRenderer.removeListener('hermes:screenshot:status', listener)- },- onRequest: callback => {- const channel = 'hermes:screenshot:request'- const listener = (_event, requestId) => callback(requestId)- if (ipcRenderer.listenerCount(channel) === 0) {- ipcRenderer.send('hermes:screenshot:subscribe', true)- }- ipcRenderer.on(channel, listener)-- return () => {- ipcRenderer.removeListener(channel, listener)- if (ipcRenderer.listenerCount(channel) === 0) {- ipcRenderer.send('hermes:screenshot:subscribe', false)+ screenshot:+ process.platform === 'darwin'+ ? {+ getSettings: () => ipcRenderer.invoke('hermes:screenshot:settings:get'),+ setEnabled: enabled => ipcRenderer.invoke('hermes:screenshot:settings:set', enabled),+ openPermissionSettings: kind => ipcRenderer.invoke('hermes:screenshot:permission', kind),+ capture: requestId => ipcRenderer.invoke('hermes:screenshot:capture', requestId),+ onStatus: callback => {+ const listener = (_event, status) => callback(status)+ ipcRenderer.on('hermes:screenshot:status', listener)++ return () => ipcRenderer.removeListener('hermes:screenshot:status', listener)+ },+ onRequest: callback => {+ const channel = 'hermes:screenshot:request'+ const listener = (_event, requestId) => callback(requestId)++ if (ipcRenderer.listenerCount(channel) === 0) {+ ipcRenderer.send('hermes:screenshot:subscribe', true)+ }++ ipcRenderer.on(channel, listener)++ return () => {+ ipcRenderer.removeListener(channel, listener)++ if (ipcRenderer.listenerCount(channel) === 0) {+ ipcRenderer.send('hermes:screenshot:subscribe', false)+ }+ }+ }}- }- }- } : undefined,+ : undefined,// Quick Entry: the global-hotkey mini composer window. Main owns the OS// shortcut + the persisted preference; the quick window only captures text// and hands it back, and the primary renderer submits it through the normaldiff --git a/apps/desktop/electron/quit-finalization.test.ts b/apps/desktop/electron/quit-finalization.test.tsindex 15e4e18a5bd..0f5e9ec3944 100644--- a/apps/desktop/electron/quit-finalization.test.ts+++ b/apps/desktop/electron/quit-finalization.test.ts@@ -14,6 +14,7 @@ import { createQuitFinalization } from './quit-finalization'test('forces a single Windows exit once the admitted quit exceeds its deadline; never arms off Windows', () => {let onTimeout: (() => void) | undefinedconst hardExit = vi.fn()+const finalization = createQuitFinalization({isWindows: true,schedule: callback => {@@ -42,11 +43,13 @@ test('a completed quit cancels the fallback and it never re-arms', () => {let onTimeout: (() => void) | undefinedconst cancel = vi.fn()const hardExit = vi.fn()+const schedule = vi.fn((callback: () => void) => {onTimeout = callbackreturn 'timer'})+const finalization = createQuitFinalization({ isWindows: true, schedule, cancel, hardExit })finalization.arm()diff --git a/apps/desktop/electron/remote-lifecycle.test.ts b/apps/desktop/electron/remote-lifecycle.test.tsindex e8723467115..9a8c0ba87c3 100644--- a/apps/desktop/electron/remote-lifecycle.test.ts+++ b/apps/desktop/electron/remote-lifecycle.test.ts@@ -1579,15 +1579,8 @@ test('buildSpawnCommand scopes umask 077 to the mkdir subshell (no leak into ser// umask 077 must apply only to the reservation-parent mkdir. A bare// umask call at the top level leaks 077 into the rest of the payload,// so the detached setsid backend inherits 077 instead of the login umask.- assert.ok(- cmd.includes('(umask 077 && mkdir -p'),- 'umask 077 must be scoped to a mkdir subshell'- )- assert.doesNotMatch(- cmd,- /(^|[^(])umask 077/,- 'no bare umask 077 may leak into the spawn chain'- )+ assert.ok(cmd.includes('(umask 077 && mkdir -p'), 'umask 077 must be scoped to a mkdir subshell')+ assert.doesNotMatch(cmd, /(^|[^(])umask 077/, 'no bare umask 077 may leak into the spawn chain')assert.ok(cmd.indexOf('(umask 077') < cmd.indexOf('serve --isolated'),'scoped mkdir must still precede the serve spawn'@@ -1889,33 +1882,36 @@ test('remote SSH ownership capability requires both secure bootstrap flags', asyassert.equal(await remoteSupportsSshOwnership(unsupported, '/x/hermes'), false)})-test.skipIf(process.platform === 'win32')('capability probe survives a zsh login shell on the remote (#111949)', async t => {- // sshd runs the remote command under the account's LOGIN shell. A bare- // `set -m` is fatal in a non-interactive zsh, so the watchdog-wrapped probe- // used to return nothing and a current remote was reported as unsupported.- const zsh = await exec('command -v zsh || true').then(r => r.stdout.trim())-- // CI installs zsh (js-tests.yml); locally a missing zsh must show as a- // skip, not a pass, or a wrapper regression stays green unnoticed.- if (!zsh) {- t.skip('zsh not installed')-- return- }+test.skipIf(process.platform === 'win32')(+ 'capability probe survives a zsh login shell on the remote (#111949)',+ async t => {+ // sshd runs the remote command under the account's LOGIN shell. A bare+ // `set -m` is fatal in a non-interactive zsh, so the watchdog-wrapped probe+ // used to return nothing and a current remote was reported as unsupported.+ const zsh = await exec('command -v zsh || true').then(r => r.stdout.trim())++ // CI installs zsh (js-tests.yml); locally a missing zsh must show as a+ // skip, not a pass, or a wrapper regression stays green unnoticed.+ if (!zsh) {+ t.skip('zsh not installed')++ return+ }- const dir = await mkdtemp(path.join(os.tmpdir(), 'hermes-zsh-probe-'))+ const dir = await mkdtemp(path.join(os.tmpdir(), 'hermes-zsh-probe-'))- try {- const hermes = path.join(dir, 'hermes')- await writeFile(hermes, '#!/bin/sh\necho "--ssh-session-token-file --ssh-owner-nonce"\n', { mode: 0o700 })+ try {+ const hermes = path.join(dir, 'hermes')+ await writeFile(hermes, '#!/bin/sh\necho "--ssh-session-token-file --ssh-owner-nonce"\n', { mode: 0o700 })- const ssh = { exec: async (command: string) => (await exec(command, { shell: zsh })).stdout }+ const ssh = { exec: async (command: string) => (await exec(command, { shell: zsh })).stdout }- assert.equal(await remoteSupportsSshOwnership(ssh, hermes), true)- } finally {- await rm(dir, { recursive: true, force: true })+ assert.equal(await remoteSupportsSshOwnership(ssh, hermes), true)+ } finally {+ await rm(dir, { recursive: true, force: true })+ }}-})+)test('probes run under the remote watchdog so a hung CLI cannot orphan (#110478)', async () => {let versionProbe = ''@@ -1949,7 +1945,10 @@ test('probes run under the remote watchdog so a hung CLI cannot orphan (#110478)assert.equal(await remoteSupportsSshOwnership(helpSsh, '/x/hermes'), true)assert.ok(helpProbe.includes('kill -9'), 'ownership probe wrapped in the remote watchdog')- assert.ok(/\$\(.*\(.*serve --help.*\) <\/dev\/null &/.test(helpProbe), 'watchdog nested around the inner serve --help')+ assert.ok(+ /\$\(.*\(.*serve --help.*\) <\/dev\/null &/.test(helpProbe),+ 'watchdog nested around the inner serve --help'+ )})test('cleanupStale escalates to SIGKILL when the backend survives the graceful wait (#91668 quit-during-active-turn)', async () => {@@ -2088,7 +2087,10 @@ test('connect() does not declare a live dashboard dead when the liveness probe aassert.equal(result.reused, false)assert.equal(result.pid, 777)- assert.ok(!ssh.calls.some(c => /(^|[^-\d])kill(?: -\w+)? 777\b/.test(c) && !/kill -0/.test(c)), 'must not reap a live backend')+ assert.ok(+ !ssh.calls.some(c => /(^|[^-\d])kill(?: -\w+)? 777\b/.test(c) && !/kill -0/.test(c)),+ 'must not reap a live backend'+ )})test('cleanupStale reaps after one lost ownership answer and keeps the lockfile when none ever settles', async () => {@@ -2100,7 +2102,10 @@ test('cleanupStale reaps after one lost ownership answer and keeps the lockfile])await cleanupStale(flaky, OWNERSHIP_ID, ownedLock({ pid: 777 }))- assert.ok(flaky.calls.some(c => /kill 777 &&/.test(c)), 'must reap the owned backend')+ assert.ok(+ flaky.calls.some(c => /kill 777 &&/.test(c)),+ 'must reap the owned backend'+ )assert.ok(flaky.calls.some(c => /rm -f .*backend\.lock\.json/.test(c)))const silent = fakeSsh([[/print\("OWNED"/, '']])@@ -2110,8 +2115,14 @@ test('cleanupStale reaps after one lost ownership answer and keeps the lockfile(error: any) => error.kind === 'transient-transport-error')- assert.ok(!silent.calls.some(c => /(^|[^-\d])kill(?: -\w+)? 777\b/.test(c) && !/kill -0/.test(c)), 'must not kill unproven')- assert.ok(!silent.calls.some(c => /rm -f .*backend\.lock\.json/.test(c)), 'record must survive for the next connect to reap')+ assert.ok(+ !silent.calls.some(c => /(^|[^-\d])kill(?: -\w+)? 777\b/.test(c) && !/kill -0/.test(c)),+ 'must not kill unproven'+ )+ assert.ok(+ !silent.calls.some(c => /rm -f .*backend\.lock\.json/.test(c)),+ 'record must survive for the next connect to reap'+ )})test('connect() post-spawn cleanup that cannot prove ownership keeps the original boot error', async () => {@@ -2132,9 +2143,19 @@ test('connect() post-spawn cleanup that cannot prove ownership keeps the origina])await assert.rejects(- connect(connectDeps(ssh, { platform: { os: 'Linux', arch: 'x86_64' }, waitForHermes: async () => { throw boot } })),+ connect(+ connectDeps(ssh, {+ platform: { os: 'Linux', arch: 'x86_64' },+ waitForHermes: async () => {+ throw boot+ }+ })+ ),(error: any) => error === boot && error.cleanupCause?.kind === 'transient-transport-error')- assert.ok(!ssh.calls.some(c => /rm -f .*backend\.lock\.json/.test(c)), 'record must survive for the next connect to reap')+ assert.ok(+ !ssh.calls.some(c => /rm -f .*backend\.lock\.json/.test(c)),+ 'record must survive for the next connect to reap'+ )})diff --git a/apps/desktop/electron/remote-lifecycle.ts b/apps/desktop/electron/remote-lifecycle.tsindex 414080bab2f..e6c77f8fe68 100644--- a/apps/desktop/electron/remote-lifecycle.ts+++ b/apps/desktop/electron/remote-lifecycle.ts@@ -408,7 +408,13 @@ async function readRemoteInstallId(ssh) {throw error}- const id = String(out || '').trim().split('\n').pop()?.trim().toLowerCase() ?? ''+ const id =+ String(out || '')+ .trim()+ .split('\n')+ .pop()+ ?.trim()+ .toLowerCase() ?? ''// Same shape check the minting side guarantees; anything else is not an identity.return /^[0-9a-f]{32}$/.test(id) ? id : undefined@@ -650,51 +656,51 @@ async function pidIsOurDashboard(}const script =- 'import os,shlex,subprocess,sys\n' +- `pid=${Number(pid)}\n` +- `expected=os.path.expanduser(${shq(hermesPath)})\n` +- // The installer-facing launcher is intentionally preserved for invocation- // (#74411), but it may `exec python <install-dir>/hermes`, leaving neither- // launcher nor HERMES_HOME-derived entrypoint in argv. The ownership-scoped- // token path + random nonce + exact profile below are the alternative proof.- `hermes_home=os.path.expanduser(${shq(hermesHome)}) if ${shq(hermesHome)} else ""\n` +- 'expected_entries={expected}\n' +- 'if hermes_home:\n' +- ' expected_entries.add(os.path.join(hermes_home,"hermes-agent","venv","bin","hermes"))\n' +- `expected_token=os.path.expanduser(${shq(ownershipId ? spawnTokenPath(ownershipId, spawnNonce) : '')})\n` +- `expected_profile=${shq(profile)}\n` +- `nonce=${shq(spawnNonce)}\n` +- 'try:\n' +- ' raw=open(f"/proc/{pid}/cmdline","rb").read()\n' +- ' args=[x.decode("utf-8","surrogateescape") for x in raw.split(b"\\0") if x]\n' +- 'except OSError:\n' +- ' try:\n' +- ' line=subprocess.check_output(["ps","-ww","-o","command=","-p",str(pid)],text=True).strip()\n' +- ' except subprocess.CalledProcessError:\n' +- ' # pid already gone — a dead process is FOREIGN, not a transport error\n' +- ' print("FOREIGN");sys.exit(0)\n' +- ' args=shlex.split(line)\n' +- 'ok=False\n' +- 'try:\n' +- ' serve=args.index("serve")\n' +- ' owner=args.index("--ssh-owner-nonce",serve+1)\n' +- ' token=args.index("--ssh-session-token-file",serve+1) if expected_token else -1\n' +- ' isolated=args.index("--isolated",serve+1)\n' +- ' profile_arg=args.index("--profile") if expected_profile else -1\n' +- ' serve_count=args.count("serve")\n' +- ' owner_count=args.count("--ssh-owner-nonce")\n' +- ' token_count=args.count("--ssh-session-token-file")\n' +- ' isolated_count=args.count("--isolated")\n' +- ' profile_count=args.count("--profile")\n' +- ' direct=args[0] in expected_entries\n' +- ' python_entry=len(args)>1 and args[1] in expected_entries and os.path.basename(args[0]).startswith("python")\n' +- ' token_ok=not expected_token or args[token+1]==expected_token\n' +- ' isolated_ok=isolated_count==1 and isolated>serve\n' +- ' profile_ok=(profile_count==1 and profile_arg<serve and args[profile_arg+1]==expected_profile) if expected_profile else profile_count==0\n' +- ' spawn_proof=bool(expected_token) and owner_count==1 and token_count==1 and token_ok and profile_ok\n' +- ' ok=(direct or python_entry or spawn_proof) and serve_count==1 and isolated_ok and owner_count==1 and args[owner+1]==nonce and token_ok and profile_ok\n' +- 'except (ValueError,IndexError):pass\n' +- 'print("OWNED" if ok else "FOREIGN")'+ 'import os,shlex,subprocess,sys\n' ++ `pid=${Number(pid)}\n` ++ `expected=os.path.expanduser(${shq(hermesPath)})\n` ++ // The installer-facing launcher is intentionally preserved for invocation+ // (#74411), but it may `exec python <install-dir>/hermes`, leaving neither+ // launcher nor HERMES_HOME-derived entrypoint in argv. The ownership-scoped+ // token path + random nonce + exact profile below are the alternative proof.+ `hermes_home=os.path.expanduser(${shq(hermesHome)}) if ${shq(hermesHome)} else ""\n` ++ 'expected_entries={expected}\n' ++ 'if hermes_home:\n' ++ ' expected_entries.add(os.path.join(hermes_home,"hermes-agent","venv","bin","hermes"))\n' ++ `expected_token=os.path.expanduser(${shq(ownershipId ? spawnTokenPath(ownershipId, spawnNonce) : '')})\n` ++ `expected_profile=${shq(profile)}\n` ++ `nonce=${shq(spawnNonce)}\n` ++ 'try:\n' ++ ' raw=open(f"/proc/{pid}/cmdline","rb").read()\n' ++ ' args=[x.decode("utf-8","surrogateescape") for x in raw.split(b"\\0") if x]\n' ++ 'except OSError:\n' ++ ' try:\n' ++ ' line=subprocess.check_output(["ps","-ww","-o","command=","-p",str(pid)],text=True).strip()\n' ++ ' except subprocess.CalledProcessError:\n' ++ ' # pid already gone — a dead process is FOREIGN, not a transport error\n' ++ ' print("FOREIGN");sys.exit(0)\n' ++ ' args=shlex.split(line)\n' ++ 'ok=False\n' ++ 'try:\n' ++ ' serve=args.index("serve")\n' ++ ' owner=args.index("--ssh-owner-nonce",serve+1)\n' ++ ' token=args.index("--ssh-session-token-file",serve+1) if expected_token else -1\n' ++ ' isolated=args.index("--isolated",serve+1)\n' ++ ' profile_arg=args.index("--profile") if expected_profile else -1\n' ++ ' serve_count=args.count("serve")\n' ++ ' owner_count=args.count("--ssh-owner-nonce")\n' ++ ' token_count=args.count("--ssh-session-token-file")\n' ++ ' isolated_count=args.count("--isolated")\n' ++ ' profile_count=args.count("--profile")\n' ++ ' direct=args[0] in expected_entries\n' ++ ' python_entry=len(args)>1 and args[1] in expected_entries and os.path.basename(args[0]).startswith("python")\n' ++ ' token_ok=not expected_token or args[token+1]==expected_token\n' ++ ' isolated_ok=isolated_count==1 and isolated>serve\n' ++ ' profile_ok=(profile_count==1 and profile_arg<serve and args[profile_arg+1]==expected_profile) if expected_profile else profile_count==0\n' ++ ' spawn_proof=bool(expected_token) and owner_count==1 and token_count==1 and token_ok and profile_ok\n' ++ ' ok=(direct or python_entry or spawn_proof) and serve_count==1 and isolated_ok and owner_count==1 and args[owner+1]==nonce and token_ok and profile_ok\n' ++ 'except (ValueError,IndexError):pass\n' ++ 'print("OWNED" if ok else "FOREIGN")'const verdict = await execProbeVerdict(ssh,diff --git a/apps/desktop/electron/remote-ws-headers.ts b/apps/desktop/electron/remote-ws-headers.tsindex d66bdeb5371..5fae666f18a 100644--- a/apps/desktop/electron/remote-ws-headers.ts+++ b/apps/desktop/electron/remote-ws-headers.ts@@ -32,9 +32,7 @@ export interface RemoteHeaderSource {interface SessionLike {webRequest?: {- onBeforeSendHeaders?: (- listener: (details: RemoteRequestDetails, callback: RemoteRequestCallback) => void- ) => void+ onBeforeSendHeaders?: (listener: (details: RemoteRequestDetails, callback: RemoteRequestCallback) => void) => void}}diff --git a/apps/desktop/electron/renderer-bundle.ts b/apps/desktop/electron/renderer-bundle.tsindex 6b87bc52de6..f2ae4af46c8 100644--- a/apps/desktop/electron/renderer-bundle.ts+++ b/apps/desktop/electron/renderer-bundle.ts@@ -87,12 +87,16 @@ function manifestAssetRefs(try {const manifest = JSON.parse(readFileSync(path.join(path.dirname(indexPath), 'renderer-manifest.json'), 'utf8'))- if (!manifest || typeof manifest !== 'object' || Array.isArray(manifest)) {return null}+ if (!manifest || typeof manifest !== 'object' || Array.isArray(manifest)) {+ return null+ }const entry = manifest['index.html']const normalize = (ref: string) => ref.replace(/^\.?\//, '')- if (!entry?.isEntry || !bootRefs.map(normalize).includes(entry.file)) {return null}+ if (!entry?.isEntry || !bootRefs.map(normalize).includes(entry.file)) {+ return null+ }const refs = new Set<string>()@@ -100,7 +104,9 @@ function manifestAssetRefs(typeof ref === 'string' && ref.length > 0 && !/^[a-z]+:|^[/\\]/i.test(ref) && !ref.split(/[/\\]/).includes('..')for (const chunk of Object.values(manifest) as Record<string, unknown>[]) {- if (!chunk || typeof chunk !== 'object' || !localRef(chunk.file)) {return null}+ if (!chunk || typeof chunk !== 'object' || !localRef(chunk.file)) {+ return null+ }refs.add(chunk.file)@@ -115,13 +121,19 @@ function manifestAssetRefs(for (const key of ['css', 'assets']) {const assets = chunk[key] ?? []- if (!Array.isArray(assets) || !assets.every(localRef)) {return null}+ if (!Array.isArray(assets) || !assets.every(localRef)) {+ return null+ }- for (const ref of assets) {refs.add(ref)}+ for (const ref of assets) {+ refs.add(ref)+ }}}- if (!bootRefs.every(ref => refs.has(normalize(ref)))) {return null}+ if (!bootRefs.every(ref => refs.has(normalize(ref)))) {+ return null+ }return [...refs]} catch {diff --git a/apps/desktop/electron/renderer-heap-flags.test.ts b/apps/desktop/electron/renderer-heap-flags.test.tsindex 0193181a72d..85e0dfbd315 100644--- a/apps/desktop/electron/renderer-heap-flags.test.ts+++ b/apps/desktop/electron/renderer-heap-flags.test.ts@@ -22,7 +22,10 @@ describe('renderer heap flags', () => {].join('\n'))- expect(cfg).toEqual({ electronFlags: ['--ozone-platform=x11', '--js-flags=--expose-gc'], rendererMaxOldSpaceMb: 2048 })+ expect(cfg).toEqual({+ electronFlags: ['--ozone-platform=x11', '--js-flags=--expose-gc'],+ rendererMaxOldSpaceMb: 2048+ })expect(planLaunchSwitches(cfg)).toEqual([{ name: 'ozone-platform', value: 'x11' },{ name: 'js-flags', value: '--expose-gc --max-old-space-size=2048' }@@ -32,7 +35,9 @@ describe('renderer heap flags', () => {})it('merges with a js-flags switch already on argv instead of overwriting it', () => {- const cfg = readDesktopLaunchConfig('desktop:\n electron_flags: [--disable-gpu]\n renderer_max_old_space_mb: 1536\n')+ const cfg = readDesktopLaunchConfig(+ 'desktop:\n electron_flags: [--disable-gpu]\n renderer_max_old_space_mb: 1536\n'+ )const planned = planLaunchSwitches(cfg, ['/app/hermes', '--js-flags=--expose-gc', '--disable-gpu'])// --disable-gpu is already on the launcher's argv: not re-applied.diff --git a/apps/desktop/electron/renderer-heap-flags.ts b/apps/desktop/electron/renderer-heap-flags.tsindex d499297f5f1..dd8691df12c 100644--- a/apps/desktop/electron/renderer-heap-flags.ts+++ b/apps/desktop/electron/renderer-heap-flags.ts@@ -42,12 +42,7 @@ export function readDesktopLaunchConfig(yamlText: string): DesktopLaunchConfig {const blockLines: string[] = []- const splitFlow = (raw: string) =>- raw- .slice(1, -1)- .split(',')- .map(unquote)- .filter(Boolean)+ const splitFlow = (raw: string) => raw.slice(1, -1).split(',').map(unquote).filter(Boolean)for (let i = start + 1; i < lines.length; i += 1) {const line = lines[i]@@ -138,7 +133,11 @@ export function planLaunchSwitches(cfg: DesktopLaunchConfig, argv: readonly striconst [, name, value] = matchif (name === 'js-flags') {- jsFlagParts.push(...String(value ?? '').split(/\s+/).filter(Boolean))+ jsFlagParts.push(+ ...String(value ?? '')+ .split(/\s+/)+ .filter(Boolean)+ )return}diff --git a/apps/desktop/electron/session-windows.ts b/apps/desktop/electron/session-windows.tsindex 8785b04d4dc..877297f248d 100644--- a/apps/desktop/electron/session-windows.ts+++ b/apps/desktop/electron/session-windows.ts@@ -95,7 +95,13 @@ interface InstanceWindowUrlOptions extends Partial<DesktopWindowLaunch> {rendererIndexPath?: string}-function buildInstanceWindowUrl({ connectionId, devServer, profile, profileWindow, rendererIndexPath }: InstanceWindowUrlOptions = {}) {+function buildInstanceWindowUrl({+ connectionId,+ devServer,+ profile,+ profileWindow,+ rendererIndexPath+}: InstanceWindowUrlOptions = {}) {const query = `?peer=1${profile ? `&profile=${encodeURIComponent(profile)}&connectionId=${encodeURIComponent(connectionId ?? '')}${profileWindow ? '&profileWindow=1' : ''}` : ''}`if (devServer) {diff --git a/apps/desktop/electron/ssh-bootstrap-coordinator.test.ts b/apps/desktop/electron/ssh-bootstrap-coordinator.test.tsindex 0e9549658ab..ae4daf60ede 100644--- a/apps/desktop/electron/ssh-bootstrap-coordinator.test.ts+++ b/apps/desktop/electron/ssh-bootstrap-coordinator.test.ts@@ -212,10 +212,13 @@ test('cancelAndWait keeps the drain up through afterCancel teardown', async () =const coordinator = createBootstrapCoordinator()const events: string[] = []let releaseAfter: (() => void) | undefined+const afterGate = new Promise<void>(resolve => {releaseAfter = resolve})+let teardownStarted: (() => void) | undefined+const started = new Promise<void>(resolve => {teardownStarted = resolve})@@ -228,6 +231,7 @@ test('cancelAndWait keeps the drain up through afterCancel teardown', async () =})await started+const next = coordinator.start('scope', 'new', async () => {events.push('new-start')@@ -289,6 +293,7 @@ test('a second cancelAndWait on the same scope composes with the teardown stillawait teardownStarted.promiseconst apply = coordinator.cancelAndWait('scope').then(() => events.push('apply-drained'))+const next = coordinator.start('scope', 'new', async () => {events.push('new-start')diff --git a/apps/desktop/electron/ssh-bootstrap-coordinator.ts b/apps/desktop/electron/ssh-bootstrap-coordinator.tsindex 57586214938..9b062eac8bf 100644--- a/apps/desktop/electron/ssh-bootstrap-coordinator.ts+++ b/apps/desktop/electron/ssh-bootstrap-coordinator.ts@@ -99,6 +99,7 @@ function createBootstrapCoordinator() {const own = new Promise<void>(resolve => {release = resolve})+// Compose with any drain already in flight for this scope (a pool stop// still tearing down SSH while a connection apply cancels the same scope):// start() must wait for every active teardown, and the map entry is@@ -126,6 +127,7 @@ function createBootstrapCoordinator() {// drain barrier still prevents stale resurrection.await Promise.allSettled(entries.flatMap(entry => [...entry.forceCleanups]).map(cleanup => cleanup()))await Promise.allSettled(entries.map(entry => entry.promise))+// Keep the drain up through caller teardown (SSH keepalive / tunnel)// so a replacement start() cannot publish before the old scope is gone.if (afterCancel) {diff --git a/apps/desktop/electron/ssh-connection.test.ts b/apps/desktop/electron/ssh-connection.test.tsindex 6da72f6148e..fe277e9b73b 100644--- a/apps/desktop/electron/ssh-connection.test.ts+++ b/apps/desktop/electron/ssh-connection.test.ts@@ -1074,24 +1074,27 @@ test('stopTunnelChild waits for process exit', async () => {assert.equal(stopped, true)})-test.skipIf(process.platform === 'win32')('withRemoteTimeout runs a healthy probe under a zsh login shell (#111949)', async t => {- // SSH runs the remote command through the account's login shell. In- // non-interactive zsh, a bare `set -m` is fatal, so the wrapper must still- // run a healthy probe rather than reporting the remote as unsupported.- const zsh = await execFileAsync('sh', ['-c', 'command -v zsh || true']).then(r => r.stdout.trim())+test.skipIf(process.platform === 'win32')(+ 'withRemoteTimeout runs a healthy probe under a zsh login shell (#111949)',+ async t => {+ // SSH runs the remote command through the account's login shell. In+ // non-interactive zsh, a bare `set -m` is fatal, so the wrapper must still+ // run a healthy probe rather than reporting the remote as unsupported.+ const zsh = await execFileAsync('sh', ['-c', 'command -v zsh || true']).then(r => r.stdout.trim())++ // CI installs zsh (js-tests.yml); locally a missing zsh must show as a+ // skip, not a pass, or a wrapper regression stays green unnoticed.+ if (!zsh) {+ t.skip('zsh not installed')- // CI installs zsh (js-tests.yml); locally a missing zsh must show as a- // skip, not a pass, or a wrapper regression stays green unnoticed.- if (!zsh) {- t.skip('zsh not installed')-- return- }+ return+ }- const { stdout: zshStdout } = await execFileAsync(zsh, ['-fc', withRemoteTimeout('echo zsh-ok', 5)])+ const { stdout: zshStdout } = await execFileAsync(zsh, ['-fc', withRemoteTimeout('echo zsh-ok', 5)])- assert.equal(zshStdout, 'zsh-ok\n')-})+ assert.equal(zshStdout, 'zsh-ok\n')+ }+)test('withRemoteTimeout kills a hung probe remotely instead of orphaning it (#110478)', async () => {if (process.platform === 'win32') {@@ -1158,7 +1161,10 @@ test('withRemoteTimeout kills a hung probe remotely instead of orphaning it (#11assert.ok(err2 && err2.code !== 0, 'hung launcher must exit non-zero')- const { stdout: grandStrays } = await execFileAsync('sh', ['-c', `ps -eo args | grep "[s]leep ${grandSecs}$" || true`])+ const { stdout: grandStrays } = await execFileAsync('sh', [+ '-c',+ `ps -eo args | grep "[s]leep ${grandSecs}$" || true`+ ])assert.equal(grandStrays.trim(), '', 'watchdog killed the launcher’s grandchild too')}diff --git a/apps/desktop/electron/ssh-isolated-keepalive.test.ts b/apps/desktop/electron/ssh-isolated-keepalive.test.tsindex dd2aa9a3e95..f35785955f1 100644--- a/apps/desktop/electron/ssh-isolated-keepalive.test.ts+++ b/apps/desktop/electron/ssh-isolated-keepalive.test.ts@@ -48,6 +48,7 @@ describe('ssh-isolated keep-alive registry (#106935)', () => {it('holds an open WebSocket per scope until that scope stops, then never reconnects it', async () => {const { createSshIsolatedKeepaliveRegistry } = await import('./ssh-isolated-keepalive')const { FakeWs, instances } = makeFakeWs()+const registry = createSshIsolatedKeepaliveRegistry({WebSocketImpl: FakeWs,reconnectDelayMs: 25diff --git a/apps/desktop/electron/ssh-isolated-keepalive.ts b/apps/desktop/electron/ssh-isolated-keepalive.tsindex 59677db4fcd..477049904c7 100644--- a/apps/desktop/electron/ssh-isolated-keepalive.ts+++ b/apps/desktop/electron/ssh-isolated-keepalive.ts@@ -40,6 +40,7 @@ const MAX_RECONNECT_DELAY_MS = 30_000function addListener(socket: any, type: string, handler: (event?: any) => void) {if (typeof socket?.addEventListener === 'function') {socket.addEventListener(type, handler)+return}@@ -51,6 +52,7 @@ function addListener(socket: any, type: string, handler: (event?: any) => void)export function createSshIsolatedKeepaliveRegistry(options: SshIsolatedKeepaliveOptions = {}) {const WebSocketImpl ='WebSocketImpl' in options ? options.WebSocketImpl : (globalThis as { WebSocket?: unknown }).WebSocket+const buildWsUrl = options.buildWsUrl ?? buildGatewayWsUrlconst log = options.logconst reconnectDelayMs = options.reconnectDelayMs ?? DEFAULT_RECONNECT_DELAY_MS@@ -111,6 +113,7 @@ export function createSshIsolatedKeepaliveRegistry(options: SshIsolatedKeepalive} catch (error) {log?.(`[ssh] keep-alive WS failed to open for ${entry.scope}: ${error instanceof Error ? error.message : error}`)scheduleReconnect(entry)+return}@@ -157,6 +160,7 @@ export function createSshIsolatedKeepaliveRegistry(options: SshIsolatedKeepalivesocket: null,target: { baseUrl, token }}+entries.set(scope, entry)connect(entry)}@@ -185,6 +189,7 @@ export function createSshIsolatedKeepaliveRegistry(options: SshIsolatedKeepalivefunction openUrl(scope: string) {const url = entries.get(scope)?.socket?.url+return typeof url === 'string' ? url : null}diff --git a/apps/desktop/electron/update-api-check.test.ts b/apps/desktop/electron/update-api-check.test.tsindex 83991b9a7e0..ec7edeee9c2 100644--- a/apps/desktop/electron/update-api-check.test.ts+++ b/apps/desktop/electron/update-api-check.test.ts@@ -136,17 +136,26 @@ test('resolveBehindLocally: unreachable tip is unknown, reachable tip is ahead,// A tip missing from the object database (truly stale checkout) stays unknown.const stale = fakeGit({ 'cat-file': { code: 1 } })assert.equal(await resolveBehindLocally(stale.runGit, '/repo', SHA_A, SHA_B), null)- assert.deepEqual(stale.calls.map(args => args[0]), ['cat-file'])+ assert.deepEqual(+ stale.calls.map(args => args[0]),+ ['cat-file']+ )// The remote tip reachable from HEAD is a local commit AHEAD, not an update.const ahead = fakeGit({})assert.equal(await resolveBehindLocally(ahead.runGit, '/repo', SHA_A, SHA_B), 0)- assert.deepEqual(ahead.calls.map(args => args[0]), ['cat-file', 'merge-base'])+ assert.deepEqual(+ ahead.calls.map(args => args[0]),+ ['cat-file', 'merge-base']+ )// Otherwise the honest local count of HEAD..tip (merge-base must fail first).const behind = fakeGit({ 'merge-base': { code: 1 }, 'rev-list': { code: 0, stdout: '3\n' } })assert.equal(await resolveBehindLocally(behind.runGit, '/repo', SHA_A, SHA_B), 3)- assert.deepEqual(behind.calls.map(args => args[0]), ['cat-file', 'merge-base', 'rev-list'])+ assert.deepEqual(+ behind.calls.map(args => args[0]),+ ['cat-file', 'merge-base', 'rev-list']+ )// A git failure mid-walk is never silently read as zero.const broken = fakeGit({ 'merge-base': { code: 1 }, 'rev-list': { code: 128 } })@@ -156,6 +165,7 @@ test('resolveBehindLocally: unreachable tip is unknown, reachable tip is ahead,test('listLocalCommits renders the local gap newest-first in the parseCompare shape', async () => {const OLDEST = '1'.repeat(40)const NEWEST = '2'.repeat(40)+const gitLog = fakeGit({log: {code: 0,diff --git a/apps/desktop/electron/update-api-check.ts b/apps/desktop/electron/update-api-check.tsindex 61f340ea465..84f9f561a4c 100644--- a/apps/desktop/electron/update-api-check.ts+++ b/apps/desktop/electron/update-api-check.ts@@ -157,7 +157,8 @@ export function describeUpdateCheckFailure(error: UpdateCheckFailure | null | unif ((status === 403 || status === 429) && error?.rateLimitRemaining === 0) {const resetMs = typeof error.rateLimitReset === 'number' ? error.rateLimitReset * 1000 - now : NaNconst minutes = Number.isFinite(resetMs) && resetMs > 0 ? Math.ceil(resetMs / 60_000) : null- const when = minutes === null ? 'within an hour' : minutes === 1 ? 'in about a minute' : `in about ${minutes} minutes`+ const when =+ minutes === null ? 'within an hour' : minutes === 1 ? 'in about a minute' : `in about ${minutes} minutes`return error.authenticated? `GitHub API rate limit reached for your GITHUB_TOKEN (HTTP ${status}) — it resets ${when}.`@@ -194,7 +195,10 @@ export function describeUpdateCheckFailure(error: UpdateCheckFailure | null | un}/** A git command runner — main.ts injects its runGit; tests inject a fake. */-export type GitRunner = (args: string[], options?: { cwd?: string }) => Promise<{+export type GitRunner = (+ args: string[],+ options?: { cwd?: string }+) => Promise<{code: numberstdout: stringstderr: stringdiff --git a/apps/desktop/electron/window-below.test.ts b/apps/desktop/electron/window-below.test.tsindex 5dcb741d848..c676c84ac7e 100644--- a/apps/desktop/electron/window-below.test.ts+++ b/apps/desktop/electron/window-below.test.ts@@ -152,14 +152,22 @@ describe('resolveOutsideAsar', () => {// land on the unpacked copy electron-builder ships beside it.it('redirects a packaged specifier into app.asar.unpacked', () => {expect(- resolveOutsideAsar('file:///Applications/Hermes.app/Contents/Resources/app.asar/dist/node_modules/get-windows/index.js')- ).toBe('file:///Applications/Hermes.app/Contents/Resources/app.asar.unpacked/dist/node_modules/get-windows/index.js')+ resolveOutsideAsar(+ 'file:///Applications/Hermes.app/Contents/Resources/app.asar/dist/node_modules/get-windows/index.js'+ )+ ).toBe(+ 'file:///Applications/Hermes.app/Contents/Resources/app.asar.unpacked/dist/node_modules/get-windows/index.js'+ )})// The staged specifier is built with path.join, so on Windows the archive// segment is delimited by backslashes, not the slashes a file: URL has.it('redirects a Windows packaged path built with backslashes', () => {- expect(resolveOutsideAsar('C:\\Users\\me\\AppData\\Local\\Hermes\\resources\\app.asar\\dist\\node_modules\\get-windows\\index.js')).toBe(+ expect(+ resolveOutsideAsar(+ 'C:\\Users\\me\\AppData\\Local\\Hermes\\resources\\app.asar\\dist\\node_modules\\get-windows\\index.js'+ )+ ).toBe('C:\\Users\\me\\AppData\\Local\\Hermes\\resources\\app.asar.unpacked\\dist\\node_modules\\get-windows\\index.js')})diff --git a/apps/desktop/electron/window-below.ts b/apps/desktop/electron/window-below.tsindex ca22056bc94..5f0477d565a 100644--- a/apps/desktop/electron/window-below.ts+++ b/apps/desktop/electron/window-below.ts@@ -189,9 +189,8 @@ const loadGetWindows = (): Promise<GetWindowsModule | EnumerationFailure> => {// the CJS loader, which this ESM main process never does (every import// here is `from 'node:child_process'`). Pointing the import at the// unpacked copy gives get-windows a real path to derive from.- const staged = resolveOutsideAsar(- path.join(app.getAppPath(), 'dist', 'node_modules', 'get-windows', 'index.js')- )+ const staged = resolveOutsideAsar(path.join(app.getAppPath(), 'dist', 'node_modules', 'get-windows', 'index.js'))+let stagedError = 'not staged in this build'if (fs.existsSync(staged)) {diff --git a/apps/desktop/electron/window-state.ts b/apps/desktop/electron/window-state.tsindex 2a973a9aa7a..afd991b37f5 100644--- a/apps/desktop/electron/window-state.ts+++ b/apps/desktop/electron/window-state.ts@@ -117,10 +117,7 @@ function computeWindowOptions(state, displays): WindowOptions {}if (state && finite(state.x) && finite(state.y)) {- const workArea = matchingWorkArea(- { x: state.x, y: state.y, width: opts.width, height: opts.height },- displays- )+ const workArea = matchingWorkArea({ x: state.x, y: state.y, width: opts.width, height: opts.height }, displays)if (workArea) {opts.width = clamp(opts.width, MIN_WIDTH, workArea.width)diff --git a/apps/desktop/electron/windows-remote-lifecycle.test.ts b/apps/desktop/electron/windows-remote-lifecycle.test.tsindex eb2f686181c..ab6acf37d46 100644--- a/apps/desktop/electron/windows-remote-lifecycle.test.ts+++ b/apps/desktop/electron/windows-remote-lifecycle.test.ts@@ -76,8 +76,7 @@ test('every emitted PowerShell script keeps try blocks attached to their catch/f// (MissingCatchOrFinally), so no probe may join a handler onto a separate// statement. The line-oriented builders join with `;`; the pair must live// in one array element.- const decode = (command: string) =>- Buffer.from(command.split(' ').at(-1) || '', 'base64').toString('utf16le')+ const decode = (command: string) => Buffer.from(command.split(' ').at(-1) || '', 'base64').toString('utf16le')const scripts: string[] = []@@ -102,6 +101,7 @@ test('every emitted PowerShell script keeps try blocks attached to their catch/f)assert.equal(scripts.length, 4)+for (const script of scripts) {assert.doesNotMatch(script, /}\s*;\s*(?:catch|finally)\b/)// `$HOME`, `$HOST`, `$PID`, ... are read-only automatic variables: assigning@@ -109,7 +109,10 @@ test('every emitted PowerShell script keeps try blocks attached to their catch/f// and the marker gate never observes CLEAR.assert.doesNotMatch(script, /\$(?:home|host|pid|profile|pwd|input|args|error)\s*=/i)}- assert.ok(scripts.slice(0, 2).every(script => /}catch \[Management\.Automation\.ItemNotFoundException\]/.test(script)))++ assert.ok(+ scripts.slice(0, 2).every(script => /}catch \[Management\.Automation\.ItemNotFoundException\]/.test(script))+ )})test('Windows relaunch gate refuses live and uncertain markers before executing the remote runtime', async () => {diff --git a/apps/desktop/src/api/config.ts b/apps/desktop/src/api/config.tsindex c37275ab992..509b81f074f 100644--- a/apps/desktop/src/api/config.ts+++ b/apps/desktop/src/api/config.ts@@ -14,13 +14,7 @@ import type {StatusResponse} from '@/types/hermes'-import {- capabilityScoped,- hermesApi,- type ProfileScope,- profileScoped,- STARTUP_REQUEST_TIMEOUT_MS-} from './client'+import { capabilityScoped, hermesApi, type ProfileScope, profileScoped, STARTUP_REQUEST_TIMEOUT_MS } from './client'export function getStatus(): Promise<StatusResponse> {return hermesApi<StatusResponse>({@@ -163,12 +157,14 @@ export function validateProviderCredential(value: string,apiKey?: string): Promise<{ ok: boolean; reachable: boolean; message: string; models?: string[]; resolved_base_url?: string }> {- return hermesApi<{ ok: boolean; reachable: boolean; message: string; models?: string[]; resolved_base_url?: string }>({- ...profileScoped(),- path: '/api/providers/validate',- method: 'POST',- body: { key, value, api_key: apiKey ?? '' }- })+ return hermesApi<{ ok: boolean; reachable: boolean; message: string; models?: string[]; resolved_base_url?: string }>(+ {+ ...profileScoped(),+ path: '/api/providers/validate',+ method: 'POST',+ body: { key, value, api_key: apiKey ?? '' }+ }+ )}export function getCustomEndpoints(profile?: null | string): Promise<CustomEndpointsResponse> {diff --git a/apps/desktop/src/api/models.ts b/apps/desktop/src/api/models.tsindex 22a85a7c732..9f3e34ecf83 100644--- a/apps/desktop/src/api/models.ts+++ b/apps/desktop/src/api/models.ts@@ -9,13 +9,7 @@ import type {ModelInfoResponse} from '@/types/hermes'-import {- capabilityScoped,- hermesApi,- type ProfileScope,- profileScoped,- STARTUP_REQUEST_TIMEOUT_MS-} from './client'+import { capabilityScoped, hermesApi, type ProfileScope, profileScoped, STARTUP_REQUEST_TIMEOUT_MS } from './client'export function getGlobalModelInfo(profile?: null | string): Promise<ModelInfoResponse> {return hermesApi<ModelInfoResponse>({diff --git a/apps/desktop/src/api/sessions.test.ts b/apps/desktop/src/api/sessions.test.tsindex ae03a525794..3376573b562 100644--- a/apps/desktop/src/api/sessions.test.ts+++ b/apps/desktop/src/api/sessions.test.ts@@ -11,8 +11,14 @@ vi.mock('./client', () => ({const client = await import('./client')-const { deleteSession, getSession, setSessionArchived, setSessionPinnedRemote, setSessionUnreadRemote, listSidebarSessions } =- await import('./sessions')+const {+ deleteSession,+ getSession,+ setSessionArchived,+ setSessionPinnedRemote,+ setSessionUnreadRemote,+ listSidebarSessions+} = await import('./sessions')const hermesApi = vi.mocked(client.hermesApi)diff --git a/apps/desktop/src/app/capabilities/index.tsx b/apps/desktop/src/app/capabilities/index.tsxindex 71105f4b810..f1c8088c08d 100644--- a/apps/desktop/src/app/capabilities/index.tsx+++ b/apps/desktop/src/app/capabilities/index.tsx@@ -122,19 +122,19 @@ export function CapabilitiesView({const pending = gated && !(skills && toolsets)const loadGate = !pending ? null : skillsFailed || toolsetsFailed ? (- <PanelEmpty- action={- <Button onClick={() => void refreshCapabilities()} size="sm">- {t.skills.refresh}- </Button>- }- description={skillsError instanceof Error ? skillsError.message : undefined}- icon="error"- title={t.skills.skillsLoadFailed}- />- ) : (- <PageLoader label={t.skills.loading} />- )+ <PanelEmpty+ action={+ <Button onClick={() => void refreshCapabilities()} size="sm">+ {t.skills.refresh}+ </Button>+ }+ description={skillsError instanceof Error ? skillsError.message : undefined}+ icon="error"+ title={t.skills.skillsLoadFailed}+ />+ ) : (+ <PageLoader label={t.skills.loading} />+ )// One entry per tab. Each is keyed on the scope so switching profile or// connection is a fresh tab — never one profile's selection, open editor or@@ -200,7 +200,11 @@ export function CapabilitiesView({{loadGate ?? tabContent[mode]()}</div>{hubMounted && (- <EmbeddedHubPicker hidden={mode !== 'skills'} installedNames={installedSkillNames} profile={scope.profile} />+ <EmbeddedHubPicker+ hidden={mode !== 'skills'}+ installedNames={installedSkillNames}+ profile={scope.profile}+ />)}</div></div>diff --git a/apps/desktop/src/app/capabilities/scope-selector.tsx b/apps/desktop/src/app/capabilities/scope-selector.tsxindex a844ea0133e..71e886148b0 100644--- a/apps/desktop/src/app/capabilities/scope-selector.tsx+++ b/apps/desktop/src/app/capabilities/scope-selector.tsx@@ -197,8 +197,15 @@ export function CapabilityScopeSelector({}return (- <div className={cn('flex min-w-0 items-center gap-2', compact ? 'flex-1' : 'border-b border-(--ui-stroke-secondary) px-3 py-2')}>- {!compact && <span className="text-[0.7rem] font-medium text-(--ui-text-tertiary)">{t.skills.configuringProfile}</span>}+ <div+ className={cn(+ 'flex min-w-0 items-center gap-2',+ compact ? 'flex-1' : 'border-b border-(--ui-stroke-secondary) px-3 py-2'+ )}+ >+ {!compact && (+ <span className="text-[0.7rem] font-medium text-(--ui-text-tertiary)">{t.skills.configuringProfile}</span>+ )}<Select onValueChange={scope.onChange} value={scope.value}><SelectTrigger className={cn('text-xs', compact ? 'h-6 w-full max-w-64 px-2' : 'h-7 w-56')}><SelectValue />diff --git a/apps/desktop/src/app/capabilities/skills/embedded-hub-picker.tsx b/apps/desktop/src/app/capabilities/skills/embedded-hub-picker.tsxindex 9139cecbe99..7d9fdbe5351 100644--- a/apps/desktop/src/app/capabilities/skills/embedded-hub-picker.tsx+++ b/apps/desktop/src/app/capabilities/skills/embedded-hub-picker.tsx@@ -7,7 +7,13 @@ import { useI18n } from '@/i18n'import { Loader2 } from '@/lib/icons'import { useStoreSelector } from '@/lib/use-session-slice'import { cn } from '@/lib/utils'-import { $hubActions, installHubSkill, notifyHubActionFailed, UPDATE_ALL_KEY, updateHubSkills } from '@/store/hub-actions'+import {+ $hubActions,+ installHubSkill,+ notifyHubActionFailed,+ UPDATE_ALL_KEY,+ updateHubSkills+} from '@/store/hub-actions'import { notify, notifyError } from '@/store/notifications'import { $paneHeightOverride, setPaneHeightOverride } from '@/store/panes'diff --git a/apps/desktop/src/app/capabilities/skills/skills-tab.tsx b/apps/desktop/src/app/capabilities/skills/skills-tab.tsxindex 639dfc46176..f13b23956cf 100644--- a/apps/desktop/src/app/capabilities/skills/skills-tab.tsx+++ b/apps/desktop/src/app/capabilities/skills/skills-tab.tsx@@ -7,7 +7,14 @@ import { ArchiveSkillConfirmDialog } from '@/app/learning/archive-skill-confirm-import { CodeEditor } from '@/components/chat/code-editor'import { Badge } from '@/components/ui/badge'import { Button } from '@/components/ui/button'-import { editLearningNode, getLearningNode, getOfficialSkills, type ProfileScope, profileScopeKey, setSkillEnabled } from '@/hermes'+import {+ editLearningNode,+ getLearningNode,+ getOfficialSkills,+ type ProfileScope,+ profileScopeKey,+ setSkillEnabled+} from '@/hermes'import { useI18n } from '@/i18n'import { Loader2 } from '@/lib/icons'import { Codecs, persistentAtom } from '@/lib/persisted'@@ -109,7 +116,9 @@ export function SkillsTab({ onRefresh, profile, query, skills }: SkillsTabProps)const installedSkillNames = useMemo(() => new Set(skills.map(s => s.name)), [skills])const visibleOfficial = useMemo(() => {- const catalog = (officialData?.skills ?? []).filter(skill => !skill.installed && !installedSkillNames.has(skill.name))+ const catalog = (officialData?.skills ?? []).filter(+ skill => !skill.installed && !installedSkillNames.has(skill.name)+ )return filteredOfficial(catalog, query)}, [installedSkillNames, officialData, query])@@ -195,12 +204,20 @@ export function SkillsTab({ onRefresh, profile, query, skills }: SkillsTabProps)checked: allEnabled,disabled: bulkBusy,label: t.skills.all,- onToggle: checked => void bulkApply(skills.filter(row => row.enabled !== checked), checked)+ onToggle: checked =>+ void bulkApply(+ skills.filter(row => row.enabled !== checked),+ checked+ )}// "Never used" = zero recorded activity. The pruning move for a 100+ skill// install: keep the workhorses, shed the noise.- const disableUnused = () => bulkApply(skills.filter(skill => skill.enabled && usageOf(skill) === 0), false)+ const disableUnused = () =>+ bulkApply(+ skills.filter(skill => skill.enabled && usageOf(skill) === 0),+ false+ )const openSkillEditor = async (name: string) => {try {@@ -312,12 +329,7 @@ export function SkillsTab({ onRefresh, profile, query, skills }: SkillsTabProps)return (<CapRowaction={- <Button- disabled={installing}- onClick={() => handleInstallOfficial(skill)}- size="xs"- variant="text"- >+ <Button disabled={installing} onClick={() => handleInstallOfficial(skill)} size="xs" variant="text">{installing && <Loader2 className="size-3 animate-spin" />}{installing ? t.skills.hub.installing : t.skills.hub.install}</Button>diff --git a/apps/desktop/src/app/capabilities/toolsets/toolsets-tab.tsx b/apps/desktop/src/app/capabilities/toolsets/toolsets-tab.tsxindex 2c9abe1ebe5..cb978c5981e 100644--- a/apps/desktop/src/app/capabilities/toolsets/toolsets-tab.tsx+++ b/apps/desktop/src/app/capabilities/toolsets/toolsets-tab.tsx@@ -132,7 +132,11 @@ export function ToolsetsTab({ profile, query, toolsets }: ToolsetsTabProps) {checked: bulkToolsets.length > 0 && bulkToolsets.every(ts => ts.enabled),disabled: bulkBusy,label: t.skills.all,- onToggle: checked => void bulkApply(bulkToolsets.filter(row => row.enabled !== checked), checked)+ onToggle: checked =>+ void bulkApply(+ bulkToolsets.filter(row => row.enabled !== checked),+ checked+ )}if (visibleToolsets.length === 0) {diff --git a/apps/desktop/src/app/chat/composer/attachments.tsx b/apps/desktop/src/app/chat/composer/attachments.tsxindex 8cb08ba7b58..00063f39954 100644--- a/apps/desktop/src/app/chat/composer/attachments.tsx+++ b/apps/desktop/src/app/chat/composer/attachments.tsx@@ -55,8 +55,7 @@ function AttachmentPill({ attachment, onRemove }: { attachment: ComposerAttachmeconst canPreview = attachment.kind !== 'folder' && attachment.kind !== 'terminal' && !isUploading- const detail =- attachment.detail && attachment.detail !== attachment.label ? attachment.detail : undefined+ const detail = attachment.detail && attachment.detail !== attachment.label ? attachment.detail : undefined// Keep full image bytes out of composer state. New chips read their path only// when clicked; previewUrl remains a compatibility fallback for older drafts.diff --git a/apps/desktop/src/app/chat/composer/floating-target.ts b/apps/desktop/src/app/chat/composer/floating-target.tsindex 4fe29bf1d94..21531b72970 100644--- a/apps/desktop/src/app/chat/composer/floating-target.ts+++ b/apps/desktop/src/app/chat/composer/floating-target.ts@@ -67,7 +67,7 @@ function selectionOutsideComposer(): boolean {}const { anchorNode } = selection- const anchorEl = anchorNode instanceof Element ? anchorNode : anchorNode?.parentElement ?? null+ const anchorEl = anchorNode instanceof Element ? anchorNode : (anchorNode?.parentElement ?? null)return !anchorEl?.closest('[data-slot="composer-rich-input"]')}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 50c61d19daa..cea1cbc3cdb 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@@ -120,7 +120,10 @@ describe('useComposerDraft — attachment scope stays coherent with the committe})expect(mainComposerScope.$attachments.get()).toEqual([preSessionAttachment])- expect(takeSessionDraft('session-created')).toEqual({ attachments: [preSessionAttachment], text: 'do not lose this draft' })+ expect(takeSessionDraft('session-created')).toEqual({+ attachments: [preSessionAttachment],+ text: 'do not lose this draft'+ })expect(takeSessionDraft(null)).toEqual({ attachments: [], text: '' })clearSessionDraft('session-created')})@@ -150,7 +153,9 @@ describe('useComposerDraft — attachment scope stays coherent with the committe// and does not re-publish the notice the user already dismissed.dismissRestoredDraftNotice()act(() => {- rerender(<ProbeHarness activeQueueSessionKey="session-A" onLayoutSnapshot={() => undefined} sessionId="session-A" />)+ rerender(+ <ProbeHarness activeQueueSessionKey="session-A" onLayoutSnapshot={() => undefined} sessionId="session-A" />+ )})act(() => {rerender(<ProbeHarness activeQueueSessionKey={null} onLayoutSnapshot={() => undefined} sessionId="" />)@@ -169,7 +174,9 @@ describe('useComposerDraft — attachment scope stays coherent with the committe)act(() => {- rerender(<ProbeHarness activeQueueSessionKey="session-A" onLayoutSnapshot={() => undefined} sessionId="session-A" />)+ rerender(+ <ProbeHarness activeQueueSessionKey="session-A" onLayoutSnapshot={() => undefined} sessionId="session-A" />+ )})expect(takeSessionDraft('session-A')).toEqual({ attachments: [], text: '' })@@ -559,7 +566,9 @@ describe('useComposerDraft — a hidden keep-alive tab never auto-focuses its coact(() => {lateRestore('rejected draft', [])- if (hidden) {lateFocus()}+ if (hidden) {+ lateFocus()+ }})expect(composerPlainText(draft.editorRef.current!)).toBe('rejected draft')diff --git a/apps/desktop/src/app/chat/composer/hooks/use-composer-screenshot.test.tsx b/apps/desktop/src/app/chat/composer/hooks/use-composer-screenshot.test.tsxindex bd3db8f0ae8..8dc0dfcfea6 100644--- a/apps/desktop/src/app/chat/composer/hooks/use-composer-screenshot.test.tsx+++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-screenshot.test.tsx@@ -17,27 +17,41 @@ const onAttach = vi.fn(async (_blob: Blob, isCurrent?: () => boolean) => isCurrefunction mount(target: string, surfaceId: string, key = 'draft-a') {const scope = { ...MAIN_COMPOSER_SCOPE, target, attachments: createComposerAttachmentScope() }+const Wrapper = ({ children }: PropsWithChildren) => (<I18nProvider configClient={null}><ComposerScopeProvider value={scope}><ComposerSurfaceProvider value={surfaceId}>- <div data-composer-surface-id={surfaceId} data-composer-target={target}>{children}</div>+ <div data-composer-surface-id={surfaceId} data-composer-target={target}>+ {children}+ </div></ComposerSurfaceProvider></ComposerScopeProvider></I18nProvider>)return renderHook(({ sessionKey }) => useComposerScreenshot({ sessionKey, onAttachImageBlob: onAttach }), {- initialProps: { sessionKey: key }, wrapper: Wrapper+ initialProps: { sessionKey: key },+ wrapper: Wrapper})}function bridge() {- window.hermesDesktop = { ...window.hermesDesktop, screenshot: {- getSettings: vi.fn(), setEnabled: vi.fn(), openPermissionSettings: vi.fn(), onStatus: () => () => undefined,- capture,- onRequest: callback => { listeners.add(callback); return () => listeners.delete(callback) }- } as ScreenshotApi }+ window.hermesDesktop = {+ ...window.hermesDesktop,+ screenshot: {+ getSettings: vi.fn(),+ setEnabled: vi.fn(),+ openPermissionSettings: vi.fn(),+ onStatus: () => () => undefined,+ capture,+ onRequest: callback => {+ listeners.add(callback)++ return () => listeners.delete(callback)+ }+ } as ScreenshotApi+ }}afterEach(() => {@@ -65,7 +79,12 @@ describe('screenshot composer routing', () => {it('rejects a late screenshot after a draft round trip and invalidates the image-write continuation', async () => {bridge()let finish!: (value: Awaited<ReturnType<ScreenshotApi['capture']>>) => void- capture.mockImplementation(() => new Promise(resolve => { finish = resolve }))+ capture.mockImplementation(+ () =>+ new Promise(resolve => {+ finish = resolve+ })+ )const hook = mount('main', 'primary')act(() => listeners.forEach(listener => listener('first')))hook.rerender({ sessionKey: 'draft-b' })@@ -75,7 +94,11 @@ describe('screenshot composer routing', () => {capture.mockResolvedValue({ ok: true, png: new Uint8Array([1]) })let isCurrent!: () => boolean- onAttach.mockImplementation(async (_blob, guard) => { isCurrent = guard!; return true })+ onAttach.mockImplementation(async (_blob, guard) => {+ isCurrent = guard!++ return true+ })act(() => listeners.forEach(listener => listener('second')))await waitFor(() => expect(onAttach).toHaveBeenCalledOnce())expect(isCurrent()).toBe(true)diff --git a/apps/desktop/src/app/chat/composer/hooks/use-composer-screenshot.ts b/apps/desktop/src/app/chat/composer/hooks/use-composer-screenshot.tsindex b1fd9ff4c79..b4942f34d81 100644--- a/apps/desktop/src/app/chat/composer/hooks/use-composer-screenshot.ts+++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-screenshot.ts@@ -26,6 +26,7 @@ export function useComposerScreenshot({ sessionKey, focusKey, onAttachImageBlobuseLayoutEffect(() => {const api = window.hermesDesktop?.screenshot+if (!api || !surfaceId || !visible) {return}@@ -33,19 +34,24 @@ export function useComposerScreenshot({ sessionKey, focusKey, onAttachImageBloblet generation = 0let mounted = truelet busy = false+const offRoute = $activeGatewayRoute.listen(() => {generation += 1})+const offStatus = api.onStatus(status => {if (!status.enabled) {generation += 1}})+const offRequest = api.onRequest(requestId => {if (busy || getActiveComposer() !== scope.target || getVisibleComposerSurfaceId(scope.target) !== surfaceId) {return}+const attach = latest.current.onAttachImageBlob+if (!attach) {return}@@ -58,13 +64,16 @@ export function useComposerScreenshot({ sessionKey, focusKey, onAttachImageBlobvoid (async () => {try {const result = await api.capture(requestId)+if (!isCurrent()) {report(latest.current.copy.contextChanged)+return}if (!result.ok) {report(latest.current.copy.captureFailed)+return}@@ -72,6 +81,7 @@ export function useComposerScreenshot({ sessionKey, focusKey, onAttachImageBlob// native bytes, before adding a chip, so a session swap cannot leak it.const blob = new Blob([new Uint8Array(result.png)], { type: 'image/png' })await attach(blob, isCurrent)+if (!isCurrent()) {report(latest.current.copy.contextChanged)}diff --git a/apps/desktop/src/app/chat/composer/hooks/use-composer-voice.ts b/apps/desktop/src/app/chat/composer/hooks/use-composer-voice.tsindex 4ea061f4036..a46513802c2 100644--- a/apps/desktop/src/app/chat/composer/hooks/use-composer-voice.ts+++ b/apps/desktop/src/app/chat/composer/hooks/use-composer-voice.ts@@ -79,9 +79,7 @@ export function useComposerVoice({// Runs on every streamed flush: test the parts in place instead of// joining the whole reply into a string just to check it is non-blank.- return last?.pending && last.parts.some(part => part.type === 'text' && /\S/.test(part.text))- ? last.id- : null+ return last?.pending && last.parts.some(part => part.type === 'text' && /\S/.test(part.text)) ? last.id : null}),[$messages])diff --git a/apps/desktop/src/app/chat/composer/hooks/use-voice-live-conversation.owner.test.tsx b/apps/desktop/src/app/chat/composer/hooks/use-voice-live-conversation.owner.test.tsxindex ab6744bb968..11f16c08435 100644--- a/apps/desktop/src/app/chat/composer/hooks/use-voice-live-conversation.owner.test.tsx+++ b/apps/desktop/src/app/chat/composer/hooks/use-voice-live-conversation.owner.test.tsx@@ -13,7 +13,9 @@ import { useVoiceLiveConversation } from './use-voice-live-conversation'// — the same owner route the TTS legs already trust (#117014) — so the voice// configured on the Bot's profile is the voice that answers (#117401).-const constructed = vi.hoisted(() => ({ owners: [] as Array<null | { connectionId?: null | string; profile?: null | string }> }))+const constructed = vi.hoisted(() => ({+ owners: [] as Array<null | { connectionId?: null | string; profile?: null | string }>+}))vi.mock('@/lib/voice-live', async importOriginal => {const actual = (await importOriginal()) as Record<string, unknown>@@ -23,7 +25,10 @@ vi.mock('@/lib/voice-live', async importOriginal => {VoiceLiveSession: class {close = vi.fn()- constructor(_handlers: VoiceLiveHandlers, owner: null | { connectionId?: null | string; profile?: null | string } = null) {+ constructor(+ _handlers: VoiceLiveHandlers,+ owner: null | { connectionId?: null | string; profile?: null | string } = null+ ) {constructed.owners.push(owner)}diff --git a/apps/desktop/src/app/chat/composer/hooks/use-voice-live-conversation.ts b/apps/desktop/src/app/chat/composer/hooks/use-voice-live-conversation.tsindex 2033e239def..6d43c93f744 100644--- a/apps/desktop/src/app/chat/composer/hooks/use-voice-live-conversation.ts+++ b/apps/desktop/src/app/chat/composer/hooks/use-voice-live-conversation.ts@@ -246,95 +246,98 @@ export function useVoiceLiveConversation({return}- const session = new VoiceLiveSession({- // The voice model answers a bare "stop" itself (it just goes quiet) and- // never delegates it, so the spoken stop phrase is judged on the user- // transcript once the utterance settles.- onTranscript: fragment => {- if (fragment.speaker !== 'user') {- return- }-- userUtteranceRef.current += fragment.text-- if (utteranceTimerRef.current) {- window.clearTimeout(utteranceTimerRef.current)- }+ const session = new VoiceLiveSession(+ {+ // The voice model answers a bare "stop" itself (it just goes quiet) and+ // never delegates it, so the spoken stop phrase is judged on the user+ // transcript once the utterance settles.+ onTranscript: fragment => {+ if (fragment.speaker !== 'user') {+ return+ }- utteranceTimerRef.current = window.setTimeout(() => {- utteranceTimerRef.current = null- const utterance = userUtteranceRef.current- userUtteranceRef.current = ''+ userUtteranceRef.current += fragment.text- if (sessionRef.current === session && isVoiceStopCommand(utterance)) {- void end()- latest.current.onStopWord?.()+ if (utteranceTimerRef.current) {+ window.clearTimeout(utteranceTimerRef.current)}- }, UTTERANCE_SETTLE_MS)- },- onClosed: (reason, usageSeconds) => {- if (sessionRef.current !== session) {- return- }- sessionRef.current = null- setDelegation(null)- setStatus('idle')+ utteranceTimerRef.current = window.setTimeout(() => {+ utteranceTimerRef.current = null+ const utterance = userUtteranceRef.current+ userUtteranceRef.current = ''++ if (sessionRef.current === session && isVoiceStopCommand(utterance)) {+ void end()+ latest.current.onStopWord?.()+ }+ }, UTTERANCE_SETTLE_MS)+ },+ onClosed: (reason, usageSeconds) => {+ if (sessionRef.current !== session) {+ return+ }- if (reason !== 'close_requested') {- notify({- kind: 'warning',- message: liveEndedMessage(reason, usageSeconds, voiceCopy),- title: voiceCopy.liveEnded- })- latest.current.onFatalError?.()- }- },- onDelegation: (delegationId, context) => {- if (sessionRef.current !== session) {- return- }+ sessionRef.current = null+ setDelegation(null)+ setStatus('idle')++ if (reason !== 'close_requested') {+ notify({+ kind: 'warning',+ message: liveEndedMessage(reason, usageSeconds, voiceCopy),+ title: voiceCopy.liveEnded+ })+ latest.current.onFatalError?.()+ }+ },+ onDelegation: (delegationId, context) => {+ if (sessionRef.current !== session) {+ return+ }- const { context: voiceContext, prompt } = delegationPrompt(context)+ const { context: voiceContext, prompt } = delegationPrompt(context)- // A spoken stop command ends the conversation instead of becoming a turn.- if (prompt && isVoiceStopCommand(prompt)) {- void end()- latest.current.onStopWord?.()+ // A spoken stop command ends the conversation instead of becoming a turn.+ if (prompt && isVoiceStopCommand(prompt)) {+ void end()+ latest.current.onStopWord?.()- return- }+ return+ }- // A newer request supersedes an in-flight turn: stop it so the answer- // the voice speaks is for what the user asked last.- if (busyRef.current) {- void latest.current.onInterrupt?.()- }+ // A newer request supersedes an in-flight turn: stop it so the answer+ // the voice speaks is for what the user asked last.+ if (busyRef.current) {+ void latest.current.onInterrupt?.()+ }- setDelegation(delegationId)- spokenResponseIdRef.current = null- spokenLengthRef.current = 0- lastToolLabelRef.current = null- turnObservedRef.current = false- submittedAtRef.current = Date.now()- latest.current.consumePendingResponse()- refreshStatus()- void Promise.resolve(latest.current.onSubmit(prompt, voiceContext)).catch(error => {- notifyError(error, voiceCopy.liveDelegationFailed)- session.speak(delegationId, 'Sorry, I could not reach Hermes for that request.')- setDelegation(null)+ setDelegation(delegationId)+ spokenResponseIdRef.current = null+ spokenLengthRef.current = 0+ lastToolLabelRef.current = null+ turnObservedRef.current = false+ submittedAtRef.current = Date.now()+ latest.current.consumePendingResponse()refreshStatus()- })- },- onError: (message, fatal) => {- notify({ kind: fatal ? 'error' : 'warning', message, title: voiceCopy.liveError })+ void Promise.resolve(latest.current.onSubmit(prompt, voiceContext)).catch(error => {+ notifyError(error, voiceCopy.liveDelegationFailed)+ session.speak(delegationId, 'Sorry, I could not reach Hermes for that request.')+ setDelegation(null)+ refreshStatus()+ })+ },+ onError: (message, fatal) => {+ notify({ kind: fatal ? 'error' : 'warning', message, title: voiceCopy.liveError })+ },+ onSpeakingChange: speaking => {+ speakingRef.current = speaking+ setLevel(speaking ? 0.6 : 0)+ refreshStatus()+ }},- onSpeakingChange: speaking => {- speakingRef.current = speaking- setLevel(speaking ? 0.6 : 0)- refreshStatus()- }- }, ownerRef.current)+ ownerRef.current+ )sessionRef.current = sessionstartingRef.current = falsediff --git a/apps/desktop/src/app/chat/composer/index.tsx b/apps/desktop/src/app/chat/composer/index.tsxindex b94fd02d6fa..249f8e5f721 100644--- a/apps/desktop/src/app/chat/composer/index.tsx+++ b/apps/desktop/src/app/chat/composer/index.tsx@@ -1414,10 +1414,7 @@ export function ChatBar({data-slot="composer-surface"ref={composerSurfaceRef}>- <div- aria-hidden- className={composerInputBacking}- />+ <div aria-hidden className={composerInputBacking} />{!guidedChat && (<CodingStatusRowonBranchOff={handleBranchOff}@@ -1540,10 +1537,7 @@ export function ChatBarFallback() {data-slot="composer-root"><div className="composer-fallback-surface relative isolate h-(--composer-fallback-height) w-full rounded-[inherit] border border-[color-mix(in_srgb,var(--dt-composer-ring)_calc(18%*var(--composer-ring-strength)),var(--dt-input))]">- <div- aria-hidden- className={composerInputBacking}- />+ <div aria-hidden className={composerInputBacking} /></div></div>)diff --git a/apps/desktop/src/app/chat/composer/queue-panel.tsx b/apps/desktop/src/app/chat/composer/queue-panel.tsxindex cc1136254bd..1f70fbe3ed6 100644--- a/apps/desktop/src/app/chat/composer/queue-panel.tsx+++ b/apps/desktop/src/app/chat/composer/queue-panel.tsx@@ -77,7 +77,8 @@ export function QueuePanel({return (<StatusRowclassName={cn(- isEditing && 'ring-1 ring-inset ring-[color-mix(in_srgb,var(--dt-composer-ring)_40%,transparent)] bg-accent/25'+ isEditing &&+ 'ring-1 ring-inset ring-[color-mix(in_srgb,var(--dt-composer-ring)_40%,transparent)] bg-accent/25')}dismiss={{ label: c.queueDelete, onDismiss: () => onDelete(entry.id) }}key={entry.id}diff --git a/apps/desktop/src/app/chat/composer/status-stack/session-control-goal.tsx b/apps/desktop/src/app/chat/composer/status-stack/session-control-goal.tsxindex a897158c171..e7b9aebc9fd 100644--- a/apps/desktop/src/app/chat/composer/status-stack/session-control-goal.tsx+++ b/apps/desktop/src/app/chat/composer/status-stack/session-control-goal.tsx@@ -339,9 +339,7 @@ export const SessionControlGoalSection = memo(function SessionControlGoalSection: ctrl.waitBarrierTitle}</StatusControlRow>)}- {!goal.wait_barrier && goal.paused_reason && (- <StatusControlRow>{goal.paused_reason}</StatusControlRow>- )}+ {!goal.wait_barrier && goal.paused_reason && <StatusControlRow>{goal.paused_reason}</StatusControlRow>}{!goal.wait_barrier && !goal.paused_reason && goal.last_reason && (<StatusControlRow>{goal.last_reason}</StatusControlRow>)}@@ -364,7 +362,11 @@ export const SessionControlGoalSection = memo(function SessionControlGoalSection<StatusRowclassName="text-[0.68rem] font-medium text-muted-foreground/75"leading={- <span aria-hidden="true" className="inline-flex text-muted-foreground/70" data-slot="criteria-state-marker">+ <span+ aria-hidden="true"+ className="inline-flex text-muted-foreground/70"+ data-slot="criteria-state-marker"+ ><Codicon name="checklist" size="0.8rem" /></span>}diff --git a/apps/desktop/src/app/chat/composer/status-stack/session-control-heartbeat.tsx b/apps/desktop/src/app/chat/composer/status-stack/session-control-heartbeat.tsxindex 32ab6d0efe8..c2de2c83911 100644--- a/apps/desktop/src/app/chat/composer/status-stack/session-control-heartbeat.tsx+++ b/apps/desktop/src/app/chat/composer/status-stack/session-control-heartbeat.tsx@@ -190,9 +190,7 @@ export const SessionControlHeartbeatSection = memo(function SessionControlHeartb<StatusControlRow className="text-[0.73rem] leading-4 text-foreground/92 break-words" icon="bell">{heartbeat.prompt}</StatusControlRow>- <StatusControlRow icon="history">- {ctrl.heartbeatFiredCount(heartbeat.fire_count)}- </StatusControlRow>+ <StatusControlRow icon="history">{ctrl.heartbeatFiredCount(heartbeat.fire_count)}</StatusControlRow></div></StatusSection></div>diff --git a/apps/desktop/src/app/chat/composer/status-stack/session-control-loop.tsx b/apps/desktop/src/app/chat/composer/status-stack/session-control-loop.tsxindex f17a4d183ca..12027f82e89 100644--- a/apps/desktop/src/app/chat/composer/status-stack/session-control-loop.tsx+++ b/apps/desktop/src/app/chat/composer/status-stack/session-control-loop.tsx@@ -210,18 +210,10 @@ export const SessionControlLoopSection = memo(function SessionControlLoopSection</span></StatusControlRow>)}- {loop.deferred_by_goal && (- <StatusControlRow>{ctrl.loopDeferredNotice}</StatusControlRow>- )}- {loop.awaiting_response && (- <StatusControlRow>{ctrl.loopAwaitingResponse}</StatusControlRow>- )}- {loop.paused_reason && (- <StatusControlRow>{loop.paused_reason}</StatusControlRow>- )}- {loop.last_stop_reason && (- <StatusControlRow>{loop.last_stop_reason}</StatusControlRow>- )}+ {loop.deferred_by_goal && <StatusControlRow>{ctrl.loopDeferredNotice}</StatusControlRow>}+ {loop.awaiting_response && <StatusControlRow>{ctrl.loopAwaitingResponse}</StatusControlRow>}+ {loop.paused_reason && <StatusControlRow>{loop.paused_reason}</StatusControlRow>}+ {loop.last_stop_reason && <StatusControlRow>{loop.last_stop_reason}</StatusControlRow>}</div></StatusSection></div>diff --git a/apps/desktop/src/app/chat/composer/trigger-popover.tsx b/apps/desktop/src/app/chat/composer/trigger-popover.tsxindex 400e8916984..571a4765b13 100644--- a/apps/desktop/src/app/chat/composer/trigger-popover.tsx+++ b/apps/desktop/src/app/chat/composer/trigger-popover.tsx@@ -200,12 +200,7 @@ export function ComposerTriggerPopover({return (<Fragment key={item.id}>{showHeader && <div className={cn(GROUP_HEADER_CLASS, isFirstHeader ? 'pt-0.5' : 'pt-2')}>{group}</div>}- <Tip- delayDuration={400}- label={kind === '/' ? description : undefined}- placement="row"- sideOffset={4}- >+ <Tip delayDuration={400} label={kind === '/' ? description : undefined} placement="row" sideOffset={4}><buttonclassName={ROW_CLASS}data-highlighted={active ? '' : undefined}diff --git a/apps/desktop/src/app/chat/history-window.test.tsx b/apps/desktop/src/app/chat/history-window.test.tsxindex 0040192d370..2d9f58ea6b2 100644--- a/apps/desktop/src/app/chat/history-window.test.tsx+++ b/apps/desktop/src/app/chat/history-window.test.tsx@@ -15,14 +15,20 @@ import { ChatRuntimeBoundary } from '.'stubThreadEnvironment()const message = (rowId: number): ChatMessage => ({- id: `live-${rowId}`, rowId, role: 'user', parts: [{ type: 'text', text: `prompt ${rowId}` }]+ id: `live-${rowId}`,+ rowId,+ role: 'user',+ parts: [{ type: 'text', text: `prompt ${rowId}` }]})const page = (rowId: number) => ({session_id: 'stored',pagination: { has_older: true, has_newer: true, limit: 120, offset: 40, returned: 120, order: 'oldest' },messages: Array.from({ length: 120 }, (_, index) => ({- id: rowId + index, role: 'user' as const, content: `prompt ${rowId + index}`, timestamp: rowId + index+ id: rowId + index,+ role: 'user' as const,+ content: `prompt ${rowId + index}`,+ timestamp: rowId + index}))})@@ -35,8 +41,10 @@ function mount(storedId = 'stored') {const $messages = atom(Array.from({ length: 120 }, (_, index) => message(10_000 + index)))const view = {- ...PRIMARY_SESSION_VIEW, $messages,- $runtimeId: atom<string | null>('runtime'), $storedId: atom<string | null>(storedId)+ ...PRIMARY_SESSION_VIEW,+ $messages,+ $runtimeId: atom<string | null>('runtime'),+ $storedId: atom<string | null>(storedId)}let window!: Required<TranscriptWindowValue>@@ -59,7 +67,17 @@ function mount(storedId = 'stored') {</SessionViewProvider>)- return { view, mutations, ...rendered, get window() { return window }, get runtime() { return runtime } }+ return {+ view,+ mutations,+ ...rendered,+ get window() {+ return window+ },+ get runtime() {+ return runtime+ }+ }}describe('bounded direct history runtime', () => {@@ -68,7 +86,9 @@ describe('bounded direct history runtime', () => {const mounted = mount()const live = mounted.view.$messages.get()let id: string | null = null- await act(async () => { id = await mounted.window.revealRow(40, new AbortController().signal) })+ await act(async () => {+ id = await mounted.window.revealRow(40, new AbortController().signal)+ })expect(api).toHaveBeenCalledTimes(1)const url = new URL(api.mock.calls[0][0].path, 'http://test')@@ -81,14 +101,18 @@ describe('bounded direct history runtime', () => {expect(mounted.window.currentMessages?.find(message => message.rowId === 40)?.id).toBe(id)expect(mounted.window.isHistorical).toBe(true)expect(mounted.window.newerAvailable).toBe(true)- act(() => { mounted.window.returnToLatest() })+ act(() => {+ mounted.window.returnToLatest()+ })expect(mounted.window.isHistorical).toBe(false)})it('keeps history static during streaming and restores the newest live tail and capabilities', async () => {vi.spyOn(window.hermesDesktop, 'api').mockResolvedValue(page(40))const mounted = mount()- await act(async () => { await mounted.window.revealRow(40, new AbortController().signal) })+ await act(async () => {+ await mounted.window.revealRow(40, new AbortController().signal)+ })const historical = mounted.runtime.thread.getState().messagesconst snapshot = mounted.window// `edit` is the one capability that survives on a bounded page: the rail@@ -98,24 +122,32 @@ describe('bounded direct history runtime', () => {expect(mounted.runtime.thread.getState().capabilities.reload).toBe(false)expect(mounted.runtime.thread.getState().capabilities.switchToBranch).toBe(false)expect(mounted.runtime.thread.getState().isDisabled).toBe(true)- act(() => { mounted.view.$messages.set([...mounted.view.$messages.get(), message(20_000)]) })+ act(() => {+ mounted.view.$messages.set([...mounted.view.$messages.get(), message(20_000)])+ })expect(mounted.runtime.thread.getState().messages).toBe(historical)expect(mounted.window).toBe(snapshot)expect(await mounted.window.expandWindow()).toBe(false)- act(() => { mounted.window.returnToLatest() })+ act(() => {+ mounted.window.returnToLatest()+ })expect(mounted.runtime.thread.getState().messages.at(-1)?.id).toBe('live-20000')expect(mounted.runtime.thread.getState().capabilities.edit).toBe(true)expect(mounted.runtime.thread.getState().capabilities.reload).toBe(true)expect(mounted.runtime.thread.getState().isDisabled).toBe(false)expect(mounted.window.isHistorical).toBe(false)- for (const callback of Object.values(mounted.mutations)) {expect(callback).not.toHaveBeenCalled()}+ for (const callback of Object.values(mounted.mutations)) {+ expect(callback).not.toHaveBeenCalled()+ }})it('keeps the edit composer available after a rail jump selects a history page', async () => {vi.spyOn(window.hermesDesktop, 'api').mockResolvedValue(page(40))const mounted = mount()- await act(async () => { await mounted.window.revealRow(40, new AbortController().signal) })+ await act(async () => {+ await mounted.window.revealRow(40, new AbortController().signal)+ })expect(mounted.window.isHistorical).toBe(true)expect(mounted.runtime.thread.getState().capabilities.edit).toBe(true)@@ -127,11 +159,19 @@ describe('bounded direct history runtime', () => {// only by the floating jump button's returnToLatest.const composer = mounted.runtime.thread.getMessageByIndex(0).composer- expect(() => act(() => { composer.beginEdit() })).not.toThrow()+ expect(() =>+ act(() => {+ composer.beginEdit()+ })+ ).not.toThrow()expect(composer.getState().isEditing).toBe(true)- act(() => { composer.cancel() })- act(() => { mounted.window.returnToLatest() })+ act(() => {+ composer.cancel()+ })+ act(() => {+ mounted.window.returnToLatest()+ })expect(composer.getState().isEditing).toBe(false)})@@ -146,24 +186,41 @@ describe('bounded direct history runtime', () => {second = mounted.window.revealRow(400, new AbortController().signal)})expect(await first).toBeNull()- await act(async () => { resolves[1](page(400)); await second })+ await act(async () => {+ resolves[1](page(400))+ await second+ })const selected = mounted.window.currentMessages- await act(async () => { resolves[0](page(40)); await Promise.resolve() })+ await act(async () => {+ resolves[0](page(40))+ await Promise.resolve()+ })expect(mounted.window.currentMessages).toBe(selected)expect(selected[0].rowId).toBe(400)})it.each(['abort', 'latest', 'session', 'unmount'] as const)('discards pending reads on %s', async action => {let resolve!: (value: ReturnType<typeof page>) => void- vi.spyOn(window.hermesDesktop, 'api').mockImplementation(() => new Promise(done => { resolve = done }))+ vi.spyOn(window.hermesDesktop, 'api').mockImplementation(+ () =>+ new Promise(done => {+ resolve = done+ })+ )const mounted = mount()const signal = new AbortController()let pending!: Promise<string | null>- act(() => { pending = mounted.window.revealRow(40, signal.signal) })act(() => {- if (action === 'abort') {signal.abort()}+ pending = mounted.window.revealRow(40, signal.signal)+ })+ act(() => {+ if (action === 'abort') {+ signal.abort()+ }- if (action === 'latest') {mounted.window.returnToLatest()}+ if (action === 'latest') {+ mounted.window.returnToLatest()+ }if (action === 'session') {mounted.view.$storedId.set('next-session')@@ -171,10 +228,15 @@ describe('bounded direct history runtime', () => {mounted.view.$messages.set([message(30_000)])}- if (action === 'unmount') {mounted.unmount()}+ if (action === 'unmount') {+ mounted.unmount()+ }})expect(await pending).toBeNull()- await act(async () => { resolve(page(40)); await Promise.resolve() })+ await act(async () => {+ resolve(page(40))+ await Promise.resolve()+ })expect(mounted.view.$messages.get().some(message => message.rowId === 40)).toBe(false)expect(mounted.window.isHistorical).toBe(false)})@@ -182,14 +244,25 @@ describe('bounded direct history runtime', () => {it('rejects oversized, missing-target and failed responses without losing the selected page', async () => {const api = vi.spyOn(window.hermesDesktop, 'api').mockResolvedValue(page(40))const mounted = mount()- await act(async () => { await mounted.window.revealRow(40, new AbortController().signal) })+ await act(async () => {+ await mounted.window.revealRow(40, new AbortController().signal)+ })const selected = mounted.window.currentMessages- for (const response of [{ ...page(400), messages: [...page(400).messages, ...page(600).messages] }, page(800), null]) {- if (response) {api.mockResolvedValueOnce(response)}- else {api.mockRejectedValueOnce(new Error('offline'))}+ for (const response of [+ { ...page(400), messages: [...page(400).messages, ...page(600).messages] },+ page(800),+ null+ ]) {+ if (response) {+ api.mockResolvedValueOnce(response)+ } else {+ api.mockRejectedValueOnce(new Error('offline'))+ }- await act(async () => { expect(await mounted.window.revealRow(400, new AbortController().signal)).toBeNull() })+ await act(async () => {+ expect(await mounted.window.revealRow(400, new AbortController().signal)).toBeNull()+ })expect(mounted.window.currentMessages).toBe(selected)}})@@ -212,13 +285,17 @@ describe('paging earlier from an open history window', () => {const mounted = mount()const live = mounted.view.$messages.get()- await act(async () => { await mounted.window.revealRow(4000, new AbortController().signal) })+ await act(async () => {+ await mounted.window.revealRow(4000, new AbortController().signal)+ })// The row was reached from the rail, but everything before it is still// back there: the transcript's own entry point must not retire.expect(mounted.window.olderAvailable).toBe(true)let grew = false- await act(async () => { grew = (await mounted.window.expandWindow()) === true })+ await act(async () => {+ grew = (await mounted.window.expandWindow()) === true+ })expect(grew).toBe(true)const rows = mounted.window.currentMessages?.map(message => message.rowId) ?? []@@ -246,10 +323,14 @@ describe('paging earlier from an open history window', () => {.mockResolvedValueOnce(page(3700))const mounted = mount('stored-gap')- await act(async () => { await mounted.window.revealRow(4000, new AbortController().signal) })+ await act(async () => {+ await mounted.window.revealRow(4000, new AbortController().signal)+ })const beforePrepend = vi.fn()let grew = false- await act(async () => { grew = (await mounted.window.expandWindow(beforePrepend)) === true })+ await act(async () => {+ grew = (await mounted.window.expandWindow(beforePrepend)) === true+ })expect(grew).toBe(true)const rows = mounted.window.currentMessages?.map(message => message.rowId) ?? []@@ -267,11 +348,15 @@ describe('paging earlier from an open history window', () => {const mounted = mount('stored-unlisted')- await act(async () => { await mounted.window.revealRow(4000, new AbortController().signal) })+ await act(async () => {+ await mounted.window.revealRow(4000, new AbortController().signal)+ })expect(mounted.window.olderAvailable).toBe(true)let grew = true- await act(async () => { grew = (await mounted.window.expandWindow()) === true })+ await act(async () => {+ grew = (await mounted.window.expandWindow()) === true+ })expect(grew).toBe(false)// No page can ever arrive: stop offering one instead of failing forever.expect(mounted.window.olderAvailable).toBe(false)diff --git a/apps/desktop/src/app/chat/history-window.ts b/apps/desktop/src/app/chat/history-window.tsindex 41aeb7ac3cf..460914896f3 100644--- a/apps/desktop/src/app/chat/history-window.ts+++ b/apps/desktop/src/app/chat/history-window.ts@@ -1,7 +1,11 @@import { useCallback, useEffect, useMemo, useRef, useState } from 'react'import { capabilityScoped, hermesApi, type ProfileScope } from '@/api/client'-import { cachedTimelineIndex, previousPromptRowId, timelineIndexKey } from '@/components/assistant-ui/thread/timeline-index'+import {+ cachedTimelineIndex,+ previousPromptRowId,+ timelineIndexKey+} from '@/components/assistant-ui/thread/timeline-index'import { type ChatMessage, toChatMessages } from '@/lib/chat-messages'import type { SessionMessagesResponse } from '@/types/hermes'@@ -35,7 +39,9 @@ export async function fetchHistoryWindow(const route = capabilityScoped(scope)const query = new URLSearchParams({ row_id: String(rowId), limit: String(HISTORY_WINDOW_LIMIT) })- if (route.profile) {query.set('profile', route.profile)}+ if (route.profile) {+ query.set('profile', route.profile)+ }// The Electron REST bridge cannot transfer AbortSignal over IPC. Cancellation// below releases the caller immediately and fences the eventual bounded read;@@ -91,51 +97,67 @@ export function useHistoryWindow({ scopeKey, storedId, scope, isCurrent }: HistosetSelection(null)}, [cancel])- const revealRow = useCallback(async (rowId: number, signal: AbortSignal): Promise<string | null> => {- cancel()-- if (signal.aborted || !Number.isSafeInteger(rowId) || rowId <= 0) {return null}- const captured = latest.current-- if (!captured.storedId || !captured.isCurrent()) {return null}- const controller = new AbortController()- pending.current = controller- const abort = () => controller.abort()- signal.addEventListener('abort', abort, { once: true })- let release!: () => void-- const aborted = new Promise<null>(resolve => {- release = () => resolve(null)- controller.signal.addEventListener('abort', release, { once: true })- })+ const revealRow = useCallback(+ async (rowId: number, signal: AbortSignal): Promise<string | null> => {+ cancel()- try {- const next = await Promise.race([- fetchHistoryWindow(captured.storedId, rowId, captured.scope, controller.signal),- aborted- ])+ if (signal.aborted || !Number.isSafeInteger(rowId) || rowId <= 0) {+ return null+ }+ const captured = latest.current- if (!next || controller.signal.aborted || latest.current.lifetime !== captured.lifetime || !captured.isCurrent()) {+ if (!captured.storedId || !captured.isCurrent()) {return null}+ const controller = new AbortController()+ pending.current = controller+ const abort = () => controller.abort()+ signal.addEventListener('abort', abort, { once: true })+ let release!: () => void++ const aborted = new Promise<null>(resolve => {+ release = () => resolve(null)+ controller.signal.addEventListener('abort', release, { once: true })+ })- const target = next.messages.find(message => message.rowId === rowId)+ try {+ const next = await Promise.race([+ fetchHistoryWindow(captured.storedId, rowId, captured.scope, controller.signal),+ aborted+ ])- if (!target) {return null}- setSelection({ lifetime: captured.lifetime, page: next })+ if (+ !next ||+ controller.signal.aborted ||+ latest.current.lifetime !== captured.lifetime ||+ !captured.isCurrent()+ ) {+ return null+ }- return target.id- } catch {- // Missing/older backend, unreadable row, and failed reads preserve the- // current page. The caller reports failure and can retry explicitly.- return null- } finally {- signal.removeEventListener('abort', abort)- controller.signal.removeEventListener('abort', release)+ const target = next.messages.find(message => message.rowId === rowId)- if (pending.current === controller) {pending.current = null}- }- }, [cancel])+ if (!target) {+ return null+ }+ setSelection({ lifetime: captured.lifetime, page: next })++ return target.id+ } catch {+ // Missing/older backend, unreadable row, and failed reads preserve the+ // current page. The caller reports failure and can retry explicitly.+ return null+ } finally {+ signal.removeEventListener('abort', abort)+ controller.signal.removeEventListener('abort', release)++ if (pending.current === controller) {+ pending.current = null+ }+ }+ },+ [cancel]+ )/*** Prepend the page before this window's first prompt. The anchor's@@ -143,79 +165,84 @@ export function useHistoryWindow({ scopeKey, storedId, scope, isCurrent }: Histo* transcript's entry point and the rail page one range. `beforePrepend` is* spent in the same commit as the prepend, exactly like a live-page grow.*/- const revealOlder = useCallback(async (beforePrepend?: () => void): Promise<boolean> => {- const captured = latest.current- const current = captured.page-- // No older rows before this page's first row, or nothing to anchor on yet.- if (!current?.olderAvailable || !captured.storedId || !captured.isCurrent()) {- return false- }+ const revealOlder = useCallback(+ async (beforePrepend?: () => void): Promise<boolean> => {+ const captured = latest.current+ const current = captured.page- const anchor = current.messages.find(message => message.role === 'user' && message.rowId !== undefined)?.rowId+ // No older rows before this page's first row, or nothing to anchor on yet.+ if (!current?.olderAvailable || !captured.storedId || !captured.isCurrent()) {+ return false+ }- cancel()- const controller = new AbortController()- pending.current = controller+ const anchor = current.messages.find(message => message.role === 'user' && message.rowId !== undefined)?.rowId++ cancel()+ const controller = new AbortController()+ pending.current = controller++ try {+ const rowId = await previousPromptRowId(captured.storedId, captured.scope, anchor)++ if (rowId === null || controller.signal.aborted) {+ // A complete index that lists no prompt before this window means the+ // backend's older rows can never be paged to: retire the offer so the+ // button and the top-edge auto-page stop promising a page that never+ // arrives. An incomplete index still leaves the page untouched for a retry.+ if (+ rowId === null &&+ anchor !== undefined &&+ !controller.signal.aborted &&+ latest.current.page === current &&+ cachedTimelineIndex(timelineIndexKey(captured.storedId, captured.scope))?.complete+ ) {+ setSelection({ lifetime: captured.lifetime, page: { ...current, olderAvailable: false } })+ }++ return false+ }- try {- const rowId = await previousPromptRowId(captured.storedId, captured.scope, anchor)+ const next = await fetchHistoryWindow(captured.storedId, rowId, captured.scope, controller.signal)+ // The around route reads forward from a prompt, so a turn longer than the+ // page limit leaves rows between that page's end and this anchor. Never+ // paint that as one continuous transcript: show the older page on its+ // own instead, the way a rail jump to that mark would.+ const contiguous = next.offset + next.messages.length >= current.offset+ const messages = contiguous ? mergeOlderTranscriptPage(current.messages, next.messages) : next.messages- if (rowId === null || controller.signal.aborted) {- // A complete index that lists no prompt before this window means the- // backend's older rows can never be paged to: retire the offer so the- // button and the top-edge auto-page stop promising a page that never- // arrives. An incomplete index still leaves the page untouched for a retry.+ // A window replaced while this one was in flight owns the display page.if (- rowId === null &&- anchor !== undefined &&- !controller.signal.aborted &&- latest.current.page === current &&- cachedTimelineIndex(timelineIndexKey(captured.storedId, captured.scope))?.complete+ controller.signal.aborted ||+ messages === current.messages ||+ latest.current.lifetime !== captured.lifetime ||+ latest.current.page !== current) {- setSelection({ lifetime: captured.lifetime, page: { ...current, olderAvailable: false } })+ return false}- return false- }+ if (contiguous) {+ beforePrepend?.()+ }- const next = await fetchHistoryWindow(captured.storedId, rowId, captured.scope, controller.signal)- // The around route reads forward from a prompt, so a turn longer than the- // page limit leaves rows between that page's end and this anchor. Never- // paint that as one continuous transcript: show the older page on its- // own instead, the way a rail jump to that mark would.- const contiguous = next.offset + next.messages.length >= current.offset- const messages = contiguous ? mergeOlderTranscriptPage(current.messages, next.messages) : next.messages-- // A window replaced while this one was in flight owns the display page.- if (- controller.signal.aborted ||- messages === current.messages ||- latest.current.lifetime !== captured.lifetime ||- latest.current.page !== current- ) {- return false- }+ setSelection({+ lifetime: captured.lifetime,+ page: contiguous ? { ...next, messages, newerAvailable: current.newerAvailable } : next+ })- if (contiguous) {- beforePrepend?.()+ return true+ } catch {+ // Missing/older backend, unreadable page, and an index that cannot name+ // the predecessor all leave the page untouched; the caller reports+ // failure and can retry explicitly.+ return false+ } finally {+ if (pending.current === controller) {+ pending.current = null+ }}-- setSelection({- lifetime: captured.lifetime,- page: contiguous ? { ...next, messages, newerAvailable: current.newerAvailable } : next- })-- return true- } catch {- // Missing/older backend, unreadable page, and an index that cannot name- // the predecessor all leave the page untouched; the caller reports- // failure and can retry explicitly.- return false- } finally {- if (pending.current === controller) {pending.current = null}- }- }, [cancel])+ },+ [cancel]+ )return { page, revealRow, returnToLatest, revealOlder }}diff --git a/apps/desktop/src/app/chat/hooks/use-composer-actions.test.ts b/apps/desktop/src/app/chat/hooks/use-composer-actions.test.tsindex 6d03c6e9466..8921c992503 100644--- a/apps/desktop/src/app/chat/hooks/use-composer-actions.test.ts+++ b/apps/desktop/src/app/chat/hooks/use-composer-actions.test.ts@@ -299,17 +299,35 @@ describe('useComposerActions native image drops', () => {it('does not attach a screenshot when its draft changes during native image saving', async () => {let finishSave!: (path: string) => void- const saveImageBuffer = vi.fn(() => new Promise<string>(resolve => { finishSave = resolve }))+ const saveImageBuffer = vi.fn(+ () =>+ new Promise<string>(resolve => {+ finishSave = resolve+ })+ )const add = vi.fn()Object.defineProperty(window, 'hermesDesktop', { configurable: true, value: { saveImageBuffer } })- const { result } = renderHook(() => useComposerActions({- activeSessionId: null,- currentCwd: '/test',- requestGateway: vi.fn(),- scope: { add, remove: vi.fn(() => null), target: 'main', update: vi.fn(() => true), updateIfCurrent: vi.fn(() => true) }- }))++ const { result } = renderHook(() =>+ useComposerActions({+ activeSessionId: null,+ currentCwd: '/test',+ requestGateway: vi.fn(),+ scope: {+ add,+ remove: vi.fn(() => null),+ target: 'main',+ update: vi.fn(() => true),+ updateIfCurrent: vi.fn(() => true)+ }+ })+ )+let current = true- const pending = result.current.attachImageBlob(new Blob([new Uint8Array([1])], { type: 'image/png' }), () => current)+ const pending = result.current.attachImageBlob(+ new Blob([new Uint8Array([1])], { type: 'image/png' }),+ () => current+ )await vi.waitFor(() => expect(saveImageBuffer).toHaveBeenCalledOnce())current = falsefinishSave('/test/screenshot.png')@@ -396,22 +414,33 @@ describe('useComposerActions generated paste title metadata', () => {const savePastedText = vi.fn(async () => '/tmp/composer-pastes/pasted-content.txt')const add = vi.fn<(attachment: ComposerAttachment) => void>()Object.defineProperty(window, 'hermesDesktop', { configurable: true, value: { savePastedText } })- const { result } = renderHook(() => useComposerActions({- activeSessionId: null,- currentCwd: '/test',- requestGateway: vi.fn(),- scope: { add, remove: vi.fn(() => null), target: 'main', update: vi.fn(() => true), updateIfCurrent: vi.fn(() => true) }- }))++ const { result } = renderHook(() =>+ useComposerActions({+ activeSessionId: null,+ currentCwd: '/test',+ requestGateway: vi.fn(),+ scope: {+ add,+ remove: vi.fn(() => null),+ target: 'main',+ update: vi.fn(() => true),+ updateIfCurrent: vi.fn(() => true)+ }+ })+ )const pasted = `Database migration incident\n${'x'.repeat(1_500)}`await expect(result.current.attachPastedText(pasted)).resolves.toBe(true)- expect(add).toHaveBeenCalledWith(expect.objectContaining({- kind: 'file',- path: '/tmp/composer-pastes/pasted-content.txt',- refText: '@file:/tmp/composer-pastes/pasted-content.txt',- titlePreview: pasted.slice(0, 1_000)- }))+ expect(add).toHaveBeenCalledWith(+ expect.objectContaining({+ kind: 'file',+ path: '/tmp/composer-pastes/pasted-content.txt',+ refText: '@file:/tmp/composer-pastes/pasted-content.txt',+ titlePreview: pasted.slice(0, 1_000)+ })+ )})})diff --git a/apps/desktop/src/app/chat/index.tsx b/apps/desktop/src/app/chat/index.tsxindex 4bba263587a..979b899afcd 100644--- a/apps/desktop/src/app/chat/index.tsx+++ b/apps/desktop/src/app/chat/index.tsx@@ -60,7 +60,12 @@ import { ChatBar, ChatBarFallback } from './composer'import { FloatingComposerSurface } from './composer/floating-surface'import { requestComposerInsert } from './composer/focus'import { droppedFileInlineRefs } from './composer/inline-refs'-import { ComposerScopeProvider, ComposerSurfaceProvider, useComposerScope, useComposerSurfaceId } from './composer/scope'+import {+ ComposerScopeProvider,+ ComposerSurfaceProvider,+ useComposerScope,+ useComposerSurfaceId+} from './composer/scope'import type { ChatBarState } from './composer/types'import { useHistoryWindow } from './history-window'import { type DroppedFile, partitionDroppedFiles } from './hooks/use-composer-actions'@@ -258,9 +263,10 @@ export function ChatRuntimeBoundary({const ownerConnection = ownerRoute?.connectionIdconst ownerProfile = ownerRoute?.targetProfile || ownerRoute?.profile- const tailProfile = useMemo(() => ownerProfile- ? { connectionId: ownerConnection, profile: ownerProfile }- : undefined, [ownerConnection, ownerProfile])+ const tailProfile = useMemo(+ () => (ownerProfile ? { connectionId: ownerConnection, profile: ownerProfile } : undefined),+ [ownerConnection, ownerProfile]+ )// A Bot chat opened IN PLACE in the main pane (openStoredBotChat) keeps the// active profile, so the ambient scope carries no owner. Publish the session@@ -331,7 +337,7 @@ export function ChatRuntimeBoundary({// static history page is not the live store, and neither is a suppressed// transcript, so both opt out.useTranscriptRetention({- anchorId: windowed ? windowedMessages[0]?.id ?? null : null,+ anchorId: windowed ? (windowedMessages[0]?.id ?? null) : null,enabled: !suppressMessages && !history.page,profile: tailProfile,runtimeId,@@ -348,7 +354,9 @@ export function ChatRuntimeBoundary({async (beforePrepend?: () => void) => {// A historical page is not the live tail: its older neighbours come from// the prompt range the rail already draws, never from store backfill.- if (history.page) {return history.revealOlder(beforePrepend)}+ if (history.page) {+ return history.revealOlder(beforePrepend)+ }// Network latency is not scroll intent. Capture at arrival, immediately// before the store prepend, and only grow a window that has a page to show.@@ -406,9 +414,18 @@ export function ChatRuntimeBoundary({const newerAvailable = history.page?.newerAvailable ?? falseconst { revealRow, returnToLatest } = history- const transcriptWindow = useMemo(() => ({- olderAvailable, expandWindow, revealRow, returnToLatest, currentMessages, isHistorical, newerAvailable- }), [expandWindow, olderAvailable, revealRow, returnToLatest, currentMessages, isHistorical, newerAvailable])+ const transcriptWindow = useMemo(+ () => ({+ olderAvailable,+ expandWindow,+ revealRow,+ returnToLatest,+ currentMessages,+ isHistorical,+ newerAvailable+ }),+ [expandWindow, olderAvailable, revealRow, returnToLatest, currentMessages, isHistorical, newerAvailable]+ )const runtime = useIncrementalExternalStoreRuntime<ThreadMessage>({messageRepository: runtimeMessageRepository,diff --git a/apps/desktop/src/app/chat/preview-tile.test.ts b/apps/desktop/src/app/chat/preview-tile.test.tsindex 9d7409ddbc7..62d1861e3fc 100644--- a/apps/desktop/src/app/chat/preview-tile.test.ts+++ b/apps/desktop/src/app/chat/preview-tile.test.ts@@ -97,7 +97,10 @@ const fileTarget = (path: string) =>// just be declared on the tile.describe('preview tiles keep a live page alive across Hide', () => {it('registers a Browser tab with lifecycleKeepAlive while a text peek stays evictable', () => {- openPreview({ kind: 'url', label: 'Browser', source: 'https://example.com', url: 'https://example.com' }, 'explicit-link')+ openPreview(+ { kind: 'url', label: 'Browser', source: 'https://example.com', url: 'https://example.com' },+ 'explicit-link'+ )openPreview(fileTarget('/tmp/a.ts'), 'file-browser')const browserId = $previewTabs.get().find(tab => tab.target.kind === 'url')!.iddiff --git a/apps/desktop/src/app/chat/resume-exhausted-overlay.tsx b/apps/desktop/src/app/chat/resume-exhausted-overlay.tsxindex dbb2bab935b..ca2efbdb3af 100644--- a/apps/desktop/src/app/chat/resume-exhausted-overlay.tsx+++ b/apps/desktop/src/app/chat/resume-exhausted-overlay.tsx@@ -21,11 +21,7 @@ export function ResumeExhaustedOverlay({return (<div className="absolute inset-0 z-10 grid place-items-center bg-(--ui-chat-surface-background) px-8 py-10">- <ErrorState- className="max-w-sm"- description={t.desktop.resumeStrandedBody}- title={t.desktop.resumeStrandedTitle}- >+ <ErrorState className="max-w-sm" description={t.desktop.resumeStrandedBody} title={t.desktop.resumeStrandedTitle}><div className="grid justify-items-center gap-1.5"><Button onClick={() => requestFreshSession()} size="sm" variant="outline">{t.assistant.thread.errorStartNewSession}diff --git a/apps/desktop/src/app/chat/right-rail/preview-input.test.ts b/apps/desktop/src/app/chat/right-rail/preview-input.test.tsindex b00e9e8c076..3df85775f50 100644--- a/apps/desktop/src/app/chat/right-rail/preview-input.test.ts+++ b/apps/desktop/src/app/chat/right-rail/preview-input.test.ts@@ -6,7 +6,7 @@ import { toWebviewInputSpace } from './preview-input'// webview's input space is css × zoom. At the shipped 90 % default an// unscaled click landed 1/0.9 too far from the origin and missed silently.describe('toWebviewInputSpace', () => {- it('scales pointer events by the guest zoom so the reporter\'s 500,310 target is hit at 90 %', () => {+ it("scales pointer events by the guest zoom so the reporter's 500,310 target is hit at 90 %", () => {const down = toWebviewInputSpace({ button: 'left', clickCount: 1, type: 'mouseDown', x: 500, y: 310 }, 0.9)expect(down).toEqual({ button: 'left', clickCount: 1, type: 'mouseDown', x: 450, y: 279 })diff --git a/apps/desktop/src/app/chat/route-tile.tsx b/apps/desktop/src/app/chat/route-tile.tsxindex 5b75a87c17c..a5706ba3844 100644--- a/apps/desktop/src/app/chat/route-tile.tsx+++ b/apps/desktop/src/app/chat/route-tile.tsx@@ -13,7 +13,14 @@ import { ContribBoundary, ContribRender } from '@/contrib/react/boundary'import { useContributions } from '@/contrib/react/use-contributions'import { $routeTiles, closeRouteTile, type RouteTile } from '@/store/route-tiles'-import { $routesVersion, ARTIFACTS_ROUTE, CAPABILITIES_ROUTE, contributedRoutes, MESSAGING_ROUTE, ROUTES_AREA } from '../routes'+import {+ $routesVersion,+ ARTIFACTS_ROUTE,+ CAPABILITIES_ROUTE,+ contributedRoutes,+ MESSAGING_ROUTE,+ ROUTES_AREA+} from '../routes'import { paneMirror } from './pane-mirror'diff --git a/apps/desktop/src/app/chat/sidebar/profile-dropdown-switcher.test.tsx b/apps/desktop/src/app/chat/sidebar/profile-dropdown-switcher.test.tsxindex 89937fc0ae9..cb39d7c0f45 100644--- a/apps/desktop/src/app/chat/sidebar/profile-dropdown-switcher.test.tsx+++ b/apps/desktop/src/app/chat/sidebar/profile-dropdown-switcher.test.tsx@@ -59,7 +59,9 @@ vi.mock('@/store/connections', () => ({}))vi.mock('@/store/profile-share', () => ({ runImportProfileFlow: vi.fn() }))-vi.mock('./use-profile-prewarm', () => ({ useProfilePrewarm: () => ({ cancelPrewarm: vi.fn(), startPrewarm: vi.fn() }) }))+vi.mock('./use-profile-prewarm', () => ({+ useProfilePrewarm: () => ({ cancelPrewarm: vi.fn(), startPrewarm: vi.fn() })+}))vi.mock('./use-fleet-roster', () => ({ useFleetRoster: () => undefined }))vi.mock('../../profiles/create-profile-dialog', () => ({ CreateProfileDialog: () => null }))diff --git a/apps/desktop/src/app/chat/sidebar/profile-dropdown-switcher.tsx b/apps/desktop/src/app/chat/sidebar/profile-dropdown-switcher.tsxindex 854b7a393ee..737ee42b6be 100644--- a/apps/desktop/src/app/chat/sidebar/profile-dropdown-switcher.tsx+++ b/apps/desktop/src/app/chat/sidebar/profile-dropdown-switcher.tsx@@ -21,7 +21,12 @@ import { triggerHaptic } from '@/lib/haptics'import { Loader2 } from '@/lib/icons'import { resolveProfileColor } from '@/lib/profile-color'import { cn } from '@/lib/utils'-import { $activeConnectionId, $connectionsRegistry, $hasMultipleConnections, selectConnection } from '@/store/connections'+import {+ $activeConnectionId,+ $connectionsRegistry,+ $hasMultipleConnections,+ selectConnection+} from '@/store/connections'import { $fleetRoster } from '@/store/fleet-roster'import { notifyError } from '@/store/notifications'import {@@ -200,7 +205,9 @@ export function ProfileSwitcher({ compact = false }: { compact?: boolean }) {<DropdownMenuLabel className={cn(dropdownMenuSectionLabel, 'flex items-center gap-1.5')}><ConnectionGlyph connection={group} /><span className="truncate">{group.label}</span>- {!group.reachable && <span aria-hidden="true" className="size-1.5 shrink-0 rounded-full bg-amber-500" />}+ {!group.reachable && (+ <span aria-hidden="true" className="size-1.5 shrink-0 rounded-full bg-amber-500" />+ )}</DropdownMenuLabel>{[group.defaultAgent, ...group.named].map(agent => (<DropdownMenuItemdiff --git a/apps/desktop/src/app/chat/sidebar/profile-rail-fleet.test.tsx b/apps/desktop/src/app/chat/sidebar/profile-rail-fleet.test.tsxindex cbeb28c9162..5f5a9bb7660 100644--- a/apps/desktop/src/app/chat/sidebar/profile-rail-fleet.test.tsx+++ b/apps/desktop/src/app/chat/sidebar/profile-rail-fleet.test.tsx@@ -247,6 +247,7 @@ describe('ProfileRail fleet mode', () => {if (condensed) {fireEvent.pointerDown(screen.getByRole('button', { name: 'Profiles' }), { button: 0, ctrlKey: false })}+fireEvent.contextMenu(screen.getByRole(condensed ? (target.connectionId ? 'menuitem' : 'menuitemradio') : 'button', {name: target.labeldiff --git a/apps/desktop/src/app/chat/sidebar/profile-switcher.tsx b/apps/desktop/src/app/chat/sidebar/profile-switcher.tsxindex bdd0a83355d..7dc3722e811 100644--- a/apps/desktop/src/app/chat/sidebar/profile-switcher.tsx+++ b/apps/desktop/src/app/chat/sidebar/profile-switcher.tsx@@ -943,7 +943,9 @@ function ProfilePill({<ProfileLaunchContextMenu connectionId={connectionId ?? null} label={profile} profile={profile}>{button}</ProfileLaunchContextMenu>- ) : button+ ) : (+ button+ )}// The gateway marker that heads every group on the fleet rail: its kind glyphdiff --git a/apps/desktop/src/app/chat/sidebar/projects/overview-row.test.tsx b/apps/desktop/src/app/chat/sidebar/projects/overview-row.test.tsxindex 825e08cafb7..b4724b910f1 100644--- a/apps/desktop/src/app/chat/sidebar/projects/overview-row.test.tsx+++ b/apps/desktop/src/app/chat/sidebar/projects/overview-row.test.tsx@@ -14,7 +14,8 @@ afterEach(cleanup)const workspaceOpen = vi.hoisted(() => ({ value: false }))const projectsStore = vi.hoisted(() => ({- fetchProjectSessions: vi.fn<(id: string, options?: { supersedable?: boolean }) => Promise<null | SidebarProjectTree>>(),+ fetchProjectSessions:+ vi.fn<(id: string, options?: { supersedable?: boolean }) => Promise<null | SidebarProjectTree>>(),projectProfile: vi.fn<() => null | string>(() => 'default')}))diff --git a/apps/desktop/src/app/chat/sidebar/projects/workspace-groups.test.ts b/apps/desktop/src/app/chat/sidebar/projects/workspace-groups.test.tsindex 2045d4a7d35..bc2c3b9b9f7 100644--- a/apps/desktop/src/app/chat/sidebar/projects/workspace-groups.test.ts+++ b/apps/desktop/src/app/chat/sidebar/projects/workspace-groups.test.ts@@ -625,11 +625,13 @@ describe('overlayLiveLanes', () => {'entering an ancestor project does not inject a backend-owned sibling worktree session (git_repo_root=%s)',gitRepoRoot => {const sibling = makeCwdSession('/work/repos/app-2', { id: 'sibling', git_repo_root: gitRepoRoot })+const ancestor = projectNode({id: 'p_work',path: '/work',repos: [{ id: '/work', label: 'work', path: '/work', groups: [], sessionCount: 0 }]})+const appRepo = {id: '/work/repos/app',label: 'app',@@ -637,6 +639,7 @@ describe('overlayLiveLanes', () => {groups: [lane({ id: '/work/repos/app-2', label: 'app-2', path: '/work/repos/app-2', sessions: [] })],sessionCount: 0}+// Overview snapshot: the row sits beyond the preview window, so only the// backend's claimed-id set knows the owner.const repo = projectNode({ id: 'p_app', path: '/work/repos/app', previewSessions: [], sessionIds: ['sibling'] })@@ -1131,6 +1134,7 @@ describe('overlayLivePreviews', () => {gitRepoRoot => {const sibling = makeCwdSession('/work/repos/app-2', { id: 'sibling', git_repo_root: gitRepoRoot })const ancestor = projectNode({ id: 'p_work', path: '/work', previewSessions: [], sessionCount: 0 })+const repo = projectNode({id: 'p_app',path: '/work/repos/app',diff --git a/apps/desktop/src/app/chat/sidebar/sessions-section-new-session-drag.test.tsx b/apps/desktop/src/app/chat/sidebar/sessions-section-new-session-drag.test.tsxindex 4defe8a74e9..bc8bfa75cbf 100644--- a/apps/desktop/src/app/chat/sidebar/sessions-section-new-session-drag.test.tsx+++ b/apps/desktop/src/app/chat/sidebar/sessions-section-new-session-drag.test.tsx@@ -178,6 +178,7 @@ beforeEach(() => {describe('Show all sessions', () => {const sessions = Array.from({ length: 6 }, (_, index) => ({ id: `session-${index + 1}` }) as SessionInfo)+const renderRows = (items: SessionInfo[]) => (<>{items.map(item => (@@ -204,6 +205,7 @@ describe('Show all sessions', () => {workspaceOpen.value = true$sidebarShowAllSessions.set(true)const now = Math.floor(Date.now() / 1000)+const previewSessions = [0, 2, 10, 40].map(days =>({diff --git a/apps/desktop/src/app/chat/sidebar/use-profile-prewarm.ts b/apps/desktop/src/app/chat/sidebar/use-profile-prewarm.tsindex 46992febac3..71783941c4b 100644--- a/apps/desktop/src/app/chat/sidebar/use-profile-prewarm.ts+++ b/apps/desktop/src/app/chat/sidebar/use-profile-prewarm.ts@@ -25,6 +25,7 @@ export function useProfilePrewarm(profile: string | null | undefined) {const cancelPrewarm = useCallback(() => {armed.current = false+if (timer.current != null) {clearTimeout(timer.current)timer.current = nulldiff --git a/apps/desktop/src/app/chat/transcript-window.ts b/apps/desktop/src/app/chat/transcript-window.tsindex 8d2e526836e..08f9f041a78 100644--- a/apps/desktop/src/app/chat/transcript-window.ts+++ b/apps/desktop/src/app/chat/transcript-window.ts@@ -231,6 +231,7 @@ export function advanceSessionTranscriptWindow(// the component-local map would pin the complete source array after the// session store intentionally releases a cold transcript.memos.delete(sessionKey)+return state}diff --git a/apps/desktop/src/app/command-palette/index.tsx b/apps/desktop/src/app/command-palette/index.tsxindex eee68e05e5c..14ea5991731 100644--- a/apps/desktop/src/app/command-palette/index.tsx+++ b/apps/desktop/src/app/command-palette/index.tsx@@ -1180,7 +1180,11 @@ function CommandPaletteBody({ onExited }: { onExited: () => void }) {})}- const fieldItems = [...settingsCatalog.subpageEntries, ...settingsCatalog.appearanceEntries, ...settingsCatalog.configEntries].map(settingsEntryItem)+ const fieldItems = [+ ...settingsCatalog.subpageEntries,+ ...settingsCatalog.appearanceEntries,+ ...settingsCatalog.configEntries+ ].map(settingsEntryItem)if (fieldItems.length > 0) {result.push({ heading: t.commandCenter.settingsFields, items: fieldItems })@@ -1302,7 +1306,11 @@ function CommandPaletteBody({ onExited }: { onExited: () => void }) {if (search.trim()) {result.push({heading: cc.settingsFields,- items: [...settingsCatalog.subpageEntries, ...settingsCatalog.appearanceEntries, ...settingsCatalog.configEntries].map(settingsEntryItem)+ items: [+ ...settingsCatalog.subpageEntries,+ ...settingsCatalog.appearanceEntries,+ ...settingsCatalog.configEntries+ ].map(settingsEntryItem)})if (settingsCatalog.credentialEntries.length > 0) {diff --git a/apps/desktop/src/app/contrib/hooks/live-status-reap.test.ts b/apps/desktop/src/app/contrib/hooks/live-status-reap.test.tsindex 153d483fd34..7e202064434 100644--- a/apps/desktop/src/app/contrib/hooks/live-status-reap.test.ts+++ b/apps/desktop/src/app/contrib/hooks/live-status-reap.test.ts@@ -65,7 +65,11 @@ describe('rehydrateLiveSessionStatuses — reaping vanished runtimes', () => {// and the first fresh snapshot that does not report it working is the// terminal fact that lights the dot.it('confirms a parked reconnect completion the poll never saw live', () => {- publishSessionState('runtime-p', { ...createClientSessionState('stored-p'), busy: true, storedSessionId: 'stored-p' })+ publishSessionState('runtime-p', {+ ...createClientSessionState('stored-p'),+ busy: true,+ storedSessionId: 'stored-p'+ })reconcileBusyStatesOnReconnect()expect($unreadFinishedSessionIds.get()).toEqual([])diff --git a/apps/desktop/src/app/contrib/hooks/restore-late-plugin-route.test.tsx b/apps/desktop/src/app/contrib/hooks/restore-late-plugin-route.test.tsxindex 848981a7e19..bd635ec71c4 100644--- a/apps/desktop/src/app/contrib/hooks/restore-late-plugin-route.test.tsx+++ b/apps/desktop/src/app/contrib/hooks/restore-late-plugin-route.test.tsx@@ -10,7 +10,12 @@ import { afterEach, beforeEach, expect, it, vi } from 'vitest'import { registry } from '@/contrib/registry'import { $diskPluginsScanPending } from '@/contrib/runtime-loader'-import { _resetLegacyDiscardForTests, getRememberedRoute, setRememberedRoute, setRememberedSessionId } from '@/store/session'+import {+ _resetLegacyDiscardForTests,+ getRememberedRoute,+ setRememberedRoute,+ setRememberedSessionId+} from '@/store/session'import { makeSessionInfo } from '../../../test/session-info'@@ -76,7 +81,12 @@ it('restores a remembered plugin page whose route registers after the session liexpect(navigate).not.toHaveBeenCalled()expect(getRememberedRoute('default')).toBe('/html-gallery')- const dispose = registry.register({ area: 'routes', id: 'gallery:page', data: { path: '/html-gallery' }, render: () => null })+ const dispose = registry.register({+ area: 'routes',+ id: 'gallery:page',+ data: { path: '/html-gallery' },+ render: () => null+ })act(() => $diskPluginsScanPending.set(false))expect(navigate).toHaveBeenCalledWith('/html-gallery', { replace: true })diff --git a/apps/desktop/src/app/contrib/hooks/use-background-sync.test.ts b/apps/desktop/src/app/contrib/hooks/use-background-sync.test.tsindex 5ee7cefd5d1..9adae150638 100644--- a/apps/desktop/src/app/contrib/hooks/use-background-sync.test.ts+++ b/apps/desktop/src/app/contrib/hooks/use-background-sync.test.ts@@ -54,7 +54,10 @@ const { refreshProjectTree } = await import('@/store/projects')const ACTIVE_RUNTIME_ID = 'runtime-active'const ACTIVE_STORED_ID = 'stored-active'-function transcript(answer: string, sessionId = ACTIVE_STORED_ID): Awaited<ReturnType<typeof getLatestSessionMessages>> {+function transcript(+ answer: string,+ sessionId = ACTIVE_STORED_ID+): Awaited<ReturnType<typeof getLatestSessionMessages>> {return {messages: [{ content: 'question', role: 'user', timestamp: 1 },diff --git a/apps/desktop/src/app/contrib/hooks/use-background-sync.ts b/apps/desktop/src/app/contrib/hooks/use-background-sync.tsindex 24463a803e8..27414635e76 100644--- a/apps/desktop/src/app/contrib/hooks/use-background-sync.ts+++ b/apps/desktop/src/app/contrib/hooks/use-background-sync.ts@@ -62,9 +62,9 @@ export function resolveActiveTranscriptSession(storedSessionId: string,runtimeSessionId: string): ActiveTranscriptSession | undefined {- const verifiedOwner = $sessionTiles.get().find(- tile => tile.storedSessionId === storedSessionId && tile.runtimeId === runtimeSessionId- )?.ownerRoute+ const verifiedOwner = $sessionTiles+ .get()+ .find(tile => tile.storedSessionId === storedSessionId && tile.runtimeId === runtimeSessionId)?.ownerRouteif (verifiedOwner) {return { ownerRoute: verifiedOwner, profile: verifiedOwner.profile }@@ -221,10 +221,7 @@ export async function reconcileTileTranscripts({// message would have to be retyped. Same composition order as// reconcileAuthoritativeChatMessages (use-session-actions/index.ts).messages: preserveLocalAssistantErrors(- preserveLocalPendingTurnMessages(- graftRefreshedTailOntoBackfill(messages, state.messages),- state.messages- ),+ preserveLocalPendingTurnMessages(graftRefreshedTailOntoBackfill(messages, state.messages), state.messages),state.messages)}),@@ -303,10 +300,7 @@ export async function reconcileActiveTranscript({// older pages "Show earlier" already backfilled instead of clobbering// them (see transcript-backfill).messages: preserveLocalAssistantErrors(- preserveLocalPendingTurnMessages(- graftRefreshedTailOntoBackfill(messages, state.messages),- state.messages- ),+ preserveLocalPendingTurnMessages(graftRefreshedTailOntoBackfill(messages, state.messages), state.messages),state.messages)}),diff --git a/apps/desktop/src/app/contrib/hooks/use-desktop-integrations.ts b/apps/desktop/src/app/contrib/hooks/use-desktop-integrations.tsindex 4af2e45e722..8aabbd1f1fa 100644--- a/apps/desktop/src/app/contrib/hooks/use-desktop-integrations.ts+++ b/apps/desktop/src/app/contrib/hooks/use-desktop-integrations.ts@@ -207,7 +207,16 @@ export function useDesktopIntegrations({} else if (!routedSessionId && !isOverlayView(appViewForPath(locationPathname))) {setRememberedRoute(locationPathname, activeProfile)}- }, [activeProfile, diskPluginsScanPending, locationPathname, navigate, profileReady, resumeLastSession, routedSessionId, sessions])+ }, [+ activeProfile,+ diskPluginsScanPending,+ locationPathname,+ navigate,+ profileReady,+ resumeLastSession,+ routedSessionId,+ sessions+ ])useEffect(() => {if (!profileReady || !resumeExhaustedSessionId) {diff --git a/apps/desktop/src/app/contrib/onboarding-kickoff.ts b/apps/desktop/src/app/contrib/onboarding-kickoff.tsindex 53998f8097e..40ef09699d0 100644--- a/apps/desktop/src/app/contrib/onboarding-kickoff.ts+++ b/apps/desktop/src/app/contrib/onboarding-kickoff.ts@@ -145,7 +145,9 @@ export function useOnboardingKickoff({})const seedMessages = buildChatOnboardingSeedMessages(- pickOnboardingGreeting(), record.free_tier !== true, capabilities+ pickOnboardingGreeting(),+ record.free_tier !== true,+ capabilities)const createOverrides: SessionCreateOverrides = { title: SETUP_CHAT_TITLE }diff --git a/apps/desktop/src/app/contrib/session-rpc-dispatcher.test.ts b/apps/desktop/src/app/contrib/session-rpc-dispatcher.test.tsindex baf69023e3b..16ce7d5abf9 100644--- a/apps/desktop/src/app/contrib/session-rpc-dispatcher.test.ts+++ b/apps/desktop/src/app/contrib/session-rpc-dispatcher.test.ts@@ -149,7 +149,7 @@ describe('createSessionRpcDispatcher: exact owner rungs', () => {expect(probe.resolveSessionOwner).not.toHaveBeenCalled()})- it('routes a freshly recovered runtime id to its session\'s owner only once the binding is published', async () => {+ it("routes a freshly recovered runtime id to its session's owner only once the binding is published", async () => {// A session-scoped retry after withSessionNotFoundResume: the new runtime id is// known to nobody until the recovering caller publishes stored → runtime. Before// that, the dispatcher cannot translate it and fails closed; after, it reaches thediff --git a/apps/desktop/src/app/contrib/wiring.tsx b/apps/desktop/src/app/contrib/wiring.tsxindex 7d6671db749..203fb37692f 100644--- a/apps/desktop/src/app/contrib/wiring.tsx+++ b/apps/desktop/src/app/contrib/wiring.tsx@@ -253,9 +253,9 @@ export function ContribWiring({ children }: { children: ReactNode }) {return}- void window.hermesDesktop?.recycleBackend?.(normalizeProfileKey($activeGatewayProfile.get())).catch(err =>- notifyError(err, translateNow('notifications.errors.restartHermesFailed'))- )+ void window.hermesDesktop+ ?.recycleBackend?.(normalizeProfileKey($activeGatewayProfile.get()))+ .catch(err => notifyError(err, translateNow('notifications.errors.restartHermesFailed')))}}, [backendRestartRequest])@@ -1327,7 +1327,10 @@ export function ContribWiring({ children }: { children: ReactNode }) {/>)}{!isHudWindow() && customWindowControls && (- <WslgWindowControls isFullscreen={Boolean(connection?.isFullscreen)} isMaximized={Boolean(connection?.isMaximized)} />+ <WslgWindowControls+ isFullscreen={Boolean(connection?.isFullscreen)}+ isMaximized={Boolean(connection?.isMaximized)}+ />)}{children}</div>diff --git a/apps/desktop/src/app/cron/cron-job-model.test.ts b/apps/desktop/src/app/cron/cron-job-model.test.tsindex 839a722cfbb..a29de820e45 100644--- a/apps/desktop/src/app/cron/cron-job-model.test.ts+++ b/apps/desktop/src/app/cron/cron-job-model.test.ts@@ -170,7 +170,9 @@ describe('nextRunOverdueMs', () => {it('keeps upcoming, within-grace, paused and unparseable slots as plain next runs', () => {expect(nextRunOverdueMs({ enabled: true, next_run_at: '2026-09-17T21:00:00+04:00' }, now)).toBeNull()expect(nextRunOverdueMs({ enabled: true, next_run_at: '2026-09-17T20:30:00+04:00' }, now)).toBeNull()- expect(nextRunOverdueMs({ enabled: true, next_run_at: '2026-09-17T13:34:18+04:00', state: 'paused' }, now)).toBeNull()+ expect(+ nextRunOverdueMs({ enabled: true, next_run_at: '2026-09-17T13:34:18+04:00', state: 'paused' }, now)+ ).toBeNull()expect(nextRunOverdueMs({ enabled: false, next_run_at: '2026-09-17T13:34:18+04:00' }, now)).toBeNull()expect(nextRunOverdueMs({ enabled: true, next_run_at: 'not-a-date' }, now)).toBeNull()})diff --git a/apps/desktop/src/app/cron/cron-job-model.ts b/apps/desktop/src/app/cron/cron-job-model.tsindex bf94470b64b..f0106001c52 100644--- a/apps/desktop/src/app/cron/cron-job-model.ts+++ b/apps/desktop/src/app/cron/cron-job-model.ts@@ -110,7 +110,7 @@ export function lastErrorSummary(lastError: string | null | undefined): string {let text = (lastError ?? '').trim()// Wrappers can nest (marker, then emoji, then exception class); peel until stable.- for (let previous = ''; previous !== text; ) {+ for (let previous = ''; previous !== text;) {previous = texttext = text.replace(ERROR_MARKER_RE, '').replace(ERROR_EMOJI_RE, '').replace(ERROR_PREFIX_RE, '').trimStart()}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 eb13cc0ad8c..fb117d2b8a2 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@@ -527,7 +527,12 @@ describe('primary failure foreground isolation', () => {}))})- desktop.getConnection.mockResolvedValue({ ...primaryConn, mode: 'remote', remoteKind: 'cloud', authMode: 'oauth' } as typeof primaryConn)+ desktop.getConnection.mockResolvedValue({+ ...primaryConn,+ mode: 'remote',+ remoteKind: 'cloud',+ authMode: 'oauth'+ } as typeof primaryConn);(window as { hermesDesktop?: unknown }).hermesDesktop = desktoprender(<Harness />)await flushAsync()@@ -655,7 +660,9 @@ describe('primary failure foreground isolation', () => {desktop.getGatewayWsUrl.mockImplementation(async conn => conn?.wsUrl ?? primaryConn.wsUrl)// A rejected session waits for explicit recovery, even after credentials change.let recovery!: Promise<void>- act(() => { recovery = reconnectGateway() })+ act(() => {+ recovery = reconnectGateway()+ })await flushAsync()await recoveryexpect($gatewayState.get()).toBe('open')@@ -691,7 +698,9 @@ describe('useGatewayBoot remote reconnect loop (real hook, fake socket)', () =>await advanceBackoff()expect(desktop.getGatewayWsUrl).toHaveBeenCalledTimes(calls)desktop.getGatewayWsUrl.mockResolvedValue(primaryConn.wsUrl)- act(() => { connectionApplied?.() })+ act(() => {+ connectionApplied?.()+ })await flushAsync()expect($gatewayState.get()).toBe('open')expect($desktopBoot.get().error).toBeNull()diff --git a/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts b/apps/desktop/src/app/gateway/hooks/use-gateway-boot.tsindex 482ef96f3eb..9602d1c281a 100644--- a/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts+++ b/apps/desktop/src/app/gateway/hooks/use-gateway-boot.ts@@ -529,7 +529,14 @@ export function useGatewayBoot({}function scheduleReconnect(manual?: { profile: string; activationEpoch: number }) {- if (cancelled || primaryReauthError || reconnecting || reconnectTimer !== null || gatewayOpen() || $gatewaySwitching.get()) {+ if (+ cancelled ||+ primaryReauthError ||+ reconnecting ||+ reconnectTimer !== null ||+ gatewayOpen() ||+ $gatewaySwitching.get()+ ) {return}@@ -629,6 +636,7 @@ export function useGatewayBoot({async function getWindowBackend(startup = false): Promise<HermesConnection> {const profile = windowProfileOverride()const peer = isPeerInstanceWindow()+const route = profile? { profile, connectionId: peer ? new URLSearchParams(window.location.search).get('connectionId') : null }: startup && !peerdiff --git a/apps/desktop/src/app/messaging/index.tsx b/apps/desktop/src/app/messaging/index.tsxindex e36ba08bd4a..60a863f9028 100644--- a/apps/desktop/src/app/messaging/index.tsx+++ b/apps/desktop/src/app/messaging/index.tsx@@ -424,7 +424,10 @@ export function MessagingView({ setStatusbarItemGroup: _setStatusbarItemGroup, .title: m.restartFailedManual,message: m.restartFailedManualDetail,action: { label: m.restartAgain, onClick: () => void runGatewayRestart() },- secondaryAction: { label: m.openLogs, onClick: () => void window.hermesDesktop?.revealLogs?.().catch(() => undefined) }+ secondaryAction: {+ label: m.openLogs,+ onClick: () => void window.hermesDesktop?.revealLogs?.().catch(() => undefined)+ }})}diff --git a/apps/desktop/src/app/open-session.test.ts b/apps/desktop/src/app/open-session.test.tsindex c3448ce64c1..17ff366006e 100644--- a/apps/desktop/src/app/open-session.test.ts+++ b/apps/desktop/src/app/open-session.test.ts@@ -5,9 +5,9 @@ const openSessionTile = vi.fn()const reuseBlankDraftTile = vi.fn()const setSessionTileWorkspaceScope = vi.fn()-const focusedSessionWorkspaceScope = vi.fn<- () => { workspaceMode: 'bots' | 'sessions'; workspaceOwnerKey?: string }->(() => ({ workspaceMode: 'sessions' }))+const focusedSessionWorkspaceScope = vi.fn<() => { workspaceMode: 'bots' | 'sessions'; workspaceOwnerKey?: string }>(+ () => ({ workspaceMode: 'sessions' })+)const openSessionInNewWindow = vi.fn()const canOpenSessionWindow = vi.fn(() => true)diff --git a/apps/desktop/src/app/open-session.ts b/apps/desktop/src/app/open-session.tsindex 2c441057d6a..9951a536f5c 100644--- a/apps/desktop/src/app/open-session.ts+++ b/apps/desktop/src/app/open-session.ts@@ -150,7 +150,8 @@ export function openSession(// routes the saved chat elsewhere while leaving the visible blank tab// active. Force the tab path so it first focuses an existing target, then// spends the scoped blank draft before stacking a new tab.- spendBlankDraft = Boolean(botWorkspaceScope) || mainChatOccupied($activeSessionId.get(), $selectedStoredSessionId.get())+ spendBlankDraft =+ Boolean(botWorkspaceScope) || mainChatOccupied($activeSessionId.get(), $selectedStoredSessionId.get())resolved = spendBlankDraft ? 'tab' : 'in-place'}diff --git a/apps/desktop/src/app/overlays/overlay-split-layout.test.tsx b/apps/desktop/src/app/overlays/overlay-split-layout.test.tsxindex 9c66340e938..2a4fdd6a8e4 100644--- a/apps/desktop/src/app/overlays/overlay-split-layout.test.tsx+++ b/apps/desktop/src/app/overlays/overlay-split-layout.test.tsx@@ -11,9 +11,17 @@ it('expands independently of navigation and reveals a newly selected child', ()const select = vi.fn()const group = (active: boolean, child: string): OverlayNavGroup => ({- active, id: 'appearance', label: 'Appearance', icon: Settings2, onSelect: select,+ active,+ id: 'appearance',+ label: 'Appearance',+ icon: Settings2,+ onSelect: select,children: ['General', 'Theme'].map(label => ({- active: active && child === label, id: label, label, icon: Settings2, onSelect: select+ active: active && child === label,+ id: label,+ label,+ icon: Settings2,+ onSelect: select}))})diff --git a/apps/desktop/src/app/right-sidebar/terminal/rail.tsx b/apps/desktop/src/app/right-sidebar/terminal/rail.tsxindex 39ae4f9cab1..cb27f6d9714 100644--- a/apps/desktop/src/app/right-sidebar/terminal/rail.tsx+++ b/apps/desktop/src/app/right-sidebar/terminal/rail.tsx@@ -121,7 +121,10 @@ function TerminalRailItem({ active, canCloseOthers, index, term, toggleHint }: TclassName="absolute inset-y-0.5 right-0 w-0.5 rounded-l-sm bg-(--ui-stroke-primary)"/>)}- <Tip label={<TipHintLabel hint={toggleHint && formatCombo(toggleHint)} text={label} />} placement="right-rail">+ <Tip+ label={<TipHintLabel hint={toggleHint && formatCombo(toggleHint)} text={label} />}+ placement="right-rail"+ ><buttonaria-label={label}aria-selected={active}diff --git a/apps/desktop/src/app/routes.workspace-reveal.test.ts b/apps/desktop/src/app/routes.workspace-reveal.test.tsindex c7039223dce..925036cb106 100644--- a/apps/desktop/src/app/routes.workspace-reveal.test.ts+++ b/apps/desktop/src/app/routes.workspace-reveal.test.ts@@ -161,14 +161,15 @@ describe('navigateToWorkspacePage', () => {expect(fronted()).toBe(true)})- it.each([`${CAPABILITIES_ROUTE}?tab=skills`, `${CAPABILITIES_ROUTE}?tab=toolsets`, `${CAPABILITIES_ROUTE}?tab=mcp&server=ctx7`])(- 'fronts for the palette target %s',- to => {- navigateToWorkspacePage(vi.fn(), to)+ it.each([+ `${CAPABILITIES_ROUTE}?tab=skills`,+ `${CAPABILITIES_ROUTE}?tab=toolsets`,+ `${CAPABILITIES_ROUTE}?tab=mcp&server=ctx7`+ ])('fronts for the palette target %s', to => {+ navigateToWorkspacePage(vi.fn(), to)- expect(fronted()).toBe(true)- }- )+ expect(fronted()).toBe(true)+ })it('passes navigation options through', () => {const navigate = vi.fn()diff --git a/apps/desktop/src/app/session/hooks/default-new-session.test.tsx b/apps/desktop/src/app/session/hooks/default-new-session.test.tsxindex 3540195dfd1..b96918b0373 100644--- a/apps/desktop/src/app/session/hooks/default-new-session.test.tsx+++ b/apps/desktop/src/app/session/hooks/default-new-session.test.tsx@@ -51,6 +51,7 @@ function mountActions() {const requestGateway = vi.fn(async () => ({ session_id: 'ambient', stored_session_id: 'ambient-stored' }) as never)const navigate = vi.fn()const state = createClientSessionState()+const result = renderHook(() =>useSessionActions({activeSessionId: 'existing-runtime',@@ -71,6 +72,7 @@ function mountActions() {updateSessionState: () => state}))+return { ...result, navigate, requestGateway }}diff --git a/apps/desktop/src/app/session/hooks/profile-rail-fresh-chat-owner.test.tsx b/apps/desktop/src/app/session/hooks/profile-rail-fresh-chat-owner.test.tsxindex f83cf41bc44..8c2973fe6d0 100644--- a/apps/desktop/src/app/session/hooks/profile-rail-fresh-chat-owner.test.tsx+++ b/apps/desktop/src/app/session/hooks/profile-rail-fresh-chat-owner.test.tsx@@ -511,72 +511,80 @@ describe('profile rail: a fresh Omar chat keeps its exact registry owner across{ connectionId: null, activeProfile: 'default' },{ connectionId: 'local', activeProfile: 'default' },{ connectionId: null, activeProfile: 'omar' }- ])('captures the saved $connectionId default before activation from remote $activeProfile', async ({ connectionId, activeProfile }) => {- const primary = makePrimary()- setPrimaryGateway(primary as never, 'default')- await ensureGatewayAgent(SOURCE_ID, activeProfile)- ownerPort = connectionId === null ? V1_PORT : OMAR_PORT- const activation = deferred<void>()- const desktop = window.hermesDesktop!- vi.mocked(desktop.getConnectionFor!).mockClear()- const getConnection = vi.mocked(desktop.getConnection).getMockImplementation()!- const getConnectionFor = vi.mocked(desktop.getConnectionFor!).getMockImplementation()!-- vi.mocked(desktop.getConnection).mockImplementation(async profile => {- await activation.promise- return { ...(await getConnection(profile)), mode: 'remote' }- })- vi.mocked(desktop.getConnectionFor!).mockImplementation(async route => {- await activation.promise- return getConnectionFor(route)- })-- const ambientRequest = vi.fn(async (method: string, params?: Record<string, unknown>) =>- (activeGateway() as unknown as MockGateway).request(method, params)- )- let handle: HarnessHandle | null = null- render(<Harness ambientRequest={ambientRequest} onReady={h => (handle = h)} />)- await waitFor(() => expect(handle).not.toBeNull())- $defaultProfileRoute.set({ connectionId, profile: 'omar' })- let creating!: Promise<string | null>-- try {- act(() => prepareDefaultNewSession())- expect(activeGatewayConnectionId()).toBe(SOURCE_ID)- expect(resolveNewChatOwnerRoute()).toEqual(connectionId === null ? null : { connectionId, profile: 'omar' })- creating = handle!.createSession()- expect(runtimeOwner).toBeNull()- } finally {- activation.resolve()- }+ ])(+ 'captures the saved $connectionId default before activation from remote $activeProfile',+ async ({ connectionId, activeProfile }) => {+ const primary = makePrimary()+ setPrimaryGateway(primary as never, 'default')+ await ensureGatewayAgent(SOURCE_ID, activeProfile)+ ownerPort = connectionId === null ? V1_PORT : OMAR_PORT+ const activation = deferred<void>()+ const desktop = window.hermesDesktop!+ vi.mocked(desktop.getConnectionFor!).mockClear()+ const getConnection = vi.mocked(desktop.getConnection).getMockImplementation()!+ const getConnectionFor = vi.mocked(desktop.getConnectionFor!).getMockImplementation()!++ vi.mocked(desktop.getConnection).mockImplementation(async profile => {+ await activation.promise++ return { ...(await getConnection(profile)), mode: 'remote' }+ })+ vi.mocked(desktop.getConnectionFor!).mockImplementation(async route => {+ await activation.promise++ return getConnectionFor(route)+ })++ const ambientRequest = vi.fn(async (method: string, params?: Record<string, unknown>) =>+ (activeGateway() as unknown as MockGateway).request(method, params)+ )++ let handle: HarnessHandle | null = null+ render(<Harness ambientRequest={ambientRequest} onReady={h => (handle = h)} />)+ await waitFor(() => expect(handle).not.toBeNull())+ $defaultProfileRoute.set({ connectionId, profile: 'omar' })+ let creating!: Promise<string | null>++ try {+ act(() => prepareDefaultNewSession())+ expect(activeGatewayConnectionId()).toBe(SOURCE_ID)+ expect(resolveNewChatOwnerRoute()).toEqual(connectionId === null ? null : { connectionId, profile: 'omar' })+ creating = handle!.createSession()+ expect(runtimeOwner).toBeNull()+ } finally {+ activation.resolve()+ }- await expect(creating).resolves.toBe(mintedRuntimeId)- await expect(handle!.submitText('first prompt')).resolves.toBe(true)- await settleTurn(handle!)- await expect(handle!.submitText('second prompt')).resolves.toBe(true)- const owner = sockets.find(socket => socket.connectUrl?.includes(`:${ownerPort}`))!- expect(runtimeOwner).toBe(owner)- expect(calls(owner).filter(method => method === 'session.create')).toHaveLength(1)- expect(calls(owner).filter(method => method === 'prompt.submit')).toHaveLength(2)- expect(desktop.getConnectionFor).not.toHaveBeenCalledWith({ connectionId: SOURCE_ID, profile: 'omar' })-- if (connectionId === null) {- expect(desktop.getConnection).toHaveBeenCalledWith('omar')- expect(desktop.getConnectionFor).not.toHaveBeenCalledWith({ connectionId: 'local', profile: 'omar' })- expect($connection.get()?.mode).toBe('remote')- expect(getSessionOwnerHint(mintedStoredId)).toBeUndefined()- } else {- expect(desktop.getConnectionFor).toHaveBeenCalledWith({ connectionId: 'local', profile: 'omar' })- expect(desktop.getConnection).not.toHaveBeenCalledWith('omar')- expect(getSessionOwnerHint(mintedStoredId)).toEqual({ connectionId, profile: 'omar' })- }+ await expect(creating).resolves.toBe(mintedRuntimeId)+ await expect(handle!.submitText('first prompt')).resolves.toBe(true)+ await settleTurn(handle!)+ await expect(handle!.submitText('second prompt')).resolves.toBe(true)+ const owner = sockets.find(socket => socket.connectUrl?.includes(`:${ownerPort}`))!+ expect(runtimeOwner).toBe(owner)+ expect(calls(owner).filter(method => method === 'session.create')).toHaveLength(1)+ expect(calls(owner).filter(method => method === 'prompt.submit')).toHaveLength(2)+ expect(desktop.getConnectionFor).not.toHaveBeenCalledWith({ connectionId: SOURCE_ID, profile: 'omar' })++ if (connectionId === null) {+ expect(desktop.getConnection).toHaveBeenCalledWith('omar')+ expect(desktop.getConnectionFor).not.toHaveBeenCalledWith({ connectionId: 'local', profile: 'omar' })+ expect($connection.get()?.mode).toBe('remote')+ expect(getSessionOwnerHint(mintedStoredId)).toBeUndefined()+ } else {+ expect(desktop.getConnectionFor).toHaveBeenCalledWith({ connectionId: 'local', profile: 'omar' })+ expect(desktop.getConnection).not.toHaveBeenCalledWith('omar')+ expect(getSessionOwnerHint(mintedStoredId)).toEqual({ connectionId, profile: 'omar' })+ }- for (const socket of [primary, ...sockets]) {- if (socket !== owner) {- expect(socket.request.mock.calls.filter(call => sessionScoped(call[1]) || call[0] === 'session.create')).toEqual([])+ for (const socket of [primary, ...sockets]) {+ if (socket !== owner) {+ expect(+ socket.request.mock.calls.filter(call => sessionScoped(call[1]) || call[0] === 'session.create')+ ).toEqual([])+ }}}- })+ )it('dials homelab::omar when boot published homelab on the active primary gateway', async () => {const primary = makePrimary()diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/duplicate-completion.test.tsx b/apps/desktop/src/app/session/hooks/use-message-stream/duplicate-completion.test.tsxindex 423f5d6e9d8..423eb0c5256 100644--- a/apps/desktop/src/app/session/hooks/use-message-stream/duplicate-completion.test.tsx+++ b/apps/desktop/src/app/session/hooks/use-message-stream/duplicate-completion.test.tsx@@ -70,9 +70,15 @@ it('keeps distinct segments, user boundaries, and failures on their own side ofconst earlierId = stream.state().messages[0].idif (fixture.user) {- stream.states.set(SID, appendMidTurnUserMessage(stream.state(), {- id: 'correction', role: 'user', parts: [textPart('Use the other file.')], hidden: fixture.hidden- }))+ stream.states.set(+ SID,+ appendMidTurnUserMessage(stream.state(), {+ id: 'correction',+ role: 'user',+ parts: [textPart('Use the other file.')],+ hidden: fixture.hidden+ })+ )}if (fixture.assistant) {@@ -90,12 +96,20 @@ it('keeps distinct segments, user boundaries, and failures on their own side of}const liveId = stream.state().streamId- await send('message.complete', { text: fixture.final ?? 'same reply', ...(fixture.error ? { error: fixture.error, status: 'error' } : {}) })+ await send('message.complete', {+ text: fixture.final ?? 'same reply',+ ...(fixture.error ? { error: fixture.error, status: 'error' } : {})+ })const messages = stream.state().messagesexpect(messages.at(-1)?.id, fixture.name).toBe(liveId)- expect(chatMessageText(messages.find(message => message.id === earlierId)!), fixture.name).toBe(fixture.interim ?? 'same reply')- expect(messages.at(-1)?.parts.some(part => part.type === 'tool-call'), fixture.name).toBe(true)+ expect(chatMessageText(messages.find(message => message.id === earlierId)!), fixture.name).toBe(+ fixture.interim ?? 'same reply'+ )+ expect(+ messages.at(-1)?.parts.some(part => part.type === 'tool-call'),+ fixture.name+ ).toBe(true)if (fixture.error) {expect(messages.at(-1)?.error).toBe(fixture.error)diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/input-requests.approval-timeout.test.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/input-requests.approval-timeout.test.tsindex 945aacde4c9..efd14874615 100644--- a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/input-requests.approval-timeout.test.ts+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/input-requests.approval-timeout.test.ts@@ -56,6 +56,7 @@ describe('approval request.cancel', () => {const next = updateSessionState.mock.results[0]?.value as {messages: { role: string; parts: { text: string }[] }[]}+expect(next.messages).toHaveLength(1)expect(next.messages[0].role).toBe('system')expect(next.messages[0].parts[0].text).toMatch(/timed out/i)diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/server-requests.test.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/server-requests.test.tsindex 29783ea8819..efdc3392aeb 100644--- a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/server-requests.test.ts+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/server-requests.test.ts@@ -19,7 +19,11 @@ const deps = {function deliver(method: string, params: Record<string, unknown>, activeSessionId: null | string) {const respond = vi.fn()const fail = vi.fn()- const handled = handleServerRequest({ fail, id: 'srq-1', method, params, profile: 'default', respond }, deps, activeSessionId)+ const handled = handleServerRequest(+ { fail, id: 'srq-1', method, params, profile: 'default', respond },+ deps,+ activeSessionId+ )return { fail, handled, respond }}@@ -83,7 +87,11 @@ describe('preview action request routing', () => {})it('leaves a scoped action request unanswered in a window showing another session', () => {- const { handled, respond, fail } = deliver('preview.act', { action: 'elements', session_id: 'session-a' }, 'session-b')+ const { handled, respond, fail } = deliver(+ 'preview.act',+ { action: 'elements', session_id: 'session-a' },+ 'session-b'+ )expect(handled).toBe(true)expect(respond).not.toHaveBeenCalled()@@ -103,7 +111,7 @@ describe('preview action request routing', () => {}})- it('answers pane reads for a session hosted in one of this window\'s tiles', async () => {+ it("answers pane reads for a session hosted in one of this window's tiles", async () => {// The tile session is not the active one, but this window hosts it: its// panes are here, so an 'ignore' would stall the tool until its deadline.$sessionTiles.set([{ runtimeId: 'session-a', storedSessionId: 'stored-a' } as never])diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/server-requests.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/server-requests.tsindex dd994c16459..6ad48827938 100644--- a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/server-requests.ts+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/server-requests.ts@@ -455,7 +455,10 @@ export function handleServerRequest(// publishes its binding synchronously between this replay and the next// turn. A second miss deliberately stays silent for another window.setTimeout(() => {- if (previewSessionRoute({ activeSessionId: deps.activeSessionIdRef.current, replayed: false, sessionId }) === 'run') {+ if (+ previewSessionRoute({ activeSessionId: deps.activeSessionIdRef.current, replayed: false, sessionId }) ===+ 'run'+ ) {handler({ deps, request, sessionId, isActiveSession: true })}}, 0)diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/status.test.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/status.test.tsindex 654573dba12..42bd43b1848 100644--- a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/status.test.ts+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/status.test.ts@@ -76,7 +76,7 @@ describe('gateway `error` event → error card + toast', () => {expect(toast.action).toBeUndefined()})- it('keeps the server\'s own plain copy as the toast message when no code was recovered', () => {+ it("keeps the server's own plain copy as the toast message when no code was recovered", () => {// tui_gateway/user_messages.py already writes actionable sentences for// pre-turn failures; the generic "couldn't finish" gloss must not bury them.const serverCopy = 'Hermes could not start the assistant for this chat. Check your model settings and try again.'diff --git a/apps/desktop/src/app/session/hooks/use-model-controls.ts b/apps/desktop/src/app/session/hooks/use-model-controls.tsindex 8f1a6a9ff90..569056b26e2 100644--- a/apps/desktop/src/app/session/hooks/use-model-controls.ts+++ b/apps/desktop/src/app/session/hooks/use-model-controls.ts@@ -335,14 +335,7 @@ export function useModelControls({return false}},- [- cacheOwnerConnectionId,- cacheProfile,- copy.modelSwitchFailed,- queryClient,- requestGateway,- updateModelOptionsCache- ]+ [cacheOwnerConnectionId, cacheProfile, copy.modelSwitchFailed, queryClient, requestGateway, updateModelOptionsCache])return { applySavedMainModel, refreshCurrentModel, selectModel }diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/index.test.tsx b/apps/desktop/src/app/session/hooks/use-prompt-actions/index.test.tsxindex 00ca71b44c6..1b4bda1dd19 100644--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/index.test.tsx+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/index.test.tsx@@ -2288,7 +2288,10 @@ describe('usePromptActions submit / queue drain semantics', () => {})expect(accepted).toBe(true)- const calls = requestGateway.mock.calls.map(([method, params]) => [method, (params as { session_id?: string })?.session_id])+ const calls = requestGateway.mock.calls.map(([method, params]) => [+ method,+ (params as { session_id?: string })?.session_id+ ])// The recovery resumes the queued send's OWN session…expect(calls).toContainEqual(['session.resume', 'stored-session-b'])diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/submit.ts b/apps/desktop/src/app/session/hooks/use-prompt-actions/submit.tsindex 17eb6006fed..5f82402114f 100644--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/submit.ts+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/submit.ts@@ -133,7 +133,9 @@ export function useSubmitPrompt(deps: SubmitPromptDeps) {Boolean(a))- const titlePreview = attachments.find(a => typeof a.titlePreview === 'string' && a.titlePreview.trim())?.titlePreview+ const titlePreview = attachments.find(+ a => typeof a.titlePreview === 'string' && a.titlePreview.trim()+ )?.titlePreviewconst terminalContextBlocks = terminalContextBlocksFromDraft(rawText).join('\n\n')const hasImage = attachments.some(a => a.kind === 'image')diff --git a/apps/desktop/src/app/session/hooks/use-session-actions.test.tsx b/apps/desktop/src/app/session/hooks/use-session-actions.test.tsxindex eba90a0b298..3afd50e32c1 100644--- a/apps/desktop/src/app/session/hooks/use-session-actions.test.tsx+++ b/apps/desktop/src/app/session/hooks/use-session-actions.test.tsx@@ -4799,7 +4799,12 @@ describe('selectSidebarItem', () => {await waitFor(() => expect(handle).not.toBeNull())act(() => {- handle!.selectSidebarItem({ icon: (() => null) as never, id: 'skills', label: 'Capabilities', route: '/capabilities' })+ handle!.selectSidebarItem({+ icon: (() => null) as never,+ id: 'skills',+ label: 'Capabilities',+ route: '/capabilities'+ })})expect(navigate).toHaveBeenCalledWith('/capabilities', undefined)diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/index.ts b/apps/desktop/src/app/session/hooks/use-session-actions/index.tsindex 0231259a8ea..00c1078d79a 100644--- a/apps/desktop/src/app/session/hooks/use-session-actions/index.ts+++ b/apps/desktop/src/app/session/hooks/use-session-actions/index.ts@@ -318,7 +318,10 @@ async function desktopSessionCreateParams(}const profile =- capturedRoute?.profile || requestedProfile || $newChatProfile.get() || normalizeProfileKey($activeGatewayProfile.get())+ capturedRoute?.profile ||+ requestedProfile ||+ $newChatProfile.get() ||+ normalizeProfileKey($activeGatewayProfile.get())if (capturedRoute) {await ensureGatewayAgent(capturedRoute.connectionId, profile)@@ -813,15 +816,17 @@ export function useSessionActions({// to fall through into the last project folder while main chat was// occupied (openTab path for "New session in Home").const explicitTarget =- options?.profile !== undefined || options?.cwd !== undefined || options?.workspaceScope?.ownerRoute !== undefined+ options?.profile !== undefined ||+ options?.cwd !== undefined ||+ options?.workspaceScope?.ownerRoute !== undefinedconst defaultTarget = options?.route === undefined && !explicitTarget ? defaultNewSessionTarget() : nullconst capturedRoute =options?.route !== undefined? options.route- : options?.workspaceScope?.ownerRoute ??- (defaultTarget ? defaultTarget.route : resolveNewChatOwnerRoute(options?.profile))+ : (options?.workspaceScope?.ownerRoute ??+ (defaultTarget ? defaultTarget.route : resolveNewChatOwnerRoute(options?.profile)))// A named local profile uses the legacy profile-only transport (no// connectionId). Tab-strip "+" omits `options.profile`; the draft ordiff --git a/apps/desktop/src/app/session/hooks/use-session-actions/utils.ts b/apps/desktop/src/app/session/hooks/use-session-actions/utils.tsindex b3241281367..5927244643c 100644--- a/apps/desktop/src/app/session/hooks/use-session-actions/utils.ts+++ b/apps/desktop/src/app/session/hooks/use-session-actions/utils.ts@@ -373,8 +373,7 @@ export function reconcileResumeMessages(nextMessages: ChatMessage[], previousMes// empty/tool-only hydrated row can share a role ordinal while being// different turns, and plain `'' === ''` would pair them (#114543),// grafting the cached reasoning/tool parts onto the unrelated row.- const sameText =- nextText.length > 0 && (nextText === previousVisibleText || nextText === previousText.trim())+ const sameText = nextText.length > 0 && (nextText === previousVisibleText || nextText === previousText.trim())// Mid-turn, the authoritative text has advanced past the cached copy by one// or more deltas. That is still the same turn, and the cached row holds the@@ -391,9 +390,7 @@ export function reconcileResumeMessages(nextMessages: ChatMessage[], previousMes// inherit its reasoning/tool parts (#76444 review / salvage).const sameTurn =sameText ||- (nextText.length > 0 &&- previousTrimmed.length > 0 &&- isStrictAnswerTextExtension(nextText, previousTrimmed)) ||+ (nextText.length > 0 && previousTrimmed.length > 0 && isStrictAnswerTextExtension(nextText, previousTrimmed)) ||(message.role === 'assistant' &&previous.role === 'assistant' &&hasStructuralParts(previous) &&@@ -853,6 +850,7 @@ export function appendLiveSessionProjection(messages: ChatMessage[], projection:// timeline projection history uses instead of as a user bubble (#112144).// `toChatMessages` yields nothing for `hidden`, so the prompt is omitted.const displayKind = projection.inflight?.display_kind+const typed = displayKind? toChatMessages([{diff --git a/apps/desktop/src/app/session/hooks/use-session-state-cache.test.tsx b/apps/desktop/src/app/session/hooks/use-session-state-cache.test.tsxindex 0f16a7b761c..95326856ff0 100644--- a/apps/desktop/src/app/session/hooks/use-session-state-cache.test.tsx+++ b/apps/desktop/src/app/session/hooks/use-session-state-cache.test.tsx@@ -188,9 +188,7 @@ describe('useSessionStateCache — stored-id rotation provenance', () => {setActiveSessionId('runtime-A')setSelectedStoredSessionId(null)arm()- render(- <Harness activeSessionId="runtime-A" onReady={value => (cache = value)} selectedStoredSessionId={null} />- )+ render(<Harness activeSessionId="runtime-A" onReady={value => (cache = value)} selectedStoredSessionId={null} />)act(() => {cache.updateSessionState('runtime-A', state => state, 'stored-A')diff --git a/apps/desktop/src/app/session/hooks/use-session-state-cache.ts b/apps/desktop/src/app/session/hooks/use-session-state-cache.tsindex d923ef8f62d..c400ddc04b5 100644--- a/apps/desktop/src/app/session/hooks/use-session-state-cache.ts+++ b/apps/desktop/src/app/session/hooks/use-session-state-cache.ts@@ -178,7 +178,11 @@ export function useSessionStateCache({// A rotation event needs a real next id — a null/cleared stored id// is a detach, not a rotation the route-follow effect should chase.- if (storedSessionId && sessionId === $activeSessionId.get() && isSessionInForeground(existing.storedSessionId)) {+ if (+ storedSessionId &&+ sessionId === $activeSessionId.get() &&+ isSessionInForeground(existing.storedSessionId)+ ) {setActiveSessionStoredIdRotation({nextStoredSessionId: storedSessionId,previousStoredSessionId: existing.storedSessionId,diff --git a/apps/desktop/src/app/session/new-session-route.ts b/apps/desktop/src/app/session/new-session-route.tsindex 2390cea6ef3..9a0c77f43f5 100644--- a/apps/desktop/src/app/session/new-session-route.ts+++ b/apps/desktop/src/app/session/new-session-route.ts@@ -11,7 +11,12 @@ import {pinLegacyNewChatProfile} from '@/store/profile'import { $projectScope, ALL_PROJECTS } from '@/store/projects'-import { isPeerInstanceWindow, isProfilePinnedWindow, windowConnectionOverride, windowProfileOverride } from '@/store/windows'+import {+ isPeerInstanceWindow,+ isProfilePinnedWindow,+ windowConnectionOverride,+ windowProfileOverride+} from '@/store/windows'/** Only generic New Session actions consult this preference. Explicit profile,* agent, project and existing-session actions keep their captured owner. */diff --git a/apps/desktop/src/app/settings/billing/index.tsx b/apps/desktop/src/app/settings/billing/index.tsxindex 1018bf2d7e8..e1f57882a1f 100644--- a/apps/desktop/src/app/settings/billing/index.tsx+++ b/apps/desktop/src/app/settings/billing/index.tsx@@ -419,9 +419,11 @@ function BillingHeader({return (<SectionHeading- aside={import.meta.env.DEV && fixtureName && onFixtureChange ? (- <BillingFixtureSelect onValueChange={onFixtureChange} value={fixtureName} />- ) : undefined}+ aside={+ import.meta.env.DEV && fixtureName && onFixtureChange ? (+ <BillingFixtureSelect onValueChange={onFixtureChange} value={fixtureName} />+ ) : undefined+ }icon={BarChart3}pagetitle={t.settings.nav.billing}diff --git a/apps/desktop/src/app/settings/chat-font-setting.test.tsx b/apps/desktop/src/app/settings/chat-font-setting.test.tsxindex a279c9ff1fb..e8c0d3cfd45 100644--- a/apps/desktop/src/app/settings/chat-font-setting.test.tsx+++ b/apps/desktop/src/app/settings/chat-font-setting.test.tsx@@ -127,6 +127,8 @@ describe('resolveChatFontFamily', () => {expect(resolveChatFontFamily('', theme)).toBe(theme)expect(resolveChatFontFamily(' ', theme)).toBe(theme)expect(resolveChatFontFamily('OpenDyslexic', theme)).toBe(`'OpenDyslexic', ${theme}`)- expect(resolveChatFontFamily("'Atkinson Hyperlegible', serif", theme)).toBe(`'Atkinson Hyperlegible', serif, ${theme}`)+ expect(resolveChatFontFamily("'Atkinson Hyperlegible', serif", theme)).toBe(+ `'Atkinson Hyperlegible', serif, ${theme}`+ )})})diff --git a/apps/desktop/src/app/settings/chat-font-setting.tsx b/apps/desktop/src/app/settings/chat-font-setting.tsxindex c401b8ff888..54ea38331f1 100644--- a/apps/desktop/src/app/settings/chat-font-setting.tsx+++ b/apps/desktop/src/app/settings/chat-font-setting.tsx@@ -141,7 +141,10 @@ export function ChatFontSetting() {))}</datalist>{/* Inherits --dt-font-sans, so it IS the live result, not a simulation. */}- <div aria-label={copy.chatFontPreview} className="overflow-hidden px-1 py-2 text-sm text-(--ui-text-secondary)">+ <div+ aria-label={copy.chatFontPreview}+ className="overflow-hidden px-1 py-2 text-sm text-(--ui-text-secondary)"+ ><span className="mr-2 text-[length:var(--conversation-caption-font-size)] text-(--ui-text-tertiary)">{copy.chatFontPreview}</span>diff --git a/apps/desktop/src/app/settings/cloud-team-change.ts b/apps/desktop/src/app/settings/cloud-team-change.tsindex 575150f4d8b..66380c077fa 100644--- a/apps/desktop/src/app/settings/cloud-team-change.ts+++ b/apps/desktop/src/app/settings/cloud-team-change.ts@@ -27,6 +27,7 @@ export async function reconnectMovedCloudAgent(if (!isCurrent()) {return false}+const result = await desktop.cloud.agentSignIn(url)if (!isCurrent() || !result.connected) {diff --git a/apps/desktop/src/app/settings/config-settings.tsx b/apps/desktop/src/app/settings/config-settings.tsxindex 1a9eee2ae1b..a1bfd35407e 100644--- a/apps/desktop/src/app/settings/config-settings.tsx+++ b/apps/desktop/src/app/settings/config-settings.tsx@@ -359,11 +359,7 @@ function ConfigSettingsInner({<SettingsProfileScope className="mb-5" />{activeSectionId === 'model' && (<div className={showModelSettings ? 'mb-6' : undefined}>- <ModelSettings- onMainModelChanged={onMainModelChanged}- scopeProfile={scopeProfile}- subpage={subpage}- />+ <ModelSettings onMainModelChanged={onMainModelChanged} scopeProfile={scopeProfile} subpage={subpage} /></div>)}{children}@@ -421,7 +417,9 @@ function ConfigSettingsInner({const showEmptyState =visibleFields.length === 0 &&- (subpage === undefined ? activeSectionId !== 'chat' : !showModelSettings && !showDesktopSettings && !showAttachments)+ (subpage === undefined+ ? activeSectionId !== 'chat'+ : !showModelSettings && !showDesktopSettings && !showAttachments)return renderPage(<>diff --git a/apps/desktop/src/app/settings/custom-endpoints-settings.test.tsx b/apps/desktop/src/app/settings/custom-endpoints-settings.test.tsxindex aeb2277d4a6..11c86cb5acd 100644--- a/apps/desktop/src/app/settings/custom-endpoints-settings.test.tsx+++ b/apps/desktop/src/app/settings/custom-endpoints-settings.test.tsx@@ -158,7 +158,10 @@ describe('CustomEndpointsSettings', () => {fireEvent.change(screen.getByPlaceholderText('gpt-5.4'), { target: { value: 'studio-model' } })fireEvent.click(screen.getByRole('button', { name: 'Save' }))- expect(saveCustomEndpoint).toHaveBeenCalledWith(expect.objectContaining({ name: 'Studio gateway' }), 'content-studio')+ expect(saveCustomEndpoint).toHaveBeenCalledWith(+ expect.objectContaining({ name: 'Studio gateway' }),+ 'content-studio'+ )})it('hydrates the API mode from a saved endpoint', async () => {@@ -209,7 +212,12 @@ describe('CustomEndpointsSettings', () => {it('Test rewrites the URL field to the base that actually served /models (#65488)', async () => {getCustomEndpoints.mockResolvedValue(emptyResponse)- validateCustomEndpoint.mockResolvedValue({ ok: true, message: '', models: ['model-a'], resolved_base_url: 'http://h.test/v1' })+ validateCustomEndpoint.mockResolvedValue({+ ok: true,+ message: '',+ models: ['model-a'],+ resolved_base_url: 'http://h.test/v1'+ })const { CustomEndpointsSettings } = await import('./custom-endpoints-settings')render(<CustomEndpointsSettings onConfigSaved={vi.fn()} onMainModelChanged={vi.fn()} />)diff --git a/apps/desktop/src/app/settings/gateway-settings.test.tsx b/apps/desktop/src/app/settings/gateway-settings.test.tsxindex bfebf009d77..37a30ba82ef 100644--- a/apps/desktop/src/app/settings/gateway-settings.test.tsx+++ b/apps/desktop/src/app/settings/gateway-settings.test.tsx@@ -66,6 +66,7 @@ describe('GatewaySettings', () => {authMode: 'oauth',org: 'old-team'}+registry.value = { connections: [saved] }getConnectionConfig.mockResolvedValue({...localConnection,@@ -74,20 +75,26 @@ describe('GatewaySettings', () => {remoteUrl: 'https://other.example'})const calls: string[] = []+const oauthLogoutConnectionConfig = vi.fn(async () => {calls.push('logout')})+const agentSignIn = vi.fn(async () => {calls.push('login')+return { connected: true }})+const save = vi.fn(async () => {calls.push('save')})+const discover = vi.fn().mockResolvedValue({needsOrgSelection: true,orgs: [{ id: 'new-team', name: 'New team', role: 'OWNER' }]})+Object.assign(window.hermesDesktop, {oauthLogoutConnectionConfig,connections: { save },@@ -211,7 +218,7 @@ describe('GatewaySettings', () => {render(<GatewaySettings embedded />)// The env override still owns the URL: the editor stays read-only.- expect((await screen.findByDisplayValue(envUrl) as HTMLInputElement).disabled).toBe(true)+ expect(((await screen.findByDisplayValue(envUrl)) as HTMLInputElement).disabled).toBe(true)fireEvent.click(await screen.findByRole('button', { name: 'Sign in with Nous Research' }))@@ -229,7 +236,7 @@ describe('GatewaySettings', () => {render(<GatewaySettings embedded />)- expect((await screen.findByDisplayValue(envUrl) as HTMLInputElement).disabled).toBe(false)+ expect(((await screen.findByDisplayValue(envUrl)) as HTMLInputElement).disabled).toBe(false)expect(await screen.findByRole('button', { name: 'Sign in with Nous Research' })).toBeTruthy()expect(oauthLoginConnectionConfig).not.toHaveBeenCalled()})diff --git a/apps/desktop/src/app/settings/index.tsx b/apps/desktop/src/app/settings/index.tsxindex 7a6a74c2fea..7014f8aa0b6 100644--- a/apps/desktop/src/app/settings/index.tsx+++ b/apps/desktop/src/app/settings/index.tsx@@ -106,22 +106,38 @@ export function SettingsView({ onClose, onConfigSaved, onMainModelChanged }: SetsubpageSearch.set('page', subpage)}- const openSettingsPage = useCallback((view: SettingsViewId, page?: string) => {- const next = new URLSearchParams(search)-- for (const key of ['page', 'field', 'setting', 'key', 'aux', 'session', 'kind', 'label', 'origin', 'pview', 'kview', 'bview']) {- next.delete(key)- }+ const openSettingsPage = useCallback(+ (view: SettingsViewId, page?: string) => {+ const next = new URLSearchParams(search)++ for (const key of [+ 'page',+ 'field',+ 'setting',+ 'key',+ 'aux',+ 'session',+ 'kind',+ 'label',+ 'origin',+ 'pview',+ 'kview',+ 'bview'+ ]) {+ next.delete(key)+ }- next.set('tab', view)- const destination = page ?? settingsSubpages(view)[0]?.id+ next.set('tab', view)+ const destination = page ?? settingsSubpages(view)[0]?.id- if (destination) {- next.set('page', destination)- }+ if (destination) {+ next.set('page', destination)+ }- navigate({ hash, pathname, search: `?${next}` }, { replace: true })- }, [hash, navigate, pathname, search])+ navigate({ hash, pathname, search: `?${next}` }, { replace: true })+ },+ [hash, navigate, pathname, search]+ )const setActiveView = useCallback((view: SettingsViewId) => openSettingsPage(view), [openSettingsPage])@@ -213,179 +229,201 @@ export function SettingsView({ onClose, onConfigSaved, onMainModelChanged }: Set}const navGroups: OverlayNavGroup[] = useMemo(- () => ([- ...SECTIONS.flatMap(s => {- const view = `config:${s.id}` as SettingsViewId-- const entry = {- active: activeView === view,- icon: s.icon,- id: view,- label: t.settings.sections[s.id] ?? s.label,- onSelect: () => setActiveView(view)- }-- // Credential Vault lives beside the Browser section: it feeds the- // browser's model-blind vault fill, so the two are one mental unit.- if (s.id === 'browser') {- return [- entry,- {- active: activeView === 'vault',- icon: ShieldLock,- id: 'vault',- label: t.settings.nav.vault,- onSelect: () => setActiveView('vault')+ () =>+ (+ [+ ...SECTIONS.flatMap(s => {+ const view = `config:${s.id}` as SettingsViewId++ const entry = {+ active: activeView === view,+ icon: s.icon,+ id: view,+ label: t.settings.sections[s.id] ?? s.label,+ onSelect: () => setActiveView(view)}- ]- }- return [entry]- }),- {- active: activeView === 'notifications',- icon: Bell,- id: 'notifications',- label: t.settings.nav.notifications,- onSelect: () => setActiveView('notifications')- },- {- active: activeView === 'billing',- children: [+ // Credential Vault lives beside the Browser section: it feeds the+ // browser's model-blind vault fill, so the two are one mental unit.+ if (s.id === 'browser') {+ return [+ entry,+ {+ active: activeView === 'vault',+ icon: ShieldLock,+ id: 'vault',+ label: t.settings.nav.vault,+ onSelect: () => setActiveView('vault')+ }+ ]+ }++ return [entry]+ }),{- active: activeView === 'billing' && (billingView === 'overview' || !canViewPlans),- icon: BarChart3,- id: 'bview:overview',- label: t.settings.subpages.billingOverview,- onSelect: () => openSubView('billing', 'bview', 'overview', 'overview')+ active: activeView === 'notifications',+ icon: Bell,+ id: 'notifications',+ label: t.settings.nav.notifications,+ onSelect: () => setActiveView('notifications')},- ...(canViewPlans ? [{- active: activeView === 'billing' && billingView === 'plans',- icon: BarChart3,- id: 'bview:plans',- label: t.settings.subpages.billingPlans,- onSelect: () => openSubView('billing', 'bview', 'plans', 'overview')- }] : [])- ],- icon: BarChart3,- id: 'billing',- label: t.settings.nav.billing,- onSelect: () => setActiveView('billing')- },- {- active: activeView === 'providers',- children: [{- active: activeView === 'providers' && providerView === 'accounts',- icon: codiconIcon('account'),- id: 'pview:accounts',- label: t.settings.nav.providerAccounts,- onSelect: () => openProviderView('accounts')+ active: activeView === 'billing',+ children: [+ {+ active: activeView === 'billing' && (billingView === 'overview' || !canViewPlans),+ icon: BarChart3,+ id: 'bview:overview',+ label: t.settings.subpages.billingOverview,+ onSelect: () => openSubView('billing', 'bview', 'overview', 'overview')+ },+ ...(canViewPlans+ ? [+ {+ active: activeView === 'billing' && billingView === 'plans',+ icon: BarChart3,+ id: 'bview:plans',+ label: t.settings.subpages.billingPlans,+ onSelect: () => openSubView('billing', 'bview', 'plans', 'overview')+ }+ ]+ : [])+ ],+ icon: BarChart3,+ id: 'billing',+ label: t.settings.nav.billing,+ onSelect: () => setActiveView('billing')},{- active: activeView === 'providers' && providerView === 'keys',- icon: KeyRound,- id: 'pview:keys',- label: t.settings.nav.providerApiKeys,- onSelect: () => openProviderView('keys')+ active: activeView === 'providers',+ children: [+ {+ active: activeView === 'providers' && providerView === 'accounts',+ icon: codiconIcon('account'),+ id: 'pview:accounts',+ label: t.settings.nav.providerAccounts,+ onSelect: () => openProviderView('accounts')+ },+ {+ active: activeView === 'providers' && providerView === 'keys',+ icon: KeyRound,+ id: 'pview:keys',+ label: t.settings.nav.providerApiKeys,+ onSelect: () => openProviderView('keys')+ },+ {+ active: activeView === 'providers' && providerView === 'custom-endpoints',+ icon: Globe,+ id: 'pview:custom-endpoints',+ label: t.settings.nav.providerCustomEndpoints,+ onSelect: () => openProviderView('custom-endpoints')+ },+ // Local models ships behind the --local launch flag: no flag, no+ // nav entry (the pane itself also refuses to render, so a stale+ // ?pview=local deep link falls back to accounts-shaped emptiness+ // rather than a hidden feature).+ ...($localModelsEnabled.get()+ ? [+ {+ active: activeView === 'providers' && providerView === 'local',+ icon: Cpu,+ id: 'pview:local',+ label: t.settings.nav.providerLocalModels,+ onSelect: () => openProviderView('local')+ }+ ]+ : [])+ ],+ gapBefore: true,+ icon: Zap,+ id: 'providers',+ label: t.settings.nav.providers,+ onSelect: () => setActiveView('providers')},{- active: activeView === 'providers' && providerView === 'custom-endpoints',+ active: activeView === 'gateway',icon: Globe,- id: 'pview:custom-endpoints',- label: t.settings.nav.providerCustomEndpoints,- onSelect: () => openProviderView('custom-endpoints')+ id: 'gateway',+ label: t.settings.nav.gateway,+ onSelect: () => setActiveView('gateway')+ },+ {+ active: activeView === 'keybinds',+ icon: Keyboard,+ id: 'keybinds',+ label: t.settings.nav.keybinds,+ onSelect: () => setActiveView('keybinds')+ },+ {+ active: activeView === 'keys',+ children: [+ {+ active: activeView === 'keys' && keysView === 'tools',+ icon: Wrench,+ id: 'kview:tools',+ label: t.settings.nav.keysTools,+ onSelect: () => openKeysView('tools')+ },+ {+ active: activeView === 'keys' && keysView === 'settings',+ icon: Settings2,+ id: 'kview:settings',+ label: t.settings.nav.keysSettings,+ onSelect: () => openKeysView('settings')+ }+ ],+ icon: KeyRound,+ id: 'keys',+ label: t.settings.nav.apiKeys,+ onSelect: () => setActiveView('keys')},- // Local models ships behind the --local launch flag: no flag, no- // nav entry (the pane itself also refuses to render, so a stale- // ?pview=local deep link falls back to accounts-shaped emptiness- // rather than a hidden feature).- ...($localModelsEnabled.get()- ? [- {- active: activeView === 'providers' && providerView === 'local',- icon: Cpu,- id: 'pview:local',- label: t.settings.nav.providerLocalModels,- onSelect: () => openProviderView('local')- }- ]- : [])- ],- gapBefore: true,- icon: Zap,- id: 'providers',- label: t.settings.nav.providers,- onSelect: () => setActiveView('providers')- },- {- active: activeView === 'gateway',- icon: Globe,- id: 'gateway',- label: t.settings.nav.gateway,- onSelect: () => setActiveView('gateway')- },- {- active: activeView === 'keybinds',- icon: Keyboard,- id: 'keybinds',- label: t.settings.nav.keybinds,- onSelect: () => setActiveView('keybinds')- },- {- active: activeView === 'keys',- children: [{- active: activeView === 'keys' && keysView === 'tools',- icon: Wrench,- id: 'kview:tools',- label: t.settings.nav.keysTools,- onSelect: () => openKeysView('tools')+ active: activeView === 'sessions',+ icon: Archive,+ id: 'sessions',+ label: t.settings.nav.archivedChats,+ onSelect: () => setActiveView('sessions')},{- active: activeView === 'keys' && keysView === 'settings',- icon: Settings2,- id: 'kview:settings',- label: t.settings.nav.keysSettings,- onSelect: () => openKeysView('settings')+ active: activeView === 'about',+ gapBefore: true,+ icon: Info,+ id: 'about',+ label: t.settings.nav.about,+ onSelect: () => setActiveView('about')}- ],- icon: KeyRound,- id: 'keys',- label: t.settings.nav.apiKeys,- onSelect: () => setActiveView('keys')- },- {- active: activeView === 'sessions',- icon: Archive,- id: 'sessions',- label: t.settings.nav.archivedChats,- onSelect: () => setActiveView('sessions')- },- {- active: activeView === 'about',- gapBefore: true,- icon: Info,- id: 'about',- label: t.settings.nav.about,- onSelect: () => setActiveView('about')- }- ] as OverlayNavGroup[]).map(group => {- const view = group.id as SettingsViewId- const children = settingsSubpages(view)-- return children.length ? {- ...group,- children: children.map(page => ({- active: group.active && subpage === page.id,- icon: settingsSubpageIcon(page, group.icon),- id: `${view}:${page.id}`,- label: t.settings.subpages[page.labelKey],- onSelect: () => openSettingsPage(view, page.id)- }))- } : group- }),- [activeView, billingView, canViewPlans, keysView, providerView, subpage, t, setActiveView, openProviderView, openKeysView, openSettingsPage, openSubView]+ ] as OverlayNavGroup[]+ ).map(group => {+ const view = group.id as SettingsViewId+ const children = settingsSubpages(view)++ return children.length+ ? {+ ...group,+ children: children.map(page => ({+ active: group.active && subpage === page.id,+ icon: settingsSubpageIcon(page, group.icon),+ id: `${view}:${page.id}`,+ label: t.settings.subpages[page.labelKey],+ onSelect: () => openSettingsPage(view, page.id)+ }))+ }+ : group+ }),+ [+ activeView,+ billingView,+ canViewPlans,+ keysView,+ providerView,+ subpage,+ t,+ setActiveView,+ openProviderView,+ openKeysView,+ openSettingsPage,+ openSubView+ ])const activeGroup = navGroups.find(group => group.active)@@ -524,7 +562,9 @@ export function SettingsView({ onClose, onConfigSaved, onMainModelChanged }: Set{activeGroup && <SettingsSubpageHeader child={activeChild} group={activeGroup} />}{needsSubpageRedirect ? (<Navigate replace to={{ hash, pathname, search: `?${subpageSearch}` }} />- ) : activeSettingsContent}+ ) : (+ activeSettingsContent+ )}</SettingsBreadcrumbContext.Provider></OverlayMain></OverlaySplitLayout>diff --git a/apps/desktop/src/app/settings/model-settings.tsx b/apps/desktop/src/app/settings/model-settings.tsxindex 6ac73cd9ec8..dbe002938da 100644--- a/apps/desktop/src/app/settings/model-settings.tsx+++ b/apps/desktop/src/app/settings/model-settings.tsx@@ -873,12 +873,7 @@ export function ModelSettings({ onMainModelChanged, scopeProfile, subpage }: Mod<div className="mt-2 flex flex-wrap items-center gap-2 text-xs text-destructive"><span>{error}</span>{skewRestart && (- <Button- disabled={restartingBackend}- onClick={() => void recycleStaleBackend()}- size="sm"- variant="textStrong"- >+ <Button disabled={restartingBackend} onClick={() => void recycleStaleBackend()} size="sm" variant="textStrong">{restartingBackend && <Loader2 className="size-3.5 animate-spin" />}{restartingBackend ? m.restartingBackend : m.restartBackend}</Button>@@ -995,7 +990,9 @@ export function ModelSettings({ onMainModelChanged, scopeProfile, subpage }: Mod{t.shell.modelOptions.fast}<Switchchecked={fastOn}- onCheckedChange={checked => void writeAgentDefault('agent.service_tier', checked ? 'fast' : 'normal')}+ onCheckedChange={checked =>+ void writeAgentDefault('agent.service_tier', checked ? 'fast' : 'normal')+ }size="xs"/></label>@@ -1098,7 +1095,10 @@ export function ModelSettings({ onMainModelChanged, scopeProfile, subpage }: ModonValueChange={value => setAuxDraft(prev => ({ ...prev, model: value }))}value={auxDraft.model}>- <SelectTrigger aria-label={`${copy.label} model`} className={cn('min-w-48', CONTROL_TEXT)}>+ <SelectTrigger+ aria-label={`${copy.label} model`}+ className={cn('min-w-48', CONTROL_TEXT)}+ ><SelectValue placeholder={m.model} /></SelectTrigger><SelectContent>@@ -1158,9 +1158,9 @@ export function ModelSettings({ onMainModelChanged, scopeProfile, subpage }: Mod{' · '}{current.reasoning_effort === 'none'? `${m.reasoning} ${m.reasoningOff}`- : (isReasoningEffort(current.reasoning_effort)- ? t.shell.modelOptions[current.reasoning_effort]- : current.reasoning_effort)}+ : isReasoningEffort(current.reasoning_effort)+ ? t.shell.modelOptions[current.reasoning_effort]+ : current.reasoning_effort}</span>)}</span>diff --git a/apps/desktop/src/app/settings/profile-scope.tsx b/apps/desktop/src/app/settings/profile-scope.tsxindex f5121da1125..e39e83db978 100644--- a/apps/desktop/src/app/settings/profile-scope.tsx+++ b/apps/desktop/src/app/settings/profile-scope.tsx@@ -16,9 +16,7 @@ import type { ProfileInfo } from '@/types/hermes'// (ui_meta['hermes-bots'].title), else the app-wide profileLabel// (display_name → slug). Scoped to this selector on purpose — the profile// rail and Profiles page keep naming profiles by display_name.-export function settingsScopeLabel(- profile: Pick<ProfileInfo, 'bot_title' | 'display_name' | 'name'>-): string {+export function settingsScopeLabel(profile: Pick<ProfileInfo, 'bot_title' | 'display_name' | 'name'>): string {return (profile.bot_title ?? '').trim() || profileLabel(profile)}diff --git a/apps/desktop/src/app/settings/screenshot-settings.test.tsx b/apps/desktop/src/app/settings/screenshot-settings.test.tsxindex e713d79aeb4..fd29a112ac6 100644--- a/apps/desktop/src/app/settings/screenshot-settings.test.tsx+++ b/apps/desktop/src/app/settings/screenshot-settings.test.tsx@@ -19,6 +19,7 @@ const copy = en.settings.screenshotfunction deferred<T>() {let resolve!: (value: T) => void+const promise = new Promise<T>(yes => {resolve = yes})@@ -29,15 +30,18 @@ function deferred<T>() {function installBridge() {let onStatus: (status: ScreenshotStatus) => void = () => {}const unsubscribe = vi.fn()+const api = {getSettings: vi.fn<() => Promise<ScreenshotStatus>>(),setEnabled: vi.fn<(enabled: boolean) => Promise<ScreenshotStatus>>(),openPermissionSettings: vi.fn<(kind: 'input' | 'screen') => Promise<void>>().mockResolvedValue(undefined),onStatus: vi.fn((callback: (status: ScreenshotStatus) => void) => {onStatus = callback+return unsubscribe})}+vi.stubGlobal('hermesDesktop', { screenshot: api })return { api, emit: (status: ScreenshotStatus) => onStatus(status), unsubscribe }@@ -161,6 +165,7 @@ describe('ScreenshotSettings', () => {it('provides every screenshot message in each locale', () => {for (const locale of [en, ja, zh, zhHant, ar, ru]) {expect(Object.keys(locale.settings.screenshot).sort()).toEqual(Object.keys(copy).sort())+for (const text of Object.values(locale.settings.screenshot)) {expect(typeof text).toBe('string')expect(text.trim()).not.toBe('')diff --git a/apps/desktop/src/app/settings/screenshot-settings.tsx b/apps/desktop/src/app/settings/screenshot-settings.tsxindex b30b094724f..64325031b4b 100644--- a/apps/desktop/src/app/settings/screenshot-settings.tsx+++ b/apps/desktop/src/app/settings/screenshot-settings.tsx@@ -63,6 +63,7 @@ export function ScreenshotSettings() {setStatus(next)setError(null)})+void refresh()return () => {@@ -108,6 +109,7 @@ export function ScreenshotSettings() {'screen-permission': s.screenPermission,unavailable: s.unavailable}+const description = busy ? s.checking : error ? s[error] : descriptions[status?.state ?? 'disabled']const showStatus = busy || error || status?.enabled || status?.state !== 'disabled'const canRetry = error || (status?.state !== 'ready' && status?.state !== 'disabled')@@ -150,7 +152,9 @@ export function ScreenshotSettings() {<ErrorIcon size="1rem" />{s.errorTitle}</span>- ) : s.statusTitle+ ) : (+ s.statusTitle+ )}/>)}diff --git a/apps/desktop/src/app/settings/subpage-navigation.tsx b/apps/desktop/src/app/settings/subpage-navigation.tsxindex 56b89b2f211..53c17ef5776 100644--- a/apps/desktop/src/app/settings/subpage-navigation.tsx+++ b/apps/desktop/src/app/settings/subpage-navigation.tsx@@ -18,12 +18,18 @@ export function SettingsSubpageHeader({ group, child }: { group: OverlayNavGroup<ChevronRight aria-hidden className="size-3 shrink-0" />{child ? (<>- <Button onClick={group.onSelect} size="inline" variant="text">{group.label}</Button>+ <Button onClick={group.onSelect} size="inline" variant="text">+ {group.label}+ </Button><ChevronRight aria-hidden className="size-3 shrink-0" />- <span aria-current="page" className="truncate text-foreground">{child.label}</span>+ <span aria-current="page" className="truncate text-foreground">+ {child.label}+ </span></>) : (- <span aria-current="page" className="truncate text-foreground">{group.label}</span>+ <span aria-current="page" className="truncate text-foreground">+ {group.label}+ </span>)}</nav>)diff --git a/apps/desktop/src/app/settings/subpages.test.ts b/apps/desktop/src/app/settings/subpages.test.tsindex 97e9a1fbff9..11374407130 100644--- a/apps/desktop/src/app/settings/subpages.test.ts+++ b/apps/desktop/src/app/settings/subpages.test.ts@@ -11,7 +11,7 @@ import type { SettingsView } from './types'const views: SettingsView[] = [...SECTIONS.map(section => `config:${section.id}` as SettingsView),- ...Object.keys(OTHER_SUBPAGES) as SettingsView[]+ ...(Object.keys(OTHER_SUBPAGES) as SettingsView[])]describe('settings subpage routing', () => {diff --git a/apps/desktop/src/app/settings/subpages.ts b/apps/desktop/src/app/settings/subpages.tsindex d433d2a5abe..2f7f470be08 100644--- a/apps/desktop/src/app/settings/subpages.ts+++ b/apps/desktop/src/app/settings/subpages.ts@@ -40,23 +40,50 @@ export interface SettingsSubpage {}const SUBPAGE_ICONS: Record<string, IconComponent> = {- appearanceTheme: Palette, appearanceTypography: CircleLetterA,- appearanceWindowLayout: Monitor, appearanceChatDisplay: MessageCircle,- appearancePet: PawPrint, appearanceGeneral: Settings2,- modelMain: Box, modelAuxiliary: Cpu, modelMoa: Users, modelFallbacks: Box,- chatBehavior: MessageCircle, chatAttachments: FileImage,- workspaceProjects: FolderOpen, workspaceShell: Terminal, workspaceFiles: FileText,- safetyApprovals: ShieldLock, safetyPrivacy: Lock, safetyCheckpoints: Archive,- browserProfile: Globe, browserNetwork: Network,- memoryPersistent: Brain, memoryContext: FileText,- voiceConversation: Mic, voiceTranscription: FileText, voiceSpeech: Volume2,- advancedRuntime: Cpu, advancedTools: Wrench, advancedTerminal: Terminal,- advancedOutput: FileText, advancedDelegation: Users, advancedDesktop: Monitor,- gatewayConnection: Monitor, gatewayDevices: Network, gatewayManagedUpdates: Download,- keyboardShortcuts: Keyboard, screenCapture: FileImage,- notificationAlerts: Bell, notificationSounds: Volume2,- archivedSessions: Archive, defaultDirectory: FolderOpen,- vaultCredentials: KeyRound, vaultSources: Lock, appUpdates: Download, uninstall: Trash2+ appearanceTheme: Palette,+ appearanceTypography: CircleLetterA,+ appearanceWindowLayout: Monitor,+ appearanceChatDisplay: MessageCircle,+ appearancePet: PawPrint,+ appearanceGeneral: Settings2,+ modelMain: Box,+ modelAuxiliary: Cpu,+ modelMoa: Users,+ modelFallbacks: Box,+ chatBehavior: MessageCircle,+ chatAttachments: FileImage,+ workspaceProjects: FolderOpen,+ workspaceShell: Terminal,+ workspaceFiles: FileText,+ safetyApprovals: ShieldLock,+ safetyPrivacy: Lock,+ safetyCheckpoints: Archive,+ browserProfile: Globe,+ browserNetwork: Network,+ memoryPersistent: Brain,+ memoryContext: FileText,+ voiceConversation: Mic,+ voiceTranscription: FileText,+ voiceSpeech: Volume2,+ advancedRuntime: Cpu,+ advancedTools: Wrench,+ advancedTerminal: Terminal,+ advancedOutput: FileText,+ advancedDelegation: Users,+ advancedDesktop: Monitor,+ gatewayConnection: Monitor,+ gatewayDevices: Network,+ gatewayManagedUpdates: Download,+ keyboardShortcuts: Keyboard,+ screenCapture: FileImage,+ notificationAlerts: Bell,+ notificationSounds: Volume2,+ archivedSessions: Archive,+ defaultDirectory: FolderOpen,+ vaultCredentials: KeyRound,+ vaultSources: Lock,+ appUpdates: Download,+ uninstall: Trash2}export function settingsSubpageIcon(page: SettingsSubpage, fallback: IconComponent): IconComponent {diff --git a/apps/desktop/src/app/settings/toolset-config-panel.test.tsx b/apps/desktop/src/app/settings/toolset-config-panel.test.tsxindex 8b5d5df91c1..b50f0befdca 100644--- a/apps/desktop/src/app/settings/toolset-config-panel.test.tsx+++ b/apps/desktop/src/app/settings/toolset-config-panel.test.tsx@@ -205,7 +205,10 @@ describe('ToolsetConfigPanel', () => {const voiceInput = screen.getByDisplayValue('alloy')fireEvent.change(voiceInput, { target: { value: 'marin' } })await waitFor(() => expect(saveHermesConfigRecord).toHaveBeenCalled(), { timeout: 3000 })- const saved = saveHermesConfigRecord.mock.calls.at(-1)?.[0] as Record<string, Record<string, Record<string, string>>>+ const saved = saveHermesConfigRecord.mock.calls.at(-1)?.[0] as Record<+ string,+ Record<string, Record<string, string>>+ >expect(saved.tts.openai.voice).toBe('marin')// Unscoped panel (no Capabilities override) → profile rides as undefined,// preserving the active-profile default. A scoped panel forwards its scope.@@ -238,10 +241,12 @@ describe('ToolsetConfigPanel', () => {fireEvent.change(await screen.findByDisplayValue('alloy'), { target: { value: 'marin' } })await waitFor(() => expect(saveHermesConfigRecord).toHaveBeenCalled(), { timeout: 3000 })+const [saved, forwarded] = saveHermesConfigRecord.mock.calls.at(-1) as [Record<string, Record<string, Record<string, string>>>,unknown]+expect(saved.tts.openai.voice).toBe('marin')expect(forwarded).toEqual(scope)})diff --git a/apps/desktop/src/app/settings/use-settings-search.ts b/apps/desktop/src/app/settings/use-settings-search.tsindex c538d71b6ea..0ef1c8b2c7f 100644--- a/apps/desktop/src/app/settings/use-settings-search.ts+++ b/apps/desktop/src/app/settings/use-settings-search.ts@@ -265,14 +265,16 @@ export function useSettingsSearchCatalog(enabled: boolean) {label: pageLabels[view],icon: Settings2}))- ].flatMap(parent => settingsSubpages(parent.view).map(page => ({- context: parent.label,- icon: parent.icon,- id: `settings-page:${parent.view}:${page.id}`,- keywords: [parent.label, page.id],- label: t.settings.subpages[page.labelKey],- target: { view: parent.view, subpage: page.id }- })))+ ].flatMap(parent =>+ settingsSubpages(parent.view).map(page => ({+ context: parent.label,+ icon: parent.icon,+ id: `settings-page:${parent.view}:${page.id}`,+ keywords: [parent.label, page.id],+ label: t.settings.subpages[page.labelKey],+ target: { view: parent.view, subpage: page.id }+ }))+ )return {subpageEntries,diff --git a/apps/desktop/src/app/settings/vault-settings.owner.test.tsx b/apps/desktop/src/app/settings/vault-settings.owner.test.tsxindex 0a33cb52e31..98a7407d47e 100644--- a/apps/desktop/src/app/settings/vault-settings.owner.test.tsx+++ b/apps/desktop/src/app/settings/vault-settings.owner.test.tsx@@ -15,7 +15,12 @@ let respond: (profile: string, method: string) => Promise<unknown> = async () =>vi.mock('@/store/gateway', async importActual => ({...(await importActual<Record<string, unknown>>()),- requestGatewayForAgent: (_connectionId: null | string, profile: string, method: string, params?: Record<string, unknown>) => {+ requestGatewayForAgent: (+ _connectionId: null | string,+ profile: string,+ method: string,+ params?: Record<string, unknown>+ ) => {calls.push({ method, params: params ?? {}, profile })return respond(profile, method)diff --git a/apps/desktop/src/app/shell/hooks/use-statusbar-items.tsx b/apps/desktop/src/app/shell/hooks/use-statusbar-items.tsxindex 3cc77a99b21..47ee6d7b292 100644--- a/apps/desktop/src/app/shell/hooks/use-statusbar-items.tsx+++ b/apps/desktop/src/app/shell/hooks/use-statusbar-items.tsx@@ -229,7 +229,7 @@ export function useStatusbarItems({// file manager on this computer can show its workspace at all.const focusedRowConnectionId = useStoreSelector($sessions, sessions =>focusedStoredSessionId- ? (sessions.find(s => sessionMatchesStoredId(s, focusedStoredSessionId))?.connection_id?.trim() || '')+ ? sessions.find(s => sessionMatchesStoredId(s, focusedStoredSessionId))?.connection_id?.trim() || '': '')diff --git a/apps/desktop/src/app/starmap/timeline.tsx b/apps/desktop/src/app/starmap/timeline.tsxindex dd70b32d3d2..61405b92c88 100644--- a/apps/desktop/src/app/starmap/timeline.tsx+++ b/apps/desktop/src/app/starmap/timeline.tsx@@ -182,7 +182,6 @@ export const Timeline = memo(function Timeline({return (<div className="pointer-events-auto flex w-[28rem] max-w-full items-center gap-3 [-webkit-app-region:no-drag]">-<buttonaria-label={playing ? 'Pause' : 'Play timeline'}className="flex size-5 shrink-0 items-center justify-center text-foreground/75 transition-colors hover:text-foreground"diff --git a/apps/desktop/src/app/types.ts b/apps/desktop/src/app/types.tsindex 7ed0a6079d2..e42030a4033 100644--- a/apps/desktop/src/app/types.ts+++ b/apps/desktop/src/app/types.ts@@ -123,13 +123,7 @@ export interface HandoffFailResponse {}export type SidebarNavId =- | 'artifacts'- | 'capabilities'- | 'command-center'- | 'cron'- | 'messaging'- | 'new-session'- | 'settings'+ 'artifacts' | 'capabilities' | 'command-center' | 'cron' | 'messaging' | 'new-session' | 'settings'export interface SidebarNavItem {/** Built-in view id, or a contributed row's namespaced contribution id. */diff --git a/apps/desktop/src/app/updates-overlay.tsx b/apps/desktop/src/app/updates-overlay.tsxindex 1fa5372b012..7148e276147 100644--- a/apps/desktop/src/app/updates-overlay.tsx+++ b/apps/desktop/src/app/updates-overlay.tsx@@ -49,7 +49,15 @@ const INSTALLER_URL = 'https://hermes-agent.nousresearch.com/'function splitDetails(text: string): [string, string | null] {const marker = text.search(/\s*Details:\s*/)- return marker < 0 ? [text, null] : [text.slice(0, marker).trim(), text.slice(marker).replace(/^\s*Details:\s*/, '').trim()]+ return marker < 0+ ? [text, null]+ : [+ text.slice(0, marker).trim(),+ text+ .slice(marker)+ .replace(/^\s*Details:\s*/, '')+ .trim()+ ]}function totalItems(groups: readonly CommitGroup[]) {diff --git a/apps/desktop/src/components/assistant-ui/clarify-tool.test.tsx b/apps/desktop/src/components/assistant-ui/clarify-tool.test.tsxindex d6ae4174ae6..8f5adfc7ae8 100644--- a/apps/desktop/src/components/assistant-ui/clarify-tool.test.tsx+++ b/apps/desktop/src/components/assistant-ui/clarify-tool.test.tsx@@ -752,8 +752,16 @@ describe('ClarifyTool batch card', () => {await waitFor(() => expect(request).toHaveBeenCalledTimes(2))// Locks ride the live qids, never the preview's synthetic ones.- expect(request).toHaveBeenNthCalledWith(1, 'clarify.lock', { answer: 'red', question_id: 'q0', request_id: 'request-batch' })- expect(request).toHaveBeenNthCalledWith(2, 'clarify.lock', { answer: 'packet', question_id: 'q1', request_id: 'request-batch' })+ expect(request).toHaveBeenNthCalledWith(1, 'clarify.lock', {+ answer: 'red',+ question_id: 'q0',+ request_id: 'request-batch'+ })+ expect(request).toHaveBeenNthCalledWith(2, 'clarify.lock', {+ answer: 'packet',+ question_id: 'q1',+ request_id: 'request-batch'+ })})it('stages locally and keeps the single confirm disabled until all answered', async () => {diff --git a/apps/desktop/src/components/assistant-ui/clarify-tool.tsx b/apps/desktop/src/components/assistant-ui/clarify-tool.tsxindex 7a529773829..d3b62ddcf57 100644--- a/apps/desktop/src/components/assistant-ui/clarify-tool.tsx+++ b/apps/desktop/src/components/assistant-ui/clarify-tool.tsx@@ -1064,7 +1064,11 @@ function ClarifyToolBatchPending({const confirmAll = useCallback(async () => {if (!request || !gateway) {- notifyError(new Error(request ? copy.gatewayDisconnected : copy.notReady), copy.sendFailed, request ? { action: reconnectAction() } : {})+ notifyError(+ new Error(request ? copy.gatewayDisconnected : copy.notReady),+ copy.sendFailed,+ request ? { action: reconnectAction() } : {}+ )return}diff --git a/apps/desktop/src/components/assistant-ui/connector-tool.test.tsx b/apps/desktop/src/components/assistant-ui/connector-tool.test.tsxindex bf48c576df5..2ef1f67ec71 100644--- a/apps/desktop/src/components/assistant-ui/connector-tool.test.tsx+++ b/apps/desktop/src/components/assistant-ui/connector-tool.test.tsx@@ -139,7 +139,11 @@ describe('ConnectorTool operation card', () => {]})- expect(screen.getAllByRole('button').map(button => button.textContent)).toEqual(['Connect', 'Try again', 'Continue'])+ expect(screen.getAllByRole('button').map(button => button.textContent)).toEqual([+ 'Connect',+ 'Try again',+ 'Continue'+ ])expect(screen.queryByRole('button', { name: 'Not now' })).toBeNull()})@@ -226,7 +230,9 @@ describe('ConnectorTool operation card', () => {it('never binds to a tool row from a different call, even for the same apps', () => {// A second connect for gmail opens a new operation on a new tool_call_id. The old row must stay// dead: it is matched by id only, never by connector names.- expect(connectionRequestOwnsPart(props(), { ...REQUEST, opId: 'operation-2', toolCallId: 'connector-call-2' })).toBe(false)+ expect(+ connectionRequestOwnsPart(props(), { ...REQUEST, opId: 'operation-2', toolCallId: 'connector-call-2' })+ ).toBe(false)expect(connectionRequestOwnsPart(props(), REQUEST)).toBe(true)})diff --git a/apps/desktop/src/components/assistant-ui/connector-tool.tsx b/apps/desktop/src/components/assistant-ui/connector-tool.tsxindex 5cd582a9bfd..48b1c1a5b61 100644--- a/apps/desktop/src/components/assistant-ui/connector-tool.tsx+++ b/apps/desktop/src/components/assistant-ui/connector-tool.tsx@@ -330,7 +330,11 @@ export function ConnectorOffer({ owner, request }: ConnectorOfferProps) {return (<ConnectorSummary- connector={{ iconUrl: connectorIconUrl(target.name), name: target.name, title: connectorTitle(target.name) }}+ connector={{+ iconUrl: connectorIconUrl(target.name),+ name: target.name,+ title: connectorTitle(target.name)+ }}key={target.name}meta={meta}tone={tone}@@ -370,7 +374,11 @@ export function ConnectorOffer({ owner, request }: ConnectorOfferProps) {return (<ConnectorRowaction={action}- connector={{ iconUrl: connectorIconUrl(target.name), name: target.name, title: connectorTitle(target.name) }}+ connector={{+ iconUrl: connectorIconUrl(target.name),+ name: target.name,+ title: connectorTitle(target.name)+ }}cue={phase.mark === 'waiting' ? copy.waiting : undefined}key={target.name}mark={phase.mark}diff --git a/apps/desktop/src/components/assistant-ui/mcp-setup-tool.test.tsx b/apps/desktop/src/components/assistant-ui/mcp-setup-tool.test.tsxindex e419db7fb83..a55021f296f 100644--- a/apps/desktop/src/components/assistant-ui/mcp-setup-tool.test.tsx+++ b/apps/desktop/src/components/assistant-ui/mcp-setup-tool.test.tsx@@ -109,11 +109,13 @@ afterEach(() => {describe('the MCP setup card', () => {it('opens required details from the row action and sends the approved environment', async () => {const rpc = vi.fn().mockResolvedValue({ status: 'ok', settled: false })+const target = {...LINEAR,instructions: 'Create a Linear API key.',requiredEnv: [{ default: 'workspace', name: 'LINEAR_TEAM', prompt: 'Team', required: true, secret: false }]}+// SAFETY: the card calls only `request`; no other gateway client surface is exercised here.// respondToConnectionRequest reads $gateway, which only applyActive publishes; set it directly.$gateway.set({ request: rpc } as never)diff --git a/apps/desktop/src/components/assistant-ui/mcp-setup-tool.tsx b/apps/desktop/src/components/assistant-ui/mcp-setup-tool.tsxindex 5e762f07b65..d6091bc4bc2 100644--- a/apps/desktop/src/components/assistant-ui/mcp-setup-tool.tsx+++ b/apps/desktop/src/components/assistant-ui/mcp-setup-tool.tsx@@ -382,7 +382,11 @@ function McpSetupRow({ action, onReissue, reissueBlocked, reissuing, request, ta} satisfies Record<Exclude<McpVerb, 'none'>, ConnectorRowAction>const displayServer = prettyName(server)- const rowCue = target.discoveryError ? t.connectors.authorizedToolsUnavailable : verb === 'open' ? t.connectors.waiting : undefined+ const rowCue = target.discoveryError+ ? t.connectors.authorizedToolsUnavailable+ : verb === 'open'+ ? t.connectors.waiting+ : undefinedreturn (<>diff --git a/apps/desktop/src/components/assistant-ui/thread/agent-delivery.tsx b/apps/desktop/src/components/assistant-ui/thread/agent-delivery.tsxindex 44592dab994..29967009525 100644--- a/apps/desktop/src/components/assistant-ui/thread/agent-delivery.tsx+++ b/apps/desktop/src/components/assistant-ui/thread/agent-delivery.tsx@@ -23,7 +23,15 @@ export function deliveryTargetFromCommand(command: string): null | string {/** `@Dr. Foo`, `scribe@laptop`, `peer/scribe` → `dr. foo` / `scribe`: the* routing alias a `message_agent` target and a "Message from" signature share. */function agentKey(value: unknown): string {- return typeof value === 'string' ? value.trim().replace(/^@/, '').replace(/@[^@]*$/, '').split('/').pop()!.toLowerCase() : ''+ return typeof value === 'string'+ ? value+ .trim()+ .replace(/^@/, '')+ .replace(/@[^@]*$/, '')+ .split('/')+ .pop()!+ .toLowerCase()+ : ''}/**@@ -37,7 +45,10 @@ function agentKey(value: unknown): string {* Matching the sender by handle OR display name (either may sign the inbound* row) errs towards "expanded": a missed fold shows content, a wrong fold hides it.*/-export function dispatchedTo(earlier: readonly { content?: unknown; role?: string }[], sender: (string | undefined)[]): boolean {+export function dispatchedTo(+ earlier: readonly { content?: unknown; role?: string }[],+ sender: (string | undefined)[]+): boolean {const keys = new Set(sender.map(agentKey).filter(Boolean))if (!keys.size) {diff --git a/apps/desktop/src/components/assistant-ui/thread/inter-agent-collapse.test.tsx b/apps/desktop/src/components/assistant-ui/thread/inter-agent-collapse.test.tsxindex fb3e2005d99..a5cbd183350 100644--- a/apps/desktop/src/components/assistant-ui/thread/inter-agent-collapse.test.tsx+++ b/apps/desktop/src/components/assistant-ui/thread/inter-agent-collapse.test.tsx@@ -125,9 +125,7 @@ describe('inter-agent collapse gate', () => {it('still collapses the reply to an unsolicited delivery (dispatch went to another teammate)', async () => {render(- <Harness- messages={[dispatch('a0', 'scribe'), user('u2', DELIVERY), assistant('a1', 'build is green', false)]}- />+ <Harness messages={[dispatch('a0', 'scribe'), user('u2', DELIVERY), assistant('a1', 'build is green', false)]} />)expect(await screen.findByText(/Replied to/)).toBeTruthy()diff --git a/apps/desktop/src/components/assistant-ui/thread/list-session-scroll.test.tsx b/apps/desktop/src/components/assistant-ui/thread/list-session-scroll.test.tsxindex c125c225594..d5374e5f6f5 100644--- a/apps/desktop/src/components/assistant-ui/thread/list-session-scroll.test.tsx+++ b/apps/desktop/src/components/assistant-ui/thread/list-session-scroll.test.tsx@@ -94,7 +94,14 @@ interface ScrollHarnessProps {window?: TranscriptWindowValue}-function ScrollHarness({ isRunning = false, messages, sessionKey, scrollProfile, sessionId, window }: ScrollHarnessProps) {+function ScrollHarness({+ isRunning = false,+ messages,+ sessionKey,+ scrollProfile,+ sessionId,+ window+}: ScrollHarnessProps) {const runtime = useExternalStoreRuntime<ThreadMessage>({isRunning,messages,@@ -219,6 +226,7 @@ describe('list session-scroll restore', () => {if (offset) {saveThreadScrollPosition('a', { fromBottom: offset, kind: 'offset' })}+const messages = sessionMessages('a')const pane = (visible: boolean) => (@@ -271,6 +279,7 @@ describe('list session-scroll restore', () => {if (offset) {saveThreadScrollPosition('a', { fromBottom: offset, kind: 'offset' })}+const messages = sessionMessages('a')let runtimeId: string | null = null@@ -392,11 +401,13 @@ describe('list session-scroll restore', () => {if (profileFirst) {setActiveProfile('pr-bot')}+rerender(pane(false))if (!profileFirst) {setActiveProfile('pr-bot')}+const otherKey = threadScrollStorageKey()await settleScroll(10)// The selected global profile can still belong to the other Bot when the@@ -553,6 +564,7 @@ describe('list session-scroll restore', () => {for (let step = 0; step < 5; step++) {await settleScroll(20)}+act(() => window.dispatchEvent(new Event('beforeunload')))expect(getThreadScrollPosition('lost')).toEqual({ kind: 'offset', fromBottom: SCROLL_H - CLIENT_H })expect(viewportEl(container).scrollTop).toBe(0)diff --git a/apps/desktop/src/components/assistant-ui/thread/list.tsx b/apps/desktop/src/components/assistant-ui/thread/list.tsxindex 5056d5f84d9..b42633bf13a 100644--- a/apps/desktop/src/components/assistant-ui/thread/list.tsx+++ b/apps/desktop/src/components/assistant-ui/thread/list.tsx@@ -184,9 +184,7 @@ export function hasTranscriptTextSelection(scrollElement?: Element | null): boolconst { anchorNode, focusNode } = selection- return Boolean(- (anchorNode && scrollElement.contains(anchorNode)) || (focusNode && scrollElement.contains(focusNode))- )+ return Boolean((anchorNode && scrollElement.contains(anchorNode)) || (focusNode && scrollElement.contains(focusNode)))}export const resolveThreadScrollTarget: GetTargetScrollTop = (targetScrollTop, { scrollElement }) => {@@ -739,7 +737,9 @@ const ThreadMessageListInner: FC<ThreadMessageListProps> = ({useEffect(() =>onScrollToBottomRequest(() => {- if (isHistorical) {returnToLatest?.()}+ if (isHistorical) {+ returnToLatest?.()+ }if (jumpRestoreRef.current) {jumpRestoreRef.current()@@ -1173,7 +1173,16 @@ const ThreadMessageListInner: FC<ThreadMessageListProps> = ({cancelAnimationFrame(rafId)record()}- }, [contentRef, hasGroups, paneVisible, scrollRef, scrollStorageKey, scrollToBottomUnlessSelecting, sessionKey, stopScroll])+ }, [+ contentRef,+ hasGroups,+ paneVisible,+ scrollRef,+ scrollStorageKey,+ scrollToBottomUnlessSelecting,+ sessionKey,+ stopScroll+ ])// A thread can mount with a run already active, without a runStart event.useEffect(() => {diff --git a/apps/desktop/src/components/assistant-ui/thread/process-notification.test.tsx b/apps/desktop/src/components/assistant-ui/thread/process-notification.test.tsxindex d15a6c94e82..b5b5d6d766a 100644--- a/apps/desktop/src/components/assistant-ui/thread/process-notification.test.tsx+++ b/apps/desktop/src/components/assistant-ui/thread/process-notification.test.tsx@@ -19,11 +19,14 @@ it('renders legacy and current process completions as tool disclosures without ifor (const display of [{},- { display_kind: 'process_complete', display_metadata: { display_text: 'Background Process Finished: node verify.mjs' } }+ {+ display_kind: 'process_complete',+ display_metadata: { display_text: 'Background Process Finished: node verify.mjs' }+ }]) {- const messages = toChatMessages([- { role: 'user', content, timestamp: 1, ...display } as SessionMessage- ]).map(toRuntimeMessage)+ const messages = toChatMessages([{ role: 'user', content, timestamp: 1, ...display } as SessionMessage]).map(+ toRuntimeMessage+ )const { container, getByRole, unmount } = render(<ThreadRuntime messages={messages}>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 81ddcf8ca96..4509ed3a6cc 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@@ -37,22 +37,31 @@ it('keeps background continuations in one response with one action bar and the oconst messages = toChatMessages(stored).map(toRuntimeMessage)const { container, rerender, unmount } = render(- <ThreadRuntime messages={messages.slice(0, 2)}><Thread onBranchInNewChat={branch} /></ThreadRuntime>+ <ThreadRuntime messages={messages.slice(0, 2)}>+ <Thread onBranchInNewChat={branch} />+ </ThreadRuntime>)const original = container.querySelector('[data-role="assistant"]')- rerender(<ThreadRuntime messages={messages}><Thread onBranchInNewChat={branch} /></ThreadRuntime>)+ rerender(+ <ThreadRuntime messages={messages}>+ <Thread onBranchInNewChat={branch} />+ </ThreadRuntime>+ )await waitFor(() => expect(container.textContent).toContain('The deployment is verified.'))expect(container.querySelectorAll('[data-slot="aui_turn-pair"]')).toHaveLength(1)expect(container.querySelectorAll('[data-slot="aui_response-group"]')).toHaveLength(1)expect(container.querySelectorAll('[data-slot="aui_msg-actions"]')).toHaveLength(1)expect(container.querySelector('[data-role="assistant"]')).toBe(original)- expect([...container.querySelectorAll('[data-role="assistant"]')].map(e => e.getAttribute('data-message-id')))- .toEqual([messages[1]!.id, messages[3]!.id])+ expect(+ [...container.querySelectorAll('[data-role="assistant"]')].map(e => e.getAttribute('data-message-id'))+ ).toEqual([messages[1]!.id, messages[3]!.id])const actions = container.querySelector('[data-slot="aui_msg-actions"]') as HTMLElementfireEvent.click(within(actions).getByRole('button', { name: 'Copy' }))- await waitFor(() => expect(clipboard.writeText).toHaveBeenLastCalledWith('Checking the deployment.\n\nThe deployment is verified.'))+ await waitFor(() =>+ expect(clipboard.writeText).toHaveBeenLastCalledWith('Checking the deployment.\n\nThe deployment is verified.')+ )fireEvent.click(within(actions).getByRole('button', { name: /branch/i }))expect(branch).toHaveBeenLastCalledWith(messages[3]!.id)@@ -61,12 +70,20 @@ it('keeps background continuations in one response with one action bar and the o{ ...messages[3]!, role: 'assistant', id: 'next', content: [], status: { type: 'running' } } as ThreadMessage]- rerender(<ThreadRuntime messages={pending}><Thread onBranchInNewChat={branch} /></ThreadRuntime>)+ rerender(+ <ThreadRuntime messages={pending}>+ <Thread onBranchInNewChat={branch} />+ </ThreadRuntime>+ )await waitFor(() => expect(container.querySelectorAll('[data-role="assistant"]')).toHaveLength(3))expect(container.querySelectorAll('[data-slot="aui_msg-actions"]')).toHaveLength(1)unmount()- const reloaded = render(<ThreadRuntime messages={messages}><Thread /></ThreadRuntime>)+ const reloaded = render(+ <ThreadRuntime messages={messages}>+ <Thread />+ </ThreadRuntime>+ )expect(reloaded.container.querySelectorAll('[data-slot="aui_msg-actions"]')).toHaveLength(1)reloaded.unmount()}@@ -82,7 +99,11 @@ it('ends the response at a real user prompt or unrelated system event', () => {{ role: 'assistant', content: 'Second answer', timestamp: 6 }]).map(toRuntimeMessage)- const { container } = render(<ThreadRuntime messages={messages}><Thread /></ThreadRuntime>)+ const { container } = render(+ <ThreadRuntime messages={messages}>+ <Thread />+ </ThreadRuntime>+ )expect(container.querySelectorAll('[data-slot="aui_turn-pair"]')).toHaveLength(2)expect(container.querySelectorAll('[data-slot="aui_msg-actions"]')).toHaveLength(3)})diff --git a/apps/desktop/src/components/assistant-ui/thread/response-group.tsx b/apps/desktop/src/components/assistant-ui/thread/response-group.tsxindex 7616568aa09..c058ced6d76 100644--- a/apps/desktop/src/components/assistant-ui/thread/response-group.tsx+++ b/apps/desktop/src/components/assistant-ui/thread/response-group.tsx@@ -51,7 +51,14 @@ export function ResponseMessages({ components, indices }: ResponseMessagesProps)// A history replacement can notify this row before its parent updates indices.return message- ? [{ index, id: message.id, role: responseMessageRole(message), hasText: contentHasVisibleText(message.content) }]+ ? [+ {+ index,+ id: message.id,+ role: responseMessageRole(message),+ hasText: contentHasVisibleText(message.content)+ }+ ]: []}))diff --git a/apps/desktop/src/components/assistant-ui/thread/sealed-tool-parts.test.tsx b/apps/desktop/src/components/assistant-ui/thread/sealed-tool-parts.test.tsxindex 98b8242c47c..ae46b0ee2f0 100644--- a/apps/desktop/src/components/assistant-ui/thread/sealed-tool-parts.test.tsx+++ b/apps/desktop/src/components/assistant-ui/thread/sealed-tool-parts.test.tsx@@ -16,7 +16,11 @@ stubThreadViewportSize()const createdAt = new Date('2026-09-11T12:00:00Z')const sealedAt = createdAt.getTime() / 1000 + 5-function sealedMessage(toolName: string, args: Record<string, unknown>, extra: Record<string, unknown> = {}): ThreadMessage {+function sealedMessage(+ toolName: string,+ args: Record<string, unknown>,+ extra: Record<string, unknown> = {}+): ThreadMessage {return {id: `assistant-sealed-${toolName}`,role: 'assistant',diff --git a/apps/desktop/src/components/assistant-ui/thread/streaming.test.tsx b/apps/desktop/src/components/assistant-ui/thread/streaming.test.tsxindex 65a94549a78..e608a9393ea 100644--- a/apps/desktop/src/components/assistant-ui/thread/streaming.test.tsx+++ b/apps/desktop/src/components/assistant-ui/thread/streaming.test.tsx@@ -735,7 +735,9 @@ describe('assistant-ui streaming renderer', () => {body.scrollTop = height - body.clientHeight - 0.5fireEvent.scroll(body)rerender(- <RunningMessageHarness message={assistantReasoningMessage('First thought. More reasoning. Latest thought.', true)} />+ <RunningMessageHarness+ message={assistantReasoningMessage('First thought. More reasoning. Latest thought.', true)}+ />)height = 1200deliverGrowth()diff --git a/apps/desktop/src/components/assistant-ui/thread/system-message.tsx b/apps/desktop/src/components/assistant-ui/thread/system-message.tsxindex 941a1e411d1..37ab0c0986f 100644--- a/apps/desktop/src/components/assistant-ui/thread/system-message.tsx+++ b/apps/desktop/src/components/assistant-ui/thread/system-message.tsx@@ -71,7 +71,11 @@ export const SystemMessage: FC = () => {if (processResult || (typeof asyncResult === 'string' && asyncResult)) {return (- <MessagePrimitive.Root className="w-full min-w-0 self-start" data-role="system" data-slot="aui_system-message-root">+ <MessagePrimitive.Root+ className="w-full min-w-0 self-start"+ data-role="system"+ data-slot="aui_system-message-root"+ ><BackgroundResultprocess={processResult}report={typeof asyncResult === 'string' ? asyncResult : ''}diff --git a/apps/desktop/src/components/assistant-ui/thread/timeline-idle.test.tsx b/apps/desktop/src/components/assistant-ui/thread/timeline-idle.test.tsxindex 71bcacdf657..6b2e8b72a44 100644--- a/apps/desktop/src/components/assistant-ui/thread/timeline-idle.test.tsx+++ b/apps/desktop/src/components/assistant-ui/thread/timeline-idle.test.tsx@@ -160,6 +160,7 @@ describe('ThreadTimeline availability', () => {<ThreadTimeline /></>)+const rails = () => container.querySelectorAll('[data-slot="thread-timeline"]')expect(rails()).toHaveLength(0)diff --git a/apps/desktop/src/components/assistant-ui/thread/timeline-index.test.ts b/apps/desktop/src/components/assistant-ui/thread/timeline-index.test.tsindex ca7706feb33..239117d8fb2 100644--- a/apps/desktop/src/components/assistant-ui/thread/timeline-index.test.ts+++ b/apps/desktop/src/components/assistant-ui/thread/timeline-index.test.ts@@ -69,11 +69,17 @@ describe('timeline metadata index', () => {it('names the mark before an anchor, paging a partial index only as far as one lookup may', async () => {api.mockResolvedValueOnce({- entries: [{ row_id: 10, preview: 'Prompt 10' }, { row_id: 20, preview: 'Prompt 20' }],+ entries: [+ { row_id: 10, preview: 'Prompt 10' },+ { row_id: 20, preview: 'Prompt 20' }+ ],pagination: { next_cursor: 20, has_more: true }}).mockResolvedValueOnce({- entries: [{ row_id: 30, preview: 'Prompt 30' }, { row_id: 40, preview: 'Prompt 40' }],+ entries: [+ { row_id: 30, preview: 'Prompt 30' },+ { row_id: 40, preview: 'Prompt 40' }+ ],pagination: { next_cursor: null, has_more: false }}).mockResolvedValue(page(1, true))diff --git a/apps/desktop/src/components/assistant-ui/thread/timeline-index.ts b/apps/desktop/src/components/assistant-ui/thread/timeline-index.tsindex 036626de45f..d5750eb2b10 100644--- a/apps/desktop/src/components/assistant-ui/thread/timeline-index.ts+++ b/apps/desktop/src/components/assistant-ui/thread/timeline-index.ts@@ -37,7 +37,11 @@ export function fetchTimelineIndex(id: string, scope: ProfileScope, beyondRowId?const cached = cache.get(key)const previous = cached?.complete && cached.expires <= Date.now() ? undefined : cached- if (cached?.complete && cached.expires > Date.now() && (beyondRowId === undefined || marksReach(cached.entries, beyondRowId))) {+ if (+ cached?.complete &&+ cached.expires > Date.now() &&+ (beyondRowId === undefined || marksReach(cached.entries, beyondRowId))+ ) {return Promise.resolve(cached)}diff --git a/apps/desktop/src/components/assistant-ui/thread/timeline-rail.test.tsx b/apps/desktop/src/components/assistant-ui/thread/timeline-rail.test.tsxindex 83588d0ddb5..60be2224a54 100644--- a/apps/desktop/src/components/assistant-ui/thread/timeline-rail.test.tsx+++ b/apps/desktop/src/components/assistant-ui/thread/timeline-rail.test.tsx@@ -52,9 +52,12 @@ describe('TimelineRail', () => {})it('resets every bar on pointer leave even while an item keeps focus', async () => {- const { container, rerender } = render(<TimelineRail activeIndex={0} entries={entries} loadingId={null} onJump={vi.fn()} />)+ const { container, rerender } = render(+ <TimelineRail activeIndex={0} entries={entries} loadingId={null} onJump={vi.fn()} />+ )const rail = container.querySelector<HTMLElement>('[data-slot="thread-timeline-ticks"]')!- const widths = () => Array.from(rail.querySelectorAll<HTMLElement>('[data-slot="timeline-bar"]'), bar => bar.style.width)+ const widths = () =>+ Array.from(rail.querySelectorAll<HTMLElement>('[data-slot="timeline-bar"]'), bar => bar.style.width)expect(new Set(widths())).toEqual(new Set(['0.5rem']))fireEvent(rail, new MouseEvent('pointermove', { bubbles: true, clientY: 70 }))diff --git a/apps/desktop/src/components/assistant-ui/thread/timeline-rail.tsx b/apps/desktop/src/components/assistant-ui/thread/timeline-rail.tsxindex e0cdcb9dca8..1b40099dbc1 100644--- a/apps/desktop/src/components/assistant-ui/thread/timeline-rail.tsx+++ b/apps/desktop/src/components/assistant-ui/thread/timeline-rail.tsx@@ -46,7 +46,9 @@ export function TimelineRail({ activeIndex, entries, loadingId, onJump }: Timeliconst measure = () => {const rem = parseFloat(getComputedStyle(element.ownerDocument.documentElement).fontSize)- if (Number.isFinite(rem) && rem > 0) {setPitch(rem * 0.4375)}+ if (Number.isFinite(rem) && rem > 0) {+ setPitch(rem * 0.4375)+ }}const observer = new ResizeObserver(measure)@@ -62,9 +64,10 @@ export function TimelineRail({ activeIndex, entries, loadingId, onJump }: Timeliframe.current = 0for (const bar of root.current?.querySelectorAll<HTMLElement>('[data-slot="timeline-bar"]') ?? []) {- const width = pointerY.current === null- ? '0.5rem'- : `${Number(timelineBarWidth(Number(bar.dataset.index), activeIndex, hover.current).toFixed(4))}rem`+ const width =+ pointerY.current === null+ ? '0.5rem'+ : `${Number(timelineBarWidth(Number(bar.dataset.index), activeIndex, hover.current).toFixed(4))}rem`if (bar.style.width !== width) {bar.style.width = widthdiff --git a/apps/desktop/src/components/assistant-ui/thread/timeline.tsx b/apps/desktop/src/components/assistant-ui/thread/timeline.tsxindex 178dac06e35..e5fbc6871f9 100644--- a/apps/desktop/src/components/assistant-ui/thread/timeline.tsx+++ b/apps/desktop/src/components/assistant-ui/thread/timeline.tsx@@ -93,8 +93,19 @@ const ActiveThreadTimeline: FC = () => {const railEntries = useMemo(() => {const indexed = indexedEntries ?? []- const selected = history.isHistorical ? deriveTimelineEntries((history.currentMessages ?? []).map(message => ({ id: message.id, rowId: message.rowId, role: message.role, text: messageContentText(message.parts) }))) : []- const loaded = new Map([...entries, ...selected].filter(entry => entry.rowId !== undefined).map(entry => [entry.rowId, entry]))+ const selected = history.isHistorical+ ? deriveTimelineEntries(+ (history.currentMessages ?? []).map(message => ({+ id: message.id,+ rowId: message.rowId,+ role: message.role,+ text: messageContentText(message.parts)+ }))+ )+ : []+ const loaded = new Map(+ [...entries, ...selected].filter(entry => entry.rowId !== undefined).map(entry => [entry.rowId, entry])+ )const seen = new Set(indexed.map(entry => entry.rowId))const merged = [@@ -105,7 +116,15 @@ const ActiveThreadTimeline: FC = () => {return (history.olderAvailable || indexedEntries) && !indexComplete? [{ id: EARLIER_TIMELINE_ID, preview: t.assistant.thread.showEarlier }, ...merged]: merged- }, [entries, indexedEntries, indexComplete, history.olderAvailable, history.currentMessages, history.isHistorical, t.assistant.thread.showEarlier])+ }, [+ entries,+ indexedEntries,+ indexComplete,+ history.olderAvailable,+ history.currentMessages,+ history.isHistorical,+ t.assistant.thread.showEarlier+ ])const root = useRef<HTMLDivElement>(null)const jumpFrame = useRef(0)@@ -161,7 +180,12 @@ const ActiveThreadTimeline: FC = () => {const timeout = window.setTimeout(() => finish(false), 15000)controller.signal.addEventListener('abort', () => finish(false), { once: true })- const detail: TimelineRevealRequest = { id, rowId: railEntries.find(entry => entry.id === id)?.rowId, signal: controller.signal, complete: finish }+ const detail: TimelineRevealRequest = {+ id,+ rowId: railEntries.find(entry => entry.id === id)?.rowId,+ signal: controller.signal,+ complete: finish+ }viewport.dispatchEvent(new CustomEvent(TIMELINE_REVEAL_EVENT, { detail }))})diff --git a/apps/desktop/src/components/assistant-ui/thread/transcript-window.tsx b/apps/desktop/src/components/assistant-ui/thread/transcript-window.tsxindex aba495adadb..f20329abb16 100644--- a/apps/desktop/src/components/assistant-ui/thread/transcript-window.tsx+++ b/apps/desktop/src/components/assistant-ui/thread/transcript-window.tsx@@ -31,7 +31,10 @@ const DEFAULT_TRANSCRIPT_WINDOW: Required<TranscriptWindowValue> = {const TranscriptWindowContext = createContext<Required<TranscriptWindowValue>>(DEFAULT_TRANSCRIPT_WINDOW)-export function TranscriptWindowProvider({ children, value }: {+export function TranscriptWindowProvider({+ children,+ value+}: {children: ReactNodevalue: Pick<TranscriptWindowValue, 'olderAvailable' | 'expandWindow'> & Partial<TranscriptWindowValue>}) {diff --git a/apps/desktop/src/components/assistant-ui/thread/use-messages-below.test.tsx b/apps/desktop/src/components/assistant-ui/thread/use-messages-below.test.tsxindex 73167b37d37..a71ea136efe 100644--- a/apps/desktop/src/components/assistant-ui/thread/use-messages-below.test.tsx+++ b/apps/desktop/src/components/assistant-ui/thread/use-messages-below.test.tsx@@ -167,10 +167,13 @@ describe('messages below the viewport', () => {vi.stubGlobal('cancelAnimationFrame', () => {frame = undefined})- vi.stubGlobal('ResizeObserver', class {- observe() {}- disconnect() {}- })+ vi.stubGlobal(+ 'ResizeObserver',+ class {+ observe() {}+ disconnect() {}+ }+ )const flush = () =>act(() => {diff --git a/apps/desktop/src/components/assistant-ui/thread/use-timeline-history.ts b/apps/desktop/src/components/assistant-ui/thread/use-timeline-history.tsindex fd51939c6a9..e02b795e6f0 100644--- a/apps/desktop/src/components/assistant-ui/thread/use-timeline-history.ts+++ b/apps/desktop/src/components/assistant-ui/thread/use-timeline-history.ts@@ -33,25 +33,28 @@ export function useTimelineHistory() {const [index, setIndex] = useState<{ key: string; value: TimelineIndex } | null>(null)const [failed, setFailed] = useState<string | null>(null)- const loadMore = useCallback(async (beyondRowId?: number) => {- if (!storedId) {- return- }+ const loadMore = useCallback(+ async (beyondRowId?: number) => {+ if (!storedId) {+ return+ }- try {- const value = await fetchTimelineIndex(storedId, scope, beyondRowId)+ try {+ const value = await fetchTimelineIndex(storedId, scope, beyondRowId)- if (view.$storedId.get() === storedId && view.$runtimeId.get() === runtimeId) {- setIndex({ key, value })- setFailed(null)+ if (view.$storedId.get() === storedId && view.$runtimeId.get() === runtimeId) {+ setIndex({ key, value })+ setFailed(null)+ }+ } catch {+ // Old backends keep the loaded rail and their explicit Show earlier path.+ setFailed(key)}- } catch {- // Old backends keep the loaded rail and their explicit Show earlier path.- setFailed(key)- }- // Owner is represented by key; do not restart on object identity alone.- // eslint-disable-next-line react-hooks/exhaustive-deps- }, [key, storedId, runtimeId, view])+ // Owner is represented by key; do not restart on object identity alone.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ },+ [key, storedId, runtimeId, view]+ )useEffect(() => {if (!storedId) {@@ -86,7 +89,8 @@ export function useTimelineHistory() {// chronological), page it forward once per new prompt — no timer; an// incomplete index still pages on demand.const last = value?.entries.at(-1)?.rowId- const stale = value?.complete === true && newestPromptRowId !== undefined && (last === undefined || last < newestPromptRowId)+ const stale =+ value?.complete === true && newestPromptRowId !== undefined && (last === undefined || last < newestPromptRowId)useEffect(() => {if (!stale || failed === key) {diff --git a/apps/desktop/src/components/assistant-ui/thread/use-timeline-reveal.test.tsx b/apps/desktop/src/components/assistant-ui/thread/use-timeline-reveal.test.tsxindex efe51f49005..33eebfc870b 100644--- a/apps/desktop/src/components/assistant-ui/thread/use-timeline-reveal.test.tsx+++ b/apps/desktop/src/components/assistant-ui/thread/use-timeline-reveal.test.tsx@@ -10,19 +10,30 @@ vi.mock('@/app/chat/session-view', () => ({ useSessionView: () => view }))const view = { $messages: { get: () => [] } }beforeEach(() => vi.stubGlobal('CSS', { escape: (id: string) => id }))-afterEach(() => { cleanup(); vi.unstubAllGlobals() })+afterEach(() => {+ cleanup()+ vi.unstubAllGlobals()+})function Harness({ fetchPage, signal }: { fetchPage: () => Promise<string | null>; signal: AbortSignal }) {const [id, setId] = useState('latest')return (- <TranscriptWindowProvider value={{ olderAvailable: true, expandWindow: vi.fn(), revealRow: async () => {- const next = await fetchPage()+ <TranscriptWindowProvider+ value={{+ olderAvailable: true,+ expandWindow: vi.fn(),+ revealRow: async () => {+ const next = await fetchPage()- if (next && !signal.aborted) {setId(next)}+ if (next && !signal.aborted) {+ setId(next)+ }- return next- } }}>+ return next+ }+ }}+ ><List id={id} /></TranscriptWindowProvider>)@@ -30,9 +41,23 @@ function Harness({ fetchPage, signal }: { fetchPage: () => Promise<string | nullfunction List({ id }: { id: string }) {const viewport = useRef<HTMLDivElement>(null)- useTimelineReveal({ viewport, groups: [{ id, weight: 1 }], hiddenCount: 0, renderBudget: 600, olderAvailable: true, revealBudget: vi.fn(), expandWindow: vi.fn(), prepare: vi.fn(), sessionKey: 'session' })+ useTimelineReveal({+ viewport,+ groups: [{ id, weight: 1 }],+ hiddenCount: 0,+ renderBudget: 600,+ olderAvailable: true,+ revealBudget: vi.fn(),+ expandWindow: vi.fn(),+ prepare: vi.fn(),+ sessionKey: 'session'+ })- return <div data-testid="viewport" ref={viewport}><div data-message-id={id}>{id}</div></div>+ return (+ <div data-testid="viewport" ref={viewport}>+ <div data-message-id={id}>{id}</div>+ </div>+ )}describe('timeline direct reveal', () => {@@ -42,7 +67,11 @@ describe('timeline direct reveal', () => {const complete = vi.fn()const ui = render(<Harness fetchPage={fetchPage} signal={controller.signal} />)await act(async () => {- ui.getByTestId('viewport').dispatchEvent(new CustomEvent(TIMELINE_REVEAL_EVENT, { detail: { id: 'history:42', rowId: 42, signal: controller.signal, complete } }))+ ui.getByTestId('viewport').dispatchEvent(+ new CustomEvent(TIMELINE_REVEAL_EVENT, {+ detail: { id: 'history:42', rowId: 42, signal: controller.signal, complete }+ })+ )})expect(fetchPage).toHaveBeenCalledOnce()expect(complete).toHaveBeenCalledWith('old-target')@@ -53,7 +82,9 @@ describe('timeline direct reveal', () => {const complete = vi.fn()const ui = render(<Harness fetchPage={async () => null} signal={controller.signal} />)await act(async () => {- ui.getByTestId('viewport').dispatchEvent(new CustomEvent(TIMELINE_REVEAL_EVENT, { detail: { id: 'history:42', signal: controller.signal, complete } }))+ ui.getByTestId('viewport').dispatchEvent(+ new CustomEvent(TIMELINE_REVEAL_EVENT, { detail: { id: 'history:42', signal: controller.signal, complete } })+ )})expect(complete).toHaveBeenCalledWith(false)expect(ui.getByText('latest')).toBeTruthy()diff --git a/apps/desktop/src/components/assistant-ui/thread/use-timeline-reveal.ts b/apps/desktop/src/components/assistant-ui/thread/use-timeline-reveal.tsindex dc4a1f6e9bd..1838540e030 100644--- a/apps/desktop/src/components/assistant-ui/thread/use-timeline-reveal.ts+++ b/apps/desktop/src/components/assistant-ui/thread/use-timeline-reveal.ts@@ -27,7 +27,9 @@ export function useTimelineReveal(options: TimelineRevealOptions) {useEffect(() => {const viewport = options.viewport.current- if (!viewport) {return}+ if (!viewport) {+ return+ }let current: AbortController | null = nullconst onReveal = (event: Event) => {@@ -38,7 +40,9 @@ export function useTimelineReveal(options: TimelineRevealOptions) {const abort = () => controller.abort()request.signal.addEventListener('abort', abort, { once: true })- if (request.signal.aborted) {controller.abort()}+ if (request.signal.aborted) {+ controller.abort()+ }const timeout = window.setTimeout(abort, 15000)const valid = () => !controller.signal.abortedconst find = (id: string) => viewport.querySelector<HTMLElement>(`[data-message-id="${CSS.escape(id)}"]`)@@ -47,26 +51,45 @@ export function useTimelineReveal(options: TimelineRevealOptions) {latest.current.prepare()let id = request.idconst rowId = request.rowId ?? (id.startsWith('history:') ? Number(id.slice(8)) : undefined)- const loaded = rowId === undefined ? undefined : [...(latest.current.history.currentMessages ?? []), ...view.$messages.get()].find(message => message.rowId === rowId)+ const loaded =+ rowId === undefined+ ? undefined+ : [...(latest.current.history.currentMessages ?? []), ...view.$messages.get()].find(+ message => message.rowId === rowId+ )id = loaded?.id ?? id- if (find(id)) {return id}+ if (find(id)) {+ return id+ }- if (rowId !== undefined && !latest.current.groups.some(group => group.id === id) && latest.current.history.revealRow) {+ if (+ rowId !== undefined &&+ !latest.current.groups.some(group => group.id === id) &&+ latest.current.history.revealRow+ ) {const target = await latest.current.history.revealRow(rowId, controller.signal)- if (!target || !valid()) {return false}+ if (!target || !valid()) {+ return false+ }id = target} else if (id === EARLIER_TIMELINE_ID) {const state = latest.current- if (!state.olderAvailable && !state.hiddenCount) {return false}+ if (!state.olderAvailable && !state.hiddenCount) {+ return false+ }state.revealBudget(state.renderBudget + 600)- if (!state.hiddenCount) {await state.expandWindow()}+ if (!state.hiddenCount) {+ await state.expandWindow()+ }}- if (!valid()) {return false}+ if (!valid()) {+ return false+ }// React commits and late row mounts wake this observer; no polling loop.return await new Promise<string | false>(resolve => {@@ -81,17 +104,25 @@ export function useTimelineReveal(options: TimelineRevealOptions) {const cancelled = () => finish(false)const check = () => {- if (!valid()) {return finish(false)}+ if (!valid()) {+ return finish(false)+ }const state = latest.current- const index = id === EARLIER_TIMELINE_ID ? Math.max(0, state.hiddenCount - 1) : state.groups.findIndex(group => group.id === id)+ const index =+ id === EARLIER_TIMELINE_ID+ ? Math.max(0, state.hiddenCount - 1)+ : state.groups.findIndex(group => group.id === id)if (index >= 0) {const budget = state.groups.slice(index).reduce((sum, group) => sum + group.weight, 0) + 1- if (budget > state.renderBudget) {state.revealBudget(budget)}+ if (budget > state.renderBudget) {+ state.revealBudget(budget)+ }}- const node = id === EARLIER_TIMELINE_ID ? viewport.querySelector<HTMLElement>('[data-message-id]') : find(id)+ const node =+ id === EARLIER_TIMELINE_ID ? viewport.querySelector<HTMLElement>('[data-message-id]') : find(id)if (node && (id !== EARLIER_TIMELINE_ID || node.dataset.messageId !== first)) {latest.current.prepare()@@ -100,14 +131,24 @@ export function useTimelineReveal(options: TimelineRevealOptions) {}const observer = new MutationObserver(check)- observer.observe(viewport, { subtree: true, childList: true, attributes: true, attributeFilter: ['data-message-id'] })+ observer.observe(viewport, {+ subtree: true,+ childList: true,+ attributes: true,+ attributeFilter: ['data-message-id']+ })controller.signal.addEventListener('abort', cancelled, { once: true })check()})- })().then(result => request.complete(result), () => request.complete(false)).finally(() => {- clearTimeout(timeout)- request.signal.removeEventListener('abort', abort)- })+ })()+ .then(+ result => request.complete(result),+ () => request.complete(false)+ )+ .finally(() => {+ clearTimeout(timeout)+ request.signal.removeEventListener('abort', abort)+ })}viewport.addEventListener(TIMELINE_REVEAL_EVENT, onReveal)diff --git a/apps/desktop/src/components/assistant-ui/thread/user-message-edit-undo-cut-drag.test.tsx b/apps/desktop/src/components/assistant-ui/thread/user-message-edit-undo-cut-drag.test.tsxindex b37677818db..12c66c04d16 100644--- a/apps/desktop/src/components/assistant-ui/thread/user-message-edit-undo-cut-drag.test.tsx+++ b/apps/desktop/src/components/assistant-ui/thread/user-message-edit-undo-cut-drag.test.tsx@@ -6,7 +6,12 @@// insertFromDrop input types at all — so handleBeforeInput cannot bank the// pre-edit snapshot for them. Undo then skips the cut entirely or steps a// paste back only to the post-cut state, the two gaps reported in #115462.-import { type AppendMessage, AssistantRuntimeProvider, ExportedMessageRepository, type ThreadMessage } from '@assistant-ui/react'+import {+ type AppendMessage,+ AssistantRuntimeProvider,+ ExportedMessageRepository,+ type ThreadMessage+} from '@assistant-ui/react'import { act, cleanup, fireEvent, render, screen } from '@testing-library/react'import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest'diff --git a/apps/desktop/src/components/assistant-ui/thread/user-message.tsx b/apps/desktop/src/components/assistant-ui/thread/user-message.tsxindex 7f970fc2161..d35526475e1 100644--- a/apps/desktop/src/components/assistant-ui/thread/user-message.tsx+++ b/apps/desktop/src/components/assistant-ui/thread/user-message.tsx@@ -2,7 +2,11 @@ import { ActionBarPrimitive, BranchPickerPrimitive, MessagePrimitive, useAuiStatimport { type FC, type ReactNode, useCallback, useEffect, useRef, useState } from 'react'import { DirectiveContent } from '@/components/assistant-ui/directive-text'-import { messageAttachmentRefs, messageContentText, PROCESS_NOTIFICATION_RE } from '@/components/assistant-ui/thread/content'+import {+ messageAttachmentRefs,+ messageContentText,+ PROCESS_NOTIFICATION_RE+} from '@/components/assistant-ui/thread/content'import { ReactionBadge, ReactionPicker } from '@/components/assistant-ui/thread/message-reactions'import { BackgroundResult } from '@/components/assistant-ui/thread/system-message'import { MessageTimelineTimestamp } from '@/components/assistant-ui/thread/timeline-timestamp'diff --git a/apps/desktop/src/components/assistant-ui/tool/approval.tsx b/apps/desktop/src/components/assistant-ui/tool/approval.tsxindex 0ae493b35c8..e09492edc2c 100644--- a/apps/desktop/src/components/assistant-ui/tool/approval.tsx+++ b/apps/desktop/src/components/assistant-ui/tool/approval.tsx@@ -147,7 +147,9 @@ function ApprovalActivity({ floating, visible }: { floating: boolean; visible: b}open={false}>- <span className={cn(SCAFFOLD_LABEL_CLASS, 'truncate')}>{summary || t.assistant.approval.jumpToApproval}</span>+ <span className={cn(SCAFFOLD_LABEL_CLASS, 'truncate')}>+ {summary || t.assistant.approval.jumpToApproval}+ </span></ScaffoldRow></div></motion.div>diff --git a/apps/desktop/src/components/assistant-ui/tool/fallback-model.test.ts b/apps/desktop/src/components/assistant-ui/tool/fallback-model.test.tsindex 5c5d24648ef..64e8c3a0df6 100644--- a/apps/desktop/src/components/assistant-ui/tool/fallback-model.test.ts+++ b/apps/desktop/src/components/assistant-ui/tool/fallback-model.test.ts@@ -155,10 +155,7 @@ describe('buildToolView calls sealed without a result', () => {})it('shows a call the user interrupted as a neutral notice', () => {- const view = buildToolView(- part({ completedAt: 5, interrupted: true, result: undefined, toolName: 'terminal' }),- ''- )+ const view = buildToolView(part({ completedAt: 5, interrupted: true, result: undefined, toolName: 'terminal' }), '')expect(view.status).toBe('notice')expect(view.title).toBe('Interrupted')diff --git a/apps/desktop/src/components/assistant-ui/tool/fallback-vision-image.test.tsx b/apps/desktop/src/components/assistant-ui/tool/fallback-vision-image.test.tsxindex 63b3981265e..cf0806d96d2 100644--- a/apps/desktop/src/components/assistant-ui/tool/fallback-vision-image.test.tsx+++ b/apps/desktop/src/components/assistant-ui/tool/fallback-vision-image.test.tsx@@ -92,7 +92,10 @@ describe('vision_analyze activity image', () => {await waitFor(() => expect(img.getAttribute('src')).toBe(DATA_URL))expect(api).toHaveBeenCalledWith(- expect.objectContaining({ path: `/api/fs/read-data-url?path=${encodeURIComponent(IMAGE_PATH)}`, profile: 'wsl-work' })+ expect.objectContaining({+ path: `/api/fs/read-data-url?path=${encodeURIComponent(IMAGE_PATH)}`,+ profile: 'wsl-work'+ }))expect(readFileDataUrl).not.toHaveBeenCalled()})diff --git a/apps/desktop/src/components/assistant-ui/tool/fallback.tsx b/apps/desktop/src/components/assistant-ui/tool/fallback.tsxindex 1cde4a24d4c..d591a97bd76 100644--- a/apps/desktop/src/components/assistant-ui/tool/fallback.tsx+++ b/apps/desktop/src/components/assistant-ui/tool/fallback.tsx@@ -977,10 +977,12 @@ const ToolRun: FC<PropsWithChildren<{ endIndex: number; startIndex: number }>> =startIndex}) => {const messageRunning = useAuiState(selectMessageRunning)+const { completedAt, count, entryIds, key, live, startedAt, summary, approvalActivity } = useToolRun(startIndex,endIndex)+const sessionId = useStore(useSessionView().$runtimeId)const approval = useStore(useMemo(() => sessionApprovalRequest(sessionId), [sessionId]))const currentTurn = useAuiState(state => isCurrentTurnMessage(state.thread.messages, state.message.id))diff --git a/apps/desktop/src/components/assistant-ui/tool/hide-code-diffs.test.tsx b/apps/desktop/src/components/assistant-ui/tool/hide-code-diffs.test.tsxindex 3ab108fb9ae..e628603c00c 100644--- a/apps/desktop/src/components/assistant-ui/tool/hide-code-diffs.test.tsx+++ b/apps/desktop/src/components/assistant-ui/tool/hide-code-diffs.test.tsx@@ -50,6 +50,7 @@ it('keeps edit counts without code in either display mode and restores disclosur<Thread /></ThreadRuntime>)+await waitFor(() => expect(container.querySelector('[data-tool-row][data-file-edit]')).not.toBeNull())const row = container.querySelector('[data-tool-row]')!// An explicitly open historical row must not override the preference.@@ -71,6 +72,7 @@ it('keeps edit counts without code in either display mode and restores disclosurexpect($hideCodeDiffs.get()).toBe(true)expect(localStorage.getItem('hermes.desktop.toolView.hideCodeDiffs')).toBe('true')}+act(() => setHideCodeDiffs(false))await waitFor(() => expect(row.hasAttribute('data-tool-open')).toBe(true))cleanup()@@ -80,11 +82,13 @@ it('keeps edit counts without code in either display mode and restores disclosurit('still discloses failed edits when code diffs are hidden', async () => {setHideCodeDiffs(true)setToolViewMode('technical')+const { container } = render(<ThreadRuntime messages={[editMessage('patch', true)]}><Thread /></ThreadRuntime>)+const toggle = container.querySelector('[data-tool-row] button[aria-expanded]')!expect(toggle).not.toBeNull()fireEvent.click(toggle)diff --git a/apps/desktop/src/components/assistant-ui/tool/tool-group.test.tsx b/apps/desktop/src/components/assistant-ui/tool/tool-group.test.tsxindex 9604e95543b..f3da8ca066a 100644--- a/apps/desktop/src/components/assistant-ui/tool/tool-group.test.tsx+++ b/apps/desktop/src/components/assistant-ui/tool/tool-group.test.tsx@@ -601,6 +601,7 @@ describe('flat tool list approval surfacing', () => {const { container, rerender } = render(<GroupHarness message={{ ...message, content: [{ type: 'text', text: 'Waiting for approval.' }] }} />)+const run = await screen.findByRole('button', { name: /Run/ })const host = run.closest('[data-approval-stack]')expect(host).not.toBeNull()diff --git a/apps/desktop/src/components/boot-failure-cause.test.ts b/apps/desktop/src/components/boot-failure-cause.test.tsindex 89f30e96655..e9bd7c4b238 100644--- a/apps/desktop/src/components/boot-failure-cause.test.ts+++ b/apps/desktop/src/components/boot-failure-cause.test.ts@@ -28,7 +28,8 @@ describe('local boot failure classification', () => {})it('keeps the raw output out of the headline and behind details', () => {- const raw = 'Hermes backend exited before it became ready (1).\nRecent backend output:\nTraceback (most recent call last):'+ const raw =+ 'Hermes backend exited before it became ready (1).\nRecent backend output:\nTraceback (most recent call last):'const copy = localBootFailureCopy(raw, CAUSES)expect(copy.headline).toBe(CAUSES.exitedEarly)diff --git a/apps/desktop/src/components/boot-failure-cause.ts b/apps/desktop/src/components/boot-failure-cause.tsindex a8d36fc6568..92f1234358c 100644--- a/apps/desktop/src/components/boot-failure-cause.ts+++ b/apps/desktop/src/components/boot-failure-cause.ts@@ -19,7 +19,10 @@ const CAUSE_PATTERNS: readonly [LocalBootCause, RegExp][] = [['diskFull', /no space left on device|database or disk is full|\bENOSPC\b|disk full/i],['permission', /permission denied|\bEACCES\b|\bEPERM\b|read-only file system|\bEROFS\b|operation not permitted/i],['portInUse', /address already in use|\bEADDRINUSE\b|port .* (?:is )?(?:already )?in use/i],- ['installMissing', /installation is missing|is missing or incomplete|venv missing|no module named|modulenotfounderror/i],+ [+ 'installMissing',+ /installation is missing|is missing or incomplete|venv missing|no module named|modulenotfounderror/i+ ],['timedOut', /timed out|timeout/i],['exitedEarly', /exited before|exited \(|process exited|exited with|traceback \(most recent call last\)/i]]diff --git a/apps/desktop/src/components/chat/composer-dock.ts b/apps/desktop/src/components/chat/composer-dock.tsindex 2c1e6c8bb82..86d246d12a8 100644--- a/apps/desktop/src/components/chat/composer-dock.ts+++ b/apps/desktop/src/components/chat/composer-dock.ts@@ -13,7 +13,10 @@ const composerFillTransition = 'transition-[background-color] duration-150 ease-* off this hot path so typing does not re-blur the transcript each frame. */export const composerInputSurface = cn(composerFill, composerFillTransition)// The `-z-10` paint layer behind the editable surface; hydrated and fallback composers share it.-export const composerInputBacking = cn('pointer-events-none absolute inset-0 -z-10 rounded-[inherit]', composerInputSurface)+export const composerInputBacking = cn(+ 'pointer-events-none absolute inset-0 -z-10 rounded-[inherit]',+ composerInputSurface+)/** Backdrop treatment for non-input composer chrome. Harmless when the fill* goes opaque (drawer open) — nothing shows through to blur. */diff --git a/apps/desktop/src/components/chat/status-row.test.tsx b/apps/desktop/src/components/chat/status-row.test.tsxindex 3cc7b408c8e..d8b31894be1 100644--- a/apps/desktop/src/components/chat/status-row.test.tsx+++ b/apps/desktop/src/components/chat/status-row.test.tsx@@ -9,11 +9,14 @@ import { I18nProvider } from '@/i18n'import { StatusRow } from './status-row'-vi.stubGlobal('ResizeObserver', class {- observe() {}- unobserve() {}- disconnect() {}-})+vi.stubGlobal(+ 'ResizeObserver',+ class {+ observe() {}+ unobserve() {}+ disconnect() {}+ }+)afterEach(cleanup)@@ -28,7 +31,16 @@ it('keeps dismiss and nested controls independent from row activation', () => {dismiss={{ label: 'Dismiss task', onDismiss: dismiss }}leading={<Codicon name="comment" />}onActivate={activate}- trailing={<button onClick={event => { event.stopPropagation(); action() }}>Edit task</button>}+ trailing={+ <button+ onClick={event => {+ event.stopPropagation()+ action()+ }}+ >+ Edit task+ </button>+ }><span>Task title</span></StatusRow>diff --git a/apps/desktop/src/components/desktop-install-overlay.tsx b/apps/desktop/src/components/desktop-install-overlay.tsxindex a8e6c0c9dc0..2b4c27a1cfb 100644--- a/apps/desktop/src/components/desktop-install-overlay.tsx+++ b/apps/desktop/src/components/desktop-install-overlay.tsx@@ -171,7 +171,10 @@ export function splitFailureDetails(text: string | null): [string, string | null}const lead = value.slice(0, marker).trim()- const detail = value.slice(marker).replace(/^\s*Details:\s*/, '').trim()+ const detail = value+ .slice(marker)+ .replace(/^\s*Details:\s*/, '')+ .trim()return [lead || value, detail || null]}diff --git a/apps/desktop/src/components/first-run-remote-form.tsx b/apps/desktop/src/components/first-run-remote-form.tsxindex 0df6cf9c125..86b38b9de26 100644--- a/apps/desktop/src/components/first-run-remote-form.tsx+++ b/apps/desktop/src/components/first-run-remote-form.tsx@@ -264,7 +264,9 @@ export function FirstRunRemoteForm({ onBack }: FirstRunRemoteFormProps) {{probe?.error ? (<details className="mt-1 text-xs text-muted-foreground"><summary className="cursor-pointer select-none">{copy.probeErrorDetails}</summary>- <pre className="mt-1 whitespace-pre-wrap wrap-break-word font-mono text-[0.6875rem]">{probe.error}</pre>+ <pre className="mt-1 whitespace-pre-wrap wrap-break-word font-mono text-[0.6875rem]">+ {probe.error}+ </pre></details>) : null}</div>diff --git a/apps/desktop/src/components/free-tier/sign-in-dialog.tsx b/apps/desktop/src/components/free-tier/sign-in-dialog.tsxindex 1e0d97a574a..252f60b5c31 100644--- a/apps/desktop/src/components/free-tier/sign-in-dialog.tsx+++ b/apps/desktop/src/components/free-tier/sign-in-dialog.tsx@@ -226,7 +226,12 @@ function failureHeading(kind: FreeTierSignInFailure, copy: FreeTierCopy): string}}-function failureBody(kind: FreeTierSignInFailure, message: null | string, retryAfter: number, copy: FreeTierCopy): string {+function failureBody(+ kind: FreeTierSignInFailure,+ message: null | string,+ retryAfter: number,+ copy: FreeTierCopy+): string {switch (kind) {case 'busy':// The backend's sentence already names the wait it was given; ours fillsdiff --git a/apps/desktop/src/components/onboarding-chat/cards/setup.tsx b/apps/desktop/src/components/onboarding-chat/cards/setup.tsxindex 18447be7d2d..be3daf49203 100644--- a/apps/desktop/src/components/onboarding-chat/cards/setup.tsx+++ b/apps/desktop/src/components/onboarding-chat/cards/setup.tsx@@ -102,7 +102,11 @@ export function ConnectorsCard({ locked }: CardProps) {icon={<ConnectorLogoclassName="size-7 rounded-full text-sm"- connector={{ iconUrl: connectorIconUrl(row.connector), name: row.connector, title: connectorTitle(row.connector) }}+ connector={{+ iconUrl: connectorIconUrl(row.connector),+ name: row.connector,+ title: connectorTitle(row.connector)+ }}/>}key={row.connector}diff --git a/apps/desktop/src/components/onboarding-chat/options.tsx b/apps/desktop/src/components/onboarding-chat/options.tsxindex 8767fc00887..941a648992f 100644--- a/apps/desktop/src/components/onboarding-chat/options.tsx+++ b/apps/desktop/src/components/onboarding-chat/options.tsx@@ -78,6 +78,7 @@ export function AccentSwatch({'relative inline-flex size-9 items-center justify-center rounded-full border border-foreground/15 transition-transform duration-150',!active && 'hover:scale-105')+const style = {background: hex,boxShadow: active ? `0 0 0 2px var(--dt-background), 0 0 0 4px ${hex}` : undefined@@ -99,7 +100,14 @@ export function AccentSwatch({/></label>) : (- <button aria-label={name} aria-pressed={active} className={className} onClick={onPick} style={style} type="button" />+ <button+ aria-label={name}+ aria-pressed={active}+ className={className}+ onClick={onPick}+ style={style}+ type="button"+ />)}</Tip>)diff --git a/apps/desktop/src/components/onboarding-chat/setup-profile.ts b/apps/desktop/src/components/onboarding-chat/setup-profile.tsindex 7810af1c8f4..4d141fd4593 100644--- a/apps/desktop/src/components/onboarding-chat/setup-profile.ts+++ b/apps/desktop/src/components/onboarding-chat/setup-profile.ts@@ -265,12 +265,17 @@ export async function buildFirstTaskSeedMessages(): Promise<{ content: string; display_kind?: 'hidden'; role: 'assistant' | 'user' }[]> {const root = plan === 'plugin' ? await window.hermesDesktop?.desktopPluginsRoot?.() : undefined- const capabilities = plan === 'machine-setup' ? '' : await readOnboardingCapabilities(scope, {- apps: answers.connectors,- context: `${task} ${answers.context}`- })+ const capabilities =+ plan === 'machine-setup'+ ? ''+ : await readOnboardingCapabilities(scope, {+ apps: answers.connectors,+ context: `${task} ${answers.context}`+ })- return [{ content: buildFirstTaskRunbook(task, answers, plan, root, capabilities), display_kind: 'hidden', role: 'user' }]+ return [+ { content: buildFirstTaskRunbook(task, answers, plan, root, capabilities), display_kind: 'hidden', role: 'user' }+ ]}/** The hidden note sent to the welcome chat once the build session is live. The check-ins after it come from thediff --git a/apps/desktop/src/components/onboarding/free-tier-setup-notice.test.tsx b/apps/desktop/src/components/onboarding/free-tier-setup-notice.test.tsxindex d0172b3c17d..cbe81d62108 100644--- a/apps/desktop/src/components/onboarding/free-tier-setup-notice.test.tsx+++ b/apps/desktop/src/components/onboarding/free-tier-setup-notice.test.tsx@@ -104,7 +104,12 @@ describe('FreeTierSetupNotice', () => {cleanup()$freeTierStatus.set(null)- const unreachable = ctxReturning({ ...NO_IDENTITY, error_code: 'anon_unreachable', retryable: true, retry_after: 15 })+ const unreachable = ctxReturning({+ ...NO_IDENTITY,+ error_code: 'anon_unreachable',+ retryable: true,+ retry_after: 15+ })render(<FreeTierSetupNotice ctx={unreachable} />)await screen.findByTestId('free-tier-setup-notice')diff --git a/apps/desktop/src/components/pane-shell/tree/focused-session-tab.test.ts b/apps/desktop/src/components/pane-shell/tree/focused-session-tab.test.tsindex c75b893f665..f2ccf3dd3b4 100644--- a/apps/desktop/src/components/pane-shell/tree/focused-session-tab.test.ts+++ b/apps/desktop/src/components/pane-shell/tree/focused-session-tab.test.ts@@ -105,7 +105,10 @@ describe('focused chat zone drives the tab verbs', () => {tree.declareDefaultTree(model.split('row', [model.group(['workspace'], { active: 'workspace', id: 'grp-main' }),- model.group(['preview-tile:url:x', 'route-tile:/capabilities'], { active: 'preview-tile:url:x', id: 'grp-view' })+ model.group(['preview-tile:url:x', 'route-tile:/capabilities'], {+ active: 'preview-tile:url:x',+ id: 'grp-view'+ })]))tree.noteActiveTreeGroup('grp-view')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 773b720e697..4310224c850 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@@ -200,6 +200,7 @@ describe('TreeGroup', () => {title: 'Browser',render: () => <input data-live-page defaultValue="original" />})+const disposePlain = registry.register({area: 'panes',id: 'plain',diff --git a/apps/desktop/src/components/tips/use-tip-rotation.test.tsx b/apps/desktop/src/components/tips/use-tip-rotation.test.tsxindex d267e93402f..c5bbae2e220 100644--- a/apps/desktop/src/components/tips/use-tip-rotation.test.tsx+++ b/apps/desktop/src/components/tips/use-tip-rotation.test.tsx@@ -170,6 +170,7 @@ it.each(['flag-off', 'tips-off', 'remote'])('does not read or offer when %s', asif (guard === 'remote') {$connection.set({ mode: 'remote' } as never)}+mount()await act(async () => {await vi.advanceTimersByTimeAsync(3_000)diff --git a/apps/desktop/src/components/ui/connector-card.test.tsx b/apps/desktop/src/components/ui/connector-card.test.tsxindex 02ef3c29348..568739aeafb 100644--- a/apps/desktop/src/components/ui/connector-card.test.tsx+++ b/apps/desktop/src/components/ui/connector-card.test.tsx@@ -71,6 +71,7 @@ describe('credentials under a row', () => {{ default: 'https://api.linear.app', name: 'LINEAR_URL', prompt: 'API URL', required: true, secret: false },{ default: '', name: 'LINEAR_API_KEY', prompt: 'API key', required: true, secret: true }]+const copy = {cancel: 'Cancel',connect: 'Connect',@@ -79,7 +80,19 @@ describe('credentials under a row', () => {}it('stay out of the way until the row asks for them', () => {- render(<SetupFormDialog copy={copy} fields={fields} onCancel={vi.fn()} onConnect={vi.fn()} onOpenBrowser={vi.fn()} open={false} pending={false} server="Linear" status="pending" />)+ render(+ <SetupFormDialog+ copy={copy}+ fields={fields}+ onCancel={vi.fn()}+ onConnect={vi.fn()}+ onOpenBrowser={vi.fn()}+ open={false}+ pending={false}+ server="Linear"+ status="pending"+ />+ )expect(screen.queryByLabelText('API key')).toBeNull()})@@ -87,7 +100,19 @@ describe('credentials under a row', () => {it('renders plain and masked inputs, prefills plain defaults, and reports the complete draft', () => {const onConnect = vi.fn()- render(<SetupFormDialog copy={copy} fields={fields} onCancel={vi.fn()} onConnect={onConnect} onOpenBrowser={vi.fn()} open pending={false} server="Linear" status="pending" />)+ render(+ <SetupFormDialog+ copy={copy}+ fields={fields}+ onCancel={vi.fn()}+ onConnect={onConnect}+ onOpenBrowser={vi.fn()}+ open+ pending={false}+ server="Linear"+ status="pending"+ />+ )const plain = screen.getByLabelText('API URL')const secret = screen.getByLabelText('API key')diff --git a/apps/desktop/src/components/ui/connector-card.tsx b/apps/desktop/src/components/ui/connector-card.tsxindex 54ae4cc4ddf..be55ca6e4ef 100644--- a/apps/desktop/src/components/ui/connector-card.tsx+++ b/apps/desktop/src/components/ui/connector-card.tsx@@ -87,7 +87,6 @@ export function ConnectorRow({ action, connector, cue, mark, markLabel }: Connec) : null}</span></div>-</div>)}diff --git a/apps/desktop/src/components/ui/decode-text.test.tsx b/apps/desktop/src/components/ui/decode-text.test.tsxindex ee30606a0d0..5d53748faaa 100644--- a/apps/desktop/src/components/ui/decode-text.test.tsx+++ b/apps/desktop/src/components/ui/decode-text.test.tsx@@ -14,7 +14,9 @@ const settleTicks = (text: string) => text.length * 2 + 16 + 4beforeEach(() => {vi.useFakeTimers()- window.matchMedia = vi.fn().mockReturnValue({ addEventListener: vi.fn(), matches: false, removeEventListener: vi.fn() })+ window.matchMedia = vi+ .fn()+ .mockReturnValue({ addEventListener: vi.fn(), matches: false, removeEventListener: vi.fn() })})afterEach(() => {diff --git a/apps/desktop/src/components/ui/fan-menu-tooltip.test.tsx b/apps/desktop/src/components/ui/fan-menu-tooltip.test.tsxindex 4d930fbd255..dcd248366c0 100644--- a/apps/desktop/src/components/ui/fan-menu-tooltip.test.tsx+++ b/apps/desktop/src/components/ui/fan-menu-tooltip.test.tsx@@ -6,7 +6,9 @@ import { FanMenu } from './fan-menu'vi.mock('./tooltip', () => ({Tip: ({ children, side }: { children: ReactNode; side: string }) => (- <span data-testid="tip" data-tip-side={side}>{children}</span>+ <span data-testid="tip" data-tip-side={side}>+ {children}+ </span>)}))diff --git a/apps/desktop/src/components/ui/setup-form-dialog.tsx b/apps/desktop/src/components/ui/setup-form-dialog.tsxindex 4e7c111484b..70a32de5efe 100644--- a/apps/desktop/src/components/ui/setup-form-dialog.tsx+++ b/apps/desktop/src/components/ui/setup-form-dialog.tsx@@ -98,7 +98,11 @@ export function SetupFormDialog({<Button disabled={pending} onClick={onCancel} variant="outline">{copy.cancel}</Button>- <Button disabled={missingRequired || pending || awaitingBrowser} loading={pending} onClick={() => onConnect(draft)}>+ <Button+ disabled={missingRequired || pending || awaitingBrowser}+ loading={pending}+ onClick={() => onConnect(draft)}+ >{copy.connect}</Button></DialogFooter>diff --git a/apps/desktop/src/components/ui/tooltip-pane-layout.test.tsx b/apps/desktop/src/components/ui/tooltip-pane-layout.test.tsxindex 0dad7a75c4d..ea84b1a1a81 100644--- a/apps/desktop/src/components/ui/tooltip-pane-layout.test.tsx+++ b/apps/desktop/src/components/ui/tooltip-pane-layout.test.tsx@@ -113,6 +113,8 @@ it('resolves the pane at open time, not at mount', async () => {await vi.waitFor(() => {// eslint-disable-next-line no-restricted-globals -- the portal mounts on the live document- expect(document.querySelector<HTMLElement>('[data-radix-popper-content-wrapper]')?.style.visibility).not.toBe('hidden')+ expect(document.querySelector<HTMLElement>('[data-radix-popper-content-wrapper]')?.style.visibility).not.toBe(+ 'hidden'+ )})})diff --git a/apps/desktop/src/contrib/events.ts b/apps/desktop/src/contrib/events.tsindex 202cc755e1e..3bbe1fbe072 100644--- a/apps/desktop/src/contrib/events.ts+++ b/apps/desktop/src/contrib/events.ts@@ -16,10 +16,7 @@ let activeDisposerTracker: ((dispose: () => void) => void) | null = null/** Run a plugin registration while associating its event listeners with its* unload disposer list. Runtime plugins are evaluated afresh on every reload,* so their host subscriptions must leave with the previous module instance. */-export function trackGatewayEventDisposers<T>(- track: (dispose: () => void) => void,- register: () => T-): T {+export function trackGatewayEventDisposers<T>(track: (dispose: () => void) => void, register: () => T): T {const previous = activeDisposerTrackeractiveDisposerTracker = trackdiff --git a/apps/desktop/src/i18n/ar.ts b/apps/desktop/src/i18n/ar.tsindex c13963bdc6a..90cf9b6a45f 100644--- a/apps/desktop/src/i18n/ar.ts+++ b/apps/desktop/src/i18n/ar.ts@@ -715,7 +715,8 @@ export const ar = defineLocale({},fieldLabels: {model: 'النموذج الافتراضي',- modelContextLength: 'يتجاوز نافذة السياق المكتشفة لنموذج المحادثة الرئيسي فقط (بالرموز). اتركه 0 لاستخدام القيمة المكتشفة للنموذج المحدد. لا يؤثر على النماذج المساعدة أو نماذج MoA.',+ modelContextLength:+ 'يتجاوز نافذة السياق المكتشفة لنموذج المحادثة الرئيسي فقط (بالرموز). اتركه 0 لاستخدام القيمة المكتشفة للنموذج المحدد. لا يؤثر على النماذج المساعدة أو نماذج MoA.',fallbackProviders: 'النماذج الاحتياطية',toolsets: 'مجموعات الأدوات المفعلة',timezone: 'المنطقة الزمنية',@@ -830,7 +831,8 @@ export const ar = defineLocale({'context.engine': 'استراتيجية إدارة المحادثات الطويلة قرب حد السياق.','compression.enabled': 'يلخص السياق الأقدم عندما تكبر المحادثات.','compression.codexGpt55Autoraise': 'يرفع عتبة الضغط إلى 85٪ لنماذج ChatGPT Codex OAuth المدعومة.',- 'auxiliary.compression.timeout': 'عدد الثواني لانتظار نموذج الضغط المساعد في كل استدعاء (الافتراضي 120). ارفعه للنماذج المحلية البطيئة.',+ 'auxiliary.compression.timeout':+ 'عدد الثواني لانتظار نموذج الضغط المساعد في كل استدعاء (الافتراضي 120). ارفعه للنماذج المحلية البطيئة.','voice.autoTts': 'ينطق ردود المساعد تلقائياً.','tts.xai.voiceId': 'معرف صوت xAI مثل eve أو معرف صوت مخصص.','tts.xai.language': 'رمز لغة النطق، مثل en.',@@ -3177,7 +3179,8 @@ export const ar = defineLocale({sudoSendFailed: 'فشل إرسال كلمة مرور sudo',secretSendFailed: 'فشل إرسال السر',sudoTitle: 'مطلوب sudo',- sudoDesc: 'راجع الأمر قبل إدخال كلمة مرور sudo. تُرسل كلمة المرور إلى الوكيل الذي ينفّذه وتُحفظ مؤقتًا لهذه الجلسة.',+ sudoDesc:+ 'راجع الأمر قبل إدخال كلمة مرور sudo. تُرسل كلمة المرور إلى الوكيل الذي ينفّذه وتُحفظ مؤقتًا لهذه الجلسة.',sudoCommandUnavailable: 'لم يقدّم هذا الوكيل الأمر. ألغِ الطلب إذا لم تتمكن من التحقق منه في المحادثة.',sudoPlaceholder: 'كلمة المرور',secretTitle: 'مطلوب سر',diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.tsindex 57d753d4147..0fb6235fa90 100644--- a/apps/desktop/src/i18n/en.ts+++ b/apps/desktop/src/i18n/en.ts@@ -146,7 +146,8 @@ export const en: Translations = {startingHermesDesktop: 'Starting Hermes Desktop…'},errors: {- backgroundExited: 'The service that runs your chats closed unexpectedly. Restart it to keep going — your chats and settings are safe.',+ backgroundExited:+ 'The service that runs your chats closed unexpectedly. Restart it to keep going — your chats and settings are safe.',backgroundExitedDuringStartup: 'Hermes stopped right after it started.',backendStopped: 'Hermes stopped working in the background',restartHermes: 'Restart Hermes',@@ -248,11 +249,13 @@ export const en: Translations = {storageFailure: "Hermes couldn't save to its data folder. Open Maintenance to check and repair it.",gatewayAuthFailed:'This Hermes no longer accepts your saved sign-in. Open Gateways and sign in again (or paste a new access token), then retry.',- methodNotAllowed: "Hermes' background service is out of step with the app, probably after an update. Restart it to fix this.",+ methodNotAllowed:+ "Hermes' background service is out of step with the app, probably after an update. Restart it to fix this.",microphonePermission: 'Microphone permission was denied.',openaiRejectedApiKey: "OpenAI didn't accept your API key. Update it in Settings → Keys, then try again.",openaiTtsNeedsKey: 'Voice needs an OpenAI key. Add one in Settings → Keys.',- codeSkewRestartRequired: 'Hermes was updated but is still running the old version. Restart it to finish the update.',+ codeSkewRestartRequired:+ 'Hermes was updated but is still running the old version. Restart it to finish the update.',restartHermesFailed: "Couldn't restart Hermes"},actions: {@@ -630,7 +633,8 @@ export const en: Translations = {desktopSuccess: name => `Desktop plugin ${name} installed`,agentFailed: 'Agent plugin install failed',desktopFailed: 'Desktop plugin install failed',- missingEnv: (name, vars) => `${name} is installed but needs a key before it can work: ${vars}. Add it now, or the plugin's tools will fail.`+ missingEnv: (name, vars) =>+ `${name} is installed but needs a key before it can work: ${vars}. Add it now, or the plugin's tools will fail.`}},vault: {@@ -798,7 +802,8 @@ export const en: Translations = {sessionDensityComfortable: 'Comfortable',sessionDensityDetailed: 'Detailed',tabStripTitle: 'Tab Strip',- tabStripDesc: 'Show tabs above a zone. Auto hides them for a single pane unless another chat or tile zone is open.',+ tabStripDesc:+ 'Show tabs above a zone. Auto hides them for a single pane unless another chat or tile zone is open.',tabStripAuto: 'Auto',tabStripAlways: 'Always',tabStripNever: 'Never',@@ -1156,7 +1161,8 @@ 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.',+ unavailableDesc:+ 'Connection settings can only be changed from the Hermes Desktop app on the computer running it.',title: 'Gateway Connection',envOverride: 'env override',intro:@@ -1209,7 +1215,8 @@ export const en: Translations = {remoteUrlTitle: 'Remote URL',remoteUrlDesc: 'Base URL for the remote dashboard backend. Path prefixes are supported, for example /hermes.',probing: 'Checking how this gateway authenticates…',- probeError: "Hermes can't reach that address. Check the URL and that the other computer is running Hermes — sign-in options appear once it answers.",+ probeError:+ "Hermes can't reach that address. Check the URL and that the other computer is running Hermes — sign-in options appear once it answers.",signedIn: 'Signed in',signIn: 'Sign in',signOut: 'Sign out',@@ -1656,7 +1663,8 @@ export const en: Translations = {useBackend: 'Use this backend',nousIncluded: 'Included with a Nous subscription — sign in with your Nous account to activate.',nousAuthNeededTitle: 'Sign in with your Nous account',- nousAuthNeededMessage: provider => `${provider} is saved but will only work once you sign in with your Nous account.`,+ nousAuthNeededMessage: provider =>+ `${provider} is saved but will only work once you sign in with your Nous account.`,nousAuthSignIn: 'Sign in',nousAuthDoneTitle: 'Nous account connected',nousAuthDoneMessage: 'Your subscription backends are now active.',@@ -1675,7 +1683,8 @@ export const en: Translations = {postSetupCompleteTitle: 'Setup complete',postSetupCompleteMessage: step => `${step} installed.`,postSetupErrorTitle: 'Setup finished with errors',- postSetupErrorMessage: step => `Setting up ${step} did not finish. Open the logs to see why, then run setup again.`,+ postSetupErrorMessage: step =>+ `Setting up ${step} did not finish. Open the logs to see why, then run setup again.`,postSetupOpenLogs: 'Open logs',postSetupRunAgain: 'Run again',postSetupFailed: step => `Failed to run ${step} setup`,@@ -1864,7 +1873,8 @@ export const en: Translations = {deepLinkCatalogInvalidName: 'The link\u2019s catalog name is missing or invalid.',deepLinkCatalogUnknown: (name: string) =>`\u201C${name}\u201D is not in the Hermes plugin catalog. Nothing was installed.`,- deepLinkCatalogUnavailable: 'Could not load the Hermes plugin catalog. Check your connection and open the link again.'+ deepLinkCatalogUnavailable:+ 'Could not load the Hermes plugin catalog. Check your connection and open the link again.'},officialCatalog: 'Available to install',officialPill: 'Official',@@ -3445,7 +3455,8 @@ export const en: Translations = {remoteUrlDesc: 'Use the base URL of the Hermes gateway, including https:// when remote.',remoteUrlPlaceholder: 'https://gateway.example.com/hermes',probing: 'Detecting gateway authentication...',- probeError: "Hermes can't reach that address. Check the URL and that the other computer is running Hermes — sign-in options appear once it answers.",+ probeError:+ "Hermes can't reach that address. Check the URL and that the other computer is running Hermes — sign-in options appear once it answers.",probeErrorDetails: 'Details',identityProvider: 'your identity provider',authTitle: 'Authentication',@@ -3613,7 +3624,7 @@ export const en: Translations = {timedOutHeading: 'That sign-in link has expired',timedOutBody: "Start again whenever you're ready. You're still on the free Nous service.",retiredBody:- 'Your session ended before the sign-in finished. Hermes will start a new one; then sign in again whenever you\'re ready.',+ "Your session ended before the sign-in finished. Hermes will start a new one; then sign in again whenever you're ready.",errorBody: "Sign-in didn't finish. Try again whenever you're ready.",busyHeading: 'Almost there',busyBody: wait =>@@ -3635,7 +3646,8 @@ export const en: Translations = {powRequired:"The Nous server asked for a proof of work, but that isn't implemented in your Agent yet. Sign in or create a free Nous account to continue.",locked: "This session can't continue without signing in. Sign in or create a free Nous account to keep going.",- generic: "Hermes couldn't set up free access without signing in. Signing in is free, or connect another provider.",+ generic:+ "Hermes couldn't set up free access without signing in. Signing in is free, or connect another provider.",signInBelow: 'Signing in is free. Pick Nous below.',tryAgain: 'Try again',retrying: 'Trying again…'@@ -4086,17 +4098,21 @@ export const en: Translations = {auth: 'The AI service rejected your sign-in. Check the credentials for this provider, then send your message again.',billing: 'Your account has no credits left for this provider. Top up or switch provider, then send again.',disk: 'Your disk is full, so Hermes could not save this conversation. Free some space, then retry.',- endpoint: "Hermes can't reach your custom model server. Check that it is running, then send your message again.",- gateway: 'Hermes hit an internal problem starting this reply. Send your message again; if it keeps happening, send diagnostics.',+ endpoint:+ "Hermes can't reach your custom model server. Check that it is running, then send your message again.",+ gateway:+ 'Hermes hit an internal problem starting this reply. Send your message again; if it keeps happening, send diagnostics.',generic: 'Something went wrong while Hermes was replying. Retry, or copy the details if it keeps happening.',provider: 'The AI service could not complete this request. Retry in a moment or switch provider.',- runtime: 'Hermes hit an internal problem starting this reply. Send your message again; if it keeps happening, send diagnostics.',+ runtime:+ 'Hermes hit an internal problem starting this reply. Send your message again; if it keeps happening, send diagnostics.',streaming: 'The connection dropped before the reply finished. Retry to send it again.'},errorCodes: {auth: {title: provider => `${provider} rejected your sign-in`,- body: provider => `The credentials saved for ${provider} were not accepted. Fix them in Settings or switch provider, then send your message again.`+ body: provider =>+ `The credentials saved for ${provider} were not accepted. Fix them in Settings or switch provider, then send your message again.`},auth_permanent: {title: provider => `${provider} rejected your sign-in`,@@ -4151,7 +4167,8 @@ export const en: Translations = {},model_not_found: {title: 'This model is not available',- body: provider => `${provider} does not offer this model on your account. Choose another model, then send your message again.`+ body: provider =>+ `${provider} does not offer this model on your account. Choose another model, then send your message again.`},provider_policy_blocked: {title: 'This model is blocked by your account settings',@@ -4441,8 +4458,10 @@ export const en: Translations = {sudoSendFailed: 'Could not send sudo password',secretSendFailed: 'Could not send secret',sudoTitle: 'Administrator password',- sudoDesc: 'Review the command before entering your sudo password. Your password is sent to the agent running it and cached for this session.',- sudoCommandUnavailable: 'This agent did not provide the command. Cancel if you cannot verify it in the conversation.',+ sudoDesc:+ 'Review the command before entering your sudo password. Your password is sent to the agent running it and cached for this session.',+ sudoCommandUnavailable:+ 'This agent did not provide the command. Cancel if you cannot verify it in the conversation.',sudoPlaceholder: 'sudo password',secretTitle: 'Secret required',secretDesc: 'Hermes needs a credential to continue.',@@ -4560,7 +4579,8 @@ export const en: Translations = {success: platform => `Handed off to ${platform}. Resume here anytime.`,systemNote: platform => `↻ Handed off to ${platform} — resume here anytime.`,failed: error => `Handoff failed: ${error}`,- timedOut: "Hermes couldn't reach your messaging connection. Start it from Settings → Messaging, then try the handoff again.",+ timedOut:+ "Hermes couldn't reach your messaging connection. Start it from Settings → Messaging, then try the handoff again.",startMessaging: 'Start messaging'}},diff --git a/apps/desktop/src/i18n/ja.ts b/apps/desktop/src/i18n/ja.tsindex 5acd3d71e08..80bd2549d73 100644--- a/apps/desktop/src/i18n/ja.ts+++ b/apps/desktop/src/i18n/ja.ts@@ -555,7 +555,8 @@ export const ja = defineLocale({sessionDensityComfortable: '標準',sessionDensityDetailed: '詳細',tabStripTitle: 'タブバー',- tabStripDesc: 'ゾーンの上にタブを表示します。自動では、他にチャットやタイルのゾーンがない限り、ペインが1つのときに隠します。',+ tabStripDesc:+ 'ゾーンの上にタブを表示します。自動では、他にチャットやタイルのゾーンがない限り、ペインが1つのときに隠します。',tabStripAuto: '自動',tabStripAlways: '常に表示',tabStripNever: '表示しない',@@ -687,7 +688,8 @@ export const ja = defineLocale({},fieldLabels: defineFieldCopy({model: 'デフォルトモデル',- modelContextLength: 'メインのチャットモデルのみ、検出されたコンテキストウィンドウを上書きします(トークン数)。0 のままにすると、選択したモデルから検出された値を使用します。補助モデル/MoA モデルには影響しません。',+ modelContextLength:+ 'メインのチャットモデルのみ、検出されたコンテキストウィンドウを上書きします(トークン数)。0 のままにすると、選択したモデルから検出された値を使用します。補助モデル/MoA モデルには影響しません。',fallbackProviders: 'フォールバックモデル',toolsets: '有効なツールセット',timezone: 'タイムゾーン',@@ -1492,8 +1494,7 @@ export const ja = defineLocale({selectedTitle: 'バックエンドを選択しました',selectedMessage: backend => `ターミナルコマンドは ${backend} で実行されます。新しいセッションに適用されます。`,failedSelect: backend => `${backend} の選択に失敗しました`,- needsSetupHint:- 'このバックエンドは選択されていますが、セットアップが完了するまでコマンドは失敗します。',+ needsSetupHint: 'このバックエンドは選択されていますが、セットアップが完了するまでコマンドは失敗します。',needsSetupConfirmTitle: backend => `それでも ${backend} を選択しますか?`,needsSetupConfirmDescription: detail =>`${detail} この変更後に開始されるセッションは、セットアップが完了するまでターミナルとファイルツールを使用できません。`,@@ -3600,7 +3601,8 @@ export const ja = defineLocale({sudoTitle: '管理者パスワード',sudoDesc:'sudo パスワードを入力する前にコマンドを確認してください。パスワードは実行するエージェントに送信され、このセッション中キャッシュされます。',- sudoCommandUnavailable: 'エージェントからコマンドが提供されていません。会話で確認できない場合はキャンセルしてください。',+ sudoCommandUnavailable:+ 'エージェントからコマンドが提供されていません。会話で確認できない場合はキャンセルしてください。',sudoPlaceholder: 'sudo パスワード',secretTitle: 'シークレットが必要です',secretDesc: 'Hermes は続行するための認証情報が必要です。',diff --git a/apps/desktop/src/i18n/ru.ts b/apps/desktop/src/i18n/ru.tsindex 85cc93f4021..e4806d00fdf 100644--- a/apps/desktop/src/i18n/ru.ts+++ b/apps/desktop/src/i18n/ru.ts@@ -610,7 +610,8 @@ export const ru = defineLocale({toolViewTitle: 'Отображение вызовов инструментов',toolViewDesc: 'Режим «Продукт» скрывает сырые данные инструментов, «Технический» показывает полный вход/выход.',hideCodeDiffsTitle: 'Скрывать изменения кода',- hideCodeDiffsDesc: 'Показывать правки файлов строками инструментов с числом добавленных и удалённых строк, без кода.',+ hideCodeDiffsDesc:+ 'Показывать правки файлов строками инструментов с числом добавленных и удалённых строк, без кода.',hideThreadTimelineTitle: 'Скрывать полоски истории диалога',hideThreadTimelineDesc: 'Скрывать полоски навигации вдоль правого края каждого диалога.',reasoningCollapsedTitle: 'Сворачивать «мышление» по умолчанию',@@ -625,7 +626,8 @@ export const ru = defineLocale({sessionDensityComfortable: 'Комфортно',sessionDensityDetailed: 'Подробно',tabStripTitle: 'Панель вкладок',- tabStripDesc: 'Показывать вкладки над зоной. Автоматически скрываются для одной панели, если не открыта другая зона чата или плитки.',+ tabStripDesc:+ 'Показывать вкладки над зоной. Автоматически скрываются для одной панели, если не открыта другая зона чата или плитки.',tabStripAuto: 'Авто',tabStripAlways: 'Всегда',tabStripNever: 'Никогда',@@ -747,7 +749,8 @@ export const ru = defineLocale({},fieldLabels: defineFieldCopy({model: 'Модель по умолчанию',- modelContextLength: 'Переопределяет обнаруженное окно контекста ТОЛЬКО основной модели чата (в токенах). Оставьте 0, чтобы использовать обнаруженное значение выбранной модели. Не влияет на вспомогательные модели и модели MoA.',+ modelContextLength:+ 'Переопределяет обнаруженное окно контекста ТОЛЬКО основной модели чата (в токенах). Оставьте 0, чтобы использовать обнаруженное значение выбранной модели. Не влияет на вспомогательные модели и модели MoA.',fallbackProviders: 'Резервные модели',toolsets: 'Включённые наборы инструментов',timezone: 'Часовой пояс',@@ -973,7 +976,8 @@ export const ru = defineLocale({},auxiliary: {compression: {- timeout: 'Сколько секунд ждать вспомогательную модель сжатия за один вызов (по умолчанию 120). Увеличьте для медленных локальных моделей.'+ timeout:+ 'Сколько секунд ждать вспомогательную модель сжатия за один вызов (по умолчанию 120). Увеличьте для медленных локальных моделей.'}},voice: {@@ -1089,7 +1093,8 @@ export const ru = defineLocale({errorTitle: 'Ошибка сочетания для снимка окна',loadFailed: 'Не удалось прочитать состояние сочетания. Повторите попытку, чтобы проверить текущую настройку.',saveFailed: 'Не удалось подтвердить изменение сочетания. Повторите попытку, чтобы проверить текущую настройку.',- permissionFailed: 'Не удалось открыть Системные настройки. Откройте раздел «Конфиденциальность и безопасность» вручную и повторите попытку.',+ permissionFailed:+ 'Не удалось открыть Системные настройки. Откройте раздел «Конфиденциальность и безопасность» вручную и повторите попытку.',captureFailed: 'Не удалось снять переднее окно. Ничего не прикреплено и не отправлено.',contextChanged: 'Текущий черновик изменился во время съёмки. Снимок не прикреплён и не отправлен.'},diff --git a/apps/desktop/src/i18n/zh-hant.ts b/apps/desktop/src/i18n/zh-hant.tsindex 31fe5602f35..e303a84e7e6 100644--- a/apps/desktop/src/i18n/zh-hant.ts+++ b/apps/desktop/src/i18n/zh-hant.ts@@ -663,7 +663,8 @@ export const zhHant = defineLocale({},fieldLabels: defineFieldCopy({model: '預設模型',- modelContextLength: '僅覆寫主聊天模型偵測到的上下文視窗(以 token 計)。保留 0 會使用所選模型偵測到的值。不影響輔助模型/MoA 模型。',+ modelContextLength:+ '僅覆寫主聊天模型偵測到的上下文視窗(以 token 計)。保留 0 會使用所選模型偵測到的值。不影響輔助模型/MoA 模型。',fallbackProviders: '備用模型',toolsets: '已啟用工具集',timezone: '時區',@@ -1510,8 +1511,10 @@ export const zhHant = defineLocale({failedSelect: backend => `選擇 ${backend} 失敗`,needsSetupHint: '此後端已選取但尚未完成設定——在設定完成前命令將會失敗。',needsSetupConfirmTitle: backend => `仍要選擇 ${backend} 嗎?`,- needsSetupConfirmDescription: detail => `${detail} 此變更生效後啟動的工作階段在設定完成前將沒有終端或檔案工具。`,- needsSetupConfirmDescriptionGeneric: '此後端尚未完成設定。此變更生效後啟動的工作階段在設定完成前將沒有終端或檔案工具。',+ needsSetupConfirmDescription: detail =>+ `${detail} 此變更生效後啟動的工作階段在設定完成前將沒有終端或檔案工具。`,+ needsSetupConfirmDescriptionGeneric:+ '此後端尚未完成設定。此變更生效後啟動的工作階段在設定完成前將沒有終端或檔案工具。',needsSetupConfirmAction: '仍然選擇'},browserRealProfile: {diff --git a/apps/desktop/src/i18n/zh.ts b/apps/desktop/src/i18n/zh.tsindex 1f02f8e8bff..dcc22d4b01e 100644--- a/apps/desktop/src/i18n/zh.ts+++ b/apps/desktop/src/i18n/zh.ts@@ -874,7 +874,8 @@ export const zh = defineLocale({},fieldLabels: defineFieldCopy({model: '默认模型',- modelContextLength: '仅覆盖主聊天模型检测到的上下文窗口(以 token 计)。保持为 0 则使用所选模型检测到的值。不影响辅助模型/MoA 模型。',+ modelContextLength:+ '仅覆盖主聊天模型检测到的上下文窗口(以 token 计)。保持为 0 则使用所选模型检测到的值。不影响辅助模型/MoA 模型。',fallbackProviders: '备用模型',toolsets: '启用的工具集',timezone: '时区',@@ -1898,7 +1899,8 @@ export const zh = defineLocale({needsSetupHint: '此后端已选中但尚未完成设置——在设置完成前命令将会失败。',needsSetupConfirmTitle: backend => `仍要选择 ${backend} 吗?`,needsSetupConfirmDescription: detail => `${detail} 此更改生效后启动的会话在设置完成前将没有终端或文件工具。`,- needsSetupConfirmDescriptionGeneric: '此后端尚未完成设置。此更改生效后启动的会话在设置完成前将没有终端或文件工具。',+ needsSetupConfirmDescriptionGeneric:+ '此后端尚未完成设置。此更改生效后启动的会话在设置完成前将没有终端或文件工具。',needsSetupConfirmAction: '仍然选择'},browserRealProfile: {@@ -2000,7 +2002,8 @@ export const zh = defineLocale({desktopHalfPending: '复制中…',desktopHalfPendingTip: '此包附带的桌面部分尚未复制到应用中。请重新扫描或重启应用。',desktopHalfRemote: '不可用(远程后端)',- desktopHalfRemoteTip: '此包的桌面部分位于远程后端的磁盘上,本应用无法读取。要在此使用,请通过“从 Git 安装”输入该包的仓库地址并勾选桌面目标,即可将桌面部分克隆到本机。',+ desktopHalfRemoteTip:+ '此包的桌面部分位于远程后端的磁盘上,本应用无法读取。要在此使用,请通过“从 Git 安装”输入该包的仓库地址并勾选桌面目标,即可将桌面部分克隆到本机。',emptyAll: '还没有插件。',empty: '此配置尚未安装任何 agent 插件。',emptyHint: '在下方目录中浏览,一键安装经过审核的插件。',diff --git a/apps/desktop/src/lib/chat-messages.test.ts b/apps/desktop/src/lib/chat-messages.test.tsindex 65aae4043c3..682ed238782 100644--- a/apps/desktop/src/lib/chat-messages.test.ts+++ b/apps/desktop/src/lib/chat-messages.test.ts@@ -190,7 +190,11 @@ describe('toChatMessages', () => {const [plain, , replied, assistant] = toChatMessages([{ role: 'user', content: `${note}\n\nCreate a project plan for Q4`, timestamp: 1 },{ role: 'assistant', content: 'ok', timestamp: 2 },- { role: 'user', content: `[Replying to: "Create a project plan for Q4"]\n\n${note}\n\nyes do that`, timestamp: 3 },+ {+ role: 'user',+ content: `[Replying to: "Create a project plan for Q4"]\n\n${note}\n\nyes do that`,+ timestamp: 3+ },{ role: 'assistant', content: note, timestamp: 4 }])@@ -1445,7 +1449,10 @@ describe('sealOpenToolParts', () => {)])- const messages = [...stopped, { id: 'u2', role: 'user', parts: [{ type: 'text', text: 'ask something else' }] } as ChatMessage]+ const messages = [+ ...stopped,+ { id: 'u2', role: 'user', parts: [{ type: 'text', text: 'ask something else' }] } as ChatMessage+ ]const restored = restorePendingClarifyToolCall(messages,diff --git a/apps/desktop/src/lib/chat-messages/parts.ts b/apps/desktop/src/lib/chat-messages/parts.tsindex b887d5878b7..58e62ac5c33 100644--- a/apps/desktop/src/lib/chat-messages/parts.ts+++ b/apps/desktop/src/lib/chat-messages/parts.ts@@ -17,22 +17,69 @@ export function reasoningPart(text: string, timestamp?: number): ChatMessagePart* unquoted path that may contain interior spaces (#96657).*/const MEDIA_DELIVERY_EXTS = [- 'png', 'jpg', 'jpeg', 'gif', 'webp', 'bmp', 'tiff', 'svg',- 'mp4', 'mov', 'avi', 'mkv', 'webm', '3gp',- 'mp3', 'm2a', 'wav', 'ogg', 'opus', 'm4a', 'flac',- 'pdf', 'docx', 'doc', 'odt', 'rtf', 'txt', 'md', 'epub',- 'xlsx', 'xls', 'ods', 'csv', 'tsv', 'json', 'xml', 'yaml', 'yml',- 'kmz', 'kml', 'geojson', 'gpx',- 'pptx', 'ppt', 'odp', 'key',- 'zip', 'tar', 'gz', 'tgz', 'bz2', 'xz', '7z', 'rar', 'apk', 'ipa',- 'html', 'htm',+ 'png',+ 'jpg',+ 'jpeg',+ 'gif',+ 'webp',+ 'bmp',+ 'tiff',+ 'svg',+ 'mp4',+ 'mov',+ 'avi',+ 'mkv',+ 'webm',+ '3gp',+ 'mp3',+ 'm2a',+ 'wav',+ 'ogg',+ 'opus',+ 'm4a',+ 'flac',+ 'pdf',+ 'docx',+ 'doc',+ 'odt',+ 'rtf',+ 'txt',+ 'md',+ 'epub',+ 'xlsx',+ 'xls',+ 'ods',+ 'csv',+ 'tsv',+ 'json',+ 'xml',+ 'yaml',+ 'yml',+ 'kmz',+ 'kml',+ 'geojson',+ 'gpx',+ 'pptx',+ 'ppt',+ 'odp',+ 'key',+ 'zip',+ 'tar',+ 'gz',+ 'tgz',+ 'bz2',+ 'xz',+ '7z',+ 'rar',+ 'apk',+ 'ipa',+ 'html',+ 'htm'] as const// Sort longest-first so the alternation never matches a shorter ext as a// prefix of a longer one (e.g. `tar` before a hypothetical `tar.gz`).-const _MEDIA_EXT_ALTERNATION = [...MEDIA_DELIVERY_EXTS]- .sort((a, b) => b.length - a.length)- .join('|')+const _MEDIA_EXT_ALTERNATION = [...MEDIA_DELIVERY_EXTS].sort((a, b) => b.length - a.length).join('|')/*** Unquoted path branch: starts with a path anchor (`~/`, `/`, `X:\` or `X:/`),@@ -40,8 +87,7 @@ const _MEDIA_EXT_ALTERNATION = [...MEDIA_DELIVERY_EXTS]* extension. Matches the Python-side `MEDIA_TAG_CLEANUP_RE` behavior where* `(?:[^\S\n]+\S+?)*?\.(?:EXT)` permits spaces inside filenames (#96657).*/-const _MEDIA_PATH_ANCHORED =- `(?:~/|/|[A-Za-z]:[/\\\\])\\S+?(?:[^\\S\\n]+\\S+?)*?\\.(?:${_MEDIA_EXT_ALTERNATION})(?=[\\s\`"'*_,;:)\\]}]|MEDIA:|$)`+const _MEDIA_PATH_ANCHORED = `(?:~/|/|[A-Za-z]:[/\\\\])\\S+?(?:[^\\S\\n]+\\S+?)*?\\.(?:${_MEDIA_EXT_ALTERNATION})(?=[\\s\`"'*_,;:)\\]}]|MEDIA:|$)`const MEDIA_LINE_RE = new RegExp(`(^|\\n)[\\t ]*[\`"']?MEDIA:\\s*(?<line>\`[^\`\\n]+\`|"[^"\\n]+"|'[^'\\n]+'|${_MEDIA_PATH_ANCHORED}|\\S+)[\`"']?[\\t ]*(\\n|$)`,diff --git a/apps/desktop/src/lib/chat-messages/reconciliation.test.ts b/apps/desktop/src/lib/chat-messages/reconciliation.test.tsindex 71b6439dfa2..6351d22eed2 100644--- a/apps/desktop/src/lib/chat-messages/reconciliation.test.ts+++ b/apps/desktop/src/lib/chat-messages/reconciliation.test.ts@@ -3,13 +3,21 @@ import { expect, it } from 'vitest'import { type ChatMessage, preserveLocalAssistantErrors, textPart, toChatMessages } from './index'const row = (id: string, role: 'user' | 'assistant', text: string, extra: Partial<ChatMessage> = {}): ChatMessage => ({- id, role, parts: [textPart(text)], ...extra+ id,+ role,+ parts: [textPart(text)],+ ...extra})it('reconciles only the represented failed tail, retaining its structured error and omitted segments', () => {const hydrated = toChatMessages([{ role: 'user', content: 'read it', timestamp: 1 },- { role: 'assistant', content: '', timestamp: 2, tool_calls: [{ id: 'call', function: { name: 'read_file', arguments: '{"path":"README.md"}' } }] },+ {+ role: 'assistant',+ content: '',+ timestamp: 2,+ tool_calls: [{ id: 'call', function: { name: 'read_file', arguments: '{"path":"README.md"}' } }]+ },{ role: 'tool', tool_call_id: 'call', tool_name: 'read_file', content: 'contents', timestamp: 3 },{ role: 'assistant', content: 'Done.', timestamp: 4 }])@@ -25,7 +33,12 @@ it('reconciles only the represented failed tail, retaining its structured errorfor (const id of [failed.id, storedAssistant.id]) {const merged = preserveLocalAssistantErrors(hydrated, [row('local-user', 'user', 'read it'), { ...failed, id }])expect(merged.filter(message => message.role === 'assistant')).toHaveLength(1)- expect(merged.at(-1)).toMatchObject({ id: storedAssistant.id, error: failed.error, errorSurface: failed.errorSurface, pending: false })+ expect(merged.at(-1)).toMatchObject({+ id: storedAssistant.id,+ error: failed.error,+ errorSurface: failed.errorSurface,+ pending: false+ })}const user = row('user', 'user', 'read it')@@ -33,13 +46,29 @@ it('reconciles only the represented failed tail, retaining its structured errorconst laterUser = row('later-user', 'user', 'read it')const cases: { name: string; stored: ChatMessage[]; local: ChatMessage[] }[] = [- { name: 'omitted continuation', stored: [user, earlier], local: [user, earlier, row('hidden', 'user', 'Continue.', { hidden: true }), failed] },+ {+ name: 'omitted continuation',+ stored: [user, earlier],+ local: [user, earlier, row('hidden', 'user', 'Continue.', { hidden: true }), failed]+ },{ name: 'older failed segment', stored: [user, earlier], local: [user, failed, earlier] },{ name: 'repeated prompt', stored: [user, earlier], local: [user, earlier, laterUser, failed] },{ name: 'older identical text', stored: [user, earlier, laterUser], local: [user, earlier, laterUser, failed] },- { name: 'different attachments', stored: [{ ...user, attachmentRefs: ['a.png'] }, earlier], local: [{ ...user, attachmentRefs: ['b.png'] }, failed] },- { name: 'different durable row', stored: [user, { ...earlier, rowId: 10 }], local: [user, { ...failed, rowId: 20 }] },- { name: 'reused tool id across turns', stored: [user, storedAssistant, laterUser], local: [user, storedAssistant, laterUser, failed] }+ {+ name: 'different attachments',+ stored: [{ ...user, attachmentRefs: ['a.png'] }, earlier],+ local: [{ ...user, attachmentRefs: ['b.png'] }, failed]+ },+ {+ name: 'different durable row',+ stored: [user, { ...earlier, rowId: 10 }],+ local: [user, { ...failed, rowId: 20 }]+ },+ {+ name: 'reused tool id across turns',+ stored: [user, storedAssistant, laterUser],+ local: [user, storedAssistant, laterUser, failed]+ }]for (const fixture of cases) {diff --git a/apps/desktop/src/lib/chat-messages/tool-parts.ts b/apps/desktop/src/lib/chat-messages/tool-parts.tsindex 2fdaaa21198..9868b98a2cc 100644--- a/apps/desktop/src/lib/chat-messages/tool-parts.ts+++ b/apps/desktop/src/lib/chat-messages/tool-parts.ts@@ -357,7 +357,12 @@ export function upsertToolPart(if (index === -1) {next.push(base)- } else if (phase === 'running' && prev?.type === 'tool-call' && prev.completedAt !== undefined && prev.result === undefined) {+ } else if (+ phase === 'running' &&+ prev?.type === 'tool-call' &&+ prev.completedAt !== undefined &&+ prev.result === undefined+ ) {// A settle-time seal (interim boundary, mid-turn user message, lost// completion) closed this call without a result. A running event for the// same id says the tool is still executing, so the row goes live againdiff --git a/apps/desktop/src/lib/connector-tools.ts b/apps/desktop/src/lib/connector-tools.tsindex 3c55d291f8e..254436bf87a 100644--- a/apps/desktop/src/lib/connector-tools.ts+++ b/apps/desktop/src/lib/connector-tools.ts@@ -45,7 +45,6 @@ export interface ConnectorRow {* for every lead-order pick). Served as an SVG with no CORS header, so it is only ever an `<img src>`. */export const connectorIconUrl = (slug: string): string => `https://logos.composio.dev/api/${slug}`-export function connectorText(value: ToolCallMessagePart['result']): string | undefined {return typeof value === 'string' ? value : undefined}diff --git a/apps/desktop/src/lib/deeplink-routes.test.ts b/apps/desktop/src/lib/deeplink-routes.test.tsindex f934d78f5f3..ace1834ef96 100644--- a/apps/desktop/src/lib/deeplink-routes.test.ts+++ b/apps/desktop/src/lib/deeplink-routes.test.ts@@ -34,9 +34,9 @@ describe('resolveDeepLinkAction', () => {).toEqual({ type: 'plugin-catalog-install', name: 'nope' })// An empty catalog name is still a catalog request (→ error toast), not a fall-through.- expect(resolveDeepLinkAction({ kind: 'plugin', name: 'install', params: { catalog: '', repo: 'evil/repo' } })).toEqual(- { type: 'plugin-catalog-install', name: '' }- )+ expect(+ resolveDeepLinkAction({ kind: 'plugin', name: 'install', params: { catalog: '', repo: 'evil/repo' } })+ ).toEqual({ type: 'plugin-catalog-install', name: '' })})it('routes legacy plugin-agent alias', () => {diff --git a/apps/desktop/src/lib/error-surface.test.ts b/apps/desktop/src/lib/error-surface.test.tsindex c39a1b6cf1e..6c9cf70f424 100644--- a/apps/desktop/src/lib/error-surface.test.ts+++ b/apps/desktop/src/lib/error-surface.test.ts@@ -142,12 +142,23 @@ describe('error copy never names a hidden Retry', () => {)it('a credential rejection keeps Retry, so its body may still say retry', () => {- const surface: ErrorSurface = { authKind: 'api_key', code: 'auth', layer: 'auth', provider: 'openai', retryable: false }+ const surface: ErrorSurface = {+ authKind: 'api_key',+ code: 'auth',+ layer: 'auth',+ provider: 'openai',+ retryable: false+ }expect(errorRecoveryPlan(surface).retry).toBe(true)})it('a WAF block names the firewall and the User-Agent fix, not the key and not a retry', () => {- const surface = parseErrorSurface({ code: 'upstream_blocked', layer: 'provider', provider: 'custom', retryable: false })!+ const surface = parseErrorSurface({+ code: 'upstream_blocked',+ layer: 'provider',+ provider: 'custom',+ retryable: false+ })!const { body, title } = errorCardText(thread, surface)expect(title).toBe(en.assistant.thread.errorCodes.upstream_blocked.title)expect(body).toMatch(/firewall/i)@@ -183,14 +194,17 @@ describe('free-tier refusals', () => {it('falls back to the table body when an older backend sent no sentence', () => {const bare = parseErrorSurface({ code: 'free_tier_rate_limited', layer: 'provider', retryable: true })!- expect(errorCardText(en.assistant.thread, bare).body).toBe(en.assistant.thread.errorCodes.free_tier_rate_limited.body)+ expect(errorCardText(en.assistant.thread, bare).body).toBe(+ en.assistant.thread.errorCodes.free_tier_rate_limited.body+ )expect(errorRecoveryPlan(bare).retry).toBe(true)})it('every free-tier code has copy and the copy never blames the free model', () => {for (const code of ERROR_CODE_KEYS.filter(key => key.startsWith('free_tier_'))) {const copy = en.assistant.thread.errorCodes[code]- const text = `${typeof copy.title === 'string' ? copy.title : ''} ${typeof copy.body === 'string' ? copy.body : ''}`.toLowerCase()+ const text =+ `${typeof copy.title === 'string' ? copy.title : ''} ${typeof copy.body === 'string' ? copy.body : ''}`.toLowerCase()expect(text).not.toMatch(/free (service|model|tier) is (off|switched off|unavailable|down)/)expect(text).not.toMatch(/anonymous|guest|credential|token|rate limit/)}@@ -220,6 +234,8 @@ describe('limit reset (#98852)', () => {expect(formatLimitReset(now / 1000 - 60, now)).toBeNull()expect(formatLimitReset(undefined, now)).toBeNull()expect(parseErrorSurface({ layer: 'provider', code: 'rate_limit', retryable: true })?.resetsAt).toBeUndefined()- expect(parseErrorSurface({ layer: 'provider', code: 'rate_limit', retryable: true, resets_at: 'soon' })?.resetsAt).toBeUndefined()+ expect(+ parseErrorSurface({ layer: 'provider', code: 'rate_limit', retryable: true, resets_at: 'soon' })?.resetsAt+ ).toBeUndefined()})})diff --git a/apps/desktop/src/lib/keybinds/actions.ts b/apps/desktop/src/lib/keybinds/actions.tsindex 553c134ba33..218e46dded3 100644--- a/apps/desktop/src/lib/keybinds/actions.ts+++ b/apps/desktop/src/lib/keybinds/actions.ts@@ -209,7 +209,9 @@ export interface KeybindContribution {// React consumers pass their `useContributions(KEYBINDS_AREA)` snapshot in:// with React Compiler enabled, an independently-called `contributedKeybinds()`// can stay memoized across a late registration the subscription DID deliver.-export function contributedKeybinds(contributions: readonly Contribution[] = registry.getArea(KEYBINDS_AREA)): KeybindContribution[] {+export function contributedKeybinds(+ contributions: readonly Contribution[] = registry.getArea(KEYBINDS_AREA)+): KeybindContribution[] {return contributions.map(c => c.data as KeybindContribution).filter(k => Boolean(k?.id && k.label) && typeof k?.run === 'function' && !ACTION_BY_ID.has(k.id))diff --git a/apps/desktop/src/lib/markdown-preprocess.ts b/apps/desktop/src/lib/markdown-preprocess.tsindex c54987da1b3..4d873f31388 100644--- a/apps/desktop/src/lib/markdown-preprocess.ts+++ b/apps/desktop/src/lib/markdown-preprocess.ts@@ -25,9 +25,7 @@ const OPEN_REASONING_BLOCK_RE = new RegExp(`(^|\\n)[ \\t]*<(${REASONING_TAGS})>[// agent/think_scrubber.py `_hold_partial`/`_max_partial_suffix` does, but only// for prefixes of the known tag names so `<div` at a line start still renders.const REASONING_TAG_PREFIXES = Array.from(- new Set(- REASONING_TAGS.split('|').flatMap((tag) => Array.from({ length: tag.length }, (_, i) => tag.slice(0, i + 1))),- ),+ new Set(REASONING_TAGS.split('|').flatMap(tag => Array.from({ length: tag.length }, (_, i) => tag.slice(0, i + 1))))).join('|')const PARTIAL_OPEN_REASONING_TAG_RE = new RegExp(`(^|\\n)[ \\t]*<(?:${REASONING_TAG_PREFIXES})?$`, 'i')diff --git a/apps/desktop/src/lib/model-status-label.test.ts b/apps/desktop/src/lib/model-status-label.test.tsindex 54150daca5e..dac0258f306 100644--- a/apps/desktop/src/lib/model-status-label.test.ts+++ b/apps/desktop/src/lib/model-status-label.test.ts@@ -1,6 +1,12 @@import { describe, expect, it } from 'vitest'-import { currentPickerSelection, displayModelName, formatModelPillLabel, modelDisplayParts, providerDisplayName } from './model-status-label'+import {+ currentPickerSelection,+ displayModelName,+ formatModelPillLabel,+ modelDisplayParts,+ providerDisplayName+} from './model-status-label'import { reasoningEffortLabel } from './reasoning-effort'describe('model-status-label', () => {diff --git a/apps/desktop/src/lib/model-status-label.ts b/apps/desktop/src/lib/model-status-label.tsindex eff96c4f449..d9271b7fc03 100644--- a/apps/desktop/src/lib/model-status-label.ts+++ b/apps/desktop/src/lib/model-status-label.ts@@ -80,7 +80,12 @@ function prettifyBase(base: string): string {if (/^claude-/i.test(base)) {// Anthropic ids spell the version with hyphens (`haiku-4-5`, `fable-5-1`);// the human name is dotted ("Haiku 4.5"), not "Haiku 4 5".- return titleCase(base.replace(/^claude-/i, '').replace(/(\d)-(?=\d)/g, '$1.').replace(/-/g, ' '))+ return titleCase(+ base+ .replace(/^claude-/i, '')+ .replace(/(\d)-(?=\d)/g, '$1.')+ .replace(/-/g, ' ')+ )}if (/^gpt-/i.test(base)) {diff --git a/apps/desktop/src/lib/onboarding-recommendations.test.ts b/apps/desktop/src/lib/onboarding-recommendations.test.tsindex bdfb4e8bbd2..5202aec5c2c 100644--- a/apps/desktop/src/lib/onboarding-recommendations.test.ts+++ b/apps/desktop/src/lib/onboarding-recommendations.test.ts@@ -14,20 +14,44 @@ it('keeps new enabled managed apps searchable without disturbing the curated leafunction entry(name: string, patch: Partial<McpCatalogEntry> = {}): McpCatalogEntry {return {- name, description: `${name} integration`, source: 'https://example.test', transport: 'stdio',- auth_type: 'none', required_env: [], command: 'example', args: [], url: null, install_url: null,- install_ref: null, bootstrap: [], default_enabled: null, post_install: 'Enable the app integration.',- needs_install: false, installed: false, enabled: false,- suggest: { keywords: [name], hosts: [], applications: [name], examples: [`Make something in ${name}`], requires_app: true },+ name,+ description: `${name} integration`,+ source: 'https://example.test',+ transport: 'stdio',+ auth_type: 'none',+ required_env: [],+ command: 'example',+ args: [],+ url: null,+ install_url: null,+ install_ref: null,+ bootstrap: [],+ default_enabled: null,+ post_install: 'Enable the app integration.',+ needs_install: false,+ installed: false,+ enabled: false,+ suggest: {+ keywords: [name],+ hosts: [],+ applications: [name],+ examples: [`Make something in ${name}`],+ requires_app: true+ },...patch}}it('recommends catalog entries from evidence and intent, never from installation as proof of access', () => {const future = entry('future-paint', { suggest: null, detected_apps: ['Future Paint'] })- expect(onboardingRecommendations([future])).toMatchObject([{- name: future.name, description: future.description, examples: [], setupAction: 'install'- }])+ expect(onboardingRecommendations([future])).toMatchObject([+ {+ name: future.name,+ description: future.description,+ examples: [],+ setupAction: 'install'+ }+ ])expect(onboardingRecommendations([])).toEqual([])const local = entry('modeler', { detected_apps: ['Modeler'] })const newEntry = entry('future-studio', { detected_apps: ['Future Studio'] })@@ -44,7 +68,11 @@ it('recommends catalog entries from evidence and intent, never from installationexpect(suggestions.every(row => row.examples.length === 1)).toBe(true)expect(onboardingRecommendations(rows, { context: 'Use future studio' })[0].examples).toContain(longerExample)expect(suggestions.map(row => row.readiness)).not.toContain('connected')- expect(suggestions.find(row => row.name === local.name)).toMatchObject({ readiness: 'setup_required', detectedApps: ['Modeler'], setupAction: 'install' })+ expect(suggestions.find(row => row.name === local.name)).toMatchObject({+ readiness: 'setup_required',+ detectedApps: ['Modeler'],+ setupAction: 'install'+ })expect(suggestions.find(row => row.name === configured.name)?.setupAction).toBeNull()expect(onboardingRecommendations(rows, { context: 'Use paused studio' })[0].setupAction).toBe('enable')expect(suggestions.find(row => row.name === configured.name)?.readiness).toBe('configured_unverified')diff --git a/apps/desktop/src/lib/onboarding-recommendations.ts b/apps/desktop/src/lib/onboarding-recommendations.tsindex 6bef1fa835b..84f116dec47 100644--- a/apps/desktop/src/lib/onboarding-recommendations.ts+++ b/apps/desktop/src/lib/onboarding-recommendations.ts@@ -16,7 +16,12 @@ export interface OnboardingRecommendation {setupAction: 'install' | 'enable' | null}-const words = (text: string): string => text.toLowerCase().split(/[^\p{L}\p{N}]+/u).filter(Boolean).join(' ')+const words = (text: string): string =>+ text+ .toLowerCase()+ .split(/[^\p{L}\p{N}]+/u)+ .filter(Boolean)+ .join(' ')/** Rank evidence, not a fixed list of products. The model derives outcomes from catalog descriptions; curated examples are optional. */export function onboardingRecommendations(@@ -29,7 +34,9 @@ export function onboardingRecommendations(const candidates = entries.flatMap(entry => {const examples = [...new Set(entry.suggest?.examples ?? [])].filter(text => text.trim())- const terms = [entry.name, ...(entry.suggest?.keywords ?? []), ...(entry.suggest?.applications ?? [])].map(words).filter(Boolean)+ const terms = [entry.name, ...(entry.suggest?.keywords ?? []), ...(entry.suggest?.applications ?? [])]+ .map(words)+ .filter(Boolean)const preferred = terms.some(term => selected.has(term))const topical = terms.some(term => subject.includes(` ${term} `))const detectedApps = entry.detected_apps ?? []@@ -62,11 +69,15 @@ export function onboardingRecommendations(return [{ recommendation, topical, preferred, configured, detected: detectedApps.length > 0 }]})- return candidates.sort((a, b) =>- Number(b.topical) - Number(a.topical)- || Number(b.preferred) - Number(a.preferred)- || Number(b.configured) - Number(a.configured)- || Number(b.detected) - Number(a.detected)- || a.recommendation.name.localeCompare(b.recommendation.name)- ).slice(0, 6).map(candidate => candidate.recommendation)+ return candidates+ .sort(+ (a, b) =>+ Number(b.topical) - Number(a.topical) ||+ Number(b.preferred) - Number(a.preferred) ||+ Number(b.configured) - Number(a.configured) ||+ Number(b.detected) - Number(a.detected) ||+ a.recommendation.name.localeCompare(b.recommendation.name)+ )+ .slice(0, 6)+ .map(candidate => candidate.recommendation)}diff --git a/apps/desktop/src/lib/plugin-catalog.ts b/apps/desktop/src/lib/plugin-catalog.tsindex c0e8bba64de..5ebcbfcb7de 100644--- a/apps/desktop/src/lib/plugin-catalog.ts+++ b/apps/desktop/src/lib/plugin-catalog.ts@@ -33,7 +33,8 @@ export interface PluginCatalogEntry {export type PluginCatalogLookupError = 'invalid_name' | 'unavailable' | 'unknown'-export type PluginCatalogLookup = { ok: false; error: PluginCatalogLookupError } | { ok: true; entry: PluginCatalogEntry }+export type PluginCatalogLookup =+ { ok: false; error: PluginCatalogLookupError } | { ok: true; entry: PluginCatalogEntry }function asEntry(raw: unknown): null | PluginCatalogEntry {if (!raw || typeof raw !== 'object') {diff --git a/apps/desktop/src/lib/reasoning-effort.test.ts b/apps/desktop/src/lib/reasoning-effort.test.tsindex b2ee5506eef..4509752ccca 100644--- a/apps/desktop/src/lib/reasoning-effort.test.ts+++ b/apps/desktop/src/lib/reasoning-effort.test.ts@@ -1,7 +1,12 @@import { DEFAULT_REASONING_EFFORT, REASONING_EFFORT_VALUES } from '@hermes/shared'import { describe, expect, it } from 'vitest'-import { isThinkingEnabled, reasoningEffortClamp, reasoningEffortLabel, resolveReasoningEffort } from './reasoning-effort'+import {+ isThinkingEnabled,+ reasoningEffortClamp,+ reasoningEffortLabel,+ resolveReasoningEffort+} from './reasoning-effort'describe('reasoning-effort', () => {it('labels every level it claims to support', () => {diff --git a/apps/desktop/src/lib/voice-client-direct.test.ts b/apps/desktop/src/lib/voice-client-direct.test.tsindex 84ff1c80f1a..d788ec11434 100644--- a/apps/desktop/src/lib/voice-client-direct.test.ts+++ b/apps/desktop/src/lib/voice-client-direct.test.ts@@ -406,6 +406,9 @@ describe('cutSentences', () => {// Historical 24-char floor (older backend, no key): the opener rides with sentence two.expect(cutSentences(text, false).sentences).toEqual(['记得,叫团团。 然后我们再说第二句话,这一句要长一些才行。'])// tts.streaming.min_len = 6 (the CJK voice setup from #96927): spoken on its own.- expect(cutSentences(text, false, 6).sentences).toEqual(['记得,叫团团。', '然后我们再说第二句话,这一句要长一些才行。'])+ expect(cutSentences(text, false, 6).sentences).toEqual([+ '记得,叫团团。',+ '然后我们再说第二句话,这一句要长一些才行。'+ ])})})diff --git a/apps/desktop/src/lib/voice-live.routing.test.ts b/apps/desktop/src/lib/voice-live.routing.test.tsindex 5d520b4f2b1..3b0cadeb1a4 100644--- a/apps/desktop/src/lib/voice-live.routing.test.ts+++ b/apps/desktop/src/lib/voice-live.routing.test.ts@@ -17,7 +17,11 @@ const handlers: VoiceLiveHandlers = {}function installApi() {- const api = vi.fn(async (_request: unknown) => ({ ok: true, session: { id: 's1' }, transport: { sdp: 'answer', type: 'answer' } }))+ const api = vi.fn(async (_request: unknown) => ({+ ok: true,+ session: { id: 's1' },+ transport: { sdp: 'answer', type: 'answer' }+ }))Object.defineProperty(window, 'hermesDesktop', { configurable: true, value: { api } })diff --git a/apps/desktop/src/plugins/hermes-bots/bot-row.test.tsx b/apps/desktop/src/plugins/hermes-bots/bot-row.test.tsxindex d2f039aaa3a..98caa0d6e41 100644--- a/apps/desktop/src/plugins/hermes-bots/bot-row.test.tsx+++ b/apps/desktop/src/plugins/hermes-bots/bot-row.test.tsx@@ -229,7 +229,17 @@ describe('the bot row context menu speaks the active language', () => {describe('a group row', () => {const members = [{ name: 'alpha' }, { name: 'beta' }, { name: 'gamma' }] as GroupMember[]- const row = <GroupRow active={false} group="crew" members={members} needsYou={false} onDisband={noop} onNewSection={noop} onOpen={noop} />+ const row = (+ <GroupRow+ active={false}+ group="crew"+ members={members}+ needsYou={false}+ onDisband={noop}+ onNewSection={noop}+ onOpen={noop}+ />+ )beforeEach(() => {locale.current = 'en'@@ -252,7 +262,9 @@ describe('a group row', () => {it('names the reader in the active language when their line is the latest, without touching the log marker', () => {// 'You' is the persisted author sentinel on the log entry; only its rendering localizes.act(() =>- $groupChats.set({ crew: { log: [{ at: 1, from: { kind: 'user', name: 'You' }, text: 'ship it' }], running: false, watermarks: {} } })+ $groupChats.set({+ crew: { log: [{ at: 1, from: { kind: 'user', name: 'You' }, text: 'ship it' }], running: false, watermarks: {} }+ }))locale.current = 'zh'diff --git a/apps/desktop/src/plugins/hermes-bots/bot-row.tsx b/apps/desktop/src/plugins/hermes-bots/bot-row.tsxindex 88e6278cf0e..b0cab447144 100644--- a/apps/desktop/src/plugins/hermes-bots/bot-row.tsx+++ b/apps/desktop/src/plugins/hermes-bots/bot-row.tsx@@ -332,7 +332,9 @@ export function BotRow({ bot, onDelete, onEdit, onGroup, onNewSection, showHandl})host.notify({kind: 'info',- message: pinned ? b.bot.unpinnedToast(displayName(bot, current)) : b.bot.pinnedToast(displayName(bot, current))+ message: pinned+ ? b.bot.unpinnedToast(displayName(bot, current))+ : b.bot.pinnedToast(displayName(bot, current))})}).catch(error => host.notifyError?.(error, b.bot.metadataLoadFailed))diff --git a/apps/desktop/src/plugins/hermes-bots/create-dialog.tsx b/apps/desktop/src/plugins/hermes-bots/create-dialog.tsxindex 85b326d35a2..31747afa2df 100644--- a/apps/desktop/src/plugins/hermes-bots/create-dialog.tsx+++ b/apps/desktop/src/plugins/hermes-bots/create-dialog.tsx@@ -799,9 +799,9 @@ export function CreateAgentDialog({ open, onClose, roster }: CreateAgentDialogPrCopy API keys from the main profile</label><div className="pl-6 pt-0.5 text-[0.7rem] leading-5 text-(--ui-text-tertiary)">- Each profile owns its credentials. API keys are copied; OAuth logins (Claude, Codex, xAI, Nous)- are not — sign the bot in with <code>hermes -p <name> model</code>. Uncheck to start with- no credentials.+ Each profile owns its credentials. API keys are copied; OAuth logins (Claude, Codex, xAI, Nous) are+ not — sign the bot in with <code>hermes -p <name> model</code>. Uncheck to start with no+ credentials.</div><label className="flex items-center gap-2 text-xs text-(--ui-text-secondary)"><Checkbox checked={noSkills} onCheckedChange={value => setNoSkills(Boolean(value))} />@@ -1351,7 +1351,10 @@ export function CreateGroupChatDialog({ open, roster, onClose, onCreated }: Crea<Button onClick={onClose} variant="secondary">{t.common.cancel}</Button>- <Button disabled={!canCreate} onClick={create}>{`Create Group${selected.length ? ` (${selected.length})` : ''}`}</Button>+ <Button+ disabled={!canCreate}+ onClick={create}+ >{`Create Group${selected.length ? ` (${selected.length})` : ''}`}</Button></DialogFooter></DialogContent></Dialog>diff --git a/apps/desktop/src/plugins/hermes-bots/cron.tsx b/apps/desktop/src/plugins/hermes-bots/cron.tsxindex 9f946213877..4db7a2de6fb 100644--- a/apps/desktop/src/plugins/hermes-bots/cron.tsx+++ b/apps/desktop/src/plugins/hermes-bots/cron.tsx@@ -384,7 +384,10 @@ export function routineDetailRows(job: RoutineJob | null | undefined): Array<{ l['Repeat', job?.repeat],// A slot parked past the scheduler grace is labelled overdue, never// promised as a next run (#114309); the card below makes the same call.- [job && nextRunOverdueMs(job) !== null ? 'Overdue since' : 'Next run', paused ? null : routineTimestamp(job?.next_run_at)],+ [+ job && nextRunOverdueMs(job) !== null ? 'Overdue since' : 'Next run',+ paused ? null : routineTimestamp(job?.next_run_at)+ ],['Last run', routineTimestamp(job?.last_run_at)],['Last result', routineLastResult(job?.last_status)],['Delivers to', job?.deliver],diff --git a/apps/desktop/src/plugins/hermes-bots/data.ts b/apps/desktop/src/plugins/hermes-bots/data.tsindex 8b5ff31e212..83cb3de2a7f 100644--- a/apps/desktop/src/plugins/hermes-bots/data.ts+++ b/apps/desktop/src/plugins/hermes-bots/data.ts@@ -67,6 +67,7 @@ const BOT_ATTENTION_CLASSES: ReadonlySet<string> = new Set<AttentionClass>([* active locale; unknown classes fall back to the generic hint. */export function botAttentionHint(reason: string): string {const text = botsText().bot+const hints: Record<string, string> = {provider_auth_or_access: text.attentionProviderAuth,provider_quota_limit: text.attentionQuota,@@ -713,9 +714,7 @@ async function fetchRosterSnapshot(activeConnectionId: null | string | undefinedreturn {...merged,- profiles: (merged?.profiles || []).map(row =>- row?.remoteSource ? { ...row, sourceReachable: false } : row- ),+ profiles: (merged?.profiles || []).map(row => (row?.remoteSource ? { ...row, sourceReachable: false } : row)),fetchedAt: issuedAt}}diff --git a/apps/desktop/src/plugins/hermes-bots/group-activity.test.ts b/apps/desktop/src/plugins/hermes-bots/group-activity.test.tsindex 421e8c9067e..a2ac0f06eb4 100644--- a/apps/desktop/src/plugins/hermes-bots/group-activity.test.ts+++ b/apps/desktop/src/plugins/hermes-bots/group-activity.test.ts@@ -195,7 +195,7 @@ describe('turn arc', () => {turn: ({ profile }) => {if (profile === 'builder') {throw new Error(- "Error invoking remote method 'hermes:api': Local backend start for \"builder\" timed out while waiting for a free slot."+ 'Error invoking remote method \'hermes:api\': Local backend start for "builder" timed out while waiting for a free slot.')}@@ -209,7 +209,9 @@ describe('turn arc', () => {const failed = feed(room, 'Slot wait').find(event => event.kind === 'failed' && event.member === 'builder')expect(failed?.reason).toBe(room.activity.GROUP_SLOT_WAIT_REASON)- expect(room.activity.groupActivityLabel(failed!, 'Slot wait')).toBe("builder couldn't start — too many bots running")+ expect(room.activity.groupActivityLabel(failed!, 'Slot wait')).toBe(+ "builder couldn't start — too many bots running"+ )expect(room.data.$botAttention.get()).toEqual({})})})@@ -217,8 +219,10 @@ describe('turn arc', () => {describe('epoch scoping', () => {it('queues follow-ups without cancelling the active turn or losing its reply delta', async () => {let release!: (reply: string) => void- const first = new Promise<string>(resolve => { release = resolve })- const room = await loadRoom({ turn: ({ n }) => n === 1 ? first : '(pass)' })+ const first = new Promise<string>(resolve => {+ release = resolve+ })+ const room = await loadRoom({ turn: ({ n }) => (n === 1 ? first : '(pass)') })const member: GroupMember[] = [{ name: 'research', title: '' }]const thread = room.rounds.sendToGroupChat('Busy', member, 'first ask')!await drain(() => room.gateway.calls.length < 1, 50)diff --git a/apps/desktop/src/plugins/hermes-bots/group-activity.ts b/apps/desktop/src/plugins/hermes-bots/group-activity.tsindex 31efdf7d7ee..55d1a41d7e7 100644--- a/apps/desktop/src/plugins/hermes-bots/group-activity.ts+++ b/apps/desktop/src/plugins/hermes-bots/group-activity.ts@@ -92,9 +92,10 @@ export function isGroupSlotWaitTimeoutText(text: unknown): boolean {* nothing to act on (a stopped backend, a dead IPC bridge and a provider* refusal all read the same), so an unclassified failure keeps its message. */export function groupFailureReason(error: unknown): string {- const typed = typeof (error as { data?: { reason?: unknown } })?.data?.reason === 'string'- ? String((error as { data: { reason: string } }).data.reason).trim()- : ''+ const typed =+ typeof (error as { data?: { reason?: unknown } })?.data?.reason === 'string'+ ? String((error as { data: { reason: string } }).data.reason).trim()+ : ''if (typed) {return typed@@ -120,14 +121,17 @@ const GROUP_FAILURE_REDACTIONS: Array<[RegExp, string]> = [/** The first non-empty line of a raw error message, trimmed, secret spans* redacted, capped — the room row is a summary, the log keeps the rest. */export function groupFailureDetail(message: unknown): string {- const line = String(message || '')- .split(/\r?\n/)- .map(part => part.trim())- .find(Boolean) || ''+ const line =+ String(message || '')+ .split(/\r?\n/)+ .map(part => part.trim())+ .find(Boolean) || ''const redacted = GROUP_FAILURE_REDACTIONS.reduce((text, [re, repl]) => text.replace(re, repl), line)- return redacted.length > GROUP_FAILURE_DETAIL_LIMIT ? `${redacted.slice(0, GROUP_FAILURE_DETAIL_LIMIT - 1)}…` : redacted+ return redacted.length > GROUP_FAILURE_DETAIL_LIMIT+ ? `${redacted.slice(0, GROUP_FAILURE_DETAIL_LIMIT - 1)}…`+ : redacted}/** Human label for one activity event, used by the collapsed summary anddiff --git a/apps/desktop/src/plugins/hermes-bots/group-chat-view-members.test.ts b/apps/desktop/src/plugins/hermes-bots/group-chat-view-members.test.tsindex 052143f546e..5adf0570f0a 100644--- a/apps/desktop/src/plugins/hermes-bots/group-chat-view-members.test.ts+++ b/apps/desktop/src/plugins/hermes-bots/group-chat-view-members.test.ts@@ -60,14 +60,22 @@ const planner: RosterRow = { name: 'planner' }const reviewer: RosterRow = { name: 'reviewer' }const seatedNames = (room: Room) =>- room.membership.groupChatMemberBots('Core', room.data.$lastRoster.get(), room.data.$botMeta.get()).map(bot => bot.name).sort()+ room.membership+ .groupChatMemberBots('Core', room.data.$lastRoster.get(), room.data.$botMeta.get())+ .map(bot => bot.name)+ .sort()function seedCore(room: Room, extra: Partial<groupChat.GroupChatRoom> = {}) {room.data.$lastRoster.set([programmer, planner, reviewer])room.data.$botMeta.set({ programmer: { groups: ['Core'] }, reviewer: { groups: ['Core'] } })room.chat.updateGroupChat('Core',- r => ({ ...r, members: room.membership.durableGroupChatMembers([programmer, reviewer]), syncRevision: 7, ...extra }),+ r => ({+ ...r,+ members: room.membership.durableGroupChatMembers([programmer, reviewer]),+ syncRevision: 7,+ ...extra+ }),{ sync: false })}@@ -77,7 +85,7 @@ beforeEach(() => {})describe('setGroupChatMembers', () => {- it('outranks a tie-revision mirror poll and clears the removed member\'s room state', async () => {+ it("outranks a tie-revision mirror poll and clears the removed member's room state", async () => {const room = await loadRoom()seedCore(room, {holds: { reviewer: { at: 1 } },@@ -92,10 +100,15 @@ describe('setGroupChatMembers', () => {// revision the room had before Save (the poll that raced the publish).const mirror = {version: 3,- rooms: { 'name:Core': { name: 'Core', log: [], members: [{ name: 'programmer' }, { name: 'reviewer' }], revision: 7 } },+ rooms: {+ 'name:Core': { name: 'Core', log: [], members: [{ name: 'programmer' }, { name: 'reviewer' }], revision: 7 }+ },deleted: {}}- room.chat.$groupChats.set(room.chat.mergeRemoteGroupChatSnapshotIntoRooms(mirror as never, room.chat.$groupChats.get()))++ room.chat.$groupChats.set(+ room.chat.mergeRemoteGroupChatSnapshotIntoRooms(mirror as never, room.chat.$groupChats.get())+ )expect(seatedNames(room)).toEqual(['planner', 'programmer'])const saved = room.chat.$groupChats.get().Core as groupChat.GroupChatRoom@@ -109,6 +122,7 @@ describe('setGroupChatMembers', () => {it('keeps a same-named local Bot out when selecting only its Connection counterpart', async () => {const room = await loadRoom()const local: RosterRow = { name: 'planner', title: 'Local Planner' }+const remote: RosterRow = {connectionId: 'remote-1',connectionKind: 'remote',@@ -125,13 +139,15 @@ describe('setGroupChatMembers', () => {await room.members.setGroupChatMembers('Core', [remote, reviewer])expect(room.data.$botMeta.get().planner.groups).toEqual([])- expect(room.chat.$groupChats.get().Core.members).toEqual(expect.arrayContaining([- expect.objectContaining({ connectionId: 'remote-1', name: 'planner', sourceScoped: true }),- expect.objectContaining({ name: 'reviewer' })- ]))+ expect(room.chat.$groupChats.get().Core.members).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ connectionId: 'remote-1', name: 'planner', sourceScoped: true }),+ expect.objectContaining({ name: 'reviewer' })+ ])+ )})- it('does not replay a removed member\'s held messages after re-adding it', async () => {+ it("does not replay a removed member's held messages after re-adding it", async () => {const room = await loadRoom()seedCore(room, {heldMessages: { reviewer: ['held-before-removal'] },diff --git a/apps/desktop/src/plugins/hermes-bots/group-chat-view-members.tsx b/apps/desktop/src/plugins/hermes-bots/group-chat-view-members.tsxindex f822d49bc06..f2731a1d88f 100644--- a/apps/desktop/src/plugins/hermes-bots/group-chat-view-members.tsx+++ b/apps/desktop/src/plugins/hermes-bots/group-chat-view-members.tsx@@ -213,7 +213,10 @@ export function GroupMemberPicker({ group, members, open, onClose }: GroupMember}role="checkbox">- <Codicon className={cn(checked ? 'text-(--ui-accent)' : 'text-(--ui-text-quaternary)')} name={checked ? 'pass-filled' : 'circle-large-outline'} />+ <Codicon+ className={cn(checked ? 'text-(--ui-accent)' : 'text-(--ui-text-quaternary)')}+ name={checked ? 'pass-filled' : 'circle-large-outline'}+ /><div className="min-w-0 flex-1 text-left"><div className="truncate text-xs text-foreground">{displayName(bot, meta)}</div><div className="truncate text-[0.625rem] text-(--ui-text-quaternary)">diff --git a/apps/desktop/src/plugins/hermes-bots/group-chat-view.inline-code.test.tsx b/apps/desktop/src/plugins/hermes-bots/group-chat-view.inline-code.test.tsxindex 5437be991b9..125bc64ee34 100644--- a/apps/desktop/src/plugins/hermes-bots/group-chat-view.inline-code.test.tsx+++ b/apps/desktop/src/plugins/hermes-bots/group-chat-view.inline-code.test.tsx@@ -76,7 +76,9 @@ it('themes inline code in room message bodies with the chat inline-code tokens',const { $groupChats } = await import('./group-chat')const { GroupChatWorkspace } = await import('./group-chat-view')- const log = [{ id: 'm1', thread: 'a', from: { kind: 'member' as const, name: 'builder' }, text: 'discover_models', at: 1 }]+ const log = [+ { id: 'm1', thread: 'a', from: { kind: 'member' as const, name: 'builder' }, text: 'discover_models', at: 1 }+ ]$groupChats.set({ Room: { log, watermarks: {}, sessions: {} } })const { getByTestId } = render(<GroupChatWorkspace group="Room" members={[{ name: 'builder' }] as never} />)diff --git a/apps/desktop/src/plugins/hermes-bots/group-chat-view.tsx b/apps/desktop/src/plugins/hermes-bots/group-chat-view.tsxindex 24f3139af1f..5a899ccd322 100644--- a/apps/desktop/src/plugins/hermes-bots/group-chat-view.tsx+++ b/apps/desktop/src/plugins/hermes-bots/group-chat-view.tsx@@ -384,7 +384,14 @@ interface GroupChatSettingsDialogProps {/** Edit an existing group chat's name and picture. Renames re-key the room* and every local member's membership (renameGroupChat); the picture rides* the room record. Both apply on Save so a cancelled dialog changes nothing. */-function GroupChatSettingsDialog({ group, members, open, onClose, onManageMembers, onRenamed }: GroupChatSettingsDialogProps) {+function GroupChatSettingsDialog({+ group,+ members,+ open,+ onClose,+ onManageMembers,+ onRenamed+}: GroupChatSettingsDialogProps) {const { t } = useI18n()const b = useBots()const rooms: Record<string, GroupChatRoom> = useValue($groupChats)@@ -851,9 +858,8 @@ export function GroupChatWorkspace({ group, members, onBack, visible = true }: G}}- const summaryActivity = !room.running && unresolvedFailures.size- ? [...unresolvedFailures.values()].at(-1)!- : latestActivity+ const summaryActivity =+ !room.running && unresolvedFailures.size ? [...unresolvedFailures.values()].at(-1)! : latestActivity// #94570 shell rewired onto the real primitive (#91868/#94569): the button// must stop the ROUND, not just spray per-member interrupts — without the@@ -880,7 +886,9 @@ export function GroupChatWorkspace({ group, members, onBack, visible = true }: G<Codicon className="shrink-0 text-[0.65rem]" name={activityOpen ? 'chevron-down' : 'chevron-right'} /><span className="shrink-0 font-medium">{b.group.activity}</span>{summaryActivity ? (- <span className={cn('min-w-0 flex-1 truncate', groupActivityTone(summaryActivity.kind))}>{`${groupActivityLabel(summaryActivity, group)} · ${relativeTime(summaryActivity.at)}`}</span>+ <span+ className={cn('min-w-0 flex-1 truncate', groupActivityTone(summaryActivity.kind))}+ >{`${groupActivityLabel(summaryActivity, group)} · ${relativeTime(summaryActivity.at)}`}</span>) : null}</RowButton>{room.running ? (@@ -1078,7 +1086,8 @@ export function GroupChatWorkspace({ group, members, onBack, visible = true }: Greturn}- const seed = (current: string) => (current.includes(`@${tag}`) ? current : `@${tag} ${current}`.replace(/\s+$/, ' '))+ const seed = (current: string) =>+ current.includes(`@${tag}`) ? current : `@${tag} ${current}`.replace(/\s+$/, ' ')const thread = groupThreadOf(entry)if (replyThread === thread) {@@ -1187,7 +1196,9 @@ export function GroupChatWorkspace({ group, members, onBack, visible = true }: G</Button></Tip>)}- {entry.text.trim() ? <CopyButton appearance="icon" buttonSize="icon" stopPropagation text={entry.text} /> : null}+ {entry.text.trim() ? (+ <CopyButton appearance="icon" buttonSize="icon" stopPropagation text={entry.text} />+ ) : null}</div>) : null}</div>@@ -1401,7 +1412,12 @@ export function GroupChatWorkspace({ group, members, onBack, visible = true }: GonManageMembers={() => setMemberPickerOpen(true)}open={settingsOpen}/>- <GroupMemberPicker group={group} members={members} onClose={() => setMemberPickerOpen(false)} open={memberPickerOpen} />+ <GroupMemberPicker+ group={group}+ members={members}+ onClose={() => setMemberPickerOpen(false)}+ open={memberPickerOpen}+ /><ConfirmDialogbusyLabel={b.group.disbanding}confirmLabel={b.group.disbandAction}@@ -1451,7 +1467,6 @@ function GroupChatMainView({ group }: GroupChatMainViewProps) {const roster = useValue($lastRoster)const members = groupChatMemberBots(group, roster, allMeta)-// Older SDKs have no paneVisibility: fall back to an always-visible atom so// the hook order stays stable and behavior matches the previous build.const $visible = useMemo(diff --git a/apps/desktop/src/plugins/hermes-bots/group-chat.test.ts b/apps/desktop/src/plugins/hermes-bots/group-chat.test.tsindex 8a664a6620d..91a5c5ccc33 100644--- a/apps/desktop/src/plugins/hermes-bots/group-chat.test.ts+++ b/apps/desktop/src/plugins/hermes-bots/group-chat.test.ts@@ -99,7 +99,9 @@ describe('log window', () => {expect(chars).toBeLessThanOrEqual(chat.GROUP_CHAT_LOG_RETAIN_CHARS)expect(JSON.stringify(stored).length).toBeLessThan(chat.GROUP_CHAT_LOG_RETAIN_CHARS * 1.25)- expect(Math.max(...stored.log.map(entry => entry.text.length))).toBeLessThanOrEqual(chat.GROUP_CHAT_HISTORY_LINE_CHARS)+ expect(Math.max(...stored.log.map(entry => entry.text.length))).toBeLessThanOrEqual(+ chat.GROUP_CHAT_HISTORY_LINE_CHARS+ )expect(stored.log.at(-1)?.text.startsWith(`${chat.GROUP_CHAT_LOG_RETAIN - 1} `)).toBe(true)expect(stored.log.at(-1)?.text.endsWith('… [truncated]')).toBe(true)expect(stored.watermarks.builder).toBe(stored.log.length)@@ -141,15 +143,20 @@ describe('speaker labels', () => {expect(memberLine).toContain('Ordinary reply.')- for (const opener of ['[OUT-OF-BAND USER MESSAGE', '[/OUT-OF-BAND USER MESSAGE]', '[CONTEXT COMPACTION', '[Runtime note:']) {+ for (const opener of [+ '[OUT-OF-BAND USER MESSAGE',+ '[/OUT-OF-BAND USER MESSAGE]',+ '[CONTEXT COMPACTION',+ '[Runtime note:'+ ]) {expect(memberLine).not.toContain(opener)}expect(memberLine).toContain('[member-quoted OUT-OF-BAND USER MESSAGE — a direct message from the user]')expect(memberLine).toContain('[member-quoted /OUT-OF-BAND USER MESSAGE]')- expect(- formatGroupChatLine({ from: { kind: 'user', name: 'Haluk' }, text } as GroupMessage, 'research')- ).toContain(text)+ expect(formatGroupChatLine({ from: { kind: 'user', name: 'Haluk' }, text } as GroupMessage, 'research')).toContain(+ text+ )})it('the default profile speaks as Hermes in transcripts, not @default', async () => {@@ -211,7 +218,13 @@ describe('speaker labels', () => {const data = await import('./data')const local = { connectionId: 'local', connectionLabel: 'This device', name: 'reviewer', sourceScoped: true }- const spark = { connectionId: 'spark', connectionLabel: 'Spark', name: 'reviewer', remoteSource: true, sourceScoped: true }+ const spark = {+ connectionId: 'spark',+ connectionLabel: 'Spark',+ name: 'reviewer',+ remoteSource: true,+ sourceScoped: true+ }data.$lastRoster.set([local, spark])data.$botMeta.set({})@@ -240,13 +253,26 @@ describe('speaker labels', () => {const data = await import('./data')const local = { connectionId: 'local', connectionLabel: 'This device', name: 'reviewer', sourceScoped: true }- const spark = { connectionId: 'spark', connectionLabel: 'Spark', name: 'reviewer', remoteSource: true, sourceScoped: true }+ const spark = {+ connectionId: 'spark',+ connectionLabel: 'Spark',+ name: 'reviewer',+ remoteSource: true,+ sourceScoped: true+ }data.$lastRoster.set([local, spark])data.$botMeta.set({})// #94869 acceptance 3: the room seats only the local reviewer, so it// reads plain "Reviewer" however many other connections expose one.- chat.updateGroupChat('Core', room => ({ ...room, members: [{ connectionId: 'local', name: 'reviewer', remoteSource: true, sourceScoped: true }] }), { sync: false })+ chat.updateGroupChat(+ 'Core',+ room => ({+ ...room,+ members: [{ connectionId: 'local', name: 'reviewer', remoteSource: true, sourceScoped: true }]+ }),+ { sync: false }+ )expect(chat.groupSpeakerLabel('local::reviewer', 'Core')).toBe('Reviewer')expect(chat.groupSpeakerLabel('local::reviewer')).toBe('Reviewer · This device')@@ -1064,7 +1090,9 @@ describe('room identity', () => {}const recreate = {- log: [{ at: 5, from: { kind: 'member', name: 'research' }, text: '@user replacement needs you', thread: 'legacy' }],+ log: [+ { at: 5, from: { kind: 'member', name: 'research' }, text: '@user replacement needs you', thread: 'legacy' }+ ],roomId: 'new-room',sessions: {},tombstone: false,@@ -1081,15 +1109,16 @@ describe('room identity', () => {const swept = chat.mergeRemoteGroupChatSnapshotIntoRooms(remote as never,- { Core: { epoch: 2, log: [], running: false, sessions: {}, tombstone: true, watermarks: {} } } as unknown as Record<- string,- GroupChat- >,+ {+ Core: { epoch: 2, log: [], running: false, sessions: {}, tombstone: true, watermarks: {} }+ } as unknown as Record<string, GroupChat>,{ deletedRooms: ['Core'] })expect(swept.Core).toBeUndefined()- expect(chat.mergeRemoteGroupChatSnapshotIntoRooms(remote as never, {}, { deletedRooms: ['Core'] }).Core).toBeUndefined()+ expect(+ chat.mergeRemoteGroupChatSnapshotIntoRooms(remote as never, {}, { deletedRooms: ['Core'] }).Core+ ).toBeUndefined()})})diff --git a/apps/desktop/src/plugins/hermes-bots/group-chat.ts b/apps/desktop/src/plugins/hermes-bots/group-chat.tsindex b8be3b3548f..df2e7c6cca3 100644--- a/apps/desktop/src/plugins/hermes-bots/group-chat.ts+++ b/apps/desktop/src/plugins/hermes-bots/group-chat.ts@@ -826,7 +826,8 @@ export function mergeRemoteGroupChatSnapshotIntoRooms(watermarks: bounded.watermarks,sessions: existing.sessions && typeof existing.sessions === 'object' ? existing.sessions : {},stranded: existing.stranded && typeof existing.stranded === 'object' ? existing.stranded : {},- externalCursors: existing.externalCursors && typeof existing.externalCursors === 'object' ? existing.externalCursors : {},+ externalCursors:+ existing.externalCursors && typeof existing.externalCursors === 'object' ? existing.externalCursors : {},members: [...members.values()],...(projectedRoomId || existing.roomId? {diff --git a/apps/desktop/src/plugins/hermes-bots/group-hold-status.test.tsx b/apps/desktop/src/plugins/hermes-bots/group-hold-status.test.tsxindex 231ca3afe75..c54a237e11b 100644--- a/apps/desktop/src/plugins/hermes-bots/group-hold-status.test.tsx+++ b/apps/desktop/src/plugins/hermes-bots/group-hold-status.test.tsx@@ -150,7 +150,9 @@ describe('durable group holds', () => {it('summarizes the most recent unresolved failure after a member fails again', async () => {const [{ GroupChatWorkspace }, chat, activity] = await Promise.all([- import('./group-chat-view'), import('./group-chat'), import('./group-activity')+ import('./group-chat-view'),+ import('./group-chat'),+ import('./group-activity')])chat.$groupChats.set({ Core: { log: [], members: MEMBERS, watermarks: {} } })diff --git a/apps/desktop/src/plugins/hermes-bots/group-membership.test.ts b/apps/desktop/src/plugins/hermes-bots/group-membership.test.tsindex a35dc2b18ee..c2eceb5a933 100644--- a/apps/desktop/src/plugins/hermes-bots/group-membership.test.ts+++ b/apps/desktop/src/plugins/hermes-bots/group-membership.test.ts@@ -405,9 +405,7 @@ describe('renamed profile descriptors (#110200)', () => {remoteSource: true}- modules.chat.$groupChats.set(- rooms({ room: { log: [], members: [{ connectionId: 'local', name: 'niezale-ny' }] } })- )+ modules.chat.$groupChats.set(rooms({ room: { log: [], members: [{ connectionId: 'local', name: 'niezale-ny' }] } }))const seated = modules.membership.groupChatMemberBots('room', [remoteTwin], {})diff --git a/apps/desktop/src/plugins/hermes-bots/group-mention-text.test.tsx b/apps/desktop/src/plugins/hermes-bots/group-mention-text.test.tsxindex 63e475739a9..1969f05af19 100644--- a/apps/desktop/src/plugins/hermes-bots/group-mention-text.test.tsx+++ b/apps/desktop/src/plugins/hermes-bots/group-mention-text.test.tsx@@ -27,7 +27,10 @@ vi.mock('@hermes/plugin-sdk', async () => {vi.mock('./shared', () => ({ getPluginCtx: () => null, ID: 'hermes-bots' }))-const members = [{ name: 'planner', handle: 'planner' }, { name: 'reviewer-mac-mini', handle: 'reviewer-mac-mini' }] as GroupMember[]+const members = [+ { name: 'planner', handle: 'planner' },+ { name: 'reviewer-mac-mini', handle: 'reviewer-mac-mini' }+] as GroupMember[]describe('group mention rendering', () => {it('classifies seated bots, the human and broadcasts, and leaves unknown tokens plain', () => {diff --git a/apps/desktop/src/plugins/hermes-bots/group-round-members.ts b/apps/desktop/src/plugins/hermes-bots/group-round-members.tsindex deb1c49344d..d5ab300f6aa 100644--- a/apps/desktop/src/plugins/hermes-bots/group-round-members.ts+++ b/apps/desktop/src/plugins/hermes-bots/group-round-members.ts@@ -113,6 +113,7 @@ function prepareGroupRoundMember(context: GroupRoundMemberContext, member: Groupconst heldSet = new Set(heldIds)const delivered = room.log.filter((entry: GroupMessage) => Boolean(entry.id && heldSet.has(entry.id)))const deliveredIds = new Set(delivered.map((entry: GroupMessage) => entry.id).filter(Boolean))+const visibleDelta = [...delivered,...delta.filter((entry: GroupMessage) => !entry.id || !deliveredIds.has(entry.id))@@ -276,12 +277,7 @@ export async function runGroupRoundMember(const spoke = reply !== null && !isGroupPassText(reply)if (reply !== null && spoke) {- appendGroupChatEntry(- context.group,- groupMemberAuthor(member),- reply,- thread- )+ appendGroupChatEntry(context.group, groupMemberAuthor(member), reply, thread)}// A member's own entries — its reply, and the rows group-external-writes.tsdiff --git a/apps/desktop/src/plugins/hermes-bots/group-round-prompt.ts b/apps/desktop/src/plugins/hermes-bots/group-round-prompt.tsindex 488d8aeb66d..fbf40db6c3d 100644--- a/apps/desktop/src/plugins/hermes-bots/group-round-prompt.ts+++ b/apps/desktop/src/plugins/hermes-bots/group-round-prompt.ts@@ -27,7 +27,8 @@ function relabelMemberControlFrames(text: string) {* profile name (legacy call sites and single-connection jobs). */export type GroupChatLineViewer =| string- | (Pick<GroupMember, 'name'> & Partial<Pick<GroupMember, 'connectionId' | 'connectionLabel' | 'installId' | 'remoteSource'>>)+ | (Pick<GroupMember, 'name'> &+ Partial<Pick<GroupMember, 'connectionId' | 'connectionLabel' | 'installId' | 'remoteSource'>>)/** Room-log line as a member sees it: `Name (user): …` / `Name: …` /* `Name (you): …`. */@@ -71,6 +72,7 @@ export function formatGroupDeltaLines(delta: GroupMessage[], viewer: GroupChatLifor (let i = delta.length - 1; i >= 0 && lines.length < GROUP_CHAT_HISTORY_LIMIT; i--) {const entry = delta[i]+const line = formatGroupChatLine({ ...entry, text: compactGroupChatSyncText(entry.text, GROUP_CHAT_HISTORY_LINE_CHARS).text },viewer,diff --git a/apps/desktop/src/plugins/hermes-bots/group-rounds.test.ts b/apps/desktop/src/plugins/hermes-bots/group-rounds.test.tsindex 06f6a2415b5..f352d84dcb7 100644--- a/apps/desktop/src/plugins/hermes-bots/group-rounds.test.ts+++ b/apps/desktop/src/plugins/hermes-bots/group-rounds.test.ts@@ -120,14 +120,23 @@ describe('routing', () => {const { rounds } = await loadRoom()const local: GroupMember = { name: 'reviewer' }- const remote: GroupMember = { connectionId: 'mini', handle: 'reviewer-mini', name: 'reviewer', remoteSource: true, sourceScoped: true }+ const remote: GroupMember = {+ connectionId: 'mini',+ handle: 'reviewer-mini',+ name: 'reviewer',+ remoteSource: true,+ sourceScoped: true+ }const members = [local, remote]for (const member of members) {const tag = rounds.groupReplyMentionTag(member, members)const parsed = rounds.parseGroupChatMentions(`@${tag} `, members)- expect([tag, [...parsed.mentioned]]).toEqual([member.remoteSource ? 'reviewer-mini' : 'reviewer-local', [member.remoteSource ? 'mini::reviewer' : 'reviewer']])+ expect([tag, [...parsed.mentioned]]).toEqual([+ member.remoteSource ? 'reviewer-mini' : 'reviewer-local',+ [member.remoteSource ? 'mini::reviewer' : 'reviewer']+ ])}// Unambiguous members keep the friendly tag the autocomplete inserts.@@ -251,7 +260,12 @@ describe('routing', () => {expect(formatGroupChatLine(reply as GroupMessage, local)).toContain('(you)')// The same entry seen by the other machine's `default` is somebody else.expect(- formatGroupChatLine(reply as GroupMessage, { connectionId: 'mbp', connectionLabel: 'MBP', name: 'default', remoteSource: true })+ formatGroupChatLine(reply as GroupMessage, {+ connectionId: 'mbp',+ connectionLabel: 'MBP',+ name: 'default',+ remoteSource: true+ })).not.toContain('(you)')})@@ -260,7 +274,13 @@ describe('routing', () => {it('matches self on the gateway install_id when Desktops label the connection differently', async () => {const room = await loadRoom({ turn: () => 'Central here.' })const { formatGroupChatLine } = await import('./group-round-prompt')- const local: GroupMember = { connectionId: 'central', connectionLabel: 'Central', installId: 'gw-1', name: 'default', title: '' }+ const local: GroupMember = {+ connectionId: 'central',+ connectionLabel: 'Central',+ installId: 'gw-1',+ name: 'default',+ title: ''+ }room.rounds.sendToGroupChat('Core', [local], '@hermes status?')await settle(room, 'Core')@@ -270,11 +290,23 @@ describe('routing', () => {expect(reply.from).toEqual({ kind: 'member', name: 'default', source: 'Central', gateway: 'gw-1' })// The other Desktop's view of the SAME gateway under its own label.expect(- formatGroupChatLine(reply, { connectionId: 'c9', connectionLabel: 'Studio', installId: 'gw-1', name: 'default', remoteSource: true })+ formatGroupChatLine(reply, {+ connectionId: 'c9',+ connectionLabel: 'Studio',+ installId: 'gw-1',+ name: 'default',+ remoteSource: true+ })).toContain('(you)')// …and a different gateway that happens to share the label is not self.expect(- formatGroupChatLine(reply, { connectionId: 'c2', connectionLabel: 'Central', installId: 'gw-2', name: 'default', remoteSource: true })+ formatGroupChatLine(reply, {+ connectionId: 'c2',+ connectionLabel: 'Central',+ installId: 'gw-2',+ name: 'default',+ remoteSource: true+ })).not.toContain('(you)')})})@@ -359,22 +391,30 @@ describe('round lifecycle', () => {})it('does not retry ambiguous member admission in later rounds or continuations', async () => {- const room = await loadRoom({ turn: ({ profile }) => {- if (profile === 'builder') { throw new Error('Ambiguous admission failure') }+ const room = await loadRoom({+ turn: ({ profile }) => {+ if (profile === 'builder') {+ throw new Error('Ambiguous admission failure')+ }- return '@builder please investigate'- } })+ return '@builder please investigate'+ }+ })room.rounds.sendToGroupChat('Failure', MEMBERS.slice(0, 2), '@research start')await settle(room, 'Failure')expect(room.gateway.calls.filter(call => call.profile === 'builder')).toHaveLength(1)- expect(Object.keys(room.chat.$groupChats.get().Failure.watermarks).some(key => key.endsWith('::builder'))).toBe(false)+ expect(Object.keys(room.chat.$groupChats.get().Failure.watermarks).some(key => key.endsWith('::builder'))).toBe(+ false+ )})it('does not retry an ambiguous submit from prequeued same-thread or cross-thread sends', async () => {let reject!: (error: Error) => void- const held = new Promise<string>((_resolve, fail) => { reject = fail })- const room = await loadRoom({ turn: ({ n }) => n === 1 ? held : '(pass)' })+ const held = new Promise<string>((_resolve, fail) => {+ reject = fail+ })+ const room = await loadRoom({ turn: ({ n }) => (n === 1 ? held : '(pass)') })const members = [MEMBERS[0]]const thread = room.rounds.sendToGroupChat('Failure', members, 'first')!await drain(() => room.gateway.calls.length < 1)@@ -394,7 +434,9 @@ describe('round lifecycle', () => {it('attributes a queued drive failure to the thread whose harvest failed', async () => {let finish!: (reply: string) => void- const held = new Promise<string>(resolve => { finish = resolve })+ const held = new Promise<string>(resolve => {+ finish = resolve+ })const room = await loadRoom({ turn: () => held })const first = room.rounds.sendToGroupChat('Failure', MEMBERS.slice(0, 2), '@research first')!await drain(() => room.gateway.calls.length < 1)@@ -411,7 +453,8 @@ describe('round lifecycle', () => {}room.chat.updateGroupChat('Failure', state => ({- ...state, stranded: { builder: { before: 0, thread: first } }+ ...state,+ stranded: { builder: { before: 0, thread: first } }}))finish('(pass)')await drain(() => !room.activity.currentGroupActivity('Failure').some(event => event.kind === 'failed'))@@ -486,8 +529,10 @@ describe('round lifecycle', () => {describe('per-member delta', () => {it('retained-log trimming cannot acknowledge messages appended during inference', async () => {let release!: (reply: string) => void- const held = new Promise<string>(resolve => { release = resolve })- const room = await loadRoom({ turn: ({ n }) => n === 1 ? held : '(pass)' })+ const held = new Promise<string>(resolve => {+ release = resolve+ })+ const room = await loadRoom({ turn: ({ n }) => (n === 1 ? held : '(pass)') })const members = [MEMBERS[0]]const thread = room.rounds.sendToGroupChat('Trim', members, 'delivered')!await drain(() => room.gateway.calls.length < 1)@@ -1078,7 +1123,11 @@ describe('member holds (#93129)', () => {it('treats a stop word far from every mention as prose, not a directive', async () => {const { rounds } = await loadRoom()- for (const text of ['@impl go, das ist halt ein Test', '@impl mach mal Pause', 'stop the presses, @impl what do you think?']) {+ for (const text of [+ '@impl go, das ist halt ein Test',+ '@impl mach mal Pause',+ 'stop the presses, @impl what do you think?'+ ]) {const action = rounds.classifyGroupHoldDirective(text, ['conn::impl'], false)expect([...action.hold]).toEqual([])@@ -1087,7 +1136,9 @@ describe('member holds (#93129)', () => {}// Keys are roster keys, not handles: proximity must still hold on the raw @token.- expect([...rounds.classifyGroupHoldDirective('@impl please halt', ['conn::impl'], false).hold]).toEqual(['conn::impl'])+ expect([...rounds.classifyGroupHoldDirective('@impl please halt', ['conn::impl'], false).hold]).toEqual([+ 'conn::impl'+ ])})// #117040: proximity is measured on what the user directs at the room, not@@ -1134,7 +1185,12 @@ describe('member holds (#93129)', () => {it('never releases the addressed member on a distant genuine stop', async () => {const { rounds } = await loadRoom()- for (const text of ['@impl please just stop now', 'hey @impl could you stop', '@impl, I need you to stop', '@impl you can stop']) {+ for (const text of [+ '@impl please just stop now',+ 'hey @impl could you stop',+ '@impl, I need you to stop',+ '@impl you can stop'+ ]) {const action = rounds.classifyGroupHoldDirective(text, ['c1::impl'], false)expect([...action.release]).toEqual([])@@ -1150,8 +1206,12 @@ describe('member holds (#93129)', () => {const { rounds } = await loadRoom()const held = { docs: { at: 2 }, impl: { at: 1 } }- expect(rounds.applyGroupHoldDirective(held, { everyone: true, mentioned: [] }, '@all tell me a joke each', {})).toEqual({})- expect(rounds.applyGroupHoldDirective(held, { everyone: true, mentioned: [] }, '@all stop', { at: 5 }, ['impl', 'docs'])).not.toEqual({})+ expect(+ rounds.applyGroupHoldDirective(held, { everyone: true, mentioned: [] }, '@all tell me a joke each', {})+ ).toEqual({})+ expect(+ rounds.applyGroupHoldDirective(held, { everyone: true, mentioned: [] }, '@all stop', { at: 5 }, ['impl', 'docs'])+ ).not.toEqual({})// An unaddressed message still leaves the holds alone.expect(rounds.applyGroupHoldDirective(held, { everyone: false, mentioned: [] }, 'anyone there?', {})).toBe(held)})@@ -1422,9 +1482,11 @@ describe('stopGroupThread (#91868/#94569)', () => {it('cancels an in-flight completion after Stop when sticky holds are disabled', async () => {let finish!: (reply: string) => void+const pendingReply = new Promise<string>(resolve => {finish = resolve})+const room = await loadRoom({ turn: () => pendingReply })const member = [{ name: 'helper', title: '' }]diff --git a/apps/desktop/src/plugins/hermes-bots/group-rounds.ts b/apps/desktop/src/plugins/hermes-bots/group-rounds.tsindex f4ebda5a098..7ce4b13ec9f 100644--- a/apps/desktop/src/plugins/hermes-bots/group-rounds.ts+++ b/apps/desktop/src/plugins/hermes-bots/group-rounds.ts@@ -324,7 +324,10 @@ function maskQuotedAndCodeSpans(value: string): string {* halt" = 2, "@x go, das ist halt ein Test" = 4); widen only with measured* cases, never by guessing. */function stopWordPlacement(value: string): 'adjacent' | 'distant' | null {- const tokens = maskQuotedAndCodeSpans(value).toLowerCase().match(/@[\p{L}\p{N}._-]+|[\p{L}\p{N}_-]+/gu) || []+ const tokens =+ maskQuotedAndCodeSpans(value)+ .toLowerCase()+ .match(/@[\p{L}\p{N}._-]+|[\p{L}\p{N}_-]+/gu) || []const mentionAt: number[] = []const stopAt: number[] = []@@ -567,7 +570,12 @@ export async function stopGroupThread(group: string, thread: null | string, memb* epoch and discards queued continuations.* Watermarks are per thread+member (`${thread}::${memberKey}`), so parallel* topics never eat each other's deltas. */-export async function runGroupChatRounds(group: string, members: GroupMember[], thread: string, failedMembers = new Set<string>()) {+export async function runGroupChatRounds(+ group: string,+ members: GroupMember[],+ thread: string,+ failedMembers = new Set<string>()+) {const binding = followGroupChat(group, name => {group = name})@@ -944,7 +952,12 @@ function queueGroupChatDrive(group: string, members: GroupMember[], thread: stri} catch (error) {if (binding.isLive()) {const reason = groupFailureReason(error)- recordGroupActivity(group, { kind: 'failed', member: null, thread: currentThread, ...(reason ? { reason } : {}) })+ recordGroupActivity(group, {+ kind: 'failed',+ member: null,+ thread: currentThread,+ ...(reason ? { reason } : {})+ })updateGroupChat(group, room => ({ ...room, running: false, turn: null }))}} finally {diff --git a/apps/desktop/src/plugins/hermes-bots/group-turns.test.ts b/apps/desktop/src/plugins/hermes-bots/group-turns.test.tsindex 54f5e9992ad..e7307366a5c 100644--- a/apps/desktop/src/plugins/hermes-bots/group-turns.test.ts+++ b/apps/desktop/src/plugins/hermes-bots/group-turns.test.ts@@ -1086,7 +1086,7 @@ describe('in-flight marker', () => {expect(room.chat.$groupChats.get().Room?.stranded?.helper).toBeUndefined()})- it('harvests a remote member\'s turn that a previous Desktop process left in flight', async () => {+ it("harvests a remote member's turn that a previous Desktop process left in flight", async () => {const room = await loadRoom()const { groupSessionKey } = await import('./group-membership')@@ -1136,9 +1136,7 @@ describe('stranded harvest', () => {const activity = await import('./group-activity')try {- expect(await room.turns.runGroupChatMemberTurn('Room', LOCAL_MEMBER, 'deploy', 't1', [])).toBe(- 'long deploy done'- )+ expect(await room.turns.runGroupChatMemberTurn('Room', LOCAL_MEMBER, 'deploy', 't1', [])).toBe('long deploy done')expect(room.chat.$groupChats.get().Room?.stranded?.helper).toBeUndefined()expect(activity.$groupActivity.get().Room?.events.map(event => event.kind)).not.toContain('timed-out')} finally {@@ -1256,7 +1254,9 @@ describe('stranded harvest', () => {await room.turns.harvestStrandedGroupReply('Dead', member)expect(room.chat.$groupChats.get().Dead.stranded?.[key]).toBeUndefined()- expect(activity.$groupActivity.get().Dead?.events.map(event => [event.kind, event.member])).toEqual([['failed', key]])+ expect(activity.$groupActivity.get().Dead?.events.map(event => [event.kind, event.member])).toEqual([+ ['failed', key]+ ])})it('never re-submits into a member the harvest just confirmed is still running', async () => {diff --git a/apps/desktop/src/plugins/hermes-bots/group-turns.ts b/apps/desktop/src/plugins/hermes-bots/group-turns.tsindex 229ef043847..649facf3550 100644--- a/apps/desktop/src/plugins/hermes-bots/group-turns.ts+++ b/apps/desktop/src/plugins/hermes-bots/group-turns.ts@@ -94,7 +94,8 @@ function pickGroupTurnReply(messages: GroupTurnTranscriptMessage[], before: numb* passes in range → the last pass; no anchor row → scan from `before`. */function pickStrandedGroupTurnReply(messages: GroupTurnTranscriptMessage[], before: number): null | string {const anchor = messages.findIndex(- (msg, i) => i >= before && msg?.role === 'user' && groupTranscriptRowText(msg).startsWith(GROUP_PROMPT_HEADER_PREFIX)+ (msg, i) =>+ i >= before && msg?.role === 'user' && groupTranscriptRowText(msg).startsWith(GROUP_PROMPT_HEADER_PREFIX))let passText: null | string = null@@ -922,7 +923,11 @@ export function strandedMarkerIsLive(marker: unknown): boolean {* member's gateway (a remote member's most of all: its gateway outlives this Desktop), and only* a persisted marker lets the next boundary harvest the finished reply instead of dropping it* and re-driving a live session. */-function markGroupTurnInFlight(group: string, member: GroupMember, marker: { before: number; thread: string; turn: string }) {+function markGroupTurnInFlight(+ group: string,+ member: GroupMember,+ marker: { before: number; thread: string; turn: string }+) {updateGroupChat(group, (r: GroupChatRoom) => {r.stranded = {...(r.stranded || {}),@@ -1313,12 +1318,7 @@ export async function harvestStrandedGroupReply(group: string, member: GroupMembmember: groupMemberKey(member),thread: strandedThread})- appendGroupChatEntry(- group,- groupMemberAuthor(member),- reply,- strandedThread- )+ appendGroupChatEntry(group, groupMemberAuthor(member), reply, strandedThread)updateGroupChat(group, (r: GroupChatRoom) => {const markKey = `${strandedThread}::${memberKey}`diff --git a/apps/desktop/src/plugins/hermes-bots/hide-bot-chats.test.ts b/apps/desktop/src/plugins/hermes-bots/hide-bot-chats.test.tsindex 313cc0c63fa..ffe45119b7d 100644--- a/apps/desktop/src/plugins/hermes-bots/hide-bot-chats.test.ts+++ b/apps/desktop/src/plugins/hermes-bots/hide-bot-chats.test.ts@@ -206,9 +206,7 @@ describe('the id half: group room member sessions', () => {}}lastRoster.value = [{ name: 'alpha' } as RosterRow]- hostMock.setPersistedSessionHidden.mockRejectedValue(- new Error('404: {"detail":"Session not found"}')- )+ hostMock.setPersistedSessionHidden.mockRejectedValue(new Error('404: {"detail":"Session not found"}'))await runSweep()diff --git a/apps/desktop/src/plugins/hermes-bots/i18n.ts b/apps/desktop/src/plugins/hermes-bots/i18n.tsindex b37afdc32b0..b6ca1513495 100644--- a/apps/desktop/src/plugins/hermes-bots/i18n.ts+++ b/apps/desktop/src/plugins/hermes-bots/i18n.ts@@ -453,7 +453,8 @@ const en: BotsMessages = {holdDetection: 'Detect stop directives',holdDetectionHint: 'Let room messages put addressed members on hold until they are mentioned again.',compressHistory: 'Compress history',- compressHistoryHint: (member: string) => `Compress ${member}'s hidden room history so the member stops failing with empty replies`,+ compressHistoryHint: (member: string) =>+ `Compress ${member}'s hidden room history so the member stops failing with empty replies`,compressing: (member: string) => `Compressing ${member}'s room history…`,compressDone: (member: string, compressed: number, detail: string) =>`Compressed ${compressed} room session${compressed === 1 ? '' : 's'} for ${member}${detail ? ` — ${detail}` : ''}`,@@ -486,7 +487,8 @@ const en: BotsMessages = {heldMembersStatus: members => `Paused: ${members}`,holdReleaseHint: 'Mention a paused bot or send @all resume to release them.',needsYourInput: 'A bot in this group chat needs your input',- noMembersToSend: group => `${group} has no members to send to — add a bot, or reopen the room if members are still loading.`,+ noMembersToSend: group =>+ `${group} has no members to send to — add a bot, or reopen the room if members are still loading.`,pictureGenerationFailed: 'Group picture generation failed',nameTaken: name => `A group named “${name}” already exists.`,memberCount: count => `${count} bots`,@@ -710,7 +712,8 @@ const ja: BotsMessages = {holdDetection: '停止指示を検出',holdDetectionHint: 'ルームのメッセージで、再びメンションされるまで対象メンバーを保留にします。',compressHistory: '履歴を圧縮',- compressHistoryHint: (member: string) => `${member} の非表示のルーム履歴を圧縮し、空の応答で失敗しなくなるようにします`,+ compressHistoryHint: (member: string) =>+ `${member} の非表示のルーム履歴を圧縮し、空の応答で失敗しなくなるようにします`,compressing: (member: string) => `${member} のルーム履歴を圧縮中…`,compressDone: (member: string, compressed: number, detail: string) =>`${member} のルームセッション ${compressed} 件を圧縮しました${detail ? ` — ${detail}` : ''}`,@@ -743,7 +746,8 @@ const ja: BotsMessages = {heldMembersStatus: members => `一時停止中: ${members}`,holdReleaseHint: '一時停止中のボットにメンションするか、@all resume を送信して再開します。',needsYourInput: 'このグループチャットのボットが入力を待っています',- noMembersToSend: group => `${group} に送信先のメンバーがいません。ボットを追加するか、メンバーの読み込み中であればルームを開き直してください。`,+ noMembersToSend: group =>+ `${group} に送信先のメンバーがいません。ボットを追加するか、メンバーの読み込み中であればルームを開き直してください。`,pictureGenerationFailed: 'グループ画像の生成に失敗しました',nameTaken: name => `「${name}」という名前のグループはすでに存在します。`,memberCount: count => `ボット${count}体`,diff --git a/apps/desktop/src/plugins/hermes-bots/plugin-panes.test.tsx b/apps/desktop/src/plugins/hermes-bots/plugin-panes.test.tsxindex 4d4c216bf10..14921547f2f 100644--- a/apps/desktop/src/plugins/hermes-bots/plugin-panes.test.tsx+++ b/apps/desktop/src/plugins/hermes-bots/plugin-panes.test.tsx@@ -197,6 +197,7 @@ describe('the Bots pane dock', () => {plugin.register(harness.ctx)const tabTitle = harness.find('pane')!.data!.tabTitle as () => ReactNode+const inLocale = (locale: string) =>renderToStaticMarkup(<I18nProvider configClient={null} initialLocale={locale}>diff --git a/apps/desktop/src/plugins/hermes-bots/plugin.mentions.test.ts b/apps/desktop/src/plugins/hermes-bots/plugin.mentions.test.tsindex c6456fa2767..9d75423936c 100644--- a/apps/desktop/src/plugins/hermes-bots/plugin.mentions.test.ts+++ b/apps/desktop/src/plugins/hermes-bots/plugin.mentions.test.ts@@ -68,10 +68,12 @@ const { cache, hostMock, live } = vi.hoisted(() => {notify: vi.fn(),request: vi.fn(async () => ({})),requestProfile: vi.fn(async () => ({})),- agents: vi.fn(async (): Promise<{ agents: Array<Record<string, unknown>>; sources: Array<Record<string, unknown>> }> => ({- agents: [],- sources: []- })),+ agents: vi.fn(+ async (): Promise<{ agents: Array<Record<string, unknown>>; sources: Array<Record<string, unknown>> }> => ({+ agents: [],+ sources: []+ })+ ),state: {connectionId: { get: () => 'local', listen: () => () => undefined },focusedSessionProfile: { get: () => live.focused, listen: () => () => undefined },@@ -330,26 +332,32 @@ describe('@-mention completions', () => {it.each([{ label: 'local first', profiles: [{ name: 'default' }, { name: 'researcher' }, ...REMOTE_DEFAULTS] },- { label: 'remotes first', profiles: [...REMOTE_DEFAULTS].reverse().concat([{ name: 'researcher' }, { name: 'default' }]) }- ])('lists titled remote defaults under their slug, qualified on collision, and keeps @hermes local ($label)', async ({ profiles }) => {- const { handler, provide } = await contributions({ focused: 'researcher', profiles })- const inserts = provide('').map(item => item.insert)-- // Both remote defaults tag as "CoS Bot" — the bare slug names neither, so- // the picker pins each to its connection; the local default stays @hermes.- expect(inserts).toEqual(expect.arrayContaining(['@hermes', '@cos-bot@vps', '@cos-bot@wsl']))- expect(inserts).not.toContain('@cos-bot')- expect(inserts.filter(insert => insert === '@hermes')).toHaveLength(1)-- const qualified = await handler({ text: 'ask @cos-bot@wsl for the plan' })- expect(qualified.text).toMatch(/message_agent target: "default@wsl"/)- expect(qualified.text).not.toMatch(/default@vps/)-- // A bare @hermes is this machine's default in either roster order.- const local = await handler({ text: '@hermes summarize' })- expect(local.text).toMatch(/@hermes = agent profile "default"/)- expect(local.text).not.toMatch(/message_agent target: "default@/)- })+ {+ label: 'remotes first',+ profiles: [...REMOTE_DEFAULTS].reverse().concat([{ name: 'researcher' }, { name: 'default' }])+ }+ ])(+ 'lists titled remote defaults under their slug, qualified on collision, and keeps @hermes local ($label)',+ async ({ profiles }) => {+ const { handler, provide } = await contributions({ focused: 'researcher', profiles })+ const inserts = provide('').map(item => item.insert)++ // Both remote defaults tag as "CoS Bot" — the bare slug names neither, so+ // the picker pins each to its connection; the local default stays @hermes.+ expect(inserts).toEqual(expect.arrayContaining(['@hermes', '@cos-bot@vps', '@cos-bot@wsl']))+ expect(inserts).not.toContain('@cos-bot')+ expect(inserts.filter(insert => insert === '@hermes')).toHaveLength(1)++ const qualified = await handler({ text: 'ask @cos-bot@wsl for the plan' })+ expect(qualified.text).toMatch(/message_agent target: "default@wsl"/)+ expect(qualified.text).not.toMatch(/default@vps/)++ // A bare @hermes is this machine's default in either roster order.+ const local = await handler({ text: '@hermes summarize' })+ expect(local.text).toMatch(/@hermes = agent profile "default"/)+ expect(local.text).not.toMatch(/message_agent target: "default@/)+ }+ )it('offers a uniquely titled remote default under its title slug', async () => {const { handler, provide } = await contributions({ profiles: [{ name: 'default' }, REMOTE_DEFAULTS[0]] })@@ -464,7 +472,13 @@ describe('the mention middleware', () => {hostMock.requestProfile.mockResolvedValueOnce({ profiles: [{ name: 'default' }] })hostMock.agents.mockResolvedValueOnce({agents: [- { connectionId: 'local', connectionKind: 'local', connectionLabel: 'This device', handle: 'default-this-device', profile: 'default' },+ {+ connectionId: 'local',+ connectionKind: 'local',+ connectionLabel: 'This device',+ handle: 'default-this-device',+ profile: 'default'+ },{connectionId: 'vps',connectionKind: 'remote',@@ -474,7 +488,10 @@ describe('the mention middleware', () => {profileMetadata: { ui_meta: { 'hermes-bots': { title: 'CoS Bot' } } }}],- sources: [{ connectionId: 'local', kind: 'local' }, { connectionId: 'vps', kind: 'remote' }]+ sources: [+ { connectionId: 'local', kind: 'local' },+ { connectionId: 'vps', kind: 'remote' }+ ]})const { handler, provide } = await contributions({ profiles: null })diff --git a/apps/desktop/src/plugins/hermes-bots/plugin.tsx b/apps/desktop/src/plugins/hermes-bots/plugin.tsxindex cec731be6f4..38e54faa782 100644--- a/apps/desktop/src/plugins/hermes-bots/plugin.tsx+++ b/apps/desktop/src/plugins/hermes-bots/plugin.tsx@@ -15,7 +15,14 @@* bot-initiated sends use `hermes -p <bot> chat --in ~ -c "Bot Chat"`.*/-import { CHAT_EMPTY_AREA, COMPOSER_AREAS, host, LocalizedTabTitle, PALETTE_AREA, translateNow } from '@hermes/plugin-sdk'+import {+ CHAT_EMPTY_AREA,+ COMPOSER_AREAS,+ host,+ LocalizedTabTitle,+ PALETTE_AREA,+ translateNow+} from '@hermes/plugin-sdk'import type { ChatEmptyProps, PluginContext } from '@hermes/plugin-sdk'import { startFaceClock, stopFaceClock } from './avatar'@@ -269,7 +276,8 @@ export default {// guard as the other maps — a held bot stays held across// window restarts until explicitly released.holds: room.holds && typeof room.holds === 'object' ? room.holds : {},- externalCursors: room.externalCursors && typeof room.externalCursors === 'object' ? room.externalCursors : {},+ externalCursors:+ room.externalCursors && typeof room.externalCursors === 'object' ? room.externalCursors : {},members: Array.isArray(room.members) ? room.members : [],roomId: typeof room.roomId === 'string' && room.roomId ? room.roomId : null,image: typeof room.image === 'string' && room.image ? room.image : null,diff --git a/apps/desktop/src/plugins/hermes-bots/relay.test.ts b/apps/desktop/src/plugins/hermes-bots/relay.test.tsindex 98c7f582024..1a29bd78c2c 100644--- a/apps/desktop/src/plugins/hermes-bots/relay.test.ts+++ b/apps/desktop/src/plugins/hermes-bots/relay.test.ts@@ -845,9 +845,7 @@ describe('the roster loop forgets a machine that left', () => {hostMock.profileRoutes = vi.fn(async () => [route('c')])await vi.advanceTimersByTimeAsync(60_000)- expect(calls.filter(call => call.method === 'bot_relay.roster.sync').map(call => call.connectionId)).toEqual([- 'c'- ])+ expect(calls.filter(call => call.method === 'bot_relay.roster.sync').map(call => call.connectionId)).toEqual(['c'])stopBotRelay()})@@ -860,7 +858,12 @@ describe('the drain loop does not let one delivery hold every other gateway’s// and the sender's waiter is finite.type RelayEnvelopeFixture = { id: string; message: string; target_connection: string; target_profile: string }const toB: RelayEnvelopeFixture = { id: 'env-1', message: 'long job', target_connection: 'b', target_profile: 'ops' }- const toA: RelayEnvelopeFixture = { id: 'env-2', message: 'quick one', target_connection: 'a', target_profile: 'default' }+ const toA: RelayEnvelopeFixture = {+ id: 'env-2',+ message: 'quick one',+ target_connection: 'a',+ target_profile: 'default'+ }it('claims every outbox first and delivers to different targets concurrently', async () => {let releaseB!: (value: { reply: string }) => voiddiff --git a/apps/desktop/src/plugins/hermes-bots/roster-actions.test.ts b/apps/desktop/src/plugins/hermes-bots/roster-actions.test.tsindex 7a23a8ad973..f8e6d49cc65 100644--- a/apps/desktop/src/plugins/hermes-bots/roster-actions.test.ts+++ b/apps/desktop/src/plugins/hermes-bots/roster-actions.test.ts@@ -156,7 +156,9 @@ describe('new activity after the seed', () => {// but the preview is identical — must not produce a second toast.trackInboundActivity([chatting('researcher', 7000, 'same message')])- const toasts = hostMock.notify.mock.calls.filter((c) => c[0].title.includes('has new activity') || c[0].title.includes('New message for'))+ const toasts = hostMock.notify.mock.calls.filter(+ c => c[0].title.includes('has new activity') || c[0].title.includes('New message for')+ )expect(toasts.length).toBe(1)})@@ -168,7 +170,9 @@ describe('new activity after the seed', () => {trackInboundActivity([chatting('researcher', 6000, 'first message')])trackInboundActivity([chatting('researcher', 7000, 'second message')])- const toasts = hostMock.notify.mock.calls.filter((c) => c[0].title.includes('has new activity') || c[0].title.includes('New message for'))+ const toasts = hostMock.notify.mock.calls.filter(+ c => c[0].title.includes('has new activity') || c[0].title.includes('New message for')+ )expect(toasts.length).toBe(2)})diff --git a/apps/desktop/src/plugins/hermes-bots/roster-pane-toolbar.tsx b/apps/desktop/src/plugins/hermes-bots/roster-pane-toolbar.tsxindex 66f31de5edd..4f019c45817 100644--- a/apps/desktop/src/plugins/hermes-bots/roster-pane-toolbar.tsx+++ b/apps/desktop/src/plugins/hermes-bots/roster-pane-toolbar.tsx@@ -106,7 +106,10 @@ export function renderRosterToolbar({</DropdownMenuItem>{/* Same selectable set as CreateGroupChatDialog: one local bot plus aremote-connection bot is a valid room (#101543). */}- <DropdownMenuItem disabled={roster.filter(bot => !bot?.ghost).length < 2} onSelect={() => setGroupCreateOpen(true)}>+ <DropdownMenuItem+ disabled={roster.filter(bot => !bot?.ghost).length < 2}+ onSelect={() => setGroupCreateOpen(true)}+ ><Codicon className="mr-1.5" name="organization" />{b.group.newTitle}</DropdownMenuItem>diff --git a/apps/desktop/src/plugins/hermes-bots/roster-pane.tsx b/apps/desktop/src/plugins/hermes-bots/roster-pane.tsxindex 842dcdf227f..10c6f2dba2b 100644--- a/apps/desktop/src/plugins/hermes-bots/roster-pane.tsx+++ b/apps/desktop/src/plugins/hermes-bots/roster-pane.tsx@@ -51,7 +51,13 @@ import { botNeedsHandleLabel, rosterGatewayOptions } from './roster-sections'import { botWorkspaceOwnerKey, setBotsWorkspaceOwner } from './routing'import { activeBots, useTurnBusy } from './row-helpers'import type { BotMeta, GatewaySource, GroupMember, RosterActivityFilter, RosterKindFilter, RosterRow } from './types'-import { $botSections, $draggingBot, adoptBotSectionsFromMeta, backfillBotSectionNames, type SectionDialogState } from './user-sections'+import {+ $botSections,+ $draggingBot,+ adoptBotSectionsFromMeta,+ backfillBotSectionNames,+ type SectionDialogState+} from './user-sections'import { useEscapeCancelsBotDrag } from './user-sections-ui'// ── roster pane ──────────────────────────────────────────────────────────────diff --git a/apps/desktop/src/plugins/hermes-bots/routing.test.ts b/apps/desktop/src/plugins/hermes-bots/routing.test.tsindex cf054fce74a..47adfffeab3 100644--- a/apps/desktop/src/plugins/hermes-bots/routing.test.ts+++ b/apps/desktop/src/plugins/hermes-bots/routing.test.ts@@ -316,6 +316,7 @@ describe('requestForBot rides the bot’s own source', () => {describe('group transcript speaker meta (#96432)', () => {const localDefault = { name: 'default' } as RosterRow+const remoteDefault = {name: 'default',connectionId: 'spark',@@ -323,13 +324,16 @@ describe('group transcript speaker meta (#96432)', () => {remoteSource: true,sourceScoped: true} as RosterRow+const allMeta = {default: { title: 'Local Default', image: 'local.png' },'spark::default': { title: 'Remote Default', image: 'remote.png' }}it('gives user lines no bot meta', () => {- expect(groupTranscriptSpeakerMeta({ from: { kind: 'user', name: 'You' } }, [localDefault, remoteDefault], allMeta)).toBeNull()+ expect(+ groupTranscriptSpeakerMeta({ from: { kind: 'user', name: 'You' } }, [localDefault, remoteDefault], allMeta)+ ).toBeNull()})it('keeps local meta for a local same-name speaker', () => {diff --git a/apps/desktop/src/plugins/hermes-bots/user-sections-ui.test.tsx b/apps/desktop/src/plugins/hermes-bots/user-sections-ui.test.tsxindex c271bcbdc30..9c5b3fad7c2 100644--- a/apps/desktop/src/plugins/hermes-bots/user-sections-ui.test.tsx+++ b/apps/desktop/src/plugins/hermes-bots/user-sections-ui.test.tsx@@ -40,15 +40,7 @@ afterEach(() => {describe('SectionNameDialog Enter handling', () => {function mount() {const onSubmit = vi.fn()- render(- <SectionNameDialog- initialName=""- mode="create"- onOpenChange={() => undefined}- onSubmit={onSubmit}- open- />- )+ render(<SectionNameDialog initialName="" mode="create" onOpenChange={() => undefined} onSubmit={onSubmit} open />)return { input: screen.getByRole('textbox'), onSubmit }}diff --git a/apps/desktop/src/plugins/hermes-bots/user-sections.groups.test.ts b/apps/desktop/src/plugins/hermes-bots/user-sections.groups.test.tsindex 52ac2c76851..94a026f7810 100644--- a/apps/desktop/src/plugins/hermes-bots/user-sections.groups.test.ts+++ b/apps/desktop/src/plugins/hermes-bots/user-sections.groups.test.ts@@ -34,7 +34,8 @@ vi.mock('./data', async () => {return {$botMeta,$lastRoster,- botRosterKey: (bot: { connectionId?: string; name?: string }) => `${bot?.connectionId || 'legacy'}::${bot?.name || 'default'}`,+ botRosterKey: (bot: { connectionId?: string; name?: string }) =>+ `${bot?.connectionId || 'legacy'}::${bot?.name || 'default'}`,saveBotMeta}})@@ -97,7 +98,9 @@ describe('user sections — group chats', () => {// Unfiling clears the assignment on the room and persists the clear.moveGroupChatsToSection(['Team Chat'], null)expect(groupChatSectionId('Team Chat', $groupChats.get())).toBeNull()- expect((storage.get('group-chats') as Record<string, { sectionId?: null | string }>)['Team Chat']?.sectionId).toBeNull()+ expect(+ (storage.get('group-chats') as Record<string, { sectionId?: null | string }>)['Team Chat']?.sectionId+ ).toBeNull()})it('grouping seats group rows per their room record section; unfiled or dangling groups fall to Unassigned', () => {diff --git a/apps/desktop/src/plugins/hermes-bots/user-sections.test.ts b/apps/desktop/src/plugins/hermes-bots/user-sections.test.tsindex 68e2680bb2c..f851a481444 100644--- a/apps/desktop/src/plugins/hermes-bots/user-sections.test.ts+++ b/apps/desktop/src/plugins/hermes-bots/user-sections.test.ts@@ -156,14 +156,18 @@ describe('user sections', () => {// local, the members carry only the id. Another desktop cannot rebuild// the section from that — so stamp the name here, once per member.$botSections.set([{ id: 'sec-clients', name: 'Clients' }])+const meta = {nanox: { sectionId: 'sec-clients' },scout: { sectionId: 'sec-clients', sectionName: 'Clients' }, // already stampedghost: { sectionId: 'sec-unknown' } // nobody here knows that section: nothing to stamp}+$botMeta.set(meta)- expect(backfillBotSectionNames([bot('nanox'), bot('scout'), bot('ghost')], meta).map(b => b.name)).toEqual(['nanox'])+ expect(backfillBotSectionNames([bot('nanox'), bot('scout'), bot('ghost')], meta).map(b => b.name)).toEqual([+ 'nanox'+ ])await vi.waitFor(() => expect(saveBotMeta).toHaveBeenCalledTimes(1))expect(saveBotMeta).toHaveBeenCalledWith(bot('nanox'), { sectionId: 'sec-clients', sectionName: 'Clients' })diff --git a/apps/desktop/src/plugins/hermes-bots/user-sections.ts b/apps/desktop/src/plugins/hermes-bots/user-sections.tsindex a547b7467a2..28f119163c1 100644--- a/apps/desktop/src/plugins/hermes-bots/user-sections.ts+++ b/apps/desktop/src/plugins/hermes-bots/user-sections.ts@@ -32,9 +32,7 @@ import type { BotMeta, GroupChat, RosterRow } from './types'/** The one section-name dialog's state: New section (optionally filing the* bot or group whose menu opened it) or Rename. */export type SectionDialogState =- | null- | { bot?: RosterRow; group?: string; mode: 'create' }- | { id: string; mode: 'rename'; name: string }+ null | { bot?: RosterRow; group?: string; mode: 'create' } | { id: string; mode: 'rename'; name: string }export const UNASSIGNED_SECTION_KEY = 'section:unassigned'export const BOT_SECTIONS_KEY = 'bot-sections-v1'@@ -356,7 +354,7 @@ export function groupRowsBySection<TRow extends { bot?: RosterRow } | RosterRow>const id = group? groupChatSectionId(String((group as { name?: string }).name || ''), groupRooms)- : botSectionId((((row as { bot?: RosterRow })?.bot || row) as RosterRow), metaByName)+ : botSectionId(((row as { bot?: RosterRow })?.bot || row) as RosterRow, metaByName)if (id && known.has(id)) {byId.get(id)!.push(row)diff --git a/apps/desktop/src/store/connection-request.test.ts b/apps/desktop/src/store/connection-request.test.tsindex d611eca9b1c..f4b0d8adf2a 100644--- a/apps/desktop/src/store/connection-request.test.ts+++ b/apps/desktop/src/store/connection-request.test.ts@@ -56,10 +56,7 @@ type Frame = Parameters<typeof applyConnectionUpdate>[1]let nextSeq = WIRE.seq + 1/** Every `connection.update` frame carries the operation snapshot; `states` overrides per-target state. */-function frame(- states: Record<string, Snapshot['targets'][number]['state']>,- extra: Partial<Frame> = {}-): Frame {+function frame(states: Record<string, Snapshot['targets'][number]['state']>, extra: Partial<Frame> = {}): Frame {return {deadline_at: WIRE.deadline_at,op_id: 'op-1',@@ -134,7 +131,10 @@ describe('connection-request store', () => {expect(overlaid.targets[0]).toMatchObject({ connectUrl: 'https://l/gmail', state: 'initiated' })const updated = applyConnectionUpdate(overlaid, {- ...frame({ gmail: 'connected' }, { actor: 'backend_watcher', from: 'initiated', target: 'gmail', to: 'connected' }),+ ...frame(+ { gmail: 'connected' },+ { actor: 'backend_watcher', from: 'initiated', target: 'gmail', to: 'connected' }+ ),deadline_at: 42 // a frame must never move the deadline the card already holds from the request})@@ -149,7 +149,10 @@ describe('connection-request store', () => {expect(foreign).toBe(req)- const settled = applyConnectionUpdate(req, frame({ gmail: 'not_connected', notion: 'not_connected' }, { settled: true, settled_by: 'deadline' }))+ const settled = applyConnectionUpdate(+ req,+ frame({ gmail: 'not_connected', notion: 'not_connected' }, { settled: true, settled_by: 'deadline' })+ )expect(settled.settled).toBe(true)expect(settled.settledBy).toBe('deadline')@@ -197,7 +200,10 @@ describe('connection-request store', () => {expect(rpc.mock.calls[0][1].result).toEqual({ targets: [{ name: 'notion', status: 'skipped' }] })expect($connectionRequests.get().a).toBeDefined()- updateConnectionRequest('a', frame({ gmail: 'connected', notion: 'skipped' }, { settled: true, settled_by: 'all_resolved' }))+ updateConnectionRequest(+ 'a',+ frame({ gmail: 'connected', notion: 'skipped' }, { settled: true, settled_by: 'all_resolved' })+ )expect(await respondToConnectionRequest(req, { settled_by: 'continue' })).toBe(false)expect(hasConnectionRequest('a')).toBe(false)})diff --git a/apps/desktop/src/store/connection-request.ts b/apps/desktop/src/store/connection-request.tsindex d6509fe41ca..42543191be7 100644--- a/apps/desktop/src/store/connection-request.ts+++ b/apps/desktop/src/store/connection-request.ts@@ -73,8 +73,7 @@ export interface ConnectionRequest {/** Answers the card may give for one target: the user said no, or the user consented and the backend* does the work. The card never reports an outcome; only the backend moves a target. */export type ConnectionTargetOutcome =- | { name: string; status: 'skipped' }- | { env?: Record<string, string>; name: string; status: 'approved' }+ { name: string; status: 'skipped' } | { env?: Record<string, string>; name: string; status: 'approved' }export interface ConnectionOutcome {targets?: ConnectionTargetOutcome[]@@ -101,7 +100,13 @@ const TARGET_STATES: readonly ConnectionTargetState[] = []const ACTIONS: readonly ConnectionTargetAction[] = ['authorize', 'connect', 'enable', 'install', 'reconnect']-const SETTLE_REASONS: readonly ConnectionSettleReason[] = ['all_resolved', 'continue', 'deadline', 'interrupt', 'unavailable']+const SETTLE_REASONS: readonly ConnectionSettleReason[] = [+ 'all_resolved',+ 'continue',+ 'deadline',+ 'interrupt',+ 'unavailable'+]// The wire carries these as typed literals already; the lookups defend against a backend a version ahead.const oneOf =@@ -167,10 +172,7 @@ export function normalizeConnectionRequest(/** Overlay the authoritative `connectors.operation.status` snapshot on the cached request. Frames for* another operation, and frames the operation wrote before the one already applied, change nothing:* the transport can reorder them and an older one would regress a row. */-export function applyOperationStatus(- request: ConnectionRequest,- status: ConnectionOperationStatus-): ConnectionRequest {+export function applyOperationStatus(request: ConnectionRequest, status: ConnectionOperationStatus): ConnectionRequest {if (status.op_id !== request.opId || status.seq <= request.seq) {return request}@@ -239,10 +241,7 @@ const sameEnvFields = (next: SetupField[], previous: SetupField[]): boolean =>/** Apply one `connection.update` frame. Every frame carries the operation's full target snapshot, so* the store overlays it; frames for another operation or for a settled request are ignored. */-export function applyConnectionUpdate(- request: ConnectionRequest,- update: ConnectionUpdatePayload-): ConnectionRequest {+export function applyConnectionUpdate(request: ConnectionRequest, update: ConnectionUpdatePayload): ConnectionRequest {if (update.op_id !== request.opId || request.settled) {return request}@@ -302,7 +301,10 @@ export const hasConnectionRequest = (sessionId: string | null | undefined): bool/** Drive the operation. The entry stays in the store: the backend answers with `connection.update`* and the card re-renders from that; only settlement removes it. */-export async function respondToConnectionRequest(request: ConnectionRequest, outcome: ConnectionOutcome): Promise<boolean> {+export async function respondToConnectionRequest(+ request: ConnectionRequest,+ outcome: ConnectionOutcome+): Promise<boolean> {const current = $connectionRequests.get()[keyFor(request.sessionId)]if (!current || current.opId !== request.opId || current.settled) {diff --git a/apps/desktop/src/store/connections.test.ts b/apps/desktop/src/store/connections.test.tsindex 62410210b7b..a9b579b1e71 100644--- a/apps/desktop/src/store/connections.test.ts+++ b/apps/desktop/src/store/connections.test.ts@@ -150,7 +150,11 @@ beforeEach(() => {api.mockResolvedValue({ profiles: [] })setApiRequestConnection(null)setApiRequestProfile(null)- vi.stubGlobal('window', { hermesDesktop: { api, connections: { list, setLastUsed } }, localStorage, location: window.location })+ vi.stubGlobal('window', {+ hermesDesktop: { api, connections: { list, setLastUsed } },+ localStorage,+ location: window.location+ })})afterEach(() => vi.unstubAllGlobals())diff --git a/apps/desktop/src/store/connections.ts b/apps/desktop/src/store/connections.tsindex 0aab5ecb537..3801e139b45 100644--- a/apps/desktop/src/store/connections.ts+++ b/apps/desktop/src/store/connections.ts@@ -195,6 +195,7 @@ function waitForInitialConnection(): Promise<void> {*/export async function initializeConnectionsRegistry(): Promise<DesktopConnectionsRegistry | null> {const freshSessionRequest = $freshSessionRequest.get()+const [registry, defaultLoaded] = await Promise.all([refreshConnectionsRegistry(),refreshDefaultProfile().then(diff --git a/apps/desktop/src/store/default-profile-startup.test.ts b/apps/desktop/src/store/default-profile-startup.test.tsindex da05a386ad7..fb18b467bfc 100644--- a/apps/desktop/src/store/default-profile-startup.test.ts+++ b/apps/desktop/src/store/default-profile-startup.test.ts@@ -77,6 +77,7 @@ describe('startup default route', () => {window.hermesDesktop.profile.getDefault = async () => {throw new Error('IPC interrupted')}+await initializeConnectionsRegistry()expect($connection.get()).toMatchObject({ connectionId: 'local', profile: 'personal' })expect(openGatewayForAgent).not.toHaveBeenCalled()@@ -122,6 +123,7 @@ describe('startup default route', () => {expect($connection.get()).toMatchObject({ connectionId: route.connectionId ?? 'local', profile: route.profile })expect($activeGatewayProfile.get()).toBe(route.profile)}+expect(ensureGatewayForAgent).toHaveBeenCalledWith('lab', 'research', expect.anything())expect(ensureGatewayForAgent).toHaveBeenCalledWith('local', 'personal', expect.anything())})diff --git a/apps/desktop/src/store/default-profile.test.ts b/apps/desktop/src/store/default-profile.test.tsindex f3193bac8a7..5eca6289d99 100644--- a/apps/desktop/src/store/default-profile.test.ts+++ b/apps/desktop/src/store/default-profile.test.ts@@ -20,14 +20,19 @@ describe('default profile preference', () => {const read = deferred<typeof oldRoute>()let listener!: (route: DesktopProfileRoute | null) => voidconst off = vi.fn()+const onDefaultChanged = vi.fn(callback => {listener = callback+return off})+const getDefault = vi.fn(() => {expect(onDefaultChanged).toHaveBeenCalledTimes(1)+return read.promise})+vi.stubGlobal('window', { hermesDesktop: { profile: { getDefault, onDefaultChanged } } })const { unmount } = renderHook(useDefaultProfilePreference)diff --git a/apps/desktop/src/store/file-actions.ts b/apps/desktop/src/store/file-actions.tsindex 9588a1e7d7a..8361dca6a69 100644--- a/apps/desktop/src/store/file-actions.ts+++ b/apps/desktop/src/store/file-actions.ts@@ -78,7 +78,10 @@ export async function copyFilePath(path: string): Promise<void> {* when that session's backend is this computer. A row tagged with a Connections* gateway other than `local` runs there; an untagged row runs on the window's* primary, remote or not (the rule the sidebar menus already apply). */-export function shouldOfferLocalReveal(connectionId: null | string | undefined, primaryRemote = isDesktopFsRemoteMode()): boolean {+export function shouldOfferLocalReveal(+ connectionId: null | string | undefined,+ primaryRemote = isDesktopFsRemoteMode()+): boolean {const tagged = String(connectionId || '').trim()return tagged ? tagged === LOCAL_CONNECTION_ID : !primaryRemotediff --git a/apps/desktop/src/store/free-tier-sign-in.ts b/apps/desktop/src/store/free-tier-sign-in.tsindex f25001ec459..864826fd65d 100644--- a/apps/desktop/src/store/free-tier-sign-in.ts+++ b/apps/desktop/src/store/free-tier-sign-in.ts@@ -15,14 +15,7 @@ const COPY_FLASH_MS = 1500* session), and the ruled outcomes of the transfer itself. Anything the* backend does not name lands on `error`, which carries its own message. */export type FreeTierSignInFailure =- | 'busy'- | 'error'- | 'rejected'- | 'retired'- | 'superseded'- | 'timed_out'- | 'unavailable'- | 'unreachable'+ 'busy' | 'error' | 'rejected' | 'retired' | 'superseded' | 'timed_out' | 'unavailable' | 'unreachable'export type FreeTierSignInState =| { status: 'already_signed_in' }@@ -94,7 +87,12 @@ const set = (state: FreeTierSignInState) => $freeTierSignIn.set(state)const fail = (kind: FreeTierSignInFailure, message: null | string = null, retryAfter = 0) => {clearTimers()- set({ kind, message: message?.trim() || null, retryAfter: Math.max(0, Math.round(retryAfter) || 0), status: 'failed' })+ set({+ kind,+ message: message?.trim() || null,+ retryAfter: Math.max(0, Math.round(retryAfter) || 0),+ status: 'failed'+ })}/** Every entry point calls this — Settings › Billing, the statusbar chip, thediff --git a/apps/desktop/src/store/gateway-connection-lifecycle.test.ts b/apps/desktop/src/store/gateway-connection-lifecycle.test.tsindex 155341c930b..1c203c56e86 100644--- a/apps/desktop/src/store/gateway-connection-lifecycle.test.ts+++ b/apps/desktop/src/store/gateway-connection-lifecycle.test.ts@@ -977,10 +977,12 @@ describe('cooperative pool retirement (supersedes #104871)', () => {describe('rejected secondary authentication', () => {it('parks only the rejected source across automatic nudges and recovers on explicit selection', async () => {vi.useFakeTimers()+const getConnectionFor = vi.fn(async ({ connectionId, profile }: { connectionId: string; profile: string }) => ({...descriptorFor(connectionId, profile),authMode: 'oauth'}))+const getGatewayWsUrlFor = vi.fn(async () => ({ ok: true, wsUrl: 'wss://cloud.invalid/api/ws?ticket=fresh' }))installDesktop({ getConnectionFor, getGatewayWsUrlFor })await ensureGatewayForAgent('cloud', 'default')@@ -1033,10 +1035,12 @@ describe('rejected secondary authentication', () => {it('keeps background auth rejection after socket disposal until recovery or connection removal', async () => {const { requestGatewayForAgent } = await import('./gateway')+const getConnectionFor = vi.fn(async ({ connectionId, profile }: { connectionId: string; profile: string }) => ({...descriptorFor(connectionId, profile),authMode: 'oauth'}))+const getGatewayWsUrlFor = vi.fn(async () => ({ ok: false, needsOauthLogin: true, error: 'Sign in again' }))installDesktop({ getConnectionFor, getGatewayWsUrlFor })await expect(requestGatewayForAgent('cloud', 'default', 'session.list')).rejects.toThrow()@@ -1057,14 +1061,18 @@ it('keeps background auth rejection after socket disposal until recovery or connit('does not let a removed connection repopulate the auth rejection', async () => {const { requestGatewayForAgent } = await import('./gateway')+const getConnectionFor = vi.fn(async ({ connectionId, profile }: { connectionId: string; profile: string }) => ({...descriptorFor(connectionId, profile),authMode: 'oauth'}))+let rejectTicket!: (error: Error) => void+const ticket = new Promise<never>((_resolve, reject) => {rejectTicket = reject})+const getGatewayWsUrlFor = vi.fn(() => ticket)installDesktop({ getConnectionFor, getGatewayWsUrlFor })const pending = requestGatewayForAgent('cloud', 'default', 'session.list')diff --git a/apps/desktop/src/store/gateway.test.ts b/apps/desktop/src/store/gateway.test.tsindex 3352dc63b2c..7bc702403fa 100644--- a/apps/desktop/src/store/gateway.test.ts+++ b/apps/desktop/src/store/gateway.test.ts@@ -400,7 +400,9 @@ describe('server→client request routing without a registry handler (#112791)',expect(dispatchPrimaryServerRequest(request as never, 'work')).toBe(true)expect(request.fail).not.toHaveBeenCalled()expect(onServerRequest).toHaveBeenCalledTimes(1)- expect(onServerRequest).toHaveBeenCalledWith(expect.objectContaining({ id: 'srq-1', method: 'clarify', profile: 'work' }))+ expect(onServerRequest).toHaveBeenCalledWith(+ expect.objectContaining({ id: 'srq-1', method: 'clarify', profile: 'work' })+ )})})diff --git a/apps/desktop/src/store/gateway.ts b/apps/desktop/src/store/gateway.tsindex 961a328d1e7..beeaceeed60 100644--- a/apps/desktop/src/store/gateway.ts+++ b/apps/desktop/src/store/gateway.ts@@ -647,6 +647,7 @@ async function openSecondary(entry: Secondary, spawnPriority: SpawnPriority = 'bconst desktop = window.hermesDesktopconst reauthError = g.reauthFailures.get(entry.scope)?.error+if (reauthError) {throw reauthError}@@ -795,6 +796,7 @@ async function openSecondary(entry: Secondary, spawnPriority: SpawnPriority = 'bentry.wantOpen = falseclearTimer(entry)}+throw error} finally {if (entry.connectPromise === pending) {@@ -827,9 +829,11 @@ function isStalledDialError(error: unknown): boolean {function rearmSecondary(entry: Secondary, priority: SpawnPriority = 'foreground'): void {const reauthError = g.reauthFailures.get(entry.scope)?.error+if (reauthError && priority !== 'foreground') {throw reauthError}+g.reauthFailures.delete(entry.scope)if (entry.retiredByPool && priority !== 'foreground') {@@ -868,6 +872,7 @@ async function reconnectSecondary(entry: Secondary): Promise<void> {} catch (error) {if (isGatewayReauthRequired(error)) {notifyError(error, translateNow('boot.errors.gatewaySignInRequired'), { action: RECOVERY_ACTIONS.openGateways() })+return}@@ -974,8 +979,7 @@ function createSecondary(profile: string, connectionId: null | string = null): Sg.config?.onEvent(scopedEvent)releaseTerminalTurnLease(entry.scope, event)})- entry.offRequest =- gateway.onRequest?.(request => dispatchServerRequest(request, profile, connectionId)) ?? (() => {})+ entry.offRequest = gateway.onRequest?.(request => dispatchServerRequest(request, profile, connectionId)) ?? (() => {})entry.offState = gateway.onState(state => {reportGatewayState(scope, state)@@ -1357,6 +1361,7 @@ export function retainGatewayForRelay(connectionId: null | string, profile: stri}entry.relayRetainCount += 1+if (!g.reauthFailures.has(entry.scope)) {rearmSecondary(entry)}@@ -1895,7 +1900,9 @@ export async function ensureGatewayForProfile(profile: string): Promise<void> {// reconnects are owned by use-gateway-boot, so we only drive secondaries here.// A scope parked on a rejected session stays parked for automatic request// retries; only a user gesture (`explicit`: the Reconnect action) may redial it.-export async function ensureActiveGatewayOpen({ explicit = false }: { explicit?: boolean } = {}): Promise<HermesGateway | null> {+export async function ensureActiveGatewayOpen({+ explicit = false+}: { explicit?: boolean } = {}): Promise<HermesGateway | null> {if (g.activeKey === g.primaryProfile) {return g.primaryGateway}@@ -1996,6 +2003,7 @@ function probeSecondaryLiveness(entry: Secondary): void {// before the turn ends, so a foreground turn mid tool call shows// activeRequests 0. The registry's live-scope hook supplies the turn.const liveScopes = g.config?.liveScopes?.()+const turnInFlight =liveScopes && (liveScopes.has(entry.scope) || (!entry.connectionId && liveScopes.has(entry.profile))) ? 1 : 0@@ -2299,6 +2307,7 @@ export function closeLegacySecondaryGateways(): void {g.reauthFailures.delete(scope)}}+closeSecondariesWhere(isLegacySecondary)}diff --git a/apps/desktop/src/store/hub-actions.blocked.test.ts b/apps/desktop/src/store/hub-actions.blocked.test.tsindex d72e1a67437..1b4fa63b3e3 100644--- a/apps/desktop/src/store/hub-actions.blocked.test.ts+++ b/apps/desktop/src/store/hub-actions.blocked.test.ts@@ -46,7 +46,9 @@ test('the current CLI "Not installed:" tail parses into findings + trust', () =>expect(parseInstallBlocked(wrapped)).toEqual({ findings: 1, unverified: false })// No count in the sentence when the scanner reported a verdict without findings.- const uncounted = ["Not installed: the security scan found high-risk patterns in 'org/skill' (listed above). Re-run with --force to install anyway."]+ const uncounted = [+ "Not installed: the security scan found high-risk patterns in 'org/skill' (listed above). Re-run with --force to install anyway."+ ]expect(parseInstallBlocked(uncounted)).toEqual({ findings: 0, unverified: false })})@@ -60,7 +62,11 @@ test('the legacy "Installation blocked:" tail still parses and toasts a plain exexpect(parseInstallBlocked(lines)).toEqual({ findings: 2, unverified: true })expect(parseInstallBlocked(['Failed to spawn skills install'])).toBeNull()- notifyHubActionFailed(new HubInstallBlockedError('org/skill', 2, true, lines.join('\n')), 'Skill action failed', 'skill')+ notifyHubActionFailed(+ new HubInstallBlockedError('org/skill', 2, true, lines.join('\n')),+ 'Skill action failed',+ 'skill'+ )const toast = $notifications.get()[0]expect(toast?.title).toMatch(/Couldn't install skill/)diff --git a/apps/desktop/src/store/hub-actions.ts b/apps/desktop/src/store/hub-actions.tsindex e89830500e1..0088fd8d52b 100644--- a/apps/desktop/src/store/hub-actions.ts+++ b/apps/desktop/src/store/hub-actions.ts@@ -240,7 +240,12 @@ export class HubInstallBlockedError extends Error {/** Toast for a failed hub action: a blocked install explains the scan gate and* offers "View scan"; anything else keeps the generic summary + raw tail. */-export function notifyHubActionFailed(err: unknown, fallbackTitle: string, skillName?: string, profile?: ProfileScope): void {+export function notifyHubActionFailed(+ err: unknown,+ fallbackTitle: string,+ skillName?: string,+ profile?: ProfileScope+): void {if (!(err instanceof HubInstallBlockedError)) {notifyError(err, fallbackTitle)diff --git a/apps/desktop/src/store/onboarding-capabilities.test.ts b/apps/desktop/src/store/onboarding-capabilities.test.tsindex 1afdaf9617c..c5b20b943df 100644--- a/apps/desktop/src/store/onboarding-capabilities.test.ts+++ b/apps/desktop/src/store/onboarding-capabilities.test.ts@@ -9,12 +9,24 @@ it('carries fresh catalog evidence into the guide, read from the pinned backend'vi.stubGlobal('window', { hermesDesktop: { api } })const entry = {- name: 'future-studio', auth_type: 'none', installed: false, enabled: false,+ name: 'future-studio',+ auth_type: 'none',+ installed: false,+ enabled: false,detected_apps: ['Future Studio'],- suggest: { keywords: ['future studio'], applications: ['Future Studio'], examples: ['Make a scene in Future Studio'], requires_app: true }+ suggest: {+ keywords: ['future studio'],+ applications: ['Future Studio'],+ examples: ['Make a scene in Future Studio'],+ requires_app: true+ }}- api.mockResolvedValue({ entries: [entry], diagnostics: [], discovery: { scope: 'backend', status: 'ok', platform: 'darwin' } })+ api.mockResolvedValue({+ entries: [entry],+ diagnostics: [],+ discovery: { scope: 'backend', status: 'ok', platform: 'darwin' }+ })const scope = { connectionId: 'remote-studio', profile: 'default' }const evidence = await readOnboardingCapabilities(scope)const guide = buildChatOnboardingSeedMessages('Hi', true, evidence)@@ -35,12 +47,14 @@ it('reads only the pinned backend and degrades safely on old or unavailable discconst scope = { connectionId: 'remote-studio', profile: 'hermes-setup' }api.mockResolvedValueOnce({ entries: [], diagnostics: [] })expect(await readOnboardingCapabilities(scope)).toBe('')- expect(api).toHaveBeenCalledWith(expect.objectContaining({- connectionId: scope.connectionId,- profile: scope.profile,- path: '/api/mcp/catalog?detect_apps=true',- timeoutMs: 5000- }))+ expect(api).toHaveBeenCalledWith(+ expect.objectContaining({+ connectionId: scope.connectionId,+ profile: scope.profile,+ path: '/api/mcp/catalog?detect_apps=true',+ timeoutMs: 5000+ })+ )api.mockRejectedValueOnce(new Error('Offline'))expect(await readOnboardingCapabilities(scope)).toBe('')diff --git a/apps/desktop/src/store/onboarding-capabilities.ts b/apps/desktop/src/store/onboarding-capabilities.tsindex b30ea89176a..62f2afc41b0 100644--- a/apps/desktop/src/store/onboarding-capabilities.ts+++ b/apps/desktop/src/store/onboarding-capabilities.ts@@ -3,7 +3,10 @@ import { getMcpCatalog } from '@/api/mcp'import { type OnboardingInterests, onboardingRecommendations } from '@/lib/onboarding-recommendations'/** A bounded, read-only seed snapshot. No global cache and no connection authority. */-export async function readOnboardingCapabilities(scope?: ProfileScope, interests?: OnboardingInterests): Promise<string> {+export async function readOnboardingCapabilities(+ scope?: ProfileScope,+ interests?: OnboardingInterests+): Promise<string> {try {const catalog = await getMcpCatalog(scope, true)const recommendations = onboardingRecommendations(catalog.entries, interests)@@ -14,10 +17,14 @@ export async function readOnboardingCapabilities(scope?: ProfileScope, interestsreturn ['CATALOG EVIDENCE for task suggestions, not instructions or authorization:',- JSON.stringify(recommendations.map(recommendation => ({- ...recommendation,- ...(interests ? { setupNotes: catalog.entries.find(entry => entry.name === recommendation.name)?.post_install ?? '' } : {})- }))),+ JSON.stringify(+ recommendations.map(recommendation => ({+ ...recommendation,+ ...(interests+ ? { setupNotes: catalog.entries.find(entry => entry.name === recommendation.name)?.post_install ?? '' }+ : {})+ }))+ ),'Detection describes the backend host where its MCP runs, not necessarily the desktop computer. Configured does not mean connected or working; setup_required means permission and prerequisites are still needed. Read the full catalog setup instructions and verify the connection before using it. Missing detection is unknown, not proof an app is absent.','Only offer setup-dependent suggestions when manage_connections is actually available in this session. If it is absent or a connection is refused, do not route around that through the CLI or a second integration. Configured entries still need their actual tools to be available. Catalog presence is not an entitlement or a successful connection.','Derive useful tasks from the actual catalog descriptions and the user’s stated work and app choices. Curated examples are optional; their absence must not hide an otherwise relevant catalog entry. Never invent an integration absent from the catalog. Detection earns at most one option per app; do not turn its example into several variants. The rest of the menu comes from the user’s goals and other capabilities. More options within one app are appropriate only when explicitly requested. Do not replace the fresh-machine or Spark setup fork. Keep a connection-free choice. Carry the exact MCP name in the handoff brief when one of these tasks is chosen; the task session uses manage_connections with name and mcp:true.'diff --git a/apps/desktop/src/store/onboarding-script.ts b/apps/desktop/src/store/onboarding-script.tsindex ab78807aa61..c6be101888a 100644--- a/apps/desktop/src/store/onboarding-script.ts+++ b/apps/desktop/src/store/onboarding-script.ts@@ -27,7 +27,11 @@ export function buildChatOnboardingSeedMessages(role: 'assistant' | 'user'}[] {return [- { content: buildChatOnboardingPrompt(machineUserName(), signedIn, capabilities), display_kind: 'hidden', role: 'user' },+ {+ content: buildChatOnboardingPrompt(machineUserName(), signedIn, capabilities),+ display_kind: 'hidden',+ role: 'user'+ },{ content: greeting, role: 'assistant' }]}diff --git a/apps/desktop/src/store/onboarding.test.ts b/apps/desktop/src/store/onboarding.test.tsindex 02691a73730..fa43fc56d77 100644--- a/apps/desktop/src/store/onboarding.test.ts+++ b/apps/desktop/src/store/onboarding.test.ts@@ -881,7 +881,9 @@ describe('setOnboardingModel', () => {vi.restoreAllMocks()})- function confirmingModelState(overrides: Partial<Extract<DesktopOnboardingState['flow'], { status: 'confirming_model' }>> = {}) {+ function confirmingModelState(+ overrides: Partial<Extract<DesktopOnboardingState['flow'], { status: 'confirming_model' }>> = {}+ ) {return baseState({flow: {status: 'confirming_model',diff --git a/apps/desktop/src/store/plugin-catalog-install.test.ts b/apps/desktop/src/store/plugin-catalog-install.test.tsindex 2a1d87c1457..caad92f0faf 100644--- a/apps/desktop/src/store/plugin-catalog-install.test.ts+++ b/apps/desktop/src/store/plugin-catalog-install.test.ts@@ -24,7 +24,12 @@ describe('requestPluginCatalogInstallFromDeepLink', () => {it('opens the reviewed/pinned catalog dialog exactly like an in-app pick', async () => {const lookup = lookupFor({ok: true,- entry: { name: 'aihubmix', repo: 'https://github.com/AIhubmix/hermes-provider-aihubmix', sha: 'b'.repeat(40), subdir: 'aihubmix' }+ entry: {+ name: 'aihubmix',+ repo: 'https://github.com/AIhubmix/hermes-provider-aihubmix',+ sha: 'b'.repeat(40),+ subdir: 'aihubmix'+ }})await requestPluginCatalogInstallFromDeepLink('aihubmix', lookup)@@ -54,7 +59,9 @@ describe('requestPluginCatalogInstallFromDeepLink', () => {})it('resolves against the live catalog feed by default and rejects unknown names', async () => {- const feed = JSON.stringify([{ name: 'weather', repo: 'https://github.com/x/weather', sha: 'a'.repeat(40), subdir: '' }])+ const feed = JSON.stringify([+ { name: 'weather', repo: 'https://github.com/x/weather', sha: 'a'.repeat(40), subdir: '' }+ ])const fetchSpy = vi.spyOn(globalThis, 'fetch').mockImplementation(async () => new Response(feed, { status: 200 }))await requestPluginCatalogInstallFromDeepLink('weather-evil')@@ -77,7 +84,15 @@ describe('openCatalogPluginInstall', () => {it('short-circuits with a success toast when the entry is installed and current', () => {$agentPlugins.set([- { catalog_name: 'weather', description: '', name: 'weather', source: 'git', status: 'enabled', update_available: false, version: '1' }+ {+ catalog_name: 'weather',+ description: '',+ name: 'weather',+ source: 'git',+ status: 'enabled',+ update_available: false,+ version: '1'+ }])openCatalogPluginInstall({ name: 'weather', repo: 'https://github.com/x/weather' }, 'workbot')diff --git a/apps/desktop/src/store/projects.test.ts b/apps/desktop/src/store/projects.test.tsindex ac8f7ed2378..39ac5871b32 100644--- a/apps/desktop/src/store/projects.test.ts+++ b/apps/desktop/src/store/projects.test.ts@@ -524,7 +524,15 @@ describe('project writes while viewing all profiles', () => {$projectsRpcAvailable.set(null)$projects.set([project])$projectTree.set([- { id: project.id, label: project.name, path: project.primary_path, color: null, icon: null, repos: [], sessionCount: 0 }+ {+ id: project.id,+ label: project.name,+ path: project.primary_path,+ color: null,+ icon: null,+ repos: [],+ sessionCount: 0+ }])$activeGatewayProfile.set('default')setShowAllProfiles(false)@@ -535,49 +543,58 @@ describe('project writes while viewing all profiles', () => {$activeGatewayProfile.set('default')})- it.each(['default', 'coder'])('updates appearance in the active %s profile without leaving All profiles', async profile => {- const request = vi.fn().mockResolvedValue({})- activeGateway.mockReturnValue({ connectionState: 'open', request } as never)- $activeGatewayProfile.set(profile)- setShowAllProfiles(true)-- await expect(updateProject(project.id, { color: '#ff0000' })).resolves.toBeUndefined()-- expect(request).toHaveBeenCalledWith(- 'projects.update',- expect.objectContaining({ profile, id: project.id, color: '#ff0000' })- )- expect($profileScope.get()).toBe(ALL_PROFILES)- expect($projects.get()).toEqual([expect.objectContaining({ id: project.id, color: '#ff0000' })])- })-- it.each(['default', 'coder'])('adds a folder in the active %s profile without leaving All profiles', async profile => {- const request = vi.fn().mockResolvedValue({})- activeGateway.mockReturnValue({ connectionState: 'open', request } as never)- $activeGatewayProfile.set(profile)- setShowAllProfiles(true)-- await expect(addProjectFolder(project.id, '/srv/ws/extra')).resolves.toBeUndefined()-- expect(request).toHaveBeenCalledWith(- 'projects.add_folder',- expect.objectContaining({ profile, id: project.id, path: '/srv/ws/extra' })- )- expect($profileScope.get()).toBe(ALL_PROFILES)- })+ it.each(['default', 'coder'])(+ 'updates appearance in the active %s profile without leaving All profiles',+ async profile => {+ const request = vi.fn().mockResolvedValue({})+ activeGateway.mockReturnValue({ connectionState: 'open', request } as never)+ $activeGatewayProfile.set(profile)+ setShowAllProfiles(true)++ await expect(updateProject(project.id, { color: '#ff0000' })).resolves.toBeUndefined()++ expect(request).toHaveBeenCalledWith(+ 'projects.update',+ expect.objectContaining({ profile, id: project.id, color: '#ff0000' })+ )+ expect($profileScope.get()).toBe(ALL_PROFILES)+ expect($projects.get()).toEqual([expect.objectContaining({ id: project.id, color: '#ff0000' })])+ }+ )++ it.each(['default', 'coder'])(+ 'adds a folder in the active %s profile without leaving All profiles',+ async profile => {+ const request = vi.fn().mockResolvedValue({})+ activeGateway.mockReturnValue({ connectionState: 'open', request } as never)+ $activeGatewayProfile.set(profile)+ setShowAllProfiles(true)++ await expect(addProjectFolder(project.id, '/srv/ws/extra')).resolves.toBeUndefined()++ expect(request).toHaveBeenCalledWith(+ 'projects.add_folder',+ expect.objectContaining({ profile, id: project.id, path: '/srv/ws/extra' })+ )+ expect($profileScope.get()).toBe(ALL_PROFILES)+ }+ )- it.each(['default', 'coder'])('deletes a project in the active %s profile without leaving All profiles', async profile => {- const request = vi.fn().mockResolvedValue({ active_id: null, projects: [], scoped_session_ids: [] })- activeGateway.mockReturnValue({ connectionState: 'open', request } as never)- $activeGatewayProfile.set(profile)- setShowAllProfiles(true)+ it.each(['default', 'coder'])(+ 'deletes a project in the active %s profile without leaving All profiles',+ async profile => {+ const request = vi.fn().mockResolvedValue({ active_id: null, projects: [], scoped_session_ids: [] })+ activeGateway.mockReturnValue({ connectionState: 'open', request } as never)+ $activeGatewayProfile.set(profile)+ setShowAllProfiles(true)- await expect(deleteProject(project.id)).resolves.toBeUndefined()+ await expect(deleteProject(project.id)).resolves.toBeUndefined()- expect(request).toHaveBeenCalledWith('projects.delete', expect.objectContaining({ profile, id: project.id }))- expect($profileScope.get()).toBe(ALL_PROFILES)- expect($projects.get()).toEqual([])- })+ expect(request).toHaveBeenCalledWith('projects.delete', expect.objectContaining({ profile, id: project.id }))+ expect($profileScope.get()).toBe(ALL_PROFILES)+ expect($projects.get()).toEqual([])+ }+ )})describe('projects RPC capability', () => {diff --git a/apps/desktop/src/store/prompts.test.ts b/apps/desktop/src/store/prompts.test.tsindex 22dbddb5277..289371a43c5 100644--- a/apps/desktop/src/store/prompts.test.ts+++ b/apps/desktop/src/store/prompts.test.ts@@ -183,6 +183,7 @@ describe('approval prompt store', () => {.map(request => request.requestId)).toEqual(['r1', 'r2'])let finish!: (result: unknown) => void+const replay = replayPendingApproval({request: () =>@@ -192,6 +193,7 @@ describe('approval prompt store', () => {},'s1')+clearApprovalRequest('s1', 'r1')finish({approvals: [diff --git a/apps/desktop/src/store/provider-wait.ts b/apps/desktop/src/store/provider-wait.tsindex 39ab8f35de4..34bc49973d6 100644--- a/apps/desktop/src/store/provider-wait.ts+++ b/apps/desktop/src/store/provider-wait.ts@@ -45,7 +45,9 @@ export function clearAllProviderWaits(): void {export function providerWaitText(text: string): string {const value = text.trim()- return /^(?:⏳|⚠|↻|⚙)\s*(?:(?:still\s+)?waiting on|loading|processing prompt|no (?:output|response)|model returned)/i.test(value)+ return /^(?:⏳|⚠|↻|⚙)\s*(?:(?:still\s+)?waiting on|loading|processing prompt|no (?:output|response)|model returned)/i.test(+ value+ )? value: ''}diff --git a/apps/desktop/src/store/reactions.ts b/apps/desktop/src/store/reactions.tsindex 66337bc5971..7ba8103054d 100644--- a/apps/desktop/src/store/reactions.ts+++ b/apps/desktop/src/store/reactions.ts@@ -86,17 +86,12 @@ export async function toggleMessageReaction(// requestForOwnedSession resolves the exact owner route and fails closed;// the ambient request stays the fallback for legacy single-profile// setups where the owner cannot be named.- const result = await requestForOwnedSession<MessageReactResponse>(- sessionId,- ambientRequest,- 'message.react',- {- session_id: sessionId,- ...(rowId === undefined ? { newest_role: message.role } : { row_id: rowId }),- emoji,- author- }- )+ const result = await requestForOwnedSession<MessageReactResponse>(sessionId, ambientRequest, 'message.react', {+ session_id: sessionId,+ ...(rowId === undefined ? { newest_role: message.role } : { row_id: rowId }),+ emoji,+ author+ })// Learn the row id from the response so later toggles address it directly.writeReactions(message.id, result?.reactions ?? [], result?.row_id)diff --git a/apps/desktop/src/store/session-states.ts b/apps/desktop/src/store/session-states.tsindex 04211e9bad0..95e56af19db 100644--- a/apps/desktop/src/store/session-states.ts+++ b/apps/desktop/src/store/session-states.ts@@ -2198,7 +2198,10 @@ export function migrateTilesForProfile(oldProfile: string, newProfile: string):if (moved) {delete tilesByProfile[from]- tilesByProfile[to] = [...(tilesByProfile[to] ?? []), ...moved.map(tile => ({ ...tile, ownerRoute: renamedOwner(tile.ownerRoute) }))]+ tilesByProfile[to] = [+ ...(tilesByProfile[to] ?? []),+ ...moved.map(tile => ({ ...tile, ownerRoute: renamedOwner(tile.ownerRoute) }))+ ]}const botTiles = tilesByProfile[BOTS_TILE_BUCKET]diff --git a/apps/desktop/src/store/session.ts b/apps/desktop/src/store/session.tsindex 12ea4965648..60dc9a1a9a4 100644--- a/apps/desktop/src/store/session.ts+++ b/apps/desktop/src/store/session.ts@@ -735,11 +735,7 @@ export function carryForwardFailedProfileSessions(for (const session of previous) {// A hidden row (canonical Bot Chat) is LISTED-NEVER by design: the// failed-slice carry must not ride it back into the sidebar (#113273).- if (- session.hidden ||- !failed.has(sidebarProfileKey(session)) ||- incomingIds.has(sessionListIdentity(session))- ) {+ if (session.hidden || !failed.has(sidebarProfileKey(session)) || incomingIds.has(sessionListIdentity(session))) {continue}diff --git a/apps/desktop/src/store/suggestion-providers/mcp.test.ts b/apps/desktop/src/store/suggestion-providers/mcp.test.tsindex 9581c70bfbd..fd61a891abb 100644--- a/apps/desktop/src/store/suggestion-providers/mcp.test.ts+++ b/apps/desktop/src/store/suggestion-providers/mcp.test.ts@@ -3,8 +3,20 @@ import { describe, expect, it } from 'vitest'import { buildMcpSuggestionIndex, matchSuggestions } from './mcp'it('does not send local-app or non-OAuth catalog suggestions through the hosted OAuth-only composer flow', () => {- const hosted = { name: 'hosted', url: 'https://mcp.example.test', auth_type: 'oauth', transport: 'http', suggest: { keywords: ['hosted'], hosts: [] } }- const editor = { ...hosted, name: 'editor', url: 'http://127.0.0.1:8000/mcp', auth_type: 'none', suggest: { ...hosted.suggest, requires_app: true } }+ const hosted = {+ name: 'hosted',+ url: 'https://mcp.example.test',+ auth_type: 'oauth',+ transport: 'http',+ suggest: { keywords: ['hosted'], hosts: [] }+ }+ const editor = {+ ...hosted,+ name: 'editor',+ url: 'http://127.0.0.1:8000/mcp',+ auth_type: 'none',+ suggest: { ...hosted.suggest, requires_app: true }+ }const key = { ...hosted, name: 'key', auth_type: 'api_key' }const stdio = { ...hosted, name: 'stdio', url: null, transport: 'stdio' }expect(buildMcpSuggestionIndex([hosted, editor, key, stdio]).map(row => row.server)).toEqual([hosted.name])diff --git a/apps/desktop/src/store/suggestion-providers/mcp.ts b/apps/desktop/src/store/suggestion-providers/mcp.tsindex bdf8cbde83d..17fca6c589a 100644--- a/apps/desktop/src/store/suggestion-providers/mcp.ts+++ b/apps/desktop/src/store/suggestion-providers/mcp.ts@@ -83,9 +83,14 @@ export function buildMcpSuggestionIndex(entries: readonly Pick<McpCatalogEntry, 'name' | 'url' | 'suggest' | 'auth_type' | 'transport'>[]): SuggestibleServer[] {return entries- .filter(entry =>- entry.transport === 'http' && entry.auth_type === 'oauth' && !entry.suggest?.requires_app- && entry.suggest && entry.url && (entry.suggest.keywords.length > 0 || entry.suggest.hosts.length > 0)+ .filter(+ entry =>+ entry.transport === 'http' &&+ entry.auth_type === 'oauth' &&+ !entry.suggest?.requires_app &&+ entry.suggest &&+ entry.url &&+ (entry.suggest.keywords.length > 0 || entry.suggest.hosts.length > 0)).map(entry => ({hosts: entry.suggest!.hosts,diff --git a/apps/desktop/src/store/terminal-backend-warning.test.ts b/apps/desktop/src/store/terminal-backend-warning.test.tsindex 721ad79fa8c..542e3382d81 100644--- a/apps/desktop/src/store/terminal-backend-warning.test.ts+++ b/apps/desktop/src/store/terminal-backend-warning.test.ts@@ -31,7 +31,10 @@ beforeEach(() => {// "Needs setup" pill inside Skills → Tools → Terminal; nothing told the user// shell commands could not run.test('a selected non-local backend that is not ready warns once with Use Local / Open settings', async () => {- getTerminalBackends.mockResolvedValue({ active: 'docker', backends: [row('local', 'ready'), row('docker', 'unavailable', true)] })+ getTerminalBackends.mockResolvedValue({+ active: 'docker',+ backends: [row('local', 'ready'), row('docker', 'unavailable', true)]+ })selectTerminalBackend.mockResolvedValue({ ok: true, backend: 'local' })expect(await warnIfTerminalBackendUnavailable()).toBe(true)diff --git a/apps/desktop/src/store/thread-scroll-restore.test.ts b/apps/desktop/src/store/thread-scroll-restore.test.tsindex b28aae3223b..187ec2ea2f5 100644--- a/apps/desktop/src/store/thread-scroll-restore.test.ts+++ b/apps/desktop/src/store/thread-scroll-restore.test.ts@@ -38,11 +38,15 @@ describe('shouldReapplyFrozenThreadScrollOffset', () => {it('re-pins a settled bottom target only on transcript growth, never on a composer-only resize', () => {const previous = { clearanceHeight: 120, clientHeight: 600, scrollHeight: 5000 }- expect(shouldReapplyFrozenThreadScrollOffset(BOTTOM, true, previous, { ...previous, scrollHeight: 5600 })).toBe(true)+ expect(shouldReapplyFrozenThreadScrollOffset(BOTTOM, true, previous, { ...previous, scrollHeight: 5600 })).toBe(+ true+ )expect(shouldReapplyFrozenThreadScrollOffset(BOTTOM, true, previous, { clearanceHeight: 200, scrollHeight: 5080 })).toBe(false)- expect(shouldReapplyFrozenThreadScrollOffset(BOTTOM, true, previous, { ...previous, scrollHeight: 4000 })).toBe(false)+ expect(shouldReapplyFrozenThreadScrollOffset(BOTTOM, true, previous, { ...previous, scrollHeight: 4000 })).toBe(+ false+ )})it('does not re-pin while the session-switch settle loop is still running', () => {diff --git a/apps/desktop/src/store/tips.test.ts b/apps/desktop/src/store/tips.test.tsindex 9404e810ade..8cfe0536243 100644--- a/apps/desktop/src/store/tips.test.ts+++ b/apps/desktop/src/store/tips.test.ts@@ -1,6 +1,15 @@import { beforeEach, describe, expect, it } from 'vitest'-import { $activeTip, $retiredTips, $tipShownAt, agentTipId, dismissTip, resetTips, retireActiveTip, showTip } from './tips'+import {+ $activeTip,+ $retiredTips,+ $tipShownAt,+ agentTipId,+ dismissTip,+ resetTips,+ retireActiveTip,+ showTip+} from './tips'const showAgentTip = (selector: string, text: string) => {showTip({diff --git a/apps/desktop/src/store/transcript-tail.test.ts b/apps/desktop/src/store/transcript-tail.test.tsindex 8f9946b9f0d..020361192f9 100644--- a/apps/desktop/src/store/transcript-tail.test.ts+++ b/apps/desktop/src/store/transcript-tail.test.ts@@ -7,10 +7,11 @@ import {rewindTranscriptTail} from './transcript-tail'-const page = (count: number, limit = 10) => ({- messages: Array.from({ length: count }, (_, i) => ({ id: `m${i}` })),- pagination: { limit, offset: 0 }-}) as never+const page = (count: number, limit = 10) =>+ ({+ messages: Array.from({ length: count }, (_, i) => ({ id: `m${i}` })),+ pagination: { limit, offset: 0 }+ }) as neverdescribe('recordTranscriptTail no-op suppression', () => {beforeEach(() => {@@ -83,7 +84,12 @@ describe('rewindTranscriptTail', () => {})it('keeps a rewind on the same route the tail was hydrated with', () => {- recordTranscriptTail('s1', page(10), { connectionId: 'c1', profile: 'work' }, { connectionId: 'c1', profile: 'work' })+ recordTranscriptTail(+ 's1',+ page(10),+ { connectionId: 'c1', profile: 'work' },+ { connectionId: 'c1', profile: 'work' }+ )expect(rewindTranscriptTail('s1', 4, { connectionId: 'c1', profile: 'work' })).toBe(true)@@ -115,8 +121,18 @@ describe('rewindTranscriptTail', () => {})it('refuses an ambiguous rewind when the session has several owner scopes', () => {- recordTranscriptTail('s1', page(10), { connectionId: 'c1', profile: 'work' }, { connectionId: 'c1', profile: 'work' })- recordTranscriptTail('s1', page(10), { connectionId: 'c2', profile: 'work' }, { connectionId: 'c2', profile: 'work' })+ recordTranscriptTail(+ 's1',+ page(10),+ { connectionId: 'c1', profile: 'work' },+ { connectionId: 'c1', profile: 'work' }+ )+ recordTranscriptTail(+ 's1',+ page(10),+ { connectionId: 'c2', profile: 'work' },+ { connectionId: 'c2', profile: 'work' }+ )expect(rewindTranscriptTail('s1', 4)).toBe(false)})diff --git a/apps/desktop/src/test/pool-retirement-renderer.ts b/apps/desktop/src/test/pool-retirement-renderer.tsindex 5e7bc58c623..79fe677324a 100644--- a/apps/desktop/src/test/pool-retirement-renderer.ts+++ b/apps/desktop/src/test/pool-retirement-renderer.ts@@ -1,7 +1,11 @@import {- closeSecondaryGateways, configureGatewayRegistry, openGatewayForAgent,- openGatewayForProfile, openSecondaryCount, parkSecondariesForRetiredBackend,- reconnectSecondaryGateways,+ closeSecondaryGateways,+ configureGatewayRegistry,+ openGatewayForAgent,+ openGatewayForProfile,+ openSecondaryCount,+ parkSecondariesForRetiredBackend,+ reconnectSecondaryGateways} from '../store/gateway'const parked: Record<string, string[]> = {}@@ -32,7 +36,7 @@ const api = {return { parked, open: openSecondaryCount() }},- close: closeSecondaryGateways,+ close: closeSecondaryGateways}Object.assign(window, { poolRetirementRenderer: api })diff --git a/apps/shared/src/gateway-contract.generated.ts b/apps/shared/src/gateway-contract.generated.tsindex e8f793ee7cb..d85544c1bcf 100644--- a/apps/shared/src/gateway-contract.generated.ts+++ b/apps/shared/src/gateway-contract.generated.ts@@ -1,7 +1,7 @@// GENERATED by scripts/gen_gateway_contracts.py from tui_gateway/contracts — DO NOT EDIT.// Regenerate: .venv/bin/python scripts/gen_gateway_contracts.py// tests/tui_gateway/contracts/test_generated.py fails when this file is stale.-/* eslint-disable */+// ── Types ──/** Any method the desktop may route to a named profile (``requestGatewayForProfile`` adds ``profile``). */export interface ProfileParams {diff --git a/ui-tui/src/__tests__/appChromeStatusRule.test.tsx b/ui-tui/src/__tests__/appChromeStatusRule.test.tsxindex 5ec8ef72a06..0b766a306b2 100644--- a/ui-tui/src/__tests__/appChromeStatusRule.test.tsx+++ b/ui-tui/src/__tests__/appChromeStatusRule.test.tsx@@ -112,8 +112,9 @@ describe('StatusRule model label', () => {expect(clamped).toContain('ultra→max')// Verbatim (or not-yet-stamped) wire levels make no claim.- expect(textContent(StatusRule({ ...baseProps, modelReasoningEffort: 'high', modelReasoningEffortWire: 'high' })))- .toContain('opus 4.8 high')+ expect(+ textContent(StatusRule({ ...baseProps, modelReasoningEffort: 'high', modelReasoningEffortWire: 'high' }))+ ).toContain('opus 4.8 high')expect(textContent(StatusRule({ ...baseProps, modelReasoningEffort: 'ultra' }))).toContain('opus 4.8 ultra')})})diff --git a/ui-tui/src/__tests__/createGatewayEventHandler.test.ts b/ui-tui/src/__tests__/createGatewayEventHandler.test.tsindex f10fbfd85f4..15c251d8865 100644--- a/ui-tui/src/__tests__/createGatewayEventHandler.test.ts+++ b/ui-tui/src/__tests__/createGatewayEventHandler.test.ts@@ -1,10 +1,7 @@import type { ConnectionOperationTarget } from '@hermes/shared/gateway-events'import { beforeEach, describe, expect, it, vi } from 'vitest'-import {- $connectionOperation,- resetConnectionOperationsForTests-} from '../app/connectionOperationStore.js'+import { $connectionOperation, resetConnectionOperationsForTests } from '../app/connectionOperationStore.js'import { createGatewayEventHandler } from '../app/createGatewayEventHandler.js'import { createServerRequestHandler } from '../app/createServerRequestHandler.js'import { getOverlayState, patchOverlayState, resetOverlayState } from '../app/overlayStore.js'@@ -69,7 +66,10 @@ const buildCtx = (appended: Msg[]) =>const serverRequest = (method: string, params: Record<string, unknown>, id = `srq-${method}`) => {const respond = vi.fn()- const handled = createServerRequestHandler({ ringPromptBell: vi.fn(), setStatus: status => patchUiState({ status }) })({+ const handled = createServerRequestHandler({+ ringPromptBell: vi.fn(),+ setStatus: status => patchUiState({ status })+ })({fail: vi.fn(),id,method,@@ -1740,7 +1740,8 @@ describe('createGatewayEventHandler', () => {it('renders a failed turn from error_surface instead of the raw provider JSON', () => {const appended: Msg[] = []const onEvent = createGatewayEventHandler(buildCtx(appended))- const raw = 'Error code: 401 - {"error": {"message": "Incorrect API key provided", "type": "invalid_request_error"}}'+ const raw =+ 'Error code: 401 - {"error": {"message": "Incorrect API key provided", "type": "invalid_request_error"}}'onEvent({payload: {@@ -1811,7 +1812,10 @@ describe('createGatewayEventHandler', () => {const ctx = buildCtx([])const onEvent = createGatewayEventHandler(ctx)- onEvent({ payload: { message: 'invalid params for prompt.submit: turn_author: Extra inputs are not permitted' }, type: 'error' } as any)+ onEvent({+ payload: { message: 'invalid params for prompt.submit: turn_author: Extra inputs are not permitted' },+ type: 'error'+ } as any)const line = String((ctx.system.sys as any).mock.calls.at(-1)?.[0])expect(line).toContain('/update')diff --git a/ui-tui/src/__tests__/createSlashHandler.test.ts b/ui-tui/src/__tests__/createSlashHandler.test.tsindex ad8b1323db0..34d5a5a4823 100644--- a/ui-tui/src/__tests__/createSlashHandler.test.ts+++ b/ui-tui/src/__tests__/createSlashHandler.test.ts@@ -937,6 +937,7 @@ describe('createSlashHandler', () => {it('surfaces the slash worker failure itself instead of the command.dispatch refusal', async () => {patchUiState({ sid: 'sid-abc' })+const ctx = buildCtx({gateway: {gw: {@@ -946,7 +947,9 @@ describe('createSlashHandler', () => {return Promise.reject(new JsonRpcGatewayError('slash worker timed out', { code: 5030 }))}- return Promise.reject(new JsonRpcGatewayError('not a quick/plugin/bundle/skill command: insights', { code: 4018 }))+ return Promise.reject(+ new JsonRpcGatewayError('not a quick/plugin/bundle/skill command: insights', { code: 4018 })+ )})},rpc: vi.fn(() => Promise.resolve({}))@@ -965,6 +968,7 @@ describe('createSlashHandler', () => {it('still falls back to command.dispatch on a 4018 "not mine" refusal', async () => {patchUiState({ sid: 'sid-abc' })+const ctx = buildCtx({gateway: {gw: {diff --git a/ui-tui/src/__tests__/processDock.test.tsx b/ui-tui/src/__tests__/processDock.test.tsxindex 24e30d365c9..9b1ac4c1d30 100644--- a/ui-tui/src/__tests__/processDock.test.tsx+++ b/ui-tui/src/__tests__/processDock.test.tsx@@ -106,9 +106,7 @@ it('paints a Processes block under the agents without letting either block hideexpect(alone).toContain('Processes · 1 running · 1 done · Ctrl+T expand')expect(alone).toContain('✔ pytest tests/ · exit 0 · 5s ago')- const collapsed = paint(- <AgentsPanelView collapsed cols={80} {...agentRows} processes={block} t={DEFAULT_THEME} />- )+ const collapsed = paint(<AgentsPanelView collapsed cols={80} {...agentRows} processes={block} t={DEFAULT_THEME} />)expect(collapsed.trim().split('\n')).toHaveLength(1)expect(collapsed).toContain('6 live agents · 1 procs')diff --git a/ui-tui/src/__tests__/useSessionLifecycle.test.ts b/ui-tui/src/__tests__/useSessionLifecycle.test.tsindex 4a5494ebb69..b2372b20f76 100644--- a/ui-tui/src/__tests__/useSessionLifecycle.test.ts+++ b/ui-tui/src/__tests__/useSessionLifecycle.test.ts@@ -77,11 +77,13 @@ describe('live session activation in-flight state', () => {user: 'process completed'}- expect(liveSessionInflightMessages(inflight)).toEqual([{- kind: 'event',- role: 'system',- text: 'Finished syncing the workspace'- }])+ expect(liveSessionInflightMessages(inflight)).toEqual([+ {+ kind: 'event',+ role: 'system',+ text: 'Finished syncing the workspace'+ }+ ])})it('ignores empty in-flight payloads', () => {diff --git a/ui-tui/src/__tests__/userMessages.test.ts b/ui-tui/src/__tests__/userMessages.test.tsindex 46c2e52be11..0cea8906f40 100644--- a/ui-tui/src/__tests__/userMessages.test.ts+++ b/ui-tui/src/__tests__/userMessages.test.ts@@ -121,9 +121,9 @@ describe('describeRpcError', () => {expect(describeRpcError(new JsonRpcGatewayError(raw, { code: 4001 }))).toBe(raw)}- expect(describeRpcError(new JsonRpcGatewayError('session not found or not owned by this transport', { code: 4001 }))).toContain(- '/resume'- )+ expect(+ describeRpcError(new JsonRpcGatewayError('session not found or not owned by this transport', { code: 4001 }))+ ).toContain('/resume')})it('records the raw wire text it replaced in the log sink', () => {diff --git a/ui-tui/src/app/createGatewayEventHandler.ts b/ui-tui/src/app/createGatewayEventHandler.tsindex 5e610f53beb..5e7a8cebbb6 100644--- a/ui-tui/src/app/createGatewayEventHandler.ts+++ b/ui-tui/src/app/createGatewayEventHandler.ts@@ -1535,7 +1535,12 @@ export function createGatewayEventHandler(ctx: GatewayEventHandlerContext): (ev:const msgs: Msg[] = failed? [...finalMessages.filter(- (m, i) => !(i === finalMessages.length - 1 && m.role === 'assistant' && isBareErrorText(m.text, payload.error))+ (m, i) =>+ !(+ i === finalMessages.length - 1 &&+ m.role === 'assistant' &&+ isBareErrorText(m.text, payload.error)+ )),{ role: 'assistant', text: describeTurnFailure(payload) }]diff --git a/ui-tui/src/app/processRoster.ts b/ui-tui/src/app/processRoster.tsindex 25e450bfbcd..930d06b1b8c 100644--- a/ui-tui/src/app/processRoster.ts+++ b/ui-tui/src/app/processRoster.ts@@ -104,7 +104,7 @@ export const buildProcessRows = (processes: readonly ProcessEntry[], nowMs: numb}return rows.sort((a, b) =>- a.status === 'running' !== (b.status === 'running')+ (a.status === 'running') !== (b.status === 'running')? a.status === 'running'? -1: 1@@ -118,8 +118,5 @@ export function useProcessRows(nowMs: number): ProcessRow[] {const snapshot = useStore($processSnapshot)const { sid } = useStore($uiState)- return useMemo(- () => buildProcessRows(snapshot.sid === sid ? snapshot.processes : [], nowMs),- [snapshot, sid, nowMs]- )+ return useMemo(() => buildProcessRows(snapshot.sid === sid ? snapshot.processes : [], nowMs), [snapshot, sid, nowMs])}diff --git a/ui-tui/src/app/useInputHandlers.ts b/ui-tui/src/app/useInputHandlers.tsindex 61d8f1755c8..2b399be04e3 100644--- a/ui-tui/src/app/useInputHandlers.ts+++ b/ui-tui/src/app/useInputHandlers.ts@@ -32,11 +32,8 @@ const DASHBOARD_NEW_SESSION_MESSAGE = 'starting a fresh dashboard chat...'export const shouldAllowIdleHotkeyExit = (dashboardTuiMode = DASHBOARD_TUI_MODE) => !dashboardTuiMode/** Text or attachments in the composer: Ctrl+D must not exit over an unsent draft (#116443). */-export const composerHasDraft = (cState: {- input: string- inputBuf: string[]- tokens?: unknown[]-}): boolean => Boolean(cState.input || cState.inputBuf.length || cState.tokens?.length)+export const composerHasDraft = (cState: { input: string; inputBuf: string[]; tokens?: unknown[] }): boolean =>+ Boolean(cState.input || cState.inputBuf.length || cState.tokens?.length)export function handleInputSelectionClipboard(selection: ReturnType<typeof getInputSelection>,diff --git a/ui-tui/src/app/useSessionLifecycle.ts b/ui-tui/src/app/useSessionLifecycle.tsindex 1dd16d09d77..3d00d44c8b8 100644--- a/ui-tui/src/app/useSessionLifecycle.ts+++ b/ui-tui/src/app/useSessionLifecycle.ts@@ -60,12 +60,14 @@ export const liveSessionInflightMessages = (inflight?: null | InflightTurn): Msgconst user = String(inflight?.user ?? '').trim()return user- ? toTranscriptMessages([{- role: 'user',- text: user,- ...(inflight?.display_kind ? { display_kind: inflight.display_kind } : {}),- ...(inflight?.display_metadata ? { display_metadata: inflight.display_metadata } : {})- }])+ ? toTranscriptMessages([+ {+ role: 'user',+ text: user,+ ...(inflight?.display_kind ? { display_kind: inflight.display_kind } : {}),+ ...(inflight?.display_metadata ? { display_metadata: inflight.display_metadata } : {})+ }+ ]): []}@@ -357,7 +359,8 @@ export function useSessionLifecycle(opts: UseSessionLifecycleOptions) {const previousSid = getUiState().sid- return gw.request<SessionResumeResult>('session.resume', { cols: colsRef.current, session_id: id })+ return gw+ .request<SessionResumeResult>('session.resume', { cols: colsRef.current, session_id: id }).then(raw => {const r = asRpcResult<SessionResumeResult>(raw)diff --git a/ui-tui/src/app/userMessages.ts b/ui-tui/src/app/userMessages.tsindex 76da58f52c3..e78f9538f43 100644--- a/ui-tui/src/app/userMessages.ts+++ b/ui-tui/src/app/userMessages.ts@@ -120,7 +120,10 @@ const SESSION_NOT_FOUND_RE = /session not found/iconst NOT_CONNECTED_RE = /^gateway not (?:connected|running)\b/const TIMED_OUT_RE = /^request timed out after (\d+)s/-type RpcErrorRow = [matcher: (code: number | undefined, text: string) => RegExpExecArray | boolean | null, render: (m: RegExpExecArray | null) => string]+type RpcErrorRow = [+ matcher: (code: number | undefined, text: string) => RegExpExecArray | boolean | null,+ render: (m: RegExpExecArray | null) => string+]// Ordered: first matching row wins. 4001 is reused by the backend for unrelated// refusals ("no active session", "slug is required", NOT_OWNER), so the code@@ -138,7 +141,8 @@ const RPC_ERROR_ROWS: RpcErrorRow[] = [],[(_code, text) => TIMED_OUT_RE.exec(text),- m => `Hermes did not answer within ${m?.[1] ?? '?'}s. Try again; if it keeps happening, type /logs and report the last lines.`+ m =>+ `Hermes did not answer within ${m?.[1] ?? '?'}s. Try again; if it keeps happening, type /logs and report the last lines.`]]diff --git a/ui-tui/src/components/connectionSetupOverlay.tsx b/ui-tui/src/components/connectionSetupOverlay.tsxindex 94a2c04040a..7ed789ab65c 100644--- a/ui-tui/src/components/connectionSetupOverlay.tsx+++ b/ui-tui/src/components/connectionSetupOverlay.tsx@@ -1,5 +1,9 @@import { Box, Text, useInput } from '@hermes/ink'-import type { ConnectionOperationTarget, ConnectionRespondParams, ConnectionTargetEnvField } from '@hermes/shared/gateway-events'+import type {+ ConnectionOperationTarget,+ ConnectionRespondParams,+ ConnectionTargetEnvField+} from '@hermes/shared/gateway-events'import { useStore } from '@nanostores/react'import { useEffect, useMemo, useState } from 'react'@@ -77,7 +81,9 @@ function handleFormKey(key: InputKey, h: FormKeyHandlers): void {function AuthorizedWithoutTools({ error, t }: { error: string; t: Theme }) {return (<Box flexDirection="column">- <Text bold color={t.color.ok}>Authorized. Tools unavailable.</Text>+ <Text bold color={t.color.ok}>+ Authorized. Tools unavailable.+ </Text><Text color={t.color.muted}>{error}</Text><Text color={t.color.accent}>▸ Continue</Text><Text color={t.color.muted}>Esc close</Text>@@ -88,7 +94,9 @@ function AuthorizedWithoutTools({ error, t }: { error: string; t: Theme }) {function AwaitingBrowser({ t, target }: { t: Theme; target: ConnectionOperationTarget }) {return (<Box flexDirection="column">- <Text bold color={t.color.text}>Set up {target.name}</Text>+ <Text bold color={t.color.text}>+ Set up {target.name}+ </Text><Text color={t.color.accent}>{target.connect_url}</Text>{target.detail ? <Text color={t.color.muted}>{target.detail}</Text> : null}<Text color={t.color.muted}>Press Enter to open in browser</Text>@@ -112,7 +120,9 @@ function FieldRow({ cols, draftValue, field, focused, onChange, onSubmit, showSereturn (<Box flexDirection="column"><Text color={focused ? t.color.accent : t.color.label}>- {focused ? '▸ ' : ' '}{fieldLabel(field)}{field.required ? ' *' : ''}+ {focused ? '▸ ' : ' '}+ {fieldLabel(field)}+ {field.required ? ' *' : ''}</Text><Box paddingLeft={2}>{showSet ? (@@ -154,8 +164,14 @@ function SetupForm(p: SetupFormProps) {return (<Box flexDirection="column">- <Text bold color={t.color.text}>Set up {target.name}</Text>- {target.instructions ? <Text color={t.color.muted} wrap="wrap">{target.instructions}</Text> : null}+ <Text bold color={t.color.text}>+ Set up {target.name}+ </Text>+ {target.instructions ? (+ <Text color={t.color.muted} wrap="wrap">+ {target.instructions}+ </Text>+ ) : null}{p.fields.map((field, index) => (<FieldRowcols={p.cols}@@ -172,7 +188,7 @@ function SetupForm(p: SetupFormProps) {))}{target.state === 'failed' && target.detail ? <Text color={t.color.error}>{target.detail}</Text> : null}<Text color={p.selectorFocused ? t.color.accent : t.color.muted}>- {p.action === 0 ? '▸ ' : ' '}Connect {p.action === 1 ? '▸ ' : ' '}Cancel+ {p.action === 0 ? '▸ ' : ' '}Connect {p.action === 1 ? '▸ ' : ' '}Cancel</Text>{p.missingRequired ? <Text color={t.color.muted}>{fieldLabel(p.missingRequired)} is required.</Text> : null}{p.submitting ? <Text color={t.color.muted}>Pending…</Text> : null}@@ -216,7 +232,7 @@ export function ConnectionSetupOverlay({ cols, t }: ConnectionSetupOverlayProps)if (target?.state === 'connected') {setDraft(current =>- Object.fromEntries(fields.map(field => [field.name, field.secret ? '' : current[field.name] ?? '']))+ Object.fromEntries(fields.map(field => [field.name, field.secret ? '' : (current[field.name] ?? '')])))}}, [fields, target?.state])diff --git a/ui-tui/src/hooks/useCompletion.ts b/ui-tui/src/hooks/useCompletion.tsindex ddf71ada44c..ab1ef2650af 100644--- a/ui-tui/src/hooks/useCompletion.ts+++ b/ui-tui/src/hooks/useCompletion.ts@@ -120,7 +120,8 @@ export function useCompletion(input: string, blocked: boolean, gw: GatewayClient// Skill completions are per session: project-local skills follow the// session's repo, so the gateway must know which session is asking.const sid = getUiState().sid- const params = request.method === 'complete.slash' && sid ? { ...request.params, session_id: sid } : request.params+ const params =+ request.method === 'complete.slash' && sid ? { ...request.params, session_id: sid } : request.paramsgw.request<CompletionResponse>(request.method, params).then(raw => {