Skip to content

The agent that grows with you

fix(desktop): route messaging session DELETE/archive to owning profile

Jeremy718654a9a234
diff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/index.ts b/apps/desktop/src/app/session/hooks/use-prompt-actions/index.ts
index 23415723a35..75712af2359 100644
--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/index.ts
+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/index.ts
@@ -28,6 +28,7 @@ import { clearPreviewArtifacts } from '@/store/preview-status'
import { clearAllPrompts } from '@/store/prompts'
import {
$busy,
+ $connection,
$currentCwd,
$messages,
$terminalBackend,
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 978e4854e2b..74f5e97efda 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
@@ -12,39 +12,47 @@ import {
getAllSessionMessages,
getLatestSessionMessages,
getSession,
+ type ProfileScope,
type SessionInfo,
- type SessionResumeResponse
+ type SessionResumeResponse,
+ setSessionArchived
} from '@/hermes'
import { createClientSessionState } from '@/lib/chat-runtime'
import { $clarifyRequests, clearClarifyRequest, setClarifyRequest } from '@/store/clarify'
import { clearSessionDraft, stashSessionDraft, takeSessionDraft } from '@/store/composer'
import { requestGatewayForAgent, requestGatewayForProfile } from '@/store/gateway'
-import { $activeGatewayProfile, $newChatProfile, $newChatRoute, ensureGatewayProfile } from '@/store/profile'
-import { $projectScope, $projectTree, ALL_PROJECTS } from '@/store/projects'
+import { $pinnedSessionIds } from '@/store/layout'
+import { $activeGatewayProfile, $newChatProfile, $newChatRoute, $profiles, ensureGatewayProfile } from '@/store/profile'
+import { $projectScope, $projectTree, $removedSessionIds, $sessionMutationsInFlight, ALL_PROJECTS } from '@/store/projects'
import {
$activeSessionId,
$activeSessionStoredIdRotation,
+ $cronSessions,
$currentCwd,
$currentFastMode,
$currentModel,
$currentProvider,
$currentReasoningEffort,
$messages,
+ $messagingSessions,
$newChatWorkspaceTarget,
$resumeFailedSessionId,
$selectedStoredSessionId,
+ $sessions,
$turnStartedAt,
setActiveSessionId,
setActiveSessionStoredIdRotation,
setAwaitingResponse,
setBusy,
setConnection,
+ setCronSessions,
setCurrentCwd,
setCurrentFastMode,
setCurrentModel,
setCurrentProvider,
setCurrentReasoningEffort,
setMessages,
+ setMessagingSessions,
setNewChatWorkspaceTarget,
setResumeFailedSessionId,
setSelectedStoredSessionId,
@@ -53,6 +61,7 @@ import {
} from '@/store/session'
import type { SessionProfileRoute } from '@/store/session-request-router'
import { $sessionTiles } from '@/store/session-states'
+import { $sessionSeenCounts, $unreadFinishedMarkers } from '@/store/session-unread'
import sessionResumeActiveTurn from '../../../../../../tests/fixtures/session-resume-active-turn.json'
import { deferred } from '../../../test/deferred'
@@ -95,6 +104,7 @@ const RUNTIME_SESSION_ID = 'rt-new-001'
type HarnessHandle = Pick<
ReturnType<typeof useSessionActions>,
+ | 'archiveSession'
| 'createBackendSessionForSend'
| 'openNewSessionTile'
| 'removeSession'
@@ -3352,3 +3362,176 @@ describe('selectSidebarItem', () => {
expect(revealTreePane).toHaveBeenCalledWith('workspace')
})
})
+
+const mockDeleteSession = vi.mocked(deleteSession)
+const mockGetSession = vi.mocked(getSession)
+const mockSetSessionArchived = vi.mocked(setSessionArchived)
+const profiles = (...names: string[]) => names.map(name => ({ name }) as never)
+
+describe('removeSession / archiveSession profile routing (#78836)', () => {
+ beforeEach(() => {
+ setSessions([])
+ setMessagingSessions([])
+ setCronSessions([])
+ $profiles.set(profiles('default', 'winefox'))
+ $activeGatewayProfile.set('default')
+ $pinnedSessionIds.set([])
+ $removedSessionIds.set(new Set())
+ $sessionMutationsInFlight.set(new Set())
+ $sessionSeenCounts.set({})
+ $unreadFinishedMarkers.set({})
+ mockDeleteSession.mockReset()
+ mockGetSession.mockReset()
+ mockSetSessionArchived.mockReset()
+ })
+
+ afterEach(() => {
+ cleanup()
+ setSessions([])
+ setMessagingSessions([])
+ setCronSessions([])
+ $profiles.set([])
+ $activeGatewayProfile.set('default')
+ $pinnedSessionIds.set([])
+ $removedSessionIds.set(new Set())
+ $sessionMutationsInFlight.set(new Set())
+ $sessionSeenCounts.set({})
+ $unreadFinishedMarkers.set({})
+ })
+
+ async function readyActions() {
+ let handle: HarnessHandle | null = null
+ render(<Harness onReady={value => (handle = value)} requestGateway={vi.fn(async () => ({}) as never)} />)
+ await waitFor(() => expect(handle).not.toBeNull())
+
+ return handle!
+ }
+
+ it('DELETEs a stamped messaging session against its owning profile', async () => {
+ mockDeleteSession.mockResolvedValue({ ok: true })
+ setMessagingSessions([
+ storedSession({ id: 'tg-winefox-1', profile: 'winefox', source: 'telegram', title: 'TG chat' })
+ ])
+
+ const handle = await readyActions()
+ await act(async () => {
+ await handle.removeSession('tg-winefox-1')
+ })
+
+ expect(mockDeleteSession).toHaveBeenCalledWith('tg-winefox-1', 'winefox')
+ expect($messagingSessions.get()).toEqual([])
+ expect($sessions.get()).toEqual([])
+ })
+
+ it('resolves a profile-less messaging DELETE before drop, without leaking into recents', async () => {
+ $sessionSeenCounts.set({
+ winefox: { 'tg-1': 4 },
+ default: { 'desk-keep': 2 }
+ })
+ $unreadFinishedMarkers.set({
+ winefox: ['tg-1'],
+ default: ['desk-keep']
+ })
+ setMessagingSessions([storedSession({ id: 'tg-1', source: 'telegram', title: 'QQ/TG' })])
+ mockGetSession.mockImplementation(async (id: string, scope?: ProfileScope) => {
+ expect($messagingSessions.get().some(session => session.id === 'tg-1')).toBe(true)
+ const profile = scope && typeof scope === 'object' ? scope.profile : scope
+
+ if (!profile) {
+ throw new Error('404: Session not found')
+ }
+
+ if (profile === 'winefox') {
+ return storedSession({ id, profile: 'winefox', source: 'telegram' })
+ }
+
+ throw new Error('404: Session not found')
+ })
+ mockDeleteSession.mockResolvedValue({ ok: true })
+
+ const handle = await readyActions()
+ await act(async () => {
+ await handle.removeSession('tg-1')
+ })
+
+ expect(mockGetSession).toHaveBeenCalled()
+ expect(mockDeleteSession).toHaveBeenCalledWith('tg-1', 'winefox')
+ expect($messagingSessions.get()).toEqual([])
+ expect($sessions.get()).toEqual([])
+ expect($sessionSeenCounts.get().winefox?.['tg-1']).toBeUndefined()
+ expect($sessionSeenCounts.get().default?.['desk-keep']).toBe(2)
+ expect($unreadFinishedMarkers.get().winefox ?? []).not.toContain('tg-1')
+ expect($unreadFinishedMarkers.get().default).toEqual(['desk-keep'])
+ })
+
+ it('restores a failed DELETE to the messaging slice, not recents', async () => {
+ const row = storedSession({ id: 'tg-roll', profile: 'winefox', source: 'telegram' })
+ setMessagingSessions([row])
+ $pinnedSessionIds.set(['tg-roll'])
+ mockDeleteSession.mockRejectedValue(new Error('backend down'))
+
+ const handle = await readyActions()
+ await act(async () => {
+ await handle.removeSession('tg-roll')
+ })
+
+ expect($messagingSessions.get().map(session => session.id)).toEqual(['tg-roll'])
+ expect($sessions.get()).toEqual([])
+ expect($pinnedSessionIds.get()).toEqual(['tg-roll'])
+ expect($removedSessionIds.get().has('tg-roll')).toBe(false)
+ expect($sessionMutationsInFlight.get().has('tg-roll')).toBe(false)
+ })
+
+ it('archives a messaging row against its owning profile', async () => {
+ mockSetSessionArchived.mockResolvedValue({ ok: true })
+ setMessagingSessions([storedSession({ id: 'tg-arch', profile: 'winefox', source: 'telegram' })])
+
+ const handle = await readyActions()
+ await act(async () => {
+ await handle.archiveSession('tg-arch')
+ })
+
+ expect(mockSetSessionArchived).toHaveBeenCalledWith('tg-arch', true, 'winefox')
+ expect($messagingSessions.get()).toEqual([])
+ })
+
+ it('restores a failed archive to the messaging slice', async () => {
+ setMessagingSessions([storedSession({ id: 'tg-arch-fail', profile: 'winefox', source: 'telegram' })])
+ mockSetSessionArchived.mockRejectedValue(new Error('archive failed'))
+
+ const handle = await readyActions()
+ await act(async () => {
+ await handle.archiveSession('tg-arch-fail')
+ })
+
+ expect($messagingSessions.get().map(session => session.id)).toEqual(['tg-arch-fail'])
+ expect($sessions.get()).toEqual([])
+ })
+
+ it('still DELETEs a desktop-native session with its listed profile', async () => {
+ mockDeleteSession.mockResolvedValue({ ok: true })
+ setSessions([storedSession({ id: 'desk-1', profile: 'default', source: 'desktop' })])
+
+ const handle = await readyActions()
+ await act(async () => {
+ await handle.removeSession('desk-1')
+ })
+
+ expect(mockDeleteSession).toHaveBeenCalledWith('desk-1', 'default')
+ expect($sessions.get()).toEqual([])
+ })
+
+ it('does not restore a failed cron DELETE into recents', async () => {
+ setCronSessions([storedSession({ id: 'cron-1', profile: 'winefox', source: 'cron' })])
+ mockDeleteSession.mockRejectedValue(new Error('cron delete failed'))
+
+ const handle = await readyActions()
+ await act(async () => {
+ await handle.removeSession('cron-1')
+ })
+
+ expect($cronSessions.get().map(session => session.id)).toEqual(['cron-1'])
+ expect($sessions.get()).toEqual([])
+ expect($messagingSessions.get()).toEqual([])
+ })
+})
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 5f5dd0d85bd..cd6a60a2894 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
@@ -78,7 +78,6 @@ import {
setResumeExhaustedSessionId,
setResumeFailedSessionId,
setSelectedStoredSessionId,
- setSessions,
setSessionStartedAt,
setTurnStartedAt,
setWorkspaceCwdOwner,
@@ -119,6 +118,8 @@ import {
type BranchMessage,
chatMessageArraysEquivalent,
dedupeInflightUserAgainstTranscript,
+ dropListedSession,
+ findListedSession,
goneSessionVerdict,
isSessionGoneError,
overlayConcurrentMessageChanges,
@@ -129,6 +130,7 @@ import {
resolveResumedBusy,
resolveSessionProfile,
resolveStoredSession,
+ restoreListedSession,
selectBranchMessages,
sessionMatchesStoredId,
sessionShouldHaveTranscript,
@@ -1938,14 +1940,20 @@ export function useSessionActions({
async (storedSessionId: string) => {
clearNotifications()
- // The row may live in the main list OR the archived view's own store
- // (archived rows are excluded from $sessions by design). Resolve from
- // both so deleting from the Archived filter evicts the row instead of
- // leaving a ghost that resumes into a dead id (infinite spinner).
- const removedFromMain = $sessions.get().find(session => sessionMatchesStoredId(session, storedSessionId))
+ // The row may live in the main list, the messaging/cron sidebar slices,
+ // OR the archived view's own store (archived rows are excluded from
+ // $sessions by design). Resolve from all of them so deleting a
+ // messaging/cron row (or from the Archived filter) evicts the row
+ // instead of leaving a ghost that resumes into a dead id.
+ const listed = findListedSession(storedSessionId)
const removed =
- removedFromMain ?? $archivedSessions.get().find(session => sessionMatchesStoredId(session, storedSessionId))
+ listed?.session ?? $archivedSessions.get().find(session => sessionMatchesStoredId(session, storedSessionId))
+
+ // Messaging/cron rows frequently arrive without an inline profile; fall
+ // back to the stored-session ownership lookup so their DELETE routes to
+ // the owning profile instead of the ambient one.
+ const profile = removed?.profile?.trim() || (await resolveSessionProfile(storedSessionId))
const wasSelected = selectedStoredSessionId === storedSessionId
const closingRuntimeId = wasSelected ? activeSessionId : null
@@ -1957,7 +1965,7 @@ export function useSessionActions({
connectionId: removed.connection_id,
profile: removed.profile || 'default'
}
- : removed?.profile
+ : profile
const previousArchived = $archivedSessions.get()
// Pins are keyed on the durable lineage-root id; the stored id may be the
@@ -1965,7 +1973,7 @@ export function useSessionActions({
const removedPinId = removed ? sessionPinId(removed) : storedSessionId
const removedIds = [storedSessionId, removed?.id, removed?._lineage_root_id]
- setSessions(prev => prev.filter(session => !sessionMatchesStoredId(session, storedSessionId)))
+ dropListedSession(storedSessionId)
$archivedSessions.set(previousArchived.filter(session => !sessionMatchesStoredId(session, storedSessionId)))
// Evict from the project tree's optimistic layer too (the backend snapshot
// still lists it until its next refresh), so grouped + flat views drop the
@@ -1993,7 +2001,7 @@ export function useSessionActions({
dropTranscriptTail(storedSessionId)
// Only after the RPC lands — the optimistic eviction above can roll
// back, and a rolled-back row must keep its watermark/marker.
- forgetSessionUnread(removedIds, removed?.profile)
+ forgetSessionUnread(removedIds, profile)
clearQueuedPrompts(storedSessionId)
if (closingRuntimeId) {
@@ -2012,8 +2020,8 @@ export function useSessionActions({
dropSessionState(tiledRuntimeId)
}
} catch (err) {
- if (removedFromMain) {
- setSessions(prev => [removedFromMain, ...prev])
+ if (listed?.session) {
+ restoreListedSession(listed.session, listed.slice)
}
// Restore the archived-view row too (no-op when it wasn't archived).
@@ -2026,7 +2034,7 @@ export function useSessionActions({
setFreshDraftReady(false)
setSelectedStoredSessionId(storedSessionId)
selectedStoredSessionIdRef.current = storedSessionId
- const stored = $sessions.get().find(session => sessionMatchesStoredId(session, storedSessionId))
+ const stored = findListedSession(storedSessionId)?.session
if (stored) {
applyStoredUsage(stored)
@@ -2067,7 +2075,9 @@ export function useSessionActions({
async (storedSessionId: string) => {
clearNotifications()
- const archived = $sessions.get().find(session => sessionMatchesStoredId(session, storedSessionId))
+ const listed = findListedSession(storedSessionId)
+ const archived = listed?.session
+ const profile = archived?.profile?.trim() || (await resolveSessionProfile(storedSessionId))
const wasSelected = selectedStoredSessionId === storedSessionId
const previousPinned = $pinnedSessionIds.get()
// Pins are keyed on the durable lineage-root id; the stored id may be the
@@ -2075,8 +2085,8 @@ export function useSessionActions({
const archivedPinId = archived ? sessionPinId(archived) : storedSessionId
const archivedIds = [storedSessionId, archived?.id, archived?._lineage_root_id]
- // Soft-hide: drop from the sidebar immediately, keep the data.
- setSessions(prev => prev.filter(session => !sessionMatchesStoredId(session, storedSessionId)))
+ // Soft-hide: drop from every sidebar slice immediately, keep the data.
+ dropListedSession(storedSessionId)
tombstoneSessions(archivedIds)
beginSessionMutation(archivedIds)
$pinnedSessionIds.set(previousPinned.filter(id => id !== storedSessionId && id !== archivedPinId))
@@ -2086,10 +2096,10 @@ export function useSessionActions({
}
try {
- await setSessionArchived(storedSessionId, true, archived?.profile)
+ await setSessionArchived(storedSessionId, true, profile)
// Archived rows never reach the sidebar, so their persisted unread can
// only rot. Dropped after the RPC so a failed archive keeps it.
- forgetSessionUnread(archivedIds, archived?.profile)
+ forgetSessionUnread(archivedIds, profile)
// An archived session is hidden from the sidebar; its tile must go too.
const tiledRuntimeId = runtimeIdByStoredSessionIdRef.current.get(storedSessionId)
closeSessionTile(storedSessionId)
@@ -2103,7 +2113,7 @@ export function useSessionActions({
notify({ durationMs: 2_000, kind: 'success', message: copy.archived })
} catch (err) {
if (archived) {
- setSessions(prev => [archived, ...prev.filter(session => !sessionMatchesStoredId(session, storedSessionId))])
+ restoreListedSession(archived, listed?.slice)
}
untombstoneSessions(archivedIds)
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 07e5a2dbab5..368661f07f7 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
@@ -4,6 +4,7 @@ import { assistantTextPart, type ChatMessage, chatMessageText, textPart } from '
import { normalizePersonalityValue } from '@/lib/chat-runtime'
import { embeddedImageUrls, textWithoutEmbeddedImages } from '@/lib/embedded-images'
import { parseErrorSurface } from '@/lib/error-surface'
+import { isMessagingSource, normalizeSessionSource } from '@/lib/session-source'
import { reconcileApprovalModeForProfile } from '@/store/approval-mode'
import { requestDesktopOnboardingForCredentialWarning } from '@/store/onboarding'
import { $activeGatewayProfile, $profiles, normalizeProfileKey } from '@/store/profile'
@@ -15,6 +16,7 @@ import {
commitWorkspaceCwdForSelectedSession,
releaseWorkspaceCwdOwner,
sessionMatchesStoredId,
+ setCronSessions,
setCurrentBranch,
setCurrentCwdTransient,
setCurrentFastMode,
@@ -24,6 +26,7 @@ import {
setCurrentReasoningEffort,
setCurrentServiceTier,
setCurrentUsage,
+ setMessagingSessions,
setSessions,
setWorkspaceCwdOwner,
setYoloActive
@@ -1289,6 +1292,70 @@ export function sessionShouldHaveTranscript(session: SessionInfo | undefined): b
return (session?.message_count ?? 0) > 0
}
+export type ListedSessionSlice = 'cron' | 'messaging' | 'sessions'
+
+export function findListedSession(
+ storedSessionId: string
+): { session: SessionInfo; slice: ListedSessionSlice } | undefined {
+ const match = (session: SessionInfo) => sessionMatchesStoredId(session, storedSessionId)
+ const fromSessions = $sessions.get().find(match)
+
+ if (fromSessions) {
+ return { session: fromSessions, slice: 'sessions' }
+ }
+
+ const fromMessaging = $messagingSessions.get().find(match)
+
+ if (fromMessaging) {
+ return { session: fromMessaging, slice: 'messaging' }
+ }
+
+ const fromCron = $cronSessions.get().find(match)
+
+ if (fromCron) {
+ return { session: fromCron, slice: 'cron' }
+ }
+
+ return undefined
+}
+
+export function dropListedSession(storedSessionId: string): void {
+ const keep = (session: SessionInfo) => !sessionMatchesStoredId(session, storedSessionId)
+
+ setSessions(prev => prev.filter(keep))
+ setMessagingSessions(prev => prev.filter(keep))
+ setCronSessions(prev => prev.filter(keep))
+}
+
+export function restoreListedSession(session: SessionInfo, slice?: ListedSessionSlice): void {
+ const target: ListedSessionSlice =
+ slice ??
+ (isMessagingSource(session.source)
+ ? 'messaging'
+ : normalizeSessionSource(session.source) === 'cron'
+ ? 'cron'
+ : 'sessions')
+
+ const prepend = (prev: SessionInfo[]) => [
+ session,
+ ...prev.filter(existing => !sessionMatchesStoredId(existing, session.id))
+ ]
+
+ if (target === 'messaging') {
+ setMessagingSessions(prepend)
+
+ return
+ }
+
+ if (target === 'cron') {
+ setCronSessions(prepend)
+
+ return
+ }
+
+ setSessions(prepend)
+}
+
function upsertResolvedSession(session: SessionInfo, storedSessionId: string) {
const lineage = session._lineage_root_id ?? session.id