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(widget): home & project dashboards, agent widget tool, chat preview and Portal (#20421)

Arvin Xu2fa05d673c64
diff --git a/.agents/skills/builtin-tool/references/ui/intervention.md b/.agents/skills/builtin-tool/references/ui/intervention.md
index 3072c940bb9..4d5dbe9e7fd 100644
--- a/.agents/skills/builtin-tool/references/ui/intervention.md
+++ b/.agents/skills/builtin-tool/references/ui/intervention.md
@@ -14,6 +14,13 @@ interface BuiltinInterventionProps<Arguments = any> {
interactionMode?: 'approval' | 'custom';
messageId: string;
+ /**
+ * Hold the host's approve action (reject / stop stay available) while the
+ * component cannot show what is being approved, e.g. review data loading or
+ * failed. Approval-mode only.
+ */
+ onApprovalBlockedChange?: (blocked: boolean) => void;
+
/** Called when the user edits the args; the approve action awaits this. */
onArgsChange?: (args: Arguments) => void | Promise<void>;
@@ -66,6 +73,7 @@ export default RunCommand;
## Intervention rules
- **Show a preview, not a form by default.** Editing UI is opt-in via `onArgsChange` and is usually inline (click to edit a code block, etc.).
+- **Never let approval outrun the review.** If the card fetches what the user is approving (a script, a version, credentials), show loading and error-with-retry states, and call `onApprovalBlockedChange(true)` until the exact data approval acts on is on screen (see `src/features/Dashboard/WidgetPreview/useWidgetReview.ts`).
- For args with debounced edit state (text fields), use `registerBeforeApprove(id, flushFn)` so the approve action waits for the debounce to flush. Always return the cleanup function.
- Call `onInteractionAction({ type: 'submit', payload })` when the user approves; `'skip'` if they skip with a reason; `'cancel'` if they cancel the whole turn.
- Add a corresponding `interventionAudit.ts` in the package root if the tool needs scope/path validation before approval (see `local-system/src/interventionAudit.ts`).
diff --git a/.agents/skills/store-data-structures/SKILL.md b/.agents/skills/store-data-structures/SKILL.md
index b5a57d22edd..217698818bd 100644
--- a/.agents/skills/store-data-structures/SKILL.md
+++ b/.agents/skills/store-data-structures/SKILL.md
@@ -10,3 +10,8 @@ user-invocable: true
Read [Zustand data structures](../zustand/references/data-structures.md) for
list/detail types, maps, reducers and shared type sources. The `zustand` skill
is the automatic entry for store work.
+
+A domain whose reads go through `@lobechat/replica` keeps its data in the same
+id-keyed `<domain>Map` views, plus one `<domain>Replica` bookkeeping field per
+view; its resources live in a sibling `projection.ts`. See
+[replica-backed server data](../zustand/SKILL.md#replica-backed-server-data).
diff --git a/apps/server/src/globalConfig/index.ts b/apps/server/src/globalConfig/index.ts
index 6479a967f97..91f843ff378 100644
--- a/apps/server/src/globalConfig/index.ts
+++ b/apps/server/src/globalConfig/index.ts
@@ -11,6 +11,7 @@ import { gatewayEnv } from '@/envs/gateway';
import { imageEnv } from '@/envs/image';
import { knowledgeEnv } from '@/envs/knowledge';
import { langfuseEnv } from '@/envs/langfuse';
+import { sandboxEnv } from '@/envs/sandbox';
import { toolsEnv } from '@/envs/tools';
import { parseSSOProviders } from '@/libs/better-auth/utils/server';
import { parseSystemAgent } from '@/server/globalConfig/parseSystemAgent';
@@ -174,6 +175,10 @@ export const getServerGlobalConfig = async () => {
// resolver's own function so both sides read the raw value identically —
// unset/invalid stays `undefined`, i.e. the resolver's default 64.
toolNameMaxLength: parseToolNameMaxLength(toolsEnv.TOOL_NAME_MAX_LENGTH),
+ // Lets the widget publish review match the sandbox's real egress contract:
+ // unless the Worker enforces per-host allowlists, declared hosts are
+ // advisory and the review must say any host is reachable.
+ widgetSandboxNetworkFormat: sandboxEnv.WIDGET_SANDBOX_NETWORK_FORMAT,
};
return config;
diff --git a/apps/server/src/router-hono/workflows/widget/handlers/tick.ts b/apps/server/src/router-hono/workflows/widget/handlers/tick.ts
index 3b481bc8a98..18af451aba6 100644
--- a/apps/server/src/router-hono/workflows/widget/handlers/tick.ts
+++ b/apps/server/src/router-hono/workflows/widget/handlers/tick.ts
@@ -3,6 +3,7 @@ import type { Context } from 'hono';
import { getServerDB } from '@/database/server';
import { appEnv } from '@/envs/app';
import { qstashClient } from '@/libs/qstash';
+import { toQStashDeduplicationId } from '@/libs/qstash/deduplicationId';
import { createWidgetSandboxRunner } from '@/server/services/widget/sandbox';
import {
isWidgetResumeTarget,
@@ -12,6 +13,7 @@ import {
export const RUN_WIDGET_PATH = '/api/workflows/widget/run-widget';
+/** Logical run key per due slot; encoded for QStash at the publish boundary. */
export const widgetRunDeduplicationId = (widgetId: string, slotIso: string) =>
`widget:${widgetId}:${slotIso}`;
@@ -57,7 +59,9 @@ export async function tick(c: Context) {
await qstashClient.publishJSON({
body: { leaseStartedAt, runId: target.runId, widgetId: target.widgetId },
// Overlapping ticks see the same stale lease; publish it once.
- deduplicationId: widgetResumeDeduplicationId(target.runId, leaseStartedAt),
+ deduplicationId: toQStashDeduplicationId(
+ widgetResumeDeduplicationId(target.runId, leaseStartedAt),
+ ),
url,
});
return;
@@ -67,7 +71,9 @@ export async function tick(c: Context) {
await qstashClient.publishJSON({
body: { slot: slotIso, widgetId: target.widgetId },
// Overlapping ticks see the same unclaimed slot; publish it once.
- deduplicationId: widgetRunDeduplicationId(target.widgetId, slotIso),
+ deduplicationId: toQStashDeduplicationId(
+ widgetRunDeduplicationId(target.widgetId, slotIso),
+ ),
url,
});
}
diff --git a/apps/server/src/routers/lambda/__tests__/integration/widget.integration.test.ts b/apps/server/src/routers/lambda/__tests__/integration/widget.integration.test.ts
index 55e35ecf27d..a07d13a10c0 100644
--- a/apps/server/src/routers/lambda/__tests__/integration/widget.integration.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/integration/widget.integration.test.ts
@@ -2,9 +2,11 @@
import type { LobeChatDatabase } from '@lobechat/database';
import {
agents,
+ dashboards,
metricPoints,
metrics,
projects,
+ topics,
widgetRuns,
widgets,
widgetVersions,
@@ -41,6 +43,17 @@ vi.mock('@/database/core/db-adaptor', () => ({
}),
}));
+// Runtime flag `dashboard` (off by default): the suite runs with it on and
+// narrows it per test to exercise the gate through the real flag mapping.
+const dashboardFlag = vi.hoisted(() => ({ value: true as boolean | string[] }));
+vi.mock('@/server/featureFlags', async () => {
+ const { mapFeatureFlagsEnvToState } = await import('@/config/featureFlags');
+ return {
+ getServerFeatureFlagsStateFromRuntimeConfig: async (userId?: string) =>
+ mapFeatureFlagsEnvToState({ dashboard: dashboardFlag.value }, userId),
+ };
+});
+
const queueMode = vi.hoisted(() => ({ enabled: false }));
vi.mock('@/envs/app', async (importOriginal) => {
const mod = await importOriginal<{ appEnv: object }>();
@@ -104,6 +117,7 @@ describe('widget + dashboard routers integration', () => {
afterEach(async () => {
queueMode.enabled = false;
+ dashboardFlag.value = true;
vi.restoreAllMocks();
vi.unstubAllEnvs();
await db.delete(workspaces).where(eq(workspaces.id, workspaceId));
@@ -121,6 +135,31 @@ describe('widget + dashboard routers integration', () => {
input: Parameters<WidgetCaller['create']>[0] = { title: 'Open PRs' },
) => (await caller.create(input))!.data;
+ describe('feature flag', () => {
+ it('refuses every widget and dashboard call, agent tool included, while `dashboard` is off for the caller', async () => {
+ dashboardFlag.value = [ownerId];
+ const owner = callers(ownerId);
+ const member = callers(memberId);
+
+ expect((await owner.board.list())!.success).toBe(true);
+ expect((await owner.widget.list())!.success).toBe(true);
+
+ await expect(member.board.list()).rejects.toMatchObject({ code: 'FORBIDDEN' });
+ await expect(member.widget.list()).rejects.toMatchObject({ code: 'FORBIDDEN' });
+ await expect(
+ member.board.runAgentTool({ apiName: 'listDashboards', args: {} }),
+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });
+
+ dashboardFlag.value = false;
+ await expect(owner.board.create({ title: 'Ops' })).rejects.toMatchObject({
+ code: 'FORBIDDEN',
+ });
+ await expect(owner.widget.create({ title: 'Open PRs' })).rejects.toMatchObject({
+ code: 'FORBIDDEN',
+ });
+ });
+ });
+
describe('version flow', () => {
it('requires a successful dry run of the exact content before publishing', async () => {
const owner = widgetRouter.createCaller(context(ownerId));
@@ -174,15 +213,37 @@ describe('widget + dashboard routers integration', () => {
const widget = await createWidget(owner, { dashboardId: board.id, title: 'Open PRs' });
const draft = (await owner.saveDraft({ widgetId: widget.id, ...statScript }))!.data;
+ const coordinatorId = await createTestAgent(db, ownerId);
+ const [project] = await db
+ .insert(projects)
+ .values({
+ coordinatorAgentId: coordinatorId,
+ identifier: 'OPS',
+ name: 'Ops project',
+ userId: ownerId,
+ })
+ .returning();
+ const projectBoard = (await ownerBoard.create({ projectId: project.id, title: 'Launch' }))!
+ .data;
+ await ownerBoard.addItem({ dashboardId: projectBoard.id, widgetId: widget.id });
+
const detail = (await owner.detail({ id: widget.id }))!.data;
expect(detail).toMatchObject({
- dashboards: [{ id: board.id, title: 'Ops' }],
draftVersion: { id: draft.id },
publishedVersion: null,
});
+ // Each board carries its project so links open it inside the project.
+ expect(detail.dashboards).toEqual(
+ expect.arrayContaining([
+ { id: board.id, projectId: null, title: 'Ops' },
+ { id: projectBoard.id, projectId: project.id, title: 'Launch' },
+ ]),
+ );
await ownerBoard.trash({ id: board.id });
- expect((await owner.detail({ id: widget.id }))!.data.dashboards).toEqual([]);
+ expect((await owner.detail({ id: widget.id }))!.data.dashboards).toEqual([
+ { id: projectBoard.id, projectId: project.id, title: 'Launch' },
+ ]);
});
it('publishes v2 over v1 and rolls back to the archived v1', async () => {
@@ -745,6 +806,77 @@ describe('widget + dashboard routers integration', () => {
});
});
+ describe('runAgentTool', () => {
+ it('scopes widgets to the conversation’s agent and project, ignoring foreign topics', async () => {
+ const agentId = await createTestAgent(db, ownerId);
+ const coordinatorId = await createTestAgent(db, ownerId);
+ const [project] = await db
+ .insert(projects)
+ .values({
+ coordinatorAgentId: coordinatorId,
+ identifier: 'TOOL',
+ name: 'P',
+ userId: ownerId,
+ })
+ .returning();
+ await db.insert(topics).values([
+ { agentId, id: `tpc_own_${ownerId}`, projectId: project.id, userId: ownerId },
+ { id: `tpc_other_${memberId}`, projectId: project.id, userId: memberId },
+ ]);
+ const { board } = callers(ownerId);
+ const createArgs = { ...statScript, description: 'Always 7', title: 'Seven' };
+
+ const created = await board.runAgentTool({
+ apiName: 'createWidgetDraft',
+ args: createArgs,
+ context: { agentId, operationId: 'op_1', topicId: `tpc_own_${ownerId}` },
+ });
+ expect(created).toMatchObject({ success: true });
+ const [widget] = await db
+ .select()
+ .from(widgets)
+ .where(eq(widgets.id, created.state.widgetId));
+ expect(widget).toMatchObject({ agentId, projectId: project.id, userId: ownerId });
+
+ // Another user's topic id is dropped instead of leaking its project.
+ const foreign = await board.runAgentTool({
+ apiName: 'createWidgetDraft',
+ args: createArgs,
+ context: { agentId, topicId: `tpc_other_${memberId}` },
+ });
+ const [foreignWidget] = await db
+ .select()
+ .from(widgets)
+ .where(eq(widgets.id, foreign.state.widgetId));
+ expect(foreignWidget).toMatchObject({ agentId, projectId: null });
+
+ // A run without the widget's agent/project cannot reach it.
+ const unscoped = await board.runAgentTool({
+ apiName: 'dryRunWidget',
+ args: { versionId: created.state.versionId, widgetId: widget.id },
+ context: { operationId: 'op_1' },
+ });
+ expect(unscoped).toMatchObject({ success: false });
+ expect(runSandbox).not.toHaveBeenCalled();
+
+ runSandbox.mockResolvedValueOnce(ok({ type: 'stat', value: 7 }));
+ const dryRun = await board.runAgentTool({
+ apiName: 'dryRunWidget',
+ args: { versionId: created.state.versionId, widgetId: widget.id },
+ context: { agentId, operationId: 'op_1', topicId: `tpc_own_${ownerId}` },
+ });
+ expect(dryRun).toMatchObject({ state: { status: 'succeeded' }, success: true });
+ expect(dryRun.content).toContain('"value": 7');
+ });
+
+ it('rejects unknown tool APIs', async () => {
+ const { board } = callers(ownerId);
+ await expect(
+ board.runAgentTool({ apiName: 'publish', args: {} } as any),
+ ).rejects.toMatchObject({ code: 'BAD_REQUEST' });
+ });
+ });
+
describe('permissions', () => {
it('lets members read and refresh public widgets but not author them', async () => {
const { board: ownerBoard, widget: owner } = callers(ownerId, workspaceId);
@@ -796,6 +928,35 @@ describe('widget + dashboard routers integration', () => {
expect((await member.list())!.data.map((w) => w.id)).toEqual([widget.id]);
});
+ it('refuses a layout write that saves nothing instead of reporting it saved', async () => {
+ const { board: ownerBoard, widget: owner } = callers(ownerId, workspaceId);
+ const { board: memberBoard } = callers(memberId, workspaceId);
+
+ const board = (await ownerBoard.create({ title: 'Team board' }))!.data;
+ const widget = await createWidget(owner, { dashboardId: board.id, title: 'CI health' });
+ const [{ item }] = (await memberBoard.detail({ id: board.id }))!.data.items;
+ const patches = [{ id: item.id, layout: { h: 2, w: 4, x: 0, y: 0 } }];
+
+ // A member can read the public board but only its creator can arrange it.
+ await expect(
+ memberBoard.updateItemLayouts({ dashboardId: board.id, patches }),
+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ // Items that are not on the board save nothing either.
+ await expect(
+ ownerBoard.updateItemLayouts({
+ dashboardId: board.id,
+ patches: [{ ...patches[0], id: widget.id }],
+ }),
+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });
+
+ expect((await ownerBoard.updateItemLayouts({ dashboardId: board.id, patches }))!.data).toBe(
+ 1,
+ );
+ expect(
+ (await ownerBoard.updateItemLayouts({ dashboardId: board.id, patches: [] }))!.data,
+ ).toBe(0);
+ });
+
it('hides a public widget, its versions, runs and metric series once its project turns private', async () => {
const coordinatorId = await createTestAgent(db, ownerId);
await db.update(agents).set({ workspaceId }).where(eq(agents.id, coordinatorId));
@@ -892,6 +1053,35 @@ describe('widget + dashboard routers integration', () => {
expect(placed.item).toMatchObject({ dashboardId: board.id, widgetId: placed.id });
});
+ it('creates a board with a widget on it in one step, keeping no board when placement fails', async () => {
+ const { board: ownerBoard, widget: owner } = callers(ownerId, workspaceId);
+ const widget = await createWidget(owner);
+ const boardsOf = (userId: string) =>
+ db
+ .select()
+ .from(dashboards)
+ .where(and(eq(dashboards.userId, userId), eq(dashboards.workspaceId, workspaceId)));
+
+ // A widget the caller cannot read (or that does not exist) is not placed.
+ await expect(
+ ownerBoard.create({ title: 'Ghost', widgetId: '00000000-0000-4000-8000-000000000000' }),
+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });
+ // The placement insert itself fails.
+ vi.spyOn(DashboardModel.prototype, 'addItem').mockRejectedValueOnce(
+ new Error('FK violation'),
+ );
+ await expect(
+ ownerBoard.create({ title: 'Failed placement', widgetId: widget.id }),
+ ).rejects.toMatchObject({ code: 'INTERNAL_SERVER_ERROR' });
+ expect(await boardsOf(ownerId)).toEqual([]);
+
+ const board = (await ownerBoard.create({ title: 'Ops', widgetId: widget.id }))!.data;
+ expect((await ownerBoard.detail({ id: board.id }))!.data.items).toMatchObject([
+ { widget: { id: widget.id } },
+ ]);
+ expect((await boardsOf(ownerId)).map(({ title }) => title)).toEqual(['Ops']);
+ });
+
it('rejects malformed ids before they reach the database', async () => {
const owner = widgetRouter.createCaller(context(ownerId));
@@ -1008,9 +1198,12 @@ describe('widget + dashboard routers integration', () => {
expect(await post('/tick', {})).toMatchObject({ claimed: 0, dispatched: 1, due: 1 });
expect(publish).toHaveBeenCalledWith({
body: { slot: slot.toISOString(), widgetId: widget.id },
- deduplicationId: `widget:${widget.id}:${slot.toISOString()}`,
+ // QStash rejects `:` in a deduplication id, so the logical
+ // `widget:<id>:<slot>` key is encoded before it is published.
+ deduplicationId: expect.stringMatching(/^[a-f0-9]{64}$/),
url: 'https://app.test/api/workflows/widget/run-widget',
});
+ expect(publish.mock.calls[0][0].deduplicationId).not.toContain(':');
// Not claimed and nothing ran in the tick: the slot is still due.
expect(await nextRunAt(widget.id)).toEqual(slot);
expect(runSandbox).not.toHaveBeenCalled();
@@ -1117,7 +1310,8 @@ describe('widget + dashboard routers integration', () => {
const resumeMessage = { leaseStartedAt, runId: reserved.id, widgetId: widget.id };
expect(publish).toHaveBeenCalledWith({
body: resumeMessage,
- deduplicationId: `widget-run:${reserved.id}:${leaseStartedAt}`,
+ // Same QStash-safe encoding as a due slot's publish.
+ deduplicationId: expect.stringMatching(/^[a-f0-9]{64}$/),
url: 'https://app.test/api/workflows/widget/run-widget',
});
diff --git a/apps/server/src/routers/lambda/_helpers/dashboardFeatureGate.ts b/apps/server/src/routers/lambda/_helpers/dashboardFeatureGate.ts
new file mode 100644
index 00000000000..9bd4ee4ff4a
--- /dev/null
+++ b/apps/server/src/routers/lambda/_helpers/dashboardFeatureGate.ts
@@ -0,0 +1,13 @@
+import { TRPCError } from '@trpc/server';
+
+import { isDashboardEnabled } from '@/server/services/widget/featureGate';
+
+/** Refuse every widget / dashboard call while the `dashboard` flag is off for the caller. */
+export const assertDashboardEnabled = async (userId: string) => {
+ if (!(await isDashboardEnabled(userId))) {
+ throw new TRPCError({
+ code: 'FORBIDDEN',
+ message: 'Dashboards are not enabled for this account',
+ });
+ }
+};
diff --git a/apps/server/src/routers/lambda/_helpers/widgetError.ts b/apps/server/src/routers/lambda/_helpers/widgetError.ts
index ddddc443471..d6dbc85c9ed 100644
--- a/apps/server/src/routers/lambda/_helpers/widgetError.ts
+++ b/apps/server/src/routers/lambda/_helpers/widgetError.ts
@@ -1,5 +1,6 @@
import { TRPCError } from '@trpc/server';
+import { DashboardItemLimitError } from '@/database/models/dashboard';
import { ScopeLevelError } from '@/database/utils/scopeLevel';
import { WidgetFlowError } from '@/server/services/widget';
@@ -25,6 +26,9 @@ export function mapWidgetError(error: unknown, domain: string, operation: string
if (error instanceof WidgetFlowError) {
throw new TRPCError({ code: FLOW_ERROR_CODES[error.code], message: error.message });
}
+ if (error instanceof DashboardItemLimitError) {
+ throw new TRPCError({ code: 'BAD_REQUEST', message: error.message });
+ }
if (error instanceof ScopeLevelError) {
throw new TRPCError({
code: error.code === 'SCOPE_MISMATCH' ? 'BAD_REQUEST' : 'NOT_FOUND',
diff --git a/apps/server/src/routers/lambda/dashboard.ts b/apps/server/src/routers/lambda/dashboard.ts
index eef968b05d1..d3b870413dc 100644
--- a/apps/server/src/routers/lambda/dashboard.ts
+++ b/apps/server/src/routers/lambda/dashboard.ts
@@ -1,3 +1,5 @@
+import { DASHBOARD_TITLE_MAX_LENGTH, DashboardApiName } from '@lobechat/builtin-tool-dashboard';
+import { DashboardExecutionRuntime } from '@lobechat/builtin-tool-dashboard/executionRuntime';
import { DASHBOARD_VISIBILITIES } from '@lobechat/types';
import { z } from 'zod';
@@ -5,15 +7,20 @@ import {
requireWorkspaceRoleWhenScoped,
wsCompatProcedure,
} from '@/business/server/trpc-middlewares/workspaceAuth';
-import { DashboardModel } from '@/database/models/dashboard';
+import { DASHBOARD_MAX_ITEMS, DashboardModel } from '@/database/models/dashboard';
+import type { LobeChatDatabase } from '@/database/type';
import { router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
import { DashboardService } from '@/server/services/dashboard';
+import { createDashboardToolService, resolveClientTopic } from '@/server/services/widget/agentTool';
+import { assertDashboardEnabled } from './_helpers/dashboardFeatureGate';
import { mapWidgetError, notFound } from './_helpers/widgetError';
const dashboardProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {
const { ctx } = opts;
+ // Off by default (runtime flag `dashboard`); covers `runAgentTool` too.
+ await assertDashboardEnabled(ctx.userId);
const workspaceId = ctx.workspaceId ?? undefined;
return opts.next({
ctx: {
@@ -43,8 +50,10 @@ const layoutSchema = z.object({
y: z.number().int().min(0),
});
-const fail = (error: unknown, operation: string): never =>
- mapWidgetError(error, 'dashboard', operation);
+// A declaration (not an arrow const) so `fail(...)` narrows control flow as `never`.
+function fail(error: unknown, operation: string): never {
+ return mapWidgetError(error, 'dashboard', operation);
+}
/**
* Dashboards (boards) and the placement of widgets on them. Widgets
@@ -88,13 +97,34 @@ export const dashboardRouter = router({
metadata,
projectId: z.string().nullish(),
sortOrder: z.number().int().optional(),
- title: z.string().min(1).max(200),
+ title: z.string().min(1).max(DASHBOARD_TITLE_MAX_LENGTH),
visibility: visibility.optional(),
+ /**
+ * Place this widget on the new board in the same transaction: a widget
+ * that cannot be placed rolls the board back, so no empty board is left.
+ */
+ widgetId: uuid.optional(),
}),
)
.mutation(async ({ ctx, input }) => {
try {
- const data = await ctx.dashboardModel.create(input);
+ const { widgetId, ...boardInput } = input;
+ if (!widgetId) {
+ const data = await ctx.dashboardModel.create(boardInput);
+ return { data, message: 'Dashboard created', success: true };
+ }
+
+ const workspaceId = ctx.workspaceId ?? undefined;
+ const data = await ctx.serverDB.transaction(async (tx) => {
+ const txDB = tx as LobeChatDatabase;
+ const board = await new DashboardModel(txDB, ctx.userId, workspaceId).create(boardInput);
+ const item = await new DashboardService(txDB, ctx.userId, workspaceId).placeWidget(
+ board.id,
+ widgetId,
+ );
+ if (!item) throw notFound('Widget');
+ return board;
+ });
return { data, message: 'Dashboard created', success: true };
} catch (error) {
fail(error, 'create dashboard');
@@ -143,7 +173,7 @@ export const dashboardRouter = router({
}),
removeItems: dashboardWriteProcedure
- .input(z.object({ dashboardId: uuid, itemIds: z.array(uuid).max(200) }))
+ .input(z.object({ dashboardId: uuid, itemIds: z.array(uuid).max(DASHBOARD_MAX_ITEMS) }))
.mutation(async ({ ctx, input }) => {
try {
const data = await ctx.dashboardService.removeItems(input.dashboardId, input.itemIds);
@@ -163,6 +193,53 @@ export const dashboardRouter = router({
}
}),
+ /**
+ * Execute one `lobe-dashboard` tool call for an agent run driven by the
+ * client runtime. The server agent runtime executes the same runtime and
+ * service in-process; both scope created widgets to the conversation's
+ * agent and (for a project topic) project. Publishing still requires the
+ * user's approval, which the agent runtime enforces before dispatching.
+ */
+ runAgentTool: dashboardWriteProcedure
+ .input(
+ z.object({
+ apiName: z.enum(Object.values(DashboardApiName) as [string, ...string[]]),
+ args: z.record(z.string(), z.unknown()),
+ context: z
+ .object({
+ agentId: z.string().nullish(),
+ messageId: z.string().nullish(),
+ operationId: z.string().nullish(),
+ topicId: z.string().nullish(),
+ })
+ .optional(),
+ }),
+ )
+ .mutation(async ({ ctx, input }) => {
+ const context = input.context ?? {};
+ const topic = await resolveClientTopic(
+ ctx.serverDB,
+ context.topicId,
+ ctx.userId,
+ ctx.workspaceId ?? undefined,
+ );
+ const runtime = new DashboardExecutionRuntime(
+ createDashboardToolService(ctx.serverDB, {
+ agentId: context.agentId ?? undefined,
+ messageId: context.messageId ?? undefined,
+ operationId: context.operationId ?? undefined,
+ projectId: topic.projectId,
+ topicId: topic.topicId,
+ userId: ctx.userId,
+ workspaceId: ctx.workspaceId ?? undefined,
+ }),
+ );
+ const method = runtime[input.apiName as keyof DashboardExecutionRuntime] as (
+ args: unknown,
+ ) => ReturnType<DashboardExecutionRuntime['listDashboards']>;
+ return method.call(runtime, input.args);
+ }),
+
trash: dashboardWriteProcedure.input(idInput).mutation(async ({ ctx, input }) => {
try {
const data = await ctx.dashboardModel.trash(input.id);
@@ -182,7 +259,7 @@ export const dashboardRouter = router({
icon: z.string().max(100).nullish(),
metadata,
sortOrder: z.number().int().optional(),
- title: z.string().min(1).max(200).optional(),
+ title: z.string().min(1).max(DASHBOARD_TITLE_MAX_LENGTH).optional(),
visibility: visibility.optional(),
}),
}),
@@ -197,7 +274,10 @@ export const dashboardRouter = router({
}
}),
- /** Persist a drag-and-drop result; ids not on this board are ignored. */
+ /**
+ * Persist a drag-and-drop result; ids not on this board are ignored. Fails
+ * with NOT_FOUND when nothing was saved (not the creator, or stale items).
+ */
updateItemLayouts: dashboardWriteProcedure
.input(
z.object({
@@ -210,12 +290,15 @@ export const dashboardRouter = router({
sortOrder: z.number().int().optional(),
}),
)
- .max(200),
+ .max(DASHBOARD_MAX_ITEMS),
}),
)
.mutation(async ({ ctx, input }) => {
try {
const data = await ctx.dashboardService.saveLayout(input.dashboardId, input.patches);
+ // Nothing saved means the caller cannot change this board (only its
+ // creator can) or none of the items are on it — never report success.
+ if (input.patches.length > 0 && data === 0) throw notFound('Dashboard or its items');
return { data, message: 'Layout saved', success: true };
} catch (error) {
fail(error, 'save layout');
diff --git a/apps/server/src/routers/lambda/widget.ts b/apps/server/src/routers/lambda/widget.ts
index b67fe64fd52..735b76144d7 100644
--- a/apps/server/src/routers/lambda/widget.ts
+++ b/apps/server/src/routers/lambda/widget.ts
@@ -12,12 +12,19 @@ import { router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
import { DashboardService } from '@/server/services/dashboard';
import { WidgetService } from '@/server/services/widget';
+import {
+ widgetMetadataPatchSchema,
+ widgetMetadataSchema,
+} from '@/server/services/widget/metadataSchema';
import { widgetVersionContentSchema } from '@/server/services/widget/versionSchema';
+import { assertDashboardEnabled } from './_helpers/dashboardFeatureGate';
import { mapWidgetError, notFound } from './_helpers/widgetError';
const widgetProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {
const { ctx } = opts;
+ // Off by default (runtime flag `dashboard`); covers `runAgentTool` too.
+ await assertDashboardEnabled(ctx.userId);
const workspaceId = ctx.workspaceId ?? undefined;
return opts.next({
ctx: {
@@ -50,8 +57,10 @@ const layoutSchema = z.object({
y: z.number().int().min(0),
});
-const fail = (error: unknown, operation: string): never =>
- mapWidgetError(error, 'widget', operation);
+// A declaration (not an arrow const) so `fail(...)` narrows control flow as `never`.
+function fail(error: unknown, operation: string): never {
+ return mapWidgetError(error, 'widget', operation);
+}
/**
* Widgets, their versions and runs.
@@ -74,11 +83,11 @@ export const widgetRouter = router({
z.object({
agentId: z.string().nullish(),
dashboardId: uuid.optional(),
- description: z.string().max(2000).nullish(),
+ // Same bounds the dashboard tool enforces — one schema, no drift.
+ ...widgetMetadataSchema.shape,
layout: layoutSchema.nullish(),
metadata,
projectId: z.string().nullish(),
- title: z.string().min(1).max(200),
visibility: visibility.optional(),
}),
)
@@ -178,6 +187,23 @@ export const widgetRouter = router({
}
}),
+ /**
+ * The preview run a publish approval was based on, fetched by version — it
+ * stays reachable after the widget's run history rolls past the list
+ * window, so old publish cards keep their body.
+ */
+ getPreviewRun: widgetProcedure
+ .input(z.object({ versionId: uuid, widgetId: uuid }))
+ .query(async ({ ctx, input }) => {
+ try {
+ const data = await ctx.widgetModel.findPreviewRun(input.widgetId, input.versionId);
+ if (!data) throw notFound('Run');
+ return { data, success: true };
+ } catch (error) {
+ fail(error, 'get widget preview run');
+ }
+ }),
+
getVersion: widgetProcedure
.input(z.object({ versionId: uuid, widgetId: uuid }))
.query(async ({ ctx, input }) => {
@@ -326,9 +352,8 @@ export const widgetRouter = router({
z.object({
id: uuid,
value: z.object({
- description: z.string().max(2000).nullish(),
+ ...widgetMetadataPatchSchema.shape,
metadata,
- title: z.string().min(1).max(200).optional(),
visibility: visibility.optional(),
}),
}),
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
index 8ac201b7f86..58e2a0bab3c 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService.ts
@@ -19,6 +19,7 @@ import {
isParkedStatus,
} from '@lobechat/agent-runtime';
import type { ISnapshotStore } from '@lobechat/agent-tracing';
+import { DASHBOARD_DRY_RUN_AUDIT } from '@lobechat/builtin-tool-dashboard';
import { appendSubAgentReference, isCallSubAgentCall } from '@lobechat/builtin-tool-lobe-agent';
import { dynamicInterventionAudits } from '@lobechat/builtin-tools/dynamicInterventionAudits';
import { ABANDONED_OPERATION_ERROR_PREFIX } from '@lobechat/const/goal';
@@ -95,6 +96,7 @@ import { QueueService } from '@/server/services/queue';
import { LocalQueueServiceImpl } from '@/server/services/queue/impls';
import { ToolExecutionService } from '@/server/services/toolExecution';
import { BuiltinToolsExecutor } from '@/server/services/toolExecution/builtin';
+import { createWidgetDryRunAudit } from '@/server/services/widget/dryRunAudit';
import {
resolveRunWorkAccessScope,
stateHasEntityFileEdits,
@@ -5115,7 +5117,14 @@ export class AgentRuntimeService {
enabled: world?.agent?.chatConfig?.enableContextCompression ?? true,
maxWindowToken: contextWindowTokens ?? undefined,
},
- dynamicInterventionAudits,
+ dynamicInterventionAudits: {
+ ...dynamicInterventionAudits,
+ [DASHBOARD_DRY_RUN_AUDIT]: createWidgetDryRunAudit(
+ this.serverDB,
+ origin?.userId ?? this.userId,
+ this.workspaceId,
+ ),
+ },
modelRuntimeConfig,
operationId,
userId: origin?.userId,
diff --git a/apps/server/src/services/aiAgent/__tests__/execAgent.pluginTriState.test.ts b/apps/server/src/services/aiAgent/__tests__/execAgent.pluginTriState.test.ts
index ff3a6927f49..337f2962d28 100644
--- a/apps/server/src/services/aiAgent/__tests__/execAgent.pluginTriState.test.ts
+++ b/apps/server/src/services/aiAgent/__tests__/execAgent.pluginTriState.test.ts
@@ -28,6 +28,15 @@ const {
mockPluginQuery: vi.fn().mockResolvedValue([]),
}));
+// Feature-gated builtin tools (e.g. lobe-dashboard) join the disabled set
+// when their flag is off; this suite covers the agent's own tri-state config,
+// so run it with every gate open. Gating has its own coverage in
+// pipeline/__tests__/toolDiscovery.featureGate.test.ts.
+vi.mock('@/server/featureFlags', async (importOriginal) => ({
+ ...(await importOriginal<Record<string, unknown>>()),
+ getServerFeatureFlagsStateFromRuntimeConfig: vi.fn().mockResolvedValue({ enableDashboard: true }),
+}));
+
vi.mock('@/libs/trusted-client', () => ({
generateTrustedClientToken: vi.fn().mockReturnValue(undefined),
getTrustedClientTokenForSession: vi.fn().mockResolvedValue(undefined),
diff --git a/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.featureGate.test.ts b/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.featureGate.test.ts
new file mode 100644
index 00000000000..0db9b89048a
--- /dev/null
+++ b/apps/server/src/services/aiAgent/pipeline/__tests__/toolDiscovery.featureGate.test.ts
@@ -0,0 +1,257 @@
+import { DashboardIdentifier } from '@lobechat/builtin-tool-dashboard';
+import type * as ModelBankModule from 'model-bank';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { AiAgentService } from '../../index';
+
+// Feature-flagged builtin tools must leave a server run's tool pool while
+// their flag is off for the user. Same harness as the share-gate suite.
+const {
+ mockCreateOperation,
+ mockCreateServerAgentToolsEngine,
+ mockFindByIds,
+ mockGetAgentConfig,
+ mockGetUserSettings,
+ mockMessageCreate,
+ mockResolveByIdentifiers,
+ mockScheduleStaleConnectorToolsRefresh,
+} = vi.hoisted(() => ({
+ mockCreateOperation: vi.fn(),
+ mockCreateServerAgentToolsEngine: vi.fn().mockReturnValue({
+ generateToolsDetailed: vi.fn().mockReturnValue({ enabledToolIds: [], tools: [] }),
+ getEnabledPluginManifests: vi.fn().mockReturnValue(new Map()),
+ }),
+ mockFindByIds: vi.fn(),
+ mockGetAgentConfig: vi.fn(),
+ mockGetUserSettings: vi.fn(),
+ mockMessageCreate: vi.fn(),
+ // Returns `[]` so `connectorsMcp` stays empty — we only care about the
+ // identifier list the share-gate filter allowed through to this call.
+ mockResolveByIdentifiers: vi.fn().mockResolvedValue([]),
+ mockScheduleStaleConnectorToolsRefresh: vi.fn(),
+}));
+
+vi.mock('@/database/models/file', () => ({
+ FileModel: vi.fn().mockImplementation(function () {
+ return {
+ findByIds: mockFindByIds,
+ };
+ }),
+}));
+
+vi.mock('@/libs/trusted-client', () => ({
+ generateTrustedClientToken: vi.fn().mockReturnValue(undefined),
+ getTrustedClientTokenForSession: vi.fn().mockResolvedValue(undefined),
+ isTrustedClientEnabled: vi.fn().mockReturnValue(false),
+}));
+
+vi.mock('@/database/models/message', () => ({
+ MessageModel: vi.fn().mockImplementation(function () {
+ return {
+ create: mockMessageCreate,
+ getLatestNonToolMessageId: vi.fn().mockResolvedValue(undefined),
+ getLatestSpineMessageId: vi.fn().mockResolvedValue(undefined),
+ query: vi.fn().mockResolvedValue([]),
+ update: vi.fn().mockResolvedValue({}),
+ };
+ }),
+}));
+
+vi.mock('@/database/models/agent', () => ({
+ AgentModel: vi.fn().mockImplementation(function () {
+ return {
+ getAgentConfig: vi.fn(),
+ queryAgents: vi.fn().mockResolvedValue([]),
+ };
+ }),
+}));
+
+vi.mock('@/server/services/agent', () => ({
+ AgentService: vi.fn().mockImplementation(function () {
+ return {
+ getAgentConfig: mockGetAgentConfig,
+ };
+ }),
+}));
+
+vi.mock('@/database/models/plugin', () => ({
+ PluginModel: vi.fn().mockImplementation(function () {
+ return {
+ query: vi.fn().mockResolvedValue([]),
+ };
+ }),
+}));
+
+vi.mock('@/database/models/connector', () => ({
+ ConnectorModel: vi.fn().mockImplementation(function () {
+ return {
+ queryByIdentifiers: vi.fn().mockResolvedValue([]),
+ resolveByIdentifiers: mockResolveByIdentifiers,
+ };
+ }),
+}));
+
+vi.mock('@/database/models/connectorTool', () => ({
+ ConnectorToolModel: vi.fn().mockImplementation(function () {
+ return {
+ queryAllByConnectorIds: vi.fn().mockResolvedValue([]),
+ queryByConnector: vi.fn().mockResolvedValue([]),
+ queryByConnectorIds: vi.fn().mockResolvedValue([]),
+ };
+ }),
+}));
+
+vi.mock('@/database/models/topic', () => ({
+ TopicModel: vi.fn().mockImplementation(function () {
+ return {
+ create: vi.fn().mockResolvedValue({ id: 'topic-1' }),
+ findById: vi.fn().mockResolvedValue(null),
+ releaseTaskCallbackReservation: vi.fn().mockResolvedValue(undefined),
+ tryReserveTaskCallback: vi.fn().mockResolvedValue(true),
+ };
+ }),
+}));
+
+vi.mock('@/database/models/thread', () => ({
+ ThreadModel: vi.fn().mockImplementation(function () {
+ return {
+ create: vi.fn(),
+ findById: vi.fn(),
+ update: vi.fn(),
+ };
+ }),
+}));
+
+vi.mock('@/database/models/user', () => ({
+ UserModel: vi.fn().mockImplementation(function () {
+ return {
+ getUserPreference: vi.fn().mockResolvedValue({}),
+ getUserSettings: () => mockGetUserSettings(),
+ };
+ }),
+}));
+
+vi.mock('@/server/services/agentRuntime', () => ({
+ AgentRuntimeService: vi.fn().mockImplementation(function () {
+ return {
+ createOperation: mockCreateOperation,
+ };
+ }),
+}));
+
+vi.mock('@/server/services/market', () => ({
+ MarketService: vi.fn().mockImplementation(function () {
+ return {
+ getLobehubSkillManifests: vi.fn().mockResolvedValue([]),
+ };
+ }),
+}));
+
+vi.mock('@/server/services/composio', () => ({
+ ComposioService: vi.fn().mockImplementation(function () {
+ return {
+ getComposioManifests: vi.fn().mockResolvedValue([]),
+ };
+ }),
+}));
+
+vi.mock('@/server/services/file', () => ({
+ FileService: vi.fn().mockImplementation(function () {
+ return {
+ uploadFromUrl: vi.fn(),
+ };
+ }),
+}));
+
+const dashboardFlag = vi.hoisted(() => ({ value: false as boolean | string[] }));
+vi.mock('@/server/featureFlags', async () => {
+ const { mapFeatureFlagsEnvToState } = await import('@/config/featureFlags');
+ return {
+ getServerFeatureFlagsStateFromRuntimeConfig: async (userId?: string) =>
+ mapFeatureFlagsEnvToState({ dashboard: dashboardFlag.value }, userId),
+ };
+});
+
+vi.mock('@/server/modules/Mecha', () => ({
+ createServerAgentToolsEngine: mockCreateServerAgentToolsEngine,
+ serverMessagesEngine: vi.fn().mockResolvedValue([{ content: 'test', role: 'user' }]),
+}));
+
+vi.mock('@/server/services/deviceGateway', () => ({
+ deviceGateway: {
+ isConfigured: false,
+ queryDeviceList: vi.fn().mockResolvedValue([]),
+ },
+}));
+
+vi.mock('@/server/modules/ModelRuntime', () => ({
+ initModelRuntimeFromDB: vi.fn(),
+}));
+
+vi.mock('@/server/services/connector/refresh', () => ({
+ buildLastSyncedAtMap: vi.fn().mockReturnValue(new Map()),
+ scheduleStaleConnectorToolsRefresh: mockScheduleStaleConnectorToolsRefresh,
+}));
+
+// The share path's atomic cap reservations open real DB transactions — stub
+// them so this test can drive execAgent with a bare mock db.
+vi.mock('../../shareVisitorAbuseGuards', () => ({
+ reserveShareVisitorTopic: vi.fn().mockResolvedValue({ id: 'topic-1' }),
+ reserveShareVisitorTurn: vi.fn().mockResolvedValue({ id: 'msg-1' }),
+}));
+
+vi.mock('model-bank', async (importOriginal) => {
+ const actual = await importOriginal<typeof ModelBankModule>();
+ return {
+ ...actual,
+ LOBE_DEFAULT_MODEL_LIST: [
+ {
+ abilities: { functionCall: true, video: false, vision: true },
+ id: 'gpt-4',
+ providerId: 'openai',
+ },
+ ],
+ };
+});
+
+describe('discoverTools - feature-flagged builtin tools', () => {
+ let service: AiAgentService;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mockMessageCreate.mockResolvedValue({ id: 'msg-1' });
+ mockCreateOperation.mockResolvedValue({
+ autoStarted: true,
+ messageId: 'queue-msg-1',
+ operationId: 'op-123',
+ success: true,
+ });
+ mockGetUserSettings.mockResolvedValue({ general: { timezone: 'UTC' } });
+ mockFindByIds.mockResolvedValue([]);
+ mockGetAgentConfig.mockResolvedValue({
+ chatConfig: {},
+ id: 'agent-1',
+ model: 'gpt-4',
+ // Even a pinned lobe-dashboard must not be offered while the flag is off.
+ plugins: [DashboardIdentifier],
+ provider: 'openai',
+ systemRole: '',
+ });
+ service = new AiAgentService({} as any, 'user-1');
+ });
+
+ const disabledIds = () =>
+ mockCreateServerAgentToolsEngine.mock.calls[0][1].disabledPluginIds as string[];
+
+ it('drops lobe-dashboard from the run while the dashboard flag is off', async () => {
+ dashboardFlag.value = false;
+ await service.execAgent({ agentId: 'agent-1', prompt: 'Hello' });
+ expect(disabledIds()).toContain(DashboardIdentifier);
+ });
+
+ it('keeps lobe-dashboard available for a user the flag enables', async () => {
+ dashboardFlag.value = ['user-1'];
+ await service.execAgent({ agentId: 'agent-1', prompt: 'Hello' });
+ expect(disabledIds()).not.toContain(DashboardIdentifier);
+ });
+});
diff --git a/apps/server/src/services/aiAgent/pipeline/toolDiscovery.ts b/apps/server/src/services/aiAgent/pipeline/toolDiscovery.ts
index a1f20e5c619..3b38da75196 100644
--- a/apps/server/src/services/aiAgent/pipeline/toolDiscovery.ts
+++ b/apps/server/src/services/aiAgent/pipeline/toolDiscovery.ts
@@ -9,6 +9,7 @@ import {
shouldExposeSelfFeedbackIntentTool,
} from '@lobechat/builtin-tool-self-iteration';
import { manualModeExcludeToolIds } from '@lobechat/builtin-tools';
+import { getFeatureDisabledToolIds } from '@lobechat/builtin-tools/featureGates';
import type {
AgentGroupConfig,
LobeToolManifest,
@@ -61,6 +62,7 @@ import {
} from '@/helpers/executionTarget';
import { buildConnectorManifests } from '@/libs/mcp/buildConnectorManifests';
import { patchManifestWithPermissions } from '@/libs/mcp/connectorPermissionCheck';
+import { getServerFeatureFlagsStateFromRuntimeConfig } from '@/server/featureFlags';
import { resolveModelMediaCapabilities } from '@/server/modules/AgentRuntime/resolveModelMediaCapabilities';
import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';
import type { ServerAgentToolsContext } from '@/server/modules/Mecha';
@@ -282,7 +284,7 @@ export const discoverTools = async (
disableLocalSystem,
disableSelfFeedbackIntentTool,
disableTools,
- disabledPluginIds,
+ disabledPluginIds: requestedDisabledPluginIds,
discordContext,
exclusivePluginIds,
externalFileTypes: rawExternalFileTypes,
@@ -298,6 +300,15 @@ export const discoverTools = async (
throwIfExecutionAborted,
topicBoundDeviceId,
} = input;
+ // Feature-flagged builtin tools (e.g. lobe-dashboard) leave the pool while
+ // their flag is off for this user; a flag read failure keeps them out.
+ const featureFlags = await getServerFeatureFlagsStateFromRuntimeConfig(deps.userId).catch(
+ () => undefined,
+ );
+ const disabledPluginIds = [
+ ...requestedDisabledPluginIds,
+ ...getFeatureDisabledToolIds(featureFlags),
+ ];
let tools: any[] | undefined;
/** Started once the tool set is known; awaited at the return. */
diff --git a/apps/server/src/services/queue/impls/qstash.ts b/apps/server/src/services/queue/impls/qstash.ts
index 53c55ff557c..484dae1fe26 100644
--- a/apps/server/src/services/queue/impls/qstash.ts
+++ b/apps/server/src/services/queue/impls/qstash.ts
@@ -1,22 +1,13 @@
-import { createHash } from 'node:crypto';
-
import debug from 'debug';
import { OtelQstashClient } from '@/libs/qstash';
+import { toQStashDeduplicationId } from '@/libs/qstash/deduplicationId';
import { type HealthCheckResult, type QueueMessage, type QueueStats } from '../types';
import { type QueueServiceImpl } from './type';
const log = debug('lobe-server:service:queue:qstash');
-/**
- * Keep the logical execution key intact in durable state and local queues, but
- * encode it at the provider boundary. QStash rejects characters such as `:`;
- * a SHA-256 hex digest is deterministic, alphanumeric, and exactly 64 chars.
- */
-const toQStashDeduplicationId = (logicalId: string): string =>
- createHash('sha256').update(logicalId).digest('hex');
-
/**
* QStash's `delay` option is second-granularity — the `Duration` string form
* (`10s`, `1m`, `2h`, `1d`) has no millisecond unit, and a bare number is
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/dashboard.ts b/apps/server/src/services/toolExecution/serverRuntimes/dashboard.ts
new file mode 100644
index 00000000000..2803112cdeb
--- /dev/null
+++ b/apps/server/src/services/toolExecution/serverRuntimes/dashboard.ts
@@ -0,0 +1,41 @@
+import { DashboardIdentifier } from '@lobechat/builtin-tool-dashboard';
+import { DashboardExecutionRuntime } from '@lobechat/builtin-tool-dashboard/executionRuntime';
+
+import {
+ createDashboardToolService,
+ resolveTopicProjectId,
+} from '@/server/services/widget/agentTool';
+import { isDashboardEnabled } from '@/server/services/widget/featureGate';
+
+import { resolveContentWorkspaceId } from './resolveWorkspaceScope';
+import { type ServerRuntimeRegistration } from './types';
+
+export const dashboardRuntime: ServerRuntimeRegistration = {
+ factory: async (context) => {
+ if (!context.userId || !context.serverDB) {
+ throw new Error('userId and serverDB are required for Dashboard tool execution');
+ }
+ // The tool is never offered while the flag is off; refuse a stray call too.
+ if (!(await isDashboardEnabled(context.userId))) {
+ throw new Error('Dashboards are not enabled for this account');
+ }
+ const db = context.serverDB;
+ const [workspaceId, projectId] = await Promise.all([
+ resolveContentWorkspaceId(context),
+ resolveTopicProjectId(db, context.topicId),
+ ]);
+
+ return new DashboardExecutionRuntime(
+ createDashboardToolService(db, {
+ agentId: context.agentId,
+ messageId: context.assistantMessageId,
+ operationId: context.operationId,
+ projectId,
+ topicId: context.topicId,
+ userId: context.userId,
+ workspaceId,
+ }),
+ );
+ },
+ identifier: DashboardIdentifier,
+};
diff --git a/apps/server/src/services/toolExecution/serverRuntimes/index.ts b/apps/server/src/services/toolExecution/serverRuntimes/index.ts
index 52543754f2e..75dbe9809c4 100644
--- a/apps/server/src/services/toolExecution/serverRuntimes/index.ts
+++ b/apps/server/src/services/toolExecution/serverRuntimes/index.ts
@@ -24,6 +24,7 @@ import { browserRuntime } from './browser';
import { calculatorRuntime } from './calculator';
import { cloudSandboxRuntime } from './cloudSandbox';
import { credsRuntime } from './creds';
+import { dashboardRuntime } from './dashboard';
import { goalRuntime } from './goal';
import { goalReportRuntime } from './goalReport';
import { goalSupervisorRuntime } from './goalSupervisor';
@@ -90,6 +91,7 @@ registerRuntimes([
topicReferenceRuntime,
userInteractionRuntime,
credsRuntime,
+ dashboardRuntime,
groupAgentBuilderRuntime,
groupManagementRuntime,
goalRuntime,
diff --git a/apps/server/src/services/widget/__tests__/agentTool.test.ts b/apps/server/src/services/widget/__tests__/agentTool.test.ts
new file mode 100644
index 00000000000..aa691de6f93
--- /dev/null
+++ b/apps/server/src/services/widget/__tests__/agentTool.test.ts
@@ -0,0 +1,645 @@
+// @vitest-environment node
+import { DashboardExecutionRuntime } from '@lobechat/builtin-tool-dashboard/executionRuntime';
+import type { LobeChatDatabase } from '@lobechat/database';
+import {
+ agents,
+ projects,
+ topics,
+ users,
+ widgets,
+ widgetVersions,
+ workspaceMembers,
+ workspaces,
+} from '@lobechat/database/schemas';
+import { getTestDB } from '@lobechat/database/test-utils';
+import { eq, inArray } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { DashboardModel } from '@/database/models/dashboard';
+import { dashboardRuntime } from '@/server/services/toolExecution/serverRuntimes/dashboard';
+
+import { createDashboardToolService, resolveClientTopic } from '../agentTool';
+
+const dashboardFlag = vi.hoisted(() => ({ value: true }));
+vi.mock('@/server/featureFlags', async () => {
+ const { mapFeatureFlagsEnvToState } = await import('@/config/featureFlags');
+ return {
+ getServerFeatureFlagsStateFromRuntimeConfig: async (userId?: string) =>
+ mapFeatureFlagsEnvToState({ dashboard: dashboardFlag.value }, userId),
+ };
+});
+
+const runSandbox = vi.fn();
+vi.mock('@/server/services/widget/sandbox', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ createWidgetSandboxRunner: () => ({ run: runSandbox }),
+}));
+
+const printed = (output: unknown) => ({
+ durationMs: 9,
+ exitCode: 0,
+ stderr: 'fetched 1 page',
+ stdout: JSON.stringify(output),
+ timedOut: false,
+});
+
+const statDraft = {
+ outputType: 'stat' as const,
+ runtime: 'node' as const,
+ script: `console.log(JSON.stringify({ type: 'stat', value: 7 }))`,
+};
+
+const userId = 'dashboard-tool-user';
+const agentId = 'dashboard-tool-agent';
+const projectId = 'dashboard-tool-project';
+const projectTopicId = 'dashboard-tool-project-topic';
+const plainTopicId = 'dashboard-tool-topic';
+
+let db: LobeChatDatabase;
+
+beforeEach(async () => {
+ runSandbox.mockReset();
+ db = await getTestDB();
+ await db.delete(users).where(eq(users.id, userId));
+ await db.insert(users).values({ id: userId });
+ await db.insert(agents).values([
+ { id: agentId, userId },
+ { id: `${projectId}-coordinator`, userId },
+ ]);
+ await db.insert(projects).values({
+ coordinatorAgentId: `${projectId}-coordinator`,
+ id: projectId,
+ identifier: 'DTP',
+ name: 'Dashboard tool project',
+ userId,
+ });
+ await db.insert(topics).values([
+ { agentId, id: projectTopicId, projectId, userId },
+ { agentId, id: plainTopicId, userId },
+ ]);
+});
+
+const teammateId = 'dashboard-tool-teammate';
+
+afterEach(async () => {
+ vi.restoreAllMocks();
+ await db.delete(users).where(inArray(users.id, [userId, teammateId]));
+});
+
+const scope = {
+ agentId,
+ messageId: 'msg_assistant_1',
+ operationId: 'op_1',
+ topicId: plainTopicId,
+ userId,
+};
+
+describe('createDashboardToolService', () => {
+ it('stamps the agent scope on the widget and the conversation on its draft', async () => {
+ const service = createDashboardToolService(db, scope);
+ const { version, widgetId } = await service.createWidgetDraft({
+ content: statDraft,
+ description: 'Always 7',
+ title: 'Seven',
+ });
+
+ const [widget] = await db.select().from(widgets).where(eq(widgets.id, widgetId));
+ expect(widget).toMatchObject({
+ agentId,
+ description: 'Always 7',
+ draftVersionId: version.id,
+ projectId: null,
+ workspaceId: null,
+ });
+ const [row] = await db.select().from(widgetVersions).where(eq(widgetVersions.id, version.id));
+ expect(row).toMatchObject({
+ sourceAgentId: agentId,
+ sourceMessageId: 'msg_assistant_1',
+ sourceOperationId: 'op_1',
+ sourceTopicId: plainTopicId,
+ sourceType: 'agent',
+ status: 'draft',
+ });
+ });
+
+ it('rejects an invalid draft without leaving an empty widget behind', async () => {
+ const service = createDashboardToolService(db, scope);
+
+ await expect(
+ service.createWidgetDraft({
+ content: { ...statDraft, manifest: { env: [{ name: 'NOT A NAME' }] } },
+ description: '',
+ title: 'Broken',
+ }),
+ ).rejects.toThrow(/Invalid widget draft/);
+ expect(await db.select().from(widgets)).toHaveLength(0);
+ });
+
+ it('rejects widget metadata beyond the router limits, on create and update', async () => {
+ const service = createDashboardToolService(db, scope);
+
+ // Create path: a title longer than the router's 200 fails before any write.
+ await expect(
+ service.createWidgetDraft({
+ content: statDraft,
+ description: '',
+ title: 'x'.repeat(201),
+ }),
+ ).rejects.toThrow(/Invalid widget metadata/);
+ expect(await db.select().from(widgets)).toHaveLength(0);
+
+ const { widgetId } = await service.createWidgetDraft({
+ content: statDraft,
+ description: '',
+ title: 'Seven',
+ });
+
+ // Update path: over-long descriptions and empty titles are refused too,
+ // and the stored metadata is untouched.
+ await expect(service.updateWidget(widgetId, { description: 'y'.repeat(2001) })).rejects.toThrow(
+ /Invalid widget metadata/,
+ );
+ await expect(service.updateWidget(widgetId, { title: '' })).rejects.toThrow(
+ /Invalid widget metadata/,
+ );
+ const [row] = await db.select().from(widgets).where(eq(widgets.id, widgetId));
+ expect(row).toMatchObject({ description: '', title: 'Seven' });
+ });
+
+ it('refuses to publish an untried draft, then publishes and runs it once after a dry run', async () => {
+ runSandbox.mockResolvedValue(printed({ type: 'stat', value: 7 }));
+ const service = createDashboardToolService(db, scope);
+ const { version, widgetId } = await service.createWidgetDraft({
+ content: statDraft,
+ description: '',
+ title: 'Seven',
+ });
+
+ await expect(service.publish(widgetId, version.id)).rejects.toThrow(/dry-run it/);
+
+ const run = await service.dryRun(widgetId);
+ expect(run).toMatchObject({
+ output: { type: 'stat', value: 7 },
+ status: 'succeeded',
+ stderr: 'fetched 1 page',
+ trigger: 'preview',
+ versionId: version.id,
+ });
+
+ const published = await service.publish(widgetId, version.id);
+ expect(published).toMatchObject({
+ firstRunStatus: 'succeeded',
+ version: { status: 'published' },
+ });
+ const [widget] = await db.select().from(widgets).where(eq(widgets.id, widgetId));
+ expect(widget.publishedVersionId).toBe(version.id);
+ // The first live run filled the card.
+ expect(widget.latestOutput).toEqual({ type: 'stat', value: 7 });
+ });
+
+ it('saves follow-up drafts on top of the previous one', async () => {
+ const service = createDashboardToolService(db, scope);
+ const { version, widgetId } = await service.createWidgetDraft({
+ content: statDraft,
+ description: '',
+ title: 'Seven',
+ });
+
+ const next = await service.saveDraft(widgetId, {
+ ...statDraft,
+ changeNote: 'print eight',
+ parentVersionId: version.id,
+ script: `console.log(JSON.stringify({ type: 'stat', value: 8 }))`,
+ });
+ expect(next).toMatchObject({ changeNote: 'print eight', status: 'draft', version: 2 });
+ expect((await service.getWidget(widgetId))?.draftVersion?.id).toBe(next.id);
+ });
+
+ it('lists home boards with their widgets and only this level’s widgets', async () => {
+ const service = createDashboardToolService(db, scope);
+ const { widgetId } = await service.createWidgetDraft({
+ content: statDraft,
+ description: '',
+ title: 'Mine',
+ });
+ // Same agent, but inside a project: a different level.
+ await createDashboardToolService(db, { ...scope, projectId }).createWidgetDraft({
+ content: statDraft,
+ description: '',
+ title: 'Project one',
+ });
+
+ const board = await service.createDashboardWithWidget('Ops', widgetId);
+ expect(board).toMatchObject({ projectId: null, title: 'Ops' });
+ expect(await service.addToDashboard(board.id, widgetId)).toEqual({
+ projectId: null,
+ title: 'Ops',
+ });
+ // Boards of an agent / project level are not home boards.
+ await new DashboardModel(db, userId).create({ agentId, title: 'Agent board' });
+
+ expect(await service.listDashboards()).toEqual([
+ { id: board.id, projectId: null, title: 'Ops', widgets: [{ id: widgetId, title: 'Mine' }] },
+ ]);
+ expect((await service.listWidgets()).map((widget) => widget.title)).toEqual(['Mine']);
+ });
+
+ it('refuses widgets of another agent or project, even the same user’s', async () => {
+ runSandbox.mockResolvedValue(printed({ type: 'stat', value: 7 }));
+ const service = createDashboardToolService(db, scope);
+ const runtime = new DashboardExecutionRuntime(service);
+ const board = await service.createDashboardWithWidget(
+ 'Ops',
+ (await service.createWidgetDraft({ content: statDraft, description: '', title: 'Mine' }))
+ .widgetId,
+ );
+
+ const otherAgent = await createDashboardToolService(db, {
+ ...scope,
+ agentId: `${projectId}-coordinator`,
+ }).createWidgetDraft({ content: statDraft, description: '', title: 'Other agent' });
+ // Same agent, but authored in a project topic.
+ const otherProject = await createDashboardToolService(db, {
+ ...scope,
+ projectId,
+ topicId: projectTopicId,
+ }).createWidgetDraft({ content: statDraft, description: '', title: 'Project one' });
+
+ for (const { version, widgetId } of [otherAgent, otherProject]) {
+ const results = await Promise.all([
+ runtime.updateWidgetDraft({ script: 'console.log(1)', widgetId }),
+ runtime.updateWidgetDraft({ title: 'Renamed', widgetId }),
+ runtime.dryRunWidget({ versionId: version.id, widgetId }),
+ runtime.requestPublish({ versionId: version.id, widgetId }),
+ runtime.addWidgetToDashboard({ dashboardId: board.id, widgetId }),
+ runtime.addWidgetToDashboard({ newDashboardTitle: 'Leaked board', widgetId }),
+ runtime.getWidgetRuns({ widgetId }),
+ ]);
+ for (const result of results) {
+ expect(result.success).toBe(false);
+ expect(result.content).toMatch(/not found/i);
+ }
+ await expect(service.saveDraft(widgetId, statDraft)).rejects.toThrow(/not found/i);
+ expect(await service.getWidget(widgetId)).toBeUndefined();
+
+ const [row] = await db.select().from(widgets).where(eq(widgets.id, widgetId));
+ expect(row).toMatchObject({ draftVersionId: version.id, publishedVersionId: null });
+ expect(row.title).not.toBe('Renamed');
+ }
+ expect(runSandbox).not.toHaveBeenCalled();
+ // Refusing a new-board placement creates no board either.
+ expect((await new DashboardModel(db, userId).list({})).map(({ title }) => title)).toEqual([
+ 'Ops',
+ ]);
+ expect((await service.listDashboards())[0].widgets.map(({ title }) => title)).toEqual(['Mine']);
+ });
+
+ it('loads the widgets of every listed board in one batch', async () => {
+ const service = createDashboardToolService(db, {
+ ...scope,
+ projectId,
+ topicId: projectTopicId,
+ });
+ const create = (title: string) =>
+ service.createWidgetDraft({ content: statDraft, description: '', title });
+ const [a, b, c] = [await create('A'), await create('B'), await create('C')];
+ const projectBoard = await service.createDashboardWithWidget('Project', a.widgetId);
+ await service.addToDashboard(projectBoard.id, b.widgetId);
+ const home = await new DashboardModel(db, userId).create({ title: 'Home' });
+ const empty = await new DashboardModel(db, userId).create({ title: 'Empty' });
+ const homeWidget = await createDashboardToolService(db, scope).createWidgetDraft({
+ content: statDraft,
+ description: '',
+ title: 'Home widget',
+ });
+ await new DashboardModel(db, userId).addItem(home.id, homeWidget.widgetId);
+ await new DashboardModel(db, userId).addItem(home.id, c.widgetId);
+
+ const perBoard = vi.spyOn(DashboardModel.prototype, 'listItems');
+ const batch = vi.spyOn(DashboardModel.prototype, 'listItemsForDashboards');
+
+ expect(await service.listDashboards()).toEqual([
+ {
+ id: projectBoard.id,
+ projectId,
+ title: 'Project',
+ widgets: [
+ { id: a.widgetId, title: 'A' },
+ { id: b.widgetId, title: 'B' },
+ ],
+ },
+ {
+ id: home.id,
+ projectId: null,
+ title: 'Home',
+ widgets: [
+ { id: homeWidget.widgetId, title: 'Home widget' },
+ { id: c.widgetId, title: 'C' },
+ ],
+ },
+ { id: empty.id, projectId: null, title: 'Empty', widgets: [] },
+ ]);
+ expect(perBoard).not.toHaveBeenCalled();
+ expect(batch).toHaveBeenCalledTimes(1);
+ });
+
+ it('refuses placement on boards outside the conversation’s project or level', async () => {
+ const service = createDashboardToolService(db, {
+ ...scope,
+ projectId,
+ topicId: projectTopicId,
+ });
+ const { widgetId } = await service.createWidgetDraft({
+ content: statDraft,
+ description: '',
+ title: 'Project metric',
+ });
+
+ // Another project's board: readable and creator-owned, but this
+ // conversation was never offered it.
+ const otherProjectId = 'dashboard-tool-other-project';
+ await db.insert(agents).values({ id: `${otherProjectId}-coordinator`, userId });
+ await db.insert(projects).values({
+ coordinatorAgentId: `${otherProjectId}-coordinator`,
+ id: otherProjectId,
+ identifier: 'DTO',
+ name: 'Other project',
+ userId,
+ });
+ const otherBoard = await new DashboardModel(db, userId).create({
+ projectId: otherProjectId,
+ title: 'Other project board',
+ });
+ // An agent-level board is not a home board either.
+ const agentBoard = await new DashboardModel(db, userId).create({
+ agentId,
+ title: 'Agent board',
+ });
+
+ await expect(service.addToDashboard(otherBoard.id, widgetId)).rejects.toThrow(/not found/i);
+ await expect(service.addToDashboard(agentBoard.id, widgetId)).rejects.toThrow(/not found/i);
+ expect(await new DashboardModel(db, userId).listItems(otherBoard.id)).toEqual([]);
+ expect(await new DashboardModel(db, userId).listItems(agentBoard.id)).toEqual([]);
+
+ // Its own project's board and home boards still take the placement.
+ const ownBoard = await service.createDashboardWithWidget('Own project board', widgetId);
+ const homeBoard = await new DashboardModel(db, userId).create({ title: 'Home board' });
+ await expect(service.addToDashboard(ownBoard.id, widgetId)).resolves.toEqual({
+ projectId,
+ title: 'Own project board',
+ });
+ await expect(service.addToDashboard(homeBoard.id, widgetId)).resolves.toEqual({
+ projectId: null,
+ title: 'Home board',
+ });
+
+ // A home conversation is the mirror image: project boards are out of reach.
+ const homeService = createDashboardToolService(db, scope);
+ const homeWidget = await homeService.createWidgetDraft({
+ content: statDraft,
+ description: '',
+ title: 'Home metric',
+ });
+ await expect(homeService.addToDashboard(ownBoard.id, homeWidget.widgetId)).rejects.toThrow(
+ /not found/i,
+ );
+ expect(await new DashboardModel(db, userId).listItems(ownBoard.id)).toHaveLength(1);
+ });
+
+ it('creates no board when the widget cannot be placed on it', async () => {
+ const service = createDashboardToolService(db, scope);
+ const runtime = new DashboardExecutionRuntime(service);
+
+ const result = await runtime.addWidgetToDashboard({
+ newDashboardTitle: 'Ops',
+ widgetId: '00000000-0000-4000-8000-000000000000',
+ });
+
+ expect(result.success).toBe(false);
+ expect(await new DashboardModel(db, userId).list({})).toEqual([]);
+ });
+
+ it('creates boards on the project in a project topic and lists them before home boards', async () => {
+ const home = await new DashboardModel(db, userId).create({ title: 'Home' });
+ const service = createDashboardToolService(db, {
+ ...scope,
+ projectId,
+ topicId: projectTopicId,
+ });
+ const { widgetId } = await service.createWidgetDraft({
+ content: statDraft,
+ description: '',
+ title: 'Project metric',
+ });
+
+ const board = await service.createDashboardWithWidget('Project board', widgetId);
+ expect(board).toMatchObject({ projectId, title: 'Project board' });
+ // A board another agent of the project owns is still the project's.
+ const agentBoard = await new DashboardModel(db, userId).create({
+ agentId,
+ projectId,
+ title: 'Agent board in project',
+ });
+
+ expect(await new DashboardModel(db, userId).findById(board.id)).toMatchObject({
+ agentId: null,
+ projectId,
+ });
+ expect(
+ (await service.listDashboards()).map(({ id, projectId: level }) => ({ id, level })),
+ ).toEqual([
+ { id: board.id, level: projectId },
+ { id: agentBoard.id, level: projectId },
+ { id: home.id, level: null },
+ ]);
+ });
+});
+
+describe('dashboardRuntime', () => {
+ it('attaches widgets built in a project conversation to that project', async () => {
+ const runtime = await dashboardRuntime.factory({
+ agentId,
+ serverDB: db,
+ toolManifestMap: {},
+ topicId: projectTopicId,
+ userId,
+ });
+
+ const result = await runtime.createWidgetDraft({
+ ...statDraft,
+ description: 'Project metric',
+ title: 'In project',
+ });
+
+ expect(result.success).toBe(true);
+ const [widget] = await db.select().from(widgets).where(eq(widgets.id, result.state.widgetId));
+ expect(widget).toMatchObject({ agentId, projectId });
+ });
+
+ it('refuses to run the tool in-process while the `dashboard` flag is off', async () => {
+ dashboardFlag.value = false;
+ try {
+ await expect(
+ dashboardRuntime.factory({ serverDB: db, toolManifestMap: {}, userId }),
+ ).rejects.toThrow('Dashboards are not enabled');
+ } finally {
+ dashboardFlag.value = true;
+ }
+ });
+});
+
+describe('resolveClientTopic', () => {
+ it('resolves only the caller’s own topics, with their project', async () => {
+ expect(await resolveClientTopic(db, projectTopicId, userId)).toEqual({
+ projectId,
+ topicId: projectTopicId,
+ });
+ expect(await resolveClientTopic(db, plainTopicId, userId)).toEqual({
+ projectId: undefined,
+ topicId: plainTopicId,
+ });
+ expect(await resolveClientTopic(db, projectTopicId, 'someone-else')).toEqual({});
+ expect(await resolveClientTopic(db, undefined, userId)).toEqual({});
+ });
+});
+
+describe('resolveClientTopic in a workspace', () => {
+ const workspaceId = 'dashboard-tool-workspace';
+ const wsAgentId = 'dashboard-tool-ws-agent';
+ const wsProjectId = 'dashboard-tool-ws-project';
+ const teammateTopicId = 'dashboard-tool-teammate-topic';
+
+ beforeEach(async () => {
+ await db.delete(users).where(eq(users.id, teammateId));
+ await db.insert(users).values({ id: teammateId });
+ await db
+ .insert(workspaces)
+ .values({ id: workspaceId, name: 'Team', primaryOwnerId: teammateId, slug: workspaceId });
+ await db.insert(workspaceMembers).values([
+ { role: 'owner', userId: teammateId, workspaceId },
+ { role: 'member', userId, workspaceId },
+ ]);
+ await db.insert(agents).values([
+ { id: wsAgentId, userId, workspaceId },
+ { id: `${wsProjectId}-coordinator`, userId: teammateId, workspaceId },
+ ]);
+ await db.insert(projects).values({
+ coordinatorAgentId: `${wsProjectId}-coordinator`,
+ id: wsProjectId,
+ identifier: 'WSP',
+ name: 'Team project',
+ userId: teammateId,
+ workspaceId,
+ });
+ // The teammate started the project topic; the member keeps working in it.
+ await db
+ .insert(topics)
+ .values({ id: teammateTopicId, projectId: wsProjectId, userId: teammateId, workspaceId });
+ });
+
+ it('builds under the project of a teammate’s workspace topic', async () => {
+ const topic = await resolveClientTopic(db, teammateTopicId, userId, workspaceId);
+ expect(topic).toEqual({ projectId: wsProjectId, topicId: teammateTopicId });
+
+ const service = createDashboardToolService(db, {
+ ...scope,
+ agentId: wsAgentId,
+ ...topic,
+ workspaceId,
+ });
+ const { widgetId } = await service.createWidgetDraft({
+ content: statDraft,
+ description: '',
+ title: 'Team metric',
+ });
+ const board = await service.createDashboardWithWidget('Team board', widgetId);
+
+ const [widget] = await db.select().from(widgets).where(eq(widgets.id, widgetId));
+ expect(widget).toMatchObject({ projectId: wsProjectId, userId, workspaceId });
+ expect(board).toMatchObject({ projectId: wsProjectId, title: 'Team board' });
+ });
+
+ it('refuses a workspace-level board outside a project and writes nothing', async () => {
+ // A workspace-root conversation: workspace set, no project. Its boards
+ // would live on the workspace home level, which has no UI at all — the
+ // tool must refuse instead of accumulating unreachable boards.
+ const service = createDashboardToolService(db, {
+ ...scope,
+ agentId: wsAgentId,
+ workspaceId,
+ });
+ const { widgetId } = await service.createWidgetDraft({
+ content: statDraft,
+ description: '',
+ title: 'Workspace metric',
+ });
+
+ await expect(service.createDashboardWithWidget('Ops', widgetId)).rejects.toThrow(
+ /inside a project/,
+ );
+ // The agent sees the same refusal, worded for the conversation.
+ const runtime = new DashboardExecutionRuntime(service);
+ const result = await runtime.addWidgetToDashboard({ newDashboardTitle: 'Ops', widgetId });
+ expect(result.success).toBe(false);
+ expect(result.content).toMatch(/inside a project/);
+
+ const model = new DashboardModel(db, userId, workspaceId);
+ expect(await model.list({})).toEqual([]);
+ expect(await model.listByProject(wsProjectId)).toEqual([]);
+ });
+
+ it('lists only boards the caller can place on', async () => {
+ // A workspace-root conversation: nothing is placeable. The home level's
+ // boards are workspace-root boards with no UI inside a workspace, and a
+ // teammate's public board can never take the caller's placement.
+ const homeService = createDashboardToolService(db, {
+ ...scope,
+ agentId: wsAgentId,
+ workspaceId,
+ });
+ const { widgetId } = await homeService.createWidgetDraft({
+ content: statDraft,
+ description: '',
+ title: 'Workspace metric',
+ });
+ await new DashboardModel(db, teammateId, workspaceId).create({ title: 'Teammate board' });
+ const workspaceRoot = await new DashboardModel(db, userId, workspaceId).create({
+ title: 'Workspace root',
+ });
+
+ expect(await homeService.listDashboards()).toEqual([]);
+ await expect(homeService.addToDashboard(workspaceRoot.id, widgetId)).rejects.toThrow(
+ /not found/i,
+ );
+ expect(
+ (await new DashboardModel(db, userId, workspaceId).listItems(workspaceRoot.id)).length,
+ ).toBe(0);
+
+ // A project conversation: the caller's own project boards are offered,
+ // teammates' project boards are not.
+ const projectService = createDashboardToolService(db, {
+ ...scope,
+ agentId: wsAgentId,
+ projectId: wsProjectId,
+ topicId: teammateTopicId,
+ workspaceId,
+ });
+ const ownProject = await new DashboardModel(db, userId, workspaceId).create({
+ projectId: wsProjectId,
+ title: 'Own project board',
+ });
+ await new DashboardModel(db, teammateId, workspaceId).create({
+ projectId: wsProjectId,
+ title: 'Teammate project board',
+ });
+
+ expect(await projectService.listDashboards()).toEqual([
+ { id: ownProject.id, projectId: wsProjectId, title: 'Own project board', widgets: [] },
+ ]);
+ });
+
+ it('does not reach a workspace topic from personal mode', async () => {
+ expect(await resolveClientTopic(db, teammateTopicId, userId)).toEqual({});
+ expect(await resolveClientTopic(db, teammateTopicId, teammateId)).toEqual({});
+ });
+});
diff --git a/apps/server/src/services/widget/__tests__/dryRunAudit.test.ts b/apps/server/src/services/widget/__tests__/dryRunAudit.test.ts
new file mode 100644
index 00000000000..a8cbae95a58
--- /dev/null
+++ b/apps/server/src/services/widget/__tests__/dryRunAudit.test.ts
@@ -0,0 +1,65 @@
+// @vitest-environment node
+import type { LobeChatDatabase } from '@lobechat/database';
+import { users } from '@lobechat/database/schemas';
+import { getTestDB } from '@lobechat/database/test-utils';
+import { inArray } from 'drizzle-orm';
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import { WidgetModel } from '@/database/models/widget';
+
+import { createWidgetDryRunAudit } from '../dryRunAudit';
+
+const userId = 'dry-run-audit-user';
+const otherUserId = 'dry-run-audit-other';
+
+const statDraft = {
+ outputType: 'stat' as const,
+ runtime: 'node' as const,
+ script: `console.log(JSON.stringify({ type: 'stat', value: 1 }))`,
+};
+
+let db: LobeChatDatabase;
+
+beforeEach(async () => {
+ db = await getTestDB();
+ await db.delete(users).where(inArray(users.id, [userId, otherUserId]));
+ await db.insert(users).values([{ id: userId }, { id: otherUserId }]);
+});
+
+afterEach(async () => {
+ await db.delete(users).where(inArray(users.id, [userId, otherUserId]));
+});
+
+const draftOf = async (owner: string, manifest: object | null) => {
+ const model = new WidgetModel(db, owner);
+ const widget = await model.create({ title: 'Stars' });
+ const version = await model.createVersion(widget.id, {
+ ...statDraft,
+ manifest,
+ sourceType: 'user',
+ } as any);
+ return { versionId: version!.id, widgetId: widget.id };
+};
+
+describe('createWidgetDryRunAudit', () => {
+ it('asks before running the named version when it is networked or credentialed', async () => {
+ const audit = createWidgetDryRunAudit(db, userId);
+ const networked = await draftOf(userId, { network: { allow: ['api.github.com'] } });
+ const credentialed = await draftOf(userId, {
+ env: [{ connector: 'github', name: 'GITHUB_TOKEN' }],
+ });
+
+ expect(await audit(networked)).toBe(true);
+ expect(await audit(credentialed)).toBe(true);
+ });
+
+ it('lets a closed draft run unattended', async () => {
+ const audit = createWidgetDryRunAudit(db, userId);
+ expect(await audit(await draftOf(userId, null))).toBe(false);
+ });
+
+ it('fails closed for a version the run user cannot read', async () => {
+ const foreign = await draftOf(otherUserId, null);
+ expect(await createWidgetDryRunAudit(db, userId)(foreign)).toBe(true);
+ });
+});
diff --git a/apps/server/src/services/widget/agentTool.ts b/apps/server/src/services/widget/agentTool.ts
new file mode 100644
index 00000000000..8e83b9fa49e
--- /dev/null
+++ b/apps/server/src/services/widget/agentTool.ts
@@ -0,0 +1,333 @@
+import type {
+ WidgetRunRecord,
+ WidgetVersionContent,
+ WidgetVersionRecord,
+} from '@lobechat/builtin-tool-dashboard';
+import type { DashboardToolService } from '@lobechat/builtin-tool-dashboard/executionRuntime';
+import type { LobeChatDatabase } from '@lobechat/database';
+import { eq } from 'drizzle-orm';
+import { z } from 'zod';
+
+import { DashboardModel } from '@/database/models/dashboard';
+import { TopicModel } from '@/database/models/topic';
+import { WidgetModel } from '@/database/models/widget';
+import type { WidgetRunRow, WidgetVersionRow } from '@/database/schemas';
+import { topics } from '@/database/schemas';
+
+import { WidgetFlowError, WidgetService } from './index';
+import { widgetMetadataPatchSchema, widgetMetadataSchema } from './metadataSchema';
+import { widgetVersionContentSchema } from './versionSchema';
+
+/** Where the conversation that authors the widget lives; stamped on what it creates. */
+export interface DashboardToolScope {
+ agentId?: string;
+ /** Assistant message carrying the tool call — recorded as the version's source. */
+ messageId?: string;
+ operationId?: string;
+ projectId?: string;
+ topicId?: string;
+ userId: string;
+ workspaceId?: string;
+}
+
+const toVersionRecord = (row: WidgetVersionRow): WidgetVersionRecord => ({
+ changeNote: row.changeNote,
+ id: row.id,
+ manifest: row.manifest,
+ outputType: row.outputType,
+ runtime: row.runtime,
+ script: row.script,
+ status: row.status,
+ version: row.version,
+ view: row.view,
+});
+
+const toRunRecord = (row: WidgetRunRow): WidgetRunRecord => ({
+ durationMs: row.durationMs,
+ error: row.error,
+ exitCode: row.exitCode,
+ finishedAt: row.finishedAt,
+ id: row.id,
+ output: row.output,
+ startedAt: row.startedAt,
+ status: row.status,
+ stderr: row.stderr,
+ stdout: row.stdout,
+ trigger: row.trigger,
+ versionId: row.versionId,
+});
+
+/** Same validation as the `dashboard.saveDraft` procedure, with a readable message. */
+const parseContent = (content: WidgetVersionContent & { changeNote?: string | null }) => {
+ const result = widgetVersionContentSchema.safeParse(content);
+ if (!result.success) throw new Error(`Invalid widget draft: ${z.prettifyError(result.error)}`);
+ return result.data;
+};
+
+/**
+ * The widget router's metadata limits (title 1–200, description ≤ 2000),
+ * shared as one schema so model-emitted metadata cannot bypass what the API
+ * would refuse.
+ */
+const parseMetadata = <S extends z.ZodType>(metadata: unknown, schema: S): z.infer<S> => {
+ const result = schema.safeParse(metadata);
+ if (!result.success) throw new Error(`Invalid widget metadata: ${z.prettifyError(result.error)}`);
+ return result.data as z.infer<S>;
+};
+
+/**
+ * The dashboard tool's data access for one conversation. Widgets it creates
+ * belong to the conversation's agent (and project, in a project topic) inside
+ * the run's workspace; drafts record the agent, topic, message and operation
+ * that wrote them. Boards it creates belong to the conversation's project in a
+ * project topic, else to the home level (personal / workspace).
+ */
+export const createDashboardToolService = (
+ db: LobeChatDatabase,
+ scope: DashboardToolScope,
+): DashboardToolService => {
+ const { agentId, projectId, userId, workspaceId } = scope;
+ const dashboards = new DashboardModel(db, userId, workspaceId);
+ const widgets = new WidgetModel(db, userId, workspaceId);
+ const flow = new WidgetService(db, userId, workspaceId);
+
+ /**
+ * A widget this conversation may work on: readable, and living on the exact
+ * level new widgets are created on (same agent and project). A stale or
+ * model-supplied id of another agent's or project's widget is out of reach,
+ * even when the same user owns it.
+ */
+ const findScopedWidget = async (widgetId: string) => {
+ const widget = await widgets.findById(widgetId);
+ if (!widget) return undefined;
+ const inScope =
+ widget.agentId === (agentId ?? null) && widget.projectId === (projectId ?? null);
+ return inScope ? widget : undefined;
+ };
+
+ const requireScopedWidget = async (widgetId: string) => {
+ const widget = await findScopedWidget(widgetId);
+ if (!widget) {
+ throw new WidgetFlowError(
+ 'NOT_FOUND',
+ 'Widget not found in this conversation’s agent and project',
+ );
+ }
+ return widget;
+ };
+
+ const source = {
+ sourceAgentId: agentId ?? null,
+ sourceMessageId: scope.messageId ?? null,
+ sourceOperationId: scope.operationId ?? null,
+ sourceTopicId: scope.topicId ?? null,
+ sourceType: 'agent' as const,
+ };
+
+ return {
+ addToDashboard: async (dashboardId, widgetId) => {
+ await requireScopedWidget(widgetId);
+ const board = await dashboards.findById(dashboardId);
+ // Only what listDashboards offers may take the placement: boards of the
+ // conversation's own project, or home boards in personal mode. A
+ // readable board of another project, of an agent-only level, or of the
+ // workspace root is out of reach even when the caller owns it.
+ const offered =
+ !!board &&
+ (board.projectId === projectId ||
+ (!workspaceId && board.projectId === null && board.agentId === null));
+ const item = offered ? await dashboards.addItem(dashboardId, widgetId) : undefined;
+ if (!board || !item) throw new Error('Dashboard or widget not found');
+ return { projectId: board.projectId, title: board.title };
+ },
+
+ createDashboardWithWidget: async (title, widgetId) => {
+ // Same conversation-scope check as placing on an existing board, before
+ // anything is written: another agent's or project's widget creates no board.
+ await requireScopedWidget(widgetId);
+ // A workspace-level board has no UI at all — the home dashboard routes
+ // are disabled inside a workspace — so creating one would report
+ // success while leaving an unreachable board behind. Boards belong in
+ // the conversation's project (or the home level in personal mode).
+ if (workspaceId && !projectId) {
+ throw new WidgetFlowError(
+ 'FORBIDDEN',
+ 'Workspace-level dashboards are not available yet — create the dashboard inside a project instead',
+ );
+ }
+ // One transaction: a widget that cannot be placed (stale, deleted,
+ // unreadable, another workspace) rolls the new board back with it.
+ return db.transaction(async (tx) => {
+ const scoped = new DashboardModel(tx as unknown as LobeChatDatabase, userId, workspaceId);
+ const board = await scoped.create({ projectId: projectId ?? null, title });
+ const item = await scoped.addItem(board.id, widgetId);
+ if (!item) throw new Error('Widget not found');
+ return { id: board.id, projectId: board.projectId, title: board.title };
+ });
+ },
+
+ createWidgetDraft: async ({ content, description, title }) => {
+ const version = parseContent(content);
+ const metadata = parseMetadata({ description, title }, widgetMetadataSchema);
+ const widget = await widgets.create({
+ agentId: agentId ?? null,
+ description: metadata.description,
+ projectId: projectId ?? null,
+ title: metadata.title,
+ });
+ try {
+ const draft = await flow.saveDraft(widget.id, { ...version, ...source });
+ return { version: toVersionRecord(draft), widgetId: widget.id };
+ } catch (error) {
+ // Never leave an empty widget behind a failed first draft.
+ await widgets.delete(widget.id);
+ throw error;
+ }
+ },
+
+ dryRun: async (widgetId, versionId) => {
+ await requireScopedWidget(widgetId);
+ const run = await flow.dryRun(widgetId, { operationId: scope.operationId, versionId });
+ if (!run) throw new Error('Widget not found');
+ return toRunRecord(run);
+ },
+
+ getRun: async (widgetId, runId) => {
+ await requireScopedWidget(widgetId);
+ const run = await widgets.findRun(widgetId, runId);
+ return run ? toRunRecord(run) : undefined;
+ },
+
+ getWidget: async (widgetId) => {
+ const widget = await findScopedWidget(widgetId);
+ if (!widget) return undefined;
+ const [publishedVersion, draftVersion] = await Promise.all([
+ widget.publishedVersionId ? widgets.findVersion(widgetId, widget.publishedVersionId) : null,
+ widget.draftVersionId ? widgets.findVersion(widgetId, widget.draftVersionId) : null,
+ ]);
+ return {
+ description: widget.description,
+ draftVersion: draftVersion ? toVersionRecord(draftVersion) : null,
+ id: widget.id,
+ publishedVersion: publishedVersion ? toVersionRecord(publishedVersion) : null,
+ schedulePattern: widget.schedulePattern,
+ scheduleTimezone: widget.scheduleTimezone,
+ title: widget.title,
+ };
+ },
+
+ listDashboards: async () => {
+ const [projectBoards, homeBoards] = await Promise.all([
+ projectId ? dashboards.listByProject(projectId) : [],
+ dashboards.list({}),
+ ]);
+ // In a workspace the readable lists include teammates' public boards,
+ // but placing writes through the board's creator (DashboardModel's
+ // manageable rule) — the same creator-only filter the client-side
+ // picker applies, so every listed board is a board the tool can
+ // actually place on. Workspace-root boards are caller-owned too, but
+ // they have no UI while a workspace is active (the home routes are
+ // disabled there), so they are excluded as well.
+ const boards = [...projectBoards, ...homeBoards].filter(
+ (board) =>
+ board.userId === userId &&
+ (!workspaceId || board.projectId !== null || board.agentId !== null),
+ );
+ const items = await dashboards.listItemsForDashboards(boards.map(({ id }) => id));
+ const widgetsByBoard = new Map<string, { id: string; title: string }[]>();
+ for (const { item, widget } of items) {
+ const list = widgetsByBoard.get(item.dashboardId) ?? [];
+ list.push({ id: widget.id, title: widget.title });
+ widgetsByBoard.set(item.dashboardId, list);
+ }
+ return boards.map((board) => ({
+ id: board.id,
+ projectId: board.projectId,
+ title: board.title,
+ widgets: widgetsByBoard.get(board.id) ?? [],
+ }));
+ },
+
+ listRuns: async (widgetId, limit) => {
+ await requireScopedWidget(widgetId);
+ return (await widgets.listRuns(widgetId, { limit })).map(toRunRecord);
+ },
+
+ listWidgets: async () => {
+ const rows = await widgets.list({ agentId, projectId });
+ return rows.map((widget) => ({
+ draftVersionId: widget.draftVersionId,
+ hasDraft: !!widget.draftVersionId,
+ id: widget.id,
+ lastRunStatus: widget.lastRunStatus,
+ published: !!widget.publishedVersionId,
+ title: widget.title,
+ }));
+ },
+
+ publish: async (widgetId, versionId) => {
+ await requireScopedWidget(widgetId);
+ const { version, widget } = await flow.publish(widgetId, versionId);
+ // Fill the live card right away instead of waiting for the first tick.
+ const firstRun = await flow.runNow(widgetId).catch((error) => {
+ console.error('[dashboard-tool] first run after publish failed widget=%s', widgetId, error);
+ return undefined;
+ });
+ return {
+ firstRunStatus: firstRun?.status,
+ schedulePattern: widget?.schedulePattern,
+ version: toVersionRecord(version),
+ };
+ },
+
+ saveDraft: async (widgetId, input) => {
+ const { parentVersionId, ...content } = input;
+ const version = parseContent(content);
+ await requireScopedWidget(widgetId);
+ const draft = await flow.saveDraft(widgetId, {
+ ...version,
+ ...source,
+ parentVersionId: parentVersionId ?? null,
+ });
+ return toVersionRecord(draft);
+ },
+
+ updateWidget: async (widgetId, patch) => {
+ await requireScopedWidget(widgetId);
+ const metadata = parseMetadata(patch, widgetMetadataPatchSchema);
+ const updated = await widgets.update(widgetId, {
+ ...(metadata.description !== undefined && { description: metadata.description }),
+ ...(metadata.title !== undefined && { title: metadata.title }),
+ });
+ if (!updated) throw new Error('Widget not found or not editable');
+ },
+ };
+};
+
+/** The project of a topic the run already authorized, when it lives in one. */
+export const resolveTopicProjectId = async (db: LobeChatDatabase, topicId?: string) => {
+ if (!topicId) return undefined;
+ const [row] = await db
+ .select({ projectId: topics.projectId })
+ .from(topics)
+ .where(eq(topics.id, topicId))
+ .limit(1);
+ return row?.projectId ?? undefined;
+};
+
+/**
+ * A topic id sent by a client, kept only when the caller can read the topic in
+ * the current scope — then its project scopes what the tool creates. In a
+ * workspace that includes teammates' topics (a member working in a teammate's
+ * project topic); in personal mode only the caller's own.
+ */
+export const resolveClientTopic = async (
+ db: LobeChatDatabase,
+ topicId: string | null | undefined,
+ userId: string,
+ workspaceId?: string,
+): Promise<{ projectId?: string; topicId?: string }> => {
+ if (!topicId) return {};
+ const topic = await new TopicModel(db, userId, workspaceId).findById(topicId);
+ return topic ? { projectId: topic.projectId ?? undefined, topicId } : {};
+};
diff --git a/apps/server/src/services/widget/dryRunAudit.ts b/apps/server/src/services/widget/dryRunAudit.ts
new file mode 100644
index 00000000000..6ad8a4ee141
--- /dev/null
+++ b/apps/server/src/services/widget/dryRunAudit.ts
@@ -0,0 +1,21 @@
+import { createDryRunAudit } from '@lobechat/builtin-tool-dashboard';
+import type { DynamicInterventionResolver } from '@lobechat/types';
+
+import { WidgetModel } from '@/database/models/widget';
+import type { LobeChatDatabase } from '@/database/type';
+
+/**
+ * The `dryRunWidget` approval audit for a server agent run: reads the exact
+ * version the call names, as the run's user, and asks for approval when it
+ * declares connector credentials or network hosts. Unreadable → approval.
+ */
+export const createWidgetDryRunAudit = (
+ db: LobeChatDatabase,
+ userId: string,
+ workspaceId?: string,
+): DynamicInterventionResolver => {
+ const widgets = new WidgetModel(db, userId, workspaceId);
+ return createDryRunAudit({
+ loadVersion: async (widgetId, versionId) => widgets.findVersion(widgetId, versionId),
+ });
+};
diff --git a/apps/server/src/services/widget/featureGate.ts b/apps/server/src/services/widget/featureGate.ts
new file mode 100644
index 00000000000..135f49bbc63
--- /dev/null
+++ b/apps/server/src/services/widget/featureGate.ts
@@ -0,0 +1,10 @@
+import { getServerFeatureFlagsStateFromRuntimeConfig } from '@/server/featureFlags';
+
+/**
+ * Whether dashboards — the widget / dashboard APIs and the `lobe-dashboard`
+ * agent tool — are enabled for this user (runtime flag `dashboard`, off by
+ * default). The scheduler is deliberately not gated: widgets already
+ * published keep refreshing while the flag is off.
+ */
+export const isDashboardEnabled = async (userId?: string) =>
+ (await getServerFeatureFlagsStateFromRuntimeConfig(userId)).enableDashboard === true;
diff --git a/apps/server/src/services/widget/metadataSchema.ts b/apps/server/src/services/widget/metadataSchema.ts
new file mode 100644
index 00000000000..ab201d41efd
--- /dev/null
+++ b/apps/server/src/services/widget/metadataSchema.ts
@@ -0,0 +1,15 @@
+import { z } from 'zod';
+
+/**
+ * Validation of a widget's own metadata — title and description — shared by
+ * every entry point that writes it (the widget router's create / update and
+ * the dashboard agent tool's draft and update paths), so all enforce exactly
+ * the same limits and the two paths cannot drift.
+ */
+export const widgetMetadataSchema = z.object({
+ description: z.string().max(2000).nullish(),
+ title: z.string().min(1).max(200),
+});
+
+/** Update entry points may send only one of the two fields. */
+export const widgetMetadataPatchSchema = widgetMetadataSchema.partial();
diff --git a/docs/self-hosting/advanced/feature-flags.mdx b/docs/self-hosting/advanced/feature-flags.mdx
index f59d4c09317..2cdbbf42bfe 100644
--- a/docs/self-hosting/advanced/feature-flags.mdx
+++ b/docs/self-hosting/advanced/feature-flags.mdx
@@ -1,9 +1,7 @@
---
title: LobeHub Feature Flags Environment Variables Configuration Guide
description: >-
- Learn how to use environment variables to customize LobeHub's feature flags,
- including controlling whether a feature is enabled or disabled, or enabling or
- disabling features for specific user groups or environments as needed.
+ Learn how to use environment variables to customize LobeHub's feature flags, including controlling whether a feature is enabled or disabled, or enabling or disabling features for specific user groups or environments as needed.
tags:
- LobeHub
- Environment Variables
@@ -36,28 +34,29 @@ You can achieve various feature combinations using the above configuration synta
their default values).
</Callout>
-| Configuration Item | Description | Default Value |
-| ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------- |
-| `check_updates` | Allows checking for updates. | Enabled |
-| `provider_settings` | Controls model provider settings display. | Enabled |
-| `openai_api_key` | Allows users to customize the OpenAI API Key. | Enabled |
-| `openai_proxy_url` | Allows users to customize the OpenAI proxy URL. | Enabled |
-| `api_key_manage` | Controls access to API key management page (/profile/apikey). | Disabled |
-| `agent_share` | Gates new or re-enabled interactive Agent shares. Requires deployment support; see the boundary below. | Disabled |
-| `agent_gateway_mux` | Routes agent runs over one multiplexed gateway socket per user. Requires a gateway that serves `/v2/ws` (`AGENT_GATEWAY_PROTOCOL=2`). | Disabled |
-| `agent_llm_relay` | Runs LLM calls for model providers only the user's device can reach (local Ollama / LM Studio, private-network endpoints) on the client that started the run, while the agent loop stays on the server. Requires an open LobeHub client for such runs. | Disabled |
-| `edit_agent` | Allows users to edit assistants. | Enabled |
-| `ai_image` | Controls AI image generation feature and page (/image). | Enabled |
-| `speech_to_text` | Enables speech-to-text functionality. | Enabled |
-| `token_counter` | Reserved for token counter display. | Enabled |
-| `welcome_suggest` | Displays welcome suggestions. | Enabled |
-| `changelog` | Controls changelog modal/page display. | Enabled |
-| `market` | Enables the assistant market functionality. | Enabled |
-| `knowledge_base` | Enables the knowledge base functionality. | Enabled |
-| `rag_eval` | Controls RAG evaluation feature (/repos/\[id]/evals). | Disabled |
-| `cloud_promotion` | Controls cloud service promotion link display in user menu. | Disabled |
-| `commercial_hide_github` | Hides GitHub-related links in settings footer (requires commercial license). | Disabled |
-| `commercial_hide_docs` | Hides documentation and help menu including changelog, docs, and feedback (requires commercial license). | Disabled |
+| Configuration Item | Description | Default Value |
+| ------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------- |
+| `check_updates` | Allows checking for updates. | Enabled |
+| `provider_settings` | Controls model provider settings display. | Enabled |
+| `openai_api_key` | Allows users to customize the OpenAI API Key. | Enabled |
+| `openai_proxy_url` | Allows users to customize the OpenAI proxy URL. | Enabled |
+| `api_key_manage` | Controls access to API key management page (/profile/apikey). | Disabled |
+| `agent_share` | Gates new or re-enabled interactive Agent shares. Requires deployment support; see the boundary below. | Disabled |
+| `agent_gateway_mux` | Routes agent runs over one multiplexed gateway socket per user. Requires a gateway that serves `/v2/ws` (`AGENT_GATEWAY_PROTOCOL=2`). | Disabled |
+| `agent_llm_relay` | Runs LLM calls for model providers only the user's device can reach (local Ollama / LM Studio, private-network endpoints) on the client that started the run, while the agent loop stays on the server. Requires an open LobeHub client for such runs. | Disabled |
+| `dashboard` | Dashboards: the home and project dashboard pages, the widget Portal, in-chat widget previews and the `lobe-dashboard` agent tool that builds monitoring widgets. When off, these are hidden and the widget / dashboard APIs return FORBIDDEN; widgets already published keep refreshing on their schedule. | Disabled |
+| `edit_agent` | Allows users to edit assistants. | Enabled |
+| `ai_image` | Controls AI image generation feature and page (/image). | Enabled |
+| `speech_to_text` | Enables speech-to-text functionality. | Enabled |
+| `token_counter` | Reserved for token counter display. | Enabled |
+| `welcome_suggest` | Displays welcome suggestions. | Enabled |
+| `changelog` | Controls changelog modal/page display. | Enabled |
+| `market` | Enables the assistant market functionality. | Enabled |
+| `knowledge_base` | Enables the knowledge base functionality. | Enabled |
+| `rag_eval` | Controls RAG evaluation feature (/repos/\[id]/evals). | Disabled |
+| `cloud_promotion` | Controls cloud service promotion link display in user menu. | Disabled |
+| `commercial_hide_github` | Hides GitHub-related links in settings footer (requires commercial license). | Disabled |
+| `commercial_hide_docs` | Hides documentation and help menu including changelog, docs, and feedback (requires commercial license). | Disabled |
## Interactive Agent Sharing: Deployment and Rollout Boundaries
diff --git a/docs/self-hosting/advanced/feature-flags.zh-CN.mdx b/docs/self-hosting/advanced/feature-flags.zh-CN.mdx
index c71f6679d20..d4f93b5c856 100644
--- a/docs/self-hosting/advanced/feature-flags.zh-CN.mdx
+++ b/docs/self-hosting/advanced/feature-flags.zh-CN.mdx
@@ -32,28 +32,29 @@ tags:
关键字,你需要手动控制所有的功能标志(否则它们会采用对应的默认值)。
</Callout>
-| 配置项 | 解释 | 默认值 |
-| ------------------------ | -------------------------------------------------------------------------------------------------- | --- |
-| `check_updates` | 允许检查更新。 | 开启 |
-| `provider_settings` | 控制模型供应商设置的显示。 | 开启 |
-| `openai_api_key` | 允许用户自定义 OpenAI API Key。 | 开启 |
-| `openai_proxy_url` | 允许用户自定义 OpenAI 代理 URL。 | 开启 |
-| `api_key_manage` | 控制 API 密钥管理页面 (/profile/apikey) 的访问。 | 关闭 |
-| `agent_share` | 控制新建或重新启用交互式助理分享;还需部署支持,详见下文边界。 | 关闭 |
-| `agent_gateway_mux` | 让助理运行共用一条按用户复用的网关连接;需要网关提供 `/v2/ws`(`AGENT_GATEWAY_PROTOCOL=2`)。 | 关闭 |
-| `agent_llm_relay` | 对只有用户设备能访问的模型服务商(本地 Ollama / LM Studio、私网地址),由发起运行的客户端执行单次模型调用,助理循环仍在服务端运行;这类运行需要有打开的 LobeHub 客户端。 | 关闭 |
-| `edit_agent` | 允许用户编辑助手。 | 开启 |
-| `ai_image` | 控制 AI 图像生成功能和页面 (/image)。 | 开启 |
-| `speech_to_text` | 启用语音转文本功能。 | 开启 |
-| `token_counter` | 保留用于令牌计数器显示。 | 开启 |
-| `welcome_suggest` | 显示欢迎建议。 | 开启 |
-| `changelog` | 控制更新日志弹窗 / 页面的显示。 | 开启 |
-| `market` | 启用助手市场功能。 | 开启 |
-| `knowledge_base` | 启用知识库功能。 | 开启 |
-| `rag_eval` | 控制 RAG 评估功能 (/repos/\[id]/evals)。 | 关闭 |
-| `cloud_promotion` | 控制用户菜单中云服务推广链接的显示。 | 关闭 |
-| `commercial_hide_github` | 隐藏设置页面底部的 GitHub 相关链接(需要商业授权)。 | 关闭 |
-| `commercial_hide_docs` | 隐藏文档和帮助菜单,包括更新日志、文档和反馈(需要商业授权)。 | 关闭 |
+| 配置项 | 解释 | 默认值 |
+| ------------------------ | -------------------------------------------------------------------------------------------------------------- | --- |
+| `check_updates` | 允许检查更新。 | 开启 |
+| `provider_settings` | 控制模型供应商设置的显示。 | 开启 |
+| `openai_api_key` | 允许用户自定义 OpenAI API Key。 | 开启 |
+| `openai_proxy_url` | 允许用户自定义 OpenAI 代理 URL。 | 开启 |
+| `api_key_manage` | 控制 API 密钥管理页面 (/profile/apikey) 的访问。 | 关闭 |
+| `agent_share` | 控制新建或重新启用交互式助理分享;还需部署支持,详见下文边界。 | 关闭 |
+| `agent_gateway_mux` | 让助理运行共用一条按用户复用的网关连接;需要网关提供 `/v2/ws`(`AGENT_GATEWAY_PROTOCOL=2`)。 | 关闭 |
+| `agent_llm_relay` | 对只有用户设备能访问的模型服务商(本地 Ollama / LM Studio、私网地址),由发起运行的客户端执行单次模型调用,助理循环仍在服务端运行;这类运行需要有打开的 LobeHub 客户端。 | 关闭 |
+| `dashboard` | 看板:首页与项目看板页面、监控组件侧边栏、对话内的组件预览,以及用于搭建监控组件的 `lobe-dashboard` 助理工具。关闭时以上入口均隐藏,组件与看板相关接口返回 FORBIDDEN;已发布的组件仍按计划刷新。 | 关闭 |
+| `edit_agent` | 允许用户编辑助手。 | 开启 |
+| `ai_image` | 控制 AI 图像生成功能和页面 (/image)。 | 开启 |
+| `speech_to_text` | 启用语音转文本功能。 | 开启 |
+| `token_counter` | 保留用于令牌计数器显示。 | 开启 |
+| `welcome_suggest` | 显示欢迎建议。 | 开启 |
+| `changelog` | 控制更新日志弹窗 / 页面的显示。 | 开启 |
+| `market` | 启用助手市场功能。 | 开启 |
+| `knowledge_base` | 启用知识库功能。 | 开启 |
+| `rag_eval` | 控制 RAG 评估功能 (/repos/\[id]/evals)。 | 关闭 |
+| `cloud_promotion` | 控制用户菜单中云服务推广链接的显示。 | 关闭 |
+| `commercial_hide_github` | 隐藏设置页面底部的 GitHub 相关链接(需要商业授权)。 | 关闭 |
+| `commercial_hide_docs` | 隐藏文档和帮助菜单,包括更新日志、文档和反馈(需要商业授权)。 | 关闭 |
## 交互式助理分享:部署与灰度边界
diff --git a/locales/en-US/common.json b/locales/en-US/common.json
index e8715ffcd86..ba5173eff6a 100644
--- a/locales/en-US/common.json
+++ b/locales/en-US/common.json
@@ -424,6 +424,7 @@
"tab.chat": "Chat",
"tab.community": "Community",
"tab.create": "Create",
+ "tab.dashboard": "Dashboards",
"tab.discover": "Discover",
"tab.eval": "Eval Lab",
"tab.files": "Files",
diff --git a/locales/en-US/dashboard.json b/locales/en-US/dashboard.json
new file mode 100644
index 00000000000..1511d25f18d
--- /dev/null
+++ b/locales/en-US/dashboard.json
@@ -0,0 +1,156 @@
+{
+ "actions.more": "More actions",
+ "actions.rename": "Rename",
+ "actions.trash": "Move to trash",
+ "actions.trashConfirm": "\"{{title}}\" and its layout will move to the trash. Widgets stay available and keep their history.",
+ "actions.trashTitle": "Move this dashboard to the trash?",
+ "actions.trashed": "\"{{title}}\" moved to the trash",
+ "board.empty": "No widgets yet. Ask an agent in a conversation to build a monitoring widget and add it to this dashboard.",
+ "board.health.failed": "{{count}} failed",
+ "board.health.ok": "{{count}} up to date",
+ "board.health.running": "{{count}} refreshing",
+ "board.health.stale": "{{count}} stale",
+ "board.lastUpdated": "Latest data {{time}}",
+ "board.refreshAll": "Refresh all",
+ "board.refreshAllFailed_one": "{{count}} widget failed to refresh; its last successful result is still shown",
+ "board.refreshAllFailed_other": "{{count}} widgets failed to refresh; their last successful results are still shown",
+ "board.widgetCount_one": "{{count}} widget",
+ "board.widgetCount_other": "{{count}} widgets",
+ "chat.add": "Add to dashboard",
+ "chat.addFailed": "Could not add the widget to the dashboard",
+ "chat.added": "Added to \"{{title}}\"",
+ "chat.definition": "Metric definition",
+ "chat.newDashboard": "New dashboard…",
+ "chat.noDashboards": "No dashboards yet",
+ "chat.noDefinition": "No metric definition given.",
+ "chat.onDashboard": "On \"{{title}}\"",
+ "chat.openDashboard": "Open dashboard",
+ "chat.openDetail": "Details",
+ "chat.outdated": "A newer draft (v{{version}}) replaced this preview.",
+ "chat.outdatedVersion": "This preview is from an older version and can no longer be published.",
+ "chat.preview.draft": "Dry run · draft v{{version}}",
+ "chat.preview.live": "Live · v{{version}}",
+ "chat.preview.running": "Running the draft in the sandbox…",
+ "chat.publish": "Publish",
+ "chat.publishFailed": "Could not publish: {{message}}",
+ "chat.publishHint": "Publishing is available after a successful dry run.",
+ "chat.publishReviewTitle": "Review before publishing",
+ "chat.published": "Published v{{version}}. It now refreshes on its schedule.",
+ "chat.unavailable": "This widget is no longer available.",
+ "create.action": "New dashboard",
+ "create.submit": "Create",
+ "create.title": "New dashboard",
+ "detail.failures": "Failures in a row",
+ "detail.lastRunAt": "Last run",
+ "detail.manualOnly": "Manual refresh only",
+ "detail.nextRunAt": "Next run",
+ "detail.noOutput": "No successful result yet.",
+ "detail.schedule": "Schedule",
+ "detail.tab.data": "Data",
+ "detail.tab.diff": "Changes",
+ "detail.tab.runs": "Run history",
+ "detail.tab.versions": "Versions",
+ "detail.updatedAt": "Data updated",
+ "detail.version": "Version",
+ "detail.versionDraft": "draft v{{version}}",
+ "detail.versionNone": "Not published",
+ "detail.versionPublished": "v{{version}} live",
+ "dryRun.intro": "The agent wants to run this draft once to preview its output. It runs in a sandbox with the access below; nothing goes live and no dashboard changes.",
+ "dryRun.runtime": "Runtime",
+ "error.hideDetails": "Hide details",
+ "error.showDetails": "Show details",
+ "form.descriptionLabel": "Description",
+ "form.descriptionPlaceholder": "What this dashboard keeps an eye on (optional)",
+ "form.titleLabel": "Name",
+ "form.titlePlaceholder": "e.g. Open-source project health",
+ "layout.cancel": "Discard changes",
+ "layout.drag": "Drag to reorder",
+ "layout.edit": "Edit layout",
+ "layout.narrower": "Narrower",
+ "layout.save": "Save layout",
+ "layout.saveFailed": "Could not save the layout. The previous layout is restored.",
+ "layout.saved": "Layout saved",
+ "layout.shorter": "Shorter",
+ "layout.taller": "Taller",
+ "layout.wider": "Wider",
+ "list.description": "Boards of live widgets. Each widget runs its own script on a schedule and keeps its history.",
+ "list.empty": "No dashboards yet",
+ "list.noDescription": "No description",
+ "list.title": "Dashboards",
+ "list.updatedAt": "Updated {{time}}",
+ "portal.dashboards": "On dashboards",
+ "portal.definition": "Metric definition",
+ "portal.diff.base": "From",
+ "portal.diff.identical": "The script is identical in these versions.",
+ "portal.diff.manifest": "Contract changes",
+ "portal.diff.single": "Only one version so far — nothing to compare.",
+ "portal.diff.target": "To",
+ "portal.goToDashboards": "All dashboards",
+ "portal.notOnDashboard": "Not on a dashboard yet.",
+ "portal.preview": "Dry run preview",
+ "portal.previewHint": "Output of the dry run this conversation produced. It does not change the live widget.",
+ "portal.title": "Widget",
+ "project.boards": "Dashboards",
+ "project.boardsEmpty": "No dashboards in this project yet",
+ "project.description": "This project's dashboards and widgets, including the ones its agents built in project conversations.",
+ "project.widgetsEmpty": "No widgets yet. Ask an agent in a conversation of this project to build a monitoring widget and it will show up here.",
+ "project.widgets_one": "Widgets ({{count}})",
+ "project.widgets_other": "Widgets ({{count}})",
+ "publish.env": "Credentials",
+ "publish.envNone": "None",
+ "publish.intro": "Once published, this script runs on its schedule with the listed credentials and its result shows on dashboards.",
+ "publish.network": "Network",
+ "publish.networkNone": "No network access",
+ "publish.networkUnrestricted": "The sandbox cannot restrict egress to the listed hosts — the script can reach any host, including ones it did not declare.",
+ "publish.noSuccessfulRun": "This draft has not succeeded in a dry run yet, so publishing it will be refused.",
+ "publish.previewTitle": "Latest dry run",
+ "publish.schedule": "Refresh",
+ "publish.scheduleNone": "Manual only",
+ "publish.scriptChanges": "Changes from live v{{version}}",
+ "publish.scriptNew": "Script",
+ "rename.title": "Rename dashboard",
+ "review.loadFailed": "Couldn't load the review, so approval is on hold",
+ "review.versionMissing": "This version is no longer available, so it can't be reviewed. Reject the request and ask the agent to try again.",
+ "run.empty": "This widget has not run yet.",
+ "run.error": "Error",
+ "run.logEmpty": "(empty)",
+ "run.logTruncated": "truncated",
+ "run.status.failed": "Failed",
+ "run.status.partial": "Partial",
+ "run.status.running": "Running",
+ "run.status.succeeded": "Succeeded",
+ "run.status.timeout": "Timed out",
+ "run.trigger.manual": "Manual",
+ "run.trigger.preview": "Preview",
+ "run.trigger.schedule": "Scheduled",
+ "version.empty": "No versions yet.",
+ "version.publishedAt": "Published {{time}}",
+ "version.script": "Script",
+ "version.source.agent": "Written by an agent",
+ "version.source.user": "Written by a user",
+ "version.status.archived": "Archived",
+ "version.status.draft": "Draft",
+ "version.status.published": "Live",
+ "widget.lastAttemptAt": "Last attempt {{time}}",
+ "widget.refresh.action": "Refresh now",
+ "widget.refresh.failed": "Refresh failed: {{message}}. The last successful result is still shown.",
+ "widget.state.failedNoOutput": "No successful result yet — the last run failed.",
+ "widget.state.firstRun": "Running for the first time…",
+ "widget.state.noRun": "Not run yet. Refresh to fetch data.",
+ "widget.state.unpublished": "No published version yet.",
+ "widget.status.failed": "Failed",
+ "widget.status.failedTip": "Last run failed: {{message}}. Showing the last successful result.",
+ "widget.status.failedTipNoMessage": "Last run failed. Showing the last successful result.",
+ "widget.status.ok": "Up to date",
+ "widget.status.partial": "Partial",
+ "widget.status.partialTip": "The script reported an incomplete result.",
+ "widget.status.running": "Running",
+ "widget.status.runningTip": "A run is in progress.",
+ "widget.status.stale": "Stale",
+ "widget.status.staleTip": "The scheduled refresh is overdue; this data may be out of date.",
+ "widget.updatedAt": "Updated {{time}}",
+ "widget.view.listEmpty": "No items",
+ "widget.view.more": "+{{count}} more",
+ "widget.view.seriesEmpty": "No data points",
+ "widget.view.tableEmpty": "No rows"
+}
diff --git a/locales/en-US/electron.json b/locales/en-US/electron.json
index 3580c5b85ad..7bdbf7d02e5 100644
--- a/locales/en-US/electron.json
+++ b/locales/en-US/electron.json
@@ -17,6 +17,7 @@
"navigation.apps": "Apps",
"navigation.channels": "Channels",
"navigation.chat": "Chat",
+ "navigation.dashboard": "Dashboards",
"navigation.discover": "Discover",
"navigation.discoverAssistants": "Discover Agents",
"navigation.discoverMcp": "Discover MCP",
diff --git a/locales/en-US/plugin.json b/locales/en-US/plugin.json
index 7ad8daf3602..0cbf59f4ff9 100644
--- a/locales/en-US/plugin.json
+++ b/locales/en-US/plugin.json
@@ -308,6 +308,14 @@
"builtins.lobe-computer-use.inspector.preview": "Check computer action",
"builtins.lobe-computer-use.inspector.preview.loading": "Checking computer action…",
"builtins.lobe-computer-use.title": "Computer Use",
+ "builtins.lobe-dashboard.apiName.addWidgetToDashboard": "Add widget to dashboard",
+ "builtins.lobe-dashboard.apiName.createWidgetDraft": "Create widget draft",
+ "builtins.lobe-dashboard.apiName.dryRunWidget": "Dry-run widget",
+ "builtins.lobe-dashboard.apiName.getWidgetRuns": "Check widget runs",
+ "builtins.lobe-dashboard.apiName.listDashboards": "List dashboards",
+ "builtins.lobe-dashboard.apiName.requestPublish": "Publish widget",
+ "builtins.lobe-dashboard.apiName.updateWidgetDraft": "Update widget draft",
+ "builtins.lobe-dashboard.title": "Dashboards",
"builtins.lobe-goal-supervisor.apiName.inspectGoal": "Inspect goal",
"builtins.lobe-goal-supervisor.apiName.inspectTask": "Inspect interrupted task",
"builtins.lobe-goal-supervisor.apiName.readArtifact": "Read goal artifact",
diff --git a/locales/en-US/project.json b/locales/en-US/project.json
index 60322f6ce96..276e46f3c25 100644
--- a/locales/en-US/project.json
+++ b/locales/en-US/project.json
@@ -144,6 +144,7 @@
"sections.acceptance": "Acceptance",
"sections.agents": "Agents",
"sections.conversations": "Topics",
+ "sections.dashboard": "Dashboards",
"sections.goals": "Goals",
"sections.home": "Project home",
"sections.knowledgeBases": "Libraries",
diff --git a/locales/en-US/setting.json b/locales/en-US/setting.json
index 296b311b85b..9943ec7f0aa 100644
--- a/locales/en-US/setting.json
+++ b/locales/en-US/setting.json
@@ -1799,6 +1799,8 @@
"tools.builtins.lobe-computer-use.title": "Computer Use",
"tools.builtins.lobe-creds.description": "Manage user credentials for authentication, environment variable injection, and API verification — handle API keys, OAuth tokens, and secrets for third-party integrations.",
"tools.builtins.lobe-creds.title": "Credentials",
+ "tools.builtins.lobe-dashboard.description": "Build live monitoring widgets from sandboxed scripts, preview them with real data and put them on dashboards",
+ "tools.builtins.lobe-dashboard.title": "Dashboards",
"tools.builtins.lobe-group-agent-builder.description": "Configure group metadata, members, and shared content for multi-agent groups",
"tools.builtins.lobe-group-agent-builder.title": "Group Agent Builder",
"tools.builtins.lobe-group-management.description": "Orchestrate and manage multi-agent group conversations",
diff --git a/locales/zh-CN/common.json b/locales/zh-CN/common.json
index 524ffc9b41c..90b85254209 100644
--- a/locales/zh-CN/common.json
+++ b/locales/zh-CN/common.json
@@ -424,6 +424,7 @@
"tab.chat": "会话",
"tab.community": "社区",
"tab.create": "创建",
+ "tab.dashboard": "看板",
"tab.discover": "发现",
"tab.eval": "评测实验室",
"tab.files": "文件",
diff --git a/locales/zh-CN/dashboard.json b/locales/zh-CN/dashboard.json
new file mode 100644
index 00000000000..09b5669d2a7
--- /dev/null
+++ b/locales/zh-CN/dashboard.json
@@ -0,0 +1,156 @@
+{
+ "actions.more": "更多操作",
+ "actions.rename": "重命名",
+ "actions.trash": "移到回收站",
+ "actions.trashConfirm": "「{{title}}」及其布局将移到回收站。组件仍然保留,历史记录不受影响。",
+ "actions.trashTitle": "将此看板移到回收站?",
+ "actions.trashed": "「{{title}}」已移到回收站",
+ "board.empty": "还没有组件。在对话中让助理编写一个监控组件,并把它添加到这个看板。",
+ "board.health.failed": "{{count}} 个失败",
+ "board.health.ok": "{{count}} 个正常",
+ "board.health.running": "{{count}} 个刷新中",
+ "board.health.stale": "{{count}} 个过期",
+ "board.lastUpdated": "最近数据 {{time}}",
+ "board.refreshAll": "全部刷新",
+ "board.refreshAllFailed_one": "{{count}} 个组件刷新失败,仍显示上次成功的结果",
+ "board.refreshAllFailed_other": "{{count}} 个组件刷新失败,仍显示上次成功的结果",
+ "board.widgetCount_one": "{{count}} 个组件",
+ "board.widgetCount_other": "{{count}} 个组件",
+ "chat.add": "添加到看板",
+ "chat.addFailed": "无法将组件添加到看板",
+ "chat.added": "已添加到「{{title}}」",
+ "chat.definition": "口径说明",
+ "chat.newDashboard": "新建看板…",
+ "chat.noDashboards": "还没有看板",
+ "chat.noDefinition": "未提供口径说明。",
+ "chat.onDashboard": "已在「{{title}}」",
+ "chat.openDashboard": "打开看板",
+ "chat.openDetail": "详情",
+ "chat.outdated": "已有更新的草稿(v{{version}}),此预览已过时。",
+ "chat.outdatedVersion": "此预览来自旧版本,无法再发布。",
+ "chat.preview.draft": "试运行 · 草稿 v{{version}}",
+ "chat.preview.live": "已上线 · v{{version}}",
+ "chat.preview.running": "正在沙箱中试运行草稿…",
+ "chat.publish": "发布",
+ "chat.publishFailed": "发布失败:{{message}}",
+ "chat.publishHint": "试运行成功后才能发布。",
+ "chat.publishReviewTitle": "发布前审查",
+ "chat.published": "已发布 v{{version}},将按计划自动刷新。",
+ "chat.unavailable": "该组件已不可用。",
+ "create.action": "新建看板",
+ "create.submit": "创建",
+ "create.title": "新建看板",
+ "detail.failures": "连续失败",
+ "detail.lastRunAt": "最近运行",
+ "detail.manualOnly": "仅手动刷新",
+ "detail.nextRunAt": "下次运行",
+ "detail.noOutput": "还没有成功的结果。",
+ "detail.schedule": "调度",
+ "detail.tab.data": "数据",
+ "detail.tab.diff": "版本对比",
+ "detail.tab.runs": "运行历史",
+ "detail.tab.versions": "版本",
+ "detail.updatedAt": "数据更新于",
+ "detail.version": "版本",
+ "detail.versionDraft": "草稿 v{{version}}",
+ "detail.versionNone": "未发布",
+ "detail.versionPublished": "v{{version}} 生效中",
+ "dryRun.intro": "智能体想先试运行一次此草稿以预览输出。它会在沙箱中以下方列出的权限运行;不会上线,也不会改动任何看板。",
+ "dryRun.runtime": "运行环境",
+ "error.hideDetails": "隐藏详情",
+ "error.showDetails": "显示详情",
+ "form.descriptionLabel": "描述",
+ "form.descriptionPlaceholder": "这个看板关注什么(可选)",
+ "form.titleLabel": "名称",
+ "form.titlePlaceholder": "例如:开源项目健康度",
+ "layout.cancel": "放弃修改",
+ "layout.drag": "拖动以调整顺序",
+ "layout.edit": "编辑布局",
+ "layout.narrower": "变窄",
+ "layout.save": "保存布局",
+ "layout.saveFailed": "布局保存失败,已恢复为之前的布局。",
+ "layout.saved": "布局已保存",
+ "layout.shorter": "变矮",
+ "layout.taller": "变高",
+ "layout.wider": "变宽",
+ "list.description": "由实时组件组成的看板。每个组件按计划运行自己的脚本,并保留历史记录。",
+ "list.empty": "还没有看板",
+ "list.noDescription": "暂无描述",
+ "list.title": "看板",
+ "list.updatedAt": "更新于 {{time}}",
+ "portal.dashboards": "所在看板",
+ "portal.definition": "口径说明",
+ "portal.diff.base": "对比版本",
+ "portal.diff.identical": "这两个版本的脚本完全相同。",
+ "portal.diff.manifest": "契约变更",
+ "portal.diff.single": "目前只有一个版本,暂无可对比内容。",
+ "portal.diff.target": "目标版本",
+ "portal.goToDashboards": "全部看板",
+ "portal.notOnDashboard": "尚未添加到任何看板。",
+ "portal.preview": "试运行预览",
+ "portal.previewHint": "本次对话产生的试运行结果,不会影响已上线的组件。",
+ "portal.title": "监控组件",
+ "project.boards": "看板",
+ "project.boardsEmpty": "此项目还没有看板",
+ "project.description": "此项目的看板与组件,包括其智能体在项目对话中创建的组件。",
+ "project.widgetsEmpty": "还没有组件。在此项目的对话中让智能体创建监控组件,它会出现在这里。",
+ "project.widgets_one": "组件({{count}})",
+ "project.widgets_other": "组件({{count}})",
+ "publish.env": "凭证",
+ "publish.envNone": "无",
+ "publish.intro": "发布后,该脚本将使用下列凭证按计划运行,结果会显示在看板上。",
+ "publish.network": "网络",
+ "publish.networkNone": "无网络访问",
+ "publish.networkUnrestricted": "沙箱无法将出口限制为所列主机——脚本可以访问任意主机,包括未声明的主机。",
+ "publish.noSuccessfulRun": "该草稿尚未试运行成功,发布将被拒绝。",
+ "publish.previewTitle": "最近一次试运行",
+ "publish.schedule": "刷新频率",
+ "publish.scheduleNone": "仅手动",
+ "publish.scriptChanges": "相对已上线 v{{version}} 的变更",
+ "publish.scriptNew": "脚本",
+ "rename.title": "重命名看板",
+ "review.loadFailed": "无法加载审阅内容,暂不能批准",
+ "review.versionMissing": "这个版本已不可用,无法审阅。请拒绝该请求,并让智能体重新尝试。",
+ "run.empty": "这个组件还没有运行过。",
+ "run.error": "错误",
+ "run.logEmpty": "(空)",
+ "run.logTruncated": "已截断",
+ "run.status.failed": "失败",
+ "run.status.partial": "部分完成",
+ "run.status.running": "运行中",
+ "run.status.succeeded": "成功",
+ "run.status.timeout": "超时",
+ "run.trigger.manual": "手动",
+ "run.trigger.preview": "预览",
+ "run.trigger.schedule": "定时",
+ "version.empty": "还没有版本。",
+ "version.publishedAt": "发布于 {{time}}",
+ "version.script": "脚本",
+ "version.source.agent": "由助理编写",
+ "version.source.user": "由用户编写",
+ "version.status.archived": "已归档",
+ "version.status.draft": "草稿",
+ "version.status.published": "生效中",
+ "widget.lastAttemptAt": "最近尝试于 {{time}}",
+ "widget.refresh.action": "立即刷新",
+ "widget.refresh.failed": "刷新失败:{{message}}。仍显示上次成功的结果。",
+ "widget.state.failedNoOutput": "还没有成功的结果——上次运行失败。",
+ "widget.state.firstRun": "首次运行中…",
+ "widget.state.noRun": "尚未运行,点击刷新获取数据。",
+ "widget.state.unpublished": "还没有已发布的版本。",
+ "widget.status.failed": "失败",
+ "widget.status.failedTip": "上次运行失败:{{message}}。当前显示上次成功的结果。",
+ "widget.status.failedTipNoMessage": "上次运行失败。当前显示上次成功的结果。",
+ "widget.status.ok": "已是最新",
+ "widget.status.partial": "部分数据",
+ "widget.status.partialTip": "脚本报告结果不完整。",
+ "widget.status.running": "运行中",
+ "widget.status.runningTip": "正在运行。",
+ "widget.status.stale": "已过期",
+ "widget.status.staleTip": "定时刷新已逾期,数据可能已过时。",
+ "widget.updatedAt": "更新于 {{time}}",
+ "widget.view.listEmpty": "没有条目",
+ "widget.view.more": "还有 {{count}} 条",
+ "widget.view.seriesEmpty": "没有数据点",
+ "widget.view.tableEmpty": "没有数据行"
+}
diff --git a/locales/zh-CN/electron.json b/locales/zh-CN/electron.json
index 2c6c45e795f..e0c872b96ee 100644
--- a/locales/zh-CN/electron.json
+++ b/locales/zh-CN/electron.json
@@ -17,6 +17,7 @@
"navigation.apps": "应用",
"navigation.channels": "消息频道",
"navigation.chat": "对话",
+ "navigation.dashboard": "看板",
"navigation.discover": "发现",
"navigation.discoverAssistants": "发现助理",
"navigation.discoverMcp": "发现 MCP",
diff --git a/locales/zh-CN/plugin.json b/locales/zh-CN/plugin.json
index 3acb68fb0dc..6a8ce63884c 100644
--- a/locales/zh-CN/plugin.json
+++ b/locales/zh-CN/plugin.json
@@ -308,6 +308,14 @@
"builtins.lobe-computer-use.inspector.preview": "检查电脑操作",
"builtins.lobe-computer-use.inspector.preview.loading": "检查电脑操作中…",
"builtins.lobe-computer-use.title": "使用电脑",
+ "builtins.lobe-dashboard.apiName.addWidgetToDashboard": "添加组件到看板",
+ "builtins.lobe-dashboard.apiName.createWidgetDraft": "创建组件草稿",
+ "builtins.lobe-dashboard.apiName.dryRunWidget": "试运行组件",
+ "builtins.lobe-dashboard.apiName.getWidgetRuns": "查看组件运行记录",
+ "builtins.lobe-dashboard.apiName.listDashboards": "列出看板",
+ "builtins.lobe-dashboard.apiName.requestPublish": "发布组件",
+ "builtins.lobe-dashboard.apiName.updateWidgetDraft": "更新组件草稿",
+ "builtins.lobe-dashboard.title": "看板",
"builtins.lobe-goal-supervisor.apiName.inspectGoal": "查看目标",
"builtins.lobe-goal-supervisor.apiName.inspectTask": "检查中断任务",
"builtins.lobe-goal-supervisor.apiName.readArtifact": "读取目标产物",
diff --git a/locales/zh-CN/project.json b/locales/zh-CN/project.json
index 6f1f4c63472..a946e75a1f4 100644
--- a/locales/zh-CN/project.json
+++ b/locales/zh-CN/project.json
@@ -144,6 +144,7 @@
"sections.acceptance": "验收",
"sections.agents": "智能体",
"sections.conversations": "话题",
+ "sections.dashboard": "看板",
"sections.goals": "目标",
"sections.home": "项目主页",
"sections.knowledgeBases": "资料库",
diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.json
index 5927e94916a..4c93212946d 100644
--- a/locales/zh-CN/setting.json
+++ b/locales/zh-CN/setting.json
@@ -1799,6 +1799,8 @@
"tools.builtins.lobe-computer-use.title": "使用电脑",
"tools.builtins.lobe-creds.description": "管理用于身份验证、环境变量注入和 API 调用的用户凭据 — 处理 API 密钥、OAuth 令牌以及第三方集成所需的密钥。",
"tools.builtins.lobe-creds.title": "凭据管理",
+ "tools.builtins.lobe-dashboard.description": "用沙箱脚本构建实时监控组件,用真实数据试运行预览,并添加到看板",
+ "tools.builtins.lobe-dashboard.title": "看板",
"tools.builtins.lobe-group-agent-builder.description": "配置群组的元信息、成员和共享内容,用于多助手群组",
"tools.builtins.lobe-group-agent-builder.title": "群组助手构建器",
"tools.builtins.lobe-group-management.description": "编排并管理多助手群组对话",
diff --git a/package.json b/package.json
index b90788af4db..3ba7338ec03 100644
--- a/package.json
+++ b/package.json
@@ -208,6 +208,7 @@
"@chat-adapter/slack": "~4.38.0",
"@chat-adapter/state-ioredis": "~4.38.0",
"@chat-adapter/telegram": "~4.38.0",
+ "@codemirror/streamparser": "^6.0.0",
"@codesandbox/sandpack-react": "^2.20.0",
"@composio/core": "^0.10.0",
"@discordjs/rest": "^2.6.3",
@@ -250,6 +251,7 @@
"@lobechat/builtin-tool-claude-code": "workspace:*",
"@lobechat/builtin-tool-cloud-sandbox": "workspace:*",
"@lobechat/builtin-tool-creds": "workspace:*",
+ "@lobechat/builtin-tool-dashboard": "workspace:*",
"@lobechat/builtin-tool-goal": "workspace:*",
"@lobechat/builtin-tool-group-agent-builder": "workspace:*",
"@lobechat/builtin-tool-group-management": "workspace:*",
diff --git a/packages/app-config/src/featureFlags/schema.test.ts b/packages/app-config/src/featureFlags/schema.test.ts
index 20cf973a0e8..0fbd3f891b6 100644
--- a/packages/app-config/src/featureFlags/schema.test.ts
+++ b/packages/app-config/src/featureFlags/schema.test.ts
@@ -182,6 +182,18 @@ describe('mapFeatureFlagsEnvToState', () => {
expect(mapFeatureFlagsEnvToState(config).enableAgentShare).toBe(false);
});
+ it('should keep dashboards off by default and enable them per user or globally', () => {
+ expect(DEFAULT_FEATURE_FLAGS.dashboard).toBe(false);
+ expect(mapFeatureFlagsEnvToState(DEFAULT_FEATURE_FLAGS, 'user-1').enableDashboard).toBe(false);
+
+ expect(mapFeatureFlagsEnvToState({ dashboard: true }).enableDashboard).toBe(true);
+
+ const config = { dashboard: ['user-123'] };
+ expect(mapFeatureFlagsEnvToState(config, 'user-123').enableDashboard).toBe(true);
+ expect(mapFeatureFlagsEnvToState(config, 'user-456').enableDashboard).toBe(false);
+ expect(mapFeatureFlagsEnvToState(config).enableDashboard).toBe(false);
+ });
+
it('should correctly map boolean feature flags to state', () => {
const config = {
provider_settings: true,
diff --git a/packages/app-config/src/featureFlags/schema.ts b/packages/app-config/src/featureFlags/schema.ts
index c82b78ac0ec..5a203f96fbc 100644
--- a/packages/app-config/src/featureFlags/schema.ts
+++ b/packages/app-config/src/featureFlags/schema.ts
@@ -59,6 +59,15 @@ export const FeatureFlagsSchema = z.object({
*/
agent_llm_relay: FeatureFlagValue.optional(),
+ /**
+ * Dashboards: monitoring widgets built by the `lobe-dashboard` agent tool,
+ * the home / project dashboard pages, the widget Portal and in-chat widget
+ * previews. Off: none of it is reachable and the tool is never offered;
+ * already-published widgets keep refreshing on their schedule. Array values
+ * are user ids.
+ */
+ dashboard: FeatureFlagValue.optional(),
+
// internal flag
agent_self_iteration: FeatureFlagValue.optional(),
agent_onboarding: FeatureFlagValue.optional(),
@@ -129,6 +138,9 @@ export const DEFAULT_FEATURE_FLAGS: IFeatureFlags = {
// Off until the client executor ships everywhere; allowlist first.
agent_llm_relay: false,
+ // Off until an admin publishes a user allowlist or flips it to true.
+ dashboard: false,
+
agent_self_iteration: isDev,
agent_onboarding: isDev,
dev_dock: isDev,
@@ -163,6 +175,7 @@ export const mapFeatureFlagsEnvToState = (
enableAgentShare: evaluateFeatureFlag(config.agent_share, userId),
enableGatewayMux: evaluateFeatureFlag(config.agent_gateway_mux, userId),
enableLlmRelay: evaluateFeatureFlag(config.agent_llm_relay, userId),
+ enableDashboard: evaluateFeatureFlag(config.dashboard, userId),
showProvider: evaluateFeatureFlag(config.provider_settings, userId),
showOpenAIApiKey: evaluateFeatureFlag(config.openai_api_key, userId),
diff --git a/packages/app-config/src/featureFlags/utils/parser.test.ts b/packages/app-config/src/featureFlags/utils/parser.test.ts
index 227dbdcaf90..02f5977f664 100644
--- a/packages/app-config/src/featureFlags/utils/parser.test.ts
+++ b/packages/app-config/src/featureFlags/utils/parser.test.ts
@@ -24,6 +24,11 @@ describe('parseFeatureFlag', () => {
});
});
+ it('should toggle dashboards with +dashboard / -dashboard', () => {
+ expect(parseFeatureFlag('+dashboard')).toEqual({ dashboard: true });
+ expect(parseFeatureFlag('-dashboard')).toEqual({ dashboard: false });
+ });
+
it('should hide content with commercial flags', () => {
const input = '+commercial_hide_github,+commercial_hide_docs';
expect(parseFeatureFlag(input)).toEqual({
diff --git a/packages/app-config/src/routes/index.ts b/packages/app-config/src/routes/index.ts
index eccee8891a8..be6339a5aae 100644
--- a/packages/app-config/src/routes/index.ts
+++ b/packages/app-config/src/routes/index.ts
@@ -3,6 +3,7 @@ import {
BrainCircuit,
FilePenIcon,
Image,
+ LayoutDashboardIcon,
LibraryBigIcon,
ListTodoIcon,
Settings,
@@ -107,6 +108,15 @@ export const NAVIGATION_ROUTES: NavigationRoute[] = [
path: '/tasks',
pathPrefix: '/tasks',
},
+ {
+ cmdkKey: 'tab.dashboard',
+ electronKey: 'navigation.dashboard',
+ icon: LayoutDashboardIcon,
+ id: 'dashboard',
+ keywords: ['dashboard', 'monitor', 'metrics', 'widget'],
+ path: '/dashboard',
+ pathPrefix: '/dashboard',
+ },
{
cmdkKey: 'cmdk.settings',
electronKey: 'navigation.settings',
diff --git a/packages/builtin-tool-dashboard/package.json b/packages/builtin-tool-dashboard/package.json
new file mode 100644
index 00000000000..8e0ca8b9be0
--- /dev/null
+++ b/packages/builtin-tool-dashboard/package.json
@@ -0,0 +1,22 @@
+{
+ "name": "@lobechat/builtin-tool-dashboard",
+ "version": "1.0.0",
+ "private": true,
+ "exports": {
+ ".": "./src/index.ts",
+ "./client": "./src/client/index.ts",
+ "./client/executor": "./src/client/executor/index.ts",
+ "./executionRuntime": "./src/ExecutionRuntime/index.ts"
+ },
+ "main": "./src/index.ts",
+ "devDependencies": {
+ "@lobechat/types": "workspace:*"
+ },
+ "peerDependencies": {
+ "@lobehub/ui": "^5",
+ "antd-style": "*",
+ "lucide-react": "*",
+ "react": "*",
+ "react-i18next": "*"
+ }
+}
diff --git a/packages/builtin-tool-dashboard/src/ExecutionRuntime/index.test.ts b/packages/builtin-tool-dashboard/src/ExecutionRuntime/index.test.ts
new file mode 100644
index 00000000000..5de864cf41f
--- /dev/null
+++ b/packages/builtin-tool-dashboard/src/ExecutionRuntime/index.test.ts
@@ -0,0 +1,392 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import type {
+ DryRunWidgetParams,
+ RequestPublishParams,
+ WidgetRunRecord,
+ WidgetVersionRecord,
+} from '../types';
+import { DashboardExecutionRuntime, type DashboardToolService, tailExcerpt } from './index';
+
+const version = (patch: Partial<WidgetVersionRecord> = {}): WidgetVersionRecord => ({
+ id: 'v1',
+ manifest: { network: { allow: ['api.github.com'] } },
+ outputType: 'stat',
+ runtime: 'node',
+ script: 'console.log(JSON.stringify({ type: "stat", value: 1 }))',
+ status: 'draft',
+ version: 1,
+ view: null,
+ ...patch,
+});
+
+const run = (patch: Partial<WidgetRunRecord> = {}): WidgetRunRecord => ({
+ durationMs: 812,
+ error: null,
+ exitCode: 0,
+ id: 'r1',
+ output: { type: 'stat', value: 42 },
+ status: 'succeeded',
+ stderr: '',
+ stdout: '{"type":"stat","value":42}',
+ trigger: 'preview',
+ versionId: 'v1',
+ ...patch,
+});
+
+const createService = (): { [K in keyof DashboardToolService]: ReturnType<typeof vi.fn> } => ({
+ addToDashboard: vi.fn(async () => ({ title: 'Ops' })),
+ createDashboardWithWidget: vi.fn(async (title: string) => ({ id: 'd-new', title })),
+ createWidgetDraft: vi.fn(async () => ({ version: version(), widgetId: 'w1' })),
+ dryRun: vi.fn(async () => run()),
+ getRun: vi.fn(async () => run()),
+ getWidget: vi.fn(async () => ({ draftVersion: version(), id: 'w1', title: 'Stars' })),
+ listDashboards: vi.fn(async () => []),
+ listRuns: vi.fn(async () => []),
+ listWidgets: vi.fn(async () => []),
+ publish: vi.fn(async () => ({
+ firstRunStatus: 'succeeded',
+ schedulePattern: '0 * * * *',
+ version: version({ status: 'published' }),
+ })),
+ saveDraft: vi.fn(async () => version({ id: 'v2', version: 2 })),
+ updateWidget: vi.fn(async () => undefined),
+});
+
+let service: ReturnType<typeof createService>;
+let runtime: DashboardExecutionRuntime;
+
+beforeEach(() => {
+ service = createService();
+ runtime = new DashboardExecutionRuntime(service as unknown as DashboardToolService);
+});
+
+describe('listDashboards', () => {
+ it('lists boards with their widgets and the agent’s own widgets', async () => {
+ service.listDashboards.mockResolvedValue([
+ { id: 'd0', projectId: 'prj_1', title: 'Launch', widgets: [] },
+ { id: 'd1', title: 'Ops', widgets: [{ id: 'w1', title: 'Stars' }] },
+ ]);
+ service.listWidgets.mockResolvedValue([
+ { hasDraft: true, id: 'w2', lastRunStatus: 'failed', published: false, title: 'Bugs' },
+ ]);
+
+ const result = await runtime.listDashboards();
+
+ expect(result.success).toBe(true);
+ expect(result.content).toContain('"Launch" (d0) [project]: no widgets');
+ expect(result.content).toContain('"Ops" (d1): "Stars" (w1)');
+ expect(result.content).toContain('"Bugs" (w2): not published, has draft, last run failed');
+ expect(result.state.dashboards).toHaveLength(2);
+ });
+
+ it('shows the current draft version id so the model can pin it', async () => {
+ service.listWidgets.mockResolvedValue([
+ { draftVersionId: 'v7', hasDraft: true, id: 'w2', published: true, title: 'Bugs' },
+ ]);
+ const result = await runtime.listDashboards();
+ expect(result.content).toContain('"Bugs" (w2): published, draft version id v7');
+ });
+
+ it('points at creating a board when there is none', async () => {
+ const result = await runtime.listDashboards();
+ expect(result.content).toContain('newDashboardTitle');
+ });
+});
+
+describe('createWidgetDraft', () => {
+ it('creates the widget with its first draft and asks for a dry run', async () => {
+ const result = await runtime.createWidgetDraft({
+ description: 'Stars of lobehub/lobehub',
+ outputType: 'stat',
+ runtime: 'node',
+ script: 'x',
+ title: 'Stars',
+ });
+
+ expect(service.createWidgetDraft).toHaveBeenCalledWith({
+ content: { outputType: 'stat', runtime: 'node', script: 'x' },
+ description: 'Stars of lobehub/lobehub',
+ title: 'Stars',
+ });
+ expect(result).toMatchObject({
+ state: { version: 1, versionId: 'v1', widgetId: 'w1' },
+ success: true,
+ });
+ expect(result.content).toContain('dryRunWidget');
+ });
+
+ it('returns the refusal as a failed result', async () => {
+ service.createWidgetDraft.mockRejectedValue(new Error('Invalid widget draft: script too long'));
+ const result = await runtime.createWidgetDraft({
+ description: '',
+ outputType: 'stat',
+ runtime: 'node',
+ script: 'x',
+ title: 'Stars',
+ });
+ expect(result).toMatchObject({ success: false });
+ expect(result.content).toContain('script too long');
+ });
+});
+
+describe('updateWidgetDraft', () => {
+ it('keeps unchanged fields from the current draft and links the parent version', async () => {
+ const result = await runtime.updateWidgetDraft({ script: 'fixed', widgetId: 'w1' });
+
+ expect(service.saveDraft).toHaveBeenCalledWith('w1', {
+ changeNote: null,
+ manifest: { network: { allow: ['api.github.com'] } },
+ outputType: 'stat',
+ parentVersionId: 'v1',
+ runtime: 'node',
+ script: 'fixed',
+ view: null,
+ });
+ expect(result).toMatchObject({ state: { version: 2, versionId: 'v2' }, success: true });
+ });
+
+ it('falls back to the published version when there is no draft', async () => {
+ service.getWidget.mockResolvedValue({
+ id: 'w1',
+ publishedVersion: version({ id: 'v-live', status: 'published' }),
+ title: 'Stars',
+ });
+ await runtime.updateWidgetDraft({ view: { limit: 5 }, widgetId: 'w1' });
+ expect(service.saveDraft).toHaveBeenCalledWith(
+ 'w1',
+ expect.objectContaining({ parentVersionId: 'v-live', view: { limit: 5 } }),
+ );
+ });
+
+ it('only renames when no content changes', async () => {
+ const result = await runtime.updateWidgetDraft({ title: 'Stars (7d)', widgetId: 'w1' });
+ expect(service.updateWidget).toHaveBeenCalledWith('w1', {
+ description: undefined,
+ title: 'Stars (7d)',
+ });
+ expect(service.saveDraft).not.toHaveBeenCalled();
+ expect(result.success).toBe(true);
+ });
+
+ it('says so when identical content reuses the draft', async () => {
+ service.saveDraft.mockResolvedValue(version());
+ const result = await runtime.updateWidgetDraft({ script: 'same', widgetId: 'w1' });
+ expect(result.content).toContain('identical');
+ });
+
+ it('leaves the title and description untouched when the draft is refused', async () => {
+ service.saveDraft.mockRejectedValue(new Error('Invalid widget draft: manifest.env'));
+
+ const result = await runtime.updateWidgetDraft({
+ description: 'New definition',
+ script: 'console.log(1)',
+ title: 'Renamed',
+ widgetId: 'w1',
+ });
+
+ expect(result.success).toBe(false);
+ expect(service.updateWidget).not.toHaveBeenCalled();
+ });
+
+ it('saves the draft before renaming when both change', async () => {
+ await runtime.updateWidgetDraft({ script: 'console.log(2)', title: 'Renamed', widgetId: 'w1' });
+ expect(service.saveDraft.mock.invocationCallOrder[0]).toBeLessThan(
+ service.updateWidget.mock.invocationCallOrder[0],
+ );
+ });
+
+ it('renames nothing when there is no version to keep', async () => {
+ service.getWidget.mockResolvedValue({ id: 'w1', title: 'Stars' });
+ const result = await runtime.updateWidgetDraft({ title: 'Renamed', widgetId: 'w1' });
+ expect(result.success).toBe(false);
+ expect(service.updateWidget).not.toHaveBeenCalled();
+ });
+
+ it('fails for an unknown widget', async () => {
+ service.getWidget.mockResolvedValue(undefined);
+ const result = await runtime.updateWidgetDraft({ script: 'x', widgetId: 'nope' });
+ expect(result).toMatchObject({ success: false });
+ });
+});
+
+describe('dryRunWidget', () => {
+ it('returns the real output of a successful run and points at publishing', async () => {
+ const result = await runtime.dryRunWidget({ versionId: 'v1', widgetId: 'w1' });
+
+ expect(result.success).toBe(true);
+ expect(result.content).toContain('Dry run succeeded');
+ expect(result.content).toContain('"value": 42');
+ expect(result.content).toContain('requestPublish');
+ expect(result.state).toMatchObject({ runId: 'r1', status: 'succeeded', versionId: 'v1' });
+ });
+
+ it('treats a partial run as working but asks to report what is missing', async () => {
+ service.dryRun.mockResolvedValue(run({ status: 'partial' }));
+
+ const result = await runtime.dryRunWidget({ versionId: 'v1', widgetId: 'w1' });
+
+ expect(result.success).toBe(true);
+ expect(result.content).toContain('Dry run partial');
+ expect(result.content).toContain('incomplete result');
+ expect(result.state).toMatchObject({ status: 'partial' });
+ });
+
+ it('gives a failing script back with its logs and a repair hint, as a normal result', async () => {
+ service.dryRun.mockResolvedValue(
+ run({
+ error: { code: 'INVALID_JSON', message: 'stdout is not a JSON document' },
+ exitCode: 0,
+ output: null,
+ status: 'failed',
+ stderr: 'warning: deprecated',
+ stdout: 'fetching…\n{"type":"stat","value":1}',
+ }),
+ );
+
+ const result = await runtime.dryRunWidget({ versionId: 'v1', widgetId: 'w1' });
+
+ // The model repairs the script from this, so the call itself succeeds.
+ expect(result.success).toBe(true);
+ expect(result.content).toContain('[INVALID_JSON]');
+ expect(result.content).toContain('move every other print/echo to stderr');
+ expect(result.content).toContain('stdout:\nfetching…');
+ expect(result.content).toContain('stderr:\nwarning: deprecated');
+ expect(result.content).toContain('updateWidgetDraft');
+ expect(result.state).toMatchObject({ error: { code: 'INVALID_JSON' }, status: 'failed' });
+ });
+
+ it('runs exactly the named version and never falls back to the current draft', async () => {
+ const result = await runtime.dryRunWidget({ widgetId: 'w1' } as DryRunWidgetParams);
+
+ expect(service.dryRun).not.toHaveBeenCalled();
+ expect(result.success).toBe(false);
+ expect(result.content).toContain('versionId is required');
+
+ await runtime.dryRunWidget({ versionId: 'v4', widgetId: 'w1' });
+ expect(service.dryRun).toHaveBeenCalledWith('w1', 'v4');
+ });
+
+ it('fails when the widget cannot be dry-run at all', async () => {
+ service.dryRun.mockRejectedValue(new Error('Only the widget creator can change it'));
+ const result = await runtime.dryRunWidget({ versionId: 'v1', widgetId: 'w1' });
+ expect(result).toMatchObject({ success: false });
+ });
+});
+
+describe('requestPublish', () => {
+ it('publishes the pinned version and reports the first live run', async () => {
+ const result = await runtime.requestPublish({ versionId: 'v1', widgetId: 'w1' });
+
+ expect(service.publish).toHaveBeenCalledWith('w1', 'v1');
+ expect(result.success).toBe(true);
+ expect(result.content).toContain('refreshes on "0 * * * *"');
+ expect(result.content).toContain('First live run: succeeded');
+ });
+
+ it('relays the dry-run gate', async () => {
+ service.publish.mockRejectedValue(new Error('dry-run it before publishing'));
+ const result = await runtime.requestPublish({ versionId: 'v9', widgetId: 'w1' });
+ expect(service.publish).toHaveBeenCalledWith('w1', 'v9');
+ expect(result).toMatchObject({ success: false });
+ expect(result.content).toContain('dry-run it before publishing');
+ });
+
+ it('never re-reads the current draft when no version was pinned', async () => {
+ // A newer draft saved while the approval was pending must not go live.
+ service.getWidget.mockResolvedValue({
+ draftVersion: version({ id: 'v-newer', version: 2 }),
+ id: 'w1',
+ title: 'Stars',
+ });
+
+ const result = await runtime.requestPublish({ widgetId: 'w1' } as RequestPublishParams);
+
+ expect(service.getWidget).not.toHaveBeenCalled();
+ expect(service.publish).not.toHaveBeenCalled();
+ expect(result.success).toBe(false);
+ expect(result.content).toContain('versionId is required');
+ });
+});
+
+describe('addWidgetToDashboard', () => {
+ it('places the widget on an existing board', async () => {
+ const result = await runtime.addWidgetToDashboard({ dashboardId: 'd1', widgetId: 'w1' });
+ expect(service.createDashboardWithWidget).not.toHaveBeenCalled();
+ expect(result).toMatchObject({
+ state: { createdDashboard: false, dashboardId: 'd1', dashboardTitle: 'Ops' },
+ success: true,
+ });
+ });
+
+ it('creates the board and the placement in one operation when asked', async () => {
+ const result = await runtime.addWidgetToDashboard({
+ newDashboardTitle: ' Team health ',
+ widgetId: 'w1',
+ });
+ expect(service.createDashboardWithWidget).toHaveBeenCalledWith('Team health', 'w1');
+ expect(service.addToDashboard).not.toHaveBeenCalled();
+ expect(result.state).toMatchObject({
+ createdDashboard: true,
+ dashboardId: 'd-new',
+ dashboardTitle: 'Team health',
+ });
+ });
+
+ it('reports a failed create-and-place without a separate board write', async () => {
+ service.createDashboardWithWidget.mockRejectedValue(new Error('Widget not found'));
+ const result = await runtime.addWidgetToDashboard({ newDashboardTitle: 'X', widgetId: 'w9' });
+ expect(result).toMatchObject({ success: false });
+ expect(result.content).toContain('Widget not found');
+ });
+
+ it('rejects a new-board title beyond the API limit before creating anything', async () => {
+ const result = await runtime.addWidgetToDashboard({
+ newDashboardTitle: 'x'.repeat(201),
+ widgetId: 'w1',
+ });
+ expect(result).toMatchObject({ success: false });
+ expect(result.content).toContain('at most 200 characters');
+ expect(service.createDashboardWithWidget).not.toHaveBeenCalled();
+ expect(service.addToDashboard).not.toHaveBeenCalled();
+ });
+
+ it('carries the board project so the card links to the project dashboard', async () => {
+ service.addToDashboard.mockResolvedValue({ projectId: 'prj_1', title: 'Project ops' });
+ const result = await runtime.addWidgetToDashboard({ dashboardId: 'd2', widgetId: 'w1' });
+ expect(result.state).toMatchObject({ dashboardId: 'd2', projectId: 'prj_1' });
+ });
+
+ it('needs a target', async () => {
+ const result = await runtime.addWidgetToDashboard({ widgetId: 'w1' });
+ expect(result.success).toBe(false);
+ });
+});
+
+describe('getWidgetRuns', () => {
+ it('lists recent runs with a clamped limit', async () => {
+ service.listRuns.mockResolvedValue([
+ run({ error: { code: 'TIMEOUT', message: 'too slow' }, id: 'r2', status: 'timeout' }),
+ run(),
+ ]);
+ const result = await runtime.getWidgetRuns({ limit: 500, widgetId: 'w1' });
+
+ expect(service.listRuns).toHaveBeenCalledWith('w1', 50);
+ expect(result.content).toContain('[TIMEOUT] too slow');
+ expect(result.state.runs.map((item: { id: string }) => item.id)).toEqual(['r2', 'r1']);
+ });
+
+ it('returns one run in full', async () => {
+ const result = await runtime.getWidgetRuns({ runId: 'r1', widgetId: 'w1' });
+ expect(service.getRun).toHaveBeenCalledWith('w1', 'r1');
+ expect(result.content).toContain('"value": 42');
+ });
+});
+
+describe('tailExcerpt', () => {
+ it('keeps the end of long logs, where errors are', () => {
+ const text = `${'a'.repeat(50)}END`;
+ expect(tailExcerpt(text, 10)).toBe('…(43 earlier chars omitted)\naaaaaaaEND');
+ expect(tailExcerpt(null)).toBe('');
+ });
+});
diff --git a/packages/builtin-tool-dashboard/src/ExecutionRuntime/index.ts b/packages/builtin-tool-dashboard/src/ExecutionRuntime/index.ts
new file mode 100644
index 00000000000..76aef749b34
--- /dev/null
+++ b/packages/builtin-tool-dashboard/src/ExecutionRuntime/index.ts
@@ -0,0 +1,508 @@
+import type { BuiltinServerRuntimeOutput } from '@lobechat/types';
+
+import {
+ type AddWidgetToDashboardParams,
+ type AddWidgetToDashboardState,
+ type CreateWidgetDraftParams,
+ DASHBOARD_TITLE_MAX_LENGTH,
+ type DashboardSummary,
+ type DashboardWidgetRecord,
+ type DashboardWidgetSummary,
+ type DryRunWidgetParams,
+ type DryRunWidgetState,
+ type GetWidgetRunsParams,
+ type GetWidgetRunsState,
+ type ListDashboardsState,
+ type RequestPublishParams,
+ type RequestPublishState,
+ type UpdateWidgetDraftParams,
+ type WidgetDraftState,
+ type WidgetRunRecord,
+ type WidgetVersionContent,
+ type WidgetVersionRecord,
+} from '../types';
+
+/**
+ * Data access the dashboard tool needs, bound by the host to the caller and to
+ * the conversation's ownership scope (agent / project / workspace). Methods
+ * throw on refused requests; the runtime turns the message into tool content.
+ */
+export interface DashboardToolService {
+ addToDashboard: (
+ dashboardId: string,
+ widgetId: string,
+ ) => Promise<{ projectId?: string | null; title: string }>;
+ /**
+ * Create a board and place the widget on it atomically: when the widget
+ * cannot be placed nothing is created. The board lives on the
+ * conversation's project in a project topic, else on the home level.
+ */
+ createDashboardWithWidget: (
+ title: string,
+ widgetId: string,
+ ) => Promise<{ id: string; projectId?: string | null; title: string }>;
+ /** Validate the content, create the widget and record its first draft. */
+ createWidgetDraft: (input: {
+ content: WidgetVersionContent;
+ description: string;
+ title: string;
+ }) => Promise<{ version: WidgetVersionRecord; widgetId: string }>;
+ dryRun: (widgetId: string, versionId: string) => Promise<WidgetRunRecord>;
+ getRun: (widgetId: string, runId: string) => Promise<WidgetRunRecord | undefined>;
+ getWidget: (widgetId: string) => Promise<DashboardWidgetRecord | undefined>;
+ /** The project's boards first (in a project topic), then the home boards. */
+ listDashboards: () => Promise<DashboardSummary[]>;
+ listRuns: (widgetId: string, limit: number) => Promise<WidgetRunRecord[]>;
+ /** Widgets owned at the conversation's level (this agent, in this project). */
+ listWidgets: () => Promise<DashboardWidgetSummary[]>;
+ publish: (
+ widgetId: string,
+ versionId: string,
+ ) => Promise<{
+ /** Status of the refresh run right after publishing, when one was attempted. */
+ firstRunStatus?: WidgetRunRecord['status'];
+ schedulePattern?: string | null;
+ version: WidgetVersionRecord;
+ }>;
+ saveDraft: (
+ widgetId: string,
+ input: WidgetVersionContent & { changeNote?: string | null; parentVersionId?: string | null },
+ ) => Promise<WidgetVersionRecord>;
+ updateWidget: (
+ widgetId: string,
+ patch: { description?: string; title?: string },
+ ) => Promise<void>;
+}
+
+/** How much of each log stream a tool result quotes. */
+export const LOG_EXCERPT_CHARS = 2000;
+/** How much of the output JSON a tool result quotes. */
+export const OUTPUT_EXCERPT_CHARS = 3000;
+
+const DEFAULT_RUN_LIMIT = 10;
+const MAX_RUN_LIMIT = 50;
+
+/** Keep the tail of a log (where errors are) and say how much was cut. */
+export const tailExcerpt = (text: string | null | undefined, max = LOG_EXCERPT_CHARS) => {
+ if (!text) return '';
+ const trimmed = text.trimEnd();
+ if (trimmed.length <= max) return trimmed;
+ return `…(${trimmed.length - max} earlier chars omitted)\n${trimmed.slice(-max)}`;
+};
+
+const headExcerpt = (text: string, max = OUTPUT_EXCERPT_CHARS) =>
+ text.length <= max ? text : `${text.slice(0, max)}\n…(${text.length - max} more chars)`;
+
+/** What the model should do about each run error code. */
+const ERROR_HINTS: Record<string, string> = {
+ CREDENTIALS_ERROR:
+ 'The platform could not read the connected credentials. Retry later; if it persists ask the user to reconnect the connector.',
+ EMPTY_OUTPUT: 'Print exactly one JSON document to stdout (logs belong on stderr).',
+ INVALID_JSON:
+ 'stdout must contain only the JSON document — move every other print/echo to stderr.',
+ INVALID_OUTPUT:
+ 'The JSON does not match the output contract for this outputType; compare field names and types with the contract.',
+ MISSING_ENV:
+ "A required variable has no source. If the message lists a connector's headers, set manifest.env[].field to the right one with updateWidgetDraft; otherwise tell the user which connector to connect for this agent or workspace — never ask for the secret in chat.",
+ NON_ZERO_EXIT: 'The script failed; read stderr, fix the script and dry-run again.',
+ OUTPUT_TOO_LARGE: 'Trim the output: fewer rows / items / points (use view.limit for display).',
+ OUTPUT_TYPE_MISMATCH: 'The printed "type" differs from the widget outputType; align them.',
+ PARTIAL_OUTPUT:
+ 'The script reported an incomplete result (meta.complete=false). Fine if intended; otherwise fix the failing source.',
+ SANDBOX_BAD_REQUEST:
+ 'The sandbox rejected the request; check runtime and manifest.timeoutMs (max 120000).',
+ SANDBOX_ERROR: 'The sandbox itself failed, not the script. Retry the dry run once.',
+ SANDBOX_NOT_CONFIGURED:
+ 'Script execution is not configured on this server. Tell the user; do not retry.',
+ SANDBOX_UNAUTHORIZED:
+ 'The sandbox rejected the platform credentials. Tell the user; do not retry.',
+ TIMEOUT: 'The script exceeded its time limit; make it do less or raise manifest.timeoutMs.',
+};
+
+const errorMessage = (error: unknown) =>
+ error instanceof Error ? error.message : String(error ?? 'Unknown error');
+
+const fail = (error: unknown, action: string): BuiltinServerRuntimeOutput => {
+ const message = errorMessage(error);
+ return { content: `Failed to ${action}: ${message}`, error: { message }, success: false };
+};
+
+const formatRunHead = (run: WidgetRunRecord, version?: number) =>
+ [
+ `run ${run.id}`,
+ version !== undefined && `v${version}`,
+ run.trigger,
+ run.status,
+ typeof run.durationMs === 'number' && `${run.durationMs}ms`,
+ run.startedAt && new Date(run.startedAt).toISOString(),
+ ]
+ .filter(Boolean)
+ .join(' · ');
+
+/** The full, model-facing account of one run: output or error, and both log tails. */
+export const formatRunDetail = (run: WidgetRunRecord) => {
+ const lines: string[] = [];
+ if (run.error) {
+ lines.push(`error: [${run.error.code}] ${run.error.message}`);
+ const hint = ERROR_HINTS[run.error.code];
+ if (hint) lines.push(`hint: ${hint}`);
+ }
+ if (typeof run.exitCode === 'number') lines.push(`exit code: ${run.exitCode}`);
+ if (run.output) {
+ lines.push(`output (${run.output.type}):`, headExcerpt(JSON.stringify(run.output, null, 2)));
+ }
+ // A good output already says what stdout held; quote stdout only when it did not parse.
+ if (!run.output) {
+ const stdout = tailExcerpt(run.stdout);
+ lines.push(stdout ? `stdout:\n${stdout}` : 'stdout: (empty)');
+ }
+ const stderr = tailExcerpt(run.stderr);
+ if (stderr) lines.push(`stderr:\n${stderr}`);
+ return lines.join('\n');
+};
+
+const versionLabel = (version: Pick<WidgetVersionRecord, 'status' | 'version'>) =>
+ `v${version.version} (${version.status})`;
+
+export class DashboardExecutionRuntime {
+ constructor(private readonly service: DashboardToolService) {}
+
+ async listDashboards(): Promise<BuiltinServerRuntimeOutput> {
+ try {
+ const [dashboards, widgets] = await Promise.all([
+ this.service.listDashboards(),
+ this.service.listWidgets(),
+ ]);
+ const state: ListDashboardsState = { dashboards, widgets };
+
+ const boardLines = dashboards.length
+ ? dashboards.map((board) => {
+ const placed = board.widgets.map((w) => `"${w.title}" (${w.id})`).join(', ');
+ const level = board.projectId ? ' [project]' : '';
+ return `- "${board.title}" (${board.id})${level}: ${placed || 'no widgets'}`;
+ })
+ : ['- none yet (addWidgetToDashboard with newDashboardTitle creates one)'];
+ const widgetLines = widgets.length
+ ? widgets.map((widget) => {
+ const status = [
+ widget.published ? 'published' : 'not published',
+ widget.hasDraft &&
+ (widget.draftVersionId ? `draft version id ${widget.draftVersionId}` : 'has draft'),
+ widget.lastRunStatus && `last run ${widget.lastRunStatus}`,
+ ]
+ .filter(Boolean)
+ .join(', ');
+ return `- "${widget.title}" (${widget.id}): ${status}`;
+ })
+ : ['- none yet'];
+
+ return {
+ content: [
+ `Dashboards (${dashboards.length}):`,
+ ...boardLines,
+ '',
+ `Widgets owned by this agent (${widgets.length}):`,
+ ...widgetLines,
+ ].join('\n'),
+ state,
+ success: true,
+ };
+ } catch (error) {
+ return fail(error, 'list dashboards');
+ }
+ }
+
+ async createWidgetDraft(params: CreateWidgetDraftParams): Promise<BuiltinServerRuntimeOutput> {
+ try {
+ const { description, title, ...content } = params;
+ const { version, widgetId } = await this.service.createWidgetDraft({
+ content,
+ description,
+ title,
+ });
+ 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.`,
+ state,
+ success: true,
+ };
+ } catch (error) {
+ return fail(error, 'create widget');
+ }
+ }
+
+ async updateWidgetDraft(params: UpdateWidgetDraftParams): Promise<BuiltinServerRuntimeOutput> {
+ const { widgetId, title, description, changeNote, ...patch } = params;
+ try {
+ const widget = await this.service.getWidget(widgetId);
+ if (!widget) return fail(new Error('Widget not found'), 'update widget draft');
+
+ // Title / description are written only after everything else in the
+ // call succeeded, so a refused draft leaves the widget untouched and a
+ // retry starts from the same state.
+ const hasMetaPatch = title !== undefined || description !== undefined;
+ const writeMeta = () =>
+ hasMetaPatch
+ ? this.service.updateWidget(widgetId, { description, title })
+ : Promise.resolve();
+
+ const base = widget.draftVersion ?? widget.publishedVersion;
+ const hasContentPatch = Object.values(patch).some((value) => value !== undefined);
+ if (!hasContentPatch) {
+ if (!base) return fail(new Error('Widget has no version to keep'), 'update widget draft');
+ await writeMeta();
+ const state: WidgetDraftState = { version: base.version, versionId: base.id, widgetId };
+ return {
+ content: `Updated widget ${widgetId}'s title/description. Script unchanged (current ${versionLabel(base)}).`,
+ state,
+ success: true,
+ };
+ }
+
+ const merged: WidgetVersionContent = {
+ manifest: patch.manifest !== undefined ? patch.manifest : base?.manifest,
+ outputType: patch.outputType ?? base?.outputType ?? 'stat',
+ runtime: patch.runtime ?? base?.runtime ?? 'node',
+ script: patch.script ?? base?.script ?? '',
+ view: patch.view !== undefined ? patch.view : base?.view,
+ };
+ if (!merged.script) {
+ return fail(new Error('script is required for the first draft'), 'update widget draft');
+ }
+
+ const version = await this.service.saveDraft(widgetId, {
+ ...merged,
+ changeNote: changeNote ?? null,
+ parentVersionId: base?.id ?? null,
+ });
+ try {
+ await writeMeta();
+ } catch (error) {
+ return fail(
+ new Error(
+ `Saved draft ${versionLabel(version)} (version id ${version.id}), but the title/description were not updated: ${errorMessage(error)}`,
+ ),
+ 'update widget title/description',
+ );
+ }
+ const state: WidgetDraftState = { version: version.version, versionId: version.id, widgetId };
+ const reused = base && version.id === base.id;
+
+ return {
+ content: reused
+ ? `The content is identical to ${versionLabel(version)}; no new draft was needed. Call dryRunWidget if it has not succeeded yet.`
+ : `Saved draft ${versionLabel(version)} (version id ${version.id}) for widget ${widgetId}. Call dryRunWidget to execute it.`,
+ state,
+ success: true,
+ };
+ } catch (error) {
+ return fail(error, 'update widget draft');
+ }
+ }
+
+ async dryRunWidget(params: DryRunWidgetParams): Promise<BuiltinServerRuntimeOutput> {
+ // Run exactly the version named in the call — the one an approval card
+ // showed — never whatever the current draft is by now.
+ if (!params.versionId) {
+ return fail(
+ new Error(
+ 'versionId is required: pass the id returned by createWidgetDraft / updateWidgetDraft',
+ ),
+ 'dry-run widget',
+ );
+ }
+ try {
+ const run = await this.service.dryRun(params.widgetId, params.versionId);
+ const state: DryRunWidgetState = {
+ durationMs: run.durationMs,
+ error: run.error,
+ runId: run.id,
+ status: run.status,
+ versionId: run.versionId,
+ widgetId: params.widgetId,
+ };
+ const next =
+ run.status === 'succeeded'
+ ? 'The draft works. Check the numbers are plausible, then call requestPublish.'
+ : run.status === 'partial'
+ ? 'The draft works but reported an incomplete result (meta.complete: false). Make it complete if you can; otherwise tell the user what is missing before calling requestPublish.'
+ : 'Fix the script with updateWidgetDraft and dry-run again.';
+
+ return {
+ content: [`Dry run ${run.status}: ${formatRunHead(run)}`, formatRunDetail(run), next].join(
+ '\n',
+ ),
+ state,
+ // A failing script is a normal authoring result, not a tool failure:
+ // the model reads the logs and repairs it.
+ success: true,
+ };
+ } catch (error) {
+ return fail(error, 'dry-run widget');
+ }
+ }
+
+ async requestPublish(params: RequestPublishParams): Promise<BuiltinServerRuntimeOutput> {
+ try {
+ // Publish exactly the version the user reviewed and approved. Never fall
+ // back to re-reading "the current draft": a newer draft saved while the
+ // approval was pending would go live without review.
+ const versionId = params.versionId;
+ if (!versionId) {
+ return fail(
+ new Error(
+ 'versionId is required: pass the id of the dry-run draft the user should approve',
+ ),
+ 'publish widget',
+ );
+ }
+
+ const { firstRunStatus, schedulePattern, version } = await this.service.publish(
+ params.widgetId,
+ versionId,
+ );
+ const state: RequestPublishState = {
+ schedulePattern,
+ version: version.version,
+ versionId: version.id,
+ widgetId: params.widgetId,
+ };
+
+ return {
+ content: [
+ `The user approved: widget ${params.widgetId} v${version.version} is live${
+ schedulePattern ? ` and refreshes on "${schedulePattern}"` : ' (manual refresh only)'
+ }.`,
+ firstRunStatus &&
+ `First live run: ${firstRunStatus}${
+ firstRunStatus === 'succeeded' || firstRunStatus === 'partial'
+ ? ''
+ : ' — inspect it with getWidgetRuns'
+ }.`,
+ ]
+ .filter(Boolean)
+ .join(' '),
+ state,
+ success: true,
+ };
+ } catch (error) {
+ return fail(error, 'publish widget');
+ }
+ }
+
+ async addWidgetToDashboard(
+ params: AddWidgetToDashboardParams,
+ ): Promise<BuiltinServerRuntimeOutput> {
+ const newTitle = params.newDashboardTitle?.trim();
+ if (!params.dashboardId && !newTitle) {
+ return fail(
+ new Error('Pass dashboardId (from listDashboards) or newDashboardTitle'),
+ 'add widget to dashboard',
+ );
+ }
+ // The API refuses titles beyond 200 characters — refuse here too, before
+ // a board is created, so a retry cannot pile malformed boards up.
+ if (newTitle && newTitle.length > DASHBOARD_TITLE_MAX_LENGTH) {
+ return fail(
+ new Error(
+ `newDashboardTitle must be at most ${DASHBOARD_TITLE_MAX_LENGTH} characters (got ${newTitle.length})`,
+ ),
+ 'add widget to dashboard',
+ );
+ }
+ try {
+ const createdDashboard = !params.dashboardId;
+ // A new board is created together with the placement, so a widget that
+ // cannot be placed never leaves an empty board behind for retries to pile up.
+ const {
+ id: dashboardId,
+ projectId,
+ title,
+ } = params.dashboardId
+ ? {
+ id: params.dashboardId,
+ ...(await this.service.addToDashboard(params.dashboardId, params.widgetId)),
+ }
+ : await this.service.createDashboardWithWidget(newTitle!, params.widgetId);
+ const state: AddWidgetToDashboardState = {
+ createdDashboard,
+ dashboardId,
+ dashboardTitle: title,
+ projectId: projectId ?? null,
+ widgetId: params.widgetId,
+ };
+
+ return {
+ content: `${createdDashboard ? `Created dashboard "${title}" (${dashboardId}) and placed` : 'Placed'} widget ${params.widgetId} on "${title}".`,
+ state,
+ success: true,
+ };
+ } catch (error) {
+ return fail(error, 'add widget to dashboard');
+ }
+ }
+
+ async getWidgetRuns(params: GetWidgetRunsParams): Promise<BuiltinServerRuntimeOutput> {
+ try {
+ if (params.runId) {
+ const run = await this.service.getRun(params.widgetId, params.runId);
+ if (!run) return fail(new Error('Run not found'), 'get widget run');
+ const state: GetWidgetRunsState = {
+ runs: [
+ {
+ durationMs: run.durationMs,
+ errorCode: run.error?.code,
+ id: run.id,
+ startedAt: run.startedAt,
+ status: run.status,
+ trigger: run.trigger,
+ },
+ ],
+ widgetId: params.widgetId,
+ };
+ return {
+ content: [formatRunHead(run), formatRunDetail(run)].join('\n'),
+ state,
+ success: true,
+ };
+ }
+
+ const limit = Math.min(
+ Math.max(Math.trunc(params.limit ?? DEFAULT_RUN_LIMIT), 1),
+ MAX_RUN_LIMIT,
+ );
+ const runs = await this.service.listRuns(params.widgetId, limit);
+ const state: GetWidgetRunsState = {
+ runs: runs.map((run) => ({
+ durationMs: run.durationMs,
+ errorCode: run.error?.code,
+ id: run.id,
+ startedAt: run.startedAt,
+ status: run.status,
+ trigger: run.trigger,
+ })),
+ widgetId: params.widgetId,
+ };
+ if (runs.length === 0) {
+ return { content: `Widget ${params.widgetId} has not run yet.`, state, success: true };
+ }
+
+ const lines = runs.map((run) => {
+ const error = run.error ? ` — [${run.error.code}] ${run.error.message}` : '';
+ return `- ${formatRunHead(run)}${error}`;
+ });
+ return {
+ content: [
+ `Last ${runs.length} runs of widget ${params.widgetId} (newest first):`,
+ ...lines,
+ 'Pass runId for a run’s full output and logs.',
+ ].join('\n'),
+ state,
+ success: true,
+ };
+ } catch (error) {
+ return fail(error, 'list widget runs');
+ }
+ }
+}
diff --git a/packages/builtin-tool-dashboard/src/client/Inspector/index.tsx b/packages/builtin-tool-dashboard/src/client/Inspector/index.tsx
new file mode 100644
index 00000000000..4e0f76783e1
--- /dev/null
+++ b/packages/builtin-tool-dashboard/src/client/Inspector/index.tsx
@@ -0,0 +1,121 @@
+'use client';
+
+import type { BuiltinInspector, BuiltinInspectorProps } from '@lobechat/types';
+import { createStaticStyles, cx } from 'antd-style';
+import { memo, type ReactNode } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { inspectorTextStyles, shinyTextStyles } from '@/styles';
+
+import type {
+ AddWidgetToDashboardState,
+ DashboardApiNameType,
+ DryRunWidgetState,
+ GetWidgetRunsState,
+ RequestPublishState,
+ WidgetDraftState,
+} from '../../types';
+import { DashboardApiName, DashboardIdentifier } from '../../types';
+
+const styles = createStaticStyles(({ css, cssVar }) => ({
+ chip: css`
+ overflow: hidden;
+ flex-shrink: 1;
+
+ min-width: 0;
+ margin-inline-start: 6px;
+ padding-block: 2px;
+ padding-inline: 8px;
+ border-radius: 999px;
+
+ font-size: 12px;
+ color: ${cssVar.colorTextSecondary};
+ text-overflow: ellipsis;
+ white-space: nowrap;
+
+ background: ${cssVar.colorFillTertiary};
+ `,
+ failed: css`
+ color: ${cssVar.colorError};
+ background: ${cssVar.colorErrorBg};
+ `,
+ succeeded: css`
+ color: ${cssVar.colorSuccess};
+ background: ${cssVar.colorSuccessBg};
+ `,
+}));
+
+type Props = BuiltinInspectorProps<Record<string, any>, any>;
+
+/** The one detail worth reading at a glance for each call, from args or the result. */
+const useChip = (apiName: DashboardApiNameType, props: Props): ReactNode => {
+ const { t } = useTranslation('dashboard');
+ const args = { ...props.partialArgs, ...props.args };
+
+ switch (apiName) {
+ case DashboardApiName.listDashboards: {
+ return 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;
+ }
+ case DashboardApiName.dryRunWidget: {
+ const state = props.pluginState as DryRunWidgetState | undefined;
+ if (!state) return undefined;
+ return (
+ <span
+ className={cx(
+ styles.chip,
+ state.status === 'succeeded' || state.status === 'partial'
+ ? styles.succeeded
+ : state.status !== 'running' && styles.failed,
+ )}
+ >
+ {state.error && state.status !== 'succeeded' && state.status !== 'partial'
+ ? state.error.code
+ : t(`run.status.${state.status}`)}
+ </span>
+ );
+ }
+ case DashboardApiName.requestPublish: {
+ const state = props.pluginState as RequestPublishState | undefined;
+ return state ? t('chat.preview.live', { version: state.version }) : undefined;
+ }
+ case DashboardApiName.addWidgetToDashboard: {
+ const state = props.pluginState as AddWidgetToDashboardState | undefined;
+ return state?.dashboardTitle ?? args.newDashboardTitle;
+ }
+ case DashboardApiName.getWidgetRuns: {
+ const state = props.pluginState as GetWidgetRunsState | undefined;
+ return state ? String(state.runs.length) : undefined;
+ }
+ }
+};
+
+const createInspector = (apiName: DashboardApiNameType) => {
+ const Inspector = memo<Props>((props) => {
+ const { t } = useTranslation('plugin');
+ const chip = useChip(apiName, props);
+
+ return (
+ <div className={inspectorTextStyles.root}>
+ <span
+ className={cx(
+ (props.isArgumentsStreaming || props.isLoading) && shinyTextStyles.shinyText,
+ )}
+ >
+ {t(`builtins.${DashboardIdentifier}.apiName.${apiName}`)}
+ </span>
+ {chip && (typeof chip === 'string' ? <span className={styles.chip}>{chip}</span> : chip)}
+ </div>
+ );
+ });
+ Inspector.displayName = `Dashboard${apiName}Inspector`;
+ return Inspector as unknown as BuiltinInspector;
+};
+
+export const DashboardInspectors: Record<string, BuiltinInspector> = Object.fromEntries(
+ Object.values(DashboardApiName).map((apiName) => [apiName, createInspector(apiName)]),
+);
diff --git a/packages/builtin-tool-dashboard/src/client/Intervention/index.tsx b/packages/builtin-tool-dashboard/src/client/Intervention/index.tsx
new file mode 100644
index 00000000000..ad0f4abd9b1
--- /dev/null
+++ b/packages/builtin-tool-dashboard/src/client/Intervention/index.tsx
@@ -0,0 +1,93 @@
+'use client';
+
+import type { BuiltinIntervention, BuiltinInterventionProps } from '@lobechat/types';
+import { memo, useCallback, useLayoutEffect } from 'react';
+
+import { DashboardFeatureGate } from '@/features/Dashboard/FeatureGate';
+import { useDashboardFeature } from '@/features/Dashboard/hooks/useDashboardFeature';
+import WidgetDryRunReview from '@/features/Dashboard/WidgetPreview/DryRunReview';
+import WidgetPublishReview from '@/features/Dashboard/WidgetPreview/PublishReview';
+
+import type { DryRunWidgetParams, RequestPublishParams } from '../../types';
+import { DashboardApiName } from '../../types';
+
+/**
+ * While no review renders — the dashboard feature is off or its flag is still
+ * loading, or the request names no widget — there is nothing to approve
+ * against: hold approval. Once the review mounts it reports its own readiness.
+ */
+const useHoldApprovalWithoutReview = (
+ widgetId: string | undefined,
+ onApprovalBlockedChange?: (blocked: boolean) => void,
+) => {
+ const { enabled } = useDashboardFeature();
+ const reviewable = enabled && !!widgetId;
+ useLayoutEffect(() => {
+ if (!reviewable) onApprovalBlockedChange?.(true);
+ }, [reviewable, onApprovalBlockedChange]);
+};
+
+/**
+ * The only way an agent gets a widget live: the user reviews the dry run,
+ * credentials, network, schedule and code diff here, then approves or rejects.
+ */
+const RequestPublishIntervention = memo<BuiltinInterventionProps<RequestPublishParams>>(
+ ({ args, onApprovalBlockedChange, onArgsChange }) => {
+ // A request without a version (older messages, a model that skipped it)
+ // gets the version on screen written into its args before approval, so
+ // the runtime publishes exactly what the user reviewed.
+ const pinVersion = useCallback(
+ (versionId: string) => onArgsChange?.({ ...args, versionId }),
+ [args, onArgsChange],
+ );
+ useHoldApprovalWithoutReview(args?.widgetId, onApprovalBlockedChange);
+
+ if (!args?.widgetId) return null;
+ return (
+ <DashboardFeatureGate>
+ <WidgetPublishReview
+ summary={args.summary}
+ versionId={args.versionId}
+ widgetId={args.widgetId}
+ onApprovalBlockedChange={onApprovalBlockedChange}
+ onPinVersion={pinVersion}
+ />
+ </DashboardFeatureGate>
+ );
+ },
+);
+
+RequestPublishIntervention.displayName = 'DashboardRequestPublishIntervention';
+
+/**
+ * Shown only for drafts that declare connector credentials or network hosts:
+ * the user approves running exactly this script with that access.
+ */
+const DryRunWidgetIntervention = memo<BuiltinInterventionProps<DryRunWidgetParams>>(
+ ({ args, onApprovalBlockedChange, onArgsChange }) => {
+ const pinVersion = useCallback(
+ (versionId: string) => onArgsChange?.({ ...args, versionId }),
+ [args, onArgsChange],
+ );
+ useHoldApprovalWithoutReview(args?.widgetId, onApprovalBlockedChange);
+
+ if (!args?.widgetId) return null;
+ return (
+ <DashboardFeatureGate>
+ <WidgetDryRunReview
+ versionId={args.versionId}
+ widgetId={args.widgetId}
+ onApprovalBlockedChange={onApprovalBlockedChange}
+ onPinVersion={pinVersion}
+ />
+ </DashboardFeatureGate>
+ );
+ },
+);
+
+DryRunWidgetIntervention.displayName = 'DashboardDryRunWidgetIntervention';
+
+export const DashboardInterventions: Record<string, BuiltinIntervention> = {
+ [DashboardApiName.dryRunWidget]: DryRunWidgetIntervention as BuiltinIntervention,
+ [DashboardApiName.requestPublish]: RequestPublishIntervention as BuiltinIntervention,
+};
diff --git a/packages/builtin-tool-dashboard/src/client/Render/AddedToDashboard.tsx b/packages/builtin-tool-dashboard/src/client/Render/AddedToDashboard.tsx
new file mode 100644
index 00000000000..6a5c620d73a
--- /dev/null
+++ b/packages/builtin-tool-dashboard/src/client/Render/AddedToDashboard.tsx
@@ -0,0 +1,50 @@
+'use client';
+
+import { Block, Flexbox, Icon } from '@lobehub/ui';
+import { Button, Text } from '@lobehub/ui/base-ui';
+import { cssVar } from 'antd-style';
+import { ArrowUpRightIcon, LayoutDashboardIcon } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { getDashboardPath } from '@/features/Dashboard/utils/path';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { useServerConfigStore } from '@/store/serverConfig';
+
+import type { AddWidgetToDashboardState } from '../../types';
+
+/** Where the widget landed, one click from the board itself. */
+const AddedToDashboard = memo<AddWidgetToDashboardState>(
+ ({ dashboardId, dashboardTitle, projectId }) => {
+ const { t } = useTranslation('dashboard');
+ const navigate = useWorkspaceAwareNavigate();
+ // Dashboard routes exist only in the desktop shell — on mobile the Open
+ // action would navigate nowhere, so the card just states the placement.
+ const isMobile = useServerConfigStore((s) => s.isMobile);
+
+ return (
+ <Block padding={10} variant={'outlined'} width={'100%'}>
+ <Flexbox horizontal align={'center'} gap={8}>
+ <Icon color={cssVar.colorTextSecondary} icon={LayoutDashboardIcon} size={16} />
+ <Text ellipsis style={{ flex: 1, minWidth: 0 }}>
+ {t('chat.added', { title: dashboardTitle })}
+ </Text>
+ {!isMobile && (
+ <Button
+ data-open-dashboard={dashboardId}
+ icon={ArrowUpRightIcon}
+ size={'small'}
+ onClick={() => navigate(getDashboardPath({ id: dashboardId, projectId }))}
+ >
+ {t('chat.openDashboard')}
+ </Button>
+ )}
+ </Flexbox>
+ </Block>
+ );
+ },
+);
+
+AddedToDashboard.displayName = 'DashboardAddedToDashboard';
+
+export default AddedToDashboard;
diff --git a/packages/builtin-tool-dashboard/src/client/Render/index.tsx b/packages/builtin-tool-dashboard/src/client/Render/index.tsx
new file mode 100644
index 00000000000..a940ee5fab7
--- /dev/null
+++ b/packages/builtin-tool-dashboard/src/client/Render/index.tsx
@@ -0,0 +1,65 @@
+'use client';
+
+import type { BuiltinRender, BuiltinRenderProps } from '@lobechat/types';
+import { memo } from 'react';
+
+import { DashboardFeatureGate } from '@/features/Dashboard/FeatureGate';
+import WidgetPreviewCard, { WidgetVersionPreviewCard } from '@/features/Dashboard/WidgetPreview';
+
+import type {
+ AddWidgetToDashboardState,
+ DryRunWidgetState,
+ RequestPublishState,
+} from '../../types';
+import { DashboardApiName } from '../../types';
+import AddedToDashboard from './AddedToDashboard';
+
+/**
+ * The dry run as it will look on a board, with publish / place / details
+ * actions. Every card here renders only while the `dashboard` flag is on.
+ */
+const DryRunWidgetRender = memo<BuiltinRenderProps<unknown, DryRunWidgetState>>(
+ ({ pluginState }) => {
+ if (!pluginState?.runId) return null;
+ return (
+ <DashboardFeatureGate>
+ <WidgetPreviewCard runId={pluginState.runId} widgetId={pluginState.widgetId} />
+ </DashboardFeatureGate>
+ );
+ },
+);
+DryRunWidgetRender.displayName = 'DashboardDryRunWidgetRender';
+
+/** After the user approved: the version that went live, with where to place it. */
+const RequestPublishRender = memo<BuiltinRenderProps<unknown, RequestPublishState>>(
+ ({ pluginState }) => {
+ if (!pluginState?.versionId) return null;
+ return (
+ <DashboardFeatureGate>
+ <WidgetVersionPreviewCard
+ versionId={pluginState.versionId}
+ widgetId={pluginState.widgetId}
+ />
+ </DashboardFeatureGate>
+ );
+ },
+);
+RequestPublishRender.displayName = 'DashboardRequestPublishRender';
+
+const AddWidgetToDashboardRender = memo<BuiltinRenderProps<unknown, AddWidgetToDashboardState>>(
+ ({ pluginState }) => {
+ if (!pluginState?.dashboardId) return null;
+ return (
+ <DashboardFeatureGate>
+ <AddedToDashboard {...pluginState} />
+ </DashboardFeatureGate>
+ );
+ },
+);
+AddWidgetToDashboardRender.displayName = 'DashboardAddWidgetToDashboardRender';
+
+export const DashboardRenders: Record<string, BuiltinRender> = {
+ [DashboardApiName.addWidgetToDashboard]: AddWidgetToDashboardRender as BuiltinRender,
+ [DashboardApiName.dryRunWidget]: DryRunWidgetRender as BuiltinRender,
+ [DashboardApiName.requestPublish]: RequestPublishRender as BuiltinRender,
+};
diff --git a/packages/builtin-tool-dashboard/src/client/executor/index.test.ts b/packages/builtin-tool-dashboard/src/client/executor/index.test.ts
new file mode 100644
index 00000000000..b6012e0f5f8
--- /dev/null
+++ b/packages/builtin-tool-dashboard/src/client/executor/index.test.ts
@@ -0,0 +1,130 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { dashboardService } from '@/services/dashboard';
+
+import { DashboardApiName } from '../../types';
+import { dashboardExecutor } from './index';
+
+const refreshWidget = vi.fn();
+const refreshWidgetPlacement = vi.fn();
+
+vi.mock('@/services/dashboard', () => ({
+ dashboardService: { runAgentTool: vi.fn() },
+}));
+vi.mock('@/store/dashboard', () => ({
+ useDashboardStore: { getState: () => ({ refreshWidget, refreshWidgetPlacement }) },
+}));
+
+beforeEach(() => {
+ vi.mocked(dashboardService.runAgentTool).mockReset();
+ refreshWidget.mockReset();
+ refreshWidgetPlacement.mockReset();
+});
+
+describe('dashboardExecutor', () => {
+ it('exposes every API', () => {
+ for (const api of Object.values(DashboardApiName))
+ expect(dashboardExecutor.hasApi(api)).toBe(true);
+ });
+
+ it('runs the call server-side with the conversation context', async () => {
+ vi.mocked(dashboardService.runAgentTool).mockResolvedValue({
+ content: 'Dry run succeeded',
+ state: { runId: 'r1' },
+ success: true,
+ });
+
+ const result = await dashboardExecutor.invoke(
+ DashboardApiName.dryRunWidget,
+ { widgetId: 'w1' },
+ { agentId: 'agt_1', messageId: 'msg_1', operationId: 'op_1', topicId: 'tpc_1' },
+ );
+
+ expect(dashboardService.runAgentTool).toHaveBeenCalledWith(
+ 'dryRunWidget',
+ { widgetId: 'w1' },
+ { agentId: 'agt_1', messageId: 'msg_1', operationId: 'op_1', topicId: 'tpc_1' },
+ );
+ expect(result).toEqual({ content: 'Dry run succeeded', state: { runId: 'r1' }, success: true });
+ });
+
+ it('keeps content and state on a refused call', async () => {
+ vi.mocked(dashboardService.runAgentTool).mockResolvedValue({
+ content: 'Failed to publish widget: dry-run it first',
+ error: { message: 'dry-run it first' },
+ success: false,
+ });
+
+ const result = await dashboardExecutor.invoke(
+ DashboardApiName.requestPublish,
+ { widgetId: 'w1' },
+ { messageId: 'msg_1' },
+ );
+
+ expect(result).toMatchObject({
+ content: 'Failed to publish widget: dry-run it first',
+ error: { message: 'dry-run it first', type: 'PluginServerError' },
+ success: false,
+ });
+ });
+
+ it('turns a transport failure into a readable result', async () => {
+ vi.mocked(dashboardService.runAgentTool).mockRejectedValue(new Error('UNAUTHORIZED'));
+ const result = await dashboardExecutor.invoke(
+ DashboardApiName.listDashboards,
+ {},
+ { messageId: 'msg_1' },
+ );
+ expect(result).toMatchObject({
+ content: 'Failed to run listDashboards: UNAUTHORIZED',
+ success: false,
+ });
+ });
+
+ it('syncs open views after a call the client runtime ran', async () => {
+ vi.mocked(dashboardService.runAgentTool).mockResolvedValue({
+ content: 'Placed widget w1 on "Open-source health".',
+ state: { createdDashboard: false, dashboardId: 'd1', widgetId: 'w1' },
+ success: true,
+ });
+
+ await dashboardExecutor.invoke(
+ DashboardApiName.addWidgetToDashboard,
+ { dashboardId: 'd1', widgetId: 'w1' },
+ { messageId: 'msg_1', topicId: 'tpc_1' },
+ );
+
+ expect(refreshWidgetPlacement).toHaveBeenCalledWith('w1', 'd1');
+ });
+
+ describe('onAfterCall', () => {
+ const after = (apiName: string, params: unknown, result: Record<string, unknown>) =>
+ dashboardExecutor.onAfterCall({
+ apiName,
+ identifier: 'lobe-dashboard',
+ params,
+ result: { content: '', success: true, ...result },
+ });
+
+ it('syncs the widget placement the agent made server-side', async () => {
+ await after(
+ DashboardApiName.addWidgetToDashboard,
+ { newDashboardTitle: 'Open-source health', widgetId: 'w1' },
+ { state: { createdDashboard: true, dashboardId: 'd1', widgetId: 'w1' } },
+ );
+ expect(refreshWidgetPlacement).toHaveBeenCalledWith('w1', 'd1');
+ });
+
+ it('refreshes a widget the agent changed', async () => {
+ await after(DashboardApiName.requestPublish, { widgetId: 'w1' }, {});
+ expect(refreshWidget).toHaveBeenCalledWith('w1');
+ });
+
+ it('leaves caches alone for failed and read-only calls', async () => {
+ await after(DashboardApiName.addWidgetToDashboard, { widgetId: 'w1' }, { success: false });
+ await after(DashboardApiName.getWidgetRuns, { widgetId: 'w1' }, {});
+ expect(refreshWidgetPlacement).not.toHaveBeenCalled();
+ expect(refreshWidget).not.toHaveBeenCalled();
+ });
+ });
+});
diff --git a/packages/builtin-tool-dashboard/src/client/executor/index.ts b/packages/builtin-tool-dashboard/src/client/executor/index.ts
new file mode 100644
index 00000000000..2773c85593a
--- /dev/null
+++ b/packages/builtin-tool-dashboard/src/client/executor/index.ts
@@ -0,0 +1,123 @@
+import type {
+ BuiltinServerRuntimeOutput,
+ BuiltinToolContext,
+ BuiltinToolResult,
+ ToolAfterCallContext,
+} from '@lobechat/types';
+import { BaseExecutor } from '@lobechat/types';
+import debug from 'debug';
+
+import { dashboardService } from '@/services/dashboard';
+import { useDashboardStore } from '@/store/dashboard';
+
+import type { AddWidgetToDashboardState, DashboardApiNameType } from '../../types';
+import { DashboardApiName, DashboardIdentifier } from '../../types';
+
+const log = debug('lobe-dashboard:executor');
+
+/** Calls that change a widget the Portal or a board may already show. */
+const WIDGET_MUTATING_APIS = new Set<string>([
+ DashboardApiName.dryRunWidget,
+ DashboardApiName.requestPublish,
+ DashboardApiName.updateWidgetDraft,
+]);
+
+/**
+ * Client-runtime executor. Every call runs server-side through
+ * `dashboard.runAgentTool` — the same `DashboardExecutionRuntime` and scoped
+ * service the server agent runtime uses — so both runtimes stamp the same
+ * ownership (agent / project / workspace) and draft provenance.
+ */
+class DashboardExecutor extends BaseExecutor<typeof DashboardApiName> {
+ readonly identifier = DashboardIdentifier;
+ protected readonly apiEnum = DashboardApiName;
+
+ listDashboards = (params: unknown, ctx?: BuiltinToolContext) =>
+ this.run(DashboardApiName.listDashboards, params, ctx);
+
+ createWidgetDraft = (params: unknown, ctx?: BuiltinToolContext) =>
+ this.run(DashboardApiName.createWidgetDraft, params, ctx);
+
+ updateWidgetDraft = (params: unknown, ctx?: BuiltinToolContext) =>
+ this.run(DashboardApiName.updateWidgetDraft, params, ctx);
+
+ dryRunWidget = (params: unknown, ctx?: BuiltinToolContext) =>
+ this.run(DashboardApiName.dryRunWidget, params, ctx);
+
+ requestPublish = (params: unknown, ctx?: BuiltinToolContext) =>
+ this.run(DashboardApiName.requestPublish, params, ctx);
+
+ addWidgetToDashboard = (params: unknown, ctx?: BuiltinToolContext) =>
+ this.run(DashboardApiName.addWidgetToDashboard, params, ctx);
+
+ getWidgetRuns = (params: unknown, ctx?: BuiltinToolContext) =>
+ this.run(DashboardApiName.getWidgetRuns, params, ctx);
+
+ /**
+ * The call changed dashboard data outside the dashboard store (server-side,
+ * from either runtime): revalidate what an open Portal or board already shows —
+ * e.g. the widget's "on boards" section after the agent places it.
+ */
+ onAfterCall = async ({ apiName, params, result }: ToolAfterCallContext) => {
+ if (!result.success) return;
+ const widgetId = (params as { widgetId?: unknown } | undefined)?.widgetId;
+ if (typeof widgetId !== 'string') return;
+
+ const store = useDashboardStore.getState();
+ try {
+ if (apiName === DashboardApiName.addWidgetToDashboard) {
+ const state = result.state as Partial<AddWidgetToDashboardState> | undefined;
+ await store.refreshWidgetPlacement(widgetId, state?.dashboardId);
+ } else if (WIDGET_MUTATING_APIS.has(apiName)) {
+ await store.refreshWidget(widgetId);
+ }
+ } catch (error) {
+ log('refresh after %s failed: %o', apiName, error);
+ }
+ };
+
+ private run = async (
+ apiName: DashboardApiNameType,
+ params: unknown,
+ ctx?: BuiltinToolContext,
+ ): Promise<BuiltinToolResult> => {
+ try {
+ log('%s params=%o', apiName, params);
+ const output = await dashboardService.runAgentTool(apiName, params, {
+ agentId: ctx?.agentId,
+ messageId: ctx?.messageId,
+ operationId: ctx?.operationId,
+ topicId: ctx?.topicId ?? undefined,
+ });
+ const result = this.toResult(output);
+ // The client runtime never fires `onAfterCall` (only streamed gateway
+ // results do), so sync open views here too.
+ await this.onAfterCall({ apiName, identifier: this.identifier, params, result });
+ return result;
+ } catch (error) {
+ const message = error instanceof Error ? error.message : String(error);
+ return {
+ content: `Failed to run ${apiName}: ${message}`,
+ error: { message, type: 'DashboardToolFailed' },
+ success: false,
+ };
+ }
+ };
+
+ private toResult(output: BuiltinServerRuntimeOutput): BuiltinToolResult {
+ const errorMessage =
+ typeof output.error?.message === 'string' ? output.error.message : undefined;
+ const content = output.content || errorMessage || 'Tool execution failed';
+ if (!output.success) {
+ return {
+ content,
+ error: { body: output.error, message: errorMessage ?? content, type: 'PluginServerError' },
+ state: output.state,
+ success: false,
+ };
+ }
+ return { content, state: output.state, success: true };
+ }
+}
+
+export const dashboardExecutor = new DashboardExecutor();
diff --git a/packages/builtin-tool-dashboard/src/client/index.ts b/packages/builtin-tool-dashboard/src/client/index.ts
new file mode 100644
index 00000000000..8411b08fda4
--- /dev/null
+++ b/packages/builtin-tool-dashboard/src/client/index.ts
@@ -0,0 +1,5 @@
+export { DashboardIdentifier, DashboardManifest } from '../manifest';
+export * from '../types';
+export { DashboardInspectors } from './Inspector';
+export { DashboardInterventions } from './Intervention';
+export { DashboardRenders } from './Render';
diff --git a/packages/builtin-tool-dashboard/src/index.ts b/packages/builtin-tool-dashboard/src/index.ts
new file mode 100644
index 00000000000..840bc3b83ce
--- /dev/null
+++ b/packages/builtin-tool-dashboard/src/index.ts
@@ -0,0 +1,9 @@
+export {
+ createDryRunAudit,
+ DASHBOARD_DRY_RUN_AUDIT,
+ type DryRunAuditOptions,
+ dryRunNeedsApproval,
+} from './interventionAudit';
+export { DashboardIdentifier, DashboardManifest } from './manifest';
+export { systemPrompt } from './systemRole';
+export * from './types';
diff --git a/packages/builtin-tool-dashboard/src/interventionAudit.test.ts b/packages/builtin-tool-dashboard/src/interventionAudit.test.ts
new file mode 100644
index 00000000000..b97c87de369
--- /dev/null
+++ b/packages/builtin-tool-dashboard/src/interventionAudit.test.ts
@@ -0,0 +1,55 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { createDryRunAudit, dryRunNeedsApproval } from './interventionAudit';
+
+describe('dryRunNeedsApproval', () => {
+ it('lets a closed draft (no credentials, no network) run unattended', () => {
+ expect(dryRunNeedsApproval(null)).toBe(false);
+ expect(dryRunNeedsApproval({})).toBe(false);
+ expect(dryRunNeedsApproval({ env: [{ name: 'PLAIN' }], network: { allow: [] } })).toBe(false);
+ });
+
+ it('asks before running a draft that reads a connector credential', () => {
+ expect(dryRunNeedsApproval({ env: [{ connector: 'github', name: 'GITHUB_TOKEN' }] })).toBe(
+ true,
+ );
+ });
+
+ it('asks before running a draft that reaches the network', () => {
+ expect(dryRunNeedsApproval({ network: { allow: ['api.github.com'] } })).toBe(true);
+ });
+});
+
+describe('createDryRunAudit', () => {
+ it('reads the exact version the call names', async () => {
+ const loadVersion = vi.fn(async () => ({ manifest: { network: { allow: ['x.dev'] } } }));
+ const audit = createDryRunAudit({ loadVersion });
+
+ expect(await audit({ versionId: 'v2', widgetId: 'w1' })).toBe(true);
+ expect(loadVersion).toHaveBeenCalledWith('w1', 'v2');
+
+ loadVersion.mockResolvedValueOnce({ manifest: null } as any);
+ expect(await audit({ versionId: 'v3', widgetId: 'w1' })).toBe(false);
+ });
+
+ it('fails closed: no pinned version, no loader, unknown version or a lookup error ask the user', async () => {
+ const loadVersion = vi.fn(async () => ({ manifest: null }));
+ expect(await createDryRunAudit({ loadVersion })({ widgetId: 'w1' })).toBe(true);
+ expect(loadVersion).not.toHaveBeenCalled();
+
+ expect(await createDryRunAudit()({ versionId: 'v1', widgetId: 'w1' })).toBe(true);
+ expect(
+ await createDryRunAudit({ loadVersion: async () => undefined })({
+ versionId: 'v1',
+ widgetId: 'w1',
+ }),
+ ).toBe(true);
+ expect(
+ await createDryRunAudit({
+ loadVersion: async () => {
+ throw new Error('boom');
+ },
+ })({ versionId: 'v1', widgetId: 'w1' }),
+ ).toBe(true);
+ });
+});
diff --git a/packages/builtin-tool-dashboard/src/interventionAudit.ts b/packages/builtin-tool-dashboard/src/interventionAudit.ts
new file mode 100644
index 00000000000..a79c250635a
--- /dev/null
+++ b/packages/builtin-tool-dashboard/src/interventionAudit.ts
@@ -0,0 +1,45 @@
+import type { DynamicInterventionResolver, WidgetManifest } from '@lobechat/types';
+
+/** Registry key of the `dryRunWidget` approval audit (see `dynamicInterventionAudits`). */
+export const DASHBOARD_DRY_RUN_AUDIT = 'dashboardDryRunAudit';
+
+/**
+ * A draft that reads connector credentials or reaches the network can act on
+ * the user's behalf (mutate, exfiltrate) the moment it runs, so running it —
+ * even as a dry run — needs the user's approval. A draft with neither runs in
+ * a sandbox with no secrets and no network and may run unattended.
+ */
+export const dryRunNeedsApproval = (manifest: WidgetManifest | null | undefined) =>
+ !!manifest &&
+ ((manifest.env ?? []).some((item) => !!item.connector) ||
+ (manifest.network?.allow ?? []).length > 0);
+
+export interface DryRunAuditOptions {
+ /**
+ * The manifest of one version of a widget the caller may author;
+ * `undefined` when the version cannot be found.
+ */
+ loadVersion?: (
+ widgetId: string,
+ versionId: string,
+ ) => Promise<{ manifest?: WidgetManifest | null } | undefined>;
+}
+
+/**
+ * Decide whether a `dryRunWidget` call needs approval by reading the exact
+ * version it names. Fails closed: without a pinned version, a loader, or a
+ * readable version, it asks the user.
+ */
+export const createDryRunAudit =
+ ({ loadVersion }: DryRunAuditOptions = {}): DynamicInterventionResolver =>
+ async (toolArgs) => {
+ const { versionId, widgetId } = toolArgs ?? {};
+ if (typeof widgetId !== 'string' || typeof versionId !== 'string' || !loadVersion) return true;
+ try {
+ const version = await loadVersion(widgetId, versionId);
+ if (!version) return true;
+ return dryRunNeedsApproval(version.manifest);
+ } catch {
+ return true;
+ }
+ };
diff --git a/packages/builtin-tool-dashboard/src/manifest.test.ts b/packages/builtin-tool-dashboard/src/manifest.test.ts
new file mode 100644
index 00000000000..d498fc8652b
--- /dev/null
+++ b/packages/builtin-tool-dashboard/src/manifest.test.ts
@@ -0,0 +1,65 @@
+import { describe, expect, it } from 'vitest';
+
+import plugin from '../../locales/src/default/plugin';
+import { DASHBOARD_DRY_RUN_AUDIT } from './interventionAudit';
+import { DashboardManifest } from './manifest';
+import { DashboardApiName, DashboardIdentifier } from './types';
+
+describe('DashboardManifest', () => {
+ it('declares exactly one API per ApiName, each with an Inspector label', () => {
+ expect(DashboardManifest.api.map((api) => api.name).sort()).toEqual(
+ Object.values(DashboardApiName).sort(),
+ );
+ for (const name of Object.values(DashboardApiName)) {
+ expect(plugin).toHaveProperty([`builtins.${DashboardIdentifier}.apiName.${name}`]);
+ }
+ });
+
+ it('never lets an agent publish without the user, even in auto-run mode', () => {
+ const publish = DashboardManifest.api.find(
+ (api) => api.name === DashboardApiName.requestPublish,
+ );
+ // `required` could be bypassed by auto-run; `always` cannot.
+ expect(publish?.humanIntervention).toBe('always');
+ });
+
+ it('asks before dry-running credentialed or networked code, and only then', () => {
+ const intervened = DashboardManifest.api.filter((api) => api.humanIntervention);
+ expect(intervened.map((api) => api.name).sort()).toEqual(
+ [DashboardApiName.dryRunWidget, DashboardApiName.requestPublish].sort(),
+ );
+
+ const dryRun = DashboardManifest.api.find((api) => api.name === DashboardApiName.dryRunWidget);
+ expect(dryRun?.humanIntervention).toEqual({
+ dynamic: { default: 'never', policy: 'always', type: DASHBOARD_DRY_RUN_AUDIT },
+ });
+ expect(dryRun?.parameters.required).toEqual(expect.arrayContaining(['versionId']));
+ expect(DashboardManifest.systemRole).toContain('only runs after the user approves');
+ });
+
+ it('makes the model name the exact version the user approves', () => {
+ const publish = DashboardManifest.api.find(
+ (api) => api.name === DashboardApiName.requestPublish,
+ );
+ expect(publish?.parameters.required).toEqual(expect.arrayContaining(['versionId']));
+ });
+
+ it('lets the model pick the header of a multi-header connector', () => {
+ for (const name of [DashboardApiName.createWidgetDraft, DashboardApiName.updateWidgetDraft]) {
+ const api = DashboardManifest.api.find((item) => item.name === name);
+ const envItem = api?.parameters.properties.manifest.properties.env.items;
+ expect(envItem.additionalProperties).toBe(false);
+ expect(envItem.properties).toHaveProperty('field.type', 'string');
+ }
+ expect(DashboardManifest.systemRole).toContain('"field"');
+ });
+
+ it('teaches the output contract and the secret rules', () => {
+ for (const type of ['stat', 'list', 'series', 'table']) {
+ expect(DashboardManifest.systemRole).toContain(`"type":"${type}"`);
+ }
+ expect(DashboardManifest.systemRole).toContain('manifest.env');
+ expect(DashboardManifest.systemRole).toContain('never write a token');
+ expect(DashboardManifest.systemRole).toContain('manifest.network.allow');
+ });
+});
diff --git a/packages/builtin-tool-dashboard/src/manifest.ts b/packages/builtin-tool-dashboard/src/manifest.ts
new file mode 100644
index 00000000000..ff59e86a45c
--- /dev/null
+++ b/packages/builtin-tool-dashboard/src/manifest.ts
@@ -0,0 +1,266 @@
+import type { BuiltinToolManifest } from '@lobechat/types';
+import { WIDGET_OUTPUT_TYPES, WIDGET_RUNTIMES } from '@lobechat/types';
+
+import { DASHBOARD_DRY_RUN_AUDIT } from './interventionAudit';
+import { systemPrompt } from './systemRole';
+import { DashboardApiName, DashboardIdentifier } from './types';
+
+export { DashboardIdentifier } from './types';
+
+const widgetIdSchema = {
+ description: 'Widget id (uuid) returned by createWidgetDraft or listDashboards.',
+ type: 'string',
+};
+
+const versionIdSchema = {
+ description:
+ 'Version id (uuid) of the exact draft, as returned by createWidgetDraft / updateWidgetDraft (listDashboards shows the current draft id of existing widgets). The user reviews and approves exactly this version.',
+ type: 'string',
+};
+
+const scriptSchema = {
+ description:
+ 'The complete script. It must print exactly one JSON document matching outputType to stdout; logs go to stderr. Never embed secrets — read them from environment variables declared in manifest.env.',
+ type: 'string',
+};
+
+const runtimeSchema = {
+ description: 'node (global fetch, no npm packages), python (standard library only) or bash.',
+ enum: [...WIDGET_RUNTIMES],
+ type: 'string',
+};
+
+const outputTypeSchema = {
+ description:
+ 'Shape of the JSON the script prints: stat (one number), list (items), series (time series), table (columns + rows).',
+ enum: [...WIDGET_OUTPUT_TYPES],
+ type: 'string',
+};
+
+const manifestSchema = {
+ additionalProperties: false,
+ description: 'What the script needs to run and how the platform treats its output.',
+ properties: {
+ env: {
+ description:
+ 'Secrets / variables the script reads from its environment. Each is injected from a connected account (connector) at run time and redacted from logs.',
+ items: {
+ additionalProperties: false,
+ properties: {
+ connector: {
+ description: 'Connector providing the value, e.g. "github", "linear".',
+ type: 'string',
+ },
+ description: { type: 'string' },
+ field: {
+ description:
+ 'For a connector holding several headers: which header to inject, e.g. "X-Api-Key" (case-insensitive). Required then; ignored for single-secret connectors.',
+ type: 'string',
+ },
+ name: { description: 'Variable name, e.g. GITHUB_TOKEN.', type: 'string' },
+ required: { type: 'boolean' },
+ },
+ required: ['name'],
+ type: 'object',
+ },
+ type: 'array',
+ },
+ metric: {
+ additionalProperties: false,
+ description:
+ "Record a stat's value on every published run for a long-term trend line. valuePath defaults to 'value'.",
+ properties: {
+ key: { type: 'string' },
+ kind: { enum: ['gauge', 'counter'], type: 'string' },
+ unit: { type: 'string' },
+ valuePath: { type: 'string' },
+ },
+ required: ['key'],
+ type: 'object',
+ },
+ network: {
+ additionalProperties: false,
+ description: 'Hostnames the script calls. Without it the sandbox has no network.',
+ properties: { allow: { items: { type: 'string' }, type: 'array' } },
+ required: ['allow'],
+ type: 'object',
+ },
+ schedule: {
+ additionalProperties: false,
+ description:
+ 'Suggested refresh cadence, applied when the widget is published, e.g. {"pattern":"0 * * * *"}.',
+ properties: {
+ pattern: { description: '5-field cron pattern.', type: 'string' },
+ timezone: { description: 'IANA timezone, e.g. Asia/Shanghai.', type: 'string' },
+ },
+ required: ['pattern'],
+ type: 'object',
+ },
+ timeoutMs: {
+ description: 'Script time limit in ms. Default 30000, max 120000.',
+ type: 'number',
+ },
+ },
+ type: 'object',
+};
+
+const viewSchema = {
+ additionalProperties: false,
+ description: 'Rendering hints for the card.',
+ properties: {
+ chart: { enum: ['line', 'bar', 'area'], type: 'string' },
+ columns: {
+ description: 'Table column keys to show, in order.',
+ items: { type: 'string' },
+ type: 'array',
+ },
+ limit: { description: 'Maximum list / table rows on the card.', type: 'number' },
+ },
+ type: 'object',
+};
+
+export const DashboardManifest: BuiltinToolManifest = {
+ api: [
+ {
+ description:
+ "List the user's dashboards (in a project conversation, the project's dashboards first, then the home ones) with the widgets placed on them, plus the widgets this agent already owns (with publish and last-run status). Call before creating a widget to avoid duplicates and to pick a dashboard.",
+ name: DashboardApiName.listDashboards,
+ parameters: {
+ additionalProperties: false,
+ properties: {},
+ type: 'object',
+ },
+ },
+ {
+ 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).',
+ name: DashboardApiName.createWidgetDraft,
+ parameters: {
+ additionalProperties: false,
+ properties: {
+ description: {
+ description:
+ 'Metric definition (口径) shown on the card: data source, filters, time window and unit.',
+ type: 'string',
+ },
+ manifest: manifestSchema,
+ outputType: outputTypeSchema,
+ runtime: runtimeSchema,
+ script: scriptSchema,
+ title: { description: 'Short card title, e.g. "Open bug issues".', type: 'string' },
+ view: viewSchema,
+ },
+ required: ['title', 'description', 'script', 'runtime', 'outputType'],
+ type: 'object',
+ },
+ },
+ {
+ description:
+ "Save a new draft of an existing widget. Omitted content fields keep the current draft's values, so send only what changes. title / description update the widget itself. Call dryRunWidget afterwards.",
+ name: DashboardApiName.updateWidgetDraft,
+ parameters: {
+ additionalProperties: false,
+ properties: {
+ changeNote: {
+ description: 'One line on what changed in this draft, shown in version history.',
+ type: 'string',
+ },
+ description: {
+ description: 'New metric definition (口径) when the logic changed.',
+ type: 'string',
+ },
+ manifest: manifestSchema,
+ outputType: outputTypeSchema,
+ runtime: runtimeSchema,
+ script: scriptSchema,
+ title: { type: 'string' },
+ view: viewSchema,
+ widgetId: widgetIdSchema,
+ },
+ required: ['widgetId'],
+ type: 'object',
+ },
+ },
+ {
+ description:
+ 'Execute one exact draft version once in the sandbox and return its real output, stdout/stderr and error. Never affects the live widget. A draft that declares connector credentials (manifest.env) or network hosts (manifest.network.allow) runs only after the user approves it. Fix the script with updateWidgetDraft and dry-run the new version again until it succeeds.',
+ // Credentialed or networked code can act on the user's behalf the moment
+ // it runs, so those drafts need approval (`always`: auto-run cannot
+ // bypass it); a draft with neither runs in a closed sandbox unattended.
+ humanIntervention: {
+ dynamic: { default: 'never', policy: 'always', type: DASHBOARD_DRY_RUN_AUDIT },
+ },
+ name: DashboardApiName.dryRunWidget,
+ parameters: {
+ additionalProperties: false,
+ properties: { versionId: versionIdSchema, widgetId: widgetIdSchema },
+ required: ['widgetId', 'versionId'],
+ type: 'object',
+ },
+ renderDisplayControl: 'expand',
+ },
+ {
+ description:
+ 'Ask the user to publish one exact draft version so it runs on its schedule. The user must confirm in the UI and exactly the versionId you pass goes live; it must have succeeded in a dry run with exactly this content.',
+ humanIntervention: 'always',
+ name: DashboardApiName.requestPublish,
+ parameters: {
+ additionalProperties: false,
+ properties: {
+ summary: {
+ description: 'One sentence for the confirmation card: what goes live and why.',
+ type: 'string',
+ },
+ versionId: versionIdSchema,
+ widgetId: widgetIdSchema,
+ },
+ required: ['widgetId', 'versionId'],
+ type: 'object',
+ },
+ renderDisplayControl: 'expand',
+ },
+ {
+ description:
+ 'Place a widget on a dashboard. Pass dashboardId from listDashboards, or newDashboardTitle to create a dashboard first (in a project conversation it belongs to the project). Placing an unpublished widget is allowed.',
+ name: DashboardApiName.addWidgetToDashboard,
+ parameters: {
+ additionalProperties: false,
+ properties: {
+ dashboardId: { description: 'Existing dashboard id (uuid).', type: 'string' },
+ newDashboardTitle: {
+ description:
+ 'Create a new dashboard with this name and place the widget on it. Titles over 200 characters are rejected.',
+ type: 'string',
+ },
+ widgetId: widgetIdSchema,
+ },
+ required: ['widgetId'],
+ type: 'object',
+ },
+ },
+ {
+ description:
+ "Recent runs of a widget (scheduled, manual and preview), newest first. Pass runId to get that run's full output and logs.",
+ name: DashboardApiName.getWidgetRuns,
+ parameters: {
+ additionalProperties: false,
+ properties: {
+ limit: { description: 'How many runs to list (1-50, default 10).', type: 'number' },
+ runId: { description: 'A run id to inspect in full.', type: 'string' },
+ widgetId: widgetIdSchema,
+ },
+ required: ['widgetId'],
+ type: 'object',
+ },
+ },
+ ],
+ identifier: DashboardIdentifier,
+ meta: {
+ avatar: '📊',
+ description:
+ 'Build live monitoring widgets from sandboxed scripts, preview them with real data and put them on dashboards',
+ title: 'Dashboards',
+ },
+ systemRole: systemPrompt,
+ type: 'builtin',
+};
diff --git a/packages/builtin-tool-dashboard/src/systemRole.ts b/packages/builtin-tool-dashboard/src/systemRole.ts
new file mode 100644
index 00000000000..8c80e076cf3
--- /dev/null
+++ b/packages/builtin-tool-dashboard/src/systemRole.ts
@@ -0,0 +1,45 @@
+export const systemPrompt = `You can build live monitoring widgets for the user's dashboards. A widget is a small script the platform runs in an isolated sandbox on a schedule; its stdout is rendered as a card.
+
+<tools>
+- **listDashboards**: The user's dashboards — in a project conversation the project's dashboards come first, marked [project], then the home ones — (with 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.
+- **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.
+- **dryRunWidget**: Execute one draft version (pass the versionId createWidgetDraft / updateWidgetDraft returned) once in the sandbox and get the REAL output, stdout/stderr and error back. Use it after every create/update and fix the script from the logs until it succeeds. A dry run never touches the live widget. A draft that declares connector credentials (manifest.env) or network hosts (manifest.network.allow) only runs after the user approves that exact version, so keep those declarations to what the script really needs; if the user rejects the dry run, ask what to change instead of retrying the same draft.
+- **requestPublish**: Ask the user to make one successfully dry-run draft live. Always pass its versionId (from createWidgetDraft / updateWidgetDraft, or the draft version id listDashboards shows): the user reviews exactly that version and exactly that version goes live. You cannot publish without the user's confirmation, and publishing a draft whose exact content has not succeeded in a dry run is refused.
+- **addWidgetToDashboard**: Place a widget on a dashboard (dashboardId from listDashboards), or create a new dashboard with newDashboardTitle — in a project conversation the new dashboard belongs to the project. Prefer the project's dashboards for a project's widgets.
+- **getWidgetRuns**: Recent runs of a widget (scheduled, manual, preview); pass runId for one run's full logs. Use it to diagnose a widget that stopped working.
+</tools>
+
+<workflow>
+1. listDashboards.
+2. createWidgetDraft (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).
+</workflow>
+
+<output_contract>
+The script must print exactly ONE JSON document to stdout — nothing else (send debug output to stderr). The document's "type" must equal the widget's outputType:
+
+- 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.
+Partial data: 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 instead of failing. Exit non-zero only when there is nothing meaningful to show.
+</output_contract>
+
+<script_rules>
+- runtime: node (use the global fetch, no npm packages), python (standard library only, e.g. urllib.request, json), or bash (curl, jq may be absent). Keep scripts short, deterministic and idempotent: they run unattended on every refresh.
+- 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"}. If a run fails with MISSING_ENV naming several headers, set "field" to one of them with updateWidgetDraft; 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.
+- 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.
+</script_rules>
+
+<metric_definition>
+The description (口径) is shown on the card and must let the user trust the number: the 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 whenever the script's logic changes.
+</metric_definition>`;
diff --git a/packages/builtin-tool-dashboard/src/types.ts b/packages/builtin-tool-dashboard/src/types.ts
new file mode 100644
index 00000000000..c357ded3ec5
--- /dev/null
+++ b/packages/builtin-tool-dashboard/src/types.ts
@@ -0,0 +1,206 @@
+import type {
+ WidgetManifest,
+ WidgetOutput,
+ WidgetOutputType,
+ WidgetRunError,
+ WidgetRunStatus,
+ WidgetRuntime,
+ WidgetRunTrigger,
+ WidgetView,
+} from '@lobechat/types';
+
+export const DashboardIdentifier = 'lobe-dashboard';
+
+export const DashboardApiName = {
+ listDashboards: 'listDashboards',
+
+ createWidgetDraft: 'createWidgetDraft',
+ updateWidgetDraft: 'updateWidgetDraft',
+ dryRunWidget: 'dryRunWidget',
+ requestPublish: 'requestPublish',
+ addWidgetToDashboard: 'addWidgetToDashboard',
+ getWidgetRuns: 'getWidgetRuns',
+} as const;
+
+export type DashboardApiNameType = (typeof DashboardApiName)[keyof typeof DashboardApiName];
+
+// ==================== Shared records ====================
+
+/** The script + contract of one version, as the model authors it. */
+export interface WidgetVersionContent {
+ manifest?: WidgetManifest | null;
+ outputType: WidgetOutputType;
+ runtime: WidgetRuntime;
+ script: string;
+ view?: WidgetView | null;
+}
+
+export interface WidgetVersionRecord extends WidgetVersionContent {
+ changeNote?: string | null;
+ id: string;
+ status: 'draft' | 'published' | 'archived';
+ version: number;
+}
+
+export interface DashboardWidgetRecord {
+ description?: string | null;
+ draftVersion?: WidgetVersionRecord | null;
+ id: string;
+ publishedVersion?: WidgetVersionRecord | null;
+ schedulePattern?: string | null;
+ scheduleTimezone?: string | null;
+ title: string;
+}
+
+export interface WidgetRunRecord {
+ durationMs?: number | null;
+ error?: WidgetRunError | null;
+ exitCode?: number | null;
+ finishedAt?: Date | string | null;
+ id: string;
+ output?: WidgetOutput | null;
+ startedAt?: Date | string | null;
+ status: WidgetRunStatus;
+ stderr?: string | null;
+ stdout?: string | null;
+ trigger: WidgetRunTrigger;
+ versionId: string;
+}
+
+export interface DashboardSummary {
+ id: string;
+ /** Set for a board of the conversation's project; home boards have none. */
+ projectId?: string | null;
+ title: string;
+ widgets: { id: string; title: string }[];
+}
+
+export interface DashboardWidgetSummary {
+ /** The current draft's version id, so the model can pin dry runs and publishes to it. */
+ draftVersionId?: string | null;
+ hasDraft: boolean;
+ id: string;
+ lastRunStatus?: WidgetRunStatus | null;
+ published: boolean;
+ title: string;
+}
+
+// ==================== listDashboards ====================
+
+export type ListDashboardsParams = Record<string, never>;
+
+export interface ListDashboardsState {
+ dashboards: DashboardSummary[];
+ widgets: DashboardWidgetSummary[];
+}
+
+// ==================== createWidgetDraft ====================
+
+export interface CreateWidgetDraftParams extends WidgetVersionContent {
+ /** Metric definition (口径): source, filters, window, unit. */
+ description: string;
+ title: string;
+}
+
+export interface WidgetDraftState {
+ version: number;
+ versionId: string;
+ widgetId: string;
+}
+
+// ==================== updateWidgetDraft ====================
+
+export interface UpdateWidgetDraftParams extends Partial<WidgetVersionContent> {
+ changeNote?: string;
+ description?: string;
+ title?: string;
+ widgetId: string;
+}
+
+// ==================== dryRunWidget ====================
+
+export interface DryRunWidgetParams {
+ /**
+ * The exact version to run — and, for a credentialed / networked draft, the
+ * one the user approves. Never resolved from "the current draft".
+ */
+ versionId: string;
+ widgetId: string;
+}
+
+export interface DryRunWidgetState {
+ durationMs?: number | null;
+ error?: WidgetRunError | null;
+ runId: string;
+ status: WidgetRunStatus;
+ versionId: string;
+ widgetId: string;
+}
+
+// ==================== requestPublish ====================
+
+export interface RequestPublishParams {
+ /** One line on what changes for the user, shown on the confirmation card. */
+ summary?: string;
+ /**
+ * The exact version the user approves and that goes live. Never resolved
+ * from "the current draft" at execution time: another tab could have saved
+ * a newer draft while the approval was pending.
+ */
+ versionId: string;
+ widgetId: string;
+}
+
+export interface RequestPublishState {
+ schedulePattern?: string | null;
+ version: number;
+ versionId: string;
+ widgetId: string;
+}
+
+// ==================== addWidgetToDashboard ====================
+
+/**
+ * The dashboard title length the API enforces (`dashboard.create` /
+ * `dashboard.update`). Exported so the tool runtime, the server router and
+ * the manifest text share one limit.
+ */
+export const DASHBOARD_TITLE_MAX_LENGTH = 200;
+
+export interface AddWidgetToDashboardParams {
+ /** An existing dashboard from listDashboards. */
+ dashboardId?: string;
+ /** Create a new dashboard with this name instead. */
+ newDashboardTitle?: string;
+ widgetId: string;
+}
+
+export interface AddWidgetToDashboardState {
+ createdDashboard: boolean;
+ dashboardId: string;
+ dashboardTitle: string;
+ /** The board's project, so the card links to the project's dashboard page. */
+ projectId?: string | null;
+ widgetId: string;
+}
+
+// ==================== getWidgetRuns ====================
+
+export interface GetWidgetRunsParams {
+ limit?: number;
+ /** Return this run's full logs instead of the recent list. */
+ runId?: string;
+ widgetId: string;
+}
+
+export interface GetWidgetRunsState {
+ runs: {
+ durationMs?: number | null;
+ errorCode?: string | null;
+ id: string;
+ startedAt?: Date | string | null;
+ status: WidgetRunStatus;
+ trigger: WidgetRunTrigger;
+ }[];
+ widgetId: string;
+}
diff --git a/packages/builtin-tool-dashboard/vitest.config.mts b/packages/builtin-tool-dashboard/vitest.config.mts
new file mode 100644
index 00000000000..04bfa099ade
--- /dev/null
+++ b/packages/builtin-tool-dashboard/vitest.config.mts
@@ -0,0 +1,35 @@
+import path from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+import { defineConfig } from 'vitest/config';
+
+const packageDir = path.dirname(fileURLToPath(import.meta.url));
+const repoRoot = path.resolve(packageDir, '../..');
+
+export default defineConfig({
+ plugins: [
+ {
+ enforce: 'pre',
+ name: 'stub-lobehub-ui-motion-provider',
+ resolveId(id, importer) {
+ if (!importer || !importer.includes('/@lobehub/ui/')) return null;
+ if (/MotionProvider(?:\/index(?:\.(?:mjs|js|tsx))?)?$/.test(id))
+ return path.resolve(repoRoot, 'tests/mocks/lobehubUiMotionProvider.tsx');
+ return null;
+ },
+ },
+ ],
+ // Resolve the root `paths` map (packages first, app src as fallback) so the
+ // app-level store/services graph imported by these tests loads correctly.
+ resolve: {
+ tsconfigPaths: true,
+ },
+ test: {
+ environment: 'happy-dom',
+ server: {
+ deps: {
+ inline: [/@lobehub\//],
+ },
+ },
+ },
+});
diff --git a/packages/builtin-tools/package.json b/packages/builtin-tools/package.json
index 7a06b7bd6e6..b348fb5d744 100644
--- a/packages/builtin-tools/package.json
+++ b/packages/builtin-tools/package.json
@@ -15,6 +15,7 @@
"./streamings": "./src/streamings.ts",
"./identifiers": "./src/identifiers.ts",
"./dynamicInterventionAudits": "./src/dynamicInterventionAudits.ts",
+ "./featureGates": "./src/featureGates.ts",
"./workRegistration": "./src/workRegistration.ts",
"./fileEditScan": "./src/fileEditScan/index.ts"
},
@@ -34,6 +35,7 @@
"@lobechat/builtin-tool-claude-code": "workspace:*",
"@lobechat/builtin-tool-cloud-sandbox": "workspace:*",
"@lobechat/builtin-tool-creds": "workspace:*",
+ "@lobechat/builtin-tool-dashboard": "workspace:*",
"@lobechat/builtin-tool-goal": "workspace:*",
"@lobechat/builtin-tool-group-agent-builder": "workspace:*",
"@lobechat/builtin-tool-group-management": "workspace:*",
diff --git a/packages/builtin-tools/src/dynamicInterventionAudits.test.ts b/packages/builtin-tools/src/dynamicInterventionAudits.test.ts
new file mode 100644
index 00000000000..612acc5cce4
--- /dev/null
+++ b/packages/builtin-tools/src/dynamicInterventionAudits.test.ts
@@ -0,0 +1,25 @@
+import { DASHBOARD_DRY_RUN_AUDIT, DashboardManifest } from '@lobechat/builtin-tool-dashboard';
+import { describe, expect, it } from 'vitest';
+
+import { dynamicInterventionAudits } from './dynamicInterventionAudits';
+
+describe('dynamicInterventionAudits', () => {
+ it('registers every dynamic audit a builtin manifest references', () => {
+ const referenced = DashboardManifest.api
+ .map((api) => api.humanIntervention)
+ .filter((config): config is { dynamic: { type: string } } =>
+ Boolean(config && typeof config === 'object' && 'dynamic' in config),
+ )
+ .map((config) => config.dynamic.type);
+
+ expect(referenced).toContain(DASHBOARD_DRY_RUN_AUDIT);
+ for (const type of referenced) expect(dynamicInterventionAudits).toHaveProperty(type);
+ });
+
+ it('asks the user for a dashboard dry run when the host cannot read the version', async () => {
+ // A missing resolver would fall back to the manifest's `default: never`.
+ await expect(
+ dynamicInterventionAudits[DASHBOARD_DRY_RUN_AUDIT]({ versionId: 'v1', widgetId: 'w1' }),
+ ).resolves.toBe(true);
+ });
+});
diff --git a/packages/builtin-tools/src/dynamicInterventionAudits.ts b/packages/builtin-tools/src/dynamicInterventionAudits.ts
index cd5fb3b5e4d..655525dd13a 100644
--- a/packages/builtin-tools/src/dynamicInterventionAudits.ts
+++ b/packages/builtin-tools/src/dynamicInterventionAudits.ts
@@ -1,6 +1,11 @@
+import { createDryRunAudit, DASHBOARD_DRY_RUN_AUDIT } from '@lobechat/builtin-tool-dashboard';
import { pathScopeAudit } from '@lobechat/builtin-tool-local-system';
import { type DynamicInterventionResolver } from '@lobechat/types';
export const dynamicInterventionAudits: Record<string, DynamicInterventionResolver> = {
+ // Without a version loader this asks the user for every dry run; hosts that
+ // can read the version (agent runtime service, client streaming executor)
+ // register a loader-backed audit under the same key.
+ [DASHBOARD_DRY_RUN_AUDIT]: createDryRunAudit(),
pathScopeAudit,
};
diff --git a/packages/builtin-tools/src/featureGates.test.ts b/packages/builtin-tools/src/featureGates.test.ts
new file mode 100644
index 00000000000..4f34209885a
--- /dev/null
+++ b/packages/builtin-tools/src/featureGates.test.ts
@@ -0,0 +1,18 @@
+import { DashboardIdentifier } from '@lobechat/builtin-tool-dashboard';
+import { describe, expect, it } from 'vitest';
+
+import { getFeatureDisabledToolIds, isToolEnabledByFeatureFlags } from './featureGates';
+
+describe('feature-gated builtin tools', () => {
+ it('drops lobe-dashboard unless the dashboard flag is on', () => {
+ expect(getFeatureDisabledToolIds(undefined)).toContain(DashboardIdentifier);
+ expect(getFeatureDisabledToolIds({ enableDashboard: false })).toContain(DashboardIdentifier);
+ expect(getFeatureDisabledToolIds({ enableDashboard: true })).not.toContain(DashboardIdentifier);
+ });
+
+ it('only gates tools that declare a flag', () => {
+ expect(isToolEnabledByFeatureFlags(DashboardIdentifier, {})).toBe(false);
+ expect(isToolEnabledByFeatureFlags(DashboardIdentifier, { enableDashboard: true })).toBe(true);
+ expect(isToolEnabledByFeatureFlags('lobe-web-browsing', {})).toBe(true);
+ });
+});
diff --git a/packages/builtin-tools/src/featureGates.ts b/packages/builtin-tools/src/featureGates.ts
new file mode 100644
index 00000000000..d600671a971
--- /dev/null
+++ b/packages/builtin-tools/src/featureGates.ts
@@ -0,0 +1,27 @@
+import { DashboardIdentifier } from '@lobechat/builtin-tool-dashboard';
+import type { IFeatureFlagsState } from '@lobechat/types';
+
+/** Builtin tools that exist only while a runtime feature flag is on for the user. */
+export const FEATURE_GATED_TOOLS: Record<string, keyof IFeatureFlagsState> = {
+ [DashboardIdentifier]: 'enableDashboard',
+};
+
+/**
+ * Identifiers to drop from a run's tool pool for the user's resolved flags.
+ * Fails closed: a flag that is unset or anything but `true` hides its tool.
+ * Hosts add these to the run's disabled identifiers, which leave the pool
+ * outright — explicit activation cannot bring them back.
+ */
+export const getFeatureDisabledToolIds = (flags: Partial<IFeatureFlagsState> | undefined) =>
+ Object.entries(FEATURE_GATED_TOOLS)
+ .filter(([, flag]) => flags?.[flag] !== true)
+ .map(([identifier]) => identifier);
+
+/** Whether a builtin tool may be offered / listed for the user's resolved flags. */
+export const isToolEnabledByFeatureFlags = (
+ identifier: string,
+ flags: Partial<IFeatureFlagsState> | undefined,
+) => {
+ const flag = FEATURE_GATED_TOOLS[identifier];
+ return !flag || flags?.[flag] === true;
+};
diff --git a/packages/builtin-tools/src/identifiers.ts b/packages/builtin-tools/src/identifiers.ts
index ef08025895f..60e15e6b6c4 100644
--- a/packages/builtin-tools/src/identifiers.ts
+++ b/packages/builtin-tools/src/identifiers.ts
@@ -15,6 +15,7 @@ import { BrowserManifest } from '@lobechat/builtin-tool-browser';
import { CalculatorManifest } from '@lobechat/builtin-tool-calculator/manifest';
import { CloudSandboxManifest } from '@lobechat/builtin-tool-cloud-sandbox';
import { CredsManifest } from '@lobechat/builtin-tool-creds';
+import { DashboardManifest } from '@lobechat/builtin-tool-dashboard';
import {
GoalManifest,
GoalReportManifest,
@@ -49,6 +50,7 @@ export const builtinToolIdentifiers: string[] = [
CalculatorManifest.identifier,
CloudSandboxManifest.identifier,
CredsManifest.identifier,
+ DashboardManifest.identifier,
GroupAgentBuilderManifest.identifier,
GroupManagementManifest.identifier,
GoalManifest.identifier,
diff --git a/packages/builtin-tools/src/index.ts b/packages/builtin-tools/src/index.ts
index 8ecc0af63b3..9dbffb8b7d3 100644
--- a/packages/builtin-tools/src/index.ts
+++ b/packages/builtin-tools/src/index.ts
@@ -22,6 +22,7 @@ import { BrowserManifest } from '@lobechat/builtin-tool-browser';
import { CalculatorManifest } from '@lobechat/builtin-tool-calculator/manifest';
import { CloudSandboxManifest } from '@lobechat/builtin-tool-cloud-sandbox';
import { CredsManifest } from '@lobechat/builtin-tool-creds';
+import { DashboardManifest } from '@lobechat/builtin-tool-dashboard';
import {
GoalManifest,
GoalReportManifest,
@@ -559,6 +560,13 @@ const builtinToolRegistry: LobeBuiltinTool[] = [
manifest: TaskManifest,
type: 'builtin',
},
+ {
+ // Opt-in: pin it in the Tools popover, or the activator enables it when a
+ // user asks for monitoring — not a default so ordinary turns stay lean.
+ identifier: DashboardManifest.identifier,
+ manifest: DashboardManifest,
+ type: 'builtin',
+ },
{
discoverable: false,
hidden: true,
diff --git a/packages/builtin-tools/src/register.ts b/packages/builtin-tools/src/register.ts
index 796439ceea0..916b35dbb2f 100644
--- a/packages/builtin-tools/src/register.ts
+++ b/packages/builtin-tools/src/register.ts
@@ -44,6 +44,12 @@ import {
CloudSandboxStreamings,
} from '@lobechat/builtin-tool-cloud-sandbox/client';
import { CredsIdentifier, CredsInterventions } from '@lobechat/builtin-tool-creds/client';
+import {
+ DashboardInspectors,
+ DashboardInterventions,
+ DashboardManifest,
+ DashboardRenders,
+} from '@lobechat/builtin-tool-dashboard/client';
import {
GoalInspectors,
GoalInterventions,
@@ -286,6 +292,7 @@ export const registerBuiltinToolSurfaces = (): void => {
[RemoteDeviceManifest.identifier]: RemoteDeviceRenders as Record<string, BuiltinRender>,
[SkillStoreManifest.identifier]: SkillStoreRenders as Record<string, BuiltinRender>,
[SkillsManifest.identifier]: SkillsRenders as Record<string, BuiltinRender>,
+ [DashboardManifest.identifier]: DashboardRenders as Record<string, BuiltinRender>,
[TaskManifest.identifier]: TaskRenders as Record<string, BuiltinRender>,
[UserInteractionIdentifier]: UserInteractionRenders as Record<string, BuiltinRender>,
[LobeActivatorManifest.identifier]: LobeActivatorRenders as Record<string, BuiltinRender>,
@@ -359,6 +366,7 @@ export const registerBuiltinToolSurfaces = (): void => {
>,
[SkillStoreManifest.identifier]: SkillStoreInspectors as Record<string, BuiltinInspector>,
[SkillsManifest.identifier]: SkillsInspectors as Record<string, BuiltinInspector>,
+ [DashboardManifest.identifier]: DashboardInspectors as Record<string, BuiltinInspector>,
[TaskManifest.identifier]: TaskInspectors as Record<string, BuiltinInspector>,
[UserInteractionIdentifier]: UserInteractionInspectors as Record<string, BuiltinInspector>,
[WebBrowsingManifest.identifier]: WebBrowsingInspectors as Record<string, BuiltinInspector>,
@@ -432,6 +440,7 @@ export const registerBuiltinToolSurfaces = (): void => {
[LocalSystemIdentifier]: LocalSystemInterventions as Record<string, BuiltinIntervention>,
[MemoryManifest.identifier]: MemoryInterventions as Record<string, BuiltinIntervention>,
[MessageManifest.identifier]: MessageInterventions as Record<string, BuiltinIntervention>,
+ [DashboardManifest.identifier]: DashboardInterventions as Record<string, BuiltinIntervention>,
[TaskManifest.identifier]: TaskInterventions as Record<string, BuiltinIntervention>,
[UserInteractionIdentifier]: UserInteractionInterventions as Record<
string,
diff --git a/packages/database/src/models/__tests__/dashboard.test.ts b/packages/database/src/models/__tests__/dashboard.test.ts
index fa7d57e1de7..12aaa690b96 100644
--- a/packages/database/src/models/__tests__/dashboard.test.ts
+++ b/packages/database/src/models/__tests__/dashboard.test.ts
@@ -10,11 +10,12 @@ import {
projects,
trashItems,
users,
+ widgets as widgetsTable,
workspaces,
} from '../../schemas';
import type { LobeChatDatabase } from '../../type';
import { ScopeLevelError } from '../../utils/scopeLevel';
-import { DashboardModel } from '../dashboard';
+import { DASHBOARD_MAX_ITEMS, DashboardItemLimitError, DashboardModel } from '../dashboard';
import { WidgetModel } from '../widget';
const serverDB: LobeChatDatabase = await getTestDB();
@@ -347,6 +348,32 @@ describe('DashboardModel', () => {
expect((await model.listItems(dashboard.id)).map((r) => r.widget.id)).toEqual([w1.id]);
});
+ it('refuses a new widget on a full board but still updates placed ones', async () => {
+ const model = new DashboardModel(serverDB, userId);
+ const dashboard = await model.create({ title: 'Full' });
+ const seeded = await serverDB
+ .insert(widgetsTable)
+ .values(
+ Array.from({ length: DASHBOARD_MAX_ITEMS + 1 }, (_, i) => ({ title: `w${i}`, userId })),
+ )
+ .returning({ id: widgetsTable.id });
+ const [extra, ...placed] = seeded;
+ await serverDB.insert(dashboardItems).values(
+ placed.map(({ id }, sortOrder) => ({
+ dashboardId: dashboard.id,
+ sortOrder,
+ userId,
+ widgetId: id,
+ })),
+ );
+
+ await expect(model.addItem(dashboard.id, extra.id)).rejects.toBeInstanceOf(
+ DashboardItemLimitError,
+ );
+ const moved = await model.addItem(dashboard.id, placed[0].id, { sortOrder: 999 });
+ expect(moved?.sortOrder).toBe(999);
+ });
+
it('refuses items on boards or widgets the caller cannot manage or see', async () => {
const model = new DashboardModel(serverDB, userId);
const other = new DashboardModel(serverDB, otherUserId);
@@ -371,6 +398,47 @@ describe('DashboardModel', () => {
).toHaveLength(1);
});
+ it('lists items of many readable boards at once, with the same rules as listItems', async () => {
+ const model = new DashboardModel(serverDB, userId);
+ const widgetModel = new WidgetModel(serverDB, userId);
+ const first = await model.create({ title: 'First' });
+ const second = await model.create({ title: 'Second' });
+ const trashedBoard = await model.create({ title: 'Trashed' });
+ const theirs = await new DashboardModel(serverDB, otherUserId).create({ title: 'Theirs' });
+ const a = await widgetModel.create({ title: 'a' });
+ const b = await widgetModel.create({ title: 'b' });
+ const gone = await widgetModel.create({ title: 'gone' });
+ await model.addItem(first.id, b.id);
+ await model.addItem(first.id, a.id);
+ await model.addItem(first.id, gone.id);
+ await model.addItem(second.id, a.id);
+ await model.addItem(trashedBoard.id, a.id);
+ await widgetModel.trash(gone.id);
+ await model.trash(trashedBoard.id);
+
+ const rows = await model.listItemsForDashboards([
+ first.id,
+ second.id,
+ trashedBoard.id,
+ theirs.id,
+ 'not-a-uuid',
+ ]);
+ const byBoard = (id: string) =>
+ rows.filter((r) => r.item.dashboardId === id).map((r) => r.widget.title);
+ for (const board of [first, second]) {
+ expect(byBoard(board.id)).toEqual(
+ (await model.listItems(board.id)).map((r) => r.widget.title),
+ );
+ }
+ expect(byBoard(first.id)).toEqual(['b', 'a']);
+ expect(byBoard(second.id)).toEqual(['a']);
+ expect(rows).toHaveLength(3);
+ expect(await model.listItemsForDashboards([])).toEqual([]);
+ expect(
+ await new DashboardModel(serverDB, otherUserId).listItemsForDashboards([first.id]),
+ ).toEqual([]);
+ });
+
it('lists the readable, live boards a widget is placed on', async () => {
const model = new DashboardModel(serverDB, userId);
const widget = await new WidgetModel(serverDB, userId).create({ title: 'w' });
@@ -382,8 +450,8 @@ describe('DashboardModel', () => {
await model.trash(trashed.id);
expect(await model.listByWidget(widget.id)).toEqual([
- { id: first.id, title: 'First' },
- { id: second.id, title: 'Second' },
+ { id: first.id, projectId: null, title: 'First' },
+ { id: second.id, projectId: null, title: 'Second' },
]);
// another user sees none of this user's boards
expect(await new DashboardModel(serverDB, otherUserId).listByWidget(widget.id)).toEqual([]);
diff --git a/packages/database/src/models/__tests__/widget.test.ts b/packages/database/src/models/__tests__/widget.test.ts
index 99836666118..dd8cfa34dfe 100644
--- a/packages/database/src/models/__tests__/widget.test.ts
+++ b/packages/database/src/models/__tests__/widget.test.ts
@@ -495,6 +495,78 @@ describe('WidgetModel', () => {
expect(await model.findRun(widget.id, MISSING_UUID)).toBeUndefined();
});
+ it('finds a version preview run however far the run history rolls on', async () => {
+ const widget = await model.create({ title: 'w' });
+ const v1 = await model.createVersion(widget.id, script(1));
+ const v2 = await model.createVersion(widget.id, script(2));
+
+ // The approval-era dry run of v1, then a failed retry of that version.
+ const approved = await model.startRun(widget.id, { trigger: 'preview', versionId: v1!.id });
+ await model.finishRun(approved!.id, {
+ output: { type: 'stat', value: 1 },
+ status: 'succeeded',
+ });
+ const failedRetry = await model.startRun(widget.id, {
+ trigger: 'preview',
+ versionId: v1!.id,
+ });
+ await model.finishRun(failedRetry!.id, { status: 'failed' });
+ // A manual run of v1 is not the dry run the approval showed.
+ const manual = await model.startRun(widget.id, { trigger: 'manual', versionId: v1!.id });
+ await model.finishRun(manual!.id, {
+ output: { type: 'stat', value: 9 },
+ status: 'succeeded',
+ });
+
+ // v2 keeps running until v1's preview leaves the newest-run window
+ // entirely — the publish card must still find it.
+ for (let i = 0; i < 35; i += 1) {
+ const run = await model.startRun(widget.id, { trigger: 'schedule', versionId: v2!.id });
+ await model.finishRun(run!.id, { output: { type: 'stat', value: 2 }, status: 'succeeded' });
+ }
+ expect(
+ (await model.listRuns(widget.id, { limit: 30 })).some((run) => run.id === approved!.id),
+ ).toBe(false);
+
+ expect(await model.findPreviewRun(widget.id, v1!.id)).toMatchObject({
+ id: approved!.id,
+ output: { type: 'stat', value: 1 },
+ status: 'succeeded',
+ });
+ // Only preview runs qualify; scheduled runs of v2 are not previews.
+ expect(await model.findPreviewRun(widget.id, v2!.id)).toBeUndefined();
+ expect(await model.findPreviewRun(widget.id, MISSING_UUID)).toBeUndefined();
+ expect(await model.findPreviewRun(MISSING_UUID, v1!.id)).toBeUndefined();
+ });
+
+ it('resolves the preview run by content hash, like the publish gate', async () => {
+ const widget = await model.create({ title: 'w' });
+ const v1 = await model.createVersion(widget.id, script(1));
+ // Move the draft pointer so re-saving v1's content creates a new row —
+ // the shape rollback drafts have.
+ const other = await model.createVersion(widget.id, script(2));
+ const v3 = await model.createVersion(widget.id, script(1));
+ expect(v3!.id).not.toBe(v1!.id);
+ expect(v3!.contentHash).toBe(v1!.contentHash);
+
+ const approved = await model.startRun(widget.id, {
+ trigger: 'preview',
+ versionId: v1!.id,
+ });
+ await model.finishRun(approved!.id, {
+ output: { type: 'stat', value: 1 },
+ status: 'succeeded',
+ });
+
+ // The publish gate accepts v1's run for the same-content v3, so the
+ // review lookup must find that same run for v3 — and not for a version
+ // with different content.
+ expect(await model.hasSucceededRunForContentHash(widget.id, v3!.contentHash)).toBe(true);
+ expect(await model.findPreviewRun(widget.id, v3!.id)).toMatchObject({ id: approved!.id });
+ expect(await model.findPreviewRun(widget.id, v1!.id)).toMatchObject({ id: approved!.id });
+ expect(await model.findPreviewRun(widget.id, other!.id)).toBeUndefined();
+ });
+
it('tracks usable runs by content hash across version rows', async () => {
const widget = await model.create({ title: 'w' });
const v1 = await model.createVersion(widget.id, script(1));
diff --git a/packages/database/src/models/dashboard.ts b/packages/database/src/models/dashboard.ts
index eda12f37afe..2d12f0d2ca8 100644
--- a/packages/database/src/models/dashboard.ts
+++ b/packages/database/src/models/dashboard.ts
@@ -1,5 +1,5 @@
import type { DashboardItemLayout, DashboardVisibility, WidgetLevelFilter } from '@lobechat/types';
-import { and, asc, eq, inArray, max } from 'drizzle-orm';
+import { and, asc, count, eq, inArray, max } from 'drizzle-orm';
import { agents } from '../schemas/agent';
import { dashboardItems, dashboards } from '../schemas/dashboard';
@@ -46,6 +46,20 @@ export interface AddDashboardItemInput {
sortOrder?: number;
}
+/**
+ * Most widgets one board holds. The layout editor saves every item of a board
+ * in one patch list, so the router's layout cap and this cap must match.
+ */
+export const DASHBOARD_MAX_ITEMS = 200;
+
+/** Raised when placing a new widget on a board that is already full. */
+export class DashboardItemLimitError extends Error {
+ constructor() {
+ super(`A dashboard holds at most ${DASHBOARD_MAX_ITEMS} widgets`);
+ this.name = 'DashboardItemLimitError';
+ }
+}
+
export interface DashboardItemLayoutPatch {
id: string;
layout?: DashboardItemLayout | null;
@@ -283,6 +297,8 @@ export class DashboardModel {
);
}
+ if (await this.isFull(dashboardId, widgetId)) throw new DashboardItemLimitError();
+
const sortOrder = input.sortOrder ?? (await this.nextSortOrder(dashboardId));
const [item] = await this.db
.insert(dashboardItems)
@@ -324,12 +340,30 @@ export class DashboardModel {
.orderBy(asc(dashboardItems.sortOrder), asc(dashboardItems.createdAt));
}
+ /**
+ * {@link listItems} for many boards in one query: items of the readable
+ * boards among `dashboardIds` (unreadable, trashed or unknown ids yield
+ * nothing), each with its readable widget, in display order per board.
+ */
+ async listItemsForDashboards(dashboardIds: string[]) {
+ const ids = [...new Set(dashboardIds.filter(isUuid))];
+ if (ids.length === 0) return [];
+
+ return this.db
+ .select({ item: dashboardItems, widget: widgets })
+ .from(dashboardItems)
+ .innerJoin(dashboards, eq(dashboardItems.dashboardId, dashboards.id))
+ .innerJoin(widgets, eq(dashboardItems.widgetId, widgets.id))
+ .where(and(inArray(dashboardItems.dashboardId, ids), this.readable(), this.readableWidget()))
+ .orderBy(asc(dashboardItems.sortOrder), asc(dashboardItems.createdAt));
+ }
+
/** Readable boards a widget is placed on, in board order. */
async listByWidget(widgetId: string) {
if (!isUuid(widgetId)) return [];
return this.db
- .select({ id: dashboards.id, title: dashboards.title })
+ .select({ id: dashboards.id, projectId: dashboards.projectId, title: dashboards.title })
.from(dashboardItems)
.innerJoin(dashboards, eq(dashboardItems.dashboardId, dashboards.id))
.where(and(eq(dashboardItems.widgetId, widgetId), this.readable()))
@@ -383,6 +417,24 @@ export class DashboardModel {
return !!dashboard;
}
+ /** Whether placing `widgetId` would add a new item to a board already at the cap. */
+ private async isFull(dashboardId: string, widgetId: string) {
+ const [placed] = await this.db
+ .select({ id: dashboardItems.id })
+ .from(dashboardItems)
+ .where(
+ and(eq(dashboardItems.dashboardId, dashboardId), eq(dashboardItems.widgetId, widgetId)),
+ )
+ .limit(1);
+ if (placed) return false;
+
+ const [row] = await this.db
+ .select({ total: count() })
+ .from(dashboardItems)
+ .where(eq(dashboardItems.dashboardId, dashboardId));
+ return (row?.total ?? 0) >= DASHBOARD_MAX_ITEMS;
+ }
+
private async nextSortOrder(dashboardId: string) {
const [row] = await this.db
.select({ max: max(dashboardItems.sortOrder) })
diff --git a/packages/database/src/models/widget.ts b/packages/database/src/models/widget.ts
index e79946f5184..aded20236d6 100644
--- a/packages/database/src/models/widget.ts
+++ b/packages/database/src/models/widget.ts
@@ -563,6 +563,48 @@ export class WidgetModel {
return run;
}
+ /**
+ * The newest usable preview run of one version's content — what a publish
+ * approval was shown, however far the run history has rolled on. Unlike
+ * {@link listRuns} this is keyed by version, so it keeps answering after
+ * the version's runs leave the newest-N window.
+ *
+ * The lookup matches by content hash, exactly like the publish gate
+ * ({@link hasSucceededRunForContentHash}): a draft row that reuses an
+ * earlier version's content is tried by that version's successful dry run,
+ * so the review must find the same run or a same-content draft would
+ * deadlock its own approval.
+ */
+ async findPreviewRun(widgetId: string, versionId: string) {
+ if (!isUuid(versionId)) return undefined;
+ const widget = await this.findById(widgetId);
+ if (!widget) return undefined;
+
+ const [version] = await this.db
+ .select({ contentHash: widgetVersions.contentHash })
+ .from(widgetVersions)
+ .where(and(eq(widgetVersions.id, versionId), eq(widgetVersions.widgetId, widgetId)))
+ .limit(1);
+ if (!version) return undefined;
+
+ const [row] = await this.db
+ .select({ run: widgetRuns })
+ .from(widgetRuns)
+ .innerJoin(widgetVersions, eq(widgetRuns.versionId, widgetVersions.id))
+ .where(
+ and(
+ eq(widgetRuns.widgetId, widgetId),
+ eq(widgetRuns.trigger, 'preview'),
+ inArray(widgetRuns.status, [...WIDGET_RUN_OUTPUT_STATUSES]),
+ eq(widgetVersions.contentHash, version.contentHash),
+ ),
+ )
+ .orderBy(desc(widgetRuns.createdAt))
+ .limit(1);
+
+ return row?.run;
+ }
+
/**
* Whether any version of this widget with the given content hash has a run
* that produced a usable output (`succeeded` or `partial`). Publishing a
diff --git a/packages/locales/src/default/common.ts b/packages/locales/src/default/common.ts
index 7afaddee22a..065d0392a5b 100644
--- a/packages/locales/src/default/common.ts
+++ b/packages/locales/src/default/common.ts
@@ -537,6 +537,7 @@ export default {
'tab.chat': 'Chat',
'recents': 'Recents',
'tab.community': 'Community',
+ 'tab.dashboard': 'Dashboards',
'tab.create': 'Create',
'tab.discover': 'Discover',
'tab.eval': 'Eval Lab',
diff --git a/packages/locales/src/default/dashboard.ts b/packages/locales/src/default/dashboard.ts
new file mode 100644
index 00000000000..11813bfba1d
--- /dev/null
+++ b/packages/locales/src/default/dashboard.ts
@@ -0,0 +1,170 @@
+export default {
+ 'actions.more': 'More actions',
+ 'actions.rename': 'Rename',
+ 'actions.trash': 'Move to trash',
+ 'actions.trashConfirm':
+ '"{{title}}" and its layout will move to the trash. Widgets stay available and keep their history.',
+ 'actions.trashTitle': 'Move this dashboard to the trash?',
+ 'actions.trashed': '"{{title}}" moved to the trash',
+ 'board.empty':
+ 'No widgets yet. Ask an agent in a conversation to build a monitoring widget and add it to this dashboard.',
+ 'board.health.failed': '{{count}} failed',
+ 'board.health.ok': '{{count}} up to date',
+ 'board.health.running': '{{count}} refreshing',
+ 'board.health.stale': '{{count}} stale',
+ 'board.lastUpdated': 'Latest data {{time}}',
+ 'board.refreshAll': 'Refresh all',
+ 'board.refreshAllFailed_one':
+ '{{count}} widget failed to refresh; its last successful result is still shown',
+ 'board.refreshAllFailed_other':
+ '{{count}} widgets failed to refresh; their last successful results are still shown',
+ 'board.widgetCount_one': '{{count}} widget',
+ 'board.widgetCount_other': '{{count}} widgets',
+ 'chat.add': 'Add to dashboard',
+ 'chat.addFailed': 'Could not add the widget to the dashboard',
+ 'chat.added': 'Added to "{{title}}"',
+ 'chat.definition': 'Metric definition',
+ 'chat.newDashboard': 'New dashboard…',
+ 'chat.noDashboards': 'No dashboards yet',
+ 'chat.noDefinition': 'No metric definition given.',
+ 'chat.onDashboard': 'On "{{title}}"',
+ 'chat.openDashboard': 'Open dashboard',
+ 'chat.openDetail': 'Details',
+ 'chat.outdated': 'A newer draft (v{{version}}) replaced this preview.',
+ 'chat.outdatedVersion': 'This preview is from an older version and can no longer be published.',
+ 'chat.preview.draft': 'Dry run · draft v{{version}}',
+ 'chat.preview.live': 'Live · v{{version}}',
+ 'chat.preview.running': 'Running the draft in the sandbox…',
+ 'chat.publish': 'Publish',
+ 'chat.publishFailed': 'Could not publish: {{message}}',
+ 'chat.publishHint': 'Publishing is available after a successful dry run.',
+ 'chat.publishReviewTitle': 'Review before publishing',
+ 'chat.published': 'Published v{{version}}. It now refreshes on its schedule.',
+ 'chat.unavailable': 'This widget is no longer available.',
+ 'create.action': 'New dashboard',
+ 'create.submit': 'Create',
+ 'create.title': 'New dashboard',
+ 'detail.failures': 'Failures in a row',
+ 'detail.lastRunAt': 'Last run',
+ 'detail.manualOnly': 'Manual refresh only',
+ 'detail.nextRunAt': 'Next run',
+ 'detail.noOutput': 'No successful result yet.',
+ 'detail.schedule': 'Schedule',
+ 'detail.tab.data': 'Data',
+ 'detail.tab.runs': 'Run history',
+ 'detail.tab.versions': 'Versions',
+ 'detail.updatedAt': 'Data updated',
+ 'detail.version': 'Version',
+ 'detail.versionDraft': 'draft v{{version}}',
+ 'detail.versionNone': 'Not published',
+ 'detail.versionPublished': 'v{{version}} live',
+ 'dryRun.intro':
+ 'The agent wants to run this draft once to preview its output. It runs in a sandbox with the access below; nothing goes live and no dashboard changes.',
+ 'dryRun.runtime': 'Runtime',
+ 'error.hideDetails': 'Hide details',
+ 'error.showDetails': 'Show details',
+ 'form.descriptionLabel': 'Description',
+ 'form.descriptionPlaceholder': 'What this dashboard keeps an eye on (optional)',
+ 'form.titleLabel': 'Name',
+ 'form.titlePlaceholder': 'e.g. Open-source project health',
+ 'project.boards': 'Dashboards',
+ 'project.boardsEmpty': 'No dashboards in this project yet',
+ 'project.description':
+ "This project's dashboards and widgets, including the ones its agents built in project conversations.",
+ 'project.widgets_one': 'Widgets ({{count}})',
+ 'project.widgets_other': 'Widgets ({{count}})',
+ 'project.widgetsEmpty':
+ 'No widgets yet. Ask an agent in a conversation of this project to build a monitoring widget and it will show up here.',
+ 'layout.cancel': 'Discard changes',
+ 'layout.drag': 'Drag to reorder',
+ 'layout.edit': 'Edit layout',
+ 'layout.narrower': 'Narrower',
+ 'layout.save': 'Save layout',
+ 'layout.saveFailed': 'Could not save the layout. The previous layout is restored.',
+ 'layout.saved': 'Layout saved',
+ 'layout.shorter': 'Shorter',
+ 'layout.taller': 'Taller',
+ 'layout.wider': 'Wider',
+ 'list.description':
+ 'Boards of live widgets. Each widget runs its own script on a schedule and keeps its history.',
+ 'list.empty': 'No dashboards yet',
+ 'list.noDescription': 'No description',
+ 'list.title': 'Dashboards',
+ 'list.updatedAt': 'Updated {{time}}',
+ 'portal.dashboards': 'On dashboards',
+ 'portal.definition': 'Metric definition',
+ 'portal.diff.base': 'From',
+ 'portal.diff.identical': 'The script is identical in these versions.',
+ 'portal.diff.manifest': 'Contract changes',
+ 'portal.diff.single': 'Only one version so far — nothing to compare.',
+ 'portal.diff.target': 'To',
+ 'portal.goToDashboards': 'All dashboards',
+ 'portal.notOnDashboard': 'Not on a dashboard yet.',
+ 'portal.preview': 'Dry run preview',
+ 'portal.previewHint':
+ 'Output of the dry run this conversation produced. It does not change the live widget.',
+ 'detail.tab.diff': 'Changes',
+ 'portal.title': 'Widget',
+ 'publish.env': 'Credentials',
+ 'publish.envNone': 'None',
+ 'publish.intro':
+ 'Once published, this script runs on its schedule with the listed credentials and its result shows on dashboards.',
+ 'publish.network': 'Network',
+ 'publish.networkNone': 'No network access',
+ 'publish.networkUnrestricted':
+ 'The sandbox cannot restrict egress to the listed hosts — the script can reach any host, including ones it did not declare.',
+ 'publish.noSuccessfulRun':
+ 'This draft has not succeeded in a dry run yet, so publishing it will be refused.',
+ 'publish.previewTitle': 'Latest dry run',
+ 'publish.schedule': 'Refresh',
+ 'publish.scheduleNone': 'Manual only',
+ 'publish.scriptChanges': 'Changes from live v{{version}}',
+ 'publish.scriptNew': 'Script',
+ 'rename.title': 'Rename dashboard',
+ 'review.loadFailed': "Couldn't load the review, so approval is on hold",
+ 'review.versionMissing':
+ "This version is no longer available, so it can't be reviewed. Reject the request and ask the agent to try again.",
+ 'run.empty': 'This widget has not run yet.',
+ 'run.error': 'Error',
+ 'run.logEmpty': '(empty)',
+ 'run.logTruncated': 'truncated',
+ 'run.status.failed': 'Failed',
+ 'run.status.partial': 'Partial',
+ 'run.status.running': 'Running',
+ 'run.status.succeeded': 'Succeeded',
+ 'run.status.timeout': 'Timed out',
+ 'run.trigger.manual': 'Manual',
+ 'run.trigger.preview': 'Preview',
+ 'run.trigger.schedule': 'Scheduled',
+ 'version.empty': 'No versions yet.',
+ 'version.publishedAt': 'Published {{time}}',
+ 'version.script': 'Script',
+ 'version.source.agent': 'Written by an agent',
+ 'version.source.user': 'Written by a user',
+ 'version.status.archived': 'Archived',
+ 'version.status.draft': 'Draft',
+ 'version.status.published': 'Live',
+ 'widget.lastAttemptAt': 'Last attempt {{time}}',
+ 'widget.refresh.action': 'Refresh now',
+ 'widget.refresh.failed':
+ 'Refresh failed: {{message}}. The last successful result is still shown.',
+ 'widget.state.failedNoOutput': 'No successful result yet — the last run failed.',
+ 'widget.state.firstRun': 'Running for the first time…',
+ 'widget.state.noRun': 'Not run yet. Refresh to fetch data.',
+ 'widget.state.unpublished': 'No published version yet.',
+ 'widget.status.failed': 'Failed',
+ 'widget.status.failedTip': 'Last run failed: {{message}}. Showing the last successful result.',
+ 'widget.status.failedTipNoMessage': 'Last run failed. Showing the last successful result.',
+ 'widget.status.ok': 'Up to date',
+ 'widget.status.partial': 'Partial',
+ 'widget.status.partialTip': 'The script reported an incomplete result.',
+ 'widget.status.running': 'Running',
+ 'widget.status.runningTip': 'A run is in progress.',
+ 'widget.status.stale': 'Stale',
+ 'widget.status.staleTip': 'The scheduled refresh is overdue; this data may be out of date.',
+ 'widget.updatedAt': 'Updated {{time}}',
+ 'widget.view.listEmpty': 'No items',
+ 'widget.view.more': '+{{count}} more',
+ 'widget.view.seriesEmpty': 'No data points',
+ 'widget.view.tableEmpty': 'No rows',
+};
diff --git a/packages/locales/src/default/electron.ts b/packages/locales/src/default/electron.ts
index 7eb69f3a80d..a92778fda7d 100644
--- a/packages/locales/src/default/electron.ts
+++ b/packages/locales/src/default/electron.ts
@@ -3,6 +3,7 @@ export default {
'navigation.agents': 'Agents',
'navigation.channels': 'Channels',
'navigation.chat': 'Chat',
+ 'navigation.dashboard': 'Dashboards',
'navigation.discover': 'Discover',
'navigation.discoverAssistants': 'Discover Agents',
'navigation.discoverMcp': 'Discover MCP',
diff --git a/packages/locales/src/default/index.ts b/packages/locales/src/default/index.ts
index 3b3a981a456..263e6f44de4 100644
--- a/packages/locales/src/default/index.ts
+++ b/packages/locales/src/default/index.ts
@@ -7,6 +7,7 @@ import chat from './chat';
import color from './color';
import common from './common';
import components from './components';
+import dashboard from './dashboard';
import desktopOnboarding from './desktop-onboarding';
import device from './device';
import discover from './discover';
@@ -63,6 +64,7 @@ const resources = {
color,
common,
components,
+ dashboard,
'desktop-onboarding': desktopOnboarding,
device,
discover,
diff --git a/packages/locales/src/default/plugin.ts b/packages/locales/src/default/plugin.ts
index 361fb9268f1..16fecdd96d1 100644
--- a/packages/locales/src/default/plugin.ts
+++ b/packages/locales/src/default/plugin.ts
@@ -536,6 +536,14 @@ export default {
'builtins.lobe-skills.apiName.activateProjectSkill': 'Activate Project Skill',
'builtins.lobe-skills.apiName.searchSkill': 'Search Skills',
'builtins.lobe-skills.title': 'Skills',
+ 'builtins.lobe-dashboard.apiName.addWidgetToDashboard': 'Add widget to dashboard',
+ 'builtins.lobe-dashboard.apiName.createWidgetDraft': 'Create widget draft',
+ 'builtins.lobe-dashboard.apiName.dryRunWidget': 'Dry-run widget',
+ 'builtins.lobe-dashboard.apiName.getWidgetRuns': 'Check widget runs',
+ 'builtins.lobe-dashboard.apiName.listDashboards': 'List dashboards',
+ 'builtins.lobe-dashboard.apiName.requestPublish': 'Publish widget',
+ 'builtins.lobe-dashboard.apiName.updateWidgetDraft': 'Update widget draft',
+ 'builtins.lobe-dashboard.title': 'Dashboards',
'builtins.lobe-task.apiName.createTask': 'Create task',
'builtins.lobe-task.apiName.createGoal': 'Start goal',
'builtins.lobe-goal.apiName.createGoal': 'Start goal',
diff --git a/packages/locales/src/default/project.ts b/packages/locales/src/default/project.ts
index 10df9f8d77d..c0cfb37ca4c 100644
--- a/packages/locales/src/default/project.ts
+++ b/packages/locales/src/default/project.ts
@@ -221,6 +221,7 @@ export default {
'overview.tasksTitle': 'Project tasks',
'sections.agents': 'Agents',
'sections.acceptance': 'Acceptance',
+ 'sections.dashboard': 'Dashboards',
'sections.goals': 'Goals',
'sections.home': 'Project home',
'sections.knowledgeBases': 'Libraries',
diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.ts
index 814e4480141..9b298351347 100644
--- a/packages/locales/src/default/setting.ts
+++ b/packages/locales/src/default/setting.ts
@@ -3645,6 +3645,9 @@ When I am ___, I need ___
'tools.builtins.lobe-skill-store.title': 'Skill Store',
'tools.builtins.lobe-skills.description': 'Activate and use reusable skill packages',
'tools.builtins.lobe-skills.title': 'Skills',
+ 'tools.builtins.lobe-dashboard.description':
+ 'Build live monitoring widgets from sandboxed scripts, preview them with real data and put them on dashboards',
+ 'tools.builtins.lobe-dashboard.title': 'Dashboards',
'tools.builtins.lobe-task.description':
'Create, schedule, list, edit, and delete tasks with dependencies and review configuration',
'tools.builtins.lobe-task.title': 'Task Tools',
diff --git a/packages/openapi/src/helpers/public-fields.ts b/packages/openapi/src/helpers/public-fields.ts
index 0b010ec5a51..96c4fbc5076 100644
--- a/packages/openapi/src/helpers/public-fields.ts
+++ b/packages/openapi/src/helpers/public-fields.ts
@@ -338,7 +338,7 @@ export const projectPublicSession = (value: SessionItem): PublicSession =>
export const projectPublicTopic = (value: TopicItem): PublicTopic =>
pickPublicFields(value, PUBLIC_TOPIC_FIELDS);
-export const projectPublicMessage = (value: MessageItem): PublicMessage =>
+export const projectPublicMessage = (value: PublicMessage): PublicMessage =>
pickPublicFields(value, PUBLIC_MESSAGE_FIELDS);
export const projectPublicEvalRun = (value: AgentEvalRunItem): PublicEvalRun =>
diff --git a/packages/openapi/src/services/message.service.ts b/packages/openapi/src/services/message.service.ts
index 2d75e30f90f..9aa975f4ef4 100644
--- a/packages/openapi/src/services/message.service.ts
+++ b/packages/openapi/src/services/message.service.ts
@@ -1,6 +1,6 @@
import { and, asc, count, desc, eq, ilike, inArray, isNull } from 'drizzle-orm';
-import type { FileItem, MessageItem, SessionItem, TopicItem } from '@/database/schemas';
+import type { FileItem, SessionItem, TopicItem } from '@/database/schemas';
import { messages, messagesFiles } from '@/database/schemas';
import type { LobeChatDatabase } from '@/database/type';
import { idGenerator } from '@/database/utils/idGenerator';
@@ -61,7 +61,7 @@ export class MessageService extends BaseService {
return await Promise.all(
messages.map(async (message) => {
return {
- ...projectPublicMessage(message as MessageItem),
+ ...projectPublicMessage(message),
files: await Promise.all(
message.filesToMessages?.map(async ({ file }) => {
const publicFile = projectPublicFile(file as FileItem);
diff --git a/packages/types/src/serverConfig.ts b/packages/types/src/serverConfig.ts
index e175688ecfd..45bc815e77d 100644
--- a/packages/types/src/serverConfig.ts
+++ b/packages/types/src/serverConfig.ts
@@ -27,6 +27,12 @@ export type IFeatureFlagsState = {
enableAgentShare: boolean | undefined;
enableAuthCaptcha: boolean | undefined;
enableCheckUpdates: boolean | undefined;
+ /**
+ * Dashboards and the `lobe-dashboard` agent tool (`dashboard`). Off by
+ * default: the pages, Portal view, in-chat previews and the tool are hidden
+ * and the widget / dashboard APIs answer FORBIDDEN.
+ */
+ enableDashboard: boolean | undefined;
enableDevDock: boolean | undefined;
/**
* Rollout gate for the multiplexed gateway socket. Necessary but not
@@ -161,6 +167,15 @@ export interface GlobalServerConfig {
* Undefined means "not configured": the default (64) applies.
*/
toolNameMaxLength?: number;
+ /**
+ * How the widget sandbox encodes the manifest's network allowlist
+ * (`WIDGET_SANDBOX_NETWORK_FORMAT`): `allowlist` when the Worker restricts
+ * egress to the declared hosts, `boolean` — or absent, the deployed
+ * Worker's only format — when the sandbox only gets an on/off switch and
+ * cannot enforce hosts. The publish review reads this to disclose
+ * unrestricted egress instead of presenting the allowlist as enforced.
+ */
+ widgetSandboxNetworkFormat?: 'allowlist' | 'boolean';
}
export interface GlobalBillboardItemLocaleFields {
diff --git a/packages/types/src/tool/builtin.ts b/packages/types/src/tool/builtin.ts
index 494a502be99..397b44c5109 100644
--- a/packages/types/src/tool/builtin.ts
+++ b/packages/types/src/tool/builtin.ts
@@ -562,6 +562,14 @@ export interface BuiltinInterventionProps<Arguments = any> {
identifier?: string;
interactionMode?: 'approval' | 'custom';
messageId: string;
+ /**
+ * Hold the host's approve action while the intervention cannot show what is
+ * being approved — e.g. its review data is still loading or failed to load.
+ * Pass `true` to block approval and `false` to release it; reject / stop stay
+ * available. Hosts without approval controls ignore it. Only approval-mode
+ * interventions receive it.
+ */
+ onApprovalBlockedChange?: (blocked: boolean) => void;
/**
* Callback to update the arguments before approval
* This is called when the user modifies the intervention content
diff --git a/src/features/CommandMenu/MainMenu.tsx b/src/features/CommandMenu/MainMenu.tsx
index 255c0df4b04..8aae4b96294 100644
--- a/src/features/CommandMenu/MainMenu.tsx
+++ b/src/features/CommandMenu/MainMenu.tsx
@@ -16,6 +16,7 @@ import { useTranslation } from 'react-i18next';
import { openFeedbackModal } from '@/components/FeedbackModal';
import { getNavigableRoutes, getRouteById } from '@/config/routes';
import { FEEDBACK } from '@/const/url';
+import { useHomeDashboardFeature } from '@/features/Dashboard/hooks/useDashboardFeature';
import { usePermission } from '@/hooks/usePermission';
import { useChatStore } from '@/store/chat';
import { topicSelectors } from '@/store/chat/selectors';
@@ -29,6 +30,7 @@ const MainMenu = memo(() => {
const { pathname, menuContext, setPages, pages, onClose } = useCommandMenuContext();
const { t } = useTranslation('common');
const { allowed: canCreate } = usePermission('create_content');
+ const { enabled: dashboardEnabled } = useHomeDashboardFeature();
// While the first send from the new-topic view is still creating the real
// topic, openNewTopicOrSaveTopic is a no-op — disable the command instead of
// letting it close the palette as a false success (same as the sidebar entry).
@@ -129,25 +131,28 @@ const MainMenu = memo(() => {
</Command.Group>
<Command.Group heading={t('cmdk.navigate')}>
- {getNavigableRoutes().map((route) => {
- const RouteIcon = route.icon;
- const keywords = route.keywordsKey
- ? t(route.keywordsKey as any).split(' ')
- : route.keywords;
- return (
- !pathname?.startsWith(route.pathPrefix) && (
- <CommandItem
- icon={<RouteIcon />}
- key={route.id}
- keywords={keywords}
- value={route.id}
- onSelect={() => handleNavigate(route.path)}
- >
- {t(route.cmdkKey as any)}
- </CommandItem>
- )
- );
- })}
+ {getNavigableRoutes()
+ // The home dashboard is personal-only and behind the `dashboard` flag.
+ .filter((route) => route.id !== 'dashboard' || dashboardEnabled)
+ .map((route) => {
+ const RouteIcon = route.icon;
+ const keywords = route.keywordsKey
+ ? t(route.keywordsKey as any).split(' ')
+ : route.keywords;
+ return (
+ !pathname?.startsWith(route.pathPrefix) && (
+ <CommandItem
+ icon={<RouteIcon />}
+ key={route.id}
+ keywords={keywords}
+ value={route.id}
+ onSelect={() => handleNavigate(route.path)}
+ >
+ {t(route.cmdkKey as any)}
+ </CommandItem>
+ )
+ );
+ })}
</Command.Group>
<Command.Group heading={t('cmdk.about')}>
diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/ApprovalActions.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/ApprovalActions.tsx
index 5ded04a44c0..1662bc54c7a 100644
--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/ApprovalActions.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/ApprovalActions.tsx
@@ -9,12 +9,18 @@ import { useTranslation } from 'react-i18next';
import { useConversationResourceAccess } from '../../../../../hooks/useConversationResourceAccess';
import { useConversationStore } from '../../../../../store';
+import { type ApprovalChoice, isChoiceSubmitBlocked } from './approvalGate';
import { type ApprovalMode } from './index';
import { isSubmitShortcutBlockedByTarget } from './submitShortcutGuard';
interface ApprovalActionsProps {
apiName: string;
approvalMode: ApprovalMode;
+ /**
+ * Hold the approve choices: the intervention cannot show what is being
+ * approved yet (see `onApprovalBlockedChange`). Reject and stop stay enabled.
+ */
+ approveDisabled?: boolean;
assistantGroupId?: string;
identifier: string;
messageId: string;
@@ -27,7 +33,7 @@ interface ApprovalActionsProps {
toolCallId: string;
}
-type Choice = 'approve' | 'approve-remember' | 'reject';
+type Choice = ApprovalChoice;
const styles = createStaticStyles(({ css, cssVar }) => ({
container: css`
@@ -130,7 +136,15 @@ const styles = createStaticStyles(({ css, cssVar }) => ({
}));
const ApprovalActions = memo<ApprovalActionsProps>(
- ({ approvalMode, apiName, assistantGroupId, identifier, messageId, onBeforeApprove }) => {
+ ({
+ approvalMode,
+ approveDisabled,
+ apiName,
+ assistantGroupId,
+ identifier,
+ messageId,
+ onBeforeApprove,
+ }) => {
const { t } = useTranslation('chat');
const [choice, setChoice] = useState<Choice>('approve');
const [reason, setReason] = useState('');
@@ -183,8 +197,9 @@ const ApprovalActions = memo<ApprovalActionsProps>(
stopPendingApprovalForCard,
messageId,
]);
+ const submitBlocked = isChoiceSubmitBlocked(choice, approveDisabled);
const handleSubmit = useCallback(async () => {
- if (loading || isMessageCreating || !canUseResource) return;
+ if (loading || isMessageCreating || !canUseResource || submitBlocked) return;
setLoading(true);
try {
if (choice === 'reject') {
@@ -215,6 +230,7 @@ const ApprovalActions = memo<ApprovalActionsProps>(
onBeforeApprove,
reason,
rejectAndContinueToolCall,
+ submitBlocked,
]);
// When choice flips to reject (via click on row, '2', or arrow), pull focus
@@ -354,6 +370,7 @@ const ApprovalActions = memo<ApprovalActionsProps>(
return (
<div
aria-checked={choice === c}
+ aria-disabled={approveDisabled || undefined}
className={cx(styles.option, choice === c && styles.optionSelected)}
key={c}
role="radio"
@@ -379,7 +396,7 @@ const ApprovalActions = memo<ApprovalActionsProps>(
</Button>
<Button
className={styles.submitButton}
- disabled={isMessageCreating}
+ disabled={isMessageCreating || submitBlocked}
loading={loading}
size={'middle'}
type={'primary'}
diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/Fallback.test.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/Fallback.test.tsx
index 9f864f4b08f..bc532b071f8 100644
--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/Fallback.test.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/Fallback.test.tsx
@@ -36,6 +36,18 @@ vi.mock('react-i18next', () => ({
vi.mock('@lobechat/builtin-tools/interventions', () => ({
getBuiltinIntervention: (identifier?: string, apiName?: string) => {
+ if (identifier === 'gated' && apiName === 'review') {
+ return ({ onApprovalBlockedChange }: BuiltinInterventionProps) => (
+ <>
+ <button type="button" onClick={() => onApprovalBlockedChange?.(true)}>
+ block
+ </button>
+ <button type="button" onClick={() => onApprovalBlockedChange?.(false)}>
+ release
+ </button>
+ </>
+ );
+ }
if (identifier !== 'devin' || apiName !== 'askUserQuestion') return;
return ({ onInteractionAction }: BuiltinInterventionProps) => (
@@ -114,7 +126,11 @@ vi.mock('../Arguments', () => ({
}));
vi.mock('./ApprovalActions', () => ({
- default: () => <div>approval-actions</div>,
+ default: ({ approveDisabled }: { approveDisabled?: boolean }) => (
+ <div data-approve-disabled={String(!!approveDisabled)} data-testid="approval-actions">
+ approval-actions
+ </div>
+ ),
}));
vi.mock('./KeyValueEditor', () => ({
@@ -197,3 +213,25 @@ describe('heterogeneous custom intervention', () => {
});
});
});
+
+describe('approval-mode builtin intervention', () => {
+ it('holds the approve action while the intervention blocks approval', () => {
+ render(
+ <Intervention
+ apiName="review"
+ id="message-gated"
+ identifier="gated"
+ requestArgs="{}"
+ toolCallId="gated-1"
+ />,
+ );
+ const actions = screen.getByTestId('approval-actions');
+ expect(actions).toHaveAttribute('data-approve-disabled', 'false');
+
+ fireEvent.click(screen.getByText('block'));
+ expect(actions).toHaveAttribute('data-approve-disabled', 'true');
+
+ fireEvent.click(screen.getByText('release'));
+ expect(actions).toHaveAttribute('data-approve-disabled', 'false');
+ });
+});
diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/approvalGate.test.ts b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/approvalGate.test.ts
new file mode 100644
index 00000000000..cade3732ef2
--- /dev/null
+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/approvalGate.test.ts
@@ -0,0 +1,20 @@
+import { describe, expect, it } from 'vitest';
+
+import { isChoiceSubmitBlocked } from './approvalGate';
+
+describe('isChoiceSubmitBlocked', () => {
+ it('holds both approve choices while the intervention blocks approval', () => {
+ expect(isChoiceSubmitBlocked('approve', true)).toBe(true);
+ expect(isChoiceSubmitBlocked('approve-remember', true)).toBe(true);
+ });
+
+ it('always lets the user reject', () => {
+ expect(isChoiceSubmitBlocked('reject', true)).toBe(false);
+ });
+
+ it('lets every choice through when nothing blocks approval', () => {
+ expect(isChoiceSubmitBlocked('approve', false)).toBe(false);
+ expect(isChoiceSubmitBlocked('approve-remember')).toBe(false);
+ expect(isChoiceSubmitBlocked('reject')).toBe(false);
+ });
+});
diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/approvalGate.ts b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/approvalGate.ts
new file mode 100644
index 00000000000..fc9636d8c7c
--- /dev/null
+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/approvalGate.ts
@@ -0,0 +1,9 @@
+export type ApprovalChoice = 'approve' | 'approve-remember' | 'reject';
+
+/**
+ * Whether submitting `choice` must wait. Approving is held while the
+ * intervention reports it cannot show what is being approved
+ * (`approveDisabled`); rejecting is always allowed, so the user is never stuck.
+ */
+export const isChoiceSubmitBlocked = (choice: ApprovalChoice, approveDisabled = false) =>
+ approveDisabled && choice !== 'reject';
diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/index.tsx b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/index.tsx
index 4fd9e3dac77..ada3935466d 100644
--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/index.tsx
+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/index.tsx
@@ -43,6 +43,9 @@ const Intervention = memo<InterventionProps>(
const approvalMode = useUserStore(toolInterventionSelectors.approvalMode);
const { canUseResource } = useConversationResourceAccess();
const [isEditing, setIsEditing] = useState(false);
+ // Raised by an intervention that cannot show what is being approved yet
+ // (review data loading or failed); the approve action waits on it.
+ const [approvalBlocked, setApprovalBlocked] = useState(false);
const updatePluginArguments = useConversationStore((s) => s.updatePluginArguments);
const message = useConversationStore((s) => dataSelectors.getDbMessageById(id)(s));
const usesDurableServerClaim = Boolean(
@@ -310,6 +313,7 @@ const Intervention = memo<InterventionProps>(
<ApprovalActions
apiName={apiName}
approvalMode={approvalMode}
+ approveDisabled={approvalBlocked}
assistantGroupId={assistantGroupId}
identifier={identifier}
messageId={id}
@@ -328,6 +332,7 @@ const Intervention = memo<InterventionProps>(
identifier={identifier}
messageId={id}
registerBeforeApprove={registerBeforeApprove}
+ onApprovalBlockedChange={setApprovalBlocked}
onArgsChange={handleArgsChange}
/>
{actionsPortalTarget ? createPortal(actions, actionsPortalTarget) : actions}
diff --git a/src/features/Dashboard/Board/BoardHeader.tsx b/src/features/Dashboard/Board/BoardHeader.tsx
new file mode 100644
index 00000000000..36042fac174
--- /dev/null
+++ b/src/features/Dashboard/Board/BoardHeader.tsx
@@ -0,0 +1,129 @@
+'use client';
+
+import { Flexbox } from '@lobehub/ui';
+import { Button, Text, Tooltip } from '@lobehub/ui/base-ui';
+import { createStaticStyles, cssVar } from 'antd-style';
+import dayjs from 'dayjs';
+import { LayoutGridIcon, RefreshCwIcon } from 'lucide-react';
+import { memo, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { usePermission } from '@/hooks/usePermission';
+import type { DashboardWidgetItem } from '@/services/dashboard';
+
+import { dashboardPageStyles as pageStyles } from '../pageStyles';
+import { getWidgetHealth, getWidgetUpdatedAt } from '../utils/widgetHealth';
+import { getHealthTone, HEALTH_TONE_COLOR, type WidgetHealthTone } from '../WidgetCard/HealthDot';
+
+const styles = createStaticStyles(({ css }) => ({
+ dot: css`
+ flex: none;
+ width: 6px;
+ height: 6px;
+ border-radius: 50%;
+ `,
+ meta: css`
+ font-size: 12px;
+ font-variant-numeric: tabular-nums;
+ color: ${cssVar.colorTextTertiary};
+ `,
+ sep: css`
+ color: ${cssVar.colorTextQuaternary};
+ `,
+}));
+
+/** Tones the summary calls out, in the order a reader should notice them. */
+const SUMMARY_TONES = ['failed', 'stale', 'running', 'ok'] as const;
+
+interface BoardHeaderProps {
+ description?: string | null;
+ /** Absent for viewers who cannot save the board's layout (not its creator). */
+ onEditLayout?: () => void;
+ onRefreshAll: () => void;
+ refreshingAll: boolean;
+ runnableCount: number;
+ title?: string;
+ widgets: DashboardWidgetItem[];
+}
+
+/**
+ * The board's own heading: what it watches, how healthy its widgets are right
+ * now and when it last heard from them, with the board-wide actions.
+ */
+const BoardHeader = memo<BoardHeaderProps>(
+ ({ title, description, widgets, runnableCount, refreshingAll, onRefreshAll, onEditLayout }) => {
+ const { t } = useTranslation('dashboard');
+ // Refreshing spends sandbox time on the user's behalf — the same
+ // create_content permission the server enforces on widget.run.
+ const { allowed: canRefresh } = usePermission('create_content');
+
+ const { counts, lastUpdatedAt } = useMemo(() => {
+ const counts: Partial<Record<WidgetHealthTone, number>> = {};
+ let lastUpdatedAt: number | undefined;
+ for (const widget of widgets) {
+ const tone = getHealthTone(getWidgetHealth(widget));
+ counts[tone] = (counts[tone] ?? 0) + 1;
+ const updatedAt = getWidgetUpdatedAt(widget);
+ if (updatedAt) {
+ const time = new Date(updatedAt).getTime();
+ if (lastUpdatedAt === undefined || time > lastUpdatedAt) lastUpdatedAt = time;
+ }
+ }
+ return { counts, lastUpdatedAt };
+ }, [widgets]);
+
+ return (
+ <Flexbox
+ data-dashboard-header
+ horizontal
+ align={'flex-end'}
+ className={pageStyles.heading}
+ gap={16}
+ justify={'space-between'}
+ >
+ <Flexbox gap={6} style={{ minWidth: 0 }}>
+ {title && <h1 className={pageStyles.title}>{title}</h1>}
+ {description && <Text className={pageStyles.description}>{description}</Text>}
+ <Flexbox horizontal align={'center'} className={styles.meta} gap={10} wrap={'wrap'}>
+ <span>{t('board.widgetCount', { count: widgets.length })}</span>
+ {SUMMARY_TONES.filter((tone) => counts[tone]).map((tone) => (
+ <Flexbox horizontal align={'center'} data-dashboard-health={tone} gap={5} key={tone}>
+ <span className={styles.dot} style={{ background: HEALTH_TONE_COLOR[tone] }} />
+ {t(`board.health.${tone}`, { count: counts[tone] })}
+ </Flexbox>
+ ))}
+ {lastUpdatedAt !== undefined && (
+ <>
+ <span className={styles.sep}>·</span>
+ <Tooltip title={dayjs(lastUpdatedAt).format('YYYY-MM-DD HH:mm:ss')}>
+ <span>{t('board.lastUpdated', { time: dayjs(lastUpdatedAt).fromNow() })}</span>
+ </Tooltip>
+ </>
+ )}
+ </Flexbox>
+ </Flexbox>
+ <Flexbox horizontal gap={8} style={{ flex: 'none' }}>
+ {canRefresh && (
+ <Button
+ disabled={runnableCount === 0}
+ icon={RefreshCwIcon}
+ loading={refreshingAll}
+ onClick={onRefreshAll}
+ >
+ {t('board.refreshAll')}
+ </Button>
+ )}
+ {onEditLayout && (
+ <Button icon={LayoutGridIcon} onClick={onEditLayout}>
+ {t('layout.edit')}
+ </Button>
+ )}
+ </Flexbox>
+ </Flexbox>
+ );
+ },
+);
+
+BoardHeader.displayName = 'DashboardBoardHeader';
+
+export default BoardHeader;
diff --git a/src/features/Dashboard/Board/BoardWidgetCard.tsx b/src/features/Dashboard/Board/BoardWidgetCard.tsx
new file mode 100644
index 00000000000..7a16e776caa
--- /dev/null
+++ b/src/features/Dashboard/Board/BoardWidgetCard.tsx
@@ -0,0 +1,35 @@
+'use client';
+
+import { memo } from 'react';
+
+import type { DashboardWidgetItem } from '@/services/dashboard';
+import { dashboardSelectors, useDashboardStore } from '@/store/dashboard';
+
+import { useWidgetTrend } from '../hooks/useWidgetTrend';
+import WidgetCard from '../WidgetCard';
+import WidgetRefreshButton from '../WidgetRefreshButton';
+
+interface BoardWidgetCardProps {
+ onOpen: (widgetId: string) => void;
+ widget: DashboardWidgetItem;
+}
+
+/** A widget card wired to the board: live trend, manual refresh and drill-down. */
+const BoardWidgetCard = memo<BoardWidgetCardProps>(({ widget, onOpen }) => {
+ const trend = useWidgetTrend(widget);
+ const running = useDashboardStore(dashboardSelectors.isWidgetRunning(widget.id));
+
+ return (
+ <WidgetCard
+ actions={<WidgetRefreshButton widget={widget} />}
+ runningLocally={running}
+ trend={trend}
+ widget={widget}
+ onOpen={() => onOpen(widget.id)}
+ />
+ );
+});
+
+BoardWidgetCard.displayName = 'DashboardBoardWidgetCard';
+
+export default BoardWidgetCard;
diff --git a/src/features/Dashboard/Board/LayoutEditor.tsx b/src/features/Dashboard/Board/LayoutEditor.tsx
new file mode 100644
index 00000000000..1eb67a97fcb
--- /dev/null
+++ b/src/features/Dashboard/Board/LayoutEditor.tsx
@@ -0,0 +1,229 @@
+'use client';
+
+import {
+ closestCenter,
+ DndContext,
+ type DragEndEvent,
+ KeyboardSensor,
+ PointerSensor,
+ useSensor,
+ useSensors,
+} from '@dnd-kit/core';
+import {
+ arrayMove,
+ rectSortingStrategy,
+ SortableContext,
+ sortableKeyboardCoordinates,
+ useSortable,
+} from '@dnd-kit/sortable';
+import { CSS } from '@dnd-kit/utilities';
+import type { DashboardItemLayout } from '@lobechat/types';
+import { Flexbox, Icon } from '@lobehub/ui';
+import { ActionIcon, Button, toast } from '@lobehub/ui/base-ui';
+import { cx } from 'antd-style';
+import {
+ ChevronDownIcon,
+ ChevronLeftIcon,
+ ChevronRightIcon,
+ ChevronUpIcon,
+ GripVerticalIcon,
+} from 'lucide-react';
+import { memo, useMemo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import type { DashboardBoardItem } from '@/services/dashboard';
+import { dashboardSelectors, useDashboardStore } from '@/store/dashboard';
+
+import {
+ DASHBOARD_MAX_H,
+ DASHBOARD_MIN_H,
+ DASHBOARD_WIDTH_PRESETS,
+ flowLayouts,
+} from '../utils/layout';
+import WidgetCard from '../WidgetCard';
+import { cellStyle, gridStyles } from './style';
+
+type Size = { h: number; w: number };
+
+const stepWidth = (w: number, direction: 1 | -1) => {
+ const presets = [...DASHBOARD_WIDTH_PRESETS];
+ if (direction > 0) return presets.find((preset) => preset > w) ?? w;
+ return presets.reverse().find((preset) => preset < w) ?? w;
+};
+
+interface EditableCellProps {
+ entry: DashboardBoardItem;
+ layout: DashboardItemLayout;
+ onResize: (size: Size) => void;
+}
+
+const EditableCell = memo<EditableCellProps>(({ entry, layout, onResize }) => {
+ const { t } = useTranslation('dashboard');
+ const { attributes, isDragging, listeners, setNodeRef, transform, transition } = useSortable({
+ id: entry.item.id,
+ });
+
+ const resizeActions = (
+ <>
+ <ActionIcon
+ aria-label={t('layout.narrower')}
+ disabled={layout.w <= DASHBOARD_WIDTH_PRESETS[0]}
+ icon={ChevronLeftIcon}
+ size={'small'}
+ title={t('layout.narrower')}
+ onClick={() => onResize({ h: layout.h, w: stepWidth(layout.w, -1) })}
+ />
+ <ActionIcon
+ aria-label={t('layout.wider')}
+ disabled={layout.w >= DASHBOARD_WIDTH_PRESETS.at(-1)!}
+ icon={ChevronRightIcon}
+ size={'small'}
+ title={t('layout.wider')}
+ onClick={() => onResize({ h: layout.h, w: stepWidth(layout.w, 1) })}
+ />
+ <ActionIcon
+ aria-label={t('layout.shorter')}
+ disabled={layout.h <= DASHBOARD_MIN_H}
+ icon={ChevronUpIcon}
+ size={'small'}
+ title={t('layout.shorter')}
+ onClick={() => onResize({ h: layout.h - 1, w: layout.w })}
+ />
+ <ActionIcon
+ aria-label={t('layout.taller')}
+ disabled={layout.h >= DASHBOARD_MAX_H}
+ icon={ChevronDownIcon}
+ size={'small'}
+ title={t('layout.taller')}
+ onClick={() => onResize({ h: layout.h + 1, w: layout.w })}
+ />
+ </>
+ );
+
+ return (
+ <div
+ className={cx(gridStyles.cell, isDragging && gridStyles.cellDragging)}
+ data-layout-cell={entry.item.id}
+ ref={setNodeRef}
+ style={{
+ ...cellStyle(layout),
+ transform: CSS.Translate.toString(transform),
+ transition,
+ }}
+ >
+ <WidgetCard
+ actions={resizeActions}
+ className={gridStyles.editCard}
+ widget={entry.widget}
+ handle={
+ <span
+ className={gridStyles.handle}
+ {...attributes}
+ {...listeners}
+ aria-label={t('layout.drag')}
+ >
+ <Icon icon={GripVerticalIcon} size={14} />
+ </span>
+ }
+ />
+ </div>
+ );
+});
+
+EditableCell.displayName = 'DashboardEditableCell';
+
+interface LayoutEditorProps {
+ dashboardId: string;
+ /** Current cells, used as the starting point of the draft. */
+ initialLayouts: Record<string, DashboardItemLayout>;
+ /** Items in reading order. */
+ items: DashboardBoardItem[];
+ onDone: () => void;
+}
+
+/**
+ * Edit a board's layout as a draft: drag to reorder, step width / height, then
+ * save every cell to `dashboard_items.layout` in one request or discard.
+ */
+const LayoutEditor = memo<LayoutEditorProps>(({ dashboardId, items, initialLayouts, onDone }) => {
+ const { t } = useTranslation('dashboard');
+ const saveDashboardLayout = useDashboardStore((s) => s.saveDashboardLayout);
+ const saving = useDashboardStore(dashboardSelectors.isLayoutSaving(dashboardId));
+
+ const [order, setOrder] = useState(() => items.map((entry) => entry.item.id));
+ const [sizes, setSizes] = useState<Record<string, Size>>(() =>
+ Object.fromEntries(
+ Object.entries(initialLayouts).map(([id, layout]) => [id, { h: layout.h, w: layout.w }]),
+ ),
+ );
+
+ const byId = useMemo(() => new Map(items.map((entry) => [entry.item.id, entry])), [items]);
+ const draftLayouts = useMemo(
+ () =>
+ flowLayouts(
+ order
+ .filter((id) => byId.has(id))
+ .map((id) => ({ id, ...(sizes[id] ?? { h: DASHBOARD_MIN_H, w: 3 }) })),
+ ),
+ [order, sizes, byId],
+ );
+
+ const sensors = useSensors(
+ useSensor(PointerSensor, { activationConstraint: { distance: 4 } }),
+ useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates }),
+ );
+
+ const handleDragEnd = ({ active, over }: DragEndEvent) => {
+ if (!over || active.id === over.id) return;
+ setOrder((current) =>
+ arrayMove(current, current.indexOf(String(active.id)), current.indexOf(String(over.id))),
+ );
+ };
+
+ const handleSave = async () => {
+ try {
+ await saveDashboardLayout(dashboardId, draftLayouts, order);
+ toast.success(t('layout.saved'));
+ onDone();
+ } catch (error) {
+ console.error('[dashboard] failed to save layout', error);
+ toast.error(t('layout.saveFailed'));
+ }
+ };
+
+ return (
+ <Flexbox gap={12}>
+ <Flexbox horizontal align={'center'} gap={8} justify={'flex-end'}>
+ <Button disabled={saving} onClick={onDone}>
+ {t('layout.cancel')}
+ </Button>
+ <Button loading={saving} type={'primary'} onClick={() => void handleSave()}>
+ {t('layout.save')}
+ </Button>
+ </Flexbox>
+ <DndContext collisionDetection={closestCenter} sensors={sensors} onDragEnd={handleDragEnd}>
+ <SortableContext items={order} strategy={rectSortingStrategy}>
+ <div className={gridStyles.grid} data-dashboard-grid={'editing'}>
+ {order.map((id) => {
+ const entry = byId.get(id);
+ const layout = draftLayouts[id];
+ if (!entry || !layout) return null;
+ return (
+ <EditableCell
+ entry={entry}
+ key={id}
+ layout={layout}
+ onResize={(size) => setSizes((current) => ({ ...current, [id]: size }))}
+ />
+ );
+ })}
+ </div>
+ </SortableContext>
+ </DndContext>
+ </Flexbox>
+ );
+});
+
+LayoutEditor.displayName = 'DashboardLayoutEditor';
+
+export default LayoutEditor;
diff --git a/src/features/Dashboard/Board/index.tsx b/src/features/Dashboard/Board/index.tsx
new file mode 100644
index 00000000000..ae93d5166af
--- /dev/null
+++ b/src/features/Dashboard/Board/index.tsx
@@ -0,0 +1,144 @@
+'use client';
+
+import { Center, Empty, Flexbox } from '@lobehub/ui';
+import { toast } from '@lobehub/ui/base-ui';
+import { LayoutDashboardIcon } from 'lucide-react';
+import { memo, useMemo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import AsyncBoundary from '@/components/AsyncBoundary';
+import { usePermission } from '@/hooks/usePermission';
+import { dashboardSelectors, useDashboardStore } from '@/store/dashboard';
+import { useUserStore } from '@/store/user';
+import { userProfileSelectors } from '@/store/user/selectors';
+
+import { resolveLayouts, sortByPosition } from '../utils/layout';
+import { isUsableRunStatus } from '../utils/widgetHealth';
+import WidgetDetailDrawer from '../WidgetDetail';
+import BoardHeader from './BoardHeader';
+import BoardWidgetCard from './BoardWidgetCard';
+import LayoutEditor from './LayoutEditor';
+import { cellStyle, gridStyles } from './style';
+
+export interface DashboardBoardProps {
+ dashboardId: string;
+ /** Shown when the board has no widgets; hosts explain how widgets get here. */
+ empty?: React.ReactNode;
+}
+
+/**
+ * A board's widget grid: cards laid out from `dashboard_items.layout`, manual
+ * refresh, layout editing and the per-widget drill-down. Hosts (home page,
+ * project page, portal) mount it with a dashboard id and add their own chrome.
+ */
+const DashboardBoard = memo<DashboardBoardProps>(({ dashboardId, empty }) => {
+ const { t } = useTranslation('dashboard');
+ const useFetchDashboardDetail = useDashboardStore((s) => s.useFetchDashboardDetail);
+ const runWidget = useDashboardStore((s) => s.runWidget);
+ const { data, error, isLoading, mutate } = useFetchDashboardDetail(dashboardId);
+ const detail = useDashboardStore(dashboardSelectors.dashboardDetail(dashboardId));
+ const userId = useUserStore(userProfileSelectors.userId);
+ const { allowed: canWrite } = usePermission('create_content');
+ const canEditLayout = useDashboardStore(
+ dashboardSelectors.canManageDashboard(dashboardId, userId, canWrite),
+ );
+
+ const [editing, setEditing] = useState(false);
+ const [openWidgetId, setOpenWidgetId] = useState<string>();
+ const [refreshingAll, setRefreshingAll] = useState(false);
+
+ const items = detail?.items;
+ // `data` is the raw server response — an older deployment may not send
+ // `items` yet, so normalize once before any dereference.
+ const responseItems = data?.items ?? [];
+ const { layouts, ordered } = useMemo(() => {
+ const entries = items ?? [];
+ const resolved = resolveLayouts(
+ entries.map(({ item, widget }) => ({
+ id: item.id,
+ layout: item.layout,
+ outputType: widget.latestOutput?.type,
+ })),
+ );
+ return {
+ layouts: resolved,
+ ordered: sortByPosition(
+ entries.map((entry) => ({ ...entry, id: entry.item.id })),
+ resolved,
+ ),
+ };
+ }, [items]);
+
+ const openWidget = items?.find(({ widget }) => widget.id === openWidgetId)?.widget;
+ const runnable = ordered.filter(({ widget }) => !!widget.publishedVersionId);
+
+ const handleRefreshAll = async () => {
+ setRefreshingAll(true);
+ try {
+ const results = await Promise.allSettled(runnable.map(({ widget }) => runWidget(widget.id)));
+ const failed = results.filter(
+ (result) =>
+ result.status === 'rejected' ||
+ (result.value !== undefined && !isUsableRunStatus(result.value.status)),
+ ).length;
+ if (failed > 0) toast.error(t('board.refreshAllFailed', { count: failed }));
+ } finally {
+ setRefreshingAll(false);
+ }
+ };
+
+ return (
+ <AsyncBoundary
+ data={data}
+ error={error}
+ isEmpty={responseItems.length === 0}
+ isLoading={isLoading}
+ empty={
+ empty ?? (
+ <Center flex={1} padding={48}>
+ <Empty description={t('board.empty')} icon={LayoutDashboardIcon} />
+ </Center>
+ )
+ }
+ onRetry={() => void mutate()}
+ >
+ {editing && canEditLayout ? (
+ <LayoutEditor
+ dashboardId={dashboardId}
+ initialLayouts={layouts}
+ items={ordered}
+ onDone={() => setEditing(false)}
+ />
+ ) : (
+ <Flexbox gap={20}>
+ <BoardHeader
+ description={detail?.description}
+ refreshingAll={refreshingAll}
+ runnableCount={runnable.length}
+ title={detail?.title}
+ widgets={ordered.map(({ widget }) => widget)}
+ onEditLayout={canEditLayout ? () => setEditing(true) : undefined}
+ onRefreshAll={() => void handleRefreshAll()}
+ />
+ <div className={gridStyles.grid} data-dashboard-grid={'view'}>
+ {ordered.map(({ item, widget }) => (
+ <div
+ className={gridStyles.cell}
+ data-layout-cell={item.id}
+ key={item.id}
+ style={cellStyle(layouts[item.id])}
+ >
+ <BoardWidgetCard widget={widget} onOpen={setOpenWidgetId} />
+ </div>
+ ))}
+ </div>
+ </Flexbox>
+ )}
+ <WidgetDetailDrawer widget={openWidget} onClose={() => setOpenWidgetId(undefined)} />
+ </AsyncBoundary>
+ );
+});
+
+DashboardBoard.displayName = 'DashboardBoard';
+
+export default DashboardBoard;
diff --git a/src/features/Dashboard/Board/style.ts b/src/features/Dashboard/Board/style.ts
new file mode 100644
index 00000000000..bb83646e3c9
--- /dev/null
+++ b/src/features/Dashboard/Board/style.ts
@@ -0,0 +1,55 @@
+import type { DashboardItemLayout } from '@lobechat/types';
+import { createStaticStyles } from 'antd-style';
+import type { CSSProperties } from 'react';
+
+import { DASHBOARD_GRID_COLUMNS, DASHBOARD_GRID_GAP, DASHBOARD_ROW_HEIGHT } from '../utils/layout';
+
+/**
+ * Cells read their placement from CSS variables (`--x`, `--y`, `--w`, `--h`) so
+ * the narrow-screen fallback can drop them and stack cards in reading order.
+ */
+export const gridStyles = createStaticStyles(({ css, cssVar }) => ({
+ cell: css`
+ grid-column: calc(var(--x) + 1) / span var(--w);
+ grid-row: calc(var(--y) + 1) / span var(--h);
+ min-width: 0;
+ min-height: 0;
+
+ @media (width <= 767px) {
+ grid-column: 1 / -1;
+ grid-row: auto / span var(--h);
+ }
+ `,
+ cellDragging: css`
+ z-index: 2;
+ opacity: 0.85;
+ `,
+ editCard: css`
+ outline: 1px dashed ${cssVar.colorBorder};
+ outline-offset: 2px;
+ `,
+ grid: css`
+ display: grid;
+ grid-auto-rows: ${DASHBOARD_ROW_HEIGHT}px;
+ grid-template-columns: repeat(${DASHBOARD_GRID_COLUMNS}, minmax(0, 1fr));
+ gap: ${DASHBOARD_GRID_GAP}px;
+
+ @media (width <= 767px) {
+ grid-template-columns: minmax(0, 1fr);
+ }
+ `,
+ handle: css`
+ touch-action: none;
+ cursor: grab;
+ flex: none;
+ color: ${cssVar.colorTextTertiary};
+
+ &:active {
+ cursor: grabbing;
+ }
+ `,
+}));
+
+/** Place a cell of `gridStyles.grid` at a resolved layout. */
+export const cellStyle = (layout: DashboardItemLayout) =>
+ ({ '--h': layout.h, '--w': layout.w, '--x': layout.x, '--y': layout.y }) as CSSProperties;
diff --git a/src/features/Dashboard/BoardPage.tsx b/src/features/Dashboard/BoardPage.tsx
new file mode 100644
index 00000000000..6c86b2d3b0b
--- /dev/null
+++ b/src/features/Dashboard/BoardPage.tsx
@@ -0,0 +1,79 @@
+'use client';
+
+import type { WidgetLevelFilter } from '@lobechat/types';
+import { Flexbox, Icon } from '@lobehub/ui';
+import { ActionIcon, Text } from '@lobehub/ui/base-ui';
+import { ChevronLeftIcon, LayoutDashboardIcon } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import NavHeader from '@/features/NavHeader';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { dashboardSelectors, useDashboardStore } from '@/store/dashboard';
+
+import DashboardBoard from './Board';
+import DashboardActionsMenu from './DashboardActionsMenu';
+import { dashboardPageStyles as styles } from './pageStyles';
+
+interface DashboardBoardPageProps {
+ /** The board list this page returns to, e.g. `/dashboard` or a project's dashboards. */
+ backPath?: string;
+ dashboardId: string;
+ /** The list level to refresh after a rename or trash. */
+ level?: WidgetLevelFilter;
+}
+
+/** Header chrome of a board page: back to the list, title and board menu. */
+const BoardPageHeader = memo<DashboardBoardPageProps>(
+ ({ backPath = '/dashboard', dashboardId, level }) => {
+ const { t } = useTranslation('dashboard');
+ const navigate = useWorkspaceAwareNavigate();
+ const detail = useDashboardStore(dashboardSelectors.dashboardDetail(dashboardId));
+
+ return (
+ <NavHeader
+ left={
+ <Flexbox horizontal align={'center'} gap={6}>
+ <ActionIcon
+ icon={ChevronLeftIcon}
+ size={'small'}
+ title={t('list.title')}
+ onClick={() => navigate(backPath)}
+ />
+ <Icon icon={LayoutDashboardIcon} size={16} />
+ <Text ellipsis weight={500}>
+ {detail?.title ?? ''}
+ </Text>
+ </Flexbox>
+ }
+ right={
+ detail && (
+ <DashboardActionsMenu
+ dashboard={detail}
+ level={level}
+ onTrashed={() => navigate(backPath)}
+ />
+ )
+ }
+ />
+ );
+ },
+);
+
+BoardPageHeader.displayName = 'DashboardBoardPageHeader';
+
+/** Page of one board — on the home level or inside a project. */
+const DashboardBoardPage = memo<DashboardBoardPageProps>(({ backPath, dashboardId, level }) => (
+ <Flexbox flex={1} height={'100%'}>
+ <BoardPageHeader backPath={backPath} dashboardId={dashboardId} level={level} />
+ <div className={styles.scroll}>
+ <div className={styles.canvas}>
+ <DashboardBoard dashboardId={dashboardId} />
+ </div>
+ </div>
+ </Flexbox>
+));
+
+DashboardBoardPage.displayName = 'DashboardBoardPage';
+
+export default DashboardBoardPage;
diff --git a/src/features/Dashboard/DashboardActionsMenu.tsx b/src/features/Dashboard/DashboardActionsMenu.tsx
new file mode 100644
index 00000000000..81fc5560ca4
--- /dev/null
+++ b/src/features/Dashboard/DashboardActionsMenu.tsx
@@ -0,0 +1,87 @@
+'use client';
+
+import type { WidgetLevelFilter } from '@lobechat/types';
+import { Icon } from '@lobehub/ui';
+import {
+ ActionIcon,
+ confirmModal,
+ type DropdownItem,
+ DropdownMenu,
+ toast,
+} from '@lobehub/ui/base-ui';
+import { MoreHorizontalIcon, PencilIcon, TrashIcon } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { usePermission } from '@/hooks/usePermission';
+import { useDashboardStore } from '@/store/dashboard';
+import { useUserStore } from '@/store/user';
+import { userProfileSelectors } from '@/store/user/selectors';
+
+import { openRenameDashboardModal } from './DashboardFormModal';
+
+interface DashboardActionsMenuProps {
+ dashboard: { id: string; title: string; userId: string };
+ level?: WidgetLevelFilter;
+ /** Called after the board moved to the trash, e.g. to leave its page. */
+ onTrashed?: () => void;
+}
+
+/**
+ * Rename / trash a board. Only its creator with the create_content
+ * permission may change it — a demoted owner keeps ownership but the server
+ * refuses their writes, so they get no menu either.
+ */
+const DashboardActionsMenu = memo<DashboardActionsMenuProps>(({ dashboard, level, onTrashed }) => {
+ const { t } = useTranslation(['dashboard', 'common']);
+ const trashDashboard = useDashboardStore((s) => s.trashDashboard);
+ const currentUserId = useUserStore(userProfileSelectors.userId);
+ const { allowed } = usePermission('create_content');
+
+ if (!allowed || currentUserId !== dashboard.userId) return null;
+
+ const items: DropdownItem[] = [
+ {
+ icon: <Icon icon={PencilIcon} />,
+ key: 'rename',
+ label: t('actions.rename'),
+ onClick: () =>
+ openRenameDashboardModal({ dashboardId: dashboard.id, level, title: dashboard.title }),
+ },
+ { type: 'divider' },
+ {
+ danger: true,
+ icon: <Icon icon={TrashIcon} />,
+ key: 'trash',
+ label: t('actions.trash'),
+ onClick: () =>
+ confirmModal({
+ cancelText: t('cancel', { ns: 'common' }),
+ content: t('actions.trashConfirm', { title: dashboard.title }),
+ okButtonProps: { danger: true },
+ okText: t('actions.trash'),
+ onOk: async () => {
+ try {
+ await trashDashboard(dashboard.id, level);
+ toast.success(t('actions.trashed', { title: dashboard.title }));
+ onTrashed?.();
+ } catch (error) {
+ console.error('[dashboard] trash failed', error);
+ toast.error(t('operationFailed', { ns: 'common' }));
+ }
+ },
+ title: t('actions.trashTitle'),
+ }),
+ },
+ ];
+
+ return (
+ <DropdownMenu items={items} placement={'bottomRight'}>
+ <ActionIcon icon={MoreHorizontalIcon} size={'small'} title={t('actions.more')} />
+ </DropdownMenu>
+ );
+});
+
+DashboardActionsMenu.displayName = 'DashboardActionsMenu';
+
+export default DashboardActionsMenu;
diff --git a/src/features/Dashboard/DashboardFormModal.test.ts b/src/features/Dashboard/DashboardFormModal.test.ts
new file mode 100644
index 00000000000..664c0c85b42
--- /dev/null
+++ b/src/features/Dashboard/DashboardFormModal.test.ts
@@ -0,0 +1,59 @@
+import type { ReactElement } from 'react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { dashboardService } from '@/services/dashboard';
+import { useDashboardStore } from '@/store/dashboard';
+import { initialState } from '@/store/dashboard/initialState';
+
+import { openCreateDashboardModal } from './DashboardFormModal';
+
+const modal = vi.hoisted(() => ({ content: undefined as ReactElement | undefined }));
+
+vi.mock('@lobehub/ui/base-ui', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ createModal: ({ content }: { content: ReactElement }) => {
+ modal.content = content;
+ },
+}));
+
+vi.mock('@/libs/swr', () => ({ mutate: vi.fn(), useClientDataSWR: vi.fn() }));
+
+vi.mock('@/services/dashboard', () => ({
+ dashboardService: { addItem: vi.fn(), create: vi.fn() },
+}));
+
+/** What the form's submit button runs; the form closes the modal only when it resolves. */
+const submit = (value: { description?: string; title: string }) =>
+ (modal.content!.props as { onSubmit: (value: unknown) => Promise<void> }).onSubmit(value);
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ modal.content = undefined;
+ useDashboardStore.setState(initialState);
+});
+
+describe('openCreateDashboardModal with a widget', () => {
+ it('creates the board and places the widget in one server write', async () => {
+ vi.mocked(dashboardService.create).mockResolvedValue({ id: 'd1', title: 'Ops' } as any);
+ const onCreated = vi.fn();
+
+ openCreateDashboardModal({ onCreated, widgetId: 'w1' });
+ await submit({ title: 'Ops' });
+
+ expect(dashboardService.create).toHaveBeenCalledTimes(1);
+ expect(dashboardService.create).toHaveBeenCalledWith({ title: 'Ops', widgetId: 'w1' });
+ expect(dashboardService.addItem).not.toHaveBeenCalled();
+ expect(onCreated).toHaveBeenCalledWith({ id: 'd1', title: 'Ops' });
+ });
+
+ it('fails the submit (keeping the modal open) when placement fails, with no separate placement', async () => {
+ vi.mocked(dashboardService.create).mockRejectedValue(new Error('Widget not found'));
+ const onCreated = vi.fn();
+
+ openCreateDashboardModal({ onCreated, widgetId: 'w1' });
+ await expect(submit({ title: 'Ops' })).rejects.toThrow('Widget not found');
+
+ expect(onCreated).not.toHaveBeenCalled();
+ expect(dashboardService.addItem).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/features/Dashboard/DashboardFormModal.tsx b/src/features/Dashboard/DashboardFormModal.tsx
new file mode 100644
index 00000000000..46d109a8e3a
--- /dev/null
+++ b/src/features/Dashboard/DashboardFormModal.tsx
@@ -0,0 +1,157 @@
+'use client';
+
+import type { WidgetLevelFilter } from '@lobechat/types';
+import { Flexbox } from '@lobehub/ui';
+import {
+ Button,
+ createModal,
+ Input,
+ ModalFooter,
+ Text,
+ TextArea,
+ toast,
+ useModalContext,
+} from '@lobehub/ui/base-ui';
+import { t as translate } from 'i18next';
+import { memo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useDashboardStore } from '@/store/dashboard';
+
+interface DashboardFormProps {
+ initialTitle?: string;
+ onSubmit: (value: { description?: string; title: string }) => Promise<void>;
+ showDescription?: boolean;
+ submitText: string;
+}
+
+const DashboardForm = memo<DashboardFormProps>(
+ ({ initialTitle = '', onSubmit, showDescription, submitText }) => {
+ const { t } = useTranslation(['dashboard', 'common']);
+ const { close } = useModalContext();
+ const [title, setTitle] = useState(initialTitle);
+ const [description, setDescription] = useState('');
+ const [loading, setLoading] = useState(false);
+ const trimmed = title.trim();
+
+ const handleSubmit = async () => {
+ if (!trimmed || loading) return;
+ setLoading(true);
+ try {
+ await onSubmit({ description: description.trim() || undefined, title: trimmed });
+ close();
+ } catch (error) {
+ console.error('[dashboard] form submit failed', error);
+ toast.error(t('operationFailed', { ns: 'common' }));
+ } finally {
+ setLoading(false);
+ }
+ };
+
+ return (
+ <>
+ <Flexbox gap={16} padding={16}>
+ <Flexbox gap={6}>
+ <Text fontSize={13} weight={500}>
+ {t('form.titleLabel')}
+ </Text>
+ <Input
+ autoFocus
+ data-dashboard-title-input
+ maxLength={200}
+ placeholder={t('form.titlePlaceholder')}
+ value={title}
+ onChange={(event) => setTitle(event.target.value)}
+ onPressEnter={() => void handleSubmit()}
+ />
+ </Flexbox>
+ {showDescription && (
+ <Flexbox gap={6}>
+ <Text fontSize={13} weight={500}>
+ {t('form.descriptionLabel')}
+ </Text>
+ <TextArea
+ autoSize={{ maxRows: 6, minRows: 2 }}
+ maxLength={2000}
+ placeholder={t('form.descriptionPlaceholder')}
+ value={description}
+ onChange={(event) => setDescription(event.target.value)}
+ />
+ </Flexbox>
+ )}
+ </Flexbox>
+ <ModalFooter>
+ <Button onClick={close}>{t('cancel', { ns: 'common' })}</Button>
+ <Button
+ disabled={!trimmed}
+ loading={loading}
+ type={'primary'}
+ onClick={() => void handleSubmit()}
+ >
+ {submitText}
+ </Button>
+ </ModalFooter>
+ </>
+ );
+ },
+);
+
+DashboardForm.displayName = 'DashboardForm';
+
+/**
+ * Create a board at `level` (personal when empty) and hand the new row to
+ * `onCreated`. With `widgetId`, the widget is placed on the board in the same
+ * server write: a failed placement creates no board and keeps the modal open.
+ */
+export const openCreateDashboardModal = ({
+ level = {},
+ onCreated,
+ widgetId,
+}: {
+ level?: WidgetLevelFilter;
+ onCreated?: (dashboard: { id: string; title: string }) => void;
+ widgetId?: string;
+} = {}) =>
+ createModal({
+ content: (
+ <DashboardForm
+ showDescription
+ submitText={translate('create.submit', { ns: 'dashboard' })}
+ onSubmit={async ({ description, title }) => {
+ const dashboard = await useDashboardStore
+ .getState()
+ .createDashboard({ ...level, description, title, widgetId });
+ if (dashboard) onCreated?.(dashboard);
+ }}
+ />
+ ),
+ footer: null,
+ styles: { content: { padding: 0 } },
+ title: translate('create.title', { ns: 'dashboard' }),
+ width: 460,
+ });
+
+export const openRenameDashboardModal = ({
+ dashboardId,
+ level,
+ title,
+}: {
+ dashboardId: string;
+ level?: WidgetLevelFilter;
+ title: string;
+}) =>
+ createModal({
+ content: (
+ <DashboardForm
+ initialTitle={title}
+ submitText={translate('save', { ns: 'common' })}
+ onSubmit={({ title: nextTitle }) =>
+ useDashboardStore.getState().renameDashboard(dashboardId, nextTitle, level)
+ }
+ />
+ ),
+ footer: null,
+ styles: { content: { padding: 0 } },
+ title: translate('rename.title', { ns: 'dashboard' }),
+ width: 460,
+ });
diff --git a/src/features/Dashboard/ErrorLine.tsx b/src/features/Dashboard/ErrorLine.tsx
new file mode 100644
index 00000000000..9573ee7ecca
--- /dev/null
+++ b/src/features/Dashboard/ErrorLine.tsx
@@ -0,0 +1,61 @@
+'use client';
+
+import { Flexbox, Icon } from '@lobehub/ui';
+import { Button, Text } from '@lobehub/ui/base-ui';
+import { createStaticStyles, cssVar } from 'antd-style';
+import { CircleAlertIcon } from 'lucide-react';
+import { memo, type ReactNode, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+const styles = createStaticStyles(({ css }) => ({
+ detail: css`
+ overflow: auto;
+
+ margin: 0;
+ padding-block: 8px;
+ padding-inline: 10px;
+ border-radius: ${cssVar.borderRadius};
+
+ font-family: ${cssVar.fontFamilyCode};
+ font-size: 12px;
+ line-height: 1.5;
+ color: ${cssVar.colorTextSecondary};
+ word-break: break-all;
+ white-space: pre-wrap;
+
+ background: ${cssVar.colorFillQuaternary};
+ `,
+}));
+
+/**
+ * The lightweight error row: one quiet line — an icon, a short human summary,
+ * and the raw provider detail folded behind a toggle — instead of a red panel
+ * with the technical message dumped in.
+ */
+export const ErrorLine = memo<{ detail?: ReactNode; summary: ReactNode }>(({ summary, detail }) => {
+ const { t } = useTranslation('dashboard');
+ const [open, setOpen] = useState(false);
+
+ return (
+ <Flexbox gap={4}>
+ <Flexbox horizontal align={'center'} gap={6} wrap={'wrap'}>
+ <Icon color={cssVar.colorError} icon={CircleAlertIcon} size={14} />
+ <Text fontSize={12} type={'secondary'}>
+ {summary}
+ </Text>
+ {detail && (
+ <Button size={'small'} type={'text'} onClick={() => setOpen((value) => !value)}>
+ {open ? t('error.hideDetails') : t('error.showDetails')}
+ </Button>
+ )}
+ </Flexbox>
+ {open && detail && (
+ <pre data-error-detail className={styles.detail}>
+ {detail}
+ </pre>
+ )}
+ </Flexbox>
+ );
+});
+
+ErrorLine.displayName = 'DashboardErrorLine';
diff --git a/src/features/Dashboard/FeatureGate.tsx b/src/features/Dashboard/FeatureGate.tsx
new file mode 100644
index 00000000000..33dd8f99654
--- /dev/null
+++ b/src/features/Dashboard/FeatureGate.tsx
@@ -0,0 +1,44 @@
+'use client';
+
+import { memo, type ReactNode } from 'react';
+import { Navigate, Outlet } from 'react-router';
+
+import { useDashboardFeature, useHomeDashboardFeature } from './hooks/useDashboardFeature';
+
+/**
+ * Layout for the project dashboard routes: renders them only while
+ * the `dashboard` feature flag is on, otherwise leaves for the parent page
+ * (the project) so a stale link or bookmark lands somewhere useful.
+ */
+export const DashboardRouteGate = memo(() => {
+ const { enabled, ready } = useDashboardFeature();
+ if (!ready) return null;
+ if (!enabled) return <Navigate replace to={'..'} />;
+ return <Outlet />;
+});
+
+DashboardRouteGate.displayName = 'DashboardRouteGate';
+
+/**
+ * Layout for the home dashboard routes (`/dashboard`): like `DashboardRouteGate`,
+ * but personal-only — inside a workspace it leaves for home too, so the board
+ * list never lists or creates workspace-level boards.
+ */
+export const HomeDashboardRouteGate = memo(() => {
+ const { enabled, ready } = useHomeDashboardFeature();
+ if (!ready) return null;
+ if (!enabled) return <Navigate replace to={'..'} />;
+ return <Outlet />;
+});
+
+HomeDashboardRouteGate.displayName = 'HomeDashboardRouteGate';
+
+/** Renders its children only while the `dashboard` feature flag is on. */
+export const DashboardFeatureGate = memo<{ children: ReactNode }>(({ children }) => {
+ const { enabled } = useDashboardFeature();
+ return enabled ? children : null;
+});
+
+DashboardFeatureGate.displayName = 'DashboardFeatureGate';
+
+export default DashboardRouteGate;
diff --git a/src/features/Dashboard/List/DashboardListCard.tsx b/src/features/Dashboard/List/DashboardListCard.tsx
new file mode 100644
index 00000000000..d070250234f
--- /dev/null
+++ b/src/features/Dashboard/List/DashboardListCard.tsx
@@ -0,0 +1,138 @@
+'use client';
+
+import type { WidgetLevelFilter } from '@lobechat/types';
+import { Center, Flexbox, Icon } from '@lobehub/ui';
+import { Text } from '@lobehub/ui/base-ui';
+import { createStaticStyles, cssVar } from 'antd-style';
+import dayjs from 'dayjs';
+import { LayoutDashboardIcon } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import WorkspaceLink from '@/features/Workspace/WorkspaceLink';
+import type { DashboardListItem } from '@/services/dashboard';
+
+import DashboardActionsMenu from '../DashboardActionsMenu';
+
+export const dashboardListStyles = createStaticStyles(({ css }) => ({
+ card: css`
+ position: relative;
+
+ display: block;
+
+ height: 100%;
+ padding: 16px;
+ border: 1px solid ${cssVar.colorBorderSecondary};
+ border-radius: ${cssVar.borderRadiusLG};
+
+ color: inherit;
+
+ background: ${cssVar.colorBgContainer};
+
+ transition:
+ border-color ${cssVar.motionDurationMid},
+ box-shadow ${cssVar.motionDurationMid};
+
+ &:hover {
+ border-color: ${cssVar.colorBorder};
+ box-shadow: ${cssVar.boxShadowTertiary};
+ }
+
+ &:hover [data-dashboard-menu] {
+ opacity: 1;
+ }
+ `,
+ description: css`
+ /* Two lines reserved, so cards with and without a description line up. */
+ min-height: calc(2 * 1.6em);
+ font-size: 13px;
+ line-height: 1.6;
+ `,
+ grid: css`
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
+ gap: 16px;
+ `,
+ icon: css`
+ flex: none;
+
+ width: 36px;
+ height: 36px;
+ border-radius: ${cssVar.borderRadius};
+
+ color: ${cssVar.geekblue};
+
+ background: color-mix(in srgb, ${cssVar.geekblue} 12%, transparent);
+ `,
+ menu: css`
+ position: absolute;
+ inset-block-start: 12px;
+ inset-inline-end: 12px;
+
+ opacity: 0;
+
+ transition: opacity ${cssVar.motionDurationMid};
+
+ &:focus-within,
+ &:has([aria-expanded='true']) {
+ opacity: 1;
+ }
+
+ @media (hover: none) {
+ opacity: 1;
+ }
+ `,
+ meta: css`
+ font-size: 12px;
+ color: ${cssVar.colorTextTertiary};
+ `,
+}));
+
+interface DashboardListCardProps {
+ dashboard: DashboardListItem;
+ /** Where the card opens the board, e.g. `/dashboard/<id>` or a project's board page. */
+ href: string;
+ /** The list the card sits in, refreshed after a rename or trash. */
+ level?: WidgetLevelFilter;
+}
+
+/** One board in a board list: name, description, freshness and the board menu. */
+const DashboardListCard = memo<DashboardListCardProps>(({ dashboard, href, level }) => {
+ const { t } = useTranslation('dashboard');
+
+ return (
+ <div className={dashboardListStyles.card} data-dashboard-id={dashboard.id}>
+ <WorkspaceLink style={{ color: 'inherit', display: 'block' }} to={href}>
+ <Flexbox gap={12}>
+ <Flexbox horizontal align={'center'} gap={12} style={{ paddingInlineEnd: 24 }}>
+ <Center className={dashboardListStyles.icon}>
+ <Icon icon={LayoutDashboardIcon} size={18} />
+ </Center>
+ <Text ellipsis fontSize={15} weight={600}>
+ {dashboard.title}
+ </Text>
+ </Flexbox>
+ <Text
+ className={dashboardListStyles.description}
+ ellipsis={{ rows: 2 }}
+ style={{
+ color: dashboard.description ? cssVar.colorTextSecondary : cssVar.colorTextQuaternary,
+ }}
+ >
+ {dashboard.description || t('list.noDescription')}
+ </Text>
+ <span className={dashboardListStyles.meta}>
+ {t('list.updatedAt', { time: dayjs(dashboard.updatedAt).fromNow() })}
+ </span>
+ </Flexbox>
+ </WorkspaceLink>
+ <span data-dashboard-menu className={dashboardListStyles.menu}>
+ <DashboardActionsMenu dashboard={dashboard} level={level} />
+ </span>
+ </div>
+ );
+});
+
+DashboardListCard.displayName = 'DashboardListCard';
+
+export default DashboardListCard;
diff --git a/src/features/Dashboard/List/index.tsx b/src/features/Dashboard/List/index.tsx
new file mode 100644
index 00000000000..c39e6db35de
--- /dev/null
+++ b/src/features/Dashboard/List/index.tsx
@@ -0,0 +1,98 @@
+'use client';
+
+import { Center, Empty, Flexbox } from '@lobehub/ui';
+import { Button, Text } from '@lobehub/ui/base-ui';
+import { LayoutDashboardIcon, PlusIcon } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import AsyncBoundary from '@/components/AsyncBoundary';
+import NavHeader from '@/features/NavHeader';
+import SkeletonList from '@/features/NavPanel/components/SkeletonList';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { dashboardSelectors, useDashboardStore } from '@/store/dashboard';
+
+import { openCreateDashboardModal } from '../DashboardFormModal';
+import { dashboardPageStyles as pageStyles } from '../pageStyles';
+import DashboardListCard, { dashboardListStyles } from './DashboardListCard';
+
+/** Home: the personal boards (no workspace / project / agent) and creating one. */
+const DashboardListPage = memo(() => {
+ const { t } = useTranslation('dashboard');
+ const navigate = useWorkspaceAwareNavigate();
+ const useFetchDashboards = useDashboardStore((s) => s.useFetchDashboards);
+ const { data, error, isLoading, mutate } = useFetchDashboards();
+ const dashboards = useDashboardStore(dashboardSelectors.dashboardList());
+
+ const handleCreate = () =>
+ openCreateDashboardModal({
+ onCreated: (dashboard) => navigate(`/dashboard/${dashboard.id}`),
+ });
+
+ return (
+ <Flexbox flex={1} height={'100%'}>
+ <NavHeader
+ left={
+ <Text style={{ paddingInlineStart: 4 }} weight={500}>
+ {t('list.title')}
+ </Text>
+ }
+ />
+ <div className={pageStyles.scroll}>
+ <div className={pageStyles.canvas}>
+ <Flexbox
+ horizontal
+ align={'flex-end'}
+ className={pageStyles.heading}
+ gap={16}
+ justify={'space-between'}
+ >
+ <Flexbox gap={6} style={{ minWidth: 0 }}>
+ <h1 className={pageStyles.title}>{t('list.title')}</h1>
+ <Text className={pageStyles.description}>{t('list.description')}</Text>
+ </Flexbox>
+ <Button
+ data-dashboard-create
+ icon={PlusIcon}
+ style={{ flex: 'none' }}
+ type={'primary'}
+ onClick={handleCreate}
+ >
+ {t('create.action')}
+ </Button>
+ </Flexbox>
+ <AsyncBoundary
+ data={data}
+ error={error}
+ isEmpty={data?.length === 0}
+ isLoading={isLoading}
+ loading={<SkeletonList rows={4} />}
+ empty={
+ <Center flex={1} gap={16} padding={48}>
+ <Empty description={t('list.empty')} icon={LayoutDashboardIcon} />
+ <Button icon={PlusIcon} onClick={handleCreate}>
+ {t('create.action')}
+ </Button>
+ </Center>
+ }
+ onRetry={() => void mutate()}
+ >
+ <div className={dashboardListStyles.grid}>
+ {dashboards.map((dashboard) => (
+ <DashboardListCard
+ dashboard={dashboard}
+ href={`/dashboard/${dashboard.id}`}
+ key={dashboard.id}
+ />
+ ))}
+ </div>
+ </AsyncBoundary>
+ </div>
+ </div>
+ </Flexbox>
+ );
+});
+
+DashboardListPage.displayName = 'DashboardListPage';
+
+export default DashboardListPage;
diff --git a/src/features/Dashboard/WidgetCard/HealthDot.test.ts b/src/features/Dashboard/WidgetCard/HealthDot.test.ts
new file mode 100644
index 00000000000..4b7e4745c1e
--- /dev/null
+++ b/src/features/Dashboard/WidgetCard/HealthDot.test.ts
@@ -0,0 +1,57 @@
+import { describe, expect, it } from 'vitest';
+
+import { getWidgetHealth } from '../utils/widgetHealth';
+import { getHealthTone } from './HealthDot';
+
+const output = { type: 'stat', value: 1 } as const;
+const NOW = new Date('2026-10-04T00:00:00Z').getTime();
+
+describe('getHealthTone', () => {
+ it('reads a running widget as running even when its last run failed', () => {
+ const health = getWidgetHealth(
+ { lastRunStatus: 'failed', latestOutput: output },
+ { now: NOW, runningLocally: true },
+ );
+ expect(getHealthTone(health)).toBe('running');
+ });
+
+ it('puts a failed run ahead of stale data', () => {
+ const health = getWidgetHealth(
+ {
+ lastRunStatus: 'failed',
+ latestOutput: output,
+ nextRunAt: new Date(NOW - 2 * 60 * 60 * 1000),
+ schedulePattern: '0 * * * *',
+ },
+ { now: NOW },
+ );
+ expect(getHealthTone(health)).toBe('failed');
+ });
+
+ it('reads an overdue schedule or a partial result as stale', () => {
+ const overdue = getWidgetHealth(
+ {
+ lastRunStatus: 'succeeded',
+ latestOutput: output,
+ nextRunAt: new Date(NOW - 2 * 60 * 60 * 1000),
+ schedulePattern: '0 * * * *',
+ },
+ { now: NOW },
+ );
+ const partial = getWidgetHealth(
+ { lastRunStatus: 'succeeded', latestOutput: { ...output, meta: { complete: false } } },
+ { now: NOW },
+ );
+ expect(getHealthTone(overdue)).toBe('stale');
+ expect(getHealthTone(partial)).toBe('stale');
+ });
+
+ it('is ok with fresh output and idle before any output exists', () => {
+ expect(
+ getHealthTone(
+ getWidgetHealth({ lastRunStatus: 'succeeded', latestOutput: output }, { now: NOW }),
+ ),
+ ).toBe('ok');
+ expect(getHealthTone(getWidgetHealth({}, { now: NOW }))).toBe('idle');
+ });
+});
diff --git a/src/features/Dashboard/WidgetCard/HealthDot.tsx b/src/features/Dashboard/WidgetCard/HealthDot.tsx
new file mode 100644
index 00000000000..b8282f43502
--- /dev/null
+++ b/src/features/Dashboard/WidgetCard/HealthDot.tsx
@@ -0,0 +1,66 @@
+'use client';
+
+import { createStaticStyles, cssVar, cx } from 'antd-style';
+import { memo } from 'react';
+
+import type { WidgetHealth } from '../utils/widgetHealth';
+
+const styles = createStaticStyles(({ css }) => ({
+ dot: css`
+ flex: none;
+ width: 6px;
+ height: 6px;
+ border-radius: 50%;
+ `,
+ running: css`
+ @keyframes dashboard-health-pulse {
+ 0%,
+ 100% {
+ opacity: 1;
+ }
+
+ 50% {
+ opacity: 0.3;
+ }
+ }
+
+ animation: dashboard-health-pulse 1.2s ease-in-out infinite;
+ `,
+}));
+
+export type WidgetHealthTone = 'failed' | 'idle' | 'ok' | 'running' | 'stale';
+
+/** The single tone a widget's freshness reads as, most urgent first. */
+export const getHealthTone = (health: WidgetHealth): WidgetHealthTone => {
+ if (health.running) return 'running';
+ if (health.failed) return 'failed';
+ if (health.stale || health.partial) return 'stale';
+ if (health.hasOutput) return 'ok';
+ return 'idle';
+};
+
+export const HEALTH_TONE_COLOR: Record<WidgetHealthTone, string> = {
+ failed: cssVar.colorError,
+ idle: cssVar.colorTextQuaternary,
+ ok: cssVar.colorSuccess,
+ running: cssVar.colorPrimary,
+ stale: cssVar.colorWarning,
+};
+
+/** A small dot carrying the widget's freshness next to its updated-at time. */
+const HealthDot = memo<{ health: WidgetHealth }>(({ health }) => {
+ const tone = getHealthTone(health);
+
+ return (
+ <span
+ aria-hidden
+ className={cx(styles.dot, tone === 'running' && styles.running)}
+ data-widget-health={tone}
+ style={{ background: HEALTH_TONE_COLOR[tone] }}
+ />
+ );
+});
+
+HealthDot.displayName = 'DashboardWidgetHealthDot';
+
+export default HealthDot;
diff --git a/src/features/Dashboard/WidgetCard/StatusBadges.tsx b/src/features/Dashboard/WidgetCard/StatusBadges.tsx
new file mode 100644
index 00000000000..aec7f3357c2
--- /dev/null
+++ b/src/features/Dashboard/WidgetCard/StatusBadges.tsx
@@ -0,0 +1,53 @@
+'use client';
+
+import { Tag, Tooltip } from '@lobehub/ui/base-ui';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import type { WidgetHealth, WidgetHealthBadge } from '../utils/widgetHealth';
+
+const BADGE_COLOR: Record<WidgetHealthBadge, string> = {
+ failed: 'error',
+ partial: 'warning',
+ running: 'processing',
+ stale: 'warning',
+};
+
+interface StatusBadgesProps {
+ /** Subset of `health.badges` to show, when the host already conveys some of them. */
+ badges?: WidgetHealthBadge[];
+ health: WidgetHealth;
+}
+
+const StatusBadges = memo<StatusBadgesProps>(({ health, badges = health.badges }) => {
+ const { t } = useTranslation('dashboard');
+
+ if (badges.length === 0) return null;
+
+ return (
+ <>
+ {badges.map((badge) => {
+ const tip =
+ badge === 'failed'
+ ? health.error?.message
+ ? t('widget.status.failedTip', { message: health.error.message })
+ : t('widget.status.failedTipNoMessage')
+ : badge === 'partial'
+ ? (health.partialMessage ?? t('widget.status.partialTip'))
+ : t(`widget.status.${badge}Tip`);
+
+ return (
+ <Tooltip key={badge} title={tip}>
+ <Tag color={BADGE_COLOR[badge]} data-widget-badge={badge} size={'small'}>
+ {t(`widget.status.${badge}`)}
+ </Tag>
+ </Tooltip>
+ );
+ })}
+ </>
+ );
+});
+
+StatusBadges.displayName = 'DashboardWidgetStatusBadges';
+
+export default StatusBadges;
diff --git a/src/features/Dashboard/WidgetCard/index.tsx b/src/features/Dashboard/WidgetCard/index.tsx
new file mode 100644
index 00000000000..3b451da9e88
--- /dev/null
+++ b/src/features/Dashboard/WidgetCard/index.tsx
@@ -0,0 +1,202 @@
+'use client';
+
+import type { WidgetView } from '@lobechat/types';
+import { Center, Flexbox, Icon } from '@lobehub/ui';
+import { Spin, Text, Tooltip } from '@lobehub/ui/base-ui';
+import { createStaticStyles, cssVar, cx } from 'antd-style';
+import dayjs from 'dayjs';
+import { CircleDashedIcon } from 'lucide-react';
+import { memo, type ReactNode } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import type { DashboardTrendSeries, DashboardWidgetItem } from '@/services/dashboard';
+
+import { ErrorLine } from '../ErrorLine';
+import { getWidgetCardBody, getWidgetHealth, getWidgetUpdatedAt } from '../utils/widgetHealth';
+import HealthDot from './HealthDot';
+import StatusBadges from './StatusBadges';
+import WidgetOutputView from './views';
+
+const styles = createStaticStyles(({ css }) => ({
+ actions: css`
+ flex: none;
+ opacity: 0;
+ transition: opacity ${cssVar.motionDurationMid};
+
+ &:focus-within {
+ opacity: 1;
+ }
+
+ @media (hover: none) {
+ opacity: 1;
+ }
+ `,
+ body: css`
+ /* Views size their headline to the card (cqi / cqh) and drop details when it is short. */
+ container-type: size;
+ overflow: hidden;
+ flex: 1;
+ min-height: 0;
+ `,
+ card: css`
+ overflow: hidden;
+
+ height: 100%;
+ padding-block: 14px 12px;
+ padding-inline: 16px;
+ border: 1px solid ${cssVar.colorBorderSecondary};
+ border-radius: ${cssVar.borderRadiusLG};
+
+ background: ${cssVar.colorBgContainer};
+
+ transition:
+ border-color ${cssVar.motionDurationMid},
+ box-shadow ${cssVar.motionDurationMid};
+
+ &:hover {
+ border-color: ${cssVar.colorBorder};
+ box-shadow: ${cssVar.boxShadowTertiary};
+ }
+
+ &:hover [data-widget-actions],
+ &[data-widget-running='true'] [data-widget-actions] {
+ opacity: 1;
+ }
+ `,
+ clickable: css`
+ cursor: pointer;
+ `,
+ failedOutput: css`
+ opacity: 0.6;
+ `,
+ footer: css`
+ flex: none;
+ min-width: 0;
+ font-size: 12px;
+ color: ${cssVar.colorTextTertiary};
+ `,
+ header: css`
+ flex: none;
+ min-height: 24px;
+ `,
+ title: css`
+ flex: 1;
+ min-width: 0;
+ `,
+}));
+
+export interface WidgetCardProps {
+ /** Header actions (refresh, menu) — a slot so read-only hosts mount none. */
+ actions?: ReactNode;
+ className?: string;
+ /** Leading header node, e.g. a drag handle while editing a board layout. */
+ handle?: ReactNode;
+ /** Open the drill-down. The card is not clickable without it. */
+ onOpen?: () => void;
+ /** A manual refresh of this widget is in flight from this client. */
+ runningLocally?: boolean;
+ /** Long-term trend from `metric_points`, when the host loaded it. */
+ trend?: DashboardTrendSeries[];
+ view?: WidgetView | null;
+ widget: DashboardWidgetItem;
+}
+
+/**
+ * One widget on a board: its latest successful output, how fresh it is, and
+ * whether the last attempt worked.
+ *
+ * A failed run never blanks the card or turns the value into 0 — the last
+ * good output stays, dimmed, under a failed badge. With no good output at all
+ * the card says so instead of rendering an empty value.
+ */
+const WidgetCard = memo<WidgetCardProps>(
+ ({ widget, trend, view, actions, handle, onOpen, runningLocally, className }) => {
+ const { t } = useTranslation('dashboard');
+ const health = getWidgetHealth(widget, { runningLocally });
+ const updatedAt = getWidgetUpdatedAt(widget);
+ const output = widget.latestOutput;
+ const bodyState = getWidgetCardBody(health);
+ // The running badge would repeat the spinning refresh button and the pulsing dot.
+ const badges = health.badges.filter((badge) => badge !== 'running');
+
+ let body: ReactNode;
+ if (bodyState === 'output' && output) {
+ body = (
+ <div className={cx(health.failed && styles.failedOutput)} style={{ height: '100%' }}>
+ <WidgetOutputView output={output} trend={trend} view={view} />
+ </div>
+ );
+ } else if (bodyState === 'firstRun') {
+ body = (
+ <Center gap={8} height={'100%'}>
+ <Spin size={'small'} />
+ <Text fontSize={12} type={'secondary'}>
+ {t('widget.state.firstRun')}
+ </Text>
+ </Center>
+ );
+ } else if (bodyState === 'failedNoOutput') {
+ body = (
+ <Center data-widget-state={'failed-no-output'} height={'100%'} padding={8}>
+ <ErrorLine detail={health.error?.message} summary={t('widget.state.failedNoOutput')} />
+ </Center>
+ );
+ } else {
+ body = (
+ <Center gap={6} height={'100%'} padding={8}>
+ <Icon color={cssVar.colorTextQuaternary} icon={CircleDashedIcon} size={20} />
+ <Text fontSize={12} type={'secondary'}>
+ {t(`widget.state.${bodyState === 'unpublished' ? 'unpublished' : 'noRun'}`)}
+ </Text>
+ </Center>
+ );
+ }
+
+ return (
+ <Flexbox
+ className={cx(styles.card, onOpen && styles.clickable, className)}
+ data-widget-id={widget.id}
+ data-widget-running={health.running}
+ gap={10}
+ onClick={onOpen}
+ >
+ <Flexbox horizontal align={'center'} className={styles.header} gap={6}>
+ {handle}
+ <Text ellipsis className={styles.title} title={widget.title} weight={500}>
+ {widget.title}
+ </Text>
+ <StatusBadges badges={badges} health={health} />
+ {actions && (
+ // Header actions must not open the drill-down.
+ <Flexbox
+ data-widget-actions
+ horizontal
+ className={styles.actions}
+ gap={2}
+ onClick={(event) => event.stopPropagation()}
+ >
+ {actions}
+ </Flexbox>
+ )}
+ </Flexbox>
+ <div className={styles.body}>{body}</div>
+ {updatedAt && (
+ <Flexbox horizontal align={'center'} className={styles.footer} gap={6}>
+ <HealthDot health={health} />
+ <Tooltip title={dayjs(updatedAt).format('YYYY-MM-DD HH:mm:ss')}>
+ <span data-widget-updated>
+ {output
+ ? t('widget.updatedAt', { time: dayjs(updatedAt).fromNow() })
+ : t('widget.lastAttemptAt', { time: dayjs(updatedAt).fromNow() })}
+ </span>
+ </Tooltip>
+ </Flexbox>
+ )}
+ </Flexbox>
+ );
+ },
+);
+
+WidgetCard.displayName = 'DashboardWidgetCard';
+
+export default WidgetCard;
diff --git a/src/features/Dashboard/WidgetCard/views/ListView.tsx b/src/features/Dashboard/WidgetCard/views/ListView.tsx
new file mode 100644
index 00000000000..99052840031
--- /dev/null
+++ b/src/features/Dashboard/WidgetCard/views/ListView.tsx
@@ -0,0 +1,93 @@
+'use client';
+
+import type { WidgetListOutput } from '@lobechat/types';
+import { Flexbox } from '@lobehub/ui';
+import { Tag, Text } from '@lobehub/ui/base-ui';
+import { createStaticStyles, cssVar } from 'antd-style';
+import dayjs from 'dayjs';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { formatWidgetValue } from '../../utils/format';
+
+const styles = createStaticStyles(({ css }) => ({
+ link: css`
+ color: inherit;
+
+ &:hover {
+ color: ${cssVar.colorPrimary};
+ }
+ `,
+ row: css`
+ padding-block: 6px;
+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};
+
+ &:last-child {
+ border-block-end: none;
+ }
+ `,
+}));
+
+interface ListViewProps {
+ /** Rows to show before the "+N more" note; unlimited when omitted. */
+ limit?: number;
+ output: WidgetListOutput;
+}
+
+const ListView = memo<ListViewProps>(({ output, limit }) => {
+ const { t } = useTranslation('dashboard');
+ // Normalize once: an older server may send a list output without `items`.
+ const allItems = output.items ?? [];
+ const items = limit ? allItems.slice(0, limit) : allItems;
+ const hidden = allItems.length - items.length;
+
+ if (allItems.length === 0) {
+ return (
+ <Text fontSize={12} type={'secondary'}>
+ {t('widget.view.listEmpty')}
+ </Text>
+ );
+ }
+
+ return (
+ <Flexbox>
+ {items.map((item, index) => (
+ <Flexbox horizontal align={'center'} className={styles.row} gap={8} key={index}>
+ <Flexbox flex={1} gap={2} style={{ minWidth: 0 }}>
+ <Text ellipsis weight={500}>
+ {item.url ? (
+ <a className={styles.link} href={item.url} rel={'noreferrer'} target={'_blank'}>
+ {item.title}
+ </a>
+ ) : (
+ item.title
+ )}
+ </Text>
+ {(item.description || item.time) && (
+ <Text ellipsis fontSize={12} type={'secondary'}>
+ {[item.description, item.time && dayjs(item.time).fromNow()]
+ .filter(Boolean)
+ .join(' · ')}
+ </Text>
+ )}
+ </Flexbox>
+ {item.status && <Tag size={'small'}>{item.status}</Tag>}
+ {item.value !== undefined && (
+ <Text style={{ fontVariantNumeric: 'tabular-nums' }} weight={500}>
+ {formatWidgetValue(item.value)}
+ </Text>
+ )}
+ </Flexbox>
+ ))}
+ {hidden > 0 && (
+ <Text fontSize={12} style={{ paddingTop: 6 }} type={'secondary'}>
+ {t('widget.view.more', { count: hidden })}
+ </Text>
+ )}
+ </Flexbox>
+ );
+});
+
+ListView.displayName = 'DashboardListView';
+
+export default ListView;
diff --git a/src/features/Dashboard/WidgetCard/views/SeriesView.tsx b/src/features/Dashboard/WidgetCard/views/SeriesView.tsx
new file mode 100644
index 00000000000..92858a3e141
--- /dev/null
+++ b/src/features/Dashboard/WidgetCard/views/SeriesView.tsx
@@ -0,0 +1,56 @@
+'use client';
+
+import type { WidgetSeriesOutput, WidgetView } from '@lobechat/types';
+import { AreaChart, BarChart, LineChart } from '@lobehub/charts';
+import { Text } from '@lobehub/ui/base-ui';
+import { memo, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import type { DashboardTrendSeries } from '@/services/dashboard';
+
+import { formatWidgetValue } from '../../utils/format';
+import { buildSeriesChartData } from '../../utils/series';
+
+const CHARTS = { area: AreaChart, bar: BarChart, line: LineChart };
+
+interface SeriesViewProps {
+ chart?: WidgetView['chart'];
+ height?: number | string;
+ output: WidgetSeriesOutput;
+ trend?: DashboardTrendSeries[];
+}
+
+const SeriesView = memo<SeriesViewProps>(({ output, trend, chart = 'line', height = '100%' }) => {
+ const { t } = useTranslation('dashboard');
+ const data = useMemo(() => buildSeriesChartData(output, trend), [output, trend]);
+ const Chart = CHARTS[chart] ?? LineChart;
+
+ if (data.rows.length === 0) {
+ return (
+ <Text fontSize={12} type={'secondary'}>
+ {t('widget.view.seriesEmpty')}
+ </Text>
+ );
+ }
+
+ return (
+ <div data-series-source={data.fromHistory ? 'metric' : 'output'} style={{ height }}>
+ <Chart
+ categories={data.categories}
+ data={data.rows}
+ height={'100%'}
+ index={'t'}
+ showLegend={data.categories.length > 1}
+ startEndOnly={data.rows.length > 12}
+ yAxisWidth={48}
+ valueFormatter={(value: number) =>
+ output.unit ? `${formatWidgetValue(value)} ${output.unit}` : formatWidgetValue(value)
+ }
+ />
+ </div>
+ );
+});
+
+SeriesView.displayName = 'DashboardSeriesView';
+
+export default SeriesView;
diff --git a/src/features/Dashboard/WidgetCard/views/StatView.tsx b/src/features/Dashboard/WidgetCard/views/StatView.tsx
new file mode 100644
index 00000000000..366eaa4fd4d
--- /dev/null
+++ b/src/features/Dashboard/WidgetCard/views/StatView.tsx
@@ -0,0 +1,144 @@
+'use client';
+
+import type { WidgetStatOutput } from '@lobechat/types';
+import { Flexbox, Icon } from '@lobehub/ui';
+import { Text } from '@lobehub/ui/base-ui';
+import { createStaticStyles, cssVar } from 'antd-style';
+import { ArrowDownRightIcon, ArrowRightIcon, ArrowUpRightIcon } from 'lucide-react';
+import { type CSSProperties, memo } from 'react';
+
+import type { DashboardTrendSeries } from '@/services/dashboard';
+
+import { formatDelta, formatWidgetValue } from '../../utils/format';
+import TrendSparkline from './TrendSparkline';
+
+const styles = createStaticStyles(({ css }) => ({
+ delta: css`
+ display: inline-flex;
+ gap: 2px;
+ align-items: center;
+
+ padding-block: 1px;
+ padding-inline: 4px 6px;
+ border-radius: ${cssVar.borderRadiusSM};
+
+ font-size: 12px;
+ font-weight: 500;
+ font-variant-numeric: tabular-nums;
+ line-height: 18px;
+ `,
+ label: css`
+ @container (max-height: 96px) {
+ display: none;
+ }
+ `,
+ sparkline: css`
+ flex: 1;
+
+ min-height: 28px;
+ max-height: 96px;
+ margin-block-start: 4px;
+
+ /* Room for the latest-point marker, which sits on the plot edge. */
+ padding-block: 4px;
+ padding-inline-end: 4px;
+ `,
+ unit: css`
+ font-size: 14px;
+ font-weight: 500;
+ color: ${cssVar.colorTextTertiary};
+ `,
+ value: css`
+ overflow: hidden;
+
+ min-width: 0;
+
+ /* Fit the card both ways: long strings (versions, ids) shrink by their length. */
+ font-size: clamp(20px, min(calc(160cqi / var(--chars)), 16cqi, 40cqh), 44px);
+ font-weight: 600;
+ font-variant-numeric: tabular-nums;
+ line-height: 1.05;
+ color: ${cssVar.colorText};
+ text-overflow: ellipsis;
+ letter-spacing: -0.02em;
+ white-space: nowrap;
+ `,
+}));
+
+const TREND = {
+ down: {
+ background: `color-mix(in srgb, ${cssVar.colorError} 12%, transparent)`,
+ color: cssVar.colorError,
+ icon: ArrowDownRightIcon,
+ },
+ flat: {
+ background: cssVar.colorFillTertiary,
+ color: cssVar.colorTextSecondary,
+ icon: ArrowRightIcon,
+ },
+ up: {
+ background: `color-mix(in srgb, ${cssVar.colorSuccess} 12%, transparent)`,
+ color: cssVar.colorSuccess,
+ icon: ArrowUpRightIcon,
+ },
+};
+
+interface StatViewProps {
+ output: WidgetStatOutput;
+ trend?: DashboardTrendSeries[];
+}
+
+const StatView = memo<StatViewProps>(({ output, trend }) => {
+ const delta = formatDelta(output.delta);
+ const values = trend?.[0]?.points.map((point) => point.value) ?? [];
+ const tone = TREND[output.trend ?? 'flat'];
+ const value = formatWidgetValue(output.value);
+
+ return (
+ <Flexbox gap={6} height={'100%'}>
+ {output.label && (
+ <Text ellipsis className={styles.label} fontSize={12} type={'secondary'}>
+ {output.label}
+ </Text>
+ )}
+ <Flexbox horizontal align={'baseline'} gap={6} style={{ minWidth: 0 }}>
+ <span
+ data-widget-value
+ className={styles.value}
+ style={{ '--chars': Math.max(value.length, 4) } as CSSProperties}
+ >
+ {value}
+ </span>
+ {output.unit && <span className={styles.unit}>{output.unit}</span>}
+ </Flexbox>
+ {(delta || output.description) && (
+ <Flexbox horizontal align={'center'} gap={8} style={{ minWidth: 0 }}>
+ {delta && (
+ <span
+ className={styles.delta}
+ data-widget-delta={output.trend ?? 'flat'}
+ style={{ background: tone.background, color: tone.color }}
+ >
+ <Icon icon={tone.icon} size={12} />
+ {delta}
+ </span>
+ )}
+ {output.description && (
+ <Text ellipsis fontSize={12} style={{ flex: 1, minWidth: 0 }} type={'secondary'}>
+ {output.description}
+ </Text>
+ )}
+ </Flexbox>
+ )}
+ {values.length > 1 && (
+ <div className={styles.sparkline}>
+ <TrendSparkline values={values} />
+ </div>
+ )}
+ </Flexbox>
+ );
+});
+
+StatView.displayName = 'DashboardStatView';
+
+export default StatView;
diff --git a/src/features/Dashboard/WidgetCard/views/TableView.tsx b/src/features/Dashboard/WidgetCard/views/TableView.tsx
new file mode 100644
index 00000000000..902942030ab
--- /dev/null
+++ b/src/features/Dashboard/WidgetCard/views/TableView.tsx
@@ -0,0 +1,120 @@
+'use client';
+
+import type { WidgetTableOutput } from '@lobechat/types';
+import { Text } from '@lobehub/ui/base-ui';
+import { createStaticStyles, cssVar } from 'antd-style';
+import { memo, useMemo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { formatCell } from '../../utils/format';
+
+const styles = createStaticStyles(({ css }) => ({
+ table: css`
+ border-collapse: collapse;
+ width: 100%;
+ font-size: 12px;
+
+ th,
+ td {
+ overflow: hidden;
+
+ max-width: 240px;
+ padding-block: 6px;
+ padding-inline: 8px;
+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};
+
+ text-align: start;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ }
+
+ th {
+ font-weight: 500;
+ color: ${cssVar.colorTextSecondary};
+ background: ${cssVar.colorFillQuaternary};
+ }
+
+ td[data-type='number'],
+ th[data-type='number'] {
+ font-variant-numeric: tabular-nums;
+ text-align: end;
+ }
+ `,
+ wrapper: css`
+ overflow: auto;
+ width: 100%;
+ `,
+}));
+
+interface TableViewProps {
+ /** Column keys to show, in order (`view.columns`). */
+ columns?: string[];
+ limit?: number;
+ output: WidgetTableOutput;
+}
+
+const TableView = memo<TableViewProps>(({ output, columns, limit }) => {
+ const { t } = useTranslation('dashboard');
+
+ const visibleColumns = useMemo(() => {
+ if (!columns?.length) return output.columns;
+ const byKey = new Map(output.columns.map((column) => [column.key, column]));
+ return columns.map((key) => byKey.get(key) ?? { key });
+ }, [columns, output.columns]);
+
+ const rows = limit ? output.rows.slice(0, limit) : output.rows;
+ const hidden = output.rows.length - rows.length;
+
+ if (output.rows.length === 0) {
+ return (
+ <Text fontSize={12} type={'secondary'}>
+ {t('widget.view.tableEmpty')}
+ </Text>
+ );
+ }
+
+ return (
+ <div className={styles.wrapper}>
+ <table className={styles.table}>
+ <thead>
+ <tr>
+ {visibleColumns.map((column) => (
+ <th data-type={column.type} key={column.key}>
+ {column.title ?? column.key}
+ </th>
+ ))}
+ </tr>
+ </thead>
+ <tbody>
+ {rows.map((row, index) => (
+ <tr key={index}>
+ {visibleColumns.map((column) => {
+ const text = formatCell(row[column.key]);
+ return (
+ <td data-type={column.type} key={column.key} title={text}>
+ {column.type === 'link' && text ? (
+ <a href={text} rel={'noreferrer'} target={'_blank'}>
+ {text}
+ </a>
+ ) : (
+ text
+ )}
+ </td>
+ );
+ })}
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ {hidden > 0 && (
+ <Text fontSize={12} style={{ display: 'block', paddingTop: 6 }} type={'secondary'}>
+ {t('widget.view.more', { count: hidden })}
+ </Text>
+ )}
+ </div>
+ );
+});
+
+TableView.displayName = 'DashboardTableView';
+
+export default TableView;
diff --git a/src/features/Dashboard/WidgetCard/views/TrendSparkline.tsx b/src/features/Dashboard/WidgetCard/views/TrendSparkline.tsx
new file mode 100644
index 00000000000..4137abe98e8
--- /dev/null
+++ b/src/features/Dashboard/WidgetCard/views/TrendSparkline.tsx
@@ -0,0 +1,75 @@
+'use client';
+
+import { cssVar } from 'antd-style';
+import { memo, useId } from 'react';
+
+import { sparklinePoints } from '../../utils/series';
+
+/** The first series color of `@lobehub/charts`, so a stat trend reads like the charts beside it. */
+const COLOR = cssVar.geekblue;
+
+const HEIGHT = 40;
+const WIDTH = 100;
+
+/**
+ * Shape-only trend under a stat: no axes, the number above carries the value.
+ * A soft area anchors the line to the card floor, and only the latest point is
+ * marked — it is the one the number above reports.
+ */
+const TrendSparkline = memo<{ values: number[] }>(({ values }) => {
+ const gradientId = useId();
+
+ if (values.length < 2) return null;
+
+ const points = sparklinePoints(values, WIDTH, HEIGHT);
+ const line = points.map(({ x, y }, index) => `${index === 0 ? 'M' : 'L'} ${x} ${y}`).join(' ');
+ const area = `${line} L ${points.at(-1)!.x} ${HEIGHT} L ${points[0].x} ${HEIGHT} Z`;
+ const last = points.at(-1)!;
+
+ return (
+ <svg
+ aria-hidden
+ data-widget-sparkline
+ height={'100%'}
+ preserveAspectRatio={'none'}
+ style={{ display: 'block', minHeight: 28, overflow: 'visible' }}
+ viewBox={`0 0 ${WIDTH} ${HEIGHT}`}
+ width={'100%'}
+ >
+ <defs>
+ <linearGradient id={gradientId} x1={0} x2={0} y1={0} y2={1}>
+ <stop offset={'0%'} stopColor={COLOR} stopOpacity={0.22} />
+ <stop offset={'100%'} stopColor={COLOR} stopOpacity={0} />
+ </linearGradient>
+ </defs>
+ <path d={area} fill={`url(#${gradientId})`} stroke={'none'} />
+ <path
+ d={line}
+ fill={'none'}
+ stroke={COLOR}
+ strokeLinejoin={'round'}
+ strokeWidth={1.75}
+ vectorEffect={'non-scaling-stroke'}
+ />
+ <path
+ d={`M ${last.x} ${last.y} l 0.0001 0`}
+ stroke={cssVar.colorBgContainer}
+ strokeLinecap={'round'}
+ strokeWidth={9}
+ vectorEffect={'non-scaling-stroke'}
+ />
+ <path
+ data-sparkline-last
+ d={`M ${last.x} ${last.y} l 0.0001 0`}
+ stroke={COLOR}
+ strokeLinecap={'round'}
+ strokeWidth={5}
+ vectorEffect={'non-scaling-stroke'}
+ />
+ </svg>
+ );
+});
+
+TrendSparkline.displayName = 'DashboardTrendSparkline';
+
+export default TrendSparkline;
diff --git a/src/features/Dashboard/WidgetCard/views/index.tsx b/src/features/Dashboard/WidgetCard/views/index.tsx
new file mode 100644
index 00000000000..bc3ee92a2c7
--- /dev/null
+++ b/src/features/Dashboard/WidgetCard/views/index.tsx
@@ -0,0 +1,58 @@
+'use client';
+
+import type { WidgetOutput, WidgetView as WidgetViewHints } from '@lobechat/types';
+import { memo } from 'react';
+
+import type { DashboardTrendSeries } from '@/services/dashboard';
+
+import ListView from './ListView';
+import SeriesView from './SeriesView';
+import StatView from './StatView';
+import TableView from './TableView';
+
+export interface WidgetOutputViewProps {
+ /** `compact` applies the view's row limit (cards); `full` shows everything (drill-down). */
+ density?: 'compact' | 'full';
+ output: WidgetOutput;
+ trend?: DashboardTrendSeries[];
+ view?: WidgetViewHints | null;
+}
+
+/** Card row cap when the version sets no `view.limit`. */
+const COMPACT_ROW_LIMIT = 8;
+
+/** Render one widget output by its contract type. */
+const WidgetOutputView = memo<WidgetOutputViewProps>(
+ ({ output, trend, view, density = 'compact' }) => {
+ const limit = density === 'compact' ? (view?.limit ?? COMPACT_ROW_LIMIT) : undefined;
+
+ switch (output.type) {
+ case 'stat': {
+ return <StatView output={output} trend={trend} />;
+ }
+ case 'list': {
+ return <ListView limit={limit} output={output} />;
+ }
+ case 'series': {
+ return (
+ <SeriesView
+ chart={view?.chart}
+ height={density === 'full' ? 280 : '100%'}
+ output={output}
+ trend={trend}
+ />
+ );
+ }
+ case 'table': {
+ return <TableView columns={view?.columns} limit={limit} output={output} />;
+ }
+ default: {
+ return null;
+ }
+ }
+ },
+);
+
+WidgetOutputView.displayName = 'DashboardWidgetOutputView';
+
+export default WidgetOutputView;
diff --git a/src/features/Dashboard/WidgetDetail/RunHistory.tsx b/src/features/Dashboard/WidgetDetail/RunHistory.tsx
new file mode 100644
index 00000000000..de6525e1e17
--- /dev/null
+++ b/src/features/Dashboard/WidgetDetail/RunHistory.tsx
@@ -0,0 +1,130 @@
+'use client';
+
+import { Flexbox, Icon } from '@lobehub/ui';
+import { Tag, Text } from '@lobehub/ui/base-ui';
+import { createStaticStyles, cssVar, cx } from 'antd-style';
+import dayjs from 'dayjs';
+import { ChevronDownIcon, ChevronRightIcon } from 'lucide-react';
+import { memo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import AsyncBoundary from '@/components/AsyncBoundary';
+import type { DashboardWidgetRunItem } from '@/services/dashboard';
+import { dashboardSelectors, useDashboardStore } from '@/store/dashboard';
+
+import { formatDuration } from '../utils/format';
+import RunLogs from './RunLogs';
+
+const RUN_STATUS_COLOR: Record<string, string> = {
+ failed: 'error',
+ running: 'processing',
+ succeeded: 'success',
+ timeout: 'warning',
+};
+
+const styles = createStaticStyles(({ css }) => ({
+ row: css`
+ cursor: pointer;
+ padding-block: 8px;
+ padding-inline: 8px;
+ border-radius: ${cssVar.borderRadius};
+
+ &:hover {
+ background: ${cssVar.colorFillTertiary};
+ }
+ `,
+ rowActive: css`
+ background: ${cssVar.colorFillTertiary};
+ `,
+}));
+
+const RunRow = memo<{ run: DashboardWidgetRunItem; versionNumber?: number }>(
+ ({ run, versionNumber }) => {
+ const { t } = useTranslation('dashboard');
+ const [open, setOpen] = useState(false);
+ const duration = formatDuration(run.durationMs);
+
+ return (
+ <Flexbox gap={8}>
+ <Flexbox
+ horizontal
+ align={'center'}
+ className={cx(styles.row, open && styles.rowActive)}
+ data-run-id={run.id}
+ gap={8}
+ onClick={() => setOpen((value) => !value)}
+ >
+ <Icon icon={open ? ChevronDownIcon : ChevronRightIcon} size={14} />
+ <Tag color={RUN_STATUS_COLOR[run.status]} size={'small'}>
+ {t(`run.status.${run.status}`)}
+ </Tag>
+ <Text fontSize={12} type={'secondary'}>
+ {t(`run.trigger.${run.trigger}`)}
+ </Text>
+ {versionNumber !== undefined && (
+ <Text fontSize={12} type={'secondary'}>
+ {`v${versionNumber}`}
+ </Text>
+ )}
+ <Flexbox flex={1} />
+ {duration && (
+ <Text fontSize={12} type={'secondary'}>
+ {duration}
+ </Text>
+ )}
+ <Text
+ fontSize={12}
+ title={dayjs(run.startedAt).format('YYYY-MM-DD HH:mm:ss')}
+ type={'secondary'}
+ >
+ {dayjs(run.startedAt).fromNow()}
+ </Text>
+ </Flexbox>
+ {open && (
+ <Flexbox paddingInline={8}>
+ <RunLogs run={run} />
+ </Flexbox>
+ )}
+ </Flexbox>
+ );
+ },
+);
+
+RunRow.displayName = 'DashboardRunRow';
+
+/** Recent runs of a widget, newest first; each expands into its logs. */
+const RunHistory = memo<{ widgetId: string }>(({ widgetId }) => {
+ const { t } = useTranslation('dashboard');
+ const useFetchWidgetRuns = useDashboardStore((s) => s.useFetchWidgetRuns);
+ const useFetchWidgetVersions = useDashboardStore((s) => s.useFetchWidgetVersions);
+ const { data, error, isLoading, mutate } = useFetchWidgetRuns(widgetId);
+ useFetchWidgetVersions(widgetId);
+ const runs = useDashboardStore(dashboardSelectors.widgetRuns(widgetId));
+ const versions = useDashboardStore(dashboardSelectors.widgetVersions(widgetId));
+ const versionNumberById = new Map(versions.map((version) => [version.id, version.version]));
+
+ return (
+ <AsyncBoundary
+ data={data}
+ error={error}
+ isEmpty={data?.length === 0}
+ isLoading={isLoading}
+ empty={
+ <Text fontSize={12} type={'secondary'}>
+ {t('run.empty')}
+ </Text>
+ }
+ onRetry={() => void mutate()}
+ >
+ <Flexbox gap={2}>
+ {runs.map((run) => (
+ <RunRow key={run.id} run={run} versionNumber={versionNumberById.get(run.versionId)} />
+ ))}
+ </Flexbox>
+ </AsyncBoundary>
+ );
+});
+
+RunHistory.displayName = 'DashboardRunHistory';
+
+export default RunHistory;
diff --git a/src/features/Dashboard/WidgetDetail/RunLogs.tsx b/src/features/Dashboard/WidgetDetail/RunLogs.tsx
new file mode 100644
index 00000000000..e3e1f94fa5c
--- /dev/null
+++ b/src/features/Dashboard/WidgetDetail/RunLogs.tsx
@@ -0,0 +1,78 @@
+'use client';
+
+import { Flexbox } from '@lobehub/ui';
+import { Text } from '@lobehub/ui/base-ui';
+import { createStaticStyles, cssVar } from 'antd-style';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import type { DashboardWidgetRunItem } from '@/services/dashboard';
+
+import { ErrorLine } from '../ErrorLine';
+import { truncateLog } from '../utils/format';
+
+const styles = createStaticStyles(({ css }) => ({
+ log: css`
+ overflow: auto;
+
+ max-height: 220px;
+ margin: 0;
+ padding: 8px;
+ border-radius: ${cssVar.borderRadius};
+
+ font-family: ${cssVar.fontFamilyCode};
+ font-size: 12px;
+ line-height: 1.5;
+ color: ${cssVar.colorTextSecondary};
+ word-break: break-all;
+ white-space: pre-wrap;
+
+ background: ${cssVar.colorFillQuaternary};
+ `,
+}));
+
+const LogBlock = memo<{ label: string; stream: 'stdout' | 'stderr'; text?: string | null }>(
+ ({ label, stream, text }) => {
+ const { t } = useTranslation('dashboard');
+ const preview = truncateLog(text);
+
+ return (
+ <Flexbox gap={4}>
+ <Text fontSize={12} weight={500}>
+ {label}
+ </Text>
+ {preview.text ? (
+ <pre className={styles.log} data-run-log={stream}>
+ {preview.text}
+ {preview.truncated && `\n… ${t('run.logTruncated')}`}
+ </pre>
+ ) : (
+ <Text fontSize={12} type={'secondary'}>
+ {t('run.logEmpty')}
+ </Text>
+ )}
+ </Flexbox>
+ );
+ },
+);
+
+LogBlock.displayName = 'DashboardRunLogBlock';
+
+/** Error, stdout and stderr of one run, each capped for display. */
+const RunLogs = memo<{ run: DashboardWidgetRunItem }>(({ run }) => {
+ const { t } = useTranslation('dashboard');
+
+ return (
+ <Flexbox gap={12}>
+ {run.error && (
+ <ErrorLine detail={`[${run.error.code}] ${run.error.message}`} summary={t('run.error')} />
+ )}
+ <LogBlock label={'stdout'} stream={'stdout'} text={run.stdout} />
+ <LogBlock label={'stderr'} stream={'stderr'} text={run.stderr} />
+ </Flexbox>
+ );
+});
+
+RunLogs.displayName = 'DashboardRunLogs';
+
+export default RunLogs;
diff --git a/src/features/Dashboard/WidgetDetail/RunPreview.tsx b/src/features/Dashboard/WidgetDetail/RunPreview.tsx
new file mode 100644
index 00000000000..e3b12fce89d
--- /dev/null
+++ b/src/features/Dashboard/WidgetDetail/RunPreview.tsx
@@ -0,0 +1,60 @@
+'use client';
+
+import type { WidgetView } from '@lobechat/types';
+import { Flexbox } from '@lobehub/ui';
+import { Tag, Text } from '@lobehub/ui/base-ui';
+import dayjs from 'dayjs';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import type { DashboardWidgetRunItem } from '@/services/dashboard';
+
+import { formatDuration } from '../utils/format';
+import WidgetOutputView from '../WidgetCard/views';
+import RunLogs from './RunLogs';
+
+const RUN_STATUS_COLOR: Record<string, string> = {
+ failed: 'error',
+ running: 'processing',
+ succeeded: 'success',
+ timeout: 'warning',
+};
+
+interface WidgetRunPreviewProps {
+ run: DashboardWidgetRunItem;
+ view?: WidgetView | null;
+}
+
+/** One run in full: its complete output (no row cap), then its error and logs. */
+const WidgetRunPreview = memo<WidgetRunPreviewProps>(({ run, view }) => {
+ const { t } = useTranslation('dashboard');
+
+ return (
+ <Flexbox data-run-preview={run.id} gap={12}>
+ <Flexbox horizontal align={'center'} gap={8}>
+ <Tag color={RUN_STATUS_COLOR[run.status]} size={'small'}>
+ {t(`run.status.${run.status}`)}
+ </Tag>
+ <Text fontSize={12} type={'secondary'}>
+ {[
+ t(`run.trigger.${run.trigger}`),
+ formatDuration(run.durationMs),
+ dayjs(run.startedAt).format('YYYY-MM-DD HH:mm:ss'),
+ ]
+ .filter(Boolean)
+ .join(' · ')}
+ </Text>
+ </Flexbox>
+ {run.output && (
+ <div style={{ minHeight: 120 }}>
+ <WidgetOutputView density={'full'} output={run.output} view={view} />
+ </div>
+ )}
+ <RunLogs run={run} />
+ </Flexbox>
+ );
+});
+
+WidgetRunPreview.displayName = 'DashboardWidgetRunPreview';
+
+export default WidgetRunPreview;
diff --git a/src/features/Dashboard/WidgetDetail/VersionDiff.tsx b/src/features/Dashboard/WidgetDetail/VersionDiff.tsx
new file mode 100644
index 00000000000..f064216e8e2
--- /dev/null
+++ b/src/features/Dashboard/WidgetDetail/VersionDiff.tsx
@@ -0,0 +1,141 @@
+'use client';
+
+import { CodeDiff, Flexbox } from '@lobehub/ui';
+import { Select, Text } from '@lobehub/ui/base-ui';
+import { memo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import AsyncBoundary from '@/components/AsyncBoundary';
+import type { DashboardWidgetVersionItem } from '@/services/dashboard';
+import { dashboardSelectors, useDashboardStore } from '@/store/dashboard';
+
+import { defaultDiffPair } from '../WidgetPreview/previewWidget';
+import { contractOf, DIFF_OPTIONS, RUNTIME_LANGUAGE, withTrailingNewline } from './diffContent';
+
+interface ScriptDiffProps {
+ base?: DashboardWidgetVersionItem;
+ target: DashboardWidgetVersionItem;
+}
+
+/** Script and contract changes from `base` to `target`; the whole script when there is no base. */
+export const ScriptDiff = memo<ScriptDiffProps>(({ base, target }) => {
+ const { t } = useTranslation('dashboard');
+ const language = RUNTIME_LANGUAGE[target.runtime] ?? 'plaintext';
+ const baseContract = base ? contractOf(base) : undefined;
+ const targetContract = contractOf(target);
+ const sameScript = base?.script === target.script;
+
+ return (
+ <Flexbox data-version-diff gap={12}>
+ {sameScript ? (
+ <Text fontSize={12} type={'secondary'}>
+ {t('portal.diff.identical')}
+ </Text>
+ ) : (
+ <CodeDiff
+ diffOptions={DIFF_OPTIONS}
+ language={language}
+ newContent={withTrailingNewline(target.script)}
+ oldContent={withTrailingNewline(base?.script ?? '')}
+ showHeader={false}
+ viewMode={'unified'}
+ />
+ )}
+ {base && baseContract !== targetContract && (
+ <Flexbox gap={6}>
+ <Text fontSize={12} weight={500}>
+ {t('portal.diff.manifest')}
+ </Text>
+ <CodeDiff
+ diffOptions={DIFF_OPTIONS}
+ language={'json'}
+ newContent={withTrailingNewline(targetContract)}
+ oldContent={withTrailingNewline(baseContract!)}
+ showHeader={false}
+ viewMode={'unified'}
+ />
+ </Flexbox>
+ )}
+ </Flexbox>
+ );
+});
+
+ScriptDiff.displayName = 'DashboardScriptDiff';
+
+interface VersionDiffProps {
+ /** Version to review first; defaults to the newest. */
+ targetVersionId?: string;
+ widgetId: string;
+}
+
+/** Pick any two versions of a widget and compare their scripts and contracts. */
+const VersionDiff = memo<VersionDiffProps>(({ widgetId, targetVersionId }) => {
+ const { t } = useTranslation('dashboard');
+ const useFetchWidgetVersions = useDashboardStore((s) => s.useFetchWidgetVersions);
+ const { data, error, isLoading, mutate } = useFetchWidgetVersions(widgetId);
+ const versions = useDashboardStore(dashboardSelectors.widgetVersions(widgetId));
+ const [picked, setPicked] = useState<{ baseId?: string; targetId?: string }>({});
+
+ const fallback = defaultDiffPair(versions, targetVersionId);
+ const targetId = picked.targetId ?? fallback.targetId;
+ const baseId = picked.baseId ?? fallback.baseId;
+ const target = versions.find((version) => version.id === targetId);
+ const base = versions.find((version) => version.id === baseId);
+
+ const options = versions.map((version) => ({
+ label: `v${version.version} · ${t(`version.status.${version.status}`)}`,
+ value: version.id,
+ }));
+
+ return (
+ <AsyncBoundary
+ data={data}
+ error={error}
+ isEmpty={data?.length === 0}
+ isLoading={isLoading}
+ empty={
+ <Text fontSize={12} type={'secondary'}>
+ {t('version.empty')}
+ </Text>
+ }
+ onRetry={() => void mutate()}
+ >
+ {versions.length < 2 || !target ? (
+ <Flexbox gap={8}>
+ <Text fontSize={12} type={'secondary'}>
+ {t('portal.diff.single')}
+ </Text>
+ {target && <ScriptDiff target={target} />}
+ </Flexbox>
+ ) : (
+ <Flexbox gap={12}>
+ <Flexbox horizontal align={'center'} gap={8} wrap={'wrap'}>
+ <Text fontSize={12} type={'secondary'}>
+ {t('portal.diff.base')}
+ </Text>
+ <Select
+ options={options}
+ size={'small'}
+ value={baseId}
+ onChange={(value) => setPicked({ baseId: String(value), targetId })}
+ />
+ <Text fontSize={12} type={'secondary'}>
+ {t('portal.diff.target')}
+ </Text>
+ <Select
+ options={options}
+ size={'small'}
+ value={targetId}
+ onChange={(value) => setPicked({ baseId, targetId: String(value) })}
+ />
+ </Flexbox>
+ <ScriptDiff base={base} target={target} />
+ </Flexbox>
+ )}
+ </AsyncBoundary>
+ );
+});
+
+VersionDiff.displayName = 'DashboardVersionDiff';
+
+export default VersionDiff;
diff --git a/src/features/Dashboard/WidgetDetail/VersionList.tsx b/src/features/Dashboard/WidgetDetail/VersionList.tsx
new file mode 100644
index 00000000000..fd6ddbb71aa
--- /dev/null
+++ b/src/features/Dashboard/WidgetDetail/VersionList.tsx
@@ -0,0 +1,134 @@
+'use client';
+
+import { Flexbox, Highlighter, Icon } from '@lobehub/ui';
+import { Tag, Text, Tooltip } from '@lobehub/ui/base-ui';
+import { createStaticStyles, cssVar } from 'antd-style';
+import dayjs from 'dayjs';
+import { BotIcon, ChevronDownIcon, ChevronRightIcon, UserIcon } from 'lucide-react';
+import { memo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import AsyncBoundary from '@/components/AsyncBoundary';
+import type { DashboardWidgetVersionItem } from '@/services/dashboard';
+import { dashboardSelectors, useDashboardStore } from '@/store/dashboard';
+
+const VERSION_STATUS_COLOR: Record<string, string | undefined> = {
+ archived: undefined,
+ draft: 'info',
+ published: 'success',
+};
+
+const RUNTIME_LANGUAGE: Record<string, string> = {
+ bash: 'bash',
+ node: 'javascript',
+ python: 'python',
+};
+
+const styles = createStaticStyles(({ css }) => ({
+ item: css`
+ padding: 10px;
+ border: 1px solid ${cssVar.colorBorderSecondary};
+ border-radius: ${cssVar.borderRadius};
+ `,
+ toggle: css`
+ cursor: pointer;
+ user-select: none;
+ `,
+}));
+
+const VersionItem = memo<{ version: DashboardWidgetVersionItem }>(({ version }) => {
+ const { t } = useTranslation('dashboard');
+ const [showScript, setShowScript] = useState(false);
+
+ return (
+ <Flexbox className={styles.item} data-version={version.version} gap={6}>
+ <Flexbox horizontal align={'center'} gap={8}>
+ <Text weight={600}>{`v${version.version}`}</Text>
+ <Tag color={VERSION_STATUS_COLOR[version.status]} size={'small'}>
+ {t(`version.status.${version.status}`)}
+ </Tag>
+ <Tag size={'small'}>{version.runtime}</Tag>
+ <Tag size={'small'}>{version.outputType}</Tag>
+ <Flexbox flex={1} />
+ <Tooltip title={t(`version.source.${version.sourceType}`)}>
+ <Icon
+ color={cssVar.colorTextTertiary}
+ icon={version.sourceType === 'agent' ? BotIcon : UserIcon}
+ size={14}
+ />
+ </Tooltip>
+ <Text
+ fontSize={12}
+ title={dayjs(version.createdAt).format('YYYY-MM-DD HH:mm:ss')}
+ type={'secondary'}
+ >
+ {dayjs(version.createdAt).fromNow()}
+ </Text>
+ </Flexbox>
+ {version.changeNote && <Text fontSize={12}>{version.changeNote}</Text>}
+ {version.publishedAt && (
+ <Text fontSize={12} type={'secondary'}>
+ {t('version.publishedAt', {
+ time: dayjs(version.publishedAt).format('YYYY-MM-DD HH:mm'),
+ })}
+ </Text>
+ )}
+ <Flexbox
+ horizontal
+ align={'center'}
+ className={styles.toggle}
+ gap={4}
+ onClick={() => setShowScript((value) => !value)}
+ >
+ <Icon icon={showScript ? ChevronDownIcon : ChevronRightIcon} size={14} />
+ <Text fontSize={12} type={'secondary'}>
+ {t('version.script')}
+ </Text>
+ </Flexbox>
+ {showScript && (
+ <Highlighter
+ language={RUNTIME_LANGUAGE[version.runtime] ?? 'plaintext'}
+ style={{ maxHeight: 320, overflow: 'auto' }}
+ variant={'filled'}
+ >
+ {version.script}
+ </Highlighter>
+ )}
+ </Flexbox>
+ );
+});
+
+VersionItem.displayName = 'DashboardVersionItem';
+
+/** Every version of the widget, newest first, with the live one marked. */
+const VersionList = memo<{ widgetId: string }>(({ widgetId }) => {
+ const { t } = useTranslation('dashboard');
+ const useFetchWidgetVersions = useDashboardStore((s) => s.useFetchWidgetVersions);
+ const { data, error, isLoading, mutate } = useFetchWidgetVersions(widgetId);
+ const versions = useDashboardStore(dashboardSelectors.widgetVersions(widgetId));
+
+ return (
+ <AsyncBoundary
+ data={data}
+ error={error}
+ isEmpty={data?.length === 0}
+ isLoading={isLoading}
+ empty={
+ <Text fontSize={12} type={'secondary'}>
+ {t('version.empty')}
+ </Text>
+ }
+ onRetry={() => void mutate()}
+ >
+ <Flexbox gap={8}>
+ {versions.map((version) => (
+ <VersionItem key={version.id} version={version} />
+ ))}
+ </Flexbox>
+ </AsyncBoundary>
+ );
+});
+
+VersionList.displayName = 'DashboardVersionList';
+
+export default VersionList;
diff --git a/src/features/Dashboard/WidgetDetail/diffContent.test.ts b/src/features/Dashboard/WidgetDetail/diffContent.test.ts
new file mode 100644
index 00000000000..69c1111e1fa
--- /dev/null
+++ b/src/features/Dashboard/WidgetDetail/diffContent.test.ts
@@ -0,0 +1,32 @@
+import { describe, expect, it } from 'vitest';
+
+import { contractOf, DIFF_OPTIONS, withTrailingNewline } from './diffContent';
+
+describe('diffContent', () => {
+ it('expands unchanged lines so the untranslatable collapsed-lines label never renders', () => {
+ expect(DIFF_OPTIONS).toMatchObject({ expandUnchanged: true });
+ });
+
+ it('diffs the contract without the script', () => {
+ const contract = contractOf({
+ manifest: { timeoutMs: 1000 },
+ outputType: 'stat',
+ runtime: 'node',
+ script: 'console.log(1)',
+ view: null,
+ } as any);
+
+ expect(JSON.parse(contract)).toEqual({
+ manifest: { timeoutMs: 1000 },
+ outputType: 'stat',
+ runtime: 'node',
+ view: null,
+ });
+ });
+
+ it('ignores a missing trailing newline', () => {
+ expect(withTrailingNewline('a')).toBe('a\n');
+ expect(withTrailingNewline('a\n')).toBe('a\n');
+ expect(withTrailingNewline('')).toBe('');
+ });
+});
diff --git a/src/features/Dashboard/WidgetDetail/diffContent.ts b/src/features/Dashboard/WidgetDetail/diffContent.ts
new file mode 100644
index 00000000000..19b9f40b85a
--- /dev/null
+++ b/src/features/Dashboard/WidgetDetail/diffContent.ts
@@ -0,0 +1,31 @@
+import type { DashboardWidgetVersionItem } from '@/services/dashboard';
+
+export const RUNTIME_LANGUAGE: Record<string, string> = {
+ bash: 'bash',
+ node: 'javascript',
+ python: 'python',
+};
+
+/** A diff reads as a change to the code, not to a missing trailing newline. */
+export const withTrailingNewline = (value: string) =>
+ value === '' || value.endsWith('\n') ? value : `${value}\n`;
+
+/**
+ * Show every line. Widget scripts are short, and the collapsed-context
+ * separator of the diff renderer is a hardcoded English label ("N unmodified
+ * lines") that cannot be localized.
+ */
+export const DIFF_OPTIONS = { expandUnchanged: true };
+
+/** The declarative half of a version: everything besides the script. */
+export const contractOf = (version: DashboardWidgetVersionItem) =>
+ JSON.stringify(
+ {
+ manifest: version.manifest ?? null,
+ outputType: version.outputType,
+ runtime: version.runtime,
+ view: version.view ?? null,
+ },
+ null,
+ 2,
+ );
diff --git a/src/features/Dashboard/WidgetDetail/index.tsx b/src/features/Dashboard/WidgetDetail/index.tsx
new file mode 100644
index 00000000000..a4efaf81d68
--- /dev/null
+++ b/src/features/Dashboard/WidgetDetail/index.tsx
@@ -0,0 +1,267 @@
+'use client';
+
+import { Flexbox } from '@lobehub/ui';
+import { Alert, Drawer, Tabs, Text } from '@lobehub/ui/base-ui';
+import { createStaticStyles, cssVar } from 'antd-style';
+import dayjs from 'dayjs';
+import { memo, type ReactNode, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import type { DashboardWidgetItem } from '@/services/dashboard';
+import { dashboardSelectors, useDashboardStore } from '@/store/dashboard';
+
+import { ErrorLine } from '../ErrorLine';
+import { useWidgetTrend } from '../hooks/useWidgetTrend';
+import { getWidgetHealth, getWidgetUpdatedAt } from '../utils/widgetHealth';
+import HealthDot, { getHealthTone, HEALTH_TONE_COLOR } from '../WidgetCard/HealthDot';
+import StatusBadges from '../WidgetCard/StatusBadges';
+import WidgetOutputView from '../WidgetCard/views';
+import WidgetRefreshButton from '../WidgetRefreshButton';
+import RunHistory from './RunHistory';
+import VersionDiff from './VersionDiff';
+import VersionList from './VersionList';
+
+const styles = createStaticStyles(({ css }) => ({
+ cell: css`
+ min-width: 0;
+ padding-block: 10px;
+ padding-inline: 12px;
+ background: ${cssVar.colorBgContainer};
+ `,
+ cellLabel: css`
+ font-size: 12px;
+ color: ${cssVar.colorTextTertiary};
+ `,
+ cellValue: css`
+ overflow: hidden;
+
+ font-size: 13px;
+ font-variant-numeric: tabular-nums;
+ color: ${cssVar.colorText};
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ `,
+ grid: css`
+ display: grid;
+ grid-template-columns: repeat(2, minmax(0, 1fr));
+ gap: 1px;
+ background: ${cssVar.colorBorderSecondary};
+ `,
+ hint: css`
+ font-size: 12px;
+ color: ${cssVar.colorTextTertiary};
+ `,
+ status: css`
+ padding-block: 10px;
+ padding-inline: 12px;
+ border-block-end: 1px solid ${cssVar.colorBorderSecondary};
+ `,
+ summary: css`
+ overflow: hidden;
+ border: 1px solid ${cssVar.colorBorderSecondary};
+ border-radius: ${cssVar.borderRadiusLG};
+ `,
+}));
+
+/** One fact of the summary grid: a quiet label over its value, with an optional second line. */
+const Cell = ({
+ hint,
+ label,
+ children,
+}: {
+ children: ReactNode;
+ hint?: ReactNode;
+ label: string;
+}) => (
+ <Flexbox className={styles.cell} gap={2}>
+ <span className={styles.cellLabel}>{label}</span>
+ <span className={styles.cellValue}>{children}</span>
+ {hint && <span className={styles.hint}>{hint}</span>}
+ </Flexbox>
+);
+
+const formatTime = (value?: Date | string | null) =>
+ value ? dayjs(value).format('YYYY-MM-DD HH:mm:ss') : undefined;
+
+const fromNow = (value?: Date | string | null) => (value ? dayjs(value).fromNow() : undefined);
+
+/** Freshness, schedule and live version of the widget, plus the last error. */
+const WidgetSummary = memo<{ widget: DashboardWidgetItem }>(({ widget }) => {
+ const { t } = useTranslation('dashboard');
+ const running = useDashboardStore(dashboardSelectors.isWidgetRunning(widget.id));
+ const useFetchWidgetVersions = useDashboardStore((s) => s.useFetchWidgetVersions);
+ useFetchWidgetVersions(widget.id);
+ const versions = useDashboardStore(dashboardSelectors.widgetVersions(widget.id));
+ const published = versions.find((version) => version.id === widget.publishedVersionId);
+ const draft = versions.find((version) => version.id === widget.draftVersionId);
+ const health = getWidgetHealth(widget, { runningLocally: running });
+ const updatedAt = getWidgetUpdatedAt(widget);
+ const tone = getHealthTone(health);
+ const badges = health.badges.filter((badge) => badge !== 'running');
+
+ return (
+ <Flexbox data-widget-summary gap={12}>
+ <div className={styles.summary}>
+ <Flexbox horizontal align={'center'} className={styles.status} gap={8}>
+ <HealthDot health={health} />
+ <Text fontSize={13} style={{ color: HEALTH_TONE_COLOR[tone] }} weight={500}>
+ {health.running
+ ? t('widget.status.running')
+ : badges.length > 0
+ ? t(`widget.status.${badges[0]}`)
+ : t('widget.status.ok')}
+ </Text>
+ {badges.length > 1 && <StatusBadges badges={badges.slice(1)} health={health} />}
+ <Flexbox flex={1} />
+ <WidgetRefreshButton widget={widget} />
+ </Flexbox>
+ <div className={styles.grid}>
+ <Cell hint={fromNow(updatedAt)} label={t('detail.updatedAt')}>
+ {formatTime(updatedAt) ?? '—'}
+ </Cell>
+ <Cell
+ label={t('detail.lastRunAt')}
+ hint={
+ widget.lastRunAt ? t(`run.status.${widget.lastRunStatus ?? 'running'}`) : undefined
+ }
+ >
+ {formatTime(widget.lastRunAt) ?? '—'}
+ </Cell>
+ <Cell
+ label={t('detail.schedule')}
+ hint={
+ widget.nextRunAt
+ ? `${t('detail.nextRunAt')} ${formatTime(widget.nextRunAt)}`
+ : undefined
+ }
+ >
+ {widget.schedulePattern
+ ? [widget.schedulePattern, widget.scheduleTimezone].filter(Boolean).join(' · ')
+ : t('detail.manualOnly')}
+ </Cell>
+ <Cell
+ hint={draft ? t('detail.versionDraft', { version: draft.version }) : undefined}
+ label={t('detail.version')}
+ >
+ {published
+ ? t('detail.versionPublished', { version: published.version })
+ : widget.publishedVersionId
+ ? '…'
+ : t('detail.versionNone')}
+ </Cell>
+ </div>
+ </div>
+ {health.failed && health.error && (
+ <ErrorLine
+ detail={`${health.error.code}\n${health.error.message}`}
+ summary={
+ widget.consecutiveFailures > 1
+ ? `${t('widget.status.failed')} · ${t('detail.failures')} ${widget.consecutiveFailures}`
+ : t('widget.status.failed')
+ }
+ />
+ )}
+ {health.partialMessage && (
+ <Alert
+ showIcon
+ description={health.partialMessage}
+ title={t('widget.status.partial')}
+ type={'warning'}
+ />
+ )}
+ </Flexbox>
+ );
+});
+
+WidgetSummary.displayName = 'DashboardWidgetSummary';
+
+/** The full latest output, without the card's row cap. */
+const WidgetData = memo<{ widget: DashboardWidgetItem }>(({ widget }) => {
+ const { t } = useTranslation('dashboard');
+ const trend = useWidgetTrend(widget);
+
+ if (!widget.latestOutput) {
+ return (
+ <Text fontSize={12} type={'secondary'}>
+ {t('detail.noOutput')}
+ </Text>
+ );
+ }
+
+ return (
+ // A stat fills its height with the trend, so give it room the drawer does not size.
+ <div style={widget.latestOutput.type === 'stat' ? { height: 200 } : { minHeight: 120 }}>
+ <WidgetOutputView density={'full'} output={widget.latestOutput} trend={trend} />
+ </div>
+ );
+});
+
+WidgetData.displayName = 'DashboardWidgetData';
+
+type DetailTab = 'data' | 'diff' | 'runs' | 'versions';
+
+export interface WidgetDetailPanelProps {
+ /** Version the diff tab reviews first, e.g. the draft a conversation produced. */
+ diffTargetVersionId?: string;
+ widget: DashboardWidgetItem;
+}
+
+/**
+ * The full drill-down of one widget — freshness summary, then full data, run
+ * history with logs, versions and a version diff. Hosted by the board drawer
+ * and by the chat Portal.
+ */
+export const WidgetDetailPanel = memo<WidgetDetailPanelProps>(({ widget, diffTargetVersionId }) => {
+ const { t } = useTranslation('dashboard');
+ const [tab, setTab] = useState<DetailTab>('data');
+
+ return (
+ <Flexbox data-widget-detail={widget.id} gap={16}>
+ <WidgetSummary widget={widget} />
+ <Tabs
+ activeKey={tab}
+ items={[
+ { key: 'data', label: t('detail.tab.data') },
+ { key: 'runs', label: t('detail.tab.runs') },
+ { key: 'versions', label: t('detail.tab.versions') },
+ { key: 'diff', label: t('detail.tab.diff') },
+ ]}
+ onChange={(key) => setTab(key as DetailTab)}
+ />
+ {tab === 'data' && <WidgetData widget={widget} />}
+ {tab === 'runs' && <RunHistory widgetId={widget.id} />}
+ {tab === 'versions' && <VersionList widgetId={widget.id} />}
+ {tab === 'diff' && <VersionDiff targetVersionId={diffTargetVersionId} widgetId={widget.id} />}
+ </Flexbox>
+ );
+});
+
+WidgetDetailPanel.displayName = 'DashboardWidgetDetailPanel';
+
+export interface WidgetDetailDrawerProps {
+ onClose: () => void;
+ /** The widget to drill into; the drawer is closed while undefined. */
+ widget?: DashboardWidgetItem;
+}
+
+/** Drill-down of one widget on a board, in a drawer. */
+const WidgetDetailDrawer = memo<WidgetDetailDrawerProps>(({ widget, onClose }) => (
+ <Drawer
+ open={!!widget}
+ placement={'right'}
+ title={widget?.title}
+ width={'min(92vw, 640px)'}
+ onClose={onClose}
+ >
+ {widget && (
+ <Flexbox gap={16}>
+ {widget.description && <Text type={'secondary'}>{widget.description}</Text>}
+ <WidgetDetailPanel widget={widget} />
+ </Flexbox>
+ )}
+ </Drawer>
+));
+
+WidgetDetailDrawer.displayName = 'DashboardWidgetDetailDrawer';
+
+export default WidgetDetailDrawer;
diff --git a/src/features/Dashboard/WidgetGrid/index.tsx b/src/features/Dashboard/WidgetGrid/index.tsx
new file mode 100644
index 00000000000..aa483b19b55
--- /dev/null
+++ b/src/features/Dashboard/WidgetGrid/index.tsx
@@ -0,0 +1,54 @@
+'use client';
+
+import { memo, useMemo, useState } from 'react';
+
+import type { DashboardWidgetItem } from '@/services/dashboard';
+
+import BoardWidgetCard from '../Board/BoardWidgetCard';
+import { cellStyle, gridStyles } from '../Board/style';
+import { resolveLayouts } from '../utils/layout';
+import WidgetDetailDrawer from '../WidgetDetail';
+
+export interface DashboardWidgetGridProps {
+ widgets: DashboardWidgetItem[];
+}
+
+/**
+ * Widgets that are not tied to one board (e.g. everything a project owns),
+ * packed at their default sizes in the board grid, with refresh and drill-down.
+ */
+const DashboardWidgetGrid = memo<DashboardWidgetGridProps>(({ widgets }) => {
+ const [openWidgetId, setOpenWidgetId] = useState<string>();
+
+ const layouts = useMemo(
+ () =>
+ resolveLayouts(
+ widgets.map((widget) => ({ id: widget.id, outputType: widget.latestOutput?.type })),
+ ),
+ [widgets],
+ );
+
+ const openWidget = widgets.find((widget) => widget.id === openWidgetId);
+
+ return (
+ <>
+ <div className={gridStyles.grid} data-dashboard-grid={'widgets'}>
+ {widgets.map((widget) => (
+ <div
+ className={gridStyles.cell}
+ data-widget-id={widget.id}
+ key={widget.id}
+ style={cellStyle(layouts[widget.id])}
+ >
+ <BoardWidgetCard widget={widget} onOpen={setOpenWidgetId} />
+ </div>
+ ))}
+ </div>
+ <WidgetDetailDrawer widget={openWidget} onClose={() => setOpenWidgetId(undefined)} />
+ </>
+ );
+});
+
+DashboardWidgetGrid.displayName = 'DashboardWidgetGrid';
+
+export default DashboardWidgetGrid;
diff --git a/src/features/Dashboard/WidgetPreview/AddToDashboardButton.tsx b/src/features/Dashboard/WidgetPreview/AddToDashboardButton.tsx
new file mode 100644
index 00000000000..e56ab4a6bd1
--- /dev/null
+++ b/src/features/Dashboard/WidgetPreview/AddToDashboardButton.tsx
@@ -0,0 +1,128 @@
+'use client';
+
+import { Icon } from '@lobehub/ui';
+import { Button, type DropdownItem, DropdownMenu, toast } from '@lobehub/ui/base-ui';
+import { CheckIcon, LayoutDashboardIcon, PlusIcon } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';
+import { usePermission } from '@/hooks/usePermission';
+import { dashboardSelectors, useDashboardStore } from '@/store/dashboard';
+import { useUserStore } from '@/store/user';
+import { userProfileSelectors } from '@/store/user/selectors';
+
+import { openCreateDashboardModal } from '../DashboardFormModal';
+import {
+ canCreateDashboardFromPreview,
+ placeableDashboards,
+ placementBoards,
+} from './previewWidget';
+
+interface AddToDashboardButtonProps {
+ /** Boards the widget is already on; they show checked and are not re-added. */
+ placedIds: string[];
+ /** The widget's project, when it lives in one: a new board is created there. */
+ projectId?: string | null;
+ widgetId: string;
+}
+
+/** Put a widget on one of its placeable boards — the home level's, and its
+ * project's when it lives in one — or on a new one. */
+const AddToDashboardButton = memo<AddToDashboardButtonProps>(
+ ({ placedIds, projectId, widgetId }) => {
+ const { t } = useTranslation('dashboard');
+ const useFetchDashboards = useDashboardStore((s) => s.useFetchDashboards);
+ const useFetchProjectDashboards = useDashboardStore((s) => s.useFetchProjectDashboards);
+ const addWidgetToDashboard = useDashboardStore((s) => s.addWidgetToDashboard);
+ const adding = useDashboardStore(dashboardSelectors.isWidgetAdding(widgetId));
+ const { isLoading } = useFetchDashboards();
+ // A project widget can also be placed on its project's boards.
+ const { isLoading: isProjectLoading } = useFetchProjectDashboards(projectId ?? undefined);
+ const homeBoards = useDashboardStore(dashboardSelectors.dashboardList());
+ const projectBoards = useDashboardStore(
+ dashboardSelectors.projectDashboards(projectId ?? undefined),
+ );
+ const currentUserId = useUserStore(userProfileSelectors.userId);
+ const workspaceActive = !!useActiveWorkspaceSlug();
+ // Placing and creating are writes: workspace viewers lack create_content
+ // and the server refuses their writes, so they get neither.
+ const { allowed: canWrite } = usePermission('create_content');
+ // Only the caller's own boards can take the placement (addItem writes as
+ // the board's creator); teammates' readable boards are not offered.
+ const placeable = canWrite
+ ? placeableDashboards(
+ placementBoards(homeBoards, projectBoards, projectId, workspaceActive),
+ currentUserId,
+ )
+ : [];
+ // In a workspace, a widget outside a project cannot create a board it
+ // could open — home-level boards have no UI there.
+ const canCreate = canWrite && canCreateDashboardFromPreview(projectId, workspaceActive);
+
+ const add = async (dashboard: { id: string; title: string }) => {
+ try {
+ await addWidgetToDashboard(dashboard.id, widgetId);
+ toast.success(t('chat.added', { title: dashboard.title }));
+ } catch (error) {
+ console.error('[dashboard] add widget failed', error);
+ toast.error(t('chat.addFailed'));
+ }
+ };
+
+ const items: DropdownItem[] = [
+ ...placeable.map((dashboard) => {
+ const placed = placedIds.includes(dashboard.id);
+ return {
+ disabled: placed,
+ icon: <Icon icon={placed ? CheckIcon : LayoutDashboardIcon} />,
+ key: dashboard.id,
+ label: dashboard.title,
+ onClick: () => void add(dashboard),
+ };
+ }),
+ ...(placeable.length > 0 && canCreate ? [{ type: 'divider' as const }] : []),
+ ...(canCreate
+ ? [
+ {
+ icon: <Icon icon={PlusIcon} />,
+ key: 'new',
+ label: t('chat.newDashboard'),
+ onClick: () =>
+ // Created and placed in one write; a failure keeps the modal open
+ // with its error and leaves no empty board behind. The board is
+ // created on the widget's own level, so a project widget never
+ // creates a home board its link cannot open.
+ openCreateDashboardModal({
+ level: { projectId: projectId ?? null },
+ onCreated: (dashboard) =>
+ toast.success(t('chat.added', { title: dashboard.title })),
+ widgetId,
+ }),
+ },
+ ]
+ : []),
+ ];
+
+ // Nothing placeable and no creation — an empty dropdown helps no one
+ // (e.g. a workspace-root widget inside a workspace).
+ if (items.length === 0) return null;
+
+ return (
+ <DropdownMenu items={items} placement={'bottomLeft'}>
+ <Button
+ data-widget-add
+ icon={LayoutDashboardIcon}
+ loading={adding || isLoading || isProjectLoading}
+ size={'small'}
+ >
+ {t('chat.add')}
+ </Button>
+ </DropdownMenu>
+ );
+ },
+);
+
+AddToDashboardButton.displayName = 'DashboardAddToDashboardButton';
+
+export default AddToDashboardButton;
diff --git a/src/features/Dashboard/WidgetPreview/DryRunReview.tsx b/src/features/Dashboard/WidgetPreview/DryRunReview.tsx
new file mode 100644
index 00000000000..2a66209dc0c
--- /dev/null
+++ b/src/features/Dashboard/WidgetPreview/DryRunReview.tsx
@@ -0,0 +1,86 @@
+'use client';
+
+import { Flexbox, Highlighter } from '@lobehub/ui';
+import { Skeleton, Text } from '@lobehub/ui/base-ui';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { RUNTIME_LANGUAGE } from '../WidgetDetail/diffContent';
+import { AccessFacts, Fact, reviewStyles, ReviewUnavailable } from './ReviewFacts';
+import { useWidgetReview } from './useWidgetReview';
+
+interface DryRunReviewProps {
+ /** Holds the host's approve action until the version that will run is on screen. */
+ onApprovalBlockedChange?: (blocked: boolean) => void;
+ /**
+ * Called once with the version shown when the request named none, so the
+ * caller can persist it into the request: approval then runs exactly the
+ * version reviewed here.
+ */
+ onPinVersion?: (versionId: string) => void;
+ /** The version that will run; when absent the current draft is shown and pinned. */
+ versionId?: string;
+ widgetId: string;
+}
+
+/**
+ * Approval for running an agent-written draft that reads credentials or
+ * reaches the network: the exact script, its runtime, and what it may touch.
+ */
+const DryRunReview = memo<DryRunReviewProps>(
+ ({ widgetId, versionId, onApprovalBlockedChange, onPinVersion }) => {
+ const { t } = useTranslation('dashboard');
+ const { error, retry, status, target, widget } = useWidgetReview(widgetId, versionId, {
+ onApprovalBlockedChange,
+ onPinVersion,
+ });
+
+ if (status === 'error' || status === 'missing') {
+ return <ReviewUnavailable error={error} missing={status === 'missing'} onRetry={retry} />;
+ }
+
+ if (!widget || !target) {
+ return (
+ <Flexbox gap={10}>
+ <Skeleton.Text rows={3} />
+ <Skeleton height={120} width={'100%'} />
+ </Flexbox>
+ );
+ }
+
+ return (
+ <Flexbox data-widget-dry-run-review={widgetId} gap={12}>
+ <Flexbox gap={4}>
+ <Text weight={600}>{`${widget.title} · v${target.version}`}</Text>
+ <Text fontSize={12} type={'secondary'}>
+ {t('dryRun.intro')}
+ </Text>
+ </Flexbox>
+
+ <Flexbox className={reviewStyles.section} gap={6}>
+ <Fact label={t('dryRun.runtime')}>
+ <Text fontSize={12}>{target.runtime}</Text>
+ </Fact>
+ <AccessFacts manifest={target.manifest} />
+ </Flexbox>
+
+ <Flexbox gap={6}>
+ <Text fontSize={12} type={'secondary'} weight={500}>
+ {t('publish.scriptNew')}
+ </Text>
+ <Highlighter
+ language={RUNTIME_LANGUAGE[target.runtime] ?? 'plaintext'}
+ style={{ maxHeight: 360, overflow: 'auto' }}
+ variant={'filled'}
+ >
+ {target.script}
+ </Highlighter>
+ </Flexbox>
+ </Flexbox>
+ );
+ },
+);
+
+DryRunReview.displayName = 'DashboardDryRunReview';
+
+export default DryRunReview;
diff --git a/src/features/Dashboard/WidgetPreview/PublishConfirmModal.tsx b/src/features/Dashboard/WidgetPreview/PublishConfirmModal.tsx
new file mode 100644
index 00000000000..4abee23755f
--- /dev/null
+++ b/src/features/Dashboard/WidgetPreview/PublishConfirmModal.tsx
@@ -0,0 +1,90 @@
+'use client';
+
+import { Flexbox } from '@lobehub/ui';
+import { Button, createModal, ModalFooter, useModalContext } from '@lobehub/ui/base-ui';
+import { t as translate } from 'i18next';
+import { memo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import PublishReview from './PublishReview';
+
+interface PublishConfirmModalProps {
+ /** Runs when the user confirms; a failure keeps the modal open. */
+ onConfirm: () => Promise<void>;
+ versionId: string;
+ widgetId: string;
+}
+
+/**
+ * The gate behind the preview's Publish action: the same review the
+ * agent-side requestPublish intervention renders — the dry run, what the
+ * version may touch, the cadence publishing will actually retain and the
+ * exact code diff — with an explicit confirm. The confirm stays disabled
+ * until the reviewed version is on screen, exactly like the intervention's
+ * approve action.
+ */
+const PublishConfirmModal = memo<PublishConfirmModalProps>(({ widgetId, versionId, onConfirm }) => {
+ const { t } = useTranslation(['dashboard', 'common']);
+ const { close } = useModalContext();
+ const [blocked, setBlocked] = useState(true);
+ const [confirming, setConfirming] = useState(false);
+
+ const handleConfirm = async () => {
+ if (confirming) return;
+ setConfirming(true);
+ try {
+ await onConfirm();
+ close();
+ } catch {
+ // The confirm handler already surfaced the failure (toast) — keep the
+ // review open so the user can fix and retry.
+ } finally {
+ setConfirming(false);
+ }
+ };
+
+ return (
+ <>
+ <Flexbox gap={12} padding={16}>
+ <PublishReview
+ versionId={versionId}
+ widgetId={widgetId}
+ onApprovalBlockedChange={setBlocked}
+ />
+ </Flexbox>
+ <ModalFooter>
+ <Button onClick={close}>{t('cancel', { ns: 'common' })}</Button>
+ <Button
+ disabled={blocked}
+ loading={confirming}
+ type={'primary'}
+ onClick={() => void handleConfirm()}
+ >
+ {t('chat.publish')}
+ </Button>
+ </ModalFooter>
+ </>
+ );
+});
+
+PublishConfirmModal.displayName = 'DashboardPublishConfirmModal';
+
+/** Open the publish review gate for one version of a widget. */
+export const openPublishConfirmModal = ({
+ onConfirm,
+ versionId,
+ widgetId,
+}: {
+ onConfirm: () => Promise<void>;
+ versionId: string;
+ widgetId: string;
+}) =>
+ createModal({
+ content: (
+ <PublishConfirmModal versionId={versionId} widgetId={widgetId} onConfirm={onConfirm} />
+ ),
+ footer: null,
+ styles: { content: { padding: 0 } },
+ title: translate('chat.publishReviewTitle', { ns: 'dashboard' }),
+ width: 560,
+ });
diff --git a/src/features/Dashboard/WidgetPreview/PublishReview.tsx b/src/features/Dashboard/WidgetPreview/PublishReview.tsx
new file mode 100644
index 00000000000..dc82da568b9
--- /dev/null
+++ b/src/features/Dashboard/WidgetPreview/PublishReview.tsx
@@ -0,0 +1,116 @@
+'use client';
+
+import { Flexbox } from '@lobehub/ui';
+import { Alert, Skeleton, Text } from '@lobehub/ui/base-ui';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import WidgetCard from '../WidgetCard';
+import { ScriptDiff } from '../WidgetDetail/VersionDiff';
+import { resolvePublishSchedule, toPreviewWidget } from './previewWidget';
+import { AccessFacts, Fact, reviewStyles, ReviewUnavailable } from './ReviewFacts';
+import { useWidgetReview } from './useWidgetReview';
+
+interface PublishReviewProps {
+ /** Holds the host's approve action until the version that goes live is on screen. */
+ onApprovalBlockedChange?: (blocked: boolean) => void;
+ /**
+ * Called once with the version shown when the request named none, so the
+ * caller can persist it into the request: approval then publishes exactly
+ * the version reviewed here, never whatever the draft is by then.
+ */
+ onPinVersion?: (versionId: string) => void;
+ /** The agent's one-line reason, if it gave one. */
+ summary?: string;
+ /** The version under review; when absent the current draft is shown and pinned. */
+ versionId?: string;
+ widgetId: string;
+}
+
+/**
+ * Everything a user needs to approve making a widget live: what it showed in
+ * its dry run, what it means, what it may touch (network, credentials), how
+ * often it runs, and exactly how its code differs from what is live now.
+ */
+const PublishReview = memo<PublishReviewProps>(
+ ({ widgetId, versionId, summary, onApprovalBlockedChange, onPinVersion }) => {
+ const { t } = useTranslation('dashboard');
+ const { error, retry, run, status, target, versions, widget } = useWidgetReview(
+ widgetId,
+ versionId,
+ { onApprovalBlockedChange, onPinVersion, withRuns: true },
+ );
+ const live = versions.find((version) => version.status === 'published');
+
+ if (status === 'error' || status === 'missing') {
+ return <ReviewUnavailable error={error} missing={status === 'missing'} onRetry={retry} />;
+ }
+
+ // Runs are part of the review too: never show "no successful run" before they load.
+ if (!widget || !target || status === 'loading') {
+ return (
+ <Flexbox gap={10}>
+ <Skeleton height={140} width={'100%'} />
+ <Skeleton.Text rows={3} />
+ </Flexbox>
+ );
+ }
+
+ const manifest = target.manifest;
+ // The cadence publishing will actually retain, not the manifest's raw
+ // suggestion: an already-scheduled widget keeps its own schedule.
+ const schedule = resolvePublishSchedule(widget, manifest);
+
+ return (
+ <Flexbox data-widget-publish-review={widgetId} gap={12}>
+ <Flexbox gap={4}>
+ <Text weight={600}>{`${widget.title} · v${target.version}`}</Text>
+ {summary && <Text fontSize={13}>{summary}</Text>}
+ <Text fontSize={12} type={'secondary'}>
+ {t('publish.intro')}
+ </Text>
+ </Flexbox>
+
+ {run ? (
+ <Flexbox gap={6}>
+ <Text fontSize={12} type={'secondary'} weight={500}>
+ {t('publish.previewTitle')}
+ </Text>
+ <div style={{ height: run.output?.type === 'stat' ? 150 : 240 }}>
+ <WidgetCard view={target.view} widget={toPreviewWidget(widget, run)} />
+ </div>
+ </Flexbox>
+ ) : (
+ <Alert showIcon title={t('publish.noSuccessfulRun')} type={'warning'} />
+ )}
+
+ <Flexbox className={reviewStyles.section} gap={6}>
+ <Fact label={t('chat.definition')}>
+ <Text fontSize={12}>{widget.description || t('chat.noDefinition')}</Text>
+ </Fact>
+ <Fact label={t('publish.schedule')}>
+ <Text fontSize={12}>
+ {schedule.pattern
+ ? [schedule.pattern, schedule.timezone].filter(Boolean).join(' · ')
+ : t('publish.scheduleNone')}
+ </Text>
+ </Fact>
+ <AccessFacts manifest={manifest} />
+ </Flexbox>
+
+ <Flexbox gap={6}>
+ <Text fontSize={12} type={'secondary'} weight={500}>
+ {live && live.id !== target.id
+ ? t('publish.scriptChanges', { version: live.version })
+ : t('publish.scriptNew')}
+ </Text>
+ <ScriptDiff base={live && live.id !== target.id ? live : undefined} target={target} />
+ </Flexbox>
+ </Flexbox>
+ );
+ },
+);
+
+PublishReview.displayName = 'DashboardPublishReview';
+
+export default PublishReview;
diff --git a/src/features/Dashboard/WidgetPreview/ReviewFacts.tsx b/src/features/Dashboard/WidgetPreview/ReviewFacts.tsx
new file mode 100644
index 00000000000..ee2cc225801
--- /dev/null
+++ b/src/features/Dashboard/WidgetPreview/ReviewFacts.tsx
@@ -0,0 +1,109 @@
+'use client';
+
+import type { WidgetManifest } from '@lobechat/types';
+import { Flexbox } from '@lobehub/ui';
+import { Tag, Text } from '@lobehub/ui/base-ui';
+import { createStaticStyles, cssVar } from 'antd-style';
+import { memo, type ReactNode } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import AsyncError from '@/components/AsyncError';
+import { serverConfigSelectors, useServerConfigStore } from '@/store/serverConfig';
+
+export const reviewStyles = createStaticStyles(({ css }) => ({
+ label: css`
+ flex: none;
+ width: 88px;
+ color: ${cssVar.colorTextTertiary};
+ `,
+ section: css`
+ padding: 10px;
+ border-radius: ${cssVar.borderRadius};
+ background: ${cssVar.colorFillQuaternary};
+ `,
+}));
+
+export const Fact = ({ label, children }: { children: ReactNode; label: string }) => (
+ <Flexbox horizontal align={'baseline'} gap={8}>
+ <Text className={reviewStyles.label} fontSize={12}>
+ {label}
+ </Text>
+ <Flexbox horizontal flex={1} gap={4} style={{ minWidth: 0 }} wrap={'wrap'}>
+ {children}
+ </Flexbox>
+ </Flexbox>
+);
+
+/** What a version may touch when it runs: the hosts it can reach and the credentials it gets. */
+export const AccessFacts = memo<{ manifest?: WidgetManifest | null }>(({ manifest }) => {
+ const { t } = useTranslation('dashboard');
+ const hosts = manifest?.network?.allow ?? [];
+ const env = manifest?.env ?? [];
+ // The boolean network format — the deployed Worker's only one — switches
+ // egress on for any nonempty allowlist without enforcing the hosts, so the
+ // facts must say the script can reach any host, not just the declared ones.
+ const enforcesHosts = useServerConfigStore(
+ serverConfigSelectors.widgetSandboxEnforcesNetworkHosts,
+ );
+
+ return (
+ <>
+ <Fact label={t('publish.network')}>
+ {hosts.length > 0 ? (
+ <>
+ {!enforcesHosts && (
+ <Text fontSize={12} type={'warning'}>
+ {t('publish.networkUnrestricted')}
+ </Text>
+ )}
+ {hosts.map((host) => (
+ <Tag key={host} size={'small'}>
+ {host}
+ </Tag>
+ ))}
+ </>
+ ) : (
+ <Text fontSize={12}>{t('publish.networkNone')}</Text>
+ )}
+ </Fact>
+ <Fact label={t('publish.env')}>
+ {env.length > 0 ? (
+ env.map((item) => (
+ <Tag key={item.name} size={'small'}>
+ {[item.connector ? `${item.name} ← ${item.connector}` : item.name, item.field]
+ .filter(Boolean)
+ .join(' · ')}
+ </Tag>
+ ))
+ ) : (
+ <Text fontSize={12}>{t('publish.envNone')}</Text>
+ )}
+ </Fact>
+ </>
+ );
+});
+
+AccessFacts.displayName = 'DashboardReviewAccessFacts';
+
+/**
+ * The review could not be shown — a request failed, or the version under
+ * review is gone. Approval stays held, so say so and offer a retry.
+ */
+export const ReviewUnavailable = memo<{
+ error?: unknown;
+ missing?: boolean;
+ onRetry: () => void;
+}>(({ error, missing, onRetry }) => {
+ const { t } = useTranslation('dashboard');
+ return (
+ <AsyncError
+ description={missing ? t('review.versionMissing') : undefined}
+ error={error}
+ title={t('review.loadFailed')}
+ variant={'block'}
+ onRetry={onRetry}
+ />
+ );
+});
+
+ReviewUnavailable.displayName = 'DashboardReviewUnavailable';
diff --git a/src/features/Dashboard/WidgetPreview/index.tsx b/src/features/Dashboard/WidgetPreview/index.tsx
new file mode 100644
index 00000000000..6c7f0027359
--- /dev/null
+++ b/src/features/Dashboard/WidgetPreview/index.tsx
@@ -0,0 +1,260 @@
+'use client';
+
+import { Flexbox, Icon } from '@lobehub/ui';
+import { Button, Skeleton, Tag, Text, toast, Tooltip } from '@lobehub/ui/base-ui';
+import { createStaticStyles, cssVar } from 'antd-style';
+import { ArrowUpRightIcon, PanelRightOpenIcon, RocketIcon } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { usePermission } from '@/hooks/usePermission';
+import type { DashboardWidgetDetail, DashboardWidgetRunItem } from '@/services/dashboard';
+import { useChatStore } from '@/store/chat';
+import { dashboardSelectors, useDashboardStore } from '@/store/dashboard';
+import { useServerConfigStore } from '@/store/serverConfig';
+import { useUserStore } from '@/store/user';
+import { userProfileSelectors } from '@/store/user/selectors';
+
+import { formatDuration } from '../utils/format';
+import { getDashboardPath } from '../utils/path';
+import WidgetCard from '../WidgetCard';
+import AddToDashboardButton from './AddToDashboardButton';
+import { canPreviewPublish, getPreviewPublishState, toPreviewWidget } from './previewWidget';
+import { openPublishConfirmModal } from './PublishConfirmModal';
+
+const styles = createStaticStyles(({ css }) => ({
+ definition: css`
+ padding-block: 8px;
+ padding-inline: 10px;
+ border-radius: ${cssVar.borderRadius};
+ background: ${cssVar.colorFillQuaternary};
+ `,
+ root: css`
+ width: 100%;
+ padding: 12px;
+ border: 1px solid ${cssVar.colorBorderSecondary};
+ border-radius: ${cssVar.borderRadiusLG};
+ `,
+}));
+
+/** Card height by output shape — a single number needs far less room than rows. */
+const CARD_HEIGHT: Record<string, number> = { list: 260, series: 240, stat: 150, table: 260 };
+
+type PreviewRun = Pick<
+ DashboardWidgetRunItem,
+ 'durationMs' | 'error' | 'finishedAt' | 'id' | 'output' | 'startedAt' | 'status' | 'versionId'
+>;
+
+interface WidgetPreviewBodyProps {
+ run: PreviewRun;
+ widget: DashboardWidgetDetail;
+}
+
+/**
+ * A dry run as the user will see it on a board, with what the number means
+ * and the decisions that follow: publish it, place it, or open the details.
+ */
+export const WidgetPreviewBody = memo<WidgetPreviewBodyProps>(({ widget, run }) => {
+ const { t } = useTranslation('dashboard');
+ const navigate = useWorkspaceAwareNavigate();
+ const openDashboardWidget = useChatStore((s) => s.openDashboardWidget);
+ const publishWidgetVersion = useDashboardStore((s) => s.publishWidgetVersion);
+ const publishing = useDashboardStore(dashboardSelectors.isWidgetPublishing(widget.id));
+ const useFetchWidgetVersions = useDashboardStore((s) => s.useFetchWidgetVersions);
+ useFetchWidgetVersions(widget.id);
+ const versions = useDashboardStore(dashboardSelectors.widgetVersions(widget.id));
+
+ const version = versions.find((item) => item.id === run.versionId);
+ const draft = versions.find((item) => item.id === widget.draftVersionId);
+ const publishState = getPreviewPublishState(widget, run);
+ const currentUserId = useUserStore(userProfileSelectors.userId);
+ // Publishing is creator-only server-side; teammates reading the widget get
+ // no publish action at all instead of a button that always fails. The same
+ // create_content permission gates the write: a demoted creator keeps
+ // widget.userId but the server refuses their publish.
+ const { allowed: canWrite } = usePermission('create_content');
+ const canPublish = canWrite && canPreviewPublish(widget, currentUserId);
+ const preview = toPreviewWidget(widget, run);
+ const outputType = run.output?.type ?? version?.outputType ?? 'stat';
+ // Normalize once: an older server may not send the widget's boards list.
+ const dashboards = widget.dashboards ?? [];
+ // Board routes exist only in the desktop shell — the chips would navigate
+ // nowhere on mobile.
+ const isMobile = useServerConfigStore((s) => s.isMobile);
+
+ // Publishing goes through the same review the requestPublish intervention
+ // renders — nothing goes live on a bare click from the preview.
+ const handlePublish = () =>
+ openPublishConfirmModal({
+ versionId: run.versionId,
+ widgetId: widget.id,
+ onConfirm: async () => {
+ try {
+ const result = await publishWidgetVersion(widget.id, run.versionId);
+ toast.success(t('chat.published', { version: result?.version.version }));
+ } catch (error) {
+ toast.error(
+ t('chat.publishFailed', { message: error instanceof Error ? error.message : '' }),
+ );
+ // A failure must keep the review open for a retry — re-throw so the
+ // modal never treats the confirm as done.
+ throw error;
+ }
+ },
+ });
+
+ return (
+ <Flexbox className={styles.root} data-widget-preview={widget.id} gap={10}>
+ <Flexbox horizontal align={'center'} gap={8} wrap={'wrap'}>
+ {version && (
+ <Tag color={publishState === 'live' ? 'success' : 'info'} size={'small'}>
+ {t(publishState === 'live' ? 'chat.preview.live' : 'chat.preview.draft', {
+ version: version.version,
+ })}
+ </Tag>
+ )}
+ <Text fontSize={12} type={'secondary'}>
+ {[t(`run.status.${run.status}`), formatDuration(run.durationMs)]
+ .filter(Boolean)
+ .join(' · ')}
+ </Text>
+ <Flexbox flex={1} />
+ <Button
+ data-widget-open-portal
+ icon={PanelRightOpenIcon}
+ size={'small'}
+ type={'text'}
+ onClick={() => openDashboardWidget(widget.id, run.id)}
+ >
+ {t('chat.openDetail')}
+ </Button>
+ </Flexbox>
+
+ <div style={{ height: CARD_HEIGHT[outputType] ?? 200 }}>
+ <WidgetCard view={version?.view} widget={preview} />
+ </div>
+
+ <Flexbox className={styles.definition} gap={2}>
+ <Text fontSize={12} type={'secondary'} weight={500}>
+ {t('chat.definition')}
+ </Text>
+ <Text data-widget-definition fontSize={12}>
+ {widget.description || t('chat.noDefinition')}
+ </Text>
+ </Flexbox>
+
+ {publishState === 'outdated' && (
+ <Text fontSize={12} type={'warning'}>
+ {draft ? t('chat.outdated', { version: draft.version }) : t('chat.outdatedVersion')}
+ </Text>
+ )}
+
+ <Flexbox horizontal align={'center'} gap={8} wrap={'wrap'}>
+ {canPublish && publishState === 'publishable' && (
+ <Button
+ data-widget-publish
+ icon={RocketIcon}
+ loading={publishing}
+ size={'small'}
+ type={'primary'}
+ onClick={handlePublish}
+ >
+ {t('chat.publish')}
+ </Button>
+ )}
+ {canPublish && publishState === 'notReady' && (
+ <Tooltip title={t('chat.publishHint')}>
+ <Button disabled icon={RocketIcon} size={'small'}>
+ {t('chat.publish')}
+ </Button>
+ </Tooltip>
+ )}
+ <AddToDashboardButton
+ placedIds={dashboards.map((dashboard) => dashboard.id)}
+ projectId={widget.projectId}
+ widgetId={widget.id}
+ />
+ {!isMobile &&
+ dashboards.map((dashboard) => (
+ <Button
+ data-widget-dashboard-link={dashboard.id}
+ icon={ArrowUpRightIcon}
+ key={dashboard.id}
+ size={'small'}
+ type={'text'}
+ onClick={() => navigate(getDashboardPath(dashboard))}
+ >
+ {t('chat.onDashboard', { title: dashboard.title })}
+ </Button>
+ ))}
+ </Flexbox>
+ </Flexbox>
+ );
+});
+
+WidgetPreviewBody.displayName = 'DashboardWidgetPreviewBody';
+
+interface WidgetPreviewCardProps {
+ /** The dry run to show. */
+ runId: string;
+ widgetId: string;
+}
+
+/** Loads a widget and one of its dry runs, then renders the preview. */
+const WidgetPreviewCard = memo<WidgetPreviewCardProps>(({ widgetId, runId }) => {
+ const { t } = useTranslation('dashboard');
+ const useFetchWidgetDetail = useDashboardStore((s) => s.useFetchWidgetDetail);
+ const useFetchWidgetRun = useDashboardStore((s) => s.useFetchWidgetRun);
+ const widgetRequest = useFetchWidgetDetail(widgetId);
+ const runRequest = useFetchWidgetRun(widgetId, runId);
+ const widget = useDashboardStore(dashboardSelectors.widgetDetail(widgetId));
+ const run = useDashboardStore(dashboardSelectors.widgetRunDetail(runId));
+
+ if (widgetRequest.error || runRequest.error) {
+ return (
+ <Flexbox horizontal align={'center'} className={styles.root} gap={6}>
+ <Icon color={cssVar.colorTextTertiary} icon={RocketIcon} size={14} />
+ <Text fontSize={12} type={'secondary'}>
+ {t('chat.unavailable')}
+ </Text>
+ </Flexbox>
+ );
+ }
+ if (!widget || !run) {
+ return (
+ <Flexbox className={styles.root} gap={10}>
+ <Skeleton height={150} width={'100%'} />
+ <Skeleton.Text rows={2} />
+ </Flexbox>
+ );
+ }
+
+ return <WidgetPreviewBody run={run} widget={widget} />;
+});
+
+WidgetPreviewCard.displayName = 'DashboardWidgetPreviewCard';
+
+/**
+ * A version's successful dry run — e.g. the one a publish approval was based
+ * on. Fetched by version, not from the newest-run window, so the card keeps
+ * its body after the widget's run history rolls past the approval.
+ */
+export const WidgetVersionPreviewCard = memo<{ versionId: string; widgetId: string }>(
+ ({ widgetId, versionId }) => {
+ const useFetchWidgetDetail = useDashboardStore((s) => s.useFetchWidgetDetail);
+ const useFetchWidgetVersionPreviewRun = useDashboardStore(
+ (s) => s.useFetchWidgetVersionPreviewRun,
+ );
+ useFetchWidgetDetail(widgetId);
+ const { data: run } = useFetchWidgetVersionPreviewRun(widgetId, versionId);
+ const widget = useDashboardStore(dashboardSelectors.widgetDetail(widgetId));
+
+ if (!widget || !run) return null;
+ return <WidgetPreviewBody run={run} widget={widget} />;
+ },
+);
+
+WidgetVersionPreviewCard.displayName = 'DashboardWidgetVersionPreviewCard';
+
+export default WidgetPreviewCard;
diff --git a/src/features/Dashboard/WidgetPreview/previewWidget.test.ts b/src/features/Dashboard/WidgetPreview/previewWidget.test.ts
new file mode 100644
index 00000000000..0e4d5f36df7
--- /dev/null
+++ b/src/features/Dashboard/WidgetPreview/previewWidget.test.ts
@@ -0,0 +1,252 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ canCreateDashboardFromPreview,
+ canPreviewPublish,
+ defaultDiffPair,
+ findSucceededPreviewRun,
+ getPreviewPublishState,
+ placeableDashboards,
+ placementBoards,
+ resolvePublishSchedule,
+ toPreviewWidget,
+} from './previewWidget';
+
+const widget = {
+ draftVersionId: 'v2',
+ id: 'w1',
+ latestOutput: { type: 'stat', value: 1 },
+ latestOutputAt: '2026-01-01T00:00:00Z',
+ nextRunAt: '2026-01-01T01:00:00Z',
+ publishedVersionId: 'v1',
+ schedulePattern: '0 * * * *',
+} as any;
+
+describe('toPreviewWidget', () => {
+ it('shows the dry run instead of the live snapshot', () => {
+ const preview = toPreviewWidget(widget, {
+ error: null,
+ finishedAt: '2026-02-02T00:00:00Z',
+ output: { type: 'stat', value: 42 },
+ startedAt: '2026-02-02T00:00:00Z',
+ status: 'succeeded',
+ versionId: 'v2',
+ } as any);
+
+ expect(preview.latestOutput).toEqual({ type: 'stat', value: 42 });
+ expect(preview.lastRunStatus).toBe('succeeded');
+ // A preview is not late for a schedule.
+ expect(preview.schedulePattern).toBeNull();
+ });
+
+ it('never shows the live value as the result of a failed dry run', () => {
+ const preview = toPreviewWidget(widget, {
+ error: { code: 'NON_ZERO_EXIT', message: 'boom' },
+ finishedAt: null,
+ output: null,
+ startedAt: '2026-02-02T00:00:00Z',
+ status: 'failed',
+ versionId: 'v2',
+ } as any);
+
+ expect(preview.latestOutput).toBeNull();
+ expect(preview.lastRunError).toEqual({ code: 'NON_ZERO_EXIT', message: 'boom' });
+ });
+
+ it('shows a partial dry run, whose output is usable', () => {
+ const output = { meta: { complete: false }, type: 'stat', value: 3 };
+ const preview = toPreviewWidget(widget, {
+ error: null,
+ finishedAt: '2026-02-02T00:00:00Z',
+ output,
+ startedAt: '2026-02-02T00:00:00Z',
+ status: 'partial',
+ versionId: 'v2',
+ } as any);
+
+ expect(preview.latestOutput).toEqual(output);
+ });
+});
+
+describe('getPreviewPublishState', () => {
+ it('offers publishing only for a successful run of the current draft', () => {
+ expect(getPreviewPublishState(widget, { status: 'succeeded', versionId: 'v2' })).toBe(
+ 'publishable',
+ );
+ expect(getPreviewPublishState(widget, { status: 'failed', versionId: 'v2' })).toBe('notReady');
+ // An incomplete result is still usable output, and the server publishes it.
+ expect(getPreviewPublishState(widget, { status: 'partial', versionId: 'v2' })).toBe(
+ 'publishable',
+ );
+ expect(getPreviewPublishState(widget, { status: 'succeeded', versionId: 'v0' })).toBe(
+ 'outdated',
+ );
+ expect(getPreviewPublishState(widget, { status: 'succeeded', versionId: 'v1' })).toBe('live');
+ });
+
+ it('marks a preview of an archived version outdated once nothing points at it', () => {
+ // v1 and v2 went live and the draft is gone: reopening v1's successful
+ // preview must not offer publishing it — the server would accept the
+ // archived version and silently roll the widget back.
+ const rolled = { draftVersionId: null, publishedVersionId: 'v2' };
+ expect(getPreviewPublishState(rolled, { status: 'succeeded', versionId: 'v1' })).toBe(
+ 'outdated',
+ );
+ expect(getPreviewPublishState(rolled, { status: 'succeeded', versionId: 'v2' })).toBe('live');
+ expect(
+ getPreviewPublishState(
+ { draftVersionId: null, publishedVersionId: null },
+ { status: 'succeeded', versionId: 'v1' },
+ ),
+ ).toBe('outdated');
+ });
+});
+
+describe('canPreviewPublish', () => {
+ const widget = { userId: 'u-creator' };
+
+ it('offers publishing to the widget creator', () => {
+ expect(canPreviewPublish(widget, 'u-creator')).toBe(true);
+ });
+
+ it('hides publishing from everyone else, so teammates never hit a guaranteed failure', () => {
+ expect(canPreviewPublish(widget, 'u-member')).toBe(false);
+ expect(canPreviewPublish(widget, null)).toBe(false);
+ expect(canPreviewPublish(widget, undefined)).toBe(false);
+ });
+});
+
+describe('canCreateDashboardFromPreview', () => {
+ it('always offers creation in personal mode', () => {
+ expect(canCreateDashboardFromPreview(null, false)).toBe(true);
+ expect(canCreateDashboardFromPreview(undefined, false)).toBe(true);
+ expect(canCreateDashboardFromPreview('p1', false)).toBe(true);
+ });
+
+ it('hides creation for a project-less widget inside a workspace', () => {
+ // The board would land on the workspace home level, whose /dashboard
+ // routes are disabled there — nothing could open it.
+ expect(canCreateDashboardFromPreview(null, true)).toBe(false);
+ expect(canCreateDashboardFromPreview(undefined, true)).toBe(false);
+ // A project widget still creates inside its project, where routes exist.
+ expect(canCreateDashboardFromPreview('p1', true)).toBe(true);
+ });
+});
+
+describe('placementBoards', () => {
+ const home = [
+ { agentId: null, id: 'h1', projectId: null },
+ { agentId: null, id: 'h2', projectId: null },
+ ];
+ const project = [
+ { agentId: null, id: 'p1', projectId: 'prj' },
+ { agentId: null, id: 'p2', projectId: 'prj' },
+ ];
+
+ it('lists the widget’s project boards ahead of the home boards', () => {
+ expect(placementBoards(home, project, 'prj')).toEqual([
+ project[0],
+ project[1],
+ home[0],
+ home[1],
+ ]);
+ expect(placementBoards(home, project, null)).toEqual(home);
+ expect(placementBoards(home, project, undefined)).toEqual(home);
+ });
+
+ it('offers no workspace-root boards while a workspace is active', () => {
+ const agentLevel = { agentId: 'ag1', id: 'a1', projectId: null };
+ // Workspace-root boards have no UI inside a workspace — the home level
+ // contributes only boards that live under a project or an agent.
+ expect(placementBoards([...home, agentLevel], [], undefined, true)).toEqual([agentLevel]);
+ expect(placementBoards(home, [], null, true)).toEqual([]);
+ // Personal mode keeps the home route, and project widgets keep their
+ // project boards in both modes.
+ expect(placementBoards(home, [], undefined, false)).toEqual(home);
+ expect(placementBoards(home, project, 'prj', true)).toEqual(project);
+ });
+});
+
+describe('placeableDashboards', () => {
+ const boards = [
+ { id: 'd1', title: 'Mine', userId: 'u-member' },
+ { id: 'd2', title: 'Teammate public', userId: 'u-owner' },
+ ];
+
+ it('offers only the caller’s own boards — placement writes as the board’s creator', () => {
+ expect(placeableDashboards(boards, 'u-member')).toEqual([boards[0]]);
+ expect(placeableDashboards(boards, 'u-owner')).toEqual([boards[1]]);
+ });
+
+ it('offers nothing while the current user is unknown', () => {
+ expect(placeableDashboards(boards, undefined)).toEqual([]);
+ expect(placeableDashboards(boards, null)).toEqual([]);
+ });
+});
+
+describe('resolvePublishSchedule', () => {
+ const manifest = { schedule: { pattern: '0 6 * * *', timezone: 'Asia/Shanghai' } };
+
+ it('keeps the widget’s own schedule when the version suggests another', () => {
+ // What makeLive persists: the persisted cadence wins, never the suggestion.
+ expect(
+ resolvePublishSchedule({ schedulePattern: '0 * * * *', scheduleTimezone: 'UTC' }, manifest),
+ ).toEqual({ pattern: '0 * * * *', timezone: 'UTC' });
+ });
+
+ it('adopts a valid manifest suggestion only when the widget has no schedule', () => {
+ expect(
+ resolvePublishSchedule({ schedulePattern: null, scheduleTimezone: null }, manifest),
+ ).toEqual({ pattern: '0 6 * * *', timezone: 'Asia/Shanghai' });
+ expect(
+ resolvePublishSchedule({ schedulePattern: '', scheduleTimezone: null }, manifest),
+ ).toEqual({ pattern: '0 6 * * *', timezone: 'Asia/Shanghai' });
+ });
+
+ it('resolves to no schedule without a persisted one and without a valid suggestion', () => {
+ expect(
+ resolvePublishSchedule(
+ { schedulePattern: null, scheduleTimezone: null },
+ { schedule: { pattern: 'not a cron' } },
+ ),
+ ).toEqual({});
+ expect(resolvePublishSchedule({ schedulePattern: null, scheduleTimezone: null }, null)).toEqual(
+ {},
+ );
+ expect(resolvePublishSchedule({ schedulePattern: null, scheduleTimezone: null }, {})).toEqual(
+ {},
+ );
+ });
+});
+
+describe('findSucceededPreviewRun', () => {
+ it('picks the newest successful dry run of that version', () => {
+ const runs = [
+ { id: 'r4', status: 'succeeded', trigger: 'manual', versionId: 'v2' },
+ { id: 'r3', status: 'failed', trigger: 'preview', versionId: 'v2' },
+ { id: 'r2', status: 'succeeded', trigger: 'preview', versionId: 'v2' },
+ { id: 'r1', status: 'succeeded', trigger: 'preview', versionId: 'v2' },
+ ] as any[];
+ expect(findSucceededPreviewRun(runs, 'v2')?.id).toBe('r2');
+ expect(findSucceededPreviewRun(runs, 'v9')).toBeUndefined();
+ expect(findSucceededPreviewRun(runs, undefined)).toBeUndefined();
+ });
+});
+
+describe('defaultDiffPair', () => {
+ const versions = [
+ { id: 'v3', parentVersionId: 'v2', status: 'draft' as const },
+ { id: 'v2', parentVersionId: 'v1', status: 'published' as const },
+ { id: 'v1', parentVersionId: null, status: 'archived' as const },
+ ];
+
+ it('compares the reviewed version against the live one', () => {
+ expect(defaultDiffPair(versions, 'v3')).toEqual({ baseId: 'v2', targetId: 'v3' });
+ });
+
+ it('falls back to the parent (or the previous version) for the live version itself', () => {
+ expect(defaultDiffPair(versions, 'v2')).toEqual({ baseId: 'v1', targetId: 'v2' });
+ expect(defaultDiffPair(versions)).toEqual({ baseId: 'v2', targetId: 'v3' });
+ expect(defaultDiffPair([])).toEqual({});
+ });
+});
diff --git a/src/features/Dashboard/WidgetPreview/previewWidget.ts b/src/features/Dashboard/WidgetPreview/previewWidget.ts
new file mode 100644
index 00000000000..9def2c8cdbb
--- /dev/null
+++ b/src/features/Dashboard/WidgetPreview/previewWidget.ts
@@ -0,0 +1,169 @@
+import type { WidgetManifest } from '@lobechat/types';
+import { validateCronPattern } from '@lobechat/utils/cronEval';
+
+import type {
+ DashboardWidgetDetail,
+ DashboardWidgetRunItem,
+ DashboardWidgetVersionItem,
+} from '@/services/dashboard';
+
+import { isUsableRunStatus } from '../utils/widgetHealth';
+
+type PreviewRun = Pick<
+ DashboardWidgetRunItem,
+ 'error' | 'finishedAt' | 'output' | 'startedAt' | 'status' | 'versionId'
+>;
+
+/**
+ * The card model for one dry run: the widget row with that run's result in
+ * place of its live snapshot. A preview never touches `latestOutput`, so the
+ * card would otherwise show the (possibly empty) live state instead of what
+ * the agent just tried.
+ */
+export const toPreviewWidget = (widget: DashboardWidgetDetail, run: PreviewRun) => ({
+ ...widget,
+ lastRunAt: run.startedAt,
+ lastRunError: run.error,
+ lastRunStatus: run.status,
+ latestOutput: isUsableRunStatus(run.status) ? run.output : null,
+ latestOutputAt: isUsableRunStatus(run.status) ? run.finishedAt : null,
+ // Stale / next-run judgement belongs to the live widget, not to a one-off preview.
+ nextRunAt: null,
+ schedulePattern: null,
+});
+
+/** The most recent usable (succeeded or partial) dry run of a version, from a newest-first run list. */
+export const findSucceededPreviewRun = <T extends PreviewRun & { trigger: string }>(
+ runs: T[],
+ versionId?: string,
+) =>
+ versionId
+ ? runs.find(
+ (run) =>
+ run.versionId === versionId && run.trigger === 'preview' && isUsableRunStatus(run.status),
+ )
+ : undefined;
+
+export type PreviewPublishState =
+ /** This run's version is live. */
+ | 'live'
+ /** The run succeeded and its version can be published. */
+ | 'publishable'
+ /** The run did not succeed (yet); nothing to publish. */
+ | 'notReady'
+ /** Not the current draft; publishing it would roll the widget back. */
+ | 'outdated';
+
+/**
+ * What the preview card offers for a dry run of `run.versionId`. Only the
+ * current draft is publishable: any other version — a superseded draft or an
+ * archived one — would silently roll the widget back to code the user never
+ * approved as a release, so it reads as outdated history.
+ */
+export const getPreviewPublishState = (
+ widget: Pick<DashboardWidgetDetail, 'draftVersionId' | 'publishedVersionId'>,
+ run: Pick<PreviewRun, 'status' | 'versionId'>,
+): PreviewPublishState => {
+ if (widget.publishedVersionId === run.versionId) return 'live';
+ if (widget.draftVersionId !== run.versionId) return 'outdated';
+ return isUsableRunStatus(run.status) ? 'publishable' : 'notReady';
+};
+
+/**
+ * Whether the preview may offer publishing at all. Publishing goes through
+ * `WidgetService.publish`, which refuses everyone but the widget's creator —
+ * a teammate reading a public widget would only meet a guaranteed failure, so
+ * the action stays hidden from them. False until the current user is known.
+ */
+export const canPreviewPublish = (
+ widget: Pick<DashboardWidgetDetail, 'userId'>,
+ currentUserId?: string | null,
+): boolean => !!currentUserId && currentUserId === widget.userId;
+
+/**
+ * Boards offered as placement targets from a widget preview. Placing writes
+ * through `DashboardModel.addItem`, which only the board's creator can
+ * perform — in a workspace the readable list includes teammates' public
+ * boards, and offering them only ends in a refused write. While the current
+ * user is unknown (profile still loading) nothing is offered.
+ */
+export const placeableDashboards = <T extends { userId: string }>(
+ dashboards: T[],
+ currentUserId?: string | null,
+): T[] =>
+ currentUserId ? dashboards.filter((dashboard) => dashboard.userId === currentUserId) : [];
+
+/**
+ * Whether a widget preview may offer creating a new board. Creating lands on
+ * the widget's own level, and inside a workspace the home level has no UI at
+ * all — the home dashboard routes are disabled there — so a widget that lives
+ * outside a project gets no creation action; the board it would create could
+ * not be opened. Personal mode (no active workspace) can always create.
+ */
+export const canCreateDashboardFromPreview = (
+ projectId: string | null | undefined,
+ workspaceActive: boolean,
+): boolean => !workspaceActive || !!projectId;
+
+/**
+ * The boards a widget preview loads as placement candidates: the home
+ * level's boards, plus — for a widget that lives in a project — that
+ * project's boards, project first. The widget can be placed on either level
+ * (the dashboard tool scopes placements to exactly this set), so hiding the
+ * project's boards would lose real targets.
+ *
+ * While a workspace is active, workspace-root boards (no project, no agent)
+ * have no UI — the home routes are disabled there — so the home level
+ * offers nothing; in personal mode the home route works and stays listed.
+ */
+export const placementBoards = <T extends { agentId?: string | null; projectId?: string | null }>(
+ homeBoards: T[],
+ projectBoards: T[],
+ projectId?: string | null,
+ workspaceActive = false,
+): T[] => {
+ const home = workspaceActive
+ ? homeBoards.filter((board) => board.agentId != null || board.projectId != null)
+ : homeBoards;
+ return projectId ? [...projectBoards, ...home] : home;
+};
+
+/** Versions to compare by default: the one under review against the live one (or its parent). */
+export const defaultDiffPair = (
+ versions: Pick<DashboardWidgetVersionItem, 'id' | 'parentVersionId' | 'status'>[],
+ targetId?: string,
+): { baseId?: string; targetId?: string } => {
+ const target = versions.find((v) => v.id === targetId) ?? versions[0];
+ if (!target) return {};
+ const live = versions.find((v) => v.status === 'published' && v.id !== target.id);
+ const base =
+ live ??
+ versions.find((v) => v.id === target.parentVersionId) ??
+ versions[versions.indexOf(target) + 1];
+ return { baseId: base?.id, targetId: target.id };
+};
+
+/**
+ * The schedule that will actually be on the widget after the version under
+ * review goes live — exactly what `WidgetService.makeLive` persists: the
+ * widget's own schedule wins, and only a widget without one adopts the
+ * manifest's suggestion (when the pattern is valid). The review must show
+ * this, not the raw manifest suggestion, or the approver signs off a cadence
+ * the publish does not retain.
+ */
+export const resolvePublishSchedule = (
+ widget: Pick<DashboardWidgetDetail, 'schedulePattern' | 'scheduleTimezone'>,
+ manifest?: Pick<WidgetManifest, 'schedule'> | null,
+): { pattern?: string; timezone?: string | null } => {
+ if (widget.schedulePattern) {
+ return { pattern: widget.schedulePattern, timezone: widget.scheduleTimezone };
+ }
+ const suggested = manifest?.schedule;
+ if (
+ suggested?.pattern &&
+ validateCronPattern(suggested.pattern, suggested.timezone ?? null).valid
+ ) {
+ return { pattern: suggested.pattern, timezone: suggested.timezone ?? null };
+ }
+ return {};
+};
diff --git a/src/features/Dashboard/WidgetPreview/useWidgetReview.test.ts b/src/features/Dashboard/WidgetPreview/useWidgetReview.test.ts
new file mode 100644
index 00000000000..3f986def232
--- /dev/null
+++ b/src/features/Dashboard/WidgetPreview/useWidgetReview.test.ts
@@ -0,0 +1,210 @@
+/**
+ * @vitest-environment happy-dom
+ */
+import { act, renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useDashboardStore } from '@/store/dashboard';
+import { initialState } from '@/store/dashboard/initialState';
+
+import { useWidgetReview } from './useWidgetReview';
+
+interface FakeResponse {
+ data?: unknown;
+ error?: unknown;
+ isValidating?: boolean;
+}
+
+/**
+ * Replica sync responses by resource name: `widgetDetail` / `widgetVersions` /
+ * `widgetPreviewRun`. The store reaches them through `useSync`, so the mock
+ * answers both the hydration read and the sync of each entry.
+ */
+const state = vi.hoisted(() => ({
+ /** Per-resource revalidate spy: `useSync().mutate()` is what `retry` calls. */
+ mutates: new Map<string, ReturnType<typeof vi.fn>>(),
+ responses: new Map<string, FakeResponse>(),
+}));
+
+vi.mock('@/libs/swr', () => ({
+ mutate: vi.fn(),
+ useClientDataSWR: (key: unknown[] | null) => {
+ if (!key) return { data: undefined, isValidating: false, mutate: vi.fn() };
+ // The persisted read completes, so the review is not stuck hydrating.
+ if (key[0] === 'replica:hydrate') {
+ return { data: true, isValidating: false, mutate: vi.fn() };
+ }
+ const name = key[1] as string;
+ if (!state.mutates.has(name)) state.mutates.set(name, vi.fn());
+ return {
+ isValidating: false,
+ mutate: state.mutates.get(name),
+ ...state.responses.get(name),
+ };
+ },
+}));
+
+const widget = { draftVersionId: 'v2', id: 'w1', title: 'Open PRs' } as any;
+const versions = [
+ { id: 'v1', status: 'published', version: 1 },
+ { id: 'v2', status: 'draft', version: 2 },
+] as any[];
+
+const respond = (resource: string, response: FakeResponse) =>
+ state.responses.set(resource, response);
+
+/** The replica projections a settled review reads, filled as `replace` would. */
+const loadAll = (patch: Record<string, unknown> = {}) => {
+ useDashboardStore.setState({
+ widgetDetailMap: { w1: widget },
+ widgetVersionsMap: { w1: versions },
+ ...patch,
+ });
+};
+
+beforeEach(() => {
+ state.responses.clear();
+ state.mutates.clear();
+ vi.clearAllMocks();
+ useDashboardStore.setState(initialState);
+});
+
+describe('useWidgetReview', () => {
+ it('reports a failed load as an error, holds approval, and retries every request', () => {
+ respond('widgetDetail', { error: new Error('500') });
+ respond('widgetVersions', { data: versions });
+ const onApprovalBlockedChange = vi.fn();
+
+ const { result } = renderHook(() => useWidgetReview('w1', 'v2', { onApprovalBlockedChange }));
+
+ expect(result.current.status).toBe('error');
+ expect(result.current.error).toEqual(new Error('500'));
+ expect(onApprovalBlockedChange).toHaveBeenLastCalledWith(true);
+
+ act(() => result.current.retry());
+ // Every review request is revalidated through its own replica slice.
+ expect(state.mutates.get('widgetDetail')).toHaveBeenCalled();
+ expect(state.mutates.get('widgetVersions')).toHaveBeenCalled();
+ });
+
+ it('holds approval while loading, including a retry in flight after a failure', () => {
+ respond('widgetDetail', { error: new Error('500'), isValidating: true });
+ respond('widgetVersions', { isValidating: true });
+ const onApprovalBlockedChange = vi.fn();
+
+ const { result } = renderHook(() => useWidgetReview('w1', 'v2', { onApprovalBlockedChange }));
+
+ expect(result.current.status).toBe('loading');
+ expect(onApprovalBlockedChange).toHaveBeenLastCalledWith(true);
+ });
+
+ it('releases approval once the pinned version is loaded', () => {
+ loadAll();
+ const onApprovalBlockedChange = vi.fn();
+
+ const { result } = renderHook(() => useWidgetReview('w1', 'v2', { onApprovalBlockedChange }));
+
+ expect(result.current.status).toBe('ready');
+ expect(result.current.target).toMatchObject({ id: 'v2' });
+ expect(onApprovalBlockedChange).toHaveBeenLastCalledWith(false);
+ });
+
+ it('keeps approval held until the shown draft is pinned into the request', () => {
+ loadAll();
+ const onApprovalBlockedChange = vi.fn();
+ const onPinVersion = vi.fn();
+
+ const { result, rerender } = renderHook(
+ ({ versionId }: { versionId?: string }) =>
+ useWidgetReview('w1', versionId, { onApprovalBlockedChange, onPinVersion }),
+ { initialProps: {} },
+ );
+
+ expect(result.current.status).toBe('pinning');
+ expect(onPinVersion).toHaveBeenCalledWith('v2');
+ expect(onApprovalBlockedChange).toHaveBeenLastCalledWith(true);
+
+ rerender({ versionId: 'v2' });
+ expect(result.current.status).toBe('ready');
+ expect(onApprovalBlockedChange).toHaveBeenLastCalledWith(false);
+ });
+
+ it('holds approval when the requested version is not among the loaded ones', () => {
+ loadAll();
+ const onApprovalBlockedChange = vi.fn();
+
+ const { result } = renderHook(() =>
+ useWidgetReview('w1', 'v-gone', { onApprovalBlockedChange }),
+ );
+
+ expect(result.current.status).toBe('missing');
+ expect(onApprovalBlockedChange).toHaveBeenLastCalledWith(true);
+ });
+
+ it('treats the preview run as part of the publish review', () => {
+ loadAll();
+ respond('widgetPreviewRun', { error: new Error('503') });
+ const onApprovalBlockedChange = vi.fn();
+
+ const { result } = renderHook(() =>
+ useWidgetReview('w1', 'v2', { onApprovalBlockedChange, withRuns: true }),
+ );
+
+ expect(result.current.status).toBe('error');
+ expect(onApprovalBlockedChange).toHaveBeenLastCalledWith(true);
+ act(() => result.current.retry());
+ expect(state.mutates.get('widgetPreviewRun')).toHaveBeenCalled();
+ });
+
+ it('loads the reviewed version’s preview by version, not the capped run list', () => {
+ // The approval-era preview no longer sits in the newest-run window; only
+ // the version-keyed entry can still see it.
+ const run = { id: 'r1', versionId: 'v2' };
+ loadAll({ widgetPreviewRunMap: { 'w1:v2': run } });
+ const onApprovalBlockedChange = vi.fn();
+
+ const { result } = renderHook(() =>
+ useWidgetReview('w1', 'v2', { onApprovalBlockedChange, withRuns: true }),
+ );
+
+ expect(result.current.status).toBe('ready');
+ expect(result.current.run).toEqual(run);
+ // A proven preview means the publish it approves will not be refused.
+ expect(onApprovalBlockedChange).toHaveBeenLastCalledWith(false);
+ });
+
+ it('holds approval when the reviewed version has no usable preview run', () => {
+ // No usable dry run of v2 — the request settles on `null`, not an error:
+ // publishing would be refused (DRY_RUN_REQUIRED), so the review renders its
+ // warning and approval stays held.
+ loadAll({ widgetPreviewRunMap: { 'w1:v2': null } });
+ const onApprovalBlockedChange = vi.fn();
+
+ const { result } = renderHook(() =>
+ useWidgetReview('w1', 'v2', { onApprovalBlockedChange, withRuns: true }),
+ );
+
+ expect(result.current.status).toBe('ready');
+ expect(result.current.run).toBeNull();
+ expect(onApprovalBlockedChange).toHaveBeenLastCalledWith(true);
+ });
+
+ it('keeps a loaded review ready through a background revalidation failure', () => {
+ loadAll();
+ respond('widgetVersions', { error: new Error('500') });
+
+ const { result } = renderHook(() => useWidgetReview('w1', 'v2'));
+
+ expect(result.current.status).toBe('ready');
+ });
+
+ it('releases the hold when the review unmounts', () => {
+ respond('widgetDetail', { error: new Error('500') });
+ const onApprovalBlockedChange = vi.fn();
+
+ const { unmount } = renderHook(() => useWidgetReview('w1', 'v2', { onApprovalBlockedChange }));
+ unmount();
+
+ expect(onApprovalBlockedChange).toHaveBeenLastCalledWith(false);
+ });
+});
diff --git a/src/features/Dashboard/WidgetPreview/useWidgetReview.ts b/src/features/Dashboard/WidgetPreview/useWidgetReview.ts
new file mode 100644
index 00000000000..0fce658de36
--- /dev/null
+++ b/src/features/Dashboard/WidgetPreview/useWidgetReview.ts
@@ -0,0 +1,124 @@
+import { useCallback, useEffect, useLayoutEffect } from 'react';
+
+import { dashboardSelectors, useDashboardStore } from '@/store/dashboard';
+
+/**
+ * - `loading` — a review request has not settled yet (first load or a retry);
+ * - `error` — a review request failed with nothing loaded to show;
+ * - `missing` — everything loaded, but the version under review is not there;
+ * - `pinning` — the review is on screen; its version is being written into the request;
+ * - `ready` — the exact version that approval acts on is on screen.
+ */
+export type WidgetReviewStatus = 'error' | 'loading' | 'missing' | 'pinning' | 'ready';
+
+interface ReviewRequest {
+ data?: unknown;
+ error?: unknown;
+ isLoading?: boolean;
+}
+
+/**
+ * Where a review stands. Settled data wins over a later background failure;
+ * loading is read before error so a retry in flight shows progress.
+ */
+export const resolveWidgetReviewStatus = ({
+ hasTarget,
+ pinned,
+ requests,
+}: {
+ hasTarget: boolean;
+ pinned: boolean;
+ requests: ReviewRequest[];
+}): WidgetReviewStatus => {
+ const settled = requests.every((request) => request.data !== undefined);
+ if (settled) {
+ if (!hasTarget) return 'missing';
+ return pinned ? 'ready' : 'pinning';
+ }
+ if (requests.some((request) => request.data === undefined && request.isLoading)) return 'loading';
+ if (requests.some((request) => request.data === undefined && request.error)) return 'error';
+ return 'loading';
+};
+
+interface UseWidgetReviewOptions {
+ /**
+ * Told whether approval must wait: blocked until the version approval acts
+ * on is loaded, shown and pinned into the request.
+ */
+ onApprovalBlockedChange?: (blocked: boolean) => void;
+ /**
+ * Called once with the version shown when the request named none, so the
+ * caller can persist it into the request.
+ */
+ onPinVersion?: (versionId: string) => void;
+ /** Also load the widget's runs (the publish review shows its latest dry run). */
+ withRuns?: boolean;
+}
+
+/**
+ * Loads what an approval card reviews — the widget and the exact version that
+ * will run or go live — and reports whether approval may proceed. Failures
+ * surface as `error` with a retry instead of an endless skeleton.
+ */
+export const useWidgetReview = (
+ widgetId: string,
+ versionId: string | undefined,
+ { onApprovalBlockedChange, onPinVersion, withRuns = false }: UseWidgetReviewOptions = {},
+) => {
+ const useFetchWidgetDetail = useDashboardStore((s) => s.useFetchWidgetDetail);
+ const useFetchWidgetVersions = useDashboardStore((s) => s.useFetchWidgetVersions);
+ const useFetchWidgetVersionPreviewRun = useDashboardStore(
+ (s) => s.useFetchWidgetVersionPreviewRun,
+ );
+ const detailRequest = useFetchWidgetDetail(widgetId);
+ const versionsRequest = useFetchWidgetVersions(widgetId);
+ const widget = useDashboardStore(dashboardSelectors.widgetDetail(widgetId));
+ const versions = useDashboardStore(dashboardSelectors.widgetVersions(widgetId));
+
+ const targetId = versionId ?? widget?.draftVersionId ?? undefined;
+ const target = versions.find((version) => version.id === targetId);
+ // Keyed by version, not the newest-N run list: a long-pending approval
+ // keeps its preview after later runs push it out of the capped list.
+ const previewRunRequest = useFetchWidgetVersionPreviewRun(
+ withRuns ? widgetId : undefined,
+ withRuns ? targetId : undefined,
+ );
+
+ const requests = withRuns
+ ? [detailRequest, versionsRequest, previewRunRequest]
+ : [detailRequest, versionsRequest];
+ const status = resolveWidgetReviewStatus({
+ hasTarget: !!widget && !!target,
+ pinned: !!versionId,
+ requests,
+ });
+ const error = requests.find((request) => request.data === undefined && request.error)?.error;
+
+ const unpinnedTargetId = versionId ? undefined : target?.id;
+ useEffect(() => {
+ if (unpinnedTargetId) onPinVersion?.(unpinnedTargetId);
+ }, [unpinnedTargetId, onPinVersion]);
+
+ // Layout effect: the host's approve action is held before the first paint,
+ // so it is never clickable while nothing has been reviewed. A publish
+ // review is exactly what approval acts on — a version with no usable
+ // preview run would be refused by the publish flow (DRY_RUN_REQUIRED), so
+ // approval stays held until a successful dry run of this version exists.
+ const hasUsablePreview = !withRuns || !!previewRunRequest.data;
+ const blocked = status !== 'ready' || !hasUsablePreview;
+ useLayoutEffect(() => {
+ onApprovalBlockedChange?.(blocked);
+ }, [blocked, onApprovalBlockedChange]);
+ useLayoutEffect(() => () => onApprovalBlockedChange?.(false), [onApprovalBlockedChange]);
+
+ const { mutate: retryDetail } = detailRequest;
+ const { mutate: retryVersions } = versionsRequest;
+ const { mutate: retryPreviewRun } = previewRunRequest;
+ const retry = useCallback(() => {
+ void retryDetail();
+ void retryVersions();
+ if (withRuns) void retryPreviewRun();
+ }, [retryDetail, retryPreviewRun, retryVersions, withRuns]);
+
+ return { error, retry, run: previewRunRequest.data, status, target, versions, widget };
+};
diff --git a/src/features/Dashboard/WidgetRefreshButton.tsx b/src/features/Dashboard/WidgetRefreshButton.tsx
new file mode 100644
index 00000000000..fb2a533e525
--- /dev/null
+++ b/src/features/Dashboard/WidgetRefreshButton.tsx
@@ -0,0 +1,60 @@
+'use client';
+
+import { ActionIcon, toast } from '@lobehub/ui/base-ui';
+import { RefreshCwIcon } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { usePermission } from '@/hooks/usePermission';
+import type { DashboardWidgetItem } from '@/services/dashboard';
+import { dashboardSelectors, useDashboardStore } from '@/store/dashboard';
+
+import { isUsableRunStatus } from './utils/widgetHealth';
+
+/**
+ * Run the widget's published version now. Hidden until a version is published —
+ * there is nothing to run before that, and hidden entirely without the
+ * create_content permission — refreshing is a write the server refuses for
+ * workspace viewers.
+ */
+const WidgetRefreshButton = memo<{ widget: DashboardWidgetItem }>(({ widget }) => {
+ const { t } = useTranslation('dashboard');
+ const runWidget = useDashboardStore((s) => s.runWidget);
+ const running = useDashboardStore(dashboardSelectors.isWidgetRunning(widget.id));
+ const { allowed } = usePermission('create_content');
+
+ if (!widget.publishedVersionId || !allowed) return null;
+
+ const handleRefresh = async () => {
+ try {
+ const run = await runWidget(widget.id);
+ if (run && !isUsableRunStatus(run.status)) {
+ toast.error(
+ t('widget.refresh.failed', {
+ message: run.error?.message ?? t(`run.status.${run.status}`),
+ }),
+ );
+ }
+ } catch (error) {
+ toast.error(
+ t('widget.refresh.failed', { message: error instanceof Error ? error.message : '' }),
+ );
+ }
+ };
+
+ return (
+ <ActionIcon
+ data-widget-refresh
+ aria-label={t('widget.refresh.action')}
+ icon={RefreshCwIcon}
+ loading={running || widget.lastRunStatus === 'running'}
+ size={'small'}
+ title={t('widget.refresh.action')}
+ onClick={() => void handleRefresh()}
+ />
+ );
+});
+
+WidgetRefreshButton.displayName = 'DashboardWidgetRefreshButton';
+
+export default WidgetRefreshButton;
diff --git a/src/features/Dashboard/hooks/useDashboardFeature.test.ts b/src/features/Dashboard/hooks/useDashboardFeature.test.ts
new file mode 100644
index 00000000000..b99ef0249c3
--- /dev/null
+++ b/src/features/Dashboard/hooks/useDashboardFeature.test.ts
@@ -0,0 +1,56 @@
+import { renderHook } from '@testing-library/react';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const mocks = vi.hoisted(() => ({
+ activeWorkspaceSlug: null as string | null,
+ enableDashboard: true,
+ serverConfigInit: true,
+}));
+
+const ENABLE_DASHBOARD = 'enableDashboard';
+vi.mock('@/store/serverConfig', () => ({
+ serverConfigSelectors: { enableDashboard: ENABLE_DASHBOARD },
+ useServerConfigStore: (selector: unknown) =>
+ selector === ENABLE_DASHBOARD
+ ? mocks.enableDashboard
+ : (selector as (s: { serverConfigInit: boolean }) => unknown)({
+ serverConfigInit: mocks.serverConfigInit,
+ }),
+}));
+
+vi.mock('@/business/client/hooks/useActiveWorkspaceSlug', () => ({
+ useActiveWorkspaceSlug: () => mocks.activeWorkspaceSlug,
+}));
+
+describe('useHomeDashboardFeature', () => {
+ beforeEach(() => {
+ mocks.activeWorkspaceSlug = null;
+ mocks.enableDashboard = true;
+ mocks.serverConfigInit = true;
+ });
+
+ const homeDashboard = async () => {
+ const { useHomeDashboardFeature } = await import('./useDashboardFeature');
+ return renderHook(() => useHomeDashboardFeature()).result.current;
+ };
+
+ it('is on in personal mode while the flag is on', async () => {
+ expect(await homeDashboard()).toEqual({ enabled: true, ready: true });
+ });
+
+ it('is off while the flag is off', async () => {
+ mocks.enableDashboard = false;
+ expect(await homeDashboard()).toEqual({ enabled: false, ready: true });
+ });
+
+ it('is off inside a workspace even while the flag is on', async () => {
+ mocks.activeWorkspaceSlug = 'lobe-team';
+ expect(await homeDashboard()).toEqual({ enabled: false, ready: true });
+ });
+
+ it('keeps project dashboards on inside a workspace', async () => {
+ mocks.activeWorkspaceSlug = 'lobe-team';
+ const { useDashboardFeature } = await import('./useDashboardFeature');
+ expect(renderHook(() => useDashboardFeature()).result.current.enabled).toBe(true);
+ });
+});
diff --git a/src/features/Dashboard/hooks/useDashboardFeature.ts b/src/features/Dashboard/hooks/useDashboardFeature.ts
new file mode 100644
index 00000000000..8964f7d072c
--- /dev/null
+++ b/src/features/Dashboard/hooks/useDashboardFeature.ts
@@ -0,0 +1,24 @@
+import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';
+import { serverConfigSelectors, useServerConfigStore } from '@/store/serverConfig';
+
+/**
+ * The runtime flag `dashboard` (off by default) as the client sees it.
+ * `ready` is false until the server config — and so the user's flags — has
+ * loaded; surfaces should neither render nor redirect before that.
+ */
+export const useDashboardFeature = () => {
+ const ready = useServerConfigStore((s) => s.serverConfigInit);
+ const enabled = useServerConfigStore(serverConfigSelectors.enableDashboard);
+ return { enabled: ready && enabled, ready };
+};
+
+/**
+ * The home dashboard (`/dashboard`): personal boards only for now —
+ * workspace-level boards have no UI yet — so it is off inside a workspace even
+ * while the flag is on. Project dashboards use `useDashboardFeature` instead.
+ */
+export const useHomeDashboardFeature = () => {
+ const { enabled, ready } = useDashboardFeature();
+ const activeWorkspaceSlug = useActiveWorkspaceSlug();
+ return { enabled: enabled && !activeWorkspaceSlug, ready };
+};
diff --git a/src/features/Dashboard/hooks/useWidgetTrend.ts b/src/features/Dashboard/hooks/useWidgetTrend.ts
new file mode 100644
index 00000000000..990401397e7
--- /dev/null
+++ b/src/features/Dashboard/hooks/useWidgetTrend.ts
@@ -0,0 +1,12 @@
+import type { DashboardWidgetItem } from '@/services/dashboard';
+import { dashboardSelectors, useDashboardStore } from '@/store/dashboard';
+
+/**
+ * The widget's long-term trend from `metric_points`. Every card and drill-down
+ * showing the same widget shares one request through the SWR key.
+ */
+export const useWidgetTrend = (widget: DashboardWidgetItem) => {
+ const useFetchWidgetTrend = useDashboardStore((s) => s.useFetchWidgetTrend);
+ useFetchWidgetTrend(widget);
+ return useDashboardStore(dashboardSelectors.widgetTrend(widget.id));
+};
diff --git a/src/features/Dashboard/index.ts b/src/features/Dashboard/index.ts
new file mode 100644
index 00000000000..8337ebc1a13
--- /dev/null
+++ b/src/features/Dashboard/index.ts
@@ -0,0 +1,10 @@
+export { default as DashboardBoard } from './Board';
+export { default as DashboardBoardPage } from './BoardPage';
+export { default as DashboardListPage } from './List';
+export { default as DashboardListCard, dashboardListStyles } from './List/DashboardListCard';
+export { default as WidgetCard } from './WidgetCard';
+export { default as WidgetDetailDrawer, WidgetDetailPanel } from './WidgetDetail';
+export { default as WidgetRunPreview } from './WidgetDetail/RunPreview';
+export { default as DashboardWidgetGrid } from './WidgetGrid';
+export { default as WidgetPreviewCard } from './WidgetPreview';
+export { default as WidgetPublishReview } from './WidgetPreview/PublishReview';
diff --git a/src/features/Dashboard/pageStyles.ts b/src/features/Dashboard/pageStyles.ts
new file mode 100644
index 00000000000..1785d2ca5cd
--- /dev/null
+++ b/src/features/Dashboard/pageStyles.ts
@@ -0,0 +1,58 @@
+import { createStaticStyles } from 'antd-style';
+
+/**
+ * Page chrome shared by the dashboard pages (board list, one board, a
+ * project's dashboards): a wide canvas — a board is read at a glance, so it
+ * gets the width the chat column does not need — and one heading scale.
+ */
+export const dashboardPageStyles = createStaticStyles(({ css, cssVar, responsive }) => ({
+ canvas: css`
+ display: flex;
+ flex-direction: column;
+ gap: 24px;
+
+ width: 100%;
+ max-width: 1440px;
+ margin-inline: auto;
+ padding-block: 24px 48px;
+ padding-inline: 32px;
+
+ ${responsive.sm} {
+ gap: 16px;
+ padding-block: 16px 32px;
+ padding-inline: 16px;
+ }
+ `,
+ description: css`
+ max-width: 72ch;
+ color: ${cssVar.colorTextSecondary};
+ `,
+ heading: css`
+ ${responsive.sm} {
+ flex-direction: column;
+ align-items: stretch;
+ }
+ `,
+ scroll: css`
+ overflow-y: auto;
+ flex: 1;
+ min-height: 0;
+ `,
+ sectionTitle: css`
+ margin: 0;
+
+ font-size: 15px;
+ font-weight: 600;
+ line-height: 1.4;
+ color: ${cssVar.colorText};
+ `,
+ title: css`
+ margin: 0;
+
+ font-size: 22px;
+ font-weight: 600;
+ line-height: 1.3;
+ color: ${cssVar.colorText};
+ letter-spacing: -0.01em;
+ `,
+}));
diff --git a/src/features/Dashboard/routeMeta.ts b/src/features/Dashboard/routeMeta.ts
new file mode 100644
index 00000000000..f69d2d0cefa
--- /dev/null
+++ b/src/features/Dashboard/routeMeta.ts
@@ -0,0 +1,16 @@
+import { LayoutDashboardIcon } from 'lucide-react';
+
+import { createSurfaceSkeleton } from '@/components/Skeleton/Surface';
+import { routeMeta } from '@/spa/router/routeMeta';
+
+export const dashboardsRouteMeta = routeMeta({
+ icon: LayoutDashboardIcon,
+ Skeleton: createSurfaceSkeleton('grid'),
+ titleKey: 'navigation.dashboard',
+});
+
+export const dashboardRouteMeta = routeMeta({
+ icon: LayoutDashboardIcon,
+ Skeleton: createSurfaceSkeleton('grid'),
+ titleKey: 'navigation.dashboard',
+});
diff --git a/src/features/Dashboard/utils/format.test.ts b/src/features/Dashboard/utils/format.test.ts
new file mode 100644
index 00000000000..3d527e5f22e
--- /dev/null
+++ b/src/features/Dashboard/utils/format.test.ts
@@ -0,0 +1,35 @@
+import { describe, expect, it } from 'vitest';
+
+import { formatDelta, formatDuration, formatWidgetValue, truncateLog } from './format';
+
+describe('dashboard format helpers', () => {
+ it('passes string stat values through untouched', () => {
+ expect(formatWidgetValue('N/A')).toBe('N/A');
+ expect(formatWidgetValue('1.2k')).toBe('1.2k');
+ });
+
+ it('renders a missing value as empty, never as 0', () => {
+ expect(formatWidgetValue(undefined)).toBe('');
+ expect(formatWidgetValue(null)).toBe('');
+ expect(formatWidgetValue(Number.NaN)).toBe('');
+ });
+
+ it('signs positive numeric deltas', () => {
+ expect(formatDelta(3)).toBe('+3');
+ expect(formatDelta(-2)).toBe('-2');
+ expect(formatDelta('+5%')).toBe('+5%');
+ expect(formatDelta(undefined)).toBeUndefined();
+ });
+
+ it('caps logs and says so', () => {
+ expect(truncateLog('abc', 10)).toEqual({ text: 'abc', truncated: false });
+ expect(truncateLog('abcdef', 3)).toEqual({ text: 'abc', truncated: true });
+ expect(truncateLog(null)).toEqual({ text: '', truncated: false });
+ });
+
+ it('formats durations', () => {
+ expect(formatDuration(850)).toBe('850ms');
+ expect(formatDuration(2500)).toBe('2.5s');
+ expect(formatDuration(null)).toBeUndefined();
+ });
+});
diff --git a/src/features/Dashboard/utils/format.ts b/src/features/Dashboard/utils/format.ts
new file mode 100644
index 00000000000..ec113b2ba08
--- /dev/null
+++ b/src/features/Dashboard/utils/format.ts
@@ -0,0 +1,45 @@
+import type { WidgetTableCell } from '@lobechat/types';
+
+/** Cap for stdout / stderr shown inline; the server already truncates what it stores. */
+export const LOG_PREVIEW_LIMIT = 4000;
+
+export const truncateLog = (text: string | null | undefined, limit = LOG_PREVIEW_LIMIT) => {
+ if (!text) return { text: '', truncated: false };
+ if (text.length <= limit) return { text, truncated: false };
+ return { text: text.slice(0, limit), truncated: true };
+};
+
+const numberFormat = new Intl.NumberFormat(undefined, { maximumFractionDigits: 2 });
+
+/**
+ * Format a stat value exactly as the script reported it. Strings pass through
+ * untouched — '1.2k' or 'N/A' are the script's own words — and only finite
+ * numbers get locale grouping.
+ */
+export const formatWidgetValue = (value: number | string | null | undefined): string => {
+ if (value === null || value === undefined) return '';
+ if (typeof value === 'number') return Number.isFinite(value) ? numberFormat.format(value) : '';
+ return value;
+};
+
+export const formatDelta = (delta: number | string | undefined): string | undefined => {
+ if (delta === undefined || delta === null) return undefined;
+ if (typeof delta === 'number') {
+ if (!Number.isFinite(delta)) return undefined;
+ return `${delta > 0 ? '+' : ''}${numberFormat.format(delta)}`;
+ }
+ return delta;
+};
+
+export const formatCell = (cell: WidgetTableCell | undefined): string => {
+ if (cell === null || cell === undefined) return '';
+ if (typeof cell === 'number') return numberFormat.format(cell);
+ if (typeof cell === 'boolean') return cell ? 'true' : 'false';
+ return cell;
+};
+
+export const formatDuration = (ms: number | null | undefined): string | undefined => {
+ if (ms === null || ms === undefined) return undefined;
+ if (ms < 1000) return `${ms}ms`;
+ return `${(ms / 1000).toFixed(ms < 10_000 ? 1 : 0)}s`;
+};
diff --git a/src/features/Dashboard/utils/layout.test.ts b/src/features/Dashboard/utils/layout.test.ts
new file mode 100644
index 00000000000..353ec5b317e
--- /dev/null
+++ b/src/features/Dashboard/utils/layout.test.ts
@@ -0,0 +1,87 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ DASHBOARD_GRID_COLUMNS,
+ DASHBOARD_GRID_GAP,
+ DASHBOARD_ROW_HEIGHT,
+ defaultWidgetSize,
+ flowLayouts,
+ resolveLayouts,
+ sortByPosition,
+} from './layout';
+
+describe('defaultWidgetSize', () => {
+ it('gives a stat card room for its value, description and trend line', () => {
+ const { h } = defaultWidgetSize('stat');
+ const cellHeight = h * DASHBOARD_ROW_HEIGHT + (h - 1) * DASHBOARD_GRID_GAP;
+ // padding 24 + header 22 + label/value/description 83 + trend 28 + footer 18 + gaps 28
+ expect(cellHeight).toBeGreaterThanOrEqual(203);
+ });
+});
+
+describe('resolveLayouts', () => {
+ it('keeps persisted layouts that fit and do not collide', () => {
+ const result = resolveLayouts([
+ { id: 'a', layout: { h: 2, w: 3, x: 0, y: 0 } },
+ { id: 'b', layout: { h: 4, w: 6, x: 6, y: 0 } },
+ ]);
+ expect(result).toEqual({
+ a: { h: 2, w: 3, x: 0, y: 0 },
+ b: { h: 4, w: 6, x: 6, y: 0 },
+ });
+ });
+
+ it('places items without a layout into the first free slot by output type', () => {
+ const result = resolveLayouts([
+ { id: 'a', layout: { h: 2, w: 3, x: 0, y: 0 } },
+ { id: 'stat', outputType: 'stat' },
+ { id: 'table', outputType: 'table' },
+ ]);
+ expect(result.stat).toEqual({ h: 3, w: 3, x: 3, y: 0 });
+ // A full-width table cannot share rows 0-2 with anything.
+ expect(result.table).toEqual({ h: 4, w: DASHBOARD_GRID_COLUMNS, x: 0, y: 3 });
+ });
+
+ it('re-places a colliding or out-of-grid layout instead of overlapping', () => {
+ const result = resolveLayouts([
+ { id: 'a', layout: { h: 2, w: 6, x: 0, y: 0 } },
+ { id: 'overlap', layout: { h: 2, w: 6, x: 3, y: 0 } },
+ { id: 'overflow', layout: { h: 2, w: 6, x: 10, y: 0 } },
+ ]);
+ expect(result.overlap).toEqual({ h: 2, w: 6, x: 6, y: 0 });
+ expect(result.overflow).toEqual({ h: 2, w: 6, x: 0, y: 2 });
+ });
+});
+
+describe('flowLayouts', () => {
+ it('wraps items into rows in the given order', () => {
+ expect(
+ flowLayouts([
+ { h: 2, id: 'a', w: 6 },
+ { h: 4, id: 'b', w: 6 },
+ { h: 2, id: 'c', w: 4 },
+ ]),
+ ).toEqual({
+ a: { h: 2, w: 6, x: 0, y: 0 },
+ b: { h: 4, w: 6, x: 6, y: 0 },
+ c: { h: 2, w: 4, x: 0, y: 4 },
+ });
+ });
+
+ it('clamps sizes into the grid', () => {
+ expect(flowLayouts([{ h: 99, id: 'a', w: 99 }]).a).toEqual({ h: 12, w: 12, x: 0, y: 0 });
+ });
+});
+
+describe('sortByPosition', () => {
+ it('orders top to bottom, then left to right', () => {
+ const layouts = {
+ a: { h: 2, w: 3, x: 6, y: 0 },
+ b: { h: 2, w: 3, x: 0, y: 2 },
+ c: { h: 2, w: 3, x: 0, y: 0 },
+ };
+ expect(
+ sortByPosition([{ id: 'a' }, { id: 'b' }, { id: 'c' }], layouts).map((i) => i.id),
+ ).toEqual(['c', 'a', 'b']);
+ });
+});
diff --git a/src/features/Dashboard/utils/layout.ts b/src/features/Dashboard/utils/layout.ts
new file mode 100644
index 00000000000..a6683c372e3
--- /dev/null
+++ b/src/features/Dashboard/utils/layout.ts
@@ -0,0 +1,137 @@
+import type { DashboardItemLayout, WidgetOutputType } from '@lobechat/types';
+
+/** Board grid width in columns; `dashboard_items.layout` is expressed in these units. */
+export const DASHBOARD_GRID_COLUMNS = 12;
+/** Height of one grid row in pixels. */
+export const DASHBOARD_ROW_HEIGHT = 72;
+export const DASHBOARD_GRID_GAP = 16;
+
+export const DASHBOARD_MIN_H = 2;
+export const DASHBOARD_MAX_H = 12;
+
+/** Width presets offered while editing, in columns. */
+export const DASHBOARD_WIDTH_PRESETS = [3, 4, 6, 8, 12] as const;
+
+const DEFAULT_SIZE: Record<WidgetOutputType, { h: number; w: number }> = {
+ list: { h: 4, w: 6 },
+ series: { h: 4, w: 6 },
+ // Three rows (240px): header, label, value, description, the 28px trend line
+ // and the updated-at footer. Two rows squeezed the trend line to nothing.
+ stat: { h: 3, w: 3 },
+ table: { h: 4, w: 12 },
+};
+
+export const defaultWidgetSize = (outputType?: WidgetOutputType | null) =>
+ DEFAULT_SIZE[outputType ?? 'stat'] ?? DEFAULT_SIZE.stat;
+
+export interface LayoutEntry {
+ id: string;
+ layout?: DashboardItemLayout | null;
+ outputType?: WidgetOutputType | null;
+}
+
+const clampSize = ({ h, w }: { h: number; w: number }) => ({
+ h: Math.min(DASHBOARD_MAX_H, Math.max(DASHBOARD_MIN_H, Math.round(h))),
+ w: Math.min(DASHBOARD_GRID_COLUMNS, Math.max(1, Math.round(w))),
+});
+
+const overlaps = (a: DashboardItemLayout, b: DashboardItemLayout) =>
+ a.x < b.x + b.w && b.x < a.x + a.w && a.y < b.y + b.h && b.y < a.y + a.h;
+
+/**
+ * Resolve every item to a concrete grid cell.
+ *
+ * Items keep a persisted layout when it fits the grid and does not collide with
+ * one placed before it; the rest (new placements, agent-created items with no
+ * layout) drop into the first free slot scanning top-down, left-right.
+ */
+export const resolveLayouts = (entries: LayoutEntry[]): Record<string, DashboardItemLayout> => {
+ const placed: DashboardItemLayout[] = [];
+ const result: Record<string, DashboardItemLayout> = {};
+ const pending: LayoutEntry[] = [];
+
+ for (const entry of entries) {
+ const layout = entry.layout;
+ if (layout) {
+ const size = clampSize(layout);
+ const candidate = {
+ ...size,
+ x: Math.max(0, Math.round(layout.x)),
+ y: Math.max(0, Math.round(layout.y)),
+ };
+ if (
+ candidate.x + candidate.w <= DASHBOARD_GRID_COLUMNS &&
+ !placed.some((other) => overlaps(other, candidate))
+ ) {
+ placed.push(candidate);
+ result[entry.id] = candidate;
+ continue;
+ }
+ }
+ pending.push(entry);
+ }
+
+ for (const entry of pending) {
+ const size = clampSize(entry.layout ?? defaultWidgetSize(entry.outputType));
+ for (let y = 0; ; y++) {
+ let found: DashboardItemLayout | undefined;
+ for (let x = 0; x + size.w <= DASHBOARD_GRID_COLUMNS; x++) {
+ const candidate = { ...size, x, y };
+ if (!placed.some((other) => overlaps(other, candidate))) {
+ found = candidate;
+ break;
+ }
+ }
+ if (found) {
+ placed.push(found);
+ result[entry.id] = found;
+ break;
+ }
+ }
+ }
+
+ return result;
+};
+
+/**
+ * Flow items in the given order into rows, like text: each item goes right of
+ * the previous one and wraps when the row is full. Used after a drag reorder or
+ * a resize, where the order is the user's intent and positions follow from it.
+ */
+export const flowLayouts = (
+ entries: { h: number; id: string; w: number }[],
+): Record<string, DashboardItemLayout> => {
+ const result: Record<string, DashboardItemLayout> = {};
+ let x = 0;
+ let y = 0;
+ let rowHeight = 0;
+
+ for (const entry of entries) {
+ const { h, w } = clampSize(entry);
+ if (x + w > DASHBOARD_GRID_COLUMNS) {
+ x = 0;
+ y += rowHeight;
+ rowHeight = 0;
+ }
+ result[entry.id] = { h, w, x, y };
+ x += w;
+ rowHeight = Math.max(rowHeight, h);
+ }
+
+ return result;
+};
+
+/** Reading order of resolved layouts: top to bottom, then left to right. */
+export const sortByPosition = <T extends { id: string }>(
+ items: T[],
+ layouts: Record<string, DashboardItemLayout>,
+) =>
+ [...items].sort((a, b) => {
+ const la = layouts[a.id];
+ const lb = layouts[b.id];
+ if (!la || !lb) return 0;
+ return la.y - lb.y || la.x - lb.x;
+ });
+
+export const isSameLayout = (a?: DashboardItemLayout | null, b?: DashboardItemLayout | null) =>
+ !!a && !!b && a.x === b.x && a.y === b.y && a.w === b.w && a.h === b.h;
diff --git a/src/features/Dashboard/utils/path.test.ts b/src/features/Dashboard/utils/path.test.ts
new file mode 100644
index 00000000000..f45a513599c
--- /dev/null
+++ b/src/features/Dashboard/utils/path.test.ts
@@ -0,0 +1,45 @@
+import { describe, expect, it } from 'vitest';
+
+import { getDashboardListPath, getDashboardPath, getHomeDashboardRedirect } from './path';
+
+describe('getDashboardPath', () => {
+ it('opens a project board inside its project', () => {
+ expect(getDashboardPath({ id: 'd-1', projectId: 'prj_1' })).toBe(
+ '/project/prj_1/dashboard/d-1',
+ );
+ });
+
+ it('opens a home board on the home dashboards', () => {
+ expect(getDashboardPath({ id: 'd-1', projectId: null })).toBe('/dashboard/d-1');
+ expect(getDashboardPath({ id: 'd-1' })).toBe('/dashboard/d-1');
+ });
+});
+
+describe('getDashboardListPath', () => {
+ it('opens the project’s board list for a project widget', () => {
+ expect(getDashboardListPath('prj_1')).toBe('/project/prj_1/dashboard');
+ });
+
+ it('opens the home list for a widget outside projects', () => {
+ expect(getDashboardListPath(null)).toBe('/dashboard');
+ expect(getDashboardListPath(undefined)).toBe('/dashboard');
+ });
+});
+
+describe('getHomeDashboardRedirect', () => {
+ it('sends a project board to its project path', () => {
+ expect(getHomeDashboardRedirect({ id: 'd-1', projectId: 'prj_1' })).toBe(
+ '/project/prj_1/dashboard/d-1',
+ );
+ });
+
+ it('keeps a home board on the home route', () => {
+ expect(getHomeDashboardRedirect({ id: 'd-1', projectId: null })).toBeUndefined();
+ expect(getHomeDashboardRedirect({ id: 'd-1' })).toBeUndefined();
+ });
+
+ it('does not redirect before the board has loaded', () => {
+ expect(getHomeDashboardRedirect(undefined)).toBeUndefined();
+ expect(getHomeDashboardRedirect(null)).toBeUndefined();
+ });
+});
diff --git a/src/features/Dashboard/utils/path.ts b/src/features/Dashboard/utils/path.ts
new file mode 100644
index 00000000000..6858ecec4b7
--- /dev/null
+++ b/src/features/Dashboard/utils/path.ts
@@ -0,0 +1,30 @@
+import { getProjectDashboardPath } from '@/features/Projects/Layout/navigation';
+
+/**
+ * Where a board opens: inside its project's shell (sidebar, back to the
+ * project's boards) when it belongs to one, else on the home dashboards.
+ */
+export const getDashboardPath = (dashboard: { id: string; projectId?: string | null }) =>
+ dashboard.projectId
+ ? getProjectDashboardPath(dashboard.projectId, dashboard.id)
+ : `/dashboard/${dashboard.id}`;
+
+/**
+ * Where a widget's board list opens: the project's dashboards when the widget
+ * lives in one, else the home dashboard list. Opening the home list for a
+ * project widget would land somewhere unrelated (personal mode) or on routes
+ * disabled inside workspaces.
+ */
+export const getDashboardListPath = (projectId?: string | null) =>
+ projectId ? getProjectDashboardPath(projectId) : '/dashboard';
+
+/**
+ * Where the home board route sends a board that actually lives in a project:
+ * into its project path, so it renders with the project shell and back path
+ * instead of the home chrome. Home boards stay on this route (`undefined`),
+ * and an unloaded board is not redirected yet.
+ */
+export const getHomeDashboardRedirect = (
+ dashboard?: { id: string; projectId?: string | null } | null,
+): string | undefined =>
+ dashboard?.projectId ? getProjectDashboardPath(dashboard.projectId, dashboard.id) : undefined;
diff --git a/src/features/Dashboard/utils/series.test.ts b/src/features/Dashboard/utils/series.test.ts
new file mode 100644
index 00000000000..55cb8936a46
--- /dev/null
+++ b/src/features/Dashboard/utils/series.test.ts
@@ -0,0 +1,101 @@
+import { describe, expect, it } from 'vitest';
+
+import { buildSeriesChartData, sparklinePoints } from './series';
+
+describe('buildSeriesChartData', () => {
+ it('prefers the metric_points history over the latest sliding window', () => {
+ const data = buildSeriesChartData(
+ {
+ series: [{ name: 'stars', points: [{ t: '2026-09-29T10:00:00Z', v: 12 }] }],
+ type: 'series',
+ },
+ [
+ {
+ name: 'stars',
+ points: [
+ { observedAt: new Date('2026-09-29T08:00:00Z'), value: 10 },
+ { observedAt: new Date('2026-09-29T09:00:00Z'), value: 11 },
+ { observedAt: new Date('2026-09-29T10:00:00Z'), value: 12 },
+ ],
+ },
+ ],
+ );
+ expect(data.fromHistory).toBe(true);
+ expect(data.categories).toEqual(['stars']);
+ expect(data.rows.map((row) => row.stars)).toEqual([10, 11, 12]);
+ });
+
+ it('falls back to the output for category labels the metrics cannot hold', () => {
+ const data = buildSeriesChartData(
+ {
+ series: [
+ {
+ name: 'visits',
+ points: [
+ { t: 'Mon', v: 3 },
+ { t: 'Tue', v: 5 },
+ ],
+ },
+ ],
+ type: 'series',
+ },
+ [],
+ );
+ expect(data.fromHistory).toBe(false);
+ expect(data.rows).toEqual([
+ { t: 'Mon', visits: 3 },
+ { t: 'Tue', visits: 5 },
+ ]);
+ });
+
+ it('merges several series on a shared, chronologically sorted axis', () => {
+ const data = buildSeriesChartData({
+ series: [
+ { name: 'a', points: [{ t: '2026-09-29T10:00:00Z', v: 2 }] },
+ {
+ name: 'b',
+ points: [
+ { t: '2026-09-29T09:00:00Z', v: 1 },
+ { t: '2026-09-29T10:00:00Z', v: 3 },
+ ],
+ },
+ ],
+ type: 'series',
+ });
+ expect(data.rows).toHaveLength(2);
+ expect(data.rows[0]).not.toHaveProperty('a');
+ expect(data.rows[1]).toMatchObject({ a: 2, b: 3 });
+ });
+
+ it('labels calendar-day points by day instead of midnight', () => {
+ const data = buildSeriesChartData({
+ series: [
+ {
+ name: 'commits',
+ points: [
+ { t: '2026-09-28', v: 55 },
+ { t: '2026-09-27', v: 41 },
+ ],
+ },
+ ],
+ type: 'series',
+ });
+ expect(data.rows).toEqual([
+ { commits: 41, t: '09-27' },
+ { commits: 55, t: '09-28' },
+ ]);
+ });
+});
+
+describe('sparklinePoints', () => {
+ it('spreads a changing history across the box', () => {
+ expect(sparklinePoints([1, 3], 100, 28)).toEqual([
+ { x: 0, y: 26 },
+ { x: 100, y: 2 },
+ ]);
+ });
+
+ it('draws a flat history mid-height instead of on the bottom edge', () => {
+ expect(sparklinePoints([12, 12, 12], 100, 28).map(({ y }) => y)).toEqual([14, 14, 14]);
+ });
+});
diff --git a/src/features/Dashboard/utils/series.ts b/src/features/Dashboard/utils/series.ts
new file mode 100644
index 00000000000..2aad984b211
--- /dev/null
+++ b/src/features/Dashboard/utils/series.ts
@@ -0,0 +1,94 @@
+import type { WidgetSeriesOutput } from '@lobechat/types';
+import dayjs from 'dayjs';
+
+import type { DashboardTrendSeries } from '@/services/dashboard';
+
+export interface SeriesChartData {
+ categories: string[];
+ /** Whether the history came from `metric_points` rather than the latest output alone. */
+ fromHistory: boolean;
+ rows: Record<string, number | string>[];
+}
+
+const ISO_PREFIX = /^\d{4}-\d{2}-\d{2}/;
+/** A calendar day with no time of day, e.g. '2026-09-27'. */
+const DATE_ONLY = /^\d{4}-\d{2}-\d{2}$/;
+
+const formatLabel = (t: string, spansDays: boolean) => {
+ if (!ISO_PREFIX.test(t)) return t;
+ const date = dayjs(t);
+ if (!date.isValid()) return t;
+ // A day has no time to show; formatting it as 'HH:mm' labels every point '00:00'.
+ if (DATE_ONLY.test(t)) return date.format('MM-DD');
+ return date.format(spansDays ? 'MM-DD HH:mm' : 'HH:mm');
+};
+
+/**
+ * Chart rows for a series widget.
+ *
+ * Each series prefers its long-term history from `metric_points` (subject
+ * `widget`, key `series:<name>`), which keeps growing across runs
+ * while a script usually only reports a sliding window. Series the metrics
+ * cannot hold — category labels like 'Mon' — fall back to the latest output.
+ */
+export const buildSeriesChartData = (
+ output: WidgetSeriesOutput,
+ trend?: DashboardTrendSeries[],
+): SeriesChartData => {
+ const history = new Map((trend ?? []).map((series) => [series.name, series.points]));
+ let fromHistory = false;
+
+ const series = output.series.map((item) => {
+ const stored = history.get(item.name);
+ if (stored && stored.length >= item.points.length && stored.length > 0) {
+ fromHistory = true;
+ return {
+ name: item.name,
+ points: stored.map((point) => ({ t: point.observedAt.toISOString(), v: point.value })),
+ };
+ }
+ return item;
+ });
+
+ const times = series.flatMap((item) => item.points.map((point) => point.t));
+ const isoTimes = times.filter((t) => ISO_PREFIX.test(t)).map((t) => dayjs(t).valueOf());
+ const spansDays =
+ isoTimes.length > 1 && Math.max(...isoTimes) - Math.min(...isoTimes) > 24 * 3600 * 1000;
+
+ // Keep first-seen order for categories; sort timestamps chronologically.
+ const order: string[] = [];
+ const seen = new Set<string>();
+ for (const t of times) {
+ if (!seen.has(t)) {
+ seen.add(t);
+ order.push(t);
+ }
+ }
+ if (order.every((t) => ISO_PREFIX.test(t))) {
+ order.sort((a, b) => dayjs(a).valueOf() - dayjs(b).valueOf());
+ }
+
+ const rows = order.map((t) => {
+ const row: Record<string, number | string> = { t: formatLabel(t, spansDays) };
+ for (const item of series) {
+ const point = item.points.find((p) => p.t === t);
+ if (point) row[item.name] = point.v;
+ }
+ return row;
+ });
+
+ return { categories: series.map((item) => item.name), fromHistory, rows };
+};
+
+/**
+ * Points of a stat's sparkline in a `width` × `height` box (2px inset). A flat
+ * history sits mid-height so it reads as a steady trend, not as the box edge.
+ */
+export const sparklinePoints = (values: number[], width: number, height: number) => {
+ const min = Math.min(...values);
+ const span = Math.max(...values) - min;
+ const x = (index: number) => (values.length > 1 ? (index / (values.length - 1)) * width : 0);
+ const y = (value: number) =>
+ span === 0 ? height / 2 : height - 2 - ((value - min) / span) * (height - 4);
+ return values.map((value, index) => ({ x: x(index), y: y(value) }));
+};
diff --git a/src/features/Dashboard/utils/widgetHealth.test.ts b/src/features/Dashboard/utils/widgetHealth.test.ts
new file mode 100644
index 00000000000..fa02e932fb3
--- /dev/null
+++ b/src/features/Dashboard/utils/widgetHealth.test.ts
@@ -0,0 +1,135 @@
+import { describe, expect, it } from 'vitest';
+
+import {
+ getWidgetCardBody,
+ getWidgetHealth,
+ getWidgetUpdatedAt,
+ WIDGET_STALE_GRACE_MS,
+} from './widgetHealth';
+
+const NOW = new Date('2026-09-29T12:00:00Z').getTime();
+const stat = { type: 'stat' as const, value: 42 };
+
+describe('getWidgetHealth', () => {
+ it('reports a fresh, complete widget with no badges', () => {
+ const health = getWidgetHealth(
+ { lastRunStatus: 'succeeded', latestOutput: stat, publishedVersionId: 'v1' },
+ { now: NOW },
+ );
+ expect(health.badges).toEqual([]);
+ expect(health.hasOutput).toBe(true);
+ });
+
+ it('keeps the last successful output when the latest run failed', () => {
+ const health = getWidgetHealth(
+ {
+ lastRunError: { code: 'NON_ZERO_EXIT', message: 'exit 1' },
+ lastRunStatus: 'failed',
+ latestOutput: stat,
+ publishedVersionId: 'v1',
+ },
+ { now: NOW },
+ );
+ expect(health.failed).toBe(true);
+ expect(health.hasOutput).toBe(true);
+ expect(health.badges).toEqual(['failed']);
+ expect(health.error?.message).toBe('exit 1');
+ });
+
+ it('treats a timeout as a failure', () => {
+ expect(getWidgetHealth({ lastRunStatus: 'timeout' }, { now: NOW }).failed).toBe(true);
+ });
+
+ it('marks running from either the server snapshot or a local refresh', () => {
+ expect(getWidgetHealth({ lastRunStatus: 'running' }, { now: NOW }).running).toBe(true);
+ expect(
+ getWidgetHealth({ lastRunStatus: 'succeeded' }, { now: NOW, runningLocally: true }).badges,
+ ).toEqual(['running']);
+ });
+
+ it('marks a scheduled widget stale once its due run is overdue past the grace', () => {
+ const base = { latestOutput: stat, publishedVersionId: 'v1', schedulePattern: '0 * * * *' };
+ expect(
+ getWidgetHealth(
+ { ...base, nextRunAt: new Date(NOW - WIDGET_STALE_GRACE_MS - 1000) },
+ { now: NOW },
+ ).stale,
+ ).toBe(true);
+ expect(
+ getWidgetHealth({ ...base, nextRunAt: new Date(NOW - 60_000) }, { now: NOW }).stale,
+ ).toBe(false);
+ });
+
+ it('never calls a manual-only widget stale', () => {
+ expect(
+ getWidgetHealth({ latestOutput: stat, nextRunAt: new Date(0) }, { now: NOW }).stale,
+ ).toBe(false);
+ });
+
+ it('flags a partial result with the script note', () => {
+ const health = getWidgetHealth(
+ {
+ latestOutput: { ...stat, meta: { complete: false, message: 'GitLab API down' } },
+ publishedVersionId: 'v1',
+ },
+ { now: NOW },
+ );
+ expect(health.partial).toBe(true);
+ expect(health.partialMessage).toBe('GitLab API down');
+ });
+
+ it('orders badges by urgency', () => {
+ const health = getWidgetHealth(
+ {
+ lastRunStatus: 'failed',
+ latestOutput: { ...stat, meta: { complete: false } },
+ nextRunAt: new Date(NOW - 2 * WIDGET_STALE_GRACE_MS),
+ schedulePattern: '*/5 * * * *',
+ },
+ { now: NOW },
+ );
+ expect(health.badges).toEqual(['failed', 'stale', 'partial']);
+ });
+
+ it('knows an unpublished widget', () => {
+ expect(getWidgetHealth({}, { now: NOW }).unpublished).toBe(true);
+ });
+});
+
+describe('getWidgetUpdatedAt', () => {
+ it('prefers the time of the shown output over the last attempt', () => {
+ expect(
+ getWidgetUpdatedAt({
+ lastRunAt: '2026-09-29T11:00:00Z',
+ latestOutputAt: '2026-09-29T10:00:00Z',
+ }),
+ ).toBe('2026-09-29T10:00:00Z');
+ expect(getWidgetUpdatedAt({ lastRunAt: '2026-09-29T11:00:00Z' })).toBe('2026-09-29T11:00:00Z');
+ });
+});
+
+describe('getWidgetCardBody', () => {
+ const body = (widget: Parameters<typeof getWidgetHealth>[0], runningLocally = false) =>
+ getWidgetCardBody(getWidgetHealth(widget, { now: NOW, runningLocally }));
+
+ it('keeps showing the last good output after a failed run', () => {
+ expect(body({ lastRunStatus: 'failed', latestOutput: stat, publishedVersionId: 'v1' })).toBe(
+ 'output',
+ );
+ });
+
+ it('keeps showing the last good output while a refresh runs', () => {
+ expect(body({ latestOutput: stat, publishedVersionId: 'v1' }, true)).toBe('output');
+ });
+
+ it('explains a failure with no good result instead of rendering a value', () => {
+ expect(body({ lastRunStatus: 'failed', publishedVersionId: 'v1' })).toBe('failedNoOutput');
+ expect(body({ lastRunStatus: 'timeout', publishedVersionId: 'v1' })).toBe('failedNoOutput');
+ });
+
+ it('distinguishes a first run, a never-run widget and an unpublished one', () => {
+ expect(body({ lastRunStatus: 'running', publishedVersionId: 'v1' })).toBe('firstRun');
+ expect(body({ publishedVersionId: 'v1' })).toBe('noRun');
+ expect(body({})).toBe('unpublished');
+ });
+});
diff --git a/src/features/Dashboard/utils/widgetHealth.ts b/src/features/Dashboard/utils/widgetHealth.ts
new file mode 100644
index 00000000000..3f9e1ccc385
--- /dev/null
+++ b/src/features/Dashboard/utils/widgetHealth.ts
@@ -0,0 +1,105 @@
+import type { WidgetOutput, WidgetRunError, WidgetRunStatus } from '@lobechat/types';
+import { WIDGET_RUN_OUTPUT_STATUSES } from '@lobechat/types';
+
+/** A run whose output the card renders: `succeeded`, or `partial` (incomplete but usable). */
+export const isUsableRunStatus = (status?: WidgetRunStatus | null) =>
+ !!status && (WIDGET_RUN_OUTPUT_STATUSES as readonly string[]).includes(status);
+
+/** How late a scheduled refresh may be before the card calls its data stale. */
+export const WIDGET_STALE_GRACE_MS = 25 * 60 * 1000;
+
+/** The widget fields a card needs to judge freshness — the hot read model on the widget row. */
+export interface WidgetHealthInput {
+ lastRunAt?: Date | string | null;
+ lastRunError?: WidgetRunError | null;
+ lastRunStatus?: WidgetRunStatus | null;
+ latestOutput?: WidgetOutput | null;
+ latestOutputAt?: Date | string | null;
+ nextRunAt?: Date | string | null;
+ publishedVersionId?: string | null;
+ schedulePattern?: string | null;
+}
+
+export type WidgetHealthBadge = 'running' | 'failed' | 'stale' | 'partial';
+
+export interface WidgetHealth {
+ /** Badges to show, most urgent first. Empty means fresh and complete. */
+ badges: WidgetHealthBadge[];
+ /** Error of the last run when it did not succeed. */
+ error?: WidgetRunError | null;
+ failed: boolean;
+ /** There is a last successful output to render. */
+ hasOutput: boolean;
+ partial: boolean;
+ /** Script note attached to a partial result. */
+ partialMessage?: string;
+ running: boolean;
+ stale: boolean;
+ /** No published version yet — nothing will ever run until one is. */
+ unpublished: boolean;
+}
+
+const toTime = (value?: Date | string | null) => (value ? new Date(value).getTime() : undefined);
+
+/**
+ * Judge what a widget card must say about its data.
+ *
+ * The card always renders the latest *successful* output. A failed or timed-out
+ * last run does not clear it: the card keeps the old value and marks it
+ * failed, so a broken script never reads as a real zero.
+ */
+export const getWidgetHealth = (
+ widget: WidgetHealthInput,
+ options: { now?: number; runningLocally?: boolean } = {},
+): WidgetHealth => {
+ const now = options.now ?? Date.now();
+ const running = !!options.runningLocally || widget.lastRunStatus === 'running';
+ const failed = widget.lastRunStatus === 'failed' || widget.lastRunStatus === 'timeout';
+ const hasOutput = !!widget.latestOutput;
+
+ const nextRunAt = toTime(widget.nextRunAt);
+ const stale =
+ !running &&
+ !!widget.schedulePattern &&
+ nextRunAt !== undefined &&
+ now - nextRunAt > WIDGET_STALE_GRACE_MS;
+
+ const meta = widget.latestOutput?.meta;
+ const partial = hasOutput && meta?.complete === false;
+
+ const badges: WidgetHealthBadge[] = [];
+ if (running) badges.push('running');
+ if (failed) badges.push('failed');
+ if (stale) badges.push('stale');
+ if (partial) badges.push('partial');
+
+ return {
+ badges,
+ error: failed ? widget.lastRunError : undefined,
+ failed,
+ hasOutput,
+ partial,
+ partialMessage: partial ? meta?.message : undefined,
+ running,
+ stale,
+ unpublished: !widget.publishedVersionId,
+ };
+};
+
+/** The instant the shown data was produced, falling back to the last attempt. */
+export const getWidgetUpdatedAt = (widget: WidgetHealthInput) =>
+ widget.latestOutputAt ?? widget.lastRunAt ?? null;
+
+/**
+ * What a card's body shows. `output` whenever a successful result exists —
+ * including after a failed run — so a broken script never replaces real data;
+ * the empty states only apply when there has never been a good result.
+ */
+export type WidgetCardBody = 'output' | 'firstRun' | 'failedNoOutput' | 'unpublished' | 'noRun';
+
+export const getWidgetCardBody = (health: WidgetHealth): WidgetCardBody => {
+ if (health.hasOutput) return 'output';
+ if (health.running) return 'firstRun';
+ if (health.failed) return 'failedNoOutput';
+ return health.unpublished ? 'unpublished' : 'noRun';
+};
diff --git a/src/features/HomeSidebar/Body/CustomizeSidebarModal.test.ts b/src/features/HomeSidebar/Body/CustomizeSidebarModal.test.ts
index e3f30582597..6170f75567a 100644
--- a/src/features/HomeSidebar/Body/CustomizeSidebarModal.test.ts
+++ b/src/features/HomeSidebar/Body/CustomizeSidebarModal.test.ts
@@ -31,4 +31,14 @@ describe('CustomizeSidebarModal', () => {
expect(getSortableSidebarItemIds(false).has('memory')).toBe(true);
expect(getSortableSidebarItemIds(true).has('memory')).toBe(false);
});
+
+ it('offers Dashboards only while the dashboard flag is on, and never in workspace mode', () => {
+ expect(getSortableSidebarItemIds(false).has('dashboard')).toBe(false);
+ expect(getSortableSidebarItemIds(false, { dashboardEnabled: true }).has('dashboard')).toBe(
+ true,
+ );
+ expect(getSortableSidebarItemIds(true, { dashboardEnabled: true }).has('dashboard')).toBe(
+ false,
+ );
+ });
});
diff --git a/src/features/HomeSidebar/Body/CustomizeSidebarModal.tsx b/src/features/HomeSidebar/Body/CustomizeSidebarModal.tsx
index 574492640da..716b133743f 100644
--- a/src/features/HomeSidebar/Body/CustomizeSidebarModal.tsx
+++ b/src/features/HomeSidebar/Body/CustomizeSidebarModal.tsx
@@ -48,6 +48,7 @@ import {
SIDEBAR_ACCORDION_KEYS,
SIDEBAR_SPACER_ID,
} from '@/store/global/selectors/systemStatus';
+import { serverConfigSelectors, useServerConfigStore } from '@/store/serverConfig';
// ---------------------------------------------------------------------------
// Types & constants
@@ -64,6 +65,7 @@ export interface SidebarItemConfig {
const ALL_SIDEBAR_ITEMS: SidebarItemConfig[] = [
{ id: 'tasks', labelKey: 'tab.tasks', routeId: 'tasks' },
+ { id: 'dashboard', labelKey: 'tab.dashboard', routeId: 'dashboard' },
{ id: 'pages', labelKey: 'tab.pages', routeId: 'page' },
{ id: 'recents', labelKey: 'recents' },
{ id: 'project', labelKey: 'project:sidebar.title' },
@@ -78,15 +80,27 @@ const ALL_SIDEBAR_ITEMS: SidebarItemConfig[] = [
// Private is workspace-only; in personal mode every row is implicitly
// owner-private, so hide it from the customizer where toggling it on
// would render an empty accordion no user can populate.
-export const getAvailableSidebarItems = (isWorkspaceMode: boolean): SidebarItemConfig[] =>
+// Dashboards also stay out until the `dashboard` feature flag is on for the
+// user; a dropped id is restored by `withAllKnownKeys` once it is.
+export const getAvailableSidebarItems = (
+ isWorkspaceMode: boolean,
+ { dashboardEnabled = false }: { dashboardEnabled?: boolean } = {},
+): SidebarItemConfig[] =>
ALL_SIDEBAR_ITEMS.filter((item) => {
- if (isWorkspaceMode && item.id === 'memory') return false;
+ if (item.id === 'dashboard' && !dashboardEnabled) return false;
+ if (isWorkspaceMode && (item.id === 'memory' || item.id === 'dashboard')) return false;
if (!isWorkspaceMode && item.id === 'private') return false;
return true;
});
-export const getSortableSidebarItemIds = (isWorkspaceMode: boolean): Set<string> =>
- new Set([...getAvailableSidebarItems(isWorkspaceMode).map((item) => item.id), SIDEBAR_SPACER_ID]);
+export const getSortableSidebarItemIds = (
+ isWorkspaceMode: boolean,
+ options?: { dashboardEnabled?: boolean },
+): Set<string> =>
+ new Set([
+ ...getAvailableSidebarItems(isWorkspaceMode, options).map((item) => item.id),
+ SIDEBAR_SPACER_ID,
+ ]);
const ITEM_MAP = new Map(ALL_SIDEBAR_ITEMS.map((item) => [item.id, item]));
@@ -376,9 +390,10 @@ const CustomizeSidebarContent = memo(() => {
);
const updateSystemStatus = useGlobalStore((s) => s.updateSystemStatus);
const isWorkspaceMode = !!useActiveWorkspaceSlug();
+ const dashboardEnabled = useServerConfigStore(serverConfigSelectors.enableDashboard);
const sortableItemIds = useMemo(
- () => getSortableSidebarItemIds(isWorkspaceMode),
- [isWorkspaceMode],
+ () => getSortableSidebarItemIds(isWorkspaceMode, { dashboardEnabled }),
+ [isWorkspaceMode, dashboardEnabled],
);
const filteredStoreItems = useMemo(
() => storeItems.filter((id) => sortableItemIds.has(id)),
diff --git a/src/features/Portal/DashboardWidget/Body.tsx b/src/features/Portal/DashboardWidget/Body.tsx
new file mode 100644
index 00000000000..59513801cfc
--- /dev/null
+++ b/src/features/Portal/DashboardWidget/Body.tsx
@@ -0,0 +1,180 @@
+import { Flexbox } from '@lobehub/ui';
+import { Button, Skeleton, Text } from '@lobehub/ui/base-ui';
+import { createStaticStyles, cssVar } from 'antd-style';
+import { ArrowUpRightIcon, LayoutDashboardIcon } from 'lucide-react';
+import { memo, type ReactNode } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspaceSlug';
+import AsyncError from '@/components/AsyncError';
+import { WidgetDetailPanel } from '@/features/Dashboard/WidgetDetail';
+import WidgetRunPreview from '@/features/Dashboard/WidgetDetail/RunPreview';
+import { canCreateDashboardFromPreview } from '@/features/Dashboard/WidgetPreview/previewWidget';
+import { useChatStore } from '@/store/chat';
+import { chatPortalSelectors } from '@/store/chat/selectors';
+import { dashboardSelectors, useDashboardStore } from '@/store/dashboard';
+import { useServerConfigStore } from '@/store/serverConfig';
+
+import { useOpenDashboard } from './useOpenDashboard';
+
+const styles = createStaticStyles(({ css }) => ({
+ label: css`
+ font-size: 12px;
+ font-weight: 600;
+ color: ${cssVar.colorTextSecondary};
+ `,
+ preview: css`
+ padding: 12px;
+ border: 1px solid ${cssVar.colorBorderSecondary};
+ border-radius: ${cssVar.borderRadiusLG};
+ `,
+}));
+
+const Section = memo<{ children: ReactNode; extra?: ReactNode; title: string }>(
+ ({ children, extra, title }) => (
+ <Flexbox gap={8}>
+ <Flexbox horizontal align={'center'} gap={8} justify={'space-between'}>
+ <span className={styles.label}>{title}</span>
+ {extra}
+ </Flexbox>
+ {children}
+ </Flexbox>
+ ),
+);
+
+Section.displayName = 'DashboardWidgetPortalSection';
+
+/** The dry run the conversation opened this view from, rendered in full. */
+const RunPreviewSection = memo<{ runId: string; widgetId: string }>(({ runId, widgetId }) => {
+ const { t } = useTranslation('dashboard');
+ const useFetchWidgetRun = useDashboardStore((s) => s.useFetchWidgetRun);
+ const { error, mutate } = useFetchWidgetRun(widgetId, runId);
+ const run = useDashboardStore(dashboardSelectors.widgetRunDetail(runId));
+ const versions = useDashboardStore(dashboardSelectors.widgetVersions(widgetId));
+ const view = versions.find((version) => version.id === run?.versionId)?.view;
+
+ return (
+ <Section title={t('portal.preview')}>
+ <Text fontSize={12} type={'secondary'}>
+ {t('portal.previewHint')}
+ </Text>
+ <div className={styles.preview}>
+ {error ? (
+ <AsyncError error={error} onRetry={() => void mutate()} />
+ ) : run ? (
+ <WidgetRunPreview run={run} view={view} />
+ ) : (
+ <Skeleton height={160} width={'100%'} />
+ )}
+ </div>
+ </Section>
+ );
+});
+
+RunPreviewSection.displayName = 'DashboardWidgetPortalRunPreview';
+
+/**
+ * A dashboard widget beside the conversation that built it: what it measures,
+ * the dry run the conversation produced, where it lives, and the full
+ * drill-down (live data, run logs, versions and their diff).
+ */
+const Body = memo(() => {
+ const { t } = useTranslation('dashboard');
+ const view = useChatStore(chatPortalSelectors.dashboardWidgetView);
+ const widgetId = view?.widgetId;
+ const useFetchWidgetDetail = useDashboardStore((s) => s.useFetchWidgetDetail);
+ const { error, mutate } = useFetchWidgetDetail(widgetId);
+ const widget = useDashboardStore(dashboardSelectors.widgetDetail(widgetId));
+ const openDashboard = useOpenDashboard();
+ // A workspace-root widget's board list resolves to the home list, which
+ // workspaces disable — opening it would close this Portal onto nothing.
+ // And dashboard routes exist only in the desktop shell, so on mobile every
+ // dashboard navigation hides rather than clear the stack onto nothing.
+ const isMobile = useServerConfigStore((s) => s.isMobile);
+ const workspaceActive = !!useActiveWorkspaceSlug();
+ const canOpenDashboards =
+ !isMobile && canCreateDashboardFromPreview(widget?.projectId, workspaceActive);
+
+ if (!widgetId) return null;
+
+ if (error && !widget) {
+ return (
+ <Flexbox flex={1} height={'100%'} style={{ minHeight: 0, overflowY: 'auto' }}>
+ <AsyncError error={error} variant={'page'} onRetry={() => void mutate()} />
+ </Flexbox>
+ );
+ }
+
+ if (!widget) {
+ return (
+ <Flexbox gap={12} padding={16}>
+ <Skeleton height={80} width={'100%'} />
+ <Skeleton height={200} width={'100%'} />
+ </Flexbox>
+ );
+ }
+
+ // Normalize once: an older server may not send the widget's boards list.
+ const dashboards = widget.dashboards ?? [];
+
+ return (
+ <Flexbox
+ data-portal-widget={widget.id}
+ flex={1}
+ gap={20}
+ height={'100%'}
+ padding={16}
+ style={{ minHeight: 0, overflowY: 'auto' }}
+ >
+ <Section title={t('portal.definition')}>
+ <Text fontSize={13}>{widget.description || t('chat.noDefinition')}</Text>
+ </Section>
+
+ {view?.runId && <RunPreviewSection runId={view.runId} widgetId={widget.id} />}
+
+ <Section
+ title={t('portal.dashboards')}
+ extra={
+ canOpenDashboards ? (
+ <Button
+ data-portal-all-dashboards
+ icon={LayoutDashboardIcon}
+ size={'small'}
+ type={'text'}
+ onClick={() => openDashboard(undefined, widget.projectId)}
+ >
+ {t('portal.goToDashboards')}
+ </Button>
+ ) : undefined
+ }
+ >
+ {!isMobile &&
+ (dashboards.length > 0 ? (
+ <Flexbox horizontal gap={8} wrap={'wrap'}>
+ {dashboards.map((dashboard) => (
+ <Button
+ data-portal-dashboard-link={dashboard.id}
+ icon={ArrowUpRightIcon}
+ key={dashboard.id}
+ size={'small'}
+ onClick={() => openDashboard(dashboard)}
+ >
+ {dashboard.title}
+ </Button>
+ ))}
+ </Flexbox>
+ ) : (
+ <Text fontSize={12} type={'secondary'}>
+ {t('portal.notOnDashboard')}
+ </Text>
+ ))}
+ </Section>
+
+ <WidgetDetailPanel diffTargetVersionId={widget.draftVersionId ?? undefined} widget={widget} />
+ </Flexbox>
+ );
+});
+
+Body.displayName = 'DashboardWidgetPortalBody';
+
+export default Body;
diff --git a/src/features/Portal/DashboardWidget/Title.tsx b/src/features/Portal/DashboardWidget/Title.tsx
new file mode 100644
index 00000000000..a283baff8c9
--- /dev/null
+++ b/src/features/Portal/DashboardWidget/Title.tsx
@@ -0,0 +1,29 @@
+import { Flexbox, Icon } from '@lobehub/ui';
+import { Text } from '@lobehub/ui/base-ui';
+import { cssVar } from 'antd-style';
+import { ChartNoAxesColumnIcon } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useChatStore } from '@/store/chat';
+import { chatPortalSelectors } from '@/store/chat/selectors';
+import { dashboardSelectors, useDashboardStore } from '@/store/dashboard';
+import { oneLineEllipsis } from '@/styles';
+
+const Title = memo(() => {
+ const { t } = useTranslation('dashboard');
+ const view = useChatStore(chatPortalSelectors.dashboardWidgetView);
+ const widget = useDashboardStore(dashboardSelectors.widgetDetail(view?.widgetId));
+
+ return (
+ // Hug the content so the shared `…` sits right after the title.
+ <Flexbox horizontal align={'center'} gap={8} style={{ minWidth: 0 }}>
+ <Icon color={cssVar.colorTextSecondary} icon={ChartNoAxesColumnIcon} size={16} />
+ <Text className={oneLineEllipsis} style={{ flex: '0 1 auto', fontSize: 14, minWidth: 0 }}>
+ {widget?.title ?? t('portal.title')}
+ </Text>
+ </Flexbox>
+ );
+});
+
+export default Title;
diff --git a/src/features/Portal/DashboardWidget/index.ts b/src/features/Portal/DashboardWidget/index.ts
new file mode 100644
index 00000000000..20754cfa7e4
--- /dev/null
+++ b/src/features/Portal/DashboardWidget/index.ts
@@ -0,0 +1,18 @@
+import { createElement, memo } from 'react';
+
+import { DashboardFeatureGate } from '@/features/Dashboard/FeatureGate';
+
+import { type PortalImpl } from '../type';
+import BodyContent from './Body';
+import TitleContent from './Title';
+import { useDashboardWidgetMoreMenu } from './useMoreMenu';
+
+// Nothing of the widget view renders while the `dashboard` flag is off.
+const Body = memo(() => createElement(DashboardFeatureGate, null, createElement(BodyContent)));
+const Title = memo(() => createElement(DashboardFeatureGate, null, createElement(TitleContent)));
+
+export const DashboardWidget: PortalImpl = {
+ Body,
+ Title,
+ useMoreMenu: useDashboardWidgetMoreMenu,
+};
diff --git a/src/features/Portal/DashboardWidget/useMoreMenu.ts b/src/features/Portal/DashboardWidget/useMoreMenu.ts
new file mode 100644
index 00000000000..48f4b4019c3
--- /dev/null
+++ b/src/features/Portal/DashboardWidget/useMoreMenu.ts
@@ -0,0 +1,30 @@
+import { type PortalMoreMenuConfig } from '@/features/Portal/components/PortalMoreMenu/types';
+import { useChatStore } from '@/store/chat';
+import { chatPortalSelectors } from '@/store/chat/selectors';
+import { dashboardSelectors, useDashboardStore } from '@/store/dashboard';
+import { useServerConfigStore } from '@/store/serverConfig';
+
+import { useOpenDashboard } from './useOpenDashboard';
+
+export const useDashboardWidgetMoreMenu = (): PortalMoreMenuConfig | undefined => {
+ const view = useChatStore(chatPortalSelectors.dashboardWidgetView);
+ const widget = useDashboardStore(dashboardSelectors.widgetDetail(view?.widgetId));
+ const refreshWidget = useDashboardStore((s) => s.refreshWidget);
+ const openDashboard = useOpenDashboard();
+ // Dashboard routes exist only in the desktop shell — on mobile opening one
+ // would just clear the Portal stack onto nothing.
+ const isMobile = useServerConfigStore((s) => s.isMobile);
+
+ if (!view) return;
+ const { widgetId } = view;
+
+ return {
+ copyId: widgetId,
+ // The widget's own page is the board it sits on; without one, the board
+ // list of its project — or home when it lives outside projects.
+ openInPage: isMobile
+ ? undefined
+ : () => openDashboard(widget?.dashboards[0], widget?.projectId),
+ refresh: () => refreshWidget(widgetId),
+ };
+};
diff --git a/src/features/Portal/DashboardWidget/useOpenDashboard.ts b/src/features/Portal/DashboardWidget/useOpenDashboard.ts
new file mode 100644
index 00000000000..2421b91c027
--- /dev/null
+++ b/src/features/Portal/DashboardWidget/useOpenDashboard.ts
@@ -0,0 +1,19 @@
+import { getDashboardListPath, getDashboardPath } from '@/features/Dashboard/utils/path';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { useChatStore } from '@/store/chat';
+
+/**
+ * Leave the conversation for a dashboard — inside its project when it has one
+ * — or for a board list: the widget project's when it lives in one, else the
+ * home dashboard list. The portal stack is this conversation's inspection
+ * session, so it is cleared on the way out.
+ */
+export const useOpenDashboard = () => {
+ const navigate = useWorkspaceAwareNavigate();
+ const clearPortalStack = useChatStore((s) => s.clearPortalStack);
+
+ return (dashboard?: { id: string; projectId?: string | null }, projectId?: string | null) => {
+ clearPortalStack();
+ navigate(dashboard ? getDashboardPath(dashboard) : getDashboardListPath(projectId));
+ };
+};
diff --git a/src/features/Portal/portalWidth.ts b/src/features/Portal/portalWidth.ts
index 5530a8efa06..b200b386816 100644
--- a/src/features/Portal/portalWidth.ts
+++ b/src/features/Portal/portalWidth.ts
@@ -33,6 +33,7 @@ const VIEW_MIN_WIDTH: PortalWidths = {
[PortalViewType.AcceptanceCheck]: CHAT_PORTAL_TOOL_UI_WIDTH,
[PortalViewType.AgentDetail]: CHAT_PORTAL_TOOL_UI_WIDTH,
[PortalViewType.Artifact]: CHAT_PORTAL_TOOL_UI_WIDTH,
+ [PortalViewType.DashboardWidget]: CHAT_PORTAL_TOOL_UI_WIDTH,
[PortalViewType.Goal]: CHAT_PORTAL_TOOL_UI_WIDTH,
[PortalViewType.GoalMetric]: CHAT_PORTAL_TOOL_UI_WIDTH,
[PortalViewType.GoalNode]: CHAT_PORTAL_TOOL_UI_WIDTH,
@@ -53,6 +54,8 @@ const VIEW_MIN_WIDTH: PortalWidths = {
const VIEW_DEFAULT_WIDTH: PortalWidths = {
[PortalViewType.Acceptance]: CHAT_PORTAL_WIDE_WIDTH,
[PortalViewType.AcceptanceCheck]: CHAT_PORTAL_WIDE_WIDTH,
+ // Full-size chart, a data table and a side-by-side script diff.
+ [PortalViewType.DashboardWidget]: CHAT_PORTAL_TASK_WIDTH,
// The goal overview carries the exploration map and the header metrics row,
// both of which only read at the wide width.
[PortalViewType.Goal]: CHAT_PORTAL_WIDE_WIDTH,
diff --git a/src/features/Portal/router.tsx b/src/features/Portal/router.tsx
index dc54a7e5b0d..b6700ab2b21 100644
--- a/src/features/Portal/router.tsx
+++ b/src/features/Portal/router.tsx
@@ -12,6 +12,7 @@ import { AgentDetail } from './AgentDetail';
import { Artifacts } from './Artifacts';
import Header from './components/Header';
import { PortalMoreMenuProvider } from './components/PortalMoreMenu/context';
+import { DashboardWidget } from './DashboardWidget';
import { Document } from './Document';
import { FilePreview } from './FilePreview';
import { Goal } from './Goal';
@@ -43,6 +44,7 @@ const VIEW_COMPONENTS: Record<PortalViewType, PortalImpl> = {
Title: HomeTitle,
},
[PortalViewType.Artifact]: Artifacts,
+ [PortalViewType.DashboardWidget]: DashboardWidget,
[PortalViewType.Document]: Document,
[PortalViewType.Notebook]: Notebook,
[PortalViewType.FilePreview]: FilePreview,
diff --git a/src/features/Projects/Dashboards/Board.tsx b/src/features/Projects/Dashboards/Board.tsx
new file mode 100644
index 00000000000..5b0f4dbc281
--- /dev/null
+++ b/src/features/Projects/Dashboards/Board.tsx
@@ -0,0 +1,30 @@
+'use client';
+
+import { Navigate, useParams } from 'react-router';
+
+import DashboardBoardPage from '@/features/Dashboard/BoardPage';
+import { dashboardSelectors, useDashboardStore } from '@/store/dashboard';
+
+import { getProjectDashboardPath } from '../Layout/navigation';
+
+/** `project/:projectId/dashboard/:dashboardId` — one project board, back to the project's list. */
+const ProjectDashboardBoard = () => {
+ const { dashboardId, projectId } = useParams<{ dashboardId: string; projectId: string }>();
+ // A home board or another project's board is not this project's: leave for the list.
+ const outsideProject = useDashboardStore(
+ dashboardSelectors.isDashboardOutsideProject(dashboardId ?? '', projectId ?? ''),
+ );
+ if (!dashboardId || !projectId) return null;
+ if (outsideProject) return <Navigate replace to={'..'} />;
+
+ return (
+ <DashboardBoardPage
+ backPath={getProjectDashboardPath(projectId)}
+ dashboardId={dashboardId}
+ key={dashboardId}
+ level={{ projectId }}
+ />
+ );
+};
+
+export default ProjectDashboardBoard;
diff --git a/src/features/Projects/Dashboards/index.tsx b/src/features/Projects/Dashboards/index.tsx
new file mode 100644
index 00000000000..765a5bad9a4
--- /dev/null
+++ b/src/features/Projects/Dashboards/index.tsx
@@ -0,0 +1,184 @@
+'use client';
+
+import { Center, Empty, Flexbox } from '@lobehub/ui';
+import { Button, Text } from '@lobehub/ui/base-ui';
+import { BlocksIcon, LayoutDashboardIcon, PlusIcon } from 'lucide-react';
+import { memo, type ReactNode } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import AsyncBoundary from '@/components/AsyncBoundary';
+import AsyncError from '@/components/AsyncError';
+import { RouteLoading } from '@/components/Skeleton/RouteSegment';
+import { openCreateDashboardModal } from '@/features/Dashboard/DashboardFormModal';
+import DashboardListCard, {
+ dashboardListStyles,
+} from '@/features/Dashboard/List/DashboardListCard';
+import { dashboardPageStyles as pageStyles } from '@/features/Dashboard/pageStyles';
+import DashboardWidgetGrid from '@/features/Dashboard/WidgetGrid';
+import NavHeader from '@/features/NavHeader';
+import SkeletonList from '@/features/NavPanel/components/SkeletonList';
+import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';
+import { useActiveRouteParams } from '@/hooks/useActiveRouteParams';
+import { usePermission } from '@/hooks/usePermission';
+import { dashboardSelectors, useDashboardStore } from '@/store/dashboard';
+import { useCurrentProjectDetail, useProjectStore } from '@/store/project';
+
+import { getProjectDashboardPath } from '../Layout/navigation';
+
+const Section = ({ children, title }: { children: ReactNode; title: string }) => (
+ <Flexbox gap={12}>
+ <h2 className={pageStyles.sectionTitle}>{title}</h2>
+ {children}
+ </Flexbox>
+);
+
+/** The project's boards, whoever in the project created them, and creating one here. */
+const ProjectBoards = memo<{ canCreate: boolean; onCreate: () => void; projectId: string }>(
+ ({ canCreate, onCreate, projectId }) => {
+ const { t } = useTranslation('dashboard');
+ const useFetchProjectDashboards = useDashboardStore((s) => s.useFetchProjectDashboards);
+ const { data, error, isLoading, mutate } = useFetchProjectDashboards(projectId);
+ const dashboards = useDashboardStore(dashboardSelectors.projectDashboards(projectId));
+
+ return (
+ <Section title={t('project.boards')}>
+ <AsyncBoundary
+ data={data}
+ error={error}
+ isEmpty={data?.length === 0}
+ isLoading={isLoading}
+ loading={<SkeletonList rows={2} />}
+ empty={
+ <Center gap={12} padding={24}>
+ <Empty description={t('project.boardsEmpty')} icon={LayoutDashboardIcon} />
+ {canCreate && (
+ <Button icon={PlusIcon} onClick={onCreate}>
+ {t('create.action')}
+ </Button>
+ )}
+ </Center>
+ }
+ onRetry={() => void mutate()}
+ >
+ <div data-project-dashboards className={dashboardListStyles.grid}>
+ {dashboards.map((dashboard) => (
+ <DashboardListCard
+ dashboard={dashboard}
+ href={getProjectDashboardPath(projectId, dashboard.id)}
+ key={dashboard.id}
+ level={{ projectId }}
+ />
+ ))}
+ </div>
+ </AsyncBoundary>
+ </Section>
+ );
+ },
+);
+
+ProjectBoards.displayName = 'ProjectBoards';
+
+/** Every widget of the project — including ones an agent built in a project conversation. */
+const ProjectWidgets = memo<{ projectId: string }>(({ projectId }) => {
+ const { t } = useTranslation('dashboard');
+ const useFetchProjectWidgets = useDashboardStore((s) => s.useFetchProjectWidgets);
+ const { data, error, isLoading, mutate } = useFetchProjectWidgets(projectId);
+ const widgets = useDashboardStore(dashboardSelectors.projectWidgets(projectId));
+
+ return (
+ <Section title={t('project.widgets', { count: widgets.length })}>
+ <AsyncBoundary
+ data={data}
+ error={error}
+ isEmpty={data?.length === 0}
+ isLoading={isLoading}
+ loading={<SkeletonList rows={2} />}
+ empty={
+ <Center padding={24}>
+ <Empty description={t('project.widgetsEmpty')} icon={BlocksIcon} />
+ </Center>
+ }
+ onRetry={() => void mutate()}
+ >
+ <DashboardWidgetGrid widgets={widgets} />
+ </AsyncBoundary>
+ </Section>
+ );
+});
+
+ProjectWidgets.displayName = 'ProjectWidgets';
+
+const ProjectDashboardsPage = memo<{ projectId: string }>(({ projectId }) => {
+ const { t } = useTranslation('dashboard');
+ const navigate = useWorkspaceAwareNavigate();
+ // Workspace viewers lack `create_content`, and the server refuses their
+ // creates with FORBIDDEN — give them no create controls at all.
+ const { allowed: canCreate } = usePermission('create_content');
+
+ const handleCreate = () =>
+ openCreateDashboardModal({
+ level: { projectId },
+ onCreated: (dashboard) => navigate(getProjectDashboardPath(projectId, dashboard.id)),
+ });
+
+ return (
+ <Flexbox flex={1} height={'100%'}>
+ <NavHeader
+ left={
+ <Text style={{ paddingInlineStart: 4 }} weight={500}>
+ {t('list.title')}
+ </Text>
+ }
+ />
+ <div className={pageStyles.scroll}>
+ <div className={pageStyles.canvas} style={{ gap: 32 }}>
+ <Flexbox
+ horizontal
+ align={'flex-end'}
+ className={pageStyles.heading}
+ gap={16}
+ justify={'space-between'}
+ >
+ <Flexbox gap={6} style={{ minWidth: 0 }}>
+ <h1 className={pageStyles.title}>{t('list.title')}</h1>
+ <Text className={pageStyles.description}>{t('project.description')}</Text>
+ </Flexbox>
+ {canCreate && (
+ <Button
+ data-dashboard-create
+ icon={PlusIcon}
+ style={{ flex: 'none' }}
+ type={'primary'}
+ onClick={handleCreate}
+ >
+ {t('create.action')}
+ </Button>
+ )}
+ </Flexbox>
+ <ProjectBoards canCreate={canCreate} projectId={projectId} onCreate={handleCreate} />
+ <ProjectWidgets projectId={projectId} />
+ </div>
+ </div>
+ </Flexbox>
+ );
+});
+
+ProjectDashboardsPage.displayName = 'ProjectDashboardsPage';
+
+/** `project/:projectId/dashboard` — the project's own boards and widgets. */
+const ProjectDashboards = () => {
+ const { projectId } = useActiveRouteParams<{ projectId: string }>();
+ const detail = useCurrentProjectDetail(projectId);
+ const { error, isHydrated, isValidating, revalidate } = useProjectStore(
+ (s) => s.useFetchProjectDetail,
+ )(projectId);
+
+ if (!detail && (!isHydrated || isValidating)) return <RouteLoading />;
+ if (error && !detail)
+ return <AsyncError error={error} variant={'page'} onRetry={() => void revalidate()} />;
+ if (!detail) return null;
+
+ return <ProjectDashboardsPage projectId={detail.project.id} />;
+};
+
+export default ProjectDashboards;
diff --git a/src/features/Projects/Layout/Sidebar.tsx b/src/features/Projects/Layout/Sidebar.tsx
index 02d9038ce99..62f41326279 100644
--- a/src/features/Projects/Layout/Sidebar.tsx
+++ b/src/features/Projects/Layout/Sidebar.tsx
@@ -1,12 +1,19 @@
'use client';
import { Flexbox } from '@lobehub/ui';
-import { ClipboardCheckIcon, ListTodoIcon, SettingsIcon, TargetIcon } from 'lucide-react';
+import {
+ ClipboardCheckIcon,
+ LayoutDashboardIcon,
+ ListTodoIcon,
+ SettingsIcon,
+ TargetIcon,
+} from 'lucide-react';
import { memo } from 'react';
import { useTranslation } from 'react-i18next';
import { useLocation } from 'react-router';
import AsyncError from '@/components/AsyncError';
+import { useDashboardFeature } from '@/features/Dashboard/hooks/useDashboardFeature';
import NavItem from '@/features/NavPanel/components/NavItem';
import { NavPanelPortal } from '@/features/NavPanel/NavPanelPortal';
import SideBarLayout from '@/features/NavPanel/SideBarLayout';
@@ -15,7 +22,12 @@ import { useActiveRouteParams } from '@/hooks/useActiveRouteParams';
import { useCurrentProjectDetail, useProjectStore } from '@/store/project';
import { ProjectDirectoryTopics } from '../WorkingDirectories/SidebarTopics';
-import { getProjectAcceptancePath, getProjectGoalsPath, getProjectTasksPath } from './navigation';
+import {
+ getProjectAcceptancePath,
+ getProjectDashboardPath,
+ getProjectGoalsPath,
+ getProjectTasksPath,
+} from './navigation';
import ProjectHeader from './ProjectHeader';
const ProjectSidebarContent = memo(() => {
@@ -25,19 +37,21 @@ const ProjectSidebarContent = memo(() => {
const { pathname } = useLocation();
const detail = useCurrentProjectDetail(projectId);
const detailSWR = useProjectStore((s) => s.useFetchProjectDetail)(projectId);
+ const { enabled: dashboardEnabled } = useDashboardFeature();
const projectTasksPath = getProjectTasksPath(projectId!);
const projectGoalsPath = getProjectGoalsPath(projectId!);
const projectAcceptancePath = getProjectAcceptancePath(projectId!);
+ const projectDashboardPath = getProjectDashboardPath(projectId!);
const header = <ProjectHeader project={detail?.project} />;
if (detailSWR.error && !detail)
return (
<SideBarLayout
+ header={header}
body={
<AsyncError error={detailSWR.error} variant="inline" onRetry={detailSWR.revalidate} />
}
- header={header}
/>
);
@@ -58,6 +72,16 @@ const ProjectSidebarContent = memo(() => {
title={t('sections.goals')}
onClick={() => navigate(projectGoalsPath)}
/>
+ {dashboardEnabled && (
+ <NavItem
+ icon={LayoutDashboardIcon}
+ title={t('sections.dashboard')}
+ active={
+ pathname === projectDashboardPath || pathname.startsWith(`${projectDashboardPath}/`)
+ }
+ onClick={() => navigate(projectDashboardPath)}
+ />
+ )}
<NavItem
active={pathname === projectAcceptancePath}
icon={ClipboardCheckIcon}
diff --git a/src/features/Projects/Layout/navigation.test.ts b/src/features/Projects/Layout/navigation.test.ts
index bc2562a11fb..79cbacd25fc 100644
--- a/src/features/Projects/Layout/navigation.test.ts
+++ b/src/features/Projects/Layout/navigation.test.ts
@@ -5,6 +5,7 @@ import {
getProjectAgentPath,
getProjectConversationPath,
getProjectConversationStartPath,
+ getProjectDashboardPath,
getProjectGoalsPath,
getProjectLibraryPath,
getProjectTasksPath,
@@ -19,6 +20,11 @@ describe('project workspace navigation', () => {
expect(getProjectAcceptancePath('prj_1')).toBe('/project/prj_1/acceptance');
});
+ it('builds the project dashboard list and board routes', () => {
+ expect(getProjectDashboardPath('prj_1')).toBe('/project/prj_1/dashboard');
+ expect(getProjectDashboardPath('prj_1', 'd-1')).toBe('/project/prj_1/dashboard/d-1');
+ });
+
it('builds new and existing conversation routes inside the project', () => {
expect(getProjectConversationPath('prj_1')).toBe('/project/prj_1/conversation');
expect(getProjectConversationPath('prj_1', 'tpc_1')).toBe('/project/prj_1/conversation/tpc_1');
diff --git a/src/features/Projects/Layout/navigation.ts b/src/features/Projects/Layout/navigation.ts
index f60a41eba0e..b465cb5ccdc 100644
--- a/src/features/Projects/Layout/navigation.ts
+++ b/src/features/Projects/Layout/navigation.ts
@@ -13,4 +13,9 @@ export const getProjectTasksPath = (projectId: string) => `/project/${projectId}
export const getProjectGoalsPath = (projectId: string) => `/project/${projectId}/goals`;
+export const getProjectDashboardPath = (projectId: string, dashboardId?: string) =>
+ dashboardId
+ ? `/project/${projectId}/dashboard/${dashboardId}`
+ : `/project/${projectId}/dashboard`;
+
export const getProjectAcceptancePath = (projectId: string) => `/project/${projectId}/acceptance`;
diff --git a/src/helpers/toolEngineering/index.test.ts b/src/helpers/toolEngineering/index.test.ts
index fe0e1cd0590..fe1a060f8e1 100644
--- a/src/helpers/toolEngineering/index.test.ts
+++ b/src/helpers/toolEngineering/index.test.ts
@@ -1,4 +1,5 @@
import { AuvManifest } from '@lobechat/builtin-tool-auv';
+import { DashboardManifest } from '@lobechat/builtin-tool-dashboard';
import type * as ConstModule from '@lobechat/const';
import { type ToolManifest } from '@lobechat/types';
import { afterEach, describe, expect, it, vi } from 'vitest';
@@ -22,6 +23,11 @@ vi.mock('@/store/tool', () => ({
connectors: [],
builtinTools: [
{ identifier: AuvManifest.identifier, manifest: AuvManifest, type: 'builtin' as const },
+ {
+ identifier: DashboardManifest.identifier,
+ manifest: DashboardManifest,
+ type: 'builtin' as const,
+ },
{
identifier: 'search',
manifest: {
@@ -178,9 +184,13 @@ vi.mock('@/store/tool/selectors', () => ({
}));
let mockServerConfig: { toolNameMaxLength?: number } = {};
+let mockFeatureFlags: { enableDashboard?: boolean } = {};
vi.mock('@/store/serverConfig', () => ({
- getServerConfigStoreState: () => ({ serverConfig: mockServerConfig }),
+ getServerConfigStoreState: () => ({
+ featureFlags: mockFeatureFlags,
+ serverConfig: mockServerConfig,
+ }),
}));
let mockIsCanUseFC = true;
@@ -253,6 +263,28 @@ describe('toolEngineering', () => {
mockCurrentChatConfig = {};
mockImageOutputSupport = false;
mockServerConfig = {};
+ mockFeatureFlags = {};
+ });
+
+ describe('feature-flagged tools', () => {
+ const generate = () =>
+ createAgentToolsEngine({ model: 'gpt-4', provider: 'openai' }).generateToolsDetailed({
+ toolIds: [DashboardManifest.identifier],
+ model: 'gpt-4',
+ provider: 'openai',
+ });
+
+ it('never offers lobe-dashboard while the dashboard flag is off, even when pinned', () => {
+ mockCurrentAgentPlugins = [DashboardManifest.identifier];
+ mockFeatureFlags = { enableDashboard: false };
+ expect(generate().enabledToolIds).not.toContain(DashboardManifest.identifier);
+ });
+
+ it('offers a pinned lobe-dashboard once the flag is on', () => {
+ mockCurrentAgentPlugins = [DashboardManifest.identifier];
+ mockFeatureFlags = { enableDashboard: true };
+ expect(generate().enabledToolIds).toContain(DashboardManifest.identifier);
+ });
});
// `TOOL_NAME_MAX_LENGTH` is a server env, but this path generates tool names in
diff --git a/src/helpers/toolEngineering/index.ts b/src/helpers/toolEngineering/index.ts
index 6813b15dec2..126d812cf67 100644
--- a/src/helpers/toolEngineering/index.ts
+++ b/src/helpers/toolEngineering/index.ts
@@ -2,6 +2,7 @@
* Tools Engineering - Unified tools processing using ToolsEngine
*/
import { AuvManifest } from '@lobechat/builtin-tool-auv';
+import { getFeatureDisabledToolIds } from '@lobechat/builtin-tools/featureGates';
import {
createEnableChecker,
type LobeToolManifest,
@@ -25,6 +26,7 @@ import {
chatConfigByIdSelectors,
} from '@/store/agent/selectors';
import { aiModelSelectors, getAiInfraStoreState } from '@/store/aiInfra';
+import { getServerConfigStoreState } from '@/store/serverConfig';
import { getToolStoreState } from '@/store/tool';
import {
composioStoreSelectors,
@@ -159,7 +161,12 @@ export const createAgentToolsEngine = (
// `currentAgentPlugins` already resolves to pinned-only identifiers.
plugins: agentSelectors.currentAgentPlugins(agentState),
},
- disabledPluginIds: agentSelectors.currentAgentDisabledPlugins(agentState),
+ // Feature-flagged tools (e.g. lobe-dashboard) leave the pool while their
+ // flag is off for this user.
+ disabledPluginIds: [
+ ...agentSelectors.currentAgentDisabledPlugins(agentState),
+ ...getFeatureDisabledToolIds(getServerConfigStoreState()?.featureFlags),
+ ],
executionTarget: chatConfigByIdSelectors.getExecutionTargetById(activeAgentId)(agentState),
hasEnabledKnowledgeBases: agentSelectors.hasEnabledKnowledgeBases(agentState),
// A `local` target only resolves on the desktop, where the host itself is
diff --git a/src/helpers/toolFilters.ts b/src/helpers/toolFilters.ts
index 59ccc7d47c3..a72affd3836 100644
--- a/src/helpers/toolFilters.ts
+++ b/src/helpers/toolFilters.ts
@@ -4,14 +4,20 @@
*/
import { AuvManifest } from '@lobechat/builtin-tool-auv';
import { LocalSystemManifest } from '@lobechat/builtin-tool-local-system';
+import { isToolEnabledByFeatureFlags } from '@lobechat/builtin-tools/featureGates';
import { isDesktop } from '@lobechat/const';
+import { getServerConfigStoreState } from '@/store/serverConfig';
+
/**
* Check if a tool should be enabled based on platform-specific constraints
* @param toolId - The tool identifier to check
* @returns true if the tool should be enabled, false otherwise
*/
export const shouldEnableTool = (toolId: string): boolean => {
+ // Feature-flagged tools (e.g. lobe-dashboard) are not listed or offered while off.
+ if (!isToolEnabledByFeatureFlags(toolId, getServerConfigStoreState()?.featureFlags)) return false;
+
// These executors call Electron IPC and cannot run in a plain web client.
if (toolId === LocalSystemManifest.identifier || toolId === AuvManifest.identifier) {
return isDesktop;
diff --git a/src/hooks/useNavLayout.test.tsx b/src/hooks/useNavLayout.test.tsx
index 897752cf642..559f8abff65 100644
--- a/src/hooks/useNavLayout.test.tsx
+++ b/src/hooks/useNavLayout.test.tsx
@@ -7,6 +7,7 @@ interface GlobalStateMock {
const mocks = vi.hoisted(() => ({
activeWorkspaceSlug: null as string | null,
+ enableDashboard: false,
showMarket: true,
}));
@@ -21,12 +22,14 @@ vi.mock('@/store/global', () => ({
selector({ toggleCommandMenu: vi.fn() }),
}));
+const ENABLE_DASHBOARD = 'enableDashboard';
vi.mock('@/store/serverConfig', () => ({
- featureFlagsSelectors: {},
- useServerConfigStore: () => ({
- hideGitHub: false,
- showMarket: mocks.showMarket,
- }),
+ featureFlagsSelectors: 'featureFlags',
+ serverConfigSelectors: { enableDashboard: ENABLE_DASHBOARD },
+ useServerConfigStore: (selector: unknown) =>
+ selector === ENABLE_DASHBOARD
+ ? mocks.enableDashboard
+ : { hideGitHub: false, showMarket: mocks.showMarket },
}));
vi.mock('@/business/client/hooks/useActiveWorkspaceSlug', () => ({
@@ -37,6 +40,25 @@ describe('useNavLayout', () => {
beforeEach(() => {
mocks.activeWorkspaceSlug = null;
mocks.showMarket = true;
+ mocks.enableDashboard = false;
+ });
+
+ const dashboardItem = async () => {
+ const { useNavLayout } = await import('./useNavLayout');
+ const { result } = renderHook(() => useNavLayout());
+ return result.current.topNavItems.find((item) => item.key === 'dashboard');
+ };
+
+ it('hides Dashboards while the dashboard feature flag is off', async () => {
+ expect((await dashboardItem())?.hidden).toBe(true);
+ });
+
+ it('shows Dashboards in personal mode once the flag is on', async () => {
+ mocks.enableDashboard = true;
+ expect((await dashboardItem())?.hidden).toBe(false);
+
+ mocks.activeWorkspaceSlug = 'lobe-team';
+ expect((await dashboardItem())?.hidden).toBe(true);
});
it('keeps Memory visible in personal mode', async () => {
diff --git a/src/hooks/useNavLayout.ts b/src/hooks/useNavLayout.ts
index ef181166425..6954156fee3 100644
--- a/src/hooks/useNavLayout.ts
+++ b/src/hooks/useNavLayout.ts
@@ -6,7 +6,11 @@ import { useActiveWorkspaceSlug } from '@/business/client/hooks/useActiveWorkspa
import { getRouteById } from '@/config/routes';
import { useGlobalStore } from '@/store/global';
import { SidebarTabKey } from '@/store/global/initialState';
-import { featureFlagsSelectors, useServerConfigStore } from '@/store/serverConfig';
+import {
+ featureFlagsSelectors,
+ serverConfigSelectors,
+ useServerConfigStore,
+} from '@/store/serverConfig';
export interface NavItem {
hidden?: boolean;
@@ -38,6 +42,7 @@ export const useNavLayout = (): NavLayout => {
const toggleCommandMenu = useGlobalStore((s) => s.toggleCommandMenu);
const { showMarket, hideGitHub } = useServerConfigStore(featureFlagsSelectors);
const activeWorkspaceSlug = useActiveWorkspaceSlug();
+ const enableDashboard = useServerConfigStore(serverConfigSelectors.enableDashboard);
const topNavItems = useMemo(
() =>
@@ -60,6 +65,15 @@ export const useNavLayout = (): NavLayout => {
title: t('tab.tasks'),
url: '/tasks',
},
+ {
+ // Personal boards only for now — workspace-level boards have no UI
+ // yet — and only while the `dashboard` feature flag is on.
+ hidden: !!activeWorkspaceSlug || !enableDashboard,
+ icon: getRouteById('dashboard')!.icon,
+ key: SidebarTabKey.Dashboard,
+ title: t('tab.dashboard'),
+ url: '/dashboard',
+ },
{
icon: getRouteById('resource')!.icon,
key: SidebarTabKey.Resource,
@@ -67,7 +81,7 @@ export const useNavLayout = (): NavLayout => {
url: '/resource',
},
] as NavItem[],
- [t, toggleCommandMenu],
+ [t, toggleCommandMenu, activeWorkspaceSlug, enableDashboard],
);
const bottomMenuItems = useMemo(
diff --git a/src/libs/qstash/deduplicationId.ts b/src/libs/qstash/deduplicationId.ts
new file mode 100644
index 00000000000..d8d634a68e4
--- /dev/null
+++ b/src/libs/qstash/deduplicationId.ts
@@ -0,0 +1,18 @@
+import { createHash } from 'node:crypto';
+
+/**
+ * Encode a logical execution key into a QStash-safe deduplication id.
+ *
+ * Keep the logical key intact in durable state and local queues, but encode it
+ * at the provider boundary: QStash rejects characters such as `:`, while a
+ * SHA-256 hex digest is deterministic, alphanumeric and exactly 64 chars.
+ *
+ * Every caller that publishes a deduplicated message must go through this —
+ * passing a raw logical id to `publishJSON` fails the publish with
+ * `DeduplicationId cannot contain ':'`.
+ *
+ * Lives beside (not inside) `@/libs/qstash` so it stays the real implementation
+ * for callers that mock the client module and still assert the encoding.
+ */
+export const toQStashDeduplicationId = (logicalId: string): string =>
+ createHash('sha256').update(logicalId).digest('hex');
diff --git a/src/libs/qstash/index.ts b/src/libs/qstash/index.ts
index c113c0bf70f..ac71484a976 100644
--- a/src/libs/qstash/index.ts
+++ b/src/libs/qstash/index.ts
@@ -6,6 +6,8 @@ import debug from 'debug';
const log = debug('lobe-server:qstash');
+export { toQStashDeduplicationId } from './deduplicationId';
+
const headers = {
...(process.env.VERCEL_AUTOMATION_BYPASS_SECRET && {
'x-vercel-protection-bypass': process.env.VERCEL_AUTOMATION_BYPASS_SECRET,
diff --git a/src/proxy.ts b/src/proxy.ts
index 59860b6e3a2..ef05754c595 100644
--- a/src/proxy.ts
+++ b/src/proxy.ts
@@ -21,6 +21,8 @@ export const config = {
'/apps(.*)',
'/community',
'/community(.*)',
+ '/dashboard',
+ '/dashboard(.*)',
'/labs',
'/eval',
'/eval(.*)',
diff --git a/src/routes/(main)/dashboard/[dashboardId]/index.tsx b/src/routes/(main)/dashboard/[dashboardId]/index.tsx
new file mode 100644
index 00000000000..467d9a840a1
--- /dev/null
+++ b/src/routes/(main)/dashboard/[dashboardId]/index.tsx
@@ -0,0 +1,22 @@
+'use client';
+
+import { Navigate, useParams } from 'react-router';
+
+import DashboardBoardPage from '@/features/Dashboard/BoardPage';
+import { getHomeDashboardRedirect } from '@/features/Dashboard/utils/path';
+import { dashboardSelectors, useDashboardStore } from '@/store/dashboard';
+
+const DashboardDetailRoute = () => {
+ const { dashboardId } = useParams<{ dashboardId: string }>();
+ const detail = useDashboardStore(dashboardSelectors.dashboardDetail(dashboardId));
+ // A project's board is not a home board: once it loads, leave for its
+ // project path so it renders inside the project shell instead of with the
+ // home back path.
+ const projectPath = getHomeDashboardRedirect(detail);
+ if (!dashboardId) return null;
+ if (projectPath) return <Navigate replace to={projectPath} />;
+
+ return <DashboardBoardPage dashboardId={dashboardId} key={dashboardId} />;
+};
+
+export default DashboardDetailRoute;
diff --git a/src/routes/(main)/dashboard/_layout/index.tsx b/src/routes/(main)/dashboard/_layout/index.tsx
new file mode 100644
index 00000000000..8c68fa91e97
--- /dev/null
+++ b/src/routes/(main)/dashboard/_layout/index.tsx
@@ -0,0 +1 @@
+export { HomeDashboardRouteGate as default } from '@/features/Dashboard/FeatureGate';
diff --git a/src/routes/(main)/dashboard/index.tsx b/src/routes/(main)/dashboard/index.tsx
new file mode 100644
index 00000000000..8fdb240d443
--- /dev/null
+++ b/src/routes/(main)/dashboard/index.tsx
@@ -0,0 +1 @@
+export { default } from '@/features/Dashboard/List';
diff --git a/src/routes/(main)/project/[projectId]/dashboard/[dashboardId]/index.tsx b/src/routes/(main)/project/[projectId]/dashboard/[dashboardId]/index.tsx
new file mode 100644
index 00000000000..dcd9d89a572
--- /dev/null
+++ b/src/routes/(main)/project/[projectId]/dashboard/[dashboardId]/index.tsx
@@ -0,0 +1 @@
+export { default } from '@/features/Projects/Dashboards/Board';
diff --git a/src/routes/(main)/project/[projectId]/dashboard/_layout/index.tsx b/src/routes/(main)/project/[projectId]/dashboard/_layout/index.tsx
new file mode 100644
index 00000000000..edb3fe05168
--- /dev/null
+++ b/src/routes/(main)/project/[projectId]/dashboard/_layout/index.tsx
@@ -0,0 +1 @@
+export { default } from '@/features/Dashboard/FeatureGate';
diff --git a/src/routes/(main)/project/[projectId]/dashboard/index.tsx b/src/routes/(main)/project/[projectId]/dashboard/index.tsx
new file mode 100644
index 00000000000..6f69ce86cb6
--- /dev/null
+++ b/src/routes/(main)/project/[projectId]/dashboard/index.tsx
@@ -0,0 +1 @@
+export { default } from '@/features/Projects/Dashboards';
diff --git a/src/services/dashboard.ts b/src/services/dashboard.ts
new file mode 100644
index 00000000000..452bf93daef
--- /dev/null
+++ b/src/services/dashboard.ts
@@ -0,0 +1,185 @@
+import type { DashboardItemLayout, WidgetLevelFilter } from '@lobechat/types';
+
+import { lambdaClient } from '@/libs/trpc/client';
+
+type DashboardRouter = typeof lambdaClient.dashboard;
+type WidgetRouter = typeof lambdaClient.widget;
+type QueryData<T extends { query: (...args: any[]) => Promise<any> }> = NonNullable<
+ Awaited<ReturnType<T['query']>>
+>['data'];
+
+export type DashboardListItem = QueryData<DashboardRouter['list']>[number];
+export type DashboardDetail = QueryData<DashboardRouter['detail']>;
+/** One placed widget: the placement row plus the widget's hot read model. */
+export type DashboardBoardItem = DashboardDetail['items'][number];
+export type DashboardWidgetItem = DashboardBoardItem['widget'];
+export type DashboardWidgetDetail = QueryData<WidgetRouter['detail']>;
+export type DashboardWidgetVersionItem = QueryData<WidgetRouter['listVersions']>[number];
+export type DashboardWidgetRunItem = QueryData<WidgetRouter['listRuns']>[number];
+export type DashboardWidgetRunDetail = QueryData<WidgetRouter['getRun']>;
+
+export interface DashboardLayoutPatch {
+ id: string;
+ layout?: DashboardItemLayout | null;
+ sortOrder?: number;
+}
+
+export interface CreateDashboardParams extends WidgetLevelFilter {
+ description?: string | null;
+ title: string;
+ /**
+ * Place this widget on the new board in the same server transaction: when
+ * it cannot be placed, no board is created.
+ */
+ widgetId?: string;
+}
+
+/** Trend points of one metric series, already parsed into numbers and dates. */
+export interface DashboardTrendSeries {
+ name: string;
+ points: { observedAt: Date; value: number }[];
+ unit?: string | null;
+}
+
+const TREND_POINT_LIMIT = 200;
+
+/** Oldest first — the metric reads return recent windows in either order. */
+const toPoints = (points: { observedAt: Date | string; value: number | string }[]) =>
+ points
+ .map((point) => ({ observedAt: new Date(point.observedAt), value: Number(point.value) }))
+ .sort((a, b) => a.observedAt.getTime() - b.observedAt.getTime());
+
+class DashboardService {
+ // ── Dashboards ──
+
+ list = async (level: WidgetLevelFilter = {}) => {
+ const { data } = await lambdaClient.dashboard.list.query(level);
+ return data;
+ };
+
+ /** Every board of a project, including those an agent of the project also owns. */
+ listByProject = async (projectId: string) => {
+ const { data } = await lambdaClient.dashboard.listByProject.query({ projectId });
+ return data;
+ };
+
+ detail = async (id: string) => {
+ const { data } = await lambdaClient.dashboard.detail.query({ id });
+ return data;
+ };
+
+ create = async (params: CreateDashboardParams) => {
+ const { data } = await lambdaClient.dashboard.create.mutate(params);
+ return data;
+ };
+
+ rename = async (id: string, title: string) =>
+ lambdaClient.dashboard.update.mutate({ id, value: { title } });
+
+ trash = async (id: string) => lambdaClient.dashboard.trash.mutate({ id });
+
+ addItem = async (dashboardId: string, widgetId: string) => {
+ const { data } = await lambdaClient.dashboard.addItem.mutate({ dashboardId, widgetId });
+ return data;
+ };
+
+ updateItemLayouts = async (dashboardId: string, patches: DashboardLayoutPatch[]) =>
+ lambdaClient.dashboard.updateItemLayouts.mutate({ dashboardId, patches });
+
+ removeItems = async (dashboardId: string, itemIds: string[]) =>
+ lambdaClient.dashboard.removeItems.mutate({ dashboardId, itemIds });
+
+ // ── Widgets ──
+
+ /** Every widget of a project, including those an agent of the project also owns. */
+ listWidgetsByProject = async (projectId: string) => {
+ const { data } = await lambdaClient.widget.listByProject.query({ projectId });
+ return data;
+ };
+
+ widgetDetail = async (widgetId: string) => {
+ const { data } = await lambdaClient.widget.detail.query({ id: widgetId });
+ return data;
+ };
+
+ runWidget = async (widgetId: string) => {
+ const { data } = await lambdaClient.widget.run.mutate({ widgetId });
+ return data;
+ };
+
+ getRun = async (widgetId: string, runId: string) => {
+ const { data } = await lambdaClient.widget.getRun.query({ runId, widgetId });
+ return data;
+ };
+
+ /**
+ * The preview run behind a publish approval, by version: not window-limited,
+ * so the card survives run-history rollover.
+ */
+ getPreviewRun = async (widgetId: string, versionId: string) => {
+ const { data } = await lambdaClient.widget.getPreviewRun.query({ versionId, widgetId });
+ return data;
+ };
+
+ publish = async (widgetId: string, versionId: string) => {
+ const { data } = await lambdaClient.widget.publish.mutate({ versionId, widgetId });
+ return data;
+ };
+
+ listRuns = async (widgetId: string, limit?: number) => {
+ const { data } = await lambdaClient.widget.listRuns.query({ limit, widgetId });
+ return data;
+ };
+
+ getVersion = async (widgetId: string, versionId: string) => {
+ const { data } = await lambdaClient.widget.getVersion.query({ versionId, widgetId });
+ return data;
+ };
+
+ listVersions = async (widgetId: string) => {
+ const { data } = await lambdaClient.widget.listVersions.query({ widgetId });
+ return data;
+ };
+
+ /** Run one `lobe-dashboard` agent tool call server-side (client agent runtime). */
+ runAgentTool = async (
+ apiName: string,
+ args: unknown,
+ context: { agentId?: string; messageId?: string; operationId?: string; topicId?: string },
+ ) =>
+ lambdaClient.dashboard.runAgentTool.mutate({
+ apiName,
+ args: (args ?? {}) as Record<string, unknown>,
+ context,
+ });
+
+ // ── Trend (metrics / metric_points, subject `widget`) ──
+
+ /** The primary series a stat widget records one point into per run. */
+ metricTrend = async (metricId: string): Promise<DashboardTrendSeries[]> => {
+ const { data } = await lambdaClient.metric.listPoints.query({
+ id: metricId,
+ limit: TREND_POINT_LIMIT,
+ });
+ return [{ name: data.title ?? '', points: toPoints(data.points), unit: data.unit }];
+ };
+
+ /** The `series:<name>` metrics a series widget appends its timestamped points to. */
+ seriesTrend = async (widgetId: string, names: string[]): Promise<DashboardTrendSeries[]> => {
+ if (names.length === 0) return [];
+
+ const { data } = await lambdaClient.metric.listSeriesWithPoints.query({
+ keys: names.map((name) => `series:${name}`),
+ limit: TREND_POINT_LIMIT,
+ subjectId: widgetId,
+ subjectType: 'widget',
+ });
+ return data.map((series) => ({
+ name: series.title ?? series.key.replace(/^series:/, ''),
+ points: toPoints(series.points),
+ unit: series.unit,
+ }));
+ };
+}
+
+export const dashboardService = new DashboardService();
diff --git a/src/spa/router/desktopRouter.shared.tsx b/src/spa/router/desktopRouter.shared.tsx
index 03934d74a4b..b24f3ab4a1f 100644
--- a/src/spa/router/desktopRouter.shared.tsx
+++ b/src/spa/router/desktopRouter.shared.tsx
@@ -47,6 +47,7 @@ import { agentDocumentRouteMeta } from '@/features/AgentDocumentPage/routeMeta';
import { goalDetailRouteMeta, goalsRouteMeta } from '@/features/AgentGoals/routeMeta';
import { taskRouteMeta, tasksRouteMeta } from '@/features/AgentTasks/routeMeta';
import { agentsRouteMeta } from '@/features/AgentViewAll/routeMeta';
+import { dashboardRouteMeta, dashboardsRouteMeta } from '@/features/Dashboard/routeMeta';
import { pageRouteMeta } from '@/features/Pages/routeMeta';
import {
projectConversationRouteMeta,
@@ -1000,6 +1001,39 @@ export const sharedMainAreaChildren: RouteObject[] = [
path: 'projects',
},
+ // Personal dashboards (free-form monitoring boards)
+ {
+ children: [
+ {
+ element: dynamicElement(() => import('@/routes/(main)/dashboard'), 'Desktop > Dashboards', {
+ preloadId: 'dashboard',
+ }),
+ handle: { meta: dashboardsRouteMeta },
+ index: true,
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/dashboard/[dashboardId]'),
+ 'Desktop > Dashboard Detail',
+ { preloadId: 'dashboard' },
+ ),
+ handle: { meta: dashboardRouteMeta },
+ path: ':dashboardId',
+ },
+ ],
+ // Personal-only, and off unless the `dashboard` feature flag is on: the gate
+ // leaves for home inside a workspace or while the flag is off.
+ element: dynamicLayout(
+ () => import('@/routes/(main)/dashboard/_layout'),
+ 'Desktop > Dashboards > Layout',
+ {
+ preloadId: 'dashboard',
+ },
+ ),
+ errorElement: <ErrorBoundary resetPath=".." />,
+ path: 'dashboard',
+ },
+
// Task workspace routes (cross-agent)
{
children: [
@@ -1041,6 +1075,35 @@ export const sharedMainAreaChildren: RouteObject[] = [
handle: { meta: goalsRouteMeta },
path: 'goals',
},
+ {
+ children: [
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/project/[projectId]/dashboard'),
+ 'Desktop > Project Dashboards',
+ { preloadId: 'dashboard' },
+ ),
+ handle: { meta: dashboardsRouteMeta },
+ index: true,
+ },
+ {
+ element: dynamicElement(
+ () => import('@/routes/(main)/project/[projectId]/dashboard/[dashboardId]'),
+ 'Desktop > Project Dashboard Detail',
+ { preloadId: 'dashboard' },
+ ),
+ handle: { meta: dashboardRouteMeta },
+ path: ':dashboardId',
+ },
+ ],
+ // Off unless the `dashboard` feature flag is on: the gate leaves for the project.
+ element: dynamicLayout(
+ () => import('@/routes/(main)/project/[projectId]/dashboard/_layout'),
+ 'Desktop > Project Dashboards > Layout',
+ { preloadId: 'dashboard' },
+ ),
+ path: 'dashboard',
+ },
{
children: [
{
diff --git a/src/spa/router/desktopRouter.sync.test.tsx b/src/spa/router/desktopRouter.sync.test.tsx
index b291670d10b..e0652ac74c3 100644
--- a/src/spa/router/desktopRouter.sync.test.tsx
+++ b/src/spa/router/desktopRouter.sync.test.tsx
@@ -193,7 +193,7 @@ describe('desktop router shared definition', () => {
});
it.each(mainAreaVariants)(
- '%s exposes project task, goal, and acceptance workspaces',
+ '%s exposes project task, goal, dashboard, and acceptance workspaces',
(_, factory) => {
const projectRoute = factory().find((route) => route.path === 'project/:projectId');
const projectIndexRoute = projectRoute?.children?.find((route) => route.index);
@@ -206,6 +206,7 @@ describe('desktop router shared definition', () => {
'tasks',
'settings/:section?',
'goals',
+ 'dashboard',
'acceptance',
]);
for (const section of ['general', 'environments', 'directories']) {
@@ -221,6 +222,16 @@ describe('desktop router shared definition', () => {
},
);
+ it.each(mainAreaVariants)('%s matches project dashboard list and board pages', (_, factory) => {
+ const list = matchRoutes(createMainAreaRoutes(factory), '/project/prj_1/dashboard');
+ const board = matchRoutes(createMainAreaRoutes(factory), '/acme/project/prj_1/dashboard/d-1');
+
+ expect(list?.at(-1)?.route.index).toBe(true);
+ expect(list?.at(-1)?.route.handle).toMatchObject({ meta: expect.any(Object) });
+ expect(board?.at(-1)?.route.path).toBe(':dashboardId');
+ expect(board?.at(-1)?.params).toMatchObject({ dashboardId: 'd-1', projectId: 'prj_1' });
+ });
+
it.each(mainAreaVariants)('%s exposes the projects view-all route', (_, factory) => {
const personalMatches = matchRoutes(createMainAreaRoutes(factory), '/projects');
const workspaceMatches = matchRoutes(createMainAreaRoutes(factory), '/acme/projects');
diff --git a/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts b/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts
index 132249938b5..826e0849ee9 100644
--- a/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts
+++ b/src/store/chat/slices/agentRun/actions/transports/client/streamingExecutor.ts
@@ -11,6 +11,7 @@ import {
GeneralChatAgent,
isParkedStatus,
} from '@lobechat/agent-runtime';
+import { createDryRunAudit, DASHBOARD_DRY_RUN_AUDIT } from '@lobechat/builtin-tool-dashboard';
import { LobeAgentManifest } from '@lobechat/builtin-tool-lobe-agent';
import { createPathScopeAudit } from '@lobechat/builtin-tool-local-system';
import { PageAgentIdentifier } from '@lobechat/builtin-tool-page-agent';
@@ -39,6 +40,7 @@ import { aiAgentService } from '@/services/aiAgent';
import { isCanUseAudio, isCanUseVideo, isCanUseVision } from '@/services/chat/helper';
import { type ResolvedAgentConfig } from '@/services/chat/mecha';
import { composeEnabledTools, resolveAgentConfig } from '@/services/chat/mecha';
+import { dashboardService } from '@/services/dashboard';
import { localFileService } from '@/services/electron/localFileService';
import { messageService } from '@/services/message';
import { hydrateProjectedConversation } from '@/services/message/hydrateProjectedTools';
@@ -73,6 +75,9 @@ import type { RunParkedReason, RunScope } from '../../lifecycle/types';
const log = debug('lobe-store:streaming-executor');
const dynamicInterventionAudits = {
+ [DASHBOARD_DRY_RUN_AUDIT]: createDryRunAudit({
+ loadVersion: (widgetId, versionId) => dashboardService.getVersion(widgetId, versionId),
+ }),
pathScopeAudit: createPathScopeAudit({
areAllPathsSafe: async ({ paths, resolveAgainstScope }) => {
if (!isDesktop) return false;
diff --git a/src/store/chat/slices/portal/action.test.ts b/src/store/chat/slices/portal/action.test.ts
index 2b007766171..4cafcb612c3 100644
--- a/src/store/chat/slices/portal/action.test.ts
+++ b/src/store/chat/slices/portal/action.test.ts
@@ -9,6 +9,14 @@ import { topicMapKey } from '@/store/chat/utils/topicMapKey';
import { createLocalFileScopeKey, createLocalFileTabId } from './helpers';
import { PortalViewType } from './initialState';
+const dashboardFlag = vi.hoisted(() => ({ enabled: true }));
+vi.mock('@/store/serverConfig', async (importOriginal) => ({
+ ...(await importOriginal<object>()),
+ getServerConfigStoreState: () => ({
+ featureFlags: { enableDashboard: dashboardFlag.enabled },
+ }),
+}));
+
const localFileTabId = ({
deviceId,
filePath,
@@ -273,6 +281,47 @@ describe('chatDockSlice', () => {
});
});
+ describe('openDashboardWidget', () => {
+ it('opens the widget view, carrying the dry run it was opened from', () => {
+ const { result } = renderHook(() => useChatStore());
+
+ act(() => {
+ result.current.clearPortalStack();
+ result.current.openDashboardWidget('widget-1', 'run-1');
+ });
+
+ expect(result.current.showPortal).toBe(true);
+ expect(chatPortalSelectors.dashboardWidgetView(result.current)).toEqual({
+ runId: 'run-1',
+ type: PortalViewType.DashboardWidget,
+ widgetId: 'widget-1',
+ });
+
+ act(() => {
+ result.current.openDashboardWidget('widget-2');
+ });
+ expect(chatPortalSelectors.dashboardWidgetView(result.current)).toEqual({
+ type: PortalViewType.DashboardWidget,
+ widgetId: 'widget-2',
+ });
+ });
+
+ it('opens nothing while the dashboard feature flag is off', () => {
+ const { result } = renderHook(() => useChatStore());
+ dashboardFlag.enabled = false;
+ try {
+ act(() => {
+ result.current.clearPortalStack();
+ result.current.openDashboardWidget('widget-1', 'run-1');
+ });
+ expect(chatPortalSelectors.dashboardWidgetView(result.current)).toBeFalsy();
+ expect(result.current.portalStack).toEqual([]);
+ } finally {
+ dashboardFlag.enabled = true;
+ }
+ });
+ });
+
describe('openArtifact', () => {
it('keeps a parent task portal addressable while its run artifact is open', () => {
const { result } = renderHook(() => useChatStore());
diff --git a/src/store/chat/slices/portal/action.ts b/src/store/chat/slices/portal/action.ts
index ad0bc0ac4db..3db02e5a1e7 100644
--- a/src/store/chat/slices/portal/action.ts
+++ b/src/store/chat/slices/portal/action.ts
@@ -3,6 +3,7 @@ import type { TopicCommentItem } from '@lobechat/types';
import { projectFileService } from '@/services/projectFile';
import { type ChatStore } from '@/store/chat/store';
import { useGlobalStore } from '@/store/global';
+import { getServerConfigStoreState } from '@/store/serverConfig';
import { type StoreSetter } from '@/store/types';
import { type PortalArtifact } from '@/types/artifact';
@@ -687,6 +688,17 @@ export class ChatPortalActionImpl {
this.#get().pushPortalView({ messageId, type: PortalViewType.MessageDetail });
};
+ /** A dashboard widget in full: data, the dry run that produced a preview, versions and logs. */
+ openDashboardWidget = (widgetId: string, runId?: string): void => {
+ // The widget view only exists while the `dashboard` feature flag is on.
+ if (getServerConfigStoreState()?.featureFlags.enableDashboard !== true) return;
+ this.#get().pushPortalView({
+ ...(runId ? { runId } : {}),
+ type: PortalViewType.DashboardWidget,
+ widgetId,
+ });
+ };
+
openNotebook = (): void => {
this.#get().pushPortalView({ type: PortalViewType.Notebook });
};
diff --git a/src/store/chat/slices/portal/initialState.ts b/src/store/chat/slices/portal/initialState.ts
index 447066288f8..8844097b74f 100644
--- a/src/store/chat/slices/portal/initialState.ts
+++ b/src/store/chat/slices/portal/initialState.ts
@@ -14,6 +14,7 @@ export enum PortalViewType {
AcceptanceCheck = 'acceptanceCheck',
AgentDetail = 'agentDetail',
Artifact = 'artifact',
+ DashboardWidget = 'dashboardWidget',
Document = 'document',
FilePreview = 'filePreview',
Goal = 'goal',
@@ -97,6 +98,7 @@ export type PortalViewData =
| { acceptanceId: string; checkId: string; type: PortalViewType.AcceptanceCheck }
| { agentId: string; type: PortalViewType.AgentDetail }
| { artifact: PortalArtifact; type: PortalViewType.Artifact }
+ | { runId?: string; type: PortalViewType.DashboardWidget; widgetId: string }
| { agentDocumentId?: string; documentId: string; type: PortalViewType.Document }
| { type: PortalViewType.Notebook }
| { file: PortalFile; type: PortalViewType.FilePreview }
diff --git a/src/store/chat/slices/portal/selectors.ts b/src/store/chat/slices/portal/selectors.ts
index 55e1a63cd69..b9e321443e6 100644
--- a/src/store/chat/slices/portal/selectors.ts
+++ b/src/store/chat/slices/portal/selectors.ts
@@ -263,6 +263,8 @@ const taskResultId = (s: ChatStoreState): string | undefined => {
return view?.taskId;
};
+const dashboardWidgetView = (s: ChatStoreState) => getViewData(s, PortalViewType.DashboardWidget);
+
// Goal detail drill-down selectors
const goalPortalId = (s: ChatStoreState): string | undefined =>
getViewData(s, PortalViewType.Goal)?.goalId;
@@ -355,6 +357,7 @@ export const chatPortalSelectors = {
// Goal drill-down data
goalMetricView,
+ dashboardWidgetView,
goalNodeView,
goalPortalId,
goalReportChapterView,
diff --git a/src/store/dashboard/index.ts b/src/store/dashboard/index.ts
new file mode 100644
index 00000000000..155604f66be
--- /dev/null
+++ b/src/store/dashboard/index.ts
@@ -0,0 +1,9 @@
+import { useDashboardStore } from './store';
+
+export const getDashboardStoreState = () => useDashboardStore.getState();
+
+export { dashboardLevelKey } from './initialState';
+export { widgetTrendSource } from './projection';
+export { dashboardSelectors } from './selectors';
+export type { DashboardAction, DashboardRequest, DashboardStore } from './store';
+export { useDashboardStore } from './store';
diff --git a/src/store/dashboard/initialState.ts b/src/store/dashboard/initialState.ts
new file mode 100644
index 00000000000..db0444b8cc5
--- /dev/null
+++ b/src/store/dashboard/initialState.ts
@@ -0,0 +1,103 @@
+import type { WidgetLevelFilter } from '@lobechat/types';
+
+import { createReplicaState, type ReplicaState } from '@/libs/replica';
+import type {
+ DashboardDetail,
+ DashboardListItem,
+ DashboardTrendSeries,
+ DashboardWidgetDetail,
+ DashboardWidgetItem,
+ DashboardWidgetRunDetail,
+ DashboardWidgetRunItem,
+ DashboardWidgetVersionItem,
+} from '@/services/dashboard';
+
+export interface DashboardState {
+ /** A create request is in flight (no persistent id to key it by yet). */
+ dashboardCreating: boolean;
+ /** Boards with their placed widgets, keyed by dashboard id. */
+ dashboardDetailMap: Record<string, DashboardDetail>;
+ /** Replica bookkeeping for `dashboardDetailMap`. */
+ dashboardDetailReplica: ReplicaState<DashboardDetail>;
+ /** Boards whose layout save is in flight. */
+ dashboardLayoutSavingIds: string[];
+ /** Board lists keyed by `dashboardLevelKey` — each level lists only what lives directly on it. */
+ dashboardListByLevel: Record<string, DashboardListItem[]>;
+ /** Replica bookkeeping for `dashboardListByLevel`. */
+ dashboardListReplica: ReplicaState<DashboardListItem[]>;
+ /** Every board of a project (with or without an agent), keyed by project id. */
+ projectDashboardsMap: Record<string, DashboardListItem[]>;
+ /** Replica bookkeeping for `projectDashboardsMap`. */
+ projectDashboardsReplica: ReplicaState<DashboardListItem[]>;
+ /** Every widget of a project (with or without an agent), keyed by project id. */
+ projectWidgetsMap: Record<string, DashboardWidgetItem[]>;
+ /** Replica bookkeeping for `projectWidgetsMap`. */
+ projectWidgetsReplica: ReplicaState<DashboardWidgetItem[]>;
+ /** Widgets with a board placement request in flight. */
+ widgetAddingIds: string[];
+ /** Widgets opened on their own (outside a board), keyed by widget id. */
+ widgetDetailMap: Record<string, DashboardWidgetDetail>;
+ /** Replica bookkeeping for `widgetDetailMap`. */
+ widgetDetailReplica: ReplicaState<DashboardWidgetDetail>;
+ /**
+ * The preview run behind a publish approval, keyed `<widgetId>:<versionId>`
+ * — fetched by version (not window-limited), and `null` when the version has
+ * no usable preview run.
+ */
+ widgetPreviewRunMap: Record<string, DashboardWidgetRunDetail | null>;
+ /** Replica bookkeeping for `widgetPreviewRunMap`. */
+ widgetPreviewRunReplica: ReplicaState<DashboardWidgetRunDetail | null>;
+ /** Widgets with a publish request in flight. */
+ widgetPublishingIds: string[];
+ /** Single runs with output and logs, keyed by run id. */
+ widgetRunDetailMap: Record<string, DashboardWidgetRunDetail>;
+ /** Replica bookkeeping for `widgetRunDetailMap`. */
+ widgetRunDetailReplica: ReplicaState<DashboardWidgetRunDetail>;
+ /** Widgets with a manual refresh in flight from this client. */
+ widgetRunningIds: string[];
+ /** Recent run history, newest first, keyed by widget id. */
+ widgetRunsMap: Record<string, DashboardWidgetRunItem[]>;
+ /** Replica bookkeeping for `widgetRunsMap`. */
+ widgetRunsReplica: ReplicaState<DashboardWidgetRunItem[]>;
+ /** Long-term metric trend, keyed by widget id. */
+ widgetTrendMap: Record<string, DashboardTrendSeries[]>;
+ /** Replica bookkeeping for `widgetTrendMap`. */
+ widgetTrendReplica: ReplicaState<DashboardTrendSeries[]>;
+ /** Version history, newest first, keyed by widget id. */
+ widgetVersionsMap: Record<string, DashboardWidgetVersionItem[]>;
+ /** Replica bookkeeping for `widgetVersionsMap`. */
+ widgetVersionsReplica: ReplicaState<DashboardWidgetVersionItem[]>;
+}
+
+export const initialState: DashboardState = {
+ dashboardCreating: false,
+ dashboardDetailMap: {},
+ dashboardDetailReplica: createReplicaState(),
+ dashboardLayoutSavingIds: [],
+ dashboardListByLevel: {},
+ dashboardListReplica: createReplicaState(),
+ projectDashboardsMap: {},
+ projectDashboardsReplica: createReplicaState(),
+ projectWidgetsMap: {},
+ projectWidgetsReplica: createReplicaState(),
+ widgetAddingIds: [],
+ widgetDetailMap: {},
+ widgetDetailReplica: createReplicaState(),
+ widgetPublishingIds: [],
+ widgetPreviewRunMap: {},
+ widgetPreviewRunReplica: createReplicaState(),
+ widgetRunDetailMap: {},
+ widgetRunDetailReplica: createReplicaState(),
+ widgetRunningIds: [],
+ widgetRunsMap: {},
+ widgetRunsReplica: createReplicaState(),
+ widgetTrendMap: {},
+ widgetTrendReplica: createReplicaState(),
+ widgetVersionsMap: {},
+ widgetVersionsReplica: createReplicaState(),
+};
+
+/** Personal (or current-workspace) level when neither id is set. */
+export const dashboardLevelKey = ({ agentId, projectId }: WidgetLevelFilter = {}) =>
+ [projectId && `project:${projectId}`, agentId && `agent:${agentId}`].filter(Boolean).join('/') ||
+ 'personal';
diff --git a/src/store/dashboard/projection.ts b/src/store/dashboard/projection.ts
new file mode 100644
index 00000000000..3f152113a4b
--- /dev/null
+++ b/src/store/dashboard/projection.ts
@@ -0,0 +1,174 @@
+import type { WidgetLevelFilter } from '@lobechat/types';
+
+import { defineReplica } from '@/libs/replica';
+import {
+ type DashboardDetail,
+ type DashboardListItem,
+ dashboardService,
+ type DashboardTrendSeries,
+ type DashboardWidgetDetail,
+ type DashboardWidgetItem,
+ type DashboardWidgetRunDetail,
+ type DashboardWidgetRunItem,
+ type DashboardWidgetVersionItem,
+} from '@/services/dashboard';
+import { isTrpcErrorCode } from '@/utils/trpcError';
+
+import { dashboardLevelKey } from './initialState';
+
+export type {
+ DashboardDetail,
+ DashboardListItem,
+ DashboardTrendSeries,
+ DashboardWidgetDetail,
+ DashboardWidgetItem,
+ DashboardWidgetRunDetail,
+ DashboardWidgetRunItem,
+ DashboardWidgetVersionItem,
+} from '@/services/dashboard';
+
+/**
+ * What a widget's trend is computed from: a stat records one point per run into
+ * its primary metric; a series appends into one `series:<name>` metric per
+ * series; list / table outputs have no trend.
+ */
+export const widgetTrendSource = (widget: DashboardWidgetItem): string | undefined => {
+ const output = widget.latestOutput;
+ if (output?.type === 'series') {
+ const names = output.series.map((series) => series.name);
+ return names.length > 0 ? `series:${names.join('\u0000')}` : undefined;
+ }
+ if (output?.type === 'stat' && widget.metricId) return `metric:${widget.metricId}`;
+ return undefined;
+};
+
+/** The board lists a level owns directly, one entry per `dashboardLevelKey`. */
+export const dashboardListResource = defineReplica<WidgetLevelFilter, DashboardListItem[]>({
+ fetcher: (level) => dashboardService.list(level ?? {}),
+ key: (level) => dashboardLevelKey(level),
+ name: 'dashboardList',
+ storage: 'indexedDB',
+ version: 1,
+});
+
+/** Every board of a project (agent-owned ones included), one entry per project. */
+export const projectDashboardListResource = defineReplica<string, DashboardListItem[]>({
+ fetcher: (projectId) => dashboardService.listByProject(projectId),
+ key: (projectId) => projectId,
+ name: 'projectDashboardList',
+ storage: 'indexedDB',
+ version: 1,
+});
+
+/** Every widget of a project (placed or not), one entry per project. */
+export const projectWidgetListResource = defineReplica<string, DashboardWidgetItem[]>({
+ fetcher: (projectId) => dashboardService.listWidgetsByProject(projectId),
+ key: (projectId) => projectId,
+ name: 'projectWidgetList',
+ storage: 'indexedDB',
+ version: 1,
+});
+
+/** One board with its placed widgets, one entry per board id. */
+export const dashboardDetailResource = defineReplica<string, DashboardDetail>({
+ fetcher: (dashboardId) => dashboardService.detail(dashboardId),
+ key: (dashboardId) => dashboardId,
+ name: 'dashboardDetail',
+ storage: 'indexedDB',
+ version: 1,
+});
+
+/** One widget on its own — a draft an agent wrote, before any board shows it. */
+export const widgetDetailResource = defineReplica<string, DashboardWidgetDetail>({
+ fetcher: (widgetId) => dashboardService.widgetDetail(widgetId),
+ key: (widgetId) => widgetId,
+ name: 'widgetDetail',
+ storage: 'indexedDB',
+ version: 1,
+});
+
+/** A widget's version history, newest first (the router returns the whole list). */
+export const widgetVersionsResource = defineReplica<string, DashboardWidgetVersionItem[]>({
+ fetcher: (widgetId) => dashboardService.listVersions(widgetId),
+ key: (widgetId) => widgetId,
+ name: 'widgetVersions',
+ storage: 'indexedDB',
+ version: 1,
+});
+
+/**
+ * A widget's recent runs, newest first. `listRuns` takes no cursor, so the
+ * window is the server's (capped), not a page a client can walk — a plain list
+ * replica, not a paged one.
+ */
+export const widgetRunsResource = defineReplica<string, DashboardWidgetRunItem[]>({
+ fetcher: (widgetId) => dashboardService.listRuns(widgetId, 30),
+ key: (widgetId) => widgetId,
+ name: 'widgetRuns',
+ storage: 'indexedDB',
+ version: 1,
+});
+
+export interface WidgetRunParams {
+ runId: string;
+ widgetId: string;
+}
+
+/** One run with its output and logs; keyed by run id (ids are globally unique). */
+export const widgetRunResource = defineReplica<WidgetRunParams, DashboardWidgetRunDetail>({
+ fetcher: ({ runId, widgetId }) => dashboardService.getRun(widgetId, runId),
+ key: ({ runId }) => runId,
+ name: 'widgetRun',
+ storage: 'memory',
+ version: 1,
+});
+
+export interface WidgetPreviewRunParams {
+ versionId: string;
+ widgetId: string;
+}
+
+/**
+ * The preview run behind a publish approval, by version: not window-limited,
+ * so the card survives run-history rollover. A version with no usable preview
+ * run is a normal state, not an error, so it settles to `null`.
+ */
+export const widgetPreviewRunResource = defineReplica<
+ WidgetPreviewRunParams,
+ DashboardWidgetRunDetail | null
+>({
+ fetcher: async ({ versionId, widgetId }) => {
+ try {
+ return await dashboardService.getPreviewRun(widgetId, versionId);
+ } catch (error) {
+ if (isTrpcErrorCode(error, 'NOT_FOUND')) return null;
+ throw error;
+ }
+ },
+ key: ({ versionId, widgetId }) => `${widgetId}:${versionId}`,
+ name: 'widgetPreviewRun',
+ storage: 'memory',
+ version: 1,
+});
+
+/**
+ * A widget's long-term trend, keyed by widget and read from the metrics the
+ * runs recorded into. `source` is the query identity: a widget whose output
+ * shape (or metric) changed must not hydrate the previous trend.
+ */
+export const widgetTrendResource = defineReplica<DashboardWidgetItem, DashboardTrendSeries[]>({
+ fetcher: async (widget) => {
+ const output = widget.latestOutput;
+ return output?.type === 'series'
+ ? dashboardService.seriesTrend(
+ widget.id,
+ output.series.map((series) => series.name),
+ )
+ : dashboardService.metricTrend(widget.metricId!);
+ },
+ key: (widget) => widget.id,
+ name: 'widgetTrend',
+ query: (widget) => widgetTrendSource(widget),
+ storage: 'indexedDB',
+ version: 1,
+});
diff --git a/src/store/dashboard/selectors.test.ts b/src/store/dashboard/selectors.test.ts
new file mode 100644
index 00000000000..02df40ca6af
--- /dev/null
+++ b/src/store/dashboard/selectors.test.ts
@@ -0,0 +1,61 @@
+import { describe, expect, it } from 'vitest';
+
+import type { DashboardStore } from './action';
+import { dashboardSelectors } from './selectors';
+
+const storeWith = (userId: string) =>
+ ({ dashboardDetailMap: { d1: { id: 'd1', items: [], userId } } }) as unknown as DashboardStore;
+
+describe('dashboardSelectors.canManageDashboard', () => {
+ it('offers layout editing to the board creator only', () => {
+ expect(dashboardSelectors.canManageDashboard('d1', 'u-owner')(storeWith('u-owner'))).toBe(true);
+ expect(dashboardSelectors.canManageDashboard('d1', 'u-member')(storeWith('u-owner'))).toBe(
+ false,
+ );
+ });
+
+ it('offers nothing after a workspace demotion, whatever the ownership', () => {
+ // The demoted creator is still dashboard.userId; without create_content
+ // the server refuses their writes, so no editor either.
+ expect(
+ dashboardSelectors.canManageDashboard('d1', 'u-owner', false)(storeWith('u-owner')),
+ ).toBe(false);
+ });
+
+ it('offers nothing before the board or the user is known', () => {
+ expect(dashboardSelectors.canManageDashboard('d1', undefined)(storeWith('u-owner'))).toBe(
+ false,
+ );
+ expect(dashboardSelectors.canManageDashboard('d2', 'u-owner')(storeWith('u-owner'))).toBe(
+ false,
+ );
+ });
+});
+
+describe('dashboardSelectors.isDashboardOutsideProject', () => {
+ const storeWithProject = (projectId: string | null) =>
+ ({
+ dashboardDetailMap: { d1: { id: 'd1', items: [], projectId, userId: 'u' } },
+ }) as unknown as DashboardStore;
+
+ it('accepts a board of the route project', () => {
+ expect(dashboardSelectors.isDashboardOutsideProject('d1', 'p1')(storeWithProject('p1'))).toBe(
+ false,
+ );
+ });
+
+ it('rejects a home board and another project board', () => {
+ expect(dashboardSelectors.isDashboardOutsideProject('d1', 'p1')(storeWithProject(null))).toBe(
+ true,
+ );
+ expect(dashboardSelectors.isDashboardOutsideProject('d1', 'p1')(storeWithProject('p2'))).toBe(
+ true,
+ );
+ });
+
+ it('waits for the board to load', () => {
+ expect(dashboardSelectors.isDashboardOutsideProject('d2', 'p1')(storeWithProject('p2'))).toBe(
+ false,
+ );
+ });
+});
diff --git a/src/store/dashboard/selectors.ts b/src/store/dashboard/selectors.ts
new file mode 100644
index 00000000000..da37444e6ce
--- /dev/null
+++ b/src/store/dashboard/selectors.ts
@@ -0,0 +1,91 @@
+import type { WidgetLevelFilter } from '@lobechat/types';
+
+import { dashboardLevelKey } from './initialState';
+import type { DashboardStore } from './store';
+
+const EMPTY: never[] = [];
+
+const dashboardList = (level?: WidgetLevelFilter) => (s: DashboardStore) =>
+ s.dashboardListByLevel[dashboardLevelKey(level)] ?? EMPTY;
+
+const projectDashboards = (projectId?: string) => (s: DashboardStore) =>
+ (projectId && s.projectDashboardsMap[projectId]) || EMPTY;
+
+const projectWidgets = (projectId?: string) => (s: DashboardStore) =>
+ (projectId && s.projectWidgetsMap[projectId]) || EMPTY;
+
+const dashboardDetail = (dashboardId?: string) => (s: DashboardStore) =>
+ dashboardId ? s.dashboardDetailMap[dashboardId] : undefined;
+
+/**
+ * Whether a loaded board lives somewhere other than this project (a home board
+ * or another project's), so a project route must not show it as its own.
+ * False until the board has loaded.
+ */
+const isDashboardOutsideProject =
+ (dashboardId: string, projectId: string) => (s: DashboardStore) => {
+ const detail = s.dashboardDetailMap[dashboardId];
+ return !!detail && detail.projectId !== projectId;
+ };
+
+/** A placed widget's hot read model, looked up across the boards already loaded. */
+const widgetById = (dashboardId: string, widgetId?: string) => (s: DashboardStore) =>
+ widgetId
+ ? s.dashboardDetailMap[dashboardId]?.items.find(({ widget }) => widget.id === widgetId)?.widget
+ : undefined;
+
+/**
+ * Only a board's creator can change it (`DashboardModel` write rule), and
+ * only with the create_content permission — a demoted owner keeps ownership
+ * but the server refuses their writes, so the layout editor is offered to
+ * them alone no more than the rename/trash menu is.
+ */
+const canManageDashboard =
+ (dashboardId: string, userId?: string, canWrite = true) =>
+ (s: DashboardStore) =>
+ !!userId && canWrite && s.dashboardDetailMap[dashboardId]?.userId === userId;
+
+const isWidgetRunning = (widgetId: string) => (s: DashboardStore) =>
+ s.widgetRunningIds.includes(widgetId);
+
+const isLayoutSaving = (dashboardId: string) => (s: DashboardStore) =>
+ s.dashboardLayoutSavingIds.includes(dashboardId);
+
+const widgetRuns = (widgetId?: string) => (s: DashboardStore) =>
+ (widgetId && s.widgetRunsMap[widgetId]) || EMPTY;
+
+const widgetVersions = (widgetId?: string) => (s: DashboardStore) =>
+ (widgetId && s.widgetVersionsMap[widgetId]) || EMPTY;
+
+const widgetTrend = (widgetId: string) => (s: DashboardStore) => s.widgetTrendMap[widgetId];
+
+const widgetDetail = (widgetId?: string) => (s: DashboardStore) =>
+ widgetId ? s.widgetDetailMap[widgetId] : undefined;
+
+const widgetRunDetail = (runId?: string) => (s: DashboardStore) =>
+ runId ? s.widgetRunDetailMap[runId] : undefined;
+
+const isWidgetPublishing = (widgetId: string) => (s: DashboardStore) =>
+ s.widgetPublishingIds.includes(widgetId);
+
+const isWidgetAdding = (widgetId: string) => (s: DashboardStore) =>
+ s.widgetAddingIds.includes(widgetId);
+
+export const dashboardSelectors = {
+ canManageDashboard,
+ dashboardDetail,
+ dashboardList,
+ isDashboardOutsideProject,
+ isLayoutSaving,
+ isWidgetAdding,
+ isWidgetPublishing,
+ isWidgetRunning,
+ projectDashboards,
+ projectWidgets,
+ widgetById,
+ widgetDetail,
+ widgetRunDetail,
+ widgetRuns,
+ widgetTrend,
+ widgetVersions,
+};
diff --git a/src/store/dashboard/store.test.ts b/src/store/dashboard/store.test.ts
new file mode 100644
index 00000000000..3849dd6f998
--- /dev/null
+++ b/src/store/dashboard/store.test.ts
@@ -0,0 +1,254 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { mutate } from '@/libs/swr';
+import { dashboardService } from '@/services/dashboard';
+
+import { useDashboardStore } from './index';
+import { dashboardLevelKey, initialState } from './initialState';
+import { widgetTrendSource } from './projection';
+
+vi.mock('@/libs/swr', () => ({
+ mutate: vi.fn(),
+ useClientDataSWR: vi.fn(),
+}));
+vi.mock('@/services/dashboard', () => ({
+ dashboardService: {
+ addItem: vi.fn(),
+ create: vi.fn(),
+ getPreviewRun: vi.fn(),
+ publish: vi.fn(),
+ removeItems: vi.fn(),
+ rename: vi.fn(),
+ runWidget: vi.fn(),
+ trash: vi.fn(),
+ updateItemLayouts: vi.fn(),
+ },
+}));
+
+const widget = (patch: Record<string, unknown> = {}) =>
+ ({ id: 'w1', latestOutput: null, metricId: null, ...patch }) as any;
+
+const board = (patch: Record<string, unknown> = {}) =>
+ ({ id: 'd1', projectId: null, title: 'Ops', userId: 'u1', ...patch }) as any;
+
+const detail = {
+ id: 'd1',
+ projectId: null,
+ title: 'Ops',
+ userId: 'u1',
+ items: [
+ { item: { id: 'i1', layout: { h: 2, w: 3, x: 0, y: 0 }, sortOrder: 0 }, widget: widget() },
+ {
+ item: { id: 'i2', layout: null, sortOrder: 1 },
+ widget: widget({ id: 'w2', lastRunStatus: 'running' }),
+ },
+ ],
+} as any;
+
+beforeEach(() => {
+ vi.clearAllMocks();
+ useDashboardStore.setState(initialState);
+});
+
+describe('dashboardLevelKey', () => {
+ it('names the personal level and scoped levels distinctly', () => {
+ expect(dashboardLevelKey()).toBe('personal');
+ expect(dashboardLevelKey({ projectId: 'p' })).toBe('project:p');
+ expect(dashboardLevelKey({ agentId: 'a', projectId: 'p' })).toBe('project:p/agent:a');
+ });
+});
+
+describe('widgetTrendSource', () => {
+ it('reads a stat trend from its primary metric', () => {
+ expect(
+ widgetTrendSource(widget({ latestOutput: { type: 'stat', value: 1 }, metricId: 'm1' })),
+ ).toBe('metric:m1');
+ });
+
+ it('reads a series trend from its per-series metrics', () => {
+ expect(
+ widgetTrendSource(
+ widget({ latestOutput: { series: [{ name: 'a' }, { name: 'b' }], type: 'series' } }),
+ ),
+ ).toBe('series:a\u0000b');
+ });
+
+ it('has no trend for list / table outputs', () => {
+ expect(
+ widgetTrendSource(widget({ latestOutput: { items: [], type: 'list' }, metricId: 'm1' })),
+ ).toBeUndefined();
+ });
+
+ it('has no stat trend without a metric', () => {
+ expect(widgetTrendSource(widget({ latestOutput: { type: 'stat', value: 1 } }))).toBeUndefined();
+ });
+});
+
+describe('board entity propagation', () => {
+ it('renames the board in every loaded projection at once', async () => {
+ useDashboardStore.setState({
+ dashboardDetailMap: { d1: detail },
+ dashboardListByLevel: { personal: [board()] },
+ projectDashboardsMap: { p1: [board({ projectId: 'p1' })] },
+ });
+ vi.mocked(dashboardService.rename).mockResolvedValue(undefined as any);
+
+ await useDashboardStore.getState().renameDashboard('d1', 'Renamed', {});
+
+ const state = useDashboardStore.getState();
+ expect(state.dashboardDetailMap.d1.title).toBe('Renamed');
+ // The detail's `items` survive the board patch.
+ expect(state.dashboardDetailMap.d1.items).toHaveLength(2);
+ expect(state.dashboardListByLevel.personal[0].title).toBe('Renamed');
+ expect(state.projectDashboardsMap.p1[0].title).toBe('Renamed');
+ });
+
+ it('drops the board from the loaded lists when trashed', async () => {
+ useDashboardStore.setState({
+ dashboardDetailMap: { d1: detail },
+ dashboardListByLevel: { personal: [board()] },
+ });
+ vi.mocked(dashboardService.trash).mockResolvedValue(undefined as any);
+
+ await useDashboardStore.getState().trashDashboard('d1', {});
+
+ const state = useDashboardStore.getState();
+ expect(state.dashboardListByLevel.personal).toEqual([]);
+ expect(state.dashboardDetailMap.d1).toBeUndefined();
+ });
+});
+
+describe('createDashboard', () => {
+ it('creates the board and revalidates the level it was created on', async () => {
+ vi.mocked(dashboardService.create).mockResolvedValue(board() as any);
+
+ await useDashboardStore.getState().createDashboard({ title: 'Ops' });
+
+ expect(dashboardService.create).toHaveBeenCalledWith({ title: 'Ops' });
+ expect(mutate).toHaveBeenCalled();
+ expect(useDashboardStore.getState().dashboardCreating).toBe(false);
+ });
+
+ it('clears the creating flag when the server refuses', async () => {
+ vi.mocked(dashboardService.create).mockRejectedValue(new Error('nope'));
+
+ await expect(useDashboardStore.getState().createDashboard({ title: 'Ops' })).rejects.toThrow(
+ 'nope',
+ );
+ expect(useDashboardStore.getState().dashboardCreating).toBe(false);
+ });
+});
+
+describe('saveDashboardLayout', () => {
+ it('renders the new cells before the server confirms', async () => {
+ useDashboardStore.setState({ dashboardDetailMap: { d1: detail } });
+ let resolveSave: () => void = () => {};
+ vi.mocked(dashboardService.updateItemLayouts).mockReturnValue(
+ new Promise<void>((resolve) => {
+ resolveSave = () => resolve();
+ }) as any,
+ );
+
+ const pending = useDashboardStore
+ .getState()
+ .saveDashboardLayout('d1', { i1: { h: 4, w: 4, x: 0, y: 0 } }, ['i2', 'i1']);
+
+ // Optimistic: the dragged layout is on screen while the write is in flight.
+ const optimistic = useDashboardStore.getState().dashboardDetailMap.d1;
+ expect(optimistic.items[0].item.id).toBe('i2');
+ expect(optimistic.items[1].item.layout).toEqual({ h: 4, w: 4, x: 0, y: 0 });
+ expect(useDashboardStore.getState().dashboardLayoutSavingIds).toEqual(['d1']);
+
+ resolveSave();
+ await pending;
+ expect(useDashboardStore.getState().dashboardLayoutSavingIds).toEqual([]);
+ });
+
+ it('revalidates the board when the save is refused', async () => {
+ useDashboardStore.setState({ dashboardDetailMap: { d1: detail } });
+ vi.mocked(dashboardService.updateItemLayouts).mockRejectedValue(new Error('read only'));
+
+ await expect(
+ useDashboardStore.getState().saveDashboardLayout('d1', { i1: null as any }, ['i1']),
+ ).rejects.toThrow('read only');
+ expect(mutate).toHaveBeenCalled();
+ expect(useDashboardStore.getState().dashboardLayoutSavingIds).toEqual([]);
+ });
+});
+
+describe('runWidget', () => {
+ it('flags the widget while the run is in flight and refreshes it after', async () => {
+ let resolveRun: (value: unknown) => void = () => {};
+ vi.mocked(dashboardService.runWidget).mockReturnValue(
+ new Promise((resolve) => {
+ resolveRun = resolve;
+ }) as any,
+ );
+
+ const pending = useDashboardStore.getState().runWidget('w1');
+ expect(useDashboardStore.getState().widgetRunningIds).toEqual(['w1']);
+
+ resolveRun({ id: 'r1', status: 'succeeded' });
+ await pending;
+
+ expect(useDashboardStore.getState().widgetRunningIds).toEqual([]);
+ // Every surface showing the widget is revalidated, succeeded or not.
+ expect(mutate).toHaveBeenCalled();
+ });
+
+ it('still refreshes when the run itself fails', async () => {
+ vi.mocked(dashboardService.runWidget).mockRejectedValue(new Error('sandbox down'));
+
+ await expect(useDashboardStore.getState().runWidget('w1')).rejects.toThrow('sandbox down');
+ expect(useDashboardStore.getState().widgetRunningIds).toEqual([]);
+ expect(mutate).toHaveBeenCalled();
+ });
+});
+
+describe('publishWidgetVersion', () => {
+ it('publishes, revalidates the versions and runs the widget once', async () => {
+ vi.mocked(dashboardService.publish).mockResolvedValue({ version: { version: 4 } } as any);
+ vi.mocked(dashboardService.runWidget).mockResolvedValue({ id: 'r1' } as any);
+
+ await useDashboardStore.getState().publishWidgetVersion('w1', 'v4');
+
+ expect(dashboardService.publish).toHaveBeenCalledWith('w1', 'v4');
+ expect(dashboardService.runWidget).toHaveBeenCalledWith('w1');
+ expect(useDashboardStore.getState().widgetPublishingIds).toEqual([]);
+ });
+
+ it('keeps the publish when the first run fails', async () => {
+ vi.mocked(dashboardService.publish).mockResolvedValue({ version: { version: 4 } } as any);
+ vi.mocked(dashboardService.runWidget).mockRejectedValue(new Error('sandbox down'));
+ const consoleError = vi.spyOn(console, 'error').mockImplementation(() => {});
+
+ await expect(useDashboardStore.getState().publishWidgetVersion('w1', 'v4')).resolves.toEqual({
+ version: { version: 4 },
+ });
+
+ expect(useDashboardStore.getState().widgetPublishingIds).toEqual([]);
+ consoleError.mockRestore();
+ });
+});
+
+describe('addWidgetToDashboard', () => {
+ it('places the widget and revalidates the board and the widget', async () => {
+ vi.mocked(dashboardService.addItem).mockResolvedValue({ id: 'i1' } as any);
+
+ await useDashboardStore.getState().addWidgetToDashboard('d1', 'w1');
+
+ expect(dashboardService.addItem).toHaveBeenCalledWith('d1', 'w1');
+ expect(mutate).toHaveBeenCalled();
+ expect(useDashboardStore.getState().widgetAddingIds).toEqual([]);
+ });
+});
+
+describe('refreshWidgetPlacement', () => {
+ it('revalidates the widget, the board and every board list', async () => {
+ await useDashboardStore.getState().refreshWidgetPlacement('w1', 'd1');
+
+ // One revalidate per affected resource: widget detail, board detail, both
+ // board lists and the project widget list.
+ expect(vi.mocked(mutate).mock.calls.length).toBeGreaterThanOrEqual(5);
+ });
+});
diff --git a/src/store/dashboard/store.ts b/src/store/dashboard/store.ts
new file mode 100644
index 00000000000..d92efdfef64
--- /dev/null
+++ b/src/store/dashboard/store.ts
@@ -0,0 +1,537 @@
+'use client';
+
+import type { DashboardItemLayout, WidgetLevelFilter } from '@lobechat/types';
+import { shallow } from 'zustand/shallow';
+import { createWithEqualityFn } from 'zustand/traditional';
+
+import {
+ arrayEntity,
+ createReplicaSlice,
+ linkReplicaEntity,
+ recordLens,
+ type ReplicaSyncResult,
+ singleEntity,
+} from '@/libs/replica';
+import {
+ type CreateDashboardParams,
+ type DashboardLayoutPatch,
+ dashboardService,
+} from '@/services/dashboard';
+import { createDevtools } from '@/store/middleware/createDevtools';
+import { expose } from '@/store/middleware/expose';
+
+import { dashboardLevelKey, type DashboardState, initialState } from './initialState';
+import {
+ type DashboardDetail,
+ dashboardDetailResource,
+ type DashboardListItem,
+ dashboardListResource,
+ type DashboardTrendSeries,
+ type DashboardWidgetDetail,
+ type DashboardWidgetItem,
+ type DashboardWidgetRunDetail,
+ type DashboardWidgetRunItem,
+ type DashboardWidgetVersionItem,
+ projectDashboardListResource,
+ projectWidgetListResource,
+ widgetDetailResource,
+ widgetPreviewRunResource,
+ widgetRunResource,
+ widgetRunsResource,
+ widgetTrendResource,
+ widgetVersionsResource,
+} from './projection';
+
+export { widgetTrendSource } from './projection';
+export type {
+ DashboardDetail,
+ DashboardListItem,
+ DashboardTrendSeries,
+ DashboardWidgetDetail,
+ DashboardWidgetItem,
+ DashboardWidgetRunDetail,
+ DashboardWidgetRunItem,
+ DashboardWidgetVersionItem,
+};
+
+/** Poll a board while one of its widgets is mid-run, so the card settles on its own. */
+const RUNNING_POLL_INTERVAL = 3000;
+/**
+ * Slow baseline poll for boards with a scheduled run pending: a scheduled
+ * widget can start after an idle load, when the cached projection still says
+ * nothing is running — the baseline observes the transition. The driver only
+ * fires it while the tab is visible, so hidden boards cost nothing.
+ */
+const IDLE_POLL_INTERVAL = 30_000;
+
+const hasRunningWidget = (detail?: DashboardDetail) =>
+ !!detail?.items.some(({ widget }) => widget.lastRunStatus === 'running');
+
+const hasScheduledWidget = (detail?: DashboardDetail) =>
+ !!detail?.items.some(({ widget }) => widget.nextRunAt != null);
+
+/**
+ * What a migrated read hook hands back. Same shape the SWR hooks returned, so
+ * call sites keep reading `data` / `error` / `isLoading` / `mutate`; `data` is
+ * the replica's store projection, not the fetch response — a persisted entry
+ * therefore paints on the first frame instead of after the request.
+ */
+export interface DashboardRequest<TData> {
+ data: TData | undefined;
+ error: unknown;
+ isLoading: boolean;
+ isValidating: boolean;
+ mutate: () => Promise<unknown>;
+}
+
+const toRequest = <TData>(
+ sync: ReplicaSyncResult,
+ data: TData | undefined,
+): DashboardRequest<TData> => ({
+ data,
+ error: sync.error,
+ isLoading: !sync.isHydrated || (data === undefined && sync.isValidating),
+ isValidating: sync.isValidating,
+ mutate: sync.revalidate,
+});
+
+export interface DashboardAction {
+ addWidgetToDashboard: (dashboardId: string, widgetId: string) => Promise<unknown>;
+ createDashboard: (params: CreateDashboardParams) => Promise<DashboardListItem>;
+ publishWidgetVersion: (
+ widgetId: string,
+ versionId: string,
+ ) => Promise<Awaited<ReturnType<typeof dashboardService.publish>>>;
+ refreshDashboardDetail: (dashboardId: string) => Promise<unknown>;
+ refreshDashboards: (level?: WidgetLevelFilter) => Promise<unknown>;
+ refreshWidget: (widgetId: string) => Promise<unknown>;
+ refreshWidgetDetail: (widgetId: string) => Promise<unknown>;
+ /** The agent placed a widget server-side: revalidate everything that shows it. */
+ refreshWidgetPlacement: (widgetId: string, dashboardId?: string) => Promise<unknown>;
+ removeWidgetFromDashboard: (dashboardId: string, itemId: string) => Promise<void>;
+ renameDashboard: (dashboardId: string, title: string, level?: WidgetLevelFilter) => Promise<void>;
+ runWidget: (widgetId: string) => Promise<DashboardWidgetRunItem | undefined>;
+ saveDashboardLayout: (
+ dashboardId: string,
+ layouts: Record<string, DashboardItemLayout>,
+ order: string[],
+ ) => Promise<void>;
+ trashDashboard: (dashboardId: string, level?: WidgetLevelFilter) => Promise<void>;
+ /** Fetch orchestration only; read the board with `dashboardSelectors.dashboardDetail`. */
+ useFetchDashboardDetail: (dashboardId?: string) => DashboardRequest<DashboardDetail>;
+ useFetchDashboards: (
+ level?: WidgetLevelFilter,
+ enabled?: boolean,
+ ) => DashboardRequest<DashboardListItem[]>;
+ useFetchProjectDashboards: (projectId?: string) => DashboardRequest<DashboardListItem[]>;
+ useFetchProjectWidgets: (projectId?: string) => DashboardRequest<DashboardWidgetItem[]>;
+ useFetchWidgetDetail: (widgetId?: string) => DashboardRequest<DashboardWidgetDetail>;
+ useFetchWidgetRun: (
+ widgetId?: string,
+ runId?: string,
+ ) => DashboardRequest<DashboardWidgetRunDetail>;
+ useFetchWidgetRuns: (widgetId?: string) => DashboardRequest<DashboardWidgetRunItem[]>;
+ useFetchWidgetTrend: (widget?: DashboardWidgetItem) => DashboardRequest<DashboardTrendSeries[]>;
+ useFetchWidgetVersionPreviewRun: (
+ widgetId?: string,
+ versionId?: string,
+ ) => DashboardRequest<DashboardWidgetRunDetail | null>;
+ useFetchWidgetVersions: (widgetId?: string) => DashboardRequest<DashboardWidgetVersionItem[]>;
+}
+
+export type DashboardStore = DashboardState & DashboardAction;
+
+const devtools = createDevtools('dashboard');
+
+export const useDashboardStore = createWithEqualityFn<DashboardStore>()(
+ devtools((set, get): DashboardStore => {
+ const list = createReplicaSlice(dashboardListResource, {
+ actionPrefix: 'dashboard/list',
+ entity: arrayEntity<DashboardListItem>((board) => board.id),
+ get,
+ set,
+ stateKey: 'dashboardListReplica',
+ view: recordLens<DashboardStore, DashboardListItem[]>('dashboardListByLevel'),
+ });
+ const projectList = createReplicaSlice(projectDashboardListResource, {
+ actionPrefix: 'dashboard/projectList',
+ entity: arrayEntity<DashboardListItem>((board) => board.id),
+ get,
+ set,
+ stateKey: 'projectDashboardsReplica',
+ view: recordLens<DashboardStore, DashboardListItem[]>('projectDashboardsMap'),
+ });
+ const projectWidgets = createReplicaSlice(projectWidgetListResource, {
+ actionPrefix: 'dashboard/projectWidgets',
+ entity: arrayEntity<DashboardWidgetItem>((widget) => widget.id),
+ get,
+ set,
+ stateKey: 'projectWidgetsReplica',
+ view: recordLens<DashboardStore, DashboardWidgetItem[]>('projectWidgetsMap'),
+ });
+ const detail = createReplicaSlice(dashboardDetailResource, {
+ actionPrefix: 'dashboard/detail',
+ // The detail adds `items` on top of the board row every list also holds.
+ entity: singleEntity<DashboardDetail, DashboardListItem>((board) => board.id, {
+ get: ({ items: _items, ...board }) => board as DashboardListItem,
+ set: (current, board) => ({ ...current, ...board }),
+ }),
+ get,
+ set,
+ stateKey: 'dashboardDetailReplica',
+ view: recordLens<DashboardStore, DashboardDetail>('dashboardDetailMap'),
+ });
+ const widgetDetail = createReplicaSlice(widgetDetailResource, {
+ actionPrefix: 'dashboard/widgetDetail',
+ entity: singleEntity<DashboardWidgetDetail>((widget) => widget.id),
+ get,
+ set,
+ stateKey: 'widgetDetailReplica',
+ view: recordLens<DashboardStore, DashboardWidgetDetail>('widgetDetailMap'),
+ });
+ const versions = createReplicaSlice(widgetVersionsResource, {
+ actionPrefix: 'dashboard/versions',
+ get,
+ set,
+ stateKey: 'widgetVersionsReplica',
+ view: recordLens<DashboardStore, DashboardWidgetVersionItem[]>('widgetVersionsMap'),
+ });
+ const runs = createReplicaSlice(widgetRunsResource, {
+ actionPrefix: 'dashboard/runs',
+ get,
+ set,
+ stateKey: 'widgetRunsReplica',
+ view: recordLens<DashboardStore, DashboardWidgetRunItem[]>('widgetRunsMap'),
+ });
+ const runDetail = createReplicaSlice(widgetRunResource, {
+ actionPrefix: 'dashboard/run',
+ get,
+ set,
+ stateKey: 'widgetRunDetailReplica',
+ view: recordLens<DashboardStore, DashboardWidgetRunDetail>('widgetRunDetailMap'),
+ });
+ const previewRun = createReplicaSlice(widgetPreviewRunResource, {
+ actionPrefix: 'dashboard/previewRun',
+ get,
+ set,
+ stateKey: 'widgetPreviewRunReplica',
+ view: recordLens<DashboardStore, DashboardWidgetRunDetail | null>('widgetPreviewRunMap'),
+ });
+ const trend = createReplicaSlice(widgetTrendResource, {
+ actionPrefix: 'dashboard/trend',
+ get,
+ set,
+ stateKey: 'widgetTrendReplica',
+ view: recordLens<DashboardStore, DashboardTrendSeries[]>('widgetTrendMap'),
+ });
+
+ // The same board lives in a level's list, its project's list and its detail
+ // page; one edit (rename / trash) lands in every loaded copy at once.
+ const board = linkReplicaEntity<DashboardListItem>([list, projectList, detail]);
+
+ const refreshDashboards = async (level?: WidgetLevelFilter) => {
+ await Promise.all([
+ list.revalidate(dashboardLevelKey(level)),
+ level?.projectId ? projectList.revalidate(level.projectId) : undefined,
+ ]);
+ };
+
+ /**
+ * Refresh a widget now, or after the run a refresh started. Every board
+ * showing it, its project's widget list, its history and its trend move
+ * together, whether the run succeeded or not.
+ */
+ const refreshWidget = async (widgetId: string) => {
+ await Promise.all([
+ detail.revalidate(),
+ projectWidgets.revalidate(),
+ widgetDetail.revalidate(widgetId),
+ runs.revalidate(widgetId),
+ trend.revalidate(widgetId),
+ ]);
+ };
+
+ return {
+ ...initialState,
+
+ // ── Reads ──
+
+ useFetchDashboards: (level = {}, enabled = true) => {
+ const data = useDashboardStore((s) => s.dashboardListByLevel[dashboardLevelKey(level)]);
+ return toRequest(list.useSync(level, { enabled }), data);
+ },
+
+ useFetchProjectDashboards: (projectId) => {
+ const data = useDashboardStore((s) =>
+ projectId ? s.projectDashboardsMap[projectId] : undefined,
+ );
+ return toRequest(projectList.useSync(projectId ?? null), data);
+ },
+
+ /** Every widget of a project — placed on a board or not — so none gets lost. */
+ useFetchProjectWidgets: (projectId) => {
+ const data = useDashboardStore((s) =>
+ projectId ? s.projectWidgetsMap[projectId] : undefined,
+ );
+ const sync = projectWidgets.useSync(projectId ?? null, {
+ refreshInterval: data?.some(({ lastRunStatus }) => lastRunStatus === 'running')
+ ? RUNNING_POLL_INTERVAL
+ : data?.some(({ nextRunAt }) => nextRunAt != null)
+ ? IDLE_POLL_INTERVAL
+ : 0,
+ });
+ return toRequest(sync, data);
+ },
+
+ useFetchDashboardDetail: (dashboardId) => {
+ const data = useDashboardStore((s) =>
+ dashboardId ? s.dashboardDetailMap[dashboardId] : undefined,
+ );
+ const sync = detail.useSync(dashboardId ?? null, {
+ refreshInterval: hasRunningWidget(data)
+ ? RUNNING_POLL_INTERVAL
+ : hasScheduledWidget(data)
+ ? IDLE_POLL_INTERVAL
+ : 0,
+ });
+ return toRequest(sync, data);
+ },
+
+ useFetchWidgetDetail: (widgetId) => {
+ const data = useDashboardStore((s) => (widgetId ? s.widgetDetailMap[widgetId] : undefined));
+ const sync = widgetDetail.useSync(widgetId ?? null, {
+ refreshInterval: data?.lastRunStatus === 'running' ? RUNNING_POLL_INTERVAL : 0,
+ });
+ return toRequest(sync, data);
+ },
+
+ /** One run with its output and logs; polls until it settles. */
+ useFetchWidgetRun: (widgetId, runId) => {
+ const data = useDashboardStore((s) => (runId ? s.widgetRunDetailMap[runId] : undefined));
+ const sync = runDetail.useSync(widgetId && runId ? { runId, widgetId } : null, {
+ refreshInterval: data?.status === 'running' ? RUNNING_POLL_INTERVAL : 0,
+ });
+ return toRequest(sync, data);
+ },
+
+ useFetchWidgetRuns: (widgetId) => {
+ const data = useDashboardStore((s) => (widgetId ? s.widgetRunsMap[widgetId] : undefined));
+ const sync = runs.useSync(widgetId ?? null, {
+ refreshInterval: data?.some(({ status }) => status === 'running')
+ ? RUNNING_POLL_INTERVAL
+ : 0,
+ });
+ return toRequest(sync, data);
+ },
+
+ useFetchWidgetVersions: (widgetId) => {
+ const data = useDashboardStore((s) =>
+ widgetId ? s.widgetVersionsMap[widgetId] : undefined,
+ );
+ return toRequest(versions.useSync(widgetId ?? null), data);
+ },
+
+ useFetchWidgetVersionPreviewRun: (widgetId, versionId) => {
+ const key = widgetId && versionId ? `${widgetId}:${versionId}` : undefined;
+ const data = useDashboardStore((s) => (key ? s.widgetPreviewRunMap[key] : undefined));
+ return toRequest(
+ previewRun.useSync(widgetId && versionId ? { versionId, widgetId } : null),
+ data,
+ );
+ },
+
+ useFetchWidgetTrend: (widget) => {
+ const data = useDashboardStore((s) => (widget ? s.widgetTrendMap[widget.id] : undefined));
+ const sync = trend.useSync(widget ?? null);
+ return toRequest(sync, data);
+ },
+
+ // ── Dashboards ──
+
+ createDashboard: async (params) => {
+ set({ dashboardCreating: true }, false, 'dashboard/create/start');
+ try {
+ const dashboard = await dashboardService.create(params);
+ await Promise.all([
+ refreshDashboards(params),
+ params.widgetId ? widgetDetail.revalidate(params.widgetId) : undefined,
+ ]);
+ return dashboard;
+ } finally {
+ set({ dashboardCreating: false }, false, 'dashboard/create/end');
+ }
+ },
+
+ renameDashboard: async (dashboardId, title, level) => {
+ await dashboardService.rename(dashboardId, title);
+ // The linked board entity updates the level list, the project list and
+ // the detail page in one commit; revalidating picks up server fields.
+ board.update(dashboardId, (current) => ({ ...current, title }));
+ await Promise.all([detail.revalidate(dashboardId), refreshDashboards(level)]);
+ },
+
+ trashDashboard: async (dashboardId, level) => {
+ await dashboardService.trash(dashboardId);
+ board.remove(dashboardId);
+ await refreshDashboards(level);
+ },
+
+ /**
+ * Persist a board's layout. The new cells render right away; a rejected
+ * save revalidates the board so the grid snaps back to what the server holds.
+ */
+ saveDashboardLayout: async (dashboardId, layouts, order) => {
+ const current = get().dashboardDetailMap[dashboardId];
+ const sortOrderOf = new Map(order.map((id, index) => [id, index]));
+ const patches: DashboardLayoutPatch[] = Object.entries(layouts).map(([id, layout]) => ({
+ id,
+ layout,
+ sortOrder: sortOrderOf.get(id),
+ }));
+
+ if (current) {
+ detail.update(dashboardId, (value) =>
+ value
+ ? {
+ ...value,
+ items: value.items
+ .map((entry) => ({
+ ...entry,
+ item: {
+ ...entry.item,
+ layout: layouts[entry.item.id] ?? entry.item.layout,
+ sortOrder: sortOrderOf.get(entry.item.id) ?? entry.item.sortOrder,
+ },
+ }))
+ .sort((a, b) => a.item.sortOrder - b.item.sortOrder),
+ }
+ : value,
+ );
+ }
+
+ set(
+ (s) => ({ dashboardLayoutSavingIds: [...s.dashboardLayoutSavingIds, dashboardId] }),
+ false,
+ 'dashboard/saveLayout/start',
+ );
+ try {
+ await dashboardService.updateItemLayouts(dashboardId, patches);
+ } catch (error) {
+ await detail.revalidate(dashboardId);
+ throw error;
+ } finally {
+ set(
+ (s) => ({
+ dashboardLayoutSavingIds: s.dashboardLayoutSavingIds.filter(
+ (id) => id !== dashboardId,
+ ),
+ }),
+ false,
+ 'dashboard/saveLayout/end',
+ );
+ }
+ },
+
+ removeWidgetFromDashboard: async (dashboardId, itemId) => {
+ await dashboardService.removeItems(dashboardId, [itemId]);
+ await detail.revalidate(dashboardId);
+ },
+
+ // ── Widgets ──
+
+ runWidget: async (widgetId) => {
+ set(
+ (s) => ({ widgetRunningIds: [...s.widgetRunningIds, widgetId] }),
+ false,
+ 'dashboard/run/start',
+ );
+ try {
+ return await dashboardService.runWidget(widgetId);
+ } finally {
+ set(
+ (s) => ({ widgetRunningIds: s.widgetRunningIds.filter((id) => id !== widgetId) }),
+ false,
+ 'dashboard/run/end',
+ );
+ await refreshWidget(widgetId);
+ }
+ },
+
+ /**
+ * Make a dry-run-proven version live, then run it once so every board
+ * shows live data right away. The server refuses a version whose exact
+ * content has not succeeded in a dry run; a failing first run leaves the
+ * publish in place.
+ */
+ publishWidgetVersion: async (widgetId, versionId) => {
+ set(
+ (s) => ({ widgetPublishingIds: [...s.widgetPublishingIds, widgetId] }),
+ false,
+ 'dashboard/publish/start',
+ );
+ try {
+ const result = await dashboardService.publish(widgetId, versionId);
+ await versions.revalidate(widgetId);
+ await get()
+ .runWidget(widgetId)
+ .catch((error) => {
+ console.error('[dashboard] first run after publish failed', error);
+ });
+ return result;
+ } finally {
+ set(
+ (s) => ({ widgetPublishingIds: s.widgetPublishingIds.filter((id) => id !== widgetId) }),
+ false,
+ 'dashboard/publish/end',
+ );
+ }
+ },
+
+ addWidgetToDashboard: async (dashboardId, widgetId) => {
+ set(
+ (s) => ({ widgetAddingIds: [...s.widgetAddingIds, widgetId] }),
+ false,
+ 'dashboard/add/start',
+ );
+ try {
+ const item = await dashboardService.addItem(dashboardId, widgetId);
+ await Promise.all([detail.revalidate(dashboardId), widgetDetail.revalidate(widgetId)]);
+ return item;
+ } finally {
+ set(
+ (s) => ({ widgetAddingIds: s.widgetAddingIds.filter((id) => id !== widgetId) }),
+ false,
+ 'dashboard/add/end',
+ );
+ }
+ },
+
+ // ── Refresh ──
+
+ refreshDashboardDetail: async (dashboardId) => {
+ await detail.revalidate(dashboardId);
+ },
+
+ refreshDashboards,
+
+ refreshWidgetDetail: async (widgetId) => {
+ await widgetDetail.revalidate(widgetId);
+ },
+
+ refreshWidgetPlacement: async (widgetId, dashboardId) => {
+ await Promise.all([
+ widgetDetail.revalidate(widgetId),
+ dashboardId ? detail.revalidate(dashboardId) : detail.revalidate(),
+ list.revalidate(),
+ projectList.revalidate(),
+ projectWidgets.revalidate(),
+ ]);
+ },
+
+ refreshWidget,
+ };
+ }),
+ shallow,
+);
+
+expose('dashboard', useDashboardStore);
diff --git a/src/store/global/initialState.ts b/src/store/global/initialState.ts
index 8969d5c4b30..0ecb92e8068 100644
--- a/src/store/global/initialState.ts
+++ b/src/store/global/initialState.ts
@@ -8,6 +8,7 @@ import { AsyncLocalStorage } from '@/utils/localStorage';
export enum SidebarTabKey {
Chat = 'chat',
Community = 'community',
+ Dashboard = 'dashboard',
Home = 'home',
Image = 'image',
Knowledge = 'knowledge',
diff --git a/src/store/global/selectors/systemStatus.test.ts b/src/store/global/selectors/systemStatus.test.ts
index b3c8414b887..3ade08ee045 100644
--- a/src/store/global/selectors/systemStatus.test.ts
+++ b/src/store/global/selectors/systemStatus.test.ts
@@ -263,6 +263,8 @@ describe('systemStatusSelectors', () => {
status: { sidebarItems: stored },
});
expect(systemStatusSelectors.sidebarItems(null)(s)).toEqual([
+ // Defaults missing from a saved layout (here the newer `dashboard`) are backfilled.
+ 'dashboard',
'private',
'agent',
'recents',
@@ -280,6 +282,7 @@ describe('systemStatusSelectors', () => {
it('should preserve a canonically-positioned spacer', () => {
const stored = [
'pages',
+ 'dashboard',
'project',
'recents',
'private',
@@ -318,6 +321,7 @@ describe('systemStatusSelectors', () => {
expect(systemStatusSelectors.sidebarItems(null)(s)).toEqual([
'tasks',
'pages',
+ 'dashboard',
'recents',
'project',
'private',
@@ -363,6 +367,7 @@ describe('systemStatusSelectors', () => {
// the legacy state was saved) is backfilled at the head of the block.
expect(items).toEqual([
'tasks',
+ 'dashboard',
'resource',
'private',
'agent',
@@ -385,6 +390,7 @@ describe('systemStatusSelectors', () => {
// backfilled at the head of the block; recents/agent keep legacy order.
expect(items).toEqual([
'tasks',
+ 'dashboard',
'resource',
'private',
'recents',
diff --git a/src/store/global/selectors/systemStatus.ts b/src/store/global/selectors/systemStatus.ts
index 1f3f52d0fba..1e2f3705b47 100644
--- a/src/store/global/selectors/systemStatus.ts
+++ b/src/store/global/selectors/systemStatus.ts
@@ -178,6 +178,7 @@ export const SIDEBAR_SPACER_ID = '__spacer__';
export const DEFAULT_SIDEBAR_ITEMS: string[] = [
'tasks',
+ 'dashboard',
'resource',
'recents',
'project',
diff --git a/src/store/serverConfig/selectors.test.ts b/src/store/serverConfig/selectors.test.ts
index a450f3fb1eb..8bb1de4fd5c 100644
--- a/src/store/serverConfig/selectors.test.ts
+++ b/src/store/serverConfig/selectors.test.ts
@@ -27,6 +27,20 @@ describe('featureFlagsSelectors', () => {
});
describe('serverConfigSelectors', () => {
+ describe('enableDashboard', () => {
+ it('is off by default and on only when the flag resolves to true', () => {
+ expect(serverConfigSelectors.enableDashboard(initServerConfigStore({}).getState())).toBe(
+ false,
+ );
+ const on = initServerConfigStore({
+ featureFlags: {
+ ...mapFeatureFlagsEnvToState({ ...DEFAULT_FEATURE_FLAGS, dashboard: true }),
+ },
+ });
+ expect(serverConfigSelectors.enableDashboard(on.getState())).toBe(true);
+ });
+ });
+
describe('enableGatewayMode', () => {
it('should return true when gateway mode is enabled', () => {
const store = initServerConfigStore({
@@ -83,4 +97,28 @@ describe('serverConfigSelectors', () => {
expect(result).toBe(false);
});
});
+
+ describe('widgetSandboxEnforcesNetworkHosts', () => {
+ it('is true only when the sandbox runs in allowlist mode', () => {
+ const enforced = initServerConfigStore({
+ serverConfig: { aiProvider: {}, telemetry: {}, widgetSandboxNetworkFormat: 'allowlist' },
+ });
+ expect(serverConfigSelectors.widgetSandboxEnforcesNetworkHosts(enforced.getState())).toBe(
+ true,
+ );
+
+ // The deployed Worker's boolean format — and an unset format, which
+ // defaults to it — cannot limit egress to the declared hosts.
+ const booleanFormat = initServerConfigStore({
+ serverConfig: { aiProvider: {}, telemetry: {}, widgetSandboxNetworkFormat: 'boolean' },
+ });
+ expect(
+ serverConfigSelectors.widgetSandboxEnforcesNetworkHosts(booleanFormat.getState()),
+ ).toBe(false);
+ const unset = initServerConfigStore({
+ serverConfig: { aiProvider: {}, telemetry: {} },
+ });
+ expect(serverConfigSelectors.widgetSandboxEnforcesNetworkHosts(unset.getState())).toBe(false);
+ });
+ });
});
diff --git a/src/store/serverConfig/selectors.ts b/src/store/serverConfig/selectors.ts
index 468422606b4..26b6b26dbbc 100644
--- a/src/store/serverConfig/selectors.ts
+++ b/src/store/serverConfig/selectors.ts
@@ -8,6 +8,8 @@ export const serverConfigSelectors = {
enableEmailVerification: (s: ServerConfigStore) =>
s.serverConfig.enableEmailVerification || false,
enableComposio: (s: ServerConfigStore) => s.serverConfig.enableComposio || false,
+ /** Runtime flag `dashboard`: dashboards, widget previews and the lobe-dashboard tool. */
+ enableDashboard: (s: ServerConfigStore) => s.featureFlags.enableDashboard === true,
enableGatewayMode: (s: ServerConfigStore) => s.serverConfig.enableGatewayMode || false,
enableLobehubSkill: (s: ServerConfigStore) => s.serverConfig.enableLobehubSkill || false,
enableMagicLink: (s: ServerConfigStore) => s.serverConfig.enableMagicLink || false,
@@ -17,6 +19,15 @@ export const serverConfigSelectors = {
enableMultimodalUnderstanding: (s: ServerConfigStore) =>
s.serverConfig.enableMultimodalUnderstanding || false,
enabledTelemetryChat: (s: ServerConfigStore) => s.serverConfig.telemetry.langfuse || false,
+ /**
+ * Whether the widget sandbox can enforce the manifest's per-host network
+ * allowlist. Only `WIDGET_SANDBOX_NETWORK_FORMAT=allowlist` restricts
+ * egress to the declared hosts; the default boolean format switches egress
+ * on for any nonempty allowlist, so the publish review must disclose
+ * unrestricted egress instead of presenting the hosts as enforced.
+ */
+ widgetSandboxEnforcesNetworkHosts: (s: ServerConfigStore) =>
+ s.serverConfig.widgetSandboxNetworkFormat === 'allowlist',
isMobile: (s: ServerConfigStore) => s.isMobile || false,
oAuthSSOProviders: (s: ServerConfigStore) => s.serverConfig.oAuthSSOProviders,
multimodalUnderstanding: (s: ServerConfigStore) => s.serverConfig.multimodalUnderstanding,
diff --git a/src/store/tool/slices/builtin/executors/catalog.ts b/src/store/tool/slices/builtin/executors/catalog.ts
index 5d3fb580224..a40c2940fe3 100644
--- a/src/store/tool/slices/builtin/executors/catalog.ts
+++ b/src/store/tool/slices/builtin/executors/catalog.ts
@@ -5,6 +5,7 @@ import { browserExecutor } from '@lobechat/builtin-tool-browser/client/executor'
import { calculatorExecutor } from '@lobechat/builtin-tool-calculator/executor';
import { cloudSandboxExecutor } from '@lobechat/builtin-tool-cloud-sandbox/executor';
import { credsExecutor } from '@lobechat/builtin-tool-creds/executor';
+import { dashboardExecutor } from '@lobechat/builtin-tool-dashboard/client/executor';
import { goalExecutor } from '@lobechat/builtin-tool-goal/client/executor';
import { groupAgentBuilderExecutor } from '@lobechat/builtin-tool-group-agent-builder/executor';
import { groupManagementExecutor } from '@lobechat/builtin-tool-group-management/executor';
@@ -83,6 +84,7 @@ export const builtinToolExecutors = [
skillStoreExecutor,
skillsExecutor,
taskExecutor,
+ dashboardExecutor,
videoGenerationExecutor,
activatorExecutor,
topicReferenceExecutor,