The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): retire empty restored tabs after conclusive absence
funky-xamarin7a086ff53b61
diff --git a/apps/desktop/src/app/chat/session-tile-gone.test.ts b/apps/desktop/src/app/chat/session-tile-gone.test.tsnew file mode 100644index 00000000000..4faf0e01436--- /dev/null+++ b/apps/desktop/src/app/chat/session-tile-gone.test.ts@@ -0,0 +1,137 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++import { getSession } from '@/hermes'+import { probeStoredSession } from '@/app/session/hooks/use-session-actions/utils'+import { setApiRequestConnection } from '@/api/client'+import { stashSessionDraft, clearSessionDraft, takeSessionDraft } from '@/store/composer'+import { $gatewaySwitching } from '@/store/gateway-switch'+import { $activeGatewayProfile, $profiles } from '@/store/profile'+import { $connection, $gatewayState, $sessions } from '@/store/session'+import { $sessionTiles, openSessionTile } from '@/store/session-states'++import { startUnrestoredTileTitleBackfill } from './session-tile'++vi.mock('@/hermes', async importActual => ({+ ...(await importActual<typeof import('@/hermes')>()),+ getSession: vi.fn()+}))++const get = vi.mocked(getSession)+let stop: (() => void) | undefined++beforeEach(() => {+ $gatewayState.set('idle')+ $activeGatewayProfile.set('default')+ $profiles.set([{ name: 'default' }, { name: 'writer' }] as never)+ $connection.set({ connectionId: 'local', mode: 'local' } as never)+ $sessions.set([])+ $sessionTiles.set([])+ get.mockReset()+})++afterEach(() => {+ stop?.()+ $gatewayState.set('idle')+ $sessionTiles.set([])+ $sessions.set([])+ $profiles.set([])+ $connection.set(null)+ $gatewaySwitching.set(false)+ clearSessionDraft('deleted-chat')+ window.localStorage.clear()+})++describe('restored dead tile backfill', () => {+ it('uses the real REST scope ladder and preserves caller-selected ownership', async () => {+ const actual = await vi.importActual<typeof import('@/hermes')>('@/hermes')+ const previous = window.hermesDesktop+ const api = vi.fn(async (_request: { path: string }) => { throw new Error('404: {"detail":"Session not found"}') })+ window.hermesDesktop = { ...previous, api } as never+ setApiRequestConnection('local')+ get.mockImplementation(actual.getSession)+ try {+ expect(await probeStoredSession('deleted-chat')).toEqual({ status: 'gone' })+ expect(api.mock.calls.map(([request]) => (request as { path: string }).path)).toEqual([+ '/api/sessions/deleted-chat?profile=default', '/api/sessions/deleted-chat?profile=writer'+ ])+ api.mockClear()+ expect(await probeStoredSession('deleted-chat', { connectionId: 'remote', profile: 'alias', targetProfile: 'actual' })).toEqual({ status: 'gone' })+ expect(api).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ connectionId: 'remote', profile: 'actual', path: '/api/sessions/deleted-chat?profile=actual' }))+ } finally {+ window.hermesDesktop = previous+ setApiRequestConnection(null)+ }+ })++ it.each(['500: Session not found', '404: endpoint unavailable', 'network disconnected'])(+ 'keeps inconclusive misses: %s',+ async message => {+ openSessionTile('deleted-chat')+ get.mockRejectedValueOnce(new Error(message)).mockRejectedValue(new Error('404: Session not found'))+ stop = startUnrestoredTileTitleBackfill()+ $gatewayState.set('open')+ await vi.waitFor(() => expect(get).toHaveBeenCalledTimes(2))+ expect($sessionTiles.get()).toHaveLength(1)+ }+ )++ it('preserves a working cross-profile fallback and fills its title', async () => {+ openSessionTile('deleted-chat')+ get+ .mockRejectedValueOnce(new Error('network disconnected'))+ .mockResolvedValueOnce({ id: 'deleted-chat', title: 'Found' } as never)+ stop = startUnrestoredTileTitleBackfill()+ $gatewayState.set('open')+ await vi.waitFor(() => expect($sessions.get()[0]?.title).toBe('Found'))+ expect($sessionTiles.get()).toHaveLength(1)+ })++ it.each(['draft', 'switch', 'profile ABA', 'cancel', 'bound', 'no inventory', 'other backend'])(+ 'preserves tiles when unsafe: %s',+ async reason => {+ openSessionTile(+ 'deleted-chat',+ 'right',+ undefined,+ undefined,+ reason === 'other backend' ? { workspaceMode: 'sessions', ownerRoute: { connectionId: 'remote', profile: 'writer' } } : undefined+ )+ if (reason === 'draft') stashSessionDraft('deleted-chat', 'keep my words', [])+ if (reason === 'switch') $gatewaySwitching.set(true)+ if (reason === 'no inventory') $profiles.set([])+ let reject!: (error: Error) => void+ get.mockRejectedValue(new Error('404: Session not found')).mockImplementationOnce(+ () =>+ new Promise((_resolve, no) => {+ reject = no+ })+ )+ stop = startUnrestoredTileTitleBackfill()+ $gatewayState.set('open')+ if (reason === 'profile ABA') {+ $activeGatewayProfile.set('writer')+ $activeGatewayProfile.set('default')+ }+ if (reason === 'cancel') stop()+ if (reason === 'bound') $sessionTiles.set($sessionTiles.get().map(tile => ({ ...tile, runtimeId: 'live' })))+ reject(new Error('404: Session not found'))+ await vi.waitFor(() =>+ expect(get).toHaveBeenCalledTimes(reason === 'other backend' || reason === 'no inventory' ? 1 : 2)+ )+ expect($sessionTiles.get()).toHaveLength(1)+ if (reason === 'draft') expect(takeSessionDraft('deleted-chat').text).toBe('keep my words')+ }+ )++ it('persistently closes an empty tile after every profile confirms the session is gone', async () => {+ openSessionTile('deleted-chat')+ get.mockRejectedValue(new Error('404: Session not found'))+ stop = startUnrestoredTileTitleBackfill()+ $gatewayState.set('open')++ await vi.waitFor(() => expect(get).toHaveBeenCalledTimes(2))+ await vi.waitFor(() => expect($sessionTiles.get()).toEqual([]))+ expect(window.localStorage.getItem('hermes.desktop.sessionTiles.v2') ?? '').not.toContain('deleted-chat')+ expect(get.mock.calls.map(call => call[1])).toEqual(['default', 'writer'])+ })+})diff --git a/apps/desktop/src/app/chat/session-tile.tsx b/apps/desktop/src/app/chat/session-tile.tsxindex e94f862bb2d..c1a1e7ba805 100644--- a/apps/desktop/src/app/chat/session-tile.tsx+++ b/apps/desktop/src/app/chat/session-tile.tsx@@ -22,7 +22,7 @@ import { useCallback, useEffect, useMemo, useRef, useSyncExternalStore } from 'rimport { useGatewayRequest } from '@/app/gateway/hooks/use-gateway-request'import { useModelControls } from '@/app/session/hooks/use-model-controls'import { blobToDataUrl } from '@/app/session/hooks/use-prompt-actions/utils'-import { resolveStoredSession } from '@/app/session/hooks/use-session-actions/utils'+import { probeStoredSession, resolveStoredSession } from '@/app/session/hooks/use-session-actions/utils'import { ModelMenuPanel } from '@/app/shell/model-menu-panel'import { ReasoningMenuPanel } from '@/app/shell/reasoning-menu-panel'import { formatRefValue } from '@/components/assistant-ui/directive-text'@@ -41,9 +41,10 @@ import { useI18n } from '@/i18n'import type { ChatMessage } from '@/lib/chat-messages'import { NEW_SESSION_TITLE, sessionTitle } from '@/lib/chat-runtime'import { transcribeAudioClientDirect } from '@/lib/voice-client-direct'-import { createComposerAttachmentScope, draftTitleFor } from '@/store/composer'+import { createComposerAttachmentScope, draftTitleFor, takeSessionDraft } from '@/store/composer'+import { $gatewaySwitching } from '@/store/gateway-switch'import { $pinnedSessionIds, pinSession, unpinSession } from '@/store/layout'-import { $activeGatewayProfile } from '@/store/profile'+import { $activeGatewayProfile, $gatewaySwapTarget, $profiles } from '@/store/profile'import { $projectTree } from '@/store/projects'import { sessionAwaitingInput } from '@/store/prompts'import {@@ -622,9 +623,14 @@ export function tileStoredRow(storedSessionId: string): SessionInfo | undefined* A restored background tab has no runtimeId and does not mount its pane, so* the resolution effect above never runs; when its row is outside the recents* page and project tree, `tileTitle()` reads "New session" until first click.- * `resolveStoredSession` upserts the row into `$sessions`, which the tab strip- * already watches — nothing is persisted. Runs once the gateway can answer. */-export function startUnrestoredTileTitleBackfill(lookup = resolveStoredSession): () => void {+ * The shared probe upserts found rows for the tab strip. An empty restored+ * tile with authoritative all-profile absence is persistently closed; drafts+ * and inconclusive/switching lookups stay recoverable. */+export function startUnrestoredTileTitleBackfill(lookup = probeStoredSession): () => void {+ // Only tiles present at startup can be retired: a newly created unbound+ // draft may legitimately have no durable row yet.+ const restored = new Set($sessionTiles.get().filter(tile => !tile.runtimeId))+ let cancelled = falseconst run = () => {if ($gatewayState.get() !== 'open') {return@@ -634,7 +640,43 @@ export function startUnrestoredTileTitleBackfill(lookup = resolveStoredSession):for (const tile of $sessionTiles.get()) {if (!tile.runtimeId && !tile.workspaceTabTitle && !tileStoredRow(tile.storedSessionId)) {- void lookup(tile.storedSessionId, tile.ownerRoute).catch(() => undefined)+ // Any scope transition invalidates absence evidence, including A→B→A.+ let changed = $gatewaySwitching.get() || Boolean($gatewaySwapTarget.get())+ const invalidate = () => {+ changed = true+ }+ const unlisten = [+ $connection.listen(invalidate),+ $activeGatewayProfile.listen(invalidate),+ $profiles.listen(invalidate),+ $gatewayState.listen(invalidate),+ $gatewaySwitching.listen(invalidate),+ $gatewaySwapTarget.listen(invalidate)+ ]+ const hasInventory = Boolean(tile.ownerRoute) || $profiles.get().length > 0++ void lookup(tile.storedSessionId, tile.ownerRoute)+ .then(result => {+ const draft = takeSessionDraft(tile.storedSessionId)+ if (+ result?.status === 'gone' &&+ !cancelled &&+ !changed &&+ hasInventory &&+ restored.has(tile) &&+ $sessionTiles.get().includes(tile) &&+ !tile.runtimeId &&+ tile.workspaceMode !== 'bots' &&+ !tileStoredRow(tile.storedSessionId) &&+ !tileBackendIdentityChanged(tile.ownerRoute?.connectionId, $connection.get()) &&+ !draft.text.trim() &&+ draft.attachments.length === 0+ ) {+ closeSessionTile(tile.storedSessionId)+ }+ })+ .catch(() => undefined)+ .finally(() => unlisten.forEach(off => off()))}}}@@ -642,7 +684,10 @@ export function startUnrestoredTileTitleBackfill(lookup = resolveStoredSession):const off = $gatewayState.listen(run)run()- return off+ return () => {+ cancelled = true+ off()+ }}/** Drop persisted tile bindings that belong to a different backend than thediff --git a/apps/desktop/src/app/session/hooks/use-session-actions/utils.ts b/apps/desktop/src/app/session/hooks/use-session-actions/utils.tsindex 466bca28ba7..eae78430caf 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@@ -1955,10 +1955,27 @@ export function cachedSessionRow(storedSessionId: string): SessionInfo | undefin)}+export type StoredSessionProbe = { status: 'found'; session: SessionInfo } | { status: 'gone' | 'inconclusive' }+export async function resolveStoredSession(storedSessionId: string,ownerRoute?: SessionProfileRoute): Promise<SessionInfo | undefined> {+ const result = await probeStoredSession(storedSessionId, ownerRoute)++ return result.status === 'found' ? result.session : undefined+}++/** Preserve the probe ladder's evidence: only explicit session 404s prove absence. */+export async function probeStoredSession(+ storedSessionId: string,+ ownerRoute?: SessionProfileRoute+): Promise<StoredSessionProbe> {+ let allGone = true+ const recordFailure = (error: unknown) => {+ const message = error instanceof Error ? error.message : String(error ?? '')+ allGone &&= /\b404\b/.test(message) && /session not found/i.test(message)+ }// Snapshot BEFORE any await: a resolve that started before an archive/delete// must reject its own stale response (see upsertResolvedSession).const tombstoneGenerationsAtRequestStart = captureSessionTombstoneGenerations()@@ -1977,7 +1994,7 @@ export async function resolveStoredSession((!cached.profile || normalizeProfileKey(cached.profile) === normalizeProfileKey(ownerRoute.profile))if (cached && cachedOwnerMatches) {- return cached+ return { status: 'found', session: cached }}try {@@ -1986,11 +2003,12 @@ export async function resolveStoredSession(session.connection_id = ownerRoute.connectionIdupsertResolvedSession(session, storedSessionId, tombstoneGenerationsAtRequestStart)- return session- } catch {+ return { status: 'found', session }+ } catch (error) {// An explicit owner is fail-closed. Probing the ambient or another// profile would turn a stale route into a cross-connection open.- return undefined+ recordFailure(error)+ return { status: allGone ? 'gone' : 'inconclusive' }}}@@ -2001,7 +2019,7 @@ export async function resolveStoredSession(const multiProfile = $profiles.get().length > 1if (cached && (cached.profile?.trim() || !multiProfile)) {- return cached+ return { status: 'found', session: cached }}// Direct by-id on the active profile — one row lookup, no list scan. Electron@@ -2020,9 +2038,10 @@ export async function resolveStoredSession(upsertResolvedSession(session, storedSessionId, tombstoneGenerationsAtRequestStart)- return session- } catch {+ return { status: 'found', session }+ } catch (error) {// Not on the active profile — fall through to the cross-profile probe.+ recordFailure(error)}// Multi-profile only: probe each remaining profile by id (still one cheap@@ -2046,13 +2065,14 @@ export async function resolveStoredSession(upsertResolvedSession(session, storedSessionId, tombstoneGenerationsAtRequestStart)- return session- } catch {+ return { status: 'found', session }+ } catch (error) {// Not on this profile; try the next.+ recordFailure(error)}}- return undefined+ return { status: allGone ? 'gone' : 'inconclusive' }}/**