🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
✨ feat(topic): schedule resumable hetero continuation (#17077)
Arvin Xufda97c698ed6
diff --git a/apps/server/src/routers/lambda/aiAgent.ts b/apps/server/src/routers/lambda/aiAgent.tsindex 70b38210d8f..1bcec8c21ac 100644--- a/apps/server/src/routers/lambda/aiAgent.ts+++ b/apps/server/src/routers/lambda/aiAgent.ts@@ -1,11 +1,12 @@import { type AgentStreamEvent } from '@lobechat/agent-gateway-client';import { parse } from '@lobechat/conversation-flow';-import { type TaskCurrentActivity, type TaskStatusResult } from '@lobechat/types';+import type { TaskCurrentActivity, TaskStatusResult } from '@lobechat/types';import {RequestTrigger,ThreadStatus,ThreadType,UserInterventionConfigSchema,+ workingDirConfigSchema,} from '@lobechat/types';import { TRPCError } from '@trpc/server';import debug from 'debug';@@ -29,8 +30,6 @@ import { AiChatService } from '@/server/services/aiChat';import { getFileProxyUrl } from '@/server/services/file';import { HeterogeneousAgentService } from '@/server/services/heterogeneousAgent';-import { workingDirConfigSchema } from './workingDirSchema';-const log = debug('lobe-server:ai-agent-router');const createUiMessageFileUrlResolver = () => {diff --git a/apps/server/src/routers/lambda/device.ts b/apps/server/src/routers/lambda/device.tsindex 1d12a1659dc..06ea3642c6d 100644--- a/apps/server/src/routers/lambda/device.ts+++ b/apps/server/src/routers/lambda/device.ts@@ -6,7 +6,7 @@ import type {DeviceWorkspaceShare,WorkingDirEntry,} from '@lobechat/types';-import { deriveWorktreePath } from '@lobechat/types';+import { deriveWorktreePath, workingDirConfigSchema } from '@lobechat/types';import { TRPCError } from '@trpc/server';import { z } from 'zod';@@ -25,7 +25,6 @@ import { type DeviceAttachment, deviceGateway } from '@/server/services/deviceGaimport { preserveWorkspaceCache } from './deviceWorkingDirs';import { assertWorkspaceDeviceVisible, assertWorkspaceRootApproved } from './deviceWorkspaceGuard';-import { workingDirConfigSchema } from './workingDirSchema';// Derive the zod enum from the canonical config so new platforms are// automatically covered without touching this file.diff --git a/apps/server/src/routers/lambda/topic.ts b/apps/server/src/routers/lambda/topic.tsindex ab13e2d88ce..112e418e0e6 100644--- a/apps/server/src/routers/lambda/topic.ts+++ b/apps/server/src/routers/lambda/topic.ts@@ -1,11 +1,11 @@import {+ chatTopicMetadataUpdateSchema,chatTopicStatusSchema,type HeteroSessionImportPayload,heteroSessionImportPayloadSchema,type RecentTopic,type RecentTopicGroup,type RecentTopicGroupMember,- serializedAgentHookSchema,} from '@lobechat/types';import { cleanObject } from '@lobechat/utils';import { inArray } from 'drizzle-orm';@@ -34,7 +34,6 @@ import {resolveContext,} from './_helpers/resolveContext';import { basicContextSchema } from './_schema/context';-import { workingDirConfigSchema } from './workingDirSchema';const topicProcedure = wsCompatProcedure.use(serverDatabase).use(async (opts) => {const { ctx } = opts;@@ -676,58 +675,7 @@ export const topicRouter = router({.input(z.object({id: z.string(),- metadata: z.object({- boundDeviceId: z.string().optional(),- heteroSessionId: z.string().optional(),- heteroSessionIdByWorkingDirectory: z.record(z.string(), z.string()).optional(),- model: z.string().optional(),- onboardingFeedback: z- .object({- comment: z.string().max(500).optional(),- rating: z.enum(['good', 'bad']),- submittedAt: z.string(),- })- .optional(),- onboardingSession: z- .object({- agentIdentityCompletedAt: z.string().optional(),- agentMarketplacePick: z- .object({- categoryHints: z.array(z.string()),- installedAgentIds: z.array(z.string()).optional(),- requestId: z.string(),- resolvedAt: z.string(),- selectedTemplateIds: z.array(z.string()).optional(),- skipReason: z.string().optional(),- skippedAgentIds: z.array(z.string()).optional(),- status: z.enum(['cancelled', 'skipped', 'submitted']),- })- .optional(),- discoveryCompletedAt: z.string().optional(),- finalAgentNames: z.array(z.string()).optional(),- finishedAt: z.string().optional(),- lastActiveAt: z.string().optional(),- phase: z.enum(['agent_identity', 'user_identity', 'discovery', 'summary']).optional(),- startedAt: z.string().optional(),- userIdentityCompletedAt: z.string().optional(),- version: z.number().optional(),- })- .optional(),- provider: z.string().optional(),- runningOperation: z- .object({- assistantMessageId: z.string(),- hooks: z.array(serializedAgentHookSchema).optional(),- operationId: z.string(),- scope: z.string().optional(),- threadId: z.string().nullish(),- })- .nullable()- .optional(),- repos: z.array(z.string()).optional(),- workingDirectory: z.string().optional(),- workingDirectoryConfig: workingDirConfigSchema.optional(),- }),+ metadata: chatTopicMetadataUpdateSchema,}),).mutation(async ({ input, ctx }) => {diff --git a/apps/server/src/routers/lambda/workingDirSchema.ts b/apps/server/src/routers/lambda/workingDirSchema.tsdeleted file mode 100644index f70f5ce7e3c..00000000000--- a/apps/server/src/routers/lambda/workingDirSchema.ts+++ /dev/null@@ -1,34 +0,0 @@-import { z } from 'zod';--const gitLinkedPullRequestSchema = z.object({- ciStatus: z.enum(['failure', 'pending', 'success', 'unknown']).optional(),- isDraft: z.boolean().optional(),- mergeable: z.string().optional(),- mergeStateStatus: z.string().optional(),- mergedAt: z.string().nullable().optional(),- number: z.number(),- reviewDecision: z.string().optional(),- state: z.string(),- title: z.string(),- url: z.string(),-});--export const workingDirConfigSchema = z.object({- git: z- .object({- activeWorktree: z.string().optional(),- branch: z.string().optional(),- detached: z.boolean().optional(),- github: z- .object({- extraPullRequestCount: z.number().optional(),- pullRequest: gitLinkedPullRequestSchema.nullable().optional(),- pullRequestStatus: z.enum(['error', 'gh-missing', 'ok']).optional(),- })- .optional(),- isWorktree: z.boolean().optional(),- })- .optional(),- path: z.string(),- repoType: z.enum(['git', 'github']).optional(),-});diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex da55354c1f8..7f337caefbf 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -117,6 +117,13 @@"cliRateLimitGuide.resetIn": "Time remaining","cliRateLimitGuide.resetInApprox": "About {{duration}}","cliRateLimitGuide.resetUnknown": "the quota resets",+ "cliRateLimitGuide.schedule.cancel": "Cancel auto-continue",+ "cliRateLimitGuide.schedule.continueAfter": "Continue in ~{{duration}}",+ "cliRateLimitGuide.schedule.continueAfterReset": "Continue after reset",+ "cliRateLimitGuide.schedule.retryNow": "Retry now",+ "cliRateLimitGuide.schedule.runNow": "Run now",+ "cliRateLimitGuide.schedule.scheduledAfterReset": "Scheduled. This run will continue automatically once the limit resets.",+ "cliRateLimitGuide.schedule.scheduledForApprox": "Scheduled. This run will continue automatically in about {{duration}}.","cliRateLimitGuide.title": "{{name}} is temporarily unavailable","codexInstallGuide.actions.openDocs": "Open Install Guide","codexInstallGuide.actions.openSystemTools": "Open System Tools",diff --git a/locales/en-US/topic.json b/locales/en-US/topic.jsonindex 5b818322c67..d0af0360f2d 100644--- a/locales/en-US/topic.json+++ b/locales/en-US/topic.json@@ -48,6 +48,7 @@"groupTitle.byStatus.paused": "Paused","groupTitle.byStatus.pending": "Needs attention","groupTitle.byStatus.running": "Running",+ "groupTitle.byStatus.scheduled": "Scheduled","groupTitle.byStatus.waitingForHuman": "Awaiting input","groupTitle.byTime.month": "This Month","groupTitle.byTime.today": "Today",@@ -147,6 +148,7 @@"management.status.idle": "Idle","management.status.paused": "Paused","management.status.running": "Running",+ "management.status.scheduled": "Scheduled","management.status.waitingForHuman": "Awaiting input","management.title": "Topics","management.view.card": "Card",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex 3e7af044695..52edf643209 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -117,6 +117,13 @@"cliRateLimitGuide.resetIn": "剩余时间","cliRateLimitGuide.resetInApprox": "约 {{duration}}","cliRateLimitGuide.resetUnknown": "额度重置",+ "cliRateLimitGuide.schedule.cancel": "取消自动继续",+ "cliRateLimitGuide.schedule.continueAfter": "约 {{duration}} 后继续",+ "cliRateLimitGuide.schedule.continueAfterReset": "重置后继续",+ "cliRateLimitGuide.schedule.retryNow": "立即重试",+ "cliRateLimitGuide.schedule.runNow": "立即运行",+ "cliRateLimitGuide.schedule.scheduledAfterReset": "已安排,限额重置后将自动继续本次运行。",+ "cliRateLimitGuide.schedule.scheduledForApprox": "已安排,约 {{duration}} 后将自动继续本次运行。","cliRateLimitGuide.title": "{{name}} 暂时不可用","codexInstallGuide.actions.openDocs": "打开安装指南","codexInstallGuide.actions.openSystemTools": "打开系统工具",diff --git a/locales/zh-CN/topic.json b/locales/zh-CN/topic.jsonindex 630aa6ad381..7bd0bd90154 100644--- a/locales/zh-CN/topic.json+++ b/locales/zh-CN/topic.json@@ -48,6 +48,7 @@"groupTitle.byStatus.paused": "已暂停","groupTitle.byStatus.pending": "待处理","groupTitle.byStatus.running": "进行中",+ "groupTitle.byStatus.scheduled": "已排期","groupTitle.byStatus.waitingForHuman": "等待处理","groupTitle.byTime.month": "本月","groupTitle.byTime.today": "今天",@@ -147,6 +148,7 @@"management.status.idle": "空闲中","management.status.paused": "已暂停","management.status.running": "运行中",+ "management.status.scheduled": "已排期","management.status.waitingForHuman": "等待响应","management.title": "话题","management.view.card": "卡片",diff --git a/packages/const/src/heterogeneousAgent.ts b/packages/const/src/heterogeneousAgent.tsnew file mode 100644index 00000000000..85d670bb035--- /dev/null+++ b/packages/const/src/heterogeneousAgent.ts@@ -0,0 +1,3 @@+/** Model instruction used when resuming an interrupted Claude Code or Codex session. */+export const HETERO_CONTINUE_PROMPT =+ 'Continue the task from where it stopped. The transcript above shows the work already completed — do not redo it.';diff --git a/packages/const/src/index.ts b/packages/const/src/index.tsindex 1483f4b5b42..d7026dd08a2 100644--- a/packages/const/src/index.ts+++ b/packages/const/src/index.ts@@ -9,6 +9,7 @@ export * from './editor';export * from './empty';export * from './fetch';export * from './file';+export * from './heterogeneousAgent';export * from './interests';export * from './layoutTokens';export * from './llmGenerationTracing';diff --git a/packages/database/src/models/__tests__/topic.test.ts b/packages/database/src/models/__tests__/topic.test.tsindex 06dac89a9e6..a90f2a24d62 100644--- a/packages/database/src/models/__tests__/topic.test.ts+++ b/packages/database/src/models/__tests__/topic.test.ts@@ -14,7 +14,6 @@ const otherUserId = 'topic-model-test-other-user';const topicModel = new TopicModel(serverDB, userId);-const now = () => new Date();const minutesAgo = (n: number) => new Date(Date.now() - n * 60 * 1000);describe('TopicModel', () => {@@ -638,4 +637,88 @@ describe('TopicModel', () => {expect(await topicModel.countTopicsForMemoryExtractor()).toBe(1);});});++ describe('scheduled continuation', () => {+ const scheduledRun = {+ createdAt: '2026-07-12T00:00:00.000Z',+ failedAssistantMessageId: 'assistant-failed',+ rateLimit: { resetsAt: 100 },+ reason: 'rate_limit' as const,+ source: 'heterogeneous_agent' as const,+ updatedAt: '2026-07-12T00:00:00.000Z',+ userMessageId: 'user-message',+ };++ it('returns only due scheduled topics and atomically grants one live claim', async () => {+ await serverDB.insert(topics).values([+ {+ id: 'scheduled-due',+ metadata: { scheduledRun },+ status: 'scheduled',+ title: 'due',+ userId,+ },+ {+ id: 'scheduled-future',+ metadata: { scheduledRun: { ...scheduledRun, rateLimit: { resetsAt: 300 } } },+ status: 'scheduled',+ title: 'future',+ userId,+ },+ ]);++ const due = await TopicModel.getDueScheduledTopics(serverDB, new Date(200_000));+ expect(due.map((topic) => topic.id)).toEqual(['scheduled-due']);++ const claim = {+ claimedAt: '2026-07-12T00:00:00.000Z',+ expiresAt: '2026-07-12T00:05:00.000Z',+ id: 'claim-1',+ };+ expect(+ await TopicModel.claimScheduledTopic(+ serverDB,+ 'scheduled-due',+ claim,+ new Date('2026-07-12T00:01:00.000Z'),+ ),+ ).toBe(true);+ expect(+ await TopicModel.claimScheduledTopic(+ serverDB,+ 'scheduled-due',+ { ...claim, id: 'claim-2' },+ new Date('2026-07-12T00:01:00.000Z'),+ ),+ ).toBe(false);+ });++ it('does not let a stale dispatcher clear a cancelled or re-claimed schedule', async () => {+ await serverDB.insert(topics).values({+ id: 'scheduled-claimed',+ metadata: {+ scheduledRun: { ...scheduledRun, claim: { claimedAt: '', expiresAt: '', id: 'new' } },+ },+ status: 'scheduled',+ title: 'claimed',+ userId,+ });++ await TopicModel.clearScheduledRun(serverDB, 'scheduled-claimed', 'running', 'old');+ const [unchanged] = await serverDB+ .select()+ .from(topics)+ .where(eq(topics.id, 'scheduled-claimed'));+ expect(unchanged.status).toBe('scheduled');+ expect(unchanged.metadata?.scheduledRun?.claim?.id).toBe('new');++ await TopicModel.clearScheduledRun(serverDB, 'scheduled-claimed', 'running', 'new');+ const [cleared] = await serverDB+ .select()+ .from(topics)+ .where(eq(topics.id, 'scheduled-claimed'));+ expect(cleared.status).toBe('running');+ expect(cleared.metadata?.scheduledRun).toBeNull();+ });+ });});diff --git a/packages/database/src/models/topic.ts b/packages/database/src/models/topic.tsindex 10ddb8dbb7e..db551f3864e 100644--- a/packages/database/src/models/topic.ts+++ b/packages/database/src/models/topic.ts@@ -144,11 +144,12 @@ const STATUS_SORT_RANK = sql`CASE ${topics.status}WHEN 'failed' THEN 1WHEN 'unread' THEN 2WHEN 'running' THEN 3- WHEN 'active' THEN 4- WHEN 'paused' THEN 5- WHEN 'completed' THEN 6- WHEN 'archived' THEN 7- ELSE 4 END`;+ WHEN 'scheduled' THEN 4+ WHEN 'active' THEN 5+ WHEN 'paused' THEN 6+ WHEN 'completed' THEN 7+ WHEN 'archived' THEN 8+ ELSE 5 END`;// Favorites always float to the top; the rest are ordered by the requested// strategy. `status` adds the priority bucket before the recency tiebreaker.@@ -1235,4 +1236,111 @@ export class TopicModel {return result[0]?.total ?? 0;};++ // **************** Scheduled continuation (backend cron) *************** //++ /**+ * Topics awaiting a backend-scheduled continuation after a rate limit.+ * 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+ * live claim (`scheduledRun.claim.expiresAt` is absent, or already expired) —+ * so a topic another replica is mid-dispatch on is skipped.+ */+ static async getDueScheduledTopics(+ db: LobeChatDatabase,+ now: Date = new Date(),+ ): Promise<TopicItem[]> {+ const nowEpochSeconds = Math.floor(now.getTime() / 1000);+ const nowIso = now.toISOString();+ 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}`,+ ),+ ),+ );+ }++ /**+ * Atomically claim a scheduled topic before dispatch, so two concurrent cron+ * ticks can't trigger the same continuation twice. Serializes on the row with+ * `SELECT … FOR UPDATE` (mirrors {@link updateMetadata}) and only writes the+ * lease if the topic is still `scheduled` and not already claimed by a live+ * lease. Returns `true` when this caller won the claim.+ */+ static async claimScheduledTopic(+ db: LobeChatDatabase,+ id: string,+ claim: { claimedAt: string; expiresAt: string; id: string },+ now: Date = new Date(),+ ): Promise<boolean> {+ return db.transaction(async (tx) => {+ const [row] = await tx+ .select({ metadata: topics.metadata, status: topics.status })+ .from(topics)+ .where(eq(topics.id, id))+ .for('update');++ if (!row || row.status !== 'scheduled') return false;++ const scheduledRun = row.metadata?.scheduledRun;+ if (!scheduledRun) return false;++ const existingClaim = scheduledRun.claim;+ const claimLive = existingClaim && new Date(existingClaim.expiresAt) > now;+ if (claimLive) return false;++ await tx+ .update(topics)+ .set({+ metadata: {+ ...row.metadata,+ scheduledRun: { ...scheduledRun, claim },+ } as ChatTopicMetadata,+ })+ .where(eq(topics.id, id));++ return true;+ });+ }++ /**+ * Clear the scheduled continuation and restore a normal status. Used both when+ * a continuation is successfully dispatched/executed and when it is cancelled.+ */+ static async clearScheduledRun(+ db: LobeChatDatabase,+ id: string,+ nextStatus: ChatTopicStatus = 'active',+ expectedClaimId?: string,+ ): Promise<void> {+ await db.transaction(async (tx) => {+ const [row] = await tx+ .select({ metadata: topics.metadata, status: topics.status })+ .from(topics)+ .where(eq(topics.id, id))+ .for('update');+ if (!row || row.status !== 'scheduled') return;+ if (expectedClaimId && row.metadata?.scheduledRun?.claim?.id !== expectedClaimId) return;++ const nextMetadata = { ...row.metadata, scheduledRun: null } as ChatTopicMetadata;+ await tx+ .update(topics)+ .set({ metadata: nextMetadata, status: nextStatus })+ .where(eq(topics.id, id));+ });+ }}diff --git a/packages/database/src/schemas/topic.ts b/packages/database/src/schemas/topic.tsindex 26f47f587af..c6cff746058 100644--- a/packages/database/src/schemas/topic.ts+++ b/packages/database/src/schemas/topic.ts@@ -50,6 +50,7 @@ export const topics = pgTable('running','paused','waitingForHuman',+ 'scheduled','failed','completed','archived',diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex e77941e047b..ee6898a02f9 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -526,6 +526,15 @@ export default {'cliRateLimitGuide.resetAt': 'Reset time','cliRateLimitGuide.resetIn': 'Time remaining','cliRateLimitGuide.resetInApprox': 'About {{duration}}',+ 'cliRateLimitGuide.schedule.cancel': 'Cancel auto-continue',+ 'cliRateLimitGuide.schedule.continueAfter': 'Continue in ~{{duration}}',+ 'cliRateLimitGuide.schedule.continueAfterReset': 'Continue after reset',+ 'cliRateLimitGuide.schedule.retryNow': 'Retry now',+ 'cliRateLimitGuide.schedule.runNow': 'Run now',+ 'cliRateLimitGuide.schedule.scheduledAfterReset':+ 'Scheduled. This run will continue automatically once the limit resets.',+ 'cliRateLimitGuide.schedule.scheduledForApprox':+ 'Scheduled. This run will continue automatically in about {{duration}}.','cliRateLimitGuide.resetUnknown': 'the quota resets','cliRateLimitGuide.title': '{{name}} is temporarily unavailable','codexInstallGuide.actions.openDocs': 'Open Install Guide',diff --git a/packages/locales/src/default/topic.ts b/packages/locales/src/default/topic.tsindex 31e6ec329e3..a757d569451 100644--- a/packages/locales/src/default/topic.ts+++ b/packages/locales/src/default/topic.ts@@ -57,6 +57,7 @@ export default {'groupTitle.byStatus.paused': 'Paused','groupTitle.byStatus.pending': 'Needs attention','groupTitle.byStatus.running': 'Running',+ 'groupTitle.byStatus.scheduled': 'Scheduled','groupTitle.byStatus.waitingForHuman': 'Awaiting input','groupTitle.byTime.month': 'This Month','groupTitle.byTime.today': 'Today',@@ -170,6 +171,7 @@ export default {'management.status.idle': 'Idle','management.status.paused': 'Paused','management.status.running': 'Running',+ 'management.status.scheduled': 'Scheduled','management.status.waitingForHuman': 'Awaiting input','management.title': 'Topics','management.view.card': 'Card',diff --git a/apps/server/src/routers/lambda/__tests__/workingDirSchema.test.ts b/packages/types/src/device.test.tssimilarity index 93%rename from apps/server/src/routers/lambda/__tests__/workingDirSchema.test.tsrename to packages/types/src/device.test.tsindex 5d8323294d9..df002145bfc 100644--- a/apps/server/src/routers/lambda/__tests__/workingDirSchema.test.ts+++ b/packages/types/src/device.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from 'vitest';-import { workingDirConfigSchema } from '../workingDirSchema';+import { workingDirConfigSchema } from './device';describe('workingDirConfigSchema', () => {it('preserves GitHub PR metadata under git.github', () => {diff --git a/packages/types/src/device.ts b/packages/types/src/device.tsindex 9b412238e96..60032572d59 100644--- a/packages/types/src/device.ts+++ b/packages/types/src/device.ts@@ -1,3 +1,5 @@+import { z } from 'zod';+export type ProjectSkillScope = 'device' | 'project';export type ProjectSkillSource = '.agents/skills' | '.claude/skills';@@ -634,3 +636,36 @@ export interface DeviceListProjectSkillsResult {/** Legacy source hint. Per-skill `scope` / `source` fields are authoritative. */source: ProjectSkillSource | null;}++const gitLinkedPullRequestSchema = z.object({+ ciStatus: z.enum(['failure', 'pending', 'success', 'unknown']).optional(),+ isDraft: z.boolean().optional(),+ mergeable: z.string().optional(),+ mergeStateStatus: z.string().optional(),+ mergedAt: z.string().nullable().optional(),+ number: z.number(),+ reviewDecision: z.string().optional(),+ state: z.string(),+ title: z.string(),+ url: z.string(),+});++export const workingDirConfigSchema = z.object({+ git: z+ .object({+ activeWorktree: z.string().optional(),+ branch: z.string().optional(),+ detached: z.boolean().optional(),+ github: z+ .object({+ extraPullRequestCount: z.number().optional(),+ pullRequest: gitLinkedPullRequestSchema.nullable().optional(),+ pullRequestStatus: z.enum(['error', 'gh-missing', 'ok']).optional(),+ })+ .optional(),+ isWorktree: z.boolean().optional(),+ })+ .optional(),+ path: z.string(),+ repoType: z.enum(['git', 'github']).optional(),+});diff --git a/packages/types/src/topic/topic.test.ts b/packages/types/src/topic/topic.test.tsnew file mode 100644index 00000000000..25ff1b66e2f--- /dev/null+++ b/packages/types/src/topic/topic.test.ts@@ -0,0 +1,37 @@+import { describe, expect, it } from 'vitest';++import { chatTopicMetadataUpdateSchema } from './topic';++describe('chatTopicMetadataUpdateSchema', () => {+ it('parses a scheduled heterogeneous continuation patch', () => {+ const metadata = {+ scheduledRun: {+ 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',+ },+ };++ expect(chatTopicMetadataUpdateSchema.parse(metadata)).toEqual(metadata);+ expect(chatTopicMetadataUpdateSchema.parse({ scheduledRun: null })).toEqual({+ scheduledRun: null,+ });+ });++ it('keeps the onboarding feedback comment limit at the shared contract boundary', () => {+ const result = chatTopicMetadataUpdateSchema.safeParse({+ onboardingFeedback: {+ comment: 'x'.repeat(501),+ rating: 'good',+ submittedAt: '2026-07-12T00:00:00.000Z',+ },+ });++ expect(result.success).toBe(false);+ });+});diff --git a/packages/types/src/topic/topic.ts b/packages/types/src/topic/topic.tsindex e24867a89f7..f26bb1a8739 100644--- a/packages/types/src/topic/topic.ts+++ b/packages/types/src/topic/topic.ts@@ -1,7 +1,9 @@import { z } from 'zod';import type { SerializedAgentHook } from '../agentHook';+import { serializedAgentHookSchema } from '../agentHook';import type { WorkingDirConfig } from '../device';+import { workingDirConfigSchema } from '../device';import type { BaseDataModel } from '../meta';// Type definitions@@ -191,6 +193,12 @@ export interface ChatTopicMetadata {scope?: string;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+ * `runningOperation`); every reader treats a nullish value as "not scheduled".+ */+ scheduledRun?: TopicScheduledRun | null;userMemoryExtractRunState?: TopicUserMemoryExtractRunState;userMemoryExtractStatus?: 'pending' | 'completed' | 'failed';/**@@ -215,6 +223,117 @@ export interface ChatTopicMetadata {workingDirectoryConfig?: WorkingDirConfig;}+/** Metadata patch accepted by the topic update API. */+export const chatTopicMetadataUpdateSchema = z.object({+ boundDeviceId: z.string().optional(),+ heteroSessionId: z.string().optional(),+ heteroSessionIdByWorkingDirectory: z.record(z.string(), z.string()).optional(),+ model: z.string().optional(),+ onboardingFeedback: z+ .object({+ comment: z.string().max(500).optional(),+ rating: z.enum(['good', 'bad']),+ submittedAt: z.string(),+ })+ .optional(),+ onboardingSession: z+ .object({+ agentIdentityCompletedAt: z.string().optional(),+ agentMarketplacePick: z+ .object({+ categoryHints: z.array(z.string()),+ installedAgentIds: z.array(z.string()).optional(),+ requestId: z.string(),+ resolvedAt: z.string(),+ selectedTemplateIds: z.array(z.string()).optional(),+ skipReason: z.string().optional(),+ skippedAgentIds: z.array(z.string()).optional(),+ status: z.enum(['cancelled', 'skipped', 'submitted']),+ })+ .optional(),+ discoveryCompletedAt: z.string().optional(),+ finalAgentNames: z.array(z.string()).optional(),+ finishedAt: z.string().optional(),+ lastActiveAt: z.string().optional(),+ phase: z.enum(['agent_identity', 'user_identity', 'discovery', 'summary']).optional(),+ startedAt: z.string().optional(),+ userIdentityCompletedAt: z.string().optional(),+ version: z.number().optional(),+ })+ .optional(),+ provider: z.string().optional(),+ repos: z.array(z.string()).optional(),+ runningOperation: z+ .object({+ assistantMessageId: z.string(),+ hooks: z.array(serializedAgentHookSchema).optional(),+ operationId: z.string(),+ scope: z.string().optional(),+ threadId: z.string().nullish(),+ })+ .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(),+ 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;@@ -235,6 +354,7 @@ export const TOPIC_STATUSES = ['running','paused','waitingForHuman',+ 'scheduled','failed','completed','archived',diff --git a/packages/utils/src/client/topic.test.ts b/packages/utils/src/client/topic.test.tsindex 7bf7bea8faa..08544015979 100644--- a/packages/utils/src/client/topic.test.ts+++ b/packages/utils/src/client/topic.test.ts@@ -292,6 +292,23 @@ describe('working directory topic helpers', () => {expect(getTopicWorkingDirectoryEffectivePath(topic)).toBe('/repo-fix');});+ it('tolerates a legacy object-form workingDirectory without crashing', () => {+ // Some heterogeneous (Claude Code) topics persisted a `WorkingDirConfig`+ // object into `workingDirectory` even though the field is typed as a string.+ // The helpers must extract its path instead of calling `dir.trim()` on it.+ const topic = createTopic('legacy-object', {+ workingDirectory: { path: '/Users/xxx/项目目录', repoType: 'git' },+ } as unknown as ChatTopic['metadata']);++ expect(getTopicWorkingDirectorySourcePath(topic)).toBe('/Users/xxx/项目目录');+ expect(getTopicWorkingDirectoryEffectivePath(topic)).toBe('/Users/xxx/项目目录');+ expect(() => groupTopicsByProject([topic], 'updatedAt')).not.toThrow();+ expect(groupTopicsByProject([topic], 'updatedAt')[0]).toMatchObject({+ id: 'project:/Users/xxx/项目目录',+ title: '项目目录',+ });+ });+it('groups worktree topics under the source project', () => {const topics = [createTopic(diff --git a/packages/utils/src/client/topic.ts b/packages/utils/src/client/topic.tsindex 39c34622268..2a8b6d539e5 100644--- a/packages/utils/src/client/topic.ts+++ b/packages/utils/src/client/topic.ts@@ -132,18 +132,24 @@ const normalizeOptionalWorkingDirectory = (dir: string | undefined): string | unreturn normalized || undefined;};+// Prefer the structured `workingDirectoryConfig`; fall back to the raw+// `workingDirectory`. `workingDirectory` is typed as a string, but a malformed+// topic may have persisted a `WorkingDirConfig` object into it (see #17050).+// Routing the whole thing through the extractor (which accepts `string |+// WorkingDirConfig`) yields the path for either shape instead of crashing+// `normalizeWorkingDirectory` with `dir.trim is not a function`.export const getTopicMetadataWorkingDirectorySourcePath = (metadata?: ChatTopicMetadata,): string | undefined =>normalizeOptionalWorkingDirectory(- getWorkingDirSourcePath(metadata?.workingDirectoryConfig) ?? metadata?.workingDirectory,+ getWorkingDirSourcePath(metadata?.workingDirectoryConfig ?? metadata?.workingDirectory),);export const getTopicMetadataWorkingDirectoryEffectivePath = (metadata?: ChatTopicMetadata,): string | undefined =>normalizeOptionalWorkingDirectory(- getWorkingDirEffectivePath(metadata?.workingDirectoryConfig) ?? metadata?.workingDirectory,+ getWorkingDirEffectivePath(metadata?.workingDirectoryConfig ?? metadata?.workingDirectory),);export const getTopicWorkingDirectorySourcePath = (topic: ChatTopic): string | undefined =>@@ -200,7 +206,7 @@ export const groupTopicsByProject = (// the sidebar surfaces "needs attention" in one place. The remaining buckets map// 1:1 to a status. The group `id` resolves its title via `groupTitle.byStatus.<id>`.export type TopicStatusBucket =- 'pending' | 'running' | 'active' | 'paused' | 'completed' | 'archived';+ 'pending' | 'running' | 'scheduled' | 'active' | 'paused' | 'completed' | 'archived';// Fixed priority order: `pending` (needs attention) comes first, then running,// then active; the remaining states fall below. Topics without a status are@@ -215,6 +221,7 @@ export type TopicStatusBucket =export const STATUS_GROUP_ORDER: TopicStatusBucket[] = ['pending','running',+ 'scheduled','active','paused','completed',@@ -236,6 +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".+ if (topic.status === 'scheduled') return 'scheduled';const status: ChatTopicStatus = topic.status ?? 'active';if (status === 'paused' || status === 'completed' || status === 'archived') return status;return 'active';diff --git a/src/components/ExecutionStatus.ts b/src/components/ExecutionStatus.tsindex 23918744903..d0022e1e836 100644--- a/src/components/ExecutionStatus.ts+++ b/src/components/ExecutionStatus.ts@@ -62,6 +62,7 @@ export const TOPIC_STATUS_VISUALS: Record<ChatTopicStatus, ExecutionStatusVisualfailed: VISUALS.failed,paused: VISUALS.paused,running: VISUALS.running,+ scheduled: VISUALS.scheduled,// `unread` rows render a custom ripple dot; this is the fallback glyph.unread: { color: cssVar.colorInfo, icon: CircleDot },waitingForHuman: VISUALS.waitingForHuman,diff --git a/src/features/Conversation/Error/index.tsx b/src/features/Conversation/Error/index.tsxindex f5e14e9e947..1311af73aa2 100644--- a/src/features/Conversation/Error/index.tsx+++ b/src/features/Conversation/Error/index.tsx@@ -14,10 +14,13 @@ import useRenderBusinessChatErrorMessageExtra from '@/business/client/hooks/useRimport ErrorContent from '@/features/Conversation/ChatItem/components/ErrorContent';import { dataSelectors, useConversationStore } from '@/features/Conversation/store';import HeterogeneousAgentStatusGuide from '@/features/Electron/HeterogeneousAgent/StatusGuide';+import type { HeterogeneousAgentScheduleState } from '@/features/Electron/HeterogeneousAgent/StatusGuide/types';import { useWorkspaceAwareNavigate } from '@/features/Workspace/useWorkspaceAwareNavigate';import { usePermission } from '@/hooks/usePermission';import { useProviderName } from '@/hooks/useProviderName';import dynamic from '@/libs/next/dynamic';+import { useChatStore } from '@/store/chat';+import { topicSelectors } from '@/store/chat/selectors';import { serverConfigSelectors, useServerConfigStore } from '@/store/serverConfig';import { getRuntimeErrorMessage } from '@/utils/locale/runtimeErrorMessage';@@ -295,12 +298,50 @@ const ErrorMessageExtra = memo<ErrorExtraProps>(scopeId: resolvedScopeId,});+ // Rate-limit waits are hours, not seconds, so instead of auto-retrying we let+ // the user hand the continuation off to the backend (topic `scheduled`). All+ // orchestration lives in the conversation store; this only binds the actions.+ const scheduleHeteroContinuation = useConversationStore((s) => s.scheduleHeteroContinuation);+ const cancelHeteroContinuation = useConversationStore((s) => s.cancelHeteroContinuation);+ const activeTopicScheduled = useChatStore(+ (s) => topicSelectors.currentActiveTopic(s)?.status === 'scheduled',+ );+ const scheduledResetsAt = useChatStore(+ (s) => topicSelectors.currentActiveTopic(s)?.metadata?.scheduledRun?.rateLimit?.resetsAt,+ );++ const isRateLimitError =+ canCreate &&+ isHeterogeneousAgentStatusGuideError(sessionErrorBody) &&+ sessionErrorBody.code === HeterogeneousAgentSessionErrorCode.RateLimit;+ const rateLimitInfo = isHeterogeneousAgentStatusGuideError(sessionErrorBody)+ ? sessionErrorBody.rateLimitInfo+ : undefined;++ const schedule: HeterogeneousAgentScheduleState | undefined = isRateLimitError+ ? {+ isScheduled: activeTopicScheduled,+ onCancel: () => void cancelHeteroContinuation(),+ onRunNow: () => void onRegenerate?.(),+ onSchedule: () =>+ void scheduleHeteroContinuation({+ failedAssistantMessageId: data.id,+ rateLimit: {+ rateLimitType: rateLimitInfo?.rateLimitType,+ resetsAt: rateLimitInfo?.resetsAt,+ },+ }),+ resetsAt: scheduledResetsAt ?? rateLimitInfo?.resetsAt,+ }+ : undefined;+if (isHeterogeneousAgentStatusGuideError(sessionErrorBody)) {return (<HeterogeneousAgentStatusGuideagentType={sessionErrorBody.agentType}autoRetry={autoRetry}error={sessionErrorBody}+ schedule={schedule}onOpenSystemTools={() => navigate('/settings/system-tools')}onRetry={handleManualRetry}/>diff --git a/src/features/Conversation/store/slices/generation/action.ts b/src/features/Conversation/store/slices/generation/action.tsindex a9fc7d1f8ff..4f6739c0bc0 100644--- a/src/features/Conversation/store/slices/generation/action.ts+++ b/src/features/Conversation/store/slices/generation/action.ts@@ -1,5 +1,5 @@import { AgentManagementIdentifier } from '@lobechat/builtin-tool-agent-management';-import { LOADING_FLAT } from '@lobechat/const';+import { HETERO_CONTINUE_PROMPT, LOADING_FLAT } from '@lobechat/const';import type {ChatImageItem,ConversationContext,@@ -94,9 +94,6 @@ const settleGenerationEntry = (* completed step (we resume the same session id), so the instruction only has to* stop the model from redoing them. Not localized: it is model input, not UI.*/-const HETERO_CONTINUE_PROMPT =- 'Continue the task from where it stopped. The transcript above shows the work already completed — do not redo it.';-/*** Where a hetero (Claude Code / Codex) run should execute, and whether it can* pick up the topic's existing CLI session.@@ -209,12 +206,21 @@ const runHeterogeneousFromExistingMessage = async (return assistantMsg.id;};+export interface HeteroContinuationScheduleParams {+ failedAssistantMessageId: string;+ rateLimit?: {+ rateLimitType?: string;+ resetsAt?: number;+ };+}+/*** Generation Actions** Handles generation control (stop, cancel, regenerate, continue)*/export interface GenerationAction {+ cancelHeteroContinuation: () => Promise<void>;/*** Cancel a specific operation*/@@ -332,6 +338,8 @@ export interface GenerationAction {*/resetHeteroOverloadRetry: (scopeId: string) => void;+ scheduleHeteroContinuation: (params: HeteroContinuationScheduleParams) => Promise<void>;+/*** Stop current generation*/@@ -359,6 +367,14 @@ export const generationSlice: StateCreator<[],GenerationAction> = (set, get) => ({+ cancelHeteroContinuation: async () => {+ const topicId = get().context.topicId;+ if (!topicId) return;++ const chatStore = useChatStore.getState();+ await chatStore.updateTopicStatus({ status: 'failed', topicId });+ await chatStore.updateTopicMetadata(topicId, { scheduledRun: null });+ },cancelOperation: (operationId: string, reason?: string) => {const state = get();const { hooks } = state;@@ -585,6 +601,41 @@ export const generationSlice: StateCreator<}},+ scheduleHeteroContinuation: async ({ failedAssistantMessageId, rateLimit }) => {+ const { context, dbMessages } = get();+ const topicId = context.topicId;+ if (!topicId) return;++ const messagesById = new Map(dbMessages.map((message) => [message.id, message]));+ let ancestor = messagesById.get(failedAssistantMessageId);+ while (ancestor?.parentId && ancestor.role !== 'user') {+ ancestor = messagesById.get(ancestor.parentId);+ }+ const userMessageId = ancestor?.role === 'user' ? ancestor.id : undefined;+ if (!userMessageId) return;++ const chatStore = useChatStore.getState();+ const topic = topicSelectors.getTopicById(topicId)(chatStore);+ const now = new Date().toISOString();++ await chatStore.updateTopicMetadata(topicId, {+ scheduledRun: {+ createdAt: now,+ failedAssistantMessageId,+ rateLimit,+ reason: 'rate_limit',+ resume: {+ sessionId: topic?.metadata?.heteroSessionId,+ workingDirectory: topic?.metadata?.workingDirectory,+ },+ source: 'heterogeneous_agent',+ updatedAt: now,+ userMessageId,+ },+ });+ await chatStore.updateTopicStatus({ status: 'scheduled', topicId });+ },+delAndRegenerateMessage: async (messageId: string) => {const { context, displayMessages } = get();const chatStore = useChatStore.getState();diff --git a/src/features/Electron/HeterogeneousAgent/StatusGuide/index.test.tsx b/src/features/Electron/HeterogeneousAgent/StatusGuide/index.test.tsxdeleted file mode 100644index 2a6d90b1579..00000000000--- a/src/features/Electron/HeterogeneousAgent/StatusGuide/index.test.tsx+++ /dev/null@@ -1,469 +0,0 @@-import { HeterogeneousAgentSessionErrorCode } from '@lobechat/electron-client-ipc';-import { render, screen } from '@testing-library/react';-import type { ReactNode } from 'react';-import { describe, expect, it, vi } from 'vitest';--import HeterogeneousAgentStatusGuide from './index';--vi.mock('@lobechat/const', () => ({- isDesktop: false,-}));--vi.mock('@lobehub/icons', () => ({- ClaudeCode: () => <span>Claude Code Icon</span>,- Codex: () => <span>Codex Icon</span>,-}));--vi.mock('@lobehub/ui', () => ({- Avatar: ({ avatar }: { avatar?: ReactNode }) => <div>{avatar}</div>,- Block: ({ children }: { children?: ReactNode }) => <div>{children}</div>,- Button: ({- children,- onClick,- type,- }: {- children?: ReactNode;- onClick?: () => void;- type?: string;- }) => (- <button data-variant={type} type="button" onClick={onClick}>- {children}- </button>- ),- Flexbox: ({ children }: { children?: ReactNode }) => <div>{children}</div>,- Highlighter: ({ children, style }: { children?: ReactNode; style?: React.CSSProperties }) => (- <pre style={style}>{children}</pre>- ),- Icon: () => <span>Icon</span>,- Snippet: ({ children, style }: { children?: ReactNode; style?: React.CSSProperties }) => (- <pre style={style}>{children}</pre>- ),- Text: ({ children }: { children?: ReactNode }) => <span>{children}</span>,-}));--vi.mock('antd-style', () => ({- createStaticStyles: (factory: (helpers: { css: () => string }) => Record<string, string>) =>- factory({ css: () => 'mock-class' }),- cssVar: {- colorBgElevated: 'transparent',- colorFillQuaternary: 'transparent',- },-}));--vi.mock('lucide-react', () => ({- Ban: () => <span>Ban Icon</span>,- ExternalLink: () => <span>ExternalLink Icon</span>,- Loader2: () => <span>Loader Icon</span>,- RotateCcw: () => <span>Retry Icon</span>,- Settings2: () => <span>Settings Icon</span>,-}));--vi.mock('react-i18next', () => ({- useTranslation: () => ({- i18n: {- language: 'en-US',- resolvedLanguage: 'en-US',- },- t: (- key: string,- options?: {- count?: number;- duration?: string;- message?: string;- name?: string;- resetAt?: string;- },- ) => {- if (key === 'cliRateLimitGuide.relative.day') {- return `${options?.count ?? 0} ${(options?.count ?? 0) === 1 ? 'day' : 'days'}`;- }-- if (key === 'cliRateLimitGuide.relative.hour') {- return `${options?.count ?? 0} ${(options?.count ?? 0) === 1 ? 'hour' : 'hours'}`;- }-- if (key === 'cliRateLimitGuide.relative.minute') {- return `${options?.count ?? 0} ${(options?.count ?? 0) === 1 ? 'minute' : 'minutes'}`;- }-- if (key === 'cliRateLimitGuide.resetInApprox') {- return `About ${options?.duration ?? ''}`;- }-- if (key === 'cliRateLimitGuide.afterReset') {- return `This account has reached its weekly usage limit. You can continue after ${options?.resetAt ?? ''}.`;- }-- if (key === 'cliOverloadedGuide.autoRetry.status') {- const o = options as { attempt?: number; max?: number; seconds?: number };- return `Upstream is temporarily overloaded (not your usage limit) · retry ${o?.attempt ?? 0}/${o?.max ?? 0} in ${o?.seconds ?? 0}s`;- }-- return (- (- {- 'cliAuthGuide.actions.openDocs': 'Open Sign-in Guide',- 'cliAuthGuide.actions.openSystemTools': 'Open System Tools',- 'cliAuthGuide.afterLogin':- 'After signing in again or refreshing credentials, retry your message.',- 'cliAuthGuide.desc': `${options?.name ?? ''} could not continue because its sign-in session expired or the credentials are invalid.`,- 'cliAuthGuide.errorDetails': 'Error details',- 'cliAuthGuide.runCommand': 'Run this in Terminal',- 'cliAuthGuide.title': `Sign in to ${options?.name ?? ''}`,- 'cliOverloadedGuide.actions.retry': 'Retry',- 'cliOverloadedGuide.autoRetry.actions.cancel': 'Stop auto-retry',- 'cliOverloadedGuide.autoRetry.actions.retryNow': 'Retry now',- 'cliOverloadedGuide.autoRetry.title': `${options?.name ?? ''} is busy — retrying automatically…`,- 'cliOverloadedGuide.desc': `${options?.name ?? ''}'s upstream model service is temporarily overloaded. This usually clears in a moment.`,- 'cliOverloadedGuide.errorDetails': 'Error details',- 'cliOverloadedGuide.retryHint':- 'Wait a few seconds and retry. If it keeps failing, the provider may be having a wider incident.',- 'cliOverloadedGuide.title': `${options?.name ?? ''} is temporarily overloaded`,- 'cliRateLimitGuide.actions.openSystemTools': 'Open System Tools',- 'cliRateLimitGuide.actions.retry': 'Retry message',- 'cliRateLimitGuide.desc': `${options?.name ?? ''} has reached its current usage limit and cannot continue this run right now.`,- 'cliRateLimitGuide.limitType': 'Quota cycle',- 'cliRateLimitGuide.limitTypes.weekCycle': 'Weekly',- 'cliRateLimitGuide.relative.resetComplete': 'Reset complete',- 'cliRateLimitGuide.relative.soon': 'Resets soon',- 'cliRateLimitGuide.resetAt': 'Reset time',- 'cliRateLimitGuide.resetIn': 'Time remaining',- 'cliRateLimitGuide.resetUnknown': 'the quota resets',- 'cliRateLimitGuide.title': `${options?.name ?? ''} is temporarily unavailable`,- 'claudeCodeInstallGuide.actions.openDocs': 'Open Install Guide',- 'claudeCodeInstallGuide.actions.openSystemTools': 'Open System Tools',- 'claudeCodeInstallGuide.afterInstall':- 'After installing, run Claude Code once to sign in, then retry your message.',- 'claudeCodeInstallGuide.desc':- 'Claude Code needs the Claude Code CLI to run locally. Install it first.',- 'claudeCodeInstallGuide.installWithBrew': 'Homebrew',- 'claudeCodeInstallGuide.installWithNpm': 'Recommended install',- 'claudeCodeInstallGuide.reason': `LobeHub could not start Claude Code: ${options?.message ?? ''}`,- 'claudeCodeInstallGuide.title': 'Install Claude Code CLI',- 'codexInstallGuide.actions.openDocs': 'Open Install Guide',- 'codexInstallGuide.actions.openSystemTools': 'Open System Tools',- 'codexInstallGuide.afterInstall':- 'After installing, run Codex once to sign in, then retry your message.',- 'codexInstallGuide.desc':- 'Codex Agent needs the Codex CLI to run locally. Install it first.',- 'codexInstallGuide.installWithBrew': 'Homebrew',- 'codexInstallGuide.installWithNpm': 'Recommended install',- 'codexInstallGuide.reason': `LobeHub could not start Codex: ${options?.message ?? ''}`,- 'codexInstallGuide.title': 'Install Codex CLI',- } as Record<string, string>- )[key] || key- );- },- }),-}));--vi.mock('@/services/electron/system', () => ({- electronSystemService: {- openExternalLink: vi.fn(),- },-}));--describe('HeterogeneousAgentStatusGuide', () => {- it('hides the duplicated reason for the known cli_not_found state', () => {- render(- <HeterogeneousAgentStatusGuide- error={{- code: HeterogeneousAgentSessionErrorCode.CliNotFound,- message: 'Codex CLI was not found',- }}- />,- );-- expect(screen.getByText('Install Codex CLI')).toBeInTheDocument();- expect(screen.queryByText(/LobeHub could not start Codex:/)).not.toBeInTheDocument();- });-- it('keeps the detailed reason for unexpected errors', () => {- render(- <HeterogeneousAgentStatusGuide- error={{- code: 'spawn_failed',- message: 'Permission denied',- }}- />,- );-- expect(- screen.getByText('LobeHub could not start Codex: Permission denied'),- ).toBeInTheDocument();- });-- it('uses a headerless layout in embedded mode', () => {- render(<HeterogeneousAgentStatusGuide variant={'embedded'} />);-- expect(screen.queryByText('Install Codex CLI')).not.toBeInTheDocument();- expect(- screen.getByText('Codex Agent needs the Codex CLI to run locally. Install it first.'),- ).toBeInTheDocument();- });-- it('renders Claude Code install guidance for the Claude CLI flow', () => {- render(- <HeterogeneousAgentStatusGuide- agentType={'claude-code'}- error={{- agentType: 'claude-code',- code: HeterogeneousAgentSessionErrorCode.CliNotFound,- message: 'Claude Code CLI was not found',- }}- />,- );-- expect(screen.getByText('Install Claude Code CLI')).toBeInTheDocument();- expect(- screen.getByText('Claude Code needs the Claude Code CLI to run locally. Install it first.'),- ).toBeInTheDocument();- expect(screen.getByText('curl -fsSL https://claude.ai/install.sh | bash')).toBeInTheDocument();- expect(screen.queryByText(/LobeHub could not start Claude Code:/)).not.toBeInTheDocument();- });-- it('renders sign-in guidance for auth-required errors', () => {- render(- <HeterogeneousAgentStatusGuide- agentType={'claude-code'}- error={{- agentType: 'claude-code',- code: HeterogeneousAgentSessionErrorCode.AuthRequired,- message: 'Failed to authenticate.\nAPI Error: 401',- }}- />,- );-- expect(screen.getByText('Sign in to Claude Code')).toBeInTheDocument();- expect(- screen.getByText(- 'Claude Code could not continue because its sign-in session expired or the credentials are invalid.',- ),- ).toBeInTheDocument();- expect(screen.getByText('Run this in Terminal')).toBeInTheDocument();- expect(screen.getByText('claude')).toBeInTheDocument();- expect(screen.getByText('Error details')).toBeInTheDocument();- const errorDetails = screen.getByText(- (_, element) => element?.textContent === 'Failed to authenticate.\nAPI Error: 401',- );- expect(errorDetails).toBeInTheDocument();- expect(errorDetails).toHaveStyle({- maxHeight: '200px',- overflow: 'auto',- });- });-- it('renders rate-limit guidance with structured metadata', () => {- vi.useFakeTimers();- vi.setSystemTime(new Date('2026-04-23T13:27:00+08:00'));- const onRetry = vi.fn();-- try {- render(- <HeterogeneousAgentStatusGuide- agentType={'claude-code'}- error={{- agentType: 'claude-code',- code: HeterogeneousAgentSessionErrorCode.RateLimit,- message: "You've hit your limit · resets 9am (Asia/Shanghai)",- rateLimitInfo: {- rateLimitType: 'seven_day',- resetsAt: 1_776_992_400,- },- }}- onRetry={onRetry}- />,- );-- expect(screen.getByText('Claude Code is temporarily unavailable')).toBeInTheDocument();- expect(screen.getByText('About 19 hours 33 minutes')).toBeInTheDocument();- expect(- screen.getByText(- /This account has reached its weekly usage limit. You can continue after .*\./,- ),- ).toBeInTheDocument();- expect(- screen.queryByText(- 'Claude Code has reached its current usage limit and cannot continue this run right now.',- ),- ).not.toBeInTheDocument();- expect(screen.getByText('Reset time')).toBeInTheDocument();- expect(screen.getByText('Time remaining')).toBeInTheDocument();- expect(screen.getByText('Quota cycle')).toBeInTheDocument();- expect(screen.getByText('Weekly')).toBeInTheDocument();- expect(screen.getAllByText(/Fri, Apr 24, 9:00 AM \(Asia\/Shanghai\)/)).toHaveLength(2);- expect(screen.queryByText('Open Install Guide')).not.toBeInTheDocument();- expect(screen.queryByText('Recommended install')).not.toBeInTheDocument();- const retryButton = screen.getByRole('button', { name: 'Retry message' });- expect(retryButton).not.toHaveAttribute('data-variant', 'primary');- retryButton.click();- expect(onRetry).toHaveBeenCalledTimes(1);- } finally {- vi.useRealTimers();- }- });-- it('allows retry after the quota reset time has passed', () => {- vi.useFakeTimers();- vi.setSystemTime(new Date('2026-04-25T13:27:00+08:00'));- const onRetry = vi.fn();-- try {- render(- <HeterogeneousAgentStatusGuide- agentType={'claude-code'}- error={{- agentType: 'claude-code',- code: HeterogeneousAgentSessionErrorCode.RateLimit,- message: "You've hit your limit",- rateLimitInfo: {- rateLimitType: 'seven_day',- resetsAt: 1_776_992_400,- },- }}- onRetry={onRetry}- />,- );-- const retryButton = screen.getByRole('button', { name: 'Retry message' });- expect(screen.getByText('Reset complete')).toBeInTheDocument();- expect(screen.queryByText('Resets soon')).not.toBeInTheDocument();- expect(retryButton).toHaveAttribute('data-variant', 'primary');- retryButton.click();- expect(onRetry).toHaveBeenCalledTimes(1);- } finally {- vi.useRealTimers();- }- });-- it('renders overloaded guidance with retry action', () => {- const onRetry = vi.fn();- render(- <HeterogeneousAgentStatusGuide- agentType={'claude-code'}- error={{- agentType: 'claude-code',- code: HeterogeneousAgentSessionErrorCode.Overloaded,- message:- 'API Error: 529 {"type":"error","error":{"type":"overloaded_error","message":"Overloaded"}}',- stderr:- 'API Error: 529 {"type":"error","error":{"type":"overloaded_error","message":"Overloaded"}}',- }}- onRetry={onRetry}- />,- );-- expect(screen.getByText('Claude Code is temporarily overloaded')).toBeInTheDocument();- expect(- screen.getByText(- "Claude Code's upstream model service is temporarily overloaded. This usually clears in a moment.",- ),- ).toBeInTheDocument();- expect(- screen.getByText(- 'Wait a few seconds and retry. If it keeps failing, the provider may be having a wider incident.',- ),- ).toBeInTheDocument();- expect(screen.getByText('Error details')).toBeInTheDocument();-- const retryButton = screen.getByRole('button', { name: 'Retry' });- retryButton.click();- expect(onRetry).toHaveBeenCalledTimes(1);- });-- it('renders the auto-retry progress state with countdown, retry-now and cancel', () => {- const onRetryNow = vi.fn();- const onCancel = vi.fn();- render(- <HeterogeneousAgentStatusGuide- agentType={'claude-code'}- autoRetry={{ attempt: 2, maxAttempts: 5, onCancel, onRetryNow, secondsLeft: 7 }}- error={{- agentType: 'claude-code',- code: HeterogeneousAgentSessionErrorCode.Overloaded,- message: 'API Error: 529 overloaded_error',- stderr: 'API Error: 529 overloaded_error',- }}- onRetry={vi.fn()}- />,- );-- // Progress copy makes clear it's the upstream (not the user's quota), with- // the countdown folded into the same line.- expect(screen.getByText('Claude Code is busy — retrying automatically…')).toBeInTheDocument();- expect(- screen.getByText(- 'Upstream is temporarily overloaded (not your usage limit) · retry 2/5 in 7s',- ),- ).toBeInTheDocument();-- // The static manual-retry card must NOT be shown while auto-retrying, and- // the raw error details are hidden to keep the progress card lightweight.- expect(screen.queryByText('Claude Code is temporarily overloaded')).not.toBeInTheDocument();- expect(screen.queryByText('Error details')).not.toBeInTheDocument();-- screen.getByRole('button', { name: 'Retry now' }).click();- expect(onRetryNow).toHaveBeenCalledTimes(1);-- screen.getByRole('button', { name: 'Stop auto-retry' }).click();- expect(onCancel).toHaveBeenCalledTimes(1);- });-- it('formats reset time with the active i18n locale instead of the system locale', () => {- vi.useFakeTimers();- vi.setSystemTime(new Date('2026-04-23T13:27:00+08:00'));-- const dateTimeFormatSpy = vi.spyOn(Intl, 'DateTimeFormat').mockImplementation(((- locale?: string | string[],- options?: Intl.DateTimeFormatOptions,- ) => {- const resolvedLocale = Array.isArray(locale) ? locale[0] : locale;-- return {- format: () => {- if (options?.weekday === 'short') {- return resolvedLocale === 'en-US' ? 'Fri 9:00 AM' : '周五 09:00';- }-- return resolvedLocale === 'en-US' ? 'Apr 24, 2026, 9:00 AM' : '2026年4月24日 09:00';- },- resolvedOptions: () => ({- calendar: 'gregory',- locale: resolvedLocale || 'zh-CN',- numberingSystem: 'latn',- timeZone: 'Asia/Shanghai',- }),- } as Intl.DateTimeFormat;- }) as typeof Intl.DateTimeFormat);-- try {- render(- <HeterogeneousAgentStatusGuide- agentType={'claude-code'}- error={{- agentType: 'claude-code',- code: HeterogeneousAgentSessionErrorCode.RateLimit,- message: "You've hit your limit · resets 9am (Asia/Shanghai)",- rateLimitInfo: {- rateLimitType: 'seven_day',- resetsAt: 1_776_992_400,- },- }}- />,- );-- expect(screen.getAllByText(/Fri 9:00 AM \(Asia\/Shanghai\)/)).toHaveLength(2);- expect(dateTimeFormatSpy).toHaveBeenCalledWith(- 'en-US',- expect.objectContaining({- hour: 'numeric',- minute: '2-digit',- weekday: 'short',- }),- );- } finally {- dateTimeFormatSpy.mockRestore();- vi.useRealTimers();- }- });-});diff --git a/src/features/Electron/HeterogeneousAgent/StatusGuide/index.tsx b/src/features/Electron/HeterogeneousAgent/StatusGuide/index.tsxindex 86a5c21dfde..fddf742f436 100644--- a/src/features/Electron/HeterogeneousAgent/StatusGuide/index.tsx+++ b/src/features/Electron/HeterogeneousAgent/StatusGuide/index.tsx@@ -11,7 +11,15 @@ import RateLimitState from './states/RateLimitState';import type { HeterogeneousAgentStatusGuideProps } from './types';const HeterogeneousAgentStatusGuide = memo<HeterogeneousAgentStatusGuideProps>(- ({ agentType = 'codex', autoRetry, error, onOpenSystemTools, onRetry, variant = 'inline' }) => {+ ({+ agentType = 'codex',+ autoRetry,+ error,+ onOpenSystemTools,+ onRetry,+ schedule,+ variant = 'inline',+ }) => {const config = resolveHeterogeneousAgentGuideConfig({agentType,errorAgentType: error?.agentType,@@ -22,6 +30,7 @@ const HeterogeneousAgentStatusGuide = memo<HeterogeneousAgentStatusGuideProps>(error,onOpenSystemTools,onRetry,+ schedule,variant,};diff --git a/src/features/Electron/HeterogeneousAgent/StatusGuide/states/RateLimitState.tsx b/src/features/Electron/HeterogeneousAgent/StatusGuide/states/RateLimitState.tsxindex 9c11133ea0e..ea937f3063c 100644--- a/src/features/Electron/HeterogeneousAgent/StatusGuide/states/RateLimitState.tsx+++ b/src/features/Electron/HeterogeneousAgent/StatusGuide/states/RateLimitState.tsx@@ -1,5 +1,6 @@-import { Text } from '@lobehub/ui';-import { createStaticStyles } from 'antd-style';+import { Flexbox, Text } from '@lobehub/ui';+import { Button } from '@lobehub/ui/base-ui';+import { CalendarClock, Play, RotateCcw } from 'lucide-react';import { useMemo } from 'react';import { useTranslation } from 'react-i18next';@@ -7,22 +8,6 @@ import GuideActions from '../GuideActions';import GuideShell from '../GuideShell';import type { HeterogeneousAgentGuideStateProps } from '../types';-const styles = createStaticStyles(({ css }) => ({- details: css`- display: grid;- grid-template-columns: max-content minmax(0, 1fr);- gap: 8px 12px;- align-items: baseline;- `,- label: css`- font-size: 12px;- white-space: nowrap;- `,- value: css`- min-width: 0;- `,-}));-const extractTimezoneLabel = (value?: string) => {if (!value) return;@@ -30,39 +15,45 @@ const extractTimezoneLabel = (value?: string) => {return match?.[1];};-const RateLimitState = ({ config, error, onRetry, variant }: HeterogeneousAgentGuideStateProps) => {+const RateLimitState = ({+ config,+ error,+ onOpenSystemTools,+ onRetry,+ schedule,+ variant,+}: HeterogeneousAgentGuideStateProps) => {const { t, i18n } = useTranslation('chat');const rawErrorDetails = error?.stderr || error?.message;- const resetsAt = error?.rateLimitInfo?.resetsAt;- const canRetry = !resetsAt || resetsAt * 1000 <= Date.now();const dateLocale = i18n.resolvedLanguage || i18n.language || undefined;+ // Prefer the persisted scheduled reset time so the "已安排" copy stays stable+ // even if the live error payload is missing it on reload.+ const effectiveResetsAt = schedule?.resetsAt ?? error?.rateLimitInfo?.resetsAt;const timezoneLabel = useMemo(() => extractTimezoneLabel(rawErrorDetails) || Intl.DateTimeFormat().resolvedOptions().timeZone,[rawErrorDetails],);const formattedResetAt = useMemo(() => {- if (!resetsAt) return;+ if (!effectiveResetsAt) return;try {return new Intl.DateTimeFormat(dateLocale, {- day: 'numeric',hour: 'numeric',minute: '2-digit',- month: 'short',...(timezoneLabel ? { timeZone: timezoneLabel } : {}),weekday: 'short',- }).format(new Date(resetsAt * 1000));+ }).format(new Date(effectiveResetsAt * 1000));} catch {try {return new Intl.DateTimeFormat(dateLocale, {dateStyle: 'medium',timeStyle: 'short',- }).format(new Date(resetsAt * 1000));+ }).format(new Date(effectiveResetsAt * 1000));} catch {return;}}- }, [dateLocale, resetsAt, timezoneLabel]);+ }, [dateLocale, effectiveResetsAt, timezoneLabel]);const rateLimitTypeLabel = useMemo(() => {const rateLimitType = error?.rateLimitInfo?.rateLimitType;if (!rateLimitType) return;@@ -73,14 +64,14 @@ const RateLimitState = ({ config, error, onRetry, variant }: HeterogeneousAgentGreturn rateLimitType.replaceAll('_', ' ');}, [error?.rateLimitInfo?.rateLimitType, t]);- const relativeResetText = useMemo(() => {- if (!resetsAt) return;+ // The "~X h Y m" duration string, reused both for the header hint and the+ // scheduling action/label copy.+ const relativeDuration = useMemo(() => {+ if (!effectiveResetsAt) return;- const now = Date.now();- const diffMs = Math.max(0, resetsAt * 1000 - now);+ const diffMs = Math.max(0, effectiveResetsAt * 1000 - Date.now());const totalMinutes = Math.floor(diffMs / 60_000);-- if (totalMinutes <= 0) return t('cliRateLimitGuide.relative.resetComplete');+ if (totalMinutes <= 0) return;const days = Math.floor(totalMinutes / (24 * 60));const hours = Math.floor((totalMinutes % (24 * 60)) / 60);@@ -93,10 +84,52 @@ const RateLimitState = ({ config, error, onRetry, variant }: HeterogeneousAgentGparts.push(t('cliRateLimitGuide.relative.minute', { count: minutes }));}- return parts.length > 0- ? t('cliRateLimitGuide.resetInApprox', { duration: parts.slice(0, 2).join(' ') })- : t('cliRateLimitGuide.relative.resetComplete');- }, [resetsAt, t]);+ return parts.length > 0 ? parts.slice(0, 2).join(' ') : undefined;+ }, [effectiveResetsAt, t]);+ const relativeResetText = useMemo(() => {+ if (!effectiveResetsAt) return;+ if (!relativeDuration) return t('cliRateLimitGuide.relative.soon');+ return t('cliRateLimitGuide.resetInApprox', { duration: relativeDuration });+ }, [effectiveResetsAt, relativeDuration, t]);++ const scheduleActions = useMemo(() => {+ if (!schedule) return;++ if (schedule.isScheduled) {+ return (+ <Flexbox horizontal gap={8} justify="flex-end" style={{ flexWrap: 'wrap' }}>+ <Button size="small" onClick={schedule.onCancel}>+ {t('cliRateLimitGuide.schedule.cancel')}+ </Button>+ <Button icon={<Play size={14} />} size="small" type="primary" onClick={schedule.onRunNow}>+ {t('cliRateLimitGuide.schedule.runNow')}+ </Button>+ </Flexbox>+ );+ }++ return (+ <Flexbox horizontal gap={8} justify="flex-end" style={{ flexWrap: 'wrap' }}>+ {onRetry && (+ <Button icon={<RotateCcw size={14} />} size="small" onClick={onRetry}>+ {t('cliRateLimitGuide.schedule.retryNow')}+ </Button>+ )}+ <Button+ icon={<CalendarClock size={14} />}+ size="small"+ type="primary"+ onClick={schedule.onSchedule}+ >+ {relativeDuration+ ? t('cliRateLimitGuide.schedule.continueAfter', { duration: relativeDuration })+ : t('cliRateLimitGuide.schedule.continueAfterReset')}+ </Button>+ </Flexbox>+ );+ }, [onRetry, relativeDuration, schedule, t]);++ const isScheduled = Boolean(schedule?.isScheduled);return (<GuideShell@@ -104,52 +137,61 @@ const RateLimitState = ({ config, error, onRetry, variant }: HeterogeneousAgentGtitle={t('cliRateLimitGuide.title', { name: config.title })}variant={variant}actions={- <GuideActions- retryLabel={t('cliRateLimitGuide.actions.retry')}- retryPrimary={canRetry}- onRetry={onRetry}- />+ scheduleActions ?? (+ <GuideActions+ retryLabel={t('cliRateLimitGuide.actions.retry')}+ openSystemToolsLabel={+ onRetry ? undefined : t('cliRateLimitGuide.actions.openSystemTools')+ }+ onOpenSystemTools={onRetry ? undefined : onOpenSystemTools}+ onRetry={onRetry}+ />+ )}headerDescription={<Text type="secondary">- {t('cliRateLimitGuide.afterReset', {- resetAt: formattedResetAt- ? `${formattedResetAt}${timezoneLabel ? ` (${timezoneLabel})` : ''}`- : t('cliRateLimitGuide.resetUnknown'),- })}+ {isScheduled+ ? relativeDuration+ ? t('cliRateLimitGuide.schedule.scheduledForApprox', { duration: relativeDuration })+ : t('cliRateLimitGuide.schedule.scheduledAfterReset')+ : t('cliRateLimitGuide.afterReset', {+ resetAt: formattedResetAt+ ? `${formattedResetAt}${timezoneLabel ? ` (${timezoneLabel})` : ''}`+ : t('cliRateLimitGuide.resetUnknown'),+ })}</Text>}>- <div className={styles.details}>+ <Flexbox gap={8}>{formattedResetAt && (- <>- <Text strong className={styles.label}>+ <Flexbox horizontal gap={8} style={{ alignItems: 'baseline' }}>+ <Text strong style={{ fontSize: 12 }}>{t('cliRateLimitGuide.resetAt')}</Text>- <div className={styles.value}>+ <Flexbox+ horizontal+ gap={8}+ style={{ alignItems: 'baseline', flexWrap: 'nowrap', whiteSpace: 'nowrap' }}+ ><Text>{`${formattedResetAt}${timezoneLabel ? ` (${timezoneLabel})` : ''}`}</Text>- </div>- </>- )}-- {relativeResetText && (- <>- <Text strong className={styles.label}>- {t('cliRateLimitGuide.resetIn')}- </Text>- <Text className={styles.value}>{relativeResetText}</Text>- </>+ {relativeResetText && (+ <Text style={{ fontSize: 12, whiteSpace: 'nowrap' }} type="secondary">+ {relativeResetText}+ </Text>+ )}+ </Flexbox>+ </Flexbox>)}{rateLimitTypeLabel && (- <>- <Text strong className={styles.label}>+ <Flexbox horizontal align="center" gap={8}>+ <Text strong style={{ fontSize: 12 }}>{t('cliRateLimitGuide.limitType')}</Text>- <Text className={styles.value}>{rateLimitTypeLabel}</Text>- </>+ <Text>{rateLimitTypeLabel}</Text>+ </Flexbox>)}- </div>+ </Flexbox></GuideShell>);};diff --git a/src/features/Electron/HeterogeneousAgent/StatusGuide/types.ts b/src/features/Electron/HeterogeneousAgent/StatusGuide/types.tsindex db933a09232..80188904efe 100644--- a/src/features/Electron/HeterogeneousAgent/StatusGuide/types.ts+++ b/src/features/Electron/HeterogeneousAgent/StatusGuide/types.ts@@ -15,12 +15,28 @@ export interface HeterogeneousAgentAutoRetryState {secondsLeft: number;}+/**+ * View-model for the rate-limit guide's "continue after reset" scheduling. When+ * present, the card can hand the continuation off to the backend instead of+ * requiring a manual retry. `isScheduled` toggles between the unscheduled entry+ * (schedule / retry-now) and the scheduled state (run-now / cancel).+ */+export interface HeterogeneousAgentScheduleState {+ isScheduled: boolean;+ onCancel: () => void;+ onRunNow: () => void;+ onSchedule: () => void;+ /** Epoch seconds when the rate-limit window resets (for the "~X h" copy). */+ resetsAt?: number;+}+export interface HeterogeneousAgentStatusGuideProps {agentType?: string;autoRetry?: HeterogeneousAgentAutoRetryState;error?: HeterogeneousAgentSessionError | null;onOpenSystemTools?: () => void;onRetry?: () => void;+ schedule?: HeterogeneousAgentScheduleState;variant?: HeterogeneousAgentStatusGuideVariant;}@@ -43,5 +59,6 @@ export interface HeterogeneousAgentGuideStateProps {error?: HeterogeneousAgentSessionError | null;onOpenSystemTools?: () => void;onRetry?: () => void;+ schedule?: HeterogeneousAgentScheduleState;variant: HeterogeneousAgentStatusGuideVariant;}diff --git a/src/server/workflows-hono/task/handlers/scheduledTopicDispatch.ts b/src/server/workflows-hono/task/handlers/scheduledTopicDispatch.tsnew file mode 100644index 00000000000..b452a87e395--- /dev/null+++ b/src/server/workflows-hono/task/handlers/scheduledTopicDispatch.ts@@ -0,0 +1,117 @@+import { randomUUID } from 'node:crypto';++import { HETERO_CONTINUE_PROMPT } from '@lobechat/const';+import { RequestTrigger } 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';++const log = debug('lobe-server:workflows:task:scheduled-topic-dispatch');++/** How long a claim lease is held before another tick may re-claim the topic. */+const CLAIM_LEASE_MS = 5 * 60 * 1000;++export interface ScheduledTopicDispatchPayload {+ /** When true, only report which topics are due without claiming/dispatching. */+ dryRun?: boolean;+}++/**+ * 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:+ *+ * 1. Loads topics with `status = 'scheduled'` whose rate-limit window 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.+ *+ * This intentionally does NOT enter TaskLifecycle — a pure topic just re-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.+ *+ * Signature verification is handled by the `qstashAuth` middleware on the route.+ */+export async function scheduledTopicDispatch(c: Context) {+ try {+ const body = (await c.req.json().catch(() => ({}))) as ScheduledTopicDispatchPayload;+ const { dryRun = false } = body ?? {};++ const db = await getServerDB();+ const now = new Date();+ const due = await TopicModel.getDueScheduledTopics(db, now);++ log('scan: due=%d dryRun=%s', due.length, dryRun);++ if (dryRun || due.length === 0) {+ return c.json({ claimed: 0, dispatched: 0, dryRun, due: due.length, success: true });+ }++ let claimed = 0;+ let dispatched = 0;+ for (const topic of due) {+ const scheduledRun = topic.metadata?.scheduledRun;+ if (!scheduledRun?.userMessageId) continue;++ const claim = {+ claimedAt: now.toISOString(),+ expiresAt: new Date(now.getTime() + CLAIM_LEASE_MS).toISOString(),+ id: randomUUID(),+ };++ const won = await TopicModel.claimScheduledTopic(db, topic.id, claim, now).catch((err) => {+ console.error('[scheduled-topic-dispatch] claim failed topic=%s: %O', topic.id, err);+ return false;+ });+ if (!won) continue;+ claimed += 1;++ 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,+ });+ if (!result.success) {+ throw new Error(+ result.error || result.message || 'Scheduled continuation 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);+ } catch (err) {+ // Leave the topic `scheduled` (e.g. device offline). The claim lease+ // expires and the next tick retries — scheduled state is never lost.+ console.error('[scheduled-topic-dispatch] dispatch failed topic=%s: %O', topic.id, err);+ }+ }++ return c.json({ claimed, 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/server/workflows-hono/task/index.ts b/src/server/workflows-hono/task/index.tsindex 286adb92338..0632b3ffe7a 100644--- a/src/server/workflows-hono/task/index.ts+++ b/src/server/workflows-hono/task/index.ts@@ -4,6 +4,7 @@ import { qstashAuth } from '../middlewares/qstashAuth';import { heartbeatTick } from './handlers/heartbeatTick';import { onTopicComplete } from './handlers/onTopicComplete';import { scheduleDispatch } from './handlers/scheduleDispatch';+import { scheduledTopicDispatch } from './handlers/scheduledTopicDispatch';import { scheduleExecute } from './handlers/scheduleExecute';import { watchdog } from './handlers/watchdog';@@ -13,6 +14,7 @@ app.post('/on-topic-complete', qstashAuth(), onTopicComplete);app.post('/heartbeat-tick', qstashAuth(), heartbeatTick);app.post('/schedule-dispatch', qstashAuth(), scheduleDispatch);app.post('/schedule-execute', qstashAuth(), scheduleExecute);+app.post('/scheduled-topic-dispatch', qstashAuth(), scheduledTopicDispatch);app.post('/watchdog', qstashAuth(), watchdog);export default app;