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(relay): serve the phone's kanban board — create it, and move cards on SSH projects
enes25f3ee7137c4
diff --git a/CLAUDE.md b/CLAUDE.mdindex ffa1b3628..27edd5364 100644--- a/CLAUDE.md+++ b/CLAUDE.md@@ -3337,7 +3337,26 @@ the Settings section and ShortcutsPanel start disagreeing about what a chord meahalf-pill itself: (`components/kanban/ColumnPill.tsx`, `columnForNode` in lib/kanban; renderedas 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: no- agent-driven card movement yet, no board undo, mobile N/A.+ agent-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+ LAZY default — `kanban` is not written until the user's first board edit — so most project files+ carry 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 columns+ therefore live in `@shared/kanban-default-board`, read by `defaultKanban()` AND by the core seeder,+ and copied verbatim (under a pinning test on both sides) by iOS `KanbanDefaults`. (2) An SSH+ project's file is on a THIRD machine the phone has no credentials for; the verb writes the entry's+ `cache` and lets the ordinary mirror push it, which is exactly what a desktop card drag does — so+ it needs nothing new from `reconcileSsh` (that decides by `rev` and unions only `nodes`). Its cache+ change IS persisted to workspace.json, because for an ssh entry the cache is the local record. (3)+ The phone's older direct-SSH write inlines the whole project.json into one argv string and so dies+ at Linux's `MAX_ARG_STRLEN` — this repo's own `.nodeterm/project.json` measured 114,695 bytes,+ ~15 KB under the 128 KB ceiling. **Both verbs announce their write on `workspaceExternalChange`+ and that is not optional**: the renderer holds its own board and the next whole-workspace save+ serializes THAT, so a change the renderer never heard about is one the next autosave reverts.- **Omni Kanban (global swimlanes)** (`components/kanban/GlobalKanbanView.tsx`; one swimlane per open project; `state/viewMode.ts` `globalKanban` (localStorage `nodeterm.globalKanban`, machine-local, like `viewByProject`) + `settings.omniKanbanEnabled` (feature gate, default OFF, `settings.json`) / `omniKanbanAsDefault` (when true, `view.kanbanToggle` — Cmd+Shift+B — opens Omni; otherwise per-project; `view.globalKanbanToggle` registry command — unbound, remappable — always opens Omni when enabled); `TabBar` and the menu IPC `onToggleKanban` share one `performKanbanToggle` decision, and `isGlobalKanbanOpen()` is the single gate (fail-closed, static import of `useSettings` — the earlier `require` failed open in the packaged renderer). The active project's lane is derived from serialized `p.nodes` via `toKanbanSessionState` — the persisted-state counterpart to `toKanbanSession` — and is committed (`commitActiveToStore`) before the overlay mounts so live React Flow edits are not stale; `pendingLaunch` never becomes `initialCommand` in the modal (the DAG launch must fire only when dependencies report done, and the canvas `TerminalNode` already delivers `initialCommand` via `writeWhenShellReady` after the `nodeterm:create-node` project switch). Active-project edits (rename / sticky / browser nav) route through Canvas live nodes (`setNodes` + `markDirty`), non-active through the store + `writeDisk`; delete uses `ConfirmDialog` (not `confirm`) and SSH-aware teardown (`transport.destroy` locally vs `sshProject.killSessions` with `everySocket` for a remote owner, plus `agentStatus` / `agentNodes` / `webviewKeepAlive` cleanup). The top bar's project pills and Cmd/Ctrl+1..9 (`nodeterm:swimlane-jump`) jump to the lane; header hint shows the correct mod (`Cmd` on Mac, `Ctrl` elsewhere). Server Edition works as-is, Mobile N/A.- **Settings** (`SettingsPage.tsx`, ⚙ / ⌘,): font/cursor (live to xterm + Monaco), defaultshell, grid + snap, **default node size** (`defaultNodeWidth`/`defaultNodeHeight` — newdiff --git a/src/core/project-kanban-write.test.ts b/src/core/project-kanban-write.test.tsnew file mode 100644index 000000000..f70bc55ef--- /dev/null+++ b/src/core/project-kanban-write.test.ts@@ -0,0 +1,147 @@+import { describe, expect, it } from 'vitest'+import { ensureProjectBoard, setProjectCardColumn } from './project-kanban-write'+import { DEFAULT_BOARD_COLUMNS } from '../shared/kanban-default-board'++const NOW = new Date('2026-09-10T12:00:00.000Z')++function file(extra: Record<string, unknown> = {}): string {+ return JSON.stringify({+ version: 1,+ rev: 7,+ savedAt: '2026-01-01T00:00:00.000Z',+ name: 'p',+ color: '#0a84ff',+ nodes: [{ id: 'term-a-1', kind: 'terminal' }],+ ...extra+ })+}++const parse = (s: string | null): Record<string, any> => JSON.parse(s ?? 'null')++describe('ensureProjectBoard', () => {+ it('seeds the shared default columns, in order, on a project with no board', () => {+ const out = parse(ensureProjectBoard(file(), NOW, () => 'kcol-fixed'))+ expect(out.kanban.columns.map((c: { title: string }) => c.title)).toEqual(+ DEFAULT_BOARD_COLUMNS.map((c) => c.title)+ )+ expect(out.kanban.columns.map((c: { color: string }) => c.color)).toEqual(+ DEFAULT_BOARD_COLUMNS.map((c) => c.color)+ )+ expect(out.kanban.assignments).toEqual([])+ expect(out.rev).toBe(8)+ expect(out.savedAt).toBe(NOW.toISOString())+ })++ it('mints a distinct id per column, in the desktop shape', () => {+ const out = parse(ensureProjectBoard(file(), NOW))+ const ids: string[] = out.kanban.columns.map((c: { id: string }) => c.id)+ expect(new Set(ids).size).toBe(3)+ for (const id of ids) expect(id).toMatch(/^kcol-[a-z0-9]{1,8}$/)+ })++ it('is idempotent: a board that already has a column is not touched', () => {+ const raw = file({ kanban: { columns: [{ id: 'kcol-x', title: 'Mine', color: '#fff' }], assignments: [] } })+ expect(ensureProjectBoard(raw, NOW)).toBeNull()+ })++ it('seeds over an EMPTY columns array (a board block with nothing in it is no board)', () => {+ const out = parse(ensureProjectBoard(file({ kanban: { columns: [], assignments: [] } }), NOW))+ expect(out.kanban.columns).toHaveLength(3)+ })++ it('keeps board metadata the phone has no UI for', () => {+ const raw = file({ kanban: { columns: [], meta: [{ nodeId: 'term-a-1', priority: 'high' }], labels: [{ id: 'l1' }] } })+ const out = parse(ensureProjectBoard(raw, NOW))+ expect(out.kanban.meta).toEqual([{ nodeId: 'term-a-1', priority: 'high' }])+ expect(out.kanban.labels).toEqual([{ id: 'l1' }])+ })++ it('round-trips every field this version does not know', () => {+ const out = parse(ensureProjectBoard(file({ bridges: [{ id: 'b' }], somethingFuture: 42 }), NOW))+ expect(out.bridges).toEqual([{ id: 'b' }])+ expect(out.somethingFuture).toBe(42)+ })++ it('refuses a file it could not parse, or one of another shape', () => {+ expect(ensureProjectBoard('{not json', NOW)).toBeNull()+ expect(ensureProjectBoard('[]', NOW)).toBeNull()+ expect(ensureProjectBoard(JSON.stringify({ version: 2, rev: 1, nodes: [] }), NOW)).toBeNull()+ expect(ensureProjectBoard(JSON.stringify({ version: 1, nodes: [] }), NOW)).toBeNull()+ })++ it('refuses a `kanban` that is not an object rather than replacing it', () => {+ expect(ensureProjectBoard(file({ kanban: 'nope' }), NOW)).toBeNull()+ expect(ensureProjectBoard(file({ kanban: [] }), NOW)).toBeNull()+ })+})++describe('setProjectCardColumn', () => {+ const board = (assignments: unknown[] = []): string =>+ file({+ kanban: {+ columns: [+ { id: 'kcol-a', title: 'To Do', color: '#0a84ff' },+ { id: 'kcol-b', title: 'Done', color: '#32d74b' }+ ],+ assignments,+ meta: [{ nodeId: 'term-a-1', priority: 'high' }]+ }+ })++ it('assigns an unassigned card and bumps rev', () => {+ const out = parse(setProjectCardColumn(board(), 'term-a-1', 'kcol-a', NOW))+ expect(out.kanban.assignments).toEqual([{ nodeId: 'term-a-1', columnId: 'kcol-a' }])+ expect(out.rev).toBe(8)+ })++ it('re-points an existing assignment instead of adding a second one', () => {+ const out = parse(+ setProjectCardColumn(board([{ nodeId: 'term-a-1', columnId: 'kcol-a' }]), 'term-a-1', 'kcol-b', NOW)+ )+ expect(out.kanban.assignments).toEqual([{ nodeId: 'term-a-1', columnId: 'kcol-b' }])+ })++ it('columnId null drops the assignment (the virtual Ungrouped column)', () => {+ const out = parse(+ setProjectCardColumn(board([{ nodeId: 'term-a-1', columnId: 'kcol-a' }]), 'term-a-1', null, NOW)+ )+ expect(out.kanban.assignments).toEqual([])+ })++ it('leaves other cards, and the card metadata, alone', () => {+ const out = parse(+ setProjectCardColumn(board([{ nodeId: 'term-z-9', columnId: 'kcol-b' }]), 'term-a-1', 'kcol-a', NOW)+ )+ expect(out.kanban.assignments).toEqual([+ { nodeId: 'term-z-9', columnId: 'kcol-b' },+ { nodeId: 'term-a-1', columnId: 'kcol-a' }+ ])+ expect(out.kanban.meta).toEqual([{ nodeId: 'term-a-1', priority: 'high' }])+ })++ it('refuses a column this board does not have', () => {+ expect(setProjectCardColumn(board(), 'term-a-1', 'kcol-gone', NOW)).toBeNull()+ })++ it('refuses a no-op move (a retry must not churn rev)', () => {+ expect(+ setProjectCardColumn(board([{ nodeId: 'term-a-1', columnId: 'kcol-a' }]), 'term-a-1', 'kcol-a', NOW)+ ).toBeNull()+ expect(setProjectCardColumn(board(), 'term-a-1', null, NOW)).toBeNull()+ })++ it('accepts a node id the canvas does not list yet (it may have just been registered)', () => {+ const out = parse(setProjectCardColumn(board(), 'term-new-1', 'kcol-a', NOW))+ expect(out.kanban.assignments).toEqual([{ nodeId: 'term-new-1', columnId: 'kcol-a' }])+ })++ it('refuses a project with no board at all — the caller seeds one first', () => {+ expect(setProjectCardColumn(file(), 'term-a-1', 'kcol-a', NOW)).toBeNull()+ expect(setProjectCardColumn(file(), 'term-a-1', null, NOW)).toBeNull()+ })++ it('refuses an empty node id and an unparsable file', () => {+ expect(setProjectCardColumn(board(), '', 'kcol-a', NOW)).toBeNull()+ expect(setProjectCardColumn('{not json', 'term-a-1', 'kcol-a', NOW)).toBeNull()+ })+})diff --git a/src/core/project-kanban-write.ts b/src/core/project-kanban-write.tsnew file mode 100644index 000000000..9b528df95--- /dev/null+++ b/src/core/project-kanban-write.ts@@ -0,0 +1,117 @@+// 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).+//+// 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+// schema — and, crucially, `kanban.meta` / `kanban.labels` / `kanban.github`, which only the desktop+// authors) round-trips untouched. The file is rewritten whole; a decode into a mirror would silently+// drop the parts of the board this surface has no UI for.+//+// Returns null whenever nothing must be written: unparsable/wrong-shape text (a file we could not+// parse must never be invented or overwritten), or a request that is already satisfied (a board that+// exists, a card already in that column) — a retry must not churn `rev`.++import { DEFAULT_BOARD_COLUMNS, makeColumnId } from '../shared/kanban-default-board'++/** Parse `raw` as the `{version:1, rev, nodes}` project file, or null. */+function parseProjectFile(raw: string): Record<string, unknown> | null {+ let root: Record<string, unknown>+ try {+ const parsed: unknown = JSON.parse(raw)+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) return null+ root = parsed as Record<string, unknown>+ } catch {+ return null+ }+ if (root.version !== 1 || typeof root.rev !== 'number' || !Array.isArray(root.nodes)) return null+ return root+}++function bumped(root: Record<string, unknown>, now: Date): string {+ root.rev = (root.rev as number) + 1+ root.savedAt = now.toISOString()+ return JSON.stringify(root, null, 2)+}++/** The board block as an object we may extend, or an empty one. A `kanban` of the wrong shape+ * (hand-edited, a future schema) is NOT overwritten — the caller gets null and says so. */+function boardOf(root: Record<string, unknown>): Record<string, unknown> | null {+ const k = root.kanban+ if (k === undefined || k === null) return {}+ if (typeof k !== 'object' || Array.isArray(k)) return null+ return k as Record<string, unknown>+}++function columnsOf(board: Record<string, unknown>): Array<Record<string, unknown>> {+ return Array.isArray(board.columns) ? (board.columns as Array<Record<string, unknown>>) : []+}++/**+ * Seed the three default columns on a project whose file has no board yet — the write the desktop+ * deliberately does NOT make until the user's first board edit (`defaultKanban`'s lazy-default+ * rule), and which therefore leaves most projects with no board at all. That was invisible on the+ * desktop (the canvas renders the lazy default) and fatal on the phone, whose Board affordance+ * asked "does this file have columns?" and so never appeared.+ *+ * IDEMPOTENT: a project that already has at least one column is left exactly as it is and returns+ * null. That is the whole safety property — the phone may ask on every Board tap, and it can never+ * be the thing that replaces a board someone built.+ */+export function ensureProjectBoard(raw: string, now: Date, mintId = makeColumnId): string | null {+ const root = parseProjectFile(raw)+ if (!root) return null+ const board = boardOf(root)+ if (!board) return null+ if (columnsOf(board).length > 0) return null+ board.columns = DEFAULT_BOARD_COLUMNS.map((c) => ({ id: mintId(), title: c.title, color: c.color }))+ if (!Array.isArray(board.assignments)) board.assignments = []+ root.kanban = board+ return bumped(root, now)+}++/**+ * Move one card to `columnId`, or to the virtual Ungrouped column (`columnId === null`).+ *+ * Only `kanban.assignments` is touched: `meta` (assignees / due / priority / labels) is independent+ * of placement on the desktop too, and a move must not disturb it.+ *+ * Refused (null, nothing written):+ * - the file is not the shape we know;+ * - `columnId` names a column this board does not have — the phone's board could be a few seconds+ * stale, and inventing the column (or writing a dangling assignment that every reader then+ * buckets as Ungrouped) would silently do something other than what the user asked;+ * - the card is already exactly where it was asked to go.+ *+ * A `nodeId` that is not on this canvas is NOT refused: node ids are also tmux session names, and a+ * session registered a moment ago by the other write path may not be in the copy we just read. The+ * assignment simply waits for it — dangling assignments are already normal (a deleted node leaves+ * one) and every reader prunes them lazily.+ */+export function setProjectCardColumn(+ raw: string,+ nodeId: string,+ columnId: string | null,+ now: Date+): string | null {+ if (typeof nodeId !== 'string' || !nodeId) return null+ const root = parseProjectFile(raw)+ if (!root) return null+ const board = boardOf(root)+ if (!board) return null+ const columns = columnsOf(board)+ if (columnId !== null && !columns.some((c) => c?.id === columnId)) return null++ const before = Array.isArray(board.assignments)+ ? (board.assignments as Array<Record<string, unknown>>)+ : []+ const current = before.find((a) => a?.nodeId === nodeId)?.columnId+ // Already there — including "already Ungrouped", which is what an ABSENT assignment means.+ if ((current ?? null) === columnId) return null++ const kept = before.filter((a) => a?.nodeId !== nodeId)+ board.assignments = columnId === null ? kept : [...kept, { nodeId, columnId }]+ if (!Array.isArray(board.columns)) board.columns = columns+ root.kanban = board+ return bumped(root, now)+}diff --git a/src/core/workspace-store.kanban.test.ts b/src/core/workspace-store.kanban.test.tsnew file mode 100644index 000000000..0254b9c66--- /dev/null+++ b/src/core/workspace-store.kanban.test.ts@@ -0,0 +1,268 @@+import { describe, it, expect, beforeEach, afterEach } from 'vitest'+import { promises as fs } from 'fs'+import os from 'os'+import path from 'path'+import { initPlatform, resetPlatformForTests } from './platform'+import { fakePlatform } from './platform-fake'+import { WorkspaceStore, type RemoteWorkspaceIO } from './workspace-store'+import { DEFAULT_BOARD_COLUMNS } from '../shared/kanban-default-board'+import type { Project, Workspace } from '../shared/types'++// The host side of the phone's Board sheet (`projects.ensureBoard` / `projects.setCardColumn`).+// Two project kinds, deliberately covered separately: a LOCAL ref writes its own file, and an SSH+// ref's file is on a third machine — the phone can never reach it, so the write lands in this+// desktop's cache and rides the ordinary mirror. That second half is the whole reason the verbs+// exist rather than more direct SSH from the phone.++let userData: string+let projRoot: string+let fake: ReturnType<typeof fakePlatform>++const project = (over: Partial<Project> = {}): Project => ({+ id: 'p1', name: 'foo', color: '#7aa2f7', viewport: { x: 0, y: 0, zoom: 1 },+ nodes: [{ id: 'term-1', kind: 'terminal', position: { x: 0, y: 0 }, size: { width: 1, height: 1 }, title: 't', color: '#fff', group: null }],+ ...over+})+const ws = (projects: Project[]): Workspace =>+ ({ version: 2, activeProjectId: projects[0]?.id ?? '', projects })+const SSH = { server: { host: 'h', user: 'u' }, remoteCwd: '~/x' } as unknown as Project['ssh']++const projectFile = (): string => path.join(projRoot, '.nodeterm/project.json')+const readFile = async (): Promise<Record<string, any>> =>+ JSON.parse(await fs.readFile(projectFile(), 'utf-8'))+const externalChanges = (): Record<string, any>[] =>+ fake.sent.filter((s) => s.channel === 'workspace:external-change').map((s) => s.args[0])++/** An ssh IO whose "server" is one in-memory string, so a mirror write is observable. */+function fakeRemote(initial: string | null = null): RemoteWorkspaceIO & { content: string | null; writes: number } {+ const io = {+ content: initial,+ writes: 0,+ async read() {+ return io.content === null+ ? ({ status: 'absent' } as const)+ : ({ status: 'ok', content: io.content } as const)+ },+ async write(_id: string, _ssh: never, content: string) {+ io.content = content+ io.writes+++ return true+ }+ }+ return io as never+}++beforeEach(async () => {+ userData = await fs.mkdtemp(path.join(os.tmpdir(), 'nt-ws-'))+ projRoot = await fs.mkdtemp(path.join(os.tmpdir(), 'nt-proj-'))+ fake = fakePlatform({ userDataDir: userData })+ initPlatform(fake)+})+afterEach(async () => {+ resetPlatformForTests()+ await fs.rm(userData, { recursive: true, force: true })+ await fs.rm(projRoot, { recursive: true, force: true })+})++describe('ensureRemoteBoard (the phone creating a board that never existed)', () => {+ // The gap this closes: the desktop writes `kanban` only on the user's FIRST board edit, so most+ // project files have no board at all — and the phone, which knows a project only by its file,+ // showed no Board button on any of them.+ it('seeds the shared default columns into a local ref project file and announces it', async () => {+ const store = new WorkspaceStore()+ await store.save(ws([project({ cwd: projRoot })]))+ expect((await readFile()).kanban).toBeUndefined()+ fake.sent.length = 0++ const columns = await store.ensureRemoteBoard('p1')+ expect(columns?.map((c) => c.title)).toEqual(DEFAULT_BOARD_COLUMNS.map((c) => c.title))+ expect(columns?.map((c) => c.color)).toEqual(DEFAULT_BOARD_COLUMNS.map((c) => c.color))++ const file = await readFile()+ expect(file.kanban.columns).toHaveLength(3)+ expect(file.rev).toBe(2)+ // Ours, and announced by us — the renderer must adopt it or the next autosave reverts it.+ expect(store.isSelfWrite(projectFile(), await fs.readFile(projectFile(), 'utf-8'))).toBe(true)+ expect(externalChanges()).toHaveLength(1)+ expect(externalChanges()[0].kanban.columns).toHaveLength(3)+ })++ it('is idempotent: an existing board comes back untouched, with no second write', async () => {+ const store = new WorkspaceStore()+ const kanban = { columns: [{ id: 'kcol-mine', title: 'Mine', color: '#fff' }], assignments: [] }+ await store.save(ws([project({ cwd: projRoot, kanban })]))+ const before = await readFile()++ const columns = await store.ensureRemoteBoard('p1')+ expect(columns).toEqual(kanban.columns)+ expect(await readFile()).toEqual(before) // rev included: no churn+ })++ it('refuses a project it cannot write a file for', async () => {+ const store = new WorkspaceStore()+ await store.save(ws([project({ cwd: projRoot }), project({ id: 'inline1' })]))+ expect(await store.ensureRemoteBoard('nope')).toBeNull()+ expect(await store.ensureRemoteBoard('inline1')).toBeNull()+ await fs.writeFile(projectFile(), '{ not json')+ expect(await store.ensureRemoteBoard('p1')).toBeNull()+ expect(await fs.readFile(projectFile(), 'utf-8')).toBe('{ not json') // untouched+ })+})++describe('setRemoteCardColumn (the phone moving a card)', () => {+ const withBoard = (): Project =>+ project({+ cwd: projRoot,+ kanban: {+ columns: [+ { id: 'kcol-a', title: 'To Do', color: '#0a84ff' },+ { id: 'kcol-b', title: 'Done', color: '#32d74b' }+ ],+ assignments: []+ }+ })++ it('writes the assignment into a local ref project file and announces it', async () => {+ const store = new WorkspaceStore()+ await store.save(ws([withBoard()]))+ fake.sent.length = 0++ expect(await store.setRemoteCardColumn('p1', 'term-1', 'kcol-b')).toBe(true)+ expect((await readFile()).kanban.assignments).toEqual([{ nodeId: 'term-1', columnId: 'kcol-b' }])+ expect(externalChanges()).toHaveLength(1)+ expect(externalChanges()[0].kanban.assignments).toEqual([{ nodeId: 'term-1', columnId: 'kcol-b' }])+ })++ it('null moves the card to Ungrouped', async () => {+ const store = new WorkspaceStore()+ await store.save(ws([withBoard()]))+ await store.setRemoteCardColumn('p1', 'term-1', 'kcol-a')+ expect(await store.setRemoteCardColumn('p1', 'term-1', null)).toBe(true)+ expect((await readFile()).kanban.assignments).toEqual([])+ })++ // False is an ANSWER the phone shows the user, not a silent no-op — the behaviour this whole+ // change exists to remove.+ it('answers false, writing nothing, for an unknown column / project and a no-op move', async () => {+ const store = new WorkspaceStore()+ await store.save(ws([withBoard()]))+ const before = await readFile()+ expect(await store.setRemoteCardColumn('p1', 'term-1', 'kcol-gone')).toBe(false)+ expect(await store.setRemoteCardColumn('nope', 'term-1', 'kcol-a')).toBe(false)+ expect(await store.setRemoteCardColumn('p1', 'term-1', null)).toBe(false) // already Ungrouped+ expect(await readFile()).toEqual(before)+ })++ it('leaves card metadata the phone cannot author alone', async () => {+ const store = new WorkspaceStore()+ const p = withBoard()+ p.kanban!.meta = [{ nodeId: 'term-1', priority: 'high', assignees: [], labels: [] } as never]+ await store.save(ws([p]))+ await store.setRemoteCardColumn('p1', 'term-1', 'kcol-a')+ expect((await readFile()).kanban.meta).toEqual([+ { nodeId: 'term-1', priority: 'high', assignees: [], labels: [] }+ ])+ })++ // The save chain is the same invariant appendRemoteNode documents: this rewrites the very file a+ // save rewrites whole, and unserialized the save's copy — which never saw the move — lands last.+ it('is serialized with saves', async () => {+ const store = new WorkspaceStore()+ await store.save(ws([withBoard()]))+ const saving = store.save(ws([{ ...withBoard(), name: 'renamed' }]))+ const moving = store.setRemoteCardColumn('p1', 'term-1', 'kcol-a')+ expect(await moving).toBe(true)+ await saving+ const file = await readFile()+ expect(file.kanban.assignments).toEqual([{ nodeId: 'term-1', columnId: 'kcol-a' }])+ expect(file.name).toBe('renamed')+ })+})++describe('an SSH project (the case the phone can never write itself)', () => {+ // The phone reaches THIS desktop. An ssh ref's `.nodeterm/project.json` is on a third machine it+ // has no credentials for, so the write goes exactly where a desktop card drag's goes: into this+ // entry's cache, rev-bumped, then out on the ordinary mirror — which is why it needs nothing new+ // from `reconcileSsh` (that decides by rev and unions only `nodes`).+ const sshProject = (kanban?: Project['kanban']): Project =>+ project({ id: 'ssh1', cwd: undefined, ssh: SSH, ...(kanban ? { kanban } : {}) })++ it('seeds a board into the entry cache and mirrors it to the server', async () => {+ const io = fakeRemote()+ const store = new WorkspaceStore(io)+ await store.save(ws([sshProject()]))+ const mirrorsBefore = io.writes+ fake.sent.length = 0++ const columns = await store.ensureRemoteBoard('ssh1')+ expect(columns?.map((c) => c.title)).toEqual(DEFAULT_BOARD_COLUMNS.map((c) => c.title))+ expect(io.writes).toBeGreaterThan(mirrorsBefore)+ expect(JSON.parse(io.content!).kanban.columns).toHaveLength(3)+ // Announced, so the live canvas adopts it instead of the next autosave writing the old board back.+ expect(externalChanges()[0]).toMatchObject({ id: 'ssh1' })+ expect(externalChanges()[0].kanban.columns).toHaveLength(3)+ })++ it('moves a card and mirrors it, and the reloaded workspace carries the move', async () => {+ const io = fakeRemote()+ const store = new WorkspaceStore(io)+ await store.save(ws([sshProject({+ columns: [{ id: 'kcol-a', title: 'To Do', color: '#0a84ff' }],+ assignments: []+ })]))++ expect(await store.setRemoteCardColumn('ssh1', 'term-1', 'kcol-a')).toBe(true)+ expect(JSON.parse(io.content!).kanban.assignments).toEqual([{ nodeId: 'term-1', columnId: 'kcol-a' }])+ const reloaded = await new WorkspaceStore(io).load()+ expect(reloaded.projects.find((p) => p.id === 'ssh1')?.kanban?.assignments)+ .toEqual([{ nodeId: 'term-1', columnId: 'kcol-a' }])+ })++ // Every refusal reason stays a refusal on this path too — a cache write that cannot be described+ // as the requested change must not be mirrored as if it were.+ it('answers false for an unknown column and writes nothing', async () => {+ const io = fakeRemote()+ const store = new WorkspaceStore(io)+ await store.save(ws([sshProject({ columns: [{ id: 'kcol-a', title: 'To Do', color: '#0a84ff' }], assignments: [] })]))+ const mirrored = io.content+ const writes = io.writes+ expect(await store.setRemoteCardColumn('ssh1', 'term-1', 'kcol-gone')).toBe(false)+ expect(io.content).toBe(mirrored)+ expect(io.writes).toBe(writes)+ })++ // A mirror that cannot land (host asleep, dial flapped) must leave the change OWED, not lost: the+ // answer to the phone is about the board, and the next save retries the push. The save here+ // carries the board because the renderer ADOPTED the broadcast — which is the contract this path+ // depends on, and the reason the broadcast is not optional: a renderer that never heard about the+ // change would serialize its old board over it on the very next autosave.+ it('keeps the change when the mirror write fails, and a later save pushes it', async () => {+ const io = fakeRemote()+ let allowWrite = false+ const flaky = { ...io, write: async (id: string, ssh: never, content: string) => allowWrite && io.write(id, ssh, content) }+ const store = new WorkspaceStore(flaky as never)+ await store.save(ws([sshProject()]))+ fake.sent.length = 0++ expect(await store.ensureRemoteBoard('ssh1')).toHaveLength(3)+ expect(io.content).toBeNull() // nothing reached the server yet++ allowWrite = true+ const adopted = externalChanges()[0] as Project+ await store.save(ws([adopted]))+ expect(JSON.parse(io.content!).kanban.columns).toHaveLength(3)+ })++ // The ssh cache is not on this machine's disk as a project.json — it lives in workspace.json, so+ // a change kept only in memory is one an app restart silently drops.+ it('persists the cache change to the index, so a restart still has the board', async () => {+ const io = fakeRemote()+ const store = new WorkspaceStore(io)+ await store.save(ws([sshProject()]))+ await store.ensureRemoteBoard('ssh1')++ const index = JSON.parse(await fs.readFile(path.join(userData, 'workspace.json'), 'utf-8'))+ const entry = index.entries.find((x: { id: string }) => x.id === 'ssh1')+ expect(entry.cache.kanban.columns).toHaveLength(3)+ })+})diff --git a/src/core/workspace-store.ts b/src/core/workspace-store.tsindex dd881aee2..5b2827187 100644--- a/src/core/workspace-store.ts+++ b/src/core/workspace-store.ts@@ -6,7 +6,8 @@ import { IPC } from '../shared/ipc'import { platform } from './platform'import {DEFAULT_PROJECT_ID, EMPTY_WORKSPACE,- type BridgeLink, type CanvasNodeState, type Project, type Workspace, type WorkspaceV1+ type BridgeLink, type CanvasNodeState, type KanbanColumn, type Project, type Workspace,+ type WorkspaceV1} from '../shared/types'import {PROJECT_DIR, PROJECT_FILE, fileToProject, inlineProjectFileRelPath, isInlineProjectFileId,@@ -27,6 +28,7 @@ import type { CapabilityAckMap } from './project-capability-consent'import { hoistLegacyNodeExec, type LocalNodeExecMap } from '../shared/node-exec'import { collisionSeed, derivedProjectId, freshProjectId } from '../shared/project-id'import { appendProjectNode, removeProjectNode, type RemoteNodeInput } from './project-node-append'+import { ensureProjectBoard, setProjectCardColumn } from './project-kanban-write'/** 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). */@@ -781,16 +783,20 @@ export class WorkspaceStore {* index write, so it can neither interleave with a save's own rewrite nor invent entries: it* persists exactly what `this.index` already holds (and does nothing before the first load). */private persistIndexNow(): Promise<void> {- const run = this.saveChain.then(async () => {- const index = this.index- if (!index) return- this.applySettingsToIndex(index)- await writeAtomic(this.indexPath, JSON.stringify(index))- })+ const run = this.saveChain.then(() => this.writeIndexNow())this.saveChain = run.catch(() => {})return run}+ /** The index write itself, WITHOUT queueing — for callers that are already running on+ * `saveChain` (queueing from inside a chain step would wait on the step itself). */+ private async writeIndexNow(): Promise<void> {+ const index = this.index+ if (!index) return+ this.applySettingsToIndex(index)+ await writeAtomic(this.indexPath, JSON.stringify(index))+ }+/*** Reads + parses one project file. Only the authoritative loadV3 path passes `sideline: true`,* which renames an unparsable/wrong-shape file to `.corrupt-<ts>` so a later save can't overwrite@@ -1658,6 +1664,182 @@ export class WorkspaceStore {return false}+ /**+ * Give a project a kanban board if it has none — the host side of the relay+ * `projects.ensureBoard` verb, i.e. the phone tapping "Board" on a project that has never had+ * one. Returns the board's columns (the ones it just seeded, or the ones already there), or null+ * when this project cannot have a board written at all.+ *+ * **Why the phone needs a verb for this at all.** The desktop's board is a LAZY default: the+ * canvas renders `kanban ?? defaultKanban()` and the `kanban` block is not written to the file+ * until the user's first board edit. So on a fresh project the columns exist only in the+ * renderer's memory — and the phone, which knows a project solely by its `.nodeterm/project.json`,+ * saw a project with no board and could not offer one. (Measured on the author's own machine:+ * 1 of 13 project files had a `kanban` block.) Seeding the SAME three columns from the SAME+ * shared definition (`@shared/kanban-default-board`) is what makes a board created on the phone+ * and a board created on the desktop the same board.+ *+ * IDEMPOTENT, and that is the safety property: an existing board is returned untouched and+ * nothing is written, so the phone may ask on every tap.+ */+ ensureRemoteBoard(projectId: string, now = new Date()): Promise<KanbanColumn[] | null> {+ const run = this.saveChain.then(() =>+ this.kanbanWriteNow(projectId, (raw) => ensureProjectBoard(raw, now))+ )+ this.saveChain = run.catch(() => {})+ // The board that is THERE NOW, whether this call seeded it or found it. `ensureProjectBoard`+ // returns null for BOTH "already has one" and "this board is not a shape I may replace", so the+ // answer comes off the file rather than off whether a write happened — a project with a+ // board is a project with a board, and the phone asks this on every Board tap.+ return run.then((res) => (res ? (res.file.kanban?.columns ?? null) : null))+ }++ /**+ * Move one session card to a board column (`columnId: null` = the virtual Ungrouped column) — the+ * host side of the relay `projects.setCardColumn` verb.+ *+ * The phone has been able to do this over DIRECT SSH since the board shipped, by rewriting the+ * whole project.json itself. That path has two holes this verb closes: it cannot reach an SSH+ * project (whose file lives on a third machine), and it carries the entire file in one argv+ * string, so it stops working — silently — once the file passes Linux's 128 KB `MAX_ARG_STRLEN`+ * (the author's own `nodeterm` project file measured 114,695 bytes, ~15 KB under the ceiling).+ * Over this verb the phone sends `{projectId, nodeId, columnId}` and the size of the canvas is+ * irrelevant.+ *+ * False = nothing was written, and the caller says so out loud rather than pretending: the+ * project is unknown or has no writable file, the file is not the shape we know, the column does+ * not exist on this board, or the card is already there (a retry — see `setProjectCardColumn`).+ */+ setRemoteCardColumn(+ projectId: string,+ nodeId: string,+ columnId: string | null,+ now = new Date()+ ): Promise<boolean> {+ const run = this.saveChain.then(() =>+ this.kanbanWriteNow(projectId, (raw) => setProjectCardColumn(raw, nodeId, columnId, now))+ )+ this.saveChain = run.catch(() => {})+ return run.then((res) => res?.written === true)+ }++ /**+ * The one read-modify-write behind both kanban verbs, 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 lands+ * last and un-writes the move the phone was told had landed.+ *+ * - **local ref** (`cwd`): read the file, transform, write it atomically — exactly+ * `appendRemoteNodeNow`'s shape, including recording the write in `lastWritten` and announcing+ * it on `workspaceExternalChange` rather than letting the watcher discover our own edit.+ * - **ssh ref** (`ssh` + `cache`): the file is on ANOTHER machine and only this desktop writes+ * it. So the write goes where the desktop's own board edits go — into `e.cache` — and is then+ * pushed by the ordinary mirror (`mirrorSshCache`, which re-reads and rescues the server's own+ * node additions first). This is why extending the phone's reach to SSH projects does not need+ * any new reconciliation: `reconcileSsh` decides between cache and server by `rev` and unions+ * only `nodes`, and this produces exactly the cache-side, rev-bumped change a desktop card drag+ * produces. What it must NOT skip is the broadcast: the renderer holds its own copy of the+ * board and the next whole-workspace save serializes THAT, so a change the renderer never heard+ * about is a change the next autosave reverts.+ *+ * Returns null when there was no readable project file to work on at all. Otherwise it returns+ * the file as it now stands together with whether this call CHANGED it — the two are different+ * answers and both callers need the difference: a refused move is `written: false` (the phone+ * says so out loud), while a board that was already there is `written: false` with the board+ * right there in `file` (nothing to do, and the honest answer is the board).+ */+ private async kanbanWriteNow(+ projectId: string,+ transform: (raw: string) => string | null+ ): Promise<{ file: ProjectFileV1; written: boolean } | null> {+ const e = this.index?.entries.find((x) => x.id === projectId)+ if (!e) return null++ if (e.ssh && e.cache) {+ const updated = transform(serializeProjectFile(e.cache))+ if (updated === null) return { file: e.cache, written: false }+ let parsed: ProjectFileV1+ try {+ parsed = JSON.parse(updated) as ProjectFileV1+ } catch {+ return { file: e.cache, written: false }+ }+ e.cache = parsed+ this.revs.set(e.id, parsed.rev)+ // Owed BEFORE the push, so a mirror that fails (the host is asleep, the dial flaps) is+ // retried by the next save instead of being lost with the answer already given.+ this.unmirrored.add(e.id)+ // The ssh cache IS the local copy of that file — it lives in workspace.json, not on this+ // machine's disk as a project.json — so an unpersisted cache change is one an app restart+ // loses even though the server already has it. (The local branch below needs no equivalent:+ // its project.json is the record.)+ await this.writeIndexNow().catch(() => {})+ this.announceProjectFile(e, parsed)+ await this.mirrorSshCache(e)+ return { file: parsed, written: true }+ }++ if (!e.cwd) return null+ const file = projectFilePath(e.cwd)+ let raw: string+ try {+ raw = await fs.readFile(file, 'utf-8')+ } catch {+ return null+ }+ const current = (): { file: ProjectFileV1; written: boolean } | null => {+ try {+ return { file: JSON.parse(raw) as ProjectFileV1, written: false }+ } catch {+ return null // unparsable: there is no board to report and none was written+ }+ }+ const updated = transform(raw)+ if (updated === null) return current()+ try {+ await writeAtomic(file, updated)+ } catch {+ return current()+ }+ this.lastWritten.set(file, updated)+ let parsed: ProjectFileV1+ try {+ parsed = JSON.parse(updated) as ProjectFileV1+ } catch {+ // The transforms only ever return a string they serialized themselves, so this cannot+ // realistically happen — but the write DID land, and reporting it as a failure would have+ // the phone tell the user their move was refused while the file says otherwise.+ return { file: { version: 1, rev: 0, savedAt: '', name: e.name, color: e.color, nodes: [] }, written: true }+ }+ this.revs.set(e.id, parsed.rev)+ this.announceProjectFile(e, parsed)+ return { file: parsed, written: true }+ }++ /** Tell the renderer about a project file THIS store just rewrote outside of `save()`. Shared by+ * the kanban verbs; the same payload `appendRemoteNode`/`removeRemoteNode` build by hand. */+ private announceProjectFile(e: IndexEntryV3, file: ProjectFileV1): void {+ try {+ platform().broadcast(+ IPC.workspaceExternalChange,+ fileToProject(file, {+ id: e.id,+ cwd: e.cwd,+ ssh: e.ssh,+ closed: e.closed,+ closedAt: e.closedAt,+ viewport: e.viewport,+ defaultAccountId: e.defaultAccountId,+ breadcrumbs: e.breadcrumbs,+ closedSessions: e.closedSessions,+ capabilityAck: e.capabilityAck,+ localExec: e.localExec+ })+ )+ } catch { /* the file is written and cached; the next load/poll surfaces the change */ }+ }+/*** The mirror write for one ssh entry, with the server's own additions rescued first.*diff --git a/src/main/index.ts b/src/main/index.tsindex 06c853272..d5dbcd330 100644--- a/src/main/index.ts+++ b/src/main/index.ts@@ -3598,6 +3598,23 @@ app.whenReady().then(async () => {codex: settingsStore.get().codexAccounts ?? []})),+ // The phone's Board sheet. Two verbs, both landing in the store's own read-modify-write (which+ // queues them behind save() and announces the result to the renderer, so the canvas adopts the+ // change live instead of the next autosave reverting it):+ //+ // - `ensureBoard` seeds the default To Do / In Progress / Done columns on a project that has+ // never had a `kanban` block. The desktop writes one only on the user's FIRST board edit+ // (the lazy default in `lib/kanban.defaultKanban`), which is invisible there — the canvas+ // renders the default either way — but left the phone, which knows a project only by its+ // file, with no board to show and so no Board button at all on nearly every project.+ // - `setCardColumn` moves one card. The phone could already do this over direct SSH, but only+ // for a project whose folder is on THIS machine and only while the whole file still fits in+ // one argv string.+ kanban: {+ ensureBoard: (projectId: string) => workspaceStore.ensureRemoteBoard(projectId),+ setCardColumn: (projectId: string, nodeId: string, columnId: string | null) =>+ workspaceStore.setRemoteCardColumn(projectId, nodeId, columnId)+ },// "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 either// — see the session-memory panel's kill rule), then take the node off its project's canvasdiff --git a/src/main/remote/host-kanban-verbs.test.ts b/src/main/remote/host-kanban-verbs.test.tsnew file mode 100644index 000000000..f4745f016--- /dev/null+++ b/src/main/remote/host-kanban-verbs.test.ts@@ -0,0 +1,165 @@+// The phone's Board verbs (`projects.ensureBoard` / `projects.setCardColumn`). What these pin:+// - Absent injection ⇒ an honest "not served" (a pre-feature host), never a silent success.+// - A missing projectId / nodeId is refused before anything is asked of the store.+// - `columnId: null` is a REAL value (the virtual Ungrouped column) and must be told apart from a+// missing or garbage key — reading either as "unassign" would move a card the user didn't ask+// to move.+// - A store REFUSAL comes back as an ok answer whose body says "no" (`columns: null` / `moved:+// false`), not a protocol error: the phone shows the user that nothing happened, which is the+// whole point of the change (the direct-SSH path used to no-op in silence).+// - The client sends nothing path-shaped; only a projectId, which the store resolves against its+// own index.+import { describe, expect, it, vi } from 'vitest'+import {+ createHostHandlers,+ type HostFsOps,+ type HostKanbanOps,+ type HostPtyManager,+ type HostRelaySocket+} from './host-service'++const COLUMNS = [+ { id: 'kcol-1', title: 'To Do', color: '#0a84ff' },+ { id: 'kcol-2', title: 'In Progress', color: '#ffd60a' },+ { id: 'kcol-3', title: 'Done', color: '#32d74b' }+]++function makeFakes(over: Partial<HostKanbanOps> = {}, served = true) {+ const responses: Array<{ id: string; ok: boolean; body: any }> = []+ const socket: HostRelaySocket = {+ respond: (id, ok, body) => responses.push({ id, ok, body }),+ sendFrame: () => true+ }+ const fs: HostFsOps = {+ listDir: async () => [],+ readText: async () => '',+ readBinary: async () => '',+ writeText: async () => true+ }+ const kanban: HostKanbanOps = {+ ensureBoard: vi.fn(async () => COLUMNS),+ setCardColumn: vi.fn(async () => true),+ ...over+ }+ const handlers = createHostHandlers(+ {} as HostPtyManager, socket, fs, () => [],+ undefined, undefined, undefined, undefined, undefined, undefined, undefined,+ served ? kanban : undefined+ )+ return { handlers, responses, kanban }+}++const flush = (): Promise<void> => new Promise((r) => setTimeout(r, 0))++describe('projects.ensureBoard', () => {+ it('seeds/returns the board and answers with its columns', async () => {+ const { handlers, responses, kanban } = makeFakes()+ handlers.onRpc({ id: '1', method: 'projects.ensureBoard', params: { projectId: 'p1' } })+ await flush()+ expect(kanban.ensureBoard).toHaveBeenCalledWith('p1')+ expect(responses[0]).toMatchObject({ ok: true })+ expect(responses[0].body.columns).toEqual(COLUMNS)+ })++ it('answers `columns: null` — an ANSWER, not an error — when the store refuses', async () => {+ const { handlers, responses } = makeFakes({ ensureBoard: async () => null })+ handlers.onRpc({ id: '1', method: 'projects.ensureBoard', params: { projectId: 'p1' } })+ await flush()+ expect(responses[0]).toEqual({ id: '1', ok: true, body: { columns: null } })+ })++ it('answers `columns: null` when the store throws', async () => {+ const { handlers, responses } = makeFakes({ ensureBoard: async () => { throw new Error('boom') } })+ handlers.onRpc({ id: '1', method: 'projects.ensureBoard', params: { projectId: 'p1' } })+ await flush()+ expect(responses[0]).toEqual({ id: '1', ok: true, body: { columns: null } })+ })++ it('refuses a missing projectId without asking the store', async () => {+ const { handlers, responses, kanban } = makeFakes()+ handlers.onRpc({ id: '1', method: 'projects.ensureBoard', params: {} })+ expect(responses[0].ok).toBe(false)+ expect(kanban.ensureBoard).not.toHaveBeenCalled()+ })++ it('is not served when the host has no kanban ops (a pre-feature desktop)', () => {+ const { handlers, responses } = makeFakes({}, false)+ handlers.onRpc({ id: '1', method: 'projects.ensureBoard', params: { projectId: 'p1' } })+ expect(responses[0].ok).toBe(false)+ expect(String(responses[0].body.message)).toContain('not served')+ })+})++describe('projects.setCardColumn', () => {+ it('moves a card to a column', async () => {+ const { handlers, responses, kanban } = makeFakes()+ handlers.onRpc({+ id: '1', method: 'projects.setCardColumn',+ params: { projectId: 'p1', nodeId: 'term-a-1', columnId: 'kcol-2' }+ })+ await flush()+ expect(kanban.setCardColumn).toHaveBeenCalledWith('p1', 'term-a-1', 'kcol-2')+ expect(responses[0]).toEqual({ id: '1', ok: true, body: { moved: true } })+ })++ it('passes columnId null straight through (the virtual Ungrouped column)', async () => {+ const { handlers, kanban } = makeFakes()+ handlers.onRpc({+ id: '1', method: 'projects.setCardColumn',+ params: { projectId: 'p1', nodeId: 'term-a-1', columnId: null }+ })+ await flush()+ expect(kanban.setCardColumn).toHaveBeenCalledWith('p1', 'term-a-1', null)+ })++ it('refuses a MISSING or non-string columnId rather than reading it as Ungrouped', async () => {+ for (const params of [+ { projectId: 'p1', nodeId: 'term-a-1' },+ { projectId: 'p1', nodeId: 'term-a-1', columnId: 7 },+ { projectId: 'p1', nodeId: 'term-a-1', columnId: {} }+ ]) {+ const { handlers, responses, kanban } = makeFakes()+ handlers.onRpc({ id: '1', method: 'projects.setCardColumn', params })+ expect(responses[0].ok).toBe(false)+ expect(kanban.setCardColumn).not.toHaveBeenCalled()+ }+ })++ it('refuses a missing projectId / nodeId without asking the store', () => {+ for (const params of [+ { nodeId: 'term-a-1', columnId: null },+ { projectId: 'p1', columnId: null },+ { projectId: 'p1', nodeId: '', columnId: null }+ ]) {+ const { handlers, responses, kanban } = makeFakes()+ handlers.onRpc({ id: '1', method: 'projects.setCardColumn', params })+ expect(responses[0].ok).toBe(false)+ expect(kanban.setCardColumn).not.toHaveBeenCalled()+ }+ })++ it('answers `moved: false` when the store refuses or throws — never a silent success', async () => {+ for (const ops of [+ { setCardColumn: async () => false },+ { setCardColumn: async () => { throw new Error('boom') } }+ ] as Partial<HostKanbanOps>[]) {+ const { handlers, responses } = makeFakes(ops)+ handlers.onRpc({+ id: '1', method: 'projects.setCardColumn',+ params: { projectId: 'p1', nodeId: 'term-a-1', columnId: 'kcol-2' }+ })+ await flush()+ expect(responses[0]).toEqual({ id: '1', ok: true, body: { moved: false } })+ }+ })++ it('is not served when the host has no kanban ops', () => {+ const { handlers, responses } = makeFakes({}, false)+ handlers.onRpc({+ id: '1', method: 'projects.setCardColumn',+ params: { projectId: 'p1', nodeId: 'term-a-1', columnId: null }+ })+ 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 0736aa781..591e38a13 100644--- a/src/main/remote/host-service.ts+++ b/src/main/remote/host-service.ts@@ -28,7 +28,7 @@ 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, PtyCreateOptions } from '../../shared/types'+import type { CanvasMutation, CanvasState, DirEntry, KanbanColumn, 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'@@ -147,6 +147,28 @@ export interface HostNodeActions {rename(nodeId: string, title: string): boolean}+/**+ * The kanban board writes the phone may ask this host to make on its behalf (`projects.ensureBoard`+ * / `projects.setCardColumn`). Both land in `WorkspaceStore`, which owns the read-modify-write and+ * the save-chain ordering; nothing here touches a file.+ *+ * Two things the phone cannot do for itself, and this is why the verbs exist rather than more SSH:+ * an SSH project's `.nodeterm/project.json` lives on a THIRD machine that the phone has no+ * credentials for (only this desktop mirrors it), and the phone's direct-SSH write inlines the+ * whole file into one argv string, so it silently stops working past Linux's `MAX_ARG_STRLEN`.+ * Over these verbs the request is a few hundred bytes whatever the canvas weighs.+ *+ * Absent ⇒ the verbs answer an honest "not served" (a pre-feature host, and every pre-feature test+ * fake), which the phone shows to the user instead of doing nothing.+ */+export interface HostKanbanOps {+ /** Seed the default board on a project that has none; returns the board's columns either way,+ * or null when this project can have no board written. IDEMPOTENT. */+ 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>+}+interface Stream {sessionId: string/** The node id (tmux persistKey) this stream attached to. The ONLY tmux target a client can@@ -228,7 +250,10 @@ export function createHostHandlers(remoteViewer?: { attached(nodeId: string): void; detached(nodeId: string): void },// Renderer-nudge node actions for the phone's session-list long-press menu (`node.wake` /// `node.refresh` / `node.rename`). Absent ⇒ the verbs answer an honest "not served".- nodeActions?: HostNodeActions+ nodeActions?: HostNodeActions,+ // Kanban board writes on the phone's behalf (`projects.ensureBoard` / `projects.setCardColumn`).+ // Absent ⇒ the verbs answer an honest "not served".+ kanban?: HostKanbanOps): HostHandlers {// streamId -> Stream. PTY callbacks close over their own `streamId` directly, so no// reverse (sessionId -> streamId) index is needed.@@ -515,6 +540,63 @@ export function createHostHandlers(.catch(() => socket.respond(req.id, true, { registered: false }))}+ /**+ * The two kanban board verbs, which exist because the phone's own SSH write cannot cover either+ * of the cases they serve (see `HostKanbanOps`).+ *+ * `projects.ensureBoard { projectId }` → `{ columns }`: seed the default board on a project that+ * has none, or hand back the board it already has. Idempotent, so the phone may call it on every+ * Board tap without ever being the thing that replaces a board someone built.+ *+ * `projects.setCardColumn { projectId, nodeId, columnId | null }` → `{ moved }`: move one card.+ *+ * 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+ * "that didn't happen" instead of leaving the optimistic card where it dropped it.+ *+ * No jail is needed and none is faked: the client sends a projectId and NOTHING path-shaped, and+ * the file path is always derived by the store from its own index — the same rule the board-log+ * handlers state. A projectId this host does not have is simply not found.+ */+ function handleKanban(req: RpcRequest): void {+ if (!kanban) {+ socket.respond(req.id, false, { message: `${req.method} is not served on this host.` })+ return+ }+ const p = asRecord(req.params)+ const projectId = str(p.projectId)+ if (!projectId) {+ socket.respond(req.id, false, { message: `${req.method} requires a projectId.` })+ return+ }+ if (req.method === 'projects.ensureBoard') {+ void kanban+ .ensureBoard(projectId)+ .then((columns) => socket.respond(req.id, true, { columns: columns ?? null }))+ .catch(() => socket.respond(req.id, true, { columns: null }))+ return+ }+ const nodeId = str(p.nodeId)+ if (!nodeId) {+ socket.respond(req.id, false, { message: 'projects.setCardColumn requires a nodeId.' })+ return+ }+ // `null` is a REAL value here (the virtual Ungrouped column), so it must be told apart from a+ // missing/garbage key — which is refused rather than silently read as "unassign".+ const raw = p.columnId+ if (raw !== null && typeof raw !== 'string') {+ socket.respond(req.id, false, {+ message: 'projects.setCardColumn requires columnId: a column id, or null for Ungrouped.'+ })+ return+ }+ void kanban+ .setCardColumn(projectId, nodeId, raw)+ .then((moved) => socket.respond(req.id, true, { moved }))+ .catch(() => socket.respond(req.id, true, { moved: false }))+ }+function handleKill(req: RpcRequest): void {const streamId = num(asRecord(req.params).streamId, -1)const stream = streams.get(streamId)@@ -678,6 +760,10 @@ export function createHostHandlers(case 'projects.registerNode':handleRegisterNode(req)break+ case 'projects.ensureBoard':+ case 'projects.setCardColumn':+ handleKanban(req)+ breakcase 'node.wake':case 'node.refresh':case 'node.rename':@@ -924,6 +1010,9 @@ export interface HostSessionOptions {/** Renderer-nudge node actions (`node.wake` / `node.refresh` / `node.rename`) for the phone's* session-list long-press menu. Optional: absent ⇒ the verbs answer an honest "not served". */nodeActions?: HostNodeActions+ /** Kanban board writes for the phone's Board sheet (`projects.ensureBoard` /+ * `projects.setCardColumn`). Optional: absent ⇒ the verbs answer an honest "not served". */+ kanban?: HostKanbanOps/** Extra fs/git jail roots beyond the shared canvas's node cwds — production passes the* workspace's local project cwds: the phone browses EVERY project over `projects.list`, so a* canvas-only jail denied whichever project the desktop didn't happen to have focused. */@@ -1047,7 +1136,8 @@ export function connectHostSession(opts: HostSessionOptions): HostSession {opts.registerNode,opts.destroyNode,opts.remoteViewer,- opts.nodeActions+ opts.nodeActions,+ opts.kanban)canvasSync = createHostCanvasSync(socket, opts.applyMutation)unsubCanvas = opts.subscribeCanvas(() => scheduleBroadcast())@@ -1076,6 +1166,8 @@ export interface HostBridgeDeps {/** Renderer-nudge node actions for the phone's session-list long-press menu (`node.wake` /* `node.refresh` / `node.rename`) — see main/index.ts's deliverers. */nodeActions?: HostNodeActions+ /** Kanban board writes for the phone's Board sheet — see main/index.ts's WorkspaceStore wiring. */+ kanban?: HostKanbanOps/** Workspace-level jail roots (local project cwds) merged with the canvas node cwds. */workspaceRoots?: () => string[]}@@ -1149,6 +1241,7 @@ export function initRemoteHost(destroyNode: bridge.destroyNode,remoteViewer: bridge.remoteViewer,nodeActions: bridge.nodeActions,+ kanban: bridge.kanban,extraRoots: bridge.workspaceRoots,// Typing attribution: this session's input frames are this phone's keystrokes.getClientId: () => phone.id(),diff --git a/src/main/remote/standing-host.ts b/src/main/remote/standing-host.tsindex b3329c242..af1e3376e 100644--- a/src/main/remote/standing-host.ts+++ b/src/main/remote/standing-host.ts@@ -338,6 +338,7 @@ export function initStandingHost(destroyNode: bridge.destroyNode,remoteViewer: bridge.remoteViewer,nodeActions: bridge.nodeActions,+ kanban: bridge.kanban,extraRoots: bridge.workspaceRoots,// Typing attribution: this pooled session's input frames are ITS phone's keystrokes.getClientId: () => pooled.presence.id(),diff --git a/src/renderer/lib/kanban.ts b/src/renderer/lib/kanban.tsindex 86da913d8..010ddce5e 100644--- a/src/renderer/lib/kanban.ts+++ b/src/renderer/lib/kanban.ts@@ -1,5 +1,6 @@import type { BoardLogAuthor, CanvasNodeState, KanbanAssignment, KanbanCardMeta, KanbanColumn, KanbanLabel, KanbanLabelColor, KanbanPriority, Project, ProjectKanban } from '@shared/types'import { NODE_COLORS } from '../state/workspace'+import { DEFAULT_BOARD_COLUMNS, makeColumnId } from '@shared/kanban-default-board'// 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).@@ -10,14 +11,12 @@ import { NODE_COLORS } from '../state/workspace'const kid = (prefix: string): string => `${prefix}-${Math.random().toString(36).slice(2, 10)}`/** Default board for a project whose file has no `kanban` yet. NOT written to disk- * until the first user edit (the spec's lazy-default rule). */+ * until the first user edit (the spec's lazy-default rule) — EXCEPT when the phone asks for one+ * outright (relay `projects.ensureBoard`), which seeds the same three columns from the same+ * shared definition so a board born on either surface is the same board. */export function defaultKanban(): ProjectKanban {return {- columns: [- { id: kid('kcol'), title: 'To Do', color: NODE_COLORS[0] },- { id: kid('kcol'), title: 'In Progress', color: NODE_COLORS[2] },- { id: kid('kcol'), title: 'Done', color: NODE_COLORS[1] }- ],+ columns: DEFAULT_BOARD_COLUMNS.map((c) => ({ id: makeColumnId(), title: c.title, color: c.color })),assignments: []}}diff --git a/src/shared/kanban-default-board.test.ts b/src/shared/kanban-default-board.test.tsnew file mode 100644index 000000000..a76a93762--- /dev/null+++ b/src/shared/kanban-default-board.test.ts@@ -0,0 +1,33 @@+// The starting board is a CROSS-SURFACE contract, and one of the surfaces cannot import this file:+// nodeterm-ios's `KanbanDefaults` copies these three titles, in this order, with these colors, so+// that a board created on the phone and a board created on the desktop are the same board. This+// test is the pin on the desktop half — change it and the iOS twin (KanbanDefaultsTests) must move+// in the same PR.+import { describe, expect, it } from 'vitest'+import { DEFAULT_BOARD_COLUMNS, makeColumnId } from './kanban-default-board'+import { NODE_COLORS } from './node-colors'++describe('DEFAULT_BOARD_COLUMNS', () => {+ it('is To Do / In Progress / Done, in that order', () => {+ expect(DEFAULT_BOARD_COLUMNS.map((c) => c.title)).toEqual(['To Do', 'In Progress', 'Done'])+ })++ it('paints them from the node palette: blue, yellow, green', () => {+ expect(DEFAULT_BOARD_COLUMNS.map((c) => c.color)).toEqual([+ NODE_COLORS[0],+ NODE_COLORS[2],+ NODE_COLORS[1]+ ])+ expect(DEFAULT_BOARD_COLUMNS.map((c) => c.color)).toEqual(['#0a84ff', '#ffd60a', '#32d74b'])+ })+})++describe('makeColumnId', () => {+ // The VALUE is random and deliberately so (a board is created once, by whichever surface got+ // there first). The SHAPE is what every project file on disk already carries.+ it('mints the desktop shape, distinctly each time', () => {+ const ids = Array.from({ length: 50 }, () => makeColumnId())+ for (const id of ids) expect(id).toMatch(/^kcol-[a-z0-9]{1,8}$/)+ expect(new Set(ids).size).toBeGreaterThan(45)+ })+})diff --git a/src/shared/kanban-default-board.ts b/src/shared/kanban-default-board.tsnew file mode 100644index 000000000..69622a2f0--- /dev/null+++ b/src/shared/kanban-default-board.ts@@ -0,0 +1,40 @@+/**+ * The starting board every project gets when it first grows one: To Do / In Progress / Done.+ *+ * It lives in `shared` because THREE writers must mint the same board and none of them may own the+ * definition: the renderer's `defaultKanban()` (the desktop's lazy default, seeded on the user's+ * first board edit), the core's `ensureProjectBoard` (the host side of the relay+ * `projects.ensureBoard` verb — the phone creating a board on a project that has never had one),+ * and, across the repo boundary, nodeterm-ios `KanbanDefaults` (which cannot import this file and+ * therefore copies it verbatim under a pinning test).+ *+ * Only the TITLES, their ORDER and their COLORS are shared. Column ids are minted per board and are+ * deliberately random: a board is created exactly once, by whichever surface got there first, and+ * every later reader addresses columns by the ids that board carries — so two surfaces agreeing on+ * an id would buy nothing and a fixed id would collide across projects.+ */+import { NODE_COLORS } from './node-colors'++export interface DefaultBoardColumn {+ title: string+ color: string+}++/** The three starting columns, in board order. */+export const DEFAULT_BOARD_COLUMNS: readonly DefaultBoardColumn[] = [+ { title: 'To Do', color: NODE_COLORS[0] },+ { title: 'In Progress', color: NODE_COLORS[2] },+ { title: 'Done', color: NODE_COLORS[1] }+] as const++/**+ * A column id in the desktop's shape: `kcol-<8 chars of base36>`.+ *+ * `Math.random().toString(36).slice(2, 10)` is what `lib/kanban.ts` has always minted, and the ids+ * it produces are what live in every project file on disk — so the SHAPE is a compatibility+ * surface even though the value is random. Kept here next to the titles so the two halves of+ * "what a fresh board looks like" cannot drift apart.+ */+export function makeColumnId(): string {+ return `kcol-${Math.random().toString(36).slice(2, 10)}`+}