Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

refactor(test): update userApi tests to mock session owner

Steven Enamakeldfce9145fb41
diff --git a/app/src/services/api/__tests__/userApi.test.ts b/app/src/services/api/__tests__/userApi.test.ts
index 891039c9e7..45d3cd7bc0 100644
--- a/app/src/services/api/__tests__/userApi.test.ts
+++ b/app/src/services/api/__tests__/userApi.test.ts
@@ -1,9 +1,9 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
-const mockCallCoreCommand = vi.fn();
+const mockFetchCurrentUser = vi.fn();
-vi.mock('../../coreCommandClient', () => ({
- callCoreCommand: (...args: unknown[]) => mockCallCoreCommand(...args),
+vi.mock('../../session/sessionOwner', () => ({
+ fetchCurrentUser: (...args: unknown[]) => mockFetchCurrentUser(...args),
}));
const { userApi } = await import('../userApi');
@@ -43,35 +43,36 @@ function getMockUser() {
describe('userApi.getMe', () => {
beforeEach(() => {
- mockCallCoreCommand.mockReset();
+ mockFetchCurrentUser.mockReset();
});
it('returns user data on success', async () => {
- mockCallCoreCommand.mockResolvedValue(getMockUser());
+ mockFetchCurrentUser.mockResolvedValue({ user: getMockUser(), stale: false, staleSeconds: 0 });
const user = await userApi.getMe();
- expect(mockCallCoreCommand).toHaveBeenCalledWith('openhuman.auth_get_me');
+ // A live answer: the session owner is asked to bypass its cache.
+ expect(mockFetchCurrentUser).toHaveBeenCalledWith(true);
expect(user._id).toBe('user-123');
expect(user.firstName).toBe('Test');
expect(user.username).toBe('testuser');
expect(user.subscription.plan).toBe('FREE');
});
- it('throws when API returns error response', async () => {
- mockCallCoreCommand.mockRejectedValue(new Error('Unauthorized'));
+ it('throws when the owner rejects the session', async () => {
+ mockFetchCurrentUser.mockRejectedValue(new Error('REJECTED: Unauthorized'));
- await expect(userApi.getMe()).rejects.toThrow();
+ await expect(userApi.getMe()).rejects.toThrow('REJECTED: Unauthorized');
});
- it('throws when API returns success=false', async () => {
- mockCallCoreCommand.mockRejectedValue(new Error('Invalid token'));
+ it('throws when nobody is signed in', async () => {
+ mockFetchCurrentUser.mockResolvedValue({ user: null, stale: false, staleSeconds: null });
- await expect(userApi.getMe()).rejects.toThrow('Invalid token');
+ await expect(userApi.getMe()).rejects.toThrow('no signed-in user');
});
it('throws on network error', async () => {
- mockCallCoreCommand.mockRejectedValue(new Error('Service unavailable'));
+ mockFetchCurrentUser.mockRejectedValue(new Error('TRANSIENT: Service unavailable'));
await expect(userApi.getMe()).rejects.toBeDefined();
});
diff --git a/app/src/services/session/__tests__/sessionOwner.test.ts b/app/src/services/session/__tests__/sessionOwner.test.ts
new file mode 100644
index 0000000000..ab63d75d64
--- /dev/null
+++ b/app/src/services/session/__tests__/sessionOwner.test.ts
@@ -0,0 +1,216 @@
+import { invoke } from '@tauri-apps/api/core';
+import { afterEach, beforeEach, describe, expect, it, type Mock, vi } from 'vitest';
+
+import { callCoreRpc } from '../../coreRpcClient';
+
+vi.mock('../../coreRpcClient', () => ({ callCoreRpc: vi.fn() }));
+vi.mock('../../backendUrl', () => ({
+ getBackendUrl: vi.fn().mockResolvedValue('https://api.test'),
+}));
+vi.mock('../../clientVersionHeaders', () => ({
+ getClientVersionHeaders: vi.fn().mockResolvedValue({ 'x-tauri-version': '1.0.0' }),
+}));
+
+const isTauriMock = vi.hoisted(() => vi.fn(() => false));
+vi.mock('../../../utils/tauriCommands/common', async importOriginal => {
+ const actual = await importOriginal<typeof import('../../../utils/tauriCommands/common')>();
+ return {
+ ...actual,
+ isTauri: isTauriMock,
+ safeInvoke: (...args: unknown[]) =>
+ (invoke as unknown as (...a: unknown[]) => unknown)(...args),
+ };
+});
+const getStoredCoreMode = vi.hoisted(() =>
+ vi.fn<() => 'local' | 'cloud' | 'gateway' | null>(() => null)
+);
+vi.mock('../../../utils/configPersistence', () => ({ getStoredCoreMode }));
+
+// The global test setup mocks this module; these tests exercise the real one.
+vi.unmock('../sessionOwner');
+const owner = await vi.importActual<typeof import('../sessionOwner')>('../sessionOwner');
+
+const mockInvoke = invoke as Mock;
+const mockCallCoreRpc = callCoreRpc as Mock;
+
+const jsonResponse = (status: number, body: unknown): Response =>
+ ({ ok: status >= 200 && status < 300, status, json: async () => body }) as unknown as Response;
+
+describe('sessionOwner (desktop shell owner)', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ isTauriMock.mockReturnValue(true);
+ getStoredCoreMode.mockReturnValue('local');
+ });
+
+ it('routes login, store, logout and current user to the shell commands', async () => {
+ mockInvoke.mockResolvedValue({ user: { id: 'u1' }, stale: false, staleSeconds: 0 });
+
+ await owner.loginWithToken('login-tok');
+ expect(mockInvoke).toHaveBeenCalledWith('auth_login_with_token', { token: 'login-tok' });
+
+ await owner.storeSessionToken('jwt', { id: 'u1' });
+ expect(mockInvoke).toHaveBeenCalledWith('auth_store_session', {
+ token: 'jwt',
+ user: { id: 'u1' },
+ });
+
+ await owner.logoutSession();
+ expect(mockInvoke).toHaveBeenCalledWith('auth_logout');
+
+ const current = await owner.fetchCurrentUser(true);
+ expect(mockInvoke).toHaveBeenCalledWith('auth_current_user', { force: true });
+ expect(current).toEqual({ user: { id: 'u1' }, stale: false, staleSeconds: 0 });
+ expect(mockCallCoreRpc).not.toHaveBeenCalled();
+ });
+
+ it('is not the owner in cloud mode even inside Tauri', () => {
+ getStoredCoreMode.mockReturnValue('cloud');
+ expect(owner.useShellSessionOwner()).toBe(false);
+ });
+});
+
+describe('sessionOwner (browser / cloud owner)', () => {
+ const fetchMock = vi.fn();
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ isTauriMock.mockReturnValue(false);
+ getStoredCoreMode.mockReturnValue(null);
+ vi.stubGlobal('fetch', fetchMock);
+ });
+
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ });
+
+ it('exchanges a login token, validates it, and hands the credential to the core', async () => {
+ fetchMock
+ .mockResolvedValueOnce(jsonResponse(200, { success: true, data: { jwt: 'jwt-1' } }))
+ .mockResolvedValueOnce(
+ jsonResponse(200, { success: true, data: { _id: 'u9', email: 'a@b' } })
+ );
+ mockCallCoreRpc.mockResolvedValue({ result: {} });
+
+ await owner.loginWithToken('login-tok');
+
+ expect(fetchMock.mock.calls[0][0]).toBe('https://api.test/auth/login-token/consume');
+ expect(JSON.parse(fetchMock.mock.calls[0][1].body)).toEqual({ token: 'login-tok' });
+ expect(fetchMock.mock.calls[1][0]).toBe('https://api.test/auth/me');
+ expect(fetchMock.mock.calls[1][1].headers.Authorization).toBe('Bearer jwt-1');
+ expect(mockCallCoreRpc).toHaveBeenCalledWith({
+ method: 'openhuman.auth_set_credential',
+ params: { token: 'jwt-1', kind: 'session', userId: 'u9', user: { _id: 'u9', email: 'a@b' } },
+ });
+ });
+
+ it('never installs a JWT the backend rejects', async () => {
+ fetchMock.mockResolvedValueOnce(jsonResponse(401, { success: false, message: 'nope' }));
+
+ await expect(owner.storeSessionToken('bad-jwt')).rejects.toThrow(/^REJECTED:/);
+ expect(mockCallCoreRpc).not.toHaveBeenCalled();
+ });
+
+ it('reports an unreachable backend as transient', async () => {
+ fetchMock.mockResolvedValueOnce(jsonResponse(503, {}));
+
+ await expect(owner.storeSessionToken('jwt')).rejects.toThrow(/^TRANSIENT:/);
+ expect(mockCallCoreRpc).not.toHaveBeenCalled();
+ });
+
+ it('stores a local token as-is without touching the backend', async () => {
+ mockCallCoreRpc.mockResolvedValue({ result: {} });
+
+ await owner.storeSessionToken('a.b.local', { id: 'local' });
+
+ expect(fetchMock).not.toHaveBeenCalled();
+ expect(mockCallCoreRpc).toHaveBeenCalledWith({
+ method: 'openhuman.auth_set_credential',
+ params: { token: 'a.b.local', kind: 'local', user: { id: 'local' } },
+ });
+ });
+
+ it('prefixes core failures so callers can classify them', async () => {
+ mockCallCoreRpc.mockRejectedValue(new Error('core unreachable'));
+
+ await expect(owner.storeSessionToken('a.b.local', { id: 'l' })).rejects.toThrow(
+ 'CORE: core unreachable'
+ );
+ });
+
+ it('logs out through auth.clear_credential', async () => {
+ mockCallCoreRpc.mockResolvedValue({ result: {} });
+ await owner.logoutSession();
+ expect(mockCallCoreRpc).toHaveBeenCalledWith({
+ method: 'openhuman.auth_clear_credential',
+ params: { kind: 'session' },
+ });
+ });
+
+ it('serves the stored user for non-session credentials and refreshes sessions', async () => {
+ mockCallCoreRpc.mockResolvedValueOnce({
+ result: { isAuthenticated: true, credential: 'local', user: { id: 'l' } },
+ });
+ expect(await owner.fetchCurrentUser()).toEqual({
+ user: { id: 'l' },
+ stale: false,
+ staleSeconds: null,
+ });
+
+ mockCallCoreRpc
+ .mockResolvedValueOnce({
+ result: { isAuthenticated: true, credential: 'session', user: { id: 'old' } },
+ })
+ .mockResolvedValueOnce({ result: { token: 'jwt' } });
+ fetchMock.mockResolvedValueOnce(jsonResponse(200, { success: true, user: { id: 'fresh' } }));
+ expect(await owner.fetchCurrentUser()).toEqual({
+ user: { id: 'fresh' },
+ stale: false,
+ staleSeconds: 0,
+ });
+ });
+
+ it('clears the session and rethrows when /auth/me rejects the stored token', async () => {
+ mockCallCoreRpc
+ .mockResolvedValueOnce({
+ result: { isAuthenticated: true, credential: 'session', user: null },
+ })
+ .mockResolvedValueOnce({ result: { token: 'jwt' } })
+ .mockResolvedValueOnce({ result: {} });
+ fetchMock.mockResolvedValueOnce(jsonResponse(401, {}));
+
+ await expect(owner.fetchCurrentUser()).rejects.toThrow(/^REJECTED:/);
+ expect(mockCallCoreRpc).toHaveBeenLastCalledWith({
+ method: 'openhuman.auth_clear_credential',
+ params: { kind: 'session' },
+ });
+ });
+
+ it('serves the stored user flagged stale when the backend is down', async () => {
+ mockCallCoreRpc
+ .mockResolvedValueOnce({
+ result: { isAuthenticated: true, credential: 'session', user: { id: 'old' } },
+ })
+ .mockResolvedValueOnce({ result: { token: 'jwt' } });
+ fetchMock.mockRejectedValueOnce(new Error('fetch failed'));
+
+ expect(await owner.fetchCurrentUser()).toEqual({
+ user: { id: 'old' },
+ stale: true,
+ staleSeconds: null,
+ });
+ });
+});
+
+describe('sessionErrorKind', () => {
+ it('classifies by stable prefix', () => {
+ expect(owner.sessionErrorKind('REJECTED: x')).toBe('rejected');
+ expect(owner.sessionErrorKind('EXPIRED: x')).toBe('expired');
+ expect(owner.sessionErrorKind('TRANSIENT: x')).toBe('transient');
+ expect(owner.sessionErrorKind('CONSUME_FAILED: x')).toBe('consume_failed');
+ expect(owner.sessionErrorKind('CORE: x')).toBe('core');
+ expect(owner.sessionErrorKind('BACKEND: x')).toBe('core');
+ expect(owner.sessionErrorKind('USER_ID_UNAVAILABLE: x')).toBe('user_id');
+ expect(owner.sessionErrorKind('something else')).toBe('other');
+ });
+});
diff --git a/app/src/services/session/__tests__/shellSessionEvents.test.ts b/app/src/services/session/__tests__/shellSessionEvents.test.ts
new file mode 100644
index 0000000000..0573b71ec8
--- /dev/null
+++ b/app/src/services/session/__tests__/shellSessionEvents.test.ts
@@ -0,0 +1,53 @@
+import { listen } from '@tauri-apps/api/event';
+import { beforeEach, describe, expect, it, type Mock, vi } from 'vitest';
+
+import { useShellSessionOwner } from '../sessionOwner';
+import { installShellSessionEventBridge } from '../shellSessionEvents';
+
+const mockListen = listen as Mock;
+
+describe('installShellSessionEventBridge', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ });
+
+ it('does nothing when the shell is not the session owner', () => {
+ vi.mocked(useShellSessionOwner).mockReturnValue(false);
+ const dispose = installShellSessionEventBridge({ onChanged: vi.fn() });
+ expect(mockListen).not.toHaveBeenCalled();
+ dispose();
+ });
+
+ it('re-dispatches auth://expired as a confirmed session-expired window event', async () => {
+ vi.mocked(useShellSessionOwner).mockReturnValue(true);
+ const handlers = new Map<string, (event: { payload: unknown }) => void>();
+ const unlisten = vi.fn();
+ mockListen.mockImplementation(
+ async (name: string, handler: (event: { payload: unknown }) => void) => {
+ handlers.set(name, handler);
+ return unlisten;
+ }
+ );
+ const onChanged = vi.fn();
+ const expired = vi.fn();
+ window.addEventListener('openhuman:session-expired', expired);
+
+ const dispose = installShellSessionEventBridge({ onChanged });
+ await Promise.resolve();
+ await Promise.resolve();
+
+ handlers.get('auth://expired')?.({ payload: { source: 'auth/me' } });
+ expect(expired).toHaveBeenCalledTimes(1);
+ expect((expired.mock.calls[0][0] as CustomEvent).detail).toEqual({
+ source: 'shell.auth/me',
+ reason: 'confirmed',
+ });
+
+ handlers.get('auth://changed')?.({ payload: {} });
+ expect(onChanged).toHaveBeenCalledTimes(1);
+
+ dispose();
+ expect(unlisten).toHaveBeenCalledTimes(2);
+ window.removeEventListener('openhuman:session-expired', expired);
+ });
+});
diff --git a/app/src/utils/__tests__/desktopDeepLinkListener.test.ts b/app/src/utils/__tests__/desktopDeepLinkListener.test.ts
index 1eb5503d09..ffcff2d6db 100644
--- a/app/src/utils/__tests__/desktopDeepLinkListener.test.ts
+++ b/app/src/utils/__tests__/desktopDeepLinkListener.test.ts
@@ -4,6 +4,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest';
import { confirmWaitlistDownload } from '../../services/api/waitlistApi';
import { clearCoreRpcTokenCache, clearCoreRpcUrlCache } from '../../services/coreRpcClient';
+import { loginWithToken, storeSessionToken } from '../../services/session/sessionOwner';
import {
completeDeepLinkAuthProcessing,
getDeepLinkAuthState,
@@ -20,7 +21,6 @@ import {
import { BILLING_DASHBOARD_URL } from '../links';
import { openUrl } from '../openUrl';
import { getSessionToken } from '../tauriCommands';
-import { loginWithToken, storeSessionToken } from '../../services/session/sessionOwner';
vi.mock('../configPersistence', () => ({ getStoredCoreMode: vi.fn() }));
vi.mock('../../services/coreRpcClient', () => ({
@@ -269,7 +269,9 @@ describe('desktopDeepLinkListener', () => {
});
it('hands the token to the session owner exactly once — retries live in the owner', async () => {
- vi.mocked(storeSessionToken).mockReset().mockRejectedValueOnce(new Error('TRANSIENT: timed out'));
+ vi.mocked(storeSessionToken)
+ .mockReset()
+ .mockRejectedValueOnce(new Error('TRANSIENT: timed out'));
const state = registerAuthDeepLinkState();
const url = `openhuman://auth?token=no-retry-token&key=auth&state=${state}`;