Skip to content

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

✨ feat(cli): add lh widget and lh dashboard commands (#20771)

Arvin Xu38d27555dd5d
diff --git a/apps/cli/src/commands/dashboard.ts b/apps/cli/src/commands/dashboard.ts
new file mode 100644
index 00000000000..c33dbc8ac8e
--- /dev/null
+++ b/apps/cli/src/commands/dashboard.ts
@@ -0,0 +1,115 @@
+import type { Command } from 'commander';
+import pc from 'picocolors';
+
+import { getTrpcClient } from '../api/client';
+import { resolveWorkspaceId } from '../api/workspace';
+import { outputJson, printTable, timeAgo, truncate } from '../utils/format';
+import { log } from '../utils/logger';
+import { resolveAppUrlBuilder } from './task/url';
+
+/** Where a board opens: inside its project when it belongs to one, else on the home dashboards. */
+const dashboardPath = (dashboard: { id: string; projectId?: string | null }) =>
+ dashboard.projectId
+ ? `/project/${encodeURIComponent(dashboard.projectId)}/dashboard/${dashboard.id}`
+ : `/dashboard/${dashboard.id}`;
+
+export function registerDashboardCommand(program: Command) {
+ const dashboard = program
+ .command('dashboard')
+ .description('Manage dashboards (boards of monitoring widgets)');
+
+ dashboard
+ .command('list')
+ .description('List dashboards')
+ .option('--project <projectId>', "Every board of a project, including its agents' boards")
+ .option('--json [fields]', 'Output JSON')
+ .action(async (options: { json?: boolean | string; project?: string }) => {
+ const client = await getTrpcClient();
+ const { data } = options.project
+ ? await client.dashboard.listByProject.query({ projectId: options.project })
+ : await client.dashboard.list.query({});
+ if (options.json !== undefined) return outputJson(data, options.json);
+ if (data.length === 0) return console.log('No dashboards found.');
+ printTable(
+ data.map((item) => [
+ item.id,
+ truncate(item.title, 40),
+ item.projectId ?? '-',
+ timeAgo(item.updatedAt),
+ ]),
+ ['ID', 'TITLE', 'PROJECT', 'UPDATED'],
+ );
+ });
+
+ dashboard
+ .command('view <id>')
+ .description('View a dashboard and the widgets on it')
+ .option('--json [fields]', 'Output JSON')
+ .action(async (id: string, options: { json?: boolean | string }) => {
+ const client = await getTrpcClient();
+ const { data } = await client.dashboard.detail.query({ id });
+ if (options.json !== undefined) return outputJson(data, options.json);
+ const buildUrl = await resolveAppUrlBuilder(client);
+ console.log(`\n${pc.bold(data.title)} ${pc.dim(data.id)}`);
+ if (data.description) console.log(data.description);
+ console.log(`${pc.dim('URL:')} ${buildUrl(dashboardPath(data))}`);
+ if (data.items.length === 0) return console.log('\nNo widgets on this board.');
+ console.log();
+ printTable(
+ data.items.map(({ widget }) => [
+ widget.id,
+ truncate(widget.title, 40),
+ widget.publishedVersionId ? 'live' : 'draft',
+ widget.lastRunStatus ?? '-',
+ ]),
+ ['WIDGET', 'TITLE', 'STATE', 'LAST RUN'],
+ );
+ });
+
+ dashboard
+ .command('create')
+ .description('Create a dashboard')
+ .requiredOption('-t, --title <title>', 'Dashboard title')
+ .option('-d, --description <text>', 'Description')
+ .option('--project <projectId>', 'Create it inside a project (required in a workspace)')
+ .option('--widget <widgetId>', 'Place this widget on the new board')
+ .option('--json [fields]', 'Output JSON')
+ .action(
+ async (options: {
+ description?: string;
+ json?: boolean | string;
+ project?: string;
+ title: string;
+ widget?: string;
+ }) => {
+ // Home dashboards are personal-only: a workspace-level board would be
+ // created but have no page to open it on.
+ if (resolveWorkspaceId() && !options.project) {
+ log.error(
+ 'Workspace dashboards live inside a project: pass --project <projectId> (see `lh project list`).',
+ );
+ process.exitCode = 1;
+ return;
+ }
+ const client = await getTrpcClient();
+ const { data } = await client.dashboard.create.mutate({
+ description: options.description,
+ projectId: options.project,
+ title: options.title,
+ widgetId: options.widget,
+ });
+ if (options.json !== undefined) return outputJson(data, options.json);
+ const buildUrl = await resolveAppUrlBuilder(client);
+ console.log(`${pc.green('✓')} Created dashboard ${pc.bold(data.id)}`);
+ console.log(`${pc.bold('dashboard')}: ${buildUrl(dashboardPath(data))}`);
+ },
+ );
+
+ dashboard
+ .command('add <dashboardId> <widgetId>')
+ .description('Place a widget on a dashboard (an unpublished widget shows data once published)')
+ .action(async (dashboardId: string, widgetId: string) => {
+ await (await getTrpcClient()).dashboard.addItem.mutate({ dashboardId, widgetId });
+ console.log(`${pc.green('✓')} Placed widget ${pc.bold(widgetId)} on ${pc.bold(dashboardId)}`);
+ });
+}
diff --git a/apps/cli/src/commands/widget.test.ts b/apps/cli/src/commands/widget.test.ts
new file mode 100644
index 00000000000..c2a0491a3fa
--- /dev/null
+++ b/apps/cli/src/commands/widget.test.ts
@@ -0,0 +1,323 @@
+import { Command } from 'commander';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { registerDashboardCommand } from './dashboard';
+import { registerWidgetCommand } from './widget';
+
+const { mockClient, mockConfirm } = vi.hoisted(() => ({
+ mockClient: {
+ dashboard: {
+ addItem: { mutate: vi.fn() },
+ create: { mutate: vi.fn() },
+ detail: { query: vi.fn() },
+ list: { query: vi.fn() },
+ listByProject: { query: vi.fn() },
+ },
+ widget: {
+ create: { mutate: vi.fn() },
+ detail: { query: vi.fn() },
+ dryRun: { mutate: vi.fn() },
+ getRun: { query: vi.fn() },
+ getVersion: { query: vi.fn() },
+ list: { query: vi.fn() },
+ listByProject: { query: vi.fn() },
+ listRuns: { query: vi.fn() },
+ publish: { mutate: vi.fn() },
+ run: { mutate: vi.fn() },
+ saveDraft: { mutate: vi.fn() },
+ setSchedule: { mutate: vi.fn() },
+ update: { mutate: vi.fn() },
+ },
+ workspace: { getById: { query: vi.fn() } },
+ },
+ mockConfirm: vi.fn(),
+}));
+
+vi.mock('../api/client', () => ({ getTrpcClient: vi.fn().mockResolvedValue(mockClient) }));
+const { mockResolveWorkspaceId } = vi.hoisted(() => ({ mockResolveWorkspaceId: vi.fn() }));
+vi.mock('../api/workspace', () => ({ resolveWorkspaceId: mockResolveWorkspaceId }));
+vi.mock('../settings', () => ({ resolveServerUrl: () => 'https://app.example.com' }));
+vi.mock('../utils/logger', () => ({ log: { error: vi.fn(), info: vi.fn(), warn: vi.fn() } }));
+vi.mock('../utils/format', async (importOriginal) => ({
+ ...(await importOriginal<Record<string, unknown>>()),
+ confirm: mockConfirm,
+}));
+
+const run = (...args: string[]) => {
+ const program = new Command();
+ program.exitOverride();
+ registerWidgetCommand(program);
+ registerDashboardCommand(program);
+ return program.parseAsync(['node', 'test', ...args]);
+};
+
+const draftVersion = {
+ id: 'ver-1',
+ manifest: { network: { allow: ['api.github.com'] } },
+ outputType: 'stat',
+ runtime: 'node',
+ script: 'console.log(1)',
+ version: 1,
+ view: null,
+};
+
+describe('widget command', () => {
+ let logs: string[];
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ process.exitCode = undefined;
+ logs = [];
+ // A closed draft (no credentials, no network) by default; risky cases override it.
+ const closed = { id: 'ver-1', manifest: null };
+ mockClient.widget.getVersion.query.mockResolvedValue({ data: closed });
+ mockClient.widget.detail.query.mockResolvedValue({
+ data: { draftVersion: closed, publishedVersion: null },
+ });
+ vi.spyOn(console, 'log').mockImplementation((...args) => logs.push(args.join(' ')));
+ });
+
+ afterEach(() => {
+ process.exitCode = undefined;
+ vi.restoreAllMocks();
+ });
+
+ it('creates a widget owned by the given agent and placed on a board', async () => {
+ mockClient.widget.create.mutate.mockResolvedValue({ data: { id: 'w-1' } });
+ await run(
+ 'widget',
+ 'create',
+ '-t',
+ 'Open bugs',
+ '-d',
+ 'Bug issues',
+ '--agent',
+ 'agt_1',
+ '--dashboard',
+ 'd-1',
+ );
+ expect(mockClient.widget.create.mutate).toHaveBeenCalledWith({
+ agentId: 'agt_1',
+ dashboardId: 'd-1',
+ description: 'Bug issues',
+ projectId: undefined,
+ title: 'Open bugs',
+ });
+ });
+
+ it('keeps the current draft values for fields a new draft omits', async () => {
+ mockClient.widget.detail.query.mockResolvedValue({
+ data: { draftVersion, publishedVersion: null },
+ });
+ mockClient.widget.saveDraft.mutate.mockResolvedValue({ data: { id: 'ver-2', version: 2 } });
+
+ await run('widget', 'draft', 'w-1', '--script', 'console.log(2)', '--note', 'fix');
+
+ expect(mockClient.widget.saveDraft.mutate).toHaveBeenCalledWith({
+ changeNote: 'fix',
+ manifest: draftVersion.manifest,
+ outputType: 'stat',
+ runtime: 'node',
+ script: 'console.log(2)',
+ view: null,
+ widgetId: 'w-1',
+ });
+ });
+
+ it('refuses a first draft without a script, runtime and output type', async () => {
+ mockClient.widget.detail.query.mockResolvedValue({
+ data: { draftVersion: null, publishedVersion: null },
+ });
+ await run('widget', 'draft', 'w-1', '--script', 'echo 1');
+ expect(mockClient.widget.saveDraft.mutate).not.toHaveBeenCalled();
+ expect(process.exitCode).toBe(1);
+ });
+
+ it('prints a failed dry run with its logs and exits non-zero', async () => {
+ mockClient.widget.dryRun.mutate.mockResolvedValue({
+ data: { error: { code: 'EXIT' }, id: 'run-1', status: 'failed', stderr: 'boom' },
+ });
+ await run('widget', 'dry-run', 'w-1', '--version', 'ver-1');
+ expect(mockClient.widget.dryRun.mutate).toHaveBeenCalledWith({
+ versionId: 'ver-1',
+ widgetId: 'w-1',
+ });
+ expect(logs.join('\n')).toContain('boom');
+ expect(process.exitCode).toBe(1);
+ });
+
+ it('exits non-zero for a failed dry run with --json too', async () => {
+ mockClient.widget.dryRun.mutate.mockResolvedValue({ data: { id: 'run-1', status: 'timeout' } });
+ await run('widget', 'dry-run', 'w-1', '--json');
+ expect(process.exitCode).toBe(1);
+ });
+
+ it('treats a partial dry run as usable, like the publish gate does', async () => {
+ mockClient.widget.dryRun.mutate.mockResolvedValue({ data: { id: 'run-1', status: 'partial' } });
+ await run('widget', 'dry-run', 'w-1', '--json');
+ expect(process.exitCode).toBeUndefined();
+ });
+
+ describe('dry-run of a credentialed or networked draft', () => {
+ const risky = {
+ id: 'ver-2',
+ manifest: {
+ env: [{ connector: 'github', name: 'GITHUB_TOKEN' }],
+ network: { allow: ['api.github.com'] },
+ },
+ };
+ let isTTY: PropertyDescriptor | undefined;
+
+ beforeEach(() => {
+ mockClient.widget.getVersion.query.mockResolvedValue({ data: risky });
+ mockClient.widget.detail.query.mockResolvedValue({
+ data: { draftVersion: risky, publishedVersion: null },
+ });
+ mockClient.widget.dryRun.mutate.mockResolvedValue({
+ data: { id: 'run-1', status: 'succeeded' },
+ });
+ isTTY = Object.getOwnPropertyDescriptor(process.stdin, 'isTTY');
+ Object.defineProperty(process.stdin, 'isTTY', { configurable: true, value: false });
+ });
+
+ afterEach(() => {
+ if (isTTY) Object.defineProperty(process.stdin, 'isTTY', isTTY);
+ else delete (process.stdin as { isTTY?: boolean }).isTTY;
+ });
+
+ it('refuses to run without the user’s approval and says what to show them', async () => {
+ await run('widget', 'dry-run', 'w-1', '--version', 'ver-2');
+ expect(mockClient.widget.dryRun.mutate).not.toHaveBeenCalled();
+ expect(process.exitCode).toBe(1);
+ const { log } = await import('../utils/logger');
+ expect(vi.mocked(log.error).mock.calls[0][0]).toMatch(
+ /GITHUB_TOKEN \(github\).*api\.github\.com.*--version ver-2 --yes/,
+ );
+ });
+
+ it('refuses --yes without the exact version the approval covers', async () => {
+ await run('widget', 'dry-run', 'w-1', '--yes');
+ expect(mockClient.widget.dryRun.mutate).not.toHaveBeenCalled();
+ expect(process.exitCode).toBe(1);
+ });
+
+ it('runs the approved exact version with --version and --yes', async () => {
+ await run('widget', 'dry-run', 'w-1', '--version', 'ver-2', '--yes');
+ expect(mockClient.widget.dryRun.mutate).toHaveBeenCalledWith({
+ versionId: 'ver-2',
+ widgetId: 'w-1',
+ });
+ });
+
+ it('asks interactively in a terminal', async () => {
+ Object.defineProperty(process.stdin, 'isTTY', { configurable: true, value: true });
+ mockConfirm.mockResolvedValue(false);
+ await run('widget', 'dry-run', 'w-1', '--version', 'ver-2');
+ expect(mockConfirm).toHaveBeenCalled();
+ expect(mockClient.widget.dryRun.mutate).not.toHaveBeenCalled();
+ });
+ });
+
+ it('exits non-zero when a manual refresh fails', async () => {
+ mockClient.widget.run.mutate.mockResolvedValue({ data: { id: 'run-1', status: 'failed' } });
+ await run('widget', 'run', 'w-1', '--json');
+ expect(process.exitCode).toBe(1);
+ });
+
+ it('treats a partial manual refresh as usable', async () => {
+ mockClient.widget.run.mutate.mockResolvedValue({ data: { id: 'run-1', status: 'partial' } });
+ await run('widget', 'run', 'w-1');
+ expect(process.exitCode).toBeUndefined();
+ });
+
+ it('does not publish when the confirmation is declined', async () => {
+ mockConfirm.mockResolvedValue(false);
+ await run('widget', 'publish', 'w-1', '--version', 'ver-1');
+ expect(mockClient.widget.publish.mutate).not.toHaveBeenCalled();
+ });
+
+ it('publishes the exact version with --yes and fills the card right away', async () => {
+ mockClient.widget.publish.mutate.mockResolvedValue({ data: { version: { version: 3 } } });
+ mockClient.widget.run.mutate.mockResolvedValue({ data: { status: 'succeeded' } });
+ await run('widget', 'publish', 'w-1', '--version', 'ver-3', '--yes');
+ expect(mockConfirm).not.toHaveBeenCalled();
+ expect(mockClient.widget.publish.mutate).toHaveBeenCalledWith({
+ versionId: 'ver-3',
+ widgetId: 'w-1',
+ });
+ expect(mockClient.widget.run.mutate).toHaveBeenCalledWith({ widgetId: 'w-1' });
+ });
+
+ it('clears the schedule with "off"', async () => {
+ mockClient.widget.setSchedule.mutate.mockResolvedValue({ data: {} });
+ await run('widget', 'schedule', 'w-1', 'off');
+ expect(mockClient.widget.setSchedule.mutate).toHaveBeenCalledWith({
+ id: 'w-1',
+ pattern: null,
+ timezone: undefined,
+ });
+ });
+});
+
+describe('dashboard command', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ process.exitCode = undefined;
+ mockResolveWorkspaceId.mockReturnValue(undefined);
+ vi.spyOn(console, 'log').mockImplementation(() => {});
+ });
+
+ afterEach(() => {
+ process.exitCode = undefined;
+ vi.restoreAllMocks();
+ });
+
+ it('lists a project’s boards', async () => {
+ mockClient.dashboard.listByProject.query.mockResolvedValue({ data: [] });
+ await run('dashboard', 'list', '--project', 'prj_1');
+ expect(mockClient.dashboard.listByProject.query).toHaveBeenCalledWith({ projectId: 'prj_1' });
+ });
+
+ it('creates a board inside a project with a widget on it', async () => {
+ mockClient.dashboard.create.mutate.mockResolvedValue({
+ data: { id: 'd-1', projectId: 'prj_1', title: 'Ops' },
+ });
+ await run('dashboard', 'create', '-t', 'Ops', '--project', 'prj_1', '--widget', 'w-1');
+ expect(mockClient.dashboard.create.mutate).toHaveBeenCalledWith({
+ description: undefined,
+ projectId: 'prj_1',
+ title: 'Ops',
+ widgetId: 'w-1',
+ });
+ expect(console.log).toHaveBeenCalledWith(
+ expect.stringContaining('https://app.example.com/project/prj_1/dashboard/d-1'),
+ );
+ });
+
+ it('refuses a project-less board in a workspace, where it could not be opened', async () => {
+ mockResolveWorkspaceId.mockReturnValue('ws_1');
+ await run('dashboard', 'create', '-t', 'Ops');
+ expect(mockClient.dashboard.create.mutate).not.toHaveBeenCalled();
+ expect(process.exitCode).toBe(1);
+ });
+
+ it('creates a project board in a workspace', async () => {
+ mockResolveWorkspaceId.mockReturnValue('ws_1');
+ mockClient.workspace.getById.query.mockResolvedValue({ slug: 'team' });
+ mockClient.dashboard.create.mutate.mockResolvedValue({
+ data: { id: 'd-1', projectId: 'prj_1', title: 'Ops' },
+ });
+ await run('dashboard', 'create', '-t', 'Ops', '--project', 'prj_1');
+ expect(mockClient.dashboard.create.mutate).toHaveBeenCalled();
+ expect(process.exitCode).toBeUndefined();
+ });
+
+ it('places a widget on a board', async () => {
+ mockClient.dashboard.addItem.mutate.mockResolvedValue({ data: {} });
+ await run('dashboard', 'add', 'd-1', 'w-1');
+ expect(mockClient.dashboard.addItem.mutate).toHaveBeenCalledWith({
+ dashboardId: 'd-1',
+ widgetId: 'w-1',
+ });
+ });
+});
diff --git a/apps/cli/src/commands/widget.ts b/apps/cli/src/commands/widget.ts
new file mode 100644
index 00000000000..7c378d5eb5d
--- /dev/null
+++ b/apps/cli/src/commands/widget.ts
@@ -0,0 +1,369 @@
+import { readFile } from 'node:fs/promises';
+
+import { WIDGET_OUTPUT_TYPES, WIDGET_RUN_OUTPUT_STATUSES, WIDGET_RUNTIMES } from '@lobechat/types';
+import type { Command } from 'commander';
+import pc from 'picocolors';
+
+import { getTrpcClient } from '../api/client';
+import { confirm, outputJson, printTable, timeAgo, truncate } from '../utils/format';
+import { log } from '../utils/logger';
+
+type WidgetRuntime = (typeof WIDGET_RUNTIMES)[number];
+type WidgetOutputType = (typeof WIDGET_OUTPUT_TYPES)[number];
+
+const parseJsonOption = (value: string | undefined, flag: string) => {
+ if (value === undefined) return undefined;
+ try {
+ return JSON.parse(value) as Record<string, unknown>;
+ } catch {
+ throw new Error(`${flag} must be valid JSON`);
+ }
+};
+
+const fail = (message: string) => {
+ log.error(message);
+ process.exitCode = 1;
+};
+
+/**
+ * Failed runs come back as records, not errors. `succeeded` and `partial` both
+ * carry output the card can show and the publish gate accepts.
+ */
+const isUsableRun = (status: string) =>
+ (WIDGET_RUN_OUTPUT_STATUSES as readonly string[]).includes(status);
+
+interface RunManifest {
+ env?: { connector?: string; name: string }[];
+ network?: { allow?: string[] };
+}
+
+/** What a version can reach outside the sandbox, or undefined for a closed run. */
+const describeRunRisk = (manifest: unknown) => {
+ const { env = [], network } = (manifest ?? {}) as RunManifest;
+ const hosts = network?.allow ?? [];
+ const parts = [
+ env.length > 0 &&
+ `credentials ${env.map((e) => (e.connector ? `${e.name} (${e.connector})` : e.name)).join(', ')}`,
+ hosts.length > 0 && `network hosts ${hosts.join(', ')}`,
+ ].filter(Boolean);
+ return parts.length > 0 ? parts.join(' and ') : undefined;
+};
+
+interface RunLike {
+ durationMs?: number | null;
+ error?: unknown;
+ id: string;
+ output?: unknown;
+ status: string;
+ stderr?: string | null;
+ stdout?: string | null;
+ trigger?: string;
+ versionId?: string | null;
+}
+
+/** A run's verdict, parsed output and logs — what an author needs to fix a script. */
+const printRun = (run: RunLike) => {
+ const color = run.status === 'succeeded' ? pc.green : run.status === 'failed' ? pc.red : pc.dim;
+ console.log(`${pc.bold('Run')} ${pc.dim(run.id)} ${color(run.status)}`);
+ if (run.versionId) console.log(`${pc.dim('Version:')} ${run.versionId}`);
+ if (run.durationMs != null) console.log(`${pc.dim('Duration:')} ${run.durationMs}ms`);
+ if (run.error) console.log(`\n${pc.red('Error:')}\n${JSON.stringify(run.error, null, 2)}`);
+ if (run.output) console.log(`\n${pc.bold('Output:')}\n${JSON.stringify(run.output, null, 2)}`);
+ if (run.stdout) console.log(`\n${pc.bold('stdout:')}\n${run.stdout}`);
+ if (run.stderr) console.log(`\n${pc.bold('stderr:')}\n${run.stderr}`);
+};
+
+export function registerWidgetCommand(program: Command) {
+ const widget = program
+ .command('widget')
+ .description('Build monitoring widgets: sandboxed scripts rendered as dashboard cards');
+
+ widget
+ .command('list')
+ .description('List widgets')
+ .option('--agent <agentId>', 'Only widgets owned by this agent')
+ .option('--project <projectId>', "Every widget of a project, including its agents' widgets")
+ .option('--json [fields]', 'Output JSON')
+ .action(async (options: { agent?: string; json?: boolean | string; project?: string }) => {
+ const client = await getTrpcClient();
+ const { data } =
+ options.project && !options.agent
+ ? await client.widget.listByProject.query({ projectId: options.project })
+ : await client.widget.list.query({ agentId: options.agent, projectId: options.project });
+ if (options.json !== undefined) return outputJson(data, options.json);
+ if (data.length === 0) return console.log('No widgets found.');
+ printTable(
+ data.map((item) => [
+ item.id,
+ truncate(item.title, 40),
+ item.publishedVersionId ? 'live' : 'draft',
+ item.lastRunStatus ?? '-',
+ item.schedulePattern ?? '-',
+ timeAgo(item.updatedAt),
+ ]),
+ ['ID', 'TITLE', 'STATE', 'LAST RUN', 'SCHEDULE', 'UPDATED'],
+ );
+ });
+
+ widget
+ .command('view <id>')
+ .description('View a widget with its draft / live versions and the boards it is on')
+ .option('--script', 'Also print the draft script')
+ .option('--json [fields]', 'Output JSON')
+ .action(async (id: string, options: { json?: boolean | string; script?: boolean }) => {
+ const { data } = await (await getTrpcClient()).widget.detail.query({ id });
+ if (options.json !== undefined) return outputJson(data, options.json);
+ console.log(`\n${pc.bold(data.title)} ${pc.dim(data.id)}`);
+ if (data.description) console.log(data.description);
+ const describe = (version: typeof data.draftVersion) =>
+ version
+ ? `v${version.version} ${pc.dim(version.id)} (${version.runtime}, ${version.outputType})`
+ : '-';
+ console.log(`\n${pc.dim('Live:')} ${describe(data.publishedVersion)}`);
+ console.log(`${pc.dim('Draft:')} ${describe(data.draftVersion)}`);
+ console.log(`${pc.dim('Schedule:')} ${data.schedulePattern ?? '-'}`);
+ console.log(`${pc.dim('Last run:')} ${data.lastRunStatus ?? '-'}`);
+ if (data.dashboards.length > 0) {
+ console.log(`${pc.dim('Boards:')} ${data.dashboards.map((d) => d.title).join(', ')}`);
+ }
+ if (options.script && data.draftVersion) console.log(`\n${data.draftVersion.script}`);
+ });
+
+ widget
+ .command('create')
+ .description('Create a widget (no script yet; save one with `widget draft`)')
+ .requiredOption('-t, --title <title>', 'Short card title')
+ .option('-d, --description <text>', 'Metric definition: source, filters, time window, unit')
+ .option('--agent <agentId>', 'Owning agent (pass your own agent id when you author it)')
+ .option('--project <projectId>', 'Owning project')
+ .option('--dashboard <dashboardId>', 'Place the widget on this board right away')
+ .option('--json [fields]', 'Output JSON')
+ .action(
+ async (options: {
+ agent?: string;
+ dashboard?: string;
+ description?: string;
+ json?: boolean | string;
+ project?: string;
+ title: string;
+ }) => {
+ const { data } = await (
+ await getTrpcClient()
+ ).widget.create.mutate({
+ agentId: options.agent,
+ dashboardId: options.dashboard,
+ description: options.description,
+ projectId: options.project,
+ title: options.title,
+ });
+ if (options.json !== undefined) return outputJson(data, options.json);
+ console.log(`${pc.green('✓')} Created widget ${pc.bold(data.id)}`);
+ },
+ );
+
+ widget
+ .command('edit <id>')
+ .description('Rename a widget or rewrite its metric definition')
+ .option('-t, --title <title>', 'Card title')
+ .option('-d, --description <text>', 'Metric definition')
+ .action(async (id: string, options: { description?: string; title?: string }) => {
+ await (await getTrpcClient()).widget.update.mutate({ id, value: options });
+ console.log(`${pc.green('✓')} Updated widget ${pc.bold(id)}`);
+ });
+
+ widget
+ .command('draft <widgetId>')
+ .description(
+ "Save a new draft version; omitted fields keep the current draft's values. Nothing goes live",
+ )
+ .option('--script-file <path>', 'Read the script from a file')
+ .option('--script <code>', 'The script inline')
+ .option('--runtime <runtime>', `Runtime (${WIDGET_RUNTIMES.join(', ')})`)
+ .option('--output-type <type>', `Printed JSON shape (${WIDGET_OUTPUT_TYPES.join(', ')})`)
+ .option('--manifest <json>', 'Manifest JSON: env, network, schedule, metric, timeoutMs')
+ .option('--view <json>', 'View hints JSON: chart, columns, limit')
+ .option('--note <text>', 'One line on what changed')
+ .option('--json [fields]', 'Output JSON')
+ .action(
+ async (
+ widgetId: string,
+ options: {
+ json?: boolean | string;
+ manifest?: string;
+ note?: string;
+ outputType?: string;
+ runtime?: string;
+ script?: string;
+ scriptFile?: string;
+ view?: string;
+ },
+ ) => {
+ const client = await getTrpcClient();
+ const { data: current } = await client.widget.detail.query({ id: widgetId });
+ const base = current.draftVersion ?? current.publishedVersion;
+
+ const script = options.scriptFile
+ ? await readFile(options.scriptFile, 'utf8')
+ : (options.script ?? base?.script);
+ const runtime = options.runtime ?? base?.runtime;
+ const outputType = options.outputType ?? base?.outputType;
+ if (!script || !runtime || !outputType) {
+ return fail('The first draft needs a script, --runtime and --output-type.');
+ }
+ if (!WIDGET_RUNTIMES.includes(runtime as WidgetRuntime)) {
+ return fail(`--runtime must be one of: ${WIDGET_RUNTIMES.join(', ')}`);
+ }
+ if (!WIDGET_OUTPUT_TYPES.includes(outputType as WidgetOutputType)) {
+ return fail(`--output-type must be one of: ${WIDGET_OUTPUT_TYPES.join(', ')}`);
+ }
+
+ const { data } = await client.widget.saveDraft.mutate({
+ changeNote: options.note,
+ manifest: (parseJsonOption(options.manifest, '--manifest') ?? base?.manifest) as any,
+ outputType: outputType as WidgetOutputType,
+ runtime: runtime as WidgetRuntime,
+ script,
+ view: (parseJsonOption(options.view, '--view') ?? base?.view) as any,
+ widgetId,
+ });
+ if (options.json !== undefined) return outputJson(data, options.json);
+ console.log(`${pc.green('✓')} Saved draft v${data.version} ${pc.bold(data.id)}`);
+ console.log(pc.dim(`Next: lh widget dry-run ${widgetId} --version ${data.id}`));
+ },
+ );
+
+ widget
+ .command('dry-run <widgetId>')
+ .description(
+ "Run a draft once in the sandbox and print its real output and logs. A draft with connector credentials or network hosts needs the user's approval of that exact version (--version + --yes)",
+ )
+ .option('--version <versionId>', 'Draft version to run (default: the current draft)')
+ .option('--yes', "Confirm the user approved this exact version's credentials and hosts")
+ .option('--json [fields]', 'Output JSON')
+ .action(
+ async (
+ widgetId: string,
+ options: { json?: boolean | string; version?: string; yes?: boolean },
+ ) => {
+ const client = await getTrpcClient();
+ const version = options.version
+ ? (await client.widget.getVersion.query({ versionId: options.version, widgetId })).data
+ : await (async () => {
+ const { data } = await client.widget.detail.query({ id: widgetId });
+ return data.draftVersion ?? data.publishedVersion;
+ })();
+ if (!version) return fail('This widget has no version to dry-run yet.');
+
+ // Credentialed or networked code can act on the user's behalf — or leak
+ // the credential — the moment it runs, so it needs consent for exactly
+ // this version, the same rule the Dashboards builtin tool enforces.
+ const risk = describeRunRisk(version.manifest);
+ if (risk) {
+ const ask = `Version ${version.id} uses ${risk}.`;
+ if (!options.yes) {
+ if (!process.stdin.isTTY) {
+ return fail(
+ `${ask} Show the user this version id, what the script does and the ${risk}, wait for their explicit approval, then rerun with --version ${version.id} --yes.`,
+ );
+ }
+ if (!(await confirm(`${ask} Run it?`))) return;
+ } else if (!options.version) {
+ return fail(
+ `${ask} Pass --version ${version.id} with --yes so the approval covers exactly this version.`,
+ );
+ }
+ }
+
+ const { data } = await client.widget.dryRun.mutate({ versionId: version.id, widgetId });
+ // Publish accepts any usable run (partial included), so only failed / timed-out
+ // dry runs fail — JSON output included.
+ if (!isUsableRun(data.status)) process.exitCode = 1;
+ if (options.json !== undefined) return outputJson(data, options.json);
+ printRun(data);
+ },
+ );
+
+ widget
+ .command('publish <widgetId>')
+ .description('Make a draft version live; it must have succeeded in a dry run')
+ .requiredOption('--version <versionId>', 'Exact draft version to publish')
+ .option('--yes', 'Skip confirmation')
+ .action(async (widgetId: string, options: { version: string; yes?: boolean }) => {
+ if (!options.yes && !(await confirm('Publish this version? It runs on its schedule.'))) {
+ return;
+ }
+ const client = await getTrpcClient();
+ const { data } = await client.widget.publish.mutate({ versionId: options.version, widgetId });
+ console.log(`${pc.green('✓')} Published v${data.version.version} of ${pc.bold(widgetId)}`);
+ // Fill the live card right away instead of waiting for the first tick.
+ const run = await client.widget.run.mutate({ widgetId }).catch((error: Error) => {
+ log.warn(`First run after publish failed: ${error.message}`);
+ return undefined;
+ });
+ if (run) console.log(`${pc.dim('First run:')} ${run.data.status}`);
+ });
+
+ widget
+ .command('run <widgetId>')
+ .description('Refresh the live version now')
+ .option('--json [fields]', 'Output JSON')
+ .action(async (widgetId: string, options: { json?: boolean | string }) => {
+ const { data } = await (await getTrpcClient()).widget.run.mutate({ widgetId });
+ if (!isUsableRun(data.status)) process.exitCode = 1;
+ if (options.json !== undefined) return outputJson(data, options.json);
+ printRun(data);
+ });
+
+ widget
+ .command('runs <widgetId>')
+ .description('Recent runs (scheduled, manual, preview), newest first')
+ .option('--run <runId>', "Print one run's full output and logs")
+ .option('-L, --limit <n>', 'How many runs to list', '10')
+ .option('--json [fields]', 'Output JSON')
+ .action(
+ async (
+ widgetId: string,
+ options: { json?: boolean | string; limit: string; run?: string },
+ ) => {
+ const client = await getTrpcClient();
+ if (options.run) {
+ const { data } = await client.widget.getRun.query({ runId: options.run, widgetId });
+ if (options.json !== undefined) return outputJson(data, options.json);
+ return printRun(data);
+ }
+ const { data } = await client.widget.listRuns.query({
+ limit: Number.parseInt(options.limit, 10),
+ widgetId,
+ });
+ if (options.json !== undefined) return outputJson(data, options.json);
+ if (data.length === 0) return console.log('No runs yet.');
+ printTable(
+ data.map((run) => [
+ run.id,
+ run.trigger,
+ run.status,
+ run.durationMs != null ? `${run.durationMs}ms` : '-',
+ timeAgo(run.startedAt ?? run.createdAt),
+ ]),
+ ['ID', 'TRIGGER', 'STATUS', 'DURATION', 'STARTED'],
+ );
+ },
+ );
+
+ widget
+ .command('schedule <widgetId> <pattern>')
+ .description('Set the refresh cron pattern of the live widget, or "off" to clear it')
+ .option('--timezone <tz>', 'IANA timezone, e.g. Asia/Shanghai')
+ .action(async (widgetId: string, pattern: string, options: { timezone?: string }) => {
+ await (
+ await getTrpcClient()
+ ).widget.setSchedule.mutate({
+ id: widgetId,
+ pattern: pattern === 'off' ? null : pattern,
+ timezone: options.timezone,
+ });
+ console.log(
+ `${pc.green('✓')} Schedule ${pattern === 'off' ? 'cleared' : `set to ${pattern}`}`,
+ );
+ });
+}
diff --git a/apps/cli/src/program.ts b/apps/cli/src/program.ts
index 6ee61b4954d..3334b57a711 100644
--- a/apps/cli/src/program.ts
+++ b/apps/cli/src/program.ts
@@ -8,6 +8,7 @@ import { registerBotCommand } from './commands/bot';
import { registerCompletionCommand } from './commands/completion';
import { registerConfigCommand } from './commands/config';
import { registerConnectCommand } from './commands/connect';
+import { registerDashboardCommand } from './commands/dashboard';
import { registerDeviceCommand } from './commands/device';
import { registerDocCommand } from './commands/doc';
import { registerDoctorCommand } from './commands/doctor';
@@ -40,6 +41,7 @@ import { registerUpdateCommand } from './commands/update';
import { registerUserCommand } from './commands/user';
import { registerVerifyCommand } from './commands/verify';
import { registerAcceptanceCommands } from './commands/verifyAcceptance';
+import { registerWidgetCommand } from './commands/widget';
import { registerWorkspaceCommand } from './commands/workspace';
import { CLI_DISPLAY_NAME, CLI_PRIMARY_BIN, CLI_PRODUCT_NAME } from './constants/identity';
import { cliVersion } from './pkg';
@@ -106,6 +108,8 @@ export function createProgram() {
registerNotifyCommand(program);
registerProviderCommand(program);
registerProjectCommand(program);
+ registerDashboardCommand(program);
+ registerWidgetCommand(program);
registerPluginCommand(program);
registerWorkspaceCommand(program);
registerUserCommand(program);
diff --git a/packages/builtin-skills/src/lobehub/content.ts b/packages/builtin-skills/src/lobehub/content.ts
index 993999a0eef..653b8dd8d4d 100644
--- a/packages/builtin-skills/src/lobehub/content.ts
+++ b/packages/builtin-skills/src/lobehub/content.ts
@@ -59,6 +59,7 @@ run commands.
| \`lh provider\` | AI provider management |
| \`lh plugin\` | Plugin management |
| \`lh bot\` | Bot integration management (Discord, Slack, Telegram, etc.) |
+| \`lh widget\` / \`lh dashboard\` | Monitoring widgets (sandboxed scripts) and the dashboards they sit on |
| \`lh eval\` | Evaluation workflow management |
| \`lh whoami\` / \`lh usage\` | User info and usage statistics (top-level commands, not a \`config\` module) |
diff --git a/packages/builtin-skills/src/lobehub/index.ts b/packages/builtin-skills/src/lobehub/index.ts
index 1973ed147d6..16d1757bab0 100644
--- a/packages/builtin-skills/src/lobehub/index.ts
+++ b/packages/builtin-skills/src/lobehub/index.ts
@@ -13,6 +13,7 @@ import botSlack from './references/bot-slack';
import botTelegram from './references/bot-telegram';
import botWechat from './references/bot-wechat';
import config from './references/config';
+import dashboard from './references/dashboard';
import doc from './references/doc';
import eval_ from './references/eval';
import file from './references/file';
@@ -43,6 +44,7 @@ export const LobeHubSkill: BuiltinSkill = {
'references/bot/telegram': botTelegram,
'references/bot/wechat': botWechat,
'references/config': config,
+ 'references/dashboard': dashboard,
'references/doc': doc,
'references/eval': eval_,
'references/file': file,
diff --git a/packages/builtin-skills/src/lobehub/references/dashboard.ts b/packages/builtin-skills/src/lobehub/references/dashboard.ts
new file mode 100644
index 00000000000..e4753a8f000
--- /dev/null
+++ b/packages/builtin-skills/src/lobehub/references/dashboard.ts
@@ -0,0 +1,77 @@
+const content = `# lh widget / lh dashboard - Monitoring Widgets and Dashboards
+
+A widget is a small script the platform runs in an isolated sandbox on a schedule; the one JSON
+document it prints to stdout is rendered as a card. Dashboards are boards of widget cards.
+
+When the Dashboards builtin tool is enabled in this conversation, prefer it: it previews widgets in the chat
+and asks the user to approve risky dry runs and publishing. Use these commands when that tool is not available.
+
+## Subcommands
+
+- \`lh dashboard list [--project <projectId>]\` - List boards (with \`--project\`, every board of that project)
+- \`lh dashboard view <id>\` - A board and the widgets on it
+- \`lh dashboard create -t <title> [--project <projectId>] [--widget <widgetId>]\` - Create a board, optionally placing a widget (\`--project\` is required in a workspace: home boards are personal-only)
+- \`lh dashboard add <dashboardId> <widgetId>\` - Place a widget on a board
+- \`lh widget list [--agent <agentId>] [--project <projectId>]\` - List widgets
+- \`lh widget view <id> [--script]\` - A widget with its draft / live versions and boards
+- \`lh widget create -t <title> -d <metric definition> [--agent <agentId>] [--project <projectId>] [--dashboard <id>]\` - Create a widget (no script yet)
+- \`lh widget edit <id> [-t <title>] [-d <metric definition>]\` - Rename or rewrite the metric definition
+- \`lh widget draft <widgetId> [--script-file <path>] [--runtime <rt>] [--output-type <type>] [--manifest <json>] [--view <json>] [--note <text>]\` - Save a new draft; omitted fields keep the current draft's values
+- \`lh widget dry-run <widgetId> [--version <versionId>] [--yes]\` - Run a draft once and print its REAL output, stdout/stderr and error (\`--yes\` only after the user approved a credentialed or networked version)
+- \`lh widget publish <widgetId> --version <versionId> [--yes]\` - Make a dry-run-succeeded draft live
+- \`lh widget run <widgetId>\` - Refresh the live version now
+- \`lh widget runs <widgetId> [--run <runId>] [-L <n>]\` - Recent runs; \`--run\` for one run's full logs
+- \`lh widget schedule <widgetId> <cron|off> [--timezone <tz>]\` - Set or clear the refresh cadence
+
+## Workflow
+
+1. \`lh widget list --agent <your agent id>\` and \`lh dashboard list\` — extend an existing widget instead of duplicating it, and pick a board.
+2. \`lh widget create\` with \`--agent <your agent id>\` (and \`--project\` in a project conversation), then \`lh widget draft\` with the script.
+3. \`lh widget dry-run <widgetId> --version <versionId>\` → read the output and logs → \`lh widget draft\` again → dry-run the new version … until it succeeds (or is \`partial\`, a run that still printed usable output) and the numbers look plausible. A draft with connector credentials or network hosts needs the user's approval first (see below). Do not stop at the first failure and do not ask the user to debug for you.
+4. Show the user what the widget measures and the dry-run result, and **get their explicit confirmation before** \`lh widget publish <widgetId> --version <versionId> --yes\`. Publishing makes the script run unattended on a schedule; never publish on your own initiative. Only a version whose exact content produced usable output (\`succeeded\` or \`partial\`) in a dry run can be published.
+5. \`lh dashboard add <dashboardId> <widgetId>\` (or \`lh dashboard create -t <title> --widget <widgetId>\`) if the user wants it on a board — prefer the project's boards for a project's widgets.
+
+A draft that declares connector credentials (\`manifest.env\`) or network hosts (\`manifest.network.allow\`)
+can act on the user's behalf — or leak a credential — the moment it runs. Before every dry run of such a
+draft, show the user the exact version id, the credentials and hosts it uses and what the script does, then
+**wait for their explicit approval of that exact version**, then run \`lh widget dry-run <widgetId> --version <versionId> --yes\` (the CLI refuses such a draft without it); a new draft needs a new approval. If they decline,
+ask what to change instead of retrying the same draft. A draft with neither runs in a closed sandbox and
+needs no approval.
+
+## Output contract
+
+The script must print exactly ONE JSON document to stdout — nothing else (debug output goes to stderr).
+Its \`"type"\` must equal the widget's output type:
+
+- stat: \`{"type":"stat","value":1234,"label":"Open issues","unit":"issues","delta":-12,"trend":"down","description":"vs last week"}\`
+- list: \`{"type":"list","items":[{"title":"Fix login","url":"https://…","status":"open","time":"2026-01-02T03:04:05Z","value":3,"description":"…"}]}\`
+- series: \`{"type":"series","unit":"ms","series":[{"name":"p95","points":[{"t":"2026-01-01","v":120},{"t":"2026-01-02","v":98}]}]}\`
+- table: \`{"type":"table","columns":[{"key":"repo","title":"Repo"},{"key":"stars","type":"number"}],"rows":[{"repo":"lobehub","stars":100}]}\`
+
+Only \`type\` plus value / items / series / columns+rows are required. Column types: string | number | date | link.
+Timestamps are ISO-8601 strings. When one of several sources fails, still print the document with
+\`"meta":{"complete":false,"message":"GitHub API rate-limited"}\` — the card shows it as partial. Exit non-zero
+only when there is nothing meaningful to show.
+
+## Script rules
+
+- Runtime: \`node\` (global fetch, no npm packages), \`python\` (standard library only) or \`bash\` (curl; jq may be absent). Keep scripts short, deterministic and read-only: they run unattended on every refresh and must never create, modify or delete anything in external systems.
+- Network is OFF unless \`manifest.network.allow\` lists the hostnames the script calls, e.g. \`{"network":{"allow":["api.github.com"]}}\`.
+- Secrets: never write a token, password or key into the script, manifest, title or description. Declare them in \`manifest.env\`, e.g. \`{"env":[{"name":"GITHUB_TOKEN","connector":"github","required":true}]}\`; the platform injects the value from the user's connected account and redacts it from logs. For a connector holding several headers, add \`"field"\` with the header to inject. If a run fails because the connector is not connected, tell the user which connector to connect — do not ask them to paste a secret into the chat.
+- \`manifest.schedule\` suggests the refresh cadence applied on publish (\`{"pattern":"0 * * * *"}\`); pick the slowest cadence that keeps the number useful. \`manifest.timeoutMs\` defaults to 30000 (max 120000).
+- \`manifest.metric\` (\`{"key":"open_issues","unit":"issues"}\`) records a stat's value on every published run for a long-term trend line.
+- \`--view\` hints: \`{"chart":"line"|"bar"|"area"}\` for series, \`{"columns":[…]}\` for table columns, \`{"limit":10}\` to cap rows.
+
+## Metric definition
+
+The widget description (口径) is shown on the card and must let the user trust the number: data source,
+filters, time window and unit — e.g. "Open issues labelled bug in lobehub/lobehub, excluding pull requests;
+counted at run time." Update it with \`lh widget edit\` whenever the script's logic changes.
+
+## Tips
+
+- Dashboards are behind the \`dashboard\` feature flag; a FORBIDDEN error means it is off for this user — say so instead of retrying.
+- Write the script to a file and pass \`--script-file\`; it avoids shell-quoting problems.
+`;
+
+export default content;
diff --git a/packages/heterogeneous-agents/src/protocol/lobeHubCliGuide.ts b/packages/heterogeneous-agents/src/protocol/lobeHubCliGuide.ts
index f010d0ac7b7..b3a28ee0c55 100644
--- a/packages/heterogeneous-agents/src/protocol/lobeHubCliGuide.ts
+++ b/packages/heterogeneous-agents/src/protocol/lobeHubCliGuide.ts
@@ -46,7 +46,8 @@ export const lobeHubCliGuide = [
'',
'- **You already know where you are.** `LOBEHUB_TOPIC_ID` (this conversation) and `LOBEHUB_OPERATION_ID` (this run) are in your environment, and `LOBEHUB_AGENT_ID` (you) is too whenever the run carries one. They are ordinary environment variables, so every sub-shell, script or tool you spawn inherits them. Pass them straight to commands rather than listing agents or topics to find yourself; if the one you need is empty, say so instead of guessing an id.',
'- **Look commands up, do not guess them.** `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 search` local resources and the web · `lh gen` text/image/video/TTS/ASR generation · `lh memory` user memory · `lh notify` notifications to the user · `lh model` / `lh provider` / `lh 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 widget` / `lh dashboard` monitoring widgets and dashboards · `lh search` local resources and the web · `lh gen` text/image/video/TTS/ASR generation · `lh memory` user memory · `lh notify` notifications to the user · `lh model` / `lh provider` / `lh 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.",
'- **When to use it:** whenever the user asks for something that lives in LobeHub rather than in this working directory — saving a document, recalling an earlier conversation, generating an image, or changing your own agent configuration. Say what you did and where it landed.',
"- **If a command comes back with an authentication or permission error**, clear `LOBEHUB_JWT` and retry it once — some runs carry a narrow token scoped to this conversation, which shadows the machine's own login. An empty value is enough, so use whichever form your shell takes: `LOBEHUB_JWT= lh …` (sh/bash/zsh), `$env:LOBEHUB_JWT=''; lh …` (PowerShell), `set LOBEHUB_JWT=` then `lh …` (cmd). If it still fails, 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 in this session.',