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(dashboard): widget presets, user params and a shared widget-spec package (#22049)

Arvin Xuf39181e61294
diff --git a/apps/server/src/services/widget/__tests__/executeRun.test.ts b/apps/server/src/services/widget/__tests__/executeRun.test.ts
index 744ba45c1a3..4b5656194d0 100644
--- a/apps/server/src/services/widget/__tests__/executeRun.test.ts
+++ b/apps/server/src/services/widget/__tests__/executeRun.test.ts
@@ -98,6 +98,73 @@ describe('executeWidgetRun', () => {
expect((run.mock.calls[0] as any[])[0].network).toEqual({ allow: ['api.github.com'] });
});
+
+ it('passes params to the script as env without redacting them from the logs', async () => {
+ const run = vi.fn(async () => ({
+ durationMs: 10,
+ exitCode: 0,
+ stderr: 'city=Hangzhou days=3',
+ stdout: '{"type":"stat","value":1}',
+ timedOut: false,
+ }));
+ const withParams = {
+ ...params,
+ version: {
+ ...params.version,
+ manifest: {
+ ...params.version.manifest,
+ params: [
+ { name: 'CITY', type: 'string', value: 'Hangzhou' },
+ { default: 3, name: 'DAYS', type: 'number' },
+ { name: 'UNSET', type: 'string' },
+ ],
+ },
+ },
+ };
+
+ await executeWidgetRun({} as any, withParams, {
+ resolveEnv: vi.fn(async () => ({ env: { GITHUB_TOKEN: 'tok' }, inject: [] })),
+ runner: { run },
+ });
+
+ expect((run.mock.calls[0] as any[])[0].env).toEqual({
+ CITY: 'Hangzhou',
+ DAYS: '3',
+ GITHUB_TOKEN: 'tok',
+ });
+ expect(vi.mocked(WidgetModel.finishRun)).toHaveBeenLastCalledWith(
+ {},
+ 'run-1',
+ expect.objectContaining({ stderr: 'city=Hangzhou days=3' }),
+ expect.any(Function),
+ );
+ });
+
+ it('fails a run whose required param has no value, before resolving env or the sandbox', async () => {
+ const resolveEnv = vi.fn();
+ const run = vi.fn();
+ const missing = {
+ ...params,
+ version: {
+ ...params.version,
+ manifest: { params: [{ label: 'City', name: 'CITY', required: true, type: 'string' }] },
+ },
+ };
+
+ await executeWidgetRun({} as any, missing, { resolveEnv, runner: { run } });
+
+ expect(resolveEnv).not.toHaveBeenCalled();
+ expect(run).not.toHaveBeenCalled();
+ expect(vi.mocked(WidgetModel.finishRun)).toHaveBeenLastCalledWith(
+ {},
+ 'run-1',
+ expect.objectContaining({
+ error: { code: 'MISSING_PARAM', message: 'Set City before running this widget' },
+ status: 'failed',
+ }),
+ expect.any(Function),
+ );
+ });
});
describe('executeWidgetRun when the sandbox is busy', () => {
diff --git a/apps/server/src/services/widget/__tests__/layoutSchema.test.ts b/apps/server/src/services/widget/__tests__/layoutSchema.test.ts
index b736860f078..8cd041eeaf5 100644
--- a/apps/server/src/services/widget/__tests__/layoutSchema.test.ts
+++ b/apps/server/src/services/widget/__tests__/layoutSchema.test.ts
@@ -1,7 +1,7 @@
import { systemPrompt } from '@lobechat/builtin-tool-dashboard';
+import { widgetLayoutSchema } from '@lobechat/widget-spec';
import { describe, expect, it } from 'vitest';
-import { widgetLayoutSchema } from '../layoutSchema';
import { widgetViewSchema } from '../versionSchema';
const text = (value: unknown) => ({ type: 'text', value });
diff --git a/apps/server/src/services/widget/__tests__/outputContract.test.ts b/apps/server/src/services/widget/__tests__/outputContract.test.ts
index f50b1b5c009..a7cfe2d7689 100644
--- a/apps/server/src/services/widget/__tests__/outputContract.test.ts
+++ b/apps/server/src/services/widget/__tests__/outputContract.test.ts
@@ -1,7 +1,6 @@
+import { parseWidgetOutput, WIDGET_OUTPUT_LIMITS } from '@lobechat/widget-spec';
import { describe, expect, it } from 'vitest';
-import { parseWidgetOutput, WIDGET_OUTPUT_LIMITS } from '../outputContract';
-
const json = (value: unknown) => JSON.stringify(value);
describe('parseWidgetOutput', () => {
diff --git a/apps/server/src/services/widget/__tests__/widgetPresets.test.ts b/apps/server/src/services/widget/__tests__/widgetPresets.test.ts
new file mode 100644
index 00000000000..6263eae6c79
--- /dev/null
+++ b/apps/server/src/services/widget/__tests__/widgetPresets.test.ts
@@ -0,0 +1,117 @@
+import {
+ applyWidgetParamValues,
+ BUILTIN_WIDGET_PRESETS,
+ findBuiltinWidgetPreset,
+ localizeWidgetPreset,
+ missingWidgetParams,
+ parseWidgetOutput,
+ parseWidgetPreset,
+ widgetManifestSchema,
+ widgetParamEnv,
+ widgetPresetSchema,
+} from '@lobechat/widget-spec';
+import { describe, expect, it } from 'vitest';
+
+describe('bundled widget presets', () => {
+ it.each(BUILTIN_WIDGET_PRESETS.map((preset) => [preset.id, preset]))(
+ '%s is a valid, installable preset with a zh-CN translation',
+ (_, preset) => {
+ expect(() => parseWidgetPreset(preset)).not.toThrow();
+ // the gallery sample is exactly what the script's contract accepts
+ expect(parseWidgetOutput(JSON.stringify(preset.sample), preset.widget.outputType).ok).toBe(
+ true,
+ );
+ expect(preset.locales?.['zh-CN']?.title).toBeTruthy();
+ // installing with defaults alone leaves nothing required unset
+ expect(missingWidgetParams(preset.widget.manifest?.params)).toEqual([]);
+ },
+ );
+
+ it('have unique ids and can be found by id', () => {
+ const ids = BUILTIN_WIDGET_PRESETS.map((preset) => preset.id);
+ expect(new Set(ids).size).toBe(ids.length);
+ expect(findBuiltinWidgetPreset('weather-now')?.category).toBe('weather');
+ expect(findBuiltinWidgetPreset('nope')).toBeUndefined();
+ });
+});
+
+describe('widgetPresetSchema', () => {
+ const base = BUILTIN_WIDGET_PRESETS.find((preset) => preset.id === 'countdown')!;
+
+ it('rejects a sample of another output type and a data preset without a layout', () => {
+ const issues = (input: unknown) =>
+ (widgetPresetSchema.safeParse(input).error?.issues ?? [])
+ .map((issue) => issue.message)
+ .join('\n');
+
+ expect(issues({ ...base, sample: { type: 'stat', value: 1 } })).toContain('sample is "stat"');
+ expect(issues({ ...base, widget: { ...base.widget, view: {} } })).toContain(
+ 'needs view.layout',
+ );
+ expect(
+ issues({ ...base, locales: { 'zh-CN': { params: { NOPE: { label: 'x' } } } } }),
+ ).toContain('unknown param "NOPE"');
+ });
+
+ it('localizes gallery copy with an English fallback', () => {
+ const zh = localizeWidgetPreset(base, 'zh-CN');
+ expect(zh.title).toBe('倒数日');
+ expect(zh.params.find((param) => param.name === 'DATE')?.label).toBe('日期');
+
+ const de = localizeWidgetPreset(base, 'de-DE');
+ expect(de.title).toBe('Countdown');
+ expect(de.params.find((param) => param.name === 'TIMEZONE')?.label).toBe('Time zone');
+ });
+});
+
+describe('widget params', () => {
+ const params = [
+ { name: 'CITY', required: true, type: 'string' as const },
+ { default: 8, name: 'LIMIT', type: 'number' as const },
+ { name: 'DATE', type: 'date' as const },
+ { name: 'UNIT', options: [{ value: 'c' }, { value: 'f' }], type: 'select' as const },
+ ];
+
+ it('reports required params without a value, and fills values by name', () => {
+ expect(missingWidgetParams(params).map((param) => param.name)).toEqual(['CITY']);
+
+ const filled = applyWidgetParamValues(params, { CITY: 'Paris', IGNORED: 'x', UNIT: 'f' });
+ expect(missingWidgetParams(filled)).toEqual([]);
+ expect(widgetParamEnv(filled)).toEqual({ CITY: 'Paris', LIMIT: '8', UNIT: 'f' });
+ });
+
+ it.each([
+ [{ LIMIT: 'eight' }, 'LIMIT must be a number'],
+ [{ DATE: '2027/01/01' }, 'DATE must be a YYYY-MM-DD date'],
+ [{ UNIT: 'k' }, 'UNIT must be one of the options'],
+ ])('rejects %j', (values, message) => {
+ expect(() => applyWidgetParamValues(params, values)).toThrow(message);
+ });
+
+ it('are validated in the manifest: typed values, unique names, no clash with secrets', () => {
+ const parse = (manifest: unknown) => widgetManifestSchema.safeParse(manifest);
+
+ expect(parse({ params: [{ default: 'x', name: 'LIMIT', type: 'number' }] }).success).toBe(
+ false,
+ );
+ expect(parse({ params: [{ name: 'city', type: 'string' }] }).success).toBe(false);
+ expect(parse({ params: [{ name: 'MODE', type: 'select' }] }).success).toBe(false);
+ expect(
+ parse({
+ params: [
+ { name: 'A', type: 'string' },
+ { name: 'A', type: 'string' },
+ ],
+ }).success,
+ ).toBe(false);
+ expect(
+ parse({
+ env: [{ connector: 'github', name: 'GITHUB_TOKEN' }],
+ params: [{ name: 'GITHUB_TOKEN', type: 'string' }],
+ }).success,
+ ).toBe(false);
+ expect(parse({ params: [{ default: '2027-01-01', name: 'DATE', type: 'date' }] }).success).toBe(
+ true,
+ );
+ });
+});
diff --git a/apps/server/src/services/widget/executeRun.ts b/apps/server/src/services/widget/executeRun.ts
index 70973e5b40d..0d9b8800f7a 100644
--- a/apps/server/src/services/widget/executeRun.ts
+++ b/apps/server/src/services/widget/executeRun.ts
@@ -1,4 +1,5 @@
import type { WidgetOutput, WidgetRunError, WidgetRunFinalStatus } from '@lobechat/types';
+import { missingWidgetParams, parseWidgetOutput, widgetParamEnv } from '@lobechat/widget-spec';
import debug from 'debug';
import { WidgetModel } from '@/database/models/widget';
@@ -15,7 +16,6 @@ import {
type WidgetCredentialScope,
} from './credentials';
import { recordWidgetMetrics } from './metrics';
-import { parseWidgetOutput } from './outputContract';
import { redactSecrets, sanitizeStream } from './redact';
import { isWidgetSandboxBusy, WidgetSandboxError, type WidgetSandboxRunner } from './sandbox/types';
import { busyDeferralDeadline, runWithBusyRetry } from './sandboxBusy';
@@ -95,6 +95,18 @@ const runInSandbox = async (
const resolveEnv = deps.resolveEnv ?? resolveWidgetEnv;
const allow = manifest?.network?.allow ?? [];
+ const missingParams = missingWidgetParams(manifest?.params);
+ if (missingParams.length > 0) {
+ return {
+ env: {},
+ error: {
+ code: 'MISSING_PARAM',
+ message: `Set ${missingParams.map((param) => param.label ?? param.name).join(', ')} before running this widget`,
+ },
+ status: 'failed',
+ };
+ }
+
let env: Record<string, string>;
let inject: ResolvedWidgetEnv['inject'];
try {
@@ -138,7 +150,9 @@ const runInSandbox = async (
deps.runner.run({
// The widget's owner (or its workspace) pays for and is rate limited on the run.
actor: { userId: widget.userId, workspaceId: widget.workspaceId },
- env,
+ // Params are settings, not secrets: they reach the script but stay out
+ // of `env`, the set every log and error message is redacted against.
+ env: { ...widgetParamEnv(manifest?.params), ...env },
network: { allow, ...(inject.length > 0 ? { inject } : {}) },
runtime: version.runtime,
script: version.script,
diff --git a/apps/server/src/services/widget/sandbox/types.ts b/apps/server/src/services/widget/sandbox/types.ts
index a366a2456c3..946ce39e265 100644
--- a/apps/server/src/services/widget/sandbox/types.ts
+++ b/apps/server/src/services/widget/sandbox/types.ts
@@ -1,7 +1,8 @@
import type { WidgetRuntime } from '@lobechat/types';
+import { WIDGET_MAX_TIMEOUT_MS } from '@lobechat/widget-spec';
/** Upper bound any provider accepts for one script execution. */
-export const WIDGET_SANDBOX_MAX_TIMEOUT_MS = 120_000;
+export const WIDGET_SANDBOX_MAX_TIMEOUT_MS = WIDGET_MAX_TIMEOUT_MS;
export const WIDGET_SANDBOX_DEFAULT_TIMEOUT_MS = 30_000;
/** Extra time a sandbox request may take beyond the script timeout (cold start, upload). */
export const WIDGET_SANDBOX_REQUEST_OVERHEAD_MS = 60_000;
diff --git a/apps/server/src/services/widget/versionSchema.ts b/apps/server/src/services/widget/versionSchema.ts
index 35296b9de8d..1766b65db53 100644
--- a/apps/server/src/services/widget/versionSchema.ts
+++ b/apps/server/src/services/widget/versionSchema.ts
@@ -1,86 +1,13 @@
-import { WIDGET_OUTPUT_TYPES, WIDGET_RUNTIMES } from '@lobechat/types';
+import { widgetContentSchema } from '@lobechat/widget-spec';
import { z } from 'zod';
-import { widgetLayoutSchema, widgetSurfaceSchema } from './layoutSchema';
-import { WIDGET_SANDBOX_MAX_TIMEOUT_MS } from './sandbox/types';
+export { widgetManifestSchema, widgetViewSchema } from '@lobechat/widget-spec';
/**
* Validation of a widget version's authored content, shared by every
* entry point that records a draft so all accept exactly the same content.
+ * The content rules live in `@lobechat/widget-spec`, which presets share.
*/
-
-const envName = z.string().regex(/^[A-Z_]\w*$/i, 'env names must be valid shell identifiers');
-
-/** A hostname, or `*.domain` for its subdomains — the form `network.allow` takes. */
-const hostPattern = z
- .string()
- .min(1)
- .max(253)
- .regex(
- /^(?:\*\.)?[\w-]+(?:\.[\w-]+)+$/,
- 'hosts must be a hostname or *.domain, without scheme or path',
- );
-
-export const widgetManifestSchema = z.object({
- description: z.string().max(2000).optional(),
- env: z
- .array(
- z.object({
- connector: z.string().min(1).optional(),
- description: z.string().max(500).optional(),
- field: z.string().min(1).max(200).optional(),
- inject: z
- .object({
- header: z
- .string()
- .regex(/^[!#$%&'*+.^`|~\w-]+$/, 'inject.header must be a valid header name')
- .max(100)
- .optional(),
- host: z.union([hostPattern, z.array(hostPattern).min(1).max(5)]),
- prefix: z
- .string()
- .max(100)
- .regex(/^[^\0\n\r]*$/, 'inject.prefix must be a single line')
- .optional(),
- })
- .optional(),
- name: envName,
- required: z.boolean().optional(),
- }),
- )
- .max(20)
- .optional(),
- metric: z
- .object({
- key: z.string().min(1).max(100),
- kind: z.enum(['gauge', 'counter']).optional(),
- unit: z.string().max(50).optional(),
- valuePath: z.string().max(200).optional(),
- })
- .optional(),
- network: z.object({ allow: z.array(z.string().min(1).max(253)).max(50) }).optional(),
- schedule: z.object({ pattern: z.string(), timezone: z.string().optional() }).optional(),
- timeoutMs: z.number().int().positive().max(WIDGET_SANDBOX_MAX_TIMEOUT_MS).optional(),
- title: z.string().max(200).optional(),
-});
-
-export const widgetViewSchema = z.object({
- chart: z.enum(['line', 'bar', 'area']).optional(),
- columns: z.array(z.string()).optional(),
- layout: widgetLayoutSchema.optional(),
- limit: z.number().int().positive().max(500).optional(),
- size: z.enum(['sm', 'md', 'lg']).optional(),
- surface: widgetSurfaceSchema.optional(),
-});
-
-export const widgetVersionContentSchema = z.object({
+export const widgetVersionContentSchema = widgetContentSchema.extend({
changeNote: z.string().max(500).nullish(),
- manifest: widgetManifestSchema.nullish(),
- outputType: z.enum(WIDGET_OUTPUT_TYPES),
- runtime: z.enum(WIDGET_RUNTIMES),
- script: z
- .string()
- .min(1)
- .max(256 * 1024),
- view: widgetViewSchema.nullish(),
});
diff --git a/locales/en-US/plugin.json b/locales/en-US/plugin.json
index fee10353a97..5a1084fc719 100644
--- a/locales/en-US/plugin.json
+++ b/locales/en-US/plugin.json
@@ -7,6 +7,7 @@
"builtins.builtin-dashboard.apiName.dryRunWidget": "Dry-run widget",
"builtins.builtin-dashboard.apiName.getWidgetRuns": "Check widget runs",
"builtins.builtin-dashboard.apiName.listDashboards": "List dashboards",
+ "builtins.builtin-dashboard.apiName.listWidgetPresets": "Browse widget presets",
"builtins.builtin-dashboard.apiName.requestPublish": "Publish widget",
"builtins.builtin-dashboard.apiName.updateDashboard": "Update dashboard",
"builtins.builtin-dashboard.apiName.updateWidgetDraft": "Update widget draft",
diff --git a/locales/zh-CN/plugin.json b/locales/zh-CN/plugin.json
index c56def6eccf..60ff2381ac9 100644
--- a/locales/zh-CN/plugin.json
+++ b/locales/zh-CN/plugin.json
@@ -7,6 +7,7 @@
"builtins.builtin-dashboard.apiName.dryRunWidget": "试运行组件",
"builtins.builtin-dashboard.apiName.getWidgetRuns": "查看组件运行记录",
"builtins.builtin-dashboard.apiName.listDashboards": "列出看板",
+ "builtins.builtin-dashboard.apiName.listWidgetPresets": "浏览组件预设",
"builtins.builtin-dashboard.apiName.requestPublish": "发布组件",
"builtins.builtin-dashboard.apiName.updateDashboard": "更新看板",
"builtins.builtin-dashboard.apiName.updateWidgetDraft": "更新组件草稿",
diff --git a/package.json b/package.json
index 3888a491c39..bd7d30010ac 100644
--- a/package.json
+++ b/package.json
@@ -326,6 +326,7 @@
"@lobechat/tool-view-model": "workspace:*",
"@lobechat/utils": "workspace:*",
"@lobechat/web-crawler": "workspace:*",
+ "@lobechat/widget-spec": "workspace:*",
"@lobehub/analytics": "^1.6.4",
"@lobehub/charts": "^6.0.0",
"@lobehub/desktop-ipc-typings": "workspace:*",
diff --git a/packages/builtin-tool-dashboard/package.json b/packages/builtin-tool-dashboard/package.json
index 027728c33ec..9e5ea5f1f69 100644
--- a/packages/builtin-tool-dashboard/package.json
+++ b/packages/builtin-tool-dashboard/package.json
@@ -9,6 +9,9 @@
"./executionRuntime": "./src/ExecutionRuntime/index.ts"
},
"main": "./src/index.ts",
+ "dependencies": {
+ "@lobechat/widget-spec": "workspace:*"
+ },
"devDependencies": {
"@lobechat/types": "workspace:*"
},
diff --git a/packages/builtin-tool-dashboard/src/ExecutionRuntime/index.ts b/packages/builtin-tool-dashboard/src/ExecutionRuntime/index.ts
index c45ddfd52e8..e91fd2b5d36 100644
--- a/packages/builtin-tool-dashboard/src/ExecutionRuntime/index.ts
+++ b/packages/builtin-tool-dashboard/src/ExecutionRuntime/index.ts
@@ -1,4 +1,10 @@
import type { BuiltinServerRuntimeOutput } from '@lobechat/types';
+import {
+ applyWidgetParamValues,
+ BUILTIN_WIDGET_PRESETS,
+ findBuiltinWidgetPreset,
+ widgetParamValue,
+} from '@lobechat/widget-spec';
import {
type AddWidgetToDashboardParams,
@@ -16,6 +22,8 @@ import {
type GetWidgetRunsParams,
type GetWidgetRunsState,
type ListDashboardsState,
+ type ListWidgetPresetsParams,
+ type ListWidgetPresetsState,
type RequestPublishParams,
type RequestPublishState,
type UpdateDashboardParams,
@@ -261,18 +269,82 @@ export class DashboardExecutionRuntime {
}
}
+ async listWidgetPresets(
+ params: ListWidgetPresetsParams = {},
+ ): Promise<BuiltinServerRuntimeOutput> {
+ const presets = BUILTIN_WIDGET_PRESETS.filter(
+ (preset) => !params.category || preset.category === params.category,
+ );
+ const state: ListWidgetPresetsState = {
+ presets: presets.map(({ category, id, title }) => ({ category, id, title })),
+ };
+ if (presets.length === 0) {
+ return { content: 'No presets in this category.', state, success: true };
+ }
+
+ const lines = presets.map((preset) => {
+ const settings = (preset.widget.manifest?.params ?? []).map((param) => {
+ const fallback = widgetParamValue(param);
+ const choices = param.options
+ ? ` one of ${param.options.map((o) => o.value).join('|')}`
+ : '';
+ return `${param.name} (${param.type}${choices}${param.required ? ', required' : ''}${fallback === undefined ? '' : `, default ${JSON.stringify(fallback)}`})`;
+ });
+ return [
+ `- ${preset.id} [${preset.category}] ${preset.title}: ${preset.description}`,
+ settings.length > 0 ? ` params: ${settings.join('; ')}` : ' params: none',
+ ].join('\n');
+ });
+ return {
+ content: [
+ 'Presets you can install with createWidgetDraft({presetId, params}); then dry-run, request publish and place it as usual:',
+ ...lines,
+ ].join('\n'),
+ state,
+ success: true,
+ };
+ }
+
async createWidgetDraft(params: CreateWidgetDraftParams): Promise<BuiltinServerRuntimeOutput> {
try {
- const { description, title, ...content } = params;
+ const { description, params: values, presetId, title, ...explicit } = params;
+ const preset = presetId ? findBuiltinWidgetPreset(presetId) : undefined;
+ if (presetId && !preset)
+ throw new Error(`Unknown preset "${presetId}"; see listWidgetPresets`);
+
+ const base = preset?.widget;
+ const manifest = explicit.manifest ?? base?.manifest;
+ const content: WidgetVersionContent = {
+ ...base,
+ ...explicit,
+ manifest:
+ manifest?.params && values
+ ? { ...manifest, params: applyWidgetParamValues(manifest.params, values) }
+ : manifest,
+ } as WidgetVersionContent;
+ const name = title ?? preset?.title;
+ const definition = description ?? preset?.description;
+ if (
+ name === undefined ||
+ definition === undefined ||
+ !content.script ||
+ !content.runtime ||
+ !content.outputType
+ ) {
+ throw new Error(
+ 'Pass title, description, script, runtime and outputType, or a presetId to install',
+ );
+ }
+
const { version, widgetId } = await this.service.createWidgetDraft({
content,
- description,
- title,
+ description: definition,
+ title: name,
});
const state: WidgetDraftState = { version: version.version, versionId: version.id, widgetId };
return {
- content: `Created widget "${title}" (${widgetId}) with draft ${versionLabel(version)}, version id ${version.id}. Nothing runs yet — call dryRunWidget to execute it.`,
+ content: `Created widget "${name}" (${widgetId})${preset ? ` from preset ${preset.id}` : ''} with draft ${versionLabel(version)}, version id ${version.id}. Nothing runs yet — call dryRunWidget to execute it.`,
state,
success: true,
};
diff --git a/packages/builtin-tool-dashboard/src/ExecutionRuntime/presets.test.ts b/packages/builtin-tool-dashboard/src/ExecutionRuntime/presets.test.ts
new file mode 100644
index 00000000000..4a665e87d5b
--- /dev/null
+++ b/packages/builtin-tool-dashboard/src/ExecutionRuntime/presets.test.ts
@@ -0,0 +1,83 @@
+import { findBuiltinWidgetPreset } from '@lobechat/widget-spec';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { DashboardExecutionRuntime, type DashboardToolService } from './index';
+
+const createWidgetDraft = vi.fn();
+let runtime: DashboardExecutionRuntime;
+
+beforeEach(() => {
+ createWidgetDraft.mockReset();
+ createWidgetDraft.mockResolvedValue({
+ version: {
+ id: 'v1',
+ outputType: 'data',
+ runtime: 'node',
+ script: 's',
+ status: 'draft',
+ version: 1,
+ },
+ widgetId: 'w1',
+ });
+ runtime = new DashboardExecutionRuntime({ createWidgetDraft } as unknown as DashboardToolService);
+});
+
+describe('listWidgetPresets', () => {
+ it('lists presets with their settings, optionally by category', async () => {
+ const all = await runtime.listWidgetPresets();
+ expect(all.content).toContain('weather-now [weather]');
+ expect(all.content).toContain('CITY (string, required, default "London")');
+ expect(all.content).toContain('LANGUAGE (select one of en|zh|ja|de|fr|es');
+
+ const time = await runtime.listWidgetPresets({ category: 'time' });
+ expect((time.state as any).presets.map((p: { id: string }) => p.id)).toEqual([
+ 'countdown',
+ 'year-progress',
+ ]);
+ });
+});
+
+describe('createWidgetDraft from a preset', () => {
+ it('installs the preset content with the given params and its own title', async () => {
+ const result = await runtime.createWidgetDraft({
+ params: { CITY: 'Hangzhou', LANGUAGE: 'zh' },
+ presetId: 'weather-now',
+ });
+
+ const preset = findBuiltinWidgetPreset('weather-now')!;
+ const call = createWidgetDraft.mock.calls[0][0];
+ expect(result.success).toBe(true);
+ expect(result.content).toContain('from preset weather-now');
+ expect(call.title).toBe(preset.title);
+ expect(call.description).toBe(preset.description);
+ expect(call.content.script).toBe(preset.widget.script);
+ expect(call.content.view).toEqual(preset.widget.view);
+ expect(call.content.manifest.params).toEqual([
+ expect.objectContaining({ name: 'CITY', value: 'Hangzhou' }),
+ expect.objectContaining({ name: 'LANGUAGE', value: 'zh' }),
+ ]);
+ });
+
+ it('lets explicit fields override the preset', async () => {
+ await runtime.createWidgetDraft({ presetId: 'countdown', title: 'Launch day' });
+
+ expect(createWidgetDraft.mock.calls[0][0].title).toBe('Launch day');
+ });
+
+ it('refuses an unknown preset, a param value of the wrong type and a draft with nothing to install', async () => {
+ const unknown = await runtime.createWidgetDraft({ presetId: 'nope' });
+ expect(unknown.success).toBe(false);
+ expect(unknown.content).toContain('Unknown preset "nope"');
+
+ const badValue = await runtime.createWidgetDraft({
+ params: { DATE: 'next friday' },
+ presetId: 'countdown',
+ });
+ expect(badValue.success).toBe(false);
+ expect(badValue.content).toContain('DATE must be a YYYY-MM-DD date');
+
+ const empty = await runtime.createWidgetDraft({ title: 'x' });
+ expect(empty.success).toBe(false);
+ expect(createWidgetDraft).not.toHaveBeenCalled();
+ });
+});
diff --git a/packages/builtin-tool-dashboard/src/client/Inspector/index.tsx b/packages/builtin-tool-dashboard/src/client/Inspector/index.tsx
index e820689387c..c15f836f525 100644
--- a/packages/builtin-tool-dashboard/src/client/Inspector/index.tsx
+++ b/packages/builtin-tool-dashboard/src/client/Inspector/index.tsx
@@ -13,6 +13,7 @@ import type {
DashboardApiNameType,
DryRunWidgetState,
GetWidgetRunsState,
+ ListWidgetPresetsState,
RequestPublishState,
UpdateDashboardState,
WidgetDraftState,
@@ -62,10 +63,17 @@ const useChip = (apiName: DashboardApiNameType, props: Props): ReactNode => {
const state = props.pluginState as CreateDashboardState | undefined;
return state?.title ?? args.title;
}
+ case DashboardApiName.listWidgetPresets: {
+ const state = props.pluginState as ListWidgetPresetsState | undefined;
+ return state ? String(state.presets.length) : undefined;
+ }
case DashboardApiName.createWidgetDraft:
case DashboardApiName.updateWidgetDraft: {
const state = props.pluginState as WidgetDraftState | undefined;
- return [args.title, state && `v${state.version}`].filter(Boolean).join(' · ') || undefined;
+ return (
+ [args.title ?? args.presetId, state && `v${state.version}`].filter(Boolean).join(' · ') ||
+ undefined
+ );
}
case DashboardApiName.dryRunWidget: {
const state = props.pluginState as DryRunWidgetState | undefined;
diff --git a/packages/builtin-tool-dashboard/src/client/executor/index.ts b/packages/builtin-tool-dashboard/src/client/executor/index.ts
index 0cf578eb0f9..0c99b4d65cd 100644
--- a/packages/builtin-tool-dashboard/src/client/executor/index.ts
+++ b/packages/builtin-tool-dashboard/src/client/executor/index.ts
@@ -40,6 +40,9 @@ class DashboardExecutor extends BaseExecutor<typeof DashboardApiName> {
listDashboards = (params: unknown, ctx?: BuiltinToolContext) =>
this.run(DashboardApiName.listDashboards, params, ctx);
+ listWidgetPresets = (params: unknown, ctx?: BuiltinToolContext) =>
+ this.run(DashboardApiName.listWidgetPresets, params, ctx);
+
createDashboard = (params: unknown, ctx?: BuiltinToolContext) =>
this.run(DashboardApiName.createDashboard, params, ctx);
diff --git a/packages/builtin-tool-dashboard/src/manifest.ts b/packages/builtin-tool-dashboard/src/manifest.ts
index 147d17d2c42..5f138046fbf 100644
--- a/packages/builtin-tool-dashboard/src/manifest.ts
+++ b/packages/builtin-tool-dashboard/src/manifest.ts
@@ -103,6 +103,38 @@ const manifestSchema = {
required: ['allow'],
type: 'object',
},
+ params: {
+ description:
+ 'Settings a person fills in (city, target date, repository) that the script reads from its environment as text. Never secrets — credentials go in env. Set value for this widget; default is the fallback.',
+ items: {
+ additionalProperties: false,
+ properties: {
+ default: { type: ['string', 'number', 'boolean'] },
+ description: { type: 'string' },
+ label: { description: 'Human label, e.g. "City".', type: 'string' },
+ name: { description: 'UPPER_SNAKE_CASE env name, e.g. CITY.', type: 'string' },
+ options: {
+ description: 'Choices of a select param.',
+ items: {
+ additionalProperties: false,
+ properties: { label: { type: 'string' }, value: { type: 'string' } },
+ required: ['value'],
+ type: 'object',
+ },
+ type: 'array',
+ },
+ required: { type: 'boolean' },
+ type: { enum: ['string', 'number', 'boolean', 'date', 'select'], type: 'string' },
+ value: {
+ description: "This widget's value (a date as YYYY-MM-DD).",
+ type: ['string', 'number', 'boolean'],
+ },
+ },
+ required: ['name', 'type'],
+ type: 'object',
+ },
+ type: 'array',
+ },
schedule: {
additionalProperties: false,
description:
@@ -159,6 +191,22 @@ export const DashboardManifest: BuiltinToolManifest = {
type: 'object',
},
},
+ {
+ description:
+ 'Ready-made widgets (weather, countdown, year progress, GitHub repository, Hacker News, …) with their settings. Check it before writing a widget from scratch: install a match with createWidgetDraft({presetId, params}).',
+ name: DashboardApiName.listWidgetPresets,
+ parameters: {
+ additionalProperties: false,
+ properties: {
+ category: {
+ description: 'Only presets of this category.',
+ enum: ['time', 'weather', 'dev', 'life', 'finance', 'content', 'business'],
+ type: 'string',
+ },
+ },
+ type: 'object',
+ },
+ },
{
description:
'Create an empty dashboard (in a project conversation it belongs to the project) and return its id. Check listDashboards first so you do not duplicate an existing board; to create a board for one widget, addWidgetToDashboard with newDashboardTitle does both in one step.',
@@ -182,11 +230,21 @@ export const DashboardManifest: BuiltinToolManifest = {
},
{
description:
- 'Create a monitoring widget and save its first draft. Nothing runs and nothing goes live; call dryRunWidget next. The widget is owned by the current agent (and project, in a project conversation).',
+ 'Create a monitoring widget and save its first draft. Nothing runs and nothing goes live; call dryRunWidget next. The widget is owned by the current agent (and project, in a project conversation). Pass presetId to install a preset from listWidgetPresets: its script, manifest and view are used, params fills its settings, and any other field you pass overrides the preset.',
name: DashboardApiName.createWidgetDraft,
parameters: {
additionalProperties: false,
properties: {
+ params: {
+ additionalProperties: { type: ['string', 'number', 'boolean'] },
+ description:
+ 'With presetId: values for the preset\'s params by name, e.g. {"CITY":"Hangzhou"}.',
+ type: 'object',
+ },
+ presetId: {
+ description: 'Id of a preset from listWidgetPresets to install.',
+ type: 'string',
+ },
description: {
description:
'Metric definition (口径) shown on the card: data source, filters, time window and unit.',
@@ -199,7 +257,7 @@ export const DashboardManifest: BuiltinToolManifest = {
title: { description: 'Short card title, e.g. "Open bug issues".', type: 'string' },
view: viewSchema,
},
- required: ['title', 'description', 'script', 'runtime', 'outputType'],
+ required: [],
type: 'object',
},
},
diff --git a/packages/builtin-tool-dashboard/src/systemRole.ts b/packages/builtin-tool-dashboard/src/systemRole.ts
index e51222fccc1..03b368b5314 100644
--- a/packages/builtin-tool-dashboard/src/systemRole.ts
+++ b/packages/builtin-tool-dashboard/src/systemRole.ts
@@ -2,6 +2,7 @@ export const systemPrompt = `You can build live monitoring widgets for the user'
<tools>
- **listDashboards**: The user's dashboards — in a project conversation the project's dashboards come first, marked [project], then the home ones — (with their descriptions and the widgets already on them) and the widgets this conversation's agent already owns. Call it first so you extend an existing widget instead of duplicating it, and so you know where to place a new one.
+- **listWidgetPresets**: Ready-made widgets (weather, countdown, year progress, GitHub repository, Hacker News, …) and their settings. When one fits the request, install it with createWidgetDraft({presetId, params}) instead of writing a script — its script, layout and schedule are already tested.
- **createDashboard**: Create an empty dashboard with a title and description — for example when the user asks for a board before any widget exists, or one board for several widgets. In a project conversation it belongs to the project.
- **createWidgetDraft**: Create a widget with its first draft (title, metric definition, script, runtime, outputType, manifest, view). Nothing runs and nothing is live yet.
- **updateWidgetDraft**: Save a new draft of an existing widget. Omitted fields keep the current draft's values, so send only what changes (e.g. just a fixed script). Also renames the widget or rewrites its metric definition.
@@ -14,7 +15,7 @@ export const systemPrompt = `You can build live monitoring widgets for the user'
<workflow>
1. listDashboards. When the user wants a new board for several widgets, createDashboard once and place every widget on it by dashboardId.
-2. createWidgetDraft (or updateWidgetDraft for an existing widget).
+2. listWidgetPresets when the request sounds like a common widget; install a match with createWidgetDraft({presetId, params: {…the user's settings…}}). Otherwise createWidgetDraft with your own script (or updateWidgetDraft for an existing widget).
3. dryRunWidget with the new versionId → read the output and logs → updateWidgetDraft → dryRunWidget with the newer versionId … until status is succeeded and the numbers look plausible. Do not stop at the first failure and do not ask the user to debug for you. Each dry run of a credentialed or networked draft asks the user for approval first.
4. requestPublish with the succeeded draft's versionId; tell the user what the widget measures.
5. addWidgetToDashboard if the user wants it on a board (placing a draft widget is allowed; it shows data once published). When it creates a board, always pass newDashboardDescription too.
@@ -38,6 +39,7 @@ Partial data: when one of several sources fails, still print the document with "
- Network is OFF unless manifest.network.allow lists the hostnames the script calls (e.g. ["api.github.com"]).
- Secrets: never write a token, password or key into the script, manifest, title or description. Declare what the script needs in manifest.env, e.g. {"name":"GITHUB_TOKEN","connector":"github","required":true}; the platform injects it from the user's connected accounts at run time and redacts it from logs. Read it from the environment (process.env.GITHUB_TOKEN / os.environ["GITHUB_TOKEN"] / $GITHUB_TOKEN). When the connector holds several headers (e.g. an API key plus an app key), add "field" with the header to inject: {"name":"DD_API_KEY","connector":"datadog","field":"DD-API-KEY"}. LobeHub Market connectors (github, linear, notion, vercel, microsoft, twitter, …) are declared the same way, but the variable only holds a placeholder: the platform replaces the request header with the real token on the way out. It works only when sent as that header to the provider's API host — e.g. GITHUB_TOKEN as "Authorization: Bearer $GITHUB_TOKEN" to api.github.com, which must also be in manifest.network.allow — never in a git clone URL, a query parameter, a request body or to another host. For another host or header add "inject": {"host":"api.example.com","header":"Authorization","prefix":"Bearer "}. If a run fails with MISSING_ENV naming several headers, set "field" to one of them with updateWidgetDraft; if it asks to add a host to manifest.network.allow, add it; if it says the connector is not connected, tell the user which connector to connect — do not ask them to paste a secret into the chat.
- Only read data. A widget must never create, modify or delete anything in external systems.
+- Settings the user chooses (a city, a date, a repository, a count) go in manifest.params, not in the script: {"name":"CITY","type":"string","label":"City","required":true,"value":"Hangzhou"}. Types: string, number, boolean, date (YYYY-MM-DD), select (with options [{"value":"c","label":"°C"}]). The script reads them as text from the environment (process.env.CITY); "value" is this widget's choice and "default" the fallback. To change a setting later, updateWidgetDraft with the manifest's params updated — the script stays the same. Params are stored in plain text: never put a secret there.
- manifest.schedule suggests the refresh cadence as a cron pattern ({"pattern":"*/30 * * * *"}); pick the slowest cadence that keeps the number useful (hourly is a good default). manifest.timeoutMs defaults to 30000 (max 120000).
- manifest.metric ({"key":"open_issues","unit":"issues"}) records a stat's value on every published run so the card gets a long-term trend line.
- view hints: {"chart":"line"|"bar"|"area"} for series, {"columns":[…]} to pick table columns, {"limit":10} to cap list/table rows.
@@ -50,7 +52,7 @@ Layout nodes (every node also accepts "flex" (grow factor), "visible" (condition
- stack {direction:"row"|"column", gap, align:"start"|"center"|"end"|"stretch"|"baseline", justify:"start"|"center"|"end"|"between"|"around", padding, wrap, children}
- grid {columns, gap, children}
- text {value, size:"xs"|"sm"|"md"|"lg"|"xl"|"2xl"|"display", weight:"regular"|"medium"|"semibold"|"bold", tone:"default"|"secondary"|"tertiary"|"success"|"warning"|"error", align, lines}
-- icon {name, size, color} — names: sun, moon, cloud, cloud-sun, cloud-moon, cloud-rain, cloud-drizzle, cloud-snow, cloud-lightning, cloud-fog, cloud-hail, snowflake, wind, droplet, droplets, thermometer, umbrella, sunrise, sunset, gauge, eye, navigation, arrow-up, arrow-down, trending-up, trending-down, check, x, alert-triangle, info, clock, calendar, map-pin, star, heart, flame, zap, activity, target, trophy, users, git-pull-request, git-commit, dollar-sign, server, database, globe, mail, message-circle, bell, timer
+- icon {name, size, color} — names: sun, moon, cloud, cloud-sun, cloud-moon, cloud-rain, cloud-drizzle, cloud-snow, cloud-lightning, cloud-fog, cloud-hail, snowflake, wind, droplet, droplets, thermometer, umbrella, sunrise, sunset, gauge, eye, navigation, arrow-up, arrow-down, trending-up, trending-down, check, x, alert-triangle, info, clock, calendar, map-pin, star, heart, flame, zap, activity, target, trophy, users, git-pull-request, git-commit, git-fork, circle-dot, dollar-sign, server, database, globe, mail, message-circle, bell, timer
- image {src (https), width, height, radius, fit}
- progress {value, min, max, color} · ring {value, max, size, color, children} · dots {value, total, columns, color} (filled dots, e.g. days of the year)
- sparkline {values:"data.hourly", key:"temp", kind:"line"|"area"|"bar", height, color}
diff --git a/packages/builtin-tool-dashboard/src/types.ts b/packages/builtin-tool-dashboard/src/types.ts
index c57583e3e7d..88509c9f9de 100644
--- a/packages/builtin-tool-dashboard/src/types.ts
+++ b/packages/builtin-tool-dashboard/src/types.ts
@@ -2,6 +2,8 @@ import type {
WidgetManifest,
WidgetOutput,
WidgetOutputType,
+ WidgetParamValue,
+ WidgetPresetCategory,
WidgetRunError,
WidgetRunStatus,
WidgetRuntime,
@@ -24,6 +26,7 @@ export const isDashboardIdentifier = (identifier: unknown): boolean =>
export const DashboardApiName = {
listDashboards: 'listDashboards',
+ listWidgetPresets: 'listWidgetPresets',
createDashboard: 'createDashboard',
createWidgetDraft: 'createWidgetDraft',
@@ -111,10 +114,25 @@ export interface ListDashboardsState {
// ==================== createWidgetDraft ====================
-export interface CreateWidgetDraftParams extends WidgetVersionContent {
- /** Metric definition (口径): source, filters, window, unit. */
- description: string;
- title: string;
+export interface CreateWidgetDraftParams extends Partial<WidgetVersionContent> {
+ /** Metric definition (口径): source, filters, window, unit. Defaults to the preset's. */
+ description?: string;
+ /** With `presetId`: values for the preset's params, by name. */
+ params?: Record<string, WidgetParamValue>;
+ /** Install this preset; explicit content fields override its parts. */
+ presetId?: string;
+ /** Defaults to the preset's title. */
+ title?: string;
+}
+
+// ==================== listWidgetPresets ====================
+
+export interface ListWidgetPresetsParams {
+ category?: WidgetPresetCategory;
+}
+
+export interface ListWidgetPresetsState {
+ presets: { category: WidgetPresetCategory; id: string; title: string }[];
}
export interface WidgetDraftState {
diff --git a/packages/locales/src/default/plugin.ts b/packages/locales/src/default/plugin.ts
index 3909a00dad0..f7a497c054d 100644
--- a/packages/locales/src/default/plugin.ts
+++ b/packages/locales/src/default/plugin.ts
@@ -582,6 +582,7 @@ export default {
'builtins.builtin-dashboard.apiName.dryRunWidget': 'Dry-run widget',
'builtins.builtin-dashboard.apiName.getWidgetRuns': 'Check widget runs',
'builtins.builtin-dashboard.apiName.listDashboards': 'List dashboards',
+ 'builtins.builtin-dashboard.apiName.listWidgetPresets': 'Browse widget presets',
'builtins.builtin-dashboard.apiName.requestPublish': 'Publish widget',
'builtins.builtin-dashboard.apiName.updateDashboard': 'Update dashboard',
'builtins.builtin-dashboard.apiName.updateWidgetDraft': 'Update widget draft',
diff --git a/packages/types/src/widget/index.ts b/packages/types/src/widget/index.ts
index 822807afddc..255fe5dc368 100644
--- a/packages/types/src/widget/index.ts
+++ b/packages/types/src/widget/index.ts
@@ -11,6 +11,7 @@
import type { WidgetLayoutNode, WidgetLayoutValue } from './layout';
export * from './layout';
+export * from './preset';
export const WIDGET_VISIBILITIES = ['private', 'public'] as const;
export type WidgetVisibility = (typeof WIDGET_VISIBILITIES)[number];
@@ -212,12 +213,39 @@ export interface WidgetManifest {
};
/** Hostnames the sandbox may reach; empty or omitted means no network. */
network?: { allow: string[] };
+ /**
+ * Settings a person fills in (a city, a target date, a repository) that
+ * the script reads from its environment. Never secrets: values are stored
+ * in plain text and shown in reviews — credentials go in `env`.
+ */
+ params?: WidgetParam[];
/** Suggested refresh schedule applied when the version is published. */
schedule?: { pattern: string; timezone?: string };
timeoutMs?: number;
title?: string;
}
+export const WIDGET_PARAM_TYPES = ['string', 'number', 'boolean', 'date', 'select'] as const;
+export type WidgetParamType = (typeof WIDGET_PARAM_TYPES)[number];
+export type WidgetParamValue = string | number | boolean;
+
+/**
+ * One setting of a widget. The script reads it as the environment variable
+ * `name`: numbers and booleans as their text, a date as `YYYY-MM-DD`. The
+ * effective value is `value` (this widget's choice), else `default`.
+ */
+export interface WidgetParam {
+ default?: WidgetParamValue;
+ description?: string;
+ label?: string;
+ name: string;
+ /** Choices of a `select` param. */
+ options?: { label?: string; value: string }[];
+ required?: boolean;
+ type: WidgetParamType;
+ value?: WidgetParamValue;
+}
+
/** Rendering hints for the widget card, independent of the data. */
export interface WidgetView {
chart?: 'line' | 'bar' | 'area';
diff --git a/packages/types/src/widget/layout.ts b/packages/types/src/widget/layout.ts
index 59aa52306a2..8bec9a145eb 100644
--- a/packages/types/src/widget/layout.ts
+++ b/packages/types/src/widget/layout.ts
@@ -156,6 +156,8 @@ export const WIDGET_LAYOUT_ICONS = [
'users',
'git-pull-request',
'git-commit',
+ 'git-fork',
+ 'circle-dot',
'dollar-sign',
'server',
'database',
diff --git a/packages/types/src/widget/preset.ts b/packages/types/src/widget/preset.ts
new file mode 100644
index 00000000000..9091107142f
--- /dev/null
+++ b/packages/types/src/widget/preset.ts
@@ -0,0 +1,64 @@
+// ============================================
+// Widget presets — ready-made widgets to install
+// ============================================
+//
+// A preset is a complete widget (script, manifest with its params, view) plus
+// what a gallery needs to show it before anything runs: a sample output, a
+// category and a default size. Bundled presets ship with the app for
+// self-hosted deployments; the rest are published to the Market.
+
+import type {
+ WidgetManifest,
+ WidgetOutput,
+ WidgetOutputType,
+ WidgetRuntime,
+ WidgetView,
+} from './index';
+
+export const WIDGET_PRESET_CATEGORIES = [
+ 'time',
+ 'weather',
+ 'dev',
+ 'life',
+ 'finance',
+ 'content',
+ 'business',
+] as const;
+export type WidgetPresetCategory = (typeof WIDGET_PRESET_CATEGORIES)[number];
+
+/** Translated gallery copy; the preset's own fields are English. */
+export interface WidgetPresetLocale {
+ description?: string;
+ /** Param labels and descriptions, keyed by param name. */
+ params?: Record<string, { description?: string; label?: string }>;
+ title?: string;
+}
+
+export interface WidgetPreset {
+ category: WidgetPresetCategory;
+ /**
+ * Shape of the data the script prints, e.g. `weather.v1`. Presets sharing a
+ * contract can swap views over the same data.
+ */
+ contract?: string;
+ description: string;
+ /** Stable kebab-case id, e.g. `weather-now`. */
+ id: string;
+ /** Keyed by locale, e.g. `zh-CN`. */
+ locales?: Record<string, WidgetPresetLocale>;
+ /** What the card shows in a gallery before the widget ever runs. */
+ sample: WidgetOutput;
+ /** Default board size in grid cells. */
+ size?: { h: number; w: number };
+ tags?: string[];
+ title: string;
+ /** Semver of the preset content. */
+ version: string;
+ widget: {
+ manifest?: WidgetManifest;
+ outputType: WidgetOutputType;
+ runtime: WidgetRuntime;
+ script: string;
+ view?: WidgetView;
+ };
+}
diff --git a/packages/widget-spec/package.json b/packages/widget-spec/package.json
new file mode 100644
index 00000000000..d49f82285b3
--- /dev/null
+++ b/packages/widget-spec/package.json
@@ -0,0 +1,18 @@
+{
+ "name": "@lobechat/widget-spec",
+ "version": "1.0.0",
+ "private": true,
+ "description": "Widget authoring contract: layout, view, manifest and preset validation shared by LobeHub and Market",
+ "sideEffects": false,
+ "type": "module",
+ "exports": {
+ ".": "./src/index.ts"
+ },
+ "main": "./src/index.ts",
+ "dependencies": {
+ "@lobechat/types": "workspace:*"
+ },
+ "peerDependencies": {
+ "zod": "^4.4.3"
+ }
+}
diff --git a/packages/widget-spec/src/index.ts b/packages/widget-spec/src/index.ts
new file mode 100644
index 00000000000..7b23c556348
--- /dev/null
+++ b/packages/widget-spec/src/index.ts
@@ -0,0 +1,6 @@
+export * from './layout';
+export * from './manifest';
+export * from './output';
+export * from './params';
+export * from './preset';
+export { BUILTIN_WIDGET_PRESETS, findBuiltinWidgetPreset } from './presets';
diff --git a/apps/server/src/services/widget/layoutSchema.ts b/packages/widget-spec/src/layout.ts
similarity index 100%
rename from apps/server/src/services/widget/layoutSchema.ts
rename to packages/widget-spec/src/layout.ts
diff --git a/packages/widget-spec/src/manifest.ts b/packages/widget-spec/src/manifest.ts
new file mode 100644
index 00000000000..5e49990391d
--- /dev/null
+++ b/packages/widget-spec/src/manifest.ts
@@ -0,0 +1,114 @@
+import { WIDGET_OUTPUT_TYPES, WIDGET_RUNTIMES } from '@lobechat/types';
+import { z } from 'zod';
+
+import { widgetLayoutSchema, widgetSurfaceSchema } from './layout';
+import { WIDGET_PARAM_LIMIT, widgetParamSchema } from './params';
+
+/** Longest a widget script may run, in milliseconds. */
+export const WIDGET_MAX_TIMEOUT_MS = 120_000;
+
+/**
+ * Validation of a widget version's manifest and view — the authored content
+ * besides the script, shared by every entry point that records a draft and by
+ * the preset contract, so all accept exactly the same content.
+ */
+
+const envName = z.string().regex(/^[A-Z_]\w*$/i, 'env names must be valid shell identifiers');
+
+/** A hostname, or `*.domain` for its subdomains — the form `network.allow` takes. */
+const hostPattern = z
+ .string()
+ .min(1)
+ .max(253)
+ .regex(
+ /^(?:\*\.)?[\w-]+(?:\.[\w-]+)+$/,
+ 'hosts must be a hostname or *.domain, without scheme or path',
+ );
+
+export const widgetManifestSchema = z
+ .object({
+ description: z.string().max(2000).optional(),
+ env: z
+ .array(
+ z.object({
+ connector: z.string().min(1).optional(),
+ description: z.string().max(500).optional(),
+ field: z.string().min(1).max(200).optional(),
+ inject: z
+ .object({
+ header: z
+ .string()
+ .regex(/^[!#$%&'*+.^`|~\w-]+$/, 'inject.header must be a valid header name')
+ .max(100)
+ .optional(),
+ host: z.union([hostPattern, z.array(hostPattern).min(1).max(5)]),
+ prefix: z
+ .string()
+ .max(100)
+ .regex(/^[^\0\n\r]*$/, 'inject.prefix must be a single line')
+ .optional(),
+ })
+ .optional(),
+ name: envName,
+ required: z.boolean().optional(),
+ }),
+ )
+ .max(20)
+ .optional(),
+ metric: z
+ .object({
+ key: z.string().min(1).max(100),
+ kind: z.enum(['gauge', 'counter']).optional(),
+ unit: z.string().max(50).optional(),
+ valuePath: z.string().max(200).optional(),
+ })
+ .optional(),
+ network: z.object({ allow: z.array(z.string().min(1).max(253)).max(50) }).optional(),
+ params: z.array(widgetParamSchema).max(WIDGET_PARAM_LIMIT).optional(),
+ schedule: z.object({ pattern: z.string(), timezone: z.string().optional() }).optional(),
+ timeoutMs: z.number().int().positive().max(WIDGET_MAX_TIMEOUT_MS).optional(),
+ title: z.string().max(200).optional(),
+ })
+ .superRefine((manifest, ctx) => {
+ const params = manifest.params ?? [];
+ const secretNames = new Set((manifest.env ?? []).map((env) => env.name));
+ const seen = new Set<string>();
+ params.forEach((param, index) => {
+ if (seen.has(param.name)) {
+ ctx.addIssue({
+ code: 'custom',
+ message: `param "${param.name}" is declared twice`,
+ path: ['params', index, 'name'],
+ });
+ }
+ seen.add(param.name);
+ if (secretNames.has(param.name)) {
+ ctx.addIssue({
+ code: 'custom',
+ message: `param "${param.name}" has the same name as an env requirement`,
+ path: ['params', index, 'name'],
+ });
+ }
+ });
+ });
+
+export const widgetViewSchema = z.object({
+ chart: z.enum(['line', 'bar', 'area']).optional(),
+ columns: z.array(z.string()).optional(),
+ layout: widgetLayoutSchema.optional(),
+ limit: z.number().int().positive().max(500).optional(),
+ size: z.enum(['sm', 'md', 'lg']).optional(),
+ surface: widgetSurfaceSchema.optional(),
+});
+
+/** A widget's authored content: script, contract, manifest and view. */
+export const widgetContentSchema = z.object({
+ manifest: widgetManifestSchema.nullish(),
+ outputType: z.enum(WIDGET_OUTPUT_TYPES),
+ runtime: z.enum(WIDGET_RUNTIMES),
+ script: z
+ .string()
+ .min(1)
+ .max(256 * 1024),
+ view: widgetViewSchema.nullish(),
+});
diff --git a/apps/server/src/services/widget/outputContract.ts b/packages/widget-spec/src/output.ts
similarity index 96%
rename from apps/server/src/services/widget/outputContract.ts
rename to packages/widget-spec/src/output.ts
index 430f49ed877..ed9ee19b359 100644
--- a/apps/server/src/services/widget/outputContract.ts
+++ b/packages/widget-spec/src/output.ts
@@ -104,7 +104,8 @@ const dataSchema = z.object({
type: z.literal('data'),
});
-const outputSchema = z.discriminatedUnion('type', [
+/** One widget output document, without the stdout framing. */
+export const widgetOutputSchema = z.discriminatedUnion('type', [
statSchema,
listSchema,
seriesSchema,
@@ -157,7 +158,7 @@ export const parseWidgetOutput = (
return fail('EMPTY_OUTPUT', 'Script printed nothing to stdout; expected one JSON document');
}
- const bytes = Buffer.byteLength(stdout, 'utf8');
+ const bytes = new TextEncoder().encode(stdout).byteLength;
if (bytes > WIDGET_OUTPUT_LIMITS.bytes) {
return fail(
'OUTPUT_TOO_LARGE',
@@ -172,7 +173,7 @@ export const parseWidgetOutput = (
return fail('INVALID_JSON', 'stdout is not a JSON document');
}
- const parsed = outputSchema.safeParse(raw);
+ const parsed = widgetOutputSchema.safeParse(raw);
if (!parsed.success) {
const tooBig = parsed.error.issues.some((issue) => issue.code === 'too_big');
const detail = parsed.error.issues
diff --git a/packages/widget-spec/src/params.ts b/packages/widget-spec/src/params.ts
new file mode 100644
index 00000000000..1e9767dd68f
--- /dev/null
+++ b/packages/widget-spec/src/params.ts
@@ -0,0 +1,106 @@
+import type { WidgetParam, WidgetParamValue } from '@lobechat/types';
+import { WIDGET_PARAM_TYPES } from '@lobechat/types';
+import { z } from 'zod';
+
+/** Most params one widget declares. */
+export const WIDGET_PARAM_LIMIT = 20;
+
+const DATE = /^\d{4}-\d{2}-\d{2}$/;
+
+const paramValue = z.union([z.string().max(500), z.number().finite(), z.boolean()]);
+
+/** Why `value` does not fit a param of this type, or undefined when it does. */
+export const widgetParamValueIssue = (
+ param: Pick<WidgetParam, 'options' | 'type'>,
+ value: WidgetParamValue,
+): string | undefined => {
+ switch (param.type) {
+ case 'number': {
+ return typeof value === 'number' ? undefined : 'must be a number';
+ }
+ case 'boolean': {
+ return typeof value === 'boolean' ? undefined : 'must be true or false';
+ }
+ case 'date': {
+ return typeof value === 'string' && DATE.test(value)
+ ? undefined
+ : 'must be a YYYY-MM-DD date';
+ }
+ case 'select': {
+ return param.options?.some((option) => option.value === value)
+ ? undefined
+ : 'must be one of the options';
+ }
+ default: {
+ return typeof value === 'string' ? undefined : 'must be text';
+ }
+ }
+};
+
+export const widgetParamSchema = z
+ .object({
+ default: paramValue.optional(),
+ description: z.string().max(500).optional(),
+ label: z.string().max(100).optional(),
+ name: z
+ .string()
+ .regex(/^[A-Z][\dA-Z_]*$/, 'param names are UPPER_SNAKE_CASE env names, e.g. CITY')
+ .max(64),
+ options: z
+ .array(z.object({ label: z.string().max(100).optional(), value: z.string().max(200) }))
+ .min(1)
+ .max(50)
+ .optional(),
+ required: z.boolean().optional(),
+ type: z.enum(WIDGET_PARAM_TYPES),
+ value: paramValue.optional(),
+ })
+ .superRefine((param, ctx) => {
+ if (param.type === 'select' && !param.options) {
+ ctx.addIssue({ code: 'custom', message: 'a select param needs options', path: ['options'] });
+ }
+ for (const key of ['default', 'value'] as const) {
+ const value = param[key];
+ if (value === undefined) continue;
+ const issue = widgetParamValueIssue(param, value);
+ if (issue) ctx.addIssue({ code: 'custom', message: `${key} ${issue}`, path: [key] });
+ }
+ });
+
+/** The effective value: this widget's choice, else the default. */
+export const widgetParamValue = (param: WidgetParam): WidgetParamValue | undefined =>
+ param.value ?? param.default;
+
+/** Required params that have neither a value nor a default. */
+export const missingWidgetParams = (params: WidgetParam[] = []): WidgetParam[] =>
+ params.filter((param) => param.required && widgetParamValue(param) === undefined);
+
+/**
+ * The params as the script's environment: each set param under its name,
+ * as text. Params are settings, not secrets, so they are kept apart from the
+ * credential env and are never redacted from logs.
+ */
+export const widgetParamEnv = (params: WidgetParam[] = []): Record<string, string> => {
+ const env: Record<string, string> = {};
+ for (const param of params) {
+ const value = widgetParamValue(param);
+ if (value !== undefined) env[param.name] = String(value);
+ }
+ return env;
+};
+
+/**
+ * Fill params with values, e.g. what a person typed when installing a preset.
+ * Unknown names are ignored; values that do not fit their param are rejected.
+ */
+export const applyWidgetParamValues = (
+ params: WidgetParam[] = [],
+ values: Record<string, WidgetParamValue> = {},
+): WidgetParam[] =>
+ params.map((param) => {
+ if (!(param.name in values)) return param;
+ const value = values[param.name];
+ const issue = widgetParamValueIssue(param, value);
+ if (issue) throw new Error(`Param ${param.name} ${issue}`);
+ return { ...param, value };
+ });
diff --git a/packages/widget-spec/src/preset.ts b/packages/widget-spec/src/preset.ts
new file mode 100644
index 00000000000..580dff6c509
--- /dev/null
+++ b/packages/widget-spec/src/preset.ts
@@ -0,0 +1,100 @@
+import type { WidgetPreset } from '@lobechat/types';
+import { WIDGET_PRESET_CATEGORIES } from '@lobechat/types';
+import { z } from 'zod';
+
+import { widgetContentSchema } from './manifest';
+import { widgetOutputSchema } from './output';
+
+const localeCopy = z.object({
+ description: z.string().max(500).optional(),
+ params: z
+ .record(
+ z.string(),
+ z.object({
+ description: z.string().max(500).optional(),
+ label: z.string().max(100).optional(),
+ }),
+ )
+ .optional(),
+ title: z.string().max(100).optional(),
+});
+
+/**
+ * Validation of a widget preset — what the gallery lists and what installing
+ * turns into a widget. Beyond each field, a preset must be installable as is:
+ * its sample is the output type it declares, a `data` preset brings its
+ * layout, and every required param has a default or is left for the person
+ * installing it to fill in.
+ */
+export const widgetPresetSchema = z
+ .object({
+ category: z.enum(WIDGET_PRESET_CATEGORIES),
+ contract: z
+ .string()
+ .regex(/^[a-z][\da-z-]*\.v\d+$/, 'contracts look like weather.v1')
+ .optional(),
+ description: z.string().min(1).max(500),
+ id: z
+ .string()
+ .regex(/^[a-z][\da-z]*(?:-[\da-z]+)*$/, 'preset ids are kebab-case')
+ .max(64),
+ locales: z.record(z.string().regex(/^[a-z]{2}(?:-[A-Z]{2})?$/), localeCopy).optional(),
+ sample: widgetOutputSchema,
+ size: z
+ .object({ h: z.number().int().min(2).max(12), w: z.number().int().min(1).max(12) })
+ .optional(),
+ tags: z.array(z.string().max(40)).max(10).optional(),
+ title: z.string().min(1).max(100),
+ version: z.string().regex(/^\d+\.\d+\.\d+$/, 'versions are semver, e.g. 1.0.0'),
+ widget: widgetContentSchema,
+ })
+ .superRefine((preset, ctx) => {
+ if (preset.sample.type !== preset.widget.outputType) {
+ ctx.addIssue({
+ code: 'custom',
+ message: `sample is "${preset.sample.type}" but the widget prints "${preset.widget.outputType}"`,
+ path: ['sample', 'type'],
+ });
+ }
+ if (preset.widget.outputType === 'data' && !preset.widget.view?.layout) {
+ ctx.addIssue({
+ code: 'custom',
+ message: 'a data preset needs view.layout to draw its card',
+ path: ['widget', 'view', 'layout'],
+ });
+ }
+ const params = new Set((preset.widget.manifest?.params ?? []).map((param) => param.name));
+ for (const [locale, copy] of Object.entries(preset.locales ?? {})) {
+ for (const name of Object.keys(copy.params ?? {})) {
+ if (!params.has(name)) {
+ ctx.addIssue({
+ code: 'custom',
+ message: `locale ${locale} labels unknown param "${name}"`,
+ path: ['locales', locale, 'params', name],
+ });
+ }
+ }
+ }
+ });
+
+/** Parse a preset, or throw with every problem listed. */
+export const parseWidgetPreset = (input: unknown): WidgetPreset => {
+ const result = widgetPresetSchema.safeParse(input);
+ if (!result.success) throw new Error(`Invalid widget preset: ${z.prettifyError(result.error)}`);
+ return result.data as WidgetPreset;
+};
+
+/** Gallery copy of a preset in a locale, falling back to its English fields. */
+export const localizeWidgetPreset = (preset: WidgetPreset, locale?: string) => {
+ const copy =
+ (locale && (preset.locales?.[locale] ?? preset.locales?.[locale.split('-')[0]])) || {};
+ return {
+ description: copy.description ?? preset.description,
+ params: (preset.widget.manifest?.params ?? []).map((param) => ({
+ ...param,
+ description: copy.params?.[param.name]?.description ?? param.description,
+ label: copy.params?.[param.name]?.label ?? param.label ?? param.name,
+ })),
+ title: copy.title ?? preset.title,
+ };
+};
diff --git a/packages/widget-spec/src/presets/countdown.ts b/packages/widget-spec/src/presets/countdown.ts
new file mode 100644
index 00000000000..f300a3cdd95
--- /dev/null
+++ b/packages/widget-spec/src/presets/countdown.ts
@@ -0,0 +1,163 @@
+import type { WidgetPreset } from '@lobechat/types';
+
+// The script runs in the widget sandbox (node, global fetch, no packages).
+const SCRIPT = String.raw`// Days until (or since) a date, counted in the chosen time zone.
+const title = process.env.TITLE || 'Countdown';
+const target = process.env.DATE;
+const timeZone = process.env.TIMEZONE || 'UTC';
+if (!/^\d{4}-\d{2}-\d{2}$/.test(target || '')) {
+ console.error('DATE must be YYYY-MM-DD');
+ process.exit(1);
+}
+
+const today = new Intl.DateTimeFormat('en-CA', { day: '2-digit', month: '2-digit', timeZone, year: 'numeric' })
+ .format(new Date());
+const days = Math.round((Date.parse(target) - Date.parse(today)) / 86400000);
+
+console.log(JSON.stringify({
+ data: { date: target, days: Math.abs(days), passed: days < 0, title, today },
+ type: 'data',
+}));
+`;
+
+export const countdown: WidgetPreset = {
+ id: 'countdown',
+ version: '1.0.0',
+ category: 'time',
+ contract: 'countdown.v1',
+ tags: ['countdown', 'date', 'holiday'],
+ title: 'Countdown',
+ description:
+ 'Days left until a date you care about — a holiday, a launch, a birthday — and days since once it has passed.',
+ locales: {
+ 'zh-CN': {
+ title: '倒数日',
+ description: '距离一个重要日子还有几天(假期、发布、生日),过了之后显示已过去几天。',
+ params: {
+ TITLE: {
+ label: '名称',
+ },
+ DATE: {
+ label: '日期',
+ },
+ TIMEZONE: {
+ label: '时区',
+ description: 'IANA 时区,例如 Asia/Shanghai',
+ },
+ },
+ },
+ },
+ size: {
+ w: 3,
+ h: 3,
+ },
+ sample: {
+ data: {
+ date: '2027-01-01',
+ days: 61,
+ passed: false,
+ title: 'Countdown',
+ today: '2026-11-01',
+ },
+ type: 'data',
+ },
+ widget: {
+ runtime: 'node',
+ outputType: 'data',
+ script: SCRIPT,
+ manifest: {
+ schedule: {
+ pattern: '0 * * * *',
+ },
+ params: [
+ {
+ name: 'TITLE',
+ type: 'string',
+ label: 'Name',
+ default: 'New Year',
+ },
+ {
+ name: 'DATE',
+ type: 'date',
+ label: 'Date',
+ required: true,
+ default: '2027-01-01',
+ },
+ {
+ name: 'TIMEZONE',
+ type: 'string',
+ label: 'Time zone',
+ description: 'IANA time zone, e.g. Europe/Berlin',
+ default: 'UTC',
+ },
+ ],
+ },
+ view: {
+ surface: 'sunset',
+ layout: {
+ type: 'stack',
+ gap: 4,
+ children: [
+ {
+ type: 'text',
+ value: {
+ bind: 'data.title',
+ },
+ weight: 'semibold',
+ },
+ {
+ type: 'spacer',
+ },
+ {
+ type: 'stack',
+ direction: 'row',
+ align: 'baseline',
+ gap: 6,
+ children: [
+ {
+ type: 'text',
+ value: '+',
+ size: '2xl',
+ visible: {
+ bind: 'data.passed',
+ eq: true,
+ },
+ },
+ {
+ type: 'text',
+ value: {
+ bind: 'data.days',
+ format: 'number',
+ },
+ size: 'display',
+ },
+ ],
+ },
+ {
+ type: 'stack',
+ direction: 'row',
+ gap: 4,
+ align: 'center',
+ children: [
+ {
+ type: 'icon',
+ name: 'calendar',
+ size: 14,
+ },
+ {
+ type: 'text',
+ value: {
+ bind: 'data.date',
+ format: 'date',
+ pattern: 'YYYY-MM-DD',
+ },
+ size: 'sm',
+ tone: 'secondary',
+ },
+ ],
+ },
+ ],
+ },
+ },
+ },
+};
diff --git a/packages/widget-spec/src/presets/githubRepo.ts b/packages/widget-spec/src/presets/githubRepo.ts
new file mode 100644
index 00000000000..c9efd266e02
--- /dev/null
+++ b/packages/widget-spec/src/presets/githubRepo.ts
@@ -0,0 +1,235 @@
+import type { WidgetPreset } from '@lobechat/types';
+
+// The script runs in the widget sandbox (node, global fetch, no packages).
+const SCRIPT = String.raw`// Stars, forks and open issues of one GitHub repository.
+const repo = process.env.REPO || 'lobehub/lobehub';
+if (!/^[\w.-]+\/[\w.-]+$/.test(repo)) {
+ console.error('REPO must look like owner/name');
+ process.exit(1);
+}
+
+const headers = { 'User-Agent': 'lobehub-widget' };
+if (process.env.GITHUB_TOKEN) headers.Authorization = 'Bearer ' + process.env.GITHUB_TOKEN;
+
+const res = await fetch('https://api.github.com/repos/' + repo, { headers });
+if (!res.ok) {
+ console.error('GitHub answered ' + res.status + ' for ' + repo);
+ process.exit(1);
+}
+const r = await res.json();
+
+console.log(JSON.stringify({
+ data: {
+ description: r.description || '',
+ forks: r.forks_count,
+ issues: r.open_issues_count,
+ language: r.language || '',
+ name: r.full_name,
+ pushedAt: r.pushed_at,
+ stars: r.stargazers_count,
+ },
+ type: 'data',
+}));
+`;
+
+export const githubRepo: WidgetPreset = {
+ id: 'github-repo',
+ version: '1.0.0',
+ category: 'dev',
+ contract: 'github-repo.v1',
+ tags: ['github', 'stars', 'open source'],
+ title: 'GitHub repository',
+ description:
+ 'Stars, forks and open issues of a GitHub repository, with its star count trended over time. Connecting GitHub avoids rate limits.',
+ locales: {
+ 'zh-CN': {
+ title: 'GitHub 仓库',
+ description:
+ 'GitHub 仓库的 Star、Fork 和未关闭 Issue 数,并记录 Star 的长期趋势。连接 GitHub 账号可以避免限流。',
+ params: {
+ REPO: {
+ label: '仓库',
+ description: 'owner/name,例如 lobehub/lobehub',
+ },
+ },
+ },
+ },
+ size: {
+ w: 4,
+ h: 4,
+ },
+ sample: {
+ data: {
+ description:
+ '🤯 LobeHub is your Chief Agent Operator, organizing your agents into 7×24 operations by hiring, scheduling, and reporting on your entire AI team.',
+ forks: 16023,
+ issues: 1193,
+ language: 'TypeScript',
+ name: 'lobehub/lobehub',
+ pushedAt: '2026-11-01T03:16:37Z',
+ stars: 83650,
+ },
+ type: 'data',
+ },
+ widget: {
+ runtime: 'node',
+ outputType: 'data',
+ script: SCRIPT,
+ manifest: {
+ network: {
+ allow: ['api.github.com'],
+ },
+ schedule: {
+ pattern: '0 * * * *',
+ },
+ metric: {
+ key: 'stars',
+ unit: 'stars',
+ valuePath: 'data.stars',
+ },
+ env: [
+ {
+ name: 'GITHUB_TOKEN',
+ connector: 'github',
+ required: false,
+ description: 'Optional; raises the GitHub API rate limit',
+ },
+ ],
+ params: [
+ {
+ name: 'REPO',
+ type: 'string',
+ label: 'Repository',
+ description: 'owner/name, e.g. lobehub/lobehub',
+ required: true,
+ default: 'lobehub/lobehub',
+ },
+ ],
+ },
+ view: {
+ surface: 'slate',
+ layout: {
+ type: 'stack',
+ gap: 6,
+ children: [
+ {
+ type: 'stack',
+ direction: 'row',
+ justify: 'between',
+ align: 'center',
+ gap: 8,
+ children: [
+ {
+ type: 'text',
+ value: {
+ bind: 'data.name',
+ },
+ weight: 'semibold',
+ },
+ {
+ type: 'badge',
+ value: {
+ bind: 'data.language',
+ },
+ visible: {
+ bind: 'data.language',
+ exists: true,
+ },
+ },
+ ],
+ },
+ {
+ type: 'stack',
+ direction: 'row',
+ align: 'center',
+ gap: 8,
+ children: [
+ {
+ type: 'icon',
+ name: 'star',
+ size: 28,
+ color: 'gold',
+ },
+ {
+ type: 'text',
+ value: {
+ template: '{data.stars|compact}',
+ },
+ size: 'display',
+ },
+ ],
+ },
+ {
+ type: 'stack',
+ direction: 'row',
+ gap: 14,
+ children: [
+ {
+ type: 'stack',
+ direction: 'row',
+ gap: 4,
+ align: 'center',
+ children: [
+ {
+ type: 'icon',
+ name: 'git-fork',
+ size: 14,
+ },
+ {
+ type: 'text',
+ value: {
+ template: '{data.forks|compact}',
+ },
+ size: 'sm',
+ },
+ ],
+ },
+ {
+ type: 'stack',
+ direction: 'row',
+ gap: 4,
+ align: 'center',
+ children: [
+ {
+ type: 'icon',
+ name: 'circle-dot',
+ size: 14,
+ },
+ {
+ type: 'text',
+ value: {
+ template: '{data.issues|compact}',
+ },
+ size: 'sm',
+ },
+ ],
+ },
+ ],
+ },
+ {
+ type: 'spacer',
+ },
+ {
+ type: 'text',
+ value: {
+ bind: 'data.description',
+ },
+ size: 'sm',
+ tone: 'secondary',
+ lines: 2,
+ hideWhen: 'short',
+ },
+ {
+ type: 'text',
+ value: {
+ bind: 'data.pushedAt',
+ format: 'relative',
+ },
+ size: 'xs',
+ tone: 'tertiary',
+ },
+ ],
+ },
+ },
+ },
+};
diff --git a/packages/widget-spec/src/presets/hackerNews.ts b/packages/widget-spec/src/presets/hackerNews.ts
new file mode 100644
index 00000000000..bb978f73d9e
--- /dev/null
+++ b/packages/widget-spec/src/presets/hackerNews.ts
@@ -0,0 +1,117 @@
+import type { WidgetPreset } from '@lobechat/types';
+
+// The script runs in the widget sandbox (node, global fetch, no packages).
+const SCRIPT = String.raw`// The top Hacker News stories right now.
+const limit = Math.min(Math.max(Number(process.env.LIMIT) || 8, 1), 20);
+const base = 'https://hacker-news.firebaseio.com/v0/';
+const get = async (path) => {
+ const res = await fetch(base + path);
+ if (!res.ok) throw new Error('Hacker News answered ' + res.status);
+ return res.json();
+};
+
+const ids = (await get('topstories.json')).slice(0, limit);
+const stories = await Promise.all(ids.map((id) => get('item/' + id + '.json')));
+
+console.log(JSON.stringify({
+ items: stories.filter(Boolean).map((s) => ({
+ // job posts have no comments
+ description: (s.descendants ?? 0) + ' comments · by ' + s.by,
+ time: new Date(s.time * 1000).toISOString(),
+ title: s.title,
+ url: s.url || 'https://news.ycombinator.com/item?id=' + s.id,
+ value: s.score,
+ })),
+ type: 'list',
+}));
+`;
+
+export const hackerNews: WidgetPreset = {
+ id: 'hacker-news-top',
+ version: '1.0.0',
+ category: 'content',
+ contract: 'hacker-news-top.v1',
+ tags: ['news', 'hacker news'],
+ title: 'Hacker News top stories',
+ description:
+ 'The stories on the Hacker News front page right now, with points and comment counts. Each opens in a new tab.',
+ locales: {
+ 'zh-CN': {
+ title: 'Hacker News 热门',
+ description: 'Hacker News 首页当前的热门文章,附分数和评论数,点击即可打开原文。',
+ params: {
+ LIMIT: {
+ label: '条数',
+ },
+ },
+ },
+ },
+ size: {
+ w: 6,
+ h: 4,
+ },
+ sample: {
+ items: [
+ {
+ description: '266 comments · by karpathy',
+ time: '2026-10-31T19:56:53.000Z',
+ title: 'HackerTube: YouTube built from videos recommended by HN',
+ url: 'https://karpathy.bearblog.dev/hacker-tube/',
+ value: 822,
+ },
+ {
+ description: '58 comments · by ecares',
+ time: '2026-10-31T22:41:06.000Z',
+ title: 'An Italian farmer found some unknown seeds in his attic and planted them',
+ url: 'https://www.smithsonianmag.com/science-nature/italian-farmer-found-unknown-seeds-attic-with-nothing-lose-planted-them-result-biblical-180989644/',
+ value: 196,
+ },
+ {
+ description: '178 comments · by oger',
+ time: '2026-10-31T19:16:30.000Z',
+ title: 'TCP Use-After-Free: CVE-2026-98432 / CVSS 9.8',
+ url: 'https://atlasum.net/blog/cve-2026-98432-linux-ipv4-tcp-uaf',
+ value: 373,
+ },
+ {
+ description: '55 comments · by guregodevo',
+ time: '2026-10-31T22:46:12.000Z',
+ title: 'Memdoor: A team of 5 Qwen3.8-27B models beats Fable 5 on LiveCodeBench Hard',
+ url: 'https://github.com/guregodevo/memdoor/tree/main/examples/workflows/team-solve',
+ value: 108,
+ },
+ {
+ description: '3 comments · by uvdn7',
+ time: '2026-10-31T22:54:55.000Z',
+ title: 'Altoids Project',
+ url: 'https://uvdn7.github.io/altoids-project/',
+ value: 59,
+ },
+ ],
+ type: 'list',
+ },
+ widget: {
+ runtime: 'node',
+ outputType: 'list',
+ script: SCRIPT,
+ manifest: {
+ network: {
+ allow: ['hacker-news.firebaseio.com'],
+ },
+ schedule: {
+ pattern: '*/30 * * * *',
+ },
+ params: [
+ {
+ name: 'LIMIT',
+ type: 'number',
+ label: 'Stories',
+ default: 8,
+ },
+ ],
+ },
+ view: {
+ limit: 20,
+ },
+ },
+};
diff --git a/packages/widget-spec/src/presets/index.ts b/packages/widget-spec/src/presets/index.ts
new file mode 100644
index 00000000000..8a5934ba773
--- /dev/null
+++ b/packages/widget-spec/src/presets/index.ts
@@ -0,0 +1,23 @@
+import type { WidgetPreset } from '@lobechat/types';
+
+import { countdown } from './countdown';
+import { githubRepo } from './githubRepo';
+import { hackerNews } from './hackerNews';
+import { weatherNow } from './weatherNow';
+import { yearProgress } from './yearProgress';
+
+/**
+ * Presets that ship with the app, so a self-hosted deployment without the
+ * Market still has ready-made widgets. Keep this set small; the full catalog
+ * lives in the Market.
+ */
+export const BUILTIN_WIDGET_PRESETS: readonly WidgetPreset[] = [
+ weatherNow,
+ countdown,
+ yearProgress,
+ githubRepo,
+ hackerNews,
+];
+
+export const findBuiltinWidgetPreset = (id: string): WidgetPreset | undefined =>
+ BUILTIN_WIDGET_PRESETS.find((preset) => preset.id === id);
diff --git a/packages/widget-spec/src/presets/weatherNow.ts b/packages/widget-spec/src/presets/weatherNow.ts
new file mode 100644
index 00000000000..f3fd3cb188d
--- /dev/null
+++ b/packages/widget-spec/src/presets/weatherNow.ts
@@ -0,0 +1,398 @@
+import type { WidgetPreset } from '@lobechat/types';
+
+// The script runs in the widget sandbox (node, global fetch, no packages).
+const SCRIPT = String.raw`// Current weather and the next hours for one city, from Open-Meteo (no key).
+const city = process.env.CITY || 'Hangzhou';
+const lang = process.env.LANGUAGE || 'en';
+
+const get = async (url) => {
+ const res = await fetch(url);
+ if (!res.ok) throw new Error(url.split('?')[0] + ' answered ' + res.status);
+ return res.json();
+};
+
+const geo = await get(
+ 'https://geocoding-api.open-meteo.com/v1/search?count=1&name=' +
+ encodeURIComponent(city) + '&language=' + encodeURIComponent(lang),
+);
+const place = geo.results && geo.results[0];
+if (!place) {
+ console.error('No place found for ' + city);
+ process.exit(1);
+}
+
+const w = await get(
+ 'https://api.open-meteo.com/v1/forecast?latitude=' + place.latitude + '&longitude=' + place.longitude +
+ '&current=temperature_2m,relative_humidity_2m,wind_speed_10m,weather_code,is_day' +
+ '&hourly=temperature_2m,weather_code,is_day' +
+ '&daily=temperature_2m_max,temperature_2m_min,precipitation_probability_max' +
+ '&timezone=auto&forecast_days=2',
+);
+
+// WMO weather code -> a short condition the layout maps to icons and surfaces.
+const condOf = (code, isDay) => {
+ if (code === 0) return isDay ? 'clear' : 'night';
+ if (code <= 2) return isDay ? 'partly' : 'night';
+ if (code === 3) return 'cloudy';
+ if (code === 45 || code === 48) return 'fog';
+ if ((code >= 51 && code <= 67) || (code >= 80 && code <= 82)) return 'rain';
+ if ((code >= 71 && code <= 77) || code === 85 || code === 86) return 'snow';
+ if (code >= 95) return 'storm';
+ return 'cloudy';
+};
+
+const now = w.current.time.slice(0, 13);
+const start = Math.max(0, w.hourly.time.findIndex((t) => t.slice(0, 13) === now));
+const hourly = w.hourly.time.slice(start, start + 6).map((t, i) => ({
+ cond: condOf(w.hourly.weather_code[start + i], w.hourly.is_day[start + i]),
+ t,
+ temp: Math.round(w.hourly.temperature_2m[start + i]),
+}));
+
+console.log(JSON.stringify({
+ data: {
+ city: place.name,
+ cond: condOf(w.current.weather_code, w.current.is_day),
+ hi: Math.round(w.daily.temperature_2m_max[0]),
+ hourly,
+ humidity: w.current.relative_humidity_2m,
+ lo: Math.round(w.daily.temperature_2m_min[0]),
+ rainChance: w.daily.precipitation_probability_max[0],
+ temp: w.current.temperature_2m,
+ wind: w.current.wind_speed_10m,
+ },
+ type: 'data',
+}));
+`;
+
+export const weatherNow: WidgetPreset = {
+ id: 'weather-now',
+ version: '1.0.0',
+ category: 'weather',
+ contract: 'weather.v1',
+ tags: ['weather', 'forecast'],
+ title: 'Weather now',
+ description:
+ 'Current temperature, conditions and the next six hours for a city, from Open-Meteo. The card turns sunny, cloudy, rainy or night with the weather.',
+ locales: {
+ 'zh-CN': {
+ title: '实时天气',
+ description:
+ '城市的当前温度、天气和未来 6 小时预报(Open-Meteo)。卡片背景随晴、阴、雨、夜自动变化。',
+ params: {
+ CITY: {
+ label: '城市',
+ description: '城市名,中英文均可',
+ },
+ LANGUAGE: {
+ label: '地名语言',
+ },
+ },
+ },
+ },
+ size: {
+ w: 4,
+ h: 4,
+ },
+ sample: {
+ data: {
+ city: 'London',
+ cond: 'cloudy',
+ hi: 13,
+ hourly: [
+ {
+ cond: 'cloudy',
+ t: '2026-11-01T03:00',
+ temp: 10,
+ },
+ {
+ cond: 'cloudy',
+ t: '2026-11-01T04:00',
+ temp: 10,
+ },
+ {
+ cond: 'cloudy',
+ t: '2026-11-01T05:00',
+ temp: 10,
+ },
+ {
+ cond: 'cloudy',
+ t: '2026-11-01T06:00',
+ temp: 10,
+ },
+ {
+ cond: 'cloudy',
+ t: '2026-11-01T07:00',
+ temp: 10,
+ },
+ {
+ cond: 'cloudy',
+ t: '2026-11-01T08:00',
+ temp: 10,
+ },
+ ],
+ humidity: 92,
+ lo: 9,
+ rainChance: 31,
+ temp: 10.1,
+ wind: 4.7,
+ },
+ type: 'data',
+ },
+ widget: {
+ runtime: 'node',
+ outputType: 'data',
+ script: SCRIPT,
+ manifest: {
+ network: {
+ allow: ['geocoding-api.open-meteo.com', 'api.open-meteo.com'],
+ },
+ schedule: {
+ pattern: '*/30 * * * *',
+ },
+ metric: {
+ key: 'temp',
+ unit: '°C',
+ valuePath: 'data.temp',
+ },
+ params: [
+ {
+ name: 'CITY',
+ type: 'string',
+ label: 'City',
+ description: 'City name in any language',
+ required: true,
+ default: 'London',
+ },
+ {
+ name: 'LANGUAGE',
+ type: 'select',
+ label: 'Place name language',
+ default: 'en',
+ options: [
+ {
+ label: 'English',
+ value: 'en',
+ },
+ {
+ label: '中文',
+ value: 'zh',
+ },
+ {
+ label: '日本語',
+ value: 'ja',
+ },
+ {
+ label: 'Deutsch',
+ value: 'de',
+ },
+ {
+ label: 'Français',
+ value: 'fr',
+ },
+ {
+ label: 'Español',
+ value: 'es',
+ },
+ ],
+ },
+ ],
+ },
+ view: {
+ surface: {
+ bind: 'data.cond',
+ map: {
+ clear: 'sky',
+ partly: 'sky',
+ night: 'night',
+ cloudy: 'cloudy',
+ fog: 'cloudy',
+ rain: 'rain',
+ snow: 'snow',
+ storm: 'storm',
+ },
+ },
+ layout: {
+ type: 'stack',
+ gap: 4,
+ children: [
+ {
+ type: 'stack',
+ direction: 'row',
+ justify: 'between',
+ align: 'start',
+ children: [
+ {
+ type: 'stack',
+ gap: 2,
+ children: [
+ {
+ type: 'text',
+ value: {
+ bind: 'data.city',
+ },
+ weight: 'semibold',
+ },
+ {
+ type: 'text',
+ value: {
+ template: '{data.temp|number:0}°',
+ },
+ size: 'display',
+ },
+ ],
+ },
+ {
+ type: 'icon',
+ name: {
+ bind: 'data.cond',
+ map: {
+ 'clear': 'sun',
+ 'partly': 'cloud-sun',
+ 'night': 'moon',
+ 'cloudy': 'cloud',
+ 'fog': 'cloud-fog',
+ 'rain': 'cloud-rain',
+ 'snow': 'cloud-snow',
+ 'storm': 'cloud-lightning',
+ '*': 'cloud',
+ },
+ },
+ size: 40,
+ },
+ ],
+ },
+ {
+ type: 'text',
+ value: {
+ template: '↑ {data.hi}° ↓ {data.lo}°',
+ },
+ size: 'sm',
+ tone: 'secondary',
+ },
+ {
+ type: 'stack',
+ direction: 'row',
+ gap: 14,
+ hideWhen: 'narrow',
+ children: [
+ {
+ type: 'stack',
+ direction: 'row',
+ gap: 4,
+ align: 'center',
+ children: [
+ {
+ type: 'icon',
+ name: 'droplets',
+ size: 14,
+ },
+ {
+ type: 'text',
+ value: {
+ template: '{data.humidity}%',
+ },
+ size: 'sm',
+ },
+ ],
+ },
+ {
+ type: 'stack',
+ direction: 'row',
+ gap: 4,
+ align: 'center',
+ children: [
+ {
+ type: 'icon',
+ name: 'wind',
+ size: 14,
+ },
+ {
+ type: 'text',
+ value: {
+ template: '{data.wind|number:0} km/h',
+ },
+ size: 'sm',
+ },
+ ],
+ },
+ {
+ type: 'stack',
+ direction: 'row',
+ gap: 4,
+ align: 'center',
+ children: [
+ {
+ type: 'icon',
+ name: 'umbrella',
+ size: 14,
+ },
+ {
+ type: 'text',
+ value: {
+ template: '{data.rainChance}%',
+ },
+ size: 'sm',
+ },
+ ],
+ },
+ ],
+ },
+ {
+ type: 'spacer',
+ },
+ {
+ type: 'repeat',
+ items: 'data.hourly',
+ limit: 6,
+ direction: 'row',
+ justify: 'between',
+ hideWhen: 'short',
+ template: {
+ type: 'stack',
+ gap: 6,
+ align: 'center',
+ children: [
+ {
+ type: 'text',
+ value: {
+ bind: 'item.t',
+ format: 'time',
+ },
+ size: 'xs',
+ tone: 'secondary',
+ },
+ {
+ type: 'icon',
+ name: {
+ bind: 'item.cond',
+ map: {
+ 'clear': 'sun',
+ 'partly': 'cloud-sun',
+ 'night': 'moon',
+ 'cloudy': 'cloud',
+ 'fog': 'cloud-fog',
+ 'rain': 'cloud-rain',
+ 'snow': 'cloud-snow',
+ 'storm': 'cloud-lightning',
+ '*': 'cloud',
+ },
+ },
+ size: 18,
+ },
+ {
+ type: 'text',
+ value: {
+ template: '{item.temp}°',
+ },
+ size: 'sm',
+ weight: 'medium',
+ },
+ ],
+ },
+ },
+ ],
+ },
+ },
+ },
+};
diff --git a/packages/widget-spec/src/presets/yearProgress.ts b/packages/widget-spec/src/presets/yearProgress.ts
new file mode 100644
index 00000000000..70a77dc0391
--- /dev/null
+++ b/packages/widget-spec/src/presets/yearProgress.ts
@@ -0,0 +1,139 @@
+import type { WidgetPreset } from '@lobechat/types';
+
+// The script runs in the widget sandbox (node, global fetch, no packages).
+const SCRIPT = String.raw`// How far through the year, month and week today is, in the chosen time zone.
+const timeZone = process.env.TIMEZONE || 'UTC';
+const today = new Intl.DateTimeFormat('en-CA', { day: '2-digit', month: '2-digit', timeZone, year: 'numeric' })
+ .format(new Date());
+const [year, month, day] = today.split('-').map(Number);
+
+const utc = (y, m, d) => Date.UTC(y, m - 1, d);
+const dayOfYear = (utc(year, month, day) - utc(year, 1, 1)) / 86400000 + 1;
+const daysInYear = (utc(year + 1, 1, 1) - utc(year, 1, 1)) / 86400000;
+const daysInMonth = new Date(Date.UTC(year, month, 0)).getUTCDate();
+const weekday = (new Date(utc(year, month, day)).getUTCDay() + 6) % 7; // Monday = 0
+
+console.log(JSON.stringify({
+ data: {
+ day: dayOfYear,
+ daysInYear,
+ month: day / daysInMonth,
+ week: (weekday + 1) / 7,
+ weeksPassed: Math.floor((dayOfYear - 1) / 7),
+ // a label, not a quantity: printed without digit grouping
+ year: String(year),
+ yearRatio: dayOfYear / daysInYear,
+ },
+ type: 'data',
+}));
+`;
+
+export const yearProgress: WidgetPreset = {
+ id: 'year-progress',
+ version: '1.0.0',
+ category: 'time',
+ contract: 'year-progress.v1',
+ tags: ['time', 'progress'],
+ title: 'Year progress',
+ description:
+ 'How much of the year has gone, as a percentage and one dot per week, with the day count.',
+ locales: {
+ 'zh-CN': {
+ title: '年度进度',
+ description: '今年已经过去多少:百分比、每周一个点,以及第几天。',
+ params: {
+ TIMEZONE: {
+ label: '时区',
+ description: 'IANA 时区,例如 Asia/Shanghai',
+ },
+ },
+ },
+ },
+ size: {
+ w: 4,
+ h: 4,
+ },
+ sample: {
+ data: {
+ day: 305,
+ daysInYear: 365,
+ month: 0.03333333333333333,
+ week: 1,
+ weeksPassed: 43,
+ year: '2026',
+ yearRatio: 0.8356164383561644,
+ },
+ type: 'data',
+ },
+ widget: {
+ runtime: 'node',
+ outputType: 'data',
+ script: SCRIPT,
+ manifest: {
+ schedule: {
+ pattern: '0 * * * *',
+ },
+ params: [
+ {
+ name: 'TIMEZONE',
+ type: 'string',
+ label: 'Time zone',
+ description: 'IANA time zone, e.g. Europe/Berlin',
+ default: 'UTC',
+ },
+ ],
+ },
+ view: {
+ surface: 'forest',
+ layout: {
+ type: 'stack',
+ gap: 8,
+ children: [
+ {
+ type: 'stack',
+ direction: 'row',
+ justify: 'between',
+ align: 'baseline',
+ children: [
+ {
+ type: 'text',
+ value: {
+ bind: 'data.year',
+ },
+ weight: 'semibold',
+ },
+ {
+ type: 'text',
+ value: {
+ template: '{data.day} / {data.daysInYear}',
+ },
+ size: 'sm',
+ tone: 'secondary',
+ },
+ ],
+ },
+ {
+ type: 'text',
+ value: {
+ bind: 'data.yearRatio',
+ format: 'percent',
+ },
+ size: 'display',
+ },
+ {
+ type: 'spacer',
+ },
+ {
+ type: 'dots',
+ value: {
+ bind: 'data.weeksPassed',
+ },
+ total: 52,
+ columns: 26,
+ hideWhen: 'short',
+ },
+ ],
+ },
+ },
+ },
+};
diff --git a/src/features/Dashboard/WidgetCard/views/LayoutView/icons.ts b/src/features/Dashboard/WidgetCard/views/LayoutView/icons.ts
index 2e8966ec8ca..7bde766d2d9 100644
--- a/src/features/Dashboard/WidgetCard/views/LayoutView/icons.ts
+++ b/src/features/Dashboard/WidgetCard/views/LayoutView/icons.ts
@@ -7,6 +7,7 @@ import {
BellIcon,
CalendarIcon,
CheckIcon,
+ CircleDotIcon,
ClockIcon,
CloudDrizzleIcon,
CloudFogIcon,
@@ -25,6 +26,7 @@ import {
FlameIcon,
GaugeIcon,
GitCommitHorizontalIcon,
+ GitForkIcon,
GitPullRequestIcon,
GlobeIcon,
HeartIcon,
@@ -62,6 +64,7 @@ export const WIDGET_LAYOUT_ICON_MAP: Record<WidgetLayoutIconName, LucideIcon> =
'bell': BellIcon,
'calendar': CalendarIcon,
'check': CheckIcon,
+ 'circle-dot': CircleDotIcon,
'clock': ClockIcon,
'cloud': CloudIcon,
'cloud-drizzle': CloudDrizzleIcon,
@@ -80,6 +83,7 @@ export const WIDGET_LAYOUT_ICON_MAP: Record<WidgetLayoutIconName, LucideIcon> =
'flame': FlameIcon,
'gauge': GaugeIcon,
'git-commit': GitCommitHorizontalIcon,
+ 'git-fork': GitForkIcon,
'git-pull-request': GitPullRequestIcon,
'globe': GlobeIcon,
'heart': HeartIcon,