# DAG rendering specification

The implementation standard for drawing. Data semantics: [Session DAG design](https://fzkuji.github.io/OpenProgram/docs/reference/design/runtime/dag/overview.html). The figures in [layout](https://fzkuji.github.io/OpenProgram/docs/reference/design/runtime/dag/layout.html) show the scenes ([§6](#s6)) and win over any text here.

Paths below: `dag/` is `apps/web/lib/runtime-bridge/dag/`; `styles/` is `apps/web/app/styles/`; `chat/` is `apps/web/components/chat/`.

## Where the graph lives

A perspective of the chat pane, per tab, for the full column width a branchy session needs. The perspective is not persisted; a reload opens the transcript.

| Piece | Where |
| --- | --- |
| Perspective state | `CenterTab.dagView`, `apps/web/lib/tabs/center-tabs-store.ts` |
| Controls (toggle and `…` menu, top right) | `chat/pane/view-controls.tsx` |
| Host (`#historyPanel`, `.history-body`) | `chat/dag/dag-view.tsx`; selected by `dag/pipeline.ts`, `dag/render/visibility.ts` |
| Swap | `.center-pane-chat[data-center-view]` in `styles/dag/view-host.css` |

- Both surfaces stay mounted and swap by `display`: the renderer paints on every capture, and unmounting would blank the graph.
- The swap hides `#chatArea`, never `#chatView`. The singleton composer lives in `#composer-mount` there, so both perspectives share one draft and send path; a node sent from the graph appears on the next capture.
- The graph covers the pane instead of taking its slot, under the composer's `z-index: 5`, so the composer stays on the bottom edge. The canvas runs under it; `fitCanvas` centres in the strip above.
- Clicking a node fills the right sidebar's Details and Context views. Rename, delete, merge and attach stay in its branch list. Branch switching is in the graph ([§5](#s5)); no strip above the canvas.

### The infinite canvas

No scroll box: the SVG fills the pane and one `<g>` carries translate and scale, so size and centre are not decided by content. The host never re-flows on resize.

| Gesture or key | Effect |
| --- | --- |
| Mouse wheel, pinch, ⌘ + wheel | Zoom about the cursor, 25%–300%; pinch at a faster rate |
| Two fingers on a trackpad | Pan |
| Right or middle drag | Pan from anywhere, and on macOS the desktop App keeps following the cursor past the window's edge until the button comes up; a right click that did not move opens the menu on release; every drag ends when its button is no longer down, even if the release was lost outside the window |
| Left drag on empty canvas | Selection box; touching selects ([§13](#s13)) |
| Left press on a node | The node's click or double-click |
| Shift+1 / Shift+0 / Shift+2 | Fit graph, down to 25% / 100% / fit selection |
| + / − | Step one wheel notch (`ZOOM_STEP`) |
| F | Glide to a working agent, next one on repeat, HEAD if none (`focusAgent`) |
| M / ? | Minimap / controls sheet |

| Rule | Design |
| --- | --- |
| Wheel kind (`interaction/view/wheel.ts`) | `ctrlKey` = pinch; sideways delta = two fingers; Chromium's `wheelDeltaY == -3 × deltaY` = trackpad, notches are multiples of 120. Judged on the first event, held until a 180 ms pause so inertia never flips to zoom. Line and page deltas become pixels. A pixel-smooth mouse reporting the trackpad ratio pans |
| Dot lattice | Pitch `COL_W`, same pan and zoom, a dot centred under every anchor; drift is a visible bug, so the fit rounds to whole pixels. Radius follows zoom, 1–3px |
| View state | Pan and zoom in `dag/store/globals.ts` per session. Only a different session re-fits; a pane resize never does |
| Opening view | The fit, floored at 80% (`OPEN_MIN_SCALE`); an overflowing axis follows HEAD near the bottom of the strip |

**Zoom column, panels and full screen**

| Part | Design |
| --- | --- |
| Zoom column (`DagZoomColumn`) | Top right, under the perspective strip. Strip one: + · readout · −, hairline, Find the working agent. Strip two: minimap, hairline, legend, controls sheet. Each stays open until pressed again. A toggle that is on holds the hover grey |
| Readout and buttons | Clicking the readout resets to 100%; buttons anchor on the pane centre and glide 0.22 s, even in log space; a press mid-glide steps on from the destination; a wheel or pan takes over (`glideZoom`). The readout is written imperatively, because routing every wheel event through React repaints the tree |
| Side column | Left of the zoom column, map width (280px): map, docked web preview, legend, controls sheet, 16px apart, full height, ending 16px above the composer, scrolling as a whole; a hidden panel folds its place |
| Web preview | Starts docked (`web-tab-pip-dock.ts`, `PipDockSlot`). A still frame stands in while scrolled partly out. Dragging frees it after 36px; within 56px of the column top it snaps in, and needs 88px to leave. One spring (framer-motion) per move. An expanded preview floats. The conversation perspective has the same dock |
| Panel motion | Fade, 95% scale, 8px slide over 100ms, reversed on exit (`PANEL_MOTION` in `chat/dag/dag-key-sheet.tsx`, `.is-hidden` in `styles/dag/panels/tools.css`). `stowMinimap` puts the map away without motion on entry. Strips slide in top to bottom, 150ms each, 40ms apart; leaving is instant |
| Material | One raised strip material, `styles/dag/panels/tools.css`; legend and sheet padding from `MENU_PANEL`, frame shared with the minimap, no ring. Glyphs are Solar Bold Duotone ([icons](https://fzkuji.github.io/OpenProgram/docs/reference/design/ui/visual-system/icons.html)) |
| Full screen | Belongs to the session pane; its button is in the perspective strip. The body grows over both sidebars and the tab strip to `--canvas-fullscreen-inset` (8px); the window keeps its size and native web views hide. Ends on press, Esc with nothing selected, another tab kind or reload (`canvas-fullscreen.ts`; `html[data-canvas-fullscreen]` in `chat/pane/center-pane.css`) |
| Full-screen motion | Web Animations, four real edges, 400ms ease-in-out in, 320ms out; content lays out at the box size each frame, never at the end size first, or transcript scroll would clamp. While moving, `canvas-motion.ts` keeps re-wrap to visible rows. Toggle mid-glide reverses; Reduce Motion skips |
| Code | Pan, zoom, fit: `interaction/view/canvas.ts`. `_viewTx`, `_viewTy`, `_viewScale`, `_viewSession`: `store/globals.ts`. Lattice: `.history-body` in `styles/dag/graph/canvas.css`. Legend rows: `styles/dag/panels/legend.css` |

## 0. What to draw

| Layer | Nodes | Answers | Count |
| --- | --- | --- | --- |
| Conversation | ROOT, user, llm replies, spawn roots, merge, manually invoked top-level functions | The session's shape | Single digits to dozens |
| Execution | Tool calls and sub-calls | What one turn did | Dozens per turn |

The viewport lays out only the conversation layer. A turn's calls and agents are its call thread ([§12](#s12)). One chip is one reply and everything the model did until the next user message:

- A runtime-notice reply (`job_followup`, `process_exit`) merges into its anchor, found by climbing `predecessor` past every followup. Its synthetic `display=runtime` user message is never painted; `filter.py` (`bridge_hidden`) re-parents the reply onto the notice's predecessor so it is never an orphan.
- A restart's "continue the interrupted task" reply is stamped `resumed` and merges into the same anchor as the reply it continues.

Chat stream and call tree are unaffected: same data, three projections.

## 1. Position = (column, row)

Column = lane start + tier. Both axes step one unit (`COL_W == ROW_H == 40`), offset by `PAD_X`, `PAD_Y`.

### Lane: which branch

| Event | New branch root | Attachment |
| --- | --- | --- |
| Retry or rewrite | Forked user or llm node | Shares predecessor with the replaced node |
| Spawn | `source=agent_spawn` user node | caller = initiator, predecessor empty |
| Merge | The merge node | Base branch lane; no new lane |

- Columns 0, 1, 2… by appearance, no gaps, no "trunk". A branch occupies its start column to its deepest visible chain node; the next starts one right.
- A fork lane keeps one extra gap column, and tiers are zeroed per lane.
- A fork lane mirrors the trunk: its first column is an empty spine where the dashed bridge lands; every turn steps one right and stubs off it. Capsules and relics take the bridge to the chip.
- Thread items reserve no width: they take the nearest column right of the anchor that no line crosses at the insertion row, so threads on different rows share a column and two open threads never share a cell.

### Tier and depth

| Node | Layer | Column |
| --- | --- | --- |
| ROOT | conversation | tier 0 |
| user | conversation | tier 1 |
| llm reply, merge | conversation | tier 2 |
| Thread item (call, spawn head) | execution | anchor's column +1; a nested open thread +1 more |

- Chain rows: a preorder walk of the structural parent tree; every visible node takes its own row.
- A fork root sits on the row of its sibling, and every branch off one point shares that row. Each bridges to the branch immediately left, so the dash is straight and two units long.
- Thread rows: from the anchor's next row, one per event; an open spawn's thread continues from its row. Later rows shift down: expansion is insertion, never overlay.
- Cross-session spawns land as the target's own chain, lane 0.

## 2. Layout rules

| Rule | Meaning |
| --- | --- |
| Square grid | Child at the parent's lower-right, 45°; the lattice makes it checkable |
| Alignment and compaction | Nodes on grid points; empty rows and columns close on every visibility change. A placeholder box violates this: running shows on the chip |
| Chips are cells | Same 28px chip, one cell, 12px gap, no shape sized to text. Captions in annotation grey right of a call or user message (`render/labels/captions.ts`) take only free room up to the next tile, tag or crossing, step past a fork line, drop when tight, and never move layout. An agent's tile shows its bubble; zoomed far out captions hide |

## 3. Edges: colour = branch, line = type

| Edge | Line | Colour | Shown |
| --- | --- | --- | --- |
| Same-branch parent to child | Solid on belt | Branch | Always |
| Retry fork bridge | Dashed `6 4`, horizontal; elbow only if rows diverged | Branch | Always |
| Call thread | Solid on belt: vertical in the anchor's column, stub per item | Anchor's branch | While open |
| Merge convergence | Solid 2.4px | Peer branch | Always |
| Attach merge-back | Dashed `4 4` | Source branch | When both ends are visible |
| Ghost (covered range) | Dashed `3 3`, no belt | Branch | When expanded |
| send_message | Dotted `1 5` | Target branch | Hover only |

- Lane colours: `LANE_COLORS`, `--lane-*` in `styles/design/color.css`. No category of edge has a fixed colour.
- The road to HEAD wears HEAD's colour (`_stampPathLanes`, `_pathLane` in `layout/assign-lanes.ts`), and `render/edges.ts` draws it last.
- Belts: an 8px opaque neutral track (`.dag-belt`) under a 2px branch line. Beads ride towards work under the line: a chain belt into a running node, a thread belt while anything down its item runs, the trunk only to that item. `paintBelts` reads `data-to`, so in-place status patches repaint it.
- Every line runs centre to centre; chip fills bury the ends.

## 4. Node chips

Every node is the same round chip (`render/tiles.ts`): a tint of its tone mixed into the canvas, opaque over the belts, with its icon. State restyles the chip; nothing is drawn around it.

| State | Chip |
| --- | --- |
| Normal | 18% tint, full-colour icon |
| Hover | 30% tint |
| Selected | Solid fill, canvas-colour icon, 8% larger |
| HEAD | 24% tint, breathing glow (2.4 s `drop-shadow`, `data-head`); steady under reduced motion. Carries no coverage mark |
| Not in next request ([§8](#s8)) | 10% tint, icon 60% |
| Running | `is-running`: icon breathes; agent dot and bubble appear |
| Error | `is-error`: red `!` on the upper right; tone stays |
| Cancelled | `is-faded`: ghost grey |

| Node | Icon | Tone |
| --- | --- | --- |
| ROOT | House | Secondary ink |
| User | Person | Branch |
| Agent reply | The agent's character | Branch |
| Call | Per tool (`presentTool`, same as the transcript) | Per tool (`styles/tool-tones.css`) |
| Sub-agent spawn | The sub-agent's character | Branch |
| Compaction summary | Archive | Memory |
| Merge / attach | Pull request / link | Plan |

| Badge | Place | Meaning |
| --- | --- | --- |
| `+N` | Upper-right shoulder, annotation grey, no shape | Folded thread size; gone when open |
| `↗` | Top right, both sides of a cross-session spawn | `spawn_remote` and `spawn_out`. No in-graph `attach_returns` edge; not clickable. Same-session spawns have none |
| `▤` | Upper left | Spilled ([§8](#s8)) |

**Agents on the canvas and semantic zoom**

| Topic | Design |
| --- | --- |
| Character | Avatar shape ([avatars](https://fzkuji.github.io/OpenProgram/docs/reference/design/ui/visual-system/agent-avatars.html)) drawn flat, eyes cut through (`components/avatar/bot/glyph.ts`), in the branch colour. The main agent wears the conversation Agent's; `chat/dag/dag-view.tsx` reports it to `render/agent-look.ts`. A sub-agent's comes from its name. Legend and Activity panel draw the same glyphs |
| Working agents (`render/agents.ts`) | A breathing status dot of branch colour on the upper-left of the tile; a bubble says "name · doing" in present tense. A node belongs to the sub-agent its chain leads to, else the main agent; each shows its latest running node. If folded, the dot sits on the nearest drawn tile. Shared tiles stack. Idle, the main agent's dot rests on HEAD, steady |
| Markers | Keep on-screen size (`--dag-marker-scale`), pinned to the tile in world units |
| Below 55% (`FAR_SCALE`, `is-far`) | Tiles become 7px solid dots, lines 1.5px, press target about 10px; corner dots, call captions, counts hide. With a selection, the rest fades to 25% (`has-selection`); the minimap draws selected nodes larger in the accent |
| Labels | One curve below 100% (`--dag-label-scale`), 12px down to about 8.5px. `interaction/view/far-labels.ts` hides any within 8px of one shown: branch names first, current branch first, then messages nearest HEAD, then calls |

## 5. Branch tags

| Aspect | Design |
| --- | --- |
| Anchor | Row of the branch's own deepest visible node, right of the tile; follows an open thread and returns on fold. An agent's bubble hides it |
| Button | Active: flat block in lane colour. Click another to check it out |
| Spawned agent | No branch tag: the agent is its chip. With its owner's thread open, the spawn head wears a name tag on its right; clicking checks out the agent's tip |
| Lines | A line along the row breaks around letters (canvas-colour halo) |
| Collision | Measured pixel boxes; every visible glyph is seeded, and the later tag steps down a row |
| Source | `list_branches` only. Merging erases the name (kept on disk), which moves to the merge node's tooltip |

## 6. Scenes

| Scene | Topic | Key points |
| --- | --- | --- |
| 1–7 | Base: single turn, multi-turn, retry, tool indent, manual function, composite, collapse | Tool calls show as the shoulder count until opened |
| 8 | Merge | On the base lane, peer lines 2.4px; attach pointers are lines only |
| 9 | send_message | A `from_branch` user node lands at the target branch tail |
| 10 | Spawn and return | The head sits in sequence on its caller's thread. The followup reply merges into the same anchor, so no return line |
| 11 | Thread aggregation | Open state is per node and recursive |
| 12 | Status and badges | [§4](#s4) |
| 13 | Tag placement | [§5](#s5) |

| Note | Rule |
| --- | --- |
| Send-back node | With `predecessor` = initiator, forms a fork if the user also sent a message, and joins the `< N/M >` switcher ([invariants](https://fzkuji.github.io/OpenProgram/docs/reference/design/ui/invariants.html) rule 7). A turn of the receiving chain whatever its `caller`: user tier, reply one right. Label is the sender's name and words; `message_from` carries the sender |
| Sub-agent spawning again | `agent.max_spawn_depth`, default 1. Past the limit a spawn is refused. The renderer recurses at any depth |

## 7. Render pipeline

1. `passes/`: `merge-runs`; `collapse-runtime-pairs` (legacy wrapper pairs); `demote-decoration-cards` (a card child is not a fork); `fold-summaries`; `thread`.
2. `layout/geometry.ts`: lattice positions from the backend's lane, tier and depth, which the front end only consumes (`openprogram/state/store/session/graph/layout/`, tier in `tier.py`).
3. `render/edges.ts`, `render/nodes.ts`, `render/labels/badges.ts`, then the canvas (`interaction/view/canvas.ts`, `gestures.ts`). `render/seat.ts` reads a drawn group's position back.

Orchestration: `pipeline.ts`. Payload: `openprogram/state/store/session/graph/builder.py`. Debug: `python scripts/maintenance/dag_dump.py <session_id>` prints lane, tier, depth and an ASCII grid. A capture caches icons, tool presentation and text widths; attaching defers pane-size work a frame; `applyView` paints once a frame; a pan rewrites only translations. A repaint of 150 nodes takes about 5ms.

## 8. Fill means context coverage

A covered tile (`is-covered`, `render/visibility.ts`) is part of the next LLM call. The graph never derives context semantics: `GET /api/sessions/{id}/context-range` returns them, built from the functions the real render uses. `enterExclusiveCoverageMode` (`dag/index.ts`) fetches it.

The set is the active branch from head back to the latest summary, plus each covered turn's code nodes listed after their owner (`_with_code_nodes`, `_coverage_nodes` in `openprogram/interfaces/server/routes/files/tree.py`). Context ids with no drawn node are ignored.

```
{"session_id": "…", "node_ids": ["…"], "count": 12,
 "nodes": [{"node_id": "…", "in_context": true, "aged": false, "spilled": true}]}
```

| Field | Meaning | Source | Drawing |
| --- | --- | --- | --- |
| `in_context` | In the covered set | `get_branch` | Full chip |
| `aged` | Always false: old results are never aged. Kept so the payload keeps its shape | `routes/files/tree.py` | None |
| `spilled` | Written to `large_nodes/`, render cites it | `metadata.spilled`, `spill.py::spill_if_large` | `▤` drawn as `<text>`, so the first-shape scan skips it |

Re-fetched on `context_stats` and `compaction_finished` (`chat-handlers.ts`). `spilled` is outside the render signature, so new coverage clears it (`setLastSignature(null)`). The summary is an ordinary chain member, so branch ids are drawn ids and need no translation; only synthetic bridges are filtered (`filter.py`).

## 9. Compaction as one capsule

A summary stands for its range, so it draws as one chip with the archive icon, its covered count `+N` on the shoulder. `metadata.covers_ids` (`context/compaction/persistence.py`), passed through `builder.py` with covered turns' caller subtrees and missing ids dropped, drives shape, fold, count, ghosts and inspector. The front end does no seq arithmetic, which would catch dead forks.

| Viewing | Covered turns | Capsule |
| --- | --- | --- |
| Carrying branch, folded | Elided; capsule first on the trunk | Coloured, `+N` |
| Carrying branch, open | Ghosts: branch colour, dashed edge, no covered fill | After its ghosts; no count |
| Other branch | Live and raw | After those turns, inert: no fold, count or fill |
| Superseded (`superseded_summary`) | — | Keeps its row, ghost grey, folds nothing |

The carrying branch's chain contains the whole segment ([compaction §3](https://fzkuji.github.io/OpenProgram/docs/reference/design/context/compaction.html)). Fold state is view-only (`_summaryExpanded`), starts folded, and sticks across branch switches. The slot never moves. Placements are clone rewrites in `fold-summaries.ts`; the stored row keeps its real `predecessor`. Grey is reserved for history no branch can carry.

## 10. Failed turns

`status=error` and off the HEAD chain (`_isArchivedFailure`): the same grey as a covered turn, the `!` kept, inspector `Failed turn · Recorded`. Both conditions matter: status alone would grey the error you are looking at; off-HEAD alone would grey every sibling. The store writes `status` ([execution control](https://fzkuji.github.io/OpenProgram/docs/reference/design/runtime/execution/control.html)); a cancel stays `cancelled`.

## 11. Hover, click, right-click, double-click

| Action | Result | Code |
| --- | --- | --- |
| Hover | Brief card: role (`Subagent · <name>` on a spawn), model and tokens, preview, folded count, status if not finished. Tokens: `llm.output_tokens`, else `chars/4` labelled estimated, none for empty text | `interaction/node/tooltip.ts` |
| Click | Fold or unfold the thread; nothing else. Details fills quietly | `interaction/node/nodes.ts` |
| Right-click | The same card expands in place with every field, coverage, full id and verbs; stays until a click elsewhere. Raw JSON opens in the inspector shell | `expandTooltip`, `renderNodeInfo`, `inspector.ts` |
| Double-click a user turn | Fork and edit | `forkAndEditNode` |

| Verb | Route | Why it is enough |
| --- | --- | --- |
| Checkout | `POST /api/chat/checkout` | A pure HEAD move |
| Fork from node | Same | Sending from a HEAD with children makes a sibling |
| Fork and edit (user turns) | Same, to the node's predecessor, then the text in the composer | An ordinary send; the same shape as `POST /api/chat/edit` |
| Copy id, raw JSON | Client only | — |

Legend: `DagLegend`, starts closed, survives canvas clicks.

## 12. The call thread

Everything a turn did is one time-ordered sequence. `passes/thread.ts` builds it; `_threadOpen` holds view state per anchor, never persisted, reset on session switch.

| State | Drawing |
| --- | --- |
| Folded | Only `+N` on the shoulder. No outline: anything shaped reads as a node |
| Open | A solid branch-colour line down the anchor's column, one stub and one real chip per event. Later rows move down; fold reclaims them |
| Spawn | The head is a call-thread chip with the sub-agent's character. The dispatch call (`agent`, `send_message`) folds into it unless no spawn opened. Internal turns merge in; its thread sits one column right. Recursive |
| Return | No line: the followup merges into the same anchor, so dispatch, work and return read top to bottom |
| Name | Tooltip, inspector and name tag; from `spawned_from.label`, stamped by the runner (`attach["label"]`, `runtime/jobs/runner/progress.py`; `ws_actions/session/transcript.py`), else the branch name |
| Visibility | An item shows only while every thread above it is open |

## 13. Selection, deleting, minimap

One mouse, no tool modes; gestures are in [the table above](#canvas). Shift or ⌘ with click or drag adds and removes; a click on empty canvas clears. Code: `interaction/selection/`, `interaction/view/gestures.ts`, `chat/dag/dag-tools.tsx`.

- Selection lights chips in place. The box is an accent outline over 8% accent. Re-applied each repaint, pruned to drawn nodes, dropped on session switch. It takes focus from the composer. Esc clears it, then leaves full screen.
- Action bar, top left: `N selected | ⌖ · Copy ID · Delete · ✕`; afterwards `Deleted N nodes | Undo` for a few seconds.
- Minimap (`interaction/view/minimap.ts`): dots on faint lines, an accent frame for the view, HEAD larger and ringed. Press or drag moves the camera; wheel zooms about the middle. Starts hidden; the choice is kept in the browser.

### Deleting

Delete or ⌫ acts at once; ⌘Z undoes.

| Rule | Behaviour |
| --- | --- |
| What goes | Selected nodes plus what they own through `caller`. Conversation followers stay, re-pointed at the nearest surviving predecessor |
| A glyph stands for its rows | A merged followup goes with its anchor; a spawn head takes its dispatch call and agent branch |
| Refused | Root, a lone spawn root, summaries, attach and merge machinery |
| HEAD, branch names | Move to the nearest surviving predecessor |
| Storage | Files move to `<sessions root>/.deleted-nodes/<session>/<op_id>/` with a journal; purged after 24 hours on the next delete |
| Undo | Replays the journal; anything moved since keeps its newer value. Stack is per session, for the page's life |
| During a turn | Both refused |
| Wire | `delete_nodes {session_id, node_ids}` → `nodes_deleted {ok, op_id, deleted, error}`; `restore_deleted_nodes {session_id, op_id}` → `nodes_restored`; on success an open chat gets `window_stale` and reads again. Any attach, merge or deletion also sends `branches_changed`, and the client asks `list_branches` again, which refreshes the graph. Store: `session_store/node_deletion.py`; socket: `ws_actions/dag_nodes.py` |

## Implementation status

All implemented, except navigation from the cross-session `↗`.

**Tests**

| Area | Test |
| --- | --- |
| Geometry, threads | `apps/web/tests/dag/dag-subagent-thread.test.mjs` |
| Compaction fold | `apps/web/tests/dag/fold-summaries.test.mjs` |
| Selection | `apps/web/tests/dag/dag-selection.test.mjs` |
| Shared composer | `apps/web/tests/tabs/center-perspective.test.mjs` |
| Coverage query | `tests/unit/context/statistics/test_context_range_coverage.py` |
| `covers_ids` | `tests/unit/dag/test_graph_builder_covers.py` |
| Deletion | `tests/component/store/session/test_node_deletion.py` |

[Layout scenes](https://fzkuji.github.io/OpenProgram/docs/reference/design/runtime/dag/layout.html)
