From cf7003f3fa650e2cebc06a0af0c09dabaf5ee367 Mon Sep 17 00:00:00 2001 From: Gille <4317663+helix4u@users.noreply.github.com> Date: Wed, 4 Nov 2026 12:07:00 -0700 Subject: [PATCH] fix(desktop): persist Bot Chat wake diagnostics --- apps/desktop/electron/renderer-log.test.ts | 43 ++++++++++++++++ apps/desktop/electron/renderer-log.ts | 17 +++++-- apps/desktop/src/sdk/bot-wake-log.ts | 8 +++ apps/desktop/src/sdk/index.ts | 5 +- apps/desktop/src/sdk/profile-routing.test.ts | 52 ++++++++++++++++++-- 5 files changed, 115 insertions(+), 10 deletions(-) create mode 100644 apps/desktop/src/sdk/bot-wake-log.ts diff --git a/apps/desktop/electron/renderer-log.test.ts b/apps/desktop/electron/renderer-log.test.ts index f955fc97e9..d0e799637f 100644 --- a/apps/desktop/electron/renderer-log.test.ts +++ b/apps/desktop/electron/renderer-log.test.ts @@ -1,5 +1,10 @@ +import { appendFileSync, mkdtempSync, readFileSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join } from 'node:path' + import { describe, expect, it, vi } from 'vitest' +import { formatDesktopLogLine } from './desktop-log-line' import { attachRendererConsoleCapture, formatRendererBoundaryReport, formatRendererConsoleLine } from './renderer-log' type ConsoleMessageEvent = { @@ -47,6 +52,44 @@ describe('formatRendererConsoleLine', () => { }) describe('attachRendererConsoleCapture', () => { + it('writes serialized wake diagnostics to desktop.log without admitting other warnings', () => { + const directory = mkdtempSync(join(tmpdir(), 'wake-log-')) + const file = join(directory, 'desktop.log') + const capture = createWindowHarness() + + const diagnostic = { + attempts: 3, + phase: 'hydration', + profile: 'tom', + runtimeBound: false, + selectionSettled: true, + storedSessionId: 'bot-chat-tom', + transcriptPainted: false + } + + try { + attachRendererConsoleCapture(capture.win, 'session-window', line => { + appendFileSync(file, `${formatDesktopLogLine(line)}\n`) + }) + capture.getHandler()?.({ + level: 'warning', + message: `[bot-wake] hydration timed out ${JSON.stringify(diagnostic)}`, + sourceId: 'file:///app/index.js', + lineNumber: 42 + }) + capture.getHandler()?.({ level: 'warning', message: 'unrelated warning', sourceId: 'src', lineNumber: 1 }) + capture.getHandler()?.({ level: 'info', message: '[bot-wake] quiet', sourceId: 'src', lineNumber: 1 }) + + const lines = readFileSync(file, 'utf8').trim().split('\n') + + expect(lines).toHaveLength(1) + expect(lines[0]).toContain('[renderer console:session-window] [bot-wake] hydration timed out ') + expect(JSON.parse(lines[0]!.split('hydration timed out ')[1]!.split(' (file:')[0]!)).toEqual(diagnostic) + } finally { + rmSync(directory, { recursive: true, force: true }) + } + }) + it('registers a single-argument listener, logs errors, and skips the rest', () => { const log = vi.fn() const capture = createWindowHarness() diff --git a/apps/desktop/electron/renderer-log.ts b/apps/desktop/electron/renderer-log.ts index e143c4a981..53ec311d26 100644 --- a/apps/desktop/electron/renderer-log.ts +++ b/apps/desktop/electron/renderer-log.ts @@ -59,20 +59,27 @@ function isConsoleMessageDetails(value: unknown): value is ConsoleMessageDetails ) } -/** Format Electron's canonical console-message event object into one line, or - * null for non-error or malformed events. Hermes's pinned Electron line - * puts severity and source metadata on the event object itself; accepting one +/** Format errors and Bot Chat wake warnings into one line, or null otherwise. + * Hermes's pinned Electron line puts severity and source metadata on the + * event object itself; accepting one * listener argument also avoids Electron's deprecated positional * `(event, level, message, line, sourceId)` path. */ export function formatRendererConsoleLine(label: string, details: ConsoleMessageEventLike): string | null { - if (!isConsoleMessageDetails(details) || details.level !== 'error') { + if (!isConsoleMessageDetails(details)) { + return null + } + + // Retain the existing quiet console policy outside this support diagnostic. + const isWakeWarning = details.level === 'warning' && details.message.startsWith('[bot-wake] ') + + if (details.level !== 'error' && !isWakeWarning) { return null } return `[renderer console:${label}] ${details.message} (${details.sourceId}:${String(details.lineNumber)})` } -/** Attach the error-level console hook to a renderer window. `log` is the +/** Attach the diagnostic console hook to a renderer window. `log` is the * desktop.log sink (rememberLog in main.ts). */ export function attachRendererConsoleCapture(win: WindowLike, label: string, log: (line: string) => void): void { win.webContents.on('console-message', event => { diff --git a/apps/desktop/src/sdk/bot-wake-log.ts b/apps/desktop/src/sdk/bot-wake-log.ts new file mode 100644 index 0000000000..9e855a700e --- /dev/null +++ b/apps/desktop/src/sdk/bot-wake-log.ts @@ -0,0 +1,8 @@ +/** Electron flattens console arguments, so keep wake fields in the message itself. + * The renderer console capture persists only this warning namespace to desktop.log. */ +export function logBotWake( + message: 'hydration timed out' | 'hydration timed out, retrying', + details: Record +): void { + console.warn(`[bot-wake] ${message} ${JSON.stringify(details)}`) +} diff --git a/apps/desktop/src/sdk/index.ts b/apps/desktop/src/sdk/index.ts index 19e7dc97ef..72b6f1fd6d 100644 --- a/apps/desktop/src/sdk/index.ts +++ b/apps/desktop/src/sdk/index.ts @@ -107,6 +107,7 @@ import type { PaginatedSessions, UsageStats } from '@/types/hermes' import type { SessionMutationSnapshot } from '../../../shared/src/session-http-mutations' +import { logBotWake } from './bot-wake-log' import { pluginDecisions, profiles, skills, toolsets } from './bridge' import { composerHost } from './composer' import { i18nHost } from './i18n' @@ -1115,7 +1116,7 @@ export const host = { // Logged per attempt so a support bundle shows the retry happened at // all; the terminal failure is reported once by the catch below. - console.warn('[bot-wake] hydration timed out, retrying', { + logBotWake('hydration timed out, retrying', { attempt, hydrationWaitMs: Date.now() - profileActiveAt, profile: targetProfile, @@ -1132,7 +1133,7 @@ export const host = { ) { const timedOutAt = Date.now() - console.warn('[bot-wake] hydration timed out', { + logBotWake('hydration timed out', { attempts: wakePhase === 'hydration' ? maxAttempts : 1, hydrationWaitMs: wakePhase === 'hydration' ? timedOutAt - profileActiveAt : 0, phase: wakePhase, diff --git a/apps/desktop/src/sdk/profile-routing.test.ts b/apps/desktop/src/sdk/profile-routing.test.ts index 7cd9d96a82..fa78705699 100644 --- a/apps/desktop/src/sdk/profile-routing.test.ts +++ b/apps/desktop/src/sdk/profile-routing.test.ts @@ -193,6 +193,7 @@ const profile = (name: string): ProfileInfo => ({ }) afterEach(() => { + vi.restoreAllMocks() vi.clearAllMocks() vi.mocked(sessionTileDelegate).mockReturnValue(null) vi.mocked(activeGatewayConnectionId).mockReturnValue('local') @@ -344,14 +345,20 @@ describe('connection-aware plugin host APIs', () => { }) ) expect(hermesApi).toHaveBeenNthCalledWith(2, { - connectionId: 'source-a', path: '/api/sessions/bot-chat/mutation-snapshot?profile=backend-worker' + connectionId: 'source-a', + path: '/api/sessions/bot-chat/mutation-snapshot?profile=backend-worker' }) expect(hermesApi).toHaveBeenNthCalledWith(3, { connectionId: 'source-a', path: '/api/sessions/bot-chat', method: 'PATCH', - body: { hidden: true, profile: 'backend-worker', expected_revision: 31, - expected_generation: 5, request_id: expect.any(String) } + body: { + hidden: true, + profile: 'backend-worker', + expected_revision: 31, + expected_generation: 5, + request_id: expect.any(String) + } }) expect(vi.mocked(hermesApi).mock.calls.every(([request]) => !('profile' in request))).toBe(true) expect(requestGatewayForAgent).not.toHaveBeenCalled() @@ -1027,6 +1034,8 @@ describe('profile-aware plugin session opens', () => { }) it('retries a Bot Chat hydration timeout once without ever arming the Retry surface (#89617)', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + $activeGatewayProfile.set('hyoseob') // First attempt: leave the surface unhealthy so the hydration wait below @@ -1059,9 +1068,12 @@ describe('profile-aware plugin session opens', () => { // call clears it for the currently-routed session. expect(setResumeExhaustedSessionId).not.toHaveBeenCalled() expect($gatewaySwapTarget.get()).toBeNull() + expect(warn).toHaveBeenCalledExactlyOnceWith(expect.stringContaining('[bot-wake] hydration timed out, retrying ')) }) it('still arms the Retry surface when a retried Bot Chat hydration times out twice', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + $activeGatewayProfile.set('hyoseob') await expect( @@ -1077,6 +1089,26 @@ describe('profile-aware plugin session opens', () => { expect(openSessionCore).toHaveBeenCalledTimes(2) expect(setResumeExhaustedSessionId).toHaveBeenCalledWith('stranded-bot-chat') expect($gatewaySwapTarget.get()).toBeNull() + expect(warn).toHaveBeenCalledTimes(2) + + const [retry, failure] = warn.mock.calls + + expect(retry).toHaveLength(1) + expect(failure).toHaveLength(1) + expect(JSON.parse(String(retry![0]).split('retrying ')[1]!)).toMatchObject({ + attempt: 1, + profile: 'hyoseob', + storedSessionId: 'stranded-bot-chat' + }) + expect(JSON.parse(String(failure![0]).split('timed out ')[1]!)).toMatchObject({ + attempts: 2, + phase: 'hydration', + profile: 'hyoseob', + runtimeBound: false, + selectionSettled: false, + storedSessionId: 'stranded-bot-chat', + transcriptPainted: false + }) }) it('lets the latest rapid bot selection win and cancels the older hydration wait', async () => { @@ -1190,6 +1222,8 @@ describe('profile-aware plugin session opens', () => { }) it('surfaces a wedged profile activation instead of waiting on it forever (#89556)', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined) + // The dial the store is waiting on never settles - a backend that accepts // the socket and then never completes the handshake. Before this was // bounded, openSession's await sat here for the life of the window and the @@ -1216,6 +1250,18 @@ describe('profile-aware plugin session opens', () => { // retry, not a frozen pane. expect(setResumeExhaustedSessionId).toHaveBeenCalledWith('wedged-chat') expect($gatewaySwapTarget.get()).toBeNull() + expect(warn).toHaveBeenCalledTimes(1) + expect(warn.mock.calls[0]).toHaveLength(1) + expect(JSON.parse(String(warn.mock.calls[0]![0]).split('timed out ')[1]!)).toMatchObject({ + attempts: 1, + hydrationWaitMs: 0, + phase: 'activation', + profile: 'medicina', + runtimeBound: true, + selectionSettled: true, + storedSessionId: 'wedged-chat', + transcriptPainted: true + }) }) it('gives hydration its own full budget after a slow but successful activation', async () => {