Skip to content

Self-improving AI Employees for everyone

feat(canvas): pushed-content display board with panel + docked sidebar

trohitg77df97259295
diff --git a/CLAUDE.md b/CLAUDE.md
index a6d9306e..be5ae454 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -39,6 +39,7 @@ This is a React Flow-based workflow automation platform implementing n8n-inspire
| **[Speech Provider RFC](./docs-internal/speech_provider_rfc.md)** | Provider-abstracted speech — two nodes (`textToSpeech`, `speechToText`) with a `provider` dropdown, backed by **two registries, one per direction** (registry membership IS the capability: a synthesis-only vendor simply never appears in the transcription enum). Everything vendor-specific lives in the plugin folder [`server/nodes/speech/`](./server/nodes/speech/) — protocol, registries, dispatch, per-vendor modules; only the generic `services/provider_registry.py` and the vendor-neutral `services/media/` are shared. v1 providers: OpenAI (both directions), ElevenLabs (TTS), Deepgram + Groq (STT), Sarvam (both). Capabilities are JSON (`server/config/speech_defaults.json`) with per-model overrides, so no shared code branches on a provider name. **Audio never travels as bytes** — nodes return an `AudioRef` (a ~400 B reference) because a 12 MB base64 result blows Temporal's 2 MiB blob limit and retries 3× re-billing the provider each time. Backing routes: `GET/POST /api/workspace/{workflow_id}/…` in [`routers/workspace.py`](./server/routers/workspace.py). |
| **[Media Transport](./docs-internal/media_transport.md)** | How files move through the engine, and why they move as **references rather than bytes**. `services/media/` — `FileRef` (the base; `FileKind = file\|audio\|image\|video\|document`) with `AudioRef(FileRef)` as the probed-container narrowing (~400 B, `extra="forbid"` so adding a bytes field is a `ValidationError` rather than a silent regression), `write_audio` / `resolve_media` / `coerce_file_param` (the one nodes should call — accepts a `FileRef`/`AudioRef`, a bare path, or the legacy base64 envelope), `inspect_audio` (tinytag → stdlib `wave` → PCM arithmetic, **never raises**), `limits.py`, and **`preview.py` — the single owner of the inline-vs-attachment rule**, with two consumers: `routers/workspace.py` picks its `Content-Disposition` from `serves_inline`, and the gallery listing sets each row's `preview` from `preview_kind`, so the panel can never offer a preview the route refuses to serve. Containment runs through `resolve_within`, which closed a live vulnerability: a node joined a user path onto the workspace root unchecked, so `audio_file="../../credentials.db"` read the encrypted credential store and uploaded it. **The id/slug asymmetry is the trap** — workspace dirs are named by the mutable `Workflow.slug` while a ref stores the immutable `workflow_id` so refs survive rename; the lookup lives in [`services/workspace_locator.py`](./server/services/workspace_locator.py) (`resolve_workspace_root(..., allow_default=)`), and **every mutating caller must pass `allow_default=False`** or an unresolvable id silently lands the write in the shared anonymous workspace. HTTP surface in [`routers/workspace.py`](./server/routers/workspace.py): Range support comes free from Starlette's `FileResponse`; `NEVER_INLINE` is `{image/svg+xml, text/html, text/xml, application/xhtml+xml}` because `shell` / `fileDownloader` / `fileModify` can write arbitrary files into a workspace. |
| **[Data Node & Vision](./docs-internal/data_node.md)** | The `dataSource` agent tool (raw local data over two namespaces: workspace paths + operator-approved `mnt/<name>/...` external mounts with per-mount writable flags; typed bounded read tiers text/csv/json/pdf/html/xlsx/image-metadata/binary; write/append but **no delete**; `copy_to_workspace` imports mount files as real FileRefs), the machine-wide `data_mounts` allowlist (`services/data/mount_store.py` — refuses `DATA_DIR` overlap, drive roots, home dir), the `visionAnalyze` delegate tool (vision for every host model via openai/anthropic/gemini official SDK shapes + the `services/media/image_fit.py` visual-token budget), and the first native-image-blocks increment: `ContentBlock.source` (durable `file_ref` vs transient `bytes` — the wire codec raises on bytes), the `llm_media` tool-result opt-in, capability-gated `hydrate_image_blocks` in `run_native_llm_step`, Anthropic `tool_result` image encoding (openai/gemini encoders pending; their `vision.enabled` stays false until then). |
+| **[Canvas Node](./docs-internal/canvas_node.md)** | The `canvas` node — pushed-content display board (the Claude/ChatGPT-Canvas analog) in [`server/nodes/tool/canvas/`](./server/nodes/tool/canvas/). Dual control: agents call the locked `canvas(...)` tool (paths / url / 64KB-capped markdown notes, append/replace), workflow edges auto-display upstream FileRefs via a structural scan of `connected_outputs` (`tts → canvas` is a zero-config edge; the node is the one addition to `NodeExecutor._NEEDS_CONNECTED_OUTPUTS`). Board = plugin-owned `canvas_boards`/`canvas_items` tables (mount_store mechanism, 200-item FIFO), identity-only `canvas_updated` broadcast (direct, no canary consumer), `canvas_list/remove/clear` WS handlers with the simple_memory security preamble. **Two frontend hosts share one renderer**: the `isCanvasPanel` parameter panel and the new docked resizable right sidebar (`CanvasDock` + `canvasDockStore`; auto-open via `notifyPushed`, ephemeral click-to-preview from the gallery dialog, `usePanelResize` extracted from ConsolePanel). Renders media carousel with follow-latest image poll, markdown/code/JSON via the repo's first capped client-side text fetch (`useWorkspaceText`, 512KB), external URLs + workspace HTML in strictly sandboxed iframes (never `allow-same-origin`; `NEVER_INLINE` untouched), and inline PDF via the `INLINE_EXACT` exact-match addition to `preview.py`. Browser screenshots became displayable in the same change: both browser plugins persist shots as workspace FileRefs via the tolerant `nodes/browser/_screenshots.py`. |
| **[Translate / Transliterate / Detect](./docs-internal/speech_provider_rfc.md#8-what-this-pattern-should-absorb-next)** | The second application of the multi-vendor pattern, and the one that retired `nodes/sarvam/`. Three nodes (`translateText`, `transliterateText`, `detectLanguage`) in [`server/nodes/translate/`](./server/nodes/translate/), backed by **three registries — one per capability**, because the asymmetry is sharper than speech's: DeepL translates and does nothing else, while Sarvam and LLM-backed providers do all three. Membership makes an unsupported selection unrepresentable rather than a runtime failure inside a paid call. Providers: **deepl** (`Authorization: DeepL-Auth-Key`, `text` is an array, free keys ending `:fx` route to a different host, and it returns `billed_characters` so cost is the provider's own figure), **sarvam** (all three over dedicated REST), **openai** (all three via `ChatUnifier` — proves the Protocol does not care what a provider does internally; billing deliberately NOT recorded because that path bills tokens the LLM layer already costs). Capabilities in `server/config/translate_defaults.json`. |
| **[CI/CD Pipeline](./docs-internal/ci_cd.md)** | GitHub Actions workflows, predeploy validation, release publishing, and composite setup action |
| **[Performance](./docs-internal/performance.md)** | Cold-start measurements (Application startup complete 2.90 s warm, 21.5 s cold post-`company clean` — was 71 s before the 2026-07-14 boot-delay fixes; first WS connect 8.29 s) + warm and cold per-phase timelines + optimisation history (lazy LangChain imports, lazy LLM-SDK exception refs, esbuild sidecar bundle, bytecode-at-build, PartySocket reconnect, TanStack Query auth bootstrap, `manualChunks`, Vite dep-cache preservation, off-loop Temporal build-id hash) + bottleneck inventory + reproduction commands + anti-patterns to never reintroduce (incl. eager SDK import at LLM provider registration, unconditional `.vite` wipe, synchronous `Worker()` on the event loop). Pairs with the build-time pipeline doc below. |
@@ -2750,6 +2751,7 @@ This function:
- **`NodeUserError` (services.plugin)**: typed exception for user/LLM-correctable failures (string not found, command not found, bad cwd, missing required field, operator-only Twitter query, Python sandbox `import`, Node.js sidecar down). `BaseNode.execute()` catches it specifically: single WARN line in the operator log (no traceback) + structured `{success: False, error_type: "NodeUserError", error: ...}` envelope. Genuine bugs still flow through the generic `except Exception` branch and keep their full stacktrace via `logger.exception`. Adopted across `fileRead` / `fileModify` / `fsSearch` / `gallery` / `process_manager` / `pythonExecutor` / `javascriptExecutor` / `typescriptExecutor`. **Plugin WS handlers that can fail user-correctably must use `@ws_response` (from `services.plugin.ws`), not `@ws_handler`** — the latter logs every exception at ERROR with a full traceback, which breaks the one-WARN-line `NodeUserError` contract. `gallery/_handlers.py` is the reference. Reach for it whenever the LLM (or user) can fix the input and retry — never for actual server bugs.
- **Process manager Windows shim resolution**: `process_service.start()` resolves `argv[0]` via `shutil.which()` before `asyncio.create_subprocess_exec`. On Windows, `shutil.which` honours `PATHEXT` and returns the absolute `.cmd` path (e.g. `C:\...\npm.cmd`); `CreateProcessW` then launches it directly. No `cmd /c` wrap — same canonical idiom used by `browser_service`, `claude_code_service`, `claude_oauth`, `himalaya_service`. Without this, bare `argv[0]="npm"` raises `WinError 2` because `CreateProcessW` does NOT apply `PATHEXT` to bare names. Missing binary → early `Command not found: '<bin>'. Check spelling or ensure the binary is on PATH.` envelope (no traceback).
- **Gallery — the workspace file explorer (`gallery`, `nodes/filesystem/gallery/`)**: sibling of the process-manager pattern below — the `isGalleryPanel` uiHint gives it a full-height MiddleSection panel (breadcrumbs, grid/list, image thumbnails, search, preview, upload) instead of the plain params list. It pairs the hint with `hideInputSection` but **keeps** the Output section, because unlike `processManager` it produces output worth seeing and dragging. Four rules worth knowing before touching it: (1) **The panel edits the node's own params** — navigating writes `path`, pinning writes `selection` — so what you browse is what the node emits, rather than a second copy of that state free to drift. (2) **The backend decides; the panel renders.** Each listing row arrives with a finished `ref` (a serialized `FileRef`, `null` for directories) and a `preview` verdict from `services/media/preview.py`; breadcrumbs arrive as `crumbs`; a search term is turned into a glob by `search_to_pattern` server-side. Re-deriving any of these client-side would be a second copy of a server rule — and for `preview` specifically, a second copy of a *security* decision. (3) **Drag uses its own `workspaceFile` discriminator, never the existing `nodeOutput`** — that branch calls `onChange(value)` unconditionally, so reusing it would mean dropping a file into a half-written prompt destroys the prompt. `ParameterRenderer.handleDrop` therefore branches: a `file` param takes the ref whole, everything else appends the path with smart spacing. (4) **`isFileRef` accepts every `FileKind`, not just `audio`** — the gallery emits `kind: "file"` even for a `.wav`, because `kind: "audio"` asserts `inspect_audio` probed the container and a fabricated duration would mis-bill a per-second provider downstream; narrowing the check back would render a dropped file as raw JSON. Listing rides the WebSocket (`list_workspace_files`) because the consumer already holds an authenticated socket with request correlation; `GET /api/workspace/{id}/files/{path}` stays the *content* channel (preview, download, Range). Frontend: [GalleryPanel.tsx](./client/src/components/parameterPanel/GalleryPanel.tsx) + `parameterPanel/gallery/`, [useDragWorkspaceFile.ts](./client/src/hooks/useDragWorkspaceFile.ts), [types/workspaceFiles.ts](./client/src/types/workspaceFiles.ts).
+- **Canvas — the pushed-content display board (`canvas`, `nodes/tool/canvas/`)**: the third full-height-panel sibling (gallery / processManager / canvas), and the first with a SECOND host — a docked resizable right sidebar ([CanvasDock.tsx](./client/src/components/ui/CanvasDock.tsx) + [canvasDockStore.ts](./client/src/stores/canvasDockStore.ts)) that auto-opens on push and serves ephemeral click-to-preview from the gallery dialog. Both hosts render one shared component ([parameterPanel/canvas/CanvasContent.tsx](./client/src/components/parameterPanel/canvas/CanvasContent.tsx)). Rules worth knowing before touching it: (1) **The broadcast is identity-only** — `canvas_updated` carries `{workflow_id, node_id, revision}`; content flows solely through the authorized `canvas_list` handler (simple_memory security preamble: external socket + owner + graph-ownership, exactly-one-node-of-type check). (2) **The board stores references, never bytes** — `display(paths=…)` builds refs via `resolve_media` + stat (never `coerce_file_param`; don't read content to make a pointer), notes cap at 64KB with a visible marker, the board FIFO-caps at 200, and the op's Output is ids+counts only. (3) **Iframe sandboxes are test-locked security decisions**: external URLs get exactly `sandbox="allow-scripts allow-forms"` + `no-referrer`; workspace HTML renders ONLY as `srcDoc` + `sandbox="allow-scripts"` (opaque origin, no cookies — `NEVER_INLINE` respected, not worked around); PDF is a plain same-origin iframe enabled by the `INLINE_EXACT` exact-match set in `preview.py`. (4) **Never `addEventListener('canvas_updated')`** — the WebSocketContext switch case shadows the default-case fan-out. (5) The `tool` group auto-derives `isConfigNode: True`; canvas declares it `False` because `input-main` is real dataflow. (6) `hooks/useWorkspaceText.ts` is the repo's first client-side file-content fetch (streamed, cancelled at 512KB, key self-busts on `size_bytes`+`modified_at`) — attachment disposition doesn't block `fetch()`. Browser screenshots became its feedstock: both browser plugins persist shots as workspace FileRefs via the tolerant, containment-checked [nodes/browser/_screenshots.py](./server/nodes/browser/_screenshots.py). Full reference: [docs-internal/canvas_node.md](./docs-internal/canvas_node.md).
- **Process manager port admission + middle panel**: server commands declare listener `ports` (with compatibility inference for `--port`, `-p`, `PORT`, and `*_PORT`). `ProcessService.start()` serializes admission, checks managed reservations plus OS TCP listeners, and returns structured `PORT_IN_USE` without killing the owner or allowing framework auto-port fallback. Explicit ports/environment survive restart. The `isProcessManagerPanel` UI hint gives only `processManager` a full-height workflow-scoped process table with PID/ports/timestamps/elapsed/output and stop/restart controls. See [docs-internal/process_manager.md](./docs-internal/process_manager.md).
- **Telegram message auto-split + caption spill**: the Bot API caps `sendMessage.text` at 4096 and media captions at 1024 (constants `_TG_TEXT_LIMIT` / `_TG_CAPTION_LIMIT` in `nodes/telegram/_service.py`; per https://core.telegram.org/bots/api). **Both limits are measured in UTF-16 code units, not characters** — an emoji costs 2 — so length goes through `_tg_len`, never `len()`. `_split_head` cuts one chunk at the cleanest paragraph → line → sentence → space boundary past the halfway mark, else hard-cuts; `_split_text` loops it. `send_message` chunks long text and threads each part under the previous (`reply_to_message_id` cascade), returning the first message's metadata + `parts` + `message_ids[]`. `_send_captioned_media` (used by `send_photo` / `send_document`) truncates an over-long caption at the cap and sends the remainder as a threaded reply with `disable_notification=True`, reporting `caption_truncated` + `follow_up_message_ids` — previously the whole send just failed with `BadRequest("Message caption is too long")`. **Ordering invariant: split the RAW body before `_resolve_body` runs markdown→HTML.** Splitting after conversion can separate a `<b>` from its closing tag, which Telegram rejects with "can't find end of the entity"; Telegram measures the cap against entity-parsed text, so truncating raw markdown is conservative. Locked by `tests/nodes/test_telegram_service.py`.
- **Telegram inbound content types**: `_format_message` extracts detail dicts for all 11 types via the `_CONTENT_PROBES` / `_DETAIL_EXTRACTORS` tables, plus a normalized `media` block (`kind` / `file_id` / `mime_type` / `file_name` / …) that downstream nodes read instead of branching per type; MIME and filename are synthesised where Telegram omits them. **Probe order is load-bearing**: Telegram sets `message.document` on animation messages too, so `animation` and `video_note` must be probed before `document` and `video` or every GIF classifies as a document. The trigger never downloads — media travels as a `file_id`, never bytes or base64, because node results are persisted, broadcast, and replayed into the LLM conversation every turn.
diff --git a/client/src/Dashboard.tsx b/client/src/Dashboard.tsx
index 8c9e4a66..682d23bf 100644
--- a/client/src/Dashboard.tsx
+++ b/client/src/Dashboard.tsx
@@ -41,6 +41,7 @@ import GetStartedChecklist from './components/onboarding/GetStartedChecklist';
import { useSaveUserSettingsMutation } from './hooks/useUserSettingsQuery';
import ErrorBoundary from './components/ui/ErrorBoundary';
import ConsolePanel from './components/ui/ConsolePanel';
+import CanvasDock from './components/ui/CanvasDock';
import StatusBar from './components/ui/StatusBar';
import CommandPaletteHost from './components/ui/CommandPaletteHost';
import { useSoundSync, withSound } from './hooks/useSound';
@@ -1531,6 +1532,11 @@ const DashboardContent: React.FC = () => {
/>
)}
</div>
+
+ {/* Docked Canvas sidebar — persistent content viewer at the
+ rightmost edge. Owns its own state (canvasDockStore);
+ auto-opens on canvas_updated for the current workflow. */}
+ <CanvasDock nodes={nodes} />
</div>
</div>
diff --git a/client/src/components/parameterPanel/CanvasPanel.tsx b/client/src/components/parameterPanel/CanvasPanel.tsx
new file mode 100644
index 00000000..77b2c15a
--- /dev/null
+++ b/client/src/components/parameterPanel/CanvasPanel.tsx
@@ -0,0 +1,88 @@
+/**
+ * Parameter-panel host for the Canvas node (uiHints.isCanvasPanel).
+ *
+ * Gallery-pattern full-height panel: header + the shared CanvasContent.
+ * Server state rides useCanvasBoardQuery; freshness is broadcast-driven
+ * (`canvas_updated` -> ['canvasBoard'] invalidation in WebSocketContext).
+ */
+
+import React from 'react';
+import { Eraser, RefreshCw } from 'lucide-react';
+import { toast } from 'sonner';
+
+import { Badge } from '@/components/ui/badge';
+import { Button } from '@/components/ui/button';
+import {
+ useCanvasBoardQuery,
+ useCanvasClear,
+ useCanvasRemove,
+} from '../../hooks/useCanvasBoard';
+import CanvasContent from './canvas/CanvasContent';
+
+interface Props {
+ nodeId: string;
+ workflowId?: string | null;
+}
+
+const CanvasPanel: React.FC<Props> = ({ nodeId, workflowId }) => {
+ const board = useCanvasBoardQuery(workflowId, nodeId);
+ const removeItem = useCanvasRemove(workflowId, nodeId);
+ const clearBoard = useCanvasClear(workflowId, nodeId);
+
+ const items = board.data?.items ?? [];
+
+ return (
+ <div className="flex min-h-0 flex-1 flex-col overflow-hidden p-4">
+ <header className="mb-3 flex shrink-0 items-start justify-between gap-3">
+ <div>
+ <h2 className="text-lg font-semibold text-fg-default">Canvas</h2>
+ <p className="text-sm text-fg-muted">
+ Content pushed here by agents and workflow runs. Items are
+ references — removing one never deletes the underlying file.
+ </p>
+ </div>
+ <div className="flex shrink-0 items-center gap-2">
+ {items.length > 0 && <Badge variant="secondary">{items.length}</Badge>}
+ <Button
+ variant="ghost"
+ size="sm"
+ disabled={items.length === 0 || clearBoard.isPending}
+ onClick={() =>
+ clearBoard.mutate(undefined, {
+ onError: (error) => toast.error(error.message),
+ })
+ }
+ >
+ <Eraser className="h-4 w-4" /> Clear
+ </Button>
+ </div>
+ </header>
+
+ {!workflowId ? (
+ <p className="py-8 text-center text-sm text-fg-muted">
+ Save this workflow to start collecting Canvas content.
+ </p>
+ ) : board.isLoading ? (
+ <div className="flex flex-1 items-center justify-center">
+ <RefreshCw className="h-4 w-4 animate-spin text-fg-muted" />
+ </div>
+ ) : board.isError ? (
+ <p className="py-8 text-center text-sm text-fg-muted">
+ {board.error.message}
+ </p>
+ ) : (
+ <CanvasContent
+ items={items}
+ workflowId={workflowId}
+ onRemove={(itemId) =>
+ removeItem.mutate(itemId, {
+ onError: (error) => toast.error(error.message),
+ })
+ }
+ />
+ )}
+ </div>
+ );
+};
+
+export default CanvasPanel;
diff --git a/client/src/components/parameterPanel/MiddleSection.tsx b/client/src/components/parameterPanel/MiddleSection.tsx
index 9740f53f..f024228d 100644
--- a/client/src/components/parameterPanel/MiddleSection.tsx
+++ b/client/src/components/parameterPanel/MiddleSection.tsx
@@ -33,6 +33,7 @@ import TaskManagerPanel from './TaskManagerPanel';
import TeamMonitorPanel from './TeamMonitorPanel';
import ProcessManagerPanel from './ProcessManagerPanel';
import GalleryPanel from './GalleryPanel';
+import CanvasPanel from './CanvasPanel';
import ContextPanel from './ContextPanel';
import MemoryToolPanel from './MemoryToolPanel';
import DataPanel from './DataPanel';
@@ -210,6 +211,7 @@ const MiddleSection: React.FC<MiddleSectionProps> = ({
const isMonitorNode = hints.isMonitorPanel === true;
const isProcessManagerNode = hints.isProcessManagerPanel === true;
const isGalleryNode = hints.isGalleryPanel === true;
+ const isCanvasNode = hints.isCanvasPanel === true;
const isAgentWithSkills = hints.hasSkills === true;
const { data: userSettings } = useUserSettingsQuery();
@@ -549,7 +551,7 @@ const MiddleSection: React.FC<MiddleSectionProps> = ({
<div className="relative flex h-full flex-1 flex-col overflow-hidden">
{/* Description - hide for code editor nodes (Python, Skill), masterSkill,
and the todo editor (each renders its own full-panel header). */}
- {!needsCodeEditorLayout && !isMasterSkillNode && !isContextNode && !isMemoryToolNode && !isTodoEditorNode && !isTaskManagerNode && !isMonitorNode && !isProcessManagerNode && !isGalleryNode && (
+ {!needsCodeEditorLayout && !isMasterSkillNode && !isContextNode && !isMemoryToolNode && !isTodoEditorNode && !isTaskManagerNode && !isMonitorNode && !isProcessManagerNode && !isGalleryNode && !isCanvasNode && (
<div className="shrink-0 border-b border-border-default bg-bg-panel px-6 pt-4 pb-2">
<p className="m-0 text-base leading-[1.5] text-fg-muted">
{nodeDefinition.description}
@@ -597,6 +599,8 @@ const MiddleSection: React.FC<MiddleSectionProps> = ({
parameters={parameters}
onParameterChange={onParameterChange}
/>
+ ) : isCanvasNode ? (
+ <CanvasPanel nodeId={nodeId} workflowId={currentWorkflow?.id} />
) : isContextNode ? (
<ContextPanel
nodeId={nodeId}
diff --git a/client/src/components/parameterPanel/__tests__/CanvasPanel.test.tsx b/client/src/components/parameterPanel/__tests__/CanvasPanel.test.tsx
new file mode 100644
index 00000000..27b10ff6
--- /dev/null
+++ b/client/src/components/parameterPanel/__tests__/CanvasPanel.test.tsx
@@ -0,0 +1,105 @@
+import { fireEvent, screen, waitFor } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { renderWithProviders as render } from '../../../test/providers';
+import type { CanvasItem } from '../../../lib/canvasBoard';
+
+const { wsMock } = vi.hoisted(() => ({
+ wsMock: { sendRequest: vi.fn(), isReady: true },
+}));
+vi.mock('../../../contexts/WebSocketContext', () => ({
+ useWebSocket: () => wsMock,
+}));
+
+import CanvasPanel from '../CanvasPanel';
+
+const noteItem = (id: string, content: string): CanvasItem => ({
+ id,
+ kind: 'note',
+ title: null,
+ ref: null,
+ url: null,
+ content,
+ language: null,
+ source: 'agent',
+ created_at: '2026-08-18T10:00:00+00:00',
+});
+
+const board = (items: CanvasItem[]) => ({
+ success: true,
+ items,
+ revision: items.length,
+});
+
+describe('CanvasPanel', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('lists the board through the authorized canvas_list handler', async () => {
+ wsMock.sendRequest.mockResolvedValue(board([noteItem('a', 'hello board')]));
+ render(<CanvasPanel nodeId="canvas-1" workflowId="wf-1" />);
+
+ expect(await screen.findByText('hello board')).toBeInTheDocument();
+ expect(wsMock.sendRequest).toHaveBeenCalledWith('canvas_list', {
+ workflow_id: 'wf-1',
+ node_id: 'canvas-1',
+ });
+ });
+
+ it('sends canvas_remove for the active item', async () => {
+ wsMock.sendRequest.mockImplementation(async (type: string) =>
+ type === 'canvas_list'
+ ? board([noteItem('a', 'keep'), noteItem('b', 'drop')])
+ : { success: true, revision: 3 },
+ );
+ render(<CanvasPanel nodeId="canvas-1" workflowId="wf-1" />);
+ await screen.findByText('drop');
+
+ fireEvent.click(screen.getByRole('button', { name: 'Remove item' }));
+ await waitFor(() =>
+ expect(wsMock.sendRequest).toHaveBeenCalledWith('canvas_remove', {
+ workflow_id: 'wf-1',
+ node_id: 'canvas-1',
+ item_id: 'b',
+ }),
+ );
+ });
+
+ it('sends canvas_clear from the header action', async () => {
+ wsMock.sendRequest.mockImplementation(async (type: string) =>
+ type === 'canvas_list'
+ ? board([noteItem('a', 'something')])
+ : { success: true, revision: 2 },
+ );
+ render(<CanvasPanel nodeId="canvas-1" workflowId="wf-1" />);
+ await screen.findByText('something');
+
+ fireEvent.click(screen.getByRole('button', { name: /Clear/ }));
+ await waitFor(() =>
+ expect(wsMock.sendRequest).toHaveBeenCalledWith('canvas_clear', {
+ workflow_id: 'wf-1',
+ node_id: 'canvas-1',
+ }),
+ );
+ });
+
+ it('never calls the backend without a workflow, and says why', async () => {
+ render(<CanvasPanel nodeId="canvas-1" />);
+ expect(
+ await screen.findByText(/Save this workflow to start collecting/),
+ ).toBeInTheDocument();
+ expect(wsMock.sendRequest).not.toHaveBeenCalled();
+ });
+
+ it('surfaces a denied listing instead of an empty board', async () => {
+ wsMock.sendRequest.mockResolvedValue({
+ success: false,
+ error: 'Canvas node does not belong to the requested workflow',
+ });
+ render(<CanvasPanel nodeId="canvas-1" workflowId="wf-1" />);
+ expect(
+ await screen.findByText(/does not belong to the requested workflow/),
+ ).toBeInTheDocument();
+ });
+});
diff --git a/client/src/components/parameterPanel/canvas/CanvasContent.tsx b/client/src/components/parameterPanel/canvas/CanvasContent.tsx
new file mode 100644
index 00000000..2a52b239
--- /dev/null
+++ b/client/src/components/parameterPanel/canvas/CanvasContent.tsx
@@ -0,0 +1,342 @@
+/**
+ * The one shared Canvas board renderer — hosted by both the parameter-panel
+ * CanvasPanel and the docked CanvasDock.
+ *
+ * The item list IS the carousel: one active item, prev/next in the footer,
+ * `pinnedId: null` meaning "follow newest" (the chat stick-to-bottom rule —
+ * a pushed item surfaces automatically unless the user deliberately
+ * navigated back). Keyboard arrows work on the focused content region only;
+ * no document-level listeners, which would fight React Flow node nudging.
+ *
+ * Only the ACTIVE item mounts — no N live videos/iframes.
+ */
+
+import React, { useCallback, useEffect, useMemo, useState } from 'react';
+import { useQuery } from '@tanstack/react-query';
+import {
+ AlertCircle,
+ ChevronLeft,
+ ChevronRight,
+ Download,
+ File as FileIcon,
+ X,
+} from 'lucide-react';
+import ReactMarkdown from 'react-markdown';
+import remarkBreaks from 'remark-breaks';
+import remarkGfm from 'remark-gfm';
+
+import { Button } from '@/components/ui/button';
+import { Label } from '@/components/ui/label';
+import { Switch } from '@/components/ui/switch';
+import { buildApiUrl } from '../../../config/api';
+import { useWebSocket } from '../../../contexts/WebSocketContext';
+import type { CanvasItem } from '../../../lib/canvasBoard';
+import type {
+ ListWorkspaceFilesResponse,
+ WorkspaceFileRef,
+} from '../../../types/workspaceFiles';
+import { formatBytes } from '../gallery/fileIcons';
+import {
+ itemLabel,
+ parentDirOf,
+ prismLanguageFor,
+ resolveRenderKind,
+} from './canvasKinds';
+import TextFileView from './TextFileView';
+import { ExternalSiteView, PdfView, WorkspaceHtmlView } from './WebView';
+
+const FOLLOW_POLL_MS = 5_000;
+
+interface Props {
+ items: CanvasItem[];
+ workflowId?: string | null;
+ onRemove?: (itemId: string) => void;
+ emptyHint?: React.ReactNode;
+ /** Initial state of the follow-latest toggle (dock persists it). */
+ followLatestDefault?: boolean;
+ onFollowLatestChange?: (value: boolean) => void;
+}
+
+const HonestFallback: React.FC<{ failed: boolean; hasUrl: boolean }> = ({
+ failed,
+ hasUrl,
+}) => (
+ <div className="flex flex-col items-center gap-2 py-10 text-center">
+ <FileIcon className="h-10 w-10 text-fg-muted" />
+ <p className="flex items-center gap-2 text-xs text-fg-muted">
+ {failed && <AlertCircle className="h-3.5 w-3.5 shrink-0 text-destructive" />}
+ {failed
+ ? 'Could not load this file. It may have been removed, or the session expired.'
+ : !hasUrl
+ ? 'Save and run this workflow to give its files a stable address.'
+ : 'No inline preview for this file type.'}
+ </p>
+ </div>
+);
+
+const BinaryView: React.FC<{ refFile: WorkspaceFileRef }> = ({ refFile }) => {
+ const href = refFile.url ? buildApiUrl(refFile.url) : null;
+ return (
+ <div className="flex flex-col items-center gap-3 py-10 text-center">
+ <FileIcon className="h-10 w-10 text-fg-muted" />
+ <div className="text-xs text-fg-muted">
+ <p className="break-all font-mono text-fg-default">{refFile.path}</p>
+ <p>
+ {refFile.mime_type || 'unknown'} · {formatBytes(refFile.size_bytes ?? 0)}
+ </p>
+ </div>
+ {href && (
+ <Button asChild variant="outline" size="sm">
+ <a href={href} download={refFile.filename} target="_blank" rel="noreferrer">
+ <Download className="h-4 w-4" /> Download
+ </a>
+ </Button>
+ )}
+ </div>
+ );
+};
+
+const CanvasContent: React.FC<Props> = ({
+ items,
+ workflowId,
+ onRemove,
+ emptyHint,
+ followLatestDefault = false,
+ onFollowLatestChange,
+}) => {
+ const { sendRequest, isReady } = useWebSocket();
+ const [pinnedId, setPinnedId] = useState<string | null>(null);
+ const [followLatest, setFollowLatest] = useState(followLatestDefault);
+ const [mediaFailed, setMediaFailed] = useState(false);
+
+ const activeIndex = useMemo(() => {
+ if (items.length === 0) return -1;
+ if (pinnedId) {
+ const index = items.findIndex((item) => item.id === pinnedId);
+ if (index >= 0) return index;
+ }
+ return items.length - 1;
+ }, [items, pinnedId]);
+
+ const active = activeIndex >= 0 ? items[activeIndex] : null;
+ useEffect(() => setMediaFailed(false), [active?.id]);
+
+ const goTo = useCallback(
+ (index: number) => {
+ if (items.length === 0) return;
+ const clamped = Math.max(0, Math.min(items.length - 1, index));
+ // Landing on the newest item resumes follow-newest.
+ setPinnedId(clamped === items.length - 1 ? null : items[clamped].id);
+ },
+ [items],
+ );
+
+ const handleKeyDown = useCallback(
+ (event: React.KeyboardEvent) => {
+ if (event.key === 'ArrowLeft') {
+ event.preventDefault();
+ goTo(activeIndex - 1);
+ } else if (event.key === 'ArrowRight') {
+ event.preventDefault();
+ goTo(activeIndex + 1);
+ } else if (event.key === 'Home') {
+ event.preventDefault();
+ goTo(0);
+ } else if (event.key === 'End') {
+ event.preventDefault();
+ setPinnedId(null);
+ }
+ },
+ [activeIndex, goTo],
+ );
+
+ const verdict = active ? resolveRenderKind(active) : null;
+
+ // Follow-latest: while the active item is a workspace image, poll its
+ // folder listing (gallery cadence) and render the newest image there —
+ // how a browser-automation run becomes a live view with zero backend.
+ const followDir = active?.ref ? parentDirOf(active.ref.path) : '';
+ const followEnabled =
+ followLatest && verdict === 'media-image' && !!workflowId && isReady;
+ const followQuery = useQuery<ListWorkspaceFilesResponse>({
+ queryKey: ['canvasFollowLatest', workflowId ?? '', followDir],
+ enabled: followEnabled,
+ refetchInterval: FOLLOW_POLL_MS,
+ queryFn: () =>
+ sendRequest<ListWorkspaceFilesResponse>('list_workspace_files', {
+ workflow_id: workflowId,
+ path: followDir,
+ limit: 500,
+ }),
+ });
+
+ const followRef = useMemo<WorkspaceFileRef | null>(() => {
+ if (!followEnabled || !followQuery.data?.success) return null;
+ const images = (followQuery.data.entries ?? []).filter(
+ (entry) => !entry.is_dir && entry.preview === 'image' && entry.ref,
+ );
+ if (images.length === 0) return null;
+ images.sort((a, b) =>
+ String(b.modified_at ?? '').localeCompare(String(a.modified_at ?? '')),
+ );
+ return images[0].ref;
+ }, [followEnabled, followQuery.data]);
+
+ if (items.length === 0) {
+ return (
+ <div className="flex flex-1 items-center justify-center p-6 text-center text-sm text-fg-muted">
+ {emptyHint ?? 'Nothing here yet — agents and workflow runs push content to this Canvas.'}
+ </div>
+ );
+ }
+ if (!active) return null;
+
+ const displayRef = verdict === 'media-image' && followRef ? followRef : active.ref;
+ const mediaSrc = displayRef?.url ? buildApiUrl(displayRef.url) : null;
+
+ const body = (() => {
+ switch (verdict) {
+ case 'note':
+ return (
+ <div className="prose prose-sm min-h-0 max-w-none flex-1 overflow-auto dark:prose-invert">
+ <ReactMarkdown remarkPlugins={[remarkGfm, remarkBreaks]}>
+ {active.content ?? ''}
+ </ReactMarkdown>
+ </div>
+ );
+ case 'web-external':
+ return <ExternalSiteView url={active.url ?? ''} title={active.title} />;
+ case 'media-image':
+ return !mediaSrc || mediaFailed ? (
+ <HonestFallback failed={mediaFailed} hasUrl={!!mediaSrc} />
+ ) : (
+ <div className="flex min-h-0 flex-1 items-center justify-center overflow-auto">
+ <img
+ src={mediaSrc}
+ alt={displayRef?.filename ?? 'canvas image'}
+ onError={() => setMediaFailed(true)}
+ className="max-h-full w-auto max-w-full rounded object-contain"
+ />
+ </div>
+ );
+ case 'media-video':
+ return !mediaSrc || mediaFailed ? (
+ <HonestFallback failed={mediaFailed} hasUrl={!!mediaSrc} />
+ ) : (
+ <video
+ controls
+ preload="metadata"
+ src={mediaSrc}
+ onError={() => setMediaFailed(true)}
+ className="min-h-0 w-full flex-1 rounded"
+ />
+ );
+ case 'media-audio':
+ return !mediaSrc || mediaFailed ? (
+ <HonestFallback failed={mediaFailed} hasUrl={!!mediaSrc} />
+ ) : (
+ <div className="flex flex-1 items-center px-2">
+ <audio
+ controls
+ preload="metadata"
+ src={mediaSrc}
+ onError={() => setMediaFailed(true)}
+ className="w-full"
+ />
+ </div>
+ );
+ case 'pdf':
+ return active.ref ? <PdfView refFile={active.ref} /> : null;
+ case 'web-srcdoc':
+ return active.ref ? <WorkspaceHtmlView refFile={active.ref} /> : null;
+ case 'markdown':
+ case 'json':
+ case 'code':
+ case 'text':
+ return active.ref ? (
+ <TextFileView
+ refFile={active.ref}
+ verdict={verdict}
+ language={prismLanguageFor(active)}
+ />
+ ) : null;
+ default:
+ return active.ref ? <BinaryView refFile={active.ref} /> : null;
+ }
+ })();
+
+ return (
+ <div
+ className="flex min-h-0 flex-1 flex-col outline-none"
+ tabIndex={0}
+ role="group"
+ aria-label="Canvas items"
+ onKeyDown={handleKeyDown}
+ >
+ <div className="flex min-h-0 flex-1 flex-col overflow-hidden rounded border border-border-default bg-bg-panel p-3">
+ {body}
+ </div>
+
+ {verdict === 'media-image' && workflowId && (
+ <div className="mt-2 flex shrink-0 items-center gap-2">
+ <Switch
+ id="canvas-follow-latest"
+ checked={followLatest}
+ onCheckedChange={(checked) => {
+ setFollowLatest(checked);
+ onFollowLatestChange?.(checked);
+ }}
+ />
+ <Label htmlFor="canvas-follow-latest" className="text-xs text-fg-muted">
+ Follow latest image{followDir ? ` in ${followDir}/` : ''}
+ </Label>
+ </div>
+ )}
+
+ <div className="mt-2 flex shrink-0 items-center gap-1">
+ {items.length > 1 && (
+ <>
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ onClick={() => goTo(activeIndex - 1)}
+ disabled={activeIndex === 0}
+ aria-label="Previous item"
+ >
+ <ChevronLeft className="h-4 w-4" />
+ </Button>
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ onClick={() => goTo(activeIndex + 1)}
+ disabled={activeIndex === items.length - 1}
+ aria-label="Next item"
+ >
+ <ChevronRight className="h-4 w-4" />
+ </Button>
+ </>
+ )}
+ <span className="min-w-0 flex-1 truncate text-xs text-fg-default" title={itemLabel(active)}>
+ {itemLabel(active)}
+ </span>
+ {items.length > 1 && (
+ <span className="shrink-0 text-xs tabular-nums text-fg-muted">
+ {activeIndex + 1}/{items.length}
+ </span>
+ )}
+ {onRemove && (
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ onClick={() => onRemove(active.id)}
+ aria-label="Remove item"
+ >
+ <X className="h-4 w-4" />
+ </Button>
+ )}
+ </div>
+ </div>
+ );
+};
+
+export default CanvasContent;
diff --git a/client/src/components/parameterPanel/canvas/TextFileView.tsx b/client/src/components/parameterPanel/canvas/TextFileView.tsx
new file mode 100644
index 00000000..d1087c55
--- /dev/null
+++ b/client/src/components/parameterPanel/canvas/TextFileView.tsx
@@ -0,0 +1,140 @@
+/**
+ * Fetched-text renderers for Canvas file items: markdown, JSON, code, text.
+ *
+ * Bodies come over the existing workspace route via useWorkspaceTextQuery
+ * (capped + truncation-flagged). All code/text paints on the per-theme
+ * `--code-*` surface tokens; markdown uses the same prose classes as
+ * OutputPanel.
+ */
+
+import React, { useMemo } from 'react';
+import JsonView from '@uiw/react-json-view';
+import { AlertCircle, RefreshCw } from 'lucide-react';
+import Prism from 'prismjs';
+import 'prismjs/components/prism-python';
+import 'prismjs/components/prism-typescript';
+import 'prismjs/components/prism-json';
+import 'prismjs/components/prism-yaml';
+import 'prismjs/components/prism-bash';
+import 'prismjs/components/prism-markdown';
+import ReactMarkdown from 'react-markdown';
+import remarkBreaks from 'remark-breaks';
+import remarkGfm from 'remark-gfm';
+
+import type { WorkspaceFileRef } from '../../../types/workspaceFiles';
+import { useWorkspaceTextQuery } from '../../../hooks/useWorkspaceText';
+import { HIGHLIGHT_MAX_CHARS } from './canvasKinds';
+
+interface Props {
+ refFile: WorkspaceFileRef;
+ verdict: 'markdown' | 'json' | 'code' | 'text';
+ /** Prism grammar name, when one is known. */
+ language: string | null;
+}
+
+const TruncationBanner: React.FC<{ sizeBytes?: number }> = ({ sizeBytes }) => (
+ <p className="mb-2 shrink-0 rounded border border-warning bg-bg-panel px-2 py-1 text-xs text-warning">
+ Showing the first 512 KB{sizeBytes ? ` of ${Math.round(sizeBytes / 1024)} KB` : ''} — use
+ Download for the full file.
+ </p>
+);
+
+const CodeSurface: React.FC<{ text: string; language: string | null }> = ({
+ text,
+ language,
+}) => {
+ const grammar = language ? Prism.languages[language] : undefined;
+ const highlighted = useMemo(() => {
+ if (!grammar || text.length > HIGHLIGHT_MAX_CHARS) return null;
+ try {
+ // Prism escapes entities while tokenizing — same usage as the
+ // ConsolePanel JSON highlighter.
+ return Prism.highlight(text, grammar, language as string);
+ } catch {
+ return null;
+ }
+ }, [grammar, language, text]);
+
+ return (
+ <pre className="min-h-0 flex-1 overflow-auto rounded border border-code-border bg-code-bg p-3 font-mono text-xs leading-relaxed text-code-text">
+ {highlighted !== null ? (
+ <code dangerouslySetInnerHTML={{ __html: highlighted }} />
+ ) : (
+ <code>{text}</code>
+ )}
+ </pre>
+ );
+};
+
+const TextFileView: React.FC<Props> = ({ refFile, verdict, language }) => {
+ const query = useWorkspaceTextQuery(refFile);
+
+ if (!refFile.url) {
+ return (
+ <p className="py-8 text-center text-xs text-fg-muted">
+ Save and run this workflow to give its files a stable address.
+ </p>
+ );
+ }
+ if (query.isLoading) {
+ return (
+ <div className="flex flex-1 items-center justify-center py-10">
+ <RefreshCw className="h-4 w-4 animate-spin text-fg-muted" />
+ </div>
+ );
+ }
+ if (query.isError) {
+ return (
+ <p className="flex items-center justify-center gap-2 py-8 text-center text-xs text-fg-muted">
+ <AlertCircle className="h-3.5 w-3.5 shrink-0 text-destructive" />
+ Could not load this file. It may have been removed, or the session expired.
+ </p>
+ );
+ }
+
+ const { text, truncated } = query.data ?? { text: '', truncated: false };
+
+ if (verdict === 'markdown') {
+ return (
+ <div className="flex min-h-0 flex-1 flex-col">
+ {truncated && <TruncationBanner sizeBytes={refFile.size_bytes} />}
+ <div className="prose prose-sm min-h-0 max-w-none flex-1 overflow-auto dark:prose-invert">
+ <ReactMarkdown remarkPlugins={[remarkGfm, remarkBreaks]}>{text}</ReactMarkdown>
+ </div>
+ </div>
+ );
+ }
+
+ if (verdict === 'json') {
+ let parsed: unknown;
+ let parseFailed = false;
+ try {
+ parsed = JSON.parse(text);
+ } catch {
+ parseFailed = true;
+ }
+ if (!parseFailed && !truncated) {
+ return (
+ <div className="min-h-0 flex-1 overflow-auto rounded border border-code-border bg-code-bg p-2">
+ <JsonView value={parsed as object} collapsed={2} displayDataTypes={false} />
+ </div>
+ );
+ }
+ // Truncated JSON never parses honestly; degrade to the code surface.
+ return (
+ <div className="flex min-h-0 flex-1 flex-col">
+ {truncated && <TruncationBanner sizeBytes={refFile.size_bytes} />}
+ <CodeSurface text={text} language="json" />
+ </div>
+ );
+ }
+
+ return (
+ <div className="flex min-h-0 flex-1 flex-col">
+ {truncated && <TruncationBanner sizeBytes={refFile.size_bytes} />}
+ <CodeSurface text={text} language={verdict === 'code' ? language : null} />
+ </div>
+ );
+};
+
+export default TextFileView;
diff --git a/client/src/components/parameterPanel/canvas/WebView.tsx b/client/src/components/parameterPanel/canvas/WebView.tsx
new file mode 100644
index 00000000..c1abc41f
--- /dev/null
+++ b/client/src/components/parameterPanel/canvas/WebView.tsx
@@ -0,0 +1,141 @@
+/**
+ * The three iframe surfaces of the Canvas board. Zero-precedent territory —
+ * these sandbox attributes are the security decisions:
+ *
+ * - External URL: `sandbox="allow-scripts allow-forms"` and NOTHING else.
+ * No allow-same-origin (opaque origin), no allow-top-navigation (a framed
+ * page must never navigate the app away), no allow-popups (the permanent
+ * Open-in-new-tab button is the escape hatch). referrerPolicy keeps
+ * workflow URLs out of third-party logs.
+ * - Workspace HTML: fetched as text and rendered via `srcDoc` with
+ * `sandbox="allow-scripts"` — never `allow-same-origin`, so a stored-XSS
+ * payload in a workspace file executes with no origin, no cookies, no
+ * app storage. Workspace HTML never enters the app DOM (also why no
+ * sanitizer dependency is needed). This respects the backend's
+ * NEVER_INLINE rule rather than working around it.
+ * - PDF: plain same-origin iframe at the file URL — the browser's built-in
+ * viewer; sandboxing breaks it in several engines. Served inline by the
+ * route since `application/pdf` joined INLINE_EXACT.
+ */
+
+import React from 'react';
+import { AlertCircle, Download, ExternalLink, RefreshCw } from 'lucide-react';
+
+import { Button } from '@/components/ui/button';
+import { buildApiUrl } from '../../../config/api';
+import { useWorkspaceTextQuery } from '../../../hooks/useWorkspaceText';
+import type { WorkspaceFileRef } from '../../../types/workspaceFiles';
+
+const SurfaceHeader: React.FC<{
+ label: string;
+ href: string;
+ hint?: string;
+}> = ({ label, href, hint }) => (
+ <div className="mb-2 flex shrink-0 items-center gap-2">
+ <span className="min-w-0 flex-1 truncate font-mono text-xs text-fg-muted" title={label}>
+ {label}
+ </span>
+ {hint && <span className="hidden shrink-0 text-[10px] text-fg-faint sm:inline">{hint}</span>}
+ <Button asChild variant="outline" size="sm">
+ <a href={href} target="_blank" rel="noopener noreferrer">
+ <ExternalLink className="h-3.5 w-3.5" /> Open in new tab
+ </a>
+ </Button>
+ </div>
+);
+
+export const ExternalSiteView: React.FC<{ url: string; title?: string | null }> = ({
+ url,
+ title,
+}) => (
+ <div className="flex min-h-0 flex-1 flex-col">
+ <SurfaceHeader
+ label={url}
+ href={url}
+ hint="Some sites refuse embedding"
+ />
+ <iframe
+ src={url}
+ title={title || url}
+ sandbox="allow-scripts allow-forms"
+ referrerPolicy="no-referrer"
+ className="min-h-0 w-full flex-1 rounded border border-border-default bg-bg-panel"
+ />
+ </div>
+);
+
+export const WorkspaceHtmlView: React.FC<{ refFile: WorkspaceFileRef }> = ({ refFile }) => {
+ const query = useWorkspaceTextQuery(refFile);
+ const href = refFile.url ? buildApiUrl(refFile.url) : null;
+
+ if (!href) {
+ return (
+ <p className="py-8 text-center text-xs text-fg-muted">
+ Save and run this workflow to give its files a stable address.
+ </p>
+ );
+ }
+ if (query.isLoading) {
+ return (
+ <div className="flex flex-1 items-center justify-center py-10">
+ <RefreshCw className="h-4 w-4 animate-spin text-fg-muted" />
+ </div>
+ );
+ }
+ if (query.isError) {
+ return (
+ <p className="flex items-center justify-center gap-2 py-8 text-center text-xs text-fg-muted">
+ <AlertCircle className="h-3.5 w-3.5 shrink-0 text-destructive" />
+ Could not load this file. It may have been removed, or the session expired.
+ </p>
+ );
+ }
+ if (query.data?.truncated) {
+ // A half-rendered page misleads (text gets a banner, HTML gets a refusal).
+ return (
+ <div className="flex flex-col items-center gap-3 py-10 text-center">
+ <p className="text-xs text-fg-muted">
+ This page is larger than the 512 KB render cap — download it instead.
+ </p>
+ <Button asChild variant="outline" size="sm">
+ <a href={href} download={refFile.filename} target="_blank" rel="noreferrer">
+ <Download className="h-4 w-4" /> Download
+ </a>
+ </Button>
+ </div>
+ );
+ }
+
+ return (
+ <div className="flex min-h-0 flex-1 flex-col">
+ <SurfaceHeader label={refFile.filename} href={href} />
+ <iframe
+ srcDoc={query.data?.text ?? ''}
+ title={refFile.filename}
+ sandbox="allow-scripts"
+ className="min-h-0 w-full flex-1 rounded border border-border-default bg-bg-panel"
+ />
+ </div>
+ );
+};
+
+export const PdfView: React.FC<{ refFile: WorkspaceFileRef }> = ({ refFile }) => {
+ const href = refFile.url ? buildApiUrl(refFile.url) : null;
+ if (!href) {
+ return (
+ <p className="py-8 text-center text-xs text-fg-muted">
+ Save and run this workflow to give its files a stable address.
+ </p>
+ );
+ }
+ return (
+ <div className="flex min-h-0 flex-1 flex-col">
+ <SurfaceHeader label={refFile.filename} href={href} />
+ <iframe
+ src={href}
+ title={refFile.filename}
+ className="min-h-0 w-full flex-1 rounded border border-border-default bg-bg-panel"
+ />
+ </div>
+ );
+};
diff --git a/client/src/components/parameterPanel/canvas/__tests__/CanvasContent.test.tsx b/client/src/components/parameterPanel/canvas/__tests__/CanvasContent.test.tsx
new file mode 100644
index 00000000..9ab13a80
--- /dev/null
+++ b/client/src/components/parameterPanel/canvas/__tests__/CanvasContent.test.tsx
@@ -0,0 +1,166 @@
+import { fireEvent, screen } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { renderWithProviders as render } from '../../../../test/providers';
+import type { CanvasItem } from '../../../../lib/canvasBoard';
+
+const { wsMock } = vi.hoisted(() => ({
+ wsMock: { sendRequest: vi.fn(), isReady: true },
+}));
+vi.mock('../../../../contexts/WebSocketContext', () => ({
+ useWebSocket: () => wsMock,
+}));
+
+// Isolate iframe/sandbox assertions from real fetches.
+const { textHookMock } = vi.hoisted(() => ({ textHookMock: vi.fn() }));
+vi.mock('../../../../hooks/useWorkspaceText', () => ({
+ TEXT_FETCH_CAP_BYTES: 512 * 1024,
+ fetchWorkspaceText: vi.fn(),
+ useWorkspaceTextQuery: (ref: unknown) => textHookMock(ref),
+}));
+
+import CanvasContent from '../CanvasContent';
+
+const note = (id: string, content: string): CanvasItem => ({
+ id,
+ kind: 'note',
+ title: null,
+ ref: null,
+ url: null,
+ content,
+ language: null,
+ source: 'agent',
+ created_at: null,
+});
+
+const urlItem = (id: string, url: string): CanvasItem => ({
+ ...note(id, ''),
+ kind: 'url',
+ content: null,
+ url,
+});
+
+const htmlItem = (id: string): CanvasItem => ({
+ id,
+ kind: 'file',
+ title: null,
+ ref: {
+ kind: 'file',
+ path: 'reports/page.html',
+ filename: 'page.html',
+ mime_type: 'text/html',
+ workflow_id: 'wf-1',
+ url: '/api/workspace/wf-1/files/reports/page.html',
+ },
+ url: null,
+ content: null,
+ language: null,
+ source: 'agent',
+ created_at: null,
+});
+
+describe('CanvasContent carousel', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ textHookMock.mockReturnValue({
+ data: { text: '<h1>report</h1>', truncated: false },
+ isLoading: false,
+ isError: false,
+ });
+ });
+
+ it('shows the newest item by default and follows new pushes', () => {
+ const items = [note('a', 'first'), note('b', 'second')];
+ const { rerender } = render(<CanvasContent items={items} workflowId="wf-1" />);
+ expect(screen.getByText('second')).toBeInTheDocument();
+
+ // Unpinned = stick to newest: a pushed item surfaces automatically.
+ rerender(<CanvasContent items={[...items, note('c', 'third')]} workflowId="wf-1" />);
+ expect(screen.getByText('third')).toBeInTheDocument();
+ });
+
+ it('pins on prev, stays pinned across pushes, resumes follow at the end', () => {
+ const items = [note('a', 'first'), note('b', 'second')];
+ const { rerender } = render(<CanvasContent items={items} workflowId="wf-1" />);
+
+ fireEvent.click(screen.getByRole('button', { name: 'Previous item' }));
+ expect(screen.getByText('first')).toBeInTheDocument();
+
+ // Pinned: a new push does NOT yank the view.
+ const grown = [...items, note('c', 'third')];
+ rerender(<CanvasContent items={grown} workflowId="wf-1" />);
+ expect(screen.getByText('first')).toBeInTheDocument();
+ expect(screen.getByText('1/3')).toBeInTheDocument();
+
+ // Navigating to the last item resumes follow-newest.
+ fireEvent.click(screen.getByRole('button', { name: 'Next item' }));
+ fireEvent.click(screen.getByRole('button', { name: 'Next item' }));
+ rerender(<CanvasContent items={[...grown, note('d', 'fourth')]} workflowId="wf-1" />);
+ expect(screen.getByText('fourth')).toBeInTheDocument();
+ });
+
+ it('navigates with arrow keys on the focused group only', () => {
+ render(
+ <CanvasContent items={[note('a', 'first'), note('b', 'second')]} workflowId="wf-1" />,
+ );
+ const group = screen.getByRole('group', { name: 'Canvas items' });
+ fireEvent.keyDown(group, { key: 'ArrowLeft' });
+ expect(screen.getByText('first')).toBeInTheDocument();
+ fireEvent.keyDown(group, { key: 'ArrowRight' });
+ expect(screen.getByText('second')).toBeInTheDocument();
+ });
+
+ it('reports the active item id on remove', () => {
+ const onRemove = vi.fn();
+ render(
+ <CanvasContent
+ items={[note('a', 'first'), note('b', 'second')]}
+ workflowId="wf-1"
+ onRemove={onRemove}
+ />,
+ );
+ fireEvent.click(screen.getByRole('button', { name: 'Remove item' }));
+ expect(onRemove).toHaveBeenCalledWith('b');
+ });
+
+ it('renders the empty hint when the board is empty', () => {
+ render(<CanvasContent items={[]} workflowId="wf-1" emptyHint="Board is empty" />);
+ expect(screen.getByText('Board is empty')).toBeInTheDocument();
+ });
+});
+
+describe('CanvasContent sandbox regression (security invariants)', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ textHookMock.mockReturnValue({
+ data: { text: '<h1>report</h1>', truncated: false },
+ isLoading: false,
+ isError: false,
+ });
+ });
+
+ it('external URLs get exactly allow-scripts allow-forms and no referrer', () => {
+ const { container } = render(
+ <CanvasContent items={[urlItem('u', 'https://example.com')]} workflowId="wf-1" />,
+ );
+ const iframe = container.querySelector('iframe') as HTMLIFrameElement;
+ expect(iframe).toBeTruthy();
+ expect(iframe.getAttribute('sandbox')).toBe('allow-scripts allow-forms');
+ expect(iframe.getAttribute('referrerpolicy')).toBe('no-referrer');
+ // The escape hatch must always be visible — framing denial is undetectable.
+ expect(screen.getByRole('link', { name: /Open in new tab/ })).toBeInTheDocument();
+ });
+
+ it('workspace HTML renders via srcDoc WITHOUT allow-same-origin', () => {
+ const { container } = render(
+ <CanvasContent items={[htmlItem('h')]} workflowId="wf-1" />,
+ );
+ const iframe = container.querySelector('iframe') as HTMLIFrameElement;
+ expect(iframe).toBeTruthy();
+ expect(iframe.getAttribute('srcdoc')).toContain('<h1>report</h1>');
+ expect(iframe.getAttribute('sandbox')).toBe('allow-scripts');
+ expect(iframe.getAttribute('sandbox')).not.toContain('allow-same-origin');
+ // Never a src pointing at the app origin for HTML.
+ expect(iframe.getAttribute('src')).toBeNull();
+ });
+});
diff --git a/client/src/components/parameterPanel/canvas/__tests__/canvasKinds.test.ts b/client/src/components/parameterPanel/canvas/__tests__/canvasKinds.test.ts
new file mode 100644
index 00000000..cb4b8760
--- /dev/null
+++ b/client/src/components/parameterPanel/canvas/__tests__/canvasKinds.test.ts
@@ -0,0 +1,111 @@
+import { describe, expect, it } from 'vitest';
+
+import type { CanvasItem } from '../../../../lib/canvasBoard';
+import {
+ itemLabel,
+ parentDirOf,
+ prismLanguageFor,
+ resolveRenderKind,
+} from '../canvasKinds';
+
+const fileItem = (
+ filename: string,
+ mime?: string,
+ overrides: Partial<CanvasItem> = {},
+): CanvasItem => ({
+ id: `item-${filename}`,
+ kind: 'file',
+ title: null,
+ ref: {
+ kind: 'file',
+ path: `media/${filename}`,
+ filename,
+ mime_type: mime,
+ workflow_id: 'wf-1',
+ url: `/api/workspace/wf-1/files/media/${filename}`,
+ },
+ url: null,
+ content: null,
+ language: null,
+ source: 'workflow',
+ created_at: null,
+ ...overrides,
+});
+
+describe('resolveRenderKind', () => {
+ it('routes notes and urls before any file inspection', () => {
+ expect(
+ resolveRenderKind({ ...fileItem('x'), kind: 'note', ref: null, content: '# hi' }),
+ ).toBe('note');
+ expect(
+ resolveRenderKind({ ...fileItem('x'), kind: 'url', ref: null, url: 'https://a.dev' }),
+ ).toBe('web-external');
+ });
+
+ it('routes media by mime prefix, and by ref.kind when mime is absent', () => {
+ expect(resolveRenderKind(fileItem('a.png', 'image/png'))).toBe('media-image');
+ expect(resolveRenderKind(fileItem('a.mp4', 'video/mp4'))).toBe('media-video');
+ expect(resolveRenderKind(fileItem('a.wav', 'audio/wav'))).toBe('media-audio');
+
+ const probedAudio = fileItem('a.bin');
+ probedAudio.ref!.kind = 'audio';
+ probedAudio.ref!.mime_type = undefined;
+ expect(resolveRenderKind(probedAudio)).toBe('media-audio');
+ });
+
+ it('mime beats extension', () => {
+ // A .txt the server identified as an image renders as an image.
+ expect(resolveRenderKind(fileItem('shot.txt', 'image/png'))).toBe('media-image');
+ });
+
+ it('routes pdf and html to their dedicated surfaces before the text tiers', () => {
+ expect(resolveRenderKind(fileItem('report.pdf', 'application/pdf'))).toBe('pdf');
+ expect(resolveRenderKind(fileItem('report.pdf'))).toBe('pdf');
+ expect(resolveRenderKind(fileItem('page.html', 'text/html'))).toBe('web-srcdoc');
+ expect(resolveRenderKind(fileItem('page.htm'))).toBe('web-srcdoc');
+ });
+
+ it('routes markdown, json, code, plain text, then binary', () => {
+ expect(resolveRenderKind(fileItem('notes.md', 'text/markdown'))).toBe('markdown');
+ expect(resolveRenderKind(fileItem('data.json', 'application/json'))).toBe('json');
+ expect(resolveRenderKind(fileItem('script.py'))).toBe('code');
+ expect(resolveRenderKind(fileItem('run.log', 'text/plain'))).toBe('text');
+ expect(resolveRenderKind(fileItem('blob.bin', 'application/octet-stream'))).toBe('binary');
+ });
+
+ it('is binary when a file item somehow has no ref', () => {
+ expect(resolveRenderKind({ ...fileItem('x'), ref: null })).toBe('binary');
+ });
+});
+
+describe('prismLanguageFor', () => {
+ it('derives the grammar from the extension', () => {
+ expect(prismLanguageFor(fileItem('a.py'))).toBe('python');
+ expect(prismLanguageFor(fileItem('a.tsx'))).toBe('typescript');
+ expect(prismLanguageFor(fileItem('a.rs'))).toBeNull();
+ });
+
+ it('lets item.language override the extension', () => {
+ const item = fileItem('a.txt');
+ item.language = 'yaml';
+ expect(prismLanguageFor(item)).toBe('yaml');
+ });
+});
+
+describe('helpers', () => {
+ it('parentDirOf returns the workspace-relative folder', () => {
+ expect(parentDirOf('media/shots/a.png')).toBe('media/shots');
+ expect(parentDirOf('a.png')).toBe('');
+ });
+
+ it('itemLabel prefers title, then filename, then url, then kind', () => {
+ expect(itemLabel({ ...fileItem('a.png'), title: 'Chart' })).toBe('Chart');
+ expect(itemLabel(fileItem('a.png'))).toBe('a.png');
+ expect(
+ itemLabel({ ...fileItem('x'), kind: 'url', ref: null, url: 'https://a.dev' }),
+ ).toBe('https://a.dev');
+ expect(
+ itemLabel({ ...fileItem('x'), kind: 'note', ref: null, content: 'hi' }),
+ ).toBe('Note');
+ });
+});
diff --git a/client/src/components/parameterPanel/canvas/canvasKinds.ts b/client/src/components/parameterPanel/canvas/canvasKinds.ts
new file mode 100644
index 00000000..8bdbff7c
--- /dev/null
+++ b/client/src/components/parameterPanel/canvas/canvasKinds.ts
@@ -0,0 +1,114 @@
+/**
+ * Pure renderer dispatch for Canvas board items. No React.
+ *
+ * Order matters: mime beats extension, and the script-bearing/document
+ * verdicts (html/pdf) are decided before the generic text tiers so a
+ * `.html` file never falls through to the plain code view by accident.
+ */
+
+import type { CanvasItem } from '../../../lib/canvasBoard';
+
+export type RenderVerdict =
+ | 'note'
+ | 'web-external'
+ | 'media-image'
+ | 'media-video'
+ | 'media-audio'
+ | 'pdf'
+ | 'web-srcdoc'
+ | 'markdown'
+ | 'json'
+ | 'code'
+ | 'text'
+ | 'binary';
+
+/** Cap above which Prism highlighting is skipped (plain <pre> instead). */
+export const HIGHLIGHT_MAX_CHARS = 100_000;
+
+const extensionOf = (name: string): string => {
+ const dot = name.lastIndexOf('.');
+ return dot > 0 ? name.slice(dot + 1).toLowerCase() : '';
+};
+
+/** Reuses the gallery's FileCode extension family (fileIcons.tsx), minus
+ * html (its own verdict) — plus plain-text extensions. */
+const CODE_EXTENSIONS = new Set([
+ 'py', 'js', 'jsx', 'ts', 'tsx', 'sh', 'ps1', 'rb', 'go', 'rs',
+ 'java', 'c', 'cpp', 'h', 'sql', 'css', 'xml', 'yaml', 'yml', 'toml',
+]);
+const TEXT_EXTENSIONS = new Set(['txt', 'log', 'csv', 'tsv', 'rtf', 'ini', 'env']);
+
+/** Extension -> Prism grammar name. Anything absent renders un-highlighted. */
+const PRISM_LANGUAGE: Record<string, string> = {
+ py: 'python',
+ js: 'javascript',
+ jsx: 'javascript',
+ ts: 'typescript',
+ tsx: 'typescript',
+ json: 'json',
+ jsonl: 'json',
+ md: 'markdown',
+ markdown: 'markdown',
+ sh: 'bash',
+ bash: 'bash',
+ yaml: 'yaml',
+ yml: 'yaml',
+};
+
+export const prismLanguageFor = (item: CanvasItem): string | null => {
+ if (item.language) {
+ const declared = item.language.toLowerCase();
+ return PRISM_LANGUAGE[declared] ?? declared;
+ }
+ const name = item.ref?.filename ?? '';
+ return PRISM_LANGUAGE[extensionOf(name)] ?? null;
+};
+
+export function resolveRenderKind(item: CanvasItem): RenderVerdict {
+ if (item.kind === 'note') return 'note';
+ if (item.kind === 'url') return 'web-external';
+
+ const ref = item.ref;
+ if (!ref) return 'binary';
+
+ const mime = ref.mime_type ?? '';
+ const refKind = ref.kind;
+ const ext = extensionOf(ref.filename);
+
+ if (mime.startsWith('image/') || refKind === 'image') return 'media-image';
+ if (mime.startsWith('video/') || refKind === 'video') return 'media-video';
+ if (mime.startsWith('audio/') || refKind === 'audio') return 'media-audio';
+
+ if (mime === 'application/pdf' || ext === 'pdf') return 'pdf';
+ if (mime === 'text/html' || ext === 'html' || ext === 'htm') return 'web-srcdoc';
+
+ if (mime === 'text/markdown' || ext === 'md' || ext === 'markdown') return 'markdown';
+ if (mime === 'application/json' || ext === 'json' || ext === 'jsonl') return 'json';
+
+ if (CODE_EXTENSIONS.has(ext)) return 'code';
+ if (TEXT_EXTENSIONS.has(ext) || mime.startsWith('text/')) return 'text';
+
+ return 'binary';
+}
+
+/** Verdicts whose body is fetched as text over the workspace route. */
+export const FETCHES_TEXT: ReadonlySet<RenderVerdict> = new Set([
+ 'web-srcdoc',
+ 'markdown',
+ 'json',
+ 'code',
+ 'text',
+]);
+
+/** Workspace-relative parent directory of a ref path ('' at the root). */
+export const parentDirOf = (path: string): string => {
+ const slash = path.lastIndexOf('/');
+ return slash > 0 ? path.slice(0, slash) : '';
+};
+
+/** Display label for an item: title, then filename/url, then kind. */
+export const itemLabel = (item: CanvasItem): string =>
+ item.title ||
+ item.ref?.filename ||
+ item.url ||
+ (item.kind === 'note' ? 'Note' : item.kind);
diff --git a/client/src/components/parameterPanel/gallery/FilePreviewDialog.tsx b/client/src/components/parameterPanel/gallery/FilePreviewDialog.tsx
index 19e62420..47b05f9d 100644
--- a/client/src/components/parameterPanel/gallery/FilePreviewDialog.tsx
+++ b/client/src/components/parameterPanel/gallery/FilePreviewDialog.tsx
@@ -1,9 +1,12 @@
import React, { useEffect, useState } from 'react';
-import { AlertCircle, Download } from 'lucide-react';
+import { AlertCircle, Download, PanelRight } from 'lucide-react';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { buildApiUrl } from '@/config/api';
+import type { CanvasItem } from '../../../lib/canvasBoard';
+import { useAppStore } from '../../../store/useAppStore';
+import { useCanvasDockStore } from '../../../stores/canvasDockStore';
import type { WorkspaceEntry } from '@/types/workspaceFiles';
import FileGlyph from './FileGlyph';
@@ -89,13 +92,43 @@ const FilePreviewDialog: React.FC<Props> = ({ entry, onOpenChange }) => {
<dd className="text-fg-default">{formatModified(entry.modified_at)}</dd>
</dl>
- {src && (
- <Button asChild variant="outline" size="sm">
- <a href={src} download={entry.name} target="_blank" rel="noreferrer">
- <Download className="h-4 w-4" /> Download
- </a>
- </Button>
- )}
+ <div className="flex shrink-0 items-center gap-2">
+ {entry.ref && (
+ <Button
+ variant="outline"
+ size="sm"
+ onClick={() => {
+ // Move the preview to the persistent docked surface. The
+ // dock sits behind this 95vw parameter modal, so opening
+ // there must also close the modal — that is the point of
+ // the affordance.
+ const item: CanvasItem = {
+ id: `ephemeral-${entry.path}`,
+ kind: 'file',
+ title: null,
+ ref: entry.ref,
+ url: null,
+ content: null,
+ language: null,
+ source: 'workflow',
+ created_at: entry.modified_at,
+ };
+ useCanvasDockStore.getState().showEphemeral(item);
+ onOpenChange(false);
+ useAppStore.getState().setSelectedNode(null);
+ }}
+ >
+ <PanelRight className="h-4 w-4" /> Open in side panel
+ </Button>
+ )}
+ {src && (
+ <Button asChild variant="outline" size="sm">
+ <a href={src} download={entry.name} target="_blank" rel="noreferrer">
+ <Download className="h-4 w-4" /> Download
+ </a>
+ </Button>
+ )}
+ </div>
</div>
</div>
</DialogContent>
diff --git a/client/src/components/ui/CanvasDock.tsx b/client/src/components/ui/CanvasDock.tsx
new file mode 100644
index 00000000..f45de86d
--- /dev/null
+++ b/client/src/components/ui/CanvasDock.tsx
@@ -0,0 +1,201 @@
+/**
+ * Docked, resizable Canvas sidebar — the persistent right-hand viewing
+ * surface (Claude-sidebar posture): stays open while working on the graph,
+ * auto-opens when content is pushed (canvas_updated -> notifyPushed), and
+ * doubles as the ephemeral click-to-preview surface for workspace files.
+ *
+ * Two modes (canvasDockStore):
+ * - 'node': renders the selected Canvas node's durable board.
+ * - 'ephemeral': renders one transient item that lives in no board.
+ */
+
+import React, { useMemo } from 'react';
+import { Monitor, PanelRightClose, Undo2 } from 'lucide-react';
+import type { Node } from 'reactflow';
+import { toast } from 'sonner';
+
+import { Badge } from '@/components/ui/badge';
+import { Button } from '@/components/ui/button';
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from '@/components/ui/select';
+import { usePanelResize } from '../../hooks/usePanelResize';
+import {
+ useCanvasBoardQuery,
+ useCanvasRemove,
+} from '../../hooks/useCanvasBoard';
+import { resolveNodeDescription } from '../../lib/nodeSpec';
+import { useAppStore } from '../../store/useAppStore';
+import {
+ DOCK_MAX_WIDTH,
+ DOCK_MIN_WIDTH,
+ useCanvasDockStore,
+} from '../../stores/canvasDockStore';
+import CanvasContent from '../parameterPanel/canvas/CanvasContent';
+
+interface CanvasDockProps {
+ nodes: Node[];
+}
+
+const isCanvasNode = (node: Node): boolean =>
+ resolveNodeDescription(node.type || '')?.uiHints?.isCanvasPanel === true;
+
+const nodeLabel = (node: Node): string =>
+ (node.data?.label as string | undefined) || node.type || node.id;
+
+const CanvasDock: React.FC<CanvasDockProps> = ({ nodes }) => {
+ const open = useCanvasDockStore((s) => s.open);
+ const widthPx = useCanvasDockStore((s) => s.widthPx);
+ const mode = useCanvasDockStore((s) => s.mode);
+ const selectedNodeId = useCanvasDockStore((s) => s.selectedNodeId);
+ const ephemeralItem = useCanvasDockStore((s) => s.ephemeralItem);
+ const followMode = useCanvasDockStore((s) => s.followMode);
+ const setFollowMode = useCanvasDockStore((s) => s.setFollowMode);
+ const setWidth = useCanvasDockStore((s) => s.setWidth);
+ const close = useCanvasDockStore((s) => s.close);
+ const selectNode = useCanvasDockStore((s) => s.selectNode);
+ const backToNode = useCanvasDockStore((s) => s.backToNode);
+
+ const workflowId = useAppStore((s) => s.currentWorkflow?.id);
+
+ const canvasNodes = useMemo(() => nodes.filter(isCanvasNode), [nodes]);
+
+ // A stale selection (workflow switch, node deleted) falls back to the
+ // first Canvas node rather than a dead board.
+ const effectiveNodeId = useMemo(() => {
+ if (selectedNodeId && canvasNodes.some((n) => n.id === selectedNodeId)) {
+ return selectedNodeId;
+ }
+ return canvasNodes[0]?.id ?? null;
+ }, [canvasNodes, selectedNodeId]);
+
+ const showBoard = open && mode === 'node';
+ const board = useCanvasBoardQuery(
+ showBoard ? workflowId : null,
+ showBoard ? effectiveNodeId : null,
+ );
+ const removeItem = useCanvasRemove(workflowId, effectiveNodeId);
+
+ const resize = usePanelResize({
+ axis: 'x',
+ cursor: 'ew-resize',
+ onMove: (deltaPx, startValue) => {
+ // The handle sits on the dock's LEFT edge — dragging left widens.
+ const viewportCap = Math.min(
+ DOCK_MAX_WIDTH,
+ Math.round(window.innerWidth * 0.6),
+ );
+ setWidth(
+ Math.min(viewportCap, Math.max(DOCK_MIN_WIDTH, startValue - deltaPx)),
+ );
+ },
+ getStartValue: () => useCanvasDockStore.getState().widthPx,
+ });
+
+ return (
+ <div
+ className={`relative flex h-full shrink-0 overflow-hidden bg-bg-panel ${
+ open ? 'border-l border-border-default' : ''
+ } ${resize.isResizing ? '[transition:none]' : 'transition-[width] duration-300'}`}
+ style={{ width: open ? widthPx : 0 }}
+ aria-hidden={!open}
+ >
+ <div
+ className="h-full w-1.5 shrink-0 cursor-ew-resize bg-transparent hover:bg-bg-hover"
+ onMouseDown={resize.start}
+ role="separator"
+ aria-orientation="vertical"
+ aria-label="Resize canvas panel"
+ />
+
+ <div className="flex min-h-0 min-w-0 flex-1 flex-col">
+ <div className="flex shrink-0 items-center gap-2 border-b border-border-default px-3 py-2">
+ <Monitor className="h-4 w-4 shrink-0 text-fg-muted" />
+ <span className="shrink-0 text-sm font-semibold text-fg-default">Canvas</span>
+
+ {mode === 'ephemeral' ? (
+ <>
+ <Badge variant="secondary" className="shrink-0">Preview</Badge>
+ <span className="min-w-0 flex-1 truncate text-xs text-fg-muted">
+ {ephemeralItem?.title || ephemeralItem?.ref?.filename || ''}
+ </span>
+ {canvasNodes.length > 0 && (
+ <Button
+ variant="ghost"
+ size="sm"
+ onClick={backToNode}
+ className="shrink-0"
+ >
+ <Undo2 className="h-3.5 w-3.5" /> Back
+ </Button>
+ )}
+ </>
+ ) : canvasNodes.length > 1 ? (
+ <div className="min-w-0 flex-1">
+ <Select
+ value={effectiveNodeId ?? undefined}
+ onValueChange={selectNode}
+ >
+ <SelectTrigger className="h-7 text-xs">
+ <SelectValue placeholder="Select canvas node" />
+ </SelectTrigger>
+ <SelectContent>
+ {canvasNodes.map((node) => (
+ <SelectItem key={node.id} value={node.id}>
+ {nodeLabel(node)}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+ ) : (
+ <span className="min-w-0 flex-1 truncate text-xs text-fg-muted">
+ {canvasNodes[0] ? nodeLabel(canvasNodes[0]) : ''}
+ </span>
+ )}
+
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ onClick={close}
+ aria-label="Close canvas panel"
+ className="shrink-0"
+ >
+ <PanelRightClose className="h-4 w-4" />
+ </Button>
+ </div>
+
+ <div className="flex min-h-0 flex-1 flex-col p-3">
+ {mode === 'ephemeral' && ephemeralItem ? (
+ <CanvasContent items={[ephemeralItem]} workflowId={workflowId} />
+ ) : !effectiveNodeId ? (
+ <div className="flex flex-1 items-center justify-center p-4 text-center text-sm text-fg-muted">
+ No Canvas node in this workflow yet — add one from the palette,
+ or open a file&apos;s preview and choose &quot;Open in side
+ panel&quot;.
+ </div>
+ ) : (
+ <CanvasContent
+ items={board.data?.items ?? []}
+ workflowId={workflowId}
+ followLatestDefault={followMode}
+ onFollowLatestChange={setFollowMode}
+ onRemove={(itemId) =>
+ removeItem.mutate(itemId, {
+ onError: (error) => toast.error(error.message),
+ })
+ }
+ emptyHint="Nothing here yet — agents push content with the canvas tool, or wire a node into the Canvas input."
+ />
+ )}
+ </div>
+ </div>
+ </div>
+ );
+};
+
+export default CanvasDock;
diff --git a/client/src/components/ui/ConsolePanel.tsx b/client/src/components/ui/ConsolePanel.tsx
index b1071c49..60eba1b8 100644
--- a/client/src/components/ui/ConsolePanel.tsx
+++ b/client/src/components/ui/ConsolePanel.tsx
@@ -36,6 +36,7 @@ import {
import { cn } from '@/lib/utils';
import { resolveNodeDescription } from '../../lib/nodeSpec';
import { useAppStore } from '../../store/useAppStore';
+import { usePanelResize } from '../../hooks/usePanelResize';
// ---------------------------------------------------------------------------
// Persisted prefs (localStorage)
@@ -81,50 +82,8 @@ const MIN_FONT_SIZE = 10;
const MAX_FONT_SIZE = 32;
const DEFAULT_FONT_SIZE = 12;
-// ---------------------------------------------------------------------------
-// Drag-resize hook
-// ---------------------------------------------------------------------------
-
-function usePanelResize(opts: {
- axis: 'y' | 'x';
- cursor: 'ns-resize' | 'ew-resize';
- onMove: (deltaPx: number, startValue: number) => void;
- getStartValue: () => number;
-}) {
- const [isResizing, setIsResizing] = useState(false);
- const startCoordRef = useRef(0);
- const startValueRef = useRef(0);
- const { axis, cursor, onMove, getStartValue } = opts;
-
- const start = useCallback((e: React.MouseEvent) => {
- e.preventDefault();
- e.stopPropagation();
- startCoordRef.current = axis === 'y' ? e.clientY : e.clientX;
- startValueRef.current = getStartValue();
- setIsResizing(true);
- }, [axis, getStartValue]);
-
- useEffect(() => {
- if (!isResizing) return;
- const handleMove = (e: MouseEvent) => {
- const cur = axis === 'y' ? e.clientY : e.clientX;
- onMove(cur - startCoordRef.current, startValueRef.current);
- };
- const handleUp = () => setIsResizing(false);
- document.addEventListener('mousemove', handleMove);
- document.addEventListener('mouseup', handleUp);
- document.body.style.cursor = cursor;
- document.body.style.userSelect = 'none';
- return () => {
- document.removeEventListener('mousemove', handleMove);
- document.removeEventListener('mouseup', handleUp);
- document.body.style.cursor = '';
- document.body.style.userSelect = '';
- };
- }, [isResizing, axis, cursor, onMove]);
-
- return { start, isResizing };
-}
+// Drag-resize hook shared with the Canvas dock — extracted verbatim to
+// hooks/usePanelResize.ts; behavior unchanged.
// ---------------------------------------------------------------------------
diff --git a/client/src/components/ui/TopToolbar.tsx b/client/src/components/ui/TopToolbar.tsx
index 61c45c9d..85683a36 100644
--- a/client/src/components/ui/TopToolbar.tsx
+++ b/client/src/components/ui/TopToolbar.tsx
@@ -24,6 +24,7 @@ import {
Clock,
Zap,
Lock,
+ Monitor,
} from 'lucide-react';
import { Badge } from '@/components/ui/badge';
import {
@@ -56,6 +57,7 @@ import {
} from '../../contexts/WebSocketContext';
import { ThemeSwitcher } from '@/components/ui/ThemeSwitcher';
import { cn } from '@/lib/utils';
+import { useCanvasDockStore } from '../../stores/canvasDockStore';
import { useAuth } from '../../contexts/AuthContext';
import { useApiKeys, GlobalModelState } from '../../hooks/useApiKeys';
import { useStoredProviderCount } from '../../hooks/useCatalogueQuery';
@@ -124,6 +126,10 @@ const TopToolbar: React.FC<TopToolbarProps> = ({
onOverrideAllAgents,
}) => {
const [isEditing, setIsEditing] = useState(false);
+ // Dock state lives on its own store (not a prop): slice reads scope
+ // re-renders to this button, and the state isn't Dashboard's to thread.
+ const canvasDockOpen = useCanvasDockStore((s) => s.open);
+ const toggleCanvasDock = useCanvasDockStore((s) => s.toggle);
const [resetOpen, setResetOpen] = useState(false);
const [tempName, setTempName] = useState(workflowName);
const { user, logout } = useAuth();
@@ -547,6 +553,17 @@ const TopToolbar: React.FC<TopToolbarProps> = ({
>
{componentPaletteVisible ? <PanelRightClose /> : <PanelRightOpen />}
</Button>
+
+ <Button
+ variant="outline"
+ size="icon-sm"
+ onClick={toggleCanvasDock}
+ aria-pressed={canvasDockOpen}
+ title={canvasDockOpen ? 'Hide canvas' : 'Show canvas'}
+ className="border-action-tools-border bg-action-tools-soft text-action-tools-ink hover:bg-action-tools-hover aria-pressed:bg-action-tools-hover"
+ >
+ <Monitor />
+ </Button>
</div>
</div>
);
diff --git a/client/src/contexts/WebSocketContext.tsx b/client/src/contexts/WebSocketContext.tsx
index 43c1d38f..15b3ab15 100644
--- a/client/src/contexts/WebSocketContext.tsx
+++ b/client/src/contexts/WebSocketContext.tsx
@@ -31,6 +31,7 @@ import {
} from '../types/cloudEvents';
import { WS_CLOSE, WS_RECONNECT } from '../lib/connectionConfig';
import { todoQueryKeyFromEvent } from '../lib/todoQuery';
+import { useCanvasDockStore } from '../stores/canvasDockStore';
// Cycle note: lib/nodeSpec imports useWebSocket from this module. Safe in
// both evaluation orders because neither side calls the other's binding at
// module top level — `executionBudgetFor` only references it inside a body.
@@ -1087,6 +1088,31 @@ export const WebSocketProvider: React.FC<{ children: React.ReactNode }> = ({ chi
break;
}
+ case 'canvas_updated': {
+ // CloudEvents-typed Canvas board change from
+ // server/nodes/tool/canvas/_events.py. Identity + revision only —
+ // panels refetch through the authorized `canvas_list` handler
+ // (ContextPanel posture). NOTE: because this switch case exists,
+ // the default-case listener fan-out never fires for this type —
+ // do not addEventListener('canvas_updated') anywhere.
+ const event = data as WorkflowEvent<{
+ workflow_id?: string | null;
+ node_id?: string | null;
+ revision?: number;
+ }>;
+ void queryClient.invalidateQueries({ queryKey: ['canvasBoard'] });
+ const identity = event?.data;
+ if (
+ identity?.node_id &&
+ identity?.workflow_id &&
+ identity.workflow_id === useAppStore.getState().currentWorkflow?.id
+ ) {
+ // Auto-open / follow the pushed node in the docked sidebar.
+ useCanvasDockStore.getState().notifyPushed(identity.node_id);
+ }
+ break;
+ }
+
case 'todos_updated': {
// CloudEvents-typed todo-list change from
// server/nodes/tool/write_todos/_events.py, emitted via the
diff --git a/client/src/hooks/__tests__/useWorkspaceText.test.ts b/client/src/hooks/__tests__/useWorkspaceText.test.ts
new file mode 100644
index 00000000..cb02cb78
--- /dev/null
+++ b/client/src/hooks/__tests__/useWorkspaceText.test.ts
@@ -0,0 +1,83 @@
+import { afterEach, describe, expect, it, vi } from 'vitest';
+
+import { fetchWorkspaceText } from '../useWorkspaceText';
+
+const encoder = new TextEncoder();
+
+/** Minimal streamed-body double: yields the given chunks, tracks cancel. */
+function streamedResponse(chunks: string[], status = 200) {
+ let index = 0;
+ const cancel = vi.fn(async () => {});
+ return {
+ response: {
+ ok: status < 400,
+ status,
+ body: {
+ getReader: () => ({
+ read: async () =>
+ index < chunks.length
+ ? { done: false, value: encoder.encode(chunks[index++]) }
+ : { done: true, value: undefined },
+ cancel,
+ }),
+ },
+ } as unknown as Response,
+ cancel,
+ };
+}
+
+afterEach(() => {
+ vi.unstubAllGlobals();
+});
+
+describe('fetchWorkspaceText', () => {
+ it('reads the full body when under the cap', async () => {
+ const { response } = streamedResponse(['hello ', 'world']);
+ vi.stubGlobal('fetch', vi.fn(async () => response));
+
+ const result = await fetchWorkspaceText('/api/workspace/wf/files/a.md');
+ expect(result).toEqual({ text: 'hello world', truncated: false });
+ });
+
+ it('stops reading at the cap, cancels the reader, and flags truncation', async () => {
+ const { response, cancel } = streamedResponse(['abcde', 'fghij', 'never-read']);
+ vi.stubGlobal('fetch', vi.fn(async () => response));
+
+ const result = await fetchWorkspaceText('/api/workspace/wf/files/big.log', 8);
+ expect(result.truncated).toBe(true);
+ expect(result.text).toBe('abcdefgh');
+ expect(cancel).toHaveBeenCalled();
+ });
+
+ it('throws with the status on a non-ok response (401 must not render blank)', async () => {
+ const { response } = streamedResponse([], 401);
+ vi.stubGlobal('fetch', vi.fn(async () => response));
+
+ await expect(fetchWorkspaceText('/api/workspace/wf/files/x.md')).rejects.toThrow('401');
+ });
+
+ it('falls back to text() when the environment has no streamed body', async () => {
+ vi.stubGlobal(
+ 'fetch',
+ vi.fn(async () => ({
+ ok: true,
+ status: 200,
+ body: null,
+ text: async () => 'x'.repeat(10),
+ })),
+ );
+
+ const result = await fetchWorkspaceText('/api/workspace/wf/files/x.md', 5);
+ expect(result).toEqual({ text: 'xxxxx', truncated: true });
+ });
+
+ it('sends the session cookie and routes through buildApiUrl', async () => {
+ const fetchMock = vi.fn(async () => streamedResponse(['ok']).response);
+ vi.stubGlobal('fetch', fetchMock);
+
+ await fetchWorkspaceText('/api/workspace/wf/files/a.md');
+ expect(fetchMock).toHaveBeenCalledWith('/api/workspace/wf/files/a.md', {
+ credentials: 'include',
+ });
+ });
+});
diff --git a/client/src/hooks/useCanvasBoard.ts b/client/src/hooks/useCanvasBoard.ts
new file mode 100644
index 00000000..1740d874
--- /dev/null
+++ b/client/src/hooks/useCanvasBoard.ts
@@ -0,0 +1,104 @@
+/**
+ * Server state for one Canvas node's board.
+ *
+ * Freshness is broadcast-driven: the `canvas_updated` case in
+ * WebSocketContext invalidates the `['canvasBoard']` prefix and the query
+ * refetches through the authorized `canvas_list` handler (identity-only
+ * broadcast, ContextPanel posture).
+ */
+
+import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
+
+import {
+ CANVAS_BOARD_QUERY_PREFIX,
+ type CanvasItem,
+ type CanvasListResponse,
+ canvasBoardQueryKey,
+} from '../lib/canvasBoard';
+import { useWebSocket } from '../contexts/WebSocketContext';
+
+export interface CanvasBoard {
+ items: CanvasItem[];
+ revision: number;
+}
+
+export function useCanvasBoardQuery(
+ workflowId: string | null | undefined,
+ nodeId: string | null | undefined,
+) {
+ const { sendRequest, isReady } = useWebSocket();
+ return useQuery<CanvasBoard, Error>({
+ queryKey: nodeId
+ ? canvasBoardQueryKey(workflowId, nodeId)
+ : [...CANVAS_BOARD_QUERY_PREFIX, 'idle'],
+ enabled: isReady && !!workflowId && !!nodeId,
+ queryFn: async () => {
+ const response = await sendRequest<CanvasListResponse>('canvas_list', {
+ workflow_id: workflowId,
+ node_id: nodeId,
+ });
+ if (!response?.success) {
+ throw new Error(response?.error || 'Failed to load canvas board');
+ }
+ return {
+ items: response.items ?? [],
+ revision: response.revision ?? 0,
+ };
+ },
+ });
+}
+
+export function useCanvasRemove(
+ workflowId: string | null | undefined,
+ nodeId: string | null | undefined,
+) {
+ const { sendRequest } = useWebSocket();
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: async (itemId: string) => {
+ const response = await sendRequest<CanvasListResponse>('canvas_remove', {
+ workflow_id: workflowId,
+ node_id: nodeId,
+ item_id: itemId,
+ });
+ if (!response?.success) {
+ throw new Error(response?.error || 'Failed to remove item');
+ }
+ return response;
+ },
+ onSettled: () => {
+ if (nodeId) {
+ void queryClient.invalidateQueries({
+ queryKey: canvasBoardQueryKey(workflowId, nodeId),
+ });
+ }
+ },
+ });
+}
+
+export function useCanvasClear(
+ workflowId: string | null | undefined,
+ nodeId: string | null | undefined,
+) {
+ const { sendRequest } = useWebSocket();
+ const queryClient = useQueryClient();
+ return useMutation({
+ mutationFn: async () => {
+ const response = await sendRequest<CanvasListResponse>('canvas_clear', {
+ workflow_id: workflowId,
+ node_id: nodeId,
+ });
+ if (!response?.success) {
+ throw new Error(response?.error || 'Failed to clear the board');
+ }
+ return response;
+ },
+ onSettled: () => {
+ if (nodeId) {
+ void queryClient.invalidateQueries({
+ queryKey: canvasBoardQueryKey(workflowId, nodeId),
+ });
+ }
+ },
+ });
+}
diff --git a/client/src/hooks/usePanelResize.ts b/client/src/hooks/usePanelResize.ts
new file mode 100644
index 00000000..4680a0cb
--- /dev/null
+++ b/client/src/hooks/usePanelResize.ts
@@ -0,0 +1,52 @@
+/**
+ * Drag-resize hook for docked panels.
+ *
+ * Extracted verbatim from ConsolePanel (its private hook since the hybrid
+ * layout) so the Canvas dock and any future docked pane share one
+ * implementation: document-level mousemove/mouseup listeners for the drag
+ * lifetime, with body cursor + userSelect managed so the drag never selects
+ * text or flickers the cursor across child elements.
+ */
+
+import { useCallback, useEffect, useRef, useState } from 'react';
+
+export function usePanelResize(opts: {
+ axis: 'y' | 'x';
+ cursor: 'ns-resize' | 'ew-resize';
+ onMove: (deltaPx: number, startValue: number) => void;
+ getStartValue: () => number;
+}) {
+ const [isResizing, setIsResizing] = useState(false);
+ const startCoordRef = useRef(0);
+ const startValueRef = useRef(0);
+ const { axis, cursor, onMove, getStartValue } = opts;
+
+ const start = useCallback((e: React.MouseEvent) => {
+ e.preventDefault();
+ e.stopPropagation();
+ startCoordRef.current = axis === 'y' ? e.clientY : e.clientX;
+ startValueRef.current = getStartValue();
+ setIsResizing(true);
+ }, [axis, getStartValue]);
+
+ useEffect(() => {
+ if (!isResizing) return;
+ const handleMove = (e: MouseEvent) => {
+ const cur = axis === 'y' ? e.clientY : e.clientX;
+ onMove(cur - startCoordRef.current, startValueRef.current);
+ };
+ const handleUp = () => setIsResizing(false);
+ document.addEventListener('mousemove', handleMove);
+ document.addEventListener('mouseup', handleUp);
+ document.body.style.cursor = cursor;
+ document.body.style.userSelect = 'none';
+ return () => {
+ document.removeEventListener('mousemove', handleMove);
+ document.removeEventListener('mouseup', handleUp);
+ document.body.style.cursor = '';
+ document.body.style.userSelect = '';
+ };
+ }, [isResizing, axis, cursor, onMove]);
+
+ return { start, isResizing };
+}
diff --git a/client/src/hooks/useWorkspaceText.ts b/client/src/hooks/useWorkspaceText.ts
new file mode 100644
index 00000000..b1ed197f
--- /dev/null
+++ b/client/src/hooks/useWorkspaceText.ts
@@ -0,0 +1,86 @@
+/**
+ * Capped client-side fetch of a workspace file's TEXT body.
+ *
+ * The first client-side file-content fetch in the repo. The workspace route
+ * serves non-media files with `Content-Disposition: attachment`, which blocks
+ * navigation/embedding but NOT `fetch()` reading the body — so markdown /
+ * code / JSON / HTML rendering needs no backend change.
+ *
+ * Bounded by construction: the body is read through a streamed reader and
+ * cancelled at the cap, so a 100 MB log never lands in memory. jsdom (tests)
+ * lacks `res.body` — falls back to `res.text()` + slice.
+ */
+
+import { useQuery } from '@tanstack/react-query';
+
+import { buildApiUrl } from '../config/api';
+import { STALE_TIME } from '../lib/queryConfig';
+import type { WorkspaceFileRef } from '../types/workspaceFiles';
+
+export const TEXT_FETCH_CAP_BYTES = 512 * 1024;
+
+export interface FetchedText {
+ text: string;
+ truncated: boolean;
+}
+
+export async function fetchWorkspaceText(
+ url: string,
+ capBytes: number = TEXT_FETCH_CAP_BYTES,
+): Promise<FetchedText> {
+ const response = await fetch(buildApiUrl(url), { credentials: 'include' });
+ if (!response.ok) {
+ // A 401 must surface as an error state, never a blank pane.
+ throw new Error(`File request failed (${response.status})`);
+ }
+
+ const body = response.body;
+ if (!body) {
+ const whole = await response.text();
+ const truncated = whole.length > capBytes;
+ return { text: truncated ? whole.slice(0, capBytes) : whole, truncated };
+ }
+
+ const reader = body.getReader();
+ const decoder = new TextDecoder('utf-8', { fatal: false });
+ const chunks: string[] = [];
+ let received = 0;
+ let truncated = false;
+
+ for (;;) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ if (value) {
+ received += value.byteLength;
+ if (received > capBytes) {
+ const keep = value.byteLength - (received - capBytes);
+ chunks.push(decoder.decode(value.subarray(0, Math.max(0, keep)), { stream: true }));
+ truncated = true;
+ await reader.cancel();
+ break;
+ }
+ chunks.push(decoder.decode(value, { stream: true }));
+ }
+ }
+ chunks.push(decoder.decode());
+ return { text: chunks.join(''), truncated };
+}
+
+/**
+ * Query wrapper. The key includes `size_bytes` + `modified_at`, so a
+ * re-pushed file arrives under a fresh key with no invalidation plumbing.
+ */
+export function useWorkspaceTextQuery(ref: WorkspaceFileRef | null | undefined) {
+ return useQuery<FetchedText, Error>({
+ queryKey: [
+ 'workspaceText',
+ ref?.url ?? '',
+ ref?.size_bytes ?? 0,
+ ref?.modified_at ?? '',
+ ],
+ queryFn: () => fetchWorkspaceText(ref!.url!),
+ enabled: !!ref?.url,
+ staleTime: STALE_TIME.SHORT,
+ retry: 1,
+ });
+}
diff --git a/client/src/lib/canvasBoard.ts b/client/src/lib/canvasBoard.ts
new file mode 100644
index 00000000..52d90716
--- /dev/null
+++ b/client/src/lib/canvasBoard.ts
@@ -0,0 +1,53 @@
+/**
+ * Wire types + React Query identity for the Canvas node's content board.
+ *
+ * Declarations only — every decision is made server-side
+ * (`server/nodes/tool/canvas/`): items arrive with finished `FileRef`s, the
+ * `canvas_updated` broadcast carries identity + revision only, and content
+ * bodies flow exclusively through the authorized `canvas_list` handler
+ * (files) or the workspace HTTP route (bytes/text).
+ */
+
+import type { WorkspaceFileRef } from '../types/workspaceFiles';
+
+export type CanvasItemKind = 'file' | 'url' | 'note';
+
+/** One board item — `server/nodes/tool/canvas/_store.py::_serialize`. */
+export interface CanvasItem {
+ id: string;
+ kind: CanvasItemKind;
+ title: string | null;
+ /** Serialized FileRef for kind 'file'; null otherwise. */
+ ref: WorkspaceFileRef | null;
+ /** http(s) address for kind 'url'; null otherwise. */
+ url: string | null;
+ /** Markdown body for kind 'note' (capped server-side); null otherwise. */
+ content: string | null;
+ language: string | null;
+ source: 'agent' | 'workflow' | string;
+ created_at: string | null;
+}
+
+/** Response to `canvas_list`. */
+export interface CanvasListResponse {
+ success: boolean;
+ error?: string;
+ items?: CanvasItem[];
+ revision?: number;
+}
+
+/** Identity carried by the `canvas_updated` broadcast (no content). */
+export interface CanvasUpdatedIdentity {
+ workflow_id?: string | null;
+ node_id?: string | null;
+ revision?: number;
+}
+
+/** One cache entry per workflow + canvas node (todoQuery.ts shape). */
+export const canvasBoardQueryKey = (
+ workflowId: string | null | undefined,
+ nodeId: string,
+) => ['canvasBoard', workflowId ?? 'unsaved', nodeId] as const;
+
+/** Prefix for broadcast-driven invalidation of every mounted board. */
+export const CANVAS_BOARD_QUERY_PREFIX = ['canvasBoard'] as const;
diff --git a/client/src/stores/__tests__/canvasDockStore.test.ts b/client/src/stores/__tests__/canvasDockStore.test.ts
new file mode 100644
index 00000000..ac3d881b
--- /dev/null
+++ b/client/src/stores/__tests__/canvasDockStore.test.ts
@@ -0,0 +1,108 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { CanvasItem } from '../../lib/canvasBoard';
+import { useCanvasDockStore } from '../canvasDockStore';
+
+const ephemeral: CanvasItem = {
+ id: 'ephemeral-x',
+ kind: 'note',
+ title: 'Preview',
+ ref: null,
+ url: null,
+ content: 'hello',
+ language: null,
+ source: 'workflow',
+ created_at: null,
+};
+
+const resetStore = () =>
+ useCanvasDockStore.setState({
+ open: false,
+ widthPx: 380,
+ autoOpen: true,
+ followMode: false,
+ mode: 'node',
+ selectedNodeId: null,
+ ephemeralItem: null,
+ });
+
+describe('canvasDockStore.notifyPushed', () => {
+ beforeEach(() => {
+ localStorage.clear();
+ resetStore();
+ });
+
+ it('opens on the pushed node when closed and autoOpen is on', () => {
+ useCanvasDockStore.getState().notifyPushed('canvas-1');
+ const state = useCanvasDockStore.getState();
+ expect(state.open).toBe(true);
+ expect(state.mode).toBe('node');
+ expect(state.selectedNodeId).toBe('canvas-1');
+ });
+
+ it('does nothing when closed and autoOpen is off', () => {
+ useCanvasDockStore.setState({ autoOpen: false });
+ useCanvasDockStore.getState().notifyPushed('canvas-1');
+ expect(useCanvasDockStore.getState().open).toBe(false);
+ expect(useCanvasDockStore.getState().selectedNodeId).toBeNull();
+ });
+
+ it('follows the pushed node when already open in node mode', () => {
+ useCanvasDockStore.setState({ open: true, selectedNodeId: 'canvas-1' });
+ useCanvasDockStore.getState().notifyPushed('canvas-2');
+ expect(useCanvasDockStore.getState().selectedNodeId).toBe('canvas-2');
+ });
+
+ it('never yanks a deliberate ephemeral preview', () => {
+ useCanvasDockStore.getState().showEphemeral(ephemeral);
+ useCanvasDockStore.getState().notifyPushed('canvas-1');
+ const state = useCanvasDockStore.getState();
+ expect(state.mode).toBe('ephemeral');
+ expect(state.ephemeralItem).toEqual(ephemeral);
+ });
+});
+
+describe('canvasDockStore prefs', () => {
+ beforeEach(() => {
+ localStorage.clear();
+ resetStore();
+ });
+
+ it('persists open/width/autoOpen/followMode and clamps width', () => {
+ useCanvasDockStore.getState().setWidth(5000);
+ expect(useCanvasDockStore.getState().widthPx).toBe(1200);
+ useCanvasDockStore.getState().setWidth(10);
+ expect(useCanvasDockStore.getState().widthPx).toBe(280);
+
+ useCanvasDockStore.getState().toggle();
+ useCanvasDockStore.getState().setFollowMode(true);
+
+ const raw = localStorage.getItem('canvas_dock_prefs_v1');
+ expect(raw).toBeTruthy();
+ const parsed = JSON.parse(raw as string);
+ expect(parsed).toMatchObject({ open: true, widthPx: 280, followMode: true });
+ // Session-only fields never persist.
+ expect(parsed).not.toHaveProperty('selectedNodeId');
+ expect(parsed).not.toHaveProperty('ephemeralItem');
+ });
+
+ it('falls back to defaults on corrupt stored prefs', async () => {
+ localStorage.setItem('canvas_dock_prefs_v1', '{not json');
+ vi.resetModules();
+ const fresh = await import('../canvasDockStore');
+ const state = fresh.useCanvasDockStore.getState();
+ expect(state.open).toBe(false);
+ expect(state.widthPx).toBe(380);
+ expect(state.autoOpen).toBe(true);
+ });
+
+ it('showEphemeral opens the dock and backToNode returns to the board', () => {
+ useCanvasDockStore.getState().showEphemeral(ephemeral);
+ expect(useCanvasDockStore.getState().open).toBe(true);
+ expect(useCanvasDockStore.getState().mode).toBe('ephemeral');
+
+ useCanvasDockStore.getState().backToNode();
+ expect(useCanvasDockStore.getState().mode).toBe('node');
+ expect(useCanvasDockStore.getState().ephemeralItem).toBeNull();
+ });
+});
diff --git a/client/src/stores/canvasDockStore.ts b/client/src/stores/canvasDockStore.ts
new file mode 100644
index 00000000..cd3afab1
--- /dev/null
+++ b/client/src/stores/canvasDockStore.ts
@@ -0,0 +1,140 @@
+/**
+ * Docked Canvas sidebar state.
+ *
+ * A small Zustand store (nodeStatusStore shape: slice-selector reads,
+ * `getState()` writes from the WS handler and click-to-preview call sites)
+ * — deliberately NOT on useAppStore or WebSocketContext.value, both of
+ * which are context fan-out traps for high-frequency or unrelated state.
+ *
+ * Prefs (open / width / autoOpen / followMode) persist to localStorage via
+ * a zod-validated envelope, the ConsolePanel idiom — no persist middleware.
+ * Node selection and ephemeral items are session-only: node ids are
+ * workflow-scoped and meaningless across reloads.
+ */
+
+import { z } from 'zod';
+import { create } from 'zustand';
+
+import type { CanvasItem } from '../lib/canvasBoard';
+
+const dockPrefsSchema = z.object({
+ open: z.boolean().default(false),
+ widthPx: z.number().min(280).max(1200).default(380),
+ autoOpen: z.boolean().default(true),
+ followMode: z.boolean().default(false),
+});
+type CanvasDockPrefs = z.infer<typeof dockPrefsSchema>;
+const DOCK_PREFS_KEY = 'canvas_dock_prefs_v1';
+
+export const DOCK_MIN_WIDTH = 280;
+export const DOCK_MAX_WIDTH = 1200;
+
+function loadDockPrefs(): CanvasDockPrefs {
+ try {
+ const raw = localStorage.getItem(DOCK_PREFS_KEY);
+ if (raw) {
+ const parsed = dockPrefsSchema.safeParse(JSON.parse(raw));
+ if (parsed.success) return parsed.data;
+ }
+ } catch { /* fall through to defaults */ }
+ return dockPrefsSchema.parse({});
+}
+
+function saveDockPrefs(prefs: CanvasDockPrefs): void {
+ try {
+ localStorage.setItem(DOCK_PREFS_KEY, JSON.stringify(prefs));
+ } catch { /* ignore */ }
+}
+
+interface CanvasDockState {
+ open: boolean;
+ widthPx: number;
+ autoOpen: boolean;
+ followMode: boolean;
+ /** 'node' renders a Canvas node's board; 'ephemeral' a transient preview. */
+ mode: 'node' | 'ephemeral';
+ selectedNodeId: string | null;
+ ephemeralItem: CanvasItem | null;
+
+ toggle: () => void;
+ close: () => void;
+ setWidth: (px: number) => void;
+ setAutoOpen: (value: boolean) => void;
+ setFollowMode: (value: boolean) => void;
+ /** Show a Canvas node's board (also switches out of ephemeral mode). */
+ selectNode: (nodeId: string) => void;
+ /** Open the dock on a transient item that lives in no node's board. */
+ showEphemeral: (item: CanvasItem) => void;
+ /** Leave ephemeral mode, back to the selected node's board. */
+ backToNode: () => void;
+ /**
+ * A canvas_updated broadcast for the CURRENT workflow (caller verifies).
+ * Closed + autoOpen -> open on the pushed node; open in node mode ->
+ * follow the pushed node; ephemeral mode -> never yank a deliberate
+ * preview.
+ */
+ notifyPushed: (nodeId: string) => void;
+}
+
+const persisted = loadDockPrefs();
+
+const persist = (state: CanvasDockState) =>
+ saveDockPrefs({
+ open: state.open,
+ widthPx: state.widthPx,
+ autoOpen: state.autoOpen,
+ followMode: state.followMode,
+ });
+
+export const useCanvasDockStore = create<CanvasDockState>((set, get) => ({
+ open: persisted.open,
+ widthPx: persisted.widthPx,
+ autoOpen: persisted.autoOpen,
+ followMode: persisted.followMode,
+ mode: 'node',
+ selectedNodeId: null,
+ ephemeralItem: null,
+
+ toggle: () => {
+ set((state) => ({ open: !state.open }));
+ persist(get());
+ },
+ close: () => {
+ set({ open: false });
+ persist(get());
+ },
+ setWidth: (px) => {
+ const clamped = Math.min(DOCK_MAX_WIDTH, Math.max(DOCK_MIN_WIDTH, Math.round(px)));
+ set({ widthPx: clamped });
+ persist(get());
+ },
+ setAutoOpen: (value) => {
+ set({ autoOpen: value });
+ persist(get());
+ },
+ setFollowMode: (value) => {
+ set({ followMode: value });
+ persist(get());
+ },
+ selectNode: (nodeId) =>
+ set({ mode: 'node', selectedNodeId: nodeId, ephemeralItem: null }),
+ showEphemeral: (item) => {
+ set({ mode: 'ephemeral', ephemeralItem: item, open: true });
+ persist(get());
+ },
+ backToNode: () => set({ mode: 'node', ephemeralItem: null }),
+
+ notifyPushed: (nodeId) => {
+ const state = get();
+ if (state.mode === 'ephemeral') return;
+ if (!state.open) {
+ if (!state.autoOpen) return;
+ set({ open: true, mode: 'node', selectedNodeId: nodeId });
+ persist(get());
+ return;
+ }
+ if (state.selectedNodeId !== nodeId) {
+ set({ mode: 'node', selectedNodeId: nodeId });
+ }
+ },
+}));
diff --git a/client/src/types/INodeProperties.ts b/client/src/types/INodeProperties.ts
index b40cc7d8..dafced16 100644
--- a/client/src/types/INodeProperties.ts
+++ b/client/src/types/INodeProperties.ts
@@ -241,6 +241,9 @@ export interface INodeUIHints {
isProcessManagerPanel?: boolean;
/** MiddleSection: render the workspace gallery (drag files to params). */
isGalleryPanel?: boolean;
+ /** MiddleSection: render the pushed-content Canvas board. The docked
+ * canvas sidebar reads the same flag to find Canvas nodes. */
+ isCanvasPanel?: boolean;
/** Special-case panel for gmaps_create with map preview. */
showLocationPanel?: boolean;
/** ConsolePanel: this node is a chat-message target. */
diff --git a/client/src/types/workspaceFiles.ts b/client/src/types/workspaceFiles.ts
index d8428d92..3dba12c9 100644
--- a/client/src/types/workspaceFiles.ts
+++ b/client/src/types/workspaceFiles.ts
@@ -13,7 +13,7 @@
*/
/** What the workspace route will let a browser render in place. */
-export type PreviewKind = 'image' | 'audio' | 'video' | 'none';
+export type PreviewKind = 'image' | 'audio' | 'video' | 'pdf' | 'none';
/** One entry in a directory listing. `path` is always workspace-relative. */
export interface WorkspaceEntry {
diff --git a/docs-internal/canvas_node.md b/docs-internal/canvas_node.md
new file mode 100644
index 00000000..63242d93
--- /dev/null
+++ b/docs-internal/canvas_node.md
@@ -0,0 +1,433 @@
+# Canvas Node — pushed-content display board (panel + docked sidebar)
+
+The `canvas` node is the platform's viewing surface — the Claude/ChatGPT-Canvas
+analog. Agents and workflow runs push content onto a per-node **board**
+(workspace file references, external URLs, small markdown notes), and the
+board renders in two hosts that share one renderer: the node's full-height
+parameter panel, and a **docked, resizable right-side sidebar** that stays
+open while working on the graph, auto-opens when content is pushed, and
+doubles as the click-to-preview surface for workspace files.
+
+Everything here composes existing patterns; the doc records which one each
+piece copies and the few places where a *new* decision had to be made (the
+iframe sandbox matrix, the PDF inline exception, the first client-side
+file-content fetch).
+
+| Piece | Pattern copied |
+|---|---|
+| Node shape | `nodes/tool/write_todos/` (ToolNode + `input-main` handle + per-scope store + metadata-only broadcast + panel WS handlers) |
+| Durable store | `services/data/mount_store.py` / `services/memory/tool_store.py` (plugin-owned SQLModel tables, `ensure_schema(checkfirst=True)`, zero `core/database.py` edits) |
+| WS handler security | `nodes/tool/simple_memory/_handlers.py` preamble, copied verbatim |
+| Broadcast | `nodes/context/_events.py` (direct `get_status_broadcaster().broadcast`, identity-only payload) |
+| Panel host | `GalleryPanel` (full-height MiddleSection panel via a uiHints flag) |
+| Live updates | ContextPanel posture (`canvas_updated` → invalidate `['canvasBoard']` → panel refetches through the authorized handler) |
+| Dock resize / prefs | ConsolePanel (`usePanelResize`, now **extracted to `client/src/hooks/usePanelResize.ts`**; zod-validated localStorage prefs) |
+| Dock state | `stores/nodeStatusStore.ts` (small Zustand store, slice-selector reads, `getState()` writes) |
+
+## Architecture
+
+```
+ agent tool call `canvas(...)` upstream node output
+ (output-tool -> agent input-tools) (input-main edge)
+ \ /
+ v v
+ nodes/tool/canvas/__init__.py @Operation("display")
+ | paths -> resolve_media + stat -> FileRef (never bytes)
+ | url -> http(s) check
+ | content -> 64KB truncate_note
+ | (none) -> structural FileRef scan of connected_outputs
+ v
+ _store.py CanvasStore (canvas_boards / canvas_items, revision++)
+ v
+ _events.py broadcast `canvas_updated` {workflow_id, node_id, revision}
+ v
+ WebSocketContext case -> invalidate ['canvasBoard'] + dock notifyPushed
+ v v
+ CanvasPanel (parameter panel) CanvasDock (right sidebar)
+ \_______________ ________________/
+ \/
+ CanvasContent (one shared renderer)
+ media carousel | markdown/code/JSON/text | sandboxed web | PDF | binary
+```
+
+Content bodies never ride the board or the broadcast: files are fetched by
+the client over the existing `GET /api/workspace/{workflow_id}/files/{path}`
+route; note bodies come back only through the authorized `canvas_list`
+handler.
+
+## Backend — [`server/nodes/tool/canvas/`](../server/nodes/tool/canvas/__init__.py)
+
+### The node
+
+`CanvasNode(ToolNode)`, `type="canvas"`, `group=("tool","ai")`,
+`tool_name="canvas"` with `tool_schema_locked=True` (stale persisted
+ToolSchema rows cannot rename or reshape the tool — simpleMemory precedent).
+Declared handles are `input-main` (left) + `output-tool` (top): declared
+handles win wholesale on the frontend, so no `hide_*` fiddling is needed
+despite `component_kind="tool"`.
+
+Two deliberate overrides of what the group/base would otherwise derive:
+
+- `ui_hints = {"isCanvasPanel": True, "isToolPanel": True, "isConfigNode": False}` —
+ the `tool` group auto-derives `isConfigNode: True`, but the Canvas node's
+ `input-main` is a real runtime dataflow edge, so it must present as a
+ normal node (no parent-input inheritance). Explicit wins over
+ auto-derivation, the sanctioned opt-out.
+- `annotations = {"destructive": False, "readonly": False, "open_world": False}` —
+ overrides ToolNode's `readonly: True` default because `display` writes the
+ durable board.
+
+`hideRunButton` is deliberately **not** set: Run with panel-typed params
+(including `{{node.field}}` templates) is how the workflow-edge path is
+authored and debugged.
+
+### The single `display` op
+
+One `@Operation("display")` serves the agent tool call, the Run button, and
+the workflow edge identically (`_pick_operation` runs a single-op node's
+lone op regardless of `parameters["operation"]`). Item sources, in order:
+
+1. **`paths`** (≤ 20/call, `NodeUserError` past the cap): each path goes
+ through `resolve_media` containment + a `stat` and becomes a serialized
+ `FileRef` built gallery-style — **never `coerce_file_param`**, which
+ reads full bytes; the board stores a pointer, and reading a 500 MB video
+ to register it would be pure waste. `kind` stays `"file"` even for
+ media, because `kind="audio"` asserts an `inspect_audio` probe this code
+ never ran.
+2. **`url`**: scheme must be `http`/`https` (`javascript:`/`file:` are
+ user-correctable `NodeUserError`s).
+3. **`content`**: markdown note, truncated at 64 KB with a visible
+ `… [truncated]` marker — a workflow run must never die on an oversized
+ note; the truncation is reported in `message` instead.
+4. **Connected-outputs scan** (only when 1–3 produced nothing): a recursive,
+ depth-capped structural walk of `ctx.raw["connected_outputs"]` collecting
+ serialized `FileRef`s. A dict is a ref iff it *validates* as one —
+ `FileRef`'s `extra="forbid"` makes near-misses (e.g. a gallery listing
+ row) fail while the `ref` nested inside them is found. Deduped by path,
+ capped at 20. This is what makes `tts → canvas` work with a zero-config
+ edge. The node is therefore in `NodeExecutor._NEEDS_CONNECTED_OUTPUTS` —
+ the one core edit, sanctioned by that frozenset's own comment, and it
+ covers direct-run and both Temporal paths because all of them funnel
+ through `NodeExecutor._dispatch`.
+
+An empty call raises `NodeUserError("Nothing to display — pass paths, url,
+or content …")` so the LLM gets a one-line correctable error.
+
+**Output payload discipline**: the op returns `{message, count, revision,
+added: [{id, kind, title}]}` — ids and counts only, never note bodies and
+never echoed refs, because a node result is persisted three ways, broadcast,
+retained in the status cache, copied into downstream activity inputs, and
+replayed into LLM context every turn.
+
+`source` labeling (`"agent"` vs `"workflow"`) keys on `_tool_config` being
+present in `ctx.raw` — `execute_as_tool` sets it around the op body and
+nothing else does. Cosmetic; a wrong label misleads nobody about security.
+
+### Params coercions (the panel/LLM boundary)
+
+`CanvasParams` is flat on purpose — it **is** the LLM tool schema (nested
+models would emit `$defs`, which the tool-schema invariant rejects), and it
+deliberately has no docstring because a Pydantic model docstring becomes the
+schema description the model reads. Boundary coercions:
+
+- `coerce_blank_params` in a `model_validator(mode="before")` — the panel
+ writes `""` for cleared fields whatever the type; blanks drop for the
+ non-str fields (`paths`, `mode`) so defaults apply.
+- `paths` accepts a JSON-encoded array string (Gemini stringifies array tool
+ args), a bare path string, and serialized ref dicts (a `{{node.files}}`
+ template resolves to a list of dicts) reduced to their `path` key.
+ Malformed JSON passes through so Pydantic raises a correctable error.
+
+### The store — [`_store.py`](../server/nodes/tool/canvas/_store.py)
+
+Plugin-owned tables, mount_store mechanism: importing the plugin registers
+`CanvasBoard` (`canvas_boards`: board id, identity columns, `revision`) and
+`CanvasItemRow` (`canvas_items`: kind/title/`ref` JSON/url/`content`
+Text/language/source/position) into SQLModel metadata before
+`Database.startup()`'s `create_all`; `ensure_schema()` (per-engine set +
+lock + `checkfirst=True`) covers late importers. No migration framework, no
+`core/database.py` edits.
+
+Scope is `CanvasScope(owner_id, workflow_id, node_id)` with the
+`"unsaved"` workflow fallback; the board id is
+`"canv_" + sha256("canvas:v1\0owner\0workflow\0node")[:48]` — the version
+string is baked into the hash material from day one (the
+`todo_session_key` lesson: keys that aren't versioned eventually need to
+be, retroactively).
+
+Every mutation is one transaction that bumps `revision`. Caps:
+`CANVAS_MAX_ITEMS = 200` (FIFO eviction by `position`),
+`CANVAS_NOTE_MAX_BYTES = 64 KB`, `CANVAS_MAX_PATHS_PER_CALL = 20`.
+`_serialize` emits the fixed wire shape with a stable, null-filled key set.
+
+### Panel WS handlers — [`_handlers.py`](../server/nodes/tool/canvas/_handlers.py)
+
+`canvas_list` / `canvas_remove` / `canvas_clear`, all `@ws_response` (never
+`@ws_handler` — a user-correctable failure must be one WARN line, not an
+ERROR with a traceback), self-registered via `register_ws_handlers` from the
+package `__init__`. Security preamble copied verbatim from simple_memory:
+
+1. `_require_external_socket` — the unauthenticated `/ws/internal` worker
+ socket is refused (defence in depth behind the deny-by-default
+ `services/authz/ws_surface.py` allowlist, which new handlers never join).
+2. `_authenticated_owner` — identity from `websocket.state`/`scope` only,
+ never from request data; `"owner"` fallback mirrors
+ `NodeContext.user_id`'s trusted default.
+3. Graph-ownership resolution — `workflow_id` + `node_id` required, the
+ persisted workflow must exist, its `owner_id` must match, and **exactly
+ one** node with that id AND `type == "canvas"` must be in the graph.
+ Neither the client nor the model can supply a scope identifier.
+
+Trade-off shipped knowingly (same as simpleMemory): the op can write to an
+`"unsaved"`-scoped board, but the panel handlers require a **saved**
+workflow (the ownership check needs the DB row) — an unsaved canvas's board
+becomes readable after the first save.
+
+Mutating handlers broadcast `canvas_updated` so every open surface (other
+tabs included) refetches.
+
+### Events — [`_events.py`](../server/nodes/tool/canvas/_events.py)
+
+`canvas_updated` is a CloudEvents `WorkflowEvent`
+(`source: opencompany://nodes/canvas`,
+`type: com.opencompany.canvas.updated`, `subject: node_id`) whose data is
+**identity + revision only** — `{workflow_id, node_id, revision}`. It is
+broadcast **directly** via `get_status_broadcaster().broadcast(...)`, not
+`dispatch.emit`: no node type registers a canary consumer for
+`com.opencompany.canvas.*`, so `emit` would run a Temporal Visibility query
+guaranteed to match nothing, once per `display` call. No item content rides
+the broadcast because it fans out to every connected socket; content flows
+only through the authorized `canvas_list`.
+
+## Wire contract
+
+```ts
+// One board item — server/nodes/tool/canvas/_store.py::_serialize
+interface CanvasItem {
+ id: string;
+ kind: 'file' | 'url' | 'note';
+ title: string | null;
+ ref: WorkspaceFileRef | null; // kind 'file'
+ url: string | null; // kind 'url'
+ content: string | null; // kind 'note' (64KB-capped markdown)
+ language: string | null;
+ source: 'agent' | 'workflow' | string;
+ created_at: string | null;
+}
+```
+
+| Channel | Shape |
+|---|---|
+| `canvas_list {workflow_id, node_id}` | `{success, items: CanvasItem[], revision}` |
+| `canvas_remove {workflow_id, node_id, item_id}` | `{success, removed, revision}` + broadcast |
+| `canvas_clear {workflow_id, node_id}` | `{success, cleared, revision}` + broadcast |
+| broadcast `canvas_updated` | `{type: 'canvas_updated', data: <WorkflowEvent>}`, data.data = `{workflow_id, node_id, revision}` |
+| tool `canvas(title?, paths?, url?, content?, language?, mode)` | flat schema, no `$defs`; `mode: 'append' \| 'replace'` |
+
+Client-side types + query keys live in
+[`client/src/lib/canvasBoard.ts`](../client/src/lib/canvasBoard.ts):
+`canvasBoardQueryKey(workflowId ?? 'unsaved', nodeId)` (todoQuery shape),
+prefix `['canvasBoard']` for broadcast-driven invalidation.
+
+## Frontend — two hosts, one renderer
+
+### Hosts
+
+- **[`CanvasPanel.tsx`](../client/src/components/parameterPanel/CanvasPanel.tsx)**
+ — the full-height parameter-panel host, dispatched by
+ `uiHints.isCanvasPanel` in `MiddleSection` (gallery pattern: flag read +
+ description-suppression chain + ternary-ladder branch). Header carries the
+ item-count badge and Clear; body is the shared renderer. Items are
+ references — removing one never deletes the underlying file, which is why
+ Clear is a plain ghost button and not an `AlertDialog`.
+- **[`CanvasDock.tsx`](../client/src/components/ui/CanvasDock.tsx)** — the
+ new docked surface, mounted as the last flex child of Dashboard's
+ main-content row (rightmost edge). Left-edge drag handle via the shared
+ `usePanelResize` (dragging left widens; clamped 280–1200 px and ≤ 60 % of
+ the viewport), `transition-[width]` disabled while dragging. Header: node
+ selector (a Select when the workflow has more than one Canvas node —
+ ConsolePanel's node-selector precedent; nodes are found by
+ `resolveNodeDescription(type)?.uiHints?.isCanvasPanel`, never by the type
+ string), ephemeral "Preview" badge + Back, close. TopToolbar carries the
+ toggle button (Monitor icon, `aria-pressed`, action-tools tokens),
+ reading the dock store directly — the state is not Dashboard's to thread.
+
+### Dock state — [`stores/canvasDockStore.ts`](../client/src/stores/canvasDockStore.ts)
+
+A small Zustand store (slice-selector reads; `getState()` writes from the WS
+handler and click-to-preview call sites) — deliberately not on `useAppStore`
+or `WebSocketContext.value`, both context-fan-out traps. Prefs
+(`open`, `widthPx`, `autoOpen`, `followMode`) persist to localStorage under
+`canvas_dock_prefs_v1` via a zod-validated envelope (ConsolePanel idiom);
+node selection and ephemeral items are session-only because node ids are
+workflow-scoped.
+
+`notifyPushed(nodeId)` rules (invoked from the `canvas_updated` case for the
+**current** workflow only): closed + `autoOpen` → open on the pushed node;
+open in node mode → follow the pushed node; **ephemeral mode → never yank a
+deliberate preview** (the invalidation still freshens data for later).
+
+### Live updates
+
+One switch case in `WebSocketContext.tsx` beside the `context.*` cases:
+invalidate the `['canvasBoard']` prefix (a no-op unless a surface is
+mounted) + the workflow-scoped `notifyPushed`. **Because a switch case
+exists, the default-case `addEventListener` fan-out never fires for this
+type — never `addEventListener('canvas_updated')` anywhere.**
+
+### The shared renderer — [`parameterPanel/canvas/CanvasContent.tsx`](../client/src/components/parameterPanel/canvas/CanvasContent.tsx)
+
+The item list **is** the carousel: one active item (only the active item
+mounts — no N live videos/iframes), prev/next in the footer,
+`pinnedId: null` meaning "follow newest" (the chat stick-to-bottom rule: a
+pushed item surfaces automatically unless the user deliberately navigated
+back; navigating onto the last item resumes following). Arrow/Home/End keys
+work on the focused `role="group"` only — no document-level listeners,
+which would fight React Flow node nudging.
+
+**Follow-latest** (the browser-automation live view): when the active item
+is a workspace image, a Switch enables a visibility-gated 5 s poll of the
+existing `list_workspace_files` handler on the image's folder, rendering the
+newest image entry in place — zero new backend. Persisted as the dock's
+`followMode` pref.
+
+Renderer dispatch is a pure function
+([`canvasKinds.ts`](../client/src/components/parameterPanel/canvas/canvasKinds.ts)),
+mime before extension, script-bearing/document verdicts before the generic
+text tiers:
+
+| Verdict | Condition | Renders |
+|---|---|---|
+| `note` | `kind === 'note'` | ReactMarkdown prose (no fetch) |
+| `web-external` | `kind === 'url'` | sandboxed iframe (below) |
+| `media-image/video/audio` | mime prefix or ref.kind | native element, FilePreviewDialog's honest-fallback idiom |
+| `pdf` | `application/pdf` / `.pdf` | plain same-origin iframe (browser viewer) |
+| `web-srcdoc` | `text/html` / `.html` | capped fetch → `srcDoc` sandbox iframe; over-cap → refusal + Download (a half-rendered page misleads) |
+| `markdown` / `json` / `code` / `text` | ext/mime tiers (code set reuses gallery's `fileIcons` family) | [`TextFileView.tsx`](../client/src/components/parameterPanel/canvas/TextFileView.tsx): prose / JsonView / Prism on the `--code-*` tokens (Prism skipped > 100 KB) |
+| `binary` | everything else | glyph + meta + Download |
+
+### First client-side file-content fetch — [`hooks/useWorkspaceText.ts`](../client/src/hooks/useWorkspaceText.ts)
+
+Text bodies (markdown/code/JSON/HTML) come over the existing workspace route
+with **no backend change**: `Content-Disposition: attachment` blocks
+navigation/embedding but not `fetch()` reading the body. Bounded by
+construction — a streamed reader cancelled at `TEXT_FETCH_CAP_BYTES`
+(512 KB) so a 100 MB log never lands in memory; `truncated` renders a
+banner. Non-ok throws with the status (a 401 must surface as an error state,
+never a blank pane). The query key includes `size_bytes` + `modified_at`,
+so a re-pushed file self-busts with no invalidation plumbing.
+
+### Click-to-preview
+
+`FilePreviewDialog` (gallery) gained an "Open in side panel" button: it
+builds an ephemeral `CanvasItem` from the entry's server-built ref, calls
+`showEphemeral`, closes the dialog **and clears the selected node** — the
+dock sits behind the 95vw parameter modal, so moving the preview to the
+persistent surface must close the modal; that is the point of the
+affordance. Ephemeral items live in no board and are never persisted.
+
+## Security decisions
+
+The iframe surfaces are zero-precedent territory (there was no `<iframe>`
+anywhere in `client/src`); these attributes are the decisions, locked by
+regression tests asserting the exact sandbox values:
+
+| Surface | Attributes | Why |
+|---|---|---|
+| External URL | `sandbox="allow-scripts allow-forms"`, `referrerPolicy="no-referrer"` | No `allow-same-origin` (opaque origin), no `allow-top-navigation` (a framed page must never navigate the app away), no `allow-popups` — the permanent "Open in new tab" button is the escape hatch, and it must always be visible because X-Frame-Options / `frame-ancestors` denial is undetectable cross-origin. |
+| Workspace HTML | fetch text → `srcDoc` + `sandbox="allow-scripts"` | Never `allow-same-origin`: a stored-XSS payload in a workspace file executes with no origin, no cookies, no app storage. Workspace HTML never enters the app DOM (also why no sanitizer dependency exists). The backend's `NEVER_INLINE` rule is **respected, not worked around** — HTML still serves `attachment` from the route. |
+| PDF | plain same-origin iframe | Browser-native viewer; sandboxing breaks it in several engines. Served inline because `application/pdf` joined a new `INLINE_EXACT` frozenset in [`services/media/preview.py`](../server/services/media/preview.py) — an **exact-match** addition (no other `application/*` type gains inline serving as a side effect), `NEVER_INLINE` untouched, `PreviewKind` gains `"pdf"` on both sides of the wire, locked by `tests/routers/test_workspace.py`. The exposure class is the same as images, not the markup-from-app-origin class the deny-set guards. |
+
+Plus: broadcasts carry no content (ownership is enforced at `canvas_list`);
+the model cannot choose a scope (trusted `NodeContext` only); handler scope
+resolves from the persisted graph, not the request.
+
+## Browser screenshot persistence — [`server/nodes/browser/_screenshots.py`](../server/nodes/browser/_screenshots.py)
+
+Shipped alongside the node because it is what gives the board its most
+interesting content. Both browser plugins historically leaked screenshots in
+unusable shapes: `browser` returned whatever agent-browser printed (a base64
+blob — a media-contract violation that also hits the 100 KB CLI-output
+truncation), `browserHarness` an absolute path under
+`<DATA_DIR>/daemons/browser-harness/tmp/` that no HTTP route can serve.
+
+The shared helper lands the bytes in the workflow workspace via
+`write_media(kind="image")` so a screenshot becomes a ~400 B `FileRef`:
+
+- `persist_screenshot_from_payload(data, ctx, fmt)` (the `browser` node's
+ `screenshot` op): probes the known inline-base64 keys (only `"base64"` is
+ evidenced in-repo; the rest are tolerated probes) then saved-file-path
+ keys, returns `(ref, consumed_key)` so the caller drops exactly the bulky
+ field from the payload.
+- `persist_screenshot_file(path, ctx, contained_under)` (the harness
+ `screenshot` op): reads **only** files contained under the harness runtime
+ dir — printed process output is not a licence to read arbitrary files.
+
+**Tolerance is the contract**: an unrecognized payload shape, a missing
+workspace, or a write failure logs one warning and returns `None`; the
+browser operation itself never breaks over persistence. Sanity bounds
+(128 B – 25 MB) refuse garbage. Tests:
+`server/tests/nodes/test_browser_screenshots.py`.
+
+## Edits outside the plugin folder (the complete list)
+
+| File | Edit | Justification |
+|---|---|---|
+| `server/services/node_executor.py` | `"canvas"` in `_NEEDS_CONNECTED_OUTPUTS` | The frozenset's own comment sanctions it; covers direct-run + both Temporal paths |
+| `server/config/node_allowlist.json` | `"canvas"` in `enabled_nodes` | Normal-mode palette visibility (positive list) |
+| `server/tests/test_node_spec.py` | `"isCanvasPanel"` in the uiHints `known` set | The test's own failure message instructs this |
+| `server/services/media/preview.py` + `server/tests/routers/test_workspace.py` | `INLINE_EXACT` / `"pdf"` | The PDF surface; `NEVER_INLINE` untouched |
+| `server/nodes/browser/{browser,browser_harness}/__init__.py` | screenshot post-process | Plugin-folder edits of the browser plugins |
+| `client/src/{types/INodeProperties.ts, types/workspaceFiles.ts, components/parameterPanel/MiddleSection.tsx, contexts/WebSocketContext.tsx, Dashboard.tsx, components/ui/TopToolbar.tsx, components/ui/ConsolePanel.tsx, components/parameterPanel/gallery/FilePreviewDialog.tsx}` | hint type, `'pdf'` PreviewKind, panel dispatch, `canvas_updated` case, dock mount, toggle, `usePanelResize` extraction, click-to-preview | The standard new-panel checklist + the dock integration |
+
+Notably **not** edited: `routers/websocket.py`, `main.py`,
+`services/authz/ws_surface.py`, `core/database.py`,
+`test_plugin_self_containment.py` (its `_PLUGINS_WITH_HANDLERS` drift check
+covers group-level folders only — nested plugin folders like this one, and
+write_todos/simple_memory/gallery before it, are out of its scope).
+
+## Tests
+
+| Surface | File | Locks |
+|---|---|---|
+| Store | [`server/tests/nodes/test_canvas_node.py`](../server/tests/nodes/test_canvas_node.py) | scope isolation, append/replace + revision monotonicity, FIFO eviction, kind rejection, stable wire key set, note truncation, versioned board id |
+| Display op | same | contained ref build (`../` rejected), url scheme, truncation notice, empty-call `NodeUserError`, connected-outputs scan (near-miss dicts skipped, nested refs found), agent/workflow source labeling, replace mode, output payload discipline |
+| Handlers | same | internal-socket denial, owner mismatch, wrong-node-type, list/remove/clear round trip + broadcast-per-mutation |
+| Event + schema | same | identity-only envelope (`subject`, type, exact data keys), `as_tool_schema()["name"] == "canvas"`, structurally no `$defs`/`$ref`, locked hints/annotations |
+| Screenshots | [`test_browser_screenshots.py`](../server/tests/nodes/test_browser_screenshots.py) | base64/path/unrecognized shapes, size bounds, missing-workspace tolerance, harness containment |
+| FE dispatch | `canvas/__tests__/canvasKinds.test.ts` | full verdict matrix, mime-over-extension, language override |
+| FE carousel + sandbox | `canvas/__tests__/CanvasContent.test.tsx` | follow-newest vs pinned semantics, keyboard, remove; **sandbox regression**: external iframe exactly `allow-scripts allow-forms`, srcDoc lacks `allow-same-origin` and has no `src` |
+| FE dock store | `stores/__tests__/canvasDockStore.test.ts` | notifyPushed truth table, width clamp, prefs round-trip + corrupt-JSON fallback, session-only fields never persisted |
+| FE text fetch | `hooks/__tests__/useWorkspaceText.test.ts` | cap + reader cancel, status error, no-body fallback, cookie + buildApiUrl |
+| FE panel | `__tests__/CanvasPanel.test.tsx` | `canvas_list/remove/clear` round trip, no-workflow guard, denied-listing surfacing |
+
+## Pitfalls & known limits
+
+- **NodeSpec cache**: `isCanvasPanel` reaches an open canvas only after a
+ hard browser reload (specs are session-sticky, revision-busted at page
+ load). Symptom: the plain params list renders instead of the board.
+- **Unsaved workflows**: the board is writable under the `"unsaved"` scope
+ but the panel reads it only after the workflow is saved (ownership needs
+ the DB row).
+- `connected_outputs` is keyed by source node **type** (engine behavior
+ shared with console/executors): two same-type upstreams collide and the
+ scan sees one output.
+- Framing denial by external sites is undetectable — the "Open in new tab"
+ affordance is permanent, not error-triggered. Site content that declares
+ no background renders transparent over dark themes (accepted; no token is
+ invented for third-party content).
+- Removing a board item never deletes the underlying workspace file;
+ deletion stays human-only in the gallery.
+- No GC of board rows on workflow delete (future work; `canvas_clear`
+ covers the manual case). Other explicit non-goals for v1: thumbnails
+ strip, OutputPanel/chat click-to-preview integrations, CDP screencast
+ live view (the follow-latest poll covers the need), a `display` skill
+ (would need a `visuals.json` alias for tool name `canvas`).
+
+## Related
+
+[media_transport.md](./media_transport.md) (FileRef contract, the serving
+rule this extends) · [plugin_system.md](./plugin_system.md) (the plugin
+recipe) · [node-logic-flows/ai_tools/canvas.md](./node-logic-flows/ai_tools/canvas.md)
+(the frozen behavioural card) · [frontend_architecture.md](./frontend_architecture.md)
+(uiHints catalogue, strict frontend rules).
diff --git a/docs-internal/frontend_architecture.md b/docs-internal/frontend_architecture.md
index 684d9108..813f5a8c 100644
--- a/docs-internal/frontend_architecture.md
+++ b/docs-internal/frontend_architecture.md
@@ -508,6 +508,7 @@ Defined on `INodeTypeDescription.uiHints` ([client/src/types/INodeProperties.ts]
| `isTaskManagerPanel` | `MiddleSection` | Render the execution-scoped team task control panel |
| `isProcessManagerPanel` | `MiddleSection` | Render live managed-process inspection and controls |
| `isGalleryPanel` | `MiddleSection` | Render the workspace file browser (breadcrumbs, grid/list, search, preview, upload, drag-to-parameter) instead of the plain params list. Declared by `gallery`, which pairs it with `hideInputSection` but **keeps** the Output section — unlike `processManager` it produces output worth seeing and dragging. The panel writes back to the node's own `path` / `selection` params, so what you browse is what the node emits. |
+| `isCanvasPanel` | `MiddleSection`, `CanvasDock` | Render the pushed-content Canvas board instead of the plain params list. Declared by `canvas`. Double duty: the docked canvas sidebar also uses this flag to FIND Canvas nodes in the graph (`resolveNodeDescription(type)?.uiHints?.isCanvasPanel`) — never the type string. Pairs with an explicit `isConfigNode: False` because the `tool` group would auto-derive `True` while the node's `input-main` is real dataflow. See [canvas_node.md](./canvas_node.md). |
| `showLocationPanel` | `LocationParameterPanel` | Special-case panel for nodes with map preview |
| `isAndroidToolkit` | `ToolSchemaEditor` | Toolkit aggregator (Android service hub) |
| `isChatTrigger` | `ConsolePanel` | This node is a chat-message target |
diff --git a/docs-internal/media_transport.md b/docs-internal/media_transport.md
index dbc48fed..c6aa34e7 100644
--- a/docs-internal/media_transport.md
+++ b/docs-internal/media_transport.md
@@ -210,15 +210,27 @@ would mean a second auth path and a second error envelope for no gain.
`preview_kind(mime)` (gated on `serves_inline` first) gives the gallery
listing each row's `preview` verdict. **Two consumers, one function** — if
they ever disagreed, the panel would open a player for a file the route forces
- to download, and the user would see a dead frame with no explanation. Only
- `audio/ image/ video/` render inline; `NEVER_INLINE` is the full set
+ to download, and the user would see a dead frame with no explanation. The
+ `audio/ image/ video/` prefixes render inline, plus the exact-match set
+ `INLINE_EXACT = {application/pdf}` (added for the Canvas node's PDF surface —
+ the browser's built-in viewer renders isolated from the page, so the exposure
+ class is images, not markup; exact-match so no other `application/*` type
+ gains inline serving as a side effect). `NEVER_INLINE` is the full set
`{image/svg+xml, text/html, text/xml, application/xhtml+xml}`. Everything else
gets `Content-Disposition: attachment`, plus `X-Content-Type-Options: nosniff`.
This is load-bearing. `shell`, `fileDownloader` and `fileModify` can all
write arbitrary files into a workspace, so serving attacker-authored markup
inline **from the app origin** would be stored XSS with session-cookie
- access. Both excluded types are script-bearing.
+ access. Both excluded types are script-bearing. The Canvas node displays
+ workspace HTML anyway — but through a `srcDoc` iframe with
+ `sandbox="allow-scripts"` and no `allow-same-origin` (opaque origin, no
+ cookies), i.e. by respecting this rule, not weakening it
+ (see [canvas_node.md](./canvas_node.md)). Two adjacent notes: attachment
+ disposition does NOT block `fetch()` reading a body — the Canvas text
+ renderers fetch markdown/code over this same route with a client-side
+ 512 KB cap (`client/src/hooks/useWorkspaceText.ts`) — and `PreviewKind`
+ now includes `"pdf"` on both sides of the wire.
- No immutable caching: workspace files are mutable. `AudioRef.sha256` is a
natural `ETag`.
diff --git a/docs-internal/node-logic-flows/README.md b/docs-internal/node-logic-flows/README.md
index 9108c0f7..71d047ab 100644
--- a/docs-internal/node-logic-flows/README.md
+++ b/docs-internal/node-logic-flows/README.md
@@ -56,6 +56,7 @@ match its doc here, and each doc must still describe what the code does.
- [Agent Builder (`agentBuilder`)](./ai_tools/agentBuilder.md)
- [Calculator Tool (`calculatorTool`)](./ai_tools/calculatorTool.md)
+- [Canvas (`canvas`)](./ai_tools/canvas.md)
- [Current Time Tool (`currentTimeTool`)](./ai_tools/currentTimeTool.md)
- [DuckDuckGo Search (`duckduckgoSearch`)](./ai_tools/duckduckgoSearch.md)
- [Task Manager (`taskManager`)](./ai_tools/taskManager.md)
diff --git a/docs-internal/node-logic-flows/ai_tools/canvas.md b/docs-internal/node-logic-flows/ai_tools/canvas.md
new file mode 100644
index 00000000..152ef14b
--- /dev/null
+++ b/docs-internal/node-logic-flows/ai_tools/canvas.md
@@ -0,0 +1,109 @@
+# Canvas (`canvas`)
+
+| Field | Value |
+|------|-------|
+| **Category** | tool / ai |
+| **Backend** | [`server/nodes/tool/canvas/__init__.py::CanvasNode.display`](../../../server/nodes/tool/canvas/__init__.py) (plugin folder: `_store.py` durable board, `_handlers.py` panel WS API, `_events.py` broadcast) |
+| **WS handlers** | `canvas_list` / `canvas_remove` / `canvas_clear` (self-registered; simple_memory security preamble: external socket + owner + graph-ownership checks) |
+| **Tests** | [`server/tests/nodes/test_canvas_node.py`](../../../server/tests/nodes/test_canvas_node.py) |
+| **Skill (if any)** | none |
+| **Dual-purpose tool** | yes - tool name `canvas` (`tool_schema_locked`) |
+
+## Purpose
+
+A display board workflows and agents push content onto — the platform's
+Claude/ChatGPT-Canvas-style viewing surface. Agents call the `canvas` tool
+after producing something the user should see (a screenshot, a chart, a
+report, a URL); workflow edges push upstream file outputs automatically. The
+board renders in two hosts sharing one component: the node's full-height
+parameter panel (`uiHints.isCanvasPanel`) and the docked right-side canvas
+sidebar (auto-opens on push, resizable, ephemeral click-to-preview mode).
+Items are *references* (serialized `FileRef`s, URLs) and small markdown
+notes — never file bytes (media-transport contract).
+
+## Inputs (handles)
+
+| Handle | Connection type | Required | Purpose |
+|--------|-----------------|----------|---------|
+| `input-main` | main | no | Upstream output to display. Explicit params win; otherwise a structural FileRef scan of `connected_outputs` collects up to 20 refs (`tts -> canvas` works zero-config). |
+| `output-tool` (source, top) | tools | no | Connect to an agent's `input-tools` so the model can call `canvas(...)` mid-run. |
+
+## Parameters
+
+| Name | Type | Default | Required | displayOptions.show | Description |
+|------|------|---------|----------|---------------------|-------------|
+| `title` | string | `null` | no | - | Caption for the first item added by the call |
+| `paths` | string[] | `null` | no | - | Workspace-relative file paths (max 20/call). Coercions: JSON-string array, bare string, ref dicts -> their `path` |
+| `url` | string | `null` | no | - | External http(s) URL (scheme-validated) |
+| `content` | string | `null` | no | - | Markdown note, truncated at 64KB with a visible marker |
+| `language` | string | `null` | no | - | Syntax-highlight hint when `content` is code |
+| `mode` | `append` \| `replace` | `append` | no | - | `replace` clears the board first |
+
+## Outputs (handles)
+
+| Handle | Shape | Description |
+|--------|-------|-------------|
+| (tool result / node result) | object | Small by contract: ids and counts only, never bodies or refs — node results are persisted 3x, broadcast, and replayed into LLM context |
+
+### Output payload (TypeScript shape)
+
+```ts
+{
+ message: string;
+ count: number; // board size after the call (FIFO cap 200)
+ revision: number;
+ added: Array<{ id: string; kind: 'file' | 'url' | 'note'; title: string | null }>;
+}
+```
+
+## Logic Flow
+
+```mermaid
+flowchart TD
+ A[display op] --> B[Scope: owner + workflow-or-unsaved + node_id]
+ B --> C{Explicit params?}
+ C -- paths --> D[resolve_media containment + stat -> FileRef, never read bytes]
+ C -- url --> E[http/https scheme check]
+ C -- content --> F[truncate_note 64KB]
+ C -- none --> G[Structural FileRef scan of connected_outputs]
+ D & E & F & G --> H{Any items?}
+ H -- no --> I[NodeUserError: Nothing to display]
+ H -- yes --> J[CanvasStore.append / replace - one transaction, revision++, FIFO evict at 200]
+ J --> K[broadcast canvas_updated - identity + revision only]
+ K --> L[Small output envelope]
+```
+
+## Decision Logic
+
+- **Validation**: >20 paths -> `NodeUserError`; non-http(s) url -> `NodeUserError`; empty call (no params, no scanned refs) -> `NodeUserError`; unknown item kind -> `CanvasStoreError` -> `NodeUserError`.
+- **Branches**: explicit params vs connected-outputs scan (scan runs only when no explicit item was produced); `mode=replace` deletes the board's rows in the same transaction.
+- **Fallbacks**: `workflow_id or "unsaved"` scope; note truncation degrades instead of failing; `source` labeled `agent` iff `_tool_config` is on ctx.raw (the `execute_as_tool` marker), else `workflow`.
+- **Error paths**: containment failure inside `resolve_media` and missing files surface as one-WARN-line `NodeUserError`s naming the path.
+
+## Side Effects
+
+- **Database writes**: `canvas_boards` (revision head) + `canvas_items` rows — plugin-owned tables (mount_store mechanism: import-time SQLModel registration + `ensure_schema(checkfirst=True)`), no `core/database.py` edits.
+- **Broadcasts**: `canvas_updated` CloudEvents envelope (`com.opencompany.canvas.updated`, subject = node_id, data = `{workflow_id, node_id, revision}` only) via `get_status_broadcaster().broadcast` directly — no canary consumer, so `dispatch.emit` would run a guaranteed-empty Visibility query.
+- **External API calls**: none.
+- **File I/O**: stat-only on displayed paths; never reads content to register a pointer.
+
+## External Dependencies
+
+- **Credentials**: none.
+- **Services**: `services.media` (`resolve_media`, `workspace_file_url`), `services.plugin.deps.get_database`.
+- **Frontend**: `client/src/components/parameterPanel/CanvasPanel.tsx` (panel host), `client/src/components/ui/CanvasDock.tsx` (docked sidebar + ephemeral preview), shared `parameterPanel/canvas/CanvasContent.tsx` (carousel, follow-latest image poll, markdown/code/JSON/text via capped client fetch, sandboxed iframes for external URLs + workspace HTML, inline PDF).
+
+## Edge cases & known limits
+
+- Board caps at 200 items (FIFO eviction) and notes at 64KB (visible truncation marker).
+- Panel handlers require a **saved** workflow (graph-ownership check needs the DB row); an unsaved canvas can push to the `unsaved` scope but the panel reads it only after save — same trade-off as simpleMemory.
+- `connected_outputs` is keyed by source node *type* (engine behavior): two same-type upstreams collide and the scan sees one output.
+- The viewer node is in `_NEEDS_CONNECTED_OUTPUTS` (`services/node_executor.py`) — the one core edit, sanctioned by that frozenset's own comment.
+- Removing an item never deletes the underlying workspace file.
+- Workspace HTML renders only in a `sandbox="allow-scripts"` srcDoc iframe (opaque origin, no cookies); `NEVER_INLINE` on the workspace route is untouched. `application/pdf` joined `INLINE_EXACT` in `services/media/preview.py` for the inline PDF surface.
+
+## Related
+
+- **Skills using this as a tool**: none yet (a paired skill would need a `visuals.json` alias for tool name `canvas`).
+- **Other nodes that consume this output**: none — the board is a sink; browser/browserHarness screenshot ops now persist workspace `FileRef`s (`nodes/browser/_screenshots.py`) precisely so this node can display them.
+- **Architecture docs**: [media_transport.md](../../media_transport.md), [plugin_system.md](../../plugin_system.md), [status_broadcaster.md](../../status_broadcaster.md).
diff --git a/server/config/node_allowlist.json b/server/config/node_allowlist.json
index 3b74d98d..bdacb4df 100644
--- a/server/config/node_allowlist.json
+++ b/server/config/node_allowlist.json
@@ -26,6 +26,7 @@
"calculatorTool",
"currentTimeTool",
"writeTodos",
+ "canvas",
"httpRequest",
"timer",
diff --git a/server/nodes/browser/_screenshots.py b/server/nodes/browser/_screenshots.py
new file mode 100644
index 00000000..82b8f18f
--- /dev/null
+++ b/server/nodes/browser/_screenshots.py
@@ -0,0 +1,156 @@
+"""Screenshot persistence shared by the two browser plugins.
+
+Both browser nodes historically leaked screenshots in shapes the platform
+cannot use: ``browser`` returned whatever agent-browser printed (a base64
+blob — a media-contract violation that also hits the 100 KB CLI-output
+truncation), and ``browserHarness`` returned an absolute path under its
+daemon tmp dir, which no HTTP route can serve. These helpers land the bytes
+in the workflow workspace via ``write_media(kind="image")`` so a screenshot
+becomes a ~400 B ``FileRef`` the Canvas board / gallery can display.
+
+Every helper is TOLERANT by contract: an unrecognized payload shape, a
+missing workspace, or a write failure logs one warning and returns ``None``
+so the browser operation itself never breaks over persistence.
+"""
+
+from __future__ import annotations
+
+import base64
+import binascii
+from pathlib import Path
+from typing import Any, Dict, Optional, Tuple
+
+from core.logging import get_logger
+
+logger = get_logger(__name__)
+
+# Keys agent-browser plausibly uses for inline image data (only "base64" is
+# evidenced in-repo; the rest are tolerated probes) and for a saved file.
+_BASE64_KEYS = ("base64", "data", "screenshot", "image")
+_PATH_KEYS = ("path", "file", "filename")
+
+# A real screenshot is never this small; refuse to "persist" garbage.
+_MIN_IMAGE_BYTES = 128
+_MAX_IMAGE_BYTES = 25 * 1024 * 1024
+
+_EXT_MIME = {
+ ".png": "image/png",
+ ".jpg": "image/jpeg",
+ ".jpeg": "image/jpeg",
+ ".webp": "image/webp",
+}
+
+
+def _write_image(payload: bytes, ctx: Any, *, ext: str, mime: str) -> Optional[Dict[str, Any]]:
+ from services.media.workspace import write_media
+
+ if not getattr(ctx, "workspace_dir", None):
+ logger.warning("[Browser] No workspace on this run; screenshot not persisted")
+ return None
+ if not (_MIN_IMAGE_BYTES <= len(payload) <= _MAX_IMAGE_BYTES):
+ logger.warning(
+ "[Browser] Screenshot payload size %d outside sane bounds; not persisted",
+ len(payload),
+ )
+ return None
+ try:
+ ref = write_media(
+ payload,
+ ctx=ctx,
+ stem="screenshot",
+ ext=ext,
+ kind="image",
+ mime_type=mime,
+ )
+ except Exception as exc: # persistence must never fail the browser op
+ logger.warning("[Browser] Could not persist screenshot: %s", exc)
+ return None
+ return ref.model_dump(mode="json")
+
+
+def persist_screenshot_from_payload(
+ data: Any, ctx: Any, *, fmt: str = "png"
+) -> Tuple[Optional[Dict[str, Any]], Optional[str]]:
+ """agent-browser screenshot payload -> ``(serialized FileRef, consumed_key)``.
+
+ Probes the known inline-base64 keys first, then saved-file-path keys.
+ ``consumed_key`` names the bulky field the caller should drop from the
+ payload so no base64 rides the node output. ``(None, None)`` on any
+ unrecognized shape — the raw payload then passes through unchanged.
+ """
+ if not isinstance(data, dict):
+ return None, None
+
+ ext = ".jpg" if fmt == "jpeg" else f".{fmt or 'png'}"
+ mime = _EXT_MIME.get(ext, "image/png")
+
+ for key in _BASE64_KEYS:
+ value = data.get(key)
+ if not isinstance(value, str) or len(value) < 200:
+ continue
+ try:
+ payload = base64.b64decode(value, validate=True)
+ except (binascii.Error, ValueError):
+ continue
+ ref = _write_image(payload, ctx, ext=ext, mime=mime)
+ return (ref, key) if ref else (None, None)
+
+ for key in _PATH_KEYS:
+ value = data.get(key)
+ if not isinstance(value, str) or not value.strip():
+ continue
+ candidate = Path(value.strip())
+ if not candidate.is_absolute() or not candidate.is_file():
+ continue
+ suffix = candidate.suffix.lower()
+ if suffix not in _EXT_MIME:
+ continue
+ try:
+ payload = candidate.read_bytes()
+ except OSError as exc:
+ logger.warning("[Browser] Could not read screenshot file %s: %s", candidate, exc)
+ return None, None
+ ref = _write_image(payload, ctx, ext=suffix, mime=_EXT_MIME[suffix])
+ # The path itself is small; nothing bulky to drop.
+ return (ref, None) if ref else (None, None)
+
+ return None, None
+
+
+def persist_screenshot_file(
+ path_text: str, ctx: Any, *, contained_under: Path
+) -> Optional[Dict[str, Any]]:
+ """A harness-printed screenshot path -> serialized FileRef.
+
+ Reads ONLY files contained under the harness runtime dir — the printed
+ path is process output, not a trusted input, so this is not a generic
+ read-any-path helper.
+ """
+ candidate = Path(str(path_text or "").strip())
+ if not candidate.is_absolute():
+ return None
+ try:
+ resolved = candidate.resolve(strict=True)
+ root = contained_under.resolve(strict=False)
+ if not resolved.is_relative_to(root):
+ logger.warning(
+ "[BrowserHarness] Screenshot path escapes the harness dir; not persisted"
+ )
+ return None
+ except OSError:
+ return None
+ if not resolved.is_file():
+ return None
+ suffix = resolved.suffix.lower()
+ mime = _EXT_MIME.get(suffix)
+ if mime is None:
+ return None
+ try:
+ payload = resolved.read_bytes()
+ except OSError as exc:
+ logger.warning("[BrowserHarness] Could not read screenshot %s: %s", resolved, exc)
+ return None
+ return _write_image(payload, ctx, ext=suffix, mime=mime)
+
+
+__all__ = ["persist_screenshot_file", "persist_screenshot_from_payload"]
diff --git a/server/nodes/browser/browser/__init__.py b/server/nodes/browser/browser/__init__.py
index e57accab..722d1e1e 100644
--- a/server/nodes/browser/browser/__init__.py
+++ b/server/nodes/browser/browser/__init__.py
@@ -394,4 +394,19 @@ class BrowserNode(ActionNode):
else:
data = await svc.run(_build_args(op, p), session, timeout, **run_kw)
+ if op == "screenshot" and isinstance(data, dict):
+ # Land the pixels in the workspace as a FileRef (media contract:
+ # references, never bytes — a base64 blob in the result rides the
+ # DB, broadcasts, Temporal payloads and LLM context). Tolerant:
+ # an unrecognized CLI shape passes through unchanged.
+ from .._screenshots import persist_screenshot_from_payload
+
+ ref, consumed_key = persist_screenshot_from_payload(
+ data, ctx, fmt=params.screenshot_format or "png"
+ )
+ if ref is not None:
+ if consumed_key:
+ data = {k: v for k, v in data.items() if k != consumed_key}
+ data["screenshot"] = ref
+
return BrowserOutput(operation=op, data=data, session=session)
diff --git a/server/nodes/browser/browser_harness/__init__.py b/server/nodes/browser/browser_harness/__init__.py
index e4789e68..5b717fbd 100644
--- a/server/nodes/browser/browser_harness/__init__.py
+++ b/server/nodes/browser/browser_harness/__init__.py
@@ -17,6 +17,7 @@ profile/session state.
from __future__ import annotations
+from pathlib import Path
from typing import Any, Literal, Optional
from pydantic import BaseModel, ConfigDict, Field
@@ -161,4 +162,27 @@ class BrowserHarnessNode(ActionNode):
else:
data = await svc.run_code(_code_for(params), timeout=params.timeout)
+ if params.operation == "screenshot" and isinstance(data, dict):
+ # capture_screenshot prints an absolute path under the harness
+ # tmp dir — unreachable over HTTP. Copy the bytes into the
+ # workspace so the shot becomes a servable FileRef; the raw
+ # output stays for provenance. Containment-checked read.
+ from core.paths import daemons_dir
+
+ from .._screenshots import persist_screenshot_file
+
+ lines = [
+ line.strip()
+ for line in str(data.get("output") or "").splitlines()
+ if line.strip()
+ ]
+ if lines:
+ ref = persist_screenshot_file(
+ lines[-1],
+ ctx,
+ contained_under=Path(daemons_dir()) / "browser-harness",
+ )
+ if ref is not None:
+ data["screenshot"] = ref
+
return BrowserHarnessOutput(operation=params.operation, data=data)
diff --git a/server/nodes/tool/canvas/__init__.py b/server/nodes/tool/canvas/__init__.py
new file mode 100644
index 00000000..19a52c4b
--- /dev/null
+++ b/server/nodes/tool/canvas/__init__.py
@@ -0,0 +1,391 @@
+"""Canvas node — a display board workflows and agents push content onto.
+
+The board holds three item kinds: workspace file *references* (never bytes —
+the media-transport contract), external URLs, and small markdown notes. The
+parameter panel and the docked canvas sidebar render it; agents push via the
+``canvas`` tool, workflows via the ``input-main`` edge (explicit params or a
+structural FileRef scan of the connected outputs).
+
+Shape follows ``nodes/tool/write_todos`` (ToolNode + input-main handle +
+per-scope store + metadata-only broadcast + panel WS handlers); the WS
+handlers copy ``nodes/tool/simple_memory``'s security preamble.
+"""
+
+from __future__ import annotations
+
+import json
+import mimetypes
+from datetime import datetime, timezone
+from typing import Any, Dict, List, Literal, Optional, get_args
+from urllib.parse import urlsplit
+
+from pydantic import (
+ BaseModel,
+ ConfigDict,
+ Field,
+ ValidationError,
+ field_validator,
+ model_validator,
+)
+
+from services.plugin import (
+ NodeContext,
+ NodeUserError,
+ Operation,
+ TaskQueue,
+ ToolNode,
+)
+from services.plugin.params import coerce_blank_params
+
+from ._store import (
+ CANVAS_MAX_PATHS_PER_CALL,
+ CanvasScope,
+ CanvasStore,
+ CanvasStoreError,
+ UNSAVED_WORKFLOW_ID,
+ truncate_note,
+)
+
+# Depth cap for the structural FileRef scan of connected outputs. Node
+# results are already payload-disciplined; anything nested deeper than this
+# is not a ref a user meant to display.
+_SCAN_MAX_DEPTH = 6
+
+
+# Flat on purpose — this IS the LLM tool schema (nested models would emit
+# $defs/$ref, which the tool-schema invariant rejects). The docstring is
+# deliberately absent: a Pydantic model docstring becomes the schema
+# description the model reads.
+class CanvasParams(BaseModel):
+ title: Optional[str] = Field(
+ default=None,
+ max_length=200,
+ description="Optional caption for the first item added by this call.",
+ )
+ paths: Optional[List[str]] = Field(
+ default=None,
+ description=(
+ "Workspace-relative file paths to display "
+ "(e.g. ['media/chart.png', 'reports/summary.md'])."
+ ),
+ )
+ url: Optional[str] = Field(
+ default=None,
+ max_length=2048,
+ description="An external http(s) URL to display in an embedded frame.",
+ )
+ content: Optional[str] = Field(
+ default=None,
+ description="Markdown text to display directly (a note/report).",
+ )
+ language: Optional[str] = Field(
+ default=None,
+ max_length=40,
+ description="Optional syntax-highlight language when content is code.",
+ )
+ mode: Literal["append", "replace"] = Field(
+ default="append",
+ description="append adds to the board; replace clears it first.",
+ )
+
+ model_config = ConfigDict(extra="ignore")
+
+ @model_validator(mode="before")
+ @classmethod
+ def _coerce_blanks(cls, values: Any) -> Any:
+ return coerce_blank_params(cls, values)
+
+ @field_validator("paths", mode="before")
+ @classmethod
+ def _coerce_paths(cls, value: Any) -> Any:
+ """Accept the shapes that actually reach this field.
+
+ - a JSON-encoded array string (Gemini stringifies array tool args —
+ same boundary coercion as ``WriteTodosParams._coerce_todos``);
+ - a bare path string (LLM passed one path instead of a list);
+ - serialized FileRef dicts (a ``{{node.files}}`` template resolves to
+ a list of dicts) — reduced to their ``path`` key.
+ Malformed JSON passes through so Pydantic raises a correctable error.
+ """
+ if isinstance(value, str):
+ stripped = value.strip()
+ if not stripped:
+ return None
+ try:
+ parsed = json.loads(stripped)
+ except (ValueError, TypeError):
+ return [stripped]
+ value = parsed if isinstance(parsed, list) else [stripped]
+ if isinstance(value, (list, tuple)):
+ coerced: List[Any] = []
+ for entry in value:
+ if isinstance(entry, dict) and entry.get("path"):
+ coerced.append(str(entry["path"]))
+ else:
+ coerced.append(entry)
+ return coerced
+ return value
+
+
+class CanvasOutput(BaseModel):
+ """Small by contract: ids and counts only, never bodies or full refs —
+ a node result is persisted, broadcast, and replayed into LLM context."""
+
+ message: Optional[str] = None
+ count: Optional[int] = None
+ revision: Optional[int] = None
+ added: Optional[list] = None
+
+ model_config = ConfigDict(extra="allow")
+
+
+class CanvasNode(ToolNode):
+ type = "canvas"
+ display_name = "Canvas"
+ subtitle = "Content Board"
+ group = ("tool", "ai")
+ description = (
+ "Display board for workflow output: images, video, audio, documents, "
+ "reports, and websites render in the Canvas panel and the docked "
+ "canvas sidebar."
+ )
+ component_kind = "tool"
+ tool_name = "canvas"
+ # Locks tool_name + schema against stale persisted ToolSchema rows
+ # (simpleMemory precedent).
+ tool_schema_locked = True
+ tool_description = (
+ "Show content to the user on the Canvas board. Pass workspace file "
+ "paths (images, video, audio, PDF, markdown, code, HTML), an external "
+ "http(s) URL, or markdown text via content. Use this after producing "
+ "a file or result the user should see — e.g. a screenshot, a chart, "
+ "or a report. mode=replace clears the board first; the default "
+ "append adds to it."
+ )
+ handles = (
+ {"name": "input-main", "kind": "input", "position": "left", "label": "Input", "role": "main"},
+ {"name": "output-tool", "kind": "output", "position": "top", "label": "Tool", "role": "tools"},
+ )
+ # isConfigNode is auto-derived True for the "tool" group; the Canvas
+ # node's input-main is a real runtime dataflow edge (upstream output
+ # displays on execution), so it must present as a normal node with
+ # inheritable inputs disabled. Explicit declaration wins over
+ # auto-derivation.
+ ui_hints = {
+ "isCanvasPanel": True,
+ "isToolPanel": True,
+ "isConfigNode": False,
+ }
+ # Overrides ToolNode's readonly default — canvas writes the durable board.
+ annotations = {"destructive": False, "readonly": False, "open_world": False}
+ task_queue = TaskQueue.DEFAULT
+
+ Params = CanvasParams
+ Output = CanvasOutput
+
+ @Operation("display")
+ async def display(self, ctx: NodeContext, params: CanvasParams) -> Any:
+ """Push content onto the board. Single op — serves the agent tool
+ call, the Run button, and the workflow edge identically."""
+ from services.plugin.deps import get_database
+
+ from ._events import dispatch_canvas_updated
+
+ scope = CanvasScope(
+ owner_id=ctx.user_id or "owner",
+ workflow_id=ctx.workflow_id or UNSAVED_WORKFLOW_ID,
+ node_id=ctx.node_id,
+ )
+ # execute_as_tool sets _tool_config around the op body; the Run
+ # button and the workflow edge never do. Cosmetic labeling only.
+ source = "agent" if "_tool_config" in ctx.raw else "workflow"
+
+ items: List[Dict[str, Any]] = []
+ notices: List[str] = []
+
+ raw_paths = [p for p in (params.paths or []) if str(p or "").strip()]
+ if len(raw_paths) > CANVAS_MAX_PATHS_PER_CALL:
+ raise NodeUserError(
+ f"Too many paths in one canvas call "
+ f"({len(raw_paths)} > {CANVAS_MAX_PATHS_PER_CALL}). "
+ "Split into multiple calls."
+ )
+ for raw in raw_paths:
+ items.append(
+ {
+ "kind": "file",
+ "ref": _build_ref(ctx, str(raw)),
+ "source": source,
+ }
+ )
+
+ if params.url:
+ scheme = urlsplit(params.url).scheme.lower()
+ if scheme not in ("http", "https"):
+ raise NodeUserError(
+ "url must be an http(s) address, "
+ f"got scheme '{scheme or 'none'}'"
+ )
+ items.append({"kind": "url", "url": params.url, "source": source})
+
+ if params.content:
+ note, truncated = truncate_note(params.content)
+ if truncated:
+ notices.append("note content was truncated at 64KB")
+ items.append(
+ {
+ "kind": "note",
+ "content": note,
+ "language": params.language,
+ "source": source,
+ }
+ )
+
+ # Workflow-edge convenience: with no explicit items, display whatever
+ # FileRefs the connected upstream outputs carry (tts -> canvas works
+ # with a zero-config edge).
+ if not items:
+ connected = ctx.raw.get("connected_outputs") or {}
+ for ref in _collect_connected_refs(
+ connected, limit=CANVAS_MAX_PATHS_PER_CALL
+ ):
+ items.append({"kind": "file", "ref": ref, "source": source})
+
+ if not items:
+ raise NodeUserError(
+ "Nothing to display — pass paths, url, or content "
+ "(or connect a node that outputs files)."
+ )
+
+ if params.title:
+ items[0]["title"] = params.title
+
+ store = CanvasStore(get_database())
+ try:
+ added, revision, total = await store.append(
+ scope, items, mode=params.mode
+ )
+ except CanvasStoreError as exc:
+ raise NodeUserError(str(exc)) from exc
+
+ await dispatch_canvas_updated(
+ workflow_id=ctx.workflow_id,
+ node_id=ctx.node_id,
+ revision=revision,
+ )
+
+ message = f"Displayed {len(added)} item(s); board holds {total}."
+ if params.mode == "replace":
+ message = f"Board replaced with {len(added)} item(s)."
+ if notices:
+ message += " " + "; ".join(notices) + "."
+ return {
+ "message": message,
+ "count": total,
+ "revision": revision,
+ "added": [
+ {"id": row["id"], "kind": row["kind"], "title": row["title"]}
+ for row in added
+ ],
+ }
+
+
+def _build_ref(ctx: NodeContext, raw_path: str) -> Dict[str, Any]:
+ """A workspace path -> a serialized ``FileRef`` (gallery-style).
+
+ Containment via ``resolve_media`` + a stat — never reads bytes: the board
+ stores a pointer, and reading a 500 MB video to register it would be
+ pure waste. ``kind`` stays ``"file"`` even for media — ``kind="audio"``
+ asserts a container probe this code never ran.
+ """
+ from services.media.refs import FileRef
+ from services.media.workspace import (
+ resolve_media,
+ workspace_file_url,
+ workspace_root,
+ )
+
+ resolved = resolve_media(raw_path, ctx=ctx)
+ if not resolved.is_file():
+ raise NodeUserError(f"File not found in workspace: {raw_path}")
+
+ root = workspace_root(ctx).resolve(strict=False)
+ try:
+ rel = resolved.relative_to(root).as_posix()
+ except ValueError as exc: # pragma: no cover - resolve_media contains
+ raise NodeUserError(
+ f"Path is outside this workflow's workspace: {raw_path}"
+ ) from exc
+
+ stat = resolved.stat()
+ name = resolved.name
+ return FileRef(
+ path=rel,
+ workflow_id=ctx.workflow_id,
+ filename=name,
+ mime_type=mimetypes.guess_type(name)[0] or "application/octet-stream",
+ size_bytes=stat.st_size,
+ modified_at=datetime.fromtimestamp(
+ stat.st_mtime, tz=timezone.utc
+ ).isoformat(),
+ url=workspace_file_url(ctx.workflow_id, rel),
+ ).model_dump(mode="json")
+
+
+def _collect_connected_refs(
+ payload: Any, *, limit: int
+) -> List[Dict[str, Any]]:
+ """Structural scan for serialized FileRefs in connected outputs.
+
+ Mirrors the frontend's structural AudioRef detection: a dict is a ref iff
+ it validates as one (``extra="forbid"`` makes near-misses fail), so a
+ gallery listing row is skipped while the ``ref`` nested inside it is
+ found. Deduped by path, order-preserving, depth- and count-capped.
+ """
+ from services.media.refs import AudioRef, FileKind, FileRef
+
+ kinds = set(get_args(FileKind))
+ found: List[Dict[str, Any]] = []
+ seen_paths: set[str] = set()
+
+ def try_ref(candidate: Dict[str, Any]) -> bool:
+ if candidate.get("kind") not in kinds:
+ return False
+ if not candidate.get("path") or not candidate.get("filename"):
+ return False
+ model = AudioRef if candidate.get("kind") == "audio" else FileRef
+ try:
+ ref = model.model_validate(candidate)
+ except ValidationError:
+ return False
+ if ref.path in seen_paths:
+ return True
+ seen_paths.add(ref.path)
+ found.append(ref.model_dump(mode="json"))
+ return True
+
+ def walk(value: Any, depth: int) -> None:
+ if len(found) >= limit or depth > _SCAN_MAX_DEPTH:
+ return
+ if isinstance(value, dict):
+ if try_ref(value):
+ return
+ for child in value.values():
+ walk(child, depth + 1)
+ elif isinstance(value, (list, tuple)):
+ for child in value:
+ walk(child, depth + 1)
+
+ walk(payload, 0)
+ return found[:limit]
+
+
+# --- self-registration on import -------------------------------------------
+# The Canvas panel and docked sidebar read/mutate the board through these WS
+# handlers (self-contained plugin-folder pattern — core router needs no
+# edit). See nodes/tool/write_todos/__init__.py for the template.
+from services.ws_handler_registry import register_ws_handlers # noqa: E402
+
+from ._handlers import WS_HANDLERS # noqa: E402
+
+register_ws_handlers(WS_HANDLERS)
diff --git a/server/nodes/tool/canvas/_events.py b/server/nodes/tool/canvas/_events.py
new file mode 100644
index 00000000..24259a59
--- /dev/null
+++ b/server/nodes/tool/canvas/_events.py
@@ -0,0 +1,62 @@
+"""Metadata-only Canvas lifecycle event.
+
+A UI lifecycle notification, not a workflow trigger. No node type registers a
+canary consumer for ``com.opencompany.canvas.*``, so routing it through
+``services.events.dispatch.emit`` would run a Temporal Visibility
+``ListWorkflowExecutions`` query that is guaranteed to match nothing — once
+per ``canvas`` tool call. It is broadcast straight to connected WebSocket
+clients instead, the canonical plugin pattern (see ``nodes/context/_events.py``).
+
+The payload is identity + revision only. It carries no item content, because
+the broadcast fans out to every connected socket; panels refetch through the
+authorized ``canvas_list`` handler, which is where ownership is enforced.
+"""
+
+from __future__ import annotations
+
+from typing import Optional
+
+from services.events.envelope import WorkflowEvent
+
+_WIRE_KEY = "canvas_updated"
+
+
+def canvas_updated(
+ *,
+ workflow_id: Optional[str],
+ node_id: str,
+ revision: int,
+) -> WorkflowEvent:
+ return WorkflowEvent(
+ source="opencompany://nodes/canvas",
+ type="com.opencompany.canvas.updated",
+ subject=node_id,
+ workflow_id=workflow_id,
+ data={
+ "workflow_id": workflow_id,
+ "node_id": node_id,
+ "revision": revision,
+ },
+ )
+
+
+async def dispatch_canvas_updated(
+ *,
+ workflow_id: Optional[str],
+ node_id: str,
+ revision: int,
+) -> None:
+ from services.status_broadcaster import get_status_broadcaster
+
+ event = canvas_updated(
+ workflow_id=workflow_id, node_id=node_id, revision=revision
+ )
+ await get_status_broadcaster().broadcast(
+ {
+ "type": _WIRE_KEY,
+ "data": event.model_dump(mode="json", exclude_none=True),
+ }
+ )
+
+
+__all__ = ["canvas_updated", "dispatch_canvas_updated"]
diff --git a/server/nodes/tool/canvas/_handlers.py b/server/nodes/tool/canvas/_handlers.py
new file mode 100644
index 00000000..f5ec3e65
--- /dev/null
+++ b/server/nodes/tool/canvas/_handlers.py
@@ -0,0 +1,152 @@
+"""Human-facing WebSocket API for the Canvas panel and docked sidebar.
+
+Every request resolves its board scope from the persisted workflow graph and
+the authenticated WebSocket. Neither the client nor the model can provide a
+scope identifier. Item content is returned only on these authorized calls;
+the ``canvas_updated`` broadcast stays metadata-only.
+
+Security preamble copied from ``nodes/tool/simple_memory/_handlers.py`` —
+the canonical template for panel handlers that read/mutate per-node state.
+"""
+
+from __future__ import annotations
+
+from typing import Any, Awaitable, Callable, Dict
+
+from fastapi import WebSocket
+
+from services.plugin import NodeUserError
+from services.plugin.deps import get_database
+from services.plugin.ws import ws_response
+
+from ._events import dispatch_canvas_updated
+from ._store import CanvasScope, CanvasStore, CanvasStoreError
+
+
+def _authenticated_owner(websocket: WebSocket) -> str:
+ """Read server-authenticated identity without consulting request data."""
+ state = getattr(websocket, "state", None)
+ for attribute in ("user_id", "principal_id", "subject"):
+ value = getattr(state, attribute, None) if state is not None else None
+ if isinstance(value, (str, int)) and str(value).strip():
+ return str(value)
+ scope = getattr(websocket, "scope", None)
+ if isinstance(scope, dict):
+ for key in ("user_id", "principal_id", "subject"):
+ value = scope.get(key)
+ if isinstance(value, (str, int)) and str(value).strip():
+ return str(value)
+ # The current deployment is single-owner when no auth principal is
+ # attached; this mirrors NodeContext.user_id's trusted default.
+ return "owner"
+
+
+def _require_external_socket(websocket: WebSocket) -> None:
+ """The internal unauthenticated worker socket may not touch the board.
+
+ Defence in depth behind the allowlist in ``services.authz.ws_surface``
+ (deny-by-default for new handlers) — same posture as Memory and Context.
+ """
+ scope = getattr(websocket, "scope", {}) or {}
+ if scope.get("path") == "/ws/internal":
+ raise NodeUserError("Canvas access requires an authenticated client")
+
+
+async def _resolve_store_and_scope(
+ data: Dict[str, Any], websocket: WebSocket
+) -> tuple[CanvasStore, CanvasScope]:
+ _require_external_socket(websocket)
+ workflow_id = str(data.get("workflow_id") or "").strip()
+ node_id = str(data.get("node_id") or "").strip()
+ if not workflow_id:
+ raise NodeUserError("workflow_id required")
+ if not node_id:
+ raise NodeUserError("node_id required")
+
+ database = get_database()
+ saved = await database.get_workflow(workflow_id)
+ if saved is None:
+ raise NodeUserError("Workflow not found")
+ graph = saved.data if hasattr(saved, "data") else saved.get("data", saved)
+ owner_id = _authenticated_owner(websocket)
+ stored_owner = (
+ str(graph.get("owner_id") or "") if isinstance(graph, dict) else ""
+ )
+ if stored_owner and stored_owner != owner_id:
+ raise NodeUserError("Workflow access denied")
+ nodes = graph.get("nodes", []) if isinstance(graph, dict) else []
+ matches = [
+ node
+ for node in nodes
+ if str(node.get("id") or "") == node_id
+ and str(node.get("type") or node.get("data", {}).get("type") or "")
+ == "canvas"
+ ]
+ if len(matches) != 1:
+ raise NodeUserError(
+ "Canvas node does not belong to the requested workflow"
+ )
+ return CanvasStore(database), CanvasScope(
+ owner_id=owner_id,
+ workflow_id=workflow_id,
+ node_id=node_id,
+ )
+
+
+@ws_response
+async def handle_canvas_list(
+ data: Dict[str, Any], websocket: WebSocket
+) -> Dict[str, Any]:
+ store, scope = await _resolve_store_and_scope(data, websocket)
+ result = await store.list(scope)
+ return {"success": True, **result}
+
+
+@ws_response
+async def handle_canvas_remove(
+ data: Dict[str, Any], websocket: WebSocket
+) -> Dict[str, Any]:
+ store, scope = await _resolve_store_and_scope(data, websocket)
+ item_id = str(data.get("item_id") or "").strip()
+ if not item_id:
+ raise NodeUserError("item_id required")
+ try:
+ result = await store.remove(scope, item_id)
+ except CanvasStoreError as exc:
+ raise NodeUserError(str(exc)) from exc
+ await dispatch_canvas_updated(
+ workflow_id=scope.workflow_id,
+ node_id=scope.node_id,
+ revision=result["revision"],
+ )
+ return {"success": True, **result}
+
+
+@ws_response
+async def handle_canvas_clear(
+ data: Dict[str, Any], websocket: WebSocket
+) -> Dict[str, Any]:
+ store, scope = await _resolve_store_and_scope(data, websocket)
+ result = await store.clear(scope)
+ await dispatch_canvas_updated(
+ workflow_id=scope.workflow_id,
+ node_id=scope.node_id,
+ revision=result["revision"],
+ )
+ return {"success": True, **result}
+
+
+WSHandler = Callable[[Dict[str, Any], WebSocket], Awaitable[Dict[str, Any]]]
+WS_HANDLERS: Dict[str, WSHandler] = {
+ "canvas_list": handle_canvas_list,
+ "canvas_remove": handle_canvas_remove,
+ "canvas_clear": handle_canvas_clear,
+}
+
+
+__all__ = [
+ "WS_HANDLERS",
+ "handle_canvas_clear",
+ "handle_canvas_list",
+ "handle_canvas_remove",
+]
diff --git a/server/nodes/tool/canvas/_store.py b/server/nodes/tool/canvas/_store.py
new file mode 100644
index 00000000..4ab653a6
--- /dev/null
+++ b/server/nodes/tool/canvas/_store.py
@@ -0,0 +1,334 @@
+"""Durable content board backing the Canvas node.
+
+This module deliberately owns its tables instead of adding canvas-specific
+methods to :mod:`core.database` — the same shape as
+:mod:`services.data.mount_store` and :mod:`services.memory.tool_store`.
+Importing the Canvas plugin registers the SQLModel tables before
+``Database.startup()`` calls ``create_all``; :meth:`CanvasStore.ensure_schema`
+covers standalone workers/tests that import later.
+
+A board holds *references* (serialized ``FileRef`` dicts, URLs) and small
+markdown notes — never file bytes. Content bodies for workspace files are
+fetched by the client over the existing workspace HTTP route; the board rows
+stay small so ``canvas_list`` is one cheap fetch.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import hashlib
+import uuid
+from dataclasses import dataclass
+from datetime import datetime, timezone
+from typing import Any, Dict, List, Optional
+
+from sqlalchemy import JSON, Column, Text, delete, func, select
+from sqlmodel import Field, SQLModel
+
+from core.logging import get_logger
+
+logger = get_logger(__name__)
+
+# Version-prefixed hash material — bump ``canvas:v1`` if the scope shape ever
+# changes (the ``todo_session_key`` lesson: version the key from day one).
+_KEY_VERSION = "canvas:v1"
+UNSAVED_WORKFLOW_ID = "unsaved"
+
+CANVAS_MAX_ITEMS = 200
+CANVAS_NOTE_MAX_BYTES = 64 * 1024
+CANVAS_MAX_PATHS_PER_CALL = 20
+
+_TRUNCATION_MARKER = "\n… [truncated]"
+
+CANVAS_ITEM_KINDS = ("file", "url", "note")
+
+
+def _utcnow() -> datetime:
+ return datetime.now(timezone.utc)
+
+
+def truncate_note(content: str) -> tuple[str, bool]:
+ """Cap a note at :data:`CANVAS_NOTE_MAX_BYTES` with a visible marker.
+
+ A workflow run must never die on an oversized note — degrade instead.
+ """
+ encoded = content.encode("utf-8")
+ if len(encoded) <= CANVAS_NOTE_MAX_BYTES:
+ return content, False
+ keep = CANVAS_NOTE_MAX_BYTES - len(_TRUNCATION_MARKER.encode("utf-8"))
+ clipped = encoded[: max(0, keep)].decode("utf-8", errors="ignore")
+ return clipped + _TRUNCATION_MARKER, True
+
+
+@dataclass(frozen=True)
+class CanvasScope:
+ """One board: (authenticated owner, workflow, canvas node)."""
+
+ owner_id: str
+ workflow_id: str
+ node_id: str
+
+ @property
+ def board_id(self) -> str:
+ material = "\0".join(
+ (_KEY_VERSION, self.owner_id, self.workflow_id, self.node_id)
+ )
+ digest = hashlib.sha256(material.encode("utf-8")).hexdigest()
+ return f"canv_{digest[:48]}"
+
+
+class CanvasBoard(SQLModel, table=True):
+ """Per-scope board head: revision counter + identity columns."""
+
+ __tablename__ = "canvas_boards"
+
+ id: str = Field(primary_key=True, max_length=80)
+ owner_id: str = Field(default="owner", index=True, max_length=255)
+ workflow_id: str = Field(index=True, max_length=255)
+ node_id: str = Field(index=True, max_length=255)
+ revision: int = Field(default=0)
+ created_at: datetime = Field(default_factory=_utcnow)
+ updated_at: datetime = Field(default_factory=_utcnow)
+
+
+class CanvasItemRow(SQLModel, table=True):
+ """One displayed item. ``ref`` is a serialized FileRef — never bytes."""
+
+ __tablename__ = "canvas_items"
+
+ id: str = Field(primary_key=True, max_length=64)
+ board_id: str = Field(index=True, max_length=80)
+ # Literal["file", "url", "note"] — SQLModel cannot map Literal on table
+ # models, so the service layer constrains it (same note as tool_store).
+ kind: str = Field(max_length=10)
+ title: Optional[str] = Field(default=None, max_length=300)
+ ref: Optional[Dict[str, Any]] = Field(default=None, sa_column=Column(JSON))
+ url: Optional[str] = Field(default=None, max_length=2048)
+ content: Optional[str] = Field(default=None, sa_column=Column(Text))
+ language: Optional[str] = Field(default=None, max_length=40)
+ source: str = Field(default="workflow", max_length=10)
+ position: int = Field(default=0, index=True)
+ created_at: datetime = Field(default_factory=_utcnow)
+
+
+class CanvasStoreError(ValueError):
+ """User-correctable store failure (unknown item id, bad kind)."""
+
+
+def _serialize(row: CanvasItemRow) -> Dict[str, Any]:
+ """Row -> the fixed CanvasItem wire shape (stable key set, null-filled)."""
+ return {
+ "id": row.id,
+ "kind": row.kind,
+ "title": row.title,
+ "ref": row.ref,
+ "url": row.url,
+ "content": row.content,
+ "language": row.language,
+ "source": row.source,
+ "created_at": row.created_at.isoformat() if row.created_at else None,
+ }
+
+
+class CanvasStore:
+ """Append/list/remove/clear over one board, each a single transaction."""
+
+ _schema_lock = asyncio.Lock()
+ _initialized_engines: set[Any] = set()
+
+ def __init__(self, database: Any) -> None:
+ self.database = database
+
+ async def ensure_schema(self) -> None:
+ engine = getattr(self.database, "engine", None)
+ if engine is None:
+ raise RuntimeError("Database is not initialized")
+ if engine in self._initialized_engines:
+ return
+ async with self._schema_lock:
+ if engine in self._initialized_engines:
+ return
+ async with engine.begin() as connection:
+ await connection.run_sync(
+ lambda sync_connection: CanvasBoard.__table__.create(
+ sync_connection, checkfirst=True
+ )
+ )
+ await connection.run_sync(
+ lambda sync_connection: CanvasItemRow.__table__.create(
+ sync_connection, checkfirst=True
+ )
+ )
+ self._initialized_engines.add(engine)
+
+ async def append(
+ self,
+ scope: CanvasScope,
+ items: List[Dict[str, Any]],
+ *,
+ mode: str = "append",
+ ) -> tuple[List[Dict[str, Any]], int, int]:
+ """Add items (``mode="replace"`` clears first). Returns
+ ``(added_wire_items, revision, total)`` after FIFO eviction."""
+ await self.ensure_schema()
+ for item in items:
+ if item.get("kind") not in CANVAS_ITEM_KINDS:
+ raise CanvasStoreError(
+ f"Unknown canvas item kind: {item.get('kind')!r}"
+ )
+ async with self.database.get_session() as session:
+ board = await self._board(session, scope, create=True)
+ if mode == "replace":
+ await session.execute(
+ delete(CanvasItemRow).where(
+ CanvasItemRow.board_id == board.id
+ )
+ )
+ next_position = 0
+ else:
+ result = await session.execute(
+ select(func.max(CanvasItemRow.position)).where(
+ CanvasItemRow.board_id == board.id
+ )
+ )
+ current_max = result.scalar()
+ next_position = (current_max + 1) if current_max is not None else 0
+
+ added: List[CanvasItemRow] = []
+ for offset, item in enumerate(items):
+ content = item.get("content")
+ if isinstance(content, str):
+ content, _ = truncate_note(content)
+ row = CanvasItemRow(
+ id=uuid.uuid4().hex,
+ board_id=board.id,
+ kind=str(item["kind"]),
+ title=item.get("title"),
+ ref=item.get("ref"),
+ url=item.get("url"),
+ content=content,
+ language=item.get("language"),
+ source=str(item.get("source") or "workflow"),
+ position=next_position + offset,
+ )
+ session.add(row)
+ added.append(row)
+
+ # FIFO eviction: keep the newest CANVAS_MAX_ITEMS by position.
+ await session.flush()
+ count_result = await session.execute(
+ select(func.count())
+ .select_from(CanvasItemRow)
+ .where(CanvasItemRow.board_id == board.id)
+ )
+ total = int(count_result.scalar() or 0)
+ if total > CANVAS_MAX_ITEMS:
+ overflow = total - CANVAS_MAX_ITEMS
+ oldest = await session.execute(
+ select(CanvasItemRow.id)
+ .where(CanvasItemRow.board_id == board.id)
+ .order_by(CanvasItemRow.position)
+ .limit(overflow)
+ )
+ evicted_ids = [value for (value,) in oldest.all()]
+ if evicted_ids:
+ await session.execute(
+ delete(CanvasItemRow).where(
+ CanvasItemRow.id.in_(evicted_ids)
+ )
+ )
+ total = CANVAS_MAX_ITEMS
+
+ board.revision += 1
+ board.updated_at = _utcnow()
+ session.add(board)
+ await session.commit()
+ return [_serialize(row) for row in added], board.revision, total
+
+ async def list(self, scope: CanvasScope) -> Dict[str, Any]:
+ await self.ensure_schema()
+ async with self.database.get_session() as session:
+ board = await self._board(session, scope, create=False)
+ if board is None:
+ return {"items": [], "revision": 0}
+ result = await session.execute(
+ select(CanvasItemRow)
+ .where(CanvasItemRow.board_id == board.id)
+ .order_by(CanvasItemRow.position)
+ )
+ return {
+ "items": [_serialize(row) for row in result.scalars().all()],
+ "revision": board.revision,
+ }
+
+ async def remove(self, scope: CanvasScope, item_id: str) -> Dict[str, Any]:
+ await self.ensure_schema()
+ async with self.database.get_session() as session:
+ board = await self._board(session, scope, create=False)
+ if board is None:
+ raise CanvasStoreError("No canvas content for this node")
+ result = await session.execute(
+ select(CanvasItemRow).where(
+ CanvasItemRow.board_id == board.id,
+ CanvasItemRow.id == str(item_id or "").strip(),
+ )
+ )
+ row = result.scalars().first()
+ if row is None:
+ raise CanvasStoreError(f"No canvas item with id '{item_id}'")
+ await session.delete(row)
+ board.revision += 1
+ board.updated_at = _utcnow()
+ session.add(board)
+ await session.commit()
+ return {"removed": True, "revision": board.revision}
+
+ async def clear(self, scope: CanvasScope) -> Dict[str, Any]:
+ await self.ensure_schema()
+ async with self.database.get_session() as session:
+ board = await self._board(session, scope, create=False)
+ if board is None:
+ return {"cleared": 0, "revision": 0}
+ result = await session.execute(
+ delete(CanvasItemRow).where(CanvasItemRow.board_id == board.id)
+ )
+ board.revision += 1
+ board.updated_at = _utcnow()
+ session.add(board)
+ await session.commit()
+ return {
+ "cleared": int(getattr(result, "rowcount", 0) or 0),
+ "revision": board.revision,
+ }
+
+ async def _board(
+ self, session: Any, scope: CanvasScope, *, create: bool
+ ) -> Optional[CanvasBoard]:
+ result = await session.execute(
+ select(CanvasBoard).where(CanvasBoard.id == scope.board_id)
+ )
+ board = result.scalars().first()
+ if board is None and create:
+ board = CanvasBoard(
+ id=scope.board_id,
+ owner_id=scope.owner_id,
+ workflow_id=scope.workflow_id,
+ node_id=scope.node_id,
+ )
+ session.add(board)
+ return board
+
+
+__all__ = [
+ "CANVAS_ITEM_KINDS",
+ "CANVAS_MAX_ITEMS",
+ "CANVAS_MAX_PATHS_PER_CALL",
+ "CANVAS_NOTE_MAX_BYTES",
+ "CanvasBoard",
+ "CanvasItemRow",
+ "CanvasScope",
+ "CanvasStore",
+ "CanvasStoreError",
+ "UNSAVED_WORKFLOW_ID",
+ "truncate_note",
+]
diff --git a/server/nodes/tool/canvas/meta.json b/server/nodes/tool/canvas/meta.json
new file mode 100644
index 00000000..507ea9d6
--- /dev/null
+++ b/server/nodes/tool/canvas/meta.json
@@ -0,0 +1,6 @@
+{
+ "color": "#8be9fd",
+ "icons": {
+ "canvas": "lucide:Monitor"
+ }
+}
diff --git a/server/services/media/preview.py b/server/services/media/preview.py
index 336e9542..4d3f49cd 100644
--- a/server/services/media/preview.py
+++ b/server/services/media/preview.py
@@ -15,7 +15,7 @@ from __future__ import annotations
from typing import Literal, Optional
-PreviewKind = Literal["image", "audio", "video", "none"]
+PreviewKind = Literal["image", "audio", "video", "pdf", "none"]
# Types a browser may render in place. Everything else downloads.
#
@@ -24,7 +24,13 @@ PreviewKind = Literal["image", "audio", "video", "none"]
# arbitrary files into a workspace, so serving attacker-authored markup
# inline from the app origin would be stored XSS with access to the session
# cookie. Both types are script-bearing.
+#
+# `application/pdf` is an exact-match addition (Canvas node): the browser's
+# built-in PDF viewer renders it isolated from the page, so the exposure
+# class is the same as images — not the markup-from-app-origin class
+# NEVER_INLINE guards.
INLINE_PREFIXES = ("audio/", "image/", "video/")
+INLINE_EXACT = frozenset({"application/pdf"})
NEVER_INLINE = frozenset(
{"image/svg+xml", "text/html", "text/xml", "application/xhtml+xml"}
)
@@ -34,7 +40,9 @@ def serves_inline(mime_type: Optional[str]) -> bool:
"""Whether the workspace route will serve this with ``inline`` disposition."""
if not mime_type:
return False
- return mime_type.startswith(INLINE_PREFIXES) and mime_type not in NEVER_INLINE
+ return (
+ mime_type.startswith(INLINE_PREFIXES) or mime_type in INLINE_EXACT
+ ) and mime_type not in NEVER_INLINE
def preview_kind(mime_type: Optional[str]) -> PreviewKind:
@@ -51,10 +59,13 @@ def preview_kind(mime_type: Optional[str]) -> PreviewKind:
return "audio"
if mime_type.startswith("video/"):
return "video"
+ if mime_type == "application/pdf":
+ return "pdf"
return "none"
__all__ = [
+ "INLINE_EXACT",
"INLINE_PREFIXES",
"NEVER_INLINE",
"PreviewKind",
diff --git a/server/services/node_executor.py b/server/services/node_executor.py
index 800517db..b7a40b8f 100644
--- a/server/services/node_executor.py
+++ b/server/services/node_executor.py
@@ -269,6 +269,7 @@ class NodeExecutor:
"webhookResponse",
"console",
"socialReceive",
+ "canvas",
}
)
diff --git a/server/tests/nodes/test_browser_screenshots.py b/server/tests/nodes/test_browser_screenshots.py
new file mode 100644
index 00000000..5277ce0c
--- /dev/null
+++ b/server/tests/nodes/test_browser_screenshots.py
@@ -0,0 +1,119 @@
+"""Screenshot persistence helpers shared by the browser plugins.
+
+Tolerance is the contract: unrecognized payload shapes pass through
+(``(None, None)``), and persistence failures never raise into the browser
+operation. The harness path helper is containment-checked — printed process
+output is not a licence to read arbitrary files.
+"""
+
+from __future__ import annotations
+
+import base64
+
+from nodes.browser._screenshots import (
+ persist_screenshot_file,
+ persist_screenshot_from_payload,
+)
+from services.plugin import NodeContext
+
+
+def _ctx(tmp_path, workflow_id="wf-shot") -> NodeContext:
+ return NodeContext(
+ node_id="browser-1",
+ node_type="browser",
+ workflow_id=workflow_id,
+ workspace_dir=str(tmp_path),
+ )
+
+
+def _fake_png(size: int = 1024) -> bytes:
+ return b"\x89PNG\r\n\x1a\n" + b"x" * size
+
+
+def test_base64_payload_is_persisted_and_bulky_key_named(tmp_path):
+ payload = {"success": True, "base64": base64.b64encode(_fake_png()).decode()}
+
+ ref, consumed = persist_screenshot_from_payload(payload, _ctx(tmp_path))
+
+ assert consumed == "base64"
+ assert ref is not None
+ assert ref["kind"] == "image"
+ assert ref["mime_type"] == "image/png"
+ assert ref["path"].startswith("media/screenshot-")
+ stored = tmp_path / ref["path"]
+ assert stored.is_file()
+ assert stored.read_bytes() == _fake_png()
+
+
+def test_jpeg_format_is_respected(tmp_path):
+ payload = {"base64": base64.b64encode(_fake_png()).decode()}
+ ref, _ = persist_screenshot_from_payload(payload, _ctx(tmp_path), fmt="jpeg")
+ assert ref is not None
+ assert ref["mime_type"] == "image/jpeg"
+ assert ref["path"].endswith(".jpg")
+
+
+def test_unrecognized_shapes_pass_through(tmp_path):
+ ctx = _ctx(tmp_path)
+ assert persist_screenshot_from_payload("not a dict", ctx) == (None, None)
+ assert persist_screenshot_from_payload({"output": "plain text"}, ctx) == (None, None)
+ # Short strings and invalid base64 are skipped, not errors.
+ assert persist_screenshot_from_payload({"base64": "AAAA"}, ctx) == (None, None)
+ assert persist_screenshot_from_payload(
+ {"base64": "!" * 400}, ctx
+ ) == (None, None)
+
+
+def test_tiny_decoded_payload_is_refused(tmp_path):
+ payload = {"base64": base64.b64encode(b"tiny").decode().ljust(300, "=")}
+ assert persist_screenshot_from_payload(payload, _ctx(tmp_path)) == (None, None)
+
+
+def test_missing_workspace_never_raises(tmp_path):
+ ctx = NodeContext(node_id="n", node_type="browser", workflow_id="wf")
+ payload = {"base64": base64.b64encode(_fake_png()).decode()}
+ assert persist_screenshot_from_payload(payload, ctx) == (None, None)
+
+
+def test_saved_file_path_form(tmp_path):
+ source = tmp_path / "cache"
+ source.mkdir()
+ shot = source / "shot.png"
+ shot.write_bytes(_fake_png())
+ workspace = tmp_path / "ws"
+ workspace.mkdir()
+
+ ref, consumed = persist_screenshot_from_payload(
+ {"path": str(shot)}, _ctx(workspace)
+ )
+ assert consumed is None
+ assert ref is not None
+ assert (workspace / ref["path"]).is_file()
+
+
+def test_harness_file_is_contained_under_runtime_dir(tmp_path):
+ runtime = tmp_path / "daemons" / "browser-harness"
+ (runtime / "tmp").mkdir(parents=True)
+ shot = runtime / "tmp" / "shot-1.png"
+ shot.write_bytes(_fake_png())
+ workspace = tmp_path / "ws"
+ workspace.mkdir()
+
+ ref = persist_screenshot_file(str(shot), _ctx(workspace), contained_under=runtime)
+ assert ref is not None
+ assert ref["kind"] == "image"
+
+ # Outside the harness dir: refused, never read.
+ outside = tmp_path / "credentials.db"
+ outside.write_bytes(_fake_png())
+ assert (
+ persist_screenshot_file(str(outside), _ctx(workspace), contained_under=runtime)
+ is None
+ )
+ # Non-image suffixes are refused even when contained.
+ text = runtime / "tmp" / "notes.txt"
+ text.write_text("hi")
+ assert (
+ persist_screenshot_file(str(text), _ctx(workspace), contained_under=runtime)
+ is None
+ )
diff --git a/server/tests/nodes/test_canvas_node.py b/server/tests/nodes/test_canvas_node.py
new file mode 100644
index 00000000..4c19464b
--- /dev/null
+++ b/server/tests/nodes/test_canvas_node.py
@@ -0,0 +1,579 @@
+"""Canvas node — board store, display op, panel handlers, event contract.
+
+Mirrors the named precedents:
+- store fixture shape: tests/services/memory/test_tool_store.py (private real
+ core.database load — the root conftest stubs it for unit speed)
+- handler security: tests/services/test_tool_input_security.py (internal
+ socket denial / owner mismatch / node-type check)
+- event identity lock: tests/nodes/test_write_todos_handlers.py
+"""
+
+from __future__ import annotations
+
+import importlib.util
+import sys
+import uuid
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+
+from nodes.tool.canvas import (
+ CanvasNode,
+ CanvasParams,
+ _collect_connected_refs,
+)
+from nodes.tool.canvas._events import canvas_updated
+from nodes.tool.canvas._handlers import (
+ handle_canvas_clear,
+ handle_canvas_list,
+ handle_canvas_remove,
+)
+from nodes.tool.canvas._store import (
+ CANVAS_NOTE_MAX_BYTES,
+ CanvasScope,
+ CanvasStore,
+ CanvasStoreError,
+ truncate_note,
+)
+from services.plugin import NodeContext, NodeUserError
+
+
+# ---------------------------------------------------------------------------
+# Real-database fixture (root conftest stubs core.database; load it privately)
+# ---------------------------------------------------------------------------
+
+
+async def canvas_database():
+ module_name = f"tests._real_canvas_database_{uuid.uuid4().hex}"
+ spec = importlib.util.spec_from_file_location(
+ module_name,
+ Path(__file__).resolve().parents[2] / "core" / "database.py",
+ )
+ assert spec is not None and spec.loader is not None
+ module = importlib.util.module_from_spec(spec)
+ sys.modules[module_name] = module
+ spec.loader.exec_module(module)
+
+ db_path = Path.cwd() / f".canvas-{uuid.uuid4().hex}.db"
+ database = module.Database(
+ SimpleNamespace(
+ database_url=f"sqlite+aiosqlite:///{db_path.as_posix()}",
+ database_echo=False,
+ database_pool_size=5,
+ database_max_overflow=5,
+ )
+ )
+ await database.startup()
+ try:
+ yield database
+ finally:
+ await database.shutdown()
+ sys.modules.pop(module_name, None)
+ for candidate in (
+ db_path,
+ Path(f"{db_path}-wal"),
+ Path(f"{db_path}-shm"),
+ ):
+ candidate.unlink(missing_ok=True)
+
+
+def _scope(node_id: str = "canvas-1", workflow_id: str = "wf-1") -> CanvasScope:
+ return CanvasScope(
+ owner_id="owner", workflow_id=workflow_id, node_id=node_id
+ )
+
+
+# ---------------------------------------------------------------------------
+# Store
+# ---------------------------------------------------------------------------
+
+
+async def test_store_scope_isolation_between_nodes(canvas_database):
+ store = CanvasStore(canvas_database)
+ a, b = _scope("canvas-a"), _scope("canvas-b")
+
+ await store.append(a, [{"kind": "note", "content": "only on a"}])
+
+ assert len((await store.list(a))["items"]) == 1
+ assert (await store.list(b)) == {"items": [], "revision": 0}
+
+
+async def test_store_append_replace_and_revision_monotonicity(canvas_database):
+ store = CanvasStore(canvas_database)
+ scope = _scope()
+
+ _, r1, total1 = await store.append(
+ scope, [{"kind": "note", "content": "one"}]
+ )
+ _, r2, total2 = await store.append(
+ scope, [{"kind": "url", "url": "https://example.com"}]
+ )
+ assert (r1, total1) == (1, 1)
+ assert (r2, total2) == (2, 2)
+
+ added, r3, total3 = await store.append(
+ scope, [{"kind": "note", "content": "fresh"}], mode="replace"
+ )
+ assert (r3, total3) == (3, 1)
+ items = (await store.list(scope))["items"]
+ assert [row["id"] for row in items] == [added[0]["id"]]
+
+ removed = await store.remove(scope, added[0]["id"])
+ assert removed == {"removed": True, "revision": 4}
+ cleared = await store.clear(scope)
+ assert cleared["revision"] == 5
+
+ with pytest.raises(CanvasStoreError):
+ await store.remove(scope, "no-such-item")
+
+
+async def test_store_fifo_eviction_at_cap(canvas_database, monkeypatch):
+ monkeypatch.setattr("nodes.tool.canvas._store.CANVAS_MAX_ITEMS", 3)
+ store = CanvasStore(canvas_database)
+ scope = _scope()
+
+ for index in range(5):
+ await store.append(
+ scope, [{"kind": "note", "content": f"note-{index}"}]
+ )
+
+ listed = await store.list(scope)
+ assert [row["content"] for row in listed["items"]] == [
+ "note-2",
+ "note-3",
+ "note-4",
+ ]
+ assert listed["revision"] == 5
+
+
+async def test_store_rejects_unknown_kind(canvas_database):
+ store = CanvasStore(canvas_database)
+ with pytest.raises(CanvasStoreError):
+ await store.append(_scope(), [{"kind": "bytes", "content": "x"}])
+
+
+async def test_item_wire_shape_is_stable(canvas_database):
+ store = CanvasStore(canvas_database)
+ added, _, _ = await store.append(
+ _scope(), [{"kind": "note", "content": "shape", "title": "t"}]
+ )
+ assert set(added[0]) == {
+ "id",
+ "kind",
+ "title",
+ "ref",
+ "url",
+ "content",
+ "language",
+ "source",
+ "created_at",
+ }
+
+
+def test_truncate_note_caps_with_visible_marker():
+ text, truncated = truncate_note("x" * (CANVAS_NOTE_MAX_BYTES + 100))
+ assert truncated is True
+ assert text.endswith("[truncated]")
+ assert len(text.encode("utf-8")) <= CANVAS_NOTE_MAX_BYTES
+
+ short, untouched = truncate_note("short")
+ assert (short, untouched) == ("short", False)
+
+
+def test_board_id_is_versioned_and_scope_sensitive():
+ base = _scope()
+ assert base.board_id.startswith("canv_")
+ assert base.board_id != _scope(node_id="other").board_id
+ assert base.board_id != _scope(workflow_id="wf-2").board_id
+
+
+# ---------------------------------------------------------------------------
+# Display op (direct op call with a constructed NodeContext)
+# ---------------------------------------------------------------------------
+
+
+def _node() -> CanvasNode:
+ return CanvasNode()
+
+
+def _ctx(tmp_path, *, raw=None, workflow_id="wf-op") -> NodeContext:
+ return NodeContext(
+ node_id="canvas-node",
+ node_type="canvas",
+ workflow_id=workflow_id,
+ workspace_dir=str(tmp_path),
+ raw=raw or {},
+ )
+
+
+def op_database(canvas_database, monkeypatch):
+ monkeypatch.setattr(
+ "services.plugin.deps.get_database", lambda: canvas_database
+ )
+ return canvas_database
+
+
+def captured_events(monkeypatch):
+ events = []
+
+ async def _capture(**kwargs):
+ events.append(kwargs)
+
+ monkeypatch.setattr(
+ "nodes.tool.canvas._events.dispatch_canvas_updated", _capture
+ )
+ return events
+
+
+async def test_display_paths_builds_contained_refs(
+ tmp_path, op_database, captured_events
+):
+ media = tmp_path / "media"
+ media.mkdir()
+ (media / "chart.png").write_bytes(b"\x89PNG fake")
+
+ result = await _node().display(
+ _ctx(tmp_path),
+ CanvasParams(paths=["media/chart.png"], title="Q3 chart"),
+ )
+
+ assert result["count"] == 1
+ assert result["added"][0]["kind"] == "file"
+ assert result["added"][0]["title"] == "Q3 chart"
+ # Payload discipline: ids and titles only — no ref bodies in the output.
+ assert set(result["added"][0]) == {"id", "kind", "title"}
+ assert captured_events == [
+ {"workflow_id": "wf-op", "node_id": "canvas-node", "revision": 1}
+ ]
+
+ store = CanvasStore(op_database)
+ items = (
+ await store.list(
+ CanvasScope(
+ owner_id="owner", workflow_id="wf-op", node_id="canvas-node"
+ )
+ )
+ )["items"]
+ ref = items[0]["ref"]
+ assert ref["kind"] == "file"
+ assert ref["path"] == "media/chart.png"
+ assert ref["mime_type"] == "image/png"
+ assert ref["workflow_id"] == "wf-op"
+ assert ref["url"] == "/api/workspace/wf-op/files/media/chart.png"
+
+
+async def test_display_rejects_traversal_paths(
+ tmp_path, op_database, captured_events
+):
+ with pytest.raises(NodeUserError):
+ await _node().display(
+ _ctx(tmp_path), CanvasParams(paths=["../../credentials.db"])
+ )
+ assert captured_events == []
+
+
+async def test_display_rejects_non_http_url(
+ tmp_path, op_database, captured_events
+):
+ with pytest.raises(NodeUserError):
+ await _node().display(
+ _ctx(tmp_path), CanvasParams(url="javascript:alert(1)")
+ )
+ with pytest.raises(NodeUserError):
+ await _node().display(
+ _ctx(tmp_path), CanvasParams(url="file:///etc/passwd")
+ )
+
+
+async def test_display_note_truncates_and_reports(
+ tmp_path, op_database, captured_events
+):
+ result = await _node().display(
+ _ctx(tmp_path),
+ CanvasParams(content="y" * (CANVAS_NOTE_MAX_BYTES + 10)),
+ )
+ assert "truncated" in result["message"]
+
+
+async def test_display_empty_call_is_user_correctable(
+ tmp_path, op_database, captured_events
+):
+ with pytest.raises(NodeUserError):
+ await _node().display(_ctx(tmp_path), CanvasParams())
+
+
+async def test_display_scans_connected_outputs_for_refs(
+ tmp_path, op_database, captured_events
+):
+ connected = {
+ "textToSpeech": {
+ "audio": {
+ "kind": "audio",
+ "path": "audio/greeting.wav",
+ "filename": "greeting.wav",
+ "format": "wav",
+ },
+ # A gallery-style listing row is NOT a ref (extra keys fail
+ # extra="forbid") — but the ref nested inside it is found.
+ "row": {
+ "name": "x.png",
+ "is_dir": False,
+ "ref": {
+ "kind": "file",
+ "path": "media/x.png",
+ "filename": "x.png",
+ },
+ },
+ }
+ }
+ result = await _node().display(
+ _ctx(tmp_path, raw={"connected_outputs": connected}), CanvasParams()
+ )
+ assert result["count"] == 2
+ assert {entry["kind"] for entry in result["added"]} == {"file"}
+
+
+async def test_display_labels_tool_calls_as_agent(
+ tmp_path, op_database, captured_events
+):
+ await _node().display(
+ _ctx(tmp_path, raw={"_tool_config": object()}),
+ CanvasParams(content="from the model"),
+ )
+ store = CanvasStore(op_database)
+ items = (
+ await store.list(
+ CanvasScope(
+ owner_id="owner", workflow_id="wf-op", node_id="canvas-node"
+ )
+ )
+ )["items"]
+ assert items[0]["source"] == "agent"
+
+
+async def test_display_replace_mode_clears_board(
+ tmp_path, op_database, captured_events
+):
+ node, ctx = _node(), _ctx(tmp_path)
+ await node.display(ctx, CanvasParams(content="first"))
+ result = await node.display(
+ ctx, CanvasParams(content="second", mode="replace")
+ )
+ assert result["count"] == 1
+ assert "replaced" in result["message"]
+
+
+def test_collect_connected_refs_dedupes_and_caps():
+ ref = {"kind": "file", "path": "a/b.png", "filename": "b.png"}
+ payload = {
+ "one": ref,
+ "two": {"nested": [dict(ref), {"kind": "file", "path": "c.md", "filename": "c.md"}]},
+ "not_a_ref": {"kind": "file", "path": "x", "filename": "x", "extra_key": 1},
+ }
+ refs = _collect_connected_refs(payload, limit=10)
+ assert [r["path"] for r in refs] == ["a/b.png", "c.md"]
+
+ many = {str(i): {"kind": "file", "path": f"p{i}", "filename": f"p{i}"} for i in range(9)}
+ assert len(_collect_connected_refs(many, limit=3)) == 3
+
+
+# ---------------------------------------------------------------------------
+# Params coercion
+# ---------------------------------------------------------------------------
+
+
+def test_params_coerce_paths_shapes():
+ assert CanvasParams(paths='["a.png", "b.md"]').paths == ["a.png", "b.md"]
+ assert CanvasParams(paths="single/path.png").paths == ["single/path.png"]
+ assert CanvasParams(
+ paths=[{"kind": "file", "path": "from/ref.wav", "filename": "ref.wav"}]
+ ).paths == ["from/ref.wav"]
+ assert CanvasParams(paths="").paths is None
+ # Blank-string mode from a cleared panel field falls back to the default.
+ assert CanvasParams(mode="").mode == "append"
+
+
+# ---------------------------------------------------------------------------
+# Panel WS handlers — security preamble + round trip
+# ---------------------------------------------------------------------------
+
+
+class _FakeSocket:
+ def __init__(self, *, path="/ws/status", user_id="owner"):
+ self.scope = {"path": path, "user_id": user_id}
+ self.state = SimpleNamespace(user_id=user_id)
+
+
+class _HandlerDatabase:
+ """Real store engine + a canned workflow graph for scope resolution."""
+
+ def __init__(self, database, graph):
+ self._database = database
+ self._graph = graph
+
+ @property
+ def engine(self):
+ return self._database.engine
+
+ def get_session(self):
+ return self._database.get_session()
+
+ async def get_workflow(self, workflow_id):
+ if workflow_id != self._graph["id"]:
+ return None
+ return SimpleNamespace(data=self._graph)
+
+
+def _graph(workflow_id="wf-h", node_id="canvas-h", node_type="canvas", owner="owner"):
+ return {
+ "id": workflow_id,
+ "owner_id": owner,
+ "nodes": [{"id": node_id, "type": node_type}],
+ "edges": [],
+ }
+
+
+def handler_env(canvas_database, monkeypatch):
+ def bind(graph):
+ wrapper = _HandlerDatabase(canvas_database, graph)
+ monkeypatch.setattr(
+ "nodes.tool.canvas._handlers.get_database", lambda: wrapper
+ )
+ return wrapper
+
+ return bind
+
+
+def handler_events(monkeypatch):
+ events = []
+
+ async def _capture(**kwargs):
+ events.append(kwargs)
+
+ monkeypatch.setattr(
+ "nodes.tool.canvas._handlers.dispatch_canvas_updated", _capture
+ )
+ return events
+
+
+async def test_internal_socket_is_denied(handler_env, handler_events):
+ handler_env(_graph())
+ response = await handle_canvas_list(
+ {"workflow_id": "wf-h", "node_id": "canvas-h"},
+ _FakeSocket(path="/ws/internal"),
+ )
+ assert response["success"] is False
+ assert "authenticated" in response["error"]
+
+
+async def test_owner_mismatch_is_denied(handler_env, handler_events):
+ handler_env(_graph(owner="someone-else"))
+ response = await handle_canvas_list(
+ {"workflow_id": "wf-h", "node_id": "canvas-h"}, _FakeSocket()
+ )
+ assert response["success"] is False
+ assert "denied" in response["error"].lower()
+
+
+async def test_wrong_node_type_is_denied(handler_env, handler_events):
+ handler_env(_graph(node_type="simpleMemory"))
+ response = await handle_canvas_list(
+ {"workflow_id": "wf-h", "node_id": "canvas-h"}, _FakeSocket()
+ )
+ assert response["success"] is False
+ assert "does not belong" in response["error"]
+
+
+async def test_handler_round_trip_list_remove_clear(
+ canvas_database, handler_env, handler_events
+):
+ handler_env(_graph())
+ store = CanvasStore(canvas_database)
+ scope = CanvasScope(owner_id="owner", workflow_id="wf-h", node_id="canvas-h")
+ added, _, _ = await store.append(
+ scope,
+ [
+ {"kind": "note", "content": "keep"},
+ {"kind": "note", "content": "drop"},
+ ],
+ )
+
+ listed = await handle_canvas_list(
+ {"workflow_id": "wf-h", "node_id": "canvas-h"}, _FakeSocket()
+ )
+ assert listed["success"] is True
+ assert [row["content"] for row in listed["items"]] == ["keep", "drop"]
+
+ removed = await handle_canvas_remove(
+ {
+ "workflow_id": "wf-h",
+ "node_id": "canvas-h",
+ "item_id": added[1]["id"],
+ },
+ _FakeSocket(),
+ )
+ assert removed["success"] is True
+
+ cleared = await handle_canvas_clear(
+ {"workflow_id": "wf-h", "node_id": "canvas-h"}, _FakeSocket()
+ )
+ assert cleared["success"] is True
+
+ # Both mutations broadcast identity + revision.
+ assert [event["node_id"] for event in handler_events] == [
+ "canvas-h",
+ "canvas-h",
+ ]
+
+ final = await handle_canvas_list(
+ {"workflow_id": "wf-h", "node_id": "canvas-h"}, _FakeSocket()
+ )
+ assert final["items"] == []
+
+
+# ---------------------------------------------------------------------------
+# Event + tool-schema contract locks
+# ---------------------------------------------------------------------------
+
+
+def test_canvas_updated_event_is_identity_only():
+ event = canvas_updated(workflow_id="wf-e", node_id="canvas-e", revision=7)
+ assert event.source == "opencompany://nodes/canvas"
+ assert event.type == "com.opencompany.canvas.updated"
+ assert event.subject == "canvas-e"
+ assert event.data == {
+ "workflow_id": "wf-e",
+ "node_id": "canvas-e",
+ "revision": 7,
+ }
+
+
+def test_tool_schema_is_locked_flat_and_named_canvas():
+ schema = CanvasNode.as_tool_schema()
+ assert schema["name"] == "canvas"
+ assert CanvasNode.tool_schema_locked is True
+
+ def assert_no_ref_keys(value):
+ if isinstance(value, dict):
+ assert "$defs" not in value and "$ref" not in value, value.keys()
+ for child in value.values():
+ assert_no_ref_keys(child)
+ elif isinstance(value, list):
+ for child in value:
+ assert_no_ref_keys(child)
+
+ assert_no_ref_keys(schema)
+
+ assert CanvasNode.ui_hints["isCanvasPanel"] is True
+ assert CanvasNode.ui_hints["isConfigNode"] is False
+ assert CanvasNode.annotations == {
+ "destructive": False,
+ "readonly": False,
+ "open_world": False,
+ }
diff --git a/server/tests/routers/test_workspace.py b/server/tests/routers/test_workspace.py
index 66e4a738..96595794 100644
--- a/server/tests/routers/test_workspace.py
+++ b/server/tests/routers/test_workspace.py
@@ -273,9 +273,21 @@ class TestInlineDispositionHasOneDefinition:
assert serves_inline(mime) is True, mime
assert preview_kind(mime) == kind, mime
+ def test_pdf_is_inline_exact_match(self):
+ """PDF renders in the browser's built-in viewer (Canvas node).
+
+ Exact-match only — ``application/pdf`` rides ``INLINE_EXACT``, not a
+ prefix, so no other ``application/*`` type gains inline serving as a
+ side effect.
+ """
+ from services.media.preview import preview_kind, serves_inline
+
+ assert serves_inline("application/pdf") is True
+ assert preview_kind("application/pdf") == "pdf"
+
def test_everything_else_downloads(self):
from services.media.preview import preview_kind, serves_inline
- for mime in ("application/pdf", "text/plain", "application/octet-stream", None):
+ for mime in ("text/plain", "application/octet-stream", "application/x-pdf", None):
assert serves_inline(mime) is False, mime
assert preview_kind(mime) == "none", mime
diff --git a/server/tests/test_node_spec.py b/server/tests/test_node_spec.py
index bfa29747..5e61e20d 100644
--- a/server/tests/test_node_spec.py
+++ b/server/tests/test_node_spec.py
@@ -939,6 +939,9 @@ class TestNodeSpecContractInvariants:
"isProcessManagerPanel",
# gallery: workspace file browser with drag-to-parameter.
"isGalleryPanel",
+ # canvas: pushed-content display board (parameter panel host;
+ # the docked canvas sidebar reads the same flag to find nodes).
+ "isCanvasPanel",
# Auto-derived on every node from BaseNode.start_to_close_timeout:
# how long it may legitimately run. Lets the client size its
# request budget instead of keeping its own list of slow types.