Skip to content

The agent that grows with you

fix(desktop): record owner stub for unlisted tile drafts so session.resume routes (#102792)

Halldrixecdd72d17b4f
diff --git a/apps/desktop/src/app/session/hooks/use-session-actions.test.tsx b/apps/desktop/src/app/session/hooks/use-session-actions.test.tsx
index e8550299c1e..733261ddbcb 100644
--- a/apps/desktop/src/app/session/hooks/use-session-actions.test.tsx
+++ b/apps/desktop/src/app/session/hooks/use-session-actions.test.tsx
@@ -42,8 +42,11 @@ import {
$selectedStoredSessionId,
$sessions,
$turnStartedAt,
+ $unlistedSessionOwnerRows,
+ _resetSessionOwnerHintsForTests,
getSessionOwnerHint,
knownSessionOwner,
+ ownerLookupSessionRows,
sessionMatchesStoredId,
setActiveSessionId,
setActiveSessionStoredIdRotation,
@@ -63,8 +66,10 @@ import {
setResumeFailedSessionId,
setSelectedStoredSessionId,
setSessions,
- setTurnStartedAt
+ setTurnStartedAt,
+ setUnlistedSessionOwnerRows
} from '@/store/session'
+import { assertSessionOwnerResolved } from '@/store/session-owner-resolution'
import { $removedSessionIds, $sessionMutationsInFlight } from '@/store/session-removal'
import { requestForSessionProfile, type SessionProfileRoute } from '@/store/session-request-router'
import { $sessionTiles, sessionTileOwnerRoute } from '@/store/session-states'
@@ -77,6 +82,7 @@ import type { ClientSessionState } from '../../types'
import { useSessionActions } from './use-session-actions'
import { useSessionStateCache } from './use-session-state-cache'
+import { upsertOptimisticSession } from './use-session-actions/utils'
vi.mock('@/hermes', async importOriginal => ({
...(await importOriginal<Record<string, unknown>>()),
@@ -4140,6 +4146,119 @@ describe('openNewSessionTile workspace target', () => {
expect(createParams).not.toHaveProperty('cwd')
})
})
+
+describe('openNewSessionTile unlisted owner (#102792)', () => {
+ const STORED_UNLISTED = 'stored-unlisted-102792'
+
+ function createRequestGateway(stored: string = STORED_UNLISTED) {
+ return vi.fn(async (method: string) => {
+ if (method === 'session.create') {
+ return {
+ info: { cwd: '', model: 'test-model', skills: {}, tools: {} },
+ session_id: RUNTIME_SESSION_ID,
+ stored_session_id: stored
+ } as never
+ }
+
+ return {} as never
+ })
+ }
+
+ async function readyHandle(requestGateway: <T>(method: string, params?: Record<string, unknown>) => Promise<T>) {
+ let handle: HarnessHandle | null = null
+ render(<Harness onReady={value => (handle = value)} requestGateway={requestGateway} />)
+ await waitFor(() => expect(handle).not.toBeNull())
+
+ return handle!
+ }
+
+ beforeEach(() => {
+ setSessions([])
+ setMessagingSessions([])
+ setCronSessions([])
+ setUnlistedSessionOwnerRows([])
+ _resetSessionOwnerHintsForTests()
+ $profiles.set(profiles('default', 'omar'))
+ $activeGatewayProfile.set('omar')
+ $sessionTiles.set([])
+ })
+
+ afterEach(() => {
+ cleanup()
+ setSessions([])
+ setMessagingSessions([])
+ setCronSessions([])
+ setUnlistedSessionOwnerRows([])
+ _resetSessionOwnerHintsForTests()
+ $profiles.set([])
+ $activeGatewayProfile.set('default')
+ $sessionTiles.set([])
+ vi.restoreAllMocks()
+ })
+
+ it('records the ambient-profile owner for an unlisted tile created on the null (legacy ambient) route', async () => {
+ const handle = await readyHandle(createRequestGateway())
+
+ await act(async () => {
+ await handle.openNewSessionTile('center', { listed: false, route: null })
+ })
+
+ // The draft stays out of the visible sidebar list ...
+ expect($sessions.get().some(s => sessionMatchesStoredId(s, STORED_UNLISTED))).toBe(false)
+ // ... but its owner still resolves on the row rung (bare ambient profile),
+ // so the tile's immediate session.resume passes the fail-closed gate.
+ const owner = knownSessionOwner(ownerLookupSessionRows(), STORED_UNLISTED)
+ expect(owner).toBe('omar')
+ expect(() =>
+ assertSessionOwnerResolved(owner, { method: 'session.resume', sessionId: STORED_UNLISTED })
+ ).not.toThrow()
+ expect($sessionTiles.get().some(t => t.storedSessionId === STORED_UNLISTED)).toBe(true)
+ })
+
+ it('stamps the exact connection tag for an unlisted tile created on a routed connection', async () => {
+ vi.mocked(requestGatewayForAgent).mockResolvedValue({
+ info: { cwd: '', model: 'test-model', skills: {}, tools: {} },
+ session_id: RUNTIME_SESSION_ID,
+ stored_session_id: STORED_UNLISTED
+ } as never)
+ const handle = await readyHandle(createRequestGateway())
+
+ await act(async () => {
+ await handle.openNewSessionTile('center', { listed: false, route: { connectionId: 'conn-1', profile: 'omar' } })
+ })
+
+ expect($sessions.get().some(s => sessionMatchesStoredId(s, STORED_UNLISTED))).toBe(false)
+ expect(knownSessionOwner(ownerLookupSessionRows(), STORED_UNLISTED)).toEqual(
+ expect.objectContaining({ connectionId: 'conn-1', profile: 'omar' })
+ )
+ })
+
+ it('evicts the stub once a real row lists the same id', async () => {
+ const stored = 'stored-unlisted-102792-b'
+ const handle = await readyHandle(createRequestGateway(stored))
+
+ await act(async () => {
+ await handle.openNewSessionTile('center', { listed: false, route: null })
+ })
+
+ expect($unlistedSessionOwnerRows.get()).toHaveLength(1)
+
+ // First send lists the draft through the normal optimistic upsert ...
+ upsertOptimisticSession(
+ {
+ info: { cwd: '', model: 'test-model', skills: {}, tools: {} },
+ session_id: RUNTIME_SESSION_ID,
+ stored_session_id: stored
+ } as never,
+ stored
+ )
+
+ // ... which supersedes the stub instead of leaving a stale double.
+ expect($unlistedSessionOwnerRows.get()).toHaveLength(0)
+ expect($sessions.get().some(s => sessionMatchesStoredId(s, stored))).toBe(true)
+ expect(knownSessionOwner(ownerLookupSessionRows(), stored)).toBe('omar')
+ })
+})
describe('selectSidebarItem', () => {
it('fronts the workspace pane when navigating to a sidebar route (issue #72602)', async () => {
const navigate = vi.fn()
diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/index.ts b/apps/desktop/src/app/session/hooks/use-session-actions/index.ts
index a57fd538dc0..b2a7e893dc3 100644
--- a/apps/desktop/src/app/session/hooks/use-session-actions/index.ts
+++ b/apps/desktop/src/app/session/hooks/use-session-actions/index.ts
@@ -172,7 +172,8 @@ import {
sessionMatchesStoredId,
sessionShouldHaveTranscript,
toBranchMessages,
- upsertOptimisticSession
+ upsertOptimisticSession,
+ upsertUnlistedSessionOwner
} from './utils'
interface SessionActionsOptions {
@@ -829,9 +830,16 @@ export function useSessionActions({
// Seed the per-runtime cache so the tile renders immediately without a
// redundant resume. Only add the row to the SIDEBAR when `listed` — an
// unlisted (draft) tab stays out of the session list until its first
- // turn persists and a refresh surfaces it.
+ // turn persists and a refresh surfaces it. An unlisted draft still
+ // records an ownership stub (same stamps, off-list atom): without it a
+ // draft minted on the legacy ambient route (null route) owns NOTHING
+ // the ladder reads — no tile route, no hint, no row — and its
+ // immediate session.resume fails closed on multi-profile installs
+ // (#102792).
if (listed) {
upsertOptimisticSession(created, stored, null, null, null, undefined, capturedRoute)
+ } else {
+ upsertUnlistedSessionOwner(created, stored, capturedRoute)
}
// A tile lives in its OWN worktree, so it must not run the full
diff --git a/apps/desktop/src/app/session/hooks/use-session-actions/utils.ts b/apps/desktop/src/app/session/hooks/use-session-actions/utils.ts
index cafeed77a4d..e4351672cef 100644
--- a/apps/desktop/src/app/session/hooks/use-session-actions/utils.ts
+++ b/apps/desktop/src/app/session/hooks/use-session-actions/utils.ts
@@ -21,6 +21,7 @@ import {
ownerLookupSessionRows,
releaseWorkspaceCwdOwner,
sessionMatchesStoredId,
+ setUnlistedSessionOwnerRows,
setCronSessions,
setCurrentBranch,
setCurrentCwdTransient,
@@ -1275,6 +1276,53 @@ export function upsertOptimisticSession(
lastActive?: number,
owner?: null | SessionProfileRoute
) {
+ const session = buildOptimisticSession(created, id, title, preview, parentSessionId, lastActive, owner)
+
+ if (owner) {
+ setSessionOwnerHint(id, owner)
+ }
+
+ // A real row supersedes any unlisted-draft stub for the same id (first send
+ // on a ⌘T tab lists it); drop the stub so the atom stays bounded. The
+ // lookup shadow-filter covers any path that lists without passing here.
+ setUnlistedSessionOwnerRows(prev => (prev.some(s => s.id === id) ? prev.filter(s => s.id !== id) : prev))
+
+ setSessions(prev => [session, ...prev.filter(s => s.id !== id)])
+}
+
+/**
+ * Record the owner of an UNLISTED draft tile without touching the visible
+ * sidebar list (see `openNewSessionTile` with `listed: false`, #102792). The
+ * stub carries the same stamps an optimistic row would — ambient profile for
+ * an unrouted create, exact connection tag for a routed one — and rides only
+ * the owner-lookup path, never the sidebar render path. A later real row for
+ * the same id shadows it; the first send replaces it outright.
+ */
+export function upsertUnlistedSessionOwner(
+ created: SessionCreateResponse,
+ id: string,
+ owner?: null | SessionProfileRoute
+) {
+ const stub = buildOptimisticSession(created, id, null, null, null, undefined, owner)
+ setSessionOwnerHintForStub(id, owner)
+ setUnlistedSessionOwnerRows(prev => [stub, ...prev.filter(s => s.id !== id)])
+}
+
+function setSessionOwnerHintForStub(id: string, owner?: null | SessionProfileRoute): void {
+ if (owner) {
+ setSessionOwnerHint(id, owner)
+ }
+}
+
+function buildOptimisticSession(
+ created: SessionCreateResponse,
+ id: string,
+ title: string | null = null,
+ preview: string | null = null,
+ parentSessionId: string | null = null,
+ lastActive?: number,
+ owner?: null | SessionProfileRoute
+): SessionInfo {
const now = lastActive ?? Date.now() / 1000
// Stamp the profile the session was just created on so the scoped sidebar
// shows the new row immediately instead of filtering it out as "default"
@@ -1313,11 +1361,7 @@ export function upsertOptimisticSession(
...(connectionId ? { connection_id: connectionId } : {})
}
- if (owner) {
- setSessionOwnerHint(id, owner)
- }
-
- setSessions(prev => [session, ...prev.filter(s => s.id !== id)])
+ return session
}
export function patchSessionWorkspace(sessionId: string, cwd: string | undefined) {
@@ -1365,6 +1409,7 @@ export function dropListedSession(storedSessionId: string): void {
setSessions(prev => prev.filter(keep))
setMessagingSessions(prev => prev.filter(keep))
setCronSessions(prev => prev.filter(keep))
+ setUnlistedSessionOwnerRows(prev => prev.filter(keep))
}
export function restoreListedSession(session: SessionInfo, slice?: ListedSessionSlice): void {
diff --git a/apps/desktop/src/store/session.ts b/apps/desktop/src/store/session.ts
index 2e0a3bff126..fe23c29b7ad 100644
--- a/apps/desktop/src/store/session.ts
+++ b/apps/desktop/src/store/session.ts
@@ -792,6 +792,44 @@ export const $messagingPlatformTotals = atom<Record<string, number>>({})
// one platform may have more rows on disk than were loaded.
export const $messagingTruncated = atom<boolean>(false)
+/**
+ * Ownership stubs for UNLISTED draft tiles (the tab-strip "+" / project
+ * sidebar "+" with `listed: false`, see `openNewSessionTile`). A brand-new
+ * backend session is in-memory only until its first turn persists a row, so
+ * these drafts have no row in any sidebar slice — yet the tile's immediate
+ * `session.resume` must still name the backend that minted them. Without a
+ * stub, a draft minted on the legacy ambient route (null owner route: local
+ * source + named profile) records its owner NOWHERE — no tile route, no hint,
+ * no row — and every session-scoped RPC fails closed with
+ * SessionOwnerResolutionError on multi-profile installs (#102792).
+ *
+ * Stubs carry the SAME owner stamps an optimistic row would (ambient profile
+ * when the create was unrouted, exact connection tag when routed) but live
+ * outside $sessions so the drafts stay out of the visible sidebar list. Real
+ * rows always outrank stubs (shadow-filtered below); the first send replaces
+ * the stub via the normal optimistic upsert.
+ */
+export const $unlistedSessionOwnerRows = atom<SessionInfo[]>([])
+
+/** Drop stubs shadowed by a real row `id` already present in `rows`. Returns
+ * `rows` untouched (same reference) when there is nothing to append, so
+ * per-list memo caches keyed on the array identity still hit. */
+function withUnlistedOwnerStubs(rows: SessionInfo[], stubs: readonly SessionInfo[]): SessionInfo[] {
+ if (!stubs.length) {
+ return rows
+ }
+
+ const listed = new Set<string>()
+
+ for (const row of rows) {
+ listed.add(row.id)
+ }
+
+ const visible = stubs.filter(stub => !listed.has(stub.id))
+
+ return visible.length ? [...rows, ...visible] : rows
+}
+
/**
* Every session row the renderer knows, for OWNER lookups. The sidebar splits
* its fetch into three source-scoped slices ($sessions / $cronSessions /
@@ -802,19 +840,22 @@ export const $messagingTruncated = atom<boolean>(false)
* install failed closed with SessionOwnerResolutionError even though the row
* naming its owner was already in memory, one atom over. Concatenation order
* mirrors lookup priority: recents first (they can carry fresher optimistic
- * connection tags), then the cron and messaging slices.
+ * connection tags), then the cron and messaging slices. Unlisted-draft stubs
+ * ($unlistedSessionOwnerRows) ride last: a real row for the same id always
+ * shadows its stub, so a listed session never resolves off a stale stamp.
*/
export function ownerLookupSessionRows(): SessionInfo[] {
const cron = $cronSessions.get()
const messaging = $messagingSessions.get()
+ const stubs = $unlistedSessionOwnerRows.get()
// Recents-only stays the common case; keep its array identity (no copy) so
// per-list memo caches (lineageAliases) keyed on the reference still hit.
if (!cron.length && !messaging.length) {
- return $sessions.get()
+ return withUnlistedOwnerStubs($sessions.get(), stubs)
}
- return [...$sessions.get(), ...cron, ...messaging]
+ return withUnlistedOwnerStubs([...$sessions.get(), ...cron, ...messaging], stubs)
}
// Whether a profile's last session page was CAPPED by the request limit, keyed
@@ -1191,6 +1232,7 @@ export const setConnection = (next: Updater<HermesConnection | null>) => {
export const setGatewayState = (next: Updater<ConnectionState>) => updateAtom($gatewayState, next)
export const setSessions = (next: Updater<SessionInfo[]>) => updateAtom($sessions, next)
+export const setUnlistedSessionOwnerRows = (next: Updater<SessionInfo[]>) => updateAtom($unlistedSessionOwnerRows, next)
export const setCronSessions = (next: Updater<SessionInfo[]>) => updateAtom($cronSessions, next)
export const setMessagingSessions = (next: Updater<SessionInfo[]>) => updateAtom($messagingSessions, next)
export const setMessagingPlatformTotals = (next: Updater<Record<string, number>>) =>