🤯 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(artifact): unify Canvas and HTML CLI publishing (#21671)
Inneidc0782743bcb
diff --git a/.gitignore b/.gitignoreindex 89730d19ec3..04e39f7afed 100644--- a/.gitignore+++ b/.gitignore@@ -160,6 +160,10 @@ apps/desktop/resources/cli-package.json# Superpowers plugin brainstorm/spec outputs (local only; do not commit).superpowers/docs/superpowers/++# Local Ryugi artifacts and specifications+.ryugi/+docs/ryugi/.heerogeneous-tracing# Kagura agent runtimediff --git a/apps/cli/README.md b/apps/cli/README.mdindex 89efcf33b00..844f05e14f6 100644--- a/apps/cli/README.md+++ b/apps/cli/README.md@@ -2,6 +2,50 @@LobeHub command-line interface.+## Publish local artifacts++```bash+# Publish ordinary HTML and its referenced local resources+lh artifact publish ./page.html --root . --json++# Read the Canvas component and generation rules+lh artifact guide canvas++# Publish a self-contained Canvas HTML file+lh artifact publish ./report.html --type canvas --json++# The binding remembers the type; subsequent publishes update the same artifact+lh artifact publish ./report.html --json++# Create a separate Canvas and bind future publishes to it+lh artifact publish ./report.html --new --json+```++Bindings and pending operations live in the project's `.lobehub/artifacts.json`.+Retry the same command with unchanged input after a failed Canvas save or publish;+the CLI resumes that operation without creating another Canvas or saved version.+Restore the original input before retrying if you edited it during recovery.+An explicit validation or version-conflict rejection releases the pending save,+so you can correct the file or inspect the latest version before trying again.+If publication explicitly rejects a slug, correct `--slug` and retry with the same+content and target; the CLI reuses the saved Canvas and version.+Canvas bindings are scoped to the authenticated account, server and workspace.++Canvas input is a single HTML file with inline styles, scripts and data, subject+to the Canvas guide's validation and size limits. Publication saves a version in+LobeHub and returns a public URL; it requires a server with Canvas publishing and+a compatible runtime. JSON errors retain any saved Canvas ID and version.++`--slug <name>` requests the readable prefix for a new deployment. Market adds an+eight-character suffix; both HTML and Canvas use the same rule. Existing deployments+retain their address when updated, including older records without a stored label.+JSON `publicUrl` is the direct hosting URL; `shareUrl` is the LobeHub product share+page, and `subdomainLabel` is the actual assigned label when the server returns it.++`--deployment <id>` overrides the deployment for this run without changing the+canonical binding. `--new` and `--deployment` cannot be combined. Changing an+existing artifact's content type requires `--new`.+## Acceptance skillThe acceptance skill is maintained in [lobehub/acceptance](https://github.com/lobehub/acceptance).diff --git a/apps/cli/src/commands/artifact.canvas.test.ts b/apps/cli/src/commands/artifact.canvas.test.tsnew file mode 100644index 00000000000..b3505e03c5c--- /dev/null+++ b/apps/cli/src/commands/artifact.canvas.test.ts@@ -0,0 +1,317 @@+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(),+ runAgentTool: vi.fn(),+ save: vi.fn(),+}));+vi.mock('../api/client', () => ({+ getTrpcClient: async () => ({+ canvas: {+ getPublishContext: { query: mocks.getPublishContext },+ getVersion: { query: mocks.getVersion },+ publish: { mutate: mocks.publish },+ runAgentTool: { mutate: mocks.runAgentTool },+ save: { mutate: mocks.save },+ },+ }),+}));+vi.mock('../settings', () => ({ resolveServerUrl: () => 'https://app.lobehub.com' }));++describe('artifact publish Canvas', () => {+ let root: string;+ let output: ReturnType<typeof vi.spyOn>;+ let exit: ReturnType<typeof vi.spyOn>;+ const manifest = () =>+ JSON.parse(fs.readFileSync(path.join(root, '.lobehub/artifacts.json'), 'utf8'));+ const binding = () => manifest().artifacts['report.html'];+ const payload = () => JSON.parse(output.mock.calls.flat().join('\n'));+ const run = async (...args: string[]) => {+ output.mockClear();+ const program = new Command().exitOverride();+ registerArtifactCommand(program);+ await program.parseAsync(['node', 'lh', 'artifact', ...args]);+ };+ const publish = (...args: string[]) =>+ run('publish', path.join(root, 'report.html'), '--root', root, '--json', ...args);++ beforeEach(() => {+ vi.resetAllMocks();+ root = fs.mkdtempSync(path.join(os.tmpdir(), 'lh-canvas-'));+ fs.writeFileSync(+ path.join(root, 'report.html'),+ '<title>Report</title><lobe-divider></lobe-divider>',+ );+ output = vi.spyOn(console, 'log').mockImplementation(() => {});+ exit = vi.spyOn(process, 'exit').mockImplementation((() => {}) as any);+ mocks.getPublishContext.mockResolvedValue({+ canPublish: true,+ userId: 'u1',+ workspaceId: null,+ });+ mocks.getVersion.mockResolvedValue({ canPublish: true, version: 1 });+ mocks.save.mockResolvedValue({ canvasId: 'cvs_1', workId: 'wk_1', version: 1 });+ mocks.publish.mockResolvedValue({+ deploymentId: 'dep_1',+ publishedVersion: 1,+ url: 'https://report.test',+ });+ mocks.runAgentTool.mockResolvedValue({+ output: { success: true, content: '# Canvas guide\nlobe-stat' },+ });+ });+ afterEach(() => {+ vi.restoreAllMocks();+ fs.rmSync(root, { recursive: true, force: true });+ });++ it('publishes Canvas and records its identity alongside the existing deployment binding', async () => {+ await publish('--type', 'canvas');+ expect(payload()).toMatchObject({+ canvasId: 'cvs_1',+ id: 'dep_1',+ publicUrl: 'https://report.test',+ version: 1,+ });+ expect(binding()).toMatchObject({+ type: 'canvas',+ canvasId: 'cvs_1',+ deploymentId: 'dep_1',+ version: 1,+ });+ expect(binding().pendingCreateKey).toBeUndefined();+ expect(mocks.save.mock.calls[0][0].html).toContain('lobe-divider');+ });++ it('inherits the bound type and updates the same Canvas on subsequent publishes', async () => {+ await publish('--type', 'canvas');+ mocks.save.mockResolvedValueOnce({ canvasId: 'cvs_1', workId: 'wk_1', version: 2 });+ mocks.publish.mockResolvedValueOnce({+ deploymentId: 'dep_1',+ publishedVersion: 2,+ url: 'https://report.test',+ });+ await publish();+ expect(payload()).toMatchObject({ canvasId: 'cvs_1', version: 2 });+ expect(mocks.save.mock.calls[1][0]).toMatchObject({ canvasId: 'cvs_1', expectedVersion: 1 });+ expect(mocks.publish.mock.calls[1][0]).toMatchObject({ canvasId: 'cvs_1', version: 2 });+ });++ it('recovers a save whose response was lost using the persisted operation key', async () => {+ mocks.save.mockRejectedValueOnce(new Error('Response lost'));+ await publish('--type', 'canvas');+ expect(exit).toHaveBeenCalledWith(1);+ expect(payload()).toMatchObject({ success: false });+ const key = binding().pendingCreateKey;+ expect(key).toEqual(expect.any(String));+ await publish();+ expect(mocks.save.mock.calls[1][0].requestId).toBe(key);+ expect(payload().canvasId).toBe('cvs_1');+ });++ it('retries a failed publication without creating another saved version', async () => {+ mocks.publish.mockRejectedValueOnce(new Error('Publication result unknown'));+ await publish('--type', 'canvas');+ expect(payload()).toMatchObject({ success: false, canvasId: 'cvs_1', version: 1 });+ await publish();+ expect(mocks.save).toHaveBeenCalledTimes(1);+ expect(payload()).toMatchObject({ id: 'dep_1', version: 1 });+ });++ it('keeps --new pending across a failed publication and rebinds only after success', async () => {+ await publish('--type', 'canvas');+ mocks.save.mockResolvedValueOnce({ canvasId: 'cvs_new', workId: 'wk_new', version: 1 });+ mocks.publish.mockRejectedValueOnce(new Error('Lost'));+ await publish('--new');+ expect(binding().canvasId).toBe('cvs_1');+ expect(mocks.save.mock.calls[1][0].canvasId).toBeUndefined();+ await publish('--new');+ expect(mocks.save).toHaveBeenCalledTimes(2);+ expect(binding().canvasId).toBe('cvs_new');+ });++ it('preserves the canonical binding when using a temporary deployment', async () => {+ await publish('--type', 'canvas');+ const original = binding();+ await publish('--deployment', 'dep_once');+ expect(mocks.publish.mock.calls.at(-1)?.[0].deploymentId).toBe('dep_once');+ expect(binding()).toEqual(original);+ });++ it('refuses changed content during recovery instead of using an old request key', async () => {+ mocks.save.mockRejectedValueOnce(new Error('Lost'));+ await publish('--type', 'canvas');+ fs.writeFileSync(path.join(root, 'report.html'), '<h1>Changed</h1>');+ await publish();+ expect(payload()).toMatchObject({+ success: false,+ error: expect.stringMatching(/pending|changed/i),+ });+ expect(mocks.save).toHaveBeenCalledTimes(1);+ });++ it('allows fixing content after the server definitively rejects a save', async () => {+ mocks.save.mockRejectedValueOnce(+ Object.assign(new Error('Invalid Canvas'), { data: { code: 'BAD_REQUEST' } }),+ );+ await publish('--type', 'canvas');+ expect(payload().success).toBe(false);+ fs.writeFileSync(path.join(root, 'report.html'), '<h1>Fixed</h1>');+ await publish();+ expect(payload().canvasId).toBe('cvs_1');+ expect(mocks.save).toHaveBeenCalledTimes(2);+ });++ it('reads a fresh expected version on an explicit retry after a save conflict', async () => {+ await publish('--type', 'canvas');+ mocks.save.mockRejectedValueOnce(+ Object.assign(new Error('Canvas version conflict'), { data: { code: 'CONFLICT' } }),+ );+ await publish();+ expect(payload().success).toBe(false);+ mocks.getVersion.mockResolvedValueOnce({ canPublish: true, version: 2 });+ await publish();+ expect(mocks.save.mock.calls.at(-1)?.[0].expectedVersion).toBe(2);+ expect(payload().canvasId).toBe('cvs_1');+ });++ it('restores an unbound one-off deployment after retrying a lost publish response', async () => {+ mocks.publish.mockRejectedValueOnce(new Error('Response lost'));+ await publish('--type', 'canvas', '--deployment', 'dep_once');+ await publish('--type', 'canvas', '--deployment', 'dep_once');+ expect(binding()).toEqual({});+ });++ it('refuses a damaged saved version without publishing or overwriting recovery data', async () => {+ mocks.publish.mockRejectedValueOnce(new Error('Response lost'));+ await publish('--type', 'canvas');+ const damaged = manifest();+ delete damaged.artifacts['report.html'].pendingCanvas.saved.version;+ const file = path.join(root, '.lobehub/artifacts.json');+ const content = JSON.stringify(damaged);+ fs.writeFileSync(file, content);+ await expect(publish()).rejects.toThrow();+ expect(mocks.publish).toHaveBeenCalledTimes(1);+ expect(fs.readFileSync(file, 'utf8')).toBe(content);+ });++ it('refuses a different account or workspace before touching a bound Canvas', async () => {+ await publish('--type', 'canvas');+ mocks.getPublishContext.mockResolvedValueOnce({+ canPublish: true,+ userId: 'u2',+ workspaceId: null,+ });+ await publish();+ expect(payload().success).toBe(false);+ expect(mocks.save).toHaveBeenCalledTimes(1);+ mocks.getPublishContext.mockResolvedValueOnce({+ canPublish: true,+ userId: 'u1',+ workspaceId: 'ws_other',+ });+ await publish();+ expect(payload().success).toBe(false);+ expect(mocks.save).toHaveBeenCalledTimes(1);+ });++ it('rejects switching the bound type without --new', async () => {+ await publish('--type', 'canvas');+ await publish('--type', 'html');+ expect(exit).toHaveBeenCalledWith(1);+ expect(binding().canvasId).toBe('cvs_1');+ });++ it('prints the shared Canvas guide through the artifact command', async () => {+ await run('guide', 'canvas');+ expect(output.mock.calls.flat().join('\n')).toContain('# Canvas guide');+ });++ it('accepts a custom slug and returns both hosting and product share URLs', async () => {+ mocks.publish.mockResolvedValueOnce({+ deploymentId: 'dep_1',+ publishedVersion: 1,+ url: 'https://sales-report-1234abcd.lobe.page',+ subdomainLabel: 'sales-report-1234abcd',+ });+ await publish('--type', 'canvas', '--slug', 'sales-report');+ expect(payload()).toMatchObject({+ publicUrl: 'https://sales-report-1234abcd.lobe.page',+ shareUrl: 'https://app.lobehub.com/share/artifact/dep_1',+ subdomainLabel: 'sales-report-1234abcd',+ });+ expect(mocks.publish.mock.calls[0][0].requestedSlug).toBe('sales-report');+ });++ it.each([+ ['static', 'sales-report'],+ [' ', 'sales-report'],+ ['a'.repeat(256), undefined],+ ])('allows correcting a rejected slug %s without saving another Canvas', async (slug, fixed) => {+ mocks.publish.mockRejectedValueOnce(+ Object.assign(new Error('Invalid slug'), { data: { code: 'BAD_REQUEST' } }),+ );+ await publish('--type', 'canvas', '--slug', slug);+ expect(payload().success).toBe(false);+ await publish(...(fixed ? ['--slug', fixed] : []));+ expect(payload()).toMatchObject({ id: 'dep_1', canvasId: 'cvs_1', version: 1 });+ expect(mocks.publish.mock.calls.at(-1)?.[0].requestedSlug).toBe(fixed);+ expect(mocks.save).toHaveBeenCalledTimes(1);+ });++ it('locks the corrected slug again when its publication result is unknown', async () => {+ mocks.publish+ .mockRejectedValueOnce(+ Object.assign(new Error('Invalid slug'), { data: { code: 'BAD_REQUEST' } }),+ )+ .mockRejectedValueOnce(new Error('Response lost'));+ await publish('--type', 'canvas', '--slug', 'static');+ await publish('--slug', 'fixed');+ expect(mocks.publish).toHaveBeenCalledTimes(2);+ await publish('--slug', 'another');+ expect(payload().success).toBe(false);+ expect(mocks.publish).toHaveBeenCalledTimes(2);+ await publish('--slug', 'fixed');+ expect(payload().id).toBe('dep_1');+ expect(mocks.save).toHaveBeenCalledTimes(1);+ });++ it('still refuses changed content after a slug rejection', async () => {+ mocks.publish.mockRejectedValueOnce(+ Object.assign(new Error('Invalid slug'), { data: { code: 'BAD_REQUEST' } }),+ );+ await publish('--type', 'canvas', '--slug', 'static');+ fs.writeFileSync(path.join(root, 'report.html'), '<h1>Changed</h1>');+ await publish('--slug', 'fixed');+ expect(payload().success).toBe(false);+ expect(mocks.publish).toHaveBeenCalledTimes(1);+ expect(mocks.save).toHaveBeenCalledTimes(1);+ });++ it.each(['new', 'deployment'])(+ 'preserves the %s target while correcting a rejected slug',+ async (target) => {+ await publish('--type', 'canvas');+ const original = binding();+ const options = target === 'new' ? ['--new'] : ['--deployment', 'dep_once'];+ mocks.save.mockResolvedValueOnce({ canvasId: 'cvs_next', workId: 'wk_next', version: 1 });+ mocks.publish.mockRejectedValueOnce(+ Object.assign(new Error('Invalid slug'), { data: { code: 'BAD_REQUEST' } }),+ );+ await publish(...options, '--slug', 'static');+ await publish(...options, '--slug', 'fixed');+ expect(payload()).toMatchObject({ id: 'dep_1', canvasId: 'cvs_next', version: 1 });+ expect(mocks.save).toHaveBeenCalledTimes(2);+ expect(binding()).toMatchObject(target === 'new' ? { canvasId: 'cvs_next' } : original);+ },+ );+});diff --git a/apps/cli/src/commands/artifact.test.ts b/apps/cli/src/commands/artifact.test.tsindex 9d72248fd76..28b2b0662cd 100644--- a/apps/cli/src/commands/artifact.test.ts+++ b/apps/cli/src/commands/artifact.test.ts@@ -159,15 +159,15 @@ describe('artifact publish', () => {expect(readManifest().artifacts['index.html']).toEqual({ deploymentId: 'dep-1' });});- it('prints the product share URL rather than the raw hosting URL', async () => {+ it('prints the hosting URL with a separate product share URL', async () => {await publish();const output = consoleSpy.mock.calls.flat().join('\n');expect(output).toContain('https://app.lobehub.com/share/artifact/dep-1');- expect(output).not.toContain('https://example.com/p');+ expect(output).toContain('https://example.com/p');});- it('emits the product share URL as publicUrl in JSON output', async () => {+ it('keeps publicUrl as the hosting URL and exposes shareUrl separately', async () => {await publish('--json');const payload = JSON.parse(@@ -176,7 +176,8 @@ describe('artifact publish', () => {.filter((value): value is string => typeof value === 'string').join('\n'),);- expect(payload.publicUrl).toBe('https://app.lobehub.com/share/artifact/dep-1');+ expect(payload.publicUrl).toBe('https://example.com/p');+ expect(payload.shareUrl).toBe('https://app.lobehub.com/share/artifact/dep-1');expect(payload.id).toBe('dep-1');});@@ -242,5 +243,18 @@ describe('artifact publish', () => {expect(readManifest().artifacts['index.html'].pendingCreateKey).toEqual(expect.any(String));});++ it('remembers a pending HTML type when replacing a Canvas and retries through HTML', async () => {+ writeManifest({+ 'index.html': { type: 'canvas', canvasId: 'cvs_old', deploymentId: 'dep_old' },+ });+ mockTrpcClient.market.deployments.prepareWorkspaceHtmlUpload.mutate.mockRejectedValueOnce(+ new Error('Response lost'),+ );+ await expect(publish('--type', 'html', '--new')).rejects.toThrow('Response lost');+ await publish('--new');+ expect(exitSpy).not.toHaveBeenCalled();+ expect(readManifest().artifacts['index.html']).toEqual({ deploymentId: 'dep-1' });+ });});});diff --git a/apps/cli/src/commands/artifact.ts b/apps/cli/src/commands/artifact.tsindex 26fc9b05d72..95931e356fc 100644--- a/apps/cli/src/commands/artifact.ts+++ b/apps/cli/src/commands/artifact.ts@@ -1,6 +1,7 @@import path from 'node:path';import {+ extractHtmlTitle,gatherWorkspaceHtmlArtifact,hostedPath,packWorkspaceHtmlDocument,@@ -17,9 +18,11 @@ import {resolveManifest,writeBinding,} from '../utils/artifactManifest';+import { formatError } from '../utils/error';import { outputJson } from '../utils/format';import { log } from '../utils/logger';import { readLocalHtmlAsset } from '../utils/readLocalHtmlAsset';+import { publishCanvasArtifact } from './artifactCanvas';interface PreparedUploadTarget {headers: Record<string, string>;@@ -33,6 +36,7 @@ interface DeploymentRecord {publicUrl?: string;slug?: string;status?: string;+ subdomainLabel?: string | null;}/**@@ -83,6 +87,26 @@ const warnList = (label: string, items: string[]) => {export function registerArtifactCommand(program: Command) {const artifact = program.command('artifact').description('Publish local pages as artifacts');+ artifact+ .command('guide <type>')+ .description('Read the generation guide for an artifact type (canvas)')+ .action(async (type: string) => {+ if (type !== 'canvas') {+ fail('The supported guide type is canvas.');+ return;+ }+ const client = await getTrpcClient();+ const { output } = await client.canvas.runAgentTool.mutate({+ apiName: 'readCanvasGuide',+ args: {},+ });+ if (!output.success) {+ fail(String(output.content));+ return;+ }+ console.log(output.content);+ });+artifact.command('publish <file>').description('Publish a local HTML file, bundling the assets it references')@@ -92,6 +116,10 @@ export function registerArtifactCommand(program: Command) {).option('--deployment <id>', 'Publish to this deployment for this run only').option('--new', 'Create a separate deployment instead of updating the bound one')+ .option(+ '--type <type>',+ 'Artifact content type: html or canvas (defaults to the bound type, then html)',+ ).option('--title <title>', 'Override the page title').option('--slug <slug>', 'Requested public slug').option('--json [fields]', 'Output JSON, optionally specify fields (comma-separated)')@@ -105,6 +133,7 @@ export function registerArtifactCommand(program: Command) {title?: string;deployment?: string;new?: boolean;+ type?: string;},) => {const entryPath = path.resolve(file);@@ -123,6 +152,71 @@ export function registerArtifactCommand(program: Command) {return;}+ const manifest = resolveManifest(entryPath, rootDirectory);+ const binding = readBinding(manifest);+ const type = options.type ?? binding.pendingType ?? binding.type ?? 'html';+ if (type !== 'html' && type !== 'canvas') {+ fail('Artifact type must be html or canvas.');+ return;+ }+ if (options.new && options.deployment) {+ fail('--new and --deployment cannot be combined.');+ return;+ }+ if (binding.pendingType && binding.pendingType !== type) {+ fail('Complete the pending publication before changing its type.');+ return;+ }+ if (type === 'canvas' && binding.pendingCreateKey && !binding.pendingCanvas) {+ fail('Complete the pending HTML publication before changing its type.');+ return;+ }+ if (+ !options.new &&+ options.type &&+ options.type !== (binding.pendingType ?? binding.type ?? 'html') &&+ (binding.deploymentId || binding.canvasId || binding.pendingCreateKey)+ ) {+ fail('Changing a bound artifact type requires --new.');+ return;+ }+ if (type === 'canvas') {+ try {+ const payload = await publishCanvasArtifact(await getTrpcClient(), {+ binding,+ deployment: options.deployment,+ html: entry.text,+ manifest,+ new: options.new,+ slug: options.slug || undefined,+ title:+ options.title ||+ extractHtmlTitle(entry.text) ||+ path.basename(entryPath, path.extname(entryPath)),+ });+ if (options.json !== undefined) {+ outputJson(payload, typeof options.json === 'string' ? options.json : undefined);+ } else {+ console.log(+ `${pc.green('✓')} Published Canvas ${payload.canvasId} (version ${payload.version})`,+ );+ console.log(` URL: ${payload.publicUrl}`);+ console.log(` Share: ${payload.shareUrl}`);+ }+ } catch (error) {+ const pending = readBinding(manifest).pendingCanvas;+ const saved = pending?.saved;+ if (options.json !== undefined)+ outputJson({ ...saved, error: formatError(error), success: false });+ fail(+ pending+ ? `${formatError(error)}. ${pending.rejectedPublication ? 'Correct the rejected slug and retry with the same content and target.' : 'Retry the same command with the original input to resume publication.'}`+ : formatError(error),+ );+ }+ return;+ }+const gathered = await gatherWorkspaceHtmlArtifact({htmlContent: entry.text,htmlFilePath: entryPath,@@ -169,14 +263,6 @@ export function registerArtifactCommand(program: Command) {const client = await getTrpcClient();const title = options.title || gathered.title;- const manifest = resolveManifest(entryPath, rootDirectory);- const binding = readBinding(manifest);-- if (options.new && options.deployment) {- fail('--new and --deployment cannot be combined.');- return;- }-const boundDeploymentId = options.new? undefined: (options.deployment ?? binding.deploymentId);@@ -195,7 +281,11 @@ export function registerArtifactCommand(program: Command) {// then loses its response must still be recoverable on the next run.const persistsBinding = target.kind === 'create' && !options.deployment;if (persistsBinding && idempotencyKey !== binding.pendingCreateKey) {- writeBinding(manifest, { ...binding, pendingCreateKey: idempotencyKey });+ writeBinding(manifest, {+ ...binding,+ pendingCreateKey: idempotencyKey,+ pendingType: 'html',+ });}const deployments = deploymentClient(client).market.deployments;@@ -242,10 +332,10 @@ export function registerArtifactCommand(program: Command) {writeBinding(manifest, { deploymentId: result.data.id });}- const publicUrl = result.data.id+ const shareUrl = result.data.id? artifactShareUrl(resolveServerUrl(), result.data.id)- : result.data.publicUrl;- const payload = { ...result.data, publicUrl };+ : undefined;+ const payload = { ...result.data, shareUrl };if (options.json !== undefined) {const fields = typeof options.json === 'string' ? options.json : undefined;@@ -254,7 +344,8 @@ export function registerArtifactCommand(program: Command) {}console.log(`${pc.green('✓')} Published ${pc.bold(title)} (${entries.length} file(s))`);- if (publicUrl) console.log(` URL: ${pc.dim(publicUrl)}`);+ if (payload.publicUrl) console.log(` URL: ${pc.dim(payload.publicUrl)}`);+ if (shareUrl) console.log(` Share: ${pc.dim(shareUrl)}`);console.log(` Deployment: ${pc.dim(result.data.id ?? '')}`);},);diff --git a/apps/cli/src/commands/artifactCanvas.ts b/apps/cli/src/commands/artifactCanvas.tsnew file mode 100644index 00000000000..0e213670196--- /dev/null+++ b/apps/cli/src/commands/artifactCanvas.ts@@ -0,0 +1,152 @@+import { createHash } from 'node:crypto';++import { artifactShareUrl } from '@lobechat/utils/artifactShare';+import { toRecord } from '@lobechat/utils/object';++import type { TrpcClient } from '../api/client';+import { resolveServerUrl } from '../settings';+import {+ type ArtifactBinding,+ createIdempotencyKey,+ type ResolvedManifest,+ writeBinding,+} from '../utils/artifactManifest';++export const publishCanvasArtifact = async (+ client: TrpcClient,+ params: {+ binding: ArtifactBinding;+ deployment?: string;+ html: string;+ manifest: ResolvedManifest;+ new?: boolean;+ slug?: string;+ title: string;+ },+) => {+ const { binding, html, manifest, title } = params;+ const context = await client.canvas.getPublishContext.query();+ if (!context.canPublish) throw new Error('Canvas publishing is unavailable on this server');+ 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 fingerprintFor = (slug?: string) =>+ createHash('sha256')+ .update(+ JSON.stringify([+ html,+ title,+ params.deployment ?? null,+ !!params.new,+ ...(slug ? [slug] : []),+ ]),+ )+ .digest('hex');+ const fingerprint = fingerprintFor(params.slug);+ let pending = binding.pendingCanvas;+ if (+ pending &&+ pending.fingerprint !== fingerprint &&+ (!pending.saved ||+ !pending.rejectedPublication ||+ pending.fingerprint !== fingerprintFor(pending.rejectedPublication.requestedSlug))+ ) {+ throw new Error(+ 'A publication is pending with different content or options; retry the original input first',+ );+ }+ if (!pending) {+ const canvasId = params.new ? undefined : binding.canvasId;+ const current = canvasId ? await client.canvas.getVersion.query({ canvasId }) : null;+ if (canvasId && (!current || !current.canPublish)) {+ throw new Error('The bound Canvas is unavailable or cannot be published by this account');+ }+ pending = {+ canvasId,+ createNew: !!params.new,+ deploymentId: params.deployment,+ expectedVersion: current?.version ?? 0,+ fingerprint,+ previous: binding,+ };+ }+ pending = { ...pending, fingerprint, rejectedPublication: undefined };+ const pendingCreateKey = binding.pendingCreateKey ?? createIdempotencyKey();+ const activeBinding: ArtifactBinding = {+ ...binding,+ pendingCanvas: pending,+ pendingCreateKey,+ scope,+ pendingType: 'canvas',+ };+ writeBinding(manifest, activeBinding);++ let saved = pending.saved;+ if (!saved) {+ try {+ saved = await client.canvas.save.mutate({+ canvasId: pending.canvasId,+ expectedVersion: pending.expectedVersion,+ html,+ requestId: pendingCreateKey,+ title,+ });+ } catch (error) {+ const code = toRecord(toRecord(error)?.data)?.code;+ if (+ code === 'BAD_REQUEST' ||+ code === 'CONFLICT' ||+ code === 'FORBIDDEN' ||+ code === 'NOT_FOUND'+ ) {+ const previous = pending.previous;+ writeBinding(+ manifest,+ previous.canvasId || previous.deploymentId ? previous : { ...previous, type: 'canvas' },+ );+ }+ throw error;+ }+ }+ writeBinding(manifest, { ...activeBinding, pendingCanvas: { ...pending, saved } });+ const published = await client.canvas.publish+ .mutate({+ canvasId: saved.canvasId,+ deploymentId: params.deployment,+ requestedSlug: params.slug,+ version: saved.version,+ })+ .catch((error) => {+ if (toRecord(toRecord(error)?.data)?.code === 'BAD_REQUEST') {+ writeBinding(manifest, {+ ...activeBinding,+ pendingCanvas: {+ ...pending,+ saved,+ rejectedPublication: { requestedSlug: params.slug },+ },+ });+ }+ throw error;+ });+ writeBinding(+ manifest,+ params.deployment+ ? pending.previous+ : {+ ...saved,+ deploymentId: published.deploymentId,+ scope,+ type: 'canvas',+ },+ );+ return {+ ...saved,+ id: published.deploymentId,+ publicUrl: published.url,+ publishedVersion: published.publishedVersion,+ shareUrl: artifactShareUrl(resolveServerUrl(), published.deploymentId),+ subdomainLabel: published.subdomainLabel,+ };+};diff --git a/apps/cli/src/utils/artifactManifest.ts b/apps/cli/src/utils/artifactManifest.tsindex 0b61bf82a2b..e0e72b47983 100644--- a/apps/cli/src/utils/artifactManifest.ts+++ b/apps/cli/src/utils/artifactManifest.ts@@ -2,17 +2,35 @@ import { randomUUID } from 'node:crypto';import fs from 'node:fs';import path from 'node:path';+import { z } from 'zod';+const MANIFEST_DIR = '.lobehub';const MANIFEST_FILE = 'artifacts.json';export interface ArtifactBinding {+ canvasId?: string;deploymentId?: string;+ pendingCanvas?: {+ canvasId?: string;+ createNew: boolean;+ deploymentId?: string;+ expectedVersion: number;+ fingerprint: string;+ previous: Omit<ArtifactBinding, 'pendingCanvas' | 'pendingCreateKey' | 'pendingType'>;+ rejectedPublication?: { requestedSlug?: string };+ saved?: { canvasId: string; version: number; workId: string };+ };/*** Set before a create is sent and cleared once its deployment is recorded, so* a retry after a lost response reuses the key and the server returns the* deployment it already made instead of minting a second site.*/pendingCreateKey?: string;+ pendingType?: 'canvas' | 'html';+ scope?: string;+ type?: 'canvas' | 'html';+ version?: number;+ workId?: string;}interface ArtifactManifest {@@ -20,6 +38,59 @@ interface ArtifactManifest {version: 1;}+const bindingIdentity = {+ canvasId: z.string().min(1).optional(),+ deploymentId: z.string().min(1).optional(),+ scope: z.string().min(1).optional(),+ type: z.enum(['canvas', 'html']).optional(),+ version: z.number().int().positive().optional(),+ workId: z.string().min(1).optional(),+};++const bindingSchema = z+ .object({+ ...bindingIdentity,+ pendingCanvas: z+ .object({+ canvasId: z.string().min(1).optional(),+ createNew: z.boolean(),+ deploymentId: z.string().min(1).optional(),+ expectedVersion: z.number().int().nonnegative(),+ fingerprint: z.string().regex(/^[\da-f]{64}$/),+ previous: z.object(bindingIdentity).passthrough(),+ rejectedPublication: z.object({ requestedSlug: z.string().optional() }).optional(),+ saved: z+ .object({+ canvasId: z.string().min(1),+ version: z.number().int().positive(),+ workId: z.string().min(1),+ })+ .optional(),+ })+ .optional(),+ pendingCreateKey: z.string().min(1).optional(),+ pendingType: z.enum(['canvas', 'html']).optional(),+ })+ .passthrough()+ .superRefine((binding, ctx) => {+ if (+ (binding.pendingCanvas || binding.pendingType === 'canvas') &&+ (!binding.pendingCanvas ||+ !z.uuid().safeParse(binding.pendingCreateKey).success ||+ !binding.scope ||+ binding.pendingType !== 'canvas')+ ) {+ ctx.addIssue({ code: 'custom', message: 'Incomplete Canvas recovery state' });+ }+ });++const manifestSchema = z+ .object({+ artifacts: z.record(z.string(), bindingSchema),+ version: z.literal(1),+ })+ .passthrough();+export interface ResolvedManifest {entryKey: string;path: string;@@ -62,18 +133,9 @@ export const resolveManifest = (entryPath: string, fallbackRoot: string): Resolv};const readManifest = (manifestPath: string): ArtifactManifest => {- try {- const parsed: unknown = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));- if (!parsed || typeof parsed !== 'object') return emptyManifest();-- const artifacts = (parsed as ArtifactManifest).artifacts;- if (!artifacts || typeof artifacts !== 'object') return emptyManifest();-- return { artifacts, version: 1 };- } catch {- // absent or unreadable — the caller creates a fresh deployment- return emptyManifest();- }+ if (!fs.existsSync(manifestPath)) return emptyManifest();+ // Corrupt recovery data must not silently become a fresh publication.+ return manifestSchema.parse(JSON.parse(fs.readFileSync(manifestPath, 'utf8')));};export const readBinding = (manifest: ResolvedManifest): ArtifactBinding =>diff --git a/apps/server/src/routers/lambda/__tests__/canvas.test.ts b/apps/server/src/routers/lambda/__tests__/canvas.test.tsindex 2fd1a273e1b..b73f97a14ff 100644--- a/apps/server/src/routers/lambda/__tests__/canvas.test.ts+++ b/apps/server/src/routers/lambda/__tests__/canvas.test.ts@@ -35,6 +35,7 @@ vi.mock('@/business/server/canvasPublish', () => ({}));const committed = vi.hoisted(() => ({ calls: 0 }));+const storedManifests = vi.hoisted(() => new Map<string, any>());const snapshots = vi.hoisted(() => ({read: vi.fn(async (key: string, owner: string) => ({entry: 'index.html',@@ -49,36 +50,51 @@ const snapshots = vi.hoisted(() => ({})),}));-vi.mock('@/server/services/canvas', () => ({- createCanvasStorageService: (_db: unknown, ownerId: string) => ({- commit: async () => {- committed.calls += 1;- return {- manifest: {},- metadata: {+vi.mock('@/server/services/canvas', async () => {+ const { createHash } = await import('node:crypto');+ const { validateCanvasProject } = await import('@lobechat/canvas');+ return {+ createCanvasStorageService: (_db: unknown, ownerId: string) => ({+ commit: async (canvasId: string, files: any[]) => {+ const validation = validateCanvasProject(files);+ if (!validation.ok) return validation;+ committed.calls += 1;+ const hash = createHash('sha256').update(files[0].content).digest('hex');+ const manifestKey = `canvas/${ownerId}/${canvasId}/manifests/${hash}.json`;+ storedManifests.set(manifestKey, {+ entry: 'index.html',+ files: { 'index.html': { hash } },+ });+ return {+ manifest: {},+ metadata: {+ entry: 'index.html',+ fileCount: 1,+ manifestKey,+ runtimeMajor: 1,+ totalSize: 40,+ },+ ok: true,+ };+ },+ ownerId,+ readSnapshot: (key: string) => snapshots.read(key, ownerId),+ readFile: async () => ({+ bytes: new TextEncoder().encode('<html><head></head><body>hi</body></html>'),+ contentType: 'text/html; charset=utf-8',+ }),+ readManifest: async (key: string) =>+ storedManifests.get(key) ?? {entry: 'index.html',- fileCount: 1,- manifestKey: `canvas/${ownerId}/cvs_new/manifests/m.json`,+ files: {+ 'index.html': { contentType: 'text/html; charset=utf-8', hash: 'h1', size: 40 },+ },runtimeMajor: 1,- totalSize: 40,+ schemaVersion: 1,},- ok: true,- };- },- ownerId,- readSnapshot: (key: string) => snapshots.read(key, ownerId),- readFile: async () => ({- bytes: new TextEncoder().encode('<html><head></head><body>hi</body></html>'),- contentType: 'text/html; charset=utf-8',- }),- readManifest: async () => ({- entry: 'index.html',- files: { 'index.html': { contentType: 'text/html; charset=utf-8', hash: 'h1', size: 40 } },- runtimeMajor: 1,- schemaVersion: 1,}),- }),-}));+ };+});vi.mock('@/libs/trpc/lambda/middleware', () => ({serverDatabase: async (opts: any) => opts.next({ ctx: { ...opts.ctx, serverDB } }),@@ -99,6 +115,7 @@ beforeEach(async () => {vi.stubEnv('KEY_VAULTS_SECRET', 'test-secret');publishing.enabled = true;committed.calls = 0;+ storedManifests.clear();publishing.publish.mockClear();await serverDB.delete(users);await serverDB.insert(users).values([{ id: userId }, { id: 'stranger' }]);@@ -207,7 +224,7 @@ describe('canvasRouter.publish', () => {const first = await caller().publish({ canvasId: 'cvs_1' });await caller().publish({ canvasId: 'cvs_1' });- expect(first).toEqual({ publishedVersion: 2, url: 'https://cost.lobehub.sites' });+ expect(first).toMatchObject({ publishedVersion: 2, url: 'https://cost.lobehub.sites' });expect(publishing.publish.mock.calls[0][0]).toMatchObject({canvasId: 'cvs_1',deploymentId: undefined,@@ -243,6 +260,95 @@ describe('canvasRouter.publish', () => {expect(publishing.publish).not.toHaveBeenCalled();expect((await caller().getVersion({ canvasId: 'cvs_1' }))?.canPublish).toBe(false);});++ it('publishes the requested saved version after a newer one was registered', async () => {+ const result = await caller().publish({ canvasId: 'cvs_1', version: 1 });+ expect(result).toMatchObject({ deploymentId: 'dep_1', publishedVersion: 1 });+ expect((await caller().getVersion({ canvasId: 'cvs_1' }))?.publishedVersion).toBe(1);+ });++ it('forwards requestedSlug to the publication host', async () => {+ await caller().publish({ canvasId: 'cvs_1', requestedSlug: 'Sales Report' });+ expect(publishing.publish.mock.calls[0][0].requestedSlug).toBe('Sales Report');+ });++ it('does not change the canonical publication when targeting a deployment for one run', async () => {+ await caller().publish({ canvasId: 'cvs_1' });+ publishing.publish.mockResolvedValueOnce({+ deploymentId: 'dep_once',+ url: 'https://once.test',+ });+ await caller().publish({ canvasId: 'cvs_1', deploymentId: 'dep_once', version: 1 });+ expect(publishing.publish.mock.calls.at(-1)?.[0].deploymentId).toBe('dep_once');+ expect(await caller().getVersion({ canvasId: 'cvs_1' })).toMatchObject({+ publishedUrl: 'https://cost.lobehub.sites',+ publishedVersion: 2,+ });+ });+});++describe('canvasRouter.save', () => {+ const input = {+ expectedVersion: 0,+ html: '<h1>Local report</h1>',+ requestId: '12345678-1234-4234-8234-123456789abc',+ title: 'Local report',+ };++ it('saves an independent Canvas and recovers the same version after a lost response', async () => {+ const first = await caller().save(input);+ const replay = await caller().save(input);+ expect(replay).toEqual(first);+ expect(first).toMatchObject({ canvasId: expect.stringMatching(/^cvs_/), version: 1 });+ expect(await caller().getVersion({ canvasId: first.canvasId })).toMatchObject({+ title: input.title,+ version: 1,+ workId: first.workId,+ });+ expect(await new WorkModel(serverDB, userId).listVersions(first.workId)).toHaveLength(1);+ expect(committed.calls).toBe(1);+ });++ it('keeps previous versions and recovers the original operation after a later save', async () => {+ const first = await caller().save(input);+ const second = await caller().save({+ ...input,+ canvasId: first.canvasId,+ expectedVersion: 1,+ html: '<h1>New snapshot</h1>',+ requestId: '22345678-1234-4234-8234-123456789abc',+ });+ expect(second.version).toBe(2);+ expect(await caller().save(input)).toEqual(first);+ expect((await caller().getVersion({ canvasId: first.canvasId }))?.version).toBe(2);+ await expect(+ caller().save({ ...input, html: '<h1>Different input</h1>' }),+ ).rejects.toMatchObject({+ code: 'CONFLICT',+ });+ await expect(+ caller().save({+ ...input,+ canvasId: first.canvasId,+ requestId: '32345678-1234-4234-8234-123456789abc',+ }),+ ).rejects.toMatchObject({ code: 'CONFLICT' });+ });++ it('rejects invalid content before storage or registration', async () => {+ await expect(+ caller().save({ ...input, html: '<img src="https://private.test/image.png">' }),+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });+ expect(committed.calls).toBe(0);+ });++ it('does not allow saving over an invisible or missing canvas', async () => {+ await expect(+ caller('stranger').save({ ...input, canvasId: 'cvs_1', expectedVersion: 2 }),+ ).rejects.toThrow();+ await expect(caller().save({ ...input, canvasId: 'missing' })).rejects.toThrow();+ expect(committed.calls).toBe(0);+ });});describe('canvasRouter.runAgentTool', () => {@@ -264,7 +370,7 @@ describe('canvasRouter.runAgentTool', () => {expect(result.output.success).toBe(true);expect(result.intent).toMatchObject({canvas: {- metadata: { manifestKey: `canvas/${userId}/cvs_new/manifests/m.json` },+ metadata: { manifestKey: expect.stringContaining(`canvas/${userId}/cvs_`) },title: 'Cost',},type: 'canvas',diff --git a/apps/server/src/routers/lambda/canvas.ts b/apps/server/src/routers/lambda/canvas.tsindex ae94be4f018..484003d98dd 100644--- a/apps/server/src/routers/lambda/canvas.ts+++ b/apps/server/src/routers/lambda/canvas.ts@@ -18,6 +18,7 @@ import { serverDatabase } from '@/libs/trpc/lambda/middleware';import { createCanvasStorageService } from '@/server/services/canvas';import { createCanvasAgentRuntime } from '@/server/services/canvas/agentRuntime';import { buildCanvasPublishBundle } from '@/server/services/canvas/publish';+import { saveCanvas } from '@/server/services/canvas/save';const canvasProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {const { ctx } = opts;@@ -29,6 +30,11 @@ const canvasProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) =});export const canvasRouter = router({+ getPublishContext: canvasProcedure.query(({ ctx }) => ({+ canPublish: isCanvasPublishEnabled(),+ userId: ctx.userId,+ workspaceId: ctx.workspaceId ?? null,+ })),getProject: canvasProcedure.input(z.object({ canvasId: z.string(), version: z.number().int().positive() })).query(async ({ ctx, input }) => {@@ -77,7 +83,14 @@ export const canvasRouter = router({publish: canvasProcedure.use(requireWorkspaceRoleWhenScoped('member'))- .input(z.object({ canvasId: z.string() }))+ .input(+ z.object({+ canvasId: z.string(),+ deploymentId: z.string().optional(),+ requestedSlug: z.string().trim().min(1).max(255).optional(),+ version: z.number().int().positive().optional(),+ }),+ ).mutation(async ({ ctx, input }) => {if (!isCanvasPublishEnabled()) {throw new TRPCError({@@ -87,9 +100,14 @@ export const canvasRouter = router({}const current = await ctx.workModel.findCanvas(input.canvasId);- const canvas = current?.version.metadata?.canvas;- if (!current || !canvas) throw new TRPCError({ code: 'NOT_FOUND' });+ if (!current) throw new TRPCError({ code: 'NOT_FOUND' });if (current.work.userId !== ctx.userId) throw new TRPCError({ code: 'FORBIDDEN' });+ const version =+ input.version && input.version !== current.version.version+ ? await ctx.workModel.findCanvasVersion(current.work.id, input.version)+ : current.version;+ const canvas = version?.metadata?.canvas;+ if (!version || !canvas) throw new TRPCError({ code: 'NOT_FOUND' });const runtimeUrl = await getCanvasPublishRuntimeUrl(canvas.runtimeMajor).catch((cause) => {throw new TRPCError({@@ -115,18 +133,26 @@ export const canvasRouter = router({bundle,canvasId: input.canvasId,db: ctx.serverDB,- deploymentId: current.work.metadata?.canvasPublish?.deploymentId,- title: current.work.title ?? input.canvasId,+ deploymentId: input.deploymentId ?? current.work.metadata?.canvasPublish?.deploymentId,+ requestedSlug: input.requestedSlug,+ title: version.title ?? current.work.title ?? input.canvasId,userId: ctx.userId,workspaceId: ctx.workspaceId,});- await ctx.workModel.recordCanvasPublish(input.canvasId, {+ if (!input.deploymentId) {+ await ctx.workModel.recordCanvasPublish(input.canvasId, {+ deploymentId: site.deploymentId,+ publishedVersion: version.version,+ url: site.url,+ });+ }++ return {deploymentId: site.deploymentId,- publishedVersion: current.version.version,+ publishedVersion: version.version,+ ...(site.subdomainLabel ? { subdomainLabel: site.subdomainLabel } : {}),url: site.url,- });-- return { publishedVersion: current.version.version, url: site.url };+ };}),runAgentTool: canvasProcedure@@ -200,4 +226,24 @@ export const canvasRouter = router({version: item.version,}));}),++ save: canvasProcedure+ .use(requireWorkspaceRoleWhenScoped('member'))+ .input(+ z.object({+ canvasId: z.string().max(128).optional(),+ expectedVersion: z.number().int().nonnegative(),+ html: z.string().max(512 * 1024),+ requestId: z.string().uuid(),+ title: z.string().trim().min(1).max(200),+ }),+ )+ .mutation(({ ctx, input }) =>+ saveCanvas(input, {+ storage: createCanvasStorageService(ctx.serverDB, ctx.userId, ctx.workspaceId),+ userId: ctx.userId,+ workModel: ctx.workModel,+ workspaceId: ctx.workspaceId,+ }),+ ),});diff --git a/apps/server/src/services/canvas/save.ts b/apps/server/src/services/canvas/save.tsnew file mode 100644index 00000000000..d172a7b28ad--- /dev/null+++ b/apps/server/src/services/canvas/save.ts@@ -0,0 +1,112 @@+import { createHash } from 'node:crypto';++import type { WorkVersionItem } from '@lobechat/types';+import { TRPCError } from '@trpc/server';++import type { WorkModel } from '@/database/models/work';+import { CanvasVersionConflictError } from '@/database/models/work/canvas';++import type { CanvasStorageService } from './storage';++export interface SaveCanvasInput {+ canvasId?: string;+ expectedVersion: number;+ html: string;+ requestId: string;+ title: string;+}++export const saveCanvas = async (+ input: SaveCanvasInput,+ deps: {+ storage: CanvasStorageService;+ userId: string;+ workModel: WorkModel;+ workspaceId?: string;+ },+) => {+ const { storage, userId, workModel, workspaceId } = deps;+ // A lost create response must still resolve to the same scoped identity.+ const canvasId =+ input.canvasId ??+ `cvs_${createHash('sha256')+ .update(JSON.stringify([userId, workspaceId ?? null, input.requestId]))+ .digest('hex')+ .slice(0, 32)}`;+ const current = await workModel.findCanvas(canvasId);+ if (input.canvasId && !current) throw new TRPCError({ code: 'NOT_FOUND' });+ if (current && current.work.userId !== userId) throw new TRPCError({ code: 'FORBIDDEN' });++ const toolCallId = `cli:${input.requestId}`;+ const result = (version: WorkVersionItem) => ({+ canvasId,+ version: version.version,+ workId: version.workId,+ });+ const replay = await workModel.findCanvasVersionByToolCall(canvasId, toolCallId);+ if (replay?.metadata?.canvas) {+ const manifest = await storage.readManifest(replay.metadata.canvas.manifestKey);+ const hash = createHash('sha256').update(input.html).digest('hex');+ if (+ replay.title !== input.title ||+ Object.keys(manifest.files).length !== 1 ||+ manifest.files['index.html']?.hash !== hash+ ) {+ throw new TRPCError({+ code: 'CONFLICT',+ message: 'This save request was already used for different content',+ });+ }+ return result(replay);+ }++ if ((current?.version.version ?? 0) !== input.expectedVersion) {+ throw new TRPCError({ code: 'CONFLICT', message: new CanvasVersionConflictError().message });+ }+ const saved = await storage.commit(canvasId, [{ content: input.html, path: 'index.html' }]);+ if (!saved.ok) {+ throw new TRPCError({+ code: 'BAD_REQUEST',+ message: saved.issues+ .map(+ (issue) =>+ `${issue.file ?? 'index.html'}${issue.line ? `:${issue.line}` : ''} [${issue.rule}]: ${issue.message}`,+ )+ .join('\n'),+ });+ }+ try {+ await workModel.registerCanvas({+ canvasId,+ description: current?.work.description,+ expectedVersion: input.expectedVersion,+ metadata: saved.metadata,+ title: input.title,+ toolCallId,+ toolIdentifier: 'lobe-canvas',+ toolName: 'saveCanvas',+ });+ } catch (error) {+ if (error instanceof CanvasVersionConflictError) {+ throw new TRPCError({ cause: error, code: 'CONFLICT', message: error.message });+ }+ throw error;+ }+ const registered = await workModel.findCanvasVersionByToolCall(canvasId, toolCallId);+ if (!registered)+ throw new TRPCError({+ code: 'INTERNAL_SERVER_ERROR',+ message: 'Canvas version registration failed',+ });+ // Registration deduplicates under its row lock, including racing requests.+ if (+ registered.title !== input.title ||+ registered.metadata?.canvas?.manifestKey !== saved.metadata.manifestKey+ ) {+ throw new TRPCError({+ code: 'CONFLICT',+ message: 'This save request was already used for different content',+ });+ }+ return result(registered);+};diff --git a/packages/builtin-skills/src/lobehub/content.ts b/packages/builtin-skills/src/lobehub/content.tsindex b78d3b61dac..611e030a16b 100644--- a/packages/builtin-skills/src/lobehub/content.ts+++ b/packages/builtin-skills/src/lobehub/content.ts@@ -53,6 +53,7 @@ run commands.| \`lh doc\` | Document management (create, parse, organize) | \`references/doc\` || \`lh kb\` | Knowledge base management (create, upload, organize) | \`references/kb\` || \`lh file\` | File management | \`references/file\` |+| \`lh artifact\` | Publish local HTML or Canvas, with persistent bindings and retry recovery | \`references/artifact\` || \`lh memory\` | User memory management (identity, activity, preference) | \`references/memory\` || \`lh search\` / \`lh recall\` | Search local resources or the web / recall past work in a time window | \`references/search\` || \`lh gen\` | Content generation (text, image, video, TTS, ASR) | \`references/generate\` |@@ -69,7 +70,7 @@ run commands.| \`lh whoami\` / \`lh usage\` / \`lh user\` / \`lh migrate\` | Account, usage, settings and imports (top-level commands, not a \`config\` module) | \`references/config\` |Covered by their own skills, so activate the skill instead of reading a reference here:-\`lh task\` inside a task run (\`task\` skill), \`lh artifact\` (\`artifacts\` skill) and+\`lh task\` inside a task run (\`task\` skill) and\`lh acceptance\` (\`acceptance\` skill).# Workspace scopediff --git a/packages/builtin-skills/src/lobehub/index.ts b/packages/builtin-skills/src/lobehub/index.tsindex ff3699f9e33..a77e1f0090f 100644--- a/packages/builtin-skills/src/lobehub/index.ts+++ b/packages/builtin-skills/src/lobehub/index.ts@@ -5,6 +5,7 @@ import { toResourceMeta } from './helpers';import { LobeHubIdentifier, LobeHubManifest } from './manifest';import agent from './references/agent';import agentGroup from './references/agent-group';+import { artifact } from './references/artifact';import bot from './references/bot';import botDiscord from './references/bot-discord';import botFeishu from './references/bot-feishu';@@ -41,6 +42,7 @@ export const LobeHubSkill: BuiltinSkill = {resources: toResourceMeta({'references/agent': agent,'references/agent-group': agentGroup,+ 'references/artifact': artifact,'references/bot': bot,'references/bot/discord': botDiscord,'references/bot/feishu': botFeishu,diff --git a/packages/builtin-skills/src/lobehub/references/artifact.ts b/packages/builtin-skills/src/lobehub/references/artifact.tsnew file mode 100644index 00000000000..f423d7cb426--- /dev/null+++ b/packages/builtin-skills/src/lobehub/references/artifact.ts@@ -0,0 +1,35 @@+const content = `# lh artifact - Publish local HTML and Canvas++## Commands++- \`lh artifact guide canvas\`: read the shared Canvas component and generation rules before authoring a Canvas.+- \`lh artifact publish <file> [--type html|canvas] [--root <dir>] [--title <title>] [--slug <name>] [--new | --deployment <id>] [--json]\`: publish a public artifact.++Ordinary HTML is the default for unbound files and bundles local resources allowed+by --root. Canvas requires --type canvas on its first publish and accepts a+self-contained HTML file with inline CSS, JS and data. Follow the guide; the+server validates Canvas content and injects its runtime. Do not add the runtime+script yourself. Both formats support --slug for a new deployment's readable+prefix; Market appends an eight-character suffix. Updating a deployment keeps+its existing address. JSON publicUrl is the direct hosting address, shareUrl+is the product share page, and subdomainLabel is the actual assigned label.++The existing project .lobehub/artifacts.json remembers the content type, Canvas+identity and deployment. Later publishes of the same path update the same result.+--new creates and rebinds; --deployment targets only this run and keeps the+canonical binding. They cannot be combined. A content type change needs --new.++After failure, retry the same command with the same content and options. The CLI+persists the operation before saving and resumes the saved version before+publishing. Do not delete recovery state or generate a new request ID on a retry.+If input changed while an operation is pending, restore the original first.+If the server explicitly rejects the save (for example invalid HTML or a stale+version), pending state is released: fix the input or inspect the latest version+and retry. Corrupt recovery data is rejected without silently creating a new site.+Canvas JSON failures include the saved canvasId, workId and version when known;+an unsuccessful publish must never be reported as successful. Only a successful+publish returns a publicUrl. A Canvas is also saved as a Work with version history;+it does not require a topic or agent and uses the current authenticated scope.+`;++export const artifact = content;diff --git a/packages/business-server/src/canvasPublish.ts b/packages/business-server/src/canvasPublish.tsindex 1348c4f5091..f3b2101598f 100644--- a/packages/business-server/src/canvasPublish.ts+++ b/packages/business-server/src/canvasPublish.ts@@ -6,6 +6,7 @@ export interface PublishCanvasSiteParams {canvasId: string;db: LobeChatDatabase;deploymentId?: string;+ requestedSlug?: string;title: string;userId: string;workspaceId?: string;@@ -13,6 +14,7 @@ export interface PublishCanvasSiteParams {export interface PublishCanvasSiteResult {deploymentId: string;+ subdomainLabel?: string | null;url: string;}diff --git a/packages/database/src/models/work/__tests__/canvas.test.ts b/packages/database/src/models/work/__tests__/canvas.test.tsindex 07d49f11434..05088aebbee 100644--- a/packages/database/src/models/work/__tests__/canvas.test.ts+++ b/packages/database/src/models/work/__tests__/canvas.test.ts@@ -161,6 +161,34 @@ describe('WorkModel · canvas', () => {expect(await model.findCanvas('cvs_missing')).toBeNull();});+ it('rejects a stale snapshot without changing the current canvas or its history', async () => {+ const model = new WorkModel(serverDB, userId);+ const first = await model.registerCanvas(params({ expectedVersion: 0 }));++ await expect(+ model.registerCanvas(params({ expectedVersion: 0, toolCallId: 'stale', title: 'Stale' })),+ ).rejects.toThrow('Canvas version conflict');+ expect((await model.findCanvas('cvs_cost'))?.work.title).toBe(params().title);+ expect(await model.listVersions(first.id)).toHaveLength(1);+ });++ it('recovers an operation version even after a later version became current', async () => {+ const model = new WorkModel(serverDB, userId);+ await model.registerCanvas(params({ expectedVersion: 0 }));+ await model.registerCanvas(params({ expectedVersion: 1, toolCallId: 'second' }));++ const saved = await model.findCanvasVersionByToolCall('cvs_cost', 'call-canvas-1');+ expect(saved?.version).toBe(1);+ expect(+ await new WorkModel(serverDB, userId2).findCanvasVersionByToolCall(+ 'cvs_cost',+ 'call-canvas-1',+ ),+ ).toBeNull();+ await model.registerCanvas(params({ expectedVersion: 0 }));+ expect((await model.findCanvas('cvs_cost'))?.version.version).toBe(2);+ });+it('reads a specific version of a canvas', async () => {const model = new WorkModel(serverDB, userId);const work = await model.registerCanvas(params());diff --git a/packages/database/src/models/work/canvas.ts b/packages/database/src/models/work/canvas.tsindex b5ba30b8aff..f0aa28fd257 100644--- a/packages/database/src/models/work/canvas.ts+++ b/packages/database/src/models/work/canvas.ts@@ -16,6 +16,12 @@ import { registerWorkVersion } from './writes';export const canvasWorkAdapter = createDisplayWorkAdapter({ type: 'canvas' });+export class CanvasVersionConflictError extends Error {+ constructor() {+ super('Canvas version conflict; read the latest version before saving again');+ }+}+const canvasResource = (ctx: WorkContext, canvasId: string) =>and(workOwnership(ctx), eq(works.resourceType, 'canvas'), eq(works.resourceId, canvasId));@@ -66,11 +72,19 @@ export const registerCanvasWork = async (// The public link written by `recordCanvasPublish` lives on the Work, and// each registration replaces every display column, so carry it over.const [published] = await txCtx.db- .select({ url: works.url })+ .select({ url: works.url, version: workVersions.version }).from(works)+ .leftJoin(workVersions, eq(workVersions.id, works.currentVersionId)).where(canvasResource(txCtx, params.canvasId)).limit(1);+ if (+ params.expectedVersion !== undefined &&+ (published?.version ?? 0) !== params.expectedVersion+ ) {+ throw new CanvasVersionConflictError();+ }+return {display: {description: params.description ?? null,@@ -118,6 +132,20 @@ export const findCanvasWorkVersion = async (return row?.version ?? null;};+export const findCanvasWorkVersionByToolCall = async (+ ctx: WorkContext,+ canvasId: string,+ toolCallId: string,+): Promise<WorkVersionItem | null> => {+ const [row] = await ctx.db+ .select({ version: workVersions })+ .from(workVersions)+ .innerJoin(works, eq(works.id, workVersions.workId))+ .where(and(canvasResource(ctx, canvasId), eq(workVersions.toolCallId, toolCallId)))+ .limit(1);+ return row?.version ?? null;+};+export const findReferencedCanvasManifestKeys = async (ctx: WorkContext, keys: string[]) => {if (keys.length === 0) return [];const manifestKey = sql<string>`${workVersions.metadata} -> 'canvas' ->> 'manifestKey'`;diff --git a/packages/database/src/models/work/index.ts b/packages/database/src/models/work/index.tsindex 97196d37846..f82b736d674 100644--- a/packages/database/src/models/work/index.ts+++ b/packages/database/src/models/work/index.ts@@ -21,6 +21,7 @@ import type { LobeChatDatabase } from '../../type';import {findCanvasWork,findCanvasWorkVersion,+ findCanvasWorkVersionByToolCall,findReferencedCanvasManifestKeys,listCanvasWorks,recordCanvasPublish,@@ -105,6 +106,9 @@ export class WorkModel {findCanvasVersion = (workId: string, version: number) =>findCanvasWorkVersion(this.ctx, workId, version);+ findCanvasVersionByToolCall = (canvasId: string, toolCallId: string) =>+ findCanvasWorkVersionByToolCall(this.ctx, canvasId, toolCallId);+findReferencedCanvasManifestKeys = (keys: string[]) =>findReferencedCanvasManifestKeys(this.ctx, keys);diff --git a/packages/types/src/work.ts b/packages/types/src/work.tsindex a3817ac1180..ef804e1b192 100644--- a/packages/types/src/work.ts+++ b/packages/types/src/work.ts@@ -419,6 +419,8 @@ export interface RegisterCanvasWorkParams {cumulativeCost?: number | null;cumulativeUsage?: WorkVersionCumulativeUsage | null;description?: string | null;+ /** Checked under the Work row lock; 0 means this must be the first version. */+ expectedVersion?: number;messageId?: string | null;metadata: CanvasWorkVersionMetadata;rootOperationId?: string | null;