The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): background Bot Chat re-resumes never navigate
Brooklyn Nicholson68a9817b57ca
diff --git a/apps/desktop/src/plugins/hermes-bots/bot-row-opens-canonical-chat.test.ts b/apps/desktop/src/plugins/hermes-bots/bot-row-opens-canonical-chat.test.tsindex 67d05b95849..a7350ac7c8f 100644--- a/apps/desktop/src/plugins/hermes-bots/bot-row-opens-canonical-chat.test.ts+++ b/apps/desktop/src/plugins/hermes-bots/bot-row-opens-canonical-chat.test.ts@@ -87,7 +87,12 @@ describe('a row click lands on the canonical chat, never a remembered side tab',try {await expect(openRosterBot(canonicalBot)).resolves.toBe(true)- expect(openBotCanonicalChat).toHaveBeenCalledWith(canonicalBot, expect.any(Function))+ expect(openBotCanonicalChat).toHaveBeenCalledWith(+ canonicalBot,+ // A fronting refresh re-pulls the transcript without navigating —+ // background: true threads refreshInPlace (issue 121874).+ { background: true, openingStillCurrent: expect.any(Function) }+ )} finally {busy.mockRestore()$selectedStoredSessionId.set(null)@@ -102,7 +107,7 @@ describe('a row click lands on the canonical chat, never a remembered side tab',await expect(openRosterBot(canonicalBot)).resolves.toBe(true)- expect(openBotCanonicalChat).toHaveBeenCalledWith(canonicalBot, expect.any(Function))+ expect(openBotCanonicalChat).toHaveBeenCalledWith(canonicalBot, { openingStillCurrent: expect.any(Function) })expect($openBotChat.get()?.openedSessionId).toBe('bot-chat-tip')})diff --git a/apps/desktop/src/plugins/hermes-bots/canonical-chat.ts b/apps/desktop/src/plugins/hermes-bots/canonical-chat.tsindex 9bde0b75eda..04e8dfea288 100644--- a/apps/desktop/src/plugins/hermes-bots/canonical-chat.ts+++ b/apps/desktop/src/plugins/hermes-bots/canonical-chat.ts@@ -79,10 +79,19 @@ export function isCanonicalChatOnScreen(return [canonical.id, canonical.resolved_id].filter(Boolean).map(String).includes(String(storedSessionId))}+interface OpenStoredBotChatOptions {+ /** Background re-resume: thread refreshInPlace to host.openSession so the+ * refresh never navigates (issue 121874). Await the transcript refresh+ * only for explicit opens — a background wake resolves once the resume+ * is requested, never blocking on a cold backend. */+ background?: boolean+}+async function openStoredBotChat(owner: RosterRow | string,storedId: string,- summary: CanonicalChatRow+ summary: CanonicalChatRow,+ { background = false }: OpenStoredBotChatOptions = {}): Promise<string> {if (!storedId || typeof host.openSession !== 'function') {throw new Error('This Hermes Desktop version cannot open stored sessions')@@ -128,11 +137,12 @@ async function openStoredBotChat(// the reason this stopped being `main`); it just loads into main instead of// minting a second tab when there is nothing to front.intent: 'in-place',- awaitHydration: true,+ awaitHydration: !background,expectHistory,forceResume: true,hydrationTimeoutMs,keepAllProfilesScope: true,+ ...(background ? { refreshInPlace: true } : {}),workspaceMode: 'bots',workspaceOwnerKey: ownerKey,retryHydrationTimeoutOnce: true,@@ -294,6 +304,18 @@ interface CreateCanonicalChatOptions {openingStillCurrent?: (() => boolean) | null}+interface OpenCanonicalChatOptions {+ /** Re-resolve and REFRESH the open chat without any navigation: the wake+ * was triggered by a background event (session.reclaimed, roster+ * activity), and a background event must never take the route or the+ * foreground away from whatever the user is reading (issue 121874 —+ * /kanban was replaced by the Bot Chat route). Threaded to+ * host.openSession's refreshInPlace; without an SDK that supports it the+ * open degrades to the old navigating shape. */+ background?: boolean+ openingStillCurrent?: (() => boolean) | null+}+/** The self-introduction a brand-new bot is born with (#91827).** Localized because it is the FIRST line of the forever-chat: shipped in@@ -546,7 +568,7 @@ export function createCanonicalChat(* bot's chat opens without re-homing Desktop's chrome. */export async function openBotCanonicalChat(owner: RosterRow | string,- openingStillCurrent: (() => boolean) | null = null+ { background = false, openingStillCurrent = null }: OpenCanonicalChatOptions = {}): Promise<{ openedId: string; registryId: string } | null> {const existing = await findExistingCanonicalChat(owner)@@ -556,7 +578,7 @@ export async function openBotCanonicalChat(}const openedId = existing.resolved_id || existing.id- await openStoredBotChat(owner, openedId, existing)+ await openStoredBotChat(owner, openedId, existing, { background })// Both identities matter downstream: the durable registry row names the// chat; the resolved lineage tip is what actually takes session focus.@@ -568,6 +590,13 @@ export async function openBotCanonicalChat(}}+ // A background re-resume never MINTS: it fires while nobody asked for this+ // bot, so a resolution miss keeps whatever the user is looking at instead+ // of creating a fresh forever-chat under their feet.+ if (background) {+ return null+ }+const created = await createCanonicalChat(owner, {openingStillCurrent})diff --git a/apps/desktop/src/plugins/hermes-bots/plugin.tsx b/apps/desktop/src/plugins/hermes-bots/plugin.tsxindex 3c2a68e5d54..18eaefff83b 100644--- a/apps/desktop/src/plugins/hermes-bots/plugin.tsx+++ b/apps/desktop/src/plugins/hermes-bots/plugin.tsx@@ -645,6 +645,11 @@ export default {// a failed re-resume (backend still down) leaves the lazy recovery on// next send as the backstop. Feature-detected — older shells have no// host.onEvent.+ //+ // This is a BACKGROUND wake: it refreshes in place (refreshInPlace+ // through openBotCanonicalChat) and never navigates, so a user+ // reading the Kanban board — or any other route — keeps their view+ // (issue 121874).const stopReclaimSync =typeof host.onEvent === 'function'? host.onEvent('session.reclaimed', event => {@@ -677,7 +682,7 @@ export default {}const generation = getBotOpenGeneration()- void openBotCanonicalChat(bot)+ void openBotCanonicalChat(bot, { background: true }).then(opened => {// A user action while the re-resume ran owns the center now.if (!opened || generation !== getBotOpenGeneration()) {diff --git a/apps/desktop/src/plugins/hermes-bots/reclaim-refresh-in-place.test.ts b/apps/desktop/src/plugins/hermes-bots/reclaim-refresh-in-place.test.tsnew file mode 100644index 00000000000..d056a300a8c--- /dev/null+++ b/apps/desktop/src/plugins/hermes-bots/reclaim-refresh-in-place.test.ts@@ -0,0 +1,195 @@+/**+ * The `session.reclaimed` listener's re-resume is a BACKGROUND refresh —+ * issue 121874.+ *+ * When the gateway reaps the runtime behind the OPEN bot chat, the plugin+ * re-resolves the canonical chat so the user's next send doesn't eat the+ * stale-id error. That re-resume used to be a full navigating open: with the+ * user reading the Kanban board (or any other route), the route flipped to+ * the Bot Chat, hijacking the foreground. "Offer; don't hijack"+ * (apps/desktop/AGENTS.md): a background event must never navigate.+ *+ * This pins the listener's contract through the real `plugin.register()`:+ * - a reclaim for the open claim re-resolves with `background: true` (the+ * refreshInPlace open — no navigation, no tile minting);+ * - a reclaim for some other session leaves the claim alone;+ * - the claim's identities update when the re-resolve reports new ones.+ */++import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'++import type * as I18nModule from './i18n'+import type { RosterRow } from './types'++const { openBotCanonicalChat, onEvent } = vi.hoisted(() => ({+ onEvent: vi.fn((_type: string, listener: (event: { payload?: unknown }) => void) => {+ listeners.push(listener)++ return () => undefined+ }),+ openBotCanonicalChat: vi.fn(async () => ({ openedId: 'bot-chat-tip', registryId: 'bot-chat' }))+}))++const listeners: Array<(event: { payload?: unknown }) => void> = []++vi.mock('@hermes/plugin-sdk', async () => {+ const { atom } = await import('nanostores')++ const stub: unknown = new Proxy(function stubbed() {}, {+ apply: () => stub,+ get: (_target, key) => (key === 'then' ? undefined : stub),+ has: () => true+ })++ const hostMock = {+ onEvent,+ paneVisibility: vi.fn(() => ({ get: () => false, listen: () => () => undefined })),+ request: vi.fn(async () => ({})),+ state: {+ focusedStoredSessionId: { get: () => null, listen: () => () => undefined },+ gateway: { get: () => 'open', listen: () => () => undefined },+ profile: { get: () => 'default', listen: () => () => undefined }+ }+ }++ const known: Record<string, unknown> = { atom, host: hostMock }++ return new Proxy(known, {+ get: (target, key) =>+ typeof key === 'symbol' || key in target ? target[key as string] : key === 'then' ? undefined : stub,+ has: () => true+ })+})++vi.mock('./avatar', () => ({ startFaceClock: vi.fn(), stopFaceClock: vi.fn() }))+vi.mock('./canonical-chat', () => ({+ CANONICAL_CHAT_TITLE: 'Bot Chat',+ isCanonicalChatOnScreen: vi.fn(() => false),+ notifyBotOpenFailure: vi.fn(),+ openBotCanonicalChat+}))+vi.mock('./chat-empty', () => ({ BotChatEmpty: () => null }))+vi.mock('./relay', () => ({ startBotRelay: vi.fn(), stopBotRelay: vi.fn() }))+vi.mock('./session-sweep', () => ({ startHideSweepScheduler: vi.fn() }))+vi.mock('./cron', () => ({ bindProfileSync: () => () => undefined, RoutinesPane: () => null }))+vi.mock('./screen-autoraise', () => ({ startScreenAutoRaise: vi.fn(() => () => undefined) }))+vi.mock('./hygiene', () => ({ annotateOrphanedGroupChatMembers: () => ({ changed: false, rooms: {} }) }))+vi.mock('./group-chat', async () => {+ const { atom: nanoAtom } = await import('nanostores')++ return {+ $groupChats: nanoAtom({}),+ $groupChatWorkspace: nanoAtom(null),+ assignLegacyThreads: (log: unknown[]) => log,+ handleSessionsGatewayTransition: vi.fn(),+ hydrateGroupChatTombstones: vi.fn(async () => undefined),+ pullGroupChatServerState: async () => false,+ scheduleGroupChatServerSync: vi.fn(),+ setGroupChatSyncDisposed: vi.fn(),+ stopGroupChatServerSync: vi.fn(),+ sweepGroupChatMembersForRemovedConnection: vi.fn(),+ updateGroupChat: vi.fn()+ }+})+vi.mock('./user-sections', () => ({ loadBotSections: vi.fn() }))+vi.mock('./data', async () => {+ const { atom: nanoAtom } = await import('nanostores')++ return {+ $botMeta: nanoAtom({}),+ $lastRoster: nanoAtom<RosterRow[]>([]),+ botHandle: (name: string) => name,+ botMentionTag: (name: string) => name,+ botRosterKey: (bot: { connectionId?: string; name?: string } | null | undefined) =>+ `${bot?.connectionId || 'legacy'}::${bot?.name || 'default'}`,+ botSelectionKey: (bot: RosterRow) => bot.name,+ cachedUnionRoster: () => null,+ isActiveRosterBot: () => false,+ migrateBotMeta: vi.fn(async () => undefined),+ primeRoster: vi.fn(async () => undefined),+ resolveRosterMentions: vi.fn(() => ({}))+ }+})+vi.mock('./i18n', async importOriginal => {+ const actual = await importOriginal<typeof I18nModule>()++ return { ...actual, BOTS_LOCALES: {} }+})+const plugin = (await import('./plugin')).default++const { $openBotChat, $selectedRosterKey } = await import('./bot-state')+const { $lastRoster } = await import('./data')++const BOT: RosterRow = { connectionId: 'local', name: 'alpha' } as RosterRow++/** Register the real plugin; the stubbed SDK records the reclaim listener. */+function register() {+ listeners.length = 0++ try {+ plugin.register({+ i18n: { register: () => () => undefined },+ onDispose: () => undefined,+ register: () => () => undefined,+ storage: { get: async () => undefined, set: async () => undefined }+ } as never)+ } catch {+ // Registration walks UI surfaces the stub does not model; the listener+ // registered before any throw is what these tests drive.+ }+}++const reclaim = (storedSessionId: string) => ({+ payload: { session_id: 'runtime-x', stored_session_id: storedSessionId },+ type: 'session.reclaimed'+})++beforeAll(async () => {+ await import('./plugin')+}, 120_000)++beforeEach(() => {+ vi.clearAllMocks()+ openBotCanonicalChat.mockClear()+ openBotCanonicalChat.mockResolvedValue({ openedId: 'bot-chat-tip', registryId: 'bot-chat' })+ listeners.length = 0+ $openBotChat.set(null)+ $selectedRosterKey.set('local::alpha')+ $lastRoster.set([BOT])+ register()+})++describe("session.reclaimed re-resumes the open Bot Chat WITHOUT navigating (issue 121874)", () => {+ it('re-resumes the claimed chat as a background refresh', async () => {+ $openBotChat.set({ key: 'local::alpha', openedRegistryId: 'bot-chat', openedSessionId: 'bot-chat-tip' })++ listeners.forEach(listener => listener(reclaim('bot-chat')))++ expect(openBotCanonicalChat).toHaveBeenCalledTimes(1)+ // THE contract: the re-resume is background — refreshInPlace, never a+ // navigating open that would replace /kanban or any other route.+ expect(openBotCanonicalChat).toHaveBeenCalledWith(BOT, { background: true })+ })++ it('ignores a reclaim for a session the claim does not own', async () => {+ $openBotChat.set({ key: 'local::alpha', openedRegistryId: 'bot-chat', openedSessionId: 'bot-chat-tip' })++ listeners.forEach(listener => listener(reclaim('someone-elses-session')))++ expect(openBotCanonicalChat).not.toHaveBeenCalled()+ })++ it('keeps the claim current when the re-resume reports rotated identities', async () => {+ $openBotChat.set({ key: 'local::alpha', openedRegistryId: 'bot-chat', openedSessionId: 'bot-chat-tip' })+ openBotCanonicalChat.mockResolvedValueOnce({ openedId: 'tip-2', registryId: 'reg-2' })++ listeners.forEach(listener => listener(reclaim('bot-chat')))+ await Promise.resolve()++ expect($openBotChat.get()).toEqual({+ key: 'local::alpha',+ openedRegistryId: 'reg-2',+ openedSessionId: 'tip-2'+ })+ })+})diff --git a/apps/desktop/src/plugins/hermes-bots/roster-actions.ts b/apps/desktop/src/plugins/hermes-bots/roster-actions.tsindex d2ddec81391..acbe7fbdace 100644--- a/apps/desktop/src/plugins/hermes-bots/roster-actions.ts+++ b/apps/desktop/src/plugins/hermes-bots/roster-actions.ts@@ -139,7 +139,12 @@ export function trackInboundActivity(roster: RosterRow[]) {* forceResume re-pulls the transcript. Only while that chat is the FOCUSED* session — a group room or another tab owning the center must not be* yanked away by background activity — and never mid-turn, when the- * activity is the turn itself, already streaming. */+ * activity is the turn itself, already streaming.+ *+ * BACKGROUND wake: passed through as `background` so the refresh runs+ * refreshInPlace and never navigates — this fires on roster activity,+ * not a user gesture, so whatever route is showing stays showing (issue+ * 121874). */function refreshOpenBotChat(bot: RosterRow, { allowWhileBusy = false }: { allowWhileBusy?: boolean } = {}) {const canonicalIds = [bot.canonical_session?.id, bot.canonical_session?.resolved_id].filter(Boolean).map(String)const focused = String(host.state.focusedStoredSessionId?.get?.() || '')@@ -149,7 +154,7 @@ function refreshOpenBotChat(bot: RosterRow, { allowWhileBusy = false }: { allowW}const generation = getBotOpenGeneration()- void openBotCanonicalChat(bot, () => generation === getBotOpenGeneration()).catch(() => {+ void openBotCanonicalChat(bot, { background: true, openingStillCurrent: () => generation === getBotOpenGeneration() }).catch(() => {/* the next click or reclaim event re-resolves it */})}@@ -317,7 +322,7 @@ export async function openRosterBot(bot: RosterRow): Promise<boolean> {}try {- const opened = await openBotCanonicalChat(bot, () => generation === getBotOpenGeneration())+ const opened = await openBotCanonicalChat(bot, { openingStillCurrent: () => generation === getBotOpenGeneration() })if (generation !== getBotOpenGeneration()) {settlePendingBotOpen(generation)diff --git a/apps/desktop/src/sdk/index.ts b/apps/desktop/src/sdk/index.tsindex 7579b1d36e7..b67078b7058 100644--- a/apps/desktop/src/sdk/index.ts+++ b/apps/desktop/src/sdk/index.ts@@ -392,6 +392,19 @@ export interface PluginOpenSessionOptions {hydrationTimeoutMs?: numberintent?: OpenSessionIntentkeepAllProfilesScope?: boolean+ /** Refresh an already-on-screen surface IN PLACE — no navigation, no+ * tile-minting, no focus steal. The canonical-chats re-resume+ * (session.reclaimed, roster activity) is a BACKGROUND refresh: the user+ * may be reading the Kanban board, a settings page, or another chat, and+ * a background event must never take the route or the foreground away+ * (issue 121874). The session is re-resolved (registry consultation,+ * backend dial, transcript pull) and the transcript of whichever surface+ * already holds it — its tile, or main when the route points at it — is+ * refreshed exactly like the SDK's own hydration probe+ * (`resumeTile(refreshTranscript)` / armed `requestSessionResume`). A+ * session that is NOT on screen resolves silently with nothing re-opened;+ * the next explicit open handles it. */+ refreshInPlace?: booleanprofile?: null | stringroute?: PluginProfileRouteworkspaceMode?: WorkspaceMode@@ -974,7 +987,11 @@ export const host = {const expectHistory = options.expectHistory ?? false- if (options.workspaceMode === 'bots') {+ // A refreshInPlace wake is not an entry into the workspace — it refreshes+ // a chat the user already opened. Never re-publish the bots scope (that+ // re-homes the pane-strip memory) and never flip the all-profiles view;+ // both belong to the explicit open that already happened.+ if (options.workspaceMode === 'bots' && !options.refreshInPlace) {publishWorkspaceScope('bots',options.workspaceOwnerKey ?? null,@@ -985,6 +1002,7 @@ export const host = {const openingStillCurrent = () =>generation === openSessionGeneration &&(options.workspaceMode !== 'bots' ||+ options.refreshInPlace ||($workspaceMode.get() === 'bots' && $workspaceOwnerKey.get() === (options.workspaceOwnerKey ?? null)))const plan = planPluginOpenSession({@@ -1064,8 +1082,11 @@ export const host = {// Only a cross-connection (explicit route) open forces the all-profiles// view; a local bot open keeps the planner's decision, unchanged from- // before the synthesized-route addition.- if (explicitRoute) {+ // before the synthesized-route addition. A refreshInPlace wake never+ // touches the view at all.+ if (options.refreshInPlace) {+ // no view change — the refresh inherits whatever is showing+ } else if (explicitRoute) {setShowAllProfiles(true)} else if (plan.showAllProfiles !== null) {setShowAllProfiles(plan.showAllProfiles)@@ -1101,6 +1122,37 @@ export const host = {const intent = options.intent ?? 'in-place'+ // Background refresh (refreshInPlace): this wake was triggered by+ // something that HAPPENED in the background (a reclaim, roster+ // activity), not by the user navigating. Never touch the route or+ // the tab strip — the user may be reading the Kanban board, a+ // settings page, or another chat (issue 121874: /kanban was+ // replaced by the Bot Chat route). Refresh only whichever surface+ // already holds the session: its tile via resumeTile+ // (refreshTranscript), or main via the armed explicit-resume+ // request — the same lever markRuntimeGone pulls for background+ // reclaims, consumed only while the route already points at the+ // session, so it can never navigate. A session that is not on+ // screen resolves without re-opening anything; the next explicit+ // open owns that.+ if (options.refreshInPlace) {+ const existingTile = $sessionTiles.get().some(tile => tile.storedSessionId === storedSessionId)+ const tileDelegate = existingTile ? sessionTileDelegate() : null+ // Main is refreshed only when it is actually showing this+ // session — the same surface discriminator the hydration probe+ // uses. An off-screen chat re-opens nothing: the request would+ // sit unconsumed and the wake would silently no-op.+ const mainShowing = $selectedStoredSessionId.get() === storedSessionId++ if (tileDelegate) {+ await tileDelegate.resumeTile(storedSessionId, { refreshTranscript: true })+ } else if (mainShowing) {+ requestSessionResume(storedSessionId, ownerRoute || undefined)+ }++ break+ }+if (options.workspaceMode === 'bots') {openSession(storedSessionId, navigate, intent, {ownerRoute: ownerRoute ?? undefined,diff --git a/apps/desktop/src/sdk/open-session-refresh-in-place.test.ts b/apps/desktop/src/sdk/open-session-refresh-in-place.test.tsnew file mode 100644index 00000000000..176a29004db--- /dev/null+++ b/apps/desktop/src/sdk/open-session-refresh-in-place.test.ts@@ -0,0 +1,223 @@+/**+ * `host.openSession({ refreshInPlace })` — the BACKGROUND re-resume contract+ * (issue 121874).+ *+ * A `session.reclaimed` (or roster-activity) wake re-resolves the open Bot+ * Chat so the user's next send doesn't eat a stale runtime id. It used to go+ * through the full navigating open: `intent: 'in-place'` → the route flipped+ * to the chat, replacing whatever the user was reading (the Kanban board).+ * Background events must never navigate — "offer; don't hijack"+ * (apps/desktop/AGENTS.md).+ *+ * The refresh-only open may dial the owner backend and re-resume, but it must+ * not: call the core open (navigation / tile minting), publish the bots+ * workspace scope, or flip the all-profiles view. It refreshes through the+ * same levers the core uses for its own staleness probe — the tile delegate's+ * `resumeTile(refreshTranscript)` or the armed `requestSessionResume`.+ */++import { afterEach, describe, expect, it, vi } from 'vitest'++import type { ProfileInfo } from '@/types/hermes'++vi.mock('@/app/chat/session-view', async () => {+ const { atom } = await import('nanostores')++ return { PRIMARY_SESSION_VIEW: { $awaitingResponse: atom(false), $busy: atom(false) } }+})+vi.mock('@/app/open-session', () => ({ openSession: vi.fn() }))+vi.mock('@/components/pane-shell/tree/store', async () => {+ const { atom } = await import('nanostores')++ return { $narrowViewport: atom(false) }+})+vi.mock('@/contrib/events', () => ({ onGatewayEvent: vi.fn() }))+vi.mock('@/hermes', () => ({ deleteProfile: vi.fn(), getLogs: vi.fn(), getStatus: vi.fn(), hermesApi: vi.fn() }))+vi.mock('@/store/notifications', () => ({ notify: vi.fn(), notifyError: vi.fn() }))+vi.mock('@/store/system-actions', () => ({ runGatewayRestart: vi.fn() }))+vi.mock('@/store/session', async () => {+ const { atom } = await import('nanostores')++ type LineageRow = { _lineage_root_id?: null | string; id: string }++ return {+ $activeSessionId: atom(null),+ $connection: atom(null),+ $cronSessions: atom([]),+ $currentCwd: atom(''),+ $currentModel: atom(''),+ $gatewayState: atom('open'),+ $messages: atom([]),+ $messagingSessions: atom([]),+ $selectedStoredSessionId: atom(null),+ $sessions: atom([]),+ $unreadFinishedSessionIds: atom([]),+ lineageAliases: (storedId: string) => [storedId],+ rememberedSessionProfile: (_sessions: unknown, _sessionId: null | string, activeProfile: null | string) =>+ (activeProfile ?? '').trim() || 'default',+ requestSessionResume: vi.fn(),+ sessionMatchesStoredId: (session: LineageRow, storedSessionId: string) =>+ session.id === storedSessionId || session._lineage_root_id === storedSessionId,+ sessionPinId: (session: LineageRow) => session._lineage_root_id ?? session.id,+ setSessionOwnerHint: vi.fn(),+ setResumeExhaustedSessionId: vi.fn()+ }+})+vi.mock('@/store/session-states', async () => {+ const { atom } = await import('nanostores')++ return {+ $attentionSessionIds: atom([]),+ $draftSessionIds: atom([]),+ $focusedRuntimeId: atom(null),+ $focusedSessionState: atom(null),+ $focusedStoredSessionId: atom(null),+ $sessionTiles: atom([]),+ $sessionStates: atom({}),+ $stalledSessionIds: atom([]),+ $workingSessionIds: atom([]),+ dropTilesForProfile: vi.fn(),+ sessionTileDelegate: vi.fn(() => null)+ }+})+vi.mock('@/store/profile', async () => {+ const { atom } = await import('nanostores')++ const profiles = atom([+ {+ has_env: false,+ is_default: false,+ model: null,+ name: 'cached-only',+ path: '/profiles/cached-only',+ provider: null,+ skill_count: 0+ }+ ])++ return {+ $activeGatewayProfile: atom('ops'),+ $gatewaySwapTarget: atom(null),+ $hydrationSyncProfile: atom(null),+ $profiles: profiles,+ $showAllProfiles: atom(false),+ ensureGatewayAgent: vi.fn(),+ ensureGatewayProfile: vi.fn(),+ newSessionInAgent: vi.fn(),+ newSessionInProfile: vi.fn(),+ normalizeProfileKey: (value: null | string | undefined) => (value ?? '').trim() || 'default',+ refreshProfiles: vi.fn(async () => profiles.get()),+ selectProfile: vi.fn(),+ setActiveProfile: vi.fn(),+ setShowAllProfiles: vi.fn()+ }+})+vi.mock('@/store/gateway', async () => {+ const { atom } = await import('nanostores')++ return {+ $activeGatewayRoute: atom('default'),+ $gateway: atom(null),+ activeGateway: vi.fn(() => null),+ activeGatewayConnectionId: vi.fn(() => 'local'),+ ensureGatewayForAgent: vi.fn(),+ openGatewayForAgent: vi.fn(),+ openGatewayForProfile: vi.fn(),+ requestGatewayForAgent: vi.fn(),+ requestGatewayForProfile: vi.fn(),+ retainGatewayForAgent: vi.fn(async () => vi.fn()),+ retireLocalProfileGateways: vi.fn()+ }+})++const { host } = await import('./index')++const { openSession: openSessionCore } = await import('@/app/open-session')++const { openGatewayForProfile } = await import('@/store/gateway')++const { $activeGatewayProfile, setShowAllProfiles } = await import('@/store/profile')++const { $sessionTiles, sessionTileDelegate } = await import('@/store/session-states')++const { requestSessionResume, setSessionOwnerHint, $selectedStoredSessionId } = await import('@/store/session')++const { setWorkspaceScope, $workspaceMode } = await import('@/components/pane-shell/workspace-scope')++const setMockAtom = <T>(store: unknown, value: T) => (store as { set(next: T): void }).set(value)++const profile = (name: string): ProfileInfo => ({+ has_env: false,+ is_default: name === 'default',+ model: null,+ name,+ path: `/profiles/${name}`,+ provider: null,+ skill_count: 0+})++afterEach(() => {+ vi.clearAllMocks()+ vi.mocked(sessionTileDelegate).mockReturnValue(null)+ setMockAtom($sessionTiles, [])+ setMockAtom($selectedStoredSessionId, null)+ $activeGatewayProfile.set('ops')+ setWorkspaceScope('sessions')+})++describe('host.openSession refreshInPlace — background re-resume never navigates (issue 121874)', () => {+ it('refreshes the open tile transcript without calling the core open', async () => {+ const resumeTile = vi.fn(async () => 'runtime-ops')++ vi.mocked(sessionTileDelegate).mockReturnValue({ resumeTile } as never)+ setMockAtom($sessionTiles, [{ storedSessionId: 'bot-chat-ops' }] as never)+ $activeGatewayProfile.set('ops')++ await host.openSession('bot-chat-ops', {+ profile: 'ops',+ refreshInPlace: true,+ workspaceMode: 'bots',+ workspaceOwnerKey: 'bot:ops'+ })++ // The one thing this wake exists for: the tile re-pulls its transcript.+ expect(resumeTile).toHaveBeenCalledWith('bot-chat-ops', { refreshTranscript: true })+ // And none of the navigating-open side effects.+ expect(openSessionCore).not.toHaveBeenCalled()+ expect($workspaceMode.get()).toBe('sessions')+ expect(setShowAllProfiles).not.toHaveBeenCalled()+ })++ it('arms the explicit-resume request instead of navigating when the chat holds main', async () => {+ // /:bot-chat-ops is the route: the refresh must arm the same+ // explicit-request lever the core's staleness probe uses — consumed only+ // while the route points at the session, so it can never navigate.+ const { $selectedStoredSessionId } = await import('@/store/session')++ setMockAtom($selectedStoredSessionId, 'bot-chat-ops')++ await host.openSession('bot-chat-ops', { profile: 'ops', refreshInPlace: true })++ expect(requestSessionResume).toHaveBeenCalledWith('bot-chat-ops', undefined)+ expect(openSessionCore).not.toHaveBeenCalled()+ })++ it('resolves without re-opening anything when the session is not on screen', async () => {+ // No tile, route elsewhere: a background wake must not mint a tab, load+ // the chat into main, or dial the backend into a workspace switch.+ await host.openSession('bot-chat-ops', { profile: 'ops', refreshInPlace: true })++ expect(requestSessionResume).not.toHaveBeenCalled()+ expect(openSessionCore).not.toHaveBeenCalled()+ expect(openGatewayForProfile).not.toHaveBeenCalled()+ })++ it('stamps the owner hint so the resume routes to the owning backend', async () => {+ await host.openSession('bot-chat-ops', { profile: 'ops', refreshInPlace: true })++ expect(setSessionOwnerHint).toHaveBeenCalledWith(+ 'bot-chat-ops',+ expect.objectContaining({ profile: 'ops' })+ )+ })+})