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(canvas): nested group trees and a recursive sessions sidebar

enesf4e03bf4a7b7
diff --git a/CLAUDE.md b/CLAUDE.md
index 6b898c73a..55aedcb9c 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -172,9 +172,17 @@ project's nodes only.** The contract:
sidebar (the sidebar no longer hoists the active project to the top). Both surfaces reorder
via drag-drop through `reorderProject(draggedId, beforeId|null)` (null = to the end; tab
strip empty area and sidebar body are the end-drop zones), persisted like any node reorder.
- Sidebar collapse behavior is `settings.sidebarAutoCollapse` (default on = historical: a
- project switch resets manual toggles and collapses inactive projects; off = everything
- defaults to expanded and switches never touch the user's choices — `isGroupCollapsed`).
+ Sidebar disclosure is **persisted**, for group frames as well as projects:
+ `settings.sidebarCollapsedItems` maps `project:<id>` / `project:<id>:group:<groupId>` → collapsed
+ (`isGroupCollapsed`), and `settings.sidebarAutoCollapse` (default on) now only supplies the
+ DEFAULT for a project row nobody has toggled (on = active expanded / others collapsed, off =
+ everything expanded). **This deliberately replaced the old "a project switch resets every manual
+ toggle" effect** (2026-08, with the nested sidebar tree): a tree the user shaped by hand should
+ still be that shape after a restart, and one transient rule for projects plus a sticky one for
+ frames would have been two contracts in one list. `projectHeadClickAction` is unchanged — an
+ inactive project row switches, the active one toggles its own (now persisted) collapse — and
+ every write **prunes** keys that no longer address a live project/frame (`pruneCollapsedItems` /
+ `liveCollapseKeys`), because settings.json is forever and a canvas churns through group ids.
- The bottom-left **canvas lock** freezes the CAMERA only (pan/zoom): nodes stay draggable,
resizable and connectable while locked — the point is "stop the map sliding", not "freeze
the work".
@@ -522,11 +530,30 @@ session.
process/terminal-title status only.
- **sticky** (`StickyNode.tsx`) — colored note, free text, collapsible. Has link handles:
connect a sticky to any terminal node to attach the note as context (see Context Link).
-- **group** (`GroupNode.tsx`) — real React Flow parent/child frame; `groupSelectedNodes`
- reparents children (`parentId` + `extent:'parent'`, relative positions), `ungroupNodes`
- restores absolute. `nodeStatesToFlow` sorts parents first (React Flow requirement).
- Visually: a dashed rounded frame in the group color with a floating label pill (color dot
- + editable name) on the top border and ungroup/× top-right (on hover/selected). The
+- **group** (`GroupNode.tsx`) — real React Flow parent/child frame, and frames **nest** (2026-08):
+ a group may contain other groups to any depth. `groupSelectedNodes` wraps objects that share ONE
+ container — frames included — creating the wrapper inside that container; a mixed-container set,
+ or an ancestor selected together with its own descendant, is **refused** rather than scrambled
+ (positions are only comparable within one container, and the descendant would be torn out of the
+ ancestor being wrapped). Box-selection routinely catches both, so structural actions normalize
+ the selection to its subtree roots first (`selectedRootIds`). `ungroupNodes` promotes a frame's
+ direct children into **its own parent** (not to the root — that would move them by the whole
+ ancestor offset); `reparentNode` moves a node OR a whole frame subtree, keeps its **root-space**
+ position fixed (`rootPosition`, not the old add-one-parent's-origin math) and refuses a cycle;
+ `addSelectionToGroup` adds a selection to an existing frame; `reorderGroupWithinParent` reorders
+ a frame among its siblings, carrying its subtree. `nodeStatesToFlow`/`groupsFirst` emit frames
+ **depth-first from the root** — a flat "groups first" sort is not enough once two groups compare
+ equal — and that persisted order is also the downgrade contract (a pre-nesting build's stable
+ sort leaves it alone, so a nested tree still hydrates parent-first and renders there).
+ **A frame that gains a child bigger than itself is re-fitted, ancestors included**
+ (`fitGroupToChildren` up the chain): a wrapper created at `(minX-28, minY-62)` relative to its
+ parent is routinely negative, and `extent:'parent'` would make React Flow clamp it into an
+ inverted range — snapping the frame hundreds of px away and dragging the whole wrapped subtree
+ with it. Visually: a dashed rounded frame in the group color with a floating label pill (color
+ dot + editable name) on the top border and ungroup/× top-right (on hover/selected). **The pill
+ is the frame's `dragHandle`** and the frame body is `pointer-events: none` — a frame is a
+ background container, not a giant drag target, so its body passes clicks to the pane and an
+ outer frame cannot swallow the clicks meant for a frame drawn inside it. The
`NodeResizer` line is hidden (`lineStyle` transparent) so it can't draw a sharp-cornered
box; the selection ring is a `box-shadow` instead, which follows the same `border-radius`.
- **editor** (`EditorNode.tsx`) — Monaco code editor for a `filePath`; reads/writes via
@@ -907,11 +934,13 @@ persisted — only `unread`/`session`/`sessionId` go to localStorage under
control the desktop's canvas. The shim is generated source no compiler checks:
`canvas-control-shim.test.ts` runs it for real (/bin/sh against a real hook server, port AND
unix-socket transports) — keep it that way.
- **Grouping verbs** (`group` / `ungroup` / `move` / `arrange` / `align`): `group` only wraps
- **top-level** nodes into a new frame (children already in a frame are skipped — the reply says
- how many + points at `move`); `ungroup --group <id>` dissolves a frame (nodes kept); `move
- --nodes <id,id> [--group <id>]` reparents nodes INTO a frame (or `top`/`none`/omit → out to top
- level) via `reparentNode` — the ONE way to move a node between frames, which `group` won't do.
+ **Grouping verbs** (`group` / `ungroup` / `move` / `arrange` / `align`): `group` wraps **sibling**
+ objects — nodes or frames — into a new frame in their shared container (a mixed-container set, or
+ an ancestor plus its descendant, is refused with that reason); `ungroup --group <id>` dissolves a
+ frame, promoting its direct children into the frame's own parent (nodes kept); `move
+ --nodes <id,id> [--group <id>]` reparents nodes OR whole frame subtrees INTO a frame (or
+ `top`/`none`/omit → out to top level) via `reparentNode` — the ONE way to move a node between
+ frames, which `group` won't do; a cycle (a frame into itself or its own descendant) is refused.
`arrange`/`align` now run in ONE coordinate space: all top-level, OR all children of one frame
(`commonParentId` decides; a mixed set is refused, not silently subset-arranged — the old
behavior). When the ids are a frame's children, the frame is shrunk to hug the tidied layout
diff --git a/src/main/canvas-control-core.ts b/src/main/canvas-control-core.ts
index 0b3b5c61f..8cfb32cc5 100644
--- a/src/main/canvas-control-core.ts
+++ b/src/main/canvas-control-core.ts
@@ -151,9 +151,9 @@ 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 TOP-LEVEL nodes in a new labeled frame (nodes already',
- ' inside another frame are skipped — use `move` for those). `ungroup --group <id>` dissolves a frame,',
- ' freeing its nodes to the top level. `move --nodes <id,id> [--group <id>]` reparents nodes INTO an',
+ '- `group --nodes <id,id> [--label L]` — 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',
' how you move a node from one frame to another.',
'- `arrange --nodes <id,id> [--layout grid|row|column] [--cols N]` /',
@@ -194,8 +194,8 @@ export function buildCanvasControlInstructions(shimPath: string): string {
'per stream `open-worktree --branch <slug>` then `open-agent --agent claude --group <groupId>',
'--prompt "<concrete task>"` (each stream on its own branch, no tree conflicts). Members land',
'in grid slots inside the frame automatically; align the frames themselves with',
- '`arrange --nodes <groupId,…> --layout row` (pass GROUP ids — arrange/align are top-level',
- 'only) and `rename` each by subject. When a station goes idle, READ what it did through the',
+ '`arrange --nodes <groupId,…> --layout row` (pass sibling GROUP ids from one container)',
+ 'and `rename` each by subject. When a station goes idle, READ what it did through the',
'context link (the linked-context CLI — see the get-linked-context section in your global',
'agent instructions) and reconcile the streams into ONE synthesis yourself; a station you',
'never read is one you cannot vouch for. The user merges when a stream is done;',
@@ -335,15 +335,14 @@ 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 TOP-LEVEL nodes in a new labeled
- group frame. Nodes that are ALREADY inside another frame are skipped (the reply says how many) —
- use \`move\` to pull those across, not \`group\`.
-- \`ungroup --group <id>\` — dissolve a group frame, freeing its nodes back to the top level (the
- nodes stay put; only the frame is removed).
-- \`move --nodes <id,id> [--group <id>]\` — reparent nodes INTO an existing group frame, keeping
+- \`group --nodes <id,id> [--label "Frontend Team"]\` — 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).
+- \`move --nodes <id,id> [--group <id>]\` — reparent nodes or group subtrees INTO an existing group, keeping
each where it sits on the canvas. Omit \`--group\` (or pass \`top\`/\`none\`) to pull them OUT to the
top level. This is how you move a node from one frame to another: \`move --nodes n1,n2 --group g2\`.
- (\`group\` only wraps loose top-level nodes; it will not steal a node out of its current frame.)
+ Invalid cycles are rejected.
- \`arrange --nodes <id,id> [--layout grid|row|column] [--cols N]\` — tidy layout, no overlap. Works
on top-level nodes OR on the children of ONE frame — every id must share a container (you cannot
arrange nodes from two different frames, or mix framed + loose, in one call). When the ids are a
@@ -429,8 +428,8 @@ across Nodeterm sessions), be the orchestration chef — plan the kitchen, then
3. Keep the kitchen tidy: members opened with \`--group\` land in neat grid slots inside the
frame automatically (the frame grows to fit), and successive \`open-worktree\` frames fan
out side by side — after opening all stations, align the frames with
- \`arrange --nodes <groupId,groupId,…> --layout row\` (arrange/align work on top-level
- nodes, so pass the GROUP ids, not the children). \`rename\` each group by subject.
+ \`arrange --nodes <groupId,groupId,…> --layout row\` (pass sibling GROUP ids from one
+ container, not their children). \`rename\` each group by subject.
4. Track progress (their status badges show working/waiting) and coordinate.
5. Collect the results yourself — this is the half most orchestrators skip. Every station you
opened is context-linked to you, so when one goes idle, read what it actually did with the
diff --git a/src/renderer/canvas/Canvas.tsx b/src/renderer/canvas/Canvas.tsx
index 0b95c6815..32e90ffaa 100644
--- a/src/renderer/canvas/Canvas.tsx
+++ b/src/renderer/canvas/Canvas.tsx
@@ -308,11 +308,14 @@ import {
isVideoFile,
duplicateNode,
flowToNodeStates,
+ addSelectionToGroup,
groupSelectedNodes,
NODE_COLORS,
nodeStatesToFlow,
+ reorderGroupWithinParent,
reorderNodeBefore,
reparentNode,
+ selectedRootIds,
resolveNewNodeAccount,
accountsForProject,
sshAccountsHint,
@@ -2671,25 +2674,57 @@ export function Canvas() {
// since both decide by comparing against what this returns.
const cwdForNewNodeIn = useCallback(
(parentId: string | undefined): string | undefined => {
- if (!parentId) return undefined
- const parent = nodesRef.current.find((n) => n.id === parentId)
- const stale = useWorktrees.getState().staleGroupIds.includes(parentId)
- if (parent?.data.worktree && !stale && !isSshProject) return parent.data.worktree.path
- return parent?.data.cwd || undefined
+ // Frames nest, so the answer is the NEAREST ancestor that states one — a node dropped in a
+ // sub-frame of a worktree frame still belongs to that worktree checkout.
+ const seen = new Set<string>()
+ let currentId = parentId
+ while (currentId && !seen.has(currentId)) {
+ seen.add(currentId)
+ const parent = nodesRef.current.find((n) => n.id === currentId)
+ if (!parent) return undefined
+ const stale = useWorktrees.getState().staleGroupIds.includes(currentId)
+ if (parent.data.worktree && !stale && !isSshProject) return parent.data.worktree.path
+ if (parent.data.cwd) return parent.data.cwd
+ currentId = parent.parentId
+ }
+ return undefined
},
[isSshProject]
)
+ /** The nearest ancestor frame (from `parentId` upward) that is bound to a git worktree. */
+ const worktreeForGroupChain = useCallback(
+ (parentId: string | undefined): { groupId: string; path: string } | undefined => {
+ const seen = new Set<string>()
+ let currentId = parentId
+ while (currentId && !seen.has(currentId)) {
+ seen.add(currentId)
+ const group = nodesRef.current.find((node) => node.id === currentId)
+ const path = group?.data.worktree?.path as string | undefined
+ if (path) return { groupId: currentId, path }
+ currentId = group?.parentId
+ }
+ return undefined
+ },
+ []
+ )
+
// Reparent a freshly-created node into a group (parentId + extent 'parent', position made
// relative to the group frame). Mirrors how `groupSelectedNodes` parents its children.
const parentInto = useCallback((node: CanvasNode, groupId: string): CanvasNode => {
const group = nodesRef.current.find((n) => n.id === groupId)
if (!group) return node
+ // The frame's own position is relative to ITS parent once frames nest, so the incoming
+ // absolute point must be converted against the frame's ROOT-space origin.
+ const groupPosition = absolutePosition(
+ group as FocusableNode,
+ nodesRef.current as FocusableNode[]
+ )
return {
...node,
parentId: groupId,
extent: 'parent' as const,
- position: { x: node.position.x - group.position.x, y: node.position.y - group.position.y }
+ position: { x: node.position.x - groupPosition.x, y: node.position.y - groupPosition.y }
}
}, [])
@@ -2725,9 +2760,6 @@ export function Canvas() {
const placeSpawned = useCallback(
(node: CanvasNode, pos: { x: number; y: number }): CanvasNode => {
const placed = { ...node, position: pos, parentId: undefined, extent: undefined }
- // A group frame is never nested into another (the model is one level deep — see
- // groupSelectedNodes/ungroupNodes); it just lands where it was dropped.
- if (placed.type === 'group') return placed
const groupId = groupAtPoint(pos)
return groupId ? parentInto(placed, groupId) : placed
},
@@ -3668,6 +3700,16 @@ export function Canvas() {
[setNodes, markDirty]
)
+ // Add the current selection to an EXISTING frame (the counterpart of "Group selection", which
+ // always makes a new one). Only subtree roots move — see addSelectionToGroup.
+ const addToExistingGroup = useCallback(
+ (ids: string[], groupId: string) => {
+ setNodes((nodes) => addSelectionToGroup(nodes as CanvasNode[], ids, groupId))
+ markDirty()
+ },
+ [setNodes, markDirty]
+ )
+
// Detach single nodes from their group frame (the frame and its other children stay).
// Counterpart of drag-into-group / `ungroup` (which dissolves the whole frame).
const removeFromGroup = useCallback(
@@ -4118,9 +4160,7 @@ export function Canvas() {
(nodeId: string) => {
const node = nodesRef.current.find((n) => n.id === nodeId)
const parentId = node?.parentId
- const wtPath = nodesRef.current.find((p) => p.id === parentId)?.data.worktree?.path as
- | string
- | undefined
+ const wtPath = worktreeForGroupChain(parentId)?.path
if (!wtPath) return
// Never open the confirm for a session that does not live on this machine (see the confirm).
if (isSshProject || isRemoteSessionNode(node?.data)) {
@@ -4137,7 +4177,7 @@ export function Canvas() {
}
setMoveTarget(nodeId)
},
- [cwdForNewNodeIn, isSshProject]
+ [cwdForNewNodeIn, isSshProject, worktreeForGroupChain]
)
const confirmMoveIntoWorktree = useCallback(async () => {
@@ -4145,8 +4185,7 @@ export function Canvas() {
setMoveTarget(null)
if (!id) return
const node = nodesRef.current.find((n) => n.id === id)
- const parent = nodesRef.current.find((p) => p.id === node?.parentId)
- const wtPath = parent?.data.worktree?.path as string | undefined
+ const wtPath = worktreeForGroupChain(node?.parentId)?.path
if (!node || !wtPath || node.data.cwd === wtPath) return
// A session that runs on another machine must never be moved into a LOCAL worktree: `destroy`
// would end its REMOTE tmux session (running processes and all) and respawn it in a directory
@@ -4209,7 +4248,7 @@ export function Canvas() {
)
)
markDirty()
- }, [moveTarget, setNodes, markDirty, cwdForNewNodeIn, isSshProject])
+ }, [moveTarget, setNodes, markDirty, cwdForNewNodeIn, isSshProject, worktreeForGroupChain])
// Bridge the move-into-worktree handler to TerminalNode (React Flow owns the instances).
useEffect(() => {
@@ -4727,22 +4766,58 @@ export function Canvas() {
return tidySeparators([
{ type: 'label', label: ids.length > 1 ? `${ids.length} nodes` : '1 node' },
...((): MenuItem[] => {
- // "Group …" only when something is actually groupable (top-level, not itself a group —
- // groupSelectedNodes silently skips the rest, so the item would otherwise no-op);
- // "Remove from group" only when a target is inside a group frame (the frame stays).
- const groupable = ids.some((nid) => {
- const n = nodesRef.current.find((nd) => nd.id === nid)
- return !!n && !n.parentId && n.type !== 'group'
- })
+ // "Group …" wraps objects that share ONE container — existing frames are valid members
+ // now that frames nest. A box-selection that caught a frame AND its children is
+ // normalized to its subtree roots first (selectedRootIds), so the children are not torn
+ // out of the frame being wrapped; a set spanning two containers is refused, because
+ // their positions are not comparable. "Remove from group" only when a target is inside
+ // a frame (the frame stays).
+ const selectedNodes = ids
+ .map((nid) => nodesRef.current.find((node) => node.id === nid))
+ .filter((node): node is CanvasNode => !!node)
+ const rootIds = selectedRootIds(nodesRef.current as CanvasNode[], ids)
+ const rootSet = new Set(rootIds)
+ const rootNodes = selectedNodes.filter((node) => rootSet.has(node.id))
+ const groupable =
+ rootNodes.length > 0 &&
+ (ids.length === 1 || rootNodes.length > 1) &&
+ new Set(rootNodes.map((node) => node.parentId ?? null)).size === 1
+ // Frames in the selection that this selection could actually be ADDED to (the pure
+ // transform is asked, so the item can never be a no-op).
+ const targetGroups = selectedNodes.filter(
+ (node) =>
+ node.type === 'group' &&
+ addSelectionToGroup(nodesRef.current as CanvasNode[], ids, node.id) !==
+ nodesRef.current
+ )
const parented = ids.some(
(nid) => !!nodesRef.current.find((nd) => nd.id === nid)?.parentId
)
const items: MenuItem[] = []
+ if (targetGroups.length === 1 && !isHidden('group', hidden)) {
+ const targetGroup = targetGroups[0]
+ items.push({
+ label: `Add selection to ${targetGroup.data.title || 'group'}`,
+ icon: <IconGroup />,
+ onClick: () => addToExistingGroup(ids, targetGroup.id)
+ })
+ } else if (targetGroups.length > 1 && !isHidden('group', hidden)) {
+ items.push({
+ type: 'submenu',
+ label: 'Add selection to group',
+ icon: <IconGroup />,
+ children: targetGroups.map((targetGroup) => ({
+ label: targetGroup.data.title || 'Group',
+ icon: <IconGroup />,
+ onClick: () => addToExistingGroup(ids, targetGroup.id)
+ }))
+ })
+ }
if (groupable && !isHidden('group', hidden))
items.push({
- label: ids.length > 1 ? 'Group selection' : 'Group node',
+ label: rootIds.length > 1 ? 'Group selection' : 'Group node',
icon: <IconGroup />,
- onClick: () => groupSelection(ids)
+ onClick: () => groupSelection(rootIds)
})
if (parented && !isHidden('remove-from-group', hidden))
items.push({
@@ -4884,6 +4959,7 @@ export function Canvas() {
])
}, [
groupSelection,
+ addToExistingGroup,
removeFromGroup,
setNodesColor,
duplicateNodes,
@@ -4981,11 +5057,45 @@ export function Canvas() {
)
const groupItems = useCallback(
- (groupId: string, at?: { x: number; y: number }): MenuItem[] =>
+ (groupId: string, at?: { x: number; y: number }): MenuItem[] => {
+ // Right-clicking a frame while other objects are selected is the natural way to say "put
+ // these in here" (or "wrap all of us in a new frame"). Both are offered only when the pure
+ // transform would actually do something.
+ const selectedIds = nodesRef.current.filter((node) => node.selected).map((node) => node.id)
+ const rootIds = selectedRootIds(nodesRef.current as CanvasNode[], selectedIds)
+ const rootSet = new Set(rootIds)
+ const rootNodes = nodesRef.current.filter((node) => rootSet.has(node.id))
+ const canWrapSelection =
+ selectedIds.includes(groupId) &&
+ rootNodes.length > 1 &&
+ new Set(rootNodes.map((node) => node.parentId ?? null)).size === 1
+ const canAddSelection =
+ selectedIds.includes(groupId) &&
+ addSelectionToGroup(nodesRef.current as CanvasNode[], selectedIds, groupId) !==
+ nodesRef.current
+ const groupHidden = isHidden('group', useSettings.getState().settings.hiddenNodeMenuItems)
// The group frame has its own colors strip; it answers to the same "Colors" toggle as the
// node menu, so hiding it in Settings hides it everywhere a right-click can reach it.
- tidySeparators([
+ return tidySeparators([
{ type: 'label', label: 'Group' },
+ ...(canAddSelection && !groupHidden
+ ? [
+ {
+ label: 'Add selected objects to group',
+ icon: <IconGroup />,
+ onClick: () => addToExistingGroup(selectedIds, groupId)
+ } as MenuItem
+ ]
+ : []),
+ ...(canWrapSelection && !groupHidden
+ ? [
+ {
+ label: 'Wrap selection in new group',
+ icon: <IconGroup />,
+ onClick: () => groupSelection(rootIds)
+ } as MenuItem
+ ]
+ : []),
{
label: 'New terminal',
icon: <IconTerminal />,
@@ -5018,7 +5128,8 @@ export function Canvas() {
danger: true,
onClick: () => ungroup(groupId)
}
- ]),
+ ])
+ },
[
setNodesColor,
ungroup,
@@ -5027,7 +5138,9 @@ export function Canvas() {
isSshProject,
addTerminal,
agentCreationItems,
- addSticky
+ addSticky,
+ addToExistingGroup,
+ groupSelection
]
)
@@ -6025,14 +6138,21 @@ export function Canvas() {
case 'group': {
const ids = (args.nodes ?? '').split(',').map((s) => s.trim()).filter(Boolean)
const live = nodesRef.current as CanvasNode[]
- const resolvable = ids.filter((gid) => live.some((nd) => nd.id === gid && !nd.parentId && nd.type !== 'group'))
+ const resolvable = ids.filter((id) => live.some((node) => node.id === id))
if (resolvable.length === 0) {
- reply({ ok: false, error: 'group: none of the given node ids are groupable (top-level, non-group)' })
+ reply({ ok: false, error: 'group: none of the given node ids exist' })
return
}
const groupCount = live.filter((nd) => nd.type === 'group').length
let grouped = groupSelectedNodes(live, resolvable, groupCount)
- const groupNode = grouped[0] // groupSelectedNodes returns the new group first
+ // The new frame is no longer guaranteed to be first (it is emitted in tree order),
+ // and a refused set returns the array unchanged — find it by id instead.
+ const oldIds = new Set(live.map((node) => node.id))
+ const groupNode = grouped.find((node) => !oldIds.has(node.id) && node.type === 'group')
+ if (!groupNode) {
+ 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) {
grouped = grouped.map((nd) =>
nd.id === groupNode.id ? { ...nd, data: { ...nd.data, title: args.label } } : nd
@@ -6040,12 +6160,8 @@ export function Canvas() {
}
setNodes(grouped)
markDirty()
- // Nodes already inside another frame are skipped (group only wraps loose nodes) — say
- // so, and point at `move`, so the agent isn't left wondering why a node stayed put.
const skippedGrouped = ids.length - resolvable.length
- const groupNote = skippedGrouped > 0
- ? ` (${skippedGrouped} already in a frame were skipped — use \`move --group ${groupNode.id}\` for those)`
- : ''
+ const groupNote = skippedGrouped > 0 ? ` (${skippedGrouped} unknown id(s) skipped)` : ''
reply({
ok: true,
message: `grouped ${resolvable.length} node(s) into ${groupNode.id}${groupNote}`,
@@ -6068,9 +6184,10 @@ export function Canvas() {
return
}
case 'move': {
- // Reparent nodes INTO an existing frame (or out to the top level) — the one way to
- // move a node OUT of its current frame, which `group` deliberately won't do. `reparentNode`
- // keeps each node fixed on the canvas via absolute↔relative conversion.
+ // Reparent nodes — or whole frame subtrees — INTO an existing frame (or out to the
+ // top level): the one way to move a node OUT of its current frame, which `group`
+ // deliberately won't do. `reparentNode` keeps each node's ROOT-space position fixed
+ // and refuses a cycle (a frame into itself or its own descendant).
const ids = (args.nodes ?? '').split(',').map((s) => s.trim()).filter(Boolean)
const live = nodesRef.current as CanvasNode[]
const rawTarget = (args.group ?? '').trim().toLowerCase()
@@ -6085,12 +6202,12 @@ export function Canvas() {
for (const id of ids) {
const before = next
const nd = next.find((n) => n.id === id)
- // Skip a group id, an unknown id, or a node already in the requested container.
- if (nd && nd.type !== 'group') next = reparentNode(next, id, targetGroup)
+ // Skip an unknown id, a node already in the requested container, or a cycle.
+ if (nd) next = reparentNode(next, id, targetGroup)
if (next !== before) moved.push(id)
}
if (moved.length === 0) {
- reply({ ok: false, error: 'move: nothing moved (unknown ids, group ids, or already there)' })
+ reply({ ok: false, error: 'move: nothing moved (unknown ids, already there, or an invalid group cycle)' })
return
}
// The source frame(s) the nodes LEFT, and the destination, may now be the wrong size —
@@ -6275,8 +6392,13 @@ export function Canvas() {
let next: CanvasNode[] = [...live, ...reviewers, ...(judge ? [judge] : [])]
next = arrangeNodes(next, panelIds, { layout: 'grid', origin: placeBelow(0) })
const vGroupCount = next.filter((nd) => nd.type === 'group').length
+ const existingGroupIds = new Set(
+ next.filter((node) => node.type === 'group').map((node) => node.id)
+ )
next = groupSelectedNodes(next, panelIds, vGroupCount)
- const vGroup = next[0]
+ const vGroup = next.find(
+ (node) => node.type === 'group' && !existingGroupIds.has(node.id)
+ )!
next = next.map((nd) =>
nd.id === vGroup.id
? { ...nd, data: { ...nd.data, title: args.label || `Verify: ${targetTitle}` } }
@@ -6355,8 +6477,13 @@ export function Canvas() {
let next: CanvasNode[] = [...live, ...members]
next = arrangeNodes(next, memberIds, { layout: 'grid', origin: placeBelow(0) })
const groupCount = next.filter((nd) => nd.type === 'group').length
+ const existingGroupIds = new Set(
+ next.filter((node) => node.type === 'group').map((node) => node.id)
+ )
next = groupSelectedNodes(next, memberIds, groupCount)
- const teamGroup = next[0]
+ const teamGroup = next.find(
+ (node) => node.type === 'group' && !existingGroupIds.has(node.id)
+ )!
next = next.map((nd) =>
nd.id === teamGroup.id ? { ...nd, data: { ...nd.data, title: args.label || 'Team' } } : nd
)
@@ -6942,6 +7069,21 @@ export function Canvas() {
[activeProjectId, setNodes, markDirty, writeDisk]
)
+ // Sibling reorder for a FRAME row in the sessions sidebar. Distinct from reorderSession:
+ // a frame carries its whole subtree, and the drop never changes its parent.
+ const reorderSidebarGroup = useCallback(
+ (projectId: string, draggedId: string, parentId: string | null, beforeId: string | null) => {
+ if (projectId === activeProjectId) {
+ setNodes((ns) => reorderGroupWithinParent(ns, draggedId, parentId, beforeId))
+ markDirty()
+ } else {
+ useProjects.getState().reorderGroup(projectId, draggedId, parentId, beforeId)
+ void writeDisk()
+ }
+ },
+ [activeProjectId, setNodes, markDirty, writeDisk]
+ )
+
const onRowContextMenu = useCallback(
(e: React.MouseEvent, projectId: string, id: string) => {
e.preventDefault()
@@ -8234,6 +8376,9 @@ export function Canvas() {
// Figma-style default: left-drag rubber-band selects, pan is middle-drag/scroll.
selectionOnDrag={!spacePan && settings.canvasDragMode !== 'pan'}
selectionMode={SelectionMode.Partial}
+ // Shift joins the default Meta/Control: adding a frame to an existing selection is the
+ // gesture "Add selection to group" is reached by, and Shift+click is what users try.
+ multiSelectionKeyCode={['Shift', 'Meta', 'Control']}
// The lock freezes the CAMERA only (pan/zoom) — nodes stay draggable, resizable and
// connectable: the point is "stop the map sliding under me", not "freeze my work".
panOnDrag={
@@ -8490,6 +8635,7 @@ export function Canvas() {
onAiNameGroup={aiNameGroup}
onMoveToGroup={moveSessionToGroup}
onReorder={reorderSession}
+ onReorderGroup={reorderSidebarGroup}
onRowContextMenu={onRowContextMenu}
onProjectContextMenu={onProjectContextMenu}
onSwitchProject={switchProject}
diff --git a/src/renderer/components/SessionsSidebar.tsx b/src/renderer/components/SessionsSidebar.tsx
index b989c3369..546838ead 100644
--- a/src/renderer/components/SessionsSidebar.tsx
+++ b/src/renderer/components/SessionsSidebar.tsx
@@ -1,9 +1,16 @@
import { useEffect, useMemo, useState } from 'react'
import {
buildSessionList,
+ groupCollapseKey,
+ groupSessionCount,
+ groupSessionRows,
isGroupCollapsed,
+ liveCollapseKeys,
+ projectCollapseKey,
projectHeadClickAction,
projectSignalCounts,
+ pruneCollapsedItems,
+ type GroupBucket,
type SessionNodeInput
} from '../lib/sessionList'
import { SessionRow } from './SessionRow'
@@ -39,6 +46,13 @@ export interface SessionsSidebarProps {
onAiNameGroup(projectId: string, groupId: string, memberIds: string[], cwd?: string): void | Promise<void>
/** Reorder a session to sit immediately before another (within/across containers). */
onReorder(projectId: string, draggedId: string, beforeId: string): void
+ /** Reorder a group frame among its siblings. `beforeId` null appends within that parent. */
+ onReorderGroup(
+ projectId: string,
+ draggedId: string,
+ parentGroupId: string | null,
+ beforeId: string | null
+ ): void
/** Reorder a project to sit before another (null = to the end). Shared order with the
* tab bar: both render the projects array, so one drag updates both surfaces. */
onReorderProject(draggedId: string, beforeId: string | null): void
@@ -58,14 +72,16 @@ export function SessionsSidebar(props: SessionsSidebarProps): JSX.Element | null
const { api } = useSession()
const [filter, setFilter] = useState('')
- // Explicit per-project collapse choices (true = collapsed, false = expanded). Absent =
- // follow the default (active project expanded, others collapsed — see isGroupCollapsed).
- // Deliberately transient: reset on every project switch, so the toggles are "for now",
- // not forever — switching projects always re-focuses the list on the active one.
- const [overrides, setOverrides] = useState<Record<string, boolean>>({})
const [branches, setBranches] = useState<Record<string, string>>({})
- // Drag-to-group: the session being dragged, and the current drop target for highlighting.
- const [drag, setDrag] = useState<{ projectId: string; nodeId: string } | null>(null)
+ // Drag-to-group: the object being dragged, and the current drop target for highlighting.
+ // A group drag also remembers its parent frame, so a sibling-reorder drop zone can refuse a
+ // drag that came from another container (that move is a REPARENT, which the head handles).
+ const [drag, setDrag] = useState<{
+ projectId: string
+ nodeId: string
+ kind: 'session' | 'group'
+ parentGroupId?: string | null
+ } | null>(null)
const [dropKey, setDropKey] = useState<string | null>(null)
// Project reorder: the project being dragged (by its header) + the project it would land
// before ('' = end of the list). Distinct from the session drag above — one at a time.
@@ -74,16 +90,12 @@ export function SessionsSidebar(props: SessionsSidebarProps): JSX.Element | null
// Inline group rename: the group node id being edited + its draft title.
const [editGroup, setEditGroup] = useState<{ id: string; draft: string } | null>(null)
- // Switching the active project resets the manual collapse choices, so the default takes
- // over again: the newly active project expands, everything else collapses. Without this,
- // one manual toggle stuck forever and project switches stopped re-focusing the list.
- // Gated on settings.sidebarAutoCollapse — with it OFF, a project switch changes nothing:
- // every project defaults to expanded (see isGroupCollapsed) and the user's toggles stick.
+ // Disclosure choices are PERSISTED (settings.sidebarCollapsedItems), for group frames as well
+ // as projects: a tree the user shaped should still be that shape after a restart. This
+ // deliberately replaces the old "a project switch resets every manual toggle" effect —
+ // sidebarAutoCollapse now only supplies the DEFAULT for a row nobody ever toggled.
const autoCollapse = useSettings((s) => s.settings.sidebarAutoCollapse)
- useEffect(() => {
- if (!autoCollapse) return
- setOverrides((prev) => (Object.keys(prev).length === 0 ? prev : {}))
- }, [activeProjectId, autoCollapse])
+ const collapsedItems = useSettings((s) => s.settings.sidebarCollapsedItems)
// Look up the current git branch for each project cwd (best-effort, cached). Gated on `open`
// and caches a NEGATIVE result too — without the '' fallback a non-git cwd re-fired a git
@@ -120,11 +132,17 @@ export function SessionsSidebar(props: SessionsSidebarProps): JSX.Element | null
)
const projectCount = (g: (typeof groups)[number]): number =>
- g.groups.reduce((n, b) => n + b.sessions.length, 0) + g.ungrouped.length
+ g.groups.reduce((n, b) => n + groupSessionCount(b), 0) + g.ungrouped.length
const total = groups.reduce((n, g) => n + projectCount(g), 0)
- const toggleCollapse = (id: string, currentlyCollapsed: boolean): void => {
- setOverrides((prev) => ({ ...prev, [id]: !currentlyCollapsed }))
+ // Every write prunes keys that no longer address a live project/frame — settings.json is
+ // forever, and a canvas churns through group ids.
+ const toggleCollapse = (key: string, currentlyCollapsed: boolean): void => {
+ const current = useSettings.getState().settings.sidebarCollapsedItems
+ const pruned = pruneCollapsedItems(current, liveCollapseKeys(groups), key)
+ useSettings.getState().update({
+ sidebarCollapsedItems: { ...pruned, [key]: !currentlyCollapsed }
+ })
}
// Drop-target wiring shared by the project header (ungroup) and group sub-headers (add).
@@ -207,7 +225,7 @@ export function SessionsSidebar(props: SessionsSidebarProps): JSX.Element | null
onRename={(title) => props.onRenameSession(projectId, row.id, title)}
onAiName={() => props.onAiNameSession(projectId, row.id, row.cwd)}
onContextMenu={(e) => props.onRowContextMenu(e, projectId, row.id)}
- onDragStart={() => setDrag({ projectId, nodeId: row.id })}
+ onDragStart={() => setDrag({ projectId, nodeId: row.id, kind: 'session' })}
onDragEnd={() => {
setDrag(null)
setDropKey(null)
@@ -217,6 +235,172 @@ export function SessionsSidebar(props: SessionsSidebarProps): JSX.Element | null
)
}
+ /**
+ * One group frame's row and everything under it, recursively — this is what makes the sidebar
+ * a TREE rather than one flat level. `parentGroupId` is the frame's container: a sibling
+ * reorder only accepts a drag that started in the same container, so a cross-container drop
+ * stays a reparent (the head's dropProps), not a silent reorder that also moved the node.
+ */
+ const renderBucket = (
+ projectId: string,
+ projectCwd: string | undefined,
+ bucket: GroupBucket,
+ parentGroupId: string | null
+ ): JSX.Element => {
+ const collapseKey = groupCollapseKey(projectId, bucket.id)
+ // A frame the user never toggled is expanded; while FILTERING nothing is collapsed, or a
+ // collapsed frame would hide the very match the user is searching for.
+ const collapsed = filter ? false : (collapsedItems[collapseKey] ?? false)
+ const members = groupSessionRows(bucket)
+ const canReorderHere = (): boolean =>
+ !!drag && drag.kind === 'group' && drag.projectId === projectId &&
+ (drag.parentGroupId ?? null) === parentGroupId
+ return (
+ <div key={bucket.id} className="ss-subgroup">
+ <div
+ className={`ss-subgroup__reorder-zone${dropKey === `group-before:${bucket.id}` ? ' is-drop-before' : ''}`}
+ onDragOver={(e) => {
+ if (!canReorderHere() || drag!.nodeId === bucket.id) return
+ e.preventDefault()
+ e.stopPropagation()
+ setDropKey(`group-before:${bucket.id}`)
+ }}
+ onDragLeave={() => setDropKey((k) => (k === `group-before:${bucket.id}` ? null : k))}
+ onDrop={(e) => {
+ if (!canReorderHere() || drag!.nodeId === bucket.id) return
+ e.preventDefault()
+ e.stopPropagation()
+ props.onReorderGroup(projectId, drag!.nodeId, parentGroupId, bucket.id)
+ setDrag(null)
+ setDropKey(null)
+ }}
+ />
+ <div
+ className={`ss-subgroup__head${dropClass(projectId, bucket.id)}`}
+ title="Click to show the group on the canvas"
+ onClick={() => props.onFocusNode(bucket.id)}
+ onContextMenu={(e) => props.onRowContextMenu(e, projectId, bucket.id)}
+ draggable
+ onDragStart={(e) => {
+ e.stopPropagation()
+ e.dataTransfer.effectAllowed = 'move'
+ setDrag({ projectId, nodeId: bucket.id, kind: 'group', parentGroupId })
+ }}
+ onDragEnd={() => {
+ setDrag(null)
+ setDropKey(null)
+ }}
+ {...dropProps(projectId, bucket.id)}
+ >
+ <button
+ type="button"
+ className="ss-group__chev"
+ aria-label={collapsed ? `Expand ${bucket.title}` : `Collapse ${bucket.title}`}
+ aria-expanded={!collapsed}
+ draggable={false}
+ onClick={(e) => {
+ e.stopPropagation()
+ toggleCollapse(collapseKey, collapsed)
+ }}
+ >
+ {collapsed ? '▶' : '▼'}
+ </button>
+ <span className="ss-subgroup__dot" style={{ background: bucket.color }} />
+ {editGroup?.id === bucket.id ? (
+ <input
+ className="ss-title-input"
+ style={{ flex: 1, minWidth: 0 }}
+ autoFocus
+ value={editGroup.draft}
+ onClick={(e) => e.stopPropagation()}
+ onChange={(e) => setEditGroup({ id: bucket.id, draft: e.target.value })}
+ onBlur={() => {
+ const t = editGroup.draft.trim()
+ if (t && t !== bucket.title) props.onRenameSession(projectId, bucket.id, t)
+ setEditGroup(null)
+ }}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter') e.currentTarget.blur()
+ if (e.key === 'Escape') setEditGroup(null)
+ }}
+ />
+ ) : (
+ <span
+ className="ss-subgroup__name"
+ title="Double-click to rename group"
+ onDoubleClick={(e) => {
+ e.stopPropagation()
+ setEditGroup({ id: bucket.id, draft: bucket.title })
+ }}
+ >
+ {bucket.title}
+ </span>
+ )}
+ <span className="ss-group__count">{groupSessionCount(bucket)}</span>
+ {members.length > 0 && (
+ <button
+ className="ss-subgroup__ai"
+ title="Name group with AI (from every session below it)"
+ disabled={!!namingById[bucket.id]}
+ onClick={(e) => {
+ e.stopPropagation()
+ if (namingById[bucket.id]) return
+ void props.onAiNameGroup(
+ projectId,
+ bucket.id,
+ members.map((session) => session.id),
+ projectCwd
+ )
+ }}
+ >
+ {namingById[bucket.id] ? '…' : '✦'}
+ </button>
+ )}
+ </div>
+ {!collapsed && (
+ <>
+ {bucket.children.map((child) => renderBucket(projectId, projectCwd, child, bucket.id))}
+ {bucket.children.length > 0 && (
+ <div
+ className={`ss-subgroup__reorder-end${dropKey === `group-end:${bucket.id}` ? ' is-drop-before' : ''}`}
+ onDragOver={(e) => {
+ if (
+ !drag ||
+ drag.kind !== 'group' ||
+ drag.projectId !== projectId ||
+ (drag.parentGroupId ?? null) !== bucket.id
+ ) return
+ e.preventDefault()
+ e.stopPropagation()
+ setDropKey(`group-end:${bucket.id}`)
+ }}
+ onDragLeave={() => setDropKey((k) => (k === `group-end:${bucket.id}` ? null : k))}
+ onDrop={(e) => {
+ if (
+ !drag ||
+ drag.kind !== 'group' ||
+ drag.projectId !== projectId ||
+ (drag.parentGroupId ?? null) !== bucket.id
+ ) return
+ e.preventDefault()
+ e.stopPropagation()
+ props.onReorderGroup(projectId, drag.nodeId, bucket.id, null)
+ setDrag(null)
+ setDropKey(null)
+ }}
+ />
+ )}
+ {bucket.sessions.length === 0 && bucket.children.length === 0 ? (
+ <div className="ss-group__empty">Drop a session or group here</div>
+ ) : (
+ bucket.sessions.map((row) => renderRow(projectId, row))
+ )}
+ </>
+ )}
+ </div>
+ )
+ }
+
if (!open) return null
return (
@@ -269,7 +453,11 @@ export function SessionsSidebar(props: SessionsSidebarProps): JSX.Element | null
>
{groups.length === 0 && <div className="sessions-sidebar__empty">No sessions yet.</div>}
{groups.map((g) => {
- const isCollapsed = isGroupCollapsed(overrides, g.projectId, g.isActive, autoCollapse)
+ const collapseKey = projectCollapseKey(g.projectId)
+ // While filtering, never collapse — a collapsed project would hide its own matches.
+ const isCollapsed = filter
+ ? false
+ : isGroupCollapsed(collapsedItems, collapseKey, g.isActive, autoCollapse)
const signals = projectSignalCounts(g)
return (
<div
@@ -287,7 +475,7 @@ export function SessionsSidebar(props: SessionsSidebarProps): JSX.Element | null
// toggles its own collapse, so the row keeps no dead zone.
onClick={() => {
if (projectHeadClickAction(g.isActive) === 'switch') props.onSwitchProject(g.projectId)
- else toggleCollapse(g.projectId, isCollapsed)
+ else toggleCollapse(collapseKey, isCollapsed)
}}
onContextMenu={(e) => props.onProjectContextMenu(e, g.projectId)}
title={drag?.projectId === g.projectId ? 'Drop here to remove from group' : undefined}
@@ -311,9 +499,10 @@ export function SessionsSidebar(props: SessionsSidebarProps): JSX.Element | null
title={isCollapsed ? 'Expand' : 'Collapse'}
aria-label={isCollapsed ? `Expand ${g.projectName}` : `Collapse ${g.projectName}`}
aria-expanded={!isCollapsed}
+ draggable={false}
onClick={(e) => {
e.stopPropagation()
- toggleCollapse(g.projectId, isCollapsed)
+ toggleCollapse(collapseKey, isCollapsed)
}}
>
{isCollapsed ? '▶' : '▼'}
@@ -357,73 +546,37 @@ export function SessionsSidebar(props: SessionsSidebarProps): JSX.Element | null
</div>
{!isCollapsed && (
<>
- {g.groups.map((bucket) => (
- <div key={bucket.id} className="ss-subgroup">
- <div
- className={`ss-subgroup__head${dropClass(g.projectId, bucket.id)}`}
- title="Click to show the group on the canvas"
- onClick={() => props.onFocusNode(bucket.id)}
- {...dropProps(g.projectId, bucket.id)}
- >
- <span className="ss-subgroup__dot" style={{ background: bucket.color }} />
- {editGroup?.id === bucket.id ? (
- <input
- className="ss-title-input"
- style={{ flex: 1, minWidth: 0 }}
- autoFocus
- value={editGroup.draft}
- onClick={(e) => e.stopPropagation()}
- onChange={(e) => setEditGroup({ id: bucket.id, draft: e.target.value })}
- onBlur={() => {
- const t = editGroup.draft.trim()
- if (t && t !== bucket.title) props.onRenameSession(g.projectId, bucket.id, t)
- setEditGroup(null)
- }}
- onKeyDown={(e) => {
- if (e.key === 'Enter') e.currentTarget.blur()
- if (e.key === 'Escape') setEditGroup(null)
- }}
- />
- ) : (
- <span
- className="ss-subgroup__name"
- title="Double-click to rename group"
- onDoubleClick={(e) => {
- e.stopPropagation()
- setEditGroup({ id: bucket.id, draft: bucket.title })
- }}
- >
- {bucket.title}
- </span>
- )}
- <span className="ss-group__count">{bucket.sessions.length}</span>
- {bucket.sessions.length > 0 && (
- <button
- className="ss-subgroup__ai"
- title="Name group with AI (from members' output)"
- disabled={!!namingById[bucket.id]}
- onClick={(e) => {
- e.stopPropagation()
- if (namingById[bucket.id]) return
- void props.onAiNameGroup(
- g.projectId,
- bucket.id,
- bucket.sessions.map((s) => s.id),
- g.cwd
- )
- }}
- >
- {namingById[bucket.id] ? '…' : '✦'}
- </button>
- )}
- </div>
- {bucket.sessions.length === 0 ? (
- <div className="ss-group__empty">Drop a session here</div>
- ) : (
- bucket.sessions.map((row) => renderRow(g.projectId, row))
- )}
- </div>
- ))}
+ {g.groups.map((bucket) => renderBucket(g.projectId, g.cwd, bucket, null))}
+ {g.groups.length > 0 && (
+ <div
+ className={`ss-subgroup__reorder-end ss-subgroup__reorder-end--root${dropKey === `group-end:${g.projectId}` ? ' is-drop-before' : ''}`}
+ onDragOver={(e) => {
+ if (
+ !drag ||
+ drag.kind !== 'group' ||
+ drag.projectId !== g.projectId ||
+ (drag.parentGroupId ?? null) !== null
+ ) return
+ e.preventDefault()
+ e.stopPropagation()
+ setDropKey(`group-end:${g.projectId}`)
+ }}
+ onDragLeave={() => setDropKey((k) => (k === `group-end:${g.projectId}` ? null : k))}
+ onDrop={(e) => {
+ if (
+ !drag ||
+ drag.kind !== 'group' ||
+ drag.projectId !== g.projectId ||
+ (drag.parentGroupId ?? null) !== null
+ ) return
+ e.preventDefault()
+ e.stopPropagation()
+ props.onReorderGroup(g.projectId, drag.nodeId, null, null)
+ setDrag(null)
+ setDropKey(null)
+ }}
+ />
+ )}
{g.ungrouped.length === 0 && g.groups.length === 0 ? (
<div className="ss-group__empty">No sessions</div>
) : (
diff --git a/src/renderer/components/settings/sections/BehaviorSection.tsx b/src/renderer/components/settings/sections/BehaviorSection.tsx
index 20fb761bd..4d71caf95 100644
--- a/src/renderer/components/settings/sections/BehaviorSection.tsx
+++ b/src/renderer/components/settings/sections/BehaviorSection.tsx
@@ -21,8 +21,8 @@ const ROWS = {
panHover: { title: 'Pan-hover delay (ms)', keywords: ['pan', 'hover', 'delay', 'focus', 'guard'] },
doubleClick: { title: 'Double-click to focus', keywords: ['double', 'click', 'focus'] },
sidebarCollapse: {
- title: 'Sidebar: focus active project',
- keywords: ['sidebar', 'sessions', 'collapse', 'expand', 'project', 'switch']
+ title: 'Sidebar: collapse inactive by default',
+ keywords: ['sidebar', 'sessions', 'collapse', 'expand', 'project', 'switch', 'group', 'tree']
},
wheelZoom: { title: 'Scroll wheel zooms', keywords: ['zoom', 'wheel', 'scroll', 'mouse', 'pan'] },
dragMode: {
@@ -135,13 +135,13 @@ export function BehaviorSection({ isActive }: { isActive: boolean }): React.JSX.
</SearchableRow>
<SearchableRow {...ROWS.sidebarCollapse}>
<FieldRow
- label="Sidebar: focus active project"
- description="Collapse inactive projects in the sessions sidebar when switching projects. Off: everything stays as you left it."
+ label="Sidebar: collapse inactive by default"
+ description="Projects without an explicit choice start collapsed when inactive. Your project and group chevron choices are remembered."
control={
<Switch
checked={settings.sidebarAutoCollapse}
onChange={(v) => update({ sidebarAutoCollapse: v })}
- ariaLabel="Sidebar: focus active project"
+ ariaLabel="Sidebar: collapse inactive by default"
/>
}
/>
diff --git a/src/renderer/lib/sessionList.test.ts b/src/renderer/lib/sessionList.test.ts
index 8915ebce9..f45a89e89 100644
--- a/src/renderer/lib/sessionList.test.ts
+++ b/src/renderer/lib/sessionList.test.ts
@@ -1,6 +1,10 @@
import { describe, it, expect } from 'vitest'
import {
buildSessionList,
+ groupSessionCount,
+ groupSessionRows,
+ liveCollapseKeys,
+ pruneCollapsedItems,
sessionStatusKind,
projectIdAtIndex,
isGroupCollapsed,
@@ -154,6 +158,7 @@ describe('buildSessionList', () => {
expect(p1.groups).toHaveLength(1)
expect(p1.groups[0]).toMatchObject({ id: 'g1', title: 'Frontend', color: '#abc' })
expect(p1.groups[0].sessions.map((s) => s.id)).toEqual(['t1', 't2'])
+ expect(p1.groups[0].children).toEqual([])
expect(p1.ungrouped.map((s) => s.id)).toEqual(['t3', 't4'])
})
@@ -187,6 +192,108 @@ describe('buildSessionList', () => {
const unfiltered = buildSessionList(projects(), null, 'p1', {}, '')
expect(unfiltered.length).toBe(2) // both projects kept when no filter
})
+
+ it('builds nested canvas groups as a recursive tree and preserves ancestors when filtering', () => {
+ const proj: ProjectInput[] = [
+ {
+ id: 'p1',
+ name: 'Alpha',
+ color: '#111',
+ nodes: [
+ node('outer', { kind: 'group', title: 'Outer' }),
+ node('inner', { kind: 'group', title: 'Inner', parentId: 'outer' }),
+ node('deep', { kind: 'group', title: 'Deep', parentId: 'inner' }),
+ node('direct', { parentId: 'outer' }),
+ node('target', { title: 'Needle session', parentId: 'deep' })
+ ]
+ }
+ ]
+ const [all] = buildSessionList(
+ proj,
+ null,
+ 'p1',
+ { target: { unread: false, state: 'waiting' } },
+ ''
+ )
+ const outer = all.groups[0]
+ expect(outer.children[0].children[0].id).toBe('deep')
+ expect(groupSessionRows(outer).map((row) => row.id)).toEqual(['direct', 'target'])
+ expect(groupSessionCount(outer)).toBe(2)
+ // A nested session still reaches the project header badges.
+ expect(projectSignalCounts(all)).toEqual({ attention: 1, unread: 0, working: 0 })
+
+ // Filtering keeps the ancestors of a match — otherwise the hit is unreachable in the tree.
+ const [filtered] = buildSessionList(proj, null, 'p1', {}, 'needle')
+ expect(filtered.groups[0].id).toBe('outer')
+ expect(filtered.groups[0].children[0].children[0].sessions.map((row) => row.id)).toEqual([
+ 'target'
+ ])
+ })
+
+ it('promotes groups with dangling or cyclic parents to a reachable root', () => {
+ const proj: ProjectInput[] = [
+ {
+ id: 'p1',
+ name: 'Alpha',
+ color: '#111',
+ nodes: [
+ node('dangling', { kind: 'group', parentId: 'missing' }),
+ node('a', { kind: 'group', parentId: 'b' }),
+ node('b', { kind: 'group', parentId: 'a' })
+ ]
+ }
+ ]
+ const [group] = buildSessionList(proj, null, 'p1', {}, '')
+ expect(new Set(group.groups.map((bucket) => bucket.id))).toEqual(
+ new Set(['dangling', 'a', 'b'])
+ )
+ })
+})
+
+describe('sidebar disclosure keys', () => {
+ const proj: ProjectInput[] = [
+ {
+ id: 'p1',
+ name: 'Alpha',
+ color: '#111',
+ nodes: [
+ node('outer', { kind: 'group', title: 'Outer' }),
+ node('inner', { kind: 'group', title: 'Inner', parentId: 'outer' }),
+ node('t1', { parentId: 'inner' })
+ ]
+ }
+ ]
+
+ it('lists a key for the project and for every frame at any depth', () => {
+ const keys = liveCollapseKeys(buildSessionList(proj, null, 'p1', {}, ''))
+ expect(keys).toEqual(
+ new Set(['project:p1', 'project:p1:group:outer', 'project:p1:group:inner'])
+ )
+ })
+
+ it('drops keys whose project or frame is gone, and keeps the key being written', () => {
+ const live = liveCollapseKeys(buildSessionList(proj, null, 'p1', {}, ''))
+ const stored = {
+ 'project:p1': true,
+ 'project:p1:group:inner': true,
+ 'project:p1:group:deleted': true,
+ 'project:closed-long-ago': true
+ }
+ expect(pruneCollapsedItems(stored, live)).toEqual({
+ 'project:p1': true,
+ 'project:p1:group:inner': true
+ })
+ // A filtered tree does not list every frame, so the key being toggled is always kept.
+ expect(pruneCollapsedItems(stored, new Set<string>(), 'project:p1:group:deleted')).toEqual({
+ 'project:p1:group:deleted': true
+ })
+ })
+
+ it('returns the same object when there is nothing to prune (no needless settings write)', () => {
+ const live = liveCollapseKeys(buildSessionList(proj, null, 'p1', {}, ''))
+ const stored = { 'project:p1': true }
+ expect(pruneCollapsedItems(stored, live)).toBe(stored)
+ })
})
describe('projectSignalCounts', () => {
diff --git a/src/renderer/lib/sessionList.ts b/src/renderer/lib/sessionList.ts
index 1cb5a735c..0d7a9ffef 100644
--- a/src/renderer/lib/sessionList.ts
+++ b/src/renderer/lib/sessionList.ts
@@ -33,39 +33,84 @@ const STATE_LABEL: Record<StatusKind, string> = {
idle: 'Idle'
}
+/** Disclosure key for a project row in the sessions tree. */
+export function projectCollapseKey(projectId: string): string {
+ return `project:${projectId}`
+}
+
+/** Disclosure key for a canvas group frame's row, scoped to its project. */
+export function groupCollapseKey(projectId: string, groupId: string): string {
+ return `project:${projectId}:group:${groupId}`
+}
+
/**
- * Whether a project group is collapsed in the sessions sidebar. With `autoCollapse` (the
- * default, `settings.sidebarAutoCollapse`) the default keeps the active project expanded and
- * every other project collapsed (so the list stays uncluttered); with it off, every project
- * defaults to expanded and nothing changes on a project switch. An explicit user toggle,
- * recorded in `overrides` (true = collapsed, false = expanded), always wins over the default.
+ * Whether a project row is collapsed in the sessions sidebar. `settings.sidebarAutoCollapse`
+ * only supplies the DEFAULT for a project the user never toggled: on (the default) keeps the
+ * active project expanded and every other one collapsed, off leaves everything expanded. An
+ * explicit toggle, recorded in `overrides` under `projectCollapseKey` (true = collapsed), always
+ * wins — and since 2026-08 those choices are PERSISTED (`settings.sidebarCollapsedItems`), so a
+ * project switch no longer discards them. Group rows are not defaulted at all: an untouched
+ * frame is expanded, which is why `renderBucket` reads the map directly.
*/
export function isGroupCollapsed(
overrides: Record<string, boolean>,
- projectId: string,
+ key: string,
isActive: boolean,
autoCollapse = true
): boolean {
- if (projectId in overrides) return overrides[projectId]
+ if (key in overrides) return overrides[key]
return autoCollapse ? !isActive : false
}
+/**
+ * Every disclosure key the current tree can address. `settings.sidebarCollapsedItems` is written
+ * to `settings.json`, so without pruning it grows forever: one entry per project and per group
+ * frame that ever existed, kept alive long after the node was deleted or the project closed.
+ */
+export function liveCollapseKeys(groups: SessionGroup[]): Set<string> {
+ const keys = new Set<string>()
+ const walk = (projectId: string, bucket: GroupBucket): void => {
+ keys.add(groupCollapseKey(projectId, bucket.id))
+ bucket.children.forEach((child) => walk(projectId, child))
+ }
+ for (const group of groups) {
+ keys.add(projectCollapseKey(group.projectId))
+ group.groups.forEach((bucket) => walk(group.projectId, bucket))
+ }
+ return keys
+}
+
+/**
+ * Drops disclosure keys that no longer address a live project or frame. Returns the SAME object
+ * when nothing would change, so a no-op toggle never marks settings dirty. `keepKey` is the key
+ * being written right now — it is kept even if the tree is filtered and does not list it.
+ */
+export function pruneCollapsedItems(
+ items: Record<string, boolean>,
+ live: Set<string>,
+ keepKey?: string
+): Record<string, boolean> {
+ const dead = Object.keys(items).filter((key) => key !== keepKey && !live.has(key))
+ if (dead.length === 0) return items
+ const next: Record<string, boolean> = {}
+ for (const [key, value] of Object.entries(items)) {
+ if (key === keepKey || live.has(key)) next[key] = value
+ }
+ return next
+}
+
/** What a left-click on a project header in the sessions sidebar does. */
export type ProjectHeadAction = 'switch' | 'toggle-collapse'
/**
* A project header's click does exactly ONE of two things, and never both.
*
- * - An INACTIVE project **switches** to that project and leaves `overrides` alone. Touching
- * collapse here would be dead-or-wrong under both settings: with `sidebarAutoCollapse` ON
- * the sidebar's own effect wipes every override on the `activeProjectId` change, so any
- * toggle written here is clobbered a tick later (and unnecessary — the newly active project
- * is expanded by default); with it OFF, writing one would discard the user's explicit
- * choice, contradicting the documented "off = switches never touch the user's choices".
+ * - An INACTIVE project **switches** to that project and leaves its disclosure choice alone.
+ * Writing one here would discard the user's explicit choice — collapse choices are persisted
+ * (`settings.sidebarCollapsedItems`), so there is nothing transient to "helpfully" reset, and
+ * a project the user never toggled is expanded by default the moment it becomes active.
* - The ACTIVE project **toggles its own collapse** — the pre-existing behavior of the whole
- * header, kept so the row has no dead zone. It sets a normal override, which is transient
- * under auto-collapse (dropped at the next switch) and sticky without it, exactly like the
- * chevron button.
+ * header, kept so the row has no dead zone. Same persisted write as the chevron button.
*
* The chevron is the escape hatch either way: it toggles collapse on ANY row (it
* stops propagation), so an inactive project can be peeked into without switching.
@@ -84,7 +129,7 @@ export function projectSignalCounts(group: SessionGroup): { attention: number; u
let attention = 0
let unread = 0
let working = 0
- for (const s of [...group.ungrouped, ...group.groups.flatMap((b) => b.sessions)]) {
+ for (const s of [...group.ungrouped, ...group.groups.flatMap(groupSessionRows)]) {
if (s.statusKind === 'attention') attention++
else if (s.unread && s.statusKind !== 'working') unread++
if (s.statusKind === 'working') working++
@@ -134,12 +179,26 @@ export interface SessionRowVM {
usesContext: boolean
}
-/** A canvas group frame and the sessions nested inside it. */
+/** A canvas group frame, the sessions directly inside it, and the frames nested inside it. */
export interface GroupBucket {
id: string
title: string
color: string
sessions: SessionRowVM[]
+ children: GroupBucket[]
+}
+
+/** Every session in this frame's whole subtree, outermost frame first. */
+export function groupSessionRows(group: GroupBucket): SessionRowVM[] {
+ return [...group.sessions, ...group.children.flatMap(groupSessionRows)]
+}
+
+/** How many sessions live in this frame's whole subtree. */
+export function groupSessionCount(group: GroupBucket): number {
+ return (
+ group.sessions.length +
+ group.children.reduce((sum, child) => sum + groupSessionCount(child), 0)
+ )
}
export interface SessionGroup {
@@ -198,21 +257,54 @@ export function buildSessionList(
const isActive = p.id === activeProjectId
const source = isActive && liveActiveNodes ? liveActiveNodes : p.nodes
const groupNodes = source.filter((n) => n.kind === 'group')
- const groupIds = new Set(groupNodes.map((n) => n.id))
+ const groupById = new Map(groupNodes.map((n) => [n.id, n]))
const terminals = source.filter((n) => n.kind === 'terminal')
- const buckets: GroupBucket[] = groupNodes.map((gn) => ({
- id: gn.id,
- title: gn.title,
- color: gn.color,
- sessions: terminals
+ // A frame's parent, but only when that parent is a frame we know AND the chain terminates.
+ // A cyclic parentId (hand-edited project.json, a bad merge) would otherwise recurse forever;
+ // such a frame is treated as a root instead of crashing the sidebar.
+ const parentFor = (group: SessionNodeInput): string | undefined => {
+ if (!group.parentId || !groupById.has(group.parentId) || group.parentId === group.id) {
+ return undefined
+ }
+ const seen = new Set<string>([group.id])
+ let parentId: string | undefined = group.parentId
+ while (parentId) {
+ if (seen.has(parentId)) return undefined
+ seen.add(parentId)
+ parentId = groupById.get(parentId)?.parentId
+ }
+ return group.parentId
+ }
+ const childGroups = new Map<string, SessionNodeInput[]>()
+ for (const group of groupNodes) {
+ const parentId = parentFor(group)
+ if (!parentId) continue
+ const children = childGroups.get(parentId) ?? []
+ children.push(group)
+ childGroups.set(parentId, children)
+ }
+ const buildBucket = (gn: SessionNodeInput): GroupBucket | null => {
+ const sessions = terminals
.filter((n) => n.parentId === gn.id)
.map((n) => toRow(n, statusById[n.id]))
.filter(keep)
- }))
+ const children = (childGroups.get(gn.id) ?? [])
+ .map(buildBucket)
+ .filter((bucket): bucket is GroupBucket => bucket !== null)
+ // While filtering, a frame survives if it matches by NAME or still holds anything;
+ // unfiltered, empty frames stay so they remain visible drop targets.
+ const groupMatches = !!needle && gn.title.toLowerCase().includes(needle)
+ if (needle && !groupMatches && sessions.length === 0 && children.length === 0) return null
+ return { id: gn.id, title: gn.title, color: gn.color, sessions, children }
+ }
+ const buckets = groupNodes
+ .filter((group) => !parentFor(group))
+ .map(buildBucket)
+ .filter((bucket): bucket is GroupBucket => bucket !== null)
const ungrouped = terminals
- .filter((n) => !n.parentId || !groupIds.has(n.parentId))
+ .filter((n) => !n.parentId || !groupById.has(n.parentId))
.map((n) => toRow(n, statusById[n.id]))
.filter(keep)
@@ -222,9 +314,7 @@ export function buildSessionList(
projectColor: p.color,
cwd: p.cwd,
isActive,
- // When filtering, hide groups whose sessions all filtered out; otherwise keep empty
- // groups so they remain visible drop targets.
- groups: needle ? buckets.filter((b) => b.sessions.length > 0) : buckets,
+ groups: buckets,
ungrouped
}
})
diff --git a/src/renderer/nodes/TerminalNode.tsx b/src/renderer/nodes/TerminalNode.tsx
index c0ad36739..f3c8176b6 100644
--- a/src/renderer/nodes/TerminalNode.tsx
+++ b/src/renderer/nodes/TerminalNode.tsx
@@ -1154,18 +1154,30 @@ export function TerminalNode({
editingTitleRef.current = editingTitle
titleRef.current = data.title as string
// "Move into worktree" affordance: shown only when this terminal is a child of a group that
- // is bound to a worktree AND its current cwd differs from that worktree path (i.e. it's still
- // running in the old folder). Reads the parent group from React Flow state (single source of
- // truth); `parentId` is set by the group reparenting transforms.
+ // or one of its ancestor groups is bound to a worktree AND its current cwd differs from that
+ // worktree path (i.e. it's still running in the old folder). Reads the group chain from React
+ // Flow state (single source of truth); `parentId` is set by the group reparenting transforms.
// A STALE group (its worktree directory was deleted outside the app) must NOT offer the move:
// "move" destroys this node's tmux session — killing whatever is running in it — and respawns it
// in the worktree path, which no longer exists. pty-manager would silently fall back to $HOME and
// `data.cwd` would persist the dead path forever, which not even Unbind undoes. The chip already
// says "· missing"; the ↪ must agree with it.
- const parentWtPath = parentId
- ? ((getNode(parentId) as CanvasNode | undefined)?.data.worktree?.path as string | undefined)
- : undefined
- const parentWtStale = useWorktrees((s) => (parentId ? s.staleGroupIds.includes(parentId) : false))
+ const parentWorktree = (() => {
+ const seen = new Set<string>()
+ let groupId = parentId
+ while (groupId && !seen.has(groupId)) {
+ seen.add(groupId)
+ const group = getNode(groupId) as CanvasNode | undefined
+ const path = group?.data.worktree?.path as string | undefined
+ if (path) return { groupId, path }
+ groupId = group?.parentId
+ }
+ return undefined
+ })()
+ const parentWtPath = parentWorktree?.path
+ const parentWtStale = useWorktrees((s) =>
+ parentWorktree ? s.staleGroupIds.includes(parentWorktree.groupId) : false
+ )
// …and a session that runs on ANOTHER MACHINE must not offer it either. Worktrees are local-only
// in v1, so ↪ would end this node's REMOTE tmux session and respawn it in a local path that does
// not exist on the host. Both halves of "remote" are asked: the project (its terminals and its git
diff --git a/src/renderer/state/projects.sessions.test.ts b/src/renderer/state/projects.sessions.test.ts
index dd4bf80c3..df2614484 100644
--- a/src/renderer/state/projects.sessions.test.ts
+++ b/src/renderer/state/projects.sessions.test.ts
@@ -108,6 +108,33 @@ describe('moveNodeToGroup', () => {
useProjects.getState().moveNodeToGroup('p1', 'nope', 'g1')
expect(useProjects.getState().getProject('p1')!.nodes).toBe(before)
})
+
+ it('moves nested group subtrees and rejects a cycle', () => {
+ const outer = group('outer', 100, 80)
+ const inner = { ...group('inner', 30, 40), parentId: 'outer' }
+ const target = group('target', 500, 200)
+ useProjects.setState({
+ projects: [
+ {
+ id: 'p1',
+ name: 'P1',
+ color: '#111',
+ viewport: { x: 0, y: 0, zoom: 1 },
+ nodes: [outer, inner, target]
+ }
+ ],
+ activeProjectId: 'p1'
+ })
+ useProjects.getState().moveNodeToGroup('p1', 'inner', 'target')
+ let nodes = useProjects.getState().getProject('p1')!.nodes
+ expect(nodes.find((node) => node.id === 'inner')).toMatchObject({
+ parentId: 'target',
+ position: { x: -370, y: -80 }
+ })
+ useProjects.getState().moveNodeToGroup('p1', 'target', 'inner')
+ nodes = useProjects.getState().getProject('p1')!.nodes
+ expect(nodes.find((node) => node.id === 'target')!.parentId).toBeUndefined()
+ })
})
describe('reorderNode', () => {
diff --git a/src/renderer/state/projects.ts b/src/renderer/state/projects.ts
index dade9d055..cdd26d2ec 100644
--- a/src/renderer/state/projects.ts
+++ b/src/renderer/state/projects.ts
@@ -9,7 +9,7 @@ import type {
Viewport,
Workspace
} from '@shared/types'
-import { applyCanvasMutation, createProject } from './workspace'
+import { applyCanvasMutation, createProject, reorderGroupWithinParent } from './workspace'
interface ProjectsState {
projects: Project[]
@@ -100,6 +100,13 @@ interface ProjectsState {
/** Reorders a node to sit immediately before another (sidebar order = array order),
* joining the target's container if they differ. */
reorderNode(projectId: string, draggedId: string, beforeId: string): void
+ /** Reorders a group subtree among its siblings without changing its parent. */
+ reorderGroup(
+ projectId: string,
+ draggedId: string,
+ parentId: string | null,
+ beforeId: string | null
+ ): void
/** Reorders a project to sit immediately before another (tab bar + sidebar order = array
* order), or to the end with beforeId = null. Closed projects keep their slots. */
reorderProject(draggedId: string, beforeId: string | null): void
@@ -114,26 +121,60 @@ interface ProjectsState {
toWorkspace(): Workspace
}
+/** A persisted node's position in ROOT space: its own plus every ancestor frame's origin. */
+function rootStatePosition(
+ node: CanvasNodeState,
+ nodes: 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 }
+}
+
+function stateIsDescendant(
+ nodes: CanvasNodeState[],
+ candidateId: string,
+ ancestorId: string
+): boolean {
+ const byId = new Map(nodes.map((node) => [node.id, node]))
+ const seen = new Set<string>()
+ let current = byId.get(candidateId)
+ while (current?.parentId && !seen.has(current.parentId)) {
+ if (current.parentId === ancestorId) return true
+ seen.add(current.parentId)
+ current = byId.get(current.parentId)
+ }
+ return false
+}
+
/** Returns `node` repositioned for a new parent (groupId, or null for top level), keeping its
- * on-canvas position fixed (one-level absolute↔relative). Unchanged if the target is not a
+ * root-space position fixed across arbitrary nesting. Unchanged if the target is not a
* group. `extent` is omitted — nodeStatesToFlow re-derives it from parentId on load. */
function repositionState(
node: CanvasNodeState,
groupId: string | null,
nodes: CanvasNodeState[]
): CanvasNodeState {
- const oldParent = node.parentId ? nodes.find((n) => n.id === node.parentId) : undefined
- const abs = {
- x: node.position.x + (oldParent?.position.x ?? 0),
- y: node.position.y + (oldParent?.position.y ?? 0)
- }
+ const abs = rootStatePosition(node, nodes)
if (groupId === null) return { ...node, parentId: undefined, position: abs }
const group = nodes.find((n) => n.id === groupId)
if (!group || group.kind !== 'group') return node
+ const groupAbs = rootStatePosition(group, nodes)
return {
...node,
parentId: group.id,
- position: { x: abs.x - group.position.x, y: abs.y - group.position.y }
+ position: { x: abs.x - groupAbs.x, y: abs.y - groupAbs.y }
}
}
@@ -338,8 +379,12 @@ export const useProjects = create<ProjectsState>((set, get) => ({
set((s) => ({
projects: mapProjectNodes(s.projects, projectId, (nodes) => {
const node = nodes.find((n) => n.id === nodeId)
- if (!node || node.kind === 'group') return nodes
+ if (!node) return nodes
if ((node.parentId ?? null) === groupId) return nodes
+ // A frame may be moved into another frame, but never into itself or its own subtree.
+ if (groupId === nodeId || (groupId && stateIsDescendant(nodes, groupId, nodeId))) {
+ return nodes
+ }
const next = repositionState(node, groupId, nodes)
if (next === node) return nodes // target group missing / not a group
return nodes.map((n) => (n.id === nodeId ? next : n))
@@ -366,6 +411,19 @@ export const useProjects = create<ProjectsState>((set, get) => ({
}))
},
+ reorderGroup(projectId, draggedId, parentId, beforeId) {
+ set((s) => ({
+ projects: mapProjectNodes(s.projects, projectId, (nodes) => {
+ const dragged = nodes.find((node) => node.id === draggedId)
+ const before = beforeId ? nodes.find((node) => node.id === beforeId) : undefined
+ if (!dragged || dragged.kind !== 'group' || (beforeId && before?.kind !== 'group')) {
+ return nodes
+ }
+ return reorderGroupWithinParent(nodes, draggedId, parentId, beforeId)
+ })
+ }))
+ },
+
reorderProject(draggedId, beforeId) {
set((s) => {
if (draggedId === beforeId) return s
diff --git a/src/renderer/state/workspace.test.ts b/src/renderer/state/workspace.test.ts
index 33cb7cc0b..aacc02f09 100644
--- a/src/renderer/state/workspace.test.ts
+++ b/src/renderer/state/workspace.test.ts
@@ -1,5 +1,6 @@
import { describe, it, expect } from 'vitest'
import {
+ addSelectionToGroup,
alignNodes,
arrangeNodes,
commonParentId,
@@ -11,9 +12,11 @@ import {
groupSelectedNodes,
nodeStatesToFlow,
nodeSshFor,
+ reorderGroupWithinParent,
reorderNodeBefore,
reparentNode,
resolveNewNodeAccount,
+ selectedRootIds,
ungroupNodes
} from './workspace'
import type { CanvasNode } from './workspace'
@@ -29,14 +32,15 @@ const term = (id: string, pos: { x: number; y: number }, parentId?: string): Can
...(parentId ? { parentId, extent: 'parent' as const } : {})
}) as unknown as CanvasNode
-const grp = (id: string, pos: { x: number; y: number }): CanvasNode =>
+const grp = (id: string, pos: { x: number; y: number }, parentId?: string): CanvasNode =>
({
id,
type: 'group',
position: pos,
width: 400,
height: 300,
- data: { title: id, color: '#fff', group: null }
+ data: { title: id, color: '#fff', group: null },
+ ...(parentId ? { parentId, extent: 'parent' as const } : {})
}) as unknown as CanvasNode
describe('reparentNode', () => {
@@ -74,6 +78,87 @@ describe('reparentNode', () => {
expect(reparentNode(nodes, 'nope', 'g1')).toBe(nodes)
expect(reparentNode(nodes, 't1', 't1')).toBe(nodes) // target is a terminal, not a group
})
+
+ it('moves a whole group subtree between nested containers without moving it in root space', () => {
+ const nodes = [
+ grp('outer', { x: 100, y: 80 }),
+ grp('inner', { x: 30, y: 40 }, 'outer'),
+ term('leaf', { x: 10, y: 12 }, 'inner'),
+ grp('target', { x: 500, y: 200 })
+ ]
+ const out = reparentNode(nodes, 'inner', 'target')
+ const inner = out.find((node) => node.id === 'inner')!
+ expect(inner.parentId).toBe('target')
+ expect(inner.position).toEqual({ x: -370, y: -80 })
+ expect(out.find((node) => node.id === 'leaf')!.position).toEqual({ x: 10, y: 12 })
+ expect(out.findIndex((node) => node.id === 'target')).toBeLessThan(
+ out.findIndex((node) => node.id === 'inner')
+ )
+ })
+
+ it('rejects parenting a group into itself or one of its descendants', () => {
+ const nodes = [grp('outer', { x: 0, y: 0 }), grp('inner', { x: 20, y: 20 }, 'outer')]
+ expect(reparentNode(nodes, 'outer', 'outer')).toBe(nodes)
+ expect(reparentNode(nodes, 'outer', 'inner')).toBe(nodes)
+ })
+})
+
+describe('addSelectionToGroup', () => {
+ it('adds selected sibling objects to the already selected group', () => {
+ const nodes = [
+ grp('target', { x: 100, y: 80 }),
+ term('a', { x: 500, y: 200 }),
+ term('b', { x: 700, y: 300 })
+ ]
+ const out = addSelectionToGroup(nodes, ['target', 'a', 'b'], 'target')
+ expect(out.find((node) => node.id === 'a')!.parentId).toBe('target')
+ expect(out.find((node) => node.id === 'b')!.parentId).toBe('target')
+ // Root-space positions are unchanged: the frame was re-fitted around its new children, so
+ // frame origin + child offset still lands on the node's old absolute position.
+ const target = out.find((node) => node.id === 'target')!
+ const a = out.find((node) => node.id === 'a')!
+ expect(target.position.x + a.position.x).toBe(500)
+ expect(target.position.y + a.position.y).toBe(200)
+ })
+
+ it('moves only a selected subtree root and rejects cycles through reparenting', () => {
+ const nodes = [
+ grp('target', { x: 500, y: 200 }),
+ grp('outer', { x: 100, y: 80 }),
+ term('leaf', { x: 10, y: 12 }, 'outer')
+ ]
+ const out = addSelectionToGroup(nodes, ['target', 'outer', 'leaf'], 'target')
+ expect(out.find((node) => node.id === 'outer')!.parentId).toBe('target')
+ expect(out.find((node) => node.id === 'leaf')!.parentId).toBe('outer')
+ const nested = [grp('outer', { x: 0, y: 0 }), grp('target', { x: 20, y: 20 }, 'outer')]
+ expect(addSelectionToGroup(nested, ['outer', 'target'], 'target')).toBe(nested)
+ })
+
+ it('is a no-op without a valid target or movable selected object', () => {
+ const nodes = [grp('target', { x: 0, y: 0 }), term('inside', { x: 10, y: 10 }, 'target')]
+ expect(addSelectionToGroup(nodes, ['target', 'inside'], 'target')).toBe(nodes)
+ expect(addSelectionToGroup(nodes, ['target'], 'missing')).toBe(nodes)
+ })
+})
+
+describe('selectedRootIds', () => {
+ it('normalizes box-selected group subtrees to their selected roots', () => {
+ const nodes = [
+ grp('outer', { x: 0, y: 0 }),
+ grp('inner', { x: 10, y: 10 }, 'outer'),
+ term('leaf', { x: 5, y: 5 }, 'inner'),
+ grp('sibling', { x: 500, y: 0 })
+ ]
+ expect(selectedRootIds(nodes, ['outer', 'inner', 'leaf', 'sibling'])).toEqual([
+ 'outer',
+ 'sibling'
+ ])
+ })
+
+ it('drops unknown ids and preserves independent selection order', () => {
+ const nodes = [term('a', { x: 0, y: 0 }), term('b', { x: 10, y: 10 })]
+ expect(selectedRootIds(nodes, ['missing', 'b', 'a'])).toEqual(['b', 'a'])
+ })
})
describe('commonParentId', () => {
@@ -188,10 +273,90 @@ describe('groupSelectedNodes', () => {
expect(out.find((n) => n.id === 't1')!.parentId).toBe(out[0].id)
})
- it('skips already-grouped children and group frames; all-skipped is a no-op', () => {
+ it('refuses an ancestor together with its descendant', () => {
const nodes = [grp('g1', { x: 0, y: 0 }), term('t1', { x: 10, y: 10 }, 'g1')]
expect(groupSelectedNodes(nodes, ['g1', 't1'], 1)).toBe(nodes)
})
+
+ it('refuses members that live in different containers', () => {
+ const nodes = [
+ grp('g1', { x: 0, y: 0 }),
+ term('inside', { x: 10, y: 10 }, 'g1'),
+ term('loose', { x: 900, y: 900 })
+ ]
+ expect(groupSelectedNodes(nodes, ['inside', 'loose'], 1)).toBe(nodes)
+ })
+
+ it('wraps sibling groups in a nested group while preserving root-space positions', () => {
+ const nodes = [grp('a', { x: 100, y: 120 }), grp('b', { x: 600, y: 180 })]
+ const out = groupSelectedNodes(nodes, ['a', 'b'], 2)
+ const wrapper = out.find((node) => !nodes.some((old) => old.id === node.id))!
+ const a = out.find((node) => node.id === 'a')!
+ expect(wrapper.type).toBe('group')
+ expect(a.parentId).toBe(wrapper.id)
+ expect(wrapper.position.x + a.position.x).toBe(100)
+ expect(wrapper.position.y + a.position.y).toBe(120)
+ expect(out.indexOf(wrapper)).toBeLessThan(out.indexOf(a))
+ })
+
+ it("creates the wrapper inside the siblings' existing parent", () => {
+ const nodes = [
+ grp('outer', { x: 100, y: 80 }),
+ grp('a', { x: 20, y: 30 }, 'outer'),
+ grp('b', { x: 500, y: 60 }, 'outer')
+ ]
+ const out = groupSelectedNodes(nodes, ['a', 'b'], 3)
+ const wrapper = out.find((node) => !nodes.some((old) => old.id === node.id))!
+ const outer = out.find((node) => node.id === 'outer')!
+ const a = out.find((node) => node.id === 'a')!
+ expect(wrapper.parentId).toBe('outer')
+ expect(a.parentId).toBe(wrapper.id)
+ // Root space is unchanged: 'a' sat at (120, 110) before and must still sit there.
+ expect(outer.position.x + wrapper.position.x + a.position.x).toBe(120)
+ expect(outer.position.y + wrapper.position.y + a.position.y).toBe(110)
+ })
+
+ /**
+ * The pure arithmetic above can be perfectly right while the canvas is wrong: a wrapper is
+ * created at (minX - 28, minY - 62) RELATIVE to its new parent — routinely negative — and
+ * carries `extent: 'parent'`. React Flow then clamps it into `[0, parentSize - wrapperSize]`,
+ * which for a wrapper bigger than its parent is an inverted range: the frame snaps hundreds of
+ * px away and drags the whole wrapped subtree with it. So assert the FRAME FITS, not just that
+ * the offsets add up. Fails without the ancestor re-fit.
+ */
+ it('grows the parent frame so the new wrapper fits inside it', () => {
+ const nodes = [
+ grp('outer', { x: 100, y: 80 }),
+ grp('a', { x: 20, y: 30 }, 'outer'),
+ grp('b', { x: 500, y: 60 }, 'outer')
+ ]
+ const out = groupSelectedNodes(nodes, ['a', 'b'], 3)
+ const outer = out.find((node) => node.id === 'outer')!
+ const wrapper = out.find((node) => !nodes.some((old) => old.id === node.id))!
+ expect(wrapper.position.x).toBeGreaterThanOrEqual(0)
+ expect(wrapper.position.y).toBeGreaterThanOrEqual(0)
+ expect(wrapper.position.x + (wrapper.width as number)).toBeLessThanOrEqual(
+ outer.width as number
+ )
+ expect(wrapper.position.y + (wrapper.height as number)).toBeLessThanOrEqual(
+ outer.height as number
+ )
+ })
+
+ it('grows every ancestor frame, not just the immediate parent', () => {
+ const nodes = [
+ grp('root', { x: 0, y: 0 }),
+ grp('outer', { x: 10, y: 10 }, 'root'),
+ grp('a', { x: 20, y: 30 }, 'outer'),
+ grp('b', { x: 500, y: 60 }, 'outer')
+ ]
+ const out = groupSelectedNodes(nodes, ['a', 'b'], 4)
+ const root = out.find((node) => node.id === 'root')!
+ const outer = out.find((node) => node.id === 'outer')!
+ expect(outer.position.x).toBeGreaterThanOrEqual(0)
+ expect(outer.position.x + (outer.width as number)).toBeLessThanOrEqual(root.width as number)
+ expect(outer.position.y + (outer.height as number)).toBeLessThanOrEqual(root.height as number)
+ })
})
describe('ungroupNodes', () => {
@@ -213,12 +378,89 @@ describe('ungroupNodes', () => {
expect(out.find((n) => n.id === 't2')!.position).toEqual({ x: 500, y: 300 })
})
+ it("promotes direct children into the removed group's parent without moving them", () => {
+ const nodes = [
+ grp('outer', { x: 100, y: 80 }),
+ grp('inner', { x: 30, y: 40 }, 'outer'),
+ term('leaf', { x: 10, y: 12 }, 'inner')
+ ]
+ const out = ungroupNodes(nodes, 'inner')
+ const leaf = out.find((node) => node.id === 'leaf')!
+ expect(leaf.parentId).toBe('outer')
+ expect(leaf.position).toEqual({ x: 40, y: 52 })
+ })
+
it('is a no-op when the group is missing', () => {
const nodes = [term('t1', { x: 0, y: 0 })]
expect(ungroupNodes(nodes, 'nope')).toBe(nodes)
})
})
+describe('nested group persistence order', () => {
+ it('hydrates every parent group before its descendants even from reversed persisted order', () => {
+ const live = [
+ grp('outer', { x: 100, y: 80 }),
+ grp('inner', { x: 30, y: 40 }, 'outer'),
+ term('leaf', { x: 10, y: 12 }, 'inner')
+ ]
+ const hydrated = nodeStatesToFlow(flowToNodeStates(live).reverse())
+ expect(hydrated.findIndex((node) => node.id === 'outer')).toBeLessThan(
+ hydrated.findIndex((node) => node.id === 'inner')
+ )
+ expect(hydrated.findIndex((node) => node.id === 'inner')).toBeLessThan(
+ hydrated.findIndex((node) => node.id === 'leaf')
+ )
+ })
+
+ it('hydrates groups with the label-only drag handle', () => {
+ const [group] = nodeStatesToFlow(flowToNodeStates([grp('outer', { x: 0, y: 0 })]))
+ expect(group.dragHandle).toBe('.group-node__label')
+ })
+})
+
+describe('reorderGroupWithinParent', () => {
+ it('moves a nested group subtree before a sibling without changing geometry or parenting', () => {
+ const nodes = [
+ grp('outer', { x: 0, y: 0 }),
+ grp('a', { x: 10, y: 10 }, 'outer'),
+ grp('a-child', { x: 5, y: 5 }, 'a'),
+ grp('b', { x: 20, y: 20 }, 'outer'),
+ term('inside-a', { x: 2, y: 3 }, 'a')
+ ]
+ const out = reorderGroupWithinParent(nodes, 'b', 'outer', 'a')
+ expect(out.map((node) => node.id)).toEqual(['outer', 'b', 'a', 'a-child', 'inside-a'])
+ expect(out.find((node) => node.id === 'b')).toMatchObject({
+ parentId: 'outer',
+ position: { x: 20, y: 20 }
+ })
+ })
+
+ it('appends a whole group subtree after its last sibling', () => {
+ const nodes = [
+ grp('a', { x: 0, y: 0 }),
+ grp('a-child', { x: 0, y: 0 }, 'a'),
+ grp('b', { x: 0, y: 0 }),
+ term('inside-a', { x: 0, y: 0 }, 'a')
+ ]
+ expect(reorderGroupWithinParent(nodes, 'a', null, null).map((node) => node.id)).toEqual([
+ 'b',
+ 'a',
+ 'a-child',
+ 'inside-a'
+ ])
+ })
+
+ it('rejects cross-parent and invalid-target reorders', () => {
+ const nodes = [
+ grp('outer', { x: 0, y: 0 }),
+ grp('a', { x: 0, y: 0 }, 'outer'),
+ grp('b', { x: 0, y: 0 })
+ ]
+ expect(reorderGroupWithinParent(nodes, 'a', null, 'b')).toBe(nodes)
+ expect(reorderGroupWithinParent(nodes, 'a', 'outer', 'missing')).toBe(nodes)
+ })
+})
+
describe('reorderNodeBefore', () => {
const ids = (out: CanvasNode[]): string[] => out.filter((n) => n.type !== 'group').map((n) => n.id)
diff --git a/src/renderer/state/workspace.ts b/src/renderer/state/workspace.ts
index f84f96e57..ad07b1bd5 100644
--- a/src/renderer/state/workspace.ts
+++ b/src/renderer/state/workspace.ts
@@ -682,6 +682,10 @@ export function createGroupNode(
return {
id: nextId('group'),
type: 'group',
+ // A frame is a background container, not a giant drag target: only its label pill drags it,
+ // so a click on the body reaches the pane (pan / rubber-band) and a NESTED frame's body is
+ // not stolen by its ancestor. Mirrored in `nodeStatesToFlow` for persisted frames.
+ dragHandle: '.group-node__label',
position,
width: size.width,
height: size.height,
@@ -817,9 +821,118 @@ export function alignNodes(nodes: CanvasNode[], ids: string[], edge: AlignEdge):
}
/**
- * Wraps the given top-level node ids in a new group frame: creates the group sized to
- * enclose them and reparents the children (positions become relative to the group).
- * Returns a new nodes array with the group placed first (React Flow needs parents first).
+ * Group (parent) nodes must precede their descendants in the array (React Flow requirement).
+ * With nesting the old "all groups, then everything else" split is not enough — a child frame
+ * could still be emitted before its parent — so groups are emitted depth-first from the root.
+ *
+ * This order is also the DOWNGRADE contract: `flowToNodeStates` preserves array order, and an
+ * older build's flat `kind === 'group'` sort returns 0 for two groups, which a stable sort
+ * (ES2019+) leaves alone. So a nested tree written by this build still hydrates parent-first,
+ * and therefore still RENDERS, on a build that predates nesting.
+ */
+function groupsFirst(nodes: CanvasNode[]): CanvasNode[] {
+ const byId = new Map(nodes.map((node) => [node.id, node]))
+ const emitted = new Set<string>()
+ const visiting = new Set<string>()
+ const groups: CanvasNode[] = []
+ const emitGroup = (node: CanvasNode): void => {
+ if (emitted.has(node.id) || node.type !== 'group') return
+ if (visiting.has(node.id)) return // cyclic parentId: emit once, don't recurse forever
+ visiting.add(node.id)
+ const parent = node.parentId ? byId.get(node.parentId) : undefined
+ if (parent?.type === 'group') emitGroup(parent)
+ visiting.delete(node.id)
+ if (!emitted.has(node.id)) {
+ emitted.add(node.id)
+ groups.push(node)
+ }
+ }
+ nodes.forEach(emitGroup)
+ return [...groups, ...nodes.filter((node) => node.type !== 'group')]
+}
+
+/** A node's position in ROOT space: its own position plus every ancestor frame's origin. */
+function rootPosition(node: CanvasNode, nodes: CanvasNode[]): { 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 }
+}
+
+function isDescendant(nodes: CanvasNode[], candidateId: string, ancestorId: string): boolean {
+ const byId = new Map(nodes.map((node) => [node.id, node]))
+ const seen = new Set<string>()
+ let current = byId.get(candidateId)
+ while (current?.parentId && !seen.has(current.parentId)) {
+ if (current.parentId === ancestorId) return true
+ seen.add(current.parentId)
+ current = byId.get(current.parentId)
+ }
+ return false
+}
+
+/**
+ * Returns only the selected subtree ROOTS. Box-selection routinely catches a frame together with
+ * its children; a structural action must move that subtree ONCE, through its selected ancestor,
+ * or the children are torn out of the frame that is being moved.
+ */
+export function selectedRootIds(nodes: CanvasNode[], ids: string[]): string[] {
+ const selected = new Set(ids)
+ const byId = new Map(nodes.map((node) => [node.id, node]))
+ return ids.filter((id) => {
+ let node = byId.get(id)
+ if (!node) return false
+ const seen = new Set<string>()
+ while (node.parentId && !seen.has(node.parentId)) {
+ if (selected.has(node.parentId)) return false
+ seen.add(node.parentId)
+ const parent = byId.get(node.parentId)
+ if (!parent) break
+ node = parent
+ }
+ return true
+ })
+}
+
+/**
+ * Grows every ancestor frame of `groupId` to hug its children again, innermost first. A frame
+ * that gained a child bigger than itself must be re-fitted BEFORE its own parent is, or the
+ * parent is fitted around a size that is about to change.
+ */
+function fitAncestorChain(nodes: CanvasNode[], groupId: string | undefined): CanvasNode[] {
+ let next = nodes
+ const seen = new Set<string>()
+ let currentId = groupId
+ while (currentId && !seen.has(currentId)) {
+ seen.add(currentId)
+ next = fitGroupToChildren(next, currentId)
+ currentId = next.find((n) => n.id === currentId)?.parentId
+ }
+ return next
+}
+
+/**
+ * Wraps nodes that share ONE container in a new group frame. The members may themselves be
+ * frames, so this is how a nested tree is built. The frame is created beside its members inside
+ * their current parent and every root-space position stays fixed. Mixed containers and
+ * ancestor+descendant selections are refused (their positions are not comparable, and the
+ * descendant would be torn out of the ancestor being wrapped).
+ *
+ * When the members live inside a parent frame, that parent (and its own ancestors) are re-fitted
+ * around the new wrapper. Without this the wrapper is created at `(minX - 28, minY - 62)` — often
+ * NEGATIVE — inside a parent that is by construction too small to hold it, and `extent: 'parent'`
+ * makes React Flow clamp it to `parentSize - wrapperSize`, i.e. hundreds of px off, dragging the
+ * whole wrapped subtree with it. Same trap `addGrouped` documents in Canvas.
*/
export function groupSelectedNodes(
nodes: CanvasNode[],
@@ -827,8 +940,17 @@ export function groupSelectedNodes(
groupIndex: number
): CanvasNode[] {
const set = new Set(ids)
- const members = nodes.filter((n) => set.has(n.id) && !n.parentId && n.type !== 'group')
- if (members.length === 0) return nodes
+ const members = nodes.filter((n) => set.has(n.id))
+ if (members.length === 0 || new Set(members.map((n) => n.parentId ?? null)).size !== 1) {
+ return nodes
+ }
+ if (
+ members.some((member) =>
+ members.some((other) => other.id !== member.id && isDescendant(nodes, other.id, member.id))
+ )
+ ) {
+ return nodes
+ }
const minX = Math.min(...members.map((n) => n.position.x))
const minY = Math.min(...members.map((n) => n.position.y))
@@ -842,9 +964,14 @@ export function groupSelectedNodes(
{ width: maxX - minX + GROUP_PAD * 2, height: maxY - minY + GROUP_PAD * 2 + GROUP_HEADER },
groupIndex
)
+ const parentId = members[0].parentId
+ if (parentId) {
+ group.parentId = parentId
+ group.extent = 'parent'
+ }
const updated = nodes.map((n) =>
- set.has(n.id) && !n.parentId && n.type !== 'group'
+ set.has(n.id)
? {
...n,
parentId: group.id,
@@ -854,7 +981,7 @@ export function groupSelectedNodes(
}
: n
)
- return [group, ...updated]
+ return fitAncestorChain(groupsFirst([group, ...updated]), parentId)
}
/** Returns a copy of a node with a fresh id, offset position, and top-level placement. */
@@ -906,83 +1033,143 @@ export function fitGroupToChildren(nodes: CanvasNode[], groupId: string): Canvas
})
}
-/** Removes a group frame and restores its children to absolute positions. */
-export function ungroupNodes(nodes: CanvasNode[], groupId: string): CanvasNode[] {
- const group = nodes.find((n) => n.id === groupId)
- if (!group) return nodes
- return nodes
- .filter((n) => n.id !== groupId)
- .map((n) =>
- n.parentId === groupId
- ? {
- ...n,
- parentId: undefined,
- extent: undefined,
- position: { x: n.position.x + group.position.x, y: n.position.y + group.position.y }
- }
- : n
- )
-}
-
/**
- * Moves a node into an existing group frame (`groupId` set) or out to the top level
- * (`groupId` null), keeping its on-canvas position fixed by converting between absolute and
- * group-relative coordinates (one level of nesting). Returns a new array with group nodes kept
- * before their children (React Flow requires parents first). No-op when the node is missing or
- * is itself a group, when it already has the requested parent, or when `groupId` is not a group.
+ * Removes a group frame, promoting its DIRECT children into the frame's own parent (the top
+ * level for an unnested frame) without moving them on canvas. A nested frame's children land in
+ * the grandparent, not at the root — sending them to the root would move them by the whole
+ * ancestor offset.
*/
-/** Group (parent) nodes must precede their children in the array (React Flow requirement). */
-function groupsFirst(nodes: CanvasNode[]): CanvasNode[] {
- return [...nodes.filter((n) => n.type === 'group'), ...nodes.filter((n) => n.type !== 'group')]
+export function ungroupNodes(nodes: CanvasNode[], groupId: string): CanvasNode[] {
+ const group = nodes.find((n) => n.id === groupId)
+ if (!group || group.type !== 'group') return nodes
+ const parentId = group.parentId ?? null
+ const moved = nodes.map((node) =>
+ node.parentId === groupId ? repositionForParent(node, parentId, nodes) : node
+ )
+ return groupsFirst(moved.filter((node) => node.id !== groupId))
}
/**
* Returns `node` repositioned for a new parent (`targetParentId`, or null for top level),
- * keeping its on-canvas position fixed via absolute↔relative conversion (one level). Returns
- * the node unchanged if the target group is missing or not a group.
+ * keeping its on-canvas position fixed via root↔relative conversion across arbitrary nesting
+ * (the old math added ONE parent's origin, which is wrong the moment frames nest). Returns the
+ * node unchanged if the target group is missing or not a group.
*/
function repositionForParent(
node: CanvasNode,
targetParentId: string | null,
nodes: CanvasNode[]
): CanvasNode {
- const oldParent = node.parentId ? nodes.find((n) => n.id === node.parentId) : undefined
- const abs = {
- x: node.position.x + (oldParent?.position.x ?? 0),
- y: node.position.y + (oldParent?.position.y ?? 0)
- }
+ const abs = rootPosition(node, nodes)
if (targetParentId === null) {
return { ...node, parentId: undefined, extent: undefined, position: abs }
}
const group = nodes.find((n) => n.id === targetParentId)
if (!group || group.type !== 'group') return node
+ const groupAbs = rootPosition(group, nodes)
return {
...node,
parentId: group.id,
extent: 'parent' as const,
- position: { x: abs.x - group.position.x, y: abs.y - group.position.y }
+ position: { x: abs.x - groupAbs.x, y: abs.y - groupAbs.y }
}
}
+/**
+ * Moves a node — or a whole group subtree — into an existing frame (`groupId` set) or out to the
+ * top level (`groupId` null), keeping its root-space position fixed. Returns a new array with
+ * frames kept before their descendants (React Flow requires parents first). No-op when the node
+ * is missing, it already has the requested parent, the target is not a group, or the move would
+ * create a cycle (a frame cannot be parented into itself or into one of its own descendants).
+ */
export function reparentNode(
nodes: CanvasNode[],
nodeId: string,
groupId: string | null
): CanvasNode[] {
const node = nodes.find((n) => n.id === nodeId)
- if (!node || node.type === 'group') return nodes
+ if (!node) return nodes
if ((node.parentId ?? null) === groupId) return nodes
+ if (groupId === nodeId || (groupId && isDescendant(nodes, groupId, nodeId))) return nodes
const updated = repositionForParent(node, groupId, nodes)
if (updated === node) return nodes // target group missing / not a group
return groupsFirst(nodes.map((n) => (n.id === nodeId ? updated : n)))
}
+/**
+ * Adds the selected objects to an existing frame. Only selected subtree ROOTS move — when a
+ * frame and one of its children are both selected, the child travels inside its frame rather
+ * than being torn out of it.
+ */
+export function addSelectionToGroup(
+ nodes: CanvasNode[],
+ selectedIds: string[],
+ groupId: string
+): CanvasNode[] {
+ if (!nodes.some((node) => node.id === groupId && node.type === 'group')) return nodes
+ const selected = new Set(selectedIds)
+ const byId = new Map(nodes.map((node) => [node.id, node]))
+ const roots = nodes.filter((node) => {
+ if (node.id === groupId || !selected.has(node.id)) return false
+ const seen = new Set<string>()
+ let parentId = node.parentId
+ while (parentId && !seen.has(parentId)) {
+ if (selected.has(parentId)) return false
+ seen.add(parentId)
+ parentId = byId.get(parentId)?.parentId
+ }
+ return true
+ })
+ let next = nodes
+ for (const root of roots) next = reparentNode(next, root.id, groupId)
+ return next === nodes ? nodes : fitAncestorChain(next, groupId)
+}
+
+/**
+ * Reorders one group subtree among its siblings without changing its parent or its geometry.
+ * `beforeId = null` appends it after the last sibling. Descendants travel with their frame so
+ * the persisted parent-before-child order stays coherent.
+ */
+export function reorderGroupWithinParent<T extends { id: string; parentId?: string }>(
+ nodes: T[],
+ draggedId: string,
+ parentId: string | null,
+ beforeId: string | null
+): T[] {
+ if (draggedId === beforeId) return nodes
+ const dragged = nodes.find((node) => node.id === draggedId)
+ if (!dragged || (dragged.parentId ?? null) !== parentId) return nodes
+ const before = beforeId ? nodes.find((node) => node.id === beforeId) : undefined
+ if (beforeId && (!before || (before.parentId ?? null) !== parentId)) return nodes
+
+ const byId = new Map(nodes.map((node) => [node.id, node]))
+ const belongsToDraggedSubtree = (node: T): boolean => {
+ if (node.id === draggedId) return true
+ const seen = new Set<string>()
+ let current = node
+ while (current.parentId && !seen.has(current.parentId)) {
+ if (current.parentId === draggedId) return true
+ seen.add(current.parentId)
+ const next = byId.get(current.parentId)
+ if (!next) return false
+ current = next
+ }
+ return false
+ }
+ const subtree = nodes.filter(belongsToDraggedSubtree)
+ const without = nodes.filter((node) => !belongsToDraggedSubtree(node))
+ const at = beforeId ? without.findIndex((node) => node.id === beforeId) : without.length
+ if (at < 0) return nodes
+ return [...without.slice(0, at), ...subtree, ...without.slice(at)]
+}
+
/**
* Moves `draggedId` to sit immediately before `beforeId` in the array (sidebar order follows
* array order). The dragged node also joins `beforeId`'s container (same reposition math) so a
* drop both reorders within a group and can move across groups. No-op when either node is
- * missing, they are the same, or the dragged node is a group.
+ * missing, they are the same, or the dragged node is a group (frames reorder through
+ * `reorderGroupWithinParent`, which keeps their whole subtree together).
*/
export function reorderNodeBefore(
nodes: CanvasNode[],
@@ -1008,12 +1195,10 @@ export function reorderNodeBefore(
/** Converts persisted node states into live React Flow nodes (parents first). */
export function nodeStatesToFlow(states: CanvasNodeState[]): CanvasNode[] {
- // React Flow requires a parent node to appear before its children in the array.
- const ordered = [...states].sort((a, b) => {
- if ((a.kind === 'group') === (b.kind === 'group')) return 0
- return a.kind === 'group' ? -1 : 1
- })
- return ordered.map((raw) => {
+ // React Flow requires a parent node to appear before its children. With nested frames a flat
+ // "groups first" sort is not enough (two frames compare equal), so `groupsFirst` re-emits the
+ // frames depth-first from the root at the end of this function.
+ const mapped = states.map((raw) => {
// The SDK chat node was removed (2026-07). A persisted chat node degrades into a sticky that
// keeps its place and tells the user how to continue the conversation — chat sessions are
// ordinary Claude sessions, resumable in any terminal. (position/size are normalized
@@ -1047,6 +1232,7 @@ export function nodeStatesToFlow(states: CanvasNodeState[]): CanvasNode[] {
id: n.id,
// Default to 'terminal' for nodes saved before the kind field existed.
type: n.kind ?? 'terminal',
+ ...((n.kind ?? 'terminal') === 'group' ? { dragHandle: '.group-node__label' } : {}),
position: n.position,
width: n.size.width,
height,
@@ -1082,6 +1268,7 @@ export function nodeStatesToFlow(states: CanvasNodeState[]): CanvasNode[] {
}
}
})
+ return groupsFirst(mapped)
}
/** Serializes live React Flow nodes back into persisted node states. */
diff --git a/src/renderer/styles.css b/src/renderer/styles.css
index 59b8bbeb6..39ebc23a1 100644
--- a/src/renderer/styles.css
+++ b/src/renderer/styles.css
@@ -4958,7 +4958,20 @@ body,
border: 1.5px dashed;
border-radius: 14px;
box-sizing: border-box;
- cursor: grab;
+}
+
+/* A frame is a background CONTAINER, not a giant drag target. Its body passes pointer input
+ through to React Flow's pane (pan / rubber-band select), and — since frames nest — an outer
+ frame no longer swallows the clicks meant for a frame drawn inside it. The label pill, the
+ actions and the resize handles explicitly opt back in; the pill is also the node's
+ `dragHandle`, so dragging a frame means dragging its label. */
+.react-flow__node-group {
+ pointer-events: none !important;
+}
+.react-flow__node-group .group-node__label,
+.react-flow__node-group .group-node__actions,
+.react-flow__node-group .react-flow__resize-control {
+ pointer-events: auto;
}
/* Bound to a git worktree: a checkout, not a loose grouping. Solid, thicker border (the tint is
@@ -4995,6 +5008,10 @@ body,
border: 1px solid var(--border);
border-radius: 999px;
user-select: none;
+ cursor: grab;
+}
+.group-node__label:active {
+ cursor: grabbing;
}
/* Zoomed far out (boost ≥ 2, toggled in Canvas.setGroupLabelBoost), the pill keeps only the
@@ -6424,6 +6441,13 @@ body,
padding-left: 6px;
border-left: 1px solid rgba(var(--tint-rgb), 0.08);
}
+/* Sibling-reorder drop zones for group rows in the sessions tree (a thin accent rule marks
+ where the dragged frame would land). */
+.ss-subgroup__reorder-zone,
+.ss-subgroup__reorder-end { position: relative; height: 5px; }
+.ss-subgroup__reorder-end--root { margin-left: 15px; }
+.ss-subgroup__reorder-zone.is-drop-before::before,
+.ss-subgroup__reorder-end.is-drop-before::before { content: ''; position: absolute; top: 1px; left: 2px; right: 6px; height: 2px; border-radius: 1px; background: var(--accent); pointer-events: none; }
.ss-subgroup__head { display: flex; align-items: center; gap: 6px; padding: 4px 6px; border-radius: 6px; border: 1px solid transparent; cursor: pointer; }
.ss-subgroup__head:hover { background: var(--panel-header); }
.ss-subgroup__dot { width: 7px; height: 7px; border-radius: 2px; flex: 0 0 auto; }
diff --git a/src/shared/scm-scope.test.ts b/src/shared/scm-scope.test.ts
index 771dbce98..3751d5fb8 100644
--- a/src/shared/scm-scope.test.ts
+++ b/src/shared/scm-scope.test.ts
@@ -56,6 +56,12 @@ describe('selectedScmGroupId', () => {
expect(selectedScmGroupId([g1, select(termNode('t1', 'g1'))])).toBe('g1')
})
+ it('inherits a bound Source Control scope through nested unbound groups', () => {
+ const inner = { ...groupNode('inner'), parentId: 'g1' }
+ expect(selectedScmGroupId([g1, inner, select(termNode('t1', 'inner'))])).toBe('g1')
+ expect(selectedScmGroupId([g1, select(inner)])).toBe('g1')
+ })
+
it('returns null for a selected ungrouped node', () => {
expect(selectedScmGroupId([g1, select(termNode('t1'))])).toBeNull()
})
diff --git a/src/shared/scm-scope.ts b/src/shared/scm-scope.ts
index f43cdc40e..85be56367 100644
--- a/src/shared/scm-scope.ts
+++ b/src/shared/scm-scope.ts
@@ -51,7 +51,8 @@ export function scmScopes(project: { cwd?: string; name: string }, bound: BoundG
/**
* The group the canvas selection points at, which Source Control opens on: a selected group node
- * itself, else a selected node's parent group.
+ * itself, else a selected node's parent chain. Nested unbound groups inherit the nearest bound
+ * ancestor's Source Control scope.
*
* A selection can span several nodes (box-select), so the pick is made explicit rather than left to
* array order: a candidate group that is actually BOUND to a worktree wins over any other, because
@@ -60,10 +61,16 @@ export function scmScopes(project: { cwd?: string; name: string }, bound: BoundG
*/
export function selectedScmGroupId(nodes: ScmScopeNode[]): string | null {
const candidates: string[] = []
+ const byId = new Map(nodes.map((node) => [node.id, node]))
for (const n of nodes) {
if (!n.selected) continue
- const groupId = n.type === 'group' ? n.id : n.parentId
- if (groupId && !candidates.includes(groupId)) candidates.push(groupId)
+ const seen = new Set<string>()
+ let groupId = n.type === 'group' ? n.id : n.parentId
+ while (groupId && !seen.has(groupId)) {
+ seen.add(groupId)
+ if (!candidates.includes(groupId)) candidates.push(groupId)
+ groupId = byId.get(groupId)?.parentId
+ }
}
if (candidates.length === 0) return null
const boundIds = new Set(boundGroups(nodes).map((b) => b.groupId))
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 1af23fcf2..38565d9fe 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -836,10 +836,14 @@ export interface Settings {
* whatever size they were saved with; other node kinds keep their own defaults. */
defaultNodeWidth: number
defaultNodeHeight: number
- /** Sessions sidebar: collapse inactive projects and re-focus the list on every project
- * switch (the historical behavior). Off = every project defaults to expanded and a
- * project switch never touches the user's expand/collapse choices. */
+ /** Sessions sidebar: the DEFAULT for a project row the user never toggled — on (historical)
+ * keeps the active project expanded and collapses the others, off leaves everything expanded.
+ * Explicit toggles live in `sidebarCollapsedItems` and always win. */
sidebarAutoCollapse: boolean
+ /** Persisted disclosure choices for the sessions tree, keyed `project:<id>` and
+ * `project:<id>:group:<groupId>` (true = collapsed). Pruned on every write against the live
+ * tree, so a deleted frame or project cannot grow settings.json forever. */
+ sidebarCollapsedItems: Record<string, boolean>
/** Fallback view for projects the user hasn't explicitly toggled (canvas or the kanban board).
* Personal machine-local preference; per-project explicit choices override it. */
defaultProjectView: 'canvas' | 'kanban'
@@ -1047,6 +1051,7 @@ export const DEFAULT_SETTINGS: Settings = {
defaultNodeWidth: 640,
defaultNodeHeight: 440,
sidebarAutoCollapse: true,
+ sidebarCollapsedItems: {},
defaultProjectView: 'canvas',
panHoverDelay: 600,
doubleClickFocus: true,