Skip to content

The agent that grows with you

fix(desktop): preserve Bot tabs across owner lifecycles

David Dudok de Wita81854a2bd81
diff --git a/apps/desktop/src/app/chat/session-tile.tsx b/apps/desktop/src/app/chat/session-tile.tsx
index 2adcc048a33..4a234022dff 100644
--- a/apps/desktop/src/app/chat/session-tile.tsx
+++ b/apps/desktop/src/app/chat/session-tile.tsx
@@ -47,14 +47,17 @@ import {
sessionMatchesStoredId,
sessionPinId
} from '@/store/session'
+import { requestForSessionProfile } from '@/store/session-request-router'
import {
$sessionStates,
+ $sessionTileDelegateRevision,
$sessionTiles,
closeSessionTile,
discardSessionTile,
patchSessionTile,
type SessionTile,
- sessionTileDelegate
+ sessionTileDelegate,
+ sessionTileOwnerRoute
} from '@/store/session-states'
import type { SessionInfo } from '@/types/hermes'
@@ -135,7 +138,15 @@ function TileChat({
}) {
const { gateway, requestGateway } = useGatewayRequest()
const queryClient = useQueryClient()
- const { selectModel } = useModelControls({ queryClient, requestGateway })
+ const ownerRoute = sessionTileOwnerRoute(storedSessionId)
+
+ const requestTileGateway = useCallback(
+ <T,>(method: string, params?: Record<string, unknown>, timeoutMs?: number, signal?: AbortSignal): Promise<T> =>
+ requestForSessionProfile<T>(ownerRoute, requestGateway, method, params, timeoutMs, signal),
+ [ownerRoute, requestGateway]
+ )
+
+ const { selectModel } = useModelControls({ queryClient, requestGateway: requestTileGateway })
const activeGatewayProfile = useStore($activeGatewayProfile)
const cwd = useStore(view.$cwd)
const gatewayOpen = useStore($gatewayState) === 'open'
@@ -160,7 +171,7 @@ function TileChat({
const composer = useComposerActions({
activeSessionId: runtimeId,
currentCwd: cwd,
- requestGateway,
+ requestGateway: requestTileGateway,
scope: {
add: attachments.add,
remove: attachments.remove,
@@ -201,11 +212,11 @@ function TileChat({
<ModelMenuPanel
gateway={gateway || undefined}
onSelectModel={selectModel}
- profile={activeGatewayProfile}
- requestGateway={requestGateway}
+ profile={ownerRoute?.profile || activeGatewayProfile}
+ requestGateway={requestTileGateway}
/>
) : null,
- [activeGatewayProfile, gateway, gatewayOpen, requestGateway, selectModel]
+ [activeGatewayProfile, gateway, gatewayOpen, ownerRoute?.profile, requestTileGateway, selectModel]
)
return (
@@ -247,6 +258,7 @@ export function SessionTilePane({ storedSessionId }: { storedSessionId: string }
const tile = tiles.find(t => t.storedSessionId === storedSessionId)
const runtimeId = tile?.runtimeId ?? null
const gatewayOpen = useStore($gatewayState) === 'open'
+ const delegateRevision = useStore($sessionTileDelegateRevision)
const resumingRef = useRef(false)
const view = useMemo(() => buildTileView(storedSessionId), [storedSessionId])
@@ -333,7 +345,7 @@ export function SessionTilePane({ storedSessionId }: { storedSessionId: string }
.finally(() => {
resumingRef.current = false
})
- }, [gatewayOpen, runtimeId, storedSessionId, tile?.error])
+ }, [delegateRevision, gatewayOpen, runtimeId, storedSessionId, tile?.error])
// The gateway (re)opening invalidates any latched error — it likely came
// from a not-yet-open gateway or the previous connection. Clearing it
@@ -401,15 +413,17 @@ export function tileStoredRow(storedSessionId: string): SessionInfo | undefined
* skipping the re-register that hands the tab back to this string. */
function tileTitle(storedSessionId: string): string {
const stored = tileStoredRow(storedSessionId)
+ const explicit = $sessionTiles.get().find(tile => tile.storedSessionId === storedSessionId)?.workspaceTabTitle
- return stored ? sessionTitle(stored) : NEW_SESSION_TITLE
+ return stored ? sessionTitle(stored) : explicit || NEW_SESSION_TITLE
}
/** The `@session` link payload for a tile tab drag — id + owning profile + title.
* Resolved at drag time, so an unsent tab drags under its draft name. */
function tileDragPayload(storedSessionId: string): SessionDragPayload {
const stored = tileStoredRow(storedSessionId)
- const title = stored ? sessionTitle(stored) : draftTitleFor(storedSessionId) || NEW_SESSION_TITLE
+ const explicit = $sessionTiles.get().find(tile => tile.storedSessionId === storedSessionId)?.workspaceTabTitle
+ const title = stored ? sessionTitle(stored) : explicit || draftTitleFor(storedSessionId) || NEW_SESSION_TITLE
return { id: storedSessionId, profile: stored?.profile ?? '', title }
}
@@ -617,7 +631,11 @@ export const watchSessionTiles = paneMirror<SessionTile>({
),
// Until the first turn lists a row there is no title to register, so the tab
// takes its name from the composer instead — live, without re-registering.
- tabTitle: storedSessionId => (tileStoredRow(storedSessionId) ? null : <SessionDraftTitle scope={storedSessionId} />),
+ tabTitle: storedSessionId =>
+ tileStoredRow(storedSessionId) ||
+ $sessionTiles.get().some(tile => tile.storedSessionId === storedSessionId && tile.workspaceTabTitle) ? null : (
+ <SessionDraftTitle scope={storedSessionId} />
+ ),
render: storedSessionId => <SessionTilePane storedSessionId={storedSessionId} />,
tabWrap: (storedSessionId, tab) => (
<SessionTabMenu
diff --git a/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.test.ts b/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.test.ts
index bca585757e0..6d8ed3be1c8 100644
--- a/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.test.ts
+++ b/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.test.ts
@@ -2,7 +2,7 @@ import { renderHook } from '@testing-library/react'
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type * as HermesModule from '@/hermes'
-import { setSessions } from '@/store/session'
+import { setSessionOwnerHint, setSessions } from '@/store/session'
import { sessionTileDelegate } from '@/store/session-states'
import type { SessionInfo } from '@/types/hermes'
@@ -12,8 +12,14 @@ vi.mock('@/hermes', async importActual => ({
...(await importActual<typeof HermesModule>()),
getLatestSessionMessages: vi.fn(async () => ({ messages: [], session_id: '' }))
}))
+vi.mock('@/store/gateway', async importActual => ({
+ ...(await importActual<Record<string, unknown>>()),
+ requestGatewayForAgent: vi.fn(),
+ requestGatewayForProfile: vi.fn()
+}))
const { getLatestSessionMessages } = await import('@/hermes')
+const { requestGatewayForAgent, requestGatewayForProfile } = await import('@/store/gateway')
const row = (over: Partial<SessionInfo>): SessionInfo =>
({
@@ -76,17 +82,26 @@ describe('useSessionTileDelegate resumeTile', () => {
method === 'session.resume' ? ({ session_id: 'runtime-1' } as never) : ({} as never)
)
+ vi.mocked(requestGatewayForProfile).mockResolvedValueOnce({ session_id: 'runtime-1' } as never)
+
renderTile(requestGateway)
const runtimeId = await sessionTileDelegate()!.resumeTile('stored-x')
expect(runtimeId).toBe('runtime-1')
expect(getLatestSessionMessages).toHaveBeenCalledWith('stored-x', 'ai-engineer')
- expect(requestGateway).toHaveBeenCalledWith('session.resume', {
- session_id: 'stored-x',
- cols: 96,
- profile: 'ai-engineer',
- omit_messages: true
- })
+ expect(requestGatewayForProfile).toHaveBeenCalledWith(
+ 'ai-engineer',
+ 'session.resume',
+ {
+ session_id: 'stored-x',
+ cols: 96,
+ profile: 'ai-engineer',
+ omit_messages: true
+ },
+ undefined,
+ undefined
+ )
+ expect(requestGateway).not.toHaveBeenCalled()
})
it('resolves and carries a default-profile session explicitly', async () => {
@@ -107,6 +122,35 @@ describe('useSessionTileDelegate resumeTile', () => {
})
})
+ it('routes a Bot tile prefetch and resume through its exact connection owner', async () => {
+ const route = {
+ connectionId: 'barry',
+ mode: 'remote' as const,
+ profile: 'oxcoder',
+ targetProfile: 'backend-oxcoder'
+ }
+
+ setSessionOwnerHint('stored-remote', route)
+ vi.mocked(requestGatewayForAgent).mockResolvedValueOnce({ session_id: 'runtime-remote' } as never)
+ const ambientRequest = vi.fn(async () => ({}) as never)
+
+ renderTile(ambientRequest)
+ const runtimeId = await sessionTileDelegate()!.resumeTile('stored-remote')
+
+ expect(runtimeId).toBe('runtime-remote')
+ expect(getLatestSessionMessages).toHaveBeenCalledWith('stored-remote', {
+ connectionId: 'barry',
+ profile: 'backend-oxcoder'
+ })
+ expect(requestGatewayForAgent).toHaveBeenCalledWith('barry', 'oxcoder', 'session.resume', {
+ session_id: 'stored-remote',
+ cols: 96,
+ omit_messages: true,
+ profile: 'backend-oxcoder'
+ })
+ expect(ambientRequest).not.toHaveBeenCalled()
+ })
+
it('reuses a warm binding that still carries a transcript', async () => {
const stateA = { busy: false, messages: [{ id: 'm1' }], storedSessionId: 'stored-a' }
const runtimeIdByStoredSessionIdRef = { current: new Map([['stored-a', 'runtime-a']]) }
diff --git a/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.ts b/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.ts
index ce4783cb7ab..4eaf3d14d90 100644
--- a/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.ts
+++ b/apps/desktop/src/app/contrib/hooks/use-session-tile-delegate.ts
@@ -2,7 +2,9 @@ import { useEffect } from 'react'
import { getLatestSessionMessages, PROMPT_SUBMIT_REQUEST_TIMEOUT_MS } from '@/hermes'
import { toChatMessages } from '@/lib/chat-messages'
-import { publishSessionState, setSessionTileDelegate } from '@/store/session-states'
+import { getSessionOwnerHint } from '@/store/session'
+import { requestForSessionProfile, type SessionOwnerScope } from '@/store/session-request-router'
+import { publishSessionState, sessionTileOwnerRoute, setSessionTileDelegate } from '@/store/session-states'
import type { SessionResumeResponse } from '@/types/hermes'
import type { usePromptActions } from '../../session/hooks/use-prompt-actions'
@@ -71,6 +73,26 @@ export function useSessionTileDelegate({
}
}
+ const ownerForStoredSession = async (storedSessionId: string): Promise<SessionOwnerScope> => {
+ const owner =
+ getSessionOwnerHint(storedSessionId) ??
+ sessionTileOwnerRoute(storedSessionId) ??
+ (await resolveSessionProfile(storedSessionId))
+
+ return owner
+ }
+
+ const requestForStoredSession = async <T>(
+ storedSessionId: string,
+ method: string,
+ params: Record<string, unknown>,
+ timeoutMs?: number
+ ): Promise<T> => {
+ const owner = await ownerForStoredSession(storedSessionId)
+
+ return requestForSessionProfile<T>(owner, requestGateway, method, params, timeoutMs)
+ }
+
setSessionTileDelegate({
archiveSession: async storedSessionId => {
await archiveSession(storedSessionId)
@@ -89,8 +111,12 @@ export function useSessionTileDelegate({
// backend no longer knows. Drop the map so resumeTile's warm path can't
// re-bind a tile to a dead runtime; live bindings re-record from
// post-reconnect events and fresh resumes.
- invalidateRuntimeBindings: () => {
- runtimeIdByStoredSessionIdRef.current.clear()
+ invalidateRuntimeBindings: preserveStoredSessionIds => {
+ for (const storedSessionId of runtimeIdByStoredSessionIdRef.current.keys()) {
+ if (!preserveStoredSessionIds?.has(storedSessionId)) {
+ runtimeIdByStoredSessionIdRef.current.delete(storedSessionId)
+ }
+ }
},
interruptSession: async runtimeId => {
// Same cooldown as the primary chat's Stop (#83855): the gateway may
@@ -99,12 +125,20 @@ export function useSessionTileDelegate({
// false. Mark the runtime id (and any recovered id) before the RPC so
// the window covers the whole wind-down.
markSessionRecentlyInterrupted(runtimeId)
+
+ const storedSessionId = storedSessionIdForRuntime(runtimeId)
+
+ const routedRequest = storedSessionId
+ ? <T>(method: string, params?: Record<string, unknown>, timeoutMs?: number) =>
+ requestForStoredSession<T>(storedSessionId, method, params ?? {}, timeoutMs)
+ : requestGateway
+
await withSessionNotFoundResume(
runtimeId,
- storedSessionIdForRuntime(runtimeId),
- liveId => requestGateway('session.interrupt', { session_id: liveId }),
+ storedSessionId,
+ liveId => routedRequest('session.interrupt', { session_id: liveId }),
{
- requestGateway,
+ requestGateway: routedRequest,
onRecovered: recoveredId => {
markSessionRecentlyInterrupted(recoveredId)
rebindTileRuntime(runtimeId)(recoveredId)
@@ -133,15 +167,20 @@ export function useSessionTileDelegate({
// reading messages) without a profile lets the gateway fall back to the
// launch-profile DB and fork the conversation into the wrong profile —
// the same cross-profile bleed the recovery resumes had (#67603).
- const profile = await resolveSessionProfile(storedSessionId)
+ const owner = await ownerForStoredSession(storedSessionId)
+
+ const restScope =
+ owner && typeof owner === 'object'
+ ? { connectionId: owner.connectionId, profile: owner.targetProfile || owner.profile }
+ : owner
const [prefetch, resumed] = await Promise.all([
- getLatestSessionMessages(storedSessionId, profile).catch(() => null),
- requestGateway<SessionResumeResponse>('session.resume', {
+ getLatestSessionMessages(storedSessionId, restScope).catch(() => null),
+ requestForSessionProfile<SessionResumeResponse>(owner, requestGateway, 'session.resume', {
session_id: storedSessionId,
cols: 96,
omit_messages: true,
- ...(profile ? { profile } : {})
+ ...(owner ? { profile: typeof owner === 'string' ? owner : owner.profile } : {})
})
])
@@ -165,11 +204,18 @@ export function useSessionTileDelegate({
return runtimeId
},
submitToSession: async (runtimeId, text) => {
+ const storedSessionId = storedSessionIdForRuntime(runtimeId)
+
+ const routedRequest = storedSessionId
+ ? <T>(method: string, params?: Record<string, unknown>, timeoutMs?: number) =>
+ requestForStoredSession<T>(storedSessionId, method, params ?? {}, timeoutMs)
+ : requestGateway
+
await withSessionNotFoundResume(
runtimeId,
- storedSessionIdForRuntime(runtimeId),
- liveId => requestGateway('prompt.submit', { session_id: liveId, text }, PROMPT_SUBMIT_REQUEST_TIMEOUT_MS),
- { requestGateway, onRecovered: rebindTileRuntime(runtimeId) }
+ storedSessionId,
+ liveId => routedRequest('prompt.submit', { session_id: liveId, text }, PROMPT_SUBMIT_REQUEST_TIMEOUT_MS),
+ { requestGateway: routedRequest, onRecovered: rebindTileRuntime(runtimeId) }
)
},
updateSession: (runtimeId, updater) => updateSessionState(runtimeId, updater)
diff --git a/apps/desktop/src/app/contrib/wiring.tsx b/apps/desktop/src/app/contrib/wiring.tsx
index 7a6e557f7ce..e5b7dbdcc26 100644
--- a/apps/desktop/src/app/contrib/wiring.tsx
+++ b/apps/desktop/src/app/contrib/wiring.tsx
@@ -890,7 +890,11 @@ export function ContribWiring({ children }: { children: ReactNode }) {
void openNewSessionTile('center', {
listed: false,
route: workspaceNewSessionTarget.route,
- workspaceScope: { workspaceMode: 'bots', workspaceOwnerKey }
+ workspaceScope: {
+ ownerRoute: workspaceNewSessionTarget.route,
+ workspaceMode: 'bots',
+ workspaceOwnerKey
+ }
})
return
diff --git a/apps/desktop/src/app/open-session.test.ts b/apps/desktop/src/app/open-session.test.ts
index d2d8339f324..4a3f95d7df0 100644
--- a/apps/desktop/src/app/open-session.test.ts
+++ b/apps/desktop/src/app/open-session.test.ts
@@ -99,7 +99,7 @@ describe('openSession', () => {
it('in-place focuses an existing tile and does not navigate', () => {
focusOpenSession.mockReturnValue('tile')
openSession('s1', navigate)
- expect(focusOpenSession).toHaveBeenCalledWith('s1')
+ expect(focusOpenSession).toHaveBeenCalledWith('s1', { workspaceMode: 'sessions' })
expect(navigate).not.toHaveBeenCalled()
expect(openSessionTile).not.toHaveBeenCalled()
})
@@ -134,7 +134,7 @@ describe('openSession', () => {
it('tab focuses an existing open session instead of stacking another', () => {
focusOpenSession.mockReturnValue('tile')
openSession('s1', navigate, 'tab')
- expect(focusOpenSession).toHaveBeenCalledWith('s1')
+ expect(focusOpenSession).toHaveBeenCalledWith('s1', { workspaceMode: 'sessions' })
expect(openSessionTile).not.toHaveBeenCalled()
expect(navigate).not.toHaveBeenCalled()
})
@@ -153,6 +153,7 @@ describe('openSession', () => {
openSession('s1', navigate, 'tab', scope)
expect(setSessionTileWorkspaceScope).toHaveBeenCalledWith('s1', scope)
+ expect(focusOpenSession).toHaveBeenCalledWith('s1', scope)
expect(openSessionTile).toHaveBeenCalledWith('s1', 'center', undefined, undefined, scope)
})
diff --git a/apps/desktop/src/app/open-session.ts b/apps/desktop/src/app/open-session.ts
index 0781cf00138..e76a9face20 100644
--- a/apps/desktop/src/app/open-session.ts
+++ b/apps/desktop/src/app/open-session.ts
@@ -16,6 +16,7 @@
*/
import type { WorkspaceMode } from '@/contrib/types'
import { $activeSessionId, $selectedStoredSessionId, markSessionRead } from '@/store/session'
+import type { SessionProfileRoute } from '@/store/session-request-router'
import {
focusedSessionNeedsRoute,
focusOpenSession,
@@ -32,8 +33,10 @@ export type OpenSessionIntent = 'in-place' | 'main' | 'stack' | 'tab' | 'window'
export type OpenSessionNavigate = (to: string, options?: { replace?: boolean }) => void
export interface OpenSessionWorkspaceScope {
+ ownerRoute?: SessionProfileRoute
workspaceMode: WorkspaceMode
workspaceOwnerKey?: string
+ workspaceTabTitle?: string
}
/**
@@ -131,7 +134,9 @@ export function openSession(
// Already on screen? Front it. openSessionTile would no-op on main without
// focusing, or try to relocate an existing tile — neither is right for a
// soft "open beside" link.
- if (focusOpenSession(storedSessionId)) {
+ const focused = focusOpenSession(storedSessionId, workspaceScope)
+
+ if (focused) {
return
}
@@ -160,7 +165,7 @@ export function openSession(
// otherwise load it into main. From a full page (artifacts, skills, …) a
// `'main'` hit still has to route back: fronting the workspace tab alone
// leaves the page showing.
- if (focusedSessionNeedsRoute(focusOpenSession(storedSessionId), $workspaceIsPage.get())) {
+ if (focusedSessionNeedsRoute(focusOpenSession(storedSessionId, workspaceScope), $workspaceIsPage.get())) {
navigate(sessionRoute(storedSessionId))
}
}
diff --git a/apps/desktop/src/plugins/hermes-bots/plugin.js b/apps/desktop/src/plugins/hermes-bots/plugin.js
index a49c7ccd5e9..0c97b25a4be 100644
--- a/apps/desktop/src/plugins/hermes-bots/plugin.js
+++ b/apps/desktop/src/plugins/hermes-bots/plugin.js
@@ -5058,7 +5058,8 @@ async function openStoredBotChat(owner, storedId, summary) {
throw new Error('This Hermes Desktop version cannot open stored sessions')
}
- const { name, route } = botOwner(owner)
+ const { bot, name, route } = botOwner(owner)
+ const ownerKey = botWorkspaceOwnerKey(bot)
const hasAuthoritativeCount =
typeof summary?.message_count === 'number' && Number.isFinite(summary.message_count)
@@ -5073,23 +5074,14 @@ async function openStoredBotChat(owner, storedId, summary) {
await host.openSession(storedId, {
...(route ? { route } : {}),
profile: name,
- intent: 'main',
+ intent: 'tab',
awaitHydration: true,
expectHistory,
- // Move the WORKSPACE onto this bot, not just the transcript.
- //
- // With the default (true) the bot's chat opened against its own backend
- // while `$activeGatewayProfile` stayed on whatever profile was active
- // before — so "New session" from inside any bot was created on that other
- // backend. Measured: four consecutive new chats started from different
- // bots all landed in the `ops` profile's state.db. Clicking a bot is a
- // workspace switch in this product (one bot = one workspace), so the
- // chrome has to follow. EXCEPT across connections: a remote bot's chat
- // opens on its own source while Desktop's chrome/API home stays put —
- // re-homing the window onto another machine for one chat is the bug
- // #90006 exists to remove.
- keepAllProfilesScope: route ? true : false,
- retryHydrationTimeoutOnce: true
+ keepAllProfilesScope: true,
+ workspaceMode: 'bots',
+ workspaceOwnerKey: ownerKey,
+ retryHydrationTimeoutOnce: true,
+ tabTitle: CANONICAL_CHAT_TITLE
})
return storedId
@@ -13110,9 +13102,15 @@ function BotsPane() {
return () => cancelAnimationFrame(frame)
}, [hiddenExpanded, hasRosterConstraint])
- if (live) {
+ useEffect(() => {
+ if (!live) {
+ return
+ }
+
// Offline-owner ghosts belong only to this render. Shared roster state
- // feeds merge caching, group membership, creation, and durable sync.
+ // feeds merge caching, group membership, creation, and durable sync. These
+ // writes must settle after render: BotsHomeView subscribes to the same
+ // atoms, so publishing here used to update it while BotsPane was rendering.
$lastRoster.set(roster.filter(row => !row?.ghost))
if (Array.isArray(data?.sources)) {
$lastSources.set(data.sources)
@@ -13121,7 +13119,10 @@ function BotsPane() {
pullServerAvatars(activeSourceRoster)
trackInboundActivity(roster)
backfillMessagingProtocol(activeSourceRoster)
- }
+ // React Query owns the stable server snapshot; derived arrays intentionally
+ // follow that snapshot rather than retriggering on their own atom writes.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [data])
// The roster has ANSWERED once data or a terminal error exists — that, not
// row count, is what lets the home stop showing its loading state (an empty
@@ -13137,6 +13138,11 @@ function BotsPane() {
if (selectionHydrated) {
reconcileRosterSelection(roster, sourceSnapshot, allMeta)
+ const selected = selectedRosterBot(roster, $selectedRosterKey.get())
+
+ if ($botsPaneVisible.get() && !$groupChatWorkspace.get() && selected) {
+ setBotsWorkspaceOwner(botWorkspaceOwnerKey(selected), selected)
+ }
}
}, [data, error, selectionHydrated, roster, sourceSnapshot, allMeta])
diff --git a/apps/desktop/src/plugins/hermes-bots/tests/bots-home.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/bots-home.test.mjs
index f3be856978e..411b4255fcc 100644
--- a/apps/desktop/src/plugins/hermes-bots/tests/bots-home.test.mjs
+++ b/apps/desktop/src/plugins/hermes-bots/tests/bots-home.test.mjs
@@ -454,6 +454,7 @@ test('opening a remote bot selects and opens its exact owner chat', async () =>
assert.equal(t.sessionOpens.length, 1)
assert.equal(t.sessionOpens[0].options.workspaceMode, 'bots')
assert.equal(t.sessionOpens[0].options.workspaceOwnerKey, 'bot:work-vps::researcher')
+ assert.equal(t.sessionOpens[0].options.tabTitle, 'Bot Chat')
assert.equal(t.sessionOpens[0].options.keepAllProfilesScope, true)
assert.equal(t.sessionOpens[0].options.route.connectionId, 'work-vps')
assert.ok(t.requests.every(request => request.route?.connectionId === 'work-vps'))
@@ -940,7 +941,7 @@ test('roster hydration and selection reconciliation run after render', () => {
assert.match(
pane,
- /useEffect\(\(\) => \{[\s\S]{0,500}?\$rosterHydrated\.set\(true\)[\s\S]{0,300}?reconcileRosterSelection\(roster, sourceSnapshot, allMeta\)[\s\S]{0,220}?\}, \[data, error, selectionHydrated, roster, sourceSnapshot, allMeta\]\)/,
+ /useEffect\(\(\) => \{[\s\S]{0,500}?\$rosterHydrated\.set\(true\)[\s\S]{0,300}?reconcileRosterSelection\(roster, sourceSnapshot, allMeta\)[\s\S]{0,700}?\}, \[data, error, selectionHydrated, roster, sourceSnapshot, allMeta\]\)/,
'persisted roster ownership must reconcile from an effect, never from a replayable render'
)
assert.equal(
diff --git a/apps/desktop/src/plugins/hermes-bots/tests/canonical-chat-registry.test.mjs b/apps/desktop/src/plugins/hermes-bots/tests/canonical-chat-registry.test.mjs
index 1fb3ad1edff..331185ecf96 100644
--- a/apps/desktop/src/plugins/hermes-bots/tests/canonical-chat-registry.test.mjs
+++ b/apps/desktop/src/plugins/hermes-bots/tests/canonical-chat-registry.test.mjs
@@ -80,8 +80,12 @@ test('open resolves the profile\u2019s "Bot Chat" row by exact title and opens i
assert.equal(runtime.opened.length, 1)
assert.equal(runtime.opened[0].id, 'forever-chat')
assert.equal(runtime.opened[0].options.profile, 'ops')
- assert.equal(runtime.opened[0].options.keepAllProfilesScope, false,
- 'opening a bot moves the workspace onto that bot')
+ assert.equal(runtime.opened[0].options.keepAllProfilesScope, true,
+ 'opening a bot leaves the Sessions workspace on its current gateway')
+ assert.equal(runtime.opened[0].options.intent, 'tab')
+ assert.equal(runtime.opened[0].options.workspaceMode, 'bots')
+ assert.equal(runtime.opened[0].options.workspaceOwnerKey, 'bot:ops')
+ assert.equal(runtime.opened[0].options.tabTitle, 'Bot Chat')
const list = runtime.requests.find(r => r.method === 'session.list')
assert.equal(list?.params?.title, 'Bot Chat', 'lookup is by exact title')
diff --git a/apps/desktop/src/sdk/index.ts b/apps/desktop/src/sdk/index.ts
index 1510f14d612..5f196bbbc39 100644
--- a/apps/desktop/src/sdk/index.ts
+++ b/apps/desktop/src/sdk/index.ts
@@ -86,7 +86,8 @@ import {
$focusedRuntimeId,
$focusedSessionState,
$focusedStoredSessionId,
- $sessionStates
+ $sessionStates,
+ $sessionTiles
} from '@/store/session-states'
import { runGatewayRestart } from '@/store/system-actions'
import type { UsageStats } from '@/types/hermes'
@@ -141,7 +142,6 @@ const $focusedSessionOwner = computed(
[$focusedStoredSessionId, $sessions, $activeGatewayProfile, $connection],
(focused, sessions, activeProfile, connection): PluginFocusedSessionOwner | null => {
const activeConnectionId = String(connection?.connectionId || (connection?.mode === 'local' ? 'local' : '')).trim()
-
const fallback = {
connectionId: activeConnectionId,
profile: normalizeProfileKey(activeProfile)
@@ -326,6 +326,7 @@ export interface PluginOpenSessionOptions {
* overlay ($resumeExhaustedSessionId) — a caller-side retry can't do this
* itself because only this SDK layer sees $resumeExhaustedSessionId. */
retryHydrationTimeoutOnce?: boolean
+ tabTitle?: string
}
export interface PluginNewChatOptions {
@@ -386,18 +387,23 @@ function waitForFocusedSessionHydration({
const profileMatches = !requireActiveProfile || normalizeProfileKey($activeGatewayProfile.get()) === profile
const mainMatches = $selectedStoredSessionId.get() === storedSessionId
- const tileMatches = $focusedStoredSessionId.get() === storedSessionId
+ const storedTile = $sessionTiles.get().find(tile => tile.storedSessionId === storedSessionId)
+ const tileMatches = $focusedStoredSessionId.get() === storedSessionId || Boolean(storedTile)
+ const focusedTileMatches = $focusedStoredSessionId.get() === storedSessionId
+ const tileRuntimeId = focusedTileMatches ? $focusedRuntimeId.get() : (storedTile?.runtimeId ?? null)
- const runtimeReady = mainMatches
- ? Boolean($activeSessionId.get())
- : tileMatches
- ? Boolean($focusedRuntimeId.get())
- : false
+ const tileState = focusedTileMatches
+ ? $focusedSessionState.get()
+ : tileRuntimeId
+ ? $sessionStates.get()[tileRuntimeId]
+ : undefined
+
+ const runtimeReady = mainMatches ? Boolean($activeSessionId.get()) : tileMatches ? Boolean(tileRuntimeId) : false
const historyPainted = mainMatches
? Boolean($messages.get().length)
: tileMatches
- ? Boolean($focusedSessionState.get()?.messages.length)
+ ? Boolean(tileState?.messages.length)
: false
// Paint-first hydration: for a history-bearing chat, the wake is DONE
@@ -427,6 +433,8 @@ function waitForFocusedSessionHydration({
unbinds.push($focusedStoredSessionId.listen(check))
unbinds.push($focusedRuntimeId.listen(check))
unbinds.push($focusedSessionState.listen(check))
+ unbinds.push($sessionTiles.listen(check))
+ unbinds.push($sessionStates.listen(check))
unbinds.push($workspaceMode.listen(check))
unbinds.push($workspaceOwnerKey.listen(check))
@@ -816,8 +824,10 @@ export const host = {
if (options.workspaceMode === 'bots') {
openSession(storedSessionId, navigate, intent, {
+ ownerRoute: ownerRoute ?? undefined,
workspaceMode: 'bots',
- workspaceOwnerKey: options.workspaceOwnerKey
+ workspaceOwnerKey: options.workspaceOwnerKey,
+ ...(options.tabTitle ? { workspaceTabTitle: options.tabTitle } : {})
})
} else {
openSession(storedSessionId, navigate, intent)
diff --git a/apps/desktop/src/sdk/profile-routing.test.ts b/apps/desktop/src/sdk/profile-routing.test.ts
index 556bb887b32..129231aadab 100644
--- a/apps/desktop/src/sdk/profile-routing.test.ts
+++ b/apps/desktop/src/sdk/profile-routing.test.ts
@@ -43,6 +43,7 @@ vi.mock('@/store/session-states', async () => {
$focusedRuntimeId: atom(null),
$focusedSessionState: atom(null),
$focusedStoredSessionId: atom(null),
+ $sessionTiles: atom([]),
$sessionStates: atom({})
}
})
@@ -122,7 +123,8 @@ const {
setShowAllProfiles
} = await import('@/store/profile')
-const { $focusedRuntimeId, $focusedSessionState, $focusedStoredSessionId } = await import('@/store/session-states')
+const { $focusedRuntimeId, $focusedSessionState, $focusedStoredSessionId, $sessionStates, $sessionTiles } =
+ await import('@/store/session-states')
const { setWorkspaceScope } = await import('@/components/pane-shell/workspace-scope')
const {
@@ -153,6 +155,8 @@ afterEach(() => {
setMockAtom($focusedRuntimeId, null)
setMockAtom($focusedStoredSessionId, null)
setMockAtom($focusedSessionState, null)
+ setMockAtom($sessionStates, {})
+ setMockAtom($sessionTiles, [])
setMockAtom($activeSessionId, null)
setMockAtom($selectedStoredSessionId, null)
setMockAtom($messages, [])
@@ -430,6 +434,7 @@ describe('profile-aware plugin session opens', () => {
})
expect(openSessionCore).toHaveBeenCalledWith('bot-chat', expect.any(Function), 'in-place', {
+ ownerRoute: route,
workspaceMode: 'bots',
workspaceOwnerKey: 'source-a::default'
})
@@ -466,6 +471,44 @@ describe('profile-aware plugin session opens', () => {
expect($selectedStoredSessionId.get()).toBeNull()
})
+ it('finishes a restored Bot wake from its hydrated tile before the first pointer focus', async () => {
+ const route = {
+ connectionId: 'source-a',
+ mode: 'remote' as const,
+ profile: 'default',
+ targetProfile: 'backend-default'
+ }
+
+ const opening = host.openSession('restored-bot-chat', {
+ awaitHydration: true,
+ expectHistory: true,
+ hydrationTimeoutMs: 1_000,
+ intent: 'tab',
+ route,
+ workspaceMode: 'bots',
+ workspaceOwnerKey: 'bot:source-a::default'
+ })
+
+ await Promise.resolve()
+ setMockAtom($sessionTiles, [
+ {
+ runtimeId: 'runtime-restored',
+ storedSessionId: 'restored-bot-chat',
+ workspaceMode: 'bots',
+ workspaceOwnerKey: 'bot:source-a::default'
+ }
+ ])
+ setMockAtom($sessionStates, {
+ 'runtime-restored': {
+ messages: [{ id: 'restored-history', parts: [], role: 'assistant' }],
+ storedSessionId: 'restored-bot-chat'
+ }
+ } as never)
+
+ await opening
+ expect($focusedStoredSessionId.get()).toBeNull()
+ })
+
it('strands a late Bot wake when the user returns to Sessions', async () => {
let releaseDial: (() => void) | undefined
diff --git a/apps/desktop/src/store/session-states.test.ts b/apps/desktop/src/store/session-states.test.ts
index 3cf17525074..6eff590dbf7 100644
--- a/apps/desktop/src/store/session-states.test.ts
+++ b/apps/desktop/src/store/session-states.test.ts
@@ -3,6 +3,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import type { ClientSessionState } from '@/app/types'
import { findGroupOfPane, group, split } from '@/components/pane-shell/tree/model'
import { $layoutTree } from '@/components/pane-shell/tree/store'
+import { $activeGatewayProfile } from '@/store/profile'
import { $selectedStoredSessionId } from '@/store/session'
import type { SessionTile } from '@/store/session-states'
import {
@@ -10,6 +11,7 @@ import {
$sessionTiles,
blankDraftTile,
focusedSessionNeedsRoute,
+ focusOpenSession,
markSelectionRestore,
nextSessionTileForWorkspace,
openSessionTile,
@@ -54,17 +56,49 @@ describe('resetTileRuntimeBindings', () => {
expect(() => resetTileRuntimeBindings()).not.toThrow()
expect($sessionTiles.get()[0]?.runtimeId).toBeUndefined()
})
+
+ it('keeps exact-owner Bot runtimes when only the primary gateway reconnects', () => {
+ const invalidateRuntimeBindings = vi.fn()
+ setSessionTileDelegate({ invalidateRuntimeBindings } as unknown as SessionTileDelegate)
+ $sessionTiles.set([
+ {
+ ownerRoute: {
+ connectionId: 'barry',
+ mode: 'remote',
+ profile: 'oxcoder',
+ targetProfile: 'oxcoder'
+ },
+ runtimeId: 'runtime-bot',
+ storedSessionId: 'stored-bot',
+ workspaceMode: 'bots',
+ workspaceOwnerKey: 'bot:barry::oxcoder'
+ }
+ ])
+
+ resetTileRuntimeBindings()
+
+ expect($sessionTiles.get()[0]?.runtimeId).toBe('runtime-bot')
+ expect(invalidateRuntimeBindings).toHaveBeenCalledWith(new Set(['stored-bot']))
+ })
})
describe('SessionTile workspace scope', () => {
afterEach(() => {
+ $activeGatewayProfile.set('default')
$layoutTree.set(null)
$selectedStoredSessionId.set(null)
$sessionTiles.set([])
})
it('stores an exact Bot owner and keeps it through placement patches', () => {
- const scope = { workspaceMode: 'bots' as const, workspaceOwnerKey: 'connection-a::default' }
+ const ownerRoute = {
+ connectionId: 'connection-a',
+ mode: 'remote' as const,
+ profile: 'default',
+ targetProfile: 'backend-default'
+ }
+
+ const scope = { ownerRoute, workspaceMode: 'bots' as const, workspaceOwnerKey: 'connection-a::default' }
openSessionTile('bot-chat', 'right', undefined, undefined, scope)
patchSessionTile('bot-chat', { dir: 'left' })
@@ -72,6 +106,7 @@ describe('SessionTile workspace scope', () => {
expect($sessionTiles.get()).toEqual([
expect.objectContaining({
dir: 'left',
+ ownerRoute,
storedSessionId: 'bot-chat',
workspaceMode: 'bots',
workspaceOwnerKey: 'connection-a::default'
@@ -79,6 +114,38 @@ describe('SessionTile workspace scope', () => {
])
})
+ it('allows a Bot-scoped tab when the same stored session is hidden in Sessions main', () => {
+ const scope = { workspaceMode: 'bots' as const, workspaceOwnerKey: 'connection-a::default' }
+
+ $selectedStoredSessionId.set('bot-chat')
+ openSessionTile('bot-chat', 'center', undefined, undefined, scope)
+
+ expect($sessionTiles.get()).toEqual([
+ expect.objectContaining({
+ storedSessionId: 'bot-chat',
+ workspaceMode: 'bots',
+ workspaceOwnerKey: 'connection-a::default'
+ })
+ ])
+ expect(focusOpenSession('bot-chat', scope)).toBe('tile')
+ })
+
+ it('keeps Bot tabs while a profile publication swaps the Sessions bucket', () => {
+ const scope = { workspaceMode: 'bots' as const, workspaceOwnerKey: 'connection-a::writer' }
+
+ openSessionTile('sessions-chat')
+ openSessionTile('bot-chat', 'center', undefined, undefined, scope)
+ $activeGatewayProfile.set('other-profile')
+
+ expect($sessionTiles.get()).toEqual([
+ expect.objectContaining({
+ storedSessionId: 'bot-chat',
+ workspaceMode: 'bots',
+ workspaceOwnerKey: 'connection-a::writer'
+ })
+ ])
+ })
+
it('re-scopes an existing tile without changing its placement', () => {
openSessionTile('chat', 'bottom', 'workspace')
diff --git a/apps/desktop/src/store/session-states.ts b/apps/desktop/src/store/session-states.ts
index e2570c1bd2f..119f54bff33 100644
--- a/apps/desktop/src/store/session-states.ts
+++ b/apps/desktop/src/store/session-states.ts
@@ -48,6 +48,7 @@ import {
setActiveSessionStoredIdRotation,
setSessions
} from './session'
+import type { SessionProfileRoute } from './session-request-router'
import { ackStoredSessionId, markSessionUnreadFinished } from './session-unread'
import { isSecondaryWindow } from './windows'
@@ -540,11 +541,17 @@ export interface SessionTile {
workspaceMode?: WorkspaceMode
/** Exact opaque owner key for Bot Mode tabs. */
workspaceOwnerKey?: string
+ /** Credential-free exact route used to resume this tab after relaunch. */
+ ownerRoute?: SessionProfileRoute
+ /** Stable title for hidden relationship chats absent from the Sessions list. */
+ workspaceTabTitle?: string
}
export interface SessionTileWorkspaceScope {
+ ownerRoute?: SessionProfileRoute
workspaceMode: WorkspaceMode
workspaceOwnerKey?: string
+ workspaceTabTitle?: string
}
// Tiles are persisted PER PROFILE: a session belongs to one profile, and the
@@ -556,22 +563,32 @@ export interface SessionTileWorkspaceScope {
const TILES_KEY = 'hermes.desktop.sessionTiles.v2'
const LEGACY_TILES_KEY = 'hermes.desktop.sessionTiles.v1'
const TILE_PANE_PREFIX = 'session-tile:'
+const BOTS_TILE_BUCKET = '__bots_workspace__'
/** Persisted placement — `dir` + strip slot (`before`) + dock `anchor` so a
* restart / profile swap re-adopts tiles in the same order, not all stacked
* right of workspace. */
type StoredTile = Pick<
SessionTile,
- 'anchor' | 'before' | 'dir' | 'storedSessionId' | 'workspaceMode' | 'workspaceOwnerKey'
+ | 'anchor'
+ | 'before'
+ | 'dir'
+ | 'ownerRoute'
+ | 'storedSessionId'
+ | 'workspaceMode'
+ | 'workspaceOwnerKey'
+ | 'workspaceTabTitle'
>
const toStored = (t: SessionTile): StoredTile => ({
anchor: t.anchor,
before: t.before,
dir: t.dir,
+ ...(t.ownerRoute ? { ownerRoute: t.ownerRoute } : {}),
storedSessionId: t.storedSessionId,
...(t.workspaceMode ? { workspaceMode: t.workspaceMode } : {}),
- ...(t.workspaceOwnerKey ? { workspaceOwnerKey: t.workspaceOwnerKey } : {})
+ ...(t.workspaceOwnerKey ? { workspaceOwnerKey: t.workspaceOwnerKey } : {}),
+ ...(t.workspaceTabTitle ? { workspaceTabTitle: t.workspaceTabTitle } : {})
})
function parseTileList(value: unknown): StoredTile[] {
@@ -585,12 +602,26 @@ function parseTileList(value: unknown): StoredTile[] {
anchor: typeof raw.anchor === 'string' ? raw.anchor : undefined,
before: typeof raw.before === 'string' || raw.before === null ? raw.before : undefined,
dir: raw.dir,
+ ownerRoute:
+ raw.ownerRoute &&
+ typeof raw.ownerRoute.connectionId === 'string' &&
+ typeof raw.ownerRoute.profile === 'string'
+ ? {
+ connectionId: raw.ownerRoute.connectionId,
+ mode: raw.ownerRoute.mode,
+ profile: raw.ownerRoute.profile,
+ ...(typeof raw.ownerRoute.targetProfile === 'string'
+ ? { targetProfile: raw.ownerRoute.targetProfile }
+ : {})
+ }
+ : undefined,
storedSessionId: raw.storedSessionId,
workspaceMode: raw.workspaceMode === 'bots' ? 'bots' : 'sessions',
workspaceOwnerKey:
raw.workspaceMode === 'bots' && typeof raw.workspaceOwnerKey === 'string'
? raw.workspaceOwnerKey
- : undefined
+ : undefined,
+ workspaceTabTitle: typeof raw.workspaceTabTitle === 'string' ? raw.workspaceTabTitle : undefined
}
})
: []
@@ -603,9 +634,19 @@ function loadTilesByProfile(): Record<string, StoredTile[]> {
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
for (const [profile, list] of Object.entries(parsed as Record<string, unknown>)) {
const tiles = parseTileList(list)
+ const key = profile === BOTS_TILE_BUCKET ? BOTS_TILE_BUCKET : normalizeProfileKey(profile)
if (tiles.length > 0) {
- byProfile[normalizeProfileKey(profile)] = tiles
+ const sessionTiles = tiles.filter(tile => tile.workspaceMode !== 'bots')
+ const botTiles = tiles.filter(tile => tile.workspaceMode === 'bots')
+
+ if (sessionTiles.length > 0) {
+ byProfile[key] = [...(byProfile[key] ?? []), ...sessionTiles]
+ }
+
+ if (botTiles.length > 0) {
+ byProfile[BOTS_TILE_BUCKET] = [...(byProfile[BOTS_TILE_BUCKET] ?? []), ...botTiles]
+ }
}
}
}
@@ -615,7 +656,17 @@ function loadTilesByProfile(): Record<string, StoredTile[]> {
if (legacy.length > 0) {
const key = normalizeProfileKey('default')
- byProfile[key] = [...(byProfile[key] ?? []), ...legacy]
+ const sessionTiles = legacy.filter(tile => tile.workspaceMode !== 'bots')
+ const botTiles = legacy.filter(tile => tile.workspaceMode === 'bots')
+
+ byProfile[key] = [...(byProfile[key] ?? []), ...sessionTiles]
+ byProfile[BOTS_TILE_BUCKET] = [...(byProfile[BOTS_TILE_BUCKET] ?? []), ...botTiles]
+ }
+
+ if (byProfile[BOTS_TILE_BUCKET]?.length) {
+ byProfile[BOTS_TILE_BUCKET] = [
+ ...new Map(byProfile[BOTS_TILE_BUCKET].map(tile => [tile.storedSessionId, tile])).values()
+ ]
}
writeJson(LEGACY_TILES_KEY, null)
@@ -634,7 +685,9 @@ const profileKey = () => normalizeProfileKey($activeGatewayProfile.get())
// atom hydrates from the stored (runtime-less) tiles for the active profile.
// A secondary window (single-chat pop-out) shows ONLY its routed session — no
// tiles, and no repopulation on a profile switch.
-export const $sessionTiles = atom<SessionTile[]>(isSecondaryWindow() ? [] : [...(tilesByProfile[profileKey()] ?? [])])
+export const $sessionTiles = atom<SessionTile[]>(
+ isSecondaryWindow() ? [] : [...(tilesByProfile[profileKey()] ?? []), ...(tilesByProfile[BOTS_TILE_BUCKET] ?? [])]
+)
function persistTiles() {
// Shares the origin's storage; a secondary window holds no tiles, so a write
@@ -647,16 +700,24 @@ function persistTiles() {
}
function saveTiles(tiles: SessionTile[]) {
- $sessionTiles.set(tiles)
const stored = tiles.map(toStored)
+ const sessionTiles = stored.filter(tile => tile.workspaceMode !== 'bots')
+ const botTiles = stored.filter(tile => tile.workspaceMode === 'bots')
- if (stored.length > 0) {
- tilesByProfile[profileKey()] = stored
+ if (sessionTiles.length > 0) {
+ tilesByProfile[profileKey()] = sessionTiles
} else {
delete tilesByProfile[profileKey()]
}
+ if (botTiles.length > 0) {
+ tilesByProfile[BOTS_TILE_BUCKET] = botTiles
+ } else {
+ delete tilesByProfile[BOTS_TILE_BUCKET]
+ }
+
persistTiles()
+ $sessionTiles.set(tiles)
}
// Profile switch: surface the new profile's tiles with runtime ids cleared so
@@ -665,7 +726,7 @@ function saveTiles(tiles: SessionTile[]) {
// never carries tiles, so it stays out of this entirely.
if (!isSecondaryWindow()) {
$activeGatewayProfile.subscribe(() => {
- $sessionTiles.set([...(tilesByProfile[profileKey()] ?? [])])
+ $sessionTiles.set([...(tilesByProfile[profileKey()] ?? []), ...(tilesByProfile[BOTS_TILE_BUCKET] ?? [])])
})
}
@@ -673,21 +734,34 @@ export function patchSessionTile(storedSessionId: string, patch: Partial<Session
saveTiles($sessionTiles.get().map(t => (t.storedSessionId === storedSessionId ? { ...t, ...patch } : t)))
}
-export function setSessionTileWorkspaceScope(
- storedSessionId: string,
- scope: SessionTileWorkspaceScope
-): boolean {
+export function sessionTileOwnerRoute(storedSessionId: string): SessionProfileRoute | undefined {
+ return $sessionTiles.get().find(tile => tile.storedSessionId === storedSessionId)?.ownerRoute
+}
+
+export function setSessionTileWorkspaceScope(storedSessionId: string, scope: SessionTileWorkspaceScope): boolean {
const tile = $sessionTiles.get().find(candidate => candidate.storedSessionId === storedSessionId)
const workspaceOwnerKey = scope.workspaceMode === 'bots' ? scope.workspaceOwnerKey : undefined
+ const ownerRoute = scope.workspaceMode === 'bots' ? scope.ownerRoute : undefined
+ const workspaceTabTitle = scope.workspaceMode === 'bots' ? scope.workspaceTabTitle : undefined
if (
!tile ||
- ((tile.workspaceMode ?? 'sessions') === scope.workspaceMode && tile.workspaceOwnerKey === workspaceOwnerKey)
+ ((tile.workspaceMode ?? 'sessions') === scope.workspaceMode &&
+ tile.workspaceOwnerKey === workspaceOwnerKey &&
+ tile.ownerRoute?.connectionId === ownerRoute?.connectionId &&
+ tile.ownerRoute?.profile === ownerRoute?.profile &&
+ tile.ownerRoute?.targetProfile === ownerRoute?.targetProfile &&
+ tile.workspaceTabTitle === workspaceTabTitle)
) {
return false
}
- patchSessionTile(storedSessionId, { workspaceMode: scope.workspaceMode, workspaceOwnerKey })
+ patchSessionTile(storedSessionId, {
+ ownerRoute,
+ workspaceMode: scope.workspaceMode,
+ workspaceOwnerKey,
+ workspaceTabTitle
+ })
return true
}
@@ -699,12 +773,18 @@ export function setSessionTileWorkspaceScope(
* runtime id from the cache, so post-wake tiles repainted empty and never
* actually re-resumed. */
export function resetTileRuntimeBindings() {
- sessionTileDelegate()?.invalidateRuntimeBindings?.()
-
const tiles = $sessionTiles.get()
- if (tiles.some(t => t.runtimeId)) {
- $sessionTiles.set(tiles.map(toStored))
+ const preservedStoredIds = new Set(
+ tiles
+ .filter(tile => tile.workspaceMode === 'bots' && Boolean(tile.ownerRoute?.connectionId))
+ .map(tile => tile.storedSessionId)
+ )
+
+ sessionTileDelegate()?.invalidateRuntimeBindings?.(preservedStoredIds)
+
+ if (tiles.some(tile => tile.runtimeId && !preservedStoredIds.has(tile.storedSessionId))) {
+ $sessionTiles.set(tiles.map(tile => (preservedStoredIds.has(tile.storedSessionId) ? tile : toStored(tile))))
}
}
@@ -749,7 +829,7 @@ export interface SessionTileDelegate {
* recorded before the reconnect is suspect — without this, `resumeTile`'s
* warm path re-binds tiles to dead runtime ids (the sleep/wake "empty
* right pane" bug). Bindings re-record from live post-reconnect events. */
- invalidateRuntimeBindings?(): void
+ invalidateRuntimeBindings?(preserveStoredSessionIds?: ReadonlySet<string>): void
/** Bind a live runtime id for a stored session (resume without touching
* the main view). Returns the runtime id, or throws. */
resumeTile(storedSessionId: string): Promise<string>
@@ -761,9 +841,11 @@ export interface SessionTileDelegate {
}
let delegate: SessionTileDelegate | null = null
+export const $sessionTileDelegateRevision = atom(0)
export function setSessionTileDelegate(next: SessionTileDelegate) {
delegate = next
+ $sessionTileDelegateRevision.set($sessionTileDelegateRevision.get() + 1)
}
export function sessionTileDelegate(): SessionTileDelegate | null {
@@ -847,14 +929,13 @@ export function openSessionTile(
markSessionRead(storedSessionId)
ackStoredSessionId(storedSessionId)
- if (storedSessionId === $selectedStoredSessionId.get()) {
+ if (workspaceScope.workspaceMode === 'sessions' && storedSessionId === $selectedStoredSessionId.get()) {
return
}
const dock = anchor ?? focusedSessionTabAnchor() ?? undefined
- const workspaceOwnerKey =
- workspaceScope.workspaceMode === 'bots' ? workspaceScope.workspaceOwnerKey : undefined
+ const workspaceOwnerKey = workspaceScope.workspaceMode === 'bots' ? workspaceScope.workspaceOwnerKey : undefined
if (!tiles.some(t => t.storedSessionId === storedSessionId)) {
saveTiles([
@@ -863,9 +944,11 @@ export function openSessionTile(
anchor: dock,
before,
dir,
+ ownerRoute: workspaceScope.workspaceMode === 'bots' ? workspaceScope.ownerRoute : undefined,
storedSessionId,
workspaceMode: workspaceScope.workspaceMode,
- workspaceOwnerKey
+ workspaceOwnerKey,
+ workspaceTabTitle: workspaceScope.workspaceMode === 'bots' ? workspaceScope.workspaceTabTitle : undefined
}
])
// Adoption is async via the registry — order sync runs after the move path
@@ -938,7 +1021,10 @@ export function nextSessionTileForWorkspace(): null | string {
* Callers that own the router need the `'main'` vs `'tile'` distinction: a
* `'main'` hit only reaches the screen if the workspace pane is actually
* showing the chat, whereas a tile renders in its own pane regardless. */
-export function focusOpenSession(storedSessionId: string): 'main' | 'tile' | null {
+export function focusOpenSession(
+ storedSessionId: string,
+ workspaceScope: SessionTileWorkspaceScope = { workspaceMode: 'sessions' }
+): 'main' | 'tile' | null {
if ($sessionTiles.get().some(t => t.storedSessionId === storedSessionId)) {
const paneId = `${TILE_PANE_PREFIX}${storedSessionId}`
revealTreePane(paneId) // un-dismiss + adopt + front in its group
@@ -954,7 +1040,7 @@ export function focusOpenSession(storedSessionId: string): 'main' | 'tile' | nul
// Already the main session: front the workspace tab and drop tile focus so
// the readouts + sidebar highlight come home (a no-op when main is focused).
- if (storedSessionId === $selectedStoredSessionId.get()) {
+ if (workspaceScope.workspaceMode === 'sessions' && storedSessionId === $selectedStoredSessionId.get()) {
revealTreePane('workspace')
noteActiveTreeGroup(null)