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.
This commit is contained in:
@@ -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
|
||||
|
||||
142
apps/desktop/src/store/connections-launch-user-open.test.ts
Normal file
142
apps/desktop/src/store/connections-launch-user-open.test.ts
Normal file
@@ -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 | string>(null)
|
||||
const $selectedStoredSessionId = atom<null | string>(null)
|
||||
|
||||
const $connection = atom<null | {
|
||||
connectionId?: string
|
||||
mode?: 'local' | 'remote'
|
||||
profile?: string
|
||||
registryScoped?: boolean
|
||||
}>(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<void> => 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<void> {
|
||||
const dial = deferred<void>()
|
||||
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')
|
||||
})
|
||||
})
|
||||
@@ -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<void> {
|
||||
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<void> {
|
||||
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<DesktopConnectionsRegistry | null> {
|
||||
const freshSessionRequest = $freshSessionRequest.get()
|
||||
const userOpenSince = currentUserSessionOpen()
|
||||
|
||||
const [registry, defaultLoaded] = await Promise.all([
|
||||
refreshConnectionsRegistry(),
|
||||
@@ -478,10 +482,16 @@ export async function initializeConnectionsRegistry(): Promise<DesktopConnection
|
||||
await waitForInitialConnection()
|
||||
|
||||
// The user got there first: a source they picked while boot was settling
|
||||
// (statusbar switcher, fleet profile rail) is not drift to "restore" over.
|
||||
// (statusbar switcher, fleet profile rail), or a chat they opened, is not
|
||||
// drift to "restore" over.
|
||||
// The launch preference only decides where a window lands when nobody has
|
||||
// said otherwise yet.
|
||||
if (switchRevision > 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<DesktopConnection
|
||||
}
|
||||
|
||||
if (registry.connections.some(connection => 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<DesktopConnection
|
||||
return registry
|
||||
}
|
||||
|
||||
await restorePreferredConnection(preferredId, preferred?.kind, freshSessionRequest)
|
||||
await restorePreferredConnection(preferredId, preferred?.kind, freshSessionRequest, userOpenSince)
|
||||
|
||||
return $connectionsRegistry.get() ?? registry
|
||||
}
|
||||
@@ -567,14 +577,24 @@ export interface SelectConnectionOptions {
|
||||
* source yet, so a second restore pass — the normal case, because main opens
|
||||
* the local backend before the registry settles — read as user-initiated. */
|
||||
restore?: boolean
|
||||
/** The launch restores: the user-open revision (store/session-open-intent)
|
||||
* when boot began. A chat the person opened since then wins over the
|
||||
* restore, however early it was opened; a chat selected automatically (the
|
||||
* cold-start route resume) does not bump it, so the restore still lands. */
|
||||
userOpenSince?: number
|
||||
/** The startup profile re-home only: it gives way to a conversation opened
|
||||
* while it dials. Other silent restores keep main's behaviour (the restore
|
||||
* wins), since a session selected during them may itself be automatic. */
|
||||
yieldToOpenedSession?: boolean
|
||||
}
|
||||
|
||||
/** The startup re-home never closes a conversation opened while it dialed. */
|
||||
/** A launch restore never closes a conversation the person opened, and the
|
||||
* startup re-home never closes one opened while it dialed. */
|
||||
function restoreYields(options: SelectConnectionOptions, openedSession: string): boolean {
|
||||
if (options.userOpenSince !== undefined && currentUserSessionOpen() !== options.userOpenSince) {
|
||||
return true
|
||||
}
|
||||
|
||||
return options.yieldToOpenedSession === true && openSessionKey() !== openedSession
|
||||
}
|
||||
|
||||
@@ -690,10 +710,12 @@ export async function selectConnection(connectionId: string, options: SelectConn
|
||||
const activation = new AbortController()
|
||||
let rehomed = false
|
||||
pendingTarget = targetKey
|
||||
|
||||
abandonInFlight = () => {
|
||||
activation.abort()
|
||||
rollbackRehome(rehomed, currentProfile, targetIsActive)
|
||||
}
|
||||
|
||||
$pendingConnectionId.set(connectionId)
|
||||
let undoRehome = (): void => undefined
|
||||
|
||||
|
||||
14
apps/desktop/src/store/session-open-intent.ts
Normal file
14
apps/desktop/src/store/session-open-intent.ts
Normal file
@@ -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
|
||||
}
|
||||
Reference in New Issue
Block a user