🤯 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.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(artboard): persist artboards, discuss them on the board, and wire them into the agent, Works and acceptance (#22204)
Innei40060aa9e742
diff --git a/.agents/acceptance/PROJECT.md b/.agents/acceptance/PROJECT.mdindex 85530ff29e3..dce7eb08891 100644--- a/.agents/acceptance/PROJECT.md+++ b/.agents/acceptance/PROJECT.md@@ -280,6 +280,15 @@ stale standalone install: a recently added workspace package fails to resolvebrowser, against a per-instance localhost origin that usually can't evencomplete. If no injectable state exists, report auth as blocked and ask forone manual sign-in instead.+- Local server: `.agents/acceptance/scripts/electron-dev.sh start-local [<id>]`+ starts pool instance `<id>` (default 1, CDP `9222+id`) already signed in to the+ local dev server (`SERVER_URL`, default `http://localhost:3010`) as the seeded+ user — no OAuth page, no manual sign-in. It mints an access token with the local+ server's own `JWKS_KEY` (`mint-desktop-login.mjs`, env from the repo-root+ `.env`; refuses non-local hosts) and hands it to the dev build through+ `LOBE_DESKTOP_DEV_REMOTE_LOGIN`. Use it whenever the change under test is+ server-side. Its login is never saved into the shared snapshot. Agents the app+ spawns (Codex, Claude Code) get the same login through the `lh` sign-in file.- Concurrent instances (N worktrees / parallel runs): `electron-dev.sh` drives apool — `start <id>` gives each its own CDP port, userData dir (with copiedlogin), Vite port, and IPC id, and labels every window with the checkout anddiff --git a/.agents/acceptance/scripts/electron-dev.sh b/.agents/acceptance/scripts/electron-dev.shindex 020a99782cb..575261171c8 100755--- a/.agents/acceptance/scripts/electron-dev.sh+++ b/.agents/acceptance/scripts/electron-dev.sh@@ -52,6 +52,15 @@# SKIP_LOGIN_SAVE=1 — on `stop <id>`, do not snapshot the login state# ELECTRON_WAIT_S — max seconds to wait for CDP (default: 90)# RENDERER_WAIT_S — max seconds to wait for the SPA (default: 60)+# SERVER_URL — `start-local` target server (default: http://localhost:3010)+#+# Local server (no OAuth, no manual sign-in):+# ./electron-dev.sh start-local [<id>] # pool instance (default id 1) signed in to the+# # local dev server as the seeded user+# Mints an access token with the local server's own JWKS_KEY+# (mint-desktop-login.mjs, env from the repo-root .env) and hands it to the+# dev build through LOBE_DESKTOP_DEV_REMOTE_LOGIN. Its login is never saved+# into the shared snapshot, which belongs to the cloud sign-in.#set -euo pipefail@@ -96,6 +105,7 @@ PIDFILE=""# Resolve the target instance's ports/paths from its id (empty id = legacy).derive_instance() {local id="$1"+ LOCAL_LOGIN_FILE=""if [ -z "$id" ]; thenPOOL_MODE=0CDP_PORT="${ENV_CDP_PORT:-$CDP_BASE}"@@ -124,6 +134,7 @@ derive_instance() {--user-data "$USER_DATA_DIR" --label "$INSTANCE_LABEL")ELECTRON_LOG="$POOL_DIR/instance-$id.log"PIDFILE="$POOL_DIR/instance-$id.pid"+ LOCAL_LOGIN_FILE="$POOL_DIR/instance-$id.local-login.json"fi}@@ -249,7 +260,10 @@ do_stop() {# Ask the still-running app whether it is signed in — after the kill there is# nothing left to ask, and the on-disk token alone can't see a cookie session.local authed=0- if [ "$POOL_MODE" = "1" ] && [ "${SKIP_LOGIN_SAVE:-0}" != "1" ]; then+ # A start-local instance holds a minted local-server login; never snapshot it.+ local skip_save="${SKIP_LOGIN_SAVE:-0}"+ [ "$POOL_MODE" = "1" ] && [ -f "$LOCAL_LOGIN_FILE" ] && skip_save=1+ if [ "$POOL_MODE" = "1" ] && [ "$skip_save" != "1" ]; thenauthed=$(probe_renderer_authed)fi@@ -318,13 +332,14 @@ do_stop() {# Pool mode: capture the (freshly rotated) login before touching the userData,# then wipe it unless asked to keep it.if [ "$POOL_MODE" = "1" ] && [ -n "$USER_DATA_DIR" ]; then- [ "${SKIP_LOGIN_SAVE:-0}" = "1" ] || save_login_state "$USER_DATA_DIR" "$authed"+ [ "$skip_save" = "1" ] || save_login_state "$USER_DATA_DIR" "$authed"if [ "${KEEP_DATA:-0}" = "1" ]; thenecho "[electron-dev] Keeping userData: $USER_DATA_DIR"elserm -rf "$USER_DATA_DIR"echo "[electron-dev] Removed userData: $USER_DATA_DIR"fi+ rm -f "$LOCAL_LOGIN_FILE"fiecho "[electron-dev] Stopped ($label)."@@ -368,6 +383,14 @@ do_start() {mkdir -p "$POOL_DIR"seed_userdata "$USER_DATA_DIR"env_assignments=("${INSTANCE_ENV[@]}")+ # Minted here, after the pre-start stop has cleared any previous instance's files.+ if [ "${START_LOCAL:-0}" = "1" ]; then+ local env_file=()+ [ -f "$PROJECT_ROOT/.env" ] && env_file=(--env-file="$PROJECT_ROOT/.env")+ node "${env_file[@]}" "$SCRIPT_DIR/mint-desktop-login.mjs" \+ --out "$LOCAL_LOGIN_FILE" --server "${SERVER_URL:-http://localhost:3010}"+ env_assignments+=("LOBE_DESKTOP_DEV_REMOTE_LOGIN=$LOCAL_LOGIN_FILE")+ fielseenv_assignments=("LOBE_DESKTOP_CDP_PORT=$CDP_PORT")[ -n "$INSTANCE_LABEL" ] && env_assignments+=("LOBE_DESKTOP_INSTANCE_LABEL=$INSTANCE_LABEL")@@ -477,6 +500,14 @@ case "$CMD" inderive_instance "$INSTANCE"do_start;;+ start-local)+ derive_instance "${INSTANCE:-1}"+ if [ "$POOL_MODE" != "1" ]; then+ echo "[electron-dev] start-local needs a pool instance (it never touches your own profile)."+ exit 1+ fi+ START_LOCAL=1 do_start+ ;;stop)if [ "$INSTANCE" = "--all" ]; thendo_stop_all@@ -509,11 +540,14 @@ case "$CMD" in;;*)echo "Usage: $0 {start|stop|status|restart} [<id>] | $0 stop --all | $0 list"- echo " $0 save-login <id> | $0 login-status"+ echo " $0 save-login <id> | $0 login-status | $0 start-local [<id>]"echo ""echo " start [<id>] — Start an instance. No id = legacy single instance (CDP 9222)."echo " <id> = pool member: CDP 9222+id, Vite 5173+id, own userData"echo " (login seeded from the saved snapshot) + IPC id."+ echo " start-local [<id>] — Start pool instance <id> (default 1) signed in to the local dev"+ echo " server (SERVER_URL, default http://localhost:3010) as the seeded"+ echo " user. No OAuth; the login is never saved to the snapshot."echo " stop [<id>] — Stop an instance. Pool stop is sibling-safe, and snapshots the"echo " instance's login first. KEEP_DATA=1 preserves the userData;"echo " SKIP_LOGIN_SAVE=1 skips the snapshot."diff --git a/.agents/acceptance/scripts/mint-desktop-login.mjs b/.agents/acceptance/scripts/mint-desktop-login.mjsnew file mode 100755index 00000000000..9b60e5c0300--- /dev/null+++ b/.agents/acceptance/scripts/mint-desktop-login.mjs@@ -0,0 +1,94 @@+#!/usr/bin/env node+/**+ * Mint a desktop sign-in for a LOCAL dev server, with no OAuth page.+ *+ * Signs an access token the way the server's OIDC provider would (RS256 with the+ * server's own JWKS_KEY, client_id lobehub-desktop) for a user of the local+ * database, and writes the file the desktop app reads at boot through+ * LOBE_DESKTOP_DEV_REMOTE_LOGIN (dev builds only; see RemoteServerConfigCtr).+ *+ * Needs the local server's env: JWKS_KEY and DATABASE_URL. Run it with the repo+ * root .env loaded (`node --env-file=.env ...`). Never point it at production.+ *+ * node --env-file=.env .agents/acceptance/scripts/mint-desktop-login.mjs \+ * --out /path/login.json [--server http://localhost:3010] \+ * [--email [email protected] | --user-id user_x] [--days 30]+ */+import { randomUUID } from 'node:crypto';+import { chmodSync, writeFileSync } from 'node:fs';+import { parseArgs } from 'node:util';++import { calculateJwkThumbprint, importJWK, SignJWT } from 'jose';+import pg from 'pg';++const { values } = parseArgs({+ options: {+ 'days': { default: '30', type: 'string' },+ 'email': { default: '[email protected]', type: 'string' },+ 'out': { type: 'string' },+ 'server': { default: process.env.SERVER_URL || 'http://localhost:3010', type: 'string' },+ 'user-id': { type: 'string' },+ },+});++const fail = (message) => {+ console.error(`[mint-desktop-login] ${message}`);+ process.exit(1);+};++if (!values.out) fail('--out is required');+const server = new URL(values.server);+if (!['localhost', '127.0.0.1', '[::1]'].includes(server.hostname))+ fail(`refusing to mint for ${server.origin}: only a local dev server is allowed`);++const jwksString = process.env.JWKS_KEY || process.env.OIDC_JWKS_KEY;+if (!jwksString) fail('JWKS_KEY is not set; load the local server env (node --env-file=.env)');+const signingKey = JSON.parse(jwksString).keys?.find(+ (key) => key.alg === 'RS256' && key.kty === 'RSA',+);+if (!signingKey) fail('JWKS_KEY has no RS256 RSA key');+const { key_ops: _keyOps, ...privateKey } = signingKey;++const findUserId = async () => {+ if (values['user-id']) return values['user-id'];+ if (!process.env.DATABASE_URL) fail('DATABASE_URL is not set; pass --user-id instead');+ const client = new pg.Client({ connectionString: process.env.DATABASE_URL });+ await client.connect();+ try {+ const { rows } = await client.query('select id from users where email = $1 limit 1', [+ values.email,+ ]);+ if (!rows[0]) fail(`no user ${values.email} in the local database; seed it first`);+ return rows[0].id;+ } finally {+ await client.end();+ }+};++const userId = await findUserId();+const expiresIn = Number(values.days) * 24 * 60 * 60;+const accessToken = await new SignJWT({+ client_id: 'lobehub-desktop',+ scope: 'openid profile email offline_access',+})+ .setProtectedHeader({+ alg: 'RS256',+ kid: privateKey.kid ?? (await calculateJwkThumbprint(privateKey)),+ typ: 'at+jwt',+ })+ .setAudience(server.origin)+ .setIssuer(server.origin)+ .setSubject(userId)+ .setIssuedAt()+ .setJti(randomUUID())+ .setExpirationTime(Math.floor(Date.now() / 1000) + expiresIn)+ .sign(await importJWK(privateKey, 'RS256'));++writeFileSync(+ values.out,+ JSON.stringify({ accessToken, expiresIn, remoteServerUrl: server.origin }, null, 2),+);+chmodSync(values.out, 0o600);+console.log(+ `[mint-desktop-login] ${userId} → ${server.origin}, valid ${values.days} days: ${values.out}`,+);diff --git a/.agents/ux/lobe-design-rules.md b/.agents/ux/lobe-design-rules.mdindex 750fc87ea9e..982cdcd4c71 100644--- a/.agents/ux/lobe-design-rules.md+++ b/.agents/ux/lobe-design-rules.md@@ -207,3 +207,9 @@ Enforcement: both surfaces use the same tool controls; regression tests cover thShow GitHub authorization guidance when an import encounters an access error. Keep the source URL in the dialog while the user connects. Offer technical details only when they add diagnostic information beyond the recovery message.Enforcement: `useGithubSkillImport.test.ts` covers the single access message, retrying discovery after authorization, and retaining the user's selection when an import needs reconnection.++## LOBE-UX-029 — Let success stay quiet; mark only the exceptions++On result surfaces (acceptance checks, verify boards, run summaries), passing is the default state and carries no badge of its own: no per-item "Passed" tag, check stamp or green outline. Show the outcome once, in one plain sentence (for example "6 项已核对,等你确认"). Item identifiers stay neutral (`01`, `04B`), without a check mark. Color and badges are reserved for what needs a person: a failed check (error color with the reason) or a pending decision. Actions such as "Accept" may keep their icon; status may not.++Source: lead review of the artboard acceptance redesign (2026-11-16): too many Pass tags read as AI-generated.diff --git a/apps/cli/src/commands/artboard.test.ts b/apps/cli/src/commands/artboard.test.tsnew file mode 100644index 00000000000..d2ee6e7b9fe--- /dev/null+++ b/apps/cli/src/commands/artboard.test.ts@@ -0,0 +1,337 @@+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';+import { Readable } from 'node:stream';++import { Command } from 'commander';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { registerArtboardCommand } from './artboard';++const { create, list, listFiles, output, prepareFileUploads, read, readFile, update, writeFiles } =+ vi.hoisted(() => ({+ create: vi.fn(),+ list: vi.fn(),+ listFiles: vi.fn(),+ output: vi.fn(),+ prepareFileUploads: vi.fn(),+ read: vi.fn(),+ readFile: vi.fn(),+ update: vi.fn(),+ writeFiles: vi.fn(),+ }));+vi.mock('../api/client', () => ({+ getTrpcClient: async () => ({+ artboard: {+ create: { mutate: create },+ list: { query: list },+ listFiles: { query: listFiles },+ prepareFileUploads: { mutate: prepareFileUploads },+ read: { query: read },+ readFile: { query: readFile },+ update: { mutate: update },+ writeFiles: { mutate: writeFiles },+ },+ }),+}));+vi.mock('../utils/format', () => ({ outputJson: output }));++const board = {+ content: {+ boards: [+ {+ expected: null,+ flowNodeId: null,+ groupId: 'abg_1',+ id: 'brd-1',+ pageId: 'abp_1',+ rect: { h: 400, w: 640, x: 0, y: 0 },+ roundId: null,+ source: { hash: 'abc', kind: 'file', path: 'pages/empty.html' },+ title: '空项目',+ type: 'html',+ },+ ],+ edges: [],+ groups: [+ {+ desc: '',+ id: 'abg_1',+ kind: 'journey',+ pageId: 'abp_1',+ rect: { h: 592, w: 736, x: -48, y: -144 },+ title: '旅程',+ },+ ],+ pages: [{ id: 'abp_1', name: 'Page 1', sortOrder: 0 }],+ questions: [],+ rounds: [],+ },+ id: 'art_8f2k',+ phase: 'discuss',+ revision: 2,+ taskId: 'task_1',+ title: '首次进入',+};++describe('lh artboard', () => {+ let log: ReturnType<typeof vi.spyOn>;+ const originalTopic = process.env.LOBEHUB_TOPIC_ID;++ beforeEach(() => {+ vi.clearAllMocks();+ log = vi.spyOn(console, 'log').mockImplementation(() => {});+ process.env.LOBEHUB_TOPIC_ID = 'tpc_run';+ });++ afterEach(() => {+ log.mockRestore();+ if (originalTopic === undefined) delete process.env.LOBEHUB_TOPIC_ID;+ else process.env.LOBEHUB_TOPIC_ID = originalTopic;+ });++ const run = (args: string[]) => {+ const program = new Command();+ registerArtboardCommand(program);+ return program.parseAsync(args, { from: 'user' });+ };++ it('creates a board in the run’s conversation and prints the result line', async () => {+ create.mockResolvedValue({ artboard: board, changedIds: ['abg_1', 'brd-1'] });+ const ops = [{ group: { kind: 'journey', title: '旅程' }, type: 'addGroup' }];+ await run(['artboard', 'create', '--title', '首次进入', '--ops', JSON.stringify(ops)]);++ expect(create).toHaveBeenCalledWith({+ description: undefined,+ files: undefined,+ ops,+ taskId: undefined,+ title: '首次进入',+ topicId: 'tpc_run',+ });+ expect(log).toHaveBeenCalledWith('artboard art_8f2k · revision 2 · 1 groups · 1 boards');+ });++ it('needs --task when the run carries no conversation', async () => {+ delete process.env.LOBEHUB_TOPIC_ID;+ await expect(run(['artboard', 'create', '--title', 'x'])).rejects.toThrow('--task');+ expect(create).not.toHaveBeenCalled();+ });++ it('updates with the revision it read and prints JSON on request', async () => {+ update.mockResolvedValue({ artboard: board, changedIds: ['brd-1'] });+ const ops = [{ id: 'brd-1', patch: { x: 10 }, type: 'updateBoard' }];+ await run([+ 'artboard',+ 'update',+ 'art_8f2k',+ '--revision',+ '1',+ '--ops',+ JSON.stringify(ops),+ '--json',+ ]);++ expect(update).toHaveBeenCalledWith({ files: undefined, id: 'art_8f2k', ops, revision: 1 });+ expect(output).toHaveBeenCalledWith({ artboard: board, changedIds: ['brd-1'] });+ expect(log).not.toHaveBeenCalled();+ });++ it('lists the boards of the run’s project', async () => {+ list.mockResolvedValue([board]);+ await run(['artboard', 'list']);+ expect(list).toHaveBeenCalledWith({ taskId: undefined, topicId: 'tpc_run' });+ expect(log).toHaveBeenCalledWith('art_8f2k 首次进入 discuss revision 2');+ });++ it('reads a board and prints its content', async () => {+ read.mockResolvedValue({ artboard: board });+ await run(['artboard', 'read', 'art_8f2k']);++ expect(read).toHaveBeenCalledWith({ id: 'art_8f2k' });+ expect(log).toHaveBeenCalledWith('artboard art_8f2k · revision 2 · 1 groups · 1 boards');+ });++ it('writes files and ops in one update', async () => {+ update.mockResolvedValue({ artboard: board, changedIds: [] });+ const files = { writes: [{ content: '<h1>A</h1>', path: 'pages/a.html' }] };+ await run([+ 'artboard',+ 'update',+ 'art_8f2k',+ '--revision',+ '2',+ '--files',+ JSON.stringify(files),+ ]);++ expect(update).toHaveBeenCalledWith({ files, id: 'art_8f2k', ops: undefined, revision: 2 });+ });++ it('lists the files of a board with their sizes', async () => {+ listFiles.mockResolvedValue([+ { contentType: 'text/html', hash: 'abc', path: 'pages/empty.html', size: 2048 },+ ]);+ await run(['artboard', 'files', 'list', 'art_8f2k']);++ expect(listFiles).toHaveBeenCalledWith({ id: 'art_8f2k' });+ expect(log).toHaveBeenCalledWith('pages/empty.html 2048 B');+ });++ it('lists the files as JSON on request', async () => {+ const files = [{ contentType: 'text/html', hash: 'abc', path: 'pages/empty.html', size: 2048 }];+ listFiles.mockResolvedValue(files);+ await run(['artboard', 'files', 'list', 'art_8f2k', '--json']);++ expect(output).toHaveBeenCalledWith(files);+ });++ it('prints one file as text', async () => {+ const write = vi.spyOn(process.stdout, 'write').mockImplementation(() => true);+ readFile.mockResolvedValue({+ content: '<h1>空项目</h1>',+ contentType: 'text/html',+ path: 'pages/empty.html',+ });+ await run(['artboard', 'files', 'read', 'art_8f2k', 'pages/empty.html']);++ expect(readFile).toHaveBeenCalledWith({ id: 'art_8f2k', path: 'pages/empty.html' });+ expect(write).toHaveBeenCalledWith('<h1>空项目</h1>');+ write.mockRestore();+ });++ it('refuses to print a binary file', async () => {+ readFile.mockResolvedValue({+ base64: 'iVBORw==',+ contentType: 'image/png',+ path: 'shots/a.png',+ });+ await expect(run(['artboard', 'files', 'read', 'art_8f2k', 'shots/a.png'])).rejects.toThrow(+ 'shots/a.png is binary',+ );+ });++ describe('files write', () => {+ let dir: string;+ const fetchMock = vi.fn();++ beforeEach(() => {+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'artboard-files-'));+ writeFiles.mockResolvedValue({ files: [] });+ prepareFileUploads.mockResolvedValue({ uploads: [] });+ fetchMock.mockReset();+ fetchMock.mockResolvedValue(new Response(null, { status: 200 }));+ vi.stubGlobal('fetch', fetchMock);+ });++ afterEach(() => {+ fs.rmSync(dir, { force: true, recursive: true });+ vi.unstubAllGlobals();+ });++ it('writes a text file read from stdin as content', async () => {+ const stdin = vi+ .spyOn(process, 'stdin', 'get')+ .mockReturnValue(Readable.from([Buffer.from('<h1>新</h1>')]) as typeof process.stdin);+ await run(['artboard', 'files', 'write', 'art_8f2k', 'pages/new.html']);+ stdin.mockRestore();++ expect(writeFiles).toHaveBeenCalledWith({+ files: { writes: [{ content: '<h1>新</h1>', path: 'pages/new.html' }] },+ id: 'art_8f2k',+ });+ });++ it('writes a binary file from --from as base64', async () => {+ const png = Buffer.from([137, 80, 78, 71]);+ fs.writeFileSync(path.join(dir, 'a.png'), png);+ await run([+ 'artboard',+ 'files',+ 'write',+ 'art_8f2k',+ 'shots/a.png',+ '--from',+ path.join(dir, 'a.png'),+ ]);++ expect(writeFiles).toHaveBeenCalledWith({+ files: { writes: [{ base64: png.toString('base64'), path: 'shots/a.png' }] },+ id: 'art_8f2k',+ });+ });++ it('sends a large file through a presigned upload', async () => {+ const image = Buffer.alloc(3 * 1024 * 1024, 5);+ fs.writeFileSync(path.join(dir, 'big.png'), image);+ prepareFileUploads.mockResolvedValue({+ uploads: [{ path: 'shots/big.png', url: 'https://s3.test/blob' }],+ });+ await run([+ 'artboard',+ 'files',+ 'write',+ 'art_8f2k',+ 'shots/big.png',+ '--from',+ path.join(dir, 'big.png'),+ ]);++ expect(prepareFileUploads).toHaveBeenCalledWith({+ files: [{ path: 'shots/big.png', size: image.byteLength }],+ id: 'art_8f2k',+ });+ expect(fetchMock.mock.calls[0][0]).toBe('https://s3.test/blob');+ expect(fetchMock.mock.calls[0][1].method).toBe('PUT');+ expect(writeFiles).toHaveBeenCalledWith({+ files: { writes: [{ path: 'shots/big.png', uploaded: true }] },+ id: 'art_8f2k',+ });+ });++ it('refuses a path a board cannot serve', async () => {+ fs.writeFileSync(path.join(dir, 'notes.md'), '# notes');+ await expect(+ run([+ 'artboard',+ 'files',+ 'write',+ 'art_8f2k',+ 'notes.md',+ '--from',+ path.join(dir, 'notes.md'),+ ]),+ ).rejects.toThrow('notes.md');+ expect(writeFiles).not.toHaveBeenCalled();+ });+ });++ it('pushes a folder with --prune without reading the boards that point at its files', async () => {+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'artboard-push-cmd-'));+ fs.writeFileSync(path.join(dir, 'index.html'), '<p>hi</p>');+ listFiles.mockResolvedValue([+ { contentType: 'text/html', hash: 'x', path: 'pages/empty.html', size: 1 },+ ]);+ writeFiles.mockResolvedValue({ files: [] });++ await run(['artboard', 'push', 'art_8f2k', dir, '--prune']);+ fs.rmSync(dir, { force: true, recursive: true });++ expect(read).not.toHaveBeenCalled();+ expect(writeFiles).toHaveBeenLastCalledWith({+ files: { deletes: ['pages/empty.html'] },+ id: 'art_8f2k',+ });+ expect(log.mock.calls).toEqual([['pushed 1 · unchanged 0 · deleted 1']]);+ });++ it('removes files', async () => {+ writeFiles.mockResolvedValue({ files: [] });+ await run(['artboard', 'files', 'rm', 'art_8f2k', 'pages/a.html', 'shots/b.png']);++ expect(writeFiles).toHaveBeenCalledWith({+ files: { deletes: ['pages/a.html', 'shots/b.png'] },+ id: 'art_8f2k',+ });+ });+});diff --git a/apps/cli/src/commands/artboard.ts b/apps/cli/src/commands/artboard.tsnew file mode 100644index 00000000000..fcbc9b37665--- /dev/null+++ b/apps/cli/src/commands/artboard.ts@@ -0,0 +1,227 @@+import fs from 'node:fs';+import { buffer } from 'node:stream/consumers';++import {+ type ArtboardContent,+ formatArtboardResultLine,+ normalizeArtboardFilePath,+} from '@lobechat/types';+import type { Command } from 'commander';++import { getTrpcClient } from '../api/client';+import { outputJson } from '../utils/format';+import { registerArtboardCommentCommands } from './artboardComments';+import { registerArtboardOpsCommand } from './artboardOps';+import { pushArtboardDir, toLocalArtboardFile, writeArtboardFiles } from './artboardPush';+import { registerArtboardSkillCommand } from './artboardSkill';++interface BoardLike {+ content: ArtboardContent;+ id: string;+ revision: number;+}++const resultLine = (artboard: BoardLike) =>+ formatArtboardResultLine({+ boardCount: artboard.content.boards.length,+ groupCount: artboard.content.groups.length,+ id: artboard.id,+ revision: artboard.revision,+ });++const parseOps = (value?: string) => {+ if (value === undefined) return undefined;+ const text = value.startsWith('@') ? fs.readFileSync(value.slice(1), 'utf8') : value;+ const ops = JSON.parse(text);+ if (!Array.isArray(ops)) throw new Error('--ops must be a JSON array of ops');+ return ops;+};++const parseFiles = (value?: string) => {+ if (value === undefined) return undefined;+ const text = value.startsWith('@') ? fs.readFileSync(value.slice(1), 'utf8') : value;+ const files = JSON.parse(text);+ if (!files || typeof files !== 'object' || Array.isArray(files))+ throw new Error('--files must be a JSON object of writes, edits and deletes');+ return files;+};++const FILES_HELP =+ 'File changes applied before the ops: {"writes":[{"path","content"}],"edits":[{"path","oldText","newText"}],"deletes":[path]} as JSON, or @file.json';++const positiveInteger = (value: string) => {+ const result = Number(value);+ if (!Number.isSafeInteger(result) || result < 1) throw new Error('Expected a positive integer');+ return result;+};++const topicId = () => process.env.LOBEHUB_TOPIC_ID || undefined;++export const registerArtboardCommand = (program: Command) => {+ const artboard = program+ .command('artboard')+ .description(+ 'Lay out a requirement on a project artboard (same ops as the builtin-artboard tool)',+ );++ artboard+ .command('create')+ .description(+ "Create the artboard for a task; without --task it uses the run's conversation project",+ )+ .requiredOption('--title <title>', 'Board title')+ .option('--description <text>', 'One line shown on the board card')+ .option('--task <task>', 'Task id or identifier, such as PRJ-12')+ .option('--files <json>', FILES_HELP)+ .option(+ '--ops <json>',+ 'Initial ops (addGroup, addBoard, addEdge, addRound, addPage, …) as a JSON array, or @file.json; shapes: lh artboard ops',+ )+ .option('--json', 'Print structured JSON')+ .action(+ async (options: {+ description?: string;+ files?: string;+ json?: boolean;+ ops?: string;+ task?: string;+ title: string;+ }) => {+ if (!options.task && !topicId())+ throw new Error('Pass --task: this shell has no LOBEHUB_TOPIC_ID to find the project');+ const client = await getTrpcClient();+ const result = await client.artboard.create.mutate({+ description: options.description,+ files: parseFiles(options.files),+ ops: parseOps(options.ops),+ taskId: options.task,+ title: options.title,+ topicId: topicId(),+ });+ if (options.json) return outputJson(result);+ console.log(resultLine(result.artboard));+ },+ );++ artboard+ .command('update <id>')+ .description('Apply file changes and ops; everything applies or nothing does')+ .requiredOption('--revision <n>', 'Revision you last read', positiveInteger)+ .option('--files <json>', FILES_HELP)+ .option(+ '--ops <json>',+ 'Ops (add/update/remove Board, Group, Page; addRound, updateRound; addEdge, removeEdge; setCheck) as a JSON array, or @file.json; shapes: lh artboard ops',+ )+ .option('--json', 'Print structured JSON')+ .action(+ async (+ id: string,+ options: { files?: string; json?: boolean; ops?: string; revision: number },+ ) => {+ if (options.files === undefined && options.ops === undefined)+ throw new Error('Pass --ops, --files or both');+ const client = await getTrpcClient();+ const result = await client.artboard.update.mutate({+ files: parseFiles(options.files),+ id,+ ops: parseOps(options.ops),+ revision: options.revision,+ });+ if (options.json) return outputJson(result);+ console.log(resultLine(result.artboard));+ },+ );++ artboard+ .command('read <id>')+ .description('Print the artboard and its revision')+ .option('--json', 'Print structured JSON')+ .action(async (id: string, options: { json?: boolean }) => {+ const client = await getTrpcClient();+ const result = await client.artboard.read.query({ id });+ if (options.json) return outputJson(result);+ console.log(resultLine(result.artboard));+ console.log(JSON.stringify(result.artboard.content, null, 2));+ });++ artboard+ .command('push <id> <dir>')+ .description(+ 'Upload the HTML pages, styles and images under <dir> as files of the artboard; unchanged files are skipped',+ )+ .option('--prune', 'Also delete artboard files that are not in <dir>')+ .option('--json', 'Print structured JSON')+ .action(async (id: string, dir: string, options: { json?: boolean; prune?: boolean }) => {+ const client = await getTrpcClient();+ const result = await pushArtboardDir(client.artboard, id, dir, { prune: options.prune });+ if (options.json) return outputJson(result);+ console.log(+ `pushed ${result.uploaded.length} · unchanged ${result.unchanged.length} · deleted ${result.deleted.length}`,+ );+ for (const skipped of result.skipped)+ console.log(`skipped ${skipped}: not a file a board can serve`);+ });++ const files = artboard+ .command('files')+ .description('List, read, write and remove artboard files');++ files+ .command('list <id>')+ .description('List the files of the artboard')+ .option('--json', 'Print structured JSON')+ .action(async (id: string, options: { json?: boolean }) => {+ const client = await getTrpcClient();+ const list = await client.artboard.listFiles.query({ id });+ if (options.json) return outputJson(list);+ for (const file of list) console.log(`${file.path} ${file.size} B`);+ });++ files+ .command('read <id> <path>')+ .description('Print one text file of the artboard')+ .action(async (id: string, path: string) => {+ const client = await getTrpcClient();+ const file = await client.artboard.readFile.query({ id, path });+ if (file.content === undefined) throw new Error(`${file.path} is binary`);+ process.stdout.write(file.content);+ });++ files+ .command('write <id> <path>')+ .description('Write one file of the artboard from stdin, or from a local file with --from')+ .option('--from <file>', 'Local file to upload instead of stdin')+ .action(async (id: string, path: string, options: { from?: string }) => {+ const normalized = normalizeArtboardFilePath(path);+ if (!normalized) throw new Error(`${path} is not a file a board can serve`);+ const bytes = options.from ? fs.readFileSync(options.from) : await buffer(process.stdin);+ const client = await getTrpcClient();+ await writeArtboardFiles(client.artboard, id, [toLocalArtboardFile(normalized, bytes)]);+ console.log(`wrote ${normalized} ${bytes.byteLength} B`);+ });++ files+ .command('rm <id> <paths...>')+ .description('Delete files of the artboard; boards that show one stay and wait for it again')+ .action(async (id: string, paths: string[]) => {+ const client = await getTrpcClient();+ await client.artboard.writeFiles.mutate({ files: { deletes: paths }, id });+ for (const path of paths) console.log(`deleted ${path}`);+ });++ artboard+ .command('list')+ .description("List the artboards in the run's project")+ .option('--task <task>', 'Find the project through this task instead')+ .option('--json', 'Print structured JSON')+ .action(async (options: { json?: boolean; task?: string }) => {+ const client = await getTrpcClient();+ const boards = await client.artboard.list.query({ taskId: options.task, topicId: topicId() });+ if (options.json) return outputJson(boards);+ for (const board of boards)+ console.log(`${board.id} ${board.title} ${board.phase} revision ${board.revision}`);+ });+ registerArtboardCommentCommands(artboard);+ registerArtboardOpsCommand(artboard);+ registerArtboardSkillCommand(artboard);+};diff --git a/apps/cli/src/commands/artboardComments.test.ts b/apps/cli/src/commands/artboardComments.test.tsnew file mode 100644index 00000000000..8abf458b5ee--- /dev/null+++ b/apps/cli/src/commands/artboardComments.test.ts@@ -0,0 +1,132 @@+import { Command } from 'commander';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { registerArtboardCommand } from './artboard';++const { askQuestion, output, read, replyAsAgent, resolveComment, takeComments } = vi.hoisted(+ () => ({+ askQuestion: vi.fn(),+ output: vi.fn(),+ read: vi.fn(),+ replyAsAgent: vi.fn(),+ resolveComment: vi.fn(),+ takeComments: vi.fn(),+ }),+);+vi.mock('../api/client', () => ({+ getTrpcClient: async () => ({+ artboard: {+ askQuestion: { mutate: askQuestion },+ read: { query: read },+ replyAsAgent: { mutate: replyAsAgent },+ resolveComment: { mutate: resolveComment },+ takeComments: { mutate: takeComments },+ },+ }),+}));+vi.mock('../utils/format', () => ({ outputJson: output }));++const content = {+ boards: [{ id: 'brd-1', pageId: 'abp_1', title: '购物清单' }],+ edges: [],+ groups: [{ id: 'abg_1', pageId: 'abp_1', title: '主流程' }],+ pages: [{ id: 'abp_1', name: '流程', sortOrder: 0 }],+ questions: [],+ rounds: [],+};++const comment = (id: string, text: string, agent = false) => ({+ authorAgentId: agent ? 'agt_run' : null,+ authorUserId: agent ? null : 'u1',+ content: text,+ createdAt: new Date(),+ id,+});++describe('lh artboard comments', () => {+ let log: ReturnType<typeof vi.spyOn>;+ const originalAgent = process.env.LOBEHUB_AGENT_ID;++ beforeEach(() => {+ vi.clearAllMocks();+ log = vi.spyOn(console, 'log').mockImplementation(() => {});+ process.env.LOBEHUB_AGENT_ID = 'agt_run';+ read.mockResolvedValue({ artboard: { content, id: 'art_1', revision: 3 } });+ });++ afterEach(() => {+ log.mockRestore();+ if (originalAgent === undefined) delete process.env.LOBEHUB_AGENT_ID;+ else process.env.LOBEHUB_AGENT_ID = originalAgent;+ });++ const run = (args: string[]) => {+ const program = new Command();+ registerArtboardCommand(program);+ return program.parseAsync(args, { from: 'user' });+ };++ const printed = () => log.mock.calls.map((call) => call.join(' ')).join('\n');++ it('takes the threads as the run’s agent and prints each with its id, place and replies', async () => {+ takeComments.mockResolvedValue([+ {+ ...comment('c1', '标签太弱'),+ boardId: 'brd-1',+ groupId: null,+ pageId: 'abp_1',+ replies: [comment('c2', '改成灰色胶囊', true)],+ resolvedAt: null,+ stale: false,+ unread: true,+ },+ ]);++ await run(['artboard', 'comments', 'art_1']);++ expect(takeComments).toHaveBeenCalledWith({ agentId: 'agt_run', id: 'art_1' });+ const text = printed();+ expect(text).toContain('c1');+ expect(text).toContain('购物清单');+ expect(text).toContain('new');+ expect(text).toContain('user: 标签太弱');+ expect(text).toContain('you: 改成灰色胶囊');+ });++ it('says so when no thread is waiting', async () => {+ takeComments.mockResolvedValue([]);+ await run(['artboard', 'comments', 'art_1']);+ expect(printed()).toMatch(/no comment/i);+ });++ it('replies, resolves and asks as the run’s agent', async () => {+ replyAsAgent.mockResolvedValue({ id: 'c3' });+ resolveComment.mockResolvedValue({ id: 'c1' });+ askQuestion.mockResolvedValue({ id: 'c4' });++ await run(['artboard', 'reply', 'c1', '已改成灰色胶囊']);+ await run(['artboard', 'resolve', 'c1']);+ await run(['artboard', 'ask', 'art_1', '--board', 'brd-1', '入口放哪?']);++ expect(replyAsAgent).toHaveBeenCalledWith({+ agentId: 'agt_run',+ commentId: 'c1',+ content: '已改成灰色胶囊',+ });+ expect(resolveComment).toHaveBeenCalledWith({ commentId: 'c1' });+ expect(askQuestion).toHaveBeenCalledWith({+ agentId: 'agt_run',+ boardId: 'brd-1',+ content: '入口放哪?',+ groupId: undefined,+ id: 'art_1',+ pageId: undefined,+ });+ });++ it('refuses to speak for an agent outside an agent run', async () => {+ delete process.env.LOBEHUB_AGENT_ID;+ await expect(run(['artboard', 'comments', 'art_1'])).rejects.toThrow('LOBEHUB_AGENT_ID');+ expect(takeComments).not.toHaveBeenCalled();+ });+});diff --git a/apps/cli/src/commands/artboardComments.ts b/apps/cli/src/commands/artboardComments.tsnew file mode 100644index 00000000000..cfbde317882--- /dev/null+++ b/apps/cli/src/commands/artboardComments.ts@@ -0,0 +1,116 @@+import type {+ ArtboardCommentThreadView,+ ArtboardCommentView,+ ArtboardContent,+} from '@lobechat/types';+import type { Command } from 'commander';++import { getTrpcClient } from '../api/client';+import { outputJson } from '../utils/format';++const runAgentId = () => {+ const id = process.env.LOBEHUB_AGENT_ID?.trim();+ if (!id)+ throw new Error(+ 'Comments are answered by the agent of a LobeHub conversation, and LOBEHUB_AGENT_ID is not set in this shell',+ );+ return id;+};++const placeOf = (thread: ArtboardCommentThreadView, content: ArtboardContent) => {+ const board = content.boards.find((item) => item.id === thread.boardId);+ if (board) return `board ${board.id} "${board.title}"`;+ const group = content.groups.find((item) => item.id === thread.groupId);+ if (group) return `group ${group.id} "${group.title}"`;+ const page = content.pages.find((item) => item.id === thread.pageId);+ return page ? `page ${page.id} "${page.name}"` : 'the canvas';+};++const speaker = (comment: ArtboardCommentView) => (comment.authorAgentId ? 'you' : 'user');++const formatThread = (thread: ArtboardCommentThreadView, content: ArtboardContent) => {+ const tags = [+ thread.unread && 'new',+ thread.resolvedAt && 'resolved',+ thread.stale && 'screen changed since',+ ].filter(Boolean);+ return [+ `${thread.id} on ${placeOf(thread, content)}${tags.length ? ` [${tags.join(', ')}]` : ''}`,+ ...[thread, ...thread.replies].map((comment) => ` ${speaker(comment)}: ${comment.content}`),+ ].join('\n');+};++const textOf = (words: string[]) => {+ const text = words.join(' ').trim();+ if (!text) throw new Error('Write the text after the id');+ return text;+};++export const registerArtboardCommentCommands = (artboard: Command) => {+ artboard+ .command('comments <id>')+ .description(+ "Print the user's comment threads waiting for you, with their ids; the ones printed count as read",+ )+ .option('--json', 'Print structured JSON')+ .action(async (id: string, options: { json?: boolean }) => {+ const agentId = runAgentId();+ const client = await getTrpcClient();+ const [threads, { artboard: board }] = await Promise.all([+ client.artboard.takeComments.mutate({ agentId, id }),+ client.artboard.read.query({ id }),+ ]);+ if (options.json) return outputJson(threads);+ if (!threads.length) return console.log('No comment threads are waiting for you');+ console.log(threads.map((thread) => formatThread(thread, board.content)).join('\n\n'));+ });++ artboard+ .command('reply <commentId> <text...>')+ .description('Answer a comment thread on the artboard')+ .action(async (commentId: string, words: string[]) => {+ const agentId = runAgentId();+ const client = await getTrpcClient();+ await client.artboard.replyAsAgent.mutate({ agentId, commentId, content: textOf(words) });+ console.log(`replied in ${commentId}`);+ });++ artboard+ .command('resolve <commentId>')+ .description(+ 'Close a thread once what it asks for is done, or once your question in it is answered',+ )+ .action(async (commentId: string) => {+ const client = await getTrpcClient();+ await client.artboard.resolveComment.mutate({ commentId });+ console.log(`resolved ${commentId}`);+ });++ artboard+ .command('ask <id> <text...>')+ .description(+ 'Ask the user a question on the artboard as a new thread; the artboard cannot be finalized while it is open',+ )+ .option('--board <boardId>', 'Board the question is about')+ .option('--group <groupId>', 'Group the question is about')+ .option('--page <pageId>', 'Page the question is about')+ .action(+ async (+ id: string,+ words: string[],+ options: { board?: string; group?: string; page?: string },+ ) => {+ const agentId = runAgentId();+ const client = await getTrpcClient();+ const question = await client.artboard.askQuestion.mutate({+ agentId,+ boardId: options.board,+ content: textOf(words),+ groupId: options.group,+ id,+ pageId: options.page,+ });+ console.log(`asked ${question.id}`);+ },+ );+};diff --git a/apps/cli/src/commands/artboardOps.test.ts b/apps/cli/src/commands/artboardOps.test.tsnew file mode 100644index 00000000000..3db7e5bace3--- /dev/null+++ b/apps/cli/src/commands/artboardOps.test.ts@@ -0,0 +1,65 @@+import { artboardOpSchema } from '@lobechat/types';+import { Command } from 'commander';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { registerArtboardCommand } from './artboard';++const { output } = vi.hoisted(() => ({ output: vi.fn() }));+vi.mock('../api/client', () => ({ getTrpcClient: vi.fn() }));+vi.mock('../utils/format', () => ({ outputJson: output }));++const run = async (...args: string[]) => {+ const program = new Command().exitOverride();+ registerArtboardCommand(program);+ await program.parseAsync(['node', 'lh', 'artboard', 'ops', ...args]);+};++const opTypes = artboardOpSchema.options.map((option) => option.shape.type.value);++describe('lh artboard ops', () => {+ let printed: string;++ beforeEach(() => {+ printed = '';+ vi.spyOn(console, 'log').mockImplementation((line: string) => {+ printed += `${line}\n`;+ });+ });++ afterEach(() => {+ vi.restoreAllMocks();+ output.mockReset();+ });++ it('prints every op the schema accepts with its fields', async () => {+ await run();++ for (const type of opTypes) expect(printed).toContain(`"type": "${type}"`);+ expect(printed).toMatch(+ /"type": "addBoard", "board": \{ "title": string, "x": number, "y": number,/,+ );+ expect(printed).toMatch(/"type": "removeEdge", "id": string/);+ });++ it('marks optional fields and spells out enums and the file source', async () => {+ await run();++ expect(printed).toContain('"ref"?: string');+ expect(printed).toContain('"kind": "journey" | "options" | "references" | "other"');+ expect(printed).toContain('"source"?: { "kind": "file", "path": string }');+ });++ it('warns about the board types and option rules the shapes cannot show', async () => {+ await run();++ expect(printed).toMatch(/"video"[^\n]*refused/);+ expect(printed).toMatch(/"recommended"[^\n]*"roundId"[^\n]*options group/);+ });++ it('prints the JSON Schema with --json', async () => {+ await run('--json');++ const schema = output.mock.calls[0][0];+ expect(schema.oneOf ?? schema.anyOf).toHaveLength(opTypes.length);+ });+});diff --git a/apps/cli/src/commands/artboardOps.ts b/apps/cli/src/commands/artboardOps.tsnew file mode 100644index 00000000000..1bcbe05ed61--- /dev/null+++ b/apps/cli/src/commands/artboardOps.ts@@ -0,0 +1,67 @@+import { artboardOpSchema } from '@lobechat/types';+import type { Command } from 'commander';+import { z } from 'zod';++import { outputJson } from '../utils/format';++interface SchemaNode {+ anyOf?: SchemaNode[];+ const?: unknown;+ enum?: unknown[];+ oneOf?: SchemaNode[];+ properties?: Record<string, SchemaNode>;+ required?: string[];+ type?: string;+}++const literal = (value: unknown) => JSON.stringify(value);++const renderNode = (node: SchemaNode): string => {+ if (node.const !== undefined) return literal(node.const);+ if (node.enum) return node.enum.map(literal).join(' | ');+ const variants = node.oneOf ?? node.anyOf;+ if (variants) return variants.map(renderNode).join(' | ');+ if (node.type === 'object' && node.properties) return renderObject(node);+ if (node.type === 'integer') return 'number';+ return node.type ?? 'unknown';+};++const renderObject = (node: SchemaNode) => {+ const required = new Set(node.required);+ const rank = ([key, value]: [string, SchemaNode]) =>+ value.const !== undefined ? 0 : required.has(key) ? 1 : 2;+ const fields = Object.entries(node.properties!)+ .map((entry, index) => ({ entry, index, rank: rank(entry) }))+ .sort((a, b) => a.rank - b.rank || a.index - b.index)+ .map(+ ({ entry: [key, value] }) => `"${key}"${required.has(key) ? '' : '?'}: ${renderNode(value)}`,+ );+ return `{ ${fields.join(', ')} }`;+};++const NOTES = [+ '--ops takes a JSON array of these, inline or as @file.json. Every op in one call applies, or none does.',+ 'A field marked ? is optional.',+ '"ref" is a name you choose on an add op; later ops in the same call can use it wherever an id is expected.',+ 'x and y are page coordinates; w and h default to 640×400. A board without pageId lands on the page of its group or round, otherwise on the first page.',+ 'A file source names a file of the artboard: put it there with `lh artboard push <id> <dir>` or --files, then point the board at its relative path.',+ 'A board of type "decision" has no source and no "expected". An .html file makes an "html" board and an image file an "image" board; "video" is refused.',+ '"recommended" marks a board as the option you would pick in its round; it needs "roundId", and a board with a "roundId" must sit in an options group.',+];++const opsAction = (options: { json?: boolean }) => {+ const schema = z.toJSONSchema(artboardOpSchema) as SchemaNode;+ if (options.json) return outputJson(schema);++ console.log('Ops accepted by `lh artboard create --ops` and `lh artboard update --ops`:\n');+ for (const op of schema.oneOf ?? schema.anyOf ?? []) console.log(` ${renderNode(op)}\n`);+ for (const note of NOTES) console.log(`- ${note}`);+};++export const registerArtboardOpsCommand = (artboard: Command) => {+ artboard+ .command('ops')+ .description('Print the shape of every op that create and update accept')+ .option('--json', 'Print the ops as JSON Schema')+ .action(opsAction);+};diff --git a/apps/cli/src/commands/artboardPush.test.ts b/apps/cli/src/commands/artboardPush.test.tsnew file mode 100644index 00000000000..61bbc4d1fba--- /dev/null+++ b/apps/cli/src/commands/artboardPush.test.ts@@ -0,0 +1,203 @@+import { createHash } from 'node:crypto';+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';++import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { pushArtboardDir } from './artboardPush';++const md5 = (bytes: string | Buffer) => createHash('md5').update(bytes).digest('hex');++let dir: string;++const put = (relative: string, content: string | Buffer) => {+ const file = path.join(dir, relative);+ fs.mkdirSync(path.dirname(file), { recursive: true });+ fs.writeFileSync(file, content);+};++const client = (+ remote: { contentType: string; hash: string; path: string; size: number }[],+ options: { uploads?: { headers?: Record<string, string>; path: string; url: string }[] } = {},+) => {+ const writeFiles = vi.fn(async ({ files }: { files: { writes?: { path: string }[] } }) => ({+ files: (files.writes ?? []).map((write) => ({ hash: 'h', path: write.path, size: 1 })),+ }));+ const prepareFileUploads = vi.fn(async () => ({ uploads: options.uploads ?? [] }));+ return {+ api: {+ listFiles: { query: vi.fn(async () => remote) },+ prepareFileUploads: { mutate: prepareFileUploads },+ writeFiles: { mutate: writeFiles },+ },+ prepareFileUploads,+ writeFiles,+ };+};++const fetchMock = vi.fn();++beforeEach(() => {+ dir = fs.mkdtempSync(path.join(os.tmpdir(), 'artboard-push-'));+ fetchMock.mockReset();+ fetchMock.mockResolvedValue(new Response(null, { status: 200 }));+ vi.stubGlobal('fetch', fetchMock);+});++afterEach(() => {+ fs.rmSync(dir, { force: true, recursive: true });+ vi.unstubAllGlobals();+});++describe('pushArtboardDir', () => {+ it('uploads new and changed files, text as content and images as base64', async () => {+ const png = Buffer.from([137, 80, 78, 71]);+ put('pages/home.html', '<h1>Home</h1>');+ put('pages/same.html', '<p>same</p>');+ put('shots/a.png', png);+ const { api, writeFiles } = client([+ { contentType: 'text/html', hash: md5('<p>same</p>'), path: 'pages/same.html', size: 11 },+ // A sha256 of the same bytes is not the ETag the server reports.+ {+ contentType: 'image/png',+ hash: createHash('sha256').update(png).digest('hex'),+ path: 'shots/a.png',+ size: 4,+ },+ ]);++ const result = await pushArtboardDir(api, 'art_1', dir, {});++ expect(writeFiles).toHaveBeenCalledTimes(1);+ expect(writeFiles.mock.calls[0][0]).toEqual({+ files: {+ writes: [+ { content: '<h1>Home</h1>', path: 'pages/home.html' },+ { base64: png.toString('base64'), path: 'shots/a.png' },+ ],+ },+ id: 'art_1',+ });+ expect(result).toEqual({+ deleted: [],+ skipped: [],+ unchanged: ['pages/same.html'],+ uploaded: ['pages/home.html', 'shots/a.png'],+ });+ });++ it('skips files a board cannot serve and hidden files', async () => {+ put('notes.md', '# notes');+ put('.DS_Store', 'x');+ put('index.html', '<p>hi</p>');+ const { api } = client([]);++ const result = await pushArtboardDir(api, 'art_1', dir, {});++ expect(result.uploaded).toEqual(['index.html']);+ expect(result.skipped).toEqual(['notes.md']);+ });++ it('deletes remote files missing locally only with prune', async () => {+ put('index.html', '<p>hi</p>');+ const remote = [+ { contentType: 'text/html', hash: md5('<p>hi</p>'), path: 'index.html', size: 9 },+ { contentType: 'text/html', hash: 'x', path: 'old.html', size: 1 },+ ];+ const kept = client(remote);+ expect((await pushArtboardDir(kept.api, 'art_1', dir, {})).deleted).toEqual([]);+ expect(kept.writeFiles).not.toHaveBeenCalled();++ const pruned = client(remote);+ const result = await pushArtboardDir(pruned.api, 'art_1', dir, { prune: true });+ expect(pruned.writeFiles.mock.calls[0][0]).toEqual({+ files: { deletes: ['old.html'] },+ id: 'art_1',+ });+ expect(result.deleted).toEqual(['old.html']);+ });++ it('prunes every remote file missing locally, even one a board points at', async () => {+ put('index.html', '<p>hi</p>');+ const remote = [+ { contentType: 'text/html', hash: md5('<p>hi</p>'), path: 'index.html', size: 9 },+ { contentType: 'text/html', hash: 'x', path: 'old.html', size: 1 },+ { contentType: 'text/html', hash: 'y', path: 'pages/shown.html', size: 1 },+ ];+ const { api, writeFiles } = client(remote);++ const result = await pushArtboardDir(api, 'art_1', dir, { prune: true });++ expect(writeFiles).toHaveBeenCalledTimes(1);+ expect(writeFiles.mock.calls[0][0]).toEqual({+ files: { deletes: ['old.html', 'pages/shown.html'] },+ id: 'art_1',+ });+ expect(result).toEqual({+ deleted: ['old.html', 'pages/shown.html'],+ skipped: [],+ unchanged: ['index.html'],+ uploaded: [],+ });+ });++ it('keeps every request under 2 MB encoded and sends a large image through a presigned PUT', async () => {+ const image = Buffer.alloc(6 * 1024 * 1024, 7);+ put('shots/big.png', image);+ // Quotes double when JSON-escaped: 700 KB on disk, 1.4 MB in the request.+ put('pages/a.html', '"'.repeat(700 * 1024));+ put('pages/b.html', '"'.repeat(700 * 1024));+ put('pages/c.html', '<p>c</p>');+ put('shots/small.png', Buffer.alloc(600 * 1024, 1));+ const headers = { 'Content-Type': 'image/png' };+ const { api, prepareFileUploads, writeFiles } = client([], {+ uploads: [{ headers, path: 'shots/big.png', url: 'https://s3.test/blob' }],+ });++ const result = await pushArtboardDir(api, 'art_1', dir, {});++ for (const [input] of writeFiles.mock.calls)+ expect(Buffer.byteLength(JSON.stringify(input))).toBeLessThanOrEqual(2 * 1024 * 1024);+ expect(prepareFileUploads).toHaveBeenCalledWith({+ files: [{ path: 'shots/big.png', size: image.byteLength }],+ id: 'art_1',+ });+ expect(fetchMock).toHaveBeenCalledTimes(1);+ const [url, init] = fetchMock.mock.calls[0];+ expect(url).toBe('https://s3.test/blob');+ expect(init.method).toBe('PUT');+ expect(init.headers).toEqual(headers);+ expect(Buffer.from(init.body).equals(image)).toBe(true);+ const writes = writeFiles.mock.calls.flatMap(([input]) => input.files.writes ?? []);+ expect(writes).toContainEqual({ path: 'shots/big.png', uploaded: true });+ expect(writes.map((write) => write.path).sort()).toEqual([+ 'pages/a.html',+ 'pages/b.html',+ 'pages/c.html',+ 'shots/big.png',+ 'shots/small.png',+ ]);+ expect(result.uploaded).toHaveLength(5);+ });++ it('fails without committing a large file the server returned no upload for', async () => {+ put('shots/big.png', Buffer.alloc(3 * 1024 * 1024, 9));+ const { api, writeFiles } = client([], { uploads: [] });++ await expect(pushArtboardDir(api, 'art_1', dir, {})).rejects.toThrow(/shots\/big\.png/);+ expect(fetchMock).not.toHaveBeenCalled();+ expect(writeFiles).not.toHaveBeenCalled();+ });++ it('names the file whose presigned upload was refused and commits nothing for it', async () => {+ put('shots/big.png', Buffer.alloc(3 * 1024 * 1024, 3));+ fetchMock.mockResolvedValue(new Response('denied', { status: 403, statusText: 'Forbidden' }));+ const { api, writeFiles } = client([], {+ uploads: [{ path: 'shots/big.png', url: 'https://s3.test/blob' }],+ });++ await expect(pushArtboardDir(api, 'art_1', dir, {})).rejects.toThrow(/shots\/big\.png.*403/);+ expect(writeFiles).not.toHaveBeenCalled();+ });+});diff --git a/apps/cli/src/commands/artboardPush.ts b/apps/cli/src/commands/artboardPush.tsnew file mode 100644index 00000000000..25b50d246fd--- /dev/null+++ b/apps/cli/src/commands/artboardPush.ts@@ -0,0 +1,181 @@+import { createHash } from 'node:crypto';+import fs from 'node:fs';+import path from 'node:path';++import { isArtboardTextPath, normalizeArtboardFilePath } from '@lobechat/types';++interface RemoteFile {+ /** ETag of the stored object: the MD5 hex of its bytes. */+ hash: string;+ path: string;+ size: number;+}++type FileWrite =+ | { base64: string; path: string }+ | { content: string; path: string }+ | { path: string; uploaded: true };++export interface ArtboardFilesApi {+ listFiles: { query: (input: { id: string }) => Promise<RemoteFile[]> };+ prepareFileUploads: {+ mutate: (input: {+ files: { path: string; size: number }[];+ id: string;+ }) => Promise<{ uploads: { headers?: Record<string, string>; path: string; url: string }[] }>;+ };+ writeFiles: {+ mutate: (input: {+ files: { deletes?: string[]; writes?: FileWrite[] };+ id: string;+ }) => Promise<unknown>;+ };+}++export interface LocalArtboardFile {+ bytes: Buffer;+ /** MD5 hex of the bytes, comparable to the ETag `listFiles` reports. */+ hash: string;+ path: string;+}++export interface ArtboardPushResult {+ deleted: string[];+ skipped: string[];+ unchanged: string[];+ uploaded: string[];+}++/**+ * Encoded JSON size of one writeFiles request. Vercel rejects bodies over 4.5 MB+ * and tRPC can batch other calls into the same request, so stay at 2 MB like+ * the web client's message write batcher.+ */+const BATCH_BYTES = 2 * 1024 * 1024;++const encodedBytes = (value: unknown) => Buffer.byteLength(JSON.stringify(value));++export const toLocalArtboardFile = (relative: string, bytes: Buffer): LocalArtboardFile => ({+ bytes,+ hash: createHash('md5').update(bytes).digest('hex'),+ path: relative,+});++const putBlob = async (+ file: LocalArtboardFile,+ upload: { headers?: Record<string, string>; url: string },+) => {+ const response = await fetch(upload.url, {+ body: file.bytes,+ headers: upload.headers,+ method: 'PUT',+ }).catch((error: unknown) => {+ throw new Error(`Upload of ${file.path} failed: ${(error as Error)?.message ?? String(error)}`);+ });+ if (!response.ok)+ throw new Error(`Upload of ${file.path} failed: ${response.status} ${response.statusText}`);+};++/**+ * Writes files to an artboard in requests of at most 2 MB encoded. A file too+ * large for one request is PUT to its path through a presigned URL first and+ * then committed as uploaded.+ */+export const writeArtboardFiles = async (+ api: Pick<ArtboardFilesApi, 'prepareFileUploads' | 'writeFiles'>,+ id: string,+ files: LocalArtboardFile[],+) => {+ const envelope = encodedBytes({ files: { writes: [] }, id });+ const writes: FileWrite[] = [];+ const large: LocalArtboardFile[] = [];+ for (const file of files) {+ const write: FileWrite = isArtboardTextPath(file.path)+ ? { content: file.bytes.toString('utf8'), path: file.path }+ : { base64: file.bytes.toString('base64'), path: file.path };+ if (envelope + encodedBytes(write) > BATCH_BYTES) large.push(file);+ else writes.push(write);+ }++ if (large.length) {+ const { uploads } = await api.prepareFileUploads.mutate({+ files: large.map((file) => ({ path: file.path, size: file.bytes.byteLength })),+ id,+ });+ const byPath = new Map(uploads.map((upload) => [upload.path, upload]));+ for (const file of large) {+ const upload = byPath.get(file.path);+ if (!upload)+ throw new Error(`Upload of ${file.path} failed: the server returned no upload URL`);+ await putBlob(file, upload);+ writes.push({ path: file.path, uploaded: true });+ }+ }++ let batch: FileWrite[] = [];+ let batchBytes = envelope;+ for (const write of writes) {+ // +1 for the comma between array items+ const bytes = encodedBytes(write) + 1;+ if (batch.length && batchBytes + bytes > BATCH_BYTES) {+ await api.writeFiles.mutate({ files: { writes: batch }, id });+ batch = [];+ batchBytes = envelope;+ }+ batch.push(write);+ batchBytes += bytes;+ }+ if (batch.length) await api.writeFiles.mutate({ files: { writes: batch }, id });+};++const listLocal = (root: string, dir = root): string[] =>+ fs.readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {+ if (entry.name.startsWith('.')) return [];+ const full = path.join(dir, entry.name);+ if (entry.isDirectory()) return listLocal(root, full);+ return entry.isFile() ? [path.relative(root, full).split(path.sep).join('/')] : [];+ });++export const pushArtboardDir = async (+ api: ArtboardFilesApi,+ id: string,+ dir: string,+ options: { prune?: boolean },+): Promise<ArtboardPushResult> => {+ const remote = new Map((await api.listFiles.query({ id })).map((file) => [file.path, file.hash]));+ const result: ArtboardPushResult = {+ deleted: [],+ skipped: [],+ unchanged: [],+ uploaded: [],+ };+ const local = new Set<string>();+ const changed: LocalArtboardFile[] = [];++ for (const relative of listLocal(dir).sort()) {+ const normalized = normalizeArtboardFilePath(relative);+ if (!normalized) {+ result.skipped.push(relative);+ continue;+ }+ local.add(normalized);+ const file = toLocalArtboardFile(normalized, fs.readFileSync(path.join(dir, relative)));+ if (remote.get(normalized) === file.hash) {+ result.unchanged.push(normalized);+ continue;+ }+ changed.push(file);+ result.uploaded.push(normalized);+ }++ await writeArtboardFiles(api, id, changed);++ if (options.prune) {+ const missing = [...remote.keys()].filter((file) => !local.has(file));+ if (missing.length) {+ await api.writeFiles.mutate({ files: { deletes: missing }, id });+ result.deleted = missing;+ }+ }+ return result;+};diff --git a/apps/cli/src/commands/artboardSkill.test.ts b/apps/cli/src/commands/artboardSkill.test.tsnew file mode 100644index 00000000000..9c0d964ae7d--- /dev/null+++ b/apps/cli/src/commands/artboardSkill.test.ts@@ -0,0 +1,224 @@+import { mkdir, mkdtemp, readFile, readlink, rm, symlink, writeFile } from 'node:fs/promises';+import { tmpdir } from 'node:os';+import path from 'node:path';++import { Command } from 'commander';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { registerArtboardCommand } from './artboard';+import { ARTBOARD_SKILL_ID } from './artboardSkill';++const { output, version } = vi.hoisted(() => ({ output: vi.fn(), version: { value: '1.4.0' } }));+vi.mock('../pkg', () => ({+ get cliVersion() {+ return version.value;+ },+}));+vi.mock('../api/client', () => ({ getTrpcClient: vi.fn() }));+vi.mock('../utils/format', () => ({ outputJson: output }));++const run = async (...args: string[]) => {+ const program = new Command().exitOverride();+ registerArtboardCommand(program);+ await program.parseAsync(['node', 'lh', 'artboard', 'skill', 'init', ...args]);+};++describe('lh artboard skill init', () => {+ let directory: string;+ const skillPath = (...parts: string[]) =>+ path.join(directory, '.agents', 'skills', ARTBOARD_SKILL_ID, ...parts);++ beforeEach(async () => {+ directory = await mkdtemp(path.join(tmpdir(), 'artboard-skill-'));+ version.value = '1.4.0';+ vi.spyOn(console, 'log').mockImplementation(() => {});+ });++ afterEach(async () => {+ vi.restoreAllMocks();+ output.mockReset();+ await rm(directory, { force: true, recursive: true });+ });++ it('writes the skill with the version of the CLI that wrote it', async () => {+ await run('--dir', directory);++ const skill = await readFile(skillPath('SKILL.md'), 'utf8');+ expect(skill).toMatch(/^---\nname: lobehub-artboard\ndescription: ".+"\n/);+ expect(skill).toContain('metadata:\n version: "1.4.0"\n---\n');+ });++ it('links the skill for a harness that does not read .agents/skills', async () => {+ await writeFile(path.join(directory, 'CLAUDE.md'), '');++ await run('--dir', directory);++ expect(await readlink(path.join(directory, '.claude', 'skills'))).toBe(+ path.join('..', '.agents', 'skills'),+ );+ });++ it('replaces an edited skill and removes files the current version does not have', async () => {+ await run('--dir', directory);+ const written = await readFile(skillPath('SKILL.md'), 'utf8');+ await writeFile(skillPath('SKILL.md'), written.replace(/\n[^\n]+\n$/, '\nedited by hand\n'));+ await mkdir(skillPath('references'), { recursive: true });+ await writeFile(skillPath('references', 'old.md'), 'stale');++ await run('--dir', directory, '--json');++ expect(await readFile(skillPath('SKILL.md'), 'utf8')).toBe(written);+ await expect(readFile(skillPath('references', 'old.md'), 'utf8')).rejects.toThrow();+ expect(output).toHaveBeenCalledWith(+ expect.objectContaining({+ removed: ['references/old.md'],+ status: 'installed',+ version: '1.4.0',+ written: ['SKILL.md'],+ }),+ );+ });++ it('leaves a skill written by a newer CLI alone', async () => {+ version.value = '1.10.0';+ await run('--dir', directory);+ const newer = await readFile(skillPath('SKILL.md'), 'utf8');+ version.value = '1.9.3';++ await run('--dir', directory, '--json');++ expect(await readFile(skillPath('SKILL.md'), 'utf8')).toBe(newer);+ expect(output).toHaveBeenLastCalledWith(+ expect.objectContaining({+ installedVersion: '1.10.0',+ status: 'newer-installed',+ version: '1.9.3',+ written: [],+ }),+ );+ });++ it('still sees the installed version after a formatter rewrote the frontmatter', async () => {+ version.value = '1.10.0';+ await run('--dir', directory);+ const reformatted = (await readFile(skillPath('SKILL.md'), 'utf8')).replace(+ ' version: "1.10.0"',+ " version: '1.10.0'",+ );+ await writeFile(skillPath('SKILL.md'), reformatted);+ version.value = '1.9.3';++ await run('--dir', directory, '--json');++ expect(await readFile(skillPath('SKILL.md'), 'utf8')).toBe(reformatted);+ expect(output).toHaveBeenLastCalledWith(expect.objectContaining({ status: 'newer-installed' }));+ });++ it('removes nothing when the skill directory is a link to somewhere else', async () => {+ const elsewhere = path.join(directory, 'elsewhere');+ await mkdir(elsewhere);+ await writeFile(path.join(elsewhere, 'keep.md'), 'not ours');+ await mkdir(path.join(directory, '.agents', 'skills'), { recursive: true });+ await symlink(elsewhere, skillPath());++ await expect(run('--dir', directory)).rejects.toThrow(/symbolic link/);++ expect(await readFile(path.join(elsewhere, 'keep.md'), 'utf8')).toBe('not ours');+ });++ it('builds screens as plain HTML files of the artboard, pushed with lh artboard push', async () => {+ await run('--dir', directory);++ const skill = await readFile(skillPath('SKILL.md'), 'utf8');++ expect(skill).toMatch(/plain HTML/i);+ expect(skill).toContain('lh artboard push');+ expect(skill).not.toMatch(/lh artifact save|Canvas/);+ });++ it('streams: lays out every board first, then writes their files one at a time', async () => {+ await run('--dir', directory);++ const skill = await readFile(skillPath('SKILL.md'), 'utf8');+ const create = skill.indexOf('lh artboard create');+ const write = skill.indexOf('lh artboard files write <id> <path> --from <file>');+ expect(create).toBeGreaterThan(-1);+ expect(write).toBeGreaterThan(create);+ expect(skill).toMatch(/not written yet/i);+ expect(skill).toMatch(/one board at a time/i);+ expect(skill).toMatch(/push[^.]*re-?sync/i);+ });++ it('answers the comments on the board itself and asks board questions there', async () => {+ await run('--dir', directory);++ const skill = await readFile(skillPath('SKILL.md'), 'utf8');+ expect(skill).toContain('lh artboard comments <id>');+ expect(skill).toContain('lh artboard reply <commentId>');+ expect(skill).toContain('lh artboard resolve <commentId>');+ expect(skill).toContain('lh artboard ask <id>');+ });++ it('does not tie a board to an existing file', async () => {+ await run('--dir', directory);++ const skill = await readFile(skillPath('SKILL.md'), 'utf8');+ expect(skill).not.toMatch(/cannot be (?:removed|deleted)/i);+ expect(skill).not.toMatch(/--prune` keeps/i);+ expect(skill).not.toMatch(/must exist/i);+ });++ it('states what the journey needs before it can be finalized', async () => {+ await run('--dir', directory);++ const skill = await readFile(skillPath('SKILL.md'), 'utf8');+ expect(skill).toMatch(/exactly one starting screen/i);+ expect(skill).toMatch(/no edge may point back to it/i);+ });++ it('carries a finalized artboard through to its acceptance', async () => {+ await run('--dir', directory);++ const skill = await readFile(skillPath('SKILL.md'), 'utf8');+ expect(skill).toMatch(/## 6\. After the user finalizes/);+ expect(skill).toContain('lh acceptance flow plan <acceptanceId>');+ expect(skill).toMatch(/do not publish another flow or create another acceptance/i);+ });++ it('says what to do when no screen can be made, instead of a decision board', async () => {+ await run('--dir', directory);++ const skill = await readFile(skillPath('SKILL.md'), 'utf8');+ expect(skill).toMatch(/no screen can be made[^.]*\./i);+ expect(skill).toMatch(/never stand a decision board[^.]*in for a screen/i);+ });++ it('says that a decision board takes no acceptance check', async () => {+ await run('--dir', directory);++ expect(await readFile(skillPath('SKILL.md'), 'utf8')).toMatch(+ /decision board[^.]*\bno(ne)?\b/i,+ );+ });++ it('touches nothing outside the skill directory and the harness links', async () => {+ await writeFile(path.join(directory, '.gitignore'), 'node_modules\n');++ await run('--dir', directory);++ expect(await readFile(path.join(directory, '.gitignore'), 'utf8')).toBe('node_modules\n');+ });++ it('names no artboard command the CLI lacks', async () => {+ await run('--dir', directory);++ const skill = await readFile(skillPath('SKILL.md'), 'utf8');+ expect(skill).toContain('lh man artboard');+ expect(skill).toContain('lh artboard ops');+ expect(skill).toContain('lh artboard files write');+ expect(skill).not.toMatch(+ /lh artboard (?!create|update|read|list|ops|push|files (?:list|read|write|rm)\b|comments|reply|resolve|ask|--help|skill)[a-z]/,+ );+ expect(skill).not.toMatch(/listArtboardComments|replyArtboardComment|askArtboardQuestion/);+ });+});diff --git a/apps/cli/src/commands/artboardSkill.ts b/apps/cli/src/commands/artboardSkill.tsnew file mode 100644index 00000000000..6acd464e92f--- /dev/null+++ b/apps/cli/src/commands/artboardSkill.ts@@ -0,0 +1,154 @@+import {+ existsSync,+ lstatSync,+ mkdirSync,+ readdirSync,+ readFileSync,+ rmSync,+ writeFileSync,+} from 'node:fs';+import path from 'node:path';++import type { Command } from 'commander';+import pc from 'picocolors';++import { cliVersion } from '../pkg';+import { outputJson } from '../utils/format';+import { AGENTS_SKILLS_DIR, linkHarnessSkills, type LinkResult } from '../utils/skillWiring';+import { artboardSkillBody, artboardSkillDescription } from './artboardSkillContent';++export const ARTBOARD_SKILL_ID = 'lobehub-artboard';++const VERSION_LINE = /^\s+version:\s*["']?(\d+)\.(\d+)\.(\d+)/m;++const renderSkill = (version: string) =>+ [+ '---',+ `name: ${ARTBOARD_SKILL_ID}`,+ `description: ${JSON.stringify(artboardSkillDescription)}`,+ 'metadata:',+ ` version: ${JSON.stringify(version)}`,+ '---',+ '',+ artboardSkillBody,+ ].join('\n');++const versionParts = (text: string) => {+ const match = /^(\d+)\.(\d+)\.(\d+)/.exec(text);+ return match ? match.slice(1).map(Number) : undefined;+};++const installedVersion = (skillFile: string) => {+ if (!existsSync(skillFile)) return undefined;+ const match = VERSION_LINE.exec(readFileSync(skillFile, 'utf8'));+ return match ? match.slice(1, 4).join('.') : undefined;+};++const isNewer = (installed: string | undefined, current: string) => {+ const a = installed && versionParts(installed);+ const b = versionParts(current);+ if (!a || !b) return false;+ for (let index = 0; index < 3; index += 1) {+ if (a[index] !== b[index]) return a[index] > b[index];+ }+ return false;+};++const listFiles = (directory: string): string[] => {+ if (!existsSync(directory)) return [];+ return readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {+ const entryPath = path.join(directory, entry.name);+ return entry.isDirectory() ? listFiles(entryPath) : [entryPath];+ });+};++const printLinks = (links: LinkResult[]) => {+ const arrow = pc.dim(' ↳');+ for (const link of links) {+ if (link.kind === 'linked' || link.kind === 'linked-single')+ console.log(`${arrow} linked ${link.link} → ${pc.dim(link.target)}`);+ else if (link.kind === 'already')+ console.log(`${arrow} ${pc.dim(`${link.link} already linked`)}`);+ else if (link.kind === 'skipped')+ console.log(`${arrow} ${pc.yellow(`skipped ${link.link}: ${link.reason}`)}`);+ else+ console.log(+ `${arrow} ${pc.dim('no harness dirs detected — agents that read .agents/skills pick it up automatically')}`,+ );+ }+};++interface InitOptions {+ dir?: string;+ json?: boolean;+}++const initAction = (options: InitOptions) => {+ const baseDir = options.dir ? path.resolve(options.dir) : process.cwd();+ const skillDir = path.join(baseDir, AGENTS_SKILLS_DIR, ARTBOARD_SKILL_ID);+ const skillFile = path.join(skillDir, 'SKILL.md');+ if (lstatSync(skillDir, { throwIfNoEntry: false })?.isSymbolicLink())+ throw new Error(+ `${skillDir} is a symbolic link; remove it or point --dir at the repository that owns the skill`,+ );+ const installed = installedVersion(skillFile);++ if (isNewer(installed, cliVersion)) {+ const result = {+ dir: skillDir,+ installedVersion: installed,+ links: [] as LinkResult[],+ removed: [] as string[],+ skill: ARTBOARD_SKILL_ID,+ status: 'newer-installed' as const,+ version: cliVersion,+ written: [] as string[],+ };+ if (options.json) return outputJson(result);+ console.log(+ `${pc.yellow('!')} ${ARTBOARD_SKILL_ID} v${installed} is already installed and this lh is v${cliVersion}; nothing changed`,+ );+ return;+ }++ const removed = listFiles(skillDir)+ .filter((file) => file !== skillFile)+ .map((file) => {+ rmSync(file, { force: true });+ return path.relative(skillDir, file).split(path.sep).join('/');+ });+ mkdirSync(skillDir, { recursive: true });+ writeFileSync(skillFile, renderSkill(cliVersion), 'utf8');+ const links = linkHarnessSkills(baseDir, ARTBOARD_SKILL_ID);++ const result = {+ dir: skillDir,+ installedVersion: installed,+ links,+ removed,+ skill: ARTBOARD_SKILL_ID,+ status: 'installed' as const,+ version: cliVersion,+ written: ['SKILL.md'],+ };+ if (options.json) return outputJson(result);+ console.log(+ `${pc.green('✓')} ${pc.bold(ARTBOARD_SKILL_ID)} ${pc.dim(`v${cliVersion}`)} skill → ${pc.dim(path.relative(process.cwd(), skillDir) || skillDir)}`,+ );+ console.log(` written: SKILL.md${removed.length ? ` · removed: ${removed.join(', ')}` : ''}`);+ printLinks(links);+ console.log(pc.dim(' Commit these files so agents working in this repository load the skill.'));+};++export const registerArtboardSkillCommand = (artboard: Command) => {+ artboard+ .command('skill')+ .description('The agent skill that tells CLI agents when and how to use the artboard')+ .command('init')+ .description(+ 'Write the artboard skill into this repository (.agents/skills) or bring it up to date',+ )+ .option('--dir <path>', 'Target working directory (default: current dir)')+ .option('--json', 'Print structured JSON')+ .action(initAction);+};diff --git a/apps/cli/src/commands/artboardSkillContent.ts b/apps/cli/src/commands/artboardSkillContent.tsnew file mode 100644index 00000000000..d033e41318e--- /dev/null+++ b/apps/cli/src/commands/artboardSkillContent.ts@@ -0,0 +1,88 @@+export const artboardSkillDescription =+ 'Lay out a feature or requirement on a LobeHub artboard so the user decides on the canvas. Use when the user wants to discuss, explore, shape or confirm a feature or requirement and this session runs inside a LobeHub project conversation (`LOBEHUB_TOPIC_ID` is set). In that case this skill takes the place of a generic brainstorming or requirements skill: the open decisions go on the artboard as choices, not into a run of questions in chat. Not for bug fixes, small or already specified changes, or questions about existing code.';++export const artboardSkillBody = `# Requirement artboard++An artboard is a canvas in the user's LobeHub project. You lay a requirement out on it: the screens, the flow between them, and the decisions you are unsure of as choices. The user picks on the canvas and submits; you carry on from their picks. You work on it through the \`lh\` CLI, which is already installed and signed in for this run.++## 1. Check first++- \`LOBEHUB_TOPIC_ID\` is set: this session runs inside a LobeHub conversation.+- \`lh artboard --help\` prints the artboard commands.++If either fails, or \`lh artboard create\` is refused, say so in one line and hold the discussion in chat the way you normally would. Do not install or upgrade \`lh\`.++## 2. Read before you draw++Read the repository for the data and the screens the requirement touches, so the artboard starts from what exists. Change no code while the requirement is being discussed.++## 3. Lay it out++Run \`lh man artboard\` for the exact flags and \`lh artboard ops\` for the shape of every op; both come from the installed CLI and are not repeated here. One requirement gets one artboard: \`lh artboard create\` makes it for this conversation's project, \`lh artboard list\` shows the ones that already exist.++**Screens.** A board shows a screen. Write each screen as a plain HTML page, a real screen of the product at the board's size with its own layout, colors, type and inline SVG, in a folder laid out like the artboard (for example \`pages/checkout/a.html\`, shared CSS in \`shared/base.css\`, screenshots in \`shots/\`, all referenced by relative paths). A board points at its page with source \`{"kind":"file","path":"pages/checkout/a.html"}\`; the file may not be written yet, and the board shows the page as soon as it is. Build the artboard in this order, so the user watches it fill in:++1. Lay out the whole structure first: one \`lh artboard create --ops\` (or \`lh artboard update --ops\` on an artboard that exists) with the pages, groups, edges and every board, each board's source pointing at the path its page will have although that file is not written yet.+2. Then write the pages one board at a time with \`lh artboard files write <id> <path> --from <file>\` (or from stdin), each as soon as it is ready, so the boards appear one by one. Write the shared CSS and images a page uses before the page.+3. \`lh artboard push <id> <dir>\` re-syncs a whole folder later: it uploads only the files that changed, and with \`--prune\` deletes the artboard files that are no longer in the folder.++- a page cannot fetch or open network connections; https images, fonts, styles and scripts load;+- to change a screen, write its file again: every board showing it updates and comments on it are marked outdated;+- \`lh artboard files list <id>\`, \`lh artboard files read <id> <path>\` and \`lh artboard files rm <id> <path>\` list, print and remove files; a board whose file is removed stays and shows the page again once it is written;+- a screenshot of the current product can be an image board: write it under \`shots/\` and point a board at it.++A board of type "decision" needs no source.++If no screen can be made (writing the files is refused or times out), tell the user in one line which step failed and hold the discussion in chat. Never stand a decision board or a text card in for a screen: a decision board marks where the journey branches and shows only a short title.++**Layout.**++- An artboard has pages; each page has its own coordinates. Use a second page when the choices would crowd the flow.+- Group the boards: one journey group for the flow the user will accept, and separate groups for options and references.+- In the journey group one board is one page state. Edges connect boards. The journey has exactly one starting screen, the only journey board no edge points to, and every other journey board is reached from it. No edge may point back to it: a way back to the start belongs in that screen's acceptance check. A journey that breaks this cannot be finalized. Label an edge, in at most four words, only when the two screens do not already show what the user does to get there.+- Where the flow branches, add a decision board, give each edge leaving it a condition, and mark the fallback branch as the default.+- Give every journey board an acceptance check: what the user must see on that page. A decision board takes none; one that carries a check is refused.+- You place every board; the user cannot move them. Boards are 640×400 unless you set a size. Leave 80 between boards in a row and lay a journey out left to right.+- A frame is drawn around each group (144 above its boards, 48 on the other sides). Leave 240 between the boards of two groups stacked vertically and 200 between groups side by side, measured from the lowest and rightmost board of a group. An update whose group frames overlap is refused.++**Choices.** Every decision you are not sure of becomes a round:++- add a round whose title is the question, then add each alternative as a board that carries that round's id and sits in an options group, and mark the one you would pick as recommended;+- one options group holds the options of exactly one round;+- the user submits every open round at once, so open only the rounds you want answered now.++**Comments and questions.** The user comments on boards, groups and pages. Answer them on the artboard, not only in chat:++- \`lh artboard comments <id>\` prints the threads waiting for you, each with its id and what it is on; the ones printed count as read;+- \`lh artboard reply <commentId> <text>\` answers a thread, and \`lh artboard resolve <commentId>\` closes it once what it asks for is done;+- to ask about one screen, group or page, use \`lh artboard ask <id> --board <boardId> <question>\` (or \`--group\`, \`--page\`) instead of asking in chat. The user answers in that thread, and the artboard cannot be finalized while your question is open: resolve it once you have the answer.++## 4. Hand over++Reply with what is on the artboard and what is waiting for the user's choice. Do not ask the same questions again in chat. A question about something on the artboard goes there with \`lh artboard ask\`; ask in your reply only what concerns no screen.++## 5. After the user submits++The picks and the user's new comments arrive as one message in this conversation. Then:++1. \`lh artboard read <id>\` to see each round's chosen board; a round the user left unpicked takes your recommendation.+2. \`lh artboard comments <id>\` for the threads and their ids; the user's answers to your questions are there too.+3. Apply the picks and what the comments ask for in one \`lh artboard update\`.+4. Reply in each thread with what you changed, then resolve the threads that are done and the questions that are answered.+5. Open the next rounds if something is still undecided; otherwise say the requirement is settled and what was decided.++## 6. After the user finalizes++Finalizing turns the journey into an acceptance. The message that arrives carries its link, and \`lh artboard read <id> --json\` gives its \`acceptanceId\`. Its flow is already published: one check per journey board, whose expected result is that board's acceptance check. Then:++1. Build the journey in this repository.+2. Verify it with the acceptance skill (\`lh acceptance install\` adds it to \`.agents/skills\` when it is missing), on that acceptance and its published flow: \`lh acceptance flow plan <acceptanceId>\` opens a round, \`lh acceptance flow record\` records each check's verdict, \`lh acceptance run evidence upload\` attaches a screenshot of the page to it, and \`lh acceptance flow complete\` closes the round. Do not publish another flow or create another acceptance: the artboard shows only this one.+3. Reply with the acceptance link and which checks passed or failed. Each journey board on the artboard then shows its check's result and screenshot.++## Editing rules++- \`lh artboard update\` needs the revision you last read. If it is refused as stale, read again and redo the change on the new revision.+- Every op in one update applies, or none does.+- Use only ids the CLI returned; never invent one. Inside one call, give an added item a ref so later ops can point at it.+- After the artboard is finalized, the journey group's boards, edges and checks are locked; other groups can still change.+`;diff --git a/apps/cli/src/commands/artifact.canvasSave.test.ts b/apps/cli/src/commands/artifact.canvasSave.test.tsnew file mode 100644index 00000000000..a6d63223ebc--- /dev/null+++ b/apps/cli/src/commands/artifact.canvasSave.test.ts@@ -0,0 +1,120 @@+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';++import { Command } from 'commander';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { registerArtifactCommand } from './artifact';++const mocks = vi.hoisted(() => ({+ getPublishContext: vi.fn(),+ getVersion: vi.fn(),+ publish: vi.fn(),+ save: vi.fn(),+}));+vi.mock('../api/client', () => ({+ getTrpcClient: async () => ({+ canvas: {+ getPublishContext: { query: mocks.getPublishContext },+ getVersion: { query: mocks.getVersion },+ publish: { mutate: mocks.publish },+ save: { mutate: mocks.save },+ },+ }),+}));+vi.mock('../settings', () => ({ resolveServerUrl: () => 'http://localhost:3010' }));++describe('artifact save', () => {+ let root: string;+ let output: ReturnType<typeof vi.spyOn>;+ let exit: ReturnType<typeof vi.spyOn>;+ const binding = () =>+ JSON.parse(fs.readFileSync(path.join(root, '.lobehub/artifacts.json'), 'utf8')).artifacts[+ 'screen.html'+ ];+ const payload = () => JSON.parse(output.mock.calls.flat().join('\n'));+ const save = async (...args: string[]) => {+ output.mockClear();+ const program = new Command().exitOverride();+ registerArtifactCommand(program);+ await program.parseAsync([+ 'node',+ 'lh',+ 'artifact',+ 'save',+ path.join(root, 'screen.html'),+ '--root',+ root,+ '--json',+ ...args,+ ]);+ };++ beforeEach(() => {+ vi.resetAllMocks();+ root = fs.mkdtempSync(path.join(os.tmpdir(), 'lh-canvas-save-'));+ fs.writeFileSync(path.join(root, 'screen.html'), '<title>Checkout</title><h1>Checkout</h1>');+ output = vi.spyOn(console, 'log').mockImplementation(() => {});+ exit = vi.spyOn(process, 'exit').mockImplementation((() => {}) as any);+ mocks.getPublishContext.mockResolvedValue({+ canPublish: false,+ userId: 'u1',+ workspaceId: null,+ });+ mocks.getVersion.mockResolvedValue({ canPublish: false, version: 1 });+ mocks.save.mockResolvedValue({ canvasId: 'cvs_1', version: 1, workId: 'wk_1' });+ });+ afterEach(() => {+ vi.restoreAllMocks();+ fs.rmSync(root, { force: true, recursive: true });+ });++ it('saves a Canvas on a server that cannot publish, without publishing it', async () => {+ await save();+ expect(exit).not.toHaveBeenCalled();+ expect(payload()).toEqual({ canvasId: 'cvs_1', version: 1, workId: 'wk_1' });+ expect(mocks.publish).not.toHaveBeenCalled();+ expect(mocks.save.mock.calls[0][0]).toMatchObject({+ expectedVersion: 0,+ html: expect.stringContaining('<h1>Checkout</h1>'),+ title: 'Checkout',+ });+ expect(binding()).toMatchObject({ canvasId: 'cvs_1', type: 'canvas', version: 1 });+ expect(binding().pendingCreateKey).toBeUndefined();+ });++ it('saves the next version of the bound Canvas', async () => {+ await save();+ mocks.save.mockResolvedValueOnce({ canvasId: 'cvs_1', version: 2, workId: 'wk_1' });+ await save();+ expect(mocks.save.mock.calls[1][0]).toMatchObject({ canvasId: 'cvs_1', expectedVersion: 1 });+ expect(payload()).toMatchObject({ canvasId: 'cvs_1', version: 2 });+ });++ it('starts a separate Canvas with --new', async () => {+ await save();+ mocks.save.mockResolvedValueOnce({ canvasId: 'cvs_2', version: 1, workId: 'wk_2' });+ await save('--new');+ expect(mocks.save.mock.calls[1][0]).toMatchObject({ canvasId: undefined, expectedVersion: 0 });+ expect(binding()).toMatchObject({ canvasId: 'cvs_2', version: 1 });+ });++ it('retries a save whose response was lost with the same request id', async () => {+ mocks.save.mockRejectedValueOnce(new Error('Response lost'));+ await save();+ expect(exit).toHaveBeenCalledWith(1);+ const { requestId } = mocks.save.mock.calls[0][0];+ await save();+ expect(mocks.save.mock.calls[1][0].requestId).toBe(requestId);+ expect(payload()).toMatchObject({ canvasId: 'cvs_1' });+ });++ it('does not replay a lost request once the content has changed', async () => {+ mocks.save.mockRejectedValueOnce(new Error('Response lost'));+ await save();+ fs.writeFileSync(path.join(root, 'screen.html'), '<h1>Changed</h1>');+ await save();+ expect(mocks.save.mock.calls[1][0].requestId).not.toBe(mocks.save.mock.calls[0][0].requestId);+ });+});diff --git a/apps/cli/src/commands/artifact.ts b/apps/cli/src/commands/artifact.tsindex f5d659660fe..ee05aa76539 100644--- a/apps/cli/src/commands/artifact.ts+++ b/apps/cli/src/commands/artifact.ts@@ -24,7 +24,7 @@ import { formatError } from '../utils/error';import { outputJson } from '../utils/format';import { log } from '../utils/logger';import { readLocalHtmlAsset } from '../utils/readLocalHtmlAsset';-import { publishCanvasArtifact } from './artifactCanvas';+import { publishCanvasArtifact, saveCanvasArtifact } from './artifactCanvas';interface PreparedUploadTarget {headers: Record<string, string>;@@ -142,6 +142,68 @@ export function registerArtifactCommand(program: Command) {console.log(output.content);});+ artifact+ .command('save <file>')+ .description(+ 'Save a local Canvas page as a new Canvas version without publishing it to the web',+ )+ .option(+ '--root <dir>',+ 'Directory the page may reference assets from (defaults to the working directory)',+ )+ .option('--new', 'Start a separate Canvas instead of a new version of the bound one')+ .option('--title <title>', 'Override the page title')+ .option('--json [fields]', 'Output JSON, optionally specify fields (comma-separated)')+ .action(+ async (+ file: string,+ options: { json?: string | boolean; new?: boolean; root?: string; title?: string },+ ) => {+ const entryPath = path.resolve(file);+ const rootDirectory = path.resolve(options.root ?? process.cwd());+ if (!entryPath.startsWith(`${rootDirectory}${path.sep}`) && entryPath !== rootDirectory) {+ fail(`${file} is outside ${rootDirectory}. Pass --root to widen the saved directory.`);+ return;+ }++ const entry = await readLocalHtmlAsset(entryPath);+ if (!entry.ok || entry.text === undefined) {+ fail(`Cannot read ${file}`);+ return;+ }++ const manifest = resolveManifest(entryPath, rootDirectory);+ const binding = readBinding(manifest);+ if (!options.new && binding.deploymentId && (binding.type ?? 'html') !== 'canvas') {+ fail('This file is bound to an HTML artifact; pass --new to save it as a Canvas.');+ return;+ }++ try {+ const saved = await saveCanvasArtifact(await getTrpcClient(), {+ binding,+ html: entry.text,+ manifest,+ new: options.new,+ title:+ options.title ||+ extractHtmlTitle(entry.text) ||+ path.basename(entryPath, path.extname(entryPath)),+ });+ if (options.json !== undefined) {+ outputJson(saved, typeof options.json === 'string' ? options.json : undefined);+ } else {+ console.log(+ `${pc.green('✓')} Saved Canvas ${saved.canvasId} (version ${saved.version})`,+ );+ }+ } catch (error) {+ if (options.json !== undefined) outputJson({ error: formatError(error), success: false });+ fail(formatError(error));+ }+ },+ );+artifact.command('publish <file>').description('Publish a local HTML file, bundling the assets it references')diff --git a/apps/cli/src/commands/artifactCanvas.ts b/apps/cli/src/commands/artifactCanvas.tsindex 0e213670196..30918eaed1a 100644--- a/apps/cli/src/commands/artifactCanvas.ts+++ b/apps/cli/src/commands/artifactCanvas.ts@@ -150,3 +150,68 @@ export const publishCanvasArtifact = async (subdomainLabel: published.subdomainLabel,};};++const saveFingerprint = (html: string, title: string, createNew: boolean) =>+ createHash('sha256')+ .update(JSON.stringify(['save', html, title, createNew]))+ .digest('hex');++export const saveCanvasArtifact = async (+ client: TrpcClient,+ params: {+ binding: ArtifactBinding;+ html: string;+ manifest: ResolvedManifest;+ new?: boolean;+ title: string;+ },+) => {+ const { binding, html, manifest, title } = params;+ if (binding.pendingCanvas) {+ throw new Error(+ 'A Canvas publication is pending; retry lh artifact publish with the original input first',+ );+ }+ if (binding.pendingCreateKey && binding.pendingType !== 'canvas') {+ throw new Error('Complete the pending HTML publication before saving a Canvas');+ }+ const context = await client.canvas.getPublishContext.query();+ const scope = JSON.stringify([resolveServerUrl(), context.userId, context.workspaceId]);+ if (binding.scope && binding.scope !== scope) {+ throw new Error('This artifact is bound to a different server, account or workspace');+ }++ const createNew = !!params.new;+ const canvasId = createNew ? undefined : binding.canvasId;+ const current = canvasId ? await client.canvas.getVersion.query({ canvasId }) : null;+ if (canvasId && !current) {+ throw new Error('The bound Canvas is unavailable to this account; save it with --new');+ }++ const fingerprint = saveFingerprint(html, title, createNew);+ const requestId =+ binding.pendingCanvasSave?.fingerprint === fingerprint+ ? binding.pendingCanvasSave.requestId+ : createIdempotencyKey();+ writeBinding(manifest, { ...binding, pendingCanvasSave: { fingerprint, requestId } });++ const saved = await client.canvas.save.mutate({+ canvasId,+ expectedVersion: current?.version ?? 0,+ html,+ requestId,+ title,+ });++ const { pendingCanvasSave: _pending, ...settled } = binding;+ writeBinding(manifest, {+ ...settled,+ ...(createNew && { deploymentId: undefined }),+ canvasId: saved.canvasId,+ scope,+ type: 'canvas',+ version: saved.version,+ workId: saved.workId,+ });+ return saved;+};diff --git a/apps/cli/src/program.ts b/apps/cli/src/program.tsindex 9556d39a5b5..7b55abfed29 100644--- a/apps/cli/src/program.ts+++ b/apps/cli/src/program.ts@@ -5,6 +5,7 @@ import { registerVerifyCommand } from './commands/acceptance/deprecatedVerify';import { registerAgentCommand } from './commands/agent';import { registerAgentGroupCommand } from './commands/agent-group';import { registerAgentSignalCommand } from './commands/agent-signal';+import { registerArtboardCommand } from './commands/artboard';import { registerArtifactCommand } from './commands/artifact';import { registerAutomationCommand } from './commands/automation';import { registerBotCommand } from './commands/bot';@@ -106,6 +107,7 @@ export function createProgram() {registerAgentGroupCommand(program);registerAgentSignalCommand(program);registerBotCommand(program);+ registerArtboardCommand(program);registerChannelCommand(program);registerGenerateCommand(program);registerGoalCommand(program);diff --git a/apps/cli/src/utils/artifactManifest.ts b/apps/cli/src/utils/artifactManifest.tsindex bcd8ff1f42f..47afb7d31be 100644--- a/apps/cli/src/utils/artifactManifest.ts+++ b/apps/cli/src/utils/artifactManifest.ts@@ -23,6 +23,7 @@ export interface ArtifactBinding {rejectedPublication?: { requestedSlug?: string };saved?: { canvasId: string; version: number; workId: string };};+ pendingCanvasSave?: { fingerprint: string; requestId: string };/*** What the pending HTML create sent (title, slug and file bytes). Market* replays a key only for the identical request, so a changed publish must@@ -77,6 +78,9 @@ const bindingSchema = z.optional(),}).optional(),+ pendingCanvasSave: z+ .object({ fingerprint: z.string().regex(/^[\da-f]{64}$/), requestId: z.uuid() })+ .optional(),pendingCreateFingerprint: z.string().min(1).optional(),pendingCreateKey: z.string().min(1).optional(),pendingType: z.enum(['canvas', 'html']).optional(),diff --git a/apps/desktop/src/main/controllers/RemoteServerConfigCtr.ts b/apps/desktop/src/main/controllers/RemoteServerConfigCtr.tsindex 5260b851d6b..254353f82b2 100644--- a/apps/desktop/src/main/controllers/RemoteServerConfigCtr.ts+++ b/apps/desktop/src/main/controllers/RemoteServerConfigCtr.ts@@ -1,10 +1,11 @@+import { readFileSync } from 'node:fs';import querystring from 'node:querystring';import { URL } from 'node:url';import type { DataSyncConfig, DesktopBootstrapIdentity } from '@lobechat/electron-client-ipc';import { safeStorage, session as electronSession } from 'electron';-import { OFFICIAL_CLOUD_SERVER } from '@/const/env';+import { isDev, OFFICIAL_CLOUD_SERVER } from '@/const/env';import { refreshAppSignIn, withdrawAppSignIn } from '@/modules/cliEmbedding/appSignInFile';import GatewayConnectionService from '@/services/gatewayConnectionSrv';import { appendVercelCookie } from '@/utils/http-headers';@@ -578,12 +579,45 @@ export default class RemoteServerConfigCtr extends ControllerModule {return this.lastRefreshAt;}+ // Before windows open: the main window picks onboarding vs app from this config.+ beforeAppReady() {+ const login = this.readDevRemoteLogin();+ if (!login) return;+ logger.info(`Dev login: signing in to ${login.remoteServerUrl}`);+ this.app.storeManager.set('dataSyncConfig', {+ active: true,+ remoteServerUrl: login.remoteServerUrl,+ storageMode: 'selfHost',+ });+ this.app.storeManager.set('desktopOnboardingCompleted', true);+ }+// Initialize by loading tokens from store when the controller is ready// We might need a dedicated lifecycle method if constructor is too early for storeManagerafterAppReady() {+ const login = this.readDevRemoteLogin();+ // safeStorage encrypts only once the app is ready. No refresh token exists for a minted+ // login; the access token outlives the dev session.+ if (login) void this.saveTokens(login.accessToken, 'dev-login', login.expiresIn);this.loadTokensFromStore();}+ /**+ * Dev builds only: a sign-in to a local server without the OAuth flow. The dev launcher+ * (`electron-dev.sh start-local`) mints an access token with the local server's own signing key+ * and points LOBE_DESKTOP_DEV_REMOTE_LOGIN at a file holding it. Tokens are then stored the+ * normal way, so keychain encryption and the `lh` sign-in file stay the app's business.+ */+ private readDevRemoteLogin() {+ const file = process.env.LOBE_DESKTOP_DEV_REMOTE_LOGIN;+ if (!isDev || !file) return;+ return JSON.parse(readFileSync(file, 'utf8')) as {+ accessToken: string;+ expiresIn: number;+ remoteServerUrl: string;+ };+ }+async getRemoteServerUrl(config?: DataSyncConfig) {const dataConfig = this.normalizeConfig(config ?? (await this.getRemoteServerConfig()));diff --git a/apps/desktop/src/main/controllers/__tests__/RemoteServerConfigCtr.test.ts b/apps/desktop/src/main/controllers/__tests__/RemoteServerConfigCtr.test.tsindex 3b65d364423..de8014bd1ec 100644--- a/apps/desktop/src/main/controllers/__tests__/RemoteServerConfigCtr.test.ts+++ b/apps/desktop/src/main/controllers/__tests__/RemoteServerConfigCtr.test.ts@@ -1,3 +1,7 @@+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';+import { tmpdir } from 'node:os';+import path from 'node:path';+import type { DataSyncConfig } from '@lobechat/electron-client-ipc';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';@@ -36,7 +40,11 @@ vi.mock('electron', () => ({}));// Mock @/const/env+const env = vi.hoisted(() => ({ isDev: false }));vi.mock('@/const/env', () => ({+ get isDev() {+ return env.isDev;+ },OFFICIAL_CLOUD_SERVER: 'https://cloud.lobehub.com',}));@@ -855,6 +863,61 @@ describe('RemoteServerConfigCtr', () => {// Verify lastRefreshAt was loadedexpect(newController.getLastTokenRefreshAt()).toBe(lastRefreshTime);});++ describe('dev login file', () => {+ let dir: string;+ let file: string;++ beforeEach(() => {+ dir = mkdtempSync(path.join(tmpdir(), 'lobe-dev-login-'));+ file = path.join(dir, 'login.json');+ writeFileSync(+ file,+ JSON.stringify({+ accessToken: 'dev-access',+ expiresIn: 3600,+ remoteServerUrl: 'http://localhost:3010',+ }),+ );+ vi.stubEnv('LOBE_DESKTOP_DEV_REMOTE_LOGIN', file);+ });++ afterEach(() => {+ vi.unstubAllEnvs();+ env.isDev = false;+ rmSync(dir, { force: true, recursive: true });+ });++ it('signs a dev build in to the local server from the launcher file', async () => {+ env.isDev = true;+ const stored = new Map<string, unknown>();+ mockStoreManager.set.mockImplementation((key: string, value: unknown) => {+ stored.set(key, value);+ });+ mockStoreManager.get.mockImplementation((key: string) => stored.get(key));++ const newController = new RemoteServerConfigCtr(mockApp);+ // Before windows open: the main window must start in the app, not the onboarding.+ newController.beforeAppReady();+ expect(stored.get('dataSyncConfig')).toEqual({+ active: true,+ remoteServerUrl: 'http://localhost:3010',+ storageMode: 'selfHost',+ });+ expect(stored.get('desktopOnboardingCompleted')).toBe(true);++ newController.afterAppReady();+ expect(await newController.getAccessToken()).toBe('dev-access');+ });++ it('ignores the file outside a dev build', () => {+ const newController = new RemoteServerConfigCtr(mockApp);+ newController.beforeAppReady();+ newController.afterAppReady();++ expect(mockStoreManager.set).not.toHaveBeenCalledWith('dataSyncConfig', expect.anything());+ });+ });});describe('getLastTokenRefreshAt', () => {diff --git a/apps/server/src/modules/AgentRuntime/executorHelpers.ts b/apps/server/src/modules/AgentRuntime/executorHelpers.tsindex 8c26fd325d9..74435f91223 100644--- a/apps/server/src/modules/AgentRuntime/executorHelpers.ts+++ b/apps/server/src/modules/AgentRuntime/executorHelpers.ts@@ -171,6 +171,7 @@ export const registerWorkFromIntent = async ({deleteDocumentWork: (params) => workModel.deleteDocumentWork(params),deleteTaskWork: (params) => workModel.deleteTaskWork(params),handleSkillToolResult: (params) => workModel.handleSkillToolResult(params),+ registerArtboard: (params) => workModel.registerArtboard(params),registerCanvas: (params) => workModel.registerCanvas(params),registerDocument: (params) => workModel.registerDocument(params),registerTask: (params) => workModel.registerTask(params),diff --git a/apps/server/src/modules/S3/index.ts b/apps/server/src/modules/S3/index.tsindex b075f087ade..b8f0b7e7cb5 100644--- a/apps/server/src/modules/S3/index.ts+++ b/apps/server/src/modules/S3/index.ts@@ -140,6 +140,28 @@ export class S3 {return (response.Contents ?? []).flatMap((object) => (object.Key ? [object.Key] : []));}+ /** Like listFileKeys, with each object's ETag (unquoted) and size. */+ public async listFileObjects(+ prefix: string,+ limit = 1000,+ ): Promise<{ etag: string; key: string; size: number }[]> {+ const response = await this.client.send(+ new ListObjectsV2Command({ Bucket: this.bucket, MaxKeys: limit, Prefix: prefix }),+ );++ return (response.Contents ?? []).flatMap((object) =>+ object.Key+ ? [+ {+ etag: (object.ETag ?? '').replaceAll('"', ''),+ key: object.Key,+ size: object.Size ?? 0,+ },+ ]+ : [],+ );+ }+public async getFileContent(key: string, byteLength?: number): Promise<string> {const boundedLength = byteLength ? Math.max(1, Math.floor(byteLength)) : undefined;const command = new GetObjectCommand({diff --git a/apps/server/src/routers/lambda/__tests__/aiAgent.test.ts b/apps/server/src/routers/lambda/__tests__/aiAgent.test.tsindex ebe082a42dd..c6240e2c0cb 100644--- a/apps/server/src/routers/lambda/__tests__/aiAgent.test.ts+++ b/apps/server/src/routers/lambda/__tests__/aiAgent.test.ts@@ -232,6 +232,28 @@ describe('AI Agent Router Integration Tests', () => {// Only a client that declares `file_works` gets file Work cards in the// pushed snapshots; a released desktop crashes on that Work type.+ it.each([+ [undefined, false],+ [['file_works'], false],+ [['artboard_works'], true],+ ])(+ 'preserves artboard opt-in independently on single and batch runs: %j',+ async (streamFeatures, accepted) => {+ const { AgentRuntimeService } = await import('@/server/services/agentRuntime');+ const caller = aiAgentRouter.createCaller(createTestContext());+ vi.mocked(AgentRuntimeService).mockClear();+ await caller.execAgent({ agentId: testAgentId, prompt: 'single', streamFeatures });+ await caller.execAgents({+ tasks: [{ agentId: testAgentId, prompt: 'batch', streamFeatures }],+ });+ const capabilities = vi+ .mocked(AgentRuntimeService)+ .mock.results.flatMap((result) => (result.value as any).createOperation.mock.calls)+ .map(([params]) => params.acceptsArtboardWorks);+ expect(capabilities).toEqual([accepted, accepted]);+ },+ );+it('forwards a declared file_works stream feature on both routes', async () => {const { AgentRuntimeService } = await import('@/server/services/agentRuntime');const caller = aiAgentRouter.createCaller(createTestContext());diff --git a/apps/server/src/routers/lambda/__tests__/artboard.test.ts b/apps/server/src/routers/lambda/__tests__/artboard.test.tsnew file mode 100644index 00000000000..e21ebb93c70--- /dev/null+++ b/apps/server/src/routers/lambda/__tests__/artboard.test.ts@@ -0,0 +1,129 @@+// @vitest-environment node+import { type LobeChatDatabase } from '@lobechat/database';+import { agents, projects, topics } from '@lobechat/database/schemas';+import { getTestDB } from '@lobechat/database/test-utils';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { artboardRouter } from '../artboard';+import { createTestUser } from './integration/setup';++let testDB: LobeChatDatabase;+vi.mock('@/database/core/db-adaptor', () => ({+ getServerDB: vi.fn(() => testDB),+}));+// Board files live in object storage; these tests write none, so the folder is always empty.+vi.mock('@/server/services/file', () => ({+ FileService: vi.fn(function FileService() {+ return { listFileObjects: async () => [] };+ }),+}));++describe('artboardRouter', () => {+ let userId: string;+ let topicId: string;++ beforeEach(async () => {+ testDB = await getTestDB();+ userId = await createTestUser(testDB);+ const projectId = `prj_${userId}`;+ topicId = `tpc_${userId}`;+ await testDB.insert(projects).values({ id: projectId, name: 'Onboarding', userId });+ await testDB.insert(topics).values({ id: topicId, projectId, title: '讨论', userId });+ });++ const caller = () => artboardRouter.createCaller({ jwtPayload: { userId }, userId } as any);++ const createBoard = () =>+ caller().create({+ ops: [{ group: { kind: 'journey', title: '旅程' }, ref: 'j', type: 'addGroup' }],+ title: '首次进入',+ topicId,+ });++ it('creates a board and reads it back by revision', async () => {+ const { artboard } = await createBoard();+ expect(await caller().getRevision({ id: artboard.id })).toMatchObject({ revision: 1 });+ expect((await caller().list({ topicId })).map((item) => item.id)).toEqual([artboard.id]);+ });++ it('maps a stale revision to CONFLICT', async () => {+ const { artboard } = await createBoard();+ const groupId = artboard.content.groups[0].id;+ await caller().update({+ id: artboard.id,+ ops: [{ id: groupId, patch: { title: '主流程' }, type: 'updateGroup' }],+ revision: 1,+ });++ await expect(+ caller().update({+ id: artboard.id,+ ops: [{ id: groupId, patch: { title: '旅程' }, type: 'updateGroup' }],+ revision: 1,+ }),+ ).rejects.toMatchObject({ code: 'CONFLICT' });+ });++ it('threads a comment through the router without touching the revision', async () => {+ const { artboard } = await createBoard();+ const thread = await caller().addComment({+ anchor: { type: 'canvas', x: 12, y: 40 },+ clientId: 'c1',+ content: '要跳过吗?',+ id: artboard.id,+ });+ await caller().replyComment({ clientId: 'c2', commentId: thread.id, content: '可以' });+ await caller().resolveComment({ commentId: thread.id });++ const [listed] = await caller().listComments({ id: artboard.id });+ expect(listed).toMatchObject({+ anchor: { type: 'canvas', x: 12, y: 40 },+ replies: [{ content: '可以' }],+ });+ expect(listed.resolvedAt).toBeInstanceOf(Date);+ expect(await caller().getRevision({ id: artboard.id })).toMatchObject({ revision: 1 });+ });++ it("lets the run's agent take the user's threads, answer them and ask its own question", async () => {+ const agentId = `agt_${userId}`;+ await testDB.insert(agents).values({ id: agentId, userId });+ const { artboard } = await createBoard();+ const thread = await caller().addComment({+ clientId: 'c1',+ content: '太挤了',+ id: artboard.id,+ });++ const taken = await caller().takeComments({ agentId, id: artboard.id });+ expect(taken.map((item) => [item.id, item.unread])).toEqual([[thread.id, true]]);+ expect(await caller().countUndeliveredComments({ id: artboard.id })).toBe(0);++ const reply = await caller().replyAsAgent({ agentId, commentId: thread.id, content: '已拉开' });+ expect(reply.authorAgentId).toBe(agentId);++ const question = await caller().askQuestion({+ agentId,+ content: '入口放哪?',+ id: artboard.id,+ });+ const { artboard: after } = await caller().get({ id: artboard.id });+ expect(after.content.questions.map((item) => item.id)).toEqual([question.id]);+ });++ it('maps a round that is not on the board to NOT_FOUND', async () => {+ const { artboard } = await createBoard();+ await expect(+ caller().submitRound({ id: artboard.id, roundId: '00000000-0000-4000-8000-000000000000' }),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });+ });++ it('maps a blocked finalize to PRECONDITION_FAILED with what is missing', async () => {+ const { artboard } = await createBoard();+ const error = await caller()+ .finalize({ id: artboard.id, revision: 1 })+ .catch((caught) => caught);++ expect(error).toMatchObject({ code: 'PRECONDITION_FAILED' });+ expect(error.cause.data.issues).toEqual([{ code: 'empty_journey' }]);+ });+});diff --git a/apps/server/src/routers/lambda/__tests__/artboardPublish.test.ts b/apps/server/src/routers/lambda/__tests__/artboardPublish.test.tsnew file mode 100644index 00000000000..5410de7b2b3--- /dev/null+++ b/apps/server/src/routers/lambda/__tests__/artboardPublish.test.ts@@ -0,0 +1,119 @@+// @vitest-environment node+import { type LobeChatDatabase } from '@lobechat/database';+import { projects, topics } from '@lobechat/database/schemas';+import { getTestDB } from '@lobechat/database/test-utils';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { artboardRouter } from '../artboard';+import { createTestUser } from './integration/setup';++let testDB: LobeChatDatabase;+vi.mock('@/database/core/db-adaptor', () => ({+ getServerDB: vi.fn(() => testDB),+}));+// Board files live in object storage; these tests write none, so the folder is always empty.+vi.mock('@/server/services/file', () => ({+ FileService: vi.fn(function FileService() {+ return { listFileObjects: async () => [] };+ }),+}));++const site = vi.hoisted(() => ({+ enabled: true,+ publishArtboardSite: vi.fn(),+ unpublishCanvasSite: vi.fn(),+}));++vi.mock('@/business/server/canvasPublish', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ getArtboardViewerUrl: vi.fn(async () => 'https://static.example.com/artboard-viewer.js'),+ isCanvasPublishEnabled: () => site.enabled,+ publishArtboardSite: site.publishArtboardSite,+ unpublishCanvasSite: site.unpublishCanvasSite,+}));++describe('artboardRouter · publish', () => {+ let userId: string;+ let topicId: string;++ beforeEach(async () => {+ site.enabled = true;+ site.publishArtboardSite.mockReset().mockResolvedValue({+ deploymentId: 'dep_1',+ url: 'https://onboarding.lobe.page',+ });+ site.unpublishCanvasSite.mockReset().mockResolvedValue(undefined);+ testDB = await getTestDB();+ userId = await createTestUser(testDB);+ const projectId = `prj_${userId}`;+ topicId = `tpc_${userId}`;+ await testDB.insert(projects).values({ id: projectId, name: 'Onboarding', userId });+ await testDB.insert(topics).values({ id: topicId, projectId, title: '讨论', userId });+ });++ const caller = () => artboardRouter.createCaller({ jwtPayload: { userId }, userId } as any);++ const createBoard = (board: Record<string, unknown> = { type: 'decision' }) =>+ caller().create({+ ops: [{ board: { title: '选一个方向', x: 0, y: 0, ...board }, ref: 'b', type: 'addBoard' }],+ title: '首次进入',+ topicId,+ });++ it('refuses to publish where publishing is unavailable', async () => {+ site.enabled = false;+ const { artboard } = await createBoard();++ await expect(caller().publish({ id: artboard.id })).rejects.toMatchObject({+ code: 'NOT_IMPLEMENTED',+ });+ expect(await caller().getPublish({ id: artboard.id })).toMatchObject({ canPublish: false });+ });++ it('publishes the board and reports the link', async () => {+ const { artboard } = await createBoard();+ await caller().addComment({ clientId: 'c1', content: '内部讨论不要外传', id: artboard.id });++ const result = await caller().publish({ id: artboard.id });++ expect(result).toEqual({ url: 'https://onboarding.lobe.page' });+ const [params] = site.publishArtboardSite.mock.calls[0];+ expect(params).toMatchObject({ artboardId: artboard.id, title: '首次进入', userId });+ expect(params.bundle.html).toContain('选一个方向');+ expect(params.bundle.html).not.toContain('内部讨论不要外传');+ expect(await caller().getPublish({ id: artboard.id })).toEqual({+ canPublish: true,+ hasUpdates: false,+ publishedUrl: 'https://onboarding.lobe.page',+ });+ });++ it('reports updates after the board changes, and republishes to the same deployment', async () => {+ const { artboard } = await createBoard();+ await caller().publish({ id: artboard.id });+ const boardId = artboard.content.boards[0].id;++ await caller().update({+ id: artboard.id,+ ops: [{ id: boardId, patch: { title: '换一个方向' }, type: 'updateBoard' }],+ revision: 1,+ });++ expect(await caller().getPublish({ id: artboard.id })).toMatchObject({ hasUpdates: true });+ await caller().publish({ id: artboard.id });+ expect(site.publishArtboardSite.mock.calls[1][0]).toMatchObject({ deploymentId: 'dep_1' });+ expect(await caller().getPublish({ id: artboard.id })).toMatchObject({ hasUpdates: false });+ });++ it('takes the share offline', async () => {+ const { artboard } = await createBoard();+ await caller().publish({ id: artboard.id });++ await caller().unpublish({ id: artboard.id });++ expect(site.unpublishCanvasSite).toHaveBeenCalledWith(+ expect.objectContaining({ deploymentId: 'dep_1', userId }),+ );+ expect(await caller().getPublish({ id: artboard.id })).toMatchObject({ publishedUrl: null });+ });+});diff --git a/apps/server/src/routers/lambda/__tests__/work.artboard.test.ts b/apps/server/src/routers/lambda/__tests__/work.artboard.test.tsnew file mode 100644index 00000000000..e00cdc4cb3f--- /dev/null+++ b/apps/server/src/routers/lambda/__tests__/work.artboard.test.ts@@ -0,0 +1,98 @@+// @vitest-environment node+import { getTestDB } from '@lobechat/database/test-utils';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { ArtboardModel } from '@/database/models/artboard';+import { WorkModel } from '@/database/models/work';+import { projects, users } from '@/database/schemas';++import { workRouter } from '../work';++const serverDB = await getTestDB();+const unpublishCanvasSite = vi.hoisted(() => vi.fn());++vi.mock('@/business/server/canvasPublish', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ unpublishCanvasSite,+}));++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-artboard-share-user';+const projectId = 'prj_work_artboard_share';+const caller = () => workRouter.createCaller({ serverDB, userId });++const publishedArtboardWork = async (publisherUserId = userId) => {+ const board = await new ArtboardModel(serverDB, userId).create({+ projectId,+ title: 'Onboarding',+ });+ const model = new WorkModel(serverDB, userId);+ const work = await model.registerArtboard({+ artboardId: board.id,+ changeType: 'created',+ title: 'Onboarding',+ toolIdentifier: 'builtin-artboard',+ toolName: 'createArtboard',+ });+ await model.recordArtboardPublish(board.id, {+ deploymentId: 'dep_artboard',+ publishedRevision: 1,+ publisherUserId,+ snapshotHash: 'hash',+ url: 'https://onboarding.lobe.page',+ });+ return { artboardId: board.id, model, workId: work.id };+};++beforeEach(async () => {+ unpublishCanvasSite.mockReset().mockResolvedValue(undefined);+ await serverDB.delete(users);+ await serverDB.insert(users).values({ id: userId });+ await serverDB.insert(projects).values({ id: projectId, name: 'Onboarding', userId });+});++describe('workRouter.deleteWork · published artboard', () => {+ it('takes the share offline before removing the Work card', async () => {+ const { artboardId, model, workId } = await publishedArtboardWork();++ await caller().deleteWork({ id: workId });++ expect(unpublishCanvasSite).toHaveBeenCalledWith(+ expect.objectContaining({ deploymentId: 'dep_artboard', userId }),+ );+ expect(await model.findArtboardWork(artboardId)).toBeNull();+ });++ it('keeps the Work card when the share cannot be taken offline', async () => {+ unpublishCanvasSite.mockRejectedValue(new Error('market down'));+ const { artboardId, model, workId } = await publishedArtboardWork();++ await expect(caller().deleteWork({ id: workId })).rejects.toThrow();++ expect((await model.findArtboardWork(artboardId))?.url).toBe('https://onboarding.lobe.page');+ });++ it('takes the share offline as the person who published it', async () => {+ const { workId } = await publishedArtboardWork('work-artboard-share-publisher');++ await caller().deleteWork({ id: workId });++ expect(unpublishCanvasSite).toHaveBeenCalledWith(+ expect.objectContaining({ userId: 'work-artboard-share-publisher' }),+ );+ });+});diff --git a/apps/server/src/routers/lambda/_helpers/messagesByCursor.ts b/apps/server/src/routers/lambda/_helpers/messagesByCursor.tsindex a8a4fc94282..a941ed43d20 100644--- a/apps/server/src/routers/lambda/_helpers/messagesByCursor.ts+++ b/apps/server/src/routers/lambda/_helpers/messagesByCursor.ts@@ -36,6 +36,7 @@ export const messagesByCursorInputSchema = z.object({cursor: z.object({ createdAt: z.string().datetime(), id: z.string().min(1) }).nullish(),direction: z.enum(['backward', 'forward']).optional(),groupId: z.string().nullish(),+ includeArtboardWorks: z.boolean().optional(),// Same opt-in as `getMessages`: only clients that ship the `file` work// descriptor ask for `file` work summaries.includeFileWorks: z.boolean().optional(),diff --git a/apps/server/src/routers/lambda/agentSteerQueue.ts b/apps/server/src/routers/lambda/agentSteerQueue.tsindex b52ba6c6f5b..11b3ea7876e 100644--- a/apps/server/src/routers/lambda/agentSteerQueue.ts+++ b/apps/server/src/routers/lambda/agentSteerQueue.ts@@ -24,7 +24,11 @@ import {import { ExecAgentFieldsSchema, foldLegacyUserMessageFields } from './aiAgent/execSchemas';import { assertCanUseAgentRunConversation } from './aiAgent/guards';-import { acceptsFileWorksOf, acceptsMemberRuntimeEndOf } from './aiAgent/utils';+import {+ acceptsArtboardWorksOf,+ acceptsFileWorksOf,+ acceptsMemberRuntimeEndOf,+} from './aiAgent/utils';const log = debug('lobe-lambda-router:agent-steer-queue');@@ -193,6 +197,7 @@ export const agentSteerQueueRouter = router({request: {// A client from before `userMessage` sends the top-level selection fields....foldLegacyUserMessageFields(request),+ acceptsArtboardWorks: acceptsArtboardWorksOf(streamFeatures),acceptsFileWorks: acceptsFileWorksOf(streamFeatures),acceptsMemberRuntimeEnd: acceptsMemberRuntimeEndOf(streamFeatures),// A follow-up continues the conversation it was typed into; it neverdiff --git a/apps/server/src/routers/lambda/aiAgent/exec.ts b/apps/server/src/routers/lambda/aiAgent/exec.tsindex 7d1d3121ea3..2258405ebe7 100644--- a/apps/server/src/routers/lambda/aiAgent/exec.ts+++ b/apps/server/src/routers/lambda/aiAgent/exec.ts@@ -51,7 +51,7 @@ import { assertCanUseAgentRunConversation } from './guards';import type { AgentInterventionDispatchContext } from './interventionDispatch';import { dispatchClaimedAgentIntervention } from './interventionDispatch';import { aiAgentWriteProcedure } from './procedures';-import { acceptsFileWorksOf, acceptsMemberRuntimeEndOf } from './utils';+import { acceptsArtboardWorksOf, acceptsFileWorksOf, acceptsMemberRuntimeEndOf } from './utils';const log = debug('lobe-server:ai-agent-router');@@ -94,7 +94,11 @@ export const bridgeLegacyResumeToSourceIntervention = async (},ctx: AgentInterventionDispatchContext,/** Forwarded to {@link dispatchClaimedAgentIntervention}; see its `options`. */- options: { acceptsFileWorks?: boolean; acceptsMemberRuntimeEnd?: boolean } = {},+ options: {+ acceptsArtboardWorks?: boolean;+ acceptsFileWorks?: boolean;+ acceptsMemberRuntimeEnd?: boolean;+ } = {},): Promise<ExecAgentResult | undefined> => {const {messageModel,@@ -295,6 +299,7 @@ export const execRouter = router({},ctx,{+ acceptsArtboardWorks: acceptsArtboardWorksOf(input.streamFeatures),acceptsFileWorks: acceptsFileWorksOf(input.streamFeatures),acceptsMemberRuntimeEnd: acceptsMemberRuntimeEndOf(input.streamFeatures),},@@ -314,6 +319,7 @@ export const execRouter = router({},{...request,+ acceptsArtboardWorks: acceptsArtboardWorksOf(input.streamFeatures),acceptsFileWorks: acceptsFileWorksOf(input.streamFeatures),acceptsMemberRuntimeEnd: acceptsMemberRuntimeEndOf(input.streamFeatures),// A non-superseding start waits on the surface like a server-started@@ -556,6 +562,7 @@ export const execRouter = router({workspaceId: ctx.workspaceId,});const result = await ctx.aiAgentService.execAgent({+ acceptsArtboardWorks: acceptsArtboardWorksOf(task.streamFeatures),acceptsFileWorks: acceptsFileWorksOf(task.streamFeatures),acceptsMemberRuntimeEnd: acceptsMemberRuntimeEndOf(task.streamFeatures),clientProtocol: task.clientProtocol,diff --git a/apps/server/src/routers/lambda/aiAgent/intervention.ts b/apps/server/src/routers/lambda/aiAgent/intervention.tsindex 6d115f7014c..2a780156e46 100644--- a/apps/server/src/routers/lambda/aiAgent/intervention.ts+++ b/apps/server/src/routers/lambda/aiAgent/intervention.ts@@ -25,7 +25,7 @@ import {import { assertCanUseAgentRunConversation, assertCanUseOperationAgent } from './guards';import { dispatchClaimedAgentIntervention } from './interventionDispatch';import { aiAgentBaseProcedure, aiAgentWriteProcedure } from './procedures';-import { acceptsFileWorksOf, acceptsMemberRuntimeEndOf } from './utils';+import { acceptsArtboardWorksOf, acceptsFileWorksOf, acceptsMemberRuntimeEndOf } from './utils';const log = debug('lobe-server:ai-agent-router');@@ -226,6 +226,7 @@ export const interventionRouter = router({}const dispatch = await dispatchClaimedAgentIntervention(resolution, ctx, {+ acceptsArtboardWorks: acceptsArtboardWorksOf(input.streamFeatures),acceptsFileWorks: acceptsFileWorksOf(input.streamFeatures),acceptsMemberRuntimeEnd: acceptsMemberRuntimeEndOf(input.streamFeatures),});diff --git a/apps/server/src/routers/lambda/aiAgent/interventionDispatch.ts b/apps/server/src/routers/lambda/aiAgent/interventionDispatch.tsindex bb86b9dbacd..ce7a0c5ef78 100644--- a/apps/server/src/routers/lambda/aiAgent/interventionDispatch.ts+++ b/apps/server/src/routers/lambda/aiAgent/interventionDispatch.ts@@ -471,7 +471,11 @@ export const dispatchClaimedAgentIntervention = async (* inherits the parked operation's declaration. `acceptsFileWorks` follows* the same rule.*/- options: { acceptsFileWorks?: boolean; acceptsMemberRuntimeEnd?: boolean } = {},+ options: {+ acceptsArtboardWorks?: boolean;+ acceptsFileWorks?: boolean;+ acceptsMemberRuntimeEnd?: boolean;+ } = {},): Promise<{ execution?: ExecAgentResult; status: AgentInterventionReviewStatus }> => {const { runtimeAction } = resolution;let execution: ExecAgentResult | undefined;@@ -555,6 +559,7 @@ export const dispatchClaimedAgentIntervention = async (const skipped = customAction.type === 'skipped';execution = await ctx.aiAgentService.execAgent({agentId: runtimeAction.agentId,+ acceptsArtboardWorks: options.acceptsArtboardWorks,acceptsFileWorks: options.acceptsFileWorks,acceptsMemberRuntimeEnd: options.acceptsMemberRuntimeEnd,approvalResolutionRequestId: resolution.resolutionRequestId,@@ -592,6 +597,7 @@ export const dispatchClaimedAgentIntervention = async (const [singleDecision] = runtimeAction.decisions;execution = await ctx.aiAgentService.execAgent({agentId: runtimeAction.agentId,+ acceptsArtboardWorks: options.acceptsArtboardWorks,acceptsFileWorks: options.acceptsFileWorks,acceptsMemberRuntimeEnd: options.acceptsMemberRuntimeEnd,approvalResolutionRequestId: resolution.resolutionRequestId,@@ -615,6 +621,7 @@ export const dispatchClaimedAgentIntervention = async (case 'resume_tool_result': {execution = await ctx.aiAgentService.execAgent({agentId: runtimeAction.agentId,+ acceptsArtboardWorks: options.acceptsArtboardWorks,acceptsFileWorks: options.acceptsFileWorks,acceptsMemberRuntimeEnd: options.acceptsMemberRuntimeEnd,approvalResolutionRequestId: resolution.resolutionRequestId,diff --git a/apps/server/src/routers/lambda/aiAgent/procedures.ts b/apps/server/src/routers/lambda/aiAgent/procedures.tsindex 5d3e5b9e440..506f66af93d 100644--- a/apps/server/src/routers/lambda/aiAgent/procedures.ts+++ b/apps/server/src/routers/lambda/aiAgent/procedures.ts@@ -41,7 +41,9 @@ export const aiAgentProcedure = aiAgentBaseProcedure.use(async (opts) => {ctx.apiKeyScopes !== undefined && !isFullAccessApiKey(ctx.apiKeyScopes),workspaceId: wsId,}),- aiChatService: new AiChatService(ctx.serverDB, ctx.userId, wsId),+ aiChatService: new AiChatService(ctx.serverDB, ctx.userId, wsId, {+ workTypeOptIn: ctx.workTypeOptIn,+ }),heterogeneousAgentService: new HeterogeneousAgentService(ctx.serverDB, ctx.userId, {workspaceId: wsId,}),diff --git a/apps/server/src/routers/lambda/aiAgent/utils.ts b/apps/server/src/routers/lambda/aiAgent/utils.tsindex 5261962c1ae..b0a4bc277f5 100644--- a/apps/server/src/routers/lambda/aiAgent/utils.ts+++ b/apps/server/src/routers/lambda/aiAgent/utils.ts@@ -25,3 +25,6 @@ export const acceptsMemberRuntimeEndOf = (streamFeatures: string[] | undefined):*/export const acceptsFileWorksOf = (streamFeatures: string[] | undefined): boolean =>streamFeatures?.includes('file_works') ?? false;++export const acceptsArtboardWorksOf = (streamFeatures: string[] | undefined): boolean =>+ streamFeatures?.includes('artboard_works') ?? false;diff --git a/apps/server/src/routers/lambda/aiChat.ts b/apps/server/src/routers/lambda/aiChat.tsindex c77f3e6367d..b31a1007338 100644--- a/apps/server/src/routers/lambda/aiChat.ts+++ b/apps/server/src/routers/lambda/aiChat.ts@@ -142,7 +142,9 @@ const aiChatProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) =return opts.next({ctx: {agentModel: new AgentModel(ctx.serverDB, ctx.userId, wsId),- aiChatService: new AiChatService(ctx.serverDB, ctx.userId, wsId),+ aiChatService: new AiChatService(ctx.serverDB, ctx.userId, wsId, {+ workTypeOptIn: ctx.workTypeOptIn,+ }),aiGenerationService: new AiGenerationService(ctx.serverDB, ctx.userId, wsId),fileService: new FileService(ctx.serverDB, ctx.userId, wsId),messageModel: new MessageModel(ctx.serverDB, ctx.userId, wsId),diff --git a/apps/server/src/routers/lambda/artboard.ts b/apps/server/src/routers/lambda/artboard.tsnew file mode 100644index 00000000000..c54d76b775b--- /dev/null+++ b/apps/server/src/routers/lambda/artboard.ts@@ -0,0 +1,303 @@+import {+ artboardFileChangesSchema,+ artboardFileUploadsSchema,+ artboardOpSchema,+} from '@lobechat/types';+import { TRPCError } from '@trpc/server';+import { z } from 'zod';++import { withScopedPermission } from '@/business/server/trpc-middlewares/rbacPermission';+import {+ requireWorkspaceRoleWhenScoped,+ wsCompatProcedure,+} from '@/business/server/trpc-middlewares/workspaceAuth';+import { router } from '@/libs/trpc/lambda';+import { serverDatabase } from '@/libs/trpc/lambda/middleware';+import {+ ArtboardService,+ ArtboardServiceError,+ type ArtboardServiceErrorCode,+} from '@/server/services/artboard';+import { ArtboardPublishService } from '@/server/services/artboard/publish';++const TRPC_CODES: Record<ArtboardServiceErrorCode, TRPCError['code']> = {+ conflict: 'CONFLICT',+ exists: 'CONFLICT',+ finalize_blocked: 'PRECONDITION_FAILED',+ invalid: 'BAD_REQUEST',+ locked: 'PRECONDITION_FAILED',+ no_project: 'BAD_REQUEST',+ not_found: 'NOT_FOUND',+ source_denied: 'FORBIDDEN',+};++const run = async <T>(label: string, action: () => Promise<T>): Promise<T> => {+ try {+ return await action();+ } catch (error) {+ if (error instanceof TRPCError) throw error;+ if (error instanceof ArtboardServiceError)+ throw new TRPCError({ cause: error, code: TRPC_CODES[error.code], message: error.message });+ console.error(`[artboard:${label}]`, error);+ throw new TRPCError({+ cause: error,+ code: 'INTERNAL_SERVER_ERROR',+ message: 'Artboard failed',+ });+ }+};++const artboardProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {+ const { ctx } = opts;+ return opts.next({+ ctx: {+ artboardPublishService: new ArtboardPublishService(+ ctx.serverDB,+ ctx.userId,+ ctx.workspaceId ?? undefined,+ ),+ artboardService: new ArtboardService(ctx.serverDB, ctx.userId, ctx.workspaceId ?? undefined),+ asAgent: (agentId: string) =>+ new ArtboardService(ctx.serverDB, ctx.userId, ctx.workspaceId ?? undefined, {+ context: { agentId },+ }),+ },+ });+});++const artboardProcedureWrite = artboardProcedure.use(withScopedPermission('agent:update'));++const artboardPublishProcedure = artboardProcedureWrite.use(+ requireWorkspaceRoleWhenScoped('member'),+);++const idInput = z.object({ id: z.string().min(1) });+const revisionInput = idInput.extend({ revision: z.number().int().positive() });++const commentInput = z.object({ commentId: z.string().min(1) });+const agentInput = z.object({ agentId: z.string().min(1) });+const commentContent = z.string().trim().min(1).max(10_000);+const commentAnchor = z.union([+ z.object({ type: z.literal('canvas'), x: z.number().finite(), y: z.number().finite() }),+ z.object({+ nodePath: z.string().min(1),+ offsetX: z.number().min(0).max(1),+ offsetY: z.number().min(0).max(1),+ type: z.literal('node'),+ }),+]);++export const artboardRouter = router({+ addComment: artboardProcedureWrite+ .input(+ idInput.extend({+ anchor: commentAnchor.nullish(),+ boardId: z.string().nullish(),+ clientId: z.string().min(1),+ content: commentContent,+ groupId: z.string().nullish(),+ pageId: z.string().nullish(),+ }),+ )+ .mutation(({ ctx, input }) => {+ const { id, ...comment } = input;+ return run('addComment', () => ctx.artboardService.addComment(id, comment));+ }),++ chooseBoard: artboardProcedureWrite+ .input(idInput.extend({ boardId: z.string().min(1), roundId: z.string().min(1) }))+ .mutation(({ ctx, input }) =>+ run('chooseBoard', () =>+ ctx.artboardService.chooseBoard(input.id, input.roundId, input.boardId),+ ),+ ),++ deliverComments: artboardProcedureWrite+ .input(idInput)+ .mutation(({ ctx, input }) =>+ run('deliverComments', () => ctx.artboardService.takeUndeliveredComments(input.id)),+ ),++ countUndeliveredComments: artboardProcedure+ .input(idInput)+ .query(({ ctx, input }) =>+ run('countUndeliveredComments', () => ctx.artboardService.countUndeliveredComments(input.id)),+ ),++ create: artboardProcedureWrite+ .input(+ z.object({+ description: z.string().nullish(),+ files: artboardFileChangesSchema.optional(),+ ops: z.array(artboardOpSchema).max(200).optional(),+ taskId: z.string().nullish(),+ title: z.string().trim().min(1),+ topicId: z.string().nullish(),+ }),+ )+ .mutation(({ ctx, input }) => {+ const { topicId, ...rest } = input;+ return run('create', () => ctx.artboardService.create(rest, { topicId }));+ }),++ finalize: artboardProcedureWrite+ .input(revisionInput)+ .mutation(({ ctx, input }) =>+ run('finalize', () => ctx.artboardService.finalize(input.id, input.revision)),+ ),++ get: artboardProcedure+ .input(idInput)+ .query(({ ctx, input }) => run('get', () => ctx.artboardService.get(input.id))),++ getByTask: artboardProcedure+ .input(z.object({ taskId: z.string().min(1) }))+ .query(({ ctx, input }) => run('getByTask', () => ctx.artboardService.getByTask(input.taskId))),++ getPublish: artboardProcedure+ .input(idInput)+ .query(({ ctx, input }) =>+ run('getPublish', () => ctx.artboardPublishService.getPublish(input.id)),+ ),++ getRevision: artboardProcedure+ .input(idInput)+ .query(({ ctx, input }) => run('getRevision', () => ctx.artboardService.getRevision(input.id))),++ list: artboardProcedure+ .input(z.object({ taskId: z.string().nullish(), topicId: z.string().nullish() }))+ .query(({ ctx, input }) => run('list', () => ctx.artboardService.list(input))),++ listFiles: artboardProcedure+ .input(idInput)+ .query(({ ctx, input }) => run('listFiles', () => ctx.artboardService.listFiles(input.id))),++ listComments: artboardProcedure+ .input(idInput)+ .query(({ ctx, input }) =>+ run('listComments', () => ctx.artboardService.listComments(input.id)),+ ),++ listByProject: artboardProcedure+ .input(z.object({ projectId: z.string().min(1) }))+ .query(({ ctx, input }) =>+ run('listByProject', () => ctx.artboardService.listByProject(input.projectId)),+ ),++ prepareFileUploads: artboardProcedureWrite+ .input(idInput.extend({ files: artboardFileUploadsSchema }))+ .mutation(({ ctx, input }) =>+ run('prepareFileUploads', () =>+ ctx.artboardService.prepareFileUploads(input.id, input.files),+ ),+ ),++ publish: artboardPublishProcedure+ .input(idInput)+ .mutation(({ ctx, input }) =>+ run('publish', () => ctx.artboardPublishService.publish(input.id)),+ ),++ read: artboardProcedure+ .input(idInput)+ .query(({ ctx, input }) => run('read', () => ctx.artboardService.read(input.id))),++ readFile: artboardProcedure+ .input(idInput.extend({ path: z.string().min(1) }))+ .query(({ ctx, input }) =>+ run('readFile', async () => {+ const { bytes, ...file } = await ctx.artboardService.readFile(input.id, input.path);+ return file.content === undefined+ ? { ...file, base64: Buffer.from(bytes).toString('base64') }+ : file;+ }),+ ),++ reopenComment: artboardProcedureWrite+ .input(commentInput)+ .mutation(({ ctx, input }) =>+ run('reopenComment', () => ctx.artboardService.reopenComment(input.commentId)),+ ),++ replyComment: artboardProcedureWrite+ .input(commentInput.extend({ clientId: z.string().min(1), content: commentContent }))+ .mutation(({ ctx, input }) =>+ run('replyComment', () =>+ ctx.artboardService.replyComment(input.commentId, {+ clientId: input.clientId,+ content: input.content,+ }),+ ),+ ),++ resolveComment: artboardProcedureWrite+ .input(commentInput)+ .mutation(({ ctx, input }) =>+ run('resolveComment', () => ctx.artboardService.resolveComment(input.commentId)),+ ),++ askQuestion: artboardProcedureWrite+ .input(+ idInput.merge(agentInput).extend({+ boardId: z.string().nullish(),+ content: commentContent,+ groupId: z.string().nullish(),+ pageId: z.string().nullish(),+ }),+ )+ .mutation(({ ctx, input }) => {+ const { agentId, id, ...question } = input;+ return run('askQuestion', () => ctx.asAgent(agentId).askQuestion(id, question));+ }),++ replyAsAgent: artboardProcedureWrite+ .input(commentInput.merge(agentInput).extend({ content: commentContent }))+ .mutation(({ ctx, input }) =>+ run('replyAsAgent', () =>+ ctx.asAgent(input.agentId).replyComment(input.commentId, { content: input.content }),+ ),+ ),++ takeComments: artboardProcedureWrite+ .input(idInput.merge(agentInput))+ .mutation(({ ctx, input }) =>+ run('takeComments', () => ctx.asAgent(input.agentId).takeUndeliveredComments(input.id)),+ ),++ submitRound: artboardProcedureWrite+ .input(idInput.extend({ roundId: z.string().min(1) }))+ .mutation(({ ctx, input }) =>+ run('submitRound', () => ctx.artboardService.submitRound(input.id, input.roundId)),+ ),++ submitRounds: artboardProcedureWrite+ .input(idInput.extend({ roundIds: z.array(z.string().min(1)).max(200).optional() }))+ .mutation(({ ctx, input }) =>+ run('submitRounds', () => ctx.artboardService.submitOpenRounds(input.id, input.roundIds)),+ ),++ unpublish: artboardPublishProcedure+ .input(idInput)+ .mutation(({ ctx, input }) =>+ run('unpublish', () => ctx.artboardPublishService.unpublish(input.id)),+ ),++ update: artboardProcedureWrite+ .input(+ revisionInput.extend({+ files: artboardFileChangesSchema.optional(),+ ops: z.array(artboardOpSchema).max(200).default([]),+ }),+ )+ .mutation(({ ctx, input }) =>+ run('update', () =>+ ctx.artboardService.update(input.id, input.revision, input.ops, input.files),+ ),+ ),++ writeFiles: artboardProcedureWrite+ .input(idInput.extend({ files: artboardFileChangesSchema }))+ .mutation(({ ctx, input }) =>+ run('writeFiles', () => ctx.artboardService.writeFiles(input.id, input.files)),+ ),+});diff --git a/apps/server/src/routers/lambda/index.ts b/apps/server/src/routers/lambda/index.tsindex f4ee4d8020f..0f86569fd2d 100644--- a/apps/server/src/routers/lambda/index.ts+++ b/apps/server/src/routers/lambda/index.ts@@ -47,6 +47,7 @@ import { aiChatRouter } from './aiChat';import { aiModelRouter } from './aiModel';import { aiProviderRouter } from './aiProvider';import { apiKeyRouter } from './apiKey';+import { artboardRouter } from './artboard';import { asrRouter } from './asr';import { authRouter } from './auth';import { botMessageRouter } from './botMessage';@@ -154,6 +155,7 @@ export const lambdaRouter = router({agentRunBoard: agentRunBoardRouter,agentSignal: agentSignalRouter,agentSteerQueue: agentSteerQueueRouter,+ artboard: artboardRouter,canvas: canvasRouter,changelog: changelogRouter,channel: channelRouter,diff --git a/apps/server/src/routers/lambda/message.ts b/apps/server/src/routers/lambda/message.tsindex 0d7a2574c6a..c4f79e63bb2 100644--- a/apps/server/src/routers/lambda/message.ts+++ b/apps/server/src/routers/lambda/message.ts@@ -64,7 +64,9 @@ const messageProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts)compressionRepo: new CompressionRepository(ctx.serverDB, ctx.userId, wsId),fileService: new FileService(ctx.serverDB, ctx.userId, wsId),messageModel: new MessageModel(ctx.serverDB, ctx.userId, wsId),- messageService: new MessageService(ctx.serverDB, ctx.userId, wsId),+ messageService: new MessageService(ctx.serverDB, ctx.userId, wsId, {+ workTypeOptIn: ctx.workTypeOptIn,+ }),topicDoctorRepo: new TopicDoctorRepo(ctx.serverDB, ctx.userId, wsId),},});@@ -479,6 +481,7 @@ export const messageRouter = router({before: z.object({ createdAt: z.date(), id: z.string() }).optional(),current: z.number().optional(),groupId: z.string().nullish(),+ includeArtboardWorks: z.boolean().optional(),// Opt-in for `file` work summaries in the payload. Absent → the legacy// set, so already-deployed clients (no `file` descriptor) never receive// a `file` summary that would crash their works UI. New clients set it.diff --git a/apps/server/src/routers/lambda/work.ts b/apps/server/src/routers/lambda/work.tsindex 01d8c442bea..ce5482e4850 100644--- a/apps/server/src/routers/lambda/work.ts+++ b/apps/server/src/routers/lambda/work.ts@@ -18,6 +18,7 @@ import { WorkModel } from '@/database/models/work';import type { LobeChatDatabase } from '@/database/type';import { router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';+import { unpublishArtboardWork } from '@/server/services/artboard/publish/offline';import { createCanvasStorageService, isOwnCanvasManifestKey } from '@/server/services/canvas';import { deleteCanvas } from '@/server/services/canvas/delete';import {@@ -163,6 +164,7 @@ export const workRouter = router({listByConversation: workProcedure.input(z.object({+ includeArtboardWorks: z.boolean().optional(),// Opt-in for the `file` work type. Absent → the legacy (pre-`file`) set,// so already-deployed clients whose descriptor table lacks `file` never// receive it (see resolveAllowedWorkTypes in the work registry).@@ -178,11 +180,15 @@ export const workRouter = router({.input(z.object({cursor: z.string().nullable().optional(),+ includeArtboardWorks: z.boolean().optional(),includeFileWorks: z.boolean().optional(),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', 'canvas']).nullable().optional(),+ type: z+ .enum(['task', 'document', 'external', 'file', 'canvas', 'artboard'])+ .nullable()+ .optional(),visibility: z.enum(['private', 'public']).optional(),}),)@@ -191,6 +197,7 @@ export const workRouter = router({listByRootOperation: workProcedure.input(z.object({+ includeArtboardWorks: z.boolean().optional(),includeFileWorks: z.boolean().optional(),limit: z.number().min(1).max(50).default(20),rootOperationId: z.string().nullable().optional(),@@ -198,6 +205,7 @@ export const workRouter = router({).query(async ({ ctx, input }) =>ctx.workModel.listByRootOperation({+ includeArtboardWorks: input.includeArtboardWorks,includeFileWorks: input.includeFileWorks,limit: input.limit,rootOperationId: input.rootOperationId,@@ -207,6 +215,7 @@ export const workRouter = router({listByRootOperations: workProcedure.input(z.object({+ includeArtboardWorks: z.boolean().optional(),includeFileWorks: z.boolean().optional(),limit: z.number().min(1).max(50).default(20),rootOperationIds: z.array(z.string()).max(100).nullable().optional(),@@ -214,6 +223,7 @@ export const workRouter = router({).query(async ({ ctx, input }) =>ctx.workModel.listByRootOperations({+ includeArtboardWorks: input.includeArtboardWorks,includeFileWorks: input.includeFileWorks,limit: input.limit,rootOperationIds: input.rootOperationIds,@@ -254,6 +264,13 @@ export const workRouter = router({return;}+ const artboardWork = await ctx.workModel.findArtboardWorkByWorkId(input.id);+ if (artboardWork?.userId === ctx.userId)+ await unpublishArtboardWork(+ { db: ctx.serverDB, userId: ctx.userId, workspaceId: ctx.workspaceId ?? undefined },+ artboardWork,+ );+await ctx.workModel.deleteWork(input);}),diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/createOperation.test.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/createOperation.test.tsindex 551528d8a81..bc56aac7265 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/createOperation.test.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/createOperation.test.ts@@ -214,6 +214,33 @@ describe('AgentRuntimeService', () => {expect(savedState).not.toHaveProperty('usage');});+ describe('artboard Works declaration', () => {+ it('persists the independent artboard capability on operation host state', async () => {+ await service.createOperation({+ ...mockParams,+ acceptsArtboardWorks: true,+ autoStart: false,+ });+ const state = mockCoordinator.saveAgentState.mock.calls[0][1];+ expect(state.host.acceptsArtboardWorks).toBe(true);+ expect(state.host.acceptsFileWorks).toBeUndefined();+ });++ it('inherits the artboard capability for a mirrored group member', async () => {+ await mockCoordinator.saveAgentState('parent-op', { host: { acceptsArtboardWorks: true } });+ mockCoordinator.saveAgentState.mockClear();+ await service.createOperation({+ ...mockParams,+ appContext: { ...mockParams.appContext, orchestrationRole: 'member' },+ autoStart: false,+ parentOperationId: 'parent-op',+ });+ expect(mockCoordinator.saveAgentState.mock.calls[0][1].host.acceptsArtboardWorks).toBe(+ true,+ );+ });+ });+describe('file Works declaration (host.acceptsFileWorks)', () => {it('stores the declaration the client made', async () => {await service.createOperation({ ...mockParams, acceptsFileWorks: true, autoStart: false });diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/interrupt.test.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/interrupt.test.tsindex 2b93e20615e..3eb4d9880dd 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/interrupt.test.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/interrupt.test.ts@@ -316,6 +316,35 @@ describe('AgentRuntimeService', () => {svc.messageServiceInstance = { queryMessages };};+ it.each([+ [{}, ['document']],+ [{ acceptsFileWorks: true }, ['document', 'file']],+ [{ acceptsArtboardWorks: true }, ['document', 'artboard']],+ [{ acceptsArtboardWorks: true, acceptsFileWorks: true }, ['document', 'file', 'artboard']],+ ])('gates terminal snapshot Work cards independently for host %j', async (host, types) => {+ stubMessageService(+ service,+ vi.fn(async (params) => [+ {+ id: 'assistant-terminal',+ role: 'assistant',+ works: [+ { id: 'doc', type: 'document' },+ ...(params.includeFileWorks ? [{ id: 'file', type: 'file' }] : []),+ ...(params.includeArtboardWorks ? [{ id: 'board', type: 'artboard' }] : []),+ ],+ },+ ]),+ );++ const snapshot = await service.queryUiMessages({+ host,+ origin: { agentId: 'agt_1', topicId: 'tpc_1' },+ } as any);++ expect(snapshot?.[0].works?.map((work) => work.type)).toEqual(types);+ });+it('returns messageService.queryMessages result when agentId + topicId are present', async () => {const stubMessages = [{ id: 'msg_x', role: 'user' }];const queryMessages = vi.fn().mockResolvedValue(stubMessages);diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/createOperation.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/createOperation.tsindex 0adf72af480..02eeec015c0 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/createOperation.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/createOperation.ts@@ -26,6 +26,7 @@ const log = debug('lobe-server:agent-runtime-service');/** What this module reads off the service. */export type CreateOperationDeps = Pick<AgentRuntimeServiceContext,+ | 'acceptsArtboardWorks'| 'acceptsFileWorks'| 'agentOperationModel'| 'baseURL'@@ -45,6 +46,7 @@ export async function createOperation(params: OperationCreationParams,): Promise<OperationCreationResult> {const {+ acceptsArtboardWorks,acceptsFileWorks,acceptsMemberRuntimeEnd,operationId,@@ -191,7 +193,17 @@ export async function createOperation(? await deps.acceptsFileWorks(parentOperationId): undefined);- const preInitState = buildPreInitState(params, { fileWorksAccepted, llmExecutor });+ const artboardWorksAccepted =+ acceptsArtboardWorks ??+ (parentOperationId && appContext?.orchestrationRole === 'member'+ ? await deps.acceptsArtboardWorks(parentOperationId)+ : undefined);++ const preInitState = buildPreInitState(params, {+ artboardWorksAccepted,+ fileWorksAccepted,+ llmExecutor,+ });// A deferred init leaves the turn's request on the state: its presence is// what tells the step-0 worker the init is still owed. The placeholder// context is saved too, so the stale-run reaper can redrive step 0.diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/index.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/index.tsindex 862ec04f53d..3becc1decd6 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/index.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/index.ts@@ -66,6 +66,7 @@ import {usesGatewayMessagePatch,} from './messages';import {+ acceptsArtboardWorks,acceptsFileWorks,acceptsMemberRuntimeEnd,controlCompletedToolResult,@@ -293,6 +294,7 @@ export class AgentRuntimeService {get messageService() {return self.messageService;},+ acceptsArtboardWorks: (...args) => self.acceptsArtboardWorks(...args),acceptsFileWorks: (...args) => self.acceptsFileWorks(...args),acceptsMemberRuntimeEnd: (...args) => self.acceptsMemberRuntimeEnd(...args),allPendingToolsFulfilled: (...args) => self.allPendingToolsFulfilled(...args),@@ -379,6 +381,10 @@ export class AgentRuntimeService {return interruptOperation(this.context, ...args);}+ acceptsArtboardWorks(...args: MethodArgs<typeof acceptsArtboardWorks>) {+ return acceptsArtboardWorks(this.context, ...args);+ }+acceptsFileWorks(...args: MethodArgs<typeof acceptsFileWorks>) {return acceptsFileWorks(this.context, ...args);}diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/messages.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/messages.tsindex 396e31bceaf..effcc4ec42d 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/messages.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/messages.ts@@ -72,6 +72,7 @@ export async function queryUiMessages(const isShareVisitorRun = !!workAccessScope;// `file` Works stay out of the push unless the receiving client declared// it renders them: released desktop builds crash on the unknown type.+ const includeArtboardWorks = agentState?.host?.acceptsArtboardWorks === true;const includeFileWorks = isShareVisitorRun || agentState?.host?.acceptsFileWorks === true;try {@@ -79,6 +80,7 @@ export async function queryUiMessages({agentId,groupId,+ ...(includeArtboardWorks && { includeArtboardWorks: true }),...(includeFileWorks && { includeFileWorks: true }),...(options?.skipCompressedMembers && { skipCompressedMembers: true }),skipWorks: options?.skipWorks,diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/operationControl.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/operationControl.tsindex ecd11e95e11..20d727ac4c7 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/operationControl.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/operationControl.ts@@ -215,6 +215,19 @@ export async function acceptsFileWorks(}}+export async function acceptsArtboardWorks(+ deps: OperationControlDeps,+ operationId: string,+): Promise<boolean> {+ try {+ const state = await deps.coordinator.loadAgentState(operationId);+ return state?.host?.acceptsArtboardWorks === true;+ } catch (error) {+ log('[%s] Failed to read the artboard Works declaration: %O', operationId, error);+ return false;+ }+}+/*** Whether the client that started this operation declared it handles* `member_runtime_end`. An unknown or expired operation reads as `false`, sodiff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/operationInitSlots.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/operationInitSlots.tsindex ee9cb588a87..aa1839f2ace 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/operationInitSlots.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/operationInitSlots.ts@@ -41,11 +41,13 @@ export type OperationInitSlots = Pick<export const buildPreInitState = (params: OperationCreationParams,{+ artboardWorksAccepted,fileWorksAccepted,llmExecutor,}: {/** The client's `file` Works declaration, inherited by a group member. */fileWorksAccepted?: boolean;+ artboardWorksAccepted?: boolean;llmExecutor?: NonNullable<AgentState['host']>['llmExecutor'];},): Partial<AgentState> => {@@ -84,6 +86,7 @@ export const buildPreInitState = (// What the host needs to deliver and retry the run. Hooks are stamped// right after creation once the dispatcher has serialized them.host: {+ ...(artboardWorksAccepted === true && { acceptsArtboardWorks: true }),...(fileWorksAccepted === true && { acceptsFileWorks: true }),...(params.clientProtocol === 2 && { clientProtocol: 2 as const }),...(params.includeFinalState === true && { includeFinalState: true }),diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/types.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/types.tsindex 8ffb37ca647..01e65a1d0a1 100644--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/types.ts+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/types.ts@@ -74,6 +74,7 @@ import type {usesGatewayMessagePatch,} from './messages';import type {+ acceptsArtboardWorks,acceptsFileWorks,acceptsMemberRuntimeEnd,controlCompletedToolResult,@@ -293,6 +294,7 @@ type Bound<F> = F extends (svc: any, ...args: infer A) => infer R ? (...args: A)* module picks the members it uses), so the members stay private on the class.*/export interface AgentRuntimeServiceContext {+ acceptsArtboardWorks: Bound<typeof acceptsArtboardWorks>;acceptsFileWorks: Bound<typeof acceptsFileWorks>;acceptsMemberRuntimeEnd: Bound<typeof acceptsMemberRuntimeEnd>;readonly agentFactory: ((config: GeneralAgentConfig) => Agent) | undefined;diff --git a/apps/server/src/services/agentRuntime/types.ts b/apps/server/src/services/agentRuntime/types.tsindex 29ff0130811..a0620eb4abb 100644--- a/apps/server/src/services/agentRuntime/types.ts+++ b/apps/server/src/services/agentRuntime/types.ts@@ -451,6 +451,7 @@ export interface ExecGroupMemberResult {}export interface OperationCreationParams {+ acceptsArtboardWorks?: boolean;/*** The client starting this run renders `file` Works (declared via* `aiAgent.execAgent`'s `streamFeatures`). Stored ondiff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.pluginTriState.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.pluginTriState.test.tsindex 280f466427e..30ded6fdec6 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.pluginTriState.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.pluginTriState.test.ts@@ -38,7 +38,7 @@ vi.mock('@/server/featureFlags', async (importOriginal) => ({...(await importOriginal<Record<string, unknown>>()),getServerFeatureFlagsStateFromRuntimeConfig: vi.fn()- .mockResolvedValue({ enableDashboard: true, enableWebhook: true }),+ .mockResolvedValue({ enableArtboard: true, enableDashboard: true, enableWebhook: true }),}));vi.mock('@/libs/trusted-client', () => ({diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.resumeApproval.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.resumeApproval.test.tsindex b7206df5992..952889af91d 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.resumeApproval.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.resumeApproval.test.ts@@ -18,13 +18,6 @@ const approvedResumeInput = (): NonNullable<toolCallId: 'call_xyz',});-const stoppedApprovalInput = (): Parameters<AiAgentService['stopPendingApproval']>[0] => ({- batchId: 'batch-1',- operationId: 'op-parked-1',- toolMessageIds: ['tool-msg-1', 'tool-msg-2'],- topicId: 'topic-1',-});-const {mockCompleteGroupActionMember,mockLoadGroupMemberBridge,@@ -167,6 +160,7 @@ vi.mock('@/database/models/userMemory/persona', () => ({vi.mock('@/server/services/agentRuntime', () => ({AgentRuntimeService: vi.fn().mockImplementation(function () {return {+ acceptsArtboardWorks: vi.fn().mockResolvedValue(false),acceptsFileWorks: vi.fn().mockResolvedValue(false),acceptsMemberRuntimeEnd: vi.fn().mockResolvedValue(false),getLlmExecutor: vi.fn().mockResolvedValue(undefined),@@ -1083,170 +1077,3 @@ describe('AiAgentService.execAgent - resumeApproval', () => {});});});--describe('AiAgentService.stopPendingApproval', () => {- let service: AiAgentService;-- const pendingToolMessage = {- createdAt: new Date('2026-08-03T00:00:00.000Z'),- id: 'tool-msg-1',- role: 'tool',- topicId: 'topic-1',- };-- beforeEach(() => {- vi.clearAllMocks();- mockFindById.mockImplementation(async (id: string) => ({ ...pendingToolMessage, id }));- mockFindMessagePlugin.mockResolvedValue({- intervention: {- batchId: 'batch-1',- operationId: 'op-parked-1',- status: 'pending',- },- });- mockListMessagePluginsByTopic.mockResolvedValue(- ['tool-msg-1', 'tool-msg-2'].map((id) => ({- id,- intervention: {- batchId: 'batch-1',- operationId: 'op-parked-1',- status: 'pending',- },- })),- );- mockResolveHumanApproval.mockResolvedValue([]);- mockUpdateMessagePlugin.mockResolvedValue(undefined);- mockUpdateToolMessage.mockResolvedValue(undefined);- mockFindOperationById.mockResolvedValue({- id: 'op-parked-1',- status: 'waiting_for_human',- topicId: 'topic-1',- });- mockRecordCompletion.mockResolvedValue(undefined);- mockInterruptOperation.mockResolvedValue(true);- mockLoadGroupMemberBridge.mockResolvedValue(undefined);- mockCompleteGroupActionMember.mockResolvedValue(true);- service = new AiAgentService({} as unknown as LobeChatDatabase, 'user-1');- });-- // Codex P1 on #20093: a member stopped on its approval never reached its own- // completion, so the supervisor stayed parked on the member barrier forever.- it("reports a stopped group member through its bridge so the supervisor isn't stranded", async () => {- const bridge = {- anchorMessageId: 'msg-speak',- expectedMembers: 1,- groupToolMessageId: 'msg-speak',- mode: 'in_group',- onComplete: 'resume',- parentOperationId: 'op-supervisor',- };- mockLoadGroupMemberBridge.mockResolvedValue({ agentId: 'agt-carol', bridge });-- await service.stopPendingApproval(stoppedApprovalInput());-- expect(mockCompleteGroupActionMember).toHaveBeenCalledWith({- ...bridge,- operationId: 'op-parked-1',- reason: 'interrupted',- });- });-- it('does not touch any bridge when the stopped run is not a group member', async () => {- await service.stopPendingApproval(stoppedApprovalInput());-- expect(mockCompleteGroupActionMember).not.toHaveBeenCalled();- });-- it('settles every pending row in place and retires the parked operation', async () => {- const result = await service.stopPendingApproval(stoppedApprovalInput());-- // In place: the approval pause already wrote these rows. Inserting fresh- // aborted rows would duplicate every tool AND leave the originals pending,- // which is what keeps the approval cards on screen after a stop.- expect(mockResolveHumanApproval).toHaveBeenCalledWith(- [- {- content: 'Tool execution was aborted by user.',- id: 'tool-msg-1',- intervention: { status: 'aborted' },- },- {- content: 'Tool execution was aborted by user.',- id: 'tool-msg-2',- intervention: { status: 'aborted' },- },- ],- { publishResult: true },- );-- // The exact parked operation and sealed batch identity are validated; a- // newer operation in the same topic can never be guessed and interrupted.- expect(mockInterruptOperation).toHaveBeenCalledWith('op-parked-1');- expect(mockRecordCompletion).toHaveBeenCalledWith(- 'op-parked-1',- expect.objectContaining({ completionReason: 'interrupted', status: 'interrupted' }),- );- expect(result.settledToolMessageIds).toEqual(['tool-msg-1', 'tool-msg-2']);- });-- it('stamps the generic resolution id on every stopped row', async () => {- const approvalResolutionRequestId = '018fbd8e-7baf-7c6d-8000-000000000098';-- await service.stopPendingApproval({- approvalResolutionRequestId,- batchId: 'batch-1',- operationId: 'op-parked-1',- toolMessageIds: ['tool-msg-1', 'tool-msg-2'],- topicId: 'topic-1',- });-- expect(mockResolveHumanApproval).toHaveBeenCalledWith(- expect.arrayContaining([- expect.objectContaining({- intervention: { resolutionRequestId: approvalResolutionRequestId, status: 'aborted' },- }),- ]),- { publishResult: true },- );- });-- it('nothing runs and the model is not continued', async () => {- mockListMessagePluginsByTopic.mockResolvedValue([- {- id: 'tool-msg-1',- intervention: {- batchId: 'batch-1',- operationId: 'op-parked-1',- status: 'pending',- },- },- ]);- await service.stopPendingApproval({- batchId: 'batch-1',- operationId: 'op-parked-1',- toolMessageIds: ['tool-msg-1'],- topicId: 'topic-1',- });-- // A stop is not a rejection: a rejection resumes the model so it can- // respond, a stop ends the turn outright.- expect(mockCreateOperation).not.toHaveBeenCalled();- });-- it('rejects a target from another topic before writing anything', async () => {- mockFindById.mockImplementation(async (id: string) => ({- ...pendingToolMessage,- id,- topicId: id === 'tool-msg-2' ? 'other-topic' : 'topic-1',- }));-- await expect(service.stopPendingApproval(stoppedApprovalInput())).rejects.toThrow(- /topicId does not match/,- );-- // Validation runs before any write, so a refused stop cannot half-clear the- // batch and strand the rest against a run that is already gone.- expect(mockResolveHumanApproval).not.toHaveBeenCalled();- expect(mockInterruptOperation).not.toHaveBeenCalled();- });-});diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.resumeToolResult.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.resumeToolResult.test.tsindex 631c2d50210..6260f56af57 100644--- a/apps/server/src/services/aiAgent/__tests__/execAgent.resumeToolResult.test.ts+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.resumeToolResult.test.ts@@ -153,6 +153,7 @@ vi.mock('@/database/models/userMemory/persona', () => ({vi.mock('@/server/services/agentRuntime', () => ({AgentRuntimeService: vi.fn().mockImplementation(function () {return {+ acceptsArtboardWorks: vi.fn().mockResolvedValue(false),acceptsFileWorks: vi.fn().mockResolvedValue(false),acceptsMemberRuntimeEnd: vi.fn().mockResolvedValue(false),getLlmExecutor: vi.fn().mockResolvedValue(undefined),diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.stopPendingApproval.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.stopPendingApproval.test.tsnew file mode 100644index 00000000000..5a801694234--- /dev/null+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.stopPendingApproval.test.ts@@ -0,0 +1,398 @@+import type { LobeChatDatabase } from '@lobechat/database';+import type * as ModelBankModule from 'model-bank';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { AiAgentService } from '../index';++const {+ mockCompleteGroupActionMember,+ mockLoadGroupMemberBridge,+ mockCreateOperation,+ mockFindById,+ mockFindMessagePlugin,+ mockMessageCreate,+ mockMessageQuery,+ mockListMessagePluginsByTopic,+ mockResolveHumanApproval,+ mockRestoreHumanApproval,+ mockUpdateMessagePlugin,+ mockUpdateTopicMetadata,+ mockUpdateToolMessage,+ mockFindOperationById,+ mockRecordCompletion,+ mockRepairAgentInterventionContinuation,+ mockInterruptOperation,+ mockEnsureInterventionContinuationStarted,+ mockLoadInterventionContinuationState,+ mockReleaseTaskCallbackReservation,+ mockTryReserveTaskCallback,+} = vi.hoisted(() => ({+ mockCompleteGroupActionMember: vi.fn(),+ mockLoadGroupMemberBridge: vi.fn(),+ mockEnsureInterventionContinuationStarted: vi.fn(),+ mockFindOperationById: vi.fn(),+ mockRecordCompletion: vi.fn(),+ mockRepairAgentInterventionContinuation: vi.fn(),+ mockInterruptOperation: vi.fn(),+ mockLoadInterventionContinuationState: vi.fn(),+ mockReleaseTaskCallbackReservation: vi.fn(),+ mockCreateOperation: vi.fn(),+ mockFindById: vi.fn(),+ mockFindMessagePlugin: vi.fn(),+ mockListMessagePluginsByTopic: vi.fn(),+ mockMessageCreate: vi.fn(),+ mockMessageQuery: vi.fn(),+ mockResolveHumanApproval: vi.fn(),+ mockRestoreHumanApproval: vi.fn(),+ mockUpdateMessagePlugin: vi.fn(),+ mockUpdateTopicMetadata: vi.fn(),+ mockUpdateToolMessage: vi.fn(),+ mockTryReserveTaskCallback: vi.fn(),+}));++vi.mock('@/libs/trusted-client', () => ({+ generateTrustedClientToken: vi.fn().mockReturnValue(undefined),+ getTrustedClientTokenForSession: vi.fn().mockResolvedValue(undefined),+ isTrustedClientEnabled: vi.fn().mockReturnValue(false),+}));++vi.mock('@/database/models/message', () => ({+ HumanApprovalAlreadyResolvedError: class HumanApprovalAlreadyResolvedError extends Error {},+ MessageModel: vi.fn().mockImplementation(function () {+ return {+ create: mockMessageCreate,+ getLatestNonToolMessageId: vi.fn().mockResolvedValue(undefined),+ getLatestSpineMessageId: vi.fn().mockResolvedValue(undefined),+ findById: mockFindById,+ findMessagePlugin: mockFindMessagePlugin,+ listMessagePluginsByTopic: mockListMessagePluginsByTopic,+ query: mockMessageQuery,+ resolveHumanApproval: mockResolveHumanApproval,+ restoreHumanApproval: mockRestoreHumanApproval,+ update: vi.fn().mockResolvedValue({}),+ updateMessagePlugin: mockUpdateMessagePlugin,+ updateToolMessage: mockUpdateToolMessage,+ };+ }),+}));++vi.mock('@/database/models/agent', () => ({+ AgentModel: vi.fn().mockImplementation(function () {+ return { queryAgents: vi.fn().mockResolvedValue([]) };+ }),+}));++vi.mock('@/server/services/agent', () => ({+ AgentService: vi.fn().mockImplementation(function () {+ return {+ getAgentConfig: vi.fn().mockResolvedValue({+ chatConfig: {},+ id: 'agent-1',+ knowledgeBases: [],+ model: 'gpt-4',+ plugins: [],+ provider: 'openai',+ systemRole: 'You are a helpful assistant',+ }),+ };+ }),+}));++vi.mock('@/database/models/plugin', () => ({+ PluginModel: vi.fn().mockImplementation(function () {+ return { query: vi.fn().mockResolvedValue([]) };+ }),+}));++vi.mock('@/database/models/topic', () => ({+ TopicModel: vi.fn().mockImplementation(function () {+ return {+ releaseTaskCallbackReservation: mockReleaseTaskCallbackReservation,+ repairAgentInterventionContinuation: mockRepairAgentInterventionContinuation,+ tryReserveTaskCallback: mockTryReserveTaskCallback,+ create: vi.fn().mockResolvedValue({ id: 'topic-1' }),+ findById: vi.fn().mockResolvedValue(null),+ updateMetadata: mockUpdateTopicMetadata,+ };+ }),+}));++vi.mock('@/database/models/thread', () => ({+ ThreadModel: vi.fn().mockImplementation(function () {+ return {+ create: vi.fn(),+ findById: vi.fn(),+ update: vi.fn(),+ };+ }),+}));++vi.mock('@/database/models/user', () => ({+ UserModel: vi.fn().mockImplementation(function () {+ return {+ getUserSettings: vi.fn().mockResolvedValue(undefined),+ };+ }),+}));++vi.mock('@/database/models/userMemory/persona', () => ({+ UserPersonaModel: vi.fn().mockImplementation(function () {+ return {+ getLatestPersonaDocument: vi.fn().mockResolvedValue(undefined),+ };+ }),+}));++vi.mock('@/server/services/agentRuntime', () => ({+ AgentRuntimeService: vi.fn().mockImplementation(function () {+ return {+ acceptsArtboardWorks: vi.fn().mockResolvedValue(false),+ acceptsFileWorks: vi.fn().mockResolvedValue(false),+ acceptsMemberRuntimeEnd: vi.fn().mockResolvedValue(false),+ getLlmExecutor: vi.fn().mockResolvedValue(undefined),+ getOperationEditingGroupId: vi.fn().mockResolvedValue(undefined),+ completeGroupActionMember: mockCompleteGroupActionMember,+ createOperation: mockCreateOperation,+ ensureInterventionContinuationStarted: mockEnsureInterventionContinuationStarted,+ interruptOperation: mockInterruptOperation,+ loadGroupMemberBridge: mockLoadGroupMemberBridge,+ loadInterventionContinuationState: mockLoadInterventionContinuationState,+ };+ }),+}));++vi.mock('@/database/models/agentOperation', () => ({+ AgentOperationModel: vi.fn().mockImplementation(function () {+ return {+ findById: mockFindOperationById,+ recordCompletion: mockRecordCompletion,+ };+ }),+}));++vi.mock('@/server/services/market', () => ({+ MarketService: vi.fn().mockImplementation(function () {+ return {+ getLobehubSkillManifests: vi.fn().mockResolvedValue([]),+ };+ }),+}));++vi.mock('@/server/services/composio', () => ({+ ComposioService: vi.fn().mockImplementation(function () {+ return {+ getComposioManifests: vi.fn().mockResolvedValue([]),+ };+ }),+}));++vi.mock('@/server/services/file', () => ({+ FileService: vi.fn().mockImplementation(function () {+ return { uploadFromUrl: vi.fn() };+ }),+}));++vi.mock('@/server/modules/Mecha', () => ({+ createServerAgentToolsEngine: vi.fn().mockReturnValue({+ generateToolsDetailed: vi.fn().mockReturnValue({ enabledToolIds: [], tools: [] }),+ getEnabledPluginManifests: vi.fn().mockReturnValue(new Map()),+ }),+}));++vi.mock('@/server/services/deviceGateway', () => ({+ deviceGateway: { isConfigured: false, queryDeviceList: vi.fn().mockResolvedValue([]) },+}));++vi.mock('@/server/modules/ModelRuntime', () => ({+ initModelRuntimeFromDB: vi.fn(),+}));++vi.mock('model-bank', async (importOriginal) => {+ const actual = await importOriginal<typeof ModelBankModule>();+ return {+ ...actual,+ LOBE_DEFAULT_MODEL_LIST: [+ {+ abilities: { functionCall: true, vision: true },+ id: 'gpt-4',+ providerId: 'openai',+ },+ ],+ };+});++describe('AiAgentService.stopPendingApproval', () => {+ let service: AiAgentService;++ const pendingToolMessage = {+ createdAt: new Date('2026-08-03T00:00:00.000Z'),+ id: 'tool-msg-1',+ role: 'tool',+ topicId: 'topic-1',+ };++ beforeEach(() => {+ vi.clearAllMocks();+ mockFindById.mockImplementation(async (id: string) => ({ ...pendingToolMessage, id }));+ mockFindMessagePlugin.mockResolvedValue({+ intervention: {+ batchId: 'batch-1',+ operationId: 'op-parked-1',+ status: 'pending',+ },+ });+ mockListMessagePluginsByTopic.mockResolvedValue(+ ['tool-msg-1', 'tool-msg-2'].map((id) => ({+ id,+ intervention: {+ batchId: 'batch-1',+ operationId: 'op-parked-1',+ status: 'pending',+ },+ })),+ );+ mockResolveHumanApproval.mockResolvedValue([]);+ mockUpdateMessagePlugin.mockResolvedValue(undefined);+ mockUpdateToolMessage.mockResolvedValue(undefined);+ mockFindOperationById.mockResolvedValue({+ id: 'op-parked-1',+ status: 'waiting_for_human',+ topicId: 'topic-1',+ });+ mockRecordCompletion.mockResolvedValue(undefined);+ mockInterruptOperation.mockResolvedValue(true);+ mockLoadGroupMemberBridge.mockResolvedValue(undefined);+ mockCompleteGroupActionMember.mockResolvedValue(true);+ service = new AiAgentService({} as unknown as LobeChatDatabase, 'user-1');+ });++ it("reports a stopped group member through its bridge so the supervisor isn't stranded", async () => {+ const bridge = {+ anchorMessageId: 'msg-speak',+ expectedMembers: 1,+ groupToolMessageId: 'msg-speak',+ mode: 'in_group',+ onComplete: 'resume',+ parentOperationId: 'op-supervisor',+ };+ mockLoadGroupMemberBridge.mockResolvedValue({ agentId: 'agt-carol', bridge });++ await service.stopPendingApproval({+ batchId: 'batch-1',+ operationId: 'op-parked-1',+ toolMessageIds: ['tool-msg-1', 'tool-msg-2'],+ topicId: 'topic-1',+ });++ expect(mockCompleteGroupActionMember).toHaveBeenCalledWith({+ ...bridge,+ operationId: 'op-parked-1',+ reason: 'interrupted',+ });+ });++ it('does not touch any bridge when the stopped run is not a group member', async () => {+ await service.stopPendingApproval({+ batchId: 'batch-1',+ operationId: 'op-parked-1',+ toolMessageIds: ['tool-msg-1', 'tool-msg-2'],+ topicId: 'topic-1',+ });++ expect(mockCompleteGroupActionMember).not.toHaveBeenCalled();+ });++ it('settles every pending row in place and retires the parked operation', async () => {+ const result = await service.stopPendingApproval({+ batchId: 'batch-1',+ operationId: 'op-parked-1',+ toolMessageIds: ['tool-msg-1', 'tool-msg-2'],+ topicId: 'topic-1',+ });++ expect(mockResolveHumanApproval).toHaveBeenCalledWith(+ [+ {+ content: 'Tool execution was aborted by user.',+ id: 'tool-msg-1',+ intervention: { status: 'aborted' },+ },+ {+ content: 'Tool execution was aborted by user.',+ id: 'tool-msg-2',+ intervention: { status: 'aborted' },+ },+ ],+ { publishResult: true },+ );++ expect(mockInterruptOperation).toHaveBeenCalledWith('op-parked-1');+ expect(mockRecordCompletion).toHaveBeenCalledWith(+ 'op-parked-1',+ expect.objectContaining({ completionReason: 'interrupted', status: 'interrupted' }),+ );+ expect(result.settledToolMessageIds).toEqual(['tool-msg-1', 'tool-msg-2']);+ });++ it('stamps the generic resolution id on every stopped row', async () => {+ const approvalResolutionRequestId = '018fbd8e-7baf-7c6d-8000-000000000098';++ await service.stopPendingApproval({+ approvalResolutionRequestId,+ batchId: 'batch-1',+ operationId: 'op-parked-1',+ toolMessageIds: ['tool-msg-1', 'tool-msg-2'],+ topicId: 'topic-1',+ });++ expect(mockResolveHumanApproval).toHaveBeenCalledWith(+ expect.arrayContaining([+ expect.objectContaining({+ intervention: { resolutionRequestId: approvalResolutionRequestId, status: 'aborted' },+ }),+ ]),+ { publishResult: true },+ );+ });++ it('nothing runs and the model is not continued', async () => {+ mockListMessagePluginsByTopic.mockResolvedValue([+ {+ id: 'tool-msg-1',+ intervention: {+ batchId: 'batch-1',+ operationId: 'op-parked-1',+ status: 'pending',+ },+ },+ ]);+ await service.stopPendingApproval({+ batchId: 'batch-1',+ operationId: 'op-parked-1',+ toolMessageIds: ['tool-msg-1'],+ topicId: 'topic-1',+ });++ expect(mockCreateOperation).not.toHaveBeenCalled();+ });++ it('rejects a target from another topic before writing anything', async () => {+ mockFindById.mockImplementation(async (id: string) => ({+ ...pendingToolMessage,+ id,+ topicId: id === 'tool-msg-2' ? 'other-topic' : 'topic-1',+ }));++ await expect(+ service.stopPendingApproval({+ batchId: 'batch-1',+ operationId: 'op-parked-1',+ toolMessageIds: ['tool-msg-1', 'tool-msg-2'],+ topicId: 'topic-1',+ }),+ ).rejects.toThrow(/topicId does not match/);++ expect(mockResolveHumanApproval).not.toHaveBeenCalled();+ expect(mockInterruptOperation).not.toHaveBeenCalled();+ });+});diff --git a/apps/server/src/services/aiAgent/composerRun.ts b/apps/server/src/services/aiAgent/composerRun.tsindex a67a5251acd..08a2d32487d 100644--- a/apps/server/src/services/aiAgent/composerRun.ts+++ b/apps/server/src/services/aiAgent/composerRun.ts@@ -15,6 +15,7 @@ import type { InternalExecAgentParams } from './types';*/export type ComposerRunRequest = Pick<InternalExecAgentParams,+ | 'acceptsArtboardWorks'| 'acceptsFileWorks'| 'acceptsMemberRuntimeEnd'| 'agentId'@@ -108,6 +109,7 @@ export const startComposerRun = async (ctx: ComposerRunContext, input: ComposerRlet reopenOutcome: TopicRunReopenOutcome | undefined;const result = await ctx.aiAgentService.execAgent({+ acceptsArtboardWorks: input.acceptsArtboardWorks,acceptsFileWorks: input.acceptsFileWorks,acceptsMemberRuntimeEnd: input.acceptsMemberRuntimeEnd,agentId: input.agentId,diff --git a/apps/server/src/services/aiAgent/pipeline/__tests__/startOperation.editingGroupId.test.ts b/apps/server/src/services/aiAgent/pipeline/__tests__/startOperation.editingGroupId.test.tsindex 382b1129d0c..14a236fe7f8 100644--- a/apps/server/src/services/aiAgent/pipeline/__tests__/startOperation.editingGroupId.test.ts+++ b/apps/server/src/services/aiAgent/pipeline/__tests__/startOperation.editingGroupId.test.ts@@ -15,6 +15,7 @@ describe('startOperation › group builder editing target inheritance', () => {const setup = (durableEditingGroupId?: string) => {const calls: string[] = [];const agentRuntimeService = {+ acceptsArtboardWorks: vi.fn(async () => true),acceptsFileWorks: vi.fn(async () => true),acceptsMemberRuntimeEnd: vi.fn(async () => true),createOperation: vi.fn(async () => ({ autoStarted: true, messageId: 'msg-assistant' })),diff --git a/apps/server/src/services/aiAgent/pipeline/__tests__/startOperation.memberRuntimeEnd.test.ts b/apps/server/src/services/aiAgent/pipeline/__tests__/startOperation.memberRuntimeEnd.test.tsindex 15b22cc1ff1..03a5ffd9193 100644--- a/apps/server/src/services/aiAgent/pipeline/__tests__/startOperation.memberRuntimeEnd.test.ts+++ b/apps/server/src/services/aiAgent/pipeline/__tests__/startOperation.memberRuntimeEnd.test.ts@@ -11,6 +11,7 @@ const sourceExecutor = { capabilities: ['llm_relay@1'], clientId: 'tab-a', proviconst setup = (sourceAccepts: boolean) => {const calls: string[] = [];const agentRuntimeService = {+ acceptsArtboardWorks: vi.fn(async () => sourceAccepts),acceptsFileWorks: vi.fn(async () => sourceAccepts),acceptsMemberRuntimeEnd: vi.fn(async () => {calls.push('read-source');@@ -64,6 +65,29 @@ const setup = (sourceAccepts: boolean) => {return { agentRuntimeService, calls, ctx, deps, input };};+describe('startOperation artboard Works continuation', () => {+ it('inherits the parked client capability before starting an approval continuation', async () => {+ const { agentRuntimeService, ctx, deps, input } = setup(true);+ await startOperation(deps, ctx, input({ approvalSourceOperationId: 'op-parked' }));+ expect(agentRuntimeService.createOperation).toHaveBeenCalledWith(+ expect.objectContaining({ acceptsArtboardWorks: true }),+ );+ });++ it('does not upgrade a released client from a parked operation capability', async () => {+ const { agentRuntimeService, ctx, deps, input } = setup(true);+ await startOperation(+ deps,+ ctx,+ input({ acceptsArtboardWorks: false, approvalSourceOperationId: 'op-parked' }),+ );+ expect(agentRuntimeService.acceptsArtboardWorks).not.toHaveBeenCalled();+ expect(agentRuntimeService.createOperation).toHaveBeenCalledWith(+ expect.objectContaining({ acceptsArtboardWorks: false }),+ );+ });+});+describe('startOperation › member_runtime_end declaration', () => {it('records the calling client declaration on the new operation', async () => {const { agentRuntimeService, ctx, deps, input } = setup(false);diff --git a/apps/server/src/services/aiAgent/pipeline/artboardContext.test.ts b/apps/server/src/services/aiAgent/pipeline/artboardContext.test.tsnew file mode 100644index 00000000000..d40f1e4cf31--- /dev/null+++ b/apps/server/src/services/aiAgent/pipeline/artboardContext.test.ts@@ -0,0 +1,45 @@+// @vitest-environment node+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { buildArtboardCommentsPrompt } from './artboardContext';++const mocks = vi.hoisted(() => ({ unreadCommentNotices: vi.fn() }));++vi.mock('@/server/services/artboard', () => ({+ ArtboardService: vi.fn().mockImplementation(function () {+ return mocks;+ }),+}));++const deps = { db: {} as never, userId: 'user-1' };++describe('buildArtboardCommentsPrompt', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ });++ it('names each artboard of the conversation with unread threads and how to read them', async () => {+ mocks.unreadCommentNotices.mockResolvedValue([+ { id: 'art_1', threads: 3, title: '导出话题' },+ { id: 'art_2', threads: 1, title: '设置页' },+ ]);++ const prompt = await buildArtboardCommentsPrompt(deps, 'proj-1', 'tpc-1');++ expect(mocks.unreadCommentNotices).toHaveBeenCalledWith('proj-1', 'tpc-1');+ expect(prompt).toContain('<artboard_comments>');+ expect(prompt).toContain('art_1 "导出话题": 3 unread comment threads');+ expect(prompt).toContain('art_2 "设置页": 1 unread comment thread');+ expect(prompt).toContain('listArtboardComments');+ });++ it('adds nothing when no thread is unread, outside a project, or when the read fails', async () => {+ mocks.unreadCommentNotices.mockResolvedValue([]);+ expect(await buildArtboardCommentsPrompt(deps, 'proj-1', 'tpc-1')).toBeUndefined();+ expect(await buildArtboardCommentsPrompt(deps, undefined, 'tpc-1')).toBeUndefined();+ expect(await buildArtboardCommentsPrompt(deps, 'proj-1', undefined)).toBeUndefined();++ mocks.unreadCommentNotices.mockRejectedValue(new Error('db down'));+ expect(await buildArtboardCommentsPrompt(deps, 'proj-1', 'tpc-1')).toBeUndefined();+ });+});diff --git a/apps/server/src/services/aiAgent/pipeline/artboardContext.ts b/apps/server/src/services/aiAgent/pipeline/artboardContext.tsnew file mode 100644index 00000000000..5c477ff65f9--- /dev/null+++ b/apps/server/src/services/aiAgent/pipeline/artboardContext.ts@@ -0,0 +1,40 @@+import debug from 'debug';++import type { ProjectContextDeps } from './projectContext';++const log = debug('lobe-server:ai-agent-service');++export const buildArtboardCommentsPrompt = async (+ deps: ProjectContextDeps,+ projectId: string | undefined,+ topicId: string | undefined,+): Promise<string | undefined> => {+ if (!projectId || !topicId) return;++ try {+ // Lazy-loaded on purpose: ArtboardService depends on TaskService, which+ // imports this agent pipeline (`task -> aiAgent -> pipeline -> here -> artboard`),+ // so a static import would close that cycle.+ const { ArtboardService } = await import('@/server/services/artboard');+ const notices = await new ArtboardService(+ deps.db,+ deps.userId,+ deps.workspaceId,+ ).unreadCommentNotices(projectId, topicId);+ if (!notices.length) return;++ const lines = notices.map(+ ({ id, threads, title }) =>+ `- ${id} "${title}": ${threads} unread comment thread${threads === 1 ? '' : 's'}`,+ );+ return [+ '<artboard_comments>',+ 'The user left comments on an artboard of this conversation that you have not read yet. Read them with listArtboardComments before you answer.',+ ...lines,+ '</artboard_comments>',+ ].join('\n');+ } catch (error) {+ log('execAgent: failed to read artboard comments for %s: %O', topicId, error);+ return;+ }+};diff --git a/apps/server/src/services/aiAgent/pipeline/execTurn.ts b/apps/server/src/services/aiAgent/pipeline/execTurn.tsindex ec26f1bd643..53424bfc456 100644--- a/apps/server/src/services/aiAgent/pipeline/execTurn.ts+++ b/apps/server/src/services/aiAgent/pipeline/execTurn.ts@@ -826,6 +826,7 @@ export const execAgentTurn = async (},runContext,{+ acceptsArtboardWorks: params.acceptsArtboardWorks,acceptsFileWorks: params.acceptsFileWorks,acceptsMemberRuntimeEnd: params.acceptsMemberRuntimeEnd,approvalClaim,diff --git a/apps/server/src/services/aiAgent/pipeline/operationPrep.ts b/apps/server/src/services/aiAgent/pipeline/operationPrep.tsindex a7344710727..d8a1cb339d6 100644--- a/apps/server/src/services/aiAgent/pipeline/operationPrep.ts+++ b/apps/server/src/services/aiAgent/pipeline/operationPrep.ts@@ -1,5 +1,6 @@import type { AgentRuntimeContext } from '@lobechat/agent-runtime';import { extractActivatedToolIdsFromMessages } from '@lobechat/agent-runtime';+import { ArtboardIdentifier } from '@lobechat/builtin-tool-artboard';import { ChannelIdentifier } from '@lobechat/builtin-tool-channel';import { getShellSyntaxGuidance } from '@lobechat/builtin-tool-local-system';import { TaskIdentifier } from '@lobechat/builtin-tool-task';@@ -39,6 +40,7 @@ import type {ResolvedWorkspaceInit,} from '../types';import { isWorkspaceCacheFresh, upsertWorkspaceScan } from '../workspaceInitCache';+import { buildArtboardCommentsPrompt } from './artboardContext';import { buildOperationSkillSet, collectSelectedSkillIds } from './operationSkillSet';import { buildRunProjectContextPrompt } from './projectContext';import type { ToolDiscoveryResult } from './toolDiscovery';@@ -749,14 +751,19 @@ export const prepareOperation = async (// Page-scoped context (the viewed task or goal) and the project the run is in.// Delegation rules name the task tool, so they follow its presence in the final set.- const [taskManagerPrompt, goalOverview, projectPrompt] = await Promise.all([+ const [taskManagerPrompt, goalOverview, projectOverview, artboardComments] = await Promise.all([buildViewedTaskContextPrompt(deps, appContext, input.taskId),buildViewedGoalOverview(deps, appContext),buildRunProjectContextPrompt(deps, appContext?.projectId, resolvedAgentId, {channelMessaging: !!toolsResult.enabledToolIds?.includes(ChannelIdentifier),coordinationRules: !!toolsResult.enabledToolIds?.includes(TaskIdentifier),}),+ toolsResult.enabledToolIds?.includes(ArtboardIdentifier)+ ? buildArtboardCommentsPrompt(deps, appContext?.projectId, topicId)+ : undefined,]);+ const projectPrompt =+ [projectOverview, artboardComments].filter(Boolean).join('\n\n') || undefined;if (taskManagerPrompt || goalOverview || projectPrompt) {initialContext = {...initialContext,diff --git a/apps/server/src/services/aiAgent/pipeline/startOperation.ts b/apps/server/src/services/aiAgent/pipeline/startOperation.tsindex f171adc69ee..d70175a7b54 100644--- a/apps/server/src/services/aiAgent/pipeline/startOperation.ts+++ b/apps/server/src/services/aiAgent/pipeline/startOperation.ts@@ -38,6 +38,7 @@ export type StartOperationInit =| { pendingRequest: OperationInitRequest };export interface StartOperationInput {+ acceptsArtboardWorks?: boolean;/** See {@link InternalExecAgentParams.acceptsFileWorks}. */acceptsFileWorks?: boolean;/** See {@link InternalExecAgentParams.acceptsMemberRuntimeEnd}. */@@ -124,6 +125,7 @@ export const startOperation = async (userMessageId,} = ctx;const {+ acceptsArtboardWorks,acceptsFileWorks,acceptsMemberRuntimeEnd,approvalClaim,@@ -212,6 +214,11 @@ export const startOperation = async (: undefined);// Its `file_works` declaration too, or the continuation's terminal push// would drop the file Work card the parked client can render.+ const artboardWorksAccepted =+ acceptsArtboardWorks ??+ (approvalSourceOperationId+ ? await deps.agentRuntimeService.acceptsArtboardWorks(approvalSourceOperationId)+ : undefined);const fileWorksAccepted =acceptsFileWorks ??(approvalSourceOperationId@@ -236,6 +243,7 @@ export const startOperation = async (: await resolveOperationInitSlots(init);const result = await deps.agentRuntimeService.createOperation({...initSlots,+ acceptsArtboardWorks: artboardWorksAccepted,pendingInitRequest,acceptsFileWorks: fileWorksAccepted,acceptsMemberRuntimeEnd: memberRuntimeEndAccepted,diff --git a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/index.ts b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/index.tsindex d3ba1fc3fe2..5a5c805bcb8 100644--- a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/index.ts+++ b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/index.ts@@ -498,6 +498,7 @@ export const discoverTools = async (attachedFileTypes: await toolReads.attachedFileTypes,externalFileTypes: rawExternalFileTypes,isBotConversation,+ isProjectConversation: !!appContext?.projectId,isProjectCoordinator: projectScope.isCoordinator,loadHistoryMessages,modelMediaCapabilities,diff --git a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/turnContext.test.ts b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/turnContext.test.tsindex ea4cc88a695..50787589f3e 100644--- a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/turnContext.test.ts+++ b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/turnContext.test.ts@@ -1,3 +1,4 @@+import { ArtboardIdentifier } from '@lobechat/builtin-tool-artboard';import { GoalIdentifier } from '@lobechat/builtin-tool-goal';import { describe, expect, it, vi } from 'vitest';@@ -39,3 +40,19 @@ describe('resolveTurnScopedPluginIds goal follow-up', () => {expect(await resolve([{ role: 'user' }, { role: 'assistant' }])).toEqual([]);});});++describe('resolveTurnScopedPluginIds artboard', () => {+ const resolveIn = (isProjectConversation: boolean) =>+ resolveTurnScopedPluginIds({+ attachedFileTypes: [],+ isBotConversation: false,+ isProjectConversation,+ loadHistoryMessages: async () => [],+ modelMediaCapabilities: { audio: true, video: true, vision: true },+ });++ it('offers the artboard tool only in a project conversation', async () => {+ expect(await resolveIn(true)).toContain(ArtboardIdentifier);+ expect(await resolveIn(false)).not.toContain(ArtboardIdentifier);+ });+});diff --git a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/turnContext.ts b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/turnContext.tsindex fa6bf18d2f0..32de3747217 100644--- a/apps/server/src/services/aiAgent/pipeline/toolDiscovery/turnContext.ts+++ b/apps/server/src/services/aiAgent/pipeline/toolDiscovery/turnContext.ts@@ -1,3 +1,4 @@+import { ArtboardIdentifier } from '@lobechat/builtin-tool-artboard';import { GoalIdentifier, hasUnfinishedGoalProposal } from '@lobechat/builtin-tool-goal';import { LobeAgentManifest } from '@lobechat/builtin-tool-lobe-agent';import { MessageToolIdentifier } from '@lobechat/builtin-tool-message';@@ -30,17 +31,25 @@ const log = debug('lobe-server:ai-agent-service');* and the goal tool while the conversation's latest goal proposal has not* created a goal (rejected with feedback, pending, or failed), so the resumed* turn or a plain "try again" can revise and resubmit it without `/goal`.+ * The artboard tool belongs to project conversations only; this server-side+ * discovery is its only way in, since it has no client executor.*/export const resolveTurnScopedPluginIds = async (params: {attachedFileTypes: string[];externalFileTypes?: string[];isBotConversation: boolean;+ isProjectConversation?: boolean;isProjectCoordinator?: boolean;loadHistoryMessages: ToolDiscoveryInput['loadHistoryMessages'];modelMediaCapabilities: Pick<ModelAbilities, 'audio' | 'video' | 'vision'>;}): Promise<string[]> => {- const { isBotConversation, isProjectCoordinator, loadHistoryMessages, modelMediaCapabilities } =- params;+ const {+ isBotConversation,+ isProjectConversation,+ isProjectCoordinator,+ loadHistoryMessages,+ modelMediaCapabilities,+ } = params;const externalFileTypes = params.externalFileTypes ?? [];const inputFileTypes = [...externalFileTypes, ...params.attachedFileTypes];const inputMediaAvailability = getMediaAvailabilityFromFileTypes(inputFileTypes);@@ -75,6 +84,7 @@ export const resolveTurnScopedPluginIds = async (params: {...(isBotConversation ? [MessageToolIdentifier] : []),...(continuesGoalProposal ? [GoalIdentifier] : []),...(isProjectCoordinator ? [TaskIdentifier] : []),+ ...(isProjectConversation ? [ArtboardIdentifier] : []),...(shouldEnableMultimodalUnderstanding ? [LobeAgentManifest.identifier] : []),];};diff --git a/apps/server/src/services/aiAgent/steerQueue/inject.test.ts b/apps/server/src/services/aiAgent/steerQueue/inject.test.tsindex 252f914359d..039717744a7 100644--- a/apps/server/src/services/aiAgent/steerQueue/inject.test.ts+++ b/apps/server/src/services/aiAgent/steerQueue/inject.test.ts@@ -64,6 +64,10 @@ describe('canJoinRunningTurn', () => {expect(canJoinRunningTurn(followUp('a', 1), state)).toBe(true);});+ it('does not join a turn that has a different artboard stream capability', () => {+ expect(canJoinRunningTurn(followUp('a', 1, { acceptsArtboardWorks: true }), state)).toBe(false);+ });+it('takes a parent’s steer instruction whatever the sub-agent run’s settings', () => {const subAgentRun = {...state,diff --git a/apps/server/src/services/aiAgent/steerQueue/inject.ts b/apps/server/src/services/aiAgent/steerQueue/inject.tsindex 8aea763ccd8..d28068062f0 100644--- a/apps/server/src/services/aiAgent/steerQueue/inject.ts+++ b/apps/server/src/services/aiAgent/steerQueue/inject.ts@@ -46,6 +46,7 @@ const matchesRunningTurnSettings = (if (request.clientProtocol && request.clientProtocol !== (state.host?.clientProtocol ?? 1)) {return false;}+ if (!!request.acceptsArtboardWorks !== !!state.host?.acceptsArtboardWorks) return false;if (!!request.acceptsFileWorks !== !!state.host?.acceptsFileWorks) return false;if (request.llmExecutor) {diff --git a/apps/server/src/services/aiAgent/types.ts b/apps/server/src/services/aiAgent/types.tsindex c57e305af8a..88864d9ffb1 100644--- a/apps/server/src/services/aiAgent/types.ts+++ b/apps/server/src/services/aiAgent/types.ts@@ -99,6 +99,7 @@ export interface ExecRunContext {* This extends the public ExecAgentParams with server-side only options*/export interface InternalExecAgentParams extends ExecAgentParams {+ acceptsArtboardWorks?: boolean;/*** The calling client renders `file` Works in pushed snapshots, derived from* the `streamFeatures` it declared on `aiAgent.execAgent`. Seediff --git a/apps/server/src/services/aiChat/index.test.ts b/apps/server/src/services/aiChat/index.test.tsindex b019abfecb3..a7c2e16e295 100644--- a/apps/server/src/services/aiChat/index.test.ts+++ b/apps/server/src/services/aiChat/index.test.ts@@ -118,4 +118,27 @@ describe('AiChatService', () => {expect(mockQueryMessages).toHaveBeenCalled();expect(res.topics).toBeUndefined();});++ it('getMessagesAndTopics returns the work types the client asked for', async () => {+ const mockQueryMessages = vi.fn().mockResolvedValue([]);+ vi.mocked(MessageModel).mockImplementation(function () {+ return { query: mockQueryMessages } as any;+ });+ vi.mocked(TopicModel).mockImplementation(function () {+ return { query: vi.fn() } as any;+ });+ vi.mocked(FileService).mockImplementation(function () {+ return {} as any;+ });++ const service = new AiChatService({} as LobeChatDatabase, 'u1', undefined, {+ workTypeOptIn: { includeArtboardWorks: true },+ });+ await service.getMessagesAndTopics({ topicId: 't1' });++ expect(mockQueryMessages).toHaveBeenCalledWith(+ { includeArtboardWorks: true, topicId: 't1' },+ expect.anything(),+ );+ });});diff --git a/apps/server/src/services/aiChat/index.ts b/apps/server/src/services/aiChat/index.tsindex 89dc29b3ec3..ae71c3cce3a 100644--- a/apps/server/src/services/aiChat/index.ts+++ b/apps/server/src/services/aiChat/index.ts@@ -3,6 +3,7 @@ import { createTimingHelpers } from '@lobechat/utils';import { MessageModel } from '@/database/models/message';import { TopicModel } from '@/database/models/topic';+import type { WorkTypeOptIn } from '@/database/models/work/registry';import { FileService } from '@/server/services/file';const { createPrefixedTimingContext, runTimedStage, toTimingContext } = createTimingHelpers(@@ -33,8 +34,15 @@ export class AiChatService {private messageModel: MessageModel;private fileService: FileService;private topicModel: TopicModel;+ private workTypeOptIn: WorkTypeOptIn;- constructor(serverDB: LobeChatDatabase, userId: string, workspaceId?: string) {+ constructor(+ serverDB: LobeChatDatabase,+ userId: string,+ workspaceId?: string,+ options: { workTypeOptIn?: WorkTypeOptIn } = {},+ ) {+ this.workTypeOptIn = options.workTypeOptIn ?? {};this.messageModel = new MessageModel(serverDB, userId, workspaceId);this.topicModel = new TopicModel(serverDB, userId, workspaceId);this.fileService = new FileService(serverDB, userId, workspaceId);@@ -56,11 +64,14 @@ export class AiChatService {timingContext,'lambda.aiChat.messagesAndTopics.messageModel.query',() =>- this.messageModel.query(messageParams, {- postProcessUrl: (path, file) =>- this.fileService.getFileAccessUrl({ id: file.id, url: path }),- ...(messageTiming ? { timing: messageTiming } : {}),- }),+ this.messageModel.query(+ { ...messageParams, ...this.workTypeOptIn },+ {+ postProcessUrl: (path, file) =>+ this.fileService.getFileAccessUrl({ id: file.id, url: path }),+ ...(messageTiming ? { timing: messageTiming } : {}),+ },+ ),{hasAgentId: !!params.agentId,hasThreadId: !!params.threadId,diff --git a/apps/server/src/services/artboard/__tests__/comments.integration.test.ts b/apps/server/src/services/artboard/__tests__/comments.integration.test.tsnew file mode 100644index 00000000000..ff9eb7acdf9--- /dev/null+++ b/apps/server/src/services/artboard/__tests__/comments.integration.test.ts@@ -0,0 +1,338 @@+// @vitest-environment node+import { createHash } from 'node:crypto';++import { type LobeChatDatabase } from '@lobechat/database';+import { getTestDB } from '@lobechat/database/test-utils';+import type { ArtboardOp } from '@lobechat/types';+import { eq } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { agents, projects, tasks, topics, users } from '@/database/schemas';++import { ArtboardServiceError } from '../errors';+import type { ArtboardBlobStore } from '../files';+import { ArtboardService } from '../index';+import type { ArtboardSourceResolver } from '../sources';++const userId = 'artboard-comments-user';+const agentId = 'agt_artboard_comments';+const projectId = 'prj_artboard_comments';+const topicId = 'tpc_artboard_comments';++const db: LobeChatDatabase = await getTestDB();++const sources: ArtboardSourceResolver = {+ imageBytes: async () => undefined,+ importPage: async () => undefined,+};++const blobs = new Map<string, Uint8Array>();+const fileStore: ArtboardBlobStore = {+ delete: async (keys) => {+ for (const key of keys) blobs.delete(key);+ },+ list: async (prefix) =>+ [...blobs]+ .filter(([key]) => key.startsWith(prefix))+ .map(([key, bytes]) => ({+ etag: createHash('md5').update(bytes).digest('hex'),+ key,+ size: bytes.byteLength,+ })),+ presignWrite: async (key) => ({ url: `memory://${key}` }),+ read: async (key) => blobs.get(key) ?? new Uint8Array(),+ write: async (key, bytes) => {+ blobs.set(key, bytes);+ },+};++const asUser = () =>+ new ArtboardService(db, userId, undefined, { context: { agentId: null }, fileStore, sources });+const asAgent = () =>+ new ArtboardService(db, userId, undefined, { context: { agentId }, fileStore, sources });++const ops = (): ArtboardOp[] => [+ { group: { kind: 'journey', title: '主流程' }, ref: 'j', type: 'addGroup' },+ {+ board: {+ groupId: 'j',+ source: { kind: 'file', path: 'pages/home.html' },+ title: '首页',+ x: 0,+ y: 0,+ },+ type: 'addBoard',+ },+ { ref: 'r', round: { title: '入口放哪' }, type: 'addRound' },+ { group: { kind: 'options', title: '方案' }, ref: 'o', type: 'addGroup' },+ {+ board: {+ groupId: 'o',+ recommended: true,+ roundId: 'r',+ source: { kind: 'file', path: 'pages/option-a.html' },+ title: 'A',+ x: 0,+ y: 800,+ },+ type: 'addBoard',+ },+];++const create = async () => {+ const { artboard } = await asUser().create(+ {+ files: {+ writes: [+ { content: '<h1>首页</h1>', path: 'pages/home.html' },+ { content: '<h1>A</h1>', path: 'pages/option-a.html' },+ ],+ },+ ops: ops(),+ title: '画板',+ },+ { topicId },+ );+ const journey = artboard.content.boards.find((b) => !b.roundId)!;+ const option = artboard.content.boards.find((b) => b.roundId)!;+ return { artboard, journey, option, round: artboard.content.rounds[0] };+};++const errorOf = async (promise: Promise<unknown>) => {+ try {+ await promise;+ } catch (error) {+ if (error instanceof ArtboardServiceError) return error;+ throw error;+ }+ throw new Error('expected an ArtboardServiceError');+};++const threadOf = async (artboardId: string, id: string) =>+ (await asUser().listComments(artboardId)).find((thread) => thread.id === id)!;++beforeEach(async () => {+ await db.delete(users).where(eq(users.id, userId));+ await db.insert(users).values({ id: userId });+ await db.insert(agents).values({ id: agentId, userId });+ await db.insert(projects).values({ id: projectId, name: 'Comments', userId });+ await db.insert(topics).values({ id: topicId, projectId, title: '需求讨论', userId });+ blobs.clear();+});++afterEach(async () => {+ await db.delete(tasks).where(eq(tasks.createdByUserId, userId));+ await db.delete(users).where(eq(users.id, userId));+});++describe('ArtboardService comment delivery', () => {+ it('marks a thread unread until the agent takes it, and again on a new user reply', async () => {+ const { artboard } = await create();+ const thread = await asUser().addComment(artboard.id, { clientId: 'c1', content: '太挤了' });+ expect((await threadOf(artboard.id, thread.id)).unread).toBe(true);++ await asAgent().takeUndeliveredComments(artboard.id);+ expect((await threadOf(artboard.id, thread.id)).unread).toBe(false);++ await asAgent().replyComment(thread.id, { content: '已拉开' });+ expect((await threadOf(artboard.id, thread.id)).unread).toBe(false);++ await asUser().replyComment(thread.id, { clientId: 'c2', content: '还是挤' });+ expect((await threadOf(artboard.id, thread.id)).unread).toBe(true);+ });++ it('drops a thread the user resolved from the unread set and from the agent', async () => {+ const { artboard } = await create();+ const thread = await asUser().addComment(artboard.id, { clientId: 'c1', content: '算了' });+ await asUser().resolveComment(thread.id);++ expect((await threadOf(artboard.id, thread.id)).unread).toBe(false);+ expect(await asUser().countUndeliveredComments(artboard.id)).toBe(0);+ expect(await asAgent().takeUndeliveredComments(artboard.id)).toEqual([]);+ });++ it("still hands the agent the user's answer when the user resolves its question first", async () => {+ const { artboard } = await create();+ const question = await asAgent().askQuestion(artboard.id, { content: '入口放哪?' });+ await asUser().replyComment(question.id, { clientId: 'c1', content: '标题旁' });+ await asUser().resolveComment(question.id);++ expect((await threadOf(artboard.id, question.id)).unread).toBe(true);+ expect(await asUser().countUndeliveredComments(artboard.id)).toBe(1);+ const taken = await asAgent().takeUndeliveredComments(artboard.id);+ expect(taken.map((thread) => thread.id)).toEqual([question.id]);+ expect(taken[0].replies.map((reply) => reply.content)).toEqual(['标题旁']);+ expect(await asUser().countUndeliveredComments(artboard.id)).toBe(0);+ });++ it('keeps a question the user resolved without answering away from the agent', async () => {+ const { artboard } = await create();+ const question = await asAgent().askQuestion(artboard.id, { content: '入口放哪?' });+ await asUser().resolveComment(question.id);++ expect(await asUser().countUndeliveredComments(artboard.id)).toBe(0);+ expect(await asAgent().takeUndeliveredComments(artboard.id)).toEqual([]);+ });++ it('keeps comments on the options of an open round from the agent until it is submitted', async () => {+ const { artboard, journey, option, round } = await create();+ const quiet = await asUser().addComment(artboard.id, {+ anchor: { type: 'canvas', x: 0.5, y: 0.5 },+ boardId: option.id,+ clientId: 'c1',+ content: 'A 的按钮太小',+ });+ const loud = await asUser().addComment(artboard.id, {+ anchor: { type: 'canvas', x: 0.1, y: 0.2 },+ boardId: journey.id,+ clientId: 'c2',+ content: '首页缺标题',+ });++ expect(await asUser().countUndeliveredComments(artboard.id)).toBe(1);+ const first = await asAgent().takeUndeliveredComments(artboard.id);+ expect(first.map((thread) => thread.id)).toEqual([loud.id]);+ expect((await threadOf(artboard.id, quiet.id)).unread).toBe(true);++ await asUser().submitRound(artboard.id, round.id);+ expect(await asUser().countUndeliveredComments(artboard.id)).toBe(1);+ const second = await asAgent().takeUndeliveredComments(artboard.id);+ expect(second.map((thread) => thread.id)).toContain(quiet.id);+ expect((await threadOf(artboard.id, quiet.id)).unread).toBe(false);+ });++ it('tells the agent which of the threads it takes carry something new', async () => {+ const { artboard } = await create();+ const old = await asUser().addComment(artboard.id, { clientId: 'c1', content: '旧的' });+ await asAgent().takeUndeliveredComments(artboard.id);+ const fresh = await asUser().addComment(artboard.id, { clientId: 'c2', content: '新的' });++ const taken = await asAgent().takeUndeliveredComments(artboard.id);++ expect(Object.fromEntries(taken.map((thread) => [thread.id, thread.unread]))).toEqual({+ [old.id]: false,+ [fresh.id]: true,+ });+ expect((await threadOf(artboard.id, fresh.id)).unread).toBe(false);+ });++ it('refuses a submit when the open rounds are not the ones the user saw', async () => {+ const { artboard, round } = await create();++ const error = await errorOf(asUser().submitOpenRounds(artboard.id, ['rnd_gone']));++ expect(error.code).toBe('conflict');+ const { artboard: after } = await asUser().get(artboard.id);+ expect(after.content.rounds[0].status).toBe('open');+ expect((await asUser().submitOpenRounds(artboard.id, [round.id])).submitted).toBe(1);+ });++ it('counts threads, not messages', async () => {+ const { artboard } = await create();+ const thread = await asUser().addComment(artboard.id, { clientId: 'c1', content: '一' });+ await asUser().replyComment(thread.id, { clientId: 'c2', content: '二' });+ await asUser().addComment(artboard.id, { clientId: 'c3', content: '三' });++ expect(await asUser().countUndeliveredComments(artboard.id)).toBe(2);+ });+});++describe('ArtboardService.unreadCommentNotices', () => {+ it('lists the artboards of a conversation that have unread threads', async () => {+ const { artboard } = await create();+ expect(await asUser().unreadCommentNotices(projectId, topicId)).toEqual([]);++ await asUser().addComment(artboard.id, { clientId: 'c1', content: '一' });+ await asUser().addComment(artboard.id, { clientId: 'c2', content: '二' });++ expect(await asUser().unreadCommentNotices(projectId, topicId)).toEqual([+ { id: artboard.id, threads: 2, title: '画板' },+ ]);+ expect(await asUser().unreadCommentNotices(projectId, 'tpc_other')).toEqual([]);+ });+});++describe('ArtboardService comment anchors', () => {+ it('flags a board thread as stale once the board file it was written on changes', async () => {+ const { artboard, journey } = await create();+ const onBoard = await asUser().addComment(artboard.id, {+ anchor: { type: 'canvas', x: 0.5, y: 0.5 },+ boardId: journey.id,+ clientId: 'c1',+ content: '按钮颜色',+ });+ const onCanvas = await asUser().addComment(artboard.id, { clientId: 'c2', content: '整体' });+ expect((await threadOf(artboard.id, onBoard.id)).stale).toBe(false);++ await asUser().writeFiles(artboard.id, {+ edits: [{ newText: '<h1>新首页</h1>', oldText: '<h1>首页</h1>', path: 'pages/home.html' }],+ });++ expect((await threadOf(artboard.id, onBoard.id)).stale).toBe(true);+ expect((await threadOf(artboard.id, onCanvas.id)).stale).toBe(false);+ });++ it('flags a board thread as stale once the board points at another file', async () => {+ const { artboard, journey } = await create();+ const onBoard = await asUser().addComment(artboard.id, {+ anchor: { type: 'canvas', x: 0.5, y: 0.5 },+ boardId: journey.id,+ clientId: 'c1',+ content: '按钮颜色',+ });++ await asUser().update(+ artboard.id,+ artboard.revision,+ [+ {+ id: journey.id,+ patch: { source: { kind: 'file', path: 'pages/home-v2.html' } },+ type: 'updateBoard',+ },+ ],+ { writes: [{ content: '<h1>首页 v2</h1>', path: 'pages/home-v2.html' }] },+ );++ expect((await threadOf(artboard.id, onBoard.id)).stale).toBe(true);+ });++ it('drops the anchor of a thread whose board was removed', async () => {+ const { artboard, journey } = await create();+ const thread = await asUser().addComment(artboard.id, {+ anchor: { type: 'canvas', x: 0.5, y: 0.25 },+ boardId: journey.id,+ clientId: 'c1',+ content: '按钮颜色',+ });+ const free = await asUser().addComment(artboard.id, {+ anchor: { type: 'canvas', x: 900, y: 40 },+ clientId: 'c2',+ content: '空白处',+ });++ await asUser().update(artboard.id, artboard.revision, [+ { id: journey.id, type: 'removeBoard' },+ ]);++ expect(await threadOf(artboard.id, thread.id)).toMatchObject({ anchor: null, boardId: null });+ expect((await threadOf(artboard.id, free.id)).anchor).toEqual({+ type: 'canvas',+ x: 900,+ y: 40,+ });+ });++ it('refuses a board anchor outside the board', async () => {+ const { artboard, journey } = await create();+ const error = await errorOf(+ asUser().addComment(artboard.id, {+ anchor: { type: 'canvas', x: 320, y: 0.5 },+ boardId: journey.id,+ clientId: 'c1',+ content: '外面',+ }),+ );+ expect(error.code).toBe('invalid');+ });+});diff --git a/apps/server/src/services/artboard/__tests__/fileAccess.integration.test.ts b/apps/server/src/services/artboard/__tests__/fileAccess.integration.test.tsnew file mode 100644index 00000000000..59b19642a0a--- /dev/null+++ b/apps/server/src/services/artboard/__tests__/fileAccess.integration.test.ts@@ -0,0 +1,136 @@+// @vitest-environment node+import { type LobeChatDatabase } from '@lobechat/database';+import { getTestDB } from '@lobechat/database/test-utils';+import { eq } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { artboards, users } from '@/database/schemas';++import {+ ARTBOARD_FILE_CSP,+ serveArtboardFile,+ signArtboardFileToken,+ verifyArtboardFileToken,+} from '../fileAccess';+import { type ArtboardBlobStore, ArtboardFileService } from '../files';++const userId = 'artboard-file-access-user';+const artboardId = 'art_file_access';+const otherArtboardId = 'art_file_access_other';+const now = new Date('2026-11-18T00:00:00Z').getTime();++const db: LobeChatDatabase = await getTestDB();++const blobs = new Map<string, Uint8Array>();+const store: ArtboardBlobStore = {+ delete: async () => {},+ list: async () => [],+ presignWrite: async (key) => ({ url: `memory://${key}` }),+ read: async (key) => {+ const bytes = blobs.get(key);+ if (!bytes) throw new Error('missing');+ return bytes;+ },+ write: async (key, bytes) => {+ blobs.set(key, bytes);+ },+};++const html = '<!doctype html><link rel="stylesheet" href="../a.css"><h1 style="color:#f50">Hi</h1>';++const serve = (token: string, path: string) =>+ serveArtboardFile({ db, path, storeFor: () => store, token });++beforeEach(async () => {+ vi.stubEnv('KEY_VAULTS_SECRET', 'test-secret');+ blobs.clear();+ await db.delete(users).where(eq(users.id, userId));+ await db.insert(users).values({ id: userId });+ await db.insert(artboards).values([+ { id: artboardId, title: 'A', userId },+ { id: otherArtboardId, title: 'B', userId },+ ]);+ await new ArtboardFileService({+ resolveImage: async () => undefined,+ resolveImport: async () => undefined,+ store,+ }).applyChanges(artboardId, {+ writes: [+ { content: html, path: 'pages/home.html' },+ { content: 'h1{font-size:40px}', path: 'a.css' },+ ],+ });+});++afterEach(() => {+ vi.unstubAllEnvs();+});++describe('artboard file tokens', () => {+ it('round-trips the artboard id until it expires', () => {+ const token = signArtboardFileToken(artboardId, now)!;++ expect(verifyArtboardFileToken(token, now + 60_000)).toBe(artboardId);+ expect(verifyArtboardFileToken(token, now + 13 * 60 * 60 * 1000)).toBeUndefined();+ });++ it('issues the same token within one window so viewers keep their frames', () => {+ expect(signArtboardFileToken(artboardId, now + 1000)).toBe(+ signArtboardFileToken(artboardId, now + 60 * 60 * 1000),+ );+ });++ it('rejects a token whose payload was changed', () => {+ const token = signArtboardFileToken(artboardId, now)!;+ const [, signature] = token.split('.');+ const forged = `${Buffer.from(JSON.stringify({ a: otherArtboardId, e: now + 1e9 })).toString('base64url')}.${signature}`;++ expect(verifyArtboardFileToken(forged, now)).toBeUndefined();+ });++ it('issues nothing without a server secret', () => {+ vi.stubEnv('KEY_VAULTS_SECRET', '');+ expect(signArtboardFileToken(artboardId, now)).toBeUndefined();+ });+});++describe('serveArtboardFile', () => {+ it('serves the file bytes under a sandboxing CSP', async () => {+ const token = signArtboardFileToken(artboardId, Date.now())!;++ const response = await serve(token, 'pages/home.html');++ expect(response.status).toBe(200);+ expect(await response.text()).toBe(html);+ expect(response.headers.get('content-type')).toBe('text/html; charset=utf-8');+ expect(response.headers.get('content-security-policy')).toBe(ARTBOARD_FILE_CSP);+ expect(ARTBOARD_FILE_CSP).toMatch(/^sandbox allow-scripts/);+ expect(ARTBOARD_FILE_CSP).toContain("connect-src 'none'");+ expect(response.headers.get('x-content-type-options')).toBe('nosniff');+ expect(response.headers.get('cache-control')).toBe('private, no-cache');+ });++ it('answers 404 under the sandbox CSP for a path nothing was written to', async () => {+ const token = signArtboardFileToken(artboardId, Date.now())!;++ const response = await serve(token, 'pages/not-yet.html');++ expect(response.status).toBe(404);+ expect(response.headers.get('content-security-policy')).toBe(ARTBOARD_FILE_CSP);+ });++ it('does not serve another artboard with a token for this one', async () => {+ const token = signArtboardFileToken(otherArtboardId, Date.now())!;++ const response = await serve(token, 'pages/home.html');++ expect(response.status).toBe(404);+ expect(response.headers.get('content-security-policy')).toBe(ARTBOARD_FILE_CSP);+ });++ it('refuses a bad token and a path that leaves the artboard', async () => {+ expect((await serve('nope', 'pages/home.html')).status).toBe(404);+ const token = signArtboardFileToken(artboardId, Date.now())!;+ expect((await serve(token, '../a.css')).status).toBe(404);+ });+});diff --git a/apps/server/src/services/artboard/__tests__/files.integration.test.ts b/apps/server/src/services/artboard/__tests__/files.integration.test.tsnew file mode 100644index 00000000000..2fca14c6cfb--- /dev/null+++ b/apps/server/src/services/artboard/__tests__/files.integration.test.ts@@ -0,0 +1,240 @@+// @vitest-environment node+import { createHash } from 'node:crypto';++import { ARTBOARD_FILE_LIMITS } from '@lobechat/types';+import { beforeEach, describe, expect, it } from 'vitest';++import { ArtboardServiceError } from '../errors';+import { type ArtboardBlobStore, ArtboardFileService } from '../files';++const artboardId = 'art_files_service';++export const memoryStore = () => {+ const blobs = new Map<string, Uint8Array>();+ const store: ArtboardBlobStore = {+ delete: async (keys) => {+ for (const key of keys) blobs.delete(key);+ },+ list: async (prefix) =>+ [...blobs]+ .filter(([key]) => key.startsWith(prefix))+ .map(([key, bytes]) => ({+ etag: createHash('md5').update(bytes).digest('hex'),+ key,+ size: bytes.byteLength,+ })),+ presignWrite: async (key) => ({ url: `memory://${key}` }),+ read: async (key) => {+ const bytes = blobs.get(key);+ if (!bytes) throw new Error(`missing ${key}`);+ return bytes;+ },+ write: async (key, bytes) => {+ blobs.set(key, bytes);+ },+ };+ return { blobs, store };+};++const md5 = (text: string | Uint8Array) => createHash('md5').update(text).digest('hex');+const shot = new Uint8Array([137, 80, 78, 71]);++let blobs: Map<string, Uint8Array>;+let service: ArtboardFileService;++const errorOf = async (promise: Promise<unknown>) => {+ try {+ await promise;+ } catch (error) {+ if (error instanceof ArtboardServiceError) return error;+ throw error;+ }+ throw new Error('expected an ArtboardServiceError');+};++beforeEach(() => {+ const memory = memoryStore();+ blobs = memory.blobs;+ service = new ArtboardFileService({+ resolveImage: async (fileRef) =>+ fileRef === 'msg_1.image_1' ? { bytes: shot, contentType: 'image/png' } : undefined,+ resolveImport: async ({ canvasId }) =>+ canvasId === 'cvs_1'+ ? {+ assets: [{ bytes: new TextEncoder().encode('p{}'), path: 'assets/app.css' }],+ entry: new TextEncoder().encode('<html>canvas</html>'),+ }+ : undefined,+ store: memory.store,+ });+});++describe('ArtboardFileService', () => {+ it('stores each file under its path and lists it with its ETag', async () => {+ const html = '<!doctype html><body style="background:#0b0b0b">hi</body>';++ const changed = await service.applyChanges(artboardId, {+ writes: [{ content: html, path: 'pages/home/a.html' }],+ });++ expect(changed).toEqual(['pages/home/a.html']);+ expect(+ new TextDecoder().decode(blobs.get(`artboards/${artboardId}/files/pages/home/a.html`)),+ ).toBe(html);+ expect(await service.list(artboardId)).toEqual([+ {+ contentType: 'text/html; charset=utf-8',+ hash: md5(html),+ path: 'pages/home/a.html',+ size: html.length,+ },+ ]);+ });++ it('reads a text file back', async () => {+ await service.applyChanges(artboardId, { writes: [{ content: 'a { }', path: 'a.css' }] });++ expect(await service.read(artboardId, 'a.css')).toMatchObject({+ content: 'a { }',+ contentType: 'text/css; charset=utf-8',+ path: 'a.css',+ });+ });++ it('reports a missing file as not found', async () => {+ expect((await errorOf(service.read(artboardId, 'gone.html'))).code).toBe('not_found');+ });++ it('copies an image from the conversation by its ref, and writes base64 as raw bytes', async () => {+ await service.applyChanges(artboardId, {+ writes: [+ { fileRef: 'msg_1.image_1', path: 'shots/a.png' },+ { base64: Buffer.from(shot).toString('base64'), path: 'shots/b.png' },+ ],+ });++ expect(blobs.get(`artboards/${artboardId}/files/shots/a.png`)).toEqual(shot);+ expect(blobs.get(`artboards/${artboardId}/files/shots/b.png`)).toEqual(shot);+ });++ it('refuses an image ref it cannot resolve', async () => {+ const error = await errorOf(+ service.applyChanges(artboardId, { writes: [{ fileRef: 'nope', path: 'x.png' }] }),+ );+ expect(error.code).toBe('source_denied');+ });++ it('imports a Canvas page as a copy, and refuses one it cannot read', async () => {+ await service.applyChanges(artboardId, {+ writes: [{ fromCanvas: { canvasId: 'cvs_1' }, path: 'pages/imported.html' }],+ });+ const missing = await errorOf(+ service.applyChanges(artboardId, {+ writes: [{ fromCanvas: { canvasId: 'cvs_gone' }, path: 'pages/x.html' }],+ }),+ );++ expect((await service.read(artboardId, 'pages/imported.html')).content).toBe(+ '<html>canvas</html>',+ );+ // Next to the page, so the page's relative <link href="assets/app.css"> still resolves.+ expect((await service.read(artboardId, 'pages/assets/app.css')).content).toBe('p{}');+ expect(missing.code).toBe('source_denied');+ });++ it('applies an edit whose old text appears exactly once', async () => {+ await service.applyChanges(artboardId, {+ writes: [{ content: '<h1>Old</h1><p>Old</p><b>x</b>', path: 'a.html' }],+ });++ await service.applyChanges(artboardId, {+ edits: [{ newText: 'y', oldText: 'x', path: 'a.html' }],+ });+ const twice = await errorOf(+ service.applyChanges(artboardId, {+ edits: [{ newText: 'New', oldText: 'Old', path: 'a.html' }],+ }),+ );+ const absent = await errorOf(+ service.applyChanges(artboardId, {+ edits: [{ newText: 'New', oldText: 'missing', path: 'a.html' }],+ }),+ );++ expect((await service.read(artboardId, 'a.html')).content).toBe(+ '<h1>Old</h1><p>Old</p><b>y</b>',+ );+ expect(twice.message).toContain('2 times');+ expect(absent.code).toBe('invalid');+ });++ it('refuses a path outside the artboard', async () => {+ const error = await errorOf(+ service.applyChanges(artboardId, { writes: [{ content: 'x', path: '../escape.html' }] }),+ );+ expect(error.code).toBe('invalid');+ });++ it('refuses a text file over the limit and writes nothing from the batch', async () => {+ const error = await errorOf(+ service.applyChanges(artboardId, {+ writes: [+ { content: 'ok', path: 'ok.html' },+ { content: 'x'.repeat(ARTBOARD_FILE_LIMITS.maxTextFileBytes + 1), path: 'big.html' },+ ],+ }),+ );++ expect(error.code).toBe('invalid');+ expect(blobs.size).toBe(0);+ });++ it('deletes files without asking whether a board shows them', async () => {+ await service.applyChanges(artboardId, {+ writes: [+ { content: 'a', path: 'a.html' },+ { content: 'b', path: 'b.html' },+ ],+ });++ await service.applyChanges(artboardId, { deletes: ['a.html', 'never-written.html'] });++ expect((await service.list(artboardId)).map((file) => file.path)).toEqual(['b.html']);+ });++ it('records a file the client PUT to its signed URL, and refuses one never uploaded', async () => {+ const { uploads } = await service.prepareUploads(artboardId, [+ { path: 'shots/big.png', size: 3 * 1024 * 1024 },+ ]);+ blobs.set(uploads[0].url.replace('memory://', ''), shot);++ const changed = await service.applyChanges(artboardId, {+ writes: [{ path: 'shots/big.png', uploaded: true }],+ });+ const never = await errorOf(+ service.applyChanges(artboardId, { writes: [{ path: 'shots/none.png', uploaded: true }] }),+ );++ expect(uploads.map((upload) => upload.path)).toEqual(['shots/big.png']);+ expect(changed).toEqual(['shots/big.png']);+ expect(never.code).toBe('invalid');+ });++ it('refuses to sign an upload over the size limit', async () => {+ const error = await errorOf(+ service.prepareUploads(artboardId, [+ { path: 'huge.png', size: ARTBOARD_FILE_LIMITS.maxImageBytes + 1 },+ ]),+ );+ expect(error.code).toBe('invalid');+ });++ it('removes every object of an artboard', async () => {+ await service.applyChanges(artboardId, { writes: [{ content: 'a', path: 'a.html' }] });+ blobs.set('artboards/other/files/keep.html', shot);++ await service.removeAll(artboardId);++ expect([...blobs.keys()]).toEqual(['artboards/other/files/keep.html']);+ });+});diff --git a/apps/server/src/services/artboard/__tests__/service.integration.test.ts b/apps/server/src/services/artboard/__tests__/service.integration.test.tsnew file mode 100644index 00000000000..c95ce1c9499--- /dev/null+++ b/apps/server/src/services/artboard/__tests__/service.integration.test.ts@@ -0,0 +1,972 @@+// @vitest-environment node+import { createHash } from 'node:crypto';++import { type LobeChatDatabase } from '@lobechat/database';+import { getTestDB } from '@lobechat/database/test-utils';+import type { ArtboardOp } from '@lobechat/types';+import { eq } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { TaskModel } from '@/database/models/task';+import {+ acceptanceFlowEdges,+ acceptanceFlowNodes,+ acceptanceFlows,+ agents,+ artboardBoards,+ artboardComments,+ artboardGroups,+ files,+ projects,+ tasks,+ topics,+ users,+} from '@/database/schemas';++import { ArtboardServiceError } from '../errors';+import type { ArtboardBlobStore } from '../files';+import { ArtboardService } from '../index';+import type { ArtboardSourceResolver } from '../sources';++const userId = 'artboard-service-user';+const projectId = 'prj_artboard_service';+const projectTopicId = 'tpc_artboard_project';+const looseTopicId = 'tpc_artboard_loose';+const context = { topicId: projectTopicId };++const db: LobeChatDatabase = await getTestDB();++const shotBytes = new Uint8Array([137, 80, 78, 71]);++const sources: ArtboardSourceResolver = {+ imageBytes: async (fileRef) =>+ fileRef === 'msg_1.image_1' ? { bytes: shotBytes, contentType: 'image/png' } : undefined,+ importPage: async () => undefined,+};++const blobs = new Map<string, Uint8Array>();+const fileStore: ArtboardBlobStore = {+ delete: async (keys) => {+ for (const key of keys) blobs.delete(key);+ },+ list: async (prefix) =>+ [...blobs]+ .filter(([key]) => key.startsWith(prefix))+ .map(([key, bytes]) => ({ etag: sha(bytes), key, size: bytes.byteLength })),+ presignWrite: async (key) => ({ url: `memory://${key}` }),+ read: async (key) => {+ const bytes = blobs.get(key);+ if (!bytes) throw new Error(`NoSuchKey ${key}`);+ return bytes;+ },+ write: async (key, bytes) => {+ blobs.set(key, bytes);+ },+};++// The object store's ETag: MD5 of the bytes for a single-part upload.+function sha(content: string | Uint8Array) {+ return createHash('md5').update(content).digest('hex');+}++const emptyHtml = '<!doctype html><body style="background:#111;color:#eee">空项目</body>';+const ingestHtml = '<!doctype html><svg width="40" height="40"><circle r="20" fill="#f50"/></svg>';++const baseFiles = {+ writes: [+ { content: emptyHtml, path: 'pages/empty.html' },+ { content: ingestHtml, path: 'pages/ingest.html' },+ ],+};++const service = () =>+ new ArtboardService(db, userId, undefined, { context: { agentId: null }, fileStore, sources });++const fileBoard = (ref: string, path: string, x: number, groupId = 'j'): ArtboardOp => ({+ board: { groupId, source: { kind: 'file', path }, title: ref, x, y: 0 },+ ref,+ type: 'addBoard',+});++const journeyOps = (): ArtboardOp[] => [+ { group: { kind: 'journey', title: '首次进入' }, ref: 'j', type: 'addGroup' },+ fileBoard('empty', 'pages/empty.html', 0),+ fileBoard('ingest', 'pages/ingest.html', 720),+ { edge: { from: 'empty', label: '点接入', to: 'ingest' }, type: 'addEdge' },+];++const optionOps = (): ArtboardOp[] => [+ { ref: 'r', round: { title: '布局' }, type: 'addRound' },+ { group: { kind: 'options', title: '方案' }, ref: 'o', type: 'addGroup' },+ {+ board: {+ groupId: 'o',+ recommended: true,+ roundId: 'r',+ source: { kind: 'file', path: 'pages/empty.html' },+ title: 'A',+ x: 0,+ y: 600,+ },+ type: 'addBoard',+ },+ {+ board: {+ groupId: 'o',+ roundId: 'r',+ source: { kind: 'file', path: 'pages/ingest.html' },+ title: 'B',+ x: 720,+ y: 600,+ },+ type: 'addBoard',+ },+];++const errorOf = async (promise: Promise<unknown>) => {+ try {+ await promise;+ } catch (error) {+ if (error instanceof ArtboardServiceError) return error;+ throw error;+ }+ throw new Error('expected an ArtboardServiceError');+};++const createJourney = (extra: ArtboardOp[] = []) =>+ service().create({ files: baseFiles, ops: [...journeyOps(), ...extra], title: '画板' }, context);++beforeEach(async () => {+ await db.delete(users).where(eq(users.id, userId));+ await db.insert(users).values({ id: userId });+ await db.insert(projects).values({ id: projectId, name: 'Onboarding', userId });+ await db.insert(topics).values([+ { id: projectTopicId, projectId, title: '需求讨论', userId },+ { id: looseTopicId, title: '随便聊聊', userId },+ ]);+ await db.insert(files).values({+ fileType: 'image/png',+ id: 'file_shot',+ name: 'shot.png',+ size: 1,+ url: 's',+ userId,+ });+ blobs.clear();+});++afterEach(async () => {+ await db.delete(tasks).where(eq(tasks.createdByUserId, userId));+ await db.delete(users).where(eq(users.id, userId));+});++describe('ArtboardService.create', () => {+ it('uses the task passed in, and stores each board as a row pointing at its file', async () => {+ const task = await new TaskModel(db, userId).create({ instruction: '首次进入', projectId });+ const result = await service().create(+ { files: baseFiles, ops: journeyOps(), taskId: task.identifier, title: '新用户首次进入项目' },+ { topicId: looseTopicId },+ );++ expect(result.artboard).toMatchObject({+ phase: 'discuss',+ projectId,+ revision: 1,+ taskId: task.id,+ topicId: looseTopicId,+ });+ expect(result.createdTask).toBe(false);+ const { boards, edges, groups, pages } = result.artboard.content;+ expect(pages).toHaveLength(1);+ expect(boards.map((b) => b.source)).toEqual([+ { hash: sha(emptyHtml), kind: 'file', path: 'pages/empty.html' },+ { hash: sha(ingestHtml), kind: 'file', path: 'pages/ingest.html' },+ ]);+ expect(boards.map((b) => b.type)).toEqual(['html', 'html']);+ expect(edges).toMatchObject([{ from: boards[0].id, label: '点接入', to: boards[1].id }]);+ expect(result.changedIds).toEqual([groups[0].id, boards[0].id, boards[1].id, edges[0].id]);++ const rows = await db+ .select()+ .from(artboardBoards)+ .where(eq(artboardBoards.projectId, projectId));+ expect(rows).toHaveLength(2);+ });++ it('wraps a group around its boards and keeps board positions in page coordinates', async () => {+ const { artboard } = await createJourney();+ const [group] = artboard.content.groups;++ expect(group.rect).toEqual({ h: 400 + 144 + 48, w: 720 + 640 + 96, x: -48, y: -144 });+ expect(artboard.content.boards.map((b) => b.rect)).toEqual([+ { h: 400, w: 640, x: 0, y: 0 },+ { h: 400, w: 640, x: 720, y: 0 },+ ]);+ const stored = await db+ .select({ rect: artboardBoards.rect })+ .from(artboardBoards)+ .where(eq(artboardBoards.groupId, group.id));+ expect(stored.map((row) => row.rect.x).sort((a, b) => a - b)).toEqual([48, 768]);+ });++ it('refuses a group whose frame lands on another group, and names both', async () => {+ const overlapping = optionOps().map((op) =>+ op.type === 'addBoard' ? { ...op, board: { ...op.board, y: 300 } } : op,+ );++ const error = await errorOf(createJourney(overlapping));++ expect(error.code).toBe('invalid');+ expect(error.message).toContain('首次进入');+ expect(error.message).toContain('方案');+ expect((await createJourney(optionOps())).artboard.content.groups).toHaveLength(2);+ });++ it('takes an edge without a label', async () => {+ const { artboard } = await service().create(+ {+ files: baseFiles,+ ops: [+ { group: { kind: 'journey', title: '首次进入' }, ref: 'j', type: 'addGroup' },+ fileBoard('empty', 'pages/empty.html', 0),+ fileBoard('ingest', 'pages/ingest.html', 720),+ { edge: { from: 'empty', to: 'ingest' }, type: 'addEdge' },+ ],+ title: '画板',+ },+ context,+ );++ expect(artboard.content.edges.map((edge) => edge.label)).toEqual(['']);+ });++ it('creates a task in the conversation’s project when none is given', async () => {+ const result = await service().create(+ { files: baseFiles, description: '讨论首次进入的流程', title: '首次进入' },+ context,+ );++ expect(result.createdTask).toBe(true);+ const [task] = await db.select().from(tasks).where(eq(tasks.id, result.artboard.taskId!));+ expect(task).toMatchObject({ name: '首次进入', projectId });+ });++ it('creates neither a board nor a task when an op is refused', async () => {+ const error = await errorOf(+ service().create(+ {+ files: baseFiles,+ ops: [+ { group: { kind: 'journey', title: 'A' }, type: 'addGroup' },+ { group: { kind: 'journey', title: 'B' }, type: 'addGroup' },+ ],+ title: '画板',+ },+ context,+ ),+ );++ expect(error).toMatchObject({ code: 'invalid', data: { opIndex: 1 } });+ expect(await db.select().from(tasks).where(eq(tasks.createdByUserId, userId))).toEqual([]);+ expect(await db.select().from(artboardGroups).where(eq(artboardGroups.userId, userId))).toEqual(+ [],+ );+ });++ it('refuses a board outside any project', async () => {+ const error = await errorOf(+ service().create({ files: baseFiles, title: '画板' }, { topicId: looseTopicId }),+ );+ expect(error.code).toBe('no_project');+ });++ it('refuses a second board for one task and names the first', async () => {+ const task = await new TaskModel(db, userId).create({ instruction: 'x', projectId });+ const first = await service().create({ files: baseFiles, taskId: task.id, title: 'A' }, {});++ const error = await errorOf(+ service().create({ files: baseFiles, taskId: task.id, title: 'B' }, {}),+ );+ expect(error.code).toBe('exists');+ expect(error.data.artboardId).toBe(first.artboard.id);+ });++ it('lays a board out before its file exists, then fills it in once the file is written', async () => {+ const { artboard } = await service().create(+ {+ ops: [+ { group: { kind: 'references', title: '参考' }, ref: 'o', type: 'addGroup' },+ fileBoard('x', 'pages/later.html', 0, 'o'),+ ],+ title: '画板',+ },+ context,+ );+ expect(artboard.content.boards[0].source).toEqual({+ hash: null,+ kind: 'file',+ path: 'pages/later.html',+ });++ await service().writeFiles(artboard.id, {+ writes: [{ content: '<p>later</p>', path: 'pages/later.html' }],+ });++ const { artboard: filled } = await service().read(artboard.id);+ expect(filled.content.boards[0].source?.hash).toBe(sha('<p>later</p>'));+ });++ it('copies an image ref into the artboard and shows it as an image board', async () => {+ const created = await service().create(+ {+ files: { writes: [{ fileRef: 'msg_1.image_1', path: 'shots/home.png' }] },+ ops: [+ { group: { kind: 'references', title: '参考' }, ref: 'r', type: 'addGroup' },+ {+ board: {+ groupId: 'r',+ source: { kind: 'file', path: 'shots/home.png' },+ title: '截图',+ x: 0,+ y: 0,+ },+ type: 'addBoard',+ },+ ],+ title: '画板',+ },+ context,+ );+ expect(created.artboard.content.boards[0]).toMatchObject({+ source: { kind: 'file', path: 'shots/home.png' },+ type: 'image',+ });+ });++ it('hands the viewer a signed base URL for the artboard files', async () => {+ vi.stubEnv('KEY_VAULTS_SECRET', 'test-secret');+ const { artboard } = await createJourney();++ const { fileBaseUrl } = await service().get(artboard.id);++ expect(fileBaseUrl).toMatch(/^\/artboard-files\/[\w-]+\.[\w-]+\/$/);+ vi.unstubAllEnvs();+ });++ it('refuses a board type that does not match its file', async () => {+ const error = await errorOf(+ service().create(+ {+ files: baseFiles,+ ops: [+ { group: { kind: 'references', title: '参考' }, ref: 'o', type: 'addGroup' },+ {+ board: {+ groupId: 'o',+ source: { kind: 'file', path: 'pages/empty.html' },+ title: 'x',+ type: 'image',+ x: 0,+ y: 0,+ },+ type: 'addBoard',+ },+ ],+ title: '画板',+ },+ context,+ ),+ );+ expect(error.code).toBe('invalid');+ });+});++describe('ArtboardService.update and read', () => {+ it('rejects a stale revision', async () => {+ const { artboard } = await createJourney();+ const [first, second] = artboard.content.boards;++ const updated = await service().update(artboard.id, 1, [+ { id: first.id, patch: { title: '新的空项目' }, type: 'updateBoard' },+ ]);+ expect(updated).toMatchObject({ artboard: { revision: 2 }, changedIds: [first.id] });++ const stale = await errorOf(+ service().update(artboard.id, 1, [{ id: second.id, type: 'removeBoard' }]),+ );+ expect(stale.code).toBe('conflict');+ });++ it('applies none of a batch when one op fails', async () => {+ const { artboard } = await createJourney();++ const error = await errorOf(+ service().update(artboard.id, 1, [+ { group: { kind: 'other', title: '其他' }, type: 'addGroup' },+ { id: 'nope', type: 'removeBoard' },+ ]),+ );++ expect(error).toMatchObject({ code: 'not_found', data: { opIndex: 1 } });+ const read = await service().read(artboard.id);+ expect(read.artboard.revision).toBe(1);+ expect(read.artboard.content.groups).toHaveLength(1);+ });++ it('moves the group and its siblings’ stored rects when a board moves left', async () => {+ const { artboard } = await createJourney();+ const [first] = artboard.content.boards;++ const { artboard: next } = await service().update(artboard.id, 1, [+ { id: first.id, patch: { x: -720 }, type: 'updateBoard' },+ ]);++ expect(next.content.groups[0].rect).toMatchObject({ w: 1440 + 640 + 96, x: -768 });+ expect(next.content.boards.map((b) => b.rect.x)).toEqual([-720, 720]);+ });++ it('keeps sibling page positions when a board lands above, changes group, or leaves', async () => {+ const { artboard } = await createJourney();+ const [empty, ingest] = artboard.content.boards;+ const journey = artboard.content.groups[0];++ const above = await service().update(artboard.id, 1, [+ {+ board: {+ groupId: journey.id,+ source: { kind: 'file', path: 'pages/empty.html' },+ title: 'top',+ x: 0,+ y: -700,+ },+ ref: 'top',+ type: 'addBoard',+ },+ { group: { kind: 'other', title: '其他' }, ref: 'x', type: 'addGroup' },+ ]);+ const at = (item: typeof above, id: string) =>+ item.artboard.content.boards.find((b) => b.id === id)!.rect;+ expect(above.artboard.content.groups[0].rect).toMatchObject({ x: -48, y: -844 });+ expect(at(above, empty.id)).toMatchObject({ x: 0, y: 0 });+ expect(at(above, ingest.id)).toMatchObject({ x: 720, y: 0 });++ const other = above.artboard.content.groups[1];+ expect(other.rect).toEqual({ h: 0, w: 0, x: 0, y: 0 });+ const top = above.artboard.content.boards.find((b) => b.title === 'top')!;+ const moved = await service().update(artboard.id, 2, [+ { id: top.id, patch: { groupId: other.id }, type: 'updateBoard' },+ ]);+ expect(moved.artboard.content.groups[0].rect).toMatchObject({ x: -48, y: -144 });+ expect(moved.artboard.content.groups[1].rect).toMatchObject({ x: -48, y: -844 });+ expect(at(moved, top.id)).toMatchObject({ x: 0, y: -700 });+ expect(at(moved, ingest.id)).toMatchObject({ x: 720, y: 0 });++ const emptied = await service().update(artboard.id, 3, [{ id: top.id, type: 'removeBoard' }]);+ expect(emptied.artboard.content.groups[1].rect).toEqual({ h: 0, w: 0, x: 0, y: 0 });+ });++ it('hides a board from another account on every entry point', async () => {+ const { artboard } = await createJourney(optionOps());+ const [round] = artboard.content.rounds;+ const [board] = artboard.content.boards;+ const thread = await service().addComment(artboard.id, { clientId: 'c1', content: 'hi' });+ await db.insert(users).values({ id: 'artboard_stranger' });+ const stranger = new ArtboardService(db, 'artboard_stranger', undefined, {+ fileStore,+ sources,+ });++ try {+ const attempts = [+ () => stranger.read(artboard.id),+ () => stranger.get(artboard.id),+ () => stranger.update(artboard.id, 1, [{ id: board.id, type: 'removeBoard' }]),+ () => stranger.chooseBoard(artboard.id, round.id, board.id),+ () => stranger.submitRound(artboard.id, round.id),+ () => stranger.listComments(artboard.id),+ () => stranger.addComment(artboard.id, { clientId: 'c2', content: 'x' }),+ () => stranger.replyComment(thread.id, { clientId: 'c3', content: 'x' }),+ () => stranger.resolveComment(thread.id),+ () => stranger.finalize(artboard.id, 1),+ ];+ for (const attempt of attempts) expect((await errorOf(attempt())).code).toBe('not_found');+ } finally {+ await db.delete(users).where(eq(users.id, 'artboard_stranger'));+ }+ });++ it('refuses a comment or reply with no text', async () => {+ const { artboard } = await createJourney();+ const thread = await service().addComment(artboard.id, { clientId: 'c1', content: 'hi' });++ const blank = await errorOf(+ service().addComment(artboard.id, { clientId: 'c2', content: ' ' }),+ );+ expect(blank.code).toBe('invalid');+ const reply = await errorOf(service().replyComment(thread.id, { content: '' }));+ expect(reply.code).toBe('invalid');+ });++ it('shows the new hash once a board file is rewritten', async () => {+ const { artboard } = await createJourney();++ await service().writeFiles(artboard.id, {+ edits: [{ newText: '新的空项目', oldText: '空项目', path: 'pages/empty.html' }],+ });++ const read = await service().read(artboard.id);+ expect(read.artboard.content.boards[0].source).toEqual({+ hash: sha(emptyHtml.replace('空项目', '新的空项目')),+ kind: 'file',+ path: 'pages/empty.html',+ });+ });++ it('moves the stamp viewers watch on a file-only write, without bumping the revision', async () => {+ const { artboard } = await createJourney();+ const before = await service().getRevision(artboard.id);++ await service().writeFiles(artboard.id, {+ edits: [{ newText: '新的空项目', oldText: '空项目', path: 'pages/empty.html' }],+ });+ const after = await service().getRevision(artboard.id);++ expect(after.revision).toBe(before.revision);+ expect(after.updatedAt.getTime()).toBeGreaterThan(before.updatedAt.getTime());+ });++ it('deletes a file a board shows; the board then shows it as missing', async () => {+ const { artboard } = await createJourney();++ await service().writeFiles(artboard.id, { deletes: ['pages/empty.html'] });++ const { artboard: after } = await service().read(artboard.id);+ expect(after.content.boards[0].source).toEqual({+ hash: null,+ kind: 'file',+ path: 'pages/empty.html',+ });+ expect((await service().listFiles(artboard.id)).map((file) => file.path)).toEqual([+ 'pages/ingest.html',+ ]);+ });++ it('removes a board and its file in one update', async () => {+ const { artboard } = await createJourney();+ const [first] = artboard.content.boards;++ await service().update(artboard.id, 1, [{ id: first.id, type: 'removeBoard' }], {+ deletes: ['pages/empty.html'],+ });++ expect((await service().listFiles(artboard.id)).map((file) => file.path)).toEqual([+ 'pages/ingest.html',+ ]);+ });++ it('keeps one journey, checks only on journey boards, and options inside a round', async () => {+ const { artboard } = await createJourney();+ const id = artboard.id;++ const second = await errorOf(+ service().update(id, 1, [{ group: { kind: 'journey', title: 'B' }, type: 'addGroup' }]),+ );+ expect(second.code).toBe('invalid');++ const check = await errorOf(+ service().update(id, 1, [+ { group: { kind: 'references', title: '参考' }, ref: 'r', type: 'addGroup' },+ {+ board: {+ expected: '看到',+ groupId: 'r',+ source: { kind: 'file', path: 'pages/empty.html' },+ title: 'x',+ x: 0,+ y: 900,+ },+ type: 'addBoard',+ },+ ]),+ );+ expect(check).toMatchObject({ code: 'invalid', data: { opIndex: 1 } });++ const loose = await errorOf(+ service().update(id, 1, [+ { group: { kind: 'options', title: '方案' }, ref: 'o', type: 'addGroup' },+ fileBoard('a', 'pages/empty.html', 0, 'o'),+ ]),+ );+ expect(loose).toMatchObject({ code: 'invalid', data: { opIndex: 1 } });++ const decision = await errorOf(+ service().update(id, 1, [+ {+ board: {+ groupId: artboard.content.groups[0].id,+ source: { kind: 'file', path: 'pages/empty.html' },+ title: '付费?',+ type: 'decision',+ x: 0,+ y: 0,+ },+ type: 'addBoard',+ },+ ]),+ );+ expect(decision.code).toBe('invalid');+ });+});++describe('ArtboardService rounds', () => {+ it('records the recommendation, lets the user pick, and submits the round', async () => {+ const { artboard } = await createJourney(optionOps());+ const [round] = artboard.content.rounds;+ const options = artboard.content.boards.filter((b) => b.roundId === round.id);+ expect(round).toMatchObject({ recommendedBoardId: options[0].id, status: 'open' });++ const chosen = await service().chooseBoard(artboard.id, round.id, options[1].id);+ expect(chosen.artboard.content.rounds[0].chosenBoardId).toBe(options[1].id);+ expect(chosen.artboard.revision).toBe(1);++ const submitted = await service().submitRound(artboard.id, round.id);+ expect(submitted.artboard.content.rounds[0]).toMatchObject({+ chosenBoardId: options[1].id,+ status: 'submitted',+ });++ const late = await errorOf(service().chooseBoard(artboard.id, round.id, options[0].id));+ expect(late.code).toBe('locked');+ const removal = await errorOf(+ service().update(artboard.id, 1, [{ id: options[1].id, type: 'removeBoard' }]),+ );+ expect(removal.code).toBe('locked');+ });++ it('keeps a draft pick from the agent-facing read until the round is submitted', async () => {+ const { artboard } = await createJourney(optionOps());+ const [round] = artboard.content.rounds;+ const options = artboard.content.boards.filter((b) => b.roundId === round.id);+ await service().chooseBoard(artboard.id, round.id, options[1].id);++ expect((await service().read(artboard.id)).artboard.content.rounds[0].chosenBoardId).toBeNull();+ expect((await service().get(artboard.id)).artboard.content.rounds[0].chosenBoardId).toBe(+ options[1].id,+ );++ await service().submitRound(artboard.id, round.id);+ expect((await service().read(artboard.id)).artboard.content.rounds[0].chosenBoardId).toBe(+ options[1].id,+ );+ });++ it('answers not_found for an id that is not a row id', async () => {+ const { artboard } = await createJourney(optionOps());+ const [round] = artboard.content.rounds;++ const pick = await errorOf(service().chooseBoard(artboard.id, round.id, 'login'));+ expect(pick.code).toBe('not_found');+ const submit = await errorOf(service().submitRound(artboard.id, 'round-1'));+ expect(submit.code).toBe('not_found');+ const reply = await errorOf(+ service().replyComment('thread-1', { clientId: 'c1', content: 'ok' }),+ );+ expect(reply.code).toBe('not_found');+ const resolve = await errorOf(service().resolveComment('thread-1'));+ expect(resolve.code).toBe('not_found');+ const comment = await errorOf(+ service().addComment(artboard.id, { boardId: 'login', clientId: 'c2', content: 'hi' }),+ );+ expect(comment.code).toBe('not_found');+ });++ it('submits all open rounds in one call and reports how many', async () => {+ const { artboard } = await createJourney([+ ...optionOps(),+ { ref: 'r2', round: { title: '命名' }, type: 'addRound' },+ { group: { kind: 'options', title: '命名方案' }, ref: 'o2', type: 'addGroup' },+ {+ board: {+ groupId: 'o2',+ recommended: true,+ roundId: 'r2',+ source: { kind: 'file', path: 'pages/empty.html' },+ title: 'N1',+ x: 0,+ y: 1400,+ },+ type: 'addBoard',+ },+ ]);++ const result = await service().submitOpenRounds(artboard.id);++ expect(result.submitted).toBe(2);+ expect(result.artboard.content.rounds.every((round) => round.status === 'submitted')).toBe(+ true,+ );+ expect((await service().submitOpenRounds(artboard.id)).submitted).toBe(0);+ });++ it('keeps one round per options group', async () => {+ const { artboard } = await createJourney(optionOps());+ const [round] = artboard.content.rounds;+ const group = artboard.content.groups.find((g) => g.kind === 'options')!;+ const option = (ref: string, groupId: string, roundId: string, y: number): ArtboardOp => ({+ board: {+ groupId,+ roundId,+ source: { kind: 'file', path: 'pages/empty.html' },+ title: ref,+ x: 0,+ y,+ },+ type: 'addBoard',+ });++ const split = await errorOf(+ service().update(artboard.id, artboard.revision, [+ { group: { kind: 'options', title: '另一组' }, ref: 'o2', type: 'addGroup' },+ option('C', 'o2', round.id, 1400),+ ]),+ );+ expect(split.code).toBe('invalid');++ const mixed = await errorOf(+ service().update(artboard.id, artboard.revision, [+ { ref: 'r2', round: { title: '命名' }, type: 'addRound' },+ option('D', group.id, 'r2', 1400),+ ]),+ );+ expect(mixed.code).toBe('invalid');+ });++ it('refuses a round of another board', async () => {+ const { artboard } = await createJourney(optionOps());+ const other = await service().create({ files: baseFiles, title: '另一块' }, context);++ const error = await errorOf(+ service().submitRound(other.artboard.id, artboard.content.rounds[0].id),+ );+ expect(error.code).toBe('not_found');+ });+});++describe('ArtboardService comments', () => {+ it('threads a user comment with replies and resolves it', async () => {+ const { artboard } = await createJourney();+ const [board] = artboard.content.boards;++ const thread = await service().addComment(artboard.id, {+ boardId: board.id,+ clientId: 'c1',+ content: '这里要不要空状态?',+ });+ await service().replyComment(thread.id, { clientId: 'c2', content: '要' });++ const [listed] = await service().listComments(artboard.id);+ expect(listed).toMatchObject({+ authorUserId: userId,+ boardId: board.id,+ pageId: board.pageId,+ replies: [{ content: '要' }],+ resolvedAt: null,+ });++ const resolved = await service().resolveComment(thread.id);+ expect(resolved.resolvedAt).toBeInstanceOf(Date);+ expect((await service().reopenComment(thread.id)).resolvedAt).toBeNull();+ expect((await service().read(artboard.id)).artboard.revision).toBe(1);+ });+});++describe('ArtboardService agent questions', () => {+ const agentId = 'agt_artboard_service';+ const asAgent = () =>+ new ArtboardService(db, userId, undefined, { context: { agentId }, fileStore, sources });++ beforeEach(async () => {+ await db.insert(agents).values({ id: agentId, userId });+ });++ it('opens a question thread that shows on the board until it is resolved', async () => {+ const { artboard } = await createJourney();+ const [board] = artboard.content.boards;++ const question = await asAgent().askQuestion(artboard.id, {+ boardId: board.id,+ content: '这一步能跳过吗?',+ });++ expect((await service().read(artboard.id)).artboard.content.questions).toEqual([+ {+ answered: false,+ boardId: board.id,+ content: '这一步能跳过吗?',+ groupId: null,+ id: question.id,+ pageId: board.pageId,+ },+ ]);+ await service().replyComment(question.id, { clientId: 'c1', content: '能' });+ expect((await service().read(artboard.id)).artboard.content.questions[0].answered).toBe(true);+ await service().resolveComment(question.id);+ expect((await service().read(artboard.id)).artboard.content.questions).toEqual([]);+ });++ it('refuses a question outside an agent run', async () => {+ const { artboard } = await createJourney();+ expect(() => service().askQuestion(artboard.id, { content: '?' })).toThrow(+ ArtboardServiceError,+ );+ });++ it('hands unresolved threads to the agent and marks them delivered', async () => {+ const { artboard } = await createJourney();+ const thread = await service().addComment(artboard.id, { clientId: 'c1', content: '太挤了' });+ await asAgent().replyComment(thread.id, { content: '已拉开间距' });++ const taken = await asAgent().takeUndeliveredComments(artboard.id);+ expect(taken).toMatchObject([+ { content: '太挤了', replies: [{ authorAgentId: agentId, content: '已拉开间距' }] },+ ]);+ const rows = await db+ .select({ deliveredAt: artboardComments.deliveredAt })+ .from(artboardComments)+ .where(eq(artboardComments.artboardId, artboard.id));+ expect(rows.every((row) => row.deliveredAt instanceof Date)).toBe(true);+ });+});++describe('ArtboardService.finalize', () => {+ const checks = (refs: string[]): ArtboardOp[] =>+ refs.map((boardId) => ({ boardId, expected: `看到 ${boardId}`, type: 'setCheck' }));++ it('lists what is missing before it will finalize', async () => {+ const { artboard } = await createJourney(optionOps());+ const [first, second] = artboard.content.boards;++ const error = await errorOf(service().finalize(artboard.id, artboard.revision));+ expect(error.code).toBe('finalize_blocked');+ expect(error.data.issues).toEqual([+ { boardId: first.id, code: 'missing_check' },+ { boardId: second.id, code: 'missing_check' },+ { code: 'open_round', roundId: artboard.content.rounds[0].id },+ ]);+ });++ it('publishes the journey as an acceptance flow once, and locks it', async () => {+ const created = await createJourney(checks(['empty', 'ingest']));++ const result = await service().finalize(created.artboard.id, created.artboard.revision);+ expect(result.artboard).toMatchObject({+ acceptanceId: result.acceptanceId,+ phase: 'finalized',+ revision: 2,+ });+ const [entry, next] = result.artboard.content.boards;+ const [edge] = result.artboard.content.edges;+ const [flow] = await db+ .select()+ .from(acceptanceFlows)+ .where(eq(acceptanceFlows.acceptanceId, result.acceptanceId));+ const nodes = await db+ .select()+ .from(acceptanceFlowNodes)+ .where(eq(acceptanceFlowNodes.flowId, flow.id));+ expect(nodes.map((node) => node.id).sort()).toEqual([entry.flowNodeId, next.flowNodeId].sort());+ const flowEdges = await db+ .select()+ .from(acceptanceFlowEdges)+ .where(eq(acceptanceFlowEdges.flowId, flow.id));+ expect(flowEdges).toMatchObject([{ id: edge.flowEdgeId, trigger: '点接入' }]);++ const again = await service().finalize(created.artboard.id, 1);+ expect(again.acceptanceId).toBe(result.acceptanceId);+ expect(again.artboard.revision).toBe(2);++ const locked = await errorOf(+ service().update(created.artboard.id, 2, [+ { id: entry.id, patch: { title: '改名' }, type: 'updateBoard' },+ ]),+ );+ expect(locked.code).toBe('locked');+ const moved = await service().update(created.artboard.id, 2, [+ { id: entry.id, patch: { x: -40 }, type: 'updateBoard' },+ ]);+ expect(moved.artboard.revision).toBe(3);+ });++ it('keeps the files of a finalized journey, while other files stay writable', async () => {+ const created = await createJourney(checks(['empty', 'ingest']));+ const { artboard } = await service().finalize(created.artboard.id, created.artboard.revision);++ const edit = await errorOf(+ service().writeFiles(artboard.id, {+ edits: [{ newText: '改了', oldText: '空项目', path: 'pages/empty.html' }],+ }),+ );+ const viaUpdate = await errorOf(+ service().update(artboard.id, artboard.revision, [], {+ writes: [{ content: '<p>new</p>', path: 'pages/ingest.html' }],+ }),+ );+ expect(edit.code).toBe('locked');+ expect(edit.message).toContain('pages/empty.html');+ expect(viaUpdate.code).toBe('locked');++ const notes = await service().writeFiles(artboard.id, {+ writes: [{ content: '<p>notes</p>', path: 'pages/notes.html' }],+ });+ expect(notes.files).toEqual(['pages/notes.html']);+ });++ it('collapses a decision board into conditioned edges between the screens around it', async () => {+ const created = await service().create(+ {+ files: baseFiles,+ ops: [+ { group: { kind: 'journey', title: '付费' }, ref: 'j', type: 'addGroup' },+ fileBoard('cart', 'pages/empty.html', 0),+ {+ board: { groupId: 'j', title: '已付费?', type: 'decision', x: 720, y: 0 },+ ref: 'paid',+ type: 'addBoard',+ },+ fileBoard('done', 'pages/ingest.html', 1440),+ { edge: { from: 'cart', label: '点结算', to: 'paid' }, type: 'addEdge' },+ { edge: { condition: '已付费', from: 'paid', label: '是', to: 'done' }, type: 'addEdge' },+ ...checks(['cart', 'done']),+ ],+ title: '付费',+ },+ context,+ );++ const result = await service().finalize(created.artboard.id, 1);+ const [flow] = await db+ .select()+ .from(acceptanceFlows)+ .where(eq(acceptanceFlows.acceptanceId, result.acceptanceId));+ const nodes = await db+ .select()+ .from(acceptanceFlowNodes)+ .where(eq(acceptanceFlowNodes.flowId, flow.id));+ const flowEdges = await db+ .select()+ .from(acceptanceFlowEdges)+ .where(eq(acceptanceFlowEdges.flowId, flow.id));++ const boards = result.artboard.content.boards;+ expect(nodes).toHaveLength(2);+ expect(boards.find((b) => b.type === 'decision')?.flowNodeId).toBeNull();+ expect(flowEdges).toMatchObject([+ {+ condition: '已付费',+ sourceNodeId: boards[0].flowNodeId,+ targetNodeId: boards[2].flowNodeId,+ trigger: '点结算',+ },+ ]);+ });+});diff --git a/apps/server/src/services/artboard/comments.ts b/apps/server/src/services/artboard/comments.tsnew file mode 100644index 00000000000..2dad886e17e--- /dev/null+++ b/apps/server/src/services/artboard/comments.ts@@ -0,0 +1,179 @@+import { randomUUID } from 'node:crypto';++import type {+ ArtboardCommentAnchor,+ ArtboardCommentThreadView,+ ArtboardCommentView,+} from '@lobechat/types';++import type {+ ArtboardCommentModel,+ ArtboardCommentThread,+} from '@/database/models/artboard/comment';+import type {+ ArtboardStructure,+ ArtboardStructureModel,+} from '@/database/models/artboard/structure';++import { ArtboardServiceError, guardArtboard, requireRowId, requireText } from './errors';+import { sourceHashKey } from './opInputs';+import { isThreadUnread, toCommentThreadView, toCommentView } from './view';++export interface ArtboardCommentInput {+ anchor?: ArtboardCommentAnchor | null;+ boardId?: string | null;+ clientId: string;+ content: string;+ groupId?: string | null;+ pageId?: string | null;+}++export interface ArtboardQuestionInput {+ boardId?: string | null;+ content: string;+ groupId?: string | null;+ pageId?: string | null;+}++interface CommentDeps {+ agentId: string | null;+ comments: ArtboardCommentModel;+ fileHashes: (id: string) => Promise<ReadonlyMap<string, string>>;+ requireArtboard: (id: string) => Promise<unknown>;+ structure: ArtboardStructureModel;+}++type BoardSnapshot = ArtboardStructure & { hashes: ReadonlyMap<string, string> };++const inside = (value: number) => value >= 0 && value <= 1;++export class ArtboardCommentService {+ constructor(private deps: CommentDeps) {}++ private async structureOf(id: string): Promise<BoardSnapshot> {+ await this.deps.requireArtboard(id);+ const [structure, hashes] = await Promise.all([+ this.deps.structure.getStructure(id),+ this.deps.fileHashes(id),+ ]);+ if (!structure) throw new ArtboardServiceError('not_found', `No artboard with id "${id}".`);+ return { ...structure, hashes };+ }++ private view(structure: BoardSnapshot) {+ const shown = new Map(structure.boards.map((b) => [b.id, sourceHashKey(b, structure.hashes)]));+ return (thread: ArtboardCommentThread): ArtboardCommentThreadView => {+ const recorded = thread.root.metadata?.sourceHash;+ const { boardId } = thread.root;+ const stale = !!recorded && !!boardId && shown.get(boardId) !== recorded;+ return toCommentThreadView(thread, stale);+ };+ }++ private awaitingSubmit(structure: ArtboardStructure) {+ const open = new Set(structure.rounds.filter((r) => r.status === 'open').map((r) => r.id));+ const quiet = new Set(+ structure.boards.filter((b) => b.roundId && open.has(b.roundId)).map((b) => b.id),+ );+ return (thread: ArtboardCommentThread) =>+ !!thread.root.boardId && quiet.has(thread.root.boardId);+ }++ private async deliverable(id: string) {+ const structure = await this.structureOf(id);+ const held = this.awaitingSubmit(structure);+ const threads = await this.deps.comments.listThreads(id);+ return {+ structure,+ threads: threads.filter(+ (thread) => !held(thread) && (!thread.root.resolvedAt || isThreadUnread(thread)),+ ),+ };+ }++ async list(id: string): Promise<ArtboardCommentThreadView[]> {+ const structure = await this.structureOf(id);+ return (await this.deps.comments.listThreads(id)).map(this.view(structure));+ }++ async countUndelivered(id: string): Promise<number> {+ const { threads } = await this.deliverable(id);+ return threads.filter(isThreadUnread).length;+ }++ async takeUndelivered(id: string): Promise<ArtboardCommentThreadView[]> {+ const { structure, threads } = await this.deliverable(id);+ const pending = threads.flatMap(({ replies, root }) =>+ [root, ...replies].filter((comment) => !comment.deliveredAt).map((comment) => comment.id),+ );+ await this.deps.comments.markDelivered(pending, new Date());+ return threads.map(this.view(structure));+ }++ async open(+ id: string,+ input: ArtboardCommentInput,+ authorAgentId: string | null,+ ): Promise<ArtboardCommentThreadView> {+ requireText(input.content);+ if (input.boardId) requireRowId(input.boardId, 'board');+ const structure = await this.structureOf(id);+ const board = structure.boards.find((item) => item.id === input.boardId);+ const group = structure.groups.find((item) => item.id === input.groupId);+ const { anchor } = input;+ if (input.boardId && anchor?.type === 'canvas' && !(inside(anchor.x) && inside(anchor.y)))+ throw new ArtboardServiceError(+ 'invalid',+ 'A comment on a board is anchored by fractions (0–1) of the board’s width and height.',+ );++ const root = await guardArtboard(() =>+ this.deps.comments.create(id, {+ anchor: anchor ?? null,+ authorAgentId,+ boardId: input.boardId ?? null,+ clientId: input.clientId,+ content: input.content,+ groupId: input.groupId ?? null,+ metadata: {+ anchorSpace: board ? 'board' : group ? 'group' : 'page',+ ...(board && sourceHashKey(board, structure.hashes)+ ? { sourceHash: sourceHashKey(board, structure.hashes) }+ : {}),+ },+ pageId: input.pageId ?? board?.pageId ?? group?.pageId ?? structure.pages[0].id,+ }),+ );+ return toCommentThreadView({ replies: [], root }, false);+ }++ ask(id: string, input: ArtboardQuestionInput) {+ if (!this.deps.agentId)+ throw new ArtboardServiceError('invalid', 'Only an agent run can open a question thread.');+ return this.open(id, { ...input, clientId: randomUUID() }, this.deps.agentId);+ }++ async reply(+ commentId: string,+ input: { clientId?: string; content: string },+ ): Promise<ArtboardCommentView> {+ requireRowId(commentId, 'comment');+ requireText(input.content);+ const reply = await guardArtboard(() =>+ this.deps.comments.reply(commentId, {+ authorAgentId: input.clientId ? null : this.deps.agentId,+ clientId: input.clientId ?? randomUUID(),+ content: input.content,+ }),+ );+ return toCommentView(reply);+ }++ async settle(commentId: string, resolved: boolean) {+ requireRowId(commentId, 'comment');+ const root = await guardArtboard(() =>+ resolved ? this.deps.comments.resolve(commentId) : this.deps.comments.reopen(commentId),+ );+ return toCommentThreadView({ replies: [], root }, false);+ }+}diff --git a/apps/server/src/services/artboard/errors.ts b/apps/server/src/services/artboard/errors.tsnew file mode 100644index 00000000000..283aa80df0e--- /dev/null+++ b/apps/server/src/services/artboard/errors.ts@@ -0,0 +1,86 @@+import type { ArtboardFinalizeIssue } from '@lobechat/types';++import { ArtboardRevisionConflictError } from '@/database/models/artboard';+import { ArtboardCommentError } from '@/database/models/artboard/comment';+import { ArtboardStructureError } from '@/database/models/artboard/structure';++export type ArtboardServiceErrorCode =+ | 'conflict'+ | 'exists'+ | 'finalize_blocked'+ | 'invalid'+ | 'locked'+ | 'no_project'+ | 'not_found'+ | 'source_denied';++export interface ArtboardServiceErrorData {+ artboardId?: string;+ issues?: ArtboardFinalizeIssue[];+ opIndex?: number;+}++export class ArtboardServiceError extends Error {+ constructor(+ public code: ArtboardServiceErrorCode,+ message: string,+ public data: ArtboardServiceErrorData = {},+ ) {+ super(message);+ }+}++export const failArtboard = (code: ArtboardServiceErrorCode, message: string): never => {+ throw new ArtboardServiceError(code, message);+};++export const artboardConflict = () =>+ new ArtboardServiceError(+ 'conflict',+ 'The board changed since you read it. Call readArtboard for the latest revision, then retry.',+ );++export const toArtboardServiceError = (error: unknown, opIndex?: number): unknown => {+ const data = opIndex === undefined ? {} : { opIndex };+ if (error instanceof ArtboardServiceError)+ return opIndex === undefined || error.data.opIndex !== undefined+ ? error+ : new ArtboardServiceError(error.code, error.message, { ...error.data, opIndex });+ if (error instanceof ArtboardRevisionConflictError) return artboardConflict();+ if (error instanceof ArtboardStructureError) {+ if (error.code === 'rounds_changed')+ return new ArtboardServiceError(+ 'conflict',+ 'The questions on this artboard changed. Check them and submit again.',+ data,+ );+ const code =+ error.code === 'not_found'+ ? 'not_found'+ : error.code === 'round_submitted'+ ? 'locked'+ : 'invalid';+ return new ArtboardServiceError(code, error.message, data);+ }+ if (error instanceof ArtboardCommentError)+ return new ArtboardServiceError(error.code, error.message, data);+ return error;+};++export const guardArtboard = async <T>(action: () => Promise<T>): Promise<T> => {+ try {+ return await action();+ } catch (error) {+ throw toArtboardServiceError(error);+ }+};++const ROW_UUID = /^[\da-f]{8}(?:-[\da-f]{4}){3}-[\da-f]{12}$/i;++export const requireRowId = (id: string, what: string) => {+ if (!ROW_UUID.test(id)) throw new ArtboardServiceError('not_found', `No ${what} ${id}.`);+};++export const requireText = (content: string) => {+ if (!content.trim()) throw new ArtboardServiceError('invalid', 'A comment needs some text.');+};diff --git a/apps/server/src/services/artboard/fileAccess.ts b/apps/server/src/services/artboard/fileAccess.tsnew file mode 100644index 00000000000..9485901231c--- /dev/null+++ b/apps/server/src/services/artboard/fileAccess.ts@@ -0,0 +1,103 @@+import { createHmac, timingSafeEqual } from 'node:crypto';++import { artboardFileContentType, normalizeArtboardFilePath } from '@lobechat/types';+import { eq } from 'drizzle-orm';++import { artboards } from '@/database/schemas';+import type { LobeChatDatabase } from '@/database/type';++import { type ArtboardBlobStore, artboardFileKey } from './files';++const DOMAIN = 'lobehub:artboard-file:v1';++const TOKEN_WINDOW_MS = 6 * 60 * 60 * 1000;++// `sandbox` makes the page an opaque origin even when the URL is opened in a tab of its own,+// so board HTML can never read the app's cookies or storage on this origin.+export const ARTBOARD_FILE_CSP = [+ 'sandbox allow-scripts allow-popups allow-forms',+ "default-src * data: blob: 'unsafe-inline' 'unsafe-eval'",+ "connect-src 'none'",+].join('; ');++const secret = () => process.env.KEY_VAULTS_SECRET?.trim() || undefined;++const sign = (key: string, payload: string) =>+ createHmac('sha256', key).update(`${DOMAIN}:${payload}`).digest('base64url');++export const signArtboardFileToken = (artboardId: string, now = Date.now()) => {+ const key = secret();+ if (!key) return;+ const payload = Buffer.from(+ JSON.stringify({ a: artboardId, e: (Math.floor(now / TOKEN_WINDOW_MS) + 2) * TOKEN_WINDOW_MS }),+ ).toString('base64url');+ return `${payload}.${sign(key, payload)}`;+};++export const verifyArtboardFileToken = (token: string, now = Date.now()) => {+ const key = secret();+ const [payload, signature] = token.split('.');+ if (!key || !payload || !signature) return;+ const expected = Buffer.from(sign(key, payload));+ const given = Buffer.from(signature);+ if (expected.length !== given.length || !timingSafeEqual(expected, given)) return;+ try {+ const { a, e } = JSON.parse(Buffer.from(payload, 'base64url').toString('utf8'));+ return typeof a === 'string' && typeof e === 'number' && e > now ? a : undefined;+ } catch {+ return;+ }+};++export const artboardFileBasePath = (artboardId: string) => {+ const token = signArtboardFileToken(artboardId);+ return token ? `/artboard-files/${token}/` : undefined;+};++const baseHeaders = {+ 'Content-Security-Policy': ARTBOARD_FILE_CSP,+ 'Referrer-Policy': 'no-referrer',+ 'X-Content-Type-Options': 'nosniff',+};++const notFound = () => new Response('Not found', { headers: baseHeaders, status: 404 });++interface ServeArtboardFileParams {+ db: LobeChatDatabase;+ path: string;+ storeFor: (owner: { userId: string; workspaceId: string | null }) => ArtboardBlobStore;+ token: string;+}++export const serveArtboardFile = async ({+ db,+ path,+ storeFor,+ token,+}: ServeArtboardFileParams): Promise<Response> => {+ const artboardId = verifyArtboardFileToken(token);+ const normalized = normalizeArtboardFilePath(path);+ if (!artboardId || !normalized) return notFound();++ // The token is the capability; the owner only picks whose storage holds the folder.+ const [owner] = await db+ .select({ userId: artboards.userId, workspaceId: artboards.workspaceId })+ .from(artboards)+ .where(eq(artboards.id, artboardId))+ .limit(1);+ if (!owner) return notFound();++ const bytes = await storeFor(owner)+ .read(artboardFileKey(artboardId, normalized))+ .catch(() => undefined);+ if (!bytes) return notFound();++ // The board URL carries ?v=<ETag>, so a changed file is a new URL; this one must not be reused.+ const headers = {+ ...baseHeaders,+ 'Cache-Control': 'private, no-cache',+ 'Content-Type': artboardFileContentType(normalized)!,+ };+ // Object-store reads are backed by a plain ArrayBuffer, never a SharedArrayBuffer.+ return new Response(bytes as Uint8Array<ArrayBuffer>, { headers, status: 200 });+};diff --git a/apps/server/src/services/artboard/files.ts b/apps/server/src/services/artboard/files.tsnew file mode 100644index 00000000000..defe3d121b3--- /dev/null+++ b/apps/server/src/services/artboard/files.ts@@ -0,0 +1,361 @@+import {+ ARTBOARD_FILE_LIMITS,+ artboardFileContentType,+ isArtboardImagePath,+ isArtboardTextPath,+ normalizeArtboardFilePath,+} from '@lobechat/types';+import pMap from 'p-map';++import type { FileService } from '@/server/services/file';++import { ArtboardServiceError } from './errors';++export interface ArtboardBlobUpload {+ headers?: Record<string, string>;+ url: string;+}++export interface ArtboardStoredObject {+ /** Object ETag without quotes; changes whenever the content does. */+ etag: string;+ key: string;+ size: number;+}++export interface ArtboardBlobStore {+ delete: (keys: string[]) => Promise<void>;+ list: (prefix: string) => Promise<ArtboardStoredObject[]>;+ /** A signed PUT the client uploads one file to, for files too large for a request body. */+ presignWrite: (key: string) => Promise<ArtboardBlobUpload>;+ read: (key: string) => Promise<Uint8Array>;+ write: (key: string, bytes: Uint8Array, contentType: string) => Promise<void>;+}++export const createFileServiceArtboardBlobStore = (+ createFileService: () => FileService,+): ArtboardBlobStore => {+ let fileService: FileService | undefined;+ const service = () => (fileService ??= createFileService());+ return {+ delete: async (keys) => {+ await service().deleteFiles(keys);+ },+ list: (prefix) => service().listFileObjects(prefix),+ // Private: board files are only ever served through the token route.+ presignWrite: (key) => service().createPreSignedUpload(key, { private: true }),+ read: (key) => service().getFileByteArray(key),+ write: async (key, bytes, contentType) => {+ await service().uploadBuffer(key, Buffer.from(bytes), contentType);+ },+ };+};++export interface ArtboardImageBytes {+ bytes: Uint8Array;+ contentType: string;+}++/** A Canvas to copy in; without `version`, its latest one. */+export interface ArtboardImportSource {+ canvasId: string;+ version?: number;+}++type Only<K extends string> = {+ [P in Exclude<'base64' | 'content' | 'fileRef' | 'fromCanvas' | 'uploaded', K>]?: never;+};++export type ArtboardFileWrite =+ | (Only<'content'> & { content: string; path: string })+ | (Only<'fileRef'> & { fileRef: string; path: string })+ | (Only<'base64'> & { base64: string; path: string })+ /** Already PUT to the URL from prepareUploads; the write only records the change. */+ | (Only<'uploaded'> & { path: string; uploaded: true })+ /** A copy of a Canvas page: it does not follow the Canvas afterwards. */+ | (Only<'fromCanvas'> & { fromCanvas: ArtboardImportSource; path: string });++export interface ArtboardFileEdit {+ newText: string;+ oldText: string;+ path: string;+}++export interface ArtboardFileChanges {+ deletes?: string[];+ edits?: ArtboardFileEdit[];+ writes?: ArtboardFileWrite[];+}++export interface ArtboardFileEntry {+ contentType: string;+ /** The object's ETag. */+ hash: string;+ path: string;+ size: number;+}++export interface ArtboardFileContent {+ bytes: Uint8Array;+ content?: string;+ contentType: string;+ path: string;+}++export interface ArtboardFileUploadRequest {+ path: string;+ size: number;+}++export interface ArtboardImportedPage {+ /** Files the entry loads, by path relative to the entry's directory. */+ assets: { bytes: Uint8Array; path: string }[];+ entry: Uint8Array;+}++interface ArtboardFileServiceDeps {+ resolveImage: (fileRef: string) => Promise<ArtboardImageBytes | undefined>;+ /**+ * A copy of a Canvas or Work version: its HTML entry plus the files it loads by relative path.+ * Undefined when it does not exist, has no HTML, or the user cannot read it.+ */+ resolveImport: (source: ArtboardImportSource) => Promise<ArtboardImportedPage | undefined>;+ store: ArtboardBlobStore;+}++/** What a set of changes will write and delete, checked against the limits but not yet stored. */+export interface ArtboardFilePlan {+ deletes: string[];+ /** Paths already uploaded through a signed URL. */+ uploaded: string[];+ writes: Map<string, Uint8Array>;+}++const encoder = new TextEncoder();+const decoder = new TextDecoder();++const invalid = (message: string): never => {+ throw new ArtboardServiceError('invalid', message);+};++const artboardPrefix = (artboardId: string) => `artboards/${artboardId}/`;++export const artboardFilesPrefix = (artboardId: string) => `${artboardPrefix(artboardId)}files/`;++export const artboardFileKey = (artboardId: string, path: string) =>+ `${artboardFilesPrefix(artboardId)}${path}`;++const requirePath = (path: string) =>+ normalizeArtboardFilePath(path) ??+ invalid(+ `"${path}" is not a valid artboard file path: use a relative path (no "..") of letters, digits and -_.@ ending in a known extension (html, css, js, json, svg, png, jpg, webp, gif, woff2…).`,+ );++const sizeLimitOf = (path: string) =>+ isArtboardImagePath(path)+ ? ARTBOARD_FILE_LIMITS.maxImageBytes+ : ARTBOARD_FILE_LIMITS.maxTextFileBytes;++const assertSize = (path: string, size: number) => {+ if (size > sizeLimitOf(path))+ invalid(`"${path}" is ${size} bytes; the limit is ${sizeLimitOf(path)}.`);+};++const countOccurrences = (text: string, part: string) => {+ if (!part) return 0;+ let count = 0;+ for (+ let index = text.indexOf(part);+ index !== -1;+ index = text.indexOf(part, index + part.length)+ )+ count += 1;+ return count;+};++const BLOB_CONCURRENCY = 6;++/**+ * An artboard's files are a plain folder in object storage, keyed by path. Nothing ties them to+ * the boards: a board may point at a path that is not written yet, and a file may be deleted while+ * a board still shows it.+ */+export class ArtboardFileService {+ constructor(private deps: ArtboardFileServiceDeps) {}++ async list(artboardId: string): Promise<ArtboardFileEntry[]> {+ const prefix = artboardFilesPrefix(artboardId);+ const objects = await this.deps.store.list(prefix);+ return objects.flatMap(({ etag, key, size }) => {+ const path = normalizeArtboardFilePath(key.slice(prefix.length));+ const contentType = path && artboardFileContentType(path);+ return path && contentType ? [{ contentType, hash: etag, path, size }] : [];+ });+ }++ async read(artboardId: string, path: string): Promise<ArtboardFileContent> {+ const normalized = requirePath(path);+ const bytes = await this.deps.store.read(artboardFileKey(artboardId, normalized)).catch(() => {+ throw new ArtboardServiceError(+ 'not_found',+ `Artboard "${artboardId}" has no file "${normalized}".`,+ );+ });+ return {+ bytes,+ ...(isArtboardTextPath(normalized) ? { content: decoder.decode(bytes) } : {}),+ contentType: artboardFileContentType(normalized)!,+ path: normalized,+ };+ }++ /** Validate the changes and compute every file they write. Stores nothing. */+ async prepare(artboardId: string, changes: ArtboardFileChanges): Promise<ArtboardFilePlan> {+ const existing = new Map((await this.list(artboardId)).map((file) => [file.path, file.size]));+ const sizes = new Map(existing);+ const writes = new Map<string, Uint8Array>();+ const uploaded: string[] = [];+ const deletes: string[] = [];++ const put = (path: string, bytes: Uint8Array) => {+ assertSize(path, bytes.byteLength);+ writes.set(path, bytes);+ sizes.set(path, bytes.byteLength);+ };++ for (const write of changes.writes ?? []) {+ const path = requirePath(write.path);+ if (write.uploaded) {+ if (!existing.has(path))+ invalid(+ `"${path}" was not uploaded: get a URL from prepareFileUploads and PUT the file first.`,+ );+ assertSize(path, existing.get(path)!);+ uploaded.push(path);+ continue;+ }+ if (write.fileRef !== undefined) {+ if (!isArtboardImagePath(path))+ invalid(`"${path}" takes text content; only image paths can be written from a fileRef.`);+ const image = await this.deps.resolveImage(write.fileRef);+ if (!image)+ throw new ArtboardServiceError(+ 'source_denied',+ `fileRef "${write.fileRef}" does not match an image you can access. Use a file id from <file id> or an image ref from <image ref> in this conversation.`,+ );+ put(path, image.bytes);+ continue;+ }+ if (write.fromCanvas !== undefined) {+ const page = await this.deps.resolveImport(write.fromCanvas);+ if (!page)+ throw new ArtboardServiceError(+ 'source_denied',+ `Canvas "${write.fromCanvas.canvasId}" was not found, cannot be read, or this server has no Canvas runtime to bundle it with.`,+ );+ put(path, page.entry);+ // Assets sit next to the page so its relative references keep working.+ const dir = path.includes('/') ? path.slice(0, path.lastIndexOf('/') + 1) : '';+ for (const asset of page.assets) put(requirePath(`${dir}${asset.path}`), asset.bytes);+ continue;+ }+ if (write.base64 !== undefined) {+ put(path, new Uint8Array(Buffer.from(write.base64, 'base64')));+ continue;+ }+ if (!isArtboardTextPath(path))+ invalid(`"${path}" is binary; write it from a fileRef or base64 instead of text content.`);+ put(path, encoder.encode(write.content ?? ''));+ }++ for (const change of changes.edits ?? []) {+ const path = requirePath(change.path);+ if (!isArtboardTextPath(path)) invalid(`"${path}" is not a text file and cannot be edited.`);+ const pending = writes.get(path);+ if (!pending && !existing.has(path)) invalid(`Artboard has no file "${path}" to edit.`);+ const text = decoder.decode(+ pending ?? (await this.deps.store.read(artboardFileKey(artboardId, path))),+ );+ const count = countOccurrences(text, change.oldText);+ if (count !== 1)+ invalid(+ count === 0+ ? `The text to replace was not found in "${path}". Read the file and copy the exact text.`+ : `The text to replace appears ${count} times in "${path}"; include more surrounding text so it appears once.`,+ );+ put(path, encoder.encode(text.replace(change.oldText, () => change.newText)));+ }++ for (const raw of changes.deletes ?? []) {+ const path = requirePath(raw);+ writes.delete(path);+ sizes.delete(path);+ deletes.push(path);+ }++ if (sizes.size > ARTBOARD_FILE_LIMITS.maxFiles)+ invalid(+ `An artboard holds at most ${ARTBOARD_FILE_LIMITS.maxFiles} files; this would make ${sizes.size}.`,+ );+ const total = [...sizes.values()].reduce((sum, size) => sum + size, 0);+ if (total > ARTBOARD_FILE_LIMITS.maxTotalBytes)+ invalid(+ `The artboard's files would total ${total} bytes; the limit is ${ARTBOARD_FILE_LIMITS.maxTotalBytes}.`,+ );++ return { deletes, uploaded, writes };+ }++ /** Every path a plan changes or deletes. */+ static touched = (plan: ArtboardFilePlan) => [+ ...plan.writes.keys(),+ ...plan.uploaded,+ ...plan.deletes,+ ];++ async apply(artboardId: string, plan: ArtboardFilePlan): Promise<string[]> {+ await pMap(+ [...plan.writes],+ ([path, bytes]) =>+ this.deps.store.write(+ artboardFileKey(artboardId, path),+ bytes,+ artboardFileContentType(path)!,+ ),+ { concurrency: BLOB_CONCURRENCY },+ );+ if (plan.deletes.length)+ await this.deps.store.delete(plan.deletes.map((path) => artboardFileKey(artboardId, path)));+ return [...plan.writes.keys(), ...plan.uploaded];+ }++ async applyChanges(artboardId: string, changes: ArtboardFileChanges) {+ return this.apply(artboardId, await this.prepare(artboardId, changes));+ }++ /** Signed PUT URLs, one per path, for files too large to send in a request body. */+ async prepareUploads(+ artboardId: string,+ requests: ArtboardFileUploadRequest[],+ ): Promise<{ uploads: (ArtboardBlobUpload & { path: string })[] }> {+ const paths = requests.map((request) => {+ const path = requirePath(request.path);+ assertSize(path, request.size);+ return path;+ });+ const uploads = await pMap(+ paths,+ async (path) => ({+ path,+ ...(await this.deps.store.presignWrite(artboardFileKey(artboardId, path))),+ }),+ { concurrency: BLOB_CONCURRENCY },+ );+ return { uploads };+ }++ async removeAll(artboardId: string) {+ const objects = await this.deps.store.list(artboardPrefix(artboardId));+ if (objects.length) await this.deps.store.delete(objects.map((object) => object.key));+ }+}diff --git a/apps/server/src/services/artboard/finalize.ts b/apps/server/src/services/artboard/finalize.tsnew file mode 100644index 00000000000..e8f01a861a0--- /dev/null+++ b/apps/server/src/services/artboard/finalize.ts@@ -0,0 +1,82 @@+import {+ type AcceptanceFlowDefinition,+ type AcceptanceFlowEdgeInput,+ type ArtboardContent,+ type ArtboardEdgeView,+ artboardJourneyOf,+} from '@lobechat/types';++export interface JourneyFlow {+ boardNodeIds: Record<string, string>;+ definition: AcceptanceFlowDefinition;+ edgeFlowIds: Record<string, string>;+}++const CONDITION_SEPARATOR = ' · ';++export const buildJourneyFlow = (content: ArtboardContent, newId: () => string): JourneyFlow => {+ const { boards = [], edges = [], group } = artboardJourneyOf(content);+ if (!group) throw new Error('The board has no single journey group');++ const screens = boards.filter((board) => board.type !== 'decision');+ const boardNodeIds = Object.fromEntries(+ screens.map((board) => [board.id, board.flowNodeId ?? newId()]),+ );+ const targets = new Set(edges.map((edge) => edge.to));+ const entry = screens.find((board) => !targets.has(board.id));+ if (!entry) throw new Error('The journey has no entry board');++ const titles = Object.fromEntries(boards.map((board) => [board.id, board.title]));+ const edgeFlowIds: Record<string, string> = {};+ const flowEdges: AcceptanceFlowEdgeInput[] = [];++ const emit = (first: ArtboardEdgeView, last: ArtboardEdgeView, conditions: string[]) => {+ const carrier = edgeFlowIds[last.id] ? undefined : last;+ const id = carrier?.flowEdgeId ?? newId();+ if (carrier) edgeFlowIds[carrier.id] = id;+ const condition = conditions.filter(Boolean).join(CONDITION_SEPARATOR);+ flowEdges.push({+ ...(condition ? { condition } : {}),+ id,+ required: true,+ sourceNodeId: boardNodeIds[first.from],+ targetNodeId: boardNodeIds[last.to],+ trigger: first.label || titles[first.to] || titles[last.to] || '',+ });+ };++ const walk = (+ first: ArtboardEdgeView,+ last: ArtboardEdgeView,+ conditions: string[],+ seen: Set<string>,+ ) => {+ if (boardNodeIds[last.to]) return emit(first, last, conditions);+ if (seen.has(last.to)) return;+ const through = new Set(seen).add(last.to);+ for (const out of edges)+ if (out.from === last.to)+ walk(first, out, [...conditions, out.condition || out.label], through);+ };++ for (const edge of edges)+ if (boardNodeIds[edge.from]) walk(edge, edge, [edge.condition ?? ''], new Set());++ return {+ boardNodeIds,+ definition: {+ edges: flowEdges,+ entryNodeId: boardNodeIds[entry.id],+ nodes: screens.map((board) => ({+ check: {+ definition: { expected: board.expected ?? '' },+ id: newId(),+ title: board.title,+ },+ id: boardNodeIds[board.id],+ })),+ title: group.title,+ },+ edgeFlowIds,+ };+};diff --git a/apps/server/src/services/artboard/index.ts b/apps/server/src/services/artboard/index.tsnew file mode 100644index 00000000000..ccba6a0dfc2--- /dev/null+++ b/apps/server/src/services/artboard/index.ts@@ -0,0 +1,476 @@+import { randomUUID } from 'node:crypto';++import { ArtboardIdentifier } from '@lobechat/builtin-tool-artboard';+import type { ArtboardItem, ArtboardOp } from '@lobechat/types';+import { checkFinalizeReadiness } from '@lobechat/types';+import pMap from 'p-map';++import { AcceptanceModel } from '@/database/models/acceptance';+import { AcceptanceFlowModel } from '@/database/models/acceptanceFlow';+import { ArtboardModel, type ArtboardRow } from '@/database/models/artboard';+import { ArtboardCommentModel } from '@/database/models/artboard/comment';+import { ArtboardStructureModel } from '@/database/models/artboard/structure';+import { TaskModel } from '@/database/models/task';+import { TopicModel } from '@/database/models/topic';+import { WorkModel } from '@/database/models/work';+import type { LobeChatDatabase } from '@/database/type';+import { FileService } from '@/server/services/file';+import { TaskService } from '@/server/services/task';++import {+ type ArtboardCommentInput,+ ArtboardCommentService,+ type ArtboardQuestionInput,+} from './comments';+import { artboardConflict, ArtboardServiceError, guardArtboard, requireRowId } from './errors';+import { artboardFileBasePath } from './fileAccess';+import {+ type ArtboardBlobStore,+ type ArtboardFileChanges,+ type ArtboardFilePlan,+ ArtboardFileService,+ type ArtboardFileUploadRequest,+ createFileServiceArtboardBlobStore,+} from './files';+import { buildJourneyFlow } from './finalize';+import { applyArtboardOps, assertJourneyFilesKept } from './ops';+import {+ ARTBOARD_SOURCE_CONCURRENCY,+ type ArtboardSourceResolver,+ createArtboardSourceResolver,+} from './sources';+import { describeArtboard, toArtboardContent, toArtboardItem, withoutDraftPicks } from './view';++export type { ArtboardCommentInput, ArtboardQuestionInput } from './comments';+export type { ArtboardServiceErrorCode } from './errors';+export { ArtboardServiceError } from './errors';+export { describeArtboard } from './view';++export const ARTBOARD_TOOL_IDENTIFIER = ArtboardIdentifier;++export interface ArtboardContext {+ agentId?: string | null;+ taskId?: string | null;+ threadId?: string | null;+ topicId?: string | null;+}++export interface ArtboardCreateInput {+ description?: string | null;+ files?: ArtboardFileChanges;+ ops?: ArtboardOp[];+ taskId?: string | null;+ title: string;+}++export interface ArtboardWriteResult {+ artboard: ArtboardItem;+ changedIds: string[];+}++export interface ArtboardCreateResult extends ArtboardWriteResult {+ createdTask: boolean;+ task: { id: string; identifier: string };+}++export interface ArtboardReadResult {+ artboard: ArtboardItem;+}++export interface ArtboardViewResult {+ artboard: ArtboardItem;+ fileBaseUrl: string | null;+}++export interface ArtboardFinalizeResult {+ acceptanceId: string;+ artboard: ArtboardItem;+}++export interface ArtboardServiceOptions {+ context?: ArtboardContext;+ fileStore?: ArtboardBlobStore;+ sources?: ArtboardSourceResolver;+}++const notFound = (id: string) =>+ new ArtboardServiceError('not_found', `Artboard "${id}" was not found.`);++export class ArtboardService {+ private artboards: ArtboardModel;+ private structure: ArtboardStructureModel;+ private comments: ArtboardCommentModel;+ private commentService: ArtboardCommentService;+ private sources: ArtboardSourceResolver;+ private files: ArtboardFileService;+ private agentId: string | null;++ constructor(+ private db: LobeChatDatabase,+ private userId: string,+ private workspaceId?: string,+ options: ArtboardServiceOptions = {},+ ) {+ this.artboards = new ArtboardModel(db, userId, workspaceId);+ this.structure = new ArtboardStructureModel(db, userId, workspaceId);+ this.comments = new ArtboardCommentModel(db, userId, workspaceId);+ this.agentId = options.context?.agentId ?? null;+ this.commentService = new ArtboardCommentService({+ agentId: this.agentId,+ comments: this.comments,+ fileHashes: async (id) =>+ new Map((await this.files.list(id)).map((file) => [file.path, file.hash])),+ requireArtboard: (id) => this.require(id),+ structure: this.structure,+ });+ this.sources =+ options.sources ??+ createArtboardSourceResolver(db, { ...options.context, userId, workspaceId });+ this.files = new ArtboardFileService({+ resolveImage: (fileRef) => this.sources.imageBytes(fileRef),+ resolveImport: (source) => this.sources.importPage(source),+ store:+ options.fileStore ??+ createFileServiceArtboardBlobStore(() => new FileService(db, userId, workspaceId)),+ });+ }++ private async require(id: string) {+ const row = await this.artboards.findById(id);+ if (!row) throw notFound(id);+ return row;+ }++ private async content(id: string) {+ const [structure, openThreads, files] = await Promise.all([+ this.structure.getStructure(id),+ this.comments.listThreads(id, { unresolvedOnly: true }),+ this.files.list(id),+ ]);+ if (!structure) throw notFound(id);+ return toArtboardContent(+ structure,+ openThreads,+ new Map(files.map((file) => [file.path, file.hash])),+ );+ }++ private item = async (row: ArtboardRow) => toArtboardItem(row, await this.content(row.id));++ private items = (rows: ArtboardRow[]) =>+ pMap(rows, this.item, { concurrency: ARTBOARD_SOURCE_CONCURRENCY });++ private async resolveTask(ref: string) {+ const task = await new TaskModel(this.db, this.userId, this.workspaceId).resolve(ref);+ if (!task) throw new ArtboardServiceError('not_found', `Task "${ref}" was not found.`);+ return task;+ }++ private async topicProjectId(topicId?: string | null) {+ if (!topicId) return null;+ const topic = await new TopicModel(this.db, this.userId, this.workspaceId).findById(topicId);+ return topic?.projectId ?? null;+ }++ private async contextProjectId(context: ArtboardContext) {+ if (context.taskId) {+ const task = await new TaskModel(this.db, this.userId, this.workspaceId).resolve(+ context.taskId,+ );+ if (task?.projectId) return task.projectId;+ }+ return this.topicProjectId(context.topicId);+ }++ async create(+ input: ArtboardCreateInput,+ context: ArtboardContext,+ ): Promise<ArtboardCreateResult> {+ const taskRef = input.taskId ?? context.taskId;+ const existingTask = taskRef ? await this.resolveTask(taskRef) : undefined;+ const projectId = existingTask+ ? existingTask.projectId+ : await this.topicProjectId(context.topicId);+ if (!projectId)+ throw new ArtboardServiceError(+ 'no_project',+ 'An artboard belongs to a project task. Open it from a project conversation, or pass a taskId of a task in a project.',+ );++ if (existingTask) {+ const [existing] = await this.artboards.listByTaskId(existingTask.id);+ if (existing)+ throw new ArtboardServiceError(+ 'exists',+ `Task ${existingTask.identifier} already has artboard "${existing.id}". Read and update it instead.`,+ { artboardId: existing.id },+ );+ }++ const { changedIds, files, row } = await guardArtboard(() =>+ this.db.transaction(async (tx) => {+ const created = await this.artboards.withTransaction(tx).create({+ description: input.description ?? null,+ projectId,+ taskId: existingTask?.id ?? null,+ title: input.title,+ topicId: context.topicId ?? null,+ });+ // Validated before the row commits; stored after, since only then does the id exist.+ const files = await this.files.prepare(created.id, input.files ?? {});+ const changed = await applyArtboardOps(+ this.structure.withTransaction(tx),+ created,+ input.ops ?? [],+ );+ return { changedIds: changed, files, row: created };+ }),+ );+ await this.files.apply(row.id, files);++ const task = existingTask ?? (await this.createTaskFor(row, input, context));+ const attached = existingTask ? row : ((await this.artboards.setTask(row.id, task.id)) ?? row);+ return {+ artboard: await this.item(attached),+ changedIds,+ createdTask: !existingTask,+ task: { id: task.id, identifier: task.identifier },+ };+ }++ // The task is created after the board so a refused op leaves no task behind.+ private async createTaskFor(+ row: ArtboardRow,+ input: ArtboardCreateInput,+ context: ArtboardContext,+ ) {+ try {+ return await new TaskService(this.db, this.userId, this.workspaceId).createTask({+ createdByAgentId: context.agentId ?? undefined,+ instruction: input.description || input.title,+ name: input.title,+ projectId: row.projectId ?? undefined,+ });+ } catch (error) {+ await this.artboards.delete(row.id);+ await this.files.removeAll(row.id);+ throw error;+ }+ }++ async update(+ id: string,+ revision: number,+ ops: ArtboardOp[],+ changes: ArtboardFileChanges = {},+ ): Promise<ArtboardWriteResult> {+ const row = await this.require(id);+ if (row.revision !== revision) throw artboardConflict();+ const files = await this.prepareFiles(row, changes);++ const { changedIds } = await guardArtboard(() =>+ this.db.transaction(async (tx) => {+ await this.artboards.withTransaction(tx).update(id, { expectedRevision: revision });+ const changed = await applyArtboardOps(this.structure.withTransaction(tx), row, ops);+ return { changedIds: changed };+ }),+ );+ const next = await this.storeFiles(id, files);+ return { artboard: await this.item(next ?? (await this.require(id))), changedIds };+ }++ async writeFiles(id: string, changes: ArtboardFileChanges) {+ const plan = await this.prepareFiles(await this.require(id), changes);+ await this.storeFiles(id, plan);+ return { files: ArtboardFileService.touched(plan) };+ }++ /** Validate file changes; a finalized journey keeps the files its boards show. */+ private async prepareFiles(row: ArtboardRow, changes: ArtboardFileChanges) {+ const plan = await this.files.prepare(row.id, changes);+ const touched = ArtboardFileService.touched(plan);+ if (row.phase === 'finalized' && touched.length) {+ const structure = await this.structure.getStructure(row.id);+ if (structure) assertJourneyFilesKept(row, structure, touched);+ }+ return plan;+ }++ /** Store the files, then move updatedAt so open boards reload (writes do not bump revision). */+ private async storeFiles(id: string, plan: ArtboardFilePlan) {+ await this.files.apply(id, plan);+ return this.artboards.touch(id);+ }++ async listFiles(id: string) {+ await this.require(id);+ return this.files.list(id);+ }++ async readFile(id: string, path: string) {+ await this.require(id);+ return this.files.read(id, path);+ }++ async prepareFileUploads(id: string, files: ArtboardFileUploadRequest[]) {+ await this.require(id);+ return this.files.prepareUploads(id, files);+ }++ async read(id: string): Promise<ArtboardReadResult> {+ return { artboard: withoutDraftPicks(await this.item(await this.require(id))) };+ }++ async get(id: string): Promise<ArtboardViewResult> {+ return {+ artboard: await this.item(await this.require(id)),+ fileBaseUrl: artboardFileBasePath(id) ?? null,+ };+ }++ async getRevision(id: string): Promise<{ revision: number; updatedAt: Date }> {+ const stamp = await this.artboards.getRevision(id);+ if (!stamp) throw notFound(id);+ return stamp;+ }++ async getByTask(taskRef: string): Promise<ArtboardItem | null> {+ const task = await this.resolveTask(taskRef);+ const [row] = await this.artboards.listByTaskId(task.id);+ return row ? this.item(row) : null;+ }++ async listByProject(projectId: string): Promise<ArtboardItem[]> {+ return this.items(await this.artboards.listByProject(projectId));+ }++ async list(context: ArtboardContext): Promise<ArtboardItem[]> {+ const projectId = await this.contextProjectId(context);+ if (!projectId)+ throw new ArtboardServiceError(+ 'no_project',+ 'This conversation is not in a project, so it has no artboards.',+ );+ return this.listByProject(projectId);+ }++ private async requireRound(id: string, roundId: string) {+ await this.require(id);+ const structure = await this.structure.getStructure(id);+ if (!structure?.rounds.some((round) => round.id === roundId))+ throw new ArtboardServiceError('not_found', `Artboard "${id}" has no round ${roundId}.`);+ }++ async chooseBoard(id: string, roundId: string, boardId: string) {+ await this.requireRound(id, roundId);+ requireRowId(boardId, 'board');+ await guardArtboard(() => this.structure.chooseBoard(roundId, boardId));+ return { artboard: await this.item(await this.require(id)) };+ }++ async submitRound(id: string, roundId: string) {+ await this.requireRound(id, roundId);+ await guardArtboard(() => this.structure.submitRound(roundId));+ return { artboard: await this.item(await this.require(id)) };+ }++ async submitOpenRounds(id: string, roundIds?: string[]) {+ await this.require(id);+ const rounds = await guardArtboard(() => this.structure.submitOpenRounds(id, roundIds));+ return { artboard: await this.item(await this.require(id)), submitted: rounds.length };+ }++ listComments = (id: string) => this.commentService.list(id);++ countUndeliveredComments = (id: string) => this.commentService.countUndelivered(id);++ takeUndeliveredComments = (id: string) => this.commentService.takeUndelivered(id);++ async unreadCommentNotices(projectId: string, topicId: string) {+ const rows = (await this.artboards.listByProject(projectId)).filter(+ (row) => row.topicId === topicId,+ );+ const notices = await pMap(+ rows,+ async ({ id, title }) => ({+ id,+ threads: await this.commentService.countUndelivered(id),+ title,+ }),+ { concurrency: ARTBOARD_SOURCE_CONCURRENCY },+ );+ return notices.filter((notice) => notice.threads > 0);+ }++ addComment = (id: string, input: ArtboardCommentInput) =>+ this.commentService.open(id, input, null);++ askQuestion = (id: string, input: ArtboardQuestionInput) => this.commentService.ask(id, input);++ replyComment = (commentId: string, input: { clientId?: string; content: string }) =>+ this.commentService.reply(commentId, input);++ resolveComment = (commentId: string) => this.commentService.settle(commentId, true);++ reopenComment = (commentId: string) => this.commentService.settle(commentId, false);++ async finalize(id: string, revision: number): Promise<ArtboardFinalizeResult> {+ const row = await this.require(id);+ if (row.phase === 'finalized' && row.acceptanceId)+ return { acceptanceId: row.acceptanceId, artboard: await this.item(row) };+ if (row.revision !== revision) throw artboardConflict();+ const { taskId } = row;+ if (!taskId)+ throw new ArtboardServiceError('invalid', 'The board has no task to accept against.');++ const content = await this.content(id);+ const issues = checkFinalizeReadiness(content);+ if (issues.length)+ throw new ArtboardServiceError('finalize_blocked', 'The board is not ready to finalize.', {+ issues,+ });++ const next = await guardArtboard(() =>+ this.db.transaction(async (tx) => {+ const txDb = tx as unknown as LobeChatDatabase;+ const acceptance = await new AcceptanceModel(+ txDb,+ this.userId,+ this.workspaceId,+ ).ensureForSubject('task', taskId, {+ metadata: { title: row.title },+ projectId: row.projectId,+ requirement: row.title,+ });+ const flow = buildJourneyFlow(content, randomUUID);+ await new AcceptanceFlowModel(txDb, acceptance.userId).publish(+ acceptance.id,+ flow.definition,+ );++ const structure = this.structure.withTransaction(tx);+ for (const [boardId, acceptanceFlowNodeId] of Object.entries(flow.boardNodeIds))+ await structure.updateBoard(boardId, { acceptanceFlowNodeId });+ for (const [edgeId, acceptanceFlowEdgeId] of Object.entries(flow.edgeFlowIds))+ await structure.updateEdge(edgeId, { acceptanceFlowEdgeId });++ const updated = await this.artboards.withTransaction(tx).update(id, {+ acceptanceId: acceptance.id,+ expectedRevision: revision,+ phase: 'finalized',+ });+ await new WorkModel(txDb, this.userId, this.workspaceId).registerArtboard({+ artboardId: id,+ changeType: 'updated',+ description: describeArtboard(content),+ projectId: updated.projectId,+ title: updated.title,+ toolIdentifier: ARTBOARD_TOOL_IDENTIFIER,+ toolName: 'finalizeArtboard',+ });+ return updated;+ }),+ );+ return { acceptanceId: next.acceptanceId!, artboard: await this.item(next) };+ }+}diff --git a/apps/server/src/services/artboard/layout.ts b/apps/server/src/services/artboard/layout.tsnew file mode 100644index 00000000000..646f902e428--- /dev/null+++ b/apps/server/src/services/artboard/layout.ts@@ -0,0 +1,40 @@+import type { ArtboardRect } from '@lobechat/types';++const GROUP_PADDING = { bottom: 48, left: 48, right: 48, top: 144 };++export const EMPTY_GROUP_RECT: ArtboardRect = { h: 0, w: 0, x: 0, y: 0 };++export const wrapBoards = (rects: ArtboardRect[]): ArtboardRect => {+ if (!rects.length) return EMPTY_GROUP_RECT;+ const minX = Math.min(...rects.map((r) => r.x));+ const minY = Math.min(...rects.map((r) => r.y));+ const maxX = Math.max(...rects.map((r) => r.x + r.w));+ const maxY = Math.max(...rects.map((r) => r.y + r.h));+ return {+ h: maxY - minY + GROUP_PADDING.top + GROUP_PADDING.bottom,+ w: maxX - minX + GROUP_PADDING.left + GROUP_PADDING.right,+ x: minX - GROUP_PADDING.left,+ y: minY - GROUP_PADDING.top,+ };+};++type Origin = Pick<ArtboardRect, 'x' | 'y'>;++export const toPageRect = (rect: ArtboardRect, origin?: Origin): ArtboardRect =>+ origin ? { ...rect, x: rect.x + origin.x, y: rect.y + origin.y } : rect;++export const toGroupRect = (rect: ArtboardRect, origin?: Origin): ArtboardRect =>+ origin ? { ...rect, x: rect.x - origin.x, y: rect.y - origin.y } : rect;++export const sameRect = (a: ArtboardRect, b: ArtboardRect) =>+ a.x === b.x && a.y === b.y && a.w === b.w && a.h === b.h;++export const rectsOverlap = (a: ArtboardRect, b: ArtboardRect) =>+ a.w > 0 &&+ a.h > 0 &&+ b.w > 0 &&+ b.h > 0 &&+ a.x < b.x + b.w &&+ b.x < a.x + a.w &&+ a.y < b.y + b.h &&+ b.y < a.y + a.h;diff --git a/apps/server/src/services/artboard/opInputs.ts b/apps/server/src/services/artboard/opInputs.tsnew file mode 100644index 00000000000..ff6e59e771a--- /dev/null+++ b/apps/server/src/services/artboard/opInputs.ts@@ -0,0 +1,96 @@+import {+ type ArtboardBoardSourceInput,+ type ArtboardBoardType,+ type ArtboardOp,+ isArtboardHtmlPath,+ isArtboardImagePath,+ normalizeArtboardFilePath,+} from '@lobechat/types';++import type { ArtboardBoardRow } from '@/database/models/artboard';++import { failArtboard } from './errors';++export const sourcePathOf = (source: ArtboardBoardSourceInput) =>+ normalizeArtboardFilePath(source.path) ??+ failArtboard('invalid', `"${source.path}" is not a valid artboard file path.`);++export const sourceHashKey = (+ board: Pick<ArtboardBoardRow, 'sourcePath'>,+ hashes: ReadonlyMap<string, string>,+): string | undefined => (board.sourcePath ? hashes.get(board.sourcePath) : undefined);++const derivedBoardType = (sourcePath: string): ArtboardBoardType => {+ if (isArtboardImagePath(sourcePath)) return 'image';+ if (isArtboardHtmlPath(sourcePath)) return 'html';+ return failArtboard(+ 'invalid',+ `"${sourcePath}" is neither an HTML page nor an image a board can show`,+ );+};++export const boardTypeOf = (+ requested: ArtboardBoardType | undefined,+ sourcePath: string | undefined,+): ArtboardBoardType => {+ if (requested === 'video') return failArtboard('invalid', 'Video boards are not supported yet');+ if (requested === 'decision') {+ if (sourcePath) failArtboard('invalid', 'A decision board has no source');+ return 'decision';+ }+ if (!sourcePath)+ return failArtboard('invalid', 'A board needs a source unless its type is "decision"');+ const derived = derivedBoardType(sourcePath);+ if (requested && requested !== derived)+ failArtboard('invalid', `"${sourcePath}" makes an "${derived}" board`);+ return derived;+};++export const resolveOpRefs = (op: ArtboardOp, refs: Map<string, string>): ArtboardOp => {+ const id = (value: string) => refs.get(value) ?? value;+ const optionalId = <T extends string | null | undefined>(value: T) =>+ (value ? id(value) : value) as T;++ switch (op.type) {+ case 'addPage': {+ return op;+ }+ case 'addRound': {+ return { ...op, round: { ...op.round, pageId: optionalId(op.round.pageId) } };+ }+ case 'addGroup': {+ return { ...op, group: { ...op.group, pageId: optionalId(op.group.pageId) } };+ }+ case 'addBoard': {+ return {+ ...op,+ board: {+ ...op.board,+ groupId: optionalId(op.board.groupId),+ pageId: optionalId(op.board.pageId),+ roundId: optionalId(op.board.roundId),+ },+ };+ }+ case 'updateBoard': {+ return {+ ...op,+ id: id(op.id),+ patch: {+ ...op.patch,+ ...('groupId' in op.patch ? { groupId: optionalId(op.patch.groupId) } : {}),+ ...('roundId' in op.patch ? { roundId: optionalId(op.patch.roundId) } : {}),+ },+ };+ }+ case 'addEdge': {+ return { ...op, edge: { ...op.edge, from: id(op.edge.from), to: id(op.edge.to) } };+ }+ case 'setCheck': {+ return { ...op, boardId: id(op.boardId) };+ }+ default: {+ return { ...op, id: id(op.id) };+ }+ }+};diff --git a/apps/server/src/services/artboard/ops.ts b/apps/server/src/services/artboard/ops.tsnew file mode 100644index 00000000000..20c90f7ae08--- /dev/null+++ b/apps/server/src/services/artboard/ops.ts@@ -0,0 +1,537 @@+import {+ ARTBOARD_BOARD_SIZE,+ type ArtboardBoardSourceInput,+ type ArtboardOp,+ type ArtboardPhase,+ type ArtboardRect,+} from '@lobechat/types';++import type {+ ArtboardBoardRow,+ ArtboardEdgeRow,+ ArtboardGroupRow,+ ArtboardPageRow,+ ArtboardRoundRow,+} from '@/database/models/artboard';+import type {+ ArtboardStructure,+ ArtboardStructureModel,+} from '@/database/models/artboard/structure';++import { failArtboard, toArtboardServiceError } from './errors';+import {+ EMPTY_GROUP_RECT,+ rectsOverlap,+ sameRect,+ toGroupRect,+ toPageRect,+ wrapBoards,+} from './layout';+import { boardTypeOf, resolveOpRefs, sourcePathOf } from './opInputs';++export interface ArtboardOpTarget {+ id: string;+ phase: ArtboardPhase;+ projectId: string | null;+}++type OpOf<T extends ArtboardOp['type']> = Extract<ArtboardOp, { type: T }>;++interface DraftBoard extends ArtboardBoardRow {+ stored: ArtboardRect;+}++const LAYOUT_KEYS = new Set(['h', 'w', 'x', 'y']);++class Draft {+ readonly changed: string[] = [];+ private refs = new Map<string, string>();+ private pages: ArtboardPageRow[];+ private rounds: ArtboardRoundRow[];+ private groups: ArtboardGroupRow[];+ private boards: DraftBoard[];+ private edges: ArtboardEdgeRow[];++ constructor(+ private model: ArtboardStructureModel,+ private artboard: ArtboardOpTarget,+ structure: ArtboardStructure,+ ) {+ this.pages = [...structure.pages];+ this.rounds = [...structure.rounds];+ this.groups = [...structure.groups];+ this.edges = [...structure.edges];+ const origins = new Map(structure.groups.map((group) => [group.id, group.rect]));+ this.boards = structure.boards.map((board) => ({+ ...board,+ rect: toPageRect(board.rect, board.groupId ? origins.get(board.groupId) : undefined),+ stored: board.rect,+ }));+ }++ private touch(id: string) {+ if (!this.changed.includes(id)) this.changed.push(id);+ }++ private page(id?: string) {+ if (!id) return this.pages[0];+ return this.pages.find((p) => p.id === id) ?? failArtboard('not_found', `No page ${id}`);+ }++ private round(id: string) {+ return this.rounds.find((r) => r.id === id) ?? failArtboard('not_found', `No round ${id}`);+ }++ private group(id: string) {+ return this.groups.find((g) => g.id === id) ?? failArtboard('not_found', `No group ${id}`);+ }++ private board(id: string) {+ return this.boards.find((b) => b.id === id) ?? failArtboard('not_found', `No board ${id}`);+ }++ private sourcePath(source: ArtboardBoardSourceInput | undefined) {+ return source ? sourcePathOf(source) : undefined;+ }++ private inJourney(groupId: string | null | undefined) {+ return !!groupId && this.groups.some((g) => g.id === groupId && g.kind === 'journey');+ }++ private assertJourneyOpen(what: string) {+ if (this.artboard.phase === 'finalized')+ failArtboard('locked', `The journey is finalized; ${what} can no longer change`);+ }++ private assertNoOtherJourney(exceptId?: string) {+ if (this.groups.some((g) => g.kind === 'journey' && g.id !== exceptId))+ failArtboard('invalid', 'The board already has a journey group');+ }++ private assertPlacement(+ pageId: string,+ group: ArtboardGroupRow | undefined,+ round: ArtboardRoundRow | undefined,+ boardId?: string,+ ) {+ if (group && group.pageId !== pageId)+ failArtboard('invalid', 'A board is on the page of its group');+ if (round && round.pageId !== pageId)+ failArtboard('invalid', 'A board is on the page of its round');+ if (group?.kind === 'options' && !round)+ failArtboard(+ 'invalid',+ 'A board in an options group is an option of a round; add a round and pass its id as roundId',+ );+ if (round && group?.kind !== 'options')+ failArtboard('invalid', 'Only a board in an options group can be an option of a round');+ if (!round || !group) return;+ const others = this.boards.filter((b) => b.id !== boardId);+ if (others.some((b) => b.roundId === round.id && b.groupId !== group.id))+ failArtboard('invalid', `Round ${round.id} already has options in another group`);+ if (others.some((b) => b.groupId === group.id && b.roundId && b.roundId !== round.id))+ failArtboard('invalid', `Group ${group.id} already holds the options of another round`);+ }++ private replaceRound(row: ArtboardRoundRow) {+ this.rounds = this.rounds.map((r) => (r.id === row.id ? row : r));+ }++ private async recommend(roundId: string, boardId: string | null) {+ this.replaceRound(await this.model.updateRound(roundId, { recommendedBoardId: boardId }));+ this.touch(roundId);+ }++ async apply(raw: ArtboardOp) {+ const ref = 'ref' in raw ? raw.ref : undefined;+ if (ref && this.refs.has(ref))+ failArtboard('invalid', `ref "${ref}" is used twice in this batch`);+ const createdId = await this.run(resolveOpRefs(raw, this.refs));+ if (ref && createdId) this.refs.set(ref, createdId);+ }++ private async run(op: ArtboardOp): Promise<string | void> {+ switch (op.type) {+ case 'addPage': {+ const sortOrder = Math.max(...this.pages.map((p) => p.sortOrder)) + 1;+ const row = await this.model.createPage(this.artboard.id, {+ name: op.page.name,+ sortOrder,+ });+ this.pages.push(row);+ this.touch(row.id);+ return row.id;+ }+ case 'updatePage': {+ this.page(op.id);+ const row = await this.model.updatePage(op.id, op.patch);+ this.pages = this.pages.map((p) => (p.id === row.id ? row : p));+ this.touch(row.id);+ return;+ }+ case 'removePage': {+ this.page(op.id);+ await this.model.deletePage(op.id);+ this.pages = this.pages.filter((p) => p.id !== op.id);+ this.touch(op.id);+ return;+ }+ case 'addRound': {+ const page = this.page(op.round.pageId);+ const row = await this.model.createRound(this.artboard.id, {+ metadata: op.round.batchId ? { batchId: op.round.batchId } : undefined,+ pageId: page.id,+ title: op.round.title,+ });+ this.rounds.push(row);+ this.touch(row.id);+ return row.id;+ }+ case 'updateRound': {+ this.round(op.id);+ this.replaceRound(await this.model.updateRound(op.id, op.patch));+ this.touch(op.id);+ return;+ }+ case 'addGroup': {+ return this.addGroup(op);+ }+ case 'updateGroup': {+ return this.updateGroup(op);+ }+ case 'removeGroup': {+ const group = this.group(op.id);+ if (this.boards.some((b) => b.groupId === group.id))+ failArtboard('invalid', `Group ${group.id} still has boards; remove or move them first`);+ if (group.kind === 'journey') this.assertJourneyOpen('the journey group');+ await this.model.deleteGroup(group.id);+ this.groups = this.groups.filter((g) => g.id !== group.id);+ this.touch(group.id);+ return;+ }+ case 'addBoard': {+ return this.addBoard(op);+ }+ case 'updateBoard': {+ return this.updateBoard(op);+ }+ case 'removeBoard': {+ return this.removeBoard(op);+ }+ case 'addEdge': {+ return this.addEdge(op);+ }+ case 'removeEdge': {+ const edge =+ this.edges.find((e) => e.id === op.id) ?? failArtboard('not_found', `No edge ${op.id}`);+ if (+ this.inJourney(this.board(edge.sourceBoardId).groupId) ||+ this.inJourney(this.board(edge.targetBoardId).groupId)+ )+ this.assertJourneyOpen('journey edges');+ await this.model.deleteEdge(edge.id);+ this.edges = this.edges.filter((e) => e.id !== edge.id);+ this.touch(edge.id);+ return;+ }+ case 'setCheck': {+ const board = this.board(op.boardId);+ if (!this.inJourney(board.groupId) || board.type === 'decision')+ failArtboard('invalid', 'Only journey boards that show a screen carry a check');+ this.assertJourneyOpen('acceptance checks');+ await this.model.updateBoard(board.id, { expected: op.expected });+ board.expected = op.expected;+ this.touch(board.id);+ }+ }+ }++ private async addGroup({ group }: OpOf<'addGroup'>) {+ if (group.kind === 'journey') this.assertNoOtherJourney();+ const page = this.page(group.pageId);+ const row = await this.model.createGroup(this.artboard.id, {+ description: group.desc ?? null,+ kind: group.kind,+ pageId: page.id,+ rect: EMPTY_GROUP_RECT,+ title: group.title,+ });+ this.groups.push(row);+ this.touch(row.id);+ return row.id;+ }++ private async updateGroup({ id, patch }: OpOf<'updateGroup'>) {+ const group = this.group(id);+ const members = this.boards.filter((b) => b.groupId === group.id);+ const kindChanges = patch.kind !== undefined && patch.kind !== group.kind;+ if (kindChanges) {+ if (patch.kind === 'journey') this.assertNoOtherJourney(group.id);+ if (group.kind === 'journey' || patch.kind === 'journey')+ this.assertJourneyOpen('the journey group');+ if (patch.kind === 'options' && members.some((b) => !b.roundId))+ failArtboard('invalid', 'Every board in an options group is an option of a round');+ if (group.kind === 'options' && members.some((b) => b.roundId))+ failArtboard('invalid', 'Take the boards out of their round before changing this group');+ }++ const row = await this.model.updateGroup(group.id, {+ ...(patch.desc === undefined ? {} : { description: patch.desc }),+ ...(patch.kind === undefined ? {} : { kind: patch.kind }),+ ...(patch.title === undefined ? {} : { title: patch.title }),+ });+ this.groups = this.groups.map((g) => (g.id === row.id ? { ...row, rect: g.rect } : g));+ this.touch(group.id);++ if (kindChanges && group.kind === 'journey')+ for (const board of members.filter((b) => b.expected !== null)) {+ await this.model.updateBoard(board.id, { expected: null });+ board.expected = null;+ }+ }++ private async addBoard({ board }: OpOf<'addBoard'>) {+ const group = board.groupId ? this.group(board.groupId) : undefined;+ const round = board.roundId ? this.round(board.roundId) : undefined;+ const page = this.page(board.pageId ?? group?.pageId ?? round?.pageId);+ this.assertPlacement(page.id, group, round);+ if (round && round.status !== 'open')+ failArtboard('locked', `Round ${round.id} is submitted; its options can no longer change`);+ const sourcePath = this.sourcePath(board.source);+ const type = boardTypeOf(board.type, sourcePath);+ const journey = this.inJourney(group?.id);+ if (journey) this.assertJourneyOpen('journey boards');+ if (board.expected !== undefined && (!journey || type === 'decision'))+ failArtboard('invalid', 'Only journey boards that show a screen carry a check');+ if (board.recommended && !round)+ failArtboard('invalid', 'Only an option of a round can be recommended');++ const rect = {+ h: board.h ?? ARTBOARD_BOARD_SIZE.height,+ w: board.w ?? ARTBOARD_BOARD_SIZE.width,+ x: board.x,+ y: board.y,+ };+ const row = await this.model.createBoard(this.artboard.id, {+ sourcePath: sourcePath ?? null,+ expected: board.expected ?? null,+ groupId: group?.id ?? null,+ pageId: page.id,+ projectId: this.artboard.projectId,+ rect,+ roundId: round?.id ?? null,+ title: board.title,+ type,+ });+ this.boards.push({ ...row, stored: rect });+ this.touch(row.id);+ if (board.recommended && round) await this.recommend(round.id, row.id);+ return row.id;+ }++ private async updateBoard({ id, patch }: OpOf<'updateBoard'>) {+ const board = this.board(id);+ const group =+ patch.groupId === undefined+ ? board.groupId+ ? this.group(board.groupId)+ : undefined+ : patch.groupId+ ? this.group(patch.groupId)+ : undefined;+ let round =+ patch.roundId === undefined+ ? board.roundId+ ? this.round(board.roundId)+ : undefined+ : patch.roundId+ ? this.round(patch.roundId)+ : undefined;+ const previousRound = board.roundId ? this.round(board.roundId) : undefined;+ const roundChanges = (round?.id ?? null) !== board.roundId;+ const journey = this.inJourney(group?.id);+ const layoutOnly = Object.keys(patch).every((key) => LAYOUT_KEYS.has(key));+ if ((journey || this.inJourney(board.groupId)) && !layoutOnly)+ this.assertJourneyOpen('journey boards');++ if (patch.recommended === false && previousRound?.recommendedBoardId === board.id)+ await this.recommend(previousRound.id, null);+ if (roundChanges) {+ const left = previousRound && this.round(previousRound.id);+ if (left && left.status !== 'open')+ failArtboard('locked', `Round ${left.id} is submitted; its options can no longer change`);+ if (left && (left.recommendedBoardId === board.id || left.chosenBoardId === board.id))+ failArtboard(+ 'invalid',+ `Board ${board.id} is the recommendation or the pick of round ${left.id}; remove the board instead of moving it`,+ );+ if (round && round.status !== 'open')+ failArtboard('locked', `Round ${round.id} is submitted; its options can no longer change`);+ }+ if (roundChanges || (group?.id ?? null) !== board.groupId)+ this.assertPlacement(board.pageId, group, round, board.id);++ const sourcePath = this.sourcePath(patch.source);+ const type =+ sourcePath === undefined+ ? board.type+ : boardTypeOf(board.type === 'decision' ? 'decision' : undefined, sourcePath);+ const carriesCheck = journey && type !== 'decision';+ if (patch.expected !== undefined && !carriesCheck)+ failArtboard('invalid', 'Only journey boards that show a screen carry a check');+ const expected = carriesCheck ? (patch.expected ?? board.expected) : null;++ const values = {+ ...(sourcePath === undefined ? {} : { sourcePath, type }),+ ...(patch.title === undefined ? {} : { title: patch.title }),+ ...(expected === board.expected ? {} : { expected }),+ ...((group?.id ?? null) === board.groupId ? {} : { groupId: group?.id ?? null }),+ ...(roundChanges ? { roundId: round?.id ?? null } : {}),+ };+ const row = Object.keys(values).length ? await this.model.updateBoard(board.id, values) : board;+ Object.assign(board, row, {+ rect: {+ h: patch.h ?? board.rect.h,+ w: patch.w ?? board.rect.w,+ x: patch.x ?? board.rect.x,+ y: patch.y ?? board.rect.y,+ },+ stored: board.stored,+ });+ this.touch(board.id);++ if (patch.recommended) {+ round = board.roundId ? this.round(board.roundId) : undefined;+ if (!round) return failArtboard('invalid', 'Only an option of a round can be recommended');+ await this.recommend(round.id, board.id);+ }+ }++ private async removeBoard({ id }: OpOf<'removeBoard'>) {+ const board = this.board(id);+ if (this.inJourney(board.groupId)) this.assertJourneyOpen('journey boards');+ const round = board.roundId ? this.round(board.roundId) : undefined;+ if (round?.status === 'submitted' && round.chosenBoardId === board.id)+ failArtboard('locked', `Board ${board.id} is the submitted pick of round ${round.id}`);++ await this.model.deleteBoard(board.id);+ this.boards = this.boards.filter((b) => b.id !== board.id);+ this.touch(board.id);+ for (const edge of this.edges)+ if (edge.sourceBoardId === board.id || edge.targetBoardId === board.id) this.touch(edge.id);+ this.edges = this.edges.filter(+ (e) => e.sourceBoardId !== board.id && e.targetBoardId !== board.id,+ );+ this.rounds = this.rounds.map((r) => ({+ ...r,+ chosenBoardId: r.chosenBoardId === board.id ? null : r.chosenBoardId,+ recommendedBoardId: r.recommendedBoardId === board.id ? null : r.recommendedBoardId,+ }));+ }++ private async addEdge({ edge }: OpOf<'addEdge'>) {+ const from = this.board(edge.from);+ const to = this.board(edge.to);+ if (from.id === to.id) failArtboard('invalid', 'An edge needs two different boards');+ if (from.pageId !== to.pageId)+ failArtboard('invalid', 'An edge connects two boards on the same page');+ if (this.inJourney(from.groupId) || this.inJourney(to.groupId))+ this.assertJourneyOpen('journey edges');+ const siblings = this.edges.filter((e) => e.sourceBoardId === from.id);+ if (edge.isDefault && siblings.some((e) => e.isDefault))+ failArtboard('invalid', `Board ${from.id} already has a default edge`);++ const row = await this.model.createEdge(this.artboard.id, {+ condition: edge.condition ?? null,+ isDefault: edge.isDefault ?? false,+ label: edge.label ?? '',+ sortOrder: siblings.length,+ sourceBoardId: from.id,+ targetBoardId: to.id,+ });+ this.edges.push(row);+ this.touch(row.id);+ return row.id;+ }++ async flushLayout() {+ const wrapped = this.groups.map((group) => ({+ group,+ rect: wrapBoards(this.boards.filter((b) => b.groupId === group.id).map((b) => b.rect)),+ }));+ for (const moved of wrapped) {+ if (sameRect(moved.group.rect, moved.rect)) continue;+ const hit = wrapped.find(+ (other) =>+ other.group.id !== moved.group.id &&+ other.group.pageId === moved.group.pageId &&+ rectsOverlap(moved.rect, other.rect),+ );+ if (hit)+ failArtboard(+ 'invalid',+ `The frame of group "${moved.group.title}" lands on group "${hit.group.title}". A frame reaches 144 above and 48 around its boards: move the boards of one group so the two frames are apart.`,+ );+ }+ for (const { group, rect } of wrapped) {+ if (sameRect(group.rect, rect)) continue;+ await this.model.updateGroup(group.id, { rect });+ group.rect = rect;+ }+ const origins = new Map(this.groups.map((group) => [group.id, group.rect]));+ for (const board of this.boards) {+ const rect = toGroupRect(board.rect, board.groupId ? origins.get(board.groupId) : undefined);+ if (sameRect(board.stored, rect)) continue;+ await this.model.updateBoard(board.id, { rect });+ board.stored = rect;+ }+ }+}++/**+ * A finalized journey is what the feature is accepted against: the files its boards show stay as+ * they are. Throws `locked` when `touched` includes one.+ */+export const assertJourneyFilesKept = (+ artboard: ArtboardOpTarget,+ structure: Pick<ArtboardStructure, 'boards' | 'groups'>,+ touched: Iterable<string>,+) => {+ if (artboard.phase !== 'finalized') return;+ const journeyIds = new Set(structure.groups.filter((g) => g.kind === 'journey').map((g) => g.id));+ const shown = new Map(+ structure.boards.flatMap((board) =>+ board.sourcePath && board.groupId && journeyIds.has(board.groupId)+ ? [[board.sourcePath, board.title] as const]+ : [],+ ),+ );+ for (const path of touched) {+ const title = shown.get(path);+ if (title !== undefined)+ failArtboard(+ 'locked',+ `The journey is finalized; "${path}" (shown by journey board "${title}") can no longer change. Write the change to a new file instead.`,+ );+ }+};++export const applyArtboardOps = async (+ model: ArtboardStructureModel,+ artboard: ArtboardOpTarget,+ ops: ArtboardOp[],+): Promise<string[]> => {+ const structure = await model.getStructure(artboard.id);+ if (!structure) return failArtboard('not_found', `Artboard "${artboard.id}" was not found.`);++ const draft = new Draft(model, artboard, structure);+ for (const [index, op] of ops.entries()) {+ try {+ await draft.apply(op);+ } catch (error) {+ throw toArtboardServiceError(error, index);+ }+ }+ await draft.flushLayout();+ return draft.changed;+};diff --git a/apps/server/src/services/artboard/publish/bundle.test.ts b/apps/server/src/services/artboard/publish/bundle.test.tsnew file mode 100644index 00000000000..13225c78879--- /dev/null+++ b/apps/server/src/services/artboard/publish/bundle.test.ts@@ -0,0 +1,81 @@+// @vitest-environment node+import type { ArtboardPublishSnapshot } from '@lobechat/types';+import { describe, expect, it } from 'vitest';++import { buildArtboardPublishBundle } from './bundle';++const snapshot = (title = 'Onboarding'): ArtboardPublishSnapshot => ({+ boards: [],+ description: null,+ edges: [],+ groups: [],+ pages: [{ id: 'pg_1', name: 'Page 1', sortOrder: 0 }],+ publishedAt: '2026-11-17T00:00:00.000Z',+ rounds: [],+ title,+ version: 1,+});++const viewerUrl = 'https://static.example.com/artboard-viewer/v1/abc/artboard-viewer.js';++const snapshotJsonOf = (html: string) =>+ JSON.parse(+ /<script type="application\/json" id="artboard-snapshot">([\s\S]*?)<\/script>/.exec(html)![1],+ );++describe('buildArtboardPublishBundle', () => {+ it('loads the viewer and embeds the snapshot in index.html', () => {+ const { html } = buildArtboardPublishBundle({+ files: [],+ snapshot: snapshot(),+ viewerUrl,+ });++ expect(html).toContain(`<script defer src="${viewerUrl}"></script>`);+ expect(snapshotJsonOf(html)).toEqual(snapshot());+ expect(html).toContain('<title>Onboarding</title>');+ });++ it('keeps a title that closes the script tag inside the JSON', () => {+ const title = '</script><script>alert(1)</script>\u2028';+ const { html } = buildArtboardPublishBundle({+ files: [],+ snapshot: snapshot(title),+ viewerUrl,+ });++ expect(html.match(/<\/script>/g)).toHaveLength(2);+ expect(snapshotJsonOf(html).title).toBe(title);+ expect(html).toContain('<title></script><script>alert(1)</script>');+ });++ it('ships every artboard file as base64 under files/', () => {+ const { files } = buildArtboardPublishBundle({+ files: [+ {+ bytes: new TextEncoder().encode('<p>a</p>'),+ contentType: 'text/html',+ path: 'pages/a.html',+ },+ { bytes: new Uint8Array([1, 2, 3]), contentType: 'image/png', path: 'shots/[email protected]' },+ ],+ snapshot: snapshot(),+ viewerUrl,+ });++ expect(files).toEqual([+ {+ content: 'PHA+YTwvcD4=',+ contentType: 'text/html',+ encoding: 'base64',+ path: '/files/pages/a.html',+ },+ {+ content: 'AQID',+ contentType: 'image/png',+ encoding: 'base64',+ path: '/files/shots/[email protected]',+ },+ ]);+ });+});diff --git a/apps/server/src/services/artboard/publish/bundle.ts b/apps/server/src/services/artboard/publish/bundle.tsnew file mode 100644index 00000000000..7e23d0dfeb3--- /dev/null+++ b/apps/server/src/services/artboard/publish/bundle.ts@@ -0,0 +1,63 @@+import {+ ARTBOARD_SITE_FILES_DIR,+ ARTBOARD_SNAPSHOT_ELEMENT_ID,+ type ArtboardPublishSnapshot,+ type CanvasPublishBundle,+ type CanvasPublishFile,+} from '@lobechat/types';++export interface ArtboardPublishFile {+ bytes: Uint8Array;+ contentType: string;+ path: string;+}++export interface ArtboardPublishBundleInput {+ files: ArtboardPublishFile[];+ snapshot: ArtboardPublishSnapshot;+ viewerUrl: string;+}++const escapeHtml = (value: string) =>+ value+ .replaceAll('&', '&')+ .replaceAll('<', '<')+ .replaceAll('>', '>')+ .replaceAll('"', '"');++const scriptSafeJson = (value: unknown) =>+ JSON.stringify(value)+ .replaceAll('<', String.raw`\u003c`)+ .replaceAll('\u2028', String.raw`\u2028`)+ .replaceAll('\u2029', String.raw`\u2029`);++const indexHtml = (snapshot: ArtboardPublishSnapshot, viewerUrl: string) =>+ [+ '<!doctype html>',+ '<html>',+ '<head>',+ '<meta charset="utf-8">',+ '<meta name="viewport" content="width=device-width, initial-scale=1">',+ `<title>${escapeHtml(snapshot.title)}</title>`,+ `<script defer src="${escapeHtml(viewerUrl)}"></script>`,+ '</head>',+ '<body>',+ '<div id="root"></div>',+ `<script type="application/json" id="${ARTBOARD_SNAPSHOT_ELEMENT_ID}">${scriptSafeJson(snapshot)}</script>`,+ '</body>',+ '</html>',+ ].join('');++export const buildArtboardPublishBundle = ({+ files,+ snapshot,+ viewerUrl,+}: ArtboardPublishBundleInput): CanvasPublishBundle => ({+ files: files.map((file): CanvasPublishFile => ({+ content: Buffer.from(file.bytes).toString('base64'),+ contentType: file.contentType,+ encoding: 'base64',+ path: `/${ARTBOARD_SITE_FILES_DIR}${file.path}`,+ })),+ html: indexHtml(snapshot, viewerUrl),+});diff --git a/apps/server/src/services/artboard/publish/index.ts b/apps/server/src/services/artboard/publish/index.tsnew file mode 100644index 00000000000..850e2fc8198--- /dev/null+++ b/apps/server/src/services/artboard/publish/index.ts@@ -0,0 +1,195 @@+import { ARTBOARD_VIEWER_MAJOR, type ArtboardItem } from '@lobechat/types';+import { TRPCError } from '@trpc/server';+import pMap from 'p-map';++import {+ getArtboardViewerUrl,+ isCanvasPublishEnabled,+ publishArtboardSite,+} from '@/business/server/canvasPublish';+import { WorkModel } from '@/database/models/work';+import type { ArtboardWork } from '@/database/models/work/artboard';+import type { LobeChatDatabase } from '@/database/type';+import { FileService } from '@/server/services/file';++import { ARTBOARD_TOOL_IDENTIFIER, ArtboardService, describeArtboard } from '..';+import { artboardFileKey, createFileServiceArtboardBlobStore } from '../files';+import { ARTBOARD_SOURCE_CONCURRENCY } from '../sources';+import { buildArtboardPublishBundle } from './bundle';+import { type ArtboardShareOwner, unpublishArtboardWork } from './offline';+import {+ type ArtboardPublishFileRef,+ buildArtboardPublishSnapshot,+ hashArtboardSnapshot,+} from './snapshot';++export { unpublishArtboardWork } from './offline';++export interface ArtboardPublishFileRow extends ArtboardPublishFileRef {+ contentType: string;+}++export interface ArtboardPublishDeps {+ listFiles: (id: string) => Promise<ArtboardPublishFileRow[]>;+ loadArtboard: (id: string) => Promise<ArtboardItem>;+ /** Bytes of one artboard file, or undefined when the object store can no longer read it. */+ readFile: (id: string, path: string) => Promise<Uint8Array | undefined>;+}++export interface ArtboardPublishState {+ canPublish: boolean;+ hasUpdates: boolean;+ publishedUrl: string | null;+}++const precondition = (message: string) => new TRPCError({ code: 'PRECONDITION_FAILED', message });++const createDefaultDeps = ({+ db,+ userId,+ workspaceId,+}: ArtboardShareOwner): ArtboardPublishDeps => {+ const artboards = new ArtboardService(db, userId, workspaceId);+ const store = createFileServiceArtboardBlobStore(() => new FileService(db, userId, workspaceId));++ return {+ listFiles: (id) => artboards.listFiles(id),+ loadArtboard: async (id) => (await artboards.get(id)).artboard,+ // Only reached after listFiles(id) checked the artboard is visible to this user.+ readFile: async (id, path) => {+ try {+ return await store.read(artboardFileKey(id, path));+ } catch (error) {+ console.error('[artboard:publish] file unreadable', id, path, error);+ return;+ }+ },+ };+};++export class ArtboardPublishService {+ private workModel: WorkModel;+ private deps: ArtboardPublishDeps;++ constructor(+ private db: LobeChatDatabase,+ private userId: string,+ private workspaceId?: string,+ deps: Partial<ArtboardPublishDeps> = {},+ ) {+ this.workModel = new WorkModel(db, userId, workspaceId);+ this.deps = { ...createDefaultDeps({ db, userId, workspaceId }), ...deps };+ }++ // works.userId follows whoever registered the board last; the deployment lives with the publisher.+ private owns = (work: ArtboardWork | null) => {+ const publisher = work?.metadata?.artboardPublish?.publisherUserId;+ return !publisher || publisher === this.userId;+ };++ async getPublish(id: string): Promise<ArtboardPublishState> {+ const artboard = await this.deps.loadArtboard(id);+ const work = await this.workModel.findArtboardWork(id);+ const canPublish = isCanvasPublishEnabled() && this.owns(work);+ const publish = work?.metadata?.artboardPublish;+ if (!publish || !work?.url) return { canPublish, hasUpdates: false, publishedUrl: null };++ const hash = hashArtboardSnapshot(+ buildArtboardPublishSnapshot(artboard, { publishedAt: '' }),+ await this.deps.listFiles(id),+ );+ return { canPublish, hasUpdates: hash !== publish.snapshotHash, publishedUrl: work.url };+ }++ async publish(id: string): Promise<{ url: string }> {+ if (!isCanvasPublishEnabled())+ throw new TRPCError({+ code: 'NOT_IMPLEMENTED',+ message: 'Artboard publishing is unavailable',+ });++ const artboard = await this.deps.loadArtboard(id);+ const work = await this.workModel.findArtboardWork(id);+ if (!this.owns(work))+ throw new TRPCError({+ code: 'FORBIDDEN',+ message: 'Only the person who owns this artboard can share it',+ });++ const missing = artboard.content.boards.find(+ (board) => !board.source && board.type !== 'decision',+ );+ if (missing) throw precondition(`Board "${missing.title}" has no file to publish`);++ // A board whose file is missing is published as is; the viewer shows it as missing.+ const rows = await this.deps.listFiles(id);++ const viewerUrl = await getArtboardViewerUrl(ARTBOARD_VIEWER_MAJOR);+ if (!viewerUrl) throw precondition('The publication host has no compatible artboard viewer');++ const files = await pMap(+ rows,+ async ({ contentType, path }) => {+ const bytes = await this.deps.readFile(id, path);+ if (!bytes) throw precondition(`Artboard file "${path}" can no longer be read`);+ return { bytes, contentType, path };+ },+ { concurrency: ARTBOARD_SOURCE_CONCURRENCY },+ );+ const snapshot = buildArtboardPublishSnapshot(artboard, {+ publishedAt: new Date().toISOString(),+ });+ const bundle = buildArtboardPublishBundle({ files, snapshot, viewerUrl });++ if (!work)+ await this.workModel.registerArtboard({+ artboardId: id,+ changeType: 'created',+ description: describeArtboard(artboard.content),+ projectId: artboard.projectId,+ title: artboard.title,+ toolIdentifier: ARTBOARD_TOOL_IDENTIFIER,+ toolName: 'publishArtboard',+ });++ const site = await publishArtboardSite({+ artboardId: id,+ bundle,+ db: this.db,+ deploymentId: work?.metadata?.artboardPublish?.deploymentId,+ title: artboard.title,+ userId: this.userId,+ workspaceId: this.workspaceId,+ });+ const recorded = await this.workModel.recordArtboardPublish(id, {+ deploymentId: site.deploymentId,+ publishedRevision: artboard.revision,+ publisherUserId: this.userId,+ snapshotHash: hashArtboardSnapshot(snapshot, rows),+ url: site.url,+ });+ if (!recorded)+ throw new TRPCError({+ code: 'INTERNAL_SERVER_ERROR',+ message: 'The share was published but could not be recorded on the artboard',+ });+ return { url: site.url };+ }++ async unpublish(id: string): Promise<void> {+ await this.deps.loadArtboard(id);+ const work = await this.workModel.findArtboardWork(id);+ if (!work?.metadata?.artboardPublish) return;+ if (!this.owns(work))+ throw new TRPCError({+ code: 'FORBIDDEN',+ message: 'Only the person who owns this artboard can stop sharing it',+ });++ await unpublishArtboardWork(+ { db: this.db, userId: this.userId, workspaceId: this.workspaceId },+ work,+ );+ await this.workModel.clearArtboardPublish(id);+ }+}diff --git a/apps/server/src/services/artboard/publish/offline.ts b/apps/server/src/services/artboard/publish/offline.tsnew file mode 100644index 00000000000..14f051842c0--- /dev/null+++ b/apps/server/src/services/artboard/publish/offline.ts@@ -0,0 +1,20 @@+import { unpublishCanvasSite } from '@/business/server/canvasPublish';+import type { ArtboardWork } from '@/database/models/work/artboard';+import type { LobeChatDatabase } from '@/database/type';++export interface ArtboardShareOwner {+ db: LobeChatDatabase;+ userId: string;+ workspaceId?: string;+}++// The deployment lives with whoever published it, not with the Work's current owner.+export const unpublishArtboardWork = async (owner: ArtboardShareOwner, work: ArtboardWork) => {+ const publish = work.metadata?.artboardPublish;+ if (!publish) return;+ await unpublishCanvasSite({+ ...owner,+ deploymentId: publish.deploymentId,+ userId: publish.publisherUserId,+ });+};diff --git a/apps/server/src/services/artboard/publish/publish.test.ts b/apps/server/src/services/artboard/publish/publish.test.tsnew file mode 100644index 00000000000..adb4bc86b40--- /dev/null+++ b/apps/server/src/services/artboard/publish/publish.test.ts@@ -0,0 +1,223 @@+// @vitest-environment node+import type { ArtboardBoardView, ArtboardItem } from '@lobechat/types';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { ArtboardPublishService } from '.';++const work = vi.hoisted(() => ({+ findArtboardWork: vi.fn(),+ recordArtboardPublish: vi.fn(),+ registerArtboard: vi.fn(),+}));++vi.mock('@/database/models/work', () => ({+ WorkModel: vi.fn(function WorkModel() {+ return work;+ }),+}));++const site = vi.hoisted(() => ({ publishArtboardSite: vi.fn() }));++vi.mock('@/business/server/canvasPublish', () => ({+ getArtboardViewerUrl: vi.fn(async () => 'https://static.example.com/artboard-viewer.js'),+ getCanvasPublishRuntimeUrl: vi.fn(),+ isCanvasPublishEnabled: () => true,+ publishArtboardSite: site.publishArtboardSite,+ unpublishCanvasSite: vi.fn(),+}));++const rect = { h: 400, w: 640, x: 0, y: 0 };++const board = (overrides: Partial<ArtboardBoardView>): ArtboardBoardView => ({+ expected: null,+ flowNodeId: null,+ groupId: null,+ id: 'brd_1',+ pageId: 'pg_1',+ rect,+ roundId: null,+ source: null,+ title: 'Board',+ type: 'decision',+ ...overrides,+});++const artboard = (boards: ArtboardBoardView[]): ArtboardItem => ({+ acceptanceId: null,+ content: { boards, edges: [], groups: [], pages: [], questions: [], rounds: [] },+ createdAt: new Date(),+ description: null,+ id: 'art_1',+ phase: 'discuss',+ projectId: 'prj_1',+ revision: 2,+ taskId: null,+ title: 'Onboarding',+ topicId: null,+ updatedAt: new Date(),+});++const fileRow = (path: string, hash = `h_${path}`) => ({+ contentType: path.endsWith('.png') ? 'image/png' : 'text/html',+ hash,+ path,+});++const htmlBoard = (id: string, path: string, title = 'Board') =>+ board({ id, source: { hash: `h_${path}`, kind: 'file', path }, title, type: 'html' });++const service = (boards: ArtboardBoardView[], deps = {}) =>+ new ArtboardPublishService({} as any, 'user_1', undefined, {+ listFiles: async () => [],+ loadArtboard: async () => artboard(boards),+ readFile: async () => new Uint8Array([1]),+ ...deps,+ });++beforeEach(() => {+ work.findArtboardWork.mockReset().mockResolvedValue(null);+ work.recordArtboardPublish.mockReset().mockResolvedValue({ id: 'work_1' });+ work.registerArtboard.mockReset();+ site.publishArtboardSite+ .mockReset()+ .mockResolvedValue({ deploymentId: 'dep_1', url: 'https://x' });+});++describe('ArtboardPublishService', () => {+ it('refuses a member who did not publish the share', async () => {+ work.findArtboardWork.mockResolvedValue({+ metadata: { artboardPublish: { deploymentId: 'dep_1', publisherUserId: 'user_2' } },+ url: 'https://x',+ userId: 'user_1',+ });++ await expect(service([board({})]).publish('art_1')).rejects.toMatchObject({+ code: 'FORBIDDEN',+ });+ expect(await service([board({})]).getPublish('art_1')).toMatchObject({ canPublish: false });+ });++ it('names the board whose source is gone', async () => {+ const boards = [board({ title: 'Checkout', type: 'html' })];++ await expect(service(boards).publish('art_1')).rejects.toMatchObject({+ code: 'PRECONDITION_FAILED',+ message: expect.stringContaining('Checkout'),+ });+ expect(site.publishArtboardSite).not.toHaveBeenCalled();+ });++ it('publishes a board whose file is missing; the viewer shows it as missing', async () => {+ const boards = [htmlBoard('a', 'pages/gone.html', 'Pricing')];++ await service(boards).publish('art_1');++ expect(site.publishArtboardSite).toHaveBeenCalledTimes(1);+ });++ it('ships every artboard file once, then records the share', async () => {+ const listFiles = async () => [+ fileRow('pages/a.html'),+ fileRow('pages/app.css'),+ fileRow('shots/home.png'),+ ];+ const readFile = vi.fn(async () => new Uint8Array([1]));+ const boards = [+ htmlBoard('a', 'pages/a.html'),+ htmlBoard('b', 'pages/a.html'),+ board({+ id: 'c',+ source: { hash: 'h_shots/home.png', kind: 'file', path: 'shots/home.png' },+ type: 'image',+ }),+ ];++ await service(boards, { listFiles, readFile }).publish('art_1');++ expect(readFile).toHaveBeenCalledTimes(3);+ const { bundle } = site.publishArtboardSite.mock.calls[0][0];+ expect(bundle.files.map((file: { path: string }) => file.path).toSorted()).toEqual([+ '/files/pages/a.html',+ '/files/pages/app.css',+ '/files/shots/home.png',+ ]);+ expect(work.registerArtboard).toHaveBeenCalledWith(+ expect.objectContaining({ artboardId: 'art_1', toolName: 'publishArtboard' }),+ );+ expect(work.recordArtboardPublish).toHaveBeenCalledWith(+ 'art_1',+ expect.objectContaining({ deploymentId: 'dep_1', publishedRevision: 2, url: 'https://x' }),+ );+ });++ it('reports updates once a file the shared pages load has changed', async () => {+ const boards = [htmlBoard('a', 'pages/a.html')];+ const published = [fileRow('pages/a.html'), fileRow('pages/app.css')];+ await service(boards, { listFiles: async () => published }).publish('art_1');+ const { snapshotHash } = work.recordArtboardPublish.mock.calls[0][1];+ work.findArtboardWork.mockResolvedValue({+ metadata: {+ artboardPublish: { deploymentId: 'dep_1', publisherUserId: 'user_1', snapshotHash },+ },+ url: 'https://x',+ userId: 'user_1',+ });++ const unchanged = await service(boards, { listFiles: async () => published }).getPublish(+ 'art_1',+ );+ const restyled = await service(boards, {+ listFiles: async () => [published[0], fileRow('pages/app.css', 'h_css_2')],+ }).getPublish('art_1');++ expect(unchanged).toMatchObject({ hasUpdates: false });+ expect(restyled).toMatchObject({ hasUpdates: true });+ });++ it('lets the person who shared the board update it after someone else edited the board', async () => {+ work.findArtboardWork.mockResolvedValue({+ metadata: { artboardPublish: { deploymentId: 'dep_1', publisherUserId: 'user_1' } },+ url: 'https://x',+ userId: 'user_2',+ });++ await service([board({})]).publish('art_1');++ expect(site.publishArtboardSite).toHaveBeenCalledWith(+ expect.objectContaining({ deploymentId: 'dep_1', userId: 'user_1' }),+ );+ expect(await service([board({})]).getPublish('art_1')).toMatchObject({ canPublish: true });+ });++ it('lets any editor share a board nobody has shared yet', async () => {+ work.findArtboardWork.mockResolvedValue({ metadata: null, url: null, userId: 'user_2' });++ await service([board({})]).publish('art_1');++ expect(work.recordArtboardPublish).toHaveBeenCalledWith(+ 'art_1',+ expect.objectContaining({ publisherUserId: 'user_1' }),+ );+ });++ it('fails when the share could not be recorded on the Work', async () => {+ work.recordArtboardPublish.mockResolvedValue(null);++ await expect(service([board({})]).publish('art_1')).rejects.toThrow();+ });++ it('names the file that can no longer be read', async () => {+ const boards = [htmlBoard('a', 'pages/a.html', 'Moodboard')];++ await expect(+ service(boards, {+ listFiles: async () => [fileRow('pages/a.html')],+ readFile: async () => undefined,+ }).publish('art_1'),+ ).rejects.toMatchObject({+ code: 'PRECONDITION_FAILED',+ message: expect.stringContaining('pages/a.html'),+ });+ expect(site.publishArtboardSite).not.toHaveBeenCalled();+ });+});diff --git a/apps/server/src/services/artboard/publish/snapshot.test.ts b/apps/server/src/services/artboard/publish/snapshot.test.tsnew file mode 100644index 00000000000..50027e71374--- /dev/null+++ b/apps/server/src/services/artboard/publish/snapshot.test.ts@@ -0,0 +1,219 @@+// @vitest-environment node+import type { ArtboardItem } from '@lobechat/types';+import { describe, expect, it } from 'vitest';++import { buildArtboardPublishSnapshot, hashArtboardSnapshot } from './snapshot';++const rect = { h: 400, w: 640, x: 0, y: 0 };++const item = (overrides: Partial<ArtboardItem['content']> = {}): ArtboardItem => ({+ acceptanceId: 'acc_1',+ content: {+ boards: [+ {+ expected: 'shows the empty state',+ flowNodeId: 'node_1',+ groupId: 'grp_options',+ id: 'brd_a',+ pageId: 'pg_1',+ rect,+ roundId: 'rnd_open',+ source: { hash: 'h_a', kind: 'file', path: 'pages/a.html' },+ title: 'Option A',+ type: 'html',+ },+ {+ expected: null,+ flowNodeId: null,+ groupId: 'grp_options',+ id: 'brd_b',+ pageId: 'pg_1',+ rect,+ roundId: 'rnd_done',+ source: { hash: 'h_b', kind: 'file', path: 'pages/b.html' },+ title: 'Option B',+ type: 'html',+ },+ {+ expected: null,+ flowNodeId: null,+ groupId: null,+ id: 'brd_img',+ pageId: 'pg_1',+ rect,+ roundId: null,+ source: { hash: 'h_img', kind: 'file', path: 'images/ref.png' },+ title: 'Reference',+ type: 'image',+ },+ {+ expected: null,+ flowNodeId: null,+ groupId: null,+ id: 'brd_decision',+ pageId: 'pg_1',+ rect,+ roundId: null,+ source: null,+ title: 'Pick one',+ type: 'decision',+ },+ ],+ edges: [+ {+ condition: null,+ flowEdgeId: 'flow_edge_1',+ from: 'brd_a',+ id: 'edg_1',+ isDefault: false,+ label: 'next',+ to: 'brd_b',+ },+ ],+ groups: [+ { desc: '', id: 'grp_options', kind: 'options', pageId: 'pg_1', rect, title: 'Options' },+ ],+ pages: [{ id: 'pg_1', name: 'Page 1', sortOrder: 0 }],+ questions: [+ {+ boardId: 'brd_a',+ content: 'secret agent question',+ groupId: null,+ id: 'q_1',+ pageId: 'pg_1',+ },+ ],+ rounds: [+ {+ batchId: 'batch_1',+ chosenBoardId: 'brd_a',+ id: 'rnd_open',+ pageId: 'pg_1',+ recommendedBoardId: 'brd_a',+ status: 'open',+ title: 'Direction',+ },+ {+ batchId: null,+ chosenBoardId: 'brd_b',+ id: 'rnd_done',+ pageId: 'pg_1',+ recommendedBoardId: null,+ status: 'submitted',+ title: 'Layout',+ },+ ],+ ...overrides,+ },+ createdAt: new Date('2026-11-01T00:00:00Z'),+ description: 'Onboarding directions',+ id: 'art_1',+ phase: 'discuss',+ projectId: 'prj_1',+ revision: 7,+ taskId: 'task_1',+ title: 'Onboarding',+ topicId: 'tpc_1',+ updatedAt: new Date('2026-11-02T00:00:00Z'),+});++const publishedAt = '2026-11-17T00:00:00.000Z';++describe('buildArtboardPublishSnapshot', () => {+ it('leaves out comments, acceptance fields and private ids', () => {+ const json = JSON.stringify(buildArtboardPublishSnapshot(item(), { publishedAt }));++ for (const leaked of [+ 'secret agent question',+ 'shows the empty state',+ 'node_1',+ 'flow_edge_1',+ 'acc_1',+ 'task_1',+ 'tpc_1',+ 'prj_1',+ 'batch_1',+ ])+ expect(json).not.toContain(leaked);+ });++ it('keeps only submitted choices', () => {+ const { rounds } = buildArtboardPublishSnapshot(item(), { publishedAt });++ expect(rounds.find((round) => round.id === 'rnd_open')?.chosenBoardId).toBeNull();+ expect(rounds.find((round) => round.id === 'rnd_open')?.recommendedBoardId).toBe('brd_a');+ expect(rounds.find((round) => round.id === 'rnd_done')?.chosenBoardId).toBe('brd_b');+ });++ it('keeps each board pointing at its artboard file and content hash', () => {+ const { boards } = buildArtboardPublishSnapshot(item(), { publishedAt });+ const sources = Object.fromEntries(boards.map((board) => [board.id, board.source]));++ expect(sources).toEqual({+ brd_a: { hash: 'h_a', kind: 'file', path: 'pages/a.html' },+ brd_b: { hash: 'h_b', kind: 'file', path: 'pages/b.html' },+ brd_decision: null,+ brd_img: { hash: 'h_img', kind: 'file', path: 'images/ref.png' },+ });+ });++ it('carries the title, description and pages', () => {+ const snapshot = buildArtboardPublishSnapshot(item(), { publishedAt });++ expect(snapshot).toMatchObject({+ description: 'Onboarding directions',+ pages: [{ id: 'pg_1', name: 'Page 1', sortOrder: 0 }],+ publishedAt,+ title: 'Onboarding',+ version: 1,+ });+ });+});++describe('hashArtboardSnapshot', () => {+ const files = [+ { hash: 'h_a', path: 'pages/a.html' },+ { hash: 'h_css', path: 'pages/app.css' },+ ];+ const hashOf = (artboard: ArtboardItem, fileList = files) =>+ hashArtboardSnapshot(buildArtboardPublishSnapshot(artboard, { publishedAt }), fileList);++ it('is the same for the same board published at different times', () => {+ const first = buildArtboardPublishSnapshot(item(), { publishedAt });+ const later = buildArtboardPublishSnapshot(item(), { publishedAt: '2026-12-01T00:00:00.000Z' });++ expect(hashArtboardSnapshot(later, files)).toBe(hashArtboardSnapshot(first, files));+ });++ it('changes when a submitted choice changes', () => {+ const base = item();+ const rechosen = item({+ rounds: base.content.rounds.map((round) =>+ round.id === 'rnd_done' ? { ...round, chosenBoardId: 'brd_a' } : round,+ ),+ });++ expect(hashOf(rechosen)).not.toBe(hashOf(base));+ });++ it('ignores a draft pick in an open round', () => {+ const base = item();+ const drafted = item({+ rounds: base.content.rounds.map((round) =>+ round.id === 'rnd_open' ? { ...round, chosenBoardId: 'brd_b' } : round,+ ),+ });++ expect(hashOf(drafted)).toBe(hashOf(base));+ });++ it('changes when a file the pages load changes, though no board moved', () => {+ const restyled = [files[0], { hash: 'h_css_2', path: 'pages/app.css' }];++ expect(hashOf(item(), restyled)).not.toBe(hashOf(item()));+ });++ it('does not depend on the order files are listed in', () => {+ expect(hashOf(item(), files.toReversed())).toBe(hashOf(item()));+ });+});diff --git a/apps/server/src/services/artboard/publish/snapshot.ts b/apps/server/src/services/artboard/publish/snapshot.tsnew file mode 100644index 00000000000..5297a4ac708--- /dev/null+++ b/apps/server/src/services/artboard/publish/snapshot.ts@@ -0,0 +1,67 @@+import { createHash } from 'node:crypto';++import type { ArtboardItem, ArtboardPublishSnapshot } from '@lobechat/types';++import { withoutDraftPicks } from '../view';++export interface ArtboardPublishFileRef {+ hash: string;+ path: string;+}++export const buildArtboardPublishSnapshot = (+ artboard: ArtboardItem,+ { publishedAt }: { publishedAt: string },+): ArtboardPublishSnapshot => {+ const { content } = withoutDraftPicks(artboard);+ return {+ boards: content.boards.map((board) => ({+ groupId: board.groupId,+ id: board.id,+ pageId: board.pageId,+ rect: board.rect,+ roundId: board.roundId,+ source: board.source,+ title: board.title,+ type: board.type,+ })),+ description: artboard.description,+ edges: content.edges.map((edge) => ({+ condition: edge.condition,+ from: edge.from,+ id: edge.id,+ isDefault: edge.isDefault,+ label: edge.label,+ to: edge.to,+ })),+ groups: content.groups,+ pages: content.pages,+ publishedAt,+ rounds: content.rounds.map((round) => ({+ chosenBoardId: round.chosenBoardId,+ id: round.id,+ pageId: round.pageId,+ recommendedBoardId: round.recommendedBoardId,+ status: round.status,+ title: round.title,+ })),+ title: artboard.title,+ version: 1,+ };+};++// Files are part of what was shared: a page's stylesheet or image can change without any board moving.+export const hashArtboardSnapshot = (+ { publishedAt: _, ...rest }: ArtboardPublishSnapshot,+ files: ArtboardPublishFileRef[],+) =>+ createHash('sha256')+ .update(+ JSON.stringify({+ ...rest,+ files: files+ .map(({ hash, path }) => [path, hash])+ .toSorted(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)),+ }),+ )+ .digest('hex');diff --git a/apps/server/src/services/artboard/sources.ts b/apps/server/src/services/artboard/sources.tsnew file mode 100644index 00000000000..f0f67b640c2--- /dev/null+++ b/apps/server/src/services/artboard/sources.ts@@ -0,0 +1,99 @@+import { createMediaFileItemsFromMessage } from '@lobechat/builtin-tool-lobe-agent';++import { getCanvasPublishRuntimeUrl } from '@/business/server/canvasPublish';+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 { createCanvasStorageService } from '@/server/services/canvas';+import { buildCanvasPublishBundle } from '@/server/services/canvas/publish';+import { FileService } from '@/server/services/file';++import type { ArtboardImageBytes, ArtboardImportedPage, ArtboardImportSource } from './files';++export const ARTBOARD_SOURCE_CONCURRENCY = 5;++export interface ArtboardSourceResolver {+ imageBytes: (fileRef: string) => Promise<ArtboardImageBytes | undefined>;+ importPage: (source: ArtboardImportSource) => Promise<ArtboardImportedPage | undefined>;+}++export interface ArtboardSourceScope {+ agentId?: string | null;+ threadId?: string | null;+ topicId?: string | null;+ userId: string;+ workspaceId?: string;+}++const MEDIA_REF_PATTERN = /^msg_[\da-z]+\.(?:audio|image|video)_\d+$/;++export const createArtboardSourceResolver = (+ db: LobeChatDatabase,+ scope: ArtboardSourceScope,+): ArtboardSourceResolver => {+ const { userId, workspaceId } = scope;+ const files = new FileModel(db, userId, workspaceId);+ let mediaFileIds: Promise<Map<string, string>> | undefined;++ const listMediaFileIds = async () => {+ if (!scope.topicId) return new Map<string, string>();+ 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))+ .flatMap((item) => (item.id ? [[item.ref, item.id] as const] : [])),+ );+ };++ return {+ imageBytes: async (fileRef) => {+ let fileId: string | undefined = fileRef;+ if (MEDIA_REF_PATTERN.test(fileRef)) {+ const pending = (mediaFileIds ??= listMediaFileIds());+ fileId = (await pending).get(fileRef);+ }+ if (!fileId) return;+ const file = await files.findById(fileId);+ if (!file?.fileType.startsWith('image/')) return;+ const bytes = await new FileService(db, userId, workspaceId).getFileByteArray(file.url);+ return { bytes, contentType: file.fileType };+ },+ // The same standalone bundle a published Canvas site serves: runtime injected, assets beside it.+ importPage: async ({ canvasId, version }) => {+ const works = new WorkModel(db, userId, workspaceId);+ const current = await works.findCanvas(canvasId);+ if (!current) return;+ const versionRow =+ version === undefined || version === current.version.version+ ? current.version+ : await works.findCanvasVersion(current.work.id, version);+ const canvas = versionRow?.metadata?.canvas;+ if (!canvas) return;+ const runtimeUrl = await getCanvasPublishRuntimeUrl(canvas.runtimeMajor);+ if (!runtimeUrl) return;+ const storage = createCanvasStorageService(db, current.work.userId, workspaceId);+ const bundle = await buildCanvasPublishBundle(+ storage,+ await storage.readManifest(canvas.manifestKey),+ runtimeUrl,+ );+ const encoder = new TextEncoder();+ return {+ assets: bundle.files.map((file) => ({+ bytes:+ file.encoding === 'base64'+ ? new Uint8Array(Buffer.from(file.content, 'base64'))+ : encoder.encode(file.content),+ path: file.path.replace(/^\/+/, ''),+ })),+ entry: encoder.encode(bundle.html),+ };+ },+ };+};diff --git a/apps/server/src/services/artboard/toolService.ts b/apps/server/src/services/artboard/toolService.tsnew file mode 100644index 00000000000..9159d56028d--- /dev/null+++ b/apps/server/src/services/artboard/toolService.ts@@ -0,0 +1,159 @@+import type {+ ArtboardToolFailure,+ ArtboardToolService,+ ArtboardToolSnapshot,+} from '@lobechat/builtin-tool-artboard';+import {+ artboardFileChangesSchema,+ type ArtboardItem,+ type ArtboardOp,+ artboardOpSchema,+} from '@lobechat/types';+import { z } from 'zod';++import type { LobeChatDatabase } from '@/database/type';++import type { ArtboardFileChanges } from './files';+import { type ArtboardContext, ArtboardService, ArtboardServiceError } from './index';++export interface ArtboardToolScope extends ArtboardContext {+ userId: string;+ workspaceId?: string;+}++const opsSchema = z.array(artboardOpSchema);++const toSnapshot = (artboard: ArtboardItem): ArtboardToolSnapshot => ({+ content: artboard.content,+ description: artboard.description,+ id: artboard.id,+ phase: artboard.phase,+ projectId: artboard.projectId,+ revision: artboard.revision,+ taskId: artboard.taskId,+ title: artboard.title,+});++const parseOps = (ops: unknown[] | undefined): ArtboardOp[] => {+ const parsed = opsSchema.safeParse(ops ?? []);+ if (parsed.success) return parsed.data;+ const issues = parsed.error.issues+ .map((issue) => `ops.${issue.path.join('.')}: ${issue.message}`)+ .join('; ');+ throw new ArtboardServiceError('invalid', `The ops are malformed: ${issues}`);+};++const parseFiles = (files: unknown): ArtboardFileChanges => {+ const parsed = artboardFileChangesSchema.safeParse(files ?? {});+ if (parsed.success) return parsed.data;+ throw new ArtboardServiceError(+ 'invalid',+ `The files are malformed: ${parsed.error.issues.map((issue) => `files.${issue.path.join('.')}: ${issue.message}`).join('; ')}. Each write is {path, content}, {path, fileRef} or {path, fromCanvas: {canvasId}}; each edit is {path, oldText, newText}.`,+ );+};++const toFiles = (rows: { hash: string; path: string; size: number }[]) =>+ rows.map(({ hash, path, size }) => ({ hash, path, size }));++const guard = async <T>(action: () => Promise<T>): Promise<T | ArtboardToolFailure> => {+ try {+ return await action();+ } catch (error) {+ if (!(error instanceof ArtboardServiceError)) throw error;+ const at = error.data.opIndex === undefined ? '' : ` (op ${error.data.opIndex})`;+ return { code: error.code, message: `${error.message}${at}`, ok: false };+ }+};++export const createArtboardToolService = (+ db: LobeChatDatabase,+ scope: ArtboardToolScope,+): ArtboardToolService => {+ const { userId, workspaceId, ...context } = scope;+ const service = new ArtboardService(db, userId, workspaceId, { context });++ return {+ askQuestion: ({ id, ...question }) =>+ guard(async () => ({+ commentId: (await service.askQuestion(id, question)).id,+ ok: true as const,+ })),+ create: (params) =>+ guard(async () => {+ const result = await service.create(+ {+ description: params.description,+ files: parseFiles(params.files),+ ops: parseOps(params.ops),+ taskId: params.taskId,+ title: params.title,+ },+ context,+ );+ return {+ artboard: toSnapshot(result.artboard),+ changedIds: result.changedIds,+ ok: true as const,+ task: { createdTask: result.createdTask, identifier: result.task.identifier },+ };+ }),+ list: () =>+ guard(async () => ({+ artboards: (await service.list(context)).map((artboard) => ({+ id: artboard.id,+ phase: artboard.phase,+ revision: artboard.revision,+ taskId: artboard.taskId,+ title: artboard.title,+ })),+ ok: true as const,+ })),+ listComments: (params) =>+ guard(async () => ({+ ok: true as const,+ threads: await service.takeUndeliveredComments(params.id),+ })),+ read: (params) =>+ guard(async () => {+ const [result, files] = await Promise.all([+ service.read(params.id),+ service.listFiles(params.id),+ ]);+ return { artboard: toSnapshot(result.artboard), files: toFiles(files), ok: true as const };+ }),+ readFile: (params) =>+ guard(async () => {+ const file = await service.readFile(params.id, params.path);+ return { content: file.content ?? null, ok: true as const, path: file.path };+ }),+ replyComment: (params) =>+ guard(async () => ({+ commentId: (await service.replyComment(params.commentId, { content: params.content })).id,+ ok: true as const,+ })),+ resolveComment: (params) =>+ guard(async () => ({+ commentId: (await service.resolveComment(params.commentId)).id,+ ok: true as const,+ })),+ update: (params) =>+ guard(async () => {+ const result = await service.update(+ params.id,+ params.revision,+ parseOps(params.ops),+ parseFiles(params.files),+ );+ return {+ artboard: toSnapshot(result.artboard),+ changedIds: result.changedIds,+ ok: true as const,+ };+ }),+ writeFiles: ({ id, ...files }) =>+ guard(async () => ({+ ok: true as const,+ paths: (await service.writeFiles(id, parseFiles(files))).files,+ })),+ };+};diff --git a/apps/server/src/services/artboard/view.ts b/apps/server/src/services/artboard/view.tsnew file mode 100644index 00000000000..66106cd0e4b--- /dev/null+++ b/apps/server/src/services/artboard/view.ts@@ -0,0 +1,145 @@+import type {+ ArtboardBoardSource,+ ArtboardCommentThreadView,+ ArtboardCommentView,+ ArtboardContent,+ ArtboardItem,+} from '@lobechat/types';++import type { ArtboardCommentRow, ArtboardRow } from '@/database/models/artboard';+import type { ArtboardCommentThread } from '@/database/models/artboard/comment';+import type { ArtboardStructure } from '@/database/models/artboard/structure';++import { toPageRect } from './layout';++export const describeArtboard = (content: ArtboardContent) =>+ `${content.groups.length} groups · ${content.boards.length} boards`;++export const toArtboardItem = (row: ArtboardRow, content: ArtboardContent): ArtboardItem => ({+ acceptanceId: row.acceptanceId,+ content,+ createdAt: row.createdAt,+ description: row.description,+ id: row.id,+ phase: row.phase,+ projectId: row.projectId,+ revision: row.revision,+ taskId: row.taskId,+ title: row.title,+ topicId: row.topicId,+ updatedAt: row.updatedAt,+});++export const toCommentView = (row: ArtboardCommentRow): ArtboardCommentView => ({+ authorAgentId: row.authorAgentId,+ authorUserId: row.authorUserId,+ content: row.content,+ createdAt: row.createdAt,+ id: row.id,+});++// A user may close an agent's question right after answering it; the answer still reaches the agent.+export const isThreadUnread = ({ replies, root }: ArtboardCommentThread) =>+ (!root.resolvedAt || !!root.authorAgentId) &&+ [root, ...replies].some((comment) => !comment.authorAgentId && !comment.deliveredAt);++const anchorOf = ({ anchor, boardId, groupId, metadata }: ArtboardCommentThread['root']) => {+ const space = metadata?.anchorSpace;+ const orphaned = (space === 'board' && !boardId) || (space === 'group' && !groupId);+ return orphaned ? null : (anchor ?? null);+};++export const toCommentThreadView = (+ thread: ArtboardCommentThread,+ stale: boolean,+): ArtboardCommentThreadView => ({+ ...toCommentView(thread.root),+ anchor: anchorOf(thread.root),+ boardId: thread.root.boardId,+ groupId: thread.root.groupId,+ pageId: thread.root.pageId,+ replies: thread.replies.map(toCommentView),+ resolvedAt: thread.root.resolvedAt,+ stale,+ unread: isThreadUnread(thread),+});++export const toArtboardContent = (+ structure: ArtboardStructure,+ openThreads: ArtboardCommentThread[],+ hashes: ReadonlyMap<string, string>,+): ArtboardContent => {+ const groupRects = new Map(structure.groups.map((group) => [group.id, group.rect]));++ // A board may point at a file not written yet, or one deleted since: hash null, nothing to show.+ const sourceOf = (board: ArtboardStructure['boards'][number]): ArtboardBoardSource | null =>+ board.sourcePath+ ? { hash: hashes.get(board.sourcePath) ?? null, kind: 'file', path: board.sourcePath }+ : null;++ return {+ boards: structure.boards.map((board) => ({+ expected: board.expected,+ flowNodeId: board.acceptanceFlowNodeId,+ groupId: board.groupId,+ id: board.id,+ pageId: board.pageId,+ rect: toPageRect(board.rect, board.groupId ? groupRects.get(board.groupId) : undefined),+ roundId: board.roundId,+ source: sourceOf(board),+ title: board.title,+ type: board.type,+ })),+ edges: structure.edges.map((edge) => ({+ condition: edge.condition,+ flowEdgeId: edge.acceptanceFlowEdgeId,+ from: edge.sourceBoardId,+ id: edge.id,+ isDefault: edge.isDefault,+ label: edge.label,+ to: edge.targetBoardId,+ })),+ groups: structure.groups.map((group) => ({+ desc: group.description ?? '',+ id: group.id,+ kind: group.kind,+ pageId: group.pageId,+ rect: group.rect,+ title: group.title,+ })),+ pages: structure.pages.map((page) => ({+ id: page.id,+ name: page.name,+ sortOrder: page.sortOrder,+ })),+ questions: openThreads+ .filter((thread) => thread.root.authorAgentId)+ .map(({ replies, root }) => ({+ answered: replies.some((reply) => !reply.authorAgentId),+ boardId: root.boardId,+ content: root.content,+ groupId: root.groupId,+ id: root.id,+ pageId: root.pageId,+ })),+ rounds: structure.rounds.map((round) => ({+ batchId: round.metadata?.batchId ?? null,+ chosenBoardId: round.chosenBoardId,+ id: round.id,+ pageId: round.pageId,+ recommendedBoardId: round.recommendedBoardId,+ status: round.status,+ title: round.title,+ })),+ };+};++export const withoutDraftPicks = (artboard: ArtboardItem): ArtboardItem => ({+ ...artboard,+ content: {+ ...artboard.content,+ rounds: artboard.content.rounds.map((round) =>+ round.status === 'open' ? { ...round, chosenBoardId: null } : round,+ ),+ },+});diff --git a/apps/server/src/services/canvas/publish.test.ts b/apps/server/src/services/canvas/publish.test.tsnew file mode 100644index 00000000000..a8a820b470f--- /dev/null+++ b/apps/server/src/services/canvas/publish.test.ts@@ -0,0 +1,36 @@+// @vitest-environment node+import { afterEach, describe, expect, it, vi } from 'vitest';++import { resolveCanvasPublicRuntimeUrl, resolvePublicRuntimeUrl } from './publish';++const revision = 'b'.repeat(64);++const serveManifest = (base: string) =>+ vi.stubGlobal(+ 'fetch',+ vi.fn(async (url: string) =>+ url === `${base}/v1/manifest.json`+ ? Response.json({ files: [], major: 1, revision })+ : new Response(null, { status: 404 }),+ ),+ );++afterEach(() => vi.unstubAllGlobals());++describe('resolvePublicRuntimeUrl', () => {+ it('points at the named file of the published revision', async () => {+ serveManifest('http://static.localhost/artboard-viewer');++ await expect(+ resolvePublicRuntimeUrl(1, 'http://static.localhost/artboard-viewer/', 'artboard-viewer.js'),+ ).resolves.toBe(`http://static.localhost/artboard-viewer/v1/${revision}/artboard-viewer.js`);+ });++ it('keeps the canvas runtime file name for canvases', async () => {+ serveManifest('http://static.localhost/canvas-runtime');++ await expect(+ resolveCanvasPublicRuntimeUrl(1, 'http://static.localhost/canvas-runtime'),+ ).resolves.toBe(`http://static.localhost/canvas-runtime/v1/${revision}/canvas-runtime.js`);+ });+});diff --git a/apps/server/src/services/canvas/publish.ts b/apps/server/src/services/canvas/publish.tsindex 8b5a0e8d196..e12bb366160 100644--- a/apps/server/src/services/canvas/publish.ts+++ b/apps/server/src/services/canvas/publish.ts@@ -9,9 +9,10 @@ import { z } from 'zod';import type { CanvasStorageService } from './storage';-export const resolveCanvasPublicRuntimeUrl = async (+export const resolvePublicRuntimeUrl = async (major: number,- baseUrl?: string,+ baseUrl: string | undefined,+ fileName: string,): Promise<string | undefined> => {if (!baseUrl || !/^https?:\/\//.test(baseUrl)) return;const base = `${baseUrl.replace(/\/+$/, '')}/v${major}`;@@ -19,13 +20,16 @@ export const resolveCanvasPublicRuntimeUrl = async (cache: 'no-store',signal: AbortSignal.timeout(15_000),});- if (!response.ok) throw new Error(`Canvas runtime v${major} has not been published`);+ if (!response.ok) throw new Error(`${fileName} v${major} has not been published`);const manifest = z.object({ major: z.literal(major), revision: z.string().regex(/^[\da-f]{64}$/) }).parse(await response.json());- return `${base}/${manifest.revision}/canvas-runtime.js`;+ return `${base}/${manifest.revision}/${fileName}`;};+export const resolveCanvasPublicRuntimeUrl = (major: number, baseUrl?: string) =>+ resolvePublicRuntimeUrl(major, baseUrl, 'canvas-runtime.js');+const injectCanvasRuntime = (html: string, runtimeUrl: string) => {const injection = `<script defer src="${runtimeUrl}"></script>`;const head = /<head(?:\s[^>]*)?>/i.exec(html);diff --git a/apps/server/src/services/file/impls/s3.ts b/apps/server/src/services/file/impls/s3.tsindex 621c7939906..dff93a4a293 100644--- a/apps/server/src/services/file/impls/s3.ts+++ b/apps/server/src/services/file/impls/s3.ts@@ -56,6 +56,10 @@ export class S3StaticFileImpl implements FileServiceImpl {return this.s3.listFileKeys(prefix, limit);}+ async listFileObjects(prefix: string, limit?: number) {+ return this.s3.listFileObjects(prefix, limit);+ }+async getFileContent(key: string, byteLength?: number): Promise<string> {return byteLength === undefined? this.s3.getFileContent(key)diff --git a/apps/server/src/services/file/impls/type.ts b/apps/server/src/services/file/impls/type.tsindex 9f190096e32..9dd483d2721 100644--- a/apps/server/src/services/file/impls/type.ts+++ b/apps/server/src/services/file/impls/type.ts@@ -81,6 +81,14 @@ export interface FileServiceImpl {*/listFileKeys: (prefix: string, limit?: number) => Promise<string[]>;+ /**+ * Like listFileKeys, with each object's ETag (unquoted) and size+ */+ listFileObjects: (+ prefix: string,+ limit?: number,+ ) => Promise<{ etag: string; key: string; size: number }[]>;+/*** Upload buffer with specified content type (for any file type)*/diff --git a/apps/server/src/services/file/index.ts b/apps/server/src/services/file/index.tsindex f40d434ba43..2ded0f0b322 100644--- a/apps/server/src/services/file/index.ts+++ b/apps/server/src/services/file/index.ts@@ -102,6 +102,13 @@ export class FileService {return this.impl.listFileKeys(prefix, limit);}+ /**+ * Like listFileKeys, with each object's ETag (unquoted) and size+ */+ public async listFileObjects(prefix: string, limit?: number) {+ return this.impl.listFileObjects(prefix, limit);+ }+/*** Get file content*/diff --git a/apps/server/src/services/message/__tests__/index.test.ts b/apps/server/src/services/message/__tests__/index.test.tsindex d52702d56f5..286110078e5 100644--- a/apps/server/src/services/message/__tests__/index.test.ts+++ b/apps/server/src/services/message/__tests__/index.test.ts@@ -309,6 +309,36 @@ describe('MessageService', () => {});});+ describe('returned message list', () => {+ it('includes the Work types the client opted into', async () => {+ vi.mocked(mockMessageModel.query).mockResolvedValue([]);+ const service = new MessageService(mockDB, userId, undefined, {+ workTypeOptIn: { includeArtboardWorks: true, includeFileWorks: true },+ });++ await service.updateMessage('msg-1', { content: 'x' } as any, { topicId: 'topic-1' });++ expect(mockMessageModel.query).toHaveBeenCalledWith(+ expect.objectContaining({+ includeArtboardWorks: true,+ includeFileWorks: true,+ topicId: 'topic-1',+ }),+ expect.anything(),+ );+ });++ it('keeps the legacy Work set for a client that sent no opt-in', async () => {+ vi.mocked(mockMessageModel.query).mockResolvedValue([]);++ await messageService.updateMessage('msg-1', { content: 'x' } as any, { topicId: 'topic-1' });++ const [params] = vi.mocked(mockMessageModel.query).mock.calls[0];+ expect(params).not.toHaveProperty('includeArtboardWorks');+ expect(params).not.toHaveProperty('includeFileWorks');+ });+ });+describe('updateMessage', () => {it('normalizes a known error from a legacy client before persistence', async () => {await messageService.updateMessage(diff --git a/apps/server/src/services/message/index.ts b/apps/server/src/services/message/index.tsindex 4dca1e8796c..8b29321f73a 100644--- a/apps/server/src/services/message/index.ts+++ b/apps/server/src/services/message/index.ts@@ -13,6 +13,7 @@ import {import { createTimingHelpers, getDurationMs } from '@lobechat/utils';import { MessageModel } from '@/database/models/message';+import type { WorkTypeOptIn } from '@/database/models/work/registry';import { FileService } from '../file';import { TrashService } from '../trash';@@ -109,8 +110,15 @@ export class MessageService {private fileService: FileService;private compressionRepository: CompressionRepository;private trashService: TrashService;-- constructor(db: LobeChatDatabase, userId: string, workspaceId?: string) {+ private workTypeOptIn: WorkTypeOptIn;++ constructor(+ db: LobeChatDatabase,+ userId: string,+ workspaceId?: string,+ options: { workTypeOptIn?: WorkTypeOptIn } = {},+ ) {+ this.workTypeOptIn = options.workTypeOptIn ?? {};this.messageModel = new MessageModel(db, userId, workspaceId);this.fileService = new FileService(db, userId, workspaceId);this.compressionRepository = new CompressionRepository(db, userId, workspaceId);@@ -135,6 +143,10 @@ export class MessageService {};}+ private withWorkTypes<T extends object>(params: T): T & WorkTypeOptIn {+ return { ...params, ...this.workTypeOptIn };+ }+/*** Query messages and return response with success status (used after mutations)* Prioritize agentId, fallback to sessionId if not provided (for backwards compatibility)@@ -157,7 +169,7 @@ export class MessageService {const queryStartedAt = Date.now();const modelTiming = createModelTiming(options, 'lambda.message.update.queryMessages');const messages = await this.messageModel.query(- { agentId, groupId, sessionId, threadId, topicId },+ this.withWorkTypes({ agentId, groupId, sessionId, threadId, topicId }),{...this.getQueryOptions(),...(modelTiming ? { timing: modelTiming } : {}),@@ -334,14 +346,14 @@ export class MessageService {// 2. Query all messages for this agent/topic// Use agentId field for queryconst messages = await this.messageModel.query(- {+ this.withWorkTypes({agentId: params.agentId,current: 0,groupId: params.groupId,pageSize: 9999,threadId: params.threadId,topicId: params.topicId,- },+ }),{postProcessUrl: this.postProcessUrl,},@@ -544,7 +556,7 @@ export class MessageService {}> {// 1. Get messages that need to be summarized (before marking them as compressed)const allMessages = await this.messageModel.query(- { topicId, ...options },+ this.withWorkTypes({ topicId, ...options }),this.getQueryOptions(),);@@ -561,7 +573,10 @@ export class MessageService {});// 3. Query updated messages (compressed messages will be grouped)- const messages = await this.messageModel.query({ topicId, ...options }, this.getQueryOptions());+ const messages = await this.messageModel.query(+ this.withWorkTypes({ topicId, ...options }),+ this.getQueryOptions(),+ );return {messageGroupId,@@ -601,7 +616,10 @@ export class MessageService {// 2. Query final messagesconst queryOptions = { agentId, groupId, threadId, topicId };- const finalMessages = await this.messageModel.query(queryOptions, this.getQueryOptions());+ const finalMessages = await this.messageModel.query(+ this.withWorkTypes(queryOptions),+ this.getQueryOptions(),+ );return {messages: finalMessages,@@ -619,7 +637,10 @@ export class MessageService {): Promise<{ messages: UIChatMessage[] }> {await this.compressionRepository.updateMetadata(messageGroupId, metadata);- const messages = await this.messageModel.query(context, this.getQueryOptions());+ const messages = await this.messageModel.query(+ this.withWorkTypes(context),+ this.getQueryOptions(),+ );return { messages };}@@ -638,7 +659,10 @@ export class MessageService {await this.compressionRepository.deleteCompressionGroup(messageGroupId);// Query updated messages- const messages = await this.messageModel.query(context, this.getQueryOptions());+ const messages = await this.messageModel.query(+ this.withWorkTypes(context),+ this.getQueryOptions(),+ );return { messages, success: true };}diff --git a/apps/server/src/services/toolExecution/serverRuntimes/artboard.ts b/apps/server/src/services/toolExecution/serverRuntimes/artboard.tsnew file mode 100644index 00000000000..70290b60ea7--- /dev/null+++ b/apps/server/src/services/toolExecution/serverRuntimes/artboard.ts@@ -0,0 +1,27 @@+import { ArtboardIdentifier } from '@lobechat/builtin-tool-artboard';+import { ArtboardExecutionRuntime } from '@lobechat/builtin-tool-artboard/executionRuntime';++import { createArtboardToolService } from '@/server/services/artboard/toolService';++import { resolveContentWorkspaceId } from './resolveWorkspaceScope';+import { type ServerRuntimeRegistration } from './types';++export const artboardRuntime: ServerRuntimeRegistration = {+ factory: async (context) => {+ if (!context.userId || !context.serverDB) {+ throw new Error('userId and serverDB are required for Artboard tool execution');+ }++ return new ArtboardExecutionRuntime(+ createArtboardToolService(context.serverDB, {+ agentId: context.agentId,+ taskId: context.taskId,+ threadId: context.threadId,+ topicId: context.topicId,+ userId: context.userId,+ workspaceId: await resolveContentWorkspaceId(context),+ }),+ );+ },+ identifier: ArtboardIdentifier,+};diff --git a/apps/server/src/services/toolExecution/serverRuntimes/index.ts b/apps/server/src/services/toolExecution/serverRuntimes/index.tsindex 163c5b96c80..0f7724d97e9 100644--- a/apps/server/src/services/toolExecution/serverRuntimes/index.ts+++ b/apps/server/src/services/toolExecution/serverRuntimes/index.ts@@ -21,6 +21,7 @@ import { agentSignalFeedbackIntentRuntime } from './agentSignalFeedbackIntent';import { agentSignalReflectionRuntime } from './agentSignalReflection';import { agentSignalReviewRuntime } from './agentSignalReview';import { agentSignalSkillManagementRuntime } from './agentSignalSkillManagement';+import { artboardRuntime } from './artboard';import { attachmentsRuntime } from './attachments';import { auvRuntime } from './auv';import { briefRuntime } from './brief';@@ -101,6 +102,7 @@ registerRuntimes([taskRuntime,userInteractionRuntime,credsRuntime,+ artboardRuntime,canvasRuntime,dashboardRuntime,groupAgentBuilderRuntime,diff --git a/apps/server/src/services/workRegistration/registerWorksForOperation.test.ts b/apps/server/src/services/workRegistration/registerWorksForOperation.test.tsindex cde897af492..d35b483e02b 100644--- a/apps/server/src/services/workRegistration/registerWorksForOperation.test.ts+++ b/apps/server/src/services/workRegistration/registerWorksForOperation.test.ts@@ -4,13 +4,13 @@ import { MessageModel } from '@/database/models/message';import { WorkModel } from '@/database/models/work';import { redeployFileWork, registerWorksForOperation } from './registerWorksForOperation';-import { stateHasEntityFileEdits } from './stateHasEntityFileEdits';const {mockFindById,mockListOperationTree,mockListPlugins,mockRegisterFile,+ mockRegisterShellArtboardResult,mockRegisterShellGithubResult,mockFindFileVersionByToolCall,mockExportAndUploadFile,@@ -26,6 +26,7 @@ const {mockListOperationTree: vi.fn(),mockListPlugins: vi.fn(),mockRegisterFile: vi.fn(),+ mockRegisterShellArtboardResult: vi.fn(),mockRegisterShellGithubResult: vi.fn(),mockUpdateMessage: vi.fn(),}));@@ -54,6 +55,7 @@ vi.mock('@/database/models/work', () => ({return {findFileVersionByToolCall: mockFindFileVersionByToolCall,registerFile: mockRegisterFile,+ registerShellArtboardResult: mockRegisterShellArtboardResult,registerShellGithubResult: mockRegisterShellGithubResult,};}),@@ -740,274 +742,31 @@ describe('redeployFileWork', () => {});});-describe('stateHasEntityFileEdits', () => {- const sandboxCall = (id: string, apiName: string, args: unknown) => ({- function: {- arguments: JSON.stringify(args),- name: `lobe-cloud-sandbox____${apiName}____builtin`,- },- id,- type: 'function',- });-- const stateWith = (toolCalls: unknown[]) => ({- messages: [- { content: 'make me a deck', role: 'user' },- { content: '', role: 'assistant', tool_calls: toolCalls },- { content: 'ok', role: 'tool', tool_call_id: 't1' },- ],- });-- it('detects an entity-format sandbox write', () => {- expect(- stateHasEntityFileEdits(- stateWith([sandboxCall('t1', 'writeFile', { path: '/w/deck.pptx' })]),- ),- ).toBe(true);- });-- it('ignores non-entity files (html / md)', () => {- expect(- stateHasEntityFileEdits(- stateWith([- sandboxCall('t1', 'writeFile', { path: '/w/index.html' }),- sandboxCall('t2', 'editFile', { path: '/w/notes.md' }),- ]),- ),- ).toBe(false);- });-- it('ignores non-sandbox tool calls, even with entity-looking arguments', () => {- expect(- stateHasEntityFileEdits(- stateWith([- {- function: {- arguments: JSON.stringify({ file_path: '/w/deck.pptx' }),- name: 'claude-code____Write____builtin',- },- id: 't1',- type: 'function',- },- ]),- ),- ).toBe(false);- });-- it('returns false for empty or malformed state', () => {- expect(stateHasEntityFileEdits(undefined)).toBe(false);- expect(stateHasEntityFileEdits({})).toBe(false);- expect(stateHasEntityFileEdits({ messages: 'nope' })).toBe(false);- expect(- stateHasEntityFileEdits(- stateWith([- { function: { arguments: '{not json', name: 'lobe-cloud-sandbox____writeFile' } },- ]),- ),- ).toBe(false);- });-- it('detects a moveFiles rename onto an entity destination from its arguments', () => {- // moveFiles is only classifiable from its tool RESULT, which the pure state- // scan lacks — the predictor over-approximates from the requested- // destinations instead (a failed/rejected move still counts).- expect(- stateHasEntityFileEdits(- stateWith([- sandboxCall('t1', 'moveFiles', {- operations: [{ destination: '/w/deck.pptx', source: '/w/draft.tmp' }],- }),- ]),- ),- ).toBe(true);- });-- it('ignores moveFiles calls with only non-entity destinations or malformed args', () => {- expect(- stateHasEntityFileEdits(- stateWith([- sandboxCall('t1', 'moveFiles', {- operations: [{ destination: '/w/archive/notes.md', source: '/w/notes.md' }],- }),- {- function: {- arguments: '{not json',- name: 'lobe-cloud-sandbox____moveFiles____builtin',- },- id: 't2',- type: 'function',- },- ]),- ),- ).toBe(false);- });-- it('detects entity edits inside conversation-flow grouped nodes (children[].tools)', () => {- // After a tool batch the runtime re-queries state.messages with- // `flatten: true`, folding this run's turn into an assistantGroup — the- // sandbox calls then live on children[].tools, not message.tool_calls.- const grouped = {- children: [- {- tools: [- {- apiName: 'writeFile',- arguments: JSON.stringify({ path: '/w/deck.pptx' }),- id: 't1',- identifier: 'lobe-cloud-sandbox',- result: { state: { path: '/w/deck.pptx', success: true } },- },- ],- },- ],- role: 'assistantGroup',- };- expect(- stateHasEntityFileEdits({ messages: [{ content: 'make a deck', role: 'user' }, grouped] }),- ).toBe(true);- });-- it('classifies a grouped moveFiles rename from its result state', () => {- const grouped = {- children: [- {- tools: [- {- apiName: 'moveFiles',- arguments: JSON.stringify({- operations: [{ destination: '/w/deck.pptx', source: '/w/draft.tmp' }],- }),- id: 't1',- identifier: 'lobe-cloud-sandbox',- result: {- state: {- results: [{ destination: '/w/deck.pptx', source: '/w/draft.tmp', success: true }],- },- },- },- ],- },- ],- role: 'assistantGroup',- };- expect(- stateHasEntityFileEdits({ messages: [{ content: 'rename it', role: 'user' }, grouped] }),- ).toBe(true);- });-- it('ignores entity edits from PREVIOUS turns (before the last user message)', () => {- // A past run's entity edit already registered on its own completion —- // counting it would permanently disable the early publish for the topic.- const pastGroup = {- children: [- {- tools: [- {- apiName: 'writeFile',- arguments: JSON.stringify({ path: '/w/old-deck.pptx' }),- id: 't1',- identifier: 'lobe-cloud-sandbox',- result: { state: { path: '/w/old-deck.pptx', success: true } },- },- ],- },- ],- role: 'assistantGroup',- };- expect(- stateHasEntityFileEdits({- messages: [- { content: 'make a deck', role: 'user' },- pastGroup,- { content: 'now just summarize it', role: 'user' },- { content: 'summary...', role: 'assistant' },- ],- }),- ).toBe(false);- });-- it('detects an entity exportFile call from its arguments (raw and grouped shapes)', () => {- // Raw tool_calls shape.- expect(- stateHasEntityFileEdits(- stateWith([sandboxCall('t1', 'exportFile', { path: '/workspace/deck.pptx' })]),- ),- ).toBe(true);- // Grouped (assistantGroup children[].tools) shape.- const grouped = {- children: [- {- tools: [- {- apiName: 'exportFile',- arguments: JSON.stringify({ path: '/workspace/report.pdf' }),- id: 't1',- identifier: 'lobe-cloud-sandbox',- },- ],- },- ],- role: 'assistantGroup',- };- expect(- stateHasEntityFileEdits({ messages: [{ content: 'export it', role: 'user' }, grouped] }),- ).toBe(true);- // Non-entity export keeps the early publish.- expect(- stateHasEntityFileEdits(- stateWith([sandboxCall('t1', 'exportFile', { path: '/workspace/notes.txt' })]),+describe('registerWorksForOperation · shell artboard works', () => {+ it('hands a codex lh artboard create to the artboard scanner, not the github one', async () => {+ mockRegisterShellArtboardResult.mockResolvedValue({ id: 'work-artboard' });+ mockListPlugins.mockResolvedValue([+ codexCommandRow(+ 'a',+ `lh artboard create --title '首次进入'`,+ 'artboard art_1 · revision 1 · 2 groups · 4 frames\n',),- ).toBe(false);- });+ ]);- it('detects an entity lobe-skills exportFile call (raw and grouped shapes)', () => {- const skillsCall = (id: string, args: unknown) => ({- function: { arguments: JSON.stringify(args), name: 'lobe-skills____exportFile____builtin' },- id,- type: 'function',+ const outcome = await registerWorksForOperation({+ ...baseParams,+ assistantMessageId: 'msg-assistant',});- // Raw tool_calls shape.- expect(- stateHasEntityFileEdits(- stateWith([skillsCall('t1', { filename: 'deck.pptx', path: '/workspace/deck.pptx' })]),- ),- ).toBe(true);- // Grouped (assistantGroup children[].tools) shape.- const grouped = {- children: [- {- tools: [- {- apiName: 'exportFile',- arguments: JSON.stringify({ filename: 'report.pdf', path: '/workspace/report.pdf' }),- id: 't1',- identifier: 'lobe-skills',- },- ],- },- ],- role: 'assistantGroup',- };- expect(- stateHasEntityFileEdits({ messages: [{ content: 'export it', role: 'user' }, grouped] }),- ).toBe(true);- // Non-entity skills export keeps the early publish.- expect(- stateHasEntityFileEdits(- stateWith([skillsCall('t1', { filename: 'notes.txt', path: '/workspace/notes.txt' })]),- ),- ).toBe(false);- });- it('detects an entity edit mixed among non-entity edits', () => {- expect(- stateHasEntityFileEdits(- stateWith([- sandboxCall('t1', 'writeFile', { path: '/w/notes.md' }),- sandboxCall('t2', 'writeFile', { path: '/w/report.xlsx' }),- ]),- ),- ).toBe(true);+ expect(mockRegisterShellGithubResult).not.toHaveBeenCalled();+ expect(mockRegisterShellArtboardResult).toHaveBeenCalledWith(+ expect.objectContaining({+ data: expect.objectContaining({ command: `lh artboard create --title '首次进入'` }),+ rootOperationId: 'op-1',+ toolIdentifier: 'codex',+ }),+ );+ expect(outcome).toEqual({ anchorMessageId: 'msg-assistant', attempted: 1, failed: 0 });});});diff --git a/apps/server/src/services/workRegistration/shellWorkScanners/artboard.ts b/apps/server/src/services/workRegistration/shellWorkScanners/artboard.tsnew file mode 100644index 00000000000..59da3449500--- /dev/null+++ b/apps/server/src/services/workRegistration/shellWorkScanners/artboard.ts@@ -0,0 +1,7 @@+import type { ShellWorkScanner } from './types';++export const artboardShellWorkScanner: ShellWorkScanner = {+ matches: (command) => /artboard (?:create|update)\b/.test(command),+ name: 'artboard',+ register: ({ workModel, ...input }) => workModel.registerShellArtboardResult(input),+};diff --git a/apps/server/src/services/workRegistration/shellWorkScanners/index.ts b/apps/server/src/services/workRegistration/shellWorkScanners/index.tsindex 5c3644db310..739cebf3e5b 100644--- a/apps/server/src/services/workRegistration/shellWorkScanners/index.ts+++ b/apps/server/src/services/workRegistration/shellWorkScanners/index.ts@@ -1,3 +1,4 @@+import { artboardShellWorkScanner } from './artboard';import { githubShellWorkScanner } from './github';import { githubPushShellWorkScanner } from './githubPush';import type { ShellWorkScanner } from './types';@@ -12,5 +13,6 @@ export type { ShellWorkScanner } from './types';*/export const SHELL_WORK_SCANNERS: ShellWorkScanner[] = [githubShellWorkScanner,+ artboardShellWorkScanner,githubPushShellWorkScanner,];diff --git a/apps/server/src/services/workRegistration/stateHasEntityFileEdits.test.ts b/apps/server/src/services/workRegistration/stateHasEntityFileEdits.test.tsnew file mode 100644index 00000000000..59b49df9f93--- /dev/null+++ b/apps/server/src/services/workRegistration/stateHasEntityFileEdits.test.ts@@ -0,0 +1,274 @@+import { describe, expect, it } from 'vitest';++import { stateHasEntityFileEdits } from './stateHasEntityFileEdits';++describe('stateHasEntityFileEdits', () => {+ const sandboxCall = (id: string, apiName: string, args: unknown) => ({+ function: {+ arguments: JSON.stringify(args),+ name: `lobe-cloud-sandbox____${apiName}____builtin`,+ },+ id,+ type: 'function',+ });++ const stateWith = (toolCalls: unknown[]) => ({+ messages: [+ { content: 'make me a deck', role: 'user' },+ { content: '', role: 'assistant', tool_calls: toolCalls },+ { content: 'ok', role: 'tool', tool_call_id: 't1' },+ ],+ });++ it('detects an entity-format sandbox write', () => {+ expect(+ stateHasEntityFileEdits(+ stateWith([sandboxCall('t1', 'writeFile', { path: '/w/deck.pptx' })]),+ ),+ ).toBe(true);+ });++ it('ignores non-entity files (html / md)', () => {+ expect(+ stateHasEntityFileEdits(+ stateWith([+ sandboxCall('t1', 'writeFile', { path: '/w/index.html' }),+ sandboxCall('t2', 'editFile', { path: '/w/notes.md' }),+ ]),+ ),+ ).toBe(false);+ });++ it('ignores non-sandbox tool calls, even with entity-looking arguments', () => {+ expect(+ stateHasEntityFileEdits(+ stateWith([+ {+ function: {+ arguments: JSON.stringify({ file_path: '/w/deck.pptx' }),+ name: 'claude-code____Write____builtin',+ },+ id: 't1',+ type: 'function',+ },+ ]),+ ),+ ).toBe(false);+ });++ it('returns false for empty or malformed state', () => {+ expect(stateHasEntityFileEdits(undefined)).toBe(false);+ expect(stateHasEntityFileEdits({})).toBe(false);+ expect(stateHasEntityFileEdits({ messages: 'nope' })).toBe(false);+ expect(+ stateHasEntityFileEdits(+ stateWith([+ { function: { arguments: '{not json', name: 'lobe-cloud-sandbox____writeFile' } },+ ]),+ ),+ ).toBe(false);+ });++ it('detects a moveFiles rename onto an entity destination from its arguments', () => {+ // moveFiles is only classifiable from its tool RESULT, which the pure state+ // scan lacks — the predictor over-approximates from the requested+ // destinations instead (a failed/rejected move still counts).+ expect(+ stateHasEntityFileEdits(+ stateWith([+ sandboxCall('t1', 'moveFiles', {+ operations: [{ destination: '/w/deck.pptx', source: '/w/draft.tmp' }],+ }),+ ]),+ ),+ ).toBe(true);+ });++ it('ignores moveFiles calls with only non-entity destinations or malformed args', () => {+ expect(+ stateHasEntityFileEdits(+ stateWith([+ sandboxCall('t1', 'moveFiles', {+ operations: [{ destination: '/w/archive/notes.md', source: '/w/notes.md' }],+ }),+ {+ function: {+ arguments: '{not json',+ name: 'lobe-cloud-sandbox____moveFiles____builtin',+ },+ id: 't2',+ type: 'function',+ },+ ]),+ ),+ ).toBe(false);+ });++ it('detects entity edits inside conversation-flow grouped nodes (children[].tools)', () => {+ // After a tool batch the runtime re-queries state.messages with+ // `flatten: true`, folding this run's turn into an assistantGroup — the+ // sandbox calls then live on children[].tools, not message.tool_calls.+ const grouped = {+ children: [+ {+ tools: [+ {+ apiName: 'writeFile',+ arguments: JSON.stringify({ path: '/w/deck.pptx' }),+ id: 't1',+ identifier: 'lobe-cloud-sandbox',+ result: { state: { path: '/w/deck.pptx', success: true } },+ },+ ],+ },+ ],+ role: 'assistantGroup',+ };+ expect(+ stateHasEntityFileEdits({ messages: [{ content: 'make a deck', role: 'user' }, grouped] }),+ ).toBe(true);+ });++ it('classifies a grouped moveFiles rename from its result state', () => {+ const grouped = {+ children: [+ {+ tools: [+ {+ apiName: 'moveFiles',+ arguments: JSON.stringify({+ operations: [{ destination: '/w/deck.pptx', source: '/w/draft.tmp' }],+ }),+ id: 't1',+ identifier: 'lobe-cloud-sandbox',+ result: {+ state: {+ results: [{ destination: '/w/deck.pptx', source: '/w/draft.tmp', success: true }],+ },+ },+ },+ ],+ },+ ],+ role: 'assistantGroup',+ };+ expect(+ stateHasEntityFileEdits({ messages: [{ content: 'rename it', role: 'user' }, grouped] }),+ ).toBe(true);+ });++ it('ignores entity edits from PREVIOUS turns (before the last user message)', () => {+ // A past run's entity edit already registered on its own completion —+ // counting it would permanently disable the early publish for the topic.+ const pastGroup = {+ children: [+ {+ tools: [+ {+ apiName: 'writeFile',+ arguments: JSON.stringify({ path: '/w/old-deck.pptx' }),+ id: 't1',+ identifier: 'lobe-cloud-sandbox',+ result: { state: { path: '/w/old-deck.pptx', success: true } },+ },+ ],+ },+ ],+ role: 'assistantGroup',+ };+ expect(+ stateHasEntityFileEdits({+ messages: [+ { content: 'make a deck', role: 'user' },+ pastGroup,+ { content: 'now just summarize it', role: 'user' },+ { content: 'summary...', role: 'assistant' },+ ],+ }),+ ).toBe(false);+ });++ it('detects an entity exportFile call from its arguments (raw and grouped shapes)', () => {+ // Raw tool_calls shape.+ expect(+ stateHasEntityFileEdits(+ stateWith([sandboxCall('t1', 'exportFile', { path: '/workspace/deck.pptx' })]),+ ),+ ).toBe(true);+ // Grouped (assistantGroup children[].tools) shape.+ const grouped = {+ children: [+ {+ tools: [+ {+ apiName: 'exportFile',+ arguments: JSON.stringify({ path: '/workspace/report.pdf' }),+ id: 't1',+ identifier: 'lobe-cloud-sandbox',+ },+ ],+ },+ ],+ role: 'assistantGroup',+ };+ expect(+ stateHasEntityFileEdits({ messages: [{ content: 'export it', role: 'user' }, grouped] }),+ ).toBe(true);+ // Non-entity export keeps the early publish.+ expect(+ stateHasEntityFileEdits(+ stateWith([sandboxCall('t1', 'exportFile', { path: '/workspace/notes.txt' })]),+ ),+ ).toBe(false);+ });++ it('detects an entity lobe-skills exportFile call (raw and grouped shapes)', () => {+ const skillsCall = (id: string, args: unknown) => ({+ function: { arguments: JSON.stringify(args), name: 'lobe-skills____exportFile____builtin' },+ id,+ type: 'function',+ });+ // Raw tool_calls shape.+ expect(+ stateHasEntityFileEdits(+ stateWith([skillsCall('t1', { filename: 'deck.pptx', path: '/workspace/deck.pptx' })]),+ ),+ ).toBe(true);+ // Grouped (assistantGroup children[].tools) shape.+ const grouped = {+ children: [+ {+ tools: [+ {+ apiName: 'exportFile',+ arguments: JSON.stringify({ filename: 'report.pdf', path: '/workspace/report.pdf' }),+ id: 't1',+ identifier: 'lobe-skills',+ },+ ],+ },+ ],+ role: 'assistantGroup',+ };+ expect(+ stateHasEntityFileEdits({ messages: [{ content: 'export it', role: 'user' }, grouped] }),+ ).toBe(true);+ // Non-entity skills export keeps the early publish.+ expect(+ stateHasEntityFileEdits(+ stateWith([skillsCall('t1', { filename: 'notes.txt', path: '/workspace/notes.txt' })]),+ ),+ ).toBe(false);+ });++ it('detects an entity edit mixed among non-entity edits', () => {+ expect(+ stateHasEntityFileEdits(+ stateWith([+ sandboxCall('t1', 'writeFile', { path: '/w/notes.md' }),+ sandboxCall('t2', 'writeFile', { path: '/w/report.xlsx' }),+ ]),+ ),+ ).toBe(true);+ });+});diff --git a/apps/share/app/stubs/artboardLoader.test.ts b/apps/share/app/stubs/artboardLoader.test.tsnew file mode 100644index 00000000000..5cf12cec8e0--- /dev/null+++ b/apps/share/app/stubs/artboardLoader.test.ts@@ -0,0 +1,17 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { openArtboardFullscreen } from './artboardLoader';++const toast = vi.hoisted(() => ({ info: vi.fn() }));++vi.mock('@lobehub/ui', () => ({ toast }));++beforeEach(() => toast.info.mockReset());++describe('share build artboard loader', () => {+ it('tells the visitor the artboard is not shared instead of doing nothing', async () => {+ await openArtboardFullscreen('art_1');++ expect(toast.info).toHaveBeenCalledWith('This artboard isn’t shared publicly');+ });+});diff --git a/apps/share/app/stubs/artboardLoader.ts b/apps/share/app/stubs/artboardLoader.tsnew file mode 100644index 00000000000..a7a06ac28db--- /dev/null+++ b/apps/share/app/stubs/artboardLoader.ts@@ -0,0 +1,11 @@+import { toast } from '@lobehub/ui';+import i18next from 'i18next';++export const openArtboardFullscreen = async (_artboardId: string): Promise<void> => {+ toast.info(+ i18next.t('artboard.share.notShared', {+ defaultValue: 'This artboard isn’t shared publicly',+ ns: 'project',+ }),+ );+};diff --git a/apps/share/vite.config.shared.mts b/apps/share/vite.config.shared.mtsindex 39759f521c2..9aa2f8ac70e 100644--- a/apps/share/vite.config.shared.mts+++ b/apps/share/vite.config.shared.mts@@ -60,6 +60,20 @@ export const createShareRrConfig = ({...extraSsrStubs,};+ // Artboards are private to signed-in projects, and their canvas frames need the+ // main SPA's `virtual:canvas-runtime` plugin, which the Share build lacks.+ const appOnlyStubs: Record<string, string> = {+ '@/features/Artboard/Gallery/loader': stub('artboardLoader.ts'),+ };++ const shareAppOnlyStubs = (): Plugin => ({+ enforce: 'pre',+ name: 'share-app-only-stubs',+ resolveId(source) {+ return appOnlyStubs[source];+ },+ });+const shareSsrStubs = (): Plugin => ({applyToEnvironment: (environment) => environment.name === 'ssr',enforce: 'pre',@@ -177,6 +191,7 @@ export const createShareRrConfig = ({plugins: [process.env.SHARE_CHUNK_REPORT ? ssrChunkReport() : undefined,process.env.SHARE_TRACE_MODULE ? ssrModuleTrace(process.env.SHARE_TRACE_MODULE) : undefined,+ shareAppOnlyStubs(),shareSsrStubs(),shareClientOnlyStub(),buildInputsManifest(),diff --git a/locales/en-US/agent.json b/locales/en-US/agent.jsonindex f0f2bb80438..7debe48e0de 100644--- a/locales/en-US/agent.json+++ b/locales/en-US/agent.json@@ -929,6 +929,7 @@"share.visitor.profile.works.desc": "Selected by the creator. See what this agent can deliver.","share.visitor.profile.works.open": "Open work","share.visitor.profile.works.title": "Featured works",+ "share.visitor.profile.works.type.artboard": "Artboard","share.visitor.profile.works.type.canvas": "Canvas","share.visitor.profile.works.type.document": "Document","share.visitor.profile.works.type.external": "Linked work",diff --git a/locales/en-US/file.json b/locales/en-US/file.jsonindex 8d96a06cce9..de5cfffd942 100644--- a/locales/en-US/file.json+++ b/locales/en-US/file.json@@ -104,6 +104,7 @@"docs.shared.title": "Shared docs","docs.viewAllPages": "View all","docs.works.all": "All",+ "docs.works.artboard": "Artboard","docs.works.canvas": "Canvas","docs.works.document": "Documents","docs.works.task": "Tasks",@@ -551,6 +552,7 @@"work.retry": "Retry","work.topicGroup.other": "Other","work.totalCost": "Total cost {{cost}}",+ "work.type.artboard": "Artboard","work.type.canvas": "Canvas","work.type.document": "Document","work.type.file": "File",diff --git a/locales/en-US/plugin.json b/locales/en-US/plugin.jsonindex 820304e6fee..a02459c6519 100644--- a/locales/en-US/plugin.json+++ b/locales/en-US/plugin.json@@ -1,6 +1,17 @@{"arguments.moreParams": "{{count}} params in total","arguments.title": "Arguments",+ "builtins.builtin-artboard.apiName.askArtboardQuestion": "Ask on artboard",+ "builtins.builtin-artboard.apiName.createArtboard": "Create artboard",+ "builtins.builtin-artboard.apiName.listArtboardComments": "Read artboard comments",+ "builtins.builtin-artboard.apiName.listArtboards": "List artboards",+ "builtins.builtin-artboard.apiName.readArtboard": "Read artboard",+ "builtins.builtin-artboard.apiName.readArtboardFile": "Read artboard file",+ "builtins.builtin-artboard.apiName.replyArtboardComment": "Reply to artboard comment",+ "builtins.builtin-artboard.apiName.resolveArtboardComment": "Resolve artboard comment",+ "builtins.builtin-artboard.apiName.updateArtboard": "Update artboard",+ "builtins.builtin-artboard.apiName.writeArtboardFiles": "Save artboard files",+ "builtins.builtin-artboard.title": "Artboard","builtins.builtin-dashboard.apiName.addWidgetToDashboard": "Add widget to dashboard","builtins.builtin-dashboard.apiName.createDashboard": "Create dashboard","builtins.builtin-dashboard.apiName.createWidgetDraft": "Create widget draft",diff --git a/locales/en-US/project.json b/locales/en-US/project.jsonindex e02581763b5..7efa29399a2 100644--- a/locales/en-US/project.json+++ b/locales/en-US/project.json@@ -30,6 +30,180 @@"acceptance.success.requestCompletion": "Completion review requested","acceptance.success.start": "Project started","acceptance.title": "Acceptance",+ "artboard.board.decision": "Decision",+ "artboard.board.fileMissing": "File not found: {{path}}",+ "artboard.board.generating": "Writing this board…",+ "artboard.board.image": "Image",+ "artboard.board.locked": "Finalized",+ "artboard.board.recommended": "Recommended",+ "artboard.board.sourceMissing": "Source unavailable",+ "artboard.card.openBoard": "Open board",+ "artboard.card.summary": "{{groups}} groups · {{boards}} screens",+ "artboard.card.updated": "Board updated · revision {{revision}}",+ "artboard.chat.noInput": "Open the conversation to add this to a message",+ "artboard.chat.quote": "Re: {{target}}",+ "artboard.comment.agent": "Agent",+ "artboard.comment.failed": "Couldn’t save the comment",+ "artboard.comment.member": "Member",+ "artboard.comment.onCanvas": "Canvas",+ "artboard.comment.placeholder": "Add a comment…",+ "artboard.comment.reopen": "Reopen",+ "artboard.comment.reply": "Reply…",+ "artboard.comment.resolve": "Resolve",+ "artboard.comment.resolved": "Resolved",+ "artboard.comment.send": "Add",+ "artboard.comment.sendHint": "{{mod}} ↵ to add · Esc to cancel",+ "artboard.comment.sendNow": "Send now",+ "artboard.comment.stale": "Screen changed since",+ "artboard.comment.unread": "Not sent",+ "artboard.comment.you": "You",+ "artboard.compare.design": "Design",+ "artboard.compare.real": "Screenshot",+ "artboard.compare.split": "Side by side",+ "artboard.empty.desc": "Describe what you want in chat, and the agent lays out the screens here.",+ "artboard.empty.title": "No board yet",+ "artboard.error.desc": "Check your connection and try again.",+ "artboard.error.retry": "Retry",+ "artboard.error.title": "Couldn’t load the board",+ "artboard.finalize.blocked": "{{count}} still open",+ "artboard.finalize.cancel": "Cancel",+ "artboard.finalize.checksTitle": "{{count}} acceptance checks will be generated",+ "artboard.finalize.confirm": "Finalize and generate acceptance",+ "artboard.finalize.issue.empty_journey": "The journey has no screens yet",+ "artboard.finalize.issue.entry_count": "The journey needs exactly one starting screen",+ "artboard.finalize.issue.multiple_journeys": "Keep a single journey group",+ "artboard.finalize.issue.no_journey": "Add a journey group first",+ "artboard.finalize.issue.unreachable": "“{{title}}” can’t be reached from the starting screen",+ "artboard.finalize.lockNote": "After finalizing, the user journey is locked as the acceptance reference. Later edits are recorded as changes.",+ "artboard.finalize.message": "Finalized “{{title}}”: {{count}} acceptance checks generated.",+ "artboard.finalize.missingCheck": "No acceptance check written for this screen yet",+ "artboard.finalize.openAcceptance": "Open acceptance",+ "artboard.finalize.pending.answered": "You answered. The agent closes this once it reads your answer, or you can close it yourself.",+ "artboard.finalize.pending.goAnswer": "Answer",+ "artboard.finalize.pending.goChoose": "Go to the choice",+ "artboard.finalize.pending.question": "The agent is waiting for your answer.",+ "artboard.finalize.pending.round": "This choice has not been submitted yet.",+ "artboard.finalize.pending.view": "View",+ "artboard.finalize.pendingTitle_one": "{{count}} open item to settle first",+ "artboard.finalize.pendingTitle_other": "{{count}} open items to settle first",+ "artboard.finalize.success": "Finalized. {{count}} acceptance checks generated.",+ "artboard.finalize.title": "Finalize the board",+ "artboard.fullscreen.placeholder": "The board is open full screen",+ "artboard.gallery.openConversation": "Open conversation",+ "artboard.group.choose": "Options · pick one",+ "artboard.group.lockedDesc": "Finalized · changes are recorded as revisions",+ "artboard.group.verifyDesc": "Screenshots from the latest check",+ "artboard.header.discuss": "Discuss",+ "artboard.header.exitFullscreen": "Back to panel",+ "artboard.header.finalize": "Finalize",+ "artboard.header.finalizePending": "Finalize · {{count}} open",+ "artboard.header.finalizeShort": "Finalize",+ "artboard.header.finalized": "Finalized",+ "artboard.header.fullscreen": "Full screen",+ "artboard.header.noTask": "This artboard has no task, so it can’t be finalized",+ "artboard.header.outline": "Outline",+ "artboard.header.phaseDraft": "Discussing",+ "artboard.header.phaseFinalized": "Finalized",+ "artboard.header.questions_one": "{{count}} question to answer",+ "artboard.header.questions_other": "{{count}} questions to answer",+ "artboard.header.title": "Artboard",+ "artboard.header.verify": "Accept",+ "artboard.header.verifyLocked": "Available after finalizing",+ "artboard.header.verifyPanel": "Acceptance panel",+ "artboard.outline.title": "Outline",+ "artboard.pages.title": "Pages",+ "artboard.question.answer": "Answer",+ "artboard.question.answered": "Answered",+ "artboard.question.hint": "Your answer goes to the agent with the next send.",+ "artboard.question.placeholder": "Answer this question…",+ "artboard.question.waiting": "Waiting for your answer",+ "artboard.selection.discuss": "Quote in chat",+ "artboard.selection.view": "View larger",+ "artboard.share.confirmTitle": "Before you share this artboard",+ "artboard.share.copied": "Link copied",+ "artboard.share.copy": "Copy link",+ "artboard.share.failed": "Couldn’t share. Try again.",+ "artboard.share.notShared": "This artboard isn’t shared publicly",+ "artboard.share.note": "Later changes stay private until you update the share.",+ "artboard.share.open": "Open share link",+ "artboard.share.privacy": "Anyone with the link can view this artboard: its pages, boards, connections and chosen options. Comments and acceptance results stay private.",+ "artboard.share.publish": "Share",+ "artboard.share.sharing": "Sharing…",+ "artboard.share.trigger": "Share",+ "artboard.share.unpublish": "Stop sharing",+ "artboard.share.unpublishConfirm": "The link will stop working for everyone who has it.",+ "artboard.share.unpublishFailed": "Couldn’t stop sharing. Try again.",+ "artboard.share.unpublished": "Sharing stopped",+ "artboard.share.update": "Update share",+ "artboard.stale.refresh": "Refresh",+ "artboard.stale.title": "This board has a newer version",+ "artboard.submit.action": "Submit to agent",+ "artboard.submit.allPicked": "{{picked}} picked",+ "artboard.submit.commentMessage_one": "Left {{count}} comment on the artboard.",+ "artboard.submit.commentMessage_other": "Left {{count}} comments on the artboard.",+ "artboard.submit.commentsTitle_one": "{{count}} comment to send",+ "artboard.submit.commentsTitle_other": "{{count}} comments to send",+ "artboard.submit.comments_one": "{{count}} comment",+ "artboard.submit.comments_other": "{{count}} comments",+ "artboard.submit.failed": "Couldn’t submit the choices",+ "artboard.submit.messageFailed": "Saved, but the message to the agent wasn’t sent.",+ "artboard.submit.message_one": "Submitted {{count}} choice on the artboard.",+ "artboard.submit.message_other": "Submitted {{count}} choices on the artboard.",+ "artboard.submit.noConversation": "Choices submitted. This artboard has no conversation, so the agent will see them the next time it reads the artboard.",+ "artboard.submit.resend": "Send again",+ "artboard.submit.status": "{{picked}} picked, {{rest}} by recommendation",+ "artboard.submit.title_one": "{{count}} question in this batch",+ "artboard.submit.title_other": "{{count}} questions in this batch",+ "artboard.submit.undecided_one": "{{count}} still unpicked",+ "artboard.submit.undecided_other": "{{count}} still unpicked",+ "artboard.title": "Artboard",+ "artboard.tool.comment": "Comment",+ "artboard.tool.select": "Select",+ "artboard.verify.accept": "Accept",+ "artboard.verify.acceptAll": "Accept all {{count}}",+ "artboard.verify.acceptAllHint": "or open one to confirm it",+ "artboard.verify.accepted": "{{id}} accepted",+ "artboard.verify.acceptedAll": "{{count}} checks accepted",+ "artboard.verify.back": "All checks",+ "artboard.verify.close": "Close acceptance",+ "artboard.verify.detailTitle": "Acceptance check",+ "artboard.verify.entry": "Entry screen",+ "artboard.verify.evidence": "Evidence",+ "artboard.verify.evidenceCount": "{{count}} screenshots",+ "artboard.verify.expected": "Expected",+ "artboard.verify.finalizedReference": "Finalized reference",+ "artboard.verify.flowLink": "Flow chart",+ "artboard.verify.next": "Next check",+ "artboard.verify.nextHint": "Accepting moves to the next check",+ "artboard.verify.noShot": "No screenshot yet",+ "artboard.verify.observation": "Agent observed: {{text}}",+ "artboard.verify.observed": "Observed",+ "artboard.verify.openDesign": "Open the design",+ "artboard.verify.path": "Path",+ "artboard.verify.paths": "How users get here",+ "artboard.verify.prev": "Previous check",+ "artboard.verify.realShot": "Real screenshot",+ "artboard.verify.reject": "Disagree, re-check",+ "artboard.verify.rejectFailed": "Send back",+ "artboard.verify.rejected": "{{id}} sent back",+ "artboard.verify.rejectedTag": "Sent back",+ "artboard.verify.reviewAccepted": "Accepted",+ "artboard.verify.reviewRejected": "Sent back for another round",+ "artboard.verify.reviewTitle": "Your call",+ "artboard.verify.reviewedTag": "Accepted",+ "artboard.verify.summary": "Checked {{checked}} of {{total}} screens",+ "artboard.verify.summaryBlocked": "{{count}} could not be checked",+ "artboard.verify.summaryFailed": "{{count}} did not match",+ "artboard.verify.title": "Acceptance",+ "artboard.verify.waiting": "Waiting for development. Results appear here when the build is ready.",+ "artboard.verifyBar.board": "Board",+ "artboard.verifyBar.list": "List",+ "artboard.verifyList.check": "Check",+ "artboard.verifyList.design": "Design",+ "artboard.zoom.actual": "Zoom to 100%",+ "artboard.zoom.fit": "Fit to screen",+ "artboard.zoom.in": "Zoom in",+ "artboard.zoom.out": "Zoom out","create.action": "Create project","create.afterCreateHint": "After it's created, the project home helps you connect code folders, sites and libraries.","create.avatarHint": "Pick an emoji or upload an image. You can also drop an image here.",diff --git a/locales/zh-CN/agent.json b/locales/zh-CN/agent.jsonindex fbfaa9e0a21..63cbe567157 100644--- a/locales/zh-CN/agent.json+++ b/locales/zh-CN/agent.json@@ -929,6 +929,7 @@"share.visitor.profile.works.desc": "由创建者精选,看看这个助手能交付什么。","share.visitor.profile.works.open": "打开成果","share.visitor.profile.works.title": "精选成果",+ "share.visitor.profile.works.type.artboard": "画板","share.visitor.profile.works.type.canvas": "画布","share.visitor.profile.works.type.document": "文档","share.visitor.profile.works.type.external": "外部成果",diff --git a/locales/zh-CN/file.json b/locales/zh-CN/file.jsonindex 57dd069f85a..f385b861089 100644--- a/locales/zh-CN/file.json+++ b/locales/zh-CN/file.json@@ -104,6 +104,7 @@"docs.shared.title": "共享文档","docs.viewAllPages": "查看全部","docs.works.all": "全部",+ "docs.works.artboard": "画板","docs.works.canvas": "画布","docs.works.document": "文档","docs.works.task": "任务",@@ -551,6 +552,7 @@"work.retry": "重试","work.topicGroup.other": "其他","work.totalCost": "累计开销 {{cost}}",+ "work.type.artboard": "画板","work.type.canvas": "画布","work.type.document": "文档","work.type.file": "文件",diff --git a/locales/zh-CN/plugin.json b/locales/zh-CN/plugin.jsonindex e998640d5a9..e3fff6839d4 100644--- a/locales/zh-CN/plugin.json+++ b/locales/zh-CN/plugin.json@@ -1,6 +1,17 @@{"arguments.moreParams": "等 {{count}} 个参数","arguments.title": "参数列表",+ "builtins.builtin-artboard.apiName.askArtboardQuestion": "在画板上提问",+ "builtins.builtin-artboard.apiName.createArtboard": "创建画板",+ "builtins.builtin-artboard.apiName.listArtboardComments": "读取画板评论",+ "builtins.builtin-artboard.apiName.listArtboards": "列出画板",+ "builtins.builtin-artboard.apiName.readArtboard": "读取画板",+ "builtins.builtin-artboard.apiName.readArtboardFile": "读取画板文件",+ "builtins.builtin-artboard.apiName.replyArtboardComment": "回复画板评论",+ "builtins.builtin-artboard.apiName.resolveArtboardComment": "解决画板评论",+ "builtins.builtin-artboard.apiName.updateArtboard": "更新画板",+ "builtins.builtin-artboard.apiName.writeArtboardFiles": "保存画板文件",+ "builtins.builtin-artboard.title": "画板","builtins.builtin-dashboard.apiName.addWidgetToDashboard": "添加组件到看板","builtins.builtin-dashboard.apiName.createDashboard": "创建看板","builtins.builtin-dashboard.apiName.createWidgetDraft": "创建组件草稿",diff --git a/locales/zh-CN/project.json b/locales/zh-CN/project.jsonindex e941271aec3..8bad495a7d8 100644--- a/locales/zh-CN/project.json+++ b/locales/zh-CN/project.json@@ -30,6 +30,180 @@"acceptance.success.requestCompletion": "已申请完成验收","acceptance.success.start": "项目已启动","acceptance.title": "验收",+ "artboard.board.decision": "分支判断",+ "artboard.board.fileMissing": "文件不存在:{{path}}",+ "artboard.board.generating": "正在生成…",+ "artboard.board.image": "图片",+ "artboard.board.locked": "已定稿",+ "artboard.board.recommended": "推荐",+ "artboard.board.sourceMissing": "来源不可用",+ "artboard.card.openBoard": "打开画板",+ "artboard.card.summary": "{{groups}} 组 · {{boards}} 个画面",+ "artboard.card.updated": "画板已更新 · 第 {{revision}} 版",+ "artboard.chat.noInput": "打开对话后才能放进消息",+ "artboard.chat.quote": "引用 {{target}}",+ "artboard.comment.agent": "Agent",+ "artboard.comment.failed": "评论没保存成功",+ "artboard.comment.member": "成员",+ "artboard.comment.onCanvas": "画布",+ "artboard.comment.placeholder": "写评论…",+ "artboard.comment.reopen": "重新打开",+ "artboard.comment.reply": "回复…",+ "artboard.comment.resolve": "解决",+ "artboard.comment.resolved": "已解决",+ "artboard.comment.send": "添加",+ "artboard.comment.sendHint": "{{mod}} ↵ 添加 · Esc 取消",+ "artboard.comment.sendNow": "立即发送",+ "artboard.comment.stale": "画面已改过",+ "artboard.comment.unread": "未发送",+ "artboard.comment.you": "你",+ "artboard.compare.design": "设计稿",+ "artboard.compare.real": "实测",+ "artboard.compare.split": "并排",+ "artboard.empty.desc": "在对话里说说想要什么,Agent 会把页面摆到这里。",+ "artboard.empty.title": "还没有画板",+ "artboard.error.desc": "检查网络后再试一次。",+ "artboard.error.retry": "重试",+ "artboard.error.title": "画板没加载出来",+ "artboard.finalize.blocked": "还有 {{count}} 个待定",+ "artboard.finalize.cancel": "取消",+ "artboard.finalize.checksTitle": "将生成 {{count}} 条验收项",+ "artboard.finalize.confirm": "定稿并生成验收",+ "artboard.finalize.issue.empty_journey": "旅程里还没有画面",+ "artboard.finalize.issue.entry_count": "旅程要有且只有一个起点画面",+ "artboard.finalize.issue.multiple_journeys": "只能保留一个旅程组",+ "artboard.finalize.issue.no_journey": "先加一个旅程组",+ "artboard.finalize.issue.unreachable": "从起点走不到「{{title}}」",+ "artboard.finalize.lockNote": "定稿后,用户旅程会锁定为验收参考。之后再改会记为变更。",+ "artboard.finalize.message": "画板「{{title}}」已定稿,生成了 {{count}} 条验收项。",+ "artboard.finalize.missingCheck": "这个画面还没写验收标准",+ "artboard.finalize.openAcceptance": "打开验收页",+ "artboard.finalize.pending.answered": "你已回答。Agent 读到回答后会关掉这个问题,你也可以自己关掉。",+ "artboard.finalize.pending.goAnswer": "去回答",+ "artboard.finalize.pending.goChoose": "去选择",+ "artboard.finalize.pending.question": "Agent 在等你回答。",+ "artboard.finalize.pending.round": "这一轮选择还没提交。",+ "artboard.finalize.pending.view": "查看",+ "artboard.finalize.pendingTitle_one": "还有 {{count}} 项待定,先定下来",+ "artboard.finalize.pendingTitle_other": "还有 {{count}} 项待定,先定下来",+ "artboard.finalize.success": "已定稿,生成了 {{count}} 条验收项",+ "artboard.finalize.title": "定稿",+ "artboard.fullscreen.placeholder": "画板已全屏打开",+ "artboard.gallery.openConversation": "打开对话",+ "artboard.group.choose": "备选方案 · 选一个",+ "artboard.group.lockedDesc": "已定稿 · 再改会记为变更",+ "artboard.group.verifyDesc": "最近一次核对的实测截图",+ "artboard.header.discuss": "讨论",+ "artboard.header.exitFullscreen": "收回面板",+ "artboard.header.finalize": "定稿",+ "artboard.header.finalizePending": "定稿 · {{count}} 待定",+ "artboard.header.finalizeShort": "定稿",+ "artboard.header.finalized": "已定稿",+ "artboard.header.fullscreen": "全屏",+ "artboard.header.noTask": "这块画板没有关联任务,不能定稿",+ "artboard.header.outline": "大纲",+ "artboard.header.phaseDraft": "讨论中",+ "artboard.header.phaseFinalized": "已定稿",+ "artboard.header.questions_one": "{{count}} 个提问待回答",+ "artboard.header.questions_other": "{{count}} 个提问待回答",+ "artboard.header.title": "画板",+ "artboard.header.verify": "验收",+ "artboard.header.verifyLocked": "定稿后可用",+ "artboard.header.verifyPanel": "验收面板",+ "artboard.outline.title": "大纲",+ "artboard.pages.title": "页",+ "artboard.question.answer": "回答",+ "artboard.question.answered": "已回答",+ "artboard.question.hint": "回答会和下一批内容一起发给 agent。",+ "artboard.question.placeholder": "回答这个提问…",+ "artboard.question.waiting": "待回答",+ "artboard.selection.discuss": "引用到对话",+ "artboard.selection.view": "放大查看",+ "artboard.share.confirmTitle": "分享画板前请确认",+ "artboard.share.copied": "链接已复制",+ "artboard.share.copy": "复制链接",+ "artboard.share.failed": "分享失败,请重试",+ "artboard.share.notShared": "这个画板没有公开分享",+ "artboard.share.note": "之后的修改不会自动公开,需要手动更新分享。",+ "artboard.share.open": "打开分享页",+ "artboard.share.privacy": "拿到链接的任何人都能查看这个画板:页面、画面、连线和已选方案。评论和验收结果不会公开。",+ "artboard.share.publish": "分享",+ "artboard.share.sharing": "正在分享…",+ "artboard.share.trigger": "分享",+ "artboard.share.unpublish": "停止分享",+ "artboard.share.unpublishConfirm": "停止后,所有拿到链接的人都将无法再打开。",+ "artboard.share.unpublishFailed": "停止分享失败,请重试",+ "artboard.share.unpublished": "已停止分享",+ "artboard.share.update": "更新分享",+ "artboard.stale.refresh": "刷新",+ "artboard.stale.title": "画板已有新版本",+ "artboard.submit.action": "提交给 agent",+ "artboard.submit.allPicked": "已选 {{picked}} 个",+ "artboard.submit.commentMessage_one": "在画板上留了 {{count}} 条评论。",+ "artboard.submit.commentMessage_other": "在画板上留了 {{count}} 条评论。",+ "artboard.submit.commentsTitle_one": "{{count}} 条评论待发送",+ "artboard.submit.commentsTitle_other": "{{count}} 条评论待发送",+ "artboard.submit.comments_one": "{{count}} 条评论",+ "artboard.submit.comments_other": "{{count}} 条评论",+ "artboard.submit.failed": "提交失败",+ "artboard.submit.messageFailed": "已保存,但发给 agent 的消息没发出去。",+ "artboard.submit.message_one": "已提交画板上的 {{count}} 个选择。",+ "artboard.submit.message_other": "已提交画板上的 {{count}} 个选择。",+ "artboard.submit.noConversation": "选择已提交;这块画板没有关联对话,agent 下次读画板时会看到。",+ "artboard.submit.resend": "重发",+ "artboard.submit.status": "已选 {{picked}} 个,另 {{rest}} 个按推荐",+ "artboard.submit.title_one": "这一批 {{count}} 个问题",+ "artboard.submit.title_other": "这一批 {{count}} 个问题",+ "artboard.submit.undecided_one": "还有 {{count}} 个没选",+ "artboard.submit.undecided_other": "还有 {{count}} 个没选",+ "artboard.title": "画板",+ "artboard.tool.comment": "评论",+ "artboard.tool.select": "选择",+ "artboard.verify.accept": "认可",+ "artboard.verify.acceptAll": "全部接受 {{count}} 项",+ "artboard.verify.acceptAllHint": "或点开逐条确认",+ "artboard.verify.accepted": "{{id}} 已认可",+ "artboard.verify.acceptedAll": "已接受 {{count}} 项",+ "artboard.verify.back": "全部验收项",+ "artboard.verify.close": "关闭验收",+ "artboard.verify.detailTitle": "验收项",+ "artboard.verify.entry": "入口页面",+ "artboard.verify.evidence": "证据",+ "artboard.verify.evidenceCount": "{{count}} 张截图",+ "artboard.verify.expected": "应看到",+ "artboard.verify.finalizedReference": "定稿参考",+ "artboard.verify.flowLink": "流程图",+ "artboard.verify.next": "下一条",+ "artboard.verify.nextHint": "接受后跳到下一条",+ "artboard.verify.noShot": "还没有截图",+ "artboard.verify.observation": "Agent 观察:{{text}}",+ "artboard.verify.observed": "实际",+ "artboard.verify.openDesign": "打开设计稿",+ "artboard.verify.path": "路径",+ "artboard.verify.paths": "用户怎么到这一屏",+ "artboard.verify.prev": "上一条",+ "artboard.verify.realShot": "真实截图",+ "artboard.verify.reject": "不认,重验",+ "artboard.verify.rejectFailed": "打回",+ "artboard.verify.rejected": "{{id}} 已打回",+ "artboard.verify.rejectedTag": "已打回",+ "artboard.verify.reviewAccepted": "已认可",+ "artboard.verify.reviewRejected": "已打回,进入下一轮",+ "artboard.verify.reviewTitle": "你的判断",+ "artboard.verify.reviewedTag": "已认可",+ "artboard.verify.summary": "已核对 {{checked}}/{{total}} 屏",+ "artboard.verify.summaryBlocked": "{{count}} 屏无法核对",+ "artboard.verify.summaryFailed": "{{count}} 屏与设计不符",+ "artboard.verify.title": "验收",+ "artboard.verify.waiting": "等待开发完成,结果会出现在这里。",+ "artboard.verifyBar.board": "画板",+ "artboard.verifyBar.list": "清单",+ "artboard.verifyList.check": "检查项",+ "artboard.verifyList.design": "设计稿",+ "artboard.zoom.actual": "缩放到 100%",+ "artboard.zoom.fit": "适应画面",+ "artboard.zoom.in": "放大",+ "artboard.zoom.out": "缩小","create.action": "创建项目","create.afterCreateHint": "建好后,项目首页会带你接入代码目录、站点、资料库这些。","create.avatarHint": "选择表情或上传图片,也可以把图片拖到这里",diff --git a/package.json b/package.jsonindex 711af6d07eb..a6d0375d7fc 100644--- a/package.json+++ b/package.json@@ -47,6 +47,7 @@"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:analyze": "cross-env NODE_OPTIONS=--max-old-space-size=81920 next experimental-analyze",+ "build:artboard-viewer": "pnpm --filter @lobechat/artboard-viewer build","build:canvas-runtime": "pnpm --filter @lobechat/canvas-runtime build","build:docker": "pnpm run build:file-parse-worker && 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:file-parse-worker": "tsx scripts/buildFileParseWorker.mts",@@ -252,6 +253,7 @@"@lobechat/builtin-tool-agent-documents": "workspace:*","@lobechat/builtin-tool-agent-management": "workspace:*","@lobechat/builtin-tool-agent-signal": "workspace:*",+ "@lobechat/builtin-tool-artboard": "workspace:*","@lobechat/builtin-tool-attachments": "workspace:*","@lobechat/builtin-tool-auv": "workspace:*","@lobechat/builtin-tool-brief": "workspace:*",diff --git a/packages/agent-gateway-client/src/types.ts b/packages/agent-gateway-client/src/types.tsindex 620b7e5aa8e..2d729ad8cd4 100644--- a/packages/agent-gateway-client/src/types.ts+++ b/packages/agent-gateway-client/src/types.ts@@ -13,7 +13,7 @@ import type { UIChatMessage } from '@lobechat/types';* summaries. Released desktop builds predate that Work type and crash on it,* so the server keeps it out of the push unless the client declares this.*/-export type AgentStreamClientFeature = 'file_works' | 'member_runtime_end';+export type AgentStreamClientFeature = 'artboard_works' | 'file_works' | 'member_runtime_end';export type AgentStreamEventType =| 'agent_runtime_init'diff --git a/packages/agent-runtime/src/agents/GeneralChatAgent.ts b/packages/agent-runtime/src/agents/GeneralChatAgent.tsindex bc2b089be51..01c81f8fc00 100644--- a/packages/agent-runtime/src/agents/GeneralChatAgent.ts+++ b/packages/agent-runtime/src/agents/GeneralChatAgent.ts@@ -32,7 +32,11 @@ import {EMPTY_ARGS_TOOL_REASON,partitionEmptyArgumentsCalls,} from '../utils/emptyArgumentsCalls';-import { selectEffectiveToolManifestMap, selectRunTools } from '../utils/operationToolSet';+import {+ selectEffectiveToolManifestMap,+ selectOperationToolSet,+ selectRunTools,+} from '../utils/operationToolSet';import { selectSecurityBlacklist, selectUserInterventionConfig } from '../utils/stateSlots';import { shouldCompress } from '../utils/tokenCounter';import {@@ -187,6 +191,10 @@ export class GeneralChatAgent implements Agent {// path-scope audit fences file paths to it).const resolverMetadata = {...state.metadata,+ enabledToolIds: [+ ...(selectOperationToolSet(state).enabledToolIds ?? []),+ ...(state.activatedStepTools ?? []).map((activation) => activation.id),+ ],securityBlacklist,workingDirectory: state.plan?.workingDirectory,};diff --git a/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.enabledToolsAudit.test.ts b/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.enabledToolsAudit.test.tsnew file mode 100644index 00000000000..17f7824abee--- /dev/null+++ b/packages/agent-runtime/src/agents/__tests__/GeneralChatAgent.enabledToolsAudit.test.ts@@ -0,0 +1,122 @@+import { type ChatToolPayload } from '@lobechat/types';+import { describe, expect, it } from 'vitest';++import { type AgentRuntimeContext, type AgentState } from '../../types';+import { GeneralChatAgent } from '../GeneralChatAgent';++describe('GeneralChatAgent — audits see the tools the run already offers', () => {+ const createState = (overrides?: Partial<AgentState>): AgentState => ({+ cost: {+ calculatedAt: new Date().toISOString(),+ currency: 'USD',+ llm: { byModel: [], currency: 'USD', total: 0 },+ tools: { byTool: [], currency: 'USD', total: 0 },+ total: 0,+ },+ createdAt: new Date().toISOString(),+ lastModified: new Date().toISOString(),+ messages: [],+ operationId: 'test-session',+ status: 'running',+ stepCount: 0,+ toolManifestMap: {},+ usage: {+ humanInteraction: {+ approvalRequests: 0,+ promptRequests: 0,+ selectRequests: 0,+ totalWaitingTimeMs: 0,+ },+ llm: { apiCalls: 0, processingTimeMs: 0, tokens: { input: 0, output: 0, total: 0 } },+ tools: { byTool: [], totalCalls: 0, totalTimeMs: 0 },+ },+ ...overrides,+ });++ const createContext = (toolsCalling: ChatToolPayload[]): AgentRuntimeContext => ({+ payload: { hasToolsCalling: true, parentMessageId: 'msg-1', toolsCalling },+ phase: 'llm_result',+ session: { messageCount: 0, sessionId: 'test-session', status: 'running', stepCount: 0 },+ });++ const seen: Record<string, any>[] = [];+ const createAgent = () =>+ new GeneralChatAgent({+ agentConfig: { maxSteps: 100 },+ dynamicInterventionAudits: {+ offeredOnly: async (toolArgs, metadata) => {+ seen.push(metadata ?? {});+ return !(metadata?.enabledToolIds ?? []).includes(toolArgs.identifier);+ },+ },+ modelRuntimeConfig: { model: 'gpt-4o-mini', provider: 'openai' },+ operationId: 'test-session',+ });++ const activator = {+ api: [+ {+ humanIntervention: {+ dynamic: { default: 'never', policy: 'required', type: 'offeredOnly' },+ },+ name: 'activateTools',+ },+ ],+ identifier: 'lobe-activator',+ };++ const activate = (identifier: string): ChatToolPayload => ({+ apiName: 'activateTools',+ arguments: JSON.stringify({ identifier }),+ id: `call-${identifier}`,+ identifier: 'lobe-activator',+ type: 'builtin',+ });++ const stateWith = (overrides?: Partial<AgentState>) =>+ createState({+ operationToolSet: {+ enabledToolIds: ['builtin-artboard'],+ manifestMap: { 'lobe-activator': activator },+ tools: [],+ },+ userInterventionConfig: { allowList: [], approvalMode: 'manual' },+ ...overrides,+ } as Partial<AgentState>);++ it('runs a call whose audit finds its target among the enabled tools', async () => {+ const call = activate('builtin-artboard');+ const result = await createAgent().runner(createContext([call]), stateWith());++ expect(result).toEqual([+ { payload: { parentMessageId: 'msg-1', toolCalling: call }, type: 'call_tool' },+ ]);+ });++ it('counts tools activated at step level as enabled', async () => {+ const call = activate('lobe-web-browsing');+ const result = await createAgent().runner(+ createContext([call]),+ stateWith({ activatedStepTools: [{ id: 'lobe-web-browsing' }] } as Partial<AgentState>),+ );++ expect(result).toEqual([+ { payload: { parentMessageId: 'msg-1', toolCalling: call }, type: 'call_tool' },+ ]);+ });++ it('asks for a call whose target the run does not offer', async () => {+ const call = activate('lobe-notebook');+ const result = await createAgent().runner(createContext([call]), stateWith());++ expect(result).toEqual([+ {+ parentMessageId: 'msg-1',+ pendingToolsCalling: [call],+ reason: 'human_intervention_required',+ type: 'request_human_approve',+ },+ ]);+ expect(seen.at(-1)?.enabledToolIds).toEqual(['builtin-artboard']);+ });+});diff --git a/packages/agent-runtime/src/executors/callLlmFinalizer.test.ts b/packages/agent-runtime/src/executors/callLlmFinalizer.test.tsindex c4972e450ab..90a30f3335e 100644--- a/packages/agent-runtime/src/executors/callLlmFinalizer.test.ts+++ b/packages/agent-runtime/src/executors/callLlmFinalizer.test.ts@@ -598,6 +598,61 @@ describe('callLlmFinalizer', () => {expect(plainUpdate.metadata ?? {}).not.toHaveProperty('work');});+ it('stamps the work display anchor when the tool interaction is nested in a parsed assistantGroup', async () => {+ const messages = createMessageTransport();+ // What the server runtime actually hands the finalizer: `state.messages` is+ // `parse(...).flatList`, so a turn's tool calls live under+ // `assistantGroup.children[].tools` — no `role: 'tool'` row and no+ // top-level `tool_calls`.+ const state = AgentRuntime.createInitialState({+ messages: [+ { content: 'Create a board', id: 'user-1', role: 'user' },+ {+ children: [+ {+ content: '',+ id: 'assistant-0',+ tools: [+ {+ apiName: 'createArtboard',+ arguments: '{}',+ id: 'call-1',+ identifier: 'builtin-artboard',+ type: 'default',+ },+ ],+ },+ ],+ content: '',+ id: 'group-1',+ role: 'assistantGroup',+ },+ ],+ operationId: 'operation-1',+ origin: { sourceMessageId: 'user-1' },+ });++ await finalizeCallLlmTurn({+ assistantMessageId: 'assistant-1',+ events: [],+ host: createHost(messages),+ model: 'gpt-4',+ output: createOutput(),+ provider: 'openai',+ shouldReplayAssistantReasoning: false,+ state,+ });++ expect(messages.update).toHaveBeenCalledWith(+ 'assistant-1',+ expect.objectContaining({+ metadata: expect.objectContaining({+ work: { rootOperationId: 'operation-1', userMessageId: 'user-1' },+ }),+ }),+ );+ });+it('serializes multimodal parts and keeps the null grounding sentinel', async () => {const messages = createMessageTransport();const state = AgentRuntime.createInitialState({ operationId: 'operation-1' });diff --git a/packages/agent-runtime/src/executors/callLlmFinalizer.ts b/packages/agent-runtime/src/executors/callLlmFinalizer.tsindex 304cf92f380..9cd91f9dd50 100644--- a/packages/agent-runtime/src/executors/callLlmFinalizer.ts+++ b/packages/agent-runtime/src/executors/callLlmFinalizer.ts@@ -172,10 +172,23 @@ const buildWorkAnchor = ({: -1;const currentOperationMessages =sourceMessageIndex >= 0 ? state.messages.slice(sourceMessageIndex + 1) : [];+ // Tool interaction also hides inside the conversation-flow `assistantGroup`+ // virtual message: the server runtime hydrates `state.messages` from+ // `parse(...).flatList`, where a turn's tool calls and results are nested+ // under `children[].tools` rather than a `role: 'tool'` row or a top-level+ // `tool_calls` array. Missing that shape dropped the Work display anchor —+ // and so the card under the reply — for every server-side run.+ const hasToolInteraction = (value: unknown): boolean => {+ if (!value || typeof value !== 'object') return false;+ if ('tool_calls' in value && Array.isArray(value.tool_calls) && value.tool_calls.length > 0)+ return true;+ if ('tools' in value && Array.isArray(value.tools) && value.tools.length > 0) return true;+ if ('children' in value && Array.isArray(value.children))+ return value.children.some((child) => hasToolInteraction(child));+ return false;+ };const hasPriorToolInteraction = currentOperationMessages.some(- (message) =>- message.role === 'tool' ||- (Array.isArray(message.tool_calls) && message.tool_calls.length > 0),+ (message) => message?.role === 'tool' || hasToolInteraction(message),);if (!hasPriorToolInteraction) return undefined;diff --git a/packages/agent-runtime/src/types/state.ts b/packages/agent-runtime/src/types/state.tsindex 8de3d71a363..84c3935aa83 100644--- a/packages/agent-runtime/src/types/state.ts+++ b/packages/agent-runtime/src/types/state.ts@@ -185,6 +185,7 @@ export interface AgentRunPlan {* carried by the runtime without interpretation.*/export interface AgentRunHostEnvelope {+ acceptsArtboardWorks?: boolean;/*** The client that started this run renders `file` Works, so the pushed* `uiMessages` snapshots and `message_patch` revisions may carry them.diff --git a/packages/app-config/src/featureFlags/schema.test.ts b/packages/app-config/src/featureFlags/schema.test.tsindex ba94d02eeda..9fdd9b16f45 100644--- a/packages/app-config/src/featureFlags/schema.test.ts+++ b/packages/app-config/src/featureFlags/schema.test.ts@@ -361,6 +361,17 @@ describe('mapFeatureFlagsEnvToState', () => {expect(mapFeatureFlagsEnvToState(config, 'user-456').enableMcpApps).toBe(false);});+ it('should keep the artboard off outside development and enable it per user or globally', () => {+ expect(DEFAULT_FEATURE_FLAGS.artboard).toBe(false);+ expect(mapFeatureFlagsEnvToState(DEFAULT_FEATURE_FLAGS, 'user-1').enableArtboard).toBe(false);++ expect(mapFeatureFlagsEnvToState({ artboard: true }).enableArtboard).toBe(true);++ const config = { artboard: ['user-123'] };+ expect(mapFeatureFlagsEnvToState(config, 'user-123').enableArtboard).toBe(true);+ expect(mapFeatureFlagsEnvToState(config, 'user-456').enableArtboard).toBe(false);+ });+it('should keep agent knowledge spaces off by default and enable them per user', () => {expect(DEFAULT_FEATURE_FLAGS.agent_knowledge_space).toBe(false);expect(diff --git a/packages/app-config/src/featureFlags/schema.ts b/packages/app-config/src/featureFlags/schema.tsindex 6c46da1c079..e1754798d0a 100644--- a/packages/app-config/src/featureFlags/schema.ts+++ b/packages/app-config/src/featureFlags/schema.ts@@ -92,6 +92,14 @@ export const FeatureFlagsSchema = z.object({*/mcp_apps: FeatureFlagValue.optional(),+ /**+ * Artboard: the agent's builtin-artboard tool in project conversations, the+ * board card and side panel, and the Artboard Works tab. Off: the tool is+ * never offered and artboard Works are not requested. Array values are user+ * ids.+ */+ artboard: FeatureFlagValue.optional(),+/*** Inbound webhooks wake Agents: MCP Events subscriptions, generic webhooks (the Agent Profile* Webhook tab) and the Automations lists. Off: deliveries are still verified, stored and@@ -225,6 +233,9 @@ export const DEFAULT_FEATURE_FLAGS: IFeatureFlags = {// Off until an admin publishes a user allowlist or flips it to true.dashboard: false,+ // On in development only; production needs an explicit allowlist.+ artboard: isDev,+// Off until an admin publishes a user allowlist or flips it to true.mcp_apps: false,webhook: false,@@ -276,6 +287,7 @@ export const mapFeatureFlagsEnvToState = (// Deprecated compatibility field for released LobeHub Mobile clients; see IFeatureFlagsState.enableGatewayMuxMobile: ENABLE_BUSINESS_FEATURES,enableLlmRelay: evaluateFeatureFlag(config.agent_llm_relay, userId, 'agent_llm_relay'),+ enableArtboard: evaluateFeatureFlag(config.artboard, userId, 'artboard'),enableDeferredInit: evaluateFeatureFlag(config.agent_deferred_init,userId,diff --git a/packages/artboard-viewer/package.json b/packages/artboard-viewer/package.jsonnew file mode 100644index 00000000000..9d518662993--- /dev/null+++ b/packages/artboard-viewer/package.json@@ -0,0 +1,10 @@+{+ "name": "@lobechat/artboard-viewer",+ "version": "1.0.0",+ "private": true,+ "type": "module",+ "scripts": {+ "build": "vite build && node scripts/finalize.mjs",+ "test": "vitest"+ }+}diff --git a/packages/artboard-viewer/scripts/finalize.mjs b/packages/artboard-viewer/scripts/finalize.mjsnew file mode 100644index 00000000000..5af25819dc0--- /dev/null+++ b/packages/artboard-viewer/scripts/finalize.mjs@@ -0,0 +1,41 @@+import { createHash } from 'node:crypto';+import { readdir, readFile, rm, writeFile } from 'node:fs/promises';+import path from 'node:path';+import { fileURLToPath } from 'node:url';++const VIEWER = 'artboard-viewer.js';++export const finalizeArtboardViewer = async (dist, major) => {+ const cssFiles = (await readdir(dist)).filter((file) => file.endsWith('.css'));+ if (cssFiles.length) {+ const css = (+ await Promise.all(cssFiles.map((file) => readFile(path.join(dist, file), 'utf8')))+ ).join('\n');+ const literal = JSON.stringify(css)+ .replaceAll('<', String.raw`\u003c`)+ .replaceAll('\u2028', String.raw`\u2028`)+ .replaceAll('\u2029', String.raw`\u2029`);+ const file = path.join(dist, VIEWER);+ const inject = `(function(){if(document.getElementById('lobe-artboard-viewer-style'))return;var s=document.createElement('style');s.id='lobe-artboard-viewer-style';s.textContent=${literal};(document.head||document.documentElement).appendChild(s)})();\n`;+ await writeFile(file, inject + (await readFile(file, 'utf8')));+ await Promise.all(cssFiles.map((file) => rm(path.join(dist, file))));+ }+ const bytes = await readFile(path.join(dist, VIEWER));+ const files = [+ { path: VIEWER, sha256: createHash('sha256').update(bytes).digest('hex'), size: bytes.length },+ ];+ const revision = createHash('sha256')+ .update(JSON.stringify([major, files.map((file) => [file.path, file.sha256, file.size])]))+ .digest('hex');+ const manifest = { files, major, revision };+ await writeFile(path.join(dist, 'manifest.json'), JSON.stringify(manifest));+ return manifest;+};++if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) {+ const here = path.dirname(fileURLToPath(import.meta.url));+ const source = await readFile(path.resolve(here, '../../types/src/artboardPublish.ts'), 'utf8');+ const major = Number(/ARTBOARD_VIEWER_MAJOR = (\d+)/.exec(source)?.[1]);+ if (!Number.isInteger(major) || major < 1) throw new Error('Missing artboard viewer major');+ console.log(JSON.stringify(await finalizeArtboardViewer(path.resolve(here, '../dist'), major)));+}diff --git a/packages/artboard-viewer/scripts/gate.mjs b/packages/artboard-viewer/scripts/gate.mjsnew file mode 100644index 00000000000..75240a1a98d--- /dev/null+++ b/packages/artboard-viewer/scripts/gate.mjs@@ -0,0 +1,14 @@+import path from 'node:path';++const FORBIDDEN = [+ /^src\/services\//,+ /^src\/libs\/trpc\//,+ /^src\/store\/(?!middleware\/)/,+ /\/@xyflow\//,+];++export const findForbiddenModules = (ids, repoRoot) =>+ ids+ .filter((id) => !id.startsWith('\0'))+ .map((id) => path.relative(repoRoot, id.split('?')[0]))+ .filter((id) => FORBIDDEN.some((pattern) => pattern.test(id)));diff --git a/packages/artboard-viewer/scripts/gate.test.ts b/packages/artboard-viewer/scripts/gate.test.tsnew file mode 100644index 00000000000..7d63e7b2263--- /dev/null+++ b/packages/artboard-viewer/scripts/gate.test.ts@@ -0,0 +1,40 @@+import { describe, expect, it } from 'vitest';++import { findForbiddenModules } from './gate.mjs';++const root = '/repo';++describe('findForbiddenModules', () => {+ it('flags app services, the tRPC client, app stores and the flow graph library', () => {+ expect(+ findForbiddenModules(+ [+ '/repo/src/services/artboard.ts',+ '/repo/src/libs/trpc/client/lambda.ts',+ '/repo/src/store/user/index.ts',+ '/repo/node_modules/@xyflow/react/dist/esm/index.js',+ ],+ root,+ ),+ ).toEqual([+ 'src/services/artboard.ts',+ 'src/libs/trpc/client/lambda.ts',+ 'src/store/user/index.ts',+ 'node_modules/@xyflow/react/dist/esm/index.js',+ ]);+ });++ it('allows the board view, its local store and the store middleware', () => {+ expect(+ findForbiddenModules(+ [+ '/repo/src/features/Artboard/Viewport/index.tsx',+ '/repo/src/features/Artboard/store/store.ts',+ '/repo/src/store/middleware/createDevtools.ts',+ '\0vite/preload-helper',+ ],+ root,+ ),+ ).toEqual([]);+ });+});diff --git a/packages/artboard-viewer/src/App.tsx b/packages/artboard-viewer/src/App.tsxnew file mode 100644index 00000000000..2d3d4cabacf--- /dev/null+++ b/packages/artboard-viewer/src/App.tsx@@ -0,0 +1,81 @@+import type { ArtboardPublishSnapshot } from '@lobechat/types';+import { ConfigProvider, Flexbox, Text } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import { motion } from 'motion/react';+import { useMemo } from 'react';++import Outline from '@/features/Artboard/Board/Outline';+import { BoardProvider } from '@/features/Artboard/BoardContext';+import BoardFrame from '@/features/Artboard/Canvas/BoardFrame';+import { boardFileUrl } from '@/features/Artboard/model';+import { useArtboardStore } from '@/features/Artboard/store';+import Viewport from '@/features/Artboard/Viewport';+import {+ type BoardCapabilities,+ BoardCapabilitiesProvider,+} from '@/features/Artboard/Viewport/capabilities';++import { snapshotToBoard } from './snapshot';++const styles = stylex.create({+ header: {+ borderBlockEndColor: cssVar.colorBorderSecondary,+ borderBlockEndStyle: 'solid',+ borderBlockEndWidth: 1,+ flex: 'none',+ paddingBlock: 10,+ paddingInline: 16,+ },+ root: {+ backgroundColor: cssVar.colorBgLayout,+ height: '100dvh',+ width: '100%',+ },+ stage: {+ flex: '1',+ minHeight: 0,+ overflow: 'hidden',+ position: 'relative',+ },+});++const App = ({ snapshot }: { snapshot: ArtboardPublishSnapshot }) => {+ const { artboard, fileBaseUrl } = useMemo(() => snapshotToBoard(snapshot), [snapshot]);+ const capabilities = useMemo<BoardCapabilities>(+ () => ({+ renderCanvas: (board) => {+ const src = boardFileUrl({ fileBaseUrl }, board);+ return src ? <BoardFrame src={src} title={board.title} /> : null;+ },+ }),+ [fileBaseUrl],+ );+ // Seeded by `initViewerStore`; the viewport keeps boards clear of it only while it is open.+ const outlineOpen = useArtboardStore((s) => s.outlineOpen);++ return (+ <ConfigProvider motion={motion}>+ <Flexbox {...stylex.props(styles.root)}>+ <Flexbox gap={2} {...stylex.props(styles.header)}>+ <Text strong>{snapshot.title}</Text>+ {snapshot.description && (+ <Text ellipsis style={{ fontSize: 12 }} type={'secondary'}>+ {snapshot.description}+ </Text>+ )}+ </Flexbox>+ <div {...stylex.props(styles.stage)}>+ <BoardProvider artboard={artboard} fileBaseUrl={fileBaseUrl}>+ <BoardCapabilitiesProvider value={capabilities}>+ <Viewport />+ {outlineOpen && <Outline />}+ </BoardCapabilitiesProvider>+ </BoardProvider>+ </div>+ </Flexbox>+ </ConfigProvider>+ );+};++export default App;diff --git a/packages/artboard-viewer/src/i18n.ts b/packages/artboard-viewer/src/i18n.tsnew file mode 100644index 00000000000..b1f14e7d8e2--- /dev/null+++ b/packages/artboard-viewer/src/i18n.ts@@ -0,0 +1,25 @@+import i18next from 'i18next';+import { initReactI18next } from 'react-i18next';++import zhCN from '../../../locales/zh-CN/project.json';+import enUS from '../../locales/src/default/project';++const artboardKeys = (resource: Record<string, string>) =>+ Object.fromEntries(Object.entries(resource).filter(([key]) => key.startsWith('artboard.')));++export const viewerLanguage = (language: string) =>+ language.toLowerCase().startsWith('zh') ? 'zh-CN' : 'en-US';++export const initViewerI18n = (language: string) =>+ i18next.use(initReactI18next).init({+ defaultNS: 'project',+ fallbackLng: 'en-US',+ interpolation: { escapeValue: false },+ keySeparator: false,+ lng: viewerLanguage(language),+ ns: ['project'],+ resources: {+ 'en-US': { project: artboardKeys(enUS) },+ 'zh-CN': { project: artboardKeys(zhCN) },+ },+ });diff --git a/packages/artboard-viewer/src/index.tsx b/packages/artboard-viewer/src/index.tsxnew file mode 100644index 00000000000..369672e098b--- /dev/null+++ b/packages/artboard-viewer/src/index.tsx@@ -0,0 +1,35 @@+import '@lobehub/ui/theme.css';+import '@lobehub/ui/global.css';+import '@lobehub/ui/style.css';+import '@/styles/stylex.css';++import { ARTBOARD_SNAPSHOT_ELEMENT_ID, type ArtboardPublishSnapshot } from '@lobechat/types';+import { createRoot } from 'react-dom/client';++import App from './App';+import { initViewerI18n } from './i18n';+import { initViewerStore } from './viewerState';++const followSystemTheme = () => {+ const query = window.matchMedia('(prefers-color-scheme: dark)');+ const apply = () => {+ document.documentElement.dataset.theme = query.matches ? 'dark' : 'light';+ };+ apply();+ query.addEventListener('change', apply);+};++const boot = async () => {+ const data = document.getElementById(ARTBOARD_SNAPSHOT_ELEMENT_ID)?.textContent;+ const root = document.getElementById('root');+ if (!data || !root) return;+ followSystemTheme();+ await initViewerI18n(navigator.language);+ const snapshot = JSON.parse(data) as ArtboardPublishSnapshot;+ initViewerStore(snapshot);+ createRoot(root).render(<App snapshot={snapshot} />);+};++if (document.readyState === 'loading')+ document.addEventListener('DOMContentLoaded', () => void boot());+else void boot();diff --git a/packages/artboard-viewer/src/snapshot.test.ts b/packages/artboard-viewer/src/snapshot.test.tsnew file mode 100644index 00000000000..a6af03652bd--- /dev/null+++ b/packages/artboard-viewer/src/snapshot.test.ts@@ -0,0 +1,94 @@+import type { ArtboardPublishSnapshot } from '@lobechat/types';+import { describe, expect, it } from 'vitest';++import { snapshotToBoard } from './snapshot';++const rect = { h: 400, w: 640, x: 0, y: 0 };++const snapshot: ArtboardPublishSnapshot = {+ boards: [+ {+ groupId: null,+ id: 'brd_html',+ pageId: 'pg_1',+ rect,+ roundId: 'rnd_1',+ source: { hash: 'abcdef0123456789', kind: 'file', path: 'pages/home page.html' },+ title: 'Option A',+ type: 'html',+ },+ {+ groupId: null,+ id: 'brd_image',+ pageId: 'pg_1',+ rect,+ roundId: null,+ source: { hash: 'fedcba9876543210', kind: 'file', path: 'shots/home.png' },+ title: 'Reference',+ type: 'image',+ },+ {+ groupId: null,+ id: 'brd_decision',+ pageId: 'pg_1',+ rect,+ roundId: null,+ source: null,+ title: 'Pick',+ type: 'decision',+ },+ ],+ description: 'Directions',+ edges: [+ { condition: null, from: 'brd_html', id: 'e1', isDefault: false, label: '', to: 'brd_image' },+ ],+ groups: [],+ pages: [{ id: 'pg_1', name: 'Page 1', sortOrder: 0 }],+ publishedAt: '2026-11-17T00:00:00.000Z',+ rounds: [+ {+ chosenBoardId: 'brd_html',+ id: 'rnd_1',+ pageId: 'pg_1',+ recommendedBoardId: 'brd_html',+ status: 'submitted',+ title: 'Direction',+ },+ ],+ title: 'Onboarding',+ version: 1,+};++describe('snapshotToBoard', () => {+ it('rebuilds a read-only artboard the shared board view can render', () => {+ const { artboard } = snapshotToBoard(snapshot);++ expect(artboard).toMatchObject({+ acceptanceId: null,+ description: 'Directions',+ phase: 'discuss',+ title: 'Onboarding',+ });+ expect(artboard.content.questions).toEqual([]);+ expect(artboard.content.rounds[0]).toMatchObject({+ batchId: null,+ chosenBoardId: 'brd_html',+ });+ expect(artboard.content.edges[0]).toMatchObject({ flowEdgeId: null, from: 'brd_html' });+ expect(artboard.content.boards.map((board) => board.expected)).toEqual([null, null, null]);+ });++ it('keeps each board on its artboard file, served from the site files directory', () => {+ const { artboard, fileBaseUrl } = snapshotToBoard(snapshot);+ const sources = Object.fromEntries(+ artboard.content.boards.map((board) => [board.id, board.source]),+ );++ expect(fileBaseUrl).toBe('files/');+ expect(sources).toEqual({+ brd_decision: null,+ brd_html: { hash: 'abcdef0123456789', kind: 'file', path: 'pages/home page.html' },+ brd_image: { hash: 'fedcba9876543210', kind: 'file', path: 'shots/home.png' },+ });+ });+});diff --git a/packages/artboard-viewer/src/snapshot.ts b/packages/artboard-viewer/src/snapshot.tsnew file mode 100644index 00000000000..cd020046932--- /dev/null+++ b/packages/artboard-viewer/src/snapshot.ts@@ -0,0 +1,39 @@+import {+ ARTBOARD_SITE_FILES_DIR,+ type ArtboardItem,+ type ArtboardPublishSnapshot,+} from '@lobechat/types';++export interface ViewerBoard {+ artboard: ArtboardItem;+ fileBaseUrl: string;+}++export const snapshotToBoard = (snapshot: ArtboardPublishSnapshot): ViewerBoard => {+ const publishedAt = new Date(snapshot.publishedAt);++ return {+ artboard: {+ acceptanceId: null,+ content: {+ boards: snapshot.boards.map((board) => ({ ...board, expected: null, flowNodeId: null })),+ edges: snapshot.edges.map((edge) => ({ ...edge, flowEdgeId: null })),+ groups: snapshot.groups,+ pages: snapshot.pages,+ questions: [],+ rounds: snapshot.rounds.map((round) => ({ ...round, batchId: null })),+ },+ createdAt: publishedAt,+ description: snapshot.description,+ id: 'published',+ phase: 'discuss',+ projectId: null,+ revision: 1,+ taskId: null,+ title: snapshot.title,+ topicId: null,+ updatedAt: publishedAt,+ },+ fileBaseUrl: ARTBOARD_SITE_FILES_DIR,+ };+};diff --git a/packages/artboard-viewer/src/viewerState.test.ts b/packages/artboard-viewer/src/viewerState.test.tsnew file mode 100644index 00000000000..1e9b815d283--- /dev/null+++ b/packages/artboard-viewer/src/viewerState.test.ts@@ -0,0 +1,42 @@+import type { ArtboardPublishSnapshot } from '@lobechat/types';+import { beforeEach, describe, expect, it } from 'vitest';++import { artboardActions, useArtboardStore } from '@/features/Artboard/store';++import { initViewerStore } from './viewerState';++const snapshot = (extra: Partial<ArtboardPublishSnapshot>) =>+ ({+ boards: [],+ edges: [],+ groups: [],+ pages: [],+ rounds: [],+ ...extra,+ }) as ArtboardPublishSnapshot;++describe('initViewerStore', () => {+ beforeEach(() => artboardActions.setOutlineOpen(false));++ // The viewport only keeps boards clear of the outline panel when the store says it is open,+ // so a viewer that shows the outline must open it there before the first fit.+ it('opens the outline for a snapshot that has groups', () => {+ initViewerStore(snapshot({ groups: [{ id: 'grp_1' }] as ArtboardPublishSnapshot['groups'] }));++ expect(useArtboardStore.getState().outlineOpen).toBe(true);+ });++ it('opens the outline for a snapshot with several pages', () => {+ initViewerStore(+ snapshot({ pages: [{ id: 'pg_1' }, { id: 'pg_2' }] as ArtboardPublishSnapshot['pages'] }),+ );++ expect(useArtboardStore.getState().outlineOpen).toBe(true);+ });++ it('keeps the outline closed for a single ungrouped page', () => {+ initViewerStore(snapshot({ pages: [{ id: 'pg_1' }] as ArtboardPublishSnapshot['pages'] }));++ expect(useArtboardStore.getState().outlineOpen).toBe(false);+ });+});diff --git a/packages/artboard-viewer/src/viewerState.ts b/packages/artboard-viewer/src/viewerState.tsnew file mode 100644index 00000000000..447680e48be--- /dev/null+++ b/packages/artboard-viewer/src/viewerState.ts@@ -0,0 +1,12 @@+import type { ArtboardPublishSnapshot } from '@lobechat/types';++import { artboardActions } from '@/features/Artboard/store';++/**+ * Seed the shared Artboard store before the first render. The viewport fits the+ * boards clear of the outline panel only while the store has it open, so the+ * outline the viewer shows must be opened here, not just rendered.+ */+export const initViewerStore = (snapshot: ArtboardPublishSnapshot) => {+ artboardActions.setOutlineOpen(snapshot.pages.length > 1 || snapshot.groups.length > 0);+};diff --git a/packages/artboard-viewer/vite.config.ts b/packages/artboard-viewer/vite.config.tsnew file mode 100644index 00000000000..1288f41a6e5--- /dev/null+++ b/packages/artboard-viewer/vite.config.ts@@ -0,0 +1,63 @@+import path from 'node:path';++import react from '@vitejs/plugin-react';+import { defineConfig, type Plugin } from 'vite';++import { lobeIconImports } from '../../plugins/vite/lobeIconImports';+import { lobeUiImports } from '../../plugins/vite/lobeUiImports';+import { vitePlatformResolve } from '../../plugins/vite/platformResolve';+import {+ sharedRendererDedupe,+ sharedRendererDefine,+} from '../../plugins/vite/sharedRendererConfig';+import { stylexPlugin, stylexTokenModules } from '../../plugins/vite/stylex';+import { findForbiddenModules } from './scripts/gate.mjs';++const repoRoot = path.resolve(import.meta.dirname, '../..');++const boardOnlyGate = (): Plugin => ({+ generateBundle() {+ const forbidden = findForbiddenModules([...this.getModuleIds()], repoRoot);+ if (forbidden.length)+ this.error(`The artboard viewer must not bundle app-only modules:\n${forbidden.join('\n')}`);+ },+ name: 'artboard-viewer-gate',+});++// A classic script: published sites load it cross-origin, so ES module chunks would need CORS.+export default defineConfig({+ build: {+ assetsInlineLimit: 100_000_000,+ cssCodeSplit: false,+ emptyOutDir: true,+ lib: {+ entry: 'src/index.tsx',+ fileName: () => 'artboard-viewer.js',+ formats: ['iife'],+ name: 'LobeArtboardViewer',+ },+ minify: true,+ outDir: 'dist',+ rolldownOptions: {+ output: { assetFileNames: 'artboard-viewer.css' },+ },+ },+ define: {+ ...sharedRendererDefine({ isElectron: false, isMobile: false }),+ 'process.env.NODE_ENV': '"production"',+ },+ optimizeDeps: { exclude: [...stylexTokenModules] },+ oxc: { jsx: { development: false } },+ plugins: [+ boardOnlyGate(),+ vitePlatformResolve('web'),+ stylexPlugin(),+ react(),+ ...lobeUiImports(),+ ...lobeIconImports(),+ ],+ resolve: {+ dedupe: [...sharedRendererDedupe, '@lobehub/ui'],+ tsconfigPaths: true,+ },+});diff --git a/packages/artboard-viewer/vitest.config.mts b/packages/artboard-viewer/vitest.config.mtsnew file mode 100644index 00000000000..ea0c1700b4e--- /dev/null+++ b/packages/artboard-viewer/vitest.config.mts@@ -0,0 +1,12 @@+import path from 'node:path';++import tsconfigPaths from 'vite-tsconfig-paths';+import { defineConfig } from 'vitest/config';++export default defineConfig({+ // The viewer reuses the app's Artboard modules, which import through the root `@/` paths.+ plugins: [tsconfigPaths({ projects: [path.resolve(import.meta.dirname, '../..')] })],+ test: {+ environment: 'node',+ },+});diff --git a/packages/builtin-tool-activator/src/index.ts b/packages/builtin-tool-activator/src/index.tsindex 11daf0da252..6e26e8f61fc 100644--- a/packages/builtin-tool-activator/src/index.ts+++ b/packages/builtin-tool-activator/src/index.ts@@ -1,3 +1,4 @@+export { ACTIVATE_TOOLS_AUDIT, activateToolsAudit } from './interventionAudit';export { LobeActivatorManifest } from './manifest';export { getSystemPromptForShareVisitor, systemPrompt } from './systemRole';export {diff --git a/packages/builtin-tool-activator/src/interventionAudit.test.ts b/packages/builtin-tool-activator/src/interventionAudit.test.tsnew file mode 100644index 00000000000..b282fa3dbde--- /dev/null+++ b/packages/builtin-tool-activator/src/interventionAudit.test.ts@@ -0,0 +1,30 @@+import { describe, expect, it } from 'vitest';++import { activateToolsAudit } from './interventionAudit';++const metadata = { enabledToolIds: ['builtin-artboard', 'lobe-web-browsing'] };++describe('activateToolsAudit', () => {+ it('lets a request for tools the run already offers through without asking', async () => {+ expect(await activateToolsAudit({ identifiers: ['builtin-artboard'] }, metadata)).toBe(false);+ expect(+ await activateToolsAudit(+ { identifiers: ['builtin-artboard____listArtboardComments', 'lobe-web-browsing'] },+ metadata,+ ),+ ).toBe(false);+ });++ it('asks when any requested identifier is not already offered', async () => {+ expect(+ await activateToolsAudit({ identifiers: ['builtin-artboard', 'lobe-notebook'] }, metadata),+ ).toBe(true);+ expect(await activateToolsAudit({ identifiers: ['artboard'] }, metadata)).toBe(true);+ });++ it('asks when the run reports no enabled tools or the request is empty', async () => {+ expect(await activateToolsAudit({ identifiers: ['builtin-artboard'] }, {})).toBe(true);+ expect(await activateToolsAudit({ identifiers: [] }, metadata)).toBe(true);+ expect(await activateToolsAudit({}, metadata)).toBe(true);+ });+});diff --git a/packages/builtin-tool-activator/src/interventionAudit.ts b/packages/builtin-tool-activator/src/interventionAudit.tsnew file mode 100644index 00000000000..4ed31bc8951--- /dev/null+++ b/packages/builtin-tool-activator/src/interventionAudit.ts@@ -0,0 +1,21 @@+import type { DynamicInterventionResolver } from '@lobechat/types';++export const ACTIVATE_TOOLS_AUDIT = 'activateToolsAudit';++const TOOL_NAME_SEPARATOR = '____';++const pluginIdOf = (identifier: string) => identifier.split(TOOL_NAME_SEPARATOR)[0];++// An identifier that names no tool may still open a skill by name, so only a+// request made entirely of tools the run already offers skips the approval.+export const activateToolsAudit: DynamicInterventionResolver = async (toolArgs, metadata) => {+ const identifiers: unknown = toolArgs?.identifiers;+ if (!Array.isArray(identifiers) || identifiers.length === 0) return true;++ const enabled = new Set<string>(metadata?.enabledToolIds ?? []);+ return !identifiers.every(+ (identifier) =>+ typeof identifier === 'string' &&+ (enabled.has(identifier) || enabled.has(pluginIdOf(identifier))),+ );+};diff --git a/packages/builtin-tool-activator/src/manifest.ts b/packages/builtin-tool-activator/src/manifest.tsindex d889636397a..d60a50f9d9c 100644--- a/packages/builtin-tool-activator/src/manifest.ts+++ b/packages/builtin-tool-activator/src/manifest.ts@@ -1,5 +1,6 @@import type { BuiltinToolManifest } from '@lobechat/types';+import { ACTIVATE_TOOLS_AUDIT } from './interventionAudit';import { systemPrompt } from './systemRole';import { ActivatorApiName, LobeActivatorIdentifier } from './types';@@ -8,7 +9,9 @@ export const LobeActivatorManifest: BuiltinToolManifest = {{description:'Activate tools from the <available_tools> list so their full API schemas become available for use. Call this before using any tool that is not yet activated. You can activate multiple tools at once.',- humanIntervention: 'required',+ humanIntervention: {+ dynamic: { default: 'never', policy: 'required', type: ACTIVATE_TOOLS_AUDIT },+ },name: ActivatorApiName.activateTools,parameters: {properties: {diff --git a/packages/builtin-tool-artboard/package.json b/packages/builtin-tool-artboard/package.jsonnew file mode 100644index 00000000000..b8699e3af2e--- /dev/null+++ b/packages/builtin-tool-artboard/package.json@@ -0,0 +1,20 @@+{+ "name": "@lobechat/builtin-tool-artboard",+ "version": "1.0.0",+ "private": true,+ "exports": {+ ".": "./src/index.ts",+ "./client": "./src/client/index.ts",+ "./executionRuntime": "./src/ExecutionRuntime/index.ts"+ },+ "main": "./src/index.ts",+ "devDependencies": {+ "@lobechat/types": "workspace:*"+ },+ "peerDependencies": {+ "@lobehub/ui": "^6.0.4",+ "@stylexjs/stylex": "*",+ "react": "*",+ "react-i18next": "*"+ }+}diff --git a/packages/builtin-tool-artboard/src/ExecutionRuntime/index.test.ts b/packages/builtin-tool-artboard/src/ExecutionRuntime/index.test.tsnew file mode 100644index 00000000000..416b1f20f55--- /dev/null+++ b/packages/builtin-tool-artboard/src/ExecutionRuntime/index.test.ts@@ -0,0 +1,406 @@+import type { ArtboardCommentThreadView } from '@lobechat/types';+import { describe, expect, it, vi } from 'vitest';++import type { ArtboardToolService, ArtboardToolSnapshot } from '../types';+import { ArtboardExecutionRuntime } from './index';++const snapshot = (overrides: Partial<ArtboardToolSnapshot> = {}): ArtboardToolSnapshot => ({+ content: {+ boards: [+ {+ expected: '看到接入入口',+ flowNodeId: null,+ groupId: 'abg_1',+ id: 'brd-1',+ pageId: 'abp_1',+ rect: { h: 400, w: 640, x: 0, y: 0 },+ roundId: null,+ source: { hash: 'a1b2c3d4e5f6a7b8', kind: 'file', path: 'pages/empty.html' },+ title: '空项目',+ type: 'html',+ },+ ],+ edges: [],+ groups: [+ {+ desc: '',+ id: 'abg_1',+ kind: 'journey',+ pageId: 'abp_1',+ rect: { h: 592, w: 736, x: -48, y: -144 },+ title: '旅程',+ },+ ],+ pages: [{ id: 'abp_1', name: 'Page 1', sortOrder: 0 }],+ questions: [],+ rounds: [],+ },+ description: '首次进入',+ id: 'art_1',+ phase: 'discuss',+ projectId: 'prj_1',+ revision: 1,+ taskId: 'task_1',+ title: '新用户首次进入项目',+ ...overrides,+});++const service = (overrides: Partial<ArtboardToolService> = {}): ArtboardToolService => ({+ askQuestion: vi.fn(),+ create: vi.fn(),+ list: vi.fn(),+ listComments: vi.fn(),+ read: vi.fn(),+ readFile: vi.fn(),+ replyComment: vi.fn(),+ resolveComment: vi.fn(),+ update: vi.fn(),+ writeFiles: vi.fn(),+ ...overrides,+});++const thread = (overrides: Partial<ArtboardCommentThreadView> = {}): ArtboardCommentThreadView => ({+ anchor: null,+ authorAgentId: null,+ authorUserId: 'user_1',+ boardId: 'brd-1',+ content: '按钮太小了',+ createdAt: new Date('2026-11-13T00:00:00.000Z'),+ groupId: null,+ id: 'cmt-1',+ pageId: 'abp_1',+ replies: [],+ resolvedAt: null,+ ...overrides,+});++describe('ArtboardExecutionRuntime', () => {+ it('reports the new board in state and asks for its Work', async () => {+ const create = vi.fn().mockResolvedValue({+ artboard: snapshot(),+ changedIds: ['abg_1', 'brd-1'],+ ok: true,+ task: { createdTask: true, identifier: 'PRJ-3' },+ });+ const onWorkRegistration = vi.fn();+ const result = await new ArtboardExecutionRuntime(service({ create })).createArtboard(+ { title: '新用户首次进入项目' },+ { onWorkRegistration },+ );++ expect(result.success).toBe(true);+ expect(result.state).toEqual({+ artboardId: 'art_1',+ boardCount: 1,+ changedIds: ['abg_1', 'brd-1'],+ groupCount: 1,+ phase: 'discuss',+ revision: 1,+ title: '新用户首次进入项目',+ });+ expect(result.content).toContain('art_1');+ expect(result.content).toContain('PRJ-3');+ expect(result.content).toContain('1 groups · 1 boards');+ expect(onWorkRegistration).toHaveBeenCalledWith({+ action: 'register',+ artboard: {+ artboardId: 'art_1',+ changeType: 'created',+ description: '首次进入',+ projectId: 'prj_1',+ title: '新用户首次进入项目',+ toolName: 'createArtboard',+ },+ type: 'artboard',+ });+ });++ it('turns a stale revision into a hint to read again, and registers nothing', async () => {+ const update = vi.fn().mockResolvedValue({+ code: 'conflict',+ message: 'The board changed since you read it.',+ ok: false,+ });+ const result = await new ArtboardExecutionRuntime(service({ update })).updateArtboard({+ id: 'art_1',+ ops: [],+ revision: 1,+ });++ expect(result.success).toBe(false);+ expect(result.content).toContain('readArtboard');+ expect(result.error).toMatchObject({ type: 'conflict' });+ });++ it('reports what an update changed and registers the new Work version', async () => {+ const update = vi.fn().mockResolvedValue({+ artboard: snapshot({ revision: 2 }),+ changedIds: ['brd-1'],+ ok: true,+ });+ const onWorkRegistration = vi.fn();+ const result = await new ArtboardExecutionRuntime(service({ update })).updateArtboard(+ {+ id: 'art_1',+ ops: [{ id: 'brd-1', patch: { x: 10 }, type: 'updateBoard' }],+ revision: 1,+ },+ { onWorkRegistration },+ );++ expect(result.state).toMatchObject({ boardCount: 1, changedIds: ['brd-1'], revision: 2 });+ expect(result.content).toContain('Changed: brd-1');+ expect(onWorkRegistration).toHaveBeenCalledWith({+ action: 'register',+ artboard: {+ artboardId: 'art_1',+ changeType: 'updated',+ description: '首次进入',+ projectId: 'prj_1',+ title: '新用户首次进入项目',+ toolName: 'updateArtboard',+ },+ type: 'artboard',+ });+ });++ it('registers nothing when an update changes nothing', async () => {+ const update = vi.fn().mockResolvedValue({+ artboard: snapshot({ revision: 2 }),+ changedIds: [],+ ok: true,+ });+ const onWorkRegistration = vi.fn();+ const result = await new ArtboardExecutionRuntime(service({ update })).updateArtboard(+ { id: 'art_1', ops: [], revision: 1 },+ { onWorkRegistration },+ );++ expect(result.success).toBe(true);+ expect(result.content).toContain('Changed: nothing');+ expect(onWorkRegistration).not.toHaveBeenCalled();+ });++ it('reads the board with the file each board shows and the artboard files', async () => {+ const read = vi.fn().mockResolvedValue({+ artboard: snapshot(),+ files: [+ { hash: 'a1b2c3d4e5f6a7b8', path: 'pages/empty.html', size: 2048 },+ { hash: 'ffeeddccbbaa0099', path: 'shared.css', size: 120 },+ ],+ ok: true,+ });+ const result = await new ArtboardExecutionRuntime(service({ read })).readArtboard({+ id: 'art_1',+ });++ expect(result.success).toBe(true);+ expect(result.content).toContain('revision 1');+ expect(result.content).toContain('- abp_1 "Page 1"');+ expect(result.content).toContain(+ '- brd-1 on abp_1 in abg_1 "空项目" at (0, 0) 640×400 file pages/empty.html check: 看到接入入口',+ );+ expect(result.content).toContain('Files:\n- pages/empty.html 2048 B\n- shared.css 120 B');+ });++ it('tells the agent which boards point at a file not written yet', async () => {+ const base = snapshot();+ const read = vi.fn().mockResolvedValue({+ artboard: {+ ...base,+ content: {+ ...base.content,+ boards: [+ {+ ...base.content.boards[0],+ source: { hash: null, kind: 'file', path: 'pages/empty.html' },+ },+ ],+ },+ },+ files: [],+ ok: true,+ });+ const result = await new ArtboardExecutionRuntime(service({ read })).readArtboard({+ id: 'art_1',+ });++ expect(result.content).toContain('file pages/empty.html (missing: write it)');+ });++ it('writes artboard files and reports what changed', async () => {+ const writeFiles = vi.fn().mockResolvedValue({ ok: true, paths: ['pages/empty.html'] });+ const result = await new ArtboardExecutionRuntime(service({ writeFiles })).writeArtboardFiles({+ edits: [{ newText: 'b', oldText: 'a', path: 'pages/empty.html' }],+ id: 'art_1',+ });++ expect(writeFiles).toHaveBeenCalledWith({+ edits: [{ newText: 'b', oldText: 'a', path: 'pages/empty.html' }],+ id: 'art_1',+ });+ expect(result.success).toBe(true);+ expect(result.content).toBe('Saved 1 file on artboard art_1: pages/empty.html.');+ expect(result.state).toEqual({ artboardId: 'art_1', paths: ['pages/empty.html'] });+ });++ it('reads one artboard file as text', async () => {+ const readFile = vi.fn().mockResolvedValue({+ content: '<h1>空项目</h1>',+ ok: true,+ path: 'pages/empty.html',+ });+ const result = await new ArtboardExecutionRuntime(service({ readFile })).readArtboardFile({+ id: 'art_1',+ path: 'pages/empty.html',+ });++ expect(result.content).toBe('<h1>空项目</h1>');+ expect(result.state).toEqual({ path: 'pages/empty.html' });+ });++ it('reads a round with its recommendation and the user’s choice, and a decision branch', async () => {+ const base = snapshot().content;+ const option = { ...base.boards[0], expected: null, groupId: 'abg_2', roundId: 'rnd-1' };+ const read = vi.fn().mockResolvedValue({+ artboard: snapshot({+ content: {+ ...base,+ boards: [+ base.boards[0],+ { ...option, id: 'opt-a', title: '方案 A' },+ { ...option, id: 'opt-b', title: '方案 B' },+ {+ ...base.boards[0],+ expected: null,+ id: 'dec-1',+ source: null,+ title: '已付费?',+ type: 'decision',+ },+ ],+ edges: [+ {+ condition: '已付费',+ flowEdgeId: null,+ from: 'dec-1',+ id: 'edg-1',+ isDefault: true,+ label: '点「继续」',+ to: 'brd-1',+ },+ ],+ questions: [+ {+ boardId: 'brd-1',+ content: '能跳过吗?',+ groupId: null,+ id: 'cmt-9',+ pageId: 'abp_1',+ },+ ],+ rounds: [+ {+ batchId: null,+ chosenBoardId: 'opt-b',+ id: 'rnd-1',+ pageId: 'abp_1',+ recommendedBoardId: 'opt-a',+ status: 'submitted',+ title: '布局',+ },+ ],+ },+ }),+ files: [],+ ok: true,+ });+ const result = await new ArtboardExecutionRuntime(service({ read })).readArtboard({+ id: 'art_1',+ });++ expect(result.content).toContain(+ '- rnd-1 on abp_1 "布局" · submitted · recommended opt-a · chosen opt-b',+ );+ expect(result.content).toContain('- opt-a on abp_1 in abg_2 round rnd-1 "方案 A"');+ expect(result.content).toContain('"已付费?" at (0, 0) 640×400 decision');+ expect(result.content).toContain('- edg-1 dec-1 → brd-1 "点「继续」" if: 已付费 (default)');+ expect(result.content).toContain('- cmt-9 on board brd-1: 能跳过吗?');+ });++ it('lists comment threads with their replies and where they sit', async () => {+ const listComments = vi.fn().mockResolvedValue({+ ok: true,+ threads: [+ thread({+ replies: [+ {+ authorAgentId: 'agt_1',+ authorUserId: null,+ content: '改成 44px',+ createdAt: new Date('2026-11-13T00:01:00.000Z'),+ id: 'cmt-2',+ },+ ],+ }),+ ],+ });+ const result = await new ArtboardExecutionRuntime(+ service({ listComments }),+ ).listArtboardComments({ id: 'art_1' });++ expect(listComments).toHaveBeenCalledWith({ id: 'art_1' });+ expect(result.content).toContain('- cmt-1 on board brd-1 · user: 按钮太小了');+ expect(result.content).toContain(' - cmt-2 · agent: 改成 44px');+ expect(result.state).toEqual({ artboardId: 'art_1', threadCount: 1 });+ });++ it('says so when no thread is open', async () => {+ const listComments = vi.fn().mockResolvedValue({ ok: true, threads: [] });+ const result = await new ArtboardExecutionRuntime(+ service({ listComments }),+ ).listArtboardComments({ id: 'art_1' });++ expect(result.success).toBe(true);+ expect(result.content).toBe('No unresolved comments on artboard art_1.');+ });++ it('replies to, resolves and opens threads through the service', async () => {+ const replyComment = vi.fn().mockResolvedValue({ commentId: 'cmt-3', ok: true });+ const resolveComment = vi.fn().mockResolvedValue({ commentId: 'cmt-1', ok: true });+ const askQuestion = vi.fn().mockResolvedValue({ commentId: 'cmt-4', ok: true });+ const runtime = new ArtboardExecutionRuntime(+ service({ askQuestion, replyComment, resolveComment }),+ );++ const reply = await runtime.replyArtboardComment({ commentId: 'cmt-1', content: '已改' });+ const resolved = await runtime.resolveArtboardComment({ commentId: 'cmt-1' });+ const asked = await runtime.askArtboardQuestion({+ boardId: 'brd-1',+ content: '能跳过吗?',+ id: 'art_1',+ });++ expect(reply.content).toContain('cmt-3');+ expect(resolved.content).toContain('Resolved thread cmt-1');+ expect(asked.content).toContain('cmt-4');+ expect(asked.content).toContain('finalize');+ expect(askQuestion).toHaveBeenCalledWith({+ boardId: 'brd-1',+ content: '能跳过吗?',+ id: 'art_1',+ });+ });++ it('passes a refused comment call back as a failure', async () => {+ const resolveComment = vi+ .fn()+ .mockResolvedValue({ code: 'not_found', message: 'No comment cmt-x', ok: false });+ const result = await new ArtboardExecutionRuntime(+ service({ resolveComment }),+ ).resolveArtboardComment({ commentId: 'cmt-x' });++ expect(result.success).toBe(false);+ expect(result.error).toMatchObject({ type: 'not_found' });+ });+});diff --git a/packages/builtin-tool-artboard/src/ExecutionRuntime/index.ts b/packages/builtin-tool-artboard/src/ExecutionRuntime/index.tsnew file mode 100644index 00000000000..a05f9c89cef--- /dev/null+++ b/packages/builtin-tool-artboard/src/ExecutionRuntime/index.ts@@ -0,0 +1,296 @@+import type {+ ArtboardBoardView,+ ArtboardCommentThreadView,+ ArtboardCommentView,+ ArtboardContent,+ BuiltinServerRuntimeOutput,+ WorkRegistrationIntent,+} from '@lobechat/types';++import {+ ArtboardApiName,+ type ArtboardToolFailure,+ type ArtboardToolFile,+ type ArtboardToolService,+ type ArtboardToolSnapshot,+ type ArtboardToolState,+ type AskArtboardQuestionParams,+ type CreateArtboardParams,+ type ListArtboardCommentsParams,+ type ReadArtboardFileParams,+ type ReadArtboardParams,+ type ReplyArtboardCommentParams,+ type ResolveArtboardCommentParams,+ type UpdateArtboardParams,+ type WriteArtboardFilesParams,+} from '../types';++interface ArtboardRuntimeContext {+ onWorkRegistration?: (intent: WorkRegistrationIntent) => void;+}++export const describeArtboardContent = (content: ArtboardContent) =>+ `${content.groups.length} groups · ${content.boards.length} boards`;++const toState = (artboard: ArtboardToolSnapshot, changedIds: string[]): ArtboardToolState => ({+ artboardId: artboard.id,+ boardCount: artboard.content.boards.length,+ changedIds,+ groupCount: artboard.content.groups.length,+ phase: artboard.phase,+ revision: artboard.revision,+ title: artboard.title,+});++const HINTS: Record<string, string> = {+ conflict: `Call ${ArtboardApiName.readArtboard} for the latest revision, then apply your change to it.`,+ exists: `Use ${ArtboardApiName.readArtboard} and ${ArtboardApiName.updateArtboard} on that board instead.`,+ locked: 'Change other groups instead, or tell the user the journey is finalized.',+};++const failure = (outcome: ArtboardToolFailure): BuiltinServerRuntimeOutput => ({+ content: [outcome.message, HINTS[outcome.code]].filter(Boolean).join(' '),+ error: { message: outcome.message, type: outcome.code },+ success: false,+});++const formatSource = (board: ArtboardBoardView) => {+ if (board.type === 'decision') return 'decision';+ if (!board.source) return `${board.type} source unavailable`;+ // The board shows nothing until the file exists: tell the agent so it writes it.+ return `file ${board.source.path}${board.source.hash ? '' : ' (missing: write it)'}`;+};++const formatAnchor = (target: {+ boardId: string | null;+ groupId: string | null;+ pageId: string | null;+}) => {+ if (target.boardId) return `on board ${target.boardId}`;+ if (target.groupId) return `on group ${target.groupId}`;+ return target.pageId ? `on page ${target.pageId}` : 'on the artboard';+};++const formatBoard = (artboard: ArtboardToolSnapshot) => {+ const { boards, edges, groups, pages, questions, rounds } = artboard.content;+ return [+ `Artboard ${artboard.id} "${artboard.title}" · revision ${artboard.revision} · ${artboard.phase}`,+ 'Pages:',+ ...pages.map((p) => `- ${p.id} "${p.name}"`),+ 'Rounds:',+ ...rounds.map(+ (r) =>+ `- ${r.id} on ${r.pageId} "${r.title}" · ${r.status}${r.batchId ? ` · batch ${r.batchId}` : ''} · recommended ${r.recommendedBoardId ?? 'none'} · chosen ${r.chosenBoardId ?? 'none'}`,+ ),+ 'Groups:',+ ...groups.map(+ (g) => `- ${g.id} on ${g.pageId} [${g.kind}] ${g.title}${g.desc ? ` — ${g.desc}` : ''}`,+ ),+ 'Boards:',+ ...boards.map(+ (b) =>+ `- ${b.id} on ${b.pageId}${b.groupId ? ` in ${b.groupId}` : ''}${b.roundId ? ` round ${b.roundId}` : ''} "${b.title}" at (${b.rect.x}, ${b.rect.y}) ${b.rect.w}×${b.rect.h} ${formatSource(b)}${b.expected ? ` check: ${b.expected}` : ''}`,+ ),+ 'Edges:',+ ...edges.map(+ (e) =>+ `- ${e.id} ${e.from} → ${e.to}${e.label ? ` "${e.label}"` : ''}${e.condition ? ` if: ${e.condition}` : ''}${e.isDefault ? ' (default)' : ''}`,+ ),+ 'Your open questions:',+ ...questions.map((q) => `- ${q.id} ${formatAnchor(q)}: ${q.content}`),+ ].join('\n');+};++const formatAuthor = (comment: ArtboardCommentView) => (comment.authorAgentId ? 'agent' : 'user');++const formatThread = (thread: ArtboardCommentThreadView) =>+ [+ `- ${thread.id} ${formatAnchor(thread)} · ${formatAuthor(thread)}: ${thread.content}`,+ ...thread.replies.map((reply) => ` - ${reply.id} · ${formatAuthor(reply)}: ${reply.content}`),+ ].join('\n');++export class ArtboardExecutionRuntime {+ constructor(private service: ArtboardToolService) {}++ async createArtboard(+ params: CreateArtboardParams,+ context?: ArtboardRuntimeContext,+ ): Promise<BuiltinServerRuntimeOutput> {+ const outcome = await this.service.create(params);+ if (!outcome.ok) return failure(outcome);++ const { artboard, changedIds, task } = outcome;+ context?.onWorkRegistration?.({+ action: 'register',+ artboard: {+ artboardId: artboard.id,+ changeType: 'created',+ description: artboard.description,+ projectId: artboard.projectId,+ title: artboard.title,+ toolName: ArtboardApiName.createArtboard,+ },+ type: 'artboard',+ });++ const taskNote = task+ ? ` for task ${task.identifier}${task.createdTask ? ' (new task)' : ''}`+ : '';+ return {+ content: `Created artboard ${artboard.id} "${artboard.title}"${taskNote} · revision ${artboard.revision} · ${describeArtboardContent(artboard.content)}. The user sees it as a card under your reply; use ${ArtboardApiName.updateArtboard} with this id and revision for changes.`,+ state: toState(artboard, changedIds),+ success: true,+ };+ }++ async updateArtboard(+ params: UpdateArtboardParams,+ context?: ArtboardRuntimeContext,+ ): Promise<BuiltinServerRuntimeOutput> {+ const outcome = await this.service.update(params);+ if (!outcome.ok) return failure(outcome);++ const { artboard, changedIds } = outcome;++ // A real edit is a new Work version: it moves the card under this reply and+ // the version history to vN. A no-op edit (every op compared equal) stays+ // out of the history — nothing changed for the user to review.+ if (changedIds.length > 0) {+ context?.onWorkRegistration?.({+ action: 'register',+ artboard: {+ artboardId: artboard.id,+ changeType: 'updated',+ description: artboard.description,+ projectId: artboard.projectId,+ title: artboard.title,+ toolName: ArtboardApiName.updateArtboard,+ },+ type: 'artboard',+ });+ }++ return {+ content: `Updated artboard ${artboard.id} · revision ${artboard.revision} · ${describeArtboardContent(artboard.content)}. Changed: ${changedIds.join(', ') || 'nothing'}.`,+ state: toState(artboard, changedIds),+ success: true,+ };+ }++ async readArtboard(params: ReadArtboardParams): Promise<BuiltinServerRuntimeOutput> {+ const outcome = await this.service.read(params);+ if (!outcome.ok) return failure(outcome);++ const { artboard, files } = outcome;+ return {+ content: [+ formatBoard(artboard),+ 'Files:',+ ...files.map((file) => `- ${file.path} ${file.size} B`),+ ].join('\n'),+ state: toState(artboard, []),+ success: true,+ };+ }++ async writeArtboardFiles(params: WriteArtboardFilesParams): Promise<BuiltinServerRuntimeOutput> {+ const outcome = await this.service.writeFiles(params);+ if (!outcome.ok) return failure(outcome);+ const { paths } = outcome;+ const count = `${paths.length} file${paths.length === 1 ? '' : 's'}`;+ return {+ content: paths.length+ ? `Saved ${count} on artboard ${params.id}: ${paths.join(', ')}.`+ : `Saved no new content on artboard ${params.id}.`,+ state: { artboardId: params.id, paths },+ success: true,+ };+ }++ async readArtboardFile(params: ReadArtboardFileParams): Promise<BuiltinServerRuntimeOutput> {+ const outcome = await this.service.readFile(params);+ if (!outcome.ok) return failure(outcome);+ return {+ content: outcome.content ?? `${outcome.path} is binary; it has no text to show.`,+ state: { path: outcome.path },+ success: true,+ };+ }++ async listArtboards(): Promise<BuiltinServerRuntimeOutput> {+ const outcome = await this.service.list();+ if (!outcome.ok) return failure(outcome);+ if (!outcome.artboards.length)+ return {+ content: 'No artboards in this project yet.',+ state: { artboards: [] },+ success: true,+ };++ return {+ content: outcome.artboards+ .map(+ (a) => `- ${a.id} "${a.title}" · task ${a.taskId} · ${a.phase} · revision ${a.revision}`,+ )+ .join('\n'),+ state: { artboards: outcome.artboards },+ success: true,+ };+ }++ async listArtboardComments(+ params: ListArtboardCommentsParams,+ ): Promise<BuiltinServerRuntimeOutput> {+ const outcome = await this.service.listComments(params);+ if (!outcome.ok) return failure(outcome);++ const { threads } = outcome;+ return {+ content: threads.length+ ? [+ `Unresolved comments on artboard ${params.id}:`,+ ...threads.map(formatThread),+ `Answer with ${ArtboardApiName.replyArtboardComment}; close a thread you have dealt with using ${ArtboardApiName.resolveArtboardComment}.`,+ ].join('\n')+ : `No unresolved comments on artboard ${params.id}.`,+ state: { artboardId: params.id, threadCount: threads.length },+ success: true,+ };+ }++ async replyArtboardComment(+ params: ReplyArtboardCommentParams,+ ): Promise<BuiltinServerRuntimeOutput> {+ const outcome = await this.service.replyComment(params);+ if (!outcome.ok) return failure(outcome);+ return {+ content: `Replied in thread ${params.commentId} as comment ${outcome.commentId}.`,+ state: { commentId: outcome.commentId },+ success: true,+ };+ }++ async resolveArtboardComment(+ params: ResolveArtboardCommentParams,+ ): Promise<BuiltinServerRuntimeOutput> {+ const outcome = await this.service.resolveComment(params);+ if (!outcome.ok) return failure(outcome);+ return {+ content: `Resolved thread ${outcome.commentId}.`,+ state: { commentId: outcome.commentId },+ success: true,+ };+ }++ async askArtboardQuestion(+ params: AskArtboardQuestionParams,+ ): Promise<BuiltinServerRuntimeOutput> {+ const outcome = await this.service.askQuestion(params);+ if (!outcome.ok) return failure(outcome);+ return {+ content: `Asked as thread ${outcome.commentId} on artboard ${params.id}. The user answers on the board; the board cannot finalize until you resolve this thread with ${ArtboardApiName.resolveArtboardComment}.`,+ state: { artboardId: params.id, commentId: outcome.commentId },+ success: true,+ };+ }+}diff --git a/packages/builtin-tool-artboard/src/client/Inspector/index.tsx b/packages/builtin-tool-artboard/src/client/Inspector/index.tsxnew file mode 100644index 00000000000..c953fc3c330--- /dev/null+++ b/packages/builtin-tool-artboard/src/client/Inspector/index.tsx@@ -0,0 +1,56 @@+'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 { ArtboardApiNameType, ArtboardToolState } from '../../types';+import { ArtboardApiName, ArtboardIdentifier } 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',+ },+});++type Props = BuiltinInspectorProps<Record<string, any>, ArtboardToolState>;++const createInspector = (apiName: ArtboardApiNameType) => {+ const Inspector = memo<Props>((props) => {+ const { t } = useTranslation('plugin');+ const args = { ...props.partialArgs, ...props.args };+ const chip = props.pluginState?.title ?? args.title ?? args.id;+ const busy = !!(props.isArgumentsStreaming || props.isLoading);++ return (+ <div className={inspectorTextStyles.root}>+ <span className={cx(busy && shinyTextStyles.shinyText)}>+ {t(`builtins.${ArtboardIdentifier}.apiName.${apiName}`)}+ </span>+ {chip && <span {...stylex.props(styles.chip)}>{chip}</span>}+ </div>+ );+ });+ Inspector.displayName = `Artboard${apiName}Inspector`;+ return Inspector as unknown as BuiltinInspector;+};++export const ArtboardInspectors: Record<string, BuiltinInspector> = Object.fromEntries(+ Object.values(ArtboardApiName).map((apiName) => [apiName, createInspector(apiName)]),+);diff --git a/packages/builtin-tool-artboard/src/client/index.ts b/packages/builtin-tool-artboard/src/client/index.tsnew file mode 100644index 00000000000..b77c4a8a24f--- /dev/null+++ b/packages/builtin-tool-artboard/src/client/index.ts@@ -0,0 +1,3 @@+export { ArtboardManifest } from '../manifest';+export * from '../types';+export { ArtboardInspectors } from './Inspector';diff --git a/packages/builtin-tool-artboard/src/index.ts b/packages/builtin-tool-artboard/src/index.tsnew file mode 100644index 00000000000..44f9459495d--- /dev/null+++ b/packages/builtin-tool-artboard/src/index.ts@@ -0,0 +1,3 @@+export { ArtboardManifest } from './manifest';+export { systemPrompt } from './systemRole';+export * from './types';diff --git a/packages/builtin-tool-artboard/src/manifest.ts b/packages/builtin-tool-artboard/src/manifest.tsnew file mode 100644index 00000000000..f87cc97fb8b--- /dev/null+++ b/packages/builtin-tool-artboard/src/manifest.ts@@ -0,0 +1,278 @@+import type { BuiltinToolManifest } from '@lobechat/types';++import { systemPrompt } from './systemRole';+import { ArtboardApiName, ArtboardIdentifier } from './types';++const OP_TYPES = [+ 'addPage',+ 'updatePage',+ 'removePage',+ 'addRound',+ 'updateRound',+ 'addGroup',+ 'updateGroup',+ 'removeGroup',+ 'addBoard',+ 'updateBoard',+ 'removeBoard',+ 'addEdge',+ 'removeEdge',+ 'setCheck',+];++const sourceSchema = {+ description:+ 'What the board shows: {kind:"file", path} of a file of this artboard, an .html page or an image (png/jpg/webp/gif/svg). Write the file in the same call (files) or before it. A decision board has no source.',+ properties: {+ kind: { enum: ['file'], type: 'string' },+ path: { type: 'string' },+ },+ required: ['kind', 'path'],+ type: 'object',+};++const filesSchema = {+ description:+ 'Files of the artboard, applied before the ops. Paths are relative, like pages/checkout/a.html or shared/base.css; pages reference each other and assets by relative paths. HTML is any HTML you would write for a browser: your own CSS, colors, fonts, inline SVG and scripts. Pages cannot fetch or open network connections; https images, fonts, styles and scripts load.',+ properties: {+ deletes: {+ description: 'Paths to delete. Boards showing a deleted file show it as missing.',+ items: { type: 'string' },+ type: 'array',+ },+ edits: {+ description: 'Exact-text edits: oldText must appear once in the file.',+ items: {+ properties: {+ newText: { type: 'string' },+ oldText: { type: 'string' },+ path: { type: 'string' },+ },+ required: ['path', 'oldText', 'newText'],+ type: 'object',+ },+ type: 'array',+ },+ writes: {+ description:+ 'Whole files: {path, content} for text (html, css, js, json, svg), {path, fileRef} to copy an image from <file id> or <image ref> in this conversation, or {path, fromCanvas: {canvasId, version?}} to copy a Canvas page in (its assets land next to it).',+ items: {+ properties: {+ content: { type: 'string' },+ fileRef: { type: 'string' },+ fromCanvas: {+ properties: { canvasId: { type: 'string' }, version: { type: 'integer' } },+ required: ['canvasId'],+ type: 'object',+ },+ path: { type: 'string' },+ },+ required: ['path'],+ type: 'object',+ },+ type: 'array',+ },+ },+ type: 'object',+};++const boardSchema = {+ properties: {+ expected: { type: 'string' },+ groupId: { type: 'string' },+ h: { type: 'number' },+ pageId: { type: 'string' },+ recommended: { type: 'boolean' },+ roundId: { type: 'string' },+ source: sourceSchema,+ title: { type: 'string' },+ type: { enum: ['html', 'image', 'video', 'decision'], type: 'string' },+ w: { type: 'number' },+ x: { type: 'number' },+ y: { type: 'number' },+ },+ type: 'object',+};++const opSchema = {+ description: [+ 'One change. Fields per type:',+ 'addPage {page:{name}}; updatePage {id, patch:{name}}; removePage {id} (only when empty, never the last page);',+ 'addRound {round:{title, pageId?, batchId?}} opens one choice question, rounds sharing a batchId are submitted together; updateRound {id, patch:{title}};',+ 'addGroup {group:{title, kind: journey|options|references|other, desc?, pageId?}};',+ 'updateGroup {id, patch:{title?, kind?, desc?}}; removeGroup {id} (only when empty);',+ 'addBoard {board:{title, x, y, w?, h?, groupId?, roundId?, pageId?, type?, source?, recommended?, expected?}}: x/y are page coordinates, size defaults to 640×400, type defaults from the source, type "decision" is a branch point with no source, roundId makes the board an option of that round and recommended marks your pick, expected is the acceptance check of a journey board;',+ 'updateBoard {id, patch:{title?, x?, y?, w?, h?, groupId?, roundId?, source?, recommended?, expected?}} (groupId or roundId null detaches); removeBoard {id} (also removes its edges);',+ 'addEdge {edge:{from, to, label?, condition?, isDefault?}} where label is what the user does in at most four words and is left out when the two screens already make the step obvious, condition is when a branch out of a decision board is taken and isDefault marks its fallback branch; removeEdge {id};',+ 'setCheck {boardId, expected} for a journey board.',+ 'pageId defaults to the first page. Add ops may set ref; later ops in the same call use that ref wherever an id is expected.',+ ].join(' '),+ properties: {+ board: boardSchema,+ boardId: { type: 'string' },+ edge: { type: 'object' },+ expected: { type: 'string' },+ group: { type: 'object' },+ id: { type: 'string' },+ page: { type: 'object' },+ patch: { properties: { source: sourceSchema }, type: 'object' },+ ref: { type: 'string' },+ round: { type: 'object' },+ type: { enum: OP_TYPES, type: 'string' },+ },+ required: ['type'],+ type: 'object',+};++const idSchema = {+ description: 'Artboard id returned by createArtboard or listArtboards.',+ type: 'string',+};++export const ArtboardManifest: BuiltinToolManifest = {+ api: [+ {+ description:+ "Create the artboard for a requirement task: the HTML pages and images it shows (files), groups of boards, edges for the user journey, and rounds of options for the user to choose from. Without taskId it uses this run's task, or creates a task titled `title` in the current project. One task has at most one artboard.",+ name: ArtboardApiName.createArtboard,+ parameters: {+ additionalProperties: false,+ properties: {+ description: { description: 'One line shown on the board card.', type: 'string' },+ files: filesSchema,+ ops: {+ description: 'Initial content, built with the same ops as updateArtboard.',+ items: opSchema,+ type: 'array',+ },+ taskId: { description: 'Task id or identifier such as PRJ-12.', type: 'string' },+ title: { description: 'Board title, usually the requirement.', type: 'string' },+ },+ required: ['title'],+ type: 'object',+ },+ },+ {+ description:+ 'Apply file changes and ops to an artboard. Either everything applies or nothing does. Pass the revision you last read; a stale revision is refused, so call readArtboard and retry.',+ name: ArtboardApiName.updateArtboard,+ parameters: {+ additionalProperties: false,+ properties: {+ files: filesSchema,+ id: idSchema,+ ops: { items: opSchema, type: 'array' },+ revision: { description: 'Revision from the last read or write.', type: 'integer' },+ },+ required: ['id', 'revision'],+ type: 'object',+ },+ },+ {+ description:+ 'Read an artboard: its pages, rounds with the user’s submitted choices, groups, boards with the file each shows, edges, your open questions, the revision, the phase, and its files.',+ name: ArtboardApiName.readArtboard,+ parameters: {+ additionalProperties: false,+ properties: { id: idSchema },+ required: ['id'],+ type: 'object',+ },+ },+ {+ description:+ 'Write, edit or delete files of an artboard without touching the layout; needs no revision. Use it to fill in the boards one per call after laying them out, and to fix a page after a comment. Each board showing a written file updates for the user as it lands.',+ name: ArtboardApiName.writeArtboardFiles,+ parameters: {+ additionalProperties: false,+ properties: { ...filesSchema.properties, id: idSchema },+ required: ['id'],+ type: 'object',+ },+ // Parallel edits to one artboard would race: run them one after another.+ serializeBy: 'id',+ },+ {+ description: 'Read one file of an artboard, to edit it with exact text.',+ name: ArtboardApiName.readArtboardFile,+ parameters: {+ additionalProperties: false,+ properties: {+ id: idSchema,+ path: { description: 'File path, as listed by readArtboard.', type: 'string' },+ },+ required: ['id', 'path'],+ type: 'object',+ },+ },+ {+ description: 'List the artboards in the current project.',+ name: ArtboardApiName.listArtboards,+ parameters: { additionalProperties: false, properties: {}, type: 'object' },+ },+ {+ description:+ 'List the unresolved comment threads on an artboard, with their replies and what each one is attached to. Threads returned here count as read by you.',+ name: ArtboardApiName.listArtboardComments,+ parameters: {+ additionalProperties: false,+ properties: { id: idSchema },+ required: ['id'],+ type: 'object',+ },+ },+ {+ description: 'Reply in a comment thread on an artboard.',+ name: ArtboardApiName.replyArtboardComment,+ parameters: {+ additionalProperties: false,+ properties: {+ commentId: { description: 'Id of the thread, or of any comment in it.', type: 'string' },+ content: { description: 'Plain text.', type: 'string' },+ },+ required: ['commentId', 'content'],+ type: 'object',+ },+ },+ {+ description:+ 'Mark a comment thread resolved once what it asks for is done, or once your question in it is answered.',+ name: ArtboardApiName.resolveArtboardComment,+ parameters: {+ additionalProperties: false,+ properties: {+ commentId: { description: 'Id of the first comment of the thread.', type: 'string' },+ },+ required: ['commentId'],+ type: 'object',+ },+ },+ {+ description:+ 'Ask the user a question on the artboard as a new comment thread, attached to a board, a group or a page. The board cannot be finalized while the thread is unresolved.',+ name: ArtboardApiName.askArtboardQuestion,+ parameters: {+ additionalProperties: false,+ properties: {+ boardId: { description: 'Board the question is about.', type: 'string' },+ content: {+ description: 'The question in plain text, with your suggestion.',+ type: 'string',+ },+ groupId: { description: 'Group the question is about.', type: 'string' },+ id: idSchema,+ pageId: {+ description: 'Page the question is about; defaults to the first page.',+ type: 'string',+ },+ },+ required: ['id', 'content'],+ type: 'object',+ },+ },+ ],+ identifier: ArtboardIdentifier,+ meta: { avatar: '🎨', title: 'Artboard' },+ systemRole: systemPrompt,+ type: 'builtin',+};diff --git a/packages/builtin-tool-artboard/src/systemRole.ts b/packages/builtin-tool-artboard/src/systemRole.tsnew file mode 100644index 00000000000..0c9398b6fa7--- /dev/null+++ b/packages/builtin-tool-artboard/src/systemRole.ts@@ -0,0 +1,44 @@+export const systemPrompt = `You can lay out a requirement on an artboard: a board in the project where the team discusses the flow and the options with you.++<when_to_use>+- Use an artboard when a requirement needs its flow or its options discussed, not for a single screen.+- Each screen is an HTML page you write as a file of the artboard (e.g. pages/checkout/a.html), shown by a board with source {kind:"file", path}. Write it as a real screen of the product at the board's size: your own layout, colors, type and inline SVG. Shared CSS or images go in their own files and are referenced by relative paths. A screenshot or photo from the conversation can be a board too: copy it in with {path, fileRef}. An existing Canvas can be copied in with {path, fromCanvas: {canvasId}}.+</when_to_use>++<order>+- Lay out first, then fill in: one createArtboard (or updateArtboard) call with every page, group, edge and board, each board's source pointing at the path its file will have. Do not write the files in that call.+- Then write the files with writeArtboardFiles, one board per call (shared CSS and images first, then the pages that use them). The user sees each board appear as its file lands.+- A board whose file is not written yet shows as missing; readArtboard marks it "(missing: write it)". Write it, or point the board at another path.+</order>++<layout>+- An artboard has pages; each page is its own canvas with its own coordinates. Everything lands on the first page unless you pass pageId.+- Group boards: one journey group for the flow that will be accepted, plus groups for options, references and anything else.+- In the journey group, one board is one page state. Edges connect boards. An edge's label is optional: add one, in at most four words, only when the two screens do not already show what the user does to get there.+- Where the flow branches, add a board of type "decision" (no source) and give each edge leaving it a condition; mark the fallback branch isDefault.+- Give every journey board an acceptance check (expected on addBoard, or setCheck): what the user must see on that page. A decision board needs none.+- You place every board; the user cannot move them. Boards are 640×400 unless you set w and h. x and y are page coordinates.+- Leave 80 between boards in a row and lay a journey out left to right. The group frame is drawn around its boards for you (144 above, 48 on the other sides), so leave 240 between the boards of two groups stacked vertically and 200 between groups side by side. Measure from the lowest and rightmost board of a group, not its first row: a journey with a branch below the main row is taller. An update whose group frames overlap is refused.+</layout>++<options>+- To let the user choose between designs, add a round (addRound) whose title is the question, then add each design as a board in an options group with that roundId. Set recommended on the one you would pick.+- One options group holds the options of exactly one round, and a round's options all sit in that one group. The round title is shown under the group title as the question.+- The user submits every open round of the artboard at once, so open only the rounds you want answered now.+- The user picks one board per round and submits. After that readArtboard shows the round as submitted with its chosenBoardId; an unpicked round takes your recommendation.+</options>++<discussion>+- When you are not sure about something, ask with askArtboardQuestion (with your suggestion) on the board, group or page it concerns instead of deciding for the user.+- The user comments on the artboard. Read new feedback with listArtboardComments, answer with replyArtboardComment, and close a thread with resolveArtboardComment once it is dealt with.+- Comments on the options of a round that is still open are held back until the user submits; read them with listArtboardComments after the submit message arrives. Threads the user resolved themselves are not handed to you.+- A round that is still open, or a question of yours that is unresolved, blocks finalizing the artboard.+</discussion>++<editing>+- When a user message quotes items from the artboard, call readArtboard first, then make every change the message asks for in one updateArtboard call.+- updateArtboard needs the revision you last saw. If it is refused as stale, read again and redo the change on the new revision. Comments and choices do not change the revision.+- To change what a board shows, change its file: writeArtboardFiles with edits (read the file first with readArtboardFile) or a whole new write. Every board showing that file updates, and comments on it are marked outdated.+- Ids are the ones the tool returns; never invent one. Use ref on add ops so later ops in the same call can point at what you just added.+- After the artboard is finalized, the journey group's boards, edges and checks are locked; other groups can still change.+</editing>`;diff --git a/packages/builtin-tool-artboard/src/types.ts b/packages/builtin-tool-artboard/src/types.tsnew file mode 100644index 00000000000..8d2e7164a30--- /dev/null+++ b/packages/builtin-tool-artboard/src/types.ts@@ -0,0 +1,154 @@+import type { ArtboardCommentThreadView, ArtboardContent, ArtboardPhase } from '@lobechat/types';++export const ArtboardIdentifier = 'builtin-artboard';++export const ArtboardApiName = {+ askArtboardQuestion: 'askArtboardQuestion',+ createArtboard: 'createArtboard',+ listArtboardComments: 'listArtboardComments',+ listArtboards: 'listArtboards',+ readArtboard: 'readArtboard',+ readArtboardFile: 'readArtboardFile',+ replyArtboardComment: 'replyArtboardComment',+ resolveArtboardComment: 'resolveArtboardComment',+ updateArtboard: 'updateArtboard',+ writeArtboardFiles: 'writeArtboardFiles',+} as const;++export type ArtboardApiNameType = (typeof ArtboardApiName)[keyof typeof ArtboardApiName];++export interface ArtboardFilesParams {+ deletes?: unknown[];+ edits?: unknown[];+ writes?: unknown[];+}++export interface CreateArtboardParams {+ description?: string;+ files?: ArtboardFilesParams;+ ops?: unknown[];+ taskId?: string;+ title: string;+}++export interface UpdateArtboardParams {+ files?: ArtboardFilesParams;+ id: string;+ ops?: unknown[];+ revision: number;+}++export interface WriteArtboardFilesParams extends ArtboardFilesParams {+ id: string;+}++export interface ReadArtboardFileParams {+ id: string;+ path: string;+}++export interface ArtboardToolFile {+ hash: string;+ path: string;+ size: number;+}++export interface ReadArtboardParams {+ id: string;+}++export interface ListArtboardCommentsParams {+ id: string;+}++export interface ReplyArtboardCommentParams {+ commentId: string;+ content: string;+}++export interface ResolveArtboardCommentParams {+ commentId: string;+}++export interface AskArtboardQuestionParams {+ boardId?: string;+ content: string;+ groupId?: string;+ id: string;+ pageId?: string;+}++export interface ArtboardToolSnapshot {+ content: ArtboardContent;+ description: string | null;+ id: string;+ phase: ArtboardPhase;+ projectId: string | null;+ revision: number;+ taskId: string | null;+ title: string;+}++export interface ArtboardToolFailure {+ code: string;+ message: string;+ ok: false;+}++export type ArtboardToolWriteOutcome =+ | {+ artboard: ArtboardToolSnapshot;+ changedIds: string[];+ ok: true;+ task?: { createdTask: boolean; identifier: string };+ }+ | ArtboardToolFailure;++export type ArtboardToolReadOutcome =+ | {+ artboard: ArtboardToolSnapshot;+ files: ArtboardToolFile[];+ ok: true;+ }+ | ArtboardToolFailure;++/** Paths written or deleted. */+export type ArtboardToolFilesOutcome = { ok: true; paths: string[] } | ArtboardToolFailure;++export type ArtboardToolFileOutcome =+ { content: string | null; ok: true; path: string } | ArtboardToolFailure;++export type ArtboardToolListOutcome =+ | {+ artboards: Pick<ArtboardToolSnapshot, 'id' | 'phase' | 'revision' | 'taskId' | 'title'>[];+ ok: true;+ }+ | ArtboardToolFailure;++export type ArtboardToolCommentsOutcome =+ { ok: true; threads: ArtboardCommentThreadView[] } | ArtboardToolFailure;++export type ArtboardToolCommentOutcome = { commentId: string; ok: true } | ArtboardToolFailure;++export interface ArtboardToolService {+ askQuestion: (params: AskArtboardQuestionParams) => Promise<ArtboardToolCommentOutcome>;+ create: (params: CreateArtboardParams) => Promise<ArtboardToolWriteOutcome>;+ list: () => Promise<ArtboardToolListOutcome>;+ listComments: (params: ListArtboardCommentsParams) => Promise<ArtboardToolCommentsOutcome>;+ read: (params: ReadArtboardParams) => Promise<ArtboardToolReadOutcome>;+ readFile: (params: ReadArtboardFileParams) => Promise<ArtboardToolFileOutcome>;+ replyComment: (params: ReplyArtboardCommentParams) => Promise<ArtboardToolCommentOutcome>;+ resolveComment: (params: ResolveArtboardCommentParams) => Promise<ArtboardToolCommentOutcome>;+ update: (params: UpdateArtboardParams) => Promise<ArtboardToolWriteOutcome>;+ writeFiles: (params: WriteArtboardFilesParams) => Promise<ArtboardToolFilesOutcome>;+}++export interface ArtboardToolState {+ artboardId: string;+ boardCount: number;+ changedIds: string[];+ groupCount: number;+ phase: ArtboardPhase;+ revision: number;+ title: string;+}diff --git a/packages/builtin-tool-artboard/vitest.config.mts b/packages/builtin-tool-artboard/vitest.config.mtsnew file mode 100644index 00000000000..4ac6027d578--- /dev/null+++ b/packages/builtin-tool-artboard/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.jsonindex 8209957a556..900d121f23a 100644--- a/packages/builtin-tools/package.json+++ b/packages/builtin-tools/package.json@@ -31,6 +31,7 @@"@lobechat/builtin-tool-agent-documents": "workspace:*","@lobechat/builtin-tool-agent-management": "workspace:*","@lobechat/builtin-tool-agent-signal": "workspace:*",+ "@lobechat/builtin-tool-artboard": "workspace:*","@lobechat/builtin-tool-attachments": "workspace:*","@lobechat/builtin-tool-auv": "workspace:*","@lobechat/builtin-tool-brief": "workspace:*",diff --git a/packages/builtin-tools/src/dynamicInterventionAudits.ts b/packages/builtin-tools/src/dynamicInterventionAudits.tsindex 2bcfe47fcaa..e48c61f900c 100644--- a/packages/builtin-tools/src/dynamicInterventionAudits.ts+++ b/packages/builtin-tools/src/dynamicInterventionAudits.ts@@ -1,3 +1,4 @@+import { ACTIVATE_TOOLS_AUDIT, activateToolsAudit } from '@lobechat/builtin-tool-activator';import {AGENT_ACCOUNT_OUTBOUND_AUDIT,agentAccountOutboundAudit,@@ -12,6 +13,7 @@ export const dynamicInterventionAudits: Record<string, DynamicInterventionResolv// can read the version (agent runtime service, client streaming executor)// register a loader-backed audit under the same key.[DASHBOARD_DRY_RUN_AUDIT]: createDryRunAudit(),+ [ACTIVATE_TOOLS_AUDIT]: activateToolsAudit,[AGENT_ACCOUNT_OUTBOUND_AUDIT]: agentAccountOutboundAudit,// Permanent deletion asks, unless the storage service will itself refuse// anything that is not a dependency, cache or build output.diff --git a/packages/builtin-tools/src/featureGates.test.ts b/packages/builtin-tools/src/featureGates.test.tsindex 16c40ec4116..54590fc303d 100644--- a/packages/builtin-tools/src/featureGates.test.ts+++ b/packages/builtin-tools/src/featureGates.test.ts@@ -1,3 +1,4 @@+import { ArtboardIdentifier } from '@lobechat/builtin-tool-artboard';import { DashboardIdentifier, LegacyDashboardIdentifier } from '@lobechat/builtin-tool-dashboard';import { WebhookIdentifier } from '@lobechat/builtin-tool-webhook';import { describe, expect, it } from 'vitest';@@ -15,6 +16,11 @@ describe('feature-gated builtin tools', () => {);});+ it('drops the artboard tool unless the artboard flag is on', () => {+ expect(getFeatureDisabledToolIds(undefined)).toContain(ArtboardIdentifier);+ expect(getFeatureDisabledToolIds({ enableArtboard: true })).not.toContain(ArtboardIdentifier);+ });+it('only gates tools that declare a flag', () => {expect(isToolEnabledByFeatureFlags(DashboardIdentifier, {})).toBe(false);expect(isToolEnabledByFeatureFlags(DashboardIdentifier, { enableDashboard: true })).toBe(true);diff --git a/packages/builtin-tools/src/featureGates.ts b/packages/builtin-tools/src/featureGates.tsindex 128bca29fa6..451d021926d 100644--- a/packages/builtin-tools/src/featureGates.ts+++ b/packages/builtin-tools/src/featureGates.ts@@ -1,9 +1,11 @@+import { ArtboardIdentifier } from '@lobechat/builtin-tool-artboard';import { DashboardIdentifier, LegacyDashboardIdentifier } from '@lobechat/builtin-tool-dashboard';import { WebhookIdentifier } from '@lobechat/builtin-tool-webhook';import type { IFeatureFlagsState } from '@lobechat/types';/** Builtin tools that exist only while a runtime feature flag is on for the user. */export const FEATURE_GATED_TOOLS: Record<string, keyof IFeatureFlagsState> = {+ [ArtboardIdentifier]: 'enableArtboard',[DashboardIdentifier]: 'enableDashboard',// A legacy pinned or replayed id must stay behind the same flag.[LegacyDashboardIdentifier]: 'enableDashboard',diff --git a/packages/builtin-tools/src/identifiers.ts b/packages/builtin-tools/src/identifiers.tsindex e1bcf1b124b..fea398dcaf5 100644--- a/packages/builtin-tools/src/identifiers.ts+++ b/packages/builtin-tools/src/identifiers.ts@@ -9,6 +9,7 @@ import {agentSignalReviewManifest,agentSignalSkillManagementManifest,} from '@lobechat/builtin-tool-agent-signal';+import { ArtboardManifest } from '@lobechat/builtin-tool-artboard';import { AttachmentsManifest } from '@lobechat/builtin-tool-attachments';import { AuvManifest } from '@lobechat/builtin-tool-auv';import { BrowserManifest } from '@lobechat/builtin-tool-browser';@@ -51,6 +52,7 @@ export const builtinToolIdentifiers: string[] = [AgentBuilderManifest.identifier,AgentDocumentsManifest.identifier,AgentManagementManifest.identifier,+ ArtboardManifest.identifier,AttachmentsManifest.identifier,AuvManifest.identifier,CalculatorManifest.identifier,diff --git a/packages/builtin-tools/src/index.ts b/packages/builtin-tools/src/index.tsindex 2259965b9fb..76635ac9c6c 100644--- a/packages/builtin-tools/src/index.ts+++ b/packages/builtin-tools/src/index.ts@@ -16,6 +16,7 @@ import {agentSignalReviewManifest,agentSignalSkillManagementManifest,} from '@lobechat/builtin-tool-agent-signal';+import { ArtboardManifest } from '@lobechat/builtin-tool-artboard';import { AttachmentsManifest } from '@lobechat/builtin-tool-attachments';import { AuvManifest } from '@lobechat/builtin-tool-auv';import { BriefManifest } from '@lobechat/builtin-tool-brief';@@ -596,6 +597,15 @@ const builtinToolRegistry: LobeBuiltinTool[] = [manifest: CanvasManifest,type: 'builtin',},+ {+ // Server tool discovery adds it to project conversations only; it has no+ // client executor, so it must never be pinned or discovered.+ discoverable: false,+ hidden: true,+ identifier: ArtboardManifest.identifier,+ manifest: ArtboardManifest,+ 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.tsindex 15cc79d17db..cbf9eefbfb0 100644--- a/packages/builtin-tools/src/register.ts+++ b/packages/builtin-tools/src/register.ts@@ -23,6 +23,7 @@ import {AgentManagementRenders,AgentManagementStreamings,} from '@lobechat/builtin-tool-agent-management/client';+import { ArtboardInspectors, ArtboardManifest } from '@lobechat/builtin-tool-artboard/client';import { AuvIdentifier, AuvInspectors } from '@lobechat/builtin-tool-auv/client';import {BrowserInspectors,@@ -414,6 +415,7 @@ export const registerBuiltinToolSurfaces = (): void => {>,[SkillStoreManifest.identifier]: SkillStoreInspectors as Record<string, BuiltinInspector>,[SkillsManifest.identifier]: SkillsInspectors as Record<string, BuiltinInspector>,+ [ArtboardManifest.identifier]: ArtboardInspectors,[CanvasManifest.identifier]: CanvasInspectors,[DashboardManifest.identifier]: DashboardInspectors as Record<string, BuiltinInspector>,// Dashboard tool calls persisted before the rename to `builtin-dashboard`.diff --git a/packages/builtin-tools/src/workRegistration.test.ts b/packages/builtin-tools/src/workRegistration.test.tsindex 238ba34f44c..355e5acd105 100644--- a/packages/builtin-tools/src/workRegistration.test.ts+++ b/packages/builtin-tools/src/workRegistration.test.ts@@ -634,3 +634,51 @@ describe('dispatchWorkRegistrationIntent · canvas', () => {).resolves.toBeUndefined();});});++describe('dispatchWorkRegistrationIntent · artboard', () => {+ it('registers the artboard version with provenance and its project', async () => {+ const registerArtboard = vi.fn().mockResolvedValue(undefined);+ await dispatchWorkRegistrationIntent(+ {+ action: 'register',+ artboard: {+ artboardId: 'art_1',+ changeType: 'created',+ description: '3 组 · 10 个画面',+ projectId: 'prj_1',+ title: '新用户首次进入项目',+ toolName: 'createArtboard',+ },+ type: 'artboard',+ },+ {+ deleteTaskWork: vi.fn(),+ handleSkillToolResult: vi.fn(),+ registerArtboard,+ registerDocument: vi.fn(),+ registerTask: vi.fn(),+ },+ {+ agentId: 'agent-1',+ messageId: 'msg-1',+ rootOperationId: 'op-root',+ toolCallId: 'call-1',+ toolIdentifier: 'builtin-artboard',+ toolName: 'createArtboard',+ topicId: 'topic-1',+ },+ );++ expect(registerArtboard).toHaveBeenCalledWith(+ expect.objectContaining({+ artboardId: 'art_1',+ changeType: 'created',+ projectId: 'prj_1',+ rootOperationId: 'op-root',+ toolCallId: 'call-1',+ toolIdentifier: 'builtin-artboard',+ toolName: 'createArtboard',+ }),+ );+ });+});diff --git a/packages/builtin-tools/src/workRegistration.ts b/packages/builtin-tools/src/workRegistration.tsindex bfde7526fba..abfe5756bf1 100644--- a/packages/builtin-tools/src/workRegistration.ts+++ b/packages/builtin-tools/src/workRegistration.ts@@ -6,6 +6,7 @@ import type {PluginApiWorkAction,PluginApiWorkConfig,PluginApiWorkResourceType,+ RegisterArtboardWorkParams,RegisterCanvasWorkParams,RegisterDocumentWorkParams,RegisterSkillToolResultWorkParams,@@ -282,6 +283,7 @@ export interface WorkRegistrationPorts {deleteDocumentWork?: (params: DeleteDocumentWorkParams) => Promise<unknown>;deleteTaskWork: (params: DeleteTaskWorkParams) => Promise<unknown>;handleSkillToolResult: (params: RegisterSkillToolResultWorkParams) => Promise<unknown>;+ registerArtboard?: (params: RegisterArtboardWorkParams) => Promise<unknown>;registerCanvas?: (params: RegisterCanvasWorkParams) => Promise<unknown>;registerDocument: (params: RegisterDocumentWorkParams) => Promise<unknown>;registerTask: (params: RegisterTaskWorkParams) => Promise<unknown>;@@ -431,6 +433,37 @@ const dispatchDocumentWorkIntent = async (});};+const dispatchArtboardWorkIntent = async (+ intent: WorkRegistrationIntentFor<'artboard'>,+ ports: WorkRegistrationPorts,+ provenance: WorkRegistrationProvenance,+): Promise<void> => {+ const {+ agentId,+ cumulativeCost,+ cumulativeUsage,+ messageId,+ rootOperationId,+ threadId,+ toolCallId,+ toolIdentifier,+ topicId,+ } = provenance;++ await ports.registerArtboard?.({+ ...intent.artboard,+ agentId,+ cumulativeCost,+ cumulativeUsage,+ messageId,+ rootOperationId,+ threadId,+ toolCallId,+ toolIdentifier,+ topicId,+ });+};+const dispatchCanvasWorkIntent = async (intent: WorkRegistrationIntentFor<'canvas'>,ports: WorkRegistrationPorts,@@ -502,6 +535,9 @@ const dispatchSkillWorkIntent = async (* fails this exhaustive registry until its behavior is registered here.*/export const WORK_REGISTRATION_ADAPTERS = {+ artboard: {+ dispatch: dispatchArtboardWorkIntent,+ },canvas: {dispatch: dispatchCanvasWorkIntent,},diff --git a/packages/business-server/src/canvasPublish.ts b/packages/business-server/src/canvasPublish.tsindex d61f74cdb91..03e342a06ea 100644--- a/packages/business-server/src/canvasPublish.ts+++ b/packages/business-server/src/canvasPublish.ts@@ -18,6 +18,16 @@ export interface PublishCanvasSiteResult {url: string;}+export interface PublishArtboardSiteParams {+ artboardId: string;+ bundle: CanvasPublishBundle;+ db: LobeChatDatabase;+ deploymentId?: string;+ title: string;+ userId: string;+ workspaceId?: string;+}+export interface UnpublishCanvasSiteParams {db: LobeChatDatabase;deploymentId: string;@@ -41,3 +51,12 @@ export const publishCanvasSite = async (* public). Nothing is ever published here, so there is nothing to take down.*/export const unpublishCanvasSite = async (_params: UnpublishCanvasSiteParams): Promise<void> => {};++export const getArtboardViewerUrl = async (_major: number): Promise<string | undefined> =>+ undefined;++export const publishArtboardSite = async (+ _params: PublishArtboardSiteParams,+): Promise<PublishCanvasSiteResult> => {+ throw new Error('Artboard publishing is not available in this deployment');+};diff --git a/packages/const/src/apiKeyScope.ts b/packages/const/src/apiKeyScope.tsindex fbb4d42faa6..cef5d7bafeb 100644--- a/packages/const/src/apiKeyScope.ts+++ b/packages/const/src/apiKeyScope.ts@@ -224,6 +224,7 @@ export const TRPC_NAMESPACE_API_KEY_RULES: Record<string, TrpcNamespaceScopeRule// `auth.getScope` only reports which scope the presented credential runs// under, so any key — however narrow — can tell where its calls landauth: 'open',+ artboard: 'blocked',artifactShare: rw('chat:read', null),// decrypts stored bot/messenger credentials and calls external channel APIsbotMessage: 'blocked',diff --git a/packages/const/src/fetch.ts b/packages/const/src/fetch.tsindex 71452602635..6658580a59b 100644--- a/packages/const/src/fetch.ts+++ b/packages/const/src/fetch.ts@@ -4,3 +4,4 @@ export const REQUEST_TOPIC_ID_HEADER = 'x-topic-id';/** The agent operation a client-runtime model call belongs to, so its usage groups with the run. */export const REQUEST_OPERATION_ID_HEADER = 'x-operation-id';export const CLIENT_VERSION_HEADER = 'x-lobe-client-version';+export const WORK_TYPES_HEADER = 'x-lobe-work-types';diff --git a/packages/database/src/models/artboard/__tests__/artboard.test.ts b/packages/database/src/models/artboard/__tests__/artboard.test.tsnew file mode 100644index 00000000000..e4c53f05050--- /dev/null+++ b/packages/database/src/models/artboard/__tests__/artboard.test.ts@@ -0,0 +1,218 @@+// @vitest-environment node+import { eq, inArray } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../../core/getTestDB';+import {+ artboardPages,+ projects,+ tasks,+ users,+ workspaceMembers,+ workspaces,+} from '../../../schemas';+import type { LobeChatDatabase } from '../../../type';+import { ArtboardModel, ArtboardRevisionConflictError } from '../index';++const serverDB: LobeChatDatabase = await getTestDB();++const userId = 'artboard-model-user';+const otherUserId = 'artboard-model-other';+const workspaceId = 'artboard-model-ws';+const taskIds = ['task_art_1', 'task_art_2', 'task_art_ws'];++const personal = new ArtboardModel(serverDB, userId);+const inWorkspace = new ArtboardModel(serverDB, userId, workspaceId);++const seedTask = (id: string, seq: number, scope?: string) =>+ serverDB.insert(tasks).values({+ createdByUserId: userId,+ id,+ identifier: `T-${seq}`,+ instruction: 'design onboarding',+ seq,+ workspaceId: scope,+ });++const cleanup = async () => {+ await serverDB.delete(users).where(inArray(users.id, [userId, otherUserId]));+};++beforeEach(async () => {+ await cleanup();+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);+ await serverDB+ .insert(workspaces)+ .values({ id: workspaceId, name: 'WS', primaryOwnerId: userId, slug: 'artboard-model-ws' });+ await serverDB.insert(workspaceMembers).values([+ { userId, workspaceId },+ { userId: otherUserId, workspaceId },+ ]);+ await serverDB.insert(projects).values({ id: 'prj_art', name: 'Onboarding', userId });+ await seedTask('task_art_1', 1);+ await seedTask('task_art_2', 2);+ await seedTask('task_art_ws', 3, workspaceId);+});++afterEach(async () => {+ await serverDB.delete(tasks).where(inArray(tasks.id, taskIds));+ await serverDB.delete(workspaces).where(eq(workspaces.id, workspaceId));+ await cleanup();+});++const create = (model: ArtboardModel, taskId: string) =>+ model.create({ projectId: 'prj_art', taskId, title: '新用户首次进入项目' });++describe('ArtboardModel', () => {+ it('creates an artboard at revision 1 in the discuss phase with one page', async () => {+ const artboard = await create(personal, 'task_art_1');++ expect(artboard.id.startsWith('art_')).toBe(true);+ expect(artboard).toMatchObject({+ content: null,+ phase: 'discuss',+ revision: 1,+ taskId: 'task_art_1',+ userId,+ });+ const pages = await serverDB+ .select()+ .from(artboardPages)+ .where(eq(artboardPages.artboardId, artboard.id));+ expect(pages).toHaveLength(1);+ expect(pages[0]).toMatchObject({ sortOrder: 0, userId });+ });++ it('finds an artboard by id, by task, and lists a project', async () => {+ const artboard = await create(personal, 'task_art_1');+ await create(personal, 'task_art_2');++ expect((await personal.findById(artboard.id))?.id).toBe(artboard.id);+ expect((await personal.listByTaskId('task_art_1')).map((row) => row.id)).toEqual([artboard.id]);+ expect(await personal.listByProject('prj_art')).toHaveLength(2);+ });++ it('allows several artboards per task, and an artboard with no task', async () => {+ await create(personal, 'task_art_1');+ await create(personal, 'task_art_1');+ const loose = await personal.create({+ content: '# 背景\n新用户第一次进项目时什么都看不到。',+ description: '新用户首次进入项目的引导',+ title: '没有任务的画板',+ });++ expect(await personal.listByTaskId('task_art_1')).toHaveLength(2);+ expect(await personal.findById(loose.id)).toMatchObject({+ content: '# 背景\n新用户第一次进项目时什么都看不到。',+ taskId: null,+ });+ });++ it('scopes an artboard with no task by its workspace', async () => {+ const loose = await inWorkspace.create({ title: '工作区画板' });++ expect(+ await new ArtboardModel(serverDB, otherUserId, workspaceId).findById(loose.id),+ ).toMatchObject({ id: loose.id });+ expect(await personal.findById(loose.id)).toBeUndefined();+ });++ it('bumps the revision on update and rejects a stale revision', async () => {+ const artboard = await create(personal, 'task_art_1');++ const updated = await personal.update(artboard.id, { expectedRevision: 1, title: '改名' });+ expect(updated).toMatchObject({ revision: 2, title: '改名' });+ expect((await personal.getRevision(artboard.id))?.revision).toBe(2);++ await expect(+ personal.update(artboard.id, { expectedRevision: 1, title: '过期写入' }),+ ).rejects.toBeInstanceOf(ArtboardRevisionConflictError);+ });++ it('keeps personal and workspace artboards apart', async () => {+ const personalArtboard = await create(personal, 'task_art_1');+ const workspaceArtboard = await create(inWorkspace, 'task_art_ws');++ expect(workspaceArtboard.workspaceId).toBe(workspaceId);+ expect(await inWorkspace.findById(personalArtboard.id)).toBeUndefined();+ expect(await personal.findById(workspaceArtboard.id)).toBeUndefined();+ expect(+ await new ArtboardModel(serverDB, otherUserId).findById(personalArtboard.id),+ ).toBeUndefined();+ });++ it('keeps the artboard and unlinks it when the task is deleted', async () => {+ const artboard = await create(personal, 'task_art_1');+ await serverDB.delete(tasks).where(eq(tasks.id, 'task_art_1'));++ expect(await personal.findById(artboard.id)).toMatchObject({ taskId: null });+ expect(+ await serverDB.select().from(artboardPages).where(eq(artboardPages.artboardId, artboard.id)),+ ).toHaveLength(1);+ });++ it('denies another workspace member every private-task artboard read and write', async () => {+ const artboard = await create(inWorkspace, 'task_art_ws');+ const member = new ArtboardModel(serverDB, otherUserId, workspaceId);+ await serverDB+ .update(tasks)+ .set({ visibility: 'private' })+ .where(eq(tasks.id, artboard.taskId!));++ expect(await member.findById(artboard.id)).toBeUndefined();+ expect(await member.listByTaskId(artboard.taskId!)).toEqual([]);+ expect(await member.getRevision(artboard.id)).toBeUndefined();+ expect(await member.listByProject('prj_art')).toEqual([]);+ await expect(+ member.update(artboard.id, { expectedRevision: 1, title: 'Changed' }),+ ).rejects.toThrow();+ expect(await inWorkspace.findById(artboard.id)).toMatchObject({+ revision: 1,+ title: artboard.title,+ });+ });++ it('follows parent visibility changes and excludes trashed parents', async () => {+ const artboard = await create(inWorkspace, 'task_art_ws');+ const member = new ArtboardModel(serverDB, otherUserId, workspaceId);+ await serverDB+ .update(tasks)+ .set({ visibility: 'public' })+ .where(eq(tasks.id, artboard.taskId!));++ expect(await member.findById(artboard.id)).toMatchObject({ id: artboard.id });+ await member.update(artboard.id, { expectedRevision: 1, title: 'Shared edit' });+ await serverDB.update(tasks).set({ isDeleted: true }).where(eq(tasks.id, artboard.taskId!));++ expect(await inWorkspace.findById(artboard.id)).toBeUndefined();+ expect(await inWorkspace.listByProject('prj_art')).toEqual([]);+ await expect(+ inWorkspace.update(artboard.id, { expectedRevision: 2, title: 'Trash edit' }),+ ).rejects.toThrow();+ });++ describe('setTask and delete', () => {+ it('attaches a task without bumping the revision', async () => {+ const board = await personal.create({ title: 'Loose' });++ const attached = await personal.setTask(board.id, 'task_art_1');++ expect(attached).toMatchObject({ revision: 1, taskId: 'task_art_1' });+ });++ it('deletes the board with its pages, and only for someone who can reach it', async () => {+ const board = await personal.create({ title: 'Loose' });++ await new ArtboardModel(serverDB, otherUserId).delete(board.id);+ expect(await personal.findById(board.id)).toBeDefined();++ await personal.delete(board.id);+ expect(await personal.findById(board.id)).toBeUndefined();+ const pages = await serverDB+ .select()+ .from(artboardPages)+ .where(eq(artboardPages.artboardId, board.id));+ expect(pages).toEqual([]);+ });+ });+});diff --git a/packages/database/src/models/artboard/__tests__/comment.test.ts b/packages/database/src/models/artboard/__tests__/comment.test.tsnew file mode 100644index 00000000000..e8d78614c4e--- /dev/null+++ b/packages/database/src/models/artboard/__tests__/comment.test.ts@@ -0,0 +1,286 @@+// @vitest-environment node+import { eq, inArray } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../../core/getTestDB';+import { artboardComments, tasks, users, workspaceMembers, workspaces } from '../../../schemas';+import type { LobeChatDatabase } from '../../../type';+import { ArtboardCommentError, ArtboardCommentModel } from '../comment';+import { ArtboardModel } from '../index';+import { ArtboardStructureModel } from '../structure';++const serverDB: LobeChatDatabase = await getTestDB();++const userId = 'artboard-comment-user';+const otherUserId = 'artboard-comment-other';+const workspaceId = 'artboard-comment-ws';+const taskId = 'task_abc_ws';++const artboards = new ArtboardModel(serverDB, userId, workspaceId);+const structure = new ArtboardStructureModel(serverDB, userId, workspaceId);+const comments = new ArtboardCommentModel(serverDB, userId, workspaceId);+const member = new ArtboardCommentModel(serverDB, otherUserId, workspaceId);++const cleanup = async () => {+ await serverDB.delete(users).where(inArray(users.id, [userId, otherUserId]));+};++beforeEach(async () => {+ await cleanup();+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);+ await serverDB+ .insert(workspaces)+ .values({ id: workspaceId, name: 'WS', primaryOwnerId: userId, slug: workspaceId });+ await serverDB.insert(workspaceMembers).values([+ { userId, workspaceId },+ { userId: otherUserId, workspaceId },+ ]);+ await serverDB.insert(tasks).values({+ createdByUserId: userId,+ id: taskId,+ identifier: 'C-1',+ instruction: 'design onboarding',+ seq: 1,+ visibility: 'public',+ workspaceId,+ });+});++afterEach(async () => {+ await serverDB.delete(tasks).where(eq(tasks.id, taskId));+ await serverDB.delete(workspaces).where(eq(workspaces.id, workspaceId));+ await cleanup();+});++const seed = async () => {+ const artboard = await artboards.create({ taskId, title: '登录流程' });+ const [page] = (await structure.getStructure(artboard.id))!.pages;+ const group = await structure.createGroup(artboard.id, {+ kind: 'journey',+ pageId: page.id,+ rect: { h: 600, w: 1500, x: 0, y: 0 },+ title: '主流程',+ });+ const board = await structure.createBoard(artboard.id, {+ groupId: group.id,+ pageId: page.id,+ rect: { h: 400, w: 640, x: 48, y: 144 },+ title: '登录页',+ type: 'html',+ });+ return { artboard, board, group, page };+};++const expectCode = async (run: Promise<unknown>, code: string) => {+ await expect(run).rejects.toBeInstanceOf(ArtboardCommentError);+ await expect(run).rejects.toMatchObject({ code });+};++describe('ArtboardCommentModel', () => {+ it('stores where a comment was made on a board', async () => {+ const { artboard, board, page } = await seed();++ const comment = await comments.create(artboard.id, {+ anchor: { nodePath: 'body > main > button', offsetX: 0.5, offsetY: 0.25, type: 'node' },+ boardId: board.id,+ clientId: 'c1',+ content: '按钮太小',+ pageId: page.id,+ });++ expect(comment.id).toMatch(/^[\da-f-]{36}$/);+ expect(comment).toMatchObject({+ anchor: { nodePath: 'body > main > button', type: 'node' },+ authorAgentId: null,+ authorUserId: userId,+ boardId: board.id,+ deliveredAt: null,+ parentCommentId: null,+ resolvedAt: null,+ });+ });++ it('writes one row when the same create is retried', async () => {+ const { artboard, page } = await seed();+ const input = { clientId: 'retry', content: '这里留白太多', pageId: page.id };++ const first = await comments.create(artboard.id, input);+ const second = await comments.create(artboard.id, input);++ expect(second.id).toBe(first.id);+ expect(+ await serverDB+ .select()+ .from(artboardComments)+ .where(eq(artboardComments.artboardId, artboard.id)),+ ).toHaveLength(1);+ });++ it('threads replies under the root, including a reply to a reply', async () => {+ const { artboard, page } = await seed();+ const root = await comments.create(artboard.id, {+ clientId: 'root',+ content: '要不要第三方登录?',+ pageId: page.id,+ });++ const reply = await member.reply(root.id, { clientId: 'r1', content: '要,先接 Google' });+ const nested = await comments.reply(reply.id, { clientId: 'r2', content: '好' });++ expect(nested.parentCommentId).toBe(root.id);+ const [thread] = await comments.listThreads(artboard.id);+ expect(thread.root.id).toBe(root.id);+ expect(thread.replies.map((item) => item.content)).toEqual(['要,先接 Google', '好']);+ expect(thread.replies[0].authorUserId).toBe(otherUserId);+ });++ it('resolves and reopens a thread, and only a root can be resolved', async () => {+ const { artboard, page } = await seed();+ const root = await comments.create(artboard.id, {+ clientId: 'root',+ content: '文案待定',+ pageId: page.id,+ });+ const reply = await comments.reply(root.id, { clientId: 'r1', content: '已改' });++ const resolved = await comments.resolve(root.id);+ expect(resolved.resolvedAt).toBeInstanceOf(Date);+ expect(resolved.resolvedByUserId).toBe(userId);+ expect(await comments.listThreads(artboard.id, { unresolvedOnly: true })).toEqual([]);+ expect(await comments.listThreads(artboard.id)).toHaveLength(1);++ const reopened = await comments.reopen(root.id);+ expect(reopened).toMatchObject({ resolvedAt: null, resolvedByUserId: null });+ await expectCode(comments.resolve(reply.id), 'invalid');+ });++ it('keeps a comment when its board is deleted', async () => {+ const { artboard, board, page } = await seed();+ const comment = await comments.create(artboard.id, {+ boardId: board.id,+ clientId: 'c1',+ content: '这张不要了',+ pageId: page.id,+ });++ await structure.deleteBoard(board.id);++ const [thread] = await comments.listThreads(artboard.id);+ expect(thread.root).toMatchObject({ boardId: null, content: '这张不要了', id: comment.id });+ });++ it('hands the agent only unresolved threads with an undelivered message', async () => {+ const { artboard, page } = await seed();+ const add = (clientId: string) =>+ comments.create(artboard.id, { clientId, content: clientId, pageId: page.id });+ const seen = await add('seen');+ const answered = await add('answered');+ const fresh = await add('fresh');+ const done = await add('done');+ await comments.resolve(done.id);++ expect((await comments.listUndelivered(artboard.id)).map((t) => t.root.id)).toEqual([+ seen.id,+ answered.id,+ fresh.id,+ ]);++ await comments.markDelivered([seen.id, answered.id], new Date('2026-11-10T09:00:00Z'));+ await comments.reply(answered.id, { clientId: 'again', content: '还有一点' });++ expect((await comments.listUndelivered(artboard.id)).map((t) => t.root.id)).toEqual([+ answered.id,+ fresh.id,+ ]);+ });++ it('keeps the first delivery time and ignores comments the caller cannot reach', async () => {+ const { artboard, page } = await seed();+ const root = await comments.create(artboard.id, {+ clientId: 'root',+ content: '先看这个',+ pageId: page.id,+ });+ const first = new Date('2026-11-10T09:00:00Z');+ await comments.markDelivered([root.id], first);+ await comments.markDelivered([root.id], new Date('2026-11-10T10:00:00Z'));+ await serverDB.update(tasks).set({ visibility: 'private' }).where(eq(tasks.id, taskId));+ const fresh = await comments.create(artboard.id, {+ clientId: 'fresh',+ content: '新的',+ pageId: page.id,+ });++ await member.markDelivered([fresh.id], new Date());++ const [thread, other] = await comments.listThreads(artboard.id);+ expect(thread.root.deliveredAt).toEqual(first);+ expect(other.root.deliveredAt).toBeNull();+ });++ it('refuses an anchor that belongs to another artboard', async () => {+ const { board } = await seed();+ await serverDB.insert(tasks).values({+ createdByUserId: userId,+ id: 'task_abc_2',+ identifier: 'C-2',+ instruction: 'another',+ seq: 2,+ visibility: 'public',+ workspaceId,+ });+ const other = await artboards.create({ taskId: 'task_abc_2', title: '另一块' });++ await expectCode(+ comments.create(other.id, { boardId: board.id, clientId: 'x', content: '串门' }),+ 'not_found',+ );+ });++ it('keeps every row when a contributing member account is deleted', async () => {+ const { artboard, group, page } = await seed();+ const memberStructure = new ArtboardStructureModel(serverDB, otherUserId, workspaceId);+ const size = {+ pageId: page.id,+ rect: { h: 400, w: 640, x: 0, y: 0 },+ type: 'html' as const,+ };+ const memberGroup = await memberStructure.createGroup(artboard.id, {+ kind: 'references',+ pageId: page.id,+ rect: { h: 600, w: 800, x: 1600, y: 0 },+ title: '参考',+ });+ await structure.createBoard(artboard.id, { ...size, groupId: memberGroup.id, title: '竞品' });+ await memberStructure.createBoard(artboard.id, { ...size, groupId: group.id, title: '注册页' });+ await member.create(artboard.id, { clientId: 'm1', content: '成员的评论', pageId: page.id });++ await serverDB.delete(users).where(eq(users.id, otherUserId));++ const read = await structure.getStructure(artboard.id);+ expect(read?.groups).toHaveLength(2);+ expect(read?.boards.map((item) => item.userId)).toEqual([userId, userId, userId]);+ const [thread] = await comments.listThreads(artboard.id);+ expect(thread.root).toMatchObject({ authorUserId: null, content: '成员的评论', userId });+ });++ it('follows the parent task: a private task hides its comments from other members', async () => {+ const { artboard, page } = await seed();+ const root = await comments.create(artboard.id, {+ clientId: 'root',+ content: '私下说',+ pageId: page.id,+ });+ await serverDB.update(tasks).set({ visibility: 'private' }).where(eq(tasks.id, taskId));++ expect(await member.listThreads(artboard.id)).toEqual([]);+ expect(await member.listUndelivered(artboard.id)).toEqual([]);+ await expectCode(+ member.create(artboard.id, { clientId: 'm1', content: '偷看', pageId: page.id }),+ 'not_found',+ );+ await expectCode(member.reply(root.id, { clientId: 'm2', content: '插话' }), 'not_found');+ await expectCode(member.resolve(root.id), 'not_found');+ expect((await comments.listThreads(artboard.id))[0].replies).toEqual([]);+ });+});diff --git a/packages/database/src/models/artboard/__tests__/structure.test.ts b/packages/database/src/models/artboard/__tests__/structure.test.tsnew file mode 100644index 00000000000..dd75812b6c5--- /dev/null+++ b/packages/database/src/models/artboard/__tests__/structure.test.ts@@ -0,0 +1,486 @@+// @vitest-environment node+import { eq, inArray } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../../core/getTestDB';+import {+ acceptanceFlowNodes,+ acceptanceFlows,+ acceptances,+ artboardEdges,+ artboardGroups,+ artboardRounds,+ projects,+ tasks,+ users,+ workspaceMembers,+ workspaces,+} from '../../../schemas';+import type { LobeChatDatabase } from '../../../type';+import { ArtboardModel } from '../index';+import { ArtboardStructureError, ArtboardStructureModel } from '../structure';++const serverDB: LobeChatDatabase = await getTestDB();++const userId = 'artboard-structure-user';+const otherUserId = 'artboard-structure-other';+const workspaceId = 'artboard-structure-ws';+const projectId = 'prj_art_structure';+const taskIds = ['task_abs_1', 'task_abs_ws'];++const structure = new ArtboardStructureModel(serverDB, userId);++const seedTask = (id: string, seq: number, scope?: string) =>+ serverDB.insert(tasks).values({+ createdByUserId: userId,+ id,+ identifier: `S-${seq}`,+ instruction: 'design onboarding',+ seq,+ workspaceId: scope,+ });++const cleanup = async () => {+ await serverDB.delete(users).where(inArray(users.id, [userId, otherUserId]));+};++beforeEach(async () => {+ await cleanup();+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);+ await serverDB+ .insert(workspaces)+ .values({ id: workspaceId, name: 'WS', primaryOwnerId: userId, slug: workspaceId });+ await serverDB.insert(workspaceMembers).values([+ { userId, workspaceId },+ { userId: otherUserId, workspaceId },+ ]);+ await serverDB.insert(projects).values({ id: projectId, name: 'Onboarding', userId });+ await seedTask('task_abs_1', 1);+ await seedTask('task_abs_ws', 2, workspaceId);+});++afterEach(async () => {+ await serverDB.delete(tasks).where(inArray(tasks.id, taskIds));+ await serverDB.delete(workspaces).where(eq(workspaces.id, workspaceId));+ await cleanup();+});++const seedArtboard = async (model = structure, artboards = new ArtboardModel(serverDB, userId)) => {+ const artboard = await artboards.create({ projectId, taskId: 'task_abs_1', title: '登录流程' });+ const [page] = (await model.getStructure(artboard.id))!.pages;+ return { artboard, page };+};++const uuid = /^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/;++const board = (+ pageId: string,+ groupId: string | null,+ title: string,+ x = 0,+ roundId: string | null = null,+) => ({+ groupId,+ pageId,+ projectId,+ rect: { h: 400, w: 640, x, y: 0 },+ roundId,+ title,+ type: 'html' as const,+});++const seedOptions = async () => {+ const { artboard, page } = await seedArtboard();+ const round = await structure.createRound(artboard.id, {+ pageId: page.id,+ title: '登录方式用哪种',+ });+ const group = await structure.createGroup(artboard.id, {+ kind: 'options',+ pageId: page.id,+ rect: { h: 600, w: 1500, x: 0, y: 0 },+ title: '登录方式怎么摆',+ });+ const a = await structure.createBoard(artboard.id, board(page.id, group.id, '卡片', 0, round.id));+ const b = await structure.createBoard(+ artboard.id,+ board(page.id, group.id, '下拉', 720, round.id),+ );+ return { a, artboard, b, group, page, round };+};++const readRound = async (id: string) => {+ const [row] = await serverDB.select().from(artboardRounds).where(eq(artboardRounds.id, id));+ return row;+};++const expectCode = async (run: Promise<unknown>, code: string) => {+ await expect(run).rejects.toBeInstanceOf(ArtboardStructureError);+ await expect(run).rejects.toMatchObject({ code });+};++describe('ArtboardStructureModel', () => {+ it('reads back pages, rounds, groups, boards and edges of an artboard', async () => {+ const { a, artboard, b, group, page, round } = await seedOptions();+ const edge = await structure.createEdge(artboard.id, {+ condition: '已有账号',+ label: '点击登录',+ sourceBoardId: a.id,+ targetBoardId: b.id,+ });++ const read = await structure.getStructure(artboard.id);++ expect(read?.pages.map((p) => p.id)).toEqual([page.id]);+ expect(read?.rounds).toMatchObject([{ chosenBoardId: null, id: round.id, status: 'open' }]);+ expect(read?.groups).toMatchObject([{ id: group.id, kind: 'options' }]);+ expect(read?.boards.map((item) => item.title)).toEqual(['卡片', '下拉']);+ expect(read?.boards[0]).toMatchObject({ roundId: round.id, type: 'html' });+ expect(read?.edges).toMatchObject([+ { condition: '已有账号', id: edge.id, isDefault: false, label: '点击登录', sortOrder: 0 },+ ]);+ expect(a.id).toMatch(uuid);+ });++ it('reads rows written in one transaction back in the order they were written', async () => {+ const { artboard, page } = await seedArtboard();++ await serverDB.transaction(async (tx) => {+ const model = structure.withTransaction(tx);+ for (const title of ['one', 'two', 'three', 'four', 'five', 'six'])+ await model.createBoard(artboard.id, board(page.id, null, title));+ });++ const { boards } = (await structure.getStructure(artboard.id))!;+ expect(boards.map((b) => b.title)).toEqual(['one', 'two', 'three', 'four', 'five', 'six']);+ });++ it('updates a board in place', async () => {+ const { a } = await seedOptions();++ const moved = await structure.updateBoard(a.id, {+ expected: '看到登录表单',+ rect: { h: 400, w: 640, x: 80, y: 0 },+ });++ expect(moved).toMatchObject({+ expected: '看到登录表单',+ id: a.id,+ rect: { x: 80 },+ title: '卡片',+ });+ });++ it('places a board outside any group', async () => {+ const { artboard, page } = await seedArtboard();++ const loose = await structure.createBoard(artboard.id, board(page.id, null, '散落的参考图'));++ expect(loose).toMatchObject({ groupId: null, roundId: null });+ });++ it('refuses a board on a different page from its group or round', async () => {+ const { artboard, group, round } = await seedOptions();+ const other = await structure.createPage(artboard.id, { name: '第二页', sortOrder: 1 });++ await expectCode(+ structure.createBoard(artboard.id, board(other.id, group.id, '跨页')),+ 'invalid',+ );+ await expectCode(+ structure.createBoard(artboard.id, board(other.id, null, '跨页', 0, round.id)),+ 'invalid',+ );+ });++ it('removes a deleted board from its edges and from the round that pointed at it', async () => {+ const { a, artboard, b, round } = await seedOptions();+ await structure.createEdge(artboard.id, { sourceBoardId: a.id, targetBoardId: b.id });+ await structure.updateRound(round.id, { recommendedBoardId: a.id });+ await structure.chooseBoard(round.id, a.id);++ await structure.deleteBoard(a.id);++ expect(+ await serverDB.select().from(artboardEdges).where(eq(artboardEdges.artboardId, artboard.id)),+ ).toEqual([]);+ expect(await readRound(round.id)).toMatchObject({+ chosenBoardId: null,+ recommendedBoardId: null,+ });+ });++ it('refuses to delete a group that still holds boards', async () => {+ const { a, b, group } = await seedOptions();++ await expectCode(structure.deleteGroup(group.id), 'not_empty');++ await structure.deleteBoard(a.id);+ await structure.deleteBoard(b.id);+ await structure.deleteGroup(group.id);+ expect(+ await serverDB.select().from(artboardGroups).where(eq(artboardGroups.id, group.id)),+ ).toEqual([]);+ });++ it('refuses to delete a page with content, and the last page', async () => {+ const { artboard, page } = await seedOptions();+ const empty = await structure.createPage(artboard.id, { name: '验收', sortOrder: 1 });++ await expectCode(structure.deletePage(page.id), 'not_empty');++ await structure.deletePage(empty.id);+ const { artboard: single, page: only } = await seedArtboard();+ await expectCode(structure.deletePage(only.id), 'last_page');+ expect((await structure.getStructure(single.id))?.pages).toHaveLength(1);+ });++ it('refuses a board whose group belongs to another artboard', async () => {+ const { group } = await seedOptions();+ const other = await new ArtboardModel(serverDB, userId, workspaceId).create({+ taskId: 'task_abs_ws',+ title: '另一块画板',+ });+ const inWorkspace = new ArtboardStructureModel(serverDB, userId, workspaceId);+ const [otherPage] = (await inWorkspace.getStructure(other.id))!.pages;++ await expectCode(+ inWorkspace.createBoard(other.id, board(otherPage.id, group.id, '串门')),+ 'not_found',+ );+ });++ it('only recommends a board that is an option of the round', async () => {+ const { a, artboard, page, round } = await seedOptions();+ const elsewhere = await structure.createBoard(artboard.id, board(page.id, null, '无关'));++ await expectCode(+ structure.updateRound(round.id, { recommendedBoardId: elsewhere.id }),+ 'not_found',+ );+ expect(await structure.updateRound(round.id, { recommendedBoardId: a.id })).toMatchObject({+ recommendedBoardId: a.id,+ });+ });++ it('keeps a choice as a draft that can change until the round is submitted', async () => {+ const { a, b, round } = await seedOptions();++ await structure.chooseBoard(round.id, a.id);+ const changed = await structure.chooseBoard(round.id, b.id);+ expect(changed).toMatchObject({ chosenBoardId: b.id, selectedBy: userId });+ expect(changed.selectedAt).toBeInstanceOf(Date);++ await structure.submitRound(round.id);+ await expectCode(structure.chooseBoard(round.id, a.id), 'round_submitted');+ });++ it('refuses a choice that is not an option of the round', async () => {+ const { artboard, page, round } = await seedOptions();+ const elsewhere = await structure.createBoard(artboard.id, board(page.id, null, '无关'));++ await expectCode(structure.chooseBoard(round.id, elsewhere.id), 'not_found');+ });++ it('applies the recommendation when a round is submitted unpicked', async () => {+ const { a, round } = await seedOptions();+ await structure.updateRound(round.id, { recommendedBoardId: a.id });++ const [submitted] = await structure.submitRound(round.id);++ expect(submitted).toMatchObject({+ chosenBoardId: a.id,+ selectedBy: userId,+ status: 'submitted',+ });+ });++ it('refuses to submit a round with neither a pick nor a recommendation', async () => {+ const { round } = await seedOptions();++ await expectCode(structure.submitRound(round.id), 'missing_choice');++ expect((await readRound(round.id)).status).toBe('open');+ });++ it('refuses to submit a round twice', async () => {+ const { a, round } = await seedOptions();+ await structure.chooseBoard(round.id, a.id);+ await structure.submitRound(round.id);++ await expectCode(structure.submitRound(round.id), 'round_submitted');+ });++ it('submits every round of a batch together', async () => {+ const { a, artboard, page, round } = await seedOptions();+ await structure.updateRound(round.id, { metadata: { batchId: 'b1' } });+ const second = await structure.createRound(artboard.id, {+ metadata: { batchId: 'b1' },+ pageId: page.id,+ title: '首页布局',+ });+ const solo = await structure.createRound(artboard.id, { pageId: page.id, title: '单独一题' });+ const c = await structure.createBoard(artboard.id, board(page.id, null, '双栏', 0, second.id));+ await structure.chooseBoard(round.id, a.id);++ await expectCode(structure.submitRound(round.id), 'missing_choice');+ expect((await readRound(round.id)).status).toBe('open');++ await structure.chooseBoard(second.id, c.id);+ const submitted = await structure.submitRound(second.id);++ expect(submitted.map((item) => item.id).sort()).toEqual([round.id, second.id].sort());+ expect((await readRound(round.id)).status).toBe('submitted');+ expect((await readRound(solo.id)).status).toBe('open');+ });++ it('submits every open round of the artboard at once, unpicked ones by recommendation', async () => {+ const { a, artboard, page, round } = await seedOptions();+ const second = await structure.createRound(artboard.id, { pageId: page.id, title: '首页布局' });+ const c = await structure.createBoard(artboard.id, board(page.id, null, '双栏', 0, second.id));+ await structure.chooseBoard(round.id, a.id);++ await expectCode(structure.submitOpenRounds(artboard.id), 'missing_choice');+ expect((await readRound(round.id)).status).toBe('open');++ await structure.updateRound(second.id, { recommendedBoardId: c.id });+ const submitted = await structure.submitOpenRounds(artboard.id);++ expect(submitted.map((item) => item.id).sort()).toEqual([round.id, second.id].sort());+ expect(await readRound(second.id)).toMatchObject({ chosenBoardId: c.id, status: 'submitted' });+ expect(await structure.submitOpenRounds(artboard.id)).toEqual([]);+ });++ it('stores a decision board and its conditional branches', async () => {+ const { artboard, page } = await seedArtboard();+ const entry = await structure.createBoard(artboard.id, board(page.id, null, '商品页'));+ const decision = await structure.createBoard(artboard.id, {+ ...board(page.id, null, '已登录?'),+ type: 'decision',+ });+ const checkout = await structure.createBoard(artboard.id, board(page.id, null, '结算'));+ const login = await structure.createBoard(artboard.id, board(page.id, null, '登录'));++ await structure.createEdge(artboard.id, {+ label: '点击购买',+ sourceBoardId: entry.id,+ targetBoardId: decision.id,+ });+ await structure.createEdge(artboard.id, {+ condition: '已登录',+ sourceBoardId: decision.id,+ targetBoardId: checkout.id,+ });+ await structure.createEdge(artboard.id, {+ isDefault: true,+ sortOrder: 1,+ sourceBoardId: decision.id,+ targetBoardId: login.id,+ });++ await expect(+ structure.createEdge(artboard.id, {+ isDefault: true,+ sourceBoardId: decision.id,+ targetBoardId: entry.id,+ }),+ ).rejects.toThrow();+ await expect(+ structure.createBoard(artboard.id, {+ ...board(page.id, null, '带来源的判断'),+ sourcePath: 'index.html',+ type: 'decision',+ }),+ ).rejects.toThrow();+ const read = await structure.getStructure(artboard.id);+ expect(read?.edges.filter((edge) => edge.sourceBoardId === decision.id)).toHaveLength(2);+ });++ it('lists rounds of a project that have no effective choice yet', async () => {+ const { a, round } = await seedOptions();++ expect((await structure.listUndecidedRoundsByProject(projectId)).map((r) => r.id)).toEqual([+ round.id,+ ]);++ await structure.chooseBoard(round.id, a.id);+ expect(await structure.listUndecidedRoundsByProject(projectId)).toHaveLength(1);++ await structure.submitRound(round.id);+ expect(await structure.listUndecidedRoundsByProject(projectId)).toEqual([]);+ });++ it('finds the board behind an acceptance item', async () => {+ const { a } = await seedOptions();+ const [acceptance] = await serverDB+ .insert(acceptances)+ .values({ subjectId: 'task_abs_1', subjectType: 'task', userId })+ .returning();+ const [flow] = await serverDB+ .insert(acceptanceFlows)+ .values({ acceptanceId: acceptance.id, title: '主流程' })+ .returning();+ const [node] = await serverDB+ .insert(acceptanceFlowNodes)+ .values({ flowId: flow.id, subFlowId: flow.id })+ .returning();++ await structure.updateBoard(a.id, { acceptanceFlowNodeId: node.id });+ expect((await structure.findBoardByAcceptanceNode(node.id))?.id).toBe(a.id);+ });++ it('keeps the acceptance link when the flow is republished with the same node id', async () => {+ const { a } = await seedOptions();+ const [acceptance] = await serverDB+ .insert(acceptances)+ .values({ subjectId: 'task_abs_1', subjectType: 'task', userId })+ .returning();+ const [flow] = await serverDB+ .insert(acceptanceFlows)+ .values({ acceptanceId: acceptance.id, title: '主流程' })+ .returning();+ const [node] = await serverDB+ .insert(acceptanceFlowNodes)+ .values({ flowId: flow.id, subFlowId: flow.id })+ .returning();+ await structure.updateBoard(a.id, { acceptanceFlowNodeId: node.id });++ await serverDB.transaction(async (tx) => {+ await tx.delete(acceptanceFlowNodes).where(eq(acceptanceFlowNodes.flowId, flow.id));+ await tx+ .insert(acceptanceFlowNodes)+ .values({ flowId: flow.id, id: node.id, subFlowId: flow.id });+ });++ expect((await structure.findBoardByAcceptanceNode(node.id))?.id).toBe(a.id);+ });++ it('hides a private task from another member across every read and write', async () => {+ const owner = new ArtboardStructureModel(serverDB, userId, workspaceId);+ const artboard = await new ArtboardModel(serverDB, userId, workspaceId).create({+ projectId,+ taskId: 'task_abs_ws',+ title: '私有画板',+ });+ const [page] = (await owner.getStructure(artboard.id))!.pages;+ const group = await owner.createGroup(artboard.id, {+ kind: 'journey',+ pageId: page.id,+ rect: { h: 600, w: 1500, x: 0, y: 0 },+ title: '主流程',+ });+ const item = await owner.createBoard(artboard.id, board(page.id, group.id, '首页'));+ await serverDB.update(tasks).set({ visibility: 'private' }).where(eq(tasks.id, 'task_abs_ws'));+ const member = new ArtboardStructureModel(serverDB, otherUserId, workspaceId);++ expect(await member.getStructure(artboard.id)).toBeUndefined();+ expect(await member.listBoardsByProject(projectId)).toEqual([]);+ await expectCode(member.updateBoard(item.id, { title: '改掉' }), 'not_found');+ await expectCode(member.deleteBoard(item.id), 'not_found');+ await expectCode(+ member.createBoard(artboard.id, board(page.id, group.id, '塞一张')),+ 'not_found',+ );+ expect((await owner.listBoardsByProject(projectId)).map((b) => b.title)).toEqual(['首页']);+ });+});diff --git a/packages/database/src/models/artboard/comment.ts b/packages/database/src/models/artboard/comment.tsnew file mode 100644index 00000000000..3d8d366d8f8--- /dev/null+++ b/packages/database/src/models/artboard/comment.ts@@ -0,0 +1,231 @@+import { and, asc, count, eq, inArray, isNull } from 'drizzle-orm';++import {+ artboardBoards,+ artboardComments,+ artboardGroups,+ artboardPages,+ artboards,+} from '../../schemas/artboard';+import type { Transaction } from '../../type';+import { accessibleArtboardIds, type ArtboardDatabase } from './index';+import type { ArtboardCommentRow, NewArtboardCommentRow } from './types';++export type ArtboardCommentErrorCode = 'invalid' | 'not_found';++export class ArtboardCommentError extends Error {+ constructor(+ public code: ArtboardCommentErrorCode,+ message: string,+ ) {+ super(message);+ }+}++const fail = (code: ArtboardCommentErrorCode, message: string): never => {+ throw new ArtboardCommentError(code, message);+};++export type CreateArtboardCommentParams = Pick<+ NewArtboardCommentRow,+ | 'anchor'+ | 'authorAgentId'+ | 'boardId'+ | 'clientId'+ | 'content'+ | 'groupId'+ | 'metadata'+ | 'pageId'+>;++export type ReplyArtboardCommentParams = Pick<+ NewArtboardCommentRow,+ 'authorAgentId' | 'clientId' | 'content' | 'metadata'+>;++export interface ArtboardCommentThread {+ replies: ArtboardCommentRow[];+ root: ArtboardCommentRow;+}++type AnchorTable = typeof artboardBoards | typeof artboardGroups | typeof artboardPages;++export class ArtboardCommentModel {+ constructor(+ private db: ArtboardDatabase,+ private userId: string,+ private workspaceId?: string,+ ) {}++ withTransaction = (tx: Transaction) =>+ new ArtboardCommentModel(tx, this.userId, this.workspaceId);++ private reachable = () =>+ inArray(+ artboardComments.artboardId,+ accessibleArtboardIds(this.db, { userId: this.userId, workspaceId: this.workspaceId }),+ );++ private findArtboard = async (artboardId: string) => {+ const [row] = await this.db+ .select({+ id: artboards.id,+ userId: artboards.userId,+ workspaceId: artboards.workspaceId,+ })+ .from(artboards)+ .where(+ and(+ eq(artboards.id, artboardId),+ inArray(+ artboards.id,+ accessibleArtboardIds(this.db, { userId: this.userId, workspaceId: this.workspaceId }),+ ),+ ),+ )+ .limit(1);+ return row;+ };++ private assertAnchor = async (table: AnchorTable, artboardId: string, id?: string | null) => {+ if (!id) return;+ const [row] = await this.db+ .select({ total: count() })+ .from(table)+ .where(and(eq(table.artboardId, artboardId), eq(table.id, id)));+ if (row.total !== 1) fail('not_found', 'The comment anchor is not on this artboard');+ };++ private findReachable = async (id: string) => {+ const [row] = await this.db+ .select()+ .from(artboardComments)+ .where(and(eq(artboardComments.id, id), this.reachable()))+ .limit(1);+ return row ?? fail('not_found', `No comment ${id}`);+ };++ private insert = async (values: NewArtboardCommentRow): Promise<ArtboardCommentRow> => {+ const [created] = await this.db+ .insert(artboardComments)+ .values(values)+ .onConflictDoNothing({+ target: [+ artboardComments.artboardId,+ artboardComments.authorUserId,+ artboardComments.clientId,+ ],+ })+ .returning();+ if (created) return created;++ const [existing] = await this.db+ .select()+ .from(artboardComments)+ .where(+ and(+ eq(artboardComments.artboardId, values.artboardId),+ eq(artboardComments.authorUserId, this.userId),+ eq(artboardComments.clientId, values.clientId),+ ),+ )+ .limit(1);+ return existing;+ };++ create = async (+ artboardId: string,+ params: CreateArtboardCommentParams,+ ): Promise<ArtboardCommentRow> => {+ const artboard = await this.findArtboard(artboardId);+ if (!artboard) return fail('not_found', `No artboard ${artboardId}`);+ await this.assertAnchor(artboardPages, artboardId, params.pageId);+ await this.assertAnchor(artboardGroups, artboardId, params.groupId);+ await this.assertAnchor(artboardBoards, artboardId, params.boardId);++ return this.insert({+ ...params,+ artboardId,+ authorUserId: this.userId,+ userId: artboard.userId,+ workspaceId: artboard.workspaceId,+ });+ };++ reply = async (+ commentId: string,+ params: ReplyArtboardCommentParams,+ ): Promise<ArtboardCommentRow> => {+ const target = await this.findReachable(commentId);+ return this.insert({+ ...params,+ artboardId: target.artboardId,+ authorUserId: this.userId,+ pageId: target.pageId,+ parentCommentId: target.parentCommentId ?? target.id,+ userId: target.userId,+ workspaceId: target.workspaceId,+ });+ };++ private setResolved = async (rootId: string, resolved: boolean) => {+ const target = await this.findReachable(rootId);+ if (target.parentCommentId) fail('invalid', 'Only a thread root can be resolved');+ const [row] = await this.db+ .update(artboardComments)+ .set({+ resolvedAt: resolved ? new Date() : null,+ resolvedByUserId: resolved ? this.userId : null,+ updatedAt: new Date(),+ })+ .where(and(eq(artboardComments.id, rootId), isNull(artboardComments.parentCommentId)))+ .returning();+ return row;+ };++ resolve = (rootId: string) => this.setResolved(rootId, true);++ reopen = (rootId: string) => this.setResolved(rootId, false);++ listThreads = async (+ artboardId: string,+ options: { unresolvedOnly?: boolean } = {},+ ): Promise<ArtboardCommentThread[]> => {+ const rows = await this.db+ .select()+ .from(artboardComments)+ .where(and(eq(artboardComments.artboardId, artboardId), this.reachable()))+ .orderBy(asc(artboardComments.createdAt), asc(artboardComments.id));++ const threads = new Map<string, ArtboardCommentThread>();+ for (const row of rows) {+ if (!row.parentCommentId) threads.set(row.id, { replies: [], root: row });+ }+ for (const row of rows) {+ if (row.parentCommentId) threads.get(row.parentCommentId)?.replies.push(row);+ }+ const all = [...threads.values()];+ return options.unresolvedOnly ? all.filter((thread) => !thread.root.resolvedAt) : all;+ };++ listUndelivered = async (artboardId: string): Promise<ArtboardCommentThread[]> => {+ const open = await this.listThreads(artboardId, { unresolvedOnly: true });+ return open.filter((thread) =>+ [thread.root, ...thread.replies].some((message) => !message.deliveredAt),+ );+ };++ markDelivered = async (commentIds: string[], at: Date): Promise<void> => {+ if (commentIds.length === 0) return;+ await this.db+ .update(artboardComments)+ .set({ deliveredAt: at })+ .where(+ and(+ inArray(artboardComments.id, commentIds),+ isNull(artboardComments.deliveredAt),+ this.reachable(),+ ),+ );+ };+}diff --git a/packages/database/src/models/artboard/index.ts b/packages/database/src/models/artboard/index.tsnew file mode 100644index 00000000000..a35df2b2f01--- /dev/null+++ b/packages/database/src/models/artboard/index.ts@@ -0,0 +1,172 @@+import { ARTBOARD_DEFAULT_PAGE_NAME, type ArtboardPhase } from '@lobechat/types';+import { and, desc, eq, exists, isNull, or, sql } from 'drizzle-orm';++import { artboardPages, artboards } from '../../schemas/artboard';+import { tasks } from '../../schemas/task';+import type { LobeChatDatabase, Transaction } from '../../type';+import { buildWorkspaceWhere } from '../../utils/workspace';+import type { ArtboardRow } from './types';++export type * from './types';++export type ArtboardDatabase = LobeChatDatabase | Transaction;++export interface ArtboardScope {+ userId: string;+ workspaceId?: string;+}++export class ArtboardRevisionConflictError extends Error {+ constructor() {+ super('Artboard changed; read it again before writing');+ }+}++export const artboardAccessWhere = (db: ArtboardDatabase, scope: ArtboardScope) =>+ and(+ buildWorkspaceWhere(scope, artboards),+ or(+ isNull(artboards.taskId),+ exists(+ db+ .select({ id: tasks.id })+ .from(tasks)+ .where(+ and(+ eq(tasks.id, artboards.taskId),+ buildWorkspaceWhere(scope, {+ isDeleted: tasks.isDeleted,+ userId: tasks.createdByUserId,+ visibility: tasks.visibility,+ workspaceId: tasks.workspaceId,+ }),+ ),+ ),+ ),+ ),+ );++export const accessibleArtboardIds = (db: ArtboardDatabase, scope: ArtboardScope) =>+ db.select({ id: artboards.id }).from(artboards).where(artboardAccessWhere(db, scope));++export interface CreateArtboardParams {+ content?: string | null;+ description?: string | null;+ projectId?: string | null;+ taskId?: string | null;+ title: string;+ topicId?: string | null;+}++export interface UpdateArtboardParams {+ acceptanceId?: string | null;+ content?: string | null;+ description?: string | null;+ expectedRevision: number;+ phase?: ArtboardPhase;+ title?: string;+}++export class ArtboardModel {+ constructor(+ private db: ArtboardDatabase,+ private userId: string,+ private workspaceId?: string,+ ) {}++ withTransaction = (tx: Transaction) => new ArtboardModel(tx, this.userId, this.workspaceId);++ private get owner() {+ return { userId: this.userId, workspaceId: this.workspaceId ?? null };+ }++ private scope = () =>+ artboardAccessWhere(this.db, { userId: this.userId, workspaceId: this.workspaceId });++ create = (params: CreateArtboardParams): Promise<ArtboardRow> =>+ this.db.transaction(async (tx) => {+ const [row] = await tx+ .insert(artboards)+ .values({+ ...this.owner,+ content: params.content ?? null,+ description: params.description ?? null,+ projectId: params.projectId ?? null,+ taskId: params.taskId ?? null,+ title: params.title,+ topicId: params.topicId ?? null,+ })+ .returning();+ await tx+ .insert(artboardPages)+ .values({ ...this.owner, artboardId: row.id, name: ARTBOARD_DEFAULT_PAGE_NAME });+ return row;+ });++ findById = async (id: string): Promise<ArtboardRow | undefined> => {+ const [row] = await this.db+ .select()+ .from(artboards)+ .where(and(eq(artboards.id, id), this.scope()))+ .limit(1);+ return row;+ };++ listByTaskId = (taskId: string): Promise<ArtboardRow[]> =>+ this.db+ .select()+ .from(artboards)+ .where(and(eq(artboards.taskId, taskId), this.scope()))+ .orderBy(desc(artboards.updatedAt));++ listByProject = (projectId: string): Promise<ArtboardRow[]> =>+ this.db+ .select()+ .from(artboards)+ .where(and(eq(artboards.projectId, projectId), this.scope()))+ .orderBy(desc(artboards.updatedAt));++ setTask = async (id: string, taskId: string): Promise<ArtboardRow | undefined> => {+ const [row] = await this.db+ .update(artboards)+ .set({ taskId, updatedAt: new Date() })+ .where(and(eq(artboards.id, id), this.scope()))+ .returning();+ return row;+ };++ delete = async (id: string): Promise<void> => {+ await this.db.delete(artboards).where(and(eq(artboards.id, id), this.scope()));+ };++ /** The structure revision and the row's updatedAt, which file-only writes also move. */+ getRevision = async (id: string): Promise<{ revision: number; updatedAt: Date } | undefined> => {+ const [row] = await this.db+ .select({ revision: artboards.revision, updatedAt: artboards.updatedAt })+ .from(artboards)+ .where(and(eq(artboards.id, id), this.scope()))+ .limit(1);+ return row;+ };++ /** Move updatedAt without a revision bump: the files changed, the structure did not. */+ touch = async (id: string): Promise<ArtboardRow | undefined> => {+ const [row] = await this.db+ .update(artboards)+ .set({ updatedAt: new Date() })+ .where(and(eq(artboards.id, id), this.scope()))+ .returning();+ return row;+ };++ update = async (id: string, params: UpdateArtboardParams): Promise<ArtboardRow> => {+ const { expectedRevision, ...fields } = params;+ const [row] = await this.db+ .update(artboards)+ .set({ ...fields, revision: sql`${artboards.revision} + 1`, updatedAt: new Date() })+ .where(and(eq(artboards.id, id), eq(artboards.revision, expectedRevision), this.scope()))+ .returning();+ if (!row) throw new ArtboardRevisionConflictError();+ return row;+ };+}diff --git a/packages/database/src/models/artboard/structure.ts b/packages/database/src/models/artboard/structure.tsnew file mode 100644index 00000000000..02d0912a9c3--- /dev/null+++ b/packages/database/src/models/artboard/structure.ts@@ -0,0 +1,496 @@+import { and, asc, count, eq, inArray, isNull, ne, or, type SQL, sql } from 'drizzle-orm';++import {+ artboardBoards,+ artboardComments,+ artboardEdges,+ artboardGroups,+ artboardPages,+ artboardRounds,+ artboards,+} from '../../schemas/artboard';+import type { Transaction } from '../../type';+import { accessibleArtboardIds, type ArtboardDatabase } from './index';+import { fail } from './structureError';+import type {+ ArtboardBoardRow,+ ArtboardEdgeRow,+ ArtboardGroupRow,+ ArtboardPageRow,+ ArtboardRoundRow,+ NewArtboardBoardRow,+ NewArtboardEdgeRow,+ NewArtboardGroupRow,+ NewArtboardPageRow,+ NewArtboardRoundRow,+} from './types';++export { ArtboardStructureError, type ArtboardStructureErrorCode } from './structureError';++// now() is frozen for a whole transaction, so a batch of rows would tie on created_at and read+// back in random order.+const writtenAt = sql`clock_timestamp()`;++type Scoped = 'artboardId' | 'createdAt' | 'id' | 'updatedAt' | 'userId' | 'workspaceId';++export type CreatePageParams = Omit<NewArtboardPageRow, Scoped>;+export type CreateRoundParams = Pick<NewArtboardRoundRow, 'metadata' | 'pageId' | 'title'>;+export type UpdateRoundParams = Partial<+ Pick<NewArtboardRoundRow, 'metadata' | 'recommendedBoardId' | 'title'>+>;+export type CreateGroupParams = Omit<NewArtboardGroupRow, Scoped>;+export type CreateBoardParams = Omit<NewArtboardBoardRow, Scoped>;+export type CreateEdgeParams = Omit<NewArtboardEdgeRow, Scoped>;++export interface ArtboardStructure {+ boards: ArtboardBoardRow[];+ edges: ArtboardEdgeRow[];+ groups: ArtboardGroupRow[];+ pages: ArtboardPageRow[];+ rounds: ArtboardRoundRow[];+}++type ChildTable =+ | typeof artboardBoards+ | typeof artboardEdges+ | typeof artboardGroups+ | typeof artboardPages+ | typeof artboardRounds;++export class ArtboardStructureModel {+ constructor(+ private db: ArtboardDatabase,+ private userId: string,+ private workspaceId?: string,+ ) {}++ withTransaction = (tx: Transaction) =>+ new ArtboardStructureModel(tx, this.userId, this.workspaceId);++ private accessible = () =>+ accessibleArtboardIds(this.db, { userId: this.userId, workspaceId: this.workspaceId });++ private reachable = (table: ChildTable) => inArray(table.artboardId, this.accessible());++ private ownerOf = async (artboardId: string) => {+ const [row] = await this.db+ .select({ userId: artboards.userId, workspaceId: artboards.workspaceId })+ .from(artboards)+ .where(and(eq(artboards.id, artboardId), inArray(artboards.id, this.accessible())))+ .limit(1);+ return row ?? fail('not_found', `No artboard ${artboardId}`);+ };++ private assertWithin = async (+ table: ChildTable,+ artboardId: string,+ ids: (string | null | undefined)[],+ ) => {+ const wanted = [...new Set(ids.filter((id): id is string => !!id))];+ if (wanted.length === 0) return;+ const [row] = await this.db+ .select({ total: count() })+ .from(table)+ .where(and(eq(table.artboardId, artboardId), inArray(table.id, wanted)));+ if (row.total !== wanted.length) fail('not_found', 'A referenced item is not on this artboard');+ };++ private assertBoardPlacement = async (+ artboardId: string,+ pageId: string | undefined,+ refs: { groupId?: string | null; roundId?: string | null },+ ) => {+ await this.assertWithin(artboardPages, artboardId, [pageId]);+ await this.assertWithin(artboardGroups, artboardId, [refs.groupId]);+ await this.assertWithin(artboardRounds, artboardId, [refs.roundId]);+ if (!pageId) return;+ for (const [table, id] of [+ [artboardGroups, refs.groupId],+ [artboardRounds, refs.roundId],+ ] as const) {+ if (!id) continue;+ const [row] = await this.db+ .select({ pageId: table.pageId })+ .from(table)+ .where(eq(table.id, id))+ .limit(1);+ if (row.pageId !== pageId)+ fail('invalid', 'A board must be on the page of its group and round');+ }+ };++ private holds = async (table: ChildTable, where: ReturnType<typeof eq>) => {+ const [row] = await this.db.select({ id: table.id }).from(table).where(where).limit(1);+ return !!row;+ };++ getStructure = async (artboardId: string): Promise<ArtboardStructure | undefined> => {+ const of = <T extends ChildTable>(table: T) =>+ and(eq(table.artboardId, artboardId), this.reachable(table));++ const pages = await this.db+ .select()+ .from(artboardPages)+ .where(of(artboardPages))+ .orderBy(asc(artboardPages.sortOrder), asc(artboardPages.createdAt));+ if (pages.length === 0) return undefined;++ const [rounds, groups, boards, edges] = await Promise.all([+ this.db+ .select()+ .from(artboardRounds)+ .where(of(artboardRounds))+ .orderBy(asc(artboardRounds.createdAt)),+ this.db+ .select()+ .from(artboardGroups)+ .where(of(artboardGroups))+ .orderBy(asc(artboardGroups.createdAt)),+ this.db+ .select()+ .from(artboardBoards)+ .where(of(artboardBoards))+ .orderBy(asc(artboardBoards.createdAt), asc(artboardBoards.id)),+ this.db+ .select()+ .from(artboardEdges)+ .where(of(artboardEdges))+ .orderBy(asc(artboardEdges.createdAt)),+ ]);+ return { boards, edges, groups, pages, rounds };+ };++ createPage = async (artboardId: string, params: CreatePageParams) => {+ const owner = await this.ownerOf(artboardId);+ const [row] = await this.db+ .insert(artboardPages)+ .values({ ...params, ...owner, artboardId, createdAt: writtenAt })+ .returning();+ return row;+ };++ updatePage = async (id: string, patch: Partial<CreatePageParams>) => {+ const [row] = await this.db+ .update(artboardPages)+ .set({ ...patch, updatedAt: new Date() })+ .where(and(eq(artboardPages.id, id), this.reachable(artboardPages)))+ .returning();+ return row ?? fail('not_found', `No page ${id}`);+ };++ deletePage = async (id: string) => {+ const [page] = await this.db+ .select()+ .from(artboardPages)+ .where(and(eq(artboardPages.id, id), this.reachable(artboardPages)))+ .limit(1);+ if (!page) return fail('not_found', `No page ${id}`);++ const occupied =+ (await this.holds(artboardBoards, eq(artboardBoards.pageId, id))) ||+ (await this.holds(artboardGroups, eq(artboardGroups.pageId, id))) ||+ (await this.holds(artboardRounds, eq(artboardRounds.pageId, id)));+ if (occupied) fail('not_empty', `Page ${id} still has content`);++ const [{ total }] = await this.db+ .select({ total: count() })+ .from(artboardPages)+ .where(eq(artboardPages.artboardId, page.artboardId));+ if (total <= 1) fail('last_page', 'An artboard keeps at least one page');++ await this.db.transaction(async (tx) => {+ await tx.delete(artboardComments).where(eq(artboardComments.pageId, id));+ await tx.delete(artboardPages).where(eq(artboardPages.id, id));+ });+ };++ createRound = async (artboardId: string, params: CreateRoundParams) => {+ const owner = await this.ownerOf(artboardId);+ await this.assertWithin(artboardPages, artboardId, [params.pageId]);+ const [row] = await this.db+ .insert(artboardRounds)+ .values({ ...params, ...owner, artboardId, createdAt: writtenAt })+ .returning();+ return row;+ };++ updateRound = async (id: string, patch: UpdateRoundParams) => {+ const [current] = await this.db+ .select({ status: artboardRounds.status })+ .from(artboardRounds)+ .where(and(eq(artboardRounds.id, id), this.reachable(artboardRounds)))+ .limit(1);+ if (!current) return fail('not_found', `No round ${id}`);+ if (current.status !== 'open') fail('round_submitted', `Round ${id} is already submitted`);+ if (patch.recommendedBoardId) {+ const [option] = await this.db+ .select({ id: artboardBoards.id })+ .from(artboardBoards)+ .where(and(eq(artboardBoards.id, patch.recommendedBoardId), eq(artboardBoards.roundId, id)))+ .limit(1);+ if (!option) fail('not_found', `Board ${patch.recommendedBoardId} is not an option of ${id}`);+ }++ const [row] = await this.db+ .update(artboardRounds)+ .set({ ...patch, updatedAt: new Date() })+ .where(eq(artboardRounds.id, id))+ .returning();+ return row;+ };++ createGroup = async (artboardId: string, params: CreateGroupParams) => {+ const owner = await this.ownerOf(artboardId);+ await this.assertWithin(artboardPages, artboardId, [params.pageId]);+ const [row] = await this.db+ .insert(artboardGroups)+ .values({ ...params, ...owner, artboardId, createdAt: writtenAt })+ .returning();+ return row;+ };++ updateGroup = async (id: string, patch: Partial<CreateGroupParams>) => {+ const [current] = await this.db+ .select({ artboardId: artboardGroups.artboardId })+ .from(artboardGroups)+ .where(and(eq(artboardGroups.id, id), this.reachable(artboardGroups)))+ .limit(1);+ if (!current) return fail('not_found', `No group ${id}`);+ await this.assertWithin(artboardPages, current.artboardId, [patch.pageId]);++ const [row] = await this.db+ .update(artboardGroups)+ .set({ ...patch, updatedAt: new Date() })+ .where(eq(artboardGroups.id, id))+ .returning();+ return row;+ };++ deleteGroup = async (id: string) => {+ const reachable = await this.holds(+ artboardGroups,+ and(eq(artboardGroups.id, id), this.reachable(artboardGroups))!,+ );+ if (!reachable) fail('not_found', `No group ${id}`);+ if (await this.holds(artboardBoards, eq(artboardBoards.groupId, id)))+ fail('not_empty', `Group ${id} still has boards`);+ await this.db.delete(artboardGroups).where(eq(artboardGroups.id, id));+ };++ createBoard = async (artboardId: string, params: CreateBoardParams) => {+ const owner = await this.ownerOf(artboardId);+ await this.assertBoardPlacement(artboardId, params.pageId, params);+ const [row] = await this.db+ .insert(artboardBoards)+ .values({ ...params, ...owner, artboardId, createdAt: writtenAt })+ .returning();+ return row;+ };++ updateBoard = async (id: string, patch: Partial<CreateBoardParams>) => {+ const [current] = await this.db+ .select()+ .from(artboardBoards)+ .where(and(eq(artboardBoards.id, id), this.reachable(artboardBoards)))+ .limit(1);+ if (!current) return fail('not_found', `No board ${id}`);+ await this.assertBoardPlacement(current.artboardId, patch.pageId ?? current.pageId, {+ groupId: patch.groupId === undefined ? current.groupId : patch.groupId,+ roundId: patch.roundId === undefined ? current.roundId : patch.roundId,+ });++ const [row] = await this.db+ .update(artboardBoards)+ .set({ ...patch, updatedAt: new Date() })+ .where(eq(artboardBoards.id, id))+ .returning();+ return row;+ };++ deleteBoard = async (id: string) => {+ const [row] = await this.db+ .delete(artboardBoards)+ .where(and(eq(artboardBoards.id, id), this.reachable(artboardBoards)))+ .returning({ id: artboardBoards.id });+ if (!row) fail('not_found', `No board ${id}`);+ };++ createEdge = async (artboardId: string, params: CreateEdgeParams) => {+ const owner = await this.ownerOf(artboardId);+ await this.assertWithin(artboardBoards, artboardId, [+ params.sourceBoardId,+ params.targetBoardId,+ ]);+ const [row] = await this.db+ .insert(artboardEdges)+ .values({ ...params, ...owner, artboardId, createdAt: writtenAt })+ .returning();+ return row;+ };++ updateEdge = async (+ id: string,+ patch: Pick<+ Partial<CreateEdgeParams>,+ 'acceptanceFlowEdgeId' | 'condition' | 'isDefault' | 'label' | 'metadata' | 'sortOrder'+ >,+ ) => {+ const [row] = await this.db+ .update(artboardEdges)+ .set({ ...patch, updatedAt: new Date() })+ .where(and(eq(artboardEdges.id, id), this.reachable(artboardEdges)))+ .returning();+ return row ?? fail('not_found', `No edge ${id}`);+ };++ deleteEdge = async (id: string) => {+ const [row] = await this.db+ .delete(artboardEdges)+ .where(and(eq(artboardEdges.id, id), this.reachable(artboardEdges)))+ .returning({ id: artboardEdges.id });+ if (!row) fail('not_found', `No edge ${id}`);+ };++ chooseBoard = (roundId: string, boardId: string): Promise<ArtboardRoundRow> =>+ this.db.transaction(async (tx) => {+ // Locks the round row so a concurrent submitRound cannot commit between this check and the write.+ const [round] = await tx+ .select({ status: artboardRounds.status })+ .from(artboardRounds)+ .where(+ and(+ eq(artboardRounds.id, roundId),+ inArray(+ artboardRounds.artboardId,+ accessibleArtboardIds(tx, { userId: this.userId, workspaceId: this.workspaceId }),+ ),+ ),+ )+ .for('update');+ if (!round) return fail('not_found', `No round ${roundId}`);+ if (round.status !== 'open')+ fail('round_submitted', 'The round is submitted; its choice is final');++ const [option] = await tx+ .select({ id: artboardBoards.id })+ .from(artboardBoards)+ .where(and(eq(artboardBoards.id, boardId), eq(artboardBoards.roundId, roundId)))+ .limit(1);+ if (!option) fail('not_found', `Board ${boardId} is not an option of round ${roundId}`);++ const now = new Date();+ const [row] = await tx+ .update(artboardRounds)+ .set({ chosenBoardId: boardId, selectedAt: now, selectedBy: this.userId, updatedAt: now })+ .where(eq(artboardRounds.id, roundId))+ .returning();+ return row;+ });++ private roundsReachableIn = (tx: Transaction) =>+ inArray(+ artboardRounds.artboardId,+ accessibleArtboardIds(tx, { userId: this.userId, workspaceId: this.workspaceId }),+ );++ private settleRounds = async (+ tx: Transaction,+ scope: SQL | undefined,+ expectedIds?: string[],+ ) => {+ const members = await tx.select().from(artboardRounds).where(scope).for('update');+ const ids = members.map((item) => item.id);+ if (+ expectedIds &&+ (expectedIds.length !== ids.length || ids.some((id) => !expectedIds.includes(id)))+ )+ fail('rounds_changed', 'The open rounds are not the ones that were submitted');+ if (!ids.length) return [];+ const undecided = members.find((item) => !item.chosenBoardId && !item.recommendedBoardId);+ if (undecided)+ fail('missing_choice', `Round ${undecided.id} has no pick and no recommendation`);++ const now = new Date();+ await tx+ .update(artboardRounds)+ .set({+ chosenBoardId: artboardRounds.recommendedBoardId,+ selectedAt: now,+ selectedBy: this.userId,+ })+ .where(and(inArray(artboardRounds.id, ids), isNull(artboardRounds.chosenBoardId)));+ return tx+ .update(artboardRounds)+ .set({ status: 'submitted', updatedAt: now })+ .where(inArray(artboardRounds.id, ids))+ .returning();+ };++ submitRound = (roundId: string): Promise<ArtboardRoundRow[]> =>+ this.db.transaction(async (tx) => {+ const [round] = await tx+ .select()+ .from(artboardRounds)+ .where(and(eq(artboardRounds.id, roundId), this.roundsReachableIn(tx)))+ .for('update');+ if (!round) return fail('not_found', `No round ${roundId}`);+ if (round.status !== 'open') fail('round_submitted', `Round ${roundId} is already submitted`);++ const batchId = round.metadata?.batchId;+ return this.settleRounds(+ tx,+ and(+ eq(artboardRounds.artboardId, round.artboardId),+ eq(artboardRounds.status, 'open'),+ batchId+ ? sql`${artboardRounds.metadata}->>'batchId' = ${batchId}`+ : eq(artboardRounds.id, roundId),+ ),+ );+ });++ submitOpenRounds = (artboardId: string, expectedIds?: string[]): Promise<ArtboardRoundRow[]> =>+ this.db.transaction((tx) =>+ this.settleRounds(+ tx,+ and(+ eq(artboardRounds.artboardId, artboardId),+ eq(artboardRounds.status, 'open'),+ this.roundsReachableIn(tx),+ ),+ expectedIds,+ ),+ );++ listBoardsByProject = (projectId: string): Promise<ArtboardBoardRow[]> =>+ this.db+ .select()+ .from(artboardBoards)+ .where(and(eq(artboardBoards.projectId, projectId), this.reachable(artboardBoards)))+ .orderBy(asc(artboardBoards.createdAt));++ findBoardByAcceptanceNode = async (nodeId: string): Promise<ArtboardBoardRow | undefined> => {+ const [row] = await this.db+ .select()+ .from(artboardBoards)+ .where(and(eq(artboardBoards.acceptanceFlowNodeId, nodeId), this.reachable(artboardBoards)))+ .limit(1);+ return row;+ };++ listUndecidedRoundsByProject = async (projectId: string): Promise<ArtboardRoundRow[]> => {+ const rows = await this.db+ .select({ round: artboardRounds })+ .from(artboardRounds)+ .innerJoin(artboards, eq(artboards.id, artboardRounds.artboardId))+ .where(+ and(+ eq(artboards.projectId, projectId),+ or(isNull(artboardRounds.chosenBoardId), ne(artboardRounds.status, 'submitted')),+ this.reachable(artboardRounds),+ ),+ )+ .orderBy(asc(artboardRounds.createdAt));+ return rows.map((row) => row.round);+ };+}diff --git a/packages/database/src/models/artboard/structureError.ts b/packages/database/src/models/artboard/structureError.tsnew file mode 100644index 00000000000..4385dcbfbba--- /dev/null+++ b/packages/database/src/models/artboard/structureError.ts@@ -0,0 +1,21 @@+export type ArtboardStructureErrorCode =+ | 'invalid'+ | 'last_page'+ | 'missing_choice'+ | 'not_empty'+ | 'not_found'+ | 'round_submitted'+ | 'rounds_changed';++export class ArtboardStructureError extends Error {+ constructor(+ public code: ArtboardStructureErrorCode,+ message: string,+ ) {+ super(message);+ }+}++export const fail = (code: ArtboardStructureErrorCode, message: string): never => {+ throw new ArtboardStructureError(code, message);+};diff --git a/packages/database/src/models/artboard/types.ts b/packages/database/src/models/artboard/types.tsnew file mode 100644index 00000000000..21ed16ff89c--- /dev/null+++ b/packages/database/src/models/artboard/types.ts@@ -0,0 +1,23 @@+import type {+ artboardBoards,+ artboardComments,+ artboardEdges,+ artboardGroups,+ artboardPages,+ artboardRounds,+ artboards,+} from '../../schemas/artboard';++export type ArtboardRow = typeof artboards.$inferSelect;+export type ArtboardPageRow = typeof artboardPages.$inferSelect;+export type NewArtboardPageRow = typeof artboardPages.$inferInsert;+export type ArtboardRoundRow = typeof artboardRounds.$inferSelect;+export type NewArtboardRoundRow = typeof artboardRounds.$inferInsert;+export type ArtboardGroupRow = typeof artboardGroups.$inferSelect;+export type NewArtboardGroupRow = typeof artboardGroups.$inferInsert;+export type ArtboardBoardRow = typeof artboardBoards.$inferSelect;+export type NewArtboardBoardRow = typeof artboardBoards.$inferInsert;+export type ArtboardEdgeRow = typeof artboardEdges.$inferSelect;+export type NewArtboardEdgeRow = typeof artboardEdges.$inferInsert;+export type ArtboardCommentRow = typeof artboardComments.$inferSelect;+export type NewArtboardCommentRow = typeof artboardComments.$inferInsert;diff --git a/packages/database/src/models/message/query.ts b/packages/database/src/models/message/query.tsindex 7d2164be187..30a087a2c1c 100644--- a/packages/database/src/models/message/query.ts+++ b/packages/database/src/models/message/query.ts@@ -101,6 +101,7 @@ export class MessageConversationQueries extends MessageScope {agentId,before,current = 0,+ includeArtboardWorks,includeFileWorks,pageSize = 1000,sessionId,@@ -203,6 +204,7 @@ export class MessageConversationQueries extends MessageScope {allowShareVisitor: effectiveIncludeVisitor,before,current,+ includeArtboardWorks,includeFileWorks,pageSize,postProcessUrl: options.postProcessUrl,@@ -234,6 +236,7 @@ export class MessageConversationQueries extends MessageScope {allowShareVisitor: effectiveIncludeVisitor,before,current,+ includeArtboardWorks,includeFileWorks,pageSize,postProcessUrl: options.postProcessUrl,@@ -269,6 +272,7 @@ export class MessageConversationQueries extends MessageScope {allowShareVisitor: effectiveIncludeVisitor,before,current,+ includeArtboardWorks,includeFileWorks,pageSize,postProcessUrl: options.postProcessUrl,@@ -434,6 +438,7 @@ export class MessageConversationQueries extends MessageScope {cursor,direction = 'backward',groupId,+ includeArtboardWorks,includeFileWorks,roundLimit = DEFAULT_ROUND_LIMIT,skipWorks,@@ -475,6 +480,7 @@ export class MessageConversationQueries extends MessageScope {const messages = await this.page.queryWithWhere({allowShareVisitor: true,current: 0,+ includeArtboardWorks,includeFileWorks,pageSize: CURSOR_PAGE_CEILING,postProcessUrl: options.postProcessUrl,diff --git a/packages/database/src/models/message/queryWithWhere.ts b/packages/database/src/models/message/queryWithWhere.tsindex 93df59e0640..ac77a7cafe3 100644--- a/packages/database/src/models/message/queryWithWhere.ts+++ b/packages/database/src/models/message/queryWithWhere.ts@@ -58,6 +58,7 @@ export class MessagePageQueries extends MessageScope {where,before,current = 0,+ includeArtboardWorks,includeFileWorks,pageSize = 1000,postProcessUrl,@@ -245,7 +246,7 @@ export class MessagePageQueries extends MessageScope {? ({} as Record<string, WorkSummaryItem[]>): this.relations.queryMessageWorkSummaries(result,- includeFileWorks,+ { includeArtboardWorks, includeFileWorks },timing,workAccessScope,),diff --git a/packages/database/src/models/message/relations.ts b/packages/database/src/models/message/relations.tsindex d195498f8a6..bc3dc7fe106 100644--- a/packages/database/src/models/message/relations.ts+++ b/packages/database/src/models/message/relations.ts@@ -208,7 +208,7 @@ export class MessageRelationQueries extends MessageScope {*/queryMessageWorkSummaries = async (rows: { id: unknown; metadata: unknown }[],- includeFileWorks?: boolean,+ optIn: { includeArtboardWorks?: boolean; includeFileWorks?: boolean } = {},timing?: ModelTimingContext,workAccessScope?: WorkAccessScope,): Promise<Record<string, WorkSummaryItem[]>> => {@@ -229,7 +229,7 @@ export class MessageRelationQueries extends MessageScope {this.workspaceId,workAccessScope,).listSummariesByRootOperations({- includeFileWorks,+ ...optIn,rootOperationIds: Array.from(anchorByRootId.keys()),}),{ rootOperationCount: anchorByRootId.size },diff --git a/packages/database/src/models/message/types.ts b/packages/database/src/models/message/types.tsindex b692c7acebb..d2310446003 100644--- a/packages/database/src/models/message/types.ts+++ b/packages/database/src/models/message/types.ts@@ -55,6 +55,8 @@ export interface QueryMessagesOptions {* timestamp strings compared with a `::timestamptz` cast.*/groupNodeWindow?: MessageGroupNodeWindow;+ /** Same opt-in as `includeFileWorks`, for `artboard` work summaries. */+ includeArtboardWorks?: boolean;/*** Opt-in for `file` work summaries in the payload (see* `QueryMessageParams.includeFileWorks`).@@ -150,6 +152,7 @@ export interface QueryTopicByCursorParams {/** Group chat topic: rows carry the group id, same filter as `query`. */groupId?: string | null;/** See {@link QueryMessageParams.includeFileWorks}. */+ includeArtboardWorks?: boolean;includeFileWorks?: boolean;/** How many rounds to load per page (the current round is always whole). */roundLimit?: number;diff --git a/packages/database/src/models/work/__tests__/artboard.test.ts b/packages/database/src/models/work/__tests__/artboard.test.tsnew file mode 100644index 00000000000..7804d7c1e4c--- /dev/null+++ b/packages/database/src/models/work/__tests__/artboard.test.ts@@ -0,0 +1,200 @@+// @vitest-environment node+import type { RegisterArtboardWorkParams } from '@lobechat/types';+import { eq } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { projects, projectWorks, tasks } from '../../../schemas';+import { ArtboardModel } from '../../artboard';+import { WorkModel } from '..';+import {+ agentId,+ cleanupWorkTestData,+ seedWorkTestData,+ serverDB,+ threadId,+ topicId,+ userId,+ userId2,+} from './_fixtures';++const projectId = 'prj_artboard_work';+let artboardId: string;++beforeEach(async () => {+ await seedWorkTestData();+ await serverDB.insert(projects).values({ id: projectId, name: 'Onboarding', userId });+ await serverDB.insert(tasks).values({+ createdByUserId: userId,+ id: 'task_artboard_work',+ identifier: 'T-1',+ instruction: 'design onboarding',+ seq: 1,+ });+ const board = await new ArtboardModel(serverDB, userId).create({+ projectId,+ taskId: 'task_artboard_work',+ title: '新用户首次进入项目',+ });+ artboardId = board.id;+});++afterEach(async () => {+ await serverDB.delete(tasks).where(eq(tasks.id, 'task_artboard_work'));+ await cleanupWorkTestData();+});++const params = (+ overrides: Partial<RegisterArtboardWorkParams> = {},+): RegisterArtboardWorkParams => ({+ agentId,+ artboardId,+ changeType: 'created',+ description: '3 组 · 10 个画面',+ projectId,+ rootOperationId: 'op-artboard-1',+ threadId,+ title: '新用户首次进入项目',+ toolCallId: 'call-artboard-1',+ toolIdentifier: 'builtin-artboard',+ toolName: 'createArtboard',+ topicId,+ ...overrides,+});++describe('WorkModel · artboard', () => {+ it('registers an artboard Work and binds it to the project', async () => {+ const model = new WorkModel(serverDB, userId);+ const work = await model.registerArtboard(params());++ expect(work).toMatchObject({+ resourceId: artboardId,+ resourceType: 'artboard',+ title: '新用户首次进入项目',+ type: 'artboard',+ });+ const bindings = await serverDB+ .select()+ .from(projectWorks)+ .where(eq(projectWorks.projectId, projectId));+ expect(bindings.map((b) => b.workId)).toEqual([work.id]);+ });++ it('appends a version on finalize without a second project binding', async () => {+ const model = new WorkModel(serverDB, userId);+ await model.registerArtboard(params());+ await model.registerArtboard(+ params({ changeType: 'updated', rootOperationId: null, toolCallId: null }),+ );++ const page = await model.listByWorkspace({ includeArtboardWorks: true, type: 'artboard' });+ expect(page.items).toHaveLength(1);+ expect(page.items[0].version.version).toBe(2);+ const bindings = await serverDB+ .select()+ .from(projectWorks)+ .where(eq(projectWorks.projectId, projectId));+ expect(bindings).toHaveLength(1);+ });++ it('hides artboard Works from clients that did not opt in, even with includeFileWorks', async () => {+ const model = new WorkModel(serverDB, userId);+ await model.registerArtboard(params());++ const fileOnly = await model.listSummariesByRootOperations({+ includeFileWorks: true,+ rootOperationIds: ['op-artboard-1'],+ });+ expect(fileOnly['op-artboard-1'] ?? []).toEqual([]);+ expect((await model.listByWorkspace({ includeFileWorks: true })).items).toEqual([]);+ expect(await model.listByConversation({ includeFileWorks: true, topicId })).toEqual([]);++ const optedIn = await model.listSummariesByRootOperations({+ includeArtboardWorks: true,+ includeFileWorks: true,+ rootOperationIds: ['op-artboard-1'],+ });+ expect(optedIn['op-artboard-1']).toHaveLength(1);+ expect(optedIn['op-artboard-1'][0]).toMatchObject({ type: 'artboard' });+ });++ it('drops the Work from the gallery once its board is gone', async () => {+ const model = new WorkModel(serverDB, userId);+ await model.registerArtboard(params());+ await new ArtboardModel(serverDB, userId).delete(artboardId);++ expect((await model.listByWorkspace({ includeArtboardWorks: true })).items).toEqual([]);+ });+});++describe('WorkModel · artboard publish', () => {+ const publish = {+ deploymentId: 'dep_1',+ publishedRevision: 4,+ publisherUserId: userId,+ snapshotHash: 'hash_1',+ url: 'https://board.lobe.page',+ };++ it('records the share on the Work and finds it again', async () => {+ const model = new WorkModel(serverDB, userId);+ await model.registerArtboard(params());++ await model.recordArtboardPublish(artboardId, publish);+ const work = await model.findArtboardWork(artboardId);++ expect(work?.url).toBe('https://board.lobe.page');+ expect(work?.metadata?.artboardPublish).toEqual({+ deploymentId: 'dep_1',+ publishedRevision: 4,+ publisherUserId: userId,+ snapshotHash: 'hash_1',+ });+ });++ it('keeps the share link when the board registers a new version', async () => {+ const model = new WorkModel(serverDB, userId);+ await model.registerArtboard(params());+ await model.recordArtboardPublish(artboardId, publish);++ await model.registerArtboard(+ params({ changeType: 'updated', rootOperationId: null, toolCallId: 'call-artboard-2' }),+ );+ const work = await model.findArtboardWork(artboardId);++ expect(work?.url).toBe('https://board.lobe.page');+ expect(work?.metadata?.artboardPublish?.deploymentId).toBe('dep_1');+ });++ it('clears the share and nothing else', async () => {+ const model = new WorkModel(serverDB, userId);+ await model.registerArtboard(params());+ await model.recordArtboardPublish(artboardId, publish);++ await model.clearArtboardPublish(artboardId);+ const work = await model.findArtboardWork(artboardId);++ expect(work?.url).toBeNull();+ expect(work?.metadata?.artboardPublish).toBeUndefined();+ expect(work?.title).toBe('新用户首次进入项目');+ });++ it('does not let another user record a share on the Work', async () => {+ await new WorkModel(serverDB, userId).registerArtboard(params());++ const row = await new WorkModel(serverDB, userId2).recordArtboardPublish(artboardId, publish);++ expect(row).toBeNull();+ expect((await new WorkModel(serverDB, userId).findArtboardWork(artboardId))?.url).toBeNull();+ });++ it('maps deployments back to their boards', async () => {+ const model = new WorkModel(serverDB, userId);+ await model.registerArtboard(params());+ await model.recordArtboardPublish(artboardId, publish);++ expect(await model.findArtboardIdsByDeploymentIds(['dep_1', 'dep_missing'])).toEqual({+ dep_1: artboardId,+ });+ expect(await model.findArtboardIdsByDeploymentIds([])).toEqual({});+ });+});diff --git a/packages/database/src/models/work/__tests__/artboardShellResult.test.ts b/packages/database/src/models/work/__tests__/artboardShellResult.test.tsnew file mode 100644index 00000000000..d75acdb1f47--- /dev/null+++ b/packages/database/src/models/work/__tests__/artboardShellResult.test.ts@@ -0,0 +1,171 @@+// @vitest-environment node+import { eq } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { projects, tasks } from '../../../schemas';+import { ArtboardModel } from '../../artboard';+import { WorkModel } from '..';+import { parseArtboardShellChange } from '../artboardShellResult';+import { cleanupWorkTestData, seedWorkTestData, serverDB, topicId, userId } from './_fixtures';++const projectId = 'prj_artboard_shell';+let artboardId: string;++beforeEach(async () => {+ await seedWorkTestData();+ await serverDB.insert(projects).values({ id: projectId, name: 'Onboarding', userId });+ await serverDB.insert(tasks).values({+ createdByUserId: userId,+ id: 'task_artboard_shell',+ identifier: 'T-9',+ instruction: 'design onboarding',+ seq: 9,+ });+ const board = await new ArtboardModel(serverDB, userId).create({+ projectId,+ taskId: 'task_artboard_shell',+ title: '首次进入',+ });+ artboardId = board.id;+});++afterEach(async () => {+ await serverDB.delete(tasks).where(eq(tasks.id, 'task_artboard_shell'));+ await cleanupWorkTestData();+});++const line = () => `artboard ${artboardId} · revision 1 · 0 groups · 0 boards`;++describe('parseArtboardShellChange', () => {+ it('reads the board id from a successful lh artboard create', () => {+ expect(+ parseArtboardShellChange({+ command: `lh artboard create --title '首次进入'`,+ exitCode: 0,+ output: 'art_1 created\nartboard art_1 · revision 1 · 2 groups · 4 boards\n',+ }),+ ).toEqual({ artboardId: 'art_1', changeType: 'created' });+ });++ it('unwraps the codex shell wrapper and reads --json output', () => {+ expect(+ parseArtboardShellChange({+ command: `/bin/zsh -lc "lh artboard create --title x --json"`,+ exitCode: 0,+ output: JSON.stringify({ artboard: { id: 'art_2', revision: 1 }, changedIds: [] }),+ }),+ ).toEqual({ artboardId: 'art_2', changeType: 'created' });+ });++ it('recognises the CLI path the app hands to an agent', () => {+ const output = 'artboard art_4 · revision 1 · 0 groups · 0 boards';+ for (const program of [+ '"$LOBEHUB_CLI"',+ '"${LOBEHUB_CLI}"',+ '"${LOBEHUB_CLI:-lh}"',+ '/tmp/app/bin/lobehub',+ 'lobe',+ ])+ expect(+ parseArtboardShellChange({+ command: `/bin/zsh -lc '${program} artboard create --title x'`,+ exitCode: 0,+ output,+ }),+ ).toEqual({ artboardId: 'art_4', changeType: 'created' });+ });++ it('reads an update as a new version of the board named in the command', () => {+ expect(+ parseArtboardShellChange({+ command: `lh artboard update art_3 --revision 1 --ops '[]'`,+ exitCode: 0,+ output: 'artboard art_3 · revision 2 · 1 groups · 1 boards',+ }),+ ).toEqual({ artboardId: 'art_3', changeType: 'updated' });+ });++ it('ignores failed runs, reads and other programs', () => {+ const output = 'artboard art_3 · revision 2 · 1 groups · 1 boards';+ expect(+ parseArtboardShellChange({ command: 'lh artboard create --title x', exitCode: 1, output }),+ ).toBeNull();+ expect(+ parseArtboardShellChange({+ command: `lh artboard update art_3 --revision 1 --ops '[]'`,+ exitCode: 1,+ output,+ }),+ ).toBeNull();+ expect(+ parseArtboardShellChange({ command: 'lh artboard read art_3', exitCode: 0, output }),+ ).toBeNull();+ expect(+ parseArtboardShellChange({ command: 'echo artboard create', exitCode: 0, output }),+ ).toBeNull();+ });+});++describe('WorkModel.registerShellArtboardResult', () => {+ it('registers the created board under the run’s root operation', async () => {+ const work = await new WorkModel(serverDB, userId).registerShellArtboardResult({+ data: { command: `lh artboard create --title '首次进入'`, exitCode: 0, output: line() },+ messageId: null,+ rootOperationId: 'op-hetero-1',+ toolCallId: 'call-shell-1',+ toolIdentifier: 'codex',+ toolName: 'command_execution',+ topicId,+ });++ expect(work).toMatchObject({ resourceId: artboardId, title: '首次进入', type: 'artboard' });+ const summaries = await new WorkModel(serverDB, userId).listSummariesByRootOperations({+ includeArtboardWorks: true,+ rootOperationIds: ['op-hetero-1'],+ });+ expect(summaries['op-hetero-1']).toHaveLength(1);+ });++ it('registers nothing for a board id it cannot find', async () => {+ expect(+ await new WorkModel(serverDB, userId).registerShellArtboardResult({+ data: {+ command: 'lh artboard create --title x',+ exitCode: 0,+ output: 'artboard art_missing · revision 1 · 0 groups · 0 boards',+ },+ toolIdentifier: 'codex',+ toolName: 'command_execution',+ }),+ ).toBeNull();+ });++ it('moves the card to the later run when the board is updated', async () => {+ const model = new WorkModel(serverDB, userId);+ const base = { toolIdentifier: 'codex', toolName: 'command_execution', topicId };+ await model.registerShellArtboardResult({+ ...base,+ data: { command: `lh artboard create --title '首次进入'`, exitCode: 0, output: line() },+ rootOperationId: 'op-hetero-1',+ toolCallId: 'call-shell-1',+ });+ await model.registerShellArtboardResult({+ ...base,+ data: {+ command: `"$LOBEHUB_CLI" artboard update ${artboardId} --revision 1 --ops '[]'`,+ exitCode: 0,+ output: line(),+ },+ rootOperationId: 'op-hetero-2',+ toolCallId: 'call-shell-2',+ });++ const summaries = await model.listSummariesByRootOperations({+ includeArtboardWorks: true,+ rootOperationIds: ['op-hetero-1', 'op-hetero-2'],+ });+ expect(summaries['op-hetero-1']).toHaveLength(0);+ expect(summaries['op-hetero-2']).toHaveLength(1);+ expect(summaries['op-hetero-2'][0]).toMatchObject({ resourceId: artboardId });+ });+});diff --git a/packages/database/src/models/work/__tests__/canvas.test.ts b/packages/database/src/models/work/__tests__/canvas.test.tsindex 22aae76ccd6..ac9e8b103ed 100644--- a/packages/database/src/models/work/__tests__/canvas.test.ts+++ b/packages/database/src/models/work/__tests__/canvas.test.ts@@ -348,4 +348,39 @@ describe('WorkModel · canvas', () => {const legacy = await model.listSummariesByRootOperations({ rootOperationIds: ['op-canvas-1'] });expect(legacy['op-canvas-1'] ?? []).toEqual([]);});++ describe('version lookups for artboard sources', () => {+ it('finds the version row of a canvas and maps version rows back to their canvas', async () => {+ const owner = new WorkModel(serverDB, userId);+ await owner.registerCanvas(params());+ await owner.registerCanvas(params({ toolCallId: 'call-canvas-2', toolName: 'updateCanvas' }));++ const first = await owner.findCanvasVersionId('cvs_cost', 1);+ const second = await owner.findCanvasVersionId('cvs_cost', 2);+ expect(first).toBeTruthy();+ expect(second).toBeTruthy();+ expect(await owner.findCanvasVersionId('cvs_cost', 3)).toBeNull();++ expect(await owner.findCanvasSourcesByVersionIds([first!, second!])).toEqual({+ [first!]: { canvasId: 'cvs_cost', version: 1 },+ [second!]: { canvasId: 'cvs_cost', version: 2 },+ });+ });++ it('hides a canvas in the trash and a canvas of another user', async () => {+ const owner = new WorkModel(serverDB, userId);+ const work = await owner.registerCanvas(params());+ const versionId = (await owner.findCanvasVersionId('cvs_cost', 1))!;++ expect(await new WorkModel(serverDB, userId2).findCanvasSourcesByVersionIds([versionId])).toEqual(+ {},+ );++ await serverDB+ .update(works)+ .set({ deletedAt: new Date(), isDeleted: true })+ .where(eq(works.id, work.id));+ expect(await owner.findCanvasSourcesByVersionIds([versionId])).toEqual({});+ });+ });});diff --git a/packages/database/src/models/work/artboard.ts b/packages/database/src/models/work/artboard.tsnew file mode 100644index 00000000000..669f9c78cad--- /dev/null+++ b/packages/database/src/models/work/artboard.ts@@ -0,0 +1,159 @@+import type {+ ArtboardWorkPublishMetadata,+ RegisterArtboardWorkParams,+ WorkItem,+ WorkMetadata,+} from '@lobechat/types';+import { and, eq, inArray, sql } from 'drizzle-orm';++import { projectWorks } from '../../schemas/projectWork';+import { works } from '../../schemas/work';+import { type WorkContext, workOwnership } from './context';+import { createDisplayWorkAdapter } from './displayWork';+import { registerWorkVersion } from './writes';++export const artboardWorkAdapter = createDisplayWorkAdapter({ type: 'artboard' });++const artboardResource = (ctx: WorkContext, artboardId: string) =>+ and(workOwnership(ctx), eq(works.resourceType, 'artboard'), eq(works.resourceId, artboardId));++export type ArtboardWork = WorkItem & { metadata: WorkMetadata | null };++export const registerArtboardWork = async (+ ctx: WorkContext,+ params: RegisterArtboardWorkParams,+): Promise<WorkItem> => {+ const work = await registerWorkVersion(+ ctx,+ {+ resourceId: params.artboardId,+ resourceType: 'artboard',+ type: 'artboard',+ userId: ctx.userId,+ visibility: 'private',+ },+ {+ agentId: params.agentId,+ changeType: params.changeType,+ 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 share link written by `recordArtboardPublish` 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(artboardResource(txCtx, params.artboardId))+ .limit(1);+ return {+ display: {+ description: params.description ?? null,+ identifier: params.artboardId,+ title: params.title,+ url: published?.url ?? null,+ },+ };+ },+ );++ if (params.projectId)+ await ctx.db+ .insert(projectWorks)+ .values({+ addedByUserId: ctx.userId,+ projectId: params.projectId,+ workId: work.id,+ workspaceId: ctx.workspaceId ?? null,+ })+ .onConflictDoNothing({ target: [projectWorks.projectId, projectWorks.workId] });++ return work;+};++export const findArtboardWork = async (+ ctx: WorkContext,+ artboardId: string,+): Promise<ArtboardWork | null> => {+ const [row] = await ctx.db.select().from(works).where(artboardResource(ctx, artboardId)).limit(1);+ return (row as ArtboardWork | undefined) ?? null;+};++export const findArtboardWorkByWorkId = async (+ ctx: WorkContext,+ workId: string,+): Promise<ArtboardWork | null> => {+ const [row] = await ctx.db+ .select()+ .from(works)+ .where(and(workOwnership(ctx), eq(works.id, workId), eq(works.resourceType, 'artboard')))+ .limit(1);+ return (row as ArtboardWork | undefined) ?? null;+};++export const recordArtboardPublish = async (+ ctx: WorkContext,+ artboardId: string,+ params: ArtboardWorkPublishMetadata & { url: string },+): Promise<WorkItem | null> => {+ const publish: ArtboardWorkPublishMetadata = {+ deploymentId: params.deploymentId,+ publishedRevision: params.publishedRevision,+ publisherUserId: params.publisherUserId,+ snapshotHash: params.snapshotHash,+ };+ const [row] = await ctx.db+ .update(works)+ .set({+ metadata: sql`coalesce(${works.metadata}, '{}'::jsonb) || jsonb_build_object('artboardPublish', ${JSON.stringify(publish)}::jsonb)`,+ url: params.url,+ })+ .where(artboardResource(ctx, artboardId))+ .returning();+ return (row as WorkItem | undefined) ?? null;+};++export const clearArtboardPublish = async (+ ctx: WorkContext,+ artboardId: string,+): Promise<WorkItem | null> => {+ const [row] = await ctx.db+ .update(works)+ .set({+ metadata: sql`coalesce(${works.metadata}, '{}'::jsonb) - 'artboardPublish'`,+ url: null,+ })+ .where(artboardResource(ctx, artboardId))+ .returning();+ return (row as WorkItem | undefined) ?? null;+};++export const findArtboardIdsByDeploymentIds = async (+ ctx: WorkContext,+ deploymentIds: string[],+): Promise<Record<string, string>> => {+ if (deploymentIds.length === 0) return {};++ const deploymentId = sql<string>`${works.metadata}->'artboardPublish'->>'deploymentId'`;+ const rows = await ctx.db+ .select({ artboardId: works.resourceId, deploymentId })+ .from(works)+ .where(+ and(+ workOwnership(ctx),+ eq(works.resourceType, 'artboard'),+ inArray(deploymentId, deploymentIds),+ ),+ );++ return Object.fromEntries(+ rows.flatMap((row) => (row.artboardId ? [[row.deploymentId, row.artboardId] as const] : [])),+ );+};diff --git a/packages/database/src/models/work/artboardShellResult.ts b/packages/database/src/models/work/artboardShellResult.tsnew file mode 100644index 00000000000..3503565776b--- /dev/null+++ b/packages/database/src/models/work/artboardShellResult.ts@@ -0,0 +1,102 @@+import {+ parseArtboardResultLine,+ type RegisterArtboardWorkParams,+ type SkillToolResultWorkInput,+ type WorkItem,+} from '@lobechat/types';++import { ArtboardModel } from '../artboard';+import { registerArtboardWork } from './artboard';+import type { WorkContext } from './context';+import { parseShellCommandSegments } from './shellCommandParsing';++interface ShellRecord {+ command: string;+ exitCode?: number;+ output?: string;+}++const isRecord = (value: unknown): value is Record<string, unknown> =>+ typeof value === 'object' && value !== null;++const CLI_NAMES = new Set(['lh', 'lobe', 'lobehub']);+const CLI_VARIABLE = /^\$\{?LOBEHUB_CLI\b/;++const isCli = (token: string) =>+ CLI_VARIABLE.test(token) || CLI_NAMES.has(token.split('/').at(-1)!);++type ArtboardShellChange = Pick<RegisterArtboardWorkParams, 'artboardId' | 'changeType'>;++const artboardCallOf = (segment: string[]) => {+ const index = segment.findIndex((token, at) => isCli(token) && segment[at + 1] === 'artboard');+ if (index < 0) return undefined;+ const [verb, target] = segment.slice(index + 2);+ if (verb === 'create') return { changeType: 'created' as const };+ if (verb === 'update' && target) return { artboardId: target, changeType: 'updated' as const };+};++const idFromJson = (output: string) => {+ try {+ const parsed: unknown = JSON.parse(output);+ const artboard = isRecord(parsed) ? parsed.artboard : undefined;+ return isRecord(artboard) && typeof artboard.id === 'string' ? artboard.id : undefined;+ } catch {+ return undefined;+ }+};++export const parseArtboardShellChange = (record: ShellRecord): ArtboardShellChange | null => {+ if (record.exitCode !== undefined && record.exitCode !== 0) return null;+ const call = parseShellCommandSegments(record.command)+ ?.map(artboardCallOf)+ .find((found) => !!found);+ if (!call || !record.output) return null;++ const artboardId =+ call.artboardId ??+ parseArtboardResultLine(record.output)?.artboardId ??+ idFromJson(record.output.trim());+ return artboardId ? { artboardId, changeType: call.changeType } : null;+};++const asShellRecord = (data: unknown): ShellRecord | undefined =>+ isRecord(data) && typeof data.command === 'string'+ ? {+ command: data.command,+ exitCode: typeof data.exitCode === 'number' ? data.exitCode : undefined,+ output: typeof data.output === 'string' ? data.output : undefined,+ }+ : undefined;++export const registerShellArtboardResult = async (+ ctx: WorkContext,+ params: SkillToolResultWorkInput & { toolIdentifier: string },+): Promise<WorkItem | null> => {+ const record = asShellRecord(params.data);+ const parsed = record && parseArtboardShellChange(record);+ if (!parsed) return null;++ const board = await new ArtboardModel(ctx.db, ctx.userId, ctx.workspaceId).findById(+ parsed.artboardId,+ );+ if (!board) return null;++ const work: RegisterArtboardWorkParams = {+ agentId: params.agentId,+ artboardId: board.id,+ changeType: parsed.changeType,+ cumulativeCost: params.cumulativeCost,+ cumulativeUsage: params.cumulativeUsage,+ description: board.description,+ messageId: params.messageId,+ projectId: board.projectId,+ rootOperationId: params.rootOperationId,+ threadId: params.threadId,+ title: board.title,+ toolCallId: params.toolCallId,+ toolIdentifier: params.toolIdentifier,+ toolName: params.toolName,+ topicId: params.topicId,+ };+ return registerArtboardWork(ctx, work);+};diff --git a/packages/database/src/models/work/canvas.ts b/packages/database/src/models/work/canvas.tsindex b4788525a97..3b621ac394d 100644--- a/packages/database/src/models/work/canvas.ts+++ b/packages/database/src/models/work/canvas.ts@@ -169,6 +169,44 @@ export const findCanvasWorkVersion = async (return row?.version ?? null;};+export const findCanvasVersionId = async (+ ctx: WorkContext,+ canvasId: string,+ version: number,+): Promise<string | null> => {+ const [row] = await ctx.db+ .select({ id: workVersions.id })+ .from(workVersions)+ .innerJoin(works, eq(works.id, workVersions.workId))+ .where(and(canvasResource(ctx, canvasId), eq(workVersions.version, version)))+ .limit(1);+ return row?.id ?? null;+};++export const findCanvasSourcesByVersionIds = async (+ ctx: WorkContext,+ versionIds: string[],+): Promise<Record<string, { canvasId: string; version: number }>> => {+ if (versionIds.length === 0) return {};+ const rows = await ctx.db+ .select({ canvasId: works.resourceId, id: workVersions.id, version: workVersions.version })+ .from(workVersions)+ .innerJoin(works, eq(works.id, workVersions.workId))+ .where(+ and(+ workOwnership(ctx),+ eq(works.resourceType, 'canvas'),+ sql`${works.isDeleted} IS NOT TRUE`,+ inArray(workVersions.id, versionIds),+ ),+ );+ return Object.fromEntries(+ rows.flatMap((row) =>+ row.canvasId ? [[row.id, { canvasId: row.canvasId, version: row.version }] as const] : [],+ ),+ );+};+export const findCanvasWorkVersionByToolCall = async (ctx: WorkContext,canvasId: string,diff --git a/packages/database/src/models/work/index.ts b/packages/database/src/models/work/index.tsindex 787d33ac708..e3fdf38f092 100644--- a/packages/database/src/models/work/index.ts+++ b/packages/database/src/models/work/index.ts@@ -1,9 +1,11 @@import {+ type ArtboardWorkPublishMetadata,type CanvasWorkPublishMetadata,type DeleteDocumentWorkParams,type DeleteTaskWorkParams,type DeleteWorkParams,isWorkSkillProvider,+ type RegisterArtboardWorkParams,type RegisterCanvasWorkParams,type RegisterDocumentWorkParams,type RegisterExternalWorkParams,@@ -20,9 +22,20 @@ import debug from 'debug';import type { LobeChatDatabase } from '../../type';import { ScmChangeRequestModel } from '../scm';+import {+ clearArtboardPublish,+ findArtboardIdsByDeploymentIds,+ findArtboardWork,+ findArtboardWorkByWorkId,+ recordArtboardPublish,+ registerArtboardWork,+} from './artboard';+import { registerShellArtboardResult } from './artboardShellResult';import {findCanvasIdByWorkId,findCanvasIdsByDeploymentIds,+ findCanvasSourcesByVersionIds,+ findCanvasVersionId,findCanvasWork,findCanvasWorkVersion,findCanvasWorkVersionByToolCall,@@ -120,6 +133,24 @@ export class WorkModel {registerFile = (params: RegisterFileWorkParams): Promise<WorkItem> =>registerFileWork(this.ctx, params);+ registerArtboard = (params: RegisterArtboardWorkParams): Promise<WorkItem> =>+ registerArtboardWork(this.ctx, params);++ findArtboardWork = (artboardId: string) => findArtboardWork(this.ctx, artboardId);++ findArtboardWorkByWorkId = (workId: string) => findArtboardWorkByWorkId(this.ctx, workId);++ recordArtboardPublish = (+ artboardId: string,+ params: ArtboardWorkPublishMetadata & { url: string },+ ): Promise<WorkItem | null> => recordArtboardPublish(this.ctx, artboardId, params);++ clearArtboardPublish = (artboardId: string): Promise<WorkItem | null> =>+ clearArtboardPublish(this.ctx, artboardId);++ findArtboardIdsByDeploymentIds = (deploymentIds: string[]) =>+ findArtboardIdsByDeploymentIds(this.ctx, deploymentIds);+registerCanvas = (params: RegisterCanvasWorkParams): Promise<WorkItem> =>registerCanvasWork(this.ctx, params);@@ -127,6 +158,12 @@ export class WorkModel {findCanvasIdByWorkId = (workId: string) => findCanvasIdByWorkId(this.ctx, workId);+ findCanvasVersionId = (canvasId: string, version: number) =>+ findCanvasVersionId(this.ctx, canvasId, version);++ findCanvasSourcesByVersionIds = (versionIds: string[]) =>+ findCanvasSourcesByVersionIds(this.ctx, versionIds);+findCanvasIdsByDeploymentIds = (deploymentIds: string[]) =>findCanvasIdsByDeploymentIds(this.ctx, deploymentIds);@@ -199,6 +236,10 @@ export class WorkModel {return this.registerExternal({ ...operation.params, toolIdentifier });};+ registerShellArtboardResult = (+ params: SkillToolResultWorkInput & { toolIdentifier: string },+ ): Promise<WorkItem | null> => registerShellArtboardResult(this.ctx, params);+/*** Hand a just-registered `github_pull_request` Work to the provider row,* when one exists in the Work's own scope. Share-visitor registrations stay@@ -241,12 +282,14 @@ export class WorkModel {writes.setTaskWorksVisibility(this.ctx, taskIds, visibility);listByRootOperation = (params: {+ includeArtboardWorks?: boolean;includeFileWorks?: boolean;limit?: number;rootOperationId?: string | null;}) => queries.listByRootOperation(this.ctx, params);listByRootOperations = (params: {+ includeArtboardWorks?: boolean;includeFileWorks?: boolean;limit?: number;rootOperationIds?: string[] | null;@@ -256,12 +299,14 @@ export class WorkModel {listSummariesByIds = (workIds: string[]) => queries.listSummariesByIds(this.ctx, workIds);listSummariesByRootOperations = (params: {+ includeArtboardWorks?: boolean;includeFileWorks?: boolean;limit?: number;rootOperationIds?: string[] | null;}) => queries.listSummariesByRootOperations(this.ctx, params);listByConversation = (params: {+ includeArtboardWorks?: boolean;includeFileWorks?: boolean;limit?: number;threadId?: string | null;diff --git a/packages/database/src/models/work/internal.ts b/packages/database/src/models/work/internal.tsindex 959fa350cf5..e4192fa6ad3 100644--- a/packages/database/src/models/work/internal.ts+++ b/packages/database/src/models/work/internal.ts@@ -15,6 +15,7 @@ import type { SQL } from 'drizzle-orm';import { and, desc, eq, sql } from 'drizzle-orm';import { alias } from 'drizzle-orm/pg-core';+import { artboards } from '../../schemas/artboard';import { documents, files } from '../../schemas/file';import { tasks } from '../../schemas/task';import { works, workVersions } from '../../schemas/work';@@ -186,7 +187,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 = 'canvas' | 'document' | 'external' | 'file';+export type DisplayWorkType = 'artboard' | 'canvas' | 'document' | 'external' | 'file';/** Version-event row for display-backed types (each mutation event). */export interface DisplayVersionEventRow {@@ -283,6 +284,7 @@ export const resourceDeletedField = sql<boolean>`case ${works.resourceType} when*/export const resourceLiveFilter = sql<boolean>`case ${works.resourceType}when 'task' then ${tasks.id} is not null+ when 'artboard' then exists (select 1 from ${artboards} where ${artboards.id} = ${works.resourceId})when 'document' then ${documents.id} is not null and ${documents.isDeleted} is not truewhen 'file' then coalesce(${currentVersions.metadata} ->> 'fileId', '') = '' or exists (select 1 from ${files}diff --git a/packages/database/src/models/work/queries.ts b/packages/database/src/models/work/queries.tsindex 9dc40daddb8..5bf5c220cce 100644--- a/packages/database/src/models/work/queries.ts+++ b/packages/database/src/models/work/queries.ts@@ -54,7 +54,8 @@ const MAX_SUMMARY_ROW_LIMIT = 1000;export const listByRootOperation = async (ctx: WorkContext,params: {- /** Opt-in gate for the `file` work type; see {@link resolveAllowedWorkTypes}. */+ /** Opt-in gates for newer work types; see {@link resolveAllowedWorkTypes}. */+ includeArtboardWorks?: boolean;includeFileWorks?: boolean;limit?: number;rootOperationId?: string | null;@@ -63,6 +64,7 @@ export const listByRootOperation = async (if (!params.rootOperationId) return [];const map = await listByRootOperations(ctx, {+ includeArtboardWorks: params.includeArtboardWorks,includeFileWorks: params.includeFileWorks,limit: params.limit,rootOperationIds: [params.rootOperationId],@@ -75,7 +77,8 @@ export const listByRootOperation = async (export const listByRootOperations = async (ctx: WorkContext,params: {- /** Opt-in gate for the `file` work type; see {@link resolveAllowedWorkTypes}. */+ /** Opt-in gates for newer work types; see {@link resolveAllowedWorkTypes}. */+ includeArtboardWorks?: boolean;includeFileWorks?: boolean;limit?: number;rootOperationIds?: string[] | null;@@ -97,7 +100,7 @@ export const listByRootOperations = async (const filters = [inArray(workVersions.rootOperationId, rootOperationIds)];const rowLimit = Math.min(rootOperationIds.length * limit, MAX_SUMMARY_ROW_LIMIT);const itemsByType = await Promise.all(- resolveWorkTypeAdapters(params.includeFileWorks).map((adapter) =>+ resolveWorkTypeAdapters(params).map((adapter) =>adapter.listVersionEvents(ctx, filters, rowLimit),),);@@ -167,7 +170,8 @@ export const listSummariesByIds = async (export const listSummariesByRootOperations = async (ctx: WorkContext,params: {- /** Opt-in gate for the `file` work type; see {@link resolveAllowedWorkTypes}. */+ /** Opt-in gates for newer work types; see {@link resolveAllowedWorkTypes}. */+ includeArtboardWorks?: boolean;includeFileWorks?: boolean;limit?: number;rootOperationIds?: string[] | null;@@ -201,7 +205,7 @@ export const listSummariesByRootOperations = async (.where(and(inArray(workVersions.rootOperationId, rootOperationIds),- inArray(works.type, resolveAllowedWorkTypes(params.includeFileWorks)),+ inArray(works.type, resolveAllowedWorkTypes(params)),),).orderBy(desc(workVersions.createdAt))@@ -231,7 +235,8 @@ export const listSummariesByRootOperations = async (export const listByConversation = async (ctx: WorkContext,params: {- /** Opt-in gate for the `file` work type; see {@link resolveAllowedWorkTypes}. */+ /** Opt-in gates for newer work types; see {@link resolveAllowedWorkTypes}. */+ includeArtboardWorks?: boolean;includeFileWorks?: boolean;limit?: number;threadId?: string | null;@@ -246,7 +251,7 @@ export const listByConversation = async (: isNull(workVersions.threadId);const rowsByType = await Promise.all(- resolveWorkTypeAdapters(params.includeFileWorks).map((adapter) =>+ resolveWorkTypeAdapters(params).map((adapter) =>adapter.listConversationRows(ctx, {rowLimit: limit * WORK_TYPE_COUNT,threadFilter,@@ -290,7 +295,8 @@ const WORKSPACE_WORK_LIMIT = 30;export interface ListByWorkspaceParams {cursor?: string | null;- /** Opt-in gate for the `file` work type; see {@link resolveAllowedWorkTypes}. */+ /** Opt-in gates for newer work types; see {@link resolveAllowedWorkTypes}. */+ includeArtboardWorks?: boolean;includeFileWorks?: boolean;limit?: number;/** Narrow results to Works first produced by one agent. */@@ -350,7 +356,7 @@ export const listByWorkspace = async (workOwnership(ctx),// Row-level gate: un-opted-in requests never see `file` works, even in the// combined (no `type`) view (see resolveAllowedWorkTypes).- inArray(works.type, resolveAllowedWorkTypes(params.includeFileWorks)),+ inArray(works.type, resolveAllowedWorkTypes(params)),// Orphaned Works (backing resource deleted or trashed) are hidden here// rather than shown as dead cards; see resourceLiveFilter.resourceLiveFilter,diff --git a/packages/database/src/models/work/registry.ts b/packages/database/src/models/work/registry.tsindex 0db3211849d..0ab4eed34e3 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 { artboardWorkAdapter } from './artboard';import { canvasWorkAdapter } from './canvas';import { documentWorkAdapter } from './document';import { externalWorkAdapter } from './external';@@ -15,6 +16,7 @@ import { taskWorkAdapter } from './task';* set) plus its type unions in `@lobechat/types`.*/export const WORK_TYPE_ADAPTERS = {+ artboard: artboardWorkAdapter,canvas: canvasWorkAdapter,document: documentWorkAdapter,external: externalWorkAdapter,@@ -45,18 +47,36 @@ export const workTypeAdapters = WORK_TYPES.map(*/const OPT_IN_WORK_TYPES = new Set<WorkType>(['canvas', 'file']);+/**+ * `artboard` shipped after clients already sent `includeFileWorks`, so it needs+ * its own declaration: a client that opted into `file` still has no artboard+ * descriptor and would throw on it the same way.+ */+const ARTBOARD_OPT_IN_WORK_TYPES = new Set<WorkType>(['artboard']);++export interface WorkTypeOptIn {+ includeArtboardWorks?: boolean;+ includeFileWorks?: boolean;+}+/** 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));+export const LEGACY_WORK_TYPES = WORK_TYPES.filter(+ (type) => !OPT_IN_WORK_TYPES.has(type) && !ARTBOARD_OPT_IN_WORK_TYPES.has(type),+);/*** Resolve the Work types a read request may return. Absent opt-in → the legacy- * set (the read-path chokepoint that preserves old clients); opt-in → every- * registered type. Used both for SQL row-level gating and to derive the adapter- * fan-out below.+ * set (the read-path chokepoint that preserves old clients); each opt-in adds+ * only the types it declares. Used both for SQL row-level gating and to derive+ * the adapter fan-out below.*/-export const resolveAllowedWorkTypes = (includeFileWorks?: boolean): WorkType[] =>- includeFileWorks ? WORK_TYPES : LEGACY_WORK_TYPES;+export const resolveAllowedWorkTypes = (optIn: WorkTypeOptIn = {}): WorkType[] =>+ WORK_TYPES.filter(+ (type) =>+ (!OPT_IN_WORK_TYPES.has(type) || optIn.includeFileWorks) &&+ (!ARTBOARD_OPT_IN_WORK_TYPES.has(type) || optIn.includeArtboardWorks),+ );/** Adapter fan-out list narrowed to the types the request is allowed to return. */-export const resolveWorkTypeAdapters = (includeFileWorks?: boolean): WorkTypeAdapter[] =>- resolveAllowedWorkTypes(includeFileWorks).map((type) => WORK_TYPE_ADAPTERS[type]);+export const resolveWorkTypeAdapters = (optIn: WorkTypeOptIn = {}): WorkTypeAdapter[] =>+ resolveAllowedWorkTypes(optIn).map((type) => WORK_TYPE_ADAPTERS[type]);diff --git a/packages/heterogeneous-agents/src/protocol/lobeHubCliGuide.ts b/packages/heterogeneous-agents/src/protocol/lobeHubCliGuide.tsindex aabba54a9a2..262a3feaa41 100644--- a/packages/heterogeneous-agents/src/protocol/lobeHubCliGuide.ts+++ b/packages/heterogeneous-agents/src/protocol/lobeHubCliGuide.ts@@ -79,7 +79,7 @@ export const LOBEHUB_CLI_GUIDE_CONTEXT = 'lobehub-cli-guide';* deliberately, says what is not one.*/export const lobeHubCliSkillDescription =- "Reach the user's LobeHub — the app this conversation runs in — through the preinstalled `lh` CLI. Use when the request concerns LobeHub itself: its documents, knowledge bases, files, memory, earlier conversations (topic ids start with `tpc_`, or a `<refer_topic>` tag), agents and your own agent configuration, tasks, projects, widgets, bots, models, providers, plugins or skills, or generating images, video or speech there. Not needed for ordinary work on local files or other tools.";+ "Reach the user's LobeHub — the app this conversation runs in — through the preinstalled `lh` CLI. Use when the request concerns LobeHub itself: its documents, knowledge bases, files, memory, earlier conversations (topic ids start with `tpc_`, or a `<refer_topic>` tag), agents and your own agent configuration, tasks, projects, artboards, widgets, bots, models, providers, plugins or skills, or generating images, video or speech there. Not needed for ordinary work on local files or other tools.";const lobeHubCliGuideBody = ["You are running inside a LobeHub conversation, on a machine where the `lh` CLI is already installed and the run normally carries the user's credentials in its environment. Never install, upgrade or replace `lh` globally — that binary may be the one running `lh connect`, which is executing you — and never run `lh login`.",@@ -90,7 +90,7 @@ const lobeHubCliGuideBody = ['- **Talking to another conversation:** `lh topic send <tpc_id> -c "…"` delivers a message to that conversation and has its agent act on it (queued behind its current turn if it is busy). To hand work to a fresh conversation instead, `lh topic send --new -c "…"` opens one for you (or `--agent-id` another agent), optionally on a given machine with `--device <id|local>` and named with `--title`; it is linked to this conversation as its parent (`--parent-topic-id <tpc_id>` names another, `--detach` links none), and `lh topic list --opened-by-me` lists the ones you opened; `lh topic stop <tpc_id>` stops a topic\'s running turn and `lh topic archive <tpc_id>` archives it; `lh message send -c "…"` is the same thing spelled message-first: without `--topic-id` it opens a new conversation, with `--topic-id <tpc_id>` it sends to that one. Prefer these over `lh agent run` for handing off work. `lh message create` only writes a row — nobody sees or answers it. A message another agent sent you starts with an `<agent_sender>` header; answer it with `lh message reply <message_id> -c "…"`, which wakes the sender\'s conversation. Your ordinary response is not delivered to that agent.','- **If `lh` is too old** — `lh man` lacks a command you expect, or `lh` reports an unknown command or option — the shell may have found a stale global install first. When `LOBEHUB_CLI` is set it is the path of the CLI this app ships — run that path instead of `lh` for the rest of the session. Otherwise, or if that one is too old as well, run the latest CLI once without installing it: `pnpm --package @lobehub/cli@latest dlx lh …` (or `npx -y -p @lobehub/cli@latest lh …`). It reads the same environment and saved login as `lh`. If the user asks you to run `lh` this way, do so.','- **Look commands up, do not guess them.** `lh man` lists every command, and `lh man <command>` (e.g. `lh man doc create`) prints the manual for the CLI actually installed here, including exactly which flags that command takes. Many commands offer `--json` for structured output, but not all of them — the manual is what says so, and an invented flag just fails the call.',- '- **What it reaches:** `lh kb` knowledge bases · `lh doc` documents · `lh file` files · `lh artifact` artifacts · `lh topic` / `lh message` past conversations · `lh agent` agents · `lh task` / `lh project` work · `lh widget` / `lh dashboard` monitoring widgets and dashboards · `lh search` local resources and the web · `lh recall` past messages, topics, goals and pages in a time window · `lh gen` text/image/video/TTS/ASR generation · `lh memory` user memory · `lh notify` notifications to the user · `lh model` / `lh provider` / `lh legacy-plugin` / `lh skill` platform configuration · `lh bot` chat-platform bots.',+ '- **What it reaches:** `lh kb` knowledge bases · `lh doc` documents · `lh file` files · `lh artifact` artifacts · `lh topic` / `lh message` past conversations · `lh agent` agents · `lh task` / `lh project` work · `lh artboard` the requirement artboard of a project (boards, flows and choices the user answers on the canvas) · `lh widget` / `lh dashboard` monitoring widgets and dashboards · `lh search` local resources and the web · `lh recall` past messages, topics, goals and pages in a time window · `lh gen` text/image/video/TTS/ASR generation · `lh memory` user memory · `lh notify` notifications to the user · `lh model` / `lh provider` / `lh legacy-plugin` / `lh skill` platform configuration · `lh bot` chat-platform bots.',"- **Widgets run code with the user's credentials.** Before `lh widget dry-run` of a draft that declares connector credentials (`manifest.env`) or network hosts (`manifest.network.allow`), show the user that version id, what the script does and which credentials and hosts it uses, and wait for their explicit approval of that exact version before passing `--version <id> --yes`. Never publish (`lh widget publish`) without the user's confirmation.",'- **If a command fails with an authentication or permission error**, tell the user what you were trying to do — do not work around it.','- **Leave these alone:** `lh hetero` and `lh connect` run the infrastructure that is executing you. And never change the persistent workspace scope with `lh workspace use` — it silently rewrites the target of every later command on this machine.',diff --git a/packages/locales/src/default/agent.ts b/packages/locales/src/default/agent.tsindex 9f08185784b..5b3c281c937 100644--- a/packages/locales/src/default/agent.ts+++ b/packages/locales/src/default/agent.ts@@ -1272,6 +1272,7 @@ export default {'share.visitor.profile.works.desc': 'Selected by the creator. See what this agent can deliver.','share.visitor.profile.works.untitled': 'Untitled work','share.visitor.profile.works.open': 'Open work',+ 'share.visitor.profile.works.type.artboard': 'Artboard','share.visitor.profile.works.type.canvas': 'Canvas','share.visitor.profile.works.type.document': 'Document','share.visitor.profile.works.type.task': 'Task',diff --git a/packages/locales/src/default/file.ts b/packages/locales/src/default/file.tsindex 013506ff30d..4e434c629ca 100644--- a/packages/locales/src/default/file.ts+++ b/packages/locales/src/default/file.ts@@ -114,6 +114,7 @@ export default {'docs.shared.title': 'Shared docs','docs.viewAllPages': 'View all','docs.works.all': 'All',+ 'docs.works.artboard': 'Artboard','docs.works.canvas': 'Canvas','docs.works.document': 'Documents','docs.works.task': 'Tasks',@@ -602,6 +603,7 @@ export default {'work.loadErrorTitle': 'Couldn’t load works','work.loadMoreError': 'Failed to load more works.','work.retry': 'Retry',+ 'work.type.artboard': 'Artboard','work.type.canvas': 'Canvas','work.type.document': 'Document','work.type.file': 'File',diff --git a/packages/locales/src/default/plugin.ts b/packages/locales/src/default/plugin.tsindex dc5eb7b4e76..45c378f424d 100644--- a/packages/locales/src/default/plugin.ts+++ b/packages/locales/src/default/plugin.ts@@ -789,6 +789,17 @@ export default {'builtins.lobe-skills.apiName.activateProjectSkill': 'Activate Project Skill','builtins.lobe-skills.apiName.searchSkill': 'Search Skills','builtins.lobe-skills.title': 'Skills',+ 'builtins.builtin-artboard.apiName.askArtboardQuestion': 'Ask on artboard',+ 'builtins.builtin-artboard.apiName.createArtboard': 'Create artboard',+ 'builtins.builtin-artboard.apiName.listArtboardComments': 'Read artboard comments',+ 'builtins.builtin-artboard.apiName.listArtboards': 'List artboards',+ 'builtins.builtin-artboard.apiName.readArtboard': 'Read artboard',+ 'builtins.builtin-artboard.apiName.readArtboardFile': 'Read artboard file',+ 'builtins.builtin-artboard.apiName.replyArtboardComment': 'Reply to artboard comment',+ 'builtins.builtin-artboard.apiName.resolveArtboardComment': 'Resolve artboard comment',+ 'builtins.builtin-artboard.apiName.updateArtboard': 'Update artboard',+ 'builtins.builtin-artboard.apiName.writeArtboardFiles': 'Save artboard files',+ 'builtins.builtin-artboard.title': 'Artboard','builtins.lobe-canvas.apiName.createCanvas': 'Create canvas','builtins.lobe-canvas.apiName.listCanvases': 'List canvases','builtins.lobe-canvas.apiName.readCanvas': 'Read canvas',diff --git a/packages/locales/src/default/project.ts b/packages/locales/src/default/project.tsindex 56feef58f5d..4d2fb6524d7 100644--- a/packages/locales/src/default/project.ts+++ b/packages/locales/src/default/project.ts@@ -501,6 +501,185 @@ export default {'onboarding.connect.goal.title': 'Goals','onboarding.connect.goal.description': 'Set a goal you can sign off','onboarding.connect.goal.count': '{{count}} set',+ 'artboard.card.openBoard': 'Open board',+ 'artboard.card.summary': '{{groups}} groups · {{boards}} screens',+ 'artboard.card.updated': 'Board updated · revision {{revision}}',+ 'artboard.chat.quote': 'Re: {{target}}',+ 'artboard.compare.design': 'Design',+ 'artboard.compare.real': 'Screenshot',+ 'artboard.compare.split': 'Side by side',+ 'artboard.empty.desc': 'Describe what you want in chat, and the agent lays out the screens here.',+ 'artboard.empty.title': 'No board yet',+ 'artboard.error.desc': 'Check your connection and try again.',+ 'artboard.error.retry': 'Retry',+ 'artboard.error.title': 'Couldn’t load the board',+ 'artboard.finalize.blocked': '{{count}} still open',+ 'artboard.finalize.cancel': 'Cancel',+ 'artboard.finalize.checksTitle': '{{count}} acceptance checks will be generated',+ 'artboard.finalize.confirm': 'Finalize and generate acceptance',+ 'artboard.finalize.lockNote':+ 'After finalizing, the user journey is locked as the acceptance reference. Later edits are recorded as changes.',+ 'artboard.finalize.missingCheck': 'No acceptance check written for this screen yet',+ 'artboard.finalize.pending.answered':+ 'You answered. The agent closes this once it reads your answer, or you can close it yourself.',+ 'artboard.finalize.pending.question': 'The agent is waiting for your answer.',+ 'artboard.finalize.pending.round': 'This choice has not been submitted yet.',+ 'artboard.finalize.pendingTitle_one': '{{count}} open item to settle first',+ 'artboard.finalize.pendingTitle_other': '{{count}} open items to settle first',+ 'artboard.finalize.success': 'Finalized. {{count}} acceptance checks generated.',+ 'artboard.finalize.title': 'Finalize the board',+ 'artboard.board.decision': 'Decision',+ 'artboard.board.fileMissing': 'File not found: {{path}}',+ 'artboard.board.generating': 'Writing this board…',+ 'artboard.board.image': 'Image',+ 'artboard.board.locked': 'Finalized',+ 'artboard.board.sourceMissing': 'Source unavailable',+ 'artboard.board.recommended': 'Recommended',+ 'artboard.group.lockedDesc': 'Finalized · changes are recorded as revisions',+ 'artboard.group.verifyDesc': 'Screenshots from the latest check',+ 'artboard.header.discuss': 'Discuss',+ 'artboard.header.finalize': 'Finalize',+ 'artboard.header.finalizePending': 'Finalize · {{count}} open',+ 'artboard.header.finalizeShort': 'Finalize',+ 'artboard.header.finalized': 'Finalized',+ 'artboard.header.outline': 'Outline',+ 'artboard.header.phaseDraft': 'Discussing',+ 'artboard.header.phaseFinalized': 'Finalized',+ 'artboard.header.title': 'Artboard',+ 'artboard.header.verify': 'Accept',+ 'artboard.header.verifyLocked': 'Available after finalizing',+ 'artboard.header.verifyPanel': 'Acceptance panel',+ 'artboard.share.confirmTitle': 'Before you share this artboard',+ 'artboard.share.copied': 'Link copied',+ 'artboard.share.copy': 'Copy link',+ 'artboard.share.failed': 'Couldn’t share. Try again.',+ 'artboard.share.note': 'Later changes stay private until you update the share.',+ 'artboard.share.notShared': 'This artboard isn’t shared publicly',+ 'artboard.share.open': 'Open share link',+ 'artboard.share.privacy':+ 'Anyone with the link can view this artboard: its pages, boards, connections and chosen options. Comments and acceptance results stay private.',+ 'artboard.share.publish': 'Share',+ 'artboard.share.sharing': 'Sharing…',+ 'artboard.share.trigger': 'Share',+ 'artboard.share.unpublish': 'Stop sharing',+ 'artboard.share.unpublishConfirm': 'The link will stop working for everyone who has it.',+ 'artboard.share.unpublished': 'Sharing stopped',+ 'artboard.share.unpublishFailed': 'Couldn’t stop sharing. Try again.',+ 'artboard.share.update': 'Update share',+ 'artboard.outline.title': 'Outline',+ 'artboard.selection.discuss': 'Quote in chat',+ 'artboard.selection.view': 'View larger',+ 'artboard.title': 'Artboard',+ 'artboard.verify.accept': 'Accept',+ 'artboard.verify.acceptAll': 'Accept all {{count}}',+ 'artboard.verify.acceptAllHint': 'or open one to confirm it',+ 'artboard.verify.accepted': '{{id}} accepted',+ 'artboard.verify.acceptedAll': '{{count}} checks accepted',+ 'artboard.verify.back': 'All checks',+ 'artboard.verify.close': 'Close acceptance',+ 'artboard.verify.detailTitle': 'Acceptance check',+ 'artboard.verify.entry': 'Entry screen',+ 'artboard.verify.evidence': 'Evidence',+ 'artboard.verify.evidenceCount': '{{count}} screenshots',+ 'artboard.verify.expected': 'Expected',+ 'artboard.verify.finalizedReference': 'Finalized reference',+ 'artboard.verify.flowLink': 'Flow chart',+ 'artboard.verify.next': 'Next check',+ 'artboard.verify.nextHint': 'Accepting moves to the next check',+ 'artboard.verify.noShot': 'No screenshot yet',+ 'artboard.verify.observation': 'Agent observed: {{text}}',+ 'artboard.verify.observed': 'Observed',+ 'artboard.verify.openDesign': 'Open the design',+ 'artboard.verify.path': 'Path',+ 'artboard.verify.paths': 'How users get here',+ 'artboard.verify.prev': 'Previous check',+ 'artboard.verify.realShot': 'Real screenshot',+ 'artboard.verify.reject': 'Disagree, re-check',+ 'artboard.verify.rejectFailed': 'Send back',+ 'artboard.verify.rejected': '{{id}} sent back',+ 'artboard.verify.rejectedTag': 'Sent back',+ 'artboard.verify.reviewAccepted': 'Accepted',+ 'artboard.verify.reviewRejected': 'Sent back for another round',+ 'artboard.verify.reviewTitle': 'Your call',+ 'artboard.verify.reviewedTag': 'Accepted',+ 'artboard.verify.summary': 'Checked {{checked}} of {{total}} screens',+ 'artboard.verify.summaryBlocked': '{{count}} could not be checked',+ 'artboard.verify.summaryFailed': '{{count}} did not match',+ 'artboard.verify.title': 'Acceptance',+ 'artboard.verify.waiting':+ 'Waiting for development. Results appear here when the build is ready.',+ 'artboard.verifyBar.board': 'Board',+ 'artboard.verifyBar.list': 'List',+ 'artboard.verifyList.check': 'Check',+ 'artboard.verifyList.design': 'Design',+ 'artboard.zoom.actual': 'Zoom to 100%',+ 'artboard.zoom.fit': 'Fit to screen',+ 'artboard.zoom.in': 'Zoom in',+ 'artboard.zoom.out': 'Zoom out',+ 'artboard.chat.noInput': 'Open the conversation to add this to a message',+ 'artboard.finalize.issue.empty_journey': 'The journey has no screens yet',+ 'artboard.finalize.issue.entry_count': 'The journey needs exactly one starting screen',+ 'artboard.finalize.issue.multiple_journeys': 'Keep a single journey group',+ 'artboard.finalize.issue.no_journey': 'Add a journey group first',+ 'artboard.finalize.issue.unreachable': '“{{title}}” can’t be reached from the starting screen',+ 'artboard.finalize.message': 'Finalized “{{title}}”: {{count}} acceptance checks generated.',+ 'artboard.finalize.openAcceptance': 'Open acceptance',+ 'artboard.fullscreen.placeholder': 'The board is open full screen',+ 'artboard.header.exitFullscreen': 'Back to panel',+ 'artboard.header.fullscreen': 'Full screen',+ 'artboard.stale.refresh': 'Refresh',+ 'artboard.stale.title': 'This board has a newer version',+ 'artboard.gallery.openConversation': 'Open conversation',+ 'artboard.finalize.pending.goChoose': 'Go to the choice',+ 'artboard.finalize.pending.goAnswer': 'Answer',+ 'artboard.finalize.pending.view': 'View',+ 'artboard.header.noTask': 'This artboard has no task, so it can’t be finalized',+ 'artboard.header.questions_one': '{{count}} question to answer',+ 'artboard.header.questions_other': '{{count}} questions to answer',+ 'artboard.tool.select': 'Select',+ 'artboard.tool.comment': 'Comment',+ 'artboard.pages.title': 'Pages',+ 'artboard.group.choose': 'Options · pick one',+ 'artboard.submit.title_one': '{{count}} question in this batch',+ 'artboard.submit.title_other': '{{count}} questions in this batch',+ 'artboard.submit.status': '{{picked}} picked, {{rest}} by recommendation',+ 'artboard.submit.allPicked': '{{picked}} picked',+ 'artboard.submit.undecided_one': '{{count}} still unpicked',+ 'artboard.submit.undecided_other': '{{count}} still unpicked',+ 'artboard.submit.action': 'Submit to agent',+ 'artboard.submit.message_one': 'Submitted {{count}} choice on the artboard.',+ 'artboard.submit.message_other': 'Submitted {{count}} choices on the artboard.',+ 'artboard.submit.noConversation':+ 'Choices submitted. This artboard has no conversation, so the agent will see them the next time it reads the artboard.',+ 'artboard.submit.messageFailed': 'Saved, but the message to the agent wasn’t sent.',+ 'artboard.submit.commentMessage_one': 'Left {{count}} comment on the artboard.',+ 'artboard.submit.commentMessage_other': 'Left {{count}} comments on the artboard.',+ 'artboard.submit.comments_one': '{{count}} comment',+ 'artboard.submit.comments_other': '{{count}} comments',+ 'artboard.submit.commentsTitle_one': '{{count}} comment to send',+ 'artboard.submit.commentsTitle_other': '{{count}} comments to send',+ 'artboard.submit.resend': 'Send again',+ 'artboard.submit.failed': 'Couldn’t submit the choices',+ 'artboard.comment.placeholder': 'Add a comment…',+ 'artboard.comment.reply': 'Reply…',+ 'artboard.comment.send': 'Add',+ 'artboard.comment.sendHint': '{{mod}} ↵ to add · Esc to cancel',+ 'artboard.comment.sendNow': 'Send now',+ 'artboard.comment.resolve': 'Resolve',+ 'artboard.comment.reopen': 'Reopen',+ 'artboard.comment.resolved': 'Resolved',+ 'artboard.comment.unread': 'Not sent',+ 'artboard.comment.stale': 'Screen changed since',+ 'artboard.comment.onCanvas': 'Canvas',+ 'artboard.comment.agent': 'Agent',+ 'artboard.comment.you': 'You',+ 'artboard.comment.member': 'Member',+ 'artboard.comment.failed': 'Couldn’t save the comment',+ 'artboard.question.waiting': 'Waiting for your answer',+ 'artboard.question.answered': 'Answered',+ 'artboard.question.placeholder': 'Answer this question…',+ 'artboard.question.answer': 'Answer',+ 'artboard.question.hint': 'Your answer goes to the agent with the next send.','environment.configure': 'Configure environment','settings.environmentIntro':'Every conversation in this project runs in this environment: its repositories are cloned, the setup command runs, and its variables are set.',diff --git a/packages/openapi/openapi.yml b/packages/openapi/openapi.ymlindex 7b414b17e17..5c54726f1cf 100644--- a/packages/openapi/openapi.yml+++ b/packages/openapi/openapi.yml@@ -3462,6 +3462,7 @@ components:resourceType:type: stringenum:+ - artboard- canvas- document- github_issue@@ -3482,6 +3483,7 @@ components:type:type: stringenum:+ - artboard- canvas- document- externaldiff --git a/packages/openapi/src/types/goal.type.ts b/packages/openapi/src/types/goal.type.tsindex f31d05fbd78..b101aff9fa0 100644--- a/packages/openapi/src/types/goal.type.ts+++ b/packages/openapi/src/types/goal.type.ts@@ -233,6 +233,7 @@ const GoalNodeWorkVersionRelationSchema = unionEnum<GoalNodeWorkVersionRelation>'contradicts',]);const WorkTypeSchema = unionEnum<WorkType>()([+ 'artboard','canvas','document','external',@@ -241,6 +242,7 @@ const WorkTypeSchema = unionEnum<WorkType>()(['task',]);const WorkResourceTypeSchema = unionEnum<WorkResourceType>()([+ 'artboard','canvas','document','github_issue',diff --git a/packages/trpc/src/client/lambda.ts b/packages/trpc/src/client/lambda.tsindex 065d5980a0c..5373d1bdcac 100644--- a/packages/trpc/src/client/lambda.ts+++ b/packages/trpc/src/client/lambda.ts@@ -209,6 +209,11 @@ const linkOptions = {const { getBusinessTrpcHeaders } = await import('@/business/client/trpc-headers');Object.assign(headers as Record<string, string>, await getBusinessTrpcHeaders());+ // Mutation responses carry message lists too; without this they would drop+ // the Work types this client renders and wipe their cards from the store.+ const { workTypeOptInHeaders } = await import('@/services/workTypeOptIn');+ Object.assign(headers as Record<string, string>, workTypeOptInHeaders());+log('Headers: %O', headers);return headers;},diff --git a/packages/trpc/src/lambda/context.test.ts b/packages/trpc/src/lambda/context.test.tsindex 38e6c1264eb..4b7d89c6163 100644--- a/packages/trpc/src/lambda/context.test.ts+++ b/packages/trpc/src/lambda/context.test.ts@@ -236,6 +236,22 @@ describe('createLambdaContext', () => {});});+ it('reads the Work types the client renders', async () => {+ const request = new NextRequest('https://example.com/trpc/lambda', {+ headers: { 'x-lobe-work-types': 'artboard,file' },+ });++ const context = await createLambdaContext(request);++ expect(context.workTypeOptIn).toEqual({ includeArtboardWorks: true, includeFileWorks: true });+ });++ it('leaves the Work opt-in empty when the client sent none', async () => {+ const context = await createLambdaContext(new NextRequest('https://example.com/trpc/lambda'));++ expect(context.workTypeOptIn).toEqual({});+ });+it('should carry the one-shot relay headers of the requesting tab', async () => {const channel = 'llmcall:user-1:0b7c1d2e-aaaa';const request = new NextRequest('https://example.com/trpc/lambda', {diff --git a/packages/trpc/src/lambda/context.ts b/packages/trpc/src/lambda/context.tsindex 3da9d4534f6..e1c2b6f9eda 100644--- a/packages/trpc/src/lambda/context.ts+++ b/packages/trpc/src/lambda/context.ts@@ -1,3 +1,4 @@+import { WORK_TYPES_HEADER } from '@lobechat/const';import { type Context as OtContext } from '@lobechat/observability-otel/api';import { type ClientSecretPayload, type SpendOrigin } from '@lobechat/types';import type { ClientMetadata } from '@lobechat/utils/server';@@ -10,6 +11,7 @@ import { auth } from '@/auth';import { canUseWorkspaceApiKeys } from '@/business/server/workspaceApiKey';import { getServerDB } from '@/database/core/db-adaptor';import { ApiKeyModel } from '@/database/models/apiKey';+import type { WorkTypeOptIn } from '@/database/models/work/registry';import { hasActiveWorkspaceMembership } from '@/database/models/workspace';import { normalizeWorkspaceId } from '@/database/utils/workspace';import { authEnv, LOBE_CHAT_OIDC_AUTH_HEADER } from '@/envs/auth';@@ -140,8 +142,19 @@ export interface AuthContext {userAgent?: string;userId?: string | null;workspaceId?: string | null;+ workTypeOptIn?: WorkTypeOptIn;}+const readWorkTypeOptIn = (headers: Headers): WorkTypeOptIn => {+ const types = new Set(+ (headers.get(WORK_TYPES_HEADER) ?? '').split(',').map((type) => type.trim()),+ );+ return {+ ...(types.has('artboard') && { includeArtboardWorks: true }),+ ...(types.has('file') && { includeFileWorks: true }),+ };+};+/*** Inner function for `createContext` where we create the context.* This is useful for testing when we don't want to mock Next.js' request/response@@ -162,6 +175,7 @@ export const createContextInner = async (params?: {traceContext?: OtContext;userAgent?: string;userId?: string | null;+ workTypeOptIn?: WorkTypeOptIn;workspaceId?: string | null;}): Promise<AuthContext> => {log('createContextInner called with params: %O', params);@@ -184,6 +198,7 @@ export const createContextInner = async (params?: {traceContext: params?.traceContext,userAgent: params?.userAgent,userId: params?.userId,+ workTypeOptIn: params?.workTypeOptIn ?? {},// A blank scope is not a workspace. Callers that "resolve" one (an empty// header, a blank env var, a `?? ''` on the way through) would otherwise// hand `''` to every model, and each write would fail on the `workspaces`@@ -201,6 +216,7 @@ export type LambdaContext = Awaited<ReturnType<typeof createContextInner>>;*/export const createLambdaContext = async (request: NextRequest): Promise<LambdaContext> => {const clientMetadata = parseClientMetadata(request.headers);+ const workTypeOptIn = readWorkTypeOptIn(request.headers);// we have a special header to debug the api endpoint in development mode// IT WON'T GO INTO PRODUCTION ANYMORE@@ -211,6 +227,7 @@ export const createLambdaContext = async (request: NextRequest): Promise<LambdaCreturn createContextInner({clientMetadata,userId: process.env.MOCK_DEV_USER_ID,+ workTypeOptIn,});}@@ -241,6 +258,7 @@ export const createLambdaContext = async (request: NextRequest): Promise<LambdaCllmRelay: isBatch ? undefined : readLlmRelayRequest(request.headers),marketAccessToken,userAgent,+ workTypeOptIn,workspaceId,};diff --git a/packages/types/src/artboard.test.ts b/packages/types/src/artboard.test.tsnew file mode 100644index 00000000000..51e68070df8--- /dev/null+++ b/packages/types/src/artboard.test.ts@@ -0,0 +1,156 @@+import { describe, expect, it } from 'vitest';++import {+ type ArtboardBoardView,+ type ArtboardContent,+ artboardOpSchema,+ formatArtboardResultLine,+ parseArtboardResultLine,+} from './artboard';+import { checkFinalizeReadiness } from './artboardReadiness';++const rect = { h: 400, w: 640, x: 0, y: 0 };++const board = (id: string, patch: Partial<ArtboardBoardView> = {}): ArtboardBoardView => ({+ expected: `sees ${id}`,+ flowNodeId: null,+ groupId: 'abg_journey',+ id,+ pageId: 'abp_1',+ rect,+ roundId: null,+ source: { canvasId: 'cvs_1', kind: 'canvas', version: 1 },+ title: id,+ type: 'html',+ ...patch,+});++const edge = (from: string, to: string) => ({+ condition: null,+ flowEdgeId: null,+ from,+ id: `${from}-${to}`,+ isDefault: false,+ label: 'next',+ to,+});++const content = (patch: Partial<ArtboardContent> = {}): ArtboardContent => ({+ boards: [board('b1'), board('b2')],+ edges: [edge('b1', 'b2')],+ groups: [{ desc: '', id: 'abg_journey', kind: 'journey', pageId: 'abp_1', rect, title: 'Flow' }],+ pages: [{ id: 'abp_1', name: 'Page 1', sortOrder: 0 }],+ questions: [],+ rounds: [],+ ...patch,+});++describe('artboardOpSchema', () => {+ it('accepts a board that shows a file of the artboard', () => {+ const op = {+ board: {+ groupId: 'g',+ source: { kind: 'file', path: 'pages/a.html' },+ title: 'A',+ x: 0,+ y: 0,+ },+ ref: 'a',+ type: 'addBoard',+ };+ expect(artboardOpSchema.parse(op)).toEqual(op);+ });++ it('rejects the Canvas source boards used to take', () => {+ const op = {+ board: { source: { canvasId: 'cvs_1', kind: 'canvas' }, title: 'A', x: 0, y: 0 },+ type: 'addBoard',+ };+ expect(artboardOpSchema.safeParse(op).success).toBe(false);+ });++ it('accepts a decision board without a source', () => {+ const op = { board: { title: 'Paid?', type: 'decision', x: 0, y: 0 }, type: 'addBoard' };+ expect(artboardOpSchema.safeParse(op).success).toBe(true);+ });++ it('rejects the frame and note ops of the JSON board', () => {+ for (const type of ['addFrame', 'addArrow', 'addNote', 'decideQuestion'])+ expect(artboardOpSchema.safeParse({ id: 'x', type }).success).toBe(false);+ });++ it('rejects moving a board to another page through updateBoard', () => {+ const parsed = artboardOpSchema.parse({+ id: 'b1',+ patch: { pageId: 'abp_2', title: 'A' },+ type: 'updateBoard',+ });+ expect(parsed).toEqual({ id: 'b1', patch: { title: 'A' }, type: 'updateBoard' });+ });+});++describe('artboard result line', () => {+ it('round-trips the id and revision', () => {+ const line = formatArtboardResultLine({+ boardCount: 3,+ groupCount: 2,+ id: 'art_1',+ revision: 7,+ });+ expect(parseArtboardResultLine(`ok\n${line}\n`)).toEqual({ artboardId: 'art_1', revision: 7 });+ });+});++describe('checkFinalizeReadiness', () => {+ it('passes a connected journey whose boards all have a check', () => {+ expect(checkFinalizeReadiness(content())).toEqual([]);+ });++ it('reports a journey board without a check, but not a decision board', () => {+ const issues = checkFinalizeReadiness(+ content({+ boards: [+ board('b1'),+ board('d1', { expected: null, source: null, type: 'decision' }),+ board('b2', { expected: ' ' }),+ ],+ edges: [edge('b1', 'd1'), edge('d1', 'b2')],+ }),+ );+ expect(issues).toEqual([{ boardId: 'b2', code: 'missing_check' }]);+ });++ it('reports a board no edge reaches', () => {+ const issues = checkFinalizeReadiness(+ content({ boards: [board('b1'), board('b2'), board('b3')], edges: [edge('b2', 'b3')] }),+ );+ expect(issues).toEqual([{ code: 'entry_count', entryBoardIds: ['b1', 'b2'] }]);+ });++ it('blocks on a round that is still open and on an unresolved agent question', () => {+ const issues = checkFinalizeReadiness(+ content({+ questions: [{ boardId: null, content: 'Skip?', groupId: null, id: 'c1', pageId: 'abp_1' }],+ rounds: [+ {+ batchId: null,+ chosenBoardId: null,+ id: 'r1',+ pageId: 'abp_1',+ recommendedBoardId: null,+ status: 'open',+ title: 'Layout',+ },+ ],+ }),+ );+ expect(issues).toEqual([+ { code: 'open_round', roundId: 'r1' },+ { code: 'open_question', commentId: 'c1' },+ ]);+ });++ it('reports a board with no journey group before anything else', () => {+ expect(checkFinalizeReadiness(content({ groups: [] }))[0]).toEqual({ code: 'no_journey' });+ });+});diff --git a/packages/types/src/artboard.ts b/packages/types/src/artboard.tsindex a1f6327478a..09fe003e126 100644--- a/packages/types/src/artboard.ts+++ b/packages/types/src/artboard.ts@@ -1,3 +1,5 @@+import { z } from 'zod';+export const ARTBOARD_PHASES = ['discuss', 'finalized'] as const;export type ArtboardPhase = (typeof ARTBOARD_PHASES)[number];@@ -22,6 +24,8 @@ export interface ArtboardRect {}export type ArtboardCommentAnchor =+ // With a board: fractions (0–1) of the board. With a group only: pixels from the group's+ // top-left. With neither: page coordinates.| { type: 'canvas'; x: number; y: number }// offsetX / offsetY are fractions (0–1) of the hit element's width and height.| { nodePath: string; offsetX: number; offsetY: number; type: 'node' };@@ -35,4 +39,227 @@ export interface ArtboardRoundMetadata {}export interface ArtboardGroupMetadata {}export interface ArtboardBoardMetadata {}-export interface ArtboardCommentMetadata {}+export interface ArtboardCommentMetadata {+ anchorSpace?: 'board' | 'group' | 'page';+ sourceHash?: string;+}++export const ARTBOARD_BOARD_SIZE = { height: 400, width: 640 } as const;++const text = z.string();+const coordinate = z.number().finite();+const size = z.number().finite().positive();++export const artboardBoardSourceSchema = z.object({+ /** Version tag of the file (its object ETag); null while the file does not exist. */+ hash: z.string().min(1).nullable(),+ kind: z.literal('file'),+ path: z.string().min(1),+});+export type ArtboardBoardSource = z.infer<typeof artboardBoardSourceSchema>;++export const artboardBoardSourceInputSchema = z.object({+ kind: z.literal('file'),+ path: z.string().min(1),+});+export type ArtboardBoardSourceInput = z.infer<typeof artboardBoardSourceInputSchema>;++export interface ArtboardPageView {+ id: string;+ name: string;+ sortOrder: number;+}++export interface ArtboardRoundView {+ batchId: string | null;+ chosenBoardId: string | null;+ id: string;+ pageId: string;+ recommendedBoardId: string | null;+ status: ArtboardRoundStatus;+ title: string;+}++export interface ArtboardGroupView {+ desc: string;+ id: string;+ kind: ArtboardGroupKind;+ pageId: string;+ // Page coordinates; the service derives it from the boards inside.+ rect: ArtboardRect;+ title: string;+}++export interface ArtboardBoardView {+ expected: string | null;+ flowNodeId: string | null;+ groupId: string | null;+ id: string;+ pageId: string;+ // Page coordinates, also for a board inside a group.+ rect: ArtboardRect;+ roundId: string | null;+ // null for a decision board.+ source: ArtboardBoardSource | null;+ title: string;+ type: ArtboardBoardType;+}++export interface ArtboardEdgeView {+ condition: string | null;+ flowEdgeId: string | null;+ from: string;+ id: string;+ isDefault: boolean;+ label: string;+ to: string;+}++export interface ArtboardQuestionView {+ answered: boolean;+ boardId: string | null;+ content: string;+ groupId: string | null;+ id: string;+ pageId: string | null;+}++export interface ArtboardContent {+ boards: ArtboardBoardView[];+ edges: ArtboardEdgeView[];+ groups: ArtboardGroupView[];+ pages: ArtboardPageView[];+ questions: ArtboardQuestionView[];+ rounds: ArtboardRoundView[];+}++export interface ArtboardItem {+ acceptanceId: string | null;+ content: ArtboardContent;+ createdAt: Date;+ description: string | null;+ id: string;+ phase: ArtboardPhase;+ projectId: string | null;+ revision: number;+ taskId: string | null;+ title: string;+ topicId: string | null;+ updatedAt: Date;+}++export interface ArtboardCommentView {+ authorAgentId: string | null;+ authorUserId: string | null;+ content: string;+ createdAt: Date;+ id: string;+}++export interface ArtboardCommentThreadView extends ArtboardCommentView {+ anchor: ArtboardCommentAnchor | null;+ boardId: string | null;+ groupId: string | null;+ pageId: string | null;+ replies: ArtboardCommentView[];+ resolvedAt: Date | null;+ // The board moved to another source version after the comment was made.+ stale: boolean;+ // Unresolved, with a user message the agent has not been handed yet.+ unread: boolean;+}++const ref = z.string().min(1).optional();+const id = z.string().min(1);++const boardFields = {+ expected: text.optional(),+ groupId: id.optional(),+ h: size.optional(),+ pageId: id.optional(),+ recommended: z.boolean().optional(),+ roundId: id.optional(),+ source: artboardBoardSourceInputSchema.optional(),+ title: text,+ type: z.enum(ARTBOARD_BOARD_TYPES).optional(),+ w: size.optional(),+ x: coordinate,+ y: coordinate,+};++const groupFields = {+ desc: text.optional(),+ kind: z.enum(ARTBOARD_GROUP_KINDS),+ pageId: id.optional(),+ title: text,+};++export const artboardOpSchema = z.discriminatedUnion('type', [+ z.object({ page: z.object({ name: text.min(1) }), ref, type: z.literal('addPage') }),+ z.object({ id, patch: z.object({ name: text.min(1) }), type: z.literal('updatePage') }),+ z.object({ id, type: z.literal('removePage') }),+ z.object({+ ref,+ round: z.object({ batchId: id.optional(), pageId: id.optional(), title: text.min(1) }),+ type: z.literal('addRound'),+ }),+ z.object({ id, patch: z.object({ title: text.min(1) }), type: z.literal('updateRound') }),+ z.object({ group: z.object(groupFields), ref, type: z.literal('addGroup') }),+ z.object({+ id,+ patch: z.object({ desc: text, kind: z.enum(ARTBOARD_GROUP_KINDS), title: text }).partial(),+ type: z.literal('updateGroup'),+ }),+ z.object({ id, type: z.literal('removeGroup') }),+ z.object({ board: z.object(boardFields), ref, type: z.literal('addBoard') }),+ z.object({+ id,+ patch: z+ .object({+ ...boardFields,+ groupId: id.nullable(),+ roundId: id.nullable(),+ })+ .omit({ pageId: true, type: true })+ .partial(),+ type: z.literal('updateBoard'),+ }),+ z.object({ id, type: z.literal('removeBoard') }),+ z.object({+ edge: z.object({+ condition: text.optional(),+ from: id,+ isDefault: z.boolean().optional(),+ label: text.optional(),+ to: id,+ }),+ ref,+ type: z.literal('addEdge'),+ }),+ z.object({ id, type: z.literal('removeEdge') }),+ z.object({ boardId: id, expected: text, type: z.literal('setCheck') }),+]);+export type ArtboardOp = z.infer<typeof artboardOpSchema>;+export type ArtboardOpType = ArtboardOp['type'];++export interface ArtboardResultLineInput {+ boardCount: number;+ groupCount: number;+ id: string;+ revision: number;+}++export const formatArtboardResultLine = ({+ boardCount,+ groupCount,+ id: artboardId,+ revision,+}: ArtboardResultLineInput) =>+ `artboard ${artboardId} · revision ${revision} · ${groupCount} groups · ${boardCount} boards`;++const RESULT_LINE = /^artboard (\S+) · revision (\d+) · \d+ groups · \d+ boards$/m;++export const parseArtboardResultLine = (output: string) => {+ const match = RESULT_LINE.exec(output);+ return match ? { artboardId: match[1], revision: Number(match[2]) } : undefined;+};diff --git a/packages/types/src/artboardFiles.test.ts b/packages/types/src/artboardFiles.test.tsnew file mode 100644index 00000000000..9c6c16c9266--- /dev/null+++ b/packages/types/src/artboardFiles.test.ts@@ -0,0 +1,47 @@+import { describe, expect, it } from 'vitest';++import {+ ARTBOARD_FILE_LIMITS,+ artboardFileContentType,+ isArtboardImagePath,+ normalizeArtboardFilePath,+} from './artboardFiles';++describe('normalizeArtboardFilePath', () => {+ it('keeps a relative path', () => {+ expect(normalizeArtboardFilePath('pages/home/a.html')).toBe('pages/home/a.html');+ });++ it('drops a leading ./', () => {+ expect(normalizeArtboardFilePath('./shots/a.png')).toBe('shots/a.png');+ });++ it.each(['../a.html', 'pages/../../a.html', '/abs.html', 'a b.html', '', 'pages//a.html'])(+ 'rejects %j',+ (path) => {+ expect(normalizeArtboardFilePath(path)).toBeUndefined();+ },+ );++ it('rejects a path longer than the limit', () => {+ expect(+ normalizeArtboardFilePath(`${'a'.repeat(ARTBOARD_FILE_LIMITS.maxPathLength)}.html`),+ ).toBeUndefined();+ });++ it('rejects an extension a board cannot serve', () => {+ expect(normalizeArtboardFilePath('tool.exe')).toBeUndefined();+ });+});++describe('artboardFileContentType', () => {+ it('serves html as utf-8 html', () => {+ expect(artboardFileContentType('pages/a.html')).toBe('text/html; charset=utf-8');+ });++ it('maps images by extension', () => {+ expect(artboardFileContentType('shots/a.JPG')).toBe('image/jpeg');+ expect(isArtboardImagePath('shots/a.webp')).toBe(true);+ expect(isArtboardImagePath('pages/a.html')).toBe(false);+ });+});diff --git a/packages/types/src/artboardFiles.ts b/packages/types/src/artboardFiles.tsnew file mode 100644index 00000000000..f235dc513b1--- /dev/null+++ b/packages/types/src/artboardFiles.ts@@ -0,0 +1,98 @@+import { z } from 'zod';++export const ARTBOARD_FILE_LIMITS = {+ maxFiles: 500,+ maxImageBytes: 10 * 1024 * 1024,+ maxPathLength: 200,+ maxTextFileBytes: 512 * 1024,+ maxTotalBytes: 50 * 1024 * 1024,+} as const;++const CONTENT_TYPES: Record<string, string> = {+ css: 'text/css; charset=utf-8',+ gif: 'image/gif',+ htm: 'text/html; charset=utf-8',+ html: 'text/html; charset=utf-8',+ jpeg: 'image/jpeg',+ jpg: 'image/jpeg',+ js: 'text/javascript; charset=utf-8',+ json: 'application/json; charset=utf-8',+ mjs: 'text/javascript; charset=utf-8',+ png: 'image/png',+ svg: 'image/svg+xml',+ txt: 'text/plain; charset=utf-8',+ webp: 'image/webp',+ woff: 'font/woff',+ woff2: 'font/woff2',+};++const IMAGE_EXTENSIONS = new Set(['gif', 'jpeg', 'jpg', 'png', 'svg', 'webp']);+const TEXT_EXTENSIONS = new Set(['css', 'htm', 'html', 'js', 'json', 'mjs', 'svg', 'txt']);++const SEGMENT = /^[\w.@-]+$/;++const extensionOf = (path: string) => {+ const name = path.slice(path.lastIndexOf('/') + 1);+ const dot = name.lastIndexOf('.');+ return dot > 0 ? name.slice(dot + 1).toLowerCase() : '';+};++export const artboardFileContentType = (path: string): string | undefined =>+ CONTENT_TYPES[extensionOf(path)];++export const isArtboardImagePath = (path: string) => IMAGE_EXTENSIONS.has(extensionOf(path));++export const isArtboardHtmlPath = (path: string) => ['htm', 'html'].includes(extensionOf(path));++export const isArtboardTextPath = (path: string) => TEXT_EXTENSIONS.has(extensionOf(path));++export const normalizeArtboardFilePath = (path: string): string | undefined => {+ const trimmed = path.trim().replace(/^\.\//, '');+ if (!trimmed || trimmed.length > ARTBOARD_FILE_LIMITS.maxPathLength) return;+ const segments = trimmed.split('/');+ if (segments.some((segment) => !SEGMENT.test(segment) || segment === '.' || segment === '..'))+ return;+ if (!artboardFileContentType(trimmed)) return;+ return trimmed;+};++const filePathSchema = z+ .string()+ .min(1)+ .max(ARTBOARD_FILE_LIMITS.maxPathLength + 2);++export const artboardFileWriteSchema = z.union([+ z.object({ content: z.string(), path: filePathSchema }).strict(),+ z.object({ fileRef: z.string().min(1), path: filePathSchema }).strict(),+ z.object({ base64: z.string().min(1), path: filePathSchema }).strict(),+ // Already PUT to the URL from artboard.prepareFileUploads; the write only records the change.+ z.object({ path: filePathSchema, uploaded: z.literal(true) }).strict(),+ // Import copies: the content is copied in now and does not follow the source afterwards.+ z+ .object({+ fromCanvas: z+ .object({ canvasId: z.string().min(1), version: z.number().int().positive().optional() })+ .strict(),+ path: filePathSchema,+ })+ .strict(),+]);++export const artboardFileUploadsSchema = z+ .array(z.object({ path: filePathSchema, size: z.number().int().nonnegative() }).strict())+ .min(1)+ .max(ARTBOARD_FILE_LIMITS.maxFiles);++export const artboardFileEditSchema = z+ .object({ newText: z.string(), oldText: z.string().min(1), path: filePathSchema })+ .strict();++export const artboardFileChangesSchema = z+ .object({+ deletes: z.array(filePathSchema).max(ARTBOARD_FILE_LIMITS.maxFiles).optional(),+ edits: z.array(artboardFileEditSchema).max(200).optional(),+ writes: z.array(artboardFileWriteSchema).max(ARTBOARD_FILE_LIMITS.maxFiles).optional(),+ })+ .strict();++export type ArtboardFileChangesInput = z.infer<typeof artboardFileChangesSchema>;diff --git a/packages/types/src/artboardPublish.ts b/packages/types/src/artboardPublish.tsnew file mode 100644index 00000000000..0c850f71299--- /dev/null+++ b/packages/types/src/artboardPublish.ts@@ -0,0 +1,32 @@+import type {+ ArtboardBoardView,+ ArtboardEdgeView,+ ArtboardGroupView,+ ArtboardPageView,+ ArtboardRoundView,+} from './artboard';++export const ARTBOARD_VIEWER_MAJOR = 1;++export const ARTBOARD_SNAPSHOT_ELEMENT_ID = 'artboard-snapshot';++/** Directory of the published site that holds the artboard's own files, keyed by their path. */+export const ARTBOARD_SITE_FILES_DIR = 'files/';++export type ArtboardPublishBoard = Omit<ArtboardBoardView, 'expected' | 'flowNodeId'>;++export type ArtboardPublishEdge = Omit<ArtboardEdgeView, 'flowEdgeId'>;++export type ArtboardPublishRound = Omit<ArtboardRoundView, 'batchId'>;++export interface ArtboardPublishSnapshot {+ boards: ArtboardPublishBoard[];+ description: string | null;+ edges: ArtboardPublishEdge[];+ groups: ArtboardGroupView[];+ pages: ArtboardPageView[];+ publishedAt: string;+ rounds: ArtboardPublishRound[];+ title: string;+ version: 1;+}diff --git a/packages/types/src/artboardReadiness.ts b/packages/types/src/artboardReadiness.tsnew file mode 100644index 00000000000..fb76dd8c823--- /dev/null+++ b/packages/types/src/artboardReadiness.ts@@ -0,0 +1,69 @@+import type { ArtboardContent } from './artboard';++export type ArtboardFinalizeIssue =+ | { code: 'empty_journey' }+ | { code: 'entry_count'; entryBoardIds: string[] }+ | { boardId: string; code: 'missing_check' }+ | { code: 'multiple_journeys' }+ | { code: 'no_journey' }+ | { code: 'open_question'; commentId: string }+ | { code: 'open_round'; roundId: string }+ | { boardId: string; code: 'unreachable' };++export const artboardJourneyOf = (content: ArtboardContent) => {+ const groups = content.groups.filter((g) => g.kind === 'journey');+ if (groups.length !== 1) return { group: undefined, groups };+ const group = groups[0];+ const boards = content.boards.filter((b) => b.groupId === group.id);+ const boardIds = new Set(boards.map((b) => b.id));+ const edges = content.edges.filter((e) => boardIds.has(e.from) && boardIds.has(e.to));+ return { boards, edges, group, groups };+};++export const checkFinalizeReadiness = (content: ArtboardContent): ArtboardFinalizeIssue[] => {+ const issues: ArtboardFinalizeIssue[] = [+ ...content.rounds+ .filter((round) => round.status === 'open')+ .map((round) => ({ code: 'open_round' as const, roundId: round.id })),+ ...content.questions.map((question) => ({+ code: 'open_question' as const,+ commentId: question.id,+ })),+ ];+ const journey = artboardJourneyOf(content);++ if (!journey.group) {+ issues.unshift({ code: journey.groups.length ? 'multiple_journeys' : 'no_journey' });+ return issues;+ }+ const { boards, edges } = journey;+ if (!boards.length) {+ issues.unshift({ code: 'empty_journey' });+ return issues;+ }++ const journeyIssues: ArtboardFinalizeIssue[] = [];+ for (const board of boards)+ if (board.type !== 'decision' && !board.expected?.trim())+ journeyIssues.push({ boardId: board.id, code: 'missing_check' });++ const targets = new Set(edges.map((e) => e.to));+ const entries = boards.filter((b) => !targets.has(b.id));+ if (entries.length !== 1 || entries[0].type === 'decision') {+ journeyIssues.push({ code: 'entry_count', entryBoardIds: entries.map((b) => b.id) });+ } else {+ const reached = new Set([entries[0].id]);+ for (let grew = true; grew;) {+ grew = false;+ for (const edge of edges)+ if (reached.has(edge.from) && !reached.has(edge.to)) {+ reached.add(edge.to);+ grew = true;+ }+ }+ for (const board of boards)+ if (!reached.has(board.id)) journeyIssues.push({ boardId: board.id, code: 'unreachable' });+ }++ return [...journeyIssues, ...issues];+};diff --git a/packages/types/src/index.ts b/packages/types/src/index.tsindex f58dc1c987c..77941801428 100644--- a/packages/types/src/index.ts+++ b/packages/types/src/index.ts@@ -100,6 +100,9 @@ export * from './acceptanceReview';export * from './acceptanceReviewRound';export * from './agentRuntime';export * from './artboard';+export * from './artboardFiles';+export * from './artboardPublish';+export * from './artboardReadiness';export * from './connector';export * from './connectorToolIdentifier';export * from './heteroPermissionMode';diff --git a/packages/types/src/message/db/params.ts b/packages/types/src/message/db/params.tsindex 43512d94ed9..82258a97946 100644--- a/packages/types/src/message/db/params.ts+++ b/packages/types/src/message/db/params.ts@@ -33,6 +33,8 @@ export interface QueryMessageParams {before?: { createdAt: Date; id: string };current?: number;groupId?: string | null;+ /** Same opt-in as `includeFileWorks`, for `artboard` work summaries. */+ includeArtboardWorks?: boolean;/*** Opt-in for `file` work summaries embedded in the message payload. Absent →* the legacy set, so already-deployed clients (whose descriptor table lacksdiff --git a/packages/types/src/serverConfig.ts b/packages/types/src/serverConfig.tsindex 047e7cc4d8f..83fc21ad02a 100644--- a/packages/types/src/serverConfig.ts+++ b/packages/types/src/serverConfig.ts@@ -24,6 +24,7 @@ export type IFeatureFlagsState = {* open/chat on an already-live shared agent. One allowlist gates both sides.*/enableAgentShare: boolean | undefined;+ enableArtboard: boolean | undefined;enableAuthCaptcha: boolean | undefined;/*** Multi-agent Channels (`channel`). Off by default: the sidebar section and Channel pages arediff --git a/packages/types/src/work.ts b/packages/types/src/work.tsindex 838fd8f2253..1daab7d3ed2 100644--- a/packages/types/src/work.ts+++ b/packages/types/src/work.ts@@ -6,7 +6,8 @@ import type { TaskStatus } from './task';* version per acceptance result. It is read through the goal graph, not the* generic Work lists.*/-export type WorkType = 'canvas' | 'document' | 'external' | 'file' | 'goal_report' | 'task';+export type WorkType =+ 'artboard' | '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 +15,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 =- 'canvas' | 'document' | ExternalWorkResourceType | 'file' | 'goal_report' | 'task';+ 'artboard' | 'canvas' | 'document' | ExternalWorkResourceType | 'file' | 'goal_report' | 'task';export type WorkVisibility = 'private' | 'public';/*** How a version changed the Work. Not derivable from `version === 1`: updating@@ -50,8 +51,16 @@ export interface CanvasWorkPublishMetadata {publishedVersion: number;}+export interface ArtboardWorkPublishMetadata {+ deploymentId: string;+ publishedRevision: number;+ publisherUserId: string;+ snapshotHash: string;+}+export interface WorkMetadata {agentShare?: AgentShareWorkProvenance;+ artboardPublish?: ArtboardWorkPublishMetadata;canvasPublish?: CanvasWorkPublishMetadata;}@@ -311,7 +320,13 @@ export interface CanvasWorkListItem extends WorkListBaseItem {type: 'canvas';}+export interface ArtboardWorkListItem extends WorkListBaseItem {+ resourceType: 'artboard';+ type: 'artboard';+}+export type WorkListItem =+ | ArtboardWorkListItem| CanvasWorkListItem| DocumentWorkListItem| ExternalWorkListItem@@ -338,7 +353,12 @@ export interface CanvasWorkVersionEventItem extends CanvasWorkListItem {version: WorkVersionPreview;}+export interface ArtboardWorkVersionEventItem extends ArtboardWorkListItem {+ version: WorkVersionPreview;+}+export type WorkVersionEventItem =+ | ArtboardWorkVersionEventItem| CanvasWorkVersionEventItem| DocumentWorkVersionEventItem| ExternalWorkVersionEventItem@@ -379,7 +399,14 @@ export interface CanvasWorkSummaryItem extends CanvasWorkListItem {version: Pick<WorkVersionItem, 'createdAt' | 'id' | 'version'> | null;}+export interface ArtboardWorkSummaryItem extends ArtboardWorkListItem {+ event: WorkSummaryVersionPreview;+ totalCost: number | null;+ version: Pick<WorkVersionItem, 'createdAt' | 'id' | 'version'> | null;+}+export type WorkSummaryItem =+ | ArtboardWorkSummaryItem| CanvasWorkSummaryItem| DocumentWorkSummaryItem| ExternalWorkSummaryItem@@ -463,6 +490,24 @@ export interface RegisterCanvasWorkParams {visibility?: WorkVisibility;}+export interface RegisterArtboardWorkParams {+ agentId?: string | null;+ artboardId: string;+ changeType: WorkVersionChangeType;+ cumulativeCost?: number | null;+ cumulativeUsage?: WorkVersionCumulativeUsage | null;+ description?: string | null;+ messageId?: string | null;+ projectId?: string | null;+ rootOperationId?: string | null;+ threadId?: string | null;+ title: string;+ toolCallId?: string | null;+ toolIdentifier: string;+ toolName: string;+ topicId?: string | null;+}+export interface DeleteDocumentWorkParams {agentDocumentId?: string | null;agentId?: string | null;@@ -660,6 +705,18 @@ export type WorkRegistrationIntent =toolName: string;};type: 'canvas';+ }+ | {+ action: 'register';+ artboard: {+ artboardId: string;+ changeType: WorkVersionChangeType;+ description?: string | null;+ projectId?: string | null;+ title: string;+ toolName: string;+ };+ type: 'artboard';};/**diff --git a/scripts/stylexMigration/plainCssImporters.json b/scripts/stylexMigration/plainCssImporters.jsonindex 347c1f48b11..8f9be20512c 100644--- a/scripts/stylexMigration/plainCssImporters.json+++ b/scripts/stylexMigration/plainCssImporters.json@@ -5,6 +5,7 @@"apps/workbench/app/root.tsx","apps/workbench/src/entry.tsx","apps/workbench/src/localReport/entry.tsx",+ "packages/artboard-viewer/src/index.tsx","packages/canvas-runtime/src/index.tsx","packages/style-equivalence/src/report/main.tsx","packages/style-equivalence/test/fixtures/mini-project/host.tsx",diff --git a/src/app/(backend)/artboard-files/[token]/[...path]/route.ts b/src/app/(backend)/artboard-files/[token]/[...path]/route.tsnew file mode 100644index 00000000000..3b0efb58c41--- /dev/null+++ b/src/app/(backend)/artboard-files/[token]/[...path]/route.ts@@ -0,0 +1,20 @@+import { getServerDB } from '@/database/server';+import { serveArtboardFile } from '@/server/services/artboard/fileAccess';+import { createFileServiceArtboardBlobStore } from '@/server/services/artboard/files';+import { FileService } from '@/server/services/file';++type Params = Promise<{ path: string[]; token: string }>;++export const GET = async (_request: Request, segmentData: { params: Params }) => {+ const { path, token } = await segmentData.params;+ const db = await getServerDB();+ return serveArtboardFile({+ db,+ path: path.join('/'),+ storeFor: ({ userId, workspaceId }) =>+ createFileServiceArtboardBlobStore(+ () => new FileService(db, userId, workspaceId ?? undefined),+ ),+ token,+ });+};diff --git a/src/features/Acceptance/Viewer/AcceptanceOverview.tsx b/src/features/Acceptance/Viewer/AcceptanceOverview.tsxindex cd36633bad0..994b09698b9 100644--- a/src/features/Acceptance/Viewer/AcceptanceOverview.tsx+++ b/src/features/Acceptance/Viewer/AcceptanceOverview.tsx@@ -13,7 +13,7 @@ import AcceptanceCheckInventory from './Checks/AcceptanceCheckInventory';import AcceptanceCheckOwnerToolbar from './Checks/AcceptanceCheckOwnerToolbar';import { columnStyles } from './columnStyles';import AcceptanceDiscussion from './Comments/AcceptanceDiscussion';-import { commentIdFromHash } from './Comments/anchor';+import { tabFromHash } from './Comments/anchor';import CollaborationRequestBanner from './Comments/CollaborationRequestBanner';import { countDiscussionMessages } from './Comments/discussionTimeline';import { useAcceptanceComments } from './Comments/hooks';@@ -75,7 +75,7 @@ export const AcceptanceOverview = ({const rounds = data?.rounds ?? [];const flowCount = getFlowNodeCount(data?.flows);const tab = resolveAcceptanceTab(- requestedTab ?? (!embedded && commentIdFromHash(hash) ? 'discussion' : undefined),+ requestedTab ?? (embedded ? undefined : tabFromHash(hash)),flowCount,Boolean(flowPlanPhase(rounds.at(-1))),md,diff --git a/src/features/Acceptance/Viewer/Comments/anchor.test.ts b/src/features/Acceptance/Viewer/Comments/anchor.test.tsindex 0563d6a35fb..8c4042d2661 100644--- a/src/features/Acceptance/Viewer/Comments/anchor.test.ts+++ b/src/features/Acceptance/Viewer/Comments/anchor.test.ts@@ -1,6 +1,12 @@import { afterEach, describe, expect, it, vi } from 'vitest';-import { commentAnchorId, commentAnchorUrl, commentIdFromHash, holdInView } from './anchor';+import {+ commentAnchorId,+ commentAnchorUrl,+ commentIdFromHash,+ holdInView,+ tabFromHash,+} from './anchor';describe('comment anchors', () => {it('round-trips a comment id through the fragment', () => {@@ -107,3 +113,11 @@ describe('holding a linked comment in view', () => {expect(other.scrollIntoView).not.toHaveBeenCalled();});});++describe('tabFromHash', () => {+ it('lands a flow link on the flow tab and a comment link on the discussion', () => {+ expect(tabFromHash('#flow')).toBe('flow');+ expect(tabFromHash('#comment-c1')).toBe('discussion');+ expect(tabFromHash('')).toBeUndefined();+ });+});diff --git a/src/features/Acceptance/Viewer/Comments/anchor.ts b/src/features/Acceptance/Viewer/Comments/anchor.tsindex 393b39af6d1..6f08fda27a6 100644--- a/src/features/Acceptance/Viewer/Comments/anchor.ts+++ b/src/features/Acceptance/Viewer/Comments/anchor.ts@@ -1,6 +1,8 @@import { useEffect, useRef } from 'react';import { useLocation } from 'react-router';+import type { AcceptanceTabKey } from '../Header/AcceptanceTabs';+/*** A comment is addressable, the way a pull-request comment is: its id lives in* the URL fragment, so a link pasted into chat opens the acceptance already@@ -12,12 +14,19 @@ const PREFIX = 'comment-';export const commentAnchorId = (commentId: string) => `${PREFIX}${commentId}`;+export const FLOW_HASH = '#flow';+/** The comment a fragment addresses, or undefined for any other fragment. */export const commentIdFromHash = (hash: string): string | undefined => {const value = hash.replace(/^#/, '');return value.startsWith(PREFIX) ? value.slice(PREFIX.length) || undefined : undefined;};+export const tabFromHash = (hash: string): AcceptanceTabKey | undefined => {+ if (hash === FLOW_HASH) return 'flow';+ if (commentIdFromHash(hash)) return 'discussion';+};+/*** The link to hand someone else — this page, this comment. `appOrigin` comes* from `useAcceptanceOrigin`, not `window.location`: on desktop that is thediff --git a/src/features/Acceptance/Viewer/Flow/FlowCanvas.tsx b/src/features/Acceptance/Viewer/Flow/FlowCanvas.tsxindex 34c536e8f16..96cae84ae65 100644--- a/src/features/Acceptance/Viewer/Flow/FlowCanvas.tsx+++ b/src/features/Acceptance/Viewer/Flow/FlowCanvas.tsx@@ -6,6 +6,7 @@ import {Background,Controls,type Edge,+ type FitViewOptions,type Node,type NodeTypes,ReactFlow,@@ -25,7 +26,7 @@ import { getSelectedFlowNodeId, panNodeIntoView, revealNode } from './flowViewpoconst edgeTypes = { transition: FlowEdge };-const fitOptions = { maxZoom: 1, minZoom: 0.65, padding: 0.08 };+const defaultFitOptions = { maxZoom: 1, minZoom: 0.65, padding: 0.08 };const styles = stylex.create({canvas: {overflow: 'hidden',@@ -54,6 +55,7 @@ const fallback = createStaticStyles(({ css, cssVar }) => ({}));export function FlowCanvas({+ fitOptions = defaultFitOptions,fullscreen = false,nodes,edges,@@ -61,6 +63,7 @@ export function FlowCanvas({onSelect,viewKey,}: {+ fitOptions?: FitViewOptions;fullscreen?: boolean;nodes: Node<FlowGraphData>[];edges: Edge[];@@ -143,7 +146,7 @@ export function FlowCanvas({height: container?.clientHeight ?? 0,});};- }, [viewKey, fullscreen, fitView, getViewport, setViewport, viewports]);+ }, [viewKey, fullscreen, fitOptions, fitView, getViewport, setViewport, viewports]);return (// Custom nodes render inside React Flow, not under its `children`, so the// anchor channel has to sit above the canvas to reach a group's toggle.diff --git a/src/features/Acceptance/Viewer/Flow/FlowNode.tsx b/src/features/Acceptance/Viewer/Flow/FlowNode.tsxindex 0956e1e55d4..bba6146b4d0 100644--- a/src/features/Acceptance/Viewer/Flow/FlowNode.tsx+++ b/src/features/Acceptance/Viewer/Flow/FlowNode.tsx@@ -17,6 +17,10 @@ import {} from 'lucide-react';import { useTranslation } from 'react-i18next';+import { flowStateColor } from './flowStateColor';++export { flowStateColor } from './flowStateColor';+export interface FlowNodeData extends Record<string, unknown> {attempts: number;evidence: number;@@ -46,23 +50,6 @@ export const flowStateBackground = (state?: string) => {}};-export const flowStateColor = (state?: string) => {- switch (state) {- case undefined: {- return cssVar.colorTextQuaternary;- }- case 'passed': {- return cssVar.colorSuccess;- }- case 'failed': {- return cssVar.colorError;- }- default: {- return cssVar.colorWarning;- }- }-};-export const flowStateIcon = (state?: string) => {switch (state) {case 'passed': {diff --git a/src/features/Acceptance/Viewer/Flow/flowStateColor.ts b/src/features/Acceptance/Viewer/Flow/flowStateColor.tsnew file mode 100644index 00000000000..224756cdf89--- /dev/null+++ b/src/features/Acceptance/Viewer/Flow/flowStateColor.ts@@ -0,0 +1,18 @@+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';++export const flowStateColor = (state?: string) => {+ switch (state) {+ case undefined: {+ return cssVar.colorTextQuaternary;+ }+ case 'passed': {+ return cssVar.colorSuccess;+ }+ case 'failed': {+ return cssVar.colorError;+ }+ default: {+ return cssVar.colorWarning;+ }+ }+};diff --git a/src/features/Artboard/Board/Fullscreen.tsx b/src/features/Artboard/Board/Fullscreen.tsxnew file mode 100644index 00000000000..a21776cab1d--- /dev/null+++ b/src/features/Artboard/Board/Fullscreen.tsx@@ -0,0 +1,39 @@+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import { useEffect } from 'react';+import { createPortal } from 'react-dom';++import BoardView from '.';++const styles = stylex.create({+ overlay: {+ backgroundColor: cssVar.colorBgLayout,+ display: 'flex',+ flexDirection: 'column',+ inset: 0,+ position: 'fixed',+ zIndex: 100,+ },+});++interface ArtboardFullscreenProps {+ artboardId: string;+ onClose: () => void;+}++export const ArtboardFullscreen = ({ artboardId, onClose }: ArtboardFullscreenProps) => {+ useEffect(() => {+ const onKey = (event: KeyboardEvent) => {+ if (event.key === 'Escape' && !document.querySelector('[role="dialog"]')) onClose();+ };+ window.addEventListener('keydown', onKey);+ return () => window.removeEventListener('keydown', onKey);+ }, [onClose]);++ return createPortal(+ <div {...stylex.props(styles.overlay)}>+ <BoardView artboardId={artboardId} onExitFullscreen={onClose} />+ </div>,+ document.body,+ );+};diff --git a/src/features/Artboard/Board/Header.tsx b/src/features/Artboard/Board/Header.tsxnew file mode 100644index 00000000000..1b0f42e8b7b--- /dev/null+++ b/src/features/Artboard/Board/Header.tsx@@ -0,0 +1,285 @@+import { ActionIcon, Button, Flexbox, Segmented, Tooltip } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import {+ ClipboardCheckIcon,+ ListTreeIcon,+ LockIcon,+ Maximize2Icon,+ MessageCirclePlusIcon,+ Minimize2Icon,+ MousePointer2Icon,+ StampIcon,+ XIcon,+} from 'lucide-react';+import { useTranslation } from 'react-i18next';++import { useDensityTokens, useHeaderActionSize } from '@/styles/density';+import { sidebarRow } from '@/styles/density.stylex';+import { electronStylish } from '@/styles/electron';+import { sx } from '@/styles/sx';++import { useBoard } from '../BoardContext';+import { nextQuestion, waitingQuestions } from '../data/commentModel';+import { useArtboardComments } from '../data/useArtboardComments';+import { createFinalizeModal } from '../Finalize';+import OpenConversation from '../Gallery/OpenConversation';+import { artboardActions, useArtboardStore } from '../store';+import type { BoardMode, VerifyView } from '../types';+import { floatStyles } from '../Viewport/floatStyles';+import { headerChrome } from './headerChrome';+import PageMenu from './PageMenu';+import ShareButton from './ShareButton';+import { useTitleBarInset } from './useTitleBarInset';++const BAR_PADDING = 10;++const styles = stylex.create({+ bar: {+ borderBlockEndColor: cssVar.colorBorderSecondary,+ borderBlockEndStyle: 'solid',+ borderBlockEndWidth: 1,+ flex: 'none',+ fontSize: sidebarRow.textFontSize,+ minHeight: sidebarRow.headerHeight,+ paddingBlock: 4,+ paddingInline: BAR_PADDING,+ },+ chip: {+ alignItems: 'center',+ borderRadius: sidebarRow.radius,+ display: 'flex',+ flex: 'none',+ fontWeight: 500,+ gap: 6,+ height: 26,+ paddingInline: 8,+ whiteSpace: 'nowrap',+ },+ questions: {+ backgroundColor: {+ ':hover': cssVar.colorWarningBgHover,+ 'default': cssVar.colorWarningBg,+ },+ borderWidth: 0,+ color: cssVar.colorWarningText,+ fontSize: sidebarRow.textFontSize,+ },+ finalized: {+ backgroundColor: cssVar.colorSuccessBg,+ color: cssVar.colorSuccessText,+ },+ finalize: {+ borderRadius: sidebarRow.radius,+ fontWeight: 500,+ height: sidebarRow.controlHeight,+ paddingInline: 12,+ },+});++interface HeaderProps {+ narrow: boolean;+ /** The board is in the Works modal; the header closes it. */+ onClose?: () => void;+ /** The board covers the whole window; the header returns it to the side panel. */+ onExitFullscreen?: () => void;+}++const Header = ({ narrow, onClose, onExitFullscreen }: HeaderProps) => {+ const { t } = useTranslation(['project', 'common']);+ const { radius } = useDensityTokens();+ const headerActionSize = useHeaderActionSize();+ const toolSize = { ...headerActionSize, borderRadius: radius, strokeWidth: 1.75 };+ const board = useBoard();+ const { finalized } = board;+ const { coversWindow, exit } = headerChrome({ onClose, onExitFullscreen });+ const trafficLightPadding = useTitleBarInset();+ const bar = sx(+ styles.bar,+ coversWindow ? electronStylish.draggable : undefined,+ coversWindow ? { paddingInlineStart: BAR_PADDING + trafficLightPadding } : {},+ );+ const nodrag = coversWindow ? electronStylish.nodrag : undefined;+ const exitButton = {+ close: { icon: XIcon, onClick: onClose, title: t('close', { ns: 'common' }) },+ enterFullscreen: {+ icon: Maximize2Icon,+ onClick: () => artboardActions.setFullscreen(true),+ title: t('artboard.header.fullscreen'),+ },+ exitFullscreen: {+ icon: Minimize2Icon,+ onClick: onExitFullscreen,+ title: t('artboard.header.exitFullscreen'),+ },+ }[exit];+ const pendingLeft = board.blockers.length;+ const hasTask = !!board.artboard.taskId;+ const { data: threads = [] } = useArtboardComments(board.artboard.id);+ const waiting = waitingQuestions(threads).length;+ const { gallery, mode, outlineOpen, tool, verifyOpen, verifyView } = useArtboardStore((s) => ({+ gallery: s.gallery,+ mode: s.mode,+ outlineOpen: s.outlineOpen,+ tool: s.tool,+ verifyOpen: s.verifyOpen,+ verifyView: s.verifyView,+ }));+ const divider = <span {...stylex.props(floatStyles.divider)} />;++ const showNextQuestion = () => {+ const next = nextQuestion(threads, useArtboardStore.getState().openThreadId);+ if (next) artboardActions.showThread(next);+ };++ const identity = (+ <Flexbox horizontal align={'center'} gap={2} style={{ minWidth: 0 }}>+ {!narrow && (+ <>+ <ActionIcon+ active={outlineOpen}+ className={nodrag}+ disabled={mode === 'verify'}+ icon={ListTreeIcon}+ size={toolSize}+ title={t('artboard.header.outline')}+ onClick={() => artboardActions.setOutlineOpen(!outlineOpen)}+ />+ {divider}+ </>+ )}+ <PageMenu className={nodrag} />+ </Flexbox>+ );+ const review = (+ <Flexbox horizontal align={'center'} className={nodrag} gap={2}>+ {mode === 'verify' && (+ <Segmented+ size={'small'}+ value={verifyView}+ options={[+ { label: t('artboard.verifyBar.board'), value: 'board' },+ { label: t('artboard.verifyBar.list'), value: 'list' },+ ]}+ onChange={(value) => artboardActions.setVerifyView(value as VerifyView)}+ />+ )}+ {mode === 'discuss' && (+ <>+ <ActionIcon+ active={tool === 'select'}+ icon={MousePointer2Icon}+ size={toolSize}+ title={t('artboard.tool.select')}+ onClick={() => artboardActions.setTool('select')}+ />+ <ActionIcon+ active={tool === 'comment'}+ icon={MessageCirclePlusIcon}+ size={toolSize}+ title={t('artboard.tool.comment')}+ onClick={() => artboardActions.setTool('comment')}+ />+ </>+ )}+ {waiting > 0 && (+ <>+ {divider}+ <Button {...stylex.props(styles.chip, styles.questions)} onClick={showNextQuestion}>+ {t('artboard.header.questions', { count: waiting })}+ </Button>+ </>+ )}+ </Flexbox>+ );+ const stage = (+ <Flexbox horizontal align={'center'} className={nodrag} gap={8}>+ <Segmented+ size={'small'}+ value={mode}+ options={[+ { label: t('artboard.header.discuss'), value: 'discuss' },+ {+ disabled: !finalized,+ label: t('artboard.header.verify'),+ title: finalized ? undefined : t('artboard.header.verifyLocked'),+ value: 'verify',+ },+ ]}+ onChange={(value) => artboardActions.setMode(value as BoardMode)}+ />+ {finalized ? (+ <span {...stylex.props(styles.chip, styles.finalized)}>+ <LockIcon size={13} strokeWidth={2} />+ {t('artboard.header.finalized')}+ </span>+ ) : (+ <Tooltip title={hasTask ? undefined : t('artboard.header.noTask')}>+ <Button+ disabled={!hasTask}+ icon={StampIcon}+ type={'primary'}+ {...stylex.props(styles.finalize)}+ onClick={() => createFinalizeModal(board.artboard.id)}+ >+ {narrow+ ? t('artboard.header.finalizeShort')+ : pendingLeft+ ? t('artboard.header.finalizePending', { count: pendingLeft })+ : t('artboard.header.finalize')}+ </Button>+ </Tooltip>+ )}+ </Flexbox>+ );+ const windowActions = (+ <Flexbox horizontal align={'center'} className={nodrag} gap={2}>+ {mode === 'verify' && (+ <ActionIcon+ active={verifyOpen}+ icon={ClipboardCheckIcon}+ size={toolSize}+ title={t('artboard.header.verifyPanel')}+ onClick={() => artboardActions.setVerifyOpen(!verifyOpen)}+ />+ )}+ {gallery && <OpenConversation onLeave={onClose} />}+ <ActionIcon+ icon={exitButton.icon}+ size={toolSize}+ title={exitButton.title}+ onClick={exitButton.onClick}+ />+ <ShareButton compact={narrow} />+ </Flexbox>+ );++ if (narrow)+ return (+ <Flexbox gap={4} {...bar}>+ <Flexbox horizontal align={'center'} gap={8} justify={'space-between'}>+ {identity}+ {windowActions}+ </Flexbox>+ <Flexbox horizontal align={'center'} gap={8} justify={'space-between'}>+ {review}+ {stage}+ </Flexbox>+ </Flexbox>+ );++ return (+ <Flexbox horizontal align={'center'} gap={8} justify={'space-between'} {...bar}>+ {identity}+ <Flexbox horizontal align={'center'} gap={2}>+ {review}+ {divider}+ {stage}+ {divider}+ {windowActions}+ </Flexbox>+ </Flexbox>+ );+};++export default Header;diff --git a/src/features/Artboard/Board/Outline.tsx b/src/features/Artboard/Board/Outline.tsxnew file mode 100644index 00000000000..422405b9f26--- /dev/null+++ b/src/features/Artboard/Board/Outline.tsx@@ -0,0 +1,131 @@+import { Flexbox } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import { type KeyboardEvent } from 'react';+import { useTranslation } from 'react-i18next';++import { useBoard } from '../BoardContext';+import { artboardActions, useArtboardStore } from '../store';+import { floatStyles } from '../Viewport/floatStyles';++const styles = stylex.create({+ divider: {+ backgroundColor: cssVar.colorBorderSecondary,+ flex: 'none',+ height: 1,+ marginBlock: 4,+ marginInline: -6,+ },+ label: {+ color: cssVar.colorTextTertiary,+ fontSize: 12,+ paddingBlockEnd: 4,+ paddingBlockStart: 6,+ paddingInline: 9,+ },+ group: {+ color: {+ ':hover': cssVar.colorText,+ 'default': cssVar.colorTextSecondary,+ },+ cursor: 'pointer',+ fontSize: 12,+ fontWeight: 600,+ overflow: 'hidden',+ paddingBlock: 6,+ paddingInline: 9,+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap',+ },+ item: {+ backgroundColor: {+ ':hover': cssVar.colorFillTertiary,+ 'default': 'transparent',+ },+ borderRadius: 6,+ color: cssVar.colorTextSecondary,+ cursor: 'pointer',+ fontSize: 13,+ overflow: 'hidden',+ paddingBlock: 5,+ paddingInline: 9,+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap',+ },+ itemActive: {+ backgroundColor: cssVar.colorFillSecondary,+ color: cssVar.colorText,+ fontWeight: 500,+ },+ panel: {+ insetBlockStart: 10,+ insetInlineStart: 10,+ maxHeight: 'calc(100% - 76px)',+ overflowY: 'auto',+ padding: 6,+ width: 184,+ },+});++const pressable = (onActivate: () => void) => ({+ onClick: onActivate,+ onKeyDown: (event: KeyboardEvent) => {+ if (event.key !== 'Enter' && event.key !== ' ') return;+ event.preventDefault();+ onActivate();+ },+ role: 'button',+ tabIndex: 0,+});++const Outline = () => {+ const { t } = useTranslation('project');+ const board = useBoard();+ const selected = useArtboardStore((s) => s.selected);++ return (+ <Flexbox gap={1} {...stylex.props(floatStyles.float, styles.panel)}>+ {board.pages.length > 1 && (+ <>+ <div {...stylex.props(styles.label)}>{t('artboard.pages.title')}</div>+ {board.pages.map((page) => (+ <div+ key={page.id}+ {...stylex.props(styles.item, page.id === board.pageId && styles.itemActive)}+ {...pressable(() => artboardActions.setPage(page.id))}+ >+ {page.name}+ </div>+ ))}+ <div {...stylex.props(styles.divider)} />+ </>+ )}+ <div {...stylex.props(styles.label)}>{t('artboard.outline.title')}</div>+ {board.groups.map((group) => {+ const members = board.boards.filter((b) => b.groupId === group.id);+ if (!members.length) return null;+ return (+ <Flexbox gap={1} key={group.id}>+ <div+ {...stylex.props(styles.group)}+ {...pressable(() => artboardActions.focus({ id: group.id, kind: 'group' }))}+ >+ {group.title}+ </div>+ {members.map((member) => (+ <div+ key={member.id}+ {...stylex.props(styles.item, selected === member.id && styles.itemActive)}+ {...pressable(() => artboardActions.focusItem(member.id))}+ >+ {member.title}+ </div>+ ))}+ </Flexbox>+ );+ })}+ </Flexbox>+ );+};++export default Outline;diff --git a/src/features/Artboard/Board/PageMenu.tsx b/src/features/Artboard/Board/PageMenu.tsxnew file mode 100644index 00000000000..1a6b674fac8--- /dev/null+++ b/src/features/Artboard/Board/PageMenu.tsx@@ -0,0 +1,101 @@+import { type DropdownItem, DropdownMenu, Icon } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import { CheckIcon, ChevronsUpDownIcon, LayersIcon } from 'lucide-react';++import { sidebarRow } from '@/styles/density.stylex';++import { useBoard } from '../BoardContext';+import { artboardActions } from '../store';++const styles = stylex.create({+ switcher: {+ alignItems: 'center',+ backgroundColor: 'transparent',+ borderRadius: sidebarRow.radius,+ display: 'flex',+ flexShrink: 1,+ gap: 8,+ height: sidebarRow.controlHeight,+ minWidth: 0,+ paddingInlineEnd: 8,+ paddingInlineStart: 10,+ },+ interactive: {+ backgroundColor: {+ ':hover': cssVar.colorFillTertiary,+ 'default': 'transparent',+ },+ cursor: 'pointer',+ },+ title: {+ color: cssVar.colorText,+ fontSize: sidebarRow.textFontSize,+ fontWeight: 600,+ maxWidth: 220,+ overflow: 'hidden',+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap',+ },+ page: {+ color: cssVar.colorTextSecondary,+ fontSize: 13,+ maxWidth: 160,+ overflow: 'hidden',+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap',+ },+ icon: {+ flex: 'none',+ },+});++const PageMenu = ({ className }: { className?: string }) => {+ const board = useBoard();+ const current = board.pages.find((page) => page.id === board.pageId);+ const multiPage = board.pages.length > 1 && !!current;++ const label = (+ <>+ <Icon+ color={cssVar.colorTextTertiary}+ icon={LayersIcon}+ size={16}+ {...stylex.props(styles.icon)}+ />+ <span {...stylex.props(styles.title)}>{board.artboard.title}</span>+ {multiPage && <span {...stylex.props(styles.page)}>{current.name}</span>}+ {multiPage && (+ <Icon+ color={cssVar.colorTextTertiary}+ icon={ChevronsUpDownIcon}+ size={14}+ {...stylex.props(styles.icon)}+ />+ )}+ </>+ );++ const items: DropdownItem[] = multiPage+ ? board.pages.map((page) => ({+ icon: <Icon icon={CheckIcon} style={{ opacity: page.id === current.id ? 1 : 0 }} />,+ key: page.id,+ label: page.name,+ onClick: () => artboardActions.setPage(page.id),+ }))+ : [];++ return (+ <div className={className} style={{ display: 'flex', minWidth: 0 }}>+ {multiPage ? (+ <DropdownMenu items={items} placement="bottomLeft">+ <div {...stylex.props(styles.switcher, styles.interactive)}>{label}</div>+ </DropdownMenu>+ ) : (+ <div {...stylex.props(styles.switcher)}>{label}</div>+ )}+ </div>+ );+};++export default PageMenu;diff --git a/src/features/Artboard/Board/ShareButton.tsx b/src/features/Artboard/Board/ShareButton.tsxnew file mode 100644index 00000000000..739c5dbf2c8--- /dev/null+++ b/src/features/Artboard/Board/ShareButton.tsx@@ -0,0 +1,89 @@+import { ActionIcon, Button, DropdownMenu } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import { GlobeIcon, LockIcon } from 'lucide-react';+import { useTranslation } from 'react-i18next';++import { useClientDataSWR } from '@/libs/swr';+import { artboardService } from '@/services/artboard';+import { useHeaderActionSize } from '@/styles/density';+import { sidebarRow } from '@/styles/density.stylex';++import { useBoard } from '../BoardContext';+import { floatStyles } from '../Viewport/floatStyles';+import { useArtboardShareTrigger } from './useArtboardShare';++const styles = stylex.create({+ button: {+ borderColor: cssVar.colorBorderSecondary,+ borderRadius: sidebarRow.radius,+ flex: 'none',+ fontSize: 12,+ gap: 6,+ height: sidebarRow.controlHeight,+ paddingInline: 10,+ },+ dot: {+ backgroundColor: cssVar.colorWarning,+ borderRadius: '50%',+ flex: 'none',+ height: 6,+ width: 6,+ },+});++const ShareButton = ({ compact }: { compact?: boolean }) => {+ const { t } = useTranslation('project');+ const headerActionSmallSize = useHeaderActionSize(true);+ const board = useBoard();+ const { id, revision } = board.artboard;+ const choices = board.artboard.content.rounds+ .map((round) => `${round.id}:${round.status}:${round.chosenBoardId ?? ''}`)+ .join(',');+ const { data, mutate } = useClientDataSWR(['artboard-publish', id, revision, choices], () =>+ artboardService.getPublish(id),+ );+ const trigger = useArtboardShareTrigger(id, data, () => mutate());++ if (trigger.kind === 'none') return null;++ const published = trigger.kind === 'menu';+ const icon = published ? GlobeIcon : LockIcon;+ const label = trigger.kind === 'action' ? trigger.action.label : t('artboard.share.trigger');+ const disabled = trigger.kind === 'action' && trigger.action.disabled;++ const button = compact ? (+ <ActionIcon+ disabled={disabled}+ icon={icon}+ size={headerActionSmallSize}+ title={label}+ onClick={trigger.kind === 'action' ? trigger.action.onClick : undefined}+ />+ ) : (+ <Button+ disabled={disabled}+ icon={icon}+ {...stylex.props(styles.button)}+ onClick={trigger.kind === 'action' ? trigger.action.onClick : undefined}+ >+ {label}+ {data?.hasUpdates && <span {...stylex.props(styles.dot)} />}+ </Button>+ );++ return (+ <>+ <span {...stylex.props(floatStyles.divider)} />+ {trigger.kind === 'action' ? (+ button+ ) : (+ <DropdownMenu items={trigger.items} placement={'bottomRight'}>+ {button}+ </DropdownMenu>+ )}+ </>+ );+};++export default ShareButton;diff --git a/src/features/Artboard/Board/StaleBanner.tsx b/src/features/Artboard/Board/StaleBanner.tsxnew file mode 100644index 00000000000..116f3eca471--- /dev/null+++ b/src/features/Artboard/Board/StaleBanner.tsx@@ -0,0 +1,62 @@+import { Button, Flexbox, Icon, Text } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import { RefreshCwIcon } from 'lucide-react';+import { useState } from 'react';+import { useTranslation } from 'react-i18next';++import { useBoard } from '../BoardContext';+import { refreshStaleArtboard } from '../data/revisionWatch';+import { useArtboardStore } from '../store';++const styles = stylex.create({+ bar: {+ backgroundColor: cssVar.colorInfoBg,+ borderBlockEndColor: cssVar.colorInfoBorder,+ borderBlockEndStyle: 'solid',+ borderBlockEndWidth: 1,+ flex: 'none',+ paddingBlock: 4,+ paddingInline: 12,+ },+});++const StaleBanner = () => {+ const { t } = useTranslation('project');+ const board = useBoard();+ const stale = useArtboardStore((s) => s.staleRevision);+ const [loading, setLoading] = useState(false);+ if (stale === null) return null;++ const refresh = async () => {+ setLoading(true);+ try {+ await refreshStaleArtboard(board.artboard.id);+ } finally {+ setLoading(false);+ }+ };++ return (+ <Flexbox+ horizontal+ align="center"+ gap={8}+ justify="space-between"+ {...stylex.props(styles.bar)}+ >+ <Text style={{ fontSize: 13 }}>{t('artboard.stale.title')}</Text>+ <Button+ icon={<Icon icon={RefreshCwIcon} />}+ loading={loading}+ size={'small'}+ type={'link'}+ onClick={refresh}+ >+ {t('artboard.stale.refresh')}+ </Button>+ </Flexbox>+ );+};++export default StaleBanner;diff --git a/src/features/Artboard/Board/States.tsx b/src/features/Artboard/Board/States.tsxnew file mode 100644index 00000000000..6ee0d096921--- /dev/null+++ b/src/features/Artboard/Board/States.tsx@@ -0,0 +1,40 @@+import { Button, Center, Empty, Spin } from '@lobehub/ui';+import { LayoutDashboardIcon, RotateCcwIcon, TriangleAlertIcon } from 'lucide-react';+import { useTranslation } from 'react-i18next';++export const BoardEmpty = () => {+ const { t } = useTranslation('project');+ return (+ <Center height={'100%'} padding={24}>+ <Empty+ description={t('artboard.empty.desc')}+ icon={LayoutDashboardIcon}+ title={t('artboard.empty.title')}+ />+ </Center>+ );+};++export const BoardLoading = () => (+ <Center flex={1} height={'100%'}>+ <Spin />+ </Center>+);++export const BoardError = ({ onRetry }: { onRetry: () => void }) => {+ const { t } = useTranslation('project');+ return (+ <Center flex={1} height={'100%'} padding={24}>+ <Empty+ description={t('artboard.error.desc')}+ icon={TriangleAlertIcon}+ title={t('artboard.error.title')}+ action={+ <Button icon={RotateCcwIcon} onClick={onRetry}>+ {t('artboard.error.retry')}+ </Button>+ }+ />+ </Center>+ );+};diff --git a/src/features/Artboard/Board/SubmitBar.tsx b/src/features/Artboard/Board/SubmitBar.tsxnew file mode 100644index 00000000000..b4795a52011--- /dev/null+++ b/src/features/Artboard/Board/SubmitBar.tsx@@ -0,0 +1,166 @@+import { Button, Flexbox } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import { Fragment, type ReactNode, useMemo, useState } from 'react';+import { useTranslation } from 'react-i18next';++import { useBoard } from '../BoardContext';+import { pendingThreads, summarizeRounds } from '../data/submitBatch';+import { useArtboardComments } from '../data/useArtboardComments';+import { artboardActions } from '../store';+import { artboardTokens } from '../tokens.stylex';+import { useSubmitBatch } from './useSubmitBatch';++const styles = stylex.create({+ bar: {+ alignItems: 'center',+ backgroundColor: cssVar.colorBgElevated,+ borderColor: cssVar.colorBorderSecondary,+ borderRadius: 999,+ borderStyle: 'solid',+ borderWidth: 1,+ boxShadow: artboardTokens.overlayShadow,+ display: 'flex',+ fontSize: 13,+ gap: 12,+ height: 44,+ insetBlockEnd: 'calc(12px + env(safe-area-inset-bottom, 0px))',+ insetInlineStart: '50%',+ lineHeight: 1,+ maxWidth: 'calc(100% - 248px)',+ paddingInlineEnd: 6,+ paddingInlineStart: 20,+ position: 'absolute',+ transform: 'translateX(-50%)',+ whiteSpace: 'nowrap',+ zIndex: 10,+ },+ raised: {+ insetBlockEnd: 'calc(64px + env(safe-area-inset-bottom, 0px))',+ maxWidth: 'calc(100% - 24px)',+ },+ title: {+ color: cssVar.colorText,+ flexShrink: 0,+ fontWeight: 500,+ maxWidth: 220,+ overflow: 'hidden',+ textOverflow: 'ellipsis',+ },+ muted: {+ color: cssVar.colorTextSecondary,+ minWidth: 0,+ overflow: 'hidden',+ textOverflow: 'ellipsis',+ },+ undecided: {+ color: {+ ':hover': cssVar.colorWarningTextHover,+ 'default': cssVar.colorWarningText,+ },+ cursor: 'pointer',+ textDecorationLine: 'underline',+ textUnderlineOffset: 3,+ },+ rule: {+ backgroundColor: cssVar.colorBorderSecondary,+ flex: 'none',+ height: 16,+ width: 1,+ },+ primary: {+ fontWeight: 500,+ height: 32,+ paddingInline: 14,+ },+});++const SubmitBar = ({ narrow }: { narrow: boolean }) => {+ const { t } = useTranslation('project');+ const board = useBoard();+ const submitBatch = useSubmitBatch();+ const { data: threads } = useArtboardComments(board.artboard.id);+ const [submitting, setSubmitting] = useState(false);+ const summary = useMemo(() => summarizeRounds(board.openRounds), [board.openRounds]);+ const comments = useMemo(() => pendingThreads(threads ?? []).length, [threads]);+ if (!summary.total && !comments) return null;++ const submit = async () => {+ setSubmitting(true);+ try {+ await submitBatch(board.openRounds.map((round) => round.id));+ } finally {+ setSubmitting(false);+ }+ };++ const showUndecided = () => {+ const round = board.openRounds.find((item) => item.id === summary.firstUndecidedId);+ const groupId = Object.keys(board.roundByGroupId).find(+ (id) => board.roundByGroupId[id].id === round?.id,+ );+ if (round && groupId)+ artboardActions.goTo({ id: groupId, kind: 'group', pageId: round.pageId });+ };++ const parts: { key: string; node: ReactNode }[] = [];+ if (summary.total && summary.undecided > 0)+ parts.push({+ key: 'undecided',+ node: (+ <span+ role={'button'}+ tabIndex={0}+ {...stylex.props(styles.undecided)}+ onClick={showUndecided}+ onKeyDown={(event) => {+ if (event.key === 'Enter' || event.key === ' ') showUndecided();+ }}+ >+ {t('artboard.submit.undecided', { count: summary.undecided })}+ </span>+ ),+ });+ else if (summary.total)+ parts.push({+ key: 'picked',+ node: summary.byRecommendation+ ? t('artboard.submit.status', { picked: summary.picked, rest: summary.byRecommendation })+ : t('artboard.submit.allPicked', { picked: summary.picked }),+ });+ if (summary.total && comments > 0)+ parts.push({ key: 'comments', node: t('artboard.submit.comments', { count: comments }) });++ return (+ <Flexbox horizontal {...stylex.props(styles.bar, narrow && styles.raised)}>+ <span {...stylex.props(styles.title)}>+ {summary.total+ ? t('artboard.submit.title', { count: summary.total })+ : t('artboard.submit.commentsTitle', { count: comments })}+ </span>+ {parts.length > 0 && (+ <span {...stylex.props(styles.muted)}>+ {parts.map((part, index) => (+ <Fragment key={part.key}>+ {index > 0 && ' · '}+ {part.node}+ </Fragment>+ ))}+ </span>+ )}+ <span {...stylex.props(styles.rule)} />+ <Button+ disabled={summary.undecided > 0}+ loading={submitting}+ shape={'round'}+ type={'primary'}+ {...stylex.props(styles.primary)}+ onClick={submit}+ >+ {t('artboard.submit.action')}+ </Button>+ </Flexbox>+ );+};++export default SubmitBar;diff --git a/src/features/Artboard/Board/headerChrome.test.ts b/src/features/Artboard/Board/headerChrome.test.tsnew file mode 100644index 00000000000..f300e7328f9--- /dev/null+++ b/src/features/Artboard/Board/headerChrome.test.ts@@ -0,0 +1,24 @@+import { describe, expect, it } from 'vitest';++import { headerChrome } from './headerChrome';++const noop = () => {};++describe('headerChrome', () => {+ // The board covers the window from its top-left corner, under the macOS traffic lights.+ it('clears the traffic lights and returns to the panel when the board covers the window', () => {+ expect(headerChrome({ onExitFullscreen: noop })).toEqual({+ coversWindow: true,+ exit: 'exitFullscreen',+ });+ });++ // The Works modal is inset from the window, so the lights never overlap it.+ it('just closes the Works modal, without clearing the traffic lights', () => {+ expect(headerChrome({ onClose: noop })).toEqual({ coversWindow: false, exit: 'close' });+ });++ it('offers to cover the window from the side panel', () => {+ expect(headerChrome({})).toEqual({ coversWindow: false, exit: 'enterFullscreen' });+ });+});diff --git a/src/features/Artboard/Board/headerChrome.ts b/src/features/Artboard/Board/headerChrome.tsnew file mode 100644index 00000000000..e421da61cb3--- /dev/null+++ b/src/features/Artboard/Board/headerChrome.ts@@ -0,0 +1,29 @@+/** What the header's window button does where the board is shown. */+export type HeaderExit = 'close' | 'enterFullscreen' | 'exitFullscreen';++export interface HeaderChrome {+ /**+ * The board covers the whole window: the header sits under the macOS traffic+ * lights, so it clears them and doubles as the window's title bar.+ */+ coversWindow: boolean;+ exit: HeaderExit;+}++/**+ * The board header's chrome for where the board is shown:+ * - covering the whole window (`onExitFullscreen`): returns the board to the side panel;+ * - in the Works modal (`onClose`): inset from the window, it just closes the modal;+ * - in the side panel: offers to cover the window.+ */+export const headerChrome = ({+ onClose,+ onExitFullscreen,+}: {+ onClose?: unknown;+ onExitFullscreen?: unknown;+}): HeaderChrome => {+ if (onClose) return { coversWindow: false, exit: 'close' };+ if (onExitFullscreen) return { coversWindow: true, exit: 'exitFullscreen' };+ return { coversWindow: false, exit: 'enterFullscreen' };+};diff --git a/src/features/Artboard/Board/index.tsx b/src/features/Artboard/Board/index.tsxnew file mode 100644index 00000000000..a338eaa3f54--- /dev/null+++ b/src/features/Artboard/Board/index.tsx@@ -0,0 +1,181 @@+'use client';++import { DraggablePanel, Flexbox } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import { useSize } from 'ahooks';+import { type ReactNode, useEffect, useRef } from 'react';++import { BoardProvider, useBoard } from '../BoardContext';+import Canvas from '../Canvas';+import AppBoardCapabilities from '../Canvas/AppCapabilities';+import { resolveArtboardFileBase } from '../data/fileBase';+import { useArtboard } from '../data/useArtboard';+import { useArtboardRevisionWatch } from '../data/useArtboardRevisionWatch';+import { artboardActions, artboardSelectors, useArtboardStore } from '../store';+import { useArtboardFeature } from '../useArtboardFeature';+import VerifyPanel from '../Verify';+import CheckTable from '../Verify/CheckTable';+import Header from './Header';+import Outline from './Outline';+import StaleBanner from './StaleBanner';+import { BoardEmpty, BoardError, BoardLoading } from './States';+import SubmitBar from './SubmitBar';++const NARROW_WIDTH = 768;++const styles = stylex.create({+ body: {+ backgroundColor: cssVar.colorBgLayout,+ display: 'flex',+ flex: '1',+ minHeight: 0,+ position: 'relative',+ },+ card: {+ backgroundColor: cssVar.colorBgElevated,+ borderColor: cssVar.colorBorderSecondary,+ borderRadius: 12,+ borderStyle: 'solid',+ borderWidth: 1,+ boxShadow: cssVar.boxShadowTertiary,+ height: 'calc(100% - 20px)',+ marginBlock: 10,+ marginInlineEnd: 10,+ overflow: 'hidden',+ },+ sheet: {+ backgroundColor: cssVar.colorBgContainer,+ inset: 0,+ position: 'absolute',+ zIndex: 20,+ },+ stage: {+ flex: '1',+ minWidth: 0,+ overflow: 'hidden',+ position: 'relative',+ },+});++const Stage = ({ narrow }: { narrow: boolean }) => {+ const board = useBoard();+ const { mode, outlineOpen, verifyView } = useArtboardStore((s) => ({+ mode: s.mode,+ outlineOpen: s.outlineOpen,+ verifyView: s.verifyView,+ }));++ if (!board.artboard.content.boards.length)+ return (+ <div {...stylex.props(styles.stage)}>+ <BoardEmpty />+ </div>+ );++ return (+ <div {...stylex.props(styles.stage)}>+ {mode === 'verify' && verifyView === 'list' ? <CheckTable narrow={narrow} /> : <Canvas />}+ {outlineOpen && !narrow && mode === 'discuss' && <Outline />}+ {mode === 'discuss' && <SubmitBar narrow={narrow} />}+ </div>+ );+};++const SidePanel = ({+ children,+ narrow,+ open,+}: {+ children: ReactNode;+ narrow: boolean;+ open: boolean;+}) => {+ if (narrow) return open ? <div {...stylex.props(styles.sheet)}>{children}</div> : null;+ return (+ <DraggablePanel+ backgroundColor={'transparent'}+ defaultSize={{ height: '100%', width: 390 }}+ expand={open}+ expandable={false}+ maxWidth={530}+ minWidth={310}+ placement={'right'}+ showBorder={false}+ >+ <div {...stylex.props(styles.card)}>{children}</div>+ </DraggablePanel>+ );+};++type BoardLayoutProps = Pick<BoardViewProps, 'onClose' | 'onExitFullscreen'>;++const BoardLayout = ({ onClose, onExitFullscreen }: BoardLayoutProps) => {+ const board = useBoard();+ useArtboardRevisionWatch(board.artboard);+ const rootRef = useRef<HTMLDivElement>(null);+ const size = useSize(rootRef);+ const narrow = !!size && size.width < NARROW_WIDTH;+ const selectedCheck = useArtboardStore(artboardSelectors.selectedCheckBoard(board));+ const { mode, verifyOpen, verifyView } = useArtboardStore((s) => ({+ mode: s.mode,+ verifyOpen: s.verifyOpen,+ verifyView: s.verifyView,+ }));+ const panelOpen = verifyOpen && (verifyView === 'board' || !!selectedCheck);++ useEffect(() => {+ if (size) artboardActions.setNarrow(narrow);+ }, [narrow, size]);++ return (+ <Flexbox data-artboard-root flex={1} height={'100%'} ref={rootRef} style={{ minWidth: 0 }}>+ <Header narrow={narrow} onClose={onClose} onExitFullscreen={onExitFullscreen} />+ <StaleBanner />+ <div {...stylex.props(styles.body)}>+ <Stage narrow={narrow} />+ {mode === 'verify' && (+ <SidePanel narrow={narrow} open={panelOpen}>+ <VerifyPanel+ onClose={narrow ? () => artboardActions.setVerifyOpen(false) : undefined}+ />+ </SidePanel>+ )}+ </div>+ </Flexbox>+ );+};++interface BoardViewProps {+ artboardId: string;+ /** Shown in the Works modal: the header offers to close it. */+ onClose?: () => void;+ /** Shown covering the whole window: the header offers to return to the side panel. */+ onExitFullscreen?: () => void;+}++const BoardView = ({ artboardId, onClose, onExitFullscreen }: BoardViewProps) => {+ const { enabled } = useArtboardFeature();+ const { data, error, isLoading, mutate } = useArtboard(artboardId);++ useEffect(() => {+ if (enabled) artboardActions.bindBoard(artboardId);+ }, [artboardId, enabled]);++ if (!enabled) return null;++ if (!data) {+ if (error && !isLoading) return <BoardError onRetry={() => void mutate()} />;+ return <BoardLoading />;+ }++ return (+ <BoardProvider artboard={data.artboard} fileBaseUrl={resolveArtboardFileBase(data.fileBaseUrl)}>+ <AppBoardCapabilities>+ <BoardLayout onClose={onClose} onExitFullscreen={onExitFullscreen} />+ </AppBoardCapabilities>+ </BoardProvider>+ );+};++export default BoardView;diff --git a/src/features/Artboard/Board/useArtboardShare.test.ts b/src/features/Artboard/Board/useArtboardShare.test.tsnew file mode 100644index 00000000000..d86e3ae0c71--- /dev/null+++ b/src/features/Artboard/Board/useArtboardShare.test.ts@@ -0,0 +1,127 @@+import { act, renderHook } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { type ArtboardShareState, useArtboardShareTrigger } from './useArtboardShare';++const mocks = vi.hoisted(() => ({+ confirmModal: vi.fn(),+ copyToClipboard: vi.fn(),+ openPublishConfirm: vi.fn(),+ publish: vi.fn(),+ toast: { error: vi.fn(), success: vi.fn() },+ unpublish: vi.fn(),+}));++vi.mock('@lobehub/ui', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ confirmModal: mocks.confirmModal,+ copyToClipboard: mocks.copyToClipboard,+ toast: mocks.toast,+}));+vi.mock('@/components/PublishConfirmModal', () => ({+ openPublishConfirm: mocks.openPublishConfirm,+}));+vi.mock('@/services/artboard', () => ({+ artboardService: { publish: mocks.publish, unpublish: mocks.unpublish },+}));++const state = (overrides: Partial<ArtboardShareState> = {}): ArtboardShareState => ({+ canPublish: true,+ hasUpdates: false,+ publishedUrl: null,+ ...overrides,+});++const trigger = (value: ArtboardShareState | undefined, refresh = vi.fn()) =>+ renderHook(() => useArtboardShareTrigger('art_1', value, refresh)).result.current;++const keysOf = (value: ReturnType<typeof trigger>) =>+ value.kind === 'menu' ? value.items.map((item) => item.key) : [];++beforeEach(() => {+ vi.clearAllMocks();+ mocks.publish.mockResolvedValue({ url: 'https://onboarding.lobe.page' });+ mocks.unpublish.mockResolvedValue(undefined);+});++describe('useArtboardShareTrigger', () => {+ it('offers nothing to someone who cannot share the board', () => {+ expect(trigger(undefined).kind).toBe('none');+ expect(trigger(state({ canPublish: false })).kind).toBe('none');+ });++ it('asks before the board becomes public, then copies the link', async () => {+ const refresh = vi.fn();+ const value = trigger(state(), refresh);+ if (value.kind !== 'action') throw new Error('expected a single share action');++ act(() => value.action.onClick());+ expect(mocks.publish).not.toHaveBeenCalled();+ const [{ onOk }] = mocks.openPublishConfirm.mock.calls[0];+ await act(async () => onOk());++ expect(mocks.publish).toHaveBeenCalledWith('art_1');+ expect(mocks.copyToClipboard).toHaveBeenCalledWith('https://onboarding.lobe.page');+ expect(refresh).toHaveBeenCalled();+ });++ it('puts updating first once the board has changed since it was shared', () => {+ expect(keysOf(trigger(state({ hasUpdates: true, publishedUrl: 'https://x' })))).toEqual([+ 'update',+ 'open',+ 'copy',+ 'unpublish',+ ]);+ expect(keysOf(trigger(state({ publishedUrl: 'https://x' })))).toEqual([+ 'open',+ 'copy',+ 'unpublish',+ ]);+ });++ it('confirms before taking the share down', async () => {+ const refresh = vi.fn();+ const value = trigger(state({ publishedUrl: 'https://x' }), refresh);+ if (value.kind !== 'menu') throw new Error('expected a menu');++ act(() => value.items.find((item) => item.key === 'unpublish')!.onClick());+ expect(mocks.unpublish).not.toHaveBeenCalled();+ const [{ onOk }] = mocks.confirmModal.mock.calls[0];+ await act(async () => onOk());++ expect(mocks.unpublish).toHaveBeenCalledWith('art_1');+ expect(refresh).toHaveBeenCalled();+ });++ it('shows the reason the server gave when sharing is refused', async () => {+ mocks.publish.mockRejectedValue(+ Object.assign(new Error('Board "Pricing" points at a Canvas version that is gone'), {+ data: { code: 'PRECONDITION_FAILED' },+ }),+ );+ const value = trigger(state());+ if (value.kind !== 'action') throw new Error('expected a single share action');++ act(() => value.action.onClick());+ const [{ onOk }] = mocks.openPublishConfirm.mock.calls[0];+ await act(async () => onOk());++ expect(mocks.toast.error).toHaveBeenCalledWith(+ 'Board "Pricing" points at a Canvas version that is gone',+ );+ });++ it('keeps the generic message for an unexpected failure', async () => {+ mocks.publish.mockRejectedValue(+ Object.assign(new Error('Artboard failed'), { data: { code: 'INTERNAL_SERVER_ERROR' } }),+ );+ const value = trigger(state());+ if (value.kind !== 'action') throw new Error('expected a single share action');++ act(() => value.action.onClick());+ const [{ onOk }] = mocks.openPublishConfirm.mock.calls[0];+ await act(async () => onOk());++ expect(mocks.toast.error).toHaveBeenCalledWith('artboard.share.failed');+ });+});diff --git a/src/features/Artboard/Board/useArtboardShare.ts b/src/features/Artboard/Board/useArtboardShare.tsnew file mode 100644index 00000000000..11862702f3c--- /dev/null+++ b/src/features/Artboard/Board/useArtboardShare.ts@@ -0,0 +1,119 @@+import { confirmModal, copyToClipboard, toast } from '@lobehub/ui';+import { useState } from 'react';+import { useTranslation } from 'react-i18next';++import { openPublishConfirm } from '@/components/PublishConfirmModal';+import { artboardService } from '@/services/artboard';++const serverReason = (error: unknown) => {+ const code = (error as { data?: { code?: string } } | undefined)?.data?.code;+ return code && code !== 'INTERNAL_SERVER_ERROR' ? (error as Error).message : undefined;+};++export interface ArtboardShareState {+ canPublish: boolean;+ hasUpdates: boolean;+ publishedUrl: string | null;+}++export interface ArtboardShareAction {+ danger?: boolean;+ disabled?: boolean;+ key: string;+ label: string;+ onClick: () => void;+}++export type ArtboardShareTrigger =+ | { kind: 'none' }+ | { action: ArtboardShareAction; kind: 'action' }+ | { items: ArtboardShareAction[]; kind: 'menu' };++export const useArtboardShareTrigger = (+ artboardId: string,+ state: ArtboardShareState | undefined,+ refresh: () => unknown,+): ArtboardShareTrigger => {+ const { t } = useTranslation(['project', 'common']);+ const [sharing, setSharing] = useState(false);++ if (!state?.canPublish) return { kind: 'none' };++ const publish = async () => {+ setSharing(true);+ try {+ const { url } = await artboardService.publish(artboardId);+ await refresh();+ await copyToClipboard(url);+ toast.success(t('artboard.share.copied'));+ } catch (error) {+ console.error('[Artboard] share failed', error);+ toast.error(serverReason(error) ?? t('artboard.share.failed'));+ } finally {+ setSharing(false);+ }+ };++ const confirmPublish = (okText: string) =>+ openPublishConfirm({+ note: t('artboard.share.note'),+ okText,+ onOk: () => publish(),+ privacy: t('artboard.share.privacy'),+ title: t('artboard.share.confirmTitle'),+ });++ const { publishedUrl } = state;+ if (!publishedUrl)+ return {+ action: {+ disabled: sharing,+ key: 'share',+ label: sharing ? t('artboard.share.sharing') : t('artboard.share.publish'),+ onClick: () => confirmPublish(t('artboard.share.publish')),+ },+ kind: 'action',+ };++ const unpublish = () =>+ confirmModal({+ cancelText: t('cancel', { ns: 'common' }),+ content: t('artboard.share.unpublishConfirm'),+ okButtonProps: { danger: true },+ okText: t('artboard.share.unpublish'),+ onOk: async () => {+ try {+ await artboardService.unpublish(artboardId);+ await refresh();+ toast.success(t('artboard.share.unpublished'));+ } catch (error) {+ console.error('[Artboard] stop sharing failed', error);+ toast.error(serverReason(error) ?? t('artboard.share.unpublishFailed'));+ }+ },+ });++ const items: ArtboardShareAction[] = [];+ if (state.hasUpdates)+ items.push({+ disabled: sharing,+ key: 'update',+ label: sharing ? t('artboard.share.sharing') : t('artboard.share.update'),+ onClick: () => confirmPublish(t('artboard.share.update')),+ });+ items.push(+ {+ key: 'open',+ label: t('artboard.share.open'),+ onClick: () => window.open(publishedUrl, '_blank', 'noopener,noreferrer'),+ },+ {+ key: 'copy',+ label: t('artboard.share.copy'),+ onClick: () =>+ void copyToClipboard(publishedUrl).then(() => toast.success(t('artboard.share.copied'))),+ },+ { danger: true, key: 'unpublish', label: t('artboard.share.unpublish'), onClick: unpublish },+ );+ return { items, kind: 'menu' };+};diff --git a/src/features/Artboard/Board/useSubmitBatch.ts b/src/features/Artboard/Board/useSubmitBatch.tsnew file mode 100644index 00000000000..555fdf2bf36--- /dev/null+++ b/src/features/Artboard/Board/useSubmitBatch.ts@@ -0,0 +1,34 @@+import { toast } from '@lobehub/ui';+import { useTranslation } from 'react-i18next';++import { useBoard } from '../BoardContext';+import { sendToBoardConversation } from '../data/boardConversation';+import { submitBoardBatch } from '../data/submitBatch';+import { mutateArtboard } from '../data/useArtboard';++export const useSubmitBatch = () => {+ const { t } = useTranslation('project');+ const board = useBoard();++ const notifyFailed = (message: string) =>+ toast.error({+ actions: [{ label: t('artboard.submit.resend'), onClick: () => void resend(message) }],+ title: t('artboard.submit.messageFailed'),+ });++ const resend = (message: string) =>+ sendToBoardConversation(board.artboard.topicId, message)+ .then((status) => status === 'messageFailed' && notifyFailed(message))+ .catch(() => notifyFailed(message));++ return async (roundIds: string[]) => {+ try {+ const { message, status } = await submitBoardBatch(board, roundIds);+ if (status === 'noConversation') toast.info(t('artboard.submit.noConversation'));+ if (status === 'messageFailed') notifyFailed(message);+ } catch (error) {+ void mutateArtboard(board.artboard.id);+ toast.error({ description: (error as Error).message, title: t('artboard.submit.failed') });+ }+ };+};diff --git a/src/features/Artboard/Board/useTitleBarInset.ts b/src/features/Artboard/Board/useTitleBarInset.tsnew file mode 100644index 00000000000..577bc6187f3--- /dev/null+++ b/src/features/Artboard/Board/useTitleBarInset.ts@@ -0,0 +1,7 @@+import { isDesktop } from '@/const/version';+import { useMacTrafficLightPadding } from '@/features/Electron/titlebar/useMacTrafficLightPadding';++const useDesktopInset = () => useMacTrafficLightPadding();+const useNoInset = () => 0;++export const useTitleBarInset = isDesktop ? useDesktopInset : useNoInset;diff --git a/src/features/Artboard/BoardContext.tsx b/src/features/Artboard/BoardContext.tsxnew file mode 100644index 00000000000..0b18c4799aa--- /dev/null+++ b/src/features/Artboard/BoardContext.tsx@@ -0,0 +1,28 @@+import type { ArtboardItem } from '@lobechat/types';+import { createContext, type ReactNode, use, useMemo } from 'react';++import { type BoardModel, buildBoardModel } from './model';+import { useArtboardStore } from './store';++const BoardContext = createContext<BoardModel | null>(null);++interface BoardProviderProps {+ artboard: ArtboardItem;+ children: ReactNode;+ fileBaseUrl: string | null;+}++export const BoardProvider = ({ artboard, children, fileBaseUrl }: BoardProviderProps) => {+ const pageId = useArtboardStore((s) => s.pageId);+ const model = useMemo(+ () => buildBoardModel(artboard, fileBaseUrl, pageId),+ [artboard, fileBaseUrl, pageId],+ );+ return <BoardContext value={model}>{children}</BoardContext>;+};++export const useBoard = () => {+ const model = use(BoardContext);+ if (!model) throw new Error('useBoard must be used inside BoardProvider');+ return model;+};diff --git a/src/features/Artboard/Canvas/AppCapabilities.tsx b/src/features/Artboard/Canvas/AppCapabilities.tsxnew file mode 100644index 00000000000..d08acd3ac38--- /dev/null+++ b/src/features/Artboard/Canvas/AppCapabilities.tsx@@ -0,0 +1,36 @@+import { toast } from '@lobehub/ui';+import { type ReactNode, useMemo } from 'react';++import { useBoard } from '../BoardContext';+import { chooseOption } from '../data/actions';+import { useAgentRunningInTopic } from '../data/agentRunning';+import { boardFileUrl } from '../model';+import { useJourneyView } from '../Verify/useJourneyView';+import { type BoardCapabilities, BoardCapabilitiesProvider } from '../Viewport/capabilities';+import BoardFrame from './BoardFrame';++const AppBoardCapabilities = ({ children }: { children: ReactNode }) => {+ const board = useBoard();+ const journey = useJourneyView();+ const artboardId = board.artboard.id;+ const { fileBaseUrl } = board;+ const agentRunning = useAgentRunningInTopic(board.artboard.topicId);+ const value = useMemo<BoardCapabilities>(+ () => ({+ agentRunning,+ journey,+ onPick: (roundId, boardId) =>+ void chooseOption(artboardId, roundId, boardId).catch((error) =>+ toast.error((error as Error).message),+ ),+ renderCanvas: (item) => {+ const src = boardFileUrl({ fileBaseUrl }, item);+ return src ? <BoardFrame src={src} title={item.title} /> : null;+ },+ }),+ [agentRunning, artboardId, fileBaseUrl, journey],+ );+ return <BoardCapabilitiesProvider value={value}>{children}</BoardCapabilitiesProvider>;+};++export default AppBoardCapabilities;diff --git a/src/features/Artboard/Canvas/BoardBody.test.tsx b/src/features/Artboard/Canvas/BoardBody.test.tsxnew file mode 100644index 00000000000..3bfc13a8d10--- /dev/null+++ b/src/features/Artboard/Canvas/BoardBody.test.tsx@@ -0,0 +1,70 @@+import type { ArtboardBoardView } from '@lobechat/types';+import { render, screen } from '@testing-library/react';+import { describe, expect, it, vi } from 'vitest';++import { type BoardCapabilities, BoardCapabilitiesProvider } from '../Viewport/capabilities';+import BoardBody from './BoardBody';++const board = (patch: Partial<ArtboardBoardView> = {}): ArtboardBoardView => ({+ expected: null,+ flowNodeId: null,+ groupId: null,+ id: 'brd_1',+ pageId: 'pg_1',+ rect: { h: 400, w: 640, x: 0, y: 0 },+ roundId: null,+ source: { hash: null, kind: 'file', path: 'pages/home.html' },+ title: 'Home',+ type: 'html',+ ...patch,+});++const renderBody = (item: ArtboardBoardView, capabilities: Partial<BoardCapabilities> = {}) => {+ const renderCanvas = vi.fn(() => <iframe title="canvas" />);+ render(+ <BoardCapabilitiesProvider value={{ renderCanvas, ...capabilities }}>+ <BoardBody live board={item} />+ </BoardCapabilitiesProvider>,+ );+ return renderCanvas;+};++describe('BoardBody with a file that does not exist', () => {+ it('shows that the board is being written while an agent runs in its topic', () => {+ const renderCanvas = renderBody(board(), { agentRunning: true });++ expect(screen.getByText('artboard.board.generating')).toBeTruthy();+ expect(screen.queryByText('artboard.board.fileMissing')).toBeNull();+ expect(renderCanvas).not.toHaveBeenCalled();+ });++ it('names the missing file when no agent is running', () => {+ const renderCanvas = renderBody(board());++ expect(screen.getByText('artboard.board.fileMissing')).toBeTruthy();+ expect(screen.queryByText('artboard.board.generating')).toBeNull();+ expect(renderCanvas).not.toHaveBeenCalled();+ });++ it('treats an image board without its file the same way', () => {+ renderBody(+ board({ source: { hash: null, kind: 'file', path: 'shots/a.png' }, type: 'image' }),+ {+ agentRunning: true,+ },+ );++ expect(screen.getByText('artboard.board.generating')).toBeTruthy();+ expect(screen.queryByRole('img')).toBeNull();+ });++ it('renders the canvas once the file exists', () => {+ const renderCanvas = renderBody(+ board({ source: { hash: 'etag_1', kind: 'file', path: 'pages/home.html' } }),+ { agentRunning: true },+ );++ expect(renderCanvas).toHaveBeenCalled();+ expect(screen.queryByText('artboard.board.generating')).toBeNull();+ });+});diff --git a/src/features/Artboard/Canvas/BoardBody.tsx b/src/features/Artboard/Canvas/BoardBody.tsxnew file mode 100644index 00000000000..ce5a885371a--- /dev/null+++ b/src/features/Artboard/Canvas/BoardBody.tsx@@ -0,0 +1,94 @@+import type { ArtboardBoardView } from '@lobechat/types';+import * as stylex from '@stylexjs/stylex';+import { FilePenLineIcon, FileXIcon, ImageOffIcon } from 'lucide-react';+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import { useBoardCapabilities } from '../Viewport/capabilities';+import BoardPlaceholder from './BoardPlaceholder';+import DecisionPill from './DecisionPill';+import { canvasStyles } from './styles';++const styles = stylex.create({+ canvas: {+ display: 'flex',+ flexDirection: 'column',+ height: '100%',+ width: '100%',+ },+ image: {+ display: 'block',+ height: '100%',+ objectFit: 'cover',+ objectPosition: 'top',+ width: '100%',+ },+});++const LiveCanvas = memo<{ board: ArtboardBoardView }>(({ board }) => {+ const { renderCanvas } = useBoardCapabilities();+ return <div {...stylex.props(styles.canvas, canvasStyles.inert)}>{renderCanvas(board)}</div>;+});++LiveCanvas.displayName = 'ArtboardLiveCanvas';++interface BoardBodyProps {+ board: ArtboardBoardView;+ imageUrl?: string;+ k?: number;+ live: boolean;+ screenshotUrl?: string;+}++const BoardBody = ({ board, imageUrl, k = 1, live, screenshotUrl }: BoardBodyProps) => {+ const { t } = useTranslation('project');+ const { agentRunning } = useBoardCapabilities();+ if (screenshotUrl)+ return (+ <img+ alt={board.title}+ draggable={false}+ src={screenshotUrl}+ {...stylex.props(styles.image)}+ />+ );++ const { source } = board;+ if (board.type === 'decision')+ return <DecisionPill height={board.rect.h} k={k} title={board.title} width={board.rect.w} />;+ // The board points at a file that is not written yet (or was deleted).+ if (source && !source.hash)+ return agentRunning ? (+ <BoardPlaceholder+ icon={FilePenLineIcon}+ k={k}+ status={t('artboard.board.generating')}+ title={board.title}+ />+ ) : (+ <BoardPlaceholder+ icon={FileXIcon}+ k={k}+ status={t('artboard.board.fileMissing', { path: source.path })}+ title={board.title}+ />+ );+ if (!source || (board.type === 'image' && !imageUrl))+ return (+ <BoardPlaceholder+ icon={ImageOffIcon}+ k={k}+ status={t('artboard.board.sourceMissing')}+ title={board.title}+ />+ );+ if (board.type === 'image')+ return (+ <img alt={board.title} draggable={false} src={imageUrl} {...stylex.props(styles.image)} />+ );++ if (!live) return <BoardPlaceholder k={k} title={board.title} />;+ return <LiveCanvas board={board} />;+};++export default BoardBody;diff --git a/src/features/Artboard/Canvas/BoardFrame.tsx b/src/features/Artboard/Canvas/BoardFrame.tsxnew file mode 100644index 00000000000..357a896d679--- /dev/null+++ b/src/features/Artboard/Canvas/BoardFrame.tsx@@ -0,0 +1,34 @@+import * as stylex from '@stylexjs/stylex';+import { memo } from 'react';++const styles = stylex.create({+ frame: {+ backgroundColor: 'transparent',+ borderWidth: 0,+ flex: '1',+ minHeight: 0,+ width: '100%',+ },+});++interface BoardFrameProps {+ src: string;+ title: string;+}++// Board pages are served from the app's own origin; the sandbox must never grant+// `allow-same-origin`, or a page could read the app's cookies and storage.+const BoardFrame = memo<BoardFrameProps>(({ src, title }) => (+ <iframe+ {...stylex.props(styles.frame)}+ loading={'lazy'}+ referrerPolicy={'no-referrer'}+ sandbox={'allow-scripts allow-popups allow-forms'}+ src={src}+ title={title}+ />+));++BoardFrame.displayName = 'ArtboardBoardFrame';++export default BoardFrame;diff --git a/src/features/Artboard/Canvas/BoardLabel.test.tsx b/src/features/Artboard/Canvas/BoardLabel.test.tsxnew file mode 100644index 00000000000..20d1beb06e7--- /dev/null+++ b/src/features/Artboard/Canvas/BoardLabel.test.tsx@@ -0,0 +1,35 @@+import type { ArtboardBoardView } from '@lobechat/types';+import { render, screen } from '@testing-library/react';+import { describe, expect, it } from 'vitest';++import BoardLabel from './BoardLabel';++const board: ArtboardBoardView = {+ expected: null,+ flowNodeId: null,+ groupId: null,+ id: 'brd_1',+ pageId: 'pg_1',+ rect: { h: 400, w: 640, x: 0, y: 0 },+ roundId: null,+ source: { hash: 'h_1', kind: 'file', path: 'pages/home.html' },+ title: 'Home',+ type: 'html',+};++describe('BoardLabel', () => {+ it('shows the title of a board backed by an artboard file', () => {+ render(+ <BoardLabel+ board={board}+ k={1}+ linked={false}+ recommended={false}+ selected={false}+ verify={false}+ />,+ );++ expect(screen.getByText('Home')).toBeTruthy();+ });+});diff --git a/src/features/Artboard/Canvas/BoardLabel.tsx b/src/features/Artboard/Canvas/BoardLabel.tsxnew file mode 100644index 00000000000..55ea6489bc0--- /dev/null+++ b/src/features/Artboard/Canvas/BoardLabel.tsx@@ -0,0 +1,194 @@+import type { ArtboardBoardView } from '@lobechat/types';+import { Icon } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import { ImageIcon, LockIcon, StarIcon } from 'lucide-react';+import { useTranslation } from 'react-i18next';++import { flowStateColor } from '@/features/Acceptance/Viewer/Flow/flowStateColor';+import { sx } from '@/styles/sx';++import StatusTag, { stateIcon } from '../StatusTag';+import { artboardTokens } from '../tokens.stylex';+import { type FlowNodeState, isFlagged } from '../Verify/flow';+import {+ BOARD_LABEL_FONT,+ boardLabelLayout,+ boardLabelScale,+ tagWidth,+ textWidth,+} from './boardLabelLayout';+import ChoiceRadio, { type BoardChoice, RADIO_WIDTH } from './ChoiceRadio';+import RecommendBadge from './RecommendBadge';++const ICON_WIDTH = 16;+const LOCK_WIDTH = 18;+const STATUS_TAG_WIDTH = 84;+const STATUS_TAG_MIN_ROW = 260;++const styles = stylex.create({+ icon: {+ color: cssVar.colorTextTertiary,+ flexShrink: 0,+ marginBlockStart: 5,+ },+ kind: {+ marginInlineEnd: 4,+ },+ lock: {+ marginInlineStart: 6,+ },+ row: {+ alignItems: 'flex-start',+ color: cssVar.colorTextSecondary,+ display: 'flex',+ fontSize: 12,+ height: 24,+ insetBlockEnd: '100%',+ insetInlineStart: 0,+ paddingBlockEnd: 2,+ position: 'absolute',+ transformOrigin: '0 100%',+ whiteSpace: 'nowrap',+ },+ spacer: {+ flexGrow: 1,+ },+ star: {+ color: artboardTokens.accent,+ flexShrink: 0,+ marginBlockStart: 5,+ marginInlineStart: 5,+ },+ state: {+ flexShrink: 0,+ marginBlockStart: 5,+ marginInlineEnd: 4,+ },+ status: {+ flexShrink: 0,+ marginInlineStart: 6,+ },+ tag: {+ borderColor: `color-mix(in srgb, ${artboardTokens.accent} 35%, transparent)`,+ borderRadius: 4,+ borderStyle: 'solid',+ borderWidth: 1,+ color: artboardTokens.accentStrong,+ flexShrink: 0,+ fontSize: 10,+ lineHeight: '13px',+ marginBlockStart: 4,+ marginInlineStart: 6,+ paddingInline: 4,+ },+ title: {+ flexGrow: '0',+ flexShrink: '1',+ flexBasis: 'auto',+ lineHeight: '16px',+ minWidth: 0,+ overflow: 'hidden',+ paddingBlockStart: 3,+ textOverflow: 'ellipsis',+ },+ titleSelected: {+ color: artboardTokens.selection,+ },+});++interface BoardLabelProps {+ board: ArtboardBoardView;+ choice?: BoardChoice;+ k: number;+ linked: boolean;+ recommended: boolean;+ selected: boolean;+ state?: FlowNodeState;+ verify: boolean;+}++const BoardLabel = ({+ board,+ choice,+ k,+ linked,+ recommended,+ selected,+ state,+ verify,+}: BoardLabelProps) => {+ const { t } = useTranslation('project');+ const flagged = verify && linked && isFlagged(state);+ if (board.type === 'decision' && !flagged) return null;++ const recommendedText = t('artboard.board.recommended');+ const image = board.type === 'image';+ const locked = linked && !verify;+ const rowScale = boardLabelScale(k, board.rect.w);+ const statusTag = flagged && !!rowScale && (board.rect.w * k) / rowScale >= STATUS_TAG_MIN_ROW;+ const layout = boardLabelLayout({+ boardWidth: board.rect.w,+ k,+ lead: (choice ? RADIO_WIDTH : 0) + (flagged && !statusTag ? ICON_WIDTH : 0),+ recommended,+ tag: tagWidth(recommendedText),+ title: textWidth(board.title, BOARD_LABEL_FONT) + (image ? ICON_WIDTH : 0),+ trail: (locked ? LOCK_WIDTH : 0) + (statusTag ? STATUS_TAG_WIDTH : 0),+ });+ const badge = layout.badge && (+ <RecommendBadge k={k} label={recommendedText} width={board.rect.w} />+ );+ const { label } = layout;+ if (!label) return badge || null;++ return (+ <>+ <div+ {...sx(styles.row, {+ transform: `scale(${label.scale / k})`,+ width: label.width,+ })}+ >+ {flagged && !statusTag && (+ <Icon+ color={flowStateColor(state)}+ icon={stateIcon(state)}+ size={12}+ {...stylex.props(styles.state)}+ />+ )}+ {choice && <ChoiceRadio {...choice} />}+ {image && <ImageIcon size={12} {...stylex.props(styles.icon, styles.kind)} />}+ <span title={board.title} {...stylex.props(styles.title, selected && styles.titleSelected)}>+ {board.title}+ </span>+ {label.mark === 'tag' && <span {...stylex.props(styles.tag)}>{recommendedText}</span>}+ {label.mark === 'star' && (+ <span aria-label={recommendedText} role="img" title={recommendedText}>+ <StarIcon+ fill="currentColor"+ size={12}+ strokeWidth={1.5}+ {...stylex.props(styles.star)}+ />+ </span>+ )}+ <span {...stylex.props(styles.spacer)} />+ {locked && (+ <span title={t('artboard.board.locked')}>+ <LockIcon size={12} {...stylex.props(styles.icon, styles.lock)} />+ </span>+ )}+ {statusTag && (+ <span {...stylex.props(styles.status)}>+ <StatusTag state={state} />+ </span>+ )}+ </div>+ {badge}+ </>+ );+};++export default BoardLabel;diff --git a/src/features/Artboard/Canvas/BoardNode.tsx b/src/features/Artboard/Canvas/BoardNode.tsxnew file mode 100644index 00000000000..e9bb1588793--- /dev/null+++ b/src/features/Artboard/Canvas/BoardNode.tsx@@ -0,0 +1,127 @@+import type { ArtboardBoardView } from '@lobechat/types';++import { flowStateColor } from '@/features/Acceptance/Viewer/Flow/flowStateColor';+import { sx } from '@/styles/sx';++import { useBoard } from '../BoardContext';+import { boardFileUrl, type BoardModel } from '../model';+import { artboardActions, useArtboardStore } from '../store';+import { isFlagged, nodeScreenshot, nodeState } from '../Verify/flow';+import { useBoardCapabilities } from '../Viewport/capabilities';+import BoardBody from './BoardBody';+import BoardLabel from './BoardLabel';+import CompareBody from './CompareBody';+import { canvasStyles } from './styles';++const SELECTION_STROKE = 1.5;+const PICKED_STROKE = 3;+const STATE_STROKE = 2;+const FRAME_RADIUS = 2;++const isRelated = (board: BoardModel, selected: string | null, id: string) =>+ !!selected &&+ selected !== id &&+ !!board.journeyGroupId &&+ board.boardById[selected]?.groupId === board.journeyGroupId &&+ board.edges.some(+ (e) => (e.from === selected && e.to === id) || (e.to === selected && e.from === id),+ );++interface BoardNodeProps {+ board: ArtboardBoardView;+ k: number;+ live: boolean;+}++const BoardNode = ({ board: item, k, live }: BoardNodeProps) => {+ const board = useBoard();+ const { journey, onPick } = useBoardCapabilities();+ const s = useArtboardStore((st) => ({+ compare: st.compare,+ flash: st.flash.includes(item.id),+ related: st.mode === 'discuss' && isRelated(board, st.selected, item.id),+ selected: st.selected === item.id,+ verify: st.mode === 'verify',+ }));++ const inJourney = !!board.journeyGroupId && item.groupId === board.journeyGroupId;+ const muted = s.verify && !inJourney;+ const state = inJourney ? nodeState(journey, item.id) : undefined;+ const border = s.verify && isFlagged(state) ? flowStateColor(state) : undefined;+ const screenshotUrl = s.verify && inJourney ? nodeScreenshot(journey, item.id) : undefined;+ const compare = s.selected && screenshotUrl ? s.compare : 'real';+ const imageUrl = item.type === 'image' ? boardFileUrl(board, item) : undefined;+ const { rect } = item;+ const round = item.groupId ? board.roundByGroupId[item.groupId] : undefined;+ const option = !s.verify && round && round.id === item.roundId ? round : undefined;+ const picked = option?.chosenBoardId === item.id;+ const framed = picked || !!border;+ const outlined = s.selected || s.related;++ return (+ <div+ data-board-item+ data-item-id={item.id}+ {...sx(canvasStyles.board, canvasStyles.appear, muted && canvasStyles.muted, {+ height: rect.h,+ left: rect.x,+ top: rect.y,+ width: rect.w,+ })}+ onClick={(e) => {+ e.stopPropagation();+ artboardActions.select(item.id);+ }}+ >+ <BoardLabel+ board={item}+ k={k}+ linked={board.finalized && inJourney}+ recommended={board.recommendedIds.has(item.id)}+ selected={s.selected}+ state={state}+ verify={s.verify}+ choice={+ option && {+ checked: picked,+ disabled: option.status !== 'open' || board.finalized || !onPick,+ onPick: () => onPick?.(option.id, item.id),+ }+ }+ />+ <div+ {...sx(+ canvasStyles.boardCard,+ item.type === 'decision' && canvasStyles.boardBare,+ s.selected && canvasStyles.boardSelected,+ !s.selected && s.related && canvasStyles.boardRelated,+ s.flash && canvasStyles.flash,+ outlined ? { outlineWidth: SELECTION_STROKE / k } : undefined,+ )}+ >+ {compare === 'split' && screenshotUrl ? (+ <CompareBody board={item} imageUrl={imageUrl} k={k} screenshotUrl={screenshotUrl} />+ ) : (+ <BoardBody+ board={item}+ imageUrl={imageUrl}+ k={k}+ live={live}+ screenshotUrl={compare === 'design' ? undefined : screenshotUrl}+ />+ )}+ {framed && (+ <div+ {...sx(canvasStyles.boardFrame, {+ borderColor: border,+ borderRadius: FRAME_RADIUS / k,+ borderWidth: (border ? STATE_STROKE : PICKED_STROKE) / k,+ })}+ />+ )}+ </div>+ </div>+ );+};++export default BoardNode;diff --git a/src/features/Artboard/Canvas/BoardPlaceholder.tsx b/src/features/Artboard/Canvas/BoardPlaceholder.tsxnew file mode 100644index 00000000000..d99b98f1493--- /dev/null+++ b/src/features/Artboard/Canvas/BoardPlaceholder.tsx@@ -0,0 +1,102 @@+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import type { LucideIcon } from 'lucide-react';++import { sx } from '@/styles/sx';++const MIN_LABEL_ZOOM = 0.25;++const styles = stylex.create({+ icon: {+ display: 'block',+ flexShrink: 0,+ opacity: 0.22,+ },+ label: {+ alignItems: 'center',+ boxSizing: 'border-box',+ color: cssVar.colorText,+ display: 'flex',+ flexDirection: 'column',+ gap: 12,+ insetBlockStart: '50%',+ insetInlineStart: '50%',+ justifyContent: 'center',+ overflow: 'hidden',+ padding: 8,+ position: 'absolute',+ textAlign: 'center',+ },+ layer: {+ inset: 0,+ pointerEvents: 'none',+ position: 'absolute',+ },+ status: {+ color: cssVar.colorTextTertiary,+ fontSize: 12,+ lineHeight: '16px',+ overflow: 'hidden',+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap',+ },+ text: {+ display: 'flex',+ flexDirection: 'column',+ gap: 4,+ maxWidth: '100%',+ },+ title: {+ color: cssVar.colorTextSecondary,+ fontSize: 13,+ fontWeight: 500,+ lineHeight: '18px',+ overflow: 'hidden',+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap',+ },+ resting: {+ outlineColor: cssVar.colorBorderSecondary,+ outlineStyle: 'solid',+ },+ waiting: {+ backgroundColor: cssVar.colorFillQuaternary,+ outlineColor: cssVar.colorTextQuaternary,+ outlineStyle: 'dashed',+ },+});++interface BoardPlaceholderProps {+ icon?: LucideIcon;+ k: number;+ status?: string;+ title: string;+}++const BoardPlaceholder = ({ icon: StatusIcon, k, status, title }: BoardPlaceholderProps) => {+ const labelZoom = Math.max(k, MIN_LABEL_ZOOM);+ return (+ <div+ {...sx(styles.layer, status ? styles.waiting : styles.resting, {+ outlineOffset: -1 / k,+ outlineWidth: 1 / k,+ })}+ >+ <div+ {...sx(styles.label, {+ height: `${100 * labelZoom}%`,+ transform: `translate(-50%, -50%) scale(${1 / labelZoom})`,+ width: `${100 * labelZoom}%`,+ })}+ >+ {StatusIcon && <StatusIcon size={24} {...stylex.props(styles.icon)} />}+ <span {...stylex.props(styles.text)}>+ <span {...stylex.props(styles.title)}>{title}</span>+ {status && <span {...stylex.props(styles.status)}>{status}</span>}+ </span>+ </div>+ </div>+ );+};++export default BoardPlaceholder;diff --git a/src/features/Artboard/Canvas/ChoiceRadio.tsx b/src/features/Artboard/Canvas/ChoiceRadio.tsxnew file mode 100644index 00000000000..40588357d77--- /dev/null+++ b/src/features/Artboard/Canvas/ChoiceRadio.tsx@@ -0,0 +1,64 @@+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';++import { artboardTokens } from '../tokens.stylex';++export const RADIO_WIDTH = 20;++export interface BoardChoice {+ checked: boolean;+ disabled: boolean;+ onPick: () => void;+}++const styles = stylex.create({+ checked: {+ borderColor: {+ ':hover': artboardTokens.accent,+ 'default': artboardTokens.accent,+ },+ borderWidth: 4.5,+ cursor: 'default',+ },+ disabled: {+ borderColor: {+ ':hover': cssVar.colorTextQuaternary,+ 'default': cssVar.colorTextQuaternary,+ },+ cursor: 'default',+ opacity: 0.6,+ },+ radio: {+ backgroundColor: cssVar.colorBgContainer,+ borderColor: {+ ':hover': artboardTokens.accent,+ 'default': cssVar.colorTextQuaternary,+ },+ borderRadius: '50%',+ borderStyle: 'solid',+ borderWidth: 1.5,+ boxSizing: 'border-box',+ cursor: 'pointer',+ flexShrink: 0,+ height: 14,+ marginBlockStart: 4,+ marginInlineEnd: 6,+ pointerEvents: 'auto',+ width: 14,+ },+});++const ChoiceRadio = ({ checked, disabled, onPick }: BoardChoice) => (+ <span+ aria-checked={checked}+ aria-disabled={disabled}+ role="radio"+ {...stylex.props(styles.radio, disabled && styles.disabled, checked && styles.checked)}+ onClick={(event) => {+ event.stopPropagation();+ if (!disabled && !checked) onPick();+ }}+ />+);++export default ChoiceRadio;diff --git a/src/features/Artboard/Canvas/CommentLayer.tsx b/src/features/Artboard/Canvas/CommentLayer.tsxnew file mode 100644index 00000000000..833c064b8e0--- /dev/null+++ b/src/features/Artboard/Canvas/CommentLayer.tsx@@ -0,0 +1,85 @@+import { useEffect, useMemo, useRef } from 'react';++import { useBoard } from '../BoardContext';+import CommentPopover from '../Comments/CommentPopover';+import DraftCard from '../Comments/DraftCard';+import { pinTone, threadNumbers } from '../Comments/layout';+import Pin from '../Comments/Pin';+import ThreadCard from '../Comments/ThreadCard';+import { pagePins } from '../data/commentModel';+import { useArtboardComments } from '../data/useArtboardComments';+import { artboardActions, useArtboardStore } from '../store';+import { ownsEscape } from './escapeScope';+import type { ViewState } from './useViewport';++const close = () => artboardActions.openThread(null);++interface CommentLayerProps {+ size: { height: number; width: number } | undefined;+ view: ViewState;+}++const CommentLayer = ({ size, view }: CommentLayerProps) => {+ const board = useBoard();+ const { data: threads } = useArtboardComments(board.artboard.id);+ const { draft, openThreadId, tool } = useArtboardStore((s) => ({+ draft: s.draft,+ openThreadId: s.openThreadId,+ tool: s.tool,+ }));+ const pins = useMemo(() => pagePins(threads ?? [], board), [threads, board]);+ const numbers = useMemo(() => threadNumbers(threads ?? []), [threads]);+ const open = pins.find((pin) => pin.thread.id === openThreadId);+ const active = !!draft || !!open;+ const marker = useRef<HTMLSpanElement>(null);++ useEffect(() => {+ if (!active) return;+ const onKey = (event: KeyboardEvent) => {+ const root = marker.current?.closest('[data-artboard-root]') ?? null;+ if (!ownsEscape(event, root)) return;+ event.stopImmediatePropagation();+ close();+ };+ window.addEventListener('keydown', onKey, true);+ return () => window.removeEventListener('keydown', onKey, true);+ }, [active]);++ const toScreen = (x: number, y: number) => ({ x: x * view.k + view.x, y: y * view.k + view.y });+ const anchor = open ? toScreen(open.x, open.y) : draft ? toScreen(draft.x, draft.y) : undefined;++ return (+ <>+ <span hidden ref={marker} />+ {pins.map(({ thread, x, y }) => {+ const current = thread.id === openThreadId;+ if (thread.resolvedAt && tool !== 'comment' && !current) return null;+ const number = numbers.get(thread.id);+ return (+ <Pin+ at={toScreen(x, y)}+ key={thread.id}+ label={number ? `#${number}` : undefined}+ number={number}+ open={current}+ tone={pinTone(thread)}+ unsent={thread.unread}+ onClick={() => artboardActions.openThread(current ? null : thread.id)}+ />+ );+ })}+ {draft && anchor && <Pin open at={anchor} />}+ {anchor && size && (+ <CommentPopover anchor={anchor} size={size}>+ {open ? (+ <ThreadCard number={numbers.get(open.thread.id)} thread={open.thread} onClose={close} />+ ) : (+ draft && <DraftCard draft={draft} />+ )}+ </CommentPopover>+ )}+ </>+ );+};++export default CommentLayer;diff --git a/src/features/Artboard/Canvas/CompareBody.tsx b/src/features/Artboard/Canvas/CompareBody.tsxnew file mode 100644index 00000000000..5e4aeefb908--- /dev/null+++ b/src/features/Artboard/Canvas/CompareBody.tsx@@ -0,0 +1,89 @@+import type { ArtboardBoardView } from '@lobechat/types';+import { Tag } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import type { ReactNode } from 'react';+import { useTranslation } from 'react-i18next';++import { sx } from '@/styles/sx';++import BoardBody from './BoardBody';++const styles = stylex.create({+ half: {+ backgroundColor: cssVar.colorBgLayout,+ flex: '1',+ minWidth: 0,+ overflow: 'hidden',+ position: 'relative',+ },+ label: {+ insetBlockStart: 8,+ insetInlineStart: 8,+ position: 'absolute',+ },+ root: {+ display: 'flex',+ gap: 2,+ height: '100%',+ width: '100%',+ },+ scaled: {+ insetInlineStart: 0,+ pointerEvents: 'none',+ position: 'absolute',+ transformOrigin: '0 0',+ },+});++const Half = ({+ board,+ children,+ label,+}: {+ board: ArtboardBoardView;+ children: ReactNode;+ label: string;+}) => {+ const { h, w } = board.rect;+ return (+ <div {...stylex.props(styles.half)}>+ <div+ {...sx(styles.scaled, {+ height: h,+ top: h / 4,+ transform: 'scale(0.5)',+ width: w,+ })}+ >+ {children}+ </div>+ <Tag size={'small'} {...stylex.props(styles.label)}>+ {label}+ </Tag>+ </div>+ );+};++interface CompareBodyProps {+ board: ArtboardBoardView;+ imageUrl?: string;+ k: number;+ screenshotUrl: string;+}++const CompareBody = ({ board, imageUrl, k, screenshotUrl }: CompareBodyProps) => {+ const { t } = useTranslation('project');+ return (+ <div {...stylex.props(styles.root)}>+ <Half board={board} label={t('artboard.compare.design')}>+ <BoardBody live board={board} imageUrl={imageUrl} k={k / 2} />+ </Half>+ <Half board={board} label={t('artboard.compare.real')}>+ <BoardBody live board={board} k={k / 2} screenshotUrl={screenshotUrl} />+ </Half>+ </div>+ );+};++export default CompareBody;diff --git a/src/features/Artboard/Canvas/DecisionPill.tsx b/src/features/Artboard/Canvas/DecisionPill.tsxnew file mode 100644index 00000000000..ff416c6ad1c--- /dev/null+++ b/src/features/Artboard/Canvas/DecisionPill.tsx@@ -0,0 +1,86 @@+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';++import { sx } from '@/styles/sx';++import { textWidth } from './boardLabelLayout';++const PILL_HEIGHT = 96;+const FONT_SIZE = 40;+const MIN_FONT_SIZE = 20;+const GLYPH = 28;+const GLYPH_GAP = 16;+const PADDING = 40;++const styles = stylex.create({+ glyph: {+ fill: 'none',+ flexShrink: 0,+ stroke: cssVar.colorText,+ strokeLinejoin: 'round',+ strokeWidth: 1.6,+ },+ pill: {+ alignItems: 'center',+ backgroundColor: cssVar.colorBgContainer,+ borderRadius: 999,+ boxSizing: 'border-box',+ color: cssVar.colorText,+ display: 'flex',+ fontWeight: 600,+ insetBlockStart: '50%',+ insetInlineStart: 0,+ justifyContent: 'center',+ lineHeight: 1,+ position: 'absolute',+ transform: 'translateY(-50%)',+ whiteSpace: 'nowrap',+ width: '100%',+ },+ text: {+ minWidth: 0,+ overflow: 'hidden',+ textOverflow: 'ellipsis',+ },+});++interface DecisionPillProps {+ height: number;+ k: number;+ title: string;+ width: number;+}++const DecisionPill = ({ height, k, title, width }: DecisionPillProps) => {+ const fit = Math.min(1, height / PILL_HEIGHT);+ const room = width - (PADDING * 2 + GLYPH_GAP + GLYPH) * fit;+ const fontSize = Math.max(+ MIN_FONT_SIZE * fit,+ Math.min(FONT_SIZE * fit, (FONT_SIZE * room) / Math.max(1, textWidth(title, FONT_SIZE))),+ );+ return (+ <div+ title={title}+ {...sx(styles.pill, {+ boxShadow: `inset 0 0 0 ${Math.max(6, 2 / k)}px ${cssVar.colorText}`,+ fontSize,+ gap: GLYPH_GAP * fit,+ height: PILL_HEIGHT * fit,+ paddingInline: PADDING * fit,+ })}+ >+ <svg+ aria-hidden+ height={GLYPH * fit}+ viewBox="0 0 10 10"+ width={GLYPH * fit}+ {...stylex.props(styles.glyph)}+ >+ <path d="M5,0.9 L9.1,5 L5,9.1 L0.9,5 Z" />+ </svg>+ <span {...stylex.props(styles.text)}>{title}</span>+ </div>+ );+};++export default DecisionPill;diff --git a/src/features/Artboard/Canvas/Edges.tsx b/src/features/Artboard/Canvas/Edges.tsxnew file mode 100644index 00000000000..8d25f25888d--- /dev/null+++ b/src/features/Artboard/Canvas/Edges.tsx@@ -0,0 +1,155 @@+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import { useState } from 'react';++import { sx } from '@/styles/sx';++import { useBoard } from '../BoardContext';+import type { BoardEdge } from '../model';+import { useArtboardStore } from '../store';+import { type FlowNodeState, nodeState } from '../Verify/flow';+import { useBoardCapabilities } from '../Viewport/capabilities';+import { ARROW_STROKE_RATIO, arrowSize, edgeArrow, edgeCurve, strokeWidthOf } from './curve';+import {+ EDGE_LABEL_MAX_WIDTH,+ EDGE_LABEL_PAD,+ edgeLabelFont,+ edgeLabelMode,+ edgeLabelText,+} from './edgeLabel';+import { canvasStyles } from './styles';++interface EdgeTone {+ color: string;+ dash?: string;+ strong: boolean;+}++const toneOf = (+ edge: BoardEdge,+ verify: boolean,+ states: Record<string, FlowNodeState>,+ hot: string | null,+): EdgeTone => {+ if (verify && (states[edge.from] === 'failed' || states[edge.to] === 'failed'))+ return { color: cssVar.colorError, strong: true };+ if (hot && (edge.from === hot || edge.to === hot))+ return { color: cssVar.colorPrimary, strong: true };+ return { color: cssVar.colorTextSecondary, strong: false };+};++const Edges = ({ k }: { k: number }) => {+ const board = useBoard();+ const { journey } = useBoardCapabilities();+ const { hot, verify } = useArtboardStore((s) => ({+ hot: s.mode === 'discuss' ? s.selected : null,+ verify: s.mode === 'verify',+ }));+ const states = Object.fromEntries(+ board.edges.flatMap((e) => [e.from, e.to]).map((id) => [id, nodeState(journey, id)]),+ );+ const [hovered, setHovered] = useState<string | null>(null);+ const shown = board.edges.map((edge) => {+ const text = edgeLabelText(edge);+ const linked = !!hot && (edge.from === hot || edge.to === hot);+ return {+ edge,+ mode: edgeLabelMode({+ crowded: edge.labelHidden,+ hovered: edge.id === hovered,+ k,+ linked,+ room: edge.room,+ text,+ }),+ branch: board.boardById[edge.from]?.type === 'decision',+ text,+ tone: toneOf(edge, verify, states, hot),+ };+ });++ return (+ <>+ <svg+ height="1"+ width="1"+ style={{+ left: 0,+ overflow: 'visible',+ pointerEvents: 'none',+ position: 'absolute',+ top: 0,+ }}+ >+ {shown.map(({ edge, tone }) => {+ const width = strokeWidthOf(k, tone.strong);+ const head = arrowSize(width);+ const line = {+ fill: 'none',+ stroke: tone.color,+ strokeLinecap: 'round',+ strokeLinejoin: 'round',+ strokeWidth: width,+ } as const;+ return (+ <g key={edge.id}>+ <path+ {...line}+ d={edgeCurve(edge.points, head)}+ strokeDasharray={tone.dash+ ?.split(' ')+ .map((v) => Number(v) * width)+ .join(' ')}+ />+ <path+ {...line}+ d={edgeArrow(edge.points, head)}+ strokeWidth={width * ARROW_STROKE_RATIO}+ />+ <path+ d={edgeCurve(edge.points)}+ fill="none"+ stroke="transparent"+ strokeWidth={16 / k}+ style={{ pointerEvents: 'stroke' }}+ onMouseEnter={() => setHovered(edge.id)}+ onMouseLeave={() => setHovered((id) => (id === edge.id ? null : id))}+ />+ </g>+ );+ })}+ </svg>+ {shown.map(({ branch, edge, mode, text, tone }) => {+ if (mode === 'none') return null;+ const full = mode === 'full';+ return (+ <div+ key={edge.id}+ title={text}+ {...sx(+ canvasStyles.edgeLabel,+ branch && canvasStyles.edgeBranch,+ full && canvasStyles.edgeLabelFull,+ {+ boxShadow: branch+ ? `0 0 0 ${Math.max(2, 1 / k)}px ${cssVar.colorBorder}`+ : undefined,+ color: tone.strong ? tone.color : undefined,+ fontSize: edgeLabelFont(k, branch),+ left: edge.lx,+ maxWidth: full+ ? undefined+ : Math.min(edge.room, EDGE_LABEL_MAX_WIDTH) - EDGE_LABEL_PAD / k,+ paddingInline: EDGE_LABEL_PAD,+ top: edge.ly,+ },+ )}+ >+ {text}+ </div>+ );+ })}+ </>+ );+};++export default Edges;diff --git a/src/features/Artboard/Canvas/Groups.tsx b/src/features/Artboard/Canvas/Groups.tsxnew file mode 100644index 00000000000..6ec8fbf88d6--- /dev/null+++ b/src/features/Artboard/Canvas/Groups.tsx@@ -0,0 +1,119 @@+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import { LockIcon } from 'lucide-react';+import { useMemo } from 'react';+import { useTranslation } from 'react-i18next';++import { sx } from '@/styles/sx';++import { useBoard } from '../BoardContext';+import { useArtboardStore } from '../store';+import { GROUP_LABEL_GAP, groupChip, groupLabelScale, roundOrder } from './groupLabel';++const DESC_MIN_SCREEN_SPAN = 420;++const styles = stylex.create({+ chip: {+ alignItems: 'center',+ backgroundColor: cssVar.colorText,+ borderRadius: 4,+ color: cssVar.colorBgContainer,+ display: 'inline-flex',+ flexShrink: 0,+ fontFamily: cssVar.fontFamilyCode,+ fontSize: 11,+ fontWeight: 500,+ height: 18,+ lineHeight: '18px',+ paddingInline: 5,+ },+ desc: {+ color: cssVar.colorTextSecondary,+ flexGrow: '0',+ flexShrink: '100',+ flexBasis: 'auto',+ fontWeight: 400,+ minWidth: 0,+ overflow: 'hidden',+ textOverflow: 'ellipsis',+ },+ label: {+ alignItems: 'center',+ color: cssVar.colorText,+ display: 'flex',+ fontSize: 13,+ fontWeight: 600,+ gap: 6,+ pointerEvents: 'none',+ position: 'absolute',+ transformOrigin: '0 0',+ transitionDuration: '0.25s',+ transitionProperty: 'opacity',+ whiteSpace: 'nowrap',+ width: 'max-content',+ },+ title: {+ flexGrow: '0',+ flexShrink: '1',+ flexBasis: 'auto',+ minWidth: 0,+ overflow: 'hidden',+ textOverflow: 'ellipsis',+ },+});++const Groups = ({ k }: { k: number }) => {+ const { t } = useTranslation('project');+ const board = useBoard();+ const verify = useArtboardStore((s) => s.mode === 'verify');+ const numberOf = useMemo(+ () => roundOrder(board.artboard.content.rounds, board.pageId),+ [board.artboard.content.rounds, board.pageId],+ );++ return board.groups.map((group) => {+ const members = board.boards.filter((b) => b.groupId === group.id);+ if (!members.length) return null;+ const x = Math.min(...members.map((b) => b.rect.x));+ const y = Math.min(...members.map((b) => b.rect.y));+ const span = Math.max(...members.map((b) => b.rect.x + b.rect.w)) - x;+ const screenScale = groupLabelScale(k, y - group.rect.y);+ if (screenScale === null) return null;+ const scale = screenScale / k;++ const journey = group.id === board.journeyGroupId;+ const locked = board.finalized && journey;+ const round = board.roundByGroupId[group.id];+ const chip = groupChip({ locked, roundNumber: round && numberOf[round.id] });+ const desc = locked+ ? t(verify ? 'artboard.group.verifyDesc' : 'artboard.group.lockedDesc')+ : round+ ? round.title || t('artboard.group.choose')+ : group.desc;+ return (+ <div+ data-group-label={group.id}+ key={group.id}+ {...sx(styles.label, {+ left: x,+ maxWidth: span / scale,+ opacity: verify && !journey ? 0.3 : 1,+ top: y,+ transform: `translateY(-${GROUP_LABEL_GAP * scale}px) scale(${scale}) translateY(-100%)`,+ })}+ >+ {chip && (+ <span {...stylex.props(styles.chip)}>+ {chip.kind === 'lock' ? <LockIcon size={11} strokeWidth={2.25} /> : chip.text}+ </span>+ )}+ <span {...stylex.props(styles.title)}>{group.title}</span>+ {desc && span * k > DESC_MIN_SCREEN_SPAN && (+ <span {...stylex.props(styles.desc)}>{desc}</span>+ )}+ </div>+ );+ });+};++export default Groups;diff --git a/src/features/Artboard/Canvas/Overlays.tsx b/src/features/Artboard/Canvas/Overlays.tsxnew file mode 100644index 00000000000..52a28c16486--- /dev/null+++ b/src/features/Artboard/Canvas/Overlays.tsx@@ -0,0 +1,97 @@+import { ActionIcon, Flexbox, Segmented, toast } from '@lobehub/ui';+import * as stylex from '@stylexjs/stylex';+import { Maximize2Icon, MessageSquareQuoteIcon } from 'lucide-react';+import { useTranslation } from 'react-i18next';++import { sx } from '@/styles/sx';++import { useBoard } from '../BoardContext';+import { addBoardReference } from '../data/addBoardReference';+import { boardReference } from '../data/references';+import { boardFileUrl } from '../model';+import { artboardActions, useArtboardStore } from '../store';+import type { CompareView } from '../types';+import { nodeScreenshot } from '../Verify/flow';+import { useJourneyView } from '../Verify/useJourneyView';+import { floatStyles } from '../Viewport/floatStyles';+import type { ViewState } from './useViewport';++const SELECTION_BAR_MIN_LEFT = 80;+const SELECTION_BAR_MIN_TOP = 80;++export const SelectionBar = ({ view }: { view: ViewState }) => {+ const { t } = useTranslation('project');+ const board = useBoard();+ const selected = useArtboardStore((s) =>+ s.mode === 'discuss' && s.selected ? board.boardById[s.selected] : undefined,+ );+ const noChatInput = useArtboardStore((s) => s.gallery || s.fullscreen);+ if (!selected || selected.pageId !== board.pageId) return null;++ const refer = () => {+ const reference = boardReference(board, selected.id, '');+ if (!reference || !addBoardReference(reference)) return toast.error(t('artboard.chat.noInput'));+ artboardActions.select(null);+ };++ const { rect } = selected;+ const fileUrl = boardFileUrl(board, selected);+ const openFull = () => {+ if (fileUrl) window.open(fileUrl, '_blank', 'noopener');+ };++ return (+ <Flexbox+ horizontal+ gap={2}++ {...sx(floatStyles.float, floatStyles.selectionBar, {+ left: Math.max(SELECTION_BAR_MIN_LEFT, (rect.x + rect.w) * view.k + view.x),+ top: Math.max(SELECTION_BAR_MIN_TOP, rect.y * view.k + view.y),+ })}+ >+ <ActionIcon+ disabled={!fileUrl}+ icon={Maximize2Icon}+ size={'small'}+ title={t('artboard.selection.view')}+ onClick={openFull}+ />+ {!noChatInput && (+ <ActionIcon+ icon={MessageSquareQuoteIcon}+ size={'small'}+ title={t('artboard.selection.discuss')}+ onClick={refer}+ />+ )}+ </Flexbox>+ );+};++export const CompareBar = () => {+ const { t } = useTranslation('project');+ const board = useBoard();+ const journey = useJourneyView();+ const { compare, selected } = useArtboardStore((s) => ({+ compare: s.compare,+ selected: s.mode === 'verify' && s.selected ? board.boardById[s.selected] : undefined,+ }));+ if (!selected || selected.pageId !== board.pageId || !nodeScreenshot(journey, selected.id))+ return null;++ return (+ <div {...stylex.props(floatStyles.topCenter)}>+ <Segmented+ size={'small'}+ value={compare}+ options={[+ { label: t('artboard.compare.real'), value: 'real' },+ { label: t('artboard.compare.design'), value: 'design' },+ { label: t('artboard.compare.split'), value: 'split' },+ ]}+ onChange={(value) => artboardActions.setCompare(value as CompareView)}+ />+ </div>+ );+};diff --git a/src/features/Artboard/Canvas/RecommendBadge.tsx b/src/features/Artboard/Canvas/RecommendBadge.tsxnew file mode 100644index 00000000000..6c3579b84f6--- /dev/null+++ b/src/features/Artboard/Canvas/RecommendBadge.tsx@@ -0,0 +1,52 @@+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import { StarIcon } from 'lucide-react';++import { sx } from '@/styles/sx';++import { artboardTokens } from '../tokens.stylex';+import { recommendBadge } from './boardLabelLayout';++const styles = stylex.create({+ badge: {+ alignItems: 'center',+ backgroundColor: cssVar.colorBgContainer,+ borderRadius: '50%',+ boxShadow: `0 0 0 1px color-mix(in srgb, ${artboardTokens.accent} 40%, transparent), 0 1px 3px ${cssVar.colorFillSecondary}`,+ color: artboardTokens.accent,+ display: 'flex',+ justifyContent: 'center',+ pointerEvents: 'none',+ position: 'absolute',+ transformOrigin: '100% 0',+ zIndex: 2,+ },+});++interface RecommendBadgeProps {+ k: number;+ label: string;+ width: number;+}++const RecommendBadge = ({ k, label, width }: RecommendBadgeProps) => {+ const badge = recommendBadge(width * k);+ if (!badge) return null;+ return (+ <span+ aria-label={label}+ role="img"+ {...sx(styles.badge, {+ height: badge.size,+ right: badge.inset / k,+ top: badge.inset / k,+ transform: `scale(${1 / k})`,+ width: badge.size,+ })}+ >+ <StarIcon fill="currentColor" size={badge.icon} strokeWidth={1.5} />+ </span>+ );+};++export default RecommendBadge;diff --git a/src/features/Artboard/Canvas/boardLabelLayout.test.ts b/src/features/Artboard/Canvas/boardLabelLayout.test.tsnew file mode 100644index 00000000000..065f98dea1e--- /dev/null+++ b/src/features/Artboard/Canvas/boardLabelLayout.test.ts@@ -0,0 +1,79 @@+import { describe, expect, it } from 'vitest';++import {+ BOARD_LABEL_FONT,+ boardLabelLayout,+ boardLabelScale,+ recommendBadge,+ textWidth,+} from './boardLabelLayout';++describe('boardLabelScale', () => {+ it('follows the zoom and caps at 23px on screen', () => {+ expect(boardLabelScale(1, 400)! * BOARD_LABEL_FONT).toBeCloseTo(23);+ expect(boardLabelScale(3, 400)! * BOARD_LABEL_FONT).toBeCloseTo(23);+ expect(boardLabelScale(0.5, 400)! * BOARD_LABEL_FONT).toBeCloseTo(12.8, 1);+ expect(boardLabelScale(0.2, 400)! * BOARD_LABEL_FONT).toBeCloseTo(5.9, 1);+ });++ it('hides the row below 11% zoom or on a board narrower than 48 screen px', () => {+ expect(boardLabelScale(0.1, 4000)).toBeNull();+ expect(boardLabelScale(0.2, 200)).toBeNull();+ expect(boardLabelScale(0.2, 240)).not.toBeNull();+ });+});++describe('textWidth', () => {+ it('counts wide characters as a full em and others as about half', () => {+ expect(textWidth('ab', 10)).toBeCloseTo(11);+ expect(textWidth('评论', 10)).toBe(20);+ });+});++describe('boardLabelLayout', () => {+ const base = { lead: 0, recommended: true, tag: 70, title: 100, trail: 0 };++ it('shows the recommended tag when it fits beside the title', () => {+ expect(boardLabelLayout({ ...base, boardWidth: 400, k: 1 })).toMatchObject({+ badge: false,+ label: { mark: 'tag' },+ });+ });++ it('falls back to a star when only the title fits', () => {+ const scale = boardLabelScale(1, 200)!;+ const layout = boardLabelLayout({ ...base, boardWidth: 150 * scale, k: 1 });+ expect(layout).toMatchObject({ badge: false, label: { mark: 'star' } });+ });++ it('floats a badge on the board when the inline mark is too small to read', () => {+ expect(boardLabelLayout({ ...base, boardWidth: 1000, k: 0.28 })).toMatchObject({+ badge: true,+ label: { mark: 'none' },+ });+ expect(boardLabelLayout({ ...base, boardWidth: 1000, k: 0.05 })).toEqual({+ badge: true,+ label: null,+ });+ });++ it('never marks a board that is not recommended', () => {+ expect(boardLabelLayout({ ...base, boardWidth: 1000, k: 0.05, recommended: false })).toEqual({+ badge: false,+ label: null,+ });+ });++ it('makes the row as wide as the board on screen', () => {+ const layout = boardLabelLayout({ ...base, boardWidth: 400, k: 0.5 });+ expect(layout.label!.width * layout.label!.scale).toBeCloseTo(200);+ });+});++describe('recommendBadge', () => {+ it('shrinks on narrow boards and hides on tiny ones', () => {+ expect(recommendBadge(200)).toEqual({ icon: 11, inset: 8, size: 20 });+ expect(recommendBadge(50)).toEqual({ icon: 8, inset: 4, size: 14 });+ expect(recommendBadge(19)).toBeNull();+ });+});diff --git a/src/features/Artboard/Canvas/boardLabelLayout.ts b/src/features/Artboard/Canvas/boardLabelLayout.tsnew file mode 100644index 00000000000..63929c5af33--- /dev/null+++ b/src/features/Artboard/Canvas/boardLabelLayout.ts@@ -0,0 +1,79 @@+export const BOARD_LABEL_FONT = 12;+const BASE = 23;+const FOLLOW = 0.85;+const HIDE_BELOW = 0.11;+const MIN_SCREEN_WIDTH = 48;++const TAG_FONT = 10;+const STAR = 12;+const STAR_ROOM = STAR + 7;+const TITLE_MIN = 56;+const MIN_TAG_PX = 9;+const MIN_STAR_PX = 10;++const WIDE_CHAR =+ /[\u1100-\u11FF\u2E80-\u9FFF\uA960-\uA97F\uAC00-\uD7FF\uF900-\uFAFF\uFE30-\uFE4F\uFF00-\uFF60\uFFE0-\uFFE6]/;++export const textWidth = (text: string, fontSize: number) => {+ let units = 0;+ for (const char of text) units += WIDE_CHAR.test(char) ? 1 : 0.55;+ return units * fontSize;+};++export const TAG_CHROME = 16;+export const tagWidth = (text: string) => textWidth(text, TAG_FONT) + TAG_CHROME;++export const boardLabelScale = (k: number, boardWidth: number): number | null => {+ if (k < HIDE_BELOW || boardWidth * k < MIN_SCREEN_WIDTH) return null;+ return Math.min(BASE * k ** FOLLOW, BASE) / BOARD_LABEL_FONT;+};++export type RecommendMark = 'none' | 'star' | 'tag';++const recommendMark = (title: number, tag: number, room: number): RecommendMark => {+ if (title + tag <= room) return 'tag';+ return room - STAR_ROOM >= Math.min(title, TITLE_MIN) ? 'star' : 'none';+};++const readable = (mark: RecommendMark, scale: number) => {+ if (mark === 'tag') return TAG_FONT * scale >= MIN_TAG_PX;+ if (mark === 'star') return STAR * scale >= MIN_STAR_PX;+ return false;+};++interface BoardLabelInput {+ boardWidth: number;+ k: number;+ lead: number;+ recommended: boolean;+ tag: number;+ title: number;+ trail: number;+}++export interface BoardLabelLayout {+ badge: boolean;+ label: { mark: RecommendMark; scale: number; width: number } | null;+}++export const boardLabelLayout = ({+ boardWidth,+ k,+ lead,+ recommended,+ tag,+ title,+ trail,+}: BoardLabelInput): BoardLabelLayout => {+ const scale = boardLabelScale(k, boardWidth);+ if (scale === null) return { badge: recommended, label: null };+ const width = (boardWidth * k) / scale;+ const mark = recommended ? recommendMark(title, tag, width - lead - trail) : 'none';+ const shown = readable(mark, scale);+ return { badge: recommended && !shown, label: { mark: shown ? mark : 'none', scale, width } };+};++export const recommendBadge = (screenWidth: number) => {+ if (screenWidth < 20) return null;+ return screenWidth < 60 ? { icon: 8, inset: 4, size: 14 } : { icon: 11, inset: 8, size: 20 };+};diff --git a/src/features/Artboard/Canvas/curve.test.ts b/src/features/Artboard/Canvas/curve.test.tsnew file mode 100644index 00000000000..2219ee2aead--- /dev/null+++ b/src/features/Artboard/Canvas/curve.test.ts@@ -0,0 +1,75 @@+import { describe, expect, it } from 'vitest';++import { arrowSize, edgeArrow, edgeCurve, strokeWidthOf } from './curve';++const numbers = (d: string) => (d.match(/-?\d+(\.\d+)?/g) ?? []).map(Number);++const direct: [number, number][] = [+ [640, 200],+ [680, 200],+ [680, 500],+ [720, 500],+];++const detour: [number, number][] = [+ [320, 400],+ [320, 640],+ [1000, 640],+ [1000, 400],+];++describe('edgeCurve', () => {+ it('bends a direct route into one smooth curve that leaves and enters level', () => {+ const d = edgeCurve(direct);+ expect(d).toMatch(/^M640 200 C/);+ expect(numbers(d)).toEqual([640, 200, 680, 200, 680, 500, 720, 500]);+ });++ it('arrives on a straight lead-in so the arrowhead lines up with the line', () => {+ const steep: [number, number][] = [+ [1680, 340],+ [1720, 340],+ [1720, 1350],+ [1760, 1350],+ ];+ const d = edgeCurve(steep, 10);+ expect(d).toMatch(/ L1760 1350$/);+ expect(numbers(d).slice(-4)).toEqual([1750, 1350, 1760, 1350]);+ });++ it('draws the same path every time', () => {+ expect(edgeCurve(direct)).toBe(edgeCurve(direct));+ });++ it('keeps a detour on its route around other boards, only rounding the corners', () => {+ const d = edgeCurve(detour);+ expect(d).not.toContain('C');+ expect(numbers(d).slice(0, 2)).toEqual([320, 400]);+ expect(numbers(d).slice(-2)).toEqual([1000, 400]);+ expect(Math.max(...numbers(d).filter((_, i) => i % 2 === 1))).toBe(640);+ });+});++describe('edgeArrow', () => {+ it('opens a chevron backwards from the tip along the last heading', () => {+ const [ax, ay, tx, ty, bx, by] = numbers(edgeArrow(direct, 10));+ expect([tx, ty]).toEqual([720, 500]);+ expect(ax).toBeLessThan(720);+ expect(bx).toBeLessThan(720);+ expect(Math.sign(ay - 500)).toBe(-Math.sign(by - 500));+ });+});++describe('sizes', () => {+ it('draws a 4px line that never gets thinner than 1.5px on screen', () => {+ expect(strokeWidthOf(0.25, false)).toBe(6);+ expect(strokeWidthOf(1, false)).toBe(4);+ expect(strokeWidthOf(2, false)).toBe(4);+ expect(strokeWidthOf(1, true)).toBe(6);+ });++ it('sizes the chevron from the stroke it ends', () => {+ expect(arrowSize(4)).toBeCloseTo(15);+ expect(arrowSize(6)).toBeCloseTo(22.5);+ });+});diff --git a/src/features/Artboard/Canvas/curve.ts b/src/features/Artboard/Canvas/curve.tsnew file mode 100644index 00000000000..6e5eedcdcc6--- /dev/null+++ b/src/features/Artboard/Canvas/curve.ts@@ -0,0 +1,89 @@+export type Point = [number, number];++const CORNER = 24;+const CHEVRON_SPREAD = 0.5;++const fmt = (value: number) => String(Math.round(value * 10) / 10);+const at = ([x, y]: Point) => `${fmt(x)} ${fmt(y)}`;++const unit = (a: Point, b: Point): Point => {+ const length = Math.hypot(b[0] - a[0], b[1] - a[1]);+ return length ? [(b[0] - a[0]) / length, (b[1] - a[1]) / length] : [0, 0];+};++const between = (value: number, a: number, b: number) =>+ value >= Math.min(a, b) && value <= Math.max(a, b);++// A direct route turns once between the two boards; a detour leaves the span to get around others.+const isDirect = (points: Point[]) => {+ if (points.length !== 4) return false;+ const [p0, p1, , p3] = points;+ return p0[1] === p1[1] ? between(p1[0], p0[0], p3[0]) : between(p1[1], p0[1], p3[1]);+};++const roundedPolyline = (points: Point[]) => {+ let d = `M${at(points[0])}`;+ for (let i = 1; i < points.length - 1; i++) {+ const prev = points[i - 1];+ const corner = points[i];+ const next = points[i + 1];+ const radius = Math.min(+ CORNER,+ Math.hypot(corner[0] - prev[0], corner[1] - prev[1]) / 2,+ Math.hypot(next[0] - corner[0], next[1] - corner[1]) / 2,+ );+ const into = unit(prev, corner);+ const out = unit(corner, next);+ d += ` L${at([corner[0] - into[0] * radius, corner[1] - into[1] * radius])}`;+ d += ` Q${at(corner)} ${at([corner[0] + out[0] * radius, corner[1] + out[1] * radius])}`;+ }+ return `${d} L${at(points.at(-1)!)}`;+};++// The arrowhead sits on a straight lead-in; on a steep curve the last stretch is nearly+// perpendicular to the board, so a chevron drawn on the curve itself reads as crooked.+export const edgeCurve = (points: Point[], lead = 0) => {+ if (!isDirect(points)) return roundedPolyline(points);+ const [p0, p1, , p3] = points;+ const horizontal = p0[1] === p1[1];+ const axis = horizontal ? 0 : 1;+ const direction = Math.sign(p3[axis] - p0[axis]);+ const span = Math.abs(p3[axis] - p0[axis]);+ const straight = Math.min(lead, span / 2);+ const end: Point = [...p3];+ end[axis] -= direction * straight;+ const reach = (span - straight) / 2;+ const c1: Point = [...p0];+ c1[axis] += direction * reach;+ const c2: Point = [...end];+ c2[axis] -= direction * reach;+ const curve = `M${at(p0)} C${at(c1)} ${at(c2)} ${at(end)}`;+ return straight ? `${curve} L${at(p3)}` : curve;+};++const headingOf = (points: Point[]) => {+ for (let i = points.length - 1; i > 0; i--) {+ const dx = points[i][0] - points[i - 1][0];+ const dy = points[i][1] - points[i - 1][1];+ if (dx || dy) return Math.atan2(dy, dx);+ }+ return 0;+};++export const edgeArrow = (points: Point[], size: number) => {+ const tip = points.at(-1)!;+ const heading = headingOf(points);+ const [a, b] = [-1, 1].map((side): Point => {+ const angle = heading + Math.PI + side * CHEVRON_SPREAD;+ return [tip[0] + Math.cos(angle) * size, tip[1] + Math.sin(angle) * size];+ });+ return `M${at(a)} L${at(tip)} L${at(b)}`;+};++const CHEVRON_PER_STROKE = 3.75;+export const ARROW_STROKE_RATIO = 0.7;++export const arrowSize = (strokeWidth: number) => strokeWidth * CHEVRON_PER_STROKE;++export const strokeWidthOf = (k: number, strong: boolean) =>+ Math.max(4, 1.5 / k) * (strong ? 1.5 : 1);diff --git a/src/features/Artboard/Canvas/edgeLabel.test.ts b/src/features/Artboard/Canvas/edgeLabel.test.tsnew file mode 100644index 00000000000..b99b4723abf--- /dev/null+++ b/src/features/Artboard/Canvas/edgeLabel.test.ts@@ -0,0 +1,51 @@+import { describe, expect, it } from 'vitest';++import { edgeLabelFont, edgeLabelMode, edgeLabelText } from './edgeLabel';++describe('edgeLabelText', () => {+ it('joins the action and the branch condition, and is empty when the edge has neither', () => {+ expect(edgeLabelText({ condition: 'paid', label: 'Checks out' })).toBe('Checks out · paid');+ expect(edgeLabelText({ condition: null, label: 'Checks out' })).toBe('Checks out');+ expect(edgeLabelText({ condition: 'paid', label: '' })).toBe('paid');+ expect(edgeLabelText({ condition: null, label: '' })).toBe('');+ });+});++describe('edgeLabelFont', () => {+ it('keeps a label at least 11px on screen', () => {+ expect(edgeLabelFont(1, false)).toBe(32);+ expect(edgeLabelFont(1, true)).toBe(28);+ expect(edgeLabelFont(0.25, false)).toBe(44);+ });+});++describe('edgeLabelMode', () => {+ const resting = { hovered: false, k: 1, linked: false, room: 64, text: 'Checks out' };++ it('shows the full label of an edge the user points at, at any zoom', () => {+ expect(edgeLabelMode({ ...resting, hovered: true, k: 0.1 })).toBe('full');+ });++ it('shows the full labels around the selected board until they would pile up', () => {+ expect(edgeLabelMode({ ...resting, k: 0.5, linked: true })).toBe('full');+ expect(edgeLabelMode({ ...resting, k: 0.13, linked: true })).toBe('none');+ });++ it('keeps a resting label inside the gap between its boards', () => {+ expect(edgeLabelMode(resting)).toBe('inline');+ });++ it('drops a resting label once it is too small to read or has no room', () => {+ expect(edgeLabelMode({ ...resting, k: 0.3 })).toBe('none');+ expect(edgeLabelMode({ ...resting, room: 20 })).toBe('none');+ });++ it('needs room on screen beyond the arrow reserve', () => {+ expect(edgeLabelMode({ ...resting, k: 0.5, room: 200 })).toBe('inline');+ expect(edgeLabelMode({ ...resting, k: 0.5, room: 100 })).toBe('none');+ });++ it('shows nothing for an edge without text', () => {+ expect(edgeLabelMode({ ...resting, hovered: true, text: '' })).toBe('none');+ });+});diff --git a/src/features/Artboard/Canvas/edgeLabel.ts b/src/features/Artboard/Canvas/edgeLabel.tsnew file mode 100644index 00000000000..694f6d6402b--- /dev/null+++ b/src/features/Artboard/Canvas/edgeLabel.ts@@ -0,0 +1,45 @@+import { textWidth } from './boardLabelLayout';++export const EDGE_LABEL_FONT = 32;+const EDGE_BRANCH_FONT = 28;+const MIN_SCREEN_FONT = 11;+export const EDGE_LABEL_PAD = 16;+export const EDGE_LABEL_MAX_WIDTH = 360;+export const EDGE_LABEL_HEIGHT = 45;+const MIN_SCREEN_ROOM = 40;+const MIN_RESTING_ZOOM = 0.25;+const MIN_LINKED_ZOOM = 0.3;++export const edgeLabelText = (edge: { condition: string | null; label: string }) =>+ [edge.label, edge.condition].filter(Boolean).join(' · ');++export const edgeLabelWidth = (text: string) =>+ textWidth(text, EDGE_LABEL_FONT) + EDGE_LABEL_PAD * 2;++export const edgeLabelFont = (k: number, branch: boolean) =>+ Math.max(branch ? EDGE_BRANCH_FONT : EDGE_LABEL_FONT, MIN_SCREEN_FONT / k);++export type EdgeLabelMode = 'full' | 'inline' | 'none';++interface EdgeLabelInput {+ crowded?: boolean;+ hovered: boolean;+ k: number;+ linked: boolean;+ room: number;+ text: string;+}++export const edgeLabelMode = ({+ crowded,+ hovered,+ k,+ linked,+ room,+ text,+}: EdgeLabelInput): EdgeLabelMode => {+ if (!text) return 'none';+ if (hovered || (linked && k >= MIN_LINKED_ZOOM)) return 'full';+ if (crowded) return 'none';+ return k >= MIN_RESTING_ZOOM && room * k - EDGE_LABEL_PAD >= MIN_SCREEN_ROOM ? 'inline' : 'none';+};diff --git a/src/features/Artboard/Canvas/escapeScope.test.ts b/src/features/Artboard/Canvas/escapeScope.test.tsnew file mode 100644index 00000000000..7190227a7d7--- /dev/null+++ b/src/features/Artboard/Canvas/escapeScope.test.ts@@ -0,0 +1,30 @@+// @vitest-environment happy-dom+import { describe, expect, it } from 'vitest';++import { ownsEscape } from './escapeScope';++const key = (target: EventTarget, init: KeyboardEventInit = {}) => {+ const event = new KeyboardEvent('keydown', { key: 'Escape', ...init });+ Object.defineProperty(event, 'target', { value: target });+ return event;+};++describe('ownsEscape', () => {+ const root = document.createElement('div');+ const inside = root.appendChild(document.createElement('textarea'));+ const outside = document.createElement('input');++ it('takes Escape pressed inside the board or with nothing focused', () => {+ expect(ownsEscape(key(inside), root)).toBe(true);+ expect(ownsEscape(key(document.body), root)).toBe(true);+ });++ it('leaves Escape to whatever else has the focus', () => {+ expect(ownsEscape(key(outside), root)).toBe(false);+ });++ it('leaves Escape to an input method that is composing, and ignores other keys', () => {+ expect(ownsEscape(key(inside, { isComposing: true }), root)).toBe(false);+ expect(ownsEscape(key(inside, { key: 'Enter' }), root)).toBe(false);+ });+});diff --git a/src/features/Artboard/Canvas/escapeScope.ts b/src/features/Artboard/Canvas/escapeScope.tsnew file mode 100644index 00000000000..4048029be31--- /dev/null+++ b/src/features/Artboard/Canvas/escapeScope.ts@@ -0,0 +1,5 @@+export const ownsEscape = (event: KeyboardEvent, root: Element | null) => {+ if (event.key !== 'Escape' || event.isComposing) return false;+ const target = event.target as Node | null;+ return !target || target === document.body || !!root?.contains(target);+};diff --git a/src/features/Artboard/Canvas/groupLabel.test.ts b/src/features/Artboard/Canvas/groupLabel.test.tsnew file mode 100644index 00000000000..38eb6a3f2b6--- /dev/null+++ b/src/features/Artboard/Canvas/groupLabel.test.ts@@ -0,0 +1,45 @@+import { describe, expect, it } from 'vitest';++import { GROUP_LABEL_FONT, groupChip, groupLabelScale, roundOrder } from './groupLabel';++describe('groupLabelScale', () => {+ it('follows the zoom with a softer curve and caps at 27px on screen', () => {+ expect(groupLabelScale(1)! * GROUP_LABEL_FONT).toBeCloseTo(27);+ expect(groupLabelScale(2)! * GROUP_LABEL_FONT).toBeCloseTo(27);+ expect(groupLabelScale(0.5)! * GROUP_LABEL_FONT).toBeCloseTo(16.6, 1);+ expect(groupLabelScale(0.3)! * GROUP_LABEL_FONT).toBeCloseTo(11.6, 1);+ });++ it('stays inside the band above the boards', () => {+ expect(groupLabelScale(0.1)).toBeCloseTo((144 * 0.1) / 46);+ expect(groupLabelScale(1, 48)).toBeCloseTo(48 / 46);+ });++ it('hides a label that would be unreadable', () => {+ expect(groupLabelScale(0.05)).toBeNull();+ expect(groupLabelScale(0.04)).toBeNull();+ expect(groupLabelScale(0.5, 4)).toBeNull();+ });+});++describe('roundOrder', () => {+ it('numbers the rounds of a page in order', () => {+ const order = roundOrder(+ [+ { id: 'a', pageId: 'p1' },+ { id: 'b', pageId: 'p2' },+ { id: 'c', pageId: 'p1' },+ ],+ 'p1',+ );+ expect(order).toEqual({ a: 1, c: 2 });+ });+});++describe('groupChip', () => {+ it('marks a finalized journey with a lock, a round with its question number, and nothing else', () => {+ expect(groupChip({ locked: true, roundNumber: 2 })).toEqual({ kind: 'lock' });+ expect(groupChip({ locked: false, roundNumber: 2 })).toEqual({ kind: 'text', text: 'Q2' });+ expect(groupChip({ locked: false })).toBeNull();+ });+});diff --git a/src/features/Artboard/Canvas/groupLabel.ts b/src/features/Artboard/Canvas/groupLabel.tsnew file mode 100644index 00000000000..38bc345740d--- /dev/null+++ b/src/features/Artboard/Canvas/groupLabel.ts@@ -0,0 +1,36 @@+export const GROUP_TOP = 144;+export const GROUP_LABEL_FONT = 13;+export const GROUP_LABEL_GAP = 26;+const GROUP_LABEL_ROW = 20;+const BASE = 27;+const FOLLOW = 0.7;+const MIN_FONT = 4;+const HIDE_BELOW = 0.05;++export const groupLabelScale = (k: number, band = GROUP_TOP): number | null => {+ if (k < HIDE_BELOW) return null;+ const size = Math.max(Math.min(BASE * k ** FOLLOW, BASE), MIN_FONT);+ const scale = Math.min(size / GROUP_LABEL_FONT, (band * k) / (GROUP_LABEL_GAP + GROUP_LABEL_ROW));+ return scale * GROUP_LABEL_FONT < MIN_FONT ? null : scale;+};++export const roundOrder = (+ rounds: { id: string; pageId: string }[],+ pageId: string | undefined,+): Record<string, number> =>+ Object.fromEntries(+ rounds.filter((round) => round.pageId === pageId).map((round, i) => [round.id, i + 1]),+ );++export type GroupChip = { kind: 'lock' } | { kind: 'text'; text: string };++export const groupChip = ({+ locked,+ roundNumber,+}: {+ locked: boolean;+ roundNumber?: number;+}): GroupChip | null => {+ if (locked) return { kind: 'lock' };+ return roundNumber ? { kind: 'text', text: `Q${roundNumber}` } : null;+};diff --git a/src/features/Artboard/Canvas/index.tsx b/src/features/Artboard/Canvas/index.tsxnew file mode 100644index 00000000000..02ff696be46--- /dev/null+++ b/src/features/Artboard/Canvas/index.tsx@@ -0,0 +1,45 @@+import { useBoard } from '../BoardContext';+import { commentTargetAt } from '../data/commentActions';+import { artboardActions, useArtboardStore } from '../store';+import Viewport from '../Viewport';+import CommentLayer from './CommentLayer';+import { CompareBar, SelectionBar } from './Overlays';++const clearSelection = () => {+ artboardActions.select(null);+ const { draft, openThreadId } = useArtboardStore.getState();+ if (draft || openThreadId) artboardActions.openThread(null);+};++const Canvas = () => {+ const board = useBoard();+ const discussing = useArtboardStore((s) => s.mode === 'discuss');+ const commenting = useArtboardStore((s) => s.mode === 'discuss' && s.tool === 'comment');++ return (+ <Viewport+ commenting={commenting}+ onBackground={clearSelection}+ onCanvasClick={(event, view) => {+ if (!commenting) return;+ event.stopPropagation();+ const box = event.currentTarget.getBoundingClientRect();+ const point = {+ x: (event.clientX - box.left - view.x) / view.k,+ y: (event.clientY - box.top - view.y) / view.k,+ };+ artboardActions.placeDraft({ ...commentTargetAt(board, point), ...point });+ }}+ >+ {({ size, view }) => (+ <>+ <SelectionBar view={view} />+ <CompareBar />+ {discussing && <CommentLayer size={size} view={view} />}+ </>+ )}+ </Viewport>+ );+};++export default Canvas;diff --git a/src/features/Artboard/Canvas/pageViews.test.ts b/src/features/Artboard/Canvas/pageViews.test.tsnew file mode 100644index 00000000000..3fa940bcfaa--- /dev/null+++ b/src/features/Artboard/Canvas/pageViews.test.ts@@ -0,0 +1,20 @@+import { describe, expect, it } from 'vitest';++import { createPageViews } from './pageViews';++describe('createPageViews', () => {+ it('gives back the view a page was left with, and nothing for a page never seen', () => {+ const views = createPageViews<{ k: number }>();++ expect(views.swap('p1', 'p2', { k: 0.5 })).toBeUndefined();+ expect(views.swap('p2', 'p1', { k: 0.8 })).toEqual({ k: 0.5 });+ expect(views.swap('p1', 'p2', { k: 0.6 })).toEqual({ k: 0.8 });+ });++ it('keeps nothing for a board that had no page', () => {+ const views = createPageViews<{ k: number }>();++ expect(views.swap(undefined, 'p1', { k: 1 })).toBeUndefined();+ expect(views.swap('p1', undefined, { k: 1 })).toBeUndefined();+ });+});diff --git a/src/features/Artboard/Canvas/pageViews.ts b/src/features/Artboard/Canvas/pageViews.tsnew file mode 100644index 00000000000..21b3df22d9d--- /dev/null+++ b/src/features/Artboard/Canvas/pageViews.ts@@ -0,0 +1,9 @@+export const createPageViews = <View>() => {+ const saved = new Map<string, View>();+ return {+ swap: (from: string | undefined, to: string | undefined, current: View) => {+ if (from) saved.set(from, current);+ return to ? saved.get(to) : undefined;+ },+ };+};diff --git a/src/features/Artboard/Canvas/styles.ts b/src/features/Artboard/Canvas/styles.tsnew file mode 100644index 00000000000..95a11d1010e--- /dev/null+++ b/src/features/Artboard/Canvas/styles.ts@@ -0,0 +1,173 @@+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';++import { artboardTokens } from '../tokens.stylex';++const appear = stylex.keyframes({+ from: { opacity: 0, transform: 'translateY(24px)' },+});++const flash = stylex.keyframes({+ '0%': { boxShadow: `0 0 0 0 ${cssVar.colorPrimary}` },+ '30%': { boxShadow: `0 0 0 14px ${cssVar.colorPrimaryBg}` },+ '100%': { boxShadow: '0 0 0 0 transparent' },+});++export const canvasStyles = stylex.create({+ appear: {+ animationDuration: '0.4s',+ animationName: appear,+ animationTimingFunction: 'ease-out',+ },+ edgeBranch: {+ backgroundColor: cssVar.colorBgContainer,+ borderRadius: 999,+ color: cssVar.colorTextSecondary,+ },+ edgeLabel: {+ backgroundColor: cssVar.colorBgLayout,+ boxSizing: 'border-box',+ color: cssVar.colorText,+ fontWeight: 500,+ lineHeight: 1.4,+ overflow: 'hidden',+ pointerEvents: 'none',+ position: 'absolute',+ textOverflow: 'ellipsis',+ transform: 'translate(-50%, -50%)',+ whiteSpace: 'nowrap',+ zIndex: 1,+ },+ edgeLabelFull: {+ zIndex: 3,+ },+ busy: {+ alignItems: 'center',+ backdropFilter: 'blur(2px)',+ backgroundColor: `color-mix(in srgb, ${cssVar.colorBgContainer} 72%, transparent)`,+ display: 'flex',+ fontSize: 15,+ gap: 8,+ inset: 0,+ justifyContent: 'center',+ position: 'absolute',+ },+ commenting: {+ cursor: 'crosshair',+ },+ cursor: {+ pointerEvents: 'none',+ position: 'absolute',+ transitionDuration: '0.8s',+ transitionProperty: 'transform',+ transitionTimingFunction: 'ease-in-out',+ },+ cursorName: {+ backgroundColor: cssVar.colorPrimary,+ borderRadius: 6,+ color: cssVar.colorBgContainer,+ fontSize: 12,+ paddingBlock: 2,+ paddingInline: 8,+ whiteSpace: 'nowrap',+ },+ drawing: {+ backgroundColor: cssVar.colorBgContainer,+ display: 'flex',+ flexDirection: 'column',+ gap: 16,+ height: '100%',+ padding: 24,+ },+ flash: {+ animationDuration: '1.6s',+ animationName: flash,+ animationTimingFunction: 'ease-out',+ },+ board: {+ cursor: 'pointer',+ position: 'absolute',+ transitionDuration: '0.25s',+ transitionProperty: 'opacity',+ },+ boardCard: {+ backgroundColor: cssVar.colorBgContainer,+ height: '100%',+ outlineColor: cssVar.colorBorderSecondary,+ outlineStyle: 'solid',+ outlineWidth: 1,+ overflow: 'hidden',+ position: 'relative',+ width: '100%',+ },+ boardBare: {+ backgroundColor: 'transparent',+ outlineStyle: 'none',+ overflow: 'visible',+ },+ boardFrame: {+ borderColor: artboardTokens.accent,+ borderStyle: 'solid',+ boxSizing: 'border-box',+ inset: 0,+ pointerEvents: 'none',+ position: 'absolute',+ },+ boardRelated: {+ outlineColor: artboardTokens.selectionLine,+ outlineStyle: 'dashed',+ },+ boardSelected: {+ outlineColor: artboardTokens.selection,+ outlineStyle: 'solid',+ },+ inert: {+ pointerEvents: 'none',+ },+ muted: {+ opacity: 0.25,+ pointerEvents: 'none',+ },+ panning: {+ cursor: 'grabbing',+ },+ scaledLabel: {+ insetBlockEnd: '100%',+ insetInlineStart: 0,+ position: 'absolute',+ transformOrigin: '0 100%',+ },+ shotChip: {+ backgroundColor: cssVar.colorText,+ borderRadius: 6,+ color: cssVar.colorBgContainer,+ fontSize: 12,+ insetBlockEnd: 10,+ insetInlineEnd: 10,+ paddingBlock: 2,+ paddingInline: 8,+ position: 'absolute',+ },+ viewport: {+ backgroundColor: cssVar.colorBgLayout,+ color: cssVar.colorText,+ cursor: 'grab',+ fontFamily: cssVar.fontFamily,+ inset: 0,+ overflow: 'hidden',+ position: 'absolute',+ touchAction: 'none',+ userSelect: 'none',+ },+ world: {+ insetBlockStart: 0,+ insetInlineStart: 0,+ position: 'absolute',+ transformOrigin: '0 0',+ },+ worldFlying: {+ transitionDuration: '0.45s',+ transitionProperty: 'transform',+ transitionTimingFunction: 'cubic-bezier(0.2, 0.8, 0.2, 1)',+ },+});diff --git a/src/features/Artboard/Canvas/useViewport.ts b/src/features/Artboard/Canvas/useViewport.tsnew file mode 100644index 00000000000..ec3e175715d--- /dev/null+++ b/src/features/Artboard/Canvas/useViewport.ts@@ -0,0 +1,243 @@+import { type PointerEvent, type RefObject, useCallback, useEffect, useRef, useState } from 'react';++import { useSingleton } from '@/hooks/useSingleton';++import { type BoardModel, type Rect, toBounds } from '../model';+import { useArtboardStore } from '../store';+import { createPageViews } from './pageViews';++export interface ViewState {+ k: number;+ x: number;+ y: number;+}++const MIN_K = 0.08;+const MAX_K = 2;+const FLY_MS = 480;+const OUTLINE_INSET = 200;++const clamp = (v: number, min: number, max: number) => Math.min(max, Math.max(min, v));++const zoomAround = (v: ViewState, k: number, px: number, py: number): ViewState => ({+ k,+ x: px - ((px - v.x) / v.k) * k,+ y: py - ((py - v.y) / v.k) * k,+});++const LABEL_SPACE = 40;++const itemRect = (board: BoardModel, id: string): Rect | undefined => {+ const item = board.boardById[id];+ if (!item) return;+ const rect = toBounds(item.rect);+ return { ...rect, minY: rect.minY - LABEL_SPACE };+};++const groupBounds = (board: BoardModel, id: string | undefined): Rect | undefined => {+ const group = id ? board.groups.find((g) => g.id === id) : undefined;+ if (!group) return;+ const rect = toBounds(group.rect);+ return { ...rect, minY: rect.minY - LABEL_SPACE };+};++export const useViewport = (+ ref: RefObject<HTMLDivElement | null>,+ board: BoardModel,+ onBackgroundClick: () => void,+) => {+ const [view, setView] = useState<ViewState>({ k: 0.3, x: 40, y: 200 });+ const [flying, setFlying] = useState(false);+ const [panning, setPanning] = useState(false);+ const drag = useRef<{+ moved: boolean;+ onItem: boolean;+ pointerId: number;+ sx: number;+ sy: number;+ vx: number;+ vy: number;+ }>(null);+ const suppressClick = useRef(false);+ const target = useRef<{ pad: number; rect: Rect } | null>({ pad: 80, rect: board.bounds });+ const boardRef = useRef(board);+ boardRef.current = board;+ const flyTimer = useRef<ReturnType<typeof setTimeout>>(undefined);++ const animate = useCallback(() => {+ setFlying(true);+ clearTimeout(flyTimer.current);+ flyTimer.current = setTimeout(() => setFlying(false), FLY_MS);+ }, []);++ const fit = useCallback(+ (b: Rect, smooth = true, pad = 80) => {+ const el = ref.current;+ if (!el) return;+ target.current = { pad, rect: b };+ const { mode, outlineOpen } = useArtboardStore.getState();+ const inset = outlineOpen && mode === 'discuss' ? OUTLINE_INSET : 0;+ const vw = el.clientWidth - inset;+ const vh = el.clientHeight;+ const k = clamp(+ Math.min((vw - pad * 2) / (b.maxX - b.minX), (vh - pad * 2) / (b.maxY - b.minY)),+ MIN_K,+ 1,+ );+ if (smooth) animate();+ setView({+ k,+ x: inset + vw / 2 - ((b.minX + b.maxX) / 2) * k,+ y: vh / 2 - ((b.minY + b.maxY) / 2) * k,+ });+ },+ [animate, ref],+ );++ const zoomBy = useCallback(+ (factor: number) => {+ const el = ref.current;+ if (!el) return;+ target.current = null;+ animate();+ setView((v) =>+ zoomAround(v, clamp(v.k * factor, MIN_K, MAX_K), el.clientWidth / 2, el.clientHeight / 2),+ );+ },+ [animate, ref],+ );++ const fitAll = useCallback(() => fit(boardRef.current.bounds), [fit]);++ const pageViews = useSingleton(() => createPageViews<ViewState>());+ const pageRef = useRef(board.pageId);+ const viewRef = useRef(view);+ viewRef.current = view;+ useEffect(() => {+ const previous = pageRef.current;+ if (previous === board.pageId) return;+ pageRef.current = board.pageId;+ const saved = pageViews.swap(previous, board.pageId, viewRef.current);+ if (!saved) return fit(boardRef.current.bounds, false);+ target.current = null;+ setFlying(false);+ setView(saved);+ }, [board.pageId, fit]);++ const outlineOpen = useArtboardStore((s) => s.outlineOpen);+ useEffect(() => {+ const t = target.current;+ if (t) fit(t.rect, true, t.pad);+ }, [fit, outlineOpen]);++ const camera = useArtboardStore((s) => s.camera);+ useEffect(() => {+ if (!camera) return;+ const current = boardRef.current;+ if (camera.kind === 'all') return fitAll();+ if (camera.kind === 'item') {+ const rect = itemRect(current, camera.id);+ if (rect) fit(rect, true, 120);+ return;+ }+ const rect = groupBounds(+ current,+ camera.kind === 'journey' ? current.journeyGroupId : camera.id,+ );+ if (rect) fit(rect, true, 48);+ }, [camera, fit, fitAll]);++ useEffect(() => {+ const el = ref.current;+ if (!el) return;+ const observer = new ResizeObserver(() => {+ const t = target.current;+ if (t) fit(t.rect, false, t.pad);+ });+ observer.observe(el);+ return () => observer.disconnect();+ }, [fit, ref]);++ useEffect(() => {+ const el = ref.current;+ if (!el) return;+ const onWheel = (e: WheelEvent) => {+ e.preventDefault();+ target.current = null;+ setFlying(false);+ const rect = el.getBoundingClientRect();+ const px = e.clientX - rect.left;+ const py = e.clientY - rect.top;+ if (e.ctrlKey || e.metaKey) {+ setView((v) =>+ zoomAround(v, clamp(v.k * Math.exp(-e.deltaY * 0.01), MIN_K, MAX_K), px, py),+ );+ } else {+ setView((v) => ({ ...v, x: v.x - e.deltaX, y: v.y - e.deltaY }));+ }+ };+ el.addEventListener('wheel', onWheel, { passive: false });+ return () => el.removeEventListener('wheel', onWheel);+ }, [ref]);++ useEffect(() => () => clearTimeout(flyTimer.current), []);++ const onPointerDown = (e: PointerEvent<HTMLDivElement>) => {+ if (e.button !== 0 || drag.current) return;+ drag.current = {+ moved: false,+ onItem: !!(e.target as HTMLElement).closest('[data-board-item]'),+ pointerId: e.pointerId,+ sx: e.clientX,+ sy: e.clientY,+ vx: view.x,+ vy: view.y,+ };+ setFlying(false);+ };++ const onPointerMove = (e: PointerEvent<HTMLDivElement>) => {+ const d = drag.current;+ if (!d || d.pointerId !== e.pointerId) return;+ const dx = e.clientX - d.sx;+ const dy = e.clientY - d.sy;+ if (!d.moved && Math.hypot(dx, dy) < 4) return;+ if (!d.moved) {+ d.moved = true;+ e.currentTarget.setPointerCapture(e.pointerId);+ target.current = null;+ setPanning(true);+ }+ setView((v) => ({ ...v, x: d.vx + dx, y: d.vy + dy }));+ };++ const onPointerUp = (e: PointerEvent<HTMLDivElement>) => {+ const d = drag.current;+ if (d && d.pointerId !== e.pointerId) return;+ drag.current = null;+ setPanning(false);+ if (d?.moved) suppressClick.current = true;+ if (d && !d.moved && !d.onItem) onBackgroundClick();+ };++ const onClickCapture = (e: { stopPropagation: () => void }) => {+ if (!suppressClick.current) return;+ suppressClick.current = false;+ e.stopPropagation();+ };++ return {+ fitAll,+ flying,+ handlers: {+ onClickCapture,+ onPointerCancel: onPointerUp,+ onPointerDown,+ onPointerMove,+ onPointerUp,+ },+ panning,+ view,+ zoomBy,+ };+};diff --git a/src/features/Artboard/Canvas/visibleBoards.test.ts b/src/features/Artboard/Canvas/visibleBoards.test.tsnew file mode 100644index 00000000000..046c84b2723--- /dev/null+++ b/src/features/Artboard/Canvas/visibleBoards.test.ts@@ -0,0 +1,49 @@+import type { ArtboardBoardView } from '@lobechat/types';+import { describe, expect, it } from 'vitest';++import { MAX_LIVE, nextLiveBoards } from './visibleBoards';++const board = (id: string, x: number, w = 640) =>+ ({ id, rect: { h: 400, w, x, y: 0 } }) as ArtboardBoardView;++const boards = [board('a', 0), board('b', 840), board('c', 4000)];+const screen = { height: 800, width: 1200 };+const at = (k: number, x = 0) => ({ ...screen, k, x, y: 0 });++describe('nextLiveBoards', () => {+ it('mounts the readable boards in the viewport', () => {+ expect(nextLiveBoards([], boards, at(1))).toEqual(['a', 'b']);+ });++ it('keeps a mounted board after it leaves the viewport', () => {+ expect(nextLiveBoards(['a', 'b'], boards, at(1, -700))).toEqual(['b', 'a']);+ });++ it('keeps mounted boards when zoomed out too far to read them', () => {+ const live = ['a', 'b'];+ expect(nextLiveBoards(live, boards, at(0.1))).toBe(live);+ });++ it('does not mount a board first seen too small to read', () => {+ expect(nextLiveBoards([], boards, at(0.1))).toEqual([]);+ });++ it('judges readability by each board’s own width', () => {+ expect(nextLiveBoards([], [board('wide', 0, 1600), board('a', 0)], at(0.1))).toEqual(['wide']);+ });++ it('releases the board seen least recently once the cap is reached', () => {+ const many = Array.from({ length: MAX_LIVE }, (_, i) => board(`b${i}`, 10_000 + i * 700));+ const previous = many.map((b) => b.id);++ const next = nextLiveBoards(previous, [board('new', 0), ...many], at(1));++ expect(next).toHaveLength(MAX_LIVE);+ expect(next[0]).toBe('new');+ expect(next).not.toContain(`b${MAX_LIVE - 1}`);+ });++ it('forgets boards that are no longer on the page', () => {+ expect(nextLiveBoards(['gone', 'a'], boards, at(0.1))).toEqual(['a']);+ });+});diff --git a/src/features/Artboard/Canvas/visibleBoards.ts b/src/features/Artboard/Canvas/visibleBoards.tsnew file mode 100644index 00000000000..136d69bdeb4--- /dev/null+++ b/src/features/Artboard/Canvas/visibleBoards.ts@@ -0,0 +1,43 @@+import type { ArtboardBoardView } from '@lobechat/types';++export const LIVE_MIN_WIDTH = 96;+export const MAX_LIVE = 24;++interface Viewport {+ height: number;+ k: number;+ width: number;+ x: number;+ y: number;+}++const readableInView = ({ rect }: ArtboardBoardView, view: Viewport) => {+ if (rect.w * view.k < LIVE_MIN_WIDTH) return false;+ const left = rect.x * view.k + view.x;+ const top = rect.y * view.k + view.y;+ return (+ left < view.width &&+ top < view.height &&+ left + rect.w * view.k > 0 &&+ top + rect.h * view.k > 0+ );+};++// A mounted Canvas is never dropped for zooming out or panning away: the overview must keep+// showing real screens. Only the cap releases one, the board seen least recently first.+export const nextLiveBoards = (+ previous: readonly string[],+ boards: ArtboardBoardView[],+ view: Viewport,+): readonly string[] => {+ const onPage = new Set(boards.map((b) => b.id));+ const seen = boards.filter((b) => readableInView(b, view)).map((b) => b.id);+ const fresh = new Set(seen);+ const next = [...seen, ...previous.filter((id) => onPage.has(id) && !fresh.has(id))].slice(+ 0,+ MAX_LIVE,+ );+ return next.length === previous.length && next.every((id, i) => id === previous[i])+ ? previous+ : next;+};diff --git a/src/features/Artboard/Comments/CommentPopover.tsx b/src/features/Artboard/Comments/CommentPopover.tsxnew file mode 100644index 00000000000..13b48c8fc16--- /dev/null+++ b/src/features/Artboard/Comments/CommentPopover.tsx@@ -0,0 +1,49 @@+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import { type ReactNode, useLayoutEffect, useRef, useState } from 'react';++import { sx } from '@/styles/sx';++import { popoverBox } from './layout';++const styles = stylex.create({+ popover: {+ backgroundColor: cssVar.colorBgElevated,+ borderRadius: 14,+ boxShadow: cssVar.boxShadowSecondary,+ overflowY: 'auto',+ overscrollBehavior: 'contain',+ position: 'absolute',+ userSelect: 'text',+ zIndex: 8,+ },+});++interface CommentPopoverProps {+ anchor: { x: number; y: number };+ children: ReactNode;+ size: { height: number; width: number };+}++const CommentPopover = ({ anchor, children, size }: CommentPopoverProps) => {+ const ref = useRef<HTMLDivElement>(null);+ const [measured, setMeasured] = useState(420);++ useLayoutEffect(() => {+ const element = ref.current;+ if (!element) return;+ const measure = () => setMeasured(element.offsetHeight);+ measure();+ const observer = new ResizeObserver(measure);+ observer.observe(element);+ return () => observer.disconnect();+ }, []);++ return (+ <div ref={ref} {...sx(styles.popover, popoverBox(anchor, size, measured))}>+ {children}+ </div>+ );+};++export default CommentPopover;diff --git a/src/features/Artboard/Comments/Composer.tsx b/src/features/Artboard/Comments/Composer.tsxnew file mode 100644index 00000000000..287c67ca5e6--- /dev/null+++ b/src/features/Artboard/Comments/Composer.tsx@@ -0,0 +1,123 @@+import { Button, TextArea, toast } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import { ArrowUp } from 'lucide-react';+import { type ReactNode, useState } from 'react';+import { useTranslation } from 'react-i18next';++const styles = stylex.create({+ actions: {+ alignItems: 'center',+ display: 'flex',+ gap: 4,+ justifyContent: 'flex-end',+ },+ composer: {+ paddingBlockEnd: 12,+ paddingBlockStart: 2,+ paddingInline: 14,+ },+ hint: {+ color: cssVar.colorTextQuaternary,+ fontSize: 10,+ paddingBlockEnd: 10,+ paddingInline: 14,+ },+ now: {+ color: cssVar.colorTextTertiary,+ fontSize: 12,+ },+});++const fieldStyle = {+ fontSize: 'inherit',+ lineHeight: 1.6,+ minHeight: 44,+ padding: 0,+};++interface ComposerProps {+ action: string;+ autoFocus?: boolean;+ hint?: ReactNode;+ nowAction?: string;+ onSend: (text: string, now: boolean) => Promise<unknown>;+ placeholder: string;+}++const Composer = ({ action, autoFocus, hint, nowAction, onSend, placeholder }: ComposerProps) => {+ const { t } = useTranslation('project');+ const [text, setText] = useState('');+ const [sending, setSending] = useState<'add' | 'now' | null>(null);+ const empty = !text.trim();++ const send = async (now: boolean) => {+ const content = text.trim();+ if (!content || sending) return;+ setSending(now ? 'now' : 'add');+ try {+ await onSend(content, now);+ setText('');+ } catch (error) {+ toast.error({+ description: (error as Error).message,+ title: t('artboard.comment.failed'),+ });+ } finally {+ setSending(null);+ }+ };++ return (+ <>+ <div {...stylex.props(styles.composer)}>+ <TextArea+ autoFocus={autoFocus}+ autoSize={{ maxRows: 12, minRows: 1 }}+ disabled={!!sending}+ placeholder={placeholder}+ resize={false}+ style={fieldStyle}+ value={text}+ variant="borderless"+ onChange={(event) => setText(event.target.value)}+ onKeyDown={(event) => {+ if (event.nativeEvent.isComposing) return;+ if (event.key === 'Enter' && (event.metaKey || event.ctrlKey)) {+ event.preventDefault();+ void send(false);+ }+ }}+ />+ <div {...stylex.props(styles.actions)}>+ {nowAction && (+ <Button+ disabled={empty || !!sending}+ loading={sending === 'now'}+ size="small"+ type="text"+ onClick={() => send(true)}+ {...stylex.props(styles.now)}+ >+ {nowAction}+ </Button>+ )}+ <Button+ aria-label={action}+ disabled={empty || !!sending}+ icon={<ArrowUp size={15} strokeWidth={2.4} />}+ loading={sending === 'add'}+ shape="circle"+ size="small"+ title={action}+ type="primary"+ onClick={() => send(false)}+ />+ </div>+ </div>+ {hint && <div {...stylex.props(styles.hint)}>{hint}</div>}+ </>+ );+};++export default Composer;diff --git a/src/features/Artboard/Comments/DraftCard.tsx b/src/features/Artboard/Comments/DraftCard.tsxnew file mode 100644index 00000000000..914b1c87e34--- /dev/null+++ b/src/features/Artboard/Comments/DraftCard.tsx@@ -0,0 +1,46 @@+import * as stylex from '@stylexjs/stylex';+import { useTranslation } from 'react-i18next';++import { isMacOS } from '@/utils/platform';++import { useSubmitBatch } from '../Board/useSubmitBatch';+import { useBoard } from '../BoardContext';+import { addThread } from '../data/commentActions';+import { artboardActions } from '../store';+import type { CommentDraft } from '../store/initialState';+import Composer from './Composer';+import { cardStyles } from './styles';++const DraftCard = ({ draft }: { draft: CommentDraft }) => {+ const { t } = useTranslation('project');+ const board = useBoard();+ const submitBatch = useSubmitBatch();+ const artboardId = board.artboard.id;+ const { x: _x, y: _y, ...target } = draft;+ const place =+ (target.boardId && board.boardById[target.boardId]?.title) ||+ (target.groupId && board.groups.find((group) => group.id === target.groupId)?.title) ||+ t('artboard.comment.onCanvas');++ return (+ <div {...stylex.props(cardStyles.card)}>+ <div {...stylex.props(cardStyles.head)}>+ <span {...stylex.props(cardStyles.label)}>{place}</span>+ </div>+ <Composer+ autoFocus+ action={t('artboard.comment.send')}+ hint={t('artboard.comment.sendHint', { mod: isMacOS() ? '⌘' : 'Ctrl' })}+ nowAction={t('artboard.comment.sendNow')}+ placeholder={t('artboard.comment.placeholder')}+ onSend={async (text, now) => {+ const thread = await addThread(artboardId, target, text);+ artboardActions.openThread(thread.id);+ if (now) await submitBatch([]);+ }}+ />+ </div>+ );+};++export default DraftCard;diff --git a/src/features/Artboard/Comments/Message.tsx b/src/features/Artboard/Comments/Message.tsxnew file mode 100644index 00000000000..9c456234990--- /dev/null+++ b/src/features/Artboard/Comments/Message.tsx@@ -0,0 +1,75 @@+import type { ArtboardCommentView } from '@lobechat/types';+import { Icon } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import { BotIcon } from 'lucide-react';+import { useTranslation } from 'react-i18next';++import { useUserStore } from '@/store/user';+import { userProfileSelectors } from '@/store/user/selectors';++import { artboardTokens } from '../tokens.stylex';++const styles = stylex.create({+ agent: {+ backgroundColor: artboardTokens.agent,+ },+ avatar: {+ alignItems: 'center',+ backgroundColor: artboardTokens.human,+ borderRadius: '50%',+ color: cssVar.colorWhite,+ display: 'flex',+ flexShrink: 0,+ fontSize: 10,+ fontWeight: 600,+ height: 20,+ justifyContent: 'center',+ width: 20,+ },+ text: {+ overflowWrap: 'anywhere',+ whiteSpace: 'pre-wrap',+ },+ time: {+ color: cssVar.colorTextQuaternary,+ fontWeight: 400,+ },+ who: {+ alignItems: 'center',+ display: 'flex',+ fontSize: 11,+ fontWeight: 600,+ gap: 7,+ marginBlockEnd: 2,+ },+});++const timeOf = (value: Date | string) =>+ new Date(value).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });++const Message = ({ comment }: { comment: ArtboardCommentView }) => {+ const { t } = useTranslation('project');+ const me = useUserStore(userProfileSelectors.userId);+ const agent = !!comment.authorAgentId;+ const name = agent+ ? t('artboard.comment.agent')+ : comment.authorUserId === me+ ? t('artboard.comment.you')+ : t('artboard.comment.member');++ return (+ <div>+ <div {...stylex.props(styles.who)}>+ <span {...stylex.props(styles.avatar, agent && styles.agent)}>+ {agent ? <Icon icon={BotIcon} size={12} /> : [...name][0]}+ </span>+ {name}+ <span {...stylex.props(styles.time)}>{timeOf(comment.createdAt)}</span>+ </div>+ <div {...stylex.props(styles.text)}>{comment.content}</div>+ </div>+ );+};++export default Message;diff --git a/src/features/Artboard/Comments/Pin.tsx b/src/features/Artboard/Comments/Pin.tsxnew file mode 100644index 00000000000..c94cef03d5a--- /dev/null+++ b/src/features/Artboard/Comments/Pin.tsx@@ -0,0 +1,102 @@+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';++import { sx } from '@/styles/sx';++import { artboardTokens } from '../tokens.stylex';+import { PIN_SIZE, type PinTone } from './layout';++const SIZE = 28;++const styles = stylex.create({+ dot: {+ backgroundColor: cssVar.colorWarning,+ borderColor: cssVar.colorWhite,+ borderRadius: '50%',+ borderStyle: 'solid',+ borderWidth: 2,+ height: 10,+ insetBlockStart: -4,+ insetInlineEnd: -4,+ position: 'absolute',+ width: 10,+ },+ open: {+ outlineColor: artboardTokens.selectionLine,+ outlineStyle: 'solid',+ outlineWidth: 3,+ },+ pin: {+ alignItems: 'center',+ appearance: 'none',+ backgroundColor: artboardTokens.selection,+ borderColor: cssVar.colorWhite,+ borderStyle: 'solid',+ borderWidth: 2,+ borderBottomLeftRadius: 0,+ borderBottomRightRadius: '50%',+ borderTopLeftRadius: '50%',+ borderTopRightRadius: '50%',+ boxSizing: 'border-box',+ color: cssVar.colorWhite,+ cursor: 'pointer',+ display: 'flex',+ fontFamily: cssVar.fontFamily,+ fontSize: 11,+ fontWeight: 600,+ height: SIZE,+ justifyContent: 'center',+ lineHeight: 1,+ margin: 0,+ padding: 0,+ position: 'absolute',+ width: SIZE,+ zIndex: 7,+ },+ resolved: {+ backgroundColor: artboardTokens.resolved,+ color: artboardTokens.resolvedText,+ },+ stale: {+ backgroundColor: cssVar.colorBgLayout,+ borderColor: artboardTokens.stale,+ borderStyle: 'dashed',+ color: artboardTokens.stale,+ },+ waiting: {+ backgroundColor: cssVar.colorWarning,+ },+});++const toneStyles = {+ default: null,+ resolved: styles.resolved,+ stale: styles.stale,+ waiting: styles.waiting,+} as const;++interface PinProps {+ at: { x: number; y: number };+ label?: string;+ number?: number;+ onClick?: () => void;+ open?: boolean;+ tone?: PinTone;+ unsent?: boolean;+}++const Pin = ({ at, label, number, onClick, open, tone = 'default', unsent }: PinProps) => {+ const props = sx(styles.pin, toneStyles[tone], open && styles.open, {+ left: at.x,+ top: at.y - PIN_SIZE,+ });+ if (!onClick) return <span {...props} />;+ return (+ <button aria-label={label} aria-pressed={open} type="button" {...props} onClick={onClick}>+ {number}+ {unsent && <span {...stylex.props(styles.dot)} />}+ </button>+ );+};++export default Pin;diff --git a/src/features/Artboard/Comments/ThreadCard.tsx b/src/features/Artboard/Comments/ThreadCard.tsxnew file mode 100644index 00000000000..b006953d9d1--- /dev/null+++ b/src/features/Artboard/Comments/ThreadCard.tsx@@ -0,0 +1,177 @@+import type { ArtboardCommentThreadView } from '@lobechat/types';+import { ActionIcon, Tag, toast } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import { CheckIcon, RotateCcwIcon, XIcon } from 'lucide-react';+import { useState } from 'react';+import { useTranslation } from 'react-i18next';++import { useSubmitBatch } from '../Board/useSubmitBatch';+import { useBoard } from '../BoardContext';+import { replyThread, settleThread } from '../data/commentActions';+import { isAnswered, isQuestion, threadPlace } from '../data/commentModel';+import { artboardTokens } from '../tokens.stylex';+import Composer from './Composer';+import Message from './Message';+import { cardStyles } from './styles';++const ICON_SIZE = { blockSize: 22, size: 13 };++const styles = stylex.create({+ badge: {+ borderRadius: 999,+ flexShrink: 0,+ fontSize: 10,+ height: 'auto',+ lineHeight: 1.6,+ marginInlineEnd: 0,+ paddingBlock: 1,+ paddingInline: 8,+ },+ info: {+ backgroundColor: cssVar.colorInfoBg,+ color: cssVar.colorInfoText,+ },+ messages: {+ display: 'flex',+ flexDirection: 'column',+ gap: 12,+ paddingBlock: 10,+ paddingInline: 14,+ },+ neutral: {+ backgroundColor: cssVar.colorFillTertiary,+ color: cssVar.colorTextSecondary,+ },+ stale: {+ color: artboardTokens.stale,+ },+ tools: {+ display: 'flex',+ flexShrink: 0,+ gap: 2,+ marginInlineStart: -4,+ },+ warning: {+ backgroundColor: cssVar.colorWarningBg,+ color: cssVar.colorWarningText,+ },+});++type BadgeTone = 'info' | 'neutral' | 'warning';++const StateTag = ({ children, tone }: { children: string; tone: BadgeTone }) => (+ <Tag+ shape="round"+ size="small"+ variant="borderless"+ {...stylex.props(styles.badge, styles[tone])}+ >+ {children}+ </Tag>+);++interface ThreadCardProps {+ number?: number;+ onClose: () => void;+ thread: ArtboardCommentThreadView;+}++const ThreadCard = ({ number, onClose, thread }: ThreadCardProps) => {+ const { t } = useTranslation(['project', 'common']);+ const board = useBoard();+ const artboardId = board.artboard.id;+ const [settling, setSettling] = useState(false);+ const submitBatch = useSubmitBatch();+ const question = isQuestion(thread);+ const answered = question && isAnswered(thread);+ const resolved = !!thread.resolvedAt;+ const place = threadPlace(thread, board);+ const placeTitle = place.kind === 'canvas' ? t('artboard.comment.onCanvas') : place.title;++ const settle = async (next: boolean) => {+ setSettling(true);+ try {+ await settleThread(artboardId, thread.id, next);+ } catch (error) {+ toast.error((error as Error).message);+ } finally {+ setSettling(false);+ }+ };++ const resolveLabel = t('artboard.comment.resolve');+ const reopenLabel = t('artboard.comment.reopen');+ const closeLabel = t('close', { ns: 'common' });++ return (+ <div {...stylex.props(cardStyles.card)}>+ <div {...stylex.props(cardStyles.head)}>+ <span {...stylex.props(cardStyles.label)}>+ {number ? `#${number} · ` : ''}+ {placeTitle}+ {thread.stale && (+ <span {...stylex.props(styles.stale)}> · {t('artboard.comment.stale')}</span>+ )}+ </span>+ {thread.unread && <StateTag tone="info">{t('artboard.comment.unread')}</StateTag>}+ {!resolved && question && (+ <StateTag tone={answered ? 'neutral' : 'warning'}>+ {t(answered ? 'artboard.question.answered' : 'artboard.question.waiting')}+ </StateTag>+ )}+ {resolved && <StateTag tone="neutral">{t('artboard.comment.resolved')}</StateTag>}+ <span {...stylex.props(styles.tools)}>+ {resolved ? (+ <ActionIcon+ aria-label={reopenLabel}+ icon={RotateCcwIcon}+ loading={settling}+ size={ICON_SIZE}+ title={reopenLabel}+ onClick={() => settle(false)}+ />+ ) : (+ (!question || answered) && (+ <ActionIcon+ aria-label={resolveLabel}+ icon={CheckIcon}+ loading={settling}+ size={ICON_SIZE}+ title={resolveLabel}+ onClick={() => settle(true)}+ />+ )+ )}+ <ActionIcon+ aria-label={closeLabel}+ icon={XIcon}+ size={ICON_SIZE}+ title={closeLabel}+ onClick={onClose}+ />+ </span>+ </div>+ <div {...stylex.props(styles.messages)}>+ <Message comment={thread} />+ {(thread.replies ?? []).map((reply) => (+ <Message comment={reply} key={reply.id} />+ ))}+ </div>+ {!resolved && (+ <Composer+ action={t(question ? 'artboard.question.answer' : 'artboard.comment.send')}+ hint={question ? t('artboard.question.hint') : undefined}+ nowAction={t('artboard.comment.sendNow')}+ placeholder={t(question ? 'artboard.question.placeholder' : 'artboard.comment.reply')}+ onSend={async (text, now) => {+ await replyThread(artboardId, thread.id, text);+ if (now) await submitBatch([]);+ }}+ />+ )}+ </div>+ );+};++export default ThreadCard;diff --git a/src/features/Artboard/Comments/layout.test.ts b/src/features/Artboard/Comments/layout.test.tsnew file mode 100644index 00000000000..5ba2b12e378--- /dev/null+++ b/src/features/Artboard/Comments/layout.test.ts@@ -0,0 +1,103 @@+import type { ArtboardCommentThreadView } from '@lobechat/types';+import { describe, expect, it } from 'vitest';++import { pinTone, popoverBox, threadNumbers } from './layout';++const thread = (id: string, patch: Partial<ArtboardCommentThreadView> = {}) =>+ ({+ anchor: null,+ authorAgentId: null,+ authorUserId: 'u1',+ boardId: null,+ content: id,+ createdAt: new Date(0),+ groupId: null,+ id,+ pageId: 'p1',+ replies: [],+ resolvedAt: null,+ stale: false,+ unread: false,+ ...patch,+ }) as ArtboardCommentThreadView;++describe('popoverBox', () => {+ const size = { height: 800, width: 1200 };++ it('opens 42px right of the pin, top aligned with the pin head', () => {+ expect(popoverBox({ x: 200, y: 300 }, size, 200)).toEqual({+ left: 242,+ maxHeight: 420,+ top: 272,+ width: 300,+ });+ });++ it('flips to the left of the pin when the right side overflows', () => {+ expect(popoverBox({ x: 1000, y: 300 }, size, 200).left).toBe(1000 - 14 - 300);+ });++ it('keeps 12px from the edges and 64px from the top', () => {+ expect(popoverBox({ x: 0, y: 10 }, size, 200)).toMatchObject({ left: 42, top: 64 });+ expect(popoverBox({ x: 200, y: 790 }, size, 300).top).toBe(800 - 300 - 12);+ expect(popoverBox({ x: 200, y: 790 }, size, 900).top).toBe(800 - 420 - 12);+ });++ it('narrows to the viewport minus 24px', () => {+ expect(popoverBox({ x: 10, y: 300 }, { height: 600, width: 280 }, 100)).toMatchObject({+ left: 12,+ width: 256,+ });+ });++ it('caps the height to what fits under the top inset', () => {+ expect(popoverBox({ x: 10, y: 100 }, { height: 300, width: 900 }, 500).maxHeight).toBe(+ 300 - 64 - 12,+ );+ });+});++describe('threadNumbers', () => {+ it('numbers threads by creation order across the artboard', () => {+ const numbers = threadNumbers([+ thread('b', { createdAt: new Date(2000) }),+ thread('a', { createdAt: new Date(1000) }),+ thread('c', { createdAt: new Date(2000), pageId: 'p2' }),+ ]);+ expect([...numbers]).toEqual([+ ['a', 1],+ ['b', 2],+ ['c', 3],+ ]);+ });++ it('accepts serialized dates', () => {+ const numbers = threadNumbers([+ thread('late', { createdAt: '2026-01-02T00:00:00Z' as unknown as Date }),+ thread('early', { createdAt: '2026-01-01T00:00:00Z' as unknown as Date }),+ ]);+ expect(numbers.get('early')).toBe(1);+ });+});++describe('pinTone', () => {+ const agent = { authorAgentId: 'agt', authorUserId: null };+ const answer = {+ authorAgentId: null,+ authorUserId: 'u1',+ content: 'ok',+ createdAt: new Date(0),+ id: 'r',+ };++ it('marks a question the user still owes an answer as waiting', () => {+ expect(pinTone(thread('q', agent))).toBe('waiting');+ expect(pinTone(thread('q', { ...agent, replies: [answer] }))).toBe('default');+ });++ it('puts resolved before stale before waiting', () => {+ expect(pinTone(thread('t', { resolvedAt: new Date(1), stale: true }))).toBe('resolved');+ expect(pinTone(thread('t', { ...agent, stale: true }))).toBe('stale');+ expect(pinTone(thread('t'))).toBe('default');+ });+});diff --git a/src/features/Artboard/Comments/layout.ts b/src/features/Artboard/Comments/layout.tsnew file mode 100644index 00000000000..5e3f94043b4--- /dev/null+++ b/src/features/Artboard/Comments/layout.ts@@ -0,0 +1,51 @@+import type { ArtboardCommentThreadView } from '@lobechat/types';++import { isAnswered, isQuestion } from '../data/commentModel';++export const PIN_SIZE = 28;+const POPOVER_WIDTH = 300;+const POPOVER_MAX_HEIGHT = 420;+const PIN_GAP = 14;+const EDGE = 12;+const TOP_INSET = 64;++export interface PopoverBox {+ left: number;+ maxHeight: number;+ top: number;+ width: number;+}++export const popoverBox = (+ pin: { x: number; y: number },+ size: { height: number; width: number },+ measuredHeight: number,+): PopoverBox => {+ const width = Math.max(0, Math.min(POPOVER_WIDTH, size.width - EDGE * 2));+ const right = pin.x + PIN_SIZE + PIN_GAP;+ const preferred = right + width > size.width - EDGE ? pin.x - PIN_GAP - width : right;+ const left = Math.max(EDGE, Math.min(preferred, size.width - width - EDGE));+ const topInset = Math.min(TOP_INSET, Math.max(0, size.height - EDGE));+ const maxHeight = Math.max(0, Math.min(POPOVER_MAX_HEIGHT, size.height - topInset - EDGE));+ const shown = Math.min(measuredHeight, maxHeight);+ const top = Math.max(topInset, Math.min(pin.y - PIN_SIZE, size.height - shown - EDGE));+ return { left, maxHeight, top, width };+};++const timeOf = (value: Date | string) => new Date(value).getTime();++export const threadNumbers = (threads: ArtboardCommentThreadView[]) =>+ new Map(+ threads+ .toSorted((a, b) => timeOf(a.createdAt) - timeOf(b.createdAt))+ .map((thread, index) => [thread.id, index + 1] as const),+ );++export type PinTone = 'default' | 'resolved' | 'stale' | 'waiting';++export const pinTone = (thread: ArtboardCommentThreadView): PinTone => {+ if (thread.resolvedAt) return 'resolved';+ if (thread.stale) return 'stale';+ if (isQuestion(thread) && !isAnswered(thread)) return 'waiting';+ return 'default';+};diff --git a/src/features/Artboard/Comments/styles.ts b/src/features/Artboard/Comments/styles.tsnew file mode 100644index 00000000000..1b0a25ef77d--- /dev/null+++ b/src/features/Artboard/Comments/styles.ts@@ -0,0 +1,27 @@+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';++export const cardStyles = stylex.create({+ card: {+ color: cssVar.colorText,+ cursor: 'default',+ fontSize: 12,+ lineHeight: 1.6,+ },+ head: {+ alignItems: 'center',+ display: 'flex',+ fontSize: 11,+ gap: 8,+ paddingBlockStart: 10,+ paddingInline: 14,+ },+ label: {+ color: cssVar.colorTextTertiary,+ flex: '1',+ minWidth: 0,+ overflow: 'hidden',+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap',+ },+});diff --git a/src/features/Artboard/Conversation/BoardCard.tsx b/src/features/Artboard/Conversation/BoardCard.tsxnew file mode 100644index 00000000000..ca0a193eff4--- /dev/null+++ b/src/features/Artboard/Conversation/BoardCard.tsx@@ -0,0 +1,108 @@+import {+ ArtboardApiName,+ type ArtboardToolState,+ type CreateArtboardParams,+} from '@lobechat/builtin-tool-artboard';+import type { BuiltinRenderProps } from '@lobechat/types';+import { Block, Button, Center, Flexbox, Icon } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import { PresentationIcon } from 'lucide-react';+import { useTranslation } from 'react-i18next';++import { useArtboardFeature } from '../useArtboardFeature';+import { openBoardPanel } from './openBoardPanel';++const styles = stylex.create({+ card: {+ borderColor: cssVar.colorBorderSecondary,+ borderRadius: 12,+ },+ tile: {+ backgroundColor: cssVar.colorFillTertiary,+ borderRadius: 8,+ color: cssVar.colorTextSecondary,+ flex: 'none',+ height: 36,+ width: 36,+ },+ eyebrow: {+ color: cssVar.colorTextTertiary,+ fontSize: 12,+ },+ title: {+ color: cssVar.colorText,+ fontSize: 14,+ fontWeight: 600,+ overflow: 'hidden',+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap',+ },+ meta: {+ color: cssVar.colorTextSecondary,+ fontSize: 12,+ overflow: 'hidden',+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap',+ },+ open: {+ borderRadius: 999,+ flex: 'none',+ },+});++type BoardCardProps = BuiltinRenderProps<Partial<CreateArtboardParams>, ArtboardToolState>;++const BoardCard = ({ apiName, args, pluginError, pluginState }: BoardCardProps) => {+ const { t } = useTranslation('project');+ const { enabled } = useArtboardFeature();+ const artboardId = pluginState?.artboardId;+ if (!enabled || pluginError || !artboardId) return null;++ const updated = apiName === ArtboardApiName.updateArtboard;+ const open = () => openBoardPanel(artboardId);++ return (+ <Block+ clickable+ horizontal+ align={'center'}+ gap={12}+ paddingBlock={10}+ paddingInline={12}+ variant={'outlined'}+ {...stylex.props(styles.card)}+ onClick={open}+ >+ <Center {...stylex.props(styles.tile)}>+ <Icon icon={PresentationIcon} size={{ size: 18, strokeWidth: 1.75 }} />+ </Center>+ <Flexbox flex={1} gap={2} style={{ minWidth: 0 }}>+ <span {...stylex.props(styles.eyebrow)}>+ {updated+ ? t('artboard.card.updated', { revision: pluginState.revision })+ : t('artboard.title')}+ </span>+ <span {...stylex.props(styles.title)}>{pluginState.title || args?.title}</span>+ <span {...stylex.props(styles.meta)}>+ {t('artboard.card.summary', {+ boards: pluginState.boardCount,+ groups: pluginState.groupCount,+ })}+ </span>+ </Flexbox>+ <Button+ size={'small'}+ {...stylex.props(styles.open)}+ onClick={(e) => {+ e.stopPropagation();+ open();+ }}+ >+ {t('artboard.card.openBoard')}+ </Button>+ </Block>+ );+};++export default BoardCard;diff --git a/src/features/Artboard/Conversation/BoardPane.tsx b/src/features/Artboard/Conversation/BoardPane.tsxnew file mode 100644index 00000000000..3fee5970860--- /dev/null+++ b/src/features/Artboard/Conversation/BoardPane.tsx@@ -0,0 +1,35 @@+import { Button, Center, Icon, Text } from '@lobehub/ui';+import { Minimize2Icon } from 'lucide-react';+import { useEffect } from 'react';+import { useTranslation } from 'react-i18next';++import BoardView from '../Board';+import { ArtboardFullscreen } from '../Board/Fullscreen';+import { artboardActions, useArtboardStore } from '../store';+import { useArtboardFeature } from '../useArtboardFeature';++const exitFullscreen = () => artboardActions.setFullscreen(false);++const FullscreenPlaceholder = ({ artboardId }: { artboardId: string }) => {+ const { t } = useTranslation('project');+ useEffect(() => exitFullscreen, []);+ return (+ <Center flex={1} gap={12}>+ <Text type="secondary">{t('artboard.fullscreen.placeholder')}</Text>+ <Button icon={<Icon icon={Minimize2Icon} />} onClick={exitFullscreen}>+ {t('artboard.header.exitFullscreen')}+ </Button>+ <ArtboardFullscreen artboardId={artboardId} onClose={exitFullscreen} />+ </Center>+ );+};++const BoardPane = ({ artboardId }: { artboardId: string }) => {+ const { enabled } = useArtboardFeature();+ const fullscreen = useArtboardStore((s) => s.fullscreen && s.boardId === artboardId);+ if (!enabled) return null;+ if (fullscreen) return <FullscreenPlaceholder artboardId={artboardId} />;+ return <BoardView artboardId={artboardId} />;+};++export default BoardPane;diff --git a/src/features/Artboard/Conversation/BoardTabLabel.tsx b/src/features/Artboard/Conversation/BoardTabLabel.tsxnew file mode 100644index 00000000000..bba9a4e8fda--- /dev/null+++ b/src/features/Artboard/Conversation/BoardTabLabel.tsx@@ -0,0 +1,15 @@+import { memo } from 'react';+import { useTranslation } from 'react-i18next';++import { useArtboard } from '../data/useArtboard';++const BoardTabLabel = memo<{ artboardId: string }>(({ artboardId }) => {+ const { t } = useTranslation('project');+ const { data } = useArtboard(artboardId);++ return data?.artboard.title || t('artboard.header.title');+});++BoardTabLabel.displayName = 'ArtboardTabLabel';++export default BoardTabLabel;diff --git a/src/features/Artboard/Conversation/openBoardPanel.test.ts b/src/features/Artboard/Conversation/openBoardPanel.test.tsnew file mode 100644index 00000000000..e8cec66fd7a--- /dev/null+++ b/src/features/Artboard/Conversation/openBoardPanel.test.ts@@ -0,0 +1,29 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { useGlobalStore } from '@/store/global';++import { openBoardPanel } from './openBoardPanel';++const feature = vi.hoisted(() => ({ enabled: true }));+vi.mock('../useArtboardFeature', () => ({ isArtboardEnabled: () => feature.enabled }));++describe('openBoardPanel', () => {+ const openWorkingSidebar = vi.fn();++ beforeEach(() => {+ openWorkingSidebar.mockReset();+ feature.enabled = true;+ useGlobalStore.setState({ openWorkingSidebar } as never);+ });++ it('opens the artboard as a tab of the working sidebar', () => {+ openBoardPanel('art_1');+ expect(openWorkingSidebar).toHaveBeenCalledWith('artboard:art_1');+ });++ it('does nothing while the feature is off', () => {+ feature.enabled = false;+ openBoardPanel('art_1');+ expect(openWorkingSidebar).not.toHaveBeenCalled();+ });+});diff --git a/src/features/Artboard/Conversation/openBoardPanel.ts b/src/features/Artboard/Conversation/openBoardPanel.tsnew file mode 100644index 00000000000..1656e20c51b--- /dev/null+++ b/src/features/Artboard/Conversation/openBoardPanel.ts@@ -0,0 +1,9 @@+import { useGlobalStore } from '@/store/global';+import { artboardTabKey } from '@/store/global/initialState';++import { isArtboardEnabled } from '../useArtboardFeature';++export const openBoardPanel = (artboardId: string) => {+ if (!isArtboardEnabled()) return;+ useGlobalStore.getState().openWorkingSidebar(artboardTabKey(artboardId));+};diff --git a/src/features/Artboard/Conversation/register.ts b/src/features/Artboard/Conversation/register.tsnew file mode 100644index 00000000000..45928a264f5--- /dev/null+++ b/src/features/Artboard/Conversation/register.ts@@ -0,0 +1,22 @@+import { ArtboardApiName } from '@lobechat/builtin-tool-artboard';+import { registerBuiltinRenders } from '@lobechat/builtin-tools/renders';+import type { BuiltinRender } from '@lobechat/types';++import { registerDeliverableTool } from '@/features/Conversation/Messages/AssistantGroup/toolRenderRules';++import BoardCard from './BoardCard';+import { ARTBOARD_TOOL } from './tool';++let registered = false;++export const registerArtboardTool = () => {+ if (registered) return;+ registered = true;+ registerDeliverableTool(ARTBOARD_TOOL);+ registerBuiltinRenders({+ [ARTBOARD_TOOL]: {+ [ArtboardApiName.createArtboard]: BoardCard as BuiltinRender,+ [ArtboardApiName.updateArtboard]: BoardCard as BuiltinRender,+ },+ });+};diff --git a/src/features/Artboard/Conversation/tool.ts b/src/features/Artboard/Conversation/tool.tsnew file mode 100644index 00000000000..fca995e7744--- /dev/null+++ b/src/features/Artboard/Conversation/tool.ts@@ -0,0 +1,3 @@+import { ArtboardIdentifier } from '@lobechat/builtin-tool-artboard';++export const ARTBOARD_TOOL = ArtboardIdentifier;diff --git a/src/features/Artboard/Finalize/FinalizeContent.tsx b/src/features/Artboard/Finalize/FinalizeContent.tsxnew file mode 100644index 00000000000..77d33af0c96--- /dev/null+++ b/src/features/Artboard/Finalize/FinalizeContent.tsx@@ -0,0 +1,182 @@+import { type ArtboardFinalizeIssue, checkFinalizeReadiness } from '@lobechat/types';+import { Button, Flexbox, Icon, ScrollArea, Tag, Text, toast, useModalContext } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import { type TFunction } from 'i18next';+import { LockIcon } from 'lucide-react';+import { useState } from 'react';+import { useTranslation } from 'react-i18next';++import { useAcceptanceOrigin } from '@/features/Acceptance/origin';++import { announceFinalized } from '../data/announceFinalized';+import { finalizeBoard } from '../data/finalizeBoard';+import { useBoardModel } from '../data/useBoardModel';+import type { BoardModel } from '../model';+import PendingItem from './PendingItem';++const BODY_MAX_HEIGHT = 'min(60vh, 520px)';++const styles = stylex.create({+ body: {+ paddingBlockStart: '4px',+ paddingBlockEnd: '16px',+ paddingInline: 16,+ },+ footer: {+ borderBlockStartColor: cssVar.colorBorderSecondary,+ borderBlockStartStyle: 'solid',+ borderBlockStartWidth: 1,+ paddingBlock: 12,+ paddingInline: 16,+ },+ check: {+ borderBlockEndColor: cssVar.colorBorderSecondary,+ borderBlockEndStyle: 'solid',+ borderBlockEndWidth: 1,+ paddingBlock: 8,+ },+ lock: {+ backgroundColor: cssVar.colorFillQuaternary,+ borderRadius: cssVar.borderRadiusLG,+ color: cssVar.colorTextSecondary,+ fontSize: 13,+ padding: 12,+ },+});++type StructureIssue = Exclude<+ ArtboardFinalizeIssue,+ { code: 'missing_check' | 'open_question' | 'open_round' }+>;++const isStructureIssue = (issue: ArtboardFinalizeIssue): issue is StructureIssue =>+ issue.code !== 'missing_check' && issue.code !== 'open_question' && issue.code !== 'open_round';++const issueText = (board: BoardModel, t: TFunction<'project'>, issue: StructureIssue) =>+ issue.code === 'unreachable'+ ? t('artboard.finalize.issue.unreachable', {+ title: board.boardById[issue.boardId]?.title ?? issue.boardId,+ })+ : t(`artboard.finalize.issue.${issue.code}`);++const FinalizeContent = ({ artboardId }: { artboardId: string }) => {+ const { t } = useTranslation('project');+ const { close } = useModalContext();+ const origin = useAcceptanceOrigin();+ const board = useBoardModel(artboardId);+ const [saving, setSaving] = useState(false);+ if (!board) return null;++ const issues = checkFinalizeReadiness(board.artboard.content);+ const structureIssues = issues.filter(isStructureIssue);+ const checks = board.journeyBoards.filter((item) => item.type !== 'decision');+ const { artboard } = board;++ const confirm = async () => {+ setSaving(true);+ try {+ const result = await finalizeBoard({+ announce: (acceptanceId) =>+ announceFinalized({+ acceptanceUrl: `${origin}/acceptance/${acceptanceId}`,+ artboard,+ count: checks.length,+ }),+ artboardId,+ revision: artboard.revision,+ });+ close();+ const url = result.acceptanceId ? `${origin}/acceptance/${result.acceptanceId}` : undefined;+ toast.success({+ actions: url+ ? [+ {+ label: t('artboard.finalize.openAcceptance'),+ onClick: () => window.open(url, '_blank', 'noopener'),+ },+ ]+ : undefined,+ title: t('artboard.finalize.success', { count: checks.length }),+ });+ } catch (error) {+ toast.error((error as Error).message);+ } finally {+ setSaving(false);+ }+ };++ return (+ <>+ <ScrollArea+ disableContentFit+ scrollFade+ style={{ maxHeight: BODY_MAX_HEIGHT, overflow: 'hidden' }}+ viewportProps={{ style: { height: 'auto', maxHeight: BODY_MAX_HEIGHT } }}+ >+ <Flexbox gap={16} {...stylex.props(styles.body)}>+ {structureIssues.length > 0 && (+ <Flexbox gap={4}>+ {structureIssues.map((issue) => (+ <Text+ key={issue.code === 'unreachable' ? `${issue.code}:${issue.boardId}` : issue.code}+ type="warning"+ >+ {issueText(board, t, issue)}+ </Text>+ ))}+ </Flexbox>+ )}+ {board.blockers.length > 0 && (+ <Flexbox gap={8}>+ <Text strong>+ {t('artboard.finalize.pendingTitle', { count: board.blockers.length })}+ </Text>+ {board.blockers.map((blocker) => (+ <PendingItem blocker={blocker} key={blocker.id} onDiscuss={close} />+ ))}+ </Flexbox>+ )}+ {checks.length > 0 && (+ <Flexbox gap={4}>+ <Text strong>{t('artboard.finalize.checksTitle', { count: checks.length })}</Text>+ {checks.map((item) => (+ <Flexbox+ horizontal+ align="center"+ gap={8}+ key={item.id}+ {...stylex.props(styles.check)}+ >+ <Text+ style={{ flex: 1, minWidth: 0 }}+ type={item.expected ? undefined : 'warning'}+ >+ {item.expected || t('artboard.finalize.missingCheck')}+ </Text>+ <Tag size={'small'}>{item.title}</Tag>+ </Flexbox>+ ))}+ </Flexbox>+ )}+ </Flexbox>+ </ScrollArea>+ <Flexbox gap={12} {...stylex.props(styles.footer)}>+ <Flexbox horizontal align="flex-start" gap={8} {...stylex.props(styles.lock)}>+ <Icon icon={LockIcon} size={14} style={{ marginTop: 3 }} />+ <span>{t('artboard.finalize.lockNote')}</span>+ </Flexbox>+ <Flexbox horizontal gap={8} justify="flex-end">+ <Button onClick={close}>{t('artboard.finalize.cancel')}</Button>+ <Button disabled={issues.length > 0} loading={saving} type={'primary'} onClick={confirm}>+ {issues.length+ ? t('artboard.finalize.blocked', { count: issues.length })+ : t('artboard.finalize.confirm')}+ </Button>+ </Flexbox>+ </Flexbox>+ </>+ );+};++export default FinalizeContent;diff --git a/src/features/Artboard/Finalize/PendingItem.tsx b/src/features/Artboard/Finalize/PendingItem.tsxnew file mode 100644index 00000000000..4c154665ab6--- /dev/null+++ b/src/features/Artboard/Finalize/PendingItem.tsx@@ -0,0 +1,73 @@+import { Button, Flexbox, Text } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import { useTranslation } from 'react-i18next';++import type { BoardBlocker } from '../model';+import { artboardActions } from '../store';++const styles = stylex.create({+ item: {+ backgroundColor: cssVar.colorWarningBg,+ borderColor: cssVar.colorWarningBorder,+ borderRadius: cssVar.borderRadiusLG,+ borderStyle: 'solid',+ borderWidth: 1,+ padding: 12,+ },+});++const copyOf = (blocker: BoardBlocker) => {+ if (blocker.kind === 'round')+ return {+ action: 'artboard.finalize.pending.goChoose',+ note: 'artboard.finalize.pending.round',+ } as const;+ if (blocker.answered)+ return {+ action: 'artboard.finalize.pending.view',+ note: 'artboard.finalize.pending.answered',+ } as const;+ return {+ action: 'artboard.finalize.pending.goAnswer',+ note: 'artboard.finalize.pending.question',+ } as const;+};++interface PendingItemProps {+ blocker: BoardBlocker;+ onDiscuss?: () => void;+}++const PendingItem = ({ blocker, onDiscuss }: PendingItemProps) => {+ const { t } = useTranslation('project');+ const copy = copyOf(blocker);+ const jump = () => {+ onDiscuss?.();+ if (blocker.kind === 'question')+ return artboardActions.showThread({+ boardId: blocker.boardId,+ id: blocker.id,+ pageId: blocker.pageId,+ });+ if (blocker.groupId)+ artboardActions.goTo({ id: blocker.groupId, kind: 'group', pageId: blocker.pageId });+ else artboardActions.setPage(blocker.pageId);+ };++ return (+ <Flexbox gap={8} {...stylex.props(styles.item)}>+ <Text strong>{blocker.text}</Text>+ <Text style={{ fontSize: 13 }} type="secondary">+ {t(copy.note)}+ </Text>+ <Flexbox horizontal gap={8}>+ <Button size={'small'} onClick={jump}>+ {t(copy.action)}+ </Button>+ </Flexbox>+ </Flexbox>+ );+};++export default PendingItem;diff --git a/src/features/Artboard/Finalize/index.tsx b/src/features/Artboard/Finalize/index.tsxnew file mode 100644index 00000000000..2cce5bb63be--- /dev/null+++ b/src/features/Artboard/Finalize/index.tsx@@ -0,0 +1,13 @@+import { createModal } from '@lobehub/ui';+import { t } from 'i18next';++import FinalizeContent from './FinalizeContent';++export const createFinalizeModal = (artboardId: string) =>+ createModal({+ content: <FinalizeContent artboardId={artboardId} />,+ footer: null,+ styles: { content: { minHeight: 0, overflow: 'hidden', padding: 0 } },+ title: t('artboard.finalize.title', { ns: 'project' }),+ width: 560,+ });diff --git a/src/features/Artboard/Gallery/OpenConversation.tsx b/src/features/Artboard/Gallery/OpenConversation.tsxnew file mode 100644index 00000000000..0e5816c41c4--- /dev/null+++ b/src/features/Artboard/Gallery/OpenConversation.tsx@@ -0,0 +1,36 @@+import { ActionIcon } from '@lobehub/ui';+import { MessageSquareIcon } from 'lucide-react';+import { useTranslation } from 'react-i18next';++import { getProjectTopicPath } from '@/features/Projects/Layout/navigation';+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';+import { useClientDataSWR } from '@/libs/swr';+import { artboardService } from '@/services/artboard';++import { useBoard } from '../BoardContext';+import { ARTBOARD_SEARCH_PARAM } from '../useOpenArtboardFromRoute';++const OpenConversation = ({ onLeave }: { onLeave?: () => void }) => {+ const { t } = useTranslation('project');+ const navigate = useWorkspaceAwareNavigate();+ const { id, topicId } = useBoard().artboard;+ const { data: topic } = useClientDataSWR(topicId ? ['artboard-topic', topicId] : null, () =>+ artboardService.getConversation(topicId!),+ );+ const projectId = topic?.projectId;+ if (!topicId || !projectId) return null;++ return (+ <ActionIcon+ icon={MessageSquareIcon}+ size={'small'}+ title={t('artboard.gallery.openConversation')}+ onClick={() => {+ onLeave?.();+ navigate(`${getProjectTopicPath(projectId, topicId)}?${ARTBOARD_SEARCH_PARAM}=${id}`);+ }}+ />+ );+};++export default OpenConversation;diff --git a/src/features/Artboard/Gallery/index.tsx b/src/features/Artboard/Gallery/index.tsxnew file mode 100644index 00000000000..abece53411c--- /dev/null+++ b/src/features/Artboard/Gallery/index.tsx@@ -0,0 +1,34 @@+'use client';++import { createModal, Flexbox, useModalContext } from '@lobehub/ui';+import { useEffect } from 'react';++import BoardView from '../Board';+import { artboardActions } from '../store';+import { useArtboardFeature } from '../useArtboardFeature';++const GalleryBoard = ({ artboardId }: { artboardId: string }) => {+ const { close } = useModalContext();+ const { enabled } = useArtboardFeature();+ useEffect(() => {+ artboardActions.setGallery(true);+ return () => artboardActions.setGallery(false);+ }, []);+ if (!enabled) return null;+ return (+ <Flexbox height={'100%'} style={{ minHeight: 0 }} width={'100%'}>+ <BoardView artboardId={artboardId} onClose={close} />+ </Flexbox>+ );+};++export const createArtboardGalleryModal = (artboardId: string) =>+ createModal({+ content: <GalleryBoard artboardId={artboardId} />,+ footer: null,+ styles: {+ content: { display: 'flex', height: 'calc(100vh - 64px)', padding: 0 },+ },+ title: null,+ width: '100vw',+ });diff --git a/src/features/Artboard/Gallery/loader.ts b/src/features/Artboard/Gallery/loader.tsnew file mode 100644index 00000000000..ec860e54bf6--- /dev/null+++ b/src/features/Artboard/Gallery/loader.ts@@ -0,0 +1,8 @@+import { isArtboardEnabled } from '../useArtboardFeature';++export const openArtboardFullscreen = async (artboardId: string) => {+ if (!isArtboardEnabled()) return;+ const { createArtboardGalleryModal } = await import('.');+ if (!isArtboardEnabled()) return;+ return createArtboardGalleryModal(artboardId);+};diff --git a/src/features/Artboard/StatusTag.tsx b/src/features/Artboard/StatusTag.tsxnew file mode 100644index 00000000000..517c20a9139--- /dev/null+++ b/src/features/Artboard/StatusTag.tsx@@ -0,0 +1,36 @@+import { Icon, Tag } from '@lobehub/ui';+import {+ CheckIcon,+ CircleDashedIcon,+ CircleDotIcon,+ CircleHelpIcon,+ CirclePauseIcon,+ XIcon,+} from 'lucide-react';+import { useTranslation } from 'react-i18next';++import type { FlowNodeState } from './Verify/flow';++const META = {+ blocked: { color: 'warning', icon: CirclePauseIcon },+ failed: { color: 'error', icon: XIcon },+ partial: { color: 'warning', icon: CircleDotIcon },+ passed: { color: 'success', icon: CheckIcon },+ pending: { color: undefined, icon: CircleDashedIcon },+ uncertain: { color: 'warning', icon: CircleHelpIcon },+} as const;++export const stateIcon = (state: FlowNodeState) => META[state ?? 'pending'].icon;++const StatusTag = ({ state }: { state: FlowNodeState }) => {+ const { t } = useTranslation('verify');+ const key = state ?? 'pending';+ const meta = META[key];+ return (+ <Tag color={meta.color} icon={<Icon icon={meta.icon} />} size={'small'}>+ {t(`flow.state.${key}`)}+ </Tag>+ );+};++export default StatusTag;diff --git a/src/features/Artboard/Verify/CheckDetail.tsx b/src/features/Artboard/Verify/CheckDetail.tsxnew file mode 100644index 00000000000..926cae0220d--- /dev/null+++ b/src/features/Artboard/Verify/CheckDetail.tsx@@ -0,0 +1,245 @@+import { Flexbox, Image, PreviewGroup, Text } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import type { ReactNode } from 'react';+import { useTranslation } from 'react-i18next';++import { useBoard } from '../BoardContext';+import { boardFileUrl } from '../model';+import StatusTag from '../StatusTag';+import { artboardActions } from '../store';+import { isFlagged, nodeAttempts, nodeScreenshot, nodeState } from './flow';+import ReviewActions from './ReviewActions';+import { useCheckBoards } from './Summary';+import { EmptyThumb, Thumb, thumbStyles } from './Thumb';+import { useCheckReview } from './useCheckReview';+import { useBoardAcceptance } from './useJourneyView';++const styles = stylex.create({+ body: {+ flex: '1',+ minHeight: 0,+ overflowY: 'auto',+ paddingBlock: 14,+ paddingInline: 16,+ },+ fact: {+ borderBlockEndColor: cssVar.colorBorderSecondary,+ borderBlockEndStyle: 'solid',+ borderBlockEndWidth: 1,+ columnGap: 12,+ display: 'grid',+ gridTemplateColumns: '64px minmax(0, 1fr)',+ paddingBlock: 8,+ },+ factLabel: {+ color: cssVar.colorTextTertiary,+ fontSize: 12,+ lineHeight: 1.8,+ },+ factValue: {+ fontSize: 13,+ lineHeight: 1.65,+ },+ foot: {+ alignItems: 'flex-start',+ flexDirection: 'column',+ borderBlockStartColor: cssVar.colorBorderSecondary,+ borderBlockStartStyle: 'solid',+ borderBlockStartWidth: 1,+ display: 'flex',+ flex: 'none',+ gap: 8,+ paddingBlock: 12,+ paddingInline: 16,+ },+ path: {+ backgroundColor: cssVar.colorFillSecondary,+ borderRadius: 6,+ color: cssVar.colorTextSecondary,+ display: 'inline-block',+ fontSize: 12,+ paddingBlock: 2,+ paddingInline: 8,+ },+ design: {+ cursor: 'zoom-in',+ display: 'flex',+ flex: '1',+ minWidth: 0,+ },+ evidence: {+ borderColor: cssVar.colorBorderSecondary,+ borderRadius: 4,+ borderStyle: 'solid',+ borderWidth: 1,+ flex: 'none',+ height: 36,+ overflow: 'hidden',+ width: 58,+ },+});++const ShotImage = ({ alt, src }: { alt: string; src: string }) => (+ <Image+ alt={alt}+ height={'100%'}+ objectFit={'cover'}+ src={src}+ styles={{ image: { objectPosition: 'top' }, wrapper: { height: '100%', width: '100%' } }}+ variant={'borderless'}+ width={'100%'}+ />+);++const Fact = ({ children, label }: { children: ReactNode; label: string }) => (+ <div {...stylex.props(styles.fact)}>+ <span {...stylex.props(styles.factLabel)}>{label}</span>+ <div {...stylex.props(styles.factValue)}>{children}</div>+ </div>+);++const CheckDetail = ({ boardId }: { boardId: string }) => {+ const { t } = useTranslation('project');+ const board = useBoard();+ const checks = useCheckBoards();+ const { journey } = useBoardAcceptance();+ const { canReview } = useCheckReview(boardId);+ const item = board.boardById[boardId];+ if (!item) return null;++ const state = nodeState(journey, boardId);+ const attempts = nodeAttempts(journey, boardId);+ const nodeKey = journey?.nodeOf(boardId);+ const verdictOf = (edgeId: string | null) =>+ attempts.find((attempt) => attempt.incomingEdgeId === edgeId)?.verdict;+ const paths = [+ ...(boardId === board.journeyEntryId ? [{ edgeId: null, label: null }] : []),+ ...(journey && nodeKey ? journey.version.edges : [])+ .filter((edge) => edge.targetNodeKey === nodeKey)+ .map((edge) => {+ const from = journey?.boardOf(edge.sourceNodeKey);+ const step = edge.condition ? `${edge.trigger} · ${edge.condition}` : edge.trigger;+ return {+ edgeId: edge.id,+ label: `${(from && board.boardById[from]?.title) ?? ''} → ${step}`,+ };+ }),+ ];+ const observation = attempts.find((attempt) => attempt.observation)?.observation;+ const shot = nodeScreenshot(journey, boardId);+ const shots = [+ ...new Set(+ attempts.flatMap((attempt) =>+ attempt.evidence.flatMap((e) => (e.type === 'screenshot' && e.fileUrl ? [e.fileUrl] : [])),+ ),+ ),+ ];+ const designUrl = boardFileUrl(board, item);+ const designImage = item.type === 'image' ? designUrl : undefined;+ const openDesign = () => {+ if (designUrl) window.open(designUrl, '_blank', 'noopener');+ };+ const next = checks[checks.findIndex((check) => check.id === boardId) + 1];++ return (+ <>+ <PreviewGroup>+ <div {...stylex.props(styles.body)}>+ <Flexbox horizontal align="center" gap={8} style={{ minWidth: 0 }}>+ <Text strong style={{ fontSize: 15 }}>+ {item.title}+ </Text>+ {isFlagged(state) && <StatusTag state={state} />}+ </Flexbox>+ <Flexbox horizontal gap={8} style={{ marginBlock: 12 }}>+ <Flexbox flex={1} gap={4} style={{ minWidth: 0 }}>+ <Text style={{ fontSize: 12 }} type="secondary">+ {t('artboard.verify.finalizedReference')}+ </Text>+ <div+ role="button"+ tabIndex={0}+ title={t('artboard.verify.openDesign')}+ {...stylex.props(styles.design)}+ onClick={openDesign}+ onKeyDown={(event) => {+ if (event.key === 'Enter' || event.key === ' ') {+ event.preventDefault();+ openDesign();+ }+ }}+ >+ <Thumb board={item} />+ </div>+ </Flexbox>+ <Flexbox flex={1} gap={4} style={{ minWidth: 0 }}>+ <Text style={{ fontSize: 12 }} type="secondary">+ {t('artboard.verify.realShot')}+ </Text>+ {shot ? (+ <div {...stylex.props(thumbStyles.box)}>+ <ShotImage alt={item.title} src={shot} />+ </div>+ ) : (+ <EmptyThumb>{t('artboard.verify.noShot')}</EmptyThumb>+ )}+ </Flexbox>+ </Flexbox>+ <Fact label={t('artboard.verify.expected')}>{item.expected}</Fact>+ {observation && (+ <Fact label={t('artboard.verify.observed')}>+ <Text type={state === 'failed' ? 'danger' : undefined}>{observation}</Text>+ </Fact>+ )}+ <Fact label={t('artboard.verify.path')}>+ <Flexbox gap={6}>+ {paths.map((path) => (+ <Flexbox horizontal align="center" gap={8} key={path.edgeId ?? 'entry'}>+ <span {...stylex.props(styles.path)}>+ {path.label ?? t('artboard.verify.entry')}+ </span>+ {isFlagged(verdictOf(path.edgeId)) && (+ <StatusTag state={verdictOf(path.edgeId)} />+ )}+ </Flexbox>+ ))}+ </Flexbox>+ </Fact>+ {shots.length > 0 && (+ <Fact label={t('artboard.verify.evidence')}>+ <Flexbox horizontal align="center" gap={6} wrap="wrap">+ {shots.map((url) => (+ <div key={url} {...stylex.props(styles.evidence)}>+ <ShotImage alt={item.title} src={url} />+ </div>+ ))}+ <Text style={{ fontSize: 12 }} type="secondary">+ {t('artboard.verify.evidenceCount', { count: shots.length })}+ </Text>+ </Flexbox>+ </Fact>+ )}+ </div>+ </PreviewGroup>+ {canReview && (+ <div {...stylex.props(styles.foot)}>+ <ReviewActions+ boardId={boardId}+ state={state}+ onReviewed={(verdict) => {+ if (verdict === 'accepted' && next) artboardActions.focusItem(next.id);+ }}+ />+ {next && (+ <Text style={{ fontSize: 12 }} type="secondary">+ {t('artboard.verify.nextHint')}+ </Text>+ )}+ </div>+ )}+ </>+ );+};++export default CheckDetail;diff --git a/src/features/Artboard/Verify/CheckTable.tsx b/src/features/Artboard/Verify/CheckTable.tsxnew file mode 100644index 00000000000..bddd0ecf6cd--- /dev/null+++ b/src/features/Artboard/Verify/CheckTable.tsx@@ -0,0 +1,159 @@+import { Flexbox, Text } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import { useTranslation } from 'react-i18next';++import StatusTag from '../StatusTag';+import { artboardActions, useArtboardStore } from '../store';+import { isFlagged, nodeAttempts, nodeScreenshot, nodeState } from './flow';+import ReviewActions from './ReviewActions';+import Summary, { useCheckBoards } from './Summary';+import { EmptyThumb, Thumb, thumbStyles } from './Thumb';+import { useJourneyView } from './useJourneyView';++const styles = stylex.create({+ card: {+ backgroundColor: cssVar.colorBgContainer,+ columnGap: 16,+ display: 'grid',+ gridTemplateColumns: 'minmax(0, 1fr) 176px 176px max-content',+ borderColor: cssVar.colorBorderSecondary,+ borderRadius: cssVar.borderRadiusLG,+ borderStyle: 'solid',+ borderWidth: 1,+ overflow: 'hidden',+ },+ clamp: {+ WebkitBoxOrient: 'vertical',+ fontSize: 12,+ WebkitLineClamp: 2,+ display: '-webkit-box',+ overflow: 'hidden',+ },+ grid: {+ alignItems: 'center',+ display: 'grid',+ gridColumnEnd: '-1',+ gridColumnStart: '1',+ gridTemplateColumns: 'subgrid',+ paddingBlock: 12,+ paddingInline: 16,+ },+ gridNarrow: {+ gridTemplateColumns: 'minmax(0, 1fr) 128px',+ },+ head: {+ borderBlockEndColor: cssVar.colorBorderSecondary,+ borderBlockEndStyle: 'solid',+ borderBlockEndWidth: 1,+ color: cssVar.colorTextTertiary,+ fontSize: 12,+ paddingBlock: 8,+ },+ row: {+ backgroundColor: {+ ':hover': cssVar.colorFillQuaternary,+ 'default': 'transparent',+ },+ borderBlockEndColor: cssVar.colorBorderSecondary,+ borderBlockEndStyle: 'solid',+ borderBlockEndWidth: {+ ':last-child': 0,+ 'default': 1,+ },+ cursor: 'pointer',+ },+ rowSelected: {+ backgroundColor: cssVar.colorFillTertiary,+ },+ stage: {+ height: '100%',+ overflowY: 'auto',+ padding: 16,+ },+});++const CheckRow = ({ boardId, narrow }: { boardId: string; narrow: boolean }) => {+ const { t } = useTranslation('project');+ const journey = useJourneyView();+ const selected = useArtboardStore((s) => s.selected === boardId);+ const checks = useCheckBoards();+ const item = checks.find((check) => check.id === boardId);+ if (!item) return null;++ const state = nodeState(journey, boardId);+ const shot = nodeScreenshot(journey, boardId);+ const observation = isFlagged(state) ? nodeAttempts(journey, boardId)[0]?.observation : null;++ return (+ <div+ {...stylex.props(styles.grid, styles.row, selected && styles.rowSelected)}+ role="button"+ tabIndex={0}+ onClick={() => artboardActions.select(boardId)}+ onKeyDown={(event) => {+ if (event.target === event.currentTarget && (event.key === 'Enter' || event.key === ' ')) {+ event.preventDefault();+ artboardActions.select(boardId);+ }+ }}+ >+ <Flexbox gap={4} style={{ minWidth: 0 }}>+ <Flexbox horizontal align="center" gap={8} style={{ minWidth: 0 }}>+ {isFlagged(state) && <StatusTag state={state} />}+ <Text ellipsis strong style={{ fontSize: 13 }}>+ {item.title}+ </Text>+ </Flexbox>+ <Text type="secondary" {...stylex.props(styles.clamp)}>+ {item.expected}+ </Text>+ {observation && (+ <Text type="danger" {...stylex.props(styles.clamp)}>+ {observation}+ </Text>+ )}+ {narrow && <ReviewActions compact boardId={boardId} state={state} />}+ </Flexbox>+ {!narrow && <Thumb board={item} />}+ {shot ? (+ <div {...stylex.props(thumbStyles.box)}>+ <img+ alt={item.title}+ src={shot}+ style={{ height: '100%', objectFit: 'cover', objectPosition: 'top', width: '100%' }}+ />+ </div>+ ) : (+ <EmptyThumb>{t('artboard.verify.noShot')}</EmptyThumb>+ )}+ {!narrow && <ReviewActions compact boardId={boardId} state={state} />}+ </div>+ );+};++const CheckTable = ({ narrow }: { narrow: boolean }) => {+ const { t } = useTranslation('project');+ const checks = useCheckBoards();++ return (+ <div {...stylex.props(styles.stage)}>+ <Flexbox gap={12}>+ <Summary />+ <div {...stylex.props(styles.card, narrow && styles.gridNarrow)}>+ <div {...stylex.props(styles.grid, styles.head)}>+ <span>{t('artboard.verifyList.check')}</span>+ {!narrow && <span>{t('artboard.verifyList.design')}</span>}+ <span>{t('artboard.verify.realShot')}</span>+ {!narrow && <span>{t('artboard.verify.reviewTitle')}</span>}+ </div>+ {checks.map((item) => (+ <CheckRow boardId={item.id} key={item.id} narrow={narrow} />+ ))}+ </div>+ </Flexbox>+ </div>+ );+};++export default CheckTable;diff --git a/src/features/Artboard/Verify/ReviewActions.tsx b/src/features/Artboard/Verify/ReviewActions.tsxnew file mode 100644index 00000000000..8e17912cca9--- /dev/null+++ b/src/features/Artboard/Verify/ReviewActions.tsx@@ -0,0 +1,51 @@+import { Button, Flexbox, Text } from '@lobehub/ui';+import { useTranslation } from 'react-i18next';++import type { FlowNodeState } from './flow';+import { type CheckVerdict, useCheckReview } from './useCheckReview';++interface ReviewActionsProps {+ boardId: string;+ compact?: boolean;+ onReviewed?: (verdict: CheckVerdict) => void;+ state: FlowNodeState;+}++const ReviewActions = ({ boardId, compact, onReviewed, state }: ReviewActionsProps) => {+ const { t } = useTranslation('project');+ const { canReview, review, saving, submit } = useCheckReview(boardId);+ if (!canReview) return null;++ if (review)+ return (+ <Text style={{ fontSize: compact ? 12 : undefined }} type={compact ? 'secondary' : undefined}>+ {t(+ review === 'accepted'+ ? 'artboard.verify.reviewAccepted'+ : 'artboard.verify.reviewRejected',+ )}+ </Text>+ );++ const act = async (verdict: CheckVerdict) => {+ if (await submit(verdict)) onReviewed?.(verdict);+ };+ const size = compact ? 'small' : undefined;+ return (+ <Flexbox horizontal gap={8} onClick={(event) => event.stopPropagation()}>+ <Button+ loading={saving}+ size={size}+ type={compact ? 'default' : 'primary'}+ onClick={() => act('accepted')}+ >+ {t('artboard.verify.accept')}+ </Button>+ <Button danger loading={saving} size={size} onClick={() => act('rejected')}>+ {t(state === 'failed' ? 'artboard.verify.rejectFailed' : 'artboard.verify.reject')}+ </Button>+ </Flexbox>+ );+};++export default ReviewActions;diff --git a/src/features/Artboard/Verify/Summary.tsx b/src/features/Artboard/Verify/Summary.tsxnew file mode 100644index 00000000000..07d5a7a2b47--- /dev/null+++ b/src/features/Artboard/Verify/Summary.tsx@@ -0,0 +1,102 @@+import { Flexbox, Icon, Text } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import { ArrowUpRightIcon } from 'lucide-react';+import { useTranslation } from 'react-i18next';++import { useAcceptanceOrigin } from '@/features/Acceptance/origin';+import { FLOW_HASH } from '@/features/Acceptance/Viewer/Comments/anchor';++import { useBoard } from '../BoardContext';+import { type JourneyView, nodeState } from './flow';+import { useBoardAcceptance, useJourneyView } from './useJourneyView';++const styles = stylex.create({+ link: {+ alignItems: 'center',+ color: {+ ':hover': cssVar.colorText,+ 'default': cssVar.colorTextSecondary,+ },+ cursor: 'pointer',+ display: 'inline-flex',+ flex: 'none',+ fontSize: 12,+ whiteSpace: 'nowrap',+ gap: 2,+ marginInlineStart: 'auto',+ },+});++const FlowLink = () => {+ const { t } = useTranslation('project');+ const { acceptanceId } = useBoardAcceptance();+ const origin = useAcceptanceOrigin();+ if (!acceptanceId) return null;+ return (+ <a+ {...stylex.props(styles.link)}+ href={`${origin}/acceptance/${acceptanceId}${FLOW_HASH}`}+ rel="noopener"+ target="_blank"+ >+ {t('artboard.verify.flowLink')}+ <Icon icon={ArrowUpRightIcon} size={12} />+ </a>+ );+};++export const resultCounts = (view: JourneyView | undefined, boardIds: string[]) => {+ const counts = { blocked: 0, checked: 0, failed: 0, total: boardIds.length };+ for (const id of boardIds) {+ const state = nodeState(view, id);+ if (!state) continue;+ counts.checked += 1;+ if (state === 'failed') counts.failed += 1;+ else if (state !== 'passed') counts.blocked += 1;+ }+ return counts;+};++export const useCheckBoards = () =>+ useBoard().journeyBoards.filter((item) => item.type !== 'decision');++const Summary = () => {+ const { t } = useTranslation('project');+ const journey = useJourneyView();+ const checks = useCheckBoards();+ if (!journey?.run)+ return (+ <Flexbox horizontal align="center" gap={8}>+ <Text style={{ fontSize: 12 }} type="secondary">+ {t('artboard.verify.waiting')}+ </Text>+ <FlowLink />+ </Flexbox>+ );++ const counts = resultCounts(+ journey,+ checks.map((item) => item.id),+ );+ return (+ <Flexbox horizontal align="center" gap={8} wrap="wrap">+ <Text style={{ fontSize: 12 }} type="secondary">+ {t('artboard.verify.summary', counts)}+ </Text>+ {counts.failed > 0 && (+ <Text style={{ fontSize: 12 }} type="danger">+ {t('artboard.verify.summaryFailed', { count: counts.failed })}+ </Text>+ )}+ {counts.blocked > 0 && (+ <Text style={{ fontSize: 12 }} type="warning">+ {t('artboard.verify.summaryBlocked', { count: counts.blocked })}+ </Text>+ )}+ <FlowLink />+ </Flexbox>+ );+};++export default Summary;diff --git a/src/features/Artboard/Verify/Thumb.tsx b/src/features/Artboard/Verify/Thumb.tsxnew file mode 100644index 00000000000..7eea8832f92--- /dev/null+++ b/src/features/Artboard/Verify/Thumb.tsx@@ -0,0 +1,76 @@+import type { ArtboardBoardView } from '@lobechat/types';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import { type ReactNode, useEffect, useRef, useState } from 'react';++import { sx } from '@/styles/sx';++import { useBoard } from '../BoardContext';+import BoardBody from '../Canvas/BoardBody';+import { boardFileUrl } from '../model';++export const thumbStyles = stylex.create({+ box: {+ aspectRatio: '16 / 10',+ borderColor: cssVar.colorBorderSecondary,+ borderRadius: cssVar.borderRadius,+ borderStyle: 'solid',+ borderWidth: 1,+ flex: '1',+ minWidth: 0,+ overflow: 'hidden',+ position: 'relative',+ },+ empty: {+ alignItems: 'center',+ borderStyle: 'dashed',+ color: cssVar.colorTextTertiary,+ display: 'flex',+ fontSize: 12,+ justifyContent: 'center',+ padding: 8,+ textAlign: 'center',+ },+});++export const Thumb = ({ board: item, tone }: { board: ArtboardBoardView; tone?: string }) => {+ const board = useBoard();+ const { h, w } = item.rect;+ const { source } = item;+ const ref = useRef<HTMLDivElement>(null);+ const [scale, setScale] = useState(0.3);+ useEffect(() => {+ const el = ref.current;+ if (!el) return;+ const observer = new ResizeObserver(() => setScale(el.clientWidth / w));+ observer.observe(el);+ return () => observer.disconnect();+ }, [w]);++ return (+ <div+ ref={ref}+ {...sx(thumbStyles.box, tone ? { borderColor: tone, borderWidth: 2 } : undefined)}+ >+ <div+ style={{+ height: h,+ pointerEvents: 'none',+ transform: `scale(${scale})`,+ transformOrigin: '0 0',+ width: w,+ }}+ >+ <BoardBody+ live+ board={item}+ imageUrl={item.type === 'image' ? boardFileUrl(board, item) : undefined}+ />+ </div>+ </div>+ );+};++export const EmptyThumb = ({ children }: { children: ReactNode }) => (+ <div {...stylex.props(thumbStyles.box, thumbStyles.empty)}>{children}</div>+);diff --git a/src/features/Artboard/Verify/acceptanceView.test.ts b/src/features/Artboard/Verify/acceptanceView.test.tsnew file mode 100644index 00000000000..0fb01609449--- /dev/null+++ b/src/features/Artboard/Verify/acceptanceView.test.ts@@ -0,0 +1,107 @@+import { describe, expect, it } from 'vitest';++import { acceptanceJourneyView } from './acceptanceView';+import { isFlagged, nodeScreenshot, nodeState } from './flow';+import { testBoard, testEdge, testModel } from './testBoard';++const board = testModel(+ {+ boards: ['b1', 'b2'].map((id, i) => testBoard(id, { flowNodeId: `node-k${i + 1}` })),+ edges: [testEdge('e1', 'b1', 'b2', { flowEdgeId: 'edge-k1', label: '下一步' })],+ },+ { acceptanceId: 'acc_1', phase: 'finalized', revision: 2 },+);++const attempt = (nodeId: string, incomingEdgeId: string | null, verdict: string) => ({+ checkItemId: `${nodeId}:${incomingEdgeId}`,+ checkResultId: null,+ evidence: [],+ id: `${nodeId}:${incomingEdgeId}`,+ incomingEdgeId,+ nodeId,+ observation: null,+ review: null,+ reviewAttachments: [],+ reviewComment: null,+ reviewDetail: null,+ sequence: 1,+ verdict,+});++const version = {+ edges: [+ {+ edgeKey: 'edge-k1',+ id: 'edge_db_1',+ required: true,+ sourceNodeId: 'node_db_1',+ sourceNodeKey: 'node-k1',+ targetNodeId: 'node_db_2',+ targetNodeKey: 'node-k2',+ trigger: '下一步',+ },+ ],+ entryNodeKey: 'node-k1',+ flowId: 'flow_1',+ id: 'ver_1',+ nodes: [+ { id: 'node_db_1', nodeKey: 'node-k1', title: 'b1' },+ { id: 'node_db_2', nodeKey: 'node-k2', title: 'b2' },+ ],+ runs: [+ {+ attempts: [attempt('node_db_1', null, 'passed'), attempt('node_db_2', 'edge_db_1', 'failed')],+ id: 'run_1',+ status: 'verifying',+ verifyRunId: 'vr_1',+ },+ ],+ title: '旅程',+ version: 1,+};++const bundle = {+ flows: [{ versions: [version] }],+ rounds: [{ run: { id: 'vr_1', roundIndex: 1 } }],+} as any;++describe('acceptanceJourneyView', () => {+ const view = acceptanceJourneyView(board, bundle)!;++ it('maps flow nodes back to boards by their flow ids', () => {+ expect(view.nodeOf('b2')).toBe('node-k2');+ expect(view.boardOf('node-k1')).toBe('b1');+ });++ it('reads each board’s verdict from the latest round', () => {+ expect(nodeState(view, 'b1')).toBe('passed');+ expect(nodeState(view, 'b2')).toBe('failed');+ });++ it('finds nothing for a board whose boards are not in the bundle', () => {+ expect(acceptanceJourneyView(board, { flows: [], rounds: [] } as any)).toBeUndefined();+ });++ it('picks the screenshot evidence of the journey board', () => {+ const withEvidence = structuredClone(bundle);+ withEvidence.flows[0].versions[0].runs[0].attempts[0].evidence = [+ { fileUrl: 'https://evidence.test/log.txt', type: 'log' },+ { fileUrl: 'https://evidence.test/b1.png', type: 'screenshot' },+ ];+ const journey = acceptanceJourneyView(board, withEvidence);++ expect(nodeScreenshot(journey, 'b1')).toBe('https://evidence.test/b1.png');+ });++ it('has no screenshot for a board without evidence instead of borrowing another board', () => {+ expect(nodeScreenshot(view, 'b2')).toBeUndefined();+ expect(nodeScreenshot(undefined, 'b1')).toBeUndefined();+ });++ it('flags only results that need a person', () => {+ expect(isFlagged('passed')).toBe(false);+ expect(isFlagged(undefined)).toBe(false);+ expect(isFlagged('failed')).toBe(true);+ expect(isFlagged('blocked')).toBe(true);+ });+});diff --git a/src/features/Artboard/Verify/acceptanceView.ts b/src/features/Artboard/Verify/acceptanceView.tsnew file mode 100644index 00000000000..b198e5b197a--- /dev/null+++ b/src/features/Artboard/Verify/acceptanceView.ts@@ -0,0 +1,30 @@+import { getFlowRoundViews } from '@/features/Acceptance/Viewer/Flow/flowNavigation';+import type { AcceptanceBundle } from '@/services/verify';++import type { BoardModel } from '../model';+import type { JourneyView } from './flow';++export const acceptanceJourneyView = (+ board: BoardModel,+ bundle: Pick<AcceptanceBundle, 'flows' | 'rounds'>,+): JourneyView | undefined => {+ const boardByNode = new Map(+ board.journeyBoards.flatMap((b) => (b.flowNodeId ? [[b.flowNodeId, b.id] as const] : [])),+ );+ if (!boardByNode.size) return;++ const views = getFlowRoundViews(bundle.flows, bundle.rounds).filter((view) =>+ view.version.nodes.some((node) => boardByNode.has(node.nodeKey)),+ );+ const view = views.find((v) => v.roundIndex !== undefined) ?? views[0];+ if (!view) return;++ const nodeByBoard = new Map([...boardByNode].map(([node, id]) => [id, node]));++ return {+ boardOf: (nodeKey) => boardByNode.get(nodeKey),+ nodeOf: (boardId) => nodeByBoard.get(boardId),+ run: view.run,+ version: view.version,+ };+};diff --git a/src/features/Artboard/Verify/flow.test.ts b/src/features/Artboard/Verify/flow.test.tsnew file mode 100644index 00000000000..47aef395a6b--- /dev/null+++ b/src/features/Artboard/Verify/flow.test.ts@@ -0,0 +1,70 @@+import { describe, expect, it } from 'vitest';++import { draftJourneyView, nodeState } from './flow';+import { testBoard, testEdge, testModel } from './testBoard';++const board = testModel({+ boards: [testBoard('b1'), testBoard('b2'), testBoard('b3'), testBoard('o1', { groupId: 'g2' })],+ edges: [+ testEdge('e1', 'b1', 'b2', { label: '下一步' }),+ testEdge('e2', 'b1', 'b3', { label: '失败' }),+ testEdge('e3', 'b3', 'b2', { label: '重试' }),+ testEdge('e4', 'b1', 'o1', { label: '看方案' }),+ ],+});++describe('draftJourneyView', () => {+ const view = draftJourneyView(board)!;++ it('turns the journey into flow nodes keyed by board, with only its own edges', () => {+ expect(view.version.entryNodeKey).toBe('b1');+ expect(view.version.nodes.map((n) => n.nodeKey)).toEqual(['b1', 'b2', 'b3']);+ expect(view.version.edges.map((e) => [e.sourceNodeKey, e.targetNodeKey, e.trigger])).toEqual([+ ['b1', 'b2', '下一步'],+ ['b1', 'b3', '失败'],+ ['b3', 'b2', '重试'],+ ]);+ });++ it('plans one check item for the entry and one per incoming path', () => {+ expect(+ Object.fromEntries(view.version.nodes.map((n) => [n.nodeKey, n.checkItemIds.length])),+ ).toEqual({ b1: 1, b2: 2, b3: 1 });+ });++ it('leaves every board pending before any acceptance run', () => {+ expect(['b1', 'b2', 'b3', 'o1'].map((id) => nodeState(view, id))).toEqual([+ undefined,+ undefined,+ undefined,+ undefined,+ ]);+ expect(view.nodeOf('o1')).toBeUndefined();+ });++ it('folds a decision board into one edge per branch', () => {+ const branched = draftJourneyView(+ testModel({+ boards: [+ testBoard('b1'),+ testBoard('d1', { expected: null, source: null, type: 'decision' }),+ testBoard('b2'),+ testBoard('b3'),+ ],+ edges: [+ testEdge('e1', 'b1', 'd1', { label: '提交' }),+ testEdge('e2', 'd1', 'b2', { condition: '已付费' }),+ testEdge('e3', 'd1', 'b3', { isDefault: true, label: '否则' }),+ ],+ }),+ )!;++ expect(branched.version.nodes.map((n) => n.nodeKey)).toEqual(['b1', 'b2', 'b3']);+ expect(+ branched.version.edges.map((e) => [e.sourceNodeKey, e.targetNodeKey, e.trigger, e.condition]),+ ).toEqual([+ ['b1', 'b2', '提交', '已付费'],+ ['b1', 'b3', '提交', '否则'],+ ]);+ });+});diff --git a/src/features/Artboard/Verify/flow.ts b/src/features/Artboard/Verify/flow.tsnew file mode 100644index 00000000000..a3928f123b3--- /dev/null+++ b/src/features/Artboard/Verify/flow.ts@@ -0,0 +1,130 @@+import type { FlowVersion } from '@/features/Acceptance/Viewer/Flow/flowNavigation';+import { getFlowNodeState } from '@/features/Acceptance/Viewer/Flow/flowNodeState';++import type { BoardModel } from '../model';++export type FlowRun = FlowVersion['runs'][number];+export type FlowNodeState = ReturnType<typeof getFlowNodeState>;++export interface JourneyView {+ boardOf: (nodeKey: string) => string | undefined;+ nodeOf: (boardId: string) => string | undefined;+ run: FlowRun | undefined;+ version: FlowVersion;+}++const foldDecisions = (board: BoardModel) => {+ const decisions = new Set(+ board.journeyBoards.filter((item) => item.type === 'decision').map((item) => item.id),+ );+ return board.journeyEdges.flatMap((edge) => {+ if (decisions.has(edge.from)) return [];+ if (!decisions.has(edge.to))+ return [+ {+ condition: edge.condition ?? undefined,+ from: edge.from,+ id: edge.id,+ to: edge.to,+ trigger: edge.label,+ },+ ];+ return board.journeyEdges+ .filter((branch) => branch.from === edge.to && !decisions.has(branch.to))+ .map((branch) => ({+ condition: branch.condition ?? branch.label,+ from: edge.from,+ id: `${edge.id}:${branch.id}`,+ to: branch.to,+ trigger: edge.label,+ }));+ });+};++export const draftJourneyView = (board: BoardModel): JourneyView | undefined => {+ const entry = board.journeyEntryId;+ const steps = board.journeyBoards.filter((item) => item.type !== 'decision');+ if (!entry || !steps.length) return;++ const edges = foldDecisions(board).map((edge) => ({+ condition: edge.condition,+ edgeKey: edge.id,+ id: edge.id,+ required: true,+ sourceNodeId: edge.from,+ sourceNodeKey: edge.from,+ targetNodeId: edge.to,+ targetNodeKey: edge.to,+ trigger: edge.trigger,+ }));+ const ids = new Set(steps.map((item) => item.id));++ const version: FlowVersion = {+ edges,+ entryNodeKey: entry,+ flowId: board.artboard.id,+ id: board.artboard.id,+ nodes: steps.map((item) => {+ const items = [+ ...(item.id === entry ? [`${item.id}:entry`] : []),+ ...edges.filter((e) => e.targetNodeKey === item.id).map((e) => `${item.id}:${e.id}`),+ ];+ const expected = item.expected ?? '';+ return {+ checkItemIds: items,+ criterionId: undefined,+ definition: { expected },+ entryRequired: true,+ expected,+ id: item.id,+ instruction: '',+ isEntry: item.id === entry,+ nodeKey: item.id,+ parentNodeId: undefined,+ requiredCheckItemIds: items,+ resourceSnapshot: undefined,+ subFlowId: undefined,+ title: item.title,+ };+ }),+ runs: [],+ title: board.artboard.content.groups.find((g) => g.id === board.journeyGroupId)?.title ?? '',+ version: 1,+ };++ return {+ boardOf: (nodeKey) => (ids.has(nodeKey) ? nodeKey : undefined),+ nodeOf: (boardId) => (ids.has(boardId) ? boardId : undefined),+ run: undefined,+ version,+ };+};++export const nodeAttempts = (view: JourneyView | undefined, boardId: string) => {+ const nodeKey = view?.nodeOf(boardId);+ if (!view?.run || !nodeKey) return [];+ const node = view.version.nodes.find((n) => n.nodeKey === nodeKey);+ return view.run.attempts.filter((attempt) => attempt.nodeId === node?.id);+};++export const nodeState = (view: JourneyView | undefined, boardId: string): FlowNodeState => {+ const nodeKey = view?.nodeOf(boardId);+ if (!view || !nodeKey) return undefined;+ return getFlowNodeState(+ nodeKey,+ view.version.entryNodeKey,+ view.version.edges,+ nodeAttempts(view, boardId),+ );+};++export const nodeReview = (view: JourneyView | undefined, boardId: string) =>+ nodeAttempts(view, boardId)[0]?.review ?? undefined;++export const nodeScreenshot = (view: JourneyView | undefined, boardId: string) =>+ nodeAttempts(view, boardId)+ .flatMap((attempt) => attempt.evidence)+ .find((evidence) => evidence.type === 'screenshot' && evidence.fileUrl)?.fileUrl ?? undefined;++// Passing is the expected outcome and stays unmarked; only a result that needs a person is flagged.+export const isFlagged = (state: FlowNodeState) => !!state && state !== 'passed';diff --git a/src/features/Artboard/Verify/index.tsx b/src/features/Artboard/Verify/index.tsxnew file mode 100644index 00000000000..8c5141704c5--- /dev/null+++ b/src/features/Artboard/Verify/index.tsx@@ -0,0 +1,276 @@+import { ActionIcon, Button, Flexbox, Icon, Text } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import { ArrowLeftIcon, ChevronLeftIcon, ChevronRightIcon, XIcon } from 'lucide-react';+import { useTranslation } from 'react-i18next';++import { sidebarRow } from '@/styles/density.stylex';++import { useBoard } from '../BoardContext';+import StatusTag from '../StatusTag';+import { artboardActions, artboardSelectors, useArtboardStore } from '../store';+import CheckDetail from './CheckDetail';+import { isFlagged, nodeReview, nodeScreenshot, nodeState } from './flow';+import Summary, { useCheckBoards } from './Summary';+import { Thumb } from './Thumb';+import { useAcceptAll } from './useCheckReview';+import { useJourneyView } from './useJourneyView';++const styles = stylex.create({+ back: {+ color: cssVar.colorTextSecondary,+ cursor: 'pointer',+ flex: '1',+ fontSize: 12,+ minWidth: 0,+ },+ clamp: {+ WebkitBoxOrient: 'vertical',+ WebkitLineClamp: 2,+ color: cssVar.colorTextSecondary,+ display: '-webkit-box',+ fontSize: 12,+ lineHeight: 1.6,+ overflow: 'hidden',+ },+ foot: {+ alignItems: 'center',+ borderBlockStartColor: cssVar.colorBorderSecondary,+ borderBlockStartStyle: 'solid',+ borderBlockStartWidth: 1,+ display: 'flex',+ flex: 'none',+ gap: 8,+ paddingBlock: 12,+ paddingInline: 16,+ },+ head: {+ borderBlockEndColor: cssVar.colorBorderSecondary,+ borderBlockEndStyle: 'solid',+ borderBlockEndWidth: 1,+ flex: 'none',+ height: sidebarRow.headerHeight,+ paddingInlineEnd: 10,+ paddingInlineStart: 16,+ },+ panel: {+ backgroundColor: cssVar.colorBgContainer,+ display: 'flex',+ flexDirection: 'column',+ height: '100%',+ },+ row: {+ backgroundColor: {+ ':hover': cssVar.colorFillQuaternary,+ 'default': 'transparent',+ },+ borderRadius: cssVar.borderRadius,+ cursor: 'pointer',+ display: 'flex',+ gap: 10,+ paddingBlock: 10,+ paddingInline: 8,+ },+ rowSelected: {+ backgroundColor: cssVar.colorFillTertiary,+ boxShadow: `inset 0 0 0 1px ${cssVar.colorBorder}`,+ },+ scroll: {+ flex: '1',+ minHeight: 0,+ overflowY: 'auto',+ },+ shot: {+ display: 'block',+ height: '100%',+ objectFit: 'cover',+ objectPosition: 'top',+ width: '100%',+ },+ summary: {+ paddingBlockStart: '12px',+ paddingBlockEnd: '4px',+ paddingInline: 16,+ },+ thumb: {+ aspectRatio: '16 / 10',+ borderColor: cssVar.colorBorderSecondary,+ borderRadius: 6,+ borderStyle: 'solid',+ borderWidth: 1,+ flex: 'none',+ overflow: 'hidden',+ width: 84,+ },+});++const CheckRow = ({ boardId }: { boardId: string }) => {+ const { t } = useTranslation('project');+ const board = useBoard();+ const journey = useJourneyView();+ const selected = useArtboardStore((s) => s.selected === boardId);+ const item = board.boardById[boardId];+ if (!item) return null;++ const state = nodeState(journey, boardId);+ const review = nodeReview(journey, boardId);+ const shot = nodeScreenshot(journey, boardId);++ return (+ <div+ role="button"+ tabIndex={0}+ {...stylex.props(styles.row, selected && styles.rowSelected)}+ onClick={() => artboardActions.focusItem(boardId)}+ onKeyDown={(event) => {+ if (event.target === event.currentTarget && (event.key === 'Enter' || event.key === ' ')) {+ event.preventDefault();+ artboardActions.focusItem(boardId);+ }+ }}+ >+ {shot ? (+ <div {...stylex.props(styles.thumb)}>+ <img alt={item.title} src={shot} {...stylex.props(styles.shot)} />+ </div>+ ) : (+ <div style={{ flex: 'none', width: 84 }}>+ <Thumb board={item} />+ </div>+ )}+ <Flexbox gap={2} style={{ flex: 1, minWidth: 0 }}>+ <Flexbox horizontal align="center" gap={6} style={{ minWidth: 0 }}>+ <Text ellipsis strong style={{ fontSize: 13 }}>+ {item.title}+ </Text>+ {isFlagged(state) && <StatusTag state={state} />}+ </Flexbox>+ <div {...stylex.props(styles.clamp)}>{item.expected}</div>+ {review && (+ <Text style={{ fontSize: 12 }} type="secondary">+ {t(+ review === 'accepted' ? 'artboard.verify.reviewedTag' : 'artboard.verify.rejectedTag',+ )}+ </Text>+ )}+ </Flexbox>+ </div>+ );+};++const CheckList = () => {+ const { t } = useTranslation('project');+ const checks = useCheckBoards();+ const { acceptAll, count, saving } = useAcceptAll(checks.map((item) => item.id));++ return (+ <>+ <div {...stylex.props(styles.summary)}>+ <Summary />+ </div>+ <div {...stylex.props(styles.scroll)}>+ <Flexbox gap={2} paddingBlock={'4px 12px'} paddingInline={8}>+ {checks.map((item) => (+ <CheckRow boardId={item.id} key={item.id} />+ ))}+ </Flexbox>+ </div>+ {count > 0 && (+ <div {...stylex.props(styles.foot)}>+ <Button loading={saving} type={'primary'} onClick={acceptAll}>+ {t('artboard.verify.acceptAll', { count })}+ </Button>+ <Text style={{ fontSize: 12 }} type="secondary">+ {t('artboard.verify.acceptAllHint')}+ </Text>+ </div>+ )}+ </>+ );+};++const DetailHead = ({ boardId, onClose }: { boardId: string; onClose?: () => void }) => {+ const { t } = useTranslation('project');+ const checks = useCheckBoards();+ const index = checks.findIndex((item) => item.id === boardId);+ const go = (offset: number) => {+ const next = checks[index + offset];+ if (next) artboardActions.focusItem(next.id);+ };++ return (+ <Flexbox horizontal align="center" gap={4} {...stylex.props(styles.head)}>+ <Flexbox+ horizontal+ align="center"+ gap={6}+ {...stylex.props(styles.back)}+ onClick={() => artboardActions.select(null)}+ >+ <Icon icon={ArrowLeftIcon} size={14} />+ {t('artboard.verify.back')}+ </Flexbox>+ <ActionIcon+ disabled={index <= 0}+ icon={ChevronLeftIcon}+ size={'small'}+ title={t('artboard.verify.prev')}+ onClick={() => go(-1)}+ />+ <Text style={{ fontSize: 12, fontVariantNumeric: 'tabular-nums' }} type="secondary">+ {index + 1} / {checks.length}+ </Text>+ <ActionIcon+ disabled={index >= checks.length - 1}+ icon={ChevronRightIcon}+ size={'small'}+ title={t('artboard.verify.next')}+ onClick={() => go(1)}+ />+ {onClose && (+ <ActionIcon+ icon={XIcon}+ size={'small'}+ title={t('artboard.verify.close')}+ onClick={onClose}+ />+ )}+ </Flexbox>+ );+};++const VerifyPanel = ({ onClose }: { onClose?: () => void }) => {+ const { t } = useTranslation('project');+ const board = useBoard();+ const selected = useArtboardStore(artboardSelectors.selectedCheckBoard(board));++ return (+ <div {...stylex.props(styles.panel)}>+ {selected ? (+ <>+ <DetailHead boardId={selected} onClose={onClose} />+ <CheckDetail boardId={selected} />+ </>+ ) : (+ <>+ <Flexbox horizontal align="center" gap={8} {...stylex.props(styles.head)}>+ <Text strong style={{ flex: 1 }}>+ {t('artboard.verify.title')}+ </Text>+ {onClose && (+ <ActionIcon+ icon={XIcon}+ size={'small'}+ title={t('artboard.verify.close')}+ onClick={onClose}+ />+ )}+ </Flexbox>+ <CheckList />+ </>+ )}+ </div>+ );+};++export default VerifyPanel;diff --git a/src/features/Artboard/Verify/testBoard.ts b/src/features/Artboard/Verify/testBoard.tsnew file mode 100644index 00000000000..bafd9473e7f--- /dev/null+++ b/src/features/Artboard/Verify/testBoard.ts@@ -0,0 +1,79 @@+import type {+ ArtboardBoardView,+ ArtboardContent,+ ArtboardEdgeView,+ ArtboardItem,+} from '@lobechat/types';++import { buildBoardModel } from '../model';++export const testBoard = (+ id: string,+ patch: Partial<ArtboardBoardView> = {},+): ArtboardBoardView => ({+ expected: `${id} works`,+ flowNodeId: null,+ groupId: 'g1',+ id,+ pageId: 'p1',+ rect: { h: 400, w: 640, x: 0, y: 0 },+ roundId: null,+ source: { hash: `hash_${id}`, kind: 'file', path: `pages/${id}.html` },+ title: id,+ type: 'html',+ ...patch,+});++export const testEdge = (+ id: string,+ from: string,+ to: string,+ patch: Partial<ArtboardEdgeView> = {},+): ArtboardEdgeView => ({+ condition: null,+ flowEdgeId: null,+ from,+ id,+ isDefault: false,+ label: id,+ to,+ ...patch,+});++export const testModel = (+ content: Pick<ArtboardContent, 'boards' | 'edges'>,+ artboard: Partial<ArtboardItem> = {},+) =>+ buildBoardModel(+ {+ content: {+ ...content,+ groups: [+ {+ desc: '',+ id: 'g1',+ kind: 'journey',+ pageId: 'p1',+ rect: { h: 0, w: 0, x: 0, y: 0 },+ title: '旅程',+ },+ {+ desc: '',+ id: 'g2',+ kind: 'options',+ pageId: 'p1',+ rect: { h: 0, w: 0, x: 0, y: 0 },+ title: '方案',+ },+ ],+ pages: [{ id: 'p1', name: 'Page 1', sortOrder: 0 }],+ questions: [],+ rounds: [],+ },+ id: 'art_1',+ phase: 'discuss',+ revision: 1,+ ...artboard,+ } as ArtboardItem,+ null,+ );diff --git a/src/features/Artboard/Verify/useCheckReview.ts b/src/features/Artboard/Verify/useCheckReview.tsnew file mode 100644index 00000000000..918b779ac8d--- /dev/null+++ b/src/features/Artboard/Verify/useCheckReview.ts@@ -0,0 +1,92 @@+import { toast } from '@lobehub/ui';+import { useState } from 'react';+import { useTranslation } from 'react-i18next';++import { verifyService } from '@/services/verify';++import { useBoard } from '../BoardContext';+import { type FlowRun, nodeAttempts, nodeReview } from './flow';+import { useBoardAcceptance } from './useJourneyView';++export type CheckVerdict = 'accepted' | 'rejected';++type Attempt = NonNullable<FlowRun>['attempts'][number];++const reviewAttempts = (acceptanceId: string, attempts: Attempt[], verdict: CheckVerdict) =>+ Promise.all(+ attempts.map((attempt) =>+ verifyService.reviewFlowStep({+ attemptId: attempt.id,+ comment: '',+ id: acceptanceId,+ review: verdict,+ }),+ ),+ );++export const useCheckReview = (boardId: string) => {+ const { t } = useTranslation('project');+ const board = useBoard();+ const { acceptanceId, journey, refresh } = useBoardAcceptance();+ const [saving, setSaving] = useState(false);+ const reviewable = nodeAttempts(journey, boardId).filter(+ (attempt) => attempt.verdict === 'passed' || attempt.verdict === 'failed',+ );++ const submit = async (verdict: CheckVerdict) => {+ if (!acceptanceId) return false;+ setSaving(true);+ try {+ await reviewAttempts(acceptanceId, reviewable, verdict);+ await refresh();+ toast.success(+ t(verdict === 'accepted' ? 'artboard.verify.accepted' : 'artboard.verify.rejected', {+ id: board.boardById[boardId]?.title ?? '',+ }),+ );+ return true;+ } catch (error) {+ toast.error((error as Error).message);+ return false;+ } finally {+ setSaving(false);+ }+ };++ return {+ canReview: !!acceptanceId && reviewable.length > 0,+ review: nodeReview(journey, boardId),+ saving,+ submit,+ };+};++export const useAcceptAll = (boardIds: string[]) => {+ const { t } = useTranslation('project');+ const { acceptanceId, journey, refresh } = useBoardAcceptance();+ const [saving, setSaving] = useState(false);+ const pending = boardIds.filter((id) => {+ const attempts = nodeAttempts(journey, id);+ return attempts.length > 0 && attempts.every((a) => a.verdict === 'passed' && !a.review);+ });++ const acceptAll = async () => {+ if (!acceptanceId) return;+ setSaving(true);+ try {+ await reviewAttempts(+ acceptanceId,+ pending.flatMap((id) => nodeAttempts(journey, id)),+ 'accepted',+ );+ await refresh();+ toast.success(t('artboard.verify.acceptedAll', { count: pending.length }));+ } catch (error) {+ toast.error((error as Error).message);+ } finally {+ setSaving(false);+ }+ };++ return { acceptAll, count: acceptanceId ? pending.length : 0, saving };+};diff --git a/src/features/Artboard/Verify/useJourneyView.ts b/src/features/Artboard/Verify/useJourneyView.tsnew file mode 100644index 00000000000..3e7e9588b6b--- /dev/null+++ b/src/features/Artboard/Verify/useJourneyView.ts@@ -0,0 +1,20 @@+import { useMemo } from 'react';++import { useAcceptanceBundle } from '@/features/Acceptance/Viewer/useAcceptanceBundle';++import { useBoard } from '../BoardContext';+import { acceptanceJourneyView } from './acceptanceView';+import { draftJourneyView } from './flow';++export const useBoardAcceptance = () => {+ const board = useBoard();+ const acceptanceId = board.finalized ? board.artboard.acceptanceId : null;+ const { data, mutate } = useAcceptanceBundle(acceptanceId);+ const journey = useMemo(+ () => (data && acceptanceJourneyView(board, data)) || draftJourneyView(board),+ [board, data],+ );+ return { acceptanceId, journey, refresh: mutate };+};++export const useJourneyView = () => useBoardAcceptance().journey;diff --git a/src/features/Artboard/Viewport/ZoomBar.tsx b/src/features/Artboard/Viewport/ZoomBar.tsxnew file mode 100644index 00000000000..2abb4db3c64--- /dev/null+++ b/src/features/Artboard/Viewport/ZoomBar.tsx@@ -0,0 +1,93 @@+import { type DropdownItem, DropdownMenu, Icon } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import { ChevronDownIcon } from 'lucide-react';+import { useEffect, useRef } from 'react';+import { useTranslation } from 'react-i18next';++import { isMacOS } from '@/utils/platform';++import { floatStyles } from './floatStyles';+import { formatZoom, type ZoomCommand, zoomCommandFromKey, zoomFactor } from './zoomCommands';++const MOD = isMacOS() ? '⌘' : 'Ctrl';++const HINTS: Record<ZoomCommand, string> = {+ actual: '⇧ 0',+ fit: '⇧ 1',+ in: `${MOD} +`,+ out: `${MOD} −`,+};++const styles = stylex.create({+ bar: {+ insetBlockEnd: 'calc(12px + env(safe-area-inset-bottom, 0px))',+ insetInlineStart: 12,+ },+ hint: {+ color: cssVar.colorTextTertiary,+ fontFamily: cssVar.fontFamilyCode,+ fontSize: 12,+ },+ value: {+ fontVariantNumeric: 'tabular-nums',+ },+});++const isEditable = (target: EventTarget | null) =>+ target instanceof HTMLElement &&+ (target.isContentEditable || !!target.closest('input, textarea, select, [contenteditable]'));++interface ZoomBarProps {+ k: number;+ onFit: () => void;+ onZoom: (factor: number) => void;+}++const ZoomBar = ({ k, onFit, onZoom }: ZoomBarProps) => {+ const { t } = useTranslation('project');+ const ref = useRef<HTMLDivElement>(null);++ useEffect(() => {+ const apply = (command: ZoomCommand) =>+ command === 'fit' ? onFit() : onZoom(zoomFactor(command, k));+ const onKey = (event: KeyboardEvent) => {+ if (event.defaultPrevented || event.isComposing || isEditable(event.target)) return;+ const command = zoomCommandFromKey(event);+ const root = ref.current?.closest('[data-artboard-root]');+ if (!command || !root) return;+ if (!root.matches(':hover') && !root.contains(document.activeElement)) return;+ event.preventDefault();+ apply(command);+ };+ window.addEventListener('keydown', onKey);+ return () => window.removeEventListener('keydown', onKey);+ }, [k, onFit, onZoom]);++ const item = (command: ZoomCommand, label: string): DropdownItem => ({+ extra: <span {...stylex.props(styles.hint)}>{HINTS[command]}</span>,+ key: command,+ label,+ onClick: () => (command === 'fit' ? onFit() : onZoom(zoomFactor(command, k))),+ });++ const items: DropdownItem[] = [+ item('in', t('artboard.zoom.in')),+ item('out', t('artboard.zoom.out')),+ item('fit', t('artboard.zoom.fit')),+ item('actual', t('artboard.zoom.actual')),+ ];++ return (+ <div ref={ref} {...stylex.props(floatStyles.float, floatStyles.bar, styles.bar)}>+ <DropdownMenu items={items} placement={'topLeft'}>+ <div {...stylex.props(floatStyles.trigger)}>+ <span {...stylex.props(styles.value)}>{formatZoom(k)}</span>+ <Icon color={cssVar.colorTextTertiary} icon={ChevronDownIcon} size={14} />+ </div>+ </DropdownMenu>+ </div>+ );+};++export default ZoomBar;diff --git a/src/features/Artboard/Viewport/capabilities.tsx b/src/features/Artboard/Viewport/capabilities.tsxnew file mode 100644index 00000000000..67957020d52--- /dev/null+++ b/src/features/Artboard/Viewport/capabilities.tsx@@ -0,0 +1,29 @@+import type { ArtboardBoardView } from '@lobechat/types';+import { createContext, type ReactNode, use } from 'react';++import type { JourneyView } from '../Verify/flow';++export interface BoardCapabilities {+ /** An agent is running in the artboard's topic, so boards without a file are still being written. */+ agentRunning?: boolean;+ journey?: JourneyView;+ onPick?: (roundId: string, boardId: string) => void;+ renderCanvas: (board: ArtboardBoardView) => ReactNode;+}++const BoardCapabilitiesContext = createContext<BoardCapabilities | null>(null);++export const BoardCapabilitiesProvider = ({+ children,+ value,+}: {+ children: ReactNode;+ value: BoardCapabilities;+}) => <BoardCapabilitiesContext value={value}>{children}</BoardCapabilitiesContext>;++export const useBoardCapabilities = () => {+ const capabilities = use(BoardCapabilitiesContext);+ if (!capabilities)+ throw new Error('useBoardCapabilities must be used inside BoardCapabilitiesProvider');+ return capabilities;+};diff --git a/src/features/Artboard/Viewport/floatStyles.ts b/src/features/Artboard/Viewport/floatStyles.tsnew file mode 100644index 00000000000..418bd776082--- /dev/null+++ b/src/features/Artboard/Viewport/floatStyles.ts@@ -0,0 +1,57 @@+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';++export const floatStyles = stylex.create({+ float: {+ backgroundColor: cssVar.colorBgElevated,+ borderColor: cssVar.colorBorderSecondary,+ borderRadius: 12,+ borderStyle: 'solid',+ borderWidth: 1,+ boxShadow: cssVar.boxShadowTertiary,+ padding: 4,+ position: 'absolute',+ zIndex: 5,+ },+ bar: {+ alignItems: 'center',+ display: 'flex',+ fontSize: 13,+ gap: 2,+ padding: 3,+ },+ divider: {+ backgroundColor: cssVar.colorBorderSecondary,+ flex: 'none',+ height: 18,+ marginInline: 4,+ width: 1,+ },+ trigger: {+ alignItems: 'center',+ backgroundColor: {+ ':hover': cssVar.colorFillTertiary,+ 'default': 'transparent',+ },+ borderRadius: 8,+ color: cssVar.colorText,+ cursor: 'pointer',+ display: 'flex',+ flex: 'none',+ gap: 4,+ height: 30,+ paddingInlineEnd: 8,+ paddingInlineStart: 10,+ },+ topCenter: {+ insetBlockStart: 12,+ insetInlineStart: '50%',+ position: 'absolute',+ transform: 'translateX(-50%)',+ zIndex: 5,+ },+ selectionBar: {+ transform: 'translate(-100%, calc(-100% - 36px))',+ zIndex: 6,+ },+});diff --git a/src/features/Artboard/Viewport/graph.test.ts b/src/features/Artboard/Viewport/graph.test.tsnew file mode 100644index 00000000000..09dfc7c8b56--- /dev/null+++ b/src/features/Artboard/Viewport/graph.test.ts@@ -0,0 +1,32 @@+import { describe, expect, it, vi } from 'vitest';++const reached = vi.hoisted(() => new Set<string>());++vi.mock('@/services/artboard', () => {+ reached.add('@/services/artboard');+ return {};+});+vi.mock('@/libs/trpc/client', () => {+ reached.add('@/libs/trpc/client');+ return {};+});+vi.mock('@/features/Conversation/WorkingSidebar/Canvas/CanvasFrame', () => {+ reached.add('CanvasFrame');+ return { default: () => null };+});+vi.mock('@/features/Acceptance/Viewer/useAcceptanceBundle', () => {+ reached.add('useAcceptanceBundle');+ return {};+});+vi.mock('@xyflow/react', () => {+ reached.add('@xyflow/react');+ return {};+});++describe('artboard Viewport', () => {+ it('renders boards without loading app services, Canvas frames or acceptance data', async () => {+ await import('.');++ expect([...reached]).toEqual([]);+ });+});diff --git a/src/features/Artboard/Viewport/index.tsx b/src/features/Artboard/Viewport/index.tsxnew file mode 100644index 00000000000..4c93dc11438--- /dev/null+++ b/src/features/Artboard/Viewport/index.tsx@@ -0,0 +1,104 @@+import * as stylex from '@stylexjs/stylex';+import { useSize } from 'ahooks';+import { memo, type MouseEvent, type ReactNode, useMemo, useRef } from 'react';++import { sx } from '@/styles/sx';++import { useBoard } from '../BoardContext';+import BoardNode from '../Canvas/BoardNode';+import Edges from '../Canvas/Edges';+import Groups from '../Canvas/Groups';+import { canvasStyles } from '../Canvas/styles';+import { useViewport, type ViewState } from '../Canvas/useViewport';+import { nextLiveBoards } from '../Canvas/visibleBoards';+import type { BoardModel } from '../model';+import ZoomBar from './ZoomBar';++const noop = () => {};++interface ContentProps {+ board: BoardModel;+ k: number;+ live: string;+}++// Panning updates the view on every pointer move; only the world transform should follow it.+const Content = memo<ContentProps>(({ board, k, live }) => {+ const liveIds = useMemo(() => new Set(live.split(' ')), [live]);+ return (+ <>+ <Groups k={k} />+ <Edges k={k} />+ {board.boards.map((item) => (+ <BoardNode board={item} k={k} key={item.id} live={liveIds.has(item.id)} />+ ))}+ </>+ );+});++Content.displayName = 'ArtboardViewportContent';++export interface ViewportSize {+ height: number;+ width: number;+}++interface ViewportProps {+ children?: (state: { size: ViewportSize | undefined; view: ViewState }) => ReactNode;+ commenting?: boolean;+ onBackground?: () => void;+ onCanvasClick?: (event: MouseEvent<HTMLDivElement>, view: ViewState) => void;+}++const Viewport = ({ children, commenting, onBackground, onCanvasClick }: ViewportProps) => {+ const board = useBoard();+ const ref = useRef<HTMLDivElement>(null);+ const size = useSize(ref);+ const { fitAll, flying, handlers, panning, view, zoomBy } = useViewport(+ ref,+ board,+ onBackground ?? noop,+ );+ const liveRef = useRef<readonly string[]>([]);+ if (size && !flying)+ liveRef.current = nextLiveBoards(liveRef.current, board.boards, { ...view, ...size });+ const live = liveRef.current.toSorted().join(' ');++ const onClickCapture = (event: MouseEvent<HTMLDivElement>) => {+ let suppressed = false;+ handlers.onClickCapture({+ stopPropagation: () => {+ suppressed = true;+ event.stopPropagation();+ },+ });+ if (!suppressed) onCanvasClick?.(event, view);+ };++ return (+ <>+ <div+ ref={ref}+ {...stylex.props(+ canvasStyles.viewport,+ commenting && canvasStyles.commenting,+ panning && canvasStyles.panning,+ )}+ {...handlers}+ onClickCapture={onClickCapture}+ >+ <div+ {...sx(canvasStyles.world, flying && canvasStyles.worldFlying, {+ transform: `translate(${view.x}px, ${view.y}px) scale(${view.k})`,+ })}+ >+ <Content board={board} k={view.k} live={live} />+ </div>+ </div>+ {children?.({ size, view })}+ <ZoomBar k={view.k} onFit={fitAll} onZoom={zoomBy} />+ </>+ );+};++export default Viewport;diff --git a/src/features/Artboard/Viewport/zoomCommands.test.ts b/src/features/Artboard/Viewport/zoomCommands.test.tsnew file mode 100644index 00000000000..cbf12a3f9e8--- /dev/null+++ b/src/features/Artboard/Viewport/zoomCommands.test.ts@@ -0,0 +1,61 @@+import { describe, expect, it } from 'vitest';++import { formatZoom, zoomCommandFromKey, zoomFactor } from './zoomCommands';++const key = (init: Partial<KeyboardEventInit> & { code?: string; key?: string }) => ({+ altKey: false,+ code: '',+ ctrlKey: false,+ key: '',+ metaKey: false,+ shiftKey: false,+ ...init,+});++describe('zoomCommandFromKey', () => {+ it('maps mod plus and minus to zoom in and out', () => {+ expect(zoomCommandFromKey(key({ code: 'Equal', key: '=', metaKey: true }))).toBe('in');+ expect(+ zoomCommandFromKey(key({ code: 'Equal', key: '+', metaKey: true, shiftKey: true })),+ ).toBe('in');+ expect(zoomCommandFromKey(key({ code: 'NumpadAdd', ctrlKey: true, key: '+' }))).toBe('in');+ expect(zoomCommandFromKey(key({ code: 'Minus', ctrlKey: true, key: '-' }))).toBe('out');+ expect(zoomCommandFromKey(key({ code: 'NumpadSubtract', key: '-', metaKey: true }))).toBe(+ 'out',+ );+ });++ it('maps shift+1 to fit and shift+0 to 100% by physical key', () => {+ expect(zoomCommandFromKey(key({ code: 'Digit1', key: '!', shiftKey: true }))).toBe('fit');+ expect(zoomCommandFromKey(key({ code: 'Digit0', key: ')', shiftKey: true }))).toBe('actual');+ });++ it('ignores the same keys without the right modifiers', () => {+ expect(zoomCommandFromKey(key({ code: 'Equal', key: '=' }))).toBeUndefined();+ expect(zoomCommandFromKey(key({ code: 'Digit1', key: '1' }))).toBeUndefined();+ expect(+ zoomCommandFromKey(key({ code: 'Digit1', key: '!', metaKey: true, shiftKey: true })),+ ).toBeUndefined();+ expect(+ zoomCommandFromKey(key({ altKey: true, code: 'Equal', key: '=', metaKey: true })),+ ).toBeUndefined();+ });+});++describe('zoomFactor', () => {+ it('steps by 1.25 in both directions', () => {+ expect(zoomFactor('in', 0.5)).toBe(1.25);+ expect(zoomFactor('out', 0.5)).toBe(0.8);+ });++ it('lands on exactly 100% from any scale', () => {+ for (const k of [0.08, 0.28, 0.5, 1.7]) expect(k * zoomFactor('actual', k)).toBeCloseTo(1, 10);+ });+});++describe('formatZoom', () => {+ it('rounds the scale to a whole percent', () => {+ expect(formatZoom(0.2849)).toBe('28%');+ expect(formatZoom(1)).toBe('100%');+ });+});diff --git a/src/features/Artboard/Viewport/zoomCommands.ts b/src/features/Artboard/Viewport/zoomCommands.tsnew file mode 100644index 00000000000..c9ad449dedd--- /dev/null+++ b/src/features/Artboard/Viewport/zoomCommands.ts@@ -0,0 +1,42 @@+export type ZoomCommand = 'in' | 'out' | 'fit' | 'actual';++export const ZOOM_STEP = 1.25;++interface ZoomKey {+ altKey: boolean;+ code: string;+ ctrlKey: boolean;+ key: string;+ metaKey: boolean;+ shiftKey: boolean;+}++export const zoomCommandFromKey = (event: ZoomKey): ZoomCommand | undefined => {+ if (event.altKey) return;+ const mod = event.metaKey || event.ctrlKey;+ if (mod) {+ if (event.code === 'Equal' || event.code === 'NumpadAdd' || event.key === '+') return 'in';+ if (event.code === 'Minus' || event.code === 'NumpadSubtract' || event.key === '-')+ return 'out';+ return;+ }+ if (!event.shiftKey) return;+ if (event.code === 'Digit1') return 'fit';+ if (event.code === 'Digit0') return 'actual';+};++export const zoomFactor = (command: Exclude<ZoomCommand, 'fit'>, k: number) => {+ switch (command) {+ case 'in': {+ return ZOOM_STEP;+ }+ case 'out': {+ return 1 / ZOOM_STEP;+ }+ case 'actual': {+ return 1 / k;+ }+ }+};++export const formatZoom = (k: number) => `${Math.round(k * 100)}%`;diff --git a/src/features/Artboard/data/actions.ts b/src/features/Artboard/data/actions.tsnew file mode 100644index 00000000000..1901a13c8c5--- /dev/null+++ b/src/features/Artboard/data/actions.ts@@ -0,0 +1,14 @@+import { artboardService } from '@/services/artboard';++import { mutateArtboard } from './useArtboard';++export const finalizeArtboard = async (id: string, revision: number) => {+ const result = await artboardService.finalize(id, revision);+ await mutateArtboard(id);+ return result;+};++export const chooseOption = async (id: string, roundId: string, boardId: string) => {+ await artboardService.chooseBoard(id, roundId, boardId);+ await mutateArtboard(id);+};diff --git a/src/features/Artboard/data/addBoardReference.test.ts b/src/features/Artboard/data/addBoardReference.test.tsnew file mode 100644index 00000000000..51a153c3252--- /dev/null+++ b/src/features/Artboard/data/addBoardReference.test.ts@@ -0,0 +1,42 @@+import { afterEach, describe, expect, it, vi } from 'vitest';++import { artboardActions } from '../store';+import { addBoardReference } from './addBoardReference';++const { insert } = vi.hoisted(() => ({ insert: vi.fn(() => true) }));+vi.mock('@/features/ChatInput/InputEditor/ReferArtboard', () => ({+ insertArtboardReference: insert,+}));++const ref = {+ artboardId: 'art_1',+ itemId: 'f1',+ itemTitle: 'A',+ text: 'x',+};++describe('addBoardReference', () => {+ afterEach(() => {+ artboardActions.reset();+ vi.clearAllMocks();+ });++ it('puts the reference into the conversation input by default', () => {+ expect(addBoardReference(ref)).toBe(true);+ expect(insert).toHaveBeenCalledWith(ref);+ });++ it('refuses while the board is full screen, where the conversation input is covered', () => {+ artboardActions.setFullscreen(true);++ expect(addBoardReference(ref)).toBe(false);+ expect(insert).not.toHaveBeenCalled();+ });++ it('refuses while the board is opened from Works, where there is no conversation input', () => {+ artboardActions.setGallery(true);++ expect(addBoardReference(ref)).toBe(false);+ expect(insert).not.toHaveBeenCalled();+ });+});diff --git a/src/features/Artboard/data/addBoardReference.ts b/src/features/Artboard/data/addBoardReference.tsnew file mode 100644index 00000000000..8456e9948b5--- /dev/null+++ b/src/features/Artboard/data/addBoardReference.ts@@ -0,0 +1,11 @@+import {+ type ArtboardReference,+ insertArtboardReference,+} from '@/features/ChatInput/InputEditor/ReferArtboard';++import { useArtboardStore } from '../store';++export const addBoardReference = (ref: ArtboardReference) => {+ const { fullscreen, gallery } = useArtboardStore.getState();+ return !gallery && !fullscreen && insertArtboardReference(ref);+};diff --git a/src/features/Artboard/data/agentRunning.ts b/src/features/Artboard/data/agentRunning.tsnew file mode 100644index 00000000000..a4a03639ecc--- /dev/null+++ b/src/features/Artboard/data/agentRunning.ts@@ -0,0 +1,15 @@+import { useChatStore } from '@/store/chat';+import { AI_RUNTIME_OPERATION_TYPES } from '@/store/chat/slices/operation/types';++/** Whether an agent run is in progress in the artboard's topic. */+export const useAgentRunningInTopic = (topicId: string | null) =>+ useChatStore(+ (s) =>+ !!topicId &&+ Object.values(s.operations).some(+ (op) =>+ op.context.topicId === topicId &&+ op.status === 'running' &&+ AI_RUNTIME_OPERATION_TYPES.includes(op.type),+ ),+ );diff --git a/src/features/Artboard/data/announceFinalized.ts b/src/features/Artboard/data/announceFinalized.tsnew file mode 100644index 00000000000..b817a56a28d--- /dev/null+++ b/src/features/Artboard/data/announceFinalized.ts@@ -0,0 +1,47 @@+import type { ArtboardItem } from '@lobechat/types';+import { t } from 'i18next';++import { useChatStore } from '@/store/chat';++import { useArtboardStore } from '../store';+import { resolveBoardConversation } from './boardConversation';++interface AnnounceParams {+ acceptanceUrl: string;+ artboard: Pick<ArtboardItem, 'title' | 'topicId'>;+ count: number;+}++const translate = (key: string, options?: Record<string, unknown>) =>+ t(key as 'artboard.chat.quote', { ...options, ns: 'project' }) as string;++const resolveTarget = async (topicId: string | null) => {+ if (useArtboardStore.getState().gallery) {+ const context = await resolveBoardConversation(topicId);+ return context ? { clear: undefined, context, editor: null, quoted: '' } : undefined;+ }++ const { activeAgentId, activeTopicId, mainInputEditor } = useChatStore.getState();+ if (!activeAgentId || !activeTopicId || activeTopicId !== topicId) return;+ return {+ clear: () => mainInputEditor?.clearContent(),+ context: { agentId: activeAgentId, topicId: activeTopicId },+ editor: mainInputEditor ?? null,+ quoted: mainInputEditor?.getMarkdownContent().trim() ?? '',+ };+};++export const announceFinalized = async ({ acceptanceUrl, artboard, count }: AnnounceParams) => {+ const target = await resolveTarget(artboard.topicId);+ if (!target) return;++ const line = translate('artboard.finalize.message', { count, title: artboard.title });+ const link = `[${translate('artboard.finalize.openAcceptance')}](${acceptanceUrl})`;++ await useChatStore.getState().sendMessage({+ context: target.context,+ inputEditor: target.editor,+ message: [target.quoted, `${line} ${link}`].filter(Boolean).join('\n\n'),+ onMessageAccepted: target.clear,+ });+};diff --git a/src/features/Artboard/data/boardConversation.test.ts b/src/features/Artboard/data/boardConversation.test.tsnew file mode 100644index 00000000000..49f6c14e1eb--- /dev/null+++ b/src/features/Artboard/data/boardConversation.test.ts@@ -0,0 +1,42 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { sendToBoardConversation } from './boardConversation';++const mocks = vi.hoisted(() => ({ getConversation: vi.fn(), sendMessage: vi.fn() }));++vi.mock('@/services/artboard', () => ({+ artboardService: { getConversation: mocks.getConversation },+}));+vi.mock('@/store/chat', () => ({+ useChatStore: { getState: () => ({ sendMessage: mocks.sendMessage }) },+}));++describe('sendToBoardConversation', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.getConversation.mockResolvedValue({ agentId: 'agt_1' });+ });++ it('reports sent once the conversation accepts the message', async () => {+ mocks.sendMessage.mockImplementation(async ({ onMessageAccepted }) => onMessageAccepted());++ expect(await sendToBoardConversation('tpc_1', 'hi')).toBe('sent');+ expect(mocks.sendMessage).toHaveBeenCalledWith(+ expect.objectContaining({ context: { agentId: 'agt_1', topicId: 'tpc_1' }, message: 'hi' }),+ );+ });++ it('reports a failure when the send settles without the message being accepted', async () => {+ mocks.sendMessage.mockResolvedValue(undefined);++ expect(await sendToBoardConversation('tpc_1', 'hi')).toBe('messageFailed');+ });++ it('reports a board with no conversation', async () => {+ mocks.getConversation.mockResolvedValue(null);++ expect(await sendToBoardConversation('tpc_1', 'hi')).toBe('noConversation');+ expect(await sendToBoardConversation(null, 'hi')).toBe('noConversation');+ expect(mocks.sendMessage).not.toHaveBeenCalled();+ });+});diff --git a/src/features/Artboard/data/boardConversation.ts b/src/features/Artboard/data/boardConversation.tsnew file mode 100644index 00000000000..8d7c131b19b--- /dev/null+++ b/src/features/Artboard/data/boardConversation.ts@@ -0,0 +1,34 @@+import { artboardService } from '@/services/artboard';+import { useChatStore } from '@/store/chat';++export interface BoardConversation {+ agentId: string;+ topicId: string;+}++export const resolveBoardConversation = async (+ topicId: string | null,+): Promise<BoardConversation | null> => {+ if (!topicId) return null;+ const topic = await artboardService.getConversation(topicId);+ return topic?.agentId ? { agentId: topic.agentId, topicId } : null;+};++export const sendToBoardConversation = async (+ topicId: string | null,+ message: string,+): Promise<'messageFailed' | 'noConversation' | 'sent'> => {+ const context = await resolveBoardConversation(topicId);+ if (!context) return 'noConversation';+ let accepted = false;+ // sendMessage reports a failed send through the chat store and still resolves.+ await useChatStore.getState().sendMessage({+ context,+ inputEditor: null,+ message,+ onMessageAccepted: () => {+ accepted = true;+ },+ });+ return accepted ? 'sent' : 'messageFailed';+};diff --git a/src/features/Artboard/data/commentActions.test.ts b/src/features/Artboard/data/commentActions.test.tsnew file mode 100644index 00000000000..5d56966a812--- /dev/null+++ b/src/features/Artboard/data/commentActions.test.ts@@ -0,0 +1,70 @@+import type { ArtboardItem } from '@lobechat/types';+import { describe, expect, it } from 'vitest';++import { buildBoardModel } from '../model';+import { commentTargetAt } from './commentActions';++const rect = (x: number, y: number, w = 640, h = 400) => ({ h, w, x, y });++const model = buildBoardModel(+ {+ content: {+ boards: [+ {+ expected: null,+ flowNodeId: null,+ groupId: 'g1',+ id: 'b1',+ pageId: 'p1',+ rect: rect(100, 200),+ roundId: null,+ source: null,+ title: '首页',+ type: 'html',+ },+ ],+ edges: [],+ groups: [+ {+ desc: '',+ id: 'g1',+ kind: 'journey',+ pageId: 'p1',+ rect: rect(52, 56, 736, 592),+ title: '主流程',+ },+ ],+ pages: [{ id: 'p1', name: 'Page 1', sortOrder: 0 }],+ questions: [],+ rounds: [],+ },+ id: 'art_1',+ phase: 'discuss',+ } as unknown as ArtboardItem,+ {},+);++describe('commentTargetAt', () => {+ it('anchors a click on a board by fractions of the board', () => {+ expect(commentTargetAt(model, { x: 420, y: 300 })).toEqual({+ anchor: { type: 'canvas', x: 0.5, y: 0.25 },+ boardId: 'b1',+ pageId: 'p1',+ });+ });++ it('anchors a click inside a group frame from the group’s top-left', () => {+ expect(commentTargetAt(model, { x: 82, y: 76 })).toEqual({+ anchor: { type: 'canvas', x: 30, y: 20 },+ groupId: 'g1',+ pageId: 'p1',+ });+ });++ it('anchors a click on empty canvas in page coordinates', () => {+ expect(commentTargetAt(model, { x: 2000, y: -40 })).toEqual({+ anchor: { type: 'canvas', x: 2000, y: -40 },+ pageId: 'p1',+ });+ });+});diff --git a/src/features/Artboard/data/commentActions.ts b/src/features/Artboard/data/commentActions.tsnew file mode 100644index 00000000000..797a79f0160--- /dev/null+++ b/src/features/Artboard/data/commentActions.ts@@ -0,0 +1,67 @@+import type { ArtboardCommentAnchor, ArtboardRect } from '@lobechat/types';++import { artboardService } from '@/services/artboard';++import type { BoardModel } from '../model';+import { mutateArtboard } from './useArtboard';+import { mutateArtboardComments } from './useArtboardComments';++export interface CommentTarget {+ anchor: ArtboardCommentAnchor;+ boardId?: string;+ groupId?: string;+ pageId: string | undefined;+}++const contains = (rect: ArtboardRect, { x, y }: { x: number; y: number }) =>+ x >= rect.x && x <= rect.x + rect.w && y >= rect.y && y <= rect.y + rect.h;++export const commentTargetAt = (+ model: BoardModel,+ point: { x: number; y: number },+): CommentTarget => {+ const { pageId } = model;+ const board = model.boards.findLast((item) => contains(item.rect, point));+ if (board)+ return {+ anchor: {+ type: 'canvas',+ x: (point.x - board.rect.x) / board.rect.w,+ y: (point.y - board.rect.y) / board.rect.h,+ },+ boardId: board.id,+ pageId,+ };++ const group = model.groups.findLast((item) => contains(item.rect, point));+ if (group)+ return {+ anchor: { type: 'canvas', x: point.x - group.rect.x, y: point.y - group.rect.y },+ groupId: group.id,+ pageId,+ };++ return { anchor: { type: 'canvas', x: point.x, y: point.y }, pageId };+};++export const addThread = async (artboardId: string, target: CommentTarget, content: string) => {+ const thread = await artboardService.addComment(artboardId, {+ ...target,+ clientId: crypto.randomUUID(),+ content,+ });+ await mutateArtboardComments(artboardId);+ return thread;+};++export const replyThread = async (artboardId: string, threadId: string, content: string) => {+ await artboardService.replyComment(threadId, crypto.randomUUID(), content);+ await mutateArtboardComments(artboardId);+};++export const settleThread = async (artboardId: string, threadId: string, resolved: boolean) => {+ await (resolved+ ? artboardService.resolveComment(threadId)+ : artboardService.reopenComment(threadId));+ await Promise.all([mutateArtboardComments(artboardId), mutateArtboard(artboardId)]);+};diff --git a/src/features/Artboard/data/commentModel.test.ts b/src/features/Artboard/data/commentModel.test.tsnew file mode 100644index 00000000000..cefcc12809c--- /dev/null+++ b/src/features/Artboard/data/commentModel.test.ts@@ -0,0 +1,143 @@+import type { ArtboardCommentThreadView, ArtboardItem } from '@lobechat/types';+import { describe, expect, it } from 'vitest';++import { buildBoardModel } from '../model';+import { isAnswered, isQuestion, nextQuestion, pagePins, threadPlace } from './commentModel';++const rect = (x: number, y: number, w = 640, h = 400) => ({ h, w, x, y });++const item = {+ content: {+ boards: [+ {+ expected: null,+ flowNodeId: null,+ groupId: 'g1',+ id: 'b1',+ pageId: 'p1',+ rect: rect(100, 200),+ roundId: null,+ source: null,+ title: '首页',+ type: 'html',+ },+ ],+ edges: [],+ groups: [+ {+ desc: '',+ id: 'g1',+ kind: 'journey',+ pageId: 'p1',+ rect: rect(52, 56, 736, 592),+ title: '主流程',+ },+ ],+ pages: [+ { id: 'p1', name: 'Page 1', sortOrder: 0 },+ { id: 'p2', name: 'Page 2', sortOrder: 1 },+ ],+ questions: [],+ rounds: [],+ },+ id: 'art_1',+ phase: 'discuss',+} as unknown as ArtboardItem;++const model = buildBoardModel(item, null);++const thread = (id: string, patch: Partial<ArtboardCommentThreadView> = {}) =>+ ({+ anchor: null,+ authorAgentId: null,+ authorUserId: 'u1',+ boardId: null,+ content: id,+ createdAt: new Date(0),+ groupId: null,+ id,+ pageId: 'p1',+ replies: [],+ resolvedAt: null,+ stale: false,+ unread: false,+ ...patch,+ }) as ArtboardCommentThreadView;++const reply = (authorAgentId: string | null) => ({+ authorAgentId,+ authorUserId: 'u1',+ content: 'r',+ createdAt: new Date(1),+ id: `r-${authorAgentId}`,+});++describe('pagePins', () => {+ it('places a board comment by fractions of the board', () => {+ const [pin] = pagePins(+ [thread('t1', { anchor: { type: 'canvas', x: 0.5, y: 0.25 }, boardId: 'b1' })],+ model,+ );+ expect(pin).toMatchObject({ x: 420, y: 300 });+ });++ it('places a group comment from the group’s top-left and a canvas comment on the page', () => {+ const pins = pagePins(+ [+ thread('t1', { anchor: { type: 'canvas', x: 30, y: 20 }, groupId: 'g1' }),+ thread('t2', { anchor: { type: 'canvas', x: 900, y: -40 } }),+ ],+ model,+ );+ expect(pins.map(({ x, y }) => ({ x, y }))).toEqual([+ { x: 82, y: 76 },+ { x: 900, y: -40 },+ ]);+ });++ it('puts an unanchored board thread on the board’s top-right corner', () => {+ const [pin] = pagePins([thread('t1', { boardId: 'b1' })], model);+ expect(pin).toMatchObject({ x: 740, y: 200 });+ });++ it('leaves out threads of other pages', () => {+ expect(pagePins([thread('t1', { pageId: 'p2' })], model)).toEqual([]);+ });+});++describe('threads', () => {+ it('treats an agent-opened thread as a question, answered once a user replies', () => {+ const asked = thread('q1', { authorAgentId: 'agt_1' });+ expect(isQuestion(asked)).toBe(true);+ expect(isQuestion(thread('t1'))).toBe(false);+ expect(isAnswered(asked)).toBe(false);+ expect(isAnswered({ ...asked, replies: [reply('agt_1')] })).toBe(false);+ expect(isAnswered({ ...asked, replies: [reply(null)] })).toBe(true);+ });++ it('cycles through the questions still waiting for an answer', () => {+ const threads = [+ thread('q1', { authorAgentId: 'agt_1' }),+ thread('t1'),+ thread('q2', { authorAgentId: 'agt_1', replies: [reply(null)] }),+ thread('q3', { authorAgentId: 'agt_1', pageId: 'p2' }),+ thread('q4', { authorAgentId: 'agt_1', resolvedAt: new Date(2) }),+ ];+ expect(nextQuestion(threads, null)?.id).toBe('q1');+ expect(nextQuestion(threads, 'q1')?.id).toBe('q3');+ expect(nextQuestion(threads, 'q3')?.id).toBe('q1');+ expect(nextQuestion([thread('t1')], null)).toBeUndefined();+ });++ it('names where a thread sits', () => {+ expect(threadPlace(thread('t1', { boardId: 'b1' }), model)).toEqual({+ kind: 'board',+ title: '首页',+ });+ expect(threadPlace(thread('t1', { groupId: 'g1' }), model)).toEqual({+ kind: 'group',+ title: '主流程',+ });+ expect(threadPlace(thread('t1'), model)).toEqual({ kind: 'canvas' });+ });+});diff --git a/src/features/Artboard/data/commentModel.ts b/src/features/Artboard/data/commentModel.tsnew file mode 100644index 00000000000..8def3efd922--- /dev/null+++ b/src/features/Artboard/data/commentModel.ts@@ -0,0 +1,58 @@+import type { ArtboardCommentThreadView } from '@lobechat/types';++import type { BoardModel } from '../model';++export interface ThreadPin {+ thread: ArtboardCommentThreadView;+ x: number;+ y: number;+}++export type ThreadPlace =+ { kind: 'board'; title: string } | { kind: 'group'; title: string } | { kind: 'canvas' };++const GROUP_PIN_INSET = 16;++export const isQuestion = (thread: ArtboardCommentThreadView) => !!thread.authorAgentId;++export const isAnswered = (thread: ArtboardCommentThreadView) =>+ thread.replies.some((reply) => !reply.authorAgentId);++const positionOf = (thread: ArtboardCommentThreadView, model: BoardModel) => {+ const point = thread.anchor?.type === 'canvas' ? thread.anchor : undefined;+ const board = thread.boardId ? model.boardById[thread.boardId] : undefined;+ if (board) {+ const { rect } = board;+ return point+ ? { x: rect.x + point.x * rect.w, y: rect.y + point.y * rect.h }+ : { x: rect.x + rect.w, y: rect.y };+ }+ const group = thread.groupId ? model.groups.find((g) => g.id === thread.groupId) : undefined;+ if (group)+ return {+ x: group.rect.x + (point?.x ?? GROUP_PIN_INSET),+ y: group.rect.y + (point?.y ?? GROUP_PIN_INSET),+ };+ return point ? { x: point.x, y: point.y } : { x: model.bounds.minX, y: model.bounds.minY };+};++export const pagePins = (threads: ArtboardCommentThreadView[], model: BoardModel): ThreadPin[] =>+ threads+ .filter((thread) => thread.pageId === model.pageId)+ .map((thread) => ({ thread, ...positionOf(thread, model) }));++export const waitingQuestions = (threads: ArtboardCommentThreadView[]) =>+ threads.filter((thread) => isQuestion(thread) && !thread.resolvedAt && !isAnswered(thread));++export const nextQuestion = (threads: ArtboardCommentThreadView[], afterId: string | null) => {+ const waiting = waitingQuestions(threads);+ const index = waiting.findIndex((thread) => thread.id === afterId);+ return waiting[(index + 1) % waiting.length];+};++export const threadPlace = (thread: ArtboardCommentThreadView, model: BoardModel): ThreadPlace => {+ const board = thread.boardId ? model.boardById[thread.boardId] : undefined;+ if (board) return { kind: 'board', title: board.title };+ const group = thread.groupId ? model.groups.find((g) => g.id === thread.groupId) : undefined;+ return group ? { kind: 'group', title: group.title } : { kind: 'canvas' };+};diff --git a/src/features/Artboard/data/fileBase.test.ts b/src/features/Artboard/data/fileBase.test.tsnew file mode 100644index 00000000000..62b393a1cd7--- /dev/null+++ b/src/features/Artboard/data/fileBase.test.ts@@ -0,0 +1,35 @@+import { describe, expect, it, vi } from 'vitest';++const { desktop, remoteServerUrl } = vi.hoisted(() => ({+ desktop: { value: false },+ remoteServerUrl: vi.fn(() => 'https://lobe.example.com/'),+}));++vi.mock('@lobechat/const', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ get isDesktop() {+ return desktop.value;+ },+}));+vi.mock('@/store/electron', () => ({ getElectronStoreState: () => ({}) }));+vi.mock('@/store/electron/selectors', () => ({ electronSyncSelectors: { remoteServerUrl } }));++const { resolveArtboardFileBase } = await import('./fileBase');++describe('resolveArtboardFileBase', () => {+ it('keeps the server path on the web', () => {+ desktop.value = false;+ expect(resolveArtboardFileBase('/artboard-files/tok/')).toBe('/artboard-files/tok/');+ });++ it('points the desktop app at its remote server', () => {+ desktop.value = true;+ expect(resolveArtboardFileBase('/artboard-files/tok/')).toBe(+ 'https://lobe.example.com/artboard-files/tok/',+ );+ });++ it('has no base when the server issued none', () => {+ expect(resolveArtboardFileBase(null)).toBeNull();+ });+});diff --git a/src/features/Artboard/data/fileBase.ts b/src/features/Artboard/data/fileBase.tsnew file mode 100644index 00000000000..cb00876a41a--- /dev/null+++ b/src/features/Artboard/data/fileBase.ts@@ -0,0 +1,11 @@+import { isDesktop } from '@lobechat/const';++import { getElectronStoreState } from '@/store/electron';+import { electronSyncSelectors } from '@/store/electron/selectors';++export const resolveArtboardFileBase = (base: string | null | undefined): string | null => {+ if (!base) return null;+ if (!isDesktop) return base;+ const origin = electronSyncSelectors.remoteServerUrl(getElectronStoreState()).replace(/\/+$/, '');+ return origin ? `${origin}${base}` : base;+};diff --git a/src/features/Artboard/data/finalizeBoard.test.ts b/src/features/Artboard/data/finalizeBoard.test.tsnew file mode 100644index 00000000000..843f6bf05ae--- /dev/null+++ b/src/features/Artboard/data/finalizeBoard.test.ts@@ -0,0 +1,49 @@+import { afterEach, describe, expect, it, vi } from 'vitest';++import { artboardActions, useArtboardStore } from '../store';+import { finalizeBoard } from './finalizeBoard';++const { finalize, mutate } = vi.hoisted(() => ({ finalize: vi.fn(), mutate: vi.fn() }));+vi.mock('@/libs/swr', () => ({ mutate, useClientDataSWR: vi.fn() }));+vi.mock('@/services/artboard', () => ({ artboardService: { finalize } }));++describe('finalizeBoard', () => {+ afterEach(() => {+ artboardActions.reset();+ vi.clearAllMocks();+ });++ it('switches to acceptance as soon as finalize succeeds, before the message is sent', async () => {+ finalize.mockResolvedValue({ acceptanceId: 'acc_1', artboard: { id: 'art_1' } });+ let release!: () => void;+ const announce = vi.fn(() => new Promise<void>((resolve) => (release = resolve)));++ const result = await finalizeBoard({ announce, artboardId: 'art_1', revision: 3 });++ expect(result.acceptanceId).toBe('acc_1');+ expect(useArtboardStore.getState().mode).toBe('verify');+ expect(announce).toHaveBeenCalledWith('acc_1');+ release();+ });++ it('keeps the board finalized when the follow-up message fails', async () => {+ finalize.mockResolvedValue({ acceptanceId: 'acc_1', artboard: { id: 'art_1' } });+ const announce = vi.fn().mockRejectedValue(new Error('offline'));++ await expect(+ finalizeBoard({ announce, artboardId: 'art_1', revision: 3 }),+ ).resolves.toMatchObject({ acceptanceId: 'acc_1' });+ expect(useArtboardStore.getState().mode).toBe('verify');+ });++ it('stays in discussion and sends nothing when finalize is refused', async () => {+ finalize.mockRejectedValue(new Error('blocked'));+ const announce = vi.fn();++ await expect(finalizeBoard({ announce, artboardId: 'art_1', revision: 3 })).rejects.toThrow(+ 'blocked',+ );+ expect(useArtboardStore.getState().mode).toBe('discuss');+ expect(announce).not.toHaveBeenCalled();+ });+});diff --git a/src/features/Artboard/data/finalizeBoard.ts b/src/features/Artboard/data/finalizeBoard.tsnew file mode 100644index 00000000000..882ab573e28--- /dev/null+++ b/src/features/Artboard/data/finalizeBoard.ts@@ -0,0 +1,16 @@+import { artboardActions } from '../store';+import { finalizeArtboard } from './actions';++interface FinalizeBoardParams {+ announce: (acceptanceId: string) => Promise<void>;+ artboardId: string;+ revision: number;+}++export const finalizeBoard = async ({ announce, artboardId, revision }: FinalizeBoardParams) => {+ const result = await finalizeArtboard(artboardId, revision);+ artboardActions.setMode('verify');+ if (result.acceptanceId)+ announce(result.acceptanceId).catch((error) => console.error('[artboard:announce]', error));+ return result;+};diff --git a/src/features/Artboard/data/onArtboardToolResult.test.ts b/src/features/Artboard/data/onArtboardToolResult.test.tsnew file mode 100644index 00000000000..8179386ef41--- /dev/null+++ b/src/features/Artboard/data/onArtboardToolResult.test.ts@@ -0,0 +1,70 @@+import { afterEach, describe, expect, it, vi } from 'vitest';++import { artboardActions, useArtboardStore } from '../store';+import { onArtboardToolResult } from './onArtboardToolResult';++const { mutate } = vi.hoisted(() => ({ mutate: vi.fn() }));+vi.mock('@/libs/swr', () => ({ mutate, useClientDataSWR: vi.fn() }));++const state = { artboardId: 'art_1', changedIds: ['f2'], revision: 4 };++describe('onArtboardToolResult', () => {+ afterEach(() => {+ artboardActions.reset();+ vi.clearAllMocks();+ });++ it('refreshes the board cache from the tool result with no board on screen', async () => {+ await onArtboardToolResult({ apiName: 'updateArtboard', result: { state, success: true } });++ expect(mutate).toHaveBeenCalledWith(['artboard', 'art_1']);+ expect(useArtboardStore.getState().flash).toEqual([]);+ });++ it('flashes the changed items on the open board', async () => {+ artboardActions.bindBoard('art_1');++ await onArtboardToolResult({ apiName: 'createArtboard', result: { state, success: true } });++ expect(useArtboardStore.getState().flash).toEqual(['f2']);+ });++ it('refreshes the board and its comments after the agent rewrites board files', async () => {+ await onArtboardToolResult({+ apiName: 'writeArtboardFiles',+ result: { state: { artboardId: 'art_1', files: [] }, success: true },+ });++ expect(mutate).toHaveBeenCalledWith(['artboard', 'art_1']);+ expect(mutate).toHaveBeenCalledWith(['artboard-comments', 'art_1']);+ });++ it('refreshes the board and its comments when the agent asks a question', async () => {+ await onArtboardToolResult({+ apiName: 'askArtboardQuestion',+ result: { state: { artboardId: 'art_1', commentId: 'c1' }, success: true },+ });++ expect(mutate).toHaveBeenCalledWith(['artboard', 'art_1']);+ expect(mutate).toHaveBeenCalledWith(['artboard-comments', 'art_1']);+ });++ it('refreshes the open board when the agent replies in or resolves a thread', async () => {+ artboardActions.bindBoard('art_9');++ await onArtboardToolResult({+ apiName: 'resolveArtboardComment',+ result: { state: { commentId: 'c1' }, success: true },+ });++ expect(mutate).toHaveBeenCalledWith(['artboard', 'art_9']);+ expect(mutate).toHaveBeenCalledWith(['artboard-comments', 'art_9']);+ });++ it('ignores failed writes and reads', async () => {+ await onArtboardToolResult({ apiName: 'updateArtboard', result: { state, success: false } });+ await onArtboardToolResult({ apiName: 'readArtboard', result: { state, success: true } });++ expect(mutate).not.toHaveBeenCalled();+ });+});diff --git a/src/features/Artboard/data/onArtboardToolResult.ts b/src/features/Artboard/data/onArtboardToolResult.tsnew file mode 100644index 00000000000..81f39c66fa1--- /dev/null+++ b/src/features/Artboard/data/onArtboardToolResult.ts@@ -0,0 +1,42 @@+import { ArtboardApiName, type ArtboardToolState } from '@lobechat/builtin-tool-artboard';++import { artboardActions, useArtboardStore } from '../store';+import { mutateArtboard } from './useArtboard';+import { mutateArtboardComments } from './useArtboardComments';++const WRITE_APIS = new Set<string>([+ ArtboardApiName.createArtboard,+ ArtboardApiName.updateArtboard,+]);++// Calls that change what boards or threads show without a new revision: a rewritten file+// changes the page and can leave comments stale.+const BOARD_AND_COMMENT_APIS = new Set<string>([+ ArtboardApiName.askArtboardQuestion,+ ArtboardApiName.replyArtboardComment,+ ArtboardApiName.resolveArtboardComment,+ ArtboardApiName.writeArtboardFiles,+]);++interface ArtboardToolOutcome {+ apiName: string;+ result: { state?: unknown; success?: boolean };+}++export const onArtboardToolResult = async ({ apiName, result }: ArtboardToolOutcome) => {+ if (result.success === false) return;+ const state = result.state as Partial<ArtboardToolState> | undefined;++ if (BOARD_AND_COMMENT_APIS.has(apiName)) {+ const artboardId = state?.artboardId ?? useArtboardStore.getState().boardId;+ if (artboardId)+ await Promise.all([mutateArtboard(artboardId), mutateArtboardComments(artboardId)]);+ return;+ }++ if (!WRITE_APIS.has(apiName) || !state?.artboardId) return;++ await mutateArtboard(state.artboardId);+ if (useArtboardStore.getState().boardId === state.artboardId)+ artboardActions.flashItems(state.changedIds ?? []);+};diff --git a/src/features/Artboard/data/references.test.ts b/src/features/Artboard/data/references.test.tsnew file mode 100644index 00000000000..f4ebd1618a0--- /dev/null+++ b/src/features/Artboard/data/references.test.ts@@ -0,0 +1,51 @@+import type { ArtboardItem } from '@lobechat/types';+import { describe, expect, it } from 'vitest';++import { buildBoardModel } from '../model';+import { boardReference } from './references';++const board = buildBoardModel(+ {+ acceptanceId: null,+ content: {+ boards: [+ {+ expected: null,+ flowNodeId: null,+ groupId: 'g1',+ id: 'b1',+ pageId: 'p1',+ rect: { h: 400, w: 640, x: 0, y: 0 },+ roundId: null,+ source: { hash: 'h_cvs_1', kind: 'file', path: 'pages/cvs_1.html' },+ title: '空项目',+ type: 'html',+ },+ ],+ edges: [],+ groups: [],+ pages: [{ id: 'p1', name: 'Page 1', sortOrder: 0 }],+ questions: [],+ rounds: [],+ },+ id: 'art_1',+ phase: 'discuss',+ revision: 1,+ } as unknown as ArtboardItem,+ {},+);++describe('boardReference', () => {+ it('names a board by its title', () => {+ expect(boardReference(board, 'b1', ' 改短 ')).toEqual({+ artboardId: 'art_1',+ itemId: 'b1',+ itemTitle: '空项目',+ text: '改短',+ });+ });++ it('refers to nothing for a board that is gone', () => {+ expect(boardReference(board, 'b9', 'x')).toBeUndefined();+ });+});diff --git a/src/features/Artboard/data/references.ts b/src/features/Artboard/data/references.tsnew file mode 100644index 00000000000..3e46c95da00--- /dev/null+++ b/src/features/Artboard/data/references.ts@@ -0,0 +1,18 @@+import type { ArtboardReference } from '@/features/ChatInput/InputEditor/ReferArtboard';++import type { BoardModel } from '../model';++export const boardReference = (+ board: BoardModel,+ boardId: string,+ text: string,+): ArtboardReference | undefined => {+ const target = board.boardById[boardId];+ if (!target) return;+ return {+ artboardId: board.artboard.id,+ itemId: boardId,+ itemTitle: target.title,+ text: text.trim(),+ };+};diff --git a/src/features/Artboard/data/revisionWatch.test.ts b/src/features/Artboard/data/revisionWatch.test.tsnew file mode 100644index 00000000000..bb92a18c490--- /dev/null+++ b/src/features/Artboard/data/revisionWatch.test.ts@@ -0,0 +1,71 @@+import { afterEach, describe, expect, it, vi } from 'vitest';++import { artboardActions, useArtboardStore } from '../store';+import { checkArtboardRevision, refreshStaleArtboard } from './revisionWatch';++const { getRevision, mutate } = vi.hoisted(() => ({ getRevision: vi.fn(), mutate: vi.fn() }));+vi.mock('@/libs/swr', () => ({ mutate, useClientDataSWR: vi.fn() }));+vi.mock('@/services/artboard', () => ({ artboardService: { getRevision } }));++const shown = { revision: 3, updatedAt: new Date('2026-11-18T10:00:00Z') };++describe('artboard revision watch', () => {+ afterEach(() => {+ artboardActions.reset();+ vi.clearAllMocks();+ });++ it('flags the open board stale when the server has a newer revision', async () => {+ artboardActions.bindBoard('art_1');+ getRevision.mockResolvedValue({ revision: 5, updatedAt: new Date('2026-11-18T11:00:00Z') });++ await checkArtboardRevision('art_1', shown);++ expect(useArtboardStore.getState().staleRevision).toBe(5);+ expect(mutate).not.toHaveBeenCalled();+ });++ it('stays quiet when the board already shows the latest revision', async () => {+ artboardActions.bindBoard('art_1');+ getRevision.mockResolvedValue(shown);++ await checkArtboardRevision('art_1', shown);++ expect(useArtboardStore.getState().staleRevision).toBeNull();+ expect(mutate).not.toHaveBeenCalled();+ });++ it('reloads the open board in place when only its files changed', async () => {+ artboardActions.bindBoard('art_1');+ getRevision.mockResolvedValue({ revision: 3, updatedAt: new Date('2026-11-18T10:05:00Z') });++ await checkArtboardRevision('art_1', shown);++ expect(useArtboardStore.getState().staleRevision).toBeNull();+ expect(mutate).toHaveBeenCalledWith(['artboard', 'art_1']);+ });++ it('ignores the answer when another board opened meanwhile', async () => {+ artboardActions.bindBoard('art_1');+ getRevision.mockImplementation(async () => {+ artboardActions.bindBoard('art_2');+ return { revision: 9, updatedAt: new Date('2026-11-18T12:00:00Z') };+ });++ await checkArtboardRevision('art_1', shown);++ expect(useArtboardStore.getState().staleRevision).toBeNull();+ expect(mutate).not.toHaveBeenCalled();+ });++ it('reloads the board and clears the banner on refresh', async () => {+ artboardActions.bindBoard('art_1');+ getRevision.mockResolvedValue({ revision: 5, updatedAt: new Date('2026-11-18T11:00:00Z') });+ await checkArtboardRevision('art_1', shown);++ await refreshStaleArtboard('art_1');++ expect(mutate).toHaveBeenCalled();+ expect(useArtboardStore.getState().staleRevision).toBeNull();+ });+});diff --git a/src/features/Artboard/data/revisionWatch.ts b/src/features/Artboard/data/revisionWatch.tsnew file mode 100644index 00000000000..459871abd07--- /dev/null+++ b/src/features/Artboard/data/revisionWatch.ts@@ -0,0 +1,28 @@+import type { ArtboardItem } from '@lobechat/types';++import { artboardService } from '@/services/artboard';++import { artboardActions, useArtboardStore } from '../store';+import { mutateArtboard } from './useArtboard';++export const checkArtboardRevision = async (+ id: string,+ shown: Pick<ArtboardItem, 'revision' | 'updatedAt'>,+) => {+ const latest = await artboardService.getRevision(id);+ if (useArtboardStore.getState().boardId !== id) return;+ if (latest.revision > shown.revision) {+ artboardActions.setStaleRevision(latest.revision);+ return;+ }+ artboardActions.setStaleRevision(null);+ // Same structure, newer row: only files changed (a CLI push, another tab). Nothing on screen+ // can conflict with a file, so reload in place instead of asking.+ if (new Date(latest.updatedAt).getTime() > new Date(shown.updatedAt).getTime())+ await mutateArtboard(id);+};++export const refreshStaleArtboard = async (id: string) => {+ await mutateArtboard(id);+ artboardActions.setStaleRevision(null);+};diff --git a/src/features/Artboard/data/submitBatch.test.ts b/src/features/Artboard/data/submitBatch.test.tsnew file mode 100644index 00000000000..19ed722e614--- /dev/null+++ b/src/features/Artboard/data/submitBatch.test.ts@@ -0,0 +1,169 @@+import type { ArtboardCommentThreadView, ArtboardRoundView } from '@lobechat/types';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type { BoardModel } from '../model';+import { pendingThreads, submitBoardBatch, summarizeRounds } from './submitBatch';++const mocks = vi.hoisted(() => ({+ deliverComments: vi.fn(),+ send: vi.fn(),+ submitRounds: vi.fn(),+}));+vi.mock('@/services/artboard', () => ({+ artboardService: { deliverComments: mocks.deliverComments, submitRounds: mocks.submitRounds },+}));+vi.mock('./boardConversation', () => ({ sendToBoardConversation: mocks.send }));+vi.mock('./useArtboard', () => ({ mutateArtboard: vi.fn() }));+vi.mock('./useArtboardComments', () => ({ mutateArtboardComments: vi.fn() }));+vi.mock('i18next', () => ({+ t: (key: string, options?: Record<string, unknown>) =>+ key === 'artboard.chat.quote' ? `Re: ${options?.target}` : `${key}:${options?.count}`,+}));++const model = {+ artboard: { id: 'art_1', title: '画板', topicId: 'tpc_1' },+ boardById: {+ b1: { id: 'b1', roundId: null, title: '购物清单' },+ b2: { id: 'b2', roundId: 'r1', title: '方案 A' },+ },+ groups: [{ id: 'g1', title: '主流程' }],+ openRounds: [],+} as unknown as BoardModel;++const comment = (content: string, agent = false) => ({+ authorAgentId: agent ? 'agt_1' : null,+ authorUserId: agent ? null : 'u1',+ content,+ createdAt: new Date(),+ id: `c_${content}`,+});++const thread = (+ id: string,+ root: ReturnType<typeof comment>,+ replies: ReturnType<typeof comment>[] = [],+ extra: Partial<ArtboardCommentThreadView> = {},+) =>+ ({+ ...root,+ anchor: null,+ boardId: 'b1',+ groupId: null,+ id,+ pageId: 'p1',+ replies,+ resolvedAt: null,+ stale: false,+ unread: true,+ ...extra,+ }) as ArtboardCommentThreadView;++const round = (id: string, patch: Partial<ArtboardRoundView> = {}): ArtboardRoundView => ({+ batchId: null,+ chosenBoardId: null,+ id,+ pageId: 'p1',+ recommendedBoardId: null,+ status: 'open',+ title: id,+ ...patch,+});++describe('summarizeRounds', () => {+ it('counts picks, recommendations that will apply, and rounds with neither', () => {+ expect(+ summarizeRounds([+ round('r1', { chosenBoardId: 'a', recommendedBoardId: 'b' }),+ round('r2', { recommendedBoardId: 'c' }),+ round('r3'),+ round('r4'),+ ]),+ ).toEqual({ byRecommendation: 1, firstUndecidedId: 'r3', picked: 1, total: 4, undecided: 2 });+ });+});++describe('pendingThreads', () => {+ it('counts every unread thread the next submit sends, including those on open-round options', () => {+ const threads = [+ thread('t1', comment('一')),+ thread('t2', comment('二'), [], { boardId: 'b2' }),+ thread('t3', comment('三'), [], { unread: false }),+ thread('t4', comment('四'), [], { resolvedAt: new Date() }),+ thread('t5', comment('放哪?', true), [comment('标题旁')], { resolvedAt: new Date() }),+ ];++ expect(pendingThreads(threads).map((item) => item.id)).toEqual(['t1', 't2', 't5']);+ });+});++describe('submitBoardBatch', () => {+ beforeEach(() => {+ vi.clearAllMocks();+ mocks.submitRounds.mockResolvedValue({ submitted: 1 });+ mocks.send.mockResolvedValue('sent');+ });++ it('sends the picks and the new comments to the topic as one message', async () => {+ mocks.deliverComments.mockResolvedValue([+ thread('t1', comment('这里改下 ui')),+ thread('t2', comment('要不要加按钮', true), [comment('要')], {+ boardId: null,+ groupId: 'g1',+ }),+ thread('t3', comment('旧的'), [], { unread: false }),+ ]);++ const result = await submitBoardBatch(model, ['r1']);++ expect(mocks.submitRounds).toHaveBeenCalledWith('art_1', ['r1']);+ expect(result.status).toBe('sent');+ expect(mocks.send).toHaveBeenCalledWith(+ 'tpc_1',+ [+ 'artboard.submit.message:1',+ 'artboard.submit.commentMessage:2',+ '> Re: t1 · 购物清单 · artboard art_1\n\n这里改下 ui',+ '> Re: t2 · 主流程 · artboard art_1\n\n要',+ '> artboard art_1 · 画板',+ ].join('\n\n'),+ );+ });++ it('sends comments alone when there is no open round', async () => {+ mocks.deliverComments.mockResolvedValue([thread('t1', comment('太挤了'))]);++ await submitBoardBatch(model, []);++ expect(mocks.submitRounds).not.toHaveBeenCalled();+ expect(mocks.send.mock.calls[0][1]).toMatch(/^artboard\.submit\.commentMessage:1\n\n> Re: t1/);+ });++ it('still submits when the board has no conversation', async () => {+ mocks.deliverComments.mockResolvedValue([]);+ mocks.send.mockResolvedValue('noConversation');++ expect((await submitBoardBatch(model, ['r1'])).status).toBe('noConversation');+ });++ it('reports a message that failed after the batch was saved', async () => {+ mocks.deliverComments.mockResolvedValue([]);+ mocks.send.mockRejectedValue(new Error('offline'));++ expect((await submitBoardBatch(model, ['r1'])).status).toBe('messageFailed');+ });++ it('sends nothing when the round submit is refused', async () => {+ mocks.submitRounds.mockRejectedValueOnce(new Error('missing choice'));++ await expect(submitBoardBatch(model, ['r1'])).rejects.toThrow('missing choice');+ expect(mocks.deliverComments).not.toHaveBeenCalled();+ expect(mocks.send).not.toHaveBeenCalled();+ });++ it('sends nothing when there is nothing new', async () => {+ mocks.deliverComments.mockResolvedValue([thread('t3', comment('旧的'), [], { unread: false })]);++ expect((await submitBoardBatch(model, [])).status).toBe('nothing');+ expect(mocks.send).not.toHaveBeenCalled();+ });+});diff --git a/src/features/Artboard/data/submitBatch.ts b/src/features/Artboard/data/submitBatch.tsnew file mode 100644index 00000000000..4336bf02007--- /dev/null+++ b/src/features/Artboard/data/submitBatch.ts@@ -0,0 +1,99 @@+import type { ArtboardCommentThreadView, ArtboardRoundView } from '@lobechat/types';+import { t } from 'i18next';++import { serializeArtboardReference } from '@/features/ChatInput/InputEditor/ReferArtboard';+import { artboardService } from '@/services/artboard';++import type { BoardModel } from '../model';+import { sendToBoardConversation } from './boardConversation';+import { isQuestion } from './commentModel';+import { mutateArtboard } from './useArtboard';+import { mutateArtboardComments } from './useArtboardComments';++const translate = (key: string, options?: Record<string, unknown>) =>+ t(key as 'artboard.chat.quote', { ...options, ns: 'project' }) as string;++export interface RoundSummary {+ byRecommendation: number;+ firstUndecidedId: string | undefined;+ picked: number;+ total: number;+ undecided: number;+}++export const summarizeRounds = (open: ArtboardRoundView[]): RoundSummary => {+ const picked = open.filter((round) => round.chosenBoardId).length;+ const undecided = open.filter((round) => !round.chosenBoardId && !round.recommendedBoardId);+ return {+ byRecommendation: open.length - picked - undecided.length,+ firstUndecidedId: undecided[0]?.id,+ picked,+ total: open.length,+ undecided: undecided.length,+ };+};++// The submit bar submits every open round, so comments held on their options go out with it.+export const pendingThreads = (threads: ArtboardCommentThreadView[]) =>+ threads.filter((thread) => thread.unread && (!thread.resolvedAt || isQuestion(thread)));++const placeTitle = (model: BoardModel, thread: ArtboardCommentThreadView) => {+ const board = thread.boardId ? model.boardById[thread.boardId] : undefined;+ if (board) return board.title;+ const group = thread.groupId ? model.groups.find((g) => g.id === thread.groupId) : undefined;+ return group?.title ?? translate('artboard.comment.onCanvas');+};++const newestFromUser = (thread: ArtboardCommentThreadView) => {+ const comments = [thread, ...thread.replies];+ const lastAgent = comments.findLastIndex((comment) => !!comment.authorAgentId);+ return comments.slice(lastAgent + 1).map((comment) => comment.content);+};++const quoteThread = (model: BoardModel, thread: ArtboardCommentThreadView) =>+ [+ serializeArtboardReference(+ {+ artboardId: model.artboard.id,+ itemId: thread.id,+ itemTitle: placeTitle(model, thread),+ text: '',+ },+ translate,+ ),+ newestFromUser(thread).join('\n\n'),+ ].join('\n\n');++export type SubmitStatus = 'messageFailed' | 'noConversation' | 'nothing' | 'sent';++export const submitBoardBatch = async (+ model: BoardModel,+ roundIds: string[],+): Promise<{ message: string; status: SubmitStatus }> => {+ const { artboard } = model;+ const choices = roundIds.length+ ? (await artboardService.submitRounds(artboard.id, roundIds)).submitted+ : 0;+ const threads = (await artboardService.deliverComments(artboard.id)).filter(+ (thread) => thread.unread,+ );+ void mutateArtboard(artboard.id);+ void mutateArtboardComments(artboard.id);++ const message = [+ ...(choices ? [translate('artboard.submit.message', { count: choices })] : []),+ ...(threads.length+ ? [translate('artboard.submit.commentMessage', { count: threads.length })]+ : []),+ ...threads.map((thread) => quoteThread(model, thread)),+ `> artboard ${artboard.id} · ${artboard.title}`,+ ].join('\n\n');+ if (!choices && !threads.length) return { message, status: 'nothing' };++ try {+ return { message, status: await sendToBoardConversation(artboard.topicId, message) };+ } catch (error) {+ console.error('[artboard:submit]', error);+ return { message, status: 'messageFailed' };+ }+};diff --git a/src/features/Artboard/data/useArtboard.ts b/src/features/Artboard/data/useArtboard.tsnew file mode 100644index 00000000000..b0a9d3618dc--- /dev/null+++ b/src/features/Artboard/data/useArtboard.ts@@ -0,0 +1,16 @@+import { mutate, useClientDataSWR } from '@/libs/swr';+import { artboardService, type ArtboardView } from '@/services/artboard';++import { useArtboardFeature } from '../useArtboardFeature';++export const artboardSWRKey = (id: string) => ['artboard', id] as const;++export const useArtboard = (id: string | undefined) => {+ const { enabled } = useArtboardFeature();+ return useClientDataSWR<ArtboardView>(enabled && id ? artboardSWRKey(id) : null, () =>+ artboardService.get(id!),+ );+};++export const mutateArtboard = (id: string, data?: ArtboardView) =>+ data ? mutate(artboardSWRKey(id), data, { revalidate: false }) : mutate(artboardSWRKey(id));diff --git a/src/features/Artboard/data/useArtboardComments.ts b/src/features/Artboard/data/useArtboardComments.tsnew file mode 100644index 00000000000..3830b7645c7--- /dev/null+++ b/src/features/Artboard/data/useArtboardComments.ts@@ -0,0 +1,21 @@+import type { ArtboardCommentThreadView } from '@lobechat/types';++import { mutate, useClientDataSWR } from '@/libs/swr';+import { artboardService } from '@/services/artboard';++import { useArtboardFeature } from '../useArtboardFeature';++const REFRESH_MS = 30_000;++export const artboardCommentsKey = (id: string) => ['artboard-comments', id] as const;++export const useArtboardComments = (id: string | undefined) => {+ const { enabled } = useArtboardFeature();+ return useClientDataSWR<ArtboardCommentThreadView[]>(+ enabled && id ? artboardCommentsKey(id) : null,+ () => artboardService.listComments(id!),+ { focusThrottleInterval: 0, refreshInterval: REFRESH_MS, revalidateOnFocus: true },+ );+};++export const mutateArtboardComments = (id: string) => mutate(artboardCommentsKey(id));diff --git a/src/features/Artboard/data/useArtboardRevisionWatch.test.ts b/src/features/Artboard/data/useArtboardRevisionWatch.test.tsnew file mode 100644index 00000000000..26ae503835e--- /dev/null+++ b/src/features/Artboard/data/useArtboardRevisionWatch.test.ts@@ -0,0 +1,81 @@+import { act, renderHook } from '@testing-library/react';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { useChatStore } from '@/store/chat';+import type { Operation } from '@/store/chat/slices/operation/types';++import { useArtboardRevisionWatch } from './useArtboardRevisionWatch';++const { checkArtboardRevision } = vi.hoisted(() => ({+ checkArtboardRevision: vi.fn(async () => {}),+}));+vi.mock('./revisionWatch', () => ({ checkArtboardRevision }));++const artboard = {+ id: 'art_1',+ revision: 3,+ topicId: 'tpc_1',+ updatedAt: new Date('2026-11-18T10:00:00Z'),+};++const run = (status: Operation['status']) =>+ act(() => {+ useChatStore.setState({+ operations: {+ op_1: {+ context: { topicId: 'tpc_1' },+ id: 'op_1',+ metadata: {},+ status,+ type: 'execHeterogeneousAgent',+ } as unknown as Operation,+ },+ });+ });++describe('useArtboardRevisionWatch', () => {+ beforeEach(() => {+ vi.useFakeTimers();+ });++ afterEach(() => {+ act(() => useChatStore.setState({ operations: {} }));+ vi.useRealTimers();+ vi.clearAllMocks();+ });++ it('polls every 2 s while an agent runs in the topic and stops when the run ends', async () => {+ run('running');+ renderHook(() => useArtboardRevisionWatch(artboard));++ await act(() => vi.advanceTimersByTimeAsync(2000));+ expect(checkArtboardRevision).toHaveBeenCalledTimes(1);+ await act(() => vi.advanceTimersByTimeAsync(4000));+ expect(checkArtboardRevision).toHaveBeenCalledTimes(3);++ run('success');+ // The run-end check fires once; no more polling after it.+ expect(checkArtboardRevision).toHaveBeenCalledTimes(4);+ await act(() => vi.advanceTimersByTimeAsync(10_000));+ expect(checkArtboardRevision).toHaveBeenCalledTimes(4);+ });++ it('stops polling when the board closes', async () => {+ run('running');+ const { unmount } = renderHook(() => useArtboardRevisionWatch(artboard));++ await act(() => vi.advanceTimersByTimeAsync(2000));+ expect(checkArtboardRevision).toHaveBeenCalledTimes(1);++ unmount();+ await act(() => vi.advanceTimersByTimeAsync(10_000));+ expect(checkArtboardRevision).toHaveBeenCalledTimes(1);+ });++ it('does not poll while no agent runs in the topic', async () => {+ renderHook(() => useArtboardRevisionWatch(artboard));++ await act(() => vi.advanceTimersByTimeAsync(10_000));+ expect(checkArtboardRevision).not.toHaveBeenCalled();+ });+});diff --git a/src/features/Artboard/data/useArtboardRevisionWatch.ts b/src/features/Artboard/data/useArtboardRevisionWatch.tsnew file mode 100644index 00000000000..ffe38798d77--- /dev/null+++ b/src/features/Artboard/data/useArtboardRevisionWatch.ts@@ -0,0 +1,54 @@+import type { ArtboardItem } from '@lobechat/types';+import { useEffect, useRef } from 'react';++import { artboardActions, useArtboardStore } from '../store';+import { useAgentRunningInTopic } from './agentRunning';+import { checkArtboardRevision } from './revisionWatch';++/** While an agent runs, files land one by one (CLI writes); poll so boards fill in as they do. */+const RUNNING_POLL_INTERVAL = 2000;++export const useArtboardRevisionWatch = (+ artboard: Pick<ArtboardItem, 'id' | 'revision' | 'topicId' | 'updatedAt'>,+) => {+ const { id, revision, topicId, updatedAt } = artboard;+ const running = useAgentRunningInTopic(topicId);+ const stale = useArtboardStore((s) => s.staleRevision);+ const shown = useRef({ revision, updatedAt });+ shown.current = { revision, updatedAt };++ useEffect(() => {+ if (stale !== null && revision >= stale) artboardActions.setStaleRevision(null);+ }, [revision, stale]);++ useEffect(() => {+ const check = () => void checkArtboardRevision(id, shown.current).catch(() => {});+ window.addEventListener('focus', check);+ return () => window.removeEventListener('focus', check);+ }, [id]);++ const wasRunning = useRef(running);+ useEffect(() => {+ if (wasRunning.current && !running)+ void checkArtboardRevision(id, shown.current).catch(() => {});+ wasRunning.current = running;+ }, [id, running]);++ useEffect(() => {+ if (!running) return;+ let stopped = false;+ let timer: ReturnType<typeof setTimeout>;+ // Chained, not an interval: a slow check never overlaps the next one.+ const schedule = () => {+ timer = setTimeout(async () => {+ await checkArtboardRevision(id, shown.current).catch(() => {});+ if (!stopped) schedule();+ }, RUNNING_POLL_INTERVAL);+ };+ schedule();+ return () => {+ stopped = true;+ clearTimeout(timer);+ };+ }, [id, running]);+};diff --git a/src/features/Artboard/data/useBoardModel.ts b/src/features/Artboard/data/useBoardModel.tsnew file mode 100644index 00000000000..69ec455785a--- /dev/null+++ b/src/features/Artboard/data/useBoardModel.ts@@ -0,0 +1,14 @@+import { useMemo } from 'react';++import { buildBoardModel } from '../model';+import { resolveArtboardFileBase } from './fileBase';+import { useArtboard } from './useArtboard';++export const useBoardModel = (artboardId: string) => {+ const { data } = useArtboard(artboardId);+ return useMemo(+ () =>+ data ? buildBoardModel(data.artboard, resolveArtboardFileBase(data.fileBaseUrl)) : undefined,+ [data],+ );+};diff --git a/src/features/Artboard/edgeSpread.test.ts b/src/features/Artboard/edgeSpread.test.tsnew file mode 100644index 00000000000..ff3d61dfce3--- /dev/null+++ b/src/features/Artboard/edgeSpread.test.ts@@ -0,0 +1,133 @@+import type { ArtboardRect } from '@lobechat/types';+import { describe, expect, it } from 'vitest';++import { EDGE_LABEL_HEIGHT } from './Canvas/edgeLabel';+import { EDGE_LABEL_SLOT, EDGE_LANE_GAP, spreadEdges } from './edgeSpread';+import { computeEdgePath } from './model';++const rect = (x: number, y: number, w = 640, h = 400): ArtboardRect => ({ h, w, x, y });+const edge = (id: string, from: ArtboardRect, to: ArtboardRect, label = id) => ({+ id,+ label,+ ...computeEdgePath(from, to),+});++/** A label of a given rendered width, so collision boxes are explicit. */+const options = (width: number) => ({+ labelBox: () => ({ h: EDGE_LABEL_HEIGHT, w: width }),+ labelled: (e: { label: string }) => !!e.label,+});+const wide = options(320);+const narrow = options(12);++const labelAt = (id: string, lx: number, ly: number) => ({+ d: `M0 0 H${lx} V${ly}`,+ id,+ label: id,+ lx,+ ly,+ points: [+ [lx - 100, ly],+ [lx, ly],+ [lx, ly],+ [lx + 100, ly],+ ] as [number, number][],+ room: 400,+});++describe('spreadEdges', () => {+ it('leaves edges that share nothing untouched', () => {+ const edges = [edge('a', rect(0, 0), rect(840, 0)), edge('b', rect(0, 2000), rect(840, 2000))];++ expect(spreadEdges(edges, wide).edges).toEqual(edges);+ });++ it('gives edges that share a vertical corridor their own lanes', () => {+ const edges = [edge('a', rect(0, 0), rect(840, 700)), edge('b', rect(0, 700), rect(840, 0))];++ const [a, b] = spreadEdges(edges, wide).edges;++ expect(b.points[1][0] - a.points[1][0]).toBe(EDGE_LANE_GAP);+ expect((a.points[1][0] + b.points[1][0]) / 2).toBe(740);+ expect(a.points[1][0]).toBe(a.points[2][0]);+ expect(a.d).toBe(`M640 200 H${a.points[1][0]} V900 H840`);+ expect(a.lx).toBe(a.points[1][0]);+ });++ it('keeps lanes inside a narrow gap', () => {+ const edges = [+ edge('a', rect(0, 0), rect(660, 700)),+ edge('b', rect(0, 700), rect(660, 0)),+ edge('c', rect(0, 350), rect(660, 1400)),+ ];++ const xs = spreadEdges(edges, wide).edges.map((e) => e.points[1][0]);++ expect(Math.min(...xs)).toBeGreaterThan(640);+ expect(Math.max(...xs)).toBeLessThan(660);+ });++ it('separates wide labels whose centres are far apart but whose glyphs overlap', () => {+ // 220px labels centred 100px apart ran straight through each other under+ // the old centre-distance heuristic.+ const edges = [labelAt('a', 400, 300), labelAt('b', 500, 300)];++ const { edges: placed, hiddenLabels } = spreadEdges(edges, wide);++ expect(hiddenLabels.size).toBe(0);+ expect(placed[0].ly).toBe(300);+ expect(Math.abs(placed[1].ly - 300)).toBe(EDGE_LABEL_HEIGHT + EDGE_LABEL_SLOT);+ });++ it('keeps narrow labels put when their boxes already clear each other', () => {+ const edges = [labelAt('a', 400, 300), labelAt('b', 500, 300)];++ const { edges: placed, hiddenLabels } = spreadEdges(edges, narrow);++ expect(hiddenLabels.size).toBe(0);+ expect(placed.map((e) => e.ly)).toEqual([300, 300]);+ });++ it('reports a label as crowded instead of drawing it over another one', () => {+ // Ten identical slots: the middle ones fit, the far ones run out of slots.+ const edges = Array.from({ length: 12 }, (_, index) => labelAt(`e${index}`, 400, 300));++ const { hiddenLabels } = spreadEdges(edges, wide);++ expect(hiddenLabels.size).toBeGreaterThan(0);+ });++ it('does not move a label away from an edge that has no text', () => {+ const edges = [+ edge('a', rect(0, 0), rect(840, 700)),+ edge('b', rect(0, 700), rect(840, 0), ''),+ ];++ const [a] = spreadEdges(edges, wide).edges;++ expect(a.ly).toBe(550);+ });++ it('moves a label off a board it would sit on', () => {+ const board = { h: 100, w: 300, x: 250, y: 250 };++ const { edges: placed, hiddenLabels } = spreadEdges([labelAt('a', 400, 300)], {+ ...wide,+ obstacles: [board],+ });++ const { ly } = placed[0];+ expect(hiddenLabels.size).toBe(0);+ expect(+ ly + EDGE_LABEL_HEIGHT / 2 <= board.y || ly - EDGE_LABEL_HEIGHT / 2 >= board.y + board.h,+ ).toBe(true);+ });++ it('hides a label that only fits on top of a board', () => {+ const board = { h: 800, w: 640, x: 80, y: -100 };++ const { hiddenLabels } = spreadEdges([labelAt('a', 400, 300)], { ...wide, obstacles: [board] });++ expect(hiddenLabels.has('a')).toBe(true);+ });+});diff --git a/src/features/Artboard/edgeSpread.ts b/src/features/Artboard/edgeSpread.tsnew file mode 100644index 00000000000..98490d9ecc3--- /dev/null+++ b/src/features/Artboard/edgeSpread.ts@@ -0,0 +1,158 @@+import type { EdgePath } from './model';++export const EDGE_LANE_GAP = 14;+/** Minimum vertical gap kept between two label boxes before they count as clear. */+export const EDGE_LABEL_SLOT = 8;+/** Vertical slots a label may try before it is treated as crowded and hidden. */+const MAX_LABEL_SLOTS = 4;+const LANE_MARGIN = 4;++type Spreadable = EdgePath & { id: string };++export interface EdgeLabelBox {+ h: number;+ w: number;+}++export interface SpreadEdgesOptions<T extends Spreadable> {+ /** Size of the label that renders at `edge.lx` / `edge.ly`. */+ labelBox: (edge: T) => EdgeLabelBox;+ labelled: (edge: T) => boolean;+ /** Boards a label must not sit on. */+ obstacles?: readonly Box[];+}++export interface SpreadEdgesResult<T extends Spreadable> {+ edges: T[];+ /**+ * Labels whose box could not be cleared from every other label. Rendering+ * keeps them to hover/selection so the overview stays readable.+ */+ hiddenLabels: Set<string>;+}++const corridorOf = (edge: EdgePath) => {+ const [, a, b] = edge.points;+ return a[0] === b[0] && a[1] !== b[1]+ ? { max: Math.max(a[1], b[1]), min: Math.min(a[1], b[1]), x: a[0] }+ : undefined;+};++const centred = (index: number, count: number, step: number) => (index - (count - 1) / 2) * step;++const toLane = <T extends Spreadable>(edge: T, x: number): T => {+ const [start, a, b, end] = edge.points;+ return {+ ...edge,+ d: `M${start[0]} ${start[1]} H${x} V${b[1]} H${end[0]}`,+ lx: x,+ points: [start, [x, a[1]], [x, b[1]], end],+ };+};++const splitLanes = <T extends Spreadable>(edges: T[]): T[] => {+ const byX = new Map<number, T[]>();+ for (const edge of edges) {+ const corridor = corridorOf(edge);+ if (corridor) byX.set(corridor.x, [...(byX.get(corridor.x) ?? []), edge]);+ }++ const moved = new Map<string, T>();+ for (const sharing of byX.values()) {+ const sorted = sharing.toSorted((p, q) => corridorOf(p)!.min - corridorOf(q)!.min);+ const bundles: T[][] = [];+ let reach = -Infinity;+ for (const edge of sorted) {+ const { max, min } = corridorOf(edge)!;+ if (min < reach) bundles.at(-1)!.push(edge);+ else bundles.push([edge]);+ reach = Math.max(reach, max);+ }++ for (const bundle of bundles) {+ if (bundle.length < 2) continue;+ const room = Math.min(...bundle.map((e) => e.room));+ const step = Math.max(+ 0,+ Math.min(EDGE_LANE_GAP, (room - LANE_MARGIN * 2) / (bundle.length - 1)),+ );+ bundle+ .toSorted((p, q) => p.points[0][1] - q.points[0][1] || p.id.localeCompare(q.id))+ .forEach((edge, index) => {+ moved.set(edge.id, toLane(edge, edge.points[1][0] + centred(index, bundle.length, step)));+ });+ }+ }++ return edges.map((edge) => moved.get(edge.id) ?? edge);+};++interface Box {+ h: number;+ w: number;+ x: number;+ y: number;+}++const overlaps = (a: Box, b: Box, gap: number) =>+ a.x < b.x + b.w + gap && b.x < a.x + a.w + gap && a.y < b.y + b.h + gap && b.y < a.y + a.h + gap;++/**+ * Width-aware label placement. Labels are anchored at their edge midpoint, so a+ * long label on a near-parallel edge used to run straight through its+ * neighbour: the old centre-distance heuristic never saw the glyphs. Here every+ * label is treated as a box the size it actually renders, and the first clear+ * vertical slot wins (0, +1, −1, +2, −2 …). A label with no clear slot within+ * {@link MAX_LABEL_SLOTS} is reported as crowded instead of being drawn on top+ * of another one.+ */+const placeLabels = <T extends Spreadable>(+ edges: T[],+ { labelBox, labelled, obstacles = [] }: SpreadEdgesOptions<T>,+): { edges: T[]; hiddenLabels: Set<string> } => {+ const hiddenLabels = new Set<string>();+ const placed: Box[] = [];+ const moved = new Map<string, T>();++ const sorted = edges+ .filter(labelled)+ .toSorted((p, q) => p.ly - q.ly || p.lx - q.lx || p.id.localeCompare(q.id));++ for (const edge of sorted) {+ const size = labelBox(edge);+ if (size.w <= 0 || size.h <= 0) continue;++ const step = size.h + EDGE_LABEL_SLOT;+ const slots = [0];+ for (let slot = 1; slot <= MAX_LABEL_SLOTS; slot += 1) slots.push(slot, -slot);++ const dy = slots+ .map((slot) => slot * step)+ .find((offset) => {+ const candidate = {+ h: size.h,+ w: size.w,+ x: edge.lx - size.w / 2,+ y: edge.ly + offset - size.h / 2,+ };+ const clear =+ placed.every((other) => !overlaps(candidate, other, EDGE_LABEL_SLOT)) &&+ obstacles.every((board) => !overlaps(candidate, board, 0));+ if (clear) placed.push(candidate);+ return clear;+ });++ if (dy === undefined) {+ hiddenLabels.add(edge.id);+ continue;+ }+ if (dy !== 0) moved.set(edge.id, { ...edge, ly: edge.ly + dy });+ }++ return { edges: edges.map((edge) => moved.get(edge.id) ?? edge), hiddenLabels };+};++export const spreadEdges = <T extends Spreadable>(+ edges: T[],+ options: SpreadEdgesOptions<T>,+): SpreadEdgesResult<T> => placeLabels(splitLanes(edges), options);diff --git a/src/features/Artboard/index.ts b/src/features/Artboard/index.tsnew file mode 100644index 00000000000..27979718382--- /dev/null+++ b/src/features/Artboard/index.ts@@ -0,0 +1,2 @@+export { useArtboardFeature } from './useArtboardFeature';+export { useRegisterArtboardTool } from './useRegisterArtboardTool';diff --git a/src/features/Artboard/loadArtboardTool.ts b/src/features/Artboard/loadArtboardTool.tsnew file mode 100644index 00000000000..25579e30abc--- /dev/null+++ b/src/features/Artboard/loadArtboardTool.ts@@ -0,0 +1,4 @@+let loading: Promise<void> | undefined;++export const loadArtboardTool = () =>+ (loading ??= import('./Conversation/register').then((m) => m.registerArtboardTool()));diff --git a/src/features/Artboard/model.test.ts b/src/features/Artboard/model.test.tsnew file mode 100644index 00000000000..9cbb6c050d3--- /dev/null+++ b/src/features/Artboard/model.test.ts@@ -0,0 +1,356 @@+import type {+ ArtboardBoardView,+ ArtboardContent,+ ArtboardEdgeView,+ ArtboardItem,+} from '@lobechat/types';+import { describe, expect, it } from 'vitest';++import { boardFileUrl, buildBoardModel, computeEdgePath } from './model';++const rect = (x: number, y: number, w = 640, h = 400) => ({ h, w, x, y });++describe('computeEdgePath', () => {+ it('leaves the right edge and enters the left edge when the target is to the right', () => {+ expect(computeEdgePath(rect(0, 0), rect(840, 0))).toEqual({+ d: 'M640 200 H740 V200 H840',+ lx: 740,+ ly: 200,+ room: 200,+ points: [+ [640, 200],+ [740, 200],+ [740, 200],+ [840, 200],+ ],+ });+ });++ it('runs right to left when the target is to the left', () => {+ expect(computeEdgePath(rect(1680, 0), rect(840, 0))).toEqual({+ d: 'M1680 200 H1580 V200 H1480',+ lx: 1580,+ ly: 200,+ room: 200,+ points: [+ [1680, 200],+ [1580, 200],+ [1580, 200],+ [1480, 200],+ ],+ });+ });++ it('goes vertical when the boards overlap horizontally', () => {+ expect(computeEdgePath(rect(0, 0), rect(100, 600))).toEqual({+ d: 'M320 400 V500 H420 V600',+ lx: 370,+ ly: 500,+ room: 640,+ points: [+ [320, 400],+ [320, 500],+ [420, 500],+ [420, 600],+ ],+ });+ });++ it('anchors on each board’s own size', () => {+ expect(computeEdgePath(rect(0, 0, 200, 100), rect(400, 0, 300, 300))).toEqual({+ d: 'M200 50 H300 V150 H400',+ lx: 300,+ ly: 100,+ room: 200,+ points: [+ [200, 50],+ [300, 50],+ [300, 150],+ [400, 150],+ ],+ });+ });++ const crosses = (points: [number, number][], r: ReturnType<typeof rect>) =>+ points.slice(1).some(([bx, by], i) => {+ const [ax, ay] = points[i];+ if (ay === by)+ return ay > r.y && ay < r.y + r.h && Math.min(ax, bx) < r.x + r.w && Math.max(ax, bx) > r.x;+ return ax > r.x && ax < r.x + r.w && Math.min(ay, by) < r.y + r.h && Math.max(ay, by) > r.y;+ });++ it('goes around a board that sits between two boards in a row', () => {+ const from = rect(0, 100, 260, 160);+ const between = rect(400, 0);+ const to = rect(1200, 0);++ const path = computeEdgePath(from, to, [from, between, to]);++ expect(crosses(path.points, between)).toBe(false);+ expect(path.points[0]).toEqual([130, 260]);+ expect(path.points.at(-1)).toEqual([1520, 400]);+ expect(path.ly).toBeGreaterThan(400);+ });++ it('goes around a board that sits between two stacked boards', () => {+ const from = rect(0, 0);+ const between = rect(0, 600);+ const to = rect(0, 1200);++ const path = computeEdgePath(from, to, [from, between, to]);++ expect(crosses(path.points, between)).toBe(false);+ expect(path.lx).toBeGreaterThan(640);+ });++ it('keeps the direct route when nothing is in the way', () => {+ expect(+ computeEdgePath(rect(0, 0), rect(840, 0), [rect(0, 0), rect(840, 0), rect(0, 900)]),+ ).toEqual(computeEdgePath(rect(0, 0), rect(840, 0)));+ });+});++const board = (id: string, patch: Partial<ArtboardBoardView> = {}): ArtboardBoardView => ({+ expected: null,+ flowNodeId: null,+ groupId: 'g2',+ id,+ pageId: 'p1',+ rect: rect(0, 0),+ roundId: null,+ source: { hash: 'h1', kind: 'file', path: 'pages/b.html' },+ title: id,+ type: 'html',+ ...patch,+});++const edge = (id: string, from: string, to: string): ArtboardEdgeView => ({+ condition: null,+ flowEdgeId: null,+ from,+ id,+ isDefault: false,+ label: id,+ to,+});++const content: ArtboardContent = {+ boards: [+ board('b1', { expected: '能看到入口' }),+ board('b2', { rect: rect(840, 0), source: { fileId: 'file_1', kind: 'image' } }),+ board('b3', { groupId: 'g1', rect: rect(0, 1000), roundId: 'r1' }),+ board('b4', { groupId: null, pageId: 'p2', rect: rect(9000, 9000) }),+ ],+ edges: [edge('e1', 'b1', 'b2'), edge('e2', 'b1', 'gone'), edge('e3', 'b1', 'b4')],+ groups: [+ {+ desc: '',+ id: 'g1',+ kind: 'options',+ pageId: 'p1',+ rect: rect(-48, 856, 736, 592),+ title: '方案',+ },+ {+ desc: '',+ id: 'g2',+ kind: 'journey',+ pageId: 'p1',+ rect: rect(-48, -144, 1576, 592),+ title: '旅程',+ },+ {+ desc: '',+ id: 'g3',+ kind: 'references',+ pageId: 'p2',+ rect: rect(0, 0, 10, 10),+ title: '参考',+ },+ ],+ pages: [+ { id: 'p1', name: 'Page 1', sortOrder: 0 },+ { id: 'p2', name: 'Page 2', sortOrder: 1 },+ ],+ questions: [+ {+ answered: false,+ boardId: 'b1',+ content: '要保留吗?',+ groupId: null,+ id: 'c1',+ pageId: 'p1',+ },+ {+ answered: true,+ boardId: 'b1',+ content: '要加按钮吗?',+ groupId: null,+ id: 'c2',+ pageId: 'p1',+ },+ ],+ rounds: [+ {+ batchId: null,+ chosenBoardId: null,+ id: 'r1',+ pageId: 'p1',+ recommendedBoardId: 'b3',+ status: 'open',+ title: '布局',+ },+ {+ batchId: null,+ chosenBoardId: 'b3',+ id: 'r2',+ pageId: 'p1',+ recommendedBoardId: null,+ status: 'submitted',+ title: '配色',+ },+ ],+};++const item = {+ acceptanceId: null,+ content,+ id: 'art_1',+ phase: 'discuss',+ revision: 3,+ taskId: 'task_1',+ title: '首次进入',+} as ArtboardItem;++describe('buildBoardModel', () => {+ const model = buildBoardModel(item, '/artboard-files/tok/');++ it('shows the boards, groups and edges of the first page only', () => {+ expect(model.pageId).toBe('p1');+ expect(model.boards.map((b) => b.id)).toEqual(['b1', 'b2', 'b3']);+ expect(model.groups.map((g) => g.id)).toEqual(['g1', 'g2']);+ expect(model.edges.map((e) => e.id)).toEqual(['e1']);+ });++ it('still finds a board of another page by id', () => {+ expect(model.boardById.b4.pageId).toBe('p2');+ });++ it('finds the single journey, its boards, edges and entry', () => {+ expect(model.journeyGroupId).toBe('g2');+ expect(model.journeyBoards.map((b) => b.id)).toEqual(['b1', 'b2']);+ expect(model.journeyEdges.map((e) => e.id)).toEqual(['e1']);+ expect(model.journeyEntryId).toBe('b1');+ });++ it('has no journey when the board holds two', () => {+ const twice = buildBoardModel(+ {+ ...item,+ content: {+ ...content,+ groups: [...content.groups, { ...content.groups[1], id: 'g4', title: '另一条' }],+ },+ },+ {},+ );+ expect(twice.journeyGroupId).toBeUndefined();+ expect(twice.journeyBoards).toEqual([]);+ });++ it('lays an edge out between its two boards', () => {+ expect(model.edges[0]).toMatchObject({ d: 'M640 200 H740 V200 H840', lx: 740, ly: 200 });+ });++ it('marks the board a round recommends', () => {+ expect([...model.recommendedIds]).toEqual(['b3']);+ });++ it('lists open rounds and unanswered agent questions as what blocks finalizing', () => {+ expect(model.blockers).toEqual([+ { groupId: 'g1', id: 'r1', kind: 'round', pageId: 'p1', text: '布局' },+ {+ answered: false,+ boardId: 'b1',+ id: 'c1',+ kind: 'question',+ pageId: 'p1',+ text: '要保留吗?',+ },+ {+ answered: true,+ boardId: 'b1',+ id: 'c2',+ kind: 'question',+ pageId: 'p1',+ text: '要加按钮吗?',+ },+ ]);+ });++ it('shows another page when asked, and falls back to the first for an unknown one', () => {+ const second = buildBoardModel(item, null, 'p2');+ expect(second.pageId).toBe('p2');+ expect(second.boards.map((b) => b.id)).toEqual(['b4']);+ expect(second.groups.map((g) => g.id)).toEqual(['g3']);+ expect(second.pages.map((p) => p.name)).toEqual(['Page 1', 'Page 2']);+ expect(buildBoardModel(item, null, 'gone').pageId).toBe('p1');+ });++ it('knows the page of any board, group or round, whatever page is shown', () => {+ expect(model.pageIdOf('b4')).toBe('p2');+ expect(model.pageIdOf('g3')).toBe('p2');+ expect(model.pageIdOf('r1')).toBe('p1');+ expect(model.pageIdOf('nope')).toBeUndefined();+ });++ it('ties an options group to its round and lists the rounds still open', () => {+ expect(model.roundByGroupId.g1.id).toBe('r1');+ expect(model.roundByGroupId.g2).toBeUndefined();+ expect(model.openRounds.map((r) => r.id)).toEqual(['r1']);+ });++ it('bounds the groups and the boards outside any group on the page', () => {+ expect(model.bounds).toEqual({ maxX: 1528, maxY: 1448, minX: -48, minY: -144 });+ const loose = buildBoardModel(+ {+ ...item,+ content: {+ ...content,+ boards: [board('x', { groupId: null, rect: rect(3000, 0, 100, 50) })],+ },+ },+ {},+ );+ expect(loose.bounds.maxX).toBe(3100);+ });+});++describe('boardFileUrl', () => {+ it('joins the base URL and the encoded path of the file a board shows', () => {+ const model = buildBoardModel(item, '/artboard-files/tok/');++ expect(+ boardFileUrl(+ model,+ board('x', { source: { hash: '0123456789abcdef', kind: 'file', path: 'shots/[email protected]' } }),+ ),+ ).toBe('/artboard-files/tok/shots/a%402x.png?v=0123456789ab');+ });++ it('has no URL without a base URL or a source', () => {+ expect(boardFileUrl(buildBoardModel(item, null), board('x'))).toBeUndefined();+ expect(+ boardFileUrl(buildBoardModel(item, '/artboard-files/tok/'), board('x', { source: null })),+ ).toBeUndefined();+ });++ it('has no URL for a board whose file does not exist yet', () => {+ expect(+ boardFileUrl(+ buildBoardModel(item, '/artboard-files/tok/'),+ board('x', { source: { hash: null, kind: 'file', path: 'pages/a.html' } }),+ ),+ ).toBeUndefined();+ });+});diff --git a/src/features/Artboard/model.ts b/src/features/Artboard/model.tsnew file mode 100644index 00000000000..25ec98b5d38--- /dev/null+++ b/src/features/Artboard/model.ts@@ -0,0 +1,329 @@+import {+ ARTBOARD_BOARD_SIZE,+ type ArtboardBoardView,+ type ArtboardEdgeView,+ type ArtboardGroupView,+ type ArtboardItem,+ artboardJourneyOf,+ type ArtboardPageView,+ type ArtboardRect,+ type ArtboardRoundView,+} from '@lobechat/types';++import {+ EDGE_LABEL_HEIGHT,+ EDGE_LABEL_MAX_WIDTH,+ edgeLabelText,+ edgeLabelWidth,+} from './Canvas/edgeLabel';+import { spreadEdges } from './edgeSpread';++export interface Rect {+ maxX: number;+ maxY: number;+ minX: number;+ minY: number;+}++export interface EdgePath {+ d: string;+ lx: number;+ ly: number;+ points: [number, number][];+ room: number;+}++export type BoardEdge = ArtboardEdgeView &+ EdgePath & {+ /** Layout found no free slot at this zoom: only hover/selection reveals it. */+ labelHidden?: boolean;+ };++export type BoardBlocker =+ | { groupId: string | null; id: string; kind: 'round'; pageId: string; text: string }+ | {+ answered: boolean;+ boardId: string | null;+ id: string;+ kind: 'question';+ pageId: string | null;+ text: string;+ };++export interface BoardModel {+ artboard: ArtboardItem;+ blockers: BoardBlocker[];+ boardById: Record<string, ArtboardBoardView>;+ boards: ArtboardBoardView[];+ bounds: Rect;+ edges: BoardEdge[];+ fileBaseUrl: string | null;+ finalized: boolean;+ groups: ArtboardGroupView[];+ journeyBoards: ArtboardBoardView[];+ journeyEdges: ArtboardEdgeView[];+ journeyEntryId: string | undefined;+ journeyGroupId: string | undefined;+ openRounds: ArtboardRoundView[];+ pageId: string | undefined;+ pageIdOf: (id: string) => string | undefined;+ pages: ArtboardPageView[];+ recommendedIds: Set<string>;+ roundByGroupId: Record<string, ArtboardRoundView>;+}++const DETOUR_GAP = 40;++type Point = [number, number];++const segmentHits = ([ax, ay]: Point, [bx, by]: Point, r: ArtboardRect) =>+ ay === by+ ? ay > r.y && ay < r.y + r.h && Math.min(ax, bx) < r.x + r.w && Math.max(ax, bx) > r.x+ : ax > r.x && ax < r.x + r.w && Math.min(ay, by) < r.y + r.h && Math.max(ay, by) > r.y;++const crossing = (points: Point[], rects: ArtboardRect[]) =>+ rects.filter((r) => points.slice(1).some((point, i) => segmentHits(points[i], point, r)));++const aroundBelowOrAbove = (from: ArtboardRect, to: ArtboardRect, blocking: ArtboardRect[]) => {+ const x1 = from.x + from.w / 2;+ const x2 = to.x + to.w / 2;+ const below = Math.max(...[from, to, ...blocking].map((r) => r.y + r.h)) + DETOUR_GAP;+ const above = Math.min(...[from, to, ...blocking].map((r) => r.y)) - DETOUR_GAP;+ return [+ [from.y + from.h, below, to.y + to.h],+ [from.y, above, to.y],+ ].map(([y1, y, y2]): EdgePath => ({+ d: `M${x1} ${y1} V${y} H${x2} V${y2}`,+ lx: (x1 + x2) / 2,+ ly: y,+ points: [+ [x1, y1],+ [x1, y],+ [x2, y],+ [x2, y2],+ ],+ room: Math.abs(x2 - x1),+ }));+};++const aroundRightOrLeft = (from: ArtboardRect, to: ArtboardRect, blocking: ArtboardRect[]) => {+ const y1 = from.y + from.h / 2;+ const y2 = to.y + to.h / 2;+ const right = Math.max(...[from, to, ...blocking].map((r) => r.x + r.w)) + DETOUR_GAP;+ const left = Math.min(...[from, to, ...blocking].map((r) => r.x)) - DETOUR_GAP;+ return [+ [from.x + from.w, right, to.x + to.w],+ [from.x, left, to.x],+ ].map(([x1, x, x2]): EdgePath => ({+ d: `M${x1} ${y1} H${x} V${y2} H${x2}`,+ lx: x,+ ly: (y1 + y2) / 2,+ points: [+ [x1, y1],+ [x, y1],+ [x, y2],+ [x2, y2],+ ],+ room: DETOUR_GAP * 2,+ }));+};++const sameRect = (a: ArtboardRect, b: ArtboardRect) =>+ a.x === b.x && a.y === b.y && a.w === b.w && a.h === b.h;++export const computeEdgePath = (+ from: ArtboardRect,+ to: ArtboardRect,+ obstacles: ArtboardRect[] = [],+): EdgePath => {+ const direct = directEdgePath(from, to);+ const others = obstacles.filter((r) => !sameRect(r, from) && !sameRect(r, to));+ const blocking = crossing(direct.points, others);+ if (!blocking.length) return direct;++ const sideBySide = to.x >= from.x + from.w || to.x + to.w <= from.x;+ const detours = (sideBySide ? aroundBelowOrAbove : aroundRightOrLeft)(from, to, blocking);+ // Below before above: board titles sit on top of each board.+ return detours.find((path) => !crossing(path.points, others).length) ?? direct;+};++const directEdgePath = (from: ArtboardRect, to: ArtboardRect): EdgePath => {+ const right = to.x >= from.x + from.w;+ const left = to.x + to.w <= from.x;++ if (right || left) {+ const x1 = right ? from.x + from.w : from.x;+ const x2 = right ? to.x : to.x + to.w;+ const y1 = from.y + from.h / 2;+ const y2 = to.y + to.h / 2;+ const mx = (x1 + x2) / 2;+ return {+ d: `M${x1} ${y1} H${mx} V${y2} H${x2}`,+ lx: mx,+ ly: (y1 + y2) / 2,+ points: [+ [x1, y1],+ [mx, y1],+ [mx, y2],+ [x2, y2],+ ],+ room: Math.abs(x2 - x1),+ };+ }++ const down = to.y >= from.y;+ const x1 = from.x + from.w / 2;+ const x2 = to.x + to.w / 2;+ const y1 = down ? from.y + from.h : from.y;+ const y2 = down ? to.y : to.y + to.h;+ const my = (y1 + y2) / 2;+ return {+ d: `M${x1} ${y1} V${my} H${x2} V${y2}`,+ lx: (x1 + x2) / 2,+ ly: my,+ points: [+ [x1, y1],+ [x1, my],+ [x2, my],+ [x2, y2],+ ],+ room: Math.min(from.w, to.w),+ };+};++export const toBounds = (rect: ArtboardRect): Rect => ({+ maxX: rect.x + rect.w,+ maxY: rect.y + rect.h,+ minX: rect.x,+ minY: rect.y,+});++const EMPTY_BOUNDS: Rect = {+ maxX: ARTBOARD_BOARD_SIZE.width,+ maxY: ARTBOARD_BOARD_SIZE.height,+ minX: 0,+ minY: 0,+};++const union = (rects: Rect[]): Rect =>+ rects.length+ ? {+ maxX: Math.max(...rects.map((r) => r.maxX)),+ maxY: Math.max(...rects.map((r) => r.maxY)),+ minX: Math.min(...rects.map((r) => r.minX)),+ minY: Math.min(...rects.map((r) => r.minY)),+ }+ : EMPTY_BOUNDS;++export const boardFileUrl = (+ model: Pick<BoardModel, 'fileBaseUrl'>,+ board: Pick<ArtboardBoardView, 'source'>,+): string | undefined =>+ model.fileBaseUrl && board.source?.hash+ ? `${model.fileBaseUrl}${board.source.path.split('/').map(encodeURIComponent).join('/')}?v=${board.source.hash.slice(0, 12)}`+ : undefined;++export const buildBoardModel = (+ artboard: ArtboardItem,+ fileBaseUrl: string | null,+ requestedPageId?: string | null,+): BoardModel => {+ const { content } = artboard;+ const pageId = (content.pages.find((p) => p.id === requestedPageId) ?? content.pages[0])?.id;+ const boardById = Object.fromEntries(content.boards.map((b) => [b.id, b]));++ const boards = content.boards.filter((b) => b.pageId === pageId);+ const groups = content.groups.filter((g) => g.pageId === pageId);+ const onPage = new Set(boards.map((b) => b.id));+ const spread = spreadEdges(+ content.edges.flatMap((edge) =>+ onPage.has(edge.from) && onPage.has(edge.to)+ ? [+ {+ ...edge,+ ...computeEdgePath(+ boardById[edge.from].rect,+ boardById[edge.to].rect,+ boards.map((b) => b.rect),+ ),+ },+ ]+ : [],+ ),+ {+ labelBox: (edge) => ({+ h: EDGE_LABEL_HEIGHT,+ w: Math.min(edgeLabelWidth(edgeLabelText(edge)), Math.min(edge.room, EDGE_LABEL_MAX_WIDTH)),+ }),+ labelled: (edge) => !!(edge.label || edge.condition),+ obstacles: boards.map((b) => b.rect),+ },+ );+ const edges: BoardEdge[] = spread.edges.map((edge) =>+ spread.hiddenLabels.has(edge.id) ? { ...edge, labelHidden: true } : edge,+ );++ const journey = artboardJourneyOf(content);+ const journeyBoards = journey.boards ?? [];+ const journeyEdges = journey.edges ?? [];+ const targets = new Set(journeyEdges.map((e) => e.to));+ const entries = journeyBoards.filter((b) => !targets.has(b.id));++ const roundById = Object.fromEntries(content.rounds.map((r) => [r.id, r]));+ const roundByGroupId: Record<string, ArtboardRoundView> = {};+ const groupIdByRound: Record<string, string> = {};+ for (const b of content.boards) {+ if (!b.roundId || !b.groupId || !roundById[b.roundId]) continue;+ roundByGroupId[b.groupId] = roundById[b.roundId];+ groupIdByRound[b.roundId] = b.groupId;+ }+ const openRounds = content.rounds.filter((round) => round.status === 'open');+ const pageIds = new Map<string, string>(+ [...content.boards, ...content.groups, ...content.rounds].map((x) => [x.id, x.pageId]),+ );++ return {+ artboard,+ blockers: [+ ...openRounds.map((round) => ({+ groupId: groupIdByRound[round.id] ?? null,+ id: round.id,+ kind: 'round' as const,+ pageId: round.pageId,+ text: round.title,+ })),+ ...content.questions.map((question) => ({+ answered: question.answered,+ boardId: question.boardId,+ id: question.id,+ kind: 'question' as const,+ pageId: question.pageId,+ text: question.content,+ })),+ ],+ boardById,+ boards,+ bounds: union([+ ...groups.map((g) => toBounds(g.rect)),+ ...boards.filter((b) => !b.groupId).map((b) => toBounds(b.rect)),+ ]),+ edges,+ finalized: artboard.phase === 'finalized',+ fileBaseUrl,+ groups,+ journeyBoards,+ journeyEdges,+ journeyEntryId: entries.length === 1 ? entries[0].id : undefined,+ journeyGroupId: journey.group?.id,+ openRounds,+ pageId,+ pageIdOf: (id) => pageIds.get(id),+ pages: content.pages,+ recommendedIds: new Set(+ content.rounds.flatMap((round) =>+ round.recommendedBoardId ? [round.recommendedBoardId] : [],+ ),+ ),+ roundByGroupId,+ };+};diff --git a/src/features/Artboard/openArtboard.test.ts b/src/features/Artboard/openArtboard.test.tsnew file mode 100644index 00000000000..8d7f8ffdac7--- /dev/null+++ b/src/features/Artboard/openArtboard.test.ts@@ -0,0 +1,62 @@+import { afterEach, describe, expect, it, vi } from 'vitest';++import { artboardOpensInPanel, openArtboard } from './openArtboard';++const mocks = vi.hoisted(() => ({+ fullscreen: vi.fn(),+ get: vi.fn(),+ panel: vi.fn(),+}));++vi.mock('@/features/Artboard/Gallery/loader', () => ({ openArtboardFullscreen: mocks.fullscreen }));+vi.mock('@/services/artboard', () => ({ artboardService: { get: mocks.get } }));+vi.mock('./Conversation/openBoardPanel', () => ({ openBoardPanel: mocks.panel }));+vi.mock('./data/useArtboard', () => ({ mutateArtboard: vi.fn() }));+vi.mock('./loadArtboardTool', () => ({ loadArtboardTool: vi.fn() }));+vi.mock('./useArtboardFeature', () => ({ isArtboardEnabled: () => true }));++afterEach(() => {+ vi.clearAllMocks();+ window.history.replaceState(null, '', '/');+});++it('reaches the gallery through the specifier the Share build stubs', async () => {+ const source = await import('./openArtboard?raw');+ expect(source.default).toContain("from '@/features/Artboard/Gallery/loader'");+});++describe('artboardOpensInPanel', () => {+ it('uses the side panel inside the conversation the artboard belongs to', () => {+ expect(artboardOpensInPanel('/project/prj_1/topic/tpc_1', 'tpc_1')).toBe(true);+ expect(artboardOpensInPanel('/acme/project/prj_1/topic/tpc_1', 'tpc_1')).toBe(true);+ });++ it('uses the modal anywhere else', () => {+ expect(artboardOpensInPanel('/project/prj_1/topic/tpc_2', 'tpc_1')).toBe(false);+ expect(artboardOpensInPanel('/project/prj_1/topic/tpc_10', 'tpc_1')).toBe(false);+ expect(artboardOpensInPanel('/project/prj_1', 'tpc_1')).toBe(false);+ expect(artboardOpensInPanel('/project/prj_1/topic/tpc_1', null)).toBe(false);+ });+});++describe('openArtboard', () => {+ it('opens the side panel inside an agent conversation the artboard belongs to', async () => {+ window.history.replaceState(null, '', '/agent/agt_1/tpc_1');+ mocks.get.mockResolvedValue({ artboard: { id: 'art_1', topicId: 'tpc_1' } });++ await openArtboard('art_1');++ expect(mocks.panel).toHaveBeenCalledWith('art_1');+ expect(mocks.fullscreen).not.toHaveBeenCalled();+ });++ it('opens fullscreen from another conversation', async () => {+ window.history.replaceState(null, '', '/agent/agt_1/tpc_2');+ mocks.get.mockResolvedValue({ artboard: { id: 'art_1', topicId: 'tpc_1' } });++ await openArtboard('art_1');++ expect(mocks.fullscreen).toHaveBeenCalledWith('art_1');+ expect(mocks.panel).not.toHaveBeenCalled();+ });+});diff --git a/src/features/Artboard/openArtboard.ts b/src/features/Artboard/openArtboard.tsnew file mode 100644index 00000000000..60a84cb28c6--- /dev/null+++ b/src/features/Artboard/openArtboard.ts@@ -0,0 +1,33 @@+// The Share build stubs this specifier; a relative path would bypass the stub.+import { openArtboardFullscreen } from '@/features/Artboard/Gallery/loader';+import { artboardService } from '@/services/artboard';++import { openBoardPanel } from './Conversation/openBoardPanel';+import { mutateArtboard } from './data/useArtboard';+import { loadArtboardTool } from './loadArtboardTool';+import { isArtboardEnabled } from './useArtboardFeature';++export const artboardOpensInPanel = (pathname: string, topicId: string | null | undefined) =>+ !!topicId && pathname.split('/').includes(topicId);++// Every conversation route ends in its topic id (`/agent/:aid/:topicId`,+// `/project/:pid/topic/:topicId`, …); `artboardOpensInPanel` matches it, so+// no route shape is assumed here.+const conversationTopicOf = async (artboardId: string) => {+ try {+ const view = await artboardService.get(artboardId);+ void mutateArtboard(artboardId, view);+ return view.artboard.topicId;+ } catch {+ return null;+ }+};++export const openArtboard = async (artboardId: string) => {+ if (!isArtboardEnabled()) return;+ const topicId = await conversationTopicOf(artboardId);+ if (!artboardOpensInPanel(window.location.pathname, topicId))+ return openArtboardFullscreen(artboardId);+ await loadArtboardTool();+ openBoardPanel(artboardId);+};diff --git a/src/features/Artboard/store/action.test.ts b/src/features/Artboard/store/action.test.tsnew file mode 100644index 00000000000..0011c9f69ff--- /dev/null+++ b/src/features/Artboard/store/action.test.ts@@ -0,0 +1,174 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { artboardActions } from './action';+import { useArtboardStore } from './store';++describe('artboardActions', () => {+ beforeEach(() => {+ vi.useFakeTimers();+ });++ afterEach(() => {+ artboardActions.reset();+ vi.useRealTimers();+ });++ it('closes the side panels again when a narrow board is revisited', () => {+ artboardActions.setNarrow(true);+ artboardActions.reset();+ expect(useArtboardStore.getState().verifyOpen).toBe(true);++ artboardActions.setNarrow(true);++ expect(useArtboardStore.getState()).toMatchObject({ outlineOpen: false, verifyOpen: false });+ });++ it('forgets the remembered page of a board opened from a link', () => {+ artboardActions.bindBoard('art_1');+ artboardActions.setPage('p2');+ artboardActions.bindBoard('art_2');++ artboardActions.forgetPage('art_1');+ artboardActions.bindBoard('art_1');++ expect(useArtboardStore.getState().pageId).toBeNull();+ });++ it('drops the selection and mode of the previous board when another board opens', () => {+ artboardActions.bindBoard('art_1');+ artboardActions.setMode('verify');+ artboardActions.select('f1');++ artboardActions.bindBoard('art_1');+ expect(useArtboardStore.getState()).toMatchObject({ mode: 'verify', selected: 'f1' });++ artboardActions.bindBoard('art_2');+ expect(useArtboardStore.getState()).toMatchObject({+ boardId: 'art_2',+ mode: 'discuss',+ selected: null,+ });+ });++ it('flashes the changed items and then clears them', () => {+ artboardActions.flashItems(['f1', 'f2']);+ expect(useArtboardStore.getState().flash).toEqual(['f1', 'f2']);++ vi.advanceTimersByTime(1700);++ expect(useArtboardStore.getState().flash).toEqual([]);+ });++ it('aims the camera at the journey when acceptance opens', () => {+ artboardActions.setNarrow(false);+ artboardActions.setVerifyOpen(false);++ artboardActions.setMode('verify');++ expect(useArtboardStore.getState()).toMatchObject({+ camera: { kind: 'journey' },+ mode: 'verify',+ verifyOpen: true,+ });+ });++ it('keeps the acceptance sheet closed on a narrow board so the flow stays visible', () => {+ artboardActions.setNarrow(true);++ artboardActions.setMode('verify');++ expect(useArtboardStore.getState()).toMatchObject({ mode: 'verify', verifyOpen: false });+ });+ it('remembers the page of each board for the session', () => {+ artboardActions.bindBoard('art_1');+ artboardActions.setPage('p2');+ artboardActions.bindBoard('art_2');+ expect(useArtboardStore.getState().pageId).toBeNull();++ artboardActions.bindBoard('art_1');++ expect(useArtboardStore.getState().pageId).toBe('p2');+ });++ it('switches page, selects and aims the camera when jumping to an item', () => {+ artboardActions.bindBoard('art_1');+ artboardActions.setMode('verify');++ artboardActions.goTo({ id: 'b4', kind: 'item', pageId: 'p2' });++ expect(useArtboardStore.getState()).toMatchObject({+ camera: { id: 'b4', kind: 'item' },+ mode: 'discuss',+ pageId: 'p2',+ selected: 'b4',+ });+ });++ it('closes the open thread and the selection when the page changes', () => {+ artboardActions.bindBoard('art_1');+ artboardActions.select('b1');+ artboardActions.openThread('t1');++ artboardActions.setPage('p2');++ expect(useArtboardStore.getState()).toMatchObject({ openThreadId: null, selected: null });+ });++ it('opens a thread on its page and aims the camera at its board', () => {+ artboardActions.bindBoard('art_1');++ artboardActions.showThread({ boardId: 'b4', id: 't9', pageId: 'p2' });++ expect(useArtboardStore.getState()).toMatchObject({+ camera: { id: 'b4', kind: 'item' },+ openThreadId: 't9',+ pageId: 'p2',+ });+ });++ it('drops the selection when the comment tool is picked', () => {+ artboardActions.bindBoard('art_1');+ artboardActions.select('b1');++ artboardActions.setTool('comment');++ expect(useArtboardStore.getState()).toMatchObject({ selected: null, tool: 'comment' });+ });++ it('keeps the Works flag while boards change', () => {+ artboardActions.setGallery(true);+ artboardActions.bindBoard('art_3');++ expect(useArtboardStore.getState().gallery).toBe(true);+ });+ it('keeps one of a new-comment draft or an open thread, and drops the draft with the tool', () => {+ const draft = { anchor: { type: 'canvas' as const, x: 1, y: 2 }, pageId: 'p1', x: 1, y: 2 };+ artboardActions.bindBoard('art_1');+ artboardActions.setTool('comment');+ artboardActions.openThread('t1');++ artboardActions.placeDraft(draft);+ expect(useArtboardStore.getState()).toMatchObject({ draft, openThreadId: null });++ artboardActions.openThread('t2');+ expect(useArtboardStore.getState()).toMatchObject({ draft: null, openThreadId: 't2' });++ artboardActions.placeDraft(draft);+ artboardActions.setTool('select');+ expect(useArtboardStore.getState().draft).toBeNull();+ });++ it('shows the next board as its screenshot again after another board is selected', () => {+ artboardActions.bindBoard('art_1');+ artboardActions.setMode('verify');+ artboardActions.select('b1');+ artboardActions.setCompare('split');++ artboardActions.select('b2');+ expect(useArtboardStore.getState()).toMatchObject({ compare: 'real', selected: 'b2' });++ artboardActions.setCompare('design');+ artboardActions.focusItem('b3');+ expect(useArtboardStore.getState().compare).toBe('real');+ });+});diff --git a/src/features/Artboard/store/action.ts b/src/features/Artboard/store/action.tsnew file mode 100644index 00000000000..fe7caabd93d--- /dev/null+++ b/src/features/Artboard/store/action.ts@@ -0,0 +1,163 @@+import type { StoreSetter } from '@/store/types';+import { setNamespace } from '@/utils/storeDebug';++import type { BoardMode, BoardTool, CameraTarget, CompareView, VerifyView } from '../types';+import { type ArtboardState, type CommentDraft, initialState } from './initialState';+import { useArtboardStore } from './store';++const n = setNamespace('artboard');++type Setter = StoreSetter<ArtboardState>;+type CameraRequest = { kind: 'all' } | { kind: 'journey' } | { id: string; kind: 'group' | 'item' };++const FLASH_MS = 1700;++export class ArtboardActionImpl {+ readonly #get: () => ArtboardState;+ readonly #set: Setter;+ #cameraSeq = 0;+ #flashTimer: ReturnType<typeof setTimeout> | undefined;+ #narrow = false;++ constructor(set: Setter, get: () => ArtboardState) {+ this.#set = set;+ this.#get = get;+ }++ bindBoard = (boardId: string) => {+ if (this.#get().boardId === boardId) return;+ clearTimeout(this.#flashTimer);+ this.#set(+ {+ ...initialState,+ boardId,+ gallery: this.#get().gallery,+ outlineOpen: false,+ pageByBoard: this.#get().pageByBoard,+ pageId: this.#get().pageByBoard[boardId] ?? null,+ verifyOpen: !this.#narrow,+ },+ false,+ n('bindBoard'),+ );+ };++ focus = (request: CameraRequest) => {+ this.#cameraSeq += 1;+ this.#set({ camera: { ...request, seq: this.#cameraSeq } as CameraTarget }, false, n('focus'));+ };++ focusItem = (id: string) => {+ this.#set({ compare: 'real', selected: id }, false, n('focusItem'));+ this.focus({ id, kind: 'item' });+ };++ flashItems = (ids: string[]) => {+ if (!ids.length) return;+ clearTimeout(this.#flashTimer);+ this.#set({ flash: ids }, false, n('flash'));+ this.#flashTimer = setTimeout(() => this.#set({ flash: [] }, false, n('flashDone')), FLASH_MS);+ };++ setGallery = (gallery: boolean) => this.#set({ gallery }, false, n('gallery'));++ setPage = (pageId: string) => {+ const { boardId, pageByBoard, pageId: current } = this.#get();+ if (pageId === current) return;+ this.#set(+ {+ draft: null,+ openThreadId: null,+ pageByBoard: boardId ? { ...pageByBoard, [boardId]: pageId } : pageByBoard,+ pageId,+ selected: null,+ },+ false,+ n('setPage'),+ );+ };++ forgetPage = (boardId: string) => {+ const { [boardId]: _, ...pageByBoard } = this.#get().pageByBoard;+ const bound = this.#get().boardId === boardId;+ this.#set({ pageByBoard, ...(bound ? { pageId: null } : {}) }, false, n('forgetPage'));+ };++ goTo = (target: { id: string; kind: 'group' | 'item'; pageId?: string | null }) => {+ if (this.#get().mode !== 'discuss') this.setMode('discuss');+ if (target.pageId) this.setPage(target.pageId);+ if (target.kind === 'item') return this.focusItem(target.id);+ this.focus({ id: target.id, kind: 'group' });+ };++ setTool = (tool: BoardTool) =>+ this.#set({ draft: null, selected: null, tool }, false, n('setTool'));++ placeDraft = (draft: CommentDraft | null) =>+ this.#set({ draft, openThreadId: null }, false, n('placeDraft'));++ openThread = (openThreadId: string | null) =>+ this.#set({ draft: null, openThreadId }, false, n('openThread'));++ showThread = (thread: { boardId: string | null; id: string; pageId: string | null }) => {+ if (this.#get().mode !== 'discuss') this.setMode('discuss');+ if (thread.pageId) this.setPage(thread.pageId);+ this.#set({ draft: null, openThreadId: thread.id, selected: null }, false, n('showThread'));+ if (thread.boardId) this.focus({ id: thread.boardId, kind: 'item' });+ };++ setFullscreen = (fullscreen: boolean) => this.#set({ fullscreen }, false, n('fullscreen'));++ setStaleRevision = (staleRevision: number | null) =>+ this.#set({ staleRevision }, false, n('staleRevision'));++ setNarrow = (narrow: boolean) => {+ if (narrow === this.#narrow) return;+ this.#narrow = narrow;+ this.#set(+ narrow ? { outlineOpen: false, verifyOpen: false } : { verifyOpen: true },+ false,+ n('narrow'),+ );+ };++ setVerifyOpen = (verifyOpen: boolean) => this.#set({ verifyOpen }, false, n('setVerifyOpen'));++ setOutlineOpen = (outlineOpen: boolean) => this.#set({ outlineOpen }, false, n('outline'));++ setVerifyView = (verifyView: VerifyView) => {+ this.#set({ verifyView }, false, n('setVerifyView'));+ if (verifyView === 'board') this.focus({ kind: 'journey' });+ };++ setCompare = (compare: CompareView) => this.#set({ compare }, false, n('setCompare'));++ select = (id: string | null) => {+ this.#set({ compare: 'real', selected: id }, false, n('select'));+ if (id && this.#get().mode === 'verify') this.setVerifyOpen(true);+ };++ setMode = (mode: BoardMode) => {+ this.#set(+ { draft: null, mode, openThreadId: null, selected: null, tool: 'select' },+ false,+ n('setMode'),+ );+ if (mode === 'verify') {+ this.#set({ outlineOpen: false, verifyOpen: !this.#narrow }, false, n('verifyEnter'));+ this.focus({ kind: 'journey' });+ } else {+ this.focus({ kind: 'all' });+ }+ };++ reset = () => {+ clearTimeout(this.#flashTimer);+ this.#narrow = false;+ this.#set({ ...initialState }, false, n('reset'));+ };+}++const { getState, setState } = useArtboardStore;++export const artboardActions = new ArtboardActionImpl(setState, getState);diff --git a/src/features/Artboard/store/index.ts b/src/features/Artboard/store/index.tsnew file mode 100644index 00000000000..9d2e9ba7e1f--- /dev/null+++ b/src/features/Artboard/store/index.ts@@ -0,0 +1,4 @@+export { artboardActions } from './action';+export { type ArtboardState } from './initialState';+export { artboardSelectors } from './selectors';+export { useArtboardStore } from './store';diff --git a/src/features/Artboard/store/initialState.ts b/src/features/Artboard/store/initialState.tsnew file mode 100644index 00000000000..9388d622286--- /dev/null+++ b/src/features/Artboard/store/initialState.ts@@ -0,0 +1,47 @@+import type { CommentTarget } from '../data/commentActions';+import type { BoardMode, BoardTool, CameraTarget, CompareView, VerifyView } from '../types';++export interface CommentDraft extends CommentTarget {+ x: number;+ y: number;+}++export interface ArtboardState {+ boardId: string | null;+ camera: CameraTarget | null;+ compare: CompareView;+ draft: CommentDraft | null;+ flash: string[];+ fullscreen: boolean;+ gallery: boolean;+ mode: BoardMode;+ openThreadId: string | null;+ outlineOpen: boolean;+ pageByBoard: Record<string, string>;+ pageId: string | null;+ selected: string | null;+ staleRevision: number | null;+ tool: BoardTool;+ verifyOpen: boolean;+ verifyView: VerifyView;+}++export const initialState: ArtboardState = {+ boardId: null,+ camera: null,+ compare: 'real',+ draft: null,+ flash: [],+ fullscreen: false,+ gallery: false,+ mode: 'discuss',+ openThreadId: null,+ outlineOpen: false,+ pageByBoard: {},+ pageId: null,+ selected: null,+ staleRevision: null,+ tool: 'select',+ verifyOpen: true,+ verifyView: 'board',+};diff --git a/src/features/Artboard/store/selectors.ts b/src/features/Artboard/store/selectors.tsnew file mode 100644index 00000000000..8d08910e57a--- /dev/null+++ b/src/features/Artboard/store/selectors.ts@@ -0,0 +1,12 @@+import type { BoardModel } from '../model';+import type { ArtboardState } from './initialState';++const inJourney = (board: BoardModel, id: string | null) =>+ !!id && !!board.journeyGroupId && board.boardById[id]?.groupId === board.journeyGroupId;++const selectedCheckBoard = (board: BoardModel) => (s: ArtboardState) =>+ inJourney(board, s.selected) ? s.selected : null;++export const artboardSelectors = {+ selectedCheckBoard,+};diff --git a/src/features/Artboard/store/store.ts b/src/features/Artboard/store/store.tsnew file mode 100644index 00000000000..625969df529--- /dev/null+++ b/src/features/Artboard/store/store.ts@@ -0,0 +1,13 @@+import { shallow } from 'zustand/shallow';+import { createWithEqualityFn } from 'zustand/traditional';++import { createDevtools } from '@/store/middleware/createDevtools';++import { type ArtboardState, initialState } from './initialState';++const devtools = createDevtools('artboard');++export const useArtboardStore = createWithEqualityFn<ArtboardState>()(+ devtools(() => initialState),+ shallow,+);diff --git a/src/features/Artboard/tokens.stylex.ts b/src/features/Artboard/tokens.stylex.tsnew file mode 100644index 00000000000..6c692ee526d--- /dev/null+++ b/src/features/Artboard/tokens.stylex.ts@@ -0,0 +1,16 @@+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';++export const artboardTokens = stylex.defineVars({+ accent: cssVar.volcano,+ accentStrong: cssVar.volcanoActive,+ agent: cssVar.volcanoActive,+ human: cssVar.colorInfo,+ overlayShadow: cssVar.boxShadowSecondary,+ resolved: cssVar.colorTextTertiary,+ resolvedText: cssVar.colorBgContainer,+ selection: cssVar.colorInfo,+ selectionFill: cssVar.colorInfoFillTertiary,+ selectionLine: cssVar.blue6A,+ stale: cssVar.colorWarning,+});diff --git a/src/features/Artboard/types.ts b/src/features/Artboard/types.tsnew file mode 100644index 00000000000..1aad9b94455--- /dev/null+++ b/src/features/Artboard/types.ts@@ -0,0 +1,9 @@+export type BoardMode = 'discuss' | 'verify';+export type VerifyView = 'board' | 'list';+export type BoardTool = 'comment' | 'select';+export type CompareView = 'design' | 'real' | 'split';++export type CameraTarget =+ | { kind: 'all'; seq: number }+ | { kind: 'journey'; seq: number }+ | { id: string; kind: 'group' | 'item'; seq: number };diff --git a/src/features/Artboard/useArtboardFeature.ts b/src/features/Artboard/useArtboardFeature.tsnew file mode 100644index 00000000000..8f31db61e90--- /dev/null+++ b/src/features/Artboard/useArtboardFeature.ts@@ -0,0 +1,16 @@+import {+ getServerConfigStoreState,+ serverConfigSelectors,+ useServerConfigStore,+} from '@/store/serverConfig';++export const isArtboardEnabled = () => {+ const config = getServerConfigStoreState();+ return !!config?.serverConfigInit && serverConfigSelectors.enableArtboard(config);+};++export const useArtboardFeature = () => {+ const ready = useServerConfigStore((s) => s.serverConfigInit);+ const enabled = useServerConfigStore(serverConfigSelectors.enableArtboard);+ return { enabled: ready && enabled, ready };+};diff --git a/src/features/Artboard/useOpenArtboardFromRoute.test.ts b/src/features/Artboard/useOpenArtboardFromRoute.test.tsnew file mode 100644index 00000000000..4c621f8f290--- /dev/null+++ b/src/features/Artboard/useOpenArtboardFromRoute.test.ts@@ -0,0 +1,116 @@+import { act, renderHook } from '@testing-library/react';+import { createElement, type ReactNode } from 'react';+import { MemoryRouter } from 'react-router';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import { useChatStore } from '@/store/chat';++import { ARTBOARD_TOOL } from './Conversation/tool';+import { useOpenArtboardFromRoute } from './useOpenArtboardFromRoute';++const openBoardPanel = vi.fn();+let resolveLoad: () => void = () => {};+const { board, feature } = vi.hoisted(() => ({+ board: { topicId: 't' },+ feature: { enabled: true, ready: true },+}));++vi.mock('./useArtboardFeature', () => ({+ useArtboardFeature: () => ({ enabled: feature.ready && feature.enabled, ready: feature.ready }),+}));++vi.mock('./data/useArtboard', () => ({ useArtboard: () => ({ data: { artboard: board } }) }));++vi.mock('./Conversation/openBoardPanel', () => ({+ openBoardPanel: (...args: unknown[]) => openBoardPanel(...args),+}));++vi.mock('./loadArtboardTool', () => ({+ loadArtboardTool: () =>+ new Promise<void>((resolve) => {+ resolveLoad = resolve;+ }),+}));++const wrapper = ({ children }: { children: ReactNode }) =>+ createElement(MemoryRouter, { initialEntries: ['/project/p/topic/t?artboard=art_1'] }, children);++beforeEach(() => {+ openBoardPanel.mockReset();+ Object.assign(feature, { enabled: true, ready: true });+ board.topicId = 't';+ useChatStore.setState({+ activeTopicId: 't',+ dbMessagesMap: {+ t: [+ {+ id: 'tool_1',+ plugin: { identifier: ARTBOARD_TOOL },+ pluginState: { artboardId: 'art_1' },+ },+ ],+ },+ } as never);+});++describe('useOpenArtboardFromRoute', () => {+ it('opens the board tab only after the artboard tool has loaded', async () => {+ renderHook(() => useOpenArtboardFromRoute(), { wrapper });++ expect(openBoardPanel).not.toHaveBeenCalled();++ await act(async () => resolveLoad());++ expect(openBoardPanel).toHaveBeenCalledWith('art_1');+ });++ it.each(['CLI-created board', 'creation message outside the loaded window'])(+ 'opens a %s by its authorized artboard id',+ async () => {+ useChatStore.setState({ dbMessagesMap: {} });+ renderHook(() => useOpenArtboardFromRoute(), { wrapper });++ await act(async () => resolveLoad());++ expect(openBoardPanel).toHaveBeenCalledWith('art_1');+ },+ );++ it('waits for the origin conversation before opening a board without a tool message', async () => {+ useChatStore.setState({ activeTopicId: 'another-topic', dbMessagesMap: {} });+ const { rerender } = renderHook(() => useOpenArtboardFromRoute(), { wrapper });++ await act(async () => resolveLoad());+ expect(openBoardPanel).not.toHaveBeenCalled();++ act(() => useChatStore.setState({ activeTopicId: 't' }));+ rerender();+ await act(async () => resolveLoad());+ expect(openBoardPanel).toHaveBeenCalledWith('art_1');+ });++ it.each([+ { enabled: false, ready: true },+ { enabled: true, ready: false },+ ])(+ 'does not open a saved historical board when flags are $enabled/$ready',+ async ({ enabled, ready }) => {+ Object.assign(feature, { enabled, ready });+ renderHook(() => useOpenArtboardFromRoute(), { wrapper });++ await act(async () => resolveLoad());++ expect(openBoardPanel).not.toHaveBeenCalled();+ },+ );++ it('cancels a pending route open when the flag becomes disabled', async () => {+ const { rerender } = renderHook(() => useOpenArtboardFromRoute(), { wrapper });+ feature.enabled = false;+ rerender();++ await act(async () => resolveLoad());++ expect(openBoardPanel).not.toHaveBeenCalled();+ });+});diff --git a/src/features/Artboard/useOpenArtboardFromRoute.ts b/src/features/Artboard/useOpenArtboardFromRoute.tsnew file mode 100644index 00000000000..5706550dc3c--- /dev/null+++ b/src/features/Artboard/useOpenArtboardFromRoute.ts@@ -0,0 +1,42 @@+import { useEffect } from 'react';+import { useSearchParams } from 'react-router';++import { useChatStore } from '@/store/chat';++import { openBoardPanel } from './Conversation/openBoardPanel';+import { useArtboard } from './data/useArtboard';+import { loadArtboardTool } from './loadArtboardTool';+import { artboardActions } from './store';+import { useArtboardFeature } from './useArtboardFeature';++export const ARTBOARD_SEARCH_PARAM = 'artboard';++export const useOpenArtboardFromRoute = () => {+ const { enabled } = useArtboardFeature();+ const [params, setParams] = useSearchParams();+ const artboardId = params.get(ARTBOARD_SEARCH_PARAM);+ const topicId = useChatStore((s) => s.activeTopicId);+ const { data } = useArtboard(artboardId ?? undefined);+ const boardTopicId = data?.artboard.topicId;++ useEffect(() => {+ if (!enabled || !artboardId || !topicId || boardTopicId !== topicId) return;+ let cancelled = false;+ void loadArtboardTool().then(() => {+ if (cancelled) return;+ artboardActions.forgetPage(artboardId);+ openBoardPanel(artboardId);+ setParams(+ (prev) => {+ const next = new URLSearchParams(prev);+ next.delete(ARTBOARD_SEARCH_PARAM);+ return next;+ },+ { replace: true },+ );+ });+ return () => {+ cancelled = true;+ };+ }, [artboardId, boardTopicId, enabled, setParams, topicId]);+};diff --git a/src/features/Artboard/useRegisterArtboardTool.ts b/src/features/Artboard/useRegisterArtboardTool.tsnew file mode 100644index 00000000000..7c759f8c381--- /dev/null+++ b/src/features/Artboard/useRegisterArtboardTool.ts@@ -0,0 +1,13 @@+import { useEffect } from 'react';++import { loadArtboardTool } from './loadArtboardTool';+import { useArtboardFeature } from './useArtboardFeature';+import { useOpenArtboardFromRoute } from './useOpenArtboardFromRoute';++export const useRegisterArtboardTool = () => {+ const { enabled } = useArtboardFeature();+ useEffect(() => {+ if (enabled) void loadArtboardTool();+ }, [enabled]);+ useOpenArtboardFromRoute();+};diff --git a/src/features/ChatInput/InputEditor/ReferArtboard/ReactReferArtboardPlugin.tsx b/src/features/ChatInput/InputEditor/ReferArtboard/ReactReferArtboardPlugin.tsxnew file mode 100644index 00000000000..08dee791616--- /dev/null+++ b/src/features/ChatInput/InputEditor/ReferArtboard/ReactReferArtboardPlugin.tsx@@ -0,0 +1,29 @@+import { useLexicalComposerContext } from '@lobehub/editor';+import { $getNodeByKey } from 'lexical';+import { type FC, useLayoutEffect } from 'react';++import { ReferArtboardPlugin } from './ReferArtboardPlugin';+import { ReferArtboardView } from './ReferArtboardView';++const ReactReferArtboardPlugin: FC = () => {+ const [editor] = useLexicalComposerContext();++ useLayoutEffect(() => {+ editor.registerPlugin(ReferArtboardPlugin, {+ decorator: (node, current) => (+ <ReferArtboardView+ reference={node.reference}+ onRemove={() =>+ current.update(() => $getNodeByKey(node.getKey())?.getParentOrThrow().remove())+ }+ />+ ),+ });+ }, [editor]);++ return null;+};++ReactReferArtboardPlugin.displayName = 'ReactReferArtboardPlugin';++export default ReactReferArtboardPlugin;diff --git a/src/features/ChatInput/InputEditor/ReferArtboard/ReferArtboardNode.ts b/src/features/ChatInput/InputEditor/ReferArtboard/ReferArtboardNode.tsnew file mode 100644index 00000000000..f92969589b5--- /dev/null+++ b/src/features/ChatInput/InputEditor/ReferArtboard/ReferArtboardNode.ts@@ -0,0 +1,103 @@+import { addClassNamesToElement } from '@lexical/utils';+import { getKernelFromEditor } from '@lobehub/editor';+import type { HeadlessRenderableNode, HeadlessRenderContext } from '@lobehub/editor/renderer';+import {+ $applyNodeReplacement,+ DecoratorNode,+ type DOMExportOutput,+ type EditorConfig,+ type LexicalEditor,+ type LexicalNode,+ type LexicalUpdateJSON,+ type SerializedLexicalNode,+ type Spread,+} from 'lexical';+import { createElement } from 'react';++import { ReferArtboardView } from './ReferArtboardView';+import type { ArtboardReference } from './serialize';++export type SerializedReferArtboardNode = Spread<ArtboardReference, SerializedLexicalNode>;++export class ReferArtboardNode extends DecoratorNode<any> implements HeadlessRenderableNode {+ __reference: ArtboardReference;++ static getType(): string {+ return 'refer-artboard';+ }++ static clone(node: ReferArtboardNode): ReferArtboardNode {+ return new ReferArtboardNode(node.__reference, node.__key);+ }++ static importJSON(serialized: SerializedReferArtboardNode): ReferArtboardNode {+ const { artboardId, itemId, itemTitle, text } = serialized;+ return $createReferArtboardNode({ artboardId, itemId, itemTitle, text }).updateFromJSON(+ serialized,+ );+ }++ static importDOM(): null {+ return null;+ }++ constructor(reference: ArtboardReference, key?: string) {+ super(key);+ this.__reference = reference;+ }++ get reference(): ArtboardReference {+ return this.__reference;+ }++ exportDOM(): DOMExportOutput {+ return { element: document.createElement('span') };+ }++ createDOM(config: EditorConfig): HTMLElement {+ const element = document.createElement('span');+ addClassNamesToElement(element, config.theme.referArtboard);+ return element;+ }++ getTextContent(): string {+ return this.__reference.text;+ }++ isInline(): true {+ return true;+ }++ updateDOM(): boolean {+ return false;+ }++ exportJSON(): SerializedReferArtboardNode {+ return { ...super.exportJSON(), ...this.__reference };+ }++ updateFromJSON(serialized: LexicalUpdateJSON<SerializedReferArtboardNode>): this {+ return super.updateFromJSON(serialized);+ }++ decorate(editor: LexicalEditor): any {+ const decorator = getKernelFromEditor(editor)?.getDecorator(ReferArtboardNode.getType());+ if (!decorator) return null;+ if (typeof decorator === 'function') return decorator(this, editor);+ return { queryDOM: decorator.queryDOM, render: decorator.render(this, editor) };+ }++ renderHeadless({ key }: HeadlessRenderContext) {+ return createElement(ReferArtboardView, { key, reference: this.__reference });+ }+}++export function $createReferArtboardNode(reference: ArtboardReference): ReferArtboardNode {+ return $applyNodeReplacement(new ReferArtboardNode(reference));+}++export function $isReferArtboardNode(+ node: LexicalNode | null | undefined,+): node is ReferArtboardNode {+ return node?.getType() === ReferArtboardNode.getType();+}diff --git a/src/features/ChatInput/InputEditor/ReferArtboard/ReferArtboardPlugin.ts b/src/features/ChatInput/InputEditor/ReferArtboard/ReferArtboardPlugin.tsnew file mode 100644index 00000000000..c7527f68a46--- /dev/null+++ b/src/features/ChatInput/InputEditor/ReferArtboard/ReferArtboardPlugin.ts@@ -0,0 +1,106 @@+import {+ type getKernelFromEditor,+ ILitexmlService,+ IMarkdownShortCutService,+} from '@lobehub/editor';+import { t } from 'i18next';+import {+ $createParagraphNode,+ $getRoot,+ $isElementNode,+ COMMAND_PRIORITY_HIGH,+ createCommand,+ type LexicalEditor,+ type LexicalNode,+} from 'lexical';++import {+ $createReferArtboardNode,+ $isReferArtboardNode,+ ReferArtboardNode,+ type SerializedReferArtboardNode,+} from './ReferArtboardNode';+import { type ArtboardReference, serializeArtboardReference } from './serialize';++export const INSERT_ARTBOARD_REFERENCE_COMMAND = createCommand<ArtboardReference>(+ 'INSERT_ARTBOARD_REFERENCE_COMMAND',+);++type IEditorKernel = ReturnType<typeof getKernelFromEditor>;++export interface ReferArtboardPluginOptions {+ decorator: (node: ReferArtboardNode, editor: LexicalEditor) => any;+}++const ATTRS = ['artboardId', 'itemId', 'itemTitle', 'text'] as const;++const isReferenceParagraph = (node: LexicalNode) =>+ $isElementNode(node) && node.getChildren().some((child) => $isReferArtboardNode(child));++const translate = (key: string, options?: Record<string, unknown>) =>+ t(key as 'artboard.chat.quote', { ...options, ns: 'project' }) as string;++export class ReferArtboardPlugin {+ static pluginName = 'ReferArtboardPlugin';++ private kernel: IEditorKernel;++ constructor(kernel: IEditorKernel, config?: ReferArtboardPluginOptions) {+ this.kernel = kernel;+ kernel.registerNodes([ReferArtboardNode]);+ kernel.registerDecorator(ReferArtboardNode.getType(), (node, editor) =>+ config?.decorator ? config.decorator(node as ReferArtboardNode, editor) : null,+ );+ }++ onInit(editor: LexicalEditor): void {+ const mdService = this.kernel.requireService(IMarkdownShortCutService);+ mdService?.registerMarkdownWriter(ReferArtboardNode.getType(), (ctx: any, node: any) => {+ if ($isReferArtboardNode(node))+ ctx.appendLine(`${serializeArtboardReference(node.reference, translate)}\n`);+ });++ const xmlService = this.kernel.requireService(ILitexmlService);+ xmlService?.registerXMLWriter(ReferArtboardNode.getType(), (node: any, ctx: any) =>+ $isReferArtboardNode(node)+ ? ctx.createXmlNode('referArtboard', { ...node.reference })+ : false,+ );+ xmlService?.registerXMLReader('referArtboard', (xmlElement: any) => {+ const read = Object.fromEntries(+ ATTRS.map((name) => [name, xmlElement.getAttribute(name) || '']),+ ) as unknown as ArtboardReference;+ return {+ ...read,+ type: ReferArtboardNode.getType(),+ version: 1,+ } satisfies SerializedReferArtboardNode;+ });++ editor.registerCommand(+ INSERT_ARTBOARD_REFERENCE_COMMAND,+ (reference) => {+ editor.update(() => {+ const root = $getRoot();+ const paragraph = $createParagraphNode().append($createReferArtboardNode(reference));+ const leading = root.getChildren();+ let anchor: LexicalNode | undefined;+ for (const child of leading) {+ if (!isReferenceParagraph(child)) break;+ anchor = child;+ }+ if (anchor) anchor.insertAfter(paragraph);+ else if (root.getFirstChild()) root.getFirstChild()!.insertBefore(paragraph);+ else root.append(paragraph, $createParagraphNode());+ root.selectEnd();+ });+ return true;+ },+ COMMAND_PRIORITY_HIGH,+ );+ }++ destroy(): void {+ this.kernel.unregisterDecorator?.(ReferArtboardNode.getType());+ }+}diff --git a/src/features/ChatInput/InputEditor/ReferArtboard/ReferArtboardView.tsx b/src/features/ChatInput/InputEditor/ReferArtboard/ReferArtboardView.tsxnew file mode 100644index 00000000000..18a12a1ebd6--- /dev/null+++ b/src/features/ChatInput/InputEditor/ReferArtboard/ReferArtboardView.tsx@@ -0,0 +1,90 @@+import { Icon } from '@lobehub/ui';+import { cssVar } from '@lobehub/ui/stylex/cssVar.stylex';+import * as stylex from '@stylexjs/stylex';+import { MessageSquareQuoteIcon, XIcon } from 'lucide-react';+import { memo } from 'react';++import type { ArtboardReference } from './serialize';++const styles = stylex.create({+ body: {+ WebkitBoxOrient: 'vertical',+ WebkitLineClamp: 3,+ color: cssVar.colorText,+ display: '-webkit-box',+ overflow: 'hidden',+ whiteSpace: 'pre-line',+ },+ close: {+ alignItems: 'center',+ color: cssVar.colorTextTertiary,+ cursor: 'pointer',+ display: 'inline-flex',+ flexShrink: 0,+ height: 20,+ marginInlineStart: 'auto',+ },+ content: {+ display: 'flex',+ flex: '1',+ flexDirection: 'column',+ minWidth: 0,+ },+ icon: {+ alignItems: 'center',+ color: cssVar.colorTextSecondary,+ display: 'inline-flex',+ flexShrink: 0,+ height: 20,+ },+ root: {+ alignItems: 'flex-start',+ backgroundColor: cssVar.colorFillTertiary,+ borderRadius: cssVar.borderRadius,+ boxSizing: 'border-box',+ display: 'flex',+ fontSize: 12,+ gap: 8,+ lineHeight: '20px',+ paddingBlock: 6,+ paddingInline: 10,+ userSelect: 'none',+ width: '100%',+ },+ target: {+ color: cssVar.colorTextSecondary,+ overflow: 'hidden',+ textOverflow: 'ellipsis',+ whiteSpace: 'nowrap',+ },+});++interface ReferArtboardViewProps {+ onRemove?: () => void;+ reference: ArtboardReference;+}++export const ReferArtboardView = memo<ReferArtboardViewProps>(({ onRemove, reference }) => (+ <span {...stylex.props(styles.root)}>+ <span {...stylex.props(styles.icon)}>+ <Icon icon={MessageSquareQuoteIcon} size={12} />+ </span>+ <span {...stylex.props(styles.content)}>+ <span {...stylex.props(styles.target)}>{reference.itemTitle}</span>+ {reference.text && <span {...stylex.props(styles.body)}>{reference.text}</span>}+ </span>+ {onRemove && (+ <span+ {...stylex.props(styles.close)}+ onClick={(event) => {+ event.stopPropagation();+ onRemove();+ }}+ >+ <Icon icon={XIcon} size={12} />+ </span>+ )}+ </span>+));++ReferArtboardView.displayName = 'ReferArtboardView';diff --git a/src/features/ChatInput/InputEditor/ReferArtboard/index.ts b/src/features/ChatInput/InputEditor/ReferArtboard/index.tsnew file mode 100644index 00000000000..7fddec1badf--- /dev/null+++ b/src/features/ChatInput/InputEditor/ReferArtboard/index.ts@@ -0,0 +1,6 @@+export { insertArtboardReference } from './insertArtboardReference';+export { default as ReactReferArtboardPlugin } from './ReactReferArtboardPlugin';+export { $isReferArtboardNode, ReferArtboardNode } from './ReferArtboardNode';+export { INSERT_ARTBOARD_REFERENCE_COMMAND } from './ReferArtboardPlugin';+export type { ArtboardReference } from './serialize';+export { serializeArtboardReference, serializeArtboardReferences } from './serialize';diff --git a/src/features/ChatInput/InputEditor/ReferArtboard/insertArtboardReference.ts b/src/features/ChatInput/InputEditor/ReferArtboard/insertArtboardReference.tsnew file mode 100644index 00000000000..71162c31705--- /dev/null+++ b/src/features/ChatInput/InputEditor/ReferArtboard/insertArtboardReference.ts@@ -0,0 +1,12 @@+import { useChatStore } from '@/store/chat';++import { INSERT_ARTBOARD_REFERENCE_COMMAND } from './ReferArtboardPlugin';+import type { ArtboardReference } from './serialize';++export const insertArtboardReference = (reference: ArtboardReference) => {+ const editor = useChatStore.getState().mainInputEditor;+ if (!editor?.instance) return false;+ editor.instance.dispatchCommand(INSERT_ARTBOARD_REFERENCE_COMMAND, reference);+ editor.focus();+ return true;+};diff --git a/src/features/ChatInput/InputEditor/ReferArtboard/serialize.test.ts b/src/features/ChatInput/InputEditor/ReferArtboard/serialize.test.tsnew file mode 100644index 00000000000..ca33046a60f--- /dev/null+++ b/src/features/ChatInput/InputEditor/ReferArtboard/serialize.test.ts@@ -0,0 +1,30 @@+import { describe, expect, it } from 'vitest';++import { serializeArtboardReference, serializeArtboardReferences } from './serialize';++const t = (key: string, options?: Record<string, unknown>) =>+ ({ 'artboard.chat.quote': `Re: ${options?.target}` })[key] ?? key;++const ref = { artboardId: 'art_1', itemId: 'b1', itemTitle: 'A', text: 'x' };++describe('serializeArtboardReference', () => {+ it('quotes a comment with the artboard and the board it points at', () => {+ expect(+ serializeArtboardReference(+ { ...ref, itemTitle: '空项目', text: '加一个返回按钮\n文案改短' },+ t,+ ),+ ).toBe('> Re: b1 · 空项目 · artboard art_1\n> 加一个返回按钮\n> 文案改短');+ });++ it('separates several references so each stays its own quote', () => {+ expect(serializeArtboardReferences([ref, { ...ref, itemId: 'b2', itemTitle: 'B' }], t)).toBe(+ '> Re: b1 · A · artboard art_1\n> x\n\n> Re: b2 · B · artboard art_1\n> x',+ );+ });+ it('quotes a board with no remark as a single line', () => {+ expect(serializeArtboardReference({ ...ref, text: '' }, t)).toBe(+ '> Re: b1 · A · artboard art_1',+ );+ });+});diff --git a/src/features/ChatInput/InputEditor/ReferArtboard/serialize.ts b/src/features/ChatInput/InputEditor/ReferArtboard/serialize.tsnew file mode 100644index 00000000000..7955ce76e74--- /dev/null+++ b/src/features/ChatInput/InputEditor/ReferArtboard/serialize.ts@@ -0,0 +1,17 @@+export interface ArtboardReference {+ artboardId: string;+ itemId: string;+ itemTitle: string;+ text: string;+}++type Translate = (key: string, options?: Record<string, unknown>) => string;++export const serializeArtboardReference = (ref: ArtboardReference, t: Translate) =>+ [+ `> ${t('artboard.chat.quote', { target: `${ref.itemId} · ${ref.itemTitle}` })} · artboard ${ref.artboardId}`,+ ...(ref.text ? ref.text.split('\n').map((line) => `> ${line}`) : []),+ ].join('\n');++export const serializeArtboardReferences = (refs: ArtboardReference[], t: Translate) =>+ refs.map((ref) => serializeArtboardReference(ref, t)).join('\n\n');diff --git a/src/features/ChatInput/InputEditor/plugins.ts b/src/features/ChatInput/InputEditor/plugins.tsindex 224608a3ff3..8297c27cdcd 100644--- a/src/features/ChatInput/InputEditor/plugins.ts+++ b/src/features/ChatInput/InputEditor/plugins.ts@@ -13,6 +13,7 @@ import { type Editor } from '@lobehub/editor/react';import { ReactActionTagPlugin } from './ActionTag';import { ReactImageRefTagPlugin } from './ImageRefTag';import { ReactLocalFileTagPlugin } from './LocalFileTag';+import { ReactReferArtboardPlugin } from './ReferArtboard';import { ReactReferDocumentPlugin } from './ReferDocument';import { ReactReferTopicPlugin } from './ReferTopic';@@ -27,6 +28,7 @@ export const CHAT_INPUT_EMBED_PLUGINS: EditorPlugins = [ReactActionTagPlugin,ReactReferTopicPlugin,ReactReferDocumentPlugin,+ ReactReferArtboardPlugin,ReactLocalFileTagPlugin,ReactImageRefTagPlugin,ReactMentionPlugin,diff --git a/src/features/Conversation/Messages/AssistantGroup/components/segments.test.ts b/src/features/Conversation/Messages/AssistantGroup/components/segments.test.tsindex 41aadd0bd11..40dfd5c998a 100644--- a/src/features/Conversation/Messages/AssistantGroup/components/segments.test.ts+++ b/src/features/Conversation/Messages/AssistantGroup/components/segments.test.ts@@ -2,6 +2,7 @@ import { describe, expect, it } from 'vitest';import { LOADING_FLAT } from '@/const/message';+import { registerDeliverableTool } from '../toolRenderRules';import {countAssistantLlmCalls,hasRenderableFinalAnswer,@@ -85,6 +86,34 @@ describe('shouldFoldProcess', () => {);const proc = [w('t1')];+ it('keeps a registered deliverable tool visible after the turn ends', () => {+ registerDeliverableTool('deliverable-tool');+ const card = { apiName: 'open', id: 'card', identifier: 'deliverable-tool' };+ const finished = {+ enabled: true,+ isGenerating: false,+ operationEnded: true,+ };++ expect(+ shouldFoldProcess({+ ...finished,+ processSegments: [{ blocks: [{ id: 'card', tools: [card] } as any], kind: 'workflow' }],+ }),+ ).toBe(false);+ expect(+ shouldFoldProcess({+ ...finished,+ processSegments: [+ {+ blocks: [{ id: 'other', tools: [{ ...card, identifier: 'other' }] } as any],+ kind: 'workflow',+ },+ ],+ }),+ ).toBe(true);+ });+it('folds a finished turn whose process only READ an image', () => {const readImage = {apiName: 'Read',diff --git a/src/features/Conversation/Messages/AssistantGroup/components/segments.ts b/src/features/Conversation/Messages/AssistantGroup/components/segments.tsindex e8098ad5665..a547ee80641 100644--- a/src/features/Conversation/Messages/AssistantGroup/components/segments.ts+++ b/src/features/Conversation/Messages/AssistantGroup/components/segments.ts@@ -3,7 +3,7 @@ import { splitAssistantGroupFinalAnswer } from '@lobechat/conversation-flow';import { LOADING_FLAT } from '@/const/message';-import { isImageOutputTool, isMcpAppTool } from '../toolRenderRules';+import { isDeliverableTool, isMcpAppTool } from '../toolRenderRules';import type { RenderableAssistantContentBlock } from './types';import type { WorkflowExpandLevel, WorkflowExpandLevelDefault } from './WorkflowCollapse';@@ -77,7 +77,7 @@ export const shouldFoldProcess = ({processSegments.some((segment) => segment.kind === 'workflow') &&!processSegments.some((segment) =>(segment.kind === 'answer' ? [segment.block] : segment.blocks).some((block) =>- block.tools?.some(isImageOutputTool),+ block.tools?.some(isDeliverableTool),),);diff --git a/src/features/Conversation/Messages/AssistantGroup/toolRenderRules.ts b/src/features/Conversation/Messages/AssistantGroup/toolRenderRules.tsindex fc38a3e1a72..d82cf95d88c 100644--- a/src/features/Conversation/Messages/AssistantGroup/toolRenderRules.ts+++ b/src/features/Conversation/Messages/AssistantGroup/toolRenderRules.ts@@ -55,6 +55,15 @@ export const isImageOutputTool = (tool: ChatToolPayloadWithResult): boolean => {);};+const deliverableTools = new Set<string>();++export const registerDeliverableTool = (identifier: string) => {+ deliverableTools.add(identifier);+};++export const isDeliverableTool = (tool: ChatToolPayloadWithResult): boolean =>+ isImageOutputTool(tool) || deliverableTools.has(tool.identifier);+/*** Any tool whose result carries an image, output or read. Drives the workflow* breakout only: a read image still surfaces as its own row once the process isdiff --git a/src/features/Conversation/Messages/User/components/RichTextMessage.tsx b/src/features/Conversation/Messages/User/components/RichTextMessage.tsxindex 792d46ccb92..97abff3f14f 100644--- a/src/features/Conversation/Messages/User/components/RichTextMessage.tsx+++ b/src/features/Conversation/Messages/User/components/RichTextMessage.tsx@@ -8,6 +8,7 @@ import { ActionTagNode } from '@/features/ChatInput/InputEditor/ActionTag/Actionimport { ImageRefTagNode } from '@/features/ChatInput/InputEditor/ImageRefTag/ImageRefTagNode';import { LocalFileTagNode } from '@/features/ChatInput/InputEditor/LocalFileTag';import { mentionPlainClassName } from '@/features/ChatInput/InputEditor/mentionStyle';+import { ReferArtboardNode } from '@/features/ChatInput/InputEditor/ReferArtboard/ReferArtboardNode';import { ReferDocumentNode } from '@/features/ChatInput/InputEditor/ReferDocument/ReferDocumentNode';import { ReferTopicNode } from '@/features/ChatInput/InputEditor/ReferTopic/ReferTopicNode';@@ -26,6 +27,7 @@ const EXTRA_NODES = [ActionTagNode,ReferTopicNode,ReferDocumentNode,+ ReferArtboardNode,LocalFileTagNode,ImageRefTagNode,];diff --git a/src/features/Conversation/WorkingSidebar/Canvas/CanvasFrame.tsx b/src/features/Conversation/WorkingSidebar/Canvas/CanvasFrame.tsxindex 60fd65bb3df..5705c2a7ada 100644--- a/src/features/Conversation/WorkingSidebar/Canvas/CanvasFrame.tsx+++ b/src/features/Conversation/WorkingSidebar/Canvas/CanvasFrame.tsx@@ -39,108 +39,119 @@ interface CanvasError {const MAX_ERRORS = 10;-const CanvasDocumentFrame = memo<{ project: CanvasPreviewProject }>(({ project }) => {- 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 [location, setLocation] = useState({ path: project.entry, hash: '' });- // Serializing a project can include megabytes of assets; themes and errors must not rebuild it.- const srcDoc = useMemo(- () => createCanvasPreviewDocument(project, location.path, location.hash),- [project, location],- );-- 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' },- '*',+const CanvasDocumentFrame = memo<{ path?: string; project: CanvasPreviewProject }>(+ ({ path, project }) => {+ 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 [location, setLocation] = useState({+ hash: '',+ path: path && project.files[path] ? path : project.entry,+ });+ // Serializing a project can include megabytes of assets; themes and errors must not rebuild it.+ const srcDoc = useMemo(+ () => createCanvasPreviewDocument(project, location.path, location.hash),+ [project, location],);- }, [theme]);- useEffect(postTheme, [postTheme]);-- useEffect(() => setErrors([]), [srcDoc]);-- 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));- });- }, [project]);-- 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 === 'navigate' &&- typeof event.data.path === 'string' &&- event.data.path.toLowerCase().endsWith('.html') &&- project.files[event.data.path]- )- setLocation({- path: event.data.path,- hash: typeof event.data.hash === 'string' ? event.data.hash : '',- });- 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, project]);+ const theme = useMemo(+ () => ({ appearance: isDarkMode ? 'dark' : 'light', neutralColor, primaryColor }),+ [isDarkMode, neutralColor, primaryColor],+ );- 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>- }+ const postTheme = useCallback(() => {+ ref.current?.contentWindow?.postMessage(+ { source: 'lobe-canvas-host', theme, type: 'theme' },+ '*',+ );+ }, [theme]);++ useEffect(postTheme, [postTheme]);++ useEffect(() => setErrors([]), [srcDoc]);++ 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));+ });+ }, [project]);++ 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 === 'navigate' &&+ typeof event.data.path === 'string' &&+ event.data.path.toLowerCase().endsWith('.html') &&+ project.files[event.data.path]+ )+ setLocation({+ path: event.data.path,+ hash: typeof event.data.hash === 'string' ? event.data.hash : '',+ });+ 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, project]);++ 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"+ srcDoc={srcDoc}+ title={t('canvas.frameTitle')}+ onLoad={postTheme}/>- )}- <iframe- {...stylex.props(styles.frame)}- ref={ref}- sandbox="allow-scripts allow-popups allow-forms allow-downloads"- srcDoc={srcDoc}- title={t('canvas.frameTitle')}- onLoad={postTheme}- />- </>- );-});+ </>+ );+ },+);CanvasDocumentFrame.displayName = 'CanvasDocumentFrame';-const CanvasProjectFrame = ({ canvasId, version }: { canvasId: string; version: number }) => {+interface CanvasFrameProps {+ canvasId: string;+ path?: string;+ version: number;+}++const CanvasProjectFrame = ({ canvasId, path, version }: CanvasFrameProps) => {const { data, error, isLoading, mutate } = useFetchCanvasProject(canvasId, version);return (<AsyncBoundary@@ -151,14 +162,14 @@ const CanvasProjectFrame = ({ canvasId, version }: { canvasId: string; version:void mutate();}}>- {data && <CanvasDocumentFrame project={data} />}+ {data && <CanvasDocumentFrame path={path} project={data} />}</AsyncBoundary>);};// Project bytes belong to this mounted preview, rather than the application's long-lived SWR cache.const previewCache = { provider: () => new Map() };-const CanvasFrame = (props: { canvasId: string; version: number }) => (+const CanvasFrame = (props: CanvasFrameProps) => (<SWRConfig value={previewCache}><CanvasProjectFrame {...props} /></SWRConfig>diff --git a/src/features/Conversation/WorkingSidebar/DynamicTabPanes.tsx b/src/features/Conversation/WorkingSidebar/DynamicTabPanes.tsxindex df3ae0716bb..d6b49db9eb6 100644--- a/src/features/Conversation/WorkingSidebar/DynamicTabPanes.tsx+++ b/src/features/Conversation/WorkingSidebar/DynamicTabPanes.tsx@@ -1,10 +1,11 @@import { Flexbox } from '@lobehub/ui';import * as stylex from '@stylexjs/stylex';-import { Globe2Icon, PanelsTopLeftIcon } from 'lucide-react';-import { Activity, lazy, memo, useEffect } from 'react';+import { DraftingCompassIcon, Globe2Icon, PanelsTopLeftIcon } from 'lucide-react';+import { Activity, lazy, memo, Suspense, useEffect } from 'react';+import BoardTabLabel from '@/features/Artboard/Conversation/BoardTabLabel';import { mcpEntryInstanceId } from '@/features/MCPApp/entrypoints';-import { canvasIdOfTab } from '@/store/global/initialState';+import { artboardIdOfTab, canvasIdOfTab } from '@/store/global/initialState';import { mcpAppActions } from '@/store/mcpApp/action';import { useMcpAppStore } from '@/store/mcpApp/store';import { serverConfigSelectors, useServerConfigStore } from '@/store/serverConfig';@@ -15,6 +16,7 @@ import CanvasTabLabel from './Canvas/CanvasTabLabel';import {browserSessionIdOfTab,type BrowserTabMetadata,+ isArtboardTab,isBrowserTab,isCanvasTab,type SidebarTabDescriptor,@@ -27,11 +29,13 @@ const McpEntryPane = lazy(() =>import('./McpEntryPane').then((m) => ({ default: m.McpEntryPane })),);const BrowserPane = lazy(() => import('./Browser'));+const BoardPane = lazy(() => import('@/features/Artboard/Conversation/BoardPane'));// 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 BOARD_PANE = { minHeight: 0, overflow: 'hidden' } as const;const styles = stylex.create({favicon: {@@ -66,6 +70,14 @@ export const dynamicTabDescriptor = (if (canvasId) {return { icon: PanelsTopLeftIcon, key: tab, label: <CanvasTabLabel canvasId={canvasId} /> };}+ const artboardId = artboardIdOfTab(tab);+ if (artboardId) {+ return {+ icon: DraftingCompassIcon,+ key: tab,+ label: <BoardTabLabel artboardId={artboardId} />,+ };+ }if (!isBrowserTab(tab)) return;return {@@ -184,6 +196,15 @@ const DynamicTabPanes = memo<DynamicTabPanesProps>(</Flexbox></Activity>))}+ {openedTabs.filter(isArtboardTab).map((tab) => (+ <Activity key={tab} mode={visible && activeTab === tab ? 'visible' : 'hidden'}>+ <Flexbox flex={1} style={BOARD_PANE}>+ <Suspense fallback={null}>+ <BoardPane artboardId={artboardIdOfTab(tab)!} />+ </Suspense>+ </Flexbox>+ </Activity>+ ))}</>);},diff --git a/src/features/Conversation/WorkingSidebar/WorksSection/WorkVersionHistoryCard.tsx b/src/features/Conversation/WorkingSidebar/WorksSection/WorkVersionHistoryCard.tsxindex baf2b776cd2..7faaf2498bd 100644--- a/src/features/Conversation/WorkingSidebar/WorksSection/WorkVersionHistoryCard.tsx+++ b/src/features/Conversation/WorkingSidebar/WorksSection/WorkVersionHistoryCard.tsx@@ -7,6 +7,7 @@ import { memo, useState } from 'react';import TaskPriorityTag from '@/features/AgentTasks/features/TaskPriorityTag';import TaskStatusTag from '@/features/AgentTasks/features/TaskStatusTag';+import { openArtboard } from '@/features/Artboard/openArtboard';import { getWorkTypeDescriptor, isSafeExternalUrl } from '@/features/Work/descriptors';import { useResourceDeletedPrompt } from '@/features/Work/useResourceDeletedPrompt';import { useChatStore } from '@/store/chat';@@ -95,6 +96,9 @@ const WorkVersionHistoryCard = memo<{ work: WorkListItem }>(({ work }) => {const handleTitleClick = (() => {if (!openTarget) return undefined;switch (openTarget.kind) {+ case 'artboard': {+ return () => void openArtboard(openTarget.artboardId);+ }case 'document': {return resourceDeleted? () => promptResourceDeleted(work)diff --git a/src/features/Conversation/WorkingSidebar/dynamicTabs.test.ts b/src/features/Conversation/WorkingSidebar/dynamicTabs.test.tsnew file mode 100644index 00000000000..feea47ca286--- /dev/null+++ b/src/features/Conversation/WorkingSidebar/dynamicTabs.test.ts@@ -0,0 +1,21 @@+import { describe, expect, it } from 'vitest';++import { artboardIdOfTab, artboardTabKey } from '@/store/global/initialState';++import { isArtboardTab, isDynamicTab, isWorkTab } from './dynamicTabs';++describe('artboard tabs', () => {+ it('round-trips an artboard id through its tab key', () => {+ expect(artboardIdOfTab(artboardTabKey('art_1'))).toBe('art_1');+ expect(artboardIdOfTab('canvas:cvs_1')).toBeUndefined();+ });++ it('belongs to one conversation, like a canvas tab', () => {+ const tab = artboardTabKey('art_1');+ expect(isArtboardTab(tab)).toBe(true);+ expect(isDynamicTab(tab)).toBe(true);+ expect(isWorkTab(tab)).toBe(true);+ expect(isWorkTab('canvas:cvs_1')).toBe(true);+ expect(isWorkTab('files')).toBe(false);+ });+});diff --git a/src/features/Conversation/WorkingSidebar/dynamicTabs.ts b/src/features/Conversation/WorkingSidebar/dynamicTabs.tsindex 32b39a823dd..620c1397cf9 100644--- a/src/features/Conversation/WorkingSidebar/dynamicTabs.ts+++ b/src/features/Conversation/WorkingSidebar/dynamicTabs.ts@@ -1,7 +1,7 @@import type { IconProps } from '@lobehub/ui';import type { ReactNode } from 'react';-import { CANVAS_TAB_PREFIX } from '@/store/global/initialState';+import { ARTBOARD_TAB_PREFIX, CANVAS_TAB_PREFIX } from '@/store/global/initialState';export interface SidebarTabDescriptor {icon: IconProps['icon'];@@ -24,13 +24,17 @@ export const isBrowserTab = (tab: string) =>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 isArtboardTab = (tab: string) => tab.startsWith(ARTBOARD_TAB_PREFIX);++export const isWorkTab = (tab: string) => isCanvasTab(tab) || isArtboardTab(tab);+export const isMcpAppTab = (tab: string) =>tab.startsWith('mcp-app:') || tab.startsWith('mcp-entry:');+// Browser pages, canvases and artboards 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) || isMcpAppTab(tab);+ isBrowserTab(tab) || isWorkTab(tab) || isMcpAppTab(tab);export const browserSessionIdOfTab = (baseSessionId: string, tab: string) =>tab === BROWSER_TAB_KEYdiff --git a/src/features/Conversation/WorkingSidebar/index.tsx b/src/features/Conversation/WorkingSidebar/index.tsxindex 0188c62cb38..b345445cd65 100644--- a/src/features/Conversation/WorkingSidebar/index.tsx+++ b/src/features/Conversation/WorkingSidebar/index.tsx@@ -79,9 +79,9 @@ import {BROWSER_TAB_PREFIX,type BrowserTabMetadata,isBrowserTab,- isCanvasTab,isDynamicTab,isMcpAppTab,+ isWorkTab,type SidebarTabDescriptor,} from './dynamicTabs';import FilesPane from './Files/FilesPane';@@ -497,7 +497,7 @@ const AgentWorkingSidebar = memo<AgentWorkingSidebarProps>(({ availableWidth })(tab: string) =>availableTabs.has(tab) ||(browserAvailable && isBrowserTab(tab)) ||- isCanvasTab(tab) ||+ isWorkTab(tab) ||(mcpAppsEnabled && isMcpAppTab(tab)),[availableTabs, browserAvailable, mcpAppsEnabled],);@@ -811,7 +811,7 @@ const AgentWorkingSidebar = memo<AgentWorkingSidebarProps>(({ availableWidth })const reviewTwoPane = activeTab === 'review' && reviewAvailable && showReviewTree;const preferredMinWidth = reviewTwoPane? TWO_PANE_MIN_WIDTH- : isCanvasTab(activeTab)+ : isWorkTab(activeTab)? CANVAS_MIN_WIDTH: 0;const displayWidth = Math.max(storedWidth, preferredMinWidth);diff --git a/src/features/Electron/titlebar/NavigationBar.tsx b/src/features/Electron/titlebar/NavigationBar.tsxindex 76e52a8d893..d62bb011080 100644--- a/src/features/Electron/titlebar/NavigationBar.tsx+++ b/src/features/Electron/titlebar/NavigationBar.tsx@@ -8,7 +8,6 @@ import { useTranslation } from 'react-i18next';import ToggleLeftPanelButton from '@/features/NavPanel/ToggleLeftPanelButton';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';-import { electronSystemService } from '@/services/electron/system';import { useElectronStore } from '@/store/electron';import { useGlobalStore } from '@/store/global';import type { GlobalState } from '@/store/global/initialState';@@ -18,9 +17,9 @@ import { electronStylish } from '@/styles/electron';import { getPlatform, isMacOS } from '@/utils/platform';import { useNavigationHistory } from '../navigation/useNavigationHistory';-import { getMacTrafficLightPadding } from './layout';import RecentlyViewed from './RecentlyViewed';import { useTrayMenuSync } from './TrayMenu/useTrayMenuSync';+import { useMacTrafficLightPadding } from './useMacTrafficLightPadding';import WindowsAppMenu from './WindowsAppMenu';const isMac = isMacOS();@@ -66,16 +65,11 @@ const NavigationBar = memo(() => {const navigate = useWorkspaceAwareNavigate();const { canGoBack, canGoForward, goBack, goForward } = useNavigationHistory();const [historyOpen, setHistoryOpen] = useState(false);- const [isWindowFullScreen, setIsWindowFullScreen] = useState(false);const activeRecentScope = useElectronStore((state) => state.activeRecentScope);const leftPanelWidth = useNavPanelWidth();const navPanelResizing = useGlobalStore((s) => !!s.isNavPanelResizing);- useWatchBroadcast('windowFullscreenChanged', ({ isFullScreen }) => {- if (isMac) setIsWindowFullScreen(isFullScreen);- });-useWatchBroadcast('openRecentlyViewed', () => setHistoryOpen(true));useWatchBroadcast('openAllAgents', () => {@@ -84,27 +78,6 @@ const NavigationBar = memo(() => {getHomeStoreState().openAllAgentsDrawer();});- useEffect(() => {- if (!isMac) return;-- let disposed = false;-- const syncFullScreenState = async () => {- try {- const isFullScreen = await electronSystemService.isWindowFullScreen();- if (!disposed) setIsWindowFullScreen(isFullScreen);- } catch {- if (!disposed) setIsWindowFullScreen(false);- }- };-- void syncFullScreenState();-- return () => {- disposed = true;- };- }, []);-// Toggle history popoverconst toggleHistoryOpen = useCallback(() => {setHistoryOpen((prev) => !prev);@@ -130,7 +103,7 @@ const NavigationBar = memo(() => {const tooltipContent = t('navigation.recentView');const isLeftPanelVisible = leftPanelWidth > 0;- const macTrafficLightPadding = getMacTrafficLightPadding(isMac, isWindowFullScreen);+ const macTrafficLightPadding = useMacTrafficLightPadding();const collapsedWidth =(isMac ? MAC_COLLAPSED_NAVIGATION_BAR_WIDTH : COLLAPSED_NAVIGATION_BAR_WIDTH) +macTrafficLightPadding;diff --git a/src/features/Electron/titlebar/useMacTrafficLightPadding.ts b/src/features/Electron/titlebar/useMacTrafficLightPadding.tsnew file mode 100644index 00000000000..b98ece6d2f7--- /dev/null+++ b/src/features/Electron/titlebar/useMacTrafficLightPadding.ts@@ -0,0 +1,40 @@+import { useWatchBroadcast } from '@lobechat/electron-client-ipc';+import { useEffect, useState } from 'react';++import { electronSystemService } from '@/services/electron/system';+import { isMacOS } from '@/utils/platform';++import { getMacTrafficLightPadding } from './layout';++const isMac = isMacOS();++export const useMacTrafficLightPadding = () => {+ const [isWindowFullScreen, setIsWindowFullScreen] = useState(false);++ useWatchBroadcast('windowFullscreenChanged', ({ isFullScreen }) => {+ if (isMac) setIsWindowFullScreen(isFullScreen);+ });++ useEffect(() => {+ if (!isMac) return;++ let disposed = false;++ const syncFullScreenState = async () => {+ try {+ const isFullScreen = await electronSystemService.isWindowFullScreen();+ if (!disposed) setIsWindowFullScreen(isFullScreen);+ } catch {+ if (!disposed) setIsWindowFullScreen(false);+ }+ };++ void syncFullScreenState();++ return () => {+ disposed = true;+ };+ }, []);++ return getMacTrafficLightPadding(isMac, isWindowFullScreen);+};diff --git a/src/features/Portal/Plugins/Body/index.tsx b/src/features/Portal/Plugins/Body/index.tsxindex 7200eae1517..4b42242158a 100644--- a/src/features/Portal/Plugins/Body/index.tsx+++ b/src/features/Portal/Plugins/Body/index.tsx@@ -1,3 +1,5 @@+import { ArtboardIdentifier } from '@lobechat/builtin-tool-artboard';+import { getBuiltinPortal } from '@lobechat/builtin-tools/portals';import { Flexbox } from '@lobehub/ui';import isEqual from 'fast-deep-equal';@@ -10,6 +12,23 @@ import ToolRender from './ToolRender';const ToolUI = () => {const messageId = useChatStore(chatPortalSelectors.toolMessageId);const message = useChatStore(dbMessageSelectors.getDbMessageById(messageId || ''), isEqual);+ const identifier = useChatStore(chatPortalSelectors.toolUIIdentifier);+ const params = useChatStore(chatPortalSelectors.toolUIParams, isEqual);+ if (identifier === ArtboardIdentifier && typeof params?.artboardId === 'string') {+ // Resolved through the registry so hosts that never load the artboard tool (Share) keep it out of their bundle.+ const ArtboardPortal = getBuiltinPortal(identifier);+ if (!ArtboardPortal) return null;+ return (+ <Flexbox flex={1} height={'100%'} paddingInline={12} style={{ overflow: 'auto' }}>+ <ArtboardPortal+ arguments={{}}+ identifier={identifier}+ messageId={messageId ?? ''}+ state={{ artboardId: params.artboardId }}+ />+ </Flexbox>+ );+ }// make sure the message and id is validif (!messageId || !message) return;diff --git a/src/features/Projects/Conversation/index.tsx b/src/features/Projects/Conversation/index.tsxindex 43d479460d4..499ec778662 100644--- a/src/features/Projects/Conversation/index.tsx+++ b/src/features/Projects/Conversation/index.tsx@@ -4,6 +4,7 @@ import { Flexbox, Text } from '@lobehub/ui';import { memo } from 'react';import ConversationSegmentSkeleton from '@/components/Skeleton/Conversation/Segment';+import { useRegisterArtboardTool } from '@/features/Artboard';import ConversationWorkspace from '@/features/Conversation/Workspace';import NavHeader from '@/features/NavHeader';import ChatConversation from '@/routes/(main)/agent/features/Conversation';@@ -17,6 +18,7 @@ import { useProjectConversation } from './useProjectConversation';const ProjectConversation = memo(() => {const { fallback, getConversationPath, getTopicPath, restageDraft, stage, title, topic } =useProjectConversation();+ useRegisterArtboardTool();if (fallback) return fallback;diff --git a/src/features/Work/WorkSummaryCard.tsx b/src/features/Work/WorkSummaryCard.tsxindex e6d1e0e541b..926a11b38b4 100644--- a/src/features/Work/WorkSummaryCard.tsx+++ b/src/features/Work/WorkSummaryCard.tsx@@ -7,6 +7,7 @@ import { CircleDollarSignIcon, CoinsIcon, GitBranchIcon } from 'lucide-react';import { memo } from 'react';import { useTranslation } from 'react-i18next';+import { openArtboard } from '@/features/Artboard/openArtboard';import { useChatStore } from '@/store/chat';import { useDensityTokens } from '@/styles/density';import { sidebarRow } from '@/styles/density.stylex';@@ -349,6 +350,10 @@ const WorkSummaryCard = memo<WorkSummaryCardProps>(if (!openTarget) return;switch (openTarget.kind) {+ case 'artboard': {+ void openArtboard(openTarget.artboardId);+ return;+ }case 'canvas': {openCanvas(openTarget.canvasId, openTarget.version);return;diff --git a/src/features/Work/descriptors.test.ts b/src/features/Work/descriptors.test.tsindex b6f72bff62b..76314f357e9 100644--- a/src/features/Work/descriptors.test.ts+++ b/src/features/Work/descriptors.test.ts@@ -223,4 +223,19 @@ describe('getWorkTypeDescriptor', () => {expect(getWorkTypeDescriptor(linear).getDescription(linear)).toBe('In Progress');});});++ describe('artboard open target', () => {+ it('opens the board it records', () => {+ const item = { resourceId: 'art_1', title: '首次进入', type: 'artboard' } as any;+ expect(getWorkTypeDescriptor(item).getOpenTarget(item)).toEqual({+ artboardId: 'art_1',+ kind: 'artboard',+ });+ });++ it('has nothing to open without a board id', () => {+ const item = { resourceId: null, title: 'x', type: 'artboard' } as any;+ expect(getWorkTypeDescriptor(item).getOpenTarget(item)).toBeNull();+ });+ });});diff --git a/src/features/Work/descriptors.tsx b/src/features/Work/descriptors.tsxindex 1dca17de5cc..38207a8a566 100644--- a/src/features/Work/descriptors.tsx+++ b/src/features/Work/descriptors.tsx@@ -16,6 +16,7 @@ import {CircleCheckIcon,CircleDotIcon,ClipboardListIcon,+ DraftingCompassIcon,FileBoxIcon,FileSpreadsheetIcon,FileTextIcon,@@ -121,6 +122,7 @@ export interface WorkBranch {* only names the destination, it never reaches into a store or the DOM itself.*/export type WorkOpenTarget =+ | { artboardId: string; kind: 'artboard' }| { agentDocumentId?: string; documentId: string; kind: 'document' }| { taskId: string; identifier?: string; kind: 'task'; name?: string | null }| { kind: 'external'; url: string }@@ -253,6 +255,14 @@ const getFileWorkPath = (item: WorkItemOfType<'file'>): string | null =>export const WORK_TYPE_DESCRIPTORS: {[T in ListedWorkType]: WorkTypeDescriptor<WorkItemOfType<T>>;} = {+ artboard: {+ getDescription: (item) => item.description?.trim() ?? null,+ getIcon: () => DraftingCompassIcon,+ getIdentifier: () => null,+ getOpenTarget: (item) =>+ item.resourceId ? { artboardId: item.resourceId, kind: 'artboard' } : null,+ getTitle: (item) => item.title,+ },canvas: {getDescription: (item) => item.description?.trim() ?? null,getIcon: () => PanelsTopLeftIcon,diff --git a/src/features/WorkGallery/WorkPreviewCard.tsx b/src/features/WorkGallery/WorkPreviewCard.tsxindex e892a9599bd..726c61a6c6d 100644--- a/src/features/WorkGallery/WorkPreviewCard.tsx+++ b/src/features/WorkGallery/WorkPreviewCard.tsx@@ -145,6 +145,9 @@ const stopPropagation = (event: MouseEvent) => event.stopPropagation();const workTypeKey = (item: WorkSummaryItem) => {switch (item.resourceType) {+ case 'artboard': {+ return 'work.type.artboard';+ }case 'canvas': {return 'work.type.canvas';}diff --git a/src/features/WorkGallery/WorksTypeTabs.tsx b/src/features/WorkGallery/WorksTypeTabs.tsxindex 8a30a2b2464..03026310147 100644--- a/src/features/WorkGallery/WorksTypeTabs.tsx+++ b/src/features/WorkGallery/WorksTypeTabs.tsx@@ -5,6 +5,7 @@ import { memo, useMemo } from 'react';import { useTranslation } from 'react-i18next';import { useBusinessResourceCategories } from '@/business/client/features/ResourceCategories';+import { useArtboardFeature } from '@/features/Artboard';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';/** Works types every deployment has; business types append after them. */@@ -15,6 +16,12 @@ const WORK_TYPES = [{ key: 'canvas', titleKey: 'docs.works.canvas', url: '/resource/works?works=canvas' },] as const;+const ARTBOARD_TYPE = {+ key: 'artboard',+ titleKey: 'docs.works.artboard',+ url: '/resource/works?works=artboard',+} as const;+interface WorksTypeTabsProps {/** A `?works=` key (`all` / `task` / `document` / `canvas`) or a business category key. */activeKey: string;@@ -28,10 +35,11 @@ const WorksTypeTabs = memo<WorksTypeTabsProps>(({ activeKey }) => {const { t } = useTranslation('file');const navigate = useWorkspaceAwareNavigate();const businessCategories = useBusinessResourceCategories();+ const { enabled: artboardEnabled } = useArtboardFeature();const options = useMemo(() => [- ...WORK_TYPES.map((type) => ({+ ...[...WORK_TYPES, ...(artboardEnabled ? [ARTBOARD_TYPE] : [])].map((type) => ({label: t(type.titleKey),url: type.url,value: type.key as string,@@ -43,7 +51,7 @@ const WorksTypeTabs = memo<WorksTypeTabsProps>(({ activeKey }) => {value: category.key,})),],- [businessCategories, t],+ [artboardEnabled, businessCategories, t],);// Narrower provider keys (linear / github) have no tab; they read as "All".diff --git a/src/features/WorkGallery/const.tsx b/src/features/WorkGallery/const.tsxindex 3f39399be61..2693002aa30 100644--- a/src/features/WorkGallery/const.tsx+++ b/src/features/WorkGallery/const.tsx@@ -7,7 +7,8 @@ import type { ListedWorkType, WorkSkillProvider } from '@lobechat/types';* deep links keep working and per-category tabs can return without a URL* migration.*/-export type WorkGalleryKey = 'all' | 'canvas' | 'document' | 'github' | 'linear' | 'task';+export type WorkGalleryKey =+ 'all' | 'artboard' | 'canvas' | 'document' | 'github' | 'linear' | 'task';/*** How a gallery key narrows the workspace Work list: `type` selects a Work type@@ -24,6 +25,7 @@ const FILTER_BY_KEY = new Map<WorkGalleryKey, WorkGalleryFilter>([['task', { type: 'task' }],['document', { type: 'document' }],['canvas', { type: 'canvas' }],+ ['artboard', { type: 'artboard' }],['linear', { provider: 'linear' }],['github', { provider: 'github' }],]);diff --git a/src/features/WorkGallery/useOpenWork.test.ts b/src/features/WorkGallery/useOpenWork.test.tsindex 2a2e1088901..679e21bf9a8 100644--- a/src/features/WorkGallery/useOpenWork.test.ts+++ b/src/features/WorkGallery/useOpenWork.test.ts@@ -4,9 +4,10 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import { useOpenWork } from './useOpenWork';-const { createModal, getVersion } = vi.hoisted(() => ({+const { createModal, getVersion, openArtboard } = vi.hoisted(() => ({createModal: vi.fn(),getVersion: vi.fn(),+ openArtboard: vi.fn(),}));vi.mock('@lobehub/ui', () => ({ createModal }));@@ -14,12 +15,13 @@ vi.mock('@/services/canvas', () => ({ canvasService: { getVersion } }));vi.mock('@/features/Workspace/useWorkspaceAwareNavigate', () => ({useWorkspaceAwareNavigate: () => vi.fn(),}));+vi.mock('@/features/Artboard/openArtboard', () => ({ openArtboard }));vi.mock('@/features/Work/descriptors', () => ({getWorkTypeDescriptor: () => ({- getOpenTarget: (item: WorkSummaryItem) => ({- canvasId: item.resourceId,- kind: 'canvas',- }),+ getOpenTarget: (item: WorkSummaryItem) =>+ item.type === 'artboard'+ ? { artboardId: item.resourceId, kind: 'artboard' }+ : { canvasId: item.resourceId, kind: 'canvas' },}),isSafeExternalUrl: () => true,}));@@ -47,3 +49,14 @@ describe('useOpenWork Canvas entry', () => {expect(window.open).not.toHaveBeenCalled();});});++describe('useOpenWork Artboard entry', () => {+ it('hands the board to the artboard opener', () => {+ const { result } = renderHook(() => useOpenWork());+ act(() => {+ result.current({ resourceId: 'art_1', type: 'artboard' } as WorkSummaryItem);+ });++ expect(openArtboard).toHaveBeenCalledWith('art_1');+ });+});diff --git a/src/features/WorkGallery/useOpenWork.ts b/src/features/WorkGallery/useOpenWork.tsindex 21d9577b742..e8181e49fde 100644--- a/src/features/WorkGallery/useOpenWork.ts+++ b/src/features/WorkGallery/useOpenWork.ts@@ -2,6 +2,7 @@ import type { WorkSummaryItem } from '@lobechat/types';import { useCallback } from 'react';import { taskDetailPath } from '@/features/AgentTasks/shared/taskDetailPath';+import { openArtboard } from '@/features/Artboard/openArtboard';import { openCanvasModal } from '@/features/CanvasModal/loader';import { openDocumentModal } from '@/features/DocumentModal/loader';import { getWorkTypeDescriptor, isSafeExternalUrl } from '@/features/Work/descriptors';@@ -21,6 +22,10 @@ export const useOpenWork = () => {if (!openTarget) return;switch (openTarget.kind) {+ case 'artboard': {+ void openArtboard(openTarget.artboardId);+ return;+ }case 'canvas': {void openCanvasModal(openTarget.canvasId, openTarget.version);return;diff --git a/src/libs/next/config/define-config.test.ts b/src/libs/next/config/define-config.test.tsindex 579792c6c00..9cce3361b84 100644--- a/src/libs/next/config/define-config.test.ts+++ b/src/libs/next/config/define-config.test.ts@@ -94,6 +94,21 @@ describe('defineConfig', () => {{ key: 'x-robots-tag', value: 'noindex, nofollow' },]);});++ it('lets the app frame artboard files while every other page refuses to be framed', async () => {+ vi.stubEnv('ENABLED_CSP', '1');+ const headersOf = async (url: string) =>+ (await unstable_getResponseFromNextConfig({ nextConfig: defineConfig({}), url })).headers;++ const page = await headersOf('https://app.example.com/settings');+ const file = await headersOf('https://app.example.com/artboard-files/tok/pages/a.html');++ expect(page.get('x-frame-options')).toBe('DENY');+ expect(page.get('content-security-policy')).toBe("frame-ancestors 'none';");+ expect(file.get('x-frame-options')).toBeNull();+ expect(file.get('content-security-policy')).toBeNull();+ expect(file.get('x-robots-tag')).toBe('all');+ });});it('disables Next.js agent rule injection', () => {diff --git a/src/libs/next/config/define-config.ts b/src/libs/next/config/define-config.tsindex 789e23a4572..b7965cdac14 100644--- a/src/libs/next/config/define-config.ts+++ b/src/libs/next/config/define-config.ts@@ -102,31 +102,28 @@ export function defineConfig(config: CustomNextConfig) {...config.experimental,},async headers() {- const securityHeaders = [- {- key: 'x-robots-tag',- value: 'all',- },- ];-- if (shouldUseCSP) {- securityHeaders.push(- {- key: 'X-Frame-Options',- value: 'DENY',- },- {- key: 'Content-Security-Policy',- value: "frame-ancestors 'none';",- },- );- }+ // Artboard board pages are framed by the app itself; their route sends its own sandbox CSP.+ const frameDenyHeaders = shouldUseCSP+ ? [+ {+ key: 'X-Frame-Options',+ value: 'DENY',+ },+ {+ key: 'Content-Security-Policy',+ value: "frame-ancestors 'none';",+ },+ ]+ : [];return [{- headers: securityHeaders,+ headers: [{ key: 'x-robots-tag', value: 'all' }],source: '/:path*',},+ ...(frameDenyHeaders.length+ ? [{ headers: frameDenyHeaders, source: '/((?!artboard-files/).*)' }]+ : []),// Agent Share visitor pages live under `/agent/:slugOrId` and are// reachable by anyone holding the link. Keep them out of search// indexes (privacy) — the SPA shell is static per variant, so adiff --git a/src/services/aiAgent.execAgentTask.test.ts b/src/services/aiAgent.execAgentTask.test.tsindex a9eed4984b1..e8387867159 100644--- a/src/services/aiAgent.execAgentTask.test.ts+++ b/src/services/aiAgent.execAgentTask.test.ts@@ -3,6 +3,11 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';import { aiAgentService } from './aiAgent';const mocks = vi.hoisted(() => ({ execAgent: vi.fn(), llmExecutor: vi.fn() }));+const { flags } = vi.hoisted(() => ({+ flags: { includeArtboardWorks: false, includeFileWorks: true },+}));++vi.mock('./workTypeOptIn', () => ({ workTypeOptIn: () => flags }));vi.mock('@/services/llmRelay', () => ({ buildLlmExecutorDeclaration: mocks.llmExecutor }));@@ -13,6 +18,7 @@ vi.mock('@/libs/trpc/client', () => ({describe('aiAgentService.execAgentTask', () => {beforeEach(() => {vi.clearAllMocks();+ flags.includeArtboardWorks = false;});// The server renames a mirrored group member terminal to `member_runtime_end`@@ -29,6 +35,13 @@ describe('aiAgentService.execAgentTask', () => {);});+ it('declares artboard Works separately when the feature is enabled', async () => {+ flags.includeArtboardWorks = true;+ mocks.execAgent.mockResolvedValueOnce({ success: true });+ await aiAgentService.execAgentTask({ agentId: 'agt-1', prompt: 'hi' });+ expect(mocks.execAgent.mock.calls[0][0].streamFeatures).toContain('artboard_works');+ });+// Inside the `agent_llm_relay` rollout the tab offers to execute relayed LLM// calls; the server only relays to a run that carries this declaration.it('declares this tab as an LLM relay executor when the rollout includes it', async () => {diff --git a/src/services/aiAgent.ts b/src/services/aiAgent.tsindex cf5bcfda902..7fd2e3a3120 100644--- a/src/services/aiAgent.ts+++ b/src/services/aiAgent.ts@@ -21,10 +21,16 @@ import { canUseGatewayProtocolV2 } from '@/helpers/gatewayProtocol';import { createWorkspaceLambdaClient, lambdaClient } from '@/libs/trpc/client';import { buildLlmExecutorDeclaration } from '@/services/llmRelay';+import { workTypeOptIn } from './workTypeOptIn';+export type { ExecAgentResult, ScheduleAgentRunParams, ScheduleAgentRunResult };/** Gateway stream features every run started from this client handles. */-const STREAM_FEATURES: AgentStreamClientFeature[] = ['file_works', 'member_runtime_end'];+const streamFeatures = (): AgentStreamClientFeature[] => [+ 'file_works',+ 'member_runtime_end',+ ...(workTypeOptIn().includeArtboardWorks ? ['artboard_works' as const] : []),+];/** An older server's strict input schema rejected the `streamFeatures` key. */const isUnknownStreamFeaturesError = (error: unknown): boolean => {@@ -356,7 +362,7 @@ class AiAgentService {clientProtocol,...(llmExecutor && { llmExecutor }),...params,- streamFeatures: STREAM_FEATURES,+ streamFeatures: streamFeatures(),},options,);@@ -384,7 +390,7 @@ class AiAgentService {clientProtocol,...(llmExecutor && { llmExecutor }),...params.request,- streamFeatures: STREAM_FEATURES,+ streamFeatures: streamFeatures(),},});}@@ -551,7 +557,7 @@ class AiAgentService {let result: Awaited<ReturnType<typeof mutate>>;try {// This client subscribes to the continuation it starts.- result = await mutate({ ...params, streamFeatures: STREAM_FEATURES });+ result = await mutate({ ...params, streamFeatures: streamFeatures() });} catch (error) {// A server from before `streamFeatures` validates this input strictly and// rejects the unknown key before claiming anything, so resending the samediff --git a/src/services/artboard.ts b/src/services/artboard.tsnew file mode 100644index 00000000000..71199d8658e--- /dev/null+++ b/src/services/artboard.ts@@ -0,0 +1,83 @@+import type {+ ArtboardCommentAnchor,+ ArtboardCommentThreadView,+ ArtboardItem,+} from '@lobechat/types';++import { lambdaClient } from '@/libs/trpc/client';++export interface ArtboardView {+ artboard: ArtboardItem;+ fileBaseUrl: string | null;+}++export interface ArtboardFinalize {+ acceptanceId: string;+ artboard: ArtboardItem;+}++export interface ArtboardCommentInput {+ anchor?: ArtboardCommentAnchor;+ boardId?: string;+ clientId: string;+ content: string;+ groupId?: string;+ pageId?: string;+}++class ArtboardService {+ addComment = (id: string, input: ArtboardCommentInput) =>+ lambdaClient.artboard.addComment.mutate({ id, ...input });++ chooseBoard = (+ id: string,+ roundId: string,+ boardId: string,+ ): Promise<{ artboard: ArtboardItem }> =>+ lambdaClient.artboard.chooseBoard.mutate({ boardId, id, roundId });++ deliverComments = (id: string): Promise<ArtboardCommentThreadView[]> =>+ lambdaClient.artboard.deliverComments.mutate({ id });++ countUndeliveredComments = (id: string): Promise<number> =>+ lambdaClient.artboard.countUndeliveredComments.query({ id });++ finalize = (id: string, revision: number): Promise<ArtboardFinalize> =>+ lambdaClient.artboard.finalize.mutate({ id, revision });++ get = (id: string): Promise<ArtboardView> => lambdaClient.artboard.get.query({ id });++ getConversation = (topicId: string) => lambdaClient.topic.getTopicDetail.query({ id: topicId });++ getPublish = (id: string) => lambdaClient.artboard.getPublish.query({ id });++ getRevision = (id: string) => lambdaClient.artboard.getRevision.query({ id });++ listByProject = (projectId: string) => lambdaClient.artboard.listByProject.query({ projectId });++ listComments = (id: string): Promise<ArtboardCommentThreadView[]> =>+ lambdaClient.artboard.listComments.query({ id });++ publish = (id: string): Promise<{ url: string }> => lambdaClient.artboard.publish.mutate({ id });++ reopenComment = (commentId: string) => lambdaClient.artboard.reopenComment.mutate({ commentId });++ replyComment = (commentId: string, clientId: string, content: string) =>+ lambdaClient.artboard.replyComment.mutate({ clientId, commentId, content });++ resolveComment = (commentId: string) =>+ lambdaClient.artboard.resolveComment.mutate({ commentId });++ submitRound = (id: string, roundId: string): Promise<{ artboard: ArtboardItem }> =>+ lambdaClient.artboard.submitRound.mutate({ id, roundId });++ submitRounds = (+ id: string,+ roundIds: string[],+ ): Promise<{ artboard: ArtboardItem; submitted: number }> =>+ lambdaClient.artboard.submitRounds.mutate({ id, roundIds });++ unpublish = (id: string) => lambdaClient.artboard.unpublish.mutate({ id });+}++export const artboardService = new ArtboardService();diff --git a/src/services/message/index.ts b/src/services/message/index.tsindex 83380157cfb..e5e4f3fc3af 100644--- a/src/services/message/index.ts+++ b/src/services/message/index.ts@@ -20,6 +20,7 @@ import { type HeatmapsProps } from '@lobehub/charts';import pMap from 'p-map';import { lambdaClient } from '@/libs/trpc/client';+import { workTypeOptIn } from '@/services/workTypeOptIn';import { abortableRequest } from '../utils/abortableRequest';import type { MessageListPage, MessageRoundCursor } from './cache';@@ -186,7 +187,7 @@ export class MessageService {// legacy set. See resolveAllowedWorkTypes.const data = await lambdaClient.message.getMessages.query({...params,- includeFileWorks: true,+ ...workTypeOptIn(),});return data as unknown as UIChatMessage[];@@ -266,7 +267,7 @@ export class MessageService {const data = await lambdaClient.message.getMessages.query({...params,before: { createdAt: new Date(cursor.createdAt), id: cursor.id },- includeFileWorks: true,+ ...workTypeOptIn(),});return { messages: data as unknown as UIChatMessage[] };diff --git a/src/services/message/roundCursorPage.ts b/src/services/message/roundCursorPage.tsindex 94e731d36ef..27c2dfed86a 100644--- a/src/services/message/roundCursorPage.ts+++ b/src/services/message/roundCursorPage.ts@@ -2,6 +2,7 @@ import type { UIChatMessage } from '@lobechat/types';import { type MessageListQueryContext, normalizeMessageListQueryContext } from '@/libs/swr/keys';import { lambdaClient } from '@/libs/trpc/client';+import { workTypeOptIn } from '@/services/workTypeOptIn';import type { MessageListPage, MessageRoundCursor } from './cache';@@ -40,7 +41,7 @@ export const toRoundCursorQueryInput = (countBudget: params.projectToolPayloads ? GATEWAY_PAGE_ROW_BUDGET : MESSAGE_PAGE_ROW_BUDGET,cursor,groupId: params.groupId,- includeFileWorks: true,+ ...workTypeOptIn(),projectToolPayloads: params.projectToolPayloads,// The row budget is the real bound; ask for as many whole rounds as it holds.roundLimit: MESSAGE_PAGE_ROW_BUDGET,@@ -93,7 +94,7 @@ export const toForwardRoundCursorQueryInput = (cursor,direction: 'forward' as const,groupId: params.groupId,- includeFileWorks: true,+ ...workTypeOptIn(),roundLimit: size.roundLimit,topicId: params.topicId,topicShareId: params.topicShareId,diff --git a/src/services/message/server.test.ts b/src/services/message/server.test.tsindex 3577acd7bae..96a2b3e78a2 100644--- a/src/services/message/server.test.ts+++ b/src/services/message/server.test.ts@@ -34,6 +34,7 @@ describe('MessageService', () => {// The service opts in to file-type works; everything else passes through untouched.expect(lambdaClient.message.getMessages.query).toHaveBeenCalledWith({...params,+ includeArtboardWorks: false,includeFileWorks: true,});});diff --git a/src/services/work.ts b/src/services/work.tsindex 74e76f68e61..083b8ba244b 100644--- a/src/services/work.ts+++ b/src/services/work.ts@@ -21,6 +21,7 @@ import { mutate } from '@/libs/swr';import { matchDomain, workKeys } from '@/libs/swr/keys';import { lambdaClient } from '@/libs/trpc/client';import { revalidateConversationMessages } from '@/services/message/replica';+import { workTypeOptIn } from '@/services/workTypeOptIn';import { topicPullRequestsResource } from '@/store/work/projection';/** One cursor page of the workspace-wide Work list (resource page 产物 gallery). */@@ -72,7 +73,7 @@ class WorkService {threadId?: string | null;topicId?: string | null;}): Promise<WorkListItem[]> =>- lambdaClient.work.listByConversation.query({ ...params, includeFileWorks: true });+ lambdaClient.work.listByConversation.query({ ...params, ...workTypeOptIn() });listByWorkspace = async (params: {cursor?: string | null;@@ -82,19 +83,19 @@ class WorkService {type?: ListedWorkType | null;visibility?: WorkVisibility;}): Promise<WorkSummaryPage> =>- lambdaClient.work.listByWorkspace.query({ ...params, includeFileWorks: true });+ lambdaClient.work.listByWorkspace.query({ ...params, ...workTypeOptIn() });listByRootOperation = async (params: {limit?: number;rootOperationId?: string | null;}): Promise<WorkVersionEventItem[]> =>- lambdaClient.work.listByRootOperation.query({ ...params, includeFileWorks: true });+ lambdaClient.work.listByRootOperation.query({ ...params, ...workTypeOptIn() });listByRootOperations = async (params: {limit?: number;rootOperationIds?: string[] | null;}): Promise<WorkVersionEventMap> =>- lambdaClient.work.listByRootOperations.query({ ...params, includeFileWorks: true });+ lambdaClient.work.listByRootOperations.query({ ...params, ...workTypeOptIn() });listVersions = async (workId: string): Promise<WorkVersionItem[]> =>lambdaClient.work.listVersions.query({ workId });diff --git a/src/services/workTypeOptIn.test.ts b/src/services/workTypeOptIn.test.tsnew file mode 100644index 00000000000..8129c7135f6--- /dev/null+++ b/src/services/workTypeOptIn.test.ts@@ -0,0 +1,29 @@+import { describe, expect, it, vi } from 'vitest';++import { workTypeOptIn, workTypeOptInHeaders } from './workTypeOptIn';++const { state } = vi.hoisted(() => ({ state: { current: undefined as unknown } }));+vi.mock('@/store/serverConfig/store', () => ({ getServerConfigStoreState: () => state.current }));++describe('workTypeOptIn', () => {+ it('asks for artboard Works only while the artboard flag is on', () => {+ state.current = { featureFlags: { enableArtboard: true } };+ expect(workTypeOptIn()).toEqual({ includeArtboardWorks: true, includeFileWorks: true });++ state.current = { featureFlags: {} };+ expect(workTypeOptIn().includeArtboardWorks).toBe(false);+ });++ it('declares the same opt-in as a request header', () => {+ state.current = { featureFlags: { enableArtboard: true } };+ expect(workTypeOptInHeaders()).toEqual({ 'x-lobe-work-types': 'artboard,file' });++ state.current = { featureFlags: {} };+ expect(workTypeOptInHeaders()).toEqual({ 'x-lobe-work-types': 'file' });+ });++ it('keeps the file opt-in before the server config has loaded', () => {+ state.current = undefined;+ expect(workTypeOptIn()).toEqual({ includeArtboardWorks: false, includeFileWorks: true });+ });+});diff --git a/src/services/workTypeOptIn.ts b/src/services/workTypeOptIn.tsnew file mode 100644index 00000000000..89791cda74b--- /dev/null+++ b/src/services/workTypeOptIn.ts@@ -0,0 +1,18 @@+import { WORK_TYPES_HEADER } from '@lobechat/const';++import { serverConfigSelectors } from '@/store/serverConfig/selectors';+import { getServerConfigStoreState } from '@/store/serverConfig/store';++export const workTypeOptIn = () => {+ const config = getServerConfigStoreState();+ return {+ includeArtboardWorks: !!config && serverConfigSelectors.enableArtboard(config),+ includeFileWorks: true,+ };+};++export const workTypeOptInHeaders = (): Record<string, string> => {+ const { includeArtboardWorks, includeFileWorks } = workTypeOptIn();+ const types = [includeArtboardWorks && 'artboard', includeFileWorks && 'file'].filter(Boolean);+ return { [WORK_TYPES_HEADER]: types.join(',') };+};diff --git a/src/store/chat/slices/agentRun/actions/transports/client/interventionAudits.ts b/src/store/chat/slices/agentRun/actions/transports/client/interventionAudits.tsindex 33c6ca9a521..8569d963610 100644--- a/src/store/chat/slices/agentRun/actions/transports/client/interventionAudits.ts+++ b/src/store/chat/slices/agentRun/actions/transports/client/interventionAudits.ts@@ -1,3 +1,4 @@+import { ACTIVATE_TOOLS_AUDIT, activateToolsAudit } from '@lobechat/builtin-tool-activator';import {AGENT_ACCOUNT_OUTBOUND_AUDIT,agentAccountOutboundAudit,@@ -21,6 +22,7 @@ export const clientInterventionAudits = {loadGrants: () => getUserStoreState().settings.tool?.widgetDryRunGrants,loadVersion: (widgetId, versionId) => dashboardService.getVersion(widgetId, versionId),}),+ [ACTIVATE_TOOLS_AUDIT]: activateToolsAudit,[AGENT_ACCOUNT_OUTBOUND_AUDIT]: agentAccountOutboundAudit,// Without it a client-driven run falls back to the manifest's `never` and// a permanent delete would run unasked.diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.tsindex 4088c7c0269..db5619f40d0 100644--- a/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor.ts@@ -105,6 +105,7 @@ import {shouldHydrateResumeReplay,} from './resumeReplay';import { buildLobeHubSessionEnv } from './sessionEnv';+import { createShellWorkScan } from './shellWorkScan';import {createSubagentStoreDispatcher,type SubagentStoreDispatcher,@@ -813,6 +814,12 @@ export const executeHeterogeneousAgent = async (createMessage: messageService.createMessage,flush: messageWriteBatcher.flush,});+ const shellWorkScan = createShellWorkScan({+ persist: pendingCreateLedger.ensureParentPersisted,+ refresh: workService.refreshConversation,+ register: workService.registerShellWorksForRun,+ topicId: context.topicId,+ });/*** Retry each failed row create, then each stashed main-assistant patch, once.@@ -1500,6 +1507,7 @@ export const executeHeterogeneousAgent = async (});toolMsgIdByCallId.set(x.payload.id, x.toolMessageId);mainToolCallIds.add(x.payload.id);+ shellWorkScan.track(x.payload.id, intent.assistantMessageId, x.payload.arguments);createClientRow(x.toolMessageId, toolMsg, { operationId });}@@ -1532,6 +1540,7 @@ export const executeHeterogeneousAgent = async (intent.pluginState,);const toolMsgId = toolMsgIdByCallId.get(intent.toolCallId);+ shellWorkScan.resolve(intent.toolCallId, toolMsgId, intent.isError);if (toolMsgId && mainToolCallIds.has(intent.toolCallId)) {const update: Partial<UIChatMessage> = { content: intent.content };if (intent.pluginState) (update as any).pluginState = intent.pluginState;@@ -2238,36 +2247,11 @@ export const executeHeterogeneousAgent = async (status: 'completed',});- // Shell Work scan for this LOCAL run: no server operation exists, so- // the completion-time scan (`registerWorksForOperation`) can never- // fire — report the run's persisted tool message ids to the server,- // which replays the same scan (gh CLI → github Work cards) under a- // synthetic anchor-derived rootOperationId. Best-effort and- // idempotent server-side; a failure only costs the card, never the- // run. Mirrors the gateway path's error-skip: only clean completions- // scan. Capped to the server's input limit — a >500-tool run keeps- // its most recent calls, which are the ones that own trailing- // create/edit output.- const toolMessageIds = [...new Set(toolMsgIdByCallId.values())].slice(-500);- // Topicless runs can't scan: the server validates the anchor against- // the claimed topic, and a card has no conversation to render in.- if (toolMessageIds.length > 0 && mainState.currentAssistantId && context.topicId) {- try {- const scan = await workService.registerShellWorksForRun({- anchorMessageId: mainState.currentAssistantId,- messageIds: toolMessageIds,- topicId: context.topicId,- });- if (scan.registered > 0) {- // Re-pull the message list so the anchor's fresh- // `metadata.work.rootOperationId` (and its works payload)- // renders without a manual refresh.- await workService.refreshConversation(context.topicId);- }- } catch (err) {- console.error('[HeterogeneousAgent] Failed to register shell works:', err);- }- }+ // Shell Work scan for this LOCAL run (no server operation exists to+ // run it); see `createShellWorkScan`. Only clean completions scan.+ await shellWorkScan.complete(mainState.currentAssistantId, [+ ...new Set(toolMsgIdByCallId.values()),+ ]);}});},diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/shellWorkScan.test.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/shellWorkScan.test.tsnew file mode 100644index 00000000000..272548c874b--- /dev/null+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/shellWorkScan.test.ts@@ -0,0 +1,89 @@+import { describe, expect, it, vi } from 'vitest';++import { createShellWorkScan } from './shellWorkScan';++const shell = (command: string) => JSON.stringify({ command });++const setup = (registered = 1) => {+ const deps = {+ persist: vi.fn().mockResolvedValue(undefined),+ refresh: vi.fn().mockResolvedValue(undefined),+ register: vi.fn().mockResolvedValue({ failed: 0, registered, rootOperationId: 'root' }),+ topicId: 'tpc_1',+ };+ return { deps, scan: createShellWorkScan(deps) };+};++describe('createShellWorkScan', () => {+ it('registers an artboard create as soon as its result lands, anchored to the issuing message', async () => {+ const { deps, scan } = setup();++ scan.track(+ 'call_1',+ 'msg_step1',+ shell('"$LOBEHUB_CLI" artboard create --task T-1 --ops @a.json'),+ );+ scan.resolve('call_1', 'msg_tool1', false);+ await vi.waitFor(() => expect(deps.refresh).toHaveBeenCalledWith('tpc_1'));++ expect(deps.persist).toHaveBeenCalledWith('msg_step1');+ expect(deps.persist.mock.invocationCallOrder[0]).toBeLessThan(+ deps.register.mock.invocationCallOrder[0],+ );+ expect(deps.register).toHaveBeenCalledWith({+ anchorMessageId: 'msg_step1',+ messageIds: ['msg_tool1'],+ topicId: 'tpc_1',+ });+ });++ // The group shows the cards of its LATEST stamped message, so a completion scan+ // stamping the final message would hide the card the live scan put up.+ it('keeps the completion scan on the live anchor instead of the final message', async () => {+ const { deps, scan } = setup();++ scan.track('call_1', 'msg_step1', shell('lh artboard create --title X'));+ scan.resolve('call_1', 'msg_tool1', false);+ await scan.complete('msg_final', ['msg_tool1', 'msg_tool2']);++ expect(deps.register).toHaveBeenCalledWith({+ anchorMessageId: 'msg_step1',+ messageIds: ['msg_tool1', 'msg_tool2'],+ topicId: 'tpc_1',+ });+ });++ it('leaves other commands and failed calls to the completion scan on the final message', async () => {+ const { deps, scan } = setup();++ scan.track('call_1', 'msg_step1', shell('lh artboard files write art_1 pages/a.html'));+ scan.resolve('call_1', 'msg_tool1', false);+ scan.track('call_2', 'msg_step2', shell('lh artboard create --title X'));+ scan.resolve('call_2', 'msg_tool2', true);+ await scan.complete('msg_final', ['msg_tool1', 'msg_tool2']);++ expect(deps.register).toHaveBeenCalledTimes(1);+ expect(deps.register).toHaveBeenCalledWith({+ anchorMessageId: 'msg_final',+ messageIds: ['msg_tool1', 'msg_tool2'],+ topicId: 'tpc_1',+ });+ });++ // The executor bounds its own write drain before completing; a live scan stuck+ // behind a write that never settles must not hold the run open.+ it('completes without waiting on a live scan whose writes never settle', async () => {+ const { deps, scan } = setup();+ deps.persist.mockReturnValue(new Promise<void>(() => {}));++ scan.track('call_1', 'msg_step1', shell('lh artboard create --title X'));+ scan.resolve('call_1', 'msg_tool1', false);+ await scan.complete('msg_final', ['msg_tool1']);++ expect(deps.register).toHaveBeenCalledWith({+ anchorMessageId: 'msg_step1',+ messageIds: ['msg_tool1'],+ topicId: 'tpc_1',+ });+ });+});diff --git a/src/store/chat/slices/agentRun/actions/transports/hetero/shellWorkScan.ts b/src/store/chat/slices/agentRun/actions/transports/hetero/shellWorkScan.tsnew file mode 100644index 00000000000..6725206d115--- /dev/null+++ b/src/store/chat/slices/agentRun/actions/transports/hetero/shellWorkScan.ts@@ -0,0 +1,98 @@+/**+ * Commands whose Work card should appear while the run is still going. A CLI+ * agent lays an artboard out with `lh artboard create` and then spends minutes+ * writing its board files; the card is the user's way in to watch them land.+ * The server's scanner does the precise parsing — this is only the trigger.+ */+const LIVE_WORK_COMMAND = /\bartboard\s+(?:create|update)\b/;++/** The server scan's input cap; a longer run keeps its most recent calls. */+const MAX_SCAN_MESSAGES = 500;++const commandOf = (args?: string) => {+ try {+ const command: unknown = JSON.parse(args ?? '')?.command;+ return typeof command === 'string' ? command : undefined;+ } catch {+ return undefined;+ }+};++export interface ShellWorkScanDeps {+ /** Make the anchor and every queued tool write durable; throws when the anchor is missing. */+ persist: (anchorMessageId: string) => Promise<void>;+ refresh: (topicId: string) => Promise<void>;+ register: (params: {+ anchorMessageId: string;+ messageIds: string[];+ topicId: string;+ }) => Promise<{ registered: number }>;+ topicId?: string | null;+}++/**+ * Shell Work scan for a desktop-LOCAL hetero run. Such runs have no server+ * operation, so the server replays its shell scan over the tool messages the+ * executor reports (`work.registerShellWorksForRun`):+ *+ * - live: a call in {@link LIVE_WORK_COMMAND} is scanned the moment its result+ * lands, anchored to the assistant message that issued it;+ * - completion: every tool message of the run, on clean completion.+ *+ * Both scans share ONE anchor, the message that issued the first live call: a+ * group renders the cards of its latest stamped message, so stamping the final+ * message too would hide the live card. Scans on one anchor derive the same+ * root id server-side and versions dedupe on `(workId, toolCallId)`, so the+ * completion scan re-reading a live-scanned call adds nothing.+ */+export const createShellWorkScan = ({ persist, refresh, register, topicId }: ShellWorkScanDeps) => {+ const liveCalls = new Map<string, string>();+ let anchorId: string | undefined;+ // One live scan at a time, so their refreshes land in order.+ let liveChain: Promise<void> = Promise.resolve();++ const report = (err: unknown) =>+ console.error('[HeterogeneousAgent] Failed to register shell works:', err);++ const scan = async (topic: string, anchorMessageId: string, messageIds: string[]) => {+ const { registered } = await register({ anchorMessageId, messageIds, topicId: topic });+ // Work summaries ride the message payload; re-pull it so the card renders.+ if (registered > 0) await refresh(topic);+ };++ return {+ /**+ * Clean completion: scan every tool message of the run. Never waits on a+ * live scan — the executor already bounded its own write drain, and a live+ * scan stuck behind a write that never settles must not hold the run open.+ */+ complete: async (finalAssistantId: string | undefined, toolMessageIds: string[]) => {+ const anchor = anchorId ?? finalAssistantId;+ // Topicless runs can't scan: the server checks the anchor against the topic.+ if (!topicId || !anchor || toolMessageIds.length === 0) return;+ await scan(topicId, anchor, toolMessageIds.slice(-MAX_SCAN_MESSAGES)).catch(report);+ },++ /** A main-agent tool call's result landed. */+ resolve: (toolCallId: string, toolMessageId: string | undefined, isError: boolean) => {+ const assistantMessageId = liveCalls.get(toolCallId);+ liveCalls.delete(toolCallId);+ if (!topicId || !assistantMessageId || !toolMessageId || isError) return;+ anchorId ??= assistantMessageId;+ const anchor = anchorId;+ liveChain = liveChain+ .then(async () => {+ // The anchor and this tool result may still sit in the write batcher.+ await persist(anchor);+ await scan(topicId, anchor, [toolMessageId]);+ })+ .catch(report);+ },++ /** A main-agent tool call was issued by `assistantMessageId`. */+ track: (toolCallId: string, assistantMessageId: string, args?: string) => {+ const command = commandOf(args);+ if (command && LIVE_WORK_COMMAND.test(command)) liveCalls.set(toolCallId, assistantMessageId);+ },+ };+};diff --git a/src/store/chat/slices/message/transcript/index.ts b/src/store/chat/slices/message/transcript/index.tsindex fb0930a0305..d550cd2d5df 100644--- a/src/store/chat/slices/message/transcript/index.ts+++ b/src/store/chat/slices/message/transcript/index.ts@@ -41,6 +41,7 @@ import { type StoreSetter } from '@/store/types';import { reconcileAssistantToolLinks } from '../utils/reconcileTools';import { bucketOfKey, createTranscriptLens } from './lens';import { type HeadRequestBoundary, mergeFetchedMessagesWithLocalState } from './mergeFetched';+import { applyStreamingWorks } from './streamingWorks';const log = debug('lobe-store:message-transcript');@@ -386,7 +387,8 @@ const createMessageTranscript = (set: StoreSetter<ChatStore>, get: () => ChatSto};// DB chunk writes can lag behind pushed content, even at an equal- // updatedAt. Keep streamed rows, but allow answers and unseen rows in.+ // updatedAt. Keep streamed rows, but allow answers, Work summaries and+ // unseen rows in.// A parked run must not block the first load of the conversation.const prevDbMessages = current?.items ?? [];const snapshot = snapshots.get(incoming);@@ -411,7 +413,7 @@ const createMessageTranscript = (set: StoreSetter<ChatStore>, get: () => ChatSto// as orphans until the next refresh (see reconcileAssistantToolLinks).const mergedMessages = reconcileAssistantToolLinks(isStreaming- ? reconcileStreamingInterventions(prevDbMessages, incoming)+ ? applyStreamingWorks(reconcileStreamingInterventions(prevDbMessages, incoming), incoming): mergeFetchedMessagesWithLocalState(incoming,prevDbMessages,diff --git a/src/store/chat/slices/message/transcript/streamingWorks.test.ts b/src/store/chat/slices/message/transcript/streamingWorks.test.tsnew file mode 100644index 00000000000..2e7da6917e5--- /dev/null+++ b/src/store/chat/slices/message/transcript/streamingWorks.test.ts@@ -0,0 +1,45 @@+import type { UIChatMessage, WorkSummaryItem } from '@lobechat/types';+import { describe, expect, it } from 'vitest';++import { applyStreamingWorks } from './streamingWorks';++const row = (id: string, extra: Partial<UIChatMessage> = {}) =>+ ({ content: '', id, role: 'assistant', updatedAt: 1, ...extra }) as UIChatMessage;++const work = (id: string, versionId: string) =>+ ({ id, version: { id: versionId } }) as unknown as WorkSummaryItem;++const stamped = { work: { rootOperationId: 'localrun_msg_1' } };++describe('applyStreamingWorks', () => {+ it('carries a Work registered mid-run onto the streamed row without its stale content', () => {+ const local = [row('msg_1', { content: 'streamed so far' }), row('msg_2')];+ const incoming = [+ row('msg_1', { content: 'lagging db', metadata: stamped, works: [work('wk_1', 'v1')] }),+ ];++ const merged = applyStreamingWorks(local, incoming);++ expect(merged[0]).toMatchObject({+ content: 'streamed so far',+ metadata: stamped,+ works: [work('wk_1', 'v1')],+ });+ expect(merged[1]).toBe(local[1]);+ });++ // The transcript sync drops a streaming fetch whose merge returns the same array.+ it('keeps the local array when the rows already show those Works', () => {+ const local = [row('msg_1', { metadata: stamped, works: [work('wk_1', 'v1')] })];+ const incoming = [row('msg_1', { metadata: stamped, works: [work('wk_1', 'v1')] })];++ expect(applyStreamingWorks(local, incoming)).toBe(local);+ });++ it('takes a newer Work version', () => {+ const local = [row('msg_1', { metadata: stamped, works: [work('wk_1', 'v1')] })];+ const incoming = [row('msg_1', { metadata: stamped, works: [work('wk_1', 'v2')] })];++ expect(applyStreamingWorks(local, incoming)[0].works).toEqual([work('wk_1', 'v2')]);+ });+});diff --git a/src/store/chat/slices/message/transcript/streamingWorks.ts b/src/store/chat/slices/message/transcript/streamingWorks.tsnew file mode 100644index 00000000000..6d53d73d0af--- /dev/null+++ b/src/store/chat/slices/message/transcript/streamingWorks.ts@@ -0,0 +1,26 @@+import type { UIChatMessage } from '@lobechat/types';++const worksKey = (message: UIChatMessage) =>+ `${message.metadata?.work?.rootOperationId ?? ''}|${(message.works ?? [])+ .map((work) => `${work.id}:${work.version?.id ?? ''}`)+ .join(',')}`;++/**+ * Work summaries are server-derived: a scan stamps `metadata.work` on an anchor+ * row and the read attaches `works`. The stream never writes either, so a fetch+ * that lands while a run streams can carry them onto the streamed rows — that+ * is how a CLI agent's artboard card shows up while the agent is still writing+ * its boards — without touching any streamed content.+ */+export const applyStreamingWorks = (local: UIChatMessage[], incoming: UIChatMessage[]) => {+ const incomingById = new Map(incoming.map((message) => [message.id, message]));+ let changed = false;+ const merged = local.map((message) => {+ const fetched = incomingById.get(message.id);+ const work = fetched?.metadata?.work;+ if (!fetched?.works?.length || !work || worksKey(fetched) === worksKey(message)) return message;+ changed = true;+ return { ...message, metadata: { ...message.metadata, work }, works: fetched.works };+ });+ return changed ? merged : local;+};diff --git a/src/store/chat/slices/operation/__tests__/actions.test.ts b/src/store/chat/slices/operation/__tests__/actions.test.tsindex 8f574fd85ea..0885bc815ab 100644--- a/src/store/chat/slices/operation/__tests__/actions.test.ts+++ b/src/store/chat/slices/operation/__tests__/actions.test.ts@@ -58,6 +58,20 @@ describe('Operation Actions', () => {expect(merged.editorData?.root.children[2]).toEqual(secondParagraph);});+ it('leaves markdown sent without an editor document to render as markdown', () => {+ const merged = mergeQueuedMessages([+ {+ content: 'Left 1 comment.\n\n> Re: t1 · 首页\n\n太挤了',+ createdAt: 1,+ id: 'q1',+ interruptMode: 'soft',+ },+ ]);++ expect(merged.content).toBe('Left 1 comment.\n\n> Re: t1 · 首页\n\n太挤了');+ expect(merged.editorData).toBeUndefined();+ });+it('should flatten file ids and filesPreview snapshots from queued messages', () => {const merged = mergeQueuedMessages([{diff --git a/src/store/chat/slices/operation/types.ts b/src/store/chat/slices/operation/types.tsindex 0904eb35c39..a8ca2db7c75 100644--- a/src/store/chat/slices/operation/types.ts+++ b/src/store/chat/slices/operation/types.ts@@ -476,6 +476,7 @@ const normalizeQueuedEditorData = (message: QueuedMessage): Record<string, any>};const mergeQueuedEditorData = (messages: QueuedMessage[]): Record<string, any> | undefined => {+ if (!messages.some((message) => message.editorData?.root)) return undefined;const mergedChildren: any[] = [];let baseRoot: Record<string, any> | undefined;diff --git a/src/store/global/initialState.ts b/src/store/global/initialState.tsindex fdb6091a00e..77d6ff3f775 100644--- a/src/store/global/initialState.ts+++ b/src/store/global/initialState.ts@@ -57,6 +57,11 @@ export const canvasTabKey = (canvasId: string) => `${CANVAS_TAB_PREFIX}${canvasIexport const canvasIdOfTab = (tab: string) =>tab.startsWith(CANVAS_TAB_PREFIX) ? tab.slice(CANVAS_TAB_PREFIX.length) : undefined;+export const ARTBOARD_TAB_PREFIX = 'artboard:';+export const artboardTabKey = (artboardId: string) => `${ARTBOARD_TAB_PREFIX}${artboardId}`;+export const artboardIdOfTab = (tab: string) =>+ tab.startsWith(ARTBOARD_TAB_PREFIX) ? tab.slice(ARTBOARD_TAB_PREFIX.length) : undefined;+export const DEFAULT_RESOURCE_MANAGER_COLUMN_WIDTHS = {date: 160,name: 574,diff --git a/src/store/serverConfig/selectors.ts b/src/store/serverConfig/selectors.tsindex ff716b2f914..a90933af6c6 100644--- a/src/store/serverConfig/selectors.ts+++ b/src/store/serverConfig/selectors.ts@@ -8,6 +8,7 @@ export const serverConfigSelectors = {agentIdentityProviders: (s: ServerConfigStore) =>s.serverConfig.agentIdentityProviders ?? EMPTY_PROVIDERS,disableEmailPassword: (s: ServerConfigStore) => s.serverConfig.disableEmailPassword || false,+ enableArtboard: (s: ServerConfigStore) => s.featureFlags.enableArtboard === true,enableBusinessFeatures: (s: ServerConfigStore) => s.serverConfig.enableBusinessFeatures || false,enableEmailVerification: (s: ServerConfigStore) =>s.serverConfig.enableEmailVerification || false,diff --git a/src/store/tool/slices/builtin/executors/artboard.test.ts b/src/store/tool/slices/builtin/executors/artboard.test.tsnew file mode 100644index 00000000000..7af4dc3a78a--- /dev/null+++ b/src/store/tool/slices/builtin/executors/artboard.test.ts@@ -0,0 +1,22 @@+import { describe, expect, it, vi } from 'vitest';++const { onArtboardToolResult } = vi.hoisted(() => ({ onArtboardToolResult: vi.fn() }));+vi.mock('@/features/Artboard/data/onArtboardToolResult', () => ({ onArtboardToolResult }));++const { artboardHookExecutor } = await import('./artboard');++describe('artboardHookExecutor', () => {+ it('hands every artboard tool_end to the board refresh', async () => {+ const result = { state: { artboardId: 'art_1' }, success: true };++ await artboardHookExecutor.onAfterCall({+ apiName: 'updateArtboard',+ identifier: 'builtin-artboard',+ params: {},+ result,+ });++ expect(onArtboardToolResult).toHaveBeenCalledWith({ apiName: 'updateArtboard', result });+ expect(artboardHookExecutor.getApiNames()).toEqual([]);+ });+});diff --git a/src/store/tool/slices/builtin/executors/artboard.ts b/src/store/tool/slices/builtin/executors/artboard.tsnew file mode 100644index 00000000000..0ac14e4e1df--- /dev/null+++ b/src/store/tool/slices/builtin/executors/artboard.ts@@ -0,0 +1,19 @@+import { ArtboardIdentifier } from '@lobechat/builtin-tool-artboard';+import type { ToolAfterCallContext } from '@lobechat/types';+import { BaseExecutor } from '@lobechat/types';++const EMPTY_API_ENUM = {} as Record<string, string>;++// Never invoked: artboard tools run on the server. It exists so tool_end refreshes the board cache+// whether or not a card or board is mounted (Works page, fullscreen board).+class ArtboardHookExecutor extends BaseExecutor<typeof EMPTY_API_ENUM> {+ readonly identifier = ArtboardIdentifier;+ protected readonly apiEnum = EMPTY_API_ENUM;++ onAfterCall = async ({ apiName, result }: ToolAfterCallContext) => {+ const { onArtboardToolResult } = await import('@/features/Artboard/data/onArtboardToolResult');+ await onArtboardToolResult({ apiName, result });+ };+}++export const artboardHookExecutor = new ArtboardHookExecutor();diff --git a/src/store/tool/slices/builtin/executors/catalog.ts b/src/store/tool/slices/builtin/executors/catalog.tsindex 975c587c681..86a3e2ae72a 100644--- a/src/store/tool/slices/builtin/executors/catalog.ts+++ b/src/store/tool/slices/builtin/executors/catalog.ts@@ -17,6 +17,7 @@ import { taskExecutor } from '@lobechat/builtin-tool-task/client/executor';import { videoGenerationExecutor } from '@lobechat/builtin-tool-video-generation/executor';import type { IBuiltinToolExecutor } from '../types';+import { artboardHookExecutor } from './artboard';import {ampExecutor,antigravityExecutor,@@ -67,6 +68,7 @@ export const builtinToolExecutors = [qoderExecutor,traeExecutor,agentBuilderExecutor,+ artboardHookExecutor,agentDocumentsExecutor,agentManagementExecutor,attachmentsExecutor,