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(kanban): review round — hostile assignees, duplicate assignments, rank exhaustion

review25c4c8969743
diff --git a/CLAUDE.md b/CLAUDE.md
index df31244f8..fdcf86ad6 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -5305,8 +5305,12 @@ the Settings section and ShortcutsPanel start disagreeing about what a chord mea
`validKanban` plus per-entry repairs, never inventions: a column that is not an object with
string `id` + `title` is dropped (React cannot render an object title — a render throw
boot-loops the app, the view choice persists), a non-string `category` is dropped, a malformed
- assignment is dropped, every other field round-trips, and a clean board comes back BY IDENTITY
- so a well-formed file is never rewritten.
+ assignment is dropped, a card's `assignees` that is not a list is dropped (entries without a
+ string name + colour filtered), every other field round-trips, and a clean board comes back BY
+ IDENTITY so a well-formed file is never rewritten. **Readers do not trust the load path alone**:
+ `cardAssignees` (`@shared/kanban-labels`) is the one reader of `meta[].assignees` — the board,
+ the card, the member filter, the log diff and the handoff pings all go through it, because an
+ `assignees: 5` iterated raw threw during render (a boot loop) and inside the `assign` verb.
- **Lifecycle category** (`KanbanColumn.category?: unstarted|started|done|closed`,
`@shared/kanban-category`). Every reader goes through `columnCategory`: an unknown STRING reads
as absent but is KEPT in the file (dropping it would erase a newer build's value on an older
@@ -5364,7 +5368,13 @@ the Settings section and ShortcutsPanel start disagreeing about what a chord mea
right after the entry before it in the ARRAY, ties keep array order. Keys are base-62
fractional-index strings with an integer head, so the board's DEFAULT (top insert) is a
decrement: a thousand top inserts stay four characters (a digits-only midpoint scheme grows a
- character every few). Strings never exhaust, so there is no rebalancing. **Every write goes
+ character every few). **A move never throws**: ~1.3k inserts into ONE gap grow a key past
+ `RANK_MAX_LENGTH` (256), and only then is the destination column re-keyed evenly as one
+ contiguous block (`rebalanceColumn`) — the one rebalance this scheme does. A rank STRING readers
+ cannot use is kept in the file (like an unknown category) and re-keyed by the next write into
+ that column; a non-string is dropped. A card assigned twice (a clean git merge can do that)
+ keeps its FIRST assignment everywhere — `sanitizeKanban`, `columnOrder` and `placeAssignment`
+ (which removes every copy of the moved card, as the pre-rank `assignNode` did). **Every write goes
through `placeAssignment`** (renderer `assignNode` AND the relay's `setProjectCardColumn`), which
also keeps the array in rank order so a build that ignores `rank` shows the same column — the
brief's two goals ("a move is a one-line diff" and "keep writing the array in rank order") pull
diff --git a/src/core/workspace-files.test.ts b/src/core/workspace-files.test.ts
index b7271a7aa..393cdceeb 100644
--- a/src/core/workspace-files.test.ts
+++ b/src/core/workspace-files.test.ts
@@ -622,24 +622,61 @@ describe('sanitizeKanban — the board is hostile, git-shared input', () => {
expect(sanitizeKanban(k)?.assignments).toEqual([{ nodeId: 'n', columnId: 'kcol-a' }])
})
- it('keeps a valid rank and drops one that is not (the card then derives from array order)', () => {
+ // Same rule as `category`: a STRING the readers cannot use is kept (they already treat it as
+ // absent, and the next write into that column re-keys it), a non-string is dropped.
+ it('keeps any rank STRING (readers ignore an invalid one), drops a non-string rank', () => {
const k = {
...clean(),
assignments: [
{ nodeId: 'ok', columnId: 'kcol-a', rank: 'a0' },
{ nodeId: 'num', columnId: 'kcol-a', rank: 5 },
{ nodeId: 'junk', columnId: 'kcol-a', rank: 'not a rank!' },
- { nodeId: 'huge', columnId: 'kcol-a', rank: 'a'.repeat(1000) }
+ { nodeId: 'obj', columnId: 'kcol-a', rank: { a: 1 } }
]
}
expect(sanitizeKanban(k)?.assignments).toEqual([
{ nodeId: 'ok', columnId: 'kcol-a', rank: 'a0' },
{ nodeId: 'num', columnId: 'kcol-a' },
- { nodeId: 'junk', columnId: 'kcol-a' },
- { nodeId: 'huge', columnId: 'kcol-a' }
+ { nodeId: 'junk', columnId: 'kcol-a', rank: 'not a rank!' },
+ { nodeId: 'obj', columnId: 'kcol-a' }
])
})
+ // A clean git merge of two machines' boards can leave one card assigned twice. The first entry is
+ // the one `columnForNode` has always answered with, so it is the one kept.
+ it('keeps only the FIRST assignment of a card assigned twice', () => {
+ const k = {
+ ...clean(),
+ assignments: [
+ { nodeId: 'x', columnId: 'kcol-a', rank: 'a0' },
+ { nodeId: 'y', columnId: 'kcol-b', rank: 'a0' },
+ { nodeId: 'x', columnId: 'kcol-b', rank: 'a1' }
+ ]
+ }
+ expect(sanitizeKanban(k)?.assignments).toEqual([
+ { nodeId: 'x', columnId: 'kcol-a', rank: 'a0' },
+ { nodeId: 'y', columnId: 'kcol-b', rank: 'a0' }
+ ])
+ })
+
+ it('normalizes a card\'s assignees: a non-list is dropped, bad entries filtered, the rest kept', () => {
+ const k = {
+ ...clean(),
+ meta: [
+ { nodeId: 'a', assignees: 5, priority: 'high' },
+ { nodeId: 'b', assignees: [{ name: 'enes', color: '#0a84ff' }, 3, { name: 1 }] },
+ { nodeId: 'c', assignees: [{ name: 'sam', color: '#ff453a' }] }
+ ]
+ }
+ expect(sanitizeKanban(k)?.meta).toEqual([
+ { nodeId: 'a', priority: 'high' },
+ { nodeId: 'b', assignees: [{ name: 'enes', color: '#0a84ff' }] },
+ { nodeId: 'c', assignees: [{ name: 'sam', color: '#ff453a' }] }
+ ])
+ const cleanMeta = { ...clean(), meta: [{ nodeId: 'c', assignees: [{ name: 'sam', color: '#ff453a' }] }] }
+ expect(sanitizeKanban(cleanMeta)).toBe(cleanMeta)
+ })
+
it('admits saved views through sanitizeViews (a garbage list is dropped, a clean one kept)', () => {
const views = [{ id: 'kview-1', name: 'Mine', query: { assignees: ['enes'] } }]
const clean = { ...clean_(), views }
diff --git a/src/core/workspace-files.ts b/src/core/workspace-files.ts
index c41782874..2a90580a2 100644
--- a/src/core/workspace-files.ts
+++ b/src/core/workspace-files.ts
@@ -8,7 +8,6 @@ import {
stripSharedNodeExec,
type LocalNodeExecMap
} from '../shared/node-exec'
-import { isValidRank } from '../shared/kanban-rank'
import { sanitizeViews } from '../shared/kanban-views'
import { CLOSED_SESSIONS_CAP } from '../shared/types'
import type { BridgeLink, CanvasNodeState, ClosedSessionEntry, NavStop, Project, ProjectKanban, Viewport, Workspace } from '../shared/types'
@@ -417,9 +416,11 @@ const isRecord = (x: unknown): x is Record<string, unknown> =>
* - a column's `category` that is not a STRING is dropped. An unknown string is KEPT: it may be a
* category a newer build added, and dropping it here would erase that build's data from the
* shared file on our next save. Readers treat it as absent (`columnCategory`);
- * - an assignment that is not an object with string `nodeId` and `columnId` is dropped, and a
- * `rank` that `isValidRank` refuses is dropped from it (the card then derives its position from
- * array order — see @shared/kanban-order).
+ * - an assignment that is not an object with string `nodeId` and `columnId` is dropped, so is a
+ * card's SECOND assignment (a clean git merge can leave two; the first is what readers use), and
+ * a non-string `rank` (a rank string readers cannot use is kept, like an unknown category);
+ * - a card's `assignees` that is not a list is dropped, and entries without a string name and
+ * colour are filtered out of one that is (`cardAssignees` is the matching reader);
* - `views` go through `sanitizeViews` (a non-list is dropped, bad entries repaired or dropped).
* Every other field — known or not — round-trips untouched.
*
@@ -445,14 +446,23 @@ export function sanitizeKanban(k: unknown): ProjectKanban | undefined {
columns.push(c as unknown as ProjectKanban['columns'][number])
}
const assignments: ProjectKanban['assignments'] = []
+ const assigned = new Set<string>()
for (const a of k.assignments as unknown[]) {
if (!isRecord(a) || typeof a.nodeId !== 'string' || typeof a.columnId !== 'string') {
changed = true
continue
}
- // A rank we could not have minted is not a position: drop it and the card derives its place
- // from array order, which every write keeps in rank order anyway (@shared/kanban-order).
- if ('rank' in a && !isValidRank(a.rank)) {
+ // A clean git merge can leave one card assigned twice; the first copy is the one every reader
+ // (`columnForNode`) has always answered with, so it is the one kept.
+ if (assigned.has(a.nodeId)) {
+ changed = true
+ continue
+ }
+ assigned.add(a.nodeId)
+ // Same rule as `category`: a rank STRING the readers cannot use is kept (they treat it as
+ // absent, and the next write into that column re-keys it — @shared/kanban-order); a non-string
+ // is dropped.
+ if ('rank' in a && typeof a.rank !== 'string') {
const { rank: _drop, ...rest } = a
assignments.push(rest as unknown as ProjectKanban['assignments'][number])
changed = true
@@ -460,6 +470,31 @@ export function sanitizeKanban(k: unknown): ProjectKanban | undefined {
}
assignments.push(a as unknown as ProjectKanban['assignments'][number])
}
+ // Card assignees: iterated by the board, the card and the log diff. A non-list is dropped and an
+ // entry without a string name + colour filtered (`cardAssignees` is the matching reader).
+ let meta: unknown = k.meta
+ if (Array.isArray(k.meta)) {
+ let metaChanged = false
+ const out = (k.meta as unknown[]).map((m) => {
+ if (!isRecord(m) || !('assignees' in m)) return m
+ const list = m.assignees
+ if (!Array.isArray(list)) {
+ metaChanged = true
+ const { assignees: _drop, ...rest } = m
+ return rest
+ }
+ const valid = list.filter(
+ (x) => isRecord(x) && typeof x.name === 'string' && typeof x.color === 'string'
+ )
+ if (valid.length === list.length) return m
+ metaChanged = true
+ return { ...m, assignees: valid }
+ })
+ if (metaChanged) {
+ meta = out
+ changed = true
+ }
+ }
// Saved views: their own tolerant reader (@shared/kanban-views), same identity discipline.
let views: ProjectKanban['views'] | undefined = k.views
if ('views' in k) {
@@ -467,7 +502,7 @@ export function sanitizeKanban(k: unknown): ProjectKanban | undefined {
if (views !== k.views) changed = true
}
if (!changed) return k
- const next: ProjectKanban = { ...k, columns, assignments }
+ const next: ProjectKanban = { ...k, columns, assignments, ...(meta !== undefined ? { meta: meta as ProjectKanban['meta'] } : {}) }
if (views) next.views = views
else delete next.views
return next
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index 7f72fbe6b..022742679 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -12784,20 +12784,26 @@ export function Canvas() {
// handoff column (a done column, or a started one past the first) tells them — through the
// existing notification consent, background-only rule and per-node cooldown. Arming the
// fold lets the Stop hook that follows seconds later not notify the same moment twice.
- const notifyPrefs = useSettings.getState().settings
- if (!document.hasFocus() && notifyPrefs.notifyOnClaudeDone && notifyPrefs.notifyConsentAsked) {
- const me = loadIdentity()?.name ?? 'you'
- const now = Date.now()
- for (const h of handoffsFor(prev, next, me)) {
- if (now - (notifyCooldownRef.current[h.nodeId] ?? 0) < 5000) continue
- notifyCooldownRef.current[h.nodeId] = now
- noteHandoff(h.nodeId, now)
- void window.nodeTerminal.notify({
- title: `${ctlProject?.name ?? 'Board'} — handed to you: ${cardTitle(h.nodeId) || 'a card'}`,
- body: `Moved to ${h.columnTitle}.`,
- nodeId: h.nodeId
- })
+ // A side effect of a move that has already been written: whatever goes wrong here must
+ // never cost the verb its reply (an agent waiting on `assign` would hang on it).
+ try {
+ const notifyPrefs = useSettings.getState().settings
+ if (!document.hasFocus() && notifyPrefs.notifyOnClaudeDone && notifyPrefs.notifyConsentAsked) {
+ const me = loadIdentity()?.name ?? 'you'
+ const now = Date.now()
+ for (const h of handoffsFor(prev, next, me)) {
+ if (now - (notifyCooldownRef.current[h.nodeId] ?? 0) < 5000) continue
+ notifyCooldownRef.current[h.nodeId] = now
+ noteHandoff(h.nodeId, now)
+ void window.nodeTerminal.notify({
+ title: `${ctlProject?.name ?? 'Board'} — handed to you: ${cardTitle(h.nodeId) || 'a card'}`,
+ body: `Moved to ${h.columnTitle}.`,
+ nodeId: h.nodeId
+ })
+ }
}
+ } catch (err) {
+ console.warn('[kanban] handoff ping failed', err)
}
const where = columnId
? next.columns.find((c) => c.id === columnId)?.title ?? columnId
diff --git a/src/renderer/components/kanban/CardMetaBar.tsx b/src/renderer/components/kanban/CardMetaBar.tsx
index f05d1b5de..02e81fe2b 100644
--- a/src/renderer/components/kanban/CardMetaBar.tsx
+++ b/src/renderer/components/kanban/CardMetaBar.tsx
@@ -1,7 +1,7 @@
import { useMemo, useState } from 'react'
import { IconClose } from '../icons'
import type { BoardLogAuthor, KanbanPriority, ProjectKanban } from '@shared/types'
-import { cardMeta, labelsForCard, setCardDue, setCardPriority, toggleAssignee } from '../../lib/kanban'
+import { cardAssignees, cardMeta, labelsForCard, setCardDue, setCardPriority, toggleAssignee } from '../../lib/kanban'
import { LabelChips } from './LabelChips'
import { LabelPicker } from './LabelPicker'
import { useShallow } from 'zustand/react/shallow'
@@ -57,7 +57,7 @@ export function CardMetaBar({ nodeId, board, onChange }: CardMetaBarProps) {
return [...seen.values()]
}, [peers, logEntries])
- const assignees = meta?.assignees ?? []
+ const assignees = cardAssignees(meta)
const due = meta?.dueAt
const overdue = due !== undefined && due < Date.now()
const priority = meta?.priority
diff --git a/src/renderer/components/kanban/KanbanView.hostile.test.tsx b/src/renderer/components/kanban/KanbanView.hostile.test.tsx
new file mode 100644
index 000000000..f19589b2b
--- /dev/null
+++ b/src/renderer/components/kanban/KanbanView.hostile.test.tsx
@@ -0,0 +1,78 @@
+// @vitest-environment jsdom
+//
+// A hand-edited or merged project.json can put anything in `meta[].assignees`. The board must still
+// render — a throw here is a boot loop, because the board view choice persists in localStorage.
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import { act } from 'react'
+import { createRoot, type Root } from 'react-dom/client'
+import { KanbanView, type KanbanSession } from './KanbanView'
+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 })
+}))
+
+let root: Root | null = null
+let host: HTMLElement
+const card = (id: string): KanbanSession =>
+ ({ id, title: `Card ${id}`, color: '#fff', kind: 'terminal', spawn: {} }) as unknown as KanbanSession
+
+beforeEach(() => {
+ vi.stubGlobal('IS_REACT_ACT_ENVIRONMENT', true)
+ vi.stubGlobal('ResizeObserver', class { observe(): void {} unobserve(): void {} disconnect(): void {} })
+ ;(window as unknown as { nodeTerminal: unknown }).nodeTerminal = {
+ boardLog: { list: async () => [], onChanged: () => () => {} },
+ settings: { save: async () => {} }
+ }
+ useProjects.setState({ activeProjectId: 'p-hostile' } as never)
+ useAgentStatus.setState({ byId: {} } as never)
+})
+afterEach(() => {
+ if (root) act(() => root!.unmount())
+ root = null
+ host?.remove()
+ document.body.innerHTML = ''
+ vi.unstubAllGlobals()
+})
+
+function mount(k: ProjectKanban): void {
+ host = document.createElement('div')
+ document.body.appendChild(host)
+ root = createRoot(host)
+ const noop = (): void => {}
+ act(() => root!.render(
+ <KanbanView board={k} sessions={['n1', 'n2'].map(card)} onChange={noop} onOpenNode={noop}
+ onCreateNode={noop} onRenameNode={noop} onEditSticky={noop} onDeleteNode={noop}
+ onModalNodeChange={noop} onBrowserNav={noop} onSetIcon={noop} />
+ ))
+}
+
+describe('KanbanView — hostile meta.assignees', () => {
+ for (const bad of [5, {}, true, 'enes', [null, 3, { name: 7 }]]) {
+ it(`renders with assignees=${JSON.stringify(bad)}, and the member filter still works`, () => {
+ const k = {
+ columns: [{ id: 'a', title: 'To Do', color: '#0a84ff' }],
+ assignments: [{ nodeId: 'n1', columnId: 'a' }, { nodeId: 'n2', columnId: 'a' }],
+ meta: [
+ { nodeId: 'n1', assignees: bad, priority: 'high' },
+ { nodeId: 'n2', assignees: [{ name: 'sam', color: '#ff453a' }] }
+ ]
+ } as unknown as ProjectKanban
+ expect(() => mount(k)).not.toThrow()
+ expect(document.querySelectorAll('.kanban-card--session')).toHaveLength(2)
+ act(() => {
+ document.querySelector('.kanban-filter-btn:not(.kanban-closed-toggle):not(.kanban-views-btn)')!
+ .dispatchEvent(new MouseEvent('click', { bubbles: true }))
+ })
+ const sam = [...document.querySelectorAll('.kanban-filter-row')].find((el) => el.textContent?.includes('sam'))!
+ act(() => {
+ sam.dispatchEvent(new MouseEvent('click', { bubbles: true }))
+ })
+ expect(
+ [...document.querySelectorAll('.kanban-card--session .kanban-card__title')].map((el) => el.textContent)
+ ).toEqual(['Card n2'])
+ })
+ }
+})
diff --git a/src/renderer/components/kanban/KanbanView.tsx b/src/renderer/components/kanban/KanbanView.tsx
index ef137d0a2..268167eb1 100644
--- a/src/renderer/components/kanban/KanbanView.tsx
+++ b/src/renderer/components/kanban/KanbanView.tsx
@@ -17,7 +17,7 @@ import { useProjects } from '../../state/projects'
import { useSettings } from '../../state/settings'
import { useBoardWallpaperStyle } from '../../state/wallpaper'
import {
- AT_COLUMN_END, addColumn, assignNode, assignedTo, boardLabels, cardMatchesLabelFilter, cardMeta, columnForNode,
+ AT_COLUMN_END, addColumn, assignNode, assignedTo, boardLabels, cardAssignees, cardMatchesLabelFilter, cardMeta, columnForNode,
deleteColumn, labelsForCard, moveColumn,
nextColumnColor, pruneAssignments, recolorColumn, renameColumn, setColumnCategory, unassigned
} from '../../lib/kanban'
@@ -463,7 +463,7 @@ export const KanbanView = memo(function KanbanView({
const columnCards = useMemo(() => {
// Label filter AND member filter AND status chips (each an OR within itself).
const hasMember = (id: string): boolean =>
- (cardMeta(board, id)?.assignees ?? []).some((a) => assigneeFilter.includes(a?.name))
+ cardAssignees(cardMeta(board, id)).some((a) => assigneeFilter.includes(a.name))
const vis = (ids: string[]): string[] =>
activeLocalFilter.length || assigneeFilter.length || statusChips.length
? ids.filter(
@@ -510,7 +510,7 @@ export const KanbanView = memo(function KanbanView({
const memberNames = useMemo(() => {
const names = new Set<string>(assigneeFilter)
for (const m of Array.isArray(board.meta) ? board.meta : []) {
- for (const a of m?.assignees ?? []) if (typeof a?.name === 'string' && a.name) names.add(a.name)
+ for (const a of cardAssignees(m)) if (a.name) names.add(a.name)
}
return [...names].sort((a, b) => a.localeCompare(b))
}, [board.meta, assigneeFilter])
diff --git a/src/renderer/components/kanban/SessionCard.tsx b/src/renderer/components/kanban/SessionCard.tsx
index 54717d02d..8dc833e9a 100644
--- a/src/renderer/components/kanban/SessionCard.tsx
+++ b/src/renderer/components/kanban/SessionCard.tsx
@@ -9,6 +9,7 @@ import { LabelChips } from './LabelChips'
import { PRIORITIES } from './CardMetaBar'
import type { KanbanSession } from './KanbanView'
import { cardBadge } from '../../lib/kanbanStatusChips'
+import { cardAssignees } from '@shared/kanban-labels'
const PRIO_COLOR = Object.fromEntries(PRIORITIES.map((p) => [p.id, p.color])) as Record<KanbanPriority, string>
@@ -57,7 +58,7 @@ export const SessionCard = memo(function SessionCard({
// can never select cards whose badge says something else. The ranking and its reasons live there.
const badge = cardBadge(session.kind, status)
const stickyPreview = session.kind === 'sticky' ? (session.text ?? '').trim() : ''
- const assignees = meta?.assignees ?? []
+ const assignees = cardAssignees(meta)
const due = meta?.dueAt
const overdue = due !== undefined && due < Date.now()
const priority = meta?.priority
diff --git a/src/renderer/lib/boardKeyNav.test.ts b/src/renderer/lib/boardKeyNav.test.ts
index 59c37e4ea..a25b14601 100644
--- a/src/renderer/lib/boardKeyNav.test.ts
+++ b/src/renderer/lib/boardKeyNav.test.ts
@@ -61,6 +61,16 @@ describe('keyOwnedByControl — the board never takes a key the focused control
expect(keyOwnedByControl(el('DIV', { role: 'slider' }), 'left')).toBe(true)
})
+ it('a BUTTON inside a card still owns Space — pressing it must not open the card', () => {
+ const insideCard = {
+ tagName: 'BUTTON',
+ getAttribute: () => null,
+ closest: (sel: string) => (sel === '[data-kanban-card]' ? el('DIV', { 'data-kanban-card': 'a1' }) : null)
+ } as unknown as Element
+ expect(keyOwnedByControl(insideCard, 'open')).toBe(true)
+ expect(keyOwnedByControl(insideCard, 'next')).toBe(false)
+ })
+
it('a card, the body, or nothing owns no key', () => {
expect(keyOwnedByControl(el('DIV', { 'data-kanban-card': 'a1' }), 'open')).toBe(false)
expect(keyOwnedByControl(el('BODY'), 'open')).toBe(false)
diff --git a/src/renderer/lib/boardKeyNav.ts b/src/renderer/lib/boardKeyNav.ts
index 5b714b4d6..5ac62d82b 100644
--- a/src/renderer/lib/boardKeyNav.ts
+++ b/src/renderer/lib/boardKeyNav.ts
@@ -44,11 +44,14 @@ const SPACE_ACTIVATED = new Set(['BUTTON', 'A', 'SUMMARY', 'INPUT'])
* - a `<select>` owns everything: arrows change its value, letters type-ahead;
* - an ARIA composite widget owns everything, for the same reasons;
* - a button, link, summary or checkbox owns Space — the key that presses it.
- * A card itself owns nothing: it is what the board's keys are for.
+ * A card itself owns nothing: it is what the board's keys are for — but a button inside a card is a
+ * button.
*/
export function keyOwnedByControl(el: Element | null, action: BoardKeyAction): boolean {
if (!el) return false
- if (el.closest?.('[data-kanban-card]')) return false
+ // Only the CARD itself owns nothing. A control INSIDE a card (the context meter, a chip) is still
+ // that control: Space presses it rather than opening the card behind it.
+ if (el.getAttribute?.('data-kanban-card') != null) return false
if (el.tagName === 'SELECT') return true
const role = el.getAttribute?.('role')
if (role && COMPOSITE_ROLES.has(role)) return true
diff --git a/src/renderer/lib/boardLogDiff.test.ts b/src/renderer/lib/boardLogDiff.test.ts
index 3e5ef8cf1..3c63bfa5f 100644
--- a/src/renderer/lib/boardLogDiff.test.ts
+++ b/src/renderer/lib/boardLogDiff.test.ts
@@ -152,3 +152,19 @@ describe('priority events', () => {
])
})
})
+
+// The UI's board-change funnel runs on every commit; a card's assignees come from a hand-editable
+// file and may not be a list at all.
+describe('boardLogEvents — hostile meta.assignees', () => {
+ it('never throws, and reads a non-list as nobody', () => {
+ const cols = [col('a', 'A')]
+ for (const bad of [5, {}, true, 'enes']) {
+ const prev = { ...board(cols, []), meta: [{ nodeId: 'n', assignees: bad }] } as unknown as ProjectKanban
+ const next = {
+ ...board(cols, []),
+ meta: [{ nodeId: 'n', assignees: [{ name: 'sam', color: '#fff' }] }]
+ } as ProjectKanban
+ expect(boardLogEvents(prev, next, title)).toEqual([{ nodeId: 'n', event: { type: 'member-assigned', to: 'sam' } }])
+ }
+ })
+})
diff --git a/src/renderer/lib/boardLogDiff.ts b/src/renderer/lib/boardLogDiff.ts
index 1c5377ae1..964009f8f 100644
--- a/src/renderer/lib/boardLogDiff.ts
+++ b/src/renderer/lib/boardLogDiff.ts
@@ -1,4 +1,5 @@
import type { BoardLogEvent, KanbanCardMeta, ProjectKanban } from '@shared/types'
+import { cardAssignees } from '@shared/kanban-labels'
// Pure prev→next board diff → the events worth recording in the board log. No fs, no IPC:
// the caller computes the next board (renderer/lib/kanban.ts) and asks here what changed.
@@ -82,8 +83,8 @@ export function boardLogEvents(
const pm = prevM.get(nodeId)
const nm = nextM.get(nodeId)
if (!nm && !cardTitle(nodeId)) continue // node gone (prune) → nothing to narrate
- const pa = pm?.assignees ?? []
- const na = nm?.assignees ?? []
+ const pa = cardAssignees(pm)
+ const na = cardAssignees(nm)
for (const a of na) if (!pa.some((x) => x.name === a.name))
out.push({ nodeId, event: { type: 'member-assigned', to: a.name } })
for (const a of pa) if (!na.some((x) => x.name === a.name))
diff --git a/src/renderer/lib/handoffPings.test.ts b/src/renderer/lib/handoffPings.test.ts
index 44fe4052e..93b63c852 100644
--- a/src/renderer/lib/handoffPings.test.ts
+++ b/src/renderer/lib/handoffPings.test.ts
@@ -116,3 +116,27 @@ describe('Canvas wiring (source pins)', () => {
expect(source()).toContain("if (sound === 'done' && suppressDoneAfterHandoff(e.nodeId, Date.now())) return")
})
})
+
+// The assign verb runs handoffsFor AFTER its board write; a throw there left the verb without a
+// reply. A card's assignees come from a hand-editable file.
+describe('handoffsFor — hostile meta.assignees', () => {
+ it('never throws, and pings nobody for a card whose assignees are not a list', () => {
+ for (const bad of [5, {}, true, 'enes']) {
+ const meta = [{ nodeId: 'n', assignees: bad }] as unknown as ProjectKanban['meta']
+ const before = board([{ nodeId: 'n', columnId: 'doing' }], meta)
+ const after = board([{ nodeId: 'n', columnId: 'done' }], meta)
+ expect(() => handoffsFor(before, after, 'enes')).not.toThrow()
+ expect(handoffsFor(before, after, 'enes')).toEqual([])
+ }
+ })
+
+ it('the assign handler cannot lose its reply to a failed ping (source pin)', () => {
+ const src = readFileSync('src/renderer/canvas/Canvas.tsx', 'utf8')
+ const assign = src.slice(src.indexOf("case 'assign': {"), src.indexOf("case 'assign': {") + 6000)
+ const ping = assign.indexOf('handoffsFor(prev, next, me)')
+ const guard = assign.lastIndexOf('try {', ping)
+ expect(guard).toBeGreaterThan(-1)
+ expect(assign.indexOf('} catch', ping)).toBeGreaterThan(ping)
+ expect(assign.indexOf('reply({', ping)).toBeGreaterThan(assign.indexOf('} catch', ping))
+ })
+})
diff --git a/src/renderer/lib/handoffPings.ts b/src/renderer/lib/handoffPings.ts
index eae75dbee..51ad6a69b 100644
--- a/src/renderer/lib/handoffPings.ts
+++ b/src/renderer/lib/handoffPings.ts
@@ -20,7 +20,7 @@
*/
import type { KanbanColumnCategory, ProjectKanban } from '@shared/types'
import { columnCategory } from '@shared/kanban-category'
-import { cardMeta } from './kanban'
+import { cardAssignees, cardMeta } from './kanban'
export const HANDOFF_FOLD_MS = 2 * 60_000
@@ -42,8 +42,7 @@ export function handoffsFor(prev: ProjectKanban, next: ProjectKanban, me: string
const category = columnCategory(column)
const handoff = category === 'done' || (category === 'started' && a.columnId !== firstStarted)
if (!column || !handoff) continue
- const assignees = cardMeta(next, a.nodeId)?.assignees ?? []
- if (!assignees.some((p) => p?.name === me)) continue
+ if (!cardAssignees(cardMeta(next, a.nodeId)).some((p) => p.name === me)) continue
out.push({ nodeId: a.nodeId, columnId: a.columnId, columnTitle: column.title, category: category as Handoff['category'] })
}
return out
diff --git a/src/shared/kanban-hostile.test.ts b/src/shared/kanban-hostile.test.ts
new file mode 100644
index 000000000..f467b187e
--- /dev/null
+++ b/src/shared/kanban-hostile.test.ts
@@ -0,0 +1,40 @@
+// Review round on #1004: shapes a hand-edited or git-merged `.nodeterm/project.json` can hold that
+// the board must survive — a card's `assignees` that is not a list, and an assignment duplicated
+// by a clean textual merge.
+import { describe, expect, it } from 'vitest'
+import type { KanbanCardMeta, ProjectKanban } from './types'
+import { cardAssignees } from './kanban-labels'
+import { columnOrder, placeAssignment } from './kanban-order'
+
+describe('cardAssignees — the one tolerant reader of meta.assignees', () => {
+ const meta = (assignees: unknown): KanbanCardMeta => ({ nodeId: 'n', assignees } as unknown as KanbanCardMeta)
+
+ it('a non-list reads as nobody, never a throw', () => {
+ for (const bad of [5, {}, true, 'enes', null, undefined]) expect(cardAssignees(meta(bad))).toEqual([])
+ expect(cardAssignees(undefined)).toEqual([])
+ })
+
+ it('keeps only entries with a string name and colour', () => {
+ const ok = { name: 'enes', color: '#0a84ff' }
+ expect(cardAssignees(meta([ok, null, 3, { name: 7, color: '#fff' }, { name: 'sam' }, 'x']))).toEqual([ok])
+ })
+})
+
+describe('an assignment duplicated by a git merge', () => {
+ const dup = (): ProjectKanban['assignments'] => [
+ { nodeId: 'X', columnId: 'c1', rank: 'a0' },
+ { nodeId: 'Y', columnId: 'c2', rank: 'a0' },
+ { nodeId: 'X', columnId: 'c1', rank: 'a1' }
+ ]
+
+ it('moving the card removes EVERY copy of it (as the pre-rank assignNode did)', () => {
+ const out = placeAssignment(dup(), 'X', 'c2', 'top')
+ expect(out.filter((a) => a.nodeId === 'X')).toHaveLength(1)
+ expect(columnOrder(out, 'c1').map((a) => a.nodeId)).toEqual([])
+ expect(columnOrder(out, 'c2').map((a) => a.nodeId)).toEqual(['X', 'Y'])
+ })
+
+ it('a column never lists one card twice (no duplicate React keys), first copy wins', () => {
+ expect(columnOrder(dup(), 'c1').map((a) => a.nodeId)).toEqual(['X'])
+ })
+})
diff --git a/src/shared/kanban-labels.ts b/src/shared/kanban-labels.ts
index 622da05e8..5831f6d07 100644
--- a/src/shared/kanban-labels.ts
+++ b/src/shared/kanban-labels.ts
@@ -20,6 +20,19 @@ export function cardMeta(k: ProjectKanban, nodeId: string): KanbanCardMeta | und
export const metaList = (k: ProjectKanban): KanbanCardMeta[] => (Array.isArray(k.meta) ? k.meta : [])
+/** The ONE tolerant reader of a card's assignees. The value comes from a hand-editable, git-shared
+ * file, so a non-list reads as nobody and an entry without a string `name` + `color` is skipped —
+ * a board that iterated it raw threw `not iterable` during render, i.e. a boot loop. */
+export function cardAssignees(meta: KanbanCardMeta | undefined): BoardLogAuthor[] {
+ const list: unknown = meta?.assignees
+ if (!Array.isArray(list)) return []
+ return list.filter(
+ (a): a is BoardLogAuthor =>
+ !!a && typeof a === 'object' && typeof (a as BoardLogAuthor).name === 'string' &&
+ typeof (a as BoardLogAuthor).color === 'string'
+ )
+}
+
/** Writes one card's meta back; an entry with no fields left is DROPPED (absent = clean file),
* and an emptied meta array drops the key entirely. */
export function withCardMeta(
@@ -47,10 +60,9 @@ export function toggleAssignee(
person: BoardLogAuthor
): ProjectKanban {
const cur = cardMeta(k, nodeId)
- const had = (cur?.assignees ?? []).some((a) => a.name === person.name)
- const assignees = had
- ? (cur?.assignees ?? []).filter((a) => a.name !== person.name)
- : [...(cur?.assignees ?? []), person]
+ const current = cardAssignees(cur)
+ const had = current.some((a) => a.name === person.name)
+ const assignees = had ? current.filter((a) => a.name !== person.name) : [...current, person]
return withCardMeta(k, nodeId, {
assignees,
dueAt: cur?.dueAt,
diff --git a/src/shared/kanban-order.test.ts b/src/shared/kanban-order.test.ts
index cd5df59a1..2121fb8d1 100644
--- a/src/shared/kanban-order.test.ts
+++ b/src/shared/kanban-order.test.ts
@@ -162,3 +162,31 @@ describe('placeAssignment', () => {
}
})
})
+
+// ~1.3k inserts into ONE gap grow a key past RANK_MAX_LENGTH; the placement used to hand that key
+// back to rankBetween on the next move and throw inside the move handler. A move must never throw:
+// past that point the column is re-keyed (the one rebalance this scheme ever does).
+describe('placeAssignment — never throws, even when one gap is exhausted', () => {
+ // 1700 crosses the point (~1525 inserts into one gap) where the next key would pass
+ // RANK_MAX_LENGTH; the moved card's neighbour is always the same top card.
+ it('1700 inserts just below the top card stay ordered, valid and in array order', { timeout: 30_000 }, () => {
+ let list: A[] = []
+ list = placeAssignment(list, 'first', 'c', 'top')
+ list = placeAssignment(list, 'second', 'c', 'end')
+ let second = 'second'
+ for (let i = 0; i < 1700; i++) {
+ list = placeAssignment(list, `x${i}`, 'c', { before: second })
+ second = `x${i}`
+ if (i % 200 === 0 || (i > 1500 && i < 1560)) {
+ const ranks = columnOrder(list, 'c').map((e) => e.rank)
+ expect(ranks.every(isValidRank), `step ${i}`).toBe(true)
+ }
+ }
+ const order = columnOrder(list, 'c').map((e) => e.nodeId)
+ expect(order[0]).toBe('first')
+ expect(order[1]).toBe('x1699')
+ expect(order.at(-1)).toBe('second')
+ expect(order).toHaveLength(1702)
+ expect(arrayOrder(list, 'c')).toEqual(order)
+ })
+})
diff --git a/src/shared/kanban-order.ts b/src/shared/kanban-order.ts
index 0c2627815..b28c6729a 100644
--- a/src/shared/kanban-order.ts
+++ b/src/shared/kanban-order.ts
@@ -19,6 +19,10 @@
* own array positions. A board's first write into an unranked column therefore ranks it once.
* A reorder WITHIN a column always moves a block: the array must change for an old build to see it.
*
+ * A move NEVER throws. Keys never run out between two distinct ones, but ~1.3k inserts into one
+ * gap grow a key past `RANK_MAX_LENGTH`, beyond which it is not a valid rank: at that point (and
+ * only then) the destination column is re-keyed evenly — `rebalanceColumn`.
+ *
* Generic over the entry type and spread-preserving, so the host core can run it on the raw
* project-file objects (the relay's move verb) and every unknown field round-trips.
*/
@@ -36,9 +40,14 @@ export type CardAnchor = 'top' | 'end' | { before: string }
/** One column's entries in board order (see the module note). Never throws. */
export function columnOrder<A extends RankedEntry>(list: readonly A[], columnId: string): A[] {
const entries: Array<{ a: A; idx: number; key: string }> = []
+ const seen = new Set<string>()
let prev = ''
list.forEach((a, idx) => {
if (!a || a.columnId !== columnId) return
+ // A card assigned twice (a clean git merge can do that) is listed once — the first copy, the
+ // one `columnForNode` answers with. Two copies would be duplicate React keys in the column.
+ if (seen.has(a.nodeId)) return
+ seen.add(a.nodeId)
const key = isValidRank(a.rank) ? a.rank : prev
entries.push({ a, idx, key })
prev = key
@@ -87,17 +96,48 @@ export function placeAssignment<A extends RankedEntry>(
): A[] {
const i0 = list.findIndex((e) => e?.nodeId === nodeId)
const old = i0 === -1 ? undefined : list[i0]
- const without = i0 === -1 ? [...list] : [...list.slice(0, i0), ...list.slice(i0 + 1)]
- let col = columnOrder(without, columnId)
+ // EVERY copy of the moved card goes (the pre-rank assignNode filtered them all out too), and so
+ // does every later copy of any other card: a clean git merge can leave a card assigned twice, and
+ // the first copy is the one every reader answers with.
+ const seen = new Set<string>([nodeId])
+ const without = list.filter((e) => {
+ if (!e || seen.has(e.nodeId)) return false
+ seen.add(e.nodeId)
+ return true
+ })
+ const col = columnOrder(without, columnId)
const anchorIdx = typeof anchor === 'object' ? col.findIndex((e) => e.nodeId === anchor.before) : -1
const at = anchor === 'end' ? col.length : anchorIdx !== -1 ? anchorIdx : 0
- if (old && old.columnId === columnId && columnOrder(list, columnId).indexOf(old) === at) {
+ const clean = without.length === list.length - 1
+ if (clean && old && old.columnId === columnId && columnOrder(list, columnId).indexOf(old) === at) {
return list as A[]
}
+ // `i0` indexes the ORIGINAL list; entries before it were all kept (it is the moved card's first
+ // copy and nothing earlier can be a duplicate of something later), so it is the same slot here.
+ try {
+ const placed = placeWithRanks(without, col, nodeId, columnId, at, old, i0)
+ if (placed) return placed
+ } catch {
+ // Fall through: a move never throws.
+ }
+ return rebalanceColumn(without, col, nodeId, columnId, at, old, i0)
+}
- // Repair the destination column, then make its array slots agree with its order.
+/** The ordinary placement: repair the column if it must be, mint ONE rank, move as little as
+ * possible. Null when a key it would write is not a valid rank (a gap exhausted past
+ * `RANK_MAX_LENGTH` — about 1.3k inserts into one gap). */
+function placeWithRanks<A extends RankedEntry>(
+ without: A[],
+ col: A[],
+ nodeId: string,
+ columnId: string,
+ at: number,
+ old: A | undefined,
+ i0: number
+): A[] | null {
let arr = without
const fixes = repairRanks(col)
+ if ([...fixes.values()].some((k) => !isValidRank(k))) return null
if (fixes.size) {
arr = arr.map((e) => (fixes.has(e) ? { ...e, rank: fixes.get(e)! } : e))
col = columnOrder(arr, columnId)
@@ -116,6 +156,7 @@ export function placeAssignment<A extends RankedEntry>(
const prev = at > 0 ? col[at - 1] : undefined
const next = at < col.length ? col[at] : undefined
const rank = rankBetween(prev?.rank ?? null, next?.rank ?? null)
+ if (!isValidRank(rank)) return null
const moved = (old ? { ...old, columnId, rank } : { nodeId, columnId, rank }) as A
const pIdx = prev ? arr.indexOf(prev) : -1
@@ -124,3 +165,29 @@ export function placeAssignment<A extends RankedEntry>(
const pos = fits ? i0 : sIdx !== -1 ? sIdx : pIdx !== -1 ? pIdx + 1 : i0 !== -1 ? i0 : arr.length
return [...arr.slice(0, pos), moved, ...arr.slice(pos)]
}
+
+/**
+ * The one rebalance this scheme ever does, and only when a gap is exhausted: the destination
+ * column gets evenly spaced fresh keys in its current order (the moved card at `at`), written as
+ * ONE contiguous block where the column's first entry sat — so the array stays in rank order for
+ * builds that ignore `rank`, and no other column is touched. A big diff, once, instead of a throw
+ * inside the move handler.
+ */
+function rebalanceColumn<A extends RankedEntry>(
+ without: A[],
+ col: A[],
+ nodeId: string,
+ columnId: string,
+ at: number,
+ old: A | undefined,
+ i0: number
+): A[] {
+ const base = (old ? { ...old, columnId } : { nodeId, columnId }) as A
+ const order = [...col.slice(0, at), base, ...col.slice(at)]
+ const keys = ranksBetween(null, null, order.length)
+ const block = order.map((e, i) => ({ ...e, rank: keys[i] }) as A)
+ const first = without.findIndex((e) => e.columnId === columnId)
+ const cut = first !== -1 ? first : i0 !== -1 ? i0 : without.length
+ const others = (part: A[]): A[] => part.filter((e) => e.columnId !== columnId)
+ return [...others(without.slice(0, cut)), ...block, ...others(without.slice(cut))]
+}
diff --git a/test/acceptance/kanban-rank-interop.test.ts b/test/acceptance/kanban-rank-interop.test.ts
new file mode 100644
index 000000000..9a6aa29bc
--- /dev/null
+++ b/test/acceptance/kanban-rank-interop.test.ts
@@ -0,0 +1,66 @@
+import { describe, expect, it } from 'vitest'
+import type { ProjectKanban } from '../../src/shared/types'
+import { columnOrder } from '../../src/shared/kanban-order'
+import { AT_COLUMN_END, assignNode, deleteColumn, pruneAssignments } from '../../src/renderer/lib/kanban'
+import { setProjectCardColumn } from '../../src/core/project-kanban-write'
+
+/**
+ * The old-build contract across every writer at once: this build's `assignNode` (renderer), the
+ * relay's `setProjectCardColumn` (core, raw file text), a build that predates ranks (its
+ * `assignNode`, reproduced below — it rebuilds the moved entry WITHOUT `rank`), and the prunes and
+ * column deletions in between. After any interleaving, every column's array order must equal the
+ * order this build shows — so a build that ignores `rank` shows the same board.
+ *
+ * Cross-layer (shared + renderer + core), which production layering forbids inside src/.
+ */
+
+/** A pre-rank build's assignNode, verbatim in behaviour: append at the end when unanchored. */
+function preRankAssign(k: ProjectKanban, nodeId: string, columnId: string | null, before: string | null): ProjectKanban {
+ if (nodeId === before) return k
+ if (columnId === null) return { ...k, assignments: k.assignments.filter((a) => a.nodeId !== nodeId) }
+ if (!k.columns.some((c) => c.id === columnId)) return k
+ const moved = { nodeId, columnId }
+ const without = k.assignments.filter((a) => a.nodeId !== nodeId)
+ const b = before ? without.find((a) => a.nodeId === before && a.columnId === columnId) : undefined
+ const idx = b ? without.indexOf(b) : -1
+ const at = idx === -1 ? without.length : idx
+ return { ...k, assignments: [...without.slice(0, at), moved, ...without.slice(at)] }
+}
+
+const arrayOrder = (k: ProjectKanban, c: string): string[] =>
+ k.assignments.filter((a) => a && a.columnId === c).map((a) => a.nodeId)
+const shownOrder = (k: ProjectKanban, c: string): string[] => columnOrder(k.assignments, c).map((a) => a.nodeId)
+
+describe('rank order vs array order across old, new and relay writers', () => {
+ it('holds after every step of a seeded random interleaving', () => {
+ let seed = 12345
+ const rnd = (n: number): number => {
+ seed = (seed * 1103515245 + 12345) & 0x7fffffff
+ return seed % n
+ }
+ const ids = Array.from({ length: 12 }, (_, i) => `n${i}`)
+ let mismatches = 0
+ for (let run = 0; run < 200; run++) {
+ let k: ProjectKanban = { columns: ['c1', 'c2', 'c3'].map((id) => ({ id, title: id, color: '' })), assignments: [] }
+ for (let step = 0; step < 60; step++) {
+ const op = rnd(10)
+ const node = ids[rnd(ids.length)]
+ const col = k.columns.length ? k.columns[rnd(k.columns.length)].id : null
+ const inCol = col ? arrayOrder(k, col) : []
+ const before = inCol.length && rnd(2) ? inCol[rnd(inCol.length)] : null
+ if (op < 4) k = assignNode(k, node, col, rnd(3) === 0 ? AT_COLUMN_END : before)
+ else if (op < 6) k = preRankAssign(k, node, col, before)
+ else if (op < 8) {
+ const out = setProjectCardColumn(JSON.stringify({ version: 1, rev: 1, nodes: [], kanban: k }), node, col, new Date())
+ if (out) k = JSON.parse(out).kanban
+ } else if (op === 8) k = pruneAssignments(k, ids.filter(() => rnd(8) !== 0))
+ else if (k.columns.length > 1 && rnd(4) === 0) {
+ k = deleteColumn(k, k.columns[rnd(k.columns.length)].id)
+ k = { ...k, columns: [...k.columns, { id: `c${run}-${step}`, title: 'x', color: '' }] }
+ }
+ for (const c of k.columns) if (arrayOrder(k, c.id).join() !== shownOrder(k, c.id).join()) mismatches++
+ }
+ }
+ expect(mismatches).toBe(0)
+ })
+})