Voice-to-text dictation app with local (Nvidia Parakeet/Whisper) and cloud models (BYOK). Privacy-first and available cross-platform.
JavaScript aianthropiccross-platformgeminigroqlinuxmacosnvidiaopen-sourceopenaiparakeetspeech-to-texttranscribewhisperwindows
import AsyncStorage from '@react-native-async-storage/async-storage';
import { useAffiliateStore } from '../useAffiliateStore';
import { useAuthStore } from '../useAuthStore';
import { useConfigStore } from '../useConfigStore';
import { AffiliateInputError, getAffiliateClientConfig } from '@/lib/affiliateLink';
import { ApiError } from '@/lib/apiClient';
import { checkAndClaimAffiliate } from '@/lib/affiliateAttribution';
jest.mock('@react-native-async-storage/async-storage', () => ({
getItem: jest.fn(),
setItem: jest.fn().mockResolvedValue(undefined),
}));
jest.mock('../useAuthStore', () => ({ useAuthStore: { getState: jest.fn() } }));
jest.mock('../useConfigStore', () => ({ useConfigStore: { getState: jest.fn() } }));
jest.mock('@/lib/affiliateLink', () => ({
getAffiliateClientConfig: jest.fn(),
AffiliateInputError: class MockAffiliateInputError extends Error {},
}));
jest.mock('@/lib/affiliateAttribution', () => ({
checkAndClaimAffiliate: jest.fn(),
AffiliateConsentError: class AffiliateConsentError extends Error {},
}));
jest.mock('@/lib/apiClient', () => ({
ApiError: class MockApiError extends Error {
status: number;
constructor(message: string, status: number) {
super(message);
this.status = status;
}
},
}));
const claim = jest.mocked(checkAndClaimAffiliate);
let auth: { user: { id: string } | null; sessionCookie: string | null; isInitialized: boolean };
let config: { usageAnalyticsEnabled?: boolean };
beforeEach(async () => {
jest.clearAllMocks();
jest
.mocked(getAffiliateClientConfig)
.mockReturnValue({ domain: 'sandbox.dub.link', publishableKey: 'dub_pk_test' });
auth = { user: { id: 'anonymous-a' }, sessionCookie: 'session-a', isInitialized: true };
config = { usageAnalyticsEnabled: true };
jest
.mocked(useAuthStore.getState)
.mockImplementation(() => auth as ReturnType<typeof useAuthStore.getState>);
jest
.mocked(useConfigStore.getState)
.mockImplementation(() => ({ config }) as ReturnType<typeof useConfigStore.getState>);
useAffiliateStore.setState({
ownerId: 'anonymous-a',
ownerAnonymous: false,
link: '',
clickId: null,
saved: false,
autoSubmit: false,
inboundOfferPending: false,
hydrated: true,
checking: false,
error: null,
});
claim.mockResolvedValue('provisional');
});
it('ordinary continuation performs no affiliate request', async () => {
expect(await useAffiliateStore.getState().prepare()).toBe(true);
expect(claim).not.toHaveBeenCalled();
});
it('editing saves locally and only an explicit prepare claims it', async () => {
await useAffiliateStore.getState().edit('https://sandbox.dub.link/creator');
expect(claim).not.toHaveBeenCalled();
expect(AsyncStorage.setItem).toHaveBeenLastCalledWith(
expect.any(String),
expect.stringContaining('sandbox.dub.link/creator'),
);
expect(await useAffiliateStore.getState().prepare()).toBe(true);
expect(useAffiliateStore.getState().saved).toBe(true);
expect(claim.mock.calls[0][2]).toBe('session-a');
});
it('navigation cancellation reaches the claim guard, and a claim the server accepted stays saved', async () => {
let current = true;
let finish!: (status: 'provisional') => void;
claim.mockImplementationOnce(
() =>
new Promise((resolve) => {
finish = resolve;
}),
);
await useAffiliateStore.getState().edit('https://sandbox.dub.link/creator');
const pending = useAffiliateStore.getState().prepare(() => current);
await new Promise<void>((resolve) => setImmediate(resolve));
expect(claim.mock.calls[0][3]()).toBe(true);
current = false;
expect(claim.mock.calls[0][3]()).toBe(false);
finish('provisional');
expect(await pending).toBe(false);
expect(useAffiliateStore.getState()).toMatchObject({ saved: true, checking: false });
expect(await useAffiliateStore.getState().prepare()).toBe(true);
expect(claim).toHaveBeenCalledTimes(1);
});
it('drops a server answer that arrives after an account switch', async () => {
let finish!: (status: 'provisional') => void;
claim.mockImplementationOnce(
() =>
new Promise((resolve) => {
finish = resolve;
}),
);
await useAffiliateStore.getState().edit('https://sandbox.dub.link/creator');
const pending = useAffiliateStore.getState().prepare();
await new Promise<void>((resolve) => setImmediate(resolve));
auth = { user: { id: 'account-b' }, sessionCookie: 'session-b', isInitialized: true };
finish('provisional');
expect(await pending).toBe(false);
expect(useAffiliateStore.getState().saved).toBe(false);
});
it('carries an unclaimed link from an anonymous session into the account it becomes', async () => {
auth = {
user: { id: 'anonymous-a', isAnonymous: true },
sessionCookie: 'session-a',
isInitialized: true,
} as typeof auth;
await useAffiliateStore.getState().edit('https://sandbox.dub.link/creator', true);
auth = { user: { id: 'account-b' }, sessionCookie: 'session-b', isInitialized: true };
await useAffiliateStore.getState().bindSession();
expect(useAffiliateStore.getState()).toMatchObject({
ownerId: 'account-b',
ownerAnonymous: false,
link: 'https://sandbox.dub.link/creator',
autoSubmit: true,
inboundOfferPending: true,
});
});
it('never carries a link between two real accounts, or a claimed one out of an anonymous session', async () => {
await useAffiliateStore.getState().edit('https://sandbox.dub.link/creator');
auth = { user: { id: 'account-b' }, sessionCookie: 'session-b', isInitialized: true };
await useAffiliateStore.getState().bindSession();
expect(useAffiliateStore.getState()).toMatchObject({ ownerId: 'account-b', link: '' });
auth = {
user: { id: 'anonymous-c', isAnonymous: true },
sessionCookie: 'session-c',
isInitialized: true,
} as typeof auth;
useAffiliateStore.setState({ ownerId: 'anonymous-c', ownerAnonymous: true });
await useAffiliateStore.getState().edit('https://sandbox.dub.link/creator');
expect(await useAffiliateStore.getState().prepare()).toBe(true);
auth = { user: { id: 'account-d' }, sessionCookie: 'session-d', isInitialized: true };
await useAffiliateStore.getState().bindSession();
expect(useAffiliateStore.getState()).toMatchObject({
ownerId: 'account-d',
link: '',
saved: false,
});
});
it('does not start collection if the caller has already left', async () => {
await useAffiliateStore.getState().edit('https://sandbox.dub.link/creator');
expect(await useAffiliateStore.getState().prepare(() => false)).toBe(false);
expect(claim).not.toHaveBeenCalled();
});
it('checking twice makes one claim and an offline failure retains input for retry or clearing', async () => {
let reject!: (error: Error) => void;
claim.mockImplementation(
() =>
new Promise((_, fail) => {
reject = fail;
}),
);
await useAffiliateStore.getState().edit('https://sandbox.dub.link/creator');
const first = useAffiliateStore.getState().prepare();
await Promise.resolve();
expect(await useAffiliateStore.getState().prepare()).toBe(false);
reject(new Error('offline'));
expect(await first).toBe(false);
expect(claim).toHaveBeenCalledTimes(1);
expect(useAffiliateStore.getState().link).toContain('/creator');
expect(useAffiliateStore.getState().error).toBe('We couldn’t check your link. Try again.');
await useAffiliateStore.getState().edit('');
expect(await useAffiliateStore.getState().prepare()).toBe(true);
});
it('a previous account response cannot claim or persist for the next account', async () => {
let finish!: (status: 'provisional') => void;
claim.mockImplementation(
() =>
new Promise((resolve) => {
finish = resolve;
}),
);
await useAffiliateStore.getState().edit('https://sandbox.dub.link/creator');
const pending = useAffiliateStore.getState().prepare();
await new Promise<void>((resolve) => setImmediate(resolve));
auth = { ...auth, user: { id: 'account-b' }, sessionCookie: 'session-b' };
await useAffiliateStore.getState().bindSession();
expect(claim.mock.calls[0][3]()).toBe(false);
finish('provisional');
expect(await pending).toBe(false);
expect(useAffiliateStore.getState()).toMatchObject({
ownerId: 'account-b',
link: '',
saved: false,
checking: false,
});
});
it('signout clears a saved referral and hydration cannot restore another account’s candidate', async () => {
useAffiliateStore.setState({ link: 'https://sandbox.dub.link/creator', saved: true });
auth = { ...auth, user: null, sessionCookie: null };
await useAffiliateStore.getState().bindSession();
expect(useAffiliateStore.getState()).toMatchObject({ link: '', saved: false, ownerId: null });
jest.mocked(AsyncStorage.getItem).mockResolvedValue(
JSON.stringify({
ownerId: 'old-user',
link: 'https://sandbox.dub.link/old',
clickId: 'click',
saved: true,
autoSubmit: false,
}),
);
useAffiliateStore.setState({ hydrated: false });
await useAffiliateStore.getState().hydrate();
await useAffiliateStore.getState().bindSession();
expect(useAffiliateStore.getState().link).toBe('');
});
it('persists the resolved click before claiming and reuses it after a failed claim', async () => {
await useAffiliateStore.getState().edit('https://sandbox.dub.link/creator');
claim.mockImplementationOnce(async (_link, _click, _cookie, _current, remember) => {
await remember('click-once');
throw new Error('claim response lost');
});
expect(await useAffiliateStore.getState().prepare()).toBe(false);
expect(useAffiliateStore.getState().clickId).toBe('click-once');
expect(await useAffiliateStore.getState().prepare()).toBe(true);
expect(claim.mock.calls[1][1]).toBe('click-once');
});
it('analytics refusal prevents collection and review does not show saved success', async () => {
await useAffiliateStore.getState().edit('https://sandbox.dub.link/creator');
config.usageAnalyticsEnabled = false;
expect(await useAffiliateStore.getState().prepare()).toBe(false);
expect(claim).not.toHaveBeenCalled();
config.usageAnalyticsEnabled = true;
claim.mockResolvedValue('review');
expect(await useAffiliateStore.getState().prepare()).toBe(false);
expect(useAffiliateStore.getState().saved).toBe(false);
});
it('claims on the default Usage Analytics setting', async () => {
delete config.usageAnalyticsEnabled;
await useAffiliateStore.getState().edit('https://sandbox.dub.link/creator');
expect(await useAffiliateStore.getState().prepare()).toBe(true);
expect(claim).toHaveBeenCalledTimes(1);
});
it.each([
['an invalid entry', () => new AffiliateInputError(), 'Enter your exact creator code'],
[
'an unavailable link',
() => new ApiError('unavailable', 400),
'This creator link is unavailable',
],
])('stops retrying an inbound link refused as %s', async (_, makeError, message) => {
claim.mockRejectedValue(makeError());
await useAffiliateStore.getState().edit('https://sandbox.dub.link/demo', true);
expect(await useAffiliateStore.getState().prepare()).toBe(false);
expect(useAffiliateStore.getState().error).toContain(message);
expect(useAffiliateStore.getState()).toMatchObject({
autoSubmit: false,
inboundOfferPending: false,
});
});
it('stops retrying an inbound link the server sends to review', async () => {
claim.mockResolvedValue('review');
await useAffiliateStore.getState().edit('https://sandbox.dub.link/demo', true);
expect(await useAffiliateStore.getState().prepare()).toBe(false);
expect(useAffiliateStore.getState()).toMatchObject({
saved: false,
autoSubmit: false,
inboundOfferPending: false,
});
});
it('keeps retrying an inbound link after a transient failure', async () => {
claim.mockRejectedValue(new Error('offline'));
await useAffiliateStore.getState().edit('https://sandbox.dub.link/demo', true);
expect(await useAffiliateStore.getState().prepare()).toBe(false);
expect(useAffiliateStore.getState().autoSubmit).toBe(true);
});
it('disabling affiliate configuration never blocks ordinary onboarding with a cached link', async () => {
await useAffiliateStore.getState().edit('https://sandbox.dub.link/creator');
jest.mocked(getAffiliateClientConfig).mockReturnValue(null);
expect(await useAffiliateStore.getState().prepare()).toBe(true);
expect(claim).not.toHaveBeenCalled();
});
it('keeps inbound intent after claiming, consumes it once, and does not invent it for typing', async () => {
await useAffiliateStore.getState().edit('demo');
expect(await useAffiliateStore.getState().consumeInboundOffer(() => true)).toBe(false);
expect(claim).not.toHaveBeenCalled();
await useAffiliateStore.getState().edit('https://sandbox.dub.link/demo', true);
await useAffiliateStore.getState().prepare();
expect(useAffiliateStore.getState()).toMatchObject({
saved: true,
autoSubmit: false,
inboundOfferPending: true,
});
const results = await Promise.all([
useAffiliateStore.getState().consumeInboundOffer(() => true),
useAffiliateStore.getState().consumeInboundOffer(() => true),
]);
expect(results.filter(Boolean)).toHaveLength(1);
expect(claim).toHaveBeenCalledTimes(1);
});
it('retains refused inbound intent and cannot consume it after navigation or account changes', async () => {
await useAffiliateStore.getState().edit('https://sandbox.dub.link/demo', true);
config.usageAnalyticsEnabled = false;
expect(await useAffiliateStore.getState().consumeInboundOffer(() => true)).toBe(false);
expect(claim).not.toHaveBeenCalled();
expect(useAffiliateStore.getState().inboundOfferPending).toBe(true);
expect(await useAffiliateStore.getState().consumeInboundOffer(() => false)).toBe(false);
auth.user = { id: 'other' };
expect(await useAffiliateStore.getState().consumeInboundOffer(() => true)).toBe(false);
expect(useAffiliateStore.getState().inboundOfferPending).toBe(false);
});
it('old persisted candidates do not acquire a new inbound offer intent', async () => {
jest.mocked(AsyncStorage.getItem).mockResolvedValue(
JSON.stringify({
ownerId: 'anonymous-a',
link: 'https://sandbox.dub.link/demo',
clickId: 'fixture',
saved: true,
autoSubmit: false,
}),
);
useAffiliateStore.setState({ hydrated: false });
await useAffiliateStore.getState().hydrate();
expect(useAffiliateStore.getState().inboundOfferPending).toBe(false);
});
it('waits for the arrival claim without making a second one', async () => {
let finish!: (status: 'provisional') => void;
claim.mockImplementationOnce(
() =>
new Promise((resolve) => {
finish = resolve;
}),
);
await useAffiliateStore.getState().edit('https://sandbox.dub.link/demo', true);
const preparing = useAffiliateStore.getState().prepare();
await new Promise<void>((resolve) => setImmediate(resolve));
const consuming = useAffiliateStore.getState().consumeInboundOffer(() => true);
await new Promise<void>((resolve) => setImmediate(resolve));
expect(claim).toHaveBeenCalledTimes(1);
finish('provisional');
await preparing;
expect(await consuming).toBe(true);
});