The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): keep archived sessions archived and renames consistent across session lists
Brooklyn Nicholson8859acea58f6
diff --git a/apps/desktop/src/app/chat/sidebar/session-actions-menu.tsx b/apps/desktop/src/app/chat/sidebar/session-actions-menu.tsxindex a28db645e0b..ee4a221e586 100644--- a/apps/desktop/src/app/chat/sidebar/session-actions-menu.tsx+++ b/apps/desktop/src/app/chat/sidebar/session-actions-menu.tsx@@ -33,17 +33,23 @@ import { PROFILE_SWATCHES } from '@/lib/profile-color'import { exportSession } from '@/lib/session-export'import { activeGateway } from '@/store/gateway'import { notify, notifyError } from '@/store/notifications'-import { $projectTree, moveSessionToProject, projectIdForCwd, projectRootCwd } from '@/store/projects'+import {+ $projectTree,+ applyRenamedSessionTitle,+ moveSessionToProject,+ projectIdForCwd,+ projectRootCwd+} from '@/store/projects'import {$activeSessionId,$connection,$selectedStoredSessionId,$sessions,$unreadFinishedSessionIds,+ applySessionTitle,markSessionRead,sessionMatchesStoredId,- sessionPinId,- setSessions+ sessionPinId} from '@/store/session'import { $sessionColorOverrides, setSessionColorOverride } from '@/store/session-color'import { $sessionTiles, closeAllOpenSessionTiles } from '@/store/session-states'@@ -699,7 +705,12 @@ function RenameSessionDialog({ open, onOpenChange, sessionId, currentTitle, proftry {const result = await renameSessionPreferringRpc(sessionId, next, profile)const finalTitle = result.title || next || ''- setSessions(prev => prev.map(s => (s.id === sessionId ? { ...s, title: finalTitle || null } : s)))+ // One write, every list: patch the main store AND the project surfaces.+ // Bare-id patching only the recents slice left project-scoped rows+ // (overview previews, entered-project lanes) on the stale title until a+ // profile switch forced a refetch (#123337).+ applySessionTitle(sessionId, finalTitle || null)+ applyRenamedSessionTitle(sessionId, finalTitle || null)notify({ durationMs: 2_000, kind: 'success', message: r.renamed })onOpenChange(false)} catch (err) {diff --git a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/session-info.ts b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/session-info.tsindex 65208aa2cd9..0113fe47901 100644--- a/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/session-info.ts+++ b/apps/desktop/src/app/session/hooks/use-message-stream/gateway-event/session-info.ts@@ -13,6 +13,7 @@ import {$currentProvider,$selectedStoredSessionId,$sessions,+ applySessionTitle,sessionMatchesStoredId,setActiveSessionId,setCurrentBranch,@@ -23,7 +24,6 @@ import {setCurrentReasoningEffortWire,setCurrentServiceTier,setCurrentUsage,- setSessions,setTerminalBackend,setWorkspaceCwdOwner,setYoloActive@@ -497,7 +497,10 @@ export function handleSessionInfoEvent(ctx: GatewayEventContext): boolean {const nextTitle = typeof payload?.title === 'string' ? payload.title.trim() : ''if (storedId && nextTitle) {- setSessions(prev => prev.map(s => (sessionMatchesStoredId(s, storedId) ? { ...s, title: nextTitle } : s)))+ // Lineage-aware across every slice — the same conversation can render+ // from any of its ids (#123337); bare recents patching left project+ // rows stale.+ applySessionTitle(storedId, nextTitle)}return truediff --git a/apps/desktop/src/app/session/hooks/use-prompt-actions/slash.ts b/apps/desktop/src/app/session/hooks/use-prompt-actions/slash.tsindex e8ad47e3a74..2bb040f5e11 100644--- a/apps/desktop/src/app/session/hooks/use-prompt-actions/slash.ts+++ b/apps/desktop/src/app/session/hooks/use-prompt-actions/slash.ts@@ -37,6 +37,7 @@ import {$connection,$sessions,$yoloActive,+ applySessionTitle,setActiveSessionId,setCurrentUsage,setModelPickerOpen,@@ -1066,7 +1067,10 @@ export function useSlashCommand(deps: SlashCommandDeps) {const finalTitle = (result?.title || arg).trim()const queued = result?.pending === true- setSessions(prev => prev.map(s => (s.id === sessionId ? { ...s, title: finalTitle || null } : s)))+ // Patch every sidebar slice (lineage-aware), then refresh the+ // project surfaces — a bare-id recents patch left project rows+ // stale until a profile switch (#123337).+ applySessionTitle(sessionId, finalTitle || null)await refreshSessions().catch(() => undefined)renderSlashOutput(finalTitlediff --git a/apps/desktop/src/app/session/hooks/use-session-list-actions.test.tsx b/apps/desktop/src/app/session/hooks/use-session-list-actions.test.tsxindex bdcf288ee26..ed81b6bdf34 100644--- a/apps/desktop/src/app/session/hooks/use-session-list-actions.test.tsx+++ b/apps/desktop/src/app/session/hooks/use-session-list-actions.test.tsx@@ -340,6 +340,98 @@ describe('refreshSessions identity + loading hygiene', () => {expect($sessions.get().map(s => s.id)).toEqual(['mine'])})+ it('drops a doomed row whose tombstone was pruned while the page was in flight (#123685)', async () => {+ // The observed Windows resurrection: a sidebar refresh STARTS (reads the+ // page pre-archive-commit), the user archives, the RPC lands, the+ // projects.tree refresh prunes the tombstone (its snapshot is right —+ // the id is gone), and THEN the stale page arrives. Membership is empty+ // by then, so dropTombstoned has nothing to say; only the removal+ // generation delta still names the row.+ const pending = deferred<SidebarSessionsResponse>()+ listSidebarSessions.mockReturnValue(pending.promise)++ const { result } = renderHook(() => useSessionListActions({ profileScope: 'default' }))++ const refresh = result.current.refreshSessions()++ // The archive lands mid-flight: tombstone armed, RPC resolves, the tree+ // prune clears membership (the real prune writes the atom directly,+ // which is exactly why the generation guard is needed).+ const removals = await import('@/store/session-removal')+ removals.tombstoneSessions(['doomed'])+ removed.ids = new Set()++ // The keep set still names the doomed row (settle grace), so the+ // survivor path would carry it back if the guard were absent.+ setSessions([row('doomed')])+ settled.ids = ['doomed']++ await act(async () => {+ pending.resolve(sidebar({ sessions: [row('doomed', { message_count: 4 }), row('mine')] }))+ await refresh+ })++ expect($sessions.get().map(s => s.id)).toEqual(['mine'])++ removals.untombstoneSessions(['doomed'])+ })++ it('re-admits a row whose archive rolled back mid-flight (release edge)', async () => {+ // A failed archive untombstones immediately; a page that raced the+ // rollback must still list the row — the guard only vetoes rows whose+ // removal lifecycle moved TOWARD removal.+ const pending = deferred<SidebarSessionsResponse>()+ listSidebarSessions.mockReturnValue(pending.promise)++ const { result } = renderHook(() => useSessionListActions({ profileScope: 'default' }))++ const refresh = result.current.refreshSessions()++ const removals = await import('@/store/session-removal')+ removals.tombstoneSessions(['rollback'])+ removals.untombstoneSessions(['rollback'])+ removed.ids = new Set()++ await act(async () => {+ pending.resolve(sidebar({ sessions: [row('rollback')] }))+ await refresh+ })++ expect($sessions.get().map(s => s.id)).toEqual(['rollback'])+ })++ it('matches a pruned-tombstone row by any lineage segment, and filters the cron slice too (#123685)', async () => {+ // The tombstone was armed on the ROOT id while the page carries the row+ // under a middle lineage segment (post-compression): the match must go+ // through _lineage_ids, not just tip + root. Same race shape as above —+ // the prune has already cleared membership.+ const pending = deferred<SidebarSessionsResponse>()+ listSidebarSessions.mockReturnValue(pending.promise)++ const { result } = renderHook(() => useSessionListActions({ profileScope: 'default' }))++ const refresh = result.current.refreshSessions()++ const removals = await import('@/store/session-removal')+ removals.tombstoneSessions(['root-x'])+ removed.ids = new Set()++ await act(async () => {+ pending.resolve(+ sidebar(+ { sessions: [row('segment', { _lineage_ids: ['root-x', 'segment', 'tip-x'] } as Partial<SessionInfo>)] },+ [row('cron-doomed', { source: 'cron', _lineage_root_id: 'root-x' } as Partial<SessionInfo>)]+ )+ )+ await refresh+ })++ expect($sessions.get().map(s => s.id)).toEqual([])+ expect($cronSessions.get().map(s => s.id)).toEqual([])++ removals.untombstoneSessions(['root-x'])+ })+it('keeps idle recents when the sidebar returns an empty page plus profile errors', async () => {// Backend contract on disk I/O / lock: HTTP 200, recents=[], errors=[{profile}].// mergeSessionPage only keeps working/pinned/selected, so Yesterday/This-weekdiff --git a/apps/desktop/src/app/session/hooks/use-session-list-actions.ts b/apps/desktop/src/app/session/hooks/use-session-list-actions.tsindex 43fc59e626f..76e49d2799d 100644--- a/apps/desktop/src/app/session/hooks/use-session-list-actions.ts+++ b/apps/desktop/src/app/session/hooks/use-session-list-actions.ts@@ -42,7 +42,13 @@ import {setSessionsLoading,stampMessagingRowsWithListServer} from '@/store/session'-import { $removedSessionIds } from '@/store/session-removal'+import {+ $removedSessionIds,+ captureSessionTombstoneGenerations,+ sessionRemovalIntersected,+ type SessionTombstoneGenerationSnapshot,+ tombstoneRowIds+} from '@/store/session-removal'import { $sessionTiles, $workingSessionIds, getRecentlySettledSessionIds } from '@/store/session-states'import { refreshCronJobs as refreshCronJobsStore } from '../../cron/cron-actions'@@ -78,13 +84,39 @@ const MESSAGING_EXCLUDED_SOURCES = ['cron', ...LOCAL_SESSION_SOURCE_IDS]// Honoring the optimistic tombstone at every ingestion point keeps the removal// stable; the tombstone self-clears once projects.tree confirms the delete,// and a failed delete untombstones immediately, so nothing is filtered on the-// non-destructive paths.+// non-destructive paths. A tombstone matches the row on ANY id the+// conversation has answered to (tip, root, and every intermediate lineage+// segment) — armed on one name, it must still catch the same conversation+// returning under another (#123685).function dropTombstoned(sessions: SessionInfo[]): SessionInfo[] {const tombstones = $removedSessionIds.get()- return tombstones.size- ? sessions.filter(s => !tombstones.has(s.id) && !(s._lineage_root_id && tombstones.has(s._lineage_root_id)))- : sessions+ if (!tombstones.size) {+ return sessions+ }++ const tombstoned = (session: SessionInfo): boolean => tombstoneRowIds(session).some(id => tombstones.has(id))++ const kept = sessions.filter(session => !tombstoned(session))++ return kept.length === sessions.length ? sessions : kept+}++// A fetch whose page was READ before an archive/delete committed can land+// after the projects.tree prune has already dropped the tombstone (the tree is+// right to prune — the id is gone from its snapshot), so `dropTombstoned` has+// nothing left to honor and the stale row resurrected through the keep set+// (#123685). The tombstone's generation counter survives the prune: capture it+// at fetch start, and reject any row whose removal lifecycle moved toward+// removal underneath the request. A release edge (failed RPC, unarchive)+// re-admits the row as before.+function dropRemovalRaced(sessions: SessionInfo[], snapshot: SessionTombstoneGenerationSnapshot): SessionInfo[] {+ const raced = (session: SessionInfo): boolean =>+ tombstoneRowIds(session).some(id => sessionRemovalIntersected(snapshot, id))++ const kept = sessions.filter(session => !raced(session))++ return kept.length === sessions.length ? sessions : kept}function publishMessagingRows(rows: SessionInfo[], scopeProfile: string): SessionInfo[] {@@ -159,6 +191,9 @@ export function useSessionListActions({ profileScope }: UseSessionListActionsArgconst requestId = refreshMessagingSessionsRequestRef.current + 1refreshMessagingSessionsRequestRef.current = requestId+ // Same removal-race guard as the recents refresh (#123685).+ const removalSnapshot = captureSessionTombstoneGenerations()+const owns = () =>refreshMessagingSessionsRequestRef.current === requestId &&sidebarProfileForScope(profileScopeRef.current) === sessionProfile@@ -186,7 +221,7 @@ export function useSessionListActions({ profileScope }: UseSessionListActionsArg// Drop any non-messaging source the broad exclude didn't catch (custom// sources) — those stay in local recents, not a platform section.const rows = publishMessagingRows(- dropTombstoned(result.sessions.filter(s => isMessagingSource(s.source))),+ dropRemovalRaced(dropTombstoned(result.sessions.filter(s => isMessagingSource(s.source))), removalSnapshot),sessionProfile)@@ -218,6 +253,10 @@ export function useSessionListActions({ profileScope }: UseSessionListActionsArgconst inPlatform = (s: SessionInfo) => normalizeSessionSource(s.source) === platform && inProfile(s)const loaded = $messagingSessions.get().filter(inPlatform).length+ // Same removal-race guard as the recents refresh: this page was read+ // before an archive could commit and can outlive the tombstone prune.+ const removalSnapshot = captureSessionTombstoneGenerations()+const owns = () =>loadMoreMessagingRequestRef.current[requestKey] === requestId &&sidebarProfileForScope(profileScopeRef.current) === sessionProfile@@ -246,7 +285,10 @@ export function useSessionListActions({ profileScope }: UseSessionListActionsArgreturn}- const incoming = publishMessagingRows(dropTombstoned(result.sessions.filter(inPlatform)), sessionProfile)+ const incoming = publishMessagingRows(+ dropRemovalRaced(dropTombstoned(result.sessions.filter(inPlatform)), removalSnapshot),+ sessionProfile+ )setMessagingSessions(prev => [...prev.filter(s => !inPlatform(s)),@@ -306,6 +348,11 @@ export function useSessionListActions({ profileScope }: UseSessionListActionsArgrefreshSessionsRequestRef.current === requestId &&sidebarProfileForScope(profileScopeRef.current) === sessionProfile+ // Snapshot the removal lifecycle BEFORE the first read: a page read+ // pre-archive-commit can land post-prune, and only the generation+ // delta (not tombstone membership) still names the doomed row then.+ const removalSnapshot = captureSessionTombstoneGenerations()+try {const limit = $sessionsLimit.get()@@ -377,7 +424,10 @@ export function useSessionListActions({ profileScope }: UseSessionListActionsArgcarryForwardFailedProfileSessions(prev, recents.sessions ?? [], recents.errors ?? result.errors))- const next = mergeSessionPage(prev, incoming, sessionsToKeep())+ // Filter AFTER the merge: the guard must also catch survivors+ // (a stale previous slice can still hold the doomed row through+ // the keep set once the tombstone prune has cleared membership).+ const next = dropRemovalRaced(mergeSessionPage(prev, incoming, sessionsToKeep()), removalSnapshot)return sameCronSignature(prev, next) ? prev : next})@@ -409,11 +459,13 @@ export function useSessionListActions({ profileScope }: UseSessionListActionsArg})// Cron section: latest N cron sessions (kept so a pinned cron run still- // resolves via sessionByAnyId), signature-gated like above.+ // resolves via sessionByAnyId), signature-gated like above. The+ // optimistic tombstone applies here too — the batched page can carry+ // a cron run whose delete/archive RPC is still in flight (#50928).setCronSessions(prev => {const incoming = carryForwardFailedProfileSessions(prev,- result.cron.sessions ?? [],+ dropRemovalRaced(dropTombstoned(result.cron.sessions ?? []), removalSnapshot),result.cron.errors ?? result.errors)@@ -426,12 +478,15 @@ export function useSessionListActions({ profileScope }: UseSessionListActionsArgconst messagingErrors = result.messaging.errors ?? result.errorsconst messagingRows = publishMessagingRows(- dropTombstoned(- carryForwardFailedProfileSessions(- $messagingSessions.get(),- (result.messaging.sessions ?? []).filter(s => isMessagingSource(s.source)),- messagingErrors- )+ dropRemovalRaced(+ dropTombstoned(+ carryForwardFailedProfileSessions(+ $messagingSessions.get(),+ (result.messaging.sessions ?? []).filter(s => isMessagingSource(s.source)),+ messagingErrors+ )+ ),+ removalSnapshot),sessionProfile)diff --git a/apps/desktop/src/store/projects.test.ts b/apps/desktop/src/store/projects.test.tsindex 951c2157ef5..b7bff129b02 100644--- a/apps/desktop/src/store/projects.test.ts+++ b/apps/desktop/src/store/projects.test.ts@@ -1,3 +1,4 @@+import { waitFor } from '@testing-library/react'import { atom } from 'nanostores'import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'@@ -14,6 +15,7 @@ import {$projectsRpcAvailable,$projectTree,addProjectFolder,+ applyRenamedSessionTitle,createProject,deleteProject,enterProject,@@ -896,6 +898,79 @@ describe('project tree profile isolation', () => {$projectTree.set([])})+ it('mirrors a renamed title into cached tree rows and refreshes the tree (#123337)', async () => {+ // The rename wrote the backend row; the cached snapshot (overview+ // previews + hydrated lanes) kept the old title until an unrelated+ // refetch. applyRenamedSessionTitle patches every cached copy by lineage+ // id and re-pulls the authoritative tree.+ const sess = (id: string, title: string) => ({ id, title })++ const treeProject = {+ id: 'p_1',+ label: 'One',+ path: '/one',+ repos: [+ {+ id: '/one',+ label: 'one',+ path: '/one',+ sessionCount: 2,+ groups: [+ {+ id: '/one::branch::main',+ label: 'main',+ path: '/one',+ sessions: [+ sess('tip-row', 'Old title'),+ sess('other-row', 'Untouched'),+ { ...sess('preview-only', 'Old title'), _lineage_root_id: 'root-x' }+ ]+ }+ ]+ }+ ],+ sessionCount: 2,+ previewSessions: [sess('tip-row', 'Old title')]+ }++ $projectTree.set([treeProject as never])++ const request = vi.fn().mockResolvedValue({ active_id: null, projects: [], scoped_session_ids: [] })+ activeGateway.mockReturnValue({ connectionState: 'open', request } as never)+ gatewayAtom.set({ connectionState: 'open', request } as never)++ applyRenamedSessionTitle('tip-row', 'New title')++ // Synchronous patch: every cached copy carries the new title.+ const project = $projectTree.get()[0]+ const lane = project.repos[0].groups[0]+ expect(lane.sessions.find(s => s.id === 'tip-row')?.title).toBe('New title')+ expect(lane.sessions.find(s => s.id === 'other-row')?.title).toBe('Untouched')+ expect(lane.sessions.find(s => s.id === 'preview-only')?.title).toBe('Old title')+ expect(project.previewSessions?.[0].title).toBe('New title')++ // A lineage-root rename reaches a row the snapshot holds under its tip.+ applyRenamedSessionTitle('root-x', 'Root renamed')+ expect($projectTree.get()[0].repos[0].groups[0].sessions.find(s => s.id === 'preview-only')?.title).toBe(+ 'Root renamed'+ )++ // And the authoritative tree is re-pulled.+ await waitFor(() => expect(request).toHaveBeenCalledWith('projects.tree', expect.anything()))+ })++ it('keeps the tree reference when no cached row matches the rename', () => {+ const before = [{ id: 'p_2', label: 'Two', path: '/two', repos: [], sessionCount: 0 }]+ $projectTree.set(before as never)++ const request = vi.fn()+ activeGateway.mockReturnValue({ connectionState: 'open', request } as never)++ applyRenamedSessionTitle('absent-row', 'Whatever')++ expect($projectTree.get()).toBe(before)+ })+it('retries a dropped projects.tree request once on the active gateway', async () => {const request = vi.fn()diff --git a/apps/desktop/src/store/projects.ts b/apps/desktop/src/store/projects.tsindex 0ed1cd0d16c..013c7f3093e 100644--- a/apps/desktop/src/store/projects.ts+++ b/apps/desktop/src/store/projects.ts@@ -3,13 +3,14 @@ import { atom, computed } from 'nanostores'import type { NewSessionPlacement } from '@/app/chat/new-session-drag'import {+ excludeProjectSessions,liveSessionProjectId,NO_PROJECT_ID,projectOwnerBySessionId,type SidebarProjectTree} from '@/app/chat/sidebar/projects/workspace-groups'import type { HermesGitBaseBranch, HermesGitBranch } from '@/global'-import { getHermesConfig, hermesApi, type HermesGateway } from '@/hermes'+import { getHermesConfig, hermesApi, type HermesGateway, type SessionInfo } from '@/hermes'import { translateNow } from '@/i18n'import { desktopDefaultCwd, isDesktopFsRemoteMode, selectDesktopPaths, writeDesktopFileText } from '@/lib/desktop-fs'import { desktopGit } from '@/lib/desktop-git'@@ -36,7 +37,14 @@ import {setSessions,workspaceCwdForNewSession} from '@/store/session'-import { $removedSessionIds, $sessionMutationsInFlight } from '@/store/session-removal'+import {+ $removedSessionIds,+ $sessionMutationsInFlight,+ captureSessionTombstoneGenerations,+ sessionRemovalIntersected,+ type SessionTombstoneGenerationSnapshot,+ tombstoneRowIds+} from '@/store/session-removal'import type { ProjectInfo, ProjectsPayload } from '@/types/hermes'// First-class, per-profile Projects (named, multi-folder workspaces). State is@@ -532,6 +540,28 @@ async function refreshProjectTreeAcrossProfiles(): Promise<void> {// membership match exactly.let projectSessionsRefreshGeneration = 0+// A drill-in page read before an archive/delete committed can land after the+// projects.tree prune has dropped the tombstone, resurrecting the row in the+// entered project's lanes (#123685, same race as the sidebar refresh). The+// tombstone's generation snapshot survives the prune, so the same guard+// applies: reject rows whose removal lifecycle moved under this request.+// `excludeProjectSessions` keeps the project ref when nothing matches, so the+// no-removal common case stays identity-stable for the drill-in's memo.+function dropRemovedProjectSessions(+ project: SidebarProjectTree | null,+ removalSnapshot: SessionTombstoneGenerationSnapshot+): SidebarProjectTree | null {+ if (!project) {+ return null+ }++ const tombstones = $removedSessionIds.get()++ return excludeProjectSessions(project, session =>+ tombstoneRowIds(session).some(id => tombstones.has(id) || sessionRemovalIntersected(removalSnapshot, id))+ )+}+// A drill-in only wants the LATEST request (an older one resolving late would// paint the wrong project), so those are `supersedable` and resolve null when// overtaken. A per-row "Show all" expansion is not: two rows expanding at once,@@ -547,6 +577,9 @@ export async function fetchProjectSessions(return null}+ // Snapshot before the read: the guard must cover the whole request window.+ const removalSnapshot = captureSessionTombstoneGenerations()+let context: ActiveProjectsContext | undefinedtry {@@ -562,7 +595,7 @@ export async function fetchProjectSessions(return null}- return res.project ?? null+ return dropRemovedProjectSessions(res.project ?? null, removalSnapshot)} catch (error) {if ((generation !== null && generation !== projectSessionsRefreshGeneration) ||@@ -576,6 +609,87 @@ export async function fetchProjectSessions(}}+// Mirror a successful rename into the cached project surfaces, the same+// optimistic-layer contract as moveSessionToProject: the backend row IS+// renamed, but the tree snapshot (overview previews + counts) still carries+// the old title until its next refresh — and the sidebar overlays live rows+// only where a live twin exists, so a snapshot-only row in the entered+// project kept the stale title until a profile switch (#123337). Patch every+// cached copy by lineage id, then re-pull the authoritative tree.+export function applyRenamedSessionTitle(sessionId: string, title: string | null): void {+ const next = title?.trim() || null++ const tree = $projectTree.get()+ let changed = false++ const renamedTree = tree.map(project => {+ const renamed = renameProjectSessions(project, sessionId, next)++ changed ||= renamed !== project++ return renamed+ })++ if (changed) {+ $projectTree.set(renamedTree)+ }++ void refreshProjectTree()+}++/** Patch every cached copy of the renamed conversation inside one project+ * node (lane rows + overview previews), keeping the node's reference when+ * nothing matched — the tree keeps unchanged nodes by reference so the+ * drill-in doesn't refetch on a no-op (#77591). */+function renameProjectSessions(+ project: SidebarProjectTree,+ sessionId: string,+ next: string | null+): SidebarProjectTree {+ let changed = false++ const rename = (sessions: SessionInfo[]): SessionInfo[] =>+ sessions.map(session => {+ if (!sessionMatchesStoredId(session, sessionId) || session.title === next) {+ return session+ }++ changed = true++ return { ...session, title: next }+ })++ const repos = project.repos.map(repo => {+ let repoChanged = false++ const groups = repo.groups.map(group => {+ const sessions = rename(group.sessions)++ if (sessions === group.sessions) {+ return group+ }++ repoChanged = true++ return { ...group, sessions }+ })++ if (!repoChanged) {+ return repo+ }++ return { ...repo, groups, sessionCount: groups.reduce((n, g) => n + g.sessions.length, 0) }+ })++ const previewSessions = project.previewSessions ? rename(project.previewSessions) : project.previewSessions++ if (!changed) {+ return project+ }++ return { ...project, previewSessions, repos, sessionCount: repos.reduce((n, repo) => n + repo.sessionCount, 0) }+}+interface WorkspaceMovePayload {branch?: null | stringcwd?: stringdiff --git a/apps/desktop/src/store/session-removal.ts b/apps/desktop/src/store/session-removal.tsindex 3dd7cbadd7c..cb69219f2ee 100644--- a/apps/desktop/src/store/session-removal.ts+++ b/apps/desktop/src/store/session-removal.ts@@ -23,6 +23,17 @@ export const $removedSessionIds = atom<Set<string>>(new Set())export type SessionTombstoneGenerationSnapshot = ReadonlyMap<string, number>let tombstoneGenerations: SessionTombstoneGenerationSnapshot = new Map()+// Direction of the LAST lifecycle edge per id: true = tombstoned (added to the+// removal set), false = released (untombstoned). Membership alone cannot serve+// the ingestion guard: `applyProjectTreePayload` prunes a tombstone once the+// authoritative tree no longer lists the id — correct for the tree overlay,+// but it strips the guard a stale in-flight sidebar page still needs. A page+// read before the archive commit can land after the prune and resurrect the+// row (#123685). The generation counter never resets, so "the removal+// lifecycle moved toward removed after this fetch started" stays answerable+// for the renderer's whole lifetime, prune or not.+let lastRemovalEdge: ReadonlyMap<string, boolean> = new Map()+function setRemovedSessionIds(next: Set<string>): void {const current = $removedSessionIds.get()const changed = new Set<string>()@@ -52,6 +63,13 @@ function setRemovedSessionIds(next: Set<string>): void {// Publish the generation FIRST: a subscriber reacting to membership must// already observe the lifecycle change when it starts a by-id lookup.tombstoneGenerations = generations+ const edges = new Map(lastRemovalEdge)++ for (const id of changed) {+ edges.set(id, next.has(id))+ }++ lastRemovalEdge = edges$removedSessionIds.set(next)}@@ -76,6 +94,37 @@ export function tombstoneLifecycleChanged(})}+/** True when the id's removal lifecycle moved TOWARD removal since `snapshot`:+ * the user archived/deleted it (or a rolled-back removal re-armed) while this+ * request was in flight. A release edge (failed RPC, explicit unarchive) does+ * NOT count — those must re-admit the row. Answers remain valid after the+ * projects.tree prune drops the tombstone, because the generation counter and+ * last-edge direction survive membership changes (#123685). */+export function sessionRemovalIntersected(+ snapshot: SessionTombstoneGenerationSnapshot,+ id: null | string | undefined+): boolean {+ const target = id?.trim()++ if (!target) {+ return false+ }++ return snapshot.get(target) !== tombstoneGenerations.get(target) && lastRemovalEdge.get(target) === true+}++/** Every id the row answers to, for tombstone matching: the live id, the+ * lineage root, and every intermediate lineage segment. dropTombstoned used+ * to match only the tip + root, so a tombstone armed on one name let a page+ * re-inject the same conversation under another segment id (#123685). */+export function tombstoneRowIds(session: {+ _lineage_ids?: null | string[]+ _lineage_root_id?: null | string+ id: string+}): string[] {+ return [session.id, ...(session._lineage_root_id ? [session._lineage_root_id] : []), ...(session._lineage_ids ?? [])]+}+export function tombstoneSessions(ids: Array<null | string | undefined>): void {const next = new Set($removedSessionIds.get())diff --git a/apps/desktop/src/store/session.test.ts b/apps/desktop/src/store/session.test.tsindex 6af5e50f403..056481dc014 100644--- a/apps/desktop/src/store/session.test.ts+++ b/apps/desktop/src/store/session.test.ts@@ -21,15 +21,18 @@ import { makeSessionInfo } from '../test/session-info'import {$activeSessionId,$connection,+ $cronSessions,$currentCwd,$currentModel,$currentProvider,+ $messagingSessions,$selectedStoredSessionId,$sessions,$unreadFinishedSessionIds,_resetLegacyDiscardForTests,_resetSessionOwnerHintsForTests,applyConfiguredDefaultProjectDir,+ applySessionTitle,carryForwardFailedProfileSessions,commitWorkspaceCwdForSelectedSession,ensureDefaultWorkspaceCwd,@@ -55,11 +58,13 @@ import {sessionPinId,setComposerSelectionOwner,setConnection,+ setCronSessions,setCurrentCwd,setCurrentCwdTransient,setCurrentModel,setCurrentModelSource,setCurrentProvider,+ setMessagingSessions,setRememberedRoute,setRememberedSessionId,setSelectedStoredSessionId,@@ -584,6 +589,30 @@ describe('mergeSessionPage', () => {}})+ it('matches a tombstone by any intermediate lineage segment (#123685)', () => {+ // archiveSession arms the tombstone on the ids the row carried when it was+ // clicked — which, mid-compression, can be a MIDDLE segment id rather than+ // the root. The survivor filter matched only tip + root, so a doomed row+ // whose tombstone names a segment came back through the keep set.+ tombstoneSessions(['segment'])++ try {+ // The doomed conversation sits in `previous`; its tombstone names the+ // middle segment, not its root. The incoming page omits it, but the keep+ // set names the live tip — the survivor path must not carry it back.+ const previous = [+ session({ id: 'mine' }),+ session({ id: 'tip', _lineage_ids: ['root', 'segment', 'tip'], _lineage_root_id: 'root' })+ ]++ const incoming = [session({ id: 'mine' })]++ expect(mergeSessionPage(previous, incoming, ['tip']).map(s => s.id)).toEqual(['mine'])+ } finally {+ untombstoneSessions(['segment'])+ }+ })+it('keeps a pinned session that has aged off the recent page', () => {// Repro of "loses pins until you refresh": a pinned chat falls off the// most-recent page, so the server stops returning it. A hard replace would@@ -823,6 +852,40 @@ describe('mergeSessionPage', () => {})})+describe('applySessionTitle', () => {+ afterEach(() => {+ setSessions([])+ })++ it('patches the title across every sidebar slice, matching by lineage (#123337)', () => {+ // The rename flow used to patch only $sessions by bare id. A compressed+ // row matched by its root, a cron row, and a messaging row all kept the+ // stale title until a profile switch forced a refetch.+ setSessions([session({ id: 'tip', _lineage_ids: ['root', 'tip'], _lineage_root_id: 'root', title: 'Old' })])+ setCronSessions([session({ id: 'cron-1', source: 'cron', title: 'Old' })])+ setMessagingSessions([session({ id: 'tg-1', source: 'telegram', title: 'Old' })])++ applySessionTitle('root', 'Fresh')+ applySessionTitle('cron-1', 'Fresh')+ applySessionTitle('tg-1', 'Fresh')++ expect($sessions.get()[0].title).toBe('Fresh')+ expect($cronSessions.get()[0].title).toBe('Fresh')+ expect($messagingSessions.get()[0].title).toBe('Fresh')+ })++ it('keeps the slice reference when no row matches or the title is current', () => {+ const before = [session({ id: 'mine', title: 'Same' })]+ setSessions(before)++ applySessionTitle('absent', 'Whatever')+ expect($sessions.get()).toBe(before)++ applySessionTitle('mine', 'Same')+ expect($sessions.get()).toBe(before)+ })+})+describe('carryForwardFailedProfileSessions', () => {it('is a no-op when the backend reported no profile errors', () => {const previous = [session({ id: 'yesterday', profile: 'default' })]diff --git a/apps/desktop/src/store/session.ts b/apps/desktop/src/store/session.tsindex 1b8697cfa63..35759e98564 100644--- a/apps/desktop/src/store/session.ts+++ b/apps/desktop/src/store/session.ts@@ -16,7 +16,7 @@ import type { TileSessionFocusStamp } from '@/lib/session-timer-since'import { persistBoolean, persistString, readJson, storedBoolean, storedString, writeJson } from '@/lib/storage'import type { SessionInfo, UsageStats } from '@/types/hermes'-import { $removedSessionIds, isSessionRemovalPending } from './session-removal'+import { $removedSessionIds, isSessionRemovalPending, tombstoneRowIds } from './session-removal'import type { SessionOwnerRoute, SessionOwnerScope } from './session-request-router'import { clearUnreadOnOpen } from './session-unread-remote'@@ -710,14 +710,14 @@ export function mergeSessionPage(// user archived or deleted must not survive through the keep set — the// settle grace keeps a just-archived chat "recently settled" for 30s, which// is exactly the window the survivor path used to resurrect it (#118156).- // Same bare-id + lineage-root match as dropTombstoned applies to incoming+ // A tombstone matches ANY id the row has answered to (tip, root, and every+ // intermediate lineage segment), same as dropTombstoned applies to incoming// rows; a failed RPC untombstones immediately, so the filter is only ever// as sticky as the removal itself.const tombstones = $removedSessionIds.get()const tombstoned = (session: SessionInfo): boolean =>- tombstones.size > 0 &&- (tombstones.has(session.id) || (session._lineage_root_id != null && tombstones.has(session._lineage_root_id)))+ tombstones.size > 0 && tombstoneRowIds(session).some(id => tombstones.has(id))const survivors = previous.filter(session =>@@ -899,6 +899,44 @@ export function touchSessionActivity(})}+/** Patch a session's title across EVERY sidebar slice, matching the row by+ * any id the conversation has answered to (`sessionMatchesStoredId`) — a+ * compression tip, its root, and a middle segment all name the same chat.+ * A rename writes one title; every surface that renders the row (recents,+ * cron, messaging) must show it without waiting for a profile switch to+ * force a refetch (#123337). Reference-stable per slice when nothing+ * matched or the title is already current. */+export function applySessionTitle(storedSessionId: string | null | undefined, title: string | null): void {+ const id = storedSessionId?.trim()++ if (!id) {+ return+ }++ const next = title?.trim() || null++ const patch = (rows: SessionInfo[]): SessionInfo[] => {+ let changed = false++ const mapped = rows.map(session => {+ if (!sessionMatchesStoredId(session, id) || session.title === next) {+ return session+ }++ changed = true++ return { ...session, title: next }+ })++ return changed ? mapped : rows+ }++ setSessions(patch)+ setCronSessions(patch)+ setMessagingSessions(patch)+ setUnlistedSessionOwnerRows(patch)+}+export const $connection = atom<HermesConnection | null>(null)export const $gatewayState = atom<ConnectionState>('idle')export const $sessions = atom<SessionInfo[]>([])