The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): bound the profile-activation half of a Bot Chat wake
Jack Lau3a50a6bea8d0
diff --git a/apps/desktop/src/sdk/index.ts b/apps/desktop/src/sdk/index.tsindex 88019d6ef7b..18bedda0094 100644--- a/apps/desktop/src/sdk/index.ts+++ b/apps/desktop/src/sdk/index.ts@@ -312,6 +312,56 @@ function waitForFocusedSessionHydration({})}+// Wait for a profile switch, but never longer than the wake budget.+//+// ensureGatewayProfile awaits the store's dial, and HermesGateway.connect() has+// no dial timeout of its own: a backend that accepts the socket and then never+// completes the handshake leaves this promise pending for the life of the+// window. That is not merely a slow open. waitForFocusedSessionHydration arms+// the only timer on this path, and it is armed AFTER this await returns - so an+// unbounded activation means the wake never settles at all, and the pane wedges+// with no error, no Retry and no timeout (#89556: `ws accepted` in the gateway+// log with no matching `ws closed`).+//+// The activation gets its OWN budget rather than sharing the hydration one. A+// cold profile backend can legitimately spend most of the hydration budget+// painting a large transcript - that race is already tight enough to lose+// (#89617) - so charging activation to the same clock would turn a wedge into a+// regression. The trade is that a wake that is slow in BOTH phases can now take+// up to twice the budget before it surfaces; that is a maintainer call and is+// called out in the PR rather than buried here.+async function awaitProfileActivation(profile: string, targetProfile: string, timeoutMs: number): Promise<void> {+ const activation = ensureGatewayProfile(profile)+ let timer: number | undefined++ try {+ await Promise.race([+ activation,+ new Promise<never>((_resolve, reject) => {+ // Same message shape as the hydration timeout on purpose: openSession's+ // catch keys the core stranded-session surface off this prefix, and a+ // wedged dial wants exactly that surface. The phase is distinguished in+ // the [bot-wake] support log, not in the user-facing string.+ timer = window.setTimeout(+ () => reject(new Error(`Timed out loading ${targetProfile}'s session history.`)),+ timeoutMs+ )+ })+ ])+ } finally {+ if (timer !== undefined) {+ window.clearTimeout(timer)+ }+ }++ // No extra catch on the abandoned dial: an in-flight activation has no+ // cancellation handle and keeps running after the budget expires, but+ // Promise.race subscribes to every input, so a rejection that lands after the+ // race has settled is already handled and cannot escape as an unhandled+ // rejection. An explicit `activation.catch()` here was dead code - verified+ // by mutation: removing it changed no test outcome.+}+export const host = {state: {/** Runtime id of the active chat session (null on a fresh draft). */@@ -511,40 +561,53 @@ export const host = {// instead of leaving us to infer it from process spawn timestamps.const wakeStartedAt = Date.now()let profileActiveAt = wakeStartedAt+ const hydrationTimeoutMs = Math.max(1, options.hydrationTimeoutMs ?? DEFAULT_SESSION_HYDRATION_TIMEOUT_MS)+ // Which half of the wake a timeout landed in. Only meaningful on the+ // failure path, where the two phases have different remedies: a stuck dial+ // is a gateway problem, a slow transcript is a backend-warmup one.+ let wakePhase: 'activation' | 'hydration' = 'activation'- if (profile && profile !== $activeGatewayProfile.get()) {- await ensureGatewayProfile(profile)- profileActiveAt = Date.now()-- if (options.keepAllProfilesScope !== false) {- setShowAllProfiles(true)+ try {+ if (profile && profile !== $activeGatewayProfile.get()) {+ // Bounded only on the hydration contract, which is where a budget and a+ // Retry surface both already exist. A plain open never asked for a+ // deadline and has nowhere to render one, so it keeps today's+ // behaviour rather than gaining a rejection its callers cannot handle.+ await (options.awaitHydration+ ? awaitProfileActivation(profile, targetProfile, hydrationTimeoutMs)+ : ensureGatewayProfile(profile))+ profileActiveAt = Date.now()++ if (options.keepAllProfilesScope !== false) {+ setShowAllProfiles(true)+ }}- }- if (generation !== openSessionGeneration) {- throw new Error('Session open was superseded by a newer selection.')- }+ wakePhase = 'hydration'- if (options.awaitHydration) {- // Keep the target-specific overlay visible through transcript hydration,- // not merely through the gateway/profile activation that precedes it.- $gatewaySwapTarget.set(targetProfile)- }+ if (generation !== openSessionGeneration) {+ throw new Error('Session open was superseded by a newer selection.')+ }++ if (options.awaitHydration) {+ // Keep the target-specific overlay visible through transcript hydration,+ // not merely through the gateway/profile activation that precedes it.+ $gatewaySwapTarget.set(targetProfile)+ }- try {openSession(- storedSessionId,- (to: string, opts?: { replace?: boolean }) => {- const target = to.startsWith('#') ? to : `#${to}`-- if (opts?.replace) {- window.location.replace(target)- } else {- window.location.hash = target- }- },- options.intent ?? 'in-place'- )+ storedSessionId,+ (to: string, opts?: { replace?: boolean }) => {+ const target = to.startsWith('#') ? to : `#${to}`++ if (opts?.replace) {+ window.location.replace(target)+ } else {+ window.location.hash = target+ }+ },+ options.intent ?? 'in-place'+ )// Judge the main surface AFTER the open: on a cold start the persisted// route can already point at this session while selection has not@@ -571,7 +634,7 @@ export const host = {generation,profile: targetProfile,storedSessionId,- timeoutMs: Math.max(1, options.hydrationTimeoutMs ?? DEFAULT_SESSION_HYDRATION_TIMEOUT_MS)+ timeoutMs: hydrationTimeoutMs})}} catch (error) {@@ -581,10 +644,13 @@ export const host = {error instanceof Error &&error.message.startsWith('Timed out loading ')) {+ const timedOutAt = Date.now()+console.warn('[bot-wake] hydration timed out', {- hydrationWaitMs: Date.now() - profileActiveAt,+ hydrationWaitMs: wakePhase === 'hydration' ? timedOutAt - profileActiveAt : 0,+ phase: wakePhase,profile: targetProfile,- profileActivationMs: profileActiveAt - wakeStartedAt,+ profileActivationMs: (wakePhase === 'activation' ? timedOutAt : profileActiveAt) - wakeStartedAt,runtimeBound: Boolean($activeSessionId.get()),selectionSettled: $selectedStoredSessionId.get() === storedSessionId,storedSessionId,diff --git a/apps/desktop/src/sdk/profile-routing.test.ts b/apps/desktop/src/sdk/profile-routing.test.tsindex da517a37306..c96d47479c9 100644--- a/apps/desktop/src/sdk/profile-routing.test.ts+++ b/apps/desktop/src/sdk/profile-routing.test.ts@@ -307,8 +307,12 @@ describe('profile-aware plugin session opens', () => {resolved = true})- await Promise.resolve()- await Promise.resolve()+ // Flush a macrotask rather than counting microtask ticks: the profile+ // activation is now a bounded race, so the number of awaits between the+ // call and the core open is an implementation detail, and `resolved`+ // staying false through a full turn of the event loop is the stronger+ // assertion anyway.+ await new Promise(resolve => setTimeout(resolve, 0))expect(openSessionCore).toHaveBeenCalledWith('bot-chat', expect.any(Function), 'in-place')expect(resolved).toBe(false)@@ -356,8 +360,7 @@ describe('profile-aware plugin session opens', () => {hydrationTimeoutMs: 1_000})- await Promise.resolve()- await Promise.resolve()+ await new Promise(resolve => setTimeout(resolve, 0))// The old pre-open "already selected" precondition skipped this request,// stranding the pane blank until timeout. It must fire now.@@ -504,4 +507,167 @@ describe('profile-aware plugin session opens', () => {expect($selectedStoredSessionId.get()).toBe('chat-b')expect($gatewaySwapTarget.get()).toBeNull()})+++ it('surfaces a wedged profile activation instead of waiting on it forever (#89556)', async () => {+ // 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+ // hydration timer, which is armed downstream, never got a chance to fire:+ // the pane wedged with no error and no Retry rather than timing out.+ vi.mocked(ensureGatewayProfile).mockImplementationOnce(() => new Promise<void>(() => undefined))++ setMockAtom($selectedStoredSessionId, 'wedged-chat')+ setMockAtom($activeSessionId, 'runtime-wedged')+ setMockAtom($messages, [{ id: 'history-1', parts: [], role: 'user' }] as never)++ await expect(+ host.openSession('wedged-chat', {+ profile: 'medicina',+ intent: 'main',+ awaitHydration: true,+ expectHistory: true,+ hydrationTimeoutMs: 60+ })+ ).rejects.toThrow("Timed out loading medicina's session history.")++ // The stranded-session surface is the point: a bounded failure the user can+ // retry, not a frozen pane.+ expect(setResumeExhaustedSessionId).toHaveBeenCalledWith('wedged-chat')+ expect($gatewaySwapTarget.get()).toBeNull()+ })++ it('names the phase in the wake log so a stuck dial is not read as a slow transcript', async () => {+ const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined)++ vi.mocked(ensureGatewayProfile).mockImplementationOnce(() => new Promise<void>(() => undefined))++ await expect(+ host.openSession('wedged-chat', {+ profile: 'medicina',+ intent: 'main',+ awaitHydration: true,+ expectHistory: true,+ hydrationTimeoutMs: 60+ })+ ).rejects.toThrow('Timed out loading ')++ expect(warn).toHaveBeenCalledWith('[bot-wake] hydration timed out', expect.objectContaining({ phase: 'activation' }))++ const payload = warn.mock.calls.at(-1)?.[1] as { hydrationWaitMs: number; profileActivationMs: number }++ // The whole budget went to activation. Reporting it as hydration wait time+ // would send a support bundle reader looking at transcript size.+ expect(payload.profileActivationMs).toBeGreaterThan(0)+ expect(payload.hydrationWaitMs).toBe(0)++ warn.mockRestore()+ })++ it('gives hydration its own full budget after a slow but successful activation', async () => {+ // Guards the choice of a SEPARATE budget per phase over one shared clock.+ // A cold profile backend can legitimately spend most of the budget getting+ // its socket up; if hydration then inherited what was left, this wake would+ // fail even though the transcript painted well inside the documented+ // 20s-equivalent window.+ vi.mocked(ensureGatewayProfile).mockImplementationOnce(+ async (target: null | string | undefined) =>+ new Promise<void>(resolve => {+ setTimeout(() => {+ $activeGatewayProfile.set(target || 'default')+ resolve()+ }, 150)+ })+ )++ const opening = host.openSession('slow-dial-chat', {+ profile: 'medicina',+ intent: 'main',+ awaitHydration: true,+ expectHistory: true,+ hydrationTimeoutMs: 200+ })++ // 300ms total is past a single shared 200ms budget and inside hydration's+ // own one, which only starts once the profile is actually active.+ await new Promise(resolve => setTimeout(resolve, 300))+ setMockAtom($selectedStoredSessionId, 'slow-dial-chat')+ setMockAtom($activeSessionId, 'runtime-medicina')+ setMockAtom($messages, [{ id: 'history-1', parts: [], role: 'user' }] as never)++ await expect(opening).resolves.toBeUndefined()+ expect(setResumeExhaustedSessionId).not.toHaveBeenCalled()+ })++ it('absorbs an activation that rejects after its budget has already expired', async () => {+ // The abandoned race loser keeps running - there is no cancellation handle+ // for an in-flight dial - so a late rejection must not escape as an+ // unhandled promise rejection long after the caller gave up.+ // Node's process-level hook, not window's: under jsdom a rejection that+ // escapes lands on the runner's process, which is where vitest turns it+ // into an "Unhandled Rejection" run failure.+ const unhandled: unknown[] = []++ const onUnhandled = (reason: unknown) => {+ unhandled.push(reason)+ }++ const existing = process.listeners('unhandledRejection')++ for (const listener of existing) {+ process.off('unhandledRejection', listener)+ }++ process.on('unhandledRejection', onUnhandled)++ vi.mocked(ensureGatewayProfile).mockImplementationOnce(+ () =>+ new Promise<void>((_resolve, reject) => {+ setTimeout(() => reject(new Error('dial failed after the caller gave up')), 120)+ })+ )++ await expect(+ host.openSession('late-failure-chat', {+ profile: 'medicina',+ intent: 'main',+ awaitHydration: true,+ expectHistory: true,+ hydrationTimeoutMs: 40+ })+ ).rejects.toThrow('Timed out loading ')++ await new Promise(resolve => setTimeout(resolve, 200))+ process.off('unhandledRejection', onUnhandled)++ for (const listener of existing) {+ process.on('unhandledRejection', listener)+ }++ expect(unhandled).toEqual([])+ })++ it('leaves a plain open unbounded, because it has no budget and no Retry surface', async () => {+ // Deliberate scope line, not an oversight: the activation deadline rides on+ // the same contract as the hydration one. A caller that never passed+ // awaitHydration gets exactly the behaviour it had before, since a+ // rejection here would surface to code with nowhere to render it.+ vi.mocked(ensureGatewayProfile).mockImplementationOnce(() => new Promise<void>(() => undefined))++ let settled = 'pending'++ void host.openSession('plain-chat', { profile: 'medicina', intent: 'main', hydrationTimeoutMs: 40 }).then(+ () => {+ settled = 'resolved'+ },+ () => {+ settled = 'rejected'+ }+ )++ await new Promise(resolve => setTimeout(resolve, 200))++ expect(settled).toBe('pending')+ expect(setResumeExhaustedSessionId).not.toHaveBeenCalled()+ })})