π€― 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
π fix(topic): retire a topic row whose run leaked its terminal frame (#20634)
Arvin Xu4283e41db976
diff --git a/src/features/AgentSidebar/Topic/index.tsx b/src/features/AgentSidebar/Topic/index.tsxindex ebb99c8a5dc..def2eb4dcd3 100644--- a/src/features/AgentSidebar/Topic/index.tsx+++ b/src/features/AgentSidebar/Topic/index.tsx@@ -10,14 +10,15 @@ import {Spin,Text,} from '@lobehub/ui/base-ui';+import { useDocumentVisibility } from 'ahooks';import { cx } from 'antd-style';-import React, { memo, Suspense, useEffect, useRef } from 'react';+import React, { memo, Suspense, useEffect } from 'react';import { useTranslation } from 'react-i18next';import SkeletonList from '@/features/NavPanel/components/SkeletonList';import { useFetchChatTopics } from '@/hooks/useFetchChatTopics';import { useChatStore } from '@/store/chat';-import { topicSelectors } from '@/store/chat/selectors';+import { operationSelectors, topicSelectors } from '@/store/chat/selectors';import Actions from './Actions';import Filter from './Filter';@@ -25,6 +26,21 @@ import List from './List';import ToggleGroups from './ToggleGroups';import { useTopicActionsDropdownMenu } from './useDropdownMenu';+/**+ * Cadence of the candidate-gated stale-run sweep. A run whose terminal frame+ * never landed leaves this tab holding a `running` op, so the topic row spins+ * and counts over a finished topic; this is how long that may last before the+ * row is retired. Only armed while `hasVisiblyRunningTopic` is true.+ */+const STALE_RUNNING_TOPIC_SWEEP_INTERVAL = 15_000;++/**+ * Ceiling the cadence backs off to while a sweep keeps retiring nothing β i.e.+ * while the run it is looking at is genuinely alive. An ordinary long run must+ * not be polled at the leak-hunting cadence for its whole duration.+ */+const STALE_RUNNING_TOPIC_SWEEP_MAX_INTERVAL = 120_000;+interface TopicProps {expanded: boolean;itemKey: string;@@ -34,17 +50,69 @@ const Topic = memo<TopicProps>(({ expanded, itemKey }) => {const { t } = useTranslation(['topic', 'common']);const topicCount = useChatStore((s) => topicSelectors.currentTopicCount(s));const cleanupStaleRunningTopics = useChatStore((s) => s.cleanupStaleRunningTopics);+ const settleAllUnbackedTopicRuns = useChatStore((s) => s.settleAllUnbackedTopicRuns);+ const hasVisiblyRunningTopic = useChatStore(operationSelectors.hasVisiblyRunningTopic);+ // A hidden tab has nothing to repaint, so polling the server for it would buy+ // nothing β and the sweep re-runs on the next visibility change anyway.+ const documentVisibility = useDocumentVisibility();const dropdownMenu = useTopicActionsDropdownMenu();const { isRevalidating } = useFetchChatTopics();- const hasRunWatchdogRef = useRef(false);+ // Sweep on EVERY expand, not once per session. A latched watchdog missed every+ // run that leaked its terminal frame after it had already fired, and such a row+ // then spun and counted over a finished topic until a full reload.useEffect(() => {- if (!expanded || hasRunWatchdogRef.current) return;+ if (!expanded) return;- hasRunWatchdogRef.current = true;void cleanupStaleRunningTopics();}, [cleanupStaleRunningTopics, expanded]);+ // Keep retiring whatever the server no longer backs for as long as a row still+ // reports itself running. The sweep returns before any server read when there+ // is no candidate, so this only runs while a row is stuck β or genuinely+ // mid-run. Serialized (never two sweeps in flight), paused while the document+ // is hidden, and backed off while a sweep retires nothing, so an ordinary long+ // run is not polled at the leak-hunting cadence.+ useEffect(() => {+ if (!expanded || documentVisibility === 'hidden' || !hasVisiblyRunningTopic) return;++ let cancelled = false;+ let inFlight = false;+ let delay = STALE_RUNNING_TOPIC_SWEEP_INTERVAL;+ let timer: ReturnType<typeof setTimeout> | undefined;++ const schedule = () => {+ timer = setTimeout(sweep, delay);+ };++ const sweep = async () => {+ if (cancelled || inFlight) return;++ inFlight = true;+ try {+ const settled = await settleAllUnbackedTopicRuns();+ // Retiring nothing means the run is alive: back off rather than keep+ // paying the per-topic detail read. Any settlement resets the cadence.+ delay =+ settled > 0+ ? STALE_RUNNING_TOPIC_SWEEP_INTERVAL+ : Math.min(delay * 2, STALE_RUNNING_TOPIC_SWEEP_MAX_INTERVAL);+ } catch (error) {+ console.error('[Topic] unbacked run sweep failed:', error);+ } finally {+ inFlight = false;+ if (!cancelled) schedule();+ }+ };++ void sweep();++ return () => {+ cancelled = true;+ if (timer) clearTimeout(timer);+ };+ }, [documentVisibility, expanded, hasVisiblyRunningTopic, settleAllUnbackedTopicRuns]);+return (<AccordionItem value={itemKey}><ContextMenuTrigger items={dropdownMenu}>diff --git a/src/services/aiAgent.ts b/src/services/aiAgent.tsindex 9947b4edb8f..8b5b8f142df 100644--- a/src/services/aiAgent.ts+++ b/src/services/aiAgent.ts@@ -343,6 +343,22 @@ class AiAgentService {return await lambdaClient.aiAgent.getSubAgentTaskStatus.query(params);}+ /**+ * Authoritative terminal outcome of a server run, by its operation id.+ *+ * The leaked-run sweep needs it to tell a run that COMPLETED from one that+ * failed / was interrupted: only a completion may drain the follow-up the user+ * queued behind it (a failed run keeps its queue, like every terminal path).+ * The terminal frame that would have carried this outcome is exactly what the+ * leak lost.+ *+ * Resolves `null` when the server no longer holds the run (its state expired).+ * Callers must treat that as UNKNOWN, never as a completion.+ */+ async getOperationStatus(params: { operationId: string }) {+ return await lambdaClient.aiAgent.getOperationStatus.query(params);+ }+/*** Interrupt a running task*/diff --git a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.tsindex d13c9f6aac2..03bec391649 100644--- a/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts+++ b/src/store/chat/slices/agentRun/actions/transports/gateway/gateway.ts@@ -56,9 +56,15 @@ import {} from '@/store/chat/pendingSandboxSelection';import { consumePendingTopicRepos, getPendingTopicRepos } from '@/store/chat/pendingTopicRepos';import { topicSelectors } from '@/store/chat/selectors';-import { INPUT_LOADING_OPERATION_TYPES } from '@/store/chat/slices/operation/types';+import { operationSelectors } from '@/store/chat/slices/operation/selectors';+import {+ SETTLEABLE_TOPIC_RUN_OPERATION_TYPES,+ TOPIC_VISIBLY_RUNNING_OPERATION_TYPES,+} from '@/store/chat/slices/operation/types';import type { ChatStore } from '@/store/chat/store';+import { isInterventionRunActive } from '@/store/chat/utils/interventionSync';import { messageMapKey } from '@/store/chat/utils/messageMapKey';+import type { TopicMapScope } from '@/store/chat/utils/topicMapKey';import { topicMapKey } from '@/store/chat/utils/topicMapKey';import { getElectronStoreState } from '@/store/electron';import { getFileStoreState } from '@/store/file/store';@@ -74,6 +80,7 @@ import { isTrpcErrorCode } from '@/utils/trpcError';import { resolveNewThreadIntent } from '../../dispatch/newThreadIntent';import { buildRunLifecycle } from '../../lifecycle/buildRunLifecycle';+import { scheduleQueuedFollowUp } from '../../lifecycle/queuedFollowUp';import type { RunScope } from '../../lifecycle/types';import { createGatewayEventBuffer } from './gatewayEventBuffer';import { createGatewayEventHandler, isCompletedRuntimeEnd } from './gatewayEventHandler';@@ -2339,6 +2346,255 @@ export class GatewayActionImpl {this.clearLocalRunningOperation({ ...params, status: 'active' });};+ /**+ * Retire the local topic-run ops whose run the server no longer considers live.+ *+ * A gateway op normally settles on its terminal frame, but that frame can be+ * lost: the socket resubscribes mid-run, the op's DO event buffer hibernates+ * away, or β the case this exists for β an intervention continuation is+ * dispatched out-of-band on a NEW operation whose stream delivers neither a+ * terminal nor a disconnect, so the terminal-missing fallback never fires. The+ * run is over on the server either way, and the leaked op is exactly what the+ * topic row reads: `isTopicVisiblyRunning` drives the sidebar spinner and+ * `getVisibleAgentRuntimeStartTimeByContext` its elapsed clock, so the row+ * keeps spinning and counting over a finished topic. `cleanupStaleRunningTopics`+ * cannot help on its own: the topic is idle on the server, so it never shows up+ * in that watchdog's `statuses: ['running']` query.+ *+ * Liveness is read from the SERVER, never guessed from a local timer: the row+ * must report no live run at all (`isInterventionRunActive` β no+ * `runningOperation`, no task reservation, and a status outside+ * running / waitingForHuman). A local run op still running on such a topic is+ * unbacked by definition.+ */+ settleUnbackedTopicRuns = async (params: {+ agentId?: string;+ groupId?: string;+ scope?: TopicMapScope;+ topicId: string;+ }): Promise<number> => {+ const { topicId } = params;+ if (!topicId) return 0;++ // Cheap local pre-check first: without a candidate there is nothing to+ // settle, and no reason to pay for a server read.+ const candidates = this.#getSettleableLocalRuntimeOps(topicId);+ if (candidates.length === 0) return 0;++ // A missing / unreadable row is not evidence the run ended β leave the ops+ // alone rather than settling them on an absent answer.+ const topic = await topicService.getTopicDetail(topicId).catch(() => undefined);+ if (!topic || isInterventionRunActive(topic)) return 0;++ // Mirror the SERVER's authoritative terminal status instead of stamping+ // `active` over it: a run that finished while the user was away settles the+ // row to `unread`, and overwriting that would suppress the completion badge+ // they come back for (or clobber `completed` / `failed`). Only a topic the+ // user is actually looking at gets the `active` pin β the same split the+ // terminal-frame path makes+ // (`viewing || !effectiveSucceeded ? 'active' : undefined`).+ const viewing = this.#get().activeTopicId === topicId;+ const terminalStatus: ChatTopicStatus = viewing ? 'active' : (topic.status ?? 'active');++ let settled = 0;+ const drainedContextKeys = new Set<string>();+ for (const op of candidates) {+ // A terminal frame may have landed while the read was in flight.+ if (this.#get().operations[op.id]?.status !== 'running') continue;++ // The transport AND the server marker are keyed by the SERVER operation id,+ // not by this tab's local Zustand op id β `connectToGateway` stores under+ // `result.operationId`. Looking the connection up by the local id (as the+ // first cut did) silently tore nothing down.+ // `#isLiveLocalRuntimeOp` already guarantees the marker is present.+ const serverOperationId = op.metadata.serverOperationId;+ if (!serverOperationId) continue;++ // Complete the op itself first: it is what every "a run is in flight"+ // surface reads (sidebar spinner, elapsed clock, stop button). Doing it+ // before the teardown below also makes the `disconnected` that teardown+ // provokes a no-op.+ this.#get().completeOperation(op.id);++ // Then tear the transport down exactly like `reconcileSilentEnd` does.+ // `internal_cleanupGatewayConnection` only drops store state, so without+ // the `disconnect()` the discarded handle keeps a v1 reconnect timer+ // opening sockets and a mux operation subscribed for a run nobody will+ // ever read. (The transcript's canonical final state is NOT this sweep's+ // job β it belongs to the conversation's own fetch/settle path, which has+ // the session closure to synthesize a `notify_update` from.)+ this.#get().gatewayConnections[serverOperationId]?.client?.disconnect();+ this.internal_cleanupGatewayConnection(serverOperationId);++ this.clearLocalRunningOperation({+ agentId: params.agentId,+ groupId: params.groupId,+ operationId: serverOperationId,+ scope: params.scope,+ status: terminalStatus,+ topicId,+ });+ settled++;++ // Retiring the op is only half of what a lost terminal frame skipped: if a+ // follow-up was queued behind the run, the same missing frame also skipped+ // the queue drain. Close that gap on the queue-aware path.+ await this.#drainQueuedFollowUpForSettledRun(op, drainedContextKeys);+ }++ return settled;+ };++ /**+ * Drain the follow-up a user queued behind a leaked run the server COMPLETED.+ *+ * `buildRunLifecycle.completeRun` (on success) and+ * `serverOperationReconciliation` (repairing a completed snapshot) both reach+ * `scheduleQueuedFollowUp`, but a run whose terminal frame never landed+ * reaches neither β the sweep retires the leaked op instead, and the queued+ * message would stay stranded. This routes the sweep's retirement through the+ * same queue-aware drain.+ *+ * Two gates keep it honest:+ *+ * 1. It needs a queued follow-up to rescue. That gate is checked FIRST, so the+ * common no-queue retirement pays neither the server read nor the drain.+ * 2. Only a run the server recorded as COMPLETED drains. A failed / cancelled+ * run preserves its queue, exactly like the terminal paths. The outcome is+ * read from the server because the terminal frame β the only local carrier+ * of it β is what leaked; an unreadable / expired outcome counts as NOT+ * completed, so a queued follow-up is never auto-sent on an outcome we+ * cannot confirm.+ */+ #drainQueuedFollowUpForSettledRun = async (+ op: ChatStore['operations'][string],+ drainedContextKeys: Set<string>,+ ): Promise<void> => {+ if (!op.context.agentId) return;++ const context = op.context as ConversationContext;+ const contextKey = messageMapKey(context);++ // Nothing queued behind this run β nothing to rescue, and no reason to pay+ // for the server read below.+ if (drainedContextKeys.has(contextKey)) return;+ if (!this.#get().queuedMessages?.[contextKey]?.length) return;++ // A newer turn in this context already owns the queue (the user sent it, or+ // another run started) β leave the drain to it. Same guard the shared+ // `scheduleQueuedFollowUp` applies on its send.+ if (operationSelectors.hasNewerConversationOperation(op.id, context)(this.#get())) return;++ const serverOperationId = op.metadata.serverOperationId;+ if (!serverOperationId) return;++ const outcome = await aiAgentService+ .getOperationStatus({ operationId: serverOperationId })+ .catch(() => null);+ if (outcome?.isCompleted !== true) return;++ drainedContextKeys.add(contextKey);+ scheduleQueuedFollowUp(this.#get, context, op.id);+ };++ /**+ * {@link settleUnbackedTopicRuns} across every topic this tab still holds a+ * visibly-running op for.+ *+ * Backs the sidebar's stale-run sweep, where the topic ids come from the local+ * op map instead of a server query: a topic the server already retired is idle,+ * so it never appears in the `statuses: ['running']` query that drives+ * `cleanupStaleRunningTopics`. Costs nothing without a candidate, so it is safe+ * to call opportunistically (e.g. on a sidebar interval).+ */+ settleAllUnbackedTopicRuns = async (): Promise<number> => {+ // Dedupe by the FULL scope, not by topicId alone. A leaked run's row lives in+ // its own agent/group bucket, and `clearLocalRunningOperation` resolves that+ // bucket from the params it is handed β so dropping the scope here made the+ // sweep clear whichever agent happened to be active instead of the one the+ // run came from, completing the op but leaving the real row spinning.+ const candidates = new Map<+ string,+ { agentId?: string; groupId?: string; scope?: TopicMapScope; topicId: string }+ >();+ for (const op of Object.values(this.#get().operations)) {+ if (!this.#isLiveLocalRuntimeOp(op)) continue;++ const { agentId, groupId, topicId } = op.context;+ if (!topicId) continue;++ // Group MAIN topics are keyed `group_${groupId}` even though the op also+ // carries the supervisor's agentId; leaving both would derive+ // `group_agent_${groupId}_${agentId}` and never find the row. Mirrors the+ // patch scope `cleanupStaleRunningTopics` uses and the optimistic-topic+ // scope in conversationLifecycle.+ const scope: TopicMapScope | undefined =+ op.context.scope === 'group' && groupId ? 'group' : undefined;++ const key = `${agentId ?? ''}|${groupId ?? ''}|${scope ?? ''}|${topicId}`;+ if (!candidates.has(key)) candidates.set(key, { agentId, groupId, scope, topicId });+ }+ if (candidates.size === 0) return 0;++ const settled = await Promise.all(+ [...candidates.values()].map((candidate) => this.settleUnbackedTopicRuns(candidate)),+ );++ return settled.reduce((sum, count) => sum + count, 0);+ };++ /**+ * Live topic-run ops this tab still holds for `topicId`, filtered to the ones+ * old enough to settle.+ *+ * `LOCAL_RUN_SETTLE_MIN_AGE_MS` covers the dispatch window where this tab's op+ * already exists but the server's own `runningOperation` / `running` status has+ * not been read back yet β without it a just-started run could be retired+ * against a stale read.+ */+ #getSettleableLocalRuntimeOps = (topicId: string) => {+ const now = Date.now();++ return Object.values(this.#get().operations).filter(+ (op) =>+ this.#isLiveLocalRuntimeOp(op) &&+ op.context.topicId === topicId &&+ typeof op.metadata.startTime === 'number' &&+ now - op.metadata.startTime >= LOCAL_RUN_SETTLE_MIN_AGE_MS,+ );+ };++ /**+ * Whether `op` is one the topic row reports as running AND the sweep is+ * allowed to retire. Three independent requirements, each closing a distinct+ * way of killing a live turn:+ *+ * 1. Its type must be one the row reads ({@link+ * SETTLEABLE_TOPIC_RUN_OPERATION_TYPES}). Anything narrower leaks β an op+ * that pins the row but sits outside the filter can never be retired, so+ * the row spins until a reload.+ * 2. It must be server-owned (`metadata.serverOperationId`). The sweep's claim+ * is "the server no longer backs this run", which is only meaningful for a+ * run the server ever owned. A local-only op owns its whole lifetime in+ * this tab, and completing it is destructive: the client-mode+ * `submitToolInteraction` / `skipToolInteraction` pre-dispatch phase+ * deliberately writes the topic back to `active` BEFORE awaiting its+ * optimistic writes, so an already-`active` server row is expected there+ * and says nothing about the run β and `#wasInterimOpStopped` then reads the+ * completed op as a user Stop, returning without ever starting the+ * continuation. `autoRetryPending` is the same shape (see+ * LOCAL_ONLY_TOPIC_RUN_OPERATION_TYPES).+ * 3. It must not already be on its way out (`isAborting`).+ *+ * The leaked op this exists for is a gateway `execServerAgentRuntime`, which+ * does carry `serverOperationId` β so requirement 2 costs nothing there.+ */+ #isLiveLocalRuntimeOp = (op: ChatStore['operations'][string]): boolean =>+ SETTLEABLE_TOPIC_RUN_OPERATION_TYPES.includes(op.type) &&+ op.status === 'running' &&+ !op.metadata.isAborting &&+ !!op.metadata.serverOperationId;+/*** Whether this tab has a live turn on `topicId` that belongs to a run other* than `serverOperationId` β e.g. a follow-up (or queued message) already sent@@ -2357,7 +2613,7 @@ export class GatewayActionImpl {return false;};- return INPUT_LOADING_OPERATION_TYPES.some((type) =>+ return TOPIC_VISIBLY_RUNNING_OPERATION_TYPES.some((type) =>(operationsByType?.[type] ?? []).some((id) => {const op = operations?.[id];return (@@ -2416,6 +2672,12 @@ export class GatewayActionImpl {agentId?: string;groupId?: string;operationId: string;+ /**+ * Explicit bucket scope. Group MAIN topic rows are keyed `group_${groupId}`+ * while the op also carries the supervisor's agentId, so the auto-detected+ * `group_agent` bucket would miss them.+ */+ scope?: TopicMapScope;/*** Mirror the topic's terminal status into the local Zustand copy alongside* the metadata clear. Omit for the "clean completion, not watching" case β@@ -2424,11 +2686,12 @@ export class GatewayActionImpl {status?: ChatTopicStatus;topicId: string;}): boolean => {- const { topicId, operationId, agentId, groupId, status } = params;+ const { topicId, operationId, agentId, groupId, scope, status } = params;const state = this.#get();const key = topicMapKey({agentId: agentId ?? state.activeAgentId,groupId: groupId ?? state.activeGroupId,+ scope,});const existingTopic = state.topicDataMap[key]?.items?.find((t) => t.id === topicId);if (!existingTopic) return false;@@ -2451,6 +2714,7 @@ export class GatewayActionImpl {agentId,groupId,id: topicId,+ scope,type: 'updateTopic',value: { metadata: { ...existingTopic.metadata, runningOperation: null } },});@@ -2462,7 +2726,7 @@ export class GatewayActionImpl {// run start) reconciles to this status instead of reapplying the stale// 'running' one and stranding the spinner again.if (!status) return false;- state.internal_pinTopicStatus?.({ agentId, groupId, status, topicId });+ state.internal_pinTopicStatus?.({ agentId, groupId, scope, status, topicId });return !markerOperationId;};@@ -2481,6 +2745,13 @@ export class GatewayActionImpl {export type GatewayAction = Pick<GatewayActionImpl, keyof GatewayActionImpl>;+/**+ * Grace period before an unbacked local run op may be retired. Covers the+ * dispatch window where this tab's op exists but the server has not yet+ * published its own `runningOperation` / `running` status.+ */+const LOCAL_RUN_SETTLE_MIN_AGE_MS = 30_000;+const GATEWAY_CONNECT_WAIT_MS = 5000;/** Resolve once the connection reads `connected`, or after a bounded wait. */diff --git a/src/store/chat/slices/operation/selectors.ts b/src/store/chat/slices/operation/selectors.tsindex f4592b7f5b3..628c096fe41 100644--- a/src/store/chat/slices/operation/selectors.ts+++ b/src/store/chat/slices/operation/selectors.ts@@ -9,6 +9,7 @@ import {isQueueBlockingOperation,QUEUE_BLOCKING_OPERATION_TYPES,SEND_NOW_CANCEL_REASON,+ TOPIC_VISIBLY_RUNNING_OPERATION_TYPES,} from './types';// === Basic Queries ===@@ -491,18 +492,21 @@ const isAgentVisiblyRunning =/*** Whether a turn is visibly in progress for a topic on THIS client β the whole- * send β run pipeline (see INPUT_LOADING_OPERATION_TYPES), matched by the- * operation context's topicId regardless of agent/group/thread.+ * send β run pipeline (see TOPIC_VISIBLY_RUNNING_OPERATION_TYPES), matched by+ * the operation context's topicId regardless of agent/group/thread.** Drives the sidebar topic spinner. Persisted `topic.status === 'running'`* covers runs owned by other clients / the server; this covers what status* cannot: client-mode runs (which never persist a status) and the startup* window of gateway/hetero runs before the server writes `running`.+ *+ * Whatever this reports as running must also be retirable by+ * `settleAllUnbackedTopicRuns` β see TOPIC_VISIBLY_RUNNING_OPERATION_TYPES.*/const isTopicVisiblyRunning =(topicId: string) =>(s: ChatStoreState): boolean => {- for (const type of INPUT_LOADING_OPERATION_TYPES) {+ for (const type of TOPIC_VISIBLY_RUNNING_OPERATION_TYPES) {const operationIds = s.operationsByType[type] || [];const hasRunning = operationIds.some((id) => {const op = s.operations[id];@@ -521,7 +525,7 @@ const isTopicVisiblyRunning =*/const visiblyRunningTopicIds = (s: ChatStoreState): Set<string> => {const ids = new Set<string>();- for (const type of INPUT_LOADING_OPERATION_TYPES) {+ for (const type of TOPIC_VISIBLY_RUNNING_OPERATION_TYPES) {for (const id of s.operationsByType[type] || []) {const op = s.operations[id];if (op && isVisiblyRunningOperation(op) && op.context.topicId) {@@ -532,6 +536,21 @@ const visiblyRunningTopicIds = (s: ChatStoreState): Set<string> => {return ids;};+/**+ * Whether ANY topic row is visibly running on this client. Backs the sidebar's+ * candidate gate for the stale-run sweep: without a candidate there is nothing+ * to retire, so the sweep must not poll the server at all.+ */+const hasVisiblyRunningTopic = (s: ChatStoreState): boolean => {+ for (const type of TOPIC_VISIBLY_RUNNING_OPERATION_TYPES) {+ for (const id of s.operationsByType[type] || []) {+ const op = s.operations[id];+ if (op && isVisiblyRunningOperation(op) && op.context.topicId) return true;+ }+ }+ return false;+};+/*** Check if agent runtime is running (including both main window and thread)* Checks all AI runtime operation types (see AI_RUNTIME_OPERATION_TYPES)@@ -1019,6 +1038,7 @@ export const operationSelectors = {isQueueDrainPending,isSendingMessage,isSteerHandoffPending,+ hasVisiblyRunningTopic,isTopicUnreadCompleted,isTopicVisiblyRunning,unreadCompletedCountForTopics,diff --git a/src/store/chat/slices/operation/types.ts b/src/store/chat/slices/operation/types.tsindex 5b1b587dcbc..0d9b539be05 100644--- a/src/store/chat/slices/operation/types.ts+++ b/src/store/chat/slices/operation/types.ts@@ -500,6 +500,49 @@ export const INPUT_LOADING_OPERATION_TYPES: OperationType[] = [...INTERIM_LOADING_OPERATION_TYPES,];+/**+ * Operation types whose in-flight state pins a topic row's `running` ring and+ * elapsed clock β the set `operationSelectors.isTopicVisiblyRunning` /+ * `visiblyRunningTopicIds` read.+ *+ * The stale-run sweep must be able to retire a leaked op from this set (see+ * {@link SETTLEABLE_TOPIC_RUN_OPERATION_TYPES}): one that pins the row but sits+ * outside the sweeper's filter strands the row spinning and counting over a+ * finished topic until a full reload. That is exactly what an intervention+ * continuation's interim op (`approveToolCalling` / `submitToolInteraction` /+ * `skipToolInteraction`) did while the sweeps only looked at+ * {@link AI_RUNTIME_OPERATION_TYPES}.+ */+export const TOPIC_VISIBLY_RUNNING_OPERATION_TYPES: OperationType[] = INPUT_LOADING_OPERATION_TYPES;++/**+ * Row-pinning operations that deliberately live WITHOUT a server-side run, so+ * the stale-run sweep must never retire them.+ *+ * `autoRetryPending` is the entire reason this list exists. It is held for the+ * heterogeneous overload backoff (`HETERO_OVERLOAD_BACKOFF_SECONDS` reaches 30s+ * Β± 20% jitter) precisely so the turn keeps its busy state across the wait. The+ * sweep's own settle age is 30s, so without this exclusion it would retire the+ * wait op mid-countdown β and `isHeteroOverloadWaitAborted` reads a non-running+ * op as "the user cancelled", which would silently exhaust the retry sequence.+ */+export const LOCAL_ONLY_TOPIC_RUN_OPERATION_TYPES: OperationType[] = ['autoRetryPending'];++/**+ * {@link TOPIC_VISIBLY_RUNNING_OPERATION_TYPES} minus the+ * {@link LOCAL_ONLY_TOPIC_RUN_OPERATION_TYPES}: the operations+ * `ChatAgentRunGatewayAction.settleAllUnbackedTopicRuns` may retire once the+ * server reports no live run.+ *+ * Anything that can pin the row and IS server-backed has to be in here, or it+ * leaks a permanently-spinning row. Anything local-only has to stay out, or the+ * sweep kills the wait it is holding.+ */+export const SETTLEABLE_TOPIC_RUN_OPERATION_TYPES: OperationType[] =+ TOPIC_VISIBLY_RUNNING_OPERATION_TYPES.filter(+ (type) => !LOCAL_ONLY_TOPIC_RUN_OPERATION_TYPES.includes(type),+ );+/*** Operation types that block a fresh `sendMessage`: a send fired while one of* these runs enqueues behind it instead of starting a concurrent run.diff --git a/src/store/chat/slices/topic/action.test.ts b/src/store/chat/slices/topic/action.test.tsindex 2b11855a429..5f4cdce4d7e 100644--- a/src/store/chat/slices/topic/action.test.ts+++ b/src/store/chat/slices/topic/action.test.ts@@ -10,6 +10,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import { LOADING_FLAT } from '@/const/message';import { cacheScope, REPLICA_INDEX_KEY, replicaKeys } from '@/libs/replica';import { mutate } from '@/libs/swr';+import { aiAgentService } from '@/services/aiAgent';import { aiChatService } from '@/services/aiChat';import { chatService } from '@/services/chat';import { messageService } from '@/services/message';@@ -17,6 +18,9 @@ import { topicService } from '@/services/topic';import { useAgentStore } from '@/store/agent';import { useAiInfraStore } from '@/store/aiInfra';import { aiModelSelectors } from '@/store/aiInfra/slices/aiModel/selectors';+import { operationSelectors } from '@/store/chat/slices/operation/selectors';+import type { TOPIC_VISIBLY_RUNNING_OPERATION_TYPES } from '@/store/chat/slices/operation/types';+import { SETTLEABLE_TOPIC_RUN_OPERATION_TYPES } from '@/store/chat/slices/operation/types';import { PortalViewType } from '@/store/chat/slices/portal/initialState';import { messageMapKey } from '@/store/chat/utils/messageMapKey';import { topicMapKey } from '@/store/chat/utils/topicMapKey';@@ -99,6 +103,7 @@ beforeEach(() => {activeGroupId: undefined,activeTopicId: undefined,agentTopicsViewMap: {},+ queuedMessages: {},searchTopics: [],topicDataMap: {},topicDetailMap: {},@@ -2939,6 +2944,478 @@ describe('topic action', () => {});});+ // A run whose terminal frame never landed (lost socket, hibernated DO buffer,+ // or an intervention continuation dispatched on a new operation) leaves this+ // tab holding a `running` op while the server has already retired the topic.+ // The row reads that op for BOTH its spinner and its elapsed clock, so it spins+ // and counts over a finished topic forever unless something retires the op.+ describe('settleAllUnbackedTopicRuns', () => {+ const agentId = 'leak-agent';+ const topicId = 'leak-topic';+ const serverOperationId = 'server-op-1';++ /**+ * The client's copy of the row as it looks after the leak: it still claims a+ * live run (`running` + a `runningOperation` marker) long after the server+ * has moved on. Returns the idle row the server would report for the same+ * topic, which is what the sweep must trust.+ */+ const seedLeakedRow = (+ localRow: Partial<{ metadata: unknown; status: string }> = {},+ rowAgentId = agentId,+ ) => {+ const key = topicMapKey({ agentId: rowAgentId });+ const localTopic = {+ agentId: rowAgentId,+ id: topicId,+ metadata: {+ runningOperation: { assistantMessageId: 'assistant-1', operationId: serverOperationId },+ },+ sessionId: rowAgentId,+ status: 'running',+ title: 'Leaked running topic',+ updatedAt: Date.now(),+ ...localRow,+ } as ChatTopic & { agentId: string };++ act(() => {+ useChatStore.setState({+ activeAgentId: rowAgentId,+ messageOperationMap: {},+ operations: {},+ operationsByContext: {},+ operationsByMessage: {},+ topicDataMap: {+ [key]: {+ currentPage: 0,+ hasMore: false,+ items: [localTopic],+ pageSize: 20,+ total: 1,+ },+ },+ });+ });++ return {+ key,+ // The server's answer: no runningOperation, status outside running /+ // waitingForHuman β i.e. the run is over.+ serverRow: {+ agentId: rowAgentId,+ id: topicId,+ metadata: {},+ sessionId: rowAgentId,+ status: 'active',+ title: 'Leaked running topic',+ updatedAt: Date.now(),+ } as unknown as ChatTopic,+ };+ };++ /** The leaked op itself: started, still `running`, old enough to settle. */+ const seedLeakedOp = (+ type: (typeof TOPIC_VISIBLY_RUNNING_OPERATION_TYPES)[number],+ {+ opAgentId = agentId,+ serverOwned = true,+ }: { opAgentId?: string; serverOwned?: boolean } = {},+ ) => {+ let operationId = '';+ act(() => {+ operationId = useChatStore.getState().startOperation({+ context: { agentId: opAgentId, topicId },+ metadata: serverOwned ? { serverOperationId } : {},+ type,+ }).operationId;+ });++ const operation = useChatStore.getState().operations[operationId];+ useChatStore.setState({+ operations: {+ ...useChatStore.getState().operations,+ [operationId]: {+ ...operation,+ // Past LOCAL_RUN_SETTLE_MIN_AGE_MS, so the dispatch window's guard+ // does not mask the leak.+ metadata: { ...operation.metadata, startTime: Date.now() - 60_000 },+ },+ },+ });++ return operationId;+ };++ // Parametrized over the exact set the sweep is allowed to retire, so a+ // server-backed type that can pin the row while sitting outside the sweep's+ // filter fails here instead of leaking a permanently-spinning row. The+ // interim types are the ones an intervention continuation leaves behind.+ it.each(SETTLEABLE_TOPIC_RUN_OPERATION_TYPES)(+ 'retires a leaked %s op once the server reports the run is over',+ async (type) => {+ const { key, serverRow } = seedLeakedRow();+ const operationId = seedLeakedOp(type);+ vi.spyOn(topicService, 'getTopicDetail').mockResolvedValue(serverRow);++ const settled = await useChatStore.getState().settleAllUnbackedTopicRuns();++ const state = useChatStore.getState();+ expect(settled).toBe(1);+ // The op no longer keeps the sidebar spinner and elapsed clock alive.+ expect(state.operations[operationId].status).toBe('completed');+ expect(operationSelectors.isTopicVisiblyRunning(topicId)(state)).toBe(false);+ // β¦and the row's own copy is retired with it, marker included.+ expect(state.topicDataMap[key].items[0]).toMatchObject({+ metadata: { runningOperation: null },+ status: 'active',+ });+ },+ );++ it('leaves a genuinely running op alone while the server reports a live run', async () => {+ const { key } = seedLeakedRow();+ const operationId = seedLeakedOp('submitToolInteraction');+ vi.spyOn(topicService, 'getTopicDetail').mockResolvedValue({+ ...useChatStore.getState().topicDataMap[key].items[0],+ } as ChatTopic);++ const settled = await useChatStore.getState().settleAllUnbackedTopicRuns();++ const state = useChatStore.getState();+ expect(settled).toBe(0);+ expect(state.operations[operationId].status).toBe('running');+ expect(operationSelectors.isTopicVisiblyRunning(topicId)(state)).toBe(true);+ expect(state.topicDataMap[key].items[0].status).toBe('running');+ });++ it('reads no server row at all when there is no local candidate', async () => {+ seedLeakedRow();+ const detail = vi.spyOn(topicService, 'getTopicDetail');++ const settled = await useChatStore.getState().settleAllUnbackedTopicRuns();++ expect(settled).toBe(0);+ expect(detail).not.toHaveBeenCalled();+ });++ // Client mode deliberately writes the topic back to `active` BEFORE awaiting+ // its optimistic plugin / content / user-message writes+ // (`conversationControl.ts`), so during that pre-dispatch phase an `active`+ // server row is the expected state while the interim op is still running β+ // and nothing has been dispatched, so there is no server operation to own it.+ // Retiring the op there makes `#wasInterimOpStopped` read it as a user Stop+ // and return without ever starting the continuation.+ it('leaves a live client-mode intervention alone while its own writes are pending', async () => {+ // Exactly what the client-mode path leaves on the row: no marker, `active`.+ seedLeakedRow({ metadata: {}, status: 'active' });+ const operationId = seedLeakedOp('submitToolInteraction', { serverOwned: false });+ vi.spyOn(topicService, 'getTopicDetail').mockResolvedValue({+ agentId,+ id: topicId,+ metadata: {},+ sessionId: agentId,+ status: 'active',+ updatedAt: Date.now(),+ } as unknown as ChatTopic);++ const settled = await useChatStore.getState().settleAllUnbackedTopicRuns();++ const state = useChatStore.getState();+ expect(settled).toBe(0);+ expect(state.operations[operationId].status).toBe('running');+ expect(operationSelectors.isTopicVisiblyRunning(topicId)(state)).toBe(true);+ });++ // The row a leaked run must be retired on lives in ITS agent/group bucket.+ // Resolving that bucket from the currently active agent instead completed the+ // op but left the real row spinning.+ it('retires the row of the scope the op came from, not the active one', async () => {+ const { key, serverRow } = seedLeakedRow();+ // The user has since switched to a different agent.+ act(() => {+ useChatStore.setState({ activeAgentId: 'agent-b' });+ });+ const operationId = seedLeakedOp('execServerAgentRuntime');+ vi.spyOn(topicService, 'getTopicDetail').mockResolvedValue(serverRow);++ const settled = await useChatStore.getState().settleAllUnbackedTopicRuns();++ expect(settled).toBe(1);+ expect(useChatStore.getState().operations[operationId].status).toBe('completed');+ // The row that was actually pinning itself must stop spinning.+ expect(useChatStore.getState().topicDataMap[key].items[0]).toMatchObject({+ metadata: { runningOperation: null },+ status: 'active',+ });+ });++ // Group MAIN topic rows live in `group_${groupId}` even though the run's op+ // also carries the supervisor's agentId. Deriving the bucket from that pair+ // alone lands in `group_agent_${groupId}_${agentId}` and never finds the row.+ it('retires a group-main row from its own bucket', async () => {+ const groupId = 'group-1';+ const key = topicMapKey({ groupId });++ act(() => {+ useChatStore.setState({+ activeAgentId: undefined,+ activeGroupId: undefined,+ messageOperationMap: {},+ operations: {},+ operationsByContext: {},+ operationsByMessage: {},+ topicDataMap: {+ [key]: {+ currentPage: 0,+ hasMore: false,+ items: [+ {+ agentId: 'supervisor-agent',+ groupId,+ id: topicId,+ metadata: {+ runningOperation: {+ assistantMessageId: 'assistant-1',+ operationId: serverOperationId,+ },+ },+ status: 'running',+ title: 'Leaked group topic',+ updatedAt: Date.now(),+ } as unknown as ChatTopic,+ ],+ pageSize: 20,+ total: 1,+ },+ },+ });+ });++ let operationId = '';+ act(() => {+ operationId = useChatStore.getState().startOperation({+ context: { agentId: 'supervisor-agent', groupId, scope: 'group', topicId },+ metadata: { serverOperationId },+ type: 'execServerAgentRuntime',+ }).operationId;+ });+ const operation = useChatStore.getState().operations[operationId];+ useChatStore.setState({+ operations: {+ ...useChatStore.getState().operations,+ [operationId]: {+ ...operation,+ metadata: { ...operation.metadata, startTime: Date.now() - 60_000 },+ },+ },+ });+ vi.spyOn(topicService, 'getTopicDetail').mockResolvedValue({+ agentId: 'supervisor-agent',+ groupId,+ id: topicId,+ metadata: {},+ status: 'active',+ updatedAt: Date.now(),+ } as unknown as ChatTopic);++ const settled = await useChatStore.getState().settleAllUnbackedTopicRuns();++ expect(settled).toBe(1);+ expect(useChatStore.getState().operations[operationId].status).toBe('completed');+ expect(useChatStore.getState().topicDataMap[key].items[0]).toMatchObject({+ metadata: { runningOperation: null },+ status: 'active',+ });+ });++ // A run that finished while the user was elsewhere settles the SERVER row to+ // `unread`. The sweep has to mirror that terminal status β stamping `active`+ // would hide the completion badge the user comes back for (and would clobber+ // `completed` / `failed` the same way).+ it("mirrors the server's terminal status instead of forcing active", async () => {+ const { key, serverRow } = seedLeakedRow();+ const operationId = seedLeakedOp('execServerAgentRuntime');+ vi.spyOn(topicService, 'getTopicDetail').mockResolvedValue({+ ...serverRow,+ status: 'unread',+ } as ChatTopic);++ const settled = await useChatStore.getState().settleAllUnbackedTopicRuns();++ expect(settled).toBe(1);+ expect(useChatStore.getState().operations[operationId].status).toBe('completed');+ expect(useChatStore.getState().topicDataMap[key].items[0]).toMatchObject({+ metadata: { runningOperation: null },+ status: 'unread',+ });+ });++ // The counter-case: an op that pins the row ON PURPOSE without a server-side+ // run. `autoRetryPending` is held across the heterogeneous overload countdown+ // β longest window 30s Β± 20% jitter, i.e. past the sweep's own 30s settle+ // age. Retiring it would make `isHeteroOverloadWaitAborted` read a+ // non-running op as "the user cancelled" and silently exhaust the retry+ // sequence, so it has to stay outside the settleable set.+ it('never retires an intentional local-only retry wait', async () => {+ const { key, serverRow } = seedLeakedRow();+ // Seeded as server-owned on purpose: the structural server-owned gate would+ // otherwise mask a regression in the policy list, and the policy list is the+ // thing this test pins.+ const operationId = seedLeakedOp('autoRetryPending', { serverOwned: true });+ vi.spyOn(topicService, 'getTopicDetail').mockResolvedValue(serverRow);++ const settled = await useChatStore.getState().settleAllUnbackedTopicRuns();++ const state = useChatStore.getState();+ expect(settled).toBe(0);+ expect(state.operations[operationId].status).toBe('running');+ expect(operationSelectors.isTopicVisiblyRunning(topicId)(state)).toBe(true);+ // Excluded from the candidate scan entirely, not merely spared by the+ // server's answer.+ expect(topicService.getTopicDetail).not.toHaveBeenCalled();+ expect(state.topicDataMap[key].items[0].status).toBe('running');+ });++ // The transport is keyed by the SERVER operation id, not by this tab's local+ // op id (`connectToGateway` stores under `result.operationId`). A teardown+ // that looked the connection up by the local id silently tore nothing down+ // and left a v1 reconnect timer / mux subscription alive for a finished run.+ it("tears the transport down under the server's operation id", async () => {+ const { serverRow } = seedLeakedRow();+ const operationId = seedLeakedOp('execServerAgentRuntime');+ const disconnect = vi.fn();+ useChatStore.setState({+ gatewayConnections: {+ ...useChatStore.getState().gatewayConnections,+ [serverOperationId]: { client: { disconnect } as never, status: 'connecting' },+ },+ });+ vi.spyOn(topicService, 'getTopicDetail').mockResolvedValue(serverRow);++ const settled = await useChatStore.getState().settleAllUnbackedTopicRuns();++ expect(settled).toBe(1);+ expect(useChatStore.getState().operations[operationId].status).toBe('completed');+ expect(disconnect).toHaveBeenCalledTimes(1);+ expect(useChatStore.getState().gatewayConnections[serverOperationId]).toBeUndefined();+ });++ // A lost terminal frame skips BOTH halves of a run's completion: retiring the+ // op AND draining the input queue (`buildRunLifecycle.completeRun` on success,+ // `reconcileServerOperation` on a completed snapshot). The sweep now closes+ // the second half too β but only for a run the server actually COMPLETED, on+ // the same queue-aware path those two use.+ it('drains a follow-up queued behind a leaked run the server completed', async () => {+ const { serverRow } = seedLeakedRow();+ const operationId = seedLeakedOp('execServerAgentRuntime');+ const contextKey = messageMapKey({ agentId, topicId });+ const readOutcome = vi+ .spyOn(aiAgentService, 'getOperationStatus')+ .mockResolvedValue({ isCompleted: true } as never);+ const sendMessage = vi+ .spyOn(useChatStore.getState(), 'sendMessage')+ .mockResolvedValue(undefined as never);+ vi.spyOn(topicService, 'getTopicDetail').mockResolvedValue(serverRow);+ act(() => {+ useChatStore.setState({+ queuedMessages: {+ [contextKey]: [+ { content: 'queued follow-up', createdAt: 1, id: 'q1', interruptMode: 'soft' },+ ],+ },+ });+ });++ const settled = await useChatStore.getState().settleAllUnbackedTopicRuns();++ expect(settled).toBe(1);+ expect(useChatStore.getState().operations[operationId].status).toBe('completed');+ // The outcome is read by the SERVER operation id, and only because a+ // follow-up actually needs rescuing.+ expect(readOutcome).toHaveBeenCalledWith({ operationId: serverOperationId });+ await waitFor(() => expect(sendMessage).toHaveBeenCalledTimes(1));+ expect(sendMessage).toHaveBeenCalledWith(+ expect.objectContaining({ message: 'queued follow-up' }),+ );+ expect(useChatStore.getState().queuedMessages[contextKey] ?? []).toEqual([]);+ });++ // The counter-case: a failed / cancelled run PRESERVES its queued follow-up+ // (every terminal path does), so the sweep must not auto-send it on an+ // outcome that is not a completion.+ it('keeps a follow-up queued behind a leaked run that did NOT complete', async () => {+ const { serverRow } = seedLeakedRow();+ const operationId = seedLeakedOp('execServerAgentRuntime');+ const contextKey = messageMapKey({ agentId, topicId });+ vi.spyOn(aiAgentService, 'getOperationStatus').mockResolvedValue({+ isCompleted: false,+ } as never);+ const sendMessage = vi+ .spyOn(useChatStore.getState(), 'sendMessage')+ .mockResolvedValue(undefined as never);+ vi.spyOn(topicService, 'getTopicDetail').mockResolvedValue(serverRow);+ act(() => {+ useChatStore.setState({+ queuedMessages: {+ [contextKey]: [+ { content: 'queued follow-up', createdAt: 1, id: 'q1', interruptMode: 'soft' },+ ],+ },+ });+ });++ const settled = await useChatStore.getState().settleAllUnbackedTopicRuns();++ expect(settled).toBe(1);+ expect(useChatStore.getState().operations[operationId].status).toBe('completed');+ await new Promise((resolve) => setTimeout(resolve, 150));+ expect(sendMessage).not.toHaveBeenCalled();+ expect(useChatStore.getState().queuedMessages[contextKey]).toHaveLength(1);+ });++ // Retiring a leaked op with an empty queue must not pay for the outcome read:+ // there is nothing to drain, so the sweep stays as cheap as it was.+ it('never reads the run outcome when nothing is queued behind it', async () => {+ const { serverRow } = seedLeakedRow();+ seedLeakedOp('execServerAgentRuntime');+ const readOutcome = vi.spyOn(aiAgentService, 'getOperationStatus');+ vi.spyOn(topicService, 'getTopicDetail').mockResolvedValue(serverRow);++ const settled = await useChatStore.getState().settleAllUnbackedTopicRuns();++ expect(settled).toBe(1);+ expect(readOutcome).not.toHaveBeenCalled();+ });++ // The user-visible contract: opening the sidebar runs the watchdog, and the+ // watchdog must retire a leak the server cannot see. Before the mirror sweep+ // existed this test hung on a `running` op forever β the spinner and elapsed+ // clock the user reported.+ it('retires a local-only leak through cleanupStaleRunningTopics', async () => {+ const { key, serverRow } = seedLeakedRow();+ const operationId = seedLeakedOp('submitToolInteraction');+ // Nothing is `running` on the SERVER: the topic was already retired, so it+ // never appears in the watchdog's own `statuses: ['running']` query.+ vi.spyOn(topicService, 'queryTopics').mockResolvedValue([]);+ vi.spyOn(topicService, 'getTopicDetail').mockResolvedValue(serverRow);++ await act(async () => {+ await useChatStore.getState().cleanupStaleRunningTopics();+ });++ await waitFor(() => {+ expect(useChatStore.getState().operations[operationId].status).toBe('completed');+ });+ expect(operationSelectors.isTopicVisiblyRunning(topicId)(useChatStore.getState())).toBe(+ false,+ );+ expect(useChatStore.getState().topicDataMap[key].items[0]).toMatchObject({+ metadata: { runningOperation: null },+ status: 'active',+ });+ });+ });+describe('syncScheduledTopicRun', () => {const agentId = 'sync-scheduled-agent';const topicId = 'sync-scheduled-topic';diff --git a/src/store/chat/slices/topic/action.ts b/src/store/chat/slices/topic/action.tsindex e36726b8d5f..4f69aa508de 100644--- a/src/store/chat/slices/topic/action.ts+++ b/src/store/chat/slices/topic/action.ts@@ -1181,6 +1181,19 @@ export class ChatTopicActionImpl {}),);+ // Mirror sweep: a run the SERVER has already retired can still leave this+ // tab holding a `running` local op β its terminal frame never landed (a+ // lost socket, a hibernated DO buffer, or an intervention continuation+ // dispatched on a new operation). Such a topic is idle on the server, so it+ // never appears in the `statuses: ['running']` query above; derive the+ // candidates from the local op map instead. Fire-and-forget: the sidebar+ // should not wait on a per-topic server read.+ void this.#get()+ .settleAllUnbackedTopicRuns()+ .catch((err) =>+ console.error('[cleanupStaleRunningTopics] unbacked local run sweep failed:', err),+ );+const cleanedCount = cleanedResults.filter(Boolean).length;if (cleanedCount > 0) {