Skip to content

Self-improving AI Employees for everyone

feat(chat): document cards that open the Canvas at their version

trohitg724f6c3cbf90
diff --git a/client/src/components/parameterPanel/CanvasPanel.tsx b/client/src/components/parameterPanel/CanvasPanel.tsx
index 77b2c15a..865e9b9d 100644
--- a/client/src/components/parameterPanel/CanvasPanel.tsx
+++ b/client/src/components/parameterPanel/CanvasPanel.tsx
@@ -74,6 +74,7 @@ const CanvasPanel: React.FC<Props> = ({ nodeId, workflowId }) => {
<CanvasContent
items={items}
workflowId={workflowId}
+ nodeId={nodeId}
onRemove={(itemId) =>
removeItem.mutate(itemId, {
onError: (error) => toast.error(error.message),
diff --git a/client/src/components/parameterPanel/canvas/CanvasContent.tsx b/client/src/components/parameterPanel/canvas/CanvasContent.tsx
index f6b1e508..fdae94af 100644
--- a/client/src/components/parameterPanel/canvas/CanvasContent.tsx
+++ b/client/src/components/parameterPanel/canvas/CanvasContent.tsx
@@ -21,16 +21,12 @@ import {
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 { useWebSocketActions } from '../../../contexts/WebSocketContext';
-import type { CanvasItem } from '../../../lib/canvasBoard';
+import type { CanvasFocus, CanvasItem } from '../../../lib/canvasBoard';
import type {
ListWorkspaceFilesResponse,
WorkspaceFileRef,
@@ -42,6 +38,7 @@ import {
prismLanguageFor,
resolveRenderKind,
} from './canvasKinds';
+import NoteView from './NoteView';
import TextFileView from './TextFileView';
import { ExternalSiteView, PdfView, WorkspaceHtmlView } from './WebView';
@@ -50,6 +47,12 @@ const FOLLOW_POLL_MS = 5_000;
interface Props {
items: CanvasItem[];
workflowId?: string | null;
+ /** The Canvas node whose board this is: a note's earlier versions are
+ * read from it. */
+ nodeId?: string | null;
+ /** Show this item, at this version (a chat reply's artifact card). It
+ * stays shown while newer items arrive; a new nonce asks again. */
+ focus?: CanvasFocus | null;
onRemove?: (itemId: string) => void;
emptyHint?: React.ReactNode;
/** Initial state of the follow-latest toggle (dock persists it). */
@@ -99,6 +102,8 @@ const BinaryView: React.FC<{ refFile: WorkspaceFileRef }> = ({ refFile }) => {
const CanvasContent: React.FC<Props> = ({
items,
workflowId,
+ nodeId,
+ focus,
onRemove,
emptyHint,
followLatestDefault = false,
@@ -109,6 +114,16 @@ const CanvasContent: React.FC<Props> = ({
const [followLatest, setFollowLatest] = useState(followLatestDefault);
const [mediaFailed, setMediaFailed] = useState(false);
+ // A focus request lands once its item is on the board, and holds until
+ // the user moves to another item.
+ const [focusNonce, setFocusNonce] = useState<number | null>(null);
+ const [heldFocus, setHeldFocus] = useState<CanvasFocus | null>(null);
+ if (focus && focus.nonce !== focusNonce && items.some((item) => item.id === focus.itemId)) {
+ setFocusNonce(focus.nonce);
+ setHeldFocus(focus);
+ setPinnedId(focus.itemId);
+ }
+
const activeIndex = useMemo(() => {
if (items.length === 0) return -1;
if (pinnedId) {
@@ -127,6 +142,7 @@ const CanvasContent: React.FC<Props> = ({
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);
+ setHeldFocus(null);
},
[items],
);
@@ -145,6 +161,7 @@ const CanvasContent: React.FC<Props> = ({
} else if (event.key === 'End') {
event.preventDefault();
setPinnedId(null);
+ setHeldFocus(null);
}
},
[activeIndex, goTo],
@@ -198,11 +215,13 @@ const CanvasContent: React.FC<Props> = ({
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>
+ <NoteView
+ key={active.id}
+ item={active}
+ workflowId={workflowId}
+ nodeId={nodeId}
+ focus={heldFocus?.itemId === active.id ? heldFocus : null}
+ />
);
case 'web-external':
return <ExternalSiteView url={active.url ?? ''} title={active.title} />;
@@ -356,6 +375,9 @@ const CanvasContent: React.FC<Props> = ({
function canvasContentPropsEqual(prev: Props, next: Props): boolean {
return (
prev.workflowId === next.workflowId &&
+ prev.nodeId === next.nodeId &&
+ prev.focus?.nonce === next.focus?.nonce &&
+ prev.focus?.itemId === next.focus?.itemId &&
prev.followLatestDefault === next.followLatestDefault &&
prev.emptyHint === next.emptyHint &&
prev.items.length === next.items.length &&
diff --git a/client/src/components/parameterPanel/canvas/NoteView.tsx b/client/src/components/parameterPanel/canvas/NoteView.tsx
new file mode 100644
index 00000000..a0330f56
--- /dev/null
+++ b/client/src/components/parameterPanel/canvas/NoteView.tsx
@@ -0,0 +1,196 @@
+/**
+ * A Canvas note as a document (design handoff chat, "artifact panel"): its
+ * versions (‹ v2/3 ›), Preview or the Markdown source, Copy, and Download
+ * as a .md file (.txt for code). The board's item is the latest version; an
+ * earlier one is read through `canvas_version` when the owner steps back to
+ * it. A newer version arriving shows itself, unless the owner stepped back.
+ * `focus` opens it at a version (a chat reply's artifact card names one). A
+ * note with a language other than Markdown is code, previewed as a code
+ * block (the server names it the same way on a reply's card).
+ */
+
+import { Check, ChevronLeft, ChevronRight, Copy, Download } from 'lucide-react';
+import { useEffect, useState } from 'react';
+import ReactMarkdown from 'react-markdown';
+import remarkBreaks from 'remark-breaks';
+import remarkGfm from 'remark-gfm';
+import { useQuery } from '@tanstack/react-query';
+
+import { Button } from '@/components/ui/button';
+import { ToggleGroup, ToggleGroupItem } from '@/components/ui/toggle-group';
+import { useWebSocketActions } from '../../../contexts/WebSocketContext';
+import type { CanvasFocus, CanvasItem, CanvasVersionResponse } from '../../../lib/canvasBoard';
+
+const COPIED_MS = 1600;
+/** Languages a note is a document in; any other makes it code. */
+const DOCUMENT_LANGUAGES = new Set(['markdown', 'md']);
+
+function codeLanguage(language: string | null | undefined): string | null {
+ const name = (language ?? '').trim().toLowerCase();
+ return name && !DOCUMENT_LANGUAGES.has(name) ? name : null;
+}
+
+/** Code, fenced so it previews as a code block whatever backticks it holds. */
+function fenced(content: string, language: string): string {
+ const longest = Math.max(0, ...(content.match(/`+/g) ?? []).map((run) => run.length));
+ const fence = '`'.repeat(Math.max(3, longest + 1));
+ return `${fence}${language}\n${content}\n${fence}`;
+}
+
+/** The download's name: the title, or "document", and the version. */
+function noteFileName(title: string | null, version: number, extension: string): string {
+ const base =
+ (title ?? '')
+ .replace(/[^\p{L}\p{N}\- ]+/gu, '')
+ .trim()
+ .replace(/\s+/g, '-')
+ .slice(0, 60) || 'document';
+ return `${base}${version > 1 ? `-v${version}` : ''}.${extension}`;
+}
+
+export default function NoteView({
+ item,
+ workflowId,
+ nodeId,
+ focus,
+}: {
+ item: CanvasItem;
+ workflowId?: string | null;
+ nodeId?: string | null;
+ focus?: Pick<CanvasFocus, 'version' | 'nonce'> | null;
+}) {
+ const { sendRequest, isReady } = useWebSocketActions();
+ const latest = item.version ?? 1;
+ const [shown, setShown] = useState(latest);
+ const [view, setView] = useState<'preview' | 'source'>('preview');
+ const [copied, setCopied] = useState(false);
+
+ // A newer version arrives: show it, unless the owner stepped back.
+ const [seen, setSeen] = useState(latest);
+ if (latest !== seen) {
+ setSeen(latest);
+ if (shown === seen) setShown(latest);
+ }
+ // A card asks for a version (each ask once).
+ const [focusNonce, setFocusNonce] = useState<number | null>(null);
+ if (focus && focus.nonce !== focusNonce) {
+ setFocusNonce(focus.nonce);
+ setShown(focus.version && focus.version >= 1 && focus.version <= latest ? focus.version : latest);
+ }
+
+ // Earlier versions are read from the board's node; without one, only the
+ // latest shows.
+ const canStep = latest > 1 && Boolean(workflowId && nodeId);
+ const earlier = canStep && shown !== latest;
+ const versionQuery = useQuery<CanvasVersionResponse>({
+ queryKey: ['canvasVersion', workflowId ?? '', nodeId ?? '', item.id, shown],
+ enabled: earlier && isReady,
+ // A saved version never changes.
+ staleTime: Infinity,
+ queryFn: () =>
+ sendRequest<CanvasVersionResponse>('canvas_version', {
+ workflow_id: workflowId,
+ node_id: nodeId,
+ item_id: item.id,
+ version: shown,
+ }),
+ });
+ const failed = earlier && (versionQuery.isError || versionQuery.data?.success === false);
+ const content = earlier ? (versionQuery.data?.item?.content ?? '') : (item.content ?? '');
+ const code = codeLanguage(earlier ? versionQuery.data?.item?.language : item.language);
+ const number = earlier ? shown : latest;
+
+ useEffect(() => {
+ if (!copied) return;
+ const timer = window.setTimeout(() => setCopied(false), COPIED_MS);
+ return () => window.clearTimeout(timer);
+ }, [copied]);
+
+ const copy = () => {
+ void navigator.clipboard?.writeText(content).then(
+ () => setCopied(true),
+ () => undefined,
+ );
+ };
+ const download = () => {
+ const url = URL.createObjectURL(new Blob([content], { type: `${code ? 'text/plain' : 'text/markdown'};charset=utf-8` }));
+ const link = document.createElement('a');
+ link.href = url;
+ link.download = noteFileName(item.title, number, code ? 'txt' : 'md');
+ link.click();
+ window.setTimeout(() => URL.revokeObjectURL(url), 0);
+ };
+ const ready = !(earlier && (versionQuery.isPending || failed));
+
+ return (
+ <div className="flex min-h-0 flex-1 flex-col gap-2">
+ <div className="flex shrink-0 flex-wrap items-center gap-1.5">
+ {canStep && (
+ <span role="group" aria-label="Versions" className="flex items-center font-mono text-xs text-fg-muted">
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ onClick={() => setShown((value) => Math.max(1, value - 1))}
+ disabled={shown <= 1}
+ aria-label="Previous version"
+ >
+ <ChevronLeft className="size-3.5" />
+ </Button>
+ <span className="tabular-nums">
+ v{shown}/{latest}
+ </span>
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ onClick={() => setShown((value) => Math.min(latest, value + 1))}
+ disabled={shown >= latest}
+ aria-label="Next version"
+ >
+ <ChevronRight className="size-3.5" />
+ </Button>
+ </span>
+ )}
+ <ToggleGroup
+ type="single"
+ variant="segmented"
+ size="sm"
+ value={view}
+ onValueChange={(value) => {
+ if (value === 'preview' || value === 'source') setView(value);
+ }}
+ aria-label="Show as"
+ className="ml-auto"
+ >
+ <ToggleGroupItem value="preview">Preview</ToggleGroupItem>
+ <ToggleGroupItem value="source">Markdown</ToggleGroupItem>
+ </ToggleGroup>
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ onClick={copy}
+ disabled={!ready}
+ aria-label={copied ? 'Copied' : 'Copy'}
+ title={copied ? 'Copied' : 'Copy'}
+ >
+ {copied ? <Check className="size-3.5 text-action-run-ink" /> : <Copy className="size-3.5" />}
+ </Button>
+ <Button variant="ghost" size="icon-sm" onClick={download} disabled={!ready} aria-label="Download" title={`Download as a .${code ? 'txt' : 'md'} file`}>
+ <Download className="size-3.5" />
+ </Button>
+ </div>
+ {failed ? (
+ <p className="m-0 text-xs text-fg-muted">Couldn’t load version {shown}.</p>
+ ) : !ready ? (
+ <p className="m-0 text-xs text-fg-muted">Loading version {shown}…</p>
+ ) : view === 'source' ? (
+ <pre className="m-0 min-h-0 flex-1 overflow-auto whitespace-pre-wrap rounded bg-bg-elevated p-3 font-mono text-xs text-fg-default">
+ {content}
+ </pre>
+ ) : (
+ <div className="prose prose-sm min-h-0 max-w-none flex-1 overflow-auto dark:prose-invert">
+ <ReactMarkdown remarkPlugins={[remarkGfm, remarkBreaks]}>{code ? fenced(content, code) : content}</ReactMarkdown>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/components/parameterPanel/canvas/__tests__/CanvasContent.test.tsx b/client/src/components/parameterPanel/canvas/__tests__/CanvasContent.test.tsx
index 7c8b658d..90d62593 100644
--- a/client/src/components/parameterPanel/canvas/__tests__/CanvasContent.test.tsx
+++ b/client/src/components/parameterPanel/canvas/__tests__/CanvasContent.test.tsx
@@ -165,3 +165,148 @@ describe('CanvasContent sandbox regression (security invariants)', () => {
expect(iframe.getAttribute('src')).toBeNull();
});
});
+
+describe('CanvasContent notes as documents', () => {
+ const doc = (id: string, content: string, extra: Partial<CanvasItem> = {}): CanvasItem => ({
+ ...note(id, content),
+ ...extra,
+ });
+
+ const versionReply = (content: string, version: number, latest: number) => ({
+ success: true,
+ item: { ...doc('a', content), version, latest },
+ });
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ wsMock.sendRequest.mockReset();
+ });
+
+ it('shows the preview, or the Markdown source', () => {
+ render(<CanvasContent items={[doc('a', '# Plan\n\nA **bold** step', { title: 'Plan' })]} workflowId="wf-1" />);
+ expect(screen.getByRole('heading', { name: 'Plan' })).toBeInTheDocument();
+ fireEvent.click(screen.getByRole('radio', { name: 'Markdown' }));
+ expect(screen.getByText(/A \*\*bold\*\* step/)).toBeInTheDocument();
+ });
+
+ it('previews a code note as a code block and downloads it as text', () => {
+ const createObjectURL = vi.fn(() => 'blob:code');
+ Object.assign(URL, { createObjectURL, revokeObjectURL: vi.fn() });
+ const click = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(function (this: HTMLAnchorElement) {
+ expect(this.download).toBe('script.txt');
+ });
+ const { container } = render(
+ <CanvasContent items={[doc('a', 'print("```")', { title: 'script', language: 'Python' })]} workflowId="wf-1" />,
+ );
+ expect(container.querySelector('pre code')?.textContent).toBe('print("```")\n');
+ fireEvent.click(screen.getByRole('button', { name: 'Download' }));
+ expect(click).toHaveBeenCalledTimes(1);
+ expect((createObjectURL.mock.calls[0] as unknown as [Blob])[0].type).toBe('text/plain;charset=utf-8');
+ click.mockRestore();
+ });
+
+ it('steps back to an earlier version read from its node', async () => {
+ wsMock.sendRequest.mockResolvedValue(versionReply('second draft', 2, 3));
+ render(<CanvasContent items={[doc('a', 'final', { version: 3 })]} workflowId="wf-1" nodeId="canvas-1" />);
+ expect(screen.getByText('v3/3')).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'Next version' })).toBeDisabled();
+
+ fireEvent.click(screen.getByRole('button', { name: 'Previous version' }));
+ expect(await screen.findByText('second draft')).toBeInTheDocument();
+ expect(screen.getByText('v2/3')).toBeInTheDocument();
+ expect(wsMock.sendRequest).toHaveBeenCalledWith('canvas_version', {
+ workflow_id: 'wf-1',
+ node_id: 'canvas-1',
+ item_id: 'a',
+ version: 2,
+ });
+ });
+
+ it('shows only the latest without a node to read versions from', () => {
+ render(<CanvasContent items={[doc('a', 'final', { version: 3 })]} workflowId="wf-1" />);
+ expect(screen.queryByRole('button', { name: 'Previous version' })).not.toBeInTheDocument();
+ expect(screen.getByText('final')).toBeInTheDocument();
+ });
+
+ it('follows a newer version unless the owner stepped back', async () => {
+ wsMock.sendRequest.mockResolvedValue(versionReply('one', 1, 2));
+ const { rerender } = render(
+ <CanvasContent items={[doc('a', 'one', { version: 1 })]} workflowId="wf-1" nodeId="canvas-1" />,
+ );
+ rerender(<CanvasContent items={[doc('a', 'two', { version: 2 })]} workflowId="wf-1" nodeId="canvas-1" />);
+ expect(screen.getByText('two')).toBeInTheDocument();
+
+ fireEvent.click(screen.getByRole('button', { name: 'Previous version' }));
+ expect(await screen.findByText('one')).toBeInTheDocument();
+ rerender(<CanvasContent items={[doc('a', 'three', { version: 3 })]} workflowId="wf-1" nodeId="canvas-1" />);
+ expect(screen.getByText('v1/3')).toBeInTheDocument();
+ expect(screen.queryByText('three')).not.toBeInTheDocument();
+ });
+
+ it('says so when a version cannot be read', async () => {
+ wsMock.sendRequest.mockResolvedValue({ success: false, error: 'No such version' });
+ render(<CanvasContent items={[doc('a', 'final', { version: 2 })]} workflowId="wf-1" nodeId="canvas-1" />);
+ fireEvent.click(screen.getByRole('button', { name: 'Previous version' }));
+ expect(await screen.findByText('Couldn’t load version 1.')).toBeInTheDocument();
+ expect(screen.getByRole('button', { name: 'Copy' })).toBeDisabled();
+ });
+
+ it('opens on the item and version a reply asks for, and holds it while others arrive', async () => {
+ wsMock.sendRequest.mockResolvedValue(versionReply('draft of a', 1, 2));
+ const items = [doc('a', 'a, final', { version: 2 }), doc('b', 'b')];
+ const focus = { itemId: 'a', version: 1, nonce: 1 };
+ const { rerender } = render(
+ <CanvasContent items={items} workflowId="wf-1" nodeId="canvas-1" focus={focus} />,
+ );
+ expect(await screen.findByText('draft of a')).toBeInTheDocument();
+ expect(screen.getByText('v1/2')).toBeInTheDocument();
+
+ rerender(<CanvasContent items={[...items, doc('c', 'c')]} workflowId="wf-1" nodeId="canvas-1" focus={focus} />);
+ expect(screen.getByText('draft of a')).toBeInTheDocument();
+ expect(screen.getByText('1/3')).toBeInTheDocument();
+
+ // Moving on lets go of it: back on the item, the latest shows.
+ fireEvent.click(screen.getByRole('button', { name: 'Next item' }));
+ fireEvent.click(screen.getByRole('button', { name: 'Previous item' }));
+ expect(screen.getByText('a, final')).toBeInTheDocument();
+ });
+
+ it('waits for the item a reply asks for to reach the board', () => {
+ const focus = { itemId: 'b', version: null, nonce: 1 };
+ const { rerender } = render(
+ <CanvasContent items={[doc('a', 'a')]} workflowId="wf-1" nodeId="canvas-1" focus={focus} />,
+ );
+ rerender(<CanvasContent items={[doc('a', 'a'), doc('b', 'b'), doc('c', 'c')]} workflowId="wf-1" nodeId="canvas-1" focus={focus} />);
+ expect(screen.getByText('b')).toBeInTheDocument();
+ expect(screen.getByText('2/3')).toBeInTheDocument();
+ });
+
+ it('copies the text and downloads it as a .md file', async () => {
+ const writeText = vi.fn().mockResolvedValue(undefined);
+ Object.defineProperty(navigator, 'clipboard', { value: { writeText }, configurable: true });
+ const createObjectURL = vi.fn(() => 'blob:doc');
+ const revokeObjectURL = vi.fn();
+ Object.assign(URL, { createObjectURL, revokeObjectURL });
+ const click = vi.spyOn(HTMLAnchorElement.prototype, 'click').mockImplementation(function (this: HTMLAnchorElement) {
+ expect(this.download).toBe('Weekly-report-v2.md');
+ expect(this.href).toBe('blob:doc');
+ });
+
+ render(
+ <CanvasContent
+ items={[doc('a', '# Weekly report', { title: 'Weekly report!', version: 2 })]}
+ workflowId="wf-1"
+ nodeId="canvas-1"
+ />,
+ );
+ fireEvent.click(screen.getByRole('button', { name: 'Copy' }));
+ expect(writeText).toHaveBeenCalledWith('# Weekly report');
+ expect(await screen.findByRole('button', { name: 'Copied' })).toBeInTheDocument();
+
+ fireEvent.click(screen.getByRole('button', { name: 'Download' }));
+ expect(click).toHaveBeenCalledTimes(1);
+ const blob = (createObjectURL.mock.calls[0] as unknown as [Blob])[0];
+ expect(blob.type).toBe('text/markdown;charset=utf-8');
+ click.mockRestore();
+ });
+});
diff --git a/client/src/components/ui/CanvasDock.tsx b/client/src/components/ui/CanvasDock.tsx
index 55d81206..b728cf84 100644
--- a/client/src/components/ui/CanvasDock.tsx
+++ b/client/src/components/ui/CanvasDock.tsx
@@ -67,6 +67,7 @@ const CanvasDock: React.FC<CanvasDockProps> = ({ nodes }) => {
const close = useCanvasDockStore((s) => s.close);
const selectNode = useCanvasDockStore((s) => s.selectNode);
const backToNode = useCanvasDockStore((s) => s.backToNode);
+ const focus = useCanvasDockStore((s) => s.focus);
const workflowId = useAppStore((s) => s.currentWorkflow?.id);
@@ -226,6 +227,8 @@ const CanvasDock: React.FC<CanvasDockProps> = ({ nodes }) => {
<CanvasContent
items={board.data?.items ?? []}
workflowId={workflowId}
+ nodeId={effectiveNodeId}
+ focus={focus?.nodeId === effectiveNodeId ? focus : null}
followLatestDefault={followMode}
onFollowLatestChange={setFollowMode}
onRemove={(itemId) =>
diff --git a/client/src/components/ui/ConsoleChat.tsx b/client/src/components/ui/ConsoleChat.tsx
index de7664b1..f812c441 100644
--- a/client/src/components/ui/ConsoleChat.tsx
+++ b/client/src/components/ui/ConsoleChat.tsx
@@ -5,6 +5,8 @@
* A message goes to the workflow's chat triggers; Clear clears the chat and
* what the workflow's agents remember of it.
*
+ * A document an agent wrote opens from its card in the Canvas dock.
+ *
* The console's font size applies to the conversation. The `chat` panel
* hook stays on ConsolePanel's root; the turns carry `chat-msg-user` /
* `chat-msg-bot` for the stylized themes.
@@ -16,6 +18,7 @@ import { ActionButton } from '@/components/ui/action-button';
import { Badge } from '@/components/ui/badge';
import { ChatPane, useChatThread, useClearChat, type ChatPaneHandle, type NotifyTone } from '@/features/chat';
import { useAppStore } from '../../store/useAppStore';
+import { useCanvasDockStore } from '../../stores/canvasDockStore';
const SEND_REFUSED: Record<string, { message: string; tone: NotifyTone }> = {
// Nothing listens while the workflow is stopped, so the server saved nothing.
@@ -74,6 +77,11 @@ export function ConsoleChat({ fontSize, ref }: { fontSize: number; ref?: Ref<Cha
<p className="m-0 py-6 text-center text-xs text-muted-foreground">Send a message to trigger chatTrigger nodes</p>
),
notify,
+ // A document the workflow's agent wrote opens in the Canvas dock.
+ openArtifact: (artifact) => {
+ if (artifact.workflowId !== useAppStore.getState().currentWorkflow?.id) return;
+ useCanvasDockStore.getState().focusItem(artifact.canvasNodeId, artifact.itemId, artifact.version);
+ },
onSendRefused: (code) => {
const refused = SEND_REFUSED[code] ?? { message: 'Your message didn’t send. Try again.', tone: 'error' as const };
notify(refused.message, refused.tone);
diff --git a/client/src/features/chat/ChatPane.tsx b/client/src/features/chat/ChatPane.tsx
index 86b30e4d..69ebaa1e 100644
--- a/client/src/features/chat/ChatPane.tsx
+++ b/client/src/features/chat/ChatPane.tsx
@@ -231,6 +231,7 @@ export function ChatPane({ host, ref }: { host: ChatHost; ref?: Ref<ChatPaneHand
uiActions={uiActions}
onUiStateChange={uiState.change}
onFollowUp={composer === 'send' ? followUp : undefined}
+ onOpenArtifact={host.openArtifact}
onScrolledChange={host.onScrolledChange}
/>
<div className={cn('relative flex-none', compact ? 'border-t border-border-default px-3 py-2' : 'px-6 pb-3')}>
diff --git a/client/src/features/chat/__tests__/artifacts.test.tsx b/client/src/features/chat/__tests__/artifacts.test.tsx
new file mode 100644
index 00000000..3bf09556
--- /dev/null
+++ b/client/src/features/chat/__tests__/artifacts.test.tsx
@@ -0,0 +1,185 @@
+/**
+ * A document the employee writes on its Canvas, in the reply that wrote it:
+ * the card arrives with the run, names the latest version the reply or the
+ * run knows, and Open hands the host the document to show.
+ */
+
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { act, fireEvent, render, screen } from '@testing-library/react';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+
+const sendRequest = vi.fn();
+
+vi.mock('@/contexts/WebSocketContext', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@/contexts/WebSocketContext')>()),
+ useWebSocketActions: () => ({ sendRequest, isReady: true, addEventListener: () => () => {} }),
+}));
+vi.mock('@/lib/motion', async (importOriginal) => ({
+ ...(await importOriginal<typeof import('@/lib/motion')>()),
+ motionSuppressed: () => true,
+}));
+
+import { resetChatRunStore, useChatRunStore } from '@/stores/chatRunStore';
+import { ChatPane } from '../ChatPane';
+import { liveArtifacts, mergeArtifacts, savedArtifacts, type ArtifactRef } from '../data/parts';
+import type { ChatHost } from '../host';
+import { ArtifactCard } from '../turns/ArtifactCard';
+import { useComposerStore } from '../state/composerStore';
+import '../markdown/ReplyMarkdown';
+
+type Wire = Record<string, unknown>;
+
+const wire = (version: number, itemId = 'item_1', title = 'Weekly report'): Wire => ({
+ workflow_id: 'w1',
+ canvas_node_id: 'w1:canvas:1',
+ item_id: itemId,
+ version,
+ title,
+ format: 'markdown',
+});
+
+const ref = (version: number, itemId = 'item_1', title = 'Weekly report'): ArtifactRef => ({
+ workflowId: 'w1',
+ canvasNodeId: 'w1:canvas:1',
+ itemId,
+ version,
+ title,
+ format: 'markdown',
+});
+
+describe('reading documents off a reply', () => {
+ it('keeps each document once and drops what does not name one', () => {
+ const parts = {
+ artifacts: [wire(1), wire(2), { item_id: 'x' }, { ...wire(1, 'item_2', ' '), format: 'code', version: 0 }, 'nope'],
+ };
+ expect(savedArtifacts(parts)).toEqual([ref(1), { ...ref(1, 'item_2', 'Document'), format: 'code' }]);
+ expect(savedArtifacts(null)).toEqual([]);
+ expect(savedArtifacts({ artifacts: 'nope' })).toEqual([]);
+ });
+
+ it('reads the run’s artifact activities only', () => {
+ expect(
+ liveArtifacts([
+ { messageId: 'artifact_item_1', activityType: 'artifact', content: wire(2), patches: 0 },
+ { messageId: 'ui_1', activityType: 'json_render', content: {}, patches: 3 },
+ ]),
+ ).toEqual([ref(2)]);
+ });
+
+ it('shows each saved document at its newest version, then the run’s new ones', () => {
+ expect(mergeArtifacts([ref(1), ref(3, 'item_2')], [ref(2), ref(1, 'item_2'), ref(1, 'item_3')])).toEqual([
+ ref(2),
+ ref(3, 'item_2'),
+ ref(1, 'item_3'),
+ ]);
+ });
+});
+
+describe('the document card', () => {
+ it('opens the document at its version', () => {
+ const onOpen = vi.fn();
+ render(<ArtifactCard artifact={ref(2)} onOpen={onOpen} />);
+ expect(screen.getByText('Document · version 2')).toBeInTheDocument();
+ fireEvent.click(screen.getByRole('button', { name: 'Open Weekly report' }));
+ expect(onOpen).toHaveBeenCalledWith(ref(2));
+ });
+
+ it('cannot open without a host that shows documents', () => {
+ render(<ArtifactCard artifact={{ ...ref(1), format: 'code' }} />);
+ expect(screen.getByRole('button', { name: 'Open Weekly report' })).toBeDisabled();
+ expect(screen.getByText('Code')).toBeInTheDocument();
+ });
+});
+
+describe('a document in a streaming reply', () => {
+ let server: { messages: Wire[]; activeRuns: Wire[] };
+ let client: QueryClient;
+
+ const row = (id: string, role: 'user' | 'assistant', text: string, patch: Wire = {}): Wire => ({
+ id,
+ role,
+ text,
+ message: text,
+ timestamp: '2026-10-04T09:00:00Z',
+ run_key: 'g1',
+ ...patch,
+ });
+
+ const frame = (seq: number, suffix: string, data: Wire = {}) => ({
+ specversion: '1.0',
+ id: `r1:${seq}`,
+ source: 'opencompany://services/chat',
+ type: `com.opencompany.chat.run.${suffix}`,
+ subject: 'r1',
+ data: { workflow_id: 'w1', session_id: 'w1', run_id: 'r1', seq, hub_epoch: 'e1', ...data },
+ });
+
+ const runEvents = (...frames: unknown[]) =>
+ act(() => {
+ const store = useChatRunStore.getState();
+ for (const item of frames) store.receive(item);
+ store.flush();
+ });
+
+ beforeEach(() => {
+ resetChatRunStore();
+ useComposerStore.setState({ drafts: {} });
+ server = {
+ messages: [row('m1', 'user', 'Write up the week', { run_id: 'r1' })],
+ activeRuns: [{ run_id: 'r1', session_id: 'w1', state: 'running', seq: 1, hub_epoch: 'e1' }],
+ };
+ sendRequest.mockReset().mockImplementation(async (kind: string, data: Wire) => {
+ switch (kind) {
+ case 'chat_subscribe':
+ return { success: true, session_id: data.session_id, hub_epoch: 'e1', active_runs: server.activeRuns };
+ case 'get_chat_messages':
+ return { success: true, messages: server.messages, thread: { active_leaf_id: null, revision: 1 }, active_runs: server.activeRuns };
+ default:
+ return { success: true };
+ }
+ });
+ });
+
+ it('arrives with the run, takes its newer version and opens through the host', async () => {
+ const openArtifact = vi.fn();
+ const host: ChatHost = {
+ kind: 'home',
+ sessionId: 'w1',
+ scope: 'all',
+ persona: { name: 'Maya', colorRole: 'agent' },
+ composer: 'send',
+ notify: vi.fn(),
+ openArtifact,
+ };
+ client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ render(
+ <QueryClientProvider client={client}>
+ <ChatPane host={host} />
+ </QueryClientProvider>,
+ );
+ await screen.findByText('Write up the week');
+
+ runEvents(
+ frame(1, 'started', { kind: 'message', user_message_id: 'm1', reply_message_id: 'a_r1', started_at: '2026-10-04T09:00:01Z' }),
+ frame(2, 'activity.snapshot', { message_id: 'artifact_item_1', activity_type: 'artifact', content: wire(1), replace: true }),
+ );
+ expect(await screen.findByRole('button', { name: 'Open Weekly report' })).toBeInTheDocument();
+ expect(screen.getByText('Document')).toBeInTheDocument();
+
+ runEvents(frame(3, 'activity.snapshot', { message_id: 'artifact_item_1', activity_type: 'artifact', content: wire(2), replace: true }));
+ expect(screen.getByText('Document · version 2')).toBeInTheDocument();
+ fireEvent.click(screen.getByRole('button', { name: 'Open Weekly report' }));
+ expect(openArtifact).toHaveBeenCalledWith(ref(2));
+
+ // The saved reply keeps the card.
+ server.activeRuns = [];
+ server.messages = [...server.messages, row('a_r1', 'assistant', 'The report is on your Canvas.', { run_id: 'r1', parts: { artifacts: [wire(2)] } })];
+ runEvents(frame(4, 'finished', { outcome: { type: 'success' }, result: { reply_message_id: 'a_r1' } }));
+ await act(async () => {
+ await client.invalidateQueries({ queryKey: ['chatThread'] });
+ });
+ await screen.findByText('The report is on your Canvas.');
+ expect(screen.getAllByRole('button', { name: 'Open Weekly report' })).toHaveLength(1);
+ expect(screen.getByText('Document · version 2')).toBeInTheDocument();
+ });
+});
diff --git a/client/src/features/chat/data/parts.ts b/client/src/features/chat/data/parts.ts
index 15310002..274fb6de 100644
--- a/client/src/features/chat/data/parts.ts
+++ b/client/src/features/chat/data/parts.ts
@@ -95,3 +95,59 @@ export function liveApprovalIds(activities: readonly RunActivity[] | undefined):
const ids = (activities ?? []).flatMap((activity) => (activity.activityType === 'approval' ? [activity.messageId] : []));
return [...new Set(ids)];
}
+
+/** A document the employee wrote on its Canvas, named on its reply: the card
+ * opens the board on it, at this version. */
+export interface ArtifactRef {
+ workflowId: string;
+ canvasNodeId: string;
+ itemId: string;
+ version: number;
+ title: string;
+ format: 'markdown' | 'code';
+}
+
+function readArtifact(item: unknown): ArtifactRef | null {
+ if (!isRecord(item)) return null;
+ const { workflow_id: workflowId, canvas_node_id: canvasNodeId, item_id: itemId } = item;
+ if (typeof workflowId !== 'string' || !workflowId || typeof canvasNodeId !== 'string' || !canvasNodeId) return null;
+ if (typeof itemId !== 'string' || !itemId) return null;
+ const version = typeof item.version === 'number' && Number.isInteger(item.version) && item.version > 0 ? item.version : 1;
+ const title = typeof item.title === 'string' && item.title.trim() ? item.title.trim() : 'Document';
+ return { workflowId, canvasNodeId, itemId, version, title, format: item.format === 'code' ? 'code' : 'markdown' };
+}
+
+/** The documents a saved reply names (`parts.artifacts`), once each. */
+export function savedArtifacts(parts: Record<string, unknown> | null | undefined): ArtifactRef[] {
+ const raw = parts?.artifacts;
+ if (!Array.isArray(raw)) return [];
+ const seen = new Set<string>();
+ return raw.flatMap((item) => {
+ const artifact = readArtifact(item);
+ if (!artifact || seen.has(artifact.itemId)) return [];
+ seen.add(artifact.itemId);
+ return [artifact];
+ });
+}
+
+/** The documents a run wrote so far (its `artifact` activities). */
+export function liveArtifacts(activities: readonly RunActivity[] | undefined): ArtifactRef[] {
+ return (activities ?? []).flatMap((activity) => {
+ if (activity.activityType !== 'artifact') return [];
+ const artifact = readArtifact(activity.content);
+ return artifact ? [artifact] : [];
+ });
+}
+
+/** A reply's documents: the saved ones in their order, each at the newer of
+ * its saved and live versions (a run can revise a document after its reply
+ * was saved), then the ones only the run has shown so far. */
+export function mergeArtifacts(saved: readonly ArtifactRef[], live: readonly ArtifactRef[]): ArtifactRef[] {
+ const newer = new Map(live.map((artifact) => [artifact.itemId, artifact]));
+ const merged = saved.map((artifact) => {
+ const shown = newer.get(artifact.itemId);
+ newer.delete(artifact.itemId);
+ return shown && shown.version > artifact.version ? shown : artifact;
+ });
+ return [...merged, ...newer.values()];
+}
diff --git a/client/src/features/chat/host.ts b/client/src/features/chat/host.ts
index 121cc213..6fb3efb8 100644
--- a/client/src/features/chat/host.ts
+++ b/client/src/features/chat/host.ts
@@ -7,6 +7,7 @@
import type { ReactNode } from 'react';
import type { ColorRole } from '@/components/catalog/presentation';
+import type { ArtifactRef } from './data/parts';
import type { ThreadScope } from './data/thread';
export type ChatHostKind = 'home' | 'dev';
@@ -61,6 +62,10 @@ export interface ChatHost {
onScrolledChange?: (scrolled: boolean) => void;
/** The console pane: denser type and spacing. */
compact?: boolean;
+ /** Show a document the employee wrote on its Canvas (Home: the Workspace's
+ * Canvas tab; Dev: the Canvas dock). Without it the reply's card cannot
+ * open it. */
+ openArtifact?: (artifact: ArtifactRef) => void;
}
/** What a host can ask of a mounted chat. */
diff --git a/client/src/features/chat/thread/ChatThread.tsx b/client/src/features/chat/thread/ChatThread.tsx
index 54f3c666..6f446d18 100644
--- a/client/src/features/chat/thread/ChatThread.tsx
+++ b/client/src/features/chat/thread/ChatThread.tsx
@@ -25,6 +25,7 @@ import type { ChatPersona } from '../host';
import { AssistantTurn } from '../turns/AssistantTurn';
import { UserTurn } from '../turns/UserTurn';
import type { ChatTurn } from './model';
+import type { ArtifactRef } from '../data/parts';
/** Closer to the bottom than this counts as at the bottom. */
const STICK_PX = 48;
@@ -59,6 +60,8 @@ export interface ChatThreadProps {
onUiStateChange?: (partId: string, changes: UiStateChange[]) => void;
/** Sends a suggested next question as the owner's message. */
onFollowUp?: (text: string) => void;
+ /** Shows a document a reply wrote, in the host's Canvas. */
+ onOpenArtifact?: (artifact: ArtifactRef) => void;
onScrolledChange?: (scrolled: boolean) => void;
}
@@ -77,6 +80,7 @@ export function ChatThread({
uiActions,
onUiStateChange,
onFollowUp,
+ onOpenArtifact,
onScrolledChange,
}: ChatThreadProps) {
const scrollRef = useRef<HTMLDivElement>(null);
@@ -217,6 +221,7 @@ export function ChatThread({
uiActions={uiActions}
onUiStateChange={onUiStateChange}
onFollowUp={onFollowUp}
+ onOpenArtifact={onOpenArtifact}
/>
)}
</div>
diff --git a/client/src/features/chat/turns/ArtifactCard.tsx b/client/src/features/chat/turns/ArtifactCard.tsx
new file mode 100644
index 00000000..215e3969
--- /dev/null
+++ b/client/src/features/chat/turns/ArtifactCard.tsx
@@ -0,0 +1,39 @@
+/**
+ * A document the employee wrote on its Canvas, in the reply that wrote it
+ * (design handoff chat, "artifact card"): its title, what it is and which
+ * version, and Open, which shows it in the host's Canvas (Home's Workspace,
+ * the editor's Canvas dock) at that version.
+ */
+
+import { FileText } from 'lucide-react';
+import { cn } from '@/lib/utils';
+import type { ArtifactRef } from '../data/parts';
+
+export function ArtifactCard({ artifact, onOpen }: { artifact: ArtifactRef; onOpen?: (artifact: ArtifactRef) => void }) {
+ const kind = artifact.format === 'code' ? 'Code' : 'Document';
+ const meta = artifact.version > 1 ? `${kind} · version ${artifact.version}` : kind;
+ return (
+ <button
+ type="button"
+ data-artifact={artifact.itemId}
+ disabled={!onOpen}
+ onClick={() => onOpen?.(artifact)}
+ aria-label={`Open ${artifact.title}`}
+ className={cn(
+ 'flex w-full max-w-105 items-center gap-3 rounded-card border border-border-default bg-bg-panel px-3.5 py-3 text-left text-fg-default transition-[border-color,transform,box-shadow] duration-(--dur-default)',
+ onOpen && 'hover:-translate-y-px hover:border-border-strong hover:shadow-card-hover motion-reduce:hover:translate-y-0',
+ )}
+ >
+ <span aria-hidden className="grid size-9.5 flex-none place-items-center rounded-lg border border-node-agent-border bg-action-tools-soft text-action-tools-ink">
+ <FileText className="size-4.25" strokeWidth={1.8} />
+ </span>
+ <span className="flex min-w-0 flex-1 flex-col gap-px">
+ <span className="truncate text-sm font-semibold">{artifact.title}</span>
+ <span className="text-xs text-fg-muted">{meta}</span>
+ </span>
+ {onOpen && <span className="text-xs font-medium text-fg-muted">Open</span>}
+ </button>
+ );
+}
+
+export default ArtifactCard;
diff --git a/client/src/features/chat/turns/AssistantTurn.tsx b/client/src/features/chat/turns/AssistantTurn.tsx
index 826cb596..e3946363 100644
--- a/client/src/features/chat/turns/AssistantTurn.tsx
+++ b/client/src/features/chat/turns/AssistantTurn.tsx
@@ -22,7 +22,19 @@ import { isLiveRun, type RunSnapshot } from '@/lib/agui/reduceRun';
import type { UiStateChange } from '@/lib/jsonRender/uiState';
import { cn } from '@/lib/utils';
import { ApprovalCard } from '../approval/ApprovalCard';
-import { liveApprovalIds, savedApprovalIds, savedFollowups, savedSources, savedUiParts, type SourceItem, type UiPart } from '../data/parts';
+import {
+ liveApprovalIds,
+ liveArtifacts,
+ mergeArtifacts,
+ savedApprovalIds,
+ savedArtifacts,
+ savedFollowups,
+ savedSources,
+ savedUiParts,
+ type ArtifactRef,
+ type SourceItem,
+ type UiPart,
+} from '../data/parts';
import type { ChatMessage } from '../data/schemas';
import type { ChatUiActions } from '../genui/actions';
import type { ChatPersona } from '../host';
@@ -31,6 +43,7 @@ import { citationOrder } from '../markdown/citations';
import { ChatAvatar } from '../thread/ChatAvatar';
import type { TurnWork } from '../thread/model';
import { timeLabel } from '../thread/timeLabel';
+import { ArtifactCard } from './ArtifactCard';
import { GeneratedUiBlock } from './GeneratedUiBlock';
import { FollowUps } from './FollowUps';
import { failureLines, liveLabel, liveText } from './runCopy';
@@ -80,6 +93,7 @@ export function AssistantTurn({
uiActions,
onUiStateChange,
onFollowUp,
+ onOpenArtifact,
}: {
message: ChatMessage | null;
run: RunSnapshot | null;
@@ -102,6 +116,8 @@ export function AssistantTurn({
onUiStateChange?: (partId: string, changes: UiStateChange[]) => void;
/** Sends a suggested next question; absent where they cannot go. */
onFollowUp?: (text: string) => void;
+ /** Shows a document the reply wrote, in the host's Canvas. */
+ onOpenArtifact?: (artifact: ArtifactRef) => void;
}) {
const queued = run?.state === 'queued';
const live = Boolean(run && isLiveRun(run) && !queued);
@@ -114,6 +130,11 @@ export function AssistantTurn({
const failure = run?.state === 'error' ? failureLines(run.error, persona.name) : null;
const saved = message ? savedUiParts(message.parts) : NO_UI;
const interfaces = saved.length > 0 ? saved : liveUi;
+ // The documents it wrote, at the latest version the reply or the run names.
+ const artifacts = useMemo(
+ () => mergeArtifacts(savedArtifacts(message?.parts), liveArtifacts(run?.activities)),
+ [message?.parts, run?.activities],
+ );
// The drafts it made: named on the saved reply, or arriving with the run.
const approvals = useMemo(
() => [...new Set([...savedApprovalIds(message?.parts), ...liveApprovalIds(run?.activities)])],
@@ -166,6 +187,9 @@ export function AssistantTurn({
onStateChange={onUiStateChange}
/>
))}
+ {artifacts.map((artifact) => (
+ <ArtifactCard key={artifact.itemId} artifact={artifact} onOpen={onOpenArtifact} />
+ ))}
{approvals.map((id) => (
<ApprovalCard key={id} approvalId={id} />
))}
diff --git a/client/src/features/home/__tests__/workspace.test.tsx b/client/src/features/home/__tests__/workspace.test.tsx
index 465d7213..74d7a764 100644
--- a/client/src/features/home/__tests__/workspace.test.tsx
+++ b/client/src/features/home/__tests__/workspace.test.tsx
@@ -229,6 +229,37 @@ describe('WorkspaceDock', () => {
renderWith([]);
expect(screen.getByText('No one on your team yet')).toBeInTheDocument();
});
+
+ it('opens on the document a reply names, on its employee’s Canvas tab', async () => {
+ const note = (id: string, content: string, version = 1) => ({
+ id,
+ kind: 'note',
+ title: null,
+ ref: null,
+ url: null,
+ content,
+ language: null,
+ source: 'agent',
+ created_at: null,
+ version,
+ });
+ actions.sendRequest.mockImplementation(async (type: string) =>
+ type === 'canvas_list'
+ ? { success: true, items: [note('n1', 'The plan', 2), note('n2', 'Later notes')], revision: 3 }
+ : { success: true },
+ );
+ useHomeStore.setState({ workspaceTab: 'browser' });
+ orbState.spike = 0;
+ renderWith([employee(), employee({ workflow_id: 'w2', name: 'Ravi' })]);
+ act(() => useHomeStore.getState().openCanvasItem({ workflowId: 'w2', canvasNodeId: 'w2:canvas:1', itemId: 'n1', version: 2 }));
+
+ expect(useHomeStore.getState()).toMatchObject({ workspaceOpen: true, workspaceFor: 'w2', workspaceTab: 'board' });
+ expect(orbState.spike).toBe(SPIKE.workspace);
+ expect(loadWorkspacePrefs()).toMatchObject({ open: true, tab: 'board' });
+ expect(await screen.findByText('The plan')).toBeInTheDocument();
+ expect(screen.getByText('1/2')).toBeInTheDocument();
+ expect(actions.sendRequest).toHaveBeenCalledWith('canvas_list', { workflow_id: 'w2', node_id: 'w2:canvas:1' });
+ });
});
describe('WorkspaceButton', () => {
diff --git a/client/src/features/home/employee/EmployeeChat.tsx b/client/src/features/home/employee/EmployeeChat.tsx
index ba4cdd44..7ebb1a88 100644
--- a/client/src/features/home/employee/EmployeeChat.tsx
+++ b/client/src/features/home/employee/EmployeeChat.tsx
@@ -15,6 +15,8 @@
* why a run of failures paused them.
* - Without a talk line, Turn on Talk offers to add one; an employee whose
* setup cannot answer gets a note instead of the box.
+ * - A document they wrote opens from its card in the reply on the
+ * Workspace's Canvas tab, at that version.
*/
import { Monitor } from 'lucide-react';
@@ -142,6 +144,7 @@ export function EmployeeChat({
? `${name} asks before sending anything on your behalf.`
: `${name} doesn’t ask before sending anything on your behalf.`,
notify: (message, tone) => pillToast(message, { tone }),
+ openArtifact: (artifact) => useHomeStore.getState().openCanvasItem(artifact),
onSendRefused,
liveNote,
onScrolledChange,
diff --git a/client/src/features/home/state/homeStore.ts b/client/src/features/home/state/homeStore.ts
index 9badc8f7..733b5e58 100644
--- a/client/src/features/home/state/homeStore.ts
+++ b/client/src/features/home/state/homeStore.ts
@@ -8,6 +8,7 @@
import { z } from 'zod';
import { create } from 'zustand';
+import type { CanvasFocus } from '@/lib/canvasBoard';
import { useShellDialogsStore } from '@/stores/shellDialogsStore';
import { SPIKE, spikeOrb } from '../orb/orb';
@@ -55,6 +56,12 @@ function saveWorkspacePrefs(state: HomeState): void {
}
}
+/** A Canvas item the Workspace was asked to show (homeStore.openCanvasItem). */
+export interface WorkspaceFocus extends CanvasFocus {
+ workflowId: string;
+ canvasNodeId: string;
+}
+
/** What a hire could not set up as asked (a tool left out while they ask
* first, a skill an employee cannot be given), shown on the new
* employee's page until the owner dismisses it or moves on. */
@@ -96,6 +103,9 @@ interface HomeState {
workspaceWide: boolean;
/** Whose workspace it shows: the employee last opened or watched. */
workspaceFor: string | null;
+ /** A Canvas item to show (a reply's document card); the nonce lets the
+ * same one be asked for again. */
+ workspaceFocus: WorkspaceFocus | null;
showHire: (options?: { focus?: boolean }) => void;
showEmployee: (workflowId: string) => void;
@@ -116,6 +126,9 @@ interface HomeState {
/** Clamped to 360px .. the window less 420px; ends Expand. */
setWorkspaceWidth: (px: number) => void;
toggleWorkspaceWide: () => void;
+ /** Open the Workspace on the Canvas tab, at an item and version of an
+ * employee's board. */
+ openCanvasItem: (target: { workflowId: string; canvasNodeId: string; itemId: string; version?: number | null }) => void;
}
const workspace = loadWorkspacePrefs();
@@ -135,6 +148,7 @@ export const useHomeStore = create<HomeState>((set, get) => ({
workspaceTab: workspace.tab,
workspaceWide: false,
workspaceFor: null,
+ workspaceFocus: null,
showHire: (options) =>
set((state) => ({
@@ -192,4 +206,14 @@ export const useHomeStore = create<HomeState>((set, get) => ({
saveWorkspacePrefs(get());
},
toggleWorkspaceWide: () => set((state) => ({ workspaceWide: !state.workspaceWide })),
+ openCanvasItem: ({ workflowId, canvasNodeId, itemId, version }) => {
+ if (!get().workspaceOpen) spikeOrb(SPIKE.workspace);
+ set((state) => ({
+ workspaceOpen: true,
+ workspaceFor: workflowId,
+ workspaceTab: 'board',
+ workspaceFocus: { workflowId, canvasNodeId, itemId, version: version ?? null, nonce: (state.workspaceFocus?.nonce ?? 0) + 1 },
+ }));
+ saveWorkspacePrefs(get());
+ },
}));
diff --git a/client/src/features/home/workspace/WorkspaceCanvas.tsx b/client/src/features/home/workspace/WorkspaceCanvas.tsx
index d7d0a9a6..62103c29 100644
--- a/client/src/features/home/workspace/WorkspaceCanvas.tsx
+++ b/client/src/features/home/workspace/WorkspaceCanvas.tsx
@@ -2,18 +2,23 @@
* The Workspace's Canvas tab: one employee's Canvas board, through the
* renderer the editor's Canvas panel and dock use (CanvasPanel.tsx is the
* template). The board refreshes on the `canvas_updated` broadcast, like
- * everywhere else it shows. Loaded lazily by WorkspaceDock.
+ * everywhere else it shows, and shows the item a reply's document card
+ * asked for (homeStore.openCanvasItem). Loaded lazily by WorkspaceDock.
*/
import { Button } from '@/components/ui/button';
import { Skeleton } from '@/components/ui/skeleton';
import CanvasContent from '@/components/parameterPanel/canvas/CanvasContent';
import { useCanvasBoardQuery, useCanvasRemove } from '@/hooks/useCanvasBoard';
+import { useHomeStore } from '../state/homeStore';
import { pillToast } from '../ui/pillToast';
export default function WorkspaceCanvas({ workflowId, nodeId, name }: { workflowId: string; nodeId: string; name: string }) {
const board = useCanvasBoardQuery(workflowId, nodeId);
const remove = useCanvasRemove(workflowId, nodeId);
+ // A reply's document card asked for an item on this board.
+ const focus = useHomeStore((s) => s.workspaceFocus);
+ const ownFocus = focus && focus.workflowId === workflowId && focus.canvasNodeId === nodeId ? focus : null;
if (board.isPending) return <Skeleton className="flex-1 rounded-card" />;
if (board.isError) {
@@ -30,6 +35,8 @@ export default function WorkspaceCanvas({ workflowId, nodeId, name }: { workflow
<CanvasContent
items={board.data.items}
workflowId={workflowId}
+ nodeId={nodeId}
+ focus={ownFocus}
emptyHint={`Nothing here yet. When ${name} finishes something you’ll want to see, it shows up here.`}
onRemove={(itemId) => remove.mutate(itemId, { onError: () => pillToast('Couldn’t remove that. Try again.', { tone: 'error' }) })}
/>
diff --git a/client/src/lib/canvasBoard.ts b/client/src/lib/canvasBoard.ts
index 52d90716..0258a4a5 100644
--- a/client/src/lib/canvasBoard.ts
+++ b/client/src/lib/canvasBoard.ts
@@ -26,6 +26,29 @@ export interface CanvasItem {
language: string | null;
source: 'agent' | 'workflow' | string;
created_at: string | null;
+ /** Its version: the agent's canvas tool revises an item in place, and the
+ * board keeps the earlier ones (`canvas_versions` / `canvas_version`). */
+ version?: number;
+ updated_at?: string | null;
+}
+
+/** A request to show one item, at a version (a chat reply's artifact
+ * card). A new nonce asks again for the same item. */
+export interface CanvasFocus {
+ itemId: string;
+ version?: number | null;
+ nonce: number;
+}
+
+/** One saved version, as `canvas_version` returns it: the item as it was
+ * then, and which version is the latest. */
+export type CanvasItemVersion = Omit<CanvasItem, 'version' | 'updated_at'> & { version: number; latest: number };
+
+/** Response to `canvas_version`. */
+export interface CanvasVersionResponse {
+ success: boolean;
+ error?: string;
+ item?: CanvasItemVersion;
}
/** Response to `canvas_list`. */
diff --git a/client/src/stores/__tests__/canvasDockStore.test.ts b/client/src/stores/__tests__/canvasDockStore.test.ts
index 22a4b392..6f2f91a6 100644
--- a/client/src/stores/__tests__/canvasDockStore.test.ts
+++ b/client/src/stores/__tests__/canvasDockStore.test.ts
@@ -74,6 +74,18 @@ describe('canvasDockStore.notifyPushed', () => {
expect(state.open).toBe(true);
expect(state.tab).toBe('browser');
});
+
+ it('opens on a document a chat reply names, leaving a preview, and asks again with a new nonce', () => {
+ useCanvasDockStore.setState({ tab: 'browser' });
+ useCanvasDockStore.getState().showEphemeral(ephemeral);
+ useCanvasDockStore.getState().focusItem('canvas-2', 'item-1', 3);
+ const state = useCanvasDockStore.getState();
+ expect(state).toMatchObject({ open: true, tab: 'board', mode: 'node', selectedNodeId: 'canvas-2', ephemeralItem: null });
+ expect(state.focus).toEqual({ nodeId: 'canvas-2', itemId: 'item-1', version: 3, nonce: 1 });
+
+ useCanvasDockStore.getState().focusItem('canvas-2', 'item-1');
+ expect(useCanvasDockStore.getState().focus).toEqual({ nodeId: 'canvas-2', itemId: 'item-1', version: null, nonce: 2 });
+ });
});
describe('canvasDockStore prefs', () => {
diff --git a/client/src/stores/canvasDockStore.ts b/client/src/stores/canvasDockStore.ts
index 683a9878..7d273af7 100644
--- a/client/src/stores/canvasDockStore.ts
+++ b/client/src/stores/canvasDockStore.ts
@@ -15,7 +15,7 @@
import { z } from 'zod';
import { create } from 'zustand';
-import type { CanvasItem } from '../lib/canvasBoard';
+import type { CanvasFocus, CanvasItem } from '../lib/canvasBoard';
import type { WorkspaceTab } from '../components/workspace/WorkspaceTabs';
const dockPrefsSchema = z.object({
@@ -62,6 +62,8 @@ interface CanvasDockState {
mode: 'node' | 'ephemeral';
selectedNodeId: string | null;
ephemeralItem: CanvasItem | null;
+ /** An item to show on a node's board (a chat reply's document card). */
+ focus: (CanvasFocus & { nodeId: string }) | null;
toggle: () => void;
close: () => void;
@@ -83,6 +85,9 @@ interface CanvasDockState {
notifyPushed: (nodeId: string) => void;
/** An agent in the CURRENT workflow asked for help in its browser (caller verifies): show the Browser tab. */
showBrowser: () => void;
+ /** Open the dock on a Canvas node's board at an item and version (a
+ * document a chat reply names, in the CURRENT workflow; caller verifies). */
+ focusItem: (nodeId: string, itemId: string, version?: number | null) => void;
}
const persisted = loadDockPrefs();
@@ -109,6 +114,7 @@ export const useCanvasDockStore = create<CanvasDockState>((set, get) => ({
mode: 'node',
selectedNodeId: null,
ephemeralItem: null,
+ focus: null,
toggle: () => {
set((state) => ({ open: !state.open }));
@@ -156,4 +162,15 @@ export const useCanvasDockStore = create<CanvasDockState>((set, get) => ({
set({ open: true, tab: 'browser' });
persist(get());
},
+ focusItem: (nodeId, itemId, version) => {
+ set((state) => ({
+ open: true,
+ tab: 'board',
+ mode: 'node',
+ selectedNodeId: nodeId,
+ ephemeralItem: null,
+ focus: { nodeId, itemId, version: version ?? null, nonce: (state.focus?.nonce ?? 0) + 1 },
+ }));
+ persist(get());
+ },
}));