import { createContext, useCallback, useContext, useState, type ReactNode, } from "react"; import type { CanvasArtifact } from "../types/artifact"; import type { CanvasMessage } from "../types/thread"; import type { StreamingArtifactPartial } from "../api/runs"; export interface CanvasGraphContextValue { messages: CanvasMessage[]; artifact: CanvasArtifact | null; streamingArtifact: StreamingArtifactPartial | null; isStreaming: boolean; setMessages: (messages: CanvasMessage[]) => void; /** Upsert a message by id — concatenates string content for streaming deltas. */ appendMessage: (msg: CanvasMessage) => void; setArtifact: (artifact: CanvasArtifact | null) => void; setStreamingArtifact: (partial: StreamingArtifactPartial | null) => void; setIsStreaming: (v: boolean) => void; } const CanvasGraphContext = createContext(null); export function CanvasGraphProvider({ children }: { children: ReactNode }) { const [messages, setMessages] = useState([]); const [artifact, setArtifact] = useState(null); const [streamingArtifact, setStreamingArtifact] = useState(null); const [isStreaming, setIsStreaming] = useState(false); const appendMessage = useCallback((msg: CanvasMessage) => { setMessages((prev) => { if (!msg.id) return [...prev, msg]; const idx = prev.findIndex((m) => m.id === msg.id); if (idx >= 0) { const existing = prev[idx]!; const existingText = typeof existing.content === "string" ? existing.content : ""; const deltaText = typeof msg.content === "string" ? msg.content : ""; const next = [...prev]; next[idx] = { ...existing, content: existingText + deltaText }; return next; } return [...prev, msg]; }); }, []); return ( {children} ); } export function useCanvasGraphContext() { const ctx = useContext(CanvasGraphContext); if (!ctx) throw new Error( "useCanvasGraphContext must be used within CanvasGraphProvider", ); return ctx; }