import { beforeEach, describe, expect, it, vi } from 'vitest'; const entries = new Map(); const keytar = vi.hoisted(() => ({ getPassword: vi.fn(), setPassword: vi.fn() })); vi.mock('../src/keyring.js', () => ({ getKeytar: async () => keytar })); import { loadAgentCredentials, saveAgentCredentials } from '../src/agent-credentials.js'; const credentials = { registrationId: 'reg_1', issuer: 'https://auth.example.com', assertion: 'assertion', claimToken: 'claim', }; describe('agent credentials', () => { beforeEach(() => { entries.clear(); vi.resetAllMocks(); keytar.getPassword.mockImplementation( async (service, account) => entries.get(`${service}/${account}`) ?? null ); keytar.setPassword.mockImplementation(async (service, account, value) => { entries.set(`${service}/${account}`, value); }); }); it('isolates projects and environments from each other and human credentials', async () => { await saveAgentCredentials('https://api.example.com', '/docs', credentials); expect(await loadAgentCredentials('https://api.example.com', '/docs')).toEqual(credentials); expect(await loadAgentCredentials('https://dev.example.com', '/docs')).toBeNull(); expect(await loadAgentCredentials('https://api.example.com', '/other')).toBeNull(); expect([...entries.keys()].every((key) => key.startsWith('mintlify-agent/'))).toBe(true); }); it('retains old registrations when the current project starts a new site', async () => { await saveAgentCredentials('https://api.example.com', '/docs', credentials); await saveAgentCredentials('https://api.example.com', '/docs', { ...credentials, registrationId: 'reg_2', }); expect((await loadAgentCredentials('https://api.example.com', '/docs'))?.registrationId).toBe( 'reg_2' ); expect(entries.has('mintlify-agent/https://api.example.com:reg_1')).toBe(true); }); it('does not switch the project pointer when storing the credential fails', async () => { keytar.setPassword.mockRejectedValueOnce(new Error('locked')); await expect( saveAgentCredentials('https://api.example.com', '/docs', credentials) ).rejects.toThrow('locked'); expect(keytar.setPassword).toHaveBeenCalledTimes(1); }); it('preserves read failures instead of treating them as an absent registration', async () => { keytar.getPassword.mockRejectedValueOnce(new Error('locked')); await expect(loadAgentCredentials('https://api.example.com', '/docs')).rejects.toThrow( 'locked' ); }); });