The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.
Rust agent-orchestrationai-agentsai-assistantdesktopllmlocal-firstmcppersonal-aiprivacyrustsecond-braintauri
fix(chat): keep live turns rendering after a new session socket or a Stop
Sanil3af435810db7
diff --git a/app/src/providers/ChatRuntimeProvider.tsx b/app/src/providers/ChatRuntimeProvider.tsxindex 799dc423df..0f3df67f70 100644--- a/app/src/providers/ChatRuntimeProvider.tsx+++ b/app/src/providers/ChatRuntimeProvider.tsx@@ -47,6 +47,7 @@ import { socketService } from '../services/socketService';import { store } from '../store';import {appendSubagentStreamDelta,+ beginInferenceTurn,bumpInferenceHeartbeatForThread,cancelUnresolvedTurnTimeline,clearInferenceStatusForThread,@@ -797,6 +798,17 @@ const ChatRuntimeProvider = ({ children }: { children: React.ReactNode }) => {) {dispatch(setToolTimelineForThread({ threadId: event.thread_id, entries: [] }));}+ // A turn this window did not send (one started right after a Stop,+ // from another window, or queued) has no lifecycle yet, or a finished+ // one: begin it here so its stream renders live, not after a reload.+ const parallel =+ !!event.request_id &&+ store.getState().chatRuntime.parallelRequestThreads[event.request_id] !== undefined;+ const lifecycle =+ store.getState().chatRuntime.inferenceTurnLifecycleByThread[event.thread_id];+ if (!parallel && lifecycle !== 'started' && lifecycle !== 'streaming') {+ dispatch(beginInferenceTurn({ threadId: event.thread_id }));+ }dispatch(markInferenceTurnStreaming({ threadId: event.thread_id }));if (event.request_id) {dispatch(liveTurnStarted({ threadId: event.thread_id, requestId: event.request_id }));diff --git a/app/src/services/__tests__/socketService.test.ts b/app/src/services/__tests__/socketService.test.tsindex ec20a7c079..bc53c06df6 100644--- a/app/src/services/__tests__/socketService.test.ts+++ b/app/src/services/__tests__/socketService.test.ts@@ -277,6 +277,53 @@ describe('socketService — resolveCoreSocketBaseUrl uses getCoreRpcUrl', () =>expect(latestSocket.once).not.toHaveBeenCalledWith('queued-on-event', expect.any(Function));});+ it('keeps subscriptions when a new session token replaces the socket', async () => {+ const { io } = await import('socket.io-client');+ const ioMock = vi.mocked(io);+ ioMock.mockClear();+ hoisted.getCoreRpcUrlMock.mockResolvedValue('http://127.0.0.1:7788/rpc');++ const { socketService } = await import('../socketService');+ socketService.disconnect();++ type MockSocket = {+ on: ReturnType<typeof vi.fn>;+ once: ReturnType<typeof vi.fn>;+ onAny: ReturnType<typeof vi.fn>;+ };+ const latest = () => ioMock.mock.results[ioMock.mock.results.length - 1].value as MockSocket;++ socketService.connect('first-session-token');+ await pollUntil(() => expect(ioMock).toHaveBeenCalledTimes(1));+ const first = latest();+ // Subscribed while the first socket is live (as the chat runtime does on mount).+ const onDelta = vi.fn();+ const onOnce = vi.fn();+ socketService.on('reconnect-survivor', onDelta);+ socketService.once('reconnect-survivor-once', onOnce);+ expect(first.on).toHaveBeenCalledWith('reconnect-survivor', expect.any(Function));++ // The session token changes: the service drops the socket and builds a new one.+ socketService.connect('second-session-token');+ await pollUntil(() => expect(ioMock).toHaveBeenCalledTimes(2));+ const second = latest();+ expect(second).not.toBe(first);+ await pollUntil(() =>+ expect(second.on).toHaveBeenCalledWith('reconnect-survivor', expect.any(Function))+ );+ expect(second.once).toHaveBeenCalledWith('reconnect-survivor-once', expect.any(Function));++ // A removed subscription stays off later sockets.+ socketService.off('reconnect-survivor', onDelta);+ socketService.off('reconnect-survivor-once', onOnce);+ socketService.connect('third-session-token');+ await pollUntil(() => expect(ioMock).toHaveBeenCalledTimes(3));+ const third = latest();+ await pollUntil(() => expect(third.onAny).toHaveBeenCalled());+ expect(third.on).not.toHaveBeenCalledWith('reconnect-survivor', expect.any(Function));+ expect(third.once).not.toHaveBeenCalledWith('reconnect-survivor-once', expect.any(Function));+ });+it('reconnects when a stale disconnected socket exists for the same token', async () => {const { io } = await import('socket.io-client');const ioMock = vi.mocked(io);diff --git a/app/src/services/socketService.ts b/app/src/services/socketService.tsindex 4bc4e1c0b1..e361842f3d 100644--- a/app/src/services/socketService.ts+++ b/app/src/services/socketService.ts@@ -58,12 +58,6 @@ interface ChannelConnectionUpdatedEvent {capabilities?: string[];}-interface PendingSocketListener {- event: string;- callback: (...args: unknown[]) => void;- once: boolean;-}-function normalizeChannelConnectionUpdatePayload(value: unknown): ChannelConnectionUpdatedEvent | null {@@ -111,13 +105,17 @@ class SocketService {private socket: Socket | null = null;private token: string | null = null;private mcpTransport: SocketIOMCPTransportImpl | null = null;- private pendingListeners: PendingSocketListener[] = [];- // Maps original caller callbacks → wrapped callbacks so off() can locate the- // exact function references that were registered with socket.io, scoped by event.+ // Every subscription, as caller callback → wrapped callbacks per event: the+ // registry each new socket is wired from, and how off() finds the exact+ // functions registered with socket.io. Subscriptions outlive any one socket:+ // a reconnect (a new session token, a stale socket) builds a new socket and+ // re-attaches them all, so a subscriber never silently stops hearing events.private listenerMap = new Map<string,Map<(...args: unknown[]) => void, Set<(...args: unknown[]) => void>>>();+ // Wrapped callbacks registered through once(), re-attached with once().+ private onceWrapped = new WeakSet<(...args: unknown[]) => void>();/*** Connect to the socket server with authentication.@@ -204,18 +202,9 @@ class SocketService {},});- // Flush any listeners that were registered before the socket existed.- if (this.pendingListeners.length > 0) {- socketLog('Flushing pending listeners', { count: this.pendingListeners.length });- for (const { event, callback, once } of this.pendingListeners) {- if (once) {- this.socket.once(event, callback);- } else {- this.socket.on(event, callback);- }- }- this.pendingListeners = [];- }+ // Wire every subscription onto this socket: those made before any socket+ // existed and those an earlier socket carried before this one replaced it.+ this.attachRegisteredListeners(this.socket);this.socket.onAny((event, ...args) => {const firstArg = args.length > 0 ? args[0] : undefined;@@ -397,8 +386,23 @@ class SocketService {}this.token = null;this.mcpTransport = null;- this.listenerMap.clear();- this.pendingListeners = [];+ // Subscriptions are kept: the next socket re-attaches them. Subscribers+ // remove their own with off().+ }++ /** Attach every registered subscription to `socket`. */+ private attachRegisteredListeners(socket: Socket): void {+ let count = 0;+ for (const [event, byEvent] of this.listenerMap) {+ for (const wrappedSet of byEvent.values()) {+ for (const wrapped of wrappedSet) {+ if (this.onceWrapped.has(wrapped)) socket.once(event, wrapped);+ else socket.on(event, wrapped);+ count += 1;+ }+ }+ }+ if (count > 0) socketLog('Attached registered listeners', { count });}/**@@ -492,8 +496,7 @@ class SocketService {if (this.socket) {this.socket.on(event, wrappedCallback);} else {- socketLog('Socket not ready, queuing listener', { event });- this.pendingListeners.push({ event, callback: wrappedCallback, once: false });+ socketLog('Socket not ready, listener attaches on connect', { event });}}@@ -516,15 +519,10 @@ class SocketService {if (this.socket) {this.socket.off(event, wrapped);}- // Also remove from the pending queue in case the socket isn't up yet.- this.pendingListeners = this.pendingListeners.filter(- p => !(p.event === event && p.callback === wrapped)- );}} else {socketLog('Removing all listeners for event', { event });this.socket?.off(event);- this.pendingListeners = this.pendingListeners.filter(p => p.event !== event);this.listenerMap.delete(event);}}@@ -558,11 +556,11 @@ class SocketService {wrappedSet.add(wrappedCallback);byEvent.set(callback, wrappedSet);this.listenerMap.set(event, byEvent);+ this.onceWrapped.add(wrappedCallback);if (this.socket) {this.socket.once(event, wrappedCallback);} else {- socketLog('Socket not ready, queuing once listener', { event });- this.pendingListeners.push({ event, callback: wrappedCallback, once: true });+ socketLog('Socket not ready, once listener attaches on connect', { event });}}}