🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(widget): widget and dashboard models, services, TRPC and scheduler (#20366)
Arvin Xu339b63355fd6
diff --git a/.env.example b/.env.exampleindex e8d8a3b38b2..54b54350f19 100644--- a/.env.example+++ b/.env.example@@ -266,6 +266,19 @@ OPENAI_API_KEY=sk-xxxxxxxxx# Optional terminal session lease in seconds for the Onlyboxes provider.# ONLYBOXES_LEASE_TTL_SEC=900+# Widget sandbox: executes widget scripts behind `POST {URL}/run`+# ({ script, runtime, env, network, timeoutMs }). Today the only provider is a+# Cloudflare Worker. Without URL + token, widget runs fail with+# SANDBOX_NOT_CONFIGURED. DASHBOARD_SANDBOX_URL / DASHBOARD_SANDBOX_TOKEN are+# still read as fallbacks.+# WIDGET_SANDBOX_URL=https://widget-sandbox.example.workers.dev+# WIDGET_SANDBOX_TOKEN=+# WIDGET_SANDBOX_PROVIDER=cloudflare-worker+# `boolean` (default) sends `network: true | false`, the only shape the current+# Worker accepts; set `allowlist` to send `network: { allow: [...hosts] }` to a+# Worker that enforces per-run hosts.+# WIDGET_SANDBOX_NETWORK_FORMAT=boolean+# ######################################## ########### Plugin Service ############# #######################################diff --git a/apps/server/src/router-hono/workflows/index.ts b/apps/server/src/router-hono/workflows/index.tsindex 9490aaa7a57..512278924fe 100644--- a/apps/server/src/router-hono/workflows/index.ts+++ b/apps/server/src/router-hono/workflows/index.ts@@ -12,6 +12,7 @@ import taskApp from './task';import topicAutoSummaryApp from './topic-auto-summary';import trashApp from './trash';import verifyApp from './verify';+import widgetApp from './widget';const app = new Hono().basePath('/api/workflows');@@ -27,5 +28,6 @@ app.route('/task', taskApp);app.route('/topic-auto-summary', topicAutoSummaryApp);app.route('/trash', trashApp);app.route('/verify', verifyApp);+app.route('/widget', widgetApp);export default app;diff --git a/apps/server/src/router-hono/workflows/widget/handlers/runWidget.ts b/apps/server/src/router-hono/workflows/widget/handlers/runWidget.tsnew file mode 100644index 00000000000..b812c73b4bc--- /dev/null+++ b/apps/server/src/router-hono/workflows/widget/handlers/runWidget.ts@@ -0,0 +1,65 @@+import type { Context } from 'hono';++import { getServerDB } from '@/database/server';+import { createWidgetSandboxRunner } from '@/server/services/widget/sandbox';+import {+ type DispatchedWidgetResult,+ resumeDispatchedRun,+ runDispatchedWidget,+} from '@/server/services/widget/scheduler';++interface RunWidgetPayload {+ /** Resume message: the lease the run was judged stale under (ISO); part of its dedup id. */+ leaseStartedAt?: string;+ /** Resume message: the abandoned reserved run to take over. */+ runId?: string;+ /** Slot message: the `next_run_at` the widget was due at when the tick dispatched it (ISO). */+ slot?: string;+ widgetId?: string;+}++/**+ * Queued half of a scheduled widget run. Two messages arrive here:+ *+ * - `{ widgetId, slot }` — a due slot. The handler claims it (advancing+ * `next_run_at` and reserving the run in one transaction) and executes the+ * reserved run. QStash delivers at least once: a redelivery for an+ * already-claimed slot resumes the reservation only when its lease expired+ * (the first worker died), otherwise it is acknowledged (2xx) untouched.+ * - `{ widgetId, runId, leaseStartedAt }` — a stale reservation found by the+ * tick's sweep, resumed if nobody took it over meanwhile.+ */+export async function runWidget(c: Context) {+ try {+ const { runId, slot, widgetId } = ((await c.req.json().catch(() => ({}))) ??+ {}) as RunWidgetPayload;+ if (!widgetId) return c.json({ error: 'widgetId is required' }, 400);++ const deps = { runner: createWidgetSandboxRunner() };+ let result: DispatchedWidgetResult;++ if (typeof runId === 'string') {+ result = await resumeDispatchedRun(await getServerDB(), { runId, widgetId }, deps);+ } else {+ // Messages from before slot claiming moved here carry no slot. Their tick+ // already claimed the slot, so running would be the duplicate; ack them.+ const slotDate = typeof slot === 'string' ? new Date(slot) : undefined;+ if (!slotDate || Number.isNaN(slotDate.getTime())) {+ return c.json({ skipped: 'missing-slot', success: true });+ }+ result = await runDispatchedWidget(await getServerDB(), { slot: slotDate, widgetId }, deps);+ }++ if (result.skipped) return c.json({ skipped: result.skipped, success: true });++ return c.json({+ ...(result.resumed && { resumed: true }),+ runId: result.run?.id,+ status: result.run?.status,+ success: true,+ });+ } catch (error) {+ console.error('[widget/run-widget] Error:', error);+ return c.json({ error: error instanceof Error ? error.message : 'Internal error' }, 500);+ }+}diff --git a/apps/server/src/router-hono/workflows/widget/handlers/tick.ts b/apps/server/src/router-hono/workflows/widget/handlers/tick.tsnew file mode 100644index 00000000000..3b481bc8a98--- /dev/null+++ b/apps/server/src/router-hono/workflows/widget/handlers/tick.ts@@ -0,0 +1,87 @@+import type { Context } from 'hono';++import { getServerDB } from '@/database/server';+import { appEnv } from '@/envs/app';+import { qstashClient } from '@/libs/qstash';+import { createWidgetSandboxRunner } from '@/server/services/widget/sandbox';+import {+ isWidgetResumeTarget,+ runWidgetSchedulerTick,+ type WidgetDispatchTarget,+} from '@/server/services/widget/scheduler';++export const RUN_WIDGET_PATH = '/api/workflows/widget/run-widget';++export const widgetRunDeduplicationId = (widgetId: string, slotIso: string) =>+ `widget:${widgetId}:${slotIso}`;++/** One resume per lease: a run that is resumed and abandoned again gets a new id. */+export const widgetResumeDeduplicationId = (runId: string, leaseStartedAtIso: string) =>+ `widget-run:${runId}:${leaseStartedAtIso}`;++interface TickPayload {+ /** Only report how many widgets are due. */+ dryRun?: boolean;+ limit?: number;+}++/**+ * Widget scheduler tick. Registered as a QStash Schedule (`lobe-widget-tick`,+ * see `scripts/serverLauncher/startServer.js`). In queue mode each due slot is+ * published to `run-widget` as `{ widgetId, slot }` (deduplicated per slot) and+ * that handler claims it before running, and each stale reservation (a run+ * whose worker died past its lease) as `{ widgetId, runId, leaseStartedAt }`+ * (deduplicated per lease) for that handler to resume; inline, the tick+ * claims, resumes and runs itself.+ *+ * Trigger a tick by hand against a local server (the script signs the+ * request when `QSTASH_CURRENT_SIGNING_KEY` is set, as `qstashAuth` then+ * requires):+ *+ * SERVER_URL=http://localhost:3010 bun run widget:tick [--dry-run]+ */+export async function tick(c: Context) {+ try {+ const body = ((await c.req.json().catch(() => ({}))) ?? {}) as TickPayload;+ const db = await getServerDB();++ const dispatch = appEnv.enableQueueAgentRuntime+ ? async (target: WidgetDispatchTarget) => {+ if (!process.env.APP_URL) {+ throw new Error('APP_URL is required to fan out widget runs via QStash');+ }+ const url = `${process.env.APP_URL.replace(/\/$/, '')}${RUN_WIDGET_PATH}`;++ if (isWidgetResumeTarget(target)) {+ const leaseStartedAt = target.leaseStartedAt.toISOString();+ 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),+ url,+ });+ return;+ }++ const slotIso = target.slot.toISOString();+ await qstashClient.publishJSON({+ body: { slot: slotIso, widgetId: target.widgetId },+ // Overlapping ticks see the same unclaimed slot; publish it once.+ deduplicationId: widgetRunDeduplicationId(target.widgetId, slotIso),+ url,+ });+ }+ : undefined;++ const result = await runWidgetSchedulerTick(+ db,+ { runner: createWidgetSandboxRunner() },+ { dispatch, dryRun: body.dryRun, limit: body.limit },+ );++ return c.json({ ...result, success: true });+ } catch (error) {+ console.error('[widget/tick] Error:', error);+ return c.json({ error: error instanceof Error ? error.message : 'Internal error' }, 500);+ }+}diff --git a/apps/server/src/router-hono/workflows/widget/index.ts b/apps/server/src/router-hono/workflows/widget/index.tsnew file mode 100644index 00000000000..2ab02916384--- /dev/null+++ b/apps/server/src/router-hono/workflows/widget/index.ts@@ -0,0 +1,12 @@+import { Hono } from 'hono';++import { qstashAuth } from '../middlewares/qstashAuth';+import { runWidget } from './handlers/runWidget';+import { tick } from './handlers/tick';++const app = new Hono();++app.post('/tick', qstashAuth(), tick);+app.post('/run-widget', qstashAuth(), runWidget);++export default app;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.tsnew file mode 100644index 00000000000..55e35ecf27d--- /dev/null+++ b/apps/server/src/routers/lambda/__tests__/integration/widget.integration.test.ts@@ -0,0 +1,1256 @@+// @vitest-environment node+import type { LobeChatDatabase } from '@lobechat/database';+import {+ agents,+ metricPoints,+ metrics,+ projects,+ widgetRuns,+ widgets,+ widgetVersions,+ workspaces,+} from '@lobechat/database/schemas';+import { getTestDB } from '@lobechat/database/test-utils';+import { and, desc, eq } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { ConnectorModel } from '@/database/models/connector';+import { DashboardModel } from '@/database/models/dashboard';+import { WidgetModel } from '@/database/models/widget';+import { qstashClient } from '@/libs/qstash';+import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';+import widgetWorkflowApp from '@/server/router-hono/workflows/widget';+import { executeWidgetRun } from '@/server/services/widget/executeRun';+import { recordWidgetMetrics } from '@/server/services/widget/metrics';+import { runWidgetSchedulerTick } from '@/server/services/widget/scheduler';++import { dashboardRouter } from '../../dashboard';+import { metricRouter } from '../../metric';+import { widgetRouter } from '../../widget';+import { cleanupTestUser, createTestAgent, createTestUser } from './setup';++vi.hoisted(() => {+ // 32-byte key so connector credentials round-trip through the real gatekeeper.+ process.env.KEY_VAULTS_SECRET = Buffer.alloc(32, 7).toString('base64');+});++let testDB: LobeChatDatabase;+vi.mock('@/database/core/db-adaptor', () => ({+ getServerDB: vi.fn(function () {+ return testDB;+ }),+}));++const queueMode = vi.hoisted(() => ({ enabled: false }));+vi.mock('@/envs/app', async (importOriginal) => {+ const mod = await importOriginal<{ appEnv: object }>();+ return {+ ...mod,+ appEnv: new Proxy(mod.appEnv, {+ get: (target, key) =>+ key === 'enableQueueAgentRuntime' ? queueMode.enabled : Reflect.get(target, key),+ }),+ };+});++const runSandbox = vi.fn();+vi.mock('@/server/services/widget/sandbox', async (importOriginal) => ({+ ...(await importOriginal<object>()),+ createWidgetSandboxRunner: () => ({ run: runSandbox }),+}));++const ok = (output: unknown) => ({+ durationMs: 12,+ exitCode: 0,+ stderr: '',+ stdout: JSON.stringify(output),+ timedOut: false,+});++const statScript = {+ outputType: 'stat' as const,+ runtime: 'node' as const,+ script: `console.log(JSON.stringify({ type: 'stat', value: 7 }))`,+};++const context = (userId: string, workspaceId?: string) => ({+ jwtPayload: { userId },+ userId,+ workspaceId,+});++describe('widget + dashboard routers integration', () => {+ let db: LobeChatDatabase;+ let ownerId: string;+ let memberId: string;+ let outsiderId: string;+ let workspaceId: string;++ beforeEach(async () => {+ runSandbox.mockReset();+ db = await getTestDB();+ testDB = db;+ [ownerId, memberId, outsiderId] = await Promise.all([+ createTestUser(db),+ createTestUser(db),+ createTestUser(db),+ ]);+ const [workspace] = await db+ .insert(workspaces)+ .values({ name: 'Dashboards', primaryOwnerId: ownerId, slug: `db-${ownerId}` })+ .returning();+ workspaceId = workspace.id;+ });++ afterEach(async () => {+ queueMode.enabled = false;+ vi.restoreAllMocks();+ vi.unstubAllEnvs();+ await db.delete(workspaces).where(eq(workspaces.id, workspaceId));+ await Promise.all([ownerId, memberId, outsiderId].map((id) => cleanupTestUser(db, id)));+ });++ type WidgetCaller = ReturnType<typeof widgetRouter.createCaller>;+ const callers = (userId: string, ws?: string) => ({+ board: dashboardRouter.createCaller(context(userId, ws)),+ widget: widgetRouter.createCaller(context(userId, ws)),+ });++ const createWidget = async (+ caller: WidgetCaller,+ input: Parameters<WidgetCaller['create']>[0] = { title: 'Open PRs' },+ ) => (await caller.create(input))!.data;++ describe('version flow', () => {+ it('requires a successful dry run of the exact content before publishing', async () => {+ const owner = widgetRouter.createCaller(context(ownerId));+ const widget = await createWidget(owner);++ const draft = (await owner.saveDraft({ widgetId: widget.id, ...statScript }))!.data;+ expect(draft).toMatchObject({ status: 'draft', version: 1 });++ await expect(+ owner.publish({ versionId: draft.id, widgetId: widget.id }),+ ).rejects.toMatchObject({+ code: 'PRECONDITION_FAILED',+ });++ // A failing dry run does not unlock publishing either.+ runSandbox.mockResolvedValueOnce({ ...ok({}), exitCode: 1, stderr: 'boom' });+ const failed = (await owner.dryRun({ widgetId: widget.id }))!.data;+ expect(failed).toMatchObject({+ error: { code: 'NON_ZERO_EXIT', message: 'Script exited with code 1: boom' },+ status: 'failed',+ trigger: 'preview',+ });+ await expect(+ owner.publish({ versionId: draft.id, widgetId: widget.id }),+ ).rejects.toMatchObject({+ code: 'PRECONDITION_FAILED',+ });++ runSandbox.mockResolvedValueOnce(ok({ type: 'stat', value: 7 }));+ const preview = (await owner.dryRun({ widgetId: widget.id }))!.data;+ expect(preview).toMatchObject({ output: { type: 'stat', value: 7 }, status: 'succeeded' });++ // Preview runs never touch the live snapshot.+ const [afterPreview] = await db.select().from(widgets).where(eq(widgets.id, widget.id));+ expect(afterPreview).toMatchObject({ lastRunId: null, latestOutput: null });++ // Saving identical content reuses the draft (same content hash).+ const again = (await owner.saveDraft({ widgetId: widget.id, ...statScript }))!.data;+ expect(again.id).toBe(draft.id);++ const published = (await owner.publish({ versionId: draft.id, widgetId: widget.id }))!.data;+ expect(published.widget).toMatchObject({+ draftVersionId: null,+ publishedVersionId: draft.id,+ });+ });++ it('reports the widget’s versions and the boards it is placed on', async () => {+ const { board: ownerBoard, widget: owner } = callers(ownerId);+ const board = (await ownerBoard.create({ title: 'Ops' }))!.data;+ const widget = await createWidget(owner, { dashboardId: board.id, title: 'Open PRs' });+ const draft = (await owner.saveDraft({ widgetId: widget.id, ...statScript }))!.data;++ const detail = (await owner.detail({ id: widget.id }))!.data;+ expect(detail).toMatchObject({+ dashboards: [{ id: board.id, title: 'Ops' }],+ draftVersion: { id: draft.id },+ publishedVersion: null,+ });++ await ownerBoard.trash({ id: board.id });+ expect((await owner.detail({ id: widget.id }))!.data.dashboards).toEqual([]);+ });++ it('publishes v2 over v1 and rolls back to the archived v1', async () => {+ const owner = widgetRouter.createCaller(context(ownerId));+ const widget = await createWidget(owner);+ runSandbox.mockResolvedValue(ok({ type: 'stat', value: 1 }));++ const v1 = (await owner.saveDraft({ widgetId: widget.id, ...statScript }))!.data;+ await owner.dryRun({ widgetId: widget.id });+ await owner.publish({ versionId: v1.id, widgetId: widget.id });++ const v2 = (await owner.saveDraft({+ changeNote: 'count drafts too',+ widgetId: widget.id,+ ...statScript,+ script: `console.log(JSON.stringify({ type: 'stat', value: 8 }))`,+ }))!.data;+ expect(v2.version).toBe(2);+ await owner.dryRun({ widgetId: widget.id });+ await owner.publish({ versionId: v2.id, widgetId: widget.id });++ const versions = (await owner.listVersions({ widgetId: widget.id }))!.data;+ expect(versions.map((v) => [v.version, v.status])).toEqual([+ [2, 'published'],+ [1, 'archived'],+ ]);++ // A draft that never went live is not a rollback target.+ const v3 = (await owner.saveDraft({+ widgetId: widget.id,+ ...statScript,+ script: 'console.log(3)',+ }))!.data;+ await expect(owner.rollback({ versionId: v3.id, widgetId: widget.id })).rejects.toMatchObject(+ {+ code: 'BAD_REQUEST',+ },+ );++ const rolled = (await owner.rollback({ widgetId: widget.id }))!.data;+ expect(rolled.widget.publishedVersionId).toBe(v1.id);+ const after = (await owner.listVersions({ widgetId: widget.id }))!.data;+ expect(after.map((v) => [v.version, v.status])).toEqual([+ [3, 'draft'],+ [2, 'archived'],+ [1, 'published'],+ ]);+ });+ });++ describe('runs', () => {+ const publishStat = async (owner: WidgetCaller, extra = {}) => {+ const widget = await createWidget(owner, { title: 'Stars', ...extra });+ const draft = (await owner.saveDraft({+ manifest: { metric: { key: 'stars', unit: 'stars' } },+ widgetId: widget.id,+ ...statScript,+ }))!.data;+ runSandbox.mockResolvedValueOnce(ok({ type: 'stat', value: 1 }));+ await owner.dryRun({ widgetId: widget.id });+ await owner.publish({ versionId: draft.id, widgetId: widget.id });+ return widget;+ };++ it('stores the output, records a metric point, and keeps it through failures', async () => {+ const owner = widgetRouter.createCaller(context(ownerId));+ const widget = await publishStat(owner);++ runSandbox.mockResolvedValueOnce(ok({ type: 'stat', value: 42 }));+ const run = (await owner.run({ widgetId: widget.id }))!.data;+ expect(run).toMatchObject({ status: 'succeeded', trigger: 'manual' });++ let [row] = await db.select().from(widgets).where(eq(widgets.id, widget.id));+ expect(row).toMatchObject({+ consecutiveFailures: 0,+ lastRunStatus: 'succeeded',+ latestOutput: { type: 'stat', value: 42 },+ });+ expect(row.metricId).toBeTruthy();+ const points = await db+ .select()+ .from(metricPoints)+ .where(eq(metricPoints.metricId, row.metricId!));+ expect(points.map((p) => p.value)).toEqual([42]);+ const [metric] = await db.select().from(metrics).where(eq(metrics.id, row.metricId!));+ expect(metric).toMatchObject({+ key: 'stars',+ subjectId: widget.id,+ subjectType: 'widget',+ });++ // Invalid output then a timeout: failures accumulate, last good output stays.+ runSandbox.mockResolvedValueOnce({ ...ok({}), stdout: 'not json' });+ const invalid = (await owner.run({ widgetId: widget.id }))!.data;+ expect(invalid).toMatchObject({ error: { code: 'INVALID_JSON' }, status: 'failed' });+ runSandbox.mockResolvedValueOnce({ ...ok({}), exitCode: 124, stdout: '', timedOut: true });+ const timeout = (await owner.run({ widgetId: widget.id }))!.data;+ expect(timeout).toMatchObject({ error: { code: 'TIMEOUT' }, status: 'timeout' });++ [row] = await db.select().from(widgets).where(eq(widgets.id, widget.id));+ expect(row).toMatchObject({+ consecutiveFailures: 2,+ lastRunError: { code: 'TIMEOUT' },+ lastRunStatus: 'timeout',+ latestOutput: { type: 'stat', value: 42 },+ });++ // A partial result finishes as `partial`: it renders, but is not a trend sample.+ runSandbox.mockResolvedValueOnce(+ ok({ meta: { complete: false, message: 'one repo failed' }, type: 'stat', value: 40 }),+ );+ const partial = (await owner.run({ widgetId: widget.id }))!.data;+ expect(partial).toMatchObject({+ error: null,+ output: { meta: { complete: false, message: 'one repo failed' }, value: 40 },+ status: 'partial',+ });+ [row] = await db.select().from(widgets).where(eq(widgets.id, widget.id));+ expect(row).toMatchObject({+ consecutiveFailures: 0,+ lastRunError: null,+ lastRunStatus: 'partial',+ latestOutput: { value: 40 },+ });+ const pointsAfter = await db+ .select()+ .from(metricPoints)+ .where(eq(metricPoints.metricId, row.metricId!));+ expect(pointsAfter).toHaveLength(1);++ const runs = (await owner.listRuns({ widgetId: widget.id }))!.data;+ expect(runs.map((r) => r.status)).toEqual([+ 'partial',+ 'timeout',+ 'failed',+ 'succeeded',+ 'succeeded',+ ]);+ });++ it('records no metric and keeps the trend link for a stale run that finishes late', async () => {+ const owner = widgetRouter.createCaller(context(ownerId));+ const widget = await publishStat(owner);+ const widgetRow = async () =>+ (await db.select().from(widgets).where(eq(widgets.id, widget.id)))[0];+ const versionRow = async (id: string) =>+ (await db.select().from(widgetVersions).where(eq(widgetVersions.id, id)))[0];+ const allPoints = async () =>+ (+ await db+ .select({ value: metricPoints.value })+ .from(metricPoints)+ .innerJoin(metrics, eq(metricPoints.metricId, metrics.id))+ .where(eq(metrics.subjectId, widget.id))+ )+ .map((p) => p.value)+ .sort((a, b) => a - b);++ runSandbox.mockResolvedValueOnce(ok({ type: 'stat', value: 42 }));+ await owner.run({ widgetId: widget.id });+ const v1Row = await widgetRow();+ const v1 = await versionRow(v1Row.publishedVersionId!);++ // a v1 run is in flight when v2 (a different metric key) goes live+ const oldVersionRun = await WidgetModel.startRun(db, v1Row, { trigger: 'schedule' });+ const v2 = (await owner.saveDraft({+ manifest: { metric: { key: 'forks' } },+ widgetId: widget.id,+ ...statScript,+ script: 'console.log(2)',+ }))!.data;+ runSandbox.mockResolvedValueOnce(ok({ type: 'stat', value: 1 }));+ await owner.dryRun({ widgetId: widget.id });+ await owner.publish({ versionId: v2.id, widgetId: widget.id });++ // a v2 run starts, then a newer one finishes first and owns the snapshot+ const startedEarly = await WidgetModel.startRun(db, await widgetRow(), {+ trigger: 'schedule',+ });+ await db+ .update(widgetRuns)+ .set({ startedAt: new Date(Date.now() - 60_000) })+ .where(eq(widgetRuns.id, startedEarly.id));+ runSandbox.mockResolvedValueOnce(ok({ type: 'stat', value: 10 }));+ await owner.run({ widgetId: widget.id });+ const current = await widgetRow();+ const forksMetricId = current.metricId;+ expect(forksMetricId).not.toBe(v1Row.metricId);+ expect(await allPoints()).toEqual([10, 42]);++ const runner = { run: runSandbox };+ runSandbox.mockResolvedValueOnce(ok({ type: 'stat', value: 99 }));+ const lateOld = await executeWidgetRun(+ db,+ { run: oldVersionRun, version: v1, widget: current },+ { runner },+ );+ runSandbox.mockResolvedValueOnce(ok({ type: 'stat', value: 98 }));+ const lateEarly = await executeWidgetRun(+ db,+ { run: startedEarly, version: await versionRow(v2.id), widget: current },+ { runner },+ );++ // both runs are closed, but neither enters the trend nor moves the link+ expect(lateOld).toMatchObject({ id: oldVersionRun.id, status: 'succeeded' });+ expect(lateEarly).toMatchObject({ id: startedEarly.id, status: 'succeeded' });+ expect(await allPoints()).toEqual([10, 42]);+ expect(await widgetRow()).toMatchObject({+ latestOutput: { type: 'stat', value: 10 },+ metricId: forksMetricId,+ });+ });++ it('labels a manual run with the version it executes when a publish races it', async () => {+ const owner = widgetRouter.createCaller(context(ownerId));+ const widget = await publishStat(owner);+ runSandbox.mockResolvedValueOnce(ok({ type: 'stat', value: 42 }));+ await owner.run({ widgetId: widget.id });+ const v1Id = (await db.select().from(widgets).where(eq(widgets.id, widget.id)))[0]+ .publishedVersionId!;++ const v2 = (await owner.saveDraft({+ widgetId: widget.id,+ ...statScript,+ script: 'console.log(2)',+ }))!.data;+ runSandbox.mockResolvedValueOnce(ok({ type: 'stat', value: 1 }));+ await owner.dryRun({ widgetId: widget.id });++ // v2 goes live between runNow reading v1 and the run row being created+ const startRun = WidgetModel.prototype.startRun;+ vi.spyOn(WidgetModel.prototype, 'startRun').mockImplementationOnce(async function (+ this: WidgetModel,+ ...args: Parameters<WidgetModel['startRun']>+ ) {+ await new WidgetModel(db, ownerId).publishVersion(widget.id, v2.id);+ return startRun.apply(this, args);+ });+ runSandbox.mockResolvedValueOnce(ok({ type: 'stat', value: 99 }));+ await owner.run({ widgetId: widget.id });++ // the run executed v1's script, so it is labeled v1 and does not become v2's result+ const [latestRun] = await db+ .select()+ .from(widgetRuns)+ .where(and(eq(widgetRuns.widgetId, widget.id), eq(widgetRuns.trigger, 'manual')))+ .orderBy(desc(widgetRuns.startedAt))+ .limit(1);+ expect(latestRun.versionId).toBe(v1Id);+ expect((await db.select().from(widgets).where(eq(widgets.id, widget.id)))[0]).toMatchObject({+ latestOutput: { type: 'stat', value: 42 },+ publishedVersionId: v2.id,+ });+ });++ it('passes the manifest network allowlist to the sandbox', async () => {+ const owner = widgetRouter.createCaller(context(ownerId));+ const widget = await createWidget(owner);+ runSandbox.mockResolvedValue(ok({ type: 'stat', value: 1 }));++ await owner.saveDraft({+ manifest: { network: { allow: ['api.github.com', 'gitlab.com'] } },+ widgetId: widget.id,+ ...statScript,+ });+ await owner.dryRun({ widgetId: widget.id });+ await owner.saveDraft({ widgetId: widget.id, ...statScript, script: 'console.log(2)' });+ await owner.dryRun({ widgetId: widget.id });++ expect(runSandbox.mock.calls.map(([request]) => request.network)).toEqual([+ { allow: ['api.github.com', 'gitlab.com'] },+ { allow: [] },+ ]);+ expect(runSandbox.mock.calls[0][0].subject).toEqual({ id: widget.id, kind: 'widget' });+ });++ it('appends only new series points to per-series metrics', async () => {+ const owner = widgetRouter.createCaller(context(ownerId));+ const widget = await createWidget(owner, { title: 'Deploys' });+ const draft = (await owner.saveDraft({+ outputType: 'series',+ runtime: 'python',+ script: 'print(1)',+ widgetId: widget.id,+ }))!.data;+ const series = (points: [string, number][]) =>+ ok({+ series: [{ name: 'deploys', points: points.map(([t, v]) => ({ t, v })) }],+ type: 'series',+ });+ runSandbox.mockResolvedValueOnce(series([['2026-09-01', 1]]));+ await owner.dryRun({ widgetId: widget.id });+ await owner.publish({ versionId: draft.id, widgetId: widget.id });++ runSandbox.mockResolvedValueOnce(+ series([+ ['2026-09-01', 1],+ ['2026-09-02', 3],+ ]),+ );+ await owner.run({ widgetId: widget.id });+ runSandbox.mockResolvedValueOnce(+ series([+ ['2026-09-02', 3],+ ['2026-09-03', 2],+ ]),+ );+ await owner.run({ widgetId: widget.id });++ const [metric] = await db+ .select()+ .from(metrics)+ .where(and(eq(metrics.subjectId, widget.id), eq(metrics.key, 'series:deploys')));+ const points = await db+ .select()+ .from(metricPoints)+ .where(eq(metricPoints.metricId, metric.id))+ .orderBy(metricPoints.observedAt);+ expect(points.map((p) => [p.observedAt.toISOString().slice(0, 10), p.value])).toEqual([+ ['2026-09-01', 1],+ ['2026-09-02', 3],+ ['2026-09-03', 2],+ ]);+ });+ it('writes an overlapping series batch once when two runs record it concurrently', async () => {+ const owner = widgetRouter.createCaller(context(ownerId));+ const widget = await createWidget(owner, { title: 'Deploys' });+ const output = {+ series: [+ {+ name: 'deploys',+ points: [+ { t: '2026-09-01', v: 1 },+ { t: '2026-09-02', v: 3 },+ ],+ },+ ],+ type: 'series' as const,+ };+ const record = (runId: string) =>+ recordWidgetMetrics(db, widget, { observedAt: new Date(), output, runId });++ // a manual refresh and a scheduled run report the same window at once+ const results = await Promise.all([record('run-a'), record('run-b')]);+ expect(results.map((r) => r.pointsWritten).sort()).toEqual([0, 2]);++ const [metric] = await db+ .select()+ .from(metrics)+ .where(and(eq(metrics.subjectId, widget.id), eq(metrics.key, 'series:deploys')));+ const points = await db+ .select()+ .from(metricPoints)+ .where(eq(metricPoints.metricId, metric.id))+ .orderBy(metricPoints.observedAt);+ expect(points.map((p) => [p.observedAt.toISOString().slice(0, 10), p.value])).toEqual([+ ['2026-09-01', 1],+ ['2026-09-02', 3],+ ]);+ });+ });++ describe('credentials', () => {+ const gateKeeperModel = async (userId: string, ws?: string) =>+ new ConnectorModel(db, userId, ws, await KeyVaultsGateKeeper.initWithEnvKey());++ const githubConnector = (token: string, extra: Record<string, unknown> = {}) => ({+ credentials: JSON.stringify({ token, type: 'bearer' }),+ identifier: 'github',+ name: 'GitHub',+ sourceType: 'custom',+ status: 'connected',+ ...extra,+ });++ const draftWithEnv = async (caller: WidgetCaller, widgetId: string) =>+ (await caller.saveDraft({+ manifest: { env: [{ connector: 'github', name: 'GITHUB_TOKEN' }] },+ widgetId,+ ...statScript,+ }))!.data;++ it('never falls back to the creator personal connector for a workspace widget', async () => {+ await (await gateKeeperModel(ownerId)).create(githubConnector('personal-token-123') as any);+ const owner = widgetRouter.createCaller(context(ownerId, workspaceId));+ const widget = await createWidget(owner);+ await draftWithEnv(owner, widget.id);++ const run = (await owner.dryRun({ widgetId: widget.id }))!.data;+ expect(run).toMatchObject({+ error: {+ code: 'MISSING_ENV',+ message:+ 'Missing required environment: GITHUB_TOKEN (connect "github" for this widget\'s agent or workspace)',+ },+ status: 'failed',+ });+ expect(runSandbox).not.toHaveBeenCalled();+ });++ it('resolves a project widget with the workspace credential, never the personal one', async () => {+ const coordinatorId = await createTestAgent(db, ownerId);+ await db.update(agents).set({ workspaceId }).where(eq(agents.id, coordinatorId));+ const [project] = await db+ .insert(projects)+ .values({+ coordinatorAgentId: coordinatorId,+ identifier: 'DASH',+ name: 'Dashboards project',+ userId: ownerId,+ workspaceId,+ })+ .returning();+ await (await gateKeeperModel(ownerId)).create(githubConnector('personal-token-123') as any);+ const owner = widgetRouter.createCaller(context(ownerId, workspaceId));+ const widget = await createWidget(owner, { projectId: project.id, title: 'Project PRs' });+ expect(widget).toMatchObject({ agentId: null, projectId: project.id, workspaceId });+ await draftWithEnv(owner, widget.id);++ // Only the creator's personal connector exists: the project widget must not use it.+ const missing = (await owner.dryRun({ widgetId: widget.id }))!.data;+ expect(missing).toMatchObject({ error: { code: 'MISSING_ENV' }, status: 'failed' });+ expect(runSandbox).not.toHaveBeenCalled();++ await (+ await gateKeeperModel(ownerId, workspaceId)+ ).create(githubConnector('workspace-token-456') as any);+ runSandbox.mockResolvedValueOnce(ok({ type: 'stat', value: 1 }));+ const run = (await owner.dryRun({ widgetId: widget.id }))!.data;++ expect(run?.status).toBe('succeeded');+ expect(runSandbox.mock.calls[0][0].env).toEqual({ GITHUB_TOKEN: 'workspace-token-456' });+ });++ it('injects a workspace connector only into widgets its creator or the workspace owner authored', async () => {+ // The owner's GitHub connector and a member's Linear connector, both workspace-wide.+ await (+ await gateKeeperModel(ownerId, workspaceId)+ ).create(githubConnector('owner-token-456') as any);+ await (+ await gateKeeperModel(memberId, workspaceId)+ ).create(+ githubConnector('member-token-789', { identifier: 'linear', name: 'Linear' }) as any,+ );+ const member = widgetRouter.createCaller(context(memberId, workspaceId));+ const owner = widgetRouter.createCaller(context(ownerId, workspaceId));+ const linearDraft = (caller: WidgetCaller, widgetId: string) =>+ caller.saveDraft({+ manifest: { env: [{ connector: 'linear', name: 'LINEAR_TOKEN' }] },+ widgetId,+ ...statScript,+ });++ // A member's script must not receive a secret someone else connected.+ const sneaky = await createWidget(member, { title: 'Sneaky' });+ await draftWithEnv(member, sneaky.id);+ const refused = (await member.dryRun({ widgetId: sneaky.id }))!.data;+ expect(refused).toMatchObject({+ error: {+ code: 'CREDENTIALS_FORBIDDEN',+ message:+ 'Connector "github" was connected by another workspace member; only its creator or the workspace owner can author a widget that reads it',+ },+ status: 'failed',+ });+ expect(runSandbox).not.toHaveBeenCalled();++ // Their own workspace connector is fine.+ runSandbox.mockResolvedValue(ok({ type: 'stat', value: 1 }));+ const own = await createWidget(member, { title: 'Own' });+ await linearDraft(member, own.id);+ expect((await member.dryRun({ widgetId: own.id }))!.data?.status).toBe('succeeded');+ expect(runSandbox.mock.calls[0][0].env).toEqual({ LINEAR_TOKEN: 'member-token-789' });++ // The workspace owner may use any workspace connector.+ const curated = await createWidget(owner, { title: 'Curated' });+ await linearDraft(owner, curated.id);+ expect((await owner.dryRun({ widgetId: curated.id }))!.data?.status).toBe('succeeded');+ expect(runSandbox.mock.calls[1][0].env).toEqual({ LINEAR_TOKEN: 'member-token-789' });+ });++ it('reads the header a manifest names from a multi-header connector', async () => {+ await (+ await gateKeeperModel(ownerId, workspaceId)+ ).create({+ ...githubConnector(''),+ credentials: JSON.stringify({+ headers: { 'X-Api-Key': 'key-1', 'X-Tenant': 'tenant-1' },+ type: 'header',+ }),+ } as any);+ const owner = widgetRouter.createCaller(context(ownerId, workspaceId));+ const widget = await createWidget(owner);+ const draft = (await owner.saveDraft({+ manifest: { env: [{ connector: 'github', field: 'X-Tenant', name: 'TENANT' }] },+ widgetId: widget.id,+ ...statScript,+ }))!.data;+ expect(draft.manifest?.env).toEqual([+ { connector: 'github', field: 'X-Tenant', name: 'TENANT' },+ ]);++ runSandbox.mockResolvedValueOnce(ok({ type: 'stat', value: 1 }));+ expect((await owner.dryRun({ widgetId: widget.id }))!.data?.status).toBe('succeeded');+ expect(runSandbox.mock.calls[0][0].env).toEqual({ TENANT: 'tenant-1' });+ });++ it('closes the run as failed when credential resolution itself errors', async () => {+ const owner = widgetRouter.createCaller(context(ownerId, workspaceId));+ const widget = await createWidget(owner);+ await draftWithEnv(owner, widget.id);+ const initWithEnvKey = vi+ .spyOn(KeyVaultsGateKeeper, 'initWithEnvKey')+ .mockRejectedValueOnce(new Error('KEY_VAULTS_SECRET is not set'));++ const run = (await owner.dryRun({ widgetId: widget.id }))!.data;++ expect(run).toMatchObject({+ error: { code: 'CREDENTIALS_ERROR', message: 'Failed to resolve widget credentials' },+ status: 'failed',+ });+ expect(runSandbox).not.toHaveBeenCalled();+ initWithEnvKey.mockRestore();+ });++ it('injects the workspace credential, prefers the agent one, and redacts echoes', async () => {+ await (await gateKeeperModel(ownerId)).create(githubConnector('personal-token-123') as any);+ await (+ await gateKeeperModel(ownerId, workspaceId)+ ).create(githubConnector('workspace-token-456') as any);+ const owner = widgetRouter.createCaller(context(ownerId, workspaceId));++ const widget = await createWidget(owner);+ await draftWithEnv(owner, widget.id);+ runSandbox.mockImplementationOnce(async ({ env }) => ({+ ...ok({ label: `token ${env.GITHUB_TOKEN}`, type: 'stat', value: 1 }),+ stderr: `debug: using ${env.GITHUB_TOKEN}`,+ }));+ const run = (await owner.dryRun({ widgetId: widget.id }))!.data;++ expect(runSandbox.mock.calls[0][0].env).toEqual({ GITHUB_TOKEN: 'workspace-token-456' });+ expect(run?.status).toBe('succeeded');+ expect(run?.output).toMatchObject({ label: 'token [REDACTED:GITHUB_TOKEN]' });+ expect(run?.stdout).not.toContain('workspace-token-456');+ expect(run?.stderr).toBe('debug: using [REDACTED:GITHUB_TOKEN]');++ // An agent-scoped connector outranks the workspace one for the agent's widget.+ const agentId = await createTestAgent(db, ownerId);+ await db.update(agents).set({ workspaceId }).where(eq(agents.id, agentId));+ await (+ await gateKeeperModel(ownerId, workspaceId)+ ).create(githubConnector('agent-token-789', { agentId }) as any);+ const agentWidget = await createWidget(owner, { agentId, title: 'Agent PRs' });+ await draftWithEnv(owner, agentWidget.id);+ runSandbox.mockResolvedValueOnce(ok({ type: 'stat', value: 1 }));+ await owner.dryRun({ widgetId: agentWidget.id });++ expect(runSandbox.mock.calls[1][0].env).toEqual({ GITHUB_TOKEN: 'agent-token-789' });+ });+ });++ describe('permissions', () => {+ it('lets members read and refresh public widgets but not author them', async () => {+ const { board: ownerBoard, widget: owner } = callers(ownerId, workspaceId);+ const { board: memberBoard, widget: member } = callers(memberId, workspaceId);+ const outsider = widgetRouter.createCaller(context(outsiderId));++ const board = (await ownerBoard.create({ title: 'Team board' }))!.data;+ const widget = await createWidget(owner, { dashboardId: board.id, title: 'CI health' });+ const draft = (await owner.saveDraft({ widgetId: widget.id, ...statScript }))!.data;+ runSandbox.mockResolvedValue(ok({ type: 'stat', value: 1 }));+ await owner.dryRun({ widgetId: widget.id });+ await owner.publish({ versionId: draft.id, widgetId: widget.id });++ const detail = (await memberBoard.detail({ id: board.id }))!.data;+ expect(detail.items.map((i) => i.widget.id)).toEqual([widget.id]);+ expect((await member.run({ widgetId: widget.id }))!.data?.status).toBe('succeeded');++ await expect(+ member.saveDraft({ widgetId: widget.id, ...statScript, script: 'x' }),+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });+ await expect(+ member.publish({ versionId: draft.id, widgetId: widget.id }),+ ).rejects.toMatchObject({+ code: 'FORBIDDEN',+ });+ await expect(+ memberBoard.update({ id: board.id, value: { title: 'x' } }),+ ).rejects.toMatchObject({+ code: 'NOT_FOUND',+ });++ await expect(outsider.detail({ id: widget.id })).rejects.toMatchObject({+ code: 'NOT_FOUND',+ });+ await expect(outsider.run({ widgetId: widget.id })).rejects.toMatchObject({+ code: 'NOT_FOUND',+ });+ await expect(outsider.listVersions({ widgetId: widget.id })).rejects.toMatchObject({+ code: 'NOT_FOUND',+ });+ await expect(outsider.listRuns({ widgetId: widget.id })).rejects.toMatchObject({+ code: 'NOT_FOUND',+ });++ const secret = await createWidget(owner, { title: 'Mine', visibility: 'private' });+ await expect(member.detail({ id: secret.id })).rejects.toMatchObject({+ code: 'NOT_FOUND',+ });+ expect((await member.list())!.data.map((w) => w.id)).toEqual([widget.id]);+ });++ 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));+ const [project] = await db+ .insert(projects)+ .values({+ coordinatorAgentId: coordinatorId,+ identifier: 'FLIP',+ name: 'Flipping project',+ userId: ownerId,+ workspaceId,+ })+ .returning();+ const { board: ownerBoard, widget: owner } = callers(ownerId, workspaceId);+ const { board: memberBoard, widget: member } = callers(memberId, workspaceId);+ const memberMetrics = metricRouter.createCaller(context(memberId, workspaceId));++ const board = (await ownerBoard.create({ title: 'Team board' }))!.data;+ const widget = await createWidget(owner, {+ dashboardId: board.id,+ projectId: project.id,+ title: 'Project stars',+ });+ const draft = (await owner.saveDraft({+ manifest: { metric: { key: 'stars' } },+ widgetId: widget.id,+ ...statScript,+ }))!.data;+ runSandbox.mockResolvedValue(ok({ type: 'stat', value: 3 }));+ await owner.dryRun({ widgetId: widget.id });+ await owner.publish({ versionId: draft.id, widgetId: widget.id });+ const run = (await owner.run({ widgetId: widget.id }))!.data!;+ const series = { subjectId: widget.id, subjectType: 'widget' as const };+ expect((await memberMetrics.listSeries(series))!.data).toHaveLength(1);++ await db.update(projects).set({ visibility: 'private' }).where(eq(projects.id, project.id));++ const notFound = { code: 'NOT_FOUND' };+ await expect(member.detail({ id: widget.id })).rejects.toMatchObject(notFound);+ await expect(member.listVersions({ widgetId: widget.id })).rejects.toMatchObject(notFound);+ await expect(+ member.getVersion({ versionId: draft.id, widgetId: widget.id }),+ ).rejects.toMatchObject(notFound);+ await expect(member.listRuns({ widgetId: widget.id })).rejects.toMatchObject(notFound);+ await expect(member.getRun({ runId: run.id, widgetId: widget.id })).rejects.toMatchObject(+ notFound,+ );+ await expect(member.run({ widgetId: widget.id })).rejects.toMatchObject(notFound);+ await expect(memberMetrics.listSeries(series)).rejects.toMatchObject(notFound);+ expect((await member.listByProject({ projectId: project.id }))!.data).toEqual([]);+ // the public board stays, without the hidden widget+ expect((await memberBoard.detail({ id: board.id }))!.data.items).toEqual([]);++ // the project's creator still reads everything+ expect((await owner.detail({ id: widget.id }))!.data.id).toBe(widget.id);+ });++ it('refuses to create a widget on a board the caller cannot manage, leaving no orphan', async () => {+ const ownerBoard = dashboardRouter.createCaller(context(ownerId, workspaceId));+ const member = widgetRouter.createCaller(context(memberId, workspaceId));+ const board = (await ownerBoard.create({ title: 'Team board' }))!.data;++ await expect(+ createWidget(member, { dashboardId: board.id, title: 'Sneaky' }),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });+ expect(await db.select().from(widgets).where(eq(widgets.workspaceId, workspaceId))).toEqual(+ [],+ );+ });++ it('fails and keeps no widget when the board cannot take it after the check', async () => {+ const { board: ownerBoard, widget: owner } = callers(ownerId, workspaceId);+ const board = (await ownerBoard.create({ title: 'Team board' }))!.data;+ const workspaceWidgets = () =>+ db.select().from(widgets).where(eq(widgets.workspaceId, workspaceId));++ // The board is gone by the time the widget is placed.+ vi.spyOn(DashboardModel.prototype, 'addItem').mockResolvedValueOnce(undefined);+ await expect(+ createWidget(owner, { dashboardId: board.id, title: 'Vanished board' }),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });+ expect(await workspaceWidgets()).toEqual([]);++ // The placement insert itself fails.+ vi.spyOn(DashboardModel.prototype, 'addItem').mockRejectedValueOnce(+ new Error('FK violation'),+ );+ await expect(+ createWidget(owner, { dashboardId: board.id, title: 'Failed placement' }),+ ).rejects.toMatchObject({ code: 'INTERNAL_SERVER_ERROR' });+ expect(await workspaceWidgets()).toEqual([]);++ const placed = await createWidget(owner, { dashboardId: board.id, title: 'Placed' });+ expect(placed.item).toMatchObject({ dashboardId: board.id, widgetId: placed.id });+ });++ it('rejects malformed ids before they reach the database', async () => {+ const owner = widgetRouter.createCaller(context(ownerId));++ await expect(owner.detail({ id: 'not-a-uuid' })).rejects.toMatchObject({+ code: 'BAD_REQUEST',+ });+ });+ });++ describe('schedule', () => {+ it('validates cron patterns and fires due widgets once per slot from the tick route', async () => {+ const owner = widgetRouter.createCaller(context(ownerId));+ const widget = await createWidget(owner);++ await expect(owner.setSchedule({ id: widget.id, pattern: '* * *' })).rejects.toMatchObject({+ code: 'BAD_REQUEST',+ });++ const scheduled = (await owner.setSchedule({+ id: widget.id,+ pattern: '*/5 * * * *',+ timezone: 'Asia/Shanghai',+ }))!.data;+ expect(scheduled.nextRunAt).toBeInstanceOf(Date);++ // Not published yet: nothing is due.+ await db+ .update(widgets)+ .set({ nextRunAt: new Date(Date.now() - 60_000) })+ .where(eq(widgets.id, widget.id));+ expect(await runWidgetSchedulerTick(db, { runner: { run: runSandbox } })).toMatchObject({+ due: 0,+ });++ const draft = (await owner.saveDraft({ widgetId: widget.id, ...statScript }))!.data;+ runSandbox.mockResolvedValue(ok({ type: 'stat', value: 5 }));+ await owner.dryRun({ widgetId: widget.id });+ await owner.publish({ versionId: draft.id, widgetId: widget.id });+ await db+ .update(widgets)+ .set({ nextRunAt: new Date(Date.now() - 60_000) })+ .where(eq(widgets.id, widget.id));++ const response = await widgetWorkflowApp.request('/tick', {+ body: '{}',+ headers: { 'content-type': 'application/json' },+ method: 'POST',+ });+ const body = await response.json();+ expect(body).toMatchObject({+ claimed: 1,+ dispatched: 1,+ due: 1,+ results: [{ status: 'succeeded', widgetId: widget.id }],+ success: true,+ });++ const [row] = await db.select().from(widgets).where(eq(widgets.id, widget.id));+ expect(row.nextRunAt!.getTime()).toBeGreaterThan(Date.now());+ expect(row.latestOutput).toEqual({ type: 'stat', value: 5 });+ const runs = await db+ .select()+ .from(widgetRuns)+ .where(and(eq(widgetRuns.widgetId, widget.id), eq(widgetRuns.trigger, 'schedule')));+ expect(runs).toHaveLength(1);++ // The slot moved forward, so an immediate second tick has nothing to do.+ const second = await widgetWorkflowApp.request('/tick', { body: '{}', method: 'POST' });+ expect(await second.json()).toMatchObject({ claimed: 0, due: 0 });+ });++ describe('dispatch and recovery', () => {+ const post = async (path: string, body: unknown) =>+ (+ await widgetWorkflowApp.request(path, {+ body: JSON.stringify(body),+ headers: { 'content-type': 'application/json' },+ method: 'POST',+ })+ ).json();++ /** A published, scheduled widget whose slot is due. */+ const dueWidget = async () => {+ const owner = widgetRouter.createCaller(context(ownerId));+ const widget = await createWidget(owner);+ await owner.setSchedule({ id: widget.id, pattern: '*/5 * * * *' });+ const draft = (await owner.saveDraft({ widgetId: widget.id, ...statScript }))!.data;+ runSandbox.mockResolvedValue(ok({ type: 'stat', value: 5 }));+ await owner.dryRun({ widgetId: widget.id });+ await owner.publish({ versionId: draft.id, widgetId: widget.id });+ runSandbox.mockClear();+ const slot = new Date(Date.now() - 60_000);+ await db.update(widgets).set({ nextRunAt: slot }).where(eq(widgets.id, widget.id));+ return { slot, widget };+ };++ const scheduleRuns = (widgetId: string) =>+ db+ .select()+ .from(widgetRuns)+ .where(and(eq(widgetRuns.widgetId, widgetId), eq(widgetRuns.trigger, 'schedule')));++ const nextRunAt = async (widgetId: string) =>+ (await db.select().from(widgets).where(eq(widgets.id, widgetId)))[0].nextRunAt;++ it('publishes each due slot with a per-slot dedup id and leaves the claim to the worker', async () => {+ vi.stubEnv('APP_URL', 'https://app.test/');+ queueMode.enabled = true;+ const publish = vi+ .spyOn(qstashClient, 'publishJSON')+ .mockResolvedValue({ messageId: 'm1' } as never);+ const { slot, widget } = await dueWidget();++ 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()}`,+ url: 'https://app.test/api/workflows/widget/run-widget',+ });+ // Not claimed and nothing ran in the tick: the slot is still due.+ expect(await nextRunAt(widget.id)).toEqual(slot);+ expect(runSandbox).not.toHaveBeenCalled();++ // A failed publish keeps the slot due, so the next tick retries it.+ publish.mockRejectedValueOnce(new Error('qstash down'));+ expect(await post('/tick', {})).toMatchObject({+ dispatched: 0,+ results: [{ error: expect.stringContaining('qstash down'), widgetId: widget.id }],+ });+ expect(await nextRunAt(widget.id)).toEqual(slot);+ });++ it('runs a redelivered slot exactly once', async () => {+ const { slot, widget } = await dueWidget();+ const message = { slot: slot.toISOString(), widgetId: widget.id };++ expect(await post('/run-widget', message)).toMatchObject({+ status: 'succeeded',+ success: true,+ });+ // QStash redelivers the same message after a lost response.+ expect(await post('/run-widget', message)).toEqual({+ skipped: 'already-claimed',+ success: true,+ });++ expect(runSandbox).toHaveBeenCalledTimes(1);+ expect(await scheduleRuns(widget.id)).toHaveLength(1);+ expect((await nextRunAt(widget.id))!.getTime()).toBeGreaterThan(Date.now());+ });++ /** Make a reserved run look abandoned: started well past any lease. */+ const expireLease = (runId: string) =>+ db+ .update(widgetRuns)+ .set({ startedAt: new Date(Date.now() - 30 * 60_000) })+ .where(eq(widgetRuns.id, runId));++ /** Deliver the slot to a worker that dies after reserving the run. */+ const crashAfterReserve = async (message: { slot: string; widgetId: string }) => {+ vi.spyOn(WidgetModel, 'finishRun').mockRejectedValueOnce(new Error('worker killed'));+ expect(await post('/run-widget', message)).toEqual({ error: 'worker killed' });+ const runs = await scheduleRuns(message.widgetId);+ expect(runs).toMatchObject([{ status: 'running' }]);+ return runs[0];+ };++ it('resumes a reserved run once its worker died and the lease expired, exactly once', async () => {+ const { slot, widget } = await dueWidget();+ const message = { slot: slot.toISOString(), widgetId: widget.id };+ const reserved = await crashAfterReserve(message);++ // Redelivered while the original worker may still be busy: left alone.+ expect(await post('/run-widget', message)).toEqual({+ skipped: 'already-claimed',+ success: true,+ });+ expect(runSandbox).toHaveBeenCalledTimes(1);++ await expireLease(reserved.id);+ const [resumed, again] = await Promise.all([+ post('/run-widget', message),+ post('/run-widget', message),+ ]);+ expect([resumed, again]).toEqual(+ expect.arrayContaining([+ { resumed: true, runId: reserved.id, status: 'succeeded', success: true },+ { skipped: 'already-claimed', success: true },+ ]),+ );+ expect(await post('/run-widget', message)).toEqual({+ skipped: 'already-claimed',+ success: true,+ });++ expect(runSandbox).toHaveBeenCalledTimes(2);+ expect(await scheduleRuns(widget.id)).toMatchObject([+ { id: reserved.id, status: 'succeeded' },+ ]);+ expect((await db.select().from(widgets).where(eq(widgets.id, widget.id)))[0]).toMatchObject(+ { lastRunId: reserved.id, latestOutput: { type: 'stat', value: 5 } },+ );+ });++ it('sweeps a stale reservation from the tick and resumes it through the worker', async () => {+ vi.stubEnv('APP_URL', 'https://app.test/');+ const { slot, widget } = await dueWidget();+ const reserved = await crashAfterReserve({ slot: slot.toISOString(), widgetId: widget.id });++ queueMode.enabled = true;+ const publish = vi+ .spyOn(qstashClient, 'publishJSON')+ .mockResolvedValue({ messageId: 'm1' } as never);++ // Still within its lease: the tick does not touch it.+ expect(await post('/tick', {})).toMatchObject({ due: 0, resumed: 0 });+ expect(publish).not.toHaveBeenCalled();++ await expireLease(reserved.id);+ const [{ startedAt }] = await scheduleRuns(widget.id);+ const leaseStartedAt = startedAt.toISOString();+ expect(await post('/tick', {})).toMatchObject({ due: 0, resumed: 1 });+ const resumeMessage = { leaseStartedAt, runId: reserved.id, widgetId: widget.id };+ expect(publish).toHaveBeenCalledWith({+ body: resumeMessage,+ deduplicationId: `widget-run:${reserved.id}:${leaseStartedAt}`,+ url: 'https://app.test/api/workflows/widget/run-widget',+ });++ expect(await post('/run-widget', resumeMessage)).toEqual({+ resumed: true,+ runId: reserved.id,+ status: 'succeeded',+ success: true,+ });+ // A duplicate resume message finds the lease renewed and the run closed.+ expect(await post('/run-widget', resumeMessage)).toEqual({+ skipped: 'not-resumable',+ success: true,+ });+ expect(runSandbox).toHaveBeenCalledTimes(2);+ expect(await scheduleRuns(widget.id)).toMatchObject([{ status: 'succeeded' }]);+ });++ it('resumes a stale reservation inline when the tick runs widgets itself', async () => {+ const { widget } = await dueWidget();++ // The inline tick reserves the slot and dies before closing the run.+ vi.spyOn(WidgetModel, 'finishRun').mockRejectedValueOnce(new Error('worker killed'));+ expect(await post('/tick', {})).toMatchObject({+ claimed: 1,+ results: [{ error: 'worker killed', widgetId: widget.id }],+ });+ const [reserved] = await scheduleRuns(widget.id);+ expect(reserved).toMatchObject({ status: 'running' });++ expect(await post('/tick', {})).toMatchObject({ claimed: 0, due: 0, resumed: 0 });+ await expireLease(reserved.id);+ expect(await post('/tick', {})).toMatchObject({+ claimed: 0,+ due: 0,+ resumed: 1,+ results: [{ runId: reserved.id, status: 'succeeded', widgetId: widget.id }],+ });+ expect(await post('/tick', {})).toMatchObject({ resumed: 0 });++ expect(runSandbox).toHaveBeenCalledTimes(2);+ expect(await scheduleRuns(widget.id)).toMatchObject([+ { id: reserved.id, status: 'succeeded' },+ ]);+ });++ it('cancels a dead reservation when the schedule is cleared, so re-enabling never resumes it', async () => {+ const owner = widgetRouter.createCaller(context(ownerId));+ const { widget } = await dueWidget();++ vi.spyOn(WidgetModel, 'finishRun').mockRejectedValueOnce(new Error('worker killed'));+ await post('/tick', {});+ const [reserved] = await scheduleRuns(widget.id);+ expect(reserved).toMatchObject({ status: 'running' });++ await owner.setSchedule({ id: widget.id, pattern: null });+ await owner.setSchedule({ id: widget.id, pattern: '*/5 * * * *' });+ await expireLease(reserved.id);++ expect(await post('/tick', {})).toMatchObject({ resumed: 0 });+ expect(runSandbox).toHaveBeenCalledTimes(1);+ expect(await scheduleRuns(widget.id)).toMatchObject([+ { error: { code: 'SCHEDULE_CHANGED' }, id: reserved.id, status: 'failed' },+ ]);+ });++ it('loses the claim when the widget is trashed or republished after the due read', async () => {+ const owner = widgetRouter.createCaller(context(ownerId));+ const { slot, widget } = await dueWidget();+ const [due] = await WidgetModel.findDue(db, { now: new Date() });+ expect(due.widget.id).toBe(widget.id);+ const claim = () =>+ WidgetModel.claimDueRun(db, {+ expectedNextRunAt: slot,+ nextRunAt: new Date(Date.now() + 300_000),+ versionId: due.version.id,+ widgetId: widget.id,+ });++ // a republish between the due read and the claim+ const v2 = (await owner.saveDraft({ widgetId: widget.id, ...statScript, script: 'x' }))!+ .data;+ runSandbox.mockResolvedValueOnce(ok({ type: 'stat', value: 2 }));+ await owner.dryRun({ widgetId: widget.id });+ await owner.publish({ versionId: v2.id, widgetId: widget.id });+ await db.update(widgets).set({ nextRunAt: slot }).where(eq(widgets.id, widget.id));+ expect(await claim()).toBeUndefined();++ // a trash between the due read and the claim+ await new WidgetModel(db, ownerId).trash(widget.id);+ expect(+ await WidgetModel.claimDueRun(db, {+ expectedNextRunAt: slot,+ nextRunAt: new Date(Date.now() + 300_000),+ versionId: v2.id,+ widgetId: widget.id,+ }),+ ).toBeUndefined();+ expect(await scheduleRuns(widget.id)).toEqual([]);+ expect(await nextRunAt(widget.id)).toEqual(slot);+ });++ it('never leaves an old-schedule reservation behind when a claim races a schedule change', async () => {+ const owner = widgetRouter.createCaller(context(ownerId));+ for (let i = 0; i < 5; i++) {+ const { slot, widget } = await dueWidget();+ const [due] = await WidgetModel.findDue(db, { now: new Date() });+ await Promise.all([+ WidgetModel.claimDueRun(db, {+ expectedNextRunAt: slot,+ nextRunAt: new Date(Date.now() + 300_000),+ versionId: due.version.id,+ widgetId: widget.id,+ }),+ owner.setSchedule({ id: widget.id, pattern: null }),+ ]);+ const running = (await scheduleRuns(widget.id)).filter((r) => r.status === 'running');+ expect(running).toEqual([]);+ expect(await nextRunAt(widget.id)).toBeNull();+ }+ });++ it('acks a message without a slot without running or claiming', async () => {+ const { slot, widget } = await dueWidget();++ expect(await post('/run-widget', { widgetId: widget.id })).toEqual({+ skipped: 'missing-slot',+ success: true,+ });+ expect(runSandbox).not.toHaveBeenCalled();+ expect(await scheduleRuns(widget.id)).toHaveLength(0);+ expect(await nextRunAt(widget.id)).toEqual(slot);+ });+ });+ });+});diff --git a/apps/server/src/routers/lambda/__tests__/metric.test.ts b/apps/server/src/routers/lambda/__tests__/metric.test.tsindex 136305c9ed2..f876697fe26 100644--- a/apps/server/src/routers/lambda/__tests__/metric.test.ts+++ b/apps/server/src/routers/lambda/__tests__/metric.test.ts@@ -49,6 +49,12 @@ vi.mock('@/database/models/agent', () => ({return { existsById: vi.fn().mockResolvedValue(false) };}),}));+const mockWidgetFindById = vi.fn();+vi.mock('@/database/models/widget', () => ({+ WidgetModel: vi.fn(function () {+ return { findById: mockWidgetFindById };+ }),+}));vi.mock('@/database/models/project', () => ({ProjectModel: vi.fn(function () {return { findById: vi.fn().mockResolvedValue(null) };@@ -176,6 +182,54 @@ describe('metricRouter', () => {});});+ describe('widget subject', () => {+ it('lists series of a widget the caller can see', async () => {+ mockWidgetFindById.mockResolvedValue({ id: 'widget-1' });+ mockModel.findBySubject.mockResolvedValue([{ id: 'mtr_w' }]);++ await caller.listSeries({ subjectId: 'widget-1', subjectType: 'widget' });++ expect(mockWidgetFindById).toHaveBeenCalledWith('widget-1');+ expect(mockModel.findBySubject).toHaveBeenCalledWith('widget', 'widget-1');+ });++ it('refuses series of a widget the caller cannot see', async () => {+ mockWidgetFindById.mockResolvedValue(undefined);++ await expect(+ caller.listSeries({ subjectId: 'widget-2', subjectType: 'widget' }),+ ).rejects.toMatchObject({ code: 'NOT_FOUND' });+ expect(mockModel.findBySubject).not.toHaveBeenCalled();+ });++ it('refuses every write to a widget series, even for a caller who can see it', async () => {+ mockWidgetFindById.mockResolvedValue({ id: 'widget-1' });+ mockModel.findById.mockResolvedValue({+ id: 'mtr_w',+ subjectId: 'widget-1',+ subjectType: 'widget',+ userId: 'user-1',+ });++ await expect(+ caller.upsertSeries({ key: 'value', subjectId: 'widget-1', subjectType: 'widget' }),+ ).rejects.toMatchObject({ code: 'FORBIDDEN' });+ await expect(caller.addPoint({ id: 'mtr_w', value: 1 })).rejects.toMatchObject({+ code: 'FORBIDDEN',+ });+ await expect(caller.updateSeries({ id: 'mtr_w', title: 'x' })).rejects.toMatchObject({+ code: 'FORBIDDEN',+ });+ await expect(caller.deleteSeries({ id: 'mtr_w' })).rejects.toMatchObject({+ code: 'FORBIDDEN',+ });+ expect(mockModel.ensure).not.toHaveBeenCalled();+ expect(mockModel.addPoint).not.toHaveBeenCalled();+ expect(mockModel.update).not.toHaveBeenCalled();+ expect(mockModel.delete).not.toHaveBeenCalled();+ });+ });+describe('listSeriesWithPoints', () => {it('bundles named series, their recent windows and true first points in one call', async () => {// The per-series alternative amplifies to 1+N RPCs on a polled surface;diff --git a/apps/server/src/routers/lambda/_helpers/widgetError.ts b/apps/server/src/routers/lambda/_helpers/widgetError.tsnew file mode 100644index 00000000000..ddddc443471--- /dev/null+++ b/apps/server/src/routers/lambda/_helpers/widgetError.ts@@ -0,0 +1,40 @@+import { TRPCError } from '@trpc/server';++import { ScopeLevelError } from '@/database/utils/scopeLevel';+import { WidgetFlowError } from '@/server/services/widget';++const FLOW_ERROR_CODES = {+ DRY_RUN_REQUIRED: 'PRECONDITION_FAILED',+ FORBIDDEN: 'FORBIDDEN',+ INVALID_SCHEDULE: 'BAD_REQUEST',+ NOT_FOUND: 'NOT_FOUND',+ NOT_ROLLBACK_TARGET: 'BAD_REQUEST',+ NO_VERSION: 'PRECONDITION_FAILED',+} as const;++export const notFound = (what: string) =>+ new TRPCError({ code: 'NOT_FOUND', message: `${what} not found` });++/**+ * Map widget / dashboard domain errors to TRPC errors. Missing and invisible+ * parents both read as NOT_FOUND so ids from other scopes are not confirmed+ * to exist; anything unexpected is logged and surfaces as a 500.+ */+export function mapWidgetError(error: unknown, domain: string, operation: string): never {+ if (error instanceof TRPCError) throw error;+ if (error instanceof WidgetFlowError) {+ throw new TRPCError({ code: FLOW_ERROR_CODES[error.code], message: error.message });+ }+ if (error instanceof ScopeLevelError) {+ throw new TRPCError({+ code: error.code === 'SCOPE_MISMATCH' ? 'BAD_REQUEST' : 'NOT_FOUND',+ message: error.message,+ });+ }+ console.error(`[${domain}:${operation}]`, error);+ throw new TRPCError({+ cause: error,+ code: 'INTERNAL_SERVER_ERROR',+ message: `Failed to ${operation}`,+ });+}diff --git a/apps/server/src/routers/lambda/dashboard.ts b/apps/server/src/routers/lambda/dashboard.tsnew file mode 100644index 00000000000..eef968b05d1--- /dev/null+++ b/apps/server/src/routers/lambda/dashboard.ts@@ -0,0 +1,224 @@+import { DASHBOARD_VISIBILITIES } from '@lobechat/types';+import { z } from 'zod';++import {+ requireWorkspaceRoleWhenScoped,+ wsCompatProcedure,+} from '@/business/server/trpc-middlewares/workspaceAuth';+import { DashboardModel } from '@/database/models/dashboard';+import { router } from '@/libs/trpc/lambda';+import { serverDatabase } from '@/libs/trpc/lambda/middleware';+import { DashboardService } from '@/server/services/dashboard';++import { mapWidgetError, notFound } from './_helpers/widgetError';++const dashboardProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {+ const { ctx } = opts;+ const workspaceId = ctx.workspaceId ?? undefined;+ return opts.next({+ ctx: {+ dashboardModel: new DashboardModel(ctx.serverDB, ctx.userId, workspaceId),+ dashboardService: new DashboardService(ctx.serverDB, ctx.userId, workspaceId),+ },+ });+});++// Board writes need at least the member role in a workspace; personal mode passes through.+const dashboardWriteProcedure = dashboardProcedure.use(requireWorkspaceRoleWhenScoped('member'));++// ── Schemas ──++// Dashboard rows use uuid keys; reject other shapes before they reach Postgres.+const uuid = z.uuid();+const idInput = z.object({ id: uuid });+const levelInput = z+ .object({ agentId: z.string().nullish(), projectId: z.string().nullish() })+ .optional();+const visibility = z.enum(DASHBOARD_VISIBILITIES);+const metadata = z.record(z.string(), z.unknown()).nullish();+const layoutSchema = z.object({+ h: z.number().int().min(1).max(48),+ w: z.number().int().min(1).max(48),+ x: z.number().int().min(0).max(96),+ y: z.number().int().min(0),+});++const fail = (error: unknown, operation: string): never =>+ mapWidgetError(error, 'dashboard', operation);++/**+ * Dashboards (boards) and the placement of widgets on them. Widgets+ * themselves live in the `widget` router.+ *+ * Access follows `DashboardModel`: reads see readable boards (workspace+ * visibility plus the current visibility of the attached project / agent)+ * and only the widgets the caller may read; edits are limited to the board's+ * creator. Missing and forbidden rows both read as NOT_FOUND.+ */+export const dashboardRouter = router({+ /** Place a widget on a board (or move it when already there). */+ addItem: dashboardWriteProcedure+ .input(+ z.object({+ dashboardId: uuid,+ layout: layoutSchema.nullish(),+ sortOrder: z.number().int().optional(),+ widgetId: uuid,+ }),+ )+ .mutation(async ({ ctx, input }) => {+ try {+ const data = await ctx.dashboardService.placeWidget(input.dashboardId, input.widgetId, {+ layout: input.layout,+ sortOrder: input.sortOrder,+ });+ if (!data) throw notFound('Dashboard or widget');+ return { data, message: 'Widget placed', success: true };+ } catch (error) {+ fail(error, 'place widget');+ }+ }),++ create: dashboardWriteProcedure+ .input(+ z.object({+ agentId: z.string().nullish(),+ description: z.string().max(2000).nullish(),+ icon: z.string().max(100).nullish(),+ metadata,+ projectId: z.string().nullish(),+ sortOrder: z.number().int().optional(),+ title: z.string().min(1).max(200),+ visibility: visibility.optional(),+ }),+ )+ .mutation(async ({ ctx, input }) => {+ try {+ const data = await ctx.dashboardModel.create(input);+ return { data, message: 'Dashboard created', success: true };+ } catch (error) {+ fail(error, 'create dashboard');+ }+ }),++ delete: dashboardWriteProcedure.input(idInput).mutation(async ({ ctx, input }) => {+ try {+ const data = await ctx.dashboardModel.delete(input.id);+ if (!data) throw notFound('Dashboard');+ return { data, message: 'Dashboard deleted', success: true };+ } catch (error) {+ fail(error, 'delete dashboard');+ }+ }),++ /** A board with its visible widgets, in display order. */+ detail: dashboardProcedure.input(idInput).query(async ({ ctx, input }) => {+ try {+ const data = await ctx.dashboardService.getDetail(input.id);+ if (!data) throw notFound('Dashboard');+ return { data, success: true };+ } catch (error) {+ fail(error, 'get dashboard');+ }+ }),++ /** Boards living directly on one level (personal / workspace, project, agent). */+ list: dashboardProcedure.input(levelInput).query(async ({ ctx, input }) => {+ try {+ return { data: await ctx.dashboardModel.list(input ?? {}), success: true };+ } catch (error) {+ fail(error, 'list dashboards');+ }+ }),++ /** Every board of a project, including those an agent of the project also owns. */+ listByProject: dashboardProcedure+ .input(z.object({ projectId: z.string().min(1) }))+ .query(async ({ ctx, input }) => {+ try {+ return { data: await ctx.dashboardModel.listByProject(input.projectId), success: true };+ } catch (error) {+ fail(error, 'list project dashboards');+ }+ }),++ removeItems: dashboardWriteProcedure+ .input(z.object({ dashboardId: uuid, itemIds: z.array(uuid).max(200) }))+ .mutation(async ({ ctx, input }) => {+ try {+ const data = await ctx.dashboardService.removeItems(input.dashboardId, input.itemIds);+ return { data, message: 'Widgets removed from dashboard', success: true };+ } catch (error) {+ fail(error, 'remove widgets');+ }+ }),++ restore: dashboardWriteProcedure.input(idInput).mutation(async ({ ctx, input }) => {+ try {+ const data = await ctx.dashboardModel.restore(input.id);+ if (!data) throw notFound('Dashboard');+ return { data, message: 'Dashboard restored', success: true };+ } catch (error) {+ fail(error, 'restore dashboard');+ }+ }),++ trash: dashboardWriteProcedure.input(idInput).mutation(async ({ ctx, input }) => {+ try {+ const data = await ctx.dashboardModel.trash(input.id);+ if (!data) throw notFound('Dashboard');+ return { data, message: 'Dashboard moved to trash', success: true };+ } catch (error) {+ fail(error, 'trash dashboard');+ }+ }),++ update: dashboardWriteProcedure+ .input(+ z.object({+ id: uuid,+ value: z.object({+ description: z.string().max(2000).nullish(),+ icon: z.string().max(100).nullish(),+ metadata,+ sortOrder: z.number().int().optional(),+ title: z.string().min(1).max(200).optional(),+ visibility: visibility.optional(),+ }),+ }),+ )+ .mutation(async ({ ctx, input }) => {+ try {+ const data = await ctx.dashboardModel.update(input.id, input.value);+ if (!data) throw notFound('Dashboard');+ return { data, message: 'Dashboard updated', success: true };+ } catch (error) {+ fail(error, 'update dashboard');+ }+ }),++ /** Persist a drag-and-drop result; ids not on this board are ignored. */+ updateItemLayouts: dashboardWriteProcedure+ .input(+ z.object({+ dashboardId: uuid,+ patches: z+ .array(+ z.object({+ id: uuid,+ layout: layoutSchema.nullish(),+ sortOrder: z.number().int().optional(),+ }),+ )+ .max(200),+ }),+ )+ .mutation(async ({ ctx, input }) => {+ try {+ const data = await ctx.dashboardService.saveLayout(input.dashboardId, input.patches);+ return { data, message: 'Layout saved', success: true };+ } catch (error) {+ fail(error, 'save layout');+ }+ }),+});diff --git a/apps/server/src/routers/lambda/index.ts b/apps/server/src/routers/lambda/index.tsindex 7b7171f4104..ac739b8ead0 100644--- a/apps/server/src/routers/lambda/index.ts+++ b/apps/server/src/routers/lambda/index.ts@@ -49,6 +49,7 @@ import { comfyuiRouter } from './comfyui';import { composioRouter } from './composio';import { configRouter } from './config';import { connectorRouter } from './connector';+import { dashboardRouter } from './dashboard';import { deviceRouter } from './device';import { deviceMetricRouter } from './deviceMetric';import { documentRouter } from './document';@@ -103,6 +104,7 @@ import { userMemoryRouter } from './userMemory';import { verifyRouter } from './verify';import { videoRouter } from './video';import { webBrowsingRouter } from './webBrowsing';+import { widgetRouter } from './widget';import { workRouter } from './work';import { workspaceUserSettingsRouter } from './workspaceUserSettings';@@ -135,6 +137,7 @@ export const lambdaRouter = router({comfyui: comfyuiRouter,config: configRouter,connector: connectorRouter,+ dashboard: dashboardRouter,device: deviceRouter,deviceMetric: deviceMetricRouter,document: documentRouter,@@ -192,6 +195,7 @@ export const lambdaRouter = router({verify: verifyRouter,video: videoRouter,webBrowsing: webBrowsingRouter,+ widget: widgetRouter,work: workRouter,workspace: workspaceRouter,workspaceAuditLog: workspaceAuditLogRouter,diff --git a/apps/server/src/routers/lambda/metric.ts b/apps/server/src/routers/lambda/metric.tsindex ebb0ffe2377..138775dee69 100644--- a/apps/server/src/routers/lambda/metric.ts+++ b/apps/server/src/routers/lambda/metric.ts@@ -1,4 +1,5 @@import type { MetricSubjectType } from '@lobechat/types';+import { METRIC_SUBJECT_TYPES } from '@lobechat/types';import { TRPCError } from '@trpc/server';import { z } from 'zod';@@ -9,6 +10,7 @@ import { GoalModel } from '@/database/models/goal';import { MetricModel } from '@/database/models/metric';import { ProjectModel } from '@/database/models/project';import { TaskModel } from '@/database/models/task';+import { WidgetModel } from '@/database/models/widget';import type { LobeChatDatabase } from '@/database/type';import { router } from '@/libs/trpc/lambda';import { serverDatabase } from '@/libs/trpc/lambda/middleware';@@ -31,7 +33,7 @@ const metricWriteProcedure = metricProcedure.use(withScopedPermission('agent:updconst idInput = z.object({ id: z.string() });const subjectInput = z.object({subjectId: z.string(),- subjectType: z.enum(['goal', 'task', 'agent', 'project', 'workspace']),+ subjectType: z.enum(METRIC_SUBJECT_TYPES),});const configSchema = z.object({direction: z.enum(['higher_is_better', 'lower_is_better']).optional(),@@ -103,6 +105,9 @@ const assertSubjectVisible = async (case 'task': {return new TaskModel(db, ctx.userId, workspaceId).findById(subjectId);}+ case 'widget': {+ return new WidgetModel(db, ctx.userId, workspaceId).findById(subjectId);+ }case 'workspace': {return workspaceId === subjectId;}@@ -118,6 +123,21 @@ const assertSubjectVisible = async (* measures. Doubles as orphan protection — a series whose subject was deleted* stops resolving instead of lingering as readable, writable telemetry.*/+/**+ * Widget series are written only by the widget's own runs (see+ * `services/widget/metrics`), which own the fixed `value` / `series:<name>`+ * keys. Letting the generic API create, append to, edit or delete them would+ * let any workspace member pre-claim those keys or rewrite a coworker's trend,+ * since series ownership here widens to the whole workspace. Reads stay open.+ */+const assertSubjectWritable = (subjectType: MetricSubjectType) => {+ if (subjectType === 'widget')+ throw new TRPCError({+ code: 'FORBIDDEN',+ message: "Widget metrics are written by the widget's runs, not through the metric API",+ });+};+const requireVisibleSeries = async (db: LobeChatDatabase,ctx: { metricModel: MetricModel; userId: string; workspaceId?: string | null },@@ -146,7 +166,8 @@ export const metricRouter = router({).mutation(async ({ input, ctx }) => {try {- await requireVisibleSeries(ctx.serverDB, ctx, input.id);+ const series = await requireVisibleSeries(ctx.serverDB, ctx, input.id);+ assertSubjectWritable(series.subjectType);const point = await ctx.metricModel.addPoint(input.id, {actorId: ctx.userId,actorType: 'user',@@ -165,6 +186,7 @@ export const metricRouter = router({deleteSeries: metricWriteProcedure.input(idInput).mutation(async ({ input, ctx }) => {try {const series = await requireVisibleSeries(ctx.serverDB, ctx, input.id);+ assertSubjectWritable(series.subjectType);// Workspace visibility lets any member read the series; deleting it (and// cascading every observation) stays with the creator or an owner.assertWorkspaceRowManageable(ctx, series.userId, 'metric series');@@ -295,6 +317,7 @@ export const metricRouter = router({try {const { id, ...patch } = input;const existing = await requireVisibleSeries(ctx.serverDB, ctx, id);+ assertSubjectWritable(existing.subjectType);// Definition edits rewrite the render/evaluation contract for everyone// reading the series — creator or workspace owner only.assertWorkspaceRowManageable(ctx, existing.userId, 'metric series');@@ -317,6 +340,7 @@ export const metricRouter = router({).mutation(async ({ input, ctx }) => {try {+ assertSubjectWritable(input.subjectType);await assertSubjectVisible(ctx.serverDB, ctx, input.subjectType, input.subjectId);const series = await ctx.metricModel.ensure(input);if (!series)diff --git a/apps/server/src/routers/lambda/widget.ts b/apps/server/src/routers/lambda/widget.tsnew file mode 100644index 00000000000..b67fe64fd52--- /dev/null+++ b/apps/server/src/routers/lambda/widget.ts@@ -0,0 +1,345 @@+import { WIDGET_VISIBILITIES } from '@lobechat/types';+import { z } from 'zod';++import {+ requireWorkspaceRoleWhenScoped,+ wsCompatProcedure,+} from '@/business/server/trpc-middlewares/workspaceAuth';+import { DashboardModel } from '@/database/models/dashboard';+import { WidgetModel } from '@/database/models/widget';+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 { WidgetService } from '@/server/services/widget';+import { widgetVersionContentSchema } from '@/server/services/widget/versionSchema';++import { mapWidgetError, notFound } from './_helpers/widgetError';++const widgetProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {+ const { ctx } = opts;+ const workspaceId = ctx.workspaceId ?? undefined;+ return opts.next({+ ctx: {+ dashboardModel: new DashboardModel(ctx.serverDB, ctx.userId, workspaceId),+ dashboardService: new DashboardService(ctx.serverDB, ctx.userId, workspaceId),+ widgetModel: new WidgetModel(ctx.serverDB, ctx.userId, workspaceId),+ widgetService: new WidgetService(ctx.serverDB, ctx.userId, workspaceId),+ },+ });+});++// Writes — including running a widget, which spends sandbox time — need at+// least the member role in a workspace; personal mode passes through.+const widgetWriteProcedure = widgetProcedure.use(requireWorkspaceRoleWhenScoped('member'));++// ── Schemas ──++// Widget rows use uuid keys; reject other shapes before they reach Postgres.+const uuid = z.uuid();+const idInput = z.object({ id: uuid });+const levelInput = z+ .object({ agentId: z.string().nullish(), projectId: z.string().nullish() })+ .optional();+const visibility = z.enum(WIDGET_VISIBILITIES);+const metadata = z.record(z.string(), z.unknown()).nullish();+const layoutSchema = z.object({+ h: z.number().int().min(1).max(48),+ w: z.number().int().min(1).max(48),+ x: z.number().int().min(0).max(96),+ y: z.number().int().min(0),+});++const fail = (error: unknown, operation: string): never =>+ mapWidgetError(error, 'widget', operation);++/**+ * Widgets, their versions and runs.+ *+ * Access follows `WidgetModel`: reads see what the caller may read (workspace+ * visibility plus the current visibility of the attached project / agent),+ * edits are limited to the creator, and running a published widget is open+ * to any member who can see it. Missing and forbidden rows both read as+ * NOT_FOUND.+ */+export const widgetRouter = router({+ /**+ * Create a widget; with `dashboardId`, place it on that board right away.+ * Creation and placement share one transaction: when the board cannot take+ * the widget — refused up front, or gone by the time it is placed — the+ * request fails and no orphan widget is left behind.+ */+ create: widgetWriteProcedure+ .input(+ z.object({+ agentId: z.string().nullish(),+ dashboardId: uuid.optional(),+ description: z.string().max(2000).nullish(),+ layout: layoutSchema.nullish(),+ metadata,+ projectId: z.string().nullish(),+ title: z.string().min(1).max(200),+ visibility: visibility.optional(),+ }),+ )+ .mutation(async ({ ctx, input }) => {+ try {+ const { dashboardId, layout, ...widgetInput } = input;+ if (!dashboardId) {+ const widget = await ctx.widgetModel.create(widgetInput);+ return { data: { ...widget, item: null }, message: 'Widget created', success: true };+ }++ if (!(await ctx.dashboardService.findManageable(dashboardId))) {+ throw notFound('Dashboard');+ }++ const workspaceId = ctx.workspaceId ?? undefined;+ const data = await ctx.serverDB.transaction(async (tx) => {+ const txDB = tx as LobeChatDatabase;+ const widget = await new WidgetModel(txDB, ctx.userId, workspaceId).create(widgetInput);+ const item = await new DashboardService(txDB, ctx.userId, workspaceId).placeWidget(+ dashboardId,+ widget.id,+ { layout },+ );+ // The board vanished after the check: roll the widget back with it.+ if (!item) throw notFound('Dashboard');+ return { ...widget, item };+ });++ return { data, message: 'Widget created', success: true };+ } catch (error) {+ fail(error, 'create widget');+ }+ }),++ delete: widgetWriteProcedure.input(idInput).mutation(async ({ ctx, input }) => {+ try {+ const data = await ctx.widgetModel.delete(input.id);+ if (!data) throw notFound('Widget');+ return { data, message: 'Widget deleted', success: true };+ } catch (error) {+ fail(error, 'delete widget');+ }+ }),++ /** A widget with its published and draft versions and the boards it is placed on. */+ detail: widgetProcedure.input(idInput).query(async ({ ctx, input }) => {+ try {+ const widget = await ctx.widgetModel.findById(input.id);+ if (!widget) throw notFound('Widget');++ const [publishedVersion, draftVersion, dashboards] = await Promise.all([+ widget.publishedVersionId+ ? ctx.widgetModel.findVersion(widget.id, widget.publishedVersionId)+ : undefined,+ widget.draftVersionId+ ? ctx.widgetModel.findVersion(widget.id, widget.draftVersionId)+ : undefined,+ ctx.dashboardModel.listByWidget(widget.id),+ ]);++ return {+ data: {+ ...widget,+ dashboards,+ draftVersion: draftVersion ?? null,+ publishedVersion: publishedVersion ?? null,+ },+ success: true,+ };+ } catch (error) {+ fail(error, 'get widget');+ }+ }),++ /** Execute a draft (default: the current one) without touching the live widget. */+ dryRun: widgetWriteProcedure+ .input(z.object({ versionId: uuid.optional(), widgetId: uuid }))+ .mutation(async ({ ctx, input }) => {+ try {+ const data = await ctx.widgetService.dryRun(input.widgetId, { versionId: input.versionId });+ return { data, message: `Dry run ${data?.status}`, success: true };+ } catch (error) {+ fail(error, 'dry-run widget');+ }+ }),++ getRun: widgetProcedure+ .input(z.object({ runId: uuid, widgetId: uuid }))+ .query(async ({ ctx, input }) => {+ try {+ const data = await ctx.widgetModel.findRun(input.widgetId, input.runId);+ if (!data) throw notFound('Run');+ return { data, success: true };+ } catch (error) {+ fail(error, 'get widget run');+ }+ }),++ getVersion: widgetProcedure+ .input(z.object({ versionId: uuid, widgetId: uuid }))+ .query(async ({ ctx, input }) => {+ try {+ const data = await ctx.widgetModel.findVersion(input.widgetId, input.versionId);+ if (!data) throw notFound('Version');+ return { data, success: true };+ } catch (error) {+ fail(error, 'get widget version');+ }+ }),++ /** Widgets living directly on one level (personal / workspace, project, agent). */+ list: widgetProcedure.input(levelInput).query(async ({ ctx, input }) => {+ try {+ return { data: await ctx.widgetModel.list(input ?? {}), success: true };+ } catch (error) {+ fail(error, 'list widgets');+ }+ }),++ /** Every widget of a project, including those an agent of the project also owns. */+ listByProject: widgetProcedure+ .input(z.object({ projectId: z.string().min(1) }))+ .query(async ({ ctx, input }) => {+ try {+ return { data: await ctx.widgetModel.listByProject(input.projectId), success: true };+ } catch (error) {+ fail(error, 'list project widgets');+ }+ }),++ listRuns: widgetProcedure+ .input(z.object({ limit: z.number().int().min(1).max(100).optional(), widgetId: uuid }))+ .query(async ({ ctx, input }) => {+ try {+ if (!(await ctx.widgetModel.findById(input.widgetId))) throw notFound('Widget');+ const data = await ctx.widgetModel.listRuns(input.widgetId, { limit: input.limit });+ return { data, success: true };+ } catch (error) {+ fail(error, 'list widget runs');+ }+ }),++ listVersions: widgetProcedure+ .input(z.object({ widgetId: uuid }))+ .query(async ({ ctx, input }) => {+ try {+ if (!(await ctx.widgetModel.findById(input.widgetId))) throw notFound('Widget');+ return { data: await ctx.widgetModel.listVersions(input.widgetId), success: true };+ } catch (error) {+ fail(error, 'list widget versions');+ }+ }),++ publish: widgetWriteProcedure+ .input(z.object({ versionId: uuid, widgetId: uuid }))+ .mutation(async ({ ctx, input }) => {+ try {+ const data = await ctx.widgetService.publish(input.widgetId, input.versionId);+ return { data, message: 'Version published', success: true };+ } catch (error) {+ fail(error, 'publish widget version');+ }+ }),++ restore: widgetWriteProcedure.input(idInput).mutation(async ({ ctx, input }) => {+ try {+ const data = await ctx.widgetModel.restore(input.id);+ if (!data) throw notFound('Widget');+ return { data, message: 'Widget restored', success: true };+ } catch (error) {+ fail(error, 'restore widget');+ }+ }),++ /** Re-publish a previously published version (default: the one last replaced). */+ rollback: widgetWriteProcedure+ .input(z.object({ versionId: uuid.optional(), widgetId: uuid }))+ .mutation(async ({ ctx, input }) => {+ try {+ const data = await ctx.widgetService.rollback(input.widgetId, input.versionId);+ return { data, message: 'Version rolled back', success: true };+ } catch (error) {+ fail(error, 'roll back widget version');+ }+ }),++ /** Refresh the published version now. */+ run: widgetWriteProcedure.input(z.object({ widgetId: uuid })).mutation(async ({ ctx, input }) => {+ try {+ const data = await ctx.widgetService.runNow(input.widgetId);+ return { data, message: `Run ${data?.status}`, success: true };+ } catch (error) {+ fail(error, 'run widget');+ }+ }),++ /** Record script + contract as the widget's draft; identical content reuses the draft. */+ saveDraft: widgetWriteProcedure+ .input(widgetVersionContentSchema.extend({ widgetId: uuid }))+ .mutation(async ({ ctx, input }) => {+ try {+ const { widgetId, ...version } = input;+ const data = await ctx.widgetService.saveDraft(widgetId, {+ ...version,+ sourceType: 'user',+ });+ return { data, message: 'Draft saved', success: true };+ } catch (error) {+ fail(error, 'save widget draft');+ }+ }),++ /** Set (cron pattern) or clear (null) the refresh schedule. */+ setSchedule: widgetWriteProcedure+ .input(+ z.object({+ id: uuid,+ pattern: z.string().max(100).nullable(),+ timezone: z.string().max(64).nullish(),+ }),+ )+ .mutation(async ({ ctx, input }) => {+ try {+ const data = await ctx.widgetService.setSchedule(input.id, input.pattern, input.timezone);+ if (!data) throw notFound('Widget');+ return { data, message: 'Schedule saved', success: true };+ } catch (error) {+ fail(error, 'set widget schedule');+ }+ }),++ trash: widgetWriteProcedure.input(idInput).mutation(async ({ ctx, input }) => {+ try {+ const data = await ctx.widgetModel.trash(input.id);+ if (!data) throw notFound('Widget');+ return { data, message: 'Widget moved to trash', success: true };+ } catch (error) {+ fail(error, 'trash widget');+ }+ }),++ update: widgetWriteProcedure+ .input(+ z.object({+ id: uuid,+ value: z.object({+ description: z.string().max(2000).nullish(),+ metadata,+ title: z.string().min(1).max(200).optional(),+ visibility: visibility.optional(),+ }),+ }),+ )+ .mutation(async ({ ctx, input }) => {+ try {+ const data = await ctx.widgetModel.update(input.id, input.value);+ if (!data) throw notFound('Widget');+ return { data, message: 'Widget updated', success: true };+ } catch (error) {+ fail(error, 'update widget');+ }+ }),+});diff --git a/apps/server/src/services/dashboard/__tests__/index.test.ts b/apps/server/src/services/dashboard/__tests__/index.test.tsnew file mode 100644index 00000000000..c9b22fe83f8--- /dev/null+++ b/apps/server/src/services/dashboard/__tests__/index.test.ts@@ -0,0 +1,38 @@+import { describe, expect, it } from 'vitest';++import { DASHBOARD_GRID, normalizeItemLayout } from '../index';++describe('normalizeItemLayout', () => {+ it('rounds to whole cells and keeps spans and offsets on the grid', () => {+ expect(normalizeItemLayout({ h: 2.4, w: 0, x: -3, y: 1.6 })).toEqual({+ h: 2,+ w: 1,+ x: 0,+ y: 2,+ });+ expect(normalizeItemLayout({ h: 999, w: 999, x: 999, y: 5 })).toEqual({+ h: DASHBOARD_GRID.maxSpan,+ w: DASHBOARD_GRID.maxSpan,+ x: DASHBOARD_GRID.maxColumns - DASHBOARD_GRID.maxSpan,+ y: 5,+ });+ });++ it('keeps the whole item inside the last column', () => {+ // a wide item near the right edge is pulled left so it ends on the grid+ expect(normalizeItemLayout({ h: 1, w: 20, x: 80, y: 0 })).toMatchObject({ w: 20, x: 76 });+ // a one-cell item cannot start past the final column+ expect(normalizeItemLayout({ h: 1, w: 1, x: 96, y: 0 })).toMatchObject({ w: 1, x: 95 });+ // the clamp uses the normalized width, not the raw one+ expect(normalizeItemLayout({ h: 1, w: 0, x: 96, y: 0 })).toMatchObject({ w: 1, x: 95 });+ expect(normalizeItemLayout({ h: 1, w: 999, x: 60, y: 0 })).toMatchObject({ w: 48, x: 48 });+ for (const layout of [+ { h: 1, w: 20, x: 80, y: 0 },+ { h: 1, w: 1, x: 96, y: 0 },+ { h: 1, w: 48, x: 1000, y: 0 },+ ]) {+ const { w, x } = normalizeItemLayout(layout);+ expect(x + w).toBeLessThanOrEqual(DASHBOARD_GRID.maxColumns);+ }+ });+});diff --git a/apps/server/src/services/dashboard/index.ts b/apps/server/src/services/dashboard/index.tsnew file mode 100644index 00000000000..21cff63bcad--- /dev/null+++ b/apps/server/src/services/dashboard/index.ts@@ -0,0 +1,87 @@+import type { DashboardItemLayout } from '@lobechat/types';++import {+ type AddDashboardItemInput,+ type DashboardItemLayoutPatch,+ DashboardModel,+} from '@/database/models/dashboard';+import type { LobeChatDatabase } from '@/database/type';++/** Grid bounds a placed item must stay within. */+export const DASHBOARD_GRID = {+ maxColumns: 96,+ maxSpan: 48,+} as const;++/**+ * Keep a layout on the grid: integer cells, a span of at least one cell, and+ * the whole item inside the columns — the width is normalized first, then `x`+ * is clamped so the item ends on the last column at the latest. Rows are+ * unbounded, so only `y >= 0` applies there.+ */+export const normalizeItemLayout = (layout: DashboardItemLayout): DashboardItemLayout => {+ const cell = (value: number, min: number, max: number) =>+ Math.min(max, Math.max(min, Math.round(value)));+ const w = cell(layout.w, 1, Math.min(DASHBOARD_GRID.maxSpan, DASHBOARD_GRID.maxColumns));+ return {+ h: cell(layout.h, 1, DASHBOARD_GRID.maxSpan),+ w,+ x: cell(layout.x, 0, DASHBOARD_GRID.maxColumns - w),+ y: cell(layout.y, 0, Number.MAX_SAFE_INTEGER),+ };+};++/**+ * Boards and the placement of widgets on them, on behalf of one caller.+ * Access follows `DashboardModel`: reads see readable boards (and only the+ * widgets the caller may read), writes are limited to the board's creator.+ */+export class DashboardService {+ private readonly model: DashboardModel;++ constructor(+ db: LobeChatDatabase,+ private readonly userId: string,+ workspaceId?: string,+ ) {+ this.model = new DashboardModel(db, userId, workspaceId);+ }++ /** A readable board with its visible items, in display order. */+ async getDetail(dashboardId: string) {+ const dashboard = await this.model.findById(dashboardId);+ if (!dashboard) return undefined;++ const items = await this.model.listItems(dashboardId);+ return { ...dashboard, items };+ }++ /** The board when the caller may change it (creator of a readable board). */+ async findManageable(dashboardId: string) {+ const dashboard = await this.model.findById(dashboardId);+ return dashboard?.userId === this.userId ? dashboard : undefined;+ }++ /** Place a widget on a board, or move it when it is already there. */+ async placeWidget(dashboardId: string, widgetId: string, input: AddDashboardItemInput = {}) {+ return this.model.addItem(dashboardId, widgetId, {+ ...input,+ layout: input.layout ? normalizeItemLayout(input.layout) : input.layout,+ });+ }++ /** Persist a drag-and-drop result; returns how many items moved. */+ async saveLayout(dashboardId: string, patches: DashboardItemLayoutPatch[]) {+ return this.model.updateItemLayouts(+ dashboardId,+ patches.map((patch) => ({+ ...patch,+ layout: patch.layout ? normalizeItemLayout(patch.layout) : patch.layout,+ })),+ );+ }++ async removeItems(dashboardId: string, itemIds: string[]) {+ return this.model.removeItems(dashboardId, itemIds);+ }+}diff --git a/apps/server/src/services/trash/__tests__/index.test.ts b/apps/server/src/services/trash/__tests__/index.test.tsindex 024a5b798f8..dc51d7a08be 100644--- a/apps/server/src/services/trash/__tests__/index.test.ts+++ b/apps/server/src/services/trash/__tests__/index.test.ts@@ -5,18 +5,22 @@ import { eq } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { AgentModel } from '@/database/models/agent';+import { DashboardModel } from '@/database/models/dashboard';import { MessageModel } from '@/database/models/message';import { SessionModel } from '@/database/models/session';import { TopicModel } from '@/database/models/topic';import { TrashModel } from '@/database/models/trash';+import { WidgetModel } from '@/database/models/widget';import { HomeRepository } from '@/database/repositories/home';import {agents,+ dashboards,messages,sessions,topics,trashItems,users,+ widgets,workspaces,} from '@/database/schemas';import type { LobeChatDatabase } from '@/database/type';@@ -590,6 +594,66 @@ describe('TrashService', () => {});});+ describe('widgets', () => {+ it('restores a trashed widget from the bin', async () => {+ const widgetModel = new WidgetModel(serverDB, userId);+ const widget = await widgetModel.create({ title: 'Open PRs' });+ await widgetModel.trash(widget.id);++ const { items } = await service.list();+ expect(items.map((i) => [i.resourceType, i.resourceId])).toEqual([['widget', widget.id]]);++ const outcome = await service.restore(items.map((i) => i.id));+ expect(outcome.failed).toEqual([]);+ expect(outcome.restored).toHaveLength(1);+ expect(await widgetModel.findById(widget.id)).toMatchObject({+ id: widget.id,+ isDeleted: null,+ });+ expect(await serverDB.select().from(trashItems)).toHaveLength(0);+ });++ it('purges a trashed widget when the bin is emptied', async () => {+ const widgetModel = new WidgetModel(serverDB, userId);+ const widget = await widgetModel.create({ title: 'Open PRs' });+ await widgetModel.trash(widget.id);++ expect(await service.emptyTrash()).toEqual({ hasMore: false, purged: 1 });+ expect(await serverDB.select().from(widgets)).toHaveLength(0);+ expect(await serverDB.select().from(trashItems)).toHaveLength(0);+ });+ });++ describe('dashboards', () => {+ it('restores a trashed dashboard from the bin', async () => {+ const dashboardModel = new DashboardModel(serverDB, userId);+ const board = await dashboardModel.create({ title: 'Ops' });+ await dashboardModel.trash(board.id);++ const { items } = await service.list();+ expect(items.map((i) => [i.resourceType, i.resourceId])).toEqual([['dashboard', board.id]]);++ const outcome = await service.restore(items.map((i) => i.id));+ expect(outcome.failed).toEqual([]);+ expect(outcome.restored).toHaveLength(1);+ expect(await dashboardModel.findById(board.id)).toMatchObject({+ id: board.id,+ isDeleted: null,+ });+ expect(await serverDB.select().from(trashItems)).toHaveLength(0);+ });++ it('purges a trashed dashboard when the bin is emptied', async () => {+ const dashboardModel = new DashboardModel(serverDB, userId);+ const board = await dashboardModel.create({ title: 'Ops' });+ await dashboardModel.trash(board.id);++ expect(await service.emptyTrash()).toEqual({ hasMore: false, purged: 1 });+ expect(await serverDB.select().from(dashboards)).toHaveLength(0);+ expect(await serverDB.select().from(trashItems)).toHaveLength(0);+ });+ });+describe('sweep', () => {it('purges only expired roots, across users, and prunes stale registry rows', async () => {const otherService = new TrashService(serverDB, otherUserId);diff --git a/apps/server/src/services/trash/handlers/dashboard.ts b/apps/server/src/services/trash/handlers/dashboard.tsnew file mode 100644index 00000000000..491c1d920b6--- /dev/null+++ b/apps/server/src/services/trash/handlers/dashboard.ts@@ -0,0 +1,25 @@+import { DashboardModel } from '@/database/models/dashboard';++import { type TrashHandler, type TrashHandlerContext, TrashRestoreError } from './types';++/**+ * Dashboards register their own `trash_items` row when trashed (see+ * `DashboardModel.trash`). The model scopes restore / delete to the board's+ * creator, so both run as the registry row's owner: the service has already+ * checked the caller may act on that row.+ */+const ownerModel = (+ ctx: TrashHandlerContext,+ root: { userId: string; workspaceId: string | null },+) => new DashboardModel(ctx.db, root.userId, root.workspaceId ?? undefined);++export const dashboardHandler: TrashHandler = {+ purge: async (ctx, root) => {+ await ownerModel(ctx, root).purge(root.resourceId);+ },+ restore: async (ctx, root) => {+ const restored = await ownerModel(ctx, root).restore(root.resourceId);+ if (!restored) throw new TrashRestoreError('notFound');+ },+ type: 'dashboard',+};diff --git a/apps/server/src/services/trash/handlers/index.ts b/apps/server/src/services/trash/handlers/index.tsindex 21f88f1c21c..40bd0e673d8 100644--- a/apps/server/src/services/trash/handlers/index.ts+++ b/apps/server/src/services/trash/handlers/index.ts@@ -1,9 +1,11 @@import type { TrashResourceType } from '@lobechat/types';import { agentHandler } from './agent';+import { dashboardHandler } from './dashboard';import { messageHandler } from './message';import { topicHandler } from './topic';import type { TrashHandler } from './types';+import { widgetHandler } from './widget';/*** One handler per trashable kind. `Partial` on purpose: `TrashResourceType`@@ -16,7 +18,9 @@ import type { TrashHandler } from './types';export const TRASH_HANDLERS: Partial<Record<TrashResourceType, TrashHandler>> = {agent: agentHandler,message: messageHandler,+ dashboard: dashboardHandler,topic: topicHandler,+ widget: widgetHandler,};/**diff --git a/apps/server/src/services/trash/handlers/widget.ts b/apps/server/src/services/trash/handlers/widget.tsnew file mode 100644index 00000000000..a33fb34782a--- /dev/null+++ b/apps/server/src/services/trash/handlers/widget.ts@@ -0,0 +1,25 @@+import { WidgetModel } from '@/database/models/widget';++import { type TrashHandler, type TrashHandlerContext, TrashRestoreError } from './types';++/**+ * Widgets register their own `trash_items` row when trashed (see+ * `WidgetModel.trash`). The model scopes restore / delete to the widget's+ * creator, so both run as the registry row's owner: the service has already+ * checked the caller may act on that row.+ */+const ownerModel = (+ ctx: TrashHandlerContext,+ root: { userId: string; workspaceId: string | null },+) => new WidgetModel(ctx.db, root.userId, root.workspaceId ?? undefined);++export const widgetHandler: TrashHandler = {+ purge: async (ctx, root) => {+ await ownerModel(ctx, root).purge(root.resourceId);+ },+ restore: async (ctx, root) => {+ const restored = await ownerModel(ctx, root).restore(root.resourceId);+ if (!restored) throw new TrashRestoreError('notFound');+ },+ type: 'widget',+};diff --git a/apps/server/src/services/widget/__tests__/credentials.test.ts b/apps/server/src/services/widget/__tests__/credentials.test.tsnew file mode 100644index 00000000000..b987a353c5e--- /dev/null+++ b/apps/server/src/services/widget/__tests__/credentials.test.ts@@ -0,0 +1,276 @@+import { describe, expect, it, vi } from 'vitest';++import type { DecryptedConnector } from '@/database/models/connector';+import { ensureFreshConnectorToken } from '@/server/services/connector/tokens';++import {+ ForbiddenWidgetCredentialsError,+ MissingWidgetEnvError,+ resolveWidgetEnv,+ selectConnectorSecret,+ type WidgetCredentialScope,+} from '../credentials';++vi.mock('@/server/services/connector/tokens', () => ({+ ensureFreshConnectorToken: vi.fn(async (connector) => connector),+}));++const connector = (overrides: Partial<DecryptedConnector>): DecryptedConnector =>+ ({+ agentId: null,+ credentials: { token: 'tok', type: 'bearer' },+ identifier: 'github',+ isEnabled: true,+ status: 'connected',+ userId: 'u1',+ workspaceId: null,+ ...overrides,+ }) as DecryptedConnector;++const modelReturning = (rows: DecryptedConnector[]) => ({+ resolveByIdentifiers: vi.fn().mockResolvedValue(rows),+ update: vi.fn(),+});++const personal: WidgetCredentialScope = {+ agentId: null,+ authorUserId: 'u1',+ projectId: null,+ userId: 'u1',+ workspaceId: null,+};+const workspace: WidgetCredentialScope = { ...personal, workspaceId: 'ws1' };++describe('selectConnectorSecret', () => {+ it.each([+ [{ accessToken: 'a', type: 'oauth2' }, 'a'],+ [{ token: 'b', type: 'bearer' }, 'b'],+ [{ apiKey: 'c', type: 'apikey' }, 'c'],+ [{ headers: { Authorization: 'Bearer d' }, type: 'header' }, 'd'],+ ] as const)('extracts the secret from %o', (credentials, expected) => {+ expect(selectConnectorSecret(credentials as any)).toEqual({ secret: expected });+ });++ it('returns no secret without credentials', () => {+ expect(selectConnectorSecret(null)).toEqual({ secret: undefined });+ });++ const multiHeader = {+ headers: { 'X-Api-Key': 'key-1', 'X-Tenant': 'tenant-1' },+ type: 'header',+ } as const;++ it('picks the named header, case-insensitively', () => {+ expect(selectConnectorSecret(multiHeader, 'x-tenant')).toEqual({ secret: 'tenant-1' });+ expect(selectConnectorSecret(multiHeader, 'X-Api-Key')).toEqual({ secret: 'key-1' });+ });++ it('refuses to guess between several headers', () => {+ expect(selectConnectorSecret(multiHeader)).toEqual({+ error: 'ambiguous_field',+ fields: ['X-Api-Key', 'X-Tenant'],+ });+ });++ it('reports a named header the connector does not hold', () => {+ expect(selectConnectorSecret(multiHeader, 'X-Org')).toEqual({+ error: 'unknown_field',+ fields: ['X-Api-Key', 'X-Tenant'],+ });+ });+});++describe('resolveWidgetEnv', () => {+ it('returns an empty env when nothing is declared', async () => {+ const model = modelReturning([]);++ expect(+ await resolveWidgetEnv({} as any, personal, undefined, { connectorModel: model as any }),+ ).toEqual({});+ expect(model.resolveByIdentifiers).not.toHaveBeenCalled();+ });++ it('resolves through the agent-aware chain on the widget scope', async () => {+ const model = modelReturning([+ connector({ credentials: { token: 'agent-tok', type: 'bearer' } }),+ ]);++ const env = await resolveWidgetEnv(+ {} as any,+ { ...personal, agentId: 'agt_1' },+ [{ connector: 'github', name: 'GITHUB_TOKEN' }],+ { connectorModel: model as any },+ );++ expect(env).toEqual({ GITHUB_TOKEN: 'agent-tok' });+ expect(model.resolveByIdentifiers).toHaveBeenCalledWith(['github'], 'agt_1');+ });++ it('never lets a personal credential reach a workspace widget', async () => {+ const model = modelReturning([connector({ workspaceId: null })]);++ await expect(+ resolveWidgetEnv({} as any, workspace, [{ connector: 'github', name: 'GITHUB_TOKEN' }], {+ connectorModel: model as any,+ }),+ ).rejects.toBeInstanceOf(MissingWidgetEnvError);+ });++ it('skips disabled connectors and connectors without credentials', async () => {+ const model = modelReturning([+ connector({ isEnabled: false }),+ connector({ credentials: null, identifier: 'linear' }),+ ]);++ const error = await resolveWidgetEnv(+ {} as any,+ personal,+ [+ { connector: 'github', name: 'GITHUB_TOKEN' },+ { connector: 'linear', name: 'LINEAR_TOKEN' },+ ],+ { connectorModel: model as any },+ ).catch((e) => e);++ expect(error).toBeInstanceOf(MissingWidgetEnvError);+ expect(error.missing.map((m: { name: string }) => m.name)).toEqual([+ 'GITHUB_TOKEN',+ 'LINEAR_TOKEN',+ ]);+ });++ it('uses an API-key connector whose tool sync never ran (status disconnected)', async () => {+ const model = modelReturning([connector({ status: 'disconnected' })]);++ const env = await resolveWidgetEnv(+ {} as any,+ personal,+ [{ connector: 'github', name: 'GITHUB_TOKEN' }],+ { connectorModel: model as any },+ );++ expect(env).toEqual({ GITHUB_TOKEN: 'tok' });+ });++ it('lists every missing required variable in one explicit error', async () => {+ const error = await resolveWidgetEnv(+ {} as any,+ workspace,+ [+ { connector: 'github', name: 'GITHUB_TOKEN' },+ { name: 'ORG' },+ { connector: 'slack', name: 'SLACK_TOKEN', required: false },+ ],+ { connectorModel: modelReturning([]) as any },+ ).catch((e) => e);++ expect(error).toBeInstanceOf(MissingWidgetEnvError);+ expect(error.message).toBe(+ 'Missing required environment: GITHUB_TOKEN (connect "github" for this widget\'s agent or workspace); ORG (no connector declared to provide it)',+ );+ });++ it('leaves optional variables out when they cannot be resolved', async () => {+ const env = await resolveWidgetEnv(+ {} as any,+ workspace,+ [{ connector: 'slack', name: 'SLACK_TOKEN', required: false }],+ { connectorModel: modelReturning([]) as any },+ );++ expect(env).toEqual({});+ });++ it('maps each header of a multi-header connector to the variable that names it', async () => {+ const model = modelReturning([+ connector({+ credentials: { headers: { 'X-Api-Key': 'key-1', 'X-Tenant': 'tenant-1' }, type: 'header' },+ }),+ ]);++ const env = await resolveWidgetEnv(+ {} as any,+ personal,+ [+ { connector: 'github', field: 'X-Api-Key', name: 'API_KEY' },+ { connector: 'github', field: 'X-Tenant', name: 'TENANT' },+ ],+ { connectorModel: model as any },+ );++ expect(env).toEqual({ API_KEY: 'key-1', TENANT: 'tenant-1' });+ });++ it('fails with an explicit error when a multi-header connector is not narrowed', async () => {+ const model = modelReturning([+ connector({+ credentials: { headers: { 'X-Api-Key': 'key-1', 'X-Tenant': 'tenant-1' }, type: 'header' },+ }),+ ]);++ const error = await resolveWidgetEnv(+ {} as any,+ personal,+ [+ { connector: 'github', name: 'API_KEY', required: false },+ { connector: 'github', field: 'X-Org', name: 'ORG' },+ ],+ { connectorModel: model as any },+ ).catch((e) => e);++ expect(error).toBeInstanceOf(MissingWidgetEnvError);+ expect(error.message).toBe(+ 'Missing required environment: API_KEY (connector "github" holds several headers; set "field" to one of: X-Api-Key, X-Tenant); ORG (connector "github" has no header "X-Org"; it holds: X-Api-Key, X-Tenant)',+ );+ });++ describe('who may receive a connector secret', () => {+ const teammates = connector({ userId: 'u2', workspaceId: 'ws1' });+ const requirement = [{ connector: 'github', name: 'GITHUB_TOKEN' }];++ it('refuses a workspace connector another member created, before touching its token', async () => {+ const isWorkspaceOwner = vi.fn().mockResolvedValue(false);+ vi.mocked(ensureFreshConnectorToken).mockClear();++ const error = await resolveWidgetEnv({} as any, workspace, requirement, {+ connectorModel: modelReturning([teammates]) as any,+ isWorkspaceOwner,+ }).catch((e) => e);++ expect(error).toBeInstanceOf(ForbiddenWidgetCredentialsError);+ expect(error.connectors).toEqual(['github']);+ expect(isWorkspaceOwner).toHaveBeenCalledWith('u1', 'ws1');+ expect(ensureFreshConnectorToken).not.toHaveBeenCalled();+ });++ it('lets the workspace owner use any workspace connector', async () => {+ const env = await resolveWidgetEnv({} as any, workspace, requirement, {+ connectorModel: modelReturning([teammates]) as any,+ isWorkspaceOwner: vi.fn().mockResolvedValue(true),+ });++ expect(env).toEqual({ GITHUB_TOKEN: 'tok' });+ });++ it('lets the creator use their own workspace connector without an owner lookup', async () => {+ const isWorkspaceOwner = vi.fn();++ const env = await resolveWidgetEnv({} as any, workspace, requirement, {+ connectorModel: modelReturning([connector({ workspaceId: 'ws1' })]) as any,+ isWorkspaceOwner,+ });++ expect(env).toEqual({ GITHUB_TOKEN: 'tok' });+ expect(isWorkspaceOwner).not.toHaveBeenCalled();+ });++ it('injects nothing once the author no longer exists', async () => {+ await expect(+ resolveWidgetEnv({} as any, { ...workspace, authorUserId: null }, requirement, {+ connectorModel: modelReturning([connector({ workspaceId: 'ws1' })]) as any,+ isWorkspaceOwner: vi.fn().mockResolvedValue(true),+ }),+ ).rejects.toBeInstanceOf(ForbiddenWidgetCredentialsError);+ });+ });+});diff --git a/apps/server/src/services/widget/__tests__/outputContract.test.ts b/apps/server/src/services/widget/__tests__/outputContract.test.tsnew file mode 100644index 00000000000..ad4cbf6f54b--- /dev/null+++ b/apps/server/src/services/widget/__tests__/outputContract.test.ts@@ -0,0 +1,119 @@+import { describe, expect, it } from 'vitest';++import { parseWidgetOutput, WIDGET_OUTPUT_LIMITS } from '../outputContract';++const json = (value: unknown) => JSON.stringify(value);++describe('parseWidgetOutput', () => {+ it.each([+ ['stat', { type: 'stat', unit: 'PRs', value: 12 }],+ ['list', { items: [{ status: 'open', title: 'Fix login', url: 'https://x' }], type: 'list' }],+ [+ 'series',+ { series: [{ name: 'stars', points: [{ t: '2026-09-01', v: 10 }] }], type: 'series' },+ ],+ [+ 'table',+ {+ columns: [{ key: 'name' }, { key: 'count', type: 'number' }],+ rows: [{ count: 1, name: 'a' }],+ type: 'table',+ },+ ],+ ] as const)('accepts a valid %s output', (type, output) => {+ const result = parseWidgetOutput(json(output), type);++ expect(result).toEqual({ ok: true, output, partial: false, partialMessage: undefined });+ });++ it('treats meta.complete=false as a partial success', () => {+ const result = parseWidgetOutput(+ json({ meta: { complete: false, message: 'GitLab timed out' }, type: 'stat', value: 3 }),+ 'stat',+ );++ expect(result).toMatchObject({ ok: true, partial: true, partialMessage: 'GitLab timed out' });+ });++ it('tolerates log lines before the final JSON line', () => {+ const result = parseWidgetOutput(`fetching...\npage 2\n${json({ type: 'stat', value: 1 })}\n`);++ expect(result).toMatchObject({ ok: true, output: { type: 'stat', value: 1 } });+ });++ it('rejects a series output that repeats a series name', () => {+ const stdout = JSON.stringify({+ series: [+ { name: 'stars', points: [{ t: '2026-10-01', v: 1 }] },+ { name: 'stars', points: [{ t: '2026-10-02', v: 2 }] },+ ],+ type: 'series',+ });+ expect(parseWidgetOutput(stdout, 'series')).toMatchObject({+ code: 'INVALID_OUTPUT',+ ok: false,+ });+ });++ it('rejects empty stdout', () => {+ expect(parseWidgetOutput(' \n')).toMatchObject({ code: 'EMPTY_OUTPUT', ok: false });+ });++ it('rejects non-JSON stdout', () => {+ expect(parseWidgetOutput('hello world')).toMatchObject({ code: 'INVALID_JSON', ok: false });+ });++ it('rejects documents that break the contract', () => {+ const result = parseWidgetOutput(json({ type: 'stat' }));++ expect(result).toMatchObject({ code: 'INVALID_OUTPUT', ok: false });+ expect(!result.ok && result.message).toContain('value');+ });++ it('rejects unknown output types', () => {+ expect(parseWidgetOutput(json({ type: 'pie', value: 1 }))).toMatchObject({+ code: 'INVALID_OUTPUT',+ ok: false,+ });+ });++ it('rejects an output whose type differs from the declared one', () => {+ expect(parseWidgetOutput(json({ items: [], type: 'list' }), 'stat')).toMatchObject({+ code: 'OUTPUT_TYPE_MISMATCH',+ ok: false,+ });+ });++ it('rejects output over the byte limit', () => {+ const big = json({+ description: 'x'.repeat(WIDGET_OUTPUT_LIMITS.bytes),+ type: 'stat',+ value: 1,+ });++ expect(parseWidgetOutput(big)).toMatchObject({ code: 'OUTPUT_TOO_LARGE', ok: false });+ });++ it('rejects too many list items', () => {+ const items = Array.from({ length: WIDGET_OUTPUT_LIMITS.listItems + 1 }, (_, i) => ({+ title: `item ${i}`,+ }));++ expect(parseWidgetOutput(json({ items, type: 'list' }))).toMatchObject({+ code: 'OUTPUT_TOO_LARGE',+ ok: false,+ });+ });++ it('rejects duplicate table column keys', () => {+ expect(+ parseWidgetOutput(json({ columns: [{ key: 'a' }, { key: 'a' }], rows: [], type: 'table' })),+ ).toMatchObject({ code: 'INVALID_OUTPUT', ok: false });+ });++ it('rejects non-finite series values', () => {+ expect(+ parseWidgetOutput('{"type":"series","series":[{"name":"a","points":[{"t":"x","v":"NaN"}]}]}'),+ ).toMatchObject({ code: 'INVALID_OUTPUT', ok: false });+ });+});diff --git a/apps/server/src/services/widget/__tests__/redact.test.ts b/apps/server/src/services/widget/__tests__/redact.test.tsnew file mode 100644index 00000000000..919352e33d7--- /dev/null+++ b/apps/server/src/services/widget/__tests__/redact.test.ts@@ -0,0 +1,57 @@+import { describe, expect, it } from 'vitest';++import { redactSecrets, sanitizeStream, truncateStream } from '../redact';++describe('redactSecrets', () => {+ it('replaces every injected secret value with its variable name', () => {+ const text = 'token=abc123secret and again abc123secret';++ expect(redactSecrets(text, { API_TOKEN: 'abc123secret' })).toBe(+ 'token=[REDACTED:API_TOKEN] and again [REDACTED:API_TOKEN]',+ );+ });++ it('matches the longest secret first', () => {+ expect(redactSecrets('value: abcdef-long', { A: 'abcdef', B: 'abcdef-long' })).toBe(+ 'value: [REDACTED:B]',+ );+ });++ it('ignores very short values that would shred normal text', () => {+ expect(redactSecrets('status: ok', { FLAG: 'ok' })).toBe('status: ok');+ });++ it('redacts well-known token shapes it was not told about', () => {+ const text = [+ 'ghp_abcdefghijklmnopqrstuvwxyz0123',+ 'sk-proj-abcdefghijklmnopqrstuvwx',+ 'Authorization: Bearer eyJhbGciOiJIUzI1NiJ9.payload.signature',+ ].join('\n');++ expect(redactSecrets(text)).toBe(+ ['[REDACTED]', '[REDACTED]', 'Authorization: Bearer [REDACTED]'].join('\n'),+ );+ });+});++describe('truncateStream', () => {+ it('keeps short streams untouched', () => {+ expect(truncateStream('hello', 10)).toBe('hello');+ });++ it('cuts long streams to the limit with a marker', () => {+ const result = truncateStream('x'.repeat(100), 40);++ expect(result.length).toBe(40);+ expect(result.endsWith('…[truncated]')).toBe(true);+ });+});++describe('sanitizeStream', () => {+ it('redacts before truncating so a secret at the cut is never half-kept', () => {+ const secret = 'supersecretvalue';+ const text = `${'a'.repeat(20)}${secret}`;++ expect(sanitizeStream(text, { S: secret })).not.toContain('supersecret');+ });+});diff --git a/apps/server/src/services/widget/credentials.ts b/apps/server/src/services/widget/credentials.tsnew file mode 100644index 00000000000..e6e97b96df9--- /dev/null+++ b/apps/server/src/services/widget/credentials.ts@@ -0,0 +1,265 @@+import type { WidgetEnvRequirement } from '@lobechat/types';++import { ConnectorModel, type DecryptedConnector } from '@/database/models/connector';+import type { ConnectorCredentials } from '@/database/schemas';+import type { LobeChatDatabase } from '@/database/type';+import { KeyVaultsGateKeeper } from '@/server/modules/KeyVaultsEncrypt';+import { ensureFreshConnectorToken } from '@/server/services/connector/tokens';+import { isWorkspacePrimaryOwner } from '@/server/services/workspacePermission';++/** Ownership columns of the widget whose script needs credentials. */+export interface WidgetCredentialScope {+ agentId: string | null;+ /**+ * Who wrote the script that will receive the secrets: the publisher of the+ * version being run, or the author of a draft being dry-run. `null` when+ * that user no longer exists — then no connector may be injected.+ */+ authorUserId: string | null;+ projectId: string | null;+ userId: string;+ workspaceId: string | null;+}++export interface MissingWidgetEnv {+ connector?: string;+ /** The header the requirement asked for. */+ field?: string;+ /** The connector's headers, for a requirement that did not pick exactly one. */+ fields?: string[];+ name: string;+ reason: 'ambiguous_field' | 'connector_not_connected' | 'no_source' | 'unknown_field';+}++export class MissingWidgetEnvError extends Error {+ constructor(public readonly missing: MissingWidgetEnv[]) {+ super(formatMissing(missing));+ this.name = 'MissingWidgetEnvError';+ }+}++/**+ * The script's author may not read a connector they resolved: raised instead+ * of running, so the secret never reaches a script its owner did not vouch for.+ */+export class ForbiddenWidgetCredentialsError extends Error {+ constructor(public readonly connectors: string[]) {+ super(+ connectors+ .map(+ (c) =>+ `Connector "${c}" was connected by another workspace member; only its creator or the workspace owner can author a widget that reads it`,+ )+ .join('; '),+ );+ this.name = 'ForbiddenWidgetCredentialsError';+ }+}++const describeMissing = (m: MissingWidgetEnv) => {+ switch (m.reason) {+ case 'no_source': {+ return `${m.name} (no connector declared to provide it)`;+ }+ case 'connector_not_connected': {+ return `${m.name} (connect "${m.connector}" for this widget's agent or workspace)`;+ }+ case 'ambiguous_field': {+ return `${m.name} (connector "${m.connector}" holds several headers; set "field" to one of: ${m.fields?.join(', ')})`;+ }+ case 'unknown_field': {+ return `${m.name} (connector "${m.connector}" has no header "${m.field}"; it holds: ${m.fields?.join(', ')})`;+ }+ }+};++const formatMissing = (missing: MissingWidgetEnv[]) =>+ `Missing required environment: ${missing.map(describeMissing).join('; ')}`;++export type ConnectorSecretSelection =+ { secret: string | undefined } | { error: 'ambiguous_field' | 'unknown_field'; fields: string[] };++/**+ * The secret string a connector contributes to one env variable. Token and+ * key credentials hold a single secret; a header credential may hold several+ * values (e.g. `X-Api-Key` plus `X-Tenant`), so `field` names the header to+ * read. Without it, only a single-header connector resolves — guessing would+ * hand the script whichever value happens to come first.+ */+export const selectConnectorSecret = (+ credentials: ConnectorCredentials | null,+ field?: string,+): ConnectorSecretSelection => {+ if (!credentials) return { secret: undefined };+ switch (credentials.type) {+ case 'oauth2': {+ return { secret: credentials.accessToken || undefined };+ }+ case 'bearer': {+ return { secret: credentials.token || undefined };+ }+ case 'apikey': {+ return { secret: credentials.apiKey || undefined };+ }+ case 'header': {+ const entries = Object.entries(credentials.headers ?? {});+ const fields = entries.map(([name]) => name);+ let value: string | undefined;+ if (field) {+ const wanted = field.toLowerCase();+ const match = entries.find(([name]) => name.toLowerCase() === wanted);+ if (!match) return { error: 'unknown_field', fields };+ value = match[1];+ } else {+ if (entries.length > 1) return { error: 'ambiguous_field', fields };+ value = entries[0]?.[1];+ }+ return { secret: value?.replace(/^Bearer\s+/i, '') || undefined };+ }+ }+};++export interface ResolveWidgetEnvOptions {+ /** Injected for tests; defaults to a model on the widget's scope. */+ connectorModel?: Pick<ConnectorModel, 'resolveByIdentifiers' | 'update'>;+ /** Injected for tests; defaults to the workspace's primary-owner check. */+ isWorkspaceOwner?: (userId: string, workspaceId: string) => Promise<boolean>;+}++/**+ * Whether the script's author may receive a connector's raw secret.+ *+ * A widget script is arbitrary code that can exfiltrate whatever it is given,+ * so injecting a secret is equivalent to handing it to the script's author.+ * Workspace connectors are visible to every member, but only their creator or+ * the workspace owner may manage them (`assertWorkspaceRowManageable`); the+ * same authority is required to read one from a script:+ *+ * - the author created the connector, or+ * - the connector is workspace-level (incl. agent-scoped rows in the+ * workspace, and the workspace connectors a project widget resolves) and+ * the author is the workspace owner.+ *+ * Personal connectors are only ever resolved for personal widgets, whose+ * author is their owner, so the creator rule covers them. A missing author+ * (deleted user) may read nothing.+ */+const mayInject = async (+ connector: DecryptedConnector,+ scope: WidgetCredentialScope,+ isOwner: () => Promise<boolean>,+): Promise<boolean> => {+ if (!scope.authorUserId) return false;+ if (connector.userId === scope.authorUserId) return true;+ return !!connector.workspaceId && isOwner();+};++/**+ * Resolve the environment a widget script declares in `manifest.env`.+ *+ * Credentials come from `user_connectors` through the same agent-aware chain+ * agent runs use (`ConnectorModel.resolveByIdentifiers`): an agent-owned+ * connector wins over the base connector of the widget's own scope, and the+ * base scope is exactly the widget's — a workspace widget resolves within the+ * workspace, a personal widget within its owner's personal connectors. A+ * project widget has no connector level of its own and uses its workspace's.+ *+ * The widget's scope, not the caller's, decides: a member refreshing a+ * teammate's widget gets the widget's credentials, and a non-personal widget+ * never falls back to its creator's personal connectors. Whether a resolved+ * connector may be injected is decided by the script's author (see+ * {@link mayInject}), not by who triggers the run.+ *+ * Throws `ForbiddenWidgetCredentialsError` when a declared connector resolves+ * to one the author may not read, and `MissingWidgetEnvError` listing every+ * required variable it could not fill; optional ones are left out.+ */+export const resolveWidgetEnv = async (+ db: LobeChatDatabase,+ scope: WidgetCredentialScope,+ requirements: WidgetEnvRequirement[] | undefined,+ options: ResolveWidgetEnvOptions = {},+): Promise<Record<string, string>> => {+ const env: Record<string, string> = {};+ if (!requirements?.length) return env;++ const connectorModel =+ options.connectorModel ??+ new ConnectorModel(+ db,+ scope.userId,+ scope.workspaceId ?? undefined,+ await KeyVaultsGateKeeper.initWithEnvKey(),+ );++ const identifiers = [+ ...new Set(requirements.map((r) => r.connector).filter((c): c is string => !!c)),+ ];+ const resolved = identifiers.length+ ? await connectorModel.resolveByIdentifiers(identifiers, scope.agentId ?? undefined)+ : [];++ const byIdentifier = new Map<string, DecryptedConnector>();+ for (const connector of resolved) {+ // Defense in depth: the model's predicate is scope-exact, but a credential+ // from another scope must never reach a script, whatever the query does.+ if ((connector.workspaceId ?? null) !== (scope.workspaceId ?? null)) continue;+ // `status` tracks MCP tool sync, not credential validity: an API-key+ // connector that never synced tools stays `disconnected` yet holds a+ // usable secret. A revoked connector has its credentials wiped instead.+ if (!connector.isEnabled) continue;+ byIdentifier.set(connector.identifier, connector);+ }++ // Check before refreshing any token: a refused connector is never touched.+ let ownerCheck: Promise<boolean> | undefined;+ const isOwner = () => {+ if (!scope.workspaceId || !scope.authorUserId) return Promise.resolve(false);+ ownerCheck ??= options.isWorkspaceOwner+ ? options.isWorkspaceOwner(scope.authorUserId, scope.workspaceId)+ : isWorkspacePrimaryOwner({ db, userId: scope.authorUserId, workspaceId: scope.workspaceId });+ return ownerCheck;+ };+ const forbidden: string[] = [];+ for (const connector of byIdentifier.values()) {+ if (!(await mayInject(connector, scope, isOwner))) forbidden.push(connector.identifier);+ }+ if (forbidden.length > 0) throw new ForbiddenWidgetCredentialsError(forbidden);++ const missing: MissingWidgetEnv[] = [];+ for (const requirement of requirements) {+ const required = requirement.required !== false;+ if (!requirement.connector) {+ if (required) missing.push({ name: requirement.name, reason: 'no_source' });+ continue;+ }++ let connector = byIdentifier.get(requirement.connector);+ if (connector) {+ connector = await ensureFreshConnectorToken(connector, connectorModel as ConnectorModel);+ }+ const selection = selectConnectorSecret(connector?.credentials ?? null, requirement.field);+ if ('error' in selection) {+ // A manifest that does not pick one header is wrong whether or not the+ // variable is optional: report it rather than silently dropping it.+ missing.push({+ connector: requirement.connector,+ field: requirement.field,+ fields: selection.fields,+ name: requirement.name,+ reason: selection.error,+ });+ } else if (selection.secret) {+ env[requirement.name] = selection.secret;+ } else if (required) {+ missing.push({+ connector: requirement.connector,+ name: requirement.name,+ reason: 'connector_not_connected',+ });+ }+ }++ if (missing.length > 0) throw new MissingWidgetEnvError(missing);+ return env;+};diff --git a/apps/server/src/services/widget/executeRun.ts b/apps/server/src/services/widget/executeRun.tsnew file mode 100644index 00000000000..2f220c76304--- /dev/null+++ b/apps/server/src/services/widget/executeRun.ts@@ -0,0 +1,223 @@+import type { WidgetOutput, WidgetRunError, WidgetRunFinalStatus } from '@lobechat/types';+import debug from 'debug';++import { WidgetModel } from '@/database/models/widget';+import type { WidgetRow, WidgetRunRow, WidgetVersionRow } from '@/database/schemas';+import type { LobeChatDatabase } from '@/database/type';++import {+ ForbiddenWidgetCredentialsError,+ MissingWidgetEnvError,+ resolveWidgetEnv,+ type WidgetCredentialScope,+} from './credentials';+import { recordWidgetMetrics } from './metrics';+import { parseWidgetOutput } from './outputContract';+import { redactSecrets, sanitizeStream } from './redact';+import { WidgetSandboxError, type WidgetSandboxRunner } from './sandbox/types';++const log = debug('lobe-server:widget:execute-run');++/** How much of stderr a NON_ZERO_EXIT error message quotes. */+const ERROR_STDERR_TAIL = 500;++export type ResolveWidgetEnv = (+ db: LobeChatDatabase,+ scope: WidgetCredentialScope,+ requirements: NonNullable<WidgetVersionRow['manifest']>['env'],+) => Promise<Record<string, string>>;++export interface ExecuteWidgetRunDeps {+ resolveEnv?: ResolveWidgetEnv;+ runner: WidgetSandboxRunner;+}++export interface ExecuteWidgetRunParams {+ run: Pick<WidgetRunRow, 'id' | 'trigger'>;+ version: Pick<+ WidgetVersionRow,+ 'manifest' | 'outputType' | 'publishedByUserId' | 'runtime' | 'script' | 'userId'+ >;+ widget: Pick<+ WidgetRow,+ 'agentId' | 'id' | 'metricId' | 'projectId' | 'title' | 'userId' | 'workspaceId'+ >;+}++interface RunOutcome {+ durationMs?: number;+ env: Record<string, string>;+ error?: WidgetRunError | null;+ exitCode?: number | null;+ output?: WidgetOutput | null;+ status: WidgetRunFinalStatus;+ stderr?: string | null;+ stdout?: string | null;+}++/**+ * Resolve env, execute on the sandbox and judge the result. Never throws for+ * script or sandbox failures — they become the outcome's status.+ */+const runInSandbox = async (+ db: LobeChatDatabase,+ { version, widget }: Pick<ExecuteWidgetRunParams, 'version' | 'widget'>,+ deps: ExecuteWidgetRunDeps,+): Promise<RunOutcome> => {+ const manifest = version.manifest ?? undefined;+ const resolveEnv = deps.resolveEnv ?? resolveWidgetEnv;++ let env: Record<string, string>;+ try {+ // Secrets go to whoever wrote the script: the publisher of a live+ // version, the author of a draft.+ const authorUserId = version.publishedByUserId ?? version.userId;+ env = await resolveEnv(+ db,+ {+ agentId: widget.agentId,+ authorUserId,+ projectId: widget.projectId,+ userId: widget.userId,+ workspaceId: widget.workspaceId,+ },+ manifest?.env,+ );+ } catch (error) {+ if (error instanceof MissingWidgetEnvError) {+ return { env: {}, error: { code: 'MISSING_ENV', message: error.message }, status: 'failed' };+ }+ if (error instanceof ForbiddenWidgetCredentialsError) {+ return {+ env: {},+ error: { code: 'CREDENTIALS_FORBIDDEN', message: error.message },+ status: 'failed',+ };+ }+ // Anything else (key vault misconfigured, DB hiccup) must still close the+ // run — an exception here would strand it in `running` forever.+ console.error('[widget:executeRun] credential resolution failed widget=%s', widget.id, error);+ return {+ env: {},+ error: { code: 'CREDENTIALS_ERROR', message: 'Failed to resolve widget credentials' },+ status: 'failed',+ };+ }++ try {+ const result = await deps.runner.run({+ env,+ network: { allow: manifest?.network?.allow ?? [] },+ runtime: version.runtime,+ script: version.script,+ subject: { id: widget.id, kind: 'widget' },+ timeoutMs: manifest?.timeoutMs,+ });++ const stdout = redactSecrets(result.stdout, env);+ const stderr = redactSecrets(result.stderr, env);+ const base = { durationMs: result.durationMs, env, exitCode: result.exitCode, stderr, stdout };++ if (result.timedOut) {+ return {+ ...base,+ error: { code: 'TIMEOUT', message: 'Script exceeded its time limit' },+ status: 'timeout',+ };+ }+ if (result.exitCode !== 0) {+ const tail = stderr.trim().slice(-ERROR_STDERR_TAIL);+ return {+ ...base,+ error: {+ code: 'NON_ZERO_EXIT',+ message: `Script exited with code ${result.exitCode}${tail ? `: ${tail}` : ''}`,+ },+ status: 'failed',+ };+ }++ const parsed = parseWidgetOutput(stdout, version.outputType);+ if (!parsed.ok) {+ return { ...base, error: { code: parsed.code, message: parsed.message }, status: 'failed' };+ }+ // `meta.complete === false`: shown on the card, kept out of the trend.+ return {+ ...base,+ error: null,+ output: parsed.output,+ status: parsed.partial ? 'partial' : 'succeeded',+ };+ } catch (error) {+ const code = error instanceof WidgetSandboxError ? error.code : 'SANDBOX_ERROR';+ const message = error instanceof Error ? error.message : String(error);+ return { env, error: { code, message: redactSecrets(message, env) }, status: 'failed' };+ }+};++/**+ * Execute one opened run end to end and close it:+ *+ * 1. resolve the declared env from the widget's connector scope — a missing+ * required variable fails the run with `MISSING_ENV`, a connector the+ * script's author may not read with `CREDENTIALS_FORBIDDEN`, both before+ * any sandbox call;+ * 2. execute the version's script on the sandbox with the manifest's network+ * allowlist;+ * 3. redact injected secrets (and well-known token shapes) from stdout / stderr+ * before anything is parsed or persisted, then truncate the streams;+ * 4. judge the result — timeout → `timeout`; non-zero exit → `NON_ZERO_EXIT`;+ * stdout not matching the contract → the contract's error code; a valid+ * output with `meta.complete === false` → `partial`;+ * 5. finish the run. `WidgetModel.finishRun` folds a current, non-preview run+ * into the widget snapshot (`succeeded` / `partial` replace `latestOutput`);+ * 6. a `succeeded` run that folded into the snapshot appends its numbers to+ * the widget's metric trend; previews, stale runs and `partial` runs never+ * do.+ *+ * Never throws for script or sandbox failures — they become the run's status.+ */+export const executeWidgetRun = async (+ db: LobeChatDatabase,+ params: ExecuteWidgetRunParams,+ deps: ExecuteWidgetRunDeps,+): Promise<WidgetRunRow | undefined> => {+ const { run, version, widget } = params;+ const outcome = await runInSandbox(db, params, deps);++ const finishedAt = new Date();+ const finished = await WidgetModel.finishRun(db, run.id, {+ durationMs: outcome.durationMs ?? null,+ error: outcome.error ?? null,+ exitCode: outcome.exitCode ?? null,+ finishedAt,+ output: outcome.output ?? null,+ status: outcome.status,+ stderr: outcome.stderr ? sanitizeStream(outcome.stderr, outcome.env) : null,+ stdout: outcome.stdout ? sanitizeStream(outcome.stdout, outcome.env) : null,+ });++ // Same "current run" rule as the snapshot: a stale run (old version, or+ // started before the snapshot's run) finishing late must not become the+ // newest trend point nor move `widgets.metric_id`.+ if (finished?.folded && outcome.status === 'succeeded' && outcome.output) {+ try {+ const { primaryMetricId } = await recordWidgetMetrics(db, widget, {+ manifest: version.manifest,+ observedAt: finishedAt,+ output: outcome.output,+ runId: run.id,+ });+ if (primaryMetricId && primaryMetricId !== widget.metricId) {+ // A newer run may have taken the snapshot while this one recorded metrics.+ await WidgetModel.linkMetric(db, widget.id, primaryMetricId, run.id);+ }+ } catch (error) {+ // The run itself succeeded; a trend write failure must not flip it.+ console.error('[widget:executeRun] failed to record metrics widget=%s', widget.id, error);+ }+ }++ log('run=%s widget=%s status=%s', run.id, widget.id, outcome.status);+ return finished?.run;+};diff --git a/apps/server/src/services/widget/index.ts b/apps/server/src/services/widget/index.tsnew file mode 100644index 00000000000..4e2f52fb80d--- /dev/null+++ b/apps/server/src/services/widget/index.ts@@ -0,0 +1,247 @@+import { validateCronPattern } from '@lobechat/utils/cronEval';++import { type CreateWidgetVersionInput, WidgetModel } from '@/database/models/widget';+import type { LobeChatDatabase } from '@/database/type';++import { executeWidgetRun, type ResolveWidgetEnv } from './executeRun';+import { createWidgetSandboxRunner } from './sandbox';+import type { WidgetSandboxRunner } from './sandbox/types';+import { nextScheduleOccurrence } from './schedule';++export type WidgetFlowErrorCode =+ | 'DRY_RUN_REQUIRED'+ | 'FORBIDDEN'+ | 'INVALID_SCHEDULE'+ | 'NO_VERSION'+ | 'NOT_FOUND'+ | 'NOT_ROLLBACK_TARGET';++/** A request the version flow refuses; mapped to a client error by the router. */+export class WidgetFlowError extends Error {+ constructor(+ public readonly code: WidgetFlowErrorCode,+ message: string,+ ) {+ super(message);+ this.name = 'WidgetFlowError';+ }+}++export interface WidgetServiceDeps {+ resolveEnv?: ResolveWidgetEnv;+ runner?: WidgetSandboxRunner;+}++/**+ * The widget version flow and run entry points, on behalf of one caller:+ *+ * draft ──dry-run──▶ (usable run for this contentHash) ──publish──▶ published+ * rollback ◀── archived+ *+ * - `saveDraft` records content as a draft version; identical content+ * (same `contentHash`) returns the current draft instead of a new row.+ * - `dryRun` executes a draft (default: the current draft) as a `preview` run+ * that never touches the widget snapshot or its metrics.+ * - `publish` makes a draft live only when a run of the *same content hash*+ * produced a usable output (`succeeded` or `partial`), so what goes live is+ * exactly what was tried.+ * - `rollback` re-publishes a previously published (archived) version; it was+ * live before, so no new dry run is required.+ * - `runNow` refreshes the published version (`manual`), open to any reader.+ *+ * Authoring (draft / dry run / publish / rollback / schedule) is limited to the+ * widget's creator, mirroring the model's write rule.+ */+export class WidgetService {+ private readonly model: WidgetModel;+ private readonly runner: WidgetSandboxRunner;+ private readonly resolveEnv?: ResolveWidgetEnv;++ constructor(+ private readonly db: LobeChatDatabase,+ private readonly userId: string,+ workspaceId?: string,+ deps: WidgetServiceDeps = {},+ ) {+ this.model = new WidgetModel(db, userId, workspaceId);+ this.runner = deps.runner ?? createWidgetSandboxRunner();+ this.resolveEnv = deps.resolveEnv;+ }++ private async requireWidget(widgetId: string) {+ const widget = await this.model.findById(widgetId);+ if (!widget) throw new WidgetFlowError('NOT_FOUND', 'Widget not found');+ return widget;+ }++ private async requireManageable(widgetId: string) {+ const widget = await this.requireWidget(widgetId);+ if (widget.userId !== this.userId) {+ throw new WidgetFlowError('FORBIDDEN', 'Only the widget creator can change it');+ }+ return widget;+ }++ private async requireVersion(widgetId: string, versionId: string) {+ const version = await this.model.findVersion(widgetId, versionId);+ if (!version) throw new WidgetFlowError('NOT_FOUND', 'Version not found');+ return version;+ }++ async saveDraft(widgetId: string, input: CreateWidgetVersionInput) {+ await this.requireManageable(widgetId);+ const version = await this.model.createVersion(widgetId, input);+ if (!version) throw new WidgetFlowError('NOT_FOUND', 'Widget not found');+ return version;+ }++ /** Execute a draft as a preview; defaults to the current draft, else the published version. */+ async dryRun(widgetId: string, options: { operationId?: string; versionId?: string } = {}) {+ const widget = await this.requireManageable(widgetId);+ const versionId = options.versionId ?? widget.draftVersionId ?? widget.publishedVersionId;+ if (!versionId) throw new WidgetFlowError('NO_VERSION', 'Widget has no version yet');+ const version = await this.requireVersion(widgetId, versionId);++ const run = await this.model.startRun(widgetId, {+ operationId: options.operationId,+ trigger: 'preview',+ versionId,+ });+ if (!run) throw new WidgetFlowError('NOT_FOUND', 'Widget not found');++ return this.execute(widget, version, run);+ }++ /** Refresh the published version now. Any reader of the widget may do this. */+ async runNow(widgetId: string) {+ const widget = await this.requireWidget(widgetId);+ if (!widget.publishedVersionId) {+ throw new WidgetFlowError('NO_VERSION', 'Widget has no published version');+ }+ const version = await this.requireVersion(widgetId, widget.publishedVersionId);++ // Pin the run to the version read above: a publish landing in between must+ // not relabel a run that executes this version's script.+ const run = await this.model.startRun(widgetId, { trigger: 'manual', versionId: version.id });+ if (!run) throw new WidgetFlowError('NOT_FOUND', 'Widget not found');++ return this.execute(widget, version, run);+ }++ async publish(widgetId: string, versionId: string) {+ const widget = await this.requireManageable(widgetId);+ const version = await this.requireVersion(widgetId, versionId);+ if (version.status === 'published') return { version, widget };++ if (version.status === 'draft') {+ const tried = await this.model.hasSucceededRunForContentHash(widgetId, version.contentHash);+ if (!tried) {+ throw new WidgetFlowError(+ 'DRY_RUN_REQUIRED',+ `Version ${version.version} has no usable run of its content yet; dry-run it before publishing`,+ );+ }+ }++ return this.makeLive(widget, version);+ }++ /**+ * Re-publish an archived version — by default the one most recently+ * replaced. Only versions that were live before qualify.+ */+ async rollback(widgetId: string, versionId?: string) {+ const widget = await this.requireManageable(widgetId);++ let target;+ if (versionId) {+ target = await this.requireVersion(widgetId, versionId);+ } else {+ const versions = await this.model.listVersions(widgetId);+ target = versions+ .filter((v) => v.status === 'archived' && v.publishedAt)+ .sort((a, b) => b.publishedAt!.getTime() - a.publishedAt!.getTime())[0];+ if (!target) {+ throw new WidgetFlowError(+ 'NOT_ROLLBACK_TARGET',+ 'No previously published version to roll back to',+ );+ }+ }+ if (target.status !== 'archived') {+ throw new WidgetFlowError(+ 'NOT_ROLLBACK_TARGET',+ `Version ${target.version} is ${target.status}; only a previously published version can be rolled back to`,+ );+ }++ return this.makeLive(widget, target);+ }++ /**+ * Set or clear the refresh schedule. The next due instant is computed from+ * the pattern; scheduled runs only fire once a version is published.+ */+ async setSchedule(widgetId: string, pattern: string | null, timezone?: string | null) {+ await this.requireManageable(widgetId);++ let nextRunAt: Date | null = null;+ if (pattern) {+ const validation = validateCronPattern(pattern, timezone ?? null, { count: 1 });+ if (!validation.valid) {+ throw new WidgetFlowError('INVALID_SCHEDULE', `Invalid schedule: ${validation.error}`);+ }+ nextRunAt = validation.nextRuns[0];+ }++ // Atomic with cancelling the old schedule's reservations, so none can resume under the new one.+ return this.model.setSchedule(widgetId, {+ nextRunAt,+ schedulePattern: pattern ? pattern.trim() : null,+ scheduleTimezone: pattern ? (timezone ?? null) : null,+ });+ }++ private async makeLive(+ widget: Awaited<ReturnType<WidgetService['requireWidget']>>,+ version: Awaited<ReturnType<WidgetService['requireVersion']>>,+ ) {+ // A widget without its own schedule adopts the one the script suggests.+ const suggested = version.manifest?.schedule;+ const adopt =+ !widget.schedulePattern &&+ suggested?.pattern &&+ validateCronPattern(suggested.pattern, suggested.timezone ?? null).valid;+ const pattern = adopt ? suggested!.pattern : widget.schedulePattern;+ const timezone = adopt ? (suggested!.timezone ?? null) : widget.scheduleTimezone;++ if (adopt) {+ await this.model.update(widget.id, {+ schedulePattern: pattern,+ scheduleTimezone: timezone,+ });+ }++ const result = await this.model.publishVersion(widget.id, version.id, {+ nextRunAt: pattern ? nextScheduleOccurrence(pattern, timezone) : null,+ });+ if (!result) throw new WidgetFlowError('NOT_FOUND', 'Version not found');+ return result;+ }++ private execute(+ widget: Awaited<ReturnType<WidgetService['requireWidget']>>,+ version: Awaited<ReturnType<WidgetService['requireVersion']>>,+ run: { id: string; trigger: 'manual' | 'preview' | 'schedule' },+ ) {+ return executeWidgetRun(+ this.db,+ { run, version, widget },+ { resolveEnv: this.resolveEnv, runner: this.runner },+ );+ }+}++export { executeWidgetRun } from './executeRun';+export { createWidgetSandboxRunner } from './sandbox';+export { nextScheduleOccurrence } from './schedule';diff --git a/apps/server/src/services/widget/metrics.ts b/apps/server/src/services/widget/metrics.tsnew file mode 100644index 00000000000..bc36e985c7b--- /dev/null+++ b/apps/server/src/services/widget/metrics.ts@@ -0,0 +1,136 @@+import type { WidgetManifest, WidgetOutput } from '@lobechat/types';++import { MetricModel } from '@/database/models/metric';+import type { LobeChatDatabase } from '@/database/type';++export interface WidgetMetricScope {+ id: string;+ metricId: string | null;+ title: string;+ userId: string;+ workspaceId: string | null;+}++export interface RecordWidgetMetricsParams {+ manifest?: WidgetManifest | null;+ observedAt: Date;+ output: WidgetOutput;+ runId: string;+}++export interface RecordWidgetMetricsResult {+ pointsWritten: number;+ /** Series the widget row should point at (`widgets.metric_id`). */+ primaryMetricId?: string;+}++const DEFAULT_STAT_KEY = 'value';+const SERIES_KEY_PREFIX = 'series:';++const toNumber = (value: unknown): number | undefined => {+ if (typeof value === 'number') return Number.isFinite(value) ? value : undefined;+ if (typeof value === 'string' && value.trim() !== '') {+ const n = Number(value.replaceAll(',', ''));+ return Number.isFinite(n) ? n : undefined;+ }+ return undefined;+};++const pickPath = (source: unknown, path: string): unknown =>+ path+ .split('.')+ .reduce<unknown>(+ (value, key) =>+ value && typeof value === 'object' ? (value as Record<string, unknown>)[key] : undefined,+ source,+ );++const parseTime = (t: string): Date | undefined => {+ // Category labels ('Mon', 'v1.2') are not time points and never enter a trend.+ if (!/^\d{4}-\d{2}-\d{2}/.test(t)) return undefined;+ const date = new Date(t);+ return Number.isNaN(date.getTime()) ? undefined : date;+};++/**+ * Fold a successful, complete run into the widget's long-term trend in+ * `metrics` / `metric_points` (subject `widget`):+ *+ * - `stat` — one point per run, the numeric `value` (or `manifest.metric.valuePath`)+ * observed at the run's finish time. Non-numeric stats are skipped.+ * - `series` — one metric per series (`series:<name>`); only points with an+ * ISO timestamp newer than the series' latest stored point are appended+ * (serialized per series), so a script re-reporting a sliding window — even+ * from two overlapping runs — does not duplicate history.+ *+ * list / table outputs carry no numbers to trend and write nothing.+ */+export const recordWidgetMetrics = async (+ db: LobeChatDatabase,+ widget: WidgetMetricScope,+ params: RecordWidgetMetricsParams,+): Promise<RecordWidgetMetricsResult> => {+ const { manifest, output, observedAt, runId } = params;+ const metricModel = new MetricModel(db, widget.userId, widget.workspaceId ?? undefined);+ const kind = manifest?.metric?.kind ?? 'gauge';++ const pointBase = {+ actorId: runId,+ actorType: 'system' as const,+ sourceType: 'probe' as const,+ };++ if (output.type === 'stat') {+ const value = toNumber(+ manifest?.metric?.valuePath ? pickPath(output, manifest.metric.valuePath) : output.value,+ );+ if (value === undefined) return { pointsWritten: 0 };++ const metric = await metricModel.ensure({+ key: manifest?.metric?.key ?? DEFAULT_STAT_KEY,+ kind,+ subjectId: widget.id,+ subjectType: 'widget',+ title: output.label ?? widget.title,+ unit: manifest?.metric?.unit ?? output.unit,+ });+ if (!metric) return { pointsWritten: 0 };++ await metricModel.addPoint(metric.id, { ...pointBase, observedAt, value });+ return { pointsWritten: 1, primaryMetricId: metric.id };+ }++ if (output.type === 'series') {+ let pointsWritten = 0;+ let primaryMetricId: string | undefined;++ for (const series of output.series) {+ const points = series.points+ .map((p) => ({ observedAt: parseTime(p.t), value: p.v }))+ .filter((p): p is { observedAt: Date; value: number } => !!p.observedAt);+ if (points.length === 0) continue;++ const metric = await metricModel.ensure({+ key: `${SERIES_KEY_PREFIX}${series.name}`,+ kind,+ subjectId: widget.id,+ subjectType: 'widget',+ title: series.name,+ unit: manifest?.metric?.unit ?? output.unit,+ });+ if (!metric) continue;+ primaryMetricId ??= metric.id;++ // Overlapping runs report the same window; the append is serialized+ // per series so each timestamp is written once.+ pointsWritten += await metricModel.appendNewerPoints(+ metric.id,+ points.map((p) => ({ ...pointBase, ...p })),+ );+ }++ return { pointsWritten, primaryMetricId };+ }++ return { pointsWritten: 0 };+};diff --git a/apps/server/src/services/widget/outputContract.ts b/apps/server/src/services/widget/outputContract.tsnew file mode 100644index 00000000000..2fc7ce8e47c--- /dev/null+++ b/apps/server/src/services/widget/outputContract.ts@@ -0,0 +1,190 @@+import type { WidgetOutput, WidgetOutputType } from '@lobechat/types';+import { z } from 'zod';++/** Upper bounds a widget output must stay within; anything larger is rejected, not clipped. */+export const WIDGET_OUTPUT_LIMITS = {+ /** UTF-8 size of the JSON document on stdout. */+ bytes: 256 * 1024,+ listItems: 200,+ pointsPerSeries: 1000,+ series: 20,+ tableColumns: 30,+ tableRows: 500,+} as const;++const text = z.string().max(2000);+const shortText = z.string().max(200);+const scalar = z.union([z.number().finite(), text]);++const metaSchema = z+ .object({ complete: z.boolean().optional(), message: text.optional() })+ .optional();++const statSchema = z.object({+ delta: scalar.optional(),+ description: text.optional(),+ label: shortText.optional(),+ meta: metaSchema,+ trend: z.enum(['up', 'down', 'flat']).optional(),+ type: z.literal('stat'),+ unit: shortText.optional(),+ value: scalar,+});++const listSchema = z.object({+ items: z+ .array(+ z.object({+ description: text.optional(),+ status: shortText.optional(),+ time: shortText.optional(),+ title: text,+ url: text.optional(),+ value: scalar.optional(),+ }),+ )+ .max(WIDGET_OUTPUT_LIMITS.listItems),+ meta: metaSchema,+ type: z.literal('list'),+});++const seriesSchema = z+ .object({+ meta: metaSchema,+ series: z+ .array(+ z.object({+ name: shortText,+ points: z+ .array(z.object({ t: shortText, v: z.number().finite() }))+ .max(WIDGET_OUTPUT_LIMITS.pointsPerSeries),+ }),+ )+ .max(WIDGET_OUTPUT_LIMITS.series),+ type: z.literal('series'),+ unit: shortText.optional(),+ })+ .superRefine((value, ctx) => {+ // Each name keys its own metric series; a repeat would merge two lines into one trend.+ const names = new Set(value.series.map((s) => s.name));+ if (names.size !== value.series.length) {+ ctx.addIssue({ code: 'custom', message: 'series names must be unique', path: ['series'] });+ }+ });++const cell = z.union([z.string().max(2000), z.number().finite(), z.boolean(), z.null()]);++const tableSchema = z+ .object({+ columns: z+ .array(+ z.object({+ key: shortText,+ title: shortText.optional(),+ type: z.enum(['string', 'number', 'date', 'link']).optional(),+ }),+ )+ .min(1)+ .max(WIDGET_OUTPUT_LIMITS.tableColumns),+ meta: metaSchema,+ rows: z.array(z.record(z.string(), cell)).max(WIDGET_OUTPUT_LIMITS.tableRows),+ type: z.literal('table'),+ })+ .superRefine((value, ctx) => {+ const keys = new Set(value.columns.map((c) => c.key));+ if (keys.size !== value.columns.length) {+ ctx.addIssue({ code: 'custom', message: 'column keys must be unique', path: ['columns'] });+ }+ });++const outputSchema = z.discriminatedUnion('type', [+ statSchema,+ listSchema,+ seriesSchema,+ tableSchema,+]);++export type WidgetOutputErrorCode =+ 'EMPTY_OUTPUT' | 'INVALID_JSON' | 'INVALID_OUTPUT' | 'OUTPUT_TOO_LARGE' | 'OUTPUT_TYPE_MISMATCH';++export type ParseWidgetOutputResult =+ | { ok: true; output: WidgetOutput; partial: boolean; partialMessage?: string }+ | { code: WidgetOutputErrorCode; message: string; ok: false };++const fail = (code: WidgetOutputErrorCode, message: string): ParseWidgetOutputResult => ({+ code,+ message,+ ok: false,+});++/**+ * The document is normally the whole stdout. Scripts that log before printing+ * the result are tolerated as long as the last non-empty line is the JSON.+ */+const extractJson = (stdout: string): unknown => {+ const trimmed = stdout.trim();+ try {+ return JSON.parse(trimmed);+ } catch {+ const lines = trimmed.split('\n').filter((line) => line.trim());+ const last = lines.at(-1);+ if (!last || lines.length === 1) throw new Error('not JSON');+ return JSON.parse(last);+ }+};++/**+ * Check a script's stdout against the widget output contract (stat / list /+ * series / table) and the version's declared output type.+ *+ * `meta.complete === false` is accepted and reported as `partial`: the run+ * finishes with status `partial` — its output is shown, but callers must not+ * treat the numbers as a full sample.+ */+export const parseWidgetOutput = (+ stdout: string,+ expectedType?: WidgetOutputType,+): ParseWidgetOutputResult => {+ if (!stdout || !stdout.trim()) {+ return fail('EMPTY_OUTPUT', 'Script printed nothing to stdout; expected one JSON document');+ }++ const bytes = Buffer.byteLength(stdout, 'utf8');+ if (bytes > WIDGET_OUTPUT_LIMITS.bytes) {+ return fail(+ 'OUTPUT_TOO_LARGE',+ `Output is ${bytes} bytes; the limit is ${WIDGET_OUTPUT_LIMITS.bytes} bytes`,+ );+ }++ let raw: unknown;+ try {+ raw = extractJson(stdout);+ } catch {+ return fail('INVALID_JSON', 'stdout is not a JSON document');+ }++ const parsed = outputSchema.safeParse(raw);+ if (!parsed.success) {+ const tooBig = parsed.error.issues.some((issue) => issue.code === 'too_big');+ const detail = parsed.error.issues+ .slice(0, 5)+ .map((issue) => `${issue.path.join('.') || '(root)'}: ${issue.message}`)+ .join('; ');+ return fail(+ tooBig ? 'OUTPUT_TOO_LARGE' : 'INVALID_OUTPUT',+ `Output does not match the widget contract: ${detail}`,+ );+ }++ const output = parsed.data as WidgetOutput;+ if (expectedType && output.type !== expectedType) {+ return fail(+ 'OUTPUT_TYPE_MISMATCH',+ `Output type "${output.type}" does not match the declared type "${expectedType}"`,+ );+ }++ const partial = output.meta?.complete === false;+ return { ok: true, output, partial, partialMessage: partial ? output.meta?.message : undefined };+};diff --git a/apps/server/src/services/widget/redact.ts b/apps/server/src/services/widget/redact.tsnew file mode 100644index 00000000000..0009795c76c--- /dev/null+++ b/apps/server/src/services/widget/redact.ts@@ -0,0 +1,55 @@+/** Persisted size of each raw stream on a run row. */+export const WIDGET_RUN_STREAM_LIMIT = 16 * 1024;++const TRUNCATION_MARKER = '\n…[truncated]';++/** Secret values shorter than this are not redacted: they would shred ordinary text. */+const MIN_SECRET_LENGTH = 6;++/**+ * Well-known token shapes redacted even when they were not injected by us —+ * a script may read a credential from elsewhere and echo it.+ */+const TOKEN_PATTERNS: RegExp[] = [+ /\b(?:ghp|gho|ghu|ghs|ghr|github_pat)_\w{20,}\b/g,+ /\bsk-[\w-]{20,}\b/g,+ /\bxox[abprs]-[\w-]{10,}\b/g,+ /\bAKIA[0-9A-Z]{16}\b/g,+];++const BEARER_PATTERN = /\b(Bearer)\s+[\w.~+/-]{16,}=*/gi;++/**+ * Replace every occurrence of the injected secret values, then any well-known+ * token shape. Secrets are matched longest first so one secret containing+ * another is removed whole.+ */+export const redactSecrets = (text: string, secrets: Record<string, string> = {}): string => {+ if (!text) return text;++ let result = text;+ const entries = Object.entries(secrets)+ .filter(([, value]) => typeof value === 'string' && value.length >= MIN_SECRET_LENGTH)+ .sort(([, a], [, b]) => b.length - a.length);++ for (const [name, value] of entries) {+ result = result.split(value).join(`[REDACTED:${name}]`);+ }++ for (const pattern of TOKEN_PATTERNS) {+ result = result.replace(pattern, '[REDACTED]');+ }+ result = result.replaceAll(BEARER_PATTERN, '$1 [REDACTED]');++ return result;+};++/** Keep the head of a stream within `limit` characters, marking the cut. */+export const truncateStream = (text: string, limit = WIDGET_RUN_STREAM_LIMIT): string => {+ if (!text || text.length <= limit) return text;+ return text.slice(0, Math.max(0, limit - TRUNCATION_MARKER.length)) + TRUNCATION_MARKER;+};++/** Redact first so a secret straddling the cut is never half-persisted. */+export const sanitizeStream = (text: string, secrets: Record<string, string> = {}): string =>+ truncateStream(redactSecrets(text, secrets));diff --git a/apps/server/src/services/widget/sandbox/__tests__/cloudflareWorker.live.test.ts b/apps/server/src/services/widget/sandbox/__tests__/cloudflareWorker.live.test.tsnew file mode 100644index 00000000000..c574d1467c7--- /dev/null+++ b/apps/server/src/services/widget/sandbox/__tests__/cloudflareWorker.live.test.ts@@ -0,0 +1,64 @@+// @vitest-environment node+/**+ * Optional live check against the real widget sandbox Worker. Skipped unless+ * both variables are set; inject the token from a local file, never inline it:+ *+ * WIDGET_SANDBOX_URL=https://<worker>.workers.dev \+ * WIDGET_SANDBOX_TOKEN="$(cat /path/to/token)" \+ * bunx vitest run apps/server/src/services/widget/sandbox/__tests__/cloudflareWorker.live.test.ts+ *+ * Node's fetch ignores HTTPS_PROXY; behind a proxy also set NODE_USE_ENV_PROXY=1.+ */+import { describe, expect, it } from 'vitest';++import { parseWidgetOutput } from '../../outputContract';+import { redactSecrets } from '../../redact';+import { CloudflareWorkerSandboxRunner } from '../cloudflareWorker';++const url = process.env.WIDGET_SANDBOX_URL;+const token = process.env.WIDGET_SANDBOX_TOKEN;++describe.skipIf(!url || !token)('CloudflareWorkerSandboxRunner (live Worker)', () => {+ const runner = new CloudflareWorkerSandboxRunner({+ networkFormat:+ process.env.WIDGET_SANDBOX_NETWORK_FORMAT === 'allowlist' ? 'allowlist' : 'boolean',+ token,+ url,+ });++ it('echoes a stat through the real sandbox with an injected env', async () => {+ const env = { ECHO_SECRET: 'live-echo-secret-value' };+ const result = await runner.run({+ env,+ network: { allow: [] },+ runtime: 'bash',+ script: [+ 'echo "debug: $ECHO_SECRET" >&2',+ `echo '{"type":"stat","label":"echo","value":42}'`,+ ].join('\n'),+ subject: { id: 'live-check', kind: 'widget' },+ timeoutMs: 60_000,+ });++ expect(result.exitCode).toBe(0);+ expect(result.timedOut).toBe(false);+ expect(parseWidgetOutput(result.stdout, 'stat')).toMatchObject({+ ok: true,+ output: { label: 'echo', type: 'stat', value: 42 },+ });+ expect(redactSecrets(result.stderr, env).trim()).toBe('debug: [REDACTED:ECHO_SECRET]');+ }, 120_000);++ it('reports a non-zero exit from the real sandbox', async () => {+ const result = await runner.run({+ env: {},+ network: { allow: [] },+ runtime: 'bash',+ script: 'echo oops >&2; exit 3',+ subject: { id: 'live-check', kind: 'widget' },+ });++ expect(result).toMatchObject({ exitCode: 3, timedOut: false });+ expect(result.stderr.trim()).toBe('oops');+ }, 120_000);+});diff --git a/apps/server/src/services/widget/sandbox/__tests__/cloudflareWorker.test.ts b/apps/server/src/services/widget/sandbox/__tests__/cloudflareWorker.test.tsnew file mode 100644index 00000000000..28f7dc04802--- /dev/null+++ b/apps/server/src/services/widget/sandbox/__tests__/cloudflareWorker.test.ts@@ -0,0 +1,162 @@+import { describe, expect, it, vi } from 'vitest';++import { CloudflareWorkerSandboxRunner } from '../cloudflareWorker';+import {+ WIDGET_SANDBOX_DEFAULT_TIMEOUT_MS,+ WIDGET_SANDBOX_MAX_TIMEOUT_MS,+ WidgetSandboxError,+ type WidgetSandboxRunRequest,+} from '../types';++const URL = 'https://sandbox.example.workers.dev/';+const TOKEN = 'test-token';++const respond = (status: number, body: unknown) =>+ vi.fn().mockImplementation(+ async () =>+ new Response(JSON.stringify(body), {+ headers: { 'content-type': 'application/json' },+ status,+ }),+ );++const runnerWith = (fetchImpl: ReturnType<typeof vi.fn>, networkFormat?: 'allowlist' | 'boolean') =>+ new CloudflareWorkerSandboxRunner({+ fetch: fetchImpl as unknown as typeof fetch,+ networkFormat,+ token: TOKEN,+ url: URL,+ });++const request = (overrides: Partial<WidgetSandboxRunRequest> = {}): WidgetSandboxRunRequest => ({+ env: {},+ network: { allow: [] },+ runtime: 'node',+ script: 'x',+ subject: { id: 'widget-1', kind: 'widget' },+ ...overrides,+});++describe('CloudflareWorkerSandboxRunner', () => {+ it('posts the script with the full network allowlist and returns the streams', async () => {+ const fetchImpl = respond(200, {+ durationMs: 42,+ exitCode: 0,+ stderr: '',+ stdout: '{"type":"stat","value":1}',+ });++ const result = await runnerWith(fetchImpl, 'allowlist').run(+ request({+ env: { GITHUB_TOKEN: 'secret' },+ network: { allow: ['api.github.com', 'gitlab.com'] },+ script: 'console.log(1)',+ timeoutMs: 10_000,+ }),+ );++ expect(result).toEqual({+ durationMs: 42,+ exitCode: 0,+ stderr: '',+ stdout: '{"type":"stat","value":1}',+ timedOut: false,+ });+ const [url, init] = fetchImpl.mock.calls[0];+ expect(url).toBe('https://sandbox.example.workers.dev/run');+ expect(init.method).toBe('POST');+ expect(init.headers.Authorization).toBe(`Bearer ${TOKEN}`);+ expect(JSON.parse(init.body)).toEqual({+ env: { GITHUB_TOKEN: 'secret' },+ network: { allow: ['api.github.com', 'gitlab.com'] },+ runtime: 'node',+ script: 'console.log(1)',+ timeoutMs: 10_000,+ });+ });++ it('collapses the allowlist to a boolean by default, the only shape the deployed Worker accepts', async () => {+ const fetchImpl = respond(200, { exitCode: 0, stderr: '', stdout: '' });+ const runner = runnerWith(fetchImpl);++ await runner.run(request({ network: { allow: ['api.github.com'] } }));+ await runner.run(request());++ expect(JSON.parse(fetchImpl.mock.calls[0][1].body).network).toBe(true);+ expect(JSON.parse(fetchImpl.mock.calls[1][1].body).network).toBe(false);+ });++ it('defaults and clamps the timeout to what the Worker accepts', async () => {+ const fetchImpl = respond(200, { exitCode: 0, stderr: '', stdout: '' });+ const runner = runnerWith(fetchImpl);++ await runner.run(request());+ await runner.run(request({ timeoutMs: 10 * 60_000 }));++ expect(JSON.parse(fetchImpl.mock.calls[0][1].body)).toMatchObject({+ network: false,+ timeoutMs: WIDGET_SANDBOX_DEFAULT_TIMEOUT_MS,+ });+ expect(JSON.parse(fetchImpl.mock.calls[1][1].body).timeoutMs).toBe(+ WIDGET_SANDBOX_MAX_TIMEOUT_MS,+ );+ });++ it('reports a non-zero exit as a result, not an error', async () => {+ const result = await runnerWith(+ respond(200, { durationMs: 5, exitCode: 3, stderr: 'oops', stdout: '' }),+ ).run(request({ runtime: 'bash', script: 'exit 3' }));++ expect(result).toMatchObject({ exitCode: 3, stderr: 'oops', timedOut: false });+ });++ it('maps the Worker timeout answer to timedOut', async () => {+ const result = await runnerWith(+ respond(200, { durationMs: 1000, error: 'timeout', message: 'Command timed out' }),+ ).run(request({ timeoutMs: 1000 }));++ expect(result).toMatchObject({ exitCode: 124, timedOut: true });+ });++ it('fails clearly when the sandbox is not configured', async () => {+ const fetchImpl = vi.fn();+ const runner = new CloudflareWorkerSandboxRunner({+ fetch: fetchImpl as unknown as typeof fetch,+ });++ expect(runner.isConfigured).toBe(false);+ await expect(runner.run(request())).rejects.toMatchObject({+ code: 'SANDBOX_NOT_CONFIGURED',+ message: expect.stringContaining('WIDGET_SANDBOX_URL'),+ });+ expect(fetchImpl).not.toHaveBeenCalled();+ });++ it.each([+ [401, { error: 'unauthorized' }, 'SANDBOX_UNAUTHORIZED'],+ [400, { error: '`runtime` must be one of node | python | bash' }, 'SANDBOX_BAD_REQUEST'],+ [500, { error: 'execution_failed', message: 'container crashed' }, 'SANDBOX_ERROR'],+ ])('throws WidgetSandboxError on HTTP %i', async (status, body, code) => {+ const error = await runnerWith(respond(status, body))+ .run(request())+ .catch((e) => e);++ expect(error).toBeInstanceOf(WidgetSandboxError);+ expect(error.code).toBe(code);+ expect(error.message).not.toContain(TOKEN);+ });++ it('wraps network failures and unreadable bodies', async () => {+ await expect(+ runnerWith(vi.fn().mockRejectedValue(new TypeError('fetch failed'))).run(request()),+ ).rejects.toMatchObject({+ code: 'SANDBOX_ERROR',+ message: 'Sandbox request failed: fetch failed',+ });+ await expect(+ runnerWith(+ vi.fn().mockResolvedValue(new Response('<html>bad gateway</html>', { status: 502 })),+ ).run(request()),+ ).rejects.toMatchObject({ code: 'SANDBOX_ERROR' });+ });+});diff --git a/apps/server/src/services/widget/sandbox/__tests__/index.test.ts b/apps/server/src/services/widget/sandbox/__tests__/index.test.tsnew file mode 100644index 00000000000..1ff96fb7ede--- /dev/null+++ b/apps/server/src/services/widget/sandbox/__tests__/index.test.ts@@ -0,0 +1,64 @@+import { beforeEach, describe, expect, it, vi } from 'vitest';++describe('createWidgetSandboxRunner', () => {+ beforeEach(() => {+ vi.resetModules();+ });++ it('defaults to the Cloudflare Worker provider with the boolean network format', async () => {+ vi.doMock('@/envs/sandbox', () => ({+ sandboxEnv: { WIDGET_SANDBOX_TOKEN: 'tok', WIDGET_SANDBOX_URL: 'https://w.example.dev' },+ }));+ const fetchImpl = vi+ .fn()+ .mockResolvedValue(+ new Response(JSON.stringify({ exitCode: 0, stderr: '', stdout: '' }), { status: 200 }),+ );+ vi.stubGlobal('fetch', fetchImpl);++ const { CloudflareWorkerSandboxRunner, createWidgetSandboxRunner } = await import('../index');+ const runner = createWidgetSandboxRunner();+ expect(runner).toBeInstanceOf(CloudflareWorkerSandboxRunner);++ await runner.run({+ env: {},+ network: { allow: ['api.github.com'] },+ runtime: 'node',+ script: 'x',+ subject: { id: 'w', kind: 'widget' },+ });+ expect(fetchImpl.mock.calls[0][0]).toBe('https://w.example.dev/run');+ expect(JSON.parse(fetchImpl.mock.calls[0][1].body).network).toBe(true);+ vi.unstubAllGlobals();+ });++ it('honors the allowlist network format', async () => {+ vi.doMock('@/envs/sandbox', () => ({+ sandboxEnv: {+ WIDGET_SANDBOX_NETWORK_FORMAT: 'allowlist',+ WIDGET_SANDBOX_PROVIDER: 'cloudflare-worker',+ WIDGET_SANDBOX_TOKEN: 'tok',+ WIDGET_SANDBOX_URL: 'https://w.example.dev',+ },+ }));+ const fetchImpl = vi+ .fn()+ .mockResolvedValue(+ new Response(JSON.stringify({ exitCode: 0, stderr: '', stdout: '' }), { status: 200 }),+ );+ vi.stubGlobal('fetch', fetchImpl);++ const { createWidgetSandboxRunner } = await import('../index');+ await createWidgetSandboxRunner().run({+ env: {},+ network: { allow: ['api.github.com'] },+ runtime: 'node',+ script: 'x',+ subject: { id: 'w', kind: 'widget' },+ });+ expect(JSON.parse(fetchImpl.mock.calls[0][1].body).network).toEqual({+ allow: ['api.github.com'],+ });+ vi.unstubAllGlobals();+ });+});diff --git a/apps/server/src/services/widget/sandbox/cloudflareWorker.ts b/apps/server/src/services/widget/sandbox/cloudflareWorker.tsnew file mode 100644index 00000000000..ef296d3417e--- /dev/null+++ b/apps/server/src/services/widget/sandbox/cloudflareWorker.ts@@ -0,0 +1,139 @@+import debug from 'debug';++import {+ clampSandboxTimeout,+ WIDGET_SANDBOX_REQUEST_OVERHEAD_MS,+ WidgetSandboxError,+ type WidgetSandboxRunner,+ type WidgetSandboxRunRequest,+ type WidgetSandboxRunResult,+} from './types';++const log = debug('lobe-server:widget:sandbox');++/**+ * How the request encodes the network allowlist:+ *+ * - `allowlist` — `network: { allow: ['api.github.com', …] }`, so the Worker+ * can restrict egress to the declared hosts;+ * - `boolean` — `network: allow.length > 0`, for a Worker that only+ * understands an on/off switch (the original contract). Hosts are then not+ * enforced by the sandbox.+ */+export type CloudflareWorkerNetworkFormat = 'allowlist' | 'boolean';++export interface CloudflareWorkerSandboxRunnerOptions {+ fetch?: typeof fetch;+ networkFormat?: CloudflareWorkerNetworkFormat;+ token?: string;+ url?: string;+}++interface WorkerRunResponse {+ durationMs?: number;+ error?: string;+ exitCode?: number;+ message?: string;+ stderr?: string;+ stdout?: string;+}++/**+ * Widget sandbox backed by a Cloudflare Worker+ * (`POST {WIDGET_SANDBOX_URL}/run`, Bearer `WIDGET_SANDBOX_TOKEN`).+ *+ * Worker contract: request `{ script, runtime, env, network, timeoutMs }`,+ * response `{ stdout, stderr, exitCode, durationMs }`; a script exceeding its+ * timeout answers 200 with `error: 'timeout'` (exit code 124), an execution+ * failure answers 500 with `error: 'execution_failed'`.+ *+ * `subject` is not sent: the Worker has no use for it and rejects nothing+ * based on it.+ */+export class CloudflareWorkerSandboxRunner implements WidgetSandboxRunner {+ private readonly fetchImpl: typeof fetch;+ private readonly networkFormat: CloudflareWorkerNetworkFormat;+ private readonly token?: string;+ private readonly url?: string;++ constructor(options: CloudflareWorkerSandboxRunnerOptions = {}) {+ this.fetchImpl = options.fetch ?? fetch;+ this.networkFormat = options.networkFormat ?? 'boolean';+ this.token = options.token;+ this.url = options.url?.replace(/\/+$/, '');+ }++ get isConfigured() {+ return !!this.url && !!this.token;+ }++ async run(request: WidgetSandboxRunRequest): Promise<WidgetSandboxRunResult> {+ if (!this.url || !this.token) {+ throw new WidgetSandboxError(+ 'SANDBOX_NOT_CONFIGURED',+ 'Widget sandbox is not configured: set WIDGET_SANDBOX_URL and WIDGET_SANDBOX_TOKEN',+ );+ }++ const timeoutMs = clampSandboxTimeout(request.timeoutMs);+ const allow = request.network.allow;+ const body = {+ env: request.env,+ network: this.networkFormat === 'boolean' ? allow.length > 0 : { allow },+ runtime: request.runtime,+ script: request.script,+ timeoutMs,+ };++ let response: Response;+ try {+ response = await this.fetchImpl(`${this.url}/run`, {+ body: JSON.stringify(body),+ headers: {+ 'Authorization': `Bearer ${this.token}`,+ 'content-type': 'application/json',+ },+ method: 'POST',+ signal: AbortSignal.timeout(timeoutMs + WIDGET_SANDBOX_REQUEST_OVERHEAD_MS),+ });+ } catch (error) {+ const message = error instanceof Error ? error.message : String(error);+ log('request failed: %s', message);+ throw new WidgetSandboxError('SANDBOX_ERROR', `Sandbox request failed: ${message}`);+ }++ const payload = (await response.json().catch(() => null)) as WorkerRunResponse | null;++ if (response.status === 401) {+ throw new WidgetSandboxError('SANDBOX_UNAUTHORIZED', 'Sandbox rejected the credentials');+ }+ if (response.status === 400) {+ throw new WidgetSandboxError(+ 'SANDBOX_BAD_REQUEST',+ `Sandbox rejected the request: ${payload?.error ?? 'bad request'}`,+ );+ }+ if (!payload || typeof payload !== 'object') {+ throw new WidgetSandboxError(+ 'SANDBOX_ERROR',+ `Sandbox returned an unreadable response (HTTP ${response.status})`,+ );+ }++ const timedOut = payload.error === 'timeout';+ if (!response.ok && !timedOut) {+ throw new WidgetSandboxError(+ 'SANDBOX_ERROR',+ `Sandbox execution failed (HTTP ${response.status}): ${payload.message ?? payload.error ?? 'unknown error'}`,+ );+ }++ return {+ durationMs: typeof payload.durationMs === 'number' ? payload.durationMs : 0,+ exitCode: typeof payload.exitCode === 'number' ? payload.exitCode : timedOut ? 124 : -1,+ stderr: typeof payload.stderr === 'string' ? payload.stderr : '',+ stdout: typeof payload.stdout === 'string' ? payload.stdout : '',+ timedOut,+ };+ }+}diff --git a/apps/server/src/services/widget/sandbox/index.ts b/apps/server/src/services/widget/sandbox/index.tsnew file mode 100644index 00000000000..a0a58afeaa8--- /dev/null+++ b/apps/server/src/services/widget/sandbox/index.ts@@ -0,0 +1,24 @@+import { sandboxEnv } from '@/envs/sandbox';++import { CloudflareWorkerSandboxRunner } from './cloudflareWorker';+import type { WidgetSandboxRunner } from './types';++/**+ * The widget sandbox selected by env (`WIDGET_SANDBOX_PROVIDER`, default+ * `cloudflare-worker`). An unconfigured provider still returns a runner; its+ * runs fail with `SANDBOX_NOT_CONFIGURED`, which closes the run as `failed`.+ */+export const createWidgetSandboxRunner = (): WidgetSandboxRunner => {+ switch (sandboxEnv.WIDGET_SANDBOX_PROVIDER ?? 'cloudflare-worker') {+ case 'cloudflare-worker': {+ return new CloudflareWorkerSandboxRunner({+ networkFormat: sandboxEnv.WIDGET_SANDBOX_NETWORK_FORMAT,+ token: sandboxEnv.WIDGET_SANDBOX_TOKEN,+ url: sandboxEnv.WIDGET_SANDBOX_URL,+ });+ }+ }+};++export { CloudflareWorkerSandboxRunner } from './cloudflareWorker';+export * from './types';diff --git a/apps/server/src/services/widget/sandbox/types.ts b/apps/server/src/services/widget/sandbox/types.tsnew file mode 100644index 00000000000..23571ea2d43--- /dev/null+++ b/apps/server/src/services/widget/sandbox/types.ts@@ -0,0 +1,71 @@+import type { WidgetRuntime } from '@lobechat/types';++/** Upper bound any provider accepts for one script execution. */+export const WIDGET_SANDBOX_MAX_TIMEOUT_MS = 120_000;+export const WIDGET_SANDBOX_DEFAULT_TIMEOUT_MS = 30_000;+/** Extra time a sandbox request may take beyond the script timeout (cold start, upload). */+export const WIDGET_SANDBOX_REQUEST_OVERHEAD_MS = 60_000;++/**+ * What the execution belongs to, for provider-side attribution, quotas and+ * log correlation. Never used for authorization — the caller already decided.+ */+export interface WidgetSandboxSubject {+ id: string;+ kind: 'widget';+}++export interface WidgetSandboxRunRequest {+ /** Variables exposed to this execution only; a provider must never persist them. */+ env: Record<string, string>;+ /** Hostnames the script may reach; an empty list means no network at all. */+ network: { allow: string[] };+ runtime: WidgetRuntime;+ script: string;+ subject: WidgetSandboxSubject;+ /** Clamped by the provider to `WIDGET_SANDBOX_MAX_TIMEOUT_MS`. */+ timeoutMs?: number;+}++export interface WidgetSandboxRunResult {+ durationMs: number;+ exitCode: number;+ stderr: string;+ stdout: string;+ timedOut: boolean;+}++/**+ * Executes one widget script in isolation. Provider-agnostic on purpose: the+ * execution layer is moving to the lobehub-market service (a one-shot,+ * Cloudflare-backed run endpoint), so callers depend only on this contract+ * and the implementation is picked by `WIDGET_SANDBOX_PROVIDER`.+ *+ * A script that runs and exits non-zero, or times out, is a normal result —+ * judging it is the caller's job. Implementations throw `WidgetSandboxError`+ * only when the script could not be executed at all.+ */+export interface WidgetSandboxRunner {+ run: (request: WidgetSandboxRunRequest) => Promise<WidgetSandboxRunResult>;+}++export type WidgetSandboxErrorCode =+ 'SANDBOX_BAD_REQUEST' | 'SANDBOX_ERROR' | 'SANDBOX_NOT_CONFIGURED' | 'SANDBOX_UNAUTHORIZED';++/** The sandbox could not execute the script at all (as opposed to the script failing). */+export class WidgetSandboxError extends Error {+ constructor(+ public readonly code: WidgetSandboxErrorCode,+ message: string,+ ) {+ super(message);+ this.name = 'WidgetSandboxError';+ }+}++export const clampSandboxTimeout = (timeoutMs?: number) => {+ if (!timeoutMs || !Number.isFinite(timeoutMs) || timeoutMs <= 0) {+ return WIDGET_SANDBOX_DEFAULT_TIMEOUT_MS;+ }+ return Math.min(Math.round(timeoutMs), WIDGET_SANDBOX_MAX_TIMEOUT_MS);+};diff --git a/apps/server/src/services/widget/schedule.ts b/apps/server/src/services/widget/schedule.tsnew file mode 100644index 00000000000..8161ca55946--- /dev/null+++ b/apps/server/src/services/widget/schedule.ts@@ -0,0 +1,11 @@+import { validateCronPattern } from '@lobechat/utils/cronEval';++/** The first cron occurrence strictly after `from`, or null when the pattern is invalid. */+export const nextScheduleOccurrence = (+ pattern: string,+ timezone: string | null | undefined,+ from: Date = new Date(),+): Date | null => {+ const result = validateCronPattern(pattern, timezone ?? null, { count: 1, from });+ return result.valid ? result.nextRuns[0] : null;+};diff --git a/apps/server/src/services/widget/scheduler.ts b/apps/server/src/services/widget/scheduler.tsnew file mode 100644index 00000000000..7edd614ef96--- /dev/null+++ b/apps/server/src/services/widget/scheduler.ts@@ -0,0 +1,314 @@+import type { WidgetManifest, WidgetRunStatus } from '@lobechat/types';+import debug from 'debug';+import pMap from 'p-map';++import { WidgetModel } from '@/database/models/widget';+import type { WidgetRow, WidgetRunRow, WidgetVersionRow } from '@/database/schemas';+import type { LobeChatDatabase } from '@/database/type';++import { executeWidgetRun, type ExecuteWidgetRunDeps } from './executeRun';+import { clampSandboxTimeout, WIDGET_SANDBOX_REQUEST_OVERHEAD_MS } from './sandbox/types';+import { nextScheduleOccurrence } from './schedule';++const log = debug('lobe-server:widget:scheduler');++const DEFAULT_TICK_LIMIT = 50;+const DEFAULT_INLINE_CONCURRENCY = 4;+const DEFAULT_DISPATCH_CONCURRENCY = 10;++/** Slack on top of the sandbox bounds before a reserved run counts as abandoned. */+export const WIDGET_RUN_LEASE_MARGIN_MS = 60_000;+/** Reservations older than this are no longer resumed — that occurrence is long gone. */+const RESUME_HORIZON_MS = 24 * 60 * 60 * 1000;++/**+ * How long a worker may hold a reserved scheduled run before another worker+ * may take it over: the version's (clamped) script timeout, plus what the+ * sandbox request may add on top, plus a margin for credential resolution+ * and closing the run.+ */+export const widgetRunLeaseMs = (manifest?: Pick<WidgetManifest, 'timeoutMs'> | null) =>+ clampSandboxTimeout(manifest?.timeoutMs) ++ WIDGET_SANDBOX_REQUEST_OVERHEAD_MS ++ WIDGET_RUN_LEASE_MARGIN_MS;++/** The shortest lease any version can have — the coarse cut for the stale query. */+const MIN_LEASE_MS = widgetRunLeaseMs({ timeoutMs: 1 });++/** One due slot handed to another worker: the widget and the `next_run_at` it was due at. */+export interface WidgetSlotTarget {+ slot: Date;+ widgetId: string;+}++/**+ * One abandoned reservation handed to another worker to resume. The lease it+ * was judged stale under travels along so a re-dispatch after a further+ * crash is a distinct message.+ */+export interface WidgetResumeTarget {+ leaseStartedAt: Date;+ runId: string;+ widgetId: string;+}++export type WidgetDispatchTarget = WidgetResumeTarget | WidgetSlotTarget;++export const isWidgetResumeTarget = (target: WidgetDispatchTarget): target is WidgetResumeTarget =>+ 'runId' in target;++export interface WidgetTickOptions {+ /**+ * Hand work to another worker (QStash in queue mode) instead of running it+ * inline: due slots, which the worker claims (see `runDispatchedWidget`),+ * and stale reservations, which it resumes (see `resumeDispatchedRun`). A+ * rejected dispatch leaves the slot due / the run stale for the next tick.+ */+ dispatch?: (target: WidgetDispatchTarget) => Promise<void>;+ /** Report what is due without claiming or running anything. */+ dryRun?: boolean;+ limit?: number;+ now?: Date;+}++export interface WidgetTickResult {+ /** Slots this tick claimed itself — inline mode only; dispatched slots are claimed by the worker. */+ claimed: number;+ dispatched: number;+ due: number;+ results: { error?: string; runId?: string; status?: WidgetRunStatus; widgetId: string }[];+ /** Stale reservations taken over (inline) or handed to a worker to resume (queue mode). */+ resumed: number;+}++interface RunTarget {+ run: WidgetRunRow;+ version: WidgetVersionRow;+ widget: WidgetRow;+}++const nextOccurrence = (+ widget: Pick<WidgetRow, 'schedulePattern' | 'scheduleTimezone'>,+ now: Date,+) => nextScheduleOccurrence(widget.schedulePattern!, widget.scheduleTimezone, now);++/**+ * Reserved scheduled runs whose lease has expired — the worker that reserved+ * (or last resumed) them is presumed dead. The query cuts at the shortest+ * possible lease; each run's own lease (from its version's timeout) decides.+ */+const findStaleRuns = async (+ db: LobeChatDatabase,+ now: Date,+ filter: { limit: number; runId?: string; widgetId?: string },+): Promise<RunTarget[]> => {+ const rows = await WidgetModel.findStaleScheduledRuns(db, {+ ...filter,+ createdAfter: new Date(now.getTime() - RESUME_HORIZON_MS),+ startedBefore: new Date(now.getTime() - MIN_LEASE_MS),+ });+ return rows.filter(+ ({ run, version }) =>+ now.getTime() - run.startedAt.getTime() > widgetRunLeaseMs(version.manifest),+ );+};++/** Take over a stale run (compare-and-set on its lease); undefined when another worker won. */+const takeOver = async (+ db: LobeChatDatabase,+ target: RunTarget,+): Promise<RunTarget | undefined> => {+ const run = await WidgetModel.renewRunLease(db, {+ expectedStartedAt: target.run.startedAt,+ runId: target.run.id,+ });+ if (!run) {+ log('skip run=%s reason=resumed-elsewhere', target.run.id);+ return undefined;+ }+ log('resume run=%s widget=%s', run.id, target.widget.id);+ return { ...target, run };+};++export type DispatchedWidgetResult =+ | {+ /** The run was a stale reservation taken over rather than a fresh claim. */+ resumed?: boolean;+ run: WidgetRunRow | undefined;+ skipped?: undefined;+ }+ | { skipped: 'already-claimed' | 'not-resumable' | 'not-runnable' };++/**+ * Consumer half of a queued scheduled run. Claims the dispatched slot —+ * advancing `next_run_at` and reserving the `schedule` run in one+ * transaction — and executes the reserved run.+ *+ * When the slot is already claimed (a redelivery, or a duplicate message),+ * the reservation it left behind is resumed only if its lease has expired,+ * i.e. the worker that reserved it died before closing it; a run still+ * within its lease is left to its worker and the message is acknowledged.+ */+export const runDispatchedWidget = async (+ db: LobeChatDatabase,+ target: WidgetSlotTarget,+ deps: ExecuteWidgetRunDeps,+ options: { now?: Date } = {},+): Promise<DispatchedWidgetResult> => {+ const now = options.now ?? new Date();+ const live = await WidgetModel.findLiveWithPublishedVersion(db, target.widgetId);+ // Trashed, unpublished or unscheduled since the tick: nothing to run.+ if (!live?.widget.schedulePattern) return { skipped: 'not-runnable' };++ const reserved = await WidgetModel.claimDueRun(db, {+ expectedNextRunAt: target.slot,+ nextRunAt: nextOccurrence(live.widget, now),+ versionId: live.version.id,+ widgetId: live.widget.id,+ });+ if (reserved) {+ return { run: await executeWidgetRun(db, { ...live, run: reserved }, deps) };+ }++ const [stale] = await findStaleRuns(db, now, { limit: 1, widgetId: target.widgetId });+ const resumed = stale && (await takeOver(db, stale));+ if (!resumed) {+ log('skip widget=%s slot=%s reason=already-claimed', target.widgetId, target.slot);+ return { skipped: 'already-claimed' };+ }++ return { resumed: true, run: await executeWidgetRun(db, resumed, deps) };+};++/**+ * Consumer half of a resume dispatched by the tick's stale sweep: take the+ * run over if it is still stale (nobody resumed or closed it meanwhile) and+ * execute it.+ */+export const resumeDispatchedRun = async (+ db: LobeChatDatabase,+ target: Pick<WidgetResumeTarget, 'runId' | 'widgetId'>,+ deps: ExecuteWidgetRunDeps,+ options: { now?: Date } = {},+): Promise<DispatchedWidgetResult> => {+ const [stale] = await findStaleRuns(db, options.now ?? new Date(), {+ limit: 1,+ runId: target.runId,+ widgetId: target.widgetId,+ });+ const resumed = stale && (await takeOver(db, stale));+ if (!resumed) return { skipped: 'not-resumable' };++ return { resumed: true, run: await executeWidgetRun(db, resumed, deps) };+};++/**+ * One scheduler tick.+ *+ * Due slots: live, published widgets whose `next_run_at` has passed. With+ * `dispatch` (queue mode) each slot is handed to a worker, which claims it.+ * Inline, the tick claims each slot itself — advancing `next_run_at` and+ * reserving the run in one transaction (compare-and-set, so overlapping ticks+ * never double-fire) — then executes the reserved runs with bounded+ * concurrency.+ *+ * Stale reservations: scheduled runs left `running` past their lease because+ * their worker died. Each tick resumes a bounded batch — handed to a worker+ * in queue mode (deduplicated per lease), taken over and executed inline+ * otherwise.+ *+ * A missed stretch (server down for hours) fires once and resumes at the next+ * future occurrence rather than replaying every skipped slot. An invalid+ * stored pattern clears `next_run_at`, parking the widget until it is fixed.+ */+export const runWidgetSchedulerTick = async (+ db: LobeChatDatabase,+ deps: ExecuteWidgetRunDeps,+ options: WidgetTickOptions = {},+): Promise<WidgetTickResult> => {+ const now = options.now ?? new Date();+ const limit = options.limit ?? DEFAULT_TICK_LIMIT;+ const due = await WidgetModel.findDue(db, { limit, now });++ if (options.dryRun) {+ return { claimed: 0, dispatched: 0, due: due.length, resumed: 0, results: [] };+ }++ const stale = await findStaleRuns(db, now, { limit });+ let dispatched = 0;+ let resumed = 0;++ if (options.dispatch) {+ const dispatch = options.dispatch;+ const targets: WidgetDispatchTarget[] = [+ ...due.map(({ widget }) => ({ slot: widget.nextRunAt!, widgetId: widget.id })),+ ...stale.map(({ run, widget }) => ({+ leaseStartedAt: run.startedAt,+ runId: run.id,+ widgetId: widget.id,+ })),+ ];+ const results = await pMap(+ targets,+ async (target): Promise<WidgetTickResult['results'][number]> => {+ const runId = isWidgetResumeTarget(target) ? target.runId : undefined;+ try {+ await dispatch(target);+ if (runId) resumed += 1;+ else dispatched += 1;+ return { ...(runId && { runId }), widgetId: target.widgetId };+ } catch (error) {+ console.error('[widget:tick] dispatch failed widget=%s', target.widgetId, error);+ return { error: String(error), ...(runId && { runId }), widgetId: target.widgetId };+ }+ },+ { concurrency: DEFAULT_DISPATCH_CONCURRENCY },+ );+ return { claimed: 0, dispatched, due: due.length, resumed, results };+ }++ const runnable: RunTarget[] = [];+ for (const target of stale) {+ const taken = await takeOver(db, target);+ if (taken) runnable.push(taken);+ }+ resumed = runnable.length;++ let claimed = 0;+ for (const { version, widget } of due) {+ const run = await WidgetModel.claimDueRun(db, {+ expectedNextRunAt: widget.nextRunAt!,+ nextRunAt: nextOccurrence(widget, now),+ versionId: version.id,+ widgetId: widget.id,+ });+ if (!run) {+ log('skip widget=%s reason=claimed-elsewhere', widget.id);+ continue;+ }+ claimed += 1;+ runnable.push({ run, version, widget });+ }++ const results = await pMap(+ runnable,+ async (target): Promise<WidgetTickResult['results'][number]> => {+ try {+ const run = await executeWidgetRun(db, target, deps);+ dispatched += 1;+ return { runId: target.run.id, status: run?.status, widgetId: target.widget.id };+ } catch (error) {+ // The reservation stays `running`; a later tick resumes it once its lease expires.+ console.error('[widget:tick] run failed widget=%s', target.widget.id, error);+ return {+ error: error instanceof Error ? error.message : String(error),+ runId: target.run.id,+ widgetId: target.widget.id,+ };+ }+ },+ { concurrency: DEFAULT_INLINE_CONCURRENCY },+ );++ return { claimed, dispatched, due: due.length, resumed, results };+};diff --git a/apps/server/src/services/widget/versionSchema.ts b/apps/server/src/services/widget/versionSchema.tsnew file mode 100644index 00000000000..becd69639a0--- /dev/null+++ b/apps/server/src/services/widget/versionSchema.ts@@ -0,0 +1,58 @@+import { WIDGET_OUTPUT_TYPES, WIDGET_RUNTIMES } from '@lobechat/types';+import { z } from 'zod';++import { WIDGET_SANDBOX_MAX_TIMEOUT_MS } from './sandbox/types';++/**+ * Validation of a widget version's authored content, shared by every+ * entry point that records a draft so all accept exactly the same content.+ */++const envName = z.string().regex(/^[A-Z_]\w*$/i, 'env names must be valid shell identifiers');++export const widgetManifestSchema = z.object({+ description: z.string().max(2000).optional(),+ env: z+ .array(+ z.object({+ connector: z.string().min(1).optional(),+ description: z.string().max(500).optional(),+ field: z.string().min(1).max(200).optional(),+ name: envName,+ required: z.boolean().optional(),+ }),+ )+ .max(20)+ .optional(),+ metric: z+ .object({+ key: z.string().min(1).max(100),+ kind: z.enum(['gauge', 'counter']).optional(),+ unit: z.string().max(50).optional(),+ valuePath: z.string().max(200).optional(),+ })+ .optional(),+ network: z.object({ allow: z.array(z.string().min(1).max(253)).max(50) }).optional(),+ schedule: z.object({ pattern: z.string(), timezone: z.string().optional() }).optional(),+ timeoutMs: z.number().int().positive().max(WIDGET_SANDBOX_MAX_TIMEOUT_MS).optional(),+ title: z.string().max(200).optional(),+});++export const widgetViewSchema = z.object({+ chart: z.enum(['line', 'bar', 'area']).optional(),+ columns: z.array(z.string()).optional(),+ limit: z.number().int().positive().max(500).optional(),+ size: z.enum(['sm', 'md', 'lg']).optional(),+});++export const widgetVersionContentSchema = z.object({+ changeNote: z.string().max(500).nullish(),+ manifest: widgetManifestSchema.nullish(),+ outputType: z.enum(WIDGET_OUTPUT_TYPES),+ runtime: z.enum(WIDGET_RUNTIMES),+ script: z+ .string()+ .min(1)+ .max(256 * 1024),+ view: widgetViewSchema.nullish(),+});diff --git a/locales/en-US/setting.json b/locales/en-US/setting.jsonindex 75099bdf528..0103fad6c44 100644--- a/locales/en-US/setting.json+++ b/locales/en-US/setting.json@@ -1780,8 +1780,10 @@"trash.restore.success": "Restored","trash.title": "Trash","trash.type.agent": "Agent",+ "trash.type.dashboard": "Dashboard","trash.type.message": "Message","trash.type.topic": "Topic",+ "trash.type.widget": "Widget","trash.untitled": "Untitled","workspace.apiKey.policy.desc": "Choose who can create personal API Keys that act on their behalf in this workspace.","workspace.apiKey.policy.options.allMembers": "All members",diff --git a/locales/zh-CN/setting.json b/locales/zh-CN/setting.jsonindex 875a01aef7c..718fb499f29 100644--- a/locales/zh-CN/setting.json+++ b/locales/zh-CN/setting.json@@ -1780,8 +1780,10 @@"trash.restore.success": "已恢复","trash.title": "回收站","trash.type.agent": "助手",+ "trash.type.dashboard": "看板","trash.type.message": "消息","trash.type.topic": "话题",+ "trash.type.widget": "小组件","trash.untitled": "未命名","workspace.apiKey.policy.desc": "选择哪些成员可以创建代表自己访问此工作区的个人 API Key。","workspace.apiKey.policy.options.allMembers": "所有成员",diff --git a/package.json b/package.jsonindex ce4c46b23e5..02d00e12e4f 100644--- a/package.json+++ b/package.json@@ -133,6 +133,7 @@"tunnel:ngrok": "ngrok http http://localhost:3010","type-check": "tsgo -p tsconfig.type-check.json --noEmit --checkers 2","type-check:tsc": "tsc --noEmit",+ "widget:tick": "tsx ./scripts/widgetTick/index.mts","workflow:cdn": "tsx ./scripts/cdnWorkflow/index.ts","workflow:changelog": "tsx ./scripts/changelogWorkflow/index.ts","workflow:changelog:gen": "tsx ./scripts/changelogWorkflow/generateChangelog.ts",diff --git a/packages/const/src/apiKeyScope.ts b/packages/const/src/apiKeyScope.tsindex 41897b08812..ee3e215d54d 100644--- a/packages/const/src/apiKeyScope.ts+++ b/packages/const/src/apiKeyScope.ts@@ -212,6 +212,9 @@ export const TRPC_NAMESPACE_API_KEY_RULES: Record<string, TrpcNamespaceScopeRulecomposio: 'blocked',config: 'open',connector: 'blocked',+ // boards only lay out widgets; reads mirror `widget`, writes stay key-less+ // so a restricted key cannot reshape what a widget run is attached to+ dashboard: rw('agent:read', null),device: 'blocked',deviceMetric: 'blocked',document: rw('knowledge:read', 'knowledge:write'),@@ -294,6 +297,10 @@ export const TRPC_NAMESPACE_API_KEY_RULES: Record<string, TrpcNamespaceScopeRulevideo: { any: 'model:invoke' },waitlist: 'blocked',webBrowsing: { any: 'model:invoke' },+ // widget runs execute user scripts in the sandbox with the owner's connector+ // credentials, so restricted keys may read widgets and runs but not change+ // or trigger them+ widget: rw('agent:read', null),work: rw('agent:read', 'agent:write'),workspace: rw('workspace:read', 'workspace:write'),workspaceAuditLog: rw('workspace:read', null),diff --git a/packages/database/src/models/__tests__/dashboard.test.ts b/packages/database/src/models/__tests__/dashboard.test.tsnew file mode 100644index 00000000000..fa7d57e1de7--- /dev/null+++ b/packages/database/src/models/__tests__/dashboard.test.ts@@ -0,0 +1,525 @@+// @vitest-environment node+import { and, eq } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it } from 'vitest';++import { getTestDB } from '../../core/getTestDB';+import {+ agents,+ dashboardItems,+ dashboards,+ projects,+ trashItems,+ users,+ workspaces,+} from '../../schemas';+import type { LobeChatDatabase } from '../../type';+import { ScopeLevelError } from '../../utils/scopeLevel';+import { DashboardModel } from '../dashboard';+import { WidgetModel } from '../widget';++const serverDB: LobeChatDatabase = await getTestDB();++const userId = 'dashboard-model-user';+const otherUserId = 'dashboard-model-other-user';+const workspaceId = 'dashboard-model-ws';+const otherWorkspaceId = 'dashboard-model-ws-2';++const seedAgent = async (id: string, owner: string, ws: string | null) => {+ await serverDB.insert(agents).values({ id, userId: owner, workspaceId: ws });+ return id;+};++let identifierSeq = 0;+const seedProject = async (+ id: string,+ owner: string,+ ws: string | null,+ visibility: 'private' | 'public' = 'public',+) => {+ const coordinatorAgentId = await seedAgent(`${id}-coordinator`, owner, ws);+ await serverDB.insert(projects).values({+ coordinatorAgentId,+ id,+ identifier: `D${String(++identifierSeq).padStart(4, '0')}`,+ name: id,+ userId: owner,+ visibility,+ workspaceId: ws,+ });+ return id;+};++beforeEach(async () => {+ await serverDB.delete(trashItems);+ await serverDB.delete(users);+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);+ await serverDB.insert(workspaces).values([+ { id: workspaceId, name: 'WS', primaryOwnerId: userId, slug: 'dashboard-ws' },+ { id: otherWorkspaceId, name: 'WS2', primaryOwnerId: userId, slug: 'dashboard-ws-2' },+ ]);+});++afterEach(async () => {+ await serverDB.delete(trashItems);+ await serverDB.delete(workspaces);+ await serverDB.delete(users);+});++describe('DashboardModel', () => {+ describe('create / find / update', () => {+ it('creates a personal dashboard with uuid id and null scope columns', async () => {+ const model = new DashboardModel(serverDB, userId);+ const dashboard = await model.create({ title: 'Home' });++ expect(dashboard.id).toMatch(/^[\da-f-]{36}$/);+ expect(dashboard).toMatchObject({+ agentId: null,+ projectId: null,+ title: 'Home',+ userId,+ visibility: 'public',+ workspaceId: null,+ });+ expect(await model.findById(dashboard.id)).toMatchObject({ id: dashboard.id });+ });++ it('updates only the creator’s dashboard', async () => {+ const model = new DashboardModel(serverDB, userId);+ const dashboard = await model.create({ title: 'Home' });++ const other = new DashboardModel(serverDB, otherUserId);+ expect(await other.update(dashboard.id, { title: 'hacked' })).toBeUndefined();+ expect(await other.findById(dashboard.id)).toBeUndefined();++ const updated = await model.update(dashboard.id, { icon: '📈', title: 'Ops' });+ expect(updated).toMatchObject({ icon: '📈', title: 'Ops' });+ });++ it('lets workspace members read public boards but not private ones or edit either', async () => {+ const owner = new DashboardModel(serverDB, userId, workspaceId);+ const member = new DashboardModel(serverDB, otherUserId, workspaceId);++ const pub = await owner.create({ title: 'Team' });+ const priv = await owner.create({ title: 'Mine', visibility: 'private' });++ expect(await member.findById(pub.id)).toMatchObject({ id: pub.id });+ expect(await member.findById(priv.id)).toBeUndefined();+ expect(await member.update(pub.id, { title: 'x' })).toBeUndefined();+ });+ });++ describe('scope consistency', () => {+ it('accepts a project and agent from the same workspace, together', async () => {+ const projectId = await seedProject('dash-p1', userId, workspaceId);+ const agentId = await seedAgent('dash-a1', userId, workspaceId);+ const model = new DashboardModel(serverDB, userId, workspaceId);++ const dashboard = await model.create({ agentId, projectId, title: 'Agent in project' });+ expect(dashboard).toMatchObject({ agentId, projectId, workspaceId });+ });++ it('rejects a project from another workspace', async () => {+ const projectId = await seedProject('dash-p2', userId, otherWorkspaceId);+ const model = new DashboardModel(serverDB, userId, workspaceId);++ await expect(model.create({ projectId, title: 'x' })).rejects.toMatchObject({+ code: 'SCOPE_MISMATCH',+ });+ });++ it('rejects a personal agent when creating a workspace dashboard', async () => {+ const agentId = await seedAgent('dash-a2', userId, null);+ const model = new DashboardModel(serverDB, userId, workspaceId);++ await expect(model.create({ agentId, title: 'x' })).rejects.toBeInstanceOf(ScopeLevelError);+ });++ it('rejects a workspace project when creating a personal dashboard', async () => {+ const projectId = await seedProject('dash-p3', userId, workspaceId);+ const model = new DashboardModel(serverDB, userId);++ await expect(model.create({ projectId, title: 'x' })).rejects.toMatchObject({+ code: 'SCOPE_MISMATCH',+ });+ });++ it('rejects another user’s personal project and unknown ids as not found', async () => {+ const projectId = await seedProject('dash-p4', otherUserId, null);+ const model = new DashboardModel(serverDB, userId);++ await expect(model.create({ projectId, title: 'x' })).rejects.toMatchObject({+ code: 'PROJECT_NOT_FOUND',+ });+ await expect(model.create({ agentId: 'missing', title: 'x' })).rejects.toMatchObject({+ code: 'AGENT_NOT_FOUND',+ });+ });+ });++ describe('list by direct level', () => {+ it('returns only rows living directly on the requested level', async () => {+ const projectId = await seedProject('dash-p5', userId, workspaceId);+ const agentId = await seedAgent('dash-a5', userId, workspaceId);+ const ws = new DashboardModel(serverDB, userId, workspaceId);+ const personal = new DashboardModel(serverDB, userId);++ const mine = await personal.create({ title: 'personal' });+ const wsBoard = await ws.create({ sortOrder: 1, title: 'workspace' });+ const wsBoard2 = await ws.create({ sortOrder: 0, title: 'workspace-2' });+ const projectBoard = await ws.create({ projectId, title: 'project' });+ const agentBoard = await ws.create({ agentId, title: 'agent' });+ const agentInProject = await ws.create({ agentId, projectId, title: 'agent-in-project' });++ expect((await personal.list()).map((d) => d.id)).toEqual([mine.id]);+ expect((await ws.list()).map((d) => d.id)).toEqual([wsBoard2.id, wsBoard.id]);+ expect((await ws.list({ projectId })).map((d) => d.id)).toEqual([projectBoard.id]);+ expect((await ws.list({ agentId })).map((d) => d.id)).toEqual([agentBoard.id]);+ expect((await ws.list({ agentId, projectId })).map((d) => d.id)).toEqual([agentInProject.id]);+ });++ it('lists every board of a project, with or without an agent, via listByProject', async () => {+ const projectId = await seedProject('dash-p7', userId, workspaceId);+ const otherProjectId = await seedProject('dash-p8', userId, workspaceId);+ const agentId = await seedAgent('dash-a7', userId, workspaceId);+ const ws = new DashboardModel(serverDB, userId, workspaceId);+ const outsider = new DashboardModel(serverDB, otherUserId, workspaceId);++ await ws.create({ title: 'workspace' });+ await ws.create({ agentId, title: 'agent only' });+ await ws.create({ projectId: otherProjectId, title: 'other project' });+ const projectBoard = await ws.create({ projectId, sortOrder: 1, title: 'project' });+ const agentInProject = await ws.create({+ agentId,+ projectId,+ sortOrder: 0,+ title: 'agent-in-project',+ });+ const privateBoard = await ws.create({+ projectId,+ sortOrder: 2,+ title: 'private',+ visibility: 'private',+ });+ await ws.trash((await ws.create({ projectId, title: 'trashed' })).id);++ expect((await ws.listByProject(projectId)).map((d) => d.id)).toEqual([+ agentInProject.id,+ projectBoard.id,+ privateBoard.id,+ ]);+ // workspace members only see the public ones+ expect((await outsider.listByProject(projectId)).map((d) => d.id)).not.toContain(+ privateBoard.id,+ );+ });++ it('cascades dashboards when their project or agent is deleted', async () => {+ const projectId = await seedProject('dash-p6', userId, null);+ const agentId = await seedAgent('dash-a6', userId, null);+ const model = new DashboardModel(serverDB, userId);+ const p = await model.create({ projectId, title: 'p' });+ const a = await model.create({ agentId, title: 'a' });++ await serverDB.delete(projects).where(eq(projects.id, projectId));+ await serverDB.delete(agents).where(eq(agents.id, agentId));++ const rows = await serverDB.select().from(dashboards);+ expect(rows.map((r) => r.id)).not.toContain(p.id);+ expect(rows.map((r) => r.id)).not.toContain(a.id);+ });+ });++ describe('recycle bin', () => {+ it('purge deletes only a board that is still trashed', async () => {+ const model = new DashboardModel(serverDB, userId, workspaceId);+ const dashboard = await model.create({ title: 'Ops' });+ await model.trash(dashboard.id);+ // a restore commits before the purge reaches the row+ await model.restore(dashboard.id);++ expect(await model.purge(dashboard.id)).toBeUndefined();+ expect(await model.findById(dashboard.id)).toMatchObject({ id: dashboard.id });++ await model.trash(dashboard.id);+ expect(await model.purge(dashboard.id)).toMatchObject({ id: dashboard.id });+ expect(+ await serverDB.select().from(trashItems).where(eq(trashItems.resourceId, dashboard.id)),+ ).toHaveLength(0);+ });++ it('trash hides the board and registers it; restore brings it back', async () => {+ const model = new DashboardModel(serverDB, userId, workspaceId);+ const dashboard = await model.create({ title: 'Ops' });++ expect(+ await new DashboardModel(serverDB, otherUserId, workspaceId).trash(dashboard.id),+ ).toBeUndefined();++ const trashed = await model.trash(dashboard.id);+ expect(trashed).toMatchObject({ isDeleted: true });+ expect(trashed?.deletedAt).toBeInstanceOf(Date);+ expect(await model.findById(dashboard.id)).toBeUndefined();+ expect(await model.list()).toEqual([]);++ const [entry] = await serverDB+ .select()+ .from(trashItems)+ .where(eq(trashItems.resourceId, dashboard.id));+ expect(entry).toMatchObject({+ deletedByUserId: userId,+ resourceType: 'dashboard',+ rootId: null,+ title: 'Ops',+ workspaceId,+ });+ expect(entry.expiresAt.getTime()).toBeGreaterThan(entry.deletedAt.getTime());++ // trashing twice is a no-op+ expect(await model.trash(dashboard.id)).toBeUndefined();++ const restored = await model.restore(dashboard.id);+ expect(restored).toMatchObject({ deletedAt: null, isDeleted: null });+ expect(await model.findById(dashboard.id)).toMatchObject({ id: dashboard.id });+ expect(+ await serverDB.select().from(trashItems).where(eq(trashItems.resourceId, dashboard.id)),+ ).toHaveLength(0);+ expect(await model.restore(dashboard.id)).toBeUndefined();+ });++ it('hard delete removes a trashed board and its registry entry', async () => {+ const model = new DashboardModel(serverDB, userId);+ const dashboard = await model.create({ title: 'tmp' });+ await model.trash(dashboard.id);++ expect(await new DashboardModel(serverDB, otherUserId).delete(dashboard.id)).toBeUndefined();+ expect(await model.delete(dashboard.id)).toMatchObject({ id: dashboard.id });+ expect(+ await serverDB.select().from(dashboards).where(eq(dashboards.id, dashboard.id)),+ ).toHaveLength(0);+ expect(await serverDB.select().from(trashItems)).toHaveLength(0);+ expect(await model.delete(dashboard.id)).toBeUndefined();+ });+ });++ describe('items', () => {+ it('adds widgets with increasing sort order, upserts placement, lists and removes', async () => {+ const model = new DashboardModel(serverDB, userId);+ const widgets = new WidgetModel(serverDB, userId);+ const dashboard = await model.create({ title: 'Home' });+ const w1 = await widgets.create({ title: 'PRs' });+ const w2 = await widgets.create({ title: 'Stars' });++ const i1 = await model.addItem(dashboard.id, w1.id, { layout: { h: 2, w: 4, x: 0, y: 0 } });+ const i2 = await model.addItem(dashboard.id, w2.id);+ expect(i1).toMatchObject({ sortOrder: 0, userId, workspaceId: null });+ expect(i2).toMatchObject({ layout: null, sortOrder: 1 });++ // re-adding updates the existing placement instead of duplicating+ const again = await model.addItem(dashboard.id, w1.id, {+ layout: { h: 3, w: 6, x: 0, y: 0 },+ });+ expect(again?.id).toBe(i1?.id);+ expect(again?.layout).toEqual({ h: 3, w: 6, x: 0, y: 0 });++ const listed = await model.listItems(dashboard.id);+ expect(listed.map((r) => r.widget.title)).toEqual(['PRs', 'Stars']);++ expect(+ await model.updateItemLayouts(dashboard.id, [+ { id: i1!.id, sortOrder: 5 },+ { id: i2!.id, layout: { h: 1, w: 2, x: 4, y: 0 }, sortOrder: 0 },+ { id: '00000000-0000-0000-0000-000000000000', sortOrder: 9 },+ ]),+ ).toBe(2);+ expect((await model.listItems(dashboard.id)).map((r) => r.widget.title)).toEqual([+ 'Stars',+ 'PRs',+ ]);+ expect(await model.updateItemLayouts(dashboard.id, [])).toBe(0);++ // trashed widgets drop out of the board without losing the placement+ await widgets.trash(w2.id);+ expect((await model.listItems(dashboard.id)).map((r) => r.widget.id)).toEqual([w1.id]);+ await widgets.restore(w2.id);++ expect(await model.removeItems(dashboard.id, [i2!.id])).toBe(1);+ expect(await model.removeItems(dashboard.id, [])).toBe(0);+ expect((await model.listItems(dashboard.id)).map((r) => r.widget.id)).toEqual([w1.id]);+ });++ 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);+ const dashboard = await model.create({ title: 'Home' });+ const myWidget = await new WidgetModel(serverDB, userId).create({ title: 'mine' });+ const theirWidget = await new WidgetModel(serverDB, otherUserId).create({+ title: 'theirs',+ });++ expect(await other.addItem(dashboard.id, myWidget.id)).toBeUndefined();+ expect(await model.addItem(dashboard.id, theirWidget.id)).toBeUndefined();+ expect(await other.listItems(dashboard.id)).toEqual([]);++ const item = await model.addItem(dashboard.id, myWidget.id);+ expect(await other.updateItemLayouts(dashboard.id, [{ id: item!.id, sortOrder: 3 }])).toBe(0);+ expect(await other.removeItems(dashboard.id, [item!.id])).toBe(0);+ expect(+ await serverDB+ .select()+ .from(dashboardItems)+ .where(and(eq(dashboardItems.id, item!.id), eq(dashboardItems.sortOrder, 0))),+ ).toHaveLength(1);+ });++ 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' });+ const first = await model.create({ sortOrder: 0, title: 'First' });+ const second = await model.create({ sortOrder: 1, title: 'Second' });+ const trashed = await model.create({ sortOrder: 2, title: 'Trashed' });+ await model.create({ title: 'Unrelated' });+ for (const board of [second, first, trashed]) await model.addItem(board.id, widget.id);+ await model.trash(trashed.id);++ expect(await model.listByWidget(widget.id)).toEqual([+ { id: first.id, title: 'First' },+ { id: second.id, title: 'Second' },+ ]);+ // another user sees none of this user's boards+ expect(await new DashboardModel(serverDB, otherUserId).listByWidget(widget.id)).toEqual([]);+ });++ it('removes placements when the board is hard deleted', async () => {+ const model = new DashboardModel(serverDB, userId);+ const dashboard = await model.create({ title: 'Home' });+ const widget = await new WidgetModel(serverDB, userId).create({ title: 'w' });+ await model.addItem(dashboard.id, widget.id);++ await model.delete(dashboard.id);+ expect(await serverDB.select().from(dashboardItems)).toHaveLength(0);+ });+ });+ describe('parent visibility', () => {+ it('forces private boards under a private project and refuses to widen them', async () => {+ const privateProject = await seedProject('dash-priv', userId, workspaceId, 'private');+ const owner = new DashboardModel(serverDB, userId, workspaceId);++ const board = await owner.create({+ projectId: privateProject,+ title: 'secret',+ visibility: 'public',+ });+ expect(board.visibility).toBe('private');+ expect((await owner.update(board.id, { visibility: 'public' }))?.visibility).toBe('private');+ });++ it('hides a public board once its project or agent turns private', async () => {+ const projectId = await seedProject('dash-flip', userId, workspaceId);+ const agentId = await seedAgent('dash-flip-agent', userId, workspaceId);+ const owner = new DashboardModel(serverDB, userId, workspaceId);+ const member = new DashboardModel(serverDB, otherUserId, workspaceId);+ const inProject = await owner.create({ projectId, title: 'p' });+ const inAgent = await owner.create({ agentId, title: 'a' });+ const widget = await new WidgetModel(serverDB, userId, workspaceId).create({ title: 'w' });+ await owner.addItem(inProject.id, widget.id);+ expect((await member.findById(inProject.id))?.id).toBe(inProject.id);++ await serverDB+ .update(projects)+ .set({ visibility: 'private' })+ .where(eq(projects.id, projectId));+ await serverDB.update(agents).set({ visibility: 'private' }).where(eq(agents.id, agentId));++ expect(await member.findById(inProject.id)).toBeUndefined();+ expect(await member.findById(inAgent.id)).toBeUndefined();+ expect(await member.list({ projectId })).toEqual([]);+ expect(await member.listByProject(projectId)).toEqual([]);+ expect(await member.listItems(inProject.id)).toEqual([]);+ expect(await member.listByWidget(widget.id)).toEqual([]);+ // the parents' creator still sees them+ expect((await owner.listByProject(projectId)).map((d) => d.id)).toEqual([inProject.id]);+ });++ it('hides boards and widget items while their project or agent is trashed', async () => {+ const personalProject = await seedProject('dash-bin', userId, null);+ const personalAgent = await seedAgent('dash-bin-agent', userId, null);+ const wsProject = await seedProject('dash-bin-ws', userId, workspaceId);+ const setTrashed = async (trashed: boolean) => {+ const stamp = trashed+ ? { deletedAt: new Date(), isDeleted: true }+ : { deletedAt: null, isDeleted: null };+ await serverDB.update(projects).set(stamp).where(eq(projects.id, personalProject));+ await serverDB.update(projects).set(stamp).where(eq(projects.id, wsProject));+ await serverDB.update(agents).set(stamp).where(eq(agents.id, personalAgent));+ };++ // personal mode+ const personal = new DashboardModel(serverDB, userId);+ const inProject = await personal.create({ projectId: personalProject, title: 'p' });+ const inAgent = await personal.create({ agentId: personalAgent, title: 'a' });+ const home = await personal.create({ title: 'home' });+ const widgetModel = new WidgetModel(serverDB, userId);+ const projectWidget = await widgetModel.create({ projectId: personalProject, title: 'pw' });+ const looseWidget = await widgetModel.create({ title: 'loose' });+ await personal.addItem(home.id, projectWidget.id);+ await personal.addItem(home.id, looseWidget.id);+ await personal.addItem(inProject.id, looseWidget.id);++ // workspace mode, public project read by a teammate+ const owner = new DashboardModel(serverDB, userId, workspaceId);+ const member = new DashboardModel(serverDB, otherUserId, workspaceId);+ const wsBoard = await owner.create({ projectId: wsProject, title: 'team' });++ await setTrashed(true);++ expect(await personal.findById(inProject.id)).toBeUndefined();+ expect(await personal.findById(inAgent.id)).toBeUndefined();+ expect(await personal.list({ projectId: personalProject })).toEqual([]);+ expect(await personal.list({ agentId: personalAgent })).toEqual([]);+ expect(await personal.listByProject(personalProject)).toEqual([]);+ expect(await personal.listItems(inProject.id)).toEqual([]);+ // a live board drops the widget of the trashed project+ expect((await personal.listItems(home.id)).map((r) => r.widget.title)).toEqual(['loose']);+ expect((await personal.listByWidget(looseWidget.id)).map((d) => d.id)).toEqual([home.id]);+ for (const reader of [owner, member]) {+ expect(await reader.findById(wsBoard.id)).toBeUndefined();+ expect(await reader.listByProject(wsProject)).toEqual([]);+ }++ // restoring the parents brings everything back+ await setTrashed(false);++ expect((await personal.findById(inProject.id))?.id).toBe(inProject.id);+ expect((await personal.findById(inAgent.id))?.id).toBe(inAgent.id);+ expect((await personal.listItems(home.id)).map((r) => r.widget.title)).toEqual([+ 'pw',+ 'loose',+ ]);+ expect((await member.listByProject(wsProject)).map((d) => d.id)).toEqual([wsBoard.id]);+ });++ it('drops widgets the reader cannot see from a public board', async () => {+ const projectId = await seedProject('dash-items', userId, workspaceId);+ const owner = new DashboardModel(serverDB, userId, workspaceId);+ const member = new DashboardModel(serverDB, otherUserId, workspaceId);+ const widgetModel = new WidgetModel(serverDB, userId, workspaceId);+ const board = await owner.create({ title: 'team' });++ const open = await widgetModel.create({ title: 'open' });+ const mine = await widgetModel.create({ title: 'mine', visibility: 'private' });+ const inProject = await widgetModel.create({ projectId, title: 'project' });+ for (const w of [open, mine, inProject]) await owner.addItem(board.id, w.id);+ await serverDB+ .update(projects)+ .set({ visibility: 'private' })+ .where(eq(projects.id, projectId));++ expect((await owner.listItems(board.id)).map((r) => r.widget.title)).toEqual([+ 'open',+ 'mine',+ 'project',+ ]);+ expect((await member.listItems(board.id)).map((r) => r.widget.title)).toEqual(['open']);+ });+ });+});diff --git a/packages/database/src/models/__tests__/metric.test.ts b/packages/database/src/models/__tests__/metric.test.tsindex ca90cdecf27..e27b37df0ed 100644--- a/packages/database/src/models/__tests__/metric.test.ts+++ b/packages/database/src/models/__tests__/metric.test.ts@@ -87,6 +87,57 @@ describe('MetricModel', () => {});describe('points', () => {+ it('appends a batch through the owned series only', async () => {+ const series = (await seed())!;+ const batch = [1, 2, 3].map((value) => ({+ actorType: 'system' as const,+ observedAt: new Date(`2026-09-0${value}T00:00:00Z`),+ sourceType: 'probe' as const,+ value,+ }));++ expect(await model.addPoints(series.id, batch)).toBe(3);+ expect(await model.addPoints(series.id, [])).toBe(0);+ expect(await otherModel.addPoints(series.id, batch)).toBe(0);+ expect((await model.latestPoint(series.id))!.value).toBe(3);+ });++ it('appends only newer points, once, when two writers report the same window', async () => {+ const series = (await seed())!;+ const point = (day: number) => ({+ actorType: 'system' as const,+ observedAt: new Date(`2026-09-0${day}T00:00:00Z`),+ sourceType: 'probe' as const,+ value: day,+ });+ const window = [point(1), point(2)];++ const written = await Promise.all([+ model.appendNewerPoints(series.id, window),+ model.appendNewerPoints(series.id, window),+ ]);+ expect(written.sort()).toEqual([0, 2]);++ // a sliding window: only the new tail is appended+ expect(await model.appendNewerPoints(series.id, [point(2), point(3)])).toBe(1);+ expect(await model.appendNewerPoints(series.id, [])).toBe(0);+ expect(await otherModel.appendNewerPoints(series.id, [point(4)])).toBe(0);+ expect((await model.recentPoints(series.id, 10)).map((p) => p.value)).toEqual([1, 2, 3]);+ });++ it('writes a timestamp repeated inside one batch once, keeping its last value', async () => {+ const series = (await seed())!;+ const at = (day: number, value: number) => ({+ actorType: 'system' as const,+ observedAt: new Date(`2026-09-0${day}T00:00:00Z`),+ sourceType: 'probe' as const,+ value,+ });++ expect(await model.appendNewerPoints(series.id, [at(1, 1), at(2, 5), at(2, 6)])).toBe(2);+ expect((await model.recentPoints(series.id, 10)).map((p) => p.value)).toEqual([1, 6]);+ });+it('appends through the owned series and refuses foreign or missing series', async () => {const series = (await seed())!;diff --git a/packages/database/src/models/__tests__/trash.test.ts b/packages/database/src/models/__tests__/trash.test.tsindex 1671db068f7..79c8bc600e5 100644--- a/packages/database/src/models/__tests__/trash.test.ts+++ b/packages/database/src/models/__tests__/trash.test.ts@@ -3,7 +3,7 @@ import { eq } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { getTestDB } from '../../core/getTestDB';-import { topics, trashItems, users, workspaces } from '../../schemas';+import { topics, trashItems, users, widgets, workspaces } from '../../schemas';import type { LobeChatDatabase } from '../../type';import { TrashModel } from '../trash';@@ -234,5 +234,26 @@ describe('TrashModel', () => {const left = await serverDB.select().from(trashItems).where(eq(trashItems.userId, userId));expect(left.map((r) => r.resourceId)).toEqual(['tpc_stamped']);});++ it('pruneOrphans matches uuid-keyed widget roots against their text registry ids', async () => {+ const deletedAt = at('2026-08-01T00:00:00Z');+ const [stamped, live] = await serverDB+ .insert(widgets)+ .values([+ { deletedAt, isDeleted: true, title: 'still trashed', userId },+ { title: 'restored elsewhere', userId },+ ])+ .returning();+ await model.register({+ deletedAt,+ root: { resourceId: stamped.id, resourceType: 'widget' },+ });+ await model.register({ deletedAt, root: { resourceId: live.id, resourceType: 'widget' } });++ const pruned = await TrashModel.pruneOrphans(serverDB);+ expect(pruned).toBe(1);+ const left = await serverDB.select().from(trashItems).where(eq(trashItems.userId, userId));+ expect(left.map((r) => r.resourceId)).toEqual([stamped.id]);+ });});});diff --git a/packages/database/src/models/__tests__/widget.test.ts b/packages/database/src/models/__tests__/widget.test.tsnew file mode 100644index 00000000000..99836666118--- /dev/null+++ b/packages/database/src/models/__tests__/widget.test.ts@@ -0,0 +1,1075 @@+// @vitest-environment node+import { eq, inArray, sql } from 'drizzle-orm';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import { getTestDB } from '../../core/getTestDB';+import {+ agents,+ metrics,+ projects,+ trashItems,+ users,+ widgetRuns,+ widgets,+ widgetVersions,+ workspaces,+} from '../../schemas';+import type { LobeChatDatabase } from '../../type';+import { ScopeLevelError } from '../../utils/scopeLevel';+import type { CreateWidgetVersionInput } from '../widget';+import { computeWidgetContentHash, WidgetModel } from '../widget';++const serverDB: LobeChatDatabase = await getTestDB();++const userId = 'widget-user';+const otherUserId = 'widget-other-user';+const workspaceId = 'widget-ws';+const MISSING_UUID = '00000000-0000-0000-0000-000000000000';++const script = (n: number): CreateWidgetVersionInput => ({+ manifest: { network: { allow: ['api.github.com'] }, title: `v${n}` },+ outputType: 'stat',+ runtime: 'node',+ script: `console.log(JSON.stringify({ type: 'stat', value: ${n} }))`,+ sourceType: 'agent',+ view: { size: 'sm' },+});++let projectSeq = 0;+const seedProject = async (+ id: string,+ opts: { owner?: string; visibility?: 'private' | 'public'; workspaceId?: string | null } = {},+) => {+ const owner = opts.owner ?? userId;+ const ws = opts.workspaceId === undefined ? workspaceId : opts.workspaceId;+ await serverDB.insert(agents).values({ id: `${id}-coord`, userId: owner, workspaceId: ws });+ await serverDB.insert(projects).values({+ coordinatorAgentId: `${id}-coord`,+ id,+ // unique per (workspace, identifier)+ identifier: `WGT${(projectSeq += 1)}`,+ name: id,+ userId: owner,+ visibility: opts.visibility ?? 'public',+ workspaceId: ws,+ });+};++beforeEach(async () => {+ await serverDB.delete(trashItems);+ await serverDB.delete(users);+ await serverDB.insert(users).values([{ id: userId }, { id: otherUserId }]);+ await serverDB+ .insert(workspaces)+ .values({ id: workspaceId, name: 'WS', primaryOwnerId: userId, slug: 'widget-ws' });+});++afterEach(async () => {+ await serverDB.delete(trashItems);+ await serverDB.delete(workspaces);+ await serverDB.delete(users);+});++describe('WidgetModel', () => {+ const model = new WidgetModel(serverDB, userId);+ const other = new WidgetModel(serverDB, otherUserId);+ const ws = new WidgetModel(serverDB, userId, workspaceId);+ const member = new WidgetModel(serverDB, otherUserId, workspaceId);++ describe('widgets', () => {+ it('creates, reads, updates and isolates widgets by owner', async () => {+ const widget = await model.create({+ schedulePattern: '0 * * * *',+ scheduleTimezone: 'Asia/Shanghai',+ title: 'Open PRs',+ });+ expect(widget).toMatchObject({+ agentId: null,+ consecutiveFailures: 0,+ draftVersionId: null,+ projectId: null,+ publishedVersionId: null,+ schedulePattern: '0 * * * *',+ userId,+ visibility: 'public',+ workspaceId: null,+ });++ expect(await other.findById(widget.id)).toBeUndefined();+ expect(await other.update(widget.id, { title: 'x' })).toBeUndefined();+ expect(await model.findById('not-a-uuid')).toBeUndefined();++ const [metric] = await serverDB+ .insert(metrics)+ .values({ key: 'prs', subjectId: widget.id, subjectType: 'widget', userId })+ .returning();+ const next = new Date('2030-01-01T00:00:00Z');+ const updated = await model.update(widget.id, {+ metricId: metric.id,+ nextRunAt: next,+ title: 'PRs',+ });+ expect(updated).toMatchObject({ metricId: metric.id, nextRunAt: next, title: 'PRs' });++ // metric deletion detaches the trend without touching the widget+ await serverDB.delete(metrics).where(eq(metrics.id, metric.id));+ expect((await model.findById(widget.id))?.metricId).toBeNull();+ });++ it('lists each direct level: personal, workspace, project, agent, project + agent', async () => {+ await seedProject('wgt-proj');+ await serverDB.insert(agents).values({ id: 'wgt-agent', userId, workspaceId });++ const personal = await model.create({ title: 'personal' });+ const direct = await ws.create({ title: 'workspace' });+ const byProject = await ws.create({ projectId: 'wgt-proj', title: 'project' });+ const byAgent = await ws.create({ agentId: 'wgt-agent', title: 'agent' });+ const both = await ws.create({ agentId: 'wgt-agent', projectId: 'wgt-proj', title: 'both' });+ expect(both).toMatchObject({ agentId: 'wgt-agent', projectId: 'wgt-proj', workspaceId });++ const ids = (rows: { id: string }[]) => rows.map((w) => w.id);+ expect(ids(await model.list())).toEqual([personal.id]);+ expect(ids(await ws.list())).toEqual([direct.id]);+ expect(ids(await ws.list({ projectId: 'wgt-proj' }))).toEqual([byProject.id]);+ expect(ids(await ws.list({ agentId: 'wgt-agent' }))).toEqual([byAgent.id]);+ expect(ids(await ws.list({ agentId: 'wgt-agent', projectId: 'wgt-proj' }))).toEqual([+ both.id,+ ]);++ // agent deletion cascades its widgets+ await serverDB.delete(agents).where(eq(agents.id, 'wgt-agent'));+ expect(await ws.findById(byAgent.id)).toBeUndefined();+ expect(await ws.findById(both.id)).toBeUndefined();+ });++ it('rejects parents from another workspace, missing parents and invisible parents', async () => {+ await serverDB.insert(agents).values({ id: 'wgt-agent-personal', userId, workspaceId: null });+ await seedProject('wgt-proj-personal', { workspaceId: null });+ await seedProject('wgt-proj-private-other', { owner: otherUserId, visibility: 'private' });++ await expect(ws.create({ agentId: 'wgt-agent-personal', title: 'x' })).rejects.toMatchObject({+ code: 'SCOPE_MISMATCH',+ });+ await expect(+ ws.create({ projectId: 'wgt-proj-personal', title: 'x' }),+ ).rejects.toBeInstanceOf(ScopeLevelError);+ await expect(ws.create({ projectId: 'wgt-proj-personal', title: 'x' })).rejects.toMatchObject(+ { code: 'SCOPE_MISMATCH' },+ );+ await expect(ws.create({ agentId: 'nope', title: 'x' })).rejects.toMatchObject({+ code: 'AGENT_NOT_FOUND',+ });+ await expect(ws.create({ projectId: 'nope', title: 'x' })).rejects.toMatchObject({+ code: 'PROJECT_NOT_FOUND',+ });+ // a teammate's private project is not visible, so it cannot be a parent+ await expect(+ ws.create({ projectId: 'wgt-proj-private-other', title: 'x' }),+ ).rejects.toMatchObject({ code: 'PROJECT_NOT_FOUND' });+ expect(await serverDB.select().from(widgets)).toHaveLength(0);+ });++ it('forces private visibility under a private project or agent', async () => {+ await seedProject('wgt-proj-private', { visibility: 'private' });+ await seedProject('wgt-proj-public');+ await serverDB+ .insert(agents)+ .values({ id: 'wgt-agent-private', userId, visibility: 'private', workspaceId });++ const inPrivateProject = await ws.create({+ projectId: 'wgt-proj-private',+ title: 'p',+ visibility: 'public',+ });+ const inPrivateAgent = await ws.create({+ agentId: 'wgt-agent-private',+ projectId: 'wgt-proj-public',+ title: 'a',+ });+ const inPublicProject = await ws.create({ projectId: 'wgt-proj-public', title: 'pub' });+ expect(inPrivateProject.visibility).toBe('private');+ expect(inPrivateAgent.visibility).toBe('private');+ expect(inPublicProject.visibility).toBe('public');++ // cannot be widened later either+ expect((await ws.update(inPrivateProject.id, { visibility: 'public' }))?.visibility).toBe(+ 'private',+ );+ expect((await ws.update(inPublicProject.id, { visibility: 'private' }))?.visibility).toBe(+ 'private',+ );+ expect((await ws.update(inPublicProject.id, { visibility: 'public' }))?.visibility).toBe(+ 'public',+ );++ // teammates never see them+ expect(await member.findById(inPrivateProject.id)).toBeUndefined();+ expect(await member.findById(inPrivateAgent.id)).toBeUndefined();+ expect((await member.findById(inPublicProject.id))?.id).toBe(inPublicProject.id);+ });++ it('honors the current visibility of the parent project / agent on every read', async () => {+ // Parents start public, so the widgets are created public …+ await seedProject('wgt-proj-flip');+ await serverDB.insert(agents).values({ id: 'wgt-agent-flip', userId, workspaceId });+ const inProject = await ws.create({ projectId: 'wgt-proj-flip', title: 'p' });+ const inAgent = await ws.create({ agentId: 'wgt-agent-flip', title: 'a' });+ expect([inProject.visibility, inAgent.visibility]).toEqual(['public', 'public']);++ const v1 = await ws.createVersion(inProject.id, script(1));+ await ws.publishVersion(inProject.id, v1!.id);+ const run = await ws.startRun(inProject.id, { trigger: 'manual' });+ await ws.finishRun(run!.id, { status: 'succeeded' });+ expect((await member.findById(inProject.id))?.id).toBe(inProject.id);++ // … then the parents turn private: the widget rows still say public.+ await serverDB+ .update(projects)+ .set({ visibility: 'private' })+ .where(eq(projects.id, 'wgt-proj-flip'));+ await serverDB+ .update(agents)+ .set({ visibility: 'private' })+ .where(eq(agents.id, 'wgt-agent-flip'));++ expect(await member.findById(inProject.id)).toBeUndefined();+ expect(await member.findById(inAgent.id)).toBeUndefined();+ expect(await member.list({ projectId: 'wgt-proj-flip' })).toEqual([]);+ expect(await member.list({ agentId: 'wgt-agent-flip' })).toEqual([]);+ expect(await member.listByProject('wgt-proj-flip')).toEqual([]);+ expect(await member.listVersions(inProject.id)).toEqual([]);+ expect(await member.findVersion(inProject.id, v1!.id)).toBeUndefined();+ expect(await member.listRuns(inProject.id)).toEqual([]);+ expect(await member.findRun(inProject.id, run!.id)).toBeUndefined();+ expect(await member.startRun(inProject.id, { trigger: 'manual' })).toBeUndefined();+ expect(await member.hasSucceededRunForContentHash(inProject.id, v1!.contentHash)).toBe(false);++ // the parents' creator still sees everything+ expect((await ws.findById(inProject.id))?.id).toBe(inProject.id);+ expect((await ws.listByProject('wgt-proj-flip')).map((w) => w.id)).toEqual([inProject.id]);+ expect(await ws.listRuns(inProject.id)).toHaveLength(1);+ });++ it('hides widgets while their project or agent is trashed, in personal and workspace mode', async () => {+ const setTrashed = async (trashed: boolean) => {+ const stamp = trashed+ ? { deletedAt: new Date(), isDeleted: true }+ : { deletedAt: null, isDeleted: null };+ await serverDB.update(projects).set(stamp).where(eq(projects.id, 'wgt-proj-bin'));+ await serverDB.update(agents).set(stamp).where(eq(agents.id, 'wgt-agent-bin'));+ await serverDB.update(projects).set(stamp).where(eq(projects.id, 'wgt-proj-bin-ws'));+ await serverDB.update(agents).set(stamp).where(eq(agents.id, 'wgt-agent-bin-ws'));+ };++ // personal mode: the caller owns every parent+ await seedProject('wgt-proj-bin', { workspaceId: null });+ await serverDB.insert(agents).values({ id: 'wgt-agent-bin', userId, workspaceId: null });+ const inProject = await model.create({ projectId: 'wgt-proj-bin', title: 'p' });+ const inAgent = await model.create({ agentId: 'wgt-agent-bin', title: 'a' });+ const v1 = await model.createVersion(inProject.id, script(1));+ await model.publishVersion(inProject.id, v1!.id);+ const run = await model.startRun(inProject.id, { trigger: 'manual' });++ // workspace mode: public parents, read by a teammate+ await seedProject('wgt-proj-bin-ws');+ await serverDB.insert(agents).values({ id: 'wgt-agent-bin-ws', userId, workspaceId });+ const wsInProject = await ws.create({ projectId: 'wgt-proj-bin-ws', title: 'wp' });+ const wsInAgent = await ws.create({ agentId: 'wgt-agent-bin-ws', title: 'wa' });++ await setTrashed(true);++ expect(await model.findById(inProject.id)).toBeUndefined();+ expect(await model.findById(inAgent.id)).toBeUndefined();+ expect(await model.list({ projectId: 'wgt-proj-bin' })).toEqual([]);+ expect(await model.list({ agentId: 'wgt-agent-bin' })).toEqual([]);+ expect(await model.listByProject('wgt-proj-bin')).toEqual([]);+ expect(await model.listVersions(inProject.id)).toEqual([]);+ expect(await model.findVersion(inProject.id, v1!.id)).toBeUndefined();+ expect(await model.listRuns(inProject.id)).toEqual([]);+ expect(await model.findRun(inProject.id, run!.id)).toBeUndefined();+ expect(await model.startRun(inProject.id, { trigger: 'manual' })).toBeUndefined();+ for (const reader of [ws, member]) {+ expect(await reader.findById(wsInProject.id)).toBeUndefined();+ expect(await reader.findById(wsInAgent.id)).toBeUndefined();+ expect(await reader.listByProject('wgt-proj-bin-ws')).toEqual([]);+ expect(await reader.list({ agentId: 'wgt-agent-bin-ws' })).toEqual([]);+ }++ // restoring the parents brings the widgets back+ await setTrashed(false);++ expect((await model.findById(inProject.id))?.id).toBe(inProject.id);+ expect((await model.findById(inAgent.id))?.id).toBe(inAgent.id);+ expect((await model.listByProject('wgt-proj-bin')).map((w) => w.id)).toEqual([inProject.id]);+ expect(await model.listRuns(inProject.id)).toHaveLength(1);+ expect((await member.findById(wsInProject.id))?.id).toBe(wsInProject.id);+ expect((await member.list({ agentId: 'wgt-agent-bin-ws' })).map((w) => w.id)).toEqual([+ wsInAgent.id,+ ]);+ });++ it('hides a widget from its own creator once a teammate makes the parent private', async () => {+ await seedProject('wgt-proj-teammate', { owner: otherUserId });+ const widget = await ws.create({ projectId: 'wgt-proj-teammate', title: 'mine' });+ expect((await ws.findById(widget.id))?.id).toBe(widget.id);++ await serverDB+ .update(projects)+ .set({ visibility: 'private' })+ .where(eq(projects.id, 'wgt-proj-teammate'));++ expect(await ws.findById(widget.id)).toBeUndefined();+ expect(await ws.update(widget.id, { title: 'x' })).toBeUndefined();+ expect((await member.findById(widget.id))?.id).toBe(widget.id);+ });++ it('lists every widget of a project, with or without an agent', async () => {+ await seedProject('wgt-proj-all');+ await serverDB.insert(agents).values({ id: 'wgt-agent-all', userId, workspaceId });+ const direct = await ws.create({ projectId: 'wgt-proj-all', title: 'direct' });+ const viaAgent = await ws.create({+ agentId: 'wgt-agent-all',+ projectId: 'wgt-proj-all',+ title: 'agent',+ });+ await ws.create({ title: 'elsewhere' });++ expect((await ws.listByProject('wgt-proj-all')).map((w) => w.id).sort()).toEqual(+ [direct.id, viaAgent.id].sort(),+ );+ });++ it('applies visibility in workspace mode and limits writes to the creator', async () => {+ const pub = await ws.create({ title: 'pub' });+ const priv = await ws.create({ title: 'priv', visibility: 'private' });++ expect((await member.list()).map((w) => w.id)).toEqual([pub.id]);+ expect((await ws.list()).map((w) => w.id).sort()).toEqual([pub.id, priv.id].sort());+ expect(await member.findById(priv.id)).toBeUndefined();++ // readable is not manageable+ expect(await member.update(pub.id, { title: 'hijack' })).toBeUndefined();+ expect(await member.trash(pub.id)).toBeUndefined();+ expect(await member.createVersion(pub.id, script(1))).toBeUndefined();+ // personal mode does not see workspace rows+ expect(await model.findById(pub.id)).toBeUndefined();+ });++ it('purge deletes only a widget that is still trashed', async () => {+ const widget = await model.create({ title: 'w' });+ await model.trash(widget.id);+ // a restore commits before the purge reaches the row+ await model.restore(widget.id);++ expect(await model.purge(widget.id)).toBeUndefined();+ expect(await model.findById(widget.id)).toMatchObject({ id: widget.id });++ await model.trash(widget.id);+ expect(await other.purge(widget.id)).toBeUndefined();+ expect(await model.purge(widget.id)).toMatchObject({ id: widget.id });+ expect(await serverDB.select().from(trashItems)).toHaveLength(0);+ });++ it('trash / restore / delete go through the recycle bin', async () => {+ const widget = await model.create({ title: 'w' });+ await model.publishVersion(widget.id, (await model.createVersion(widget.id, script(1)))!.id);++ expect(await other.trash(widget.id)).toBeUndefined();+ expect(await model.trash(widget.id)).toMatchObject({ isDeleted: true });+ expect(await model.findById(widget.id)).toBeUndefined();+ expect(await model.list()).toEqual([]);+ expect(await serverDB.select().from(trashItems)).toEqual([+ expect.objectContaining({+ resourceId: widget.id,+ resourceType: 'widget',+ rootId: null,+ title: 'w',+ userId,+ }),+ ]);++ expect(await other.restore(widget.id)).toBeUndefined();+ expect(await model.restore(widget.id)).toMatchObject({ deletedAt: null, isDeleted: null });+ expect(await serverDB.select().from(trashItems)).toHaveLength(0);+ expect(await model.restore(widget.id)).toBeUndefined();++ await model.trash(widget.id);+ expect(await other.delete(widget.id)).toBeUndefined();+ expect(await model.delete(widget.id)).toMatchObject({ id: widget.id });+ expect(await serverDB.select().from(widgetVersions)).toHaveLength(0);+ expect(await serverDB.select().from(trashItems)).toHaveLength(0);+ expect(await model.delete(widget.id)).toBeUndefined();+ expect(await model.trash('bad')).toBeUndefined();+ });+ });++ describe('versions', () => {+ it('creates numbered drafts, dedupes identical content, and chains parents', async () => {+ const widget = await model.create({ title: 'w' });++ const v1 = await model.createVersion(widget.id, script(1));+ expect(v1).toMatchObject({+ contentHash: computeWidgetContentHash(script(1)),+ parentVersionId: null,+ status: 'draft',+ userId,+ version: 1,+ });+ expect((await model.findById(widget.id))?.draftVersionId).toBe(v1!.id);++ // identical content returns the current draft+ expect((await model.createVersion(widget.id, script(1)))?.id).toBe(v1!.id);++ const v2 = await model.createVersion(widget.id, {+ ...script(2),+ changeNote: 'bump',+ sourceOperationId: 'op_1',+ sourceType: 'user',+ });+ expect(v2).toMatchObject({ parentVersionId: v1!.id, sourceType: 'user', version: 2 });++ expect((await model.listVersions(widget.id)).map((v) => v.version)).toEqual([2, 1]);+ expect(await model.findVersion(widget.id, v1!.id)).toMatchObject({ id: v1!.id });+ expect(await other.listVersions(widget.id)).toEqual([]);+ expect(await other.findVersion(widget.id, v1!.id)).toBeUndefined();+ expect(await other.createVersion(widget.id, script(3))).toBeUndefined();+ });++ it('hash is key-order independent and sensitive to script changes', () => {+ const a = computeWidgetContentHash({+ manifest: { network: { allow: ['a'] }, timeoutMs: 1000 },+ outputType: 'stat',+ runtime: 'node',+ script: 'x',+ });+ const b = computeWidgetContentHash({+ manifest: { timeoutMs: 1000, network: { allow: ['a'] } },+ outputType: 'stat',+ runtime: 'node',+ script: 'x',+ });+ expect(a).toBe(b);+ expect(a).not.toBe(+ computeWidgetContentHash({ outputType: 'stat', runtime: 'node', script: 'y' }),+ );+ });++ it('publishes a version, archives the previous one and sets the schedule', async () => {+ const widget = await model.create({ schedulePattern: '*/5 * * * *', title: 'w' });+ const v1 = await model.createVersion(widget.id, script(1));+ const next = new Date('2030-01-01T00:05:00Z');++ const first = await model.publishVersion(widget.id, v1!.id, { nextRunAt: next });+ expect(first?.version).toMatchObject({ publishedByUserId: userId, status: 'published' });+ expect(first?.version.publishedAt).toBeInstanceOf(Date);+ expect(first?.widget).toMatchObject({+ draftVersionId: null,+ nextRunAt: next,+ publishedVersionId: v1!.id,+ });++ const v2 = await model.createVersion(widget.id, script(2));+ const v3 = await model.createVersion(widget.id, script(3));+ // publishing a non-draft version keeps the current draft pointer+ const second = await model.publishVersion(widget.id, v2!.id);+ expect(second?.widget).toMatchObject({+ draftVersionId: v3!.id,+ nextRunAt: next,+ publishedVersionId: v2!.id,+ });+ expect((await model.findVersion(widget.id, v1!.id))?.status).toBe('archived');++ expect(await other.publishVersion(widget.id, v3!.id)).toBeUndefined();+ expect(await model.publishVersion(widget.id, MISSING_UUID)).toBeUndefined();+ });+ });++ describe('runs', () => {+ it('finds a run by id only through a readable widget', async () => {+ const widget = await model.create({ title: 'w' });+ await model.createVersion(widget.id, script(1));+ const run = await model.startRun(widget.id, { trigger: 'preview' });++ expect(await model.findRun(widget.id, run!.id)).toMatchObject({ id: run!.id });+ expect(await other.findRun(widget.id, run!.id)).toBeUndefined();+ expect(await model.findRun(widget.id, MISSING_UUID)).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));+ await model.createVersion(widget.id, script(2));+ // Back to v1's content: a new draft row with the same hash.+ const v3 = await model.createVersion(widget.id, script(1));+ expect(v3!.id).not.toBe(v1!.id);+ expect(v3!.contentHash).toBe(v1!.contentHash);++ expect(await model.hasSucceededRunForContentHash(widget.id, v1!.contentHash)).toBe(false);++ const failed = await model.startRun(widget.id, { trigger: 'preview', versionId: v1!.id });+ await model.finishRun(failed!.id, { status: 'failed' });+ expect(await model.hasSucceededRunForContentHash(widget.id, v1!.contentHash)).toBe(false);++ const partial = await model.startRun(widget.id, { trigger: 'preview', versionId: v1!.id });+ await model.finishRun(partial!.id, { status: 'partial' });+ expect(await model.hasSucceededRunForContentHash(widget.id, v3!.contentHash)).toBe(true);+ expect(await other.hasSucceededRunForContentHash(widget.id, v1!.contentHash)).toBe(false);+ });++ it('preview runs use the draft and never touch the widget snapshot', async () => {+ const widget = await model.create({ title: 'w' });+ const draft = await model.createVersion(widget.id, script(1));++ const run = await model.startRun(widget.id, { operationId: 'op_x', trigger: 'preview' });+ expect(run).toMatchObject({+ operationId: 'op_x',+ status: 'running',+ trigger: 'preview',+ versionId: draft!.id,+ });++ const finished = await model.finishRun(run!.id, {+ exitCode: 0,+ output: { type: 'stat', value: 1 },+ sandboxId: 'sbx_1',+ status: 'succeeded',+ stdout: '{"type":"stat","value":1}',+ });+ expect(finished).toMatchObject({ exitCode: 0, sandboxId: 'sbx_1', status: 'succeeded' });+ expect(finished!.durationMs).toBeGreaterThanOrEqual(0);++ const failing = await model.startRun(widget.id, { trigger: 'preview' });+ await model.finishRun(failing!.id, { status: 'failed' });++ expect(await model.findById(widget.id)).toMatchObject({+ consecutiveFailures: 0,+ lastRunId: null,+ lastRunStatus: null,+ latestOutput: null,+ });+ });++ it('folds manual / scheduled runs into the snapshot: succeeded, failed, timeout, partial', async () => {+ const widget = await model.create({ title: 'w' });+ const v1 = await model.createVersion(widget.id, script(1));+ await expect(model.startRun(widget.id, { trigger: 'manual' })).rejects.toThrow(+ 'no version to run',+ );+ await model.publishVersion(widget.id, v1!.id);++ const ok = await model.startRun(widget.id, { trigger: 'manual' });+ await model.finishRun(ok!.id, {+ durationMs: 120,+ output: { type: 'stat', value: 42 },+ status: 'succeeded',+ });+ let w = await model.findById(widget.id);+ expect(w).toMatchObject({+ consecutiveFailures: 0,+ lastRunId: ok!.id,+ lastRunStatus: 'succeeded',+ latestOutput: { type: 'stat', value: 42 },+ });++ for (const status of ['failed', 'timeout'] as const) {+ const bad = await WidgetModel.startRun(serverDB, w!, { trigger: 'schedule' });+ await WidgetModel.finishRun(serverDB, bad.id, {+ error: { code: 'NON_ZERO_EXIT', message: 'boom' },+ exitCode: 1,+ status,+ stderr: 'boom',+ });+ }+ w = await model.findById(widget.id);+ expect(w).toMatchObject({+ consecutiveFailures: 2,+ lastRunError: { code: 'NON_ZERO_EXIT', message: 'boom' },+ lastRunStatus: 'timeout',+ // the last good output survives failures+ latestOutput: { type: 'stat', value: 42 },+ });++ // a partial result is shown and ends the failure streak+ const partialOutput = {+ meta: { complete: false, message: 'GitLab API down' },+ type: 'stat' as const,+ value: 7,+ };+ const partial = await WidgetModel.startRun(serverDB, w!, { trigger: 'schedule' });+ await WidgetModel.finishRun(serverDB, partial.id, {+ output: partialOutput,+ status: 'partial',+ });+ w = await model.findById(widget.id);+ expect(w).toMatchObject({+ consecutiveFailures: 0,+ lastRunError: null,+ lastRunId: partial.id,+ lastRunStatus: 'partial',+ latestOutput: partialOutput,+ });+ expect(w!.latestOutputAt).toBeInstanceOf(Date);++ // finishing twice is a no-op+ expect(await model.finishRun(ok!.id, { status: 'failed' })).toBeUndefined();+ expect(await model.finishRun(MISSING_UUID, { status: 'failed' })).toBeUndefined();++ const runs = await model.listRuns(widget.id);+ expect(runs).toHaveLength(4);+ expect(runs.every((r) => r.userId === userId && r.versionId === v1!.id)).toBe(true);+ expect(await model.listRuns(widget.id, { limit: 1 })).toHaveLength(1);+ expect(await other.listRuns(widget.id)).toEqual([]);+ });++ it('does not fold a run that started before the snapshot run into the widget', async () => {+ const widget = await model.create({ title: 'w' });+ const v1 = await model.createVersion(widget.id, script(1));+ await model.publishVersion(widget.id, v1!.id);++ const older = await model.startRun(widget.id, { trigger: 'manual' });+ const newer = await model.startRun(widget.id, { trigger: 'schedule' });+ await serverDB+ .update(widgetRuns)+ .set({ startedAt: new Date(Date.now() - 120_000) })+ .where(eq(widgetRuns.id, older!.id));+ await serverDB+ .update(widgetRuns)+ .set({ startedAt: new Date(Date.now() - 60_000) })+ .where(eq(widgetRuns.id, newer!.id));++ await model.finishRun(newer!.id, {+ output: { type: 'stat', value: 2 },+ status: 'succeeded',+ });+ // the slower, older run reports last — it must not overwrite the newer result+ const late = await model.finishRun(older!.id, {+ error: { code: 'NON_ZERO_EXIT', message: 'boom' },+ status: 'failed',+ });+ expect(late).toMatchObject({ id: older!.id, status: 'failed' });++ expect(await model.findById(widget.id)).toMatchObject({+ consecutiveFailures: 0,+ lastRunError: null,+ lastRunId: newer!.id,+ lastRunStatus: 'succeeded',+ latestOutput: { type: 'stat', value: 2 },+ });+ expect(await model.findRun(widget.id, older!.id)).toMatchObject({ status: 'failed' });+ });++ it('does not fold a run of a version that is no longer published', async () => {+ const widget = await model.create({ title: 'w' });+ const v1 = await model.createVersion(widget.id, script(1));+ await model.publishVersion(widget.id, v1!.id);+ const first = await model.startRun(widget.id, { trigger: 'manual' });+ await model.finishRun(first!.id, { output: { type: 'stat', value: 1 }, status: 'succeeded' });++ const stale = await model.startRun(widget.id, { trigger: 'schedule' });+ // v2 goes live while v1's run is still in flight+ const v2 = await model.createVersion(widget.id, script(2));+ await model.publishVersion(widget.id, v2!.id);++ const finished = await model.finishRun(stale!.id, {+ output: { type: 'stat', value: 99 },+ status: 'succeeded',+ });+ expect(finished).toMatchObject({ id: stale!.id, status: 'succeeded', versionId: v1!.id });+ expect(await model.findById(widget.id)).toMatchObject({+ lastRunId: first!.id,+ latestOutput: { type: 'stat', value: 1 },+ });++ // a run of the live version still folds+ const fresh = await model.startRun(widget.id, { trigger: 'manual' });+ await model.finishRun(fresh!.id, { output: { type: 'stat', value: 2 }, status: 'succeeded' });+ expect(await model.findById(widget.id)).toMatchObject({+ lastRunId: fresh!.id,+ latestOutput: { type: 'stat', value: 2 },+ });+ });++ it('reports whether a finished run folded into the snapshot', async () => {+ const widget = await model.create({ title: 'w' });+ const v1 = await model.createVersion(widget.id, script(1));+ await model.publishVersion(widget.id, v1!.id);+ const live = (await model.findById(widget.id))!;+ const done = { output: { type: 'stat' as const, value: 1 }, status: 'succeeded' as const };++ const preview = await WidgetModel.startRun(serverDB, live, { trigger: 'preview' });+ expect(await WidgetModel.finishRun(serverDB, preview.id, done)).toMatchObject({+ folded: false,+ run: { id: preview.id },+ });++ const early = await WidgetModel.startRun(serverDB, live, { trigger: 'schedule' });+ await serverDB+ .update(widgetRuns)+ .set({ startedAt: new Date(Date.now() - 60_000) })+ .where(eq(widgetRuns.id, early.id));+ const current = await WidgetModel.startRun(serverDB, live, { trigger: 'manual' });+ expect(await WidgetModel.finishRun(serverDB, current.id, done)).toMatchObject({+ folded: true,+ run: { id: current.id, status: 'succeeded' },+ });+ // started before the snapshot's run: persisted, not folded+ expect(await WidgetModel.finishRun(serverDB, early.id, done)).toMatchObject({+ folded: false,+ run: { id: early.id, status: 'succeeded' },+ });++ const stale = await WidgetModel.startRun(serverDB, live, { trigger: 'schedule' });+ const v2 = await model.createVersion(widget.id, script(2));+ await model.publishVersion(widget.id, v2!.id);+ expect(await WidgetModel.finishRun(serverDB, stale.id, done)).toMatchObject({+ folded: false,+ });+ expect(await WidgetModel.finishRun(serverDB, stale.id, done)).toBeUndefined();+ });++ it('lets workspace readers run a public widget but not a private one', async () => {+ const pub = await ws.create({ title: 'pub' });+ const priv = await ws.create({ title: 'priv', visibility: 'private' });+ for (const w of [pub, priv]) {+ await ws.publishVersion(w.id, (await ws.createVersion(w.id, script(1)))!.id);+ }++ const run = await member.startRun(pub.id, { trigger: 'manual' });+ // run ownership follows the widget, not the actor+ expect(run).toMatchObject({ userId, workspaceId });+ expect(await member.finishRun(run!.id, { status: 'succeeded' })).toMatchObject({+ status: 'succeeded',+ });++ expect(await member.startRun(priv.id, { trigger: 'manual' })).toBeUndefined();+ const privRun = await ws.startRun(priv.id, { trigger: 'manual' });+ expect(await member.finishRun(privRun!.id, { status: 'succeeded' })).toBeUndefined();+ expect(await member.listRuns(priv.id)).toEqual([]);+ });++ it('rejects a version that belongs to another widget', async () => {+ const a = await model.create({ title: 'a' });+ const b = await model.create({ title: 'b' });+ const vb = await model.createVersion(b.id, script(1));++ await expect(model.startRun(a.id, { trigger: 'preview', versionId: vb!.id })).rejects.toThrow(+ 'does not belong',+ );+ expect(await model.startRun(MISSING_UUID, { trigger: 'manual' })).toBeUndefined();+ });+ });++ describe('scheduler', () => {+ it('loads a live widget with its published version and links its metric', async () => {+ const widget = await model.create({ title: 'w' });+ expect(await WidgetModel.findLiveWithPublishedVersion(serverDB, widget.id)).toBeUndefined();++ const v1 = await model.createVersion(widget.id, script(1));+ await model.publishVersion(widget.id, v1!.id);+ const live = await WidgetModel.findLiveWithPublishedVersion(serverDB, widget.id);+ expect(live).toMatchObject({ version: { id: v1!.id }, widget: { id: widget.id } });++ const [metric] = await serverDB+ .insert(metrics)+ .values({ key: 'value', subjectId: widget.id, subjectType: 'widget', userId })+ .returning();+ const [runA, runB] = [+ await WidgetModel.startRun(serverDB, widget, { trigger: 'manual', versionId: v1!.id }),+ await WidgetModel.startRun(serverDB, widget, { trigger: 'manual', versionId: v1!.id }),+ ];+ await serverDB.update(widgets).set({ lastRunId: runA.id }).where(eq(widgets.id, widget.id));+ await WidgetModel.linkMetric(serverDB, widget.id, metric.id, runA.id);+ expect((await model.findById(widget.id))!.metricId).toBe(metric.id);++ // run B took the snapshot; a late link from run A must not move the metric+ const [other] = await serverDB+ .insert(metrics)+ .values({ key: 'series:a', subjectId: widget.id, subjectType: 'widget', userId })+ .returning();+ await serverDB.update(widgets).set({ lastRunId: runB.id }).where(eq(widgets.id, widget.id));+ await WidgetModel.linkMetric(serverDB, widget.id, other.id, runA.id);+ expect((await model.findById(widget.id))!.metricId).toBe(metric.id);++ await model.trash(widget.id);+ expect(await WidgetModel.findLiveWithPublishedVersion(serverDB, widget.id)).toBeUndefined();+ });++ it('finds due widgets across users and claims each slot once', async () => {+ const now = new Date('2030-01-01T01:00:00Z');+ const past = new Date('2030-01-01T00:00:00Z');+ const future = new Date('2030-01-01T02:00:00Z');++ const make = async (+ m: WidgetModel,+ title: string,+ opts: { nextRunAt?: Date | null; publish?: boolean; schedule?: string | null },+ ) => {+ const w = await m.create({ schedulePattern: opts.schedule ?? null, title });+ const v = await m.createVersion(w.id, script(title.length));+ if (opts.publish !== false) await m.publishVersion(w.id, v!.id);+ await m.update(w.id, { nextRunAt: opts.nextRunAt ?? null });+ return w;+ };++ const due = await make(model, 'due', { nextRunAt: past, schedule: '0 * * * *' });+ const otherDue = await make(other, 'other-due', {+ nextRunAt: new Date('2030-01-01T00:30:00Z'),+ schedule: '0 * * * *',+ });+ await make(model, 'future', { nextRunAt: future, schedule: '0 * * * *' });+ await make(model, 'unscheduled', { nextRunAt: past, schedule: null });+ await make(model, 'unpublished', { nextRunAt: past, publish: false, schedule: '0 * * * *' });+ const trashed = await make(model, 'trashed', { nextRunAt: past, schedule: '0 * * * *' });+ await model.trash(trashed.id);++ const found = await WidgetModel.findDue(serverDB, { now });+ expect(found.map((r) => r.widget.id)).toEqual([due.id, otherDue.id]);+ expect(found[0].version.id).toBe(found[0].widget.publishedVersionId);+ expect(await WidgetModel.findDue(serverDB, { limit: 1, now })).toHaveLength(1);++ // two ticks racing for the same slot: exactly one wins and reserves the run+ const claim = {+ expectedNextRunAt: past,+ nextRunAt: future,+ versionId: found[0].version.id,+ widgetId: due.id,+ };+ const results = await Promise.all([+ WidgetModel.claimDueRun(serverDB, claim),+ WidgetModel.claimDueRun(serverDB, claim),+ ]);+ const reserved = results.filter(Boolean);+ expect(reserved).toHaveLength(1);+ expect(reserved[0]).toMatchObject({+ finishedAt: null,+ status: 'running',+ trigger: 'schedule',+ userId,+ versionId: found[0].version.id,+ widgetId: due.id,+ });+ expect(await WidgetModel.claimDueRun(serverDB, claim)).toBeUndefined();++ const remaining = await WidgetModel.findDue(serverDB, { now });+ expect(remaining.map((r) => r.widget.id)).toEqual([otherDue.id]);++ const [row] = await serverDB.select().from(widgets).where(eq(widgets.id, due.id));+ expect(row.nextRunAt).toEqual(future);+ expect(await serverDB.select().from(widgetRuns)).toMatchObject([{ id: reserved[0]!.id }]);+ });++ describe('reservations', () => {+ const past = new Date('2030-01-01T00:00:00Z');+ const future = new Date('2030-01-01T02:00:00Z');++ const dueWidget = async (m = model) => {+ const w = await m.create({ schedulePattern: '0 * * * *', title: 'scheduled' });+ const v = await m.createVersion(w.id, script(1));+ await m.publishVersion(w.id, v!.id);+ await m.update(w.id, { nextRunAt: past });+ return { version: v!, widget: w };+ };+ const reserve = async ({ version, widget }: Awaited<ReturnType<typeof dueWidget>>) =>+ (await WidgetModel.claimDueRun(serverDB, {+ expectedNextRunAt: past,+ nextRunAt: future,+ versionId: version.id,+ widgetId: widget.id,+ }))!;+ const backdate = (runId: string, ms: number) =>+ serverDB+ .update(widgetRuns)+ .set({ startedAt: new Date(Date.now() - ms) })+ .where(eq(widgetRuns.id, runId));+ const staleOptions = (extra = {}) => ({+ createdAfter: new Date(Date.now() - 60 * 60_000),+ limit: 10,+ startedBefore: new Date(Date.now() - 5 * 60_000),+ ...extra,+ });++ it('leaves the slot due and reserves nothing when the reservation fails', async () => {+ const target = await dueWidget();+ const transaction = serverDB.transaction.bind(serverDB);+ vi.spyOn(serverDB, 'transaction').mockImplementationOnce(((+ fn: Parameters<typeof transaction>[0],+ ) =>+ transaction(async (tx) => {+ vi.spyOn(tx, 'insert').mockImplementation(() => {+ throw new Error('insert failed');+ });+ return fn(tx);+ })) as typeof serverDB.transaction);++ await expect(+ WidgetModel.claimDueRun(serverDB, {+ expectedNextRunAt: past,+ nextRunAt: future,+ versionId: target.version.id,+ widgetId: target.widget.id,+ }),+ ).rejects.toThrow('insert failed');+ vi.restoreAllMocks();++ const [row] = await serverDB.select().from(widgets).where(eq(widgets.id, target.widget.id));+ expect(row.nextRunAt).toEqual(past);+ expect(await serverDB.select().from(widgetRuns)).toHaveLength(0);+ // the slot is still claimable afterwards+ expect(await reserve(target)).toMatchObject({ status: 'running' });+ });++ it('finds reservations started before the cut, only for live scheduled widgets', async () => {+ const a = await dueWidget();+ const fresh = await dueWidget();+ const trashed = await dueWidget();+ const unscheduled = await dueWidget();+ const runA = await reserve(a);+ await reserve(fresh);+ const runTrashed = await reserve(trashed);+ const runUnscheduled = await reserve(unscheduled);+ for (const id of [runA.id, runTrashed.id, runUnscheduled.id])+ await backdate(id, 10 * 60_000);+ await model.trash(trashed.widget.id);+ await model.update(unscheduled.widget.id, { schedulePattern: null });++ // a manual run left running is not a reservation+ const manual = await model.startRun(a.widget.id, { trigger: 'manual' });+ await backdate(manual!.id, 10 * 60_000);++ const found = await WidgetModel.findStaleScheduledRuns(serverDB, staleOptions());+ expect(found.map((r) => r.run.id)).toEqual([runA.id]);+ expect(found[0]).toMatchObject({+ version: { id: a.version.id },+ widget: { id: a.widget.id },+ });+ expect(+ await WidgetModel.findStaleScheduledRuns(+ serverDB,+ staleOptions({ widgetId: a.widget.id }),+ ),+ ).toHaveLength(1);+ expect(+ await WidgetModel.findStaleScheduledRuns(serverDB, staleOptions({ runId: MISSING_UUID })),+ ).toEqual([]);+ expect(+ await WidgetModel.findStaleScheduledRuns(serverDB, staleOptions({ runId: 'nope' })),+ ).toEqual([]);+ // older than the recovery horizon: no longer resumed+ expect(+ await WidgetModel.findStaleScheduledRuns(+ serverDB,+ staleOptions({ createdAfter: new Date(Date.now() + 60_000) }),+ ),+ ).toEqual([]);++ // once finished it is no longer a candidate+ await WidgetModel.finishRun(serverDB, runA.id, { status: 'failed' });+ expect(await WidgetModel.findStaleScheduledRuns(serverDB, staleOptions())).toEqual([]);+ });++ it('renews a lease once per observed start, only while the run is running', async () => {+ const run = await reserve(await dueWidget());+ await backdate(run.id, 10 * 60_000);+ const [stale] = await WidgetModel.findStaleScheduledRuns(serverDB, staleOptions());++ const renew = () =>+ WidgetModel.renewRunLease(serverDB, {+ expectedStartedAt: stale.run.startedAt,+ runId: run.id,+ });+ const [first, second] = await Promise.all([renew(), renew()]);+ const won = [first, second].filter(Boolean);+ expect(won).toHaveLength(1);+ expect(won[0]!.startedAt.getTime()).toBeGreaterThan(Date.now() - 60_000);+ // the renewed run is within its lease again+ expect(await WidgetModel.findStaleScheduledRuns(serverDB, staleOptions())).toEqual([]);++ // a run created by `startRun` carries microseconds; the lease still compares+ await backdate(run.id, 10 * 60_000);+ await serverDB+ .update(widgetRuns)+ .set({ startedAt: sql`now() - interval '10 minutes 0.000123 seconds'` })+ .where(eq(widgetRuns.id, run.id));+ const [again] = await WidgetModel.findStaleScheduledRuns(serverDB, staleOptions());+ expect(+ await WidgetModel.renewRunLease(serverDB, {+ expectedStartedAt: again.run.startedAt,+ runId: run.id,+ }),+ ).toMatchObject({ id: run.id, status: 'running' });++ await WidgetModel.finishRun(serverDB, run.id, { status: 'failed' });+ expect(+ await WidgetModel.renewRunLease(serverDB, {+ expectedStartedAt: (await model.findRun(stale.widget.id, run.id))!.startedAt,+ runId: run.id,+ }),+ ).toBeUndefined();+ expect(+ await WidgetModel.renewRunLease(serverDB, { expectedStartedAt: new Date(), runId: 'x' }),+ ).toBeUndefined();+ });+ });++ it('skips due widgets whose project or agent is trashed or private to someone else', async () => {+ const now = new Date('2030-01-01T01:00:00Z');+ const past = new Date('2030-01-01T00:00:00Z');+ await seedProject('wgt-due-trash');+ await serverDB.insert(agents).values({ id: 'wgt-due-agent', userId, workspaceId });+ await seedProject('wgt-due-teammate', { owner: otherUserId });+ await seedProject('wgt-due-own-private');++ const make = async (title: string, scope: { agentId?: string; projectId?: string }) => {+ const w = await ws.create({ ...scope, schedulePattern: '0 * * * *', title });+ const v = await ws.createVersion(w.id, script(title.length));+ await ws.publishVersion(w.id, v!.id);+ await ws.update(w.id, { nextRunAt: past });+ return w;+ };+ const inTrashedProject = await make('trashed-project', { projectId: 'wgt-due-trash' });+ const inTrashedAgent = await make('trashed-agent', { agentId: 'wgt-due-agent' });+ const inTeammateProject = await make('teammate', { projectId: 'wgt-due-teammate' });+ const inOwnPrivate = await make('own-private', { projectId: 'wgt-due-own-private' });++ const trashStampValue = { deletedAt: now, isDeleted: true };+ await serverDB.update(projects).set(trashStampValue).where(eq(projects.id, 'wgt-due-trash'));+ await serverDB.update(agents).set(trashStampValue).where(eq(agents.id, 'wgt-due-agent'));+ await serverDB+ .update(projects)+ .set({ visibility: 'private' })+ .where(inArray(projects.id, ['wgt-due-teammate', 'wgt-due-own-private']));++ const dueIds = async () =>+ (await WidgetModel.findDue(serverDB, { now })).map((r) => r.widget.id).sort();++ // a private parent the widget's owner created does not block it+ expect(await dueIds()).toEqual([inOwnPrivate.id]);+ // nor can an already-dispatched slot load them for execution+ for (const w of [inTrashedProject, inTrashedAgent, inTeammateProject]) {+ expect(await WidgetModel.findLiveWithPublishedVersion(serverDB, w.id)).toBeUndefined();+ }+ expect(+ await WidgetModel.findLiveWithPublishedVersion(serverDB, inOwnPrivate.id),+ ).toBeDefined();+ // skipped widgets keep their slot+ const rows = await serverDB+ .select()+ .from(widgets)+ .where(inArray(widgets.id, [inTrashedProject.id, inTrashedAgent.id, inTeammateProject.id]));+ expect(rows.map((r) => r.nextRunAt)).toEqual([past, past, past]);++ // restore the trashed parents and make the teammate's project public again+ const restored = { deletedAt: null, isDeleted: null };+ await serverDB.update(projects).set(restored).where(eq(projects.id, 'wgt-due-trash'));+ await serverDB.update(agents).set(restored).where(eq(agents.id, 'wgt-due-agent'));+ await serverDB+ .update(projects)+ .set({ visibility: 'public' })+ .where(eq(projects.id, 'wgt-due-teammate'));++ expect(await dueIds()).toEqual(+ [inTrashedProject.id, inTrashedAgent.id, inTeammateProject.id, inOwnPrivate.id].sort(),+ );+ });+ });+});diff --git a/packages/database/src/models/dashboard.ts b/packages/database/src/models/dashboard.tsnew file mode 100644index 00000000000..8c1eda19df2--- /dev/null+++ b/packages/database/src/models/dashboard.ts@@ -0,0 +1,405 @@+import type { DashboardItemLayout, DashboardVisibility, WidgetLevelFilter } from '@lobechat/types';+import { and, asc, eq, inArray, max } from 'drizzle-orm';++import { agents } from '../schemas/agent';+import { dashboardItems, dashboards } from '../schemas/dashboard';+import { projects } from '../schemas/project';+import { widgets } from '../schemas/widget';+import type { LobeChatDatabase, Transaction } from '../type';+import {+ assertScopeParents,+ buildDirectLevelWhere,+ buildParentVisibilityWhere,+ buildProjectWhere,+ hasPrivateParent,+ ScopeLevelError,+} from '../utils/scopeLevel';+import { isTrashed, restoreStamp, trashStamp } from '../utils/softDelete';+import { isUuid } from '../utils/uuid';+import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';+import { TrashModel } from './trash';++export interface CreateDashboardInput {+ agentId?: string | null;+ description?: string | null;+ icon?: string | null;+ metadata?: Record<string, unknown> | null;+ projectId?: string | null;+ sortOrder?: number;+ title: string;+ /** Ignored (forced to 'private') when the attached project or agent is private. */+ visibility?: DashboardVisibility;+}++export interface UpdateDashboardInput {+ description?: string | null;+ icon?: string | null;+ metadata?: Record<string, unknown> | null;+ sortOrder?: number;+ title?: string;+ /** 'public' is refused (kept 'private') while the project or agent is private. */+ visibility?: DashboardVisibility;+}++export interface AddDashboardItemInput {+ layout?: DashboardItemLayout | null;+ sortOrder?: number;+}++export interface DashboardItemLayoutPatch {+ id: string;+ layout?: DashboardItemLayout | null;+ sortOrder?: number;+}++/**+ * Boards and the placement of widgets on them.+ *+ * Same scope model as `WidgetModel`: scope columns (workspace / project /+ * agent) are fixed at creation and checked by `assertScopeParents`; reads+ * follow `buildWorkspaceWhere` plus the current visibility of the attached+ * project / agent; writes are limited to the creator. Role-based permissions+ * are enforced in the routers.+ */+export class DashboardModel {+ constructor(+ private readonly db: LobeChatDatabase,+ private readonly userId: string,+ private readonly workspaceId?: string,+ ) {}++ private get ctx() {+ return { userId: this.userId, workspaceId: this.workspaceId };+ }++ /** Visible to the caller, live, and not hidden by a private parent. */+ private readable() {+ return and(+ buildWorkspaceWhere(this.ctx, dashboards),+ buildParentVisibilityWhere(this.ctx, dashboards),+ );+ }++ private manageable() {+ return and(this.readable(), eq(dashboards.userId, this.userId));+ }++ /** The caller's own boards, trashed or not — for restore and hard delete. */+ private ownedIncludingTrashed() {+ return and(+ buildWorkspaceWhere({ ...this.ctx, includeTrashed: true }, dashboards),+ eq(dashboards.userId, this.userId),+ );+ }++ /** Widgets the caller may see on a board: the widget's own read rule. */+ private readableWidget() {+ return and(+ buildWorkspaceWhere(this.ctx, widgets),+ buildParentVisibilityWhere(this.ctx, widgets),+ );+ }++ // ── Dashboards ──++ async create(input: CreateDashboardInput) {+ const scope = { agentId: input.agentId ?? null, projectId: input.projectId ?? null };+ const parents = await assertScopeParents(this.db, this.ctx, scope);+ const visibility: DashboardVisibility | undefined = hasPrivateParent(parents)+ ? 'private'+ : input.visibility;++ const [dashboard] = await this.db+ .insert(dashboards)+ .values(buildWorkspacePayload(this.ctx, { ...input, ...scope, visibility }))+ .returning();++ return dashboard;+ }++ async findById(id: string) {+ if (!isUuid(id)) return undefined;++ const [dashboard] = await this.db+ .select()+ .from(dashboards)+ .where(and(eq(dashboards.id, id), this.readable()))+ .limit(1);++ return dashboard;+ }++ /** Boards living directly on one level, in board order. */+ async list(filter: WidgetLevelFilter = {}) {+ return this.db+ .select()+ .from(dashboards)+ .where(and(this.readable(), buildDirectLevelWhere(dashboards, filter)))+ .orderBy(asc(dashboards.sortOrder), asc(dashboards.createdAt));+ }++ /** Every board of a project, including those an agent of the project also owns. */+ async listByProject(projectId: string) {+ return this.db+ .select()+ .from(dashboards)+ .where(and(this.readable(), buildProjectWhere(dashboards, projectId)))+ .orderBy(asc(dashboards.sortOrder), asc(dashboards.createdAt));+ }++ async update(id: string, input: UpdateDashboardInput) {+ if (!isUuid(id)) return undefined;++ const values = { ...input };+ if (values.visibility === 'public' && (await this.hasPrivateParent(id))) {+ values.visibility = 'private';+ }++ const [dashboard] = await this.db+ .update(dashboards)+ .set({ ...values, updatedAt: new Date() })+ .where(and(eq(dashboards.id, id), this.manageable()))+ .returning();++ return dashboard;+ }++ /** Move a board to the recycle bin. Its items stay intact for restore. */+ async trash(id: string) {+ if (!isUuid(id)) return undefined;++ return this.db.transaction(async (tx) => {+ const now = new Date();+ const [dashboard] = await tx+ .update(dashboards)+ .set(trashStamp(now))+ .where(and(eq(dashboards.id, id), this.manageable()))+ .returning();+ if (!dashboard) return undefined;++ await this.trashRegistry(tx).register(+ {+ deletedAt: now,+ root: { resourceId: dashboard.id, resourceType: 'dashboard', title: dashboard.title },+ },+ tx,+ );++ return dashboard;+ });+ }++ async restore(id: string) {+ if (!isUuid(id)) return undefined;++ return this.db.transaction(async (tx) => {+ const [dashboard] = await tx+ .update(dashboards)+ .set(restoreStamp())+ .where(+ and(eq(dashboards.id, id), this.ownedIncludingTrashed(), isTrashed(dashboards.isDeleted)),+ )+ .returning();+ if (!dashboard) return undefined;++ await this.trashRegistry(tx).removeByResources(+ [{ resourceId: dashboard.id, resourceType: 'dashboard' }],+ tx,+ );+ return dashboard;+ });+ }++ /** Hard delete, live or trashed; items cascade, widgets are untouched. */+ async delete(id: string) {+ return this.hardDelete(id, false);+ }++ /**+ * Permanently delete a dashboard the recycle bin still holds. Gated on+ * `is_deleted` so a restore that commits after the purge read the registry+ * keeps the row instead of losing it.+ */+ async purge(id: string) {+ return this.hardDelete(id, true);+ }++ private async hardDelete(id: string, onlyTrashed: boolean) {+ if (!isUuid(id)) return undefined;++ return this.db.transaction(async (tx) => {+ const [dashboard] = await tx+ .delete(dashboards)+ .where(+ and(+ eq(dashboards.id, id),+ this.ownedIncludingTrashed(),+ onlyTrashed ? isTrashed(dashboards.isDeleted) : undefined,+ ),+ )+ .returning();+ if (!dashboard) return undefined;++ await this.trashRegistry(tx).removeByResources(+ [{ resourceId: dashboard.id, resourceType: 'dashboard' }],+ tx,+ );+ return dashboard;+ });+ }++ // ── Items ──++ /**+ * Place a widget on a board (or update its placement if already there). The+ * widget must be readable by the caller and share the board's workspace.+ */+ async addItem(dashboardId: string, widgetId: string, input: AddDashboardItemInput = {}) {+ if (!isUuid(dashboardId) || !isUuid(widgetId)) return undefined;++ const [dashboard] = await this.db+ .select({ id: dashboards.id, workspaceId: dashboards.workspaceId })+ .from(dashboards)+ .where(and(eq(dashboards.id, dashboardId), this.manageable()))+ .limit(1);+ if (!dashboard) return undefined;++ const [widget] = await this.db+ .select({ id: widgets.id, workspaceId: widgets.workspaceId })+ .from(widgets)+ .where(and(eq(widgets.id, widgetId), this.readableWidget()))+ .limit(1);+ if (!widget) return undefined;++ if (widget.workspaceId !== dashboard.workspaceId) {+ throw new ScopeLevelError(+ 'SCOPE_MISMATCH',+ 'Widget belongs to a different workspace than the dashboard',+ );+ }++ const sortOrder = input.sortOrder ?? (await this.nextSortOrder(dashboardId));+ const [item] = await this.db+ .insert(dashboardItems)+ .values({+ dashboardId,+ layout: input.layout ?? null,+ sortOrder,+ userId: this.userId,+ widgetId,+ workspaceId: dashboard.workspaceId,+ })+ .onConflictDoUpdate({+ set: {+ ...(input.layout !== undefined && { layout: input.layout }),+ ...(input.sortOrder !== undefined && { sortOrder: input.sortOrder }),+ updatedAt: new Date(),+ },+ target: [dashboardItems.dashboardId, dashboardItems.widgetId],+ })+ .returning();++ return item;+ }++ /**+ * Items of a readable board with their widgets, in display order. Widgets the+ * caller cannot read (trashed, private to a teammate, under a private+ * parent) drop out without losing their placement.+ */+ async listItems(dashboardId: string) {+ const dashboard = await this.findById(dashboardId);+ if (!dashboard) return [];++ return this.db+ .select({ item: dashboardItems, widget: widgets })+ .from(dashboardItems)+ .innerJoin(widgets, eq(dashboardItems.widgetId, widgets.id))+ .where(and(eq(dashboardItems.dashboardId, dashboardId), 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 })+ .from(dashboardItems)+ .innerJoin(dashboards, eq(dashboardItems.dashboardId, dashboards.id))+ .where(and(eq(dashboardItems.widgetId, widgetId), this.readable()))+ .orderBy(asc(dashboards.sortOrder), asc(dashboards.createdAt));+ }++ /** Persist a drag-and-drop result; ignores ids that are not on this board. */+ async updateItemLayouts(dashboardId: string, patches: DashboardItemLayoutPatch[]) {+ const validPatches = patches.filter((patch) => isUuid(patch.id));+ if (validPatches.length === 0 || !(await this.isManageable(dashboardId))) return 0;++ return this.db.transaction(async (tx) => {+ let updated = 0;+ const now = new Date();+ for (const patch of validPatches) {+ const rows = await tx+ .update(dashboardItems)+ .set({+ ...(patch.layout !== undefined && { layout: patch.layout }),+ ...(patch.sortOrder !== undefined && { sortOrder: patch.sortOrder }),+ updatedAt: now,+ })+ .where(and(eq(dashboardItems.id, patch.id), eq(dashboardItems.dashboardId, dashboardId)))+ .returning({ id: dashboardItems.id });+ updated += rows.length;+ }+ return updated;+ });+ }++ async removeItems(dashboardId: string, itemIds: string[]) {+ const ids = itemIds.filter(isUuid);+ if (ids.length === 0 || !(await this.isManageable(dashboardId))) return 0;++ const rows = await this.db+ .delete(dashboardItems)+ .where(and(eq(dashboardItems.dashboardId, dashboardId), inArray(dashboardItems.id, ids)))+ .returning({ id: dashboardItems.id });++ return rows.length;+ }++ private async isManageable(dashboardId: string) {+ if (!isUuid(dashboardId)) return false;++ const [dashboard] = await this.db+ .select({ id: dashboards.id })+ .from(dashboards)+ .where(and(eq(dashboards.id, dashboardId), this.manageable()))+ .limit(1);+ return !!dashboard;+ }++ private async nextSortOrder(dashboardId: string) {+ const [row] = await this.db+ .select({ max: max(dashboardItems.sortOrder) })+ .from(dashboardItems)+ .where(eq(dashboardItems.dashboardId, dashboardId));+ return row?.max === null || row?.max === undefined ? 0 : row.max + 1;+ }++ private trashRegistry(tx: Transaction) {+ return new TrashModel(tx as unknown as LobeChatDatabase, this.userId, this.workspaceId);+ }++ /** Whether the board's project or agent is currently private. */+ private async hasPrivateParent(id: string) {+ const [row] = await this.db+ .select({ agentVisibility: agents.visibility, projectVisibility: projects.visibility })+ .from(dashboards)+ .leftJoin(projects, eq(dashboards.projectId, projects.id))+ .leftJoin(agents, eq(dashboards.agentId, agents.id))+ .where(eq(dashboards.id, id))+ .limit(1);++ return row?.projectVisibility === 'private' || row?.agentVisibility === 'private';+ }+}diff --git a/packages/database/src/models/metric.ts b/packages/database/src/models/metric.tsindex 1d0eff515fd..7887ed05b1a 100644--- a/packages/database/src/models/metric.ts+++ b/packages/database/src/models/metric.ts@@ -215,6 +215,70 @@ export class MetricModel {return row;};+ /**+ * Append many observations to one series in a single insert — for samplers+ * that report a batch (e.g. a widget's time series). Same+ * ownership rule as {@link addPoint}; returns the inserted count, 0 when the+ * series is not the caller's.+ */+ addPoints = async (metricId: string, points: AddMetricPointParams[]): Promise<number> => {+ if (points.length === 0) return 0;+ const series = await this.findById(metricId);+ if (!series) return 0;++ const rows = await this.db+ .insert(metricPoints)+ .values(+ points.map((point) =>+ buildWorkspacePayload(+ { userId: this.userId, workspaceId: this.workspaceId },+ { ...point, metricId },+ ),+ ),+ )+ .returning({ id: metricPoints.id });+ return rows.length;+ };++ /**+ * Append only the points newer than the series' latest stored point — for+ * samplers that re-report a sliding window. The read and the insert run+ * under a row lock on the series, so two writers reporting the same window+ * at once serialize and the second one finds nothing new (no unique key on+ * `(metric_id, observed_at)` to lean on). A timestamp repeated inside the+ * batch is written once, keeping the value reported last. Returns the+ * inserted count, 0 when the series is not the caller's.+ */+ appendNewerPoints = async (+ metricId: string,+ points: (AddMetricPointParams & { observedAt: Date })[],+ ): Promise<number> => {+ if (points.length === 0) return 0;++ return this.db.transaction(async (tx) => {+ const [series] = await tx+ .select({ id: metrics.id })+ .from(metrics)+ .where(and(eq(metrics.id, metricId), this.seriesOwnership()))+ .limit(1)+ .for('update');+ if (!series) return 0;++ const scoped = new MetricModel(+ tx as unknown as LobeChatDatabase,+ this.userId,+ this.workspaceId,+ );+ const latest = await scoped.latestPoint(metricId);+ // Last value wins for a timestamp the batch reports more than once.+ const byTime = new Map(points.map((p) => [p.observedAt.getTime(), p]));+ const fresh = [...byTime.values()].filter(+ (p) => !latest || p.observedAt.getTime() > latest.observedAt.getTime(),+ );+ return scoped.addPoints(metricId, fresh);+ });+ };+/** The most recent observation — what numeric acceptance criteria read. */latestPoint = async (metricId: string): Promise<MetricPointItem | undefined> => {const [row] = await this.dbdiff --git a/packages/database/src/models/trash.ts b/packages/database/src/models/trash.tsindex e783c0da117..46806aaf53f 100644--- a/packages/database/src/models/trash.ts+++ b/packages/database/src/models/trash.ts@@ -10,7 +10,7 @@ import type {import { and, asc, count, desc, eq, inArray, isNull, lt, lte, or, sql } from 'drizzle-orm';import type { NewTrashItemRow, TrashItemRow } from '../schemas';-import { agents, messages, topics, trashItems } from '../schemas';+import { agents, dashboards, messages, topics, trashItems, widgets } from '../schemas';import type { LobeChatDatabase, Transaction } from '../type';import { buildWorkspaceWhere } from '../utils/workspace';@@ -41,8 +41,10 @@ export interface TrashRegisterParams {*/const ROOT_TABLES: Record<TrashResourceType, { id: any; isDeleted: any; table: any }> = {agent: { id: agents.id, isDeleted: agents.isDeleted, table: agents },+ dashboard: { id: dashboards.id, isDeleted: dashboards.isDeleted, table: dashboards },message: { id: messages.id, isDeleted: messages.isDeleted, table: messages },topic: { id: topics.id, isDeleted: topics.isDeleted, table: topics },+ widget: { id: widgets.id, isDeleted: widgets.isDeleted, table: widgets },};const toTrashItem = (row: TrashItemRow): TrashItem => ({@@ -413,7 +415,8 @@ export class TrashModel {and(eq(trashItems.resourceType, resourceType),isNull(trashItems.rootId),- sql`NOT EXISTS (SELECT 1 FROM ${source.table} WHERE ${source.id} = ${trashItems.resourceId} AND ${source.isDeleted} = true)`,+ // `::text` because some roots (widgets, dashboards) key on uuid while the registry stores text ids+ sql`NOT EXISTS (SELECT 1 FROM ${source.table} WHERE ${source.id}::text = ${trashItems.resourceId} AND ${source.isDeleted} = true)`,),).returning({ id: trashItems.id });diff --git a/packages/database/src/models/widget.ts b/packages/database/src/models/widget.tsnew file mode 100644index 00000000000..e28b0ad04f8--- /dev/null+++ b/packages/database/src/models/widget.ts@@ -0,0 +1,939 @@+import type {+ WidgetLevelFilter,+ WidgetManifest,+ WidgetOutput,+ WidgetOutputType,+ WidgetRunError,+ WidgetRunFinalStatus,+ WidgetRuntime,+ WidgetRunTrigger,+ WidgetVersionSource,+ WidgetView,+ WidgetVisibility,+} from '@lobechat/types';+import { WIDGET_RUN_OUTPUT_STATUSES } from '@lobechat/types';+import { and, asc, desc, eq, gte, inArray, isNotNull, lt, lte, max, sql } from 'drizzle-orm';++import { sha256Json } from '../repositories/ftsSearchDocument/fingerprint';+import { agents } from '../schemas/agent';+import { projects } from '../schemas/project';+import {+ type WidgetRow,+ type WidgetRunRow,+ widgetRuns,+ widgets,+ widgetVersions,+} from '../schemas/widget';+import type { LobeChatDatabase, Transaction } from '../type';+import {+ assertScopeParents,+ buildDirectLevelWhere,+ buildParentAccessibleToOwnerWhere,+ buildParentVisibilityWhere,+ buildProjectWhere,+ hasPrivateParent,+} from '../utils/scopeLevel';+import { isTrashed, notTrashed, restoreStamp, trashStamp } from '../utils/softDelete';+import { isUuid } from '../utils/uuid';+import { buildWorkspacePayload, buildWorkspaceWhere } from '../utils/workspace';+import { TrashModel } from './trash';++export interface CreateWidgetInput {+ agentId?: string | null;+ description?: string | null;+ metadata?: Record<string, unknown> | null;+ projectId?: string | null;+ schedulePattern?: string | null;+ scheduleTimezone?: string | null;+ title: string;+ /** Ignored (forced to 'private') when the attached project or agent is private. */+ visibility?: WidgetVisibility;+}++export interface UpdateWidgetInput {+ description?: string | null;+ metadata?: Record<string, unknown> | null;+ metricId?: string | null;+ /** Recomputed by the service whenever the schedule changes. */+ nextRunAt?: Date | null;+ schedulePattern?: string | null;+ scheduleTimezone?: string | null;+ title?: string;+ /** 'public' is refused (kept 'private') while the project or agent is private. */+ visibility?: WidgetVisibility;+}++export interface CreateWidgetVersionInput {+ changeNote?: string | null;+ manifest?: WidgetManifest | null;+ outputType: WidgetOutputType;+ parentVersionId?: string | null;+ runtime: WidgetRuntime;+ script: string;+ sourceAgentId?: string | null;+ sourceMessageId?: string | null;+ sourceOperationId?: string | null;+ sourceTopicId?: string | null;+ sourceType: WidgetVersionSource;+ view?: WidgetView | null;+}++export interface PublishWidgetVersionOptions {+ /** First due instant under the widget's schedule, computed by the caller. */+ nextRunAt?: Date | null;+}++export interface StartWidgetRunInput {+ operationId?: string | null;+ trigger: WidgetRunTrigger;+ /** Defaults to the draft (preview) or the published version (manual / schedule). */+ versionId?: string;+}++export interface FinishWidgetRunInput {+ durationMs?: number | null;+ error?: WidgetRunError | null;+ exitCode?: number | null;+ finishedAt?: Date;+ output?: WidgetOutput | null;+ sandboxId?: string | null;+ status: WidgetRunFinalStatus;+ stderr?: string | null;+ stdout?: string | null;+}++/** Content identity of a version: everything that changes what a run does or shows. */+export const computeWidgetContentHash = (input: {+ manifest?: WidgetManifest | null;+ outputType: WidgetOutputType;+ runtime: WidgetRuntime;+ script: string;+ view?: WidgetView | null;+}): string =>+ sha256Json({+ manifest: input.manifest ?? null,+ outputType: input.outputType,+ runtime: input.runtime,+ script: input.script,+ view: input.view ?? null,+ });++/** `succeeded` and `partial` both carry a renderable output. */+const producesOutput = (status: WidgetRunFinalStatus) =>+ (WIDGET_RUN_OUTPUT_STATUSES as readonly WidgetRunFinalStatus[]).includes(status);++/**+ * Widgets, their script versions and run history.+ *+ * Instance methods are ownership-scoped like `ProjectModel`: reads follow+ * `buildWorkspaceWhere` (workspace + visibility, trashed rows hidden), writes+ * (edit, version, publish, trash) are limited to the creator, while any reader+ * may trigger a run. Role-based permissions are enforced in the routers. The+ * static methods at the bottom are the scheduler's cross-user entry points and+ * must only be called from trusted server code.+ */+export class WidgetModel {+ constructor(+ private readonly db: LobeChatDatabase,+ private readonly userId: string,+ private readonly workspaceId?: string,+ ) {}++ private get ctx() {+ return { userId: this.userId, workspaceId: this.workspaceId };+ }++ /**+ * Visible to the caller: workspace + own visibility (`widgets` is+ * trash-aware, so trashed rows drop out) and the *current* visibility of the+ * attached project / agent. Versions, runs and the metric subject are all+ * reached through this predicate.+ */+ private readable() {+ return and(+ buildWorkspaceWhere(this.ctx, widgets),+ buildParentVisibilityWhere(this.ctx, widgets),+ );+ }++ private manageable() {+ return and(this.readable(), eq(widgets.userId, this.userId));+ }++ /** The caller's own rows, trashed or not — for restore and hard delete. */+ private ownedIncludingTrashed() {+ return and(+ buildWorkspaceWhere({ ...this.ctx, includeTrashed: true }, widgets),+ eq(widgets.userId, this.userId),+ );+ }++ // ── Widgets ──++ async create(input: CreateWidgetInput) {+ const scope = { agentId: input.agentId ?? null, projectId: input.projectId ?? null };+ const parents = await assertScopeParents(this.db, this.ctx, scope);+ const visibility: WidgetVisibility | undefined = hasPrivateParent(parents)+ ? 'private'+ : input.visibility;++ const [widget] = await this.db+ .insert(widgets)+ .values(buildWorkspacePayload(this.ctx, { ...input, ...scope, visibility }))+ .returning();++ return widget;+ }++ async findById(id: string) {+ // uuid column: a malformed id would abort the query with 22P02.+ if (!isUuid(id)) return undefined;++ const [widget] = await this.db+ .select()+ .from(widgets)+ .where(and(eq(widgets.id, id), this.readable()))+ .limit(1);++ return widget;+ }++ /** Widgets living directly on one level, most recently updated first. */+ async list(filter: WidgetLevelFilter = {}) {+ return this.db+ .select()+ .from(widgets)+ .where(and(this.readable(), buildDirectLevelWhere(widgets, filter)))+ .orderBy(desc(widgets.updatedAt));+ }++ /** Every widget of a project, including those an agent of the project also owns. */+ async listByProject(projectId: string) {+ return this.db+ .select()+ .from(widgets)+ .where(and(this.readable(), buildProjectWhere(widgets, projectId)))+ .orderBy(desc(widgets.updatedAt));+ }++ async update(id: string, input: UpdateWidgetInput) {+ const values = { ...input };+ if (values.visibility === 'public' && (await this.hasPrivateParent(id))) {+ values.visibility = 'private';+ }++ const [widget] = await this.db+ .update(widgets)+ .set({ ...values, updatedAt: new Date() })+ .where(and(eq(widgets.id, id), this.manageable()))+ .returning();++ return widget;+ }++ /**+ * Move a widget to the recycle bin and register it there. Trashed widgets+ * drop out of every read and of the scheduler's due query; versions and runs+ * stay for restore.+ */+ async trash(id: string) {+ if (!isUuid(id)) return undefined;++ return this.db.transaction(async (tx) => {+ const now = new Date();+ const [widget] = await tx+ .update(widgets)+ .set(trashStamp(now))+ .where(and(eq(widgets.id, id), this.manageable()))+ .returning();+ if (!widget) return undefined;++ await this.trashRegistry(tx).register(+ {+ deletedAt: now,+ root: { resourceId: widget.id, resourceType: 'widget', title: widget.title },+ },+ tx,+ );++ return widget;+ });+ }++ async restore(id: string) {+ if (!isUuid(id)) return undefined;++ return this.db.transaction(async (tx) => {+ const [widget] = await tx+ .update(widgets)+ .set(restoreStamp())+ .where(and(eq(widgets.id, id), this.ownedIncludingTrashed(), isTrashed(widgets.isDeleted)))+ .returning();+ if (!widget) return undefined;++ await this.trashRegistry(tx).removeByResources(+ [{ resourceId: widget.id, resourceType: 'widget' }],+ tx,+ );+ return widget;+ });+ }++ /** Hard delete; versions and runs cascade. */+ async delete(id: string) {+ return this.hardDelete(id, false);+ }++ /**+ * Permanently delete a widget the recycle bin still holds. Gated on+ * `is_deleted` so a restore that commits after the purge read the registry+ * keeps the row instead of losing it.+ */+ async purge(id: string) {+ return this.hardDelete(id, true);+ }++ private async hardDelete(id: string, onlyTrashed: boolean) {+ if (!isUuid(id)) return undefined;++ return this.db.transaction(async (tx) => {+ const [widget] = await tx+ .delete(widgets)+ .where(+ and(+ eq(widgets.id, id),+ this.ownedIncludingTrashed(),+ onlyTrashed ? isTrashed(widgets.isDeleted) : undefined,+ ),+ )+ .returning();+ if (!widget) return undefined;++ await this.trashRegistry(tx).removeByResources(+ [{ resourceId: widget.id, resourceType: 'widget' }],+ tx,+ );+ return widget;+ });+ }++ /**+ * Replace (or clear) the refresh schedule of a widget the caller manages and+ * close every scheduled run still reserved (`running`) as failed with+ * `SCHEDULE_CHANGED`, in one transaction holding the widget row lock.+ *+ * The lock serializes this against `claimDueRun`, which claims by updating+ * the same row: a claim that committed first has its reservation cancelled+ * here; a claim that arrives after finds `next_run_at` changed and fails its+ * compare-and-set. No reservation from the old schedule survives either way.+ */+ async setSchedule(+ widgetId: string,+ schedule: {+ nextRunAt: Date | null;+ schedulePattern: string | null;+ scheduleTimezone: string | null;+ },+ ) {+ if (!isUuid(widgetId)) return undefined;++ return this.db.transaction(async (tx) => {+ const [widget] = await tx+ .select({ id: widgets.id })+ .from(widgets)+ .where(and(eq(widgets.id, widgetId), this.manageable()))+ .limit(1)+ .for('update');+ if (!widget) return undefined;++ await tx+ .update(widgetRuns)+ .set({+ error: {+ code: 'SCHEDULE_CHANGED',+ message: 'The schedule changed before this run finished',+ },+ finishedAt: new Date(),+ status: 'failed',+ })+ .where(+ and(+ eq(widgetRuns.widgetId, widgetId),+ eq(widgetRuns.trigger, 'schedule'),+ eq(widgetRuns.status, 'running'),+ ),+ );++ const [updated] = await tx+ .update(widgets)+ .set({ ...schedule, updatedAt: new Date() })+ .where(eq(widgets.id, widgetId))+ .returning();+ return updated;+ });+ }++ // ── Versions ──++ /**+ * Record a new draft version and make it the widget's current draft. When+ * the content is identical to the current draft, that draft is returned+ * instead of minting a duplicate.+ */+ async createVersion(widgetId: string, input: CreateWidgetVersionInput) {+ if (!isUuid(widgetId)) return undefined;++ return this.db.transaction(async (tx) => {+ const [widget] = await tx+ .select()+ .from(widgets)+ .where(and(eq(widgets.id, widgetId), this.manageable()))+ .limit(1)+ .for('update');+ if (!widget) return undefined;++ const contentHash = computeWidgetContentHash(input);++ if (widget.draftVersionId) {+ const [draft] = await tx+ .select()+ .from(widgetVersions)+ .where(eq(widgetVersions.id, widget.draftVersionId))+ .limit(1);+ if (draft?.contentHash === contentHash) return draft;+ }++ const [latest] = await tx+ .select({ version: max(widgetVersions.version) })+ .from(widgetVersions)+ .where(eq(widgetVersions.widgetId, widgetId));++ const [version] = await tx+ .insert(widgetVersions)+ .values({+ ...input,+ contentHash,+ parentVersionId:+ input.parentVersionId ?? widget.draftVersionId ?? widget.publishedVersionId,+ status: 'draft',+ userId: widget.userId,+ version: (latest?.version ?? 0) + 1,+ widgetId,+ workspaceId: widget.workspaceId,+ })+ .returning();++ await tx+ .update(widgets)+ .set({ draftVersionId: version.id, updatedAt: new Date() })+ .where(eq(widgets.id, widgetId));++ return version;+ });+ }++ async listVersions(widgetId: string) {+ const widget = await this.findById(widgetId);+ if (!widget) return [];++ return this.db+ .select()+ .from(widgetVersions)+ .where(eq(widgetVersions.widgetId, widgetId))+ .orderBy(desc(widgetVersions.version));+ }++ async findVersion(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()+ .from(widgetVersions)+ .where(and(eq(widgetVersions.id, versionId), eq(widgetVersions.widgetId, widgetId)))+ .limit(1);++ return version;+ }++ /**+ * Make a version live. The previously published version is archived, the+ * draft pointer is cleared when it is the one being published, and the+ * schedule's first due instant is stored when provided.+ */+ async publishVersion(+ widgetId: string,+ versionId: string,+ options: PublishWidgetVersionOptions = {},+ ) {+ if (!isUuid(widgetId) || !isUuid(versionId)) return undefined;++ return this.db.transaction(async (tx) => {+ const [widget] = await tx+ .select()+ .from(widgets)+ .where(and(eq(widgets.id, widgetId), this.manageable()))+ .limit(1)+ .for('update');+ if (!widget) return undefined;++ const now = new Date();+ const [version] = await tx+ .update(widgetVersions)+ .set({ publishedAt: now, publishedByUserId: this.userId, status: 'published' })+ .where(and(eq(widgetVersions.id, versionId), eq(widgetVersions.widgetId, widgetId)))+ .returning();+ if (!version) return undefined;++ if (widget.publishedVersionId && widget.publishedVersionId !== versionId) {+ await tx+ .update(widgetVersions)+ .set({ status: 'archived' })+ .where(eq(widgetVersions.id, widget.publishedVersionId));+ }++ const [updated] = await tx+ .update(widgets)+ .set({+ ...(widget.draftVersionId === versionId && { draftVersionId: null }),+ ...(options.nextRunAt !== undefined && { nextRunAt: options.nextRunAt }),+ publishedVersionId: versionId,+ updatedAt: now,+ })+ .where(eq(widgets.id, widgetId))+ .returning();++ return { version, widget: updated };+ });+ }++ // ── Runs ──++ /** Open a run for a readable widget. Any reader may refresh a widget. */+ async startRun(widgetId: string, input: StartWidgetRunInput) {+ const widget = await this.findById(widgetId);+ if (!widget) return undefined;++ return WidgetModel.startRun(this.db, widget, input);+ }++ async finishRun(runId: string, input: FinishWidgetRunInput) {+ if (!isUuid(runId)) return undefined;++ const [run] = await this.db+ .select({ id: widgetRuns.id })+ .from(widgetRuns)+ .innerJoin(widgets, eq(widgetRuns.widgetId, widgets.id))+ .where(and(eq(widgetRuns.id, runId), this.readable()))+ .limit(1);+ if (!run) return undefined;++ return (await WidgetModel.finishRun(this.db, runId, input))?.run;+ }++ async listRuns(widgetId: string, options: { limit?: number } = {}) {+ const widget = await this.findById(widgetId);+ if (!widget) return [];++ return this.db+ .select()+ .from(widgetRuns)+ .where(eq(widgetRuns.widgetId, widgetId))+ .orderBy(desc(widgetRuns.createdAt))+ .limit(options.limit ?? 20);+ }++ async findRun(widgetId: string, runId: string) {+ if (!isUuid(runId)) return undefined;+ const widget = await this.findById(widgetId);+ if (!widget) return undefined;++ const [run] = await this.db+ .select()+ .from(widgetRuns)+ .where(and(eq(widgetRuns.id, runId), eq(widgetRuns.widgetId, widgetId)))+ .limit(1);++ return 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+ * draft is gated on this: the exact content going live must have executed+ * and met the output contract at least once, whichever version row carried+ * it.+ */+ async hasSucceededRunForContentHash(widgetId: string, contentHash: string) {+ const widget = await this.findById(widgetId);+ if (!widget) return false;++ const [row] = await this.db+ .select({ id: widgetRuns.id })+ .from(widgetRuns)+ .innerJoin(widgetVersions, eq(widgetRuns.versionId, widgetVersions.id))+ .where(+ and(+ eq(widgetRuns.widgetId, widgetId),+ inArray(widgetRuns.status, [...WIDGET_RUN_OUTPUT_STATUSES]),+ eq(widgetVersions.contentHash, contentHash),+ ),+ )+ .limit(1);++ return !!row;+ }++ private trashRegistry(tx: Transaction) {+ return new TrashModel(tx as unknown as LobeChatDatabase, this.userId, this.workspaceId);+ }++ /** Whether the widget's project or agent is currently private. */+ private async hasPrivateParent(id: string) {+ if (!isUuid(id)) return false;++ const [row] = await this.db+ .select({ agentVisibility: agents.visibility, projectVisibility: projects.visibility })+ .from(widgets)+ .leftJoin(projects, eq(widgets.projectId, projects.id))+ .leftJoin(agents, eq(widgets.agentId, agents.id))+ .where(eq(widgets.id, id))+ .limit(1);++ return row?.projectVisibility === 'private' || row?.agentVisibility === 'private';+ }++ // ── Scheduler (trusted, cross-user) ──++ /** A live widget and its published version, for a queued scheduled run. */+ static async findLiveWithPublishedVersion(db: LobeChatDatabase, widgetId: string) {+ if (!isUuid(widgetId)) return undefined;++ const [row] = await db+ .select({ version: widgetVersions, widget: widgets })+ .from(widgets)+ .innerJoin(widgetVersions, eq(widgets.publishedVersionId, widgetVersions.id))+ .where(+ and(+ eq(widgets.id, widgetId),+ notTrashed(widgets.isDeleted),+ // Same gate as `findDue`: a slot dispatched just before the parent was+ // trashed or made private must not run on the owner's credentials.+ buildParentAccessibleToOwnerWhere(widgets),+ ),+ )+ .limit(1);++ return row;+ }++ /** Point the widget at its trend series once the first point is written. */+ static async linkMetric(+ db: LobeChatDatabase,+ widgetId: string,+ metricId: string,+ /** Only link while this run still owns the snapshot (`last_run_id`). */+ runId: string,+ ) {+ await db+ .update(widgets)+ .set({ metricId })+ .where(and(eq(widgets.id, widgetId), eq(widgets.lastRunId, runId)));+ }++ /**+ * Live, published, scheduled widgets whose `next_run_at` has passed, with+ * the version to execute. Walks `widgets_due_idx`.+ *+ * Skips widgets their owner can no longer reach through the attached+ * project / agent (trashed, or private to someone else). `next_run_at` is+ * left as is, so the schedule resumes once access returns.+ */+ static async findDue(db: LobeChatDatabase, options: { limit?: number; now?: Date } = {}) {+ return db+ .select({ version: widgetVersions, widget: widgets })+ .from(widgets)+ .innerJoin(widgetVersions, eq(widgets.publishedVersionId, widgetVersions.id))+ .where(+ and(+ isNotNull(widgets.nextRunAt),+ isNotNull(widgets.schedulePattern),+ isNotNull(widgets.publishedVersionId),+ notTrashed(widgets.isDeleted),+ lte(widgets.nextRunAt, options.now ?? new Date()),+ buildParentAccessibleToOwnerWhere(widgets),+ ),+ )+ .orderBy(asc(widgets.nextRunAt))+ .limit(options.limit ?? 50);+ }++ /**+ * Claim one due slot and reserve its run in a single transaction: move+ * `next_run_at` forward only if it still holds the value the caller read+ * (compare-and-set), and insert the `schedule` run as `running`. Either both+ * happen or neither, so a claimed slot always leaves a durable run behind+ * that a later worker can resume (see `findStaleScheduledRuns`). Returns+ * undefined when another worker won the slot.+ */+ static async claimDueRun(+ db: LobeChatDatabase,+ params: {+ expectedNextRunAt: Date;+ nextRunAt: Date | null;+ /** The published version read with the due widget. */+ versionId: string;+ widgetId: string;+ },+ ): Promise<WidgetRunRow | undefined> {+ return db.transaction(async (tx) => {+ const [claimed] = await tx+ .update(widgets)+ .set({ nextRunAt: params.nextRunAt })+ .where(+ and(+ eq(widgets.id, params.widgetId),+ eq(widgets.nextRunAt, params.expectedNextRunAt),+ // Re-check what the due read saw: a trash, unpublish/republish or a+ // parent turning inaccessible that commits first makes the claim lose.+ eq(widgets.publishedVersionId, params.versionId),+ notTrashed(widgets.isDeleted),+ buildParentAccessibleToOwnerWhere(widgets),+ ),+ )+ .returning({ userId: widgets.userId, workspaceId: widgets.workspaceId });+ if (!claimed) return undefined;++ const [run] = await tx+ .insert(widgetRuns)+ .values({+ // Millisecond precision on purpose: the lease is compared-and-set+ // against the value a reader got back as a JS Date.+ startedAt: new Date(),+ status: 'running',+ trigger: 'schedule',+ userId: claimed.userId,+ versionId: params.versionId,+ widgetId: params.widgetId,+ workspaceId: claimed.workspaceId,+ })+ .returning();++ return run;+ });+ }++ /**+ * Reserved `schedule` runs still `running` that started before+ * `startedBefore` — candidates whose worker may have died. The caller+ * applies each run's own lease (it depends on the version's timeout) before+ * resuming one through {@link renewRunLease}.+ *+ * Driven from live, scheduled widgets (the `widgets_due_idx` predicate) and+ * their runs created since `createdAfter` (`widget_runs_widget_id_created_at_idx`),+ * so the sweep never scans the whole run history. Widgets that are trashed,+ * unscheduled or no longer reachable by their owner are not resumed.+ */+ static async findStaleScheduledRuns(+ db: LobeChatDatabase,+ options: {+ createdAfter: Date;+ limit: number;+ runId?: string;+ startedBefore: Date;+ widgetId?: string;+ },+ ) {+ if (options.runId !== undefined && !isUuid(options.runId)) return [];+ if (options.widgetId !== undefined && !isUuid(options.widgetId)) return [];++ return db+ .select({ run: widgetRuns, version: widgetVersions, widget: widgets })+ .from(widgets)+ .innerJoin(+ widgetRuns,+ and(eq(widgetRuns.widgetId, widgets.id), gte(widgetRuns.createdAt, options.createdAfter)),+ )+ .innerJoin(widgetVersions, eq(widgetRuns.versionId, widgetVersions.id))+ .where(+ and(+ isNotNull(widgets.nextRunAt),+ isNotNull(widgets.schedulePattern),+ isNotNull(widgets.publishedVersionId),+ notTrashed(widgets.isDeleted),+ buildParentAccessibleToOwnerWhere(widgets),+ eq(widgetRuns.status, 'running'),+ eq(widgetRuns.trigger, 'schedule'),+ lt(widgetRuns.startedAt, options.startedBefore),+ options.widgetId ? eq(widgets.id, options.widgetId) : undefined,+ options.runId ? eq(widgetRuns.id, options.runId) : undefined,+ ),+ )+ .orderBy(asc(widgetRuns.startedAt))+ .limit(options.limit);+ }++ /**+ * Take over a stale running run by restarting its lease: `started_at` moves+ * to now only if the run is still `running` and its `started_at` is still+ * the value the caller judged stale (compare-and-set). Exactly one resumer+ * wins; the others get undefined.+ */+ static async renewRunLease(+ db: LobeChatDatabase,+ params: { expectedStartedAt: Date; runId: string },+ ): Promise<WidgetRunRow | undefined> {+ if (!isUuid(params.runId)) return undefined;++ const [run] = await db+ .update(widgetRuns)+ .set({ startedAt: new Date() })+ .where(+ and(+ eq(widgetRuns.id, params.runId),+ eq(widgetRuns.status, 'running'),+ sql`date_trunc('milliseconds', ${widgetRuns.startedAt}) = ${params.expectedStartedAt.toISOString()}::timestamptz`,+ ),+ )+ .returning();++ return run;+ }++ /** Insert a `running` run owned by the widget's owner and workspace. */+ static async startRun(+ db: LobeChatDatabase,+ widget: Pick<+ WidgetRow,+ 'draftVersionId' | 'id' | 'publishedVersionId' | 'userId' | 'workspaceId'+ >,+ input: StartWidgetRunInput,+ ) {+ const versionId =+ input.versionId ??+ (input.trigger === 'preview'+ ? (widget.draftVersionId ?? widget.publishedVersionId)+ : widget.publishedVersionId);+ if (!versionId) throw new Error('Widget has no version to run');+ if (!isUuid(versionId)) throw new Error('Version does not belong to this widget');++ const [version] = await db+ .select({ id: widgetVersions.id })+ .from(widgetVersions)+ .where(and(eq(widgetVersions.id, versionId), eq(widgetVersions.widgetId, widget.id)))+ .limit(1);+ if (!version) throw new Error('Version does not belong to this widget');++ const [run] = await db+ .insert(widgetRuns)+ .values({+ operationId: input.operationId ?? null,+ status: 'running',+ trigger: input.trigger,+ userId: widget.userId,+ versionId,+ widgetId: widget.id,+ workspaceId: widget.workspaceId,+ })+ .returning();++ return run;+ }++ /**+ * Whether a finished non-preview run may update the widget snapshot: it ran+ * the published version and started no earlier than the snapshot's run.+ */+ private static async isCurrentRun(+ tx: Transaction,+ widget: Pick<WidgetRow, 'lastRunId' | 'publishedVersionId'>,+ run: Pick<WidgetRunRow, 'id' | 'startedAt' | 'versionId'>,+ ) {+ if (run.versionId !== widget.publishedVersionId) return false;+ if (!widget.lastRunId || widget.lastRunId === run.id) return true;++ const [last] = await tx+ .select({ startedAt: widgetRuns.startedAt })+ .from(widgetRuns)+ .where(eq(widgetRuns.id, widget.lastRunId))+ .limit(1);++ return !last || run.startedAt.getTime() >= last.startedAt.getTime();+ }++ /**+ * Close a running run and, unless it was a preview, fold the result into+ * the widget snapshot: `succeeded` and `partial` store the output and reset+ * the failure streak; `failed` / `timeout` increment it and keep the last+ * usable output. Finishing an already-finished run is a no-op that returns+ * undefined.+ *+ * Runs finish out of order (a slow manual refresh can report after the next+ * scheduled run, or after a new version went live). The run row is always+ * persisted, but it only folds into the snapshot when it is still current:+ * its version is the widget's published version and it started no earlier+ * than the run that last updated the snapshot (`last_run_id`). The widget+ * row is locked for the decision so concurrent finishers serialize.+ *+ * `folded` reports that decision, so anything else derived from "the+ * widget's current value" (the metric trend) follows the same rule.+ */+ static async finishRun(+ db: LobeChatDatabase,+ runId: string,+ input: FinishWidgetRunInput,+ ): Promise<{ folded: boolean; run: WidgetRunRow } | undefined> {+ return db.transaction(async (tx) => {+ const finishedAt = input.finishedAt ?? new Date();+ const [run] = await tx+ .update(widgetRuns)+ .set({+ durationMs:+ input.durationMs ??+ sql<number>`GREATEST(0, (EXTRACT(EPOCH FROM (${finishedAt.toISOString()}::timestamptz - ${widgetRuns.startedAt})) * 1000)::integer)`,+ error: input.error ?? null,+ exitCode: input.exitCode ?? null,+ finishedAt,+ output: input.output ?? null,+ sandboxId: input.sandboxId ?? null,+ status: input.status,+ stderr: input.stderr ?? null,+ stdout: input.stdout ?? null,+ })+ .where(and(eq(widgetRuns.id, runId), eq(widgetRuns.status, 'running')))+ .returning();+ if (!run) return undefined;++ if (run.trigger === 'preview') return { folded: false, run };++ const [widget] = await tx+ .select({+ lastRunId: widgets.lastRunId,+ publishedVersionId: widgets.publishedVersionId,+ })+ .from(widgets)+ .where(eq(widgets.id, run.widgetId))+ .limit(1)+ .for('update');+ if (!widget || !(await WidgetModel.isCurrentRun(tx, widget, run))) {+ return { folded: false, run };+ }++ const usable = producesOutput(input.status);+ await tx+ .update(widgets)+ .set({+ consecutiveFailures: usable ? 0 : sql`${widgets.consecutiveFailures} + 1`,+ lastRunAt: finishedAt,+ lastRunError: input.error ?? null,+ lastRunId: run.id,+ lastRunStatus: input.status,+ ...(usable && { latestOutput: input.output ?? null, latestOutputAt: finishedAt }),+ })+ .where(eq(widgets.id, run.widgetId));++ return { folded: true, run };+ });+ }+}diff --git a/packages/database/src/utils/scopeLevel.ts b/packages/database/src/utils/scopeLevel.tsnew file mode 100644index 00000000000..387da7e1453--- /dev/null+++ b/packages/database/src/utils/scopeLevel.ts@@ -0,0 +1,206 @@+import { and, eq, isNull, type SQL, sql } from 'drizzle-orm';+import type { AnyPgColumn } from 'drizzle-orm/pg-core';++import { agents } from '../schemas/agent';+import { projects } from '../schemas/project';+import type { LobeChatDatabase } from '../type';+import { buildWorkspaceWhere } from './workspace';++// Ownership levels for entities that can live directly on a user, a workspace,+// a project or an agent (optionally inside a project) — widgets today, other+// mountable entities later. The level is derived from which of the nullable+// `project_id` / `agent_id` columns are set; the workspace always comes from+// the caller context.++/** The optional parents that pick a row's direct level. */+export interface ScopeLevelFilter {+ agentId?: string | null;+ projectId?: string | null;+}++export type ScopeLevelErrorCode = 'AGENT_NOT_FOUND' | 'PROJECT_NOT_FOUND' | 'SCOPE_MISMATCH';++/**+ * Raised when a row would be attached to a project or agent the caller cannot+ * see, or whose workspace differs from the row's own.+ */+export class ScopeLevelError extends Error {+ constructor(+ public readonly code: ScopeLevelErrorCode,+ message: string,+ ) {+ super(message);+ this.name = 'ScopeLevelError';+ }+}++interface ScopeCtx {+ userId: string;+ workspaceId?: string;+}++type ParentVisibility = 'private' | 'public';++interface ScopeParent {+ id: string;+ visibility: ParentVisibility;+}++/** The resolved parents of a scope; a key is present only when that parent was requested. */+export interface ScopeParents {+ agent?: ScopeParent;+ project?: ScopeParent;+}++/**+ * Whether any attached parent is private. A child of a private parent must+ * not be more visible than the parent itself, or it would leak the parent's+ * existence (and its own content) to the whole workspace.+ */+export const hasPrivateParent = (parents: ScopeParents): boolean =>+ parents.project?.visibility === 'private' || parents.agent?.visibility === 'private';++/**+ * Enforce the ownership invariant of level-scoped rows: an attached project /+ * agent must be visible to the caller and live in the same workspace as the+ * row (both NULL in personal mode). The row's workspace is always the caller+ * context's workspace, so checking the parent against the context is+ * sufficient. Returns the resolved parents with their visibility so the+ * caller can tighten the row's own visibility.+ */+export const assertScopeParents = async (+ db: LobeChatDatabase,+ ctx: ScopeCtx,+ scope: ScopeLevelFilter,+): Promise<ScopeParents> => {+ const expectedWorkspaceId = ctx.workspaceId ?? null;+ const parents: ScopeParents = {};++ if (scope.projectId) {+ // `buildWorkspaceWhere` applies visibility and skips trashed projects.+ const [project] = await db+ .select({ id: projects.id, visibility: projects.visibility })+ .from(projects)+ .where(and(eq(projects.id, scope.projectId), buildWorkspaceWhere(ctx, projects)))+ .limit(1);++ if (!project) {+ // Distinguish "exists in another workspace" from "does not exist" so the+ // caller gets an actionable error without leaking row contents.+ const [other] = await db+ .select({ workspaceId: projects.workspaceId })+ .from(projects)+ .where(and(eq(projects.id, scope.projectId), eq(projects.userId, ctx.userId)))+ .limit(1);+ if (other && other.workspaceId !== expectedWorkspaceId) {+ throw new ScopeLevelError(+ 'SCOPE_MISMATCH',+ 'Project belongs to a different workspace than the record',+ );+ }+ throw new ScopeLevelError('PROJECT_NOT_FOUND', 'Project not found');+ }+ parents.project = project;+ }++ if (scope.agentId) {+ const [agent] = await db+ .select({ id: agents.id, visibility: agents.visibility })+ .from(agents)+ .where(and(eq(agents.id, scope.agentId), buildWorkspaceWhere(ctx, agents)))+ .limit(1);++ if (!agent) {+ const [other] = await db+ .select({ workspaceId: agents.workspaceId })+ .from(agents)+ .where(and(eq(agents.id, scope.agentId), eq(agents.userId, ctx.userId)))+ .limit(1);+ if (other && other.workspaceId !== expectedWorkspaceId) {+ throw new ScopeLevelError(+ 'SCOPE_MISMATCH',+ 'Agent belongs to a different workspace than the record',+ );+ }+ throw new ScopeLevelError('AGENT_NOT_FOUND', 'Agent not found');+ }+ parents.agent = agent;+ }++ return parents;+};++/**+ * Predicate selecting rows that live *directly* on one level:+ *+ * - agent given → that agent, and the given project or none+ * - project only → that project, without an agent+ * - neither → the context level (personal or workspace) with no project/agent+ *+ * Combine with `buildWorkspaceWhere` for access control.+ */+export const buildDirectLevelWhere = (+ cols: { agentId: AnyPgColumn; projectId: AnyPgColumn },+ filter: ScopeLevelFilter,+): SQL => {+ if (filter.agentId) {+ return and(+ eq(cols.agentId, filter.agentId),+ filter.projectId ? eq(cols.projectId, filter.projectId) : isNull(cols.projectId),+ ) as SQL;+ }+ if (filter.projectId) {+ return and(eq(cols.projectId, filter.projectId), isNull(cols.agentId)) as SQL;+ }+ return and(isNull(cols.projectId), isNull(cols.agentId)) as SQL;+};++/**+ * Predicate selecting everything that belongs to a project, whether or not an+ * agent inside the project also owns it — what a project's page shows.+ * Combine with `buildWorkspaceWhere` for access control.+ */+export const buildProjectWhere = (cols: { projectId: AnyPgColumn }, projectId: string): SQL =>+ eq(cols.projectId, projectId);++/**+ * Read gate for level-scoped rows: a row attached to a project or agent is+ * readable only while the caller can see that parent *now*. A row's own+ * `visibility` is clamped when it is written, but a parent can turn private+ * or be trashed later — without this gate a still-'public' child would keep+ * exposing the parent's content.+ *+ * A parent hides its children when it sits in the recycle bin (personal and+ * workspace mode alike), or — in workspace mode — when it is private and the+ * caller is not its creator (NULL visibility counts as public, as in+ * `buildWorkspaceWhere`). Restoring or re-publishing the parent shows them+ * again.+ *+ * Combine with `buildWorkspaceWhere` for every ordinary read.+ */+export const buildParentVisibilityWhere = (+ ctx: ScopeCtx,+ cols: { agentId: AnyPgColumn; projectId: AnyPgColumn },+): SQL => {+ const hiddenProject = ctx.workspaceId+ ? sql`${projects.isDeleted} IS TRUE OR (${projects.visibility} = 'private' AND ${projects.userId} <> ${ctx.userId})`+ : sql`${projects.isDeleted} IS TRUE`;+ const hiddenAgent = ctx.workspaceId+ ? sql`${agents.isDeleted} IS TRUE OR (${agents.visibility} = 'private' AND ${agents.userId} <> ${ctx.userId})`+ : sql`${agents.isDeleted} IS TRUE`;++ return sql`NOT EXISTS (SELECT 1 FROM ${projects} WHERE ${projects.id} = ${cols.projectId} AND (${hiddenProject})) AND NOT EXISTS (SELECT 1 FROM ${agents} WHERE ${agents.id} = ${cols.agentId} AND (${hiddenAgent}))`;+};++/**+ * Cross-user counterpart of {@link buildParentVisibilityWhere} for trusted+ * jobs (the widget scheduler): keeps a row only while its *owner* could still+ * read it through its parents — no attached project / agent is trashed, and+ * none is private unless the row's owner created it.+ */+export const buildParentAccessibleToOwnerWhere = (cols: {+ agentId: AnyPgColumn;+ projectId: AnyPgColumn;+ userId: AnyPgColumn;+}): SQL =>+ sql`NOT EXISTS (SELECT 1 FROM ${projects} WHERE ${projects.id} = ${cols.projectId} AND (${projects.isDeleted} IS TRUE OR (${projects.visibility} = 'private' AND ${projects.userId} <> ${cols.userId}))) AND NOT EXISTS (SELECT 1 FROM ${agents} WHERE ${agents.id} = ${cols.agentId} AND (${agents.isDeleted} IS TRUE OR (${agents.visibility} = 'private' AND ${agents.userId} <> ${cols.userId})))`;diff --git a/packages/database/src/utils/workspace.ts b/packages/database/src/utils/workspace.tsindex 8b3262020d6..33b6053d48e 100644--- a/packages/database/src/utils/workspace.ts+++ b/packages/database/src/utils/workspace.ts@@ -22,6 +22,7 @@ export const TRASH_AWARE_TABLES: ReadonlySet<string> = new Set(['agent_skills','agents','chat_groups',+ 'dashboards','documents','files','generation_batches',@@ -37,6 +38,7 @@ export const TRASH_AWARE_TABLES: ReadonlySet<string> = new Set(['threads','topics','user_memories',+ 'widgets','works',]);diff --git a/packages/env/src/__tests__/sandbox.test.ts b/packages/env/src/__tests__/sandbox.test.tsindex 10dde1ad35b..eca96ed6bfe 100644--- a/packages/env/src/__tests__/sandbox.test.ts+++ b/packages/env/src/__tests__/sandbox.test.ts@@ -10,6 +10,16 @@ describe('getSandboxConfig', () => {delete process.env.ONLYBOXES_JIT_SIGNING_KEY;delete process.env.ONLYBOXES_JIT_TTL_SEC;delete process.env.ONLYBOXES_LEASE_TTL_SEC;+ for (const key of [+ 'WIDGET_SANDBOX_URL',+ 'WIDGET_SANDBOX_TOKEN',+ 'WIDGET_SANDBOX_PROVIDER',+ 'WIDGET_SANDBOX_NETWORK_FORMAT',+ 'DASHBOARD_SANDBOX_URL',+ 'DASHBOARD_SANDBOX_TOKEN',+ ]) {+ delete process.env[key];+ }});it('should treat docker empty string defaults as unset optional values', async () => {@@ -49,4 +59,33 @@ describe('getSandboxConfig', () => {expect(config.ONLYBOXES_JIT_TTL_SEC).toBe(900);expect(config.ONLYBOXES_LEASE_TTL_SEC).toBe(3600);});++ it('reads the widget sandbox from WIDGET_SANDBOX_*', async () => {+ process.env.WIDGET_SANDBOX_URL = 'https://widget.example.dev';+ process.env.WIDGET_SANDBOX_TOKEN = 'widget-token';+ process.env.WIDGET_SANDBOX_PROVIDER = 'cloudflare-worker';+ process.env.WIDGET_SANDBOX_NETWORK_FORMAT = 'boolean';+ process.env.DASHBOARD_SANDBOX_URL = 'https://legacy.example.dev';+ process.env.DASHBOARD_SANDBOX_TOKEN = 'legacy-token';++ const { getSandboxConfig } = await import('../sandbox');+ const config = getSandboxConfig();++ expect(config.WIDGET_SANDBOX_URL).toBe('https://widget.example.dev');+ expect(config.WIDGET_SANDBOX_TOKEN).toBe('widget-token');+ expect(config.WIDGET_SANDBOX_PROVIDER).toBe('cloudflare-worker');+ expect(config.WIDGET_SANDBOX_NETWORK_FORMAT).toBe('boolean');+ });++ it('falls back to the legacy DASHBOARD_SANDBOX_* names', async () => {+ process.env.DASHBOARD_SANDBOX_URL = 'https://legacy.example.dev';+ process.env.DASHBOARD_SANDBOX_TOKEN = 'legacy-token';++ const { getSandboxConfig } = await import('../sandbox');+ const config = getSandboxConfig();++ expect(config.WIDGET_SANDBOX_URL).toBe('https://legacy.example.dev');+ expect(config.WIDGET_SANDBOX_TOKEN).toBe('legacy-token');+ expect(config.WIDGET_SANDBOX_PROVIDER).toBeUndefined();+ });});diff --git a/packages/env/src/sandbox.ts b/packages/env/src/sandbox.tsindex f469d057dda..8f706bee7e4 100644--- a/packages/env/src/sandbox.ts+++ b/packages/env/src/sandbox.ts@@ -12,6 +12,11 @@ export const getSandboxConfig = () => {ONLYBOXES_JIT_TTL_SEC: process.env.ONLYBOXES_JIT_TTL_SEC,ONLYBOXES_LEASE_TTL_SEC: process.env.ONLYBOXES_LEASE_TTL_SEC,SANDBOX_PROVIDER: process.env.SANDBOX_PROVIDER,+ WIDGET_SANDBOX_NETWORK_FORMAT: process.env.WIDGET_SANDBOX_NETWORK_FORMAT,+ WIDGET_SANDBOX_PROVIDER: process.env.WIDGET_SANDBOX_PROVIDER,+ // `DASHBOARD_SANDBOX_*` is the pre-rename name, still read as a fallback.+ WIDGET_SANDBOX_TOKEN: process.env.WIDGET_SANDBOX_TOKEN || process.env.DASHBOARD_SANDBOX_TOKEN,+ WIDGET_SANDBOX_URL: process.env.WIDGET_SANDBOX_URL || process.env.DASHBOARD_SANDBOX_URL,},server: {ONLYBOXES_BASE_URL: z.preprocess(emptyStringToUndefined, z.string().url().optional()),@@ -26,6 +31,26 @@ export const getSandboxConfig = () => {emptyStringToUndefined,z.enum(['market', 'onlyboxes']).optional(),),+ /**+ * How the widget sandbox request encodes the manifest's network+ * allowlist: `boolean` (default) sends `network: allow.length > 0`, which is+ * all the deployed Worker understands today (it rejects an object with 400);+ * `allowlist` sends `network: { allow: [...] }` for a Worker that enforces+ * per-run hosts.+ */+ WIDGET_SANDBOX_NETWORK_FORMAT: z.preprocess(+ emptyStringToUndefined,+ z.enum(['allowlist', 'boolean']).optional(),+ ),+ /** Widget script executor; only the Cloudflare Worker exists today. */+ WIDGET_SANDBOX_PROVIDER: z.preprocess(+ emptyStringToUndefined,+ z.enum(['cloudflare-worker']).optional(),+ ),+ /** Bearer token for the widget sandbox (`POST /run`). Falls back to `DASHBOARD_SANDBOX_TOKEN`. */+ WIDGET_SANDBOX_TOKEN: z.preprocess(emptyStringToUndefined, z.string().optional()),+ /** Base URL of the widget sandbox. Falls back to `DASHBOARD_SANDBOX_URL`. */+ WIDGET_SANDBOX_URL: z.preprocess(emptyStringToUndefined, z.string().url().optional()),},});};diff --git a/packages/locales/src/default/setting.ts b/packages/locales/src/default/setting.tsindex 5a72356692a..60325209113 100644--- a/packages/locales/src/default/setting.ts+++ b/packages/locales/src/default/setting.ts@@ -1845,8 +1845,10 @@ When I am ___, I need ___'trash.purge.success': 'Deleted permanently','trash.title': 'Trash','trash.type.agent': 'Agent',+ 'trash.type.dashboard': 'Dashboard','trash.type.message': 'Message','trash.type.topic': 'Topic',+ 'trash.type.widget': 'Widget','trash.untitled': 'Untitled','workspace.create.descPlaceholder': 'Describe what this workspace is for (optional)','workspace.create.namePlaceholder': 'e.g. Acme Team',diff --git a/packages/types/src/metric.ts b/packages/types/src/metric.tsindex 9ac16d91b0c..eb40bf875aa 100644--- a/packages/types/src/metric.ts+++ b/packages/types/src/metric.ts@@ -8,7 +8,15 @@* so new subject kinds are a type-only change. Goals are the first consumer;* the metrics layer itself never special-cases any of these.*/-export type MetricSubjectType = 'goal' | 'task' | 'agent' | 'project' | 'workspace';+export const METRIC_SUBJECT_TYPES = [+ 'goal',+ 'task',+ 'agent',+ 'project',+ 'workspace',+ 'widget',+] as const;+export type MetricSubjectType = (typeof METRIC_SUBJECT_TYPES)[number];/*** Decimal places `metric_points.value` keeps — the column is `numeric(20, 6)`.diff --git a/packages/types/src/trash.ts b/packages/types/src/trash.tsindex 700545e545b..bc77f270eb3 100644--- a/packages/types/src/trash.ts+++ b/packages/types/src/trash.ts@@ -15,7 +15,7 @@* are still registered as `trash_items` children so a restore / purge of the* root can find them, but the UI never lists them on their own.*/-export const TRASH_RESOURCE_TYPES = ['agent', 'topic', 'message'] as const;+export const TRASH_RESOURCE_TYPES = ['agent', 'topic', 'message', 'widget', 'dashboard'] as const;export type TrashResourceType = (typeof TRASH_RESOURCE_TYPES)[number];/**diff --git a/packages/types/src/widget/index.ts b/packages/types/src/widget/index.tsindex e65a5cc504a..f49d655d9df 100644--- a/packages/types/src/widget/index.ts+++ b/packages/types/src/widget/index.ts@@ -128,6 +128,13 @@ export interface WidgetEnvRequirement {*/connector?: string;description?: string;+ /**+ * Header of a header-credential connector to read, matched+ * case-insensitively, e.g. 'X-Api-Key'. Required when the connector holds+ * more than one header; other credential types hold a single secret and+ * ignore it.+ */+ field?: string;/** Environment variable name the script reads, e.g. 'GITHUB_TOKEN'. */name: string;required?: boolean;diff --git a/scripts/serverLauncher/startServer.js b/scripts/serverLauncher/startServer.jsindex 8d40f1cb4e1..f4dd4ea02b3 100644--- a/scripts/serverLauncher/startServer.js+++ b/scripts/serverLauncher/startServer.js@@ -186,6 +186,11 @@ const QSTASH_SCHEDULES = [id: 'lobe-goal-sweep',path: '/api/workflows/goal/sweep',},+ {+ cron: '* * * * *',+ id: 'lobe-widget-tick',+ path: '/api/workflows/widget/tick',+ },];// Function to create the recurring QStash schedules the server relies ondiff --git a/scripts/widgetTick/index.mts b/scripts/widgetTick/index.mtsnew file mode 100644index 00000000000..b7aaad9aace--- /dev/null+++ b/scripts/widgetTick/index.mts@@ -0,0 +1,56 @@+/**+ * Fire one widget scheduler tick against a local server — the same+ * request the `lobe-widget-tick` QStash schedule sends every minute.+ *+ * bun run widget:tick # run every due widget now+ * bun run widget:tick --dry-run # only report how many are due+ * SERVER_URL=http://localhost:3011 bun run widget:tick+ *+ * When QSTASH_CURRENT_SIGNING_KEY is set the route verifies signatures, so the+ * request is signed with that key the way QStash would; otherwise it is sent+ * unsigned, which the route accepts.+ */+import { createHash, createHmac, randomUUID } from 'node:crypto';++const serverUrl = (+ process.env.SERVER_URL ||+ process.env.APP_URL ||+ 'http://localhost:3010'+).replace(/\/$/, '');+const url = `${serverUrl}/api/workflows/widget/tick`;+const body = JSON.stringify({ dryRun: process.argv.includes('--dry-run') });++const base64url = (value: Buffer | string) => Buffer.from(value).toString('base64url');++/** An Upstash-Signature JWT over `body`, as QStash would send it. */+const sign = (key: string) => {+ const now = Math.floor(Date.now() / 1000);+ const header = base64url(JSON.stringify({ alg: 'HS256', typ: 'JWT' }));+ const payload = base64url(+ JSON.stringify({+ body: base64url(createHash('sha256').update(body).digest()),+ exp: now + 300,+ iat: now,+ iss: 'Upstash',+ jti: randomUUID(),+ nbf: now,+ sub: url,+ }),+ );+ const signature = base64url(createHmac('sha256', key).update(`${header}.${payload}`).digest());+ return `${header}.${payload}.${signature}`;+};++const signingKey = process.env.QSTASH_CURRENT_SIGNING_KEY;+const response = await fetch(url, {+ body,+ headers: {+ 'content-type': 'application/json',+ ...(signingKey && { 'Upstash-Signature': sign(signingKey) }),+ },+ method: 'POST',+});++console.log(`POST ${url} → ${response.status}${signingKey ? ' (signed)' : ''}`);+console.log(JSON.stringify(await response.json(), null, 2));+if (!response.ok) process.exit(1);diff --git a/src/features/Settings/trash/features/typeMeta.ts b/src/features/Settings/trash/features/typeMeta.tsindex 5e3b27bff7d..0d2b79d3ef2 100644--- a/src/features/Settings/trash/features/typeMeta.ts+++ b/src/features/Settings/trash/features/typeMeta.ts@@ -1,12 +1,26 @@import type { TrashResourceType } from '@lobechat/types';-import { BotIcon, HashIcon, MessageSquareIcon } from 'lucide-react';+import {+ BotIcon,+ ChartNoAxesColumnIcon,+ HashIcon,+ LayoutDashboardIcon,+ MessageSquareIcon,+} from 'lucide-react';/** Icon per recycle-bin resource kind — mirrors the sidebar / recents glyphs. */export const TRASH_TYPE_ICON: Record<TrashResourceType, typeof HashIcon> = {agent: BotIcon,+ dashboard: LayoutDashboardIcon,message: MessageSquareIcon,topic: HashIcon,+ widget: ChartNoAxesColumnIcon,};/** Order the type filter shows kinds in — most-deleted first. */-export const TRASH_TYPE_ORDER: TrashResourceType[] = ['topic', 'agent', 'message'];+export const TRASH_TYPE_ORDER: TrashResourceType[] = [+ 'topic',+ 'agent',+ 'message',+ 'widget',+ 'dashboard',+];