Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

fix(relay): sidebar, tab dot and kanban cards show a team tab's agent status

review0d17bd7a04bd
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index a2fa9e536..d4c95366a 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -690,6 +690,7 @@ import {
holdSessionTeardown,
projectIdsBoundToSession,
} from '../session/session'
+import { lookupFromStores } from '../session/agent-status-lookup'
import {
openRelayTab,
handleRelayDrop,
@@ -10748,8 +10749,9 @@ export function Canvas() {
/**
* "Go to next agent needing you" (`node.nextNeedingYou`, ⌘K): one chord to a waiting agent in
* another project. The queue is built ON DEMAND from `getState()` reads — Canvas never
- * subscribes to the status store's `byId` (every working/waiting flip would re-render the whole
- * canvas; see StatusAwareMiniMap). The cycle
+ * subscribes to a status store's `byId` (every working/waiting flip would re-render the whole
+ * canvas; see StatusAwareMiniMap). Each project's rows are read from ITS session's store
+ * (`lookupFromStores`), so a team tab's waiting agent is in the queue too. The cycle
* cursor is memory only: a restart starts again at the oldest wait, which is the right answer.
* Travel is `travelToNodeRef` (declared above this point; the callback itself is defined much
* further down) so a closed-project hop keeps travelToNode's hosted-team reopen guard.
@@ -10771,7 +10773,7 @@ export function Canvas() {
color: n.data.color ?? '#888'
}))
: null
- return [projects, live, active, useAgentStatus.getState().byId] as const
+ return [projects, live, active, lookupFromStores(projects.map((p) => p.id))] as const
}, [nodesRef, nodesProjectIdRef])
const needsYouQueueNow = useCallback((): string[] => needsYouQueue(...needsYouInputs()), [needsYouInputs])
const goToNextNeedingYou = useCallback((): void => {
diff --git a/src/renderer/components/AccountChip.tsx b/src/renderer/components/AccountChip.tsx
index 91937b54a..01a0ec8f7 100644
--- a/src/renderer/components/AccountChip.tsx
+++ b/src/renderer/components/AccountChip.tsx
@@ -1,7 +1,7 @@
import { useEffect, useMemo } from 'react'
import type { ObservedClaudeAccount } from '@shared/types'
import { accountChipFor, accountKey, hasMultipleAccountKeys, type AccountChipInfo } from '../lib/accountChip'
-import { useAgentStatus } from '../state/agentStatus'
+import { useAgentStatus, type AgentStatusSession } from '../state/agentStatus'
import { useSettings } from '../state/settings'
import { useSystemAccount } from '../state/systemAccount'
@@ -39,15 +39,18 @@ export function AccountChip({
* the system account with only one identity in play is the unremarkable case, and a chip on every
* pane would say nothing.
*
- * Reads the DEFAULT agent-status store on purpose: it is the store Canvas's `agent:status`
- * listener writes and the store every one of these surfaces already reads its `status` from, so
- * the chip cannot disagree with the RUNNING/unread badges beside it.
+ * Reads the SAME agent-status store the surface reads its `status` from (`statusStore`; absent =
+ * the default store, which Canvas's `agent:status` listener writes), so the chip cannot disagree
+ * with the RUNNING/unread badges beside it — a team tab's node passes its relay session's store.
*/
export function useAccountChip(
/** The node's creation-time account (`data.accountId`) — absent for a plain terminal. */
dataAccountId: string | undefined,
/** What this node's session was observed running as (agent-status `account`). */
- observed: ObservedClaudeAccount | undefined
+ observed: ObservedClaudeAccount | undefined,
+ /** The agent-status store of the session the node's project belongs to. Absent = the default
+ * store. */
+ statusStore?: AgentStatusSession['store']
): AccountChipInfo | null {
const accounts = useSettings((s) => s.settings.claudeAccounts)
const systemLabel = useSettings((s) => s.settings.systemAccountLabel)
@@ -57,7 +60,7 @@ export function useAccountChip(
// event of every node. `hasMultipleAccountKeys` early-exits at the second key. `accounts` rides
// along so a dir that was linked since its observation counts as ONE identity with the account
// it now belongs to, not two.
- const multiple = useAgentStatus((s) => hasMultipleAccountKeys(s.byId, dataAccountId, accounts))
+ const multiple = (statusStore ?? useAgentStatus)((s) => hasMultipleAccountKeys(s.byId, dataAccountId, accounts))
// The system account's email is looked up lazily and only when something will show it — a node
// whose account is entirely unknown renders no chip, so it must not trigger the fetch.
const known = accountKey(dataAccountId, observed, accounts) !== null
diff --git a/src/renderer/components/LiveLinkChip.surfaces.test.tsx b/src/renderer/components/LiveLinkChip.surfaces.test.tsx
index 1aa514a54..65fe4e7b3 100644
--- a/src/renderer/components/LiveLinkChip.surfaces.test.tsx
+++ b/src/renderer/components/LiveLinkChip.surfaces.test.tsx
@@ -19,10 +19,18 @@ import { SessionRow } from './SessionRow'
import type { KanbanSession } from './kanban/KanbanView'
import type { SessionRowVM } from '../lib/sessionList'
-vi.mock('../session/session', () => ({
- useSession: () => ({ api: { pty: {}, shell: { openExternal: vi.fn(async () => {}) } } }),
- sessionForProject: () => ({ source: 'local', api: {} })
-}))
+vi.mock('../session/session', async () => {
+ // The agent-status reads now resolve a store per project / per session (bug D, covered in
+ // session/agent-status-lookup.test.tsx). Here every one answers the default store, as before.
+ const { defaultAgentStatus } = await import('../state/agentStatus')
+ return {
+ useSession: () => ({ api: { pty: {}, shell: { openExternal: vi.fn(async () => {}) } } }),
+ sessionForProject: () => ({ source: 'local', api: {} }),
+ agentStatusForProject: () => defaultAgentStatus,
+ useSessionRegistryVersion: () => 0,
+ useSessionStores: () => ({ agentStatus: defaultAgentStatus })
+ }
+})
vi.mock('./kanban/BoardLogPanel', () => ({ BoardLogPanel: () => null }))
vi.mock('./ContextMeter', () => ({ ContextMeter: () => null }))
vi.mock('./kanban/ModalTerminal', () => ({ ModalTerminal: () => <div className="kanban-modal__term" /> }))
diff --git a/src/renderer/components/SessionsSidebar.tsx b/src/renderer/components/SessionsSidebar.tsx
index d3e1c93b4..65518ac7c 100644
--- a/src/renderer/components/SessionsSidebar.tsx
+++ b/src/renderer/components/SessionsSidebar.tsx
@@ -27,7 +27,7 @@ import { ClosedHistorySection } from './ClosedHistorySection'
import { IconBellFilled, IconCircleCheck, IconClose, IconPin } from './icons'
import { useProjects } from '../state/projects'
import { useSettings } from '../state/settings'
-import { useAgentStatus } from '../state/agentStatus'
+import { useAgentStatusLookup } from '../session/agent-status-lookup'
import { useSessionNaming } from '../state/sessionNaming'
import { ProjectBranch } from './ProjectBranch'
import { useDragAutoScroll } from '../lib/dragAutoScroll'
@@ -146,7 +146,10 @@ export function SessionsSidebar(props: SessionsSidebarProps): JSX.Element | null
// Closed projects are hidden from the tab bar; hide them from the sidebar too.
const projects = useMemo(() => allProjects.filter((p) => !p.closed), [allProjects])
const activeProjectId = useProjects((s) => s.activeProjectId)
- const statusById = useAgentStatus((s) => s.byId)
+ // Each row's status is read through ITS project's session store (a team tab's agents live in its
+ // relay session's store, and share node ids with the handed-off SSH project it serves).
+ const projectIds = useMemo(() => projects.map((p) => p.id), [projects])
+ const statusFor = useAgentStatusLookup(projectIds)
const namingById = useSessionNaming((s) => s.byId)
const [filter, setFilter] = useState('')
@@ -186,17 +189,17 @@ export function SessionsSidebar(props: SessionsSidebarProps): JSX.Element | null
// case), and the O(projects × nodes) rebuild re-ran on every agent hook event otherwise.
const groups = useMemo(
() =>
- open ? buildSessionList(projects, liveActiveNodes, activeProjectId, statusById, filter) : [],
- [open, projects, liveActiveNodes, activeProjectId, statusById, filter]
+ open ? buildSessionList(projects, liveActiveNodes, activeProjectId, statusFor, filter) : [],
+ [open, projects, liveActiveNodes, activeProjectId, statusFor, filter]
)
// Status-grouped sections (only computed in status mode — flattens all projects' sessions by
// live agent status so attention floats to the top). Same inputs as `groups`.
const statusSections = useMemo(
() =>
open && grouping === 'status'
- ? buildStatusList(projects, liveActiveNodes, activeProjectId, statusById, filter)
+ ? buildStatusList(projects, liveActiveNodes, activeProjectId, statusFor, filter)
: [],
- [open, grouping, projects, liveActiveNodes, activeProjectId, statusById, filter]
+ [open, grouping, projects, liveActiveNodes, activeProjectId, statusFor, filter]
)
/**
* The list came back with nothing in it — in EITHER grouping mode. "Nothing here" and "nothing
diff --git a/src/renderer/components/TabBar.tsx b/src/renderer/components/TabBar.tsx
index b7ce078a8..35b0eff2e 100644
--- a/src/renderer/components/TabBar.tsx
+++ b/src/renderer/components/TabBar.tsx
@@ -2,8 +2,7 @@ import { useEffect, useMemo, useRef, useState, type DragEvent } from 'react'
import { createPortal } from 'react-dom'
import { useProjects } from '../state/projects'
import { isOmniKanbanEnabled, toggleBoardView, useViewMode, viewFor } from '../state/viewMode'
-import { useAgentStatus } from '../state/agentStatus'
-import { unreadIdSet, unreadIdsSig } from '../lib/unreadBadge'
+import { useAgentStatusSig, type AgentStatusLookup } from '../session/agent-status-lookup'
import { usePauseCounts } from '../state/pauseCounts'
import { useSettings } from '../state/settings'
import { accountsForProject, sshAccountsHint, systemAccountDisplay } from '../state/workspace'
@@ -72,6 +71,44 @@ interface TabBarProps {
onResumeAllProject: (id: string) => void
}
+/**
+ * The unread count of every project that has one, as ONE primitive — the tab dots' selector shape,
+ * so a working/waiting flip of any agent does not re-render the tab bar. Each node is asked through
+ * ITS project (`lookup(project.id, node.id)`): a team tab's unread lives in its relay session's
+ * store, and its node ids are the handed-off SSH project's too, so counting one store for every tab
+ * put one project's dot on the other's tab. Written with `JSON.stringify` (`[[projectId, count]…]`),
+ * never a raw join — ids come from git-shared, hand-editable project files. `''` when nothing is
+ * unread. Counts `p.nodes` entries, exactly as the dot always did.
+ */
+export function unreadSigFor(
+ projects: readonly { id: string; nodes: readonly { id: string }[] }[],
+ lookup: AgentStatusLookup
+): string {
+ const entries: Array<[string, number]> = []
+ for (const p of projects) {
+ let count = 0
+ for (const n of p.nodes) if (lookup(p.id, n.id)?.unread) count++
+ if (count > 0) entries.push([p.id, count])
+ }
+ return entries.length ? JSON.stringify(entries) : ''
+}
+
+/** Parse `unreadSigFor` back into projectId → unread count (projects with none are absent). */
+export function parseUnreadSig(sig: string): ReadonlyMap<string, number> {
+ const out = new Map<string, number>()
+ if (!sig) return out
+ try {
+ const entries: unknown = JSON.parse(sig)
+ if (!Array.isArray(entries)) return out
+ for (const e of entries) {
+ if (Array.isArray(e) && typeof e[0] === 'string' && typeof e[1] === 'number') out.set(e[0], e[1])
+ }
+ } catch {
+ /* our own output; an unparseable one reads as nothing unread */
+ }
+ return out
+}
+
/**
* The runtime session dimension of a tab (which core the project lives on). Rendered ONLY when
* more than one session exists, `sessionCount()` is 1 for a solo user today, so this never
@@ -125,10 +162,12 @@ export function TabBar({
const perProjectKanban = useViewMode((s) => !!activeId && viewFor(s, activeId) === 'kanban')
const kanbanActive = isGlobal || perProjectKanban
const highlightedId = useViewMode((s) => s.highlightedSwimlaneId)
- // Unread dots need only the unread id set — subscribing to the whole status map re-rendered
- // the TabBar on every working/waiting flip of any agent. Primitive signature → rare updates.
- const unreadIds = useAgentStatus((s) => unreadIdsSig(s.byId))
- const unreadSet = useMemo(() => unreadIdSet(unreadIds), [unreadIds])
+ // Unread dots need only each tab's unread count — subscribing to the whole status map re-rendered
+ // the TabBar on every working/waiting flip of any agent. Primitive signature → rare updates. Each
+ // tab counts from ITS project's session store (`unreadSigFor`).
+ const projectIds = useMemo(() => projects.map((p) => p.id), [projects])
+ const unreadSig = useAgentStatusSig(projectIds, (lookup) => unreadSigFor(projects, lookup))
+ const unreadCounts = useMemo(() => parseUnreadSig(unreadSig), [unreadSig])
// ⏸ badge + the "Cancel pending pauses" row. Computed HERE, not in Canvas: this component
// already holds the projects array, and Canvas subscribing to it would re-render the whole canvas
// on every node serialization.
@@ -365,7 +404,7 @@ export function TabBar({
{projects.map((p) => {
const active = isGlobal ? (highlightedId ? p.id === highlightedId : p.id === activeId) : p.id === activeId
const swimlaneHighlight = isGlobal && p.id === highlightedId
- const unreadCount = p.nodes.filter((n) => unreadSet.has(n.id)).length
+ const unreadCount = unreadCounts.get(p.id) ?? 0
return (
<div
key={p.id}
diff --git a/src/renderer/components/TeamProgressChip.tsx b/src/renderer/components/TeamProgressChip.tsx
index 18a0a9606..aa2643221 100644
--- a/src/renderer/components/TeamProgressChip.tsx
+++ b/src/renderer/components/TeamProgressChip.tsx
@@ -1,5 +1,5 @@
import { memo, useState } from 'react'
-import { useAgentStatus } from '../state/agentStatus'
+import { useAgentStatus, type AgentStatusSession } from '../state/agentStatus'
import {
parseTeamProgressSig,
STATION_LABEL,
@@ -20,19 +20,26 @@ const RING_C = 2 * Math.PI * RING_R
* to that node.
*
* It subscribes to a primitive signature of its OWN stations' states (`teamProgressSig`), never to
- * the whole status map, so a hook event elsewhere on the canvas re-renders nothing here.
+ * the whole status map, so a hook event elsewhere on the canvas re-renders nothing here. The map is
+ * the host surface's session store (`statusStore`): a team tab's stations report into its relay
+ * session's store, and share node ids with the handed-off SSH project, so the default store would
+ * count that project's stations.
*/
export const TeamProgressChip = memo(function TeamProgressChip({
stations,
onTravel,
- menuZIndex = 70
+ menuZIndex = 70,
+ statusStore
}: {
stations: readonly TeamStation[]
onTravel: (nodeId: string) => void
/** Above the host surface: the card modal's scrim sits at 55. */
menuZIndex?: number
+ /** The agent-status store of the session the host node's project belongs to. Absent = the
+ * default store. */
+ statusStore?: AgentStatusSession['store']
}): React.JSX.Element | null {
- const sig = useAgentStatus((s) => teamProgressSig(s.byId, stations))
+ const sig = (statusStore ?? useAgentStatus)((s) => teamProgressSig(s.byId, stations))
const [menu, setMenu] = useState<{ x: number; y: number } | null>(null)
if (stations.length === 0) return null
const kinds = parseTeamProgressSig(sig)
diff --git a/src/renderer/components/kanban/CardModal.actions.test.tsx b/src/renderer/components/kanban/CardModal.actions.test.tsx
index 789f71453..163adca0b 100644
--- a/src/renderer/components/kanban/CardModal.actions.test.tsx
+++ b/src/renderer/components/kanban/CardModal.actions.test.tsx
@@ -13,9 +13,17 @@ import type { KanbanSession } from './KanbanView'
import type { MenuItem } from '../ContextMenu'
const generateName = vi.fn()
-vi.mock('../../session/session', () => ({
- useSession: () => ({ api: { pty: { generateName }, shell: { openExternal: vi.fn() } } })
-}))
+vi.mock('../../session/session', async () => {
+ // The agent-status reads now resolve a store per project / per session (bug D, covered in
+ // session/agent-status-lookup.test.tsx). Here every one answers the default store, as before.
+ const { defaultAgentStatus } = await import('../../state/agentStatus')
+ return {
+ useSession: () => ({ api: { pty: { generateName }, shell: { openExternal: vi.fn() } } }),
+ agentStatusForProject: () => defaultAgentStatus,
+ useSessionRegistryVersion: () => 0,
+ useSessionStores: () => ({ agentStatus: defaultAgentStatus })
+ }
+})
vi.mock('./BoardLogPanel', () => ({ BoardLogPanel: () => null }))
vi.mock('./CardMetaBar', () => ({ CardMetaBar: () => null }))
vi.mock('../ContextMeter', () => ({ ContextMeter: () => null }))
diff --git a/src/renderer/components/kanban/CardModal.liveChatEscape.test.tsx b/src/renderer/components/kanban/CardModal.liveChatEscape.test.tsx
index d2f6c5174..05afbdccd 100644
--- a/src/renderer/components/kanban/CardModal.liveChatEscape.test.tsx
+++ b/src/renderer/components/kanban/CardModal.liveChatEscape.test.tsx
@@ -17,9 +17,17 @@ import { useWatchLinks } from '../../state/watchLinks'
import { CardModal } from './CardModal'
import type { KanbanSession } from './KanbanView'
-vi.mock('../../session/session', () => ({
- useSession: () => ({ api: { pty: {}, shell: {} } })
-}))
+vi.mock('../../session/session', async () => {
+ // The agent-status reads now resolve a store per project / per session (bug D, covered in
+ // session/agent-status-lookup.test.tsx). Here every one answers the default store, as before.
+ const { defaultAgentStatus } = await import('../../state/agentStatus')
+ return {
+ useSession: () => ({ api: { pty: {}, shell: {} } }),
+ agentStatusForProject: () => defaultAgentStatus,
+ useSessionRegistryVersion: () => 0,
+ useSessionStores: () => ({ agentStatus: defaultAgentStatus })
+ }
+})
vi.mock('./BoardLogPanel', () => ({ BoardLogPanel: () => <textarea className="board-log__composer" /> }))
vi.mock('./CardMetaBar', () => ({ CardMetaBar: () => null }))
vi.mock('../ContextMeter', () => ({ ContextMeter: () => null }))
diff --git a/src/renderer/components/kanban/CardModal.liveLink.test.tsx b/src/renderer/components/kanban/CardModal.liveLink.test.tsx
index 740b86b02..79953e30f 100644
--- a/src/renderer/components/kanban/CardModal.liveLink.test.tsx
+++ b/src/renderer/components/kanban/CardModal.liveLink.test.tsx
@@ -14,10 +14,18 @@ import { CardModal } from './CardModal'
import type { KanbanSession } from './KanbanView'
const flags = vi.hoisted(() => ({ browser: false, relayProjects: new Set<string>() }))
-vi.mock('../../session/session', () => ({
- useSession: () => ({ api: { pty: {}, shell: { openExternal: vi.fn(async () => {}) } } }),
- sessionForProject: (id: string) => ({ source: flags.relayProjects.has(id) ? 'relay' : 'local', api: {} })
-}))
+vi.mock('../../session/session', async () => {
+ // The agent-status reads now resolve a store per project / per session (bug D, covered in
+ // session/agent-status-lookup.test.tsx). Here every one answers the default store, as before.
+ const { defaultAgentStatus } = await import('../../state/agentStatus')
+ return {
+ useSession: () => ({ api: { pty: {}, shell: { openExternal: vi.fn(async () => {}) } } }),
+ sessionForProject: (id: string) => ({ source: flags.relayProjects.has(id) ? 'relay' : 'local', api: {} }),
+ agentStatusForProject: () => defaultAgentStatus,
+ useSessionRegistryVersion: () => 0,
+ useSessionStores: () => ({ agentStatus: defaultAgentStatus })
+ }
+})
vi.mock('@renderer/bridge/runtime', () => ({ isBrowserRuntime: () => flags.browser }))
vi.mock('./BoardLogPanel', () => ({ BoardLogPanel: () => null }))
vi.mock('../ContextMeter', () => ({ ContextMeter: () => null }))
diff --git a/src/renderer/components/kanban/CardModal.mentionEscape.test.tsx b/src/renderer/components/kanban/CardModal.mentionEscape.test.tsx
index d6dd82017..afd25d55e 100644
--- a/src/renderer/components/kanban/CardModal.mentionEscape.test.tsx
+++ b/src/renderer/components/kanban/CardModal.mentionEscape.test.tsx
@@ -14,9 +14,17 @@ import type { KanbanSession } from './KanbanView'
const picker = vi.hoisted(() => ({ open: true }))
-vi.mock('../../session/session', () => ({
- useSession: () => ({ api: { pty: {}, shell: {} } })
-}))
+vi.mock('../../session/session', async () => {
+ // The agent-status reads now resolve a store per project / per session (bug D, covered in
+ // session/agent-status-lookup.test.tsx). Here every one answers the default store, as before.
+ const { defaultAgentStatus } = await import('../../state/agentStatus')
+ return {
+ useSession: () => ({ api: { pty: {}, shell: {} } }),
+ agentStatusForProject: () => defaultAgentStatus,
+ useSessionRegistryVersion: () => 0,
+ useSessionStores: () => ({ agentStatus: defaultAgentStatus })
+ }
+})
vi.mock('./BoardLogPanel', () => ({
BoardLogPanel: () => (
<textarea className="board-log__composer" aria-expanded={picker.open ? true : undefined} />
diff --git a/src/renderer/components/kanban/CardModal.teamProgress.test.tsx b/src/renderer/components/kanban/CardModal.teamProgress.test.tsx
index 0bec7dc00..3b66df568 100644
--- a/src/renderer/components/kanban/CardModal.teamProgress.test.tsx
+++ b/src/renderer/components/kanban/CardModal.teamProgress.test.tsx
@@ -12,9 +12,17 @@ import { CardModal } from './CardModal'
import type { KanbanSession } from './KanbanView'
import type { TeamStation } from '../../lib/teamProgress'
-vi.mock('../../session/session', () => ({
- useSession: () => ({ api: { pty: {}, shell: { openExternal: vi.fn(async () => {}) } } })
-}))
+vi.mock('../../session/session', async () => {
+ // The agent-status reads now resolve a store per project / per session (bug D, covered in
+ // session/agent-status-lookup.test.tsx). Here every one answers the default store, as before.
+ const { defaultAgentStatus } = await import('../../state/agentStatus')
+ return {
+ useSession: () => ({ api: { pty: {}, shell: { openExternal: vi.fn(async () => {}) } } }),
+ agentStatusForProject: () => defaultAgentStatus,
+ useSessionRegistryVersion: () => 0,
+ useSessionStores: () => ({ agentStatus: defaultAgentStatus })
+ }
+})
vi.mock('./BoardLogPanel', () => ({ BoardLogPanel: () => null }))
vi.mock('../ContextMeter', () => ({ ContextMeter: () => null }))
vi.mock('./ModalTerminal', () => ({ ModalTerminal: () => <div className="kanban-modal__term" /> }))
diff --git a/src/renderer/components/kanban/CardModal.test.tsx b/src/renderer/components/kanban/CardModal.test.tsx
index 3bdae1059..7abe0d4ab 100644
--- a/src/renderer/components/kanban/CardModal.test.tsx
+++ b/src/renderer/components/kanban/CardModal.test.tsx
@@ -8,14 +8,22 @@ import { useAgentStatus } from '../../state/agentStatus'
import { CardModal } from './CardModal'
import type { KanbanSession } from './KanbanView'
-vi.mock('../../session/session', () => ({
- useSession: () => ({
- api: {
- pty: { generateName: vi.fn(async () => ({ ok: true, message: 'AI Name' })) },
- shell: { openExternal: vi.fn(async () => {}) }
- }
- })
-}))
+vi.mock('../../session/session', async () => {
+ // The agent-status reads now resolve a store per project / per session (bug D, covered in
+ // session/agent-status-lookup.test.tsx). Here every one answers the default store, as before.
+ const { defaultAgentStatus } = await import('../../state/agentStatus')
+ return {
+ useSession: () => ({
+ api: {
+ pty: { generateName: vi.fn(async () => ({ ok: true, message: 'AI Name' })) },
+ shell: { openExternal: vi.fn(async () => {}) }
+ }
+ }),
+ agentStatusForProject: () => defaultAgentStatus,
+ useSessionRegistryVersion: () => 0,
+ useSessionStores: () => ({ agentStatus: defaultAgentStatus })
+ }
+})
// Stub non-terminal/non-browser child panels so CardModal tests run in isolation without store/context dependencies
vi.mock('./BoardLogPanel', () => ({
diff --git a/src/renderer/components/kanban/CardModal.tsx b/src/renderer/components/kanban/CardModal.tsx
index b5c0ab671..5b875c820 100644
--- a/src/renderer/components/kanban/CardModal.tsx
+++ b/src/renderer/components/kanban/CardModal.tsx
@@ -37,7 +37,6 @@ import { useProjects } from '../../state/projects'
import type { TeamStation } from '../../lib/teamProgress'
import { sessionNameRepeatsTitle } from '../../lib/cardRedundancy'
import type { IssueRef } from '@shared/github-issue-ref'
-import { useAgentStatus } from '../../state/agentStatus'
import { useSessionNaming } from '../../state/sessionNaming'
import { useCardPanel } from '../../state/cardPanel'
import {
@@ -48,7 +47,7 @@ import {
CARD_MODAL_MIN_W,
CARD_MODAL_MIN_H
} from '../../state/cardModalSize'
-import { useSession } from '../../session/session'
+import { useSession, useSessionStores } from '../../session/session'
// The same wake trigger the canvas node's SLEEPING/PAUSED chip and mount/visibility auto-wakes
// use — NOT a bespoke resume path, so a click here gets the same WakeInputBuffer protection and
// retries. Importing one function out of the canvas node module is safe: TerminalNode.tsx already
@@ -179,21 +178,25 @@ export function CardModal({ session, projectId, projectName, projectColor, colum
// Sticky body: rendered markdown until clicked, the plain textarea while editing (mirrors
// StickyNode's toggle, so the canvas and the card can't disagree about how a note reads).
const [editingNote, setEditingNote] = useState(false)
- const agentSessionId = useAgentStatus((st) => st.byId[session.id]?.sessionId)
- const observedAgentId = useAgentStatus((st) => st.byId[session.id]?.agentId)
- const paused = useAgentStatus((st) => !!st.byId[session.id]?.paused)
- const dropped = useAgentStatus((st) => !!st.byId[session.id]?.dropped)
- const hibernated = useAgentStatus((st) => !!st.byId[session.id]?.hibernated)
- const wakeBlocked = useAgentStatus((st) => st.byId[session.id]?.wakeBlocked)
+ // The agent status of the session this card's PROJECT runs under (the board mounts the modal
+ // through `ProjectSessionScope`): a team tab's card reads its relay session's store, never the
+ // default one, which holds the handed-off SSH project's entry under the same node id.
+ const agentStatusStore = useSessionStores().agentStatus.store
+ const agentSessionId = agentStatusStore((st) => st.byId[session.id]?.sessionId)
+ const observedAgentId = agentStatusStore((st) => st.byId[session.id]?.agentId)
+ const paused = agentStatusStore((st) => !!st.byId[session.id]?.paused)
+ const dropped = agentStatusStore((st) => !!st.byId[session.id]?.dropped)
+ const hibernated = agentStatusStore((st) => !!st.byId[session.id]?.hibernated)
+ const wakeBlocked = agentStatusStore((st) => st.byId[session.id]?.wakeBlocked)
// Same chip as the card and the canvas node header — the modal is where a user checks WHICH
// session this is, so the account belongs in its header chips, not only two views away.
- const observedAccount = useAgentStatus((st) => st.byId[session.id]?.account)
+ const observedAccount = agentStatusStore((st) => st.byId[session.id]?.account)
// The session name, where it is not already the title (lib/cardRedundancy — the rule the card
// and the canvas node header use). The card carries it on its detail line; the modal, which
// hides the node, carries it here so the session's name is never two views away.
- const sessionName = useAgentStatus((st) => st.byId[session.id]?.session)
+ const sessionName = agentStatusStore((st) => st.byId[session.id]?.session)
const portsRemote = useProjects((s) => !!(portsProjectId && s.getProject(portsProjectId)?.ssh))
- const accountChip = useAccountChip(session.spawn.accountId, observedAccount)
+ const accountChip = useAccountChip(session.spawn.accountId, observedAccount, agentStatusStore)
const [naming, setNaming] = useState(false)
// The board funnel's progress for this node (`onAiName`), shared with the card menu's row.
const funnelNaming = useSessionNaming((st) => !!st.byId[session.id])
@@ -526,7 +529,7 @@ export function CardModal({ session, projectId, projectName, projectColor, colum
<span className="kanban-modal__column" title={columnTitle ?? 'Ungrouped'}>{columnTitle ?? 'Ungrouped'}</span>
</div>
{isTerminal && onOpenIssue && <IssueRefChip issueRef={session.issueRef} onOpen={onOpenIssue} />}
- {isTerminal && team && team.length > 0 && onTravel && <TeamProgressChip stations={team} onTravel={onTravel} />}
+ {isTerminal && team && team.length > 0 && onTravel && <TeamProgressChip stations={team} onTravel={onTravel} statusStore={agentStatusStore} />}
{isTerminal && session.pendingLaunch && (
<QueuedLaunchChip nodeId={session.id} pending={session.pendingLaunch} firstOpen={session.launchFirstOpen} onRun={onRunQueued} />
)}
diff --git a/src/renderer/components/kanban/GlobalKanbanView.live.test.tsx b/src/renderer/components/kanban/GlobalKanbanView.live.test.tsx
index 82dc49c01..9bbb960d5 100644
--- a/src/renderer/components/kanban/GlobalKanbanView.live.test.tsx
+++ b/src/renderer/components/kanban/GlobalKanbanView.live.test.tsx
@@ -21,17 +21,25 @@ import { addColumn, defaultKanban } from '../../lib/kanban'
const localApi = { tag: 'local-api' }
const hostedApi = { tag: 'hosted-api' }
-vi.mock('../../session/session', () => ({
- useSession: () => ({ id: 'local', source: 'local', api: localApi }),
- sessionForProject: (projectId: string) =>
- projectId === 'hosted'
- ? { id: 'hosted-session', source: 'relay', api: hostedApi }
- : projectId === 'relay'
- ? { id: 'relay-session', source: 'relay', api: hostedApi }
- : { id: 'local', source: 'local', api: localApi },
- // The card modal's `ProjectSessionScope` provides the lane's session; `useSession` is mocked above.
- SessionProvider: ({ children }: { children: unknown }) => children
-}))
+vi.mock('../../session/session', async () => {
+ // The agent-status reads now resolve a store per project / per session (bug D, covered in
+ // session/agent-status-lookup.test.tsx). Here every one answers the default store, as before.
+ const { defaultAgentStatus } = await import('../../state/agentStatus')
+ return {
+ useSession: () => ({ id: 'local', source: 'local', api: localApi }),
+ sessionForProject: (projectId: string) =>
+ projectId === 'hosted'
+ ? { id: 'hosted-session', source: 'relay', api: hostedApi }
+ : projectId === 'relay'
+ ? { id: 'relay-session', source: 'relay', api: hostedApi }
+ : { id: 'local', source: 'local', api: localApi },
+ // The card modal's `ProjectSessionScope` provides the lane's session; `useSession` is mocked above.
+ SessionProvider: ({ children }: { children: unknown }) => children,
+ agentStatusForProject: () => defaultAgentStatus,
+ useSessionRegistryVersion: () => 0,
+ useSessionStores: () => ({ agentStatus: defaultAgentStatus })
+ }
+})
vi.mock('../../state/hostedTeams', () => ({
isHostedReadOnly: (sessionId: string) => sessionId === 'hosted-session'
}))
diff --git a/src/renderer/components/kanban/GlobalKanbanView.liveLink.test.tsx b/src/renderer/components/kanban/GlobalKanbanView.liveLink.test.tsx
index a9e4a90bb..6513f0189 100644
--- a/src/renderer/components/kanban/GlobalKanbanView.liveLink.test.tsx
+++ b/src/renderer/components/kanban/GlobalKanbanView.liveLink.test.tsx
@@ -16,11 +16,19 @@ import { useViewMode } from '../../state/viewMode'
import { useWatchLinks } from '../../state/watchLinks'
import type { MenuItem } from '../ContextMenu'
-vi.mock('../../session/session', () => ({
- useSession: () => ({ id: 'local', source: 'local', api: {} }),
- sessionForProject: (projectId: string) =>
- projectId === 'relay' ? { id: 'relay-session', source: 'relay', api: {} } : { id: 'local', source: 'local', api: {} }
-}))
+vi.mock('../../session/session', async () => {
+ // The agent-status reads now resolve a store per project / per session (bug D, covered in
+ // session/agent-status-lookup.test.tsx). Here every one answers the default store, as before.
+ const { defaultAgentStatus } = await import('../../state/agentStatus')
+ return {
+ useSession: () => ({ id: 'local', source: 'local', api: {} }),
+ sessionForProject: (projectId: string) =>
+ projectId === 'relay' ? { id: 'relay-session', source: 'relay', api: {} } : { id: 'local', source: 'local', api: {} },
+ agentStatusForProject: () => defaultAgentStatus,
+ useSessionRegistryVersion: () => 0,
+ useSessionStores: () => ({ agentStatus: defaultAgentStatus })
+ }
+})
vi.mock('../ContextMeter', () => ({ ContextMeter: () => null }))
vi.mock('./CardModal', () => ({ CardModal: () => null }))
diff --git a/src/renderer/components/kanban/GlobalKanbanView.teamProgress.test.tsx b/src/renderer/components/kanban/GlobalKanbanView.teamProgress.test.tsx
index 7d17844a2..f73a7fc84 100644
--- a/src/renderer/components/kanban/GlobalKanbanView.teamProgress.test.tsx
+++ b/src/renderer/components/kanban/GlobalKanbanView.teamProgress.test.tsx
@@ -10,10 +10,18 @@ import { GlobalKanbanView } from './GlobalKanbanView'
import { useProjects } from '../../state/projects'
import { useAgentStatus, type AgentNodeStatus } from '../../state/agentStatus'
-vi.mock('../../session/session', () => ({
- useSession: () => ({ source: 'local', api: window.nodeTerminal }),
- sessionForProject: () => ({ id: 'local', source: 'local', api: window.nodeTerminal })
-}))
+vi.mock('../../session/session', async () => {
+ // The agent-status reads now resolve a store per project / per session (bug D, covered in
+ // session/agent-status-lookup.test.tsx). Here every one answers the default store, as before.
+ const { defaultAgentStatus } = await import('../../state/agentStatus')
+ return {
+ useSession: () => ({ source: 'local', api: window.nodeTerminal }),
+ sessionForProject: () => ({ id: 'local', source: 'local', api: window.nodeTerminal }),
+ agentStatusForProject: () => defaultAgentStatus,
+ useSessionRegistryVersion: () => 0,
+ useSessionStores: () => ({ agentStatus: defaultAgentStatus })
+ }
+})
vi.mock('../ContextMeter', () => ({ ContextMeter: () => null }))
let root: Root | null = null
diff --git a/src/renderer/components/kanban/GlobalKanbanView.test.tsx b/src/renderer/components/kanban/GlobalKanbanView.test.tsx
index f9f2297e8..65b8c630b 100644
--- a/src/renderer/components/kanban/GlobalKanbanView.test.tsx
+++ b/src/renderer/components/kanban/GlobalKanbanView.test.tsx
@@ -16,7 +16,12 @@ describe('global kanban swimlane collapse wiring', () => {
describe('global kanban card read state', () => {
it('clears the unread dot when a card opens, like the per-project board', () => {
- expect(GLOBAL_KANBAN_SRC).toContain("import { useAgentStatus } from '../../state/agentStatus'")
- expect(GLOBAL_KANBAN_SRC).toContain('if (modalNodeId) useAgentStatus.getState().clearUnread(modalNodeId)')
+ // On the store of the card's own lane project (bug D): a team lane reads its relay session's.
+ expect(GLOBAL_KANBAN_SRC).toContain(
+ "import { agentStatusForProject, sessionForProject, useSessionRegistryVersion } from '../../session/session'"
+ )
+ expect(GLOBAL_KANBAN_SRC).toContain(
+ 'if (modalNodeId) agentStatusForProject(modalProjectId).store.getState().clearUnread(modalNodeId)'
+ )
})
})
diff --git a/src/renderer/components/kanban/GlobalKanbanView.tsx b/src/renderer/components/kanban/GlobalKanbanView.tsx
index 56f8c4b40..5b6b9ecbb 100644
--- a/src/renderer/components/kanban/GlobalKanbanView.tsx
+++ b/src/renderer/components/kanban/GlobalKanbanView.tsx
@@ -3,7 +3,6 @@ import type { BridgeLink, CanvasNodeState, ProjectKanban } from '@shared/types'
import { AGENT_CONFIG, BUILTIN_AGENT_IDS, type AgentId } from '@shared/agents/config'
import { useProjects } from '../../state/projects'
import { useSettings } from '../../state/settings'
-import { useAgentStatus } from '../../state/agentStatus'
import { useBoardWallpaperStyle } from '../../state/wallpaper'
import { AerialWallpaper } from '../AerialWallpaper'
import {
@@ -19,7 +18,7 @@ import { createAgentNode, createBrowserNode, createStickyNode, createTerminalNod
import { markCanvasCovered } from '../../lib/canvasCovered'
import { showCanvas, useViewMode } from '../../state/viewMode'
import { KanbanScopeSwitch } from './KanbanScopeSwitch'
-import { sessionForProject } from '../../session/session'
+import { agentStatusForProject, sessionForProject, useSessionRegistryVersion } from '../../session/session'
import { ProjectSessionScope } from '../../session/owning-project'
import { isHostedReadOnly } from '../../state/hostedTeams'
import { activePermissionMode } from '../../state/permissionMode'
@@ -156,6 +155,16 @@ const Swimlane = memo(function Swimlane({
const travel = useCallback((nodeId: string) => onOpenNode(nodeId, projectId), [onOpenNode, projectId])
// Which machine this lane's nodes run on: only a local lane shows this machine's LIVE chips (R57).
const liveLinkSource = projectSessionSource(projectId)
+ // The agent-status store of the session this LANE's project belongs to — a lane is not the
+ // active project, and a team lane's cards read its relay session's store (they share node ids
+ // with the handed-off SSH project, whose entries are the default store's).
+ const registryVersion = useSessionRegistryVersion()
+ const statusStore = useMemo(
+ () => agentStatusForProject(projectId).store,
+ // `registryVersion`: a reconnect swaps the project's session (and its store) under the same id.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ [projectId, registryVersion]
+ )
const sessionIds = useMemo(() => sessions.map(s => s.id), [sessions])
const paletteLabels = useMemo(() => boardLabels(board), [board])
@@ -265,6 +274,7 @@ const Swimlane = memo(function Swimlane({
ports={cardPorts}
onOpenPort={openPort}
onRunQueued={runQueued}
+ statusStore={statusStore}
/>
))
}]
@@ -431,11 +441,14 @@ export const GlobalKanbanView = memo(function GlobalKanbanView({ live = null, on
setModal(nodeId ? { projectId, nodeId, view } : null)
}, [])
const modalNodeId = modal?.nodeId ?? null
- // Same rule as the per-project board: opening a card marks its completion read.
+ const modalProjectId = modal?.projectId ?? null
+ // Same rule as the per-project board: opening a card marks its completion read — on the store of
+ // the card's OWN lane project, so a team lane's read stays on this desktop and never clears the
+ // handed-off SSH project's entry under the same node id.
useEffect(() => {
onModalNodeChange?.(modalNodeId)
- if (modalNodeId) useAgentStatus.getState().clearUnread(modalNodeId)
- }, [modalNodeId, onModalNodeChange])
+ if (modalNodeId) agentStatusForProject(modalProjectId).store.getState().clearUnread(modalNodeId)
+ }, [modalNodeId, modalProjectId, onModalNodeChange])
// Closing the overview with a card open must not leave the node "watched" forever.
const onModalNodeChangeRef = useRef(onModalNodeChange)
onModalNodeChangeRef.current = onModalNodeChange
diff --git a/src/renderer/components/kanban/KanbanView.accountMenu.test.tsx b/src/renderer/components/kanban/KanbanView.accountMenu.test.tsx
index c735dd837..46e200d33 100644
--- a/src/renderer/components/kanban/KanbanView.accountMenu.test.tsx
+++ b/src/renderer/components/kanban/KanbanView.accountMenu.test.tsx
@@ -11,12 +11,20 @@ import { KanbanView, type KanbanSession } from './KanbanView'
import { defaultKanban } from '../../lib/kanban'
import type { MenuItem } from '../ContextMenu'
-vi.mock('../../session/session', () => ({
- useSession: () => ({ source: 'local', api: window.nodeTerminal }),
- // The card modal's `ProjectSessionScope` asks for the card project's session and provides it.
- sessionForProject: () => ({ id: 'local', source: 'local', api: window.nodeTerminal }),
- SessionProvider: ({ children }: { children: unknown }) => children
-}))
+vi.mock('../../session/session', async () => {
+ // The agent-status reads now resolve a store per project / per session (bug D, covered in
+ // session/agent-status-lookup.test.tsx). Here every one answers the default store, as before.
+ const { defaultAgentStatus } = await import('../../state/agentStatus')
+ return {
+ useSession: () => ({ source: 'local', api: window.nodeTerminal }),
+ // The card modal's `ProjectSessionScope` asks for the card project's session and provides it.
+ sessionForProject: () => ({ id: 'local', source: 'local', api: window.nodeTerminal }),
+ SessionProvider: ({ children }: { children: unknown }) => children,
+ agentStatusForProject: () => defaultAgentStatus,
+ useSessionRegistryVersion: () => 0,
+ useSessionStores: () => ({ agentStatus: defaultAgentStatus })
+ }
+})
vi.mock('./CardModal', () => ({
CardModal: (p: { session: { id: string }; initialView?: string; onDelete?: () => void; onSetColor?: (c: string) => void }) => (
<div className="card-modal-mock" data-node={p.session.id} data-view={p.initialView ?? ''}>
diff --git a/src/renderer/components/kanban/KanbanView.category.test.tsx b/src/renderer/components/kanban/KanbanView.category.test.tsx
index 5efca0e0d..3199cbe20 100644
--- a/src/renderer/components/kanban/KanbanView.category.test.tsx
+++ b/src/renderer/components/kanban/KanbanView.category.test.tsx
@@ -10,9 +10,17 @@ import type { ProjectKanban } from '@shared/types'
import { useKanbanDisplay } from '../../state/kanbanDisplay'
import { useProjects } from '../../state/projects'
-vi.mock('../../session/session', () => ({
- useSession: () => ({ source: 'local', api: window.nodeTerminal })
-}))
+vi.mock('../../session/session', async () => {
+ // The agent-status reads now resolve a store per project / per session (bug D, covered in
+ // session/agent-status-lookup.test.tsx). Here every one answers the default store, as before.
+ const { defaultAgentStatus } = await import('../../state/agentStatus')
+ return {
+ useSession: () => ({ source: 'local', api: window.nodeTerminal }),
+ agentStatusForProject: () => defaultAgentStatus,
+ useSessionRegistryVersion: () => 0,
+ useSessionStores: () => ({ agentStatus: defaultAgentStatus })
+ }
+})
let root: Root
let host: HTMLElement
diff --git a/src/renderer/components/kanban/KanbanView.hostile.test.tsx b/src/renderer/components/kanban/KanbanView.hostile.test.tsx
index f19589b2b..70fc6ca11 100644
--- a/src/renderer/components/kanban/KanbanView.hostile.test.tsx
+++ b/src/renderer/components/kanban/KanbanView.hostile.test.tsx
@@ -10,9 +10,17 @@ import type { ProjectKanban } from '@shared/types'
import { useProjects } from '../../state/projects'
import { useAgentStatus } from '../../state/agentStatus'
-vi.mock('../../session/session', () => ({
- useSession: () => ({ source: 'local', api: window.nodeTerminal })
-}))
+vi.mock('../../session/session', async () => {
+ // The agent-status reads now resolve a store per project / per session (bug D, covered in
+ // session/agent-status-lookup.test.tsx). Here every one answers the default store, as before.
+ const { defaultAgentStatus } = await import('../../state/agentStatus')
+ return {
+ useSession: () => ({ source: 'local', api: window.nodeTerminal }),
+ agentStatusForProject: () => defaultAgentStatus,
+ useSessionRegistryVersion: () => 0,
+ useSessionStores: () => ({ agentStatus: defaultAgentStatus })
+ }
+})
let root: Root | null = null
let host: HTMLElement
diff --git a/src/renderer/components/kanban/KanbanView.issueBinding.test.tsx b/src/renderer/components/kanban/KanbanView.issueBinding.test.tsx
index 75f1f22ea..beaede532 100644
--- a/src/renderer/components/kanban/KanbanView.issueBinding.test.tsx
+++ b/src/renderer/components/kanban/KanbanView.issueBinding.test.tsx
@@ -16,9 +16,17 @@ import { useProjects } from '../../state/projects'
import { useViewMode } from '../../state/viewMode'
import { useGitHubIssues } from '../../state/githubIssues'
-vi.mock('../../session/session', () => ({
- useSession: () => ({ source: 'local', api: window.nodeTerminal })
-}))
+vi.mock('../../session/session', async () => {
+ // The agent-status reads now resolve a store per project / per session (bug D, covered in
+ // session/agent-status-lookup.test.tsx). Here every one answers the default store, as before.
+ const { defaultAgentStatus } = await import('../../state/agentStatus')
+ return {
+ useSession: () => ({ source: 'local', api: window.nodeTerminal }),
+ agentStatusForProject: () => defaultAgentStatus,
+ useSessionRegistryVersion: () => 0,
+ useSessionStores: () => ({ agentStatus: defaultAgentStatus })
+ }
+})
const ISSUE: GitHubIssueCardView = {
id: 9001, number: 42, title: 'Parser drops the last line', body: 'body text', state: 'open',
diff --git a/src/renderer/components/kanban/KanbanView.keyboard.test.tsx b/src/renderer/components/kanban/KanbanView.keyboard.test.tsx
index d1954cdf2..57156cb5a 100644
--- a/src/renderer/components/kanban/KanbanView.keyboard.test.tsx
+++ b/src/renderer/components/kanban/KanbanView.keyboard.test.tsx
@@ -12,12 +12,20 @@ import type { ProjectKanban } from '@shared/types'
import { runBoardKey } from '../../lib/boardKeys'
import { popDialog, pushDialog, resetDialogStack } from '../dialog-stack'
-vi.mock('../../session/session', () => ({
- useSession: () => ({ source: 'local', api: window.nodeTerminal }),
- // The card modal's `ProjectSessionScope` asks for the card project's session and provides it.
- sessionForProject: () => ({ id: 'local', source: 'local', api: window.nodeTerminal }),
- SessionProvider: ({ children }: { children: unknown }) => children
-}))
+vi.mock('../../session/session', async () => {
+ // The agent-status reads now resolve a store per project / per session (bug D, covered in
+ // session/agent-status-lookup.test.tsx). Here every one answers the default store, as before.
+ const { defaultAgentStatus } = await import('../../state/agentStatus')
+ return {
+ useSession: () => ({ source: 'local', api: window.nodeTerminal }),
+ // The card modal's `ProjectSessionScope` asks for the card project's session and provides it.
+ sessionForProject: () => ({ id: 'local', source: 'local', api: window.nodeTerminal }),
+ SessionProvider: ({ children }: { children: unknown }) => children,
+ agentStatusForProject: () => defaultAgentStatus,
+ useSessionRegistryVersion: () => 0,
+ useSessionStores: () => ({ agentStatus: defaultAgentStatus })
+ }
+})
// The real modal is exercised by CardModal.test; here it only has to be a dialog on the stack that
// names its card and can close.
diff --git a/src/renderer/components/kanban/KanbanView.placement.test.tsx b/src/renderer/components/kanban/KanbanView.placement.test.tsx
index 0b71aa297..459392f9b 100644
--- a/src/renderer/components/kanban/KanbanView.placement.test.tsx
+++ b/src/renderer/components/kanban/KanbanView.placement.test.tsx
@@ -10,9 +10,17 @@ import { KanbanView, type KanbanSession } from './KanbanView'
import type { ProjectKanban } from '@shared/types'
import { assignedTo } from '../../lib/kanban'
-vi.mock('../../session/session', () => ({
- useSession: () => ({ source: 'local', api: window.nodeTerminal })
-}))
+vi.mock('../../session/session', async () => {
+ // The agent-status reads now resolve a store per project / per session (bug D, covered in
+ // session/agent-status-lookup.test.tsx). Here every one answers the default store, as before.
+ const { defaultAgentStatus } = await import('../../state/agentStatus')
+ return {
+ useSession: () => ({ source: 'local', api: window.nodeTerminal }),
+ agentStatusForProject: () => defaultAgentStatus,
+ useSessionRegistryVersion: () => 0,
+ useSessionStores: () => ({ agentStatus: defaultAgentStatus })
+ }
+})
let root: Root
let host: HTMLElement
diff --git a/src/renderer/components/kanban/KanbanView.statusChips.test.tsx b/src/renderer/components/kanban/KanbanView.statusChips.test.tsx
index 2b92c3085..0059e7ba9 100644
--- a/src/renderer/components/kanban/KanbanView.statusChips.test.tsx
+++ b/src/renderer/components/kanban/KanbanView.statusChips.test.tsx
@@ -10,9 +10,17 @@ import { KanbanView, type KanbanSession } from './KanbanView'
import type { ProjectKanban } from '@shared/types'
import { useAgentStatus } from '../../state/agentStatus'
-vi.mock('../../session/session', () => ({
- useSession: () => ({ source: 'local', api: window.nodeTerminal })
-}))
+vi.mock('../../session/session', async () => {
+ // The agent-status reads now resolve a store per project / per session (bug D, covered in
+ // session/agent-status-lookup.test.tsx). Here every one answers the default store, as before.
+ const { defaultAgentStatus } = await import('../../state/agentStatus')
+ return {
+ useSession: () => ({ source: 'local', api: window.nodeTerminal }),
+ agentStatusForProject: () => defaultAgentStatus,
+ useSessionRegistryVersion: () => 0,
+ useSessionStores: () => ({ agentStatus: defaultAgentStatus })
+ }
+})
let root: Root | null = null
let host: HTMLElement
diff --git a/src/renderer/components/kanban/KanbanView.teamProgress.test.tsx b/src/renderer/components/kanban/KanbanView.teamProgress.test.tsx
index 90e9111ac..9f0c2ecc2 100644
--- a/src/renderer/components/kanban/KanbanView.teamProgress.test.tsx
+++ b/src/renderer/components/kanban/KanbanView.teamProgress.test.tsx
@@ -12,9 +12,17 @@ import { useAgentStatus, type AgentNodeStatus } from '../../state/agentStatus'
import { stationsByOpener, type StationNodeLike } from '../../lib/teamProgress'
import { waitRopeId } from '../../lib/edgeModel'
-vi.mock('../../session/session', () => ({
- useSession: () => ({ source: 'local', api: window.nodeTerminal })
-}))
+vi.mock('../../session/session', async () => {
+ // The agent-status reads now resolve a store per project / per session (bug D, covered in
+ // session/agent-status-lookup.test.tsx). Here every one answers the default store, as before.
+ const { defaultAgentStatus } = await import('../../state/agentStatus')
+ return {
+ useSession: () => ({ source: 'local', api: window.nodeTerminal }),
+ agentStatusForProject: () => defaultAgentStatus,
+ useSessionRegistryVersion: () => 0,
+ useSessionStores: () => ({ agentStatus: defaultAgentStatus })
+ }
+})
vi.mock('../ContextMeter', () => ({ ContextMeter: () => null }))
let root: Root | null = null
diff --git a/src/renderer/components/kanban/KanbanView.tsx b/src/renderer/components/kanban/KanbanView.tsx
index 3e9ea1e42..0ea3675aa 100644
--- a/src/renderer/components/kanban/KanbanView.tsx
+++ b/src/renderer/components/kanban/KanbanView.tsx
@@ -44,8 +44,7 @@ import type { GitHubCloseReason, GitHubIssueCardView } from '@shared/github-issu
import { issueKey, issueRefFromHtmlUrl, issueUrl, type IssueRef } from '@shared/github-issue-ref'
import { NO_ISSUE_RUNS, boundRunsByIssue, type IssueRun } from '../../lib/issueRuns'
import { useGitHubIssues } from '../../state/githubIssues'
-import { useAgentStatus } from '../../state/agentStatus'
-import { useSession } from '../../session/session'
+import { agentStatusForProject, useSession, useSessionRegistryVersion } from '../../session/session'
import { ProjectSessionScope } from '../../session/owning-project'
import { KanbanSourceFilter, type KanbanSource } from './KanbanSourceFilter'
import { GitHubIssueSummaryModal } from './GitHubIssueSummaryModal'
@@ -311,6 +310,17 @@ export const KanbanView = memo(function KanbanView({
// Which machine this board's nodes run on — only a local board shows this machine's LIVE chips
// (R57). A primitive, so the memoized cards are not re-rendered by it.
const liveLinkSource = projectSessionSource(projectId)
+ // The agent-status store of the session this board's PROJECT belongs to: a team tab's cards read
+ // its relay session's store (they share node ids with the handed-off SSH project, whose entries
+ // are the default store's). Every card, the chips' signature and the open card's read mark use it.
+ const registryVersion = useSessionRegistryVersion()
+ const statusStore = useMemo(
+ () => agentStatusForProject(projectId).store,
+ // `registryVersion`: a reconnect swaps the project's session (and so its store) under the same
+ // id, and an unbind sends it to the offline session's; the memo must re-resolve on either.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ [projectId, registryVersion]
+ )
// The card face's Ports chip: this board is always the project on the canvas, which is the one
// the dev-port scanner covers. Stable identities, because SessionCard is memoized.
const portsRemote = useProjects((s) => !!s.getProject(projectId)?.ssh)
@@ -404,9 +414,11 @@ export const KanbanView = memo(function KanbanView({
setLabelFilter((f) => (f.includes(id) ? f.filter((x) => x !== id) : [...f, id]))
// Report the open node to the canvas (dictation shortcut targeting) and mark its completion read.
// This clears notification affordances only; the live `done` state remains waiting for a prompt.
+ // On the board project's own store: a relay card's read stays on this desktop (that store sends
+ // no ack to the host) and never clears the handed-off SSH project's entry under the same id.
useEffect(() => {
onModalNodeChange(modalNodeId)
- if (modalNodeId) useAgentStatus.getState().clearUnread(modalNodeId)
+ if (modalNodeId) statusStore.getState().clearUnread(modalNodeId)
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [modalNodeId])
// Someone asked for a card while the board is up (notch Go, a notification, ⌘K…). Open it here
@@ -579,7 +591,7 @@ export const KanbanView = memo(function KanbanView({
// running / needs-you / unread fact does) — never `byId`, which changes on every hook event of
// every node and would re-render the whole board each time.
const chipCards = useMemo<StatusChipCard[]>(() => sessions.map((s) => ({ id: s.id, kind: s.kind })), [sessions])
- const statusSig = useAgentStatus((st) => statusChipSig(st.byId, chipCards))
+ const statusSig = statusStore((st) => statusChipSig(st.byId, chipCards))
const statusFacts = useMemo(() => parseStatusChipSig(statusSig), [statusSig])
const statusCounts = useMemo(() => chipCounts(statusFacts), [statusFacts])
const toggleStatusChip = (chip: StatusChip): void =>
@@ -962,6 +974,7 @@ export const KanbanView = memo(function KanbanView({
ports={cardPorts}
onOpenPort={openPort}
onRunQueued={onRunQueued}
+ statusStore={statusStore}
/>
))
})
diff --git a/src/renderer/components/kanban/KanbanView.views.test.tsx b/src/renderer/components/kanban/KanbanView.views.test.tsx
index 5051f526a..b22c1d085 100644
--- a/src/renderer/components/kanban/KanbanView.views.test.tsx
+++ b/src/renderer/components/kanban/KanbanView.views.test.tsx
@@ -12,9 +12,17 @@ import { useKanbanDisplay } from '../../state/kanbanDisplay'
import { useProjects } from '../../state/projects'
import { useAgentStatus } from '../../state/agentStatus'
-vi.mock('../../session/session', () => ({
- useSession: () => ({ source: 'local', api: window.nodeTerminal })
-}))
+vi.mock('../../session/session', async () => {
+ // The agent-status reads now resolve a store per project / per session (bug D, covered in
+ // session/agent-status-lookup.test.tsx). Here every one answers the default store, as before.
+ const { defaultAgentStatus } = await import('../../state/agentStatus')
+ return {
+ useSession: () => ({ source: 'local', api: window.nodeTerminal }),
+ agentStatusForProject: () => defaultAgentStatus,
+ useSessionRegistryVersion: () => 0,
+ useSessionStores: () => ({ agentStatus: defaultAgentStatus })
+ }
+})
const prompt = vi.hoisted(() => ({ answer: 'Mine' as string | null }))
vi.mock('../promptDialog', () => ({ promptDialog: vi.fn(async () => prompt.answer) }))
diff --git a/src/renderer/components/kanban/ModalTerminal.tsx b/src/renderer/components/kanban/ModalTerminal.tsx
index 8bd2c85e4..2cedcf6b9 100644
--- a/src/renderer/components/kanban/ModalTerminal.tsx
+++ b/src/renderer/components/kanban/ModalTerminal.tsx
@@ -19,9 +19,8 @@ import { liveProjectJumpTarget } from '../../lib/projectJump'
import { terminalChordBubbles, terminalShortcutPolicy } from '../../lib/keybindingOverrides'
import { focusXtermUnlessCovered, useMdModeFocus } from '../../terminal/useMdModeFocus'
import { FindBar } from '../FindBar'
-import { useAgentStatus } from '../../state/agentStatus'
import { useProjects } from '../../state/projects'
-import { isRemoteProjectId, useSession } from '../../session/session'
+import { isRemoteProjectId, useSession, useSessionStores } from '../../session/session'
import { REMOTE_PROJECT_SPAWN_REFUSAL, spawnBelongsElsewhere, useOwningProjectId } from '../../session/owning-project'
import { isHostedReadOnly } from '../../state/hostedTeams'
import { useSettings } from '../../state/settings'
@@ -160,6 +159,10 @@ export function ModalTerminal({
}: ModalTerminalProps) {
const session = useSession()
const { api } = session
+ // The agent status of the session this card's project runs under (mounted through
+ // `ProjectSessionScope`), never the default store: a team tab's node shares its id with the
+ // handed-off SSH project, whose entry is the default store's.
+ const agentStatusStore = useSessionStores().agentStatus.store
// Read at click time from the lifecycle effect, which runs once per mount.
const projectIdRef = useRef(projectId)
projectIdRef.current = projectId
@@ -206,12 +209,12 @@ export function ModalTerminal({
const sessionIdRef = useRef<string | null>(null)
const fitRef = useRef<FitAddon | null>(null)
const transportRef = useRef<LocalTransport | null>(null)
- const agentSessionId = useAgentStatus((s) => s.byId[nodeId]?.sessionId)
- const observedAgentId = useAgentStatus((s) => s.byId[nodeId]?.agentId)
+ const agentSessionId = agentStatusStore((s) => s.byId[nodeId]?.sessionId)
+ const observedAgentId = agentStatusStore((s) => s.byId[nodeId]?.agentId)
// MIRROR TerminalNode: transcript READS go to the account the session is actually running as,
// which for a plain terminal is only ever the observed one. The spawn below keeps
// `spawn.accountId` — launch identity stays creation-time.
- const observedAccount = useAgentStatus((s) => s.byId[nodeId]?.account)
+ const observedAccount = agentStatusStore((s) => s.byId[nodeId]?.account)
// …resolved against the live account list, so linking the dir repoints the reader at once.
const claudeAccounts = useSettings((s) => s.settings.claudeAccounts)
// MIRROR TerminalNode: the meter's rehydration reads the same session the ⌘M view does.
@@ -713,7 +716,7 @@ export function ModalTerminal({
if (!term || !files.length) return
// Clipboard bytes must be written before they have a path, which is not instant either.
const needsWrite = files.some((f) => !window.nodeTerminal.getPathForFile(f))
- const st = useAgentStatus.getState().byId[nodeId]
+ const st = agentStatusStore.getState().byId[nodeId]
const paneAgent = spawn.agentId ?? st?.agentId
const agentPane = agentProcessInPane(paneAgent, st)
// MIRROR TerminalNode.dropDialectFor: spelled for the core that owns the pane, not this window.
diff --git a/src/renderer/components/kanban/SessionCard.tsx b/src/renderer/components/kanban/SessionCard.tsx
index 4ff476be2..36fde8f70 100644
--- a/src/renderer/components/kanban/SessionCard.tsx
+++ b/src/renderer/components/kanban/SessionCard.tsx
@@ -1,6 +1,6 @@
import { memo, useState } from 'react'
import type { KanbanCardMeta, KanbanColumnCategory, KanbanLabel, KanbanPriority } from '@shared/types'
-import { useAgentStatus } from '../../state/agentStatus'
+import { useAgentStatus, type AgentStatusSession } from '../../state/agentStatus'
import { AccountChip, useAccountChip } from '../AccountChip'
import { LiveLinkChip, showsLiveLinks } from '../LiveLinkChip'
import type { SessionSource } from '../../session/session'
@@ -65,11 +65,18 @@ interface SessionCardProps {
/** ▶ on the card's QUEUED chip: start the node's held launch now (Canvas's `run` path; on a relay
* tab Canvas answers with a "runs on the host" notice instead). Absent = the chip shows without ▶. */
onRunQueued?: (nodeId: string) => void
+ /** The agent-status store of the session the card's PROJECT belongs to
+ * (`agentStatusForProject(projectId).store`, re-resolved by the board on a registry change).
+ * A team tab's card reads its relay session's store; its node id is the handed-off SSH
+ * project's too, so the default store would show that project's state on this card. Absent =
+ * the default store. A stable reference per board (SessionCard is memoized). */
+ statusStore?: AgentStatusSession['store']
}
export const SessionCard = memo(function SessionCard({
session, meta, labels = [], onOpen, onDragStart, onDragEnd, onDropAt, onContext, pulls,
- pullFreshness = 'fresh', onOpenIssue, team, onTravel, columnCategory, liveLinkSource, ports, onOpenPort, onRunQueued
+ pullFreshness = 'fresh', onOpenIssue, team, onTravel, columnCategory, liveLinkSource, ports, onOpenPort, onRunQueued,
+ statusStore
}: SessionCardProps) {
// THIS card's agent status, subscribed per card rather than threaded down from the board.
// KanbanView used to hold `useAgentStatus((s) => s.byId)` and pass the map through the column:
@@ -77,13 +84,13 @@ export const SessionCard = memo(function SessionCard({
// flip re-rendered the whole board — every column, every card. The same rule Canvas follows
// (see its loopSig comment) and StatusAwareMiniMap demonstrates: subscribe where the value is
// read, so the re-render is confined to the one thing that changed.
- const status = useAgentStatus((s) => s.byId[session.id])
+ const status = (statusStore ?? useAgentStatus)((s) => s.byId[session.id])
// The card's meter follows the same session rule as the node and the card modal.
const cardTranscript = transcriptSessionFor({ live: status?.sessionId, persisted: session.spawn.agentSessionId, cwd: session.spawn.cwd })
// The board is the canvas's other view of the same node (CONTRIBUTING), so the card carries the
// node header's account chip from the same helper — created-with account, else what the session
// was observed running as.
- const accountChip = useAccountChip(session.spawn.accountId, status?.account)
+ const accountChip = useAccountChip(session.spawn.accountId, status?.account, statusStore)
// Local drag state only styles THIS card (ghost look) — the drag payload lives in KanbanView.
const [dragging, setDragging] = useState(false)
// Which edge a drag is hovering over → shows the drop line (top = before, bottom = after).
@@ -166,7 +173,7 @@ export const SessionCard = memo(function SessionCard({
<IssueRefChip issueRef={session.issueRef} onOpen={onOpenIssue} />
)}
{session.kind === 'terminal' && team && team.length > 0 && onTravel && (
- <TeamProgressChip stations={team} onTravel={onTravel} />
+ <TeamProgressChip stations={team} onTravel={onTravel} statusStore={statusStore} />
)}
{session.kind === 'terminal' && session.pendingLaunch && (
<QueuedLaunchChip
diff --git a/src/renderer/lib/nextNeedingYou.test.ts b/src/renderer/lib/nextNeedingYou.test.ts
index 27338f458..3a575e829 100644
--- a/src/renderer/lib/nextNeedingYou.test.ts
+++ b/src/renderer/lib/nextNeedingYou.test.ts
@@ -7,6 +7,14 @@ import {
type NeedsYouProject
} from './nextNeedingYou'
import type { AgentNodeStatus } from '../state/agentStatus'
+import type { AgentStatusLookup } from '../session/agent-status-lookup'
+
+// The queue reads status per PROJECT (`buildStatusList`'s lookup). These cases have one store, so
+// a map that ignores the project stands in.
+const lookupFromMap =
+ (byId: Record<string, AgentNodeStatus>): AgentStatusLookup =>
+ (_projectId, nodeId) =>
+ byId[nodeId]
const node = (id: string, title = id) => ({ id, kind: 'terminal' as const, title, color: '#888' })
@@ -32,20 +40,20 @@ describe('needsYouQueue', () => {
c1: st('waiting', 200)
}
// Working, done and unread rows are not "needing you"; the active project is irrelevant to order.
- expect(needsYouQueue(projects(), null, 'p1', status)).toEqual(['b1', 'c1', 'a1'])
- expect(needsYouQueue(projects(), null, 'p3', status)).toEqual(['b1', 'c1', 'a1'])
+ expect(needsYouQueue(projects(), null, 'p1', lookupFromMap(status))).toEqual(['b1', 'c1', 'a1'])
+ expect(needsYouQueue(projects(), null, 'p3', lookupFromMap(status))).toEqual(['b1', 'c1', 'a1'])
})
it('breaks clock ties by project store order, then title, deterministically', () => {
const ps = projects()
ps[0].nodes = [node('a1', 'zeta'), node('a2', 'Alpha')]
const status = { a1: st('waiting', 100), a2: st('waiting', 100), b1: st('waiting', 100) }
- expect(needsYouQueue(ps, null, 'p1', status)).toEqual(['a2', 'a1', 'b1'])
+ expect(needsYouQueue(ps, null, 'p1', lookupFromMap(status))).toEqual(['a2', 'a1', 'b1'])
})
it('sorts a row with no clock last instead of first', () => {
const status = { a1: st('waiting'), b1: st('waiting', 999) }
- expect(needsYouQueue(projects(), null, 'p1', status)).toEqual(['b1', 'a1'])
+ expect(needsYouQueue(projects(), null, 'p1', lookupFromMap(status))).toEqual(['b1', 'a1'])
})
it('matches the sidebar: closed projects are out, an unavailable one cannot be travelled to', () => {
@@ -53,17 +61,17 @@ describe('needsYouQueue', () => {
ps[1].closed = true
ps[2].unavailable = true
const status = { a1: st('waiting', 3), b1: st('waiting', 1), c1: st('waiting', 2) }
- expect(needsYouQueue(ps, null, 'p1', status)).toEqual(['a1'])
+ expect(needsYouQueue(ps, null, 'p1', lookupFromMap(status))).toEqual(['a1'])
})
it('counts a live active-project node that is not committed to the store yet', () => {
const live = [...projects()[0].nodes, node('fresh')]
const status = { fresh: st('blocked', 5), b1: st('waiting', 9) }
- expect(needsYouQueue(projects(), live, 'p1', status)).toEqual(['fresh', 'b1'])
+ expect(needsYouQueue(projects(), live, 'p1', lookupFromMap(status))).toEqual(['fresh', 'b1'])
})
it('is empty when nothing needs the user', () => {
- expect(needsYouQueue(projects(), null, 'p1', { a1: st('working', 1) })).toEqual([])
+ expect(needsYouQueue(projects(), null, 'p1', lookupFromMap({ a1: st('working', 1) }))).toEqual([])
})
})
@@ -108,8 +116,8 @@ describe('after a restart: agents last seen waiting, with nothing reported since
b1: restored('working'),
c1: restored('waiting')
}
- expect(needsYouQueue(projects(), null, 'p1', status)).toEqual([])
- expect(waitingBeforeRestart(projects(), null, 'p1', status)).toBe(3)
+ expect(needsYouQueue(projects(), null, 'p1', lookupFromMap(status))).toEqual([])
+ expect(waitingBeforeRestart(projects(), null, 'p1', lookupFromMap(status))).toBe(3)
})
it('a clock from THIS run, a live state, or a closed project does not count', () => {
@@ -120,7 +128,7 @@ describe('after a restart: agents last seen waiting, with nothing reported since
a2: { ...restored('waiting'), state: 'working', lastEventAt: 9 }, // it reported since
c1: restored('waiting') // its project is closed, like the queue's membership
}
- expect(waitingBeforeRestart(ps, null, 'p1', status)).toBe(0)
+ expect(waitingBeforeRestart(ps, null, 'p1', lookupFromMap(status))).toBe(0)
})
it('says why the queue is empty instead of "no agent is waiting"', () => {
diff --git a/src/renderer/lib/nextNeedingYou.ts b/src/renderer/lib/nextNeedingYou.ts
index 8137d444d..df7cc3213 100644
--- a/src/renderer/lib/nextNeedingYou.ts
+++ b/src/renderer/lib/nextNeedingYou.ts
@@ -2,11 +2,13 @@
// another project, instead of opening the sidebar, finding the project and the row, and clicking.
//
// Pure, so the ordering and the cycle are unit-tested here (vitest runs in the node environment,
-// no jsdom). Canvas calls this ON DEMAND, once per keypress or palette open, reading the stores
-// with `getState()` — it must NEVER subscribe to the status store's `byId` for this: every working/waiting flip
-// would re-render the whole canvas (see `StatusAwareMiniMap`'s header in Canvas.tsx).
+// no jsdom). Canvas calls this ON DEMAND, once per keypress or palette open, with a per-project
+// lookup that reads the stores' current state (`lookupFromStores`) — it must NEVER subscribe to a
+// status store's `byId` for this: every working/waiting flip would re-render the whole canvas (see
+// `StatusAwareMiniMap`'s header in Canvas.tsx). Per project, because a team tab's agents live in
+// its relay session's store, and a node id can be in two projects (bug D).
-import type { AgentNodeStatus } from '../state/agentStatus'
+import type { AgentStatusLookup } from '../session/agent-status-lookup'
import { buildStatusList, type ProjectInput, type SessionNodeInput } from './sessionList'
import { nodeTravel, type TravelProject } from './presenceTravel'
@@ -28,12 +30,12 @@ export function needsYouQueue(
projects: readonly NeedsYouProject[],
liveActiveNodes: SessionNodeInput[] | null,
activeProjectId: string,
- statusById: Record<string, AgentNodeStatus>
+ statusFor: AgentStatusLookup
): string[] {
const open = projects.filter((p) => !p.closed)
const pidx = new Map(open.map((p, i) => [p.id, i]))
const attention =
- buildStatusList(open, liveActiveNodes, activeProjectId, statusById, '').find(
+ buildStatusList(open, liveActiveNodes, activeProjectId, statusFor, '').find(
(s) => s.kind === 'attention'
)?.rows ?? []
return attention
@@ -63,10 +65,10 @@ export function waitingBeforeRestart(
projects: readonly NeedsYouProject[],
liveActiveNodes: SessionNodeInput[] | null,
activeProjectId: string,
- statusById: Record<string, AgentNodeStatus>
+ statusFor: AgentStatusLookup
): number {
const open = projects.filter((p) => !p.closed)
- return buildStatusList(open, liveActiveNodes, activeProjectId, statusById, '')
+ return buildStatusList(open, liveActiveNodes, activeProjectId, statusFor, '')
.flatMap((s) => s.rows)
.filter(
(r) =>
diff --git a/src/renderer/lib/sessionList.test.ts b/src/renderer/lib/sessionList.test.ts
index 413eb8025..cd3a9fd11 100644
--- a/src/renderer/lib/sessionList.test.ts
+++ b/src/renderer/lib/sessionList.test.ts
@@ -19,6 +19,14 @@ import {
type SessionGroup
} from './sessionList'
import type { AgentNodeStatus } from '../state/agentStatus'
+import type { AgentStatusLookup } from '../session/agent-status-lookup'
+
+// The builders ask a per-PROJECT lookup (a node id can be in two projects that read different
+// stores, bug D). Most cases here have one store, so a map that ignores the project stands in.
+const lookupFromMap =
+ (byId: Record<string, AgentNodeStatus>): AgentStatusLookup =>
+ (_projectId, nodeId) =>
+ byId[nodeId]
const node = (id: string, over: Partial<ProjectInput['nodes'][number]> = {}) => ({
id,
@@ -137,13 +145,13 @@ describe('projectHeadClickAction', () => {
describe('buildSessionList', () => {
it('keeps store order (mirrors the tab bar) regardless of which project is active', () => {
- const groups = buildSessionList(projects(), null, 'p2', {}, '')
+ const groups = buildSessionList(projects(), null, 'p2', lookupFromMap({}), '')
expect(groups.map((g) => g.projectId)).toEqual(['p1', 'p2'])
expect(groups.find((g) => g.projectId === 'p2')!.isActive).toBe(true)
})
it('keeps only terminal/agent nodes and flags agents', () => {
- const groups = buildSessionList(projects(), null, 'p1', {}, '')
+ const groups = buildSessionList(projects(), null, 'p1', lookupFromMap({}), '')
const p2 = groups.find((g) => g.projectId === 'p2')!
expect(p2.ungrouped.map((s) => s.id)).toEqual(['t2']) // sticky + editor dropped
const p1 = groups.find((g) => g.projectId === 'p1')!
@@ -155,7 +163,7 @@ describe('buildSessionList', () => {
const status: Record<string, AgentNodeStatus> = {
a1: { unread: true, state: 'working', agentId: 'claude', session: 'fix bug', sessionId: 'sess-1' }
}
- const groups = buildSessionList(projects(), null, 'p1', status, '')
+ const groups = buildSessionList(projects(), null, 'p1', lookupFromMap(status), '')
const a1 = groups[0].ungrouped.find((s) => s.id === 'a1')!
expect(a1.statusKind).toBe('working')
expect(a1.unread).toBe(true)
@@ -166,7 +174,7 @@ describe('buildSessionList', () => {
it('uses live nodes for the active project instead of serialized ones', () => {
const live = [node('t1', { title: 'renamed live' })]
- const groups = buildSessionList(projects(), live, 'p1', {}, '')
+ const groups = buildSessionList(projects(), live, 'p1', lookupFromMap({}), '')
const p1 = groups.find((g) => g.projectId === 'p1')!
expect(p1.ungrouped.map((s) => s.title)).toEqual(['renamed live'])
})
@@ -186,7 +194,7 @@ describe('buildSessionList', () => {
]
}
]
- const [p1] = buildSessionList(proj, null, 'p1', {}, '')
+ const [p1] = buildSessionList(proj, null, 'p1', lookupFromMap({}), '')
expect(p1.groups).toHaveLength(1)
expect(p1.groups[0]).toMatchObject({ id: 'g1', title: 'Frontend', color: '#abc' })
expect(p1.groups[0].sessions.map((s) => s.id)).toEqual(['t1', 't2'])
@@ -207,21 +215,21 @@ describe('buildSessionList', () => {
]
}
]
- const unfiltered = buildSessionList(proj, null, 'p1', {}, '')
+ const unfiltered = buildSessionList(proj, null, 'p1', lookupFromMap({}), '')
expect(unfiltered[0].groups.map((b) => b.id)).toEqual(['g1', 'g2']) // empty g1 kept
- const filtered = buildSessionList(proj, null, 'p1', {}, 'spec')
+ const filtered = buildSessionList(proj, null, 'p1', lookupFromMap({}), 'spec')
expect(filtered[0].groups.map((b) => b.id)).toEqual(['g2']) // empty g1 dropped
expect(filtered[0].groups[0].sessions.map((s) => s.id)).toEqual(['t1'])
})
it('filters by title and session name, hiding empty projects only when filtering', () => {
const status: Record<string, AgentNodeStatus> = { a1: { unread: false, session: 'special' } }
- const filtered = buildSessionList(projects(), null, 'p1', status, 'spec')
+ const filtered = buildSessionList(projects(), null, 'p1', lookupFromMap(status), 'spec')
expect(filtered.map((g) => g.projectId)).toEqual(['p1'])
expect(filtered[0].ungrouped.map((s) => s.id)).toEqual(['a1'])
- const unfiltered = buildSessionList(projects(), null, 'p1', {}, '')
+ const unfiltered = buildSessionList(projects(), null, 'p1', lookupFromMap({}), '')
expect(unfiltered.length).toBe(2) // both projects kept when no filter
})
@@ -244,7 +252,7 @@ describe('buildSessionList', () => {
proj,
null,
'p1',
- { target: { unread: false, state: 'waiting' } },
+ lookupFromMap({ target: { unread: false, state: 'waiting' } }),
''
)
const outer = all.groups[0]
@@ -255,7 +263,7 @@ describe('buildSessionList', () => {
expect(projectSignalCounts(all)).toEqual({ attention: 1, unread: 0, working: 0 })
// Filtering keeps the ancestors of a match — otherwise the hit is unreachable in the tree.
- const [filtered] = buildSessionList(proj, null, 'p1', {}, 'needle')
+ const [filtered] = buildSessionList(proj, null, 'p1', lookupFromMap({}), 'needle')
expect(filtered.groups[0].id).toBe('outer')
expect(filtered.groups[0].children[0].children[0].sessions.map((row) => row.id)).toEqual([
'target'
@@ -275,7 +283,7 @@ describe('buildSessionList', () => {
]
}
]
- const [group] = buildSessionList(proj, null, 'p1', {}, '')
+ const [group] = buildSessionList(proj, null, 'p1', lookupFromMap({}), '')
expect(new Set(group.groups.map((bucket) => bucket.id))).toEqual(
new Set(['dangling', 'a', 'b'])
)
@@ -297,14 +305,14 @@ describe('sidebar disclosure keys', () => {
]
it('lists a key for the project and for every frame at any depth', () => {
- const keys = liveCollapseKeys(buildSessionList(proj, null, 'p1', {}, ''))
+ const keys = liveCollapseKeys(buildSessionList(proj, null, 'p1', lookupFromMap({}), ''))
expect(keys).toEqual(
new Set(['project:p1', 'project:p1:group:outer', 'project:p1:group:inner'])
)
})
it('drops keys whose project or frame is gone, and keeps the key being written', () => {
- const live = liveCollapseKeys(buildSessionList(proj, null, 'p1', {}, ''))
+ const live = liveCollapseKeys(buildSessionList(proj, null, 'p1', lookupFromMap({}), ''))
const stored = {
'project:p1': true,
'project:p1:group:inner': true,
@@ -322,7 +330,7 @@ describe('sidebar disclosure keys', () => {
})
it('returns the same object when there is nothing to prune (no needless settings write)', () => {
- const live = liveCollapseKeys(buildSessionList(proj, null, 'p1', {}, ''))
+ const live = liveCollapseKeys(buildSessionList(proj, null, 'p1', lookupFromMap({}), ''))
const stored = { 'project:p1': true }
expect(pruneCollapsedItems(stored, live)).toBe(stored)
})
@@ -376,7 +384,7 @@ describe('projectSignalCounts', () => {
d: { unread: true },
e: { unread: true, state: 'working' }
}
- const [g] = buildSessionList(proj, null, 'p1', status, '')
+ const [g] = buildSessionList(proj, null, 'p1', lookupFromMap(status), '')
// `e` is the load-bearing one: it is the single working session AND carries an unread mark,
// so it must land in `working` and NOT in `unread`. `c` (done+unread) now counts as unread,
// not attention — the user's call: unread already signals "there's something new here".
@@ -388,7 +396,7 @@ describe('projectSignalCounts', () => {
[{ id: 'p1', name: 'P1', color: '#123', nodes: [node('x')] }],
null,
'p1',
- {},
+ lookupFromMap({}),
''
)
expect(projectSignalCounts(g)).toEqual({ attention: 0, unread: 0, working: 0 })
@@ -427,7 +435,7 @@ describe('projectSignalCounts', () => {
a1: { unread: true, state: 'blocked', agentId: 'claude', session: 'blocked task', sessionId: 'sess-a1' },
a2: { unread: true, state: 'working', agentId: 'claude', session: 'working task', sessionId: 'sess-a2' }
}
- const [p1] = buildSessionList(proj, null, 'p1', status, '')
+ const [p1] = buildSessionList(proj, null, 'p1', lookupFromMap(status), '')
expect(p1.groups[0].sessions.map((s) => s.id)).toEqual(['a1', 'a2']) // sanity: sessions really live under group.groups
expect(projectSignalCounts(p1)).toEqual({ attention: 1, unread: 0, working: 1 })
})
@@ -457,12 +465,12 @@ describe('groupSignalCounts', () => {
}
it('counts the frame whole subtree, nested frames included', () => {
- const [g] = buildSessionList(proj, null, 'p1', status, '')
+ const [g] = buildSessionList(proj, null, 'p1', lookupFromMap(status), '')
expect(groupSignalCounts(g.groups[0])).toEqual({ attention: 1, unread: 0, working: 1 })
})
it('counts only its own subtree, not the rest of the project', () => {
- const [g] = buildSessionList(proj, null, 'p1', status, '')
+ const [g] = buildSessionList(proj, null, 'p1', lookupFromMap(status), '')
// The inner frame sees only c1; the ungrouped t1 belongs to no frame and is the difference
// between the frame totals and the project total.
expect(groupSignalCounts(g.groups[0].children[0])).toEqual({
@@ -484,12 +492,12 @@ describe('groupSignalCounts', () => {
]
// The absence of a working badge is what tells the user the task is waiting for them, so a
// quiet frame must report zeros rather than anything the header could render.
- const [g] = buildSessionList(quiet, null, 'p1', {}, '')
+ const [g] = buildSessionList(quiet, null, 'p1', lookupFromMap({}), '')
expect(groupSignalCounts(g.groups[0])).toEqual({ attention: 0, unread: 0, working: 0 })
})
it('counts the rows the sidebar is showing, so an active filter narrows it', () => {
- const [g] = buildSessionList(proj, null, 'p1', status, 'c1')
+ const [g] = buildSessionList(proj, null, 'p1', lookupFromMap(status), 'c1')
// a1 is filtered out of the tree, so the badge must not claim an attention the user cannot
// see or click — the same rule the project badge already follows.
expect(groupSignalCounts(g.groups[0])).toEqual({ attention: 0, unread: 0, working: 1 })
@@ -522,7 +530,7 @@ describe('buildStatusList', () => {
]
it('groups by status in the fixed order attention → unread → working → idle → unknown', () => {
- const sections = buildStatusList(proj, null, 'p1', status, '')
+ const sections = buildStatusList(proj, null, 'p1', lookupFromMap(status), '')
expect(sections.map((s) => s.kind)).toEqual([
'attention',
'unread',
@@ -533,7 +541,7 @@ describe('buildStatusList', () => {
})
it('flattens across projects and tags each row with its project', () => {
- const sections = buildStatusList(proj, null, 'p1', status, '')
+ const sections = buildStatusList(proj, null, 'p1', lookupFromMap(status), '')
const attention = sections.find((s) => s.kind === 'attention')!
expect(attention.rows.map((r) => r.id).sort()).toEqual(['a1', 'a2'])
expect(sections.find((s) => s.kind === 'idle')!.rows.map((r) => r.id)).toEqual(['d1'])
@@ -547,7 +555,7 @@ describe('buildStatusList', () => {
})
it('sorts rows within a section by descending state-change time', () => {
- const sections = buildStatusList(proj, null, 'p1', status, '')
+ const sections = buildStatusList(proj, null, 'p1', lookupFromMap(status), '')
// a2 (300) before a1 (100); d1 (read + done) sits in Idle, not between them.
expect(sections.find((s) => s.kind === 'attention')!.rows.map((r) => r.id)).toEqual([
'a2',
@@ -557,21 +565,21 @@ describe('buildStatusList', () => {
})
it('keeps only terminal nodes (drops stickies/editors)', () => {
- const sections = buildStatusList(proj, null, 'p1', status, '')
+ const sections = buildStatusList(proj, null, 'p1', lookupFromMap(status), '')
const ids = sections.flatMap((s) => s.rows.map((r) => r.id))
expect(ids).not.toContain('s1')
})
it('uses live nodes for the active project', () => {
const live = [node('a1', { title: 'renamed live', agentId: 'claude' })]
- const sections = buildStatusList(proj, live, 'p1', status, '')
+ const sections = buildStatusList(proj, live, 'p1', lookupFromMap(status), '')
const a1 = sections.flatMap((s) => s.rows).find((r) => r.id === 'a1')!
expect(a1.title).toBe('renamed live')
})
it('keeps empty sections while filtering rows by title/session', () => {
// 'runner' only matches w1 (working)
- const filtered = buildStatusList(proj, null, 'p1', status, 'runner')
+ const filtered = buildStatusList(proj, null, 'p1', lookupFromMap(status), 'runner')
expect(filtered.map((s) => s.kind)).toEqual([
'attention',
'unread',
@@ -589,7 +597,7 @@ describe('buildStatusList', () => {
{ id: 'p1', name: 'Alpha', color: '#111', nodes: [node('a1'), node('d1')] }
]
const two: Record<string, AgentNodeStatus> = { a1: { unread: false, state: 'waiting' }, d1: { unread: false, state: 'done' } }
- const sections = buildStatusList(onlyTwo, null, 'p1', two, '')
+ const sections = buildStatusList(onlyTwo, null, 'p1', lookupFromMap(two), '')
expect(sections.map((s) => s.kind)).toEqual([
'attention',
'unread',
@@ -610,7 +618,7 @@ describe('buildStatusList', () => {
i1: { unread: true }, // no state + unread → Unread
w1: { unread: true, state: 'working' } // actively working → Running (working wins over unread)
}
- const sections = buildStatusList(proj, null, 'p1', glowing, '')
+ const sections = buildStatusList(proj, null, 'p1', lookupFromMap(glowing), '')
const unread = sections.find((s) => s.kind === 'unread')!
expect(unread.label).toBe('Unread')
expect(unread.rows.map((r) => r.id).sort()).toEqual(['d1', 'i1'])
@@ -623,7 +631,7 @@ describe('buildStatusList', () => {
})
it('falls through to Unknown when no live state is known', () => {
- const sections = buildStatusList(proj, null, 'p1', status, '')
+ const sections = buildStatusList(proj, null, 'p1', lookupFromMap(status), '')
const unknown = sections.find((s) => s.kind === 'unknown')!
expect(unknown.label).toBe('Unknown')
expect(unknown.rows.map((r) => r.id)).toEqual(['i1'])
@@ -640,7 +648,7 @@ describe('buildStatusList', () => {
{ id: 'p2', name: 'ImmyBot', color: '#222', nodes: [node('b1', { title: 'other' })] }
]
// activeProjectId is now p2, but liveActiveNodes still carries p1's a1 (stale window).
- const sections = buildStatusList(proj2, p1Nodes, 'p2', { a1: { unread: false } }, '')
+ const sections = buildStatusList(proj2, p1Nodes, 'p2', lookupFromMap({ a1: { unread: false } }), '')
const allRows = sections.flatMap((s) => s.rows)
// a1 appears exactly once…
expect(allRows.filter((r) => r.id === 'a1')).toHaveLength(1)
@@ -673,44 +681,77 @@ describe('sidebar filter matches the PROJECT itself (issue #543)', () => {
]
it('keeps a session-less project that the needle NAMES, and drops the others', () => {
- const filtered = buildSessionList(proj(), null, 'p2', {}, 'dot-github')
+ const filtered = buildSessionList(proj(), null, 'p2', lookupFromMap({}), 'dot-github')
expect(filtered.map((g) => g.projectId)).toEqual(['p1'])
// Shown whole: an empty frame stays, exactly as it does unfiltered.
expect(filtered[0].groups.map((b) => b.id)).toEqual(['g1'])
})
it('matches the project cwd too — the identity the row tooltip already shows', () => {
- const filtered = buildSessionList(proj(), null, 'p1', {}, '/repos/website')
+ const filtered = buildSessionList(proj(), null, 'p1', lookupFromMap({}), '/repos/website')
expect(filtered.map((g) => g.projectId)).toEqual(['p2'])
})
it('a project matched by name comes back with ALL of its sessions, not just matching ones', () => {
- const filtered = buildSessionList(proj(), null, 'p1', {}, 'website')
+ const filtered = buildSessionList(proj(), null, 'p1', lookupFromMap({}), 'website')
expect(filtered.map((g) => g.projectId)).toEqual(['p2'])
expect(filtered[0].ungrouped.map((s) => s.id)).toEqual(['t1'])
expect(filtered[0].groups[0].sessions.map((s) => s.id)).toEqual(['t2'])
})
it('a session-level needle still narrows inside projects it does not name', () => {
- const filtered = buildSessionList(proj(), null, 'p1', {}, 'deploy')
+ const filtered = buildSessionList(proj(), null, 'p1', lookupFromMap({}), 'deploy')
expect(filtered.map((g) => g.projectId)).toEqual(['p2'])
expect(filtered[0].ungrouped).toEqual([])
expect(filtered[0].groups[0].sessions.map((s) => s.id)).toEqual(['t2'])
})
it('status mode keeps every row of a project the needle names (same rule, per row)', () => {
- const sections = buildStatusList(proj(), null, 'p1', {}, 'website')
+ const sections = buildStatusList(proj(), null, 'p1', lookupFromMap({}), 'website')
const ids = sections.flatMap((s) => s.rows.map((r) => r.id))
expect(ids.sort()).toEqual(['t1', 't2'])
})
it('status mode still narrows by row for projects the needle does not name', () => {
- const sections = buildStatusList(proj(), null, 'p1', {}, 'deploy')
+ const sections = buildStatusList(proj(), null, 'p1', lookupFromMap({}), 'deploy')
expect(sections.flatMap((s) => s.rows.map((r) => r.id))).toEqual(['t2'])
})
it('an unfiltered list is untouched by the project rule', () => {
- const unfiltered = buildSessionList(proj(), null, 'p1', {}, '')
+ const unfiltered = buildSessionList(proj(), null, 'p1', lookupFromMap({}), '')
expect(unfiltered.map((g) => g.projectId)).toEqual(['p1', 'p2'])
})
})
+
+describe('a node id shared by two projects (bug D)', () => {
+ // The field shape: a handed-off SSH project (closed in the field; a local session, so the default
+ // store) and the team tab now serving the same canvas (a relay session with its own store) hold
+ // the SAME node id. Each row must read its own project's answer, never the other project's.
+ const SSH = 'project-ssh-handed-off'
+ const TEAM = 'project-team-tab'
+ const NODE = 'term-shared-node'
+ const ssh: ProjectInput = { id: SSH, name: 'ssh', color: '#111', nodes: [node(NODE, { agentId: 'claude' })] }
+ const team: ProjectInput = { id: TEAM, name: 'team', color: '#222', nodes: [node(NODE, { agentId: 'claude' })] }
+ const lookup: AgentStatusLookup = (projectId, nodeId) => {
+ if (nodeId !== NODE) return undefined
+ if (projectId === SSH) return { unread: false, state: 'done' }
+ if (projectId === TEAM) return { unread: false, state: 'working' }
+ return undefined
+ }
+ const rowFor = (projectId: string, nodeId: string): SessionRowVM => {
+ const group = buildSessionList([ssh, team], null, TEAM, lookup, '').find((g) => g.projectId === projectId)
+ const row = group?.ungrouped.find((r) => r.id === nodeId)
+ expect(row, `${projectId}/${nodeId}`).toBeDefined()
+ return row!
+ }
+
+ it('a shared node id resolves per project', () => {
+ expect(rowFor(TEAM, NODE).statusKind).toBe('working')
+ expect(rowFor(SSH, NODE).statusKind).not.toBe('working')
+ expect(rowFor(SSH, NODE).statusKind).toBe('done')
+ // Status mode asks the lookup with the row's own project too (the sidebar passes only the open
+ // projects, so the closed SSH project is not in it).
+ const working = buildStatusList([team], null, TEAM, lookup, '').find((s) => s.kind === 'working')!
+ expect(working.rows.map((r) => [r.projectId, r.id])).toEqual([[TEAM, NODE]])
+ })
+})
diff --git a/src/renderer/lib/sessionList.ts b/src/renderer/lib/sessionList.ts
index 974420f0e..d112ed253 100644
--- a/src/renderer/lib/sessionList.ts
+++ b/src/renderer/lib/sessionList.ts
@@ -1,4 +1,5 @@
import type { AgentNodeStatus } from '../state/agentStatus'
+import type { AgentStatusLookup } from '../session/agent-status-lookup'
import type { AgentId } from '@shared/agents/config'
import type { AgentState } from '@shared/agents/normalize'
import type { NodeKind, ObservedClaudeAccount } from '@shared/types'
@@ -442,7 +443,7 @@ export function buildSessionList(
projects: ProjectInput[],
liveActiveNodes: SessionNodeInput[] | null,
activeProjectId: string,
- statusById: Record<string, AgentNodeStatus>,
+ statusFor: AgentStatusLookup,
filter: string
): SessionGroup[] {
const needle = filter.trim().toLowerCase()
@@ -486,7 +487,7 @@ export function buildSessionList(
const buildBucket = (gn: SessionNodeInput): GroupBucket | null => {
const sessions = terminals
.filter((n) => n.parentId === gn.id)
- .map((n) => toRow(n, statusById[n.id]))
+ .map((n) => toRow(n, statusFor(p.id, n.id)))
.filter(keep)
const children = (childGroups.get(gn.id) ?? [])
.map(buildBucket)
@@ -507,7 +508,7 @@ export function buildSessionList(
const ungrouped = terminals
.filter((n) => !n.parentId || !groupById.has(n.parentId))
- .map((n) => toRow(n, statusById[n.id]))
+ .map((n) => toRow(n, statusFor(p.id, n.id)))
.filter(keep)
return {
@@ -548,16 +549,16 @@ export interface StatusSection {
* re-sort within project. Within a section, rows are ordered by most-recent state transition first,
* so the freshest work in each bucket is easiest to reach.
*
- * Status comes from the same global `statusById` map `buildSessionList` reads; for local-core
- * projects that map is live for every node regardless of which project is active. Remote/relay
- * nodes are absent from it, so they fall through to `unknown` — the same way they render in project
- * mode today, so this introduces no regression.
+ * Status comes from the same per-project lookup `buildSessionList` reads (`AgentStatusLookup`):
+ * each row is asked through ITS project, so a relay/team tab's node reads that tab's session store
+ * and a local node the default one, whichever project is active. A node id held by two projects (a
+ * handed-off SSH project and the team tab serving it) therefore reads each project's own answer.
*/
export function buildStatusList(
projects: ProjectInput[],
liveActiveNodes: SessionNodeInput[] | null,
activeProjectId: string,
- statusById: Record<string, AgentNodeStatus>,
+ statusFor: AgentStatusLookup,
filter: string
): StatusSection[] {
const needle = filter.trim().toLowerCase()
@@ -605,7 +606,7 @@ export function buildStatusList(
const node = isActive && liveById.has(n.id) ? liveById.get(n.id)! : n
if (seen.has(node.id)) continue
seen.add(node.id)
- const row = toRow(node, statusById[node.id], p)
+ const row = toRow(node, statusFor(p.id, node.id), p)
if (keep(row, p.id)) tagged.push({ row, pidx })
}
})
@@ -619,7 +620,7 @@ export function buildStatusList(
for (const n of liveActiveNodes) {
if (n.kind !== 'terminal' || seen.has(n.id) || ownerById.has(n.id)) continue
seen.add(n.id)
- const row = toRow(n, statusById[n.id], active)
+ const row = toRow(n, statusFor(active.id, n.id), active)
if (keep(row, active.id)) tagged.push({ row, pidx: activePidx })
}
}
diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsx
index 310910f3d..7020d720b 100644
--- a/src/renderer/nodes/TerminalNode.tsx
+++ b/src/renderer/nodes/TerminalNode.tsx
@@ -1964,7 +1964,7 @@ export function TerminalNode({
* stays creation-time (`transport.create` keeps passing `data.accountId`).
*/
const observedAccount = status?.account
- const accountChip = useAccountChip(data.accountId, observedAccount)
+ const accountChip = useAccountChip(data.accountId, observedAccount, agentStatusStore)
// This node's team (the stations it opened), published by Canvas from the live ropes. The store
// keeps each unchanged team's array identity, so this re-renders only when THIS team changes.
const team = useTeamStations((s) => s.byNode.get(id))
@@ -6319,7 +6319,7 @@ export function TerminalNode({
/>
{/* The stations this session opened, and how far along they are — the same ring its board
card and card modal draw (lib/teamProgress). A row travels to that station. */}
- {team && <TeamProgressChip stations={team} onTravel={travelToStation} menuZIndex={60} />}
+ {team && <TeamProgressChip stations={team} onTravel={travelToStation} menuZIndex={60} statusStore={agentStatusStore} />}
{/* The fallback, made visible. A Codex node that could not get a managed shared identity
runs a perfectly good plain `codex` — but the user has to be able to SEE that it did,
without reading a log, so the chip states it and its tooltip says why. Absent (and the
diff --git a/src/renderer/nodes/browser-partition-parity.test.tsx b/src/renderer/nodes/browser-partition-parity.test.tsx
index e0c79ec1e..83646d6a9 100644
--- a/src/renderer/nodes/browser-partition-parity.test.tsx
+++ b/src/renderer/nodes/browser-partition-parity.test.tsx
@@ -27,7 +27,17 @@ vi.mock('./BrowserSurface', () => ({
}))
// CardModal's non-browser children are irrelevant to partition parity — stub them so the modal
// renders without their store/context burden.
-vi.mock('../session/session', () => ({ useSession: () => ({ api: { pty: { generateName: vi.fn() } } }) }))
+vi.mock('../session/session', async () => {
+ // The agent-status reads now resolve a store per project / per session (bug D, covered in
+ // session/agent-status-lookup.test.tsx). Here every one answers the default store, as before.
+ const { defaultAgentStatus } = await import('../state/agentStatus')
+ return {
+ useSession: () => ({ api: { pty: { generateName: vi.fn() } } }),
+ agentStatusForProject: () => defaultAgentStatus,
+ useSessionRegistryVersion: () => 0,
+ useSessionStores: () => ({ agentStatus: defaultAgentStatus })
+ }
+})
vi.mock('../components/kanban/BoardLogPanel', () => ({ BoardLogPanel: () => null }))
vi.mock('../components/kanban/CardMetaBar', () => ({ CardMetaBar: () => null }))
vi.mock('../components/kanban/ModalTerminal', () => ({ ModalTerminal: () => null }))
diff --git a/src/renderer/session/agent-status-lookup.test.tsx b/src/renderer/session/agent-status-lookup.test.tsx
new file mode 100644
index 000000000..bef81823b
--- /dev/null
+++ b/src/renderer/session/agent-status-lookup.test.tsx
@@ -0,0 +1,287 @@
+// @vitest-environment jsdom
+//
+// Bug D, Task 6: the LIST surfaces — the sessions sidebar, the project-tab unread dot, the kanban
+// cards and the card modal — read each project's agent status from the store of the session that
+// PROJECT belongs to. A handed-off SSH project (local session, the default store) and the team tab
+// now serving it (relay session, its own keyless store) hold the SAME node ids, so a list that read
+// one store for every row showed the team tab's agents as Unknown, or the SSH project's state on
+// the team tab's row.
+import { act } from 'react'
+import { createRoot, type Root } from 'react-dom/client'
+import { readFileSync } from 'node:fs'
+import { resolve } from 'node:path'
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import type { NodeTerminalApi, Project } from '@shared/types'
+import {
+ bindProjectToSession,
+ createSession,
+ disposeSession,
+ getSessionStores,
+ resetSessionsForTest,
+ setActiveSession,
+ setOfflineRelayApiFactory
+} from './session'
+import { lookupFromStores, useAgentStatusLookup, useAgentStatusSig, type AgentStatusLookup } from './agent-status-lookup'
+import { defaultAgentStatus } from '../state/agentStatus'
+import { useProjects } from '../state/projects'
+import { parseUnreadSig, unreadSigFor } from '../components/TabBar'
+import { SessionCard } from '../components/kanban/SessionCard'
+import type { KanbanSession } from '../components/kanban/KanbanView'
+
+vi.mock('../components/ContextMeter', () => ({ ContextMeter: () => null }))
+
+;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true
+
+// The local session's api IS `window.nodeTerminal`, and state/agentStatus.ts seeds its api memo with
+// that object at module load — which is what makes the local session's store the DEFAULT one.
+// Hoisted so the seed happens before that import evaluates, exactly as in the app.
+const LOCAL_API = vi.hoisted(() => {
+ const api = { marker: 'local' }
+ ;(window as unknown as { nodeTerminal: unknown }).nodeTerminal = api
+ return api
+}) as unknown as NodeTerminalApi
+const OFFLINE_API = { marker: 'offline' } as unknown as NodeTerminalApi
+
+const SSH_PROJECT = 'project-ssh-handed-off'
+const TEAM_PROJECT = 'project-team-tab'
+const NODE = 'term-shared-node'
+
+const project = (id: string, remote: boolean): Project =>
+ ({ id, name: id, color: '#888', nodes: [{ id: NODE }], ...(remote ? { remote: true } : {}) }) as unknown as Project
+
+let host: HTMLDivElement
+let root: Root
+
+beforeEach(() => {
+ resetSessionsForTest()
+ setActiveSession(createSession('local', LOCAL_API, 'This machine').id)
+ setOfflineRelayApiFactory(() => OFFLINE_API)
+ useProjects.setState({ projects: [project(SSH_PROJECT, false), project(TEAM_PROJECT, true)], activeProjectId: TEAM_PROJECT })
+ host = document.createElement('div')
+ document.body.appendChild(host)
+ root = createRoot(host)
+})
+
+afterEach(() => {
+ act(() => root.unmount())
+ host.remove()
+ setOfflineRelayApiFactory(null)
+ useProjects.setState({ projects: [], activeProjectId: '' })
+ defaultAgentStatus.store.setState({ byId: {}, activeId: null })
+ localStorage.clear()
+})
+
+/** A team tab joined over the relay: its own session, bound to the team project. A fresh api per
+ * join: the relay store is memoized BY API IDENTITY (`agentStatusForApi`), so a shared api object
+ * would carry one test's statuses into the next — and a reconnect is a new connection's api. */
+function joinTeam(): string {
+ const relay = createSession('relay', { marker: 'relay' } as unknown as NodeTerminalApi, 'Team')
+ bindProjectToSession(TEAM_PROJECT, relay.id)
+ return relay.id
+}
+
+const relayStore = (sessionId: string) => getSessionStores(sessionId).agentStatus.store
+
+describe('useAgentStatusLookup', () => {
+ it('useAgentStatusLookup re-renders on a relay store change and on a reconnect', () => {
+ const first = joinTeam()
+ let renders = 0
+ function Probe() {
+ renders++
+ const lookup = useAgentStatusLookup([SSH_PROJECT, TEAM_PROJECT])
+ const team = lookup(TEAM_PROJECT, NODE)?.state ?? '-'
+ const ssh = lookup(SSH_PROJECT, NODE)?.state ?? '-'
+ return <span>{`${team}/${ssh}`}</span>
+ }
+ act(() => root.render(<Probe />))
+ expect(host.textContent).toBe('-/-')
+
+ // A host event lands in the team tab's own store: its row moves, the SSH project's does not.
+ act(() => relayStore(first).getState().setState(NODE, 'working', 'claude'))
+ expect(host.textContent).toBe('working/-')
+ // And the SSH project's entry under the same id is the default store's.
+ act(() => defaultAgentStatus.store.getState().setState(NODE, 'done', 'claude'))
+ expect(host.textContent).toBe('working/done')
+
+ // A reconnect: the old session goes, a new one (another api, so another store) takes the tab.
+ // The lookup re-resolves the project to the NEW store…
+ const firstStore = relayStore(first)
+ const second = joinTeam()
+ act(() => disposeSession(first))
+ expect(relayStore(second)).not.toBe(firstStore)
+ expect(host.textContent).toBe('-/done')
+ // …and is subscribed to it: a change there re-renders, a change in the dead one does not.
+ act(() => relayStore(second).getState().setState(NODE, 'blocked', 'claude'))
+ expect(host.textContent).toBe('blocked/done')
+ const before = renders
+ act(() => firstStore.getState().setState(NODE, 'working', 'claude'))
+ expect(renders).toBe(before)
+ expect(host.textContent).toBe('blocked/done')
+ })
+
+ it('useAgentStatusSig does not re-render on a change that leaves the signature alone', () => {
+ const relay = joinTeam()
+ let renders = 0
+ function Probe() {
+ renders++
+ const sig = useAgentStatusSig([TEAM_PROJECT], (lookup) => (lookup(TEAM_PROJECT, NODE)?.unread ? 'unread' : 'read'))
+ return <span>{sig}</span>
+ }
+ act(() => root.render(<Probe />))
+ expect(host.textContent).toBe('read')
+ const settled = renders
+
+ // State flips that leave `unread` alone: the signature is the same string, nothing re-renders.
+ act(() => relayStore(relay).getState().setState(NODE, 'working', 'claude'))
+ act(() => relayStore(relay).getState().setState(NODE, 'waiting', 'claude'))
+ expect(renders).toBe(settled)
+
+ act(() => relayStore(relay).getState().markUnread(NODE))
+ expect(host.textContent).toBe('unread')
+ expect(renders).toBe(settled + 1)
+ })
+})
+
+describe('unreadSigFor', () => {
+ it("unreadSigFor counts a relay project's unread from its own store, not the default one", () => {
+ const relay = joinTeam()
+ const projects = useProjects.getState().projects
+ const counts = (): ReadonlyMap<string, number> =>
+ parseUnreadSig(unreadSigFor(projects, lookupFromStores([SSH_PROJECT, TEAM_PROJECT])))
+
+ expect(counts().size).toBe(0)
+ // Unread on the team tab's own store: the team tab's dot, never the SSH project's.
+ act(() => relayStore(relay).getState().markUnread(NODE))
+ expect(counts().get(TEAM_PROJECT)).toBe(1)
+ expect(counts().get(SSH_PROJECT)).toBeUndefined()
+ expect(defaultAgentStatus.store.getState().byId[NODE]?.unread).toBeFalsy()
+
+ // And the reverse: the default store's unread is the SSH project's, not the team tab's.
+ act(() => relayStore(relay).getState().clearUnread(NODE))
+ act(() => defaultAgentStatus.store.getState().markUnread(NODE))
+ expect(counts().get(SSH_PROJECT)).toBe(1)
+ expect(counts().get(TEAM_PROJECT)).toBeUndefined()
+ })
+})
+
+describe('SessionCard', () => {
+ const card: KanbanSession = { id: NODE, title: 'agent', color: '#fff', kind: 'terminal', spawn: {} }
+ const noop = (): void => {}
+ const renderCard = (statusStore?: ReturnType<typeof relayStore>): void =>
+ act(() =>
+ root.render(
+ <SessionCard
+ session={card}
+ onOpen={noop}
+ onDragStart={noop}
+ onDragEnd={noop}
+ onDropAt={noop}
+ onContext={noop}
+ liveLinkSource="relay"
+ statusStore={statusStore}
+ />
+ )
+ )
+
+ it("a SessionCard given statusStore shows that store's badge", () => {
+ const relay = joinTeam()
+ act(() => relayStore(relay).getState().setState(NODE, 'working', 'claude'))
+ // The default store says something else under the same id (the handed-off SSH project).
+ act(() => defaultAgentStatus.store.getState().setState(NODE, 'waiting', 'claude'))
+
+ renderCard(relayStore(relay))
+ expect(host.querySelector('.kanban-badge--running')?.textContent).toBe('RUNNING')
+ expect(host.querySelector('.kanban-badge--needs')).toBeNull()
+ // Live: the card follows ITS store.
+ act(() => relayStore(relay).getState().setState(NODE, 'blocked', 'claude'))
+ expect(host.querySelector('.kanban-badge--needs')?.textContent).toBe('NEEDS YOU')
+
+ // Absent = the default store, exactly as before.
+ act(() => relayStore(relay).getState().setState(NODE, 'working', 'claude'))
+ renderCard(undefined)
+ expect(host.querySelector('.kanban-badge--needs')?.textContent).toBe('NEEDS YOU')
+ expect(host.querySelector('.kanban-badge--running')).toBeNull()
+ })
+})
+
+// Source pins: the boards, the card modal and the modal terminal need Canvas, a pty and a project
+// on disk to mount.
+const read = (rel: string) => readFileSync(resolve(__dirname, '..', rel), 'utf8').replace(/\r\n/g, '\n')
+
+/** The text from `start` up to (not including) the first `end` after it; fails loudly if either is
+ * missing, so a renamed anchor reads as a broken pin rather than an empty, passing slice. */
+function between(text: string, start: string, end: string): string {
+ const from = text.indexOf(start)
+ expect(from, `anchor not found: ${start}`).toBeGreaterThanOrEqual(0)
+ const to = text.indexOf(end, from + start.length)
+ expect(to, `end anchor not found after ${start}: ${end}`).toBeGreaterThan(from)
+ return text.slice(from, to)
+}
+
+describe('the board surfaces read the store of the project they show', () => {
+ it('CardModal and ModalTerminal read the session store', () => {
+ for (const f of ['components/kanban/CardModal.tsx', 'components/kanban/ModalTerminal.tsx']) {
+ const src = read(f)
+ expect(src, f).not.toMatch(/\buseAgentStatus\b/)
+ expect(src, f).toContain('const agentStatusStore = useSessionStores().agentStatus.store')
+ }
+ // The modal terminal's file insert reads the pane's agent off the same store.
+ const insertFiles = between(read('components/kanban/ModalTerminal.tsx'), 'const insertFiles = async (', 'const onDrop = async')
+ expect(insertFiles).toContain('const st = agentStatusStore.getState().byId[nodeId]')
+ })
+
+ it('both boards hand SessionCard a per-project store and clear unread on it', () => {
+ // The memo re-resolves on a registry change: a reconnect swaps the project's store.
+ const resolvesPerProject = (src: string): void => {
+ expect(src).toContain('const registryVersion = useSessionRegistryVersion()')
+ const memo = between(src, 'const statusStore = useMemo(', '\n )')
+ expect(memo).toContain('() => agentStatusForProject(projectId).store,')
+ expect(memo).toContain('[projectId, registryVersion]')
+ }
+ const board = read('components/kanban/KanbanView.tsx')
+ expect(board).not.toMatch(/\buseAgentStatus\b/)
+ resolvesPerProject(board)
+ expect(between(board, '<SessionCard', '/>')).toContain('statusStore={statusStore}')
+ expect(board).toContain('if (modalNodeId) statusStore.getState().clearUnread(modalNodeId)')
+ expect(board).toContain('const statusSig = statusStore((st) => statusChipSig(st.byId, chipCards))')
+
+ const global = read('components/kanban/GlobalKanbanView.tsx')
+ expect(global).not.toMatch(/\buseAgentStatus\b/)
+ const lane = between(global, 'const Swimlane = memo(function Swimlane(', 'export const GlobalKanbanView')
+ resolvesPerProject(lane)
+ expect(between(lane, '<SessionCard', '/>')).toContain('statusStore={statusStore}')
+ // The overview's open card is cleared on ITS lane's project store, never the default one.
+ expect(global).toContain('const modalProjectId = modal?.projectId ?? null')
+ expect(global).toContain(
+ 'if (modalNodeId) agentStatusForProject(modalProjectId).store.getState().clearUnread(modalNodeId)'
+ )
+ })
+
+ it('TerminalNode, the board card and the card modal hand their store to the team and account chips', () => {
+ // Neither chip reads the default store unconditionally: absent = default, given = that store.
+ const team = read('components/TeamProgressChip.tsx')
+ expect(team).not.toMatch(/useAgentStatus\(\(/)
+ expect(team).toContain('const sig = (statusStore ?? useAgentStatus)((s) => teamProgressSig(s.byId, stations))')
+ const account = read('components/AccountChip.tsx')
+ expect(account).not.toMatch(/useAgentStatus\(\(/)
+ expect(account).toContain(
+ 'const multiple = (statusStore ?? useAgentStatus)((s) => hasMultipleAccountKeys(s.byId, dataAccountId, accounts))'
+ )
+
+ const node = read('nodes/TerminalNode.tsx')
+ expect(node).toContain('const accountChip = useAccountChip(data.accountId, observedAccount, agentStatusStore)')
+ expect(node).toContain(
+ '{team && <TeamProgressChip stations={team} onTravel={travelToStation} menuZIndex={60} statusStore={agentStatusStore} />}'
+ )
+ const cardSrc = read('components/kanban/SessionCard.tsx')
+ expect(cardSrc).toContain('const accountChip = useAccountChip(session.spawn.accountId, status?.account, statusStore)')
+ expect(cardSrc).toContain('<TeamProgressChip stations={team} onTravel={onTravel} statusStore={statusStore} />')
+ const modal = read('components/kanban/CardModal.tsx')
+ expect(modal).toContain('const accountChip = useAccountChip(session.spawn.accountId, observedAccount, agentStatusStore)')
+ expect(modal).toContain('<TeamProgressChip stations={team} onTravel={onTravel} statusStore={agentStatusStore} />')
+ })
+})
+
+// Type-level: the lookup is the shape the builders consume.
+const _shape: AgentStatusLookup = lookupFromStores([])
+void _shape
diff --git a/src/renderer/session/agent-status-lookup.ts b/src/renderer/session/agent-status-lookup.ts
new file mode 100644
index 000000000..874bcefb5
--- /dev/null
+++ b/src/renderer/session/agent-status-lookup.ts
@@ -0,0 +1,144 @@
+import { useCallback, useRef, useSyncExternalStore } from 'react'
+import type { AgentNodeStatus, AgentStatusSession } from '../state/agentStatus'
+import { agentStatusForProject, sessionRegistryVersion, subscribeSessionRegistry } from './session'
+
+/**
+ * A node's agent status, asked PER PROJECT (bug D). The list surfaces — the sessions sidebar, the
+ * project-tab unread dot, the boards — show many projects at once, and a node id is not unique
+ * across them: a handed-off SSH project (local session, the default store) and the team tab now
+ * serving the same canvas (relay session, its own keyless store) hold the SAME ids. So a status is
+ * looked up through the store of the session the row's PROJECT belongs to (`agentStatusForProject`),
+ * never through one store for every row and never through the active project.
+ */
+export type AgentStatusLookup = (projectId: string, nodeId: string) => AgentNodeStatus | undefined
+
+type StatusStore = AgentStatusSession['store']
+
+/** An own entry of the table, or nothing. Node ids come from a git-shared, hand-editable project
+ * file, and `byId['constructor']` on a plain object is Object's constructor, not a status. */
+function entryOf(byId: Readonly<Record<string, AgentNodeStatus>>, nodeId: string): AgentNodeStatus | undefined {
+ return Object.prototype.hasOwnProperty.call(byId, nodeId) ? byId[nodeId] : undefined
+}
+
+function storeFor(projectId: string): StatusStore {
+ return agentStatusForProject(projectId).store
+}
+
+/**
+ * The non-hook lookup, for tests and imperative reads (an on-demand queue build, a click handler):
+ * each listed project's store is resolved NOW, and every call reads that store's CURRENT table. A
+ * project that was not listed is resolved at call time. Subscribes to nothing — a component that
+ * renders from it wants `useAgentStatusLookup` / `useAgentStatusSig`.
+ */
+export function lookupFromStores(projectIds: readonly string[]): AgentStatusLookup {
+ const stores = new Map<string, StatusStore>()
+ for (const id of projectIds) stores.set(id, storeFor(id))
+ return (projectId, nodeId) => entryOf((stores.get(projectId) ?? storeFor(projectId)).getState().byId, nodeId)
+}
+
+/** A lookup over a FROZEN set of tables (one per listed project) — the hook's snapshot, so a
+ * render reads one consistent state. Unlisted ids fall back to a live read, like `lookupFromStores`. */
+function lookupFromTables(tables: ReadonlyMap<string, Readonly<Record<string, AgentNodeStatus>>>): AgentStatusLookup {
+ return (projectId, nodeId) => {
+ const byId = tables.get(projectId) ?? storeFor(projectId).getState().byId
+ return entryOf(byId, nodeId)
+ }
+}
+
+/** A stable small number per store object, so the set of resolved stores can key a callback. */
+const storeIds = new WeakMap<StatusStore, number>()
+let nextStoreId = 0
+function storeId(store: StatusStore): number {
+ let id = storeIds.get(store)
+ if (id === undefined) {
+ id = ++nextStoreId
+ storeIds.set(store, id)
+ }
+ return id
+}
+
+interface Snapshot {
+ key: readonly unknown[]
+ lookup: AgentStatusLookup
+}
+
+function sameKey(a: readonly unknown[], b: readonly unknown[]): boolean {
+ if (a.length !== b.length) return false
+ for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false
+ return true
+}
+
+/**
+ * The shared source behind both hooks: one subscription to every DISTINCT store the listed
+ * projects resolve to plus the session registry signal, and a snapshot lookup memoized on the
+ * tuple (project ids, registry version, each project's `byId` reference).
+ *
+ * Re-resolution: a registry change (a reconnect swaps a project's session, an unbind sends it to
+ * the offline session) notifies the subscriber; the snapshot re-resolves and changes, the caller
+ * re-renders, the render resolves the NEW store set, and its changed key re-subscribes. A
+ * resolution that moves only because the projects store changed (`remote` read by
+ * `agentStatusForProject`) is picked up the same way on the caller's next render — every caller
+ * holds the projects it passes, so it re-renders on them.
+ */
+function useLookupSource(projectIds: readonly string[]): {
+ subscribe: (onChange: () => void) => () => void
+ getLookup: () => AgentStatusLookup
+} {
+ const distinct = [...new Set(projectIds.map(storeFor))]
+ const storesKey = distinct.map(storeId).join(',')
+ // The callback closes over THIS render's distinct stores; its identity changes exactly when the
+ // set does, which is what makes React re-subscribe.
+ const subscribe = useCallback(
+ (onChange: () => void) => {
+ const offs = distinct.map((store) => store.subscribe(onChange))
+ offs.push(subscribeSessionRegistry(onChange))
+ return () => {
+ for (const off of offs) off()
+ }
+ },
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ [storesKey]
+ )
+ const idsRef = useRef(projectIds)
+ idsRef.current = projectIds
+ const cache = useRef<Snapshot | null>(null)
+ const getLookup = useCallback((): AgentStatusLookup => {
+ const ids = idsRef.current
+ const tables = ids.map((id) => storeFor(id).getState().byId)
+ const key: unknown[] = [JSON.stringify(ids), sessionRegistryVersion(), ...tables]
+ if (cache.current && sameKey(cache.current.key, key)) return cache.current.lookup
+ const lookup = lookupFromTables(new Map(ids.map((id, i) => [id, tables[i]])))
+ cache.current = { key, lookup }
+ return lookup
+ }, [])
+ return { subscribe, getLookup }
+}
+
+/** Re-renders when a resolved store's byId changes or a project's resolution changes. */
+export function useAgentStatusLookup(projectIds: readonly string[]): AgentStatusLookup {
+ const { subscribe, getLookup } = useLookupSource(projectIds)
+ return useSyncExternalStore(subscribe, getLookup)
+}
+
+/**
+ * Primitive-signature form: re-renders only when `sig(lookup)` changes. The list surfaces' rule
+ * (`unreadIdsSig`, `statusChipSig`): a hook event elsewhere on the canvas changes `byId` but not
+ * the fact this caller shows, and must re-render nothing here.
+ */
+export function useAgentStatusSig(
+ projectIds: readonly string[],
+ sig: (lookup: AgentStatusLookup) => string
+): string {
+ const { subscribe, getLookup } = useLookupSource(projectIds)
+ const last = useRef<{ lookup: AgentStatusLookup; sig: (lookup: AgentStatusLookup) => string; value: string } | null>(
+ null
+ )
+ const getSig = (): string => {
+ const lookup = getLookup()
+ if (last.current && last.current.lookup === lookup && last.current.sig === sig) return last.current.value
+ const value = sig(lookup)
+ last.current = { lookup, sig, value }
+ return value
+ }
+ return useSyncExternalStore(subscribe, getSig)
+}
diff --git a/src/renderer/state/agentStatus.lastSeen.test.ts b/src/renderer/state/agentStatus.lastSeen.test.ts
index 76d8ad574..d5ecf65e8 100644
--- a/src/renderer/state/agentStatus.lastSeen.test.ts
+++ b/src/renderer/state/agentStatus.lastSeen.test.ts
@@ -3,6 +3,15 @@ import { buildHibernationCandidates } from '../lib/hibernationCandidates'
import { planHibernation } from '../terminal/hibernation-policy'
import { shouldDeferReleaseForEco } from '../terminal/offscreen-policy'
import { buildStatusList } from '../lib/sessionList'
+import type { AgentNodeStatus } from './agentStatus'
+import type { AgentStatusLookup } from '../session/agent-status-lookup'
+
+// `buildStatusList` reads status per PROJECT (bug D); these cases have one store, so a map that
+// ignores the project stands in.
+const lookupFromMap =
+ (byId: Record<string, AgentNodeStatus>): AgentStatusLookup =>
+ (_projectId, nodeId) =>
+ byId[nodeId]
// The persisted "last seen" clock (`AgentNodeStatus.lastSeen`): restored across an app restart as a
// CLOCK that orders and ages sidebar rows — never as a live state, never as Eco's idle clock. It
@@ -154,7 +163,7 @@ describe('the first event after a restart (SessionStart of a cold-restore resume
color: '#fff',
nodes: [{ id: 'r', kind: 'terminal' as const, title: 'r', color: '#fff', agentId: 'claude' as const }]
}
- const row = buildStatusList([project], null, 'p', after, '').flatMap((g) => g.rows)[0]
+ const row = buildStatusList([project], null, 'p', lookupFromMap(after), '').flatMap((g) => g.rows)[0]
expect(row.statusClock).toBe('seen') // NOT "before nodeterm restarted"
const { sessionStateAgeTitle } = await import('../lib/sessionList')
expect(sessionStateAgeTitle('seen just now', row.statusClock)).not.toMatch(/restarted/)
@@ -311,7 +320,7 @@ describe('sidebar ordering and age label', () => {
{ id: 'recent', kind: 'terminal' as const, title: 'c-recent', color: '#fff', agentId: 'claude' as const }
]
}
- const groups = buildStatusList([project], null, 'p', useAgentStatus.getState().byId, '')
+ const groups = buildStatusList([project], null, 'p', lookupFromMap(useAgentStatus.getState().byId), '')
const unknown = groups.find((g) => g.kind === 'unknown')!
expect(unknown.rows.map((r) => r.id)).toEqual(['recent', 'old', 'noClock'])
expect(groups.flatMap((g) => g.rows).some((r) => r.id === 'ghost')).toBe(false)
@@ -325,7 +334,7 @@ describe('sidebar ordering and age label', () => {
expect(sessionStateAgeTitle(label!, 'restored', 'working')).toMatch(/Running/)
// A live transition wins.
useAgentStatus.getState().setState('old', 'done', 'claude')
- const after = buildStatusList([project], null, 'p', useAgentStatus.getState().byId, '')
+ const after = buildStatusList([project], null, 'p', lookupFromMap(useAgentStatus.getState().byId), '')
const oldRow = after.flatMap((g) => g.rows).find((r) => r.id === 'old')!
expect(oldRow.statusClock).toBe('transition')
expect(sessionStateAgeLabel(oldRow.statusUpdatedAt, Date.now(), oldRow.statusClock)).toBe('just now')