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(socket): re-read the core bearer on every handshake
M3gA-Mindb07c47bcf5cf
diff --git a/app/src/services/__tests__/coreRpcClient.test.ts b/app/src/services/__tests__/coreRpcClient.test.tsindex 0064931bc4..af579ef8ee 100644--- a/app/src/services/__tests__/coreRpcClient.test.ts+++ b/app/src/services/__tests__/coreRpcClient.test.ts@@ -521,7 +521,7 @@ describe('coreRpcClient', () => {expect(fetch).not.toHaveBeenCalled();});- test('caches a missing token result after the first Tauri lookup failure', async () => {+ test('looks the token up again after a failed Tauri lookup', async () => {vi.resetModules();vi.mocked(isTauri).mockReturnValue(true);vi.mocked(invoke).mockImplementation(async (cmd: string) => {@@ -540,7 +540,7 @@ describe('coreRpcClient', () => {const tokenCalls = vi.mocked(invoke).mock.calls.filter(([cmd]) => cmd === 'core_rpc_endpoint').length;- expect(tokenCalls).toBe(1);+ expect(tokenCalls).toBe(2);expect(fetch).not.toHaveBeenCalled();});diff --git a/app/src/services/__tests__/coreSocket.test.ts b/app/src/services/__tests__/coreSocket.test.tsindex fdf2e8886b..f4be7be90f 100644--- a/app/src/services/__tests__/coreSocket.test.ts+++ b/app/src/services/__tests__/coreSocket.test.ts@@ -25,49 +25,66 @@ const ioMock = hoisted.ioMock;const getCoreRpcTokenMock = hoisted.getCoreRpcTokenMock;const resolveCoreSocketEndpointMock = hoisted.resolveCoreSocketEndpointMock;+/** Runs the `auth` callback the way socket.io-client does on each handshake. */+function handshake(auth: unknown): Promise<Record<string, unknown>> {+ return new Promise(resolve =>+ (auth as (cb: (data: Record<string, unknown>) => void) => void)(resolve)+ );+}+describe('createCoreSocket', () => {beforeEach(() => {ioMock.mockClear();+ // No resolvable bearer: the handshake falls back to the caller's token.+ getCoreRpcTokenMock.mockReset();+ getCoreRpcTokenMock.mockResolvedValue(null);});- it('passes the core bearer through the auth payload', () => {+ it('passes the core bearer through the auth payload', async () => {createCoreSocket('http://127.0.0.1:7788', { coreToken: 'core-bearer-xyz' });expect(ioMock).toHaveBeenCalledTimes(1);- const call = ioMock.mock.calls[0] as unknown as [string, { auth: { token: string } }];+ const call = ioMock.mock.calls[0] as unknown as [string, { auth: unknown }];expect(call[0]).toBe('http://127.0.0.1:7788');- expect(call[1].auth.token).toBe('core-bearer-xyz');+ expect((await handshake(call[1].auth)).token).toBe('core-bearer-xyz');});- it('substitutes empty string when no core token is available', () => {+ it('substitutes empty string when no core token is available', async () => {createCoreSocket('http://127.0.0.1:7788', { coreToken: null });- const call = ioMock.mock.calls[0] as unknown as [string, { auth: { token: string } }];- expect(call[1].auth.token).toBe('');+ const call = ioMock.mock.calls[0] as unknown as [string, { auth: unknown }];+ expect((await handshake(call[1].auth)).token).toBe('');});- it('merges authExtras alongside the token slot', () => {+ it('merges authExtras alongside the token slot', async () => {createCoreSocket('http://127.0.0.1:7788', {coreToken: 'core',authExtras: { session: 'jwt-abc' },});- const call = ioMock.mock.calls[0] as unknown as [- string,- { auth: { token: string; session: string } },- ];- expect(call[1].auth.token).toBe('core');- expect(call[1].auth.session).toBe('jwt-abc');+ const call = ioMock.mock.calls[0] as unknown as [string, { auth: unknown }];+ const payload = await handshake(call[1].auth);+ expect(payload.token).toBe('core');+ expect(payload.session).toBe('jwt-abc');+ });++ it('re-reads the core bearer on every handshake, so a reconnect after a core restart uses the new one', async () => {+ createCoreSocket('http://127.0.0.1:7788', { coreToken: 'launch-1-bearer' });+ const call = ioMock.mock.calls[0] as unknown as [string, { auth: unknown }];+ getCoreRpcTokenMock.mockResolvedValue('launch-1-bearer');+ expect((await handshake(call[1].auth)).token).toBe('launch-1-bearer');+ getCoreRpcTokenMock.mockResolvedValue('launch-2-bearer');+ expect((await handshake(call[1].auth)).token).toBe('launch-2-bearer');});- it('honours overrides without dropping the auth payload', () => {+ it('honours overrides without dropping the auth payload', async () => {createCoreSocket('http://127.0.0.1:7788', {coreToken: 'core',overrides: { reconnectionAttempts: 5, forceNew: false, timeout: 4000 },});const call = ioMock.mock.calls[0] as unknown as [string,- { auth: { token: string }; reconnectionAttempts: number; forceNew: boolean; timeout: number },+ { auth: unknown; reconnectionAttempts: number; forceNew: boolean; timeout: number },];const opts = call[1];- expect(opts.auth.token).toBe('core');+ expect((await handshake(opts.auth)).token).toBe('core');expect(opts.reconnectionAttempts).toBe(5);expect(opts.forceNew).toBe(false);expect(opts.timeout).toBe(4000);@@ -93,9 +110,9 @@ describe('connectCoreSocket', () => {expect(getBaseUrl).toHaveBeenCalledTimes(1);expect(getCoreRpcTokenMock).toHaveBeenCalledTimes(1);expect(ioMock).toHaveBeenCalledTimes(1);- const call = ioMock.mock.calls[0] as unknown as [string, { auth: { token: string } }];+ const call = ioMock.mock.calls[0] as unknown as [string, { auth: unknown }];expect(call[0]).toBe('http://127.0.0.1:7788');- expect(call[1].auth.token).toBe('mock-core-bearer');+ expect((await handshake(call[1].auth)).token).toBe('mock-core-bearer');});it('short-circuits to null when disposed flips before token resolves', async () => {@@ -131,18 +148,18 @@ describe('connectCoreSocket', () => {});const call = ioMock.mock.calls[0] as unknown as [string,- { auth: { token: string; session: string }; reconnectionAttempts: number },+ { auth: unknown; reconnectionAttempts: number },];- expect(call[1].auth.session).toBe('jwt-xyz');+ expect((await handshake(call[1].auth)).session).toBe('jwt-xyz');expect(call[1].reconnectionAttempts).toBe(7);});it('passes empty token through when getCoreRpcToken resolves to null', async () => {- getCoreRpcTokenMock.mockResolvedValueOnce(null);+ getCoreRpcTokenMock.mockResolvedValue(null);const getBaseUrl = vi.fn().mockResolvedValue('http://127.0.0.1:7788');await connectCoreSocket({ getBaseUrl });- const call = ioMock.mock.calls[0] as unknown as [string, { auth: { token: string } }];- expect(call[1].auth.token).toBe('');+ const call = ioMock.mock.calls[0] as unknown as [string, { auth: unknown }];+ expect((await handshake(call[1].auth)).token).toBe('');});it('uses the private-LAN shell relay and forces WebSocket transport', async () => {diff --git a/app/src/services/__tests__/socketService.events.test.ts b/app/src/services/__tests__/socketService.events.test.tsindex f20ef7cc66..41a62c8813 100644--- a/app/src/services/__tests__/socketService.events.test.ts+++ b/app/src/services/__tests__/socketService.events.test.ts@@ -44,9 +44,11 @@ vi.mock('../../lib/mcp', () => ({ SocketIOMCPTransportImpl: MockMCPTransport }))// getCoreRpcUrl mock — each test sets what it needs.const getCoreRpcUrlMock = vi.fn<() => Promise<string>>();+const clearCoreRpcTokenCacheMock = vi.fn();vi.mock('../coreRpcClient', () => ({getCoreRpcUrl: getCoreRpcUrlMock,clearCoreRpcUrlCache: vi.fn(),+ clearCoreRpcTokenCache: clearCoreRpcTokenCacheMock,// socketService now reads the per-process bearer for the Socket.IO// handshake `auth.token` payload; tests only care that the resolve// chain proceeds, not what the bearer value is.@@ -209,8 +211,11 @@ describe('socketService — socket event handler dispatches (lines 212, 230, 237await pollUntil(() => expect(handlers['connect_error']).toBeDefined());setBackendMock.mockClear();+ clearCoreRpcTokenCacheMock.mockClear();handlers['connect_error']!(new Error('connection refused'));+ // The next handshake must re-read the bearer (the core may have restarted).+ expect(clearCoreRpcTokenCacheMock).toHaveBeenCalledTimes(1);const disconnectedCall = setBackendMock.mock.calls.find(([arg]) => (arg as { value: string }).value === 'disconnected'diff --git a/app/src/services/__tests__/socketService.test.ts b/app/src/services/__tests__/socketService.test.tsindex bc53c06df6..f76538a3d9 100644--- a/app/src/services/__tests__/socketService.test.ts+++ b/app/src/services/__tests__/socketService.test.ts@@ -82,6 +82,7 @@ const hoisted = vi.hoisted(() => ({ getCoreRpcUrlMock: vi.fn<() => Promise<strinvi.mock('../coreRpcClient', () => ({getCoreRpcUrl: hoisted.getCoreRpcUrlMock,clearCoreRpcUrlCache: vi.fn(),+ clearCoreRpcTokenCache: vi.fn(),// socketService now reads the per-process bearer for the Socket.IO// handshake `auth.token` payload; the test value is irrelevant — the// mock just needs to resolve so the connect flow proceeds.diff --git a/app/src/services/coreRpcClient.ts b/app/src/services/coreRpcClient.tsindex a5079b4dee..ad54f1e128 100644--- a/app/src/services/coreRpcClient.ts+++ b/app/src/services/coreRpcClient.ts@@ -539,13 +539,14 @@ export async function getCoreRpcToken(): Promise<string | null> {try {const endpoint = await resolveShellEndpoint();resolvedCoreRpcToken = endpoint?.token?.trim() || null;- didResolveCoreRpcToken = true;+ // Only a real token is cached: a missing one (core still starting, or a+ // failed lookup) is looked up again on the next call.+ didResolveCoreRpcToken = resolvedCoreRpcToken !== null;coreRpcLog('core RPC token loaded');return resolvedCoreRpcToken;} catch (err) {coreRpcError('failed to load core RPC token', err);resolvedCoreRpcToken = null;- didResolveCoreRpcToken = true;return null;} finally {resolvingCoreRpcToken = null;diff --git a/app/src/services/coreSocket.ts b/app/src/services/coreSocket.tsindex e44c23de69..beb12395f2 100644--- a/app/src/services/coreSocket.ts+++ b/app/src/services/coreSocket.ts@@ -45,7 +45,16 @@ const DEFAULT_OPTIONS: Partial<ManagerOptions & SocketOptions> = {};export function createCoreSocket(baseUrl: string, opts: CoreSocketOptions): Socket {- const auth = { token: opts.coreToken ?? '', ...(opts.authExtras ?? {}) };+ const extras = opts.authExtras ?? {};+ // socket.io-client resends an object `auth` unchanged on every reconnect, so+ // after a core restart (new per-launch bearer) it would retry the dead one+ // forever. A function `auth` runs on every handshake and re-reads the bearer.+ const auth = (cb: (data: object) => void) => {+ void getCoreRpcToken().then(+ token => cb({ token: token ?? opts.coreToken ?? '', ...extras }),+ () => cb({ token: opts.coreToken ?? '', ...extras })+ );+ };return io(baseUrl, { ...DEFAULT_OPTIONS, ...(opts.overrides ?? {}), auth });}diff --git a/app/src/services/socketService.ts b/app/src/services/socketService.tsindex e361842f3d..c60c5c46e1 100644--- a/app/src/services/socketService.ts+++ b/app/src/services/socketService.ts@@ -12,7 +12,12 @@ import type { ChannelAuthMode, ChannelConnectionStatus, ChannelType } from '../timport type { UserErrorScope } from '../types/userError';import { IS_DEV, IS_TEST } from '../utils/config';import { createSafeLogData, sanitizeError } from '../utils/sanitize';-import { getCoreRpcToken, getCoreRpcUrl, resolveCoreSocketEndpoint } from './coreRpcClient';+import {+ clearCoreRpcTokenCache,+ getCoreRpcToken,+ getCoreRpcUrl,+ resolveCoreSocketEndpoint,+} from './coreRpcClient';import { createCoreSocket } from './coreSocket';// Socket service logger using debug package@@ -263,6 +268,9 @@ class SocketService {});this.socket.on('connect_error', (error: Error) => {+ // The core may have restarted with a new bearer; make the next+ // handshake's `auth` callback re-read it.+ clearCoreRpcTokenCache();const uid = getSocketUserId();socketError('Connection error', { userId: uid, error: sanitizeError(error) });store.dispatch(setStatusForUser({ userId: uid, status: 'disconnected' }));