Skip to content

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

feat(server): own and color headless groups

freshjuiceze6ffc6226469
diff --git a/src/core/canvas-control-core.ts b/src/core/canvas-control-core.ts
index 510595685..267c06d78 100644
--- a/src/core/canvas-control-core.ts
+++ b/src/core/canvas-control-core.ts
@@ -11,6 +11,7 @@ import { RETRYABLE } from './agents/agent-message-decide'
import { FANOUT_PER_TURN, PAIR_MIN_INTERVAL_MS } from './agents/agent-message-flow'
import { BROWSER_RETRYABLE, BROWSER_OUTCOME_LABEL } from './browser-outcomes'
import { BROWSER_KEYS, BROWSER_TIMEOUT_DEFAULT_MS, BROWSER_TIMEOUT_MAX_MS } from './browser-verb'
+import { NODE_COLORS } from '@shared/node-colors'
/**
* The messaging verbs' retry guidance, RENDERED from `RETRYABLE` — the table is the source, and
@@ -115,6 +116,7 @@ export type ControlVerb =
| 'close-worktree'
| 'branch'
| 'rename'
+ | 'color'
| 'write'
| 'close'
| 'board'
@@ -152,6 +154,7 @@ const VERBS: ControlVerb[] = [
'close-worktree',
'branch',
'rename',
+ 'color',
'write',
'close',
'board',
@@ -218,6 +221,8 @@ export function parseControlRequest(
if (v === 'branch' && !args.node) return { error: 'branch requires --node <id>' }
if (v === 'rename' && !args.node) return { error: 'rename requires --node <id>' }
if (v === 'rename' && !args.title) return { error: 'rename requires --title' }
+ if (v === 'color' && !args.node) return { error: 'color requires --node <id,id>' }
+ if (v === 'color' && args.color === undefined) return { error: 'color requires --color' }
if ((v === 'send' || v === 'reply') && !args.node) return { error: `${v} requires --node <id>` }
if ((v === 'send' || v === 'reply') && !args.text) return { error: `${v} requires --text` }
if (v === 'notify' && !args.node) return { error: 'notify requires --node <id>' }
@@ -311,7 +316,7 @@ export function buildCanvasControlInstructions(shimPath: string): string {
'- `show-image <path>` / `show-video <path>` — open a media file as a node.',
'- `show-web (--url U | --file P.html | --html "<...>")` — open a web viewer.',
'- `open-browser --url U` — open a navigable browser node.',
- '- `group --nodes <id,id> [--label L]` — wrap sibling nodes or sibling groups in a new labeled frame.',
+ '- `group --nodes <id,id> [--label L] [--color C]` — wrap sibling nodes or sibling groups in a new labeled frame.',
' Every id must share one container. `ungroup --group <id>` dissolves a frame and promotes its direct',
' children into the frame\'s parent. `move --nodes <id,id> [--group <id>]` reparents nodes or groups INTO an',
' existing frame (omit `--group`, or pass `top`/`none`, to pull them out to the top level) — this is',
@@ -336,6 +341,7 @@ export function buildCanvasControlInstructions(shimPath: string): string {
' the user to confirm deletion.',
'- `branch --node <id>` — branch a Claude node\'s conversation (Claude nodes only).',
'- `rename --node <id> --title "New Name"` — rename any node (terminals, groups, stickies…).',
+ `- \`color --node <id,id> --color C\` — recolor nodes, frames, or stickies. C is one of: ${NODE_COLORS.join(', ')}.`,
'- `write --node <id> --text "..."` / `close --node <id>` — type into / close a node.',
' Desktop asks the user to confirm both. Server Edition close is narrower: only nodes this',
' caller opened during the current server run can be closed, and those close without a dialog;',
@@ -448,7 +454,7 @@ nt_verb="list"
if [ $# -gt 0 ]; then nt_verb="$1"; shift; fi
# Translate \`--flag value\` pairs — plus the one bare positional the show-image/show-video and
-# write/close/rename/branch/send/reply/sticky forms accept — into curl --data-urlencode arguments. The positional
+# write/close/rename/color/branch/send/reply/sticky forms accept — into curl --data-urlencode arguments. The positional
# list doubles as the accumulator: originals are consumed from the front, translated pairs
# appended at the back, so "$@" holds exactly the curl args once the loop drains.
nt_seen_pos=0
@@ -492,7 +498,7 @@ while [ "$nt_i" -lt "$nt_count" ]; do
nt_seen_pos=1
case "$nt_verb" in
show-image|show-video) set -- "$@" --data-urlencode "arg.path=$nt_a" ;;
- write|close|rename|branch|send|reply|sticky) set -- "$@" --data-urlencode "arg.node=$nt_a" ;;
+ write|close|rename|color|branch|send|reply|sticky) set -- "$@" --data-urlencode "arg.node=$nt_a" ;;
esac
fi
;;
@@ -650,7 +656,7 @@ Verbs:
render on the DESKTOP: \`show-image\` and \`show-video\` still work with a host path (the
file is read/fetched back over the connection), but \`show-web --file/--html\` is refused —
use \`--url\`, or copy the file to the desktop first.
-- \`group --nodes <id,id> [--label "Frontend Team"]\` — wrap sibling nodes or sibling groups in a
+- \`group --nodes <id,id> [--label "Frontend Team"] [--color C]\` — wrap sibling nodes or sibling groups in a
new labeled frame. Every id must share one container; an ancestor cannot be grouped with its descendant.
- \`ungroup --group <id>\` — dissolve a group frame, promoting its direct children into the frame's
parent (the nodes stay put; only the frame is removed).
@@ -691,6 +697,7 @@ Verbs:
- \`branch --node <id>\` — branch a Claude node's conversation: the node stays on the new
branch and a new node opens resuming the original. Target must be a Claude agent node.
- \`rename --node <id> --title "New Name"\` — rename any node (terminals, groups, stickies…).
+- \`color --node <id,id> --color C\` — recolor nodes, frames, or stickies. C is one of: ${NODE_COLORS.join(', ')}.
- \`write --node <id> --text "..."\` — type text into a terminal node. (Asks the user to confirm.)
- \`close --node <id>\` — close a node. Desktop asks the user to confirm. Server Edition closes
only nodes this caller opened during the current server run, without a dialog; every other
@@ -759,6 +766,7 @@ Typical requests this skill covers:
- "Move this node into that group" → \`move --nodes <id> --group <targetGroupId>\` (not \`group\`, which only
wraps loose nodes). "Break up this group" → \`ungroup --group <id>\`.
- "Rename this node/group" → \`rename\`.
+- "Color these nodes/groups by subject" → \`color --node <id,id> --color <palette value>\`.
## Nodeterm orchestration ("Build with Nodeterm orchestration")
diff --git a/src/main/canvas-control-core.test.ts b/src/main/canvas-control-core.test.ts
index b2f3d1aea..13efc27ca 100644
--- a/src/main/canvas-control-core.test.ts
+++ b/src/main/canvas-control-core.test.ts
@@ -160,6 +160,20 @@ describe('parseControlRequest', () => {
expect(isDestructiveVerb('rename')).toBe(false)
})
+ it('color requires --node and --color, and is metadata-only', () => {
+ expect(parseControlRequest('color', {})).toEqual({
+ error: 'color requires --node <id,id>'
+ })
+ expect(parseControlRequest('color', { node: 'n1,n2' })).toEqual({
+ error: 'color requires --color'
+ })
+ expect(parseControlRequest('color', { node: 'n1,n2', color: '#32d74b' })).toEqual({
+ verb: 'color',
+ args: { node: 'n1,n2', color: '#32d74b' }
+ })
+ expect(isDestructiveVerb('color')).toBe(false)
+ })
+
it('ungroup requires --group; move requires --nodes; neither is destructive', () => {
expect(parseControlRequest('ungroup', {})).toEqual({ error: 'ungroup requires --group <id>' })
expect(parseControlRequest('ungroup', { group: 'g1' })).toEqual({ verb: 'ungroup', args: { group: 'g1' } })
@@ -207,9 +221,14 @@ describe('parseControlRequest', () => {
it('instructions cover the verb set and the confirm caveat', () => {
const body = buildCanvasControlInstructions('/tmp/nodeterm.sh')
- for (const verb of ['list', 'open-agent', 'spawn-team', 'group', 'ungroup', 'move', 'arrange', 'rename', 'write', 'close', 'board', 'assign']) {
+ for (const verb of ['list', 'open-agent', 'spawn-team', 'group', 'ungroup', 'move', 'arrange', 'rename', 'color', 'write', 'close', 'board', 'assign']) {
expect(body).toContain(verb)
}
+ expect(body).toContain('group --nodes <id,id> [--label L] [--color C]')
+ expect(body).toContain('color --node <id,id> --color C')
+ const skill = buildCanvasSkillBody('/tmp/nodeterm.sh')
+ expect(skill).toContain('group --nodes <id,id> [--label "Frontend Team"] [--color C]')
+ expect(skill).toContain('color --node <id,id> --color C')
expect(body.toLowerCase()).toContain('confirm')
})
@@ -262,10 +281,10 @@ describe('parseControlRequest', () => {
expect(parseControlRequest('reply', { node: 'n1' })).toEqual({ error: 'reply requires --text' })
})
- it('the shim maps a bare positional onto arg.node for send/reply/sticky too', () => {
+ it('the shim maps a bare positional onto arg.node for color/send/reply/sticky too', () => {
// The positional list is a case pattern inside CONTROL_SHIM_SCRIPT; send/reply/sticky take the
- // same "first bare word is the node" convenience write/close/rename/branch already have.
- expect(CONTROL_SHIM_SCRIPT).toContain('write|close|rename|branch|send|reply|sticky)')
+ // same "first bare word is the node" convenience write/close/rename/color/branch already have.
+ expect(CONTROL_SHIM_SCRIPT).toContain('write|close|rename|color|branch|send|reply|sticky)')
})
it('sticky requires --node plus exactly one of --text/--append, and is not destructive', () => {
diff --git a/src/main/canvas-control-shim.test.ts b/src/main/canvas-control-shim.test.ts
index ac3fe80c7..d0a50fa32 100644
--- a/src/main/canvas-control-shim.test.ts
+++ b/src/main/canvas-control-shim.test.ts
@@ -99,6 +99,8 @@ describe('canvas-control shim', () => {
expect(received.at(-1)?.args).toEqual({ path: '/tmp/a b.png' })
await callShim(['close', 'node-9'])
expect(received.at(-1)?.args).toEqual({ node: 'node-9' })
+ await callShim(['color', 'node-9,node-10', '--color', '#bf5af2'])
+ expect(received.at(-1)?.args).toEqual({ node: 'node-9,node-10', color: '#bf5af2' })
})
it('accepts a trailing flag with no value', async () => {
diff --git a/src/main/control-shim-parse.test.ts b/src/main/control-shim-parse.test.ts
index 028dafe86..63c211993 100644
--- a/src/main/control-shim-parse.test.ts
+++ b/src/main/control-shim-parse.test.ts
@@ -107,6 +107,10 @@ describe('the control shim translates flags', () => {
// subtle part of this script and a reordering would mean the drain went wrong.
it('the bare positional forms still work', () => {
expect(run(['write', 'n7', '--text', 'hi'])).toEqual(['arg.node=n7', 'arg.text=hi'])
+ expect(run(['color', 'n7,n8', '--color', '#32d74b'])).toEqual([
+ 'arg.node=n7,n8',
+ 'arg.color=#32d74b'
+ ])
})
// Task 5.4: the messaging verbs take the same "first bare word is the node" convenience —
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index 41e3b7548..6ba0fa641 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -387,6 +387,7 @@ import { useReopenHistory } from '../state/reopenHistory'
import { snapshotNode, recreateNodeFromSnapshot } from '../lib/reopenNode'
import { planReopen } from '../lib/reopenPlan'
import { oneLine } from '@shared/one-line'
+import { invalidNodeColorMessage, isNodeColor } from '@shared/node-colors'
import { parseLenses, verifyLensPrompt, verifySynthesisPrompt } from '../lib/verifyPanel'
import { useSettings } from '../state/settings'
import { activePermissionMode, projectPermissionMode } from '../state/permissionMode'
@@ -8758,6 +8759,10 @@ export function Canvas() {
return
}
case 'group': {
+ if (args.color !== undefined && !isNodeColor(args.color)) {
+ reply({ ok: false, error: invalidNodeColorMessage() })
+ return
+ }
const ids = (args.nodes ?? '').split(',').map((s) => s.trim()).filter(Boolean)
const live = nodesRef.current as CanvasNode[]
const resolvable = ids.filter((id) => live.some((node) => node.id === id))
@@ -8775,9 +8780,18 @@ export function Canvas() {
reply({ ok: false, error: 'group: nodes must be siblings in one container and may not include an ancestor with its descendant' })
return
}
- if (args.label) {
+ if (args.label || args.color) {
grouped = grouped.map((nd) =>
- nd.id === groupNode.id ? { ...nd, data: { ...nd.data, title: args.label } } : nd
+ nd.id === groupNode.id
+ ? {
+ ...nd,
+ data: {
+ ...nd.data,
+ ...(args.label ? { title: args.label } : {}),
+ ...(args.color ? { color: args.color } : {})
+ }
+ }
+ : nd
)
}
setNodes(grouped)
@@ -9301,6 +9315,38 @@ export function Canvas() {
reply({ ok: true, message: `renamed ${id} to "${title}"` })
return
}
+ case 'color': {
+ if (!isNodeColor(args.color)) {
+ reply({ ok: false, error: invalidNodeColorMessage() })
+ return
+ }
+ const ids = [
+ ...new Set((args.node ?? '').split(',').map((id) => id.trim()).filter(Boolean))
+ ]
+ const live = nodesRef.current
+ const colored = ids.filter((id) => live.some((node) => node.id === id))
+ if (!colored.length) {
+ reply({ ok: false, error: 'color: none of the given node ids exist' })
+ return
+ }
+ const selected = new Set(colored)
+ setNodes((nodes) =>
+ nodes.map((node) =>
+ selected.has(node.id)
+ ? { ...node, data: { ...node.data, color: args.color } }
+ : node
+ )
+ )
+ markDirty()
+ const skipped = ids.length - colored.length
+ const note = skipped ? ` (${skipped} unknown id(s) skipped)` : ''
+ reply({
+ ok: true,
+ message: `colored ${colored.length} node(s) ${args.color}${note}`,
+ result: { colored, skipped, color: args.color }
+ })
+ return
+ }
case 'sticky': {
// Write INTO a note (issue #144): the door for "sync Linear/Jira/GitHub onto the
// canvas" — a scheduled agent turn rewrites one titled note; nodeterm ships no
diff --git a/src/renderer/state/workspace.ts b/src/renderer/state/workspace.ts
index b999f795d..ed0b47bfd 100644
--- a/src/renderer/state/workspace.ts
+++ b/src/renderer/state/workspace.ts
@@ -25,17 +25,11 @@ import { useSettings } from './settings'
// reflector.
export { applyCanvasMutation } from '@shared/canvas-mutations'
import { sanitizeInboundNode } from '@shared/node-exec'
+import { NODE_COLORS } from '@shared/node-colors'
-/** Preset color palette — macOS system colors (dark mode). */
-export const NODE_COLORS = [
- '#0a84ff', // systemBlue
- '#32d74b', // systemGreen
- '#ffd60a', // systemYellow
- '#ff453a', // systemRed
- '#bf5af2', // systemPurple
- '#6ac4dc', // systemTeal
- '#ff9f0a' // systemOrange
-]
+// Preserve the renderer's long-standing import surface; validation and the palette now live in
+// shared so Server Edition and canvas-control accept exactly what these pickers display.
+export { NODE_COLORS } from '@shared/node-colors'
const TERMINAL_SIZE = { width: 640, height: 440 }
const STICKY_SIZE = { width: 240, height: 200 }
diff --git a/src/server/canvas-control.ts b/src/server/canvas-control.ts
index e9abe8098..7ed151dea 100644
--- a/src/server/canvas-control.ts
+++ b/src/server/canvas-control.ts
@@ -171,6 +171,7 @@ export async function initServerCanvasControl(
link: (sourceNodeId, args, verified) => factory.link(sourceNodeId, args, verified),
group: (sourceNodeId, args) => factory.group(sourceNodeId, args),
rename: (sourceNodeId, args) => factory.rename(sourceNodeId, args),
+ color: (sourceNodeId, args) => factory.color(sourceNodeId, args),
sticky: (sourceNodeId, args) => factory.sticky(sourceNodeId, args),
deliver: async (input) => (await deliverFromControl(input, messaging)).reply
}
diff --git a/src/server/control-unsupported.test.ts b/src/server/control-unsupported.test.ts
index a0de1318a..4882b7217 100644
--- a/src/server/control-unsupported.test.ts
+++ b/src/server/control-unsupported.test.ts
@@ -179,6 +179,7 @@ describe('the enabled Server Edition handler parses and dispatches the v1 surfac
link: vi.fn(async () => ({ ok: true as const, result: { linked: ['term-target'] } })),
group: vi.fn(async () => ({ ok: true as const, result: { groupId: 'group-new' } })),
rename: vi.fn(async () => ({ ok: true as const, result: { id: 'renamed' } })),
+ color: vi.fn(async () => ({ ok: true as const, result: { colored: ['term-target'] } })),
sticky: vi.fn(async () => ({ ok: true as const, result: { id: 'sticky-new' } })),
deliver: vi.fn(async () => ({ ok: true as const, message: 'queued' }))
})
@@ -261,7 +262,7 @@ describe('the enabled Server Edition handler parses and dispatches the v1 surfac
})
})
- it('dispatches headless link, group, and rename while preserving link identity', async () => {
+ it('dispatches headless link, group, rename, and color while preserving link identity', async () => {
const a = actions()
const handler = createServerEditionControlHandler(a)
await handler({
@@ -273,7 +274,13 @@ describe('the enabled Server Edition handler parses and dispatches the v1 surfac
await handler({
verb: 'group',
nodeId: 'term-source',
- args: { nodes: 'term-a,term-b', label: 'Pair' },
+ args: { nodes: 'term-a,term-b', label: 'Pair', color: '#bf5af2' },
+ verified: true
+ })
+ await handler({
+ verb: 'color',
+ nodeId: 'term-source',
+ args: { node: 'term-a,term-b', color: '#32d74b' },
verified: true
})
await handler({
@@ -289,9 +296,14 @@ describe('the enabled Server Edition handler parses and dispatches the v1 surfac
)
expect(a.group).toHaveBeenCalledWith('term-source', {
nodes: 'term-a,term-b',
- label: 'Pair'
+ label: 'Pair',
+ color: '#bf5af2'
})
expect(a.rename).toHaveBeenCalledWith('term-source', { node: 'term-a', title: 'A' })
+ expect(a.color).toHaveBeenCalledWith('term-source', {
+ node: 'term-a,term-b',
+ color: '#32d74b'
+ })
})
it('keeps every deferred or unknown verb a clean permanent edition refusal', async () => {
diff --git a/src/server/control-unsupported.ts b/src/server/control-unsupported.ts
index 2b8d13d54..e914371d1 100644
--- a/src/server/control-unsupported.ts
+++ b/src/server/control-unsupported.ts
@@ -86,6 +86,7 @@ export interface ServerEditionControlActions {
): Promise<ServerControlReply>
group(sourceNodeId: string, args: Record<string, string>): Promise<ServerControlReply>
rename(sourceNodeId: string, args: Record<string, string>): Promise<ServerControlReply>
+ color(sourceNodeId: string, args: Record<string, string>): Promise<ServerControlReply>
sticky(sourceNodeId: string, args: Record<string, string>): Promise<ServerControlReply>
deliver(input: {
verb: 'send' | 'reply' | 'notify'
@@ -102,6 +103,7 @@ const SERVER_V1_VERBS: ReadonlySet<string> = new Set([
'link',
'group',
'rename',
+ 'color',
'send',
'reply',
'notify',
@@ -153,6 +155,8 @@ export function createServerEditionControlHandler(actions: ServerEditionControlA
return actions.group(nodeId, command.args)
case 'rename':
return actions.rename(nodeId, command.args)
+ case 'color':
+ return actions.color(nodeId, command.args)
case 'sticky':
return actions.sticky(nodeId, command.args)
case 'send':
diff --git a/src/server/headless-node-factory.test.ts b/src/server/headless-node-factory.test.ts
index 4232fbd59..68591612b 100644
--- a/src/server/headless-node-factory.test.ts
+++ b/src/server/headless-node-factory.test.ts
@@ -375,6 +375,200 @@ describe('HeadlessNodeFactory', () => {
})
})
+ it('lets the creator close a nested frame only, promoting surviving members to its parent', async () => {
+ const outerReply = await factory.group('term-source', {
+ nodes: 'term-source,term-upstream',
+ label: 'Outer'
+ })
+ const outerId = (outerReply.result as { groupId: string }).groupId
+ const innerReply = await factory.group('term-source', {
+ nodes: 'term-source,term-upstream',
+ label: 'Inner'
+ })
+ const innerId = (innerReply.result as { groupId: string }).groupId
+ const before = (await store.load({ sideline: false })).projects[0]
+ const root = (project: (typeof before), id: string): { x: number; y: number } => {
+ const node = project.nodes.find((candidate) => candidate.id === id)!
+ let x = node.position.x
+ let y = node.position.y
+ let parentId = node.parentId
+ const seen = new Set<string>()
+ while (parentId && !seen.has(parentId)) {
+ seen.add(parentId)
+ const parent = project.nodes.find((candidate) => candidate.id === parentId)
+ if (!parent) break
+ x += parent.position.x
+ y += parent.position.y
+ parentId = parent.parentId
+ }
+ return { x, y }
+ }
+ const rootsBefore = new Map(
+ ['term-source', 'term-upstream'].map((id) => [id, root(before, id)])
+ )
+ published.length = 0
+ publishedProjects.length = 0
+ removed.length = 0
+
+ await expect(factory.close('term-source', { node: innerId }, true)).resolves.toMatchObject({
+ ok: true,
+ result: { ids: [innerId] }
+ })
+
+ const after = (await new WorkspaceStore().load({ sideline: false })).projects[0]
+ expect(after.nodes.some((node) => node.id === innerId)).toBe(false)
+ expect(after.nodes.some((node) => node.id === outerId)).toBe(true)
+ for (const id of ['term-source', 'term-upstream']) {
+ expect(after.nodes.find((node) => node.id === id)?.parentId).toBe(outerId)
+ expect(root(after, id)).toEqual(rootsBefore.get(id))
+ }
+ expect(pty.destroys).toEqual([])
+ expect(removed).toEqual([innerId])
+ expect(published.map((node) => node.id)).toEqual(
+ expect.arrayContaining(['term-source', 'term-upstream'])
+ )
+ expect(publishedProjects.at(-1)?.nodes.some((node) => node.id === innerId)).toBe(false)
+ })
+
+ it('refuses a non-creator that tries to close a headless-created frame', async () => {
+ const grouped = await factory.group('term-source', {
+ nodes: 'term-source,term-upstream'
+ })
+ const groupId = (grouped.result as { groupId: string }).groupId
+ publishedProjects.length = 0
+
+ await expect(factory.close('term-upstream', { node: groupId }, true)).resolves.toMatchObject({
+ ok: false,
+ error: expect.stringContaining('close-not-owner')
+ })
+ expect((await store.load({ sideline: false })).projects[0].nodes.some(
+ (node) => node.id === groupId
+ )).toBe(true)
+ expect(pty.destroys).toEqual([])
+ expect(removed).toEqual([])
+ expect(publishedProjects).toEqual([])
+ })
+
+ it('closes an owned empty frame after its members were separately closed', async () => {
+ const first = await factory.openTerminal('term-source', {}, true)
+ const second = await factory.openTerminal('term-source', {}, true)
+ const memberIds = [
+ (first.result as { id: string }).id,
+ (second.result as { id: string }).id
+ ]
+ const grouped = await factory.group('term-source', { nodes: memberIds.join(',') })
+ const groupId = (grouped.result as { groupId: string }).groupId
+
+ for (const id of memberIds) {
+ await expect(factory.close('term-source', { node: id }, true)).resolves.toMatchObject({
+ ok: true
+ })
+ }
+ expect((await store.load({ sideline: false })).projects[0].nodes.find(
+ (node) => node.id === groupId
+ )).toMatchObject({ kind: 'group' })
+
+ await expect(factory.close('term-source', { node: groupId }, true)).resolves.toMatchObject({
+ ok: true,
+ result: { ids: [groupId] }
+ })
+ const after = await store.load({ sideline: false })
+ expect(after.projects[0].nodes.some((node) => node.id === groupId)).toBe(false)
+ expect(pty.destroys.map((entry) => entry.nodeId)).toEqual(memberIds)
+ expect(removed).toEqual([...memberIds, groupId])
+ })
+
+ it('applies a validated palette color when creating a group', async () => {
+ const reply = await factory.group('term-source', {
+ nodes: 'term-source,term-upstream',
+ label: 'Purple team',
+ color: '#bf5af2'
+ })
+ const groupId = (reply.result as { groupId: string }).groupId
+ const project = (await new WorkspaceStore().load({ sideline: false })).projects[0]
+ expect(project.nodes.find((node) => node.id === groupId)).toMatchObject({
+ title: 'Purple team',
+ color: '#bf5af2'
+ })
+ expect(publishedProjects.at(-1)?.nodes.find((node) => node.id === groupId)?.color).toBe(
+ '#bf5af2'
+ )
+ expect(pty.sends).toEqual([])
+ })
+
+ it('recolors a node, frame, and sticky with persistence and fanout but no PTY write', async () => {
+ const grouped = await factory.group('term-source', {
+ nodes: 'term-source,term-upstream',
+ label: 'Color targets'
+ })
+ const groupId = (grouped.result as { groupId: string }).groupId
+ const workspace = await store.load({ sideline: false })
+ workspace.projects[0].nodes.push({
+ id: 'sticky-color',
+ kind: 'sticky',
+ position: { x: 1200, y: 30 },
+ size: { width: 240, height: 200 },
+ title: 'Color note',
+ color: '#ffd60a',
+ group: null,
+ text: 'ready'
+ })
+ await store.save(workspace)
+ published.length = 0
+ publishedProjects.length = 0
+
+ await expect(factory.color('term-source', {
+ node: `term-upstream,${groupId},sticky-color`,
+ color: '#32d74b'
+ })).resolves.toMatchObject({
+ ok: true,
+ result: {
+ colored: ['term-upstream', groupId, 'sticky-color'],
+ skipped: 0,
+ color: '#32d74b'
+ }
+ })
+ const project = (await new WorkspaceStore().load({ sideline: false })).projects[0]
+ for (const id of ['term-upstream', groupId, 'sticky-color']) {
+ expect(project.nodes.find((node) => node.id === id)?.color, id).toBe('#32d74b')
+ }
+ expect(published.map((node) => node.id)).toEqual([
+ 'term-upstream',
+ groupId,
+ 'sticky-color'
+ ])
+ expect(publishedProjects).toHaveLength(1)
+ expect(pty.sends).toEqual([])
+ expect(pty.destroys).toEqual([])
+ const projectFile = JSON.parse(
+ fs.readFileSync(path.join(projectDir, '.nodeterm', 'project.json'), 'utf8')
+ ) as { nodes: CanvasNodeState[] }
+ expect(projectFile.nodes.find((node) => node.id === 'sticky-color')?.color).toBe('#32d74b')
+ })
+
+ it('refuses invalid group and recolor values by name without persistence or fanout', async () => {
+ await expect(factory.group('term-source', {
+ nodes: 'term-source,term-upstream',
+ color: 'var(--danger)'
+ })).resolves.toMatchObject({
+ ok: false,
+ error: expect.stringContaining('node-color-invalid')
+ })
+ await expect(factory.color('term-source', {
+ node: 'term-source',
+ color: '#ffffff'
+ })).resolves.toMatchObject({
+ ok: false,
+ error: expect.stringContaining('node-color-invalid')
+ })
+ const project = (await store.load({ sideline: false })).projects[0]
+ expect(project.nodes.filter((node) => node.kind === 'group')).toEqual([])
+ expect(project.nodes.find((node) => node.id === 'term-source')?.color).toBe('#d97757')
+ expect(published).toEqual([])
+ expect(publishedProjects).toEqual([])
+ expect(pty.sends).toEqual([])
+ })
+
it('refuses grouping across containers or across an ancestor boundary', async () => {
const workspace = await store.load({ sideline: false })
const frame: CanvasNodeState = {
diff --git a/src/server/headless-node-factory.ts b/src/server/headless-node-factory.ts
index dc4175f29..37a57ed7e 100644
--- a/src/server/headless-node-factory.ts
+++ b/src/server/headless-node-factory.ts
@@ -3,6 +3,12 @@ import { randomBytes, randomUUID } from 'node:crypto'
import { publishCanvasMutation } from '../core/canvas-sync'
import { gateProjectTarget } from '../core/project-grants'
import { planBridges, type LinkEndpoint } from '../shared/canvas-link'
+import {
+ invalidNodeColorMessage,
+ isNodeColor,
+ NODE_COLORS,
+ type NodeColor
+} from '../shared/node-colors'
import { applyStickyWrite, parseStickyArgs, resolveStickyRef } from '../shared/sticky-write'
import type { WorkspaceStore } from '../core/workspace-store'
import {
@@ -72,7 +78,6 @@ const TERMINAL_LIMIT = 8
const AGENT_LIMIT = 5
const TERMINAL_COLS = 120
const TERMINAL_ROWS = 36
-const NODE_COLORS = ['#0a84ff', '#32d74b', '#ffd60a', '#ff453a', '#bf5af2', '#6ac4dc', '#ff9f0a']
const TERMINAL_SIZE = { width: 640, height: 440 }
const STICKY_SIZE = { width: 240, height: 200 }
const H_GAP = 80
@@ -310,7 +315,8 @@ function groupPersistedNodes(
nodes: CanvasNodeState[],
ids: string[],
groupIndex: number,
- label: string | undefined
+ label: string | undefined,
+ color: NodeColor | undefined
): { nodes: CanvasNodeState[]; groupId: string; changed: CanvasNodeState[] } | null {
const selected = new Set(ids)
const members = nodes.filter((node) => selected.has(node.id))
@@ -343,7 +349,7 @@ function groupPersistedNodes(
height: maxY - minY + GROUP_PAD * 2 + GROUP_HEADER
},
title: label || `Group ${groupIndex + 1}`,
- color: NODE_COLORS[groupIndex % NODE_COLORS.length],
+ color: color ?? NODE_COLORS[groupIndex % NODE_COLORS.length],
group: null,
...(parentId ? { parentId } : {})
}
@@ -365,6 +371,55 @@ function groupPersistedNodes(
}
}
+function rootPosition(
+ nodes: readonly CanvasNodeState[],
+ node: CanvasNodeState
+): { x: number; y: number } {
+ const byId = new Map(nodes.map((candidate) => [candidate.id, candidate]))
+ const seen = new Set<string>([node.id])
+ let x = node.position.x
+ let y = node.position.y
+ let parentId = node.parentId
+ while (parentId && !seen.has(parentId)) {
+ seen.add(parentId)
+ const parent = byId.get(parentId)
+ if (!parent) break
+ x += parent.position.x
+ y += parent.position.y
+ parentId = parent.parentId
+ }
+ return { x, y }
+}
+
+/** Desktop `ungroupNodes` semantics over persisted nodes: direct children move up one level. */
+function ungroupPersistedNodes(
+ nodes: CanvasNodeState[],
+ groupId: string
+): { nodes: CanvasNodeState[]; promoted: CanvasNodeState[] } {
+ const frame = nodes.find((node) => node.id === groupId)
+ if (!frame || frame.kind !== 'group') return { nodes, promoted: [] }
+ const parentId = frame.parentId
+ const parent = parentId ? nodes.find((node) => node.id === parentId && node.kind === 'group') : undefined
+ const parentRoot = parent ? rootPosition(nodes, parent) : { x: 0, y: 0 }
+ const promoted: CanvasNodeState[] = []
+ const moved = nodes.map((node) => {
+ if (node.parentId !== groupId) return node
+ const root = rootPosition(nodes, node)
+ const next: CanvasNodeState = {
+ ...node,
+ position: { x: root.x - parentRoot.x, y: root.y - parentRoot.y }
+ }
+ if (parent) next.parentId = parent.id
+ else delete next.parentId
+ promoted.push(next)
+ return next
+ })
+ return {
+ nodes: groupsFirst(moved.filter((node) => node.id !== groupId)),
+ promoted
+ }
+}
+
function ptyOptions(project: Project, node: CanvasNodeState): PtyCreateOptions {
return {
cwd: node.cwd || project.cwd,
@@ -410,20 +465,24 @@ export class HeadlessNodeFactory {
return run
}
- private publish(project: Project, nodes: readonly CanvasNodeState[]): void {
+ private publishChangeSet(
+ project: Project,
+ nodes: readonly CanvasNodeState[],
+ removedIds: readonly string[]
+ ): void {
this.deps.publishProject?.(project)
- const publish = this.deps.publishNode ?? ((projectId: string, node: CanvasNodeState) => {
+ const publishNode = this.deps.publishNode ?? ((projectId: string, node: CanvasNodeState) => {
publishCanvasMutation(projectId, { op: 'upsert', node })
})
- for (const node of nodes) publish(project.id, node)
- }
-
- private publishRemovals(project: Project, nodeIds: readonly string[]): void {
- this.deps.publishProject?.(project)
- const publish = this.deps.publishRemoval ?? ((projectId: string, nodeId: string) => {
+ const publishRemoval = this.deps.publishRemoval ?? ((projectId: string, nodeId: string) => {
publishCanvasMutation(projectId, { op: 'remove', id: nodeId })
})
- for (const nodeId of nodeIds) publish(project.id, nodeId)
+ for (const node of nodes) publishNode(project.id, node)
+ for (const nodeId of removedIds) publishRemoval(project.id, nodeId)
+ }
+
+ private publish(project: Project, nodes: readonly CanvasNodeState[]): void {
+ this.publishChangeSet(project, nodes, [])
}
private async attach(project: Project, node: CanvasNodeState): Promise<PtyCreateResult> {
@@ -528,6 +587,7 @@ export class HeadlessNodeFactory {
// Validate the WHOLE list before killing anything. A mixed owned/unowned request is one
// refusal, never a partial destructive success whose surviving ids the caller must guess.
+ const frameIds = new Set<string>()
for (const id of ids) {
const ownership = this.spawnedBy.get(id)
if (!ownership || ownership.sourceNodeId !== sourceNodeId) {
@@ -536,21 +596,35 @@ export class HeadlessNodeFactory {
error: `close-not-owner: ${sourceNodeId} did not spawn ${id} during this server run`
}
}
+ const project = workspace.projects.find((candidate) => candidate.id === ownership.projectId)
+ if (project?.nodes.find((node) => node.id === id)?.kind === 'group') frameIds.add(id)
}
- // Kill first: the durable canvas must never lose a node whose session outcome is unknown.
- // `destroySession` treats a backend already absent as success, which is exactly the cleanup
- // case for a pane the operator killed directly before asking its owner to close the node.
+ // Kill terminal panes first: the durable canvas must never lose a session whose outcome is
+ // unknown. Frames have no PTY; closing one is the desktop `ungroup` transform followed by
+ // removal of the frame alone, regardless of who owns its members.
await Promise.all(
- ids.map((id) => this.deps.ptyManager.destroySession(null, id, { everySocket: true }))
+ ids
+ .filter((id) => !frameIds.has(id))
+ .map((id) => this.deps.ptyManager.destroySession(null, id, { everySocket: true }))
)
const removedByProject = new Map<Project, string[]>()
+ const changedByProject = new Map<Project, Map<string, CanvasNodeState>>()
for (const id of ids) {
const projectId = this.spawnedBy.get(id)!.projectId
const project = workspace.projects.find((candidate) => candidate.id === projectId)
- if (!project || !project.nodes.some((node) => node.id === id)) continue
- project.nodes = project.nodes.filter((node) => node.id !== id)
+ const target = project?.nodes.find((node) => node.id === id)
+ if (!project || !target) continue
+ if (target.kind === 'group') {
+ const ungrouped = ungroupPersistedNodes(project.nodes, id)
+ project.nodes = ungrouped.nodes
+ const changed = changedByProject.get(project) ?? new Map<string, CanvasNodeState>()
+ for (const node of ungrouped.promoted) changed.set(node.id, node)
+ changedByProject.set(project, changed)
+ } else {
+ project.nodes = project.nodes.filter((node) => node.id !== id)
+ }
if (project.ropes) {
project.ropes = project.ropes.filter((edge) => edge.source !== id && edge.target !== id)
}
@@ -564,7 +638,13 @@ export class HeadlessNodeFactory {
if (removedByProject.size) {
await this.deps.workspaceStore.save(workspace)
- for (const [project, removed] of removedByProject) this.publishRemovals(project, removed)
+ for (const [project, removed] of removedByProject) {
+ const surviving = project.nodes.map((node) => node.id)
+ const changed = [...(changedByProject.get(project)?.values() ?? [])].filter((node) =>
+ surviving.includes(node.id)
+ )
+ this.publishChangeSet(project, changed, removed)
+ }
}
for (const id of ids) {
@@ -663,8 +743,13 @@ export class HeadlessNodeFactory {
group(sourceNodeId: string, args: Record<string, string>): Promise<ServerControlReply> {
return this.runExclusive(async () => {
- const flagError = unsupportedFlags(args, new Set(['nodes', 'label']))
+ const flagError = unsupportedFlags(args, new Set(['nodes', 'label', 'color']))
if (flagError) return { ok: false, error: `group: ${flagError}` }
+ let color: NodeColor | undefined
+ if (args.color !== undefined) {
+ if (!isNodeColor(args.color)) return { ok: false, error: invalidNodeColorMessage() }
+ color = args.color
+ }
const workspace = await this.deps.workspaceStore.load({ sideline: false })
const source = sourceProject(workspace, sourceNodeId)
if (!source) return { ok: false, error: 'source node is not in exactly one saved project' }
@@ -681,7 +766,8 @@ export class HeadlessNodeFactory {
source.project.nodes,
resolvable,
source.project.nodes.filter((node) => node.kind === 'group').length,
- args.label ? oneLine(args.label) : undefined
+ args.label ? oneLine(args.label) : undefined,
+ color
)
if (!grouped) {
return {
@@ -693,6 +779,10 @@ export class HeadlessNodeFactory {
source.project.nodes = grouped.nodes
await this.deps.workspaceStore.save(workspace)
+ this.spawnedBy.set(grouped.groupId, {
+ sourceNodeId,
+ projectId: source.project.id
+ })
this.publish(source.project, grouped.changed)
const skipped = ids.length - resolvable.length
const note = skipped ? ` (${skipped} unknown id(s) skipped)` : ''
@@ -738,6 +828,41 @@ export class HeadlessNodeFactory {
})
}
+ color(sourceNodeId: string, args: Record<string, string>): Promise<ServerControlReply> {
+ return this.runExclusive(async () => {
+ const flagError = unsupportedFlags(args, new Set(['node', 'color']))
+ if (flagError) return { ok: false, error: `color: ${flagError}` }
+ if (!isNodeColor(args.color)) return { ok: false, error: invalidNodeColorMessage() }
+
+ const workspace = await this.deps.workspaceStore.load({ sideline: false })
+ const source = sourceProject(workspace, sourceNodeId)
+ if (!source) return { ok: false, error: 'source node is not in exactly one saved project' }
+ if (!sourceCanControl(source.node, this.deps.agentIdOf)) {
+ return { ok: false, error: 'source node is not a control-capable agent' }
+ }
+
+ const ids = [...new Set((args.node ?? '').split(',').map((id) => id.trim()).filter(Boolean))]
+ const changed = ids
+ .map((id) => source.project.nodes.find((node) => node.id === id))
+ .filter((node): node is CanvasNodeState => !!node)
+ .map((node) => ({ ...node, color: args.color }))
+ if (!changed.length) {
+ return { ok: false, error: 'color: none of the given node ids exist in the caller project' }
+ }
+ const byId = new Map(changed.map((node) => [node.id, node]))
+ source.project.nodes = source.project.nodes.map((node) => byId.get(node.id) ?? node)
+ await this.deps.workspaceStore.save(workspace)
+ this.publish(source.project, changed)
+ const skipped = ids.length - changed.length
+ const note = skipped ? ` (${skipped} unknown id(s) skipped)` : ''
+ return {
+ ok: true,
+ message: `colored ${changed.length} node(s) ${args.color}${note}`,
+ result: { colored: changed.map((node) => node.id), skipped, color: args.color }
+ }
+ })
+ }
+
private open(
sourceNodeId: string,
verb: 'open-terminal' | 'open-agent',
@@ -799,7 +924,7 @@ export class HeadlessNodeFactory {
for (let i = 0; i < count; i++) {
let command = args.cmd
let title = `Terminal ${startIndex + i + 1}`
- let color = NODE_COLORS[(startIndex + i) % NODE_COLORS.length]
+ let color: string = NODE_COLORS[(startIndex + i) % NODE_COLORS.length]
let mintedSessionId: string | undefined
let permissionMode
if (verb === 'open-agent') {
diff --git a/src/shared/node-colors.test.ts b/src/shared/node-colors.test.ts
new file mode 100644
index 000000000..3f1e95af4
--- /dev/null
+++ b/src/shared/node-colors.test.ts
@@ -0,0 +1,24 @@
+import { describe, expect, it } from 'vitest'
+
+import {
+ invalidNodeColorMessage,
+ isNodeColor,
+ NODE_COLORS,
+ NODE_COLOR_INVALID_ERROR
+} from './node-colors'
+
+describe('node color palette', () => {
+ it('accepts exactly the renderer palette', () => {
+ for (const color of NODE_COLORS) expect(isNodeColor(color), color).toBe(true)
+ for (const color of ['#ffffff', '#0A84FF', 'red', 'var(--accent)', '', undefined]) {
+ expect(isNodeColor(color), String(color)).toBe(false)
+ }
+ })
+
+ it('returns a stable named refusal without echoing hostile input', () => {
+ const message = invalidNodeColorMessage()
+ expect(message).toContain(NODE_COLOR_INVALID_ERROR)
+ expect(message).toContain(NODE_COLORS.join(', '))
+ expect(message).not.toContain('\n')
+ })
+})
diff --git a/src/shared/node-colors.ts b/src/shared/node-colors.ts
new file mode 100644
index 000000000..da25fc61c
--- /dev/null
+++ b/src/shared/node-colors.ts
@@ -0,0 +1,28 @@
+/**
+ * The node/frame/sticky palette shown by every renderer color picker.
+ *
+ * This is also the control boundary: agent-supplied colors must be one of these exact values,
+ * never an arbitrary CSS token that would be persisted and interpolated into node styles.
+ */
+export const NODE_COLORS = [
+ '#0a84ff', // systemBlue
+ '#32d74b', // systemGreen
+ '#ffd60a', // systemYellow
+ '#ff453a', // systemRed
+ '#bf5af2', // systemPurple
+ '#6ac4dc', // systemTeal
+ '#ff9f0a' // systemOrange
+] as const
+
+export type NodeColor = (typeof NODE_COLORS)[number]
+
+export const NODE_COLOR_INVALID_ERROR = 'node-color-invalid'
+
+export function isNodeColor(value: unknown): value is NodeColor {
+ return typeof value === 'string' && (NODE_COLORS as readonly string[]).includes(value)
+}
+
+/** Stable named refusal shared by desktop and Server Edition control dispatch. */
+export function invalidNodeColorMessage(): string {
+ return `${NODE_COLOR_INVALID_ERROR}: --color must be one of ${NODE_COLORS.join(', ')}`
+}