chore: import upstream snapshot with attribution

This commit is contained in:
wehub-resource-sync
2026-07-13 12:58:18 +08:00
commit 6d5d58c1a9
18293 changed files with 3502153 additions and 0 deletions
@@ -0,0 +1,18 @@
# LangGraph deployment URL (required in production, defaults to http://localhost:8125 in dev)
# LANGGRAPH_DEPLOYMENT_URL=
# LANGSMITH_* variables below are primarily consumed by the agent /
# LangGraph deployment at deploy time (set them in the agent's
# environment, e.g. the LangGraph Cloud deployment or `apps/agent/.env`).
# The Next.js web app itself only observes LANGSMITH_API_KEY here to
# emit a dev-only "missing key" warning and to forward the key through
# to the LangGraphAgent client in apps/web/src/app/api/copilotkit/route.ts.
# LangSmith API key (optional, for production tracing)
# LANGSMITH_API_KEY=
# Enable LangSmith tracing (optional)
# LANGSMITH_TRACING=true
# LangSmith project name (optional; used by LangSmith tracing if LANGSMITH_TRACING=true)
# LANGSMITH_PROJECT=interrupts-langgraph
@@ -0,0 +1,23 @@
import nextCoreWebVitals from "eslint-config-next/core-web-vitals";
import nextTypescript from "eslint-config-next/typescript";
// Flat-config ESLint setup for Next 16 / React 19 / TS 5. Mirrors the
// sibling `examples/showcases/open-mcp-client/apps/web/eslint.config.mjs`
// so lint behaviour stays consistent across starters. Next 16 removed
// the `next lint` command, so package.json now invokes `eslint .`
// directly against this config.
const eslintConfig = [
...nextCoreWebVitals,
...nextTypescript,
{
ignores: [
"node_modules/**",
".next/**",
"out/**",
"build/**",
"next-env.d.ts",
],
},
];
export default eslintConfig;
@@ -0,0 +1,7 @@
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
serverExternalPackages: ["@copilotkit/runtime"],
};
export default nextConfig;
@@ -0,0 +1,42 @@
{
"name": "web-langgraph-interrupt",
"version": "0.1.7",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "eslint . --max-warnings=0"
},
"dependencies": {
"@copilotkit/react-core": "workspace:*",
"@copilotkit/react-ui": "workspace:*",
"@copilotkit/runtime": "workspace:*",
"next": "16.0.8",
"react": "^19.2.1",
"react-dom": "^19.2.1",
"shiki": "^3.22.0",
"zod": "^3.25.76"
},
"devDependencies": {
"@eslint/eslintrc": "^3",
"@tailwindcss/postcss": "^4",
"@types/node": "^22.19.11",
"@types/react": "^19",
"@types/react-dom": "^19",
"eslint": "^9",
"eslint-config-next": "16.0.8",
"tailwindcss": "^4",
"typescript": "^5.9.3"
},
"engines": {
"node": ">=20.0.0"
},
"nx": {
"targets": {
"build": {
"cache": false
}
}
}
}
@@ -0,0 +1,5 @@
const config = {
plugins: ["@tailwindcss/postcss"],
};
export default config;
@@ -0,0 +1,28 @@
{
"name": "web-langgraph-interrupt",
"$schema": "../../node_modules/nx/schemas/project-schema.json",
"sourceRoot": "apps/web/src",
"projectType": "application",
"targets": {
"dev": {
"executor": "nx:run-commands",
"options": {
"command": "pnpm --filter web-langgraph-interrupt dev"
}
},
"build": {
"executor": "nx:run-commands",
"cache": false,
"options": {
"command": "pnpm --filter web-langgraph-interrupt build"
}
},
"lint": {
"executor": "nx:run-commands",
"options": {
"command": "pnpm --filter web-langgraph-interrupt lint"
}
}
},
"tags": []
}
@@ -0,0 +1 @@
<svg fill="none" viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg"><path d="M14.5 13.5V5.41a1 1 0 0 0-.3-.7L9.8.29A1 1 0 0 0 9.08 0H1.5v13.5A2.5 2.5 0 0 0 4 16h8a2.5 2.5 0 0 0 2.5-2.5m-1.5 0v-7H8v-5H3v12a1 1 0 0 0 1 1h8a1 1 0 0 0 1-1M9.5 5V2.12L12.38 5zM5.13 5h-.62v1.25h2.12V5zm-.62 3h7.12v1.25H4.5zm.62 3h-.62v1.25h7.12V11z" clip-rule="evenodd" fill="#666" fill-rule="evenodd"/></svg>

After

Width:  |  Height:  |  Size: 391 B

@@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><g clip-path="url(#a)"><path fill-rule="evenodd" clip-rule="evenodd" d="M10.27 14.1a6.5 6.5 0 0 0 3.67-3.45q-1.24.21-2.7.34-.31 1.83-.97 3.1M8 16A8 8 0 1 0 8 0a8 8 0 0 0 0 16m.48-1.52a7 7 0 0 1-.96 0H7.5a4 4 0 0 1-.84-1.32q-.38-.89-.63-2.08a40 40 0 0 0 3.92 0q-.25 1.2-.63 2.08a4 4 0 0 1-.84 1.31zm2.94-4.76q1.66-.15 2.95-.43a7 7 0 0 0 0-2.58q-1.3-.27-2.95-.43a18 18 0 0 1 0 3.44m-1.27-3.54a17 17 0 0 1 0 3.64 39 39 0 0 1-4.3 0 17 17 0 0 1 0-3.64 39 39 0 0 1 4.3 0m1.1-1.17q1.45.13 2.69.34a6.5 6.5 0 0 0-3.67-3.44q.65 1.26.98 3.1M8.48 1.5l.01.02q.41.37.84 1.31.38.89.63 2.08a40 40 0 0 0-3.92 0q.25-1.2.63-2.08a4 4 0 0 1 .85-1.32 7 7 0 0 1 .96 0m-2.75.4a6.5 6.5 0 0 0-3.67 3.44 29 29 0 0 1 2.7-.34q.31-1.83.97-3.1M4.58 6.28q-1.66.16-2.95.43a7 7 0 0 0 0 2.58q1.3.27 2.95.43a18 18 0 0 1 0-3.44m.17 4.71q-1.45-.12-2.69-.34a6.5 6.5 0 0 0 3.67 3.44q-.65-1.27-.98-3.1" fill="#666"/></g><defs><clipPath id="a"><path fill="#fff" d="M0 0h16v16H0z"/></clipPath></defs></svg>

After

Width:  |  Height:  |  Size: 1.0 KiB

@@ -0,0 +1 @@
<svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 394 80"><path fill="#000" d="M262 0h68.5v12.7h-27.2v66.6h-13.6V12.7H262V0ZM149 0v12.7H94v20.4h44.3v12.6H94v21h55v12.6H80.5V0h68.7zm34.3 0h-17.8l63.8 79.4h17.9l-32-39.7 32-39.6h-17.9l-23 28.6-23-28.6zm18.3 56.7-9-11-27.1 33.7h17.8l18.3-22.7z"/><path fill="#000" d="M81 79.3 17 0H0v79.3h13.6V17l50.2 62.3H81Zm252.6-.4c-1 0-1.8-.4-2.5-1s-1.1-1.6-1.1-2.6.3-1.8 1-2.5 1.6-1 2.6-1 1.8.3 2.5 1a3.4 3.4 0 0 1 .6 4.3 3.7 3.7 0 0 1-3 1.8zm23.2-33.5h6v23.3c0 2.1-.4 4-1.3 5.5a9.1 9.1 0 0 1-3.8 3.5c-1.6.8-3.5 1.3-5.7 1.3-2 0-3.7-.4-5.3-1s-2.8-1.8-3.7-3.2c-.9-1.3-1.4-3-1.4-5h6c.1.8.3 1.6.7 2.2s1 1.2 1.6 1.5c.7.4 1.5.5 2.4.5 1 0 1.8-.2 2.4-.6a4 4 0 0 0 1.6-1.8c.3-.8.5-1.8.5-3V45.5zm30.9 9.1a4.4 4.4 0 0 0-2-3.3 7.5 7.5 0 0 0-4.3-1.1c-1.3 0-2.4.2-3.3.5-.9.4-1.6 1-2 1.6a3.5 3.5 0 0 0-.3 4c.3.5.7.9 1.3 1.2l1.8 1 2 .5 3.2.8c1.3.3 2.5.7 3.7 1.2a13 13 0 0 1 3.2 1.8 8.1 8.1 0 0 1 3 6.5c0 2-.5 3.7-1.5 5.1a10 10 0 0 1-4.4 3.5c-1.8.8-4.1 1.2-6.8 1.2-2.6 0-4.9-.4-6.8-1.2-2-.8-3.4-2-4.5-3.5a10 10 0 0 1-1.7-5.6h6a5 5 0 0 0 3.5 4.6c1 .4 2.2.6 3.4.6 1.3 0 2.5-.2 3.5-.6 1-.4 1.8-1 2.4-1.7a4 4 0 0 0 .8-2.4c0-.9-.2-1.6-.7-2.2a11 11 0 0 0-2.1-1.4l-3.2-1-3.8-1c-2.8-.7-5-1.7-6.6-3.2a7.2 7.2 0 0 1-2.4-5.7 8 8 0 0 1 1.7-5 10 10 0 0 1 4.3-3.5c2-.8 4-1.2 6.4-1.2 2.3 0 4.4.4 6.2 1.2 1.8.8 3.2 2 4.3 3.4 1 1.4 1.5 3 1.5 5h-5.8z"/></svg>

After

Width:  |  Height:  |  Size: 1.3 KiB

@@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1155 1000"><path d="m577.3 0 577.4 1000H0z" fill="#fff"/></svg>

After

Width:  |  Height:  |  Size: 128 B

@@ -0,0 +1 @@
<svg fill="none" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16"><path fill-rule="evenodd" clip-rule="evenodd" d="M1.5 2.5h13v10a1 1 0 0 1-1 1h-11a1 1 0 0 1-1-1zM0 1h16v11.5a2.5 2.5 0 0 1-2.5 2.5h-11A2.5 2.5 0 0 1 0 12.5zm3.75 4.5a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5M7 4.75a.75.75 0 1 1-1.5 0 .75.75 0 0 1 1.5 0m1.75.75a.75.75 0 1 0 0-1.5.75.75 0 0 0 0 1.5" fill="#666"/></svg>

After

Width:  |  Height:  |  Size: 385 B

@@ -0,0 +1,149 @@
import {
CopilotRuntime,
ExperimentalEmptyAdapter,
copilotRuntimeNextJSAppRouterEndpoint,
} from "@copilotkit/runtime";
import { LangGraphAgent } from "@copilotkit/runtime/langgraph";
import { NextRequest, NextResponse } from "next/server";
// 1. Runtime adapter. Since this starter wires agent responses directly
// (no OpenAI/Anthropic-compatible chat-completions fallback), we use
// the empty adapter: it satisfies the runtime interface without
// dispatching any LLM requests of its own.
const serviceAdapter = new ExperimentalEmptyAdapter();
// 2. LANGGRAPH_DEPLOYMENT_URL handling. In development we fall back to
// localhost:8125 (the port this starter's LangGraph dev server uses —
// see apps/agent/package.json) and warn so the developer sees it. In
// production a missing URL is almost always a misconfiguration — but
// we defer the hard failure to the first request (see POST below)
// rather than throwing at module load. `next build` evaluates route
// modules with NODE_ENV=production during route collection, while
// runtime-only env vars (Vercel secrets, Railway env, Docker ENV at
// container start) are NOT injected at build time. Throwing at module
// load would abort otherwise-valid production builds.
if (
!process.env.LANGGRAPH_DEPLOYMENT_URL &&
process.env.NODE_ENV !== "production"
) {
console.warn(
"[copilotkit/route] LANGGRAPH_DEPLOYMENT_URL is not set; falling back to http://localhost:8125. Set LANGGRAPH_DEPLOYMENT_URL in production.",
);
}
// LangSmith is optional; warn once at module load so a missing key
// surfaces in logs. When absent we omit the langsmithApiKey field
// entirely rather than passing "" — omitting the field disables
// LangSmith tracing cleanly; passing an empty string may be forwarded
// to the SDK. Gate the warn on NODE_ENV so it does not fire during
// `next build` in CI (same rationale as the DEPLOYMENT_URL warn above).
if (!process.env.LANGSMITH_API_KEY && process.env.NODE_ENV !== "production") {
console.warn(
"[copilotkit/route] LANGSMITH_API_KEY is not set; LangSmith tracing is disabled for this session.",
);
}
// 3. Lazy runtime construction. We build the LangGraphAgent + runtime +
// handler on the first request rather than at module load, so that
// `next build` (which evaluates this file with NODE_ENV=production but
// without runtime env vars) does not bake the fallback localhost URL
// into the compiled artifact. The cached closure keeps per-request
// overhead at the same single-allocation cost as the eager form.
// Matches the signature returned by copilotRuntimeNextJSAppRouterEndpoint:
// `(req: Request) => Response | Promise<Response>`. NextRequest extends
// Request, so the POST handler below can still pass its req through
// without an explicit cast.
let cachedHandleRequest:
| ((req: Request) => Response | Promise<Response>)
| null = null;
const getHandleRequest = () => {
if (cachedHandleRequest) return cachedHandleRequest;
const deploymentUrl = process.env.LANGGRAPH_DEPLOYMENT_URL;
if (!deploymentUrl && process.env.NODE_ENV === "production") {
throw new Error(
"[copilotkit/route] LANGGRAPH_DEPLOYMENT_URL is required in production. " +
"Set it to the deployed LangGraph endpoint for this starter.",
);
}
const agent = new LangGraphAgent({
deploymentUrl: deploymentUrl || "http://localhost:8125",
graphId: "default",
// Only pass langsmithApiKey when it's a non-empty string; omitting
// the field disables LangSmith tracing without asking the SDK to
// authenticate with an empty key.
...(process.env.LANGSMITH_API_KEY
? { langsmithApiKey: process.env.LANGSMITH_API_KEY }
: {}),
});
// Register the single LangGraph agent under the `default` name, which
// matches the <CopilotKit agent="default"> prop in layout.tsx. If you
// need to expose this agent under an additional id (e.g. when pointing
// a second frontend at this runtime), add another entry here and
// update the corresponding <CopilotKit agent="..."> prop.
const runtime = new CopilotRuntime({
agents: {
default: agent,
},
});
const { handleRequest } = copilotRuntimeNextJSAppRouterEndpoint({
runtime,
serviceAdapter,
endpoint: "/api/copilotkit",
});
cachedHandleRequest = handleRequest;
return handleRequest;
};
// 4. POST handler. Resolves the cached handler (building it on first
// request), then dispatches. Wrap in try/catch so unhandled exceptions
// surface as a structured 500 rather than a raw Next.js error page,
// and log the failure for observability. Errors inside the streaming
// response are handled by the runtime itself.
export const POST = async (req: NextRequest) => {
// Redact `detail` in production: raw error messages can leak
// internals (stack-adjacent strings, paths, env-var names). Keep
// the full detail in non-production builds so developers see the
// real cause locally.
const isProd = process.env.NODE_ENV === "production";
// Split construction vs dispatch into two try/catch regions so
// logs distinguish runtime-construction failures (bad config / env)
// from dispatch failures inside handleRequest. Response shape is
// unchanged between the two.
let handleRequest: (req: Request) => Response | Promise<Response>;
try {
handleRequest = getHandleRequest();
} catch (err) {
console.error("[copilotkit/route] runtime construction failed:", err);
return NextResponse.json(
{
error: "Internal error while dispatching CopilotKit request.",
...(isProd
? {}
: { detail: err instanceof Error ? err.message : String(err) }),
},
{ status: 500 },
);
}
try {
return await handleRequest(req);
} catch (err) {
console.error("[copilotkit/route] handleRequest dispatch failed:", err);
return NextResponse.json(
{
error: "Internal error while dispatching CopilotKit request.",
...(isProd
? {}
: { detail: err instanceof Error ? err.message : String(err) }),
},
{ status: 500 },
);
}
};
Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

@@ -0,0 +1,24 @@
@import "tailwindcss";
:root {
--background: #ffffff;
--foreground: #171717;
}
@media (prefers-color-scheme: dark) {
:root {
--background: #0a0a0a;
--foreground: #ededed;
}
}
body {
background: var(--background);
color: var(--foreground);
font-family: Arial, Helvetica, sans-serif;
}
body,
html {
height: 100%;
}
@@ -0,0 +1,27 @@
import type { Metadata } from "next";
import { CopilotKit } from "@copilotkit/react-core";
import "./globals.css";
import "@copilotkit/react-ui/styles.css";
export const metadata: Metadata = {
title: "CopilotKit LangGraph Interrupts Starter",
description:
"A starter template for building AI agents with human-in-the-loop interrupts using LangGraph and CopilotKit.",
};
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode;
}>) {
return (
<html lang="en">
<body className={"antialiased"}>
<CopilotKit runtimeUrl="/api/copilotkit" agent="default">
{children}
</CopilotKit>
</body>
</html>
);
}
@@ -0,0 +1,398 @@
"use client";
import { useCoAgent, useCopilotAction } from "@copilotkit/react-core";
import { CopilotKitCSSProperties, CopilotSidebar } from "@copilotkit/react-ui";
import { useInterrupt } from "@copilotkit/react-core/v2";
import { useState } from "react";
export default function CopilotKitPage() {
const [themeColor, setThemeColor] = useState("#6366f1");
// 🪁 Frontend Actions: https://docs.copilotkit.ai/guides/frontend-actions
useCopilotAction(
{
name: "setThemeColor",
description: "Set the theme color of the page.",
parameters: [
{
name: "themeColor",
type: "string",
description: "The theme color to set. Make sure to pick nice colors.",
required: true,
},
],
handler({ themeColor }) {
// Defensive guard: during streaming, the LLM may invoke the handler
// before the `themeColor` arg has fully arrived. Skipping the update
// here avoids writing `undefined` into the CSS custom property, which
// would collapse the --copilot-kit-primary-color variable.
if (typeof themeColor !== "string" || themeColor.length === 0) return;
setThemeColor(themeColor);
},
},
[setThemeColor],
);
// 🪁 Interrupts: Handle human-in-the-loop confirmations from the agent
// https://docs.copilotkit.ai/coagents/human-in-the-loop (useInterrupt)
//
// The agent emits interrupt payloads shaped as
// { action: "delete_proverb"; proverb: string; message: string }
// Today the only supported action is delete_proverb. When future
// actions are added, widen InterruptPayload to a discriminated union
// on `action` and extend APPROVE_LABELS below — TypeScript will flag
// the missing key as a compile error because APPROVE_LABELS is typed
// as Record<InterruptPayload["action"], string>.
useInterrupt({
render: ({ event, resolve }) => {
const parsed = parseInterruptPayload(event.value);
if (!parsed.ok) {
// Unknown/malformed payload shape. Surface a generic fallback
// rather than crashing on an unchecked cast. Resolving with a
// cancellation unblocks the agent in case the user dismisses it.
// Log the reason + raw payload so developers can diagnose
// schema drift from the agent side — the UI shows "unknown"
// without this, which is useless for debugging. The parser
// itself does not log, so this is the single log line for
// the whole failure path.
console.error(
"[interrupts-langgraph] Unknown interrupt payload shape:",
parsed.reason,
event.value,
);
return (
<div className="bg-red-50 border border-red-200 rounded-lg p-4 my-2">
<p className="text-sm text-red-800">
Received an unknown interrupt payload. This will tell the agent to
cancel.
</p>
<button
onClick={() => resolve({ approved: false })}
className="mt-2 px-3 py-1.5 text-sm font-medium text-gray-700 bg-gray-100 hover:bg-gray-200 rounded-md transition-colors"
>
Cancel request
</button>
</div>
);
}
// Resolve the button label for this action.
const payload = parsed.value;
const approveLabel = APPROVE_LABELS[payload.action];
return (
<div className="bg-yellow-50 border border-yellow-200 rounded-lg p-4 my-2">
<p className="text-sm font-medium text-yellow-800 mb-1">
Confirmation Required
</p>
<p className="text-sm text-yellow-700 mb-3">{payload.message}</p>
<div className="flex gap-2">
<button
onClick={() => resolve({ approved: true })}
className="px-3 py-1.5 text-sm font-medium text-white bg-red-500 hover:bg-red-600 rounded-md transition-colors"
>
{approveLabel}
</button>
<button
onClick={() => resolve({ approved: false })}
className="px-3 py-1.5 text-sm font-medium text-gray-700 bg-gray-100 hover:bg-gray-200 rounded-md transition-colors"
>
Cancel
</button>
</div>
</div>
);
},
});
return (
<main
style={
{ "--copilot-kit-primary-color": themeColor } as CopilotKitCSSProperties
}
>
<YourMainContent themeColor={themeColor} />
<CopilotSidebar
clickOutsideToClose={false}
defaultOpen={true}
labels={{
title: "Popup Assistant",
initial:
'👋 Hi, there! You\'re chatting with an agent. This agent comes with a few tools to get you started.\n\nFor example you can try:\n- **Frontend Tools**: "Set the theme to orange"\n- **Shared State**: "Write a proverb about AI"\n- **Generative UI**: "Get the weather in SF"\n- **Interrupts**: "Delete the first proverb" (will ask for confirmation)\n\nAs you interact with the agent, you\'ll see the UI update in real-time to reflect the agent\'s **state**, **tool calls**, and **progress**.',
}}
/>
</main>
);
}
// Partial view of the agent state the UI reads + writes. The agent's
// full state is defined in apps/agent/src/agent.ts (AgentStateAnnotation);
// this type intentionally declares only the subset the UI consumes. Keep
// the field names and types in sync with the agent side.
type AgentState = {
proverbs: string[];
};
// Shape of interrupt payloads produced by deleteProverb on the agent
// side. Validated at runtime by `parseInterruptPayload` below. Kept
// close to the consumer so divergence surfaces in the renderer where
// it's used.
type InterruptPayload = {
action: "delete_proverb";
proverb: string;
message: string;
};
// Approve-button label per interrupt action. Typed exhaustively against
// InterruptPayload["action"] so adding a new action anywhere else in the
// file is a compile error until this map is extended.
const APPROVE_LABELS: Record<InterruptPayload["action"], string> = {
delete_proverb: "Yes, delete it",
};
// Result type surfaces the first failed predicate as a stable reason
// string so the caller can log a single message containing both the
// reason and the raw value. The parser itself does no logging — the
// renderer owns the single log line (avoids the prior double-log).
type ParseResult =
| { ok: true; value: InterruptPayload }
| { ok: false; reason: string };
function parseInterruptPayload(value: unknown): ParseResult {
if (value === null || typeof value !== "object" || Array.isArray(value)) {
return { ok: false, reason: "payload is not object" };
}
const v = value as Record<string, unknown>;
if (v.action !== "delete_proverb") {
return { ok: false, reason: "action mismatch" };
}
if (typeof v.proverb !== "string") {
return { ok: false, reason: "proverb not string" };
}
if (typeof v.message !== "string") {
return { ok: false, reason: "message not string" };
}
return {
ok: true,
value: {
action: "delete_proverb",
proverb: v.proverb,
message: v.message,
},
};
}
function YourMainContent({ themeColor }: { themeColor: string }) {
// 🪁 Shared State: https://docs.copilotkit.ai/coagents/shared-state
const { state, setState } = useCoAgent<AgentState>({
name: "default",
initialState: {
proverbs: [
"CopilotKit may be new, but it's the best thing since sliced bread.",
],
},
});
// Defensive default: during transient state-sync, `state` or
// `state.proverbs` can momentarily be undefined. Coalescing here
// keeps the map/length checks below from falling into the
// `undefined !== 0` trap that would hide the "No proverbs yet"
// empty-state fallback.
const proverbs = state?.proverbs ?? [];
// 🪁 Shared State action: writes into the shared agent state above
// (not to be confused with a pure frontend action — this mutates
// `proverbs`, which is part of the agent's CoAgent state and is
// synced back to the graph on the next turn).
// https://docs.copilotkit.ai/coagents/shared-state
useCopilotAction(
{
name: "addProverb",
description: "Add a proverb to the list.",
parameters: [
{
name: "proverb",
type: "string",
description: "The proverb to add. Make it witty, short and concise.",
required: true,
},
],
handler: ({ proverb }) => {
// Defensive guard: during streaming, the LLM may invoke the handler
// before the `proverb` arg has fully arrived. Skipping the update
// here avoids pushing `undefined` into the proverbs array, which
// would break React rendering and React key stability.
if (typeof proverb !== "string" || proverb.length === 0) return;
setState((prevState) => ({
...prevState,
proverbs: [...(prevState?.proverbs || []), proverb],
}));
},
},
[setState],
);
//🪁 Generative UI: https://docs.copilotkit.ai/coagents/generative-ui
//
// `available: "disabled"` is the correct pairing with `render:` here.
// In @copilotkit/react-core, useCopilotAction routes based on the
// `available` value (see
// node_modules/@copilotkit/react-core/src/hooks/use-copilot-action.ts
// `getActionConfig`):
// - "enabled" / "remote" → frontend tool (handler runs client-side)
// - "frontend" / "disabled" → render-only (registers a tool-call
// renderer; no handler)
// We want the BACKEND `getWeather` tool in agent.ts to execute the
// handler server-side AND have the streamed tool-call args drive a
// client-side gen-UI render here. The render-only path (via
// useRenderToolCall) still adds this renderer to
// `copilotkit.renderToolCalls` regardless of `available`, so the
// WeatherCard fires during tool-call streaming (see
// examples/showcases/scene-creator/src/app/page.tsx for the same
// pattern). Setting `"enabled"` here would register a FRONTEND handler
// of the same name and collide with the backend tool.
useCopilotAction(
{
name: "getWeather",
description: "Get the weather for a given location.",
available: "disabled",
parameters: [{ name: "location", type: "string", required: true }],
render: ({ args }) => {
return <WeatherCard location={args.location} themeColor={themeColor} />;
},
},
[themeColor],
);
return (
<div
style={{ backgroundColor: themeColor }}
className="h-screen w-screen flex justify-center items-center flex-col transition-colors duration-300"
>
<div className="bg-white/20 backdrop-blur-md p-8 rounded-2xl shadow-xl max-w-2xl w-full">
<h1 className="text-4xl font-bold text-white mb-2 text-center">
Proverbs
</h1>
<p className="text-gray-200 text-center italic mb-6">
This is a demonstrative page, but it could be anything you want! 🪁
</p>
<hr className="border-white/20 my-6" />
<div className="flex flex-col gap-3">
{proverbs.map((proverb, index) => (
// Intentional index-and-content composite key: `${index}-${proverb}`.
// Plain `proverb` collides on duplicates (React logs a
// duplicate-key warning and collapses to one node); plain
// `index` destabilizes rows across agent-side inserts/deletes.
// The composite tolerates duplicates for this demo where rows
// are append-only and reordering is not a concern. Migrating
// to `{id, text}` objects (seeded with crypto.randomUUID())
// is the proper fix and is deferred to a follow-up since it
// requires widening AgentState.proverbs.
<div
key={`${index}-${proverb}`}
className="bg-white/15 p-4 rounded-xl text-white relative group hover:bg-white/20 transition-all"
>
<p className="pr-8">{proverb}</p>
<button
onClick={() =>
setState((prev) => ({
...(prev ?? {}),
// Filter by value identity rather than captured index:
// between render and click, the agent may have
// inserted/removed proverbs, shifting `index` to point
// at a different entry. Matching on the string value
// is stable (and consistent with the React key above).
proverbs: (prev?.proverbs ?? []).filter(
(p) => p !== proverb,
),
}))
}
className="absolute right-3 top-3 opacity-0 group-hover:opacity-100 transition-opacity
bg-red-500 hover:bg-red-600 text-white rounded-full h-6 w-6 flex items-center justify-center"
>
</button>
</div>
))}
</div>
{proverbs.length === 0 && (
<p className="text-center text-white/80 italic my-8">
No proverbs yet. Ask the assistant to add some!
</p>
)}
</div>
</div>
);
}
function SunIcon() {
return (
<svg
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 24 24"
fill="currentColor"
className="w-14 h-14 text-yellow-200"
>
<circle cx="12" cy="12" r="5" />
<path
d="M12 1v2M12 21v2M4.22 4.22l1.42 1.42M18.36 18.36l1.42 1.42M1 12h2M21 12h2M4.22 19.78l1.42-1.42M18.36 5.64l1.42-1.42"
strokeWidth="2"
stroke="currentColor"
/>
</svg>
);
}
// Weather card rendered by the getWeather action. `location` and
// `themeColor` are driven by the agent's tool-call args + frontend state.
function WeatherCard({
location,
themeColor,
}: {
location?: string;
themeColor: string;
}) {
return (
<div
style={{ backgroundColor: themeColor }}
className="rounded-xl shadow-xl mt-6 mb-4 max-w-md w-full"
>
<div className="bg-white/20 p-4 w-full">
<div className="flex items-center justify-between">
<div>
<h3 className="text-xl font-bold text-white capitalize">
{/* During streaming, the tool-call arg may not have arrived
yet, leaving `location` undefined and producing a blank
heading. Show a loading placeholder in that window. */}
{location || "Loading…"}
</h3>
<p className="text-white">Current Weather</p>
</div>
<SunIcon />
</div>
<div className="mt-4 flex items-end justify-between">
<div className="text-3xl font-bold text-white">70°</div>
<div className="text-sm text-white">Clear skies</div>
</div>
<div className="mt-4 pt-4 border-t border-white">
<div className="grid grid-cols-3 gap-2 text-center">
<div>
<p className="text-white text-xs">Humidity</p>
<p className="text-white font-medium">45%</p>
</div>
<div>
<p className="text-white text-xs">Wind</p>
<p className="text-white font-medium">5 mph</p>
</div>
<div>
<p className="text-white text-xs">Feels Like</p>
<p className="text-white font-medium">72°</p>
</div>
</div>
</div>
</div>
</div>
);
}
@@ -0,0 +1,34 @@
{
"compilerOptions": {
"target": "ES2022",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "bundler",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "react-jsx",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"baseUrl": ".",
"paths": {
"@/*": ["./src/*"]
}
},
"include": [
"next-env.d.ts",
"**/*.ts",
"**/*.tsx",
".next/types/**/*.ts",
".next/dev/types/**/*.ts"
],
"exclude": ["node_modules"]
}