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(chat): restore loading for background review runs (#21064)

AmAzing-a0fd0130a950
diff --git a/apps/server/src/routers/lambda/__tests__/scm.test.ts b/apps/server/src/routers/lambda/__tests__/scm.test.ts
index 86bce8c188e..cd174ae94fd 100644
--- a/apps/server/src/routers/lambda/__tests__/scm.test.ts
+++ b/apps/server/src/routers/lambda/__tests__/scm.test.ts
@@ -7,7 +7,13 @@ import {
ScmIdentityModel,
ScmInstallationModel,
} from '@/database/models/scm';
-import { scmWebhookDeliveries, users, workspaceMembers, workspaces } from '@/database/schemas';
+import {
+ scmWebhookDeliveries,
+ topics,
+ users,
+ workspaceMembers,
+ workspaces,
+} from '@/database/schemas';
import { scmRouter } from '../scm';
@@ -15,9 +21,8 @@ const serverDB = await getTestDB();
const userId = 'scm-router-user';
const otherUserId = 'scm-router-user-2';
-vi.mock('@/envs/scm', () => ({
- scmEnv: { ENABLED_GITHUB_APP: true, GITHUB_APP_SLUG: 'lobehub-dev' },
-}));
+const scmEnv = vi.hoisted(() => ({ ENABLED_GITHUB_APP: true, GITHUB_APP_SLUG: 'lobehub-dev' }));
+vi.mock('@/envs/scm', () => ({ scmEnv }));
const mocks = vi.hoisted(() => ({ consumeClaim: vi.fn(), fetchInstallation: vi.fn() }));
vi.mock('@/server/services/scm/oauth/stateStore', () => ({
@@ -140,6 +145,31 @@ describe('scmRouter', () => {
]);
});
+ it('reports a wake target for the caller own open PR, and none without the GitHub App', async () => {
+ await serverDB.insert(topics).values({ id: 'scm-router-topic', title: 't', userId });
+ await ScmChangeRequestModel.upsert(serverDB, {
+ links: { topicId: 'scm-router-topic' },
+ number: 4,
+ provider: 'github',
+ repoFullName: 'a/wake',
+ state: 'open',
+ url: 'https://github.com/a/wake/pull/4',
+ userId,
+ });
+
+ expect(await caller({ userId }).hasWakeTarget({ topicId: 'scm-router-topic' })).toBe(true);
+ expect(
+ await caller({ userId: otherUserId }).hasWakeTarget({ topicId: 'scm-router-topic' }),
+ ).toBe(false);
+
+ scmEnv.ENABLED_GITHUB_APP = false;
+ try {
+ expect(await caller({ userId }).hasWakeTarget({ topicId: 'scm-router-topic' })).toBe(false);
+ } finally {
+ scmEnv.ENABLED_GITHUB_APP = true;
+ }
+ });
+
it('refuses a claim that is expired or was minted for someone else', async () => {
mocks.fetchInstallation.mockResolvedValue({
accountExternalId: '9',
diff --git a/apps/server/src/routers/lambda/scm.ts b/apps/server/src/routers/lambda/scm.ts
index 36cf30da6d0..b30edbd4268 100644
--- a/apps/server/src/routers/lambda/scm.ts
+++ b/apps/server/src/routers/lambda/scm.ts
@@ -11,6 +11,7 @@ import { scmEnv } from '@/envs/scm';
import { router } from '@/libs/trpc/lambda';
import { serverDatabase } from '@/libs/trpc/lambda/middleware';
import { fetchGitHubInstallation } from '@/server/services/scm/github/app';
+import { SCM_MAX_WAKES } from '@/server/services/scm/limits';
import { consumeScmInstallClaim } from '@/server/services/scm/oauth/stateStore';
import { canWriteScmScope } from '@/server/services/scm/scope';
@@ -115,6 +116,22 @@ export const scmRouter = router({
};
}),
+ /**
+ * Whether a review or CI event can still wake this conversation. An open
+ * conversation polls for that background run only while this holds.
+ */
+ hasWakeTarget: scmProcedure
+ .input(z.object({ topicId: z.string() }))
+ .query(async ({ ctx, input }) => {
+ if (!scmEnv.ENABLED_GITHUB_APP) return false;
+ return ScmChangeRequestModel.hasWakeTarget(
+ ctx.serverDB,
+ ctx.scope,
+ input.topicId,
+ SCM_MAX_WAKES,
+ );
+ }),
+
listChangeRequests: scmProcedure
.input(z.object({ limit: z.number().int().min(1).max(200).optional() }).optional())
.query(async ({ ctx, input }) =>
diff --git a/apps/server/src/services/scm/ScmControlService.ts b/apps/server/src/services/scm/ScmControlService.ts
index 9b89385853c..ec3ff01586b 100644
--- a/apps/server/src/services/scm/ScmControlService.ts
+++ b/apps/server/src/services/scm/ScmControlService.ts
@@ -21,6 +21,7 @@ import {
postGitHubPullRequestComment,
updateGitHubPullRequestComment,
} from './github/app';
+import { SCM_MAX_WAKES } from './limits';
import { canWriteScmScope } from './scope';
import { buildTrackingComment } from './trackingComment';
import type { ScmInboundEvent } from './types';
@@ -28,8 +29,8 @@ import { buildCiFailurePrompt, buildReviewPrompt, type ScmWakeReason } from './w
const log = debug('lobe-server:scm:control');
-/** Wakes per change request before the loop hands over to a human. */
-export const SCM_MAX_WAKES = 3;
+export { SCM_MAX_WAKES };
+
/** Window in which repeated events on one change request collapse into one wake. */
const WAKE_DEBOUNCE_SECONDS = 60;
/** How far back review feedback is collected for a wake. */
diff --git a/apps/server/src/services/scm/limits.ts b/apps/server/src/services/scm/limits.ts
new file mode 100644
index 00000000000..31f45661b75
--- /dev/null
+++ b/apps/server/src/services/scm/limits.ts
@@ -0,0 +1,2 @@
+/** Wakes per change request before the loop hands over to a human. */
+export const SCM_MAX_WAKES = 3;
diff --git a/packages/database/src/models/scm/__tests__/changeRequest.test.ts b/packages/database/src/models/scm/__tests__/changeRequest.test.ts
index 1b953164570..57297321123 100644
--- a/packages/database/src/models/scm/__tests__/changeRequest.test.ts
+++ b/packages/database/src/models/scm/__tests__/changeRequest.test.ts
@@ -3,7 +3,7 @@ import { eq } from 'drizzle-orm';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { getTestDB } from '../../../core/getTestDB';
-import { acceptances, scmWebhookDeliveries, users } from '../../../schemas';
+import { acceptances, scmWebhookDeliveries, topics, users } from '../../../schemas';
import { mergeChecks, rollupCiStatus, ScmChangeRequestModel } from '../changeRequest';
import { ScmWebhookDeliveryModel } from '../delivery';
import { ScmInstallationModel } from '../installation';
@@ -401,6 +401,33 @@ describe('ScmChangeRequestModel', () => {
expect(moved.topicId).toBeNull();
});
+ it('reports a wake target only for an open, ready, uncapped PR in the caller scope', async () => {
+ await serverDB.insert(topics).values({ id: 'scm-wake-topic', title: 't', userId });
+ const has = (scope = { userId }) =>
+ ScmChangeRequestModel.hasWakeTarget(serverDB, scope, 'scm-wake-topic', 2);
+ const link = (number: number, extra: Partial<typeof snapshot> & { isDraft?: boolean } = {}) =>
+ ScmChangeRequestModel.upsert(serverDB, {
+ ...snapshot,
+ ...extra,
+ links: { topicId: 'scm-wake-topic' },
+ number,
+ });
+
+ expect(await has()).toBe(false);
+ await link(20, { isDraft: true });
+ await link(21, { state: 'closed' });
+ expect(await has()).toBe(false);
+
+ const open = await link(22);
+ expect(await has()).toBe(true);
+ expect(await has({ userId: 'someone-else' })).toBe(false);
+
+ await ScmChangeRequestModel.reserveWake(serverDB, open.id, 2);
+ expect(await has()).toBe(true);
+ await ScmChangeRequestModel.reserveWake(serverDB, open.id, 2);
+ expect(await has()).toBe(false);
+ });
+
it('rolls up review verdicts per reviewer, in any delivery order', async () => {
const row = await ScmChangeRequestModel.upsert(serverDB, snapshot);
diff --git a/packages/database/src/models/scm/changeRequest.ts b/packages/database/src/models/scm/changeRequest.ts
index dc6c7f1beb6..b61ab257629 100644
--- a/packages/database/src/models/scm/changeRequest.ts
+++ b/packages/database/src/models/scm/changeRequest.ts
@@ -15,6 +15,11 @@ import type { ScmChangeRequestItem } from '../../schemas';
import { scmChangeRequests, scmInstallations } from '../../schemas';
import type { LobeChatDatabase } from '../../type';
+const ownedByScope = (scope: { userId: string; workspaceId?: string | null }) =>
+ scope.workspaceId
+ ? eq(scmChangeRequests.workspaceId, scope.workspaceId)
+ : and(eq(scmChangeRequests.userId, scope.userId), isNull(scmChangeRequests.workspaceId));
+
/**
* Conclusions worth waking an agent over: something broke and there is
* something to fix. A cancelled or stale run is not one of them β€” usually a
@@ -199,9 +204,7 @@ export class ScmChangeRequestModel {
scope: { userId: string; workspaceId?: string | null },
options: { limit?: number } = {},
): Promise<ScmChangeRequestItem[]> => {
- const owned = scope.workspaceId
- ? eq(scmChangeRequests.workspaceId, scope.workspaceId)
- : and(eq(scmChangeRequests.userId, scope.userId), isNull(scmChangeRequests.workspaceId));
+ const owned = ownedByScope(scope);
const connected = db
.select({ id: scmInstallations.id })
@@ -223,6 +226,35 @@ export class ScmChangeRequestModel {
.limit(options.limit ?? 50);
};
+ /**
+ * Whether a provider event could still wake `topicId`: the static half of
+ * `ScmControlService.wake`'s gate. Scoped like that wake, which resolves the
+ * topic under the row's own tenant. Lets an open conversation poll for a
+ * background run only when one can actually arrive.
+ */
+ static hasWakeTarget = async (
+ db: LobeChatDatabase,
+ scope: { userId: string; workspaceId?: string | null },
+ topicId: string,
+ maxWakes: number,
+ ): Promise<boolean> => {
+ const [row] = await db
+ .select({ id: scmChangeRequests.id })
+ .from(scmChangeRequests)
+ .where(
+ and(
+ eq(scmChangeRequests.topicId, topicId),
+ eq(scmChangeRequests.state, 'open'),
+ eq(scmChangeRequests.isDraft, false),
+ lt(scmChangeRequests.wakeCount, maxWakes),
+ ownedByScope(scope),
+ ),
+ )
+ .limit(1);
+
+ return !!row;
+ };
+
static listByTopic = async (
db: LobeChatDatabase,
topicId: string,
diff --git a/src/hooks/useFetchActiveTopicDetail.test.ts b/src/hooks/useFetchActiveTopicDetail.test.ts
new file mode 100644
index 00000000000..098782e95b7
--- /dev/null
+++ b/src/hooks/useFetchActiveTopicDetail.test.ts
@@ -0,0 +1,279 @@
+import { act, renderHook } from '@testing-library/react';
+import { createElement, type PropsWithChildren } from 'react';
+import { SWRConfig } from 'swr';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { cacheScope, createReplicaState } from '@/libs/replica';
+import { scmService } from '@/services/scm';
+import { topicService } from '@/services/topic';
+import { useChatStore } from '@/store/chat';
+import { topicSelectors } from '@/store/chat/selectors';
+import type { ChatTopic } from '@/types/topic';
+
+import { useFetchActiveTopicDetail } from './useFetchActiveTopicDetail';
+import { useGatewayReconnect } from './useGatewayReconnect';
+import { useOperationState } from './useOperationState';
+
+const config = vi.hoisted(() => ({ serverConfig: { agentGatewayUrl: 'wss://gateway.test' } }));
+vi.mock('@/store/serverConfig', () => ({
+ useServerConfigStore: (selector: (state: typeof config) => unknown) => selector(config),
+}));
+
+const context = { agentId: 'agent-cr', topicId: 'topic-cr' };
+const topic = {
+ createdAt: new Date(),
+ id: context.topicId,
+ metadata: {},
+ status: 'active',
+ title: 'Review feedback',
+ updatedAt: new Date(),
+} as ChatTopic;
+const runningOperation = {
+ assistantMessageId: 'assistant-cr',
+ heteroType: 'claude-code',
+ operationId: 'server-cr',
+};
+
+const wrapper = ({ children }: PropsWithChildren) =>
+ createElement(SWRConfig, { value: { provider: () => new Map() } }, children);
+
+const useConversation = () => {
+ useFetchActiveTopicDetail();
+ const marker = useChatStore(
+ (s) => topicSelectors.getTopicById(context.topicId)(s)?.metadata?.runningOperation,
+ );
+ useGatewayReconnect(context.topicId, marker, context.agentId);
+ return useOperationState(context);
+};
+
+describe('background runs in the active topic', () => {
+ beforeEach(() => {
+ vi.spyOn(cacheScope, 'get').mockReturnValue('cr-test:personal');
+ vi.spyOn(cacheScope, 'use').mockReturnValue('cr-test:personal');
+ vi.spyOn(cacheScope, 'canHydrate').mockReturnValue(false);
+ vi.spyOn(cacheScope, 'canPersist').mockReturnValue(false);
+ useChatStore.setState({
+ activeAgentId: context.agentId,
+ activeTopicId: context.topicId,
+ activeGroupId: undefined,
+ creatingTopicIds: [],
+ operations: {},
+ operationsByContext: {},
+ operationsByMessage: {},
+ operationsByType: {},
+ topicDataMap: {},
+ topicDetailMap: {},
+ topicDetailReplica: createReplicaState(),
+ topicListReplica: createReplicaState(),
+ });
+ useChatStore
+ .getState()
+ .internal_updateTopics(context.agentId, { items: [topic], pageSize: 20, total: 1 });
+ config.serverConfig.agentGatewayUrl = 'wss://gateway.test';
+ vi.spyOn(topicService, 'getTopicDetail').mockResolvedValue(topic);
+ vi.spyOn(scmService, 'hasWakeTarget').mockResolvedValue(true);
+ // Network boundary: reconnect's local operation is what the real composer reads.
+ vi.spyOn(useChatStore.getState(), 'reconnectToGatewayOperation').mockImplementation(
+ async () => {
+ useChatStore.getState().startOperation({ context, type: 'execServerAgentRuntime' });
+ },
+ );
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ vi.useRealTimers();
+ });
+
+ it('discovers a CR run while the conversation stays open and restores the stop control', async () => {
+ vi.useFakeTimers();
+ const { result } = renderHook(useConversation, { wrapper });
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(0);
+ });
+ expect(result.current.isInputVisiblyLoading).toBe(false);
+
+ vi.mocked(topicService.getTopicDetail).mockResolvedValue({
+ ...topic,
+ metadata: { runningOperation },
+ status: 'running',
+ });
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(15_000);
+ });
+ expect(result.current.isInputVisiblyLoading).toBe(true);
+ expect(
+ topicSelectors.getTopicById(topic.id)(useChatStore.getState())?.metadata?.runningOperation,
+ ).toEqual(runningOperation);
+
+ const reads = vi.mocked(topicService.getTopicDetail).mock.calls.length;
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(10_000);
+ });
+ expect(topicService.getTopicDetail).toHaveBeenCalledTimes(reads);
+
+ act(() => {
+ for (const op of Object.values(useChatStore.getState().operations)) {
+ useChatStore.getState().completeOperation(op.id);
+ }
+ });
+ expect(result.current.isInputVisiblyLoading).toBe(false);
+ });
+
+ it('discovers another background run after the previous one ends', async () => {
+ vi.useFakeTimers();
+ vi.mocked(topicService.getTopicDetail).mockResolvedValue({
+ ...topic,
+ metadata: { runningOperation },
+ });
+ const { result } = renderHook(useConversation, { wrapper });
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(0);
+ });
+ expect(result.current.isInputVisiblyLoading).toBe(true);
+
+ vi.mocked(topicService.getTopicDetail).mockResolvedValue(topic);
+ await act(async () => {
+ useChatStore.getState().internal_dispatchTopic({
+ id: topic.id,
+ type: 'updateTopic',
+ value: { metadata: { runningOperation: null } },
+ });
+ for (const op of Object.values(useChatStore.getState().operations)) {
+ useChatStore.getState().completeOperation(op.id);
+ }
+ await vi.advanceTimersByTimeAsync(1000);
+ });
+ expect(result.current.isInputVisiblyLoading).toBe(false);
+
+ const next = { ...runningOperation, operationId: 'server-cr-2' };
+ vi.mocked(topicService.getTopicDetail).mockResolvedValue({
+ ...topic,
+ metadata: { runningOperation: next },
+ });
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(15_000);
+ });
+ expect(result.current.isInputVisiblyLoading).toBe(true);
+ expect(useChatStore.getState().reconnectToGatewayOperation).toHaveBeenCalledTimes(2);
+ });
+
+ it('does not overwrite a local run that starts while discovery is in flight', async () => {
+ vi.useFakeTimers();
+ let resolve!: (topic: ChatTopic) => void;
+ vi.mocked(topicService.getTopicDetail).mockReturnValue(
+ new Promise((done) => {
+ resolve = done;
+ }),
+ );
+ const { result } = renderHook(useConversation, { wrapper });
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(0);
+ });
+ act(() => {
+ useChatStore.getState().startOperation({ context, type: 'sendMessage' });
+ });
+ await act(async () => {
+ resolve({ ...topic, metadata: { runningOperation } });
+ await vi.advanceTimersByTimeAsync(0);
+ });
+ expect(result.current.isInputVisiblyLoading).toBe(true);
+ expect(useChatStore.getState().reconnectToGatewayOperation).not.toHaveBeenCalled();
+ expect(
+ topicSelectors.getTopicById(topic.id)(useChatStore.getState())?.metadata?.runningOperation,
+ ).toBeUndefined();
+ });
+
+ it('does not resurrect a run when a local send also finishes before the discovery response', async () => {
+ vi.useFakeTimers();
+ let resolve!: (topic: ChatTopic) => void;
+ vi.mocked(topicService.getTopicDetail).mockReturnValue(
+ new Promise((done) => {
+ resolve = done;
+ }),
+ );
+ const { result } = renderHook(useConversation, { wrapper });
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(0);
+ });
+ act(() => {
+ const { operationId } = useChatStore
+ .getState()
+ .startOperation({ context, type: 'sendMessage' });
+ useChatStore.getState().completeOperation(operationId);
+ });
+ await act(async () => {
+ resolve({ ...topic, metadata: { runningOperation } });
+ await vi.advanceTimersByTimeAsync(0);
+ });
+ expect(result.current.isInputVisiblyLoading).toBe(false);
+ expect(useChatStore.getState().reconnectToGatewayOperation).not.toHaveBeenCalled();
+ });
+
+ it('does not poll a known topic that no review or CI event can wake', async () => {
+ vi.useFakeTimers();
+ vi.mocked(scmService.hasWakeTarget).mockResolvedValue(false);
+ renderHook(useConversation, { wrapper });
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(60_000);
+ });
+ expect(scmService.hasWakeTarget).toHaveBeenCalledWith(context.topicId);
+ expect(topicService.getTopicDetail).not.toHaveBeenCalled();
+ });
+
+ it('starts watching once a local run links the topic to a pull request', async () => {
+ vi.useFakeTimers();
+ vi.mocked(scmService.hasWakeTarget).mockResolvedValue(false);
+ const { result } = renderHook(useConversation, { wrapper });
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(0);
+ });
+
+ // The agent opens a pull request during this run.
+ let operationId!: string;
+ act(() => {
+ ({ operationId } = useChatStore.getState().startOperation({ context, type: 'sendMessage' }));
+ });
+ vi.mocked(scmService.hasWakeTarget).mockResolvedValue(true);
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(3000);
+ useChatStore.getState().completeOperation(operationId);
+ // SWR revalidates a cached key on the next animation frame.
+ await vi.advanceTimersByTimeAsync(100);
+ });
+ expect(scmService.hasWakeTarget).toHaveBeenCalledTimes(2);
+ expect(topicService.getTopicDetail).toHaveBeenCalled();
+
+ vi.mocked(topicService.getTopicDetail).mockResolvedValue({
+ ...topic,
+ metadata: { runningOperation },
+ });
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(15_000);
+ });
+ expect(result.current.isInputVisiblyLoading).toBe(true);
+ });
+
+ it('does not poll known topics without a gateway', async () => {
+ vi.useFakeTimers();
+ config.serverConfig.agentGatewayUrl = '';
+ renderHook(useConversation, { wrapper });
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(10_000);
+ });
+ expect(topicService.getTopicDetail).not.toHaveBeenCalled();
+ });
+
+ it('keeps the missing-topic detail fallback without a gateway', async () => {
+ vi.useFakeTimers();
+ config.serverConfig.agentGatewayUrl = '';
+ useChatStore
+ .getState()
+ .internal_updateTopics(context.agentId, { items: [], pageSize: 20, total: 0 });
+ renderHook(useFetchActiveTopicDetail, { wrapper });
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(0);
+ });
+ expect(topicSelectors.getTopicById(topic.id)(useChatStore.getState())).toEqual(topic);
+ });
+});
diff --git a/src/hooks/useFetchActiveTopicDetail.ts b/src/hooks/useFetchActiveTopicDetail.ts
index d87ed769317..4be6bd4d37e 100644
--- a/src/hooks/useFetchActiveTopicDetail.ts
+++ b/src/hooks/useFetchActiveTopicDetail.ts
@@ -1,17 +1,21 @@
+import useSWR from 'swr';
+
+import { scmKeys } from '@/libs/swr/keys';
+import { scmService } from '@/services/scm';
import { useChatStore } from '@/store/chat';
import { topicSelectors } from '@/store/chat/selectors';
+import { hasLocalTopicRun } from '@/store/chat/slices/topic/topicDetail';
+import { useServerConfigStore } from '@/store/serverConfig';
/**
- * Fetch the active topic's detail when it is missing from the loaded list
- * bucket β€” e.g. an archived (`completed`) topic that the sidebar fetch
- * excludes via `excludeStatuses`, or a topic opened by URL whose page hasn't
- * been fetched. The result lands in `topicDetailMap`, which
- * `currentActiveTopic` reads as a fallback, so the header keeps the real
- * title instead of degrading to the "new topic" placeholder.
+ * Keep missing details available and discover runs started outside this client.
+ * SCM can wake an idle, already-open topic without a frontend send. Poll its
+ * detail until the normal gateway reconnect owns a local operation; that path
+ * supplies streaming, the composer's Stop control, and terminal cleanup.
*
- * Waits for the list bucket to load before deciding the topic is missing, so
- * the common case (topic present in the first page) never fires an extra
- * request.
+ * Polling is armed only while a review or CI event can still wake the topic.
+ * That check re-runs on entry, on focus, and after each local run, which is
+ * when the agent may have opened a pull request.
*/
export const useFetchActiveTopicDetail = () => {
const [activeTopicId, isMissingFromList, useFetchTopicDetail] = useChatStore((s) => [
@@ -21,6 +25,20 @@ export const useFetchActiveTopicDetail = () => {
!topicSelectors.currentTopics(s)?.some((topic) => topic.id === s.activeTopicId),
s.useFetchTopicDetail,
]);
+ const gatewayEnabled = useServerConfigStore((s) => !!s.serverConfig.agentGatewayUrl);
+ const idle = useChatStore(
+ (s) =>
+ !!s.activeTopicId &&
+ gatewayEnabled &&
+ !s.creatingTopicIds.includes(s.activeTopicId) &&
+ !hasLocalTopicRun(s, s.activeTopicId),
+ );
+ const { data: wakeable } = useSWR(
+ idle && activeTopicId ? scmKeys.wakeTarget(activeTopicId) : null,
+ () => scmService.hasWakeTarget(activeTopicId!),
+ { shouldRetryOnError: false },
+ );
+ const watchRuns = idle && !!wakeable;
- useFetchTopicDetail(isMissingFromList ? activeTopicId : undefined);
+ useFetchTopicDetail(isMissingFromList || watchRuns ? activeTopicId : undefined, watchRuns);
};
diff --git a/src/libs/swr/keys.ts b/src/libs/swr/keys.ts
index ff18cbe7593..9ad90f9f458 100644
--- a/src/libs/swr/keys.ts
+++ b/src/libs/swr/keys.ts
@@ -664,6 +664,7 @@ export const scmKeys = {
'scm:installations',
workspaceId ?? null,
]),
+ wakeTarget: def('scm:wakeTarget', (topicId: string) => ['scm:wakeTarget', topicId]),
};
// ---- verify (deliverable judging) ---------------------------------------
diff --git a/src/services/scm.ts b/src/services/scm.ts
index 771d793b51f..2aeb5dd12aa 100644
--- a/src/services/scm.ts
+++ b/src/services/scm.ts
@@ -9,6 +9,8 @@ class ScmService {
getIdentity = async (provider: 'github') => lambdaClient.scm.getIdentity.query({ provider });
+ hasWakeTarget = async (topicId: string) => lambdaClient.scm.hasWakeTarget.query({ topicId });
+
listChangeRequests = async (params?: { limit?: number }) =>
lambdaClient.scm.listChangeRequests.query(params);
diff --git a/src/store/chat/slices/topic/action.ts b/src/store/chat/slices/topic/action.ts
index 7fca269bd73..8d94f9bdcc6 100644
--- a/src/store/chat/slices/topic/action.ts
+++ b/src/store/chat/slices/topic/action.ts
@@ -29,7 +29,6 @@ import {
recordLens,
type ReplicaPageResult,
type ReplicaSyncResult,
- singleEntity,
} from '@/libs/replica';
import { mutate, useClientDataSWRWithSync } from '@/libs/swr';
import { cronKeys, deviceKeys, topicKeys } from '@/libs/swr/keys';
@@ -75,12 +74,12 @@ import {
normalizeTopicListParams,
type TopicAgentViewParams,
topicAgentViewResource,
- topicDetailResource,
type TopicListParams,
topicListResource,
} from './projection';
import { type ChatTopicDispatch } from './reducer';
import { topicSelectors } from './selectors';
+import { createTopicDetailSlice, RUN_WATCH_INTERVAL } from './topicDetail';
const n = setNamespace('t');
@@ -267,16 +266,14 @@ export class ChatTopicActionImpl {
view: recordLens<ChatStore, TopicData>('agentTopicsViewMap'),
viewFields: ({ withDetails }) => ({ withDetails }),
});
- this.#topicDetail = createReplicaSlice(topicDetailResource, {
- actionPrefix: n('topicDetail'),
- entity: singleEntity<ChatTopic>((topic) => topic.id),
- fetcher: (topicId) => topicService.getTopicDetail(topicId),
+ this.#topicDetail = createTopicDetailSlice({
get,
- // A missing topic keeps whatever is cached (the list may still hold it).
- merge: (topic, confirmed) => (!topic || isEqual(topic, confirmed) ? undefined : topic),
+ onRunningOperation: (fresh) =>
+ this.#topicEntity.update(fresh.id, (topic) => ({
+ ...topic,
+ metadata: { ...topic.metadata, runningOperation: fresh.metadata!.runningOperation },
+ })),
set,
- stateKey: 'topicDetailReplica',
- view: recordLens<ChatStore, ChatTopic>('topicDetailMap'),
});
this.#topicEntity = linkReplicaEntity<ChatTopic>([
this.#topicList,
@@ -1455,16 +1452,15 @@ export class ChatTopicActionImpl {
return this.#topicList.hydrate(normalized, scope);
};
- /**
- * By-id topic detail fetch, used as a fallback when a topic the UI is
- * anchored on is missing from the loaded list bucket β€” e.g. an archived
- * (`completed`) topic that the sidebar fetch excludes via `excludeStatuses`,
- * or a topic deep-linked from the Topics management page. The result lands
- * in `topicDetailMap`, which `currentActiveTopic` / `getTopicById` read as
- * a fallback. Pass `undefined` to disable the fetch.
- */
- useFetchTopicDetail = (topicId?: string | null): ReplicaSyncResult =>
- this.#topicDetail.useSync(topicId || null);
+ /** By-id details and background run discovery. An absent id disables the read. */
+ useFetchTopicDetail = (topicId?: string | null, watchRuns = false): ReplicaSyncResult =>
+ this.#topicDetail.useSync(topicId || null, {
+ dedupingInterval: 1000,
+ focusThrottleInterval: 5000,
+ refreshInterval: watchRuns ? RUN_WATCH_INTERVAL : 0,
+ refreshWhenHidden: false,
+ refreshWhenOffline: false,
+ });
/**
* Topic fetch dedicated to the Agent Topics management page. Its own
diff --git a/src/store/chat/slices/topic/topicDetail.ts b/src/store/chat/slices/topic/topicDetail.ts
new file mode 100644
index 00000000000..a9aa3da548a
--- /dev/null
+++ b/src/store/chat/slices/topic/topicDetail.ts
@@ -0,0 +1,80 @@
+import isEqual from 'fast-deep-equal';
+
+import { createReplicaSlice, recordLens, singleEntity } from '@/libs/replica';
+import { topicService } from '@/services/topic';
+import type { ChatStore } from '@/store/chat';
+import type { StoreSetter } from '@/store/types';
+import type { ChatTopic } from '@/types/topic';
+import { setNamespace } from '@/utils/storeDebug';
+
+import { INPUT_LOADING_OPERATION_TYPES } from '../operation/types';
+import { topicDetailResource } from './projection';
+import { topicSelectors } from './selectors';
+
+const topicOperations = (state: ChatStore, topicId: string) =>
+ Object.values(state.operations).filter(
+ (op) => op.context.topicId === topicId && INPUT_LOADING_OPERATION_TYPES.includes(op.type),
+ );
+
+/** Background run discovery cadence; armed only while SCM can wake the topic. */
+export const RUN_WATCH_INTERVAL = 15_000;
+
+/** Include terminal bookkeeping: its stream still owns the conversation. */
+export const hasLocalTopicRun = (state: ChatStore, topicId: string) =>
+ topicOperations(state, topicId).some((op) => op.status === 'running');
+
+/** Topic details also discover runs started by SCM, schedules, or another client. */
+export const createTopicDetailSlice = ({
+ get,
+ set,
+ onRunningOperation,
+}: {
+ get: () => ChatStore;
+ onRunningOperation: (topic: ChatTopic) => void;
+ set: StoreSetter<ChatStore>;
+}) => {
+ const snapshots = new WeakMap<ChatTopic, { operationIds: string; topic?: ChatTopic }>();
+ const operationIds = (topicId: string) =>
+ topicOperations(get(), topicId)
+ .map((op) => op.id)
+ .join(',');
+
+ return createReplicaSlice(topicDetailResource, {
+ actionPrefix: setNamespace('t')('topicDetail'),
+ effects: {
+ onApplied: (topic) => {
+ if (topic?.metadata?.runningOperation && !hasLocalTopicRun(get(), topic.id)) {
+ onRunningOperation(topic);
+ }
+ },
+ },
+ entity: singleEntity<ChatTopic>((topic) => topic.id),
+ fetcher: async (topicId) => {
+ const snapshot = {
+ operationIds: operationIds(topicId),
+ topic: topicSelectors.getTopicById(topicId)(get()),
+ };
+ const topic = await topicService.getTopicDetail(topicId);
+ if (topic) snapshots.set(topic, snapshot);
+ return topic;
+ },
+ get,
+ // Keep cached details when a topic is missing, as before.
+ merge: (topic, confirmed) => (!topic || isEqual(topic, confirmed) ? undefined : topic),
+ prepareHead: (topic, _current, topicId) => {
+ const snapshot = topic && snapshots.get(topic);
+ // A local send, stop, or topic edit may overtake this read. Do not install
+ // an older marker over it, even if that local run has already finished.
+ if (
+ snapshot &&
+ (snapshot.topic !== topicSelectors.getTopicById(topicId)(get()) ||
+ snapshot.operationIds !== operationIds(topicId))
+ )
+ return undefined;
+ return topic;
+ },
+ set,
+ stateKey: 'topicDetailReplica',
+ view: recordLens<ChatStore, ChatTopic>('topicDetailMap'),
+ });
+};