Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions examples/miscellaneous/assistant-ui-dashboards/next.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import type { NextConfig } from "next";

const config: NextConfig = {
turbopack: { root: process.cwd() },
// The badge would sit over the sidebar's list.
devIndicators: { position: "bottom-right" },
// With THESYS_BASE_URL set, such as a local stack, the browser reaches it through this app's
// origin, so it needs no CORS setup. The page tells the browser to do so.
async rewrites() {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { createOpenAI } from "@ai-sdk/openai";
import { AISDKToolkit } from "@assistant-ui/ai-sdk";
import { convertToModelMessages, stepCountIs, streamText, type UIMessage } from "ai";
import { APICallError, convertToModelMessages, stepCountIs, streamText, type UIMessage } from "ai";
import { baseUrl } from "../../../lib/openui";
import { chatPrompt } from "../../../lib/prompt";
import toolkit from "../../../lib/toolkit";
Expand All @@ -12,7 +12,15 @@ const dashboardTools = new AISDKToolkit({ toolkit });

export async function POST(request: Request) {
// assistant-ui sends the whole thread; the browser keeps it.
const { messages } = (await request.json()) as { messages: UIMessage[] };
const { messages, openDashboardId } = (await request.json()) as {
messages: UIMessage[];
openDashboardId?: unknown;
};
// The dashboard open beside the chat, if any: "this dashboard" means that one.
const openId =
typeof openDashboardId === "string" && /^art_[\w-]{1,64}$/.test(openDashboardId)
? openDashboardId
: undefined;
const apiKey = process.env.THESYS_API_KEY;
if (!apiKey) throw new Error("Set THESYS_API_KEY in .env.local, then restart.");

Expand All @@ -22,12 +30,24 @@ export async function POST(request: Request) {

const result = streamText({
model: gateway.chat(process.env.OPENUI_MODEL || "anthropic/claude-sonnet-5.5"),
system: chatPrompt,
system: openId
? `${chatPrompt}\n\nThe user has dashboard ${openId} open beside the chat right now.`
: chatPrompt,
messages: await convertToModelMessages(messages, { tools }),
tools,
// Calls the dashboard tools the model asks for, then lets it reply.
stopWhen: stepCountIs(4),
abortSignal: request.signal,
// The gateway already falls back across providers; retrying here only delays the error.
maxRetries: 0,
});
return result.toUIMessageStreamResponse();
return result.toUIMessageStreamResponse({ onError: errorMessage });
}

// Show the gateway's own error message in the chat; anything else stays in the server log.
function errorMessage(error: unknown) {
console.error(error);
return APICallError.isInstance(error)
? error.message
: "Something went wrong. Check the server logs.";
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import { ThreadList } from "@/components/assistant-ui/elements/thread-list.aui";
import { Thread } from "@/components/assistant-ui/elements/thread.aui";
import { cn } from "@/lib/utils";
import { useChatRuntime } from "@assistant-ui/ai-sdk";
import { AssistantChatTransport, useChatRuntime } from "@assistant-ui/ai-sdk";
import {
AssistantRuntimeProvider,
AuiConfig,
Expand All @@ -17,17 +17,27 @@ import { OpenUICloudProvider } from "@openuidev/react-ui/cloud";
import { LayoutDashboard, MessageSquare } from "lucide-react";
import { useState } from "react";
import toolkit from "../lib/toolkit";
import { DashboardPanel, OpenDashboardProvider, useOpenDashboard } from "./dashboard";
import {
DashboardPanel,
OpenDashboardProvider,
openDashboardId,
useOpenDashboard,
} from "./dashboard";
import { DashboardList } from "./dashboard-list";
import { localThreadList } from "./threads";

const token = "/api/frontend-token";

// Each message carries the dashboard open beside the chat, so an edit lands on that one.
const transport = new AssistantChatTransport({
body: () => ({ openDashboardId: openDashboardId.current ?? undefined }),
});

export default function App({ apiBaseUrl }: { apiBaseUrl?: string }) {
// Each thread posts to /api/chat, which runs the dashboard tools on the server. Threads are
// kept in this browser (src/components/threads.tsx), not in OpenUI Cloud.
const runtime = useRemoteThreadListRuntime({
runtimeHook: () => useChatRuntime(),
runtimeHook: () => useChatRuntime({ transport }),
adapter: localThreadList,
});
return (
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ import {
import { LayoutDashboard, Pencil, Pin, PinOff, Trash2 } from "lucide-react";
import { useEffect, useState, type FormEvent } from "react";
import { useOpenDashboard } from "./dashboard";
import { chatOf } from "./threads";

/**
* The user's dashboards in OpenUI Cloud: pinned ones first, then the rest, newest first. Each
Expand All @@ -47,7 +48,7 @@ export function DashboardList() {
const { unpin } = useArtifactUnpin();
const { update } = useArtifactUpdate();
const { deleteArtifact } = useArtifactDelete();
const { open, setOpen, openId, saved } = useOpenDashboard();
const { open, setOpen, openInChat, openId, saved } = useOpenDashboard();
// The dashboard a dialog is about. It stays set while the dialog animates closed, so the
// dialog keeps showing its name.
const [renaming, setRenaming] = useState<DialogTarget>(null);
Expand Down Expand Up @@ -81,7 +82,9 @@ export function DashboardList() {
<li key={artifact.id} className="group relative">
<button
type="button"
onClick={() => setOpen({ key: `list:${artifact.id}`, id: artifact.id })}
onClick={() =>
openInChat({ key: `list:${artifact.id}`, id: artifact.id }, chatOf(artifact.id))
}
aria-current={open !== null && openId === artifact.id}
className={cn(
"flex w-full items-center gap-2 rounded-md px-2 py-1.5 pr-20 text-left text-sm hover:bg-sidebar-accent",
Expand Down Expand Up @@ -121,7 +124,7 @@ export function DashboardList() {
);

return (
<nav className="flex min-h-0 flex-1 flex-col gap-4 overflow-y-auto">
<nav className="flex min-h-0 flex-1 flex-col gap-4 overflow-y-auto pb-4">
{pinned.artifacts.length > 0 && (
<section className="flex flex-col gap-1">
<h2 className="px-2 text-xs font-medium text-muted-foreground">Pinned</h2>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import type { ToolCallMessagePartProps } from "@assistant-ui/react";
import { useAui, useAuiState, type ToolCallMessagePartProps } from "@assistant-ui/react";
import { ThemeProvider } from "@openuidev/dashboard-library";
import { LiveArtifactRenderer, useArtifactRenderer } from "@openuidev/react-ui/cloud";
import {
Expand Down Expand Up @@ -35,7 +35,10 @@ type Open = DashboardSource & { key: string };

const OpenDashboard = createContext<{
open: Open | null;
/** Opens a dashboard beside the current chat, or closes it with `null`. */
setOpen: (open: Open | null) => void;
/** Opens a dashboard beside its chat, switching to it; with no chat, beside a new one. */
openInChat: (open: Open, chatId: string | undefined) => void;
/** The open dashboard's artifact id, once its renderer knows it. */
openId: string | null;
setOpenId: (id: string | null) => void;
Expand All @@ -45,19 +48,55 @@ const OpenDashboard = createContext<{
}>({
open: null,
setOpen: () => {},
openInChat: () => {},
openId: null,
setOpenId: () => {},
saved: 0,
onSaved: () => {},
});

/**
* The open dashboard's artifact id, for the chat transport: it sends it with each message, so
* "this dashboard" means the one the user is looking at. Outside React because the transport is.
*/
export const openDashboardId: { current: string | null } = { current: null };

export function OpenDashboardProvider({ children }: { children: ReactNode }) {
const [open, setOpen] = useState<Open | null>(null);
const aui = useAui();
// `moving`: the dashboard waits for the chat switch it asked for, then stays with that chat.
const [state, setState] = useState<{ open: Open; moving: boolean } | null>(null);
const [openId, setOpenId] = useState<string | null>(null);
useEffect(() => {
openDashboardId.current = openId;
}, [openId]);
const [saved, setSaved] = useState(0);
const onSaved = useCallback(() => setSaved((count) => count + 1), []);

// The panel belongs to its chat: switching chats closes it.
const threadId = useAuiState((s) => s.threads.mainThreadId);
useEffect(
() => setState((current) => (current?.moving ? { ...current, moving: false } : null)),
[threadId],
);

const setOpen = useCallback((open: Open | null) => setState(open && { open, moving: false }), []);
const openInChat = useCallback(
(open: Open, chatId: string | undefined) => {
const { mainThreadId, newThreadId } = aui.threads.getState();
// Already beside its chat, or, with none, beside an empty new chat.
if (chatId ? chatId === mainThreadId : mainThreadId === newThreadId) return setOpen(open);
setState({ open, moving: true });
if (chatId) aui.threads.switchToThread(chatId);
else aui.threads.switchToNewThread();
},
[aui, setOpen],
);

const open = state?.open ?? null;
return (
<OpenDashboard.Provider value={{ open, setOpen, openId, setOpenId, saved, onSaved }}>
<OpenDashboard.Provider
value={{ open, setOpen, openInChat, openId, setOpenId, saved, onSaved }}
>
{children}
</OpenDashboard.Provider>
);
Expand All @@ -83,31 +122,97 @@ export function DashboardCard({
isError,
status,
}: DashboardToolProps) {
const { open, setOpen } = useOpenDashboard();
const isOpen = open?.key === toolCallId;
const { setOpen, openId } = useOpenDashboard();
const response = !isError && typeof result === "string" ? result : undefined;

// Opens once, when the result arrives, so closing the panel sticks.
const opened = useRef(false);
// Opens once, when the result arrives, so closing the panel sticks. A result already there
// when the card mounts is from a past chat being reopened: it stays closed. An edit to the
// dashboard already in the panel leaves the panel as it is: it follows the edit through the
// stream it shares with this card, and keeps its filters and scroll position.
const opened = useRef(Boolean(response));
const showing = openId !== null && openId === args?.id;
useEffect(() => {
if (!response || opened.current) return;
opened.current = true;
setOpen({ key: toolCallId, response });
}, [response, toolCallId, setOpen]);
if (!showing) setOpen({ key: toolCallId, response });
}, [response, toolCallId, setOpen, showing]);

const isEdit = toolName === "edit_dashboard";
const title = args?.title ?? (isEdit ? "Dashboard change" : "New dashboard");
if (!response) {
return (
<Card
title={title}
status={
isError
? ["Couldn't start", "error"]
: [status?.type === "running" ? "Starting" : "Waiting", "busy"]
}
/>
);
}

// A renderer of its own, never opened, so the card shows the same state as the panel: every
// renderer of one dashboard shares its stream. Closed, it doesn't render the dashboard.
return (
<LiveArtifactRenderer
response={response}
library={library}
interpreter={{ url: "/api/interpreter" }}
isOpen={false}
>
<LiveArtifactRenderer.Preview>
<RendererCard title={title} isEdit={isEdit} toolCallId={toolCallId} response={response} />
</LiveArtifactRenderer.Preview>
</LiveArtifactRenderer>
);
}

function RendererCard({
title,
isEdit,
toolCallId,
response,
}: {
title: string;
isEdit: boolean;
toolCallId: string;
response: string;
}) {
const { id, isStreaming, error } = useArtifactRenderer();
const { open, openId, setOpen } = useOpenDashboard();
// Open from this card, or the panel is showing the same dashboard: opened from another of its
// cards or from the Dashboards list.
const isOpen = open?.key === toolCallId || (id !== null && openId === id);
const status: [string, Tone] = error
? ["Couldn't load", "error"]
: isStreaming
? [isEdit ? "Changing" : "Generating", "busy"]
: [isEdit ? "Changed" : "Live", "live"];
return (
<Card
title={title}
status={status}
isOpen={isOpen}
onToggle={() => setOpen(isOpen ? null : { key: toolCallId, response })}
/>
);
}

const title =
args?.title ?? (toolName === "edit_dashboard" ? "Dashboard change" : "New dashboard");
const [label, tone]: [string, Tone] = isError
? ["Couldn't start", "error"]
: response
? [toolName === "edit_dashboard" ? "Change started" : "Live", "live"]
: [status?.type === "running" ? "Starting" : "Waiting", "busy"];
type CardProps = {
title: string;
status: [label: string, tone: Tone];
isOpen?: boolean;
/** Without it, the card can't be opened yet. */
onToggle?: () => void;
};

function Card({ title, status: [label, tone], isOpen = false, onToggle }: CardProps) {
return (
<button
type="button"
disabled={!response}
onClick={() => setOpen(isOpen || !response ? null : { key: toolCallId, response })}
disabled={!onToggle}
onClick={onToggle}
aria-pressed={isOpen}
className={cn(
"group my-3 flex w-full max-w-md items-center gap-3 rounded-xl border bg-card p-3 text-left shadow-xs transition-colors",
Expand All @@ -125,7 +230,7 @@ export function DashboardCard({
{label}
</span>
</span>
{response && (
{onToggle && (
<span className="flex items-center gap-0.5 text-xs font-medium text-muted-foreground group-hover:text-foreground">
{isOpen ? "Close" : "Open"}
{isOpen ? <PanelRightClose className="size-4" /> : <ChevronRight className="size-4" />}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,22 @@ function updateThread(remoteId: string, change: Partial<StoredThread>) {
write("threads", { ...all, [remoteId]: { ...current, ...change, updatedAt: Date.now() } });
}

/**
* The chat that built a dashboard: the one whose saved messages hold its id, in the tool
* result's `artifact_id=` reference. A dashboard built elsewhere, such as in another browser,
* has none.
*/
export function chatOf(artifactId: string): string | undefined {
const reference = `artifact_id=${encodeURIComponent(artifactId)}&`;
return Object.keys(threads()).find((remoteId) => {
try {
return localStorage.getItem(`${PREFIX}:messages:${remoteId}`)?.includes(reference);
} catch {
return false;
}
});
}

/** Loads and saves each thread's messages. */
function useHistory() {
const aui = useAui();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ ${data}

- When the user asks for a dashboard, call create_dashboard with a short title and a prompt naming the packages or repositories (owner/name) and describing the sections, metrics, charts, tables, and filters, and which data each shows. Don't put numbers in the prompt; the dashboard loads them.
- If the user names a project, use its npm package name and GitHub repository as you know them, such as react and facebook/react.
- To change a dashboard, call edit_dashboard with the artifact_id from the tool result that created it. "It" or "the dashboard" means the latest one. Create a new dashboard only when asked.
- To change a dashboard, call edit_dashboard with the artifact_id from the tool result that created it. "It", "this" or "the dashboard" means the one open beside the chat when there is one, otherwise the latest one. Create a new dashboard only when asked.
- The tools return as soon as the dashboard has an id, and the user watches it being built. Never repeat the tool result.
- After a tool call, reply in one or two short sentences: what the dashboard shows and one change they could ask for. Use Markdown sparingly.
- You can't see the data, so don't state any numbers. If a request is outside this data, say so.`;
Loading