Skip to content

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

โœจ feat(topic): schedule a hetero agent run for later ("send in N hours") (#17127)

Arvin Xu1ced57852ad0
diff --git a/.agents/skills/agent-testing/references/probe-mock-patterns.md b/.agents/skills/agent-testing/references/probe-mock-patterns.md
index 0c3b6218533..c1e75ea2ff8 100644
--- a/.agents/skills/agent-testing/references/probe-mock-patterns.md
+++ b/.agents/skills/agent-testing/references/probe-mock-patterns.md
@@ -1165,3 +1165,75 @@ nodeintegration, plugins, disablewebsecurity, allowpopups, preload, โ€ฆ`). The h
`scripts/test-env.sh` after the server is up, it reads the ports-file. And
the `os error 35` agent-browser daemon wedge (D8) recovers with
`agent-browser close --all` + re-running `setup-auth.sh web-seed`.
+
+### C7. `document.body.innerText` is ALWAYS 0 in this app โ€” probe `#root`, and use textContent to tell a wedge from a blank
+
+- **Situation**: asserting rendered text with `document.body.innerText.includes(...)`. It returns `""` / length 0 even on a fully rendered page, so every text assertion silently fails and reads as "the page is blank".
+- **Works**: probe `document.getElementById('root').innerText`. (Cause not established โ€” some ancestor of `#root` makes body's inner-text computation collapse; `#root` itself is fine.)
+- **Bonus diagnostic**: `innerText` needs layout, `textContent` does not. When `#root` gives `innerText === 0` but `textContent > 0`, the DOM is fine and the RENDERER is not painting (see D16) โ€” as opposed to a genuinely empty DOM, where both are 0.
+
+### D16. Electron renderer compositor wedges after a mid-session Vite dep re-optimize โ€” restart the instance
+
+- **Situation**: partway through a long Electron run the app stops painting: `cdp-screenshot.sh` returns `CAPTURED BUT BLACK`, `#root` `innerText` is 0 while `textContent` still holds the full DOM, and `document.visibilityState` reports `visible` with real `innerWidth/innerHeight`.
+- **Not the cause**: display sleep or Screen Recording permission (`check-screen-recording.sh` passes), and the window is not hidden โ€” CDP capture would survive both (D9/D10).
+- **What precedes it**: the instance log shows Vite re-optimizing (`[vite] Re-optimizing dependencies because vite config has changed`) followed by `Failed to fetch dynamically imported module: .../node_modules/.vite/deps/โ€ฆ`. The renderer keeps its DOM but never composites another frame.
+- **Works**: `electron-dev.sh restart <id>`. `location.reload()` alone does NOT clear it. Login survives the restart (the userData dir is kept).
+
+### D17. Virtua message lists: driving `scrollTop` by hand blanks the conversation pane โ€” use a SMALL fixture instead
+
+- **Situation**: hunting one specific message in a long imported conversation (400+ messages). Stepping `scrollContainer.scrollTop` in a loop to bring it into the virtualizer's window.
+- **Doesn't work**: the virtualizer unmounts the node as you scroll past it (a `TreeWalker` search then reports "not found" on a node that was there a second ago), and forcing `scrollTop` far outside the rendered window leaves the pane **completely blank** โ€” the scroll container itself disappears from the DOM, which reads exactly like a render bug.
+- **Works**: pick a fixture with few messages so the target is on the first screen (for transcript-import tests: scan the corpus for a session with < \~15 messages that still has the feature under test). Cheaper and far more reliable than fighting the virtualizer.
+
+### D18. React controlled checkboxes ignore synthetic MouseEvents โ€” use `agent-browser click <ref>` (trusted CDP input)
+
+- **Situation**: selecting a row in a modal list. `el.click()`, and even a full `pointerdown/mousedown/pointerup/mouseup/click` `dispatchEvent` sequence with correct coordinates, leave `checked === false` and the footer's primary button disabled.
+- **Cause**: the value is React-controlled; synthetic events are `isTrusted: false` and the component's state never updates.
+- **Works**: `agent-browser snapshot -i` for the ref, then `agent-browser click <ref>` โ€” it goes through CDP `Input.dispatchMouseEvent`, which the page sees as a real user click. The same snapshot also tells you when a row is `[disabled]` (i.e. the app is deliberately refusing the selection), which a coordinate-click would never reveal.
+
+### E20. Killing the dev server mid-write corrupts `.next/dev` โ€” every route 404s and `/` โ†” `/signin` ping-pong
+
+- **Situation**: after `init-dev-env.sh clean` (or any kill) and a restart, the whole app is broken: `/` 302s to `/signin`, `/signin` 307s back to `/` (`ERR_TOO_MANY_REDIRECTS` in the browser, `redirect count exceeded` in the dev server's own prewarm), and even API routes like `/api/auth/sign-in/email` return the app-router not-found. It looks like an auth/OIDC misconfiguration.
+- **Cause**: a corrupt Turbopack build in `.next/dev` โ€” the route manifest is gone, so every path falls through to `GlobalNotFound`, whose redirect collides with the middleware's.
+- **Works**: `rm -rf .next` then restart. Diagnose it in one step: if `/signin` does not return 200, the routes are not compiled โ€” stop debugging auth.
+
+### E21. โœ… WORKS โ€” a QStash-protected workflow endpoint can't be curl'd; publish through local QStash to get a signed delivery
+
+- **Situation**: driving a cron-style workflow handler under `/api/workflows/**` (e.g. a dispatcher you want to fire on demand instead of waiting for its schedule).
+- **Doesn't work**: `curl -X POST <app>/api/workflows/<...>` โ†’ `{"error":"Invalid signature"}` / HTTP 401. The `qstashAuth` middleware verifies the Upstash signature whenever `QSTASH_CURRENT_SIGNING_KEY` is set โ€” and `init-dev-env.sh` exports it, so the local env DOES verify. (Do not "fix" this by unsetting the key: you would then be testing an unauthenticated path that production doesn't have.)
+- **Works**: start local QStash (`init-dev-env.sh qstash`) and publish to the endpoint with the QStash client โ€” QStash signs the delivery, so the handler sees exactly the production shape:
+ ```ts
+ // must live INSIDE the repo (a script under /tmp cannot resolve @upstash/qstash)
+ import { Client } from '@upstash/qstash';
+ const client = new Client({ baseUrl: process.env.QSTASH_URL!, token: process.env.QSTASH_TOKEN! });
+ await client.publishJSON({
+ body: { dryRun: false },
+ url: `${process.env.APP_URL}/api/workflows/<path>`,
+ });
+ ```
+ Run it with `eval "$(init-dev-env.sh env)" && bunx tsx ./scripts/<probe>.mts`, then read the outcome from **DB side effects**, not the HTTP body โ€” QStash swallows the response. (A claim/lease row, a status transition, or new message rows are all observable; the handler's JSON return is not.)
+- **Time-travel a schedule instead of waiting**: for a "runs at T" feature, `UPDATE ... SET metadata = jsonb_set(metadata, '{...,runAt}', '"<past ISO>"')` and then fire the dispatcher. Cheaper and more deterministic than sleeping until the real due time.
+
+### E22. Local dev env has no `JWKS_KEY` โ€” every hetero agent run dies at `signOperationJwt`
+
+- **Situation**: a real Claude Code / Codex run in the local no-`.env` env fails immediately with `Failed to sign operation JWT for hetero agent` (`apps/server/src/services/aiAgent/index.ts`). Nothing in the UI explains it; the topic just fails.
+- **Cause**: `signOperationJwt` โ†’ `getSigningKey()` โ†’ `getJwksKey()` needs the `JWKS_KEY` RSA JWK, and `init-dev-env.sh` does not export one.
+- **Works**: the repo ships a generator โ€” `JWKS_KEY="$(node scripts/generate-oidc-jwk.mjs)" ./.agents/skills/agent-testing/scripts/init-dev-env.sh dev`. Must be present at dev-server **start** (it is read from `process.env`), so a running server has to be restarted.
+- **Note the failure is downstream-honest**: with `JWKS_KEY` set, the run proceeds and then fails at the hetero _sandbox_ (`Hetero sandbox spawn failed / unauthorized`) unless the agent has a real Claude Code token. Those are two different walls โ€” don't read the second as the first.
+
+### D19. A hidden zero-size duplicate of the composer sits at (0,0) โ€” `querySelector` grabs IT, not the visible one
+
+- **Situation**: driving the chat composer. `document.querySelector('[contenteditable]')` reads back `""` right after a successful `fill`, and `svg.lucide-plus` โ†’ `.closest('button')` resolves to a button whose click does nothing.
+- **Cause (measured, not guessed)**: the page renders a SECOND, hidden copy of the composer subtree at `x:0, y:0, width:0` โ€” including its own contenteditable and its own action-bar buttons. It is first in DOM order, so every `querySelector` singular lookup picks the phantom. The real one is the second match. Cause of the duplicate not established (likely a measurement/offscreen render), but the fingerprint is unambiguous: a `getBoundingClientRect()` of all-zeros.
+- **Doesn't work**: `document.querySelector('[contenteditable]')`, `document.querySelector('svg.lucide-plus')` โ€” both silently target the phantom. A `fill` that reports `โœ“ Done` can still leave the visible box empty-looking, and a click on the phantom button is a no-op with no error. This burned a full round chasing a "menu won't open" regression that did not exist.
+- **Works โ€” always disambiguate by geometry or by an identifying attribute**:
+ ```js
+ // enumerate, never singular-select
+ [...document.querySelectorAll('[contenteditable]')]
+ .filter(e => e.getBoundingClientRect().width > 0)[0]
+ // or target by the component's own aria-label (survives DOM order)
+ [...document.querySelectorAll('[role=button],button')]
+ .find(b => b.getAttribute('aria-label') === '<the tooltip text>')
+ ```
+ Tag the resolved element with a `data-probe` attribute and drive it with `agent-browser click '[data-probe=...]'` (trusted CDP input, D18).
+- **Corollary**: the phantom also owns the tooltip text of whatever component it duplicates, so an `innerText`/aria grep can "find" a control that the user cannot see. Assert on `getBoundingClientRect()` before believing a control is present.
diff --git a/apps/server/src/routers/lambda/aiAgent.ts b/apps/server/src/routers/lambda/aiAgent.ts
index 1bcec8c21ac..52cdeb60ae3 100644
--- a/apps/server/src/routers/lambda/aiAgent.ts
+++ b/apps/server/src/routers/lambda/aiAgent.ts
@@ -282,6 +282,35 @@ const ExecAgentsSchema = z.object({
tasks: z.array(ExecAgentSchema).min(1),
});
+/**
+ * Schema for scheduleAgentRun - defer an agent run to a future time
+ */
+const ScheduleAgentRunSchema = z
+ .object({
+ /** The agent ID to run (either agentId or slug is required) */
+ agentId: z.string().optional(),
+ /** File IDs of already-uploaded attachments to attach when the run fires */
+ fileIds: z.array(z.string()).optional(),
+ /** Group to file the topic under, when scheduling from a group conversation */
+ groupId: z.string().nullish(),
+ /** Override the agent's default model */
+ model: z.string().optional(),
+ /** The user input/prompt, replayed verbatim when the run comes due */
+ prompt: z.string().min(1),
+ /** Override the agent's default provider */
+ provider: z.string().optional(),
+ /**
+ * When to run. UTC ISO-8601 (`โ€ฆZ`) โ€” the dispatcher's due query compares it
+ * as text, so a zoned offset would break the ordering.
+ */
+ runAt: z.string().datetime(),
+ /** The agent slug to run (either agentId or slug is required) */
+ slug: z.string().optional(),
+ })
+ .refine((data) => data.agentId || data.slug, {
+ message: 'Either agentId or slug must be provided',
+ });
+
/**
* Schema for execSubAgentTask - execute SubAgent task
* Supports both Group mode (with groupId) and Single Agent mode (without groupId)
@@ -763,6 +792,35 @@ export const aiAgentRouter = router({
}
}),
+ /**
+ * Defer an agent run to a future time ("send this in 3 hours").
+ *
+ * Kept separate from `execAgent` rather than folded in behind a `runAt` flag:
+ * nothing is executed here, so every run-shaped field of `ExecAgentResult`
+ * (operationId, assistantMessageId, autoStarted) would come back empty and
+ * every caller would have to branch on it.
+ *
+ * Cancelling / rescheduling goes through the ordinary topic update mutations โ€”
+ * those are already ownership-scoped, and a schedule is just topic state.
+ */
+ scheduleAgentRun: aiAgentWriteProcedure
+ .input(ScheduleAgentRunSchema)
+ .mutation(async ({ input, ctx }) => {
+ log('scheduleAgentRun: identifier=%s, runAt=%s', input.agentId || input.slug, input.runAt);
+
+ try {
+ return await ctx.aiAgentService.scheduleAgentRun(input);
+ } catch (error: any) {
+ if (error instanceof TRPCError) throw error;
+
+ throw new TRPCError({
+ cause: error,
+ code: 'INTERNAL_SERVER_ERROR',
+ message: `Failed to schedule agent run: ${error.message}`,
+ });
+ }
+ }),
+
/**
* Batch execute multiple agents
* Supports parallel or sequential execution
diff --git a/apps/server/src/services/aiAgent/index.ts b/apps/server/src/services/aiAgent/index.ts
index 5239a4359b2..8afd4743143 100644
--- a/apps/server/src/services/aiAgent/index.ts
+++ b/apps/server/src/services/aiAgent/index.ts
@@ -54,6 +54,8 @@ import type {
LobeAgentConfig,
MessagePluginItem,
RuntimeMentionedAgent,
+ ScheduleAgentRunParams,
+ ScheduleAgentRunResult,
UserInterventionConfig,
WorkspaceInitResult,
} from '@lobechat/types';
@@ -964,6 +966,109 @@ export class AiAgentService {
return this.agentRuntimeService.completeGroupActionMember(params);
}
+ /**
+ * Resolve an agent by id or slug, with default config merged.
+ *
+ * Builtin agents (inbox / page / task / self-iteration slugs) may be addressed
+ * purely by slug before a row exists โ€” e.g. background self-iteration runs
+ * dispatched via `execAgent({ slug })`. Lazily materialize the virtual row from
+ * the builtin registry (mirrors the inbox/task `getBuiltinAgent` path) and
+ * re-resolve. No-op for ordinary agent ids (getBuiltinAgent returns null).
+ */
+ private async resolveAgentConfigOrThrow(identifier: string) {
+ let agentConfig = await this.agentService.getAgentConfig(identifier);
+ if (!agentConfig && (Object.values(BUILTIN_AGENT_SLUGS) as string[]).includes(identifier)) {
+ await this.agentModel.getBuiltinAgent(identifier);
+ agentConfig = await this.agentService.getAgentConfig(identifier);
+ }
+ if (!agentConfig) {
+ // `agentService.getAgentConfig` already routes through `AgentModel`'s
+ // workspace + visibility ownership predicate, so a cross-user private
+ // agent resolves to null here. Surface that as NOT_FOUND (not a generic
+ // 500) so callers โ€” chat, bot, cron task, sub-agent, REST โ€” return a
+ // uniform 404 and we never leak whether the id exists for another user.
+ throw new TRPCError({ code: 'NOT_FOUND', message: `Agent not found: ${identifier}` });
+ }
+
+ return agentConfig;
+ }
+
+ /**
+ * Defer an agent run to a future time ("send this in 3 hours").
+ *
+ * Creates the topic now, `scheduled` and empty, carrying the whole request in
+ * `metadata.scheduledRun`; the cron dispatcher replays it through `execAgent`
+ * once `runAt` passes. The prompt is deliberately NOT pre-persisted as a user
+ * message โ€” storing the request whole keeps the dispatch identical to a user
+ * pressing send, and keeps editing / cancelling a pending run a single JSONB
+ * write.
+ *
+ * One-shot only: recurring execution belongs to `tasks.automationMode = 'schedule'`.
+ */
+ async scheduleAgentRun(params: ScheduleAgentRunParams): Promise<ScheduleAgentRunResult> {
+ const { agentId, slug, prompt, runAt, fileIds, groupId, model, provider } = params;
+
+ if (!agentId && !slug) throw new Error('Either agentId or slug must be provided');
+
+ const runAtDate = new Date(runAt);
+ if (Number.isNaN(runAtDate.getTime())) {
+ throw new TRPCError({ code: 'BAD_REQUEST', message: `Invalid runAt: ${runAt}` });
+ }
+ if (runAtDate.getTime() <= Date.now()) {
+ throw new TRPCError({ code: 'BAD_REQUEST', message: 'runAt must be in the future' });
+ }
+
+ const agentConfig = await this.resolveAgentConfigOrThrow(agentId || slug!);
+ const resolvedAgentId = agentConfig.id;
+
+ const titleSource = markdownToTxt(prompt);
+ const topic = await this.topicModel.create({
+ agentId: resolvedAgentId,
+ groupId,
+ // A scheduled run is still an ordinary user chat, just deferred โ€” so it
+ // keeps the `chat` trigger and stays in the main sidebar (where its
+ // `scheduled` status renders a clock), unlike system-owned cron topics.
+ title: titleSource.slice(0, 50) + (titleSource.length > 50 ? '...' : ''),
+ trigger: 'chat',
+ });
+
+ // Persist the user turn now rather than stashing the prompt in metadata: the
+ // pending run then reads as the user's own words in the topic, and the message
+ // stays the single source of truth for the prompt (the dispatcher reads it
+ // back, so editing a pending run is just editing the message).
+ const userMessage = await this.messageModel.create({
+ agentId: resolvedAgentId,
+ content: prompt,
+ files: fileIds,
+ groupId: groupId ?? undefined,
+ metadata: { trigger: RequestTrigger.Scheduled },
+ role: 'user',
+ topicId: topic.id,
+ });
+
+ const now = new Date().toISOString();
+ await this.topicModel.armScheduledRun(topic.id, {
+ createdAt: now,
+ kind: 'delayed_start',
+ model,
+ provider,
+ // Normalize to UTC ISO: the dispatcher's due query compares this as text.
+ runAt: runAtDate.toISOString(),
+ updatedAt: now,
+ userMessageId: userMessage.id,
+ });
+
+ log(
+ 'scheduleAgentRun: topic %s scheduled for %s (agent %s, message %s)',
+ topic.id,
+ runAtDate.toISOString(),
+ resolvedAgentId,
+ userMessage.id,
+ );
+
+ return { agentId: resolvedAgentId, runAt: runAtDate.toISOString(), topicId: topic.id };
+ }
+
/**
* Execute agent with just a prompt
*
@@ -1067,24 +1172,7 @@ export class AiAgentService {
throwIfAborted(signal, 'Agent execution aborted before startup');
// 1. Get agent configuration with default config merged (supports both id and slug)
- let agentConfig = await this.agentService.getAgentConfig(identifier);
- // Builtin agents (inbox / page / task / self-iteration slugs) may be addressed
- // purely by slug before a row exists โ€” e.g. background self-iteration runs
- // dispatched via execAgent({ slug }). Lazily materialize the virtual row from
- // the builtin registry (mirrors the inbox/task `getBuiltinAgent` path) and
- // re-resolve. No-op for ordinary agent ids (getBuiltinAgent returns null).
- if (!agentConfig && (Object.values(BUILTIN_AGENT_SLUGS) as string[]).includes(identifier)) {
- await this.agentModel.getBuiltinAgent(identifier);
- agentConfig = await this.agentService.getAgentConfig(identifier);
- }
- if (!agentConfig) {
- // `agentService.getAgentConfig` already routes through `AgentModel`'s
- // workspace + visibility ownership predicate, so a cross-user private
- // agent resolves to null here. Surface that as NOT_FOUND (not a generic
- // 500) so callers โ€” chat, bot, cron task, sub-agent, REST โ€” return a
- // uniform 404 and we never leak whether the id exists for another user.
- throw new TRPCError({ code: 'NOT_FOUND', message: `Agent not found: ${identifier}` });
- }
+ const agentConfig = await this.resolveAgentConfigOrThrow(identifier);
// Use actual agent ID from config for subsequent operations
const resolvedAgentId = agentConfig.id;
diff --git a/locales/en-US/chat.json b/locales/en-US/chat.json
index c98cfad3be9..58d25925236 100644
--- a/locales/en-US/chat.json
+++ b/locales/en-US/chat.json
@@ -406,12 +406,21 @@
"input.costEstimate.tooltip": "Estimated from current context, tools, and model pricing. Actual cost may vary.",
"input.disclaimer": "Agents can make mistakes. Use your judgment for critical info.",
"input.errorMsg": "Send failed: {{errorMsg}}. Retry, or send again later.",
+ "input.heteroPlus.tooltip": "Formatting and scheduling",
"input.inputCompletionError.desc": "Input suggestions stopped after an error. Retry, or adjust the suggestion model in Settings.",
"input.inputCompletionError.retry": "Retry",
"input.inputCompletionError.settings": "Settings",
"input.inputCompletionError.title": "Input suggestions paused",
"input.modelUnavailable": "The current model is no longer available. Choose another model to continue.",
"input.more": "More",
+ "input.schedule.cancel": "Cancel",
+ "input.schedule.clear": "Cancel scheduled send",
+ "input.schedule.failed": "Could not schedule this message. Try again.",
+ "input.schedule.inHours": "In {{count}} hour",
+ "input.schedule.inHours_other": "In {{count}} hours",
+ "input.schedule.pending": "Will be sent at {{time}}",
+ "input.schedule.scheduled": "Scheduled for {{time}}",
+ "input.schedule.title": "Send later",
"input.send": "Send",
"input.sendWithCmdEnter": "Press <key/> to send",
"input.sendWithEnter": "Press <key/> to send",
diff --git a/locales/en-US/topic.json b/locales/en-US/topic.json
index 69bc8e46ca3..dd8888f2faa 100644
--- a/locales/en-US/topic.json
+++ b/locales/en-US/topic.json
@@ -180,6 +180,7 @@
"projectStatus.waitingForHuman_other": "{{count}} topics awaiting input",
"renameModal.description": "Keep it short and easy to recognize.",
"renameModal.title": "Rename Topic",
+ "scheduledStatusTip": "Scheduled to run at {{time}}.",
"searchPlaceholder": "Search Topics...",
"searchResultEmpty": "No search results found.",
"sidebar.collapseAll": "Collapse all groups",
diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.json
index 45e31372061..3d2ac2e10bb 100644
--- a/locales/zh-CN/chat.json
+++ b/locales/zh-CN/chat.json
@@ -406,12 +406,21 @@
"input.costEstimate.tooltip": "ๆ นๆฎๅฝ“ๅ‰ไธŠไธ‹ๆ–‡ใ€ๅทฅๅ…ทๅ’Œๆจกๅž‹ๅฎšไปทไผฐ็ฎ—ใ€‚ๅฎž้™…่ดน็”จๅฏ่ƒฝๆœ‰ๆ‰€ไธๅŒใ€‚",
"input.disclaimer": "ๅŠฉ็†ไนŸๅฏ่ƒฝๅ‡บ้”™ใ€‚ๅ…ณ้”ฎไฟกๆฏ่ฏทไปฅไฝ ็š„ๅˆคๆ–ญไธบๅ‡†",
"input.errorMsg": "ๅ‘้€้‡ๅˆฐไบ†้—ฎ้ข˜๏ผš{{errorMsg}}ใ€‚ไฝ ๅฏไปฅ้‡่ฏ•๏ผŒๆˆ–็จๅŽๅ†ๅ‘",
+ "input.heteroPlus.tooltip": "ๆ ผๅผๅทฅๅ…ทไธŽๅฎšๆ—ถๅ‘้€",
"input.inputCompletionError.desc": "่พ“ๅ…ฅ่กฅๅ…จ้‡ๅˆฐ้”™่ฏฏๅŽๅทฒๆš‚ๅœใ€‚่ฏท้‡่ฏ•๏ผŒๆˆ–ๅˆฐ่ฎพ็ฝฎไธญ่ฐƒๆ•ด่กฅๅ…จๆจกๅž‹ใ€‚",
"input.inputCompletionError.retry": "้‡่ฏ•",
"input.inputCompletionError.settings": "่ฎพ็ฝฎ",
"input.inputCompletionError.title": "่พ“ๅ…ฅ่กฅๅ…จๅทฒๆš‚ๅœ",
"input.modelUnavailable": "ๅฝ“ๅ‰ๆจกๅž‹ๅทฒไธ‹็บฟใ€‚่ฏท้€‰ๆ‹ฉๅ…ถไป–ๆจกๅž‹ๅŽ็ปง็ปญไฝฟ็”จใ€‚",
"input.more": "ๆ›ดๅคš",
+ "input.schedule.cancel": "ๅ–ๆถˆๆŽ’ๆœŸ",
+ "input.schedule.clear": "ๅ–ๆถˆๅฎšๆ—ถ",
+ "input.schedule.failed": "ๅฎšๆ—ถๅ‘้€ๅคฑ่ดฅ๏ผŒ่ฏท้‡่ฏ•",
+ "input.schedule.inHours": "{{count}} ๅฐๆ—ถๅŽ",
+ "input.schedule.inHours_other": "{{count}} ๅฐๆ—ถๅŽ",
+ "input.schedule.pending": "ๅฐ†ไบŽ {{time}} ๅ‘้€",
+ "input.schedule.scheduled": "ๅทฒๅฎšๆ—ถ่‡ณ {{time}}",
+ "input.schedule.title": "ๅฎšๆ—ถๅ‘้€",
"input.send": "ๅ‘้€",
"input.sendWithCmdEnter": "ๆŒ‰ <key/> ๅ‘้€",
"input.sendWithEnter": "ๆŒ‰ <key/> ๅ‘้€",
diff --git a/locales/zh-CN/topic.json b/locales/zh-CN/topic.json
index b9d62ba5556..aa99eb46386 100644
--- a/locales/zh-CN/topic.json
+++ b/locales/zh-CN/topic.json
@@ -180,6 +180,7 @@
"projectStatus.waitingForHuman_other": "{{count}} ไธช็ญ‰ๅพ…ๅค„็†็š„่ฏ้ข˜",
"renameModal.description": "ไฟๆŒ็ฎ€็Ÿญไธ”ๆ˜“ไบŽ่ฏ†ๅˆซใ€‚",
"renameModal.title": "้‡ๅ‘ฝๅ่ฏ้ข˜",
+ "scheduledStatusTip": "ๅฐ†ไบŽ {{time}} ่ฟ่กŒ",
"searchPlaceholder": "ๆœ็ดข่ฏ้ข˜โ€ฆ",
"searchResultEmpty": "ๆš‚ๆ— ๆœ็ดข็ป“ๆžœ",
"sidebar.collapseAll": "ๆŠ˜ๅ ๆ‰€ๆœ‰ๅˆ†็ป„",
diff --git a/packages/database/src/models/__tests__/jsonbNullTest.test.ts b/packages/database/src/models/__tests__/jsonbNullTest.test.ts
new file mode 100644
index 00000000000..90f06cb6c13
--- /dev/null
+++ b/packages/database/src/models/__tests__/jsonbNullTest.test.ts
@@ -0,0 +1,54 @@
+// @vitest-environment node
+import { readdirSync, readFileSync, statSync } from 'node:fs';
+import path from 'node:path';
+
+import { describe, expect, it } from 'vitest';
+
+/**
+ * Null-testing a jsonb arrow / path expression inside a WHERE clause crashes the
+ * engine backing production โ€” `rt_fetch used out-of-bounds`, SQLSTATE XX000 โ€”
+ * before a single row is read.
+ *
+ * Stock Postgres runs these predicates perfectly happily, so no test against a
+ * real database will ever catch one: `getDueScheduledTopics` shipped with full
+ * green model tests and its cron then crashed on every tick in production for
+ * days. A source-shape guard is the only thing that can hold the line, which is
+ * why this asserts on the text of the query rather than on its behavior.
+ *
+ * The fix is always the same โ€” COALESCE the extracted value to a sentinel:
+ *
+ * (metadata ->> 'x') IS NULL โ†’ COALESCE(metadata ->> 'x', '') = ''
+ * (metadata ->> 'x') IS NOT NULL โ†’ COALESCE(metadata ->> 'x', '') <> ''
+ * (metadata ->> 'x') IS DISTINCT FROM 'y' โ†’ COALESCE(metadata ->> 'x', '') <> 'y'
+ *
+ * Prior casualties: `getLatestSpineMessageId` (LOBE-11376, #16693),
+ * `getDueScheduledTopics` (#17077).
+ */
+const FORBIDDEN = /(?:->>?|#>>?)[^\n]*?\b(?:IS\s+(?:NOT\s+)?NULL|IS\s+DISTINCT\s+FROM)\b/i;
+
+const MODELS_DIR = path.join(import.meta.dirname, '..');
+
+const sourceFiles = (dir: string): string[] =>
+ readdirSync(dir).flatMap((entry) => {
+ const entryPath = path.join(dir, entry);
+ if (statSync(entryPath).isDirectory())
+ return entry === '__tests__' ? [] : sourceFiles(entryPath);
+ return entryPath.endsWith('.ts') ? [entryPath] : [];
+ });
+
+describe('jsonb null tests in WHERE clauses', () => {
+ it('are absent from every model โ€” they take the production engine down', () => {
+ const offenders = sourceFiles(MODELS_DIR).flatMap((file) =>
+ readFileSync(file, 'utf8')
+ .split('\n')
+ .map((line, index) => ({ file, line: line.trim(), lineNo: index + 1 }))
+ // Comments are where we explain the rule, so they get to name the shape.
+ .filter(
+ ({ line }) => FORBIDDEN.test(line) && !line.startsWith('*') && !line.startsWith('//'),
+ )
+ .map(({ file, line, lineNo }) => `${file.split('/models/')[1]}:${lineNo} ${line}`),
+ );
+
+ expect(offenders).toEqual([]);
+ });
+});
diff --git a/packages/database/src/models/__tests__/topic.test.ts b/packages/database/src/models/__tests__/topic.test.ts
index a90f2a24d62..3ea57a6136e 100644
--- a/packages/database/src/models/__tests__/topic.test.ts
+++ b/packages/database/src/models/__tests__/topic.test.ts
@@ -638,12 +638,13 @@ describe('TopicModel', () => {
});
});
- describe('scheduled continuation', () => {
+ describe('scheduled run', () => {
const scheduledRun = {
createdAt: '2026-07-12T00:00:00.000Z',
failedAssistantMessageId: 'assistant-failed',
+ kind: 'resume_after_rate_limit' as const,
rateLimit: { resetsAt: 100 },
- reason: 'rate_limit' as const,
+ runAt: '2026-07-12T00:00:00.000Z',
source: 'heterogeneous_agent' as const,
updatedAt: '2026-07-12T00:00:00.000Z',
userMessageId: 'user-message',
@@ -660,15 +661,34 @@ describe('TopicModel', () => {
},
{
id: 'scheduled-future',
- metadata: { scheduledRun: { ...scheduledRun, rateLimit: { resetsAt: 300 } } },
+ metadata: { scheduledRun: { ...scheduledRun, runAt: '2026-07-12T06:00:00.000Z' } },
status: 'scheduled',
title: 'future',
userId,
},
+ // A delayed_start due at the same instant โ€” the gate is kind-agnostic.
+ {
+ id: 'delayed-due',
+ metadata: {
+ scheduledRun: {
+ createdAt: '2026-07-12T00:00:00.000Z',
+ kind: 'delayed_start' as const,
+ runAt: '2026-07-12T00:00:00.000Z',
+ updatedAt: '2026-07-12T00:00:00.000Z',
+ userMessageId: 'user-scheduled',
+ },
+ },
+ status: 'scheduled',
+ title: 'delayed',
+ userId,
+ },
]);
- const due = await TopicModel.getDueScheduledTopics(serverDB, new Date(200_000));
- expect(due.map((topic) => topic.id)).toEqual(['scheduled-due']);
+ const due = await TopicModel.getDueScheduledTopics(
+ serverDB,
+ new Date('2026-07-12T00:01:00.000Z'),
+ );
+ expect(due.map((topic) => topic.id).sort()).toEqual(['delayed-due', 'scheduled-due']);
const claim = {
claimedAt: '2026-07-12T00:00:00.000Z',
@@ -693,6 +713,88 @@ describe('TopicModel', () => {
).toBe(false);
});
+ it('arms status and payload together, so a scheduled topic always has something to run', async () => {
+ const topic = await topicModel.create({ title: 'to schedule' });
+ expect(topic.status).toBeNull();
+
+ await topicModel.armScheduledRun(topic.id, {
+ createdAt: '2026-07-12T00:00:00.000Z',
+ kind: 'delayed_start',
+ runAt: '2026-07-12T03:00:00.000Z',
+ updatedAt: '2026-07-12T00:00:00.000Z',
+ userMessageId: 'user-scheduled',
+ });
+
+ const [armed] = await serverDB.select().from(topics).where(eq(topics.id, topic.id));
+ expect(armed.status).toBe('scheduled');
+ expect(armed.metadata?.scheduledRun).toMatchObject({
+ kind: 'delayed_start',
+ userMessageId: 'user-scheduled',
+ });
+ });
+
+ it('still finds a continuation parked by the pre-`kind` version, which gated on resetsAt', async () => {
+ // Upgrade day: these rows have no `runAt` at all. If the due query only
+ // understood `runAt`, they would sit at `scheduled` forever.
+ const legacy = {
+ createdAt: '2026-07-12T00:00:00.000Z',
+ failedAssistantMessageId: 'assistant-failed',
+ reason: 'rate_limit',
+ source: 'heterogeneous_agent',
+ updatedAt: '2026-07-12T00:00:00.000Z',
+ userMessageId: 'user-message',
+ };
+ await serverDB.insert(topics).values([
+ {
+ id: 'legacy-window-passed',
+ // resetsAt is epoch SECONDS, and this window closed long ago.
+ metadata: { scheduledRun: { ...legacy, rateLimit: { resetsAt: 1_768_000_000 } } as any },
+ status: 'scheduled',
+ title: 'legacy due',
+ userId,
+ },
+ {
+ id: 'legacy-no-reset',
+ // The provider reported no reset โ€” the old gate read that as "due now".
+ metadata: { scheduledRun: legacy as any },
+ status: 'scheduled',
+ title: 'legacy no reset',
+ userId,
+ },
+ {
+ id: 'legacy-window-open',
+ metadata: { scheduledRun: { ...legacy, rateLimit: { resetsAt: 4_102_444_800 } } as any },
+ status: 'scheduled',
+ title: 'legacy not yet due',
+ userId,
+ },
+ ]);
+
+ const due = await TopicModel.getDueScheduledTopics(
+ serverDB,
+ new Date('2026-07-12T00:01:00Z'),
+ );
+ const ids = due.map((topic) => topic.id);
+
+ expect(ids).toContain('legacy-window-passed');
+ expect(ids).toContain('legacy-no-reset');
+ expect(ids).not.toContain('legacy-window-open');
+ });
+
+ it('never treats a scheduled topic with no runAt as due', async () => {
+ const { runAt: _runAt, ...noRunAt } = scheduledRun;
+ await serverDB.insert(topics).values({
+ id: 'scheduled-no-run-at',
+ metadata: { scheduledRun: noRunAt as any },
+ status: 'scheduled',
+ title: 'no runAt',
+ userId,
+ });
+
+ const due = await TopicModel.getDueScheduledTopics(serverDB, new Date('2030-01-01'));
+ expect(due.map((topic) => topic.id)).not.toContain('scheduled-no-run-at');
+ });
+
it('does not let a stale dispatcher clear a cancelled or re-claimed schedule', async () => {
await serverDB.insert(topics).values({
id: 'scheduled-claimed',
diff --git a/packages/database/src/models/topic.ts b/packages/database/src/models/topic.ts
index db551f3864e..47fa681f978 100644
--- a/packages/database/src/models/topic.ts
+++ b/packages/database/src/models/topic.ts
@@ -4,6 +4,7 @@ import type {
DBMessageItem,
TopicQuerySortBy,
TopicRankItem,
+ TopicScheduledRun,
} from '@lobechat/types';
import type { TimingSink } from '@lobechat/utils';
import {
@@ -50,6 +51,12 @@ export interface CreateTopicParams {
messages?: string[];
metadata?: ChatTopicMetadata;
sessionId?: string | null;
+ /**
+ * Initial status. Defaults to the column default (`active`). A topic created
+ * with `metadata.scheduledRun` must set `scheduled` here so the status and the
+ * payload land in the same insert โ€” the dispatcher treats the pair as one fact.
+ */
+ status?: ChatTopicStatus;
title?: string;
trigger?: string | null;
}
@@ -158,6 +165,34 @@ const buildTopicOrderBy = (topicActivityAt: SQL, sortBy?: TopicQuerySortBy): SQL
? [desc(topics.favorite), asc(STATUS_SORT_RANK), desc(topicActivityAt)]
: [desc(topics.favorite), desc(topicActivityAt)];
+/**
+ * NEVER null-test a jsonb arrow / path expression inside a WHERE clause:
+ *
+ * ```sql
+ * (metadata ->> 'cronJobId') IS NULL -- ๐Ÿ’ฅ
+ * (metadata #>> '{a,b}') IS NOT NULL -- ๐Ÿ’ฅ
+ * (metadata ->> 'status') IS DISTINCT FROM 'done' -- ๐Ÿ’ฅ
+ * ```
+ *
+ * The engine backing production is not stock Postgres, and this query *shape*
+ * crashes it outright โ€” `rt_fetch used out-of-bounds`, SQLSTATE XX000, thrown
+ * before any row is read (a table with zero matching rows crashes just the same,
+ * so no test on real Postgres will ever catch it). Drizzle then reports it as a
+ * bare `Failed query:`, with the real cause only in the driver's `[cause]`.
+ *
+ * COALESCE the extracted value to a sentinel instead โ€” same semantics, a shape
+ * the engine survives:
+ *
+ * ```sql
+ * COALESCE(metadata ->> 'cronJobId', '') = '' -- "is null"
+ * COALESCE((metadata #>> '{a,b}')::numeric, 0) <= $1 -- numeric gate
+ * COALESCE(metadata ->> 'status', '') <> 'done' -- IS DISTINCT FROM
+ * ```
+ *
+ * This has now bitten twice: `getLatestSpineMessageId` (LOBE-11376, #16693) and
+ * `getDueScheduledTopics` (#17077 โ€” the scheduled-run cron crashed on every tick
+ * from the day it shipped, so rate-limit continuations never once resumed).
+ */
export class TopicModel {
private userId: string;
private db: LobeChatDatabase;
@@ -1095,6 +1130,35 @@ export class TopicModel {
});
};
+ /**
+ * Arm a scheduled run on an owned topic: writes `metadata.scheduledRun` and
+ * flips the status to `scheduled` in a single update.
+ *
+ * The pair is one fact โ€” a topic that is `scheduled` with no payload spins in
+ * the dispatcher forever, and a payload on a non-`scheduled` topic never fires
+ * โ€” so they must never be written separately. The inverse is
+ * {@link TopicModel.clearScheduledRun}.
+ */
+ armScheduledRun = async (id: string, scheduledRun: TopicScheduledRun): Promise<void> => {
+ await this.db.transaction(async (tx) => {
+ const [existing] = await tx
+ .select({ metadata: topics.metadata })
+ .from(topics)
+ .where(and(eq(topics.id, id), this.ownership()))
+ .for('update');
+
+ if (!existing) return;
+
+ await tx
+ .update(topics)
+ .set({
+ metadata: { ...existing.metadata, scheduledRun } as ChatTopicMetadata,
+ status: 'scheduled',
+ })
+ .where(and(eq(topics.id, id), this.ownership()));
+ });
+ };
+
getCronTopicsGroupedByCronJob = async (
agentId: string,
): Promise<{ cronJobId: string; topics: TopicItem[] }[]> => {
@@ -1106,7 +1170,7 @@ export class TopicModel {
this.ownership(),
eq(topics.agentId, agentId),
eq(topics.trigger, 'cron'),
- sql`(${topics.metadata}->>'cronJobId') IS NOT NULL`,
+ sql`COALESCE(${topics.metadata}->>'cronJobId', '') <> ''`,
),
)
.orderBy(desc(topics.createdAt));
@@ -1201,10 +1265,10 @@ export class TopicModel {
options.endDate ? lte(topics.createdAt, options.endDate) : undefined,
options.ignoreExtracted
? undefined
- : or(
- isNull(topics.metadata),
- sql`(${topics.metadata}->>'userMemoryExtractStatus') IS DISTINCT FROM 'completed'`,
- ),
+ : // COALESCE, not `IS DISTINCT FROM`: a null test on a jsonb arrow
+ // expression crashes the production engine (see the note on the class).
+ // A null `metadata` extracts to '' here too, so this covers it.
+ sql`COALESCE(${topics.metadata}->>'userMemoryExtractStatus', '') <> 'completed'`,
cursorCondition,
),
});
@@ -1227,49 +1291,67 @@ export class TopicModel {
options.endDate ? lte(topics.createdAt, options.endDate) : undefined,
options.ignoreExtracted
? undefined
- : or(
- isNull(topics.metadata),
- sql`(${topics.metadata}->>'userMemoryExtractStatus') IS DISTINCT FROM 'completed'`,
- ),
+ : sql`COALESCE(${topics.metadata}->>'userMemoryExtractStatus', '') <> 'completed'`,
),
);
return result[0]?.total ?? 0;
};
- // **************** Scheduled continuation (backend cron) *************** //
+ // **************** Scheduled run (backend cron) *************** //
/**
- * Topics awaiting a backend-scheduled continuation after a rate limit.
+ * Topics with a scheduled run that has come due.
* System-level sweep (no ownership filter) used by the cron dispatcher.
*
- * Due = `status = 'scheduled'` AND the rate-limit window has passed
- * (`scheduledRun.rateLimit.resetsAt` is absent, or `<= now`) AND there is no
+ * Due = `status = 'scheduled'` AND the run's gate has passed AND there is no
* live claim (`scheduledRun.claim.expiresAt` is absent, or already expired) โ€”
* so a topic another replica is mid-dispatch on is skipped.
+ *
+ * `runAt` is the gate for every {@link TopicScheduledRunKind}: a row carrying a
+ * `kind` but no `runAt` is never due, which is what keeps a half-written
+ * scheduled topic from being dispatched immediately.
+ *
+ * The one exception is a row parked by the pre-`kind` version, which has no
+ * `runAt` and gated on the rate-limit reset instead. Those are still in the DB
+ * on deploy, so this reproduces their old gate rather than stranding them at
+ * `scheduled` forever โ€” matching `parseTopicScheduledRun`, which upgrades the
+ * payload the dispatcher then reads.
*/
static async getDueScheduledTopics(
db: LobeChatDatabase,
now: Date = new Date(),
): Promise<TopicItem[]> {
- const nowEpochSeconds = Math.floor(now.getTime() / 1000);
const nowIso = now.toISOString();
+ const nowEpochSeconds = Math.floor(now.getTime() / 1000);
+
+ // Every jsonb path below is COALESCE'd to a sentinel rather than null-tested:
+ // `#>> โ€ฆ IS NULL` in a WHERE clause takes the production engine down. See the
+ // note on the class.
+ const runAt = sql`COALESCE(${topics.metadata}#>>'{scheduledRun,runAt}', '')`;
+
return db
.select()
.from(topics)
.where(
and(
eq(topics.status, 'scheduled'),
- // resetsAt absent OR already passed
or(
- sql`(${topics.metadata}#>>'{scheduledRun,rateLimit,resetsAt}') IS NULL`,
- sql`(${topics.metadata}#>>'{scheduledRun,rateLimit,resetsAt}')::numeric <= ${nowEpochSeconds}`,
- ),
- // no claim OR the claim lease has expired
- or(
- sql`(${topics.metadata}#>>'{scheduledRun,claim,expiresAt}') IS NULL`,
- sql`(${topics.metadata}#>>'{scheduledRun,claim,expiresAt}') <= ${nowIso}`,
+ // `''` is the absent-runAt sentinel, and it never satisfies this pair โ€”
+ // an absent gate must not read as "due now", which is what keeps a
+ // half-written schedule parked.
+ and(sql`${runAt} <> ''`, sql`${runAt} <= ${nowIso}`),
+ // Legacy (pre-`kind`) payload: no `runAt`, gated on the rate-limit
+ // reset, and an absent reset read as "due now" (hence the 0 default).
+ and(
+ sql`${runAt} = ''`,
+ sql`COALESCE(${topics.metadata}#>>'{scheduledRun,reason}', '') = 'rate_limit'`,
+ sql`COALESCE((${topics.metadata}#>>'{scheduledRun,rateLimit,resetsAt}')::numeric, 0) <= ${nowEpochSeconds}`,
+ ),
),
+ // No claim, or the lease has expired. `''` (no claim) sorts before every
+ // ISO timestamp, so the same comparison covers both.
+ sql`COALESCE(${topics.metadata}#>>'{scheduledRun,claim,expiresAt}', '') <= ${nowIso}`,
),
);
}
diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.ts
index 581f4f7cb8e..9561ffe1255 100644
--- a/packages/locales/src/default/chat.ts
+++ b/packages/locales/src/default/chat.ts
@@ -418,7 +418,16 @@ export default {
'input.inputCompletionError.title': 'Input suggestions paused',
'input.modelUnavailable':
'The current model is no longer available. Choose another model to continue.',
+ 'input.heteroPlus.tooltip': 'Formatting and scheduling',
'input.more': 'More',
+ 'input.schedule.cancel': 'Cancel',
+ 'input.schedule.clear': 'Cancel scheduled send',
+ 'input.schedule.failed': 'Could not schedule this message. Try again.',
+ 'input.schedule.inHours': 'In {{count}} hour',
+ 'input.schedule.inHours_other': 'In {{count}} hours',
+ 'input.schedule.pending': 'Will be sent at {{time}}',
+ 'input.schedule.scheduled': 'Scheduled for {{time}}',
+ 'input.schedule.title': 'Send later',
'input.send': 'Send',
'input.sendWithCmdEnter': 'Press <key/> to send',
'input.sendWithEnter': 'Press <key/> to send',
diff --git a/packages/locales/src/default/topic.ts b/packages/locales/src/default/topic.ts
index cc3edf37e24..3a682496940 100644
--- a/packages/locales/src/default/topic.ts
+++ b/packages/locales/src/default/topic.ts
@@ -187,6 +187,7 @@ export default {
'newTopic': 'New Topic',
'renameModal.description': 'Keep it short and easy to recognize.',
'renameModal.title': 'Rename Topic',
+ 'scheduledStatusTip': 'Scheduled to run at {{time}}.',
'searchPlaceholder': 'Search Topics...',
'searchResultEmpty': 'No search results found.',
'sidebar.collapseAll': 'Collapse all groups',
diff --git a/packages/types/src/agentExecution/index.ts b/packages/types/src/agentExecution/index.ts
index 89d593a16cc..4bca61a449a 100644
--- a/packages/types/src/agentExecution/index.ts
+++ b/packages/types/src/agentExecution/index.ts
@@ -175,6 +175,43 @@ export interface ExecAgentParams {
slug?: string;
}
+/**
+ * Parameters for scheduleAgentRun โ€” defer an agent run to a future time.
+ *
+ * Deliberately a subset of {@link ExecAgentParams}: a deferred run creates the
+ * topic now and replays the request later through `execAgent`, so anything tied
+ * to a live turn (`existingMessageIds`, `parentOperationId`, `autoStart`) has no
+ * meaning here. One-shot only โ€” recurring execution belongs to
+ * `tasks.automationMode = 'schedule'`.
+ */
+export interface ScheduleAgentRunParams {
+ /** The agent ID to run (either agentId or slug is required) */
+ agentId?: string;
+ /** File IDs of already-uploaded attachments to attach when the run fires */
+ fileIds?: string[];
+ /** Group to file the topic under, when scheduling from a group conversation */
+ groupId?: string | null;
+ /** Override the agent's default model */
+ model?: string;
+ /** The user input/prompt, replayed verbatim when the run comes due */
+ prompt: string;
+ /** Override the agent's default provider */
+ provider?: string;
+ /** When to run. UTC ISO-8601 (`โ€ฆZ`) โ€” see `TopicScheduledRun.runAt`. */
+ runAt: string;
+ /** The agent slug to run (either agentId or slug is required) */
+ slug?: string;
+}
+
+export interface ScheduleAgentRunResult {
+ /** The resolved agent ID */
+ agentId: string;
+ /** Echoes the scheduled time, so callers don't re-derive it */
+ runAt: string;
+ /** The topic created to hold the deferred run (status `scheduled`) */
+ topicId: string;
+}
+
/**
* Response from execAgent
*/
diff --git a/packages/types/src/agentRuntime.ts b/packages/types/src/agentRuntime.ts
index 845710a80d6..ea9bddb7b69 100644
--- a/packages/types/src/agentRuntime.ts
+++ b/packages/types/src/agentRuntime.ts
@@ -12,6 +12,8 @@ export enum RequestTrigger {
Notify = 'notify',
Onboarding = 'onboarding',
Openapi = 'openapi',
+ /** A run the user deferred to a future time (`topic.metadata.scheduledRun`). */
+ Scheduled = 'scheduled',
SemanticSearch = 'semantic_search',
SignupEmailLLMReview = 'signup_email_llm_review',
Topic = 'topic',
diff --git a/packages/types/src/topic/topic.test.ts b/packages/types/src/topic/topic.test.ts
index 25ff1b66e2f..87ba9c9db11 100644
--- a/packages/types/src/topic/topic.test.ts
+++ b/packages/types/src/topic/topic.test.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from 'vitest';
-import { chatTopicMetadataUpdateSchema } from './topic';
+import { chatTopicMetadataUpdateSchema, parseTopicScheduledRun } from './topic';
describe('chatTopicMetadataUpdateSchema', () => {
it('parses a scheduled heterogeneous continuation patch', () => {
@@ -8,9 +8,10 @@ describe('chatTopicMetadataUpdateSchema', () => {
scheduledRun: {
createdAt: '2026-07-12T00:00:00.000Z',
failedAssistantMessageId: 'assistant-1',
+ kind: 'resume_after_rate_limit',
rateLimit: { rateLimitType: 'seven_day', resetsAt: 1_800_000_000 },
- reason: 'rate_limit',
resume: { sessionId: 'session-1', workingDirectory: '/repo' },
+ runAt: '2027-01-15T22:40:00.000Z',
source: 'heterogeneous_agent',
updatedAt: '2026-07-12T00:00:00.000Z',
userMessageId: 'user-1',
@@ -23,6 +24,46 @@ describe('chatTopicMetadataUpdateSchema', () => {
});
});
+ it('parses a delayed-start patch', () => {
+ const metadata = {
+ scheduledRun: {
+ createdAt: '2026-07-12T00:00:00.000Z',
+ kind: 'delayed_start',
+ runAt: '2026-07-12T03:00:00.000Z',
+ updatedAt: '2026-07-12T00:00:00.000Z',
+ userMessageId: 'user-1',
+ },
+ };
+
+ expect(chatTopicMetadataUpdateSchema.parse(metadata)).toEqual(metadata);
+ });
+
+ it('rejects a delayed start with no user message โ€” the persisted turn IS the prompt', () => {
+ const result = chatTopicMetadataUpdateSchema.safeParse({
+ scheduledRun: {
+ createdAt: '2026-07-12T00:00:00.000Z',
+ kind: 'delayed_start',
+ runAt: '2026-07-12T03:00:00.000Z',
+ updatedAt: '2026-07-12T00:00:00.000Z',
+ },
+ });
+
+ expect(result.success).toBe(false);
+ });
+
+ it('rejects a scheduled run with no runAt โ€” an absent due gate must not read as "due now"', () => {
+ const result = chatTopicMetadataUpdateSchema.safeParse({
+ scheduledRun: {
+ createdAt: '2026-07-12T00:00:00.000Z',
+ kind: 'delayed_start',
+ updatedAt: '2026-07-12T00:00:00.000Z',
+ userMessageId: 'user-1',
+ },
+ });
+
+ expect(result.success).toBe(false);
+ });
+
it('keeps the onboarding feedback comment limit at the shared contract boundary', () => {
const result = chatTopicMetadataUpdateSchema.safeParse({
onboardingFeedback: {
@@ -35,3 +76,54 @@ describe('chatTopicMetadataUpdateSchema', () => {
expect(result.success).toBe(false);
});
});
+
+describe('parseTopicScheduledRun', () => {
+ /** What the pre-`kind` version parked: no `kind`, no `runAt`, gated on `resetsAt`. */
+ const legacy = {
+ createdAt: '2026-07-12T00:00:00.000Z',
+ failedAssistantMessageId: 'assistant-1',
+ rateLimit: { rateLimitType: 'seven_day', resetsAt: 1_800_000_000 },
+ reason: 'rate_limit',
+ resume: { sessionId: 'session-1', workingDirectory: '/repo' },
+ source: 'heterogeneous_agent',
+ updatedAt: '2026-07-12T00:00:00.000Z',
+ userMessageId: 'user-1',
+ };
+
+ it('returns a current payload unchanged', () => {
+ const run = {
+ createdAt: '2026-07-12T00:00:00.000Z',
+ kind: 'delayed_start' as const,
+ runAt: '2026-07-12T03:00:00.000Z',
+ updatedAt: '2026-07-12T00:00:00.000Z',
+ userMessageId: 'user-1',
+ };
+
+ expect(parseTopicScheduledRun(run)).toEqual(run);
+ });
+
+ it('upgrades a legacy rate-limit payload, deriving runAt from the reset window', () => {
+ // resetsAt is epoch SECONDS โ€” the gate is the instant the window reopens.
+ expect(parseTopicScheduledRun(legacy)).toMatchObject({
+ failedAssistantMessageId: 'assistant-1',
+ kind: 'resume_after_rate_limit',
+ runAt: new Date(1_800_000_000 * 1000).toISOString(),
+ });
+ });
+
+ it('upgrades a legacy payload with no reset window to due-now, as the old gate read it', () => {
+ const { rateLimit: _rateLimit, ...noReset } = legacy;
+
+ // `createdAt` is in the past by construction, so this dispatches on the next tick.
+ expect(parseTopicScheduledRun(noReset)).toMatchObject({
+ kind: 'resume_after_rate_limit',
+ runAt: legacy.createdAt,
+ });
+ });
+
+ it('rejects a payload carrying an unknown kind rather than reading it as legacy', () => {
+ expect(parseTopicScheduledRun({ ...legacy, kind: 'who_knows' })).toBeNull();
+ expect(parseTopicScheduledRun({ kind: 'delayed_start' })).toBeNull();
+ expect(parseTopicScheduledRun(null)).toBeNull();
+ });
+});
diff --git a/packages/types/src/topic/topic.ts b/packages/types/src/topic/topic.ts
index f26bb1a8739..0176478927e 100644
--- a/packages/types/src/topic/topic.ts
+++ b/packages/types/src/topic/topic.ts
@@ -194,8 +194,8 @@ export interface ChatTopicMetadata {
threadId?: string | null;
} | null;
/**
- * Backend-scheduled continuation after a rate limit. Present iff the topic
- * status is `scheduled`. Set to `null` to clear it (same clear-convention as
+ * A deferred agent run on this topic. Present iff the topic status is
+ * `scheduled`. Set to `null` to clear it (same clear-convention as
* `runningOperation`); every reader treats a nullish value as "not scheduled".
*/
scheduledRun?: TopicScheduledRun | null;
@@ -223,6 +223,157 @@ export interface ChatTopicMetadata {
workingDirectoryConfig?: WorkingDirConfig;
}
+/**
+ * What a {@link TopicScheduledRun} does when it comes due.
+ *
+ * - `resume_after_rate_limit`: a heterogeneous turn that hit a provider rate
+ * limit; resumes the surviving CLI session from the failed assistant turn.
+ * - `delayed_start`: a run the user deliberately deferred ("send this in 3
+ * hours"); replays a stored `execAgent` request as a fresh turn.
+ */
+export const TOPIC_SCHEDULED_RUN_KINDS = ['resume_after_rate_limit', 'delayed_start'] as const;
+
+export type TopicScheduledRunKind = (typeof TOPIC_SCHEDULED_RUN_KINDS)[number];
+
+/**
+ * Lease taken by the cron dispatcher before it dispatches a scheduled run, so
+ * two concurrent ticks / replicas never trigger the same run twice. Kind-agnostic.
+ */
+const topicScheduledRunClaimSchema = z.object({
+ claimedAt: z.string(),
+ expiresAt: z.string(),
+ id: z.string(),
+});
+
+const topicScheduledRunBaseSchema = z.object({
+ claim: topicScheduledRunClaimSchema.optional(),
+ createdAt: z.string(),
+ /**
+ * The single due gate โ€” the cron dispatches a scheduled topic once
+ * `runAt <= now`, regardless of kind. Required: a scheduled run with no
+ * `runAt` would otherwise be indistinguishable from "due immediately".
+ *
+ * Must be a UTC ISO-8601 timestamp (`โ€ฆZ`, what `Date#toISOString` emits). The
+ * dispatcher's due query compares it as text against `now().toISOString()`, so
+ * a zoned offset (`โ€ฆ+08:00`) would silently break the ordering.
+ */
+ runAt: z.string().datetime(),
+ updatedAt: z.string(),
+});
+
+const resumeAfterRateLimitRunSchema = topicScheduledRunBaseSchema.extend({
+ /** The failed assistant turn that hit the rate limit (regenerated in place). */
+ failedAssistantMessageId: z.string(),
+ kind: z.literal('resume_after_rate_limit'),
+ /** Diagnostics only โ€” `runAt` is derived from `resetsAt` at write time. */
+ rateLimit: z
+ .object({ rateLimitType: z.string().optional(), resetsAt: z.number().optional() })
+ .optional(),
+ /** Resume snapshot; both fields are derivable from topic metadata but cached here. */
+ resume: z
+ .object({ sessionId: z.string().optional(), workingDirectory: z.string().optional() })
+ .optional(),
+ source: z.literal('heterogeneous_agent'),
+ /** The user message whose turn is being continued. */
+ userMessageId: z.string(),
+});
+
+const delayedStartRunSchema = topicScheduledRunBaseSchema.extend({
+ kind: z.literal('delayed_start'),
+ /** Model override captured at schedule time (the agent default is used if absent). */
+ model: z.string().optional(),
+ /** Provider override captured at schedule time. */
+ provider: z.string().optional(),
+ /**
+ * The user turn to run when due. Persisted as a real message at schedule time,
+ * so the pending prompt reads as the user's own words in the topic (and in any
+ * list rendering the last message) instead of hiding in metadata.
+ *
+ * This message โ€” not a copy in this payload โ€” is the single source of truth for
+ * the prompt: the dispatcher reads its content back, so editing a pending run
+ * is just editing the message.
+ */
+ userMessageId: z.string(),
+});
+
+/**
+ * A deferred agent run on a topic: *when* to run (`runAt`), a lease so only one
+ * replica dispatches it (`claim`), and *what* to run (the `kind` variant).
+ *
+ * Stored on `topic.metadata.scheduledRun` and paired with topic
+ * `status = 'scheduled'` โ€” the two are written and cleared together, so a
+ * scheduled topic always carries a dispatchable payload. The cron dispatcher
+ * scans due topics and re-enters `AiAgentService.execAgent`; it does NOT enter
+ * TaskLifecycle. Recurrence is deliberately out of scope: repeated execution
+ * belongs to `tasks.automationMode = 'schedule'`.
+ */
+export const topicScheduledRunSchema = z.discriminatedUnion('kind', [
+ resumeAfterRateLimitRunSchema,
+ delayedStartRunSchema,
+]);
+
+export type TopicScheduledRunClaim = z.infer<typeof topicScheduledRunClaimSchema>;
+export type ResumeAfterRateLimitRun = z.infer<typeof resumeAfterRateLimitRunSchema>;
+export type DelayedStartRun = z.infer<typeof delayedStartRunSchema>;
+export type TopicScheduledRun = z.infer<typeof topicScheduledRunSchema>;
+
+/**
+ * The pre-`kind` payload, written by the first version of this mechanism (which
+ * only ever parked rate-limited hetero continuations). It has neither `kind` nor
+ * `runAt`: the due gate was `rateLimit.resetsAt` (epoch seconds), and an absent
+ * one meant "due now".
+ *
+ * Rows in this shape are sitting in the DB when this code deploys, so the reader
+ * upgrades them rather than a migration backfilling them โ€” a scheduled run is
+ * cleared the moment it dispatches, so the legacy shape drains on its own.
+ */
+const legacyRateLimitRunSchema = z.object({
+ claim: topicScheduledRunClaimSchema.optional(),
+ createdAt: z.string(),
+ failedAssistantMessageId: z.string(),
+ // Legacy by definition โ€” a payload that carries a `kind` but failed the union
+ // above is corrupt, and must be discarded rather than read as a rate limit.
+ kind: z.undefined().optional(),
+ rateLimit: z
+ .object({ rateLimitType: z.string().optional(), resetsAt: z.number().optional() })
+ .optional(),
+ reason: z.literal('rate_limit'),
+ resume: z
+ .object({ sessionId: z.string().optional(), workingDirectory: z.string().optional() })
+ .optional(),
+ source: z.literal('heterogeneous_agent'),
+ updatedAt: z.string(),
+ userMessageId: z.string(),
+});
+
+/**
+ * Read a stored `scheduledRun` in either the current or the legacy shape, or
+ * `null` when it is neither (the caller discards those โ€” see the dispatcher).
+ *
+ * Pairs with the due query in `TopicModel.getDueScheduledTopics`, which carries
+ * the matching legacy fallback: the two must agree on what "due" means, or a row
+ * this upgrades would never be selected in the first place.
+ */
+export const parseTopicScheduledRun = (raw: unknown): TopicScheduledRun | null => {
+ const current = topicScheduledRunSchema.safeParse(raw);
+ if (current.success) return current.data;
+
+ const legacy = legacyRateLimitRunSchema.safeParse(raw);
+ if (!legacy.success) return null;
+
+ const { kind: _kind, reason: _reason, ...rest } = legacy.data;
+
+ return {
+ ...rest,
+ kind: 'resume_after_rate_limit',
+ // Reproduce the old gate exactly: the rate-limit reset if there was one, and
+ // otherwise "due immediately" โ€” which `createdAt`, always in the past, is.
+ runAt: rest.rateLimit?.resetsAt
+ ? new Date(rest.rateLimit.resetsAt * 1000).toISOString()
+ : rest.createdAt,
+ };
+};
+
/** Metadata patch accepted by the topic update API. */
export const chatTopicMetadataUpdateSchema = z.object({
boundDeviceId: z.string().optional(),
@@ -273,67 +424,11 @@ export const chatTopicMetadataUpdateSchema = z.object({
})
.nullable()
.optional(),
- scheduledRun: z
- .object({
- claim: z.object({ claimedAt: z.string(), expiresAt: z.string(), id: z.string() }).optional(),
- createdAt: z.string(),
- failedAssistantMessageId: z.string(),
- rateLimit: z
- .object({ rateLimitType: z.string().optional(), resetsAt: z.number().optional() })
- .optional(),
- reason: z.literal('rate_limit'),
- resume: z
- .object({ sessionId: z.string().optional(), workingDirectory: z.string().optional() })
- .optional(),
- source: z.literal('heterogeneous_agent'),
- updatedAt: z.string(),
- userMessageId: z.string(),
- })
- .nullish(),
+ scheduledRun: topicScheduledRunSchema.nullish(),
workingDirectory: z.string().optional(),
workingDirectoryConfig: workingDirConfigSchema.optional(),
});
-/**
- * Backend-scheduled continuation of a pure (non-Task) heterogeneous topic after
- * a rate limit. Stored on `topic.metadata.scheduledRun` and paired with topic
- * `status = 'scheduled'`. The backend cron scans scheduled topics and re-dispatches
- * the continuation through the existing heterogeneous regenerate path โ€” it does NOT
- * enter TaskLifecycle.
- *
- * MVP note: no dedicated `dueAt` field. The cron re-runs scheduled topics on each
- * tick; when `rateLimit.resetsAt` is present it is used as the "not before" gate,
- * otherwise the topic is dispatched on the next tick. `provider`/`model` are NOT
- * duplicated here โ€” they are read from the topic's own `provider`/`model` columns
- * and `heteroSessionId` metadata.
- */
-export interface TopicScheduledRun {
- /** Atomic lease taken by the cron before dispatch, to avoid double-trigger. */
- claim?: {
- claimedAt: string;
- expiresAt: string;
- id: string;
- };
- createdAt: string;
- /** The failed assistant turn that hit the rate limit (regenerated in place). */
- failedAssistantMessageId: string;
- rateLimit?: {
- rateLimitType?: string;
- /** Epoch seconds when the rate-limit window resets; used as the due gate. */
- resetsAt?: number;
- };
- reason: 'rate_limit';
- /** Resume snapshot; both fields are derivable from topic metadata but cached here. */
- resume?: {
- sessionId?: string;
- workingDirectory?: string;
- };
- source: 'heterogeneous_agent';
- updatedAt: string;
- /** The user message whose turn is being continued. */
- userMessageId: string;
-}
-
export interface ChatTopicSummary {
content: string;
model: string;
diff --git a/packages/utils/src/client/topic.ts b/packages/utils/src/client/topic.ts
index 2a8b6d539e5..61446fa152f 100644
--- a/packages/utils/src/client/topic.ts
+++ b/packages/utils/src/client/topic.ts
@@ -243,8 +243,9 @@ const resolveStatusBucket = (
if (topic.status === 'waitingForHuman' || topic.status === 'failed' || topic.status === 'unread')
return 'pending';
if (loadingTopicIds?.has(topic.id) || topic.status === 'running') return 'running';
- // `scheduled` (backend will auto-continue after a rate limit) is its own bucket:
- // it must NOT collapse into `pending`, so users don't read it as "needs manual action".
+ // `scheduled` (the backend will run this later โ€” a user-deferred send, or an
+ // auto-continue after a rate limit) is its own bucket: it must NOT collapse
+ // into `pending`, so users don't read it as "needs manual action".
if (topic.status === 'scheduled') return 'scheduled';
const status: ChatTopicStatus = topic.status ?? 'active';
if (status === 'paused' || status === 'completed' || status === 'archived') return status;
diff --git a/src/features/Conversation/ChatInput/index.tsx b/src/features/Conversation/ChatInput/index.tsx
index dfe5d78d518..9d1bfc164d9 100644
--- a/src/features/Conversation/ChatInput/index.tsx
+++ b/src/features/Conversation/ChatInput/index.tsx
@@ -33,7 +33,12 @@ import { fileChatSelectors, useFileStore } from '@/store/file';
import { buildMessageContextSelections } from '../../ChatInput/utils/contextSelections';
import WideScreenContainer from '../../WideScreenContainer';
import InterventionBar from '../InterventionBar';
-import { dataSelectors, messageStateSelectors, useConversationStore } from '../store';
+import {
+ dataSelectors,
+ messageStateSelectors,
+ useConversationStore,
+ useConversationStoreApi,
+} from '../store';
import TodoProgress from '../TodoProgress';
import OpStatusTray from './OpStatusTray';
import QueueTray from './QueueTray';
@@ -226,6 +231,7 @@ const ChatInput = memo<ChatInputProps>(
const { t } = useTranslation('chat');
// ConversationStore state
+ const storeApi = useConversationStoreApi();
const dbMessages = useConversationStore(dataSelectors.dbMessages);
const context = useConversationStore((s) => s.context);
const draftKey = useMemo(() => messageMapKey(context), [context]);
@@ -354,10 +360,28 @@ const ChatInput = memo<ChatInputProps>(
// Capture editor JSON state before clearing for rich text rendering
const editorData = getEditorData();
+ const clearComposer = () => {
+ clearContent();
+ fileStore.clearChatUploadFileList();
+ fileStore.clearChatContextSelections();
+ };
+
+ // A deferred send was armed from the composer (see `scheduledSendAt`):
+ // park the turn as a `scheduled` topic instead of running it. Send stays
+ // the single commit action โ€” picking a time never dispatches by itself.
+ //
+ // The composer is cleared only once the schedule is persisted, unlike the
+ // normal path below: a rejected schedule (the picked time just went past,
+ // the request failed) leaves no message row to recover the text from, so
+ // an up-front clear would simply lose it.
+ if (storeApi.getState().scheduledSendAt) {
+ const scheduled = await storeApi.getState().commitScheduledSend(message, currentFileList);
+ if (scheduled) clearComposer();
+ return;
+ }
+
// Clear content immediately for responsive UX
- clearContent();
- fileStore.clearChatUploadFileList();
- fileStore.clearChatContextSelections();
+ clearComposer();
const { contextSelections, pageSelections } =
buildMessageContextSelections(currentContextList);
@@ -371,7 +395,7 @@ const ChatInput = memo<ChatInputProps>(
pageSelections,
});
},
- [sendMessage, disableQueue, disableSend, isInputQueueBlocked],
+ [sendMessage, storeApi, disableQueue, disableSend, isInputQueueBlocked],
);
const sendButtonProps: SendButtonProps = {
diff --git a/src/features/Conversation/Error/index.tsx b/src/features/Conversation/Error/index.tsx
index 1311af73aa2..528d20b5c89 100644
--- a/src/features/Conversation/Error/index.tsx
+++ b/src/features/Conversation/Error/index.tsx
@@ -306,9 +306,12 @@ const ErrorMessageExtra = memo<ErrorExtraProps>(
const activeTopicScheduled = useChatStore(
(s) => topicSelectors.currentActiveTopic(s)?.status === 'scheduled',
);
- const scheduledResetsAt = useChatStore(
- (s) => topicSelectors.currentActiveTopic(s)?.metadata?.scheduledRun?.rateLimit?.resetsAt,
- );
+ const scheduledResetsAt = useChatStore((s) => {
+ const scheduledRun = topicSelectors.currentActiveTopic(s)?.metadata?.scheduledRun;
+ return scheduledRun?.kind === 'resume_after_rate_limit'
+ ? scheduledRun.rateLimit?.resetsAt
+ : undefined;
+ });
const isRateLimitError =
canCreate &&
diff --git a/src/features/Conversation/Messages/User/ScheduledRunFooter.tsx b/src/features/Conversation/Messages/User/ScheduledRunFooter.tsx
new file mode 100644
index 00000000000..73f087a6c51
--- /dev/null
+++ b/src/features/Conversation/Messages/User/ScheduledRunFooter.tsx
@@ -0,0 +1,63 @@
+'use client';
+
+import { ActionIcon, Flexbox, Icon, Text } from '@lobehub/ui';
+import { cssVar } from 'antd-style';
+import dayjs from 'dayjs';
+import { BanIcon, ClockIcon } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useChatStore } from '@/store/chat';
+import { topicSelectors } from '@/store/chat/selectors';
+
+import { useConversationStore } from '../../store';
+
+interface ScheduledRunFooterProps {
+ id: string;
+}
+
+/**
+ * Pending-run footer under the user bubble a deferred run is parked on.
+ *
+ * A `delayed_start` persists its prompt as a real user message and points
+ * `scheduledRun.userMessageId` at it, so the promise ("this will run at โ€ฆ") is
+ * shown exactly where the user left it, with the way out attached. Deliberately
+ * unboxed and muted โ€” it is a quiet status line under the message, not an alert
+ * demanding attention. Renders nothing for any other message.
+ */
+const ScheduledRunFooter = memo<ScheduledRunFooterProps>(({ id }) => {
+ const { t } = useTranslation('chat');
+
+ const runAt = useChatStore((s) => {
+ const topic = topicSelectors.currentActiveTopic(s);
+ if (topic?.status !== 'scheduled') return;
+
+ const scheduledRun = topic.metadata?.scheduledRun;
+ if (scheduledRun?.kind !== 'delayed_start' || scheduledRun.userMessageId !== id) return;
+
+ return scheduledRun.runAt;
+ });
+
+ const cancelScheduledRun = useConversationStore((s) => s.cancelScheduledRun);
+
+ if (!runAt) return null;
+
+ return (
+ <Flexbox horizontal align={'center'} gap={4} justify={'flex-end'} paddingBlock={4}>
+ <Icon icon={ClockIcon} size={14} style={{ color: cssVar.colorTextQuaternary }} />
+ <Text style={{ fontSize: 12 }} type={'secondary'}>
+ {t('input.schedule.pending', { time: dayjs(runAt).format('MM-DD HH:mm') })}
+ </Text>
+ <ActionIcon
+ icon={BanIcon}
+ size={'small'}
+ title={t('input.schedule.cancel')}
+ onClick={() => void cancelScheduledRun()}
+ />
+ </Flexbox>
+ );
+});
+
+ScheduledRunFooter.displayName = 'ScheduledRunFooter';
+
+export default ScheduledRunFooter;
diff --git a/src/features/Conversation/Messages/User/index.tsx b/src/features/Conversation/Messages/User/index.tsx
index 6f3141a3cb2..8bf90b98e1a 100644
--- a/src/features/Conversation/Messages/User/index.tsx
+++ b/src/features/Conversation/Messages/User/index.tsx
@@ -21,6 +21,7 @@ import {
import Actions from './Actions';
import UserMessageContent from './components/MessageContent';
import { UserMessageExtra } from './Extra';
+import ScheduledRunFooter from './ScheduledRunFooter';
interface UserMessageProps {
disableEditing?: boolean;
@@ -88,6 +89,7 @@ const UserMessage = memo<UserMessageProps>(({ id, disableEditing, index }) => {
<ChatItem
actions={<Actions data={item} disableEditing={disableEditing} id={id} />}
avatar={{ avatar, title }}
+ belowMessage={<ScheduledRunFooter id={id} />}
editing={editing}
id={id}
message={content}
diff --git a/src/features/Conversation/store/slices/generation/action.ts b/src/features/Conversation/store/slices/generation/action.ts
index 4f6739c0bc0..3e9fe28a841 100644
--- a/src/features/Conversation/store/slices/generation/action.ts
+++ b/src/features/Conversation/store/slices/generation/action.ts
@@ -10,6 +10,7 @@ import { type StateCreator } from 'zustand';
import { message as antdMessage } from '@/components/AntdStaticMethods';
import { MESSAGE_CANCEL_FLAT } from '@/const/index';
+import { saveDraft } from '@/features/ChatInput/draftStorage';
import { isHeterogeneousAgentStatusGuideError } from '@/features/Conversation/Error/heterogeneous';
import { messageService } from '@/services/message';
import { getAgentStoreState } from '@/store/agent';
@@ -29,6 +30,7 @@ import {
mergeAgentRuntimeInitialContexts,
resolveActiveTopicDocumentInitialContext,
} from '@/store/chat/utils/activeTopicDocumentContext';
+import { messageMapKey } from '@/store/chat/utils/messageMapKey';
import { getElectronStoreState } from '@/store/electron';
import { type Store as ConversationStore } from '../../action';
@@ -225,6 +227,15 @@ export interface GenerationAction {
* Cancel a specific operation
*/
cancelOperation: (operationId: string, reason?: string) => void;
+ /**
+ * Cancel a user-deferred run ("send this in 3 hours") before it fires.
+ *
+ * Distinct from {@link cancelHeteroContinuation}, which parks the topic at
+ * `failed` because it is cancelling the retry of a turn that already failed.
+ * Nothing has failed here โ€” the topic drops back to `active` and keeps the
+ * pending user message, so the user can send it now or delete the topic.
+ */
+ cancelScheduledRun: () => Promise<void>;
/**
* Clear all operations
@@ -375,6 +386,52 @@ export const generationSlice: StateCreator<
await chatStore.updateTopicStatus({ status: 'failed', topicId });
await chatStore.updateTopicMetadata(topicId, { scheduledRun: null });
},
+ cancelScheduledRun: async () => {
+ const { context, dbMessages, editor } = get();
+ const topicId = context.topicId;
+ if (!topicId) return;
+
+ const chatStore = useChatStore.getState();
+ const topic = topicSelectors.getTopicById(topicId)(chatStore);
+ const scheduledRun = topic?.metadata?.scheduledRun;
+ const userMessageId =
+ scheduledRun?.kind === 'delayed_start' ? scheduledRun.userMessageId : undefined;
+ // Capture the text before anything is deleted โ€” cancelling a scheduled send
+ // hands the user's words back to the composer rather than discarding them.
+ const pendingContent = userMessageId
+ ? dbMessages.find((message) => message.id === userMessageId)?.content
+ : undefined;
+
+ await chatStore.updateTopicStatus({ status: 'active', topicId });
+ await chatStore.updateTopicMetadata(topicId, { scheduledRun: null });
+
+ // A `delayed_start` topic exists solely to hold the deferred turn, so once
+ // that turn is cancelled the topic has nothing left in it โ€” drop it instead
+ // of stranding an empty row in the sidebar. Guarded on the message count so
+ // a topic that somehow holds other turns keeps them and only loses the
+ // pending one.
+ const isOnlyMessage = dbMessages.length === 1 && dbMessages[0]?.id === userMessageId;
+
+ if (pendingContent && editor) {
+ // Load the text into the live editor first โ€” that is also how we get it in
+ // the editor's own JSON shape, which is the only thing a draft can carry.
+ editor.setDocument('markdown', pendingContent);
+
+ if (isOnlyMessage) {
+ // Deleting the topic navigates back to the agent's compose surface, which
+ // mounts a DIFFERENT ChatInput โ€” anything written to the editor we hold
+ // here dies with it. Stash the text as that surface's draft instead; the
+ // new composer restores it on mount. (Re-reading `get().editor` after the
+ // switch doesn't work either: the new instance hasn't registered yet.)
+ saveDraft(messageMapKey({ ...context, topicId: null }), editor.getJSONState());
+ } else {
+ editor.focus();
+ }
+ }
+
+ if (isOnlyMessage) await chatStore.removeTopic(topicId);
+ else if (userMessageId) await get().deleteMessage(userMessageId);
+ },
cancelOperation: (operationId: string, reason?: string) => {
const state = get();
const { hooks } = state;
@@ -616,18 +673,26 @@ export const generationSlice: StateCreator<
const chatStore = useChatStore.getState();
const topic = topicSelectors.getTopicById(topicId)(chatStore);
- const now = new Date().toISOString();
+ const nowDate = new Date();
+ const now = nowDate.toISOString();
+ // The rate-limit reset is the "not before" gate. Absent (some providers don't
+ // report one) means "retry on the next tick" โ€” never "already due", which is
+ // why `runAt` is always written.
+ const runAt = rateLimit?.resetsAt
+ ? new Date(rateLimit.resetsAt * 1000).toISOString()
+ : nowDate.toISOString();
await chatStore.updateTopicMetadata(topicId, {
scheduledRun: {
createdAt: now,
failedAssistantMessageId,
+ kind: 'resume_after_rate_limit',
rateLimit,
- reason: 'rate_limit',
resume: {
sessionId: topic?.metadata?.heteroSessionId,
workingDirectory: topic?.metadata?.workingDirectory,
},
+ runAt,
source: 'heterogeneous_agent',
updatedAt: now,
userMessageId,
diff --git a/src/features/Conversation/store/slices/input/action.ts b/src/features/Conversation/store/slices/input/action.ts
index b5c3b332811..208d5e9849a 100644
--- a/src/features/Conversation/store/slices/input/action.ts
+++ b/src/features/Conversation/store/slices/input/action.ts
@@ -1,5 +1,8 @@
+import { toast } from '@lobehub/ui/base-ui';
+import { t } from 'i18next';
import { type StateCreator } from 'zustand';
+import { aiAgentService } from '@/services/aiAgent';
import { useChatStore } from '@/store/chat';
import { type State } from '../../initialState';
@@ -10,6 +13,20 @@ export interface InputAction {
*/
cleanupInput: () => void;
+ /**
+ * Commit the armed scheduled send: persist the composer's turn as a `scheduled`
+ * topic that the backend cron fires at {@link State.scheduledSendAt}.
+ *
+ * Called from the send handler instead of `sendMessage` โ€” nothing runs now, so
+ * this deliberately does not go through the agent runtime.
+ *
+ * Returns whether the schedule was persisted. The send handler keeps the
+ * composer intact until it is: scheduling is one rejectable round-trip (the
+ * chosen time may have just gone past, the request may fail) and โ€” unlike a
+ * normal send โ€” there is no message row to recover the text from afterwards.
+ */
+ commitScheduledSend: (message: string, files?: { id: string }[]) => Promise<boolean>;
+
/**
* Report the floating overlay height (TodoProgress + QueueTray) so the
* ChatList scroll container can reserve matching bottom padding.
@@ -21,6 +38,9 @@ export interface InputAction {
*/
setEditor: (editor: any) => void;
+ /** Arm (or, with `undefined`, disarm) a deferred send. */
+ setScheduledSendAt: (runAt?: string) => void;
+
/**
* Update the input message
*/
@@ -29,11 +49,61 @@ export interface InputAction {
export const inputSlice: StateCreator<State & InputAction, [], [], InputAction> = (set, get) => ({
cleanupInput: () => {
- set({ chatInputOverlayHeight: 0, editor: null, inputMessage: '' });
+ set({
+ chatInputOverlayHeight: 0,
+ editor: null,
+ inputMessage: '',
+ scheduledSendAt: undefined,
+ });
// Also clear ChatStore's mainInputEditor
useChatStore.setState({ mainInputEditor: null });
},
+ commitScheduledSend: async (message, files) => {
+ const { context, scheduledSendAt } = get();
+ const agentId = context.agentId;
+ if (!scheduledSendAt || !agentId || !message.trim()) return false;
+
+ const fileIds = (files ?? []).map((file) => file.id);
+
+ try {
+ await aiAgentService.scheduleAgentRun({
+ agentId,
+ fileIds: fileIds.length > 0 ? fileIds : undefined,
+ prompt: message,
+ runAt: scheduledSendAt,
+ });
+ } catch (error) {
+ // The composer still holds the text and the attachments โ€” the send handler
+ // clears it only on a `true` return โ€” so the user can retry, or pick a new
+ // time if this one went past while they were typing. Stay armed: the chip
+ // is the only thing telling them the next Send is still a scheduled one.
+ console.error('[commitScheduledSend] failed:', error);
+ toast.error(t('input.schedule.failed', { ns: 'chat' }));
+ return false;
+ }
+
+ // Disarm only now that the turn is parked: a live chip would otherwise claim
+ // the NEXT message is scheduled too.
+ set({ scheduledSendAt: undefined });
+
+ // Surface the new topic in the sidebar, where it renders with a clock.
+ await useChatStore.getState().refreshTopic();
+ toast.success(
+ t('input.schedule.scheduled', {
+ ns: 'chat',
+ time: new Date(scheduledSendAt).toLocaleString(undefined, {
+ day: '2-digit',
+ hour: '2-digit',
+ minute: '2-digit',
+ month: '2-digit',
+ }),
+ }),
+ );
+
+ return true;
+ },
+
setChatInputOverlayHeight: (height) => {
if (get().chatInputOverlayHeight === height) return;
set({ chatInputOverlayHeight: height });
@@ -45,6 +115,10 @@ export const inputSlice: StateCreator<State & InputAction, [], [], InputAction>
useChatStore.setState({ mainInputEditor: editor });
},
+ setScheduledSendAt: (runAt) => {
+ set({ scheduledSendAt: runAt });
+ },
+
updateInputMessage: (message) => {
set({ inputMessage: message });
},
diff --git a/src/features/Conversation/store/slices/input/initialState.ts b/src/features/Conversation/store/slices/input/initialState.ts
index 42b1b8e263a..f8851b2f1ea 100644
--- a/src/features/Conversation/store/slices/input/initialState.ts
+++ b/src/features/Conversation/store/slices/input/initialState.ts
@@ -16,10 +16,20 @@ export interface InputState {
* Current input message text
*/
inputMessage: string;
+
+ /**
+ * When set, the next send is deferred to this time instead of running now.
+ *
+ * Picking a time from the composer only *arms* the send โ€” it does not create
+ * anything. The send button stays the single commit action, so "pick a time"
+ * and "send" don't become two competing ways to dispatch a turn. UTC ISO.
+ */
+ scheduledSendAt?: string;
}
export const inputInitialState: InputState = {
chatInputOverlayHeight: 0,
editor: null,
inputMessage: '',
+ scheduledSendAt: undefined,
};
diff --git a/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/index.tsx b/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/index.tsx
index e11f6778ec0..2a32a978e33 100644
--- a/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/index.tsx
+++ b/src/routes/(main)/agent/_layout/Sidebar/Topic/List/Item/index.tsx
@@ -7,6 +7,7 @@ import {
} from '@lobechat/utils/client/topic';
import { Flexbox, Icon, Popover, Skeleton, Tag, Text, Tooltip } from '@lobehub/ui';
import { createStaticStyles, cssVar, keyframes, useTheme } from 'antd-style';
+import dayjs from 'dayjs';
import { HashIcon, MessageSquareDashed } from 'lucide-react';
import type { CSSProperties } from 'react';
import { memo, Suspense, useCallback, useEffect, useMemo, useState } from 'react';
@@ -288,6 +289,7 @@ const TopicItem = memo<TopicItemProps>(
const isFailed = status === 'failed';
const isRunning = status === 'running';
+ const isScheduled = status === 'scheduled';
const isWaitingForHuman = status === 'waitingForHuman';
// Post-visible-output tail: the user-visible answer is complete but the run
// is still doing terminal bookkeeping (unread persist, title summary) โ€”
@@ -399,6 +401,22 @@ const TopicItem = memo<TopicItemProps>(
title={title === '...' ? <DotsLoading gap={3} size={4} /> : title}
titleColor={cssVar.colorText}
icon={(() => {
+ // A scheduled topic hasn't run yet โ€” nothing else can be true of it,
+ // so its clock outranks the other states.
+ if (isScheduled) {
+ const visual = TOPIC_STATUS_VISUALS.scheduled;
+ const runAt = metadata?.scheduledRun?.runAt;
+ const icon = <Icon icon={visual.icon} size={'small'} style={{ color: visual.color }} />;
+ return runAt ? (
+ <Tooltip
+ title={t('scheduledStatusTip', { time: dayjs(runAt).format('MM-DD HH:mm') })}
+ >
+ {icon}
+ </Tooltip>
+ ) : (
+ icon
+ );
+ }
if (isWaitingForHuman) {
const visual = TOPIC_STATUS_VISUALS.waitingForHuman;
return <Icon icon={visual.icon} size={'small'} style={{ color: visual.color }} />;
diff --git a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/HeteroPlus.tsx b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/HeteroPlus.tsx
new file mode 100644
index 00000000000..30dc48a12cf
--- /dev/null
+++ b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/HeteroPlus.tsx
@@ -0,0 +1,113 @@
+'use client';
+
+import { Icon } from '@lobehub/ui';
+import { cssVar } from 'antd-style';
+import dayjs from 'dayjs';
+import { CalendarClockIcon, CheckIcon, ChevronRight, PlusIcon, TypeIcon } from 'lucide-react';
+import { memo, useCallback, useMemo, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import Action from '@/features/ChatInput/ActionBar/components/Action';
+import { type ActionDropdownMenuItems } from '@/features/ChatInput/ActionBar/components/ActionDropdown';
+import { useChatInputStore } from '@/features/ChatInput/store';
+import { useConversationStore } from '@/features/Conversation';
+
+import { OFFSETS_IN_HOURS, resolveScheduleTime } from './scheduleTime';
+
+/**
+ * The hetero action bar's `+` menu.
+ *
+ * Mirrors the agent composer's Plus, but carries only what a heterogeneous run
+ * actually has: the formatting-toolbar toggle and "Send later". The agent Plus
+ * is not reused โ€” most of it (attachments, web search, skills, gateway mode) has
+ * no meaning for a CLI agent, and a menu of mostly-inapplicable rows is worse
+ * than a small one.
+ *
+ * Picking a time here only *arms* the send (`scheduledSendAt`); it creates
+ * nothing. The send button remains the single commit action, and the armed state
+ * is shown next to it by `ScheduledSendChip`.
+ */
+const HeteroPlus = memo(() => {
+ const { t } = useTranslation('chat');
+ const { t: tEditor } = useTranslation('editor');
+ const [open, setOpen] = useState(false);
+
+ const [showTypoBar, setShowTypoBar] = useChatInputStore((s) => [s.showTypoBar, s.setShowTypoBar]);
+
+ const scheduledSendAt = useConversationStore((s) => s.scheduledSendAt);
+ const setScheduledSendAt = useConversationStore((s) => s.setScheduledSendAt);
+
+ const armSchedule = useCallback(
+ (hours: number) => {
+ setScheduledSendAt(resolveScheduleTime(hours).toISOString());
+ setOpen(false);
+ },
+ [setScheduledSendAt],
+ );
+
+ const items: ActionDropdownMenuItems = useMemo(() => {
+ // Which row is armed: compare against the same on-the-hour slot each row
+ // would produce, so the check mark tracks the row the user actually picked.
+ const armedHours = scheduledSendAt
+ ? OFFSETS_IN_HOURS.find((hours) =>
+ resolveScheduleTime(hours).isSame(dayjs(scheduledSendAt), 'minute'),
+ )
+ : undefined;
+
+ return [
+ {
+ children: OFFSETS_IN_HOURS.map((hours) => ({
+ extra:
+ armedHours === hours ? (
+ <Icon icon={CheckIcon} size={16} style={{ color: cssVar.colorSuccess }} />
+ ) : (
+ <span style={{ color: cssVar.colorTextTertiary, fontSize: 12 }}>
+ {resolveScheduleTime(hours).format('MM-DD HH:mm')}
+ </span>
+ ),
+ key: `scheduleSend-${hours}h`,
+ label: t('input.schedule.inHours', { count: hours }),
+ onClick: () => armSchedule(hours),
+ })),
+ // Trailing chevron (replaces base-ui's default triangle submenu arrow,
+ // which ActionDropdown hides via the .lobe-submenu-chevron rule).
+ extra: <Icon className="lobe-submenu-chevron" icon={ChevronRight} size={16} />,
+ icon: CalendarClockIcon,
+ key: 'scheduleSend',
+ label: t('input.schedule.title'),
+ },
+ { type: 'divider' },
+ // Formatting toolbar toggle โ€” same trailing-switch row as the agent Plus.
+ {
+ checked: Boolean(showTypoBar),
+ icon: TypeIcon,
+ key: 'typo',
+ label: tEditor('actions.typobar.title'),
+ onCheckedChange: (checked: boolean) => setShowTypoBar(checked),
+ type: 'switch',
+ },
+ ];
+ }, [t, tEditor, showTypoBar, setShowTypoBar, armSchedule, scheduledSendAt]);
+
+ return (
+ <Action
+ icon={PlusIcon}
+ open={open}
+ size={{ blockSize: 32, borderRadius: 16, size: 18 }}
+ // Not the agent Plus's tooltip โ€” it promises files / skills / context, none
+ // of which this menu has.
+ title={t('input.heteroPlus.tooltip')}
+ tooltipProps={{ placement: 'top' }}
+ dropdown={{
+ menu: { items },
+ minWidth: 220,
+ placement: 'topLeft',
+ }}
+ onOpenChange={setOpen}
+ />
+ );
+});
+
+HeteroPlus.displayName = 'HeteroPlus';
+
+export default HeteroPlus;
diff --git a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/ScheduledSendChip.tsx b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/ScheduledSendChip.tsx
new file mode 100644
index 00000000000..f0cd5c9bb80
--- /dev/null
+++ b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/ScheduledSendChip.tsx
@@ -0,0 +1,62 @@
+'use client';
+
+import { ActionIcon, Flexbox, Icon, Text } from '@lobehub/ui';
+import { createStaticStyles, cssVar } from 'antd-style';
+import dayjs from 'dayjs';
+import { CalendarClockIcon, XIcon } from 'lucide-react';
+import { memo } from 'react';
+import { useTranslation } from 'react-i18next';
+
+import { useConversationStore } from '@/features/Conversation';
+
+const styles = createStaticStyles(({ css }) => ({
+ chip: css`
+ flex: none;
+
+ height: 28px;
+ padding-inline: 8px 4px;
+ border-radius: 14px;
+
+ background: ${cssVar.colorInfoBg};
+ `,
+ label: css`
+ font-size: 12px;
+ line-height: 1;
+ color: ${cssVar.colorInfoText};
+ white-space: nowrap;
+ `,
+}));
+
+/**
+ * The armed-schedule chip, sitting right next to the `+` menu that armed it.
+ *
+ * Picking a time from `+` only arms the send; this is what makes that armed
+ * state visible โ€” otherwise the send button would silently do something other
+ * than send. Clearing the chip disarms it, so the way out is attached to the
+ * promise.
+ */
+const ScheduledSendChip = memo(() => {
+ const { t } = useTranslation('chat');
+
+ const scheduledSendAt = useConversationStore((s) => s.scheduledSendAt);
+ const setScheduledSendAt = useConversationStore((s) => s.setScheduledSendAt);
+
+ if (!scheduledSendAt) return null;
+
+ return (
+ <Flexbox horizontal align={'center'} className={styles.chip} gap={4}>
+ <Icon icon={CalendarClockIcon} size={12} style={{ color: cssVar.colorInfoText }} />
+ <Text className={styles.label}>{dayjs(scheduledSendAt).format('MM-DD HH:mm')}</Text>
+ <ActionIcon
+ icon={XIcon}
+ size={'small'}
+ title={t('input.schedule.clear')}
+ onClick={() => setScheduledSendAt(undefined)}
+ />
+ </Flexbox>
+ );
+});
+
+ScheduledSendChip.displayName = 'ScheduledSendChip';
+
+export default ScheduledSendChip;
diff --git a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/index.tsx b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/index.tsx
index aef33eb8bab..47d64940016 100644
--- a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/index.tsx
+++ b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/index.tsx
@@ -26,15 +26,17 @@ import { agentByIdSelectors, agentSelectors } from '@/store/agent/selectors';
import { useChatStore } from '@/store/chat';
import HeteroControlBar from './HeteroControlBar';
+import HeteroPlus from './HeteroPlus';
+import ScheduledSendChip from './ScheduledSendChip';
import { shouldShowHeteroModelSelector } from './shouldShowHeteroModelSelector';
// Heterogeneous agents (e.g. Claude Code) bring their own toolchain and memory,
-// so most LobeHub-side pickers don't apply. Typo is kept so the user can still
-// toggle the rich-text formatting bar. The CLI model + thinking-effort selector
-// is injected right after it via `extraActionItems`, so it sits in the input's
-// bottom-left corner (consistent with where the model picker lives in a normal
-// agent chat), rather than off in the control-bar strip below the box.
-const leftActions: ActionKeys[] = ['typo'];
+// so most LobeHub-side pickers don't apply โ€” no built-in left action fits, and
+// the bar is composed entirely from `extraActionItems`: a hetero-only `+` menu
+// (formatting toolbar + "Send later"), then the CLI model + thinking-effort
+// selector. Both sit in the input's bottom-left corner, where the agent composer
+// puts its `+` and model picker, rather than off in the control-bar strip below.
+const leftActions: ActionKeys[] = [];
/**
* GuardBanner
@@ -112,11 +114,21 @@ const HeterogeneousChatInput = memo(() => {
executionTarget: agencyConfig?.executionTarget,
isDesktopClient: isDesktop,
});
+ // The armed-schedule chip sits immediately after the `+` that armed it, so the
+ // state and the control that produced it read as one unit.
const extraActionItems = useMemo<ChatInputActionsProps['items']>(
- () =>
- showHeteroModel
- ? [{ alwaysDisplay: true, children: <HeteroModel />, key: 'heteroModel' }]
- : [],
+ () => [
+ { alwaysDisplay: true, children: <HeteroPlus />, key: 'heteroPlus' },
+ { alwaysDisplay: true, children: <ScheduledSendChip />, key: 'scheduledSendChip' },
+ ],
+ [],
+ );
+
+ // The model selector rides in the send-area prefix rather than the
+ // (left-aligned) action bar, so it sits right next to Send โ€” it qualifies the
+ // run the send button is about to commit.
+ const sendAreaPrefix = useMemo(
+ () => (showHeteroModel ? <HeteroModel /> : undefined),
[showHeteroModel],
);
@@ -202,9 +214,11 @@ const HeterogeneousChatInput = memo(() => {
{renderCloudConfigGuard()}
{renderDeviceGuard()}
<ChatInput
+ allowExpand={false}
controlBarSlot={<HeteroControlBar />}
extraActionItems={extraActionItems}
leftActions={leftActions}
+ sendAreaPrefix={sendAreaPrefix}
sendButtonProps={{ disabled: inputDisabled, shape: 'round' }}
skipScrollMarginWithList={!hasGuard}
onEditorReady={(instance) => {
diff --git a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/scheduleTime.test.ts b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/scheduleTime.test.ts
new file mode 100644
index 00000000000..d0a787a9bf4
--- /dev/null
+++ b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/scheduleTime.test.ts
@@ -0,0 +1,28 @@
+import dayjs from 'dayjs';
+import { describe, expect, it } from 'vitest';
+
+import { resolveScheduleTime } from './scheduleTime';
+
+describe('resolveScheduleTime', () => {
+ it('lands on the hour instead of the minute the menu happened to open', () => {
+ const now = dayjs('2026-07-13T12:35:00');
+
+ expect(resolveScheduleTime(1, now).format('HH:mm')).toBe('13:00');
+ expect(resolveScheduleTime(3, now).format('HH:mm')).toBe('15:00');
+ expect(resolveScheduleTime(8, now).format('HH:mm')).toBe('20:00');
+ expect(resolveScheduleTime(24, now).format('MM-DD HH:mm')).toBe('07-14 12:00');
+ });
+
+ it('takes the next hour when flooring would leave almost no lead time', () => {
+ // 12:59 + 1h floored is 13:00 โ€” 60 seconds away, which makes "in 1 hour" a lie.
+ const now = dayjs('2026-07-13T12:59:00');
+
+ expect(resolveScheduleTime(1, now).format('HH:mm')).toBe('14:00');
+ });
+
+ it('keeps the floored slot when it is comfortably ahead', () => {
+ const now = dayjs('2026-07-13T12:45:00');
+
+ expect(resolveScheduleTime(1, now).format('HH:mm')).toBe('13:00');
+ });
+});
diff --git a/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/scheduleTime.ts b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/scheduleTime.ts
new file mode 100644
index 00000000000..d5b82808a41
--- /dev/null
+++ b/src/routes/(main)/agent/features/Conversation/HeterogeneousChatInput/scheduleTime.ts
@@ -0,0 +1,22 @@
+import dayjs, { type Dayjs } from 'dayjs';
+
+/** Offsets offered by "Send later", in hours. */
+export const OFFSETS_IN_HOURS = [1, 3, 8, 24];
+
+/**
+ * A schedule is only ever approximate ("in ~3 hours"), so land it on the hour
+ * rather than on whatever minute the user happened to open the menu โ€” "15:00"
+ * is a promise a person can hold in their head; "15:37" is noise.
+ *
+ * Floors to the hour, then guards the degenerate case: at 12:59, flooring
+ * "in 1 hour" gives 13:00, which is 60 seconds away and makes the label a lie.
+ * When the floored slot is less than {@link MIN_LEAD_MINUTES} out, take the next
+ * hour instead.
+ */
+const MIN_LEAD_MINUTES = 10;
+
+export const resolveScheduleTime = (hours: number, now: Dayjs = dayjs()): Dayjs => {
+ const floored = now.add(hours, 'hour').startOf('hour');
+
+ return floored.diff(now, 'minute') < MIN_LEAD_MINUTES ? floored.add(1, 'hour') : floored;
+};
diff --git a/src/server/workflows-hono/task/handlers/__tests__/scheduledTopicDispatch.test.ts b/src/server/workflows-hono/task/handlers/__tests__/scheduledTopicDispatch.test.ts
new file mode 100644
index 00000000000..697b0bb73d3
--- /dev/null
+++ b/src/server/workflows-hono/task/handlers/__tests__/scheduledTopicDispatch.test.ts
@@ -0,0 +1,200 @@
+import { Hono } from 'hono';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { scheduledTopicDispatch } from '../scheduledTopicDispatch';
+
+const mocks = vi.hoisted(() => ({
+ claimScheduledTopic: vi.fn(),
+ clearScheduledRun: vi.fn(),
+ execAgent: vi.fn(),
+ findById: vi.fn(),
+ getDueScheduledTopics: vi.fn(),
+ getServerDB: vi.fn(),
+}));
+
+vi.mock('@/database/server', () => ({ getServerDB: mocks.getServerDB }));
+
+vi.mock('@/database/models/topic', () => ({
+ TopicModel: {
+ claimScheduledTopic: mocks.claimScheduledTopic,
+ clearScheduledRun: mocks.clearScheduledRun,
+ getDueScheduledTopics: mocks.getDueScheduledTopics,
+ },
+}));
+
+vi.mock('@/database/models/message', () => ({
+ MessageModel: class {
+ findById = mocks.findById;
+ },
+}));
+
+vi.mock('@/server/services/aiAgent', () => ({
+ AiAgentService: class {
+ execAgent = mocks.execAgent;
+ },
+}));
+
+const createApp = () => {
+ const app = new Hono();
+ app.post('/scheduled-topic-dispatch', scheduledTopicDispatch);
+ return app;
+};
+
+const dispatch = () => createApp().request('/scheduled-topic-dispatch', { method: 'POST' });
+
+const topic = (scheduledRun: unknown) => ({
+ agentId: 'agent-1',
+ id: 'topic-1',
+ metadata: { scheduledRun },
+ userId: 'user-1',
+ workspaceId: null,
+});
+
+const delayedStart = {
+ createdAt: '2026-07-12T00:00:00.000Z',
+ kind: 'delayed_start',
+ runAt: '2026-07-12T03:00:00.000Z',
+ updatedAt: '2026-07-12T00:00:00.000Z',
+ userMessageId: 'user-scheduled',
+};
+
+const resumeAfterRateLimit = {
+ createdAt: '2026-07-12T00:00:00.000Z',
+ failedAssistantMessageId: 'assistant-failed',
+ kind: 'resume_after_rate_limit',
+ runAt: '2026-07-12T03:00:00.000Z',
+ source: 'heterogeneous_agent',
+ updatedAt: '2026-07-12T00:00:00.000Z',
+ userMessageId: 'user-message',
+};
+
+/** Parked by the pre-`kind` version: no `kind`, no `runAt`, gated on `resetsAt`. */
+const legacyRateLimitRun = {
+ createdAt: '2026-07-12T00:00:00.000Z',
+ failedAssistantMessageId: 'assistant-failed',
+ rateLimit: { rateLimitType: '5h', resetsAt: 1_768_000_000 },
+ reason: 'rate_limit',
+ source: 'heterogeneous_agent',
+ updatedAt: '2026-07-12T00:00:00.000Z',
+ userMessageId: 'user-message',
+};
+
+describe('scheduledTopicDispatch', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ mocks.getServerDB.mockResolvedValue({});
+ mocks.claimScheduledTopic.mockResolvedValue(true);
+ mocks.clearScheduledRun.mockResolvedValue(undefined);
+ mocks.execAgent.mockResolvedValue({ success: true });
+ mocks.findById.mockImplementation(async (id: string) => ({ content: 'summarize my PRs', id }));
+ });
+
+ it('runs a delayed start off its pre-persisted user turn, without writing it twice', async () => {
+ mocks.getDueScheduledTopics.mockResolvedValue([topic(delayedStart)]);
+
+ const response = await dispatch();
+
+ await expect(response.json()).resolves.toMatchObject({ claimed: 1, dispatched: 1 });
+ // The prompt is read back from the message, not from a copy in the payload โ€”
+ // so a pending run the user edited fires with the edited text.
+ expect(mocks.findById).toHaveBeenCalledWith('user-scheduled');
+ expect(mocks.execAgent).toHaveBeenCalledWith(
+ expect.objectContaining({
+ agentId: 'agent-1',
+ appContext: { topicId: 'topic-1' },
+ autoStart: true,
+ prompt: 'summarize my PRs',
+ suppressUserMessage: true,
+ trigger: 'scheduled',
+ }),
+ );
+ // A delayed start starts a fresh operation โ€” it is not resuming a prior one.
+ expect(mocks.execAgent.mock.calls[0][0]).not.toHaveProperty('resume', true);
+ // `suppressUserMessage` writes no user row, so the assistant turn anchors on
+ // `parentMessageId` alone โ€” without it the reply persists as a second root and
+ // renders above the prompt it answers (LOBE-11489).
+ expect(mocks.execAgent.mock.calls[0][0]).toMatchObject({ parentMessageId: 'user-scheduled' });
+ // Success hands the run to execAgent, so the topic leaves `scheduled`.
+ expect(mocks.clearScheduledRun).toHaveBeenCalledWith(
+ {},
+ 'topic-1',
+ 'running',
+ expect.any(String),
+ );
+ });
+
+ it('leaves the topic scheduled when the user deleted the pending message', async () => {
+ mocks.getDueScheduledTopics.mockResolvedValue([topic(delayedStart)]);
+ mocks.findById.mockResolvedValue(undefined);
+
+ const response = await dispatch();
+
+ await expect(response.json()).resolves.toMatchObject({ claimed: 1, dispatched: 0 });
+ expect(mocks.execAgent).not.toHaveBeenCalled();
+ });
+
+ it('resumes a rate-limited continuation from its failed turn', async () => {
+ mocks.getDueScheduledTopics.mockResolvedValue([topic(resumeAfterRateLimit)]);
+
+ await dispatch();
+
+ expect(mocks.execAgent).toHaveBeenCalledWith(
+ expect.objectContaining({
+ appContext: { topicId: 'topic-1' },
+ parentMessageId: 'assistant-failed',
+ resume: true,
+ }),
+ );
+ });
+
+ it('leaves the topic scheduled when dispatch fails, so the next tick retries', async () => {
+ mocks.getDueScheduledTopics.mockResolvedValue([topic(delayedStart)]);
+ mocks.execAgent.mockResolvedValue({ error: 'device offline', success: false });
+
+ const response = await dispatch();
+
+ await expect(response.json()).resolves.toMatchObject({ claimed: 1, dispatched: 0 });
+ expect(mocks.clearScheduledRun).not.toHaveBeenCalled();
+ });
+
+ it('dispatches a continuation parked by the pre-`kind` version, rather than discarding it', async () => {
+ // Upgrade-day rows: written before `kind`/`runAt` existed. Discarding them
+ // would silently drop a continuation the user is still waiting on.
+ mocks.getDueScheduledTopics.mockResolvedValue([topic(legacyRateLimitRun)]);
+
+ const response = await dispatch();
+
+ await expect(response.json()).resolves.toMatchObject({
+ discarded: 0,
+ dispatched: 1,
+ });
+ expect(mocks.execAgent).toHaveBeenCalledWith(
+ expect.objectContaining({ parentMessageId: 'assistant-failed', resume: true }),
+ );
+ });
+
+ it('discards an unparseable payload instead of re-surfacing it every tick', async () => {
+ // `runAt` is present (so the due query returns it) but the kind is unknown โ€”
+ // no handler can run it, and skipping would spin forever.
+ mocks.getDueScheduledTopics.mockResolvedValue([
+ topic({ kind: 'who_knows', runAt: '2026-07-12T03:00:00.000Z' }),
+ ]);
+
+ const response = await dispatch();
+
+ await expect(response.json()).resolves.toMatchObject({ discarded: 1, dispatched: 0 });
+ expect(mocks.claimScheduledTopic).not.toHaveBeenCalled();
+ expect(mocks.execAgent).not.toHaveBeenCalled();
+ expect(mocks.clearScheduledRun).toHaveBeenCalledWith({}, 'topic-1', 'active');
+ });
+
+ it('skips a topic another replica already claimed', async () => {
+ mocks.getDueScheduledTopics.mockResolvedValue([topic(delayedStart)]);
+ mocks.claimScheduledTopic.mockResolvedValue(false);
+
+ const response = await dispatch();
+
+ await expect(response.json()).resolves.toMatchObject({ claimed: 0, dispatched: 0 });
+ expect(mocks.execAgent).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/server/workflows-hono/task/handlers/scheduledRunKinds.ts b/src/server/workflows-hono/task/handlers/scheduledRunKinds.ts
new file mode 100644
index 00000000000..77864466722
--- /dev/null
+++ b/src/server/workflows-hono/task/handlers/scheduledRunKinds.ts
@@ -0,0 +1,105 @@
+import { HETERO_CONTINUE_PROMPT } from '@lobechat/const';
+import type { LobeChatDatabase } from '@lobechat/database';
+import type { ExecAgentResult, TopicScheduledRun, TopicScheduledRunKind } from '@lobechat/types';
+import { RequestTrigger } from '@lobechat/types';
+
+import { MessageModel } from '@/database/models/message';
+import type { TopicItem } from '@/database/schemas/topic';
+import { AiAgentService } from '@/server/services/aiAgent';
+
+export interface ScheduledRunContext {
+ db: LobeChatDatabase;
+ topic: TopicItem;
+ workspaceId?: string;
+}
+
+type ScheduledRunHandlers = {
+ [K in TopicScheduledRunKind]: (
+ run: Extract<TopicScheduledRun, { kind: K }>,
+ ctx: ScheduledRunContext,
+ ) => Promise<ExecAgentResult>;
+};
+
+/**
+ * Resume a heterogeneous turn that was parked when the provider rate-limited it.
+ *
+ * Mirrors `continueHeteroAfterError`: resume the surviving CLI session from the
+ * assistant-chain tail with the shared continuation instruction. The failed turn
+ * is deliberately NOT deleted before dispatch โ€” a dispatch failure must leave the
+ * user's error card and retry entry intact.
+ */
+const runResumeAfterRateLimit: ScheduledRunHandlers['resume_after_rate_limit'] = async (
+ run,
+ { db, topic, workspaceId },
+) => {
+ const messageModel = new MessageModel(db, topic.userId, workspaceId);
+ const failedMessage = await messageModel.findById(run.failedAssistantMessageId);
+ if (!failedMessage) throw new Error('Scheduled continuation message no longer exists');
+
+ return new AiAgentService(db, topic.userId, { workspaceId }).execAgent({
+ agentId: topic.agentId ?? undefined,
+ appContext: { topicId: topic.id },
+ parentMessageId: failedMessage.id,
+ prompt: HETERO_CONTINUE_PROMPT,
+ resume: true,
+ trigger: RequestTrigger.Cron,
+ });
+};
+
+/**
+ * Fire a run the user deliberately deferred ("send this in 3 hours").
+ *
+ * The user turn was already persisted at schedule time, so it is the last thing
+ * in history and `suppressUserMessage` runs the turn off it rather than injecting
+ * a second copy. That also makes the message the single source of truth for the
+ * prompt โ€” we read it back here rather than trusting a snapshot in the payload,
+ * so a pending run that the user edited fires with the edited text.
+ */
+const runDelayedStart: ScheduledRunHandlers['delayed_start'] = async (
+ run,
+ { db, topic, workspaceId },
+) => {
+ const messageModel = new MessageModel(db, topic.userId, workspaceId);
+ const userMessage = await messageModel.findById(run.userMessageId);
+ if (!userMessage) throw new Error('Scheduled user message no longer exists');
+
+ return new AiAgentService(db, topic.userId, { workspaceId }).execAgent({
+ agentId: topic.agentId ?? undefined,
+ appContext: { topicId: topic.id },
+ autoStart: true,
+ model: run.model,
+ // `suppressUserMessage` creates no user row, so the assistant turn anchors on
+ // `parentMessageId` alone. Leave it out and the reply persists as a SECOND
+ // root: the renderer walks the parentId forest depth-first, so it would land
+ // above the very prompt it answers (LOBE-11489).
+ parentMessageId: userMessage.id,
+ prompt: userMessage.content ?? '',
+ provider: run.provider,
+ // The user turn is already the tail of history โ€” don't write it twice.
+ suppressUserMessage: true,
+ trigger: RequestTrigger.Scheduled,
+ });
+};
+
+const HANDLERS: ScheduledRunHandlers = {
+ delayed_start: runDelayedStart,
+ resume_after_rate_limit: runResumeAfterRateLimit,
+};
+
+/**
+ * Run a due {@link TopicScheduledRun}. The dispatcher owns scanning, the claim
+ * lease and clearing state โ€” all kind-agnostic; a kind only decides *what*
+ * `execAgent` call to make. Adding a kind means adding a variant to
+ * {@link TopicScheduledRun} and an entry here; the type forces the pairing.
+ */
+export const dispatchScheduledRun = (
+ run: TopicScheduledRun,
+ ctx: ScheduledRunContext,
+): Promise<ExecAgentResult> => {
+ const handler = HANDLERS[run.kind] as (
+ run: TopicScheduledRun,
+ ctx: ScheduledRunContext,
+ ) => Promise<ExecAgentResult>;
+
+ return handler(run, ctx);
+};
diff --git a/src/server/workflows-hono/task/handlers/scheduledTopicDispatch.ts b/src/server/workflows-hono/task/handlers/scheduledTopicDispatch.ts
index b452a87e395..3249ad209c5 100644
--- a/src/server/workflows-hono/task/handlers/scheduledTopicDispatch.ts
+++ b/src/server/workflows-hono/task/handlers/scheduledTopicDispatch.ts
@@ -1,14 +1,13 @@
import { randomUUID } from 'node:crypto';
-import { HETERO_CONTINUE_PROMPT } from '@lobechat/const';
-import { RequestTrigger } from '@lobechat/types';
+import { parseTopicScheduledRun } from '@lobechat/types';
import debug from 'debug';
import type { Context } from 'hono';
-import { MessageModel } from '@/database/models/message';
import { TopicModel } from '@/database/models/topic';
import { getServerDB } from '@/database/server';
-import { AiAgentService } from '@/server/services/aiAgent';
+
+import { dispatchScheduledRun } from './scheduledRunKinds';
const log = debug('lobe-server:workflows:task:scheduled-topic-dispatch');
@@ -21,19 +20,23 @@ export interface ScheduledTopicDispatchPayload {
}
/**
- * Cron-style dispatcher for pure-topic continuations scheduled after a rate
- * limit. Registered as a QStash Schedule (e.g. `*\/10 * * * *`) pointing at this
- * endpoint. On each tick:
+ * Cron-style dispatcher for deferred runs on pure (non-Task) topics. Registered
+ * as a QStash Schedule (e.g. `*\/10 * * * *`) pointing at this endpoint. On each
+ * tick:
*
- * 1. Loads topics with `status = 'scheduled'` whose rate-limit window has
+ * 1. Loads topics with `status = 'scheduled'` whose `scheduledRun.runAt` has
* passed and that aren't under a live claim.
* 2. Atomically claims each (a lease on `metadata.scheduledRun.claim`) so two
- * ticks / replicas never trigger the same continuation twice.
- * 3. Re-runs the turn via `AiAgentService.execAgent` in resume mode โ€” the same
- * execution engine as a normal agent run, which already routes remote runs
- * to the topic's bound device via the device gateway.
+ * ticks / replicas never dispatch the same run twice.
+ * 3. Hands the run to its kind handler, which re-enters
+ * `AiAgentService.execAgent` โ€” the same execution engine as a normal agent
+ * run, which already routes remote runs to the topic's bound device via the
+ * device gateway.
+ *
+ * Everything here is kind-agnostic: scanning, the lease and clearing state are
+ * shared, and a {@link dispatchScheduledRun} handler decides only *what* to run.
*
- * This intentionally does NOT enter TaskLifecycle โ€” a pure topic just re-runs its
+ * This intentionally does NOT enter TaskLifecycle โ€” a pure topic just runs its
* agent. On success the scheduled state is cleared; on failure (e.g. the device
* is offline) the topic stays `scheduled` and the claim lease expires so the next
* tick retries โ€” the scheduled state is never lost.
@@ -57,9 +60,24 @@ export async function scheduledTopicDispatch(c: Context) {
let claimed = 0;
let dispatched = 0;
+ let discarded = 0;
for (const topic of due) {
- const scheduledRun = topic.metadata?.scheduledRun;
- if (!scheduledRun?.userMessageId) continue;
+ // Reads the current payload and the pre-`kind` legacy one alike โ€” the due
+ // query selects both, so this must dispatch both.
+ const run = parseTopicScheduledRun(topic.metadata?.scheduledRun);
+ if (!run) {
+ // A due topic whose payload we can't dispatch would re-surface on every
+ // tick forever, so drop the schedule instead of skipping it. Back to
+ // `active`: the topic itself is intact, only the schedule is unusable.
+ console.error(
+ '[scheduled-topic-dispatch] discarding unparseable scheduledRun topic=%s: %O',
+ topic.id,
+ topic.metadata?.scheduledRun,
+ );
+ await TopicModel.clearScheduledRun(db, topic.id, 'active').catch(() => undefined);
+ discarded += 1;
+ continue;
+ }
const claim = {
claimedAt: now.toISOString(),
@@ -76,32 +94,20 @@ export async function scheduledTopicDispatch(c: Context) {
const workspaceId = topic.workspaceId ?? undefined;
try {
- const messageModel = new MessageModel(db, topic.userId, workspaceId);
- const failedMessage = await messageModel.findById(scheduledRun.failedAssistantMessageId);
- if (!failedMessage) throw new Error('Scheduled continuation message no longer exists');
-
- // Match continueHeteroAfterError: resume the surviving CLI session from
- // the assistant-chain tail with the shared continuation instruction.
- // Do not delete the failed turn before dispatch; a dispatch failure must
- // leave the user's error card and retry entry intact.
- const result = await new AiAgentService(db, topic.userId, { workspaceId }).execAgent({
- agentId: topic.agentId ?? undefined,
- appContext: { topicId: topic.id },
- parentMessageId: failedMessage.id,
- prompt: HETERO_CONTINUE_PROMPT,
- resume: true,
- trigger: RequestTrigger.Cron,
- });
+ const result = await dispatchScheduledRun(run, { db, topic, workspaceId });
if (!result.success) {
- throw new Error(
- result.error || result.message || 'Scheduled continuation dispatch failed',
- );
+ throw new Error(result.error || result.message || 'Scheduled run dispatch failed');
}
// Success โ€” execAgent now owns the run; clear the scheduled state.
await TopicModel.clearScheduledRun(db, topic.id, 'running', claim.id);
dispatched += 1;
- log('dispatched topic=%s device=%s', topic.id, topic.metadata?.boundDeviceId);
+ log(
+ 'dispatched topic=%s kind=%s device=%s',
+ topic.id,
+ run.kind,
+ topic.metadata?.boundDeviceId,
+ );
} catch (err) {
// Leave the topic `scheduled` (e.g. device offline). The claim lease
// expires and the next tick retries โ€” scheduled state is never lost.
@@ -109,7 +115,7 @@ export async function scheduledTopicDispatch(c: Context) {
}
}
- return c.json({ claimed, dispatched, due: due.length, success: true });
+ return c.json({ claimed, discarded, dispatched, due: due.length, success: true });
} catch (error) {
console.error('[task/scheduled-topic-dispatch] Error:', error);
return c.json({ error: error instanceof Error ? error.message : 'Internal error' }, 500);
diff --git a/src/services/aiAgent.ts b/src/services/aiAgent.ts
index 2340894c65a..8a2ecd47107 100644
--- a/src/services/aiAgent.ts
+++ b/src/services/aiAgent.ts
@@ -2,12 +2,14 @@ import type {
ExecAgentAppContext,
ExecAgentResult,
RuntimeMentionedAgent,
+ ScheduleAgentRunParams,
+ ScheduleAgentRunResult,
UserInterventionConfig,
} from '@lobechat/types';
import { lambdaClient } from '@/libs/trpc/client';
-export type { ExecAgentResult };
+export type { ExecAgentResult, ScheduleAgentRunParams, ScheduleAgentRunResult };
/**
* Resume instruction for an operation that hit `human_approve_required`. When
@@ -172,6 +174,14 @@ class AiAgentService {
return await lambdaClient.aiAgent.execAgent.mutate(params, options);
}
+ /**
+ * Defer an agent run to a future time. Creates an empty `scheduled` topic that
+ * the backend cron fires once `runAt` passes; nothing runs now.
+ */
+ async scheduleAgentRun(params: ScheduleAgentRunParams): Promise<ScheduleAgentRunResult> {
+ return await lambdaClient.aiAgent.scheduleAgentRun.mutate(params);
+ }
+
/**
* Execute a sub-agent task (supports both Group and Single Agent mode)
*