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.
TypeScript adhdagent-orchestrationai-agentscanvasclaude-codecodexcoding-agentsdeveloper-toolselectrongeminilinuxmacosmultiplexeropencodeparallel-agentsterminalterminal-emulatorterminal-multiplexertmuxworkspace-manager
Count the Dock badge over live nodes and sweep orphaned status entries
Uri Blochbfe63cc2b6b8
diff --git a/CLAUDE.md b/CLAUDE.mdindex 4669e052f..67cef08e3 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -4138,7 +4138,9 @@ command-bearing opens; this does not add a human-confirm dialog or change mobileSettings (`notifyOnClaudeDone`). Selecting, focusing, dwelling into, or opening a session cardclears `unread` and ACKs the finish across phone/notch surfaces — existing read-on-view behavior.This NEVER changes the workflow bucket: read state is independent from agent state.- The unread COUNT is the macOS Dock badge, and on **Windows** a taskbar overlay icon (pure+ The unread COUNT is the macOS Dock badge (counted over nodes some project HOLDS, closed ones+ included — never over the raw status table, which outlives nodes deleted by paths that skip+ `remove`; stale entries are swept at load past a 7-day grace, `lib/unreadBadge.ts`), and on **Windows** a taskbar overlay icon (pure`planBadge` + BGRA rasterizer `rasterizeBadge`, "9+" above nine, `main/taskbar-badge.ts`) plus a`flashFrame` when the count RISES while unfocused (cleared on focus); Linux shows nothing. Windowstoasts need `app.setAppUserModelId` set before ready to the package.json `build.appId` the NSISdiff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsxindex 559d50158..b237d7649 100644--- a/src/renderer/canvas/Canvas.tsx+++ b/src/renderer/canvas/Canvas.tsx@@ -520,6 +520,7 @@ import {} from '../lib/explorerPinHint'import { addRelayTab, sameSshEndpoint, setKanbanPublishHook, setStoredCanvasPublishHook, useProjects } from '../state/projects'import { useAgentStatus, recordsTurnInterrupt } from '../state/agentStatus'+import { countUnreadInProjects, orphanStatusIds, unreadIdSet, unreadIdsSig } from '../lib/unreadBadge'import { usePendingPause, startPendingPauseWatcher } from '../state/pendingPause'import {planBulkPause,@@ -3255,6 +3256,7 @@ export function Canvas() {)// 1) Load the whole workspace once and hydrate the projects store.+ const [workspaceLoaded, setWorkspaceLoaded] = useState(false)useEffect(() => {let cancelled = false// Pull the current license status: the main process broadcasts it on launch, but that@@ -3291,6 +3293,13 @@ export function Canvas() {// persists the conversion, so the next load is a no-op.const projects = ws.projects.map(migrateProjectTags)useProjects.getState().hydrate({ ...ws, projects })+ // Drop status entries whose node is in no project (past a grace window) — the table is+ // persisted and otherwise grows forever. `orphanStatusIds` refuses to judge an incomplete+ // load (no projects, or an unreadable one), so a bad index read never costs a live node its+ // resume id.+ const status = useAgentStatus.getState()+ status.removeMany(orphanStatusIds(status.byId, useProjects.getState().projects, Date.now()))+ setWorkspaceLoaded(true)// Upgrade the on-disk format (e.g. v1 -> v2 migration) right away. Reported like every// other save: a `void` here used to make the very first write of the session the one write// that could fail with no signal at all — including the format migration.@@ -5209,17 +5218,21 @@ export function Canvas() {if (valid.length !== linkEdges.length) setLinkEdges(valid)}, [linkEdges, nodes, setLinkEdges])- // Reflect Claude nodes with unread output as a macOS Dock badge count (across all projects).- // Subscribes to the derived count (a primitive), not the byId map, for the same reason as- // loopSig above — state flips must not re-render the canvas.- const unreadCount = useAgentStatus((s) => {- let count = 0- for (const st of Object.values(s.byId)) if (st?.unread) count++- return count- })+ // The app-level unread count (macOS Dock badge, Windows taskbar overlay, tray), across all+ // projects. Counted over the nodes the projects HOLD, never over the status table alone: that+ // table outlives nodes deleted by paths that never reach `remove`, and counting it raw showed+ // a Dock of 20 beside a single tab badge of 1 (lib/unreadBadge.ts). Both selectors return a+ // primitive, so neither a state flip nor a node serialization re-renders the canvas.+ const unreadSig = useAgentStatus((s) => unreadIdsSig(s.byId))+ const unreadSet = useMemo(() => unreadIdSet(unreadSig), [unreadSig])+ const unreadCount = useProjects((s) => countUnreadInProjects(s.projects, unreadSet))useEffect(() => {+ // Not before the workspace is loaded: with no projects yet the count reads 0, and on Windows+ // the real count arriving a moment later would read as a RISE and flash the taskbar at boot+ // (planBadge treats the FIRST report as the baseline).+ if (!workspaceLoaded) returnwindow.nodeTerminal.setBadgeCount(unreadCount)- }, [unreadCount])+ }, [unreadCount, workspaceLoaded])// Feed per-session context-window fill from main into the transient store.useEffect(() => {diff --git a/src/renderer/components/TabBar.tsx b/src/renderer/components/TabBar.tsxindex a3f4ace86..b7ce078a8 100644--- a/src/renderer/components/TabBar.tsx+++ b/src/renderer/components/TabBar.tsx@@ -3,6 +3,7 @@ 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 { usePauseCounts } from '../state/pauseCounts'import { useSettings } from '../state/settings'import { accountsForProject, sshAccountsHint, systemAccountDisplay } from '../state/workspace'@@ -126,12 +127,8 @@ export function TabBar({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) => {- let ids = ''- for (const [id, st] of Object.entries(s.byId)) if (st?.unread) ids += `${id}|`- return ids- })- const unreadSet = useMemo(() => new Set(unreadIds.split('|').filter(Boolean)), [unreadIds])+ const unreadIds = useAgentStatus((s) => unreadIdsSig(s.byId))+ const unreadSet = useMemo(() => unreadIdSet(unreadIds), [unreadIds])// ⏸ 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.diff --git a/src/renderer/lib/unreadBadge.test.ts b/src/renderer/lib/unreadBadge.test.tsnew file mode 100644index 000000000..b80ce82d0--- /dev/null+++ b/src/renderer/lib/unreadBadge.test.ts@@ -0,0 +1,58 @@+import { describe, expect, it } from 'vitest'+import {+ ORPHAN_STATUS_GRACE_MS,+ countUnreadInProjects,+ orphanStatusIds,+ unreadIdSet,+ unreadIdsSig+} from './unreadBadge'++const DAY = 24 * 60 * 60_000+const NOW = 1_800_000_000_000++describe('countUnreadInProjects (the Dock / taskbar / tray count)', () => {+ it('counts only unread entries whose node a project holds — the field report: 20 unread, 1 live', () => {+ const byId: Record<string, { unread: boolean }> = { live: { unread: true }, read: { unread: false } }+ for (let i = 0; i < 19; i++) byId[`gone-${i}`] = { unread: true }+ const projects = [{ nodes: [{ id: 'live' }, { id: 'read' }] }, { nodes: [{ id: 'other' }] }]+ const unread = unreadIdSet(unreadIdsSig(byId))+ expect(unread.size).toBe(20)+ expect(countUnreadInProjects(projects, unread)).toBe(1)+ })++ it('counts a closed project too (its sessions still run), and a node held by two projects once', () => {+ const projects = [+ { nodes: [{ id: 'a' }] },+ { closed: true, nodes: [{ id: 'b' }, { id: 'a' }] }+ ]+ expect(countUnreadInProjects(projects, new Set(['a', 'b']))).toBe(2)+ })++ it('is 0 with no projects loaded', () => {+ expect(countUnreadInProjects([], new Set(['a']))).toBe(0)+ })+})++describe('orphanStatusIds (the boot sweep)', () => {+ const projects = [{ nodes: [{ id: 'live' }] }]++ it('drops an entry whose node is in no project, with no clock or an old one', () => {+ const byId = {+ live: { unread: true },+ noClock: { unread: true },+ old: { lastSeen: { at: NOW - ORPHAN_STATUS_GRACE_MS - 1 } }+ }+ expect(orphanStatusIds(byId, projects, NOW).sort()).toEqual(['noClock', 'old'])+ })++ it('keeps a recently-seen orphan (an SSH cache that lags, a canvas a checkout may restore)', () => {+ const byId = { recent: { unread: true, lastSeen: { at: NOW - 2 * DAY } } }+ expect(orphanStatusIds(byId, projects, NOW)).toEqual([])+ })++ it('judges nothing when the load is incomplete: no projects, or an unreadable one', () => {+ const byId = { x: { unread: true } }+ expect(orphanStatusIds(byId, [], NOW)).toEqual([])+ expect(orphanStatusIds(byId, [...projects, { unavailable: true, nodes: [] }], NOW)).toEqual([])+ })+})diff --git a/src/renderer/lib/unreadBadge.ts b/src/renderer/lib/unreadBadge.tsnew file mode 100644index 000000000..1b8d38477--- /dev/null+++ b/src/renderer/lib/unreadBadge.ts@@ -0,0 +1,83 @@+/**+ * The app-level unread count (macOS Dock badge, Windows taskbar overlay, tray) and the boot-time+ * cleanup of status entries that belong to no node.+ *+ * The agent-status table is keyed by node id and persisted, and it is NOT pruned when a node goes+ * away by any path other than the few delete funnels that call `remove` (an outside edit or a sync+ * that drops nodes, an in-place reload, …). Counting every `unread` entry in it therefore counted+ * nodes that no longer exist anywhere — measured on one machine: 633 entries, 20 unread, 1 of them+ * a live node; the Dock said 20 while the only tab badge said 1. The count is now taken over the+ * nodes the projects actually hold, the same set the tab badges count from.+ *+ * Pure, so the rules test without a store.+ */++interface StatusLike {+ unread?: boolean+ lastSeen?: { at: number }+}++interface ProjectLike {+ nodes: ReadonlyArray<{ id: string }>+}++/** The unread node ids as one primitive string — the selector shape the tab bar and the canvas+ * subscribe with, so a working/waiting flip of any agent does not re-render them. */+export function unreadIdsSig(byId: Readonly<Record<string, StatusLike | undefined>>): string {+ let ids = ''+ for (const [id, st] of Object.entries(byId)) if (st?.unread) ids += `${id}|`+ return ids+}++/** Parse `unreadIdsSig` back into a set. */+export function unreadIdSet(sig: string): Set<string> {+ return new Set(sig.split('|').filter(Boolean))+}++/**+ * Unread nodes that exist in a project. Every project counts, CLOSED ones included: a closed+ * project keeps its sessions running and "go to node" reopens it, so its unread finish is still+ * one the user has not seen (the count has always been "across all projects"). What it never+ * counts is an entry whose node is in no project at all.+ */+export function countUnreadInProjects(+ projects: ReadonlyArray<ProjectLike>,+ unread: ReadonlySet<string>+): number {+ if (unread.size === 0) return 0+ const seen = new Set<string>()+ for (const p of projects) for (const n of p.nodes) if (unread.has(n.id)) seen.add(n.id)+ return seen.size+}++/** A status entry whose node is in no project is kept this long after its last hook event before+ * the boot sweep drops it. The node may come back: an SSH project's offline copy can lag the host+ * until the next reconcile, and a git checkout can restore an older canvas — dropping its entry at+ * once would cost it its resume id. */+export const ORPHAN_STATUS_GRACE_MS = 7 * 24 * 60 * 60_000++/**+ * The status ids the boot sweep may drop: their node is in no project, and their last hook event+ * (if any was recorded) is older than the grace window. Returns `[]` — sweep nothing — unless the+ * projects can be trusted to be COMPLETE: an empty list (a fresh, failed or corrupt index load) or+ * any project whose content could not be read (an `unavailable` placeholder carries no nodes)+ * would make every one of its live nodes look orphaned.+ */+export function orphanStatusIds(+ byId: Readonly<Record<string, StatusLike | undefined>>,+ projects: ReadonlyArray<ProjectLike & { unavailable?: boolean }>,+ nowMs: number,+ graceMs: number = ORPHAN_STATUS_GRACE_MS+): string[] {+ if (projects.length === 0 || projects.some((p) => p.unavailable)) return []+ const live = new Set<string>()+ for (const p of projects) for (const n of p.nodes) live.add(n.id)+ const out: string[] = []+ for (const [id, st] of Object.entries(byId)) {+ if (live.has(id)) continue+ const at = st?.lastSeen?.at+ if (typeof at === 'number' && nowMs - at < graceMs) continue+ out.push(id)+ }+ return out+}diff --git a/src/renderer/state/agentStatus.persist.test.ts b/src/renderer/state/agentStatus.persist.test.tsindex 5713736e7..3e576683d 100644--- a/src/renderer/state/agentStatus.persist.test.ts+++ b/src/renderer/state/agentStatus.persist.test.ts@@ -496,3 +496,31 @@ describe('observed Claude account persistence (a plain terminal knows it nowhereexpect(useAgentStatus.getState().byId).toBe(before)})})++describe('removeMany (boot sweep of orphaned entries)', () => {+ it('drops the named entries from both keys in one write each, and ignores unknown ids', async () => {+ const now = Date.now()+ const store = memStorage({+ 'nodeterm.agentStatus': JSON.stringify({+ keep: { unread: true, sessionId: 's1' },+ gone: { unread: true, sessionId: 's2' }+ }),+ 'nodeterm.agentStatus.lastSeen': JSON.stringify({ keep: { at: now }, gone: { at: now } })+ })+ vi.stubGlobal('localStorage', store)+ const { useAgentStatus } = await import('./agentStatus')+ useAgentStatus.getState().removeMany(['gone', 'never-existed'])+ expect(Object.keys(useAgentStatus.getState().byId)).toEqual(['keep'])+ expect(Object.keys(JSON.parse(store.getItem('nodeterm.agentStatus')!))).toEqual(['keep'])+ expect(Object.keys(JSON.parse(store.getItem('nodeterm.agentStatus.lastSeen')!))).toEqual(['keep'])+ })++ it('is a no-op (same state, no write) when no id is present', async () => {+ const store = memStorage({ 'nodeterm.agentStatus': JSON.stringify({ keep: { unread: true } }) })+ vi.stubGlobal('localStorage', store)+ const { useAgentStatus } = await import('./agentStatus')+ const before = useAgentStatus.getState().byId+ useAgentStatus.getState().removeMany(['nope'])+ expect(useAgentStatus.getState().byId).toBe(before)+ })+})diff --git a/src/renderer/state/agentStatus.ts b/src/renderer/state/agentStatus.tsindex ee1c3fc8e..4be0aa008 100644--- a/src/renderer/state/agentStatus.ts+++ b/src/renderer/state/agentStatus.ts@@ -421,6 +421,9 @@ export interface AgentStatusStore {/** Record a /loop iteration (count++ and append its summary). No-op if not looping. */bumpLoop(id: string, message?: string): voidremove(id: string): void+ /** Drop several entries with ONE write of each key (the boot sweep of orphaned entries —+ * `orphanStatusIds` in lib/unreadBadge.ts decides which). Ids not in the table are ignored. */+ removeMany(ids: readonly string[]): void}/** The persisted "last seen" clock (see `AgentNodeStatus.lastSeen`). */@@ -1201,6 +1204,21 @@ export function createAgentStatusSession(// Now, not on the debounce: the deleted node's clock must not outlive it on disk.if (s.byId[id].lastSeen) saveClocks(byId)return { byId }+ }),++ removeMany: (ids) =>+ set((s) => {+ const present = ids.filter((id) => id in s.byId)+ if (present.length === 0) return s+ const byId = { ...s.byId }+ let clocks = false+ for (const id of present) {+ if (byId[id].lastSeen) clocks = true+ delete byId[id]+ }+ save(byId)+ if (clocks) saveClocks(byId)+ return { byId }})}))