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.

✨ feat(chat): stream runs started on another device into an open topic (#21322)

Arvin Xu33469ef76df4
diff --git a/apps/server/src/modules/AgentRuntime/AgentRuntimeCoordinator.ts b/apps/server/src/modules/AgentRuntime/AgentRuntimeCoordinator.ts
index dbe3237d4c1..5bafad7de40 100644
--- a/apps/server/src/modules/AgentRuntime/AgentRuntimeCoordinator.ts
+++ b/apps/server/src/modules/AgentRuntime/AgentRuntimeCoordinator.ts
@@ -4,6 +4,7 @@ import debug from 'debug';
import { type AgentOperationMetadata, type StepResult } from './AgentStateManager';
import { createAgentStateManager, createStreamEventManager } from './factory';
+import type { GatewayInitMeta } from './GatewayStreamNotifier';
import { type IAgentStateManager, type IStreamEventManager } from './types';
import { hasVisibleOutputEndPublished } from './visibleOutputEnd';
@@ -104,6 +105,12 @@ export class AgentRuntimeCoordinator {
userId?: string;
workspaceId?: string;
},
+ /**
+ * Routing facts (topicId, agentId, …) sent with the gateway `init` but not
+ * persisted: the hub's `op_lifecycle` carries them to every socket of the
+ * user, so a client that did not start the run can tell where it belongs.
+ */
+ initMeta?: GatewayInitMeta,
): Promise<void> {
try {
// Create operation metadata
@@ -114,7 +121,10 @@ export class AgentRuntimeCoordinator {
if (metadata) {
// Send agent runtime init event
- await this.streamEventManager.publishAgentRuntimeInit(operationId, metadata);
+ await this.streamEventManager.publishAgentRuntimeInit(operationId, {
+ ...metadata,
+ ...initMeta,
+ });
log('[%s] Agent operation created and initialized', operationId);
}
} catch (error) {
diff --git a/apps/server/src/modules/AgentRuntime/__tests__/AgentRuntimeCoordinator.test.ts b/apps/server/src/modules/AgentRuntime/__tests__/AgentRuntimeCoordinator.test.ts
index 8afa8d7ce0b..570050d241b 100644
--- a/apps/server/src/modules/AgentRuntime/__tests__/AgentRuntimeCoordinator.test.ts
+++ b/apps/server/src/modules/AgentRuntime/__tests__/AgentRuntimeCoordinator.test.ts
@@ -76,6 +76,25 @@ describe('AgentRuntimeCoordinator', () => {
expect(mockStreamManager.publishAgentRuntimeInit).toHaveBeenCalledWith(operationId, metadata);
});
+ it('adds the routing meta to the init event without persisting it', async () => {
+ const operationId = 'test-operation-id';
+ const data = { userId: 'user-123' };
+ const metadata = { createdAt: '2024-01-01T00:00:00.000Z', status: 'idle', ...data };
+ mockStateManager.getOperationMetadata.mockResolvedValue(metadata);
+
+ await coordinator.createAgentOperation(operationId, data, {
+ agentId: 'agt_1',
+ topicId: 'tpc_1',
+ });
+
+ expect(mockStateManager.createOperationMetadata).toHaveBeenCalledWith(operationId, data);
+ expect(mockStreamManager.publishAgentRuntimeInit).toHaveBeenCalledWith(operationId, {
+ ...metadata,
+ agentId: 'agt_1',
+ topicId: 'tpc_1',
+ });
+ });
+
it('should not publish init event if metadata creation fails', async () => {
const operationId = 'test-operation-id';
const data = { userId: 'user-123' };
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/createOperation.relayExecutor.test.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/createOperation.relayExecutor.test.ts
index 9723dbc2e6e..822a5323958 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/createOperation.relayExecutor.test.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/__tests__/createOperation.relayExecutor.test.ts
@@ -300,11 +300,15 @@ describe('AgentRuntimeService', () => {
}),
);
- expect(mockCoordinator.createAgentOperation).toHaveBeenCalledWith('test-operation-1', {
- agentConfig: mockParams.agentConfig,
- modelRuntimeConfig: mockParams.modelRuntimeConfig,
- userId: mockParams.userId,
- });
+ expect(mockCoordinator.createAgentOperation).toHaveBeenCalledWith(
+ 'test-operation-1',
+ {
+ agentConfig: mockParams.agentConfig,
+ modelRuntimeConfig: mockParams.modelRuntimeConfig,
+ userId: mockParams.userId,
+ },
+ expect.any(Object),
+ );
expect(mockQueueService.scheduleMessage).toHaveBeenCalledWith({
operationId: 'test-operation-1',
@@ -316,6 +320,37 @@ describe('AgentRuntimeService', () => {
});
});
+ // Other clients of the user learn which conversation a run belongs to only
+ // from the gateway hub's `op_lifecycle`, which carries the init meta.
+ it('sends the run routing facts with the gateway init', async () => {
+ await service.createOperation({
+ ...mockParams,
+ appContext: {
+ agentId: 'agt_1',
+ groupId: 'grp_1',
+ scope: 'main',
+ taskId: 'task_1',
+ threadId: 'thd_1',
+ topicId: 'tpc_1',
+ },
+ parentOperationId: 'op_parent',
+ } as any);
+
+ expect(mockCoordinator.createAgentOperation).toHaveBeenCalledWith(
+ 'test-operation-1',
+ expect.any(Object),
+ {
+ agentId: 'agt_1',
+ groupId: 'grp_1',
+ parentOperationId: 'op_parent',
+ scope: 'main',
+ taskId: 'task_1',
+ threadId: 'thd_1',
+ topicId: 'tpc_1',
+ },
+ );
+ });
+
it('freezes the builder editing target on the run origin', async () => {
await service.createOperation({
...mockParams,
@@ -493,6 +528,7 @@ describe('AgentRuntimeService', () => {
expect(mockCoordinator.createAgentOperation).toHaveBeenCalledWith(
'test-operation-1',
expect.objectContaining({ modelRuntimeConfig: { model: 'gpt-4' } }),
+ expect.any(Object),
);
});
diff --git a/apps/server/src/services/agentRuntime/AgentRuntimeService/createOperation.ts b/apps/server/src/services/agentRuntime/AgentRuntimeService/createOperation.ts
index 318f66ebe91..f8956a5b722 100644
--- a/apps/server/src/services/agentRuntime/AgentRuntimeService/createOperation.ts
+++ b/apps/server/src/services/agentRuntime/AgentRuntimeService/createOperation.ts
@@ -350,26 +350,38 @@ export async function createOperation(
const mirrorToOperationId =
appContext?.orchestrationRole === 'member' ? (parentOperationId ?? undefined) : undefined;
await traceStartStage('runtime_meta', () =>
- deps.coordinator.createAgentOperation(operationId, {
- acceptsMemberRuntimeEnd,
- agentConfig,
- // Persisted so a queue worker that never ran this op's init still
- // applies the owner-configured visitor redaction policy instead of the
- // fail-closed full strip. See `gatewayVisitorRedaction.ts`.
- visitorRedaction: agentShareVisitor
- ? {
- showErrorDetails: agentShareVisitor.showErrorDetails,
- showModelInfo: agentShareVisitor.showModelInfo,
- }
- : undefined,
- mirrorToOperationId,
- modelRuntimeConfig: withoutFrozenModelFacts(modelRuntimeConfig),
- // Share-visitor runs execute as the creator (`userId`) but stream only
- // to the visitor — the gateway registers the WS channel under this id.
- streamOwnerUserId: agentShareVisitor?.visitorUserId,
- userId,
- workspaceId: deps.workspaceId,
- }),
+ deps.coordinator.createAgentOperation(
+ operationId,
+ {
+ acceptsMemberRuntimeEnd,
+ agentConfig,
+ // Persisted so a queue worker that never ran this op's init still
+ // applies the owner-configured visitor redaction policy instead of the
+ // fail-closed full strip. See `gatewayVisitorRedaction.ts`.
+ visitorRedaction: agentShareVisitor
+ ? {
+ showErrorDetails: agentShareVisitor.showErrorDetails,
+ showModelInfo: agentShareVisitor.showModelInfo,
+ }
+ : undefined,
+ mirrorToOperationId,
+ modelRuntimeConfig: withoutFrozenModelFacts(modelRuntimeConfig),
+ // Share-visitor runs execute as the creator (`userId`) but stream only
+ // to the visitor — the gateway registers the WS channel under this id.
+ streamOwnerUserId: agentShareVisitor?.visitorUserId,
+ userId,
+ workspaceId: deps.workspaceId,
+ },
+ {
+ agentId: appContext?.agentId ?? undefined,
+ groupId: appContext?.groupId ?? undefined,
+ parentOperationId: parentOperationId ?? undefined,
+ scope: appContext?.scope ?? undefined,
+ taskId: appContext?.taskId ?? undefined,
+ threadId: appContext?.threadId ?? undefined,
+ topicId: appContext?.topicId ?? undefined,
+ },
+ ),
);
operationCreated = true;
diff --git a/src/features/Portal/Topic/Chat/index.tsx b/src/features/Portal/Topic/Chat/index.tsx
index acf79cf2575..0223058a472 100644
--- a/src/features/Portal/Topic/Chat/index.tsx
+++ b/src/features/Portal/Topic/Chat/index.tsx
@@ -19,6 +19,7 @@ import SkeletonList from '@/features/Conversation/components/SkeletonList';
import { useChatFollowUp } from '@/features/Conversation/hooks/useChatFollowUp';
import { useGatewayReconnect } from '@/hooks/useGatewayReconnect';
import { useOperationState } from '@/hooks/useOperationState';
+import { useTopicRunEvents } from '@/hooks/useTopicRunEvents';
import HeterogeneousChatInput from '@/routes/(main)/agent/features/Conversation/HeterogeneousChatInput';
import { useAgentStore } from '@/store/agent';
import { agentByIdSelectors, chatConfigByIdSelectors } from '@/store/agent/selectors';
@@ -66,6 +67,7 @@ const TopicChat = memo(() => {
: undefined,
);
useGatewayReconnect(portalTopicId, runningOperation);
+ useTopicRunEvents(portalTopicId, activeAgentId);
const agentChatConfig = useAgentStore(chatConfigByIdSelectors.getChatConfigById(activeAgentId));
const hooks: ConversationHooks = useChatFollowUp({
diff --git a/src/hooks/useTopicRunEvents.test.ts b/src/hooks/useTopicRunEvents.test.ts
new file mode 100644
index 00000000000..9e484b097d4
--- /dev/null
+++ b/src/hooks/useTopicRunEvents.test.ts
@@ -0,0 +1,240 @@
+import { renderHook } from '@testing-library/react';
+import { act } from 'react';
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+import { useChatStore } from '@/store/chat';
+
+import {
+ latestTopicOperation,
+ MARKER_RETRY_DELAYS,
+ syncRemoteTopicRun,
+ useTopicRunEvents,
+} from './useTopicRunEvents';
+
+const topicWithRun = (operationId?: string) => ({
+ id: 'tpc-1',
+ metadata: operationId ? { runningOperation: { assistantMessageId: 'msg-a', operationId } } : {},
+ title: 'Topic',
+});
+
+/** `markers[i]` is what the i-th detail read returns. */
+const setup = ({
+ failReads = 0,
+ localRun = false,
+ marker,
+ markers = [],
+}: {
+ failReads?: number;
+ localRun?: boolean | 'thread';
+ marker?: string;
+ markers?: (string | undefined)[];
+} = {}) => {
+ const refreshMessages = vi.fn().mockResolvedValue(undefined);
+ let reads = 0;
+ const refreshTopicDetail = vi.fn(async () => {
+ if (reads < failReads) {
+ reads++;
+ throw new Error('network');
+ }
+ const next = markers[Math.min(reads++, markers.length - 1)];
+ useChatStore.setState({ topicDetailMap: { 'tpc-1': topicWithRun(next) as any } });
+ });
+ useChatStore.setState({
+ gatewayFeed: {},
+ operations: localRun
+ ? {
+ 'op-local': {
+ context: {
+ agentId: 'agt-1',
+ threadId: localRun === 'thread' ? 'thd-1' : undefined,
+ topicId: 'tpc-1',
+ },
+ id: 'op-local',
+ metadata: {},
+ status: 'running',
+ type: 'sendMessage',
+ } as any,
+ }
+ : {},
+ refreshMessages,
+ refreshTopicDetail,
+ topicDataMap: {},
+ topicDetailMap: { 'tpc-1': topicWithRun(marker) as any },
+ });
+ return { refreshMessages, refreshTopicDetail };
+};
+
+const sync = () =>
+ syncRemoteTopicRun({ agentId: 'agt-1', operationId: 'op-remote', topicId: 'tpc-1' });
+
+describe('latestTopicOperation', () => {
+ it('picks the newest main-line run of the topic from the hub feed', () => {
+ useChatStore.setState({
+ gatewayFeed: {
+ 'op-child': {
+ at: 5,
+ meta: { parentOperationId: 'op-a', topicId: 'tpc-1' },
+ status: 'running',
+ },
+ 'op-done': { at: 0, meta: { topicId: 'tpc-1' }, status: 'completed' },
+ 'op-a': { at: 1, meta: { topicId: 'tpc-1' }, status: 'running' },
+ 'op-b': { at: 2, meta: { topicId: 'tpc-1' }, status: 'running' },
+ 'op-other': { at: 3, meta: { topicId: 'tpc-2' }, status: 'running' },
+ 'op-thread': { at: 6, meta: { threadId: 'thd-1', topicId: 'tpc-1' }, status: 'running' },
+ } as any,
+ });
+
+ expect(latestTopicOperation('tpc-1')(useChatStore.getState())).toBe('op-b:live');
+ });
+
+ it('treats a run waiting on the user as live and a settled one as ended', () => {
+ const feed = (status: string) => ({
+ gatewayFeed: { 'op-a': { at: 1, meta: { topicId: 'tpc-1' }, status } } as any,
+ });
+
+ for (const status of ['running', 'waiting_input', 'waiting_confirmation']) {
+ useChatStore.setState(feed(status));
+ expect(latestTopicOperation('tpc-1')(useChatStore.getState())).toBe('op-a:live');
+ }
+ useChatStore.setState(feed('completed'));
+ expect(latestTopicOperation('tpc-1')(useChatStore.getState())).toBe('op-a:ended');
+ });
+});
+
+describe('syncRemoteTopicRun', () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it('reads the new run marker and the new turn when another device starts a run', async () => {
+ const { refreshMessages, refreshTopicDetail } = setup({ markers: ['op-remote'] });
+
+ await sync();
+
+ expect(refreshTopicDetail).toHaveBeenCalledTimes(1);
+ expect(refreshTopicDetail).toHaveBeenCalledWith('tpc-1', true);
+ expect(refreshMessages).toHaveBeenCalledWith({ agentId: 'agt-1', topicId: 'tpc-1' });
+ });
+
+ it('re-reads the detail until the server has written the marker', async () => {
+ const { refreshTopicDetail } = setup({ markers: [undefined, undefined, 'op-remote'] });
+
+ const done = sync();
+ await vi.runAllTimersAsync();
+ await done;
+
+ expect(refreshTopicDetail).toHaveBeenCalledTimes(3);
+ });
+
+ it('gives up after the retry budget when no marker ever appears', async () => {
+ const { refreshTopicDetail } = setup({ markers: [undefined] });
+
+ const done = sync();
+ await vi.runAllTimersAsync();
+ await done;
+
+ expect(refreshTopicDetail).toHaveBeenCalledTimes(MARKER_RETRY_DELAYS.length);
+ });
+
+ it('leaves a run this client started (or already streams) to its own connection', async () => {
+ const { refreshMessages, refreshTopicDetail } = setup({ localRun: true });
+
+ await sync();
+
+ expect(refreshTopicDetail).not.toHaveBeenCalled();
+ expect(refreshMessages).not.toHaveBeenCalled();
+ });
+
+ it('does not mistake a streaming thread for a main-line run of this client', async () => {
+ const { refreshTopicDetail } = setup({ localRun: 'thread', markers: ['op-remote'] });
+
+ await sync();
+
+ expect(refreshTopicDetail).toHaveBeenCalledWith('tpc-1', true);
+ });
+
+ it('keeps retrying after a transient detail read failure', async () => {
+ const { refreshTopicDetail } = setup({ failReads: 1, markers: ['op-remote'] });
+
+ const done = sync();
+ await vi.runAllTimersAsync();
+ await done;
+
+ expect(refreshTopicDetail).toHaveBeenCalledTimes(2);
+ });
+
+ it('ignores a run whose marker it already holds', async () => {
+ const { refreshMessages, refreshTopicDetail } = setup({ marker: 'op-remote' });
+
+ await sync();
+
+ expect(refreshTopicDetail).not.toHaveBeenCalled();
+ expect(refreshMessages).not.toHaveBeenCalled();
+ });
+});
+
+describe('useTopicRunEvents', () => {
+ it('syncs when the hub reports a new running operation on the shown topic', async () => {
+ const { refreshTopicDetail } = setup({ markers: ['op-remote'] });
+ renderHook(() => useTopicRunEvents('tpc-1', 'agt-1'));
+ expect(refreshTopicDetail).not.toHaveBeenCalled();
+
+ await act(async () => {
+ useChatStore.setState({
+ gatewayFeed: {
+ 'op-remote': { at: 1, meta: { topicId: 'tpc-1' }, status: 'running' },
+ } as any,
+ });
+ });
+
+ expect(refreshTopicDetail).toHaveBeenCalledWith('tpc-1', true);
+ });
+
+ it('reads the settled transcript when a remote run ends before its marker is found', async () => {
+ const { refreshMessages } = setup({ markers: [undefined] });
+ renderHook(() => useTopicRunEvents('tpc-1', 'agt-1'));
+
+ await act(async () => {
+ useChatStore.setState({
+ gatewayFeed: {
+ 'op-remote': { at: 1, meta: { topicId: 'tpc-1' }, status: 'running' },
+ } as any,
+ });
+ });
+ refreshMessages.mockClear();
+ await act(async () => {
+ useChatStore.setState({
+ gatewayFeed: {
+ 'op-remote': { at: 2, meta: { topicId: 'tpc-1' }, status: 'completed' },
+ } as any,
+ });
+ });
+
+ expect(refreshMessages).toHaveBeenCalledWith({ agentId: 'agt-1', topicId: 'tpc-1' });
+ });
+
+ it('does not refetch when a run of this client ends', async () => {
+ const { refreshMessages } = setup({ localRun: true });
+ renderHook(() => useTopicRunEvents('tpc-1', 'agt-1'));
+
+ await act(async () => {
+ useChatStore.setState({
+ gatewayFeed: { 'op-mine': { at: 1, meta: { topicId: 'tpc-1' }, status: 'running' } } as any,
+ });
+ });
+ await act(async () => {
+ useChatStore.setState({
+ gatewayFeed: {
+ 'op-mine': { at: 2, meta: { topicId: 'tpc-1' }, status: 'completed' },
+ } as any,
+ operations: {},
+ });
+ });
+
+ expect(refreshMessages).not.toHaveBeenCalled();
+ });
+});
diff --git a/src/hooks/useTopicRunEvents.ts b/src/hooks/useTopicRunEvents.ts
new file mode 100644
index 00000000000..3c576aad6c1
--- /dev/null
+++ b/src/hooks/useTopicRunEvents.ts
@@ -0,0 +1,137 @@
+'use client';
+
+import { useEffect, useMemo } from 'react';
+
+import { useChatStore } from '@/store/chat';
+import type { ChatStoreState } from '@/store/chat/initialState';
+import { gatewayFeedSelectors, topicSelectors } from '@/store/chat/selectors';
+import { INPUT_LOADING_OPERATION_TYPES } from '@/store/chat/slices/operation/types';
+
+/** Non-terminal hub statuses: the run can still stream or wait on the user. */
+const LIVE_STATUSES = new Set(['running', 'waiting_input', 'waiting_confirmation']);
+
+const currentOperationId = (topicId: string) =>
+ topicSelectors.getTopicById(topicId)(useChatStore.getState())?.metadata?.runningOperation
+ ?.operationId;
+
+/**
+ * This client runs or streams the topic's main conversation. Thread runs are
+ * excluded: they never own the topic's `runningOperation` marker.
+ */
+const hasLocalMainRun = (topicId: string) =>
+ Object.values(useChatStore.getState().operations).some(
+ (op) =>
+ op.status === 'running' &&
+ op.context.topicId === topicId &&
+ !op.context.threadId &&
+ INPUT_LOADING_OPERATION_TYPES.includes(op.type),
+ );
+
+const isHandled = (topicId: string, operationId: string) =>
+ hasLocalMainRun(topicId) || currentOperationId(topicId) === operationId;
+
+/**
+ * The newest main-line run of `topicId` in the gateway hub feed, encoded as
+ * `<operationId>:live` or `<operationId>:ended` so the selection is a stable
+ * primitive. Thread and child runs never own the topic's marker.
+ */
+export const latestTopicOperation =
+ (topicId: string) =>
+ (s: ChatStoreState): string | undefined => {
+ let latest: { at: number; operationId: string; status: string } | undefined;
+ for (const [operationId, entry] of Object.entries(gatewayFeedSelectors.gatewayFeed(s))) {
+ const { meta } = entry;
+ if (meta?.topicId !== topicId || meta.threadId || meta.parentOperationId) continue;
+ if (!latest || entry.at > latest.at)
+ latest = { at: entry.at, operationId, status: entry.status };
+ }
+ if (!latest) return;
+ return `${latest.operationId}:${LIVE_STATUSES.has(latest.status) ? 'live' : 'ended'}`;
+ };
+
+/**
+ * The hub announces a run at gateway init, which precedes the server writing
+ * the topic's `runningOperation` marker; re-read the detail until it lands.
+ */
+export const MARKER_RETRY_DELAYS = [0, 500, 1500, 3000];
+
+/**
+ * Pick up a run another client started on this topic. Re-reading the topic
+ * detail installs its `runningOperation` marker, which `useGatewayReconnect`
+ * attaches to with full replay; the message refetch brings the new user turn.
+ */
+export const syncRemoteTopicRun = async (params: {
+ agentId: string;
+ operationId: string;
+ signal?: AbortSignal;
+ topicId: string;
+}): Promise<void> => {
+ const { agentId, operationId, signal, topicId } = params;
+ if (isHandled(topicId, operationId)) return;
+
+ const messages = useChatStore.getState().refreshMessages({ agentId, topicId });
+ let lastError: unknown;
+ for (const delay of MARKER_RETRY_DELAYS) {
+ if (delay) await new Promise((resolve) => setTimeout(resolve, delay));
+ if (signal?.aborted) break;
+ try {
+ await useChatStore.getState().refreshTopicDetail(topicId, true);
+ lastError = undefined;
+ } catch (error) {
+ // A transient read failure must not end discovery; the next attempt may land.
+ lastError = error;
+ }
+ if (isHandled(topicId, operationId)) break;
+ }
+ await messages;
+ if (lastError) throw lastError;
+};
+
+/**
+ * Follow runs started on another device while a conversation shows the topic.
+ * The per-user gateway socket already broadcasts every operation's lifecycle
+ * (`op_lifecycle`, mirrored into `gatewayFeed`) whether or not this client
+ * subscribed to it, so a new live operation on this topic is the signal.
+ */
+export const useTopicRunEvents = (topicId: string | null | undefined, agentId?: string) => {
+ const latest = useChatStore((s) => (topicId ? latestTopicOperation(topicId)(s) : undefined));
+
+ // Runs already in the feed when the view opened come with its own fetch;
+ // `remote` holds runs this view picked up from another client.
+ const seen = useMemo(
+ () => ({
+ atMount: new Set(Object.keys(useChatStore.getState().gatewayFeed)),
+ live: new Set<string>(),
+ remote: new Set<string>(),
+ }),
+ [topicId],
+ );
+
+ useEffect(() => {
+ if (!topicId || !agentId || !latest) return;
+
+ const separator = latest.lastIndexOf(':');
+ const operationId = latest.slice(0, separator);
+ const onError = (error: unknown) => {
+ console.error('[TopicRunEvents] Failed to sync remote run:', error);
+ };
+
+ if (latest.slice(separator + 1) === 'live') {
+ seen.live.add(operationId);
+ if (isHandled(topicId, operationId)) return;
+
+ seen.remote.add(operationId);
+ const ac = new AbortController();
+ syncRemoteTopicRun({ agentId, operationId, signal: ac.signal, topicId }).catch(onError);
+ return () => ac.abort();
+ }
+
+ // A remote run can end before its marker was ever readable (a fast reply,
+ // a startup failure): nothing attached, so read the settled transcript.
+ const missedLive = !seen.live.has(operationId) && !seen.atMount.has(operationId);
+ if (!seen.remote.has(operationId) && !missedLive) return;
+ seen.remote.delete(operationId);
+ if (hasLocalMainRun(topicId)) return;
+ useChatStore.getState().refreshMessages({ agentId, topicId }).catch(onError);
+ }, [agentId, latest, seen, topicId]);
+};
diff --git a/src/routes/(main)/agent/features/Conversation/ConversationArea.tsx b/src/routes/(main)/agent/features/Conversation/ConversationArea.tsx
index a16d97323e1..2e6fc36e4ec 100644
--- a/src/routes/(main)/agent/features/Conversation/ConversationArea.tsx
+++ b/src/routes/(main)/agent/features/Conversation/ConversationArea.tsx
@@ -26,6 +26,7 @@ import { mergeConversationHooks } from '@/features/Conversation/utils/mergeConve
import { useGatewayReconnect } from '@/hooks/useGatewayReconnect';
import { useOperationState } from '@/hooks/useOperationState';
import { useScheduledRunWatch } from '@/hooks/useScheduledRunWatch';
+import { useTopicRunEvents } from '@/hooks/useTopicRunEvents';
import { useAgentStore } from '@/store/agent';
import { agentByIdSelectors, chatConfigByIdSelectors } from '@/store/agent/selectors';
import { useChatStore } from '@/store/chat';
@@ -94,6 +95,8 @@ const Conversation = memo(() => {
: undefined,
);
useGatewayReconnect(context.topicId, runningOperation, context.agentId);
+ // A run started on another device pushes here, so it streams without a refetch.
+ useTopicRunEvents(context.topicId, context.agentId);
// While the topic is parked as `scheduled`, pull the cron dispatch into the
// store when `runAt` passes — nothing pushes it, and the reconnect above
diff --git a/src/store/chat/slices/agentRun/initialState.ts b/src/store/chat/slices/agentRun/initialState.ts
index 447a7e71a12..9cc49805c45 100644
--- a/src/store/chat/slices/agentRun/initialState.ts
+++ b/src/store/chat/slices/agentRun/initialState.ts
@@ -29,8 +29,8 @@ export interface ChatAIChatState {
*/
gatewayConnections: Record<string, GatewayConnection>;
/**
- * Mux-level op lifecycle feed, keyed by operationId. No UI reads it yet;
- * later work drives spinners / reconnect decisions from it.
+ * Mux-level op lifecycle feed, keyed by operationId. `useTopicRunEvents`
+ * reads it to follow runs another device starts on an open topic.
*/
gatewayFeed: Record<string, GatewayFeedEntry>;
inputFiles: File[];
diff --git a/src/store/chat/slices/topic/action.ts b/src/store/chat/slices/topic/action.ts
index 1c9eab5815c..242a8daaac4 100644
--- a/src/store/chat/slices/topic/action.ts
+++ b/src/store/chat/slices/topic/action.ts
@@ -1748,10 +1748,9 @@ export class ChatTopicActionImpl {
]);
};
- /** Revalidate one topic's by-id detail, e.g. after a dispatch wrote a new receipt. */
- refreshTopicDetail = async (topicId: string): Promise<void> => {
- await this.#topicDetail.revalidate(topicId);
- };
+ /** Re-read one topic's by-id detail; `fetch` also reads it when no view has it mounted. */
+ refreshTopicDetail = (id: string, fetch?: boolean): Promise<unknown> =>
+ fetch ? this.#topicDetail.fetch(id, { fresh: true }) : this.#topicDetail.revalidate(id);
internal_replaceTopicId = (params: {
agentId?: string;