🤯 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(hetero): hand off rate-limited chats to another agent (#19080)
Arvin Xu066d22fd0cab
diff --git a/apps/server/src/routers/lambda/topic.ts b/apps/server/src/routers/lambda/topic.tsindex 407009c57ee..545431e7523 100644--- a/apps/server/src/routers/lambda/topic.ts+++ b/apps/server/src/routers/lambda/topic.ts@@ -248,6 +248,22 @@ const recordTopicShareAudit = async (};export const topicRouter = router({+ cancelRateLimitContinuation: topicProcedure+ .use(withScopedPermission('topic:update'))+ .input(z.object({ id: z.string() }))+ .mutation(async ({ input, ctx }) => {+ await assertCanUseTopicTargets(guardCtx(ctx), [input.id]);+ await assertCreatorTopicTargets(guardCtx(ctx), [input.id]);+ const result = await ctx.topicModel.cancelRateLimitContinuation(input.id);+ if (result.status === 'busy')+ throw new TRPCError({+ code: 'CONFLICT',+ message: 'The source continuation has already been claimed or started.',+ });+ if (result.status === 'unchanged') return null;+ return { metadata: result.metadata };+ }),+getTopicDetail: topicProcedure.input(z.object({ id: z.string() })).query(async ({ input, ctx }) => {diff --git a/locales/en-US/chat.json b/locales/en-US/chat.jsonindex 6ab337a47c1..4c8247b2134 100644--- a/locales/en-US/chat.json+++ b/locales/en-US/chat.json@@ -127,6 +127,7 @@"cliOverloadedGuide.title": "{{name}} is temporarily overloaded","cliRateLimitGuide.actions.openSystemTools": "Open System Tools","cliRateLimitGuide.actions.retry": "Retry message",+ "cliRateLimitGuide.actions.transfer": "Transfer to another Agent","cliRateLimitGuide.afterReset": "This account has reached its current usage limit. You can continue after {{resetAt}}.","cliRateLimitGuide.afterResetWithLimitType": "This account has reached its {{limitType}} usage limit. You can continue after {{resetAt}}.","cliRateLimitGuide.desc": "{{name}} has reached its current usage limit and cannot continue this run right now.",@@ -1045,6 +1046,7 @@"heteroAgent.switchCwd.content": "Agent sessions are pinned to a working directory. Switching will start a new session for this topic — chat messages stay, but the previous session context cannot be resumed.","heteroAgent.switchCwd.ok": "Switch and start new session","heteroAgent.switchCwd.title": "Switch working directory?",+ "heteroRateLimit.cancelFailed": "Could not cancel the scheduled continuation. It may already be claimed or running. Refresh the conversation to check its status.","hideForYou": "Direct message content is hidden. Please enable 'Show Direct Message Content' in settings to view.","history.title": "The Agent will keep only the latest {{count}} messages.","historyRange": "History Range",@@ -1216,10 +1218,12 @@"messageForward.success": "Forwarded to {{title}}","messageForward.successMulti": "Forwarded to {{count}} agents","messageForward.topic.context": "Topic context",- "messageForward.topic.description": "The user and assistant messages in this topic will be sent as context. Tool messages are excluded.",+ "messageForward.topic.description": "The selected Agent will receive this topic's context and continue the work.",+ "messageForward.topic.handoffFailed": "Transfer did not start because the source continuation could not be cancelled. It may already be running. Refresh the conversation and check its status.","messageForward.topic.header": "The following topic was forwarded from another conversation. Please use it as context and continue:","messageForward.topic.loadFailed": "Could not load this topic for forwarding","messageForward.topic.modalTitle": "Forward topic to Agent",+ "messageForward.topic.sourceSchedulePaused": "Transfer could not be confirmed. The original scheduled continuation is paused. Check the target conversation before retrying or scheduling again.","messageForward.transcript.header": "The following {{count}} messages were forwarded from another conversation. Please use them as context and continue:","messageLink.openInSideBrowser": "Open in side browser","messageLongCollapse.collapse": "Show less",diff --git a/locales/zh-CN/chat.json b/locales/zh-CN/chat.jsonindex b6c1a02ed33..a7b5fb07960 100644--- a/locales/zh-CN/chat.json+++ b/locales/zh-CN/chat.json@@ -127,6 +127,7 @@"cliOverloadedGuide.title": "{{name}} 服务暂时繁忙","cliRateLimitGuide.actions.openSystemTools": "打开系统工具","cliRateLimitGuide.actions.retry": "重试这条消息",+ "cliRateLimitGuide.actions.transfer": "转派给其他 Agent 继续","cliRateLimitGuide.afterReset": "当前账号已达到当前使用上限,{{resetAt}} 后可继续使用。","cliRateLimitGuide.afterResetWithLimitType": "当前账号已达到{{limitType}}使用上限,{{resetAt}} 后可继续使用。","cliRateLimitGuide.desc": "{{name}} 已达到当前使用上限,这次运行暂时无法继续。",@@ -1045,6 +1046,7 @@"heteroAgent.switchCwd.content": "Agent 会话会绑定到具体的工作目录。切换后将为当前话题开启一个新会话——消息记录会保留,但之前会话的上下文无法恢复。","heteroAgent.switchCwd.ok": "切换并开启新会话","heteroAgent.switchCwd.title": "切换工作目录?",+ "heteroRateLimit.cancelFailed": "未能取消定时续跑,任务可能已被领取或正在运行。请刷新会话确认状态。","hideForYou": "私信内容已隐藏。可在设置中开启「显示私信内容」查看","history.title": "助理将仅保留最近 {{count}} 条消息","historyRange": "历史范围",@@ -1216,10 +1218,12 @@"messageForward.success": "已转发给 {{title}}","messageForward.successMulti": "已转发给 {{count}} 个智能体","messageForward.topic.context": "话题上下文",- "messageForward.topic.description": "该话题中的用户和助手消息将作为上下文发送,工具消息不会被转发。",+ "messageForward.topic.description": "选中的 Agent 将获取该话题的上下文并继续处理。",+ "messageForward.topic.handoffFailed": "未能取消源会话续跑,转交未开始。源任务可能已被领取或正在运行,请刷新会话确认状态。","messageForward.topic.header": "以下话题转发自另一段对话,请将其作为上下文并继续处理:","messageForward.topic.loadFailed": "无法加载该话题进行转发","messageForward.topic.modalTitle": "转发话题给助手",+ "messageForward.topic.sourceSchedulePaused": "无法确认转交结果,原定时续跑已暂停。请先检查目标会话,再重试或重新安排续跑。","messageForward.transcript.header": "以下 {{count}} 条消息转发自另一段对话,请将其作为上下文并继续处理:","messageLink.openInSideBrowser": "在侧边浏览器中打开","messageLongCollapse.collapse": "收起",diff --git a/packages/database/src/models/__tests__/topic.test.ts b/packages/database/src/models/__tests__/topic.test.tsindex bd43a104930..09e2a97b80f 100644--- a/packages/database/src/models/__tests__/topic.test.ts+++ b/packages/database/src/models/__tests__/topic.test.ts@@ -1,5 +1,5 @@// @vitest-environment node-import { eq } from 'drizzle-orm';+import { eq, sql } from 'drizzle-orm';import { afterEach, beforeEach, describe, expect, it } from 'vitest';import { getTestDB } from '../../core/getTestDB';@@ -35,6 +35,97 @@ describe('TopicModel', () => {await serverDB.delete(users);});+ describe('rate-limit cancellation', () => {+ const run = {+ createdAt: '2026-09-19T00:00:00.000Z',+ failedAssistantMessageId: 'failed-message',+ kind: 'resume_after_rate_limit' as const,+ source: 'heterogeneous_agent' as const,+ runAt: '2026-09-19T01:00:00.000Z',+ updatedAt: '2026-09-19T00:00:00.000Z',+ userMessageId: 'user-message',+ };+ const claim = { claimedAt: run.createdAt, expiresAt: run.runAt, id: 'dispatcher' };++ it('cancels status and payload together and prevents a later dispatcher claim', async () => {+ const topic = await topicModel.create({ title: 'source' });+ await topicModel.armScheduledRun(topic.id, run);+ const result = await topicModel.cancelRateLimitContinuation(topic.id);+ expect(result.status).toBe('cancelled');+ const [row] = await serverDB.select().from(topics).where(eq(topics.id, topic.id));+ expect(row.status).toBe('failed');+ expect(row.metadata?.scheduledRun).toBeNull();+ expect(await TopicModel.claimScheduledTopic(serverDB, topic.id, claim)).toBe(false);+ });++ it('refuses cancellation after the dispatcher claims, even if its lease expired', async () => {+ const topic = await topicModel.create({ title: 'source' });+ await topicModel.armScheduledRun(topic.id, run);+ await TopicModel.claimScheduledTopic(serverDB, topic.id, claim, new Date(run.createdAt));+ expect(await topicModel.cancelRateLimitContinuation(topic.id)).toEqual({ status: 'busy' });+ const [row] = await serverDB.select().from(topics).where(eq(topics.id, topic.id));+ expect(row.status).toBe('scheduled');+ expect(row.metadata?.scheduledRun?.claim?.id).toBe('dispatcher');+ });++ it('rolls back both fields when the database rejects cancellation', async () => {+ const topic = await topicModel.create({ title: 'source' }, 'cancel-rejected');+ await topicModel.armScheduledRun(topic.id, run);+ await serverDB.execute(+ sql`ALTER TABLE topics ADD CONSTRAINT test_cancel_failure CHECK (id != 'cancel-rejected' OR status != 'failed')`,+ );+ try {+ await expect(topicModel.cancelRateLimitContinuation(topic.id)).rejects.toThrow();+ const [row] = await serverDB.select().from(topics).where(eq(topics.id, topic.id));+ expect(row.status).toBe('scheduled');+ expect(row.metadata?.scheduledRun).toEqual(run);+ } finally {+ await serverDB.execute(sql`ALTER TABLE topics DROP CONSTRAINT test_cancel_failure`);+ }+ });++ it('allows only one of a concurrent cancellation and dispatcher claim', async () => {+ const topic = await topicModel.create({ title: 'source' });+ await topicModel.armScheduledRun(topic.id, run);+ const [cancelled, claimed] = await Promise.all([+ topicModel.cancelRateLimitContinuation(topic.id),+ TopicModel.claimScheduledTopic(serverDB, topic.id, claim, new Date(run.createdAt)),+ ]);+ expect(Number(cancelled.status === 'cancelled') + Number(claimed)).toBe(1);+ });++ it('also cancels the legacy rate-limit payload the dispatcher can run', async () => {+ const topic = await topicModel.create({ title: 'legacy' });+ const { kind: _kind, runAt: _runAt, ...legacy } = run;+ await serverDB+ .update(topics)+ .set({+ status: 'scheduled',+ metadata: sql`${JSON.stringify({ scheduledRun: { ...legacy, reason: 'rate_limit' } })}::jsonb`,+ })+ .where(eq(topics.id, topic.id));+ expect((await topicModel.cancelRateLimitContinuation(topic.id)).status).toBe('cancelled');+ });++ it('does not cancel another user or a delayed-start schedule', async () => {+ const topic = await topicModel.create({ title: 'source' });+ await topicModel.armScheduledRun(topic.id, run);+ expect(+ await new TopicModel(serverDB, otherUserId).cancelRateLimitContinuation(topic.id),+ ).toEqual({ status: 'unchanged' });+ await topicModel.armScheduledRun(topic.id, {+ createdAt: run.createdAt,+ kind: 'delayed_start',+ runAt: run.runAt,+ updatedAt: run.updatedAt,+ userMessageId: run.userMessageId,+ });+ expect(await topicModel.cancelRateLimitContinuation(topic.id)).toEqual({+ status: 'unchanged',+ });+ });+ });+describe('create', () => {it('creates a topic owned by the calling user with null owner columns by default', async () => {const topic = await topicModel.create({ title: 'Hello' });diff --git a/packages/database/src/models/topic.ts b/packages/database/src/models/topic.tsindex 74fe0047a78..d2a12c9668b 100644--- a/packages/database/src/models/topic.ts+++ b/packages/database/src/models/topic.ts@@ -7,6 +7,7 @@ import type {TopicRankItem,TopicScheduledRun,} from '@lobechat/types';+import { parseTopicScheduledRun } from '@lobechat/types';import type { TimingSink } from '@lobechat/utils';import {getDurationMs,@@ -2469,6 +2470,31 @@ export class TopicModel {return 'released';});+ /** Atomically cancel an unclaimed rate-limit run, serialized with the dispatcher. */+ cancelRateLimitContinuation = async (id: string) =>+ this.db.transaction(async (tx) => {+ const [row] = await tx+ .select({ metadata: topics.metadata, status: topics.status })+ .from(topics)+ .where(and(eq(topics.id, id), this.ownership()))+ .for('update');+ if (!row) return { status: 'unchanged' as const };+ if (row.status === 'running') return { status: 'busy' as const };+ const scheduledRun = parseTopicScheduledRun(row.metadata?.scheduledRun);+ if (row.status !== 'scheduled' || scheduledRun?.kind !== 'resume_after_rate_limit')+ return { status: 'unchanged' as const };+ // A lease expiring does not stop its dispatcher. Once claimed, a handoff+ // must not race that worker, even if its five-minute lease has elapsed.+ if (scheduledRun.claim) return { status: 'busy' as const };++ const metadata = { ...row.metadata, scheduledRun: null };+ await tx+ .update(topics)+ .set({ metadata, status: 'failed' })+ .where(and(eq(topics.id, id), this.ownership()));+ return { metadata, status: 'cancelled' as const };+ });+/*** Arm a scheduled run on an owned topic: writes `metadata.scheduledRun` and* flips the status to `scheduled` in a single update.diff --git a/packages/locales/src/default/chat.ts b/packages/locales/src/default/chat.tsindex e88184ce7a7..b45dec76576 100644--- a/packages/locales/src/default/chat.ts+++ b/packages/locales/src/default/chat.ts@@ -781,6 +781,8 @@ export default {'messageAction.regenerate': 'Regenerate','messageAction.select': 'Select','messageLink.openInSideBrowser': 'Open in side browser',+ 'heteroRateLimit.cancelFailed':+ 'Could not cancel the scheduled continuation. It may already be claimed or running. Refresh the conversation to check its status.','messageForward.bar.cancel': 'Cancel','messageForward.bar.delete': 'Delete','messageForward.bar.forward': 'Forward',@@ -808,9 +810,13 @@ export default {'messageForward.successMulti': 'Forwarded to {{count}} agents','messageForward.transcript.header':'The following {{count}} messages were forwarded from another conversation. Please use them as context and continue:',+ 'messageForward.topic.handoffFailed':+ 'Transfer did not start because the source continuation could not be cancelled. It may already be running. Refresh the conversation and check its status.',+ 'messageForward.topic.sourceSchedulePaused':+ 'Transfer could not be confirmed. The original scheduled continuation is paused. Check the target conversation before retrying or scheduling again.','messageForward.topic.context': 'Topic context','messageForward.topic.description':- 'The user and assistant messages in this topic will be sent as context. Tool messages are excluded.',+ "The selected Agent will receive this topic's context and continue the work.",'messageForward.topic.header':'The following topic was forwarded from another conversation. Please use it as context and continue:','messageForward.topic.loadFailed': 'Could not load this topic for forwarding',@@ -941,6 +947,7 @@ export default {'cliOverloadedGuide.title': '{{name}} is temporarily overloaded','cliRateLimitGuide.actions.openSystemTools': 'Open System Tools','cliRateLimitGuide.actions.retry': 'Retry message',+ 'cliRateLimitGuide.actions.transfer': 'Transfer to another Agent','cliRateLimitGuide.afterReset':'This account has reached its current usage limit. You can continue after {{resetAt}}.','cliRateLimitGuide.afterResetWithLimitType':diff --git a/src/features/Conversation/Error/index.test.tsx b/src/features/Conversation/Error/index.test.tsxindex 1ae5abdd48d..b4560b9d36b 100644--- a/src/features/Conversation/Error/index.test.tsx+++ b/src/features/Conversation/Error/index.test.tsx@@ -8,6 +8,8 @@ import { fireEvent, render, screen, waitFor } from '@testing-library/react';import type { ReactNode } from 'react';import { beforeEach, describe, expect, it, vi } from 'vitest';+import { useChatStore } from '@/store/chat';+import ErrorMessageExtra, { useErrorContent } from './index';const navigateMock = vi.fn();@@ -18,10 +20,19 @@ const serverConfigMock = vi.hoisted(() => ({ enableBusinessFeatures: false }));const shareContextMock = vi.hoisted(() => ({ topicShareId: '' }));const delAndRegenerateMessageMock = vi.hoisted(() => vi.fn());const detectHeterogeneousAgentCommandMock = vi.hoisted(() => vi.fn());+const cancelHeteroContinuationMock = vi.hoisted(() => vi.fn());// Keyed by message id so a test can decide whether `data.id` is a top-level// displayMessage hanging off a user turn — the condition that decides whether a// self-contained retry can actually do anything.const displayMessageMock = vi.hoisted(() => new Map<string, { parentId?: string }>());+const conversationContextMock = vi.hoisted(+ () =>+ ({ agentId: undefined, topicId: undefined }) as {+ agentId?: string;+ topicId?: string;+ },+);+const createTopicForwardModalMock = vi.hoisted(() => vi.fn());// Stands in for whatever card a downstream build installs into the business slot.const businessSlot = vi.hoisted(() => ({ render: false }));const missingTranslationKeys = vi.hoisted(() => new Set<string>());@@ -111,16 +122,19 @@ vi.mock('@/features/Electron/HeterogeneousAgent/StatusGuide', () => ({error,onDismiss,onRetry,+ onTransfer,}: {agentType?: string;error?: { code?: string };onDismiss?: () => void;onRetry?: () => void;+ onTransfer?: () => void;}) => (<div>{`guide:${agentType}:${error?.code}`}{onDismiss && <button onClick={onDismiss}>dismiss</button>}{onRetry && <button onClick={onRetry}>guide-retry</button>}+ {onTransfer && <button onClick={onTransfer}>transfer</button>}</div>),}));@@ -131,6 +145,10 @@ vi.mock('@/services/electron/binary', () => ({},}));+vi.mock('@/features/Conversation/MessageForward/TopicForwardModal', () => ({+ createTopicForwardModal: createTopicForwardModalMock,+}));+vi.mock('@/hooks/useProviderName', () => ({useProviderName: () => 'Mock Provider',}));@@ -156,12 +174,17 @@ vi.mock('@/store/serverConfig', () => ({}));vi.mock('@/features/Conversation/store', () => ({+ contextSelectors: {+ agentId: (state: { context: typeof conversationContextMock }) => state.context.agentId,+ topicId: (state: { context: typeof conversationContextMock }) => state.context.topicId,+ },dataSelectors: {getDisplayMessageById: (id: string) => () => displayMessageMock.get(id),},useConversationStore: (selector: (state: unknown) => unknown) =>selector({- context: shareContextMock,+ context: { ...conversationContextMock, ...shareContextMock },+ cancelHeteroContinuation: cancelHeteroContinuationMock,delAndRegenerateMessage: delAndRegenerateMessageMock,deleteMessage: vi.fn(),heteroOverloadRetryAttempts: {},@@ -197,7 +220,12 @@ describe('ErrorMessageExtra', () => {});updateMessageErrorMock.mockClear();delAndRegenerateMessageMock.mockClear();+ cancelHeteroContinuationMock.mockClear();displayMessageMock.clear();+ conversationContextMock.agentId = undefined;+ conversationContextMock.topicId = undefined;+ createTopicForwardModalMock.mockClear();+ useChatStore.setState({ activeTopicId: null as any, topicDetailMap: {} });});// Regression: the standalone surfaces (Assistant / Task / AgentCouncil) render@@ -543,6 +571,8 @@ describe('ErrorMessageExtra', () => {});it('renders the rate-limit guide when the refreshed error carries rate_limit code', () => {+ conversationContextMock.agentId = 'source-agent';+ conversationContextMock.topicId = 'source-topic';render(<ErrorMessageExtraerror={{ message: 'response.undefined' }}@@ -561,6 +591,58 @@ describe('ErrorMessageExtra', () => {);expect(screen.getByText('guide:claude-code:rate_limit')).toBeInTheDocument();+ fireEvent.click(screen.getByText('transfer'));+ expect(createTopicForwardModalMock).toHaveBeenCalledWith({+ cancelSourceContinuation: true,+ sourceAgentId: 'source-agent',+ topicId: 'source-topic',+ topicTitle: '',+ });+ });++ it('requests cancellation of the conversation source even when another topic is active', () => {+ useChatStore.setState({+ activeTopicId: 'main-topic',+ topicDetailMap: {+ 'main-topic': {+ id: 'main-topic',+ status: 'active',+ title: 'Main topic',+ } as any,+ 'source-topic': {+ id: 'source-topic',+ metadata: { scheduledRun: { kind: 'resume_after_rate_limit' } },+ status: 'scheduled',+ title: 'Review task',+ } as any,+ },+ });+ conversationContextMock.agentId = 'source-agent';+ conversationContextMock.topicId = 'source-topic';++ render(+ <ErrorMessageExtra+ error={{ message: 'response.undefined' }}+ data={{+ error: {+ body: {+ agentType: 'codex',+ code: HeterogeneousAgentSessionErrorCode.RateLimit,+ message: 'rate limited',+ },+ message: 'rate limited',+ } as any,+ id: 'msg-rate-limit',+ }}+ />,+ );++ fireEvent.click(screen.getByText('transfer'));+ expect(cancelHeteroContinuationMock).not.toHaveBeenCalled();++ const props = createTopicForwardModalMock.mock.calls[0][0];+ expect(props.cancelSourceContinuation).toBe(true);+ expect(props.topicId).toBe('source-topic');});it('renders the working-directory guide instead of the CLI install guide', () => {diff --git a/src/features/Conversation/Error/index.tsx b/src/features/Conversation/Error/index.tsxindex 8dd235e606b..9b0a79e9834 100644--- a/src/features/Conversation/Error/index.tsx+++ b/src/features/Conversation/Error/index.tsx@@ -7,7 +7,7 @@ import { type ChatMessageError, type ErrorType, type IToolErrorType } from '@lobimport { ChatErrorType } from '@lobechat/types';import { isRecord } from '@lobechat/utils/object';import { Block, Highlighter } from '@lobehub/ui';-import { type AlertProps, Skeleton } from '@lobehub/ui/base-ui';+import { type AlertProps, Skeleton, toast } from '@lobehub/ui/base-ui';import { memo, useCallback, useMemo } from 'react';import { useTranslation } from 'react-i18next';@@ -16,7 +16,12 @@ import useBusinessErrorContent from '@/business/client/hooks/useBusinessErrorConimport useRenderBusinessChatErrorMessageExtra from '@/business/client/hooks/useRenderBusinessChatErrorMessageExtra';import ErrorContent from '@/features/Conversation/ChatItem/components/ErrorContent';import { useConversationResourceAccess } from '@/features/Conversation/hooks/useConversationResourceAccess';-import { dataSelectors, useConversationStore } from '@/features/Conversation/store';+import { createTopicForwardModal } from '@/features/Conversation/MessageForward/TopicForwardModal';+import {+ contextSelectors,+ 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';@@ -275,6 +280,7 @@ interface ErrorExtraProps {const ErrorMessageExtra = memo<ErrorExtraProps>(({ error: alertError, data, onRegenerate, retryScopeId }) => {const error = data.error;+ const { t } = useTranslation('chat');const navigate = useWorkspaceAwareNavigate();const enableBusinessFeatures = useServerConfigStore(serverConfigSelectors.enableBusinessFeatures,@@ -284,6 +290,8 @@ const ErrorMessageExtra = memo<ErrorExtraProps>(// access on top of the workspace-role capability.const { canUseResource } = useConversationResourceAccess();const canCreate = canCreateContent && canUseResource;+ const conversationAgentId = useConversationStore(contextSelectors.agentId);+ const conversationTopicId = useConversationStore(contextSelectors.topicId);const isSharedTopic = useConversationStore((s) => !!s.context?.topicShareId);const sessionErrorBody = error?.body;const rawErrorMessage = getRawErrorMessage(error);@@ -385,16 +393,16 @@ const ErrorMessageExtra = memo<ErrorExtraProps>(// 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 activeAgentId = useChatStore((s) => s.activeAgentId);- const scheduledResetsAt = useChatStore((s) => {- const scheduledRun = topicSelectors.currentActiveTopic(s)?.metadata?.scheduledRun;- return scheduledRun?.kind === 'resume_after_rate_limit'+ const conversationTopic = useChatStore((s) =>+ conversationTopicId ? topicSelectors.getTopicById(conversationTopicId)(s) : undefined,+ );+ const conversationTopicScheduled = conversationTopic?.status === 'scheduled';+ const scheduledRun = conversationTopic?.metadata?.scheduledRun;+ const scheduledResetsAt =+ scheduledRun?.kind === 'resume_after_rate_limit'? scheduledRun.rateLimit?.resetsAt: undefined;- });const isRateLimitError =canCreate &&@@ -406,8 +414,12 @@ const ErrorMessageExtra = memo<ErrorExtraProps>(const schedule: HeterogeneousAgentScheduleState | undefined = isRateLimitError? {- isScheduled: activeTopicScheduled,- onCancel: () => void cancelHeteroContinuation(),+ isScheduled: conversationTopicScheduled,+ onCancel: () =>+ void cancelHeteroContinuation(conversationTopicId).catch((error) => {+ console.error('[ErrorMessageExtra] Failed to cancel scheduled continuation:', error);+ toast.error(t('heteroRateLimit.cancelFailed'));+ }),// Same fallback as the retry button: `onRegenerate` is absent on the// standalone surfaces, where a bare `onRegenerate?.()` was a no-op.onRunNow: handleManualRetry,@@ -441,6 +453,17 @@ const ErrorMessageExtra = memo<ErrorExtraProps>(: '/settings/credential',)}+ onTransfer={+ isRateLimitError && conversationAgentId && conversationTopicId+ ? () =>+ createTopicForwardModal({+ cancelSourceContinuation: true,+ sourceAgentId: conversationAgentId,+ topicId: conversationTopicId,+ topicTitle: conversationTopic?.title || '',+ })+ : undefined+ }/>);}diff --git a/src/features/Conversation/MessageForward/TopicForwardModal/Content.tsx b/src/features/Conversation/MessageForward/TopicForwardModal/Content.tsxindex 5fc6ef49122..bc1d7627454 100644--- a/src/features/Conversation/MessageForward/TopicForwardModal/Content.tsx+++ b/src/features/Conversation/MessageForward/TopicForwardModal/Content.tsx@@ -55,12 +55,14 @@ const styles = createStaticStyles(({ css }) => ({}));export interface TopicForwardContentProps {+ cancelSourceContinuation?: boolean;sourceAgentId: string;topicId: string;topicTitle: string;}export const TopicForwardContent = ({+ cancelSourceContinuation,sourceAgentId,topicId,topicTitle,@@ -71,7 +73,11 @@ export const TopicForwardContent = ({const [note, setNote] = useState('');const [selectedIds, setSelectedIds] = useState<string[]>([]);const agents = useHomeStore(homeAgentListSelectors.allAgents);- const forwardTopic = useForwardTopic({ agentId: sourceAgentId, topicId });+ const forwardTopic = useForwardTopic({+ agentId: sourceAgentId,+ cancelSourceContinuation,+ topicId,+ });useFetchAgentList();diff --git a/src/features/Conversation/MessageForward/useForwardTopic.test.ts b/src/features/Conversation/MessageForward/useForwardTopic.test.tsnew file mode 100644index 00000000000..2156f8ef7d4--- /dev/null+++ b/src/features/Conversation/MessageForward/useForwardTopic.test.ts@@ -0,0 +1,71 @@+import { act, renderHook } from '@testing-library/react';+import { beforeEach, describe, expect, it, vi } from 'vitest';++import type { ForwardTopicParams } from '@/store/chat/slices/forward/action';++import { useForwardTopic } from './useForwardTopic';++const mocks = vi.hoisted(() => ({+ clearPortalStack: vi.fn(),+ forwardTopic: vi.fn(),+ navigate: vi.fn(),+ error: vi.fn(),+ success: vi.fn(),+}));+vi.mock('@/store/chat', () => ({+ useChatStore: (selector: (state: typeof mocks) => unknown) => selector(mocks),+}));+vi.mock('@/features/Workspace/useWorkspaceAwareNavigate', () => ({+ useWorkspaceAwareNavigate: () => mocks.navigate,+}));+vi.mock('react-i18next', () => ({ useTranslation: () => ({ t: (key: string) => key }) }));+vi.mock('@lobehub/ui/base-ui', () => ({ toast: { error: mocks.error, success: mocks.success } }));++describe('topic handoff acceptance', () => {+ beforeEach(() => vi.clearAllMocks());++ it('navigates only to the primary target while target runs are pending', async () => {+ let params!: ForwardTopicParams;+ let finish!: () => void;+ mocks.forwardTopic.mockImplementation((input: ForwardTopicParams) => {+ params = input;+ return new Promise((resolve) => {+ finish = () => resolve({ succeeded: [{ agentId: 'b' }, { agentId: 'c' }], failed: [] });+ });+ });+ const { result } = renderHook(() => useForwardTopic({ agentId: 'a', topicId: 'source' }));+ act(() => result.current([{ id: 'b' }, { id: 'c' }]));+ expect(mocks.navigate).not.toHaveBeenCalled();+ await act(async () => {+ await params.onTopicCreated?.({ id: 'c' }, 'topic-c');+ });+ expect(mocks.navigate).not.toHaveBeenCalled();+ await act(async () => {+ await params.onTopicCreated?.({ id: 'b' }, 'topic-b');+ });+ expect(mocks.navigate).toHaveBeenCalledTimes(1);+ await act(async () => finish());+ expect(mocks.navigate).toHaveBeenCalledTimes(1);+ });++ it('explains that the source schedule stays paused after an ambiguous send', async () => {+ mocks.forwardTopic.mockResolvedValue({+ succeeded: [],+ failed: [{ agentId: 'b' }],+ sourceSchedulePaused: true,+ });+ const { result } = renderHook(() =>+ useForwardTopic({ agentId: 'a', topicId: 'source', cancelSourceContinuation: true }),+ );+ await act(async () => result.current([{ id: 'b' }]));+ expect(mocks.error).toHaveBeenCalledWith('messageForward.topic.sourceSchedulePaused');+ });++ it('does not navigate when every target fails before persistence', async () => {+ mocks.forwardTopic.mockResolvedValue({ succeeded: [], failed: [{ agentId: 'b' }] });+ const { result } = renderHook(() => useForwardTopic({ agentId: 'a', topicId: 'source' }));+ await act(async () => result.current([{ id: 'b' }]));+ expect(mocks.navigate).not.toHaveBeenCalled();+ expect(mocks.error).toHaveBeenCalled();+ });+});diff --git a/src/features/Conversation/MessageForward/useForwardTopic.ts b/src/features/Conversation/MessageForward/useForwardTopic.tsindex 3c2bca64f5d..f490d2a71e9 100644--- a/src/features/Conversation/MessageForward/useForwardTopic.ts+++ b/src/features/Conversation/MessageForward/useForwardTopic.ts@@ -9,10 +9,15 @@ import type { ForwardTarget } from '@/store/chat/slices/forward/action';interface ForwardTopicSource {agentId: string;+ cancelSourceContinuation?: boolean;topicId: string;}-export const useForwardTopic = ({ agentId, topicId }: ForwardTopicSource) => {+export const useForwardTopic = ({+ agentId,+ cancelSourceContinuation,+ topicId,+}: ForwardTopicSource) => {const { t } = useTranslation('chat');const navigate = useWorkspaceAwareNavigate();@@ -25,6 +30,7 @@ export const useForwardTopic = ({ agentId, topicId }: ForwardTopicSource) => {const primaryTarget = targets[0];void forwardTopic({+ cancelSourceContinuation,header: t('messageForward.topic.header'),note,onTopicCreated: (target, createdTopicId) => {@@ -46,10 +52,26 @@ export const useForwardTopic = ({ agentId, topicId }: ForwardTopicSource) => {: t('messageForward.successMulti', { count: result.succeeded.length }),);}- if (result.failed.length > 0) toast.error(t('messageForward.failed'));+ if (result.failed.length > 0)+ toast.error(+ t(+ result.sourceSchedulePaused+ ? 'messageForward.topic.sourceSchedulePaused'+ : 'messageForward.failed',+ ),+ );})- .catch(() => toast.error(t('messageForward.topic.loadFailed')));+ .catch((error) => {+ console.error('[useForwardTopic] Forwarding failed:', error);+ toast.error(+ t(+ cancelSourceContinuation+ ? 'messageForward.topic.handoffFailed'+ : 'messageForward.topic.loadFailed',+ ),+ );+ });},- [agentId, clearPortalStack, forwardTopic, navigate, t, topicId],+ [agentId, cancelSourceContinuation, clearPortalStack, forwardTopic, navigate, t, topicId],);};diff --git a/src/features/Conversation/Messages/AssistantGroup/components/ContentBlock.test.tsx b/src/features/Conversation/Messages/AssistantGroup/components/ContentBlock.test.tsxindex 3a91108b8ae..dda25e76d24 100644--- a/src/features/Conversation/Messages/AssistantGroup/components/ContentBlock.test.tsx+++ b/src/features/Conversation/Messages/AssistantGroup/components/ContentBlock.test.tsx@@ -108,6 +108,10 @@ vi.mock('./MessageContent', () => ({}));vi.mock('../../../store', () => ({+ contextSelectors: {+ agentId: () => undefined,+ topicId: () => undefined,+ },dataSelectors: {getDisplayMessageById: () => () => ({ parentId: 'user-1' }),},diff --git a/src/features/Conversation/store/slices/generation/action.test.ts b/src/features/Conversation/store/slices/generation/action.test.tsindex a6ac15c2287..a81b82d44ac 100644--- a/src/features/Conversation/store/slices/generation/action.test.ts+++ b/src/features/Conversation/store/slices/generation/action.test.ts@@ -3,6 +3,7 @@ import { act } from '@testing-library/react';import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { messageService } from '@/services/message';+import { topicService } from '@/services/topic';import { agentSelectors } from '@/store/agent/selectors';import * as agentDispatcher from '@/store/chat/slices/agentRun/actions/dispatch/agentDispatcher';import * as heterogeneousAgentExecutor from '@/store/chat/slices/agentRun/actions/transports/hetero/heterogeneousAgentExecutor';@@ -13,6 +14,8 @@ import { type ConversationContext, type ConversationHooks } from '../../../typesimport { createStore } from '../../index';import { MAX_HETERO_AUTO_RETRIES } from './heteroRetryConfig';+vi.mock('@/services/topic', () => ({ topicService: { cancelRateLimitContinuation: vi.fn() } }));+// Mock useChatStoreconst mockCancelOperations = vi.fn();const mockCancelOperation = vi.fn();@@ -29,6 +32,12 @@ const mockFailOperation = vi.fn();const mockExecuteClientAgent = vi.fn();const mockIsGatewayModeEnabled = vi.fn(() => false);const mockExecuteGatewayAgent = vi.fn();+const mockUpdateTopicMetadata = vi.fn();+const mockUpdateTopicStatus = vi.fn();+const mockSourceTopic = {+ status: 'scheduled',+ metadata: { scheduledRun: { kind: 'resume_after_rate_limit' } },+};vi.mock('@/store/chat', () => ({useChatStore: {@@ -39,6 +48,8 @@ vi.mock('@/store/chat', () => ({{ id: 'msg-2', role: 'assistant', content: 'Hi there', parentId: 'msg-1' },],},+ topicDataMap: {},+ topicDetailMap: { 'source-topic': mockSourceTopic },operations: {},operationsByMessage: {},@@ -57,6 +68,9 @@ vi.mock('@/store/chat', () => ({executeClientAgent: mockExecuteClientAgent,isGatewayModeEnabled: mockIsGatewayModeEnabled,executeGatewayAgent: mockExecuteGatewayAgent,+ internal_dispatchTopic: vi.fn(),+ updateTopicMetadata: mockUpdateTopicMetadata,+ updateTopicStatus: mockUpdateTopicStatus,})),setState: vi.fn(),},@@ -65,12 +79,48 @@ vi.mock('@/store/chat', () => ({describe('Generation Actions', () => {beforeEach(() => {vi.clearAllMocks();+ mockSourceTopic.status = 'scheduled';});afterEach(() => {vi.clearAllTimers();});+ describe('cancelHeteroContinuation', () => {+ it('does not overwrite a source topic that has already started running', async () => {+ mockSourceTopic.status = 'running';+ const store = createStore({+ context: { agentId: 'target-agent', topicId: 'target-topic', threadId: null },+ });+ await store.getState().cancelHeteroContinuation('source-topic');+ expect(mockUpdateTopicStatus).not.toHaveBeenCalled();+ expect(mockUpdateTopicMetadata).not.toHaveBeenCalled();+ });++ it('propagates cancellation failure instead of clearing metadata separately', async () => {+ vi.mocked(topicService.cancelRateLimitContinuation).mockRejectedValueOnce(+ new Error('database failed'),+ );+ const store = createStore({+ context: { agentId: 'agent', topicId: 'source-topic', threadId: null },+ });+ await expect(store.getState().cancelHeteroContinuation()).rejects.toThrow('database failed');+ expect(mockUpdateTopicMetadata).not.toHaveBeenCalled();+ });++ it('cancels the captured source topic after navigation changes the conversation context', async () => {+ const store = createStore({+ context: { agentId: 'target-agent', threadId: null, topicId: 'target-topic' },+ });++ await store.getState().cancelHeteroContinuation('source-topic');++ expect(topicService.cancelRateLimitContinuation).toHaveBeenCalledWith('source-topic');+ expect(mockUpdateTopicStatus).not.toHaveBeenCalled();+ expect(mockUpdateTopicMetadata).not.toHaveBeenCalled();+ });+ });+describe('stopGenerating', () => {it('should cancel all running execAgentRuntime operations', () => {const context: ConversationContext = {diff --git a/src/features/Conversation/store/slices/generation/action.ts b/src/features/Conversation/store/slices/generation/action.tsindex a2754d15f19..dddee59d19a 100644--- a/src/features/Conversation/store/slices/generation/action.ts+++ b/src/features/Conversation/store/slices/generation/action.ts@@ -23,6 +23,7 @@ import { resolveAgentWorkingDirectory } from '@/helpers/agentWorkingDirectory';import { resolveWorkspaceScoped } from '@/helpers/executionTarget';import { globalAgentContextManager } from '@/helpers/GlobalAgentContextManager';import { messageService } from '@/services/message';+import { topicService } from '@/services/topic';import { getAgentStoreState } from '@/store/agent';import { agentByIdSelectors, agentSelectors } from '@/store/agent/selectors';import { useChatStore } from '@/store/chat';@@ -507,7 +508,7 @@ const regenerateUserMessageFromSource = async (* Handles generation control (stop, cancel, regenerate, continue)*/export interface GenerationAction {- cancelHeteroContinuation: () => Promise<void>;+ cancelHeteroContinuation: (topicId?: string | null) => Promise<void>;/*** Cancel a specific operation*/@@ -669,13 +670,17 @@ export const generationSlice: StateCreator<[],GenerationAction> = (set, get) => ({- cancelHeteroContinuation: async () => {- const topicId = get().context.topicId;+ cancelHeteroContinuation: async (sourceTopicId) => {+ const topicId = sourceTopicId ?? get().context.topicId;if (!topicId) return;- const chatStore = useChatStore.getState();- await chatStore.updateTopicStatus({ status: 'failed', topicId });- await chatStore.updateTopicMetadata(topicId, { scheduledRun: null });+ const result = await topicService.cancelRateLimitContinuation(topicId);+ if (result)+ useChatStore.getState().internal_dispatchTopic({+ id: topicId,+ type: 'updateTopic',+ value: { metadata: result.metadata, status: 'failed' },+ });},cancelScheduledRun: async () => {const { context, dbMessages, editor } = get();diff --git a/src/features/Electron/HeterogeneousAgent/StatusGuide/index.tsx b/src/features/Electron/HeterogeneousAgent/StatusGuide/index.tsxindex 7b50912294f..a72c12b01ef 100644--- a/src/features/Electron/HeterogeneousAgent/StatusGuide/index.tsx+++ b/src/features/Electron/HeterogeneousAgent/StatusGuide/index.tsx@@ -20,6 +20,7 @@ const HeterogeneousAgentStatusGuide = memo<HeterogeneousAgentStatusGuideProps>(onDismiss,onOpenSystemTools,onRetry,+ onTransfer,schedule,variant = 'inline',}) => {@@ -34,6 +35,7 @@ const HeterogeneousAgentStatusGuide = memo<HeterogeneousAgentStatusGuideProps>(onDismiss,onOpenSystemTools,onRetry,+ onTransfer,schedule,variant,};diff --git a/src/features/Electron/HeterogeneousAgent/StatusGuide/states/RateLimitState.tsx b/src/features/Electron/HeterogeneousAgent/StatusGuide/states/RateLimitState.tsxindex 2cfee370ecf..269d1c508b9 100644--- a/src/features/Electron/HeterogeneousAgent/StatusGuide/states/RateLimitState.tsx+++ b/src/features/Electron/HeterogeneousAgent/StatusGuide/states/RateLimitState.tsx@@ -1,7 +1,7 @@import { readHeterogeneousErrorContext } from '@lobechat/heterogeneous-agents/errors';import { Flexbox } from '@lobehub/ui';import { Button, Text } from '@lobehub/ui/base-ui';-import { CalendarClock, Play, RotateCcw } from 'lucide-react';+import { CalendarClock, Forward, Play, RotateCcw } from 'lucide-react';import { useMemo } from 'react';import { useTranslation } from 'react-i18next';@@ -22,6 +22,7 @@ const RateLimitState = ({onDismiss,onOpenSystemTools,onRetry,+ onTransfer,schedule,variant,}: HeterogeneousAgentGuideStateProps) => {@@ -108,9 +109,14 @@ const RateLimitState = ({<Button size="small" onClick={schedule.onCancel}>{t('cliRateLimitGuide.schedule.cancel')}</Button>- <Button icon={<Play size={14} />} size="small" type="primary" onClick={schedule.onRunNow}>+ <Button icon={<Play size={14} />} size="small" onClick={schedule.onRunNow}>{t('cliRateLimitGuide.schedule.runNow')}</Button>+ {onTransfer && (+ <Button icon={<Forward size={14} />} size="small" type="primary" onClick={onTransfer}>+ {t('cliRateLimitGuide.actions.transfer')}+ </Button>+ )}</Flexbox>);}@@ -118,23 +124,23 @@ const RateLimitState = ({return (<Flexbox horizontal gap={8} justify="flex-end" style={{ flexWrap: 'wrap' }}>{onRetry && (- <Button icon={<RotateCcw size={14} />} size="small" onClick={onRetry}>+ <Button icon={<RotateCcw size={14} />} size="small" type="text" onClick={onRetry}>{t('cliRateLimitGuide.schedule.retryNow')}</Button>)}- <Button- icon={<CalendarClock size={14} />}- size="small"- type="primary"- onClick={schedule.onSchedule}- >+ <Button icon={<CalendarClock size={14} />} size="small" onClick={schedule.onSchedule}>{relativeDuration? t('cliRateLimitGuide.schedule.continueAfter', { duration: relativeDuration }): t('cliRateLimitGuide.schedule.continueAfterReset')}</Button>+ {onTransfer && (+ <Button icon={<Forward size={14} />} size="small" type="primary" onClick={onTransfer}>+ {t('cliRateLimitGuide.actions.transfer')}+ </Button>+ )}</Flexbox>);- }, [onRetry, relativeDuration, schedule, t]);+ }, [onRetry, onTransfer, relativeDuration, schedule, t]);const isScheduled = Boolean(schedule?.isScheduled);const title = isScheduleddiff --git a/src/features/Electron/HeterogeneousAgent/StatusGuide/types.ts b/src/features/Electron/HeterogeneousAgent/StatusGuide/types.tsindex 4a28834c0ff..78cef736552 100644--- a/src/features/Electron/HeterogeneousAgent/StatusGuide/types.ts+++ b/src/features/Electron/HeterogeneousAgent/StatusGuide/types.ts@@ -39,6 +39,7 @@ export interface HeterogeneousAgentStatusGuideProps {onDismiss?: () => void;onOpenSystemTools?: () => void;onRetry?: () => void;+ onTransfer?: () => void;schedule?: HeterogeneousAgentScheduleState;variant?: HeterogeneousAgentStatusGuideVariant;}@@ -63,6 +64,7 @@ export interface HeterogeneousAgentGuideStateProps {onDismiss?: () => void;onOpenSystemTools?: () => void;onRetry?: () => void;+ onTransfer?: () => void;schedule?: HeterogeneousAgentScheduleState;variant: HeterogeneousAgentStatusGuideVariant;}diff --git a/src/services/topic/index.ts b/src/services/topic/index.tsindex c78f63f5c10..60f3f3ec427 100644--- a/src/services/topic/index.ts+++ b/src/services/topic/index.ts@@ -47,6 +47,9 @@ type UpdateTopicMetadataInput = Omit<Partial<ChatTopicMetadata>, 'onboardingSess};export class TopicService {+ cancelRateLimitContinuation = (id: string) =>+ lambdaClient.topic.cancelRateLimitContinuation.mutate({ id });+createTopic = (params: CreateTopicParams): Promise<string> => {return lambdaClient.topic.createTopic.mutate({...params,diff --git a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.tsindex 47ae76d4cff..7abad999068 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/conversationLifecycle.test.ts@@ -1591,6 +1591,38 @@ describe('ConversationLifecycle actions', () => {);});+ it('reports an isolated gateway topic at acceptance and returns its ID', async () => {+ const onTopicCreated = vi.fn();+ const executeGatewayAgent = vi.fn().mockImplementation(async (params) => {+ await params.onTopicCreated?.(TEST_IDS.NEW_TOPIC_ID);+ expect(onTopicCreated).toHaveBeenCalledWith(TEST_IDS.NEW_TOPIC_ID);+ useChatStore.getState().completeOperation(params.parentOperationId);+ return {+ assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,+ topicId: TEST_IDS.NEW_TOPIC_ID,+ userMessageId: TEST_IDS.USER_MESSAGE_ID,+ };+ });+ useChatStore.setState({+ executeGatewayAgent,+ isGatewayModeEnabled: () => true,+ });++ const result = await useChatStore.getState().sendMessage({+ context: {+ agentId: TEST_IDS.SESSION_ID,+ isNew: true,+ isolatedTopic: true,+ scope: 'main',+ },+ message: 'Continue the forwarded work',+ onTopicCreated,+ });++ expect(onTopicCreated).toHaveBeenCalledTimes(1);+ expect(result?.createdTopicId).toBe(TEST_IDS.NEW_TOPIC_ID);+ });+it('should stop the sidebar spinner after a gateway send creates the topic', async () => {const { result } = renderHook(() => useChatStore());const agentId = TEST_IDS.SESSION_ID;@@ -1842,6 +1874,114 @@ describe('ConversationLifecycle actions', () => {);});+ it('notifies an isolated hetero caller before execution and returns its created topic', async () => {+ mockConstEnv.isDesktop = true;+ setupMockSelectors({+ agentConfig: {+ agencyConfig: {+ heterogeneousProvider: { command: 'codex', type: 'codex' },+ },+ },+ });++ const { result } = renderHook(() => useChatStore());+ const agentId = TEST_IDS.SESSION_ID;+ const topicKey = topicMapKey({ agentId });+ const newTopicId = TEST_IDS.NEW_TOPIC_ID;++ act(() => {+ useChatStore.setState({+ activeAgentId: agentId,+ activeTopicId: undefined,+ summaryTopicTitle: vi.fn().mockResolvedValue(undefined),+ topicDataMap: {+ [topicKey]: {+ currentPage: 0,+ hasMore: false,+ isExpandingPageSize: false,+ isLoadingMore: false,+ items: [],+ pageSize: 20,+ total: 0,+ },+ },+ });+ });++ vi.spyOn(aiChatService, 'sendMessageInServer').mockResolvedValue({+ assistantMessageId: TEST_IDS.ASSISTANT_MESSAGE_ID,+ isCreateNewTopic: true,+ messages: [+ createMockMessage({+ id: TEST_IDS.USER_MESSAGE_ID,+ role: 'user',+ topicId: newTopicId,+ }),+ createMockMessage({+ id: TEST_IDS.ASSISTANT_MESSAGE_ID,+ role: 'assistant',+ topicId: newTopicId,+ }),+ ],+ topicId: newTopicId,+ topics: { items: [{ id: newTopicId, title: 'Server Topic' }], total: 1 },+ userMessageId: TEST_IDS.USER_MESSAGE_ID,+ } as any);++ let resolveExecutor!: () => void;+ executeHeterogeneousAgentMock.mockImplementation(+ (_getStore: unknown, opts: { operationId: string }) =>+ new Promise<void>((resolve) => {+ resolveExecutor = () => {+ // The real executor settles its execHeterogeneousAgent op at+ // the terminal; without this the leaked running op would keep+ // the spinner on (and pollute later tests).+ useChatStore.getState().completeOperation(opts.operationId);+ resolve();+ };+ }),+ );++ const onTopicCreated = vi.fn();+ const switchTopic = vi.spyOn(useChatStore.getState(), 'switchTopic');+ let sendPromise!: ReturnType<typeof result.current.sendMessage>;+ act(() => {+ sendPromise = result.current.sendMessage({+ context: { agentId, isNew: true, isolatedTopic: true, scope: 'main' },+ onTopicCreated,+ message: 'hello',+ });+ });++ await waitFor(() => expect(executeHeterogeneousAgentMock).toHaveBeenCalled());++ expect(onTopicCreated).toHaveBeenCalledWith(newTopicId);+ expect(switchTopic).not.toHaveBeenCalled();++ // The executor only writes the persisted `status === 'running'` (the+ // run spinner's other driver) after startSession resolves — the running+ // execHeterogeneousAgent operation must keep the spinner on while the+ // executor starts up, or it blanks during a slow CLI startup.+ expect(operationSelectors.isTopicVisiblyRunning(newTopicId)(useChatStore.getState())).toBe(+ true,+ );++ await act(async () => {+ resolveExecutor();+ expect(await sendPromise).toEqual(+ expect.objectContaining({ createdTopicId: newTopicId }),+ );+ // Let the fire-and-forget afterUserMessagePersisted title task settle+ // inside this test instead of leaking into the next one.+ await Promise.resolve();+ await Promise.resolve();+ });++ expect(operationSelectors.isTopicVisiblyRunning(newTopicId)(useChatStore.getState())).toBe(+ false,+ );+ });+it('should keep a gateway optimistic topic in its pending repo project group', async () => {const { result } = renderHook(() => useChatStore());const agentId = TEST_IDS.SESSION_ID;diff --git a/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.tsindex 866624ec3a9..d6d06206672 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/gateway.test.ts@@ -637,6 +637,45 @@ describe('GatewayActionImpl', () => {delete (globalThis as any).window;});+ it('acknowledges an isolated topic before UI hydration without switching topics', async () => {+ const { action, switchTopic, connectToGateway } = createExecuteTestAction();+ vi.mocked(aiAgentService.execAgentTask).mockResolvedValue({+ agentId: 'target-agent',+ assistantMessageId: 'assistant-1',+ autoStarted: true,+ createdAt: new Date().toISOString(),+ message: 'ok',+ operationId: 'server-op-1',+ status: 'created',+ success: true,+ timestamp: new Date().toISOString(),+ token: 'token',+ topicId: 'target-topic',+ userMessageId: 'user-1',+ });+ const events: string[] = [];+ const onTopicCreated = vi.fn(() => {+ events.push('accepted');+ });+ vi.mocked(messageService.getMessages).mockImplementationOnce(async () => {+ events.push('hydrate');+ return [];+ });++ const result = await action.executeGatewayAgent({+ context: { agentId: 'target-agent', isolatedTopic: true, scope: 'main' },+ message: 'Continue the forwarded work',+ onTopicCreated,+ });++ expect(result.topicId).toBe('target-topic');+ expect(events).toEqual(['accepted', 'hydrate']);+ expect(onTopicCreated).toHaveBeenCalledWith('target-topic');+ expect(onTopicCreated).toHaveBeenCalledTimes(1);+ expect(switchTopic).not.toHaveBeenCalled();+ expect(connectToGateway).toHaveBeenCalled();+ });+it.each([{expectedEnabled: true,diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.tsindex 07476be4a8d..335a4aca732 100644--- a/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts+++ b/src/store/chat/slices/agentRun/actions/entries/conversationLifecycle.ts@@ -1481,10 +1481,14 @@ export class ConversationLifecycleActionImpl {resolveOptimisticTopic(heteroData.topicId, newTopicTitle);void Promise.resolve(this.#get().refreshTopic()).catch(console.error);}- await this.#get().switchTopic(heteroData.topicId, {- clearNewKey: true,- skipRefreshMessage: true,- });+ if (context.isolatedTopic) {+ await onTopicCreated?.(heteroData.topicId);+ } else {+ await this.#get().switchTopic(heteroData.topicId, {+ clearNewKey: true,+ skipRefreshMessage: true,+ });+ }}let directMentionThreadId: string | undefined;@@ -1537,6 +1541,7 @@ export class ConversationLifecycleActionImpl {if (abortController.signal.aborted) {return {assistantMessageId: heteroData.assistantMessageId,+ createdTopicId: heteroData.isCreateNewTopic ? heteroData.topicId : undefined,userMessageId: heteroData.userMessageId,};}@@ -1678,6 +1683,7 @@ export class ConversationLifecycleActionImpl {return {assistantMessageId: heteroData.assistantMessageId,+ createdTopicId: heteroData.isCreateNewTopic ? heteroData.topicId : undefined,userMessageId: heteroData.userMessageId,};}@@ -1716,6 +1722,7 @@ export class ConversationLifecycleActionImpl {? { ...requestMetadata, steer: true }: requestMetadata,onMessageAccepted: notifyMessageAccepted,+ onTopicCreated: context.isolatedTopic ? onTopicCreated : undefined,parentOperationId: operationId,replacesOperationId: replaceableGatewayOperationId,optimisticTopic,@@ -1789,6 +1796,7 @@ export class ConversationLifecycleActionImpl {return {assistantMessageId: result.assistantMessageId,createdThreadId: result.createdThreadId,+ createdTopicId: willCreateNewTopic ? result.topicId : undefined,userMessageId: result.userMessageId,};} catch (e) {diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.tsindex 7f7543fffda..829793639e0 100644--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts@@ -637,6 +637,8 @@ export class GatewayActionImpl {metadata?: Pick<MessageMetadata, 'steer' | 'trigger'>;/** Called as soon as phase-1 returns with a persisted user message. */onMessageAccepted?: () => void;+ /** Called when a new topic is persisted, before UI hydration and stream setup. */+ onTopicCreated?: (topicId: string) => void | Promise<void>;/** Called when the gateway session completes (agent finished running) */onComplete?: () => void;/** Temporary sidebar topic inserted by sendMessage before the server creates the real topic. */@@ -714,6 +716,7 @@ export class GatewayActionImpl {metadata,onComplete,onMessageAccepted,+ onTopicCreated,optimisticTopic,parentMessageId,parentOperationId,@@ -894,6 +897,14 @@ export class GatewayActionImpl {console.error('[Gateway] onMessageAccepted callback failed:', error);}+ if (isCreateNewTopic && result.topicId) {+ try {+ await onTopicCreated?.(result.topicId);+ } catch (error) {+ console.error('[Gateway] onTopicCreated callback failed:', error);+ }+ }+let hasInterruptedAfterPersistence = false;const interruptIfCancelledAfterPersistence = () => {if (!abortSignal?.aborted) return false;@@ -998,10 +1009,12 @@ export class GatewayActionImpl {/* non-critical */}- await this.#get().switchTopic(result.topicId, {- clearNewKey: true,- skipRefreshMessage: true,- });+ if (!messageContext.isolatedTopic) {+ await this.#get().switchTopic(result.topicId, {+ clearNewKey: true,+ skipRefreshMessage: true,+ });+ }// Refresh the topic list so the new topic appears in topicDataMap (sidebar).// Unlike the direct-API sendMessage path (which receives topics[] in thediff --git a/src/store/chat/slices/forward/action.test.ts b/src/store/chat/slices/forward/action.test.tsindex b46e036fd24..e3f8676bcc8 100644--- a/src/store/chat/slices/forward/action.test.ts+++ b/src/store/chat/slices/forward/action.test.ts@@ -3,6 +3,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { agentService } from '@/services/agent';import { messageService } from '@/services/message';+import { topicService } from '@/services/topic';import { useAgentStore } from '@/store/agent';import { ChatForwardActionImpl } from './action';@@ -16,12 +17,82 @@ describe('ChatForwardAction', () => {vi.spyOn(agentService, 'getAgentConfigById').mockImplementation(async (id) => ({ id }) as never,);+ vi.spyOn(messageService, 'getMessages').mockResolvedValue([]);});afterEach(() => {vi.restoreAllMocks();});+ it('does not start a target when the dispatcher already owns the source', async () => {+ vi.spyOn(topicService, 'cancelRateLimitContinuation').mockRejectedValue(new Error('claimed'));+ const sendMessage = vi.fn();+ const action = new ChatForwardActionImpl(vi.fn() as never, () => ({ sendMessage }) as never);++ await expect(+ action.forwardTopic({+ cancelSourceContinuation: true,+ header: 'Forwarded',+ roleLabel: (role) => role,+ sourceAgentId: 'source-agent',+ targets: [{ id: 'target-agent' }],+ topicId: 'source-topic',+ }),+ ).rejects.toThrow('claimed');+ expect(sendMessage).not.toHaveBeenCalled();+ });++ it.each([false, true])(+ 'keeps the source paused after an ambiguous send (%s)',+ async (accepted) => {+ const receipt = { metadata: { scheduledRun: null } };+ const cancel = vi+ .spyOn(topicService, 'cancelRateLimitContinuation')+ .mockResolvedValue(receipt);+ const sendMessage = vi.fn().mockImplementation(async ({ onTopicCreated }) => {+ expect(cancel).toHaveBeenCalledWith('source-topic');+ if (accepted) await onTopicCreated('target-topic');+ throw new Error('execution failed');+ });+ const action = new ChatForwardActionImpl(+ vi.fn() as never,+ () =>+ ({+ internal_dispatchTopic: vi.fn(),+ sendMessage,+ }) as never,+ );++ const result = await action.forwardTopic({+ cancelSourceContinuation: true,+ header: 'Forwarded',+ roleLabel: (role) => role,+ sourceAgentId: 'source-agent',+ targets: [{ id: 'target-agent' }],+ topicId: 'source-topic',+ });+ expect(result.sourceSchedulePaused).toBe(!accepted);+ },+ );++ it('leaves the source schedule alone when context preparation fails', async () => {+ vi.mocked(messageService.getMessages).mockRejectedValue(new Error('history unavailable'));+ const cancel = vi.spyOn(topicService, 'cancelRateLimitContinuation');+ const sendMessage = vi.fn();+ const action = new ChatForwardActionImpl(vi.fn() as never, () => ({ sendMessage }) as never);+ const result = await action.forwardTopic({+ cancelSourceContinuation: true,+ header: 'Forwarded',+ roleLabel: (role) => role,+ sourceAgentId: 'source',+ targets: [{ id: 'target' }],+ topicId: 'source-topic',+ });+ expect(result.failed).toHaveLength(1);+ expect(cancel).not.toHaveBeenCalled();+ expect(sendMessage).not.toHaveBeenCalled();+ });+it('forwards only user and assistant text into isolated topics', async () => {const onTopicCreated = vi.fn();const sendMessage = vi@@ -90,23 +161,75 @@ describe('ChatForwardAction', () => {expect(result.failed[0].agentId).toBe('missing-agent');});- it('loads topic messages before forwarding them', async () => {- vi.spyOn(messageService, 'getMessages').mockResolvedValue([message('user', 'from topic')]);- const sendMessage = vi.fn().mockResolvedValue({ createdTopicId: 'new-topic' });+ it('includes transcript fallback for a heterogeneous target without LobeHub CLI access', async () => {+ vi.mocked(messageService.getMessages).mockResolvedValueOnce([+ message('user', 'question'),+ message('tool', 'private tool output'),+ message('assistant', 'answer'),+ ]);+ vi.mocked(agentService.getAgentConfigById).mockResolvedValueOnce({+ agencyConfig: { heterogeneousProvider: { type: 'codex' } },+ id: 'target-agent',+ } as never);+ const onTopicCreated = vi.fn();+ const sendMessage = vi.fn().mockImplementation(async ({ onTopicCreated: notify }) => {+ notify('new-topic');+ return { createdTopicId: 'new-topic' };+ });const action = new ChatForwardActionImpl(vi.fn() as never, () => ({ sendMessage }) as never);const result = await action.forwardTopic({header: 'Forwarded topic',+ note: 'Finish the review',+ onTopicCreated,roleLabel: (role) => role,sourceAgentId: 'source-agent',targets: [{ id: 'target-agent' }],topicId: 'source-topic',});+ expect(onTopicCreated).toHaveBeenCalledWith({ id: 'target-agent' }, 'new-topic');+ expect(sendMessage.mock.calls[0][0].message).toContain('lh topic view source-topic -L 500');+ expect(sendMessage.mock.calls[0][0].message).toContain('Finish the review');+ expect(sendMessage.mock.calls[0][0].context).toEqual({+ agentId: 'target-agent',+ isNew: true,+ isolatedTopic: true,+ scope: 'main',+ });+ expect(result.succeeded).toEqual([{ agentId: 'target-agent', topicId: 'new-topic' }]);+ expect(sendMessage.mock.calls[0][0].message).toContain('question');+ expect(sendMessage.mock.calls[0][0].message).toContain('answer');+ expect(sendMessage.mock.calls[0][0].message).not.toContain('private tool output');+ });++ it('keeps transcript context when the target agent cannot use the LobeHub CLI', async () => {+ vi.mocked(messageService.getMessages).mockResolvedValueOnce([+ message('user', 'question'),+ message('assistant', 'answer'),+ ]);+ const sendMessage = vi.fn().mockImplementation(async ({ onTopicCreated: notify }) => {+ notify('new-topic');+ return { createdTopicId: 'new-topic' };+ });+ const action = new ChatForwardActionImpl(vi.fn() as never, () => ({ sendMessage }) as never);++ await action.forwardTopic({+ header: 'Forwarded topic',+ note: 'Continue carefully',+ roleLabel: (role) => role,+ sourceAgentId: 'source-agent',+ targets: [{ id: 'plain-agent' }],+ topicId: 'source-topic',+ });+expect(messageService.getMessages).toHaveBeenCalledWith({agentId: 'source-agent',topicId: 'source-topic',});- expect(result.succeeded).toEqual([{ agentId: 'target-agent', topicId: 'new-topic' }]);+ expect(sendMessage.mock.calls[0][0].message).toBe(+ 'Forwarded topic\n\n---\n\n**user**\n\nquestion\n\n---\n\n**assistant**\n\nanswer\n\nContinue carefully',+ );+ expect(sendMessage.mock.calls[0][0].message).not.toContain('lh topic view');});});diff --git a/src/store/chat/slices/forward/action.ts b/src/store/chat/slices/forward/action.tsindex dcfd572d2fb..60f285fe809 100644--- a/src/store/chat/slices/forward/action.ts+++ b/src/store/chat/slices/forward/action.ts@@ -2,6 +2,7 @@ import type { UIChatMessage } from '@lobechat/types';import { agentService } from '@/services/agent';import { messageService } from '@/services/message';+import { topicService } from '@/services/topic';import { getAgentStoreState } from '@/store/agent';import { agentSelectors } from '@/store/agent/selectors';import type { ChatStore } from '@/store/chat/store';@@ -23,17 +24,19 @@ export interface ForwardResultItem {export interface ForwardResult {failed: ForwardResultItem[];+ sourceSchedulePaused?: boolean;succeeded: ForwardResultItem[];}export interface ForwardMessagesParams extends ForwardContentOptions {messages: UIChatMessage[];note?: string;- onTopicCreated?: (target: ForwardTarget, topicId: string) => void;+ onTopicCreated?: (target: ForwardTarget, topicId: string) => void | Promise<void>;targets: ForwardTarget[];}export interface ForwardTopicParams extends Omit<ForwardMessagesParams, 'messages'> {+ cancelSourceContinuation?: boolean;sourceAgentId: string;topicId: string;}@@ -97,12 +100,99 @@ export class ChatForwardActionImpl {};forwardTopic = async ({- sourceAgentId,+ cancelSourceContinuation,+ header,topicId,- ...params+ note,+ onTopicCreated,+ roleLabel,+ sourceAgentId,+ targets,}: ForwardTopicParams): Promise<ForwardResult> => {- const messages = await messageService.getMessages({ agentId: sourceAgentId, topicId });- return this.forwardMessages({ ...params, messages });+ if (targets.length === 0) return { failed: [], succeeded: [] };++ const cliInstruction = [+ `Use the LobeHub CLI to read the full conversation history for topic ${topicId}:`,+ '',+ `lh topic view ${topicId} -L 500`,+ '',+ 'Every message it prints is the context from the previous Agent. If the topic has more than 500 messages, page through the remainder with --from and --to. Continue the work from where it left off and handle the remaining request item by item.',+ 'If the CLI is unavailable, continue using the conversation transcript included below.',+ ]+ .filter(Boolean)+ .join('\n');+ let transcriptPromise: Promise<string> | undefined;+ const getTranscript = () => {+ transcriptPromise ??= messageService+ .getMessages({ agentId: sourceAgentId, topicId })+ .then((messages) => {+ const transcript = buildForwardedContent(messages, { header, roleLabel });+ return note?.trim() ? `${transcript}\n\n${note.trim()}` : transcript;+ });+ return transcriptPromise;+ };+ // Resolve configuration and context before touching the source schedule.+ const prepared = await Promise.allSettled(+ targets.map(async (target) => {+ let config = agentSelectors.getAgentConfigById(target.id)(getAgentStoreState());+ if (!config) {+ const fetchedConfig = await agentService.getAgentConfigById(target.id);+ if (!fetchedConfig) throw new Error(`Forwarding target agent not found: ${target.id}`);+ config = fetchedConfig;+ getAgentStoreState().internal_dispatchAgentMap(target.id, fetchedConfig);+ }++ const content = config.agencyConfig?.heterogeneousProvider+ ? `${cliInstruction}\n\n${await getTranscript()}`+ : await getTranscript();++ return { content, target };+ }),+ );+ const hasReadyTarget = prepared.some((item) => item.status === 'fulfilled');+ // A claimed source rejects the handoff before any target can start.+ const cancellation =+ cancelSourceContinuation && hasReadyTarget+ ? await topicService.cancelRateLimitContinuation(topicId)+ : null;+ if (cancellation)+ this.#get().internal_dispatchTopic({+ id: topicId,+ type: 'updateTopic',+ value: { metadata: cancellation.metadata, status: 'failed' },+ });+ let accepted = false;+ const settled = await Promise.allSettled(+ prepared.map(async (item) => {+ if (item.status === 'rejected') throw item.reason;+ const { content, target } = item.value;+ const result = await this.#get().sendMessage({+ context: { agentId: target.id, isNew: true, isolatedTopic: true, scope: 'main' },+ message: content,+ messages: [],+ onTopicCreated: async (createdTopicId) => {+ accepted = true;+ await onTopicCreated?.(target, createdTopicId);+ },+ });+ if (!result?.createdTopicId)+ throw new Error(`Forwarding did not create a topic for ${target.id}`);++ accepted = true;+ return { agentId: target.id, topicId: result.createdTopicId };+ }),+ );++ // A failed response can follow a persisted target. Do not re-arm the source+ // on ambiguous sends; let the user inspect the target before retrying.+ return settled.reduce<ForwardResult>(+ (result, item, index) => {+ if (item.status === 'fulfilled') result.succeeded.push(item.value);+ else result.failed.push({ agentId: targets[index].id, error: item.reason });+ return result;+ },+ { failed: [], succeeded: [], sourceSchedulePaused: !!cancellation && !accepted },+ );};}