Skip to content

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

🐛 fix(widget): queue scheduled runs when the Market sandbox is busy, sign plan concurrency claim (#21613)

Arvin Xu69954763d4f2
diff --git a/apps/server/src/router-hono/workflows/widget/handlers/runWidget.ts b/apps/server/src/router-hono/workflows/widget/handlers/runWidget.ts
index b812c73b4bc..1f57a7c0b2a 100644
--- a/apps/server/src/router-hono/workflows/widget/handlers/runWidget.ts
+++ b/apps/server/src/router-hono/workflows/widget/handlers/runWidget.ts
@@ -53,6 +53,9 @@ export async function runWidget(c: Context) {
if (result.skipped) return c.json({ skipped: result.skipped, success: true });
return c.json({
+ // Acknowledged either way: a deferred run stays reserved and the tick's
+ // stale sweep resumes it once its lease expires.
+ ...(result.deferred && { deferred: true }),
...(result.resumed && { resumed: true }),
runId: result.run?.id,
status: result.run?.status,
diff --git a/apps/server/src/routers/lambda/__tests__/integration/widget.sandboxBusy.integration.test.ts b/apps/server/src/routers/lambda/__tests__/integration/widget.sandboxBusy.integration.test.ts
new file mode 100644
index 00000000000..284c2d046a6
--- /dev/null
+++ b/apps/server/src/routers/lambda/__tests__/integration/widget.sandboxBusy.integration.test.ts
@@ -0,0 +1,258 @@
+// @vitest-environment node
+import type { LobeChatDatabase } from '@lobechat/database';
+import { widgetRuns, widgets } from '@lobechat/database/schemas';
+import { getTestDB } from '@lobechat/database/test-utils';
+import { and, eq } from 'drizzle-orm';
+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { qstashClient } from '@/libs/qstash';
+import widgetWorkflowApp from '@/server/router-hono/workflows/widget';
+import { WidgetSandboxError } from '@/server/services/widget/sandbox/types';
+import { WIDGET_BUSY_DEFER_DEADLINE_MS } from '@/server/services/widget/sandboxBusy';
+
+import { widgetRouter } from '../../widget';
+import { cleanupTestUser, createTestUser } from './setup';
+
+let testDB: LobeChatDatabase;
+vi.mock('@/database/core/db-adaptor', () => ({
+ getServerDB: vi.fn(function () {
+ return testDB;
+ }),
+}));
+
+vi.mock('@/server/featureFlags', async () => {
+ const { mapFeatureFlagsEnvToState } = await import('@/config/featureFlags');
+ return {
+ getServerFeatureFlagsStateFromRuntimeConfig: async (userId?: string) =>
+ mapFeatureFlagsEnvToState({ dashboard: true }, userId),
+ };
+});
+
+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 = (value: number) => ({
+ durationMs: 12,
+ exitCode: 0,
+ stderr: '',
+ stdout: JSON.stringify({ type: 'stat', value }),
+ timedOut: false,
+});
+
+const busy = () =>
+ new WidgetSandboxError(
+ 'SANDBOX_BUSY',
+ 'Sandbox is busy for this account: concurrency_limited: Too many concurrent sandbox runs',
+ { retryAfterMs: 5000 },
+ );
+
+const statScript = {
+ outputType: 'stat' as const,
+ runtime: 'node' as const,
+ script: `console.log(JSON.stringify({ type: 'stat', value: 7 }))`,
+};
+
+/**
+ * Market caps one account's concurrent one-shot runs. A scheduled run it turns
+ * away (`SANDBOX_BUSY`) waits in its reservation and is resumed through the
+ * stale-lease recovery, instead of closing as failed until its next slot.
+ */
+describe('widget scheduled runs when the sandbox is busy', { timeout: 60_000 }, () => {
+ let db: LobeChatDatabase;
+ let ownerId: string;
+
+ // The first call migrates the in-memory database; keep it out of the per-test hook budget.
+ beforeAll(async () => {
+ await getTestDB();
+ }, 300_000);
+
+ beforeEach(async () => {
+ runSandbox.mockReset();
+ db = await getTestDB();
+ testDB = db;
+ ownerId = await createTestUser(db);
+ });
+
+ afterEach(async () => {
+ queueMode.enabled = false;
+ vi.restoreAllMocks();
+ vi.unstubAllEnvs();
+ await cleanupTestUser(db, ownerId);
+ });
+
+ 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, hourly widget whose slot is due. */
+ const dueWidget = async () => {
+ const owner = widgetRouter.createCaller({
+ jwtPayload: { userId: ownerId },
+ userId: ownerId,
+ } as any);
+ const widget = (await owner.create({ title: 'Open PRs' }))!.data;
+ await owner.setSchedule({ id: widget.id, pattern: '0 * * * *' });
+ const draft = (await owner.saveDraft({ widgetId: widget.id, ...statScript }))!.data;
+ runSandbox.mockResolvedValue(ok(5));
+ await owner.dryRun({ widgetId: widget.id });
+ await owner.publish({ versionId: draft.id, widgetId: widget.id });
+ runSandbox.mockReset();
+ 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 widgetRow = async (widgetId: string) =>
+ (await db.select().from(widgets).where(eq(widgets.id, widgetId)))[0];
+
+ /** Fast-forward a deferred run past its lease (and optionally its reservation age). */
+ const age = (runId: string, by: { createdMs?: number; startedMs: number }) =>
+ db
+ .update(widgetRuns)
+ .set({
+ ...(by.createdMs && { createdAt: new Date(Date.now() - by.createdMs) }),
+ startedAt: new Date(Date.now() - by.startedMs),
+ })
+ .where(eq(widgetRuns.id, runId));
+
+ it('defers a busy run inline and resumes it from a later tick, exactly once', async () => {
+ const { widget } = await dueWidget();
+ runSandbox.mockRejectedValueOnce(busy()).mockResolvedValue(ok(9));
+
+ expect(await post('/tick', {})).toMatchObject({
+ claimed: 1,
+ results: [{ deferred: true, widgetId: widget.id }],
+ });
+ const [reserved] = await scheduleRuns(widget.id);
+ expect(reserved).toMatchObject({ error: null, status: 'running' });
+ // The card keeps what it had: the waiting run is not reported as failed.
+ expect(await widgetRow(widget.id)).toMatchObject({
+ consecutiveFailures: 0,
+ lastRunStatus: null,
+ });
+
+ // Within its lease the deferred run is left alone.
+ expect(await post('/tick', {})).toMatchObject({ claimed: 0, resumed: 0 });
+ expect(runSandbox).toHaveBeenCalledTimes(1);
+
+ await age(reserved.id, { startedMs: 10 * 60_000 });
+ expect(await post('/tick', {})).toMatchObject({
+ 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' }]);
+ expect(await widgetRow(widget.id)).toMatchObject({
+ lastRunId: reserved.id,
+ lastRunStatus: 'succeeded',
+ latestOutput: { type: 'stat', value: 9 },
+ });
+ });
+
+ it('acks a busy queued run and resumes it through one resume message', async () => {
+ vi.stubEnv('APP_URL', 'https://app.test/');
+ const { slot, widget } = await dueWidget();
+ const message = { slot: slot.toISOString(), widgetId: widget.id };
+ runSandbox.mockRejectedValueOnce(busy()).mockResolvedValue(ok(9));
+
+ const first = await post('/run-widget', message);
+ const [reserved] = await scheduleRuns(widget.id);
+ expect(first).toEqual({ deferred: true, success: true });
+ expect(reserved).toMatchObject({ status: 'running' });
+ // A redelivery of the slot does not run it again while it waits.
+ expect(await post('/run-widget', message)).toEqual({
+ skipped: 'already-claimed',
+ success: true,
+ });
+
+ queueMode.enabled = true;
+ const publish = vi
+ .spyOn(qstashClient, 'publishJSON')
+ .mockResolvedValue({ messageId: 'm1' } as never);
+ expect(await post('/tick', {})).toMatchObject({ resumed: 0 });
+
+ await age(reserved.id, { startedMs: 10 * 60_000 });
+ const [{ startedAt }] = await scheduleRuns(widget.id);
+ expect(await post('/tick', {})).toMatchObject({ resumed: 1 });
+ const resume = {
+ leaseStartedAt: startedAt.toISOString(),
+ runId: reserved.id,
+ widgetId: widget.id,
+ };
+ expect(publish).toHaveBeenCalledWith(expect.objectContaining({ body: resume }));
+
+ // QStash delivers at least once: two copies race, one runs.
+ const results = await Promise.all([post('/run-widget', resume), post('/run-widget', resume)]);
+ expect(results).toEqual(
+ expect.arrayContaining([
+ { resumed: true, runId: reserved.id, status: 'succeeded', success: true },
+ { skipped: 'not-resumable', success: true },
+ ]),
+ );
+ expect(runSandbox).toHaveBeenCalledTimes(2);
+ expect(await scheduleRuns(widget.id)).toMatchObject([{ status: 'succeeded' }]);
+ });
+
+ it('defers a resumed run again while still busy, and closes it as SANDBOX_BUSY past the deadline', async () => {
+ const { widget } = await dueWidget();
+ runSandbox.mockRejectedValue(busy());
+
+ await post('/tick', {});
+ const [reserved] = await scheduleRuns(widget.id);
+
+ await age(reserved.id, { startedMs: 10 * 60_000 });
+ expect(await post('/tick', {})).toMatchObject({
+ resumed: 1,
+ results: [{ deferred: true, runId: reserved.id }],
+ });
+ expect(await scheduleRuns(widget.id)).toMatchObject([{ status: 'running' }]);
+
+ await age(reserved.id, {
+ createdMs: WIDGET_BUSY_DEFER_DEADLINE_MS + 60_000,
+ startedMs: 10 * 60_000,
+ });
+ expect(await post('/tick', {})).toMatchObject({
+ resumed: 1,
+ results: [{ runId: reserved.id, status: 'failed' }],
+ });
+
+ expect(runSandbox).toHaveBeenCalledTimes(3);
+ expect(await scheduleRuns(widget.id)).toMatchObject([
+ { error: { code: 'SANDBOX_BUSY' }, status: 'failed' },
+ ]);
+ expect(await widgetRow(widget.id)).toMatchObject({
+ lastRunError: { code: 'SANDBOX_BUSY' },
+ lastRunStatus: 'failed',
+ });
+ // Closed for good: nothing left for the sweep.
+ expect(await post('/tick', {})).toMatchObject({ resumed: 0 });
+ });
+});
diff --git a/apps/server/src/services/widget/__tests__/executeRun.test.ts b/apps/server/src/services/widget/__tests__/executeRun.test.ts
index c5eb5e3e9e6..744ba45c1a3 100644
--- a/apps/server/src/services/widget/__tests__/executeRun.test.ts
+++ b/apps/server/src/services/widget/__tests__/executeRun.test.ts
@@ -1,8 +1,10 @@
-import { describe, expect, it, vi } from 'vitest';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { WidgetModel } from '@/database/models/widget';
-import { executeWidgetRun } from '../executeRun';
+import { executeWidgetRun, executeWidgetRunDetailed } from '../executeRun';
+import { WidgetSandboxError } from '../sandbox/types';
+import { WIDGET_BUSY_DEFER_DEADLINE_MS } from '../sandboxBusy';
vi.mock('@/database/models/widget', () => ({
WidgetModel: { finishRun: vi.fn(async () => ({ folded: false, run: { id: 'run-1' } })) },
@@ -97,3 +99,183 @@ describe('executeWidgetRun', () => {
expect((run.mock.calls[0] as any[])[0].network).toEqual({ allow: ['api.github.com'] });
});
});
+
+describe('executeWidgetRun when the sandbox is busy', () => {
+ const busy = (retryAfterMs = 5000) =>
+ new WidgetSandboxError(
+ 'SANDBOX_BUSY',
+ 'Sandbox is busy for this account: concurrency_limited',
+ {
+ retryAfterMs,
+ },
+ );
+ const ran = {
+ durationMs: 10,
+ exitCode: 0,
+ stderr: '',
+ stdout: '{"type":"stat","value":1}',
+ timedOut: false,
+ };
+ const resolveEnv = vi.fn(async () => ({ env: {}, inject: [] }));
+ const finishRun = vi.mocked(WidgetModel.finishRun);
+
+ beforeEach(() => {
+ vi.useFakeTimers();
+ vi.spyOn(Math, 'random').mockReturnValue(0);
+ finishRun.mockClear();
+ });
+ afterEach(() => {
+ vi.useRealTimers();
+ vi.restoreAllMocks();
+ });
+
+ describe('a run someone waits on (manual / preview)', () => {
+ it('retries in process honouring Retry-After, then closes with the result', async () => {
+ const run = vi
+ .fn()
+ .mockRejectedValueOnce(busy(5000))
+ .mockRejectedValueOnce(busy(2000))
+ .mockResolvedValueOnce(ran);
+
+ const pending = executeWidgetRun({} as any, params, { resolveEnv, runner: { run } });
+ await vi.advanceTimersByTimeAsync(4999);
+ expect(run).toHaveBeenCalledTimes(1);
+ await vi.advanceTimersByTimeAsync(1);
+ expect(run).toHaveBeenCalledTimes(2);
+ await vi.advanceTimersByTimeAsync(2000);
+ await pending;
+
+ expect(run).toHaveBeenCalledTimes(3);
+ expect(finishRun).toHaveBeenCalledWith(
+ {},
+ 'run-1',
+ expect.objectContaining({ status: 'succeeded' }),
+ expect.any(Function),
+ );
+ });
+
+ it('gives up after three attempts with a clear SANDBOX_BUSY failure', async () => {
+ const run = vi.fn().mockRejectedValue(busy(5000));
+
+ const pending = executeWidgetRun({} as any, params, { resolveEnv, runner: { run } });
+ await vi.advanceTimersByTimeAsync(10_000);
+ await pending;
+
+ expect(run).toHaveBeenCalledTimes(3);
+ expect(finishRun).toHaveBeenCalledWith(
+ {},
+ 'run-1',
+ expect.objectContaining({
+ error: {
+ code: 'SANDBOX_BUSY',
+ message: expect.stringContaining('busy with other widget runs of this account'),
+ },
+ status: 'failed',
+ }),
+ expect.any(Function),
+ );
+ });
+
+ it('does not start a wait that would overrun the retry budget', async () => {
+ // rate_limited at the start of a minute: the next slot is ~60 s away.
+ const run = vi.fn().mockRejectedValue(busy(59_000));
+
+ await executeWidgetRun({} as any, params, { resolveEnv, runner: { run } });
+
+ expect(run).toHaveBeenCalledTimes(1);
+ expect(finishRun).toHaveBeenCalledWith(
+ {},
+ 'run-1',
+ expect.objectContaining({ error: expect.objectContaining({ code: 'SANDBOX_BUSY' }) }),
+ expect.any(Function),
+ );
+ });
+ });
+
+ describe('a scheduled run', () => {
+ const scheduled = (createdAt: Date, schedulePattern: string | null = '0 * * * *') => ({
+ ...params,
+ run: { createdAt, id: 'run-1', startedAt: createdAt, trigger: 'schedule' },
+ widget: { ...params.widget, schedulePattern, scheduleTimezone: null },
+ });
+
+ it('stays reserved instead of failing, without retrying in process', async () => {
+ vi.setSystemTime(new Date('2026-10-25T08:00:05Z'));
+ const run = vi.fn().mockRejectedValue(busy());
+
+ await expect(
+ executeWidgetRunDetailed({} as any, scheduled(new Date('2026-10-25T08:00:00Z')), {
+ resolveEnv,
+ runner: { run },
+ }),
+ ).resolves.toEqual({ deferred: true, run: undefined });
+
+ expect(run).toHaveBeenCalledTimes(1);
+ expect(finishRun).not.toHaveBeenCalled();
+ });
+
+ it('closes as failed SANDBOX_BUSY once it has waited past the deadline', async () => {
+ const createdAt = new Date('2026-10-25T08:00:00Z');
+ vi.setSystemTime(createdAt.getTime() + WIDGET_BUSY_DEFER_DEADLINE_MS + 1);
+ const run = vi.fn().mockRejectedValue(busy());
+
+ const result = await executeWidgetRunDetailed({} as any, scheduled(createdAt), {
+ resolveEnv,
+ runner: { run },
+ });
+
+ expect(result.deferred).toBeUndefined();
+ expect(finishRun).toHaveBeenCalledWith(
+ {},
+ 'run-1',
+ expect.objectContaining({
+ error: expect.objectContaining({ code: 'SANDBOX_BUSY' }),
+ expectedStartedAt: createdAt,
+ status: 'failed',
+ }),
+ expect.any(Function),
+ );
+ });
+
+ it('stops waiting when the widget’s next slot arrives first', async () => {
+ // Every 10 minutes: the next slot (08:10) comes before the 30-minute bound.
+ vi.setSystemTime(new Date('2026-10-25T08:10:30Z'));
+ const run = vi.fn().mockRejectedValue(busy());
+
+ const result = await executeWidgetRunDetailed(
+ {} as any,
+ scheduled(new Date('2026-10-25T08:00:00Z'), '*/10 * * * *'),
+ { resolveEnv, runner: { run } },
+ );
+
+ expect(result.deferred).toBeUndefined();
+ expect(finishRun).toHaveBeenCalledWith(
+ {},
+ 'run-1',
+ expect.objectContaining({ status: 'failed' }),
+ expect.any(Function),
+ );
+ });
+
+ it('fails other sandbox errors at once, as before', async () => {
+ vi.setSystemTime(new Date('2026-10-25T08:00:05Z'));
+ const run = vi
+ .fn()
+ .mockRejectedValue(new WidgetSandboxError('SANDBOX_ERROR', 'HTTP 503: unavailable'));
+
+ const result = await executeWidgetRunDetailed(
+ {} as any,
+ scheduled(new Date('2026-10-25T08:00:00Z')),
+ { resolveEnv, runner: { run } },
+ );
+
+ expect(result.deferred).toBeUndefined();
+ expect(finishRun).toHaveBeenCalledWith(
+ {},
+ 'run-1',
+ expect.objectContaining({ error: expect.objectContaining({ code: 'SANDBOX_ERROR' }) }),
+ expect.any(Function),
+ );
+ });
+ });
+});
diff --git a/apps/server/src/services/widget/executeRun.ts b/apps/server/src/services/widget/executeRun.ts
index 8e58aac801b..70973e5b40d 100644
--- a/apps/server/src/services/widget/executeRun.ts
+++ b/apps/server/src/services/widget/executeRun.ts
@@ -17,7 +17,8 @@ import {
import { recordWidgetMetrics } from './metrics';
import { parseWidgetOutput } from './outputContract';
import { redactSecrets, sanitizeStream } from './redact';
-import { WidgetSandboxError, type WidgetSandboxRunner } from './sandbox/types';
+import { isWidgetSandboxBusy, WidgetSandboxError, type WidgetSandboxRunner } from './sandbox/types';
+import { busyDeferralDeadline, runWithBusyRetry } from './sandboxBusy';
const log = debug('lobe-server:widget:execute-run');
@@ -45,7 +46,9 @@ export interface ExecuteWidgetRunDeps {
class MetricPublicationError extends Error {}
export interface ExecuteWidgetRunParams {
- run: Pick<WidgetRunRow, 'id' | 'trigger'> & Partial<Pick<WidgetRunRow, 'startedAt'>>;
+ /** `createdAt` is when a scheduled run was reserved; it bounds a busy deferral. */
+ run: Pick<WidgetRunRow, 'id' | 'trigger'> &
+ Partial<Pick<WidgetRunRow, 'createdAt' | 'startedAt'>>;
version: Pick<
WidgetVersionRow,
'manifest' | 'outputType' | 'publishedByUserId' | 'runtime' | 'script' | 'userId'
@@ -53,10 +56,22 @@ export interface ExecuteWidgetRunParams {
widget: Pick<
WidgetRow,
'agentId' | 'id' | 'metricId' | 'projectId' | 'title' | 'userId' | 'workspaceId'
- >;
+ > &
+ Partial<Pick<WidgetRow, 'schedulePattern' | 'scheduleTimezone'>>;
}
+/**
+ * What became of an executed run. `deferred`: a scheduled run the sandbox was
+ * too busy to take; its reservation stays `running` and is resumed once its
+ * lease expires. Otherwise `run` is the closed run, or undefined when this
+ * worker no longer held it (another worker took it over or closed it).
+ */
+export type ExecutedWidgetRun =
+ { deferred: true; run: undefined } | { deferred?: undefined; run: WidgetRunRow | undefined };
+
interface RunOutcome {
+ /** The sandbox turned the run away for the account's limits (`SANDBOX_BUSY`). */
+ busy?: boolean;
durationMs?: number;
env: Record<string, string>;
error?: WidgetRunError | null;
@@ -73,7 +88,7 @@ interface RunOutcome {
*/
const runInSandbox = async (
db: LobeChatDatabase,
- { version, widget }: Pick<ExecuteWidgetRunParams, 'version' | 'widget'>,
+ { run, version, widget }: ExecuteWidgetRunParams,
deps: ExecuteWidgetRunDeps,
): Promise<RunOutcome> => {
const manifest = version.manifest ?? undefined;
@@ -119,8 +134,8 @@ const runInSandbox = async (
};
}
- try {
- const result = await deps.runner.run({
+ const execute = () =>
+ deps.runner.run({
// The widget's owner (or its workspace) pays for and is rate limited on the run.
actor: { userId: widget.userId, workspaceId: widget.workspaceId },
env,
@@ -131,6 +146,11 @@ const runInSandbox = async (
timeoutMs: manifest?.timeoutMs,
});
+ try {
+ // Someone waits on a manual or preview run, so a busy sandbox is waited
+ // out here; a scheduled run is deferred by the caller instead.
+ const result = await (run.trigger === 'schedule' ? execute() : runWithBusyRetry(execute));
+
const stdout = redactSecrets(result.stdout, env);
const stderr = redactSecrets(result.stderr, env);
const base = { durationMs: result.durationMs, env, exitCode: result.exitCode, stderr, stdout };
@@ -168,7 +188,21 @@ const runInSandbox = async (
} 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' };
+ const busy = isWidgetSandboxBusy(error);
+ return {
+ ...(busy && { busy }),
+ env,
+ error: {
+ code,
+ message: redactSecrets(
+ busy
+ ? `The sandbox is busy with other widget runs of this account; try again shortly (${message})`
+ : message,
+ env,
+ ),
+ },
+ status: 'failed',
+ };
}
};
@@ -181,7 +215,10 @@ const runInSandbox = async (
* any sandbox call;
* 2. execute the version's script on the sandbox with the manifest's network
* allowlist, plus the credential headers the egress proxy adds for LobeHub
- * Market connectors (whose env variables only hold placeholders);
+ * Market connectors (whose env variables only hold placeholders). When the
+ * account is at its sandbox limits (`SANDBOX_BUSY`), a manual or preview
+ * run retries in process (bounded); a scheduled run is deferred — see
+ * {@link executeWidgetRunDetailed};
* 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`;
@@ -199,10 +236,34 @@ export const executeWidgetRun = async (
db: LobeChatDatabase,
params: ExecuteWidgetRunParams,
deps: ExecuteWidgetRunDeps,
-): Promise<WidgetRunRow | undefined> => {
+): Promise<WidgetRunRow | undefined> => (await executeWidgetRunDetailed(db, params, deps)).run;
+
+/**
+ * {@link executeWidgetRun}, also reporting a deferral: a `schedule` run the
+ * sandbox answered `SANDBOX_BUSY` is not closed while it is before its
+ * {@link busyDeferralDeadline}. Its reservation stays `running` with the lease
+ * it has, so the scheduler resumes it like an abandoned run once that lease
+ * expires — inline from the tick, or through a resume message in queue mode —
+ * under the same compare-and-set takeover, so it never runs twice at once.
+ * Past the deadline it closes as `failed` with `SANDBOX_BUSY`.
+ */
+export const executeWidgetRunDetailed = async (
+ db: LobeChatDatabase,
+ params: ExecuteWidgetRunParams,
+ deps: ExecuteWidgetRunDeps,
+): Promise<ExecutedWidgetRun> => {
const { run, version, widget } = params;
const outcome = await runInSandbox(db, params, deps);
+ if (outcome.busy && run.trigger === 'schedule') {
+ const deadline = busyDeferralDeadline(run, widget);
+ if (deadline && Date.now() < deadline.getTime()) {
+ log('defer run=%s widget=%s reason=sandbox-busy until=%s', run.id, widget.id, deadline);
+ return { deferred: true, run: undefined };
+ }
+ log('give up run=%s widget=%s reason=sandbox-busy-past-deadline', run.id, widget.id);
+ }
+
const finishedAt = new Date();
let finished: Awaited<ReturnType<typeof WidgetModel.finishRun>>;
try {
@@ -261,5 +322,5 @@ export const executeWidgetRun = async (
}
log('run=%s widget=%s status=%s', run.id, widget.id, outcome.status);
- return finished?.run;
+ return { run: finished?.run };
};
diff --git a/apps/server/src/services/widget/sandbox/__tests__/market.test.ts b/apps/server/src/services/widget/sandbox/__tests__/market.test.ts
index ec7f88216f8..34b533b7557 100644
--- a/apps/server/src/services/widget/sandbox/__tests__/market.test.ts
+++ b/apps/server/src/services/widget/sandbox/__tests__/market.test.ts
@@ -3,7 +3,9 @@ import { describe, expect, it, vi } from 'vitest';
vi.mock('@/server/services/market', () => ({ MarketService: vi.fn() }));
-const { MarketWidgetSandboxRunner } = await import('../market');
+const { MarketService } = await import('@/server/services/market');
+const { resolveSandboxRunLimits } = await import('@/business/server/sandboxRun');
+const { MarketWidgetSandboxRunner, marketRetryAfterMs } = await import('../market');
const { WIDGET_SANDBOX_DEFAULT_TIMEOUT_MS, WIDGET_SANDBOX_MAX_TIMEOUT_MS } =
await import('../types');
@@ -26,10 +28,17 @@ const result = {
truncated: false,
};
-const setup = (run: (...args: any[]) => Promise<unknown>) => {
+const setup = (
+ run: (...args: any[]) => Promise<unknown>,
+ resolveLimits?: (...args: any[]) => Promise<{ maxConcurrency: number } | null>,
+) => {
const sandbox = { run: vi.fn(run) };
- const sandboxFor = vi.fn(() => sandbox as any);
- const runner = new MarketWidgetSandboxRunner({ isEnabled: () => true, sandboxFor });
+ const sandboxFor = vi.fn((..._args: any[]) => sandbox as any);
+ const runner = new MarketWidgetSandboxRunner({
+ isEnabled: () => true,
+ resolveLimits,
+ sandboxFor,
+ });
return { runner, sandbox, sandboxFor };
};
@@ -47,7 +56,8 @@ describe('MarketWidgetSandboxRunner', () => {
stdout: '{"type":"stat"}',
timedOut: false,
});
- expect(sandboxFor).toHaveBeenCalledWith({ userId: 'user-1', workspaceId: 'ws-1' });
+ // The open-source hook grants nothing: Market's default concurrency applies.
+ expect(sandboxFor).toHaveBeenCalledWith({ userId: 'user-1', workspaceId: 'ws-1' }, null);
expect(sandbox.run).toHaveBeenCalledWith(
{
egress: { allow: ['api.github.com'] },
@@ -108,7 +118,9 @@ describe('MarketWidgetSandboxRunner', () => {
[403, { error: 'forbidden_client' }, 'SANDBOX_UNAUTHORIZED'],
[400, { error: 'invalid_request', error_description: 'bad host' }, 'SANDBOX_BAD_REQUEST'],
[422, { error: 'secret_unusable' }, 'SANDBOX_BAD_REQUEST'],
- [429, { error: 'rate_limited' }, 'SANDBOX_ERROR'],
+ [429, { error: 'rate_limited' }, 'SANDBOX_BUSY'],
+ [429, { error: 'concurrency_limited' }, 'SANDBOX_BUSY'],
+ [429, undefined, 'SANDBOX_BUSY'],
[503, { error: 'sandbox_unavailable' }, 'SANDBOX_ERROR'],
[500, undefined, 'SANDBOX_ERROR'],
])('maps HTTP %d %j to %s', async (status, body, code) => {
@@ -139,4 +151,104 @@ describe('MarketWidgetSandboxRunner', () => {
message: expect.stringContaining('fetch failed'),
});
});
+
+ describe('account limits (429)', () => {
+ // Production incident: four widgets of one account due in the same minute;
+ // two ran and two closed as terminal SANDBOX_ERROR until their next slot.
+ it('turns concurrency_limited into a retryable SANDBOX_BUSY with Market’s 5 s backoff', async () => {
+ const { runner } = setup(async () => {
+ throw apiError(429, {
+ error: 'concurrency_limited',
+ error_description: 'Too many concurrent sandbox runs',
+ });
+ });
+
+ await expect(runner.run(request)).rejects.toMatchObject({
+ code: 'SANDBOX_BUSY',
+ message: expect.stringContaining('concurrency_limited'),
+ retryAfterMs: 5000,
+ });
+ });
+
+ it('waits out the rest of Market’s epoch-aligned minute for rate_limited', () => {
+ const error = apiError(429, { error: 'rate_limited' });
+ expect(marketRetryAfterMs(error, 'rate_limited', 60_000 * 1000 + 45_000)).toBe(15_000);
+ // Never less than a second, even at the very end of the window.
+ expect(marketRetryAfterMs(error, 'rate_limited', 60_000 * 1000 + 59_999)).toBe(1000);
+ });
+
+ it('prefers a retry_after hint in the body, capped at a minute', () => {
+ expect(
+ marketRetryAfterMs(
+ apiError(429, { error: 'rate_limited', retry_after: 7 }),
+ 'rate_limited',
+ ),
+ ).toBe(7000);
+ expect(
+ marketRetryAfterMs(
+ apiError(429, { error: 'x', retry_after: '2.5' }),
+ 'concurrency_limited',
+ ),
+ ).toBe(2500);
+ expect(
+ marketRetryAfterMs(apiError(429, { error: 'x', retry_after: 3600 }), 'rate_limited'),
+ ).toBe(60_000);
+ expect(
+ marketRetryAfterMs(apiError(429, { error: 'x', retry_after: -1 }), 'concurrency_limited'),
+ ).toBe(5000);
+ });
+ });
+
+ describe('plan-based concurrency claim', () => {
+ it('defaults to no claim in the open-source build', async () => {
+ await expect(
+ resolveSandboxRunLimits({ userId: 'user-1', workspaceId: 'ws-1' }),
+ ).resolves.toBe(null);
+ });
+
+ it('resolves the limits for the run’s actor and hands them to the Market client', async () => {
+ const resolveLimits = vi.fn(async () => ({ maxConcurrency: 5 }));
+ const { runner, sandboxFor } = setup(async () => result, resolveLimits);
+
+ await runner.run(request);
+
+ expect(resolveLimits).toHaveBeenCalledWith({ userId: 'user-1', workspaceId: 'ws-1' });
+ expect(sandboxFor).toHaveBeenCalledWith(
+ { userId: 'user-1', workspaceId: 'ws-1' },
+ { maxConcurrency: 5 },
+ );
+ });
+
+ it('runs without a claim when the lookup fails or answers something Market would reject', async () => {
+ for (const resolveLimits of [
+ vi.fn(async () => {
+ throw new Error('billing down');
+ }),
+ vi.fn(async () => ({ maxConcurrency: 0 })),
+ vi.fn(async () => ({ maxConcurrency: 2.5 })),
+ ]) {
+ const { runner, sandboxFor } = setup(async () => result, resolveLimits);
+ await expect(runner.run(request)).resolves.toMatchObject({ exitCode: 0 });
+ expect(sandboxFor).toHaveBeenCalledWith(expect.anything(), null);
+ }
+ });
+
+ it('signs the claim onto the actor’s trusted-client token by default', async () => {
+ const run = vi.fn(async () => result);
+ vi.mocked(MarketService).mockImplementation(function () {
+ return { market: { sandbox: { run } } } as any;
+ });
+ const runner = new MarketWidgetSandboxRunner({
+ isEnabled: () => true,
+ resolveLimits: async () => ({ maxConcurrency: 5 }),
+ });
+
+ await runner.run(request);
+
+ expect(MarketService).toHaveBeenCalledWith({
+ userInfo: { sandboxRun: { maxConcurrency: 5 }, userId: 'user-1', workspaceId: 'ws-1' },
+ });
+ expect(run).toHaveBeenCalledTimes(1);
+ });
+ });
});
diff --git a/apps/server/src/services/widget/sandbox/market.ts b/apps/server/src/services/widget/sandbox/market.ts
index fe04db21d26..3ca38a3a869 100644
--- a/apps/server/src/services/widget/sandbox/market.ts
+++ b/apps/server/src/services/widget/sandbox/market.ts
@@ -1,6 +1,7 @@
import { MarketAPIError, type MarketSDK } from '@lobehub/market-sdk';
import debug from 'debug';
+import { resolveSandboxRunLimits, type SandboxRunLimits } from '@/business/server/sandboxRun';
import { isTrustedClientEnabled } from '@/libs/trusted-client';
import { MarketService } from '@/server/services/market';
@@ -21,15 +22,67 @@ type SandboxClient = Pick<MarketSDK['sandbox'], 'run'>;
export interface MarketWidgetSandboxRunnerOptions {
/** Defaults to `isTrustedClientEnabled`: Market only accepts trusted clients here. */
isEnabled?: () => boolean;
- /** Defaults to the Market SDK acting as the run's actor. */
- sandboxFor?: (actor: WidgetSandboxActor) => SandboxClient;
+ /** Defaults to the `sandboxRun` business hook (the actor's plan). */
+ resolveLimits?: (actor: WidgetSandboxActor) => Promise<SandboxRunLimits | null>;
+ /**
+ * Defaults to the Market SDK acting as the run's actor, with the resolved
+ * limits signed onto its trusted-client token as the `sandboxRun` claim.
+ */
+ sandboxFor?: (actor: WidgetSandboxActor, limits: SandboxRunLimits | null) => SandboxClient;
}
-const defaultSandboxFor = (actor: WidgetSandboxActor): SandboxClient =>
+const defaultSandboxFor = (
+ actor: WidgetSandboxActor,
+ limits: SandboxRunLimits | null,
+): SandboxClient =>
new MarketService({
- userInfo: { userId: actor.userId, workspaceId: actor.workspaceId ?? undefined },
+ userInfo: {
+ sandboxRun: limits,
+ userId: actor.userId,
+ workspaceId: actor.workspaceId ?? undefined,
+ },
}).market.sandbox;
+const defaultResolveLimits = (actor: WidgetSandboxActor) =>
+ resolveSandboxRunLimits({ userId: actor.userId, workspaceId: actor.workspaceId ?? null });
+
+/** Market's fixed backoff for `concurrency_limited`, used when it sends no hint we can read. */
+const CONCURRENCY_RETRY_AFTER_MS = 5000;
+/** Market's rate window: fixed, epoch-aligned minutes. */
+const RATE_WINDOW_MS = 60_000;
+
+/**
+ * When Market expects the account to have room again. Market sends the hint as
+ * a `Retry-After` header, which the SDK error does not carry, so a body field
+ * (`retry_after`, seconds) is read when present and otherwise Market's own
+ * rules are mirrored: a fixed 5 s for concurrency, the rest of the current
+ * epoch-aligned minute for rate.
+ */
+export const marketRetryAfterMs = (
+ error: MarketAPIError,
+ code: string,
+ now: number = Date.now(),
+): number => {
+ const hinted = (error.errorBody as { retry_after?: unknown } | undefined)?.retry_after;
+ const seconds = typeof hinted === 'string' ? Number(hinted) : hinted;
+ if (typeof seconds === 'number' && Number.isFinite(seconds) && seconds > 0) {
+ return Math.min(Math.ceil(seconds * 1000), RATE_WINDOW_MS);
+ }
+ if (code === 'rate_limited') return Math.max(1000, RATE_WINDOW_MS - (now % RATE_WINDOW_MS));
+ return CONCURRENCY_RETRY_AFTER_MS;
+};
+
+/**
+ * Only a positive integer is a claim Market accepts — anything else makes it
+ * reject the whole token — so a malformed answer degrades to no claim.
+ */
+const sanitizeLimits = (limits: SandboxRunLimits | null | undefined): SandboxRunLimits | null => {
+ const max = limits?.maxConcurrency;
+ return typeof max === 'number' && Number.isSafeInteger(max) && max > 0
+ ? { maxConcurrency: max }
+ : null;
+};
+
/** Market's error body: `{ error: '<code>', error_description?: '…' }`. */
const describeMarketError = (error: MarketAPIError) => {
const body = error.errorBody as { error?: unknown; error_description?: unknown } | undefined;
@@ -50,13 +103,25 @@ const describeMarketError = (error: MarketAPIError) => {
*/
export class MarketWidgetSandboxRunner implements WidgetSandboxRunner {
private readonly isEnabled: () => boolean;
- private readonly sandboxFor: (actor: WidgetSandboxActor) => SandboxClient;
+ private readonly resolveLimits: NonNullable<MarketWidgetSandboxRunnerOptions['resolveLimits']>;
+ private readonly sandboxFor: NonNullable<MarketWidgetSandboxRunnerOptions['sandboxFor']>;
constructor(options: MarketWidgetSandboxRunnerOptions = {}) {
this.isEnabled = options.isEnabled ?? isTrustedClientEnabled;
+ this.resolveLimits = options.resolveLimits ?? defaultResolveLimits;
this.sandboxFor = options.sandboxFor ?? defaultSandboxFor;
}
+ /** Never throws: a failed plan lookup runs at Market's default concurrency instead. */
+ private async limitsFor(actor: WidgetSandboxActor): Promise<SandboxRunLimits | null> {
+ try {
+ return sanitizeLimits(await this.resolveLimits(actor));
+ } catch (error) {
+ log('sandbox run limits lookup failed for %s: %O', actor.userId, error);
+ return null;
+ }
+ }
+
async run(request: WidgetSandboxRunRequest): Promise<WidgetSandboxRunResult> {
if (!this.isEnabled()) {
throw new WidgetSandboxError(
@@ -66,8 +131,9 @@ export class MarketWidgetSandboxRunner implements WidgetSandboxRunner {
}
const timeoutMs = clampSandboxTimeout(request.timeoutMs);
+ const limits = await this.limitsFor(request.actor);
try {
- const result = await this.sandboxFor(request.actor).run(
+ const result = await this.sandboxFor(request.actor, limits).run(
{
egress: {
allow: request.network.allow,
@@ -111,6 +177,17 @@ export class MarketWidgetSandboxRunner implements WidgetSandboxRunner {
`Sandbox rejected the credentials (${message})`,
);
}
+ // The account is at its concurrency or rate limit: the run is fine, it
+ // just has to wait for a slot. Callers queue or retry it.
+ if (error.status === 429 || code === 'concurrency_limited' || code === 'rate_limited') {
+ throw new WidgetSandboxError(
+ 'SANDBOX_BUSY',
+ `Sandbox is busy for this account: ${message}`,
+ {
+ retryAfterMs: marketRetryAfterMs(error, code),
+ },
+ );
+ }
if (error.status === 400 || error.status === 422) {
throw new WidgetSandboxError(
'SANDBOX_BAD_REQUEST',
diff --git a/apps/server/src/services/widget/sandbox/types.ts b/apps/server/src/services/widget/sandbox/types.ts
index 1d3d50338aa..a366a2456c3 100644
--- a/apps/server/src/services/widget/sandbox/types.ts
+++ b/apps/server/src/services/widget/sandbox/types.ts
@@ -78,19 +78,38 @@ export interface WidgetSandboxRunner {
}
export type WidgetSandboxErrorCode =
- 'SANDBOX_BAD_REQUEST' | 'SANDBOX_ERROR' | 'SANDBOX_NOT_CONFIGURED' | 'SANDBOX_UNAUTHORIZED';
+ | 'SANDBOX_BAD_REQUEST'
+ | 'SANDBOX_BUSY'
+ | 'SANDBOX_ERROR'
+ | 'SANDBOX_NOT_CONFIGURED'
+ | 'SANDBOX_UNAUTHORIZED';
-/** The sandbox could not execute the script at all (as opposed to the script failing). */
+/**
+ * The sandbox could not execute the script at all (as opposed to the script failing).
+ *
+ * `SANDBOX_BUSY` is the one transient code: the actor's account is at its
+ * concurrency or rate limit and the same request will run once a slot frees
+ * up. `retryAfterMs` says when that is expected.
+ */
export class WidgetSandboxError extends Error {
+ public readonly retryAfterMs?: number;
+
constructor(
public readonly code: WidgetSandboxErrorCode,
message: string,
+ options: { retryAfterMs?: number } = {},
) {
super(message);
this.name = 'WidgetSandboxError';
+ this.retryAfterMs = options.retryAfterMs;
}
}
+export const isWidgetSandboxBusy = (
+ error: unknown,
+): error is WidgetSandboxError & { code: 'SANDBOX_BUSY' } =>
+ error instanceof WidgetSandboxError && error.code === 'SANDBOX_BUSY';
+
export const clampSandboxTimeout = (timeoutMs?: number) => {
if (!timeoutMs || !Number.isFinite(timeoutMs) || timeoutMs <= 0) {
return WIDGET_SANDBOX_DEFAULT_TIMEOUT_MS;
diff --git a/apps/server/src/services/widget/sandboxBusy.ts b/apps/server/src/services/widget/sandboxBusy.ts
new file mode 100644
index 00000000000..f5620ea8946
--- /dev/null
+++ b/apps/server/src/services/widget/sandboxBusy.ts
@@ -0,0 +1,74 @@
+import type { WidgetRow, WidgetRunRow } from '@/database/schemas';
+
+import { isWidgetSandboxBusy } from './sandbox/types';
+import { nextScheduleOccurrence } from './schedule';
+
+/**
+ * What a run does when the sandbox answers `SANDBOX_BUSY` (the account is at
+ * its concurrency or rate limit):
+ *
+ * - someone is waiting on the request (`manual`, `preview`): retry in process,
+ * honouring the hint, a few times and well inside the request budget, then
+ * fail with `SANDBOX_BUSY`;
+ * - a `schedule` run: leave the reservation `running`, so the scheduler's
+ * stale-lease recovery picks it up again once its lease expires (a couple of
+ * minutes), until {@link busyDeferralDeadline} — then close it as failed.
+ */
+
+/** Attempts a waiting caller's run makes in total, the first included. */
+export const WIDGET_BUSY_MAX_ATTEMPTS = 3;
+/** Total time a waiting caller's run may spend waiting for a slot. */
+export const WIDGET_BUSY_RETRY_BUDGET_MS = 30_000;
+/** Used when the sandbox gave no hint. */
+export const WIDGET_BUSY_DEFAULT_RETRY_AFTER_MS = 5000;
+/** Spread so two runs turned away together do not collide again. */
+const WIDGET_BUSY_RETRY_JITTER_MS = 500;
+/** How long a scheduled run keeps waiting for a slot after it was reserved. */
+export const WIDGET_BUSY_DEFER_DEADLINE_MS = 30 * 60 * 1000;
+
+const sleep = (ms: number) =>
+ new Promise<void>((resolve) => {
+ setTimeout(resolve, ms);
+ });
+
+/**
+ * Run `attempt`, retrying while it throws `SANDBOX_BUSY` — at most
+ * {@link WIDGET_BUSY_MAX_ATTEMPTS} attempts and
+ * {@link WIDGET_BUSY_RETRY_BUDGET_MS} of waiting in total. A wait that would
+ * overrun the budget is not started: the busy error is rethrown at once.
+ */
+export const runWithBusyRetry = async <T>(attempt: () => Promise<T>): Promise<T> => {
+ let waited = 0;
+ for (let attempts = 1; ; attempts += 1) {
+ try {
+ return await attempt();
+ } catch (error) {
+ if (!isWidgetSandboxBusy(error) || attempts >= WIDGET_BUSY_MAX_ATTEMPTS) throw error;
+ const wait =
+ (error.retryAfterMs ?? WIDGET_BUSY_DEFAULT_RETRY_AFTER_MS) +
+ Math.floor(Math.random() * WIDGET_BUSY_RETRY_JITTER_MS);
+ if (waited + wait > WIDGET_BUSY_RETRY_BUDGET_MS) throw error;
+ await sleep(wait);
+ waited += wait;
+ }
+ }
+};
+
+/**
+ * Until when a busy scheduled run may stay deferred: 30 minutes after it was
+ * reserved, or the widget's next slot after that, whichever comes first — the
+ * next slot reserves a fresh run, and two runs of one widget waiting for the
+ * same account's slots only make the queue longer. Without a reservation time
+ * (not a reserved run) there is nothing to defer.
+ */
+export const busyDeferralDeadline = (
+ run: Partial<Pick<WidgetRunRow, 'createdAt'>>,
+ widget: Partial<Pick<WidgetRow, 'schedulePattern' | 'scheduleTimezone'>>,
+): Date | undefined => {
+ if (!run.createdAt) return undefined;
+ const byAge = new Date(run.createdAt.getTime() + WIDGET_BUSY_DEFER_DEADLINE_MS);
+ const nextSlot = widget.schedulePattern
+ ? nextScheduleOccurrence(widget.schedulePattern, widget.scheduleTimezone, run.createdAt)
+ : null;
+ return nextSlot && nextSlot < byAge ? nextSlot : byAge;
+};
diff --git a/apps/server/src/services/widget/scheduler.ts b/apps/server/src/services/widget/scheduler.ts
index 9cf166d4c51..b8174433fb2 100644
--- a/apps/server/src/services/widget/scheduler.ts
+++ b/apps/server/src/services/widget/scheduler.ts
@@ -7,7 +7,7 @@ import type { WidgetRow, WidgetRunRow, WidgetVersionRow } from '@/database/schem
import type { LobeChatDatabase } from '@/database/type';
import { GoalSubscriptionService } from '../goal/subscriptions';
-import { executeWidgetRun, type ExecuteWidgetRunDeps } from './executeRun';
+import { type ExecuteWidgetRunDeps, executeWidgetRunDetailed } from './executeRun';
import { widgetRunLeaseMs } from './lease';
import { nextScheduleOccurrence } from './schedule';
@@ -67,7 +67,14 @@ export interface WidgetTickResult {
claimed: number;
dispatched: number;
due: number;
- results: { error?: string; runId?: string; status?: WidgetRunStatus; widgetId: string }[];
+ results: {
+ /** The sandbox was busy; the run stays reserved and is resumed after its lease. */
+ deferred?: true;
+ error?: string;
+ runId?: string;
+ status?: WidgetRunStatus;
+ widgetId: string;
+ }[];
/** Stale reservations taken over (inline) or handed to a worker to resume (queue mode). */
resumed: number;
}
@@ -123,6 +130,8 @@ const takeOver = async (
export type DispatchedWidgetResult =
| {
+ /** The sandbox was busy: the run stays reserved and is resumed after its lease. */
+ deferred?: true;
/** The run was a stale reservation taken over rather than a fresh claim. */
resumed?: boolean;
run: WidgetRunRow | undefined;
@@ -158,7 +167,7 @@ export const runDispatchedWidget = async (
widgetId: live.widget.id,
});
if (reserved) {
- return { run: await executeWidgetRun(db, { ...live, run: reserved }, deps) };
+ return executeWidgetRunDetailed(db, { ...live, run: reserved }, deps);
}
const [stale] = await findStaleRuns(db, now, { limit: 1, widgetId: target.widgetId });
@@ -168,7 +177,7 @@ export const runDispatchedWidget = async (
return { skipped: 'already-claimed' };
}
- return { resumed: true, run: await executeWidgetRun(db, resumed, deps) };
+ return { resumed: true, ...(await executeWidgetRunDetailed(db, resumed, deps)) };
};
/**
@@ -190,7 +199,7 @@ export const resumeDispatchedRun = async (
const resumed = stale && (await takeOver(db, stale));
if (!resumed) return { skipped: 'not-resumable' };
- return { resumed: true, run: await executeWidgetRun(db, resumed, deps) };
+ return { resumed: true, ...(await executeWidgetRunDetailed(db, resumed, deps)) };
};
/**
@@ -204,7 +213,9 @@ export const resumeDispatchedRun = async (
* concurrency.
*
* Stale reservations: scheduled runs left `running` past their lease because
- * their worker died. Each tick resumes a bounded batch — handed to a worker
+ * their worker died, or because the sandbox was busy for the widget owner's
+ * account and the run was deferred (see `executeWidgetRunDetailed`) — the
+ * lease doubles as the backoff. Each tick resumes a bounded batch — handed to a worker
* in queue mode (deduplicated per lease), taken over and executed inline
* otherwise.
*
@@ -286,9 +297,14 @@ export const runWidgetSchedulerTick = async (
runnable,
async (target): Promise<WidgetTickResult['results'][number]> => {
try {
- const run = await executeWidgetRun(db, target, deps);
+ const { deferred, run } = await executeWidgetRunDetailed(db, target, deps);
dispatched += 1;
- return { runId: target.run.id, status: run?.status, widgetId: target.widget.id };
+ return {
+ ...(deferred && { deferred }),
+ 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);
diff --git a/packages/builtin-tool-dashboard/src/ExecutionRuntime/index.ts b/packages/builtin-tool-dashboard/src/ExecutionRuntime/index.ts
index fc75f2117a5..ddb2b92b037 100644
--- a/packages/builtin-tool-dashboard/src/ExecutionRuntime/index.ts
+++ b/packages/builtin-tool-dashboard/src/ExecutionRuntime/index.ts
@@ -111,6 +111,8 @@ const ERROR_HINTS: Record<string, string> = {
'The script reported an incomplete result (meta.complete=false). Fine if intended; otherwise fix the failing source.',
SANDBOX_BAD_REQUEST:
'The sandbox rejected the request; check runtime and manifest.timeoutMs (max 120000). "secret_not_found" means a LobeHub Market connector is not connected on Market for this account: ask the user to reconnect it.',
+ SANDBOX_BUSY:
+ "The account's sandbox slots stayed busy with other widget runs (already retried for a while). Not a script problem: wait a minute and dry-run again; do not change the script.",
SANDBOX_ERROR: 'The sandbox itself failed, not the script. Retry the dry run once.',
SANDBOX_NOT_CONFIGURED:
'Script execution is not configured on this server. Tell the user; do not retry.',
diff --git a/packages/business-server/src/sandboxRun.ts b/packages/business-server/src/sandboxRun.ts
new file mode 100644
index 00000000000..9eb7818c0f8
--- /dev/null
+++ b/packages/business-server/src/sandboxRun.ts
@@ -0,0 +1,20 @@
+/**
+ * How many one-shot sandbox runs (widget scripts) this caller may have in
+ * flight at once, or `null` to leave it to the execution plane's default —
+ * which is the only behaviour the open-source build has.
+ *
+ * A deployment that sells more concurrency overrides this module to answer
+ * from whatever it uses to decide entitlements. The answer is signed onto the
+ * trusted-client token as the `sandboxRun` claim; the execution plane still
+ * applies its own ceiling, so this can only ask for up to what it allows.
+ */
+export interface SandboxRunLimits {
+ /** Concurrent one-shot runs allowed for the account; a positive integer. */
+ maxConcurrency: number;
+}
+
+export const resolveSandboxRunLimits = async (_params: {
+ userId: string;
+ /** Organization workspace the run is scoped to; it is judged, not the acting member. */
+ workspaceId?: string | null;
+}): Promise<SandboxRunLimits | null> => null;
diff --git a/packages/types/src/widget/index.ts b/packages/types/src/widget/index.ts
index aa3902060c0..4f96ffe603a 100644
--- a/packages/types/src/widget/index.ts
+++ b/packages/types/src/widget/index.ts
@@ -265,7 +265,7 @@ export const WIDGET_RUN_OUTPUT_STATUSES = [
] as const satisfies readonly WidgetRunFinalStatus[];
export interface WidgetRunError {
- /** Machine-readable reason, e.g. 'INVALID_OUTPUT', 'SANDBOX_ERROR', 'NON_ZERO_EXIT'. */
+ /** Machine-readable reason, e.g. 'INVALID_OUTPUT', 'SANDBOX_ERROR', 'SANDBOX_BUSY', 'NON_ZERO_EXIT'. */
code: string;
message: string;
}
diff --git a/src/libs/trusted-client/index.test.ts b/src/libs/trusted-client/index.test.ts
index 67a2f855a94..d122e5a3b43 100644
--- a/src/libs/trusted-client/index.test.ts
+++ b/src/libs/trusted-client/index.test.ts
@@ -89,4 +89,26 @@ describe('generateTrustedClientToken', () => {
const [payload] = vi.mocked(createTrustedClientToken).mock.calls[0];
expect(payload).not.toHaveProperty('sandboxStorage');
});
+
+ // Market sizes the account's one-shot run concurrency from this claim, so it
+ // must be signed — and absent unless a plan grants something.
+ it('signs the sandbox run concurrency claim only when one is granted', () => {
+ generateTrustedClientToken({ sandboxRun: { maxConcurrency: 5 }, userId: 'user_real' });
+
+ expect(createTrustedClientToken).toHaveBeenCalledWith(
+ expect.objectContaining({ sandboxRun: { maxConcurrency: 5 } }),
+ 'client-secret',
+ );
+ expect(buildTrustedClientPayload).toHaveBeenCalledWith(
+ expect.not.objectContaining({ sandboxRun: expect.anything() }),
+ );
+
+ vi.mocked(createTrustedClientToken).mockClear();
+ generateTrustedClientToken({ sandboxRun: null, userId: 'user_real' });
+ generateTrustedClientToken({ userId: 'user_real' });
+
+ for (const [payload] of vi.mocked(createTrustedClientToken).mock.calls) {
+ expect(payload).not.toHaveProperty('sandboxRun');
+ }
+ });
});
diff --git a/src/libs/trusted-client/index.ts b/src/libs/trusted-client/index.ts
index 101ae538d71..e3eb2983114 100644
--- a/src/libs/trusted-client/index.ts
+++ b/src/libs/trusted-client/index.ts
@@ -5,6 +5,7 @@ import {
type TrustedClientPayload,
} from '@lobehub/market-sdk';
+import type { SandboxRunLimits } from '@/business/server/sandboxRun';
import { appEnv } from '@/envs/app';
export interface TrustedClientUserInfo {
@@ -19,6 +20,13 @@ export interface TrustedClientUserInfo {
* thing the execution plane must not let a caller choose for itself.
*/
sandboxOperation?: { operationId: string; topicId: string };
+ /**
+ * One-shot sandbox run entitlement (per-account concurrency) for this
+ * principal, resolved by `resolveSandboxRunLimits`. Absent means the
+ * execution plane's default; like `sandboxStorage`, it rides the signed token
+ * because a caller must not choose it for itself.
+ */
+ sandboxRun?: SandboxRunLimits | null;
sandboxStorage?: SandboxStorageClaim | null;
userId: string;
/**
@@ -94,6 +102,7 @@ export const generateTrustedClientToken = (userInfo: TrustedClientUserInfo): str
...payload,
...(userInfo.sandboxStorage && { sandboxStorage: userInfo.sandboxStorage }),
...(userInfo.sandboxOperation && { sandboxOperation: userInfo.sandboxOperation }),
+ ...(userInfo.sandboxRun && { sandboxRun: userInfo.sandboxRun }),
};
return createTrustedClientToken(signedPayload, MARKET_TRUSTED_CLIENT_SECRET);