The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(desktop): aggregate session dot state per profile on the rail (#91710)
Brooklyn Nicholson434b1011a95a
diff --git a/apps/desktop/src/app/chat/sidebar/profile-rail-connect.test.tsx b/apps/desktop/src/app/chat/sidebar/profile-rail-connect.test.tsxindex e9c1b0b3d7a..4d68a14091e 100644--- a/apps/desktop/src/app/chat/sidebar/profile-rail-connect.test.tsx+++ b/apps/desktop/src/app/chat/sidebar/profile-rail-connect.test.tsx@@ -49,6 +49,9 @@ vi.mock('@/store/profile', () => ({$profileOrder: atom([]),$profiles: atom([{ is_default: true, name: 'default' }]),$profileScope: atom('default'),+ // The rail's status summary (profile-dot-state) rides the real session+ // stores, whose import graph reaches $showAllProfiles through layout state.+ $showAllProfiles: atom(false),ALL_PROFILES: '*',normalizeProfileKey: (name: string) => name,profileLabel: (profile: { display_name?: string; name: string }) =>diff --git a/apps/desktop/src/app/chat/sidebar/profile-rail-fleet.test.tsx b/apps/desktop/src/app/chat/sidebar/profile-rail-fleet.test.tsxindex 5f5a9bb7660..e32acbaa7a8 100644--- a/apps/desktop/src/app/chat/sidebar/profile-rail-fleet.test.tsx+++ b/apps/desktop/src/app/chat/sidebar/profile-rail-fleet.test.tsx@@ -78,6 +78,9 @@ vi.mock('@/store/profile', () => ({$profileOrder: atom([]),$profiles: atom([{ is_default: true, name: 'default' }]),$profileScope: atom('default'),+ // The rail's status summary (profile-dot-state) rides the real session+ // stores, whose import graph reaches $showAllProfiles through layout state.+ $showAllProfiles: atom(false),ALL_PROFILES: '*',normalizeProfileKey: (name: string) => name,profileLabel: (profile: { display_name?: string; name: string }) =>diff --git a/apps/desktop/src/app/chat/sidebar/profile-rail-status.test.tsx b/apps/desktop/src/app/chat/sidebar/profile-rail-status.test.tsxnew file mode 100644index 00000000000..913db7ef9c5--- /dev/null+++ b/apps/desktop/src/app/chat/sidebar/profile-rail-status.test.tsx@@ -0,0 +1,187 @@+import { cleanup, fireEvent, render, screen } from '@testing-library/react'+import { atom } from 'nanostores'+import { afterEach, describe, expect, it, vi } from 'vitest'++import { ProfileRail } from './profile-switcher'++// #91710: a profile that finishes work while another is selected must carry a+// durable unread/attention indicator on its rail square (and in the condensed+// dropdown), with the counts in the accessible name. The summary derives from+// the REAL session-unread/session-dot-state stores — only the rail's own shell+// dependencies (routing, profile registry, dialogs) are mocked, so this tests+// the marker → summary → square path end to end.++const navigate = vi.fn()++vi.mock('react-router', () => ({+ useNavigate: () => navigate+}))++vi.mock('@/i18n', () => ({+ useI18n: () => ({+ t: {+ common: { cancel: 'Cancel', delete: 'Delete' },+ profiles: {+ actions: 'Actions',+ allProfiles: 'All profiles',+ color: 'Color…',+ colorFor: 'Color',+ connectGateway: 'Manage gateways…',+ editSoul: 'Edit SOUL.md…',+ exportMenu: 'Export profile…',+ failedLoadSoul: 'Failed to load SOUL.md',+ failedSaveSoul: 'Failed to save SOUL.md',+ importProfile: 'Import profile…',+ manageProfiles: 'Manage profiles…',+ newProfile: 'New profile',+ renameMenu: 'Rename…',+ remoteOverride: {+ badge: (host: string) => `Runs on ${host}`,+ menuItem: 'Connect to a remote host…'+ },+ saveSoul: 'Save',+ saving: 'Saving…',+ showAllProfiles: 'Show all profiles',+ soulSaved: 'SOUL.md saved',+ status: {+ needsInput: (count: number) => `${count} needs input`,+ unread: (count: number) => `${count} unread`,+ working: (count: number) => `${count} working`+ },+ switchConnectionFailed: (name: string) => `Could not connect to ${name}`,+ switchToProfile: (name: string) => `Switch to ${name}`,+ title: 'Profiles'+ }+ }+ })+}))++vi.mock('@/store/profile', () => ({+ $activeGatewayProfile: atom('default'),+ $profileColors: atom({}),+ $profileCreateRequest: atom(0),+ $profileOrder: atom([]),+ $profiles: atom([{ is_default: true, name: 'default' }]),+ $profileScope: atom('default'),+ $showAllProfiles: atom(false),+ ALL_PROFILES: '*',+ normalizeProfileKey: (name: string) => name,+ profileLabel: (profile: { display_name?: string; name: string }) =>+ (profile.display_name ?? '').trim() || profile.name,+ refreshActiveProfile: vi.fn().mockResolvedValue(undefined),+ selectProfile: vi.fn(),+ setProfileColor: vi.fn(),+ setProfileOrder: vi.fn(),+ setShowAllProfiles: vi.fn(),+ sortByProfileOrder: (profiles: unknown[]) => profiles+}))++vi.mock('@/store/connections', () => ({+ $activeConnectionId: atom<null | string>(null),+ $connectionsRegistry: atom(null),+ $hasMultipleConnections: atom(false),+ selectConnection: vi.fn()+}))++vi.mock('@/store/profile-share', () => ({+ runExportProfileFlow: vi.fn(),+ runImportProfileFlow: vi.fn()+}))++vi.mock('./use-profile-prewarm', () => ({+ useProfilePrewarm: () => ({ cancelPrewarm: vi.fn(), notePointerMove: vi.fn(), startPrewarm: vi.fn() })+}))++vi.mock('@/hermes', () => ({+ getProfileSoul: vi.fn().mockResolvedValue({ content: '' }),+ updateProfileSoul: vi.fn()+}))++vi.mock('@/components/chat/code-editor', () => ({ CodeEditor: () => null }))+vi.mock('../../profiles/create-profile-dialog', () => ({ CreateProfileDialog: () => null }))+vi.mock('../../profiles/delete-profile-dialog', () => ({ DeleteProfileDialog: () => null }))+vi.mock('../../profiles/rename-profile-dialog', () => ({ RenameProfileDialog: () => null }))++const { $profiles } = await import('@/store/profile')+const profiles = $profiles as ReturnType<typeof atom<Array<{ is_default: boolean; name: string }>>>+const { $unreadFinishedMarkers } = await import('@/store/session-unread')++afterEach(() => {+ cleanup()+ profiles.set([{ is_default: true, name: 'default' }])+ $unreadFinishedMarkers.set({})+})++describe('ProfileRail per-profile status (#91710)', () => {+ it('marks an inactive profile square unread and names the count accessibly', () => {+ profiles.set([+ { is_default: true, name: 'default' },+ { is_default: false, name: 'writer' }+ ])+ // writer's session finished while default was selected; its rows are not+ // even loaded — the persisted marker is the whole signal.+ $unreadFinishedMarkers.set({ writer: ['s1'] })++ render(<ProfileRail />)++ const writerSquare = screen.getByRole('button', { name: 'writer, 1 unread' })++ expect(writerSquare.querySelector('[data-slot="profile-status-dot"]')).not.toBeNull()+ })++ it('keeps the active profile square clean', () => {+ profiles.set([+ { is_default: true, name: 'default' },+ { is_default: false, name: 'writer' }+ ])+ $unreadFinishedMarkers.set({ writer: ['s1'], default: ['s9'] })++ render(<ProfileRail />)++ // default is the active home: no status dot on its square, no status in+ // its accessible name — the sidebar it owns already shows the row dots.+ // (The default square doubles as the "show all" toggle when already home.)+ const homePill = screen.getByRole('button', { name: 'Show all profiles' })++ expect(homePill.querySelector('[data-slot="profile-status-dot"]')).toBeNull()++ const writerSquare = screen.getByRole('button', { name: 'writer, 1 unread' })++ expect(writerSquare.querySelector('[data-slot="profile-status-dot"]')).not.toBeNull()+ })++ it('leaves every square clean when no profile has unread or live work', () => {+ profiles.set([+ { is_default: true, name: 'default' },+ { is_default: false, name: 'writer' }+ ])++ render(<ProfileRail />)++ expect(screen.getByRole('button', { name: 'writer' })).toBeTruthy()+ // eslint-disable-next-line no-restricted-globals -- whole-rail assertion: no square painted a status dot+ expect(document.querySelector('[data-slot="profile-status-dot"]')).toBeNull()+ })++ it('keeps the indicator in the condensed dropdown beyond the square threshold', async () => {+ // Past 13 squares the rail collapses to a dropdown; the unread state must+ // survive the collapse.+ profiles.set([+ { is_default: true, name: 'default' },+ { is_default: false, name: 'writer' },+ ...Array.from({ length: 13 }, (_, index) => ({ is_default: false, name: `bot-${index}` }))+ ])+ $unreadFinishedMarkers.set({ writer: ['s1'] })++ render(<ProfileRail />)++ const trigger = screen.getByRole('button', { name: 'Profiles' })++ fireEvent.pointerDown(trigger, { button: 0, ctrlKey: false, pointerType: 'mouse' })+ fireEvent.click(trigger)++ const writerItem = await screen.findByRole('menuitemradio', { name: 'writer, 1 unread' })++ expect(writerItem.querySelector('[data-slot="profile-status-dot"]')).not.toBeNull()+ })+})diff --git a/apps/desktop/src/app/chat/sidebar/profile-switcher.tsx b/apps/desktop/src/app/chat/sidebar/profile-switcher.tsxindex 8e3a5a2beb9..9da34305a6f 100644--- a/apps/desktop/src/app/chat/sidebar/profile-switcher.tsx+++ b/apps/desktop/src/app/chat/sidebar/profile-switcher.tsx@@ -46,7 +46,7 @@ import { ProfileGlyph } from '@/components/ui/profile-glyph'import { Tip, Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'import type { DesktopRegistryConnection } from '@/global'import { getProfileSoul, updateProfileSoul } from '@/hermes'-import { useI18n } from '@/i18n'+import { type Translations, useI18n } from '@/i18n'import { sortConnectionsForDisplay } from '@/lib/connection-display'import { triggerHaptic } from '@/lib/haptics'import { Loader2 } from '@/lib/icons'@@ -58,6 +58,7 @@ import {reorderCommitHaptic,reorderStepHaptic} from '@/lib/reorder'+import { useStoreSelector } from '@/lib/use-session-slice'import { cn } from '@/lib/utils'import {$activeConnectionId,@@ -84,6 +85,12 @@ import {setShowAllProfiles,sortByProfileOrder} from '@/store/profile'+import {+ $profileDotStateByScope,+ type ProfileDotState,+ type ProfileDotSummary,+ profileDotSummaryFor+} from '@/store/profile-dot-state'import {$profileRemoteOverrides,openRemoteOverrideDialog,@@ -112,6 +119,63 @@ const RAIL_GAP = 4 // px — matches gap-1 between squares.// menu. Drag-reorder and long-press-recolor live only on the squares path.const PROFILE_DROPDOWN_THRESHOLD = 13+// #91710: a profile that finished (or blocked, or is still working) while+// another was selected carries an indicator on its rail square and dropdown+// row. The colors mirror the session status dot's palette — amber for "needs+// your answer", accent for running, success green for unread — so a profile's+// loudest state reads the same as its sessions' dots in the sidebar below.+const PROFILE_STATUS_DOT_CLASS: Record<ProfileDotState, string> = {+ 'needs-input': 'bg-amber-500',+ working: 'bg-(--ui-accent)',+ unread: 'bg-(--ui-success)'+}++/** The a11y/tooltip text for one square's summary — every non-zero count,+ * most urgent first ("1 session needs your answer, 2 unread sessions"). The+ * counts ride the accessible name so the state is never color-only. */+function profileStatusLabel(p: Translations['profiles'], summary: ProfileDotSummary): string {+ const parts: string[] = []++ if (summary.needsInputCount > 0) {+ parts.push(p.status.needsInput(summary.needsInputCount))+ }++ if (summary.workingCount > 0) {+ parts.push(p.status.working(summary.workingCount))+ }++ if (summary.unreadCount > 0) {+ parts.push(p.status.unread(summary.unreadCount))+ }++ return parts.join(', ')+}++/** One profile square's rollup of its sessions' shared dot state, keyed by the+ * (gateway, profile) the square names. `connectionId` is null for this+ * machine's primary. The interned summaries keep the selector's bail-out+ * intact: a square re-renders only when its own counts change. */+function useProfileStatus(+ profile: null | string,+ connectionId: null | string | undefined+): ProfileDotSummary | null {+ return useStoreSelector($profileDotStateByScope, byScope =>+ profile ? (profileDotSummaryFor(byScope, connectionId, profile) ?? null) : null+ )+}++/** The dot a square/dropdown row paints for a summary. `status-dot` slot so+ * tests (and tours) can find it without duplicating the class string. */+function ProfileStatusDot({ summary }: { summary: ProfileDotSummary }) {+ return (+ <span+ aria-hidden="true"+ className={cn('size-1.5 rounded-full', PROFILE_STATUS_DOT_CLASS[summary.state])}+ data-slot="profile-status-dot"+ />+ )+}+// Neighbors reflow on RAIL_TRANSITION; the dragged square glides between// snapped cells on the snappier DRAG_TRANSITION. Both come from the SHARED// reorder primitive (lib/reorder.ts) so every reorder strip feels identical.@@ -810,6 +874,7 @@ function ProfileDropdown({<ProfileDropdownItemcolor={resolveProfileColor(profile.name, colors)}connectionId={connectionId}+ hideStatus={profile.name === value}key={profile.name}label={profileLabel(profile)}name={profile.name}@@ -825,28 +890,13 @@ function ProfileDropdown({{!group.reachable && <span aria-hidden="true" className="size-1.5 shrink-0 rounded-full bg-amber-500" />}</DropdownMenuLabel>{[group.defaultAgent, ...group.named].map(agent => (- <ProfileLaunchContextMenu- connectionId={agent.connectionId}+ <RestDropdownItem+ agent={agent}+ colors={colors}+ gatewayLabel={group.label}key={agent.profile}- label={p.fleet.onGateway(agent.profile, group.label)}- profile={agent.profile}- >- <DropdownMenuItem- aria-label={p.fleet.onGateway(agent.profile, group.label)}- className="min-w-0"- onSelect={() => onSelectRest(agent)}- >- <span className="flex min-w-0 items-center gap-1.5">- <ProfileGlyph- aria-hidden="true"- color={resolveProfileColor(agent.profile, colors)}- isDefault={agent.isDefault}- name={agent.profile}- />- <span className="truncate">{agent.profile}</span>- </span>- </DropdownMenuItem>- </ProfileLaunchContextMenu>+ onSelect={onSelectRest}+ />))}</div>))}@@ -860,15 +910,23 @@ function ProfileDropdown({function ProfileDropdownItem({color,connectionId,+ hideStatus,label,name}: {color: null | stringconnectionId: null | string+ /** The dropdown's own selected row: its sessions are on screen in the+ * sidebar, so its rollup is suppressed like the active square (#91710). */+ hideStatus?: booleanlabel: stringname: string}) {+ const { t } = useI18n()+ const p = t.profilesconst { cancelPrewarm, notePointerMove, startPrewarm } = useProfilePrewarm(name)+ const summary = useProfileStatus(name, connectionId)+ const statusText = summary && !hideStatus ? profileStatusLabel(p, summary) : nullreturn (<ProfileLaunchContextMenu connectionId={connectionId} label={label} profile={name}>@@ -882,12 +940,55 @@ function ProfileDropdownItem({<span className="flex min-w-0 items-center gap-1.5"><ProfileGlyph aria-hidden="true" color={color} isDefault={false} name={name} /><span className="truncate">{label}</span>+ {summary && !hideStatus && <ProfileStatusDot summary={summary} />}</span>+ {statusText && <span className="sr-only">{`, ${statusText}`}</span>}</DropdownMenuRadioItem></ProfileLaunchContextMenu>)}+// One at-rest gateway's profile row in the condensed dropdown — the dropdown+// twin of RestSquare, carrying the same rollup (#91710).+function RestDropdownItem({+ agent,+ colors,+ gatewayLabel,+ onSelect+}: {+ agent: FleetAgent+ colors: Record<string, string>+ gatewayLabel: string+ onSelect: (agent: FleetAgent) => void+}) {+ const { t } = useI18n()+ const p = t.profiles+ const label = p.fleet.onGateway(agent.profile, gatewayLabel)+ const summary = useProfileStatus(agent.profile, agent.connectionId)+ const statusText = summary ? profileStatusLabel(p, summary) : null++ return (+ <ProfileLaunchContextMenu connectionId={agent.connectionId} label={label} profile={agent.profile}>+ <DropdownMenuItem+ aria-label={statusText ? `${label}, ${statusText}` : label}+ className="min-w-0"+ onSelect={() => onSelect(agent)}+ >+ <span className="flex min-w-0 items-center gap-1.5">+ <ProfileGlyph+ aria-hidden="true"+ color={resolveProfileColor(agent.profile, colors)}+ isDefault={agent.isDefault}+ name={agent.profile}+ />+ <span className="truncate">{agent.profile}</span>+ {summary && <ProfileStatusDot summary={summary} />}+ </span>+ </DropdownMenuItem>+ </ProfileLaunchContextMenu>+ )+}+interface ProfilePillProps {active: boolean// home / All / Manage are glyph action buttons (navigation, not identity).@@ -913,16 +1014,26 @@ function ProfilePill({profile,slot}: ProfilePillProps) {+ const { t } = useI18n()+ const p = t.profiles+ // The default profile's home face carries the same rollup as a named square+ // (its sessions can finish while another profile is selected too), again+ // suppressed while it is the active home (#91710).+ const summary = useProfileStatus(profile ?? null, connectionId)+ const statusText = !active && summary ? profileStatusLabel(p, summary) : null+ const accessibleLabel = statusText ? `${label}, ${statusText}` : label+const button = (- <Tip label={label}>+ <Tip label={accessibleLabel}><Buttonaria-busy={pending || undefined}- aria-label={label}+ aria-label={accessibleLabel}aria-pressed={active}className={cn('bg-transparent text-(--ui-text-tertiary) hover:bg-(--ui-control-hover-background) hover:text-foreground',active && 'bg-(--ui-control-active-background) text-foreground',- muted && 'opacity-40 hover:opacity-100'+ muted && 'opacity-40 hover:opacity-100',+ summary && !active && 'relative')}data-connection-id={connectionId}data-slot={slot}@@ -936,6 +1047,11 @@ function ProfilePill({) : (<Codicon name={glyph} size="0.875rem" />)}+ {summary && !active && (+ <span className="absolute -right-0.5 -top-0.5">+ <ProfileStatusDot summary={summary} />+ </span>+ )}</Button></Tip>)@@ -1088,6 +1204,12 @@ function RestSquare({const [pickerOpen, setPickerOpen] = useState(false)const label = p.fleet.onGateway(agent.profile, agent.connectionLabel)+ // An at-rest gateway's square always carries its profiles' rollup — it is+ // never the active square, and its sessions are not on screen anywhere+ // else (#91710).+ const summary = useProfileStatus(agent.profile, agent.connectionId)+ const statusText = summary ? profileStatusLabel(p, summary) : null+const pickColor = (next: null | string) => {onRecolor(next)setPickerOpen(false)@@ -1104,7 +1226,7 @@ function RestSquare({<TooltipTrigger asChild><buttonaria-busy={pending || undefined}- aria-label={label}+ aria-label={statusText ? `${label}, ${statusText}` : label}className="relative grid size-5 shrink-0 select-none place-items-center rounded-[3px] text-[0.5625rem] font-semibold uppercase leading-none opacity-35 transition-opacity hover:opacity-100 aria-busy:opacity-100"data-connection-id={agent.connectionId}data-profile={agent.profile}@@ -1118,11 +1240,16 @@ function RestSquare({) : (profileShortLabel(agent.profile))}+ {summary && (+ <span className="absolute -bottom-0.5 -right-0.5">+ <ProfileStatusDot summary={summary} />+ </span>+ )}</button></TooltipTrigger></ContextMenuTrigger></PopoverAnchor>- <TooltipContent>{label}</TooltipContent>+ <TooltipContent>{statusText ? `${label} · ${statusText}` : label}</TooltipContent></Tooltip></TooltipProvider>@@ -1233,6 +1360,12 @@ function ProfileSquare({// spawn now so a cold click doesn't pay the full boot.const { cancelPrewarm, notePointerMove, startPrewarm } = useProfilePrewarm(name)+ // The square carries its profile's session rollup — but never when active:+ // the workspace is homed there and the sidebar below already shows that+ // profile's own row dots (#91710).+ const summary = useProfileStatus(name, connectionId)+ const statusText = !active && summary ? profileStatusLabel(p, summary) : null+const { attributes, isDragging, listeners, setNodeRef, transform, transition } = useSortable({id: name,transition: RAIL_TRANSITION@@ -1291,7 +1424,11 @@ function ProfileSquare({type="button"{...attributes}{...listeners}- aria-label={remoteHost ? `${label} — ${p.remoteOverride.badge(remoteHost)}` : label}+ aria-label={+ [remoteHost ? `${label} — ${p.remoteOverride.badge(remoteHost)}` : label, statusText]+ .filter(Boolean)+ .join(', ') || label+ }aria-pressed={active}// Hold-to-recolor rides alongside the dnd pointer listener (call// it first so drag tracking still arms), then a timer opens the@@ -1342,11 +1479,22 @@ function ProfileSquare({<Codicon name="globe" size="0.5rem" /></span>)}+ {/* The profile's session rollup (#91710): bottom-right so it+ never fights the remote globe. */}+ {!active && summary && (+ <span className="absolute -bottom-0.5 -right-0.5">+ <ProfileStatusDot summary={summary} />+ </span>+ )}</button></TooltipTrigger></ContextMenuTrigger></PopoverAnchor>- <TooltipContent>{remoteHost ? `${label} · ${p.remoteOverride.badge(remoteHost)}` : label}</TooltipContent>+ <TooltipContent>+ {[remoteHost ? `${label} · ${p.remoteOverride.badge(remoteHost)}` : label, statusText]+ .filter(Boolean)+ .join(' · ')}+ </TooltipContent></Tooltip></TooltipProvider>diff --git a/apps/desktop/src/i18n/de.ts b/apps/desktop/src/i18n/de.tsindex 7c3f12406a0..889244e357a 100644--- a/apps/desktop/src/i18n/de.ts+++ b/apps/desktop/src/i18n/de.ts@@ -3529,6 +3529,12 @@ export const deOverrides = {switchTo: (name, gateway) => `Zu ${name} auf ${gateway} wechseln`,deleteOn: gateway => ` auf ${gateway}`},+ status: {+ unread: (count: number) => (count === 1 ? '1 ungelesene Sitzung' : `${count} ungelesene Sitzungen`),+ needsInput: (count: number) =>+ count === 1 ? '1 Sitzung wartet auf Ihre Antwort' : `${count} Sitzungen warten auf Ihre Antwort`,+ working: (count: number) => (count === 1 ? '1 laufende Sitzung' : `${count} laufende Sitzungen`)+ },remoteOverride: {menuItem: 'Mit Remote-Host verbinden…',badge: (host: string) => `Läuft auf ${host}`,diff --git a/apps/desktop/src/i18n/en.ts b/apps/desktop/src/i18n/en.tsindex 804cd193213..5de6ef49877 100644--- a/apps/desktop/src/i18n/en.ts+++ b/apps/desktop/src/i18n/en.ts@@ -3087,6 +3087,12 @@ export const en: Translations = {switchTo: (name, gateway) => `Switch to ${name} on ${gateway}`,deleteOn: gateway => ` on ${gateway}`},+ status: {+ unread: (count: number) => (count === 1 ? '1 unread session' : `${count} unread sessions`),+ needsInput: (count: number) =>+ count === 1 ? '1 session needs your answer' : `${count} sessions need your answer`,+ working: (count: number) => (count === 1 ? '1 session running' : `${count} sessions running`)+ },remoteOverride: {menuItem: 'Connect to a remote host…',badge: (host: string) => `Runs on ${host}`,diff --git a/apps/desktop/src/i18n/es.ts b/apps/desktop/src/i18n/es.tsindex 5138f9127ab..4541f2e8349 100644--- a/apps/desktop/src/i18n/es.ts+++ b/apps/desktop/src/i18n/es.ts@@ -3519,6 +3519,12 @@ export const esOverrides = {switchTo: (name: string, gateway: string) => `Cambiar a ${name} en ${gateway}`,deleteOn: (gateway: string) => ` en ${gateway}`},+ status: {+ unread: (count: number) => (count === 1 ? '1 sesión sin leer' : `${count} sesiones sin leer`),+ needsInput: (count: number) =>+ count === 1 ? '1 sesión espera tu respuesta' : `${count} sesiones esperan tu respuesta`,+ working: (count: number) => (count === 1 ? '1 sesión en ejecución' : `${count} sesiones en ejecución`)+ },remoteOverride: {menuItem: 'Conectar a un host remoto…',badge: (host: string) => `Se ejecuta en ${host}`,diff --git a/apps/desktop/src/i18n/fr.ts b/apps/desktop/src/i18n/fr.tsindex 90c7a6fa3cb..d617f185fd3 100644--- a/apps/desktop/src/i18n/fr.ts+++ b/apps/desktop/src/i18n/fr.ts@@ -3536,6 +3536,12 @@ export const frOverrides = {switchTo: (name, gateway) => `Basculer vers ${name} sur ${gateway}`,deleteOn: gateway => ` sur ${gateway}`},+ status: {+ unread: (count: number) => (count === 1 ? '1 session non lue' : `${count} sessions non lues`),+ needsInput: (count: number) =>+ count === 1 ? '1 session attend votre réponse' : `${count} sessions attendent votre réponse`,+ working: (count: number) => (count === 1 ? '1 session en cours' : `${count} sessions en cours`)+ },remoteOverride: {menuItem: 'Se connecter à un hôte distant…',badge: (host: string) => `S'exécute sur ${host}`,diff --git a/apps/desktop/src/i18n/types.ts b/apps/desktop/src/i18n/types.tsindex 43bb541a641..ae928d3de2a 100644--- a/apps/desktop/src/i18n/types.ts+++ b/apps/desktop/src/i18n/types.ts@@ -2584,6 +2584,11 @@ export interface Translations {switchTo: (name: string, gateway: string) => stringdeleteOn: (gateway: string) => string}+ status: {+ unread: (count: number) => string+ needsInput: (count: number) => string+ working: (count: number) => string+ }remoteOverride: {menuItem: stringbadge: (host: string) => stringdiff --git a/apps/desktop/src/store/profile-dot-state.test.ts b/apps/desktop/src/store/profile-dot-state.test.tsnew file mode 100644index 00000000000..5e422b920c8--- /dev/null+++ b/apps/desktop/src/store/profile-dot-state.test.ts@@ -0,0 +1,183 @@+import { afterEach, beforeEach, describe, expect, it } from 'vitest'++import { createClientSessionState } from '@/lib/chat-runtime'+import type { SessionInfo } from '@/types/hermes'++import { makeSessionInfo } from '../test/session-info'++import { $fleetRoster } from './fleet-roster'+import { $activeGatewayProfile, $profiles } from './profile'+import { $profileDotStateByScope, profileDotScopeKey } from './profile-dot-state'+import {+ $cronSessions,+ $messagingSessions,+ $selectedStoredSessionId,+ $sessions,+ $unreadFinishedSessionIds,+ setSessions+} from './session'+import {+ clearAllSessionStates,+ publishSessionState,+ recordSessionEventScope+} from './session-states'+import { $sessionSeenCounts, $unreadFinishedMarkers } from './session-unread'++const session = (over: Partial<SessionInfo>): SessionInfo => makeSessionInfo({ id: 'live', ...over })++const profileInfo = (name: string, is_default = false) => ({+ has_env: false,+ is_default,+ model: null,+ name,+ path: `/profiles/${name}`,+ provider: null,+ skill_count: 0+})++function resetAll() {+ clearAllSessionStates()+ $sessions.set([])+ $cronSessions.set([])+ $messagingSessions.set([])+ $selectedStoredSessionId.set(null)+ $activeGatewayProfile.set('default')+ $sessionSeenCounts.set({})+ $unreadFinishedMarkers.set({})+ $unreadFinishedSessionIds.set([])+ $fleetRoster.set(null)+ $profiles.set([profileInfo('default', true), profileInfo('writer')])+}++const summaryFor = (connectionId: null | string, profile: string) =>+ $profileDotStateByScope.get()[profileDotScopeKey(connectionId, profile)]++describe('profile rail dot state ($profileDotStateByScope)', () => {+ beforeEach(resetAll)+ afterEach(resetAll)++ it("lights the inactive profile's scope when its session finishes unread (#91710)", () => {+ // Profile writer's turn runs; the user is homed on default.+ setSessions([session({ id: 's1', message_count: 3, profile: 'writer' })])++ publishSessionState('r1', { ...createClientSessionState('s1'), busy: true })+ publishSessionState('r1', { ...createClientSessionState('s1'), busy: false })++ // The busy→idle edge persisted the marker into the ROW's profile bucket.+ expect($unreadFinishedMarkers.get()['writer']).toBeDefined()++ // Profile switch drains the list: the marker alone must keep the square lit.+ setSessions([])++ const writer = summaryFor(null, 'writer')++ expect(writer).toBeDefined()+ expect(writer?.state).toBe('unread')+ expect(writer?.unreadCount).toBe(1)+ expect(summaryFor(null, 'default')).toBeUndefined()+ })++ it('ranks needs-input over working within one profile', () => {+ setSessions([+ session({ id: 's1', message_count: 3, profile: 'writer' }),+ session({ id: 's2', message_count: 3, profile: 'writer' })+ ])++ publishSessionState('r1', { ...createClientSessionState('s1'), busy: true })+ publishSessionState('r2', { ...createClientSessionState('s2'), needsInput: true })++ const writer = summaryFor(null, 'writer')++ expect(writer?.state).toBe('needs-input')+ expect(writer?.needsInputCount).toBe(1)+ expect(writer?.workingCount).toBe(1)+ })++ it('ranks working over unread within one profile', () => {+ setSessions([+ session({ id: 's1', message_count: 3, profile: 'writer' }),+ session({ id: 's2', message_count: 3, profile: 'writer' })+ ])++ publishSessionState('r1', { ...createClientSessionState('s1'), busy: true })+ publishSessionState('r2', { ...createClientSessionState('s2'), busy: true })+ // s2 finishes unread while s1 is still running.+ publishSessionState('r2', { ...createClientSessionState('s2'), busy: false })++ const writer = summaryFor(null, 'writer')++ expect(writer?.state).toBe('working')+ expect(writer?.workingCount).toBe(1)+ expect(writer?.unreadCount).toBe(1)+ })++ it('keeps a same-id session in another profile from cross-marking', () => {+ // writer's finished session shares default's stored id; only writer holds+ // the marker, so only writer's square lights.+ $unreadFinishedMarkers.set({ writer: ['s1'] })+ setSessions([session({ id: 's1', message_count: 3, profile: 'default' })])++ expect(summaryFor(null, 'writer')?.unreadCount).toBe(1)+ expect(summaryFor(null, 'default')).toBeUndefined()+ })++ it('counts a backend-unread row in its own profile', () => {+ setSessions([session({ id: 's9', message_count: 2, profile: 'default', unread: true })])++ const summary = summaryFor(null, 'default')++ expect(summary?.state).toBe('unread')+ expect(summary?.unreadCount).toBe(1)+ })++ it('counts a marker-backed unread row once (row and marker agree)', () => {+ $unreadFinishedMarkers.set({ writer: ['s1'] })+ $sessionSeenCounts.set({ writer: { s1: 3 } })+ setSessions([session({ id: 's1', message_count: 5, profile: 'writer' })])++ expect(summaryFor(null, 'writer')?.unreadCount).toBe(1)+ })++ it('does not attribute ambiguous bare-profile markers when two gateways share the profile name', () => {+ $unreadFinishedMarkers.set({ writer: ['s1'] })+ $fleetRoster.set({+ agents: [+ {+ connectionId: 'remote-1',+ connectionKind: 'ssh',+ connectionLabel: 'Box',+ handle: 'h1',+ profile: 'writer'+ }+ ],+ sources: []+ })++ // The local gateway exposes 'writer' too, so the persisted marker (bucketed+ // by bare profile name) cannot say which machine owns it: no dot, rather+ // than a wrong one.+ expect(summaryFor(null, 'writer')).toBeUndefined()+ })++ it('attributes an unlisted working session to its owning gateway scope', () => {+ recordSessionEventScope({ connectionId: 'conn-1', profile: 'writer', session_id: 'r4' })+ publishSessionState('r4', { ...createClientSessionState('s4'), busy: true })++ const summary = summaryFor('conn-1', 'writer')++ expect(summary?.state).toBe('working')+ expect(summary?.workingCount).toBe(1)+ })++ it('writes the finish marker to the socket-proven profile, not the active one', () => {+ // No loaded row: without the event-proven owner the marker would fall back+ // to the ACTIVE gateway profile and light the wrong square (#91710).+ recordSessionEventScope({ connectionId: 'conn-9', profile: 'writer', session_id: 'r3' })++ publishSessionState('r3', { ...createClientSessionState('s3'), busy: true })+ publishSessionState('r3', { ...createClientSessionState('s3'), busy: false })++ expect($unreadFinishedMarkers.get()['writer']).toBeDefined()+ expect($unreadFinishedMarkers.get()['default']).toBeUndefined()+ })+})diff --git a/apps/desktop/src/store/profile-dot-state.ts b/apps/desktop/src/store/profile-dot-state.tsnew file mode 100644index 00000000000..bd1a8ff48b2--- /dev/null+++ b/apps/desktop/src/store/profile-dot-state.ts@@ -0,0 +1,274 @@+/**+ * PROFILE DOT STATE — the profile rail's per-profile rollup of the shared+ * session dot state ($sessionDotStateById), so a profile that finished (or+ * blocked, or is still working) while another profile was selected shows an+ * indicator on its rail square and in the condensed profile dropdown (#91710).+ *+ * The session-level layers already exist and stay authoritative: the live+ * busy→idle edge, the persisted per-profile unread markers+ * ($unreadFinishedMarkers, which survive restarts), and the backend's derived+ * row.unread watermark — all folded by session-dot-state.ts into ONE state per+ * session. This module only re-buckets those resolved states by the profile+ * that owns each session, keyed by the same composite (connection, profile)+ * scope the gateway registry uses (backendScopeKey), so identically named+ * profiles on different gateways never cross-mark.+ *+ * Three passes, weakest claim first (a later pass overwrites on priority, the+ * same rule session-dot-state applies per session):+ *+ * 1. LOADED ROWS — every listed chat/messaging row claims its own scope from+ * its (connection_id, profile) tags. Cron rows are deliberately EXCLUDED:+ * cron runs finish unwatched by design and counting them would turn every+ * profile's square into a permanently lit cron-run counter (#93552).+ * 2. UNLISTED RUNTIMES — a live (busy / needs-input) session whose row is not+ * loaded (an inactive profile's background work, a hidden Bot Chat) claims+ * the scope its socket proved (runtimeSessionOwner: the exact registry+ * (connection, profile), or the legacy profile-only pool's bare name).+ * No proven owner → no claim: no dot rather than a wrong one.+ * 3. PERSISTED UNREAD MARKERS — the cross-profile, cross-restart half. A+ * marker with no loaded row is an unread session in a profile whose rows+ * are not on screen. Markers are bucketed by BARE profile name (see+ * session-unread.ts), so they are attributed to a (connection, profile)+ * scope only when the gateway that owns that profile name is unambiguous —+ * loaded rows' connections, the active gateway, and the fleet roster must+ * all agree. Two gateways exposing the same profile name leave that bucket+ * unpainted rather than guessing (#91710: identically named profiles stay+ * independently scoped).+ */++import { backendScopeKey, LOCAL_CONNECTION_ID } from '@hermes/shared'+import { computed } from 'nanostores'++import { stableRecord } from '@/lib/stable-array'+import type { SessionInfo } from '@/types/hermes'++import { $activeConnectionId } from './connections'+import { $fleetRoster } from './fleet-roster'+import { $profiles, normalizeProfileKey } from './profile'+import { $cronSessions, $messagingSessions, $sessions, sessionMatchesStoredId, sessionPinId } from './session'+import { $sessionDotStateById } from './session-dot-state'+import { $sessionStates, runtimeSessionOwner } from './session-states'+import { $unreadFinishedMarkers } from './session-unread'++/** The summary one profile square paints: its loudest state plus the counts+ * behind it. Priority matches the session-level rank: a profile that needs+ * your answer outranks one that is working, which outranks unread. */+export type ProfileDotState = 'needs-input' | 'unread' | 'working'++export interface ProfileDotSummary {+ readonly state: ProfileDotState+ readonly needsInputCount: number+ readonly workingCount: number+ readonly unreadCount: number+}++/** The canonical scope key for a rail square or a session row: the same+ * composite the registry uses, so a row and its square can never disagree+ * about which (gateway, profile) a session belongs to. */+export const profileDotScopeKey = (+ connectionId: null | string | undefined,+ profile: null | string | undefined+): string => backendScopeKey(connectionId?.trim() || null, profile)++const profileKeyOf = (row: Pick<SessionInfo, 'profile'>): string => normalizeProfileKey(row.profile)++const rowScopeOf = (row: Pick<SessionInfo, 'connection_id' | 'profile'>): string =>+ profileDotScopeKey(row.connection_id, profileKeyOf(row))++// Interned so `useStoreSelector` consumers bail out when their square's+// counts did not change, and so stableRecord's per-value reference compare+// gates the computed's emit.+const summaryCache = new Map<string, ProfileDotSummary>()++function internSummary(needsInputCount: number, workingCount: number, unreadCount: number): ProfileDotSummary {+ const key = `${needsInputCount}\u0000${workingCount}\u0000${unreadCount}`+ let summary = summaryCache.get(key)++ if (!summary) {+ summary = Object.freeze({+ state: needsInputCount > 0 ? ('needs-input' as const) : workingCount > 0 ? ('working' as const) : ('unread' as const),+ needsInputCount,+ workingCount,+ unreadCount+ })+ summaryCache.set(key, summary)+ }++ return summary+}++interface Tally {+ needsInput: number+ unread: number+ working: number+}++let prev: Readonly<Record<string, ProfileDotSummary>> = {}++/** Profile-scope key → the summary that scope's rail square paints. Scopes+ * with no claims are absent. */+export const $profileDotStateByScope = computed(+ [+ $sessionDotStateById,+ $sessionStates,+ $sessions,+ $messagingSessions,+ $cronSessions,+ $unreadFinishedMarkers,+ $profiles,+ $fleetRoster,+ $activeConnectionId+ ],+ (dots, states, sessions, messaging, cron, markers, profiles, roster, activeConnectionId) => {+ const tallies = new Map<string, Tally>()++ const tallyFor = (scope: string): Tally => {+ let tally = tallies.get(scope)++ if (!tally) {+ tally = { needsInput: 0, unread: 0, working: 0 }+ tallies.set(scope, tally)+ }++ return tally+ }++ const claimRow = (scope: string, state: 'needs-input' | 'unread' | 'working') => {+ const tally = tallyFor(scope)++ if (state === 'needs-input') {+ tally.needsInput+++ } else if (state === 'working') {+ tally.working+++ } else {+ tally.unread+++ }+ }++ // Pass 1: loaded rows. The dot state is already resolved per session;+ // stalled/background fold into working exactly like the sidebar's status+ // buckets do.+ const chatRows: readonly SessionInfo[] = [...sessions, ...messaging]++ for (const row of chatRows) {+ if (row.archived) {+ continue+ }++ const dot = dots[row.id]++ if (dot === 'needs-input' || dot === 'working' || dot === 'unread') {+ claimRow(rowScopeOf(row), dot)+ } else if (dot === 'stalled' || dot === 'background') {+ claimRow(rowScopeOf(row), 'working')+ }+ }++ // Pass 2: unlisted live runtimes. A listed conversation is already claimed+ // by its row (under every alias the dot state publishes), so this pass only+ // decides scope for work the row lists cannot see.+ const listedIds = new Set<string>()++ for (const row of [...chatRows, ...cron]) {+ listedIds.add(row.id)++ if (row._lineage_root_id) {+ listedIds.add(row._lineage_root_id)+ }++ if (row._lineage_ids) {+ for (const id of row._lineage_ids) {+ listedIds.add(id)+ }+ }+ }++ for (const [runtimeId, state] of Object.entries(states)) {+ if (!state || (!state.busy && !state.needsInput)) {+ continue+ }++ const storedId = state.storedSessionId ?? runtimeId++ if (listedIds.has(storedId)) {+ continue+ }++ const owner = runtimeSessionOwner(runtimeId)++ if (!owner) {+ continue+ }++ const scope =+ typeof owner === 'string'+ ? profileDotScopeKey(null, owner)+ : profileDotScopeKey(owner.connectionId, owner.profile)++ claimRow(scope, state.needsInput ? 'needs-input' : 'working')+ }++ // Pass 3: persisted unread markers with no loaded row — the sessions of a+ // profile whose rows are not on screen (inactive profile, cold start).+ // The marker bucket is a BARE profile name; attribute it to a gateway scope+ // only when every source that names this profile agrees on which gateway+ // that is.+ const allRows: readonly SessionInfo[] = [...chatRows, ...cron]++ for (const [profile, ids] of Object.entries(markers)) {+ const rowsInProfile = allRows.filter(row => profileKeyOf(row) === profile)++ const unmatched = ids.filter(+ id => !rowsInProfile.some(row => sessionPinId(row) === id || sessionMatchesStoredId(row, id))+ )++ if (!unmatched.length) {+ continue+ }++ const connections = new Set<null | string>()++ for (const row of rowsInProfile) {+ connections.add(row.connection_id?.trim() || null)+ }++ if (profiles.some(entry => normalizeProfileKey(entry.name) === profile)) {+ connections.add(+ activeConnectionId && activeConnectionId !== LOCAL_CONNECTION_ID ? activeConnectionId : null+ )+ }++ for (const agent of roster?.agents ?? []) {+ if (normalizeProfileKey(agent.profile) === profile) {+ connections.add(agent.connectionId)+ }+ }++ if (connections.size !== 1) {+ continue+ }++ const [connectionId] = connections++ tallyFor(profileDotScopeKey(connectionId, profile)).unread += unmatched.length+ }++ const next: Record<string, ProfileDotSummary> = {}++ for (const [scope, tally] of tallies) {+ if (tally.needsInput || tally.working || tally.unread) {+ next[scope] = internSummary(tally.needsInput, tally.working, tally.unread)+ }+ }++ return (prev = stableRecord(prev, next))+ }+)++/** The summary for one rail square's (connection, profile). Absent scope →+ * undefined → the square paints no indicator. */+export const profileDotSummaryFor = (+ byScope: Readonly<Record<string, ProfileDotSummary>>,+ connectionId: null | string | undefined,+ profile: null | string | undefined+): ProfileDotSummary | undefined => byScope[profileDotScopeKey(connectionId, profile)]diff --git a/apps/desktop/src/store/session-states.ts b/apps/desktop/src/store/session-states.tsindex 54df09155ce..1da294e4eb5 100644--- a/apps/desktop/src/store/session-states.ts+++ b/apps/desktop/src/store/session-states.ts@@ -525,17 +525,17 @@ function handleTransition(previous: ClientSessionState | null, next: ClientSessi// producer and a turn that ended while the socket was down would never// earn its dot.if (deferringReconcileUnread) {- unconfirmedReconnectSettles.add(storedId)+ unconfirmedReconnectSettles.set(storedId, runtimeId)return}- lightUnreadCompletion(storedId)+ lightUnreadCompletion(storedId, runtimeId)}}/** Mark a completed turn unread unless the user is already looking at it. */-function lightUnreadCompletion(storedId: string) {+function lightUnreadCompletion(storedId: string, runtimeId?: string) {// FOCUSED, not selected: a session finishing in the tile the user is// watching is already seen, and a tile is never the primary selection.if (storedId === $focusedStoredSessionId.get()) {@@ -550,17 +550,27 @@ function lightUnreadCompletion(storedId: string) {if (Date.now() > lastReadAt) {// Flags the transient atom AND persists a marker, so the green dot- // survives an app restart (see session-unread.ts).- markSessionUnreadFinished(storedId)+ // survives an app restart (see session-unread.ts). The marker's profile+ // bucket comes from the loaded row when there is one; with no row, the+ // socket-proven owner profile keeps a background profile's finish out of+ // the ACTIVE profile's bucket — the per-profile rail unread (#91710)+ // would otherwise light the wrong square.+ const owner = runtimeId ? runtimeSessionOwner(runtimeId) : undefined++ const profileHint =+ typeof owner === 'string' ? owner : typeof owner?.profile === 'string' && owner.profile.trim() ? owner.profile : undefined++ markSessionUnreadFinished(storedId, profileHint)}}/** Stored ids whose busy claim a PRIMARY reconnect reconcile retired without- * any proof the turn ended. The authoritative post-reconnect snapshot settles- * each one: `confirmReconnectSettlesExcept` when the runtime is idle or gone,- * a busy re-assert (stream event or `working` row) when the turn is still- * live. */-const unconfirmedReconnectSettles = new Set<string>()+ * any proof the turn ended — mapped to their runtime id so a later confirm+ * can still consult the socket-proven owner (the unread marker's profile+ * bucket). The authoritative post-reconnect snapshot settles each one:+ * `confirmReconnectSettlesExcept` when the runtime is idle or gone, a busy+ * re-assert (stream event or `working` row) when the turn is still live. */+const unconfirmedReconnectSettles = new Map<string, string>()let deferringReconcileUnread = false/** A fresh authoritative snapshot arrived: every parked completion whose@@ -571,10 +581,10 @@ let deferringReconcileUnread = false* parked completion with no confirm producer must fall back to lighting* rather than never lighting. No-op when nothing is parked. */export function confirmReconnectSettlesExcept(workingStoredIds: ReadonlySet<string>) {- for (const storedId of unconfirmedReconnectSettles) {+ for (const [storedId, runtimeId] of unconfirmedReconnectSettles) {if (!workingStoredIds.has(storedId)) {unconfirmedReconnectSettles.delete(storedId)- lightUnreadCompletion(storedId)+ lightUnreadCompletion(storedId, runtimeId)}}}