Skip to content

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

πŸ› fix(topic): sync scheduled runs into active conversations (#17473)

Arvin Xu07e02f2e622d
diff --git a/apps/server/src/services/heterogeneousAgent/index.ts b/apps/server/src/services/heterogeneousAgent/index.ts
index a14d95265e3..20ae9a37b27 100644
--- a/apps/server/src/services/heterogeneousAgent/index.ts
+++ b/apps/server/src/services/heterogeneousAgent/index.ts
@@ -260,6 +260,11 @@ export class HeterogeneousAgentService {
? currentMsgRef.msgId
: topic?.metadata?.runningOperation?.assistantMessageId;
await this.topicModel.updateMetadata(topicId, { runningOperation: null });
+ // Settle `status: 'running'` for runs with no renderer attached (e.g. a
+ // cron-dispatched scheduled resume) β€” otherwise nothing ever moves the
+ // topic off `running`. Guarded in the model: an attached client's own
+ // terminal write ('active'/'unread') is never clobbered.
+ await this.topicModel.settleRunningStatus(topicId);
} catch (err) {
log('heteroFinish: failed to clear runningOperation (non-fatal): %O', err);
}
diff --git a/packages/database/src/models/__tests__/topic.test.ts b/packages/database/src/models/__tests__/topic.test.ts
index da64b17f425..b53a4ee6a61 100644
--- a/packages/database/src/models/__tests__/topic.test.ts
+++ b/packages/database/src/models/__tests__/topic.test.ts
@@ -527,6 +527,46 @@ describe('TopicModel', () => {
});
});
+ describe('settleRunningStatus', () => {
+ it("settles a running topic to 'unread' by default", async () => {
+ const topic = await topicModel.create({ title: 'running run' });
+ await topicModel.update(topic.id, { status: 'running' });
+
+ const [settled] = await topicModel.settleRunningStatus(topic.id);
+ expect(settled.status).toBe('unread');
+ });
+
+ it('never clobbers a status a client already wrote', async () => {
+ // Regression: heteroFinish settles server-side after the terminal stream
+ // event; a renderer that received the same event may have written
+ // 'active'/'unread' first. The guard must turn the late settle into a
+ // no-op instead of reverting the client's write.
+ const topic = await topicModel.create({ title: 'client settled first' });
+ await topicModel.update(topic.id, { status: 'active' });
+
+ const result = await topicModel.settleRunningStatus(topic.id);
+ expect(result).toHaveLength(0);
+
+ const [row] = await serverDB.select().from(topics).where(eq(topics.id, topic.id));
+ expect(row.status).toBe('active');
+ });
+
+ it('does not settle a topic owned by another user', async () => {
+ await serverDB.insert(topics).values({
+ id: 't-foreign-settle',
+ status: 'running',
+ title: 'foreign running',
+ userId: otherUserId,
+ });
+
+ const result = await topicModel.settleRunningStatus('t-foreign-settle');
+ expect(result).toHaveLength(0);
+
+ const [row] = await serverDB.select().from(topics).where(eq(topics.id, 't-foreign-settle'));
+ expect(row.status).toBe('running');
+ });
+ });
+
describe('updateMetadata', () => {
it('merges new metadata into existing metadata', async () => {
const topic = await topicModel.create({
diff --git a/packages/database/src/models/topic.ts b/packages/database/src/models/topic.ts
index fcb7244aca2..c58aa73a332 100644
--- a/packages/database/src/models/topic.ts
+++ b/packages/database/src/models/topic.ts
@@ -1200,6 +1200,26 @@ export class TopicModel {
.returning();
};
+ /**
+ * Settle a topic out of `running` once its run has terminated server-side.
+ *
+ * Guarded on `status = 'running'` so it is race-tolerant with clients: an
+ * attached renderer writes 'active' (focused) or 'unread' (backgrounded) on
+ * the terminal stream event, and whichever write lands first wins β€” this one
+ * degrades to a no-op instead of clobbering it. Without a server-side settle,
+ * a run with no client attached (cron-dispatched scheduled resume, app closed
+ * mid-run) leaves the topic at `running` forever.
+ *
+ * Returns the settled row, or nothing when the guard didn't match.
+ */
+ settleRunningStatus = async (id: string, status: TopicItem['status'] = 'unread') => {
+ return this.db
+ .update(topics)
+ .set({ status, updatedAt: new Date() })
+ .where(and(eq(topics.id, id), eq(topics.status, 'running'), this.ownership()))
+ .returning({ id: topics.id, status: topics.status });
+ };
+
/**
* Move multiple topics (and all their messages) to another agent.
*
diff --git a/src/hooks/useScheduledRunWatch.ts b/src/hooks/useScheduledRunWatch.ts
new file mode 100644
index 00000000000..265aaf1935a
--- /dev/null
+++ b/src/hooks/useScheduledRunWatch.ts
@@ -0,0 +1,58 @@
+import useSWR from 'swr';
+
+import { topicKeys } from '@/libs/swr/keys';
+import { useChatStore } from '@/store/chat';
+import { topicSelectors } from '@/store/chat/selectors';
+
+/** Poll cadence once the run is due β€” the cron dispatcher ticks every ~10 min. */
+const POLL_INTERVAL_MS = 30_000;
+/** Start polling slightly before `runAt` so the first due tick isn't missed. */
+const POLL_LEAD_MS = 60_000;
+
+/**
+ * Watch the open topic while it is parked as `scheduled` (rate-limit resume or
+ * a deferred send) and pull the cron dispatch into the store when it happens.
+ *
+ * The dispatcher only writes to the DB β€” there is no push channel to a client
+ * already sitting on the topic β€” so without this the stale rate-limit card,
+ * the `scheduled` status and the missing stream all persist until an unrelated
+ * SWR revalidation (blur→focus, reconnect) happens to refetch.
+ *
+ * Two triggers, one sync (`syncScheduledTopicRun`):
+ * - on topic entry: an immediate check, catching a dispatch that happened
+ * while the topic wasn't open;
+ * - around `runAt`: a 30s poll, armed just before the run is due. Far from
+ * `runAt` the "interval" is a single timer that lands at the window start,
+ * so an idle parked topic costs no recurring requests.
+ *
+ * Stops by itself: once the sync folds the dispatch in, the topic's status
+ * leaves `scheduled` and the SWR key becomes null. From there
+ * `useGatewayReconnect` (keyed off the synced `runningOperation`) attaches to
+ * the live stream.
+ */
+export const useScheduledRunWatch = (topicId: string | null | undefined) => {
+ // `null` = scheduled but no runAt recorded β€” treat as due now rather than
+ // never (mirrors the dispatcher, whose due query requires runAt <= now but
+ // whose writers always stamp one).
+ const scheduledRunAt = useChatStore((s): string | null | undefined => {
+ if (!topicId) return undefined;
+ const topic = topicSelectors.getTopicById(topicId)(s);
+ if (topic?.status !== 'scheduled') return undefined;
+ return topic.metadata?.scheduledRun?.runAt ?? null;
+ });
+
+ useSWR(
+ topicId && scheduledRunAt !== undefined ? topicKeys.scheduledRunWatch(topicId) : null,
+ () => useChatStore.getState().syncScheduledTopicRun(topicId!),
+ {
+ refreshInterval: () => {
+ if (scheduledRunAt === undefined) return 0;
+ const dueAt = scheduledRunAt ? new Date(scheduledRunAt).getTime() - POLL_LEAD_MS : 0;
+ const untilDue = dueAt - Date.now();
+ return untilDue > POLL_INTERVAL_MS ? untilDue : POLL_INTERVAL_MS;
+ },
+ revalidateOnFocus: true,
+ shouldRetryOnError: false,
+ },
+ );
+};
diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.ts
index 674118b9a45..9b1637d584a 100644
--- a/src/libs/swr/keys.ts
+++ b/src/libs/swr/keys.ts
@@ -126,6 +126,10 @@ export const topicKeys = {
containerKey,
opts,
]),
+ scheduledRunWatch: def('topic:scheduledRunWatch', (topicId: string) => [
+ 'topic:scheduledRunWatch',
+ topicId,
+ ]),
search: def('topic:search', (keywords: string, agentId?: string, groupId?: string) => [
'topic:search',
keywords,
diff --git a/src/routes/(main)/agent/features/Conversation/ConversationArea.tsx b/src/routes/(main)/agent/features/Conversation/ConversationArea.tsx
index 46f51b5642b..28a41662d2f 100644
--- a/src/routes/(main)/agent/features/Conversation/ConversationArea.tsx
+++ b/src/routes/(main)/agent/features/Conversation/ConversationArea.tsx
@@ -19,6 +19,7 @@ import {
import { mergeConversationHooks } from '@/features/Conversation/utils/mergeConversationHooks';
import { useGatewayReconnect } from '@/hooks/useGatewayReconnect';
import { useOperationState } from '@/hooks/useOperationState';
+import { useScheduledRunWatch } from '@/hooks/useScheduledRunWatch';
import { useAgentStore } from '@/store/agent';
import { agentByIdSelectors, chatConfigByIdSelectors } from '@/store/agent/selectors';
import { useChatStore } from '@/store/chat';
@@ -96,6 +97,11 @@ const Conversation = memo(() => {
);
useGatewayReconnect(context.topicId, runningOperation);
+ // While the topic is parked as `scheduled`, pull the cron dispatch into the
+ // store when `runAt` passes β€” nothing pushes it, and the reconnect above
+ // can't fire until the synced `runningOperation` lands in the topic map.
+ useScheduledRunWatch(context.topicId);
+
const agentChatConfig = useAgentStore(chatConfigByIdSelectors.getChatConfigById(context.agentId));
const chatFollowUpHooks = useChatFollowUp({
agentChatConfig,
diff --git a/src/store/chat/slices/topic/action.test.ts b/src/store/chat/slices/topic/action.test.ts
index 8223acc20d2..a0d4815c040 100644
--- a/src/store/chat/slices/topic/action.test.ts
+++ b/src/store/chat/slices/topic/action.test.ts
@@ -43,6 +43,7 @@ vi.mock('@/services/topic', () => ({
updateTopicTitle: vi.fn(),
updateTopic: vi.fn(),
batchRemoveTopics: vi.fn(),
+ getTopicDetail: vi.fn(),
getTopics: vi.fn(),
queryTopics: vi.fn(),
searchTopics: vi.fn(),
@@ -1796,6 +1797,118 @@ describe('topic action', () => {
});
});
+ describe('syncScheduledTopicRun', () => {
+ const agentId = 'sync-scheduled-agent';
+ const topicId = 'sync-scheduled-topic';
+ const key = topicMapKey({ agentId });
+
+ const scheduledRun = {
+ createdAt: '2026-07-22T00:00:00.000Z',
+ failedAssistantMessageId: 'assistant-failed',
+ kind: 'resume_after_rate_limit',
+ runAt: '2026-07-22T05:00:00.000Z',
+ source: 'heterogeneous_agent',
+ updatedAt: '2026-07-22T00:00:00.000Z',
+ userMessageId: 'user-1',
+ };
+
+ const seedScheduledTopic = (refreshMessages = vi.fn()) => {
+ const topic = {
+ id: topicId,
+ metadata: { scheduledRun },
+ status: 'scheduled',
+ title: 'Parked topic',
+ } as unknown as ChatTopic;
+
+ act(() => {
+ useChatStore.setState({
+ activeAgentId: agentId,
+ refreshMessages,
+ topicDataMap: {
+ [key]: { currentPage: 0, hasMore: false, items: [topic], pageSize: 20, total: 1 },
+ },
+ });
+ });
+
+ return refreshMessages;
+ };
+
+ it('folds a cron dispatch into the topic map and refetches messages', async () => {
+ const { result } = renderHook(() => useChatStore());
+ const refreshMessages = seedScheduledTopic();
+
+ // The dispatcher has fired: status moved off `scheduled`, the schedule is
+ // cleared and the live operation marker is seeded.
+ const runningOperation = { assistantMessageId: 'assistant-new', operationId: 'op-1' };
+ vi.spyOn(topicService, 'getTopicDetail').mockResolvedValue({
+ id: topicId,
+ metadata: { runningOperation },
+ status: 'running',
+ } as any);
+
+ let synced = false;
+ await act(async () => {
+ synced = await result.current.syncScheduledTopicRun(topicId);
+ });
+
+ expect(synced).toBe(true);
+ // The patched map is what `useGatewayReconnect` reads β€” without this the
+ // sitting client never attaches to the resumed stream (the original bug).
+ expect(useChatStore.getState().topicDataMap[key].items[0]).toMatchObject({
+ metadata: { runningOperation },
+ status: 'running',
+ });
+ expect(refreshMessages).toHaveBeenCalled();
+ });
+
+ it('is a no-op while the server still parks the topic', async () => {
+ const { result } = renderHook(() => useChatStore());
+ const refreshMessages = seedScheduledTopic();
+
+ vi.spyOn(topicService, 'getTopicDetail').mockResolvedValue({
+ id: topicId,
+ metadata: { scheduledRun },
+ status: 'scheduled',
+ } as any);
+
+ let synced = true;
+ await act(async () => {
+ synced = await result.current.syncScheduledTopicRun(topicId);
+ });
+
+ expect(synced).toBe(false);
+ expect(useChatStore.getState().topicDataMap[key].items[0].status).toBe('scheduled');
+ expect(refreshMessages).not.toHaveBeenCalled();
+ });
+
+ it('does not fetch at all when the store topic is not scheduled', async () => {
+ const { result } = renderHook(() => useChatStore());
+ const refreshMessages = vi.fn();
+ const topic = { id: topicId, status: 'active', title: 'Live topic' } as unknown as ChatTopic;
+
+ act(() => {
+ useChatStore.setState({
+ activeAgentId: agentId,
+ refreshMessages,
+ topicDataMap: {
+ [key]: { currentPage: 0, hasMore: false, items: [topic], pageSize: 20, total: 1 },
+ },
+ });
+ });
+
+ const detailSpy = vi.spyOn(topicService, 'getTopicDetail');
+
+ let synced = true;
+ await act(async () => {
+ synced = await result.current.syncScheduledTopicRun(topicId);
+ });
+
+ expect(synced).toBe(false);
+ expect(detailSpy).not.toHaveBeenCalled();
+ expect(refreshMessages).not.toHaveBeenCalled();
+ });
+ });
+
describe('internal_updateTopicLinkedPullRequest', () => {
const agentId = 'agent-1';
const topicId = 'topic-1';
diff --git a/src/store/chat/slices/topic/action.ts b/src/store/chat/slices/topic/action.ts
index 8803fedd7b4..4efe07fd393 100644
--- a/src/store/chat/slices/topic/action.ts
+++ b/src/store/chat/slices/topic/action.ts
@@ -636,6 +636,55 @@ export class ChatTopicActionImpl {
}
};
+ /**
+ * Re-read a `scheduled` topic from the server and fold any dispatch back into
+ * the store. The cron dispatcher (`scheduledTopicDispatch`) mutates only the
+ * DB when `runAt` passes β€” status β†’ 'running', `scheduledRun` cleared,
+ * `runningOperation` seeded, the parked error card cleared off the failed
+ * message β€” and no push channel tells a client that is already sitting on the
+ * topic. This is the pull side: `useScheduledRunWatch` calls it on topic entry
+ * and on a short poll around `runAt`.
+ *
+ * When the server has moved past `scheduled`, the fresh row is patched into
+ * the topic map (so `useGatewayReconnect` sees `runningOperation` and attaches
+ * to the live stream) and the message list is refetched (so the stale
+ * rate-limit card drops and the continuation's assistant row appears).
+ *
+ * Returns whether a dispatch was observed and folded in.
+ */
+ syncScheduledTopicRun = async (topicId: string): Promise<boolean> => {
+ const stored = topicSelectors.getTopicById(topicId)(this.#get());
+ // Only a topic the store believes is parked needs syncing; anything else
+ // already has a live update path (or isn't loaded in the active bucket).
+ if (stored?.status !== 'scheduled') return false;
+
+ const fresh = await topicService.getTopicDetail(topicId);
+ if (!fresh) return false;
+
+ // Server still parked β€” nothing to fold in.
+ if (fresh.status === 'scheduled' && fresh.metadata?.scheduledRun) return false;
+
+ // Re-check after the await: a topic/agent switch mid-flight means the
+ // active bucket no longer holds this row β€” don't patch a foreign bucket.
+ if (topicSelectors.getTopicById(topicId)(this.#get())?.status !== 'scheduled') return false;
+
+ this.#get().internal_dispatchTopic(
+ {
+ id: topicId,
+ type: 'updateTopic',
+ value: { metadata: fresh.metadata, status: fresh.status },
+ },
+ n('syncScheduledTopicRun'),
+ );
+
+ // The dispatcher also rewrote messages before handing off (cleared/deleted
+ // the failed step, created the continuation's placeholder), so the list
+ // must be refetched before the gateway reconnect anchors on it.
+ await this.#get().refreshMessages();
+
+ return true;
+ };
+
useFetchTopicLinkedPullRequest = (
topicId?: string,
metadata?: ChatTopicMetadata,