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
feat(kanban): projects.editCardLabels relay verb for the phone's label sheet
enese772bdbed07b
diff --git a/CLAUDE.md b/CLAUDE.mdindex f108819c7..4a1852718 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -4054,7 +4054,14 @@ the Settings section and ShortcutsPanel start disagreeing about what a chord meachanges via fs.watch; desktop SSH projects poll 5s while subscribed; inline projects show ahint. Relay tabs BRIDGE boardLog to the host (pre-dispatch `sharedProjectId` scope guard in therelay dispatch — an out-of-scope projectId is refused before any registry/path resolution; a- connection drop replays its outstanding onChanged unsubscribes). Deliberate v1 gaps: column-level+ connection drop replays its outstanding onChanged unsubscribes). **The relay-guest scope jail is+ keyed on channel CLASS, not a per-feature list** (`main/remote/relay-project-scope.ts`): every+ method whose name starts with `githubIssues:` / `board-log:` / `projects.` is project-scoped, and+ one the table cannot read a projectId out of is REFUSED on a scoped session. The switch it+ replaced had a `default: not project-scoped` arm, so a new verb in one of those namespaces reached+ another project's data with no refusal anywhere. A new channel in a scoped class therefore needs a+ table row to become reachable — and `relay-project-scope.test.ts` fails if a live IPC channel in a+ scoped class has none, so the fail-closed default cannot silently swallow a shipped verb. Deliberate v1 gaps: column-levelevents are stored but no card feed shows them; canvas-born nodes get no card-created; nocard-deleted type.Per-column "+ New session" menus create agents/terminal/sticky nodes assigned to the column@@ -4063,11 +4070,24 @@ the Settings section and ShortcutsPanel start disagreeing about what a chord meaas a SIBLING of the node root — the roots are overflow:hidden — hidden for Ungrouped/dangling,click opens the board). Server Edition works as-is (pure renderer + workspace.save). Scope: noagent-driven card movement yet, no board undo.- **Mobile (nodeterm-ios) reaches the board through two relay verbs**, both landing in- `WorkspaceStore.ensureRemoteBoard` / `setRemoteCardColumn` (host-service `handleKanban`; wired in- `main/index.ts`'s `hostBridge.kanban`; pure transforms in `core/project-kanban-write.ts`):- `projects.ensureBoard` seeds the default columns on a project that has none, `projects.setCardColumn`- moves one card. Three things make them necessary rather than convenient. (1) The desktop board is a+ **Mobile (nodeterm-ios) reaches the board through three relay verbs**, all landing in+ `WorkspaceStore.ensureRemoteBoard` / `setRemoteCardColumn` / `editRemoteCardLabels` (host-service+ `handleKanban`; wired in `main/index.ts`'s `hostBridge.kanban`; pure transforms in+ `core/project-kanban-write.ts`): `projects.ensureBoard` seeds the default columns on a project that+ has none, `projects.setCardColumn` moves one card, and `projects.editCardLabels` adds / removes /+ creates **board labels** on one card (the phone's long-press label sheet, 2026-09). There is ONE+ label model — the per-project palette in `kanban.labels` plus per-card ids in `kanban.meta[].labels`+ — and the label verb writes it through the SAME transforms the canvas node's "+ Label" row and the+ kanban card use: the card-meta + label half of `lib/kanban.ts` moved to `@shared/kanban-labels`+ (re-exported, renderer call sites unchanged) so core can apply it; a test pins that a phone edit+ produces the board `toggleCardLabel` produces. Params are validated at the write site+ (`parseCardLabelEdit`: bounded control-free ids, 1–60-char control-free names, colour from the closed+ palette, no id both added and removed) because they land in a git-shared, hand-editable file; a+ created name matching an existing label case-insensitively REUSES it (the picker offers no Create+ on an exact match); the first label on a board-less project seeds the default board, as the+ desktop's first "+ Label" does; a stale `add` answers `edited:false` with the CURRENT palette so the+ phone can redraw. Deleting/renaming palette entries is deliberately desktop-only (it touches every+ card). The iOS direct-SSH path has a Swift twin of the transform for projects on the host it dials. Three things make them necessary rather than convenient. (1) The desktop board is aLAZY default — `kanban` is not written until the user's first board edit — so most project filescarry NO board and the phone, which knows a project only by its file, could not offer one(measured: 1 of 13 project files on the author's machine had a `kanban` block). The default columnsdiff --git a/CONTRIBUTING.md b/CONTRIBUTING.mdindex 0223794bd..d8682eb05 100644--- a/CONTRIBUTING.md+++ b/CONTRIBUTING.md@@ -248,6 +248,12 @@ lane unaffected.the relay, so a key that works locks it onto a path that cannot work. CLAUDE.md, "Remote access",has the details.+- **A relay channel that names a project needs a row in `relay-project-scope.ts`.** A relay guest+ bound to one shared project must never reach another, and the jail is keyed on channel class:+ anything named `githubIssues:*`, `board-log:*` or `projects.*` is refused on a scoped session+ unless that table can read its projectId. Add the row in the same PR as the channel, or the verb+ is refused for every scoped guest (and `relay-project-scope.test.ts` goes red telling you so).+- **Normalize BOTH sides of a path comparison, through one function.** A marker normalized whereit is built and matched raw where it is used is a no-op on the machine you wrote it on and asilent defect on Windows. That is issue #558: the managed-hook marker was folded to `/` whilediff --git a/src/core/project-kanban-write.labels.test.ts b/src/core/project-kanban-write.labels.test.tsnew file mode 100644index 000000000..f67610883--- /dev/null+++ b/src/core/project-kanban-write.labels.test.ts@@ -0,0 +1,192 @@+// The phone's label verb (`projects.editCardLabels`) against the ONE label model the desktop edits.+// What these pin:+// - Round trip: a label the phone adds is the label the canvas node's "+ Label" row and the kanban+// card render (`labelsForCard`), and a label the desktop picker created is one the phone can+// apply/remove by id — both directions through the same `@shared/kanban-labels` transforms.+// - Adding the first label seeds the default board, exactly like the desktop's first "+ Label".+// - Write-site validation of hostile input: ids, names, colours, contradictory edits.+// - Nothing else in the file moves: columns, assignments, other cards' meta, this card's other meta.+import { describe, expect, it } from 'vitest'+import {+ LABEL_NAME_MAX,+ editProjectCardLabels,+ parseCardLabelEdit,+ type CardLabelEdit+} from './project-kanban-write'+import { DEFAULT_BOARD_COLUMNS } from '../shared/kanban-default-board'+import { createLabel, labelsForCard, toggleCardLabel } from '../shared/kanban-labels'+import type { ProjectKanban } from '../shared/types'++const NOW = new Date('2026-09-23T12:00:00.000Z')++function file(extra: Record<string, unknown> = {}): string {+ return JSON.stringify({+ version: 1,+ rev: 3,+ savedAt: '2026-01-01T00:00:00.000Z',+ name: 'p',+ color: '#0a84ff',+ nodes: [{ id: 'term-a', kind: 'terminal' }, { id: 'term-b', kind: 'terminal' }],+ ...extra+ })+}+const parse = (s: string | null): Record<string, any> => JSON.parse(s ?? 'null')++const BOARD: ProjectKanban = {+ columns: [{ id: 'kcol-1', title: 'Doing', color: '#fff' }],+ assignments: [{ nodeId: 'term-a', columnId: 'kcol-1' }],+ labels: [+ { id: 'klbl-bug', name: 'bug', color: 'red' },+ { id: 'klbl-ui', name: 'UI', color: 'blue' }+ ],+ meta: [+ { nodeId: 'term-a', priority: 'high', labels: ['klbl-bug'] },+ { nodeId: 'term-b', labels: ['klbl-ui'] }+ ]+}+const edit = (e: CardLabelEdit): CardLabelEdit => parseCardLabelEdit(e)!++describe('editProjectCardLabels — round trip with the desktop label model', () => {+ it('an id the phone adds is what the canvas node / kanban card then render', () => {+ const out = parse(editProjectCardLabels(file({ kanban: BOARD }), 'term-a', edit({ add: ['klbl-ui'] }), NOW))+ expect(labelsForCard(out.kanban, 'term-a').map((l) => l.name)).toEqual(['bug', 'UI'])+ expect(out.rev).toBe(4)+ expect(out.savedAt).toBe(NOW.toISOString())+ })++ it('produces the SAME board the desktop picker (toggleCardLabel) produces for the same edit', () => {+ const phone = parse(editProjectCardLabels(file({ kanban: BOARD }), 'term-a', edit({ add: ['klbl-ui'] }), NOW))+ const desktop = toggleCardLabel(BOARD, 'term-a', 'klbl-ui')+ expect(phone.kanban).toEqual(desktop)+ })++ it('removes a label the desktop created, and drops the meta entry when nothing is left', () => {+ const out = parse(editProjectCardLabels(file({ kanban: BOARD }), 'term-b', edit({ remove: ['klbl-ui'] }), NOW))+ expect(out.kanban.meta.find((m: { nodeId: string }) => m.nodeId === 'term-b')).toBeUndefined()+ // the palette entry itself survives — "remove from this session" is not "delete the label"+ expect(out.kanban.labels.map((l: { id: string }) => l.id)).toEqual(['klbl-bug', 'klbl-ui'])+ })++ it('a created label joins the palette with a desktop-shaped id and is applied to the card', () => {+ const out = parse(+ editProjectCardLabels(file({ kanban: BOARD }), 'term-b', edit({ create: [{ name: ' ship it ', color: 'green' }] }), NOW)+ )+ const created = out.kanban.labels.at(-1)+ expect(created).toMatchObject({ name: 'ship it', color: 'green' })+ expect(created.id).toMatch(/^klbl-[a-z0-9]{1,8}$/)+ expect(labelsForCard(out.kanban, 'term-b').map((l) => l.name)).toEqual(['UI', 'ship it'])+ // …and the desktop can toggle it off again by that id+ expect(labelsForCard(toggleCardLabel(out.kanban, 'term-b', created.id), 'term-b').map((l) => l.name)).toEqual(['UI'])+ })++ it('a label the desktop picker just created is immediately addable from the phone', () => {+ const { k, id } = createLabel(BOARD, 'docs', 'yellow')+ const out = parse(editProjectCardLabels(file({ kanban: k }), 'term-b', edit({ add: [id] }), NOW))+ expect(labelsForCard(out.kanban, 'term-b').map((l) => l.name)).toEqual(['UI', 'docs'])+ })++ it('creating a name that already exists (case-insensitive) REUSES it instead of minting a duplicate', () => {+ const out = parse(editProjectCardLabels(file({ kanban: BOARD }), 'term-b', edit({ create: [{ name: 'BUG', color: 'gray' }] }), NOW))+ expect(out.kanban.labels).toHaveLength(2)+ expect(out.kanban.meta.find((m: { nodeId: string }) => m.nodeId === 'term-b').labels).toEqual(['klbl-ui', 'klbl-bug'])+ })++ it('keeps columns, assignments, other cards and this card\'s other meta exactly as they were', () => {+ const out = parse(editProjectCardLabels(file({ kanban: BOARD, bridges: [{ id: 'x' }] }), 'term-a', edit({ add: ['klbl-ui'] }), NOW))+ expect(out.kanban.columns).toEqual(BOARD.columns)+ expect(out.kanban.assignments).toEqual(BOARD.assignments)+ expect(out.kanban.meta.find((m: { nodeId: string }) => m.nodeId === 'term-b')).toEqual({ nodeId: 'term-b', labels: ['klbl-ui'] })+ expect(out.kanban.meta.find((m: { nodeId: string }) => m.nodeId === 'term-a').priority).toBe('high')+ expect(out.bridges).toEqual([{ id: 'x' }])+ })++ it('keeps a GitHub mapping block it has no UI for', () => {+ const github = { columnMappings: [{ columnId: 'kcol-1', label: 'doing' }] }+ const out = parse(editProjectCardLabels(file({ kanban: { ...BOARD, github } }), 'term-a', edit({ add: ['klbl-ui'] }), NOW))+ expect(out.kanban.github).toEqual(github)+ })+})++describe('editProjectCardLabels — the first label seeds the board', () => {+ it('a project with no board gets the default columns plus the label', () => {+ const out = parse(+ editProjectCardLabels(file(), 'term-a', edit({ create: [{ name: 'bug', color: 'red' }] }), NOW, () => 'kcol-x')+ )+ expect(out.kanban.columns.map((c: { title: string }) => c.title)).toEqual(DEFAULT_BOARD_COLUMNS.map((c) => c.title))+ expect(out.kanban.assignments).toEqual([])+ expect(labelsForCard(out.kanban, 'term-a').map((l) => l.name)).toEqual(['bug'])+ })++ it('a no-op on a project with no board writes nothing (no board nobody asked for)', () => {+ expect(editProjectCardLabels(file(), 'term-a', edit({ remove: ['klbl-bug'] }), NOW)).toBeNull()+ })+})++describe('editProjectCardLabels — refusals (null, nothing written)', () => {+ it('refuses an add naming a label this palette does not have (stale phone copy)', () => {+ expect(editProjectCardLabels(file({ kanban: BOARD }), 'term-a', edit({ add: ['klbl-gone'] }), NOW)).toBeNull()+ })++ it('writes nothing for an edit that is already satisfied — a retry must not churn rev', () => {+ expect(editProjectCardLabels(file({ kanban: BOARD }), 'term-a', edit({ add: ['klbl-bug'] }), NOW)).toBeNull()+ })++ it('refuses a kanban block of a shape it must not replace', () => {+ expect(editProjectCardLabels(file({ kanban: [1, 2] }), 'term-a', edit({ add: ['klbl-bug'] }), NOW)).toBeNull()+ expect(editProjectCardLabels(file({ kanban: 'x' }), 'term-a', edit({ add: ['klbl-bug'] }), NOW)).toBeNull()+ })++ it('refuses a file that is not the project shape', () => {+ expect(editProjectCardLabels('not json', 'term-a', edit({ add: ['klbl-bug'] }), NOW)).toBeNull()+ expect(editProjectCardLabels(JSON.stringify({ version: 2, rev: 1, nodes: [] }), 'term-a', edit({ add: ['a'] }), NOW)).toBeNull()+ })++ it('refuses an empty or control-bearing nodeId', () => {+ expect(editProjectCardLabels(file({ kanban: BOARD }), '', edit({ add: ['klbl-ui'] }), NOW)).toBeNull()+ expect(editProjectCardLabels(file({ kanban: BOARD }), 'term-a\n', edit({ add: ['klbl-ui'] }), NOW)).toBeNull()+ })+})++describe('parseCardLabelEdit — write-site validation of client-sent params', () => {+ it('accepts the three lists and dedupes ids', () => {+ expect(parseCardLabelEdit({ add: ['a', 'a'], remove: ['b'], create: [{ name: 'x', color: 'pink' }] })).toEqual({+ add: ['a'], remove: ['b'], create: [{ name: 'x', color: 'pink' }]+ })+ })++ it('trims names and collapses duplicate creations by the picker\'s name identity', () => {+ expect(parseCardLabelEdit({ create: [{ name: ' Bug ', color: 'red' }, { name: 'bug', color: 'blue' }] })?.create).toEqual([+ { name: 'Bug', color: 'red' }+ ])+ })++ it.each([+ ['nothing at all', {}],+ ['empty lists', { add: [], remove: [], create: [] }],+ ['not an object', 'add'],+ ['an array', [1]],+ ['a non-string id', { add: [7] }],+ ['an empty id', { add: [''] }],+ ['an over-long id', { add: ['x'.repeat(129)] }],+ ['a control char in an id', { remove: ['a\u001b[2J'] }],+ ['an id both added and removed', { add: ['a'], remove: ['a'] }],+ ['an empty name', { create: [{ name: ' ', color: 'red' }] }],+ ['an over-long name', { create: [{ name: 'x'.repeat(LABEL_NAME_MAX + 1), color: 'red' }] }],+ ['a newline in a name', { create: [{ name: 'a\nb', color: 'red' }] }],+ ['an ESC in a name', { create: [{ name: 'a\u001b]52;c;x\u0007', color: 'red' }] }],+ ['a colour outside the palette', { create: [{ name: 'a', color: '#ff0000' }] }],+ ['a prototype-name colour', { create: [{ name: 'a', color: 'constructor' }] }],+ ['a missing colour', { create: [{ name: 'a' }] }],+ ['too many ids', { add: Array.from({ length: 33 }, (_, i) => `l${i}`) }]+ ])('refuses %s', (_label, raw) => {+ expect(parseCardLabelEdit(raw)).toBeNull()+ })++ it('counts the name cap in characters, not UTF-16 units', () => {+ // 🏷️ is U+1F3F7 U+FE0F: 3 UTF-16 units, 2 code points. 25 of them = 75 units (over the cap if+ // measured in units) but 50 code points (under it).+ const name = '🏷️'.repeat(25)+ expect(name.length).toBeGreaterThan(LABEL_NAME_MAX)+ expect(parseCardLabelEdit({ create: [{ name, color: 'red' }] })).not.toBeNull()+ })+})diff --git a/src/core/project-kanban-write.ts b/src/core/project-kanban-write.tsindex 9b528df95..d66e2595b 100644--- a/src/core/project-kanban-write.ts+++ b/src/core/project-kanban-write.ts@@ -1,6 +1,7 @@// Pure kanban writes into a project.json's raw text — the host side of the relay-// `projects.ensureBoard` / `projects.setCardColumn` verbs (the phone's twin of this logic lives in-// nodeterm-ios ProjectNodeRegistrar and writes over direct SSH; both converge on one board shape).+// `projects.ensureBoard` / `projects.setCardColumn` / `projects.editCardLabels` verbs (the phone's+// twin of this logic lives in nodeterm-ios KanbanBoardWriter and writes over direct SSH; both+// converge on one board shape).//// Same raw-object discipline as `project-node-append.ts`: the transforms work on the PARSED OBJECT,// not the typed mirrors, so every field this version does not know (bridges, dino scores, future@@ -13,6 +14,14 @@// exists, a card already in that column) — a retry must not churn `rev`.import { DEFAULT_BOARD_COLUMNS, makeColumnId } from '../shared/kanban-default-board'+import {+ KANBAN_LABEL_COLORS,+ boardLabels,+ cardMeta,+ createLabel,+ setCardLabels+} from '../shared/kanban-labels'+import type { KanbanLabelColor, ProjectKanban } from '../shared/types'/** Parse `raw` as the `{version:1, rev, nodes}` project file, or null. */function parseProjectFile(raw: string): Record<string, unknown> | null {@@ -115,3 +124,140 @@ export function setProjectCardColumn(root.kanban = boardreturn bumped(root, now)}++// ── Card labels (the phone's `projects.editCardLabels` verb) ─────────────────────────────────────++/** Longest label name the phone may create. The desktop picker has no cap of its own; this one is+ * a write-site bound on hostile input (the verb's params are client-sent), generous for a chip. */+export const LABEL_NAME_MAX = 60+/** Most label ids / creations one edit may carry — a sheet toggles one or two at a time. */+export const LABEL_EDIT_MAX = 32+/** Longest label id accepted from the wire. Minted ids are `klbl-xxxxxxxx`; hand-edited ones can+ * be anything, which is why this is a length/charset bound rather than the minted shape. */+const LABEL_ID_MAX = 128++// C0 + DEL + C1. A label name is rendered on three surfaces and written into a git-shared file;+// a newline or an ESC in it has no legitimate use and is exactly what hand-edited input smuggles.+// eslint-disable-next-line no-control-regex+const CONTROL_CHARS = /[\u0000-\u001f\u007f-\u009f]/++/** One label edit on one card, as the phone sends it. All three lists are optional; at least one+ * entry overall is required. `create`d labels are added to the palette AND applied to the card. */+export interface CardLabelEdit {+ add?: string[]+ remove?: string[]+ create?: Array<{ name: string; color: KanbanLabelColor }>+}++const validId = (x: unknown): x is string =>+ typeof x === 'string' && x.length > 0 && x.length <= LABEL_ID_MAX && !CONTROL_CHARS.test(x)++/** Label-name identity: the same trim + case fold `LabelPicker` uses to hide "Create" on an exact+ * match and `migrateTagsToLabels` uses to reuse a label — so the phone cannot mint a duplicate the+ * desktop picker would never have let the user create. */+const nameKey = (s: string): string => s.trim().toLowerCase()++/**+ * Validate a client-sent label edit at the write site, or return null (refused, nothing written).+ *+ * The params come off the wire and end up in a git-shared, hand-editable file every collaborator's+ * canvas renders, so nothing is coerced into shape: an id that is not a bounded, control-free+ * string, a name that is empty / too long / carries control characters, a colour outside the closed+ * palette, an id both added and removed, or an edit with nothing in it — each refuses the whole+ * edit rather than writing a "nearest" version of it.+ */+export function parseCardLabelEdit(raw: unknown): CardLabelEdit | null {+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return null+ const r = raw as Record<string, unknown>+ const list = (x: unknown): string[] | null => {+ if (x === undefined || x === null) return []+ if (!Array.isArray(x) || x.length > LABEL_EDIT_MAX || !x.every(validId)) return null+ return [...new Set(x)]+ }+ const add = list(r.add)+ const remove = list(r.remove)+ if (!add || !remove) return null+ if (add.some((id) => remove.includes(id))) return null++ const create: Array<{ name: string; color: KanbanLabelColor }> = []+ if (r.create !== undefined && r.create !== null) {+ if (!Array.isArray(r.create) || r.create.length > LABEL_EDIT_MAX) return null+ for (const c of r.create) {+ if (!c || typeof c !== 'object') return null+ const { name, color } = c as { name?: unknown; color?: unknown }+ if (typeof name !== 'string' || CONTROL_CHARS.test(name)) return null+ const trimmed = name.trim()+ if (!trimmed || [...trimmed].length > LABEL_NAME_MAX) return null+ if (!KANBAN_LABEL_COLORS.includes(color as KanbanLabelColor)) return null+ if (create.some((x) => nameKey(x.name) === nameKey(trimmed))) continue+ create.push({ name: trimmed, color: color as KanbanLabelColor })+ }+ }+ if (!add.length && !remove.length && !create.length) return null+ return { add, remove, create }+}++/**+ * Apply one label edit to one card in the project file's raw text — through the SAME pure+ * transforms the desktop's `LabelPicker` uses (`@shared/kanban-labels`), so a label added on the+ * phone is the same palette entry + the same `meta[].labels` id the desktop would have written.+ *+ * Order: creations first (a name matching an existing label, case-insensitively, REUSES that label+ * instead of minting a duplicate — the desktop picker offers no "Create" on an exact match either),+ * then removals, then additions. `kanban.columns` / `assignments` / `github` and every other card's+ * meta round-trip untouched (the same raw-object discipline as the rest of this file).+ *+ * A project with no board gets the default one seeded first, exactly as the desktop's first+ * "+ Label" does (`NodeLabels` edits `kanban ?? defaultKanban()`) — but only when the edit actually+ * changes something, so a no-op never writes a board nobody asked for.+ *+ * Returns null (nothing written) for a file of the wrong shape, an unusable `kanban` block, an+ * `add` naming a label this palette does not have (the phone's copy is stale — applying a dangling+ * id would show nothing anywhere), or an edit that leaves the card and palette exactly as they were.+ */+export function editProjectCardLabels(+ raw: string,+ nodeId: string,+ edit: CardLabelEdit,+ now: Date,+ mintId = makeColumnId+): string | null {+ if (!validId(nodeId)) return null+ const root = parseProjectFile(raw)+ if (!root) return null+ const block = boardOf(root)+ if (!block) return null+ // The shared transforms are typed on ProjectKanban and spread `...k`, so every field we do not+ // type survives; the cast only lends them the arrays they read (both tolerated when absent).+ let k = block as unknown as ProjectKanban+ const before = JSON.stringify([boardLabels(k), cardMeta(k, nodeId)?.labels ?? []])++ const apply: string[] = []+ for (const c of edit.create ?? []) {+ const existing = boardLabels(k).find((l) => nameKey(l.name) === nameKey(c.name))+ if (existing) {+ apply.push(existing.id)+ continue+ }+ const res = createLabel(k, c.name, c.color)+ k = res.k+ apply.push(res.id)+ }+ const known = new Set(boardLabels(k).map((l) => l.id))+ if ((edit.add ?? []).some((id) => !known.has(id))) return null++ const drop = new Set(edit.remove ?? [])+ const current = cardMeta(k, nodeId)?.labels+ const kept = (Array.isArray(current) ? current : []).filter((id) => !drop.has(id))+ k = setCardLabels(k, nodeId, [...kept, ...(edit.add ?? []).filter((id) => !drop.has(id)), ...apply])++ if (JSON.stringify([boardLabels(k), cardMeta(k, nodeId)?.labels ?? []]) === before) return null++ const next = k as unknown as Record<string, unknown>+ if (columnsOf(next).length === 0) {+ next.columns = DEFAULT_BOARD_COLUMNS.map((c) => ({ id: mintId(), title: c.title, color: c.color }))+ }+ if (!Array.isArray(next.assignments)) next.assignments = []+ root.kanban = next+ return bumped(root, now)+}diff --git a/src/core/workspace-store.kanban.test.ts b/src/core/workspace-store.kanban.test.tsindex 0254b9c66..203bb3b3c 100644--- a/src/core/workspace-store.kanban.test.ts+++ b/src/core/workspace-store.kanban.test.ts@@ -266,3 +266,100 @@ describe('an SSH project (the case the phone can never write itself)', () => {expect(entry.cache.kanban.columns).toHaveLength(3)})})++describe('editRemoteCardLabels (the phone labelling a session)', () => {+ // ONE label model: the palette in `kanban.labels` + ids in `kanban.meta[].labels`, the same the+ // canvas node's "+ Label" row and the kanban card write. These pin that a phone edit lands there,+ // is announced (so the live canvas adopts it rather than the next autosave reverting it), and that+ // a desktop-authored label comes back to the phone in the answer.+ const withLabels = (over: Partial<Project> = {}): Project =>+ project({+ cwd: projRoot,+ kanban: {+ columns: [{ id: 'kcol-a', title: 'To Do', color: '#0a84ff' }],+ assignments: [],+ labels: [{ id: 'klbl-bug', name: 'bug', color: 'red' }]+ },+ ...over+ })++ it('applies a desktop label to the card, writes the file and announces it', async () => {+ const store = new WorkspaceStore()+ await store.save(ws([withLabels()]))+ fake.sent.length = 0++ const res = await store.editRemoteCardLabels('p1', 'term-1', { add: ['klbl-bug'] })+ expect(res).toEqual({+ edited: true,+ labels: [{ id: 'klbl-bug', name: 'bug', color: 'red' }],+ cardLabelIds: ['klbl-bug']+ })+ expect((await readFile()).kanban.meta).toEqual([{ nodeId: 'term-1', labels: ['klbl-bug'] }])+ expect(externalChanges()).toHaveLength(1)+ expect(externalChanges()[0].kanban.meta).toEqual([{ nodeId: 'term-1', labels: ['klbl-bug'] }])+ })++ it('the first label on a board-less project seeds the default board', async () => {+ const store = new WorkspaceStore()+ await store.save(ws([project({ cwd: projRoot })]))+ const res = await store.editRemoteCardLabels('p1', 'term-1', { create: [{ name: 'ui', color: 'blue' }] })+ expect(res?.edited).toBe(true)+ expect(res?.labels.map((l) => l.name)).toEqual(['ui'])+ expect(res?.cardLabelIds).toEqual([res?.labels[0].id])+ expect((await readFile()).kanban.columns.map((c: { title: string }) => c.title))+ .toEqual(DEFAULT_BOARD_COLUMNS.map((c) => c.title))+ })++ it('a stale add is `edited:false` WITH the current palette, so the sheet can redraw', async () => {+ const store = new WorkspaceStore()+ await store.save(ws([withLabels()]))+ const before = await readFile()+ const res = await store.editRemoteCardLabels('p1', 'term-1', { add: ['klbl-deleted-elsewhere'] })+ expect(res).toEqual({ edited: false, labels: [{ id: 'klbl-bug', name: 'bug', color: 'red' }], cardLabelIds: [] })+ expect(await readFile()).toEqual(before)+ })++ it('drops dangling ids from the answer exactly as the desktop readers do', async () => {+ const store = new WorkspaceStore()+ const p = withLabels()+ p.kanban!.meta = [{ nodeId: 'term-1', labels: ['klbl-bug', 'klbl-ghost'] }]+ await store.save(ws([p]))+ const res = await store.editRemoteCardLabels('p1', 'term-1', { add: ['klbl-bug'] })+ expect(res?.cardLabelIds).toEqual(['klbl-bug'])+ })++ it('answers null for a project it cannot write', async () => {+ const store = new WorkspaceStore()+ await store.save(ws([withLabels(), project({ id: 'inline1' })]))+ expect(await store.editRemoteCardLabels('nope', 'term-1', { add: ['klbl-bug'] })).toBeNull()+ expect(await store.editRemoteCardLabels('inline1', 'term-1', { add: ['klbl-bug'] })).toBeNull()+ })++ it('is serialized with saves', async () => {+ const store = new WorkspaceStore()+ await store.save(ws([withLabels()]))+ const saving = store.save(ws([{ ...withLabels(), name: 'renamed' }]))+ const labelling = store.editRemoteCardLabels('p1', 'term-1', { add: ['klbl-bug'] })+ expect((await labelling)?.edited).toBe(true)+ await saving+ const file = await readFile()+ expect(file.kanban.meta).toEqual([{ nodeId: 'term-1', labels: ['klbl-bug'] }])+ expect(file.name).toBe('renamed')+ })++ it('an SSH project: writes the cache, mirrors it, and the reload carries the label', async () => {+ const io = fakeRemote()+ const store = new WorkspaceStore(io)+ await store.save(ws([project({+ id: 'ssh1', cwd: undefined, ssh: SSH,+ kanban: { columns: [{ id: 'kcol-a', title: 'To Do', color: '#0a84ff' }], assignments: [],+ labels: [{ id: 'klbl-bug', name: 'bug', color: 'red' }] }+ })]))+ const res = await store.editRemoteCardLabels('ssh1', 'term-1', { add: ['klbl-bug'] })+ expect(res?.edited).toBe(true)+ expect(JSON.parse(io.content!).kanban.meta).toEqual([{ nodeId: 'term-1', labels: ['klbl-bug'] }])+ const reloaded = await new WorkspaceStore(io).load()+ expect(reloaded.projects.find((p) => p.id === 'ssh1')?.kanban?.meta)+ .toEqual([{ nodeId: 'term-1', labels: ['klbl-bug'] }])+ })+})diff --git a/src/core/workspace-store.ts b/src/core/workspace-store.tsindex b800ecd50..133fcc9e6 100644--- a/src/core/workspace-store.ts+++ b/src/core/workspace-store.ts@@ -6,7 +6,7 @@ import { IPC } from '../shared/ipc'import { platform } from './platform'import {DEFAULT_PROJECT_ID, EMPTY_WORKSPACE,- type BridgeLink, type CanvasNodeState, type KanbanColumn, type Project, type Workspace,+ type BridgeLink, type CanvasNodeState, type KanbanColumn, type KanbanLabel, type Project, type Workspace,type WorkspaceV1} from '../shared/types'import {@@ -33,7 +33,8 @@ import {sanitizeLayouts} from '../shared/canvas-layout'import { appendProjectNode, removeProjectNode, type RemoteNodeInput } from './project-node-append'-import { ensureProjectBoard, setProjectCardColumn } from './project-kanban-write'+import { editProjectCardLabels, ensureProjectBoard, setProjectCardColumn, type CardLabelEdit } from './project-kanban-write'+import { boardLabels, cardMeta } from '../shared/kanban-labels'/** Checked remote read: `absent` (no file — safe to push our cache) is NOT `error` (connection* down / ssh failure — a failed read is never evidence of absence, so nothing may be pushed). */@@ -1766,7 +1767,48 @@ export class WorkspaceStore {}/**- * The one read-modify-write behind both kanban verbs, for BOTH kinds of ref project.+ * Add / remove / create board labels on one session card — the host side of the relay+ * `projects.editCardLabels` verb, i.e. the phone's long-press label sheet.+ *+ * There is ONE label model (the per-project palette in `kanban.labels` + per-card ids in+ * `kanban.meta[].labels`, the same one the canvas node's "+ Label" row and the kanban card edit),+ * and this writes into it through the same shared transforms and the same `kanbanWriteNow`+ * read-modify-write as `setRemoteCardColumn` — so the change is announced to the renderer and the+ * canvas node + kanban card adopt it live, local and SSH projects alike.+ *+ * Answers the palette and this card's label ids AS THEY NOW STAND, whether or not this call+ * changed them (`edited` says which): a refused `add` (the phone's palette is stale) comes back as+ * `edited: false` with the current palette, so the sheet can redraw instead of guessing. Null =+ * the project is unknown or has no readable project file.+ */+ editRemoteCardLabels(+ projectId: string,+ nodeId: string,+ edit: CardLabelEdit,+ now = new Date()+ ): Promise<{ edited: boolean; labels: KanbanLabel[]; cardLabelIds: string[] } | null> {+ const run = this.saveChain.then(() =>+ this.kanbanWriteNow(projectId, (raw) => editProjectCardLabels(raw, nodeId, edit, now))+ )+ this.saveChain = run.catch(() => {})+ return run.then((res) => {+ if (!res) return null+ const k = res.file.kanban+ if (!k || typeof k !== 'object') return { edited: res.written, labels: [], cardLabelIds: [] }+ const labels = boardLabels(k)+ const known = new Set(labels.map((l) => l.id))+ const ids = cardMeta(k, nodeId)?.labels+ return {+ edited: res.written,+ labels,+ // Dangling ids (a label deleted elsewhere) are dropped exactly as every desktop reader drops them.+ cardLabelIds: Array.isArray(ids) ? ids.filter((id) => known.has(id)) : []+ }+ })+ }++ /**+ * The one read-modify-write behind every kanban verb, for BOTH kinds of ref project.** Queued on `saveChain` by its callers for the same reason `appendRemoteNode` is: this rewrites* the very file a save rewrites whole, and off the chain a save that read the file first landsdiff --git a/src/main/index.ts b/src/main/index.tsindex 6e451993a..bf98800b0 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -76,6 +76,7 @@ import type { TranscriptPresence } from '../shared/types'import { boardLogRemotePath } from '../core/board-log'import { PtyManager } from '../core/pty-manager'import { WorkspaceStore } from '../core/workspace-store'+import type { CardLabelEdit } from '../core/project-kanban-write'import { WorkspaceWatcher } from '../core/workspace-watcher'import { SettingsStore } from '../core/settings-store'import { registerAgentEnvIpc } from '../core/agent-env-ipc'@@ -3907,7 +3908,11 @@ app.whenReady().then(async () => {kanban: {ensureBoard: (projectId: string) => workspaceStore.ensureRemoteBoard(projectId),setCardColumn: (projectId: string, nodeId: string, columnId: string | null) =>- workspaceStore.setRemoteCardColumn(projectId, nodeId, columnId)+ workspaceStore.setRemoteCardColumn(projectId, nodeId, columnId),+ // The phone's long-press label sheet. Same store read-modify-write + renderer announce as the+ // card move, so a label added on the phone lands on the canvas node and the kanban card live.+ editCardLabels: (projectId: string, nodeId: string, edit: CardLabelEdit) =>+ workspaceStore.editRemoteCardLabels(projectId, nodeId, edit)},// "End session" from the phone (`pty.destroy`): the SAME two steps the desktop × performs —// kill the tmux session on every socket it could live on (the sweep may have seen it on eitherdiff --git a/src/main/remote/host-kanban-verbs.test.ts b/src/main/remote/host-kanban-verbs.test.tsindex f4745f016..d571d7ee2 100644--- a/src/main/remote/host-kanban-verbs.test.ts+++ b/src/main/remote/host-kanban-verbs.test.ts@@ -39,6 +39,11 @@ function makeFakes(over: Partial<HostKanbanOps> = {}, served = true) {const kanban: HostKanbanOps = {ensureBoard: vi.fn(async () => COLUMNS),setCardColumn: vi.fn(async () => true),+ editCardLabels: vi.fn(async () => ({+ edited: true,+ labels: [{ id: 'klbl-bug', name: 'bug', color: 'red' as const }],+ cardLabelIds: ['klbl-bug']+ })),...over}const handlers = createHostHandlers(@@ -163,3 +168,66 @@ describe('projects.setCardColumn', () => {expect(String(responses[0].body.message)).toContain('not served')})})++describe('projects.editCardLabels (the phone\'s long-press label sheet)', () => {+ const call = (handlers: ReturnType<typeof makeFakes>['handlers'], params: Record<string, unknown>) =>+ handlers.onRpc({ id: '1', method: 'projects.editCardLabels', params })++ it('passes a validated edit to the store and answers the palette + card ids', async () => {+ const { handlers, responses, kanban } = makeFakes()+ call(handlers, { projectId: 'p1', nodeId: 'term-a-1', add: ['klbl-bug'], create: [{ name: ' ui ', color: 'blue' }] })+ await flush()+ expect(kanban.editCardLabels).toHaveBeenCalledWith('p1', 'term-a-1', {+ add: ['klbl-bug'], remove: [], create: [{ name: 'ui', color: 'blue' }]+ })+ expect(responses[0]).toEqual({+ id: '1', ok: true,+ body: { edited: true, labels: [{ id: 'klbl-bug', name: 'bug', color: 'red' }], cardLabelIds: ['klbl-bug'] }+ })+ })++ // Validated at the write site, before the store is asked anything: these params end up in a+ // git-shared file every collaborator's canvas renders.+ it('refuses malformed edits without asking the store', () => {+ for (const params of [+ { projectId: 'p1', nodeId: 'term-a-1' },+ { projectId: 'p1', nodeId: 'term-a-1', add: [42] },+ { projectId: 'p1', nodeId: 'term-a-1', create: [{ name: 'x', color: '#f00' }] },+ { projectId: 'p1', nodeId: 'term-a-1', create: [{ name: 'a\u001b[31m', color: 'red' }] },+ { projectId: 'p1', nodeId: 'term-a-1', add: ['a'], remove: ['a'] },+ { nodeId: 'term-a-1', add: ['a'] },+ { projectId: 'p1', add: ['a'] }+ ]) {+ const { handlers, responses, kanban } = makeFakes()+ call(handlers, params)+ expect(responses[0].ok).toBe(false)+ expect(kanban.editCardLabels).not.toHaveBeenCalled()+ }+ })++ it('answers `labels: null` when the store has no writable file or throws', async () => {+ for (const ops of [+ { editCardLabels: async () => null },+ { editCardLabels: async () => { throw new Error('boom') } }+ ] as Partial<HostKanbanOps>[]) {+ const { handlers, responses } = makeFakes(ops)+ call(handlers, { projectId: 'p1', nodeId: 'term-a-1', add: ['klbl-bug'] })+ await flush()+ expect(responses[0]).toEqual({ id: '1', ok: true, body: { edited: false, labels: null, cardLabelIds: null } })+ }+ })++ it('is not served by a host whose kanban ops predate the verb', () => {+ const { handlers, responses } = makeFakes({ editCardLabels: undefined })+ call(handlers, { projectId: 'p1', nodeId: 'term-a-1', add: ['klbl-bug'] })+ expect(responses[0].ok).toBe(false)+ expect(String(responses[0].body.message)).toContain('not served')+ })++ it('is not served when the host has no kanban ops at all', () => {+ const { handlers, responses } = makeFakes({}, false)+ call(handlers, { projectId: 'p1', nodeId: 'term-a-1', add: ['klbl-bug'] })+ expect(responses[0].ok).toBe(false)+ expect(String(responses[0].body.message)).toContain('not served')+ })+})diff --git a/src/main/remote/host-service.ts b/src/main/remote/host-service.tsindex 591e38a13..b046b0fe4 100644--- a/src/main/remote/host-service.ts+++ b/src/main/remote/host-service.ts@@ -28,11 +28,12 @@ import path from 'path'import { app, ipcMain, type BrowserWindow } from 'electron'import { IPC } from '../../shared/ipc'import { REF_MAX_LEN } from '../../shared/presence'-import type { CanvasMutation, CanvasState, DirEntry, KanbanColumn, PtyCreateOptions } from '../../shared/types'+import type { CanvasMutation, CanvasState, DirEntry, KanbanColumn, KanbanLabel, PtyCreateOptions } from '../../shared/types'import type { AgentId } from '../../shared/agents/config'import { PtyManager, type DetachedSinks } from '../../core/pty-manager'import * as fsOps from '../../core/fs-ops'import { TITLE_MAX, type RemoteNodeInput } from '../../core/project-node-append'+import { parseCardLabelEdit, type CardLabelEdit } from '../../core/project-kanban-write'import { getStoredEntitlement, isPremium } from '../../core/license'import { publicKeyToB64, type KeyPair } from './e2ee'import { loadOrCreateHostKeyPair, HostKeyLockedError } from './host-identity'@@ -167,6 +168,15 @@ export interface HostKanbanOps {ensureBoard(projectId: string): Promise<KanbanColumn[] | null>/** Move a card to a column (null = the virtual Ungrouped column). False = nothing was written. */setCardColumn(projectId: string, nodeId: string, columnId: string | null): Promise<boolean>+ /** Add / remove / create board labels on one card (`projects.editCardLabels`) — the phone's+ * long-press label sheet. Answers the palette + the card's label ids as they now stand, or null+ * when the project has no writable file. Optional so a host (or test fake) built before the verb+ * answers an honest "not served" instead of failing to compile. */+ editCardLabels?(+ projectId: string,+ nodeId: string,+ edit: CardLabelEdit+ ): Promise<{ edited: boolean; labels: KanbanLabel[]; cardLabelIds: string[] } | null>}interface Stream {@@ -550,6 +560,12 @@ export function createHostHandlers(** `projects.setCardColumn { projectId, nodeId, columnId | null }` → `{ moved }`: move one card.*+ * `projects.editCardLabels { projectId, nodeId, add?, remove?, create? }` →+ * `{ edited, labels, cardLabelIds }`: the phone's long-press label sheet, writing the SAME board+ * labels the canvas node's "+ Label" row and the kanban card edit (`@shared/kanban-labels`).+ * `labels: null` = this project has no writable file; `edited: false` with a palette = nothing+ * changed (a retry, or an `add` naming a label the phone's stale copy still had).+ ** Validation lives in the store's pure transforms (`project-kanban-write.ts`), which refuse* anything they cannot do rather than inventing a board or a column — and a refusal is an* `ok:{...false}` ANSWER, not a protocol error, because the phone must be able to tell the user@@ -579,7 +595,38 @@ export function createHostHandlers(}const nodeId = str(p.nodeId)if (!nodeId) {- socket.respond(req.id, false, { message: 'projects.setCardColumn requires a nodeId.' })+ socket.respond(req.id, false, { message: `${req.method} requires a nodeId.` })+ return+ }+ if (req.method === 'projects.editCardLabels') {+ if (!kanban.editCardLabels) {+ socket.respond(req.id, false, { message: `${req.method} is not served on this host.` })+ return+ }+ // Validated HERE, at the write site, before the store is touched: the params are client-sent+ // and end up in a git-shared, hand-editable file every collaborator's canvas renders. A+ // malformed edit is a protocol error (the phone sent something it should never send), unlike+ // a stale label id, which is an `edited:false` answer carrying the current palette.+ const edit = parseCardLabelEdit({ add: p.add, remove: p.remove, create: p.create })+ if (!edit) {+ socket.respond(req.id, false, {+ message:+ 'projects.editCardLabels requires add/remove (label ids) and/or create ' ++ '({name, color}) with at least one entry; names must be 1–60 characters without ' ++ 'control characters and colors one of the board palette.'+ })+ return+ }+ void kanban+ .editCardLabels(projectId, nodeId, edit)+ .then((res) =>+ socket.respond(+ req.id,+ true,+ res ?? { edited: false, labels: null, cardLabelIds: null }+ )+ )+ .catch(() => socket.respond(req.id, true, { edited: false, labels: null, cardLabelIds: null }))return}// `null` is a REAL value here (the virtual Ungrouped column), so it must be told apart from a@@ -762,6 +809,7 @@ export function createHostHandlers(breakcase 'projects.ensureBoard':case 'projects.setCardColumn':+ case 'projects.editCardLabels':handleKanban(req)breakcase 'node.wake':diff --git a/src/main/remote/relay-host.test.ts b/src/main/remote/relay-host.test.tsindex 1fc0da104..adc841b70 100644--- a/src/main/remote/relay-host.test.ts+++ b/src/main/remote/relay-host.test.ts@@ -458,6 +458,75 @@ describe('relay host — GitHub issue RPCs are scoped to the shared project', ()})})+describe('relay host — project-scoped channel CLASSES fail closed', () => {+ // The jail used to be a per-feature switch whose default arm passed anything it did not list. It+ // is now keyed on channel class (relay-project-scope.ts), so the phone board verbs — label edits+ // included — and any future verb in a scoped class are judged by the shared project.+ const collect = async (s: ReturnType<typeof openHostAgainstFakeRelay>, id: number) => {+ await vi.waitFor(() => expect(s.textFrames.some((f) => JSON.parse(f).id === id)).toBe(true))+ return s.textFrames.map((f) => JSON.parse(f)).find((m) => m.id === id)+ }++ it('refuses a label edit naming another project before any handler runs', async () => {+ const reached: unknown[] = []+ platform.handle('projects.editCardLabels', async (...args: unknown[]) => { reached.push(args) })+ const s = openHostAgainstFakeRelay({ sharedProjectId: 'proj-1' })+ await s.openMutually()+ s.peerSendsTunnelText(JSON.stringify({+ t: 'req', id: 301, method: 'projects.editCardLabels',+ args: [{ projectId: 'proj-2', nodeId: 'n', add: ['klbl-x'] }]+ }))+ const res = await collect(s, 301)+ expect(res).toMatchObject({ ok: false, error: { code: 'E_FORBIDDEN' } })+ expect(reached).toEqual([])+ })++ it('refuses an UNLISTED method in a scoped class even when it names the shared project', async () => {+ const reached: string[] = []+ platform.handle('githubIssues:future-verb', async () => { reached.push('gh') })+ const s = openHostAgainstFakeRelay({ sharedProjectId: 'proj-1' })+ await s.openMutually()+ s.peerSendsTunnelText(JSON.stringify({ t: 'req', id: 302, method: 'githubIssues:future-verb', args: ['proj-1'] }))+ expect(await collect(s, 302)).toMatchObject({ ok: false, error: { code: 'E_FORBIDDEN' } })+ expect(reached).toEqual([])+ })++ it('lets the shared project through to dispatch', async () => {+ const reached: unknown[] = []+ platform.handle('projects.editCardLabels', async (...args: unknown[]) => { reached.push(args); return 'ok' })+ const s = openHostAgainstFakeRelay({ sharedProjectId: 'proj-1' })+ await s.openMutually()+ s.peerSendsTunnelText(JSON.stringify({+ t: 'req', id: 303, method: 'projects.editCardLabels', args: [{ projectId: 'proj-1', nodeId: 'n', add: ['l'] }]+ }))+ expect(await collect(s, 303)).toMatchObject({ ok: true })+ expect(reached).toHaveLength(1)+ })++ it('an unscoped session is unaffected (legacy behaviour)', async () => {+ const reached: string[] = []+ platform.handle('githubIssues:future-verb', async () => { reached.push('gh'); return 1 })+ const s = openHostAgainstFakeRelay()+ await s.openMutually()+ s.peerSendsTunnelText(JSON.stringify({ t: 'req', id: 304, method: 'githubIssues:future-verb', args: ['proj-2'] }))+ expect(await collect(s, 304)).toMatchObject({ ok: true })+ expect(reached).toEqual(['gh'])+ })++ it('drops an out-of-scope cast in a scoped class', async () => {+ const calls: string[] = []+ platform.onWithSender('board-log:future-cast', () => calls.push('future'))+ platform.onWithSender(IPC.githubIssuesUnsubscribe, () => calls.push('listed'))+ const s = openHostAgainstFakeRelay({ sharedProjectId: 'proj-1' })+ await s.openMutually()+ s.peerSendsTunnelText(JSON.stringify({ t: 'cast', method: 'board-log:future-cast', args: ['proj-1'] }))+ // Positive control, sent AFTER: once the listed cast has arrived, the unlisted one had its turn.+ s.peerSendsTunnelText(JSON.stringify({ t: 'cast', method: IPC.githubIssuesUnsubscribe, args: ['proj-1'] }))+ await vi.waitFor(() => expect(calls).toContain('listed'))+ expect(calls).toEqual(['listed'])+ })+})+describe('relay host — nothing is served before mutual approval', () => {it('a peer RPC BEFORE mutual approval is refused (no dispatch, no sink, no presence)', async () => {let created = 0diff --git a/src/main/remote/relay-host.ts b/src/main/remote/relay-host.tsindex fde04c6e1..b6a3202b9 100644--- a/src/main/remote/relay-host.ts+++ b/src/main/remote/relay-host.ts@@ -31,6 +31,7 @@ import { allocateRelayClientId, presenceHub } from '../../core/presence/hub'import { E_UNAUTHORIZED, parseRpcMessage, type RpcErr, type RpcOk } from '../../shared/rpc'import { IPC } from '../../shared/ipc'import { scopeWorkspaceToProject } from '../../shared/relay-workspace-scope'+import { outOfProjectScope } from './relay-project-scope'import type { Workspace } from '../../shared/types'export interface RelayHostSession {@@ -196,40 +197,23 @@ export function connectRelayHost(opts: ConnectRelayHostOptions): RelayHostSessio? { t: 'res', id, ok: true, result: { entries: [], unsupported: true } }: { t: 'res', id, ok: true, result: false }- const githubIssuesProject = (method: string, args: unknown[]): {- githubIssues: boolean- projectId: unknown- } => {- switch (method) {- case IPC.githubIssuesSubscribe:- case IPC.githubIssuesQuery:- case IPC.githubIssuesMove:- return {- githubIssues: true,- projectId: args[0] && typeof args[0] === 'object'- ? (args[0] as { projectId?: unknown }).projectId- : undefined- }- case IPC.githubIssuesRefresh:- case IPC.githubIssuesCreateLabels:- case IPC.githubIssuesClearCache:- case IPC.githubIssuesUnsubscribe:- return { githubIssues: true, projectId: args[0] }- default:- return { githubIssues: false, projectId: undefined }- }- }-- const githubIssuesOutOfScope = (method: string, args: unknown[]): boolean => {- const target = githubIssuesProject(method, args)- return !!opts.sharedProjectId && target.githubIssues && target.projectId !== opts.sharedProjectId- }+ /** SCOPE jail for every project-naming channel class (`relay-project-scope.ts`): a method in a+ * scoped class that names another project — or that the table cannot read a projectId out of —+ * is refused on a session bound to one project. Fail-closed by class, so a channel added to+ * `githubIssues:*` / `board-log:*` / `projects.*` without a table row is refused, not waved on. */+ const projectOutOfScope = (method: string, args: unknown[]): boolean =>+ outOfProjectScope(opts.sharedProjectId, method, args)- const githubIssuesRefusal = (id: number): RpcErr => ({+ const projectScopeRefusal = (method: string, id: number): RpcErr => ({t: 'res',id,ok: false,- error: { code: 'E_FORBIDDEN', message: 'GitHub Issues project is outside this relay session' }+ error: {+ code: 'E_FORBIDDEN',+ message: method.startsWith('githubIssues:')+ ? 'GitHub Issues project is outside this relay session'+ : 'That project is outside this relay session'+ }})const socket = connectRelay({@@ -285,12 +269,9 @@ export function connectRelayHost(opts: ConnectRelayHostOptions): RelayHostSessioreturn}if (m.t === 'req') {- if (githubIssuesOutOfScope(m.method, m.args)) {- socket.sendTunnelText(JSON.stringify(githubIssuesRefusal(m.id)))- return- }// Board-log read/append naming a project outside this session's scope: refuse WITHOUT// dispatching (the host router never resolves it), degrading exactly as an unknown project.+ // Checked before the generic jail so these two keep their established degraded shape.if ((m.method === IPC.boardLogAppend || m.method === IPC.boardLogRead) &&boardLogOutOfScope(m.args[0])@@ -298,12 +279,16 @@ export function connectRelayHost(opts: ConnectRelayHostOptions): RelayHostSessiosocket.sendTunnelText(JSON.stringify(boardLogRefusal(m.method, m.id)))return}+ if (projectOutOfScope(m.method, m.args)) {+ socket.sendTunnelText(JSON.stringify(projectScopeRefusal(m.method, m.id)))+ return+ }const id = clientIdvoid opts.platform.dispatch(id, m).then((res) => socket.sendTunnelText(JSON.stringify(scopeResponse(m.method, res))))} else if (m.t === 'cast') {- if (githubIssuesOutOfScope(m.method, m.args)) return+ if (projectOutOfScope(m.method, m.args)) return// Board-log subscribe/unsubscribe: scope-jail out-of-scope projects, and track this// connection's net per-project count so a dropped guest's watch is released in detach().if (m.method === IPC.boardLogSubscribe || m.method === IPC.boardLogUnsubscribe) {diff --git a/src/main/remote/relay-project-scope.test.ts b/src/main/remote/relay-project-scope.test.tsnew file mode 100644index 000000000..17264d065--- /dev/null+++ b/src/main/remote/relay-project-scope.test.ts@@ -0,0 +1,71 @@+// The relay-guest scope jail's classifier. What these pin:+// - every project-naming channel we serve today is classified AND has its projectId read, so the+// refactor from per-feature switches changed no existing decision;+// - a method inside a scoped class with NO table row fails CLOSED on a scoped session (the old+// `default: not project-scoped` arm waved it through);+// - the phone dialect's board verbs, `projects.editCardLabels` included, are judged by the shared+// project should they ever arrive on this tunnel;+// - an unscoped session is never affected, and unrelated methods are never classified.+import { describe, expect, it } from 'vitest'+import { IPC } from '../../shared/ipc'+import { outOfProjectScope, projectScopeOf, PROJECT_SCOPED_PREFIXES } from './relay-project-scope'++describe('projectScopeOf', () => {+ it.each([+ [IPC.githubIssuesSubscribe, [{ projectId: 'p1' }]],+ [IPC.githubIssuesQuery, [{ projectId: 'p1' }]],+ [IPC.githubIssuesMove, [{ projectId: 'p1' }]],+ [IPC.githubIssuesRefresh, ['p1', true]],+ [IPC.githubIssuesCreateLabels, ['p1']],+ [IPC.githubIssuesClearCache, ['p1']],+ [IPC.githubIssuesUnsubscribe, ['p1']],+ [IPC.boardLogAppend, ['p1', {}]],+ [IPC.boardLogRead, ['p1']],+ [IPC.boardLogSubscribe, ['p1']],+ [IPC.boardLogUnsubscribe, ['p1']],+ ['projects.ensureBoard', [{ projectId: 'p1' }]],+ ['projects.setCardColumn', [{ projectId: 'p1', nodeId: 'n', columnId: null }]],+ ['projects.editCardLabels', [{ projectId: 'p1', nodeId: 'n', add: ['l'] }]]+ ])('reads the projectId of %s', (method, args) => {+ expect(projectScopeOf(method, args)).toEqual({ scoped: true, projectId: 'p1' })+ })++ it('every IPC channel in a scoped class has a table row (no silent fail-closed of a live verb)', () => {+ const live = (Object.values(IPC) as unknown[]).filter(+ (v): v is string => typeof v === 'string' && PROJECT_SCOPED_PREFIXES.some((p) => v.startsWith(p))+ )+ expect(live.length).toBeGreaterThan(0)+ for (const method of live) {+ expect(projectScopeOf(method, ['p1']).projectId ?? projectScopeOf(method, [{ projectId: 'p1' }]).projectId, method)+ .toBe('p1')+ }+ })++ it('leaves unrelated methods unclassified', () => {+ expect(projectScopeOf(IPC.gitStatus, ['/w'])).toEqual({ scoped: false, projectId: undefined })+ expect(projectScopeOf(IPC.workspaceLoad, [])).toEqual({ scoped: false, projectId: undefined })+ })+})++describe('outOfProjectScope', () => {+ it('refuses another project and permits the shared one', () => {+ expect(outOfProjectScope('p1', 'projects.editCardLabels', [{ projectId: 'p2' }])).toBe(true)+ expect(outOfProjectScope('p1', 'projects.editCardLabels', [{ projectId: 'p1' }])).toBe(false)+ })++ it('fails CLOSED for an unlisted method in a scoped class, even naming the shared project', () => {+ expect(outOfProjectScope('p1', 'githubIssues:delete-everything', ['p1'])).toBe(true)+ expect(outOfProjectScope('p1', 'board-log:truncate', ['p1'])).toBe(true)+ expect(outOfProjectScope('p1', 'projects.deleteLabel', [{ projectId: 'p1' }])).toBe(true)+ })++ it('refuses a scoped method whose projectId is missing or not a string', () => {+ expect(outOfProjectScope('p1', 'projects.editCardLabels', [])).toBe(true)+ expect(outOfProjectScope('p1', IPC.boardLogRead, [{ projectId: 'p1' }])).toBe(true)+ })++ it('never affects an unscoped session', () => {+ expect(outOfProjectScope(undefined, 'githubIssues:delete-everything', ['p2'])).toBe(false)+ expect(outOfProjectScope(undefined, 'projects.editCardLabels', [{ projectId: 'p2' }])).toBe(false)+ })+})diff --git a/src/main/remote/relay-project-scope.ts b/src/main/remote/relay-project-scope.tsnew file mode 100644index 000000000..ec0195d44--- /dev/null+++ b/src/main/remote/relay-project-scope.ts@@ -0,0 +1,75 @@+// Which relay-guest methods name a PROJECT, and which project — the one table behind the scope jail+// in `relay-host.ts` (a session bound to one shared project must never let the guest reach another).+//+// The jail used to be a per-feature switch with a `default: not project-scoped` arm, so a method the+// switch did not list was waved through. That is safe only for as long as every project-naming+// channel is remembered in every switch, and it failed OPEN for the next one nobody added: a new+// `githubIssues:*` verb would have reached another project's repository with no refusal anywhere.+// So membership is by CLASS (channel prefix), and a method inside a class that this table cannot+// read a projectId out of is answered as "names an unknown project" — which a scoped session+// refuses. Adding a channel to a class therefore costs one table row to become reachable, rather+// than one forgotten row to become a hole.+//+// `projects.*` is in the class although no IPC channel carries that prefix today: it is the phone+// dialect's board verbs (`projects.ensureBoard` / `setCardColumn` / `editCardLabels`, served by+// host-service to an approved PHONE, never on this tunnel). Classifying it here means that if a+// relay guest ever sends one — or a future channel is named after it — it is judged by the shared+// project rather than passed to a router on the assumption that nothing answers.+//+// Unscoped sessions are not affected at all: with no shared project the jail is off, exactly as+// before (the host registry is then the only gate, as it is for the host's own renderer).++import { IPC } from '../../shared/ipc'++export interface ProjectScope {+ /** The method belongs to a project-scoped channel class. */+ scoped: boolean+ /** The projectId it names — `undefined` when the class is known but the method is not, which+ * the jail treats as "not the shared project" (fail closed). */+ projectId: unknown+}++/** Channel prefixes whose every method acts on ONE project. */+export const PROJECT_SCOPED_PREFIXES = ['githubIssues:', 'board-log:', 'projects.'] as const++const fromFirstArg = (args: unknown[]): unknown => args[0]+const fromFirstArgField = (args: unknown[]): unknown =>+ args[0] && typeof args[0] === 'object' ? (args[0] as { projectId?: unknown }).projectId : undefined++/** Methods whose projectId we know how to read. Everything else in a scoped class fails closed. */+const EXTRACTORS: Record<string, (args: unknown[]) => unknown> = {+ [IPC.githubIssuesSubscribe]: fromFirstArgField,+ [IPC.githubIssuesQuery]: fromFirstArgField,+ [IPC.githubIssuesMove]: fromFirstArgField,+ [IPC.githubIssuesRefresh]: fromFirstArg,+ [IPC.githubIssuesCreateLabels]: fromFirstArg,+ [IPC.githubIssuesClearCache]: fromFirstArg,+ [IPC.githubIssuesUnsubscribe]: fromFirstArg,+ [IPC.boardLogAppend]: fromFirstArg,+ [IPC.boardLogRead]: fromFirstArg,+ [IPC.boardLogSubscribe]: fromFirstArg,+ [IPC.boardLogUnsubscribe]: fromFirstArg,+ // The phone dialect's params object, should one ever arrive as the first arg.+ 'projects.ensureBoard': fromFirstArgField,+ 'projects.setCardColumn': fromFirstArgField,+ 'projects.editCardLabels': fromFirstArgField+}++export function projectScopeOf(method: string, args: unknown[]): ProjectScope {+ if (!PROJECT_SCOPED_PREFIXES.some((p) => method.startsWith(p))) {+ return { scoped: false, projectId: undefined }+ }+ const extract = EXTRACTORS[method]+ return { scoped: true, projectId: extract ? extract(Array.isArray(args) ? args : []) : undefined }+}++/** True when a session bound to `sharedProjectId` must refuse this method. Unscoped ⇒ never. */+export function outOfProjectScope(+ sharedProjectId: string | undefined,+ method: string,+ args: unknown[]+): boolean {+ if (!sharedProjectId) return false+ const scope = projectScopeOf(method, args)+ return scope.scoped && scope.projectId !== sharedProjectId+}diff --git a/src/renderer/lib/kanban.ts b/src/renderer/lib/kanban.tsindex c14c03d6c..46d4187c0 100644--- a/src/renderer/lib/kanban.ts+++ b/src/renderer/lib/kanban.ts@@ -1,6 +1,11 @@-import type { BoardLogAuthor, CanvasNodeState, KanbanAssignment, KanbanCardMeta, KanbanColumn, KanbanLabel, KanbanLabelColor, KanbanPriority, Project, ProjectKanban } from '@shared/types'+import type { CanvasNodeState, KanbanAssignment, KanbanColumn, Project, ProjectKanban } from '@shared/types'import { SYSTEM_NODE_COLORS } from '../state/workspace'import { DEFAULT_BOARD_COLUMNS, makeColumnId } from '@shared/kanban-default-board'+import { autoLabelColor, boardLabels, cardMeta, createLabel, metaList, setCardLabels } from '@shared/kanban-labels'++// The card-meta + label transforms live in `@shared/kanban-labels` (the host core applies the+// same ones for the phone's label verb); re-exported so every renderer import stays as it was.+export * from '@shared/kanban-labels'// Pure kanban board transforms — the ONLY place board structure changes. The UI computes// the next board here and hands it whole to setProjectKanban (no second live source).@@ -176,217 +181,6 @@ export function columnForNode(return a ? k.columns.find((c) => c.id === a.columnId) : undefined}-/** Tolerant read of a card's metadata — `meta` may be absent or (hand-edited) malformed. */-export function cardMeta(k: ProjectKanban, nodeId: string): KanbanCardMeta | undefined {- if (!Array.isArray(k.meta)) return undefined- return k.meta.find((m) => m && m.nodeId === nodeId)-}--const metaList = (k: ProjectKanban): KanbanCardMeta[] => (Array.isArray(k.meta) ? k.meta : [])--/** 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. */-function withCardMeta(- k: ProjectKanban,- nodeId: string,- next: Omit<KanbanCardMeta, 'nodeId'> | null-): ProjectKanban {- const rest = metaList(k).filter((m) => m && m.nodeId !== nodeId)- const keep =- next &&- ((next.assignees?.length ?? 0) > 0 ||- next.dueAt !== undefined ||- next.priority !== undefined ||- (next.labels?.length ?? 0) > 0)- const meta = keep ? [...rest, { nodeId, ...next }] : rest- const { meta: _m, ...bare } = k- return meta.length ? { ...bare, meta } : bare-}--/** Adds the person to the card (or removes them if already assigned — matched by NAME, the- * presence identity's stable part; color is display-only and may drift per machine). */-export function toggleAssignee(- k: ProjectKanban,- nodeId: string,- 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]- return withCardMeta(k, nodeId, {- assignees,- dueAt: cur?.dueAt,- priority: cur?.priority,- labels: cur?.labels- })-}--/** Sets (or clears, with null) the card's due timestamp. */-export function setCardDue(k: ProjectKanban, nodeId: string, dueAt: number | null): ProjectKanban {- const cur = cardMeta(k, nodeId)- return withCardMeta(k, nodeId, {- assignees: cur?.assignees,- priority: cur?.priority,- labels: cur?.labels,- ...(dueAt === null ? {} : { dueAt })- })-}--/** Sets (or clears, with null) the card's priority. */-export function setCardPriority(- k: ProjectKanban,- nodeId: string,- priority: KanbanPriority | null-): ProjectKanban {- const cur = cardMeta(k, nodeId)- return withCardMeta(k, nodeId, {- assignees: cur?.assignees,- dueAt: cur?.dueAt,- labels: cur?.labels,- ...(priority === null ? {} : { priority })- })-}--// ── Board labels (Notion-style palette) ──────────────────────────────────────────────────────--/** Ordered color palette for the picker (also the fallback order). Chip colors live in the UI- * (`kanbanLabelColors.ts`); this is the closed set of names only. */-export const KANBAN_LABEL_COLORS: KanbanLabelColor[] = [- 'default',- 'gray',- 'brown',- 'orange',- 'yellow',- 'green',- 'blue',- 'purple',- 'pink',- 'red'-]--/** Normalize any read color to a known palette value ('default' for garbage from a hand-edited file). */-export function labelColor(c: unknown): KanbanLabelColor {- return KANBAN_LABEL_COLORS.includes(c as KanbanLabelColor) ? (c as KanbanLabelColor) : 'default'-}--/** The board's label palette (defensive against a missing/garbage array), ids+names deduped-safe. */-export function boardLabels(k: ProjectKanban): KanbanLabel[] {- if (!Array.isArray(k.labels)) return []- return k.labels.filter(- (l): l is KanbanLabel => !!l && typeof l.id === 'string' && typeof l.name === 'string'- )-}--/** The resolved labels applied to a card, in palette order, dropping ids with no matching label. */-export function labelsForCard(k: ProjectKanban, nodeId: string): KanbanLabel[] {- const ids = cardMeta(k, nodeId)?.labels- if (!Array.isArray(ids) || !ids.length) return []- const set = new Set(ids)- return boardLabels(k).filter((l) => set.has(l.id))-}--/** Create a new board label; returns the next board AND the new id (so the caller can select it). */-export function createLabel(- k: ProjectKanban,- name: string,- color: KanbanLabelColor-): { k: ProjectKanban; id: string } {- const id = kid('klbl')- const label: KanbanLabel = { id, name: name.trim(), color: labelColor(color) }- return { k: { ...k, labels: [...boardLabels(k), label] }, id }-}--export function renameLabel(k: ProjectKanban, id: string, name: string): ProjectKanban {- return { ...k, labels: boardLabels(k).map((l) => (l.id === id ? { ...l, name: name.trim() } : l)) }-}--export function recolorLabel(k: ProjectKanban, id: string, color: KanbanLabelColor): ProjectKanban {- return {- ...k,- labels: boardLabels(k).map((l) => (l.id === id ? { ...l, color: labelColor(color) } : l))- }-}--/** Deletes a board label AND strips its id from every card's meta (no dangling references). */-export function deleteLabel(k: ProjectKanban, id: string): ProjectKanban {- const labels = boardLabels(k).filter((l) => l.id !== id)- const meta = metaList(k)- .map((m) => (m?.labels?.includes(id) ? { ...m, labels: m.labels.filter((x) => x !== id) } : m))- // an entry emptied to nothing but the nodeId is dropped, matching withCardMeta's invariant- .filter(- (m) =>- (m.assignees?.length ?? 0) > 0 ||- m.dueAt !== undefined ||- m.priority !== undefined ||- (m.labels?.length ?? 0) > 0- )- const { labels: _l, meta: _m, ...bare } = k- return {- ...bare,- ...(labels.length ? { labels } : {}),- ...(meta.length ? { meta } : {})- }-}--/** Moves a label before `beforeId` (null = to the end) — the palette's display order. */-export function reorderLabels(k: ProjectKanban, id: string, beforeId: string | null): ProjectKanban {- if (id === beforeId) return k- const labels = boardLabels(k)- const dragged = labels.find((l) => l.id === id)- if (!dragged) return k- const without = labels.filter((l) => l.id !== id)- const idx = beforeId ? without.findIndex((l) => l.id === beforeId) : -1- const at = idx === -1 ? without.length : idx- return { ...k, labels: [...without.slice(0, at), dragged, ...without.slice(at)] }-}--/** Toggle a label on a card (add if absent, remove if present). Preserves the card's other meta. */-export function toggleCardLabel(k: ProjectKanban, nodeId: string, labelId: string): ProjectKanban {- const cur = cardMeta(k, nodeId)- const has = (cur?.labels ?? []).includes(labelId)- const labels = has- ? (cur?.labels ?? []).filter((x) => x !== labelId)- : [...(cur?.labels ?? []), labelId]- return withCardMeta(k, nodeId, {- assignees: cur?.assignees,- dueAt: cur?.dueAt,- priority: cur?.priority,- labels- })-}--/** Does a card pass the label filter? Empty filter = everything; otherwise the card must carry- * AT LEAST ONE of the selected labels (OR semantics, like Trello's default). */-export function cardMatchesLabelFilter(- k: ProjectKanban,- nodeId: string,- filterIds: readonly string[]-): boolean {- if (!filterIds.length) return true- const on = new Set(cardMeta(k, nodeId)?.labels ?? [])- return filterIds.some((id) => on.has(id))-}--/** Set a card's exact label list (dedup; empty drops the field/entry). */-export function setCardLabels(k: ProjectKanban, nodeId: string, ids: string[]): ProjectKanban {- const cur = cardMeta(k, nodeId)- const labels = [...new Set(ids)]- return withCardMeta(k, nodeId, {- assignees: cur?.assignees,- dueAt: cur?.dueAt,- priority: cur?.priority,- ...(labels.length ? { labels } : {})- })-}--/** Auto-color for a created label: rotate the palette skipping 'default' (Notion-style). */-export function autoLabelColor(k: ProjectKanban): KanbanLabelColor {- const colors = KANBAN_LABEL_COLORS.filter((c) => c !== 'default')- return colors[boardLabels(k).length % colors.length]-}-// ── Unification: legacy free-text node tags → board labels ────────────────────────────────────/** Fold each node's free-text tags into board labels: reuse an existing label by name (case-diff --git a/src/shared/kanban-labels.ts b/src/shared/kanban-labels.tsnew file mode 100644index 000000000..622da05e8--- /dev/null+++ b/src/shared/kanban-labels.ts@@ -0,0 +1,224 @@+import type { BoardLogAuthor, KanbanCardMeta, KanbanLabel, KanbanLabelColor, KanbanPriority, ProjectKanban } from './types'++// Per-card board metadata and the board LABEL palette — pure transforms shared by the renderer+// (the canvas node's "+ Label" row, the kanban card, `LabelPicker`) and the host core (the phone's+// relay `projects.editCardLabels` verb, `core/project-kanban-write.ts`). There is exactly ONE label+// model: a per-project palette in `project.kanban.labels` plus per-card id lists in+// `kanban.meta[].labels`. Both surfaces write it through these functions so a label edited on the+// phone and one edited on the desktop are byte-for-byte the same edit. `renderer/lib/kanban.ts`+// re-exports everything here, so renderer call sites are unchanged.+//+// Every function returns a new board; unknown ids are no-ops returning an equivalent board.++const kid = (prefix: string): string => `${prefix}-${Math.random().toString(36).slice(2, 10)}`++/** Tolerant read of a card's metadata — `meta` may be absent or (hand-edited) malformed. */+export function cardMeta(k: ProjectKanban, nodeId: string): KanbanCardMeta | undefined {+ if (!Array.isArray(k.meta)) return undefined+ return k.meta.find((m) => m && m.nodeId === nodeId)+}++export const metaList = (k: ProjectKanban): KanbanCardMeta[] => (Array.isArray(k.meta) ? k.meta : [])++/** 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(+ k: ProjectKanban,+ nodeId: string,+ next: Omit<KanbanCardMeta, 'nodeId'> | null+): ProjectKanban {+ const rest = metaList(k).filter((m) => m && m.nodeId !== nodeId)+ const keep =+ next &&+ ((next.assignees?.length ?? 0) > 0 ||+ next.dueAt !== undefined ||+ next.priority !== undefined ||+ (next.labels?.length ?? 0) > 0)+ const meta = keep ? [...rest, { nodeId, ...next }] : rest+ const { meta: _m, ...bare } = k+ return meta.length ? { ...bare, meta } : bare+}++/** Adds the person to the card (or removes them if already assigned — matched by NAME, the+ * presence identity's stable part; color is display-only and may drift per machine). */+export function toggleAssignee(+ k: ProjectKanban,+ nodeId: string,+ 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]+ return withCardMeta(k, nodeId, {+ assignees,+ dueAt: cur?.dueAt,+ priority: cur?.priority,+ labels: cur?.labels+ })+}++/** Sets (or clears, with null) the card's due timestamp. */+export function setCardDue(k: ProjectKanban, nodeId: string, dueAt: number | null): ProjectKanban {+ const cur = cardMeta(k, nodeId)+ return withCardMeta(k, nodeId, {+ assignees: cur?.assignees,+ priority: cur?.priority,+ labels: cur?.labels,+ ...(dueAt === null ? {} : { dueAt })+ })+}++/** Sets (or clears, with null) the card's priority. */+export function setCardPriority(+ k: ProjectKanban,+ nodeId: string,+ priority: KanbanPriority | null+): ProjectKanban {+ const cur = cardMeta(k, nodeId)+ return withCardMeta(k, nodeId, {+ assignees: cur?.assignees,+ dueAt: cur?.dueAt,+ labels: cur?.labels,+ ...(priority === null ? {} : { priority })+ })+}++// ── Board labels (Notion-style palette) ──────────────────────────────────────────────────────++/** Ordered color palette for the picker (also the fallback order). Chip colors live in the UI+ * (`kanbanLabelColors.ts`); this is the closed set of names only. */+export const KANBAN_LABEL_COLORS: KanbanLabelColor[] = [+ 'default',+ 'gray',+ 'brown',+ 'orange',+ 'yellow',+ 'green',+ 'blue',+ 'purple',+ 'pink',+ 'red'+]++/** Normalize any read color to a known palette value ('default' for garbage from a hand-edited file). */+export function labelColor(c: unknown): KanbanLabelColor {+ return KANBAN_LABEL_COLORS.includes(c as KanbanLabelColor) ? (c as KanbanLabelColor) : 'default'+}++/** The board's label palette (defensive against a missing/garbage array), ids+names deduped-safe. */+export function boardLabels(k: ProjectKanban): KanbanLabel[] {+ if (!Array.isArray(k.labels)) return []+ return k.labels.filter(+ (l): l is KanbanLabel => !!l && typeof l.id === 'string' && typeof l.name === 'string'+ )+}++/** The resolved labels applied to a card, in palette order, dropping ids with no matching label. */+export function labelsForCard(k: ProjectKanban, nodeId: string): KanbanLabel[] {+ const ids = cardMeta(k, nodeId)?.labels+ if (!Array.isArray(ids) || !ids.length) return []+ const set = new Set(ids)+ return boardLabels(k).filter((l) => set.has(l.id))+}++/** Create a new board label; returns the next board AND the new id (so the caller can select it). */+export function createLabel(+ k: ProjectKanban,+ name: string,+ color: KanbanLabelColor+): { k: ProjectKanban; id: string } {+ const id = kid('klbl')+ const label: KanbanLabel = { id, name: name.trim(), color: labelColor(color) }+ return { k: { ...k, labels: [...boardLabels(k), label] }, id }+}++export function renameLabel(k: ProjectKanban, id: string, name: string): ProjectKanban {+ return { ...k, labels: boardLabels(k).map((l) => (l.id === id ? { ...l, name: name.trim() } : l)) }+}++export function recolorLabel(k: ProjectKanban, id: string, color: KanbanLabelColor): ProjectKanban {+ return {+ ...k,+ labels: boardLabels(k).map((l) => (l.id === id ? { ...l, color: labelColor(color) } : l))+ }+}++/** Deletes a board label AND strips its id from every card's meta (no dangling references). */+export function deleteLabel(k: ProjectKanban, id: string): ProjectKanban {+ const labels = boardLabels(k).filter((l) => l.id !== id)+ const meta = metaList(k)+ .map((m) => (m?.labels?.includes(id) ? { ...m, labels: m.labels.filter((x) => x !== id) } : m))+ // an entry emptied to nothing but the nodeId is dropped, matching withCardMeta's invariant+ .filter(+ (m) =>+ (m.assignees?.length ?? 0) > 0 ||+ m.dueAt !== undefined ||+ m.priority !== undefined ||+ (m.labels?.length ?? 0) > 0+ )+ const { labels: _l, meta: _m, ...bare } = k+ return {+ ...bare,+ ...(labels.length ? { labels } : {}),+ ...(meta.length ? { meta } : {})+ }+}++/** Moves a label before `beforeId` (null = to the end) — the palette's display order. */+export function reorderLabels(k: ProjectKanban, id: string, beforeId: string | null): ProjectKanban {+ if (id === beforeId) return k+ const labels = boardLabels(k)+ const dragged = labels.find((l) => l.id === id)+ if (!dragged) return k+ const without = labels.filter((l) => l.id !== id)+ const idx = beforeId ? without.findIndex((l) => l.id === beforeId) : -1+ const at = idx === -1 ? without.length : idx+ return { ...k, labels: [...without.slice(0, at), dragged, ...without.slice(at)] }+}++/** Toggle a label on a card (add if absent, remove if present). Preserves the card's other meta. */+export function toggleCardLabel(k: ProjectKanban, nodeId: string, labelId: string): ProjectKanban {+ const cur = cardMeta(k, nodeId)+ const has = (cur?.labels ?? []).includes(labelId)+ const labels = has+ ? (cur?.labels ?? []).filter((x) => x !== labelId)+ : [...(cur?.labels ?? []), labelId]+ return withCardMeta(k, nodeId, {+ assignees: cur?.assignees,+ dueAt: cur?.dueAt,+ priority: cur?.priority,+ labels+ })+}++/** Does a card pass the label filter? Empty filter = everything; otherwise the card must carry+ * AT LEAST ONE of the selected labels (OR semantics, like Trello's default). */+export function cardMatchesLabelFilter(+ k: ProjectKanban,+ nodeId: string,+ filterIds: readonly string[]+): boolean {+ if (!filterIds.length) return true+ const on = new Set(cardMeta(k, nodeId)?.labels ?? [])+ return filterIds.some((id) => on.has(id))+}++/** Set a card's exact label list (dedup; empty drops the field/entry). */+export function setCardLabels(k: ProjectKanban, nodeId: string, ids: string[]): ProjectKanban {+ const cur = cardMeta(k, nodeId)+ const labels = [...new Set(ids)]+ return withCardMeta(k, nodeId, {+ assignees: cur?.assignees,+ dueAt: cur?.dueAt,+ priority: cur?.priority,+ ...(labels.length ? { labels } : {})+ })+}++/** Auto-color for a created label: rotate the palette skipping 'default' (Notion-style). */+export function autoLabelColor(k: ProjectKanban): KanbanLabelColor {+ const colors = KANBAN_LABEL_COLORS.filter((c) => c !== 'default')+ return colors[boardLabels(k).length % colors.length]+}