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: 修复消息停止与冷刷新恢复 (#21550)

Mocha4e7eb4eb97d4
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/factory.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/factory.test.ts
index fa4f7481f2e..1393dcb2ebb 100644
--- a/apps/server/src/modules/AgentRuntime/__tests__/factory.test.ts
+++ b/apps/server/src/modules/AgentRuntime/__tests__/factory.test.ts
@@ -42,6 +42,7 @@ vi.mock('@/envs/app', () => ({
vi.mock('../redis', () => ({
getAgentRuntimeRedisClient: mockGetAgentRuntimeRedisClient,
+ isAgentRuntimeRedisEnabled: () => mockGetAgentRuntimeRedisClient() !== null,
}));
vi.mock('../InMemoryAgentStateManager', () => ({
@@ -86,11 +87,19 @@ describe('AgentRuntime factory', () => {
});
describe('createAgentStateManager', () => {
- it('uses in-memory state when queue mode is disabled', () => {
+ it('uses in-memory state when queue mode is disabled and Redis is unavailable', () => {
expect(createAgentStateManager()).toBe(mockInMemoryAgentStateManager);
expect(MockAgentStateManager).not.toHaveBeenCalled();
});
+ it('shares Redis-backed state when queue mode is disabled and Redis is available', () => {
+ mockGetAgentRuntimeRedisClient.mockReturnValue({ ping: vi.fn() });
+
+ expect(createAgentStateManager()).toEqual({ kind: 'redis-state-manager' });
+ expect(MockAgentStateManager).toHaveBeenCalledTimes(1);
+ expect(mockAppEnv.enableQueueAgentRuntime).toBe(false);
+ });
+
it('uses Redis-backed state when queue mode is enabled and Redis is available', () => {
mockAppEnv.enableQueueAgentRuntime = true;
mockGetAgentRuntimeRedisClient.mockReturnValue({ ping: vi.fn() });
diff --git a/apps/server/src/modules/AgentRuntime/factory.sharedState.test.ts b/apps/server/src/modules/AgentRuntime/factory.sharedState.test.ts
new file mode 100644
index 00000000000..7b89bb0c83d
--- /dev/null
+++ b/apps/server/src/modules/AgentRuntime/factory.sharedState.test.ts
@@ -0,0 +1,40 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+const transport = vi.hoisted(() => {
+ const values = new Map<string, string>();
+ return {
+ values,
+ client: {
+ exists: async (key: string) => Number(values.has(key)),
+ setex: async (key: string, _ttl: number, value: string) => {
+ values.set(key, value);
+ return 'OK';
+ },
+ },
+ };
+});
+
+vi.mock('@/envs/app', () => ({ appEnv: { enableQueueAgentRuntime: false } }));
+vi.mock('./redis', () => ({ getAgentRuntimeRedisClient: () => transport.client }));
+vi.mock('./GatewayStreamNotifier', () => ({ GatewayStreamNotifier: vi.fn() }));
+
+// Separate module graphs represent independent inline runtime instances. Only
+// the Redis transport boundary is replaced; both factories and managers are real.
+describe('inline runtime shared interruption state', () => {
+ beforeEach(() => {
+ vi.resetModules();
+ transport.values.clear();
+ });
+
+ it('observes an interruption written by another factory instance', async () => {
+ const first = (await import('./factory')).createAgentStateManager();
+ vi.resetModules();
+ const second = (await import('./factory')).createAgentStateManager();
+
+ expect(first).not.toBe(second);
+ expect(await first.isInterrupted('shared-run')).toBe(false);
+ await second.markInterrupted('shared-run');
+ expect(await first.isInterrupted('shared-run')).toBe(true);
+ expect(await first.isInterrupted('unrelated-run')).toBe(false);
+ });
+});
diff --git a/apps/server/src/modules/AgentRuntime/factory.ts b/apps/server/src/modules/AgentRuntime/factory.ts
index 9e627e918d1..08d720ffd7c 100644
--- a/apps/server/src/modules/AgentRuntime/factory.ts
+++ b/apps/server/src/modules/AgentRuntime/factory.ts
@@ -22,7 +22,7 @@ export const isRedisAvailable = (): boolean => {
/**
* Check if queue-based agent runtime is enabled
- * When disabled (default), use InMemory implementations for local/simple deployments
+ * Controls execution scheduling independently of the state/stream storage backend
*/
const isQueueModeEnabled = (): boolean => {
return appEnv.enableQueueAgentRuntime === true;
@@ -32,20 +32,19 @@ const isQueueModeEnabled = (): boolean => {
* Create AgentStateManager based on configuration
*/
export const createAgentStateManager = (): IAgentStateManager => {
- // When queue mode is disabled, always use InMemory for simplicity
- if (!isQueueModeEnabled()) {
- log('Queue mode disabled, using InMemoryAgentStateManager');
- return inMemoryAgentStateManager;
+ // Share state and interrupt sentinels across web/worker replicas even when
+ // execution stays inline. Storage selection must match the shared stream bus.
+ if (isRedisAvailable()) {
+ log('Redis available, using AgentStateManager');
+ return new AgentStateManager();
}
- // Queue mode enabled, Redis is required
- if (!isRedisAvailable()) {
- throw new Error(
- 'Redis is required when AGENT_RUNTIME_MODE=queue. Please configure `REDIS_URL`.',
- );
+ if (!isQueueModeEnabled()) {
+ log('Redis unavailable and queue mode disabled, using InMemoryAgentStateManager');
+ return inMemoryAgentStateManager;
}
- return new AgentStateManager();
+ throw new Error('Redis is required when AGENT_RUNTIME_MODE=queue. Please configure `REDIS_URL`.');
};
/**
@@ -101,7 +100,7 @@ export const createStreamEventManager = (
// Resolver lets a queue worker (which never ran the member op's init) mirror
// its stream events onto the supervisor channel by reading the persisted
// `mirrorToOperationId` from op metadata. Shares the same state manager
- // backing the runtime (in-memory singleton locally, Redis in queue mode).
+ // backing the runtime (Redis when configured, otherwise the in-memory singleton).
const stateManager = createAgentStateManager();
return new GatewayStreamNotifier(
manager,
diff --git a/src/hooks/useFetchActiveTopicDetail.test.ts b/src/hooks/useFetchActiveTopicDetail.test.ts
index 098782e95b7..4b884d14277 100644
--- a/src/hooks/useFetchActiveTopicDetail.test.ts
+++ b/src/hooks/useFetchActiveTopicDetail.test.ts
@@ -85,6 +85,215 @@ describe('background runs in the active topic', () => {
vi.useRealTimers();
});
+ it.each(['empty bucket', 'listed row'])(
+ 'recovers a live run on cold entry with %s and stale detail',
+ async (source) => {
+ vi.useFakeTimers();
+ vi.mocked(scmService.hasWakeTarget).mockResolvedValue(false);
+ useChatStore.setState({
+ topicDataMap: source === 'empty bucket' ? {} : useChatStore.getState().topicDataMap,
+ topicDetailMap: { [topic.id]: topic },
+ });
+ const marker = { ...runningOperation, heteroType: null, scope: 'main', threadId: null };
+ vi.mocked(topicService.getTopicDetail).mockResolvedValue({
+ ...topic,
+ metadata: { runningOperation: marker },
+ status: 'running',
+ });
+ const { result } = renderHook(useConversation, { wrapper });
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(0);
+ });
+ expect(
+ topicSelectors.getTopicById(topic.id)(useChatStore.getState())?.metadata?.runningOperation,
+ ).toEqual(marker);
+ expect(result.current.isInputVisiblyLoading).toBe(true);
+ const reads = vi.mocked(topicService.getTopicDetail).mock.calls.length;
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(60_000);
+ });
+ expect(topicService.getTopicDetail).toHaveBeenCalledTimes(reads);
+ },
+ );
+
+ it.each(['topic edit', 'detail edit', 'list hydration'])(
+ 'applies a fresh live marker after %s overtakes the detail read',
+ async (change) => {
+ vi.useFakeTimers();
+ let resolve!: (topic: ChatTopic) => void;
+ vi.mocked(topicService.getTopicDetail).mockReturnValue(
+ new Promise((done) => {
+ resolve = done;
+ }),
+ );
+ if (change !== 'topic edit')
+ useChatStore.setState({ topicDataMap: {}, topicDetailMap: { [topic.id]: topic } });
+ const { result } = renderHook(useConversation, { wrapper });
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(0);
+ });
+ act(() => {
+ if (change === 'list hydration') {
+ useChatStore.getState().internal_updateTopics(context.agentId, {
+ items: [{ ...topic, title: 'Updated', status: 'running' }],
+ pageSize: 20,
+ total: 1,
+ });
+ } else {
+ useChatStore.getState().internal_dispatchTopic({
+ id: topic.id,
+ type: 'updateTopic',
+ value: { title: 'Updated', status: 'running' },
+ });
+ }
+ });
+ const marker = { ...runningOperation, heteroType: null, scope: 'main', threadId: null };
+ await act(async () => {
+ resolve({ ...topic, metadata: { runningOperation: marker }, status: 'running' });
+ await vi.advanceTimersByTimeAsync(0);
+ });
+ expect(
+ topicSelectors.getTopicById(topic.id)(useChatStore.getState())?.metadata?.runningOperation,
+ ).toEqual(marker);
+ expect(result.current.isInputVisiblyLoading).toBe(true);
+ expect(topicSelectors.getTopicById(topic.id)(useChatStore.getState())?.title).toBe('Updated');
+ },
+ );
+
+ it.each(['deleted topic', 'edited topic without a live response'])(
+ 'does not revive stale details after %s',
+ async (change) => {
+ vi.useFakeTimers();
+ let resolve!: (value: ChatTopic) => void;
+ vi.mocked(topicService.getTopicDetail).mockReturnValue(
+ new Promise((done) => {
+ resolve = done;
+ }),
+ );
+ renderHook(useFetchActiveTopicDetail, { wrapper });
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(0);
+ });
+ act(() => {
+ if (change === 'deleted topic') {
+ useChatStore.getState().internal_dispatchTopic({ id: topic.id, type: 'deleteTopic' });
+ } else {
+ useChatStore.getState().internal_dispatchTopic({
+ id: topic.id,
+ type: 'updateTopic',
+ value: { title: 'Updated', status: 'completed' },
+ });
+ }
+ });
+ await act(async () => {
+ resolve(change === 'deleted topic' ? { ...topic, metadata: { runningOperation } } : topic);
+ await vi.advanceTimersByTimeAsync(0);
+ });
+ const current = topicSelectors.getTopicById(topic.id)(useChatStore.getState());
+ if (change === 'deleted topic') expect(current).toBeUndefined();
+ else expect(current).toMatchObject({ title: 'Updated', status: 'completed' });
+ expect(useChatStore.getState().reconnectToGatewayOperation).not.toHaveBeenCalled();
+ },
+ );
+
+ it.each(['stop marker', 'replacement marker'])(
+ 'rejects a live response overtaken by a %s',
+ async (change) => {
+ vi.useFakeTimers();
+ let resolve!: (topic: ChatTopic) => void;
+ vi.mocked(topicService.getTopicDetail).mockReturnValue(
+ new Promise((done) => {
+ resolve = done;
+ }),
+ );
+ renderHook(useFetchActiveTopicDetail, { wrapper });
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(0);
+ });
+ const newerMarker =
+ change === 'stop marker' ? null : { ...runningOperation, operationId: 'newer-run' };
+ act(() => {
+ useChatStore.getState().internal_dispatchTopic({
+ id: topic.id,
+ type: 'updateTopic',
+ value: { metadata: { runningOperation: newerMarker } },
+ });
+ });
+ await act(async () => {
+ resolve({ ...topic, metadata: { runningOperation } });
+ await vi.advanceTimersByTimeAsync(0);
+ });
+ expect(
+ topicSelectors.getTopicById(topic.id)(useChatStore.getState())?.metadata?.runningOperation,
+ ).toEqual(newerMarker);
+ expect(useChatStore.getState().reconnectToGatewayOperation).not.toHaveBeenCalled();
+ },
+ );
+
+ it.each([true, false])(
+ 'waits for topic creation before reading a missing topic (gateway %s)',
+ async (gateway) => {
+ vi.useFakeTimers();
+ config.serverConfig.agentGatewayUrl = gateway ? 'wss://gateway.test' : '';
+ useChatStore.setState({ topicDataMap: {}, creatingTopicIds: [topic.id] });
+ vi.mocked(scmService.hasWakeTarget).mockResolvedValue(false);
+ renderHook(useFetchActiveTopicDetail, { wrapper });
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(0);
+ });
+ expect(topicService.getTopicDetail).not.toHaveBeenCalled();
+ act(() => {
+ useChatStore.setState({ creatingTopicIds: [] });
+ });
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(0);
+ });
+ expect(topicService.getTopicDetail).toHaveBeenCalledTimes(1);
+ expect(topicSelectors.getTopicById(topic.id)(useChatStore.getState())).toEqual(topic);
+ },
+ );
+
+ it.each(['missing', 'error'])(
+ 'keeps cached running status when a cold detail read is %s',
+ async (response) => {
+ vi.useFakeTimers();
+ const cached = { ...topic, status: 'running' as const };
+ useChatStore.setState({ topicDataMap: {}, topicDetailMap: { [topic.id]: cached } });
+ vi.mocked(scmService.hasWakeTarget).mockResolvedValue(false);
+ if (response === 'missing') vi.mocked(topicService.getTopicDetail).mockResolvedValue(null);
+ else
+ vi.mocked(topicService.getTopicDetail).mockRejectedValue(new Error('detail unavailable'));
+ const { result } = renderHook(useConversation, { wrapper });
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(0);
+ });
+ expect(topicSelectors.getTopicById(topic.id)(useChatStore.getState())).toEqual(cached);
+ expect(result.current.isInputVisiblyLoading).toBe(false);
+ expect(useChatStore.getState().reconnectToGatewayOperation).not.toHaveBeenCalled();
+ },
+ );
+
+ it('does not create a local run for a completed topic on cold entry', async () => {
+ vi.useFakeTimers();
+ useChatStore.setState({ topicDataMap: {}, topicDetailMap: { [topic.id]: topic } });
+ vi.mocked(scmService.hasWakeTarget).mockResolvedValue(false);
+ vi.mocked(topicService.getTopicDetail).mockResolvedValue({
+ ...topic,
+ status: 'completed',
+ metadata: { runningOperation: null },
+ });
+ const { result } = renderHook(useConversation, { wrapper });
+ await act(async () => {
+ await vi.advanceTimersByTimeAsync(60_000);
+ });
+ expect(topicSelectors.getTopicById(topic.id)(useChatStore.getState())?.status).toBe(
+ 'completed',
+ );
+ expect(result.current.isInputVisiblyLoading).toBe(false);
+ expect(useChatStore.getState().reconnectToGatewayOperation).not.toHaveBeenCalled();
+ expect(topicService.getTopicDetail).toHaveBeenCalledTimes(1);
+ });
+
it('discovers a CR run while the conversation stays open and restores the stop control', async () => {
vi.useFakeTimers();
const { result } = renderHook(useConversation, { wrapper });
@@ -218,7 +427,8 @@ describe('background runs in the active topic', () => {
await vi.advanceTimersByTimeAsync(60_000);
});
expect(scmService.hasWakeTarget).toHaveBeenCalledWith(context.topicId);
- expect(topicService.getTopicDetail).not.toHaveBeenCalled();
+ // One entry read checks for an existing run; no SCM target means no polling.
+ expect(topicService.getTopicDetail).toHaveBeenCalledTimes(1);
});
it('starts watching once a local run links the topic to a pull request', async () => {
diff --git a/src/hooks/useFetchActiveTopicDetail.ts b/src/hooks/useFetchActiveTopicDetail.ts
index 4be6bd4d37e..b456bbe2ab5 100644
--- a/src/hooks/useFetchActiveTopicDetail.ts
+++ b/src/hooks/useFetchActiveTopicDetail.ts
@@ -21,7 +21,7 @@ export const useFetchActiveTopicDetail = () => {
const [activeTopicId, isMissingFromList, useFetchTopicDetail] = useChatStore((s) => [
s.activeTopicId,
!!s.activeTopicId &&
- !!topicSelectors.currentTopicData(s) &&
+ !s.creatingTopicIds.includes(s.activeTopicId) &&
!topicSelectors.currentTopics(s)?.some((topic) => topic.id === s.activeTopicId),
s.useFetchTopicDetail,
]);
@@ -40,5 +40,8 @@ export const useFetchActiveTopicDetail = () => {
);
const watchRuns = idle && !!wakeable;
- useFetchTopicDetail(isMissingFromList || watchRuns ? activeTopicId : undefined, watchRuns);
+ // Revalidate on entry even when a persisted row exists: SCM wakeability does
+ // not describe runs already active on the server after a reload. Only SCM
+ // wake targets need continued polling once that first read has settled.
+ useFetchTopicDetail(isMissingFromList || idle ? activeTopicId : undefined, watchRuns);
};
diff --git a/src/store/chat/slices/operation/actions.cancellation.test.ts b/src/store/chat/slices/operation/actions.cancellation.test.ts
new file mode 100644
index 00000000000..bdb42332528
--- /dev/null
+++ b/src/store/chat/slices/operation/actions.cancellation.test.ts
@@ -0,0 +1,147 @@
+import { toast } from '@lobehub/ui';
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+import { createStore } from 'zustand/vanilla';
+
+import type { ChatStore } from '@/store/chat/store';
+
+import { OperationActionsImpl } from './actions';
+import { initialOperationState } from './initialState';
+import { operationSelectors } from './selectors';
+import type { OperationContext } from './types';
+
+vi.mock('@lobehub/ui', async (importOriginal) => ({
+ ...(await importOriginal<Record<string, unknown>>()),
+ toast: { error: vi.fn() },
+}));
+
+vi.mock('@/store/home', () => ({ getHomeStoreState: () => ({}) }));
+
+const useChatStore = createStore<ChatStore>()(
+ (set, get) =>
+ ({
+ ...initialOperationState,
+ ...new OperationActionsImpl(set, get),
+ }) as ChatStore,
+);
+
+describe('operation cancellation context and recovery', () => {
+ beforeEach(() => {
+ useChatStore.setState(useChatStore.getInitialState());
+ vi.clearAllMocks();
+ });
+
+ it.each([
+ { context: {}, scope: 'main' },
+ { context: { groupId: 'group1' }, scope: 'group' },
+ { context: { threadId: 'thread1' }, scope: 'thread' },
+ ] as const)(
+ 'matches inferred $scope scope without crossing context boundaries',
+ ({ context, scope }) => {
+ const store = useChatStore.getState();
+ const start = (extra: OperationContext = {}) =>
+ store.startOperation({
+ context: { agentId: 'agent1', topicId: 'topic1', ...context, ...extra },
+ type: 'execServerAgentRuntime',
+ }).operationId;
+ const implicit = start();
+ const explicit = start({ scope });
+ const unrelated = [
+ start({ agentId: 'other-agent' }),
+ start({ topicId: 'other-topic' }),
+ start({ scope: 'sub_agent' }),
+ start({ scope: 'thread', threadId: 'other-thread' }),
+ start({ groupId: 'other-group', scope: 'group' }),
+ start({ scope: 'group_agent' }),
+ start({ groupId: 'other-group', scope: undefined }),
+ start({ scope: undefined, threadId: 'other-thread' }),
+ start({ isNew: true, scope: 'thread', threadId: null }),
+ ];
+
+ expect(
+ store.cancelOperations({
+ agentId: 'agent1',
+ groupId: 'groupId' in context ? context.groupId : undefined,
+ scope,
+ threadId: 'threadId' in context ? context.threadId : null,
+ topicId: 'topic1',
+ }),
+ ).toEqual([implicit, explicit]);
+ expect(unrelated.map((id) => useChatStore.getState().operations[id].status)).toEqual(
+ unrelated.map(() => 'running'),
+ );
+ },
+ );
+
+ it('matches absent group and existing-conversation defaults without cancelling new contexts', () => {
+ const store = useChatStore.getState();
+ const start = (context: OperationContext) =>
+ store.startOperation({
+ context: { agentId: 'agent1', topicId: 'topic1', ...context },
+ type: 'execServerAgentRuntime',
+ }).operationId;
+ const implicit = start({});
+ const explicit = start({ isNew: false, scope: 'main' });
+ const newConversation = start({ isNew: true, scope: 'main' });
+ const groupConversation = start({ groupId: 'group1', isNew: false });
+
+ expect(
+ store.cancelOperations({
+ agentId: 'agent1',
+ groupId: null,
+ isNew: false,
+ scope: 'main',
+ topicId: 'topic1',
+ }),
+ ).toEqual([implicit, explicit]);
+ expect(useChatStore.getState().operations[newConversation].status).toBe('running');
+ expect(useChatStore.getState().operations[groupConversation].status).toBe('running');
+ });
+
+ it.each(['reject', 'throw'] as const)(
+ 'restores Stop and supports retry after handlers %s',
+ async (failure) => {
+ const store = useChatStore.getState();
+ const context = { agentId: 'agent1', scope: 'main' as const, topicId: 'topic1' };
+ const { operationId } = store.startOperation({ context, type: 'execServerAgentRuntime' });
+ const handler = vi
+ .fn()
+ .mockImplementationOnce(() => {
+ if (failure === 'throw') throw new Error('cancel unavailable');
+ return Promise.reject(new Error('cancel unavailable'));
+ })
+ .mockResolvedValue(undefined);
+ store.onOperationCancel(operationId, handler);
+
+ await expect(store.cancelOperation(operationId)).resolves.toBe(false);
+ const failedState = useChatStore.getState();
+ expect(failedState.operations[operationId].status).toBe('running');
+ expect(failedState.operations[operationId].metadata.isAborting).toBeFalsy();
+ expect(operationSelectors.isAgentRuntimeRunningByContext(context)(failedState)).toBe(true);
+
+ await expect(store.cancelOperation(operationId)).resolves.toBe(true);
+ expect(handler).toHaveBeenCalledTimes(2);
+ expect(useChatStore.getState().operations[operationId].status).toBe('cancelled');
+ },
+ );
+
+ it('reports a failed batch cancellation and leaves it available for retry', async () => {
+ const store = useChatStore.getState();
+ const { operationId } = store.startOperation({
+ context: { agentId: 'agent1' },
+ type: 'execServerAgentRuntime',
+ });
+ const handler = vi
+ .fn()
+ .mockRejectedValueOnce(new Error('network unavailable'))
+ .mockResolvedValue(undefined);
+ store.onOperationCancel(operationId, handler);
+
+ expect(store.cancelOperations({ agentId: 'agent1', scope: 'main' })).toEqual([operationId]);
+ await vi.waitFor(() => expect(toast.error).toHaveBeenCalledOnce());
+ expect(useChatStore.getState().operations[operationId].metadata.isAborting).toBeFalsy();
+ expect(store.cancelOperations({ agentId: 'agent1', scope: 'main' })).toEqual([operationId]);
+ await vi.waitFor(() => expect(handler).toHaveBeenCalledTimes(2));
+ expect(useChatStore.getState().operations[operationId].status).toBe('cancelled');
+ expect(toast.error).toHaveBeenCalledOnce();
+ });
+});
diff --git a/src/store/chat/slices/operation/actions.ts b/src/store/chat/slices/operation/actions.ts
index 5647d092333..ad7bac1cd41 100644
--- a/src/store/chat/slices/operation/actions.ts
+++ b/src/store/chat/slices/operation/actions.ts
@@ -1,5 +1,7 @@
import { nanoid } from '@lobechat/utils';
+import { toast } from '@lobehub/ui';
import debug from 'debug';
+import { t } from 'i18next';
import { produce } from 'immer';
import { topicService } from '@/services/topic';
@@ -563,6 +565,7 @@ export class OperationActionsImpl {
if (!op || op.status !== 'cancelled' || op.metadata.cancelReason !== reason) return;
op.status = 'running';
+ delete op.metadata.isAborting;
delete op.metadata.cancelReason;
delete op.metadata.duration;
delete op.metadata.endTime;
@@ -640,13 +643,18 @@ export class OperationActionsImpl {
matches = matches && isSameNullableContextValue(op.context.threadId, filter.threadId);
}
if (filter.groupId !== undefined) {
- matches = matches && op.context.groupId === filter.groupId;
+ matches = matches && isSameNullableContextValue(op.context.groupId, filter.groupId);
}
if (filter.scope !== undefined) {
- matches = matches && op.context.scope === filter.scope;
+ // Match message-map scope inference, while keeping explicit sub-agent
+ // scopes separate: sharing a display bucket does not authorize Stop.
+ const scope =
+ op.context.scope ??
+ (op.context.groupId ? 'group' : op.context.threadId ? 'thread' : 'main');
+ matches = matches && scope === filter.scope;
}
if (filter.isNew !== undefined) {
- matches = matches && op.context.isNew === filter.isNew;
+ matches = matches && (op.context.isNew ?? false) === filter.isNew;
}
if (matches) {
@@ -655,9 +663,16 @@ export class OperationActionsImpl {
});
// Cancel all matched operations
- matchedIds.forEach((id) => {
- this.#get().cancelOperation(id, reason);
- });
+ void Promise.all(matchedIds.map((id) => this.#get().cancelOperation(id, reason)))
+ .then((confirmations) => {
+ if (confirmations.some((confirmed) => !confirmed)) {
+ toast.error(t('backgroundActivity.stopFailed', { ns: 'chat' }));
+ }
+ })
+ .catch((error: unknown) => {
+ log('[cancelOperations] cancellation error: %O', error);
+ toast.error(t('backgroundActivity.stopFailed', { ns: 'chat' }));
+ });
return matchedIds;
};
diff --git a/src/store/chat/slices/operation/types.ts b/src/store/chat/slices/operation/types.ts
index 8abe1d113d8..4a1ab8d403c 100644
--- a/src/store/chat/slices/operation/types.ts
+++ b/src/store/chat/slices/operation/types.ts
@@ -491,7 +491,7 @@ export const mergeQueuedMessages = (messages: QueuedMessage[]): MergedQueuedMess
*/
export interface OperationFilter {
agentId?: string;
- groupId?: string;
+ groupId?: string | null;
isNew?: boolean;
messageId?: string;
scope?: MessageMapScope;
diff --git a/src/store/chat/slices/topic/topicDetail.ts b/src/store/chat/slices/topic/topicDetail.ts
index a9aa3da548a..fe0cf37da3c 100644
--- a/src/store/chat/slices/topic/topicDetail.ts
+++ b/src/store/chat/slices/topic/topicDetail.ts
@@ -63,14 +63,31 @@ export const createTopicDetailSlice = ({
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.
+ const current = topicSelectors.getTopicById(topicId)(get());
+ // Local runs and explicit marker changes supersede this read, including
+ // a stop that finished before it returned. List hydration and unrelated
+ // topic edits can replace the row without invalidating its run state.
if (
snapshot &&
- (snapshot.topic !== topicSelectors.getTopicById(topicId)(get()) ||
+ ((!!snapshot.topic && !current) ||
+ !isEqual(
+ snapshot.topic?.metadata?.runningOperation,
+ current?.metadata?.runningOperation,
+ ) ||
snapshot.operationIds !== operationIds(topicId))
)
return undefined;
+ if (snapshot && snapshot.topic !== current) {
+ // Preserve newer local fields while still accepting the server's live
+ // marker. The linked entity fans that marker into any loaded lists.
+ if (current && topic?.metadata?.runningOperation) {
+ return {
+ ...current,
+ metadata: { ...current.metadata, runningOperation: topic.metadata.runningOperation },
+ };
+ }
+ return undefined;
+ }
return topic;
},
set,