From fc6445ede5ee5c8100033a93d42a977d36f24ce9 Mon Sep 17 00:00:00 2001 From: Teknium <127238744+teknium1@users.noreply.github.com> Date: Sun, 1 Nov 2026 19:18:09 -0800 Subject: [PATCH] fix(desktop): the launch restore never closes a chat the person opened With launch mode "last used" on a gateway other than the one main opens first, the window paints on This device and the launch restore (restorePreferredConnection -> restoreConnection(preferredId)) dials the saved gateway in the background. That restore does not yield (only the startup profile re-home does, #147711), so a stored chat the person opened right as the window painted was closed when the restore landed seconds later and the window jumped to a blank draft on the other gateway. openSession, the one door every surface opens a chat through, now bumps a user-open revision (store/session-open-intent). The launch restores carry the revision captured when boot began and give way once it moves. Route effects that select a chat on their own (the cold-start route resume, runtime recovery) never bump it, so those restores still land as on main. --- apps/desktop/src/app/open-session.ts | 4 + .../connections-launch-user-open.test.ts | 142 ++++++++++++++++++ apps/desktop/src/store/connections.ts | 42 ++++-- apps/desktop/src/store/session-open-intent.ts | 14 ++ 4 files changed, 192 insertions(+), 10 deletions(-) create mode 100644 apps/desktop/src/store/connections-launch-user-open.test.ts create mode 100644 apps/desktop/src/store/session-open-intent.ts diff --git a/apps/desktop/src/app/open-session.ts b/apps/desktop/src/app/open-session.ts index b4da7a42c4..e7466cc7ee 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, requestSessionResume } from '@/store/session' +import { noteUserSessionOpen } from '@/store/session-open-intent' import type { SessionProfileRoute } from '@/store/session-request-router' import { focusedSessionNeedsRoute, @@ -141,6 +142,9 @@ export function openSession( resolved = 'tab' } + // A chat opened in this window: the launch restore must not close it. + noteUserSessionOpen() + if (resolved === 'main') { // Canonical relationship chats explicitly own the main workspace. Route // even when the session is already open as a tile; resumeSession removes diff --git a/apps/desktop/src/store/connections-launch-user-open.test.ts b/apps/desktop/src/store/connections-launch-user-open.test.ts new file mode 100644 index 0000000000..73f4ea45ca --- /dev/null +++ b/apps/desktop/src/store/connections-launch-user-open.test.ts @@ -0,0 +1,142 @@ +import { atom } from 'nanostores' +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' + +import type { DesktopAgentRoster, DesktopConnectionsRegistry } from '@/global' + +import { deferred } from '../test/deferred' + +// The launch restore onto the last-used gateway dials while the window already +// shows the source main opened first, so the person can open a chat before it +// lands. A chat they opened is theirs: the restore gives way. A chat selected +// on its own (the cold-start route resume) is not, and the restore still lands. + +const $activeGatewayProfile = atom('default') +const $freshSessionRequest = atom(0) +const $activeSessionId = atom(null) +const $selectedStoredSessionId = atom(null) + +const $connection = atom(null) + +const ensureGatewayAgent = vi.fn( + async (connectionId: null | string, profile: string, options?: { beforeActivate?: () => boolean }) => { + if (options?.beforeActivate && !options.beforeActivate()) { + return + } + + $connection.set({ connectionId: connectionId ?? undefined, mode: 'remote', profile, registryScoped: true }) + } +) + +const openGatewayAgent = vi.fn(async (_connectionId: string, _profile: string): Promise => undefined) + +vi.mock('@/store/session', () => ({ + $connection, + $activeSessionId, + $selectedStoredSessionId, + setActiveSessionId: (id: null | string) => $activeSessionId.set(id), + setSelectedStoredSessionId: (id: null | string) => $selectedStoredSessionId.set(id) +})) +vi.mock('@/store/project-scope', () => ({ exitProjectScope: vi.fn() })) +vi.mock('@/store/gateway-switch', () => ({ supersedeGatewaySwitch: vi.fn() })) +vi.mock('@/store/profile', () => ({ + $activeGatewayProfile, + $freshSessionRequest, + $newChatProfile: atom(null), + $newChatRoute: atom(null), + $showAllProfiles: atom(false), + captureNewChatSource: vi.fn(), + currentNewChatIntent: () => 0, + ensureGatewayAgent, + normalizeProfileKey: (name: null | string | undefined) => (name ?? '').trim() || 'default', + openGatewayAgent, + refreshActiveProfile: vi.fn(async () => undefined), + requestFreshSession: vi.fn() +})) + +const { _resetConnectionsForTests, initializeConnectionsRegistry } = await import('./connections') +const { _resetFleetRosterForTests } = await import('./fleet-roster') +const { noteUserSessionOpen } = await import('./session-open-intent') + +const registry: DesktopConnectionsRegistry = { + connections: [ + { id: 'local', kind: 'local', label: 'This device', tokenPreview: null, tokenSet: false }, + { id: 'box', kind: 'ssh', label: 'Box', tokenPreview: null, tokenSet: false } + ], + lastUsed: 'box', + launchMode: 'last-used', + primary: 'local', + secureTokenStorage: true, + version: 2 +} + +const reachable: DesktopAgentRoster = { + agents: [], + sources: [ + { connectionId: 'local', kind: 'local', label: 'This device', reachable: true }, + { connectionId: 'box', kind: 'ssh', label: 'Box', reachable: true, error: 'connect-on-demand' } + ] +} + +const setLastUsed = vi.fn(async (id: string) => ({ ok: true, registry: { ...registry, lastUsed: id } })) + +beforeEach(() => { + localStorage.clear() + _resetConnectionsForTests() + _resetFleetRosterForTests() + $connection.set({ connectionId: 'local', mode: 'local', registryScoped: true }) + $activeGatewayProfile.set('default') + $activeSessionId.set(null) + $selectedStoredSessionId.set(null) + ensureGatewayAgent.mockClear() + openGatewayAgent.mockReset() + setLastUsed.mockClear() + vi.stubGlobal('window', { + hermesDesktop: { + api: vi.fn(async () => ({ profiles: [] })), + connections: { list: vi.fn(async () => registry), setLastUsed }, + getAgentRoster: async () => reachable + }, + localStorage, + location: window.location + }) +}) + +afterEach(() => vi.unstubAllGlobals()) + +async function bootWhile(select: () => void): Promise { + const dial = deferred() + openGatewayAgent.mockReturnValueOnce(dial.promise) + + const boot = initializeConnectionsRegistry() + await vi.waitFor(() => expect(openGatewayAgent).toHaveBeenCalledWith('box', 'default')) + select() + dial.resolve() + await boot +} + +describe('launch restore onto the last-used gateway', () => { + it('never closes a chat the person opened while it dialed', async () => { + await bootWhile(() => { + // openSession marks the intent at the click; the resume binds later. + noteUserSessionOpen() + $selectedStoredSessionId.set('opened-by-user') + }) + + expect($selectedStoredSessionId.get()).toBe('opened-by-user') + expect($connection.get()?.connectionId).toBe('local') + expect(setLastUsed).not.toHaveBeenCalled() + }) + + it('still lands over a chat selected automatically, as the cold-start route resume does', async () => { + await bootWhile(() => $selectedStoredSessionId.set('resumed-from-route')) + + expect($connection.get()?.connectionId).toBe('box') + expect($selectedStoredSessionId.get()).toBeNull() + expect(setLastUsed).toHaveBeenCalledWith('box') + }) +}) diff --git a/apps/desktop/src/store/connections.ts b/apps/desktop/src/store/connections.ts index 55069ae142..01a78138fb 100644 --- a/apps/desktop/src/store/connections.ts +++ b/apps/desktop/src/store/connections.ts @@ -40,6 +40,7 @@ import { setActiveSessionId, setSelectedStoredSessionId } from '@/store/session' +import { currentUserSessionOpen } from '@/store/session-open-intent' import { reloadOpenStarmapGraph, resetStarmapGraph } from '@/store/starmap' import { isPeerInstanceWindow, windowProfileOverride } from '@/store/windows' @@ -375,7 +376,8 @@ async function restoreConnection(connectionId: string, options: SelectConnection async function reconcileStartupProfile( connectionId: string, kind: string | undefined, - freshSessionRequest: number + freshSessionRequest: number, + userOpenSince: number ): Promise { if (kind === 'local' || $activeSessionId.get() || $selectedStoredSessionId.get()) { return @@ -419,7 +421,7 @@ async function reconcileStartupProfile( ) if (target) { - await restoreConnection(connectionId, { profile: target, yieldToOpenedSession: true }) + await restoreConnection(connectionId, { profile: target, userOpenSince, yieldToOpenedSession: true }) } else if ( roster.profiles.some(candidate => candidate.name === profile) && (served === null || served.has(profile)) @@ -433,16 +435,17 @@ async function reconcileStartupProfile( async function restorePreferredConnection( preferredId: string, kind: string | undefined, - freshSessionRequest: number + freshSessionRequest: number, + userOpenSince: number ): Promise { if ($activeConnectionId.get() !== preferredId) { - await restoreConnection(preferredId) + await restoreConnection(preferredId, { userOpenSince }) return } const revision = switchRevision - await reconcileStartupProfile(preferredId, kind, freshSessionRequest) + await reconcileStartupProfile(preferredId, kind, freshSessionRequest, userOpenSince) // The roster read is a window: a pick that landed meanwhile saved its own // source, and the reconcile's own switch already saved this one. @@ -459,6 +462,7 @@ async function restorePreferredConnection( */ export async function initializeConnectionsRegistry(): Promise { const freshSessionRequest = $freshSessionRequest.get() + const userOpenSince = currentUserSessionOpen() const [registry, defaultLoaded] = await Promise.all([ refreshConnectionsRegistry(), @@ -478,10 +482,16 @@ export async function initializeConnectionsRegistry(): Promise 0 || pendingTarget !== null || $freshSessionRequest.get() !== freshSessionRequest) { + if ( + switchRevision > 0 || + pendingTarget !== null || + $freshSessionRequest.get() !== freshSessionRequest || + currentUserSessionOpen() !== userOpenSince + ) { return registry } @@ -503,7 +513,7 @@ export async function initializeConnectionsRegistry(): Promise connection.id === connectionId)) { - await restoreConnection(connectionId, { profile: defaultRoute.profile }) + await restoreConnection(connectionId, { profile: defaultRoute.profile, userOpenSince }) } return $connectionsRegistry.get() ?? registry @@ -534,7 +544,7 @@ export async function initializeConnectionsRegistry(): Promise { activation.abort() rollbackRehome(rehomed, currentProfile, targetIsActive) } + $pendingConnectionId.set(connectionId) let undoRehome = (): void => undefined diff --git a/apps/desktop/src/store/session-open-intent.ts b/apps/desktop/src/store/session-open-intent.ts new file mode 100644 index 0000000000..9dbd688ed0 --- /dev/null +++ b/apps/desktop/src/store/session-open-intent.ts @@ -0,0 +1,14 @@ +// Bumped when the person opens a chat in this window (sidebar row, ⌘K, a +// notification, the session switcher: every door goes through openSession). +// Route effects that select a chat on their own (the cold-start route resume, +// runtime recovery) never bump it, so a background restore can tell a chat the +// user chose, which it must leave open, from one selected automatically. +let userSessionOpenRevision = 0 + +export function currentUserSessionOpen(): number { + return userSessionOpenRevision +} + +export function noteUserSessionOpen(): void { + userSessionOpenRevision += 1 +}