Skip to content

🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.

✨ feat(canvas): Canvas — multi-file HTML artifacts rendered with lobe-* elements (#21326)

Inneidbd209934c62
diff --git a/.agents/acceptance/common-mistakes.md b/.agents/acceptance/common-mistakes.md
index b5ca2cd0a80..128d2e4fc8a 100644
--- a/.agents/acceptance/common-mistakes.md
+++ b/.agents/acceptance/common-mistakes.md
@@ -39,6 +39,7 @@ the next free number of that prefix.
- **L-E20** Build fixtures through the same composition the product uses; compare an entity page against a canary-created sibling before publishing it as evidence.
- **L-E21** Evidence for "A is unaffected by B" must be able to tell A from B: distinct content and the target echoed in the request line.
- **L-E21** Publish against production even when the subject exists only locally; a local ingest may supplement, never replace.
+- **L-E22** `requiredEvidence: text` is satisfied only by `.txt`/`.json`-style files; an `.md` file ingests as `markdown` and leaves the check `uncertain`.
**Product and interaction contracts**
@@ -605,3 +606,15 @@ dev.mjs 每次启动都会拉起 renderer Vite dev server,而后者启动即
**Rule:** 每次 `start`/`restart` 之后、驱动之前,先 `cd apps/desktop && pnpm build:renderer`
(约 25s)并确认 `dist/renderer/apps/desktop/index.html` 存在。同一个 dev.mjs 生命周期内
的后续重启不会再次清空;改用 `restart` 而不是 `start` 时也按同一规则处理。
+
+### L-E22 — 用 .md 文件充当 text 证据
+
+`since 2026-10-21` · `holds-while: lh acceptance run ingest 按扩展名推断证据类型,.md → markdown`
+
+**Trap:** 计划项声明 `requiredEvidence: ["text"]`,唯一的文本证据是 `assets/*.md`。`ingest --dry-run`
+不报错,正式发布却返回 `publicationStatus: partial`,这些检查被记成 `uncertain`。原因是 `.md`
+被存成 `markdown` 类型,不算 `text`。
+
+**Rule:** 文本类执行记录用 `.txt` 或 `.json` 保存;必须用 Markdown 排版时,另附一份同内容的
+`.txt`。发布后用 `lh acceptance run result list --run <id> --json` 核对每项 verdict。已发布的轮次
+用 `lh acceptance run result submit --type text --file <x>.txt --verdict ...` 补交,不要新开一轮。
diff --git a/.gitignore b/.gitignore
index 15786469594..89730d19ec3 100644
--- a/.gitignore
+++ b/.gitignore
@@ -59,6 +59,7 @@ bun.lockb
# Build outputs
dist/
+public/canvas-runtime/
public/_spa/
public/_spa-auth/
public/_spa-share/
diff --git a/apps/desktop/src/main/const/__tests__/protocol.test.ts b/apps/desktop/src/main/const/__tests__/protocol.test.ts
index 818f5379241..3d5902188d7 100644
--- a/apps/desktop/src/main/const/__tests__/protocol.test.ts
+++ b/apps/desktop/src/main/const/__tests__/protocol.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest';
-import { isBackendPath } from '../protocol';
+import { isBackendPath, isSandboxedBackendRequestAllowed } from '../protocol';
describe('isBackendPath', () => {
// The renderer runs relayed local-model calls and uploads their output to
@@ -15,3 +15,16 @@ describe('isBackendPath', () => {
expect(isBackendPath('/api/agent/llm-relayx')).toBe(false);
});
});
+
+describe('canvas previews', () => {
+ it('proxies canvas preview pages and the canvas runtime', () => {
+ expect(isBackendPath('/canvas-preview/token/index.html')).toBe(true);
+ expect(isBackendPath('/canvas-runtime/v1/canvas-runtime.js')).toBe(true);
+ });
+
+ it('keeps sandboxed canvas pages away from authenticated backend paths', () => {
+ expect(isSandboxedBackendRequestAllowed('/trpc/lambda/user.getUserState', 'null')).toBe(false);
+ expect(isSandboxedBackendRequestAllowed('/canvas-preview/token/data.json', 'null')).toBe(true);
+ expect(isSandboxedBackendRequestAllowed('/trpc/lambda/user.getUserState', null)).toBe(true);
+ });
+});
diff --git a/apps/desktop/src/main/const/protocol.ts b/apps/desktop/src/main/const/protocol.ts
index 1129fe02d40..70db9565922 100644
--- a/apps/desktop/src/main/const/protocol.ts
+++ b/apps/desktop/src/main/const/protocol.ts
@@ -18,7 +18,18 @@ export const BACKEND_PATH_PREFIXES = [
'/api/auth',
'/api/agent/llm-relay',
'/market',
+ '/canvas-preview',
+ '/canvas-runtime',
];
-export const isBackendPath = (pathname: string) =>
- BACKEND_PATH_PREFIXES.some((prefix) => pathname === prefix || pathname.startsWith(`${prefix}/`));
+const SANDBOXED_PATH_PREFIXES = ['/canvas-preview', '/canvas-runtime'];
+
+const matchesPrefix = (pathname: string, prefixes: string[]) =>
+ prefixes.some((prefix) => pathname === prefix || pathname.startsWith(`${prefix}/`));
+
+export const isBackendPath = (pathname: string) => matchesPrefix(pathname, BACKEND_PATH_PREFIXES);
+
+// Canvas previews run in an opaque-origin sandbox (Origin: null); the proxy would otherwise
+// attach the user's access token to whatever backend path their scripts fetch.
+export const isSandboxedBackendRequestAllowed = (pathname: string, origin: string | null) =>
+ origin !== 'null' || matchesPrefix(pathname, SANDBOXED_PATH_PREFIXES);
diff --git a/apps/desktop/src/main/core/infrastructure/BackendProxyProtocolManager.ts b/apps/desktop/src/main/core/infrastructure/BackendProxyProtocolManager.ts
index c1e18af3d70..27e7d804cd2 100644
--- a/apps/desktop/src/main/core/infrastructure/BackendProxyProtocolManager.ts
+++ b/apps/desktop/src/main/core/infrastructure/BackendProxyProtocolManager.ts
@@ -2,7 +2,7 @@ import { AUTH_FAILURE_HEADER, AUTH_REQUIRED_HEADER } from '@lobechat/desktop-bri
import { BrowserWindow, type Session, session as electronSession } from 'electron';
import { isDev } from '@/const/env';
-import { isBackendPath } from '@/const/protocol';
+import { isBackendPath, isSandboxedBackendRequestAllowed } from '@/const/protocol';
import { getDesktopEnv } from '@/env';
import { appendVercelCookie } from '@/utils/http-headers';
import { describeJwtClaims } from '@/utils/jwt-claims';
@@ -211,6 +211,8 @@ export class BackendProxyProtocolManager {
return async (request) => {
const url = new URL(request.url);
if (!isBackendPath(url.pathname)) return null;
+ if (!isSandboxedBackendRequestAllowed(url.pathname, request.headers.get('origin')))
+ return new Response('Forbidden', { status: 403 });
const session = electronSession.defaultSession;
if (!session)
diff --git a/apps/desktop/vite.renderer.config.ts b/apps/desktop/vite.renderer.config.ts
index e80142bc8c6..631dc7b5ec7 100644
--- a/apps/desktop/vite.renderer.config.ts
+++ b/apps/desktop/vite.renderer.config.ts
@@ -7,6 +7,7 @@ import type { PluginOption, UserConfig, ViteDevServer } from 'vite';
import { defineConfig } from 'vite';
import tsconfigPaths from 'vite-tsconfig-paths';
+import { canvasRuntimeEntries } from '../../plugins/vite/canvasRuntime';
import { devLoadingProgress } from '../../plugins/vite/devLoadingProgress';
import {
createSharedRolldownOutput,
@@ -237,7 +238,7 @@ export default defineConfig(async (env) => {
rolldownOptions: {
input: RENDERER_INPUTS,
output: createSharedRolldownOutput({
- initialEntries: RENDERER_INPUTS,
+ initialEntries: { ...RENDERER_INPUTS, ...canvasRuntimeEntries },
strictExecutionOrder: true,
}),
preserveEntrySignatures: 'allow-extension',
diff --git a/apps/server/src/modules/AgentRuntime/executorHelpers.ts b/apps/server/src/modules/AgentRuntime/executorHelpers.ts
index 79bbfc4f241..85b103ce1b3 100644
--- a/apps/server/src/modules/AgentRuntime/executorHelpers.ts
+++ b/apps/server/src/modules/AgentRuntime/executorHelpers.ts
@@ -170,6 +170,7 @@ export const registerWorkFromIntent = async ({
deleteDocumentWork: (params) => workModel.deleteDocumentWork(params),
deleteTaskWork: (params) => workModel.deleteTaskWork(params),
handleSkillToolResult: (params) => workModel.handleSkillToolResult(params),
+ registerCanvas: (params) => workModel.registerCanvas(params),
registerDocument: (params) => workModel.registerDocument(params),
registerTask: (params) => workModel.registerTask(params),
},
diff --git a/apps/server/src/routers/lambda/__tests__/canvas.test.ts b/apps/server/src/routers/lambda/__tests__/canvas.test.ts
new file mode 100644
index 00000000000..32e9c70e49a
--- /dev/null
+++ b/apps/server/src/routers/lambda/__tests__/canvas.test.ts
@@ -0,0 +1,249 @@
+// @vitest-environment node
+import { getTestDB } from '@lobechat/database/test-utils';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { WorkModel } from '@/database/models/work';
+import { users, workspaceMembers, workspaces } from '@/database/schemas';
+import { verifyCanvasPreviewToken } from '@/server/services/canvas/serve';
+
+import { canvasRouter } from '../canvas';
+
+const serverDB = await getTestDB();
+
+vi.mock('@/business/server/trpc-middlewares/workspaceAuth', async () => {
+ const mod = await vi.importActual<{ trpc: any }>('@/libs/trpc/lambda/init');
+ return {
+ requireWorkspaceRoleWhenScoped: () => mod.trpc.middleware(async (opts: any) => opts.next()),
+ wsCompatProcedure: mod.trpc.procedure,
+ };
+});
+
+const publishing = vi.hoisted(() => ({
+ enabled: true,
+ publish: vi.fn(async (_params: any) => ({
+ deploymentId: 'dep_1',
+ url: 'https://cost.lobehub.sites',
+ })),
+}));
+
+vi.mock('@/business/server/canvasPublish', () => ({
+ isCanvasPublishEnabled: () => publishing.enabled,
+ publishCanvasSite: publishing.publish,
+}));
+
+const committed = vi.hoisted(() => ({ calls: 0 }));
+
+vi.mock('@/server/services/canvas', () => ({
+ createCanvasStorageService: (_db: unknown, ownerId: string) => ({
+ commit: async () => {
+ committed.calls += 1;
+ return {
+ manifest: {},
+ metadata: {
+ entry: 'index.html',
+ fileCount: 1,
+ manifestKey: `canvas/${ownerId}/cvs_new/manifests/m.json`,
+ runtimeMajor: 1,
+ totalSize: 40,
+ },
+ ok: true,
+ };
+ },
+ ownerId,
+ readFile: async () => ({
+ bytes: new TextEncoder().encode('<html><head></head><body>hi</body></html>'),
+ contentType: 'text/html; charset=utf-8',
+ }),
+ readManifest: async () => ({
+ entry: 'index.html',
+ files: { 'index.html': { contentType: 'text/html; charset=utf-8', hash: 'h1', size: 40 } },
+ runtimeMajor: 1,
+ schemaVersion: 1,
+ }),
+ }),
+}));
+
+vi.mock('@/libs/trpc/lambda/middleware', () => ({
+ serverDatabase: async (opts: any) => opts.next({ ctx: { ...opts.ctx, serverDB } }),
+}));
+
+const userId = 'canvas-router-user';
+const caller = (id = userId) => canvasRouter.createCaller({ serverDB, userId: id } as any);
+
+const metadata = (key: string) => ({
+ entry: 'index.html',
+ fileCount: 1,
+ manifestKey: `canvas/${userId}/cvs_1/manifests/${key}.json`,
+ runtimeMajor: 1,
+ totalSize: 10,
+});
+
+beforeEach(async () => {
+ vi.stubEnv('KEY_VAULTS_SECRET', 'test-secret');
+ publishing.enabled = true;
+ committed.calls = 0;
+ publishing.publish.mockClear();
+ await serverDB.delete(users);
+ await serverDB.insert(users).values([{ id: userId }, { id: 'stranger' }]);
+ const model = new WorkModel(serverDB, userId);
+ for (const [index, key] of ['a', 'b'].entries()) {
+ await model.registerCanvas({
+ canvasId: 'cvs_1',
+ description: 'Up 23%',
+ metadata: metadata(key),
+ title: 'Cost report',
+ toolCallId: `call-${index}`,
+ toolIdentifier: 'lobe-canvas',
+ toolName: 'createCanvas',
+ });
+ }
+});
+
+describe('canvasRouter.getVersion', () => {
+ it('returns the latest version with a signed preview URL for its manifest', async () => {
+ const result = await caller().getVersion({ canvasId: 'cvs_1' });
+
+ expect(result).toMatchObject({
+ canvasId: 'cvs_1',
+ description: 'Up 23%',
+ latestVersion: 2,
+ title: 'Cost report',
+ version: 2,
+ });
+ const token = result!.previewUrl.split('/')[2];
+ expect(verifyCanvasPreviewToken(token)).toMatchObject({
+ manifestKey: metadata('b').manifestKey,
+ userId,
+ });
+ expect(result!.runtimeUrl).toBe('/canvas-runtime/v1/canvas-runtime.js');
+ expect(result!.previewUrl).toBe(`/canvas-preview/${token}/index.html`);
+ });
+
+ it('returns a pinned version', async () => {
+ const result = await caller().getVersion({ canvasId: 'cvs_1', version: 1 });
+
+ expect(result).toMatchObject({ latestVersion: 2, version: 1 });
+ expect(verifyCanvasPreviewToken(result!.previewUrl.split('/')[2])?.manifestKey).toBe(
+ metadata('a').manifestKey,
+ );
+ });
+
+ it('signs a teammate preview with the owner so the owner-scoped manifest resolves', async () => {
+ const workspaceId = 'canvas-router-ws';
+ await serverDB
+ .insert(workspaces)
+ .values({ id: workspaceId, name: 'ws', primaryOwnerId: userId, slug: workspaceId });
+ await serverDB.insert(workspaceMembers).values([
+ { role: 'owner', userId, workspaceId },
+ { role: 'editor', userId: 'stranger', workspaceId },
+ ]);
+ await new WorkModel(serverDB, userId, workspaceId).registerCanvas({
+ canvasId: 'cvs_ws',
+ metadata: metadata('ws'),
+ title: 'Shared',
+ toolCallId: 'call-ws',
+ toolIdentifier: 'lobe-canvas',
+ toolName: 'createCanvas',
+ visibility: 'public',
+ });
+
+ const result = await canvasRouter
+ .createCaller({ serverDB, userId: 'stranger', workspaceId } as any)
+ .getVersion({ canvasId: 'cvs_ws' });
+
+ expect(verifyCanvasPreviewToken(result!.previewUrl.split('/')[2])).toMatchObject({
+ userId,
+ workspaceId,
+ });
+ });
+
+ it('returns null for another user or a missing version', async () => {
+ expect(await caller('stranger').getVersion({ canvasId: 'cvs_1' })).toBeNull();
+ expect(await caller().getVersion({ canvasId: 'cvs_1', version: 9 })).toBeNull();
+ });
+});
+
+describe('canvasRouter.publish', () => {
+ beforeEach(() => {
+ vi.stubEnv('CANVAS_RUNTIME_BASE_URL', 'https://cdn.test/canvas-runtime');
+ });
+
+ afterEach(() => {
+ vi.unstubAllEnvs();
+ });
+
+ it('publishes the current version, then republishes to the same site', async () => {
+ const first = await caller().publish({ canvasId: 'cvs_1' });
+ await caller().publish({ canvasId: 'cvs_1' });
+
+ expect(first).toEqual({ publishedVersion: 2, url: 'https://cost.lobehub.sites' });
+ expect(publishing.publish.mock.calls[0][0]).toMatchObject({
+ canvasId: 'cvs_1',
+ deploymentId: undefined,
+ title: 'Cost report',
+ userId,
+ });
+ expect(publishing.publish.mock.calls[0][0].bundle.html).toContain(
+ 'https://cdn.test/canvas-runtime/v1/canvas-runtime.js',
+ );
+ expect(publishing.publish.mock.calls[1][0].deploymentId).toBe('dep_1');
+ expect(await caller().getVersion({ canvasId: 'cvs_1' })).toMatchObject({
+ canPublish: true,
+ publishedUrl: 'https://cost.lobehub.sites',
+ publishedVersion: 2,
+ });
+ });
+
+ it('refuses when publishing is unavailable or the canvas is not visible', async () => {
+ await expect(caller('stranger').publish({ canvasId: 'cvs_1' })).rejects.toThrow();
+ publishing.enabled = false;
+
+ await expect(caller().publish({ canvasId: 'cvs_1' })).rejects.toThrow();
+ expect(publishing.publish).not.toHaveBeenCalled();
+ expect((await caller().getVersion({ canvasId: 'cvs_1' }))?.canPublish).toBe(false);
+ });
+});
+
+describe('canvasRouter.runAgentTool', () => {
+ it('returns the guide for a browser-run agent loop', async () => {
+ const result = await caller().runAgentTool({ apiName: 'readCanvasGuide', args: {} });
+
+ expect(result.output).toMatchObject({ state: { guideRead: true }, success: true });
+ expect(result.output.content).toContain('lobe-');
+ expect(result.intent).toBeUndefined();
+ });
+
+ it('saves a canvas and hands back the Work intent for the client to register', async () => {
+ const result = await caller().runAgentTool({
+ apiName: 'createCanvas',
+ args: { files: [{ content: '<p>x</p>', path: 'index.html' }], title: 'Cost' },
+ });
+
+ expect(committed.calls).toBe(1);
+ expect(result.output.success).toBe(true);
+ expect(result.intent).toMatchObject({
+ canvas: {
+ metadata: { manifestKey: `canvas/${userId}/cvs_new/manifests/m.json` },
+ title: 'Cost',
+ },
+ type: 'canvas',
+ });
+ });
+
+ it('runs for any account, with no lab to turn on first', async () => {
+ const result = await caller('stranger').runAgentTool({
+ apiName: 'readCanvasGuide',
+ args: {},
+ });
+
+ expect(result.output.success).toBe(true);
+ });
+});
+
+describe('canvasRouter.listVersions', () => {
+ it('lists versions newest first', async () => {
+ const versions = await caller().listVersions({ canvasId: 'cvs_1' });
+
+ expect(versions.map((item) => item.version)).toEqual([2, 1]);
+ });
+});
diff --git a/apps/server/src/routers/lambda/__tests__/work.canvas.test.ts b/apps/server/src/routers/lambda/__tests__/work.canvas.test.ts
new file mode 100644
index 00000000000..85943cc81f8
--- /dev/null
+++ b/apps/server/src/routers/lambda/__tests__/work.canvas.test.ts
@@ -0,0 +1,147 @@
+// @vitest-environment node
+import { getTestDB } from '@lobechat/database/test-utils';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { WorkModel } from '@/database/models/work';
+import { users, workspaces } from '@/database/schemas';
+import { createCanvasStorageService } from '@/server/services/canvas';
+
+import { workRouter } from '../work';
+
+const serverDB = await getTestDB();
+const objects = vi.hoisted(() => new Map<string, Uint8Array>());
+
+vi.mock('@/server/services/file', () => ({
+ FileService: class {
+ async deleteFiles(keys: string[]) {
+ for (const key of keys) objects.delete(key);
+ }
+
+ async getFileByteArray(key: string) {
+ const bytes = objects.get(key);
+ if (!bytes) throw new Error(`Missing ${key}`);
+ return bytes;
+ }
+
+ async uploadBuffer(key: string, bytes: Uint8Array) {
+ objects.set(key, bytes);
+ }
+ },
+}));
+
+vi.mock('@/business/server/trpc-middlewares/workspaceAuth', async () => {
+ const { trpc } = await import('@/libs/trpc/lambda/init');
+ return { wsCompatProcedure: trpc.procedure };
+});
+
+vi.mock('@/business/server/trpc-middlewares/rbacPermission', async () => {
+ const { trpc } = await import('@/libs/trpc/lambda/init');
+ return { withScopedPermission: () => trpc.middleware((opts) => opts.next()) };
+});
+
+vi.mock('@/libs/trpc/lambda/middleware', () => ({
+ serverDatabase: async (opts: { next: (input: unknown) => unknown }) =>
+ opts.next({ ctx: { serverDB } }),
+}));
+
+const userId = 'work-canvas-cleanup-user';
+const caller = (id = userId, workspaceId?: string) =>
+ workRouter.createCaller({ serverDB, userId: id, workspaceId });
+
+beforeEach(async () => {
+ objects.clear();
+ await serverDB.delete(users);
+ await serverDB.insert(users).values([{ id: userId }, { id: 'work-canvas-stranger' }]);
+});
+
+const createCanvas = async () => {
+ const storage = createCanvasStorageService(serverDB, userId);
+ const model = new WorkModel(serverDB, userId);
+ let workId = '';
+ for (const content of ['first', 'second']) {
+ const result = await storage.commit('cvs_cleanup', [
+ { content: `<html><body>${content}</body></html>`, path: 'index.html' },
+ ]);
+ if (!result.ok) throw new Error('commit failed');
+ const work = await model.registerCanvas({
+ canvasId: 'cvs_cleanup',
+ metadata: result.metadata,
+ title: 'Cleanup',
+ toolCallId: `cleanup-${content}`,
+ toolIdentifier: 'lobe-canvas',
+ toolName: 'createCanvas',
+ });
+ workId = work.id;
+ }
+ return { model, workId };
+};
+
+describe('workRouter.deleteWork · Canvas storage', () => {
+ it('removes all manifests after the Work and its versions are deleted', async () => {
+ const { model, workId } = await createCanvas();
+ expect([...objects.keys()].filter((key) => key.includes('/manifests/'))).toHaveLength(2);
+
+ await caller().deleteWork({ id: workId });
+
+ expect(await model.findCanvas('cvs_cleanup')).toBeNull();
+ expect(await model.listVersions(workId)).toEqual([]);
+ expect(objects.size).toBe(0);
+ });
+
+ it('preserves another user’s Canvas and stored objects', async () => {
+ const { model, workId } = await createCanvas();
+ const keys = [...objects.keys()].sort();
+
+ await caller('work-canvas-stranger').deleteWork({ id: workId });
+
+ expect(await model.findCanvas('cvs_cleanup')).not.toBeNull();
+ expect([...objects.keys()].sort()).toEqual(keys);
+ });
+
+ it.each([
+ [undefined, 'canvas-cleanup-ws-a'],
+ ['canvas-cleanup-ws-a', undefined],
+ ['canvas-cleanup-ws-a', 'canvas-cleanup-ws-b'],
+ ])(
+ 'preserves a manifest shared between %s and %s until both works are deleted',
+ async (from, to) => {
+ await serverDB.insert(workspaces).values(
+ ['canvas-cleanup-ws-a', 'canvas-cleanup-ws-b'].map((id) => ({
+ id,
+ name: id,
+ primaryOwnerId: userId,
+ slug: id,
+ })),
+ );
+ const registrations = [];
+ for (const workspaceId of [from, to]) {
+ const storage = createCanvasStorageService(serverDB, userId, workspaceId);
+ const result = await storage.commit('cvs_shared', [
+ { content: '<html><body>Shared Canvas</body></html>', path: 'index.html' },
+ ]);
+ if (!result.ok) throw new Error('commit failed');
+ const work = await new WorkModel(serverDB, userId, workspaceId).registerCanvas({
+ canvasId: 'cvs_shared',
+ metadata: result.metadata,
+ title: 'Shared Canvas',
+ toolCallId: `shared-${workspaceId ?? 'personal'}`,
+ toolIdentifier: 'lobe-canvas',
+ toolName: 'createCanvas',
+ });
+ registrations.push({ manifestKey: result.metadata.manifestKey, storage, work });
+ }
+ const [first, second] = registrations;
+ expect(first.manifestKey).toBe(second.manifestKey);
+
+ await caller(userId, from).deleteWork({ id: first.work.id });
+
+ const manifest = await second.storage.readManifest(second.manifestKey);
+ const file = await second.storage.readFile(manifest, 'index.html');
+ expect(new TextDecoder().decode(file?.bytes)).toContain('Shared Canvas');
+
+ await caller(userId, to).deleteWork({ id: second.work.id });
+
+ expect(objects.size).toBe(0);
+ },
+ );
+});
diff --git a/apps/server/src/routers/lambda/canvas.ts b/apps/server/src/routers/lambda/canvas.ts
new file mode 100644
index 00000000000..8fa029e811d
--- /dev/null
+++ b/apps/server/src/routers/lambda/canvas.ts
@@ -0,0 +1,195 @@
+import { CanvasApiName } from '@lobechat/builtin-tool-canvas';
+import type { BuiltinServerRuntimeOutput, WorkRegistrationIntent } from '@lobechat/types';
+import { TRPCError } from '@trpc/server';
+import { z } from 'zod';
+
+import { isCanvasPublishEnabled, publishCanvasSite } from '@/business/server/canvasPublish';
+import {
+ requireWorkspaceRoleWhenScoped,
+ wsCompatProcedure,
+} from '@/business/server/trpc-middlewares/workspaceAuth';
+import { WorkModel } from '@/database/models/work';
+import { appEnv } from '@/envs/app';
+import { router } from '@/libs/trpc/lambda';
+import { serverDatabase } from '@/libs/trpc/lambda/middleware';
+import { createCanvasStorageService } from '@/server/services/canvas';
+import { createCanvasAgentRuntime } from '@/server/services/canvas/agentRuntime';
+import {
+ buildCanvasPublishBundle,
+ resolveCanvasPublicRuntimeUrl,
+} from '@/server/services/canvas/publish';
+import {
+ buildCanvasPreviewUrl,
+ resolveCanvasRuntimeUrl,
+} from '@/server/services/canvas/runtimeUrl';
+import { signCanvasPreviewToken } from '@/server/services/canvas/serve';
+
+const canvasProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {
+ const { ctx } = opts;
+ const workspaceId = ctx.workspaceId ?? undefined;
+
+ return opts.next({
+ ctx: { workModel: new WorkModel(ctx.serverDB, ctx.userId, workspaceId), workspaceId },
+ });
+});
+
+export const canvasRouter = router({
+ getVersion: canvasProcedure
+ .input(z.object({ canvasId: z.string(), version: z.number().int().positive().optional() }))
+ .query(async ({ ctx, input }) => {
+ const current = await ctx.workModel.findCanvas(input.canvasId);
+ if (!current) return null;
+
+ const version =
+ input.version && input.version !== current.version.version
+ ? await ctx.workModel.findCanvasVersion(current.work.id, input.version)
+ : current.version;
+ const canvas = version?.metadata?.canvas;
+ if (!version || !canvas) return null;
+
+ const token = signCanvasPreviewToken({
+ manifestKey: canvas.manifestKey,
+ userId: current.work.userId,
+ workspaceId: ctx.workspaceId,
+ });
+
+ return {
+ canPublish: isCanvasPublishEnabled() && current.work.userId === ctx.userId,
+ canvasId: input.canvasId,
+ createdAt: version.createdAt,
+ description: version.description ?? current.work.description,
+ latestVersion: current.version.version,
+ metadata: canvas,
+ previewUrl: buildCanvasPreviewUrl(token, canvas.entry),
+ publishedUrl: current.work.url,
+ publishedVersion: current.work.metadata?.canvasPublish?.publishedVersion ?? null,
+ runtimeUrl: resolveCanvasRuntimeUrl(canvas.runtimeMajor),
+ title: version.title ?? current.work.title,
+ version: version.version,
+ workId: current.work.id,
+ };
+ }),
+
+ publish: canvasProcedure
+ .use(requireWorkspaceRoleWhenScoped('member'))
+ .input(z.object({ canvasId: z.string() }))
+ .mutation(async ({ ctx, input }) => {
+ if (!isCanvasPublishEnabled()) {
+ throw new TRPCError({
+ code: 'NOT_IMPLEMENTED',
+ message: 'Canvas publishing is unavailable',
+ });
+ }
+
+ const current = await ctx.workModel.findCanvas(input.canvasId);
+ const canvas = current?.version.metadata?.canvas;
+ if (!current || !canvas) throw new TRPCError({ code: 'NOT_FOUND' });
+ if (current.work.userId !== ctx.userId) throw new TRPCError({ code: 'FORBIDDEN' });
+
+ const runtimeUrl = resolveCanvasPublicRuntimeUrl(canvas.runtimeMajor, {
+ appUrl: appEnv.APP_URL,
+ baseUrl: process.env.CANVAS_RUNTIME_BASE_URL,
+ });
+ if (!runtimeUrl) {
+ throw new TRPCError({
+ code: 'PRECONDITION_FAILED',
+ message: 'Publishing needs APP_URL or an absolute CANVAS_RUNTIME_BASE_URL',
+ });
+ }
+
+ const storage = createCanvasStorageService(ctx.serverDB, ctx.userId, ctx.workspaceId);
+ const bundle = await buildCanvasPublishBundle(
+ storage,
+ await storage.readManifest(canvas.manifestKey),
+ runtimeUrl,
+ );
+ const site = await publishCanvasSite({
+ bundle,
+ canvasId: input.canvasId,
+ db: ctx.serverDB,
+ deploymentId: current.work.metadata?.canvasPublish?.deploymentId,
+ title: current.work.title ?? input.canvasId,
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ });
+ await ctx.workModel.recordCanvasPublish(input.canvasId, {
+ deploymentId: site.deploymentId,
+ publishedVersion: current.version.version,
+ url: site.url,
+ });
+
+ return { publishedVersion: current.version.version, url: site.url };
+ }),
+
+ runAgentTool: canvasProcedure
+ .use(requireWorkspaceRoleWhenScoped('member'))
+ .input(
+ z.object({
+ apiName: z.enum(Object.values(CanvasApiName) as [string, ...string[]]),
+ args: z.record(z.string(), z.unknown()),
+ context: z
+ .object({
+ agentId: z.string().nullish(),
+ messageId: z.string().nullish(),
+ threadId: z.string().nullish(),
+ topicId: z.string().nullish(),
+ })
+ .optional(),
+ }),
+ )
+ .mutation(async ({ ctx, input }) => {
+ const context = input.context ?? {};
+ const runtime = createCanvasAgentRuntime(ctx.serverDB, {
+ agentId: context.agentId,
+ threadId: context.threadId,
+ topicId: context.topicId,
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId,
+ });
+
+ let intent: WorkRegistrationIntent | undefined;
+ const onWorkRegistration = (next: WorkRegistrationIntent) => {
+ intent = next;
+ };
+ const args = input.args as any;
+ let output: BuiltinServerRuntimeOutput;
+ switch (input.apiName) {
+ case CanvasApiName.createCanvas: {
+ output = await runtime.createCanvas(args, { onWorkRegistration });
+ break;
+ }
+ case CanvasApiName.updateCanvas: {
+ output = await runtime.updateCanvas(args, { onWorkRegistration });
+ break;
+ }
+ case CanvasApiName.readCanvas: {
+ output = await runtime.readCanvas(args);
+ break;
+ }
+ case CanvasApiName.listCanvases: {
+ output = await runtime.listCanvases();
+ break;
+ }
+ default: {
+ output = await runtime.readCanvasGuide();
+ }
+ }
+
+ return { intent, output };
+ }),
+
+ listVersions: canvasProcedure
+ .input(z.object({ canvasId: z.string() }))
+ .query(async ({ ctx, input }) => {
+ const current = await ctx.workModel.findCanvas(input.canvasId);
+ if (!current) return [];
+
+ const versions = await ctx.workModel.listVersions(current.work.id);
+ return versions.map((item) => ({
+ createdAt: item.createdAt,
+ description: item.description,
+ title: item.title,
+ version: item.version,
+ }));
+ }),
+});
diff --git a/apps/server/src/routers/lambda/index.ts b/apps/server/src/routers/lambda/index.ts
index 09f7276f5b9..66377756e92 100644
--- a/apps/server/src/routers/lambda/index.ts
+++ b/apps/server/src/routers/lambda/index.ts
@@ -45,6 +45,7 @@ import { apiKeyRouter } from './apiKey';
import { asrRouter } from './asr';
import { botMessageRouter } from './botMessage';
import { briefRouter } from './brief';
+import { canvasRouter } from './canvas';
import { changelogRouter } from './changelog';
import { chunkRouter } from './chunk';
import { comfyuiRouter } from './comfyui';
@@ -132,6 +133,7 @@ export const lambdaRouter = router({
expertise: expertiseRouter,
agentSignal: agentSignalRouter,
agentSteerQueue: agentSteerQueueRouter,
+ canvas: canvasRouter,
changelog: changelogRouter,
brief: briefRouter,
aiAgent: aiAgentRouter,
diff --git a/apps/server/src/routers/lambda/work.ts b/apps/server/src/routers/lambda/work.ts
index 3d0673d1f36..60b140d1f01 100644
--- a/apps/server/src/routers/lambda/work.ts
+++ b/apps/server/src/routers/lambda/work.ts
@@ -1,10 +1,12 @@
import {
+ type RegisterCanvasWorkParams,
type RegisterDocumentWorkParams,
type RegisterSkillToolResultWorkParams,
type RegisterTaskWorkParams,
WORK_SKILL_PROVIDERS,
type WorkVersionCumulativeUsage,
} from '@lobechat/types';
+import { TRPCError } from '@trpc/server';
import { z } from 'zod';
import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPermission';
@@ -13,6 +15,7 @@ import { MessageModel } from '@/database/models/message';
import { WorkModel } from '@/database/models/work';
import { router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
+import { createCanvasStorageService, isOwnCanvasManifestKey } from '@/server/services/canvas';
import { registerShellWorksForLocalRun } from '@/server/services/workRegistration';
const workProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {
@@ -88,6 +91,29 @@ const registerSkillToolResultSchema = z.object({
topicId: z.string().nullable().optional(),
}) satisfies z.ZodType<RegisterSkillToolResultWorkParams>;
+const registerCanvasSchema = z.object({
+ agentId: z.string().nullable().optional(),
+ canvasId: z.string().min(1),
+ cumulativeCost: z.number().nullable().optional(),
+ cumulativeUsage: cumulativeUsageSchema.nullable().optional(),
+ description: z.string().nullable().optional(),
+ messageId: z.string().nullable().optional(),
+ metadata: z.object({
+ entry: z.string().min(1),
+ fileCount: z.number().int().nonnegative(),
+ manifestKey: z.string().min(1),
+ runtimeMajor: z.number().int().positive(),
+ totalSize: z.number().int().nonnegative(),
+ }),
+ rootOperationId: z.string().nullable().optional(),
+ threadId: z.string().nullable().optional(),
+ title: z.string().min(1),
+ toolCallId: z.string().nullable().optional(),
+ toolIdentifier: z.string().min(1),
+ toolName: z.string().min(1),
+ topicId: z.string().nullable().optional(),
+}) satisfies z.ZodType<RegisterCanvasWorkParams>;
+
const registerDocumentSchema = z.object({
agentDocumentId: z.string().nullable().optional(),
agentId: z.string().nullable().optional(),
@@ -128,7 +154,7 @@ export const workRouter = router({
limit: z.number().min(1).max(100).default(30),
originAgentId: z.string().nullable().optional(),
provider: z.enum(WORK_SKILL_PROVIDERS).optional(),
- type: z.enum(['task', 'document', 'external', 'file']).nullable().optional(),
+ type: z.enum(['task', 'document', 'external', 'file', 'canvas']).nullable().optional(),
visibility: z.enum(['private', 'public']).optional(),
}),
)
@@ -181,12 +207,36 @@ export const workRouter = router({
// task / document is already gone, so a live Work cannot be removed here.
deleteWork: skillWorkProcedureWrite
.input(z.object({ id: z.string().min(1) }))
- .mutation(async ({ ctx, input }) => ctx.workModel.deleteWork(input)),
+ .mutation(async ({ ctx, input }) => {
+ const removed = await ctx.workModel.deleteWork(input);
+ const canvases = removed.flatMap((row) =>
+ row.resourceType === 'canvas' && row.resourceId
+ ? [{ id: row.resourceId, manifestKeys: row.canvasManifestKeys }]
+ : [],
+ );
+ if (canvases.length === 0) return;
+
+ const storage = createCanvasStorageService(
+ ctx.serverDB,
+ ctx.userId,
+ ctx.workspaceId ?? undefined,
+ );
+ for (const canvas of canvases) await storage.removeCanvas(canvas.id, canvas.manifestKeys);
+ }),
registerTask: taskWorkProcedureWrite
.input(registerTaskSchema)
.mutation(async ({ ctx, input }) => ctx.workModel.registerTask(input)),
+ registerCanvas: skillWorkProcedureWrite
+ .input(registerCanvasSchema)
+ .mutation(async ({ ctx, input }) => {
+ if (!isOwnCanvasManifestKey(ctx.userId, input.metadata.manifestKey)) {
+ throw new TRPCError({ code: 'FORBIDDEN', message: 'Canvas manifest is not yours' });
+ }
+ return ctx.workModel.registerCanvas(input);
+ }),
+
registerDocument: documentWorkProcedureWrite
.input(registerDocumentSchema)
.mutation(async ({ ctx, input }) => ctx.workModel.registerDocument(input)),
diff --git a/apps/server/src/services/canvas/__tests__/agentRuntime.test.ts b/apps/server/src/services/canvas/__tests__/agentRuntime.test.ts
new file mode 100644
index 00000000000..c38b8b8dc80
--- /dev/null
+++ b/apps/server/src/services/canvas/__tests__/agentRuntime.test.ts
@@ -0,0 +1,70 @@
+// @vitest-environment node
+import { createMediaFileRef } from '@lobechat/const/mediaRef';
+import { getTestDB } from '@lobechat/database/test-utils';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { agents, files, messages, messagesFiles, topics, users } from '@/database/schemas';
+
+import { createCanvasFileRefResolverFor } from '../agentRuntime';
+
+const { getFileByteArray } = vi.hoisted(() => ({ getFileByteArray: vi.fn() }));
+
+vi.mock('@/server/services/file', () => ({
+ FileService: class {
+ getFileByteArray = getFileByteArray;
+ },
+}));
+
+const serverDB = await getTestDB();
+const userId = 'canvas-ref-user';
+const otherUserId = 'canvas-ref-other';
+const agentId = 'canvas-ref-agent';
+const topicId = 'canvas-ref-topic';
+const messageId = 'canvas-ref-message';
+const png = new Uint8Array([137, 80, 78, 71]);
+
+const fileRow = (id: string, owner: string) => ({
+ fileType: 'image/png',
+ id,
+ name: `${id}.png`,
+ size: png.byteLength,
+ url: `files/${owner}/${id}.png`,
+ userId: owner,
+});
+
+beforeEach(async () => {
+ getFileByteArray.mockReset().mockResolvedValue(png);
+ await serverDB.delete(users);
+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);
+ await serverDB.insert(agents).values({ id: agentId, userId });
+ await serverDB.insert(topics).values({ agentId, id: topicId, userId });
+ await serverDB
+ .insert(files)
+ .values([fileRow('file_photo', userId), fileRow('file_foreign', otherUserId)]);
+ await serverDB
+ .insert(messages)
+ .values({ agentId, content: 'use this', id: messageId, role: 'user', topicId, userId });
+ await serverDB.insert(messagesFiles).values({ fileId: 'file_photo', messageId, userId });
+});
+
+describe('createCanvasFileRefResolverFor', () => {
+ it('resolves an image attached in the topic by its media ref', async () => {
+ const resolve = createCanvasFileRefResolverFor(serverDB, { agentId, topicId, userId });
+ const ref = createMediaFileRef({ index: 0, messageId, type: 'image' });
+
+ const result = await resolve([{ fileRef: ref, path: 'img/photo.png' }]);
+
+ expect(result.issues).toEqual([]);
+ expect(result.contents.get(ref)).toBe(png);
+ expect(getFileByteArray).toHaveBeenCalledWith(`files/${userId}/file_photo.png`);
+ });
+
+ it("does not read another user's file", async () => {
+ const resolve = createCanvasFileRefResolverFor(serverDB, { agentId, topicId, userId });
+
+ const result = await resolve([{ fileRef: 'file_foreign', path: 'img/x.png' }]);
+
+ expect(result.issues.map((issue) => issue.rule)).toEqual(['unresolved-file-ref']);
+ expect(getFileByteArray).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/services/canvas/__tests__/fileRefs.test.ts b/apps/server/src/services/canvas/__tests__/fileRefs.test.ts
new file mode 100644
index 00000000000..595d74216df
--- /dev/null
+++ b/apps/server/src/services/canvas/__tests__/fileRefs.test.ts
@@ -0,0 +1,123 @@
+import { CANVAS_LIMITS } from '@lobechat/canvas';
+import { describe, expect, it, vi } from 'vitest';
+
+import { type CanvasRefFile, createCanvasFileRefResolver } from '../fileRefs';
+
+const png = new Uint8Array([137, 80, 78, 71]);
+
+const fileOf = (overrides: Partial<CanvasRefFile> = {}): CanvasRefFile => ({
+ fileType: 'image/png',
+ id: 'file_logo',
+ name: 'logo.png',
+ size: png.byteLength,
+ url: 'files/user/logo.png',
+ ...overrides,
+});
+
+const setup = (
+ files: CanvasRefFile[] = [fileOf()],
+ mediaRefs: Record<string, string | undefined> = {},
+) => {
+ const readBytes = vi.fn(async (key: string) => {
+ if (key.endsWith('.csv')) return new TextEncoder().encode('a,b\n1,2');
+ if (key.endsWith('.bin')) return new Uint8Array([0xff, 0xfe, 0x00]);
+ return png;
+ });
+ const listMediaFileIds = vi.fn(async () => new Map(Object.entries(mediaRefs)));
+ const resolver = createCanvasFileRefResolver({
+ findFile: async (id) => files.find((file) => file.id === id),
+ listMediaFileIds,
+ readBytes,
+ });
+ return { listMediaFileIds, readBytes, resolver };
+};
+
+describe('createCanvasFileRefResolver', () => {
+ it('copies an owned file by id', async () => {
+ const { resolver } = setup();
+
+ const result = await resolver([{ fileRef: 'file_logo', path: 'img/logo.png' }]);
+
+ expect(result.issues).toEqual([]);
+ expect(result.contents.get('file_logo')).toBe(png);
+ });
+
+ it('resolves an image ref from the conversation to its file', async () => {
+ const { resolver } = setup([fileOf()], { 'msg_a1b2c3.image_1': 'file_logo' });
+
+ const result = await resolver([{ fileRef: 'msg_a1b2c3.image_1', path: 'img/photo.png' }]);
+
+ expect(result.issues).toEqual([]);
+ expect(result.contents.get('msg_a1b2c3.image_1')).toBe(png);
+ });
+
+ it('only looks up conversation media when a media ref is used', async () => {
+ const { listMediaFileIds, resolver } = setup();
+
+ await resolver([{ fileRef: 'file_logo', path: 'img/logo.png' }]);
+
+ expect(listMediaFileIds).not.toHaveBeenCalled();
+ });
+
+ it('decodes a file written to a text path', async () => {
+ const { resolver } = setup([fileOf({ fileType: 'text/csv', id: 'file_csv', url: 'k.csv' })]);
+
+ const result = await resolver([{ fileRef: 'file_csv', path: 'data/table.csv' }]);
+
+ expect(result.contents.get('file_csv')).toBe('a,b\n1,2');
+ });
+
+ it('reports refs that match no accessible file', async () => {
+ const { readBytes, resolver } = setup([], { 'msg_a1b2c3.image_1': undefined });
+
+ const result = await resolver([
+ { fileRef: 'file_other_user', path: 'a.png' },
+ { fileRef: 'msg_a1b2c3.image_1', path: 'b.png' },
+ { fileRef: 'msg_zzzzzz.image_9', path: 'c.png' },
+ ]);
+
+ expect(result.issues.map((issue) => [issue.file, issue.rule])).toEqual([
+ ['a.png', 'unresolved-file-ref'],
+ ['b.png', 'unresolved-file-ref'],
+ ['c.png', 'unresolved-file-ref'],
+ ]);
+ expect(readBytes).not.toHaveBeenCalled();
+ });
+
+ it('refuses a file whose kind does not match the target path', async () => {
+ const { readBytes, resolver } = setup([
+ fileOf(),
+ fileOf({ fileType: 'application/pdf', id: 'file_pdf' }),
+ ]);
+
+ const imageAsPdf = await resolver([{ fileRef: 'file_logo', path: 'fonts/brand.woff2' }]);
+ const unknownKind = await resolver([{ fileRef: 'file_pdf', path: 'img/scan.png' }]);
+
+ expect(imageAsPdf.issues.map((issue) => issue.rule)).toEqual(['file-type-mismatch']);
+ expect(unknownKind.issues).toEqual([]);
+ expect(readBytes).toHaveBeenCalledTimes(1);
+ });
+
+ it('refuses non-UTF-8 bytes on a text path', async () => {
+ const { resolver } = setup([fileOf({ fileType: '', id: 'file_bin', url: 'k.bin' })]);
+
+ const result = await resolver([{ fileRef: 'file_bin', path: 'data/table.csv' }]);
+
+ expect(result.issues.map((issue) => issue.rule)).toEqual(['file-type-mismatch']);
+ });
+
+ it('refuses an oversized file before downloading it', async () => {
+ const { readBytes, resolver } = setup([
+ fileOf({ size: CANVAS_LIMITS.maxFileBytes + 1 }),
+ fileOf({ fileType: 'text/csv', id: 'file_csv', size: CANVAS_LIMITS.maxTextFileBytes + 1 }),
+ ]);
+
+ const result = await resolver([
+ { fileRef: 'file_logo', path: 'img/logo.png' },
+ { fileRef: 'file_csv', path: 'data/table.csv' },
+ ]);
+
+ expect(result.issues.map((issue) => issue.rule)).toEqual(['file-too-large', 'file-too-large']);
+ expect(readBytes).not.toHaveBeenCalled();
+ });
+});
diff --git a/apps/server/src/services/canvas/__tests__/publish.test.ts b/apps/server/src/services/canvas/__tests__/publish.test.ts
new file mode 100644
index 00000000000..069d12a3612
--- /dev/null
+++ b/apps/server/src/services/canvas/__tests__/publish.test.ts
@@ -0,0 +1,69 @@
+// @vitest-environment node
+import { describe, expect, it, vi } from 'vitest';
+
+import { buildCanvasPublishBundle, resolveCanvasPublicRuntimeUrl } from '../publish';
+import type { CanvasStorageService } from '../storage';
+
+const manifest = {
+ entry: 'index.html',
+ files: {
+ 'about/index.html': { contentType: 'text/html; charset=utf-8', hash: 'h3', size: 20 },
+ 'index.html': { contentType: 'text/html; charset=utf-8', hash: 'h1', size: 40 },
+ 'logo.png': { contentType: 'image/png', hash: 'h4', size: 3 },
+ 'styles.css': { contentType: 'text/css; charset=utf-8', hash: 'h2', size: 10 },
+ },
+ runtimeMajor: 1,
+ schemaVersion: 1 as const,
+};
+
+const contents: Record<string, Uint8Array> = {
+ 'about/index.html': new TextEncoder().encode('<p>about</p>'),
+ 'index.html': new TextEncoder().encode('<html><head></head><body>hi</body></html>'),
+ 'logo.png': new Uint8Array([1, 2, 3]),
+ 'styles.css': new TextEncoder().encode('body{}'),
+};
+
+const storage = {
+ readFile: vi.fn(async (_manifest: unknown, path: string) => ({
+ bytes: contents[path],
+ contentType: manifest.files[path as keyof typeof manifest.files].contentType,
+ })),
+} as unknown as CanvasStorageService;
+
+describe('buildCanvasPublishBundle', () => {
+ it('injects the public runtime into every page and ships the rest as hosted files', async () => {
+ const bundle = await buildCanvasPublishBundle(storage, manifest, 'https://cdn.test/v1/r.js');
+
+ expect(bundle.html).toContain('<script defer src="https://cdn.test/v1/r.js"></script>');
+ expect(bundle.html).not.toContain('data-lobe-canvas-bridge');
+ expect(bundle.files.map((file) => file.path)).toEqual([
+ '/about/index.html',
+ '/logo.png',
+ '/styles.css',
+ ]);
+ expect(bundle.files[0]).toMatchObject({ encoding: 'utf8' });
+ expect(bundle.files[0].content).toContain('https://cdn.test/v1/r.js');
+ expect(bundle.files[1]).toEqual({
+ content: Buffer.from([1, 2, 3]).toString('base64'),
+ contentType: 'image/png',
+ encoding: 'base64',
+ path: '/logo.png',
+ });
+ expect(bundle.files[2]).toMatchObject({ content: 'body{}', encoding: 'utf8' });
+ });
+});
+
+describe('resolveCanvasPublicRuntimeUrl', () => {
+ it('needs an absolute runtime URL because published sites live on another origin', () => {
+ expect(resolveCanvasPublicRuntimeUrl(1, { appUrl: 'https://app.test/' })).toBe(
+ 'https://app.test/canvas-runtime/v1/canvas-runtime.js',
+ );
+ expect(
+ resolveCanvasPublicRuntimeUrl(1, {
+ appUrl: 'https://app.test',
+ baseUrl: 'https://cdn.test/rt/',
+ }),
+ ).toBe('https://cdn.test/rt/v1/canvas-runtime.js');
+ expect(resolveCanvasPublicRuntimeUrl(1, {})).toBeUndefined();
+ });
+});
diff --git a/apps/server/src/services/canvas/__tests__/serve.test.ts b/apps/server/src/services/canvas/__tests__/serve.test.ts
new file mode 100644
index 00000000000..1a8ba6c402b
--- /dev/null
+++ b/apps/server/src/services/canvas/__tests__/serve.test.ts
@@ -0,0 +1,190 @@
+// @vitest-environment node
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import {
+ CANVAS_PREVIEW_TTL_BUCKET_SECONDS,
+ CANVAS_PREVIEW_TTL_SECONDS,
+ injectCanvasRuntime,
+ serveCanvasFile,
+ signCanvasPreviewToken,
+ verifyCanvasPreviewToken,
+} from '../serve';
+import type { CanvasStorageService } from '../storage';
+
+const manifest = {
+ entry: 'index.html',
+ files: {
+ 'data.json': { contentType: 'application/json; charset=utf-8', hash: 'h2', size: 5 },
+ 'index.html': { contentType: 'text/html; charset=utf-8', hash: 'h1', size: 40 },
+ },
+ runtimeMajor: 1,
+ schemaVersion: 1 as const,
+};
+
+const storageFor = (files: Record<string, string>) =>
+ ({
+ readFile: vi.fn(async (_manifest: unknown, path: string) =>
+ path in files
+ ? {
+ bytes: new TextEncoder().encode(files[path]),
+ contentType: manifest.files[path as keyof typeof manifest.files].contentType,
+ }
+ : undefined,
+ ),
+ readManifest: vi.fn(async () => manifest),
+ }) as unknown as CanvasStorageService;
+
+beforeEach(() => {
+ vi.stubEnv('KEY_VAULTS_SECRET', 'test-secret');
+});
+
+afterEach(() => {
+ vi.unstubAllEnvs();
+ vi.useRealTimers();
+});
+
+describe('canvas preview tokens', () => {
+ it('round-trips a signed token', () => {
+ const token = signCanvasPreviewToken({
+ manifestKey: 'canvas/u/c/manifests/a.json',
+ userId: 'u',
+ });
+
+ expect(verifyCanvasPreviewToken(token)).toMatchObject({
+ manifestKey: 'canvas/u/c/manifests/a.json',
+ userId: 'u',
+ });
+ });
+
+ it('rejects a tampered or expired token', () => {
+ const token = signCanvasPreviewToken({ manifestKey: 'k', userId: 'u' });
+ const [body, signature] = token.split('.');
+ const forged = `${Buffer.from(JSON.stringify({ e: 9_999_999_999, k: 'k', u: 'other' })).toString('base64url')}.${signature}`;
+
+ expect(verifyCanvasPreviewToken(forged)).toBeUndefined();
+ expect(verifyCanvasPreviewToken(`${body}.`)).toBeUndefined();
+
+ vi.useFakeTimers();
+ vi.setSystemTime(
+ Date.now() + (CANVAS_PREVIEW_TTL_SECONDS + CANVAS_PREVIEW_TTL_BUCKET_SECONDS + 5) * 1000,
+ );
+ expect(verifyCanvasPreviewToken(token)).toBeUndefined();
+ });
+
+ it('keeps the token stable within a time bucket so the preview frame does not reload', () => {
+ vi.useFakeTimers();
+ vi.setSystemTime(new Date('2026-10-20T10:00:00Z'));
+ const first = signCanvasPreviewToken({ manifestKey: 'k', userId: 'u' });
+ vi.setSystemTime(new Date('2026-10-20T10:04:00Z'));
+
+ expect(signCanvasPreviewToken({ manifestKey: 'k', userId: 'u' })).toBe(first);
+ });
+});
+
+describe('injectCanvasRuntime', () => {
+ it('adds the publication runtime right after <head>', () => {
+ const html = injectCanvasRuntime(
+ '<!doctype html><html><head><title>x</title></head><body></body></html>',
+ {
+ runtimeUrl: '/canvas-runtime/v1/canvas-runtime.js',
+ },
+ );
+
+ expect(html).toContain('<head><script defer');
+ expect(html).toContain('<script defer src="/canvas-runtime/v1/canvas-runtime.js"></script>');
+ expect(html.indexOf('canvas-runtime.js')).toBeLessThan(html.indexOf('<title>'));
+ });
+
+ it('wraps a fragment that has no <head>', () => {
+ const html = injectCanvasRuntime('<lobe-tag>x</lobe-tag>', { runtimeUrl: '/r.js' });
+
+ expect(html.startsWith('<!doctype html>')).toBe(true);
+ expect(html).toContain('<lobe-tag>x</lobe-tag>');
+ expect(html).toContain('<script defer src="/r.js"></script>');
+ });
+});
+
+describe('serveCanvasFile', () => {
+ const token = () =>
+ signCanvasPreviewToken({ manifestKey: 'canvas/u/c/manifests/a.json', userId: 'u' });
+
+ it('serves the entry page with the runtime injected and a locked-down CSP', async () => {
+ const storage = storageFor({ 'index.html': '<html><head></head><body>hi</body></html>' });
+
+ const response = await serveCanvasFile({
+ createStorage: () => storage,
+ path: '',
+ runtimeUrl: '/canvas-runtime/v1/canvas-runtime.js',
+ token: token(),
+ });
+
+ expect(response.status).toBe(200);
+ expect(response.headers.get('content-type')).toContain('text/html');
+ expect(response.headers.get('content-security-policy')).toContain("connect-src 'self'");
+ expect(response.headers.get('content-security-policy')).toContain("default-src 'none'");
+ const html = await response.text();
+ expect(html).toContain('data-lobe-canvas-bridge');
+ expect(html).not.toContain('<script defer src=');
+ expect(response.headers.get('content-security-policy')).toContain(
+ "script-src 'self' 'unsafe-inline' blob:",
+ );
+ });
+
+ it('sandboxes every response into an opaque origin even when opened top-level', async () => {
+ const response = await serveCanvasFile({
+ createStorage: () => storageFor({ 'data.json': '[1,2]' }),
+ path: 'data.json',
+ runtimeUrl: '/r.js',
+ token: token(),
+ });
+ const csp = response.headers.get('content-security-policy')!;
+
+ expect(csp).toMatch(
+ /(^|; )sandbox allow-scripts allow-popups allow-forms allow-downloads(;|$)/,
+ );
+ expect(csp).not.toContain('allow-same-origin');
+ });
+
+ it('serves project files as-is and allows the opaque sandbox origin to read them', async () => {
+ const response = await serveCanvasFile({
+ createStorage: () => storageFor({ 'data.json': '[1,2]' }),
+ path: 'data.json',
+ runtimeUrl: '/r.js',
+ token: token(),
+ });
+
+ expect(await response.text()).toBe('[1,2]');
+ expect(response.headers.get('access-control-allow-origin')).toBe('*');
+ });
+
+ it('answers 403 for a bad token and 404 for a missing file', async () => {
+ const createStorage = () => storageFor({});
+
+ expect(
+ (await serveCanvasFile({ createStorage, path: '', runtimeUrl: '/r.js', token: 'nope' }))
+ .status,
+ ).toBe(403);
+ expect(
+ (
+ await serveCanvasFile({
+ createStorage,
+ path: 'missing.css',
+ runtimeUrl: '/r.js',
+ token: token(),
+ })
+ ).status,
+ ).toBe(404);
+ });
+
+ it('answers 404 instead of the entry page for a path that escapes the project', async () => {
+ const response = await serveCanvasFile({
+ createStorage: () =>
+ storageFor({ 'index.html': '<html><head></head><body>hi</body></html>' }),
+ path: '../../package.json',
+ runtimeUrl: '/r.js',
+ token: token(),
+ });
+
+ expect(response.status).toBe(404);
+ });
+});
diff --git a/apps/server/src/services/canvas/__tests__/storage.test.ts b/apps/server/src/services/canvas/__tests__/storage.test.ts
new file mode 100644
index 00000000000..d6c668c1b7f
--- /dev/null
+++ b/apps/server/src/services/canvas/__tests__/storage.test.ts
@@ -0,0 +1,168 @@
+// @vitest-environment node
+import { getTestDB } from '@lobechat/database/test-utils';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { FileModel } from '@/database/models/file';
+import { users } from '@/database/schemas';
+
+import { type CanvasBlobStore, CanvasStorageService, isOwnCanvasManifestKey } from '../storage';
+
+const serverDB = await getTestDB();
+const userId = 'canvas-storage-user';
+
+const createMemoryStore = () => {
+ const objects = new Map<string, Uint8Array>();
+ const store: CanvasBlobStore = {
+ delete: vi.fn(async (keys: string[]) => {
+ for (const key of keys) objects.delete(key);
+ }),
+ read: async (key) => {
+ const value = objects.get(key);
+ if (!value) throw new Error(`missing ${key}`);
+ return value;
+ },
+ write: vi.fn(async (key: string, bytes: Uint8Array) => {
+ objects.set(key, bytes);
+ }),
+ };
+ return { objects, store };
+};
+
+const page = (body: string) => `<!doctype html><html><body>${body}</body></html>`;
+
+beforeEach(async () => {
+ await serverDB.delete(users);
+ await serverDB.insert(users).values({ id: userId });
+});
+
+describe('isOwnCanvasManifestKey', () => {
+ it('accepts only manifests stored under the caller', () => {
+ expect(isOwnCanvasManifestKey('u1', 'canvas/u1/cvs_1/manifests/a.json')).toBe(true);
+ expect(isOwnCanvasManifestKey('u1', 'canvas/u2/cvs_1/manifests/a.json')).toBe(false);
+ expect(isOwnCanvasManifestKey('u1', 'canvas/u1/../u2/cvs_1/manifests/a.json')).toBe(false);
+ expect(isOwnCanvasManifestKey('u1', 'canvas/u1x/cvs_1/manifests/a.json')).toBe(false);
+ });
+});
+
+describe('CanvasStorageService', () => {
+ it('stores a project as content-addressed blobs plus a manifest and counts it toward usage', async () => {
+ const { store } = createMemoryStore();
+ const service = new CanvasStorageService({ db: serverDB, store, userId });
+
+ const result = await service.commit('cvs_a', [
+ { content: page('<lobe-tag>hi</lobe-tag>'), path: 'index.html' },
+ { content: '[1,2]', path: 'data.json' },
+ ]);
+
+ expect(result.ok).toBe(true);
+ if (!result.ok) return;
+ expect(result.metadata).toMatchObject({ entry: 'index.html', fileCount: 2, runtimeMajor: 1 });
+ expect(result.metadata.manifestKey).toMatch(
+ /^canvas\/canvas-storage-user\/cvs_a\/manifests\/.+\.json$/,
+ );
+
+ const manifest = await service.readManifest(result.metadata.manifestKey);
+ expect(Object.keys(manifest.files).sort()).toEqual(['data.json', 'index.html']);
+
+ const file = await service.readFile(manifest, 'data.json');
+ expect(new TextDecoder().decode(file?.bytes)).toBe('[1,2]');
+ expect(file?.contentType).toContain('application/json');
+
+ expect(await new FileModel(serverDB, userId).countUsage()).toBe(result.metadata.totalSize);
+ });
+
+ it('uploads unchanged files only once across versions', async () => {
+ const { store } = createMemoryStore();
+ const service = new CanvasStorageService({ db: serverDB, store, userId });
+ const files = [
+ { content: page('a'), path: 'index.html' },
+ { content: 'body{}', path: 'app.css' },
+ ];
+
+ await service.commit('cvs_a', files);
+ await service.commit('cvs_a', [{ ...files[0], content: page('b') }, files[1]]);
+
+ expect(store.write).toHaveBeenCalledTimes(2 + 1 + 1 + 1);
+ });
+
+ it('loads the previous version with text files read and binary files sized', async () => {
+ const { store } = createMemoryStore();
+ const service = new CanvasStorageService({ db: serverDB, store, userId });
+ const result = await service.commit('cvs_a', [
+ { content: page('<img src="a.png">'), path: 'index.html' },
+ { content: new Uint8Array([1, 2, 3, 4]), path: 'a.png' },
+ ]);
+ if (!result.ok) throw new Error('commit failed');
+
+ const project = await service.loadProject(
+ await service.readManifest(result.metadata.manifestKey),
+ );
+
+ expect(project.get('index.html')?.content).toBe(page('<img src="a.png">'));
+ expect(project.get('a.png')).toMatchObject({ size: 4 });
+
+ const next = await service.commit('cvs_a', [...project.values()]);
+ expect(next.ok).toBe(true);
+ });
+
+ it('returns validation issues without writing anything', async () => {
+ const { store } = createMemoryStore();
+ const service = new CanvasStorageService({ db: serverDB, store, userId });
+
+ const result = await service.commit('cvs_a', [
+ { content: page('<lobe-nope></lobe-nope>'), path: 'index.html' },
+ ]);
+
+ expect(result).toMatchObject({ issues: [{ rule: 'unknown-component' }], ok: false });
+ expect(store.write).not.toHaveBeenCalled();
+ });
+
+ it('refuses a commit that exceeds the storage quota', async () => {
+ const { store } = createMemoryStore();
+ const checkQuota = vi.fn().mockResolvedValue({ message: 'Storage is full', ok: false });
+ const service = new CanvasStorageService({ checkQuota, db: serverDB, store, userId });
+
+ const result = await service.commit('cvs_a', [{ content: page('x'), path: 'index.html' }]);
+
+ expect(result).toMatchObject({
+ issues: [{ message: 'Storage is full', rule: 'quota-exceeded' }],
+ ok: false,
+ });
+ expect(checkQuota).toHaveBeenCalledWith(
+ expect.objectContaining({ addedBytes: expect.any(Number), userId }),
+ );
+ expect(store.write).not.toHaveBeenCalled();
+ });
+
+ it('refuses to read another user’s manifest', async () => {
+ const { store } = createMemoryStore();
+ const service = new CanvasStorageService({ db: serverDB, store, userId });
+
+ await expect(
+ service.readManifest('canvas/someone-else/cvs/manifests/x.json'),
+ ).rejects.toThrow();
+ });
+
+ it('deletes every version manifest and unshared blob while preserving other canvases', async () => {
+ const { objects, store } = createMemoryStore();
+ const service = new CanvasStorageService({ db: serverDB, store, userId });
+ const manifests: string[] = [];
+ for (const content of ['first', 'second']) {
+ const result = await service.commit('cvs_a', [
+ { content: page(content), path: 'index.html' },
+ ]);
+ if (!result.ok) throw new Error('commit failed');
+ manifests.push(result.metadata.manifestKey);
+ }
+ const otherKeys = [
+ `canvas/${userId}/cvs_b/manifests/other.json`,
+ 'canvas/another-user/cvs_a/manifests/other.json',
+ ];
+ for (const key of otherKeys) objects.set(key, new Uint8Array([1]));
+
+ await service.removeCanvas('cvs_a', [...manifests, ...otherKeys]);
+
+ expect(await new FileModel(serverDB, userId).countUsage()).toBe(0);
+ expect([...objects.keys()].sort()).toEqual(otherKeys.sort());
+ });
+});
diff --git a/apps/server/src/services/canvas/__tests__/toolService.test.ts b/apps/server/src/services/canvas/__tests__/toolService.test.ts
new file mode 100644
index 00000000000..30278e1f3a2
--- /dev/null
+++ b/apps/server/src/services/canvas/__tests__/toolService.test.ts
@@ -0,0 +1,281 @@
+// @vitest-environment node
+import { getTestDB } from '@lobechat/database/test-utils';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { WorkModel } from '@/database/models/work';
+import { agents, users, workspaceMembers, workspaces } from '@/database/schemas';
+
+import type { CanvasFileRefResolver } from '../fileRefs';
+import { type CanvasBlobStore, CanvasStorageService } from '../storage';
+import { CanvasToolServiceImpl } from '../toolService';
+
+const serverDB = await getTestDB();
+const userId = 'canvas-tool-user';
+const agentId = 'canvas-tool-agent';
+
+const memoryStore = (): CanvasBlobStore => {
+ const objects = new Map<string, Uint8Array>();
+ return {
+ delete: async (keys) => keys.forEach((key) => objects.delete(key)),
+ read: async (key) => {
+ const value = objects.get(key);
+ if (!value) throw new Error(`missing ${key}`);
+ return value;
+ },
+ write: async (key, bytes) => {
+ objects.set(key, bytes);
+ },
+ };
+};
+
+const page = (body: string) => `<!doctype html><html><body>${body}</body></html>`;
+
+const setup = (
+ overrides: {
+ actorId?: string;
+ findGuideState?: () => Promise<unknown>;
+ resolveFileRefs?: CanvasFileRefResolver;
+ store?: CanvasBlobStore;
+ topicId?: string;
+ workspaceId?: string;
+ } = {},
+) => {
+ const actorId = overrides.actorId ?? userId;
+ const store = overrides.store ?? memoryStore();
+ const storageFor = (ownerId: string) =>
+ new CanvasStorageService({
+ db: serverDB,
+ store,
+ userId: ownerId,
+ workspaceId: overrides.workspaceId,
+ });
+ const storage = storageFor(actorId);
+ const workModel = new WorkModel(serverDB, actorId, overrides.workspaceId);
+ const service = new CanvasToolServiceImpl({
+ agentId,
+ findGuideState: overrides.findGuideState ?? vi.fn().mockResolvedValue({ guideRead: true }),
+ resolveFileRefs: overrides.resolveFileRefs,
+ storage,
+ storageFor,
+ topicId: 'topicId' in overrides ? overrides.topicId : 'topic-1',
+ workModel,
+ });
+ return { service, storage, workModel };
+};
+
+const registerFromOutcome = async (
+ workModel: WorkModel,
+ outcome: Awaited<ReturnType<CanvasToolServiceImpl['create']>>,
+ toolCallId: string,
+) => {
+ if (!outcome.ok) throw new Error('save failed');
+ await workModel.registerCanvas({
+ agentId,
+ canvasId: outcome.canvasId,
+ description: outcome.description,
+ metadata: outcome.metadata,
+ title: outcome.title,
+ toolCallId,
+ toolIdentifier: 'lobe-canvas',
+ toolName: 'createCanvas',
+ });
+};
+
+beforeEach(async () => {
+ await serverDB.delete(users);
+ await serverDB.insert(users).values({ id: userId });
+ await serverDB.insert(agents).values({ id: agentId, userId });
+});
+
+describe('CanvasToolServiceImpl', () => {
+ it('creates a canvas with a fresh id', async () => {
+ const { service } = setup();
+
+ const outcome = await service.create({
+ description: 'Up 23%',
+ files: [{ content: page('<lobe-tag>x</lobe-tag>'), path: 'index.html' }],
+ title: 'Cost report',
+ });
+
+ expect(outcome).toMatchObject({ description: 'Up 23%', ok: true, title: 'Cost report' });
+ if (outcome.ok) expect(outcome.canvasId).toMatch(/^cvs_/);
+ });
+
+ it('updates the latest version with edits and keeps the title when not given', async () => {
+ const { service, storage, workModel } = setup();
+ const created = await service.create({
+ files: [{ content: page('<h1>Old</h1>'), path: 'index.html' }],
+ title: 'Cost report',
+ });
+ await registerFromOutcome(workModel, created, 'call-1');
+ if (!created.ok) return;
+
+ const updated = await service.update({
+ canvasId: created.canvasId,
+ edits: [{ newText: 'New', oldText: 'Old', path: 'index.html' }],
+ });
+
+ expect(updated).toMatchObject({ canvasId: created.canvasId, ok: true, title: 'Cost report' });
+ if (!updated.ok) return;
+ const manifest = await storage.readManifest(updated.metadata.manifestKey);
+ const file = await storage.readFile(manifest, 'index.html');
+ expect(new TextDecoder().decode(file?.bytes)).toContain('<h1>New</h1>');
+ });
+
+ it('saves a referenced file into the canvas on create and update', async () => {
+ const logo = new Uint8Array([137, 80, 78, 71]);
+ const resolveFileRefs: CanvasFileRefResolver = vi.fn(async (writes) => ({
+ contents: new Map(writes.map((write) => [write.fileRef, logo])),
+ issues: [],
+ }));
+ const { service, storage, workModel } = setup({ resolveFileRefs });
+ const created = await service.create({
+ files: [
+ { content: page('<img src="img/logo.png" alt="Logo">'), path: 'index.html' },
+ { fileRef: 'file_logo', path: 'img/logo.png' },
+ ],
+ title: 'Brand',
+ });
+ await registerFromOutcome(workModel, created, 'call-1');
+ if (!created.ok) throw new Error('create failed');
+
+ const updated = await service.update({
+ canvasId: created.canvasId,
+ writes: [{ fileRef: 'msg_a1b2c3.image_1', path: 'img/photo.png' }],
+ });
+
+ expect(updated.ok).toBe(true);
+ if (!updated.ok) return;
+ const manifest = await storage.readManifest(updated.metadata.manifestKey);
+ expect((await storage.readFile(manifest, 'img/logo.png'))?.bytes).toEqual(logo);
+ expect((await storage.readFile(manifest, 'img/photo.png'))?.bytes).toEqual(logo);
+ expect(resolveFileRefs).toHaveBeenLastCalledWith([
+ { fileRef: 'msg_a1b2c3.image_1', path: 'img/photo.png' },
+ ]);
+ });
+
+ it('fails the save with the issues of a reference that cannot be resolved', async () => {
+ const issue = { file: 'img/logo.png', message: 'nope', rule: 'unresolved-file-ref' as const };
+ const { service } = setup({
+ resolveFileRefs: vi.fn(async () => ({ contents: new Map(), issues: [issue] })),
+ });
+
+ const outcome = await service.create({
+ files: [
+ { content: page('<img src="img/logo.png" alt="Logo">'), path: 'index.html' },
+ { fileRef: 'file_other', path: 'img/logo.png' },
+ ],
+ title: 'Brand',
+ });
+
+ expect(outcome).toEqual({ issues: [issue], ok: false });
+ });
+
+ it('turns a bad edit or an unknown canvas into a failed outcome', async () => {
+ const { service, workModel } = setup();
+ const created = await service.create({
+ files: [{ content: page('<h1>Old</h1>'), path: 'index.html' }],
+ title: 'Cost report',
+ });
+ await registerFromOutcome(workModel, created, 'call-1');
+ if (!created.ok) return;
+
+ expect(
+ await service.update({
+ canvasId: created.canvasId,
+ edits: [{ newText: 'x', oldText: 'missing', path: 'index.html' }],
+ }),
+ ).toMatchObject({ error: expect.stringContaining('0 times'), ok: false });
+ expect(await service.update({ canvasId: 'cvs_nope', writes: [] })).toMatchObject({
+ error: expect.stringContaining('cvs_nope'),
+ ok: false,
+ });
+ });
+
+ it('reads text files and lists binary ones by size', async () => {
+ const { service, workModel } = setup();
+ const created = await service.create({
+ files: [
+ { content: page('<img src="a.png">'), path: 'index.html' },
+ { content: 'AQID', encoding: 'base64', path: 'a.png' },
+ ],
+ title: 'Cost report',
+ });
+ await registerFromOutcome(workModel, created, 'call-1');
+ if (!created.ok) return;
+
+ const read = await service.read({ canvasId: created.canvasId });
+
+ expect(read?.files).toEqual([
+ { path: 'a.png', size: 3 },
+ { path: 'index.html', size: expect.any(Number) },
+ ]);
+ expect(read?.texts).toEqual([{ content: page('<img src="a.png">'), path: 'index.html' }]);
+ });
+
+ it('lets a teammate read a shared canvas but not overwrite it', async () => {
+ const workspaceId = 'canvas-tool-ws';
+ const mateId = 'canvas-tool-mate';
+ await serverDB.insert(users).values({ id: mateId });
+ await serverDB
+ .insert(workspaces)
+ .values({ id: workspaceId, name: 'ws', primaryOwnerId: userId, slug: workspaceId });
+ await serverDB.insert(workspaceMembers).values([
+ { role: 'owner', userId, workspaceId },
+ { role: 'editor', userId: mateId, workspaceId },
+ ]);
+ const store = memoryStore();
+ const owner = setup({ store, workspaceId });
+ const outcome = await owner.service.create({
+ files: [{ content: page('<lobe-tag>x</lobe-tag>'), path: 'index.html' }],
+ title: 'Shared',
+ });
+ if (!outcome.ok) throw new Error('save failed');
+ await owner.workModel.registerCanvas({
+ canvasId: outcome.canvasId,
+ metadata: outcome.metadata,
+ title: outcome.title,
+ toolCallId: 'call-shared',
+ toolIdentifier: 'lobe-canvas',
+ toolName: 'createCanvas',
+ visibility: 'public',
+ });
+ const mate = setup({ actorId: mateId, store, workspaceId });
+
+ const read = await mate.service.read({ canvasId: outcome.canvasId });
+ const update = await mate.service.update({
+ canvasId: outcome.canvasId,
+ edits: [{ newText: 'y', oldText: '>x<', path: 'index.html' }],
+ });
+
+ expect(read?.texts[0].content).toContain('<lobe-tag>x</lobe-tag>');
+ expect(update).toMatchObject({ ok: false });
+ expect(update.ok === false && update.error).toContain('owner');
+ });
+
+ it('lists canvases made by the agent', async () => {
+ const { service, workModel } = setup();
+ const created = await service.create({
+ files: [{ content: page('x'), path: 'index.html' }],
+ title: 'Cost report',
+ });
+ await registerFromOutcome(workModel, created, 'call-1');
+
+ const list = await service.list();
+
+ expect(list).toEqual([expect.objectContaining({ title: 'Cost report' })]);
+ });
+
+ it('knows whether the guide was read in this topic', async () => {
+ expect(await setup().service.hasReadGuide()).toBe(true);
+ expect(
+ await setup({ findGuideState: vi.fn().mockResolvedValue(undefined) }).service.hasReadGuide(),
+ ).toBe(false);
+ expect(
+ await setup({
+ findGuideState: vi.fn().mockResolvedValue(undefined),
+ topicId: undefined,
+ }).service.hasReadGuide(),
+ ).toBe(true);
+ });
+});
diff --git a/apps/server/src/services/canvas/agentRuntime.ts b/apps/server/src/services/canvas/agentRuntime.ts
new file mode 100644
index 00000000000..57280f4f2a0
--- /dev/null
+++ b/apps/server/src/services/canvas/agentRuntime.ts
@@ -0,0 +1,74 @@
+import { CanvasApiName, CanvasIdentifier } from '@lobechat/builtin-tool-canvas';
+import { CanvasExecutionRuntime } from '@lobechat/builtin-tool-canvas/executionRuntime';
+import { createMediaFileItemsFromMessage } from '@lobechat/builtin-tool-lobe-agent';
+
+import { FileModel } from '@/database/models/file';
+import { MessageModel } from '@/database/models/message';
+import { WorkModel } from '@/database/models/work';
+import type { LobeChatDatabase } from '@/database/type';
+import { FileService } from '@/server/services/file';
+
+import { type CanvasFileRefResolver, createCanvasFileRefResolver } from './fileRefs';
+import { createCanvasStorageService } from './index';
+import { CanvasToolServiceImpl } from './toolService';
+
+export interface CanvasAgentRuntimeScope {
+ agentId?: string | null;
+ threadId?: string | null;
+ topicId?: string | null;
+ userId: string;
+ workspaceId?: string;
+}
+
+export const createCanvasFileRefResolverFor = (
+ db: LobeChatDatabase,
+ scope: CanvasAgentRuntimeScope,
+): CanvasFileRefResolver => {
+ const { userId, workspaceId } = scope;
+
+ return createCanvasFileRefResolver({
+ findFile: async (id) => {
+ const file = await new FileModel(db, userId, workspaceId).findById(id);
+ return file
+ ? { fileType: file.fileType, id: file.id, name: file.name, size: file.size, url: file.url }
+ : undefined;
+ },
+ listMediaFileIds: async () => {
+ if (!scope.topicId) return new Map();
+ const messages = await new MessageModel(db, userId, workspaceId).query({
+ agentId: scope.agentId ?? undefined,
+ skipWorks: true,
+ threadId: scope.threadId ?? undefined,
+ topicId: scope.topicId,
+ });
+ return new Map(
+ messages
+ .flatMap((message) => createMediaFileItemsFromMessage(message))
+ .map((item) => [item.ref, item.id]),
+ );
+ },
+ readBytes: (key) => new FileService(db, userId, workspaceId).getFileByteArray(key),
+ });
+};
+
+export const createCanvasAgentRuntime = (db: LobeChatDatabase, scope: CanvasAgentRuntimeScope) => {
+ const { userId, workspaceId } = scope;
+
+ return new CanvasExecutionRuntime(
+ new CanvasToolServiceImpl({
+ agentId: scope.agentId,
+ resolveFileRefs: createCanvasFileRefResolverFor(db, scope),
+ findGuideState: () =>
+ new MessageModel(db, userId, workspaceId).findLatestPluginStateInTopic({
+ apiName: CanvasApiName.readCanvasGuide,
+ identifier: CanvasIdentifier,
+ threadId: scope.threadId,
+ topicId: scope.topicId!,
+ }),
+ storage: createCanvasStorageService(db, userId, workspaceId),
+ storageFor: (ownerId) => createCanvasStorageService(db, ownerId, workspaceId),
+ topicId: scope.topicId,
+ workModel: new WorkModel(db, userId, workspaceId),
+ }),
+ );
+};
diff --git a/apps/server/src/services/canvas/fileRefs.ts b/apps/server/src/services/canvas/fileRefs.ts
new file mode 100644
index 00000000000..f5b0e4a6701
--- /dev/null
+++ b/apps/server/src/services/canvas/fileRefs.ts
@@ -0,0 +1,109 @@
+import {
+ CANVAS_LIMITS,
+ type CanvasFileRefWrite,
+ type CanvasIssue,
+ getCanvasContentType,
+ isCanvasTextPath,
+} from '@lobechat/canvas';
+
+export interface CanvasRefFile {
+ fileType: string;
+ id: string;
+ name: string;
+ size: number;
+ url: string;
+}
+
+export interface CanvasFileRefResolverDeps {
+ findFile: (id: string) => Promise<CanvasRefFile | undefined>;
+ listMediaFileIds: () => Promise<Map<string, string | undefined>>;
+ readBytes: (key: string) => Promise<Uint8Array>;
+}
+
+export interface CanvasFileRefResolution {
+ contents: Map<string, string | Uint8Array>;
+ issues: CanvasIssue[];
+}
+
+export type CanvasFileRefResolver = (
+ writes: CanvasFileRefWrite[],
+) => Promise<CanvasFileRefResolution>;
+
+const MEDIA_REF_PATTERN = /^msg_[\da-z]+\.(?:audio|image|video)_\d+$/;
+
+type MediaKind = 'audio' | 'font' | 'image' | 'text' | 'video';
+
+const kindOf = (contentType: string): MediaKind | undefined => {
+ const [type = '', subtype = ''] = contentType.split(';')[0].trim().toLowerCase().split('/');
+ if (type === 'audio' || type === 'font' || type === 'image' || type === 'video') return type;
+ if (subtype.includes('font')) return 'font';
+ if (type === 'text' || subtype === 'json' || subtype.includes('javascript')) return 'text';
+};
+
+const unresolved = (path: string, fileRef: string): CanvasIssue => ({
+ file: path,
+ message: `fileRef "${fileRef}" does not match a file you can access. Use a file id from <file id> or an image ref from <image ref> in this conversation.`,
+ rule: 'unresolved-file-ref',
+});
+
+export const createCanvasFileRefResolver =
+ (deps: CanvasFileRefResolverDeps): CanvasFileRefResolver =>
+ async (writes) => {
+ const contents = new Map<string, string | Uint8Array>();
+ const issues: CanvasIssue[] = [];
+ let mediaFileIds: Map<string, string | undefined> | undefined;
+
+ for (const { fileRef, path } of writes) {
+ if (contents.has(fileRef)) continue;
+
+ let fileId: string | undefined = fileRef;
+ if (MEDIA_REF_PATTERN.test(fileRef)) {
+ mediaFileIds ??= await deps.listMediaFileIds();
+ fileId = mediaFileIds.get(fileRef);
+ }
+ const file = fileId ? await deps.findFile(fileId) : undefined;
+ if (!file) {
+ issues.push(unresolved(path, fileRef));
+ continue;
+ }
+
+ const sourceKind = kindOf(file.fileType);
+ const targetKind = kindOf(getCanvasContentType(path));
+ if (sourceKind && targetKind && sourceKind !== targetKind) {
+ issues.push({
+ file: path,
+ message: `fileRef "${fileRef}" is ${file.fileType}, which cannot be saved as a ${targetKind} file. Pick a path whose extension matches the file.`,
+ rule: 'file-type-mismatch',
+ });
+ continue;
+ }
+
+ const isText = isCanvasTextPath(path);
+ const limit = isText ? CANVAS_LIMITS.maxTextFileBytes : CANVAS_LIMITS.maxFileBytes;
+ if (file.size > limit) {
+ issues.push({
+ file: path,
+ message: `fileRef "${fileRef}" is ${file.size} bytes; the limit for this file type is ${limit} bytes.`,
+ rule: 'file-too-large',
+ });
+ continue;
+ }
+
+ const bytes = await deps.readBytes(file.url);
+ if (!isText) {
+ contents.set(fileRef, bytes);
+ continue;
+ }
+ try {
+ contents.set(fileRef, new TextDecoder('utf-8', { fatal: true }).decode(bytes));
+ } catch {
+ issues.push({
+ file: path,
+ message: `fileRef "${fileRef}" is not UTF-8 text, so it cannot be saved as a text file.`,
+ rule: 'file-type-mismatch',
+ });
+ }
+ }
+
+ return { contents, issues };
+ };
diff --git a/apps/server/src/services/canvas/index.ts b/apps/server/src/services/canvas/index.ts
new file mode 100644
index 00000000000..a171e84d58e
--- /dev/null
+++ b/apps/server/src/services/canvas/index.ts
@@ -0,0 +1,30 @@
+import { checkCanvasStorageQuota } from '@/business/server/canvasStorage';
+import type { LobeChatDatabase } from '@/database/type';
+import { FileService } from '@/server/services/file';
+
+import { type CanvasBlobStore, CanvasStorageService } from './storage';
+
+export * from './storage';
+
+export const createFileServiceBlobStore = (fileService: FileService): CanvasBlobStore => ({
+ delete: async (keys) => {
+ await fileService.deleteFiles(keys);
+ },
+ read: (key) => fileService.getFileByteArray(key),
+ write: async (key, bytes, contentType) => {
+ await fileService.uploadBuffer(key, Buffer.from(bytes), contentType);
+ },
+});
+
+export const createCanvasStorageService = (
+ db: LobeChatDatabase,
+ userId: string,
+ workspaceId?: string,
+) =>
+ new CanvasStorageService({
+ checkQuota: checkCanvasStorageQuota,
+ db,
+ store: createFileServiceBlobStore(new FileService(db, userId, workspaceId)),
+ userId,
+ workspaceId,
+ });
diff --git a/apps/server/src/services/canvas/publish.ts b/apps/server/src/services/canvas/publish.ts
new file mode 100644
index 00000000000..db2ec42be3b
--- /dev/null
+++ b/apps/server/src/services/canvas/publish.ts
@@ -0,0 +1,70 @@
+import {
+ CANVAS_ENTRY,
+ type CanvasManifest,
+ getCanvasFileExtension,
+ isCanvasTextPath,
+} from '@lobechat/canvas';
+import type { CanvasPublishBundle, CanvasPublishFile } from '@lobechat/types';
+
+import { CANVAS_RUNTIME_FILE } from './runtimeUrl';
+import { injectCanvasRuntime } from './serve';
+import type { CanvasStorageService } from './storage';
+
+const isAbsoluteUrl = (value: string) => /^https?:\/\//.test(value);
+
+export const resolveCanvasPublicRuntimeUrl = (
+ major: number,
+ env: { appUrl?: string; baseUrl?: string },
+): string | undefined => {
+ const base = env.baseUrl?.replace(/\/$/, '');
+ if (base && isAbsoluteUrl(base)) return `${base}/v${major}/${CANVAS_RUNTIME_FILE}`;
+ if (!env.appUrl || !isAbsoluteUrl(env.appUrl)) return;
+ return new URL(`${base ?? '/canvas-runtime'}/v${major}/${CANVAS_RUNTIME_FILE}`, env.appUrl).href;
+};
+
+export const buildCanvasPublishBundle = async (
+ storage: Pick<CanvasStorageService, 'readFile'>,
+ manifest: CanvasManifest,
+ runtimeUrl: string,
+): Promise<CanvasPublishBundle> => {
+ const decoder = new TextDecoder();
+ const entry = manifest.entry || CANVAS_ENTRY;
+ let html = '';
+ const files: CanvasPublishFile[] = [];
+
+ for (const path of Object.keys(manifest.files).toSorted()) {
+ const file = await storage.readFile(manifest, path);
+ if (!file) throw new Error(`Canvas file ${path} is missing`);
+
+ if (getCanvasFileExtension(path) === 'html') {
+ const page = injectCanvasRuntime(decoder.decode(file.bytes), { runtimeUrl });
+ if (path === entry) html = page;
+ else
+ files.push({
+ content: page,
+ contentType: file.contentType,
+ encoding: 'utf8',
+ path: `/${path}`,
+ });
+ continue;
+ }
+
+ files.push(
+ isCanvasTextPath(path)
+ ? {
+ content: decoder.decode(file.bytes),
+ contentType: file.contentType,
+ encoding: 'utf8',
+ path: `/${path}`,
+ }
+ : {
+ content: Buffer.from(file.bytes).toString('base64'),
+ contentType: file.contentType,
+ encoding: 'base64',
+ path: `/${path}`,
+ },
+ );
+ }
+
+ return { files, html };
+};
diff --git a/apps/server/src/services/canvas/runtimeUrl.ts b/apps/server/src/services/canvas/runtimeUrl.ts
new file mode 100644
index 00000000000..6731b5ba441
--- /dev/null
+++ b/apps/server/src/services/canvas/runtimeUrl.ts
@@ -0,0 +1,13 @@
+import { CANVAS_ENTRY, CANVAS_RUNTIME_MAJOR } from '@lobechat/canvas';
+
+export const CANVAS_RUNTIME_FILE = 'canvas-runtime.js';
+
+export const resolveCanvasRuntimeUrl = (major = CANVAS_RUNTIME_MAJOR) => {
+ const base = process.env.CANVAS_RUNTIME_BASE_URL?.replace(/\/$/, '') ?? '/canvas-runtime';
+ return `${base}/v${major}/${CANVAS_RUNTIME_FILE}`;
+};
+
+// Next redirects a trailing-slash URL to its slashless form, which would resolve the
+// project's relative file references one directory too high; address the entry file instead.
+export const buildCanvasPreviewUrl = (token: string, entry = CANVAS_ENTRY) =>
+ `/canvas-preview/${token}/${entry}`;
diff --git a/apps/server/src/services/canvas/serve.ts b/apps/server/src/services/canvas/serve.ts
new file mode 100644
index 00000000000..594e5d0b0a7
--- /dev/null
+++ b/apps/server/src/services/canvas/serve.ts
@@ -0,0 +1,142 @@
+import { createHmac, timingSafeEqual } from 'node:crypto';
+
+import { CANVAS_ENTRY, getCanvasFileExtension, normalizeCanvasPath } from '@lobechat/canvas';
+import { installCanvasBridge } from '@lobechat/canvas/runtime';
+
+import type { CanvasStorageService } from './storage';
+
+export const CANVAS_PREVIEW_TTL_SECONDS = 60 * 60;
+export const CANVAS_PREVIEW_TTL_BUCKET_SECONDS = 15 * 60;
+
+export interface CanvasPreviewTokenPayload {
+ manifestKey: string;
+ userId: string;
+ workspaceId?: string;
+}
+
+interface EncodedPayload {
+ e: number;
+ k: string;
+ u: string;
+ w?: string;
+}
+
+const secret = () => {
+ const value = process.env.KEY_VAULTS_SECRET;
+ if (!value) throw new Error('`KEY_VAULTS_SECRET` is required to sign canvas preview URLs');
+ return value;
+};
+
+const sign = (body: string) =>
+ createHmac('sha256', secret()).update(`canvas-preview:${body}`).digest('base64url');
+
+export const signCanvasPreviewToken = (
+ payload: CanvasPreviewTokenPayload,
+ ttlSeconds = CANVAS_PREVIEW_TTL_SECONDS,
+) => {
+ const bucket = CANVAS_PREVIEW_TTL_BUCKET_SECONDS;
+ const encoded: EncodedPayload = {
+ e: (Math.floor(Date.now() / 1000 / bucket) + 1) * bucket + ttlSeconds,
+ k: payload.manifestKey,
+ u: payload.userId,
+ ...(payload.workspaceId && { w: payload.workspaceId }),
+ };
+ const body = Buffer.from(JSON.stringify(encoded)).toString('base64url');
+ return `${body}.${sign(body)}`;
+};
+
+export const verifyCanvasPreviewToken = (token: string): CanvasPreviewTokenPayload | undefined => {
+ const [body, signature] = token.split('.');
+ if (!body || !signature) return;
+
+ const expected = Buffer.from(sign(body));
+ const actual = Buffer.from(signature);
+ if (expected.length !== actual.length || !timingSafeEqual(expected, actual)) return;
+
+ try {
+ const payload = JSON.parse(Buffer.from(body, 'base64url').toString()) as EncodedPayload;
+ if (payload.e * 1000 < Date.now()) return;
+ return { manifestKey: payload.k, userId: payload.u, workspaceId: payload.w };
+ } catch {
+ return;
+ }
+};
+
+const injectHead = (html: string, injection: string) => {
+ const head = /<head(?:\s[^>]*)?>/i.exec(html);
+ if (head) {
+ const at = head.index + head[0].length;
+ return `${html.slice(0, at)}${injection}${html.slice(at)}`;
+ }
+ return `<!doctype html><html><head><meta charset="utf-8">${injection}</head><body>${html}</body></html>`;
+};
+
+export const injectCanvasRuntime = (html: string, options: { runtimeUrl: string }) =>
+ injectHead(html, `<script defer src="${options.runtimeUrl}"></script>`);
+
+const injectCanvasPreview = (html: string, runtimeUrl: string) => {
+ const fallback = JSON.stringify(runtimeUrl).replaceAll('<', String.raw`\u003c`);
+ return injectHead(
+ html,
+ `<script data-lobe-canvas-bridge>(${installCanvasBridge.toString()})(${fallback});</script>`,
+ );
+};
+
+const contentSecurityPolicy = (runtimeUrl: string) => {
+ const runtimeOrigin = /^https?:\/\//.test(runtimeUrl) ? ` ${new URL(runtimeUrl).origin}` : '';
+ return [
+ 'sandbox allow-scripts allow-popups allow-forms allow-downloads',
+ "default-src 'none'",
+ `script-src 'self' 'unsafe-inline' blob:${runtimeOrigin}`,
+ "style-src 'self' 'unsafe-inline'",
+ "img-src 'self' data: blob:",
+ "font-src 'self' data:",
+ "media-src 'self' data: blob:",
+ "connect-src 'self'",
+ "form-action 'none'",
+ "base-uri 'none'",
+ ].join('; ');
+};
+
+export interface ServeCanvasFileParams {
+ createStorage: (
+ payload: CanvasPreviewTokenPayload,
+ ) => Pick<CanvasStorageService, 'readFile' | 'readManifest'>;
+ path: string;
+ runtimeUrl: string;
+ token: string;
+}
+
+export const serveCanvasFile = async ({
+ createStorage,
+ path,
+ runtimeUrl,
+ token,
+}: ServeCanvasFileParams): Promise<Response> => {
+ const payload = verifyCanvasPreviewToken(token);
+ if (!payload) return new Response('Forbidden', { status: 403 });
+
+ const requested = path ? normalizeCanvasPath(path) : undefined;
+ if (path && !requested) return new Response('Not found', { status: 404 });
+
+ const storage = createStorage(payload);
+ const manifest = await storage.readManifest(payload.manifestKey);
+ const target = requested || manifest.entry || CANVAS_ENTRY;
+ const file = await storage.readFile(manifest, target);
+ if (!file) return new Response('Not found', { status: 404 });
+
+ const headers = new Headers({
+ 'access-control-allow-origin': '*',
+ 'cache-control': 'private, max-age=300',
+ 'content-security-policy': contentSecurityPolicy(runtimeUrl),
+ 'content-type': file.contentType,
+ 'x-content-type-options': 'nosniff',
+ });
+
+ if (getCanvasFileExtension(target) === 'html') {
+ const html = injectCanvasPreview(new TextDecoder().decode(file.bytes), runtimeUrl);
+ return new Response(html, { headers, status: 200 });
+ }
+
+ return new Response(new Blob([file.bytes as Uint8Array<ArrayBuffer>]), { headers, status: 200 });
+};
diff --git a/apps/server/src/services/canvas/storage.ts b/apps/server/src/services/canvas/storage.ts
new file mode 100644
index 00000000000..ab197ba287f
--- /dev/null
+++ b/apps/server/src/services/canvas/storage.ts
@@ -0,0 +1,232 @@
+import { createHash } from 'node:crypto';
+
+import {
+ CANVAS_ENTRY,
+ CANVAS_RUNTIME_MAJOR,
+ type CanvasIssue,
+ type CanvasManifest,
+ type CanvasProjectFile,
+ getCanvasContentType,
+ isCanvasTextPath,
+ normalizeCanvasPath,
+ validateCanvasProject,
+} from '@lobechat/canvas';
+import { checkCanvasMermaid } from '@lobechat/canvas/mermaid';
+import type { CanvasWorkVersionMetadata } from '@lobechat/types';
+import pMap from 'p-map';
+
+import type { CanvasStorageQuotaResult } from '@/business/server/canvasStorage';
+import { CanvasFileModel } from '@/database/models/canvasFile';
+import { WorkModel } from '@/database/models/work';
+import { CanvasFileRepository } from '@/database/repositories/canvasFile';
+import type { LobeChatDatabase } from '@/database/type';
+
+export interface CanvasBlobStore {
+ delete: (keys: string[]) => Promise<void>;
+ read: (key: string) => Promise<Uint8Array>;
+ write: (key: string, bytes: Uint8Array, contentType: string) => Promise<void>;
+}
+
+export type CanvasCommitFile = CanvasProjectFile & { hash?: string };
+
+export type CanvasCommitResult =
+ | { issues: CanvasIssue[]; ok: false }
+ | { manifest: CanvasManifest; metadata: CanvasWorkVersionMetadata; ok: true };
+
+interface CanvasStorageDeps {
+ checkQuota?: (params: {
+ addedBytes: number;
+ userId: string;
+ workspaceId?: string | null;
+ }) => Promise<CanvasStorageQuotaResult>;
+ db: LobeChatDatabase;
+ store: CanvasBlobStore;
+ userId: string;
+ workspaceId?: string;
+}
+
+const encoder = new TextEncoder();
+const decoder = new TextDecoder();
+
+const sha256 = (bytes: Uint8Array | string) => createHash('sha256').update(bytes).digest('hex');
+
+const toBytes = (content: string | Uint8Array) =>
+ typeof content === 'string' ? encoder.encode(content) : content;
+
+const basename = (path: string) => path.slice(path.lastIndexOf('/') + 1);
+
+export const isOwnCanvasManifestKey = (userId: string, key: string) =>
+ key.startsWith(`canvas/${userId}/`) && !key.includes('..');
+
+const BLOB_READ_CONCURRENCY = 8;
+
+export class CanvasStorageService {
+ private deps: CanvasStorageDeps;
+ private files: CanvasFileModel;
+ private fileRegistry: CanvasFileRepository;
+
+ constructor(deps: CanvasStorageDeps) {
+ this.deps = deps;
+ this.files = new CanvasFileModel(deps.db, deps.userId, deps.workspaceId);
+ this.fileRegistry = new CanvasFileRepository(deps.db, deps.userId, deps.workspaceId);
+ }
+
+ get ownerId() {
+ return this.deps.userId;
+ }
+
+ private get prefix() {
+ return `canvas/${this.deps.userId}/`;
+ }
+
+ private blobKey(hash: string) {
+ return `${this.prefix}blobs/${hash}`;
+ }
+
+ ownsKey(key: string) {
+ return isOwnCanvasManifestKey(this.deps.userId, key);
+ }
+
+ async readManifest(key: string): Promise<CanvasManifest> {
+ if (!this.ownsKey(key)) throw new Error('Canvas manifest is not owned by the current user');
+ return JSON.parse(decoder.decode(await this.deps.store.read(key))) as CanvasManifest;
+ }
+
+ async readFile(manifest: CanvasManifest, path: string) {
+ const normalized = normalizeCanvasPath(path);
+ const entry = normalized ? manifest.files[normalized] : undefined;
+ if (!entry) return;
+
+ return {
+ bytes: await this.deps.store.read(this.blobKey(entry.hash)),
+ contentType: entry.contentType,
+ };
+ }
+
+ async loadProject(manifest: CanvasManifest): Promise<Map<string, CanvasCommitFile>> {
+ const entries = await pMap(
+ Object.entries(manifest.files),
+ async ([path, entry]): Promise<[string, CanvasCommitFile]> => {
+ if (!isCanvasTextPath(path)) {
+ return [path, { content: new Uint8Array(0), hash: entry.hash, path, size: entry.size }];
+ }
+ const bytes = await this.deps.store.read(this.blobKey(entry.hash));
+ return [path, { content: decoder.decode(bytes), path }];
+ },
+ { concurrency: BLOB_READ_CONCURRENCY },
+ );
+ return new Map(entries);
+ }
+
+ async commit(canvasId: string, input: CanvasCommitFile[]): Promise<CanvasCommitResult> {
+ const validation = validateCanvasProject(input, { checkMermaid: checkCanvasMermaid });
+ if (!validation.ok) return { issues: validation.issues, ok: false };
+
+ const files = input.map((file) => {
+ const path = normalizeCanvasPath(file.path)!;
+ if (file.hash && file.size !== undefined) {
+ return {
+ bytes: undefined,
+ contentType: getCanvasContentType(path),
+ hash: file.hash,
+ path,
+ size: file.size,
+ };
+ }
+ const bytes = toBytes(file.content);
+ return {
+ bytes,
+ contentType: getCanvasContentType(path),
+ hash: sha256(bytes),
+ path,
+ size: bytes.byteLength,
+ };
+ });
+
+ const known = await this.files.listByHashes([...new Set(files.map((file) => file.hash))]);
+ const inThisCanvas = new Set(
+ known.filter((row) => row.canvasId === canvasId).map((row) => row.fileHash),
+ );
+ const uploaded = new Set(known.map((row) => row.fileHash));
+
+ const added = new Map<string, (typeof files)[number]>();
+ for (const file of files) if (!inThisCanvas.has(file.hash)) added.set(file.hash, file);
+
+ const addedBytes = [...added.values()].reduce((sum, file) => sum + file.size, 0);
+ if (addedBytes > 0 && this.deps.checkQuota) {
+ const quota = await this.deps.checkQuota({
+ addedBytes,
+ userId: this.deps.userId,
+ workspaceId: this.deps.workspaceId,
+ });
+ if (!quota.ok)
+ return { issues: [{ message: quota.message, rule: 'quota-exceeded' }], ok: false };
+ }
+
+ for (const file of added.values()) {
+ if (uploaded.has(file.hash)) continue;
+ if (!file.bytes) throw new Error(`Canvas blob ${file.hash} for ${file.path} is missing`);
+ await this.deps.store.write(this.blobKey(file.hash), file.bytes, file.contentType);
+ uploaded.add(file.hash);
+ }
+
+ await this.fileRegistry.register(
+ canvasId,
+ [...added.values()].map((file) => ({
+ contentType: file.contentType,
+ hash: file.hash,
+ name: basename(file.path),
+ size: file.size,
+ url: this.blobKey(file.hash),
+ })),
+ );
+
+ const manifest: CanvasManifest = {
+ entry: CANVAS_ENTRY,
+ files: Object.fromEntries(
+ files
+ .toSorted((a, b) => a.path.localeCompare(b.path))
+ .map((file) => [
+ file.path,
+ { contentType: file.contentType, hash: file.hash, size: file.size },
+ ]),
+ ),
+ runtimeMajor: CANVAS_RUNTIME_MAJOR,
+ schemaVersion: 1,
+ };
+ const manifestBytes = encoder.encode(JSON.stringify(manifest));
+ const manifestKey = `${this.prefix}${canvasId}/manifests/${sha256(manifestBytes)}.json`;
+ await this.deps.store.write(manifestKey, manifestBytes, 'application/json');
+
+ return {
+ manifest,
+ metadata: {
+ entry: CANVAS_ENTRY,
+ fileCount: files.length,
+ manifestKey,
+ runtimeMajor: CANVAS_RUNTIME_MAJOR,
+ totalSize: files.reduce((sum, file) => sum + file.size, 0),
+ },
+ ok: true,
+ };
+ }
+
+ async removeCanvas(canvasId: string, manifestKeys: string[]) {
+ const orphaned = await this.files.deleteByCanvas(canvasId);
+ const referenced = new Set(
+ await new WorkModel(this.deps.db, this.deps.userId).findReferencedCanvasManifestKeys(
+ manifestKeys,
+ ),
+ );
+ const keys = [
+ ...orphaned,
+ ...manifestKeys.filter(
+ (key) =>
+ this.ownsKey(key) &&
+ key.startsWith(`${this.prefix}${canvasId}/manifests/`) &&
+ !referenced.has(key),
+ ),
+ ];
+ if (keys.length > 0) await this.deps.store.delete(keys);
+ }
+}
diff --git a/apps/server/src/services/canvas/toolService.ts b/apps/server/src/services/canvas/toolService.ts
new file mode 100644
index 00000000000..d00cfe18fe4
--- /dev/null
+++ b/apps/server/src/services/canvas/toolService.ts
@@ -0,0 +1,159 @@
+import type {
+ CanvasReadOutcome,
+ CanvasSaveOutcome,
+ CanvasSummary,
+ CanvasToolService,
+ CreateCanvasParams,
+ ReadCanvasParams,
+ UpdateCanvasParams,
+} from '@lobechat/builtin-tool-canvas';
+import {
+ applyCanvasChanges,
+ type CanvasChangeSet,
+ collectCanvasFileRefs,
+ isCanvasTextPath,
+ normalizeCanvasPath,
+} from '@lobechat/canvas';
+import { nanoid } from '@lobechat/utils';
+
+import type { WorkModel } from '@/database/models/work';
+
+import type { CanvasFileRefResolution, CanvasFileRefResolver } from './fileRefs';
+import type { CanvasStorageService } from './storage';
+
+const READ_TEXT_CHAR_BUDGET = 60_000;
+
+interface CanvasToolServiceDeps {
+ agentId?: string | null;
+ findGuideState: () => Promise<unknown>;
+ resolveFileRefs?: CanvasFileRefResolver;
+ storage: CanvasStorageService;
+ storageFor: (ownerId: string) => CanvasStorageService;
+ topicId?: string | null;
+ workModel: WorkModel;
+}
+
+const ownerOnly = (canvasId: string): CanvasSaveOutcome => ({
+ error: `Canvas "${canvasId}" belongs to another member; only its owner can update it. Read it and create a new canvas instead.`,
+ issues: [],
+ ok: false,
+});
+
+const notFound = (canvasId: string): CanvasSaveOutcome => ({
+ error: `Canvas "${canvasId}" was not found.`,
+ issues: [],
+ ok: false,
+});
+
+export class CanvasToolServiceImpl implements CanvasToolService {
+ private deps: CanvasToolServiceDeps;
+
+ constructor(deps: CanvasToolServiceDeps) {
+ this.deps = deps;
+ }
+
+ hasReadGuide = async () => {
+ if (!this.deps.topicId) return true;
+ const state = (await this.deps.findGuideState()) as { guideRead?: boolean } | undefined;
+ return state?.guideRead === true;
+ };
+
+ private resolveFileRefs = async (changes: CanvasChangeSet): Promise<CanvasFileRefResolution> => {
+ const writes = collectCanvasFileRefs(changes);
+ if (writes.length === 0 || !this.deps.resolveFileRefs)
+ return { contents: new Map(), issues: [] };
+ return this.deps.resolveFileRefs(writes);
+ };
+
+ create = async (params: CreateCanvasParams): Promise<CanvasSaveOutcome> => {
+ const fileRefs = await this.resolveFileRefs({ writes: params.files });
+ if (fileRefs.issues.length > 0) return { issues: fileRefs.issues, ok: false };
+
+ const changes = applyCanvasChanges(new Map(), { writes: params.files }, fileRefs.contents);
+ if (!changes.ok) return { error: changes.error, issues: [], ok: false };
+
+ const canvasId = `cvs_${nanoid()}`;
+ const result = await this.deps.storage.commit(canvasId, changes.files);
+ if (!result.ok) return { issues: result.issues, ok: false };
+
+ return {
+ canvasId,
+ description: params.description ?? null,
+ metadata: result.metadata,
+ ok: true,
+ title: params.title,
+ };
+ };
+
+ update = async (params: UpdateCanvasParams): Promise<CanvasSaveOutcome> => {
+ const current = await this.deps.workModel.findCanvas(params.canvasId);
+ const manifestKey = current?.version.metadata?.canvas?.manifestKey;
+ if (!current || !manifestKey) return notFound(params.canvasId);
+ if (current.work.userId !== this.deps.storage.ownerId) return ownerOnly(params.canvasId);
+
+ const fileRefs = await this.resolveFileRefs(params);
+ if (fileRefs.issues.length > 0) return { issues: fileRefs.issues, ok: false };
+
+ const base = await this.deps.storage.loadProject(
+ await this.deps.storage.readManifest(manifestKey),
+ );
+ const changes = applyCanvasChanges(base, params, fileRefs.contents);
+ if (!changes.ok) return { error: changes.error, issues: [], ok: false };
+
+ const result = await this.deps.storage.commit(params.canvasId, changes.files);
+ if (!result.ok) return { issues: result.issues, ok: false };
+
+ return {
+ canvasId: params.canvasId,
+ description: params.description ?? current.work.description,
+ metadata: result.metadata,
+ ok: true,
+ title: params.title ?? current.work.title ?? 'Untitled',
+ };
+ };
+
+ read = async (params: ReadCanvasParams): Promise<CanvasReadOutcome | undefined> => {
+ const current = await this.deps.workModel.findCanvas(params.canvasId);
+ const manifestKey = current?.version.metadata?.canvas?.manifestKey;
+ if (!current || !manifestKey) return;
+
+ const storage = this.deps.storageFor(current.work.userId);
+ const manifest = await storage.readManifest(manifestKey);
+ const requested = params.paths?.map((path) => normalizeCanvasPath(path));
+ const texts: CanvasReadOutcome['texts'] = [];
+ let budget = READ_TEXT_CHAR_BUDGET;
+
+ for (const path of Object.keys(manifest.files)) {
+ if (!isCanvasTextPath(path)) continue;
+ if (requested && !requested.includes(path)) continue;
+ const file = await storage.readFile(manifest, path);
+ if (!file) continue;
+ const content = new TextDecoder().decode(file.bytes);
+ if (content.length > budget) {
+ texts.push({ content: `[${content.length} characters; read this file on its own]`, path });
+ continue;
+ }
+ budget -= content.length;
+ texts.push({ content, path });
+ }
+
+ return {
+ canvasId: params.canvasId,
+ description: current.work.description,
+ files: Object.entries(manifest.files).map(([path, entry]) => ({ path, size: entry.size })),
+ texts,
+ title: current.work.title,
+ };
+ };
+
+ list = async (): Promise<CanvasSummary[]> => {
+ const works = await this.deps.workModel.listCanvases({ agentId: this.deps.agentId });
+
+ return works.map((work) => ({
+ canvasId: work.resourceId!,
+ description: work.description,
+ title: work.title,
+ updatedAt: new Date(work.updatedAt).toISOString(),
+ }));
+ };
+}
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/canvas.ts b/apps/server/src/services/toolExecution/serverRuntimes/canvas.ts
new file mode 100644
index 00000000000..b5a4a405714
--- /dev/null
+++ b/apps/server/src/services/toolExecution/serverRuntimes/canvas.ts
@@ -0,0 +1,23 @@
+import { CanvasIdentifier } from '@lobechat/builtin-tool-canvas';
+
+import { createCanvasAgentRuntime } from '@/server/services/canvas/agentRuntime';
+
+import { resolveContentWorkspaceId } from './resolveWorkspaceScope';
+import { type ServerRuntimeRegistration } from './types';
+
+export const canvasRuntime: ServerRuntimeRegistration = {
+ factory: async (context) => {
+ if (!context.userId || !context.serverDB) {
+ throw new Error('userId and serverDB are required for Canvas tool execution');
+ }
+
+ return createCanvasAgentRuntime(context.serverDB, {
+ agentId: context.agentId,
+ threadId: context.threadId,
+ topicId: context.topicId,
+ userId: context.userId,
+ workspaceId: await resolveContentWorkspaceId(context),
+ });
+ },
+ identifier: CanvasIdentifier,
+};
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/index.ts b/apps/server/src/services/toolExecution/serverRuntimes/index.ts
index 6630e4aec0f..6425ef8a927 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/index.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/index.ts
@@ -22,6 +22,7 @@ import { auvRuntime } from './auv';
import { briefRuntime } from './brief';
import { browserRuntime } from './browser';
import { calculatorRuntime } from './calculator';
+import { canvasRuntime } from './canvas';
import { cloudSandboxRuntime } from './cloudSandbox';
import { credsRuntime } from './creds';
import { dashboardRuntime } from './dashboard';
@@ -89,6 +90,7 @@ registerRuntimes([
taskRuntime,
userInteractionRuntime,
credsRuntime,
+ canvasRuntime,
dashboardRuntime,
groupAgentBuilderRuntime,
groupManagementRuntime,
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index 4cdb9d91d9f..14f9c3f94ee 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -3518,6 +3518,8 @@
"workingPanel.tabs.pinned": "Pinned tab",
"workingPanel.tabs.unpin": "Unpin tab",
"workingPanel.title": "Working Panel",
+ "workingPanel.works.canvasPublished": "Published",
+ "workingPanel.works.canvasUntitled": "Untitled canvas",
"workingPanel.works.changeType.created": "Created",
"workingPanel.works.changeType.updated": "Updated",
"workingPanel.works.documentDeleted": "This document has been deleted",
diff --git a/locales/en-US/file.json b/locales/en-US/file.json
index e936025dc14..44b2a9ebe94 100644
--- a/locales/en-US/file.json
+++ b/locales/en-US/file.json
@@ -424,6 +424,7 @@
"work.retry": "Retry",
"work.topicGroup.other": "Other",
"work.totalCost": "Total cost {{cost}}",
+ "work.type.canvas": "Canvas",
"work.type.document": "Document",
"work.type.file": "File",
"work.type.githubIssue": "GitHub Issue",
diff --git a/locales/en-US/plugin.json b/locales/en-US/plugin.json
index 4cff53feafe..826fc529c01 100644
--- a/locales/en-US/plugin.json
+++ b/locales/en-US/plugin.json
@@ -241,6 +241,12 @@
"builtins.lobe-browser.apiName.scroll": "Scrolled page",
"builtins.lobe-browser.apiName.snapshot": "Read page elements",
"builtins.lobe-browser.title": "Browser",
+ "builtins.lobe-canvas.apiName.createCanvas": "Create canvas",
+ "builtins.lobe-canvas.apiName.listCanvases": "List canvases",
+ "builtins.lobe-canvas.apiName.readCanvas": "Read canvas",
+ "builtins.lobe-canvas.apiName.readCanvasGuide": "Read canvas guide",
+ "builtins.lobe-canvas.apiName.updateCanvas": "Update canvas",
+ "builtins.lobe-canvas.title": "Canvas",
"builtins.lobe-claude-code.agent.instruction": "Instruction",
"builtins.lobe-claude-code.agent.result": "Result",
"builtins.lobe-claude-code.askUserQuestion.noAnswer": "No answer received — model continued without their input.",
diff --git a/locales/en-US/portal.json b/locales/en-US/portal.json
index 8f840b439c1..7c49d955563 100644
--- a/locales/en-US/portal.json
+++ b/locales/en-US/portal.json
@@ -30,6 +30,22 @@
"artifacts.svg.copySuccess": "Image copied successfully",
"artifacts.svg.download.png": "Download as PNG",
"artifacts.svg.download.svg": "Download as SVG",
+ "canvas.frameTitle": "Canvas preview",
+ "canvas.generating": "Generating v{{version}}…",
+ "canvas.menu.openInTab": "Open in new tab",
+ "canvas.menu.openPublic": "Open public link",
+ "canvas.menu.publish": "Publish v{{version}} to a public link",
+ "canvas.menu.publishing": "Publishing…",
+ "canvas.menu.updatePublic": "Update public link to v{{version}}",
+ "canvas.menu.versionItem": "v{{version}} · {{date}}",
+ "canvas.menu.versions": "Version history",
+ "canvas.notFound": "This canvas no longer exists or is not available to you.",
+ "canvas.publish.failed": "Couldn’t publish. Try again.",
+ "canvas.publish.note": "Newer versions stay private until you update the public link.",
+ "canvas.publish.success": "Published v{{version}}",
+ "canvas.runtimeErrors": "This canvas reported errors ({{count}})",
+ "canvas.runtimeErrorsHint": "Some components could not render. Ask the agent to fix the canvas, or expand to see details.",
+ "canvas.title": "Canvas",
"document.saveConflict": "This document was updated elsewhere. Refreshing to the latest version.",
"document.todos.allCompleted": "All tasks completed",
"document.todos.title": "Tasks",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index e61598e5f2b..b15aaf9a195 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -3518,6 +3518,8 @@
"workingPanel.tabs.pinned": "已固定标签页",
"workingPanel.tabs.unpin": "取消固定标签页",
"workingPanel.title": "工作面板",
+ "workingPanel.works.canvasPublished": "已发布",
+ "workingPanel.works.canvasUntitled": "未命名画布",
"workingPanel.works.changeType.created": "已创建",
"workingPanel.works.changeType.updated": "已编辑",
"workingPanel.works.documentDeleted": "文档已被删除",
diff --git a/locales/zh-CN/file.json b/locales/zh-CN/file.json
index 57980259c2e..b91fa6079f4 100644
--- a/locales/zh-CN/file.json
+++ b/locales/zh-CN/file.json
@@ -424,6 +424,7 @@
"work.retry": "重试",
"work.topicGroup.other": "其他",
"work.totalCost": "累计开销 {{cost}}",
+ "work.type.canvas": "画布",
"work.type.document": "文档",
"work.type.file": "文件",
"work.type.githubIssue": "GitHub Issue",
diff --git a/locales/zh-CN/plugin.json b/locales/zh-CN/plugin.json
index e907a85cd89..eedd809791a 100644
--- a/locales/zh-CN/plugin.json
+++ b/locales/zh-CN/plugin.json
@@ -241,6 +241,12 @@
"builtins.lobe-browser.apiName.scroll": "滚动了页面",
"builtins.lobe-browser.apiName.snapshot": "读取了页面元素",
"builtins.lobe-browser.title": "浏览器",
+ "builtins.lobe-canvas.apiName.createCanvas": "创建画布",
+ "builtins.lobe-canvas.apiName.listCanvases": "列出画布",
+ "builtins.lobe-canvas.apiName.readCanvas": "读取画布",
+ "builtins.lobe-canvas.apiName.readCanvasGuide": "读取画布指南",
+ "builtins.lobe-canvas.apiName.updateCanvas": "更新画布",
+ "builtins.lobe-canvas.title": "画布",
"builtins.lobe-claude-code.agent.instruction": "指令",
"builtins.lobe-claude-code.agent.result": "结果",
"builtins.lobe-claude-code.askUserQuestion.noAnswer": "未收到回答——模型在没有用户输入的情况下继续。",
diff --git a/locales/zh-CN/portal.json b/locales/zh-CN/portal.json
index b6345156f59..2fb401fd5c7 100644
--- a/locales/zh-CN/portal.json
+++ b/locales/zh-CN/portal.json
@@ -30,6 +30,22 @@
"artifacts.svg.copySuccess": "图片复制成功",
"artifacts.svg.download.png": "下载为 PNG",
"artifacts.svg.download.svg": "下载为 SVG",
+ "canvas.frameTitle": "画布预览",
+ "canvas.generating": "正在生成 v{{version}}…",
+ "canvas.menu.openInTab": "在新标签页打开",
+ "canvas.menu.openPublic": "打开公开链接",
+ "canvas.menu.publish": "将 v{{version}} 发布到公开链接",
+ "canvas.menu.publishing": "发布中…",
+ "canvas.menu.updatePublic": "将公开链接更新到 v{{version}}",
+ "canvas.menu.versionItem": "v{{version}} · {{date}}",
+ "canvas.menu.versions": "版本历史",
+ "canvas.notFound": "这个画布不存在或你没有访问权限。",
+ "canvas.publish.failed": "发布失败,请重试",
+ "canvas.publish.note": "之后的新版本在你更新公开链接前保持私密。",
+ "canvas.publish.success": "已发布 v{{version}}",
+ "canvas.runtimeErrors": "画布运行时报错({{count}})",
+ "canvas.runtimeErrorsHint": "部分组件未能渲染。可以让助手修复画布,或展开查看详情。",
+ "canvas.title": "画布",
"document.saveConflict": "文档已在别处更新,正在刷新为最新版本",
"document.todos.allCompleted": "所有任务已完成",
"document.todos.title": "任务",
diff --git a/package.json b/package.json
index 41e48b9abb9..607626f1332 100644
--- a/package.json
+++ b/package.json
@@ -45,12 +45,13 @@
"alint": "alint",
"alint:audit": "alint --config alint.audit.toml --format json --rule-concurrency 48 src packages",
"alint:setup": "bun packages/alint/setup.ts",
- "build": "bun run build:spa && bun run build:spa:auth && bun run build:spa:workbench && bun run build:spa:share && bun run build:spa:copy && bun run build:next",
+ "build": "bun run build:canvas-runtime && bun run build:spa && bun run build:spa:auth && bun run build:spa:workbench && bun run build:spa:share && bun run build:spa:copy && bun run build:next",
"build:analyze": "cross-env NODE_OPTIONS=--max-old-space-size=81920 next experimental-analyze",
- "build:docker": "pnpm run build:spa && pnpm run build:spa:mobile && pnpm run build:spa:auth && pnpm run build:spa:workbench && pnpm run build:spa:share && cross-env WORKBENCH_REQUIRED=1 SHARE_REQUIRED=1 pnpm run build:spa:copy && cross-env NODE_OPTIONS=--max-old-space-size=8192 DOCKER=true next build",
+ "build:canvas-runtime": "pnpm --filter @lobechat/canvas-runtime build",
+ "build:docker": "pnpm run build:canvas-runtime && pnpm run build:spa && pnpm run build:spa:mobile && pnpm run build:spa:auth && pnpm run build:spa:workbench && pnpm run build:spa:share && cross-env WORKBENCH_REQUIRED=1 SHARE_REQUIRED=1 pnpm run build:spa:copy && cross-env NODE_OPTIONS=--max-old-space-size=8192 DOCKER=true next build",
"build:next": "cross-env NODE_OPTIONS=--max-old-space-size=7168 bun run build:next:raw",
"build:next:raw": "next build",
- "build:raw": "bun run build:spa:raw && bun run build:spa:auth && bun run build:spa:workbench && bun run build:spa:share && bun run build:spa:copy && bun run build:next:raw",
+ "build:raw": "bun run build:canvas-runtime && bun run build:spa:raw && bun run build:spa:auth && bun run build:spa:workbench && bun run build:spa:share && bun run build:spa:copy && bun run build:next:raw",
"build:spa": "cross-env NODE_OPTIONS=--max-old-space-size=8192 pnpm run build:spa:raw",
"build:spa:auth": "rm -rf public/_spa public/_spa-auth && cross-env NODE_OPTIONS=--max-old-space-size=8192 AUTH=true vite build",
"build:spa:copy": "tsx scripts/copySpaBuild.mts && tsx scripts/generateSpaTemplates.mts",
@@ -247,6 +248,7 @@
"@lobechat/builtin-tool-brief": "workspace:*",
"@lobechat/builtin-tool-browser": "workspace:*",
"@lobechat/builtin-tool-calculator": "workspace:*",
+ "@lobechat/builtin-tool-canvas": "workspace:*",
"@lobechat/builtin-tool-claude-code": "workspace:*",
"@lobechat/builtin-tool-cloud-sandbox": "workspace:*",
"@lobechat/builtin-tool-creds": "workspace:*",
@@ -278,6 +280,7 @@
"@lobechat/business-const": "workspace:*",
"@lobechat/business-model-bank": "workspace:*",
"@lobechat/business-model-runtime": "workspace:*",
+ "@lobechat/canvas": "workspace:*",
"@lobechat/chat-adapter-feishu": "workspace:*",
"@lobechat/chat-adapter-imessage": "workspace:*",
"@lobechat/chat-adapter-line": "workspace:*",
diff --git a/packages/builtin-skills/src/artifacts/content.ts b/packages/builtin-skills/src/artifacts/content.ts
index f618d2aa43a..63267c3e491 100644
--- a/packages/builtin-skills/src/artifacts/content.ts
+++ b/packages/builtin-skills/src/artifacts/content.ts
@@ -8,7 +8,9 @@ The assistant possesses two ways to present visual and interactive content: **Ar
Both modes are first-class:
- **Inline preview** — a fenced \`html\` code block that the chat renders in the message flow. **Default for explanation**: teaching a concept, showing how something behaves, illustrating a mechanism, comparing states, or any demo the reader looks at *while reading the answer*. Placing the visual next to the sentence that explains it is what makes an explanation comfortable to read.
-- **Artifact** — a \`<lobeArtifact>\` card that opens in its own panel. **Default for deliverables**: applications, dashboards, tools, multi-file projects — anything the user keeps, reopens, iterates on or downloads.
+- **Artifact** — a \`<lobeArtifact>\` card that opens in its own panel. **Default for deliverables**: applications, tools, games, multi-file projects — anything the user keeps, reopens, iterates on or downloads.
+
+Reports, analyses, comparisons and data dashboards are not this skill's job when the **lobe-canvas** tool is available (listed in available tools): activate it and build a Canvas, which is versioned and can be published as a public page. Fall back to an Artifact only when Canvas is unavailable.
Rule of thumb: if the visual *explains something*, render it inline; if the visual *is the thing the user came to build*, make it an Artifact. When it is genuinely both (an explainer the user then asks to keep and extend), start inline and promote it to an Artifact once they ask to build on it — do not open a panel for a picture the user only wants to understand.
@@ -16,7 +18,7 @@ For a self-contained preview, emit the result directly after loading these instr
## When to Create an Artifact (Qualifying Content)
Target content that serves as a distinct visual or interactive "deliverable." Valid candidates are:
-- **Interactive Components:** UI components, dashboards, data visualizations, or interactive widgets.
+- **Interactive Components:** UI components, interactive widgets, or dashboards and data visualizations when Canvas is unavailable.
- **Visual Content:** SVG graphics, illustrations, icons, or diagrams the user wants to keep, reuse or hand off.
- **Web Pages:** Landing pages, forms, or any HTML-based layouts.
- **Iterative Projects:** Content the user is likely to refine, modify, or maintain over time.
@@ -36,7 +38,7 @@ Do NOT generate an artifact or an inline preview for:
- **Capability Mapping:**
- If asked for "SVG", provide an SVG artifact, unless the drawing only illustrates the explanation — then wrap it in a minimal inline HTML document. Raster image files use the available image-generation or file tools.
- If asked for "websites" or "web pages" as a deliverable, provide HTML or React artifacts. A page whose only purpose is to demonstrate an idea is an inline preview.
- - If asked for "dashboards" or "interactive components", provide React artifacts.
+ - If asked for reports, analyses, comparisons or "dashboards", use Canvas when it is available; otherwise provide React artifacts. For "interactive components", provide React artifacts.
- If asked for a code snippet or code explanation, provide it inline as markdown code blocks, NOT as an artifact. "Write code for a playable web game" still requests a runnable deliverable.
- **Safety:** Do NOT generate hazardous content. Apply the same safety standards as text responses.
diff --git a/packages/builtin-skills/src/artifacts/index.ts b/packages/builtin-skills/src/artifacts/index.ts
index e24cb2c4694..dab6e17ba16 100644
--- a/packages/builtin-skills/src/artifacts/index.ts
+++ b/packages/builtin-skills/src/artifacts/index.ts
@@ -5,6 +5,7 @@ import { ArtifactsIdentifier, ArtifactsManifest } from './manifest';
export { ArtifactsIdentifier };
+/** Superseded by Canvas (`lobe-canvas`); kept so existing conversations keep rendering. */
export const ArtifactsSkill: BuiltinSkill = {
...ArtifactsManifest,
content: systemPrompt,
diff --git a/packages/builtin-skills/src/artifacts/manifest.ts b/packages/builtin-skills/src/artifacts/manifest.ts
index fc69d1d460d..bbc1d9245ac 100644
--- a/packages/builtin-skills/src/artifacts/manifest.ts
+++ b/packages/builtin-skills/src/artifacts/manifest.ts
@@ -5,7 +5,7 @@ export const ArtifactsIdentifier = 'lobe-artifacts';
export const ArtifactsManifest: BuiltinSkillManifest = {
avatar: `data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iMTAyNCIgaGVpZ2h0PSIxMDI0IiBmaWxsPSJub25lIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciPjxyZWN0IHdpZHRoPSIxMDI0IiBoZWlnaHQ9IjEwMjQiIHJ4PSI1MTIiIGZpbGw9IiNDNDc4NUIiLz48cGF0aCBkPSJNNTEyIDYxMmM1NS4yMjggMCAxMDAtNDQuNzcyIDEwMC0xMDBzLTQ0Ljc3Mi0xMDAtMTAwLTEwMC0xMDAgNDQuNzcyLTEwMCAxMDAgNDQuNzcyIDEwMCAxMDAgMTAwWiIgc3Ryb2tlPSIjZmZmIiBzdHJva2Utd2lkdGg9IjU2IiBzdHJva2UtbGluZWNhcD0icm91bmQiIHN0cm9rZS1saW5lam9pbj0icm91bmQiLz48cGF0aCBkPSJNNTEyIDY2MmExNDkuOTk4IDE0OS45OTggMCAwIDEtOTIuNTk3IDEzOC41ODIgMTUwLjAwMiAxNTAuMDAyIDAgMCAxLTIwNC41MjEtMTA5LjMxOCAxNDkuOTk4IDE0OS45OTggMCAwIDEgNjMuNzgzLTE1My45ODRBMTQ5Ljk5MiAxNDkuOTkyIDAgMCAxIDM2MiA1MTJhMTQ5Ljk5OSAxNDkuOTk5IDAgMSAxIDE1MC0xNTAgMTQ5Ljk5OCAxNDkuOTk4IDAgMCAxIDI5Ny4xMTgtMjkuMjYzQTE1MCAxNTAgMCAwIDEgNjYyIDUxMmMyOS42NjcgMCA1OC42NjggOC43OTcgODMuMzM1IDI1LjI4YTE0OS45OTUgMTQ5Ljk5NSAwIDAgMSA2My43ODMgMTUzLjk4NEExNTAgMTUwIDAgMCAxIDUxMiA2NjJaTTUxMiAzNjJ2NTBNMzYyIDUxMmg1ME02NjIgNTEyaC01ME01MTIgNjYydi01ME0zNzguNjY3IDM3OC42NjdsNjIuNjY2IDYyLjY2Nk01ODIuNjY3IDQ0MS4zMzNsNjIuNjY2LTYyLjY2Nk0zNzguNjY3IDY0NS4zMzNsNjIuNjY2LTYyLjY2Nk01ODIuNjY3IDU4Mi42NjdsNjIuNjY2IDYyLjY2NiIgc3Ryb2tlPSIjZmZmIiBzdHJva2Utd2lkdGg9IjU2IiBzdHJva2UtbGluZWNhcD0icm91bmQiIHN0cm9rZS1saW5lam9pbj0icm91bmQiLz48L3N2Zz4=`,
description:
- 'Create directly viewable web pages, browser games, SVG graphics or animations, and React components, and decide how a visual is delivered. Explanatory visuals default to an inline HTML preview rendered inside the reply (a complete html code block), which reads better than a separate panel; deliverables the user keeps, reopens or iterates on become Artifacts. Use files only when the user explicitly requests a download; HTML/SVG specify the implementation format, not download intent. Do not add a downloadable file or sandbox preparation to a self-contained preview request. Answer code snippets and explanations directly without loading this skill.',
+ 'Create directly viewable web pages, browser games, SVG graphics or animations, and React components, and decide how a visual is delivered. Explanatory visuals default to an inline HTML preview rendered inside the reply (a complete html code block), which reads better than a separate panel; deliverables the user keeps, reopens or iterates on become Artifacts. Reports, analyses, comparisons and data dashboards the user reads, revisits or shares belong in Canvas (activate the lobe-canvas tool) whenever it is listed in available tools; do not load this skill for them. Use files only when the user explicitly requests a download; HTML/SVG specify the implementation format, not download intent. Do not add a downloadable file or sandbox preparation to a self-contained preview request. Answer code snippets and explanations directly without loading this skill.',
identifier: ArtifactsIdentifier,
name: 'artifacts',
source: 'builtin',
diff --git a/packages/builtin-tool-canvas/package.json b/packages/builtin-tool-canvas/package.json
new file mode 100644
index 00000000000..9f908576e51
--- /dev/null
+++ b/packages/builtin-tool-canvas/package.json
@@ -0,0 +1,24 @@
+{
+ "name": "@lobechat/builtin-tool-canvas",
+ "version": "1.0.0",
+ "private": true,
+ "exports": {
+ ".": "./src/index.ts",
+ "./client": "./src/client/index.ts",
+ "./executionRuntime": "./src/ExecutionRuntime/index.ts"
+ },
+ "main": "./src/index.ts",
+ "dependencies": {
+ "@lobechat/canvas": "workspace:*"
+ },
+ "devDependencies": {
+ "@lobechat/types": "workspace:*"
+ },
+ "peerDependencies": {
+ "@lobehub/ui": "^6.0.4",
+ "@stylexjs/stylex": "*",
+ "lucide-react": "*",
+ "react": "*",
+ "react-i18next": "*"
+ }
+}
diff --git a/packages/builtin-tool-canvas/src/ExecutionRuntime/index.test.ts b/packages/builtin-tool-canvas/src/ExecutionRuntime/index.test.ts
new file mode 100644
index 00000000000..8ae533d1738
--- /dev/null
+++ b/packages/builtin-tool-canvas/src/ExecutionRuntime/index.test.ts
@@ -0,0 +1,177 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { CanvasExecutionRuntime, type CanvasToolService } from '.';
+
+const metadata = {
+ entry: 'index.html',
+ fileCount: 1,
+ manifestKey: 'canvas/u/cvs_1/manifests/a.json',
+ runtimeMajor: 1,
+ totalSize: 120,
+};
+
+const createService = (overrides: Partial<CanvasToolService> = {}): CanvasToolService => ({
+ create: vi.fn().mockResolvedValue({
+ canvasId: 'cvs_1',
+ description: 'Up 23%',
+ metadata,
+ ok: true,
+ title: 'Cost report',
+ }),
+ hasReadGuide: vi.fn().mockResolvedValue(true),
+ list: vi.fn().mockResolvedValue([]),
+ read: vi.fn().mockResolvedValue(undefined),
+ update: vi.fn().mockResolvedValue({
+ canvasId: 'cvs_1',
+ description: 'Up 23%',
+ metadata,
+ ok: true,
+ title: 'Cost report',
+ }),
+ ...overrides,
+});
+
+const createParams = {
+ files: [{ content: '<lobe-alert>x</lobe-alert>', path: 'index.html' }],
+ title: 'Cost report',
+};
+
+describe('CanvasExecutionRuntime', () => {
+ it('returns the guide with the generated component reference', async () => {
+ const runtime = new CanvasExecutionRuntime(createService());
+
+ const result = await runtime.readCanvasGuide();
+
+ expect(result.success).toBe(true);
+ expect(result.content).toContain('### <lobe-stat>');
+ expect(result.content).toContain('Conclusion first');
+ expect(result.state).toEqual({ guideRead: true });
+ });
+
+ it('refuses to write before the guide was read in this conversation', async () => {
+ const service = createService({ hasReadGuide: vi.fn().mockResolvedValue(false) });
+ const runtime = new CanvasExecutionRuntime(service);
+
+ const result = await runtime.createCanvas(createParams);
+
+ expect(result.success).toBe(false);
+ expect(result.content).toContain('readCanvasGuide');
+ expect(service.create).not.toHaveBeenCalled();
+ });
+
+ it('creates a canvas and registers its version as a Work', async () => {
+ const onWorkRegistration = vi.fn();
+ const runtime = new CanvasExecutionRuntime(createService());
+
+ const result = await runtime.createCanvas(createParams, { onWorkRegistration });
+
+ expect(result.success).toBe(true);
+ expect(result.content).toContain('cvs_1');
+ expect(result.state).toMatchObject({ canvasId: 'cvs_1', metadata });
+ expect(onWorkRegistration).toHaveBeenCalledWith({
+ action: 'register',
+ canvas: {
+ canvasId: 'cvs_1',
+ description: 'Up 23%',
+ metadata,
+ title: 'Cost report',
+ toolName: 'createCanvas',
+ },
+ type: 'canvas',
+ });
+ });
+
+ it('reports validation issues with their location and registers nothing', async () => {
+ const onWorkRegistration = vi.fn();
+ const runtime = new CanvasExecutionRuntime(
+ createService({
+ create: vi.fn().mockResolvedValue({
+ issues: [
+ {
+ file: 'index.html',
+ line: 3,
+ message: '<lobe-nope> is not a Canvas component.',
+ rule: 'unknown-component',
+ },
+ ],
+ ok: false,
+ }),
+ }),
+ );
+
+ const result = await runtime.createCanvas(createParams, { onWorkRegistration });
+
+ expect(result.success).toBe(false);
+ expect(result.content).toContain('index.html:3');
+ expect(result.content).toContain('<lobe-nope> is not a Canvas component.');
+ expect(result.state.issues).toHaveLength(1);
+ expect(onWorkRegistration).not.toHaveBeenCalled();
+ });
+
+ it('updates a canvas and registers the new version under updateCanvas', async () => {
+ const onWorkRegistration = vi.fn();
+ const service = createService();
+ const runtime = new CanvasExecutionRuntime(service);
+
+ const result = await runtime.updateCanvas(
+ { canvasId: 'cvs_1', edits: [{ newText: 'b', oldText: 'a', path: 'index.html' }] },
+ { onWorkRegistration },
+ );
+
+ expect(result.success).toBe(true);
+ expect(service.update).toHaveBeenCalledWith(expect.objectContaining({ canvasId: 'cvs_1' }));
+ expect(onWorkRegistration.mock.calls[0][0].canvas.toolName).toBe('updateCanvas');
+ });
+
+ it('reads a canvas file listing and text contents', async () => {
+ const runtime = new CanvasExecutionRuntime(
+ createService({
+ read: vi.fn().mockResolvedValue({
+ canvasId: 'cvs_1',
+ description: null,
+ files: [
+ { path: 'index.html', size: 30 },
+ { path: 'logo.png', size: 900 },
+ ],
+ texts: [{ content: '<h1>Hi</h1>', path: 'index.html' }],
+ title: 'Cost report',
+ }),
+ }),
+ );
+
+ const result = await runtime.readCanvas({ canvasId: 'cvs_1' });
+
+ expect(result.success).toBe(true);
+ expect(result.content).toContain('logo.png (900 bytes)');
+ expect(result.content).toContain('<h1>Hi</h1>');
+ });
+
+ it('fails clearly when the canvas does not exist', async () => {
+ const runtime = new CanvasExecutionRuntime(createService());
+
+ const result = await runtime.readCanvas({ canvasId: 'cvs_missing' });
+
+ expect(result).toMatchObject({ success: false });
+ expect(result.content).toContain('cvs_missing');
+ });
+
+ it('lists canvases', async () => {
+ const runtime = new CanvasExecutionRuntime(
+ createService({
+ list: vi.fn().mockResolvedValue([
+ {
+ canvasId: 'cvs_1',
+ description: 'Up',
+ title: 'Cost report',
+ updatedAt: '2026-10-20T10:00:00.000Z',
+ },
+ ]),
+ }),
+ );
+
+ const result = await runtime.listCanvases();
+
+ expect(result.content).toContain('cvs_1');
+ expect(result.content).toContain('Cost report');
+ });
+});
diff --git a/packages/builtin-tool-canvas/src/ExecutionRuntime/index.ts b/packages/builtin-tool-canvas/src/ExecutionRuntime/index.ts
new file mode 100644
index 00000000000..66fb7a982f0
--- /dev/null
+++ b/packages/builtin-tool-canvas/src/ExecutionRuntime/index.ts
@@ -0,0 +1,137 @@
+import type { CanvasIssue } from '@lobechat/canvas';
+import type { BuiltinServerRuntimeOutput, WorkRegistrationIntent } from '@lobechat/types';
+
+import { buildCanvasGuide } from '../guide';
+import {
+ CanvasApiName,
+ type CanvasReadOutcome,
+ type CanvasSaveOutcome,
+ type CanvasSummary,
+ type CreateCanvasParams,
+ type ReadCanvasParams,
+ type UpdateCanvasParams,
+} from '../types';
+
+export interface CanvasToolService {
+ create: (params: CreateCanvasParams) => Promise<CanvasSaveOutcome>;
+ hasReadGuide: () => Promise<boolean>;
+ list: () => Promise<CanvasSummary[]>;
+ read: (params: ReadCanvasParams) => Promise<CanvasReadOutcome | undefined>;
+ update: (params: UpdateCanvasParams) => Promise<CanvasSaveOutcome>;
+}
+
+interface CanvasRuntimeContext {
+ onWorkRegistration?: (intent: WorkRegistrationIntent) => void;
+}
+
+const GUIDE_REQUIRED = `Call ${CanvasApiName.readCanvasGuide} first: it lists the components and rules a Canvas must follow. Then call this again.`;
+
+const formatIssues = (issues: CanvasIssue[]) =>
+ issues
+ .map((issue) => {
+ const location = issue.file
+ ? `${issue.file}${issue.line ? `:${issue.line}` : ''}`
+ : 'project';
+ return `- ${location} [${issue.rule}] ${issue.message}`;
+ })
+ .join('\n');
+
+export class CanvasExecutionRuntime {
+ private service: CanvasToolService;
+
+ constructor(service: CanvasToolService) {
+ this.service = service;
+ }
+
+ async readCanvasGuide(): Promise<BuiltinServerRuntimeOutput> {
+ return { content: buildCanvasGuide(), state: { guideRead: true }, success: true };
+ }
+
+ async createCanvas(
+ params: CreateCanvasParams,
+ context?: CanvasRuntimeContext,
+ ): Promise<BuiltinServerRuntimeOutput> {
+ if (!(await this.service.hasReadGuide())) return { content: GUIDE_REQUIRED, success: false };
+ return this.finishSave(CanvasApiName.createCanvas, await this.service.create(params), context);
+ }
+
+ async updateCanvas(
+ params: UpdateCanvasParams,
+ context?: CanvasRuntimeContext,
+ ): Promise<BuiltinServerRuntimeOutput> {
+ if (!(await this.service.hasReadGuide())) return { content: GUIDE_REQUIRED, success: false };
+ return this.finishSave(CanvasApiName.updateCanvas, await this.service.update(params), context);
+ }
+
+ async readCanvas(params: ReadCanvasParams): Promise<BuiltinServerRuntimeOutput> {
+ const canvas = await this.service.read(params);
+ if (!canvas) {
+ return {
+ content: `Canvas "${params.canvasId}" was not found. Call ${CanvasApiName.listCanvases} to see the available ones.`,
+ success: false,
+ };
+ }
+
+ const listing = canvas.files.map((file) => `- ${file.path} (${file.size} bytes)`).join('\n');
+ const texts = canvas.texts
+ .map((file) => `<file path="${file.path}">\n${file.content}\n</file>`)
+ .join('\n\n');
+
+ return {
+ content:
+ `Canvas ${canvas.canvasId}: ${canvas.title ?? 'Untitled'}\n\nFiles:\n${listing}\n\n${texts}`.trim(),
+ state: { canvasId: canvas.canvasId, files: canvas.files },
+ success: true,
+ };
+ }
+
+ async listCanvases(): Promise<BuiltinServerRuntimeOutput> {
+ const canvases = await this.service.list();
+ if (canvases.length === 0)
+ return { content: 'No canvases yet.', state: { canvases }, success: true };
+
+ return {
+ content: canvases
+ .map(
+ (canvas) =>
+ `- ${canvas.canvasId}: ${canvas.title ?? 'Untitled'}${canvas.description ? ` — ${canvas.description}` : ''} (updated ${canvas.updatedAt})`,
+ )
+ .join('\n'),
+ state: { canvases },
+ success: true,
+ };
+ }
+
+ private finishSave(
+ toolName: string,
+ outcome: CanvasSaveOutcome,
+ context?: CanvasRuntimeContext,
+ ): BuiltinServerRuntimeOutput {
+ if (!outcome.ok) {
+ const details = outcome.issues.length > 0 ? `\n${formatIssues(outcome.issues)}` : '';
+ return {
+ content: `The canvas was not saved.${outcome.error ? ` ${outcome.error}` : ''}${details}\nFix these and save again; the previous version is unchanged.`,
+ state: { issues: outcome.issues },
+ success: false,
+ };
+ }
+
+ context?.onWorkRegistration?.({
+ action: 'register',
+ canvas: {
+ canvasId: outcome.canvasId,
+ description: outcome.description,
+ metadata: outcome.metadata,
+ title: outcome.title,
+ toolName,
+ },
+ type: 'canvas',
+ });
+
+ return {
+ content: `Saved canvas ${outcome.canvasId} "${outcome.title}" (${outcome.metadata.fileCount} files). The user sees it as a card under your reply. Use updateCanvas with canvasId "${outcome.canvasId}" for changes.`,
+ state: { canvasId: outcome.canvasId, metadata: outcome.metadata, title: outcome.title },
+ success: true,
+ };
+ }
+}
diff --git a/packages/builtin-tool-canvas/src/client/Inspector/index.tsx b/packages/builtin-tool-canvas/src/client/Inspector/index.tsx
new file mode 100644
index 00000000000..64e0a63ab37
--- /dev/null
+++ b/packages/builtin-tool-canvas/src/client/Inspector/index.tsx
@@ -0,0 +1,63 @@
+'use client';
+
+import type { BuiltinInspector, BuiltinInspectorProps } from '@lobechat/types';
+import { cx } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { inspectorTextStyles, shinyTextStyles } from '@/styles';
+
+import type { CanvasApiNameType, CanvasSaveState } from '../../types';
+import { CanvasApiName, CanvasIdentifier } from '../../types';
+
+const styles = stylex.create({
+ chip: {
+ backgroundColor: cssVar.colorFillTertiary,
+ borderRadius: 999,
+ color: cssVar.colorTextSecondary,
+ flexShrink: 1,
+ fontSize: 12,
+ marginInlineStart: 6,
+ minWidth: 0,
+ overflow: 'hidden',
+ paddingBlock: 2,
+ paddingInline: 8,
+ textOverflow: 'ellipsis',
+ whiteSpace: 'nowrap',
+ },
+ failed: {
+ backgroundColor: cssVar.colorErrorBg,
+ color: cssVar.colorError,
+ },
+});
+
+type Props = BuiltinInspectorProps<Record<string, any>, CanvasSaveState>;
+
+const createInspector = (apiName: CanvasApiNameType) => {
+ const Inspector = memo<Props>((props) => {
+ const { t } = useTranslation('plugin');
+ const args = { ...props.partialArgs, ...props.args };
+ const issueCount = props.pluginState?.issues?.length ?? 0;
+ const isSave = apiName === CanvasApiName.createCanvas || apiName === CanvasApiName.updateCanvas;
+ const chip = isSave ? (props.pluginState?.title ?? args.title ?? args.canvasId) : args.canvasId;
+ const busy = !!(props.isArgumentsStreaming || props.isLoading);
+
+ return (
+ <div className={inspectorTextStyles.root}>
+ <span className={cx(busy && shinyTextStyles.shinyText)}>
+ {t(`builtins.${CanvasIdentifier}.apiName.${apiName}`)}
+ </span>
+ {chip && <span {...stylex.props(styles.chip)}>{chip}</span>}
+ {issueCount > 0 && <span {...stylex.props(styles.chip, styles.failed)}>{issueCount}</span>}
+ </div>
+ );
+ });
+ Inspector.displayName = `Canvas${apiName}Inspector`;
+ return Inspector as unknown as BuiltinInspector;
+};
+
+export const CanvasInspectors: Record<string, BuiltinInspector> = Object.fromEntries(
+ Object.values(CanvasApiName).map((apiName) => [apiName, createInspector(apiName)]),
+);
diff --git a/packages/builtin-tool-canvas/src/client/index.ts b/packages/builtin-tool-canvas/src/client/index.ts
new file mode 100644
index 00000000000..c29ce1e0e67
--- /dev/null
+++ b/packages/builtin-tool-canvas/src/client/index.ts
@@ -0,0 +1,3 @@
+export { CanvasManifest } from '../manifest';
+export * from '../types';
+export { CanvasInspectors } from './Inspector';
diff --git a/packages/builtin-tool-canvas/src/guide.ts b/packages/builtin-tool-canvas/src/guide.ts
new file mode 100644
index 00000000000..acf79717c0a
--- /dev/null
+++ b/packages/builtin-tool-canvas/src/guide.ts
@@ -0,0 +1,59 @@
+import { buildCanvasComponentReference, CANVAS_LIMITS, CANVAS_PALETTE } from '@lobechat/canvas';
+
+const rules = `# Canvas guide
+
+A Canvas is a small web project (HTML, CSS, JS, JSON data and assets) that renders inside LobeHub with LobeHub's own components. It is shown as a card under your reply and opens in the side panel. Use it for reports and analyses the user will read, compare or come back to — not for a short answer that fits in the reply.
+
+## Project
+
+- The entry page is \`index.html\`. Further pages, \`.css\`, \`.js\`, \`.json\` and assets (png/jpg/svg/webp/fonts) live next to it and are referenced by relative paths.
+- To use a file that already exists — one the user attached (\`<file id>\`, \`<image ref>\`) or one in their files — write it with \`fileRef\` instead of \`content\`, e.g. \`{ "path": "img/photo.jpg", "fileRef": "msg_xxx.image_1" }\`, then reference \`img/photo.jpg\` from the page. Never paste such a file as base64. If a fileRef cannot be resolved the save is refused with the reason; drop or replace that asset and save again.
+- No build step: write plain HTML, CSS and JS that runs as written. No npm, no imports from URLs, no frameworks.
+- There is no network: \`fetch\`, \`XMLHttpRequest\`, \`WebSocket\`, remote scripts, remote images and remote stylesheets are rejected. Put the data in the project: inline JSON attributes, a \`<script type="application/json" data-prop="...">\` child, or a \`.json\` file referenced with a \`<name>-src\` attribute.
+- Do not add a \`<script>\` for the component runtime; the host injects it.
+- Limits: ${CANVAS_LIMITS.maxFiles} files, ${CANVAS_LIMITS.maxTextFileBytes / 1024} KB per text file, ${CANVAS_LIMITS.maxTotalBytes / 1024 / 1024} MB in total.
+
+## Components
+
+- Build with \`<lobe-*>\` components (reference below). Plain \`h1\`–\`h4\`, \`p\`, \`ul\`, \`ol\`, \`a\`, \`blockquote\` and \`table\` are styled to match; use them for prose.
+- Only the tags and attributes listed below exist. An unknown tag or attribute is rejected — never invent one.
+- Write every component with a closing tag: \`<lobe-divider></lobe-divider>\`, never \`<lobe-divider />\`.
+- Boolean attributes are written bare (\`<lobe-switch checked>\`). JSON attributes take single-quoted JSON: \`data='[{"a":1}]'\`.
+- JSON props can come from a child \`<script type="application/json" data-prop="data">…</script>\` or from a project file: \`data-src="./data/cost.json"\`.
+- Diagrams — flowcharts, sequences, state machines, architecture — are \`<lobe-mermaid>\` with Mermaid text. Do not draw them by hand with SVG.
+- \`<lobe-code>\` and \`<lobe-mermaid>\` hold plain text: write \`<\` as \`&lt;\` and \`&\` as \`&amp;\`. A tag inside them is rejected.
+- Colors follow the user's theme. Never hard-code colors on components (no \`style="color:#..."\`, no \`rgb()\`); use \`type\`, \`status\` or \`color\` attributes. Chart and tag colors are palette names: ${CANVAS_PALETTE.join(', ')}.
+
+## Report structure
+
+1. Conclusion first: one \`<lobe-alert>\` stating the answer in a sentence.
+2. Key numbers: up to four \`<lobe-stat>\` in a \`<lobe-grid>\`.
+3. Evidence: charts and tables that support the conclusion, each with a heading that says what it shows.
+4. Recommendation and risks, if the user needs to act.
+5. Sources and coverage: what data this used, its time range and what it leaves out.
+
+Prefer one clear chart over several similar ones. Real numbers only; never placeholder data.
+
+## Interactivity
+
+Controls (\`lobe-select\`, \`lobe-segmented\`, \`lobe-switch\`, \`lobe-input\`, \`lobe-slider\`, \`lobe-button\`, …) fire a bubbling \`lobe-change\` event whose \`detail.value\` is the new value. Listen in plain JS and update the page, for example toggling \`hidden\` on sections or setting a chart's \`data\` attribute:
+
+\`\`\`html
+<lobe-segmented id="view" value="chart"><lobe-option value="chart">Chart</lobe-option><lobe-option value="table">Table</lobe-option></lobe-segmented>
+<script>
+ document.querySelector('#view').addEventListener('lobe-change', (event) => {
+ document.querySelector('#chart').hidden = event.detail.value !== 'chart';
+ document.querySelector('#table').hidden = event.detail.value !== 'table';
+ });
+</script>
+\`\`\`
+
+## Editing
+
+- \`updateCanvas\` takes \`edits\` (exact \`oldText\` → \`newText\`, \`oldText\` must appear once), \`writes\` (whole files) and \`deletes\`. Prefer \`edits\` for small changes.
+- Every successful save is a new version; the user sees the previous one until the new one validates.
+- A rejected save lists each problem as \`file:line\`. Fix exactly those and save again.
+
+# Component reference`;
+
+export const buildCanvasGuide = () => `${rules}\n\n${buildCanvasComponentReference()}`;
diff --git a/packages/builtin-tool-canvas/src/index.ts b/packages/builtin-tool-canvas/src/index.ts
new file mode 100644
index 00000000000..24cc54d7e6b
--- /dev/null
+++ b/packages/builtin-tool-canvas/src/index.ts
@@ -0,0 +1,5 @@
+export type { CanvasToolService } from './ExecutionRuntime';
+export { buildCanvasGuide } from './guide';
+export { CanvasManifest } from './manifest';
+export { systemPrompt } from './systemRole';
+export * from './types';
diff --git a/packages/builtin-tool-canvas/src/manifest.ts b/packages/builtin-tool-canvas/src/manifest.ts
new file mode 100644
index 00000000000..678a2b17518
--- /dev/null
+++ b/packages/builtin-tool-canvas/src/manifest.ts
@@ -0,0 +1,136 @@
+import type { BuiltinToolManifest } from '@lobechat/types';
+
+import { systemPrompt } from './systemRole';
+import { CanvasApiName, CanvasIdentifier } from './types';
+
+const canvasIdSchema = {
+ description: 'Canvas id returned by createCanvas or listCanvases.',
+ type: 'string',
+};
+
+const fileWriteSchema = {
+ additionalProperties: false,
+ properties: {
+ content: {
+ description:
+ 'Full file content. Base64 when encoding is "base64". Omit when fileRef is given.',
+ type: 'string',
+ },
+ encoding: {
+ description: 'Use "base64" for small generated binary assets. Defaults to utf8.',
+ enum: ['utf8', 'base64'],
+ type: 'string',
+ },
+ fileRef: {
+ description:
+ 'Copy an existing file into the project instead of writing content: a file id from <file id="..."> or a media ref from <image ref="..."> in this conversation.',
+ type: 'string',
+ },
+ path: {
+ description: 'Project-relative path, e.g. "index.html" or "img/logo.png".',
+ type: 'string',
+ },
+ },
+ required: ['path'],
+ type: 'object',
+};
+
+export const CanvasManifest: BuiltinToolManifest = {
+ api: [
+ {
+ description:
+ 'Return the Canvas rules and the full component reference. Call once per conversation before createCanvas or updateCanvas; they are refused until you have.',
+ name: CanvasApiName.readCanvasGuide,
+ parameters: { additionalProperties: false, properties: {}, type: 'object' },
+ },
+ {
+ description:
+ 'Create a Canvas from project files. The project needs index.html. Files are validated against the component reference; a rejected save lists each problem as file:line and creates nothing.',
+ name: CanvasApiName.createCanvas,
+ parameters: {
+ additionalProperties: false,
+ properties: {
+ description: {
+ description: 'One-line summary shown on the card, e.g. the conclusion.',
+ type: 'string',
+ },
+ files: { description: 'Project files.', items: fileWriteSchema, type: 'array' },
+ title: { description: 'Short title shown on the card.', type: 'string' },
+ },
+ required: ['title', 'files'],
+ type: 'object',
+ },
+ },
+ {
+ description:
+ 'Change an existing Canvas. Edits replace exact text (oldText must appear exactly once in the file), writes replace or add whole files, deletes remove files. Applied together as one new version; a rejected save changes nothing.',
+ name: CanvasApiName.updateCanvas,
+ parameters: {
+ additionalProperties: false,
+ properties: {
+ canvasId: canvasIdSchema,
+ deletes: { description: 'Paths to delete.', items: { type: 'string' }, type: 'array' },
+ description: { description: 'New one-line summary.', type: 'string' },
+ edits: {
+ description: 'Exact-text replacements.',
+ items: {
+ additionalProperties: false,
+ properties: {
+ newText: { type: 'string' },
+ oldText: {
+ description: 'Text to replace; must appear exactly once.',
+ type: 'string',
+ },
+ path: { type: 'string' },
+ },
+ required: ['path', 'oldText', 'newText'],
+ type: 'object',
+ },
+ type: 'array',
+ },
+ title: { description: 'New title.', type: 'string' },
+ writes: {
+ description: 'Whole files to add or replace.',
+ items: fileWriteSchema,
+ type: 'array',
+ },
+ },
+ required: ['canvasId'],
+ type: 'object',
+ },
+ },
+ {
+ description:
+ "Read a Canvas's file list and the contents of its text files. Pass paths to read only some files.",
+ name: CanvasApiName.readCanvas,
+ parameters: {
+ additionalProperties: false,
+ properties: {
+ canvasId: canvasIdSchema,
+ paths: {
+ description: 'Files to read. Defaults to every text file.',
+ items: { type: 'string' },
+ type: 'array',
+ },
+ },
+ required: ['canvasId'],
+ type: 'object',
+ },
+ },
+ {
+ description: 'List the Canvases this agent has made, newest first.',
+ name: CanvasApiName.listCanvases,
+ parameters: { additionalProperties: false, properties: {}, type: 'object' },
+ },
+ ],
+ executors: ['server'],
+ identifier: CanvasIdentifier,
+ meta: {
+ avatar: '🖼️',
+ description:
+ 'Default for reports, analyses, comparisons and data dashboards: a versioned page built from LobeHub components that the user can revisit and publish. Prefer it over inline HTML or Artifacts for these',
+ title: 'Canvas',
+ },
+ systemRole: systemPrompt,
+ type: 'builtin',
+};
diff --git a/packages/builtin-tool-canvas/src/systemRole.ts b/packages/builtin-tool-canvas/src/systemRole.ts
new file mode 100644
index 00000000000..4e5b43a6f4c
--- /dev/null
+++ b/packages/builtin-tool-canvas/src/systemRole.ts
@@ -0,0 +1,16 @@
+export const systemPrompt = `You can build a Canvas: a report-style page made of LobeHub's own components, shown as a card under your reply and opened in the side panel. Use it when the answer is an analysis, comparison or report the user will read, filter or revisit; answer short questions in the reply instead.
+
+<tools>
+- **readCanvasGuide**: The rules and the full component reference. Required once per conversation before createCanvas / updateCanvas.
+- **createCanvas**: Create a Canvas from project files (index.html plus optional CSS/JS/JSON/assets).
+- **updateCanvas**: Change an existing Canvas with exact-text edits, whole-file writes or deletes. Each save is a new version.
+- **readCanvas**: Read a Canvas's file list and text files before editing it.
+- **listCanvases**: Canvases made by this agent, so you can continue one from another conversation.
+</tools>
+
+<workflow>
+1. readCanvasGuide (once per conversation).
+2. createCanvas, or readCanvas then updateCanvas for an existing one.
+3. If a save is rejected, fix exactly the listed problems and save again.
+4. In your reply, say in one or two sentences what the Canvas shows; do not repeat its content.
+</workflow>`;
diff --git a/packages/builtin-tool-canvas/src/types.ts b/packages/builtin-tool-canvas/src/types.ts
new file mode 100644
index 00000000000..306ff49c851
--- /dev/null
+++ b/packages/builtin-tool-canvas/src/types.ts
@@ -0,0 +1,68 @@
+import type { CanvasChangeSet, CanvasFileWrite, CanvasIssue } from '@lobechat/canvas';
+import type { CanvasWorkVersionMetadata } from '@lobechat/types';
+
+export const CanvasIdentifier = 'lobe-canvas';
+
+export const CanvasApiName = {
+ createCanvas: 'createCanvas',
+ listCanvases: 'listCanvases',
+ readCanvas: 'readCanvas',
+ readCanvasGuide: 'readCanvasGuide',
+ updateCanvas: 'updateCanvas',
+} as const;
+
+export type CanvasApiNameType = (typeof CanvasApiName)[keyof typeof CanvasApiName];
+
+export interface CreateCanvasParams {
+ description?: string;
+ files: CanvasFileWrite[];
+ title: string;
+}
+
+export interface UpdateCanvasParams extends CanvasChangeSet {
+ canvasId: string;
+ description?: string;
+ title?: string;
+}
+
+export interface ReadCanvasParams {
+ canvasId: string;
+ paths?: string[];
+}
+
+export interface CanvasFileSummary {
+ path: string;
+ size: number;
+}
+
+export interface CanvasSummary {
+ canvasId: string;
+ description: string | null;
+ title: string | null;
+ updatedAt: string;
+}
+
+export type CanvasSaveOutcome =
+ | { error?: string; issues: CanvasIssue[]; ok: false }
+ | {
+ canvasId: string;
+ description: string | null;
+ metadata: CanvasWorkVersionMetadata;
+ ok: true;
+ title: string;
+ };
+
+export interface CanvasReadOutcome {
+ canvasId: string;
+ description: string | null;
+ files: CanvasFileSummary[];
+ texts: { content: string; path: string }[];
+ title: string | null;
+}
+
+export interface CanvasSaveState {
+ canvasId?: string;
+ issues?: CanvasIssue[];
+ metadata?: CanvasWorkVersionMetadata;
+ title?: string;
+}
diff --git a/packages/builtin-tool-canvas/vitest.config.mts b/packages/builtin-tool-canvas/vitest.config.mts
new file mode 100644
index 00000000000..4ac6027d578
--- /dev/null
+++ b/packages/builtin-tool-canvas/vitest.config.mts
@@ -0,0 +1,7 @@
+import { defineConfig } from 'vitest/config';
+
+export default defineConfig({
+ test: {
+ environment: 'node',
+ },
+});
diff --git a/packages/builtin-tools/package.json b/packages/builtin-tools/package.json
index 62b2021be09..209b6bef206 100644
--- a/packages/builtin-tools/package.json
+++ b/packages/builtin-tools/package.json
@@ -32,6 +32,7 @@
"@lobechat/builtin-tool-auv": "workspace:*",
"@lobechat/builtin-tool-brief": "workspace:*",
"@lobechat/builtin-tool-browser": "workspace:*",
+ "@lobechat/builtin-tool-canvas": "workspace:*",
"@lobechat/builtin-tool-claude-code": "workspace:*",
"@lobechat/builtin-tool-cloud-sandbox": "workspace:*",
"@lobechat/builtin-tool-creds": "workspace:*",
diff --git a/packages/builtin-tools/src/identifiers.ts b/packages/builtin-tools/src/identifiers.ts
index c64a28624ef..d3eba35444b 100644
--- a/packages/builtin-tools/src/identifiers.ts
+++ b/packages/builtin-tools/src/identifiers.ts
@@ -13,6 +13,7 @@ import { AttachmentsManifest } from '@lobechat/builtin-tool-attachments';
import { AuvManifest } from '@lobechat/builtin-tool-auv';
import { BrowserManifest } from '@lobechat/builtin-tool-browser';
import { CalculatorManifest } from '@lobechat/builtin-tool-calculator/manifest';
+import { CanvasManifest } from '@lobechat/builtin-tool-canvas';
import { CloudSandboxManifest } from '@lobechat/builtin-tool-cloud-sandbox';
import { CredsManifest } from '@lobechat/builtin-tool-creds';
import { DashboardManifest } from '@lobechat/builtin-tool-dashboard';
@@ -47,6 +48,7 @@ export const builtinToolIdentifiers: string[] = [
AttachmentsManifest.identifier,
AuvManifest.identifier,
CalculatorManifest.identifier,
+ CanvasManifest.identifier,
CloudSandboxManifest.identifier,
CredsManifest.identifier,
DashboardManifest.identifier,
diff --git a/packages/builtin-tools/src/index.ts b/packages/builtin-tools/src/index.ts
index 9fc8c95f12f..68ab1a86aef 100644
--- a/packages/builtin-tools/src/index.ts
+++ b/packages/builtin-tools/src/index.ts
@@ -20,6 +20,7 @@ import { AuvManifest } from '@lobechat/builtin-tool-auv';
import { BriefManifest } from '@lobechat/builtin-tool-brief';
import { BrowserManifest } from '@lobechat/builtin-tool-browser';
import { CalculatorManifest } from '@lobechat/builtin-tool-calculator/manifest';
+import { CanvasManifest } from '@lobechat/builtin-tool-canvas';
import { CloudSandboxManifest } from '@lobechat/builtin-tool-cloud-sandbox';
import { CredsManifest } from '@lobechat/builtin-tool-creds';
import { DashboardManifest } from '@lobechat/builtin-tool-dashboard';
@@ -76,6 +77,7 @@ export const defaultToolIds = [
AgentDocumentsManifest.identifier,
TaskManifest.identifier,
LobeAgentManifest.identifier,
+ CanvasManifest.identifier,
];
/**
@@ -557,6 +559,11 @@ const builtinToolRegistry: LobeBuiltinTool[] = [
manifest: TaskManifest,
type: 'builtin',
},
+ {
+ identifier: CanvasManifest.identifier,
+ manifest: CanvasManifest,
+ type: 'builtin',
+ },
{
// Opt-in: pin it in the Tools popover, or the activator enables it when a
// user asks for monitoring — not a default so ordinary turns stay lean.
diff --git a/packages/builtin-tools/src/register.ts b/packages/builtin-tools/src/register.ts
index b7a52fea8f2..86e9810a77f 100644
--- a/packages/builtin-tools/src/register.ts
+++ b/packages/builtin-tools/src/register.ts
@@ -29,6 +29,7 @@ import {
BrowserManifest,
BrowserRenders,
} from '@lobechat/builtin-tool-browser/client';
+import { CanvasInspectors, CanvasManifest } from '@lobechat/builtin-tool-canvas/client';
import {
ClaudeCodeApiName,
ClaudeCodeIdentifier,
@@ -367,6 +368,7 @@ export const registerBuiltinToolSurfaces = (): void => {
>,
[SkillStoreManifest.identifier]: SkillStoreInspectors as Record<string, BuiltinInspector>,
[SkillsManifest.identifier]: SkillsInspectors as Record<string, BuiltinInspector>,
+ [CanvasManifest.identifier]: CanvasInspectors,
[DashboardManifest.identifier]: DashboardInspectors as Record<string, BuiltinInspector>,
[TaskManifest.identifier]: TaskInspectors as Record<string, BuiltinInspector>,
[UserInteractionIdentifier]: UserInteractionInspectors as Record<string, BuiltinInspector>,
diff --git a/packages/builtin-tools/src/workRegistration.test.ts b/packages/builtin-tools/src/workRegistration.test.ts
index 726033d223c..736f1a58db1 100644
--- a/packages/builtin-tools/src/workRegistration.test.ts
+++ b/packages/builtin-tools/src/workRegistration.test.ts
@@ -555,3 +555,82 @@ describe('dispatchWorkRegistrationIntent', () => {
});
});
});
+
+describe('dispatchWorkRegistrationIntent · canvas', () => {
+ const provenance: WorkRegistrationProvenance = {
+ agentId: 'agent-1',
+ cumulativeCost: 0.02,
+ messageId: 'msg-1',
+ rootOperationId: 'op-root',
+ threadId: 'thread-1',
+ toolCallId: 'call-1',
+ toolIdentifier: 'lobe-canvas',
+ toolName: 'createCanvas',
+ topicId: 'topic-1',
+ };
+
+ const intent: WorkRegistrationIntent = {
+ action: 'register',
+ canvas: {
+ canvasId: 'cvs_1',
+ description: 'Cost up',
+ metadata: {
+ entry: 'index.html',
+ fileCount: 1,
+ manifestKey: 'k',
+ runtimeMajor: 1,
+ totalSize: 10,
+ },
+ title: 'Cost report',
+ toolName: 'writeCanvasFiles',
+ },
+ type: 'canvas',
+ };
+
+ it('registers the canvas version with provenance', async () => {
+ const registerCanvas = vi.fn().mockResolvedValue(undefined);
+ await dispatchWorkRegistrationIntent(
+ intent,
+ {
+ deleteTaskWork: vi.fn(),
+ handleSkillToolResult: vi.fn(),
+ registerCanvas,
+ registerDocument: vi.fn(),
+ registerTask: vi.fn(),
+ },
+ provenance,
+ );
+
+ expect(registerCanvas).toHaveBeenCalledWith({
+ agentId: 'agent-1',
+ canvasId: 'cvs_1',
+ cumulativeCost: 0.02,
+ cumulativeUsage: undefined,
+ description: 'Cost up',
+ messageId: 'msg-1',
+ metadata: intent.type === 'canvas' ? intent.canvas.metadata : undefined,
+ rootOperationId: 'op-root',
+ threadId: 'thread-1',
+ title: 'Cost report',
+ toolCallId: 'call-1',
+ toolIdentifier: 'lobe-canvas',
+ toolName: 'writeCanvasFiles',
+ topicId: 'topic-1',
+ });
+ });
+
+ it('is a no-op when the side has no canvas port', async () => {
+ await expect(
+ dispatchWorkRegistrationIntent(
+ intent,
+ {
+ deleteTaskWork: vi.fn(),
+ handleSkillToolResult: vi.fn(),
+ registerDocument: vi.fn(),
+ registerTask: vi.fn(),
+ },
+ provenance,
+ ),
+ ).resolves.toBeUndefined();
+ });
+});
diff --git a/packages/builtin-tools/src/workRegistration.ts b/packages/builtin-tools/src/workRegistration.ts
index f15931c8e50..829ca4af3d8 100644
--- a/packages/builtin-tools/src/workRegistration.ts
+++ b/packages/builtin-tools/src/workRegistration.ts
@@ -6,6 +6,7 @@ import type {
PluginApiWorkAction,
PluginApiWorkConfig,
PluginApiWorkResourceType,
+ RegisterCanvasWorkParams,
RegisterDocumentWorkParams,
RegisterSkillToolResultWorkParams,
RegisterTaskWorkParams,
@@ -279,6 +280,7 @@ export interface WorkRegistrationPorts {
deleteDocumentWork?: (params: DeleteDocumentWorkParams) => Promise<unknown>;
deleteTaskWork: (params: DeleteTaskWorkParams) => Promise<unknown>;
handleSkillToolResult: (params: RegisterSkillToolResultWorkParams) => Promise<unknown>;
+ registerCanvas?: (params: RegisterCanvasWorkParams) => Promise<unknown>;
registerDocument: (params: RegisterDocumentWorkParams) => Promise<unknown>;
registerTask: (params: RegisterTaskWorkParams) => Promise<unknown>;
}
@@ -427,6 +429,37 @@ const dispatchDocumentWorkIntent = async (
});
};
+const dispatchCanvasWorkIntent = async (
+ intent: WorkRegistrationIntentFor<'canvas'>,
+ ports: WorkRegistrationPorts,
+ provenance: WorkRegistrationProvenance,
+): Promise<void> => {
+ const {
+ agentId,
+ cumulativeCost,
+ cumulativeUsage,
+ messageId,
+ rootOperationId,
+ threadId,
+ toolCallId,
+ toolIdentifier,
+ topicId,
+ } = provenance;
+
+ await ports.registerCanvas?.({
+ ...intent.canvas,
+ agentId,
+ cumulativeCost,
+ cumulativeUsage,
+ messageId,
+ rootOperationId,
+ threadId,
+ toolCallId,
+ toolIdentifier,
+ topicId,
+ });
+};
+
const dispatchSkillWorkIntent = async (
intent: WorkRegistrationIntentFor<'skill'>,
ports: WorkRegistrationPorts,
@@ -467,6 +500,9 @@ const dispatchSkillWorkIntent = async (
* fails this exhaustive registry until its behavior is registered here.
*/
export const WORK_REGISTRATION_ADAPTERS = {
+ canvas: {
+ dispatch: dispatchCanvasWorkIntent,
+ },
document: {
dispatch: dispatchDocumentWorkIntent,
resolve: resolveDocumentWorkIntent,
diff --git a/packages/business-server/src/canvasPublish.ts b/packages/business-server/src/canvasPublish.ts
new file mode 100644
index 00000000000..01cb3682cad
--- /dev/null
+++ b/packages/business-server/src/canvasPublish.ts
@@ -0,0 +1,25 @@
+import type { LobeChatDatabase } from '@lobechat/database';
+import type { CanvasPublishBundle } from '@lobechat/types';
+
+export interface PublishCanvasSiteParams {
+ bundle: CanvasPublishBundle;
+ canvasId: string;
+ db: LobeChatDatabase;
+ deploymentId?: string;
+ title: string;
+ userId: string;
+ workspaceId?: string;
+}
+
+export interface PublishCanvasSiteResult {
+ deploymentId: string;
+ url: string;
+}
+
+export const isCanvasPublishEnabled = () => false;
+
+export const publishCanvasSite = async (
+ _params: PublishCanvasSiteParams,
+): Promise<PublishCanvasSiteResult> => {
+ throw new Error('Canvas publishing is not available in this deployment');
+};
diff --git a/packages/business-server/src/canvasStorage.ts b/packages/business-server/src/canvasStorage.ts
new file mode 100644
index 00000000000..96246f20c84
--- /dev/null
+++ b/packages/business-server/src/canvasStorage.ts
@@ -0,0 +1,7 @@
+export type CanvasStorageQuotaResult = { message: string; ok: false } | { ok: true };
+
+export const checkCanvasStorageQuota = async (_params: {
+ addedBytes: number;
+ userId: string;
+ workspaceId?: string | null;
+}): Promise<CanvasStorageQuotaResult> => ({ ok: true });
diff --git a/packages/canvas-runtime/package.json b/packages/canvas-runtime/package.json
new file mode 100644
index 00000000000..686a7c457da
--- /dev/null
+++ b/packages/canvas-runtime/package.json
@@ -0,0 +1,15 @@
+{
+ "name": "@lobechat/canvas-runtime",
+ "version": "1.0.0",
+ "private": true,
+ "type": "module",
+ "scripts": {
+ "build": "vite build && vite build --mode highlight && vite build --mode mermaid && node scripts/finalize.mjs",
+ "test": "vitest"
+ },
+ "dependencies": {
+ "@lobechat/canvas": "workspace:*",
+ "pele": "^1.6.0",
+ "shiki": "^4.4.3"
+ }
+}
diff --git a/packages/canvas-runtime/scripts/finalize.mjs b/packages/canvas-runtime/scripts/finalize.mjs
new file mode 100644
index 00000000000..86d5c2c292c
--- /dev/null
+++ b/packages/canvas-runtime/scripts/finalize.mjs
@@ -0,0 +1,39 @@
+import fs from 'node:fs';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+const here = path.dirname(fileURLToPath(import.meta.url));
+const dist = path.resolve(here, '../dist');
+const jsFile = path.join(dist, 'canvas-runtime.js');
+const cssFiles = fs.readdirSync(dist).filter((file) => file.endsWith('.css'));
+const addonCss = cssFiles.filter((file) => file !== 'canvas-runtime.css');
+if (addonCss.length > 0) {
+ throw new Error(
+ `Canvas add-ons must not emit CSS; style them in base.css: ${addonCss.join(', ')}`,
+ );
+}
+const css = cssFiles.map((file) => fs.readFileSync(path.join(dist, file), 'utf8')).join('\n');
+const cssLiteral = JSON.stringify(css)
+ .replaceAll('<', String.raw`\u003c`)
+ .replaceAll('\u2028', String.raw`\u2028`)
+ .replaceAll('\u2029', String.raw`\u2029`);
+const inject = `(function(){if(document.getElementById('lobe-canvas-style'))return;var s=document.createElement('style');s.id='lobe-canvas-style';s.textContent=${cssLiteral};(document.head||document.documentElement).appendChild(s)})();\n`;
+
+fs.writeFileSync(jsFile, inject + fs.readFileSync(jsFile, 'utf8'));
+for (const file of cssFiles) fs.rmSync(path.join(dist, file));
+
+const manifestSource = fs.readFileSync(
+ path.resolve(here, '../../canvas/src/project/manifest.ts'),
+ 'utf8',
+);
+const CANVAS_RUNTIME_MAJOR = Number(/CANVAS_RUNTIME_MAJOR = (\d+)/.exec(manifestSource)[1]);
+const target = path.resolve(here, `../../../public/canvas-runtime/v${CANVAS_RUNTIME_MAJOR}`);
+fs.rmSync(target, { force: true, recursive: true });
+fs.mkdirSync(target, { recursive: true });
+const bytes = {};
+for (const file of fs.readdirSync(dist).filter((name) => name.endsWith('.js'))) {
+ fs.copyFileSync(path.join(dist, file), path.join(target, file));
+ bytes[file] = fs.statSync(path.join(dist, file)).size;
+}
+
+console.log(JSON.stringify({ bytes, target }));
diff --git a/packages/canvas-runtime/src/addons/highlight.test.ts b/packages/canvas-runtime/src/addons/highlight.test.ts
new file mode 100644
index 00000000000..a1fcf639d76
--- /dev/null
+++ b/packages/canvas-runtime/src/addons/highlight.test.ts
@@ -0,0 +1,25 @@
+import { CANVAS_CODE_LANGUAGES } from '@lobechat/canvas';
+import { describe, expect, it } from 'vitest';
+
+import { CODE_GRAMMARS, highlightCode } from './highlight';
+
+describe('highlight add-on', () => {
+ it('bundles a grammar for every language the component reference promises', () => {
+ expect(Object.keys(CODE_GRAMMARS).sort()).toEqual([...CANVAS_CODE_LANGUAGES].sort());
+ });
+
+ it('colors code with theme variables and accepts common aliases', async () => {
+ const html = await highlightCode('const ids: string[] = [];', 'ts');
+
+ expect(html).toContain('const');
+ expect(html).toMatch(/style="color:\s?var\(--lobe-/);
+ expect(await highlightCode('echo hi', 'sh')).toMatch(/style="color:\s?var\(--lobe-/);
+ });
+
+ it('shows an unknown language as escaped plain text', async () => {
+ const html = await highlightCode('a < b', 'brainfudge');
+
+ expect(html).toContain('a &#x3C; b');
+ expect(html).not.toMatch(/<span style="color:\s?var\(--lobe-color-success/);
+ });
+});
diff --git a/packages/canvas-runtime/src/addons/highlight.ts b/packages/canvas-runtime/src/addons/highlight.ts
new file mode 100644
index 00000000000..c99daf629d2
--- /dev/null
+++ b/packages/canvas-runtime/src/addons/highlight.ts
@@ -0,0 +1,86 @@
+import type { CANVAS_CODE_LANGUAGES } from '@lobechat/canvas';
+import { ShikiLobeTheme } from '@lobehub/ui';
+import {
+ createHighlighterCore,
+ type HighlighterCore,
+ type LanguageRegistration,
+ type ThemeRegistration,
+} from 'shiki/core';
+import c from 'shiki/dist/langs/c.mjs';
+import cpp from 'shiki/dist/langs/cpp.mjs';
+import csharp from 'shiki/dist/langs/csharp.mjs';
+import css from 'shiki/dist/langs/css.mjs';
+import diff from 'shiki/dist/langs/diff.mjs';
+import dockerfile from 'shiki/dist/langs/dockerfile.mjs';
+import go from 'shiki/dist/langs/go.mjs';
+import html from 'shiki/dist/langs/html.mjs';
+import java from 'shiki/dist/langs/java.mjs';
+import javascript from 'shiki/dist/langs/javascript.mjs';
+import json from 'shiki/dist/langs/json.mjs';
+import jsx from 'shiki/dist/langs/jsx.mjs';
+import kotlin from 'shiki/dist/langs/kotlin.mjs';
+import python from 'shiki/dist/langs/python.mjs';
+import ruby from 'shiki/dist/langs/ruby.mjs';
+import rust from 'shiki/dist/langs/rust.mjs';
+import shellscript from 'shiki/dist/langs/shellscript.mjs';
+import sql from 'shiki/dist/langs/sql.mjs';
+import swift from 'shiki/dist/langs/swift.mjs';
+import toml from 'shiki/dist/langs/toml.mjs';
+import tsx from 'shiki/dist/langs/tsx.mjs';
+import typescript from 'shiki/dist/langs/typescript.mjs';
+import yaml from 'shiki/dist/langs/yaml.mjs';
+import { createJavaScriptRegexEngine } from 'shiki/engine/javascript';
+
+import { registerCanvasAddon } from './registry';
+
+export const CODE_GRAMMARS: Record<(typeof CANVAS_CODE_LANGUAGES)[number], LanguageRegistration[]> =
+ {
+ bash: shellscript,
+ c,
+ cpp,
+ csharp,
+ css,
+ diff,
+ dockerfile,
+ go,
+ html,
+ java,
+ javascript,
+ json,
+ jsx,
+ kotlin,
+ python,
+ ruby,
+ rust,
+ sql,
+ swift,
+ toml,
+ tsx,
+ typescript,
+ yaml,
+ };
+
+const PLAIN_TEXT = 'text';
+
+const LOBE_THEME = ShikiLobeTheme as ThemeRegistration;
+
+let highlighter: Promise<HighlighterCore> | undefined;
+
+const getHighlighter = () => {
+ highlighter ??= createHighlighterCore({
+ engine: createJavaScriptRegexEngine({ forgiving: true }),
+ langs: Object.values(CODE_GRAMMARS),
+ themes: [LOBE_THEME],
+ });
+ return highlighter;
+};
+
+export const highlightCode = async (code: string, language?: string) => {
+ const instance = await getHighlighter();
+ const requested = language?.trim().toLowerCase();
+ const lang =
+ requested && instance.getLoadedLanguages().includes(requested) ? requested : PLAIN_TEXT;
+ return instance.codeToHtml(code, { lang, theme: LOBE_THEME.name! });
+};
+
+if (typeof window !== 'undefined') registerCanvasAddon('highlight', { highlight: highlightCode });
diff --git a/packages/canvas-runtime/src/addons/load.test.ts b/packages/canvas-runtime/src/addons/load.test.ts
new file mode 100644
index 00000000000..bdf555327a0
--- /dev/null
+++ b/packages/canvas-runtime/src/addons/load.test.ts
@@ -0,0 +1,54 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { loadCanvasAddon, resolveCanvasAddonUrl } from './load';
+import { registerCanvasAddon } from './registry';
+
+let appended: HTMLScriptElement[] = [];
+
+beforeEach(() => {
+ appended = [];
+ vi.spyOn(document.head, 'append').mockImplementation((...nodes) => {
+ appended.push(...(nodes as HTMLScriptElement[]));
+ });
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+ delete window.__LOBE_CANVAS_ADDONS__;
+});
+
+describe('canvas add-ons', () => {
+ it('resolves add-ons next to the runtime script, not the project page', () => {
+ expect(
+ resolveCanvasAddonUrl(
+ 'mermaid',
+ 'https://app.lobehub.com/canvas-runtime/v1/canvas-runtime.js',
+ ),
+ ).toBe('https://app.lobehub.com/canvas-runtime/v1/canvas-runtime-mermaid.js');
+ });
+
+ it('loads an add-on script once and resolves with what it registers', async () => {
+ const first = loadCanvasAddon('mermaid');
+ const second = loadCanvasAddon('mermaid');
+
+ expect(appended).toHaveLength(1);
+ expect(appended[0].src).toContain('canvas-runtime-mermaid.js');
+
+ const addon = { render: () => ({ svg: '<svg></svg>' }) };
+ registerCanvasAddon('mermaid', addon);
+ appended[0].dispatchEvent(new Event('load'));
+
+ await expect(first).resolves.toBe(addon);
+ await expect(second).resolves.toBe(addon);
+ });
+
+ it('rejects when the add-on script cannot be fetched, so a later call can retry', async () => {
+ const failed = loadCanvasAddon('highlight');
+ appended[0].dispatchEvent(new Event('error'));
+
+ await expect(failed).rejects.toThrow('highlight add-on failed to load');
+
+ void loadCanvasAddon('highlight');
+ expect(appended).toHaveLength(2);
+ });
+});
diff --git a/packages/canvas-runtime/src/addons/load.ts b/packages/canvas-runtime/src/addons/load.ts
new file mode 100644
index 00000000000..9a91a262503
--- /dev/null
+++ b/packages/canvas-runtime/src/addons/load.ts
@@ -0,0 +1,60 @@
+import { canvasAddonFile, type CanvasAddonName, type CanvasAddons } from './registry';
+
+declare global {
+ interface Window {
+ __LOBE_CANVAS_LOAD_ADDON__?: (name: CanvasAddonName) => Promise<unknown>;
+ }
+}
+
+// Captured while the runtime script runs: add-ons sit next to it, and the page's own
+// URL points at the user's project, not at the runtime's origin.
+const runtimeSrc =
+ typeof document !== 'undefined' && document.currentScript instanceof HTMLScriptElement
+ ? document.currentScript.src
+ : undefined;
+
+const pending = new Map<CanvasAddonName, Promise<unknown>>();
+
+export const resolveCanvasAddonUrl = (name: CanvasAddonName, base = runtimeSrc) =>
+ new URL(canvasAddonFile(name), base ?? document.baseURI).href;
+
+export const loadCanvasAddon = <K extends CanvasAddonName>(name: K): Promise<CanvasAddons[K]> => {
+ const ready = window.__LOBE_CANVAS_ADDONS__?.[name];
+ if (ready) return Promise.resolve(ready as CanvasAddons[K]);
+
+ let promise = pending.get(name);
+ if (!promise) {
+ if (window.__LOBE_CANVAS_LOAD_ADDON__) {
+ promise = window
+ .__LOBE_CANVAS_LOAD_ADDON__(name)
+ .then(() => {
+ const addon = window.__LOBE_CANVAS_ADDONS__?.[name];
+ if (!addon) throw new Error(`The ${name} add-on loaded without registering`);
+ return addon;
+ })
+ .catch((error) => {
+ pending.delete(name);
+ throw error;
+ });
+ pending.set(name, promise);
+ return promise as Promise<CanvasAddons[K]>;
+ }
+ promise = new Promise<CanvasAddons[K]>((resolve, reject) => {
+ const script = document.createElement('script');
+ script.src = resolveCanvasAddonUrl(name);
+ script.addEventListener('load', () => {
+ const addon = window.__LOBE_CANVAS_ADDONS__?.[name];
+ if (addon) resolve(addon as CanvasAddons[K]);
+ else reject(new Error(`The ${name} add-on loaded without registering`));
+ });
+ script.addEventListener('error', () => {
+ pending.delete(name);
+ script.remove();
+ reject(new Error(`The ${name} add-on failed to load from ${script.src}`));
+ });
+ document.head.append(script);
+ });
+ pending.set(name, promise);
+ }
+ return promise as Promise<CanvasAddons[K]>;
+};
diff --git a/packages/canvas-runtime/src/addons/mermaid.test.ts b/packages/canvas-runtime/src/addons/mermaid.test.ts
new file mode 100644
index 00000000000..ad69d43eb8b
--- /dev/null
+++ b/packages/canvas-runtime/src/addons/mermaid.test.ts
@@ -0,0 +1,24 @@
+import { describe, expect, it } from 'vitest';
+
+import { mountMermaid } from './mermaid';
+
+describe('mermaid add-on', () => {
+ it('mounts a valid flowchart without an error', () => {
+ const element = document.createElement('div');
+ document.body.append(element);
+
+ const mounted = mountMermaid(element, 'flowchart TD\n A[Login] --> B{Valid?}', 'scope-');
+
+ expect(mounted.error).toBeUndefined();
+ mounted.destroy();
+ });
+
+ it('returns the parser error instead of throwing', () => {
+ const element = document.createElement('div');
+ document.body.append(element);
+
+ expect(mountMermaid(element, 'flowchart TD\n A[Login --> B', 'scope-').error).toContain(
+ 'Parse error',
+ );
+ });
+});
diff --git a/packages/canvas-runtime/src/addons/mermaid.ts b/packages/canvas-runtime/src/addons/mermaid.ts
new file mode 100644
index 00000000000..9b40baf0aa7
--- /dev/null
+++ b/packages/canvas-runtime/src/addons/mermaid.ts
@@ -0,0 +1,40 @@
+import { mount } from 'pele';
+
+import { type CanvasMermaidMount, registerCanvasAddon } from './registry';
+
+const messageOf = (error: unknown) => (error instanceof Error ? error.message : String(error));
+
+// Long edges route around one side, so a wide diagram's middle is often empty space;
+// the topmost node is where reading starts.
+const revealStart = (element: HTMLElement) => {
+ if (element.scrollWidth <= element.clientWidth) return;
+ let start: Element | undefined;
+ for (const node of element.querySelectorAll('.pele-node')) {
+ if (!start || node.getBoundingClientRect().top < start.getBoundingClientRect().top)
+ start = node;
+ }
+ if (!start) return;
+ const box = element.getBoundingClientRect();
+ const target = start.getBoundingClientRect();
+ element.scrollLeft += target.left + target.width / 2 - (box.left + box.width / 2);
+};
+
+export const mountMermaid = (
+ element: HTMLElement,
+ source: string,
+ idPrefix: string,
+): CanvasMermaidMount => {
+ try {
+ const mounted = mount(element, source, { fontSize: 14, idPrefix, zoom: false });
+ if (mounted.error) {
+ mounted.destroy();
+ return { destroy: () => {}, error: messageOf(mounted.error) };
+ }
+ revealStart(element);
+ return { destroy: () => mounted.destroy() };
+ } catch (error) {
+ return { destroy: () => {}, error: messageOf(error) };
+ }
+};
+
+if (typeof window !== 'undefined') registerCanvasAddon('mermaid', { mount: mountMermaid });
diff --git a/packages/canvas-runtime/src/addons/registry.ts b/packages/canvas-runtime/src/addons/registry.ts
new file mode 100644
index 00000000000..e2accb1801a
--- /dev/null
+++ b/packages/canvas-runtime/src/addons/registry.ts
@@ -0,0 +1,32 @@
+export interface CanvasHighlightAddon {
+ highlight: (code: string, language?: string) => Promise<string>;
+}
+
+export interface CanvasMermaidMount {
+ destroy: () => void;
+ error?: string;
+}
+
+export interface CanvasMermaidAddon {
+ mount: (element: HTMLElement, source: string, idPrefix: string) => CanvasMermaidMount;
+}
+
+export interface CanvasAddons {
+ highlight: CanvasHighlightAddon;
+ mermaid: CanvasMermaidAddon;
+}
+
+export type CanvasAddonName = keyof CanvasAddons;
+
+declare global {
+ interface Window {
+ __LOBE_CANVAS_ADDONS__?: Partial<CanvasAddons>;
+ }
+}
+
+export const registerCanvasAddon = <K extends CanvasAddonName>(name: K, addon: CanvasAddons[K]) => {
+ window.__LOBE_CANVAS_ADDONS__ ??= {};
+ window.__LOBE_CANVAS_ADDONS__[name] = addon;
+};
+
+export const canvasAddonFile = (name: CanvasAddonName) => `canvas-runtime-${name}.js`;
diff --git a/packages/canvas-runtime/src/base.css b/packages/canvas-runtime/src/base.css
new file mode 100644
index 00000000000..032efa27bad
--- /dev/null
+++ b/packages/canvas-runtime/src/base.css
@@ -0,0 +1,193 @@
+@layer lobe-canvas-base {
+ html {
+ color-scheme: light dark;
+ }
+
+ body {
+ margin: 0;
+ padding: 24px;
+ font-family: var(--lobe-font-family);
+ font-size: var(--lobe-font-size);
+ line-height: var(--lobe-line-height);
+ color: var(--lobe-color-text);
+ background: var(--lobe-color-bg-layout, var(--lobe-color-bg-container));
+ -webkit-font-smoothing: antialiased;
+ }
+
+ /* Models wrap pages in <main>/<section> and stack blocks inside tabs, so block
+ spacing cannot rely on being a direct child of <body>. Flex and grid
+ components space their items with gap and are left out. */
+ :where(body, main, section, article, header, footer, aside, [data-lobe-canvas-flow]) > * + * {
+ margin-block-start: 16px;
+ }
+
+ h1,
+ h2,
+ h3,
+ h4 {
+ margin-block: 24px 8px;
+ font-weight: var(--lobe-font-weight-strong);
+ color: var(--lobe-color-text-heading, var(--lobe-color-text));
+ }
+
+ h1 {
+ font-size: var(--lobe-font-size-heading-3);
+ line-height: var(--lobe-line-height-heading-3);
+ }
+
+ h2 {
+ font-size: var(--lobe-font-size-heading-4);
+ line-height: var(--lobe-line-height-heading-4);
+ }
+
+ h3 {
+ font-size: var(--lobe-font-size-heading-5);
+ line-height: var(--lobe-line-height-heading-5);
+ }
+
+ h4 {
+ font-size: var(--lobe-font-size);
+ }
+
+ p,
+ ul,
+ ol,
+ blockquote {
+ margin-block: 8px;
+ }
+
+ a {
+ color: var(--lobe-color-link, var(--lobe-color-primary));
+ text-decoration: none;
+ }
+
+ a:hover {
+ text-decoration: underline;
+ }
+
+ blockquote {
+ margin-inline: 0;
+ padding-inline-start: 12px;
+ border-inline-start: 3px solid var(--lobe-color-border);
+ color: var(--lobe-color-text-secondary);
+ }
+
+ code {
+ font-family: var(--lobe-font-family-code);
+ font-size: 0.9em;
+ }
+
+ table {
+ width: 100%;
+ border-collapse: collapse;
+ font-variant-numeric: tabular-nums;
+ }
+
+ th,
+ td {
+ padding: 8px 12px;
+ border-block-end: 1px solid var(--lobe-color-border-secondary);
+ text-align: start;
+ }
+
+ th {
+ font-weight: 500;
+ color: var(--lobe-color-text-secondary);
+ }
+
+ lobe-flex,
+ lobe-grid,
+ lobe-card,
+ lobe-tabs,
+ lobe-accordion,
+ lobe-alert,
+ lobe-table,
+ lobe-steps,
+ lobe-descriptions,
+ lobe-code,
+ lobe-mermaid,
+ lobe-area-chart,
+ lobe-bar-chart,
+ lobe-line-chart,
+ lobe-scatter-chart,
+ lobe-radar-chart,
+ lobe-donut-chart,
+ lobe-bar-list,
+ lobe-tracker,
+ lobe-heatmap,
+ lobe-funnel-chart,
+ lobe-divider {
+ display: block;
+ }
+
+ [data-lobe-canvas-slot] {
+ display: contents;
+ }
+
+ [hidden] {
+ display: none !important;
+ }
+
+ [data-lobe-canvas-root] {
+ display: contents;
+ }
+}
+
+@layer lobe-canvas-base {
+ pre {
+ overflow: auto;
+ margin: 0;
+ padding: 12px 16px;
+ border: 1px solid var(--lobe-color-border-secondary);
+ border-radius: var(--lobe-border-radius);
+ background: var(--lobe-color-fill-quaternary);
+ }
+
+ pre code {
+ font-size: 13px;
+ line-height: 1.6;
+ }
+}
+
+@layer lobe-canvas-base {
+ [data-lobe-canvas-code] {
+ overflow: hidden;
+ border: 1px solid var(--lobe-color-border-secondary);
+ border-radius: var(--lobe-border-radius);
+ background: var(--lobe-color-fill-quaternary);
+ }
+
+ [data-lobe-canvas-code-header] {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding-block: 4px;
+ padding-inline: 12px 4px;
+ border-block-end: 1px solid var(--lobe-color-border-secondary);
+ font-family: var(--lobe-font-family-code);
+ font-size: 12px;
+ color: var(--lobe-color-text-description);
+ }
+
+ /* shiki writes the theme background on the <pre> as an inline style */
+ [data-lobe-canvas-code] pre {
+ border: 0;
+ border-radius: 0;
+ background: transparent !important;
+ }
+
+ [data-lobe-canvas-mermaid] {
+ overflow-x: auto;
+ padding: 16px;
+ border: 1px solid var(--lobe-color-border-secondary);
+ border-radius: var(--lobe-border-radius);
+ }
+
+ /* pele caps the SVG at max-width:100% inline; a wide diagram shrunk to the pane leaves
+ unreadable text, so keep its natural size and scroll instead */
+ [data-lobe-canvas-mermaid] svg {
+ display: block;
+ max-width: none !important;
+ margin-inline: auto;
+ }
+}
diff --git a/packages/canvas-runtime/src/codeText.test.ts b/packages/canvas-runtime/src/codeText.test.ts
new file mode 100644
index 00000000000..8125b07c897
--- /dev/null
+++ b/packages/canvas-runtime/src/codeText.test.ts
@@ -0,0 +1,19 @@
+import { describe, expect, it } from 'vitest';
+
+import { normalizeCodeText } from './codeText';
+
+describe('normalizeCodeText', () => {
+ it('drops the blank lines and the indentation the surrounding HTML adds', () => {
+ const text = '\n if (ok) {\n run();\n }\n ';
+
+ expect(normalizeCodeText(text)).toBe('if (ok) {\n run();\n}');
+ });
+
+ it('keeps code that starts at the first column as written', () => {
+ expect(normalizeCodeText('select 1;\n -- note')).toBe('select 1;\n -- note');
+ });
+
+ it('ignores blank lines when measuring the common indentation', () => {
+ expect(normalizeCodeText(' a\n\n b')).toBe('a\n\nb');
+ });
+});
diff --git a/packages/canvas-runtime/src/codeText.ts b/packages/canvas-runtime/src/codeText.ts
new file mode 100644
index 00000000000..3ca5d857ddb
--- /dev/null
+++ b/packages/canvas-runtime/src/codeText.ts
@@ -0,0 +1,12 @@
+export const normalizeCodeText = (text: string) => {
+ const lines = text.replaceAll('\r\n', '\n').split('\n');
+ while (lines.length > 0 && lines[0].trim() === '') lines.shift();
+ while (lines.length > 0 && lines.at(-1)!.trim() === '') lines.pop();
+
+ const indent = Math.min(
+ ...lines.filter((line) => line.trim() !== '').map((line) => /^[\t ]*/.exec(line)![0].length),
+ );
+ return Number.isFinite(indent) && indent > 0
+ ? lines.map((line) => line.slice(Math.min(indent, /^[\t ]*/.exec(line)![0].length))).join('\n')
+ : lines.join('\n');
+};
diff --git a/packages/canvas-runtime/src/element.test.tsx b/packages/canvas-runtime/src/element.test.tsx
new file mode 100644
index 00000000000..883c4978627
--- /dev/null
+++ b/packages/canvas-runtime/src/element.test.tsx
@@ -0,0 +1,97 @@
+import { CANVAS_COMPONENT_MAP } from '@lobechat/canvas';
+import { act } from 'react';
+import { afterEach, beforeAll, describe, expect, it, vi } from 'vitest';
+
+import { defineCanvasElement } from './element';
+import { type CanvasHostRoot, createHostRoot } from './host';
+
+(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
+
+let hosts: CanvasHostRoot | undefined;
+const getHosts = () => {
+ hosts ??= createHostRoot({ onError: vi.fn(), wrap: (children) => children });
+ return hosts;
+};
+
+const define = (tag: string, view: Parameters<typeof defineCanvasElement>[1]) =>
+ customElements.define(tag, defineCanvasElement(CANVAS_COMPONENT_MAP.get(tag)!, view, getHosts));
+
+beforeAll(() => {
+ define('lobe-card', ({ props, slot }) => (
+ <section data-title={props.title as string}>
+ <span data-lobe-canvas-slot="" ref={slot} />
+ </section>
+ ));
+ define('lobe-segmented', ({ change, items, value }) => (
+ <div data-value={String(value)}>
+ {items.map((item) => (
+ <button key={item.attrs.value} type="button" onClick={() => change(item.attrs.value)}>
+ {item.label}
+ </button>
+ ))}
+ </div>
+ ));
+ define('lobe-tag', ({ props, slot }) => (
+ <em data-color={props.color as string}>
+ <span data-lobe-canvas-slot="" ref={slot} />
+ </em>
+ ));
+});
+
+afterEach(() => {
+ document.body.querySelectorAll('main').forEach((node) => node.remove());
+});
+
+const mount = async (html: string) => {
+ const main = document.createElement('main');
+ main.innerHTML = html;
+ await act(async () => {
+ document.body.append(main);
+ });
+ return main;
+};
+
+describe('canvas elements', () => {
+ it('renders every element through one shared React root and keeps light-DOM children', async () => {
+ const main = await mount(
+ '<lobe-card title="Cost"><p>Body <lobe-tag color="green">ok</lobe-tag></p></lobe-card><lobe-tag>second</lobe-tag>',
+ );
+
+ expect(document.querySelectorAll('[data-lobe-canvas-root]')).toHaveLength(1);
+ expect(main.querySelector('section')?.dataset.title).toBe('Cost');
+ expect(main.querySelector('section p')?.textContent).toBe('Body ok');
+ expect(main.querySelector('lobe-card lobe-tag em')?.getAttribute('data-color')).toBe('green');
+ expect(main.querySelectorAll('em')).toHaveLength(2);
+ });
+
+ it('reads option children as data and fires lobe-change with the new value', async () => {
+ const main = await mount(
+ '<lobe-segmented value="a"><lobe-option value="a">A</lobe-option><lobe-option value="b">B</lobe-option></lobe-segmented>',
+ );
+ const listener = vi.fn();
+ main.addEventListener('lobe-change', (event) => listener((event as CustomEvent).detail));
+
+ expect(main.querySelector('lobe-option')).toBeNull();
+ await act(async () => {
+ main.querySelectorAll('button')[1].click();
+ });
+
+ expect(listener).toHaveBeenCalledWith({ checked: false, value: 'b' });
+ expect(main.querySelector('[data-value]')?.getAttribute('data-value')).toBe('b');
+ });
+
+ it('re-renders on attribute changes and stops rendering once removed', async () => {
+ const main = await mount('<lobe-card title="Old"></lobe-card>');
+ const card = main.querySelector('lobe-card')!;
+
+ await act(async () => {
+ card.setAttribute('title', 'New');
+ });
+ expect(main.querySelector('section')?.dataset.title).toBe('New');
+
+ await act(async () => {
+ card.remove();
+ });
+ expect(card.querySelector('section')).toBeNull();
+ });
+});
diff --git a/packages/canvas-runtime/src/element.ts b/packages/canvas-runtime/src/element.ts
new file mode 100644
index 00000000000..52d8563cfec
--- /dev/null
+++ b/packages/canvas-runtime/src/element.ts
@@ -0,0 +1,156 @@
+import type { CanvasComponentSpec } from '@lobechat/canvas';
+import type { ReactNode } from 'react';
+
+import type { CanvasHostRoot } from './host';
+import {
+ type CanvasChildItem,
+ jsonSourceAttributes,
+ readChildItems,
+ readJsonChildren,
+ readProps,
+} from './props';
+
+export interface CanvasViewContext {
+ change: (value: unknown) => void;
+ checked: boolean;
+ items: CanvasChildItem[];
+ props: Record<string, any>;
+ slot: (node: HTMLElement | null) => void;
+ text: string;
+ value: unknown;
+}
+
+export type CanvasView = (context: CanvasViewContext) => ReactNode;
+
+const GLOBAL_OBSERVED = ['hidden', 'class', 'style'];
+
+export const defineCanvasElement = (
+ spec: CanvasComponentSpec,
+ view: CanvasView,
+ getHosts: () => CanvasHostRoot,
+) => {
+ const sources = jsonSourceAttributes(spec);
+
+ class CanvasElement extends HTMLElement {
+ static get observedAttributes() {
+ return [...Object.keys(spec.attributes), ...sources, ...GLOBAL_OBSERVED];
+ }
+
+ #mounted = false;
+ #nodes: Node[] = [];
+ #items: CanvasChildItem[] = [];
+ #text = '';
+ #childData: Record<string, unknown> = {};
+ #loaded: Record<string, unknown> = {};
+ #slotNode: HTMLElement | null = null;
+ #value: unknown;
+ #checked = false;
+
+ get value() {
+ return this.#value;
+ }
+
+ set value(next: unknown) {
+ this.#value = next;
+ this.#render();
+ }
+
+ get checked() {
+ return this.#checked;
+ }
+
+ set checked(next: boolean) {
+ this.#checked = next;
+ this.#render();
+ }
+
+ connectedCallback() {
+ if (!this.#mounted) {
+ this.#mounted = true;
+ this.#text = this.textContent ?? '';
+ this.#childData = readJsonChildren(this);
+ if (spec.children === 'options') this.#items = readChildItems(this);
+ this.#nodes = spec.children === 'content' ? [...this.childNodes] : [];
+ this.#value = this.getAttribute('value') ?? undefined;
+ if (spec.attributes.value?.type === 'number' && this.#value !== undefined) {
+ this.#value = Number(this.#value);
+ }
+ this.#checked = this.#readChecked();
+ this.replaceChildren();
+ for (const source of sources) this.#loadSource(source);
+ }
+ getHosts().register(this, () => view(this.#context()));
+ }
+
+ disconnectedCallback() {
+ getHosts().unregister(this);
+ }
+
+ attributeChangedCallback(name: string, previous: string | null, next: string | null) {
+ if (!this.#mounted || previous === next) return;
+ if (name === 'value') this.#value = next ?? undefined;
+ if (name === 'checked') this.#checked = this.#readChecked();
+ if (sources.includes(name)) this.#loadSource(name);
+ this.#render();
+ }
+
+ #readChecked() {
+ const raw = this.getAttribute('checked');
+ return raw !== null && raw !== 'false';
+ }
+
+ #render() {
+ if (this.#mounted) getHosts().update(this);
+ }
+
+ #loadSource(source: string) {
+ const url = this.getAttribute(source);
+ if (!url) return;
+ const prop = source.slice(0, -'-src'.length);
+ fetch(new URL(url, document.baseURI))
+ .then((response) => {
+ if (!response.ok) throw new Error(`${response.status} ${response.statusText}`);
+ return response.json();
+ })
+ .then((data) => {
+ this.#loaded = { ...this.#loaded, [prop]: data };
+ this.#render();
+ })
+ .catch((error) => {
+ window.dispatchEvent(
+ new CustomEvent('lobe-canvas-component-error', {
+ detail: { message: `${source}="${url}": ${String(error)}`, tag: spec.tag },
+ }),
+ );
+ });
+ }
+
+ #context(): CanvasViewContext {
+ return {
+ change: (value) => {
+ if (typeof value === 'boolean') this.#checked = value;
+ else this.#value = value;
+ this.#render();
+ this.dispatchEvent(
+ new CustomEvent('lobe-change', {
+ bubbles: true,
+ detail: { checked: this.#checked, value },
+ }),
+ );
+ },
+ checked: this.#checked,
+ items: this.#items,
+ props: readProps(this, spec, { ...this.#childData, ...this.#loaded }),
+ slot: (node) => {
+ if (!node || node === this.#slotNode) return;
+ this.#slotNode = node;
+ node.append(...this.#nodes);
+ },
+ text: this.#text,
+ value: this.#value,
+ };
+ }
+ }
+
+ return CanvasElement;
+};
diff --git a/packages/canvas-runtime/src/format.test.ts b/packages/canvas-runtime/src/format.test.ts
new file mode 100644
index 00000000000..36c11756425
--- /dev/null
+++ b/packages/canvas-runtime/src/format.test.ts
@@ -0,0 +1,24 @@
+import { describe, expect, it } from 'vitest';
+
+import { formatValue, heatmapLevel } from './format';
+
+describe('formatValue', () => {
+ it('formats by the requested style and appends the unit', () => {
+ expect(formatValue(1234.567)).toBe(
+ new Intl.NumberFormat(undefined, { maximumFractionDigits: 2 }).format(1234.567),
+ );
+ expect(formatValue(0.25, 'percent')).toContain('25');
+ expect(formatValue(25, 'percent')).toContain('25');
+ expect(formatValue(10, 'currency')).toBe('$10');
+ expect(formatValue(120, undefined, 'ms')).toBe('120 ms');
+ expect(formatValue('n/a')).toBe('n/a');
+ });
+});
+
+describe('heatmapLevel', () => {
+ it('maps counts onto five levels', () => {
+ expect(heatmapLevel(0, 10)).toBe(0);
+ expect(heatmapLevel(1, 10)).toBe(1);
+ expect(heatmapLevel(10, 10)).toBe(4);
+ });
+});
diff --git a/packages/canvas-runtime/src/format.ts b/packages/canvas-runtime/src/format.ts
new file mode 100644
index 00000000000..8cf05257fc5
--- /dev/null
+++ b/packages/canvas-runtime/src/format.ts
@@ -0,0 +1,31 @@
+const compact = new Intl.NumberFormat(undefined, { maximumFractionDigits: 1, notation: 'compact' });
+const number = new Intl.NumberFormat(undefined, { maximumFractionDigits: 2 });
+const percent = new Intl.NumberFormat(undefined, { maximumFractionDigits: 1, style: 'percent' });
+
+export const formatValue = (value: unknown, format?: unknown, unit?: unknown): string => {
+ if (typeof value !== 'number') return value === undefined || value === null ? '' : String(value);
+
+ let text: string;
+ switch (format) {
+ case 'compact': {
+ text = compact.format(value);
+ break;
+ }
+ case 'percent': {
+ text = percent.format(Math.abs(value) > 1 ? value / 100 : value);
+ break;
+ }
+ case 'currency': {
+ text = `$${number.format(value)}`;
+ break;
+ }
+ default: {
+ text = number.format(value);
+ }
+ }
+
+ return typeof unit === 'string' && unit ? `${text} ${unit}` : text;
+};
+
+export const heatmapLevel = (count: number, max: number) =>
+ count <= 0 || max <= 0 ? 0 : Math.min(4, Math.ceil((count / max) * 4));
diff --git a/packages/canvas-runtime/src/host.test.ts b/packages/canvas-runtime/src/host.test.ts
new file mode 100644
index 00000000000..dbdcde2132d
--- /dev/null
+++ b/packages/canvas-runtime/src/host.test.ts
@@ -0,0 +1,38 @@
+import { act, createElement, useEffect } from 'react';
+import { expect, it } from 'vitest';
+
+import { createHostRoot } from './host';
+
+it('unmounts rendered views and removes its root when the Canvas is destroyed', async () => {
+ let effects = 0;
+ const View = () => {
+ useEffect(() => {
+ effects++;
+ return () => {
+ effects--;
+ };
+ }, []);
+ return createElement('button', { type: 'button' }, 'Canvas content');
+ };
+ const host = document.createElement('section');
+ document.body.append(host);
+ const root = createHostRoot({
+ onError: (error) => {
+ throw error;
+ },
+ wrap: (children) => children,
+ });
+ await act(async () => root.register(host, () => createElement(View)));
+ expect(host.querySelector('button')?.textContent).toBe('Canvas content');
+ expect(effects).toBe(1);
+ await act(async () => root.destroy());
+ expect(effects).toBe(0);
+ expect(host.children).toHaveLength(0);
+ expect(document.querySelector('[data-lobe-canvas-root]')).toBeNull();
+ await act(async () => {
+ root.update(host);
+ root.register(host, () => createElement(View));
+ });
+ expect(host.children).toHaveLength(0);
+ host.remove();
+});
diff --git a/packages/canvas-runtime/src/host.tsx b/packages/canvas-runtime/src/host.tsx
new file mode 100644
index 00000000000..9685f760617
--- /dev/null
+++ b/packages/canvas-runtime/src/host.tsx
@@ -0,0 +1,125 @@
+import { Component, memo, type ReactNode, useSyncExternalStore } from 'react';
+import { createPortal } from 'react-dom';
+import { createRoot } from 'react-dom/client';
+
+export type HostView = () => ReactNode;
+
+interface Entry {
+ key: string;
+ revision: number;
+ view: HostView;
+}
+
+interface BoundaryProps {
+ children: ReactNode;
+ host: HTMLElement;
+ onError: (error: unknown, host: HTMLElement) => void;
+ revision: number;
+}
+
+interface BoundaryState {
+ failedAt: number | null;
+}
+
+class Boundary extends Component<BoundaryProps, BoundaryState> {
+ state: BoundaryState = { failedAt: null };
+
+ static getDerivedStateFromError() {
+ return { failedAt: -1 };
+ }
+
+ static getDerivedStateFromProps(props: BoundaryProps, state: BoundaryState) {
+ if (state.failedAt === -1) return { failedAt: props.revision };
+ if (state.failedAt !== null && state.failedAt !== props.revision) return { failedAt: null };
+ return null;
+ }
+
+ componentDidCatch(error: unknown) {
+ this.props.onError(error, this.props.host);
+ }
+
+ render() {
+ return this.state.failedAt === null ? this.props.children : null;
+ }
+}
+
+const View = memo(function View({ view }: { revision: number; view: HostView }) {
+ return view();
+});
+
+export interface CanvasHostRoot {
+ destroy: () => void;
+ register: (host: HTMLElement, view: HostView) => void;
+ unregister: (host: HTMLElement) => void;
+ update: (host: HTMLElement) => void;
+}
+
+export const createHostRoot = (options: {
+ onError: (error: unknown, host: HTMLElement) => void;
+ wrap: (children: ReactNode) => ReactNode;
+}): CanvasHostRoot => {
+ const entries = new Map<HTMLElement, Entry>();
+ const listeners = new Set<() => void>();
+ let snapshot: [HTMLElement, Entry][] = [];
+ let nextKey = 0;
+ let destroyed = false;
+
+ const publish = () => {
+ snapshot = [...entries];
+ for (const listener of listeners) listener();
+ };
+ const subscribe = (listener: () => void) => {
+ listeners.add(listener);
+ return () => listeners.delete(listener);
+ };
+ const getSnapshot = () => snapshot;
+
+ const Hosts = () => {
+ const hosts = useSyncExternalStore(subscribe, getSnapshot);
+ return options.wrap(
+ hosts.map(([host, entry]) =>
+ createPortal(
+ <Boundary host={host} revision={entry.revision} onError={options.onError}>
+ <View revision={entry.revision} view={entry.view} />
+ </Boundary>,
+ host,
+ entry.key,
+ ),
+ ),
+ );
+ };
+
+ const container = document.createElement('div');
+ container.dataset.lobeCanvasRoot = '';
+ (document.body ?? document.documentElement).append(container);
+ const root = createRoot(container);
+ root.render(<Hosts />);
+
+ return {
+ destroy: () => {
+ if (destroyed) return;
+ destroyed = true;
+ entries.clear();
+ listeners.clear();
+ snapshot = [];
+ root.unmount();
+ container.remove();
+ },
+ register: (host, view) => {
+ if (destroyed) return;
+ entries.set(host, { key: `h${nextKey++}`, revision: 0, view });
+ publish();
+ },
+ unregister: (host) => {
+ if (destroyed) return;
+ if (entries.delete(host)) publish();
+ },
+ update: (host) => {
+ if (destroyed) return;
+ const entry = entries.get(host);
+ if (!entry) return;
+ entries.set(host, { ...entry, revision: entry.revision + 1 });
+ publish();
+ },
+ };
+};
diff --git a/packages/canvas-runtime/src/index.tsx b/packages/canvas-runtime/src/index.tsx
new file mode 100644
index 00000000000..b1b1474e4a4
--- /dev/null
+++ b/packages/canvas-runtime/src/index.tsx
@@ -0,0 +1,62 @@
+import '@lobehub/ui/theme.css';
+import '@lobehub/ui/style.css';
+import './base.css';
+
+import { CANVAS_COMPONENTS } from '@lobechat/canvas';
+
+import { defineCanvasElement } from './element';
+import { type CanvasHostRoot, createHostRoot } from './host';
+import { wrapCanvasTree } from './providers';
+import { startThemeSync } from './theme';
+import { baseViews } from './views/base';
+import { chartViews } from './views/charts';
+import { codeViews } from './views/code';
+import { mermaidViews } from './views/mermaid';
+
+const views = { ...baseViews, ...chartViews, ...codeViews, ...mermaidViews };
+
+const reportError = (error: unknown, host: HTMLElement) => {
+ console.error('[lobe-canvas]', error);
+ window.dispatchEvent(
+ new CustomEvent('lobe-canvas-component-error', {
+ detail: {
+ message: error instanceof Error ? error.message : String(error),
+ tag: host.tagName.toLowerCase(),
+ },
+ }),
+ );
+};
+
+if (typeof window !== 'undefined' && !customElements.get('lobe-flex')) {
+ const stopThemeSync = startThemeSync();
+
+ let hosts: CanvasHostRoot | undefined;
+ let disposed = false;
+ const getHosts = () => {
+ hosts ??= createHostRoot({
+ onError: reportError,
+ wrap: wrapCanvasTree,
+ });
+ if (disposed) hosts.destroy();
+ return hosts;
+ };
+
+ window.addEventListener(
+ 'lobe-canvas-dispose',
+ () => {
+ disposed = true;
+ stopThemeSync();
+ hosts?.destroy();
+ },
+ { once: true },
+ );
+
+ for (const spec of CANVAS_COMPONENTS) {
+ customElements.define(
+ spec.tag,
+ defineCanvasElement(spec, views[spec.tag] ?? (() => null), getHosts),
+ );
+ }
+
+ document.dispatchEvent(new CustomEvent('lobe-canvas:ready'));
+}
diff --git a/packages/canvas-runtime/src/props.test.ts b/packages/canvas-runtime/src/props.test.ts
new file mode 100644
index 00000000000..7c421046157
--- /dev/null
+++ b/packages/canvas-runtime/src/props.test.ts
@@ -0,0 +1,51 @@
+import { CANVAS_COMPONENT_MAP } from '@lobechat/canvas';
+import { describe, expect, it } from 'vitest';
+
+import { parseAttributeValue, readChildItems, readJsonChildren, readProps } from './props';
+
+const host = (html: string) => {
+ const container = document.createElement('div');
+ container.innerHTML = html;
+ return container.firstElementChild!;
+};
+
+describe('parseAttributeValue', () => {
+ it('parses each schema type', () => {
+ expect(parseAttributeValue({ description: '', type: 'boolean' }, 'a', '')).toBe(true);
+ expect(parseAttributeValue({ description: '', type: 'boolean' }, 'a', 'false')).toBe(false);
+ expect(parseAttributeValue({ description: '', type: 'number' }, 'a', '42')).toBe(42);
+ expect(parseAttributeValue({ description: '', type: 'number' }, 'a', 'x')).toBeUndefined();
+ expect(
+ parseAttributeValue({ description: '', type: 'enum', values: ['a'] }, 'a', 'b'),
+ ).toBeUndefined();
+ expect(parseAttributeValue({ description: '', type: 'json' }, 'a', '[1]')).toEqual([1]);
+ expect(parseAttributeValue({ description: '', type: 'json' }, 'a', '{')).toBeUndefined();
+ });
+});
+
+describe('readProps', () => {
+ it('prefers attributes and falls back to JSON child data', () => {
+ const el = host(
+ `<lobe-bar-list unit="ms"><script type="application/json" data-prop="data">[{"name":"a","value":1}]</script></lobe-bar-list>`,
+ );
+ const spec = CANVAS_COMPONENT_MAP.get('lobe-bar-list')!;
+
+ expect(readProps(el, spec, readJsonChildren(el))).toEqual({
+ data: [{ name: 'a', value: 1 }],
+ unit: 'ms',
+ });
+ });
+});
+
+describe('readChildItems', () => {
+ it('reads option-like children with their label and nodes', () => {
+ const el = host(
+ `<lobe-select value="b"><lobe-option value="a">A</lobe-option><lobe-option value="b" disabled>B</lobe-option></lobe-select>`,
+ );
+
+ expect(readChildItems(el).map(({ attrs, label, tag }) => ({ attrs, label, tag }))).toEqual([
+ { attrs: { value: 'a' }, label: 'A', tag: 'lobe-option' },
+ { attrs: { disabled: '', value: 'b' }, label: 'B', tag: 'lobe-option' },
+ ]);
+ });
+});
diff --git a/packages/canvas-runtime/src/props.ts b/packages/canvas-runtime/src/props.ts
new file mode 100644
index 00000000000..5c15c3c0e8b
--- /dev/null
+++ b/packages/canvas-runtime/src/props.ts
@@ -0,0 +1,84 @@
+import type { CanvasAttributeSpec, CanvasComponentSpec } from '@lobechat/canvas';
+
+export const parseAttributeValue = (
+ spec: CanvasAttributeSpec,
+ name: string,
+ raw: string | null,
+) => {
+ if (raw === null) return undefined;
+
+ switch (spec.type) {
+ case 'boolean': {
+ return raw !== 'false';
+ }
+ case 'number': {
+ const value = Number(raw);
+ return raw.trim() !== '' && Number.isFinite(value) ? value : undefined;
+ }
+ case 'enum': {
+ return spec.values?.includes(raw) ? raw : undefined;
+ }
+ case 'json': {
+ try {
+ return JSON.parse(raw);
+ } catch {
+ console.warn(`[lobe-canvas] ${name} is not valid JSON`);
+ return undefined;
+ }
+ }
+ default: {
+ return raw;
+ }
+ }
+};
+
+export interface CanvasChildItem {
+ attrs: Record<string, string>;
+ label: string;
+ nodes: Node[];
+ tag: string;
+}
+
+export const readJsonChildren = (host: Element) => {
+ const data: Record<string, unknown> = {};
+ for (const script of host.querySelectorAll(
+ ':scope > script[type="application/json"][data-prop]',
+ )) {
+ const prop = script.getAttribute('data-prop')!;
+ try {
+ data[prop] = JSON.parse(script.textContent ?? '');
+ } catch {
+ console.warn(`[lobe-canvas] data-prop="${prop}" script is not valid JSON`);
+ }
+ }
+ return data;
+};
+
+export const readChildItems = (host: Element): CanvasChildItem[] =>
+ [...host.children]
+ .filter((child) => child.tagName.toLowerCase().startsWith('lobe-'))
+ .map((child) => ({
+ attrs: Object.fromEntries([...child.attributes].map((attr) => [attr.name, attr.value])),
+ label: child.textContent?.trim() ?? '',
+ nodes: [...child.childNodes],
+ tag: child.tagName.toLowerCase(),
+ }));
+
+export const jsonSourceAttributes = (spec: CanvasComponentSpec) =>
+ Object.entries(spec.attributes)
+ .filter(([, attr]) => attr.type === 'json')
+ .map(([name]) => `${name}-src`);
+
+export const readProps = (
+ host: Element,
+ spec: CanvasComponentSpec,
+ overrides: Record<string, unknown>,
+): Record<string, unknown> => {
+ const props: Record<string, unknown> = {};
+ for (const [name, attr] of Object.entries(spec.attributes)) {
+ const value = parseAttributeValue(attr, name, host.getAttribute(name));
+ if (value !== undefined) props[name] = value;
+ else if (name in overrides) props[name] = overrides[name];
+ }
+ return props;
+};
diff --git a/packages/canvas-runtime/src/providers.test.ts b/packages/canvas-runtime/src/providers.test.ts
new file mode 100644
index 00000000000..d25bb7c2e0e
--- /dev/null
+++ b/packages/canvas-runtime/src/providers.test.ts
@@ -0,0 +1,26 @@
+import { act, createElement } from 'react';
+import { createRoot } from 'react-dom/client';
+import { describe, expect, it } from 'vitest';
+
+import { wrapCanvasTree } from './providers';
+
+(globalThis as any).IS_REACT_ACT_ENVIRONMENT = true;
+
+describe('wrapCanvasTree', () => {
+ it('does not request CDN webfonts that the canvas CSP would block', async () => {
+ const container = document.createElement('div');
+ document.body.append(container);
+ const root = createRoot(container);
+
+ await act(async () => {
+ root.render(wrapCanvasTree(createElement('span', null, 'x')));
+ });
+
+ const urls = [...document.querySelectorAll('link[href], style')].map(
+ (node) => (node as HTMLLinkElement).href || node.textContent || '',
+ );
+ expect(container.textContent).toBe('x');
+ expect(urls.filter((url) => /webfont|katex|npmmirror|jsdelivr|unpkg/.test(url))).toEqual([]);
+ act(() => root.unmount());
+ });
+});
diff --git a/packages/canvas-runtime/src/providers.tsx b/packages/canvas-runtime/src/providers.tsx
new file mode 100644
index 00000000000..8221ac58de6
--- /dev/null
+++ b/packages/canvas-runtime/src/providers.tsx
@@ -0,0 +1,10 @@
+import { ConfigProvider } from '@lobehub/ui';
+import { motion } from 'motion/react';
+import type { ReactNode } from 'react';
+
+// The canvas CSP only allows same-origin fonts, so lobe-ui's CDN webfonts would be blocked.
+export const wrapCanvasTree = (children: ReactNode) => (
+ <ConfigProvider enableCustomFonts={false} motion={motion}>
+ {children}
+ </ConfigProvider>
+);
diff --git a/packages/canvas-runtime/src/theme.ts b/packages/canvas-runtime/src/theme.ts
new file mode 100644
index 00000000000..c6fd969cf2c
--- /dev/null
+++ b/packages/canvas-runtime/src/theme.ts
@@ -0,0 +1,37 @@
+import { type LobeThemeState, setLobeTheme } from '@lobehub/ui';
+
+declare global {
+ interface Window {
+ __LOBE_CANVAS_THEME__?: Partial<LobeThemeState>;
+ }
+}
+
+const systemAppearance = () =>
+ matchMedia('(prefers-color-scheme: dark)').matches ? ('dark' as const) : ('light' as const);
+
+export const startThemeSync = () => {
+ let hostTheme = window.__LOBE_CANVAS_THEME__;
+
+ const apply = () => {
+ const appearance = hostTheme?.appearance ?? systemAppearance();
+ setLobeTheme({ ...hostTheme, appearance });
+ document.documentElement.style.colorScheme = appearance;
+ };
+
+ const onTheme = (event: Event) => {
+ hostTheme = (event as CustomEvent<Partial<LobeThemeState>>).detail;
+ apply();
+ };
+ const onSystemTheme = () => {
+ if (!hostTheme?.appearance) apply();
+ };
+ const media = matchMedia('(prefers-color-scheme: dark)');
+ window.addEventListener('lobe-canvas-theme', onTheme);
+ media.addEventListener('change', onSystemTheme);
+
+ apply();
+ return () => {
+ window.removeEventListener('lobe-canvas-theme', onTheme);
+ media.removeEventListener('change', onSystemTheme);
+ };
+};
diff --git a/packages/canvas-runtime/src/views/base.tsx b/packages/canvas-runtime/src/views/base.tsx
new file mode 100644
index 00000000000..97ebd7a0077
--- /dev/null
+++ b/packages/canvas-runtime/src/views/base.tsx
@@ -0,0 +1,278 @@
+import {
+ Accordion,
+ Alert,
+ Badge,
+ Block,
+ Button,
+ Checkbox,
+ Descriptions,
+ Divider,
+ Flexbox,
+ Grid,
+ Input,
+ Progress,
+ RadioGroup,
+ Segmented,
+ Select,
+ Slider,
+ Statistic,
+ Steps,
+ Switch,
+ Table,
+ Tabs,
+ Tag,
+ Text,
+} from '@lobehub/ui';
+import { ArrowDownRight, ArrowRight, ArrowUpRight } from 'lucide-react';
+import { memo, type ReactNode, useState } from 'react';
+
+import type { CanvasView, CanvasViewContext } from '../element';
+import { formatValue } from '../format';
+import type { CanvasChildItem } from '../props';
+
+const Slot = ({ slot }: Pick<CanvasViewContext, 'slot'>) => (
+ <span data-lobe-canvas-slot="" ref={slot} />
+);
+
+const NodesSlot = memo<{ nodes: Node[] }>(({ nodes }) => (
+ <span
+ data-lobe-canvas-flow=""
+ data-lobe-canvas-slot=""
+ ref={(node) => {
+ if (node && node.childNodes.length === 0) node.append(...nodes);
+ }}
+ />
+));
+
+const optionsOf = (items: CanvasChildItem[]) =>
+ items
+ .filter((item) => item.tag === 'lobe-option')
+ .map((item) => ({
+ disabled: 'disabled' in item.attrs && item.attrs.disabled !== 'false',
+ label: item.label,
+ value: item.attrs.value ?? item.label,
+ }));
+
+const TabsView = memo<{ context: CanvasViewContext }>(({ context }) => {
+ const tabs = context.items.filter((item) => item.tag === 'lobe-tab');
+ const [active, setActive] = useState<string | undefined>(
+ (context.props.value as string | undefined) ?? tabs[0]?.attrs.value,
+ );
+ return (
+ <Tabs
+ activeKey={active}
+ items={tabs.map((tab) => ({
+ children: <NodesSlot nodes={tab.nodes} />,
+ key: tab.attrs.value,
+ label: tab.attrs.label,
+ }))}
+ onChange={(key) => {
+ setActive(key);
+ context.change(key);
+ }}
+ />
+ );
+});
+
+const TREND_ICONS = { down: ArrowDownRight, flat: ArrowRight, up: ArrowUpRight };
+
+const StatView = memo<{ props: Record<string, any> }>(({ props }) => {
+ const TrendIcon = props.trend ? TREND_ICONS[props.trend as keyof typeof TREND_ICONS] : undefined;
+ return (
+ <Block gap={4} padding={16} variant={'outlined'}>
+ <Statistic
+ precision={props.precision}
+ prefix={props.prefix}
+ suffix={props.suffix}
+ title={props.title}
+ value={props.value}
+ />
+ {(TrendIcon || props['trend-text']) && (
+ <Flexbox horizontal align={'center'} gap={4}>
+ {TrendIcon && <TrendIcon size={14} />}
+ <Text fontSize={12} type={'secondary'}>
+ {props['trend-text']}
+ </Text>
+ </Flexbox>
+ )}
+ </Block>
+ );
+});
+
+const card = (context: CanvasViewContext): ReactNode => {
+ const { props } = context;
+ return (
+ <Block gap={12} padding={props.padding ?? 16} variant={props.variant ?? 'outlined'}>
+ {props.title && <Text strong>{props.title}</Text>}
+ <Slot slot={context.slot} />
+ </Block>
+ );
+};
+
+export const baseViews: Record<string, CanvasView> = {
+ 'lobe-accordion': ({ items }) => {
+ const sections = items.filter((item) => item.tag === 'lobe-accordion-item');
+ return (
+ <Accordion
+ defaultValue={sections.flatMap((section, index) =>
+ 'open' in section.attrs ? [`s${index}`] : [],
+ )}
+ items={sections.map((section, index) => ({
+ children: <NodesSlot nodes={section.nodes} />,
+ key: `s${index}`,
+ title: section.attrs.title,
+ }))}
+ />
+ );
+ },
+ 'lobe-alert': ({ props, slot }) => (
+ <Alert description={<Slot slot={slot} />} title={props.title} type={props.type ?? 'info'} />
+ ),
+ 'lobe-badge': ({ props }) => (
+ <Badge count={props.count} status={props.status} text={props.text} />
+ ),
+ 'lobe-button': (context) => (
+ <Button
+ block={context.props.block}
+ disabled={context.props.disabled}
+ size={context.props.size}
+ type={context.props.type ?? 'default'}
+ onClick={() => context.change(context.props.value ?? true)}
+ >
+ <Slot slot={context.slot} />
+ </Button>
+ ),
+ 'lobe-card': card,
+ 'lobe-checkbox': (context) => (
+ <Checkbox
+ checked={context.checked}
+ disabled={context.props.disabled}
+ onChange={(checked) => context.change(checked)}
+ >
+ <Slot slot={context.slot} />
+ </Checkbox>
+ ),
+ 'lobe-descriptions': ({ props }) => (
+ <Descriptions
+ column={props.columns ?? 2}
+ items={(Array.isArray(props.items) ? props.items : []).map((item: any, index: number) => ({
+ children: formatValue(item.value),
+ key: String(index),
+ label: item.label,
+ }))}
+ />
+ ),
+ 'lobe-divider': ({ props }) => <Divider dashed={props.dashed} />,
+ 'lobe-flex': ({ props, slot }) => (
+ <Flexbox
+ align={props.align}
+ gap={props.gap ?? 12}
+ horizontal={props.horizontal}
+ justify={props.justify}
+ wrap={props.wrap ? 'wrap' : undefined}
+ >
+ <Slot slot={slot} />
+ </Flexbox>
+ ),
+ 'lobe-grid': ({ props, slot }) => (
+ <Grid gap={props.gap ?? 12} maxItemWidth={props['max-item-width']} rows={props.rows}>
+ <Slot slot={slot} />
+ </Grid>
+ ),
+ 'lobe-input': (context) => (
+ <Input
+ defaultValue={context.value as string | undefined}
+ disabled={context.props.disabled}
+ placeholder={context.props.placeholder}
+ size={context.props.size}
+ onChange={(event) => context.change(event.target.value)}
+ />
+ ),
+ 'lobe-progress': ({ props }) => (
+ <Progress percent={props.percent ?? 0} status={props.status} type={props.type} />
+ ),
+ 'lobe-radio-group': (context) => (
+ <RadioGroup
+ disabled={context.props.disabled}
+ options={optionsOf(context.items)}
+ value={context.value as string | undefined}
+ onChange={(value) => context.change(value)}
+ />
+ ),
+ 'lobe-segmented': (context) => (
+ <Segmented
+ disabled={context.props.disabled}
+ options={optionsOf(context.items)}
+ size={context.props.size}
+ value={context.value as string | undefined}
+ onChange={(value) => context.change(value)}
+ />
+ ),
+ 'lobe-select': (context) => (
+ <Select
+ disabled={context.props.disabled}
+ options={optionsOf(context.items)}
+ placeholder={context.props.placeholder}
+ size={context.props.size}
+ style={{ minWidth: 160 }}
+ value={context.value as string | undefined}
+ onChange={(value) => context.change(value)}
+ />
+ ),
+ 'lobe-slider': (context) => (
+ <Slider
+ disabled={context.props.disabled}
+ max={context.props.max ?? 100}
+ min={context.props.min ?? 0}
+ step={context.props.step ?? 1}
+ value={typeof context.value === 'number' ? context.value : Number(context.value ?? 0)}
+ onChange={(value) => context.change(value)}
+ />
+ ),
+ 'lobe-stat': ({ props }) => <StatView props={props} />,
+ 'lobe-steps': ({ props }) => (
+ <Steps
+ items={Array.isArray(props.items) ? props.items : []}
+ orientation={props.vertical ? 'vertical' : 'horizontal'}
+ />
+ ),
+ 'lobe-switch': (context) => (
+ <Flexbox horizontal align={'center'} gap={8}>
+ <Switch
+ checked={context.checked}
+ disabled={context.props.disabled}
+ onChange={(checked) => context.change(checked)}
+ />
+ {context.props.label && <Text>{context.props.label}</Text>}
+ </Flexbox>
+ ),
+ 'lobe-table': ({ props }) => {
+ const columns = (Array.isArray(props.columns) ? props.columns : []).map((column: any) => ({
+ align: column.align,
+ dataIndex: column.key,
+ key: column.key,
+ render: (value: unknown) => formatValue(value, column.format),
+ title: column.title,
+ }));
+ const data = (Array.isArray(props.data) ? props.data : []).map((row: any, index: number) => ({
+ __key: String(index),
+ ...row,
+ }));
+ return (
+ <Table
+ columns={columns}
+ dataSource={data}
+ pagination={false}
+ rowKey={'__key'}
+ size={'middle'}
+ variant={'outlined'}
+ />
+ );
+ },
+ 'lobe-tabs': (context) => <TabsView context={context} />,
+ 'lobe-tag': ({ props, slot }) => (
+ <Tag color={props.color}>
+ <Slot slot={slot} />
+ </Tag>
+ ),
+};
diff --git a/packages/canvas-runtime/src/views/charts.tsx b/packages/canvas-runtime/src/views/charts.tsx
new file mode 100644
index 00000000000..dac9a52b95d
--- /dev/null
+++ b/packages/canvas-runtime/src/views/charts.tsx
@@ -0,0 +1,142 @@
+import {
+ AreaChart,
+ BarChart,
+ BarList,
+ DonutChart,
+ FunnelChart,
+ Heatmaps,
+ LineChart,
+ RadarChart,
+ ScatterChart,
+ SparkAreaChart,
+ SparkBarChart,
+ SparkLineChart,
+ Tracker,
+} from '@lobehub/charts';
+import { useTheme } from '@lobehub/ui';
+import { memo } from 'react';
+
+import type { CanvasView } from '../element';
+import { formatValue, heatmapLevel } from '../format';
+
+type Props = Record<string, any>;
+
+const usePaletteColors = (names: unknown): string[] | undefined => {
+ const theme = useTheme() as unknown as Record<string, string>;
+ if (!Array.isArray(names)) return;
+ const colors = names.map((name) => theme[String(name)]).filter(Boolean);
+ return colors.length > 0 ? colors : undefined;
+};
+
+const asArray = (value: unknown) => (Array.isArray(value) ? value : []);
+
+const baseChartProps = (props: Props) => ({
+ categories: asArray(props.categories),
+ data: asArray(props.data),
+ height: props.height ?? 280,
+ index: props.index,
+ showLegend: props['show-legend'] ?? true,
+ valueFormatter: (value: number) => formatValue(value, props['value-format'], props.unit),
+});
+
+const Area = memo<{ props: Props }>(({ props }) => (
+ <AreaChart
+ {...baseChartProps(props)}
+ colors={usePaletteColors(props.colors)}
+ stack={props.stack}
+ />
+));
+
+const Bar = memo<{ props: Props }>(({ props }) => (
+ <BarChart
+ {...baseChartProps(props)}
+ colors={usePaletteColors(props.colors)}
+ layout={props.layout === 'horizontal' ? 'vertical' : 'horizontal'}
+ stack={props.stack}
+ />
+));
+
+const Line = memo<{ props: Props }>(({ props }) => (
+ <LineChart {...baseChartProps(props)} colors={usePaletteColors(props.colors)} />
+));
+
+const Radar = memo<{ props: Props }>(({ props }) => (
+ <RadarChart {...baseChartProps(props)} colors={usePaletteColors(props.colors)} />
+));
+
+const Scatter = memo<{ props: Props }>(({ props }) => (
+ <ScatterChart
+ category={props.category}
+ colors={usePaletteColors(props.colors)}
+ data={asArray(props.data)}
+ height={props.height ?? 280}
+ showLegend={props['show-legend'] ?? true}
+ size={props.size}
+ x={props.x}
+ y={props.y}
+ />
+));
+
+const Donut = memo<{ props: Props }>(({ props }) => (
+ <DonutChart
+ category={props.category}
+ colors={usePaletteColors(props.colors)}
+ data={asArray(props.data)}
+ index={props.index}
+ valueFormatter={(value: number) => formatValue(value, props['value-format'], props.unit)}
+ variant={props.variant ?? 'donut'}
+ />
+));
+
+const Spark = memo<{ props: Props }>(({ props }) => {
+ const colors = usePaletteColors(props.colors);
+ const common = {
+ categories: asArray(props.categories),
+ colors,
+ data: asArray(props.data),
+ index: props.index,
+ };
+ if (props.kind === 'bar') return <SparkBarChart {...common} />;
+ if (props.kind === 'line') return <SparkLineChart {...common} />;
+ return <SparkAreaChart {...common} />;
+});
+
+const TrackerView = memo<{ props: Props }>(({ props }) => {
+ const theme = useTheme() as unknown as Record<string, string>;
+ const data = asArray(props.data).map((item: Props, index) => ({
+ color: theme[item.color] ?? item.color,
+ key: String(index),
+ tooltip: item.tooltip,
+ }));
+ return <Tracker data={data} />;
+});
+
+const Heatmap = memo<{ props: Props }>(({ props }) => {
+ const rows = asArray(props.data) as Props[];
+ const max = Math.max(0, ...rows.map((row) => Number(row.count) || 0));
+ const data = rows.map((row) => ({
+ count: Number(row.count) || 0,
+ date: String(row.date),
+ level: typeof row.level === 'number' ? row.level : heatmapLevel(Number(row.count) || 0, max),
+ }));
+ return <Heatmaps data={data} />;
+});
+
+export const chartViews: Record<string, CanvasView> = {
+ 'lobe-area-chart': ({ props }) => <Area props={props} />,
+ 'lobe-bar-chart': ({ props }) => <Bar props={props} />,
+ 'lobe-bar-list': ({ props }) => (
+ <BarList
+ data={asArray(props.data)}
+ valueFormatter={(value: number) => formatValue(value, props['value-format'], props.unit)}
+ />
+ ),
+ 'lobe-donut-chart': ({ props }) => <Donut props={props} />,
+ 'lobe-funnel-chart': ({ props }) => <FunnelChart data={asArray(props.data)} />,
+ 'lobe-heatmap': ({ props }) => <Heatmap props={props} />,
+ 'lobe-line-chart': ({ props }) => <Line props={props} />,
+ 'lobe-radar-chart': ({ props }) => <Radar props={props} />,
+ 'lobe-scatter-chart': ({ props }) => <Scatter props={props} />,
+ 'lobe-spark-chart': ({ props }) => <Spark props={props} />,
+ 'lobe-tracker': ({ props }) => <TrackerView props={props} />,
+};
diff --git a/packages/canvas-runtime/src/views/code.tsx b/packages/canvas-runtime/src/views/code.tsx
new file mode 100644
index 00000000000..697c1d1dce2
--- /dev/null
+++ b/packages/canvas-runtime/src/views/code.tsx
@@ -0,0 +1,48 @@
+import { CopyButton } from '@lobehub/ui';
+import { memo, useEffect, useState } from 'react';
+
+import { loadCanvasAddon } from '../addons/load';
+import { normalizeCodeText } from '../codeText';
+import type { CanvasView } from '../element';
+
+const CodeBlock = memo<{ code: string; language?: string }>(({ code, language }) => {
+ const [html, setHtml] = useState<string>();
+
+ useEffect(() => {
+ let live = true;
+ setHtml(undefined);
+ loadCanvasAddon('highlight')
+ .then((addon) => addon.highlight(code, language))
+ .then((next) => {
+ if (live) setHtml(next);
+ })
+ .catch((error) => console.error('[lobe-canvas] code highlighting failed', error));
+ return () => {
+ live = false;
+ };
+ }, [code, language]);
+
+ return (
+ <div data-lobe-canvas-code="">
+ <div data-lobe-canvas-code-header="">
+ <span>{language || 'text'}</span>
+ <CopyButton content={code} size={'small'} />
+ </div>
+ {html ? (
+ <div dangerouslySetInnerHTML={{ __html: html }} />
+ ) : (
+ <pre>
+ <code>{code}</code>
+ </pre>
+ )}
+ </div>
+ );
+});
+
+CodeBlock.displayName = 'CanvasCodeBlock';
+
+export const codeViews: Record<string, CanvasView> = {
+ 'lobe-code': ({ props, text }) => (
+ <CodeBlock code={normalizeCodeText(text)} language={props.language} />
+ ),
+};
diff --git a/packages/canvas-runtime/src/views/mermaid.tsx b/packages/canvas-runtime/src/views/mermaid.tsx
new file mode 100644
index 00000000000..fb038fc6dc1
--- /dev/null
+++ b/packages/canvas-runtime/src/views/mermaid.tsx
@@ -0,0 +1,80 @@
+import { type CSSProperties, memo, useEffect, useId, useRef, useState } from 'react';
+
+import { loadCanvasAddon } from '../addons/load';
+import type { CanvasMermaidMount } from '../addons/registry';
+import { normalizeCodeText } from '../codeText';
+import type { CanvasView } from '../element';
+
+const SERIES = ['blue', 'gold', 'green', 'red', 'purple', 'cyan', 'orange', 'magenta'];
+
+// Same mapping lobe-ui's Mermaid uses for its default theme, so diagrams follow the app theme.
+const PELE_THEME = {
+ '--pele-accent': 'var(--lobe-color-primary)',
+ '--pele-bg': 'var(--lobe-color-bg-container)',
+ '--pele-border': 'var(--lobe-color-border)',
+ '--pele-critical': 'var(--lobe-color-error)',
+ '--pele-error': 'var(--lobe-color-error)',
+ '--pele-fg': 'var(--lobe-color-text)',
+ '--pele-font': 'var(--lobe-font-family)',
+ '--pele-font-mono': 'var(--lobe-font-family-code)',
+ '--pele-line': 'var(--lobe-color-text-secondary)',
+ '--pele-muted': 'var(--lobe-color-text-description)',
+ '--pele-radius': 'var(--lobe-border-radius)',
+ '--pele-surface': 'var(--lobe-color-fill-tertiary)',
+ '--pele-surface-alt': 'var(--lobe-color-fill-secondary)',
+ ...Object.fromEntries(
+ SERIES.map((color, index) => [`--pele-series-${index + 1}`, `var(--lobe-${color})`]),
+ ),
+} as CSSProperties;
+
+const reportDiagramError = (message: string) =>
+ window.dispatchEvent(
+ new CustomEvent('lobe-canvas-component-error', { detail: { message, tag: 'lobe-mermaid' } }),
+ );
+
+const MermaidDiagram = memo<{ source: string }>(({ source }) => {
+ const reactId = useId();
+ const idPrefix = `lobe-mermaid-${reactId.replaceAll(':', '')}-`;
+ const container = useRef<HTMLDivElement>(null);
+ const [error, setError] = useState<string>();
+
+ useEffect(() => {
+ let live = true;
+ let mounted: CanvasMermaidMount | undefined;
+ setError(undefined);
+
+ const fail = (message: string) => {
+ if (!live) return;
+ setError(message);
+ reportDiagramError(message);
+ };
+
+ loadCanvasAddon('mermaid')
+ .then((addon) => {
+ if (!live || !container.current) return;
+ mounted = addon.mount(container.current, source, idPrefix);
+ if (mounted.error) fail(mounted.error);
+ })
+ .catch((reason: unknown) => fail(reason instanceof Error ? reason.message : String(reason)));
+
+ return () => {
+ live = false;
+ mounted?.destroy();
+ };
+ }, [source, idPrefix]);
+
+ if (error)
+ return (
+ <pre data-lobe-canvas-mermaid-fallback="">
+ <code>{source}</code>
+ </pre>
+ );
+
+ return <div data-lobe-canvas-mermaid="" ref={container} style={PELE_THEME} />;
+});
+
+MermaidDiagram.displayName = 'CanvasMermaidDiagram';
+
+export const mermaidViews: Record<string, CanvasView> = {
+ 'lobe-mermaid': ({ text }) => <MermaidDiagram source={normalizeCodeText(text)} />,
+};
diff --git a/packages/canvas-runtime/vite.config.ts b/packages/canvas-runtime/vite.config.ts
new file mode 100644
index 00000000000..4d38eb18071
--- /dev/null
+++ b/packages/canvas-runtime/vite.config.ts
@@ -0,0 +1,34 @@
+import react from '@vitejs/plugin-react';
+import { defineConfig } from 'vite';
+
+import { lobeUiImports } from '../../plugins/vite/lobeUiImports';
+
+const ADDONS = new Set(['highlight', 'mermaid']);
+
+// Each add-on is its own classic script: sandboxed canvas pages have an opaque origin,
+// so ES module chunks would need CORS headers from wherever the runtime is hosted.
+export default defineConfig(({ mode }) => {
+ const addon = ADDONS.has(mode) ? mode : undefined;
+ const file = addon ? `canvas-runtime-${addon}` : 'canvas-runtime';
+
+ return {
+ build: {
+ assetsInlineLimit: 100_000_000,
+ cssCodeSplit: false,
+ emptyOutDir: !addon,
+ minify: true,
+ lib: {
+ entry: addon ? `src/addons/${addon}.ts` : 'src/index.tsx',
+ fileName: () => `${file}.js`,
+ formats: ['iife'],
+ name: addon ? `LobeCanvasAddon_${addon}` : 'LobeCanvasRuntime',
+ },
+ outDir: 'dist',
+ rolldownOptions: {
+ output: { assetFileNames: `${file}.css` },
+ },
+ },
+ define: { 'process.env.NODE_ENV': '"production"' },
+ plugins: [react(), ...lobeUiImports()],
+ };
+});
diff --git a/packages/canvas-runtime/vitest.config.mts b/packages/canvas-runtime/vitest.config.mts
new file mode 100644
index 00000000000..a9f5456ffd2
--- /dev/null
+++ b/packages/canvas-runtime/vitest.config.mts
@@ -0,0 +1,7 @@
+import { defineConfig } from 'vitest/config';
+
+export default defineConfig({
+ test: {
+ environment: 'happy-dom',
+ },
+});
diff --git a/packages/canvas/package.json b/packages/canvas/package.json
new file mode 100644
index 00000000000..4a68aa5af91
--- /dev/null
+++ b/packages/canvas/package.json
@@ -0,0 +1,21 @@
+{
+ "name": "@lobechat/canvas",
+ "version": "1.0.0",
+ "private": true,
+ "sideEffects": false,
+ "exports": {
+ ".": "./src/index.ts",
+ "./mermaid": "./src/mermaid.ts",
+ "./runtime": "./src/runtime/index.ts"
+ },
+ "main": "./src/index.ts",
+ "types": "./src/index.ts",
+ "scripts": {
+ "test": "vitest",
+ "test:coverage": "vitest --coverage --silent='passed-only'"
+ },
+ "dependencies": {
+ "htmlparser2": "^10.1.0",
+ "pele": "^1.6.0"
+ }
+}
diff --git a/packages/canvas/src/index.ts b/packages/canvas/src/index.ts
new file mode 100644
index 00000000000..5345203af2a
--- /dev/null
+++ b/packages/canvas/src/index.ts
@@ -0,0 +1,9 @@
+export * from './project/changes';
+export * from './project/limits';
+export * from './project/manifest';
+export * from './project/path';
+export * from './schema/components';
+export * from './schema/reference';
+export type * from './schema/types';
+export * from './validate/types';
+export * from './validate/validateCanvasProject';
diff --git a/packages/canvas/src/mermaid.ts b/packages/canvas/src/mermaid.ts
new file mode 100644
index 00000000000..38726e38c1d
--- /dev/null
+++ b/packages/canvas/src/mermaid.ts
@@ -0,0 +1,20 @@
+import { parse, PeleError } from 'pele';
+
+import type { CanvasMermaidProblem } from './validate/types';
+
+const MAX_MESSAGE_LENGTH = 600;
+
+export const checkCanvasMermaid = (source: string): CanvasMermaidProblem | undefined => {
+ try {
+ parse(source);
+ return;
+ } catch (error) {
+ const message = (error instanceof Error ? error.message : String(error)).slice(
+ 0,
+ MAX_MESSAGE_LENGTH,
+ );
+ return error instanceof PeleError && error.line > 0
+ ? { line: error.line, message }
+ : { message };
+ }
+};
diff --git a/packages/canvas/src/project/changes.test.ts b/packages/canvas/src/project/changes.test.ts
new file mode 100644
index 00000000000..1ac8e6edce0
--- /dev/null
+++ b/packages/canvas/src/project/changes.test.ts
@@ -0,0 +1,105 @@
+import { describe, expect, it } from 'vitest';
+
+import { applyCanvasChanges, collectCanvasFileRefs } from './changes';
+
+const base = new Map([
+ ['index.html', { content: '<h1>Old title</h1><p>body</p>', path: 'index.html' }],
+ ['data.json', { content: '[1]', path: 'data.json' }],
+]);
+
+const textOf = (result: ReturnType<typeof applyCanvasChanges>, path: string) => {
+ if (!result.ok) throw new Error(result.error);
+ return result.files.find((file) => file.path === path)?.content;
+};
+
+describe('applyCanvasChanges', () => {
+ it('writes, replaces and deletes files in one change set', () => {
+ const result = applyCanvasChanges(base, {
+ deletes: ['data.json'],
+ edits: [{ newText: 'New title', oldText: 'Old title', path: 'index.html' }],
+ writes: [{ content: 'body{}', path: './css/app.css' }],
+ });
+
+ expect(result.ok).toBe(true);
+ expect(textOf(result, 'index.html')).toBe('<h1>New title</h1><p>body</p>');
+ expect(textOf(result, 'css/app.css')).toBe('body{}');
+ expect(textOf(result, 'data.json')).toBeUndefined();
+ });
+
+ it('decodes base64 writes into bytes', () => {
+ const result = applyCanvasChanges(new Map(), {
+ writes: [{ content: 'AQID', encoding: 'base64', path: 'a.png' }],
+ });
+
+ expect(textOf(result, 'a.png')).toEqual(new Uint8Array([1, 2, 3]));
+ });
+
+ it('rejects an edit whose old text is missing or ambiguous', () => {
+ expect(
+ applyCanvasChanges(base, { edits: [{ newText: 'x', oldText: 'nope', path: 'index.html' }] }),
+ ).toMatchObject({ ok: false });
+ expect(
+ applyCanvasChanges(new Map([['a.html', { content: 'aa', path: 'a.html' }]]), {
+ edits: [{ newText: 'b', oldText: 'a', path: 'a.html' }],
+ }),
+ ).toMatchObject({ error: expect.stringContaining('2 times'), ok: false });
+ });
+
+ it('rejects edits and deletes of files that do not exist', () => {
+ expect(applyCanvasChanges(base, { deletes: ['nope.css'] })).toMatchObject({ ok: false });
+ expect(
+ applyCanvasChanges(base, { edits: [{ newText: 'b', oldText: 'a', path: 'nope.html' }] }),
+ ).toMatchObject({ ok: false });
+ });
+
+ it('rejects edits of binary files', () => {
+ const binary = new Map([['a.png', { content: new Uint8Array([1]), path: 'a.png' }]]);
+ expect(
+ applyCanvasChanges(binary, { edits: [{ newText: 'b', oldText: 'a', path: 'a.png' }] }),
+ ).toMatchObject({ ok: false });
+ });
+
+ it('fills fileRef writes from the resolved contents', () => {
+ const bytes = new Uint8Array([1, 2, 3]);
+ const result = applyCanvasChanges(
+ new Map(),
+ { writes: [{ fileRef: 'file_logo', path: './img/logo.png' }] },
+ new Map([['file_logo', bytes]]),
+ );
+
+ expect(textOf(result, 'img/logo.png')).toBe(bytes);
+ });
+
+ it('refuses a fileRef write that was not resolved', () => {
+ const result = applyCanvasChanges(new Map(), {
+ writes: [{ fileRef: 'file_missing', path: 'img/logo.png' }],
+ });
+
+ expect(result).toEqual({
+ error: '"img/logo.png": fileRef "file_missing" could not be resolved.',
+ ok: false,
+ });
+ });
+});
+
+describe('collectCanvasFileRefs', () => {
+ it('treats an empty fileRef as a plain content write', () => {
+ const changes = {
+ writes: [{ content: 'body{}', encoding: 'utf8' as const, fileRef: '', path: 'app.css' }],
+ };
+
+ expect(collectCanvasFileRefs(changes)).toEqual([]);
+ expect(textOf(applyCanvasChanges(new Map(), changes), 'app.css')).toBe('body{}');
+ });
+
+ it('lists the fileRef writes with normalized paths', () => {
+ expect(
+ collectCanvasFileRefs({
+ writes: [
+ { content: 'body{}', path: 'app.css' },
+ { fileRef: 'msg_abc.image_1', path: './img/photo.jpg' },
+ ],
+ }),
+ ).toEqual([{ fileRef: 'msg_abc.image_1', path: 'img/photo.jpg' }]);
+ });
+});
diff --git a/packages/canvas/src/project/changes.ts b/packages/canvas/src/project/changes.ts
new file mode 100644
index 00000000000..aa418bc82d5
--- /dev/null
+++ b/packages/canvas/src/project/changes.ts
@@ -0,0 +1,115 @@
+import type { CanvasProjectFile } from '../validate/types';
+import { normalizeCanvasPath } from './path';
+
+export interface CanvasFileWrite {
+ content?: string;
+ encoding?: 'base64' | 'utf8';
+ fileRef?: string;
+ path: string;
+}
+
+export interface CanvasFileRefWrite {
+ fileRef: string;
+ path: string;
+}
+
+export interface CanvasFileEdit {
+ newText: string;
+ oldText: string;
+ path: string;
+}
+
+export interface CanvasChangeSet {
+ deletes?: string[];
+ edits?: CanvasFileEdit[];
+ writes?: CanvasFileWrite[];
+}
+
+export type CanvasChangeResult =
+ { error: string; ok: false } | { files: CanvasProjectFile[]; ok: true };
+
+const decodeBase64 = (value: string) => Uint8Array.from(atob(value), (char) => char.charCodeAt(0));
+
+// Strict tool-calling models fill every schema property, so a plain write arrives with fileRef "".
+export const isCanvasFileRefWrite = (write: CanvasFileWrite): write is CanvasFileRefWrite =>
+ typeof write.fileRef === 'string' && write.fileRef.length > 0;
+
+export const collectCanvasFileRefs = (changes: CanvasChangeSet): CanvasFileRefWrite[] =>
+ (changes.writes ?? []).filter(isCanvasFileRefWrite).map((write) => ({
+ fileRef: write.fileRef,
+ path: normalizeCanvasPath(write.path) ?? write.path,
+ }));
+
+const countOccurrences = (text: string, search: string) => {
+ let count = 0;
+ for (let index = text.indexOf(search); index !== -1; index = text.indexOf(search, index + 1)) {
+ count += 1;
+ }
+ return count;
+};
+
+export const applyCanvasChanges = (
+ base: ReadonlyMap<string, CanvasProjectFile>,
+ changes: CanvasChangeSet,
+ resolvedFileRefs: ReadonlyMap<string, string | Uint8Array> = new Map(),
+): CanvasChangeResult => {
+ const files = new Map(base);
+
+ for (const write of changes.writes ?? []) {
+ const path = normalizeCanvasPath(write.path) ?? write.path;
+ if (isCanvasFileRefWrite(write)) {
+ const content = resolvedFileRefs.get(write.fileRef);
+ if (content === undefined) {
+ return {
+ error: `"${path}": fileRef "${write.fileRef}" could not be resolved.`,
+ ok: false,
+ };
+ }
+ files.set(path, { content, path });
+ continue;
+ }
+
+ if (write.content === undefined) {
+ return { error: `"${path}": provide content or fileRef.`, ok: false };
+ }
+ let content: string | Uint8Array = write.content;
+ if (write.encoding === 'base64') {
+ try {
+ content = decodeBase64(write.content);
+ } catch {
+ return { error: `"${write.path}" is not valid base64.`, ok: false };
+ }
+ }
+ files.set(path, { content, path });
+ }
+
+ for (const edit of changes.edits ?? []) {
+ const path = normalizeCanvasPath(edit.path) ?? edit.path;
+ const file = files.get(path);
+ if (!file) return { error: `Cannot edit "${edit.path}": the file does not exist.`, ok: false };
+ if (typeof file.content !== 'string') {
+ return {
+ error: `Cannot edit "${edit.path}": it is a binary file. Write it instead.`,
+ ok: false,
+ };
+ }
+
+ const occurrences = countOccurrences(file.content, edit.oldText);
+ if (occurrences !== 1) {
+ return {
+ error: `Cannot edit "${edit.path}": oldText appears ${occurrences} times; it must appear exactly once. Include more surrounding text.`,
+ ok: false,
+ };
+ }
+ files.set(path, { content: file.content.replace(edit.oldText, () => edit.newText), path });
+ }
+
+ for (const target of changes.deletes ?? []) {
+ const path = normalizeCanvasPath(target) ?? target;
+ if (!files.delete(path)) {
+ return { error: `Cannot delete "${target}": the file does not exist.`, ok: false };
+ }
+ }
+
+ return { files: [...files.values()], ok: true };
+};
diff --git a/packages/canvas/src/project/limits.ts b/packages/canvas/src/project/limits.ts
new file mode 100644
index 00000000000..81c446b38f5
--- /dev/null
+++ b/packages/canvas/src/project/limits.ts
@@ -0,0 +1,67 @@
+export const CANVAS_ENTRY = 'index.html';
+
+export const CANVAS_LIMITS = {
+ maxFileBytes: 5 * 1024 * 1024,
+ maxFiles: 64,
+ maxTextFileBytes: 512 * 1024,
+ maxTotalBytes: 20 * 1024 * 1024,
+} as const;
+
+export const CANVAS_TEXT_EXTENSIONS = new Set([
+ 'css',
+ 'csv',
+ 'html',
+ 'js',
+ 'json',
+ 'md',
+ 'mjs',
+ 'svg',
+ 'txt',
+]);
+
+export const CANVAS_BINARY_EXTENSIONS = new Set([
+ 'avif',
+ 'gif',
+ 'ico',
+ 'jpeg',
+ 'jpg',
+ 'mp3',
+ 'mp4',
+ 'ogg',
+ 'otf',
+ 'png',
+ 'ttf',
+ 'wav',
+ 'webm',
+ 'webp',
+ 'woff',
+ 'woff2',
+]);
+
+export const CANVAS_CONTENT_TYPES: Record<string, string> = {
+ avif: 'image/avif',
+ css: 'text/css; charset=utf-8',
+ csv: 'text/csv; charset=utf-8',
+ gif: 'image/gif',
+ html: 'text/html; charset=utf-8',
+ ico: 'image/x-icon',
+ jpeg: 'image/jpeg',
+ jpg: 'image/jpeg',
+ js: 'text/javascript; charset=utf-8',
+ json: 'application/json; charset=utf-8',
+ md: 'text/markdown; charset=utf-8',
+ mjs: 'text/javascript; charset=utf-8',
+ mp3: 'audio/mpeg',
+ mp4: 'video/mp4',
+ ogg: 'audio/ogg',
+ otf: 'font/otf',
+ png: 'image/png',
+ svg: 'image/svg+xml',
+ ttf: 'font/ttf',
+ txt: 'text/plain; charset=utf-8',
+ wav: 'audio/wav',
+ webm: 'video/webm',
+ webp: 'image/webp',
+ woff: 'font/woff',
+ woff2: 'font/woff2',
+};
diff --git a/packages/canvas/src/project/manifest.ts b/packages/canvas/src/project/manifest.ts
new file mode 100644
index 00000000000..e0427b4a2ec
--- /dev/null
+++ b/packages/canvas/src/project/manifest.ts
@@ -0,0 +1,14 @@
+export const CANVAS_RUNTIME_MAJOR = 1;
+
+export interface CanvasManifestFile {
+ contentType: string;
+ hash: string;
+ size: number;
+}
+
+export interface CanvasManifest {
+ entry: string;
+ files: Record<string, CanvasManifestFile>;
+ runtimeMajor: number;
+ schemaVersion: 1;
+}
diff --git a/packages/canvas/src/project/path.ts b/packages/canvas/src/project/path.ts
new file mode 100644
index 00000000000..1ea260c524b
--- /dev/null
+++ b/packages/canvas/src/project/path.ts
@@ -0,0 +1,69 @@
+import { CANVAS_BINARY_EXTENSIONS, CANVAS_CONTENT_TYPES, CANVAS_TEXT_EXTENSIONS } from './limits';
+
+export const getCanvasFileExtension = (path: string): string => {
+ const base = path.slice(path.lastIndexOf('/') + 1);
+ const dot = base.lastIndexOf('.');
+ return dot > 0 ? base.slice(dot + 1).toLowerCase() : '';
+};
+
+export const isCanvasTextPath = (path: string) =>
+ CANVAS_TEXT_EXTENSIONS.has(getCanvasFileExtension(path));
+
+export const isAllowedCanvasPath = (path: string) => {
+ const extension = getCanvasFileExtension(path);
+ return CANVAS_TEXT_EXTENSIONS.has(extension) || CANVAS_BINARY_EXTENSIONS.has(extension);
+};
+
+export const getCanvasContentType = (path: string) =>
+ CANVAS_CONTENT_TYPES[getCanvasFileExtension(path)] ?? 'application/octet-stream';
+
+const SEGMENT_PATTERN = /^[\w\-.@ ]+$/;
+
+export const normalizeCanvasPath = (input: string): string | undefined => {
+ const segments: string[] = [];
+
+ for (const segment of input.replaceAll('\\', '/').split('/')) {
+ if (!segment || segment === '.') continue;
+ if (segment === '..') {
+ if (segments.length === 0) return;
+ segments.pop();
+ continue;
+ }
+ if (!SEGMENT_PATTERN.test(segment)) return;
+ segments.push(segment);
+ }
+
+ return segments.length > 0 ? segments.join('/') : undefined;
+};
+
+export type CanvasHrefKind = 'anchor' | 'data' | 'local' | 'remote';
+
+export interface ResolvedCanvasHref {
+ kind: CanvasHrefKind;
+ path?: string;
+}
+
+const stripQueryAndHash = (href: string) => href.split(/[#?]/)[0];
+
+const decode = (value: string) => {
+ try {
+ return decodeURIComponent(value);
+ } catch {
+ return value;
+ }
+};
+
+export const resolveCanvasHref = (fromFile: string, rawHref: string): ResolvedCanvasHref => {
+ const href = rawHref.trim();
+ if (!href || href.startsWith('#')) return { kind: 'anchor' };
+ if (/^data:/i.test(href)) return { kind: 'data' };
+ if (/^[a-z][\d+.a-z-]*:/i.test(href) || href.startsWith('//')) return { kind: 'remote' };
+
+ const target = decode(stripQueryAndHash(href)).replaceAll('\\', '/');
+ if (!target) return { kind: 'anchor' };
+ if (target.startsWith('/')) return { kind: 'local' };
+
+ const baseDir = fromFile.includes('/') ? fromFile.slice(0, fromFile.lastIndexOf('/')) : '';
+
+ return { kind: 'local', path: normalizeCanvasPath(`${baseDir}/${target}`) };
+};
diff --git a/packages/canvas/src/runtime/bridge.test.ts b/packages/canvas/src/runtime/bridge.test.ts
new file mode 100644
index 00000000000..20218cf0bb1
--- /dev/null
+++ b/packages/canvas/src/runtime/bridge.test.ts
@@ -0,0 +1,31 @@
+// @vitest-environment happy-dom
+import { afterEach, expect, it, vi } from 'vitest';
+
+import { installCanvasBridge } from './bridge';
+
+afterEach(() => {
+ window.dispatchEvent(new PageTransitionEvent('pagehide'));
+ document.head.innerHTML = '';
+ vi.restoreAllMocks();
+ vi.unstubAllGlobals();
+});
+
+it('initializes standalone previews without secure-context UUID support', () => {
+ vi.stubGlobal('crypto', { randomUUID: undefined });
+ expect(() => installCanvasBridge('/runtime.js')).not.toThrow();
+ expect(document.querySelector('script')?.src).toContain('/runtime.js');
+});
+
+it('keeps a BFCache preview alive and disposes only on a final pagehide', () => {
+ const disposed = vi.fn();
+ window.addEventListener('lobe-canvas-dispose', disposed, { once: true });
+ installCanvasBridge('/runtime.js');
+ const cached = new PageTransitionEvent('pagehide');
+ Object.defineProperty(cached, 'persisted', { value: true });
+ window.dispatchEvent(cached);
+ expect(disposed).not.toHaveBeenCalled();
+ expect(document.querySelector('script')).not.toBeNull();
+ window.dispatchEvent(new PageTransitionEvent('pagehide', { persisted: false }));
+ expect(disposed).toHaveBeenCalledOnce();
+ expect(document.querySelector('script')).toBeNull();
+});
diff --git a/packages/canvas/src/runtime/bridge.ts b/packages/canvas/src/runtime/bridge.ts
new file mode 100644
index 00000000000..4aa45c332ed
--- /dev/null
+++ b/packages/canvas/src/runtime/bridge.ts
@@ -0,0 +1,189 @@
+import type { CanvasRuntimeBundle } from './types';
+
+// Serialized into preview HTML: keep this function self-contained.
+export function installCanvasBridge(fallbackRuntimeUrl: string) {
+ const host = window.parent;
+ const instanceId = `${Date.now()}-${Math.random()}`;
+ const urls = new Set<string>();
+ const nodes = new Set<HTMLElement>();
+ const imports: Record<string, string> = {};
+ const styles = new Set<string>();
+ const pending = new Map<
+ number,
+ { resolve: (value: unknown) => void; reject: (cause: Error) => void }
+ >();
+ let requestId = 0;
+ let importModule: ((url: string) => Promise<unknown>) | undefined;
+ let started = false;
+ let disposed = false;
+ let observer: ResizeObserver | undefined;
+ const post = (message: Record<string, unknown>) => {
+ if (host !== window) host.postMessage({ ...message, instanceId, source: 'lobe-canvas' }, '*');
+ };
+ const ready = () => post({ type: 'ready' });
+ const error = (message: string) => post({ message, type: 'error' });
+ const append = (node: HTMLElement) => {
+ nodes.add(node);
+ document.head.append(node);
+ };
+ const objectUrl = (code: string) => {
+ const url = URL.createObjectURL(new Blob([code], { type: 'text/javascript' }));
+ urls.add(url);
+ return url;
+ };
+ const dispose = () => {
+ if (disposed) return;
+ disposed = true;
+ window.dispatchEvent(new Event('lobe-canvas-dispose'));
+ observer?.disconnect();
+ for (const url of urls) URL.revokeObjectURL(url);
+ urls.clear();
+ for (const node of nodes) node.remove();
+ nodes.clear();
+ Reflect.deleteProperty(window, '__LOBE_CANVAS_LOAD_ADDON__');
+ for (const request of pending.values()) request.reject(new Error('Canvas runtime disposed'));
+ pending.clear();
+ styles.clear();
+ for (const id of Object.keys(imports)) delete imports[id];
+ importModule = undefined;
+ };
+ const install = (bundle: CanvasRuntimeBundle) => {
+ for (const css of bundle.styles) {
+ if (styles.has(css)) continue;
+ styles.add(css);
+ const style = document.createElement('style');
+ style.textContent = css;
+ append(style);
+ }
+ const added: Record<string, string> = {};
+ for (const module of bundle.modules) {
+ if (imports[`lobe-canvas/${module.id}`]) continue;
+ const edits = [
+ ...module.imports.map(({ start, end, target }) => ({
+ start,
+ end,
+ text: JSON.stringify(`lobe-canvas/${target}`),
+ })),
+ ...(module.meta ?? []).map(({ start, end }) => ({
+ start,
+ end,
+ text: JSON.stringify(module.url),
+ })),
+ ].sort((a, b) => b.start - a.start);
+ let code = module.code;
+ for (const edit of edits) code = code.slice(0, edit.start) + edit.text + code.slice(edit.end);
+ added[`lobe-canvas/${module.id}`] = objectUrl(code);
+ }
+ const map = document.createElement('script');
+ map.type = 'importmap';
+ map.textContent = JSON.stringify({ imports: added });
+ append(map);
+ Object.assign(imports, added);
+ return imports;
+ };
+ const start = (bundle: CanvasRuntimeBundle) => {
+ if (started || disposed) return;
+ started = true;
+ try {
+ install(bundle);
+ Reflect.set(
+ window,
+ '__LOBE_CANVAS_LOAD_ADDON__',
+ (name: string) =>
+ new Promise((resolve, reject) => {
+ const id = ++requestId;
+ pending.set(id, { resolve, reject });
+ post({ type: 'load-addon', name, requestId: id });
+ }),
+ );
+ const script = document.createElement('script');
+ script.type = 'module';
+ const entries = Object.fromEntries(
+ Object.entries(bundle.entries).map(([name, id]) => [name, imports[`lobe-canvas/${id}`]]),
+ );
+ script.src = objectUrl(`const entries = ${JSON.stringify(entries)};
+window.dispatchEvent(new CustomEvent("lobe-canvas-import", { detail: url => import(url) }));
+await import(entries.runtime);
+window.parent.postMessage({ source: 'lobe-canvas', type: 'runtime-loaded', instanceId: ${JSON.stringify(instanceId)} }, '*');`);
+ script.addEventListener(
+ 'error',
+ () => {
+ error('Canvas runtime failed to load');
+ dispose();
+ },
+ { once: true },
+ );
+ append(script);
+ } catch (cause) {
+ error(cause instanceof Error ? cause.message : String(cause));
+ dispose();
+ }
+ };
+ window.addEventListener(
+ 'lobe-canvas-import',
+ (event) => {
+ importModule = (event as CustomEvent).detail;
+ },
+ { once: true },
+ );
+ window.addEventListener('message', (event) => {
+ if (disposed) return;
+ if (event.source !== host || event.data?.source !== 'lobe-canvas-host') return;
+ const message = event.data;
+ if (message.type === 'request-runtime') ready();
+ if (message.type === 'theme') {
+ Reflect.set(window, '__LOBE_CANVAS_THEME__', message.theme);
+ window.dispatchEvent(new CustomEvent('lobe-canvas-theme', { detail: message.theme }));
+ }
+ if (message.instanceId !== instanceId) return;
+ if (message.type === 'runtime') start(message.bundle);
+ if (message.type === 'addon') {
+ const request = pending.get(message.requestId);
+ if (!request) return;
+ pending.delete(message.requestId);
+ if (message.error) request.reject(new Error(message.error));
+ else {
+ try {
+ install(message.bundle);
+ request.resolve(
+ importModule!(imports[`lobe-canvas/${message.bundle.entries[message.name]}`]),
+ );
+ } catch (cause) {
+ request.reject(cause instanceof Error ? cause : new Error(String(cause)));
+ }
+ }
+ }
+ if (message.type === 'dispose-runtime') dispose();
+ });
+ window.addEventListener('error', (event) =>
+ error(String(event.message || event.error || 'Script error')),
+ );
+ window.addEventListener('unhandledrejection', (event) =>
+ error(String(event.reason?.message ?? event.reason)),
+ );
+ window.addEventListener('lobe-canvas-component-error', (event) => {
+ const detail = (event as CustomEvent).detail;
+ post({ type: 'error', message: detail?.message, component: detail?.tag });
+ });
+ window.addEventListener('pagehide', (event) => {
+ if (!event.persisted) dispose();
+ });
+ window.addEventListener(
+ 'load',
+ () => {
+ ready();
+ const size = () => post({ type: 'height', height: document.documentElement.scrollHeight });
+ size();
+ observer = new ResizeObserver(size);
+ observer.observe(document.documentElement);
+ },
+ { once: true },
+ );
+ if (host === window) {
+ // A private preview opened directly reuses the publication runtime.
+ const script = document.createElement('script');
+ script.defer = true;
+ script.src = fallbackRuntimeUrl;
+ append(script);
+ }
+}
diff --git a/packages/canvas/src/runtime/index.ts b/packages/canvas/src/runtime/index.ts
new file mode 100644
index 00000000000..07d2858c55f
--- /dev/null
+++ b/packages/canvas/src/runtime/index.ts
@@ -0,0 +1,2 @@
+export { installCanvasBridge } from './bridge';
+export type * from './types';
diff --git a/packages/canvas/src/runtime/types.ts b/packages/canvas/src/runtime/types.ts
new file mode 100644
index 00000000000..adc07291dd0
--- /dev/null
+++ b/packages/canvas/src/runtime/types.ts
@@ -0,0 +1,21 @@
+export interface CanvasRuntimeModule {
+ code: string;
+ id: string;
+ imports: { end: number; start: number; target: string }[];
+ meta?: { end: number; start: number }[];
+ url: string;
+}
+
+export interface CanvasRuntimeManifest {
+ base: string;
+ entries: { highlight: string; mermaid: string; runtime: string };
+ entryStyles?: Partial<Record<keyof CanvasRuntimeManifest['entries'], string[]>>;
+ modules: Omit<CanvasRuntimeModule, 'code' | 'url'>[];
+ styles: string[];
+}
+
+export interface CanvasRuntimeBundle {
+ entries: CanvasRuntimeManifest['entries'];
+ modules: CanvasRuntimeModule[];
+ styles: string[];
+}
diff --git a/packages/canvas/src/schema/components.ts b/packages/canvas/src/schema/components.ts
new file mode 100644
index 00000000000..6caade90faa
--- /dev/null
+++ b/packages/canvas/src/schema/components.ts
@@ -0,0 +1,615 @@
+import type { CanvasAttributeSpec, CanvasComponentSpec } from './types';
+
+export const CANVAS_TAG_PREFIX = 'lobe-';
+
+export const CANVAS_PALETTE = [
+ 'red',
+ 'volcano',
+ 'orange',
+ 'gold',
+ 'yellow',
+ 'lime',
+ 'green',
+ 'cyan',
+ 'blue',
+ 'geekblue',
+ 'purple',
+ 'magenta',
+ 'gray',
+] as const;
+
+export const CANVAS_VALUE_FORMATS = ['number', 'compact', 'percent', 'currency'] as const;
+
+export const CANVAS_CODE_LANGUAGES = [
+ 'bash',
+ 'c',
+ 'cpp',
+ 'csharp',
+ 'css',
+ 'diff',
+ 'dockerfile',
+ 'go',
+ 'html',
+ 'java',
+ 'javascript',
+ 'json',
+ 'jsx',
+ 'kotlin',
+ 'python',
+ 'ruby',
+ 'rust',
+ 'sql',
+ 'swift',
+ 'toml',
+ 'tsx',
+ 'typescript',
+ 'yaml',
+] as const;
+
+const size: CanvasAttributeSpec = {
+ description: 'Control size.',
+ type: 'enum',
+ values: ['small', 'middle', 'large'],
+};
+
+const gap: CanvasAttributeSpec = { description: 'Gap between children in px.', type: 'number' };
+
+const optionValue: CanvasAttributeSpec = {
+ description: 'Value of the selected option; matches a child <lobe-option value>.',
+ type: 'string',
+};
+
+const disabled: CanvasAttributeSpec = { description: 'Disable the control.', type: 'boolean' };
+
+const chartAttributes: Record<string, CanvasAttributeSpec> = {
+ 'categories': {
+ description: 'JSON array of the data keys to plot as series.',
+ required: true,
+ type: 'json',
+ },
+ 'colors': {
+ description: `JSON array of palette names, one per category: ${CANVAS_PALETTE.join(', ')}.`,
+ type: 'json',
+ },
+ 'data': {
+ description: 'JSON array of row objects.',
+ required: true,
+ type: 'json',
+ },
+ 'height': { description: 'Chart height in px. Default 280.', type: 'number' },
+ 'index': { description: 'Row key used for the x axis.', required: true, type: 'string' },
+ 'show-legend': { description: 'Show the legend. Default true.', type: 'boolean' },
+ 'unit': { description: 'Unit appended to formatted values, e.g. "ms".', type: 'string' },
+ 'value-format': {
+ description: 'How values are formatted.',
+ type: 'enum',
+ values: CANVAS_VALUE_FORMATS,
+ },
+};
+
+const chart = (
+ tag: string,
+ description: string,
+ extra: Record<string, CanvasAttributeSpec> = {},
+): CanvasComponentSpec => ({
+ attributes: { ...chartAttributes, ...extra },
+ category: 'chart',
+ children: 'none',
+ description,
+ example: `<${tag} index="month" categories='["cost"]' data='[{"month":"Sep","cost":1200},{"month":"Oct","cost":1840}]'></${tag}>`,
+ tag,
+});
+
+export const CANVAS_COMPONENTS: readonly CanvasComponentSpec[] = [
+ {
+ attributes: {
+ align: {
+ description: 'Cross-axis alignment.',
+ type: 'enum',
+ values: ['start', 'center', 'end', 'stretch', 'baseline'],
+ },
+ gap,
+ horizontal: { description: 'Lay children out in a row.', type: 'boolean' },
+ justify: {
+ description: 'Main-axis distribution.',
+ type: 'enum',
+ values: ['start', 'center', 'end', 'space-between', 'space-around'],
+ },
+ wrap: { description: 'Wrap children onto new lines.', type: 'boolean' },
+ },
+ category: 'layout',
+ children: 'content',
+ description: 'Flex container. Vertical by default.',
+ example: '<lobe-flex horizontal gap="12" align="center">…</lobe-flex>',
+ tag: 'lobe-flex',
+ },
+ {
+ attributes: {
+ 'gap': gap,
+ 'max-item-width': {
+ description: 'Maximum item width in px before wrapping to more columns.',
+ type: 'number',
+ },
+ 'rows': { description: 'Number of columns.', type: 'number' },
+ },
+ category: 'layout',
+ children: 'content',
+ description: 'Responsive grid. Use for stat rows and card grids.',
+ example: '<lobe-grid rows="3" gap="12">…</lobe-grid>',
+ tag: 'lobe-grid',
+ },
+ {
+ attributes: {
+ padding: { description: 'Inner padding in px. Default 16.', type: 'number' },
+ title: { description: 'Card title.', type: 'string' },
+ variant: {
+ description: 'Surface style.',
+ type: 'enum',
+ values: ['outlined', 'filled', 'borderless'],
+ },
+ },
+ category: 'layout',
+ children: 'content',
+ description: 'Card surface that groups related content.',
+ example: '<lobe-card title="By model">…</lobe-card>',
+ tag: 'lobe-card',
+ },
+ {
+ attributes: {
+ dashed: { description: 'Dashed line.', type: 'boolean' },
+ },
+ category: 'layout',
+ children: 'none',
+ description: 'Horizontal divider between sections.',
+ example: '<lobe-divider></lobe-divider>',
+ tag: 'lobe-divider',
+ },
+ {
+ attributes: {
+ value: { description: 'Key of the active tab.', type: 'string' },
+ },
+ category: 'layout',
+ children: 'options',
+ description: 'Tabs. Each <lobe-tab> child is one panel.',
+ example:
+ '<lobe-tabs value="model"><lobe-tab value="model" label="By model">…</lobe-tab><lobe-tab value="team" label="By team">…</lobe-tab></lobe-tabs>',
+ tag: 'lobe-tabs',
+ },
+ {
+ attributes: {
+ label: { description: 'Tab label.', required: true, type: 'string' },
+ value: { description: 'Tab key.', required: true, type: 'string' },
+ },
+ category: 'layout',
+ children: 'content',
+ description: 'One tab panel inside <lobe-tabs>.',
+ example: '<lobe-tab value="model" label="By model">…</lobe-tab>',
+ parents: ['lobe-tabs'],
+ tag: 'lobe-tab',
+ },
+ {
+ attributes: {},
+ category: 'layout',
+ children: 'options',
+ description: 'Collapsible sections. Each <lobe-accordion-item> child is one section.',
+ example:
+ '<lobe-accordion><lobe-accordion-item title="Method">…</lobe-accordion-item></lobe-accordion>',
+ tag: 'lobe-accordion',
+ },
+ {
+ attributes: {
+ open: { description: 'Expanded by default.', type: 'boolean' },
+ title: { description: 'Section title.', required: true, type: 'string' },
+ },
+ category: 'layout',
+ children: 'content',
+ description: 'One collapsible section inside <lobe-accordion>.',
+ example: '<lobe-accordion-item title="Method" open>…</lobe-accordion-item>',
+ parents: ['lobe-accordion'],
+ tag: 'lobe-accordion-item',
+ },
+ {
+ attributes: {
+ title: { description: 'Bold first line.', type: 'string' },
+ type: {
+ description: 'Meaning of the message.',
+ type: 'enum',
+ values: ['info', 'success', 'warning', 'error'],
+ },
+ },
+ category: 'text',
+ children: 'content',
+ description: 'Callout for the conclusion or an important caveat.',
+ example: '<lobe-alert type="info" title="Cost is up 23%">Almost all from Opus.</lobe-alert>',
+ tag: 'lobe-alert',
+ },
+ {
+ attributes: {
+ color: { description: 'Palette color.', type: 'enum', values: CANVAS_PALETTE },
+ },
+ category: 'text',
+ children: 'content',
+ description: 'Short label or status tag.',
+ example: '<lobe-tag color="green">Stable</lobe-tag>',
+ tag: 'lobe-tag',
+ },
+ {
+ attributes: {
+ count: { description: 'Number shown in the badge.', type: 'number' },
+ status: {
+ description: 'Status dot.',
+ type: 'enum',
+ values: ['success', 'processing', 'default', 'error', 'warning'],
+ },
+ text: { description: 'Text next to the status dot.', type: 'string' },
+ },
+ category: 'text',
+ children: 'content',
+ description: 'Status dot or count badge.',
+ example: '<lobe-badge status="success" text="Healthy"></lobe-badge>',
+ tag: 'lobe-badge',
+ },
+ {
+ attributes: {
+ language: {
+ description: `Code language or a common alias (ts, js, py, sh). Highlighted: ${CANVAS_CODE_LANGUAGES.join(', ')}; any other shows as plain text.`,
+ type: 'string',
+ },
+ },
+ category: 'text',
+ children: 'text',
+ description:
+ 'Code block with syntax highlighting and a copy button. The code is the text content: write < as &lt; and & as &amp;.',
+ example:
+ '<lobe-code language="ts">const ids: Array&lt;string&gt; = rows.map((row) =&gt; row.id);</lobe-code>',
+ tag: 'lobe-code',
+ },
+ {
+ attributes: {},
+ category: 'chart',
+ children: 'text',
+ description:
+ 'Diagram drawn from Mermaid text: flowchart, sequenceDiagram, classDiagram, stateDiagram-v2, erDiagram, gantt, timeline, mindmap and the other Mermaid types. Use it for every flowchart, sequence or architecture diagram instead of drawing SVG by hand. The diagram is the text content: write < as &lt; and & as &amp;. Invalid Mermaid is rejected with the parser error.',
+ example:
+ '<lobe-mermaid>\nflowchart TD\n A[Request] --&gt; B{Token valid?}\n B -- yes --&gt; C[Response]\n B -- no --&gt; D[Refresh]\n</lobe-mermaid>',
+ tag: 'lobe-mermaid',
+ },
+ {
+ attributes: {
+ 'precision': { description: 'Decimal places.', type: 'number' },
+ 'prefix': { description: 'Text before the value, e.g. "$".', type: 'string' },
+ 'suffix': { description: 'Text after the value, e.g. "%".', type: 'string' },
+ 'title': { description: 'Label above the value.', required: true, type: 'string' },
+ 'trend': {
+ description: 'Direction of change, shown next to the value.',
+ type: 'enum',
+ values: ['up', 'down', 'flat'],
+ },
+ 'trend-text': { description: 'Change text, e.g. "+23% MoM".', type: 'string' },
+ 'value': { description: 'The number.', required: true, type: 'number' },
+ },
+ category: 'data',
+ children: 'none',
+ description: 'Key number with label and optional trend.',
+ example:
+ '<lobe-stat title="Total cost" value="18420" prefix="$" trend="up" trend-text="+23%"></lobe-stat>',
+ tag: 'lobe-stat',
+ },
+ {
+ attributes: {
+ columns: {
+ description:
+ 'JSON array of {"title","key","align"?:"left"|"right","format"?:"number"|"compact"|"percent"|"currency"}.',
+ required: true,
+ type: 'json',
+ },
+ data: { description: 'JSON array of row objects.', required: true, type: 'json' },
+ striped: { description: 'Zebra rows.', type: 'boolean' },
+ },
+ category: 'data',
+ children: 'none',
+ description: 'Data table.',
+ example:
+ '<lobe-table columns=\'[{"title":"Model","key":"model"},{"title":"Cost","key":"cost","align":"right","format":"currency"}]\' data=\'[{"model":"Opus","cost":11236}]\'></lobe-table>',
+ tag: 'lobe-table',
+ },
+ {
+ attributes: {
+ percent: { description: 'Progress 0–100.', required: true, type: 'number' },
+ status: {
+ description: 'Status color.',
+ type: 'enum',
+ values: ['normal', 'success', 'exception', 'active'],
+ },
+ type: { description: 'Shape.', type: 'enum', values: ['line', 'circle'] },
+ },
+ category: 'data',
+ children: 'none',
+ description: 'Progress bar or ring.',
+ example: '<lobe-progress percent="61"></lobe-progress>',
+ tag: 'lobe-progress',
+ },
+ {
+ attributes: {
+ items: {
+ description:
+ 'JSON array of {"title","description"?,"status"?:"wait"|"process"|"finish"|"error"}.',
+ required: true,
+ type: 'json',
+ },
+ vertical: { description: 'Vertical timeline.', type: 'boolean' },
+ },
+ category: 'data',
+ children: 'none',
+ description: 'Ordered steps or a timeline.',
+ example: '<lobe-steps vertical items=\'[{"title":"Collect","status":"finish"}]\'></lobe-steps>',
+ tag: 'lobe-steps',
+ },
+ {
+ attributes: {
+ columns: { description: 'Items per row. Default 2.', type: 'number' },
+ items: {
+ description: 'JSON array of {"label","value"}.',
+ required: true,
+ type: 'json',
+ },
+ },
+ category: 'data',
+ children: 'none',
+ description: 'Label/value pairs, e.g. metadata or a comparison.',
+ example:
+ '<lobe-descriptions items=\'[{"label":"Period","value":"Oct 2026"}]\'></lobe-descriptions>',
+ tag: 'lobe-descriptions',
+ },
+ {
+ attributes: {
+ block: { description: 'Full width.', type: 'boolean' },
+ disabled,
+ size,
+ type: {
+ description: 'Visual weight.',
+ type: 'enum',
+ values: ['primary', 'default', 'text', 'link'],
+ },
+ value: { description: 'Value sent with the change event when clicked.', type: 'string' },
+ },
+ category: 'control',
+ children: 'content',
+ description: 'Button. Clicking fires lobe-change with its value.',
+ example: '<lobe-button type="primary" value="refresh">Recalculate</lobe-button>',
+ tag: 'lobe-button',
+ },
+ {
+ attributes: {
+ disabled,
+ placeholder: { description: 'Placeholder text.', type: 'string' },
+ size,
+ value: optionValue,
+ },
+ category: 'control',
+ children: 'options',
+ description: 'Dropdown select with <lobe-option> children.',
+ example:
+ '<lobe-select id="range" value="30d"><lobe-option value="7d">7 days</lobe-option><lobe-option value="30d">30 days</lobe-option></lobe-select>',
+ tag: 'lobe-select',
+ },
+ {
+ attributes: { disabled, size, value: optionValue },
+ category: 'control',
+ children: 'options',
+ description: 'Segmented switch between a few views, with <lobe-option> children.',
+ example:
+ '<lobe-segmented id="view" value="chart"><lobe-option value="chart">Chart</lobe-option><lobe-option value="table">Table</lobe-option></lobe-segmented>',
+ tag: 'lobe-segmented',
+ },
+ {
+ attributes: { disabled, value: optionValue },
+ category: 'control',
+ children: 'options',
+ description: 'Radio group with <lobe-option> children.',
+ example:
+ '<lobe-radio-group value="a"><lobe-option value="a">A</lobe-option><lobe-option value="b">B</lobe-option></lobe-radio-group>',
+ tag: 'lobe-radio-group',
+ },
+ {
+ attributes: {
+ disabled,
+ value: { description: 'Option value.', required: true, type: 'string' },
+ },
+ category: 'control',
+ children: 'content',
+ description: 'One option inside a select, segmented or radio group. Text content is the label.',
+ example: '<lobe-option value="7d">7 days</lobe-option>',
+ parents: ['lobe-select', 'lobe-segmented', 'lobe-radio-group'],
+ tag: 'lobe-option',
+ },
+ {
+ attributes: {
+ checked: { description: 'On by default.', type: 'boolean' },
+ disabled,
+ label: { description: 'Label next to the switch.', type: 'string' },
+ },
+ category: 'control',
+ children: 'none',
+ description: 'On/off switch.',
+ example: '<lobe-switch id="cached" label="Include cached" checked></lobe-switch>',
+ tag: 'lobe-switch',
+ },
+ {
+ attributes: {
+ checked: { description: 'Checked by default.', type: 'boolean' },
+ disabled,
+ },
+ category: 'control',
+ children: 'content',
+ description: 'Checkbox. Text content is the label.',
+ example: '<lobe-checkbox id="opus" checked>Opus</lobe-checkbox>',
+ tag: 'lobe-checkbox',
+ },
+ {
+ attributes: {
+ disabled,
+ placeholder: { description: 'Placeholder text.', type: 'string' },
+ size,
+ value: { description: 'Initial value.', type: 'string' },
+ },
+ category: 'control',
+ children: 'none',
+ description: 'Single-line text input.',
+ example: '<lobe-input id="q" placeholder="Filter models"></lobe-input>',
+ tag: 'lobe-input',
+ },
+ {
+ attributes: {
+ disabled,
+ max: { description: 'Maximum. Default 100.', type: 'number' },
+ min: { description: 'Minimum. Default 0.', type: 'number' },
+ step: { description: 'Step. Default 1.', type: 'number' },
+ value: { description: 'Initial value.', type: 'number' },
+ },
+ category: 'control',
+ children: 'none',
+ description: 'Slider for a numeric parameter.',
+ example: '<lobe-slider id="share" min="0" max="100" value="40"></lobe-slider>',
+ tag: 'lobe-slider',
+ },
+ chart('lobe-area-chart', 'Area chart for trends over time.', {
+ stack: { description: 'Stack series.', type: 'boolean' },
+ }),
+ chart('lobe-bar-chart', 'Bar chart for comparing categories.', {
+ layout: { description: 'Bar direction.', type: 'enum', values: ['horizontal', 'vertical'] },
+ stack: { description: 'Stack series.', type: 'boolean' },
+ }),
+ chart('lobe-line-chart', 'Line chart for trends.'),
+ {
+ attributes: {
+ 'category': {
+ description: 'Row key that groups points into series.',
+ required: true,
+ type: 'string',
+ },
+ 'colors': chartAttributes.colors,
+ 'data': chartAttributes.data,
+ 'height': chartAttributes.height,
+ 'show-legend': chartAttributes['show-legend'],
+ 'size': { description: 'Row key that scales each point.', type: 'string' },
+ 'x': { description: 'Row key for the x value.', required: true, type: 'string' },
+ 'y': { description: 'Row key for the y value.', required: true, type: 'string' },
+ },
+ category: 'chart',
+ children: 'none',
+ description: 'Scatter chart for correlation between two measures.',
+ example:
+ '<lobe-scatter-chart x="latency" y="cost" category="model" data=\'[{"model":"Opus","latency":2.1,"cost":11}]\'></lobe-scatter-chart>',
+ tag: 'lobe-scatter-chart',
+ },
+ chart('lobe-radar-chart', 'Radar chart for comparing a few items across several dimensions.'),
+ {
+ attributes: {
+ 'category': { description: 'Row key holding the value.', required: true, type: 'string' },
+ 'colors': chartAttributes.colors,
+ 'data': chartAttributes.data,
+ 'index': { description: 'Row key holding the slice name.', required: true, type: 'string' },
+ 'unit': chartAttributes.unit,
+ 'value-format': chartAttributes['value-format'],
+ 'variant': { description: 'Shape.', type: 'enum', values: ['donut', 'pie'] },
+ },
+ category: 'chart',
+ children: 'none',
+ description: 'Donut or pie chart for shares of a whole.',
+ example:
+ '<lobe-donut-chart index="model" category="cost" data=\'[{"model":"Opus","cost":61},{"model":"GPT","cost":22}]\'></lobe-donut-chart>',
+ tag: 'lobe-donut-chart',
+ },
+ {
+ attributes: {
+ 'data': {
+ description: 'JSON array of {"name","value"}.',
+ required: true,
+ type: 'json',
+ },
+ 'unit': chartAttributes.unit,
+ 'value-format': chartAttributes['value-format'],
+ },
+ category: 'chart',
+ children: 'none',
+ description: 'Ranked horizontal bars, best for top-N lists.',
+ example: '<lobe-bar-list data=\'[{"name":"Code review","value":9870}]\'></lobe-bar-list>',
+ tag: 'lobe-bar-list',
+ },
+ {
+ attributes: {
+ categories: chartAttributes.categories,
+ colors: chartAttributes.colors,
+ data: chartAttributes.data,
+ index: chartAttributes.index,
+ kind: { description: 'Shape.', type: 'enum', values: ['area', 'line', 'bar'] },
+ },
+ category: 'chart',
+ children: 'none',
+ description: 'Tiny inline trend chart without axes.',
+ example:
+ '<lobe-spark-chart kind="area" index="d" categories=\'["v"]\' data=\'[{"d":1,"v":3},{"d":2,"v":5}]\'></lobe-spark-chart>',
+ tag: 'lobe-spark-chart',
+ },
+ {
+ attributes: {
+ data: {
+ description: 'JSON array of {"color": palette name, "tooltip"?}.',
+ required: true,
+ type: 'json',
+ },
+ },
+ category: 'chart',
+ children: 'none',
+ description: 'Row of status blocks, e.g. daily uptime.',
+ example: '<lobe-tracker data=\'[{"color":"green","tooltip":"Oct 1"}]\'></lobe-tracker>',
+ tag: 'lobe-tracker',
+ },
+ {
+ attributes: {
+ data: {
+ description: 'JSON array of {"date":"YYYY-MM-DD","count"}.',
+ required: true,
+ type: 'json',
+ },
+ },
+ category: 'chart',
+ children: 'none',
+ description: 'Calendar heatmap of daily activity.',
+ example: '<lobe-heatmap data=\'[{"date":"2026-10-01","count":4}]\'></lobe-heatmap>',
+ tag: 'lobe-heatmap',
+ },
+ {
+ attributes: {
+ data: {
+ description: 'JSON array of {"name","value"} in funnel order.',
+ required: true,
+ type: 'json',
+ },
+ },
+ category: 'chart',
+ children: 'none',
+ description: 'Funnel chart for conversion between stages.',
+ example:
+ '<lobe-funnel-chart data=\'[{"name":"Visit","value":1000},{"name":"Sign up","value":120}]\'></lobe-funnel-chart>',
+ tag: 'lobe-funnel-chart',
+ },
+];
+
+export const CANVAS_COMPONENT_MAP: ReadonlyMap<string, CanvasComponentSpec> = new Map(
+ CANVAS_COMPONENTS.map((spec) => [spec.tag, spec]),
+);
+
+export const CANVAS_GLOBAL_ATTRIBUTES = new Set([
+ 'class',
+ 'hidden',
+ 'id',
+ 'role',
+ 'slot',
+ 'style',
+ 'title',
+]);
+
+export const isCanvasGlobalAttribute = (name: string): boolean =>
+ CANVAS_GLOBAL_ATTRIBUTES.has(name) || name.startsWith('data-') || name.startsWith('aria-');
diff --git a/packages/canvas/src/schema/reference.test.ts b/packages/canvas/src/schema/reference.test.ts
new file mode 100644
index 00000000000..cc0b299e8ca
--- /dev/null
+++ b/packages/canvas/src/schema/reference.test.ts
@@ -0,0 +1,24 @@
+import { describe, expect, it } from 'vitest';
+
+import { CANVAS_COMPONENTS } from './components';
+import { buildCanvasComponentReference } from './reference';
+
+describe('buildCanvasComponentReference', () => {
+ const reference = buildCanvasComponentReference();
+
+ it('documents every component with its example', () => {
+ for (const spec of CANVAS_COMPONENTS) {
+ expect(reference).toContain(`### <${spec.tag}>`);
+ expect(reference).toContain(spec.example);
+ }
+ });
+
+ it('marks required attributes and lists enum values', () => {
+ expect(reference).toContain('- `value` (number, required)');
+ expect(reference).toContain('- `type` (one of: info | success | warning | error)');
+ });
+
+ it('explains where option-like children may appear', () => {
+ expect(reference).toContain('Only inside <lobe-select>, <lobe-segmented>, <lobe-radio-group>.');
+ });
+});
diff --git a/packages/canvas/src/schema/reference.ts b/packages/canvas/src/schema/reference.ts
new file mode 100644
index 00000000000..3d004fed378
--- /dev/null
+++ b/packages/canvas/src/schema/reference.ts
@@ -0,0 +1,41 @@
+import { CANVAS_COMPONENTS } from './components';
+import type { CanvasAttributeSpec, CanvasComponentCategory, CanvasComponentSpec } from './types';
+
+const CATEGORY_TITLES: Record<CanvasComponentCategory, string> = {
+ chart: 'Charts',
+ control: 'Controls',
+ data: 'Data',
+ layout: 'Layout',
+ text: 'Text',
+};
+
+const CATEGORY_ORDER: CanvasComponentCategory[] = ['layout', 'text', 'data', 'control', 'chart'];
+
+const describeType = (spec: CanvasAttributeSpec) =>
+ spec.type === 'enum' ? `one of: ${spec.values?.join(' | ')}` : spec.type;
+
+const renderComponent = (spec: CanvasComponentSpec) => {
+ const lines = [`### <${spec.tag}>`, '', spec.description];
+ if (spec.parents) lines.push(`Only inside ${spec.parents.map((p) => `<${p}>`).join(', ')}.`);
+
+ const attributes = Object.entries(spec.attributes);
+ if (attributes.length > 0) {
+ lines.push('');
+ for (const [name, attr] of attributes) {
+ lines.push(
+ `- \`${name}\` (${describeType(attr)}${attr.required ? ', required' : ''}): ${attr.description}`,
+ );
+ }
+ }
+
+ lines.push('', '```html', spec.example, '```');
+ return lines.join('\n');
+};
+
+export const buildCanvasComponentReference = () =>
+ CATEGORY_ORDER.map((category) =>
+ [
+ `## ${CATEGORY_TITLES[category]}`,
+ ...CANVAS_COMPONENTS.filter((spec) => spec.category === category).map(renderComponent),
+ ].join('\n\n'),
+ ).join('\n\n');
diff --git a/packages/canvas/src/schema/types.ts b/packages/canvas/src/schema/types.ts
new file mode 100644
index 00000000000..28027429e29
--- /dev/null
+++ b/packages/canvas/src/schema/types.ts
@@ -0,0 +1,22 @@
+export type CanvasAttributeType = 'boolean' | 'enum' | 'json' | 'number' | 'string';
+
+export interface CanvasAttributeSpec {
+ description: string;
+ required?: boolean;
+ type: CanvasAttributeType;
+ values?: readonly string[];
+}
+
+export type CanvasComponentCategory = 'chart' | 'control' | 'data' | 'layout' | 'text';
+
+export type CanvasChildren = 'content' | 'none' | 'options' | 'text';
+
+export interface CanvasComponentSpec {
+ attributes: Record<string, CanvasAttributeSpec>;
+ category: CanvasComponentCategory;
+ children: CanvasChildren;
+ description: string;
+ example: string;
+ parents?: readonly string[];
+ tag: string;
+}
diff --git a/packages/canvas/src/validate/html.ts b/packages/canvas/src/validate/html.ts
new file mode 100644
index 00000000000..fa7cfb90442
--- /dev/null
+++ b/packages/canvas/src/validate/html.ts
@@ -0,0 +1,368 @@
+import { Parser } from 'htmlparser2';
+
+import { resolveCanvasHref } from '../project/path';
+import {
+ CANVAS_COMPONENT_MAP,
+ CANVAS_COMPONENTS,
+ CANVAS_PALETTE,
+ CANVAS_TAG_PREFIX,
+ isCanvasGlobalAttribute,
+} from '../schema/components';
+import type { CanvasAttributeSpec, CanvasComponentSpec } from '../schema/types';
+import { checkScriptText, collectCssRefs, findHardCodedColor, lineAt } from './text';
+import type { CanvasIssue, CanvasValidationOptions } from './types';
+
+export interface CanvasProjectIndex {
+ has: (path: string) => boolean;
+ readText: (path: string) => string | undefined;
+}
+
+interface ComponentFrame {
+ attrs: Record<string, string>;
+ line: number;
+ provided: Set<string>;
+ spec: CanvasComponentSpec;
+ text: string;
+}
+
+interface ElementFrame {
+ component?: ComponentFrame;
+ tag: string;
+}
+
+const RESOURCE_ATTRIBUTES: Record<string, string[]> = {
+ a: ['href'],
+ audio: ['src'],
+ embed: ['src'],
+ iframe: ['src'],
+ img: ['src'],
+ link: ['href'],
+ script: ['src'],
+ source: ['src'],
+ video: ['src', 'poster'],
+};
+
+const levenshtein = (a: string, b: string) => {
+ const row = Array.from({ length: b.length + 1 }, (_, i) => i);
+ for (let i = 1; i <= a.length; i += 1) {
+ let previous = row[0];
+ row[0] = i;
+ for (let j = 1; j <= b.length; j += 1) {
+ const current = row[j];
+ row[j] = a[i - 1] === b[j - 1] ? previous : Math.min(previous, row[j], row[j - 1]) + 1;
+ previous = current;
+ }
+ }
+ return row[b.length];
+};
+
+const suggestTag = (tag: string) => {
+ let best: string | undefined;
+ let bestDistance = Infinity;
+ for (const spec of CANVAS_COMPONENTS) {
+ const distance = levenshtein(tag, spec.tag);
+ if (distance < bestDistance) {
+ best = spec.tag;
+ bestDistance = distance;
+ }
+ }
+ return bestDistance <= 3 ? best : undefined;
+};
+
+const isJsonScript = (attrs: Record<string, string>) =>
+ attrs.type?.trim().toLowerCase() === 'application/json';
+
+const isExecutableScript = (attrs: Record<string, string>) => {
+ const type = attrs.type?.trim().toLowerCase();
+ return !type || type === 'module' || type.includes('javascript');
+};
+
+const checkValue = (name: string, spec: CanvasAttributeSpec, value: string): string | undefined => {
+ switch (spec.type) {
+ case 'number': {
+ return value.trim() !== '' && Number.isFinite(Number(value)) ? undefined : 'expects a number';
+ }
+ case 'boolean': {
+ return ['', 'true', 'false', name].includes(value)
+ ? undefined
+ : 'is a boolean: write it bare or "true"/"false"';
+ }
+ case 'enum': {
+ return spec.values?.includes(value)
+ ? undefined
+ : `must be one of: ${spec.values?.join(', ')}`;
+ }
+ case 'json': {
+ return checkJson(name, value);
+ }
+ default: {
+ return undefined;
+ }
+ }
+};
+
+const checkJson = (name: string, text: string): string | undefined => {
+ let parsed: unknown;
+ try {
+ parsed = JSON.parse(text);
+ } catch (error) {
+ return `is not valid JSON (${(error as Error).message})`;
+ }
+ if (name === 'colors') {
+ const palette = new Set<string>(CANVAS_PALETTE);
+ if (!Array.isArray(parsed) || parsed.some((color) => !palette.has(color))) {
+ return `must be a JSON array of palette names: ${CANVAS_PALETTE.join(', ')}`;
+ }
+ }
+};
+
+export const validateHtmlFile = (
+ file: string,
+ html: string,
+ project: CanvasProjectIndex,
+ options: CanvasValidationOptions = {},
+): CanvasIssue[] => {
+ const issues: CanvasIssue[] = [];
+ const stack: ElementFrame[] = [];
+ let pendingScript: { attrs: Record<string, string>; line: number; text: string } | undefined;
+ let pendingStyle: { line: number; text: string } | undefined;
+
+ const report = (line: number, rule: CanvasIssue['rule'], message: string) =>
+ issues.push({ file, line, message, rule });
+
+ const checkRef = (line: number, tag: string, attr: string, value: string) => {
+ const resolved = resolveCanvasHref(file, value);
+ if (resolved.kind === 'remote') {
+ if (tag === 'a') return;
+ report(
+ line,
+ 'remote-resource',
+ `<${tag} ${attr}="${value}"> loads a remote resource. Copy it into the project and reference it by relative path.`,
+ );
+ return;
+ }
+ if (resolved.kind !== 'local') return;
+ if (!resolved.path || !project.has(resolved.path)) {
+ report(
+ line,
+ 'broken-reference',
+ `<${tag} ${attr}="${value}"> points at a file that is not in the project.`,
+ );
+ }
+ };
+
+ const checkCss = (text: string, lineOffset: number) => {
+ for (const ref of collectCssRefs(text)) {
+ const resolved = resolveCanvasHref(file, ref.href);
+ const line = lineOffset + lineAt(text, ref.index) - 1;
+ if (resolved.kind === 'remote') {
+ report(
+ line,
+ 'remote-resource',
+ `CSS reference "${ref.href}" is remote. Copy it into the project.`,
+ );
+ } else if (resolved.kind === 'local' && (!resolved.path || !project.has(resolved.path))) {
+ report(
+ line,
+ 'broken-reference',
+ `CSS reference "${ref.href}" points at a file that is not in the project.`,
+ );
+ }
+ }
+ };
+
+ const openComponent = (
+ tag: string,
+ attrs: Record<string, string>,
+ line: number,
+ ): ComponentFrame | undefined => {
+ const spec = CANVAS_COMPONENT_MAP.get(tag);
+ if (!spec) {
+ const suggestion = suggestTag(tag);
+ report(
+ line,
+ 'unknown-component',
+ `<${tag}> is not a Canvas component.${suggestion ? ` Did you mean <${suggestion}>?` : ''} See the component reference in the Canvas skill.`,
+ );
+ return;
+ }
+
+ const parent = stack.at(-1)?.tag;
+ if (spec.parents && (!parent || !spec.parents.includes(parent))) {
+ report(
+ line,
+ 'misplaced-component',
+ `<${tag}> must be a direct child of ${spec.parents.map((p) => `<${p}>`).join(' or ')}.`,
+ );
+ }
+
+ const frame: ComponentFrame = { attrs, line, provided: new Set(), spec, text: '' };
+
+ for (const [name, value] of Object.entries(attrs)) {
+ const attrSpec = spec.attributes[name];
+ if (attrSpec) {
+ frame.provided.add(name);
+ const problem = checkValue(name, attrSpec, value);
+ if (problem) report(line, 'invalid-attribute', `<${tag} ${name}> ${problem}.`);
+ continue;
+ }
+
+ const sourceOf = name.endsWith('-src') ? name.slice(0, -'-src'.length) : undefined;
+ if (sourceOf && spec.attributes[sourceOf]?.type === 'json') {
+ frame.provided.add(sourceOf);
+ const resolved = resolveCanvasHref(file, value);
+ if (resolved.kind !== 'local' || !resolved.path || !project.has(resolved.path)) {
+ report(
+ line,
+ 'broken-reference',
+ `<${tag} ${name}="${value}"> must point at a .json file in the project.`,
+ );
+ continue;
+ }
+ const text = project.readText(resolved.path);
+ const problem = text === undefined ? 'is not a text file' : checkJson(sourceOf, text);
+ if (problem)
+ report(line, 'invalid-attribute', `<${tag} ${name}>: ${resolved.path} ${problem}.`);
+ continue;
+ }
+
+ if (isCanvasGlobalAttribute(name)) {
+ if (name === 'style') {
+ const color = findHardCodedColor(value);
+ if (color)
+ report(
+ line,
+ 'hard-coded-color',
+ `<${tag} style="${color}"> hard-codes a color. Components follow the app theme; use a variant/type/color attribute or a var(--lobe-*) token.`,
+ );
+ }
+ continue;
+ }
+
+ report(
+ line,
+ 'unknown-attribute',
+ `<${tag}> has no attribute "${name}". Allowed: ${Object.keys(spec.attributes).join(', ') || 'none'}.`,
+ );
+ }
+
+ return frame;
+ };
+
+ const closeComponent = (frame: ComponentFrame) => {
+ for (const [name, attrSpec] of Object.entries(frame.spec.attributes)) {
+ if (attrSpec.required && !frame.provided.has(name)) {
+ report(
+ frame.line,
+ 'missing-attribute',
+ `<${frame.spec.tag}> requires "${name}" (${attrSpec.description})`,
+ );
+ }
+ }
+ if (frame.spec.tag === 'lobe-mermaid' && options.checkMermaid) {
+ const problem = options.checkMermaid(frame.text);
+ if (problem) {
+ const line = problem.line ? frame.line + problem.line - 1 : frame.line;
+ const message = problem.line
+ ? problem.message.replace(`line ${problem.line}`, `line ${line}`)
+ : problem.message;
+ report(line, 'invalid-diagram', `<lobe-mermaid> is not valid Mermaid. ${message}`);
+ }
+ }
+ };
+
+ const parser: Parser = new Parser(
+ {
+ onclosetag(tag) {
+ if (tag === 'script' && pendingScript) {
+ const { attrs, line, text } = pendingScript;
+ pendingScript = undefined;
+ if (isJsonScript(attrs)) {
+ const prop = attrs['data-prop'];
+ const owner = [...stack].reverse().find((frame) => frame.tag !== 'script')?.component;
+ if (prop && owner) {
+ const attrSpec = owner.spec.attributes[prop];
+ if (attrSpec?.type === 'json') {
+ owner.provided.add(prop);
+ const problem = checkJson(prop, text);
+ if (problem)
+ report(
+ line,
+ 'invalid-attribute',
+ `<${owner.spec.tag}> data-prop="${prop}" script ${problem}.`,
+ );
+ } else {
+ report(
+ line,
+ 'unknown-attribute',
+ `<${owner.spec.tag}> has no JSON attribute "${prop}".`,
+ );
+ }
+ }
+ } else if (isExecutableScript(attrs) && !attrs.src) {
+ issues.push(...checkScriptText(file, text, line));
+ }
+ }
+ if (tag === 'style' && pendingStyle) {
+ checkCss(pendingStyle.text, pendingStyle.line);
+ pendingStyle = undefined;
+ }
+
+ const index = stack.findLastIndex((frame) => frame.tag === tag);
+ if (index === -1) return;
+ for (const frame of stack.splice(index).reverse())
+ if (frame.component) closeComponent(frame.component);
+ },
+ onopentag(tag, attrs) {
+ const line = lineAt(html, parser.startIndex);
+
+ if (
+ html.slice(parser.startIndex, parser.endIndex + 1).endsWith('/>') &&
+ tag.startsWith(CANVAS_TAG_PREFIX)
+ ) {
+ report(
+ line,
+ 'self-closing-component',
+ `<${tag} /> is not closed in HTML. Write <${tag}></${tag}>.`,
+ );
+ }
+
+ for (const attr of RESOURCE_ATTRIBUTES[tag] ?? []) {
+ if (attrs[attr] !== undefined) checkRef(line, tag, attr, attrs[attr]);
+ }
+ if (attrs.style) checkCss(attrs.style, line);
+
+ const textOwner = stack.at(-1)?.component;
+ if (textOwner?.spec.children === 'text') {
+ report(
+ line,
+ 'markup-in-text',
+ `<${tag}> inside <${textOwner.spec.tag}> is parsed as an element and its text is lost. <${textOwner.spec.tag}> holds plain text: write < as &lt; and & as &amp;.`,
+ );
+ }
+
+ const component = tag.startsWith(CANVAS_TAG_PREFIX)
+ ? openComponent(tag, attrs, line)
+ : undefined;
+ stack.push({ component, tag });
+
+ if (tag === 'script') pendingScript = { attrs, line, text: '' };
+ if (tag === 'style') pendingStyle = { line, text: '' };
+ },
+ ontext(text) {
+ const textOwner = stack.at(-1)?.component;
+ if (textOwner?.spec.children === 'text') textOwner.text += text;
+ if (pendingScript) pendingScript.text += text;
+ if (pendingStyle) pendingStyle.text += text;
+ },
+ },
+ { decodeEntities: true, lowerCaseAttributeNames: true, lowerCaseTags: true },
+ );
+
+ parser.write(html);
+ parser.end();
+
+ for (const frame of stack.reverse()) if (frame.component) closeComponent(frame.component);
+
+ return issues;
+};
diff --git a/packages/canvas/src/validate/text.test.ts b/packages/canvas/src/validate/text.test.ts
new file mode 100644
index 00000000000..ca5eac14ae8
--- /dev/null
+++ b/packages/canvas/src/validate/text.test.ts
@@ -0,0 +1,22 @@
+import { describe, expect, it } from 'vitest';
+
+import { collectCssRefs } from './text';
+
+describe('collectCssRefs', () => {
+ it('collects url() and @import references', () => {
+ const css = `@import "theme.css"; .a { background: url('img/bg.png'); } .b { mask: url(icons.svg) }`;
+
+ expect(collectCssRefs(css).map((ref) => ref.href)).toEqual([
+ 'img/bg.png',
+ 'icons.svg',
+ 'theme.css',
+ ]);
+ });
+
+ it('scans adversarial url( runs in linear time', () => {
+ const started = performance.now();
+ collectCssRefs('url(!'.repeat(40_000));
+
+ expect(performance.now() - started).toBeLessThan(500);
+ });
+});
diff --git a/packages/canvas/src/validate/text.ts b/packages/canvas/src/validate/text.ts
new file mode 100644
index 00000000000..c721d8c58fe
--- /dev/null
+++ b/packages/canvas/src/validate/text.ts
@@ -0,0 +1,60 @@
+import type { CanvasIssue } from './types';
+
+const NETWORK_PATTERNS: [RegExp, string][] = [
+ [/\bfetch\s*\(/, 'fetch()'],
+ [/\bXMLHttpRequest\b/, 'XMLHttpRequest'],
+ [/\bWebSocket\b/, 'WebSocket'],
+ [/\bEventSource\b/, 'EventSource'],
+ [/\bsendBeacon\b/, 'navigator.sendBeacon'],
+ [/\bimportScripts\s*\(/, 'importScripts()'],
+ [/\bimport\s*\(\s*["'`](?:https?:)?\/\//, 'remote import()'],
+ [/\bfrom\s*["'](?:https?:)?\/\//, 'remote import'],
+];
+
+export const lineAt = (text: string, index: number) => {
+ let line = 1;
+ for (let i = 0; i < index && i < text.length; i += 1) if (text.charCodeAt(i) === 10) line += 1;
+ return line;
+};
+
+export const checkScriptText = (file: string, text: string, lineOffset = 1): CanvasIssue[] => {
+ const issues: CanvasIssue[] = [];
+
+ for (const [pattern, name] of NETWORK_PATTERNS) {
+ const match = pattern.exec(text);
+ if (!match) continue;
+ issues.push({
+ file,
+ line: lineOffset + lineAt(text, match.index) - 1,
+ message: `${name} is not available: a Canvas has no network access. Embed the data in the project (inline JSON or a .json file) instead.`,
+ rule: 'network-api',
+ });
+ }
+
+ return issues;
+};
+
+const CSS_URL_PATTERN = /url\(\s*(["']?)([^\s"'()]+)\1\s*\)/g;
+const CSS_IMPORT_PATTERN = /@import\s+(["'])([^"']+)\1/g;
+
+export const collectCssRefs = (text: string): { href: string; index: number }[] => {
+ const refs: { href: string; index: number }[] = [];
+ for (const pattern of [CSS_URL_PATTERN, CSS_IMPORT_PATTERN]) {
+ for (const match of text.matchAll(pattern)) refs.push({ href: match[2], index: match.index });
+ }
+ return refs;
+};
+
+const COLOR_PROPERTY = /color|background|border|fill|stroke|shadow|outline/;
+const COLOR_LITERAL =
+ /#[\da-f]{3,8}\b|\b(?:rgba?|hsla?|hwb|lab|lch|oklab|oklch)\(|\b(?:black|white|red|green|blue|yellow|orange|purple|pink|gray|grey|brown|cyan|magenta)\b/i;
+
+export const findHardCodedColor = (style: string): string | undefined => {
+ for (const declaration of style.split(';')) {
+ const colon = declaration.indexOf(':');
+ if (colon === -1) continue;
+ const property = declaration.slice(0, colon).trim().toLowerCase();
+ const value = declaration.slice(colon + 1).trim();
+ if (COLOR_PROPERTY.test(property) && COLOR_LITERAL.test(value)) return declaration.trim();
+ }
+};
diff --git a/packages/canvas/src/validate/types.ts b/packages/canvas/src/validate/types.ts
new file mode 100644
index 00000000000..a0778035b26
--- /dev/null
+++ b/packages/canvas/src/validate/types.ts
@@ -0,0 +1,49 @@
+export type CanvasIssueRule =
+ | 'broken-reference'
+ | 'duplicate-path'
+ | 'entry-missing'
+ | 'file-too-large'
+ | 'file-type-mismatch'
+ | 'hard-coded-color'
+ | 'invalid-attribute'
+ | 'invalid-diagram'
+ | 'invalid-path'
+ | 'misplaced-component'
+ | 'missing-attribute'
+ | 'network-api'
+ | 'markup-in-text'
+ | 'project-too-large'
+ | 'quota-exceeded'
+ | 'remote-resource'
+ | 'self-closing-component'
+ | 'too-many-files'
+ | 'unknown-attribute'
+ | 'unknown-component'
+ | 'unresolved-file-ref';
+
+export interface CanvasIssue {
+ file?: string;
+ line?: number;
+ message: string;
+ rule: CanvasIssueRule;
+}
+
+export interface CanvasValidationResult {
+ issues: CanvasIssue[];
+ ok: boolean;
+}
+
+export interface CanvasMermaidProblem {
+ line?: number;
+ message: string;
+}
+
+export interface CanvasValidationOptions {
+ checkMermaid?: (source: string) => CanvasMermaidProblem | undefined;
+}
+
+export interface CanvasProjectFile {
+ content: string | Uint8Array;
+ path: string;
+ size?: number;
+}
diff --git a/packages/canvas/src/validate/validateCanvasProject.test.ts b/packages/canvas/src/validate/validateCanvasProject.test.ts
new file mode 100644
index 00000000000..50e97daf6b1
--- /dev/null
+++ b/packages/canvas/src/validate/validateCanvasProject.test.ts
@@ -0,0 +1,284 @@
+import { describe, expect, it } from 'vitest';
+
+import { checkCanvasMermaid } from '../mermaid';
+import { CANVAS_LIMITS } from '../project/limits';
+import { CANVAS_COMPONENTS } from '../schema/components';
+import { validateCanvasProject } from './validateCanvasProject';
+
+const page = (body: string) =>
+ `<!doctype html><html><head><title>R</title></head><body>${body}</body></html>`;
+
+const run = (files: Record<string, string | Uint8Array>) =>
+ validateCanvasProject(Object.entries(files).map(([path, content]) => ({ content, path })));
+
+const rules = (files: Record<string, string | Uint8Array>) => run(files).issues.map((i) => i.rule);
+
+describe('validateCanvasProject', () => {
+ it('accepts a valid multi-file project', () => {
+ const result = run({
+ 'data/cost.json': '[{"m":"Sep","v":1}]',
+ 'index.html': page(`
+ <lobe-alert type="info" title="Up 23%">Opus drove it.</lobe-alert>
+ <lobe-grid rows="3" gap="12">
+ <lobe-stat title="Total" value="18420" prefix="$" trend="up"></lobe-stat>
+ </lobe-grid>
+ <lobe-line-chart index="m" categories='["v"]' data-src="./data/cost.json"></lobe-line-chart>
+ <lobe-select id="r" value="7d"><lobe-option value="7d">7 days</lobe-option></lobe-select>
+ <img src="assets/logo.png">
+ <a href="detail.html">Detail</a>
+ <script src="./app.js"></script>
+ `),
+ 'app.js': 'document.querySelector("#r").addEventListener("lobe-change", () => {});',
+ 'assets/logo.png': new Uint8Array([1, 2, 3]),
+ 'detail.html': page('<p>detail</p>'),
+ });
+
+ expect(result.issues).toEqual([]);
+ expect(result.ok).toBe(true);
+ });
+
+ it('requires an index.html entry', () => {
+ expect(rules({ 'a.html': page('') })).toContain('entry-missing');
+ });
+
+ it('rejects unknown lobe tags with a suggestion', () => {
+ const { issues } = run({ 'index.html': page('<lobe-stats title="a" value="1"></lobe-stats>') });
+
+ expect(issues[0]).toMatchObject({ file: 'index.html', rule: 'unknown-component' });
+ expect(issues[0].message).toContain('lobe-stat');
+ });
+
+ it('reports the line of the offending tag', () => {
+ const { issues } = run({
+ 'index.html': '<html>\n<body>\n<lobe-nope></lobe-nope>\n</body></html>',
+ });
+
+ expect(issues[0]).toMatchObject({ line: 3, rule: 'unknown-component' });
+ });
+
+ it('rejects unknown attributes but allows global ones', () => {
+ expect(
+ rules({
+ 'index.html': page('<lobe-tag color="green" id="t" data-x="1" aria-label="t">x</lobe-tag>'),
+ }),
+ ).toEqual([]);
+ expect(rules({ 'index.html': page('<lobe-tag colour="green">x</lobe-tag>') })).toEqual([
+ 'unknown-attribute',
+ ]);
+ });
+
+ it('checks attribute types', () => {
+ expect(rules({ 'index.html': page('<lobe-stat title="a" value="lots"></lobe-stat>') })).toEqual(
+ ['invalid-attribute'],
+ );
+ expect(rules({ 'index.html': page('<lobe-alert type="danger">x</lobe-alert>') })).toEqual([
+ 'invalid-attribute',
+ ]);
+ expect(
+ rules({ 'index.html': page(`<lobe-table columns='[{"title":"a"' data='[]'></lobe-table>`) }),
+ ).toEqual(['invalid-attribute']);
+ expect(rules({ 'index.html': page('<lobe-switch checked="yes"></lobe-switch>') })).toEqual([
+ 'invalid-attribute',
+ ]);
+ });
+
+ it('requires required attributes from an attribute, a -src file or a JSON child script', () => {
+ expect(rules({ 'index.html': page('<lobe-stat title="a"></lobe-stat>') })).toEqual([
+ 'missing-attribute',
+ ]);
+ expect(
+ rules({
+ 'index.html': page(`
+ <lobe-bar-list>
+ <script type="application/json" data-prop="data">[{"name":"a","value":1}]</script>
+ </lobe-bar-list>`),
+ }),
+ ).toEqual([]);
+ expect(
+ rules({ 'index.html': page('<lobe-bar-list data-src="missing.json"></lobe-bar-list>') }),
+ ).toEqual(['broken-reference']);
+ });
+
+ it('rejects invalid JSON in a -src file and in a JSON child script', () => {
+ expect(
+ rules({
+ 'bad.json': '{nope',
+ 'index.html': page('<lobe-bar-list data-src="bad.json"></lobe-bar-list>'),
+ }),
+ ).toEqual(['invalid-attribute']);
+ expect(
+ rules({
+ 'index.html': page(
+ '<lobe-bar-list><script type="application/json" data-prop="data">{nope</script></lobe-bar-list>',
+ ),
+ }),
+ ).toEqual(['invalid-attribute']);
+ });
+
+ it('only allows option-like children inside their parents', () => {
+ expect(rules({ 'index.html': page('<lobe-option value="a">A</lobe-option>') })).toEqual([
+ 'misplaced-component',
+ ]);
+ });
+
+ it('rejects chart colors outside the palette', () => {
+ expect(
+ rules({
+ 'index.html': page(
+ `<lobe-bar-chart index="a" categories='["b"]' data='[]' colors='["#ff0000"]'></lobe-bar-chart>`,
+ ),
+ }),
+ ).toEqual(['invalid-attribute']);
+ });
+
+ it('rejects hard-coded colors in inline styles of lobe components', () => {
+ expect(
+ rules({ 'index.html': page('<lobe-card style="background:#fff;padding:8px">x</lobe-card>') }),
+ ).toEqual(['hard-coded-color']);
+ expect(
+ rules({ 'index.html': page('<lobe-card style="color: rgb(0,0,0)">x</lobe-card>') }),
+ ).toEqual(['hard-coded-color']);
+ expect(
+ rules({
+ 'index.html': page('<lobe-card style="color: var(--lobe-color-text)">x</lobe-card>'),
+ }),
+ ).toEqual([]);
+ });
+
+ it('rejects network APIs in inline scripts and JS files', () => {
+ expect(rules({ 'index.html': page('<script>fetch("https://x.dev")</script>') })).toEqual([
+ 'network-api',
+ ]);
+ expect(
+ rules({
+ 'index.html': page('<script src="a.js"></script>'),
+ 'a.js': 'const ws = new WebSocket("wss://x")',
+ }),
+ ).toEqual(['network-api']);
+ });
+
+ it('rejects remote resources but allows data URIs and external links', () => {
+ expect(
+ rules({ 'index.html': page('<script src="https://cdn.example.com/x.js"></script>') }),
+ ).toEqual(['remote-resource']);
+ expect(rules({ 'index.html': page('<img src="https://example.com/a.png">') })).toEqual([
+ 'remote-resource',
+ ]);
+ expect(
+ rules({
+ 'index.html': page(
+ '<img src="data:image/png;base64,AA=="><a href="https://lobehub.com">x</a>',
+ ),
+ }),
+ ).toEqual([]);
+ });
+
+ it('rejects broken relative references', () => {
+ expect(rules({ 'index.html': page('<img src="./a.png">') })).toEqual(['broken-reference']);
+ expect(
+ rules({
+ 'index.html': page('<link rel="stylesheet" href="css/app.css">'),
+ 'css/app.css': 'body{background:url(../img/bg.png)}',
+ }),
+ ).toEqual(['broken-reference']);
+ });
+
+ it.each(['/image.png', '/image.png?v=1#preview', '\\image.png'])(
+ 'rejects root-relative HTML resources even when the project has the file: %s',
+ (href) => {
+ expect(
+ rules({
+ 'image.png': new Uint8Array([1, 2, 3]),
+ 'index.html': page(`<img src="${href}">`),
+ }),
+ ).toEqual(['broken-reference']);
+ },
+ );
+
+ it('rejects root-relative references in CSS assets', () => {
+ expect(
+ rules({
+ 'app.css': 'body{background-image:url(/image.png)}',
+ 'image.png': new Uint8Array([1, 2, 3]),
+ 'index.html': page('<link rel="stylesheet" href="app.css">'),
+ }),
+ ).toEqual(['broken-reference']);
+ });
+
+ it('rejects unsafe paths and disallowed file types', () => {
+ expect(rules({ '../x.html': '', 'index.html': page('') })).toEqual(['invalid-path']);
+ expect(rules({ 'index.html': page(''), 'run.exe': new Uint8Array([0]) })).toEqual([
+ 'invalid-path',
+ ]);
+ });
+
+ it('trusts a known size for files whose bytes were not loaded', () => {
+ const result = validateCanvasProject([
+ { content: page('<img src="big.png">'), path: 'index.html' },
+ { content: new Uint8Array(0), path: 'big.png', size: CANVAS_LIMITS.maxFileBytes + 1 },
+ ]);
+
+ expect(result.issues.map((issue) => issue.rule)).toEqual(['file-too-large']);
+ });
+
+ it('enforces size and count limits', () => {
+ const many: Record<string, string> = { 'index.html': page('') };
+ for (let i = 0; i < CANVAS_LIMITS.maxFiles; i += 1) many[`f${i}.json`] = '[]';
+ expect(rules(many)).toContain('too-many-files');
+
+ expect(
+ rules({
+ 'big.png': new Uint8Array(CANVAS_LIMITS.maxFileBytes + 1),
+ 'index.html': page(''),
+ }),
+ ).toContain('file-too-large');
+ });
+});
+
+describe('validateCanvasProject · text components', () => {
+ const runWithMermaid = (html: string) =>
+ validateCanvasProject([{ content: html, path: 'index.html' }], {
+ checkMermaid: checkCanvasMermaid,
+ });
+
+ it('accepts the documented code and diagram examples', () => {
+ const examples = CANVAS_COMPONENTS.filter((spec) => spec.children === 'text')
+ .map((spec) => spec.example)
+ .join('\n');
+
+ expect(runWithMermaid(page(examples)).issues).toEqual([]);
+ });
+
+ it('rejects markup inside code, which the browser would swallow as an element', () => {
+ const { issues } = run({
+ 'index.html':
+ '<html>\n<body>\n<lobe-code language="ts">\nconst x: Array<string> = [];\n</lobe-code></body></html>',
+ });
+
+ expect(issues).toHaveLength(1);
+ expect(issues[0]).toMatchObject({ line: 4, rule: 'markup-in-text' });
+ expect(issues[0].message).toContain('&lt;');
+ });
+
+ it('rejects invalid Mermaid at the line the parser points at', () => {
+ const { issues } = runWithMermaid(
+ '<html>\n<body>\n<lobe-mermaid>\nflowchart TD\n A[Login --&gt; B\n</lobe-mermaid></body></html>',
+ );
+
+ expect(issues).toHaveLength(1);
+ expect(issues[0]).toMatchObject({ file: 'index.html', line: 6, rule: 'invalid-diagram' });
+ expect(issues[0].message).toContain('Parse error on line 6');
+ });
+
+ it('rejects text that is not a diagram', () => {
+ expect(
+ runWithMermaid(page('<lobe-mermaid>just some words</lobe-mermaid>')).issues.map(
+ (issue) => issue.rule,
+ ),
+ ).toEqual(['invalid-diagram']);
+ });
+
+ it('skips the Mermaid check when no checker is supplied', () => {
+ expect(rules({ 'index.html': page('<lobe-mermaid>not a diagram</lobe-mermaid>') })).toEqual([]);
+ });
+});
diff --git a/packages/canvas/src/validate/validateCanvasProject.ts b/packages/canvas/src/validate/validateCanvasProject.ts
new file mode 100644
index 00000000000..953d6d7c551
--- /dev/null
+++ b/packages/canvas/src/validate/validateCanvasProject.ts
@@ -0,0 +1,128 @@
+import { CANVAS_ENTRY, CANVAS_LIMITS } from '../project/limits';
+import {
+ getCanvasFileExtension,
+ isAllowedCanvasPath,
+ isCanvasTextPath,
+ normalizeCanvasPath,
+ resolveCanvasHref,
+} from '../project/path';
+import { type CanvasProjectIndex, validateHtmlFile } from './html';
+import { checkScriptText, collectCssRefs, lineAt } from './text';
+import type {
+ CanvasIssue,
+ CanvasProjectFile,
+ CanvasValidationOptions,
+ CanvasValidationResult,
+} from './types';
+
+const decoder = new TextDecoder();
+
+const byteLength = (content: string | Uint8Array) =>
+ typeof content === 'string' ? new TextEncoder().encode(content).byteLength : content.byteLength;
+
+const toText = (content: string | Uint8Array) =>
+ typeof content === 'string' ? content : decoder.decode(content);
+
+export const validateCanvasProject = (
+ files: CanvasProjectFile[],
+ options: CanvasValidationOptions = {},
+): CanvasValidationResult => {
+ const issues: CanvasIssue[] = [];
+ const entries = new Map<string, CanvasProjectFile>();
+ let totalBytes = 0;
+
+ for (const file of files) {
+ const path = normalizeCanvasPath(file.path);
+ if (!path || !isAllowedCanvasPath(path)) {
+ issues.push({
+ file: file.path,
+ message: path
+ ? `"${file.path}" has a file type a Canvas cannot hold.`
+ : `"${file.path}" is not a valid project path (relative, no "..", letters/digits/-_.@ only).`,
+ rule: 'invalid-path',
+ });
+ continue;
+ }
+ if (entries.has(path)) {
+ issues.push({
+ file: path,
+ message: `"${path}" appears more than once.`,
+ rule: 'duplicate-path',
+ });
+ continue;
+ }
+
+ const size = file.size ?? byteLength(file.content);
+ totalBytes += size;
+ const limit = isCanvasTextPath(path)
+ ? CANVAS_LIMITS.maxTextFileBytes
+ : CANVAS_LIMITS.maxFileBytes;
+ if (size > limit) {
+ issues.push({
+ file: path,
+ message: `"${path}" is ${size} bytes; the limit is ${limit}.`,
+ rule: 'file-too-large',
+ });
+ }
+ entries.set(path, { content: file.content, path });
+ }
+
+ if (files.length > CANVAS_LIMITS.maxFiles) {
+ issues.push({
+ message: `A Canvas holds at most ${CANVAS_LIMITS.maxFiles} files; got ${files.length}.`,
+ rule: 'too-many-files',
+ });
+ }
+ if (totalBytes > CANVAS_LIMITS.maxTotalBytes) {
+ issues.push({
+ message: `The project is ${totalBytes} bytes; the limit is ${CANVAS_LIMITS.maxTotalBytes}.`,
+ rule: 'project-too-large',
+ });
+ }
+ if (!entries.has(CANVAS_ENTRY)) {
+ issues.push({
+ message: `The project needs an entry page at "${CANVAS_ENTRY}".`,
+ rule: 'entry-missing',
+ });
+ }
+
+ const project: CanvasProjectIndex = {
+ has: (path) => entries.has(path),
+ readText: (path) => {
+ const entry = entries.get(path);
+ return entry && isCanvasTextPath(path) ? toText(entry.content) : undefined;
+ },
+ };
+
+ for (const [path, entry] of entries) {
+ const extension = getCanvasFileExtension(path);
+ if (extension === 'html') {
+ issues.push(...validateHtmlFile(path, toText(entry.content), project, options));
+ } else if (extension === 'js' || extension === 'mjs') {
+ issues.push(...checkScriptText(path, toText(entry.content)));
+ } else if (extension === 'css') {
+ const text = toText(entry.content);
+ for (const ref of collectCssRefs(text)) {
+ const resolved = resolveCanvasHref(path, ref.href);
+ const line = lineAt(text, ref.index);
+ if (resolved.kind === 'remote') {
+ issues.push({
+ file: path,
+ line,
+ message: `CSS reference "${ref.href}" is remote. Copy it into the project.`,
+ rule: 'remote-resource',
+ });
+ } else if (resolved.kind === 'local' && (!resolved.path || !entries.has(resolved.path))) {
+ issues.push({
+ file: path,
+ line,
+ message: `CSS reference "${ref.href}" points at a file that is not in the project.`,
+ rule: 'broken-reference',
+ });
+ }
+ }
+ }
+ }
+
+ return { issues, ok: issues.length === 0 };
+};
diff --git a/packages/canvas/vitest.config.mts b/packages/canvas/vitest.config.mts
new file mode 100644
index 00000000000..4ac6027d578
--- /dev/null
+++ b/packages/canvas/vitest.config.mts
@@ -0,0 +1,7 @@
+import { defineConfig } from 'vitest/config';
+
+export default defineConfig({
+ test: {
+ environment: 'node',
+ },
+});
diff --git a/packages/const/src/apiKeyScope.ts b/packages/const/src/apiKeyScope.ts
index 21c47778012..691f3a41fb1 100644
--- a/packages/const/src/apiKeyScope.ts
+++ b/packages/const/src/apiKeyScope.ts
@@ -206,6 +206,8 @@ export const TRPC_NAMESPACE_API_KEY_RULES: Record<string, TrpcNamespaceScopeRule
// decrypts stored bot/messenger credentials and calls external channel APIs
botMessage: 'blocked',
brief: rw('chat:read', 'chat:write'),
+ // publish opens a public site from stored files; no key-based client drives canvases
+ canvas: 'blocked',
changelog: 'open',
chunk: rw('knowledge:read', 'knowledge:write'),
comfyui: rw('model:read', 'model:write'),
diff --git a/packages/database/src/models/canvasFile.ts b/packages/database/src/models/canvasFile.ts
new file mode 100644
index 00000000000..46495672759
--- /dev/null
+++ b/packages/database/src/models/canvasFile.ts
@@ -0,0 +1,89 @@
+import { FileSource } from '@lobechat/types';
+import { and, eq, inArray, sql } from 'drizzle-orm';
+
+import { files } from '../schemas';
+import type { LobeChatDatabase } from '../type';
+import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';
+
+export interface CanvasBlobRecord {
+ contentType: string;
+ hash: string;
+ name: string;
+ size: number;
+ url: string;
+}
+
+const canvasIdField = sql<string | null>`${files.metadata} ->> 'canvasId'`;
+
+export class CanvasFileModel {
+ private db: LobeChatDatabase;
+ private userId: string;
+ private workspaceId?: string;
+
+ constructor(db: LobeChatDatabase, userId: string, workspaceId?: string) {
+ this.db = db;
+ this.userId = userId;
+ this.workspaceId = workspaceId;
+ }
+
+ private ownership = () =>
+ and(
+ buildWorkspaceWhere({ userId: this.userId, workspaceId: this.workspaceId }, files),
+ eq(files.userId, this.userId),
+ eq(files.source, FileSource.Canvas),
+ );
+
+ listByHashes = async (hashes: string[]) => {
+ if (hashes.length === 0) return [];
+
+ return this.db
+ .select({ canvasId: canvasIdField, fileHash: files.fileHash, id: files.id, url: files.url })
+ .from(files)
+ .where(and(this.ownership(), inArray(files.fileHash, hashes)));
+ };
+
+ insertFiles = async (canvasId: string, blobs: CanvasBlobRecord[]) => {
+ if (blobs.length === 0) return;
+
+ await this.db.insert(files).values(
+ blobs.map((item) =>
+ buildWorkspacePayload(
+ { userId: this.userId, workspaceId: this.workspaceId },
+ {
+ fileHash: item.hash,
+ fileType: item.contentType,
+ metadata: { canvasId },
+ name: item.name,
+ size: item.size,
+ source: FileSource.Canvas,
+ url: item.url,
+ },
+ ),
+ ),
+ );
+ };
+
+ deleteByCanvas = async (canvasId: string): Promise<string[]> => {
+ const removed = await this.db
+ .delete(files)
+ .where(and(this.ownership(), eq(canvasIdField, canvasId)))
+ .returning({ url: files.url });
+
+ const urls = [...new Set(removed.map((row) => row.url))];
+ if (urls.length === 0) return [];
+
+ const stillUsed = await this.db
+ .select({ url: files.url })
+ .from(files)
+ .where(
+ and(
+ eq(files.userId, this.userId),
+ eq(files.source, FileSource.Canvas),
+ inArray(files.url, urls),
+ ),
+ );
+ const used = new Set(stillUsed.map((row) => row.url));
+
+ return urls.filter((url) => !used.has(url));
+ };
+}
diff --git a/packages/database/src/models/work/__tests__/canvas.test.ts b/packages/database/src/models/work/__tests__/canvas.test.ts
new file mode 100644
index 00000000000..c71027bf144
--- /dev/null
+++ b/packages/database/src/models/work/__tests__/canvas.test.ts
@@ -0,0 +1,181 @@
+// @vitest-environment node
+import type { RegisterCanvasWorkParams } from '@lobechat/types';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { WorkModel } from '..';
+import {
+ agentId,
+ cleanupWorkTestData,
+ seedWorkTestData,
+ serverDB,
+ threadId,
+ topicId,
+ userId,
+ userId2,
+} from './_fixtures';
+
+beforeEach(seedWorkTestData);
+afterEach(cleanupWorkTestData);
+
+const params = (overrides: Partial<RegisterCanvasWorkParams> = {}): RegisterCanvasWorkParams => ({
+ agentId,
+ canvasId: 'cvs_cost',
+ description: 'Total cost up 23%',
+ metadata: {
+ entry: 'index.html',
+ fileCount: 2,
+ manifestKey: 'canvas/u/cvs_cost/manifests/a.json',
+ runtimeMajor: 1,
+ totalSize: 4096,
+ },
+ rootOperationId: 'op-canvas-1',
+ threadId,
+ title: 'October cost report',
+ toolCallId: 'call-canvas-1',
+ toolIdentifier: 'lobe-canvas',
+ toolName: 'createCanvas',
+ topicId,
+ ...overrides,
+});
+
+describe('WorkModel · canvas', () => {
+ it('appends a version per registration of the same canvas id', async () => {
+ const model = new WorkModel(serverDB, userId);
+
+ const first = await model.registerCanvas(params());
+ const second = await model.registerCanvas(
+ params({
+ metadata: { ...params().metadata, manifestKey: 'canvas/u/cvs_cost/manifests/b.json' },
+ title: 'October cost report v2',
+ toolCallId: 'call-canvas-2',
+ toolName: 'writeCanvasFiles',
+ }),
+ );
+
+ expect(second.id).toBe(first.id);
+ expect(second).toMatchObject({
+ resourceType: 'canvas',
+ title: 'October cost report v2',
+ type: 'canvas',
+ });
+
+ const versions = await model.listVersions(first.id);
+ expect(versions.map((v) => [v.version, v.changeType])).toEqual([
+ [2, 'updated'],
+ [1, 'created'],
+ ]);
+ expect(versions[0].metadata?.canvas?.manifestKey).toBe('canvas/u/cvs_cost/manifests/b.json');
+ expect(versions[1]).toMatchObject({ messageId: null, toolCallId: 'call-canvas-1' });
+ });
+
+ it('resolves a canvas with its current version, scoped to the owner', async () => {
+ const model = new WorkModel(serverDB, userId);
+ const work = await model.registerCanvas(params());
+
+ const found = await model.findCanvas('cvs_cost');
+ expect(found).toMatchObject({ version: { version: 1 }, work: { id: work.id } });
+ expect(found?.version.metadata?.canvas?.entry).toBe('index.html');
+
+ expect(await new WorkModel(serverDB, userId2).findCanvas('cvs_cost')).toBeNull();
+ expect(await model.findCanvas('cvs_missing')).toBeNull();
+ });
+
+ it('reads a specific version of a canvas', async () => {
+ const model = new WorkModel(serverDB, userId);
+ const work = await model.registerCanvas(params());
+ await model.registerCanvas(params({ toolCallId: 'call-canvas-2' }));
+
+ expect((await model.findCanvasVersion(work.id, 1))?.version).toBe(1);
+ expect((await model.findCanvasVersion(work.id, 2))?.version).toBe(2);
+ expect(await model.findCanvasVersion(work.id, 3)).toBeNull();
+ });
+
+ it('lists canvases first made by an agent, newest first', async () => {
+ const model = new WorkModel(serverDB, userId);
+ await model.registerCanvas(params());
+ await model.registerCanvas(params({ canvasId: 'cvs_other', title: 'Other', toolCallId: 'c3' }));
+
+ const list = await model.listCanvases({ agentId });
+ expect(list.map((item) => item.resourceId)).toEqual(['cvs_other', 'cvs_cost']);
+ expect(await model.listCanvases({ agentId: 'nobody' })).toEqual([]);
+ });
+
+ it('reports a deleted canvas work so its stored files can be purged', async () => {
+ const model = new WorkModel(serverDB, userId);
+ const work = await model.registerCanvas(params());
+ const secondManifest = 'canvas/u/cvs_cost/manifests/b.json';
+ await model.registerCanvas(
+ params({
+ metadata: { ...params().metadata, manifestKey: secondManifest },
+ toolCallId: 'call-canvas-delete-2',
+ }),
+ );
+
+ const [removed] = await model.deleteWork({ id: work.id });
+ expect(removed).toMatchObject({ resourceId: 'cvs_cost', resourceType: 'canvas' });
+ expect(removed.canvasManifestKeys).toEqual(
+ expect.arrayContaining([params().metadata.manifestKey, secondManifest]),
+ );
+ expect(removed.canvasManifestKeys).toHaveLength(2);
+ expect(await model.findCanvas('cvs_cost')).toBeNull();
+ expect(await model.listVersions(work.id)).toEqual([]);
+ });
+
+ it('records where a canvas is published, owner only, keeping other metadata', async () => {
+ const model = new WorkModel(serverDB, userId);
+ await model.registerCanvas(params());
+
+ expect(
+ await new WorkModel(serverDB, userId2).recordCanvasPublish('cvs_cost', {
+ deploymentId: 'dep_1',
+ publishedVersion: 1,
+ url: 'https://evil.lobehub.sites',
+ }),
+ ).toBeNull();
+ const work = await model.recordCanvasPublish('cvs_cost', {
+ deploymentId: 'dep_1',
+ publishedVersion: 1,
+ url: 'https://cost.lobehub.sites',
+ });
+
+ expect(work).toMatchObject({
+ metadata: { canvasPublish: { deploymentId: 'dep_1', publishedVersion: 1 } },
+ url: 'https://cost.lobehub.sites',
+ });
+ expect((await model.findCanvas('cvs_cost'))?.work.url).toBe('https://cost.lobehub.sites');
+ });
+
+ it('keeps the public link of a published canvas when a newer version is registered', async () => {
+ const model = new WorkModel(serverDB, userId);
+ await model.registerCanvas(params());
+ await model.recordCanvasPublish('cvs_cost', {
+ deploymentId: 'dep_1',
+ publishedVersion: 1,
+ url: 'https://cost.lobehub.sites',
+ });
+
+ await model.registerCanvas(params({ toolCallId: 'call-canvas-2', toolName: 'updateCanvas' }));
+
+ const current = await model.findCanvas('cvs_cost');
+ expect(current?.version.version).toBe(2);
+ expect(current?.work).toMatchObject({
+ metadata: { canvasPublish: { deploymentId: 'dep_1', publishedVersion: 1 } },
+ url: 'https://cost.lobehub.sites',
+ });
+ });
+
+ it('only surfaces canvas works to clients that opted into newer work types', async () => {
+ const model = new WorkModel(serverDB, userId);
+ await model.registerCanvas(params());
+
+ const optedIn = await model.listSummariesByRootOperations({
+ includeFileWorks: true,
+ rootOperationIds: ['op-canvas-1'],
+ });
+ expect(optedIn['op-canvas-1']).toHaveLength(1);
+ expect(optedIn['op-canvas-1'][0]).toMatchObject({ type: 'canvas' });
+
+ const legacy = await model.listSummariesByRootOperations({ rootOperationIds: ['op-canvas-1'] });
+ expect(legacy['op-canvas-1'] ?? []).toEqual([]);
+ });
+});
diff --git a/packages/database/src/models/work/__tests__/document.test.ts b/packages/database/src/models/work/__tests__/document.test.ts
index 2355548c7ea..ac5d5748a2e 100644
--- a/packages/database/src/models/work/__tests__/document.test.ts
+++ b/packages/database/src/models/work/__tests__/document.test.ts
@@ -541,7 +541,7 @@ describe('WorkModel · workspace document visibility', () => {
const ownerWorks = new WorkModel(serverDB, userId, workspaceId);
await registerWorkspaceDocument('public');
- await expect(ownerWorks.deleteWork({ id: 'work_missing' })).resolves.toBeUndefined();
+ await expect(ownerWorks.deleteWork({ id: 'work_missing' })).resolves.toEqual([]);
expect(await ownerWorks.listByConversation({ topicId })).toHaveLength(1);
});
});
diff --git a/packages/database/src/models/work/__tests__/queries.test.ts b/packages/database/src/models/work/__tests__/queries.test.ts
index 1f21d129266..bdba266d1bc 100644
--- a/packages/database/src/models/work/__tests__/queries.test.ts
+++ b/packages/database/src/models/work/__tests__/queries.test.ts
@@ -93,9 +93,9 @@ describe('WorkModel · queries', () => {
rootOperationIds: ['op-batch-1', 'op-batch-2', 'op-batch-missing'],
});
- // One query per work type across all ids, not per (id x type). Four
- // registered types now: document / external / file / task.
- expect(selectSpy).toHaveBeenCalledTimes(4);
+ // One query per work type across all ids, not per (id x type). Five
+ // registered types now: canvas / document / external / file / task.
+ expect(selectSpy).toHaveBeenCalledTimes(5);
expect(byOperations['op-batch-1']?.map((item) => item.resourceId)).toEqual([firstTask.id]);
expect(byOperations['op-batch-2']?.map((item) => item.resourceId)).toEqual([secondTask.id]);
expect(byOperations['op-batch-missing']).toEqual([]);
diff --git a/packages/database/src/models/work/canvas.ts b/packages/database/src/models/work/canvas.ts
new file mode 100644
index 00000000000..eeae7bff1db
--- /dev/null
+++ b/packages/database/src/models/work/canvas.ts
@@ -0,0 +1,165 @@
+import type {
+ CanvasWorkPublishMetadata,
+ RegisterCanvasWorkParams,
+ WorkItem,
+ WorkMetadata,
+ WorkVersionItem,
+} from '@lobechat/types';
+import { and, desc, eq, inArray, sql } from 'drizzle-orm';
+
+import { works, workVersions } from '../../schemas/work';
+import { type WorkContext, workOwnership } from './context';
+import { createDisplayWorkAdapter } from './displayWork';
+import { registerWorkVersion } from './writes';
+
+export const canvasWorkAdapter = createDisplayWorkAdapter({ type: 'canvas' });
+
+const canvasResource = (ctx: WorkContext, canvasId: string) =>
+ and(workOwnership(ctx), eq(works.resourceType, 'canvas'), eq(works.resourceId, canvasId));
+
+export const registerCanvasWork = async (
+ ctx: WorkContext,
+ params: RegisterCanvasWorkParams,
+): Promise<WorkItem> => {
+ const [existing] = await ctx.db
+ .select({ id: works.id })
+ .from(works)
+ .where(canvasResource(ctx, params.canvasId))
+ .limit(1);
+
+ return registerWorkVersion(
+ ctx,
+ {
+ resourceId: params.canvasId,
+ resourceType: 'canvas',
+ type: 'canvas',
+ userId: ctx.userId,
+ visibility: params.visibility ?? 'private',
+ },
+ {
+ agentId: params.agentId,
+ changeType: existing ? 'updated' : 'created',
+ cumulativeCost: params.cumulativeCost,
+ cumulativeUsage: params.cumulativeUsage,
+ messageId: params.messageId,
+ rootOperationId: params.rootOperationId,
+ threadId: params.threadId,
+ toolCallId: params.toolCallId,
+ toolIdentifier: params.toolIdentifier,
+ toolName: params.toolName,
+ topicId: params.topicId,
+ },
+ async (txCtx) => {
+ // The public link written by `recordCanvasPublish` lives on the Work, and
+ // each registration replaces every display column, so carry it over.
+ const [published] = await txCtx.db
+ .select({ url: works.url })
+ .from(works)
+ .where(canvasResource(txCtx, params.canvasId))
+ .limit(1);
+
+ return {
+ display: {
+ description: params.description ?? null,
+ identifier: params.canvasId,
+ title: params.title,
+ url: published?.url ?? null,
+ },
+ metadata: { canvas: params.metadata },
+ };
+ },
+ );
+};
+
+export interface CanvasWorkWithVersion {
+ version: WorkVersionItem;
+ work: WorkItem & { metadata: WorkMetadata | null };
+}
+
+export const findCanvasWork = async (
+ ctx: WorkContext,
+ canvasId: string,
+): Promise<CanvasWorkWithVersion | null> => {
+ const [row] = await ctx.db
+ .select({ version: workVersions, work: works })
+ .from(works)
+ .innerJoin(workVersions, eq(workVersions.id, works.currentVersionId))
+ .where(canvasResource(ctx, canvasId))
+ .limit(1);
+
+ return row ? { version: row.version, work: row.work as CanvasWorkWithVersion['work'] } : null;
+};
+
+export const findCanvasWorkVersion = async (
+ ctx: WorkContext,
+ workId: string,
+ version: number,
+): Promise<WorkVersionItem | null> => {
+ const [row] = await ctx.db
+ .select({ version: workVersions })
+ .from(workVersions)
+ .innerJoin(works, and(eq(workVersions.workId, works.id), workOwnership(ctx)))
+ .where(and(eq(works.id, workId), eq(works.type, 'canvas'), eq(workVersions.version, version)))
+ .limit(1);
+
+ return row?.version ?? null;
+};
+
+export const findReferencedCanvasManifestKeys = async (ctx: WorkContext, keys: string[]) => {
+ if (keys.length === 0) return [];
+ const manifestKey = sql<string>`${workVersions.metadata} -> 'canvas' ->> 'manifestKey'`;
+ const rows = await ctx.db
+ .selectDistinct({ manifestKey })
+ .from(workVersions)
+ .innerJoin(works, eq(workVersions.workId, works.id))
+ .where(
+ and(
+ // Object keys are shared by the user's canvases across all workspaces.
+ eq(works.userId, ctx.userId),
+ eq(works.resourceType, 'canvas'),
+ inArray(manifestKey, keys),
+ ),
+ );
+ return rows.map((row) => row.manifestKey);
+};
+
+export const listCanvasWorks = async (
+ ctx: WorkContext,
+ params: { agentId?: string | null; limit?: number },
+): Promise<WorkItem[]> => {
+ const rows = await ctx.db
+ .select()
+ .from(works)
+ .where(
+ and(
+ workOwnership(ctx),
+ eq(works.type, 'canvas'),
+ params.agentId ? eq(works.originAgentId, params.agentId) : undefined,
+ ),
+ )
+ .orderBy(desc(works.updatedAt), desc(works.id))
+ .limit(params.limit ?? 20);
+
+ return rows as WorkItem[];
+};
+
+export const recordCanvasPublish = async (
+ ctx: WorkContext,
+ canvasId: string,
+ params: CanvasWorkPublishMetadata & { url: string },
+): Promise<WorkItem | null> => {
+ const publish: CanvasWorkPublishMetadata = {
+ deploymentId: params.deploymentId,
+ publishedVersion: params.publishedVersion,
+ };
+ const [row] = await ctx.db
+ .update(works)
+ .set({
+ metadata: sql`coalesce(${works.metadata}, '{}'::jsonb) || jsonb_build_object('canvasPublish', ${JSON.stringify(publish)}::jsonb)`,
+ url: params.url,
+ })
+ .where(and(canvasResource(ctx, canvasId), eq(works.userId, ctx.userId)))
+ .returning();
+
+ return (row as WorkItem | undefined) ?? null;
+};
diff --git a/packages/database/src/models/work/index.ts b/packages/database/src/models/work/index.ts
index 9ae580cfcfc..97196d37846 100644
--- a/packages/database/src/models/work/index.ts
+++ b/packages/database/src/models/work/index.ts
@@ -1,8 +1,10 @@
import {
+ type CanvasWorkPublishMetadata,
type DeleteDocumentWorkParams,
type DeleteTaskWorkParams,
type DeleteWorkParams,
isWorkSkillProvider,
+ type RegisterCanvasWorkParams,
type RegisterDocumentWorkParams,
type RegisterExternalWorkParams,
type RegisterFileWorkParams,
@@ -16,6 +18,14 @@ import {
} from '@lobechat/types';
import type { LobeChatDatabase } from '../../type';
+import {
+ findCanvasWork,
+ findCanvasWorkVersion,
+ findReferencedCanvasManifestKeys,
+ listCanvasWorks,
+ recordCanvasPublish,
+ registerCanvasWork,
+} from './canvas';
import type { WorkContext } from './context';
import { registerDocumentWork } from './document';
import { registerExternalWork } from './external';
@@ -82,6 +92,25 @@ export class WorkModel {
registerFile = (params: RegisterFileWorkParams): Promise<WorkItem> =>
registerFileWork(this.ctx, params);
+ registerCanvas = (params: RegisterCanvasWorkParams): Promise<WorkItem> =>
+ registerCanvasWork(this.ctx, params);
+
+ findCanvas = (canvasId: string) => findCanvasWork(this.ctx, canvasId);
+
+ recordCanvasPublish = (
+ canvasId: string,
+ params: CanvasWorkPublishMetadata & { url: string },
+ ): Promise<WorkItem | null> => recordCanvasPublish(this.ctx, canvasId, params);
+
+ findCanvasVersion = (workId: string, version: number) =>
+ findCanvasWorkVersion(this.ctx, workId, version);
+
+ findReferencedCanvasManifestKeys = (keys: string[]) =>
+ findReferencedCanvasManifestKeys(this.ctx, keys);
+
+ listCanvases = (params: { agentId?: string | null; limit?: number }) =>
+ listCanvasWorks(this.ctx, params);
+
registerGoalReport = (params: RegisterGoalReportWorkParams): Promise<WorkItem> =>
registerGoalReportWork(this.ctx, params);
@@ -139,7 +168,7 @@ export class WorkModel {
deleteTaskWork = (params: DeleteTaskWorkParams): Promise<void> =>
writes.deleteTaskWork(this.ctx, params);
- deleteWork = (params: DeleteWorkParams): Promise<void> => writes.deleteWork(this.ctx, params);
+ deleteWork = (params: DeleteWorkParams) => writes.deleteWork(this.ctx, params);
/** See {@link writes.setTaskWorksVisibility}. */
setTaskWorksVisibility = (taskIds: string[], visibility: WorkVisibility): Promise<void> =>
diff --git a/packages/database/src/models/work/internal.ts b/packages/database/src/models/work/internal.ts
index 4a197264290..959fa350cf5 100644
--- a/packages/database/src/models/work/internal.ts
+++ b/packages/database/src/models/work/internal.ts
@@ -186,7 +186,7 @@ export interface TaskWorkSummaryQueryRow {
* Work types whose list rows are fully described by the `works` display columns
* (unlike `task`, which additionally joins the live tasks table).
*/
-export type DisplayWorkType = 'document' | 'external' | 'file';
+export type DisplayWorkType = 'canvas' | 'document' | 'external' | 'file';
/** Version-event row for display-backed types (each mutation event). */
export interface DisplayVersionEventRow {
diff --git a/packages/database/src/models/work/registry.ts b/packages/database/src/models/work/registry.ts
index 82e78310c95..0db3211849d 100644
--- a/packages/database/src/models/work/registry.ts
+++ b/packages/database/src/models/work/registry.ts
@@ -1,5 +1,6 @@
import type { WorkType } from '@lobechat/types';
+import { canvasWorkAdapter } from './canvas';
import { documentWorkAdapter } from './document';
import { externalWorkAdapter } from './external';
import { fileWorkAdapter } from './file';
@@ -14,6 +15,7 @@ import { taskWorkAdapter } from './task';
* set) plus its type unions in `@lobechat/types`.
*/
export const WORK_TYPE_ADAPTERS = {
+ canvas: canvasWorkAdapter,
document: documentWorkAdapter,
external: externalWorkAdapter,
file: fileWorkAdapter,
@@ -41,7 +43,7 @@ export const workTypeAdapters = WORK_TYPES.map(
* request that does not opt in therefore receives the pre-`file` set, keeping
* every already-deployed client byte-identically safe; new clients opt in.
*/
-const OPT_IN_WORK_TYPES = new Set<WorkType>(['file']);
+const OPT_IN_WORK_TYPES = new Set<WorkType>(['canvas', 'file']);
/** The pre-`file` type set every already-deployed client is known to render. */
export const LEGACY_WORK_TYPES = WORK_TYPES.filter((type) => !OPT_IN_WORK_TYPES.has(type));
diff --git a/packages/database/src/models/work/writes.ts b/packages/database/src/models/work/writes.ts
index 1c543d04b0f..48ce9254985 100644
--- a/packages/database/src/models/work/writes.ts
+++ b/packages/database/src/models/work/writes.ts
@@ -388,13 +388,16 @@ export const setTaskWorksVisibility = async (
* eligible. Cascades `work_versions`, `project_works` and
* `goal_node_work_versions` via FK.
*/
-export const deleteWork = async (ctx: WorkContext, params: DeleteWorkParams): Promise<void> => {
+export const deleteWork = async (
+ ctx: WorkContext,
+ params: DeleteWorkParams,
+): Promise<{ canvasManifestKeys: string[]; resourceId: string | null; resourceType: string }[]> => {
const backingResourceGone = sql<boolean>`case ${works.resourceType}
when 'task' then not exists (select 1 from ${tasks} where ${tasks.id} = ${works.resourceId})
when 'document' then not exists (select 1 from ${documents} where ${documents.id} = ${works.resourceId})
else true end`;
- await ctx.db
+ return ctx.db
.delete(works)
.where(
and(
@@ -403,5 +406,16 @@ export const deleteWork = async (ctx: WorkContext, params: DeleteWorkParams): Pr
eq(works.userId, ctx.userId),
backingResourceGone,
),
- );
+ )
+ .returning({
+ // RETURNING reads the version keys before the FK cascade removes their rows.
+ canvasManifestKeys: sql<string[]>`array(
+ select distinct ${workVersions.metadata} -> 'canvas' ->> 'manifestKey'
+ from ${workVersions}
+ where ${workVersions.workId} = ${params.id}
+ and coalesce(${workVersions.metadata} -> 'canvas' ->> 'manifestKey', '') <> ''
+ )`,
+ resourceId: works.resourceId,
+ resourceType: works.resourceType,
+ });
};
diff --git a/packages/database/src/repositories/canvasFile/__tests__/index.test.ts b/packages/database/src/repositories/canvasFile/__tests__/index.test.ts
new file mode 100644
index 00000000000..fe8a2203755
--- /dev/null
+++ b/packages/database/src/repositories/canvasFile/__tests__/index.test.ts
@@ -0,0 +1,112 @@
+// @vitest-environment node
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { getTestDB } from '../../../core/getTestDB';
+import { CanvasFileModel } from '../../../models/canvasFile';
+import { FileModel } from '../../../models/file';
+import { users, workspaceMembers, workspaces } from '../../../schemas';
+import type { LobeChatDatabase } from '../../../type';
+import { CanvasFileRepository } from '../index';
+
+const serverDB: LobeChatDatabase = await getTestDB();
+const userId = 'canvas-file-user';
+const otherUserId = 'canvas-file-user-2';
+
+beforeEach(async () => {
+ await serverDB.delete(users);
+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);
+});
+
+afterEach(async () => {
+ await serverDB.delete(users);
+});
+
+const blob = (hash: string, size = 10) => ({
+ contentType: 'text/html',
+ hash,
+ name: 'index.html',
+ size,
+ url: `canvas/${userId}/blobs/${hash}`,
+});
+
+describe('CanvasFileRepository', () => {
+ it('registers one file row per canvas blob and counts it toward storage usage', async () => {
+ const repository = new CanvasFileRepository(serverDB, userId);
+ await repository.register('cvs_a', [blob('h1', 100), blob('h2', 50)]);
+ await repository.register('cvs_a', [blob('h1', 100)]);
+ const model = new CanvasFileModel(serverDB, userId);
+
+ expect(
+ (await model.listByHashes(['h1', 'h2'])).map((row) => [row.canvasId, row.fileHash]),
+ ).toEqual(
+ expect.arrayContaining([
+ ['cvs_a', 'h1'],
+ ['cvs_a', 'h2'],
+ ]),
+ );
+ expect(await new FileModel(serverDB, userId).countUsage()).toBe(150);
+ });
+
+ it('keeps blobs owned per user', async () => {
+ await new CanvasFileRepository(serverDB, userId).register('cvs_a', [blob('h1')]);
+
+ expect(await new CanvasFileModel(serverDB, otherUserId).listByHashes(['h1'])).toEqual([]);
+ });
+
+ it('does not reuse a teammate canvas blob in a shared workspace', async () => {
+ const workspaceId = 'canvas-file-ws';
+ await serverDB
+ .insert(workspaces)
+ .values({ id: workspaceId, name: 'ws', primaryOwnerId: userId, slug: workspaceId });
+ await serverDB.insert(workspaceMembers).values([
+ { role: 'owner', userId, workspaceId },
+ { role: 'editor', userId: otherUserId, workspaceId },
+ ]);
+ await new CanvasFileRepository(serverDB, userId, workspaceId).register('cvs_a', [blob('h1')]);
+
+ expect(
+ await new CanvasFileModel(serverDB, otherUserId, workspaceId).listByHashes(['h1']),
+ ).toEqual([]);
+ });
+
+ it('removes a canvas and reports blobs no other canvas still uses', async () => {
+ const repository = new CanvasFileRepository(serverDB, userId);
+ await repository.register('cvs_a', [blob('shared'), blob('only-a')]);
+ await repository.register('cvs_b', [blob('shared')]);
+ const model = new CanvasFileModel(serverDB, userId);
+
+ const orphaned = await model.deleteByCanvas('cvs_a');
+
+ expect(orphaned).toEqual([`canvas/${userId}/blobs/only-a`]);
+ expect((await model.listByHashes(['shared', 'only-a'])).map((row) => row.canvasId)).toEqual([
+ 'cvs_b',
+ ]);
+ });
+
+ it.each([
+ [undefined, 'canvas-ws-a'],
+ ['canvas-ws-a', undefined],
+ ['canvas-ws-a', 'canvas-ws-b'],
+ ])('preserves shared blobs when deleting from %s while %s still uses them', async (from, to) => {
+ await serverDB.insert(workspaces).values(
+ ['canvas-ws-a', 'canvas-ws-b'].map((id) => ({
+ id,
+ name: id,
+ primaryOwnerId: userId,
+ slug: id,
+ })),
+ );
+ await new CanvasFileRepository(serverDB, userId, from).register('cvs_a', [
+ blob('shared'),
+ blob('only-a'),
+ ]);
+ await new CanvasFileRepository(serverDB, userId, to).register('cvs_b', [blob('shared')]);
+
+ expect(await new CanvasFileModel(serverDB, userId, from).deleteByCanvas('cvs_a')).toEqual([
+ `canvas/${userId}/blobs/only-a`,
+ ]);
+ const remaining = new CanvasFileModel(serverDB, userId, to);
+ expect(await remaining.listByHashes(['shared'])).toHaveLength(1);
+ expect(await remaining.deleteByCanvas('cvs_b')).toEqual([`canvas/${userId}/blobs/shared`]);
+ });
+});
diff --git a/packages/database/src/repositories/canvasFile/index.ts b/packages/database/src/repositories/canvasFile/index.ts
new file mode 100644
index 00000000000..45c0958d89e
--- /dev/null
+++ b/packages/database/src/repositories/canvasFile/index.ts
@@ -0,0 +1,43 @@
+import { type CanvasBlobRecord, CanvasFileModel } from '../../models/canvasFile';
+import { globalFiles } from '../../schemas';
+import type { LobeChatDatabase } from '../../type';
+
+export class CanvasFileRepository {
+ private db: LobeChatDatabase;
+ private userId: string;
+ private workspaceId?: string;
+
+ constructor(db: LobeChatDatabase, userId: string, workspaceId?: string) {
+ this.db = db;
+ this.userId = userId;
+ this.workspaceId = workspaceId;
+ }
+
+ register = async (canvasId: string, blobs: CanvasBlobRecord[]) => {
+ const model = new CanvasFileModel(this.db, this.userId, this.workspaceId);
+ const existing = new Set(
+ (await model.listByHashes(blobs.map((item) => item.hash)))
+ .filter((row) => row.canvasId === canvasId)
+ .map((row) => row.fileHash),
+ );
+ const fresh = blobs.filter((item) => !existing.has(item.hash));
+ if (fresh.length === 0) return;
+
+ await this.db.transaction(async (tx) => {
+ await tx
+ .insert(globalFiles)
+ .values(
+ fresh.map((item) => ({
+ creator: this.userId,
+ fileType: item.contentType,
+ hashId: item.hash,
+ size: item.size,
+ url: item.url,
+ })),
+ )
+ .onConflictDoNothing();
+
+ await new CanvasFileModel(tx, this.userId, this.workspaceId).insertFiles(canvasId, fresh);
+ });
+ };
+}
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index b70de9622bc..a5cae7dbd56 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -3561,6 +3561,8 @@ export default {
'workingPanel.works.emptyVersions': 'No versions yet',
'workingPanel.works.error': 'Failed to load works',
'workingPanel.works.documentLoadError': 'Failed to load document',
+ 'workingPanel.works.canvasPublished': 'Published',
+ 'workingPanel.works.canvasUntitled': 'Untitled canvas',
'workingPanel.works.changeType.created': 'Created',
'workingPanel.works.changeType.updated': 'Updated',
'workingPanel.works.documentDeleted': 'This document has been deleted',
diff --git a/packages/locales/src/default/file.ts b/packages/locales/src/default/file.ts
index 7e923f32238..3c0a947f003 100644
--- a/packages/locales/src/default/file.ts
+++ b/packages/locales/src/default/file.ts
@@ -451,6 +451,7 @@ export default {
'work.loadErrorTitle': 'Couldn’t load works',
'work.loadMoreError': 'Failed to load more works.',
'work.retry': 'Retry',
+ 'work.type.canvas': 'Canvas',
'work.type.document': 'Document',
'work.type.file': 'File',
'work.type.githubIssue': 'GitHub Issue',
diff --git a/packages/locales/src/default/plugin.ts b/packages/locales/src/default/plugin.ts
index 1337b5fe3f2..516a204d80b 100644
--- a/packages/locales/src/default/plugin.ts
+++ b/packages/locales/src/default/plugin.ts
@@ -550,6 +550,12 @@ export default {
'builtins.lobe-skills.apiName.activateProjectSkill': 'Activate Project Skill',
'builtins.lobe-skills.apiName.searchSkill': 'Search Skills',
'builtins.lobe-skills.title': 'Skills',
+ 'builtins.lobe-canvas.apiName.createCanvas': 'Create canvas',
+ 'builtins.lobe-canvas.apiName.listCanvases': 'List canvases',
+ 'builtins.lobe-canvas.apiName.readCanvas': 'Read canvas',
+ 'builtins.lobe-canvas.apiName.readCanvasGuide': 'Read canvas guide',
+ 'builtins.lobe-canvas.apiName.updateCanvas': 'Update canvas',
+ 'builtins.lobe-canvas.title': 'Canvas',
'builtins.lobe-dashboard.apiName.addWidgetToDashboard': 'Add widget to dashboard',
'builtins.lobe-dashboard.apiName.createWidgetDraft': 'Create widget draft',
'builtins.lobe-dashboard.apiName.dryRunWidget': 'Dry-run widget',
diff --git a/packages/locales/src/default/portal.ts b/packages/locales/src/default/portal.ts
index 3e790ae0c57..c8bbb15e541 100644
--- a/packages/locales/src/default/portal.ts
+++ b/packages/locales/src/default/portal.ts
@@ -38,6 +38,23 @@ export default {
'artifacts.svg.copySuccess': 'Image copied successfully',
'artifacts.svg.download.png': 'Download as PNG',
'artifacts.svg.download.svg': 'Download as SVG',
+ 'canvas.frameTitle': 'Canvas preview',
+ 'canvas.generating': 'Generating v{{version}}…',
+ 'canvas.menu.openInTab': 'Open in new tab',
+ 'canvas.menu.versionItem': 'v{{version}} · {{date}}',
+ 'canvas.menu.versions': 'Version history',
+ 'canvas.menu.openPublic': 'Open public link',
+ 'canvas.menu.publish': 'Publish v{{version}} to a public link',
+ 'canvas.menu.publishing': 'Publishing…',
+ 'canvas.menu.updatePublic': 'Update public link to v{{version}}',
+ 'canvas.notFound': 'This canvas no longer exists or is not available to you.',
+ 'canvas.publish.failed': 'Couldn’t publish. Try again.',
+ 'canvas.publish.note': 'Newer versions stay private until you update the public link.',
+ 'canvas.publish.success': 'Published v{{version}}',
+ 'canvas.runtimeErrors': 'This canvas reported errors ({{count}})',
+ 'canvas.runtimeErrorsHint':
+ 'Some components could not render. Ask the agent to fix the canvas, or expand to see details.',
+ 'canvas.title': 'Canvas',
'document.saveConflict': 'This document was updated elsewhere. Refreshing to the latest version.',
'document.todos.allCompleted': 'All tasks completed',
'document.todos.title': 'Tasks',
diff --git a/packages/types/src/files/index.ts b/packages/types/src/files/index.ts
index 1287c3ca6a6..4d80bc427b0 100644
--- a/packages/types/src/files/index.ts
+++ b/packages/types/src/files/index.ts
@@ -23,6 +23,7 @@ export enum FileSource {
Acceptance = 'acceptance',
/** Original upload owned by an agent's document tree rather than the resource library. */
AgentDocument = 'agent-document',
+ Canvas = 'canvas',
ImageGeneration = 'image_generation',
PageEditor = 'page-editor',
VideoGeneration = 'video_generation',
@@ -43,6 +44,7 @@ export enum FileSource {
export const LIBRARY_HIDDEN_FILE_SOURCES: FileSource[] = [
FileSource.Acceptance,
FileSource.AgentDocument,
+ FileSource.Canvas,
];
/** Sources a generation model wrote, as opposed to anything a human put there. */
diff --git a/packages/types/src/work.ts b/packages/types/src/work.ts
index 585584965fc..a3817ac1180 100644
--- a/packages/types/src/work.ts
+++ b/packages/types/src/work.ts
@@ -6,7 +6,7 @@ import type { TaskStatus } from './task';
* version per acceptance result. It is read through the goal graph, not the
* generic Work lists.
*/
-export type WorkType = 'document' | 'external' | 'file' | 'goal_report' | 'task';
+export type WorkType = 'canvas' | 'document' | 'external' | 'file' | 'goal_report' | 'task';
/** Work types the generic Work lists return; a `goal_report` is read through its goal. */
export type ListedWorkType = Exclude<WorkType, 'goal_report'>;
export type LinearWorkResourceType = 'linear_document' | 'linear_issue';
@@ -14,7 +14,7 @@ export type GithubWorkResourceType = 'github_issue' | 'github_pull_request';
/** Every resource type backed by the unified `external` Work type. */
export type ExternalWorkResourceType = GithubWorkResourceType | LinearWorkResourceType;
export type WorkResourceType =
- 'document' | ExternalWorkResourceType | 'file' | 'goal_report' | 'task';
+ 'canvas' | 'document' | ExternalWorkResourceType | 'file' | 'goal_report' | 'task';
export type WorkVisibility = 'private' | 'public';
/**
* How a version changed the Work. Not derivable from `version === 1`: updating
@@ -45,8 +45,14 @@ export interface AgentShareWorkProvenance {
visitorUserId: string;
}
+export interface CanvasWorkPublishMetadata {
+ deploymentId: string;
+ publishedVersion: number;
+}
+
export interface WorkMetadata {
agentShare?: AgentShareWorkProvenance;
+ canvasPublish?: CanvasWorkPublishMetadata;
}
/**
@@ -70,8 +76,29 @@ export const agentShareWorkAccessScope = (
visitorUserId: provenance.visitorUserId,
});
+export interface CanvasPublishFile {
+ content: string;
+ contentType: string;
+ encoding: 'base64' | 'utf8';
+ path: string;
+}
+
+export interface CanvasPublishBundle {
+ files: CanvasPublishFile[];
+ html: string;
+}
+
+export interface CanvasWorkVersionMetadata {
+ entry: string;
+ fileCount: number;
+ manifestKey: string;
+ runtimeMajor: number;
+ totalSize: number;
+}
+
export interface WorkVersionMetadata {
agentDocumentId?: string;
+ canvas?: CanvasWorkVersionMetadata;
/**
* `file` Work — the edited file's identity in the file store, when the entity
* file was persisted. `filePath` is always present for a file Work; the
@@ -249,8 +276,17 @@ export interface FileWorkListItem extends WorkListBaseItem {
type: 'file';
}
+export interface CanvasWorkListItem extends WorkListBaseItem {
+ resourceType: 'canvas';
+ type: 'canvas';
+}
+
export type WorkListItem =
- DocumentWorkListItem | ExternalWorkListItem | FileWorkListItem | TaskWorkListItem;
+ | CanvasWorkListItem
+ | DocumentWorkListItem
+ | ExternalWorkListItem
+ | FileWorkListItem
+ | TaskWorkListItem;
export interface TaskWorkVersionEventItem extends TaskWorkListItem {
version: WorkVersionPreview;
@@ -268,7 +304,12 @@ export interface FileWorkVersionEventItem extends FileWorkListItem {
version: WorkVersionPreview;
}
+export interface CanvasWorkVersionEventItem extends CanvasWorkListItem {
+ version: WorkVersionPreview;
+}
+
export type WorkVersionEventItem =
+ | CanvasWorkVersionEventItem
| DocumentWorkVersionEventItem
| ExternalWorkVersionEventItem
| FileWorkVersionEventItem
@@ -302,8 +343,18 @@ export interface FileWorkSummaryItem extends FileWorkListItem {
version: Pick<WorkVersionItem, 'createdAt' | 'id' | 'version'> | null;
}
+export interface CanvasWorkSummaryItem extends CanvasWorkListItem {
+ event: WorkSummaryVersionPreview;
+ totalCost: number | null;
+ version: Pick<WorkVersionItem, 'createdAt' | 'id' | 'version'> | null;
+}
+
export type WorkSummaryItem =
- DocumentWorkSummaryItem | ExternalWorkSummaryItem | FileWorkSummaryItem | TaskWorkSummaryItem;
+ | CanvasWorkSummaryItem
+ | DocumentWorkSummaryItem
+ | ExternalWorkSummaryItem
+ | FileWorkSummaryItem
+ | TaskWorkSummaryItem;
export type WorkSummaryMap = Record<string, WorkSummaryItem[]>;
export interface RegisterDocumentWorkParams {
@@ -362,6 +413,24 @@ export interface RegisterFileWorkParams {
visibility?: WorkVisibility;
}
+export interface RegisterCanvasWorkParams {
+ agentId?: string | null;
+ canvasId: string;
+ cumulativeCost?: number | null;
+ cumulativeUsage?: WorkVersionCumulativeUsage | null;
+ description?: string | null;
+ messageId?: string | null;
+ metadata: CanvasWorkVersionMetadata;
+ rootOperationId?: string | null;
+ threadId?: string | null;
+ title: string;
+ toolCallId?: string | null;
+ toolIdentifier: string;
+ toolName: string;
+ topicId?: string | null;
+ visibility?: WorkVisibility;
+}
+
export interface DeleteDocumentWorkParams {
agentDocumentId?: string | null;
agentId?: string | null;
@@ -542,4 +611,15 @@ export type WorkRegistrationIntent =
action: 'delete';
document: { agentDocumentId?: string | null; agentId?: string | null; documentId: string };
type: 'document';
+ }
+ | {
+ action: 'register';
+ canvas: {
+ canvasId: string;
+ description?: string | null;
+ metadata: CanvasWorkVersionMetadata;
+ title: string;
+ toolName: string;
+ };
+ type: 'canvas';
};
diff --git a/plugins/vite/canvasRuntime.test.ts b/plugins/vite/canvasRuntime.test.ts
new file mode 100644
index 00000000000..3db3414de7f
--- /dev/null
+++ b/plugins/vite/canvasRuntime.test.ts
@@ -0,0 +1,113 @@
+// @vitest-environment node
+import { mkdir, mkdtemp, readdir, readFile, rm, writeFile } from 'node:fs/promises';
+import { tmpdir } from 'node:os';
+import path from 'node:path';
+
+import type { CanvasRuntimeManifest } from '@lobechat/canvas/runtime';
+import { build, createServer } from 'vite';
+import { expect, it } from 'vitest';
+
+import { canvasRuntime } from './canvasRuntime';
+
+it('reuses App dependencies for injected runtime and excludes the publication bundle', async () => {
+ const root = await mkdtemp(path.join(tmpdir(), 'canvas-chunks-'));
+ try {
+ await mkdir(path.join(root, 'public/canvas-runtime/v1'), { recursive: true });
+ await writeFile(path.join(root, 'public/canvas-runtime/v1/legacy.js'), 'publication-only');
+ await writeFile(path.join(root, 'shared.js'), 'export const shared = "unique-shared-ui-code";');
+ await writeFile(path.join(root, 'canvas.css'), 'body {color: rgb(1, 2, 3)}');
+ await writeFile(
+ path.join(root, 'index.html'),
+ '<script type="module" src="/main.js"></script>',
+ );
+ await writeFile(
+ path.join(root, 'main.js'),
+ 'import url from "virtual:canvas-runtime"; import {shared} from "./shared.js"; globalThis.resources = {url,shared};',
+ );
+ await build({
+ root,
+ base: '/_spa/',
+ configFile: false,
+ logLevel: 'silent',
+ plugins: [
+ {
+ name: 'canvas-fixture',
+ load(id) {
+ if (id.endsWith('/canvas-runtime/src/index.tsx'))
+ return 'import {shared} from "/shared.js"; import "/canvas.css"; globalThis.canvasValue = shared;';
+ if (/canvas-runtime\/src\/addons\/(?:highlight|mermaid)\.ts$/.test(id))
+ return 'import {shared} from "/shared.js"; globalThis.addonValue = shared;';
+ },
+ },
+ canvasRuntime(),
+ ],
+ build: {
+ minify: false,
+ rolldownOptions: {
+ input: path.join(root, 'main.js'),
+ preserveEntrySignatures: 'allow-extension',
+ },
+ },
+ });
+ const assets = await readdir(path.join(root, 'dist/assets'));
+ const manifestFile = assets.find((file) => file.endsWith('.js.json'))!;
+ expect(manifestFile).toBeTruthy();
+ const manifest: CanvasRuntimeManifest = JSON.parse(
+ await readFile(path.join(root, 'dist/assets', manifestFile), 'utf8'),
+ );
+ const code = await Promise.all(
+ assets
+ .filter((file) => file.endsWith('.js'))
+ .map((file) => readFile(path.join(root, 'dist/assets', file), 'utf8')),
+ );
+ expect(code.join('\n').match(/unique-shared-ui-code/g)).toHaveLength(1);
+ expect(await readdir(path.join(root, 'dist'))).not.toContain('canvas-runtime');
+ expect(await readFile(path.join(root, 'public/canvas-runtime/v1/legacy.js'), 'utf8')).toBe(
+ 'publication-only',
+ );
+ expect(manifest.styles).toHaveLength(1);
+ for (const module of manifest.modules) {
+ const source = await readFile(path.join(root, 'dist', module.id), 'utf8');
+ for (const reference of module.imports) {
+ expect(JSON.parse(source.slice(reference.start, reference.end))).toContain('.js');
+ expect(manifest.modules.some((item) => item.id === reference.target)).toBe(true);
+ }
+ }
+ expect(manifest.modules.some((module) => module.id === manifest.entries.runtime)).toBe(true);
+ } finally {
+ await rm(root, { force: true, recursive: true });
+ }
+});
+
+it('serves an in-memory development runtime without writing a publication build', async () => {
+ const root = await mkdtemp(path.join(tmpdir(), 'canvas-dev-'));
+ const server = await createServer({
+ root,
+ configFile: false,
+ logLevel: 'silent',
+ optimizeDeps: { noDiscovery: true, entries: [] },
+ plugins: [canvasRuntime()],
+ server: { host: '127.0.0.1', port: 0 },
+ });
+ try {
+ await server.listen();
+ const address = server.httpServer!.address();
+ if (!address || typeof address === 'string') throw new Error('Dev server has no port');
+ const response = await fetch(`http://127.0.0.1:${address.port}/@lobe-canvas/runtime.json`);
+ expect(response.status).toBe(200);
+ const { bundle } = await response.json();
+ expect(bundle.modules).toHaveLength(3);
+ expect(bundle.styles.length).toBeGreaterThan(0);
+ for (const entry of Object.values(bundle.entries))
+ expect(
+ bundle.modules.some(
+ (module: { code: string; id: string }) =>
+ module.id === entry && module.code.length > 1000,
+ ),
+ ).toBe(true);
+ expect(await readdir(root)).not.toContain('dist');
+ } finally {
+ await server.close();
+ await rm(root, { force: true, recursive: true });
+ }
+}, 30_000);
diff --git a/plugins/vite/canvasRuntime.ts b/plugins/vite/canvasRuntime.ts
new file mode 100644
index 00000000000..601667e789d
--- /dev/null
+++ b/plugins/vite/canvasRuntime.ts
@@ -0,0 +1,197 @@
+import { rm } from 'node:fs/promises';
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+import type {
+ CanvasRuntimeBundle,
+ CanvasRuntimeManifest,
+ CanvasRuntimeModule,
+} from '@lobechat/canvas/runtime';
+import { build, type ESTree, parseAst, type Plugin, type ResolvedConfig, Visitor } from 'vite';
+
+const virtualId = 'virtual:canvas-runtime';
+const resolvedId = `\0${virtualId}`;
+const runtimeRoot = fileURLToPath(new URL('../../packages/canvas-runtime/', import.meta.url));
+
+export const canvasRuntimeEntries = {
+ runtime: path.join(runtimeRoot, 'src/index.tsx'),
+ highlight: path.join(runtimeRoot, 'src/addons/highlight.ts'),
+ mermaid: path.join(runtimeRoot, 'src/addons/mermaid.ts'),
+};
+
+const describeModule = (code: string, id: string): Omit<CanvasRuntimeModule, 'code' | 'url'> => {
+ const imports: CanvasRuntimeModule['imports'] = [];
+ const meta: NonNullable<CanvasRuntimeModule['meta']> = [];
+ const reference = (source: ESTree.Node) => {
+ if (source.type !== 'Literal' || typeof source.value !== 'string') return;
+ imports.push({
+ start: source.start,
+ end: source.end,
+ target: path.posix.normalize(
+ path.posix.join(path.posix.dirname(id), source.value.split('?')[0]),
+ ),
+ });
+ };
+ new Visitor({
+ ImportDeclaration: (node) => reference(node.source),
+ ExportAllDeclaration: (node) => reference(node.source),
+ ExportNamedDeclaration: (node) => {
+ if (node.source) reference(node.source);
+ },
+ ImportExpression: (node) => reference(node.source),
+ MemberExpression(node) {
+ if (
+ node.object.type === 'MetaProperty' &&
+ node.property.type === 'Identifier' &&
+ node.property.name === 'url'
+ )
+ meta.push({ start: node.start, end: node.end });
+ },
+ }).visit(parseAst(code));
+ return { id, imports, meta };
+};
+
+export function canvasRuntime(): Plugin {
+ let config: ResolvedConfig;
+ let references: Record<keyof typeof canvasRuntimeEntries, string> | undefined;
+ let development: Promise<CanvasRuntimeBundle> | undefined;
+ return {
+ name: 'lobe-canvas-runtime',
+ enforce: 'post',
+ configResolved(resolved) {
+ config = resolved;
+ },
+ configureServer(server) {
+ const compile = async (): Promise<CanvasRuntimeBundle> => {
+ const modules: CanvasRuntimeModule[] = [];
+ const styles: string[] = [];
+ const entries = { runtime: '', highlight: '', mermaid: '' };
+ for (const name of ['runtime', 'highlight', 'mermaid'] as const) {
+ const result = await build({
+ root: runtimeRoot,
+ configFile: path.join(runtimeRoot, 'vite.config.ts'),
+ mode: name === 'runtime' ? 'production' : name,
+ logLevel: 'error',
+ build: { write: false, emptyOutDir: false },
+ });
+ const outputs = Array.isArray(result) ? result : [result];
+ const files = outputs.flatMap((output) => {
+ if (!('output' in output)) throw new Error('Canvas dev build did not return a bundle');
+ return output.output;
+ });
+ for (const file of files) {
+ if (file.type === 'chunk') {
+ entries[name] = file.fileName;
+ modules.push({
+ id: file.fileName,
+ code: file.code,
+ imports: [],
+ url: new URL(file.fileName, 'http://localhost/').href,
+ });
+ } else if (file.fileName.endsWith('.css')) {
+ styles.push(
+ typeof file.source === 'string'
+ ? file.source
+ : new TextDecoder().decode(file.source),
+ );
+ }
+ }
+ }
+ return { entries, modules, styles };
+ };
+ server.middlewares.use('/@lobe-canvas/runtime.json', async (_request, response) => {
+ try {
+ development ??= compile().catch((error) => {
+ development = undefined;
+ throw error;
+ });
+ response.setHeader('Content-Type', 'application/json');
+ response.setHeader('Cache-Control', 'no-store');
+ response.end(JSON.stringify({ bundle: await development }));
+ } catch (error) {
+ server.config.logger.error(String(error));
+ response.statusCode = 500;
+ response.end('Canvas runtime compilation failed');
+ }
+ });
+ server.watcher.on('change', (file) => {
+ if (file.startsWith(runtimeRoot) || file.includes('/packages/canvas/src/')) {
+ development = undefined;
+ server.ws.send({ type: 'full-reload' });
+ }
+ });
+ },
+ resolveId(id) {
+ if (id === virtualId) return resolvedId;
+ },
+ load(id) {
+ if (id !== resolvedId) return;
+ if (config.command === 'serve')
+ return 'const endpoint = "/@lobe-canvas/runtime.json"; export default new URL(endpoint, import.meta.url).href';
+ references ??= Object.fromEntries(
+ Object.entries(canvasRuntimeEntries).map(([name, entry]) => [
+ name,
+ this.emitFile({
+ type: 'chunk',
+ id: entry,
+ name: `canvas-${name}`,
+ preserveSignature: 'strict',
+ }),
+ ]),
+ ) as Record<keyof typeof canvasRuntimeEntries, string>;
+ return `export default import.meta.ROLLUP_FILE_URL_${references!.runtime} + ".json";`;
+ },
+ generateBundle: {
+ order: 'post',
+ handler(_options, bundle) {
+ if (!references) return;
+ const entries = Object.fromEntries(
+ Object.entries(references).map(([name, reference]) => [
+ name,
+ this.getFileName(reference),
+ ]),
+ ) as CanvasRuntimeManifest['entries'];
+ const modules = new Map<string, CanvasRuntimeManifest['modules'][number]>();
+ const styles = new Set<string>();
+ const entryStyles: CanvasRuntimeManifest['entryStyles'] = {};
+ const visit = (id: string) => {
+ if (modules.has(id)) return;
+ const chunk = bundle[id];
+ if (!chunk || chunk.type !== 'chunk')
+ this.error(`Canvas module is not in the App bundle: ${id}`);
+ const module = describeModule(chunk.code, id);
+ modules.set(id, module);
+ for (const dependency of [...chunk.imports, ...chunk.dynamicImports]) visit(dependency);
+ for (const css of chunk.viteMetadata?.importedCss ?? []) styles.add(css);
+ };
+ for (const [name, entry] of Object.entries(entries)) {
+ styles.clear();
+ modules.clear();
+ visit(entry);
+ entryStyles[name as keyof typeof entries] = [...styles];
+ }
+ modules.clear();
+ styles.clear();
+ for (const entry of Object.values(entries)) visit(entry);
+ this.emitFile({
+ type: 'asset',
+ fileName: `${entries.runtime}.json`,
+ source: JSON.stringify({
+ base: config.base,
+ entries,
+ entryStyles,
+ modules: [...modules.values()],
+ styles: [...styles],
+ } satisfies CanvasRuntimeManifest),
+ });
+ },
+ },
+ async writeBundle() {
+ // The standalone IIFE belongs to published pages, never to an App renderer.
+ await rm(path.resolve(config.root, config.build.outDir, 'canvas-runtime'), {
+ force: true,
+ recursive: true,
+ });
+ },
+ };
+}
diff --git a/plugins/vite/sharedRendererConfig.test.ts b/plugins/vite/sharedRendererConfig.test.ts
index a7c450a7576..409ca17062a 100644
--- a/plugins/vite/sharedRendererConfig.test.ts
+++ b/plugins/vite/sharedRendererConfig.test.ts
@@ -1,3 +1,4 @@
+// @vitest-environment node
import { describe, expect, it } from 'vitest';
import {
diff --git a/plugins/vite/sharedRendererConfig.ts b/plugins/vite/sharedRendererConfig.ts
index 0d19ee033fe..86badc6b627 100644
--- a/plugins/vite/sharedRendererConfig.ts
+++ b/plugins/vite/sharedRendererConfig.ts
@@ -2,6 +2,7 @@ import react from '@vitejs/plugin-react';
import { codeInspectorPlugin } from 'code-inspector-plugin';
import type { ModulePreloadOptions, Plugin } from 'vite';
+import { canvasRuntime } from './canvasRuntime';
import { viteCompletionSounds } from './completionSounds';
import { lobeIconImports } from './lobeIconImports';
import { lobeUiImports } from './lobeUiImports';
@@ -490,6 +491,7 @@ interface SharedRendererOptions {
export function sharedRendererPlugins(options: SharedRendererOptions) {
return [
+ canvasRuntime(),
viteCompletionSounds(),
viteMarkdownImport(),
viteNodeModuleStub(),
diff --git a/src/app/(backend)/canvas-preview/[token]/[[...path]]/route.ts b/src/app/(backend)/canvas-preview/[token]/[[...path]]/route.ts
new file mode 100644
index 00000000000..b2f66f4adc0
--- /dev/null
+++ b/src/app/(backend)/canvas-preview/[token]/[[...path]]/route.ts
@@ -0,0 +1,24 @@
+import { getServerDB } from '@/database/server';
+import { createCanvasStorageService } from '@/server/services/canvas';
+import { resolveCanvasRuntimeUrl } from '@/server/services/canvas/runtimeUrl';
+import { serveCanvasFile } from '@/server/services/canvas/serve';
+
+type Params = Promise<{ path?: string[]; token: string }>;
+
+export const GET = async (_req: Request, segmentData: { params: Params }) => {
+ const { path, token } = await segmentData.params;
+ const db = await getServerDB();
+
+ try {
+ return await serveCanvasFile({
+ createStorage: (payload) =>
+ createCanvasStorageService(db, payload.userId, payload.workspaceId),
+ path: path?.join('/') ?? '',
+ runtimeUrl: resolveCanvasRuntimeUrl(),
+ token,
+ });
+ } catch (error) {
+ console.error('Canvas preview error:', error);
+ return new Response('Internal server error', { status: 500 });
+ }
+};
diff --git a/src/components/HtmlPreview/HtmlDocumentFrame.tsx b/src/components/HtmlPreview/HtmlDocumentFrame.tsx
index 6e9761f7b11..7aae636b912 100644
--- a/src/components/HtmlPreview/HtmlDocumentFrame.tsx
+++ b/src/components/HtmlPreview/HtmlDocumentFrame.tsx
@@ -65,4 +65,5 @@ const HtmlDocumentFrame = ({ content, title }: HtmlDocumentFrameProps) => {
);
};
+/** Superseded by Canvas (`lobe-canvas`); kept so existing conversations keep rendering. */
export default HtmlDocumentFrame;
diff --git a/src/components/HtmlPreview/InlinePreview.tsx b/src/components/HtmlPreview/InlinePreview.tsx
index eb1535ab0ac..a43cf40eed8 100644
--- a/src/components/HtmlPreview/InlinePreview.tsx
+++ b/src/components/HtmlPreview/InlinePreview.tsx
@@ -46,4 +46,5 @@ const InlineHtmlPreview = memo<InlineHtmlPreviewProps>(
InlineHtmlPreview.displayName = 'InlineHtmlPreview';
+/** Superseded by Canvas (`lobe-canvas`); kept so existing conversations keep rendering. */
export default InlineHtmlPreview;
diff --git a/src/components/HtmlPreview/PreviewDrawer.tsx b/src/components/HtmlPreview/PreviewDrawer.tsx
index ac5dde5254b..c4966b2a33c 100644
--- a/src/components/HtmlPreview/PreviewDrawer.tsx
+++ b/src/components/HtmlPreview/PreviewDrawer.tsx
@@ -126,4 +126,5 @@ const HtmlPreviewDrawer = memo<HtmlPreviewDrawerProps>(({ content, open, onClose
HtmlPreviewDrawer.displayName = 'HtmlPreviewDrawer';
+/** Superseded by Canvas (`lobe-canvas`); kept so existing conversations keep rendering. */
export default HtmlPreviewDrawer;
diff --git a/src/components/PublishConfirmModal/index.tsx b/src/components/PublishConfirmModal/index.tsx
new file mode 100644
index 00000000000..b7ef8518eed
--- /dev/null
+++ b/src/components/PublishConfirmModal/index.tsx
@@ -0,0 +1,69 @@
+import { Button, createModal, Flexbox, ScrollArea, Text, useModalContext } from '@lobehub/ui';
+import { t } from 'i18next';
+import { type ReactNode } from 'react';
+import { useTranslation } from 'react-i18next';
+
+const CONFIRM_BODY_MAX_HEIGHT = 'min(52vh, 360px)';
+
+const PublishConfirmContent = ({ details, note }: { details?: ReactNode; note?: ReactNode }) => {
+ const { t } = useTranslation('chat');
+
+ return (
+ <ScrollArea
+ disableContentFit
+ scrollFade
+ style={{ maxHeight: CONFIRM_BODY_MAX_HEIGHT, overflow: 'hidden' }}
+ viewportProps={{ style: { height: 'auto', maxHeight: CONFIRM_BODY_MAX_HEIGHT } }}
+ >
+ <Flexbox gap={8} style={{ paddingBlock: 12, paddingInline: 16 }}>
+ <Text>{t('workingPanel.localFile.publish.privacy')}</Text>
+ {details}
+ {note && <Text type={'secondary'}>{note}</Text>}
+ </Flexbox>
+ </ScrollArea>
+ );
+};
+
+const PublishConfirmFooter = ({ okText, onOk }: { okText: string; onOk: () => void }) => {
+ const { t } = useTranslation('common');
+ const { close } = useModalContext();
+
+ return (
+ <Flexbox
+ horizontal
+ gap={8}
+ justify={'flex-end'}
+ style={{ paddingBlock: 12, paddingInline: 16 }}
+ >
+ <Button onClick={() => close()}>{t('cancel')}</Button>
+ <Button
+ type={'primary'}
+ onClick={() => {
+ close();
+ onOk();
+ }}
+ >
+ {okText}
+ </Button>
+ </Flexbox>
+ );
+};
+
+export interface PublishConfirmOptions {
+ details?: ReactNode;
+ note?: ReactNode;
+ okText: string;
+ onOk: () => void;
+}
+
+export const openPublishConfirm = ({ details, note, okText, onOk }: PublishConfirmOptions) => {
+ createModal({
+ content: <PublishConfirmContent details={details} note={note} />,
+ footer: <PublishConfirmFooter okText={okText} onOk={onOk} />,
+ styles: {
+ content: { minHeight: 0, overflow: 'hidden', padding: 0 },
+ },
+ title: t('workingPanel.localFile.publish.confirmTitle', { ns: 'chat' }),
+ width: 420,
+ });
+};
diff --git a/src/features/Conversation/Messages/useChatMarkdown.tsx b/src/features/Conversation/Messages/useChatMarkdown.tsx
index 478cc10fe72..100893083a0 100644
--- a/src/features/Conversation/Messages/useChatMarkdown.tsx
+++ b/src/features/Conversation/Messages/useChatMarkdown.tsx
@@ -67,6 +67,7 @@ export const useChatMarkdown = ({
},
components,
enableCustomFootnotes: true,
+ // @deprecated Inline HTML preview and streaming are superseded by Canvas; kept for existing messages.
enableHtmlPreview: true,
enableStream,
rehypePlugins,
diff --git a/src/features/Conversation/WorkingSidebar/Canvas/CanvasFrame.tsx b/src/features/Conversation/WorkingSidebar/Canvas/CanvasFrame.tsx
new file mode 100644
index 00000000000..cbbf3b2e498
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/Canvas/CanvasFrame.tsx
@@ -0,0 +1,122 @@
+import { Alert, useThemeMode } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useUserStore } from '@/store/user';
+import { userGeneralSettingsSelectors } from '@/store/user/selectors';
+
+import { attachCanvasRuntime } from './runtime/host';
+
+const styles = stylex.create({
+ details: {
+ color: cssVar.colorTextSecondary,
+ fontFamily: cssVar.fontFamilyCode,
+ fontSize: 12,
+ margin: 0,
+ whiteSpace: 'pre-wrap',
+ wordBreak: 'break-word',
+ },
+ frame: {
+ backgroundColor: 'transparent',
+ borderWidth: 0,
+ flex: '1',
+ minHeight: 0,
+ width: '100%',
+ },
+});
+
+interface CanvasError {
+ component?: string;
+ message: string;
+}
+
+const MAX_ERRORS = 10;
+
+const CanvasFrame = memo<{ src: string }>(({ src }) => {
+ const { t } = useTranslation('portal');
+ const ref = useRef<HTMLIFrameElement>(null);
+ const { isDarkMode } = useThemeMode();
+ const primaryColor = useUserStore(userGeneralSettingsSelectors.primaryColor);
+ const neutralColor = useUserStore(userGeneralSettingsSelectors.neutralColor);
+ const [errors, setErrors] = useState<CanvasError[]>([]);
+
+ const theme = useMemo(
+ () => ({ appearance: isDarkMode ? 'dark' : 'light', neutralColor, primaryColor }),
+ [isDarkMode, neutralColor, primaryColor],
+ );
+
+ const postTheme = useCallback(() => {
+ ref.current?.contentWindow?.postMessage(
+ { source: 'lobe-canvas-host', theme, type: 'theme' },
+ '*',
+ );
+ }, [theme]);
+
+ useEffect(postTheme, [postTheme]);
+
+ useEffect(() => setErrors([]), [src]);
+
+ useEffect(() => {
+ const frame = ref.current;
+ if (!frame) return;
+ return attachCanvasRuntime(frame, (error) => {
+ console.error('[lobe-canvas]', error);
+ setErrors((current) => [...current, { message: String(error) }].slice(-MAX_ERRORS));
+ });
+ }, [src]);
+
+ useEffect(() => {
+ const onMessage = (event: MessageEvent) => {
+ if (event.source !== ref.current?.contentWindow || event.data?.source !== 'lobe-canvas')
+ return;
+ if (event.data.type === 'ready') postTheme();
+ if (event.data.type === 'error') {
+ setErrors((current) =>
+ current.length >= MAX_ERRORS
+ ? current
+ : [
+ ...current,
+ { component: event.data.component, message: String(event.data.message) },
+ ],
+ );
+ }
+ };
+ window.addEventListener('message', onMessage);
+ return () => window.removeEventListener('message', onMessage);
+ }, [postTheme]);
+
+ return (
+ <>
+ {errors.length > 0 && (
+ <Alert
+ description={t('canvas.runtimeErrorsHint')}
+ title={t('canvas.runtimeErrors', { count: errors.length })}
+ type={'warning'}
+ extra={
+ <pre {...stylex.props(styles.details)}>
+ {errors
+ .map((error) =>
+ error.component ? `<${error.component}> ${error.message}` : error.message,
+ )
+ .join('\n')}
+ </pre>
+ }
+ />
+ )}
+ <iframe
+ {...stylex.props(styles.frame)}
+ ref={ref}
+ sandbox="allow-scripts allow-popups allow-forms allow-downloads"
+ src={src}
+ title={t('canvas.frameTitle')}
+ onLoad={postTheme}
+ />
+ </>
+ );
+});
+
+CanvasFrame.displayName = 'CanvasFrame';
+
+export default CanvasFrame;
diff --git a/src/features/Conversation/WorkingSidebar/Canvas/CanvasPane.tsx b/src/features/Conversation/WorkingSidebar/Canvas/CanvasPane.tsx
new file mode 100644
index 00000000000..9035ab3f82b
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/Canvas/CanvasPane.tsx
@@ -0,0 +1,123 @@
+import { Empty, Flexbox, Skeleton, Tag, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { Loader2Icon, PanelsTopLeftIcon } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import PortalMoreMenu from '@/features/Portal/components/PortalMoreMenu';
+
+import CanvasFrame from './CanvasFrame';
+import { useCanvasMoreMenu } from './useCanvasMoreMenu';
+import { useAwaitingCanvasSave, useCanvasTabView, useCanvasVersion } from './useCanvasVersion';
+import { usePendingCanvasUpdate } from './usePendingCanvasUpdate';
+
+const spin = stylex.keyframes({
+ to: { transform: 'rotate(360deg)' },
+});
+
+const styles = stylex.create({
+ body: {
+ minHeight: 0,
+ position: 'relative',
+ },
+ content: {
+ minHeight: 0,
+ },
+ dimmed: {
+ filter: 'grayscale(1)',
+ opacity: 0.45,
+ pointerEvents: 'none',
+ transition: 'opacity 0.2s ease',
+ },
+ pill: {
+ backgroundColor: cssVar.colorBgElevated,
+ borderColor: cssVar.colorBorder,
+ borderRadius: 999,
+ borderStyle: 'solid',
+ borderWidth: 1,
+ boxShadow: cssVar.boxShadowSecondary,
+ insetBlockStart: 52,
+ insetInlineStart: '50%',
+ paddingBlock: 6,
+ paddingInline: 12,
+ position: 'absolute',
+ transform: 'translateX(-50%)',
+ zIndex: 1,
+ },
+ spin: {
+ animationDuration: '1s',
+ animationIterationCount: 'infinite',
+ animationName: spin,
+ animationTimingFunction: 'linear',
+ },
+ toolbar: {
+ borderBlockEndColor: cssVar.colorBorderSecondary,
+ borderBlockEndStyle: 'solid',
+ borderBlockEndWidth: 1,
+ minWidth: 0,
+ },
+});
+
+interface CanvasPaneProps {
+ canvasId: string;
+}
+
+const CanvasPane = memo<CanvasPaneProps>(({ canvasId }) => {
+ const { t } = useTranslation('portal');
+ const view = useCanvasTabView(canvasId);
+ const { data, isLoading, mutate } = useCanvasVersion(view);
+ const moreMenu = useCanvasMoreMenu(view, data, () => mutate());
+ const pending = usePendingCanvasUpdate(canvasId);
+ const awaitingSave = useAwaitingCanvasSave(view, data?.metadata.manifestKey);
+ const showPending =
+ (pending || awaitingSave) && (!view.version || view.version === data?.latestVersion);
+
+ if (isLoading && !data) {
+ return (
+ <Flexbox gap={16} padding={24}>
+ <Skeleton height={24} width={'40%'} />
+ <Skeleton height={120} width={'100%'} />
+ <Skeleton height={16} width={'80%'} />
+ <Skeleton height={16} width={'60%'} />
+ </Flexbox>
+ );
+ }
+
+ if (!data) {
+ return <Empty description={t('canvas.notFound')} icon={PanelsTopLeftIcon} />;
+ }
+
+ return (
+ <Flexbox flex={1} {...stylex.props(styles.body)}>
+ <Flexbox
+ horizontal
+ align={'center'}
+ flex={'none'}
+ gap={8}
+ height={36}
+ paddingInline={12}
+ {...stylex.props(styles.toolbar)}
+ >
+ <Tag size={'small'}>{`v${data.version}`}</Tag>
+ <Text ellipsis fontSize={12} style={{ flex: 1, minWidth: 0 }} type={'secondary'}>
+ {data.title}
+ </Text>
+ <PortalMoreMenu config={moreMenu} outdent={'end'} />
+ </Flexbox>
+ {showPending && (
+ <Flexbox horizontal align={'center'} gap={8} {...stylex.props(styles.pill)}>
+ <Loader2Icon size={14} {...stylex.props(styles.spin)} />
+ <Text fontSize={12}>{t('canvas.generating', { version: data.latestVersion + 1 })}</Text>
+ </Flexbox>
+ )}
+ <Flexbox flex={1} {...stylex.props(styles.content, showPending && styles.dimmed)}>
+ <CanvasFrame src={data.previewUrl} />
+ </Flexbox>
+ </Flexbox>
+ );
+});
+
+CanvasPane.displayName = 'WorkingSidebarCanvasPane';
+
+export default CanvasPane;
diff --git a/src/features/Conversation/WorkingSidebar/Canvas/CanvasTabLabel.tsx b/src/features/Conversation/WorkingSidebar/Canvas/CanvasTabLabel.tsx
new file mode 100644
index 00000000000..b1a92936c7b
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/Canvas/CanvasTabLabel.tsx
@@ -0,0 +1,15 @@
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useCanvasTabView, useCanvasVersion } from './useCanvasVersion';
+
+const CanvasTabLabel = memo<{ canvasId: string }>(({ canvasId }) => {
+ const { t } = useTranslation('portal');
+ const { data } = useCanvasVersion(useCanvasTabView(canvasId));
+
+ return data?.title || t('canvas.title');
+});
+
+CanvasTabLabel.displayName = 'WorkingSidebarCanvasTabLabel';
+
+export default CanvasTabLabel;
diff --git a/src/features/Conversation/WorkingSidebar/Canvas/latestCanvasVersion.test.ts b/src/features/Conversation/WorkingSidebar/Canvas/latestCanvasVersion.test.ts
new file mode 100644
index 00000000000..dd872eb0ae9
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/Canvas/latestCanvasVersion.test.ts
@@ -0,0 +1,66 @@
+import { describe, expect, it } from 'vitest';
+
+import { getLatestCanvasVersion, getLatestSavedManifestKey } from './latestCanvasVersion';
+
+const work = (
+ resourceId: string,
+ eventVersion: number,
+ currentVersion?: number,
+ type = 'canvas',
+) => ({
+ event: { version: eventVersion },
+ id: `work_${resourceId}`,
+ resourceId,
+ type,
+ version: currentVersion ? { version: currentVersion } : null,
+});
+
+describe('getLatestCanvasVersion', () => {
+ it('returns the highest version any message summary knows for the canvas', () => {
+ const messages = [
+ { id: 'm1', role: 'assistant', works: [work('cvs_1', 1, 1)] },
+ { id: 'm2', role: 'assistant', works: [work('cvs_1', 2, 3), work('cvs_2', 9, 9)] },
+ ];
+
+ expect(getLatestCanvasVersion(messages as any, 'cvs_1')).toBe(3);
+ });
+
+ it('is 0 when no summary mentions the canvas', () => {
+ const messages = [
+ { id: 'm1', role: 'assistant', works: [work('cvs_1', 4, 4, 'document')] },
+ { id: 'm2', role: 'user' },
+ ];
+
+ expect(getLatestCanvasVersion(messages as any, 'cvs_1')).toBe(0);
+ });
+});
+
+const saved = (canvasId: string, manifestKey: string, extra: Record<string, unknown> = {}) => ({
+ content: 'Saved',
+ id: `msg_${manifestKey}`,
+ plugin: { apiName: 'updateCanvas', identifier: 'lobe-canvas' },
+ pluginState: { canvasId, metadata: { manifestKey } },
+ role: 'tool',
+ ...extra,
+});
+
+describe('getLatestSavedManifestKey', () => {
+ it('returns the manifest of the newest successful save of the canvas', () => {
+ const messages = [
+ saved('cvs_1', 'm/a.json'),
+ saved('cvs_2', 'm/x.json'),
+ saved('cvs_1', 'm/b.json'),
+ {
+ ...saved('cvs_1', 'm/c.json'),
+ plugin: { apiName: 'readCanvas', identifier: 'lobe-canvas' },
+ },
+ { ...saved('cvs_1', 'm/d.json'), plugin: { apiName: 'updateCanvas', identifier: 'other' } },
+ ];
+
+ expect(getLatestSavedManifestKey(messages as any, 'cvs_1')).toBe('m/b.json');
+ });
+
+ it('is undefined before the canvas was saved in this conversation', () => {
+ expect(getLatestSavedManifestKey([saved('cvs_2', 'm/x.json')] as any, 'cvs_1')).toBeUndefined();
+ });
+});
diff --git a/src/features/Conversation/WorkingSidebar/Canvas/latestCanvasVersion.ts b/src/features/Conversation/WorkingSidebar/Canvas/latestCanvasVersion.ts
new file mode 100644
index 00000000000..d2561af48d7
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/Canvas/latestCanvasVersion.ts
@@ -0,0 +1,26 @@
+import { CanvasApiName, CanvasIdentifier } from '@lobechat/builtin-tool-canvas';
+import type { UIChatMessage } from '@lobechat/types';
+
+const SAVE_APIS = new Set<string>([CanvasApiName.createCanvas, CanvasApiName.updateCanvas]);
+
+export const getLatestCanvasVersion = (messages: UIChatMessage[], canvasId: string) => {
+ let latest = 0;
+ for (const message of messages) {
+ for (const work of message.works ?? []) {
+ if (work.type !== 'canvas' || work.resourceId !== canvasId) continue;
+ latest = Math.max(latest, work.event?.version ?? 0, work.version?.version ?? 0);
+ }
+ }
+ return latest;
+};
+
+export const getLatestSavedManifestKey = (messages: UIChatMessage[], canvasId: string) => {
+ for (let index = messages.length - 1; index >= 0; index--) {
+ const message = messages[index];
+ if (message.role !== 'tool' || message.plugin?.identifier !== CanvasIdentifier) continue;
+ if (!SAVE_APIS.has(message.plugin.apiName) || message.pluginState?.canvasId !== canvasId)
+ continue;
+ const manifestKey = message.pluginState?.metadata?.manifestKey;
+ if (typeof manifestKey === 'string') return manifestKey;
+ }
+};
diff --git a/src/features/Conversation/WorkingSidebar/Canvas/pendingUpdate.test.ts b/src/features/Conversation/WorkingSidebar/Canvas/pendingUpdate.test.ts
new file mode 100644
index 00000000000..bbf9caa5588
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/Canvas/pendingUpdate.test.ts
@@ -0,0 +1,89 @@
+import { CanvasApiName, CanvasIdentifier } from '@lobechat/builtin-tool-canvas';
+import { describe, expect, it } from 'vitest';
+
+import { getCanvasUpdateStatus } from './pendingUpdate';
+
+const updateCall = (id: string, args: string, extra: Record<string, unknown> = {}) => ({
+ apiName: CanvasApiName.updateCanvas,
+ arguments: args,
+ id,
+ identifier: CanvasIdentifier,
+ type: 'builtin',
+ ...extra,
+});
+
+const assistant = (...tools: any[]) => ({ content: '', id: 'msg_a', role: 'assistant', tools });
+
+describe('getCanvasUpdateStatus', () => {
+ it('is streaming while the update arguments are still arriving', () => {
+ const messages = [assistant(updateCall('call_1', '{"canvasId":"cvs_1","files":[{"pa'))];
+
+ expect(getCanvasUpdateStatus(messages as any, 'cvs_1')).toBe('streaming');
+ });
+
+ it('is executing once the call is approved and still has no result', () => {
+ const messages = [
+ assistant(updateCall('call_1', '{"canvasId":"cvs_1"}')),
+ {
+ content: '',
+ id: 'msg_t',
+ pluginIntervention: { status: 'approved' },
+ role: 'tool',
+ tool_call_id: 'call_1',
+ },
+ ];
+
+ expect(getCanvasUpdateStatus(messages as any, 'cvs_1')).toBe('executing');
+ });
+
+ it('reports a call that waits for approval', () => {
+ const messages = [
+ assistant(updateCall('call_1', '{"canvasId":"cvs_1"}')),
+ {
+ content: '',
+ id: 'msg_t',
+ pluginIntervention: { status: 'pending' },
+ role: 'tool',
+ tool_call_id: 'call_1',
+ },
+ ];
+
+ expect(getCanvasUpdateStatus(messages as any, 'cvs_1')).toBe('awaitingApproval');
+ });
+
+ it('settles once the tool message carries a result', () => {
+ const messages = [
+ assistant(updateCall('call_1', '{"canvasId":"cvs_1"}')),
+ {
+ content: 'Saved canvas cvs_1',
+ id: 'msg_t',
+ pluginState: { canvasId: 'cvs_1' },
+ role: 'tool',
+ tool_call_id: 'call_1',
+ },
+ ];
+
+ expect(getCanvasUpdateStatus(messages as any, 'cvs_1')).toBe('none');
+ });
+
+ it('settles when the user rejects or aborts the call', () => {
+ for (const status of ['rejected', 'aborted']) {
+ const messages = [
+ assistant(updateCall('call_1', '{"canvasId":"cvs_1"}', { intervention: { status } })),
+ ];
+
+ expect(getCanvasUpdateStatus(messages as any, 'cvs_1')).toBe('none');
+ }
+ });
+
+ it('ignores updates to other canvases and other canvas calls', () => {
+ const messages = [
+ assistant(updateCall('call_1', '{"canvasId":"cvs_2"}'), {
+ ...updateCall('call_2', '{"canvasId":"cvs_1"}'),
+ apiName: CanvasApiName.readCanvas,
+ }),
+ ];
+
+ expect(getCanvasUpdateStatus(messages as any, 'cvs_1')).toBe('none');
+ });
+});
diff --git a/src/features/Conversation/WorkingSidebar/Canvas/pendingUpdate.ts b/src/features/Conversation/WorkingSidebar/Canvas/pendingUpdate.ts
new file mode 100644
index 00000000000..67701d233e1
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/Canvas/pendingUpdate.ts
@@ -0,0 +1,47 @@
+import { CanvasApiName, CanvasIdentifier } from '@lobechat/builtin-tool-canvas';
+import type { UIChatMessage } from '@lobechat/types';
+import { safeParsePartialJSON } from '@lobechat/utils';
+
+export type CanvasUpdateStatus = 'awaitingApproval' | 'executing' | 'none' | 'streaming';
+
+const SETTLED_INTERVENTIONS = new Set(['aborted', 'rejected']);
+
+const isSettledToolMessage = (message: UIChatMessage) =>
+ !!message.content ||
+ message.pluginState !== undefined ||
+ !!message.pluginError ||
+ SETTLED_INTERVENTIONS.has(message.pluginIntervention?.status ?? '');
+
+export const getCanvasUpdateStatus = (
+ messages: UIChatMessage[],
+ canvasId: string,
+): CanvasUpdateStatus => {
+ const toolMessages = new Map(
+ messages
+ .filter((message) => message.role === 'tool' && message.tool_call_id)
+ .map((message) => [message.tool_call_id!, message]),
+ );
+
+ for (const message of messages) {
+ for (const tool of message.tools ?? []) {
+ if (tool.identifier !== CanvasIdentifier || tool.apiName !== CanvasApiName.updateCanvas)
+ continue;
+ if (SETTLED_INTERVENTIONS.has(tool.intervention?.status ?? '')) continue;
+
+ const toolMessage = toolMessages.get(tool.id);
+ if (toolMessage && isSettledToolMessage(toolMessage)) continue;
+
+ const args = safeParsePartialJSON(tool.arguments) as { canvasId?: string } | undefined;
+ if (args?.canvasId !== canvasId) continue;
+
+ if (
+ toolMessage?.pluginIntervention?.status === 'pending' ||
+ tool.intervention?.status === 'pending'
+ )
+ return 'awaitingApproval';
+ return toolMessage ? 'executing' : 'streaming';
+ }
+ }
+
+ return 'none';
+};
diff --git a/src/features/Conversation/WorkingSidebar/Canvas/runtime/CanvasRuntimeManager.test.ts b/src/features/Conversation/WorkingSidebar/Canvas/runtime/CanvasRuntimeManager.test.ts
new file mode 100644
index 00000000000..7debfded17a
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/Canvas/runtime/CanvasRuntimeManager.test.ts
@@ -0,0 +1,111 @@
+import type { CanvasRuntimeBundle } from '@lobechat/canvas/runtime';
+import { describe, expect, it } from 'vitest';
+
+import { CanvasRuntimeManager } from './CanvasRuntimeManager';
+import type { CanvasRuntimeSource } from './CanvasRuntimeSource';
+
+const source = (load: () => Promise<CanvasRuntimeBundle>): CanvasRuntimeSource => {
+ const values = new Set<CanvasRuntimeBundle>();
+ let disposed = false;
+ const clear = (value: CanvasRuntimeBundle) => {
+ value.modules.length = 0;
+ value.styles.length = 0;
+ };
+ return {
+ async load() {
+ const value = await load();
+ if (disposed) clear(value);
+ else values.add(value);
+ return value;
+ },
+ dispose() {
+ disposed = true;
+ for (const value of values) clear(value);
+ values.clear();
+ },
+ };
+};
+
+const bundle = (): CanvasRuntimeBundle => ({
+ entries: { runtime: 'entry.js', highlight: 'highlight.js', mermaid: 'mermaid.js' },
+ modules: [
+ {
+ id: 'entry.js',
+ code: 'globalThis.ready = true',
+ imports: [],
+ url: 'https://app.test/entry.js',
+ },
+ ],
+ styles: ['body { color: red }'],
+});
+
+describe('CanvasRuntimeManager', () => {
+ it('shares one load and keeps it alive until the last Canvas releases it', async () => {
+ let loads = 0;
+ let signal: AbortSignal | undefined;
+ const manager = new CanvasRuntimeManager((nextSignal) =>
+ source(async () => {
+ loads++;
+ signal = nextSignal;
+ return bundle();
+ }),
+ );
+ const first = manager.acquire();
+ const second = manager.acquire();
+ const content = await first.ready;
+ expect(await second.ready).toBe(content);
+ expect(loads).toBe(1);
+
+ first.release();
+ first.release();
+ expect(signal?.aborted).toBe(false);
+ expect(content.modules).toHaveLength(1);
+
+ second.release();
+ expect(signal?.aborted).toBe(true);
+ expect(content.modules).toEqual([]);
+ expect(content.styles).toEqual([]);
+ const third = manager.acquire();
+ expect((await third.ready).modules).toHaveLength(1);
+ expect(loads).toBe(2);
+ third.release();
+ });
+
+ it('disposes a late completion after close without clearing a newer Canvas load', async () => {
+ let complete: ((value: CanvasRuntimeBundle) => void) | undefined;
+ const pending = new Promise<CanvasRuntimeBundle>((resolve) => {
+ complete = resolve;
+ });
+ let loads = 0;
+ const manager = new CanvasRuntimeManager(() => {
+ const next = ++loads === 1 ? pending : Promise.resolve(bundle());
+ return source(() => next);
+ });
+ const old = manager.acquire();
+ old.release();
+ const current = manager.acquire();
+ const live = await current.ready;
+ const stale = bundle();
+ complete!(stale);
+ await old.ready;
+ expect(stale.modules).toEqual([]);
+ expect(live.modules).toHaveLength(1);
+ current.release();
+ });
+
+ it('allows a fresh load after the last failed lease is released', async () => {
+ let loads = 0;
+ const manager = new CanvasRuntimeManager(() =>
+ source(async () => {
+ if (++loads === 1) throw new Error('offline');
+ return bundle();
+ }),
+ );
+ const failed = manager.acquire();
+ await expect(failed.ready).rejects.toThrow('offline');
+ failed.release();
+ const retry = manager.acquire();
+ expect((await retry.ready).modules).toHaveLength(1);
+ retry.release();
+ });
+});
diff --git a/src/features/Conversation/WorkingSidebar/Canvas/runtime/CanvasRuntimeManager.ts b/src/features/Conversation/WorkingSidebar/Canvas/runtime/CanvasRuntimeManager.ts
new file mode 100644
index 00000000000..9bc411ec518
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/Canvas/runtime/CanvasRuntimeManager.ts
@@ -0,0 +1,55 @@
+import type { CanvasRuntimeBundle } from '@lobechat/canvas/runtime';
+
+import type { CanvasRuntimeEntry, CanvasRuntimeSource } from './CanvasRuntimeSource';
+
+export class CanvasRuntimeManager {
+ private current?: {
+ controller: AbortController;
+ pending: Map<CanvasRuntimeEntry, Promise<CanvasRuntimeBundle>>;
+ references: number;
+ source: CanvasRuntimeSource;
+ };
+
+ constructor(private create: (signal: AbortSignal) => CanvasRuntimeSource) {}
+
+ acquire() {
+ if (!this.current) {
+ const controller = new AbortController();
+ const state = {
+ controller,
+ pending: new Map<CanvasRuntimeEntry, Promise<CanvasRuntimeBundle>>(),
+ references: 0,
+ source: this.create(controller.signal),
+ };
+ this.current = state;
+ }
+ const state = this.current;
+ state.references++;
+ let released = false;
+ const load = (entry: CanvasRuntimeEntry) => {
+ if (released) return Promise.reject(new Error('Canvas runtime released'));
+ let pending = state.pending.get(entry);
+ if (!pending) {
+ pending = state.source.load(entry).catch((error) => {
+ state.pending.delete(entry);
+ throw error;
+ });
+ state.pending.set(entry, pending);
+ }
+ return pending;
+ };
+ return {
+ ready: load('runtime'),
+ loadAddon: (name: 'highlight' | 'mermaid') => load(name),
+ release: () => {
+ if (released) return;
+ released = true;
+ if (--state.references > 0) return;
+ if (this.current === state) this.current = undefined;
+ state.controller.abort();
+ state.source.dispose();
+ state.pending.clear();
+ },
+ };
+ }
+}
diff --git a/src/features/Conversation/WorkingSidebar/Canvas/runtime/CanvasRuntimeSource.test.ts b/src/features/Conversation/WorkingSidebar/Canvas/runtime/CanvasRuntimeSource.test.ts
new file mode 100644
index 00000000000..2f970a1222a
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/Canvas/runtime/CanvasRuntimeSource.test.ts
@@ -0,0 +1,48 @@
+import type { CanvasRuntimeManifest } from '@lobechat/canvas/runtime';
+import { afterEach, expect, it, vi } from 'vitest';
+
+import { CanvasRuntimeManager } from './CanvasRuntimeManager';
+import { createCanvasRuntimeSource } from './CanvasRuntimeSource';
+
+afterEach(() => vi.unstubAllGlobals());
+
+it('loads optional graphs only on demand, shares their dependencies, and releases all code', async () => {
+ const requests: string[] = [];
+ let failAddon = true;
+ const manifest: CanvasRuntimeManifest = {
+ base: '/_spa/',
+ entries: { runtime: 'runtime.js', highlight: 'highlight.js', mermaid: 'mermaid.js' },
+ modules: ['runtime', 'highlight', 'mermaid', 'shared'].map((name) => ({
+ id: `${name}.js`,
+ imports: name === 'shared' ? [] : [{ start: 0, end: 1, target: 'shared.js' }],
+ })),
+ styles: ['ui.css'],
+ };
+ vi.stubGlobal('fetch', async (url: URL) => {
+ requests.push(url.pathname);
+ if (url.pathname === '/manifest.json') return Response.json(manifest);
+ if (url.pathname.endsWith('highlight.js') && failAddon)
+ return new Response('', { status: 503 });
+ return new Response(url.pathname.endsWith('.css') ? 'a{background:url(./image.png)}' : 'code');
+ });
+ const manager = new CanvasRuntimeManager((signal) =>
+ createCanvasRuntimeSource(new URL('https://app.test/manifest.json'), signal),
+ );
+ const first = manager.acquire();
+ const second = manager.acquire();
+ const base = await first.ready;
+ expect(await second.ready).toBe(base);
+ expect(requests).not.toContain('/_spa/highlight.js');
+ expect(requests).not.toContain('/_spa/mermaid.js');
+ expect(base.styles[0]).toContain('https://app.test/_spa/image.png');
+ await expect(first.loadAddon('highlight')).rejects.toThrow('503');
+ expect(base.modules).toHaveLength(2);
+ failAddon = false;
+ const addon = await second.loadAddon('highlight');
+ expect(requests.filter((url) => url.endsWith('shared.js'))).toHaveLength(1);
+ first.release();
+ expect(addon.modules).toHaveLength(2);
+ second.release();
+ expect(base.modules).toEqual([]);
+ expect(addon.modules).toEqual([]);
+});
diff --git a/src/features/Conversation/WorkingSidebar/Canvas/runtime/CanvasRuntimeSource.ts b/src/features/Conversation/WorkingSidebar/Canvas/runtime/CanvasRuntimeSource.ts
new file mode 100644
index 00000000000..8850e6af1dc
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/Canvas/runtime/CanvasRuntimeSource.ts
@@ -0,0 +1,92 @@
+import type { CanvasRuntimeBundle, CanvasRuntimeManifest } from '@lobechat/canvas/runtime';
+
+export type CanvasRuntimeEntry = keyof CanvasRuntimeManifest['entries'];
+export interface CanvasRuntimeSource {
+ dispose: () => void;
+ load: (entry: CanvasRuntimeEntry) => Promise<CanvasRuntimeBundle>;
+}
+
+export const createCanvasRuntimeSource = (
+ url: URL,
+ signal: AbortSignal,
+ deployment?: string,
+): CanvasRuntimeSource => {
+ const cache = new Map<string, Promise<string>>();
+ const bundles = new Set<CanvasRuntimeBundle>();
+ const text = (url: URL) => {
+ const key = url.href;
+ let pending = cache.get(key);
+ if (!pending) {
+ pending = fetch(url, { signal })
+ .then(async (response) => {
+ if (!response.ok) throw new Error(`Canvas runtime: ${response.status} ${url.pathname}`);
+ return response.text();
+ })
+ .catch((error) => {
+ cache.delete(key);
+ throw error;
+ });
+ cache.set(key, pending);
+ }
+ return pending;
+ };
+ return {
+ dispose() {
+ cache.clear();
+ for (const bundle of bundles) {
+ bundle.modules.length = 0;
+ bundle.styles.length = 0;
+ }
+ bundles.clear();
+ },
+ async load(entry) {
+ const manifest: CanvasRuntimeManifest | { bundle: CanvasRuntimeBundle } = JSON.parse(
+ await text(url),
+ );
+ signal.throwIfAborted();
+ if ('bundle' in manifest) {
+ bundles.add(manifest.bundle);
+ return manifest.bundle;
+ }
+ const base = new URL(manifest.base, url);
+ const assetUrl = (id: string) => {
+ const asset = new URL(id, base);
+ if (deployment) asset.searchParams.set('dpl', deployment);
+ return asset;
+ };
+ const graph = new Map(manifest.modules.map((module) => [module.id, module]));
+ const selected = new Set<string>();
+ const visit = (id: string) => {
+ if (selected.has(id)) return;
+ selected.add(id);
+ const module = graph.get(id);
+ if (!module) throw new Error(`Canvas module missing: ${id}`);
+ for (const dependency of module.imports) visit(dependency.target);
+ };
+ visit(manifest.entries[entry]);
+ const [modules, styles] = await Promise.all([
+ Promise.all(
+ [...selected].map(async (id) => {
+ const module = graph.get(id)!;
+ const url = assetUrl(id);
+ return { ...module, code: await text(url), url: url.href };
+ }),
+ ),
+ Promise.all(
+ (manifest.entryStyles?.[entry] ?? manifest.styles).map(async (id) => {
+ const url = assetUrl(id);
+ return (await text(url)).replaceAll(
+ /url\((['"]?)(?!data:|blob:|#)([^)'"\s]+)\1\)/g,
+ (_match, _quote: string, value: string) =>
+ `url(${JSON.stringify(new URL(value, url).href)})`,
+ );
+ }),
+ ),
+ ]);
+ signal.throwIfAborted();
+ const bundle = { entries: manifest.entries, modules, styles };
+ bundles.add(bundle);
+ return bundle;
+ },
+ };
+};
diff --git a/src/features/Conversation/WorkingSidebar/Canvas/runtime/host.test.ts b/src/features/Conversation/WorkingSidebar/Canvas/runtime/host.test.ts
new file mode 100644
index 00000000000..a5e117322df
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/Canvas/runtime/host.test.ts
@@ -0,0 +1,31 @@
+import { afterEach, expect, it, vi } from 'vitest';
+
+import { attachCanvasRuntime } from './host';
+
+vi.mock('virtual:canvas-runtime', () => ({ default: 'https://app.test/runtime.json' }));
+
+afterEach(() => {
+ document.body.innerHTML = '';
+ vi.unstubAllGlobals();
+});
+
+it('retains a hidden Activity iframe and releases only when its DOM is removed', async () => {
+ let signal: AbortSignal | undefined;
+ let loads = 0;
+ vi.stubGlobal('fetch', async (_url: URL, options: RequestInit) => {
+ loads++;
+ signal = options.signal!;
+ return Response.json({ bundle: { entries: {}, modules: [], styles: [] } });
+ });
+ const frame = document.createElement('iframe');
+ document.body.append(frame);
+ const detach = attachCanvasRuntime(frame, vi.fn());
+ await vi.waitFor(() => expect(loads).toBe(1));
+ detach();
+ expect(signal?.aborted).toBe(false);
+ const detachAgain = attachCanvasRuntime(frame, vi.fn());
+ expect(loads).toBe(1);
+ detachAgain();
+ frame.remove();
+ await vi.waitFor(() => expect(signal?.aborted).toBe(true));
+});
diff --git a/src/features/Conversation/WorkingSidebar/Canvas/runtime/host.ts b/src/features/Conversation/WorkingSidebar/Canvas/runtime/host.ts
new file mode 100644
index 00000000000..fec5e665c69
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/Canvas/runtime/host.ts
@@ -0,0 +1,95 @@
+import manifestUrl from 'virtual:canvas-runtime';
+
+import { CanvasRuntimeManager } from './CanvasRuntimeManager';
+import { createCanvasRuntimeSource } from './CanvasRuntimeSource';
+
+const manager = new CanvasRuntimeManager((signal) =>
+ createCanvasRuntimeSource(
+ new URL(manifestUrl, window.location.href),
+ signal,
+ import.meta.env.VITE_VERCEL_DEPLOYMENT_ID,
+ ),
+);
+
+const frames = new WeakMap<HTMLIFrameElement, { detach: () => void; resume: () => void }>();
+
+export const attachCanvasRuntime = (
+ frame: HTMLIFrameElement,
+ onError: (error: unknown) => void,
+) => {
+ const existing = frames.get(frame);
+ if (existing) {
+ existing.resume();
+ return existing.detach;
+ }
+ const lease = manager.acquire();
+ let active = true;
+ let instanceId: string | undefined;
+ const host = frame.ownerDocument.defaultView!;
+ const post = (message: Record<string, unknown>) =>
+ frame.contentWindow?.postMessage({ ...message, source: 'lobe-canvas-host' }, '*');
+ const onMessage = (event: MessageEvent) => {
+ if (
+ event.source !== frame.contentWindow ||
+ event.data?.source !== 'lobe-canvas' ||
+ typeof event.data.instanceId !== 'string'
+ )
+ return;
+ if (event.data.type === 'load-addon' && event.data.instanceId === instanceId) {
+ const { name, requestId } = event.data;
+ if ((name !== 'highlight' && name !== 'mermaid') || typeof requestId !== 'number') return;
+ const nextId = instanceId;
+ void lease
+ .loadAddon(name)
+ .then((bundle) => {
+ if (active && instanceId === nextId)
+ post({ type: 'addon', bundle, name, requestId, instanceId });
+ })
+ .catch((error) => {
+ if (active && instanceId === nextId)
+ post({ type: 'addon', error: String(error), requestId, instanceId });
+ });
+ return;
+ }
+ if (event.data.type !== 'ready') return;
+ const nextId = event.data.instanceId;
+ if (nextId === instanceId) return;
+ instanceId = nextId;
+ void lease.ready
+ .then((bundle) => {
+ if (active && instanceId === nextId) post({ type: 'runtime', bundle, instanceId });
+ })
+ .catch((error) => {
+ if (active) onError(error);
+ });
+ };
+ // Observe load failures even if the frame never completes its handshake.
+ void lease.ready.catch((error) => {
+ if (active && !instanceId) onError(error);
+ });
+ const request = () => post({ type: 'request-runtime' });
+ host.addEventListener('message', onMessage);
+ frame.addEventListener('load', request);
+ request();
+ let observer: MutationObserver | undefined;
+ const dispose = () => {
+ if (!active) return;
+ active = false;
+ post({ type: 'dispose-runtime', instanceId });
+ host.removeEventListener('message', onMessage);
+ frame.removeEventListener('load', request);
+ observer?.disconnect();
+ frames.delete(frame);
+ lease.release();
+ };
+ const detach = () => {
+ // Activity cleans up effects while retaining the iframe; its document is still alive.
+ if (!frame.isConnected) return dispose();
+ observer ??= new MutationObserver(() => {
+ if (!frame.isConnected) dispose();
+ });
+ observer.observe(frame.ownerDocument, { childList: true, subtree: true });
+ };
+ frames.set(frame, { detach, resume: () => observer?.disconnect() });
+ return detach;
+};
diff --git a/src/features/Conversation/WorkingSidebar/Canvas/useCanvasMoreMenu.tsx b/src/features/Conversation/WorkingSidebar/Canvas/useCanvasMoreMenu.tsx
new file mode 100644
index 00000000000..b515678df1e
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/Canvas/useCanvasMoreMenu.tsx
@@ -0,0 +1,54 @@
+import type { DropdownItem } from '@lobehub/ui';
+import { useTranslation } from 'react-i18next';
+
+import { type PortalMoreMenuConfig } from '@/features/Portal/components/PortalMoreMenu/types';
+import { type CanvasVersionDetail } from '@/services/canvas';
+import { useChatStore } from '@/store/chat';
+
+import { useCanvasPublishItems } from './useCanvasPublishItems';
+import { type CanvasTabView, useCanvasVersions } from './useCanvasVersion';
+
+export const useCanvasMoreMenu = (
+ view: CanvasTabView,
+ data: CanvasVersionDetail | null | undefined,
+ refresh: () => unknown,
+): PortalMoreMenuConfig | undefined => {
+ const { t } = useTranslation('portal');
+ const { data: versions } = useCanvasVersions(view.canvasId);
+ const openCanvas = useChatStore((s) => s.openCanvas);
+ const publishItems = useCanvasPublishItems(data, refresh);
+
+ if (!data) return;
+
+ const extraItems: DropdownItem[] = [
+ ...publishItems,
+ {
+ key: 'open-in-tab',
+ label: t('canvas.menu.openInTab'),
+ onClick: () => window.open(data.previewUrl, '_blank', 'noopener,noreferrer'),
+ },
+ ];
+
+ if (versions && versions.length > 1) {
+ extraItems.unshift({
+ children: versions.map((item) => ({
+ key: `v${item.version}`,
+ label: t('canvas.menu.versionItem', {
+ date: new Date(item.createdAt).toLocaleString(),
+ version: item.version,
+ }),
+ onClick: () =>
+ openCanvas(view.canvasId, item.version === data.latestVersion ? undefined : item.version),
+ })),
+ key: 'versions',
+ label: t('canvas.menu.versions'),
+ });
+ }
+
+ return {
+ copyId: view.canvasId,
+ copyLink: data.publishedUrl ?? undefined,
+ extraItems,
+ refresh,
+ };
+};
diff --git a/src/features/Conversation/WorkingSidebar/Canvas/useCanvasPublishItems.test.ts b/src/features/Conversation/WorkingSidebar/Canvas/useCanvasPublishItems.test.ts
new file mode 100644
index 00000000000..1ebaa71f4f2
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/Canvas/useCanvasPublishItems.test.ts
@@ -0,0 +1,75 @@
+import { act, renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type { CanvasVersionDetail } from '@/services/canvas';
+
+import { useCanvasPublishItems } from './useCanvasPublishItems';
+
+const mocks = vi.hoisted(() => ({
+ openPublishConfirm: vi.fn(),
+ publish: vi.fn(),
+ refreshAllConversations: vi.fn(),
+}));
+
+vi.mock('@/components/PublishConfirmModal', () => ({
+ openPublishConfirm: mocks.openPublishConfirm,
+}));
+vi.mock('@/services/canvas', () => ({ canvasService: { publish: mocks.publish } }));
+vi.mock('@/services/work', () => ({
+ workService: { refreshAllConversations: mocks.refreshAllConversations },
+}));
+
+const detail = (overrides: Partial<CanvasVersionDetail> = {}) =>
+ ({
+ canPublish: true,
+ canvasId: 'cvs_1',
+ latestVersion: 2,
+ publishedUrl: null,
+ publishedVersion: null,
+ ...overrides,
+ }) as unknown as CanvasVersionDetail;
+
+const clickPublish = (data: CanvasVersionDetail, onPublished = vi.fn()) => {
+ const { result } = renderHook(() => useCanvasPublishItems(data, onPublished));
+ const item = result.current.find((entry) => entry && 'key' in entry && entry.key === 'publish');
+ act(() => {
+ (item as { onClick: () => void }).onClick();
+ });
+};
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.publish.mockResolvedValue({ publishedVersion: 2 });
+});
+
+describe('useCanvasPublishItems', () => {
+ it('asks for confirmation before a canvas becomes public', () => {
+ clickPublish(detail());
+
+ expect(mocks.publish).not.toHaveBeenCalled();
+ expect(mocks.openPublishConfirm).toHaveBeenCalledWith(
+ expect.objectContaining({ okText: 'canvas.menu.publish', note: 'canvas.publish.note' }),
+ );
+ });
+
+ it('publishes once the confirmation is accepted', async () => {
+ const onPublished = vi.fn();
+ clickPublish(detail(), onPublished);
+
+ await act(async () => {
+ mocks.openPublishConfirm.mock.calls[0][0].onOk();
+ });
+
+ expect(mocks.publish).toHaveBeenCalledWith('cvs_1');
+ expect(onPublished).toHaveBeenCalled();
+ });
+
+ it('confirms updating an existing public link as well', () => {
+ clickPublish(detail({ publishedUrl: 'https://cost.lobehub.sites', publishedVersion: 1 }));
+
+ expect(mocks.openPublishConfirm).toHaveBeenCalledWith(
+ expect.objectContaining({ okText: 'canvas.menu.updatePublic' }),
+ );
+ expect(mocks.publish).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/features/Conversation/WorkingSidebar/Canvas/useCanvasPublishItems.ts b/src/features/Conversation/WorkingSidebar/Canvas/useCanvasPublishItems.ts
new file mode 100644
index 00000000000..717c50ee189
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/Canvas/useCanvasPublishItems.ts
@@ -0,0 +1,63 @@
+import { type DropdownItem, toast } from '@lobehub/ui';
+import { useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { openPublishConfirm } from '@/components/PublishConfirmModal';
+import { canvasService, type CanvasVersionDetail } from '@/services/canvas';
+import { workService } from '@/services/work';
+
+export const useCanvasPublishItems = (
+ data: CanvasVersionDetail | null | undefined,
+ onPublished: () => unknown,
+): DropdownItem[] => {
+ const { t } = useTranslation('portal');
+ const [publishing, setPublishing] = useState(false);
+
+ if (!data) return [];
+
+ const items: DropdownItem[] = [];
+ const publishedUrl = data.publishedUrl;
+
+ if (publishedUrl) {
+ items.push({
+ key: 'open-public',
+ label: t('canvas.menu.openPublic'),
+ onClick: () => window.open(publishedUrl, '_blank', 'noopener,noreferrer'),
+ });
+ }
+
+ if (data.canPublish && (publishing || data.publishedVersion !== data.latestVersion)) {
+ const publish = async () => {
+ setPublishing(true);
+ try {
+ const result = await canvasService.publish(data.canvasId);
+ await onPublished();
+ await workService.refreshAllConversations();
+ toast.success(t('canvas.publish.success', { version: result.publishedVersion }));
+ } catch (error) {
+ console.error('[Canvas] publish failed', error);
+ toast.error(t('canvas.publish.failed'));
+ } finally {
+ setPublishing(false);
+ }
+ };
+
+ const publishLabel = t(publishedUrl ? 'canvas.menu.updatePublic' : 'canvas.menu.publish', {
+ version: data.latestVersion,
+ });
+
+ items.push({
+ disabled: publishing,
+ key: 'publish',
+ label: publishing ? t('canvas.menu.publishing') : publishLabel,
+ onClick: () =>
+ openPublishConfirm({
+ note: t('canvas.publish.note'),
+ okText: publishLabel,
+ onOk: () => void publish(),
+ }),
+ });
+ }
+
+ return items;
+};
diff --git a/src/features/Conversation/WorkingSidebar/Canvas/useCanvasVersion.ts b/src/features/Conversation/WorkingSidebar/Canvas/useCanvasVersion.ts
new file mode 100644
index 00000000000..973c4529745
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/Canvas/useCanvasVersion.ts
@@ -0,0 +1,63 @@
+import { useClientDataSWR } from '@/libs/swr';
+import { canvasService } from '@/services/canvas';
+import { useChatStore } from '@/store/chat';
+import { dbMessageSelectors } from '@/store/chat/slices/message/selectors';
+
+import { getLatestCanvasVersion, getLatestSavedManifestKey } from './latestCanvasVersion';
+import { isActiveRunRunning } from './usePendingCanvasUpdate';
+
+export interface CanvasTabView {
+ canvasId: string;
+ version?: number;
+}
+
+export const useCanvasTabView = (canvasId: string): CanvasTabView => {
+ const version = useChatStore((s) => s.canvasTabVersions[canvasId]);
+
+ return { canvasId, version };
+};
+
+const useLatestKnownVersion = (canvasId?: string) =>
+ useChatStore((s) =>
+ canvasId ? getLatestCanvasVersion(dbMessageSelectors.activeDbMessages(s), canvasId) : 0,
+ );
+
+export const useAwaitingCanvasSave = (view: CanvasTabView, shownManifestKey?: string) =>
+ useChatStore((s) => {
+ if (view.version || !shownManifestKey || !isActiveRunRunning(s)) return false;
+ const saved = getLatestSavedManifestKey(dbMessageSelectors.activeDbMessages(s), view.canvasId);
+ return !!saved && saved !== shownManifestKey;
+ });
+
+export const useCanvasVersion = (view: CanvasTabView) => {
+ const latestKnown = useLatestKnownVersion(view.canvasId);
+ const savedManifestKey = useChatStore((s) =>
+ view.version
+ ? undefined
+ : getLatestSavedManifestKey(dbMessageSelectors.activeDbMessages(s), view.canvasId),
+ );
+ const running = useChatStore(isActiveRunRunning);
+
+ const result = useClientDataSWR(
+ ['canvas-version', view.canvasId, view.version ?? 'latest', latestKnown, savedManifestKey],
+ () => canvasService.getVersion(view.canvasId, view.version),
+ {
+ keepPreviousData: true,
+ // In the client loop the version row is registered just after the tool result lands.
+ refreshInterval: (data) =>
+ running && savedManifestKey && data?.metadata.manifestKey !== savedManifestKey ? 1000 : 0,
+ },
+ );
+
+ return result.data && result.data.canvasId !== view.canvasId
+ ? { ...result, data: undefined }
+ : result;
+};
+
+export const useCanvasVersions = (canvasId?: string) => {
+ const latestKnown = useLatestKnownVersion(canvasId);
+
+ return useClientDataSWR(canvasId ? ['canvas-versions', canvasId, latestKnown] : null, () =>
+ canvasService.listVersions(canvasId!),
+ );
+};
diff --git a/src/features/Conversation/WorkingSidebar/Canvas/usePendingCanvasUpdate.test.ts b/src/features/Conversation/WorkingSidebar/Canvas/usePendingCanvasUpdate.test.ts
new file mode 100644
index 00000000000..3440b1638a0
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/Canvas/usePendingCanvasUpdate.test.ts
@@ -0,0 +1,92 @@
+import { CanvasApiName, CanvasIdentifier } from '@lobechat/builtin-tool-canvas';
+import { renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { usePendingCanvasUpdate } from './usePendingCanvasUpdate';
+
+const state = { messages: [] as any[], running: false };
+
+vi.mock('@/store/chat', () => ({
+ useChatStore: (selector: (s: typeof state) => unknown) => selector(state),
+}));
+vi.mock('@/store/chat/slices/operation/selectors', () => ({
+ operationSelectors: {
+ isAgentRuntimeRunningByContext: () => (s: typeof state) => s.running,
+ },
+}));
+vi.mock('@/store/chat/slices/message/selectors', () => ({
+ dbMessageSelectors: { activeDbMessages: (s: typeof state) => s.messages },
+}));
+
+const streamingUpdate = [
+ {
+ id: 'msg_a',
+ role: 'assistant',
+ tools: [
+ {
+ apiName: CanvasApiName.updateCanvas,
+ arguments: '{"canvasId":"cvs_1"',
+ id: 'call_1',
+ identifier: CanvasIdentifier,
+ },
+ ],
+ },
+];
+const savedUpdate = [
+ ...streamingUpdate,
+ { content: 'Saved', id: 'msg_t', pluginState: {}, role: 'tool', tool_call_id: 'call_1' },
+];
+
+beforeEach(() => {
+ state.messages = [];
+ state.running = false;
+});
+
+describe('usePendingCanvasUpdate', () => {
+ it('reports pending only while the run that edits this canvas is active', () => {
+ state.messages = streamingUpdate;
+ state.running = true;
+ const { rerender, result } = renderHook(() => usePendingCanvasUpdate('cvs_1'));
+ expect(result.current).toBe(true);
+
+ state.running = false;
+ rerender();
+ expect(result.current).toBe(false);
+ });
+
+ it('stays pending while the approved call executes even when the run is not tracked as running', () => {
+ state.messages = [
+ ...streamingUpdate,
+ {
+ content: '',
+ id: 'msg_t',
+ pluginIntervention: { status: 'approved' },
+ role: 'tool',
+ tool_call_id: 'call_1',
+ },
+ ];
+ const { result } = renderHook(() => usePendingCanvasUpdate('cvs_1'));
+
+ expect(result.current).toBe(true);
+ });
+
+ it('stays pending through the approval wait even when the run is paused', () => {
+ state.messages = [
+ ...streamingUpdate,
+ {
+ content: '',
+ id: 'msg_t',
+ pluginIntervention: { status: 'pending' },
+ role: 'tool',
+ tool_call_id: 'call_1',
+ },
+ ];
+ const { rerender, result } = renderHook(() => usePendingCanvasUpdate('cvs_1'));
+ expect(result.current).toBe(true);
+
+ state.messages = savedUpdate;
+ state.running = true;
+ rerender();
+ expect(result.current).toBe(false);
+ });
+});
diff --git a/src/features/Conversation/WorkingSidebar/Canvas/usePendingCanvasUpdate.ts b/src/features/Conversation/WorkingSidebar/Canvas/usePendingCanvasUpdate.ts
new file mode 100644
index 00000000000..67d38210e47
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/Canvas/usePendingCanvasUpdate.ts
@@ -0,0 +1,21 @@
+import { useChatStore } from '@/store/chat';
+import type { ChatStoreState } from '@/store/chat/initialState';
+import { dbMessageSelectors } from '@/store/chat/slices/message/selectors';
+import { operationSelectors } from '@/store/chat/slices/operation/selectors';
+
+import { getCanvasUpdateStatus } from './pendingUpdate';
+
+export const isActiveRunRunning = (s: ChatStoreState) =>
+ operationSelectors.isAgentRuntimeRunningByContext({
+ agentId: s.activeAgentId,
+ groupId: s.activeGroupId,
+ threadId: s.activeThreadId,
+ topicId: s.activeTopicId,
+ })(s);
+
+export const usePendingCanvasUpdate = (canvasId?: string) =>
+ useChatStore((s) => {
+ if (!canvasId) return false;
+ const status = getCanvasUpdateStatus(dbMessageSelectors.activeDbMessages(s), canvasId);
+ return status === 'streaming' ? isActiveRunRunning(s) : status !== 'none';
+ });
diff --git a/src/features/Conversation/WorkingSidebar/DynamicTabPanes.tsx b/src/features/Conversation/WorkingSidebar/DynamicTabPanes.tsx
new file mode 100644
index 00000000000..1608ff779e0
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/DynamicTabPanes.tsx
@@ -0,0 +1,107 @@
+import { Flexbox } from '@lobehub/ui';
+import * as stylex from '@stylexjs/stylex';
+import { Globe2Icon, PanelsTopLeftIcon } from 'lucide-react';
+import { Activity, lazy, memo } from 'react';
+
+import { canvasIdOfTab } from '@/store/global/initialState';
+
+import type { ComposerTarget } from '../types';
+import CanvasPane from './Canvas/CanvasPane';
+import CanvasTabLabel from './Canvas/CanvasTabLabel';
+import {
+ browserSessionIdOfTab,
+ type BrowserTabMetadata,
+ isBrowserTab,
+ isCanvasTab,
+ type SidebarTabDescriptor,
+} from './dynamicTabs';
+
+const BrowserPane = lazy(() => import('./Browser'));
+
+// Inline, because StyleX layout rules can lose to the `.lobe-flex` class of
+// Flexbox depending on stylesheet order.
+const PANE = { minHeight: 0, overflowY: 'auto' } as const;
+const HIDDEN_PANE = { ...PANE, display: 'none' } as const;
+
+const styles = stylex.create({
+ favicon: {
+ borderRadius: 2,
+ height: 14,
+ objectFit: 'contain',
+ width: 14,
+ },
+});
+
+export const dynamicTabDescriptor = (
+ tab: string,
+ browserMetadata: BrowserTabMetadata | undefined,
+ browserFallbackLabel: string,
+): SidebarTabDescriptor | undefined => {
+ const canvasId = canvasIdOfTab(tab);
+ if (canvasId) {
+ return { icon: PanelsTopLeftIcon, key: tab, label: <CanvasTabLabel canvasId={canvasId} /> };
+ }
+ if (!isBrowserTab(tab)) return;
+
+ return {
+ icon: Globe2Icon,
+ iconNode: browserMetadata?.faviconUrl ? (
+ <img alt="" src={browserMetadata.faviconUrl} {...stylex.props(styles.favicon)} />
+ ) : undefined,
+ key: tab,
+ label: browserMetadata?.title?.trim() || browserFallbackLabel,
+ };
+};
+
+interface DynamicTabPanesProps {
+ activeTab: string;
+ agentId?: string;
+ browserAvailable: boolean;
+ browserSessionId: string;
+ composerTarget: ComposerTarget;
+ onBrowserMetadataChange: (tab: string, metadata: BrowserTabMetadata) => void;
+ openedTabs: string[];
+ visible: boolean;
+}
+
+const DynamicTabPanes = memo<DynamicTabPanesProps>(
+ ({
+ activeTab,
+ agentId,
+ browserAvailable,
+ browserSessionId,
+ composerTarget,
+ onBrowserMetadataChange,
+ openedTabs,
+ visible,
+ }) => (
+ <>
+ {browserAvailable &&
+ openedTabs.filter(isBrowserTab).map((tab) => {
+ const sessionId = browserSessionIdOfTab(browserSessionId, tab);
+
+ return (
+ <Flexbox flex={1} key={sessionId} style={activeTab === tab ? PANE : HIDDEN_PANE}>
+ <BrowserPane
+ agentId={agentId}
+ composerTarget={composerTarget}
+ sessionId={sessionId}
+ onMetadataChange={(metadata) => onBrowserMetadataChange(tab, metadata)}
+ />
+ </Flexbox>
+ );
+ })}
+ {openedTabs.filter(isCanvasTab).map((tab) => (
+ <Activity key={tab} mode={visible && activeTab === tab ? 'visible' : 'hidden'}>
+ <Flexbox flex={1} style={PANE}>
+ <CanvasPane canvasId={canvasIdOfTab(tab)!} />
+ </Flexbox>
+ </Activity>
+ ))}
+ </>
+ ),
+);
+
+DynamicTabPanes.displayName = 'WorkingSidebarDynamicTabPanes';
+
+export default DynamicTabPanes;
diff --git a/src/features/Conversation/WorkingSidebar/WorksSection/WorkVersionHistoryCard.tsx b/src/features/Conversation/WorkingSidebar/WorksSection/WorkVersionHistoryCard.tsx
index cf84107ea22..17d154f8cb0 100644
--- a/src/features/Conversation/WorkingSidebar/WorksSection/WorkVersionHistoryCard.tsx
+++ b/src/features/Conversation/WorkingSidebar/WorksSection/WorkVersionHistoryCard.tsx
@@ -57,7 +57,8 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
const WorkVersionHistoryCard = memo<{ work: WorkListItem }>(({ work }) => {
const [expanded, setExpanded] = useState(false);
- const [openDocument, openFilePreview, openTaskDetail] = useChatStore((s) => [
+ const [openCanvas, openDocument, openFilePreview, openTaskDetail] = useChatStore((s) => [
+ s.openCanvas,
s.openDocument,
s.openFilePreview,
s.openTaskDetail,
@@ -92,6 +93,9 @@ const WorkVersionHistoryCard = memo<{ work: WorkListItem }>(({ work }) => {
? () => window.open(openTarget.url, '_blank', 'noopener,noreferrer')
: undefined;
}
+ case 'canvas': {
+ return () => openCanvas(openTarget.canvasId, openTarget.version);
+ }
case 'filePreview': {
return () => openFilePreview({ fileId: openTarget.fileId });
}
diff --git a/src/features/Conversation/WorkingSidebar/dynamicTabs.ts b/src/features/Conversation/WorkingSidebar/dynamicTabs.ts
new file mode 100644
index 00000000000..1c1cf49f06a
--- /dev/null
+++ b/src/features/Conversation/WorkingSidebar/dynamicTabs.ts
@@ -0,0 +1,34 @@
+import type { IconProps } from '@lobehub/ui';
+import type { ReactNode } from 'react';
+
+import { CANVAS_TAB_PREFIX } from '@/store/global/initialState';
+
+export interface SidebarTabDescriptor {
+ icon: IconProps['icon'];
+ iconNode?: ReactNode;
+ key: string;
+ label: ReactNode;
+}
+
+export interface BrowserTabMetadata {
+ faviconUrl?: string;
+ title: string;
+ url: string;
+}
+
+export const BROWSER_TAB_KEY = 'browser';
+export const BROWSER_TAB_PREFIX = 'browser:';
+
+export const isBrowserTab = (tab: string) =>
+ tab === BROWSER_TAB_KEY || tab.startsWith(BROWSER_TAB_PREFIX);
+
+export const isCanvasTab = (tab: string) => tab.startsWith(CANVAS_TAB_PREFIX);
+
+// Browser pages and canvases belong to one conversation, so pinning them across
+// every topic of the agent would reopen content that does not exist there.
+export const isDynamicTab = (tab: string) => isBrowserTab(tab) || isCanvasTab(tab);
+
+export const browserSessionIdOfTab = (baseSessionId: string, tab: string) =>
+ tab === BROWSER_TAB_KEY
+ ? baseSessionId
+ : `${baseSessionId}:tab:${tab.slice(BROWSER_TAB_PREFIX.length)}`;
diff --git a/src/features/Conversation/WorkingSidebar/index.tsx b/src/features/Conversation/WorkingSidebar/index.tsx
index 27b798d0c89..55d25bd3bc4 100644
--- a/src/features/Conversation/WorkingSidebar/index.tsx
+++ b/src/features/Conversation/WorkingSidebar/index.tsx
@@ -1,15 +1,7 @@
import type { SFSymbol } from '@lobechat/electron-client-ipc';
import { getWorkingDirEffectivePath } from '@lobechat/types';
import { nanoid } from '@lobechat/utils';
-import {
- ActionIcon,
- type DropdownItem,
- DropdownMenu,
- Flexbox,
- Icon,
- type IconProps,
- Skeleton,
-} from '@lobehub/ui';
+import { ActionIcon, type DropdownItem, DropdownMenu, Flexbox, Icon, Skeleton } from '@lobehub/ui';
import { createStaticStyles, cssVar } from '@lobehub/ui';
import { SkillsIcon } from '@lobehub/ui/icons';
import {
@@ -36,7 +28,6 @@ import {
Activity,
lazy,
memo,
- type ReactNode,
Suspense,
useCallback,
useEffect,
@@ -82,10 +73,20 @@ import { sandboxActions, sandboxSelectors, useSandboxStore } from '@/store/sandb
import { type ComposerTarget, createComposerTarget, resolveThreadComposerTarget } from '../types';
import DeferredSkeleton from './DeferredSkeleton';
+import DynamicTabPanes, { dynamicTabDescriptor } from './DynamicTabPanes';
+import {
+ BROWSER_TAB_KEY,
+ BROWSER_TAB_PREFIX,
+ type BrowserTabMetadata,
+ isBrowserTab,
+ isCanvasTab,
+ isDynamicTab,
+ type SidebarTabDescriptor,
+} from './dynamicTabs';
import FilesPane from './Files/FilesPane';
import { useFilesPaneLocation } from './Files/useFilesPaneLocation';
import { sidebarWidthBudget } from './fitsBesidePortal';
-import { MAX_PANEL_WIDTH, MIN_PANEL_WIDTH, OVERVIEW_PANEL_WIDTH } from './layout';
+import { CANVAS_MIN_WIDTH, MAX_PANEL_WIDTH, MIN_PANEL_WIDTH, OVERVIEW_PANEL_WIDTH } from './layout';
import Overview from './Overview';
import { getStatusDeviceId } from './Overview/overviewData';
import OverviewSlot from './OverviewSlot';
@@ -97,7 +98,6 @@ import WorkspaceTab from './WorkspaceTab';
import WorksSection from './WorksSection';
const ParamsSection = lazy(() => import('./ParamsSection'));
-const BrowserPane = lazy(() => import('./Browser'));
const styles = createStaticStyles(({ css }) => ({
body: css`
@@ -127,12 +127,6 @@ const styles = createStaticStyles(({ css }) => ({
add: css`
flex-shrink: 0;
`,
- favicon: css`
- width: 14px;
- height: 14px;
- border-radius: 2px;
- object-fit: contain;
- `,
overviewBody: css`
overflow-y: auto;
min-height: 0;
@@ -196,23 +190,6 @@ const OVERVIEW_TRANSITION = { duration: 0.25, ease: [0.32, 0.72, 0, 1] } as cons
// Two-pane Review (diff list + file-tree rail) is cramped below this.
const TWO_PANE_MIN_WIDTH = 560;
-interface SidebarTabDescriptor {
- icon: IconProps['icon'];
- iconNode?: ReactNode;
- key: string;
- label: ReactNode;
-}
-
-interface BrowserTabMetadata {
- faviconUrl?: string;
- title: string;
- url: string;
-}
-
-const BROWSER_TAB_KEY = 'browser';
-const BROWSER_TAB_PREFIX = 'browser:';
-const isBrowserTab = (tab: string) => tab === BROWSER_TAB_KEY || tab.startsWith(BROWSER_TAB_PREFIX);
-
interface AgentWorkingSidebarProps {
/**
* Measured width of the row this sidebar shares with the conversation and the
@@ -537,7 +514,8 @@ const AgentWorkingSidebar = memo<AgentWorkingSidebarProps>(({ availableWidth })
);
const availableTabsSignature = JSON.stringify(tabDescriptors.map((tab) => tab.key));
const isAvailableTab = useCallback(
- (tab: string) => availableTabs.has(tab) || (browserAvailable && isBrowserTab(tab)),
+ (tab: string) =>
+ availableTabs.has(tab) || (browserAvailable && isBrowserTab(tab)) || isCanvasTab(tab),
[availableTabs, browserAvailable],
);
const openTabsContextKey = topicId
@@ -570,7 +548,7 @@ const AgentWorkingSidebar = memo<AgentWorkingSidebarProps>(({ availableWidth })
const pinnedTabs = useMemo(
() =>
(pinnedTabsByAgent[pinnedTabsAgentKey] ?? []).filter(
- (tab) => !isBrowserTab(tab) && isAvailableTab(tab),
+ (tab) => !isDynamicTab(tab) && isAvailableTab(tab),
),
[isAvailableTab, pinnedTabsAgentKey, pinnedTabsByAgent],
);
@@ -702,7 +680,7 @@ const AgentWorkingSidebar = memo<AgentWorkingSidebarProps>(({ availableWidth })
const pinTab = useCallback(
(tab: string) => {
- if (!availableTabs.has(tab) || isBrowserTab(tab)) return;
+ if (!availableTabs.has(tab) || isDynamicTab(tab)) return;
updateOpenedTabs((current) => (current.includes(tab) ? current : [...current, tab]));
updatePinnedTabs((current) => (current.includes(tab) ? current : [...current, tab]));
},
@@ -749,20 +727,14 @@ const AgentWorkingSidebar = memo<AgentWorkingSidebarProps>(({ availableWidth })
const closeTab = useCallback((tab: string) => closeTabs([tab]), [closeTabs]);
const displayedTabs = openedTabs
- .map((tab): SidebarTabDescriptor | undefined => {
- if (!isBrowserTab(tab)) return availableTabs.get(tab);
- const metadata = browserTabMetadata[`${openTabsContextKey}:${tab}`];
- const fallbackLabel = t('workingPanel.browser.title');
- const label = metadata?.title?.trim() || fallbackLabel;
- return {
- icon: Globe2Icon,
- iconNode: metadata?.faviconUrl ? (
- <img alt="" className={styles.favicon} src={metadata.faviconUrl} />
- ) : undefined,
- key: tab,
- label,
- };
- })
+ .map(
+ (tab) =>
+ dynamicTabDescriptor(
+ tab,
+ browserTabMetadata[`${openTabsContextKey}:${tab}`],
+ t('workingPanel.browser.title'),
+ ) ?? availableTabs.get(tab),
+ )
.filter((tab): tab is SidebarTabDescriptor => Boolean(tab));
const createTabContextMenuItems = useCallback(
(tab: string, index: number): NativeContextMenuItem[] => {
@@ -773,7 +745,7 @@ const AgentWorkingSidebar = memo<AgentWorkingSidebarProps>(({ availableWidth })
const hasClosable = (tabs: string[]) => tabs.some((item) => !pinnedTabsSet.has(item));
return [
- ...(!isBrowserTab(tab)
+ ...(!isDynamicTab(tab)
? [
{
icon: pinned ? PinOffIcon : PinIcon,
@@ -896,7 +868,12 @@ const AgentWorkingSidebar = memo<AgentWorkingSidebarProps>(({ availableWidth })
false,
);
const reviewTwoPane = activeTab === 'review' && reviewAvailable && showReviewTree;
- const displayWidth = reviewTwoPane ? Math.max(storedWidth, TWO_PANE_MIN_WIDTH) : storedWidth;
+ const preferredMinWidth = reviewTwoPane
+ ? TWO_PANE_MIN_WIDTH
+ : isCanvasTab(activeTab)
+ ? CANVAS_MIN_WIDTH
+ : 0;
+ const displayWidth = Math.max(storedWidth, preferredMinWidth);
// Yield the row to conversation + portal when the three no longer fit. A
// stored width that merely outgrew the current row (the user dragged the
// panel out, or resized the window down) renders clamped instead of
@@ -1050,7 +1027,7 @@ const AgentWorkingSidebar = memo<AgentWorkingSidebarProps>(({ availableWidth })
defaultWidth={renderWidth}
expand={Boolean(showRightPanel) && fits}
maxWidth={maxPanelWidth}
- minWidth={MIN_PANEL_WIDTH}
+ minWidth={Math.min(Math.max(MIN_PANEL_WIDTH, preferredMinWidth), maxPanelWidth)}
style={!showRightPanel ? { visibility: 'hidden' } : undefined}
width={renderWidth}
onSizeChange={(size) => {
@@ -1177,36 +1154,25 @@ const AgentWorkingSidebar = memo<AgentWorkingSidebarProps>(({ availableWidth })
</Flexbox>
</Activity>
)}
- {browserAvailable &&
- openedTabs.filter(isBrowserTab).map((tab) => {
- const sessionId =
- tab === BROWSER_TAB_KEY
- ? browserSessionId
- : `${browserSessionId}:tab:${tab.slice(BROWSER_TAB_PREFIX.length)}`;
-
- return (
- <Flexbox
- className={activeTab === tab ? styles.pane : styles.paneHidden}
- key={sessionId}
- >
- <BrowserPane
- agentId={activeAgentId}
- composerTarget={composerTarget}
- sessionId={sessionId}
- onMetadataChange={(metadata) => {
- const metadataKey = `${openTabsContextKey}:${tab}`;
- setBrowserTabMetadata((current) =>
- current[metadataKey]?.faviconUrl === metadata.faviconUrl &&
- current[metadataKey]?.title === metadata.title &&
- current[metadataKey]?.url === metadata.url
- ? current
- : { ...current, [metadataKey]: metadata },
- );
- }}
- />
- </Flexbox>
+ <DynamicTabPanes
+ activeTab={activeTab}
+ agentId={activeAgentId}
+ browserAvailable={browserAvailable}
+ browserSessionId={browserSessionId}
+ composerTarget={composerTarget}
+ openedTabs={openedTabs}
+ visible={!!showRightPanel}
+ onBrowserMetadataChange={(tab, metadata) => {
+ const metadataKey = `${openTabsContextKey}:${tab}`;
+ setBrowserTabMetadata((current) =>
+ current[metadataKey]?.faviconUrl === metadata.faviconUrl &&
+ current[metadataKey]?.title === metadata.title &&
+ current[metadataKey]?.url === metadata.url
+ ? current
+ : { ...current, [metadataKey]: metadata },
);
- })}
+ }}
+ />
{businessTabs.map((tab) => (
<Flexbox
className={activeTab === tab.key ? styles.pane : styles.paneHidden}
diff --git a/src/features/Conversation/WorkingSidebar/layout.ts b/src/features/Conversation/WorkingSidebar/layout.ts
index 6e3cdce81d7..e8420959e82 100644
--- a/src/features/Conversation/WorkingSidebar/layout.ts
+++ b/src/features/Conversation/WorkingSidebar/layout.ts
@@ -1,6 +1,8 @@
export const OVERVIEW_PANEL_WIDTH = 340;
export const MIN_PANEL_WIDTH = 300;
export const MAX_PANEL_WIDTH = 1200;
+// A canvas is a laid-out page; narrower than this it reflows into its mobile layout.
+export const CANVAS_MIN_WIDTH = 560;
interface WorkingPanelPreference {
showRightPanel?: boolean;
diff --git a/src/features/Portal/Artifacts/Body/Renderer/HTML.tsx b/src/features/Portal/Artifacts/Body/Renderer/HTML.tsx
index cd8029691b1..a9b40d73165 100644
--- a/src/features/Portal/Artifacts/Body/Renderer/HTML.tsx
+++ b/src/features/Portal/Artifacts/Body/Renderer/HTML.tsx
@@ -17,4 +17,5 @@ const HTMLRenderer = memo<HTMLRendererProps>(
},
);
+/** Superseded by Canvas (`lobe-canvas`); kept so existing conversations keep rendering. */
export default HTMLRenderer;
diff --git a/src/features/Portal/Artifacts/Body/Renderer/React/index.tsx b/src/features/Portal/Artifacts/Body/Renderer/React/index.tsx
index b6a99a6c032..70e1178affc 100644
--- a/src/features/Portal/Artifacts/Body/Renderer/React/index.tsx
+++ b/src/features/Portal/Artifacts/Body/Renderer/React/index.tsx
@@ -33,4 +33,5 @@ const ReactRenderer = memo<ReactRendererProps>(({ code }) => {
);
});
+/** Superseded by Canvas (`lobe-canvas`); kept so existing conversations keep rendering. */
export default ReactRenderer;
diff --git a/src/features/Portal/LocalFile/PublishHtmlArtifactConfirm.tsx b/src/features/Portal/LocalFile/PublishHtmlArtifactConfirm.tsx
index 2d58038fa89..808a077a2c6 100644
--- a/src/features/Portal/LocalFile/PublishHtmlArtifactConfirm.tsx
+++ b/src/features/Portal/LocalFile/PublishHtmlArtifactConfirm.tsx
@@ -1,20 +1,12 @@
-import {
- Accordion,
- Button,
- createModal,
- Flexbox,
- ScrollArea,
- Text,
- useModalContext,
-} from '@lobehub/ui';
+import { Accordion, Flexbox, Text } from '@lobehub/ui';
import { t } from 'i18next';
import { useTranslation } from 'react-i18next';
+import { openPublishConfirm } from '@/components/PublishConfirmModal';
+
import type { ReadyWorkspaceHtmlPublishPlan } from './prepareWorkspaceHtmlPublish';
import { WORKSPACE_HTML_ARTIFACT_INLINE_MAX_BYTES } from './readWorkspaceAsset';
-const CONFIRM_BODY_MAX_HEIGHT = 'min(52vh, 360px)';
-
const PathList = ({ items }: { items: string[] }) => (
<Flexbox gap={4}>
{items.map((item) => (
@@ -25,7 +17,7 @@ const PathList = ({ items }: { items: string[] }) => (
</Flexbox>
);
-interface PublishHtmlArtifactConfirmContentProps {
+interface PublishHtmlArtifactDetailsProps {
inlinedPaths: string[];
inlineLimit: string;
missing: string[];
@@ -35,7 +27,7 @@ interface PublishHtmlArtifactConfirmContentProps {
uploadedPaths: string[];
}
-const PublishHtmlArtifactConfirmContent = ({
+const PublishHtmlArtifactDetails = ({
inlineLimit,
inlinedPaths,
missing,
@@ -43,128 +35,80 @@ const PublishHtmlArtifactConfirmContent = ({
remotes,
unsupported,
uploadedPaths,
-}: PublishHtmlArtifactConfirmContentProps) => {
+}: PublishHtmlArtifactDetailsProps) => {
const { t } = useTranslation('chat');
const showDetails = [inlinedPaths, uploadedPaths, missing, oversized, remotes, unsupported].some(
(list) => list.length > 0,
);
- return (
- <ScrollArea
- disableContentFit
- scrollFade
- style={{ maxHeight: CONFIRM_BODY_MAX_HEIGHT, overflow: 'hidden' }}
- viewportProps={{ style: { height: 'auto', maxHeight: CONFIRM_BODY_MAX_HEIGHT } }}
- >
- <Flexbox gap={8} style={{ paddingBlock: 12, paddingInline: 16 }}>
- <Text>{t('workingPanel.localFile.publish.privacy')}</Text>
- {showDetails && (
- <Accordion
- indicatorPlacement={'start'}
- variant={'borderless'}
- items={[
- {
- children: (
- <Flexbox gap={8} paddingBlock={'4px 0'}>
- {inlinedPaths.length > 0 && (
- <>
- <Text>
- {t('workingPanel.localFile.publish.inline', {
- count: inlinedPaths.length,
- limit: inlineLimit,
- })}
- </Text>
- <PathList items={inlinedPaths} />
- </>
- )}
- {uploadedPaths.length > 0 && (
- <>
- <Text>
- {t('workingPanel.localFile.publish.upload', {
- count: uploadedPaths.length,
- })}
- </Text>
- <PathList items={uploadedPaths} />
- </>
- )}
- {missing.length > 0 && (
- <Text type={'secondary'}>
- {t('workingPanel.localFile.publish.missing', { list: missing.join(', ') })}
- </Text>
- )}
- {oversized.length > 0 && (
- <Text type={'secondary'}>
- {t('workingPanel.localFile.publish.oversized', {
- list: oversized.join(', '),
- })}
- </Text>
- )}
- {unsupported.length > 0 && (
- <Text type={'secondary'}>
- {t('workingPanel.localFile.publish.unsupported', {
- list: unsupported.join(', '),
- })}
- </Text>
- )}
- {remotes.length > 0 && (
- <>
- <Text>{t('workingPanel.localFile.publish.remotes')}</Text>
- <PathList items={remotes} />
- </>
- )}
- <Text type={'secondary'}>{t('workingPanel.localFile.publish.dynamic')}</Text>
- </Flexbox>
- ),
- key: 'details',
- title: (
- <Text fontSize={12} type={'secondary'} weight={500}>
- {t('workingPanel.localFile.publish.details')}
- </Text>
- ),
- },
- ]}
- />
- )}
- <Text type={'secondary'}>{t('workingPanel.localFile.publish.note')}</Text>
- </Flexbox>
- </ScrollArea>
- );
-};
-
-const PublishHtmlArtifactConfirmFooter = ({
- okText,
- onOk,
-}: {
- okText: string;
- onOk: () => void;
-}) => {
- const { t } = useTranslation('common');
- const { close } = useModalContext();
+ if (!showDetails) return null;
return (
- <Flexbox
- horizontal
- gap={8}
- justify={'flex-end'}
- style={{ paddingBlock: 12, paddingInline: 16 }}
- >
- <Button
- onClick={() => {
- close();
- }}
- >
- {t('cancel')}
- </Button>
- <Button
- type={'primary'}
- onClick={() => {
- close();
- onOk();
- }}
- >
- {okText}
- </Button>
- </Flexbox>
+ <Accordion
+ indicatorPlacement={'start'}
+ variant={'borderless'}
+ items={[
+ {
+ children: (
+ <Flexbox gap={8} paddingBlock={'4px 0'}>
+ {inlinedPaths.length > 0 && (
+ <>
+ <Text>
+ {t('workingPanel.localFile.publish.inline', {
+ count: inlinedPaths.length,
+ limit: inlineLimit,
+ })}
+ </Text>
+ <PathList items={inlinedPaths} />
+ </>
+ )}
+ {uploadedPaths.length > 0 && (
+ <>
+ <Text>
+ {t('workingPanel.localFile.publish.upload', {
+ count: uploadedPaths.length,
+ })}
+ </Text>
+ <PathList items={uploadedPaths} />
+ </>
+ )}
+ {missing.length > 0 && (
+ <Text type={'secondary'}>
+ {t('workingPanel.localFile.publish.missing', { list: missing.join(', ') })}
+ </Text>
+ )}
+ {oversized.length > 0 && (
+ <Text type={'secondary'}>
+ {t('workingPanel.localFile.publish.oversized', {
+ list: oversized.join(', '),
+ })}
+ </Text>
+ )}
+ {unsupported.length > 0 && (
+ <Text type={'secondary'}>
+ {t('workingPanel.localFile.publish.unsupported', {
+ list: unsupported.join(', '),
+ })}
+ </Text>
+ )}
+ {remotes.length > 0 && (
+ <>
+ <Text>{t('workingPanel.localFile.publish.remotes')}</Text>
+ <PathList items={remotes} />
+ </>
+ )}
+ <Text type={'secondary'}>{t('workingPanel.localFile.publish.dynamic')}</Text>
+ </Flexbox>
+ ),
+ key: 'details',
+ title: (
+ <Text fontSize={12} type={'secondary'} weight={500}>
+ {t('workingPanel.localFile.publish.details')}
+ </Text>
+ ),
+ },
+ ]}
+ />
);
};
@@ -184,9 +128,9 @@ export const openWorkspaceHtmlPublishConfirm = ({
{ ns: 'chat' },
);
- createModal({
- content: (
- <PublishHtmlArtifactConfirmContent
+ openPublishConfirm({
+ details: (
+ <PublishHtmlArtifactDetails
inlineLimit={`${WORKSPACE_HTML_ARTIFACT_INLINE_MAX_BYTES / 1024} KB`}
inlinedPaths={plan.packed.inlinedPaths}
missing={plan.gathered.missing}
@@ -196,11 +140,8 @@ export const openWorkspaceHtmlPublishConfirm = ({
uploadedPaths={plan.packed.sidecars.map((file) => file.path)}
/>
),
- footer: <PublishHtmlArtifactConfirmFooter okText={okText} onOk={onOk} />,
- styles: {
- content: { minHeight: 0, overflow: 'hidden', padding: 0 },
- },
- title: t('workingPanel.localFile.publish.confirmTitle', { ns: 'chat' }),
- width: 420,
+ note: t('workingPanel.localFile.publish.note', { ns: 'chat' }),
+ okText,
+ onOk,
});
};
diff --git a/src/features/Portal/components/PortalMoreMenu/index.tsx b/src/features/Portal/components/PortalMoreMenu/index.tsx
index 36c3c2e06cc..b1a36009f2a 100644
--- a/src/features/Portal/components/PortalMoreMenu/index.tsx
+++ b/src/features/Portal/components/PortalMoreMenu/index.tsx
@@ -1,6 +1,12 @@
'use client';
-import { ActionIcon, copyToClipboard, DropdownMenu, toast } from '@lobehub/ui';
+import {
+ ActionIcon,
+ type ActionIconOutdent,
+ copyToClipboard,
+ DropdownMenu,
+ toast,
+} from '@lobehub/ui';
import { MoreHorizontal } from 'lucide-react';
import { memo, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
@@ -10,6 +16,7 @@ import { type PortalMoreMenuConfig } from './types';
interface PortalMoreMenuProps {
config?: PortalMoreMenuConfig;
+ outdent?: ActionIconOutdent;
}
/**
@@ -17,7 +24,7 @@ interface PortalMoreMenuProps {
* render it themselves — they declare capabilities on `PortalImpl.useMoreMenu`
* and the shared header mounts this menu in its title slot.
*/
-const PortalMoreMenu = memo<PortalMoreMenuProps>(({ config }) => {
+const PortalMoreMenu = memo<PortalMoreMenuProps>(({ config, outdent }) => {
const { t } = useTranslation('portal');
const items = useMemo(
@@ -44,6 +51,7 @@ const PortalMoreMenu = memo<PortalMoreMenuProps>(({ config }) => {
<ActionIcon
aria-label={t('moreMenu.trigger')}
icon={MoreHorizontal}
+ outdent={outdent}
size={'small'}
style={{ flex: 'none' }}
title={t('moreMenu.trigger')}
diff --git a/src/features/Work/CanvasWorkCard.tsx b/src/features/Work/CanvasWorkCard.tsx
new file mode 100644
index 00000000000..c4b38bb4012
--- /dev/null
+++ b/src/features/Work/CanvasWorkCard.tsx
@@ -0,0 +1,133 @@
+'use client';
+
+import type { WorkSummaryItem } from '@lobechat/types';
+import { cx, Flexbox, Tag, Text } from '@lobehub/ui';
+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';
+import * as stylex from '@stylexjs/stylex';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+const styles = stylex.create({
+ bar: {
+ backgroundColor: cssVar.colorFillSecondary,
+ borderRadius: 2,
+ height: 5,
+ },
+ barLong: {
+ width: '90%',
+ },
+ barMedium: {
+ width: '80%',
+ },
+ barTitle: {
+ height: 7,
+ width: '70%',
+ },
+ box: {
+ backgroundColor: cssVar.colorBgContainer,
+ borderColor: cssVar.colorBorderSecondary,
+ borderRadius: 3,
+ borderStyle: 'solid',
+ borderWidth: 1,
+ flex: '1',
+ height: 16,
+ },
+ card: {
+ backgroundColor: cssVar.colorBgElevated,
+ borderColor: cssVar.colorBorderSecondary,
+ borderRadius: cssVar.borderRadiusLG,
+ borderStyle: 'solid',
+ borderWidth: 1,
+ maxWidth: 480,
+ overflow: 'hidden',
+ width: '100%',
+ },
+ chart: {
+ backgroundImage: `linear-gradient(180deg, transparent 45%, ${cssVar.colorFillTertiary} 45%)`,
+ borderColor: cssVar.colorBorderSecondary,
+ borderRadius: 3,
+ borderStyle: 'solid',
+ borderWidth: 1,
+ height: 26,
+ },
+ clickable: {
+ borderColor: { ':hover': cssVar.colorBorder, 'default': cssVar.colorBorderSecondary },
+ cursor: 'pointer',
+ },
+ info: {
+ minWidth: 0,
+ paddingBlock: 12,
+ paddingInline: 14,
+ },
+ meta: {
+ marginBlockStart: 'auto',
+ },
+ thumb: {
+ backgroundColor: cssVar.colorBgContainerSecondary,
+ borderInlineEndColor: cssVar.colorBorderSecondary,
+ borderInlineEndStyle: 'solid',
+ borderInlineEndWidth: 1,
+ flex: 'none',
+ padding: 10,
+ width: 120,
+ },
+});
+
+interface CanvasWorkCardProps {
+ className?: string;
+ item: WorkSummaryItem;
+ onOpen?: () => void;
+}
+
+const CanvasWorkCard = memo<CanvasWorkCardProps>(({ className, item, onOpen }) => {
+ const { t } = useTranslation('chat');
+ const version = item.event.version;
+ const updatedAt = new Date(item.event.createdAt ?? item.updatedAt).toLocaleString();
+ const cardProps = stylex.props(styles.card, onOpen && styles.clickable);
+
+ return (
+ <Flexbox
+ horizontal
+ {...cardProps}
+ className={cx(cardProps.className, className)}
+ onClick={onOpen}
+ >
+ <Flexbox gap={5} {...stylex.props(styles.thumb)}>
+ <div {...stylex.props(styles.bar, styles.barTitle)} />
+ <div {...stylex.props(styles.bar, styles.barLong)} />
+ <Flexbox horizontal gap={4}>
+ <div {...stylex.props(styles.box)} />
+ <div {...stylex.props(styles.box)} />
+ <div {...stylex.props(styles.box)} />
+ </Flexbox>
+ <div {...stylex.props(styles.chart)} />
+ <div {...stylex.props(styles.bar, styles.barMedium)} />
+ </Flexbox>
+ <Flexbox flex={1} gap={4} {...stylex.props(styles.info)}>
+ <Text ellipsis strong>
+ {item.title || t('workingPanel.works.canvasUntitled')}
+ </Text>
+ {item.description && (
+ <Text ellipsis={{ rows: 2 }} fontSize={12} type={'secondary'}>
+ {item.description}
+ </Text>
+ )}
+ <Flexbox horizontal align={'center'} gap={6} {...stylex.props(styles.meta)}>
+ <Tag size={'small'}>{`v${version}`}</Tag>
+ <Text fontSize={12} type={'secondary'}>
+ {updatedAt}
+ </Text>
+ {item.url && (
+ <Tag color={'blue'} size={'small'}>
+ {t('workingPanel.works.canvasPublished')}
+ </Tag>
+ )}
+ </Flexbox>
+ </Flexbox>
+ </Flexbox>
+ );
+});
+
+CanvasWorkCard.displayName = 'CanvasWorkCard';
+
+export default CanvasWorkCard;
diff --git a/src/features/Work/WorkSummaryCard.tsx b/src/features/Work/WorkSummaryCard.tsx
index 9670a3be50d..6e0c764b1f7 100644
--- a/src/features/Work/WorkSummaryCard.tsx
+++ b/src/features/Work/WorkSummaryCard.tsx
@@ -11,6 +11,7 @@ import { useChatStore } from '@/store/chat';
import { getWorkVersionTotalTokens } from '@/utils/workCumulativeUsage';
import { formatWorkVersionCost } from '@/utils/workVersionCost';
+import CanvasWorkCard from './CanvasWorkCard';
import { getWorkTypeDescriptor, isSafeExternalUrl } from './descriptors';
import { useResourceDeletedPrompt } from './useResourceDeletedPrompt';
@@ -132,6 +133,7 @@ interface WorkSummaryCardProps {
const WorkSummaryCard = memo<WorkSummaryCardProps>(
({ className, item, onOpen, variant = 'card' }) => {
const { t } = useTranslation('chat');
+ const openCanvas = useChatStore((s) => s.openCanvas);
const openDocument = useChatStore((s) => s.openDocument);
const openFilePreview = useChatStore((s) => s.openFilePreview);
const openTaskDetail = useChatStore((s) => s.openTaskDetail);
@@ -182,6 +184,10 @@ const WorkSummaryCard = memo<WorkSummaryCardProps>(
if (!openTarget) return;
switch (openTarget.kind) {
+ case 'canvas': {
+ openCanvas(openTarget.canvasId, openTarget.version);
+ return;
+ }
case 'document': {
openDocument(openTarget.documentId, openTarget.agentDocumentId);
return;
@@ -202,6 +208,16 @@ const WorkSummaryCard = memo<WorkSummaryCardProps>(
}
};
+ if (item.type === 'canvas' && variant === 'card') {
+ return (
+ <CanvasWorkCard
+ className={className}
+ item={item}
+ onOpen={clickable ? handleOpen : undefined}
+ />
+ );
+ }
+
if (variant === 'inline') {
return (
<Flexbox
diff --git a/src/features/Work/descriptors.test.ts b/src/features/Work/descriptors.test.ts
index da847dbb828..98bdb231f99 100644
--- a/src/features/Work/descriptors.test.ts
+++ b/src/features/Work/descriptors.test.ts
@@ -98,4 +98,35 @@ describe('getWorkTypeDescriptor', () => {
kind: 'document',
});
});
+
+ describe('canvas open target', () => {
+ const canvasItem = (eventVersion: number, currentVersion: number) =>
+ ({
+ event: { version: eventVersion },
+ id: 'work-canvas-1',
+ resourceId: 'cvs_1',
+ title: 'Report',
+ type: 'canvas',
+ version: { version: currentVersion },
+ }) as any;
+
+ it('follows the latest version when the card is the current version', () => {
+ const item = canvasItem(2, 2);
+
+ expect(getWorkTypeDescriptor(item).getOpenTarget(item)).toEqual({
+ canvasId: 'cvs_1',
+ kind: 'canvas',
+ });
+ });
+
+ it('pins the version when the card shows an older version', () => {
+ const item = canvasItem(1, 2);
+
+ expect(getWorkTypeDescriptor(item).getOpenTarget(item)).toEqual({
+ canvasId: 'cvs_1',
+ kind: 'canvas',
+ version: 1,
+ });
+ });
+ });
});
diff --git a/src/features/Work/descriptors.tsx b/src/features/Work/descriptors.tsx
index 56a7ee9210a..17a78a23c1c 100644
--- a/src/features/Work/descriptors.tsx
+++ b/src/features/Work/descriptors.tsx
@@ -17,6 +17,7 @@ import {
FileTextIcon,
FileTypeIcon,
LinkIcon,
+ PanelsTopLeftIcon,
PresentationIcon,
} from 'lucide-react';
import type { ComponentType } from 'react';
@@ -51,7 +52,8 @@ export type WorkOpenTarget =
* `url` is the already-allowlisted download fallback for surfaces without a
* chat portal (WorkGallery), so they don't recompute the file-metadata lookup.
*/
- | { fileId: string; kind: 'filePreview'; url?: string };
+ | { fileId: string; kind: 'filePreview'; url?: string }
+ | { canvasId: string; kind: 'canvas'; version?: number };
/**
* Client-side allowlist for external Work URLs (defense in depth over the
@@ -159,6 +161,24 @@ const getFileWorkPath = (item: WorkItemOfType<'file'>): string | null =>
export const WORK_TYPE_DESCRIPTORS: {
[T in ListedWorkType]: WorkTypeDescriptor<WorkItemOfType<T>>;
} = {
+ canvas: {
+ getDescription: (item) => item.description?.trim() ?? null,
+ getIcon: () => PanelsTopLeftIcon,
+ getIdentifier: () => null,
+ getOpenTarget: (item) => {
+ if (!item.resourceId) return null;
+ const eventVersion = 'event' in item ? item.event?.version : undefined;
+ const currentVersion = 'version' in item ? item.version?.version : undefined;
+ // Only an older card pins its version; the current card follows edits made after it opened.
+ const pinned = eventVersion && currentVersion && eventVersion < currentVersion;
+ return {
+ canvasId: item.resourceId,
+ kind: 'canvas',
+ ...(pinned ? { version: eventVersion } : {}),
+ };
+ },
+ getTitle: (item) => item.title,
+ },
document: {
getDescription: (item) => item.description?.trim() ?? null,
getIcon: () => FileTextIcon,
diff --git a/src/features/WorkGallery/WorkPreviewCard.tsx b/src/features/WorkGallery/WorkPreviewCard.tsx
index 73d44092690..9fd4142b49e 100644
--- a/src/features/WorkGallery/WorkPreviewCard.tsx
+++ b/src/features/WorkGallery/WorkPreviewCard.tsx
@@ -125,6 +125,9 @@ interface WorkPreviewCardProps {
const workTypeKey = (item: WorkSummaryItem) => {
switch (item.resourceType) {
+ case 'canvas': {
+ return 'work.type.canvas';
+ }
case 'document': {
return 'work.type.document';
}
diff --git a/src/features/WorkGallery/useOpenWork.ts b/src/features/WorkGallery/useOpenWork.ts
index 955c79b9817..ad30ba87774 100644
--- a/src/features/WorkGallery/useOpenWork.ts
+++ b/src/features/WorkGallery/useOpenWork.ts
@@ -5,6 +5,7 @@ import { taskDetailPath } from '@/features/AgentTasks/shared/taskDetailPath';
import { openDocumentModal } from '@/features/DocumentModal/loader';
import { getWorkTypeDescriptor, isSafeExternalUrl } from '@/features/Work/descriptors';
import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { canvasService } from '@/services/canvas';
/**
* Open a Work summary item at its canonical target (document modal, external
@@ -20,6 +21,14 @@ export const useOpenWork = () => {
if (!openTarget) return;
switch (openTarget.kind) {
+ case 'canvas': {
+ void canvasService
+ .getVersion(openTarget.canvasId, openTarget.version)
+ .then(
+ (detail) => detail && window.open(detail.previewUrl, '_blank', 'noopener,noreferrer'),
+ );
+ return;
+ }
case 'document': {
void openDocumentModal(openTarget.documentId);
return;
diff --git a/src/services/canvas.ts b/src/services/canvas.ts
new file mode 100644
index 00000000000..379429dbe6e
--- /dev/null
+++ b/src/services/canvas.ts
@@ -0,0 +1,32 @@
+import { lambdaClient } from '@/libs/trpc/client';
+
+type CanvasRouter = typeof lambdaClient.canvas;
+
+export type CanvasVersionDetail = NonNullable<
+ Awaited<ReturnType<CanvasRouter['getVersion']['query']>>
+>;
+export type CanvasVersionSummary = Awaited<
+ ReturnType<CanvasRouter['listVersions']['query']>
+>[number];
+
+class CanvasService {
+ getVersion = (canvasId: string, version?: number) =>
+ lambdaClient.canvas.getVersion.query({ canvasId, version });
+
+ listVersions = (canvasId: string) => lambdaClient.canvas.listVersions.query({ canvasId });
+
+ publish = (canvasId: string) => lambdaClient.canvas.publish.mutate({ canvasId });
+
+ runAgentTool = (
+ apiName: string,
+ args: unknown,
+ context: { agentId?: string; messageId?: string; threadId?: string; topicId?: string },
+ ) =>
+ lambdaClient.canvas.runAgentTool.mutate({
+ apiName,
+ args: (args ?? {}) as Record<string, unknown>,
+ context,
+ });
+}
+
+export const canvasService = new CanvasService();
diff --git a/src/services/work.ts b/src/services/work.ts
index 20baa8a4aa3..dd689aec80b 100644
--- a/src/services/work.ts
+++ b/src/services/work.ts
@@ -1,6 +1,7 @@
import { TaskApiName, TaskIdentifier } from '@lobechat/builtin-tool-task';
import type {
ListedWorkType,
+ RegisterCanvasWorkParams,
RegisterDocumentWorkParams,
RegisterSkillToolResultWorkParams,
RegisterTaskWorkParams,
@@ -98,6 +99,9 @@ class WorkService {
registerTask = async (params: RegisterTaskWorkParams): Promise<WorkItem | null> =>
lambdaClient.work.registerTask.mutate(params);
+ registerCanvas = async (params: RegisterCanvasWorkParams): Promise<WorkItem> =>
+ lambdaClient.work.registerCanvas.mutate(params);
+
registerDocument = async (params: RegisterDocumentWorkParams): Promise<WorkItem | null> =>
lambdaClient.work.registerDocument.mutate(params);
diff --git a/src/store/chat/agents/__tests__/registerClientWorkFromIntent.test.ts b/src/store/chat/agents/__tests__/registerClientWorkFromIntent.test.ts
index f0dbf0b68ae..99364bd7885 100644
--- a/src/store/chat/agents/__tests__/registerClientWorkFromIntent.test.ts
+++ b/src/store/chat/agents/__tests__/registerClientWorkFromIntent.test.ts
@@ -5,6 +5,7 @@ const mocks = vi.hoisted(() => ({
deleteTaskWork: vi.fn(),
handleSkillToolResult: vi.fn(),
refreshConversation: vi.fn(),
+ registerCanvas: vi.fn(),
registerDocument: vi.fn(),
registerTask: vi.fn(),
}));
@@ -14,6 +15,7 @@ vi.mock('@/services/work', () => ({
deleteTaskWork: mocks.deleteTaskWork,
handleSkillToolResult: mocks.handleSkillToolResult,
refreshConversation: mocks.refreshConversation,
+ registerCanvas: mocks.registerCanvas,
registerDocument: mocks.registerDocument,
registerTask: mocks.registerTask,
},
@@ -57,6 +59,46 @@ describe('registerClientWorkFromIntent', () => {
mocks.refreshConversation.mockResolvedValue(undefined);
});
+ describe('canvas', () => {
+ it('registers the saved canvas version with the cumulative cost', async () => {
+ const metadata = {
+ entry: 'index.html',
+ fileCount: 2,
+ manifestKey: 'canvas/u/cvs_1/manifests/a.json',
+ runtimeMajor: 1,
+ totalSize: 40,
+ };
+ await registerClientWorkFromIntent({
+ ...base,
+ intent: {
+ action: 'register',
+ canvas: {
+ canvasId: 'cvs_1',
+ description: 'Up',
+ metadata,
+ title: 'Cost',
+ toolName: 'createCanvas',
+ },
+ type: 'canvas',
+ },
+ sourceToolIdentifier: 'lobe-canvas',
+ sourceToolName: 'createCanvas',
+ });
+
+ expect(mocks.registerCanvas).toHaveBeenCalledWith(
+ expect.objectContaining({
+ canvasId: 'cvs_1',
+ cumulativeCost: 0.011,
+ metadata,
+ title: 'Cost',
+ toolCallId: 'tool-call-1',
+ toolIdentifier: 'lobe-canvas',
+ topicId: 'topic-1',
+ }),
+ );
+ });
+ });
+
describe('task', () => {
it('registers each created target with the cumulative cost without refreshing per tool', async () => {
await registerClientWorkFromIntent({
diff --git a/src/store/chat/agents/registerClientWorkFromIntent.ts b/src/store/chat/agents/registerClientWorkFromIntent.ts
index a324a426d10..68c1c46f34e 100644
--- a/src/store/chat/agents/registerClientWorkFromIntent.ts
+++ b/src/store/chat/agents/registerClientWorkFromIntent.ts
@@ -64,6 +64,7 @@ export const registerClientWorkFromIntent = async ({
// document-delete intent a no-op.
deleteTaskWork: (params) => workService.deleteTaskWork(params),
handleSkillToolResult: (params) => workService.handleSkillToolResult(params),
+ registerCanvas: (params) => workService.registerCanvas(params),
registerDocument: (params) => workService.registerDocument(params),
registerTask: (params) => workService.registerTask(params),
},
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.preserveWorks.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.preserveWorks.test.ts
new file mode 100644
index 00000000000..68b95a64130
--- /dev/null
+++ b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.preserveWorks.test.ts
@@ -0,0 +1,95 @@
+import { act, renderHook } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { agentService } from '@/services/agent';
+import { aiChatService } from '@/services/aiChat';
+import { messageMapKey } from '@/store/chat/utils/messageMapKey';
+import { getSessionStoreState } from '@/store/session';
+import { useUserStore } from '@/store/user';
+
+import { useChatStore } from '../../../../store';
+import { createMockAgentConfig, createMockMessage, TEST_CONTENT, TEST_IDS } from './fixtures';
+import { resetTestEnvironment, setupMockSelectors, spyOnMessageService } from './helpers';
+
+vi.mock('@/services/resourcePermission', () => ({
+ resourcePermissionService: { getGeneralAccess: vi.fn() },
+}));
+
+vi.mock('@/libs/trpc/client', () => ({
+ lambdaClient: {
+ session: { updateSession: { mutate: vi.fn().mockResolvedValue(undefined) } },
+ },
+}));
+
+beforeEach(() => {
+ resetTestEnvironment();
+ setupMockSelectors();
+ spyOnMessageService();
+ vi.spyOn(getSessionStoreState(), 'triggerSessionUpdate').mockResolvedValue(undefined);
+ vi.spyOn(agentService, 'getAgentConfigById').mockResolvedValue(createMockAgentConfig() as any);
+ useUserStore.setState({ workspaceUserPreference: {} });
+
+ act(() => {
+ useChatStore.setState({
+ executeClientAgent: vi.fn(),
+ mainInputEditor: null,
+ refreshMessages: vi.fn(),
+ refreshTopic: vi.fn(),
+ });
+ });
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+describe('sendMessage server response', () => {
+ it('keeps the Work summaries of earlier replies that the send response omits', async () => {
+ const agentId = TEST_IDS.SESSION_ID;
+ const topicId = TEST_IDS.TOPIC_ID;
+ const works = [{ event: { version: 1 }, id: 'work-1', resourceId: 'cvs_1', type: 'canvas' }];
+ const earlierReply = createMockMessage({ id: 'earlier-reply', role: 'assistant', topicId });
+ const key = messageMapKey({ agentId, topicId });
+
+ act(() => {
+ useChatStore.setState({
+ activeAgentId: agentId,
+ activeTopicId: topicId,
+ dbMessagesMap: { [key]: [{ ...earlierReply, works } as any] },
+ messagesMap: { [key]: [{ ...earlierReply, works } as any] },
+ });
+ });
+
+ vi.spyOn(aiChatService, 'sendMessageInServer').mockResolvedValue({
+ assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,
+ messages: [
+ earlierReply,
+ createMockMessage({
+ id: TEST_IDS.USER_MESSAGE_ID,
+ parentId: earlierReply.id,
+ role: 'user',
+ topicId,
+ }),
+ createMockMessage({
+ id: TEST_IDS.ASSISTANT_MESSAGE_ID,
+ parentId: TEST_IDS.USER_MESSAGE_ID,
+ role: 'assistant',
+ topicId,
+ }),
+ ],
+ topicId,
+ userMessageId: TEST_IDS.USER_MESSAGE_ID,
+ } as any);
+
+ const { result } = renderHook(() => useChatStore());
+ await act(async () => {
+ await result.current.sendMessage({
+ context: { agentId, threadId: null, topicId },
+ message: TEST_CONTENT.USER_MESSAGE,
+ });
+ });
+
+ const stored = useChatStore.getState().dbMessagesMap[key];
+ expect(stored.find((message) => message.id === earlierReply.id)?.works).toEqual(works);
+ });
+});
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.discoverableManifests.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.discoverableManifests.test.ts
new file mode 100644
index 00000000000..21cce23ef81
--- /dev/null
+++ b/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.discoverableManifests.test.ts
@@ -0,0 +1,58 @@
+import { act } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import * as toolEngineering from '@/helpers/toolEngineering';
+import * as agentConfigResolver from '@/services/chat/mecha/agentConfigResolver';
+import { useToolStore } from '@/store/tool';
+
+import { useChatStore } from '../../../../store';
+import {
+ createMockAgentConfig,
+ createMockChatConfig,
+ createMockMessage,
+ TEST_IDS,
+} from './fixtures';
+import { resetTestEnvironment } from './helpers';
+
+const discoverableTool = {
+ identifier: 'test-discoverable',
+ manifest: {
+ api: [{ description: 'run', name: 'run', parameters: {} }],
+ identifier: 'test-discoverable',
+ meta: {},
+ type: 'builtin',
+ },
+ type: 'builtin',
+} as any;
+
+describe('internal_createAgentState manifest map', () => {
+ beforeEach(() => {
+ resetTestEnvironment();
+ vi.spyOn(agentConfigResolver, 'resolveAgentConfig').mockReturnValue({
+ agentConfig: createMockAgentConfig(),
+ chatConfig: createMockChatConfig(),
+ isBuiltinAgent: false,
+ plugins: [],
+ });
+ vi.spyOn(toolEngineering, 'createAgentToolsEngine').mockReturnValue({
+ generateToolsDetailed: vi
+ .fn()
+ .mockReturnValue({ enabledManifests: [], enabledToolIds: [], tools: [] }),
+ } as any);
+ act(() => {
+ useToolStore.setState({ builtinTools: [discoverableTool] });
+ });
+ });
+
+ it('carries discoverable manifests so a tool activated mid-run keeps its own approval policy', () => {
+ const { state } = useChatStore.getState().internal_createAgentState({
+ agentId: TEST_IDS.SESSION_ID,
+ messages: [createMockMessage()],
+ parentMessageId: TEST_IDS.USER_MESSAGE_ID,
+ topicId: TEST_IDS.TOPIC_ID,
+ });
+
+ expect(state.operationToolSet?.manifestMap['test-discoverable']).toBeDefined();
+ expect(state.operationToolSet?.enabledToolIds).not.toContain('test-discoverable');
+ });
+});
diff --git a/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.workRefresh.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.workRefresh.test.ts
new file mode 100644
index 00000000000..16aa77abcb7
--- /dev/null
+++ b/src/store/chat/slices/agentRun/actions/__tests__/streamingExecutor.workRefresh.test.ts
@@ -0,0 +1,131 @@
+import { type UIChatMessage } from '@lobechat/types';
+import { act, renderHook } from '@testing-library/react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { chatService } from '@/services/chat';
+import { workService } from '@/services/work';
+import { useAgentStore } from '@/store/agent';
+import { useAiInfraStore } from '@/store/aiInfra';
+
+import { useChatStore } from '../../../../store';
+import { messageMapKey } from '../../../../utils/messageMapKey';
+import { TEST_CONTENT, TEST_IDS } from './fixtures';
+import { resetTestEnvironment, setupMockSelectors, spyOnMessageService } from './helpers';
+
+vi.mock('@/utils/localStorage', () => {
+ class AsyncLocalStorage<State> {
+ getFromLocalStorageSync(): State {
+ return {} as State;
+ }
+
+ async getFromLocalStorage(): Promise<State> {
+ return {} as State;
+ }
+
+ async saveToLocalStorage(): Promise<void> {
+ return undefined;
+ }
+ }
+
+ return { AsyncLocalStorage };
+});
+vi.mock('@/store/chat/slices/agentRun/actions/lifecycle/agentSignalBridge', () => ({
+ emitClientAgentSignalSourceEvent: vi.fn().mockResolvedValue(undefined),
+}));
+vi.mock('@/services/electron/completionSound', () => ({
+ completionSoundService: {
+ getNotificationSoundFile: vi.fn().mockResolvedValue(undefined),
+ play: vi.fn().mockResolvedValue(undefined),
+ },
+}));
+
+const realExecAgentRuntime = useChatStore.getState().executeClientAgent;
+const context = { agentId: TEST_IDS.SESSION_ID, topicId: TEST_IDS.TOPIC_ID };
+
+const runOnce = async () => {
+ const userMessage = {
+ content: TEST_CONTENT.USER_MESSAGE,
+ id: TEST_IDS.USER_MESSAGE_ID,
+ role: 'user',
+ sessionId: TEST_IDS.SESSION_ID,
+ topicId: TEST_IDS.TOPIC_ID,
+ } as UIChatMessage;
+ act(() => {
+ useChatStore.setState((state) => ({
+ dbMessagesMap: { ...state.dbMessagesMap, [messageMapKey(context)]: [userMessage] },
+ executeClientAgent: realExecAgentRuntime,
+ }));
+ });
+
+ vi.spyOn(chatService, 'buildAssistantMessageContext').mockImplementation(
+ async (params, options) => ({
+ options: options ?? {},
+ params: { ...params, messages: params.messages as any } as any,
+ replayAssistantReasoning: false,
+ }),
+ );
+ vi.spyOn(chatService, 'getChatCompletion').mockImplementation(async (_params, options) => {
+ options?.onMessageHandle?.({ text: TEST_CONTENT.AI_RESPONSE, type: 'text' } as any);
+ await options?.onFinish?.(TEST_CONTENT.AI_RESPONSE, {} as any);
+ return new Response();
+ });
+
+ const { result } = renderHook(() => useChatStore());
+ const statusesAtRefresh: (string | undefined)[] = [];
+ const refreshMessages = vi.fn(async () => {
+ const op = Object.values(useChatStore.getState().operations).find(
+ (operation) => operation.type === 'execAgentRuntime',
+ );
+ statusesAtRefresh.push(op?.status);
+ });
+ act(() => {
+ useChatStore.setState({ refreshMessages });
+ });
+
+ await act(async () => {
+ await result.current.executeClientAgent({
+ context,
+ messages: [userMessage],
+ parentMessageId: userMessage.id,
+ parentMessageType: 'user',
+ });
+ });
+
+ return statusesAtRefresh;
+};
+
+beforeEach(() => {
+ resetTestEnvironment();
+ setupMockSelectors();
+ spyOnMessageService();
+ act(() => {
+ useAgentStore.setState({ availableAgents: [] });
+ useAiInfraStore.setState({ isInitAiProviderRuntimeState: true });
+ });
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+describe('executeClientAgent Work refresh', () => {
+ it('re-reads the transcript after the run completes when it registered a Work', async () => {
+ vi.spyOn(workService, 'listByRootOperation').mockResolvedValue([
+ { id: 'registered-work' } as Awaited<
+ ReturnType<typeof workService.listByRootOperation>
+ >[number],
+ ]);
+
+ const statuses = await runOnce();
+
+ expect(statuses.at(-1)).toBe('completed');
+ });
+
+ it('keeps a single in-run refresh when the run registered no Work', async () => {
+ vi.spyOn(workService, 'listByRootOperation').mockResolvedValue([]);
+
+ const statuses = await runOnce();
+
+ expect(statuses).toEqual(['running']);
+ });
+});
diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
index 4813bd0254d..afe9a359615 100644
--- a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts
@@ -139,10 +139,7 @@ import {
parseSingleAgentMentionDirectRoute,
processCommands,
} from './commandBus';
-import {
- attachSendTimeMetadataToUserMessage,
- mergePartialPersistedMessages,
-} from './persistedMessages';
+import { mergePartialPersistedMessages, resolveSendResponseMessages } from './persistedMessages';
import { resolveExistingTopicForRun } from './resolveExistingTopic';
/**
@@ -2153,25 +2150,23 @@ export class ConversationLifecycleActionImpl {
finalMessageKey,
);
this.#get().moveVoiceMessages(operationContext, finalContext);
- const persistedMessages = attachSendTimeMetadataToUserMessage(
- data.messages,
- data.userMessageId,
- userMessageMetadata,
- );
data = {
...data,
- messages: responseMeta.__isPartialMessages
- ? mergePartialPersistedMessages(
- this.#get().messagesMap[finalMessageKey] || [],
- persistedMessages,
- [tempId, tempAssistantId],
- )
- : persistedMessages,
+ messages: resolveSendResponseMessages({
+ currentMessages: this.#get().messagesMap[finalMessageKey] || [],
+ isPartial: !!responseMeta.__isPartialMessages,
+ messages: data.messages,
+ replacedMessageIds: [tempId, tempAssistantId],
+ userMessageId: data.userMessageId,
+ userMessageMetadata,
+ }),
};
+ // The send response skips Work summaries; keep the ones earlier replies already carry.
this.#get().replaceMessages(data.messages, {
context: finalContext,
action: 'sendMessage/serverResponse',
+ preserveWorks: true,
});
if (isCreateNewTopic && data.topicId) {
diff --git a/src/store/chat/slices/agentRun/actions/entries/persistedMessages.ts b/src/store/chat/slices/agentRun/actions/entries/persistedMessages.ts
index c3914c58800..c06eb051251 100644
--- a/src/store/chat/slices/agentRun/actions/entries/persistedMessages.ts
+++ b/src/store/chat/slices/agentRun/actions/entries/persistedMessages.ts
@@ -47,3 +47,28 @@ export const mergePartialPersistedMessages = (
...persistedMessages,
];
};
+
+export const resolveSendResponseMessages = ({
+ currentMessages,
+ isPartial,
+ messages,
+ replacedMessageIds,
+ userMessageId,
+ userMessageMetadata,
+}: {
+ currentMessages: UIChatMessage[];
+ isPartial: boolean;
+ messages: UIChatMessage[];
+ replacedMessageIds: string[];
+ userMessageId: string;
+ userMessageMetadata: MessageMetadata | undefined;
+}): UIChatMessage[] => {
+ const persisted = attachSendTimeMetadataToUserMessage(
+ messages,
+ userMessageId,
+ userMessageMetadata,
+ );
+ return isPartial
+ ? mergePartialPersistedMessages(currentMessages, persisted, replacedMessageIds)
+ : persisted;
+};
diff --git a/src/store/chat/slices/agentRun/actions/transports/client/discoverableManifests.test.ts b/src/store/chat/slices/agentRun/actions/transports/client/discoverableManifests.test.ts
new file mode 100644
index 00000000000..01b7d515334
--- /dev/null
+++ b/src/store/chat/slices/agentRun/actions/transports/client/discoverableManifests.test.ts
@@ -0,0 +1,34 @@
+import { describe, expect, it } from 'vitest';
+
+import { initialState } from '@/store/tool/initialState';
+
+import { buildRunManifestMap } from './discoverableManifests';
+
+const builtin = (identifier: string, discoverable?: boolean) =>
+ ({
+ discoverable,
+ identifier,
+ manifest: { api: [], identifier, meta: {}, type: 'builtin' },
+ type: 'builtin',
+ }) as any;
+
+describe('buildRunManifestMap', () => {
+ const state = {
+ ...initialState,
+ builtinTools: [
+ builtin('test-enabled'),
+ builtin('test-discoverable'),
+ builtin('test-hidden', false),
+ ],
+ } as any;
+
+ it('keeps discoverable tools so a tool activated mid-run is not treated as unknown', () => {
+ const enabled = { api: [{ name: 'run' }], identifier: 'test-enabled' } as any;
+
+ const map = buildRunManifestMap(state, [enabled]);
+
+ expect(map['test-enabled']).toBe(enabled);
+ expect(map['test-discoverable']?.identifier).toBe('test-discoverable');
+ expect(map['test-hidden']).toBeUndefined();
+ });
+});
diff --git a/src/store/chat/slices/agentRun/actions/transports/client/discoverableManifests.ts b/src/store/chat/slices/agentRun/actions/transports/client/discoverableManifests.ts
new file mode 100644
index 00000000000..063ef80c592
--- /dev/null
+++ b/src/store/chat/slices/agentRun/actions/transports/client/discoverableManifests.ts
@@ -0,0 +1,21 @@
+import type { LobeToolManifest } from '@lobechat/context-engine';
+
+import type { ToolStoreState } from '@/store/tool/initialState';
+import { toolSelectors } from '@/store/tool/selectors/tool';
+
+// Mirrors the server's discovery pool: the map is broader than `enabledToolIds`, so a
+// tool activated mid-run is looked up by the approval guard instead of being unknown.
+export const buildRunManifestMap = (
+ toolState: ToolStoreState,
+ enabledManifests: LobeToolManifest[],
+): Record<string, LobeToolManifest> => {
+ const map: Record<string, LobeToolManifest> = {};
+
+ for (const { identifier } of toolSelectors.availableToolsForDiscovery(toolState)) {
+ const manifest = toolSelectors.getManifestById(identifier)(toolState);
+ if (manifest) map[identifier] = manifest as LobeToolManifest;
+ }
+ for (const manifest of enabledManifests) map[manifest.identifier] = manifest;
+
+ return map;
+};
diff --git a/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts b/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts
index 44a45292058..8d18e89d046 100644
--- a/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts
@@ -63,6 +63,7 @@ import { messageMapKey } from '@/store/chat/utils/messageMapKey';
import { getElectronStoreState } from '@/store/electron';
import { getGoalStoreState } from '@/store/goal';
import { getServerConfigStoreState, serverConfigSelectors } from '@/store/serverConfig';
+import { getToolStoreState } from '@/store/tool';
import { pageAgentRuntime } from '@/store/tool/slices/builtin/executors/pageAgentRuntime';
import { type StoreSetter } from '@/store/types';
import { toolInterventionSelectors } from '@/store/user/selectors';
@@ -71,6 +72,7 @@ import { getUserStoreState } from '@/store/user/store';
import { buildRunLifecycle } from '../../lifecycle/buildRunLifecycle';
import type { RunParkedReason, RunScope } from '../../lifecycle/types';
import { buildViewedTaskPrompt } from '../viewedTaskPrompt';
+import { buildRunManifestMap } from './discoverableManifests';
const log = debug('lobe-store:streaming-executor');
@@ -312,9 +314,9 @@ export class StreamingExecutorActionImpl {
});
// Use enabledManifests directly to avoid getEnabledPluginManifests adding default tools again
- const toolManifestMap = Object.fromEntries(
- enabledManifests.map((manifest) => [manifest.identifier, manifest]),
- );
+ const toolManifestMap = disableTools
+ ? Object.fromEntries(enabledManifests.map((manifest) => [manifest.identifier, manifest]))
+ : buildRunManifestMap(getToolStoreState(), enabledManifests);
// Merge tools generation result into agentConfig for chatService to use
const agentConfigWithTools = {
@@ -925,6 +927,7 @@ export class StreamingExecutorActionImpl {
// Registered Works survive message folding; anchor them before refreshing
// the message list so its summary query can attach them to the final reply.
const finalAssistantId = state.metadata?.workAssistantMessageId;
+ let anchoredWork = false;
if (state.status === 'done' && typeof finalAssistantId === 'string') {
try {
const works = await workService.listByRootOperation({
@@ -932,6 +935,7 @@ export class StreamingExecutorActionImpl {
rootOperationId: operationId,
});
if (works.length > 0) {
+ anchoredWork = true;
await messageService.updateMessageMetadata(
finalAssistantId,
{
@@ -991,6 +995,10 @@ export class StreamingExecutorActionImpl {
// A queued follow-up sendMessage was scheduled — skip the post-run notification.
if (requeued) return;
+ // The run-end refresh above lands while this operation still counts as running, so
+ // the transcript keeps its streamed rows and drops the Work summaries the server attached.
+ if (anchoredWork) await this.#get().refreshMessages(context);
+
await runLifecycle.afterRunComplete(completeEvent);
// Return usage and cost data for caller to use
diff --git a/src/store/chat/slices/portal/action.canvas.test.ts b/src/store/chat/slices/portal/action.canvas.test.ts
new file mode 100644
index 00000000000..b1e66aa51db
--- /dev/null
+++ b/src/store/chat/slices/portal/action.canvas.test.ts
@@ -0,0 +1,38 @@
+import { act, renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it } from 'vitest';
+
+import { useChatStore } from '@/store/chat';
+import { useGlobalStore } from '@/store/global';
+
+describe('openCanvas', () => {
+ beforeEach(() => {
+ useGlobalStore.setState({ isStatusInit: true });
+ });
+
+ it('opens an existing canvas as a working sidebar tab', () => {
+ const { result } = renderHook(() => useChatStore());
+
+ act(() => {
+ result.current.clearPortalStack();
+ result.current.openCanvas('cvs_1', 2);
+ });
+
+ expect(result.current.showPortal).toBe(false);
+ expect(result.current.canvasTabVersions).toEqual({ cvs_1: 2 });
+ expect(useGlobalStore.getState().status.showRightPanel).toBe(true);
+ expect(useGlobalStore.getState().status.workingSidebarTab).toBe('canvas:cvs_1');
+ });
+
+ it('follows the latest version again when reopened without one', () => {
+ const { result } = renderHook(() => useChatStore());
+
+ act(() => {
+ result.current.openCanvas('cvs_1', 2);
+ result.current.openCanvas('cvs_2', 1);
+ result.current.openCanvas('cvs_1');
+ });
+
+ expect(result.current.canvasTabVersions).toEqual({ cvs_2: 1 });
+ expect(useGlobalStore.getState().status.workingSidebarTab).toBe('canvas:cvs_1');
+ });
+});
diff --git a/src/store/chat/slices/portal/action.ts b/src/store/chat/slices/portal/action.ts
index 71993893af1..73bcf7fcc03 100644
--- a/src/store/chat/slices/portal/action.ts
+++ b/src/store/chat/slices/portal/action.ts
@@ -3,6 +3,7 @@ import type { LayersEnum, TopicCommentItem } from '@lobechat/types';
import { projectFileService } from '@/services/projectFile';
import { type ChatStore } from '@/store/chat/store';
import { useGlobalStore } from '@/store/global';
+import { canvasTabKey } from '@/store/global/initialState';
import { getServerConfigStoreState } from '@/store/serverConfig';
import { type StoreSetter } from '@/store/types';
import { type PortalArtifact } from '@/types/artifact';
@@ -703,6 +704,20 @@ export class ChatPortalActionImpl {
});
};
+ openCanvas = (canvasId: string, version?: number): void => {
+ const { [canvasId]: _previous, ...canvasTabVersions } = this.#get().canvasTabVersions;
+ this.#set(
+ {
+ canvasTabVersions: version
+ ? { ...canvasTabVersions, [canvasId]: version }
+ : canvasTabVersions,
+ },
+ false,
+ 'openCanvas',
+ );
+ useGlobalStore.getState().openWorkingSidebar(canvasTabKey(canvasId));
+ };
+
openNotebook = (): void => {
this.#get().pushPortalView({ type: PortalViewType.Notebook });
};
diff --git a/src/store/chat/slices/portal/initialState.ts b/src/store/chat/slices/portal/initialState.ts
index 8a4c87a4f0d..ca5a886e0e2 100644
--- a/src/store/chat/slices/portal/initialState.ts
+++ b/src/store/chat/slices/portal/initialState.ts
@@ -145,6 +145,9 @@ export interface ChatPortalState {
/** Path of the currently active tab; kept for legacy consumers that only need display/open path. */
activeLocalFilePath?: string;
+ /** Version a canvas tab is held at; a canvas absent here follows its latest version. */
+ canvasTabVersions: Record<string, number>;
+
/** Unsaved edit buffers keyed by file path. Presence implies the file is dirty. */
dirtyLocalFileContents: Record<string, string>;
@@ -174,6 +177,7 @@ export interface ChatPortalState {
export const initialChatPortalState: ChatPortalState = {
activeLocalFileIdsByScope: {},
+ canvasTabVersions: {},
dirtyLocalFileContents: {},
openLocalFiles: [],
portalArtifactDisplayMode: ArtifactDisplayMode.Preview,
diff --git a/src/store/global/initialState.ts b/src/store/global/initialState.ts
index c50ed053ac9..47c4c0c9be6 100644
--- a/src/store/global/initialState.ts
+++ b/src/store/global/initialState.ts
@@ -49,6 +49,11 @@ export type WorkingSidebarTab =
| 'web'
| (string & {});
+export const CANVAS_TAB_PREFIX = 'canvas:';
+export const canvasTabKey = (canvasId: string) => `${CANVAS_TAB_PREFIX}${canvasId}`;
+export const canvasIdOfTab = (tab: string) =>
+ tab.startsWith(CANVAS_TAB_PREFIX) ? tab.slice(CANVAS_TAB_PREFIX.length) : undefined;
+
export const DEFAULT_RESOURCE_MANAGER_COLUMN_WIDTHS = {
date: 160,
name: 574,
diff --git a/src/store/tool/slices/builtin/executors/catalog.ts b/src/store/tool/slices/builtin/executors/catalog.ts
index 132fe967e01..bff06430a7f 100644
--- a/src/store/tool/slices/builtin/executors/catalog.ts
+++ b/src/store/tool/slices/builtin/executors/catalog.ts
@@ -35,6 +35,7 @@ import {
import { activatorExecutor } from './lobe-activator';
import { agentDocumentsExecutor } from './lobe-agent-documents';
import { attachmentsExecutor } from './lobe-attachments';
+import { canvasExecutor } from './lobe-canvas';
import { messageExecutor } from './lobe-message';
import { notebookExecutor } from './lobe-notebook';
import { pageAgentExecutor } from './lobe-page-agent';
@@ -67,6 +68,7 @@ export const builtinToolExecutors = [
attachmentsExecutor,
auvExecutor,
calculatorExecutor,
+ canvasExecutor,
cloudSandboxExecutor,
credsExecutor,
groupAgentBuilderExecutor,
diff --git a/src/store/tool/slices/builtin/executors/lobe-canvas.test.ts b/src/store/tool/slices/builtin/executors/lobe-canvas.test.ts
new file mode 100644
index 00000000000..1eae326e883
--- /dev/null
+++ b/src/store/tool/slices/builtin/executors/lobe-canvas.test.ts
@@ -0,0 +1,85 @@
+import { CanvasApiName } from '@lobechat/builtin-tool-canvas';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { takeWorkIntent } from '@/utils/clientWorkIntentStash';
+
+const { runAgentTool } = vi.hoisted(() => ({ runAgentTool: vi.fn() }));
+
+vi.mock('@/services/canvas', () => ({ canvasService: { runAgentTool } }));
+
+const intent = {
+ action: 'register' as const,
+ canvas: {
+ canvasId: 'cvs_1',
+ description: null,
+ metadata: {
+ entry: 'index.html',
+ fileCount: 1,
+ manifestKey: 'canvas/u/cvs_1/manifests/a.json',
+ runtimeMajor: 1,
+ totalSize: 10,
+ },
+ title: 'Cost',
+ toolName: 'createCanvas',
+ },
+ type: 'canvas' as const,
+};
+
+beforeEach(() => {
+ runAgentTool.mockReset();
+});
+
+describe('canvasExecutor', () => {
+ it('exposes every Canvas API', async () => {
+ const { canvasExecutor } = await import('./lobe-canvas');
+
+ for (const api of Object.values(CanvasApiName)) expect(canvasExecutor.hasApi(api)).toBe(true);
+ });
+
+ it('runs the call server-side and stashes the Work intent for call_tool', async () => {
+ const { canvasExecutor } = await import('./lobe-canvas');
+ runAgentTool.mockResolvedValue({
+ intent,
+ output: { content: 'Saved canvas cvs_1', state: { canvasId: 'cvs_1' }, success: true },
+ });
+
+ const result = await canvasExecutor.invoke(
+ CanvasApiName.createCanvas,
+ { files: [], title: 'Cost' },
+ {
+ agentId: 'agt_1',
+ messageId: 'msg_1',
+ threadId: 'thd_1',
+ toolCallId: 'call_1',
+ topicId: 'tpc_1',
+ } as any,
+ );
+
+ expect(runAgentTool).toHaveBeenCalledWith(
+ CanvasApiName.createCanvas,
+ { files: [], title: 'Cost' },
+ { agentId: 'agt_1', messageId: 'msg_1', threadId: 'thd_1', topicId: 'tpc_1' },
+ );
+ expect(result).toEqual({
+ content: 'Saved canvas cvs_1',
+ state: { canvasId: 'cvs_1' },
+ success: true,
+ });
+ expect(takeWorkIntent('call_1')).toEqual(intent);
+ });
+
+ it('turns a refused save into a failed result without a Work intent', async () => {
+ const { canvasExecutor } = await import('./lobe-canvas');
+ runAgentTool.mockResolvedValue({
+ output: { content: 'The canvas was not saved.', state: { issues: [] }, success: false },
+ });
+
+ const result = await canvasExecutor.invoke(CanvasApiName.updateCanvas, { canvasId: 'cvs_1' }, {
+ toolCallId: 'call_2',
+ topicId: 'tpc_1',
+ } as any);
+
+ expect(result).toMatchObject({ content: 'The canvas was not saved.', success: false });
+ expect(takeWorkIntent('call_2')).toBeUndefined();
+ });
+});
diff --git a/src/store/tool/slices/builtin/executors/lobe-canvas.ts b/src/store/tool/slices/builtin/executors/lobe-canvas.ts
new file mode 100644
index 00000000000..d356e6af3fe
--- /dev/null
+++ b/src/store/tool/slices/builtin/executors/lobe-canvas.ts
@@ -0,0 +1,62 @@
+import { CanvasApiName, CanvasIdentifier } from '@lobechat/builtin-tool-canvas';
+import type { BuiltinToolContext, BuiltinToolResult } from '@lobechat/types';
+import { BaseExecutor } from '@lobechat/types';
+
+import { canvasService } from '@/services/canvas';
+import { stashWorkIntent } from '@/utils/clientWorkIntentStash';
+
+class CanvasExecutor extends BaseExecutor<typeof CanvasApiName> {
+ readonly identifier = CanvasIdentifier;
+ protected readonly apiEnum = CanvasApiName;
+
+ readCanvasGuide = (params: unknown, ctx?: BuiltinToolContext) =>
+ this.run(CanvasApiName.readCanvasGuide, params, ctx);
+
+ createCanvas = (params: unknown, ctx?: BuiltinToolContext) =>
+ this.run(CanvasApiName.createCanvas, params, ctx);
+
+ updateCanvas = (params: unknown, ctx?: BuiltinToolContext) =>
+ this.run(CanvasApiName.updateCanvas, params, ctx);
+
+ readCanvas = (params: unknown, ctx?: BuiltinToolContext) =>
+ this.run(CanvasApiName.readCanvas, params, ctx);
+
+ listCanvases = (params: unknown, ctx?: BuiltinToolContext) =>
+ this.run(CanvasApiName.listCanvases, params, ctx);
+
+ private run = async (
+ apiName: string,
+ params: unknown,
+ ctx?: BuiltinToolContext,
+ ): Promise<BuiltinToolResult> => {
+ try {
+ const { intent, output } = await canvasService.runAgentTool(apiName, params, {
+ agentId: ctx?.agentId,
+ messageId: ctx?.messageId,
+ threadId: ctx?.threadId ?? undefined,
+ topicId: ctx?.topicId ?? undefined,
+ });
+ if (intent) stashWorkIntent(ctx?.toolCallId, intent);
+
+ const content = output.content || 'Canvas tool returned no content';
+ if (!output.success) {
+ return {
+ content,
+ error: { body: output.error, message: content, type: 'PluginServerError' },
+ state: output.state,
+ success: false,
+ };
+ }
+ return { content, state: output.state, success: true };
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ return {
+ content: `Failed to run ${apiName}: ${message}`,
+ error: { message, type: 'CanvasToolFailed' },
+ success: false,
+ };
+ }
+ };
+}
+
+export const canvasExecutor = new CanvasExecutor();
diff --git a/src/types/canvasRuntime.d.ts b/src/types/canvasRuntime.d.ts
new file mode 100644
index 00000000000..38279c6271f
--- /dev/null
+++ b/src/types/canvasRuntime.d.ts
@@ -0,0 +1,4 @@
+declare module 'virtual:canvas-runtime' {
+ const manifestUrl: string;
+ export default manifestUrl;
+}
diff --git a/vite.config.ts b/vite.config.ts
index 7bcdcc01bdb..033d495ddf0 100644
--- a/vite.config.ts
+++ b/vite.config.ts
@@ -7,6 +7,7 @@ import type { PluginOption, ViteDevServer } from 'vite';
import { defineConfig, loadEnv } from 'vite';
import { VitePWA } from 'vite-plugin-pwa';
+import { canvasRuntimeEntries } from './plugins/vite/canvasRuntime';
import { customBrandingLoadingScreen } from './plugins/vite/customBrandingLoadingScreen';
import { viteEnvRestartKeys } from './plugins/vite/envRestartKeys';
import {
@@ -118,7 +119,16 @@ export default defineConfig({
__dirname,
isAuth ? 'index.auth.html' : isMobile ? 'index.mobile.html' : 'index.html',
),
- output: createSharedRolldownOutput({ strictExecutionOrder: true }),
+ output: createSharedRolldownOutput({
+ initialEntries: {
+ main: path.resolve(
+ __dirname,
+ isAuth ? 'index.auth.html' : isMobile ? 'index.mobile.html' : 'index.html',
+ ),
+ ...(!isAuth && canvasRuntimeEntries),
+ },
+ strictExecutionOrder: true,
+ }),
preserveEntrySignatures: 'allow-extension',
},
},
diff --git a/vitest.config.mts b/vitest.config.mts
index 0321518bdd5..6a1f0901612 100644
--- a/vitest.config.mts
+++ b/vitest.config.mts
@@ -3,6 +3,7 @@ import { dirname, join, resolve } from 'node:path';
import tsconfigPaths from 'vite-tsconfig-paths';
import { defineConfig } from 'vitest/config';
+import { canvasRuntime } from './plugins/vite/canvasRuntime';
import { stylexPlugin, stylexTokenModules } from './plugins/vite/stylex';
if (process.env.NODE_ENV === 'production') {
@@ -79,6 +80,7 @@ export default defineConfig({
exclude: ['crypto', 'util', 'tty'],
},
plugins: [
+ canvasRuntime(),
stylexPlugin(),
tsconfigPaths({ projects: ['.', './apps/share', './apps/workbench'] }),
// Let `.md` imports resolve to their raw text content so Rollup/Vitest