diff --git a/apps/mobile-rn/__tests__/abort-and-stream-guards.test.ts b/apps/mobile-rn/__tests__/abort-and-stream-guards.test.ts new file mode 100644 index 0000000..dbfab38 --- /dev/null +++ b/apps/mobile-rn/__tests__/abort-and-stream-guards.test.ts @@ -0,0 +1,87 @@ +import { + AdminServiceError, + listAdminUsers, +} from '../src/features/admin/admin-service' +import { + ChatServiceError, + sendChatMessage, +} from '../src/features/chat/chat-service' +import { streamTalkResponse } from '../src/features/talk/llm-stream-service' + +const originalFetch = global.fetch + +afterEach(() => { + global.fetch = originalFetch + jest.restoreAllMocks() + jest.useRealTimers() +}) + +describe('abort and streaming lifecycle guards', () => { + test('sendChatMessage_이미중단된시그널전달시_fetch없이즉시CANCELLED거부', async () => { + const fetchMock = jest.fn() + global.fetch = fetchMock + const controller = new AbortController() + controller.abort() + + await expect( + sendChatMessage([{ role: 'user', content: 'hello' }], { + accessToken: 'signed-access-token', + timeoutMs: 60_000, + signal: controller.signal, + }), + ).rejects.toMatchObject({ + name: 'ChatServiceError', + code: 'CANCELLED', + retryable: false, + }) + expect(fetchMock).not.toHaveBeenCalled() + expect(ChatServiceError.name).toBe('ChatServiceError') + }) + + test('adminService_이미중단된시그널전달시_비재시도네트워크오류로즉시거부', async () => { + const fetchMock = jest.fn() + global.fetch = fetchMock + const controller = new AbortController() + controller.abort() + + await expect( + listAdminUsers({ + accessToken: 'authenticated-admin-access-token', + signal: controller.signal, + }), + ).rejects.toMatchObject({ + code: 'network', + retryable: false, + }) + expect(fetchMock).not.toHaveBeenCalled() + expect(AdminServiceError.name).toBe('AdminServiceError') + }) + + test('streamTalkResponse_생성영수증ID누락시_응답스트림을취소하고실패종료', async () => { + const cancelMock = jest.fn(async () => undefined) + global.fetch = jest.fn().mockResolvedValue({ + ok: true, + status: 200, + headers: { + get: (name: string) => ( + name.toLowerCase() === 'content-type' ? 'text/event-stream' : null + ), + }, + body: { + cancel: cancelMock, + getReader: () => ({ + read: async () => ({ done: true, value: undefined }), + releaseLock: jest.fn(), + }), + }, + } as unknown as Response) + + await expect( + streamTalkResponse([{ role: 'user', content: 'hello' }], { + accessToken: 'signed-talk-token', + onTextDelta: jest.fn(), + }), + ).rejects.toMatchObject({ code: 'INVALID_RESPONSE', retryable: true }) + expect(cancelMock).toHaveBeenCalledTimes(1) + }) +}) diff --git a/apps/mobile-rn/__tests__/context-lifecycle-guards.test.tsx b/apps/mobile-rn/__tests__/context-lifecycle-guards.test.tsx new file mode 100644 index 0000000..17eacb5 --- /dev/null +++ b/apps/mobile-rn/__tests__/context-lifecycle-guards.test.tsx @@ -0,0 +1,467 @@ +import React from 'react' +import ReactTestRenderer, { act } from 'react-test-renderer' +import AsyncStorage from '@react-native-async-storage/async-storage' +import { Platform } from 'react-native' + +const USER_A = '11111111-1111-4111-8111-111111111111' +const USER_B = '22222222-2222-4222-8222-222222222222' +const PRODUCT_ID = 'd3ro_voice_pro_monthly' + +let mockAuthState: { + user: { id: string } | null + purgeLocalSession: jest.Mock +} = { + user: { id: USER_A }, + purgeLocalSession: jest.fn(async () => undefined), +} + +const mockEntitlementHookValue = { + loading: false, + stale: false, + error: null, + snapshot: { + tier: 'free', + adFree: false, + overageCredits: 0, + provider: 'none', + storeProductId: null, + }, + refresh: jest.fn, []>(async () => null), +} + +const mockFrom = jest.fn() +const mockFunctionsInvoke = jest.fn() + +jest.mock('../src/lib/auth-context', () => ({ + useAuth: () => mockAuthState, +})) +jest.mock('../src/lib/entitlement-context', () => { + const actual = jest.requireActual('../src/lib/entitlement-context') as typeof import('../src/lib/entitlement-context') + return { + ...actual, + useEntitlement: jest.fn(() => mockEntitlementHookValue), + } +}) +jest.mock('../src/lib/native-config', () => ({ + getMobileRuntimeConfig: jest.fn(() => ({ + debug: true, + installedFromPlayStore: true, + adMobBannerUnitId: 'ca-app-pub-3940256099942544/6300978111', + adMobRewardedUnitId: 'ca-app-pub-3940256099942544/5224354917', + })), +})) +jest.mock('../src/lib/supabase', () => ({ + supabase: { + from: (...args: unknown[]) => mockFrom(...args), + functions: { + invoke: (...args: unknown[]) => mockFunctionsInvoke(...args), + }, + channel: jest.fn(() => ({ + on: jest.fn().mockReturnThis(), + subscribe: jest.fn().mockReturnThis(), + })), + removeChannel: jest.fn(async () => 'ok'), + }, +})) + +const mockedEntitlement = jest.requireMock('../src/lib/entitlement-context') as { + useEntitlement: jest.Mock + EntitlementProvider: typeof import('../src/lib/entitlement-context').EntitlementProvider +} +const mockedAds = jest.requireActual('react-native-google-mobile-ads') as { + AdsConsent: { + gatherConsent: jest.Mock + getConsentInfo: jest.Mock + showPrivacyOptionsForm: jest.Mock + } + MobileAds: jest.Mock + useRewardedAd: jest.Mock +} +const mockedIap = jest.requireActual('react-native-iap') as { + useIAP: jest.Mock + __stableUseIapResult: Record & { + onPurchaseSuccess?: (purchase: unknown) => void + } +} + +import { MobileAdsProvider, useMobileAds, useRewardedCredits } from '../src/lib/mobile-ads-context' +import { BillingProvider, useBilling } from '../src/lib/billing-context' +import { DeviceProvider, useDevice } from '../src/lib/device-context' +import { DeviceServiceError, registerCurrentDevice } from '../src/features/devices/device-service' + +function deferred() { + let resolve: (value: T) => void = () => undefined + let reject: (reason?: unknown) => void = () => undefined + const promise = new Promise((res, rej) => { + resolve = res + reject = rej + }) + return { promise, resolve, reject } +} + +async function flushMicrotasks(): Promise { + for (let index = 0; index < 8; index += 1) await Promise.resolve() +} + +describe('context lifecycle and concurrency guards', () => { + const originalPlatform = Platform.OS + let activeRenderer: ReactTestRenderer.ReactTestRenderer | null = null + + beforeAll(() => { + Object.defineProperty(Platform, 'OS', { configurable: true, value: 'android' }) + }) + + afterAll(() => { + Object.defineProperty(Platform, 'OS', { configurable: true, value: originalPlatform }) + }) + + beforeEach(async () => { + await AsyncStorage.clear() + mockAuthState = { + user: { id: USER_A }, + purgeLocalSession: jest.fn(async () => undefined), + } + mockEntitlementHookValue.loading = false + mockEntitlementHookValue.stale = false + mockEntitlementHookValue.error = null + mockEntitlementHookValue.snapshot = { + tier: 'free', + adFree: false, + overageCredits: 0, + provider: 'none', + storeProductId: null, + } + mockEntitlementHookValue.refresh = jest.fn(async () => null) + mockedEntitlement.useEntitlement.mockImplementation(() => mockEntitlementHookValue) + mockFrom.mockReset() + mockFunctionsInvoke.mockReset() + mockedAds.AdsConsent.gatherConsent.mockReset().mockResolvedValue({ + canRequestAds: true, + privacyOptionsRequirementStatus: 'NOT_REQUIRED', + }) + mockedAds.AdsConsent.getConsentInfo.mockReset().mockResolvedValue({ + canRequestAds: true, + privacyOptionsRequirementStatus: 'NOT_REQUIRED', + }) + mockedAds.MobileAds.mockReset().mockImplementation(() => ({ + initialize: jest.fn(async () => []), + setRequestConfiguration: jest.fn(async () => undefined), + })) + mockedIap.__stableUseIapResult.connected = true + mockedIap.__stableUseIapResult.subscriptions = [] + mockedIap.useIAP.mockImplementation(() => mockedIap.__stableUseIapResult) + }) + + afterEach(() => { + if (activeRenderer !== null) { + const target = activeRenderer + activeRenderer = null + act(() => target.unmount()) + } + jest.restoreAllMocks() + jest.useRealTimers() + }) + + test('MobileAdsProvider_광고초기화중비대상전환시_ready로덮어쓰지않음', async () => { + const initGate = deferred() + mockedAds.MobileAds.mockImplementation(() => ({ + setRequestConfiguration: jest.fn(async () => undefined), + initialize: jest.fn(() => initGate.promise), + })) + + let latestAds: ReturnType | null = null + function Probe(): null { + latestAds = useMobileAds() + return null + } + + let renderer!: ReactTestRenderer.ReactTestRenderer + await act(async () => { + renderer = ReactTestRenderer.create( + , + ) + activeRenderer = renderer + await flushMicrotasks() + }) + expect(latestAds?.status).toBe('initializing') + + // User upgrades to Pro (adFree: true -> eligible: false) while MobileAds().initialize() is pending. + mockEntitlementHookValue.snapshot = { + ...mockEntitlementHookValue.snapshot, + tier: 'pro', + adFree: true, + } + await act(async () => { + renderer.update() + await flushMicrotasks() + }) + expect(latestAds?.status).toBe('disabled') + + await act(async () => { + initGate.resolve([]) + await flushMicrotasks() + }) + + expect(latestAds?.status).toBe('disabled') + act(() => renderer.unmount()) + }) + + test('useRewardedCredits_entitlement갱신중재시도시_이전검증완료상태로덮어쓰지않음', async () => { + jest.useFakeTimers() + let latestRewarded: ReturnType | null = null + mockedAds.useRewardedAd.mockImplementation(() => ({ + error: undefined, + isClosed: false, + isEarnedReward: true, + isLoaded: true, + isShowing: false, + load: jest.fn(), + show: jest.fn(), + })) + mockFrom.mockImplementation(() => ({ + select: jest.fn().mockReturnThis(), + eq: jest.fn().mockReturnThis(), + maybeSingle: jest.fn(async () => ({ data: { overage_credits: 5 }, error: null })), + })) + const refreshGate = deferred() + mockEntitlementHookValue.refresh = jest.fn(() => refreshGate.promise) + + function Probe(): null { + latestRewarded = useRewardedCredits() + return null + } + + let renderer!: ReactTestRenderer.ReactTestRenderer + await act(async () => { + renderer = ReactTestRenderer.create( + , + ) + activeRenderer = renderer + await flushMicrotasks() + }) + + await act(async () => { + await jest.advanceTimersByTimeAsync(1_200) + await flushMicrotasks() + }) + expect(mockEntitlementHookValue.refresh).toHaveBeenCalledTimes(1) + + // Call reload() while entitlement.refresh() is still in flight. + act(() => { + latestRewarded?.reload() + }) + expect(latestRewarded?.status).toBe('loading') + + await act(async () => { + refreshGate.resolve(null) + await flushMicrotasks() + }) + + expect(latestRewarded?.status).toBe('loading') + act(() => renderer.unmount()) + }) + + test('BillingProvider_결제요청중계정전환시_이전계정오류로상태를덮어쓰지않음', async () => { + const requestPurchaseGate = deferred() + mockedIap.__stableUseIapResult.subscriptions = [{ + id: PRODUCT_ID, + platform: 'android', + title: 'Pro Monthly', + description: 'Pro', + displayPrice: '$9.99', + subscriptionOffers: [{ + offerTokenAndroid: 'offer-token-1', + displayPrice: '$9.99', + basePlanIdAndroid: 'monthly', + offerTagsAndroid: ['default'], + }], + }] + mockedIap.__stableUseIapResult.getAvailablePurchases = jest.fn(async () => []) + mockedIap.__stableUseIapResult.requestPurchase = jest.fn(() => requestPurchaseGate.promise) + + let latestBilling: ReturnType | null = null + function Probe(): null { + latestBilling = useBilling() + return null + } + + let renderer!: ReactTestRenderer.ReactTestRenderer + await act(async () => { + renderer = ReactTestRenderer.create( + , + ) + activeRenderer = renderer + await flushMicrotasks() + }) + + let pendingPurchase: Promise = Promise.resolve() + act(() => { + pendingPurchase = latestBilling!.purchase(PRODUCT_ID).catch(() => undefined) + }) + await flushMicrotasks() + expect(latestBilling?.operation).toBe('purchasing') + + // Account switches from USER_A to USER_B while Google Play purchase flow is pending. + mockAuthState.user = { id: USER_B } + await act(async () => { + renderer.update() + await flushMicrotasks() + }) + expect(latestBilling?.operation).toBe('idle') + + await act(async () => { + requestPurchaseGate.reject(new Error('billing unavailable')) + await pendingPurchase + await flushMicrotasks() + }) + + expect(latestBilling?.operation).toBe('idle') + expect(latestBilling?.errorCode).toBe(null) + activeRenderer = null + act(() => renderer.unmount()) + }) + + test('DeviceProvider_세션파기실패후재시도시_복구호출을영구차단하지않음', async () => { + mockAuthState.purgeLocalSession + .mockRejectedValueOnce(new Error('storage busy')) + .mockResolvedValueOnce(undefined) + + const revokedRow = { + id: 'device-1', + user_id: USER_A, + installation_id: '00000000-0000-4000-8000-000000000001', + platform: 'android', + device_name: 'Pixel 8', + app_version: '1.0.0', + os_version: 'Android 14', + push_token: null, + last_seen_at: '2026-08-21T00:00:00Z', + revoked_at: '2026-08-21T00:00:05Z', + created_at: '2026-08-20T00:00:00Z', + updated_at: '2026-08-21T00:00:05Z', + } + mockFrom.mockImplementation(() => ({ + select: jest.fn().mockReturnThis(), + eq: jest.fn().mockReturnThis(), + maybeSingle: jest.fn(async () => ({ data: revokedRow, error: null })), + update: jest.fn().mockReturnThis(), + single: jest.fn(async () => ({ data: revokedRow, error: null })), + })) + + let latestDevice: ReturnType | null = null + function Probe(): null { + latestDevice = useDevice() + return null + } + + let renderer!: ReactTestRenderer.ReactTestRenderer + await act(async () => { + renderer = ReactTestRenderer.create( + , + ) + activeRenderer = renderer + await flushMicrotasks() + }) + + expect(mockAuthState.purgeLocalSession).toHaveBeenCalledTimes(1) + + await act(async () => { + await latestDevice?.refreshCurrentDevice() + }) + + expect(mockAuthState.purgeLocalSession).toHaveBeenCalledTimes(2) + act(() => renderer.unmount()) + }) + + test('registerCurrentDevice_23505충돌반복시_무한재귀없이실패종료', async () => { + const maybeSingle = jest.fn(async () => ({ data: null, error: null })) + let attempts = 0 + const single = jest.fn(async () => { + attempts += 1 + if (attempts <= 5) { + return { + data: null, + error: { code: '23505', message: 'duplicate key value violates unique constraint' }, + } + } + return { + data: { + id: 'device-after-loop', + user_id: USER_A, + installation_id: '00000000-0000-4000-8000-000000000001', + platform: 'android', + device_name: 'Pixel 8', + app_version: '1.0.0', + os_version: 'Android 14', + push_token: null, + last_seen_at: '2026-08-21T00:00:00Z', + revoked_at: null, + created_at: '2026-08-20T00:00:00Z', + updated_at: '2026-08-21T00:00:00Z', + }, + error: null, + } + }) + mockFrom.mockImplementation(() => ({ + select: jest.fn().mockReturnThis(), + eq: jest.fn().mockReturnThis(), + maybeSingle, + insert: jest.fn(() => ({ + select: jest.fn(() => ({ single })), + })), + })) + + await expect( + registerCurrentDevice(USER_A, { debug: true, packageName: 'com.d3ro.voice' } as never), + ).rejects.toThrow(DeviceServiceError) + expect(single).toHaveBeenCalledTimes(2) + }) + + test('EntitlementProvider_캐시읽기실패시_미처리거부없이원격갱신진행', async () => { + jest.spyOn(AsyncStorage, 'getItem').mockRejectedValueOnce(new Error('disk I/O failure')) + mockFrom.mockImplementation((table: string) => { + const result = table === 'subscriptions' + ? { data: null, error: null } + : { data: [], error: null } + const builder: Record = { + select: jest.fn(() => builder), + eq: jest.fn(() => builder), + order: jest.fn(() => builder), + limit: jest.fn(() => builder), + maybeSingle: jest.fn(async () => ({ data: null, error: null })), + then: (resolve: (val: unknown) => unknown, reject: (err: unknown) => unknown) => ( + Promise.resolve(result).then(resolve, reject) + ), + } + return builder + }) + + let unhandledError: unknown = null + const onUnhandled = (reason: unknown): void => { + unhandledError = reason + } + process.on('unhandledRejection', onUnhandled) + + const actualModule = jest.requireActual('../src/lib/entitlement-context') as typeof import('../src/lib/entitlement-context') + let latestEnt: ReturnType | null = null + function Probe(): null { + latestEnt = actualModule.useEntitlement() + return null + } + + let renderer!: ReactTestRenderer.ReactTestRenderer + await act(async () => { + renderer = ReactTestRenderer.create( + , + ) + activeRenderer = renderer + await flushMicrotasks() + await new Promise((resolve) => setTimeout(resolve, 0)) + }) + + process.off('unhandledRejection', onUnhandled) + expect(unhandledError).toBe(null) + expect(latestEnt?.loading).toBe(false) + act(() => renderer.unmount()) + }) +}) diff --git a/apps/mobile-rn/__tests__/queue-and-history-races.test.ts b/apps/mobile-rn/__tests__/queue-and-history-races.test.ts new file mode 100644 index 0000000..c5afc7a --- /dev/null +++ b/apps/mobile-rn/__tests__/queue-and-history-races.test.ts @@ -0,0 +1,316 @@ +import React from 'react' +import { act, create, type ReactTestRenderer } from 'react-test-renderer' +import AsyncStorage from '@react-native-async-storage/async-storage' +import { FileSystem } from 'react-native-file-access' +import { + AudioPipelineError, + type AudioPipelineResult, + type LocalAudioInput, +} from '../src/features/import/audio-import-types' +import type { HistoryListEntry, HistoryPageResult } from '../src/features/history/history-service' + +const START_MS = 1_700_000_000_000 +const USER_A = '11111111-1111-4111-8111-111111111111' +const USER_B = '22222222-2222-4222-8222-222222222222' + +const mockProcessAudioInput = jest.fn, [LocalAudioInput, unknown]>() +const mockListHistoryPage = jest.fn, [unknown]>() +const mockLoadHistoryCache = jest.fn() +const mockUpdateHistoryRevisionSafe = jest.fn() +let mockAuthUser: { id: string } | null = null + +jest.mock('../src/lib/supabase', () => ({ + supabase: { + channel: jest.fn(), + removeChannel: jest.fn(async () => 'ok'), + }, +})) +jest.mock('../src/lib/auth-context', () => ({ + useAuth: () => ({ user: mockAuthUser }), +})) +jest.mock('../src/features/import/audio-transcription-service', () => ({ + processAudioInput: (input: LocalAudioInput, options: unknown) => mockProcessAudioInput(input, options), +})) +jest.mock('../src/features/meetings/meetings-service', () => ({ + failMeetingRecording: jest.fn(async () => undefined), + markMeetingProcessingFailure: jest.fn(async () => undefined), + queueMeetingRecording: jest.fn(async () => undefined), +})) +jest.mock('../src/features/history/history-service', () => ({ + ...jest.requireActual('../src/features/history/history-service'), + listHistoryPage: (options: unknown) => mockListHistoryPage(options), + subscribeToHistory: () => ({ unsubscribe: async () => undefined }), + updateHistoryRevisionSafe: (...args: unknown[]) => mockUpdateHistoryRevisionSafe(...args), +})) +jest.mock('../src/features/history/history-cache', () => ({ + ...jest.requireActual('../src/features/history/history-cache'), + loadHistoryCache: (...args: unknown[]) => mockLoadHistoryCache(...args), + saveHistoryCache: jest.fn(async () => undefined), + clearHistoryCache: jest.fn(async () => undefined), +})) + +import { + clearQueuedAudioForUser, + durableQueueTestContract, + processQueuedAudioNow, + QueuedAudioPendingError, + resumeQueuedAudioForUser, + retainQueuedAudioOnlyForUser, + retryQueuedAudio, + type DurableQueueItem, +} from '../src/features/recording/durable-processing-queue' +import { useHistorySync } from '../src/features/history/use-history-sync' + +const mockFileSystem = FileSystem as typeof FileSystem & { filesystem: Map } + +function makeQueueItem( + userId: string, + suffix: string, + overrides: Partial = {}, +): DurableQueueItem { + const path = `${durableQueueTestContract.queueDirectory}/queued-${suffix}.wav` + return { + schemaVersion: 1, + id: suffix, + userId, + meetingId: null, + path, + uri: `file://${path}`, + fileName: `${suffix}.wav`, + mimeType: 'audio/wav', + sizeBytes: 128, + durationMs: 1_000, + source: 'recording', + languageCode: 'ko', + status: 'pending', + phase: null, + attempts: 0, + uploadedBytes: 0, + nextAttemptAtMs: START_MS, + lastErrorCode: null, + lastErrorMessage: null, + createdAtMs: START_MS, + updatedAtMs: START_MS, + ...overrides, + } +} + +function makeHistoryEntry(id: string, userId = USER_A): HistoryListEntry { + return { + id, + user_id: userId, + title: `entry ${id}`, + original_text: `text ${id}`, + polished_text: null, + focused_app: null, + focused_app_name: null, + focused_app_window_title: null, + mode: 'dictation', + status: 'completed', + error_code: null, + audio_storage_key: null, + duration: 2, + detected_language: 'ko', + mic_device: null, + word_count: 1, + stt_model: 'whisper', + llm_model: null, + stt_latency_ms: null, + llm_latency_ms: null, + app_version: '1.0.0', + summary_text: null, + is_favorite: false, + revision: 1, + created_at: '2026-08-21T00:00:00.000Z', + updated_at: '2026-08-21T00:00:00.000Z', + activeJob: null, + } +} + +function deferred() { + let resolve: (value: T) => void = () => undefined + let reject: (reason?: unknown) => void = () => undefined + const promise = new Promise((res, rej) => { + resolve = res + reject = rej + }) + return { promise, resolve, reject } +} + +async function flushMicrotasks(): Promise { + for (let index = 0; index < 8; index += 1) await Promise.resolve() +} + +describe('durable queue and history sync race guards', () => { + let activeRenderer: ReactTestRenderer | null = null + + beforeEach(async () => { + jest.useFakeTimers({ now: START_MS }) + await AsyncStorage.clear() + mockFileSystem.filesystem.clear() + mockProcessAudioInput.mockReset() + mockListHistoryPage.mockReset() + mockLoadHistoryCache.mockReset() + mockUpdateHistoryRevisionSafe.mockReset() + mockAuthUser = null + }) + + afterEach(async () => { + if (activeRenderer !== null) { + const target = activeRenderer + activeRenderer = null + act(() => target.unmount()) + } + await clearQueuedAudioForUser(USER_A).catch(() => undefined) + await clearQueuedAudioForUser(USER_B).catch(() => undefined) + await resumeQueuedAudioForUser(USER_A).catch(() => undefined) + await resumeQueuedAudioForUser(USER_B).catch(() => undefined) + jest.clearAllTimers() + jest.useRealTimers() + }) + + test('durableQueue_정지된사용자의재시도실패시_스케줄러를재예약하지않음', async () => { + const item = makeQueueItem(USER_A, 'aaaa0001') + mockFileSystem.filesystem.set(item.path, 'audio-bytes') + await AsyncStorage.setItem(durableQueueTestContract.storageKey, JSON.stringify([item])) + + const runGate = deferred() + mockProcessAudioInput.mockImplementationOnce(() => runGate.promise) + + const processing = processQueuedAudioNow(USER_A, item.id).catch((err: unknown) => err) + await flushMicrotasks() + + await retainQueuedAudioOnlyForUser(USER_A) + + runGate.reject(new AudioPipelineError('upload', 'network temporarily offline')) + const caught = await processing + expect(caught).toBeInstanceOf(QueuedAudioPendingError) + expect(jest.getTimerCount()).toBe(0) + + await jest.advanceTimersByTimeAsync(120_000) + await flushMicrotasks() + + // While USER_A remains suspended after retainQueuedAudioOnlyForUser, no retry run fires. + expect(mockProcessAudioInput).toHaveBeenCalledTimes(1) + }) + + test('durableQueue_정지또는정리단계항목재시도시_running이나cleanup상태를덮어쓰지않음', async () => { + const cleaningItem = makeQueueItem(USER_A, 'aaaa0002', { + status: 'cleanup', + phase: 'saving', + }) + const runningItem = makeQueueItem(USER_A, 'aaaa0003', { + status: 'running', + phase: 'transcribing', + }) + mockFileSystem.filesystem.set(cleaningItem.path, 'audio-bytes') + mockFileSystem.filesystem.set(runningItem.path, 'audio-bytes') + await AsyncStorage.setItem( + durableQueueTestContract.storageKey, + JSON.stringify([cleaningItem, runningItem]), + ) + mockProcessAudioInput.mockResolvedValue({ + historyId: null, + audioFileId: 'audio-file', + meetingId: null, + processingJobId: null, + transcript: 'done', + provider: 'test', + language: 'ko', + durationSeconds: 1, + deduplicated: false, + }) + + // Hold resume at readQueue or reject nothing — instead inspect status change before resume consumes running. + await retryQueuedAudio(USER_A, cleaningItem.id) + const afterCleanupRetry = durableQueueTestContract.parseQueue( + await AsyncStorage.getItem(durableQueueTestContract.storageKey), + ) + const cleanupState = afterCleanupRetry.find((candidate) => candidate.id === cleaningItem.id) + // cleanup item must not be downgraded to retry and re-transcribed. + expect(mockProcessAudioInput).not.toHaveBeenCalled() + expect(cleanupState).toBeUndefined() + + await retryQueuedAudio(USER_A, runningItem.id) + const afterRunningRetry = durableQueueTestContract.parseQueue( + await AsyncStorage.getItem(durableQueueTestContract.storageKey), + ) + expect(afterRunningRetry.find((candidate) => candidate.id === runningItem.id)?.status).toBe('running') + }) + + test('useHistorySync_오프라인캐시조회중새요청이나언마운트시_오래된캐시로덮어쓰지않음', async () => { + jest.useRealTimers() + let latestState: ReturnType | null = null + function Probe(): null { + latestState = useHistorySync() + return null + } + + const firstOfflineCache = deferred<{ savedAt: string; entries: HistoryListEntry[] } | null>() + mockAuthUser = { id: USER_A } + mockListHistoryPage + .mockRejectedValueOnce(new TypeError('Network request failed')) + .mockResolvedValueOnce({ + entries: [makeHistoryEntry('fresh-entry', USER_B)], + nextCursor: null, + }) + mockLoadHistoryCache.mockReturnValueOnce(firstOfflineCache.promise) + + let renderer!: ReactTestRenderer + await act(async () => { + renderer = create(React.createElement(Probe)) + activeRenderer = renderer + await flushMicrotasks() + }) + + // Switch user while USER_A's offline cache load is still pending. + mockAuthUser = { id: USER_B } + await act(async () => { + renderer.update(React.createElement(Probe)) + await flushMicrotasks() + }) + expect(latestState?.entries.map((item) => item.id)).toEqual(['fresh-entry']) + + // Now USER_A's stalled offline cache finishes. + await act(async () => { + firstOfflineCache.resolve({ + savedAt: '2026-08-21T00:00:00.000Z', + entries: [makeHistoryEntry('stale-user-a-cache', USER_A)], + }) + await flushMicrotasks() + }) + + expect(latestState?.entries.map((item) => item.id)).toEqual(['fresh-entry']) + expect(latestState?.offline).toBe(false) + + // Now test toggleFavorite resolving after user switch does not pollute USER_B's entries. + const favGate = deferred() + mockUpdateHistoryRevisionSafe.mockReturnValueOnce(favGate.promise) + const staleEntry = makeHistoryEntry('shared-like-entry', USER_A) + let pendingToggle: Promise = Promise.resolve() + act(() => { + pendingToggle = latestState!.toggleFavorite(staleEntry).catch(() => undefined) + }) + + mockAuthUser = { id: USER_A } + mockListHistoryPage.mockResolvedValueOnce({ + entries: [makeHistoryEntry('shared-like-entry', USER_A)], + nextCursor: null, + }) + await act(async () => { + renderer.update(React.createElement(Probe)) + await flushMicrotasks() + }) + expect(latestState?.entries[0]?.is_favorite).toBe(false) + + await act(async () => { + favGate.resolve({ ...staleEntry, is_favorite: true, revision: 2 }) + await pendingToggle + await flushMicrotasks() + }) + + expect(latestState?.entries[0]?.is_favorite).toBe(false) + activeRenderer = null + act(() => renderer.unmount()) + }) +}) diff --git a/apps/mobile-rn/__tests__/recorder-lifecycle-races.test.ts b/apps/mobile-rn/__tests__/recorder-lifecycle-races.test.ts new file mode 100644 index 0000000..8cf8108 --- /dev/null +++ b/apps/mobile-rn/__tests__/recorder-lifecycle-races.test.ts @@ -0,0 +1,238 @@ +import { NativeModules } from 'react-native' +import { FileSystem } from 'react-native-file-access' + +const mockStartRecorder = jest.fn, [string, unknown, boolean]>() +const mockStopRecorder = jest.fn(async () => 'stopped') +const mockPauseRecorder = jest.fn(async () => 'paused') +const mockResumeRecorder = jest.fn(async () => 'resumed') + +jest.mock('react-native-nitro-sound', () => ({ + AudioEncoderAndroidType: { AAC: 3 }, + AudioSourceAndroidType: { MIC: 1 }, + AVEncoderAudioQualityIOSType: { high: 96 }, + OutputFormatAndroidType: { MPEG_4: 2 }, + createSound: () => ({ + addRecordBackListener: () => undefined, + pauseRecorder: () => mockPauseRecorder(), + resumeRecorder: () => mockResumeRecorder(), + setSubscriptionDuration: () => undefined, + startRecorder: (path: string, settings: unknown, metering: boolean) => ( + mockStartRecorder(path, settings, metering) + ), + stopRecorder: () => mockStopRecorder(), + }), +})) + +import { + AudioRecorder, + RecorderBusyError, + type RecorderBackend, +} from '../src/lib/audio-recorder' +import { AndroidForegroundRecorderBackend } from '../src/lib/recorder/android-foreground-backend' +import { NitroRecorderBackend } from '../src/lib/recorder/nitro-backend' + +const MEETING_PATH = '/data/user/0/com.d3ro.voice/files/recordings/d3ro-recording-11111111-1111-4111-8111-111111111111.wav' + +function nativeSnapshot( + state: 'idle' | 'starting' | 'recording' | 'paused' | 'stopped' | 'recoverable', +) { + const hasFile = state !== 'idle' + return { + state, + path: hasFile ? MEETING_PATH : null, + uri: hasFile ? `file://${MEETING_PATH}` : null, + fileName: hasFile ? 'd3ro-recording-11111111-1111-4111-8111-111111111111.wav' : null, + mimeType: 'audio/wav', + size: hasFile ? 64_044 : 0, + durationMs: hasFile ? 4_000 : 0, + meteringDb: null, + meetingId: null, + interruptionReason: null, + startedAtMs: hasFile ? 1_000 : 0, + recoverable: state === 'recoverable', + } +} + +function deferred() { + let resolve: (value: T) => void = () => undefined + let reject: (reason?: unknown) => void = () => undefined + const promise = new Promise((res, rej) => { + resolve = res + reject = rej + }) + return { promise, resolve, reject } +} + +describe('audio recorder and backend lifecycle race guards', () => { + afterEach(() => { + jest.clearAllTimers() + jest.useRealTimers() + jest.restoreAllMocks() + mockStartRecorder.mockReset() + mockStopRecorder.mockClear() + delete (NativeModules as Record).D3RORecording + }) + + test('AudioRecorder_동시start클레임경합시_한소유자만인정하고실패시임대해제', async () => { + const busyChecks: Array>> = [] + let active = false + let failNextStart = true + const backend: RecorderBackend = { + requestPermission: jest.fn(async () => true), + start: jest.fn(async () => { + if (failNextStart) { + failNextStart = false + throw new Error('mic unavailable') + } + active = true + }), + pause: jest.fn(async () => undefined), + resume: jest.fn(async () => undefined), + stop: jest.fn(async () => ({ + uri: 'file:///cache/cap.m4a', + path: '/cache/cap.m4a', + fileName: 'cap.m4a', + mimeType: 'audio/mp4', + size: 128, + durationMs: 1_000, + })), + cleanup: jest.fn(async () => { active = false }), + cancel: jest.fn(async () => { active = false }), + restore: jest.fn(async () => ({ + state: 'idle' as const, + recording: null, + meetingId: null, + interruptionReason: null, + startedAtMs: 0, + })), + isBusy: jest.fn(() => { + const gate = deferred() + busyChecks.push(gate) + return gate.promise + }), + hasInProcessCapture: jest.fn(() => active), + } + + const recorder = new AudioRecorder(backend) + const recordAcquire = recorder.acquire('record') + await Promise.resolve() + busyChecks.pop()?.resolve(false) + const record = await recordAcquire + + const talkAcquire = recorder.acquire('talk') + await Promise.resolve() + busyChecks.pop()?.resolve(false) + const talk = await talkAcquire + + // Both record.start and talk.start race while isBusy() is pending. + const recordStart = record.start(() => undefined) + const talkStart = talk.start(() => undefined) + await Promise.resolve() + while (busyChecks.length > 0) busyChecks.shift()?.resolve(false) + + await expect(recordStart).rejects.toThrow('mic unavailable') + await expect(talkStart).rejects.toBeInstanceOf(RecorderBusyError) + expect(backend.start).toHaveBeenCalledTimes(1) + + // After record.start fails and stays idle, lease must be released for talk. + const secondTalkStart = talk.start(() => undefined) + await Promise.resolve() + while (busyChecks.length > 0) busyChecks.shift()?.resolve(false) + await expect(secondTalkStart).resolves.toBeUndefined() + expect(backend.start).toHaveBeenCalledTimes(2) + }) + + test('NitroRecorderBackend_임시파일정리중취소시_녹음시작하지않고idle복귀', async () => { + const lsGate = deferred() + jest.spyOn(FileSystem, 'ls').mockReturnValueOnce(lsGate.promise) + mockStartRecorder.mockResolvedValue('file:///cache/fake-nitro-recording.m4a') + const backend = new NitroRecorderBackend() + + const startPromise = backend.start(() => undefined) + await Promise.resolve() + + await backend.cancel() + lsGate.resolve([]) + + await expect(startPromise).rejects.toThrow('cancelled') + expect(mockStartRecorder).not.toHaveBeenCalled() + expect(backend.hasInProcessCapture()).toBe(false) + }) + + test('AndroidForegroundRecorderBackend_정지및취소시_예약된폴타이머를모두해제함', async () => { + jest.useFakeTimers() + const native = { + current: nativeSnapshot('idle'), + getStatus: jest.fn(async () => native.current), + start: jest.fn(async () => { + native.current = nativeSnapshot('recording') + return native.current + }), + pause: jest.fn(async () => nativeSnapshot('paused')), + resume: jest.fn(async () => nativeSnapshot('recording')), + stop: jest.fn(async () => { + native.current = nativeSnapshot('stopped') + return native.current + }), + cancel: jest.fn(async () => { + native.current = nativeSnapshot('idle') + return native.current + }), + dispose: jest.fn(async () => { + native.current = nativeSnapshot('idle') + }), + } + ;(NativeModules as Record).D3RORecording = native + + const backend = new AndroidForegroundRecorderBackend() + await backend.start(() => undefined) + await Promise.resolve() + + expect(jest.getTimerCount()).toBeGreaterThan(0) + await backend.stop() + expect(jest.getTimerCount()).toBe(0) + + await backend.cleanup() + native.getStatus.mockRejectedValueOnce(new Error('transient bridge error')) + await backend.start(() => undefined) + await Promise.resolve() + + expect(jest.getTimerCount()).toBeGreaterThan(0) + await backend.cancel() + expect(jest.getTimerCount()).toBe(0) + }) + + test('AndroidForegroundRecorderBackend_시작중취소호출시_지연된시작응답이idle상태를덮어쓰지않음', async () => { + jest.useFakeTimers() + const startGate = deferred>() + const native = { + current: nativeSnapshot('idle'), + getStatus: jest.fn(async () => native.current), + start: jest.fn(() => startGate.promise), + pause: jest.fn(async () => nativeSnapshot('paused')), + resume: jest.fn(async () => nativeSnapshot('recording')), + stop: jest.fn(async () => nativeSnapshot('stopped')), + cancel: jest.fn(async () => { + native.current = nativeSnapshot('idle') + return native.current + }), + dispose: jest.fn(async () => undefined), + } + ;(NativeModules as Record).D3RORecording = native + + const backend = new AndroidForegroundRecorderBackend() + const startPromise = backend.start(() => undefined) + await Promise.resolve() + + await backend.cancel() + expect(native.cancel).toHaveBeenCalledTimes(1) + + native.current = nativeSnapshot('recording') + startGate.resolve(native.current) + + await expect(startPromise).rejects.toThrow('cancelled') + expect(backend.hasInProcessCapture()).toBe(false) + expect(native.cancel).toHaveBeenCalledTimes(2) + expect(jest.getTimerCount()).toBe(0) + }) +}) diff --git a/apps/mobile-rn/__tests__/screen-async-lifecycle.test.tsx b/apps/mobile-rn/__tests__/screen-async-lifecycle.test.tsx new file mode 100644 index 0000000..7a4a4f9 --- /dev/null +++ b/apps/mobile-rn/__tests__/screen-async-lifecycle.test.tsx @@ -0,0 +1,832 @@ +import React from 'react' +import { TextInput } from 'react-native' +import { act, create, type ReactTestRenderer } from 'react-test-renderer' +import type { Meeting } from '@d3ro/api-client' +import { AudioPipelineError, type LocalAudioInput } from '../src/features/import/audio-import-types' +import { CommandSyncError, type SyncedCommand } from '../src/features/commands/command-service' +import type { HistoryDetail } from '../src/features/history/history-service' +import type { MobileDashboardStats } from '../src/features/dashboard/dashboard-service' + +const USER_A = '11111111-1111-4111-8111-111111111111' +const USER_B = '22222222-2222-4222-8222-222222222222' +const MEETING_ID_1 = '33333333-3333-4333-8333-333333333333' +const MEETING_ID_2 = '44444444-4444-4444-8444-444444444444' +const HISTORY_ID = '55555555-5555-4555-8555-555555555555' +const AUDIO_ID = '66666666-6666-4666-8666-666666666666' +const AUDIO_ID_2 = '66666666-6666-4666-8666-666666666667' +const COMMAND_ID = '77777777-7777-4777-8777-777777777777' +const TEAM_ID = '88888888-8888-4888-8888-888888888888' + +let mockCurrentUser: { id: string; email?: string } | null = { id: USER_A, email: 'a@example.com' } +const mockSession = { access_token: 'access-token' } +const mockNavigate = jest.fn() +const mockGoBack = jest.fn() +const mockNavigation = { + navigate: mockNavigate, + goBack: mockGoBack, + getParent: () => undefined, +} +const mockSafeInsets = { top: 0, bottom: 0, left: 0, right: 0 } +const mockI18nValue = { + t: (key: string) => key, + locale: 'ko', + formatDate: () => '2026-08-21', + formatRelativeDate: () => 'today', + formatTime: () => '10:00', +} +const mockRefreshEntitlement = jest.fn(async () => null) +const mockEntitlementValue = { + refresh: mockRefreshEntitlement, + snapshot: { tier: 'free', adFree: false, overageCredits: 0 }, +} +const { d3roNativeDarkPalette } = jest.requireActual('@d3ro/ui-native') as typeof import('@d3ro/ui-native') +const mockPreferencesValue = { + palette: d3roNativeDarkPalette, + preferences: { preferredLlmModel: 'claude-haiku-4-5-20251001' }, +} + +const mockLoadDashboardStats = jest.fn, [string]>() +const mockListMeetingsPage = jest.fn() +const mockListKnowledgeDocuments = jest.fn() +const mockConsumeIncomingMediaAudio = jest.fn, []>() +const mockEnqueueAudioProcessing = jest.fn() +const mockProcessQueuedAudioNow = jest.fn() +const mockGetHistoryDetail = jest.fn, [string, string]>() +const mockCreateAudioPlaybackUrl = jest.fn, [string, unknown]>() +const mockStartPlayer = jest.fn(async () => 'started') +const mockStopPlayer = jest.fn(async () => 'stopped') +const mockLoadSyncedCommandCatalog = jest.fn() +const mockCreateSyncedCommand = jest.fn() +const mockListTeams = jest.fn() +const mockCreateTeam = jest.fn() + +jest.mock('@react-navigation/native', () => { + const ReactValue = require('react') as typeof React + return { + useNavigation: () => mockNavigation, + useFocusEffect: (callback: () => void | (() => void)) => { + ReactValue.useEffect(callback, [callback]) + }, + } +}) +jest.mock('react-native-safe-area-context', () => ({ + useSafeAreaInsets: () => mockSafeInsets, +})) +jest.mock('../src/navigation/tab-layout', () => ({ + useTabScreenBottomPadding: () => 88, +})) +jest.mock('@d3ro/i18n', () => ({ + useI18n: () => mockI18nValue, +})) +jest.mock('../src/lib/auth-context', () => ({ + useAuth: () => ({ + user: mockCurrentUser, + session: mockSession, + loading: false, + }), +})) +jest.mock('../src/lib/entitlement-context', () => ({ + useEntitlement: () => mockEntitlementValue, +})) +jest.mock('../src/lib/preferences-context', () => ({ + useMobilePreferences: () => mockPreferencesValue, +})) +jest.mock('../src/lib/supabase', () => ({ + supabase: { + channel: jest.fn(() => ({ + on: jest.fn().mockReturnThis(), + subscribe: jest.fn().mockReturnThis(), + })), + removeChannel: jest.fn(async () => 'ok'), + }, +})) +jest.mock('../src/components/ScreenHeader', () => ({ + ScreenHeader: ({ rightContent }: { rightContent?: React.ReactNode }) => rightContent ?? null, +})) +jest.mock('../src/components/ContentReportSheet', () => () => null) +jest.mock('../src/features/dashboard/dashboard-service', () => ({ + loadDashboardStats: (userId: string) => mockLoadDashboardStats(userId), +})) +jest.mock('../src/features/meetings/meetings-service', () => { + class MockMeetingServiceError extends Error { + code: string + constructor(code: string, message: string) { + super(message) + this.code = code + } + } + return { + MeetingServiceError: MockMeetingServiceError, + createMeetingCreationIdempotencyKey: () => 'cccccccc-cccc-4ccc-8ccc-cccccccccccc', + createMeetingWorkspaceWithMetadata: jest.fn(), + listMeetingsPage: (opts: unknown) => mockListMeetingsPage(opts), + updateMeetingTitleRevisionSafe: jest.fn(), + deleteMeetingRevisionSafe: jest.fn(), + beginMeetingRecording: jest.fn(async () => ({})), + cancelMeetingRecording: jest.fn(async () => ({})), + failMeetingRecording: jest.fn(async () => ({})), + getMeetingRecordingLanguage: jest.fn(async () => 'ko'), + } +}) +jest.mock('../src/features/templates', () => ({ + loadTemplateLibrary: jest.fn(async () => ({ templates: [], selections: {} })), +})) +jest.mock('../src/features/knowledge/knowledge-service', () => { + class MockKnowledgeServiceError extends Error { + code: string + constructor(code: string, message: string) { + super(message) + this.code = code + } + } + return { + KnowledgeServiceError: MockKnowledgeServiceError, + createKnowledgeDocument: jest.fn(), + deleteKnowledgeDocument: jest.fn(), + indexKnowledgeDocument: jest.fn(), + listKnowledgeDocuments: (opts: unknown) => mockListKnowledgeDocuments(opts), + mergeKnowledgeDocuments: (current: unknown[], next: unknown[]) => [...current, ...next], + searchKnowledge: jest.fn(), + subscribeToKnowledgeDocuments: () => ({ unsubscribe: async () => undefined }), + } +}) +jest.mock('../src/features/knowledge/knowledge-file-picker', () => ({ + pickKnowledgeFile: jest.fn(), +})) +jest.mock('../src/features/import/incoming-media-intent', () => ({ + consumeIncomingMediaAudio: () => mockConsumeIncomingMediaAudio(), +})) +jest.mock('../src/features/import/audio-validation', () => ({ + validateLocalAudio: jest.fn(), +})) +jest.mock('../src/features/import/audio-file-picker', () => ({ + pickAudioFile: jest.fn(), +})) +jest.mock('../src/features/notifications/notification-native', () => ({ + showLocalTranscriptionCompleted: jest.fn(async () => true), +})) +jest.mock('../src/lib/audio-recorder', () => ({ + RecorderBusyError: class extends Error {}, + audioRecorder: { + acquire: async () => ({ + restore: async () => ({ state: 'idle', recording: null, meetingId: null, interruptionReason: null }), + start: jest.fn(async () => undefined), + stop: jest.fn(), + cleanup: jest.fn(async () => undefined), + cancel: jest.fn(async () => undefined), + pause: jest.fn(async () => undefined), + resume: jest.fn(async () => undefined), + }), + requestPermission: async () => true, + }, +})) +jest.mock('../src/features/recording/durable-processing-queue', () => ({ + discardQueuedAudio: jest.fn(async () => undefined), + enqueueAudioProcessing: (...args: unknown[]) => mockEnqueueAudioProcessing(...args), + processQueuedAudioNow: (...args: unknown[]) => mockProcessQueuedAudioNow(...args), + QueuedAudioPendingError: class extends Error { item = { id: 'q-1' } }, + retryQueuedAudio: jest.fn(async () => undefined), + subscribeToDurableQueue: () => () => undefined, +})) +jest.mock('react-native-nitro-sound', () => ({ + useSoundWithStates: () => ({ + state: { isPlaying: false, playback: { position: 0, duration: 1_000 } }, + startPlayer: () => mockStartPlayer(), + stopPlayer: () => mockStopPlayer(), + pausePlayer: jest.fn(async () => 'paused'), + resumePlayer: jest.fn(async () => 'resumed'), + }), +})) +jest.mock('../src/features/history/history-cache', () => ({ + loadHistoryCache: jest.fn(async () => null), +})) +jest.mock('../src/features/history/history-service', () => ({ + HistoryServiceError: class extends Error { + code: string + constructor(code: string, message: string) { + super(message) + this.code = code + } + }, + getHistoryDetail: (userId: string, historyId: string) => mockGetHistoryDetail(userId, historyId), + createAudioPlaybackUrl: (userId: string, audioFile: unknown) => ( + mockCreateAudioPlaybackUrl(userId, audioFile) + ), + updateHistoryRevisionSafe: jest.fn(), + deleteHistoryRevisionSafe: jest.fn(), +})) +jest.mock('../src/features/commands/command-service', () => { + class MockCommandSyncError extends Error { + code: string + constructor(code: string, message: string) { + super(message) + this.code = code + } + } + return { + COMMAND_INPUT_MAX_CHARS: 4000, + CommandExecutionError: class extends Error { + code: string + retryable: boolean + constructor(code: string, retryable = false) { + super(code) + this.code = code + this.retryable = retryable + } + }, + CommandSyncError: MockCommandSyncError, + createSyncedCommand: (...args: unknown[]) => mockCreateSyncedCommand(...args), + deleteSyncedCommand: jest.fn(), + executeSyncedCommand: jest.fn(), + loadSyncedCommandCatalog: (...args: unknown[]) => mockLoadSyncedCommandCatalog(...args), + reorderSyncedCommand: jest.fn(), + setActiveSyncedCommand: jest.fn(), + updateSyncedCommand: jest.fn(), + } +}) +jest.mock('../src/features/teams/team-service', () => { + class MockTeamServiceError extends Error { + code: string + constructor(code: string, message: string) { + super(message) + this.code = code + } + } + return { + TeamServiceError: MockTeamServiceError, + listTeams: (...args: unknown[]) => mockListTeams(...args), + createTeam: (...args: unknown[]) => mockCreateTeam(...args), + } +}) + +import HomeScreen from '../src/screens/HomeScreen' +import MeetingsScreen from '../src/screens/MeetingsScreen' +import KnowledgeScreen from '../src/screens/KnowledgeScreen' +import RecordScreen from '../src/screens/RecordScreen' +import HistoryDetailScreen from '../src/screens/HistoryDetailScreen' +import CommandsScreen from '../src/screens/CommandsScreen' +import TeamsScreen from '../src/screens/TeamsScreen' + +function deferred() { + let resolve: (value: T) => void = () => undefined + let reject: (reason?: unknown) => void = () => undefined + const promise = new Promise((res, rej) => { + resolve = res + reject = rej + }) + return { promise, resolve, reject } +} + +async function flush(): Promise { + for (let index = 0; index < 8; index += 1) await Promise.resolve() +} + +function findHostByTestId(renderer: ReactTestRenderer, testID: string) { + return renderer.root.findAll( + (node) => typeof node.type === 'string' && node.props.testID === testID, + ) +} + +function makeMeeting(id: string, title: string, userId = USER_A): Meeting { + return { + id, + user_id: userId, + team_id: null, + title, + status: 'completed', + started_at: '2026-08-21T00:00:00.000Z', + ended_at: '2026-08-21T00:05:00.000Z', + duration_ms: 300_000, + raw_transcript: 'transcript', + edited_transcript: null, + minutes_markdown: null, + minutes_json: null, + stt_model: null, + llm_model: null, + stt_latency_ms: null, + llm_latency_ms: null, + error_message: null, + audio_storage_key: null, + language: 'ko', + attendees: [], + template_id: null, + creation_idempotency_key: null, + creation_request_hash: null, + created_at: '2026-08-21T00:00:00.000Z', + updated_at: '2026-08-21T00:05:00.000Z', + } +} + +describe('screen async lifecycle and race guards', () => { + let activeRenderer: ReactTestRenderer | null = null + + beforeEach(() => { + mockCurrentUser = { id: USER_A, email: 'a@example.com' } + mockNavigate.mockReset() + mockGoBack.mockReset() + mockRefreshEntitlement.mockClear() + mockLoadDashboardStats.mockReset() + mockListMeetingsPage.mockReset() + mockListKnowledgeDocuments.mockReset() + mockConsumeIncomingMediaAudio.mockReset() + mockEnqueueAudioProcessing.mockReset() + mockProcessQueuedAudioNow.mockReset() + mockGetHistoryDetail.mockReset() + mockCreateAudioPlaybackUrl.mockReset() + mockStartPlayer.mockClear() + mockStopPlayer.mockClear() + mockLoadSyncedCommandCatalog.mockReset() + mockCreateSyncedCommand.mockReset() + mockListTeams.mockReset() + mockCreateTeam.mockReset() + }) + + afterEach(() => { + if (activeRenderer !== null) { + const target = activeRenderer + activeRenderer = null + act(() => target.unmount()) + } + jest.restoreAllMocks() + jest.clearAllTimers() + jest.useRealTimers() + }) + + test('HomeScreen_새로고침중계정변경시_이전계정응답으로화면을덮어쓰지않음', async () => { + const statsA = deferred() + const meetingsA = deferred<{ meetings: Meeting[]; total: number; page: number; pageSize: number; hasMore: boolean }>() + + mockLoadDashboardStats + .mockReturnValueOnce(statsA.promise) + .mockResolvedValueOnce({ + totalSessions: 1, + totalRecordingSeconds: 10, + totalWordCount: 5, + todaySessions: 1, + todayRecordingSeconds: 10, + todayWordCount: 5, + streakDays: 1, + recentHistory: [{ + id: 'user-b-rec', + title: 'User B record', + text: 'User B note', + durationSeconds: 10, + mode: 'dictation', + createdAt: '2026-08-21T00:00:00.000Z', + }], + generatedAt: '2026-08-21T00:00:00.000Z', + }) + mockListMeetingsPage + .mockReturnValueOnce(meetingsA.promise) + .mockResolvedValueOnce({ + meetings: [makeMeeting(MEETING_ID_2, 'User B Meeting', USER_B)], + total: 1, + page: 0, + pageSize: 3, + hasMore: false, + }) + + let renderer!: ReactTestRenderer + await act(async () => { + renderer = create() + activeRenderer = renderer + await flush() + }) + + // User switches from USER_A to USER_B while USER_A's dashboard request is still pending. + mockCurrentUser = { id: USER_B, email: 'b@example.com' } + await act(async () => { + renderer.update() + await flush() + }) + expect(findHostByTestId(renderer, `home-meeting-${MEETING_ID_2}`)).toHaveLength(1) + + await act(async () => { + statsA.resolve({ + totalSessions: 9, + totalRecordingSeconds: 90, + totalWordCount: 90, + todaySessions: 2, + todayRecordingSeconds: 20, + todayWordCount: 20, + streakDays: 3, + recentHistory: [{ + id: 'user-a-stale-rec', + title: 'Stale A', + text: 'Stale A', + durationSeconds: 20, + mode: 'dictation', + createdAt: '2026-08-21T00:00:00.000Z', + }], + generatedAt: '2026-08-21T00:00:00.000Z', + }) + meetingsA.resolve({ + meetings: [makeMeeting(MEETING_ID_1, 'Stale A Meeting', USER_A)], + total: 1, + page: 0, + pageSize: 3, + hasMore: false, + }) + await flush() + }) + + expect(findHostByTestId(renderer, `home-meeting-${MEETING_ID_1}`)).toHaveLength(0) + expect(findHostByTestId(renderer, `home-meeting-${MEETING_ID_2}`)).toHaveLength(1) + activeRenderer = null + act(() => renderer.unmount()) + }) + + test('MeetingsScreen_더보기조회중새검색실행시_이전페이지결과를병합하지않음', async () => { + jest.useFakeTimers({ now: 1_700_000_000_000 }) + const stalePage2 = deferred<{ meetings: Meeting[]; total: number; page: number; pageSize: number; hasMore: boolean }>() + mockListMeetingsPage.mockImplementation(async (opts: { page: number; search?: string }) => { + if (opts.search && opts.search.length > 0) { + return { + meetings: [makeMeeting(MEETING_ID_2, 'Filtered Search Result')], + total: 1, + page: 0, + pageSize: 30, + hasMore: false, + } + } + if (opts.page === 1) return stalePage2.promise + return { + meetings: [makeMeeting(MEETING_ID_1, 'Initial Meeting')], + total: 2, + page: 0, + pageSize: 30, + hasMore: true, + } + }) + + let renderer!: ReactTestRenderer + await act(async () => { + renderer = create() + activeRenderer = renderer + await flush() + }) + + const flatList = renderer.root.findAll((node) => typeof node.props.onEndReached === 'function')[0] + await act(async () => { + flatList.props.onEndReached() + await Promise.resolve() + }) + + // Trigger a new search (debounced 300ms) while page 1 (loadMore) is still in flight. + const searchInput = renderer.root.findByProps({ testID: 'meetings-search' }) + await act(async () => { + searchInput.props.onChangeText('Filtered') + }) + await act(async () => { + await jest.advanceTimersByTimeAsync(350) + await flush() + }) + + expect(findHostByTestId(renderer, `meeting-card-${MEETING_ID_2}`)).toHaveLength(1) + + await act(async () => { + stalePage2.resolve({ + meetings: [makeMeeting('99999999-9999-4999-8999-999999999999', 'Stale Page 2')], + total: 2, + page: 1, + pageSize: 30, + hasMore: false, + }) + await flush() + }) + + expect(findHostByTestId(renderer, 'meeting-card-99999999-9999-4999-8999-999999999999')).toHaveLength(0) + expect(findHostByTestId(renderer, `meeting-card-${MEETING_ID_2}`)).toHaveLength(1) + activeRenderer = null + act(() => renderer.unmount()) + }) + + test('KnowledgeScreen_더보기조회중새검색실행시_이전문서결과를병합하지않음', async () => { + const staleDocPage2 = deferred<{ documents: unknown[]; total: number; page: number; pageSize: number; hasMore: boolean }>() + const makeDoc = (id: string, title: string) => ({ + id, + user_id: USER_A, + team_id: null, + title, + file_name: `${id}.md`, + file_type: 'md', + source_url: null, + storage_key: null, + chunk_count: 1, + indexed: true, + indexed_at: '2026-08-21T00:00:00.000Z', + created_at: '2026-08-21T00:00:00.000Z', + updated_at: '2026-08-21T00:00:00.000Z', + }) + + mockListKnowledgeDocuments.mockImplementation(async (opts: { page: number; search?: string }) => { + if (opts.search && opts.search.length > 0) { + return { + documents: [makeDoc('doc-search', 'Filtered Doc')], + total: 1, + page: 0, + pageSize: 30, + hasMore: false, + } + } + if (opts.page === 1) return staleDocPage2.promise + return { + documents: [makeDoc('doc-1', 'Doc 1')], + total: 2, + page: 0, + pageSize: 30, + hasMore: true, + } + }) + + let renderer!: ReactTestRenderer + await act(async () => { + renderer = create() + activeRenderer = renderer + await flush() + }) + + const flatList = renderer.root.findAll((node) => typeof node.props.onEndReached === 'function')[0] + await act(async () => { + flatList.props.onEndReached() + await Promise.resolve() + }) + + const searchInput = renderer.root.findByProps({ testID: 'knowledge-document-search' }) + const searchSubmit = renderer.root.findByProps({ testID: 'knowledge-document-search-submit' }) + await act(async () => { + searchInput.props.onChangeText('Filtered') + await Promise.resolve() + }) + await act(async () => { + searchSubmit.props.onPress() + await flush() + }) + + expect(findHostByTestId(renderer, 'knowledge-document-doc-search')).toHaveLength(1) + + await act(async () => { + staleDocPage2.resolve({ + documents: [makeDoc('doc-stale', 'Stale Doc Page 2')], + total: 2, + page: 1, + pageSize: 30, + hasMore: false, + }) + await flush() + }) + + expect(findHostByTestId(renderer, 'knowledge-document-doc-stale')).toHaveLength(0) + activeRenderer = null + act(() => renderer.unmount()) + }) + + test('RecordScreen_공유미디어가져오기중단시_오류대신idle상태로복귀', async () => { + const input: LocalAudioInput = { + uri: 'file:///cache/shared.wav', + path: '/cache/shared.wav', + fileName: 'shared.wav', + mimeType: 'audio/wav', + sizeBytes: 1_024, + durationMs: 2_000, + source: 'share-intent', + dispose: jest.fn(async () => undefined), + } + mockConsumeIncomingMediaAudio.mockResolvedValueOnce(input) + mockEnqueueAudioProcessing.mockResolvedValueOnce({ id: 'queue-1' }) + mockProcessQueuedAudioNow.mockRejectedValueOnce(new AudioPipelineError('cancelled', 'Import cancelled')) + + let renderer!: ReactTestRenderer + await act(async () => { + renderer = create( + undefined, setParams: jest.fn() }} + />, + ) + activeRenderer = renderer + await flush() + }) + + expect(findHostByTestId(renderer, 'record-error')).toHaveLength(0) + activeRenderer = null + act(() => renderer.unmount()) + }) + + test('HistoryDetailScreen_오디오전환후이전URL응답시_오래된트랙재생을시작하지않음', async () => { + const detail: HistoryDetail = { + entry: { + id: HISTORY_ID, + user_id: USER_A, + title: 'Memo', + original_text: 'Body', + polished_text: null, + focused_app: null, + focused_app_name: null, + focused_app_window_title: null, + mode: 'dictation', + status: 'completed', + error_code: null, + audio_storage_key: 'audio/sample.wav', + duration: 12, + detected_language: 'ko', + mic_device: null, + word_count: 1, + stt_model: 'whisper', + llm_model: null, + stt_latency_ms: null, + llm_latency_ms: null, + app_version: '1.16.5', + summary_text: null, + is_favorite: false, + revision: 1, + created_at: '2026-08-21T00:00:00.000Z', + updated_at: '2026-08-21T00:00:00.000Z', + }, + audioFiles: [ + { + id: AUDIO_ID, + user_id: USER_A, + history_id: HISTORY_ID, + meeting_id: null, + storage_bucket: 'audio-files', + storage_key: 'audio/sample-1.wav', + original_name: 'sample-1.wav', + mime_type: 'audio/wav', + size_bytes: 2_048, + duration_ms: 12_000, + checksum_sha256: 'abc', + upload_status: 'uploaded', + retention_until: null, + created_at: '2026-08-21T00:00:00.000Z', + updated_at: '2026-08-21T00:00:00.000Z', + }, + { + id: AUDIO_ID_2, + user_id: USER_A, + history_id: HISTORY_ID, + meeting_id: null, + storage_bucket: 'audio-files', + storage_key: 'audio/sample-2.wav', + original_name: 'sample-2.wav', + mime_type: 'audio/wav', + size_bytes: 2_048, + duration_ms: 12_000, + checksum_sha256: 'def', + upload_status: 'uploaded', + retention_until: null, + created_at: '2026-08-21T00:00:00.000Z', + updated_at: '2026-08-21T00:00:00.000Z', + }, + ], + jobs: [], + } + mockGetHistoryDetail.mockResolvedValueOnce(detail) + const slowUrlGate = deferred() + mockCreateAudioPlaybackUrl + .mockReturnValueOnce(slowUrlGate.promise) + .mockResolvedValueOnce('https://storage.example/track-2.wav') + + let renderer!: ReactTestRenderer + await act(async () => { + renderer = create( + , + ) + activeRenderer = renderer + await flush() + }) + + const row1 = renderer.root.findByProps({ testID: `history-audio-${AUDIO_ID}` }) + const row2 = renderer.root.findByProps({ testID: `history-audio-${AUDIO_ID_2}` }) + const play1 = row1.findAll( + (node) => typeof node.props.onPress === 'function' && node.props.accessibilityLabel === 'mobile.hist.audioPlay', + )[0] + const play2 = row2.findAll( + (node) => typeof node.props.onPress === 'function' && node.props.accessibilityLabel === 'mobile.hist.audioPlay', + )[0] + + await act(async () => { + // Simulate rapid tap on track 1 then track 2 before React disables buttons. + play1.props.onPress() + play2.props.onPress() + await flush() + }) + + await act(async () => { + slowUrlGate.resolve('https://storage.example/track-1.wav') + await flush() + }) + + expect(mockStartPlayer).toHaveBeenCalledTimes(1) + activeRenderer = null + act(() => renderer.unmount()) + }) + + test('CommandsScreen_저장충돌실패전언마운트시_카탈로그재조회를시작하지않음', async () => { + const command: SyncedCommand = { + id: COMMAND_ID, + userId: USER_A, + builtinKey: null, + name: 'Summarize', + description: '', + prompt: 'Summarize: {{text}}', + icon: 'bolt', + sortOrder: 0, + revision: 1, + createdAt: '2026-08-21T00:00:00.000Z', + updatedAt: '2026-08-21T00:00:00.000Z', + } + mockLoadSyncedCommandCatalog.mockResolvedValue({ + commands: [command], + activeCommandId: null, + }) + const saveGate = deferred() + mockCreateSyncedCommand.mockReturnValueOnce(saveGate.promise) + + let renderer!: ReactTestRenderer + await act(async () => { + renderer = create() + activeRenderer = renderer + await flush() + }) + expect(mockLoadSyncedCommandCatalog).toHaveBeenCalledTimes(1) + + act(() => { + renderer.root.findByProps({ testID: 'commands-add' }).props.onPress() + }) + const editor = renderer.root.findByProps({ testID: 'commands-editor' }) + const inputs = editor.findAllByType(TextInput) + act(() => { + inputs[0]?.props.onChangeText('New Command') + inputs[2]?.props.onChangeText('Prompt: {{text}}') + }) + + await act(async () => { + renderer.root.findByProps({ testID: 'commands-editor-save' }).props.onPress() + await Promise.resolve() + }) + + activeRenderer = null + act(() => renderer.unmount()) + + await act(async () => { + saveGate.reject(new CommandSyncError('conflict', 'stale revision')) + await flush() + }) + + expect(mockLoadSyncedCommandCatalog).toHaveBeenCalledTimes(1) + }) + + test('TeamsScreen_팀생성중언마운트시_상세화면으로이동하지않음', async () => { + mockListTeams.mockResolvedValueOnce([]) + const createGate = deferred<{ + id: string + name: string + ownerId: string + role: 'owner' + memberCount: number + createdAt: string + updatedAt: string + }>() + mockCreateTeam.mockReturnValueOnce(createGate.promise) + + let renderer!: ReactTestRenderer + await act(async () => { + renderer = create() + activeRenderer = renderer + await flush() + }) + + act(() => { + renderer.root.findByProps({ testID: 'teams-create' }).props.onPress() + }) + act(() => { + renderer.root.findByProps({ testID: 'team-name-input' }).props.onChangeText('Product Team') + }) + await act(async () => { + renderer.root.findByProps({ testID: 'team-create-submit' }).props.onPress() + await Promise.resolve() + }) + + activeRenderer = null + act(() => renderer.unmount()) + + await act(async () => { + createGate.resolve({ + id: TEAM_ID, + name: 'Product Team', + ownerId: USER_A, + role: 'owner', + memberCount: 1, + createdAt: '2026-08-21T00:00:00.000Z', + updatedAt: '2026-08-21T00:00:00.000Z', + }) + await flush() + }) + + expect(mockNavigate).not.toHaveBeenCalled() + }) +}) diff --git a/apps/mobile-rn/src/features/admin/admin-service.ts b/apps/mobile-rn/src/features/admin/admin-service.ts index ad9e53d..3c482a7 100644 --- a/apps/mobile-rn/src/features/admin/admin-service.ts +++ b/apps/mobile-rn/src/features/admin/admin-service.ts @@ -406,6 +406,9 @@ async function requestAdmin(path: string, options: RequestOptions): Promise controller.abort(), REQUEST_TIMEOUT_MS) try { + if (options.signal?.aborted === true) { + throw new AdminServiceError('network', null, false) + } const response = await fetch(`${SUPABASE_URL}/functions/v1/${path}`, { method: options.method ?? 'GET', headers: { diff --git a/apps/mobile-rn/src/features/chat/chat-service.ts b/apps/mobile-rn/src/features/chat/chat-service.ts index 9cf92c2..6e19a80 100644 --- a/apps/mobile-rn/src/features/chat/chat-service.ts +++ b/apps/mobile-rn/src/features/chat/chat-service.ts @@ -100,6 +100,9 @@ async function sendChatRequest( const timer = setTimeout(() => controller.abort(), options.timeoutMs ?? 45_000) try { + if (options.signal?.aborted === true) { + throw new ChatServiceError('CANCELLED', false) + } const headers: Record = { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json', diff --git a/apps/mobile-rn/src/features/devices/device-service.ts b/apps/mobile-rn/src/features/devices/device-service.ts index ed7e9ac..eb01bd7 100644 --- a/apps/mobile-rn/src/features/devices/device-service.ts +++ b/apps/mobile-rn/src/features/devices/device-service.ts @@ -87,6 +87,14 @@ const DEVICE_COLUMNS = [ export async function registerCurrentDevice( userId: string, config: MobileRuntimeConfig, +): Promise { + return registerCurrentDeviceAttempt(userId, config, true) +} + +async function registerCurrentDeviceAttempt( + userId: string, + config: MobileRuntimeConfig, + allowConflictRetry: boolean, ): Promise { requireUserId(userId) const existing = await supabase @@ -130,9 +138,11 @@ export async function registerCurrentDevice( .select(DEVICE_COLUMNS) .single() if (inserted.error) { - // A simultaneous bootstrap may have won the unique key. Fetching again is - // safe and never clears a remote revocation. - if (inserted.error.code === '23505') return registerCurrentDevice(userId, config) + // A simultaneous bootstrap may have won the unique key. Retry once safely + // while preventing infinite recursion when conflict errors persist. + if (inserted.error.code === '23505' && allowConflictRetry) { + return registerCurrentDeviceAttempt(userId, config, false) + } throw new DeviceServiceError('server') } return normalizeRegisteredDevice(inserted.data) diff --git a/apps/mobile-rn/src/features/history/use-history-sync.ts b/apps/mobile-rn/src/features/history/use-history-sync.ts index 5e45de7..edadce8 100644 --- a/apps/mobile-rn/src/features/history/use-history-sync.ts +++ b/apps/mobile-rn/src/features/history/use-history-sync.ts @@ -209,6 +209,7 @@ export function useHistorySync(): HistorySyncModel { try { const cached = await loadHistoryCache(userId) + if (currentRequest !== requestId.current) return if (cached !== null) { commitWindow({ entries: filterCachedHistory(cached.entries, filter, debouncedSearch), @@ -222,6 +223,7 @@ export function useHistorySync(): HistorySyncModel { setOffline(normalized.code === 'network') } } catch (cacheError) { + if (currentRequest !== requestId.current) return setCacheWarning(true) setError(normalized.code === 'network' ? normalized : syncError(cacheError)) setOffline(normalized.code === 'network') @@ -378,6 +380,7 @@ export function useHistorySync(): HistorySyncModel { entry.revision, { is_favorite: optimisticFavorite }, ) + if (!isCurrentScope()) return const replacement: HistoryListEntry = { ...entry, ...updated } updateEntries((current) => { if (filter === 'favorites' && !updated.is_favorite) { @@ -387,9 +390,11 @@ export function useHistorySync(): HistorySyncModel { }) await patchCachedEntry(entry.id, replacement, isCurrentScope) } catch (mutationError) { - updateEntries((current) => current.map((item) => ( - item.id === entry.id ? entry : item - ))) + if (isCurrentScope()) { + updateEntries((current) => current.map((item) => ( + item.id === entry.id ? entry : item + ))) + } throw mutationError } finally { endMutation(entry.id) @@ -404,9 +409,12 @@ export function useHistorySync(): HistorySyncModel { updateEntries((current) => current.filter((item) => item.id !== entry.id)) try { await deleteHistoryRevisionSafe(userId, entry.id, entry.revision) + if (!isCurrentScope()) return await patchCachedEntry(entry.id, null, isCurrentScope) } catch (mutationError) { - updateEntries((current) => mergeHistoryEntries(current, [entry])) + if (isCurrentScope()) { + updateEntries((current) => mergeHistoryEntries(current, [entry])) + } throw mutationError } finally { endMutation(entry.id) diff --git a/apps/mobile-rn/src/features/recording/durable-processing-queue.ts b/apps/mobile-rn/src/features/recording/durable-processing-queue.ts index b7159af..f7fcd6c 100644 --- a/apps/mobile-rn/src/features/recording/durable-processing-queue.ts +++ b/apps/mobile-rn/src/features/recording/durable-processing-queue.ts @@ -438,7 +438,14 @@ async function processItemCore(item: DurableQueueItem): Promise undefined); + throw new AudioPipelineError('cancelled', 'Queued audio processing was cancelled', error); + } + if (canRetry && !suspendedUsers.has(current.userId)) { + scheduler.arm(current.userId, current.nextAttemptAtMs); + } throw canRetry ? new QueuedAudioPendingError(current) : error; } finally { runningControllers.delete(item.id); @@ -523,6 +530,11 @@ export async function retryQueuedAudio(userId: string, itemId: string): Promise< const items = await readQueue(); const item = items.find(candidate => candidate.id === itemId && candidate.userId === userId); if (item === undefined) throw new AudioPipelineError('file-read', 'Queued audio was not found'); + if (item.status === 'running' || runningItemPromises.has(item.id)) return; + if (item.status === 'cleanup') { + await removeItem(item); + return; + } await replaceItem({ ...item, status: 'retry', diff --git a/apps/mobile-rn/src/features/talk/llm-stream-service.ts b/apps/mobile-rn/src/features/talk/llm-stream-service.ts index 7468ede..d2a715f 100644 --- a/apps/mobile-rn/src/features/talk/llm-stream-service.ts +++ b/apps/mobile-rn/src/features/talk/llm-stream-service.ts @@ -280,6 +280,7 @@ export async function streamTalkResponse( const generationId = response.headers.get('X-D3RO-Generation-Id')?.trim() ?? '' if (!isUuid(generationId)) { + await response.body?.cancel?.().catch(() => undefined) throw new ChatServiceError('INVALID_RESPONSE', true) } const text = await consumeStreamingBody(response, options.onTextDelta) diff --git a/apps/mobile-rn/src/lib/audio-recorder.ts b/apps/mobile-rn/src/lib/audio-recorder.ts index 971f5ce..ae7dd8e 100644 --- a/apps/mobile-rn/src/lib/audio-recorder.ts +++ b/apps/mobile-rn/src/lib/audio-recorder.ts @@ -44,6 +44,7 @@ export function createPlatformRecorderBackend(): RecorderBackend { export class AudioRecorder { private selectedBackend: RecorderBackend | null; private lease: RecorderOwner | null = null; + private pendingClaim: { owner: RecorderOwner; depth: number } | null = null; constructor(backend?: RecorderBackend) { this.selectedBackend = backend ?? null; @@ -102,6 +103,9 @@ export class AudioRecorder { } private async assertAvailable(owner: RecorderOwner): Promise { + if (this.pendingClaim !== null && this.pendingClaim.owner !== owner) { + throw new RecorderBusyError(this.pendingClaim.owner); + } const holder = await this.holder(); if (holder !== null && holder !== owner) throw new RecorderBusyError(holder); // Another owner may have started a capture while the status was read. @@ -115,9 +119,28 @@ export class AudioRecorder { claim: boolean, operation: () => Promise, ): Promise { - await this.assertAvailable(owner); - if (claim) this.lease = owner; - return operation(); + if (this.pendingClaim !== null && this.pendingClaim.owner !== owner) { + throw new RecorderBusyError(this.pendingClaim.owner); + } + if (claim) { + this.pendingClaim = this.pendingClaim?.owner === owner + ? { owner, depth: this.pendingClaim.depth + 1 } + : { owner, depth: 1 }; + } + try { + await this.assertAvailable(owner); + if (claim) this.lease = owner; + return await operation(); + } finally { + if (claim && this.pendingClaim?.owner === owner) { + if (this.pendingClaim.depth <= 1) { + this.pendingClaim = null; + } else { + this.pendingClaim = { owner, depth: this.pendingClaim.depth - 1 }; + } + this.releaseIfIdle(owner); + } + } } private async cleanupAsOwner( diff --git a/apps/mobile-rn/src/lib/billing-context.tsx b/apps/mobile-rn/src/lib/billing-context.tsx index 60bd3d7..53f2d8e 100644 --- a/apps/mobile-rn/src/lib/billing-context.tsx +++ b/apps/mobile-rn/src/lib/billing-context.tsx @@ -298,13 +298,24 @@ export function BillingProvider({ children }: { children: ReactNode }): React.Re const [errorCode, setErrorCode] = useState(null) const inFlightPurchases = useRef(new Set()) const userIdRef = useRef(user?.id ?? null) + const mountedRef = useRef(true) + const productsGenerationRef = useRef(0) const installedFromPlayStore = useMemo( () => Platform.OS === 'android' && getMobileRuntimeConfig().installedFromPlayStore, [], ) + useEffect(() => { + mountedRef.current = true + return () => { + mountedRef.current = false + productsGenerationRef.current += 1 + } + }, []) + useEffect(() => { userIdRef.current = user?.id ?? null + productsGenerationRef.current += 1 inFlightPurchases.current.clear() setOperation('idle') setErrorCode(null) @@ -329,11 +340,13 @@ export function BillingProvider({ children }: { children: ReactNode }): React.Re productId: purchase.productId, purchaseToken: purchase.purchaseToken, }) + if (!mountedRef.current || userIdRef.current !== currentUserId) return if (!result.ok) throw new Error(billingFailureCode(result)) const data = result.data const verifiedProduct = verifiedRestorableProduct(data, purchase.productId) const verification = data && isRecord(data.verification) ? data.verification : null const refreshed = await entitlement.refresh() + if (!mountedRef.current || userIdRef.current !== currentUserId) return if (verifiedProduct !== null) { if ( refreshed === null @@ -346,11 +359,15 @@ export function BillingProvider({ children }: { children: ReactNode }): React.Re throw new Error('purchase_not_verified_active') } } catch (candidate) { - if (userIdRef.current !== currentUserId) return + if (!mountedRef.current || userIdRef.current !== currentUserId) return + const resolvedErrorCode = await functionErrorCode(candidate) + if (!mountedRef.current || userIdRef.current !== currentUserId) return setOperation('failed') - setErrorCode(await functionErrorCode(candidate)) + setErrorCode(resolvedErrorCode) } finally { - inFlightPurchases.current.delete(identity) + if (userIdRef.current === currentUserId) { + inFlightPurchases.current.delete(identity) + } } }, [entitlement]) @@ -406,16 +423,20 @@ export function BillingProvider({ children }: { children: ReactNode }): React.Re setErrorCode('play_store_install_required') return } + const productsGeneration = ++productsGenerationRef.current setOperation('loading-products') setErrorCode(null) try { if (!connected) { const didReconnect = await reconnect() + if (!mountedRef.current || productsGeneration !== productsGenerationRef.current) return if (!didReconnect) throw new Error('store_connection_failed') } await fetchProducts({ skus: [...GOOGLE_PLAY_SUBSCRIPTION_IDS], type: 'subs' }) + if (!mountedRef.current || productsGeneration !== productsGenerationRef.current) return setOperation('idle') } catch (candidate) { + if (!mountedRef.current || productsGeneration !== productsGenerationRef.current) return setOperation('failed') setErrorCode(candidate instanceof Error ? candidate.message : 'product_fetch_failed') } @@ -454,6 +475,7 @@ export function BillingProvider({ children }: { children: ReactNode }): React.Re const replacementPurchases = currentProvider === 'google_play' ? await getAvailablePurchases({ includeSuspendedAndroid: true }) : [] + if (!mountedRef.current || userIdRef.current !== currentUserId) return const replacementPurchase = currentProvider === 'google_play' ? replacementPurchases.find((candidate) => ( candidate.productId === currentProductId @@ -491,6 +513,7 @@ export function BillingProvider({ children }: { children: ReactNode }): React.Re }, }) } catch (candidate) { + if (!mountedRef.current || userIdRef.current !== currentUserId) return setOperation('failed') setErrorCode(candidate instanceof Error ? candidate.message : 'purchase_failed') } @@ -525,7 +548,9 @@ export function BillingProvider({ children }: { children: ReactNode }): React.Re await restoreGooglePlayPurchaseSet( restoredPurchases, async (restoredPurchase) => { - if (userIdRef.current !== currentUserId) throw new Error('restore_session_changed') + if (!mountedRef.current || userIdRef.current !== currentUserId) { + throw new Error('restore_session_changed') + } const result = await invokeEdgeFunction('iap-verify', { platform: 'google_play', productId: restoredPurchase.productId, @@ -536,14 +561,18 @@ export function BillingProvider({ children }: { children: ReactNode }): React.Re return data }, async () => { - if (userIdRef.current !== currentUserId) throw new Error('restore_session_changed') + if (!mountedRef.current || userIdRef.current !== currentUserId) { + throw new Error('restore_session_changed') + } return entitlement.refresh() }, ) - if (userIdRef.current !== currentUserId) throw new Error('restore_session_changed') + if (!mountedRef.current || userIdRef.current !== currentUserId) { + throw new Error('restore_session_changed') + } setOperation('succeeded') } catch (candidate) { - if (userIdRef.current !== currentUserId) return + if (!mountedRef.current || userIdRef.current !== currentUserId) return setOperation('failed') setErrorCode(candidate instanceof Error ? candidate.message : 'restore_failed') } diff --git a/apps/mobile-rn/src/lib/device-context.tsx b/apps/mobile-rn/src/lib/device-context.tsx index 52b6647..75986fb 100644 --- a/apps/mobile-rn/src/lib/device-context.tsx +++ b/apps/mobile-rn/src/lib/device-context.tsx @@ -39,7 +39,12 @@ export function DeviceProvider({ children }: { children: ReactNode }): React.Rea const handleRevocation = useCallback(async (): Promise => { if (revocationHandledRef.current) return revocationHandledRef.current = true - await purgeLocalSession() + try { + await purgeLocalSession() + } catch (revocationError) { + revocationHandledRef.current = false + throw revocationError + } }, [purgeLocalSession]) const refreshCurrentDevice = useCallback(async (): Promise => { diff --git a/apps/mobile-rn/src/lib/entitlement-context.tsx b/apps/mobile-rn/src/lib/entitlement-context.tsx index dff7d6b..f9c2e02 100644 --- a/apps/mobile-rn/src/lib/entitlement-context.tsx +++ b/apps/mobile-rn/src/lib/entitlement-context.tsx @@ -280,7 +280,7 @@ function isCachedSnapshot(value: unknown, userId: string): value is CacheEnvelop } async function readCache(userId: string): Promise { - const serialized = await AsyncStorage.getItem(cacheKey(userId)) + const serialized = await AsyncStorage.getItem(cacheKey(userId)).catch(() => null) if (!serialized) return null try { const value: unknown = JSON.parse(serialized) @@ -393,7 +393,7 @@ export function EntitlementProvider({ children }: { children: ReactNode }): Reac setSnapshot(cached) setStale(true) setLoading(false) - }).finally(() => { + }).catch(() => null).finally(() => { if (!cancelled) void refresh() }) diff --git a/apps/mobile-rn/src/lib/mobile-ads-context.tsx b/apps/mobile-rn/src/lib/mobile-ads-context.tsx index 65ca648..59a265f 100644 --- a/apps/mobile-rn/src/lib/mobile-ads-context.tsx +++ b/apps/mobile-rn/src/lib/mobile-ads-context.tsx @@ -86,7 +86,8 @@ export function MobileAdsProvider({ children }: { children: ReactNode }): React. } }, []) - const initializeAds = useCallback(async (): Promise => { + const initializeAds = useCallback(async (expectedGeneration: number): Promise => { + if (expectedGeneration !== generation.current) return if (initialized.current) { setStatus('ready') return @@ -96,11 +97,17 @@ export function MobileAdsProvider({ children }: { children: ReactNode }): React. maxAdContentRating: MaxAdContentRating.T, testDeviceIdentifiers: runtimeConfig?.debug ? ['EMULATOR'] : undefined, }) + if (expectedGeneration !== generation.current) return await MobileAds().initialize() + if (expectedGeneration !== generation.current) return initialized.current = true setStatus('ready') }, [runtimeConfig?.debug]) + useEffect(() => () => { + generation.current += 1 + }, []) + useEffect(() => { const currentGeneration = ++generation.current if (!eligible) { @@ -127,7 +134,7 @@ export function MobileAdsProvider({ children }: { children: ReactNode }): React. setStatus('consent-blocked') return } - await initializeAds() + await initializeAds(currentGeneration) }) .catch((candidate) => { if (currentGeneration !== generation.current) return @@ -137,25 +144,36 @@ export function MobileAdsProvider({ children }: { children: ReactNode }): React. }, [eligible, initializeAds, runtimeConfig]) useEffect(() => { + let cancelled = false void AdsConsent.getConsentInfo().then((info) => { + if (cancelled) return setPrivacyOptionsRequired( info.privacyOptionsRequirementStatus === AdsConsentPrivacyOptionsRequirementStatus.REQUIRED, ) }).catch(() => undefined) + return () => { + cancelled = true + } }, []) const showPrivacyOptions = useCallback(async (): Promise => { + const opGeneration = generation.current + const opEligible = eligible try { const consentInfo = await AdsConsent.showPrivacyOptionsForm() + if (opGeneration !== generation.current) return false setPrivacyOptionsRequired( consentInfo.privacyOptionsRequirementStatus === AdsConsentPrivacyOptionsRequirementStatus.REQUIRED, ) - if (eligible && consentInfo.canRequestAds) await initializeAds() - if (eligible && !consentInfo.canRequestAds) setStatus('consent-blocked') + if (opEligible && consentInfo.canRequestAds) await initializeAds(opGeneration) + if (opEligible && !consentInfo.canRequestAds && opGeneration === generation.current) { + setStatus('consent-blocked') + } return true } catch (candidate) { + if (opGeneration !== generation.current) return false setErrorCode(candidateMessage(candidate, 'privacy_options_unavailable')) return false } @@ -318,6 +336,7 @@ export function useRewardedCredits(): RewardedCreditsValue { ).then(async (credited) => { if (currentGeneration !== verificationGeneration.current) return await entitlement.refresh() + if (currentGeneration !== verificationGeneration.current) return setStatus(credited ? 'credited' : 'verification-pending') }).catch((candidate) => { if (currentGeneration !== verificationGeneration.current) return diff --git a/apps/mobile-rn/src/lib/recorder/android-foreground-backend.ts b/apps/mobile-rn/src/lib/recorder/android-foreground-backend.ts index 17d6fd2..1253674 100644 --- a/apps/mobile-rn/src/lib/recorder/android-foreground-backend.ts +++ b/apps/mobile-rn/src/lib/recorder/android-foreground-backend.ts @@ -139,6 +139,8 @@ export class AndroidForegroundRecorderBackend implements RecorderBackend { private progressHandler: RecordingProgressHandler | null = null; private stateHandler: RecordingStateHandler | null = null; private pollGeneration = 0; + private pollTimer: ReturnType | null = null; + private sessionGeneration = 0; async requestPermission(): Promise { const permission = PermissionsAndroid.PERMISSIONS.RECORD_AUDIO; @@ -163,6 +165,7 @@ export class AndroidForegroundRecorderBackend implements RecorderBackend { throw new Error(`Cannot start recorder while it is ${this.state}`); } + const sessionGen = ++this.sessionGeneration; this.state = 'starting'; this.progressHandler = onProgress; this.stateHandler = options.onStateChange ?? null; @@ -174,6 +177,10 @@ export class AndroidForegroundRecorderBackend implements RecorderBackend { : { meetingId: options.meetingId }, ), ); + if (sessionGen !== this.sessionGeneration) { + await androidRecordingModule().cancel().catch(() => undefined); + throw new Error('Recording start was cancelled'); + } if (snapshot.state !== 'recording' || snapshot.recording === null) { throw new Error('Android foreground recorder did not start'); } @@ -186,10 +193,9 @@ export class AndroidForegroundRecorderBackend implements RecorderBackend { this.stateHandler?.(snapshot); this.startPolling(); } catch (error) { - this.progressHandler = null; - this.stateHandler = null; - this.currentPath = null; - this.state = 'idle'; + if (sessionGen === this.sessionGeneration) { + this.resetToIdle(); + } throw error; } } @@ -199,14 +205,20 @@ export class AndroidForegroundRecorderBackend implements RecorderBackend { throw new Error(`Cannot pause recorder while it is ${this.state}`); } + const sessionGen = this.sessionGeneration; this.state = 'pausing'; try { const snapshot = parseNativeSnapshot(await androidRecordingModule().pause()); + if (sessionGen !== this.sessionGeneration) { + throw new Error('Recording was cancelled'); + } if (snapshot.state !== 'paused') throw new Error('Android recorder did not pause'); this.state = 'paused'; this.stateHandler?.(snapshot); } catch (error) { - this.state = 'recording'; + if (sessionGen === this.sessionGeneration) { + this.state = 'recording'; + } throw error; } } @@ -216,14 +228,20 @@ export class AndroidForegroundRecorderBackend implements RecorderBackend { throw new Error(`Cannot resume recorder while it is ${this.state}`); } + const sessionGen = this.sessionGeneration; this.state = 'resuming'; try { const snapshot = parseNativeSnapshot(await androidRecordingModule().resume()); + if (sessionGen !== this.sessionGeneration) { + throw new Error('Recording was cancelled'); + } if (snapshot.state !== 'recording') throw new Error('Android recorder did not resume'); this.state = 'recording'; this.stateHandler?.(snapshot); } catch (error) { - this.state = 'paused'; + if (sessionGen === this.sessionGeneration) { + this.state = 'paused'; + } throw error; } } @@ -234,13 +252,19 @@ export class AndroidForegroundRecorderBackend implements RecorderBackend { } if (this.currentPath === null) throw new Error('Recorder has no output path'); + const sessionGen = this.sessionGeneration; const previousState = this.state; this.state = 'stopping'; let snapshot: RecordingRuntimeSnapshot; try { snapshot = parseNativeSnapshot(await androidRecordingModule().stop()); + if (sessionGen !== this.sessionGeneration) { + throw new Error('Recording was cancelled'); + } } catch (error) { - await this.resyncAfterFailedStop(previousState, null); + if (sessionGen === this.sessionGeneration) { + await this.resyncAfterFailedStop(previousState, null); + } throw error; } @@ -273,14 +297,19 @@ export class AndroidForegroundRecorderBackend implements RecorderBackend { if (recording !== undefined && this.currentPath !== null && path !== this.currentPath) { return; } + this.sessionGeneration += 1; this.stopPolling(); this.resetToIdle(); } async cancel(): Promise { + const cancelGen = ++this.sessionGeneration; this.stopPolling(); - await androidRecordingModule().cancel(); this.resetToIdle(); + await androidRecordingModule().cancel(); + if (cancelGen === this.sessionGeneration) { + this.resetToIdle(); + } } async restore( @@ -288,6 +317,7 @@ export class AndroidForegroundRecorderBackend implements RecorderBackend { onStateChange?: RecordingStateHandler, ): Promise { const snapshot = parseNativeSnapshot(await androidRecordingModule().getStatus()); + this.sessionGeneration += 1; this.stopPolling(); this.progressHandler = onProgress ?? null; this.stateHandler = onStateChange ?? null; @@ -386,7 +416,13 @@ export class AndroidForegroundRecorderBackend implements RecorderBackend { this.stateHandler?.(snapshot); if (snapshot.state === 'recording' || snapshot.state === 'paused') { this.state = snapshot.state; - setTimeout(() => { void poll(); }, 250); + if (generation === this.pollGeneration) { + if (this.pollTimer !== null) clearTimeout(this.pollTimer); + this.pollTimer = setTimeout(() => { + this.pollTimer = null; + void poll(); + }, 250); + } } else { this.currentPath = snapshot.recording?.path ?? null; this.state = snapshot.state === 'idle' ? 'idle' : 'stopped'; @@ -394,7 +430,11 @@ export class AndroidForegroundRecorderBackend implements RecorderBackend { } catch { // A transient React bridge failure must not stop the native foreground capture. if (generation === this.pollGeneration) { - setTimeout(() => { void poll(); }, 500); + if (this.pollTimer !== null) clearTimeout(this.pollTimer); + this.pollTimer = setTimeout(() => { + this.pollTimer = null; + void poll(); + }, 500); } } }; @@ -403,5 +443,9 @@ export class AndroidForegroundRecorderBackend implements RecorderBackend { private stopPolling(): void { this.pollGeneration += 1; + if (this.pollTimer !== null) { + clearTimeout(this.pollTimer); + this.pollTimer = null; + } } } diff --git a/apps/mobile-rn/src/lib/recorder/nitro-backend.ts b/apps/mobile-rn/src/lib/recorder/nitro-backend.ts index d9f0573..5b037dc 100644 --- a/apps/mobile-rn/src/lib/recorder/nitro-backend.ts +++ b/apps/mobile-rn/src/lib/recorder/nitro-backend.ts @@ -104,6 +104,7 @@ export class NitroRecorderBackend implements RecorderBackend { private state: NitroRecorderState = 'idle'; private currentPath: string | null = null; private progress: RecordingProgress = { durationMs: 0, meteringDb: null }; + private startGeneration = 0; private pendingStart: Promise | null = null; private pendingTransition: Promise | null = null; private pendingStop: Promise | null = null; @@ -144,14 +145,21 @@ export class NitroRecorderBackend implements RecorderBackend { throw new Error(`Cannot start recorder while it is ${this.state}`); } + const generation = ++this.startGeneration; this.state = 'starting'; try { await deleteStaleTemporaryFiles(); } catch (error) { - this.state = 'idle'; + if (generation === this.startGeneration) { + this.state = 'idle'; + } throw error; } + if (generation !== this.startGeneration) { + throw new Error('Recording start was cancelled'); + } + const outputPath = createTemporaryPath(); this.currentPath = outputPath; this.progress = { durationMs: 0, meteringDb: null }; @@ -296,10 +304,15 @@ export class NitroRecorderBackend implements RecorderBackend { } async cancel(): Promise { + this.startGeneration += 1; if (this.state === 'starting' && this.pendingStart !== null) { try { await this.pendingStart; } catch { + this.progressHandler = null; + this.currentPath = null; + this.state = 'idle'; + this.progress = { durationMs: 0, meteringDb: null }; return; } } diff --git a/apps/mobile-rn/src/screens/CommandsScreen.tsx b/apps/mobile-rn/src/screens/CommandsScreen.tsx index 68dd52d..c413735 100644 --- a/apps/mobile-rn/src/screens/CommandsScreen.tsx +++ b/apps/mobile-rn/src/screens/CommandsScreen.tsx @@ -176,16 +176,25 @@ export default function CommandsScreen(): React.ReactElement { return () => { void supabase.removeChannel(channel) } }, [load, user?.id]) + const actorUserIdRef = useRef(user?.id ?? null) + useEffect(() => { + actorUserIdRef.current = user?.id ?? null + }, [user?.id]) + async function toggleActive(command: SyncedCommand): Promise { if (!user?.id || mutationId) return + const actorUserId = user.id setMutationId(command.id) try { - setActiveId(await setActiveSyncedCommand(user.id, activeId === command.id ? null : command.id)) + const nextActiveId = await setActiveSyncedCommand(actorUserId, activeId === command.id ? null : command.id) + if (!alive.current || actorUserIdRef.current !== actorUserId) return + setActiveId(nextActiveId) setSyncError(null) } catch (error) { + if (!alive.current || actorUserIdRef.current !== actorUserId) return setSyncError(error instanceof CommandSyncError ? error.code : 'server') } finally { - setMutationId(null) + if (alive.current) setMutationId(null) } } @@ -207,42 +216,48 @@ export default function CommandsScreen(): React.ReactElement { async function save(): Promise { if (!editor || !user?.id || mutationId) return + const actorUserId = user.id setMutationId(editor.command?.id ?? 'create') setEditorError(null) try { const saved = editor.command - ? await updateSyncedCommand(user.id, editor.command, editor) - : await createSyncedCommand(user.id, { + ? await updateSyncedCommand(actorUserId, editor.command, editor) + : await createSyncedCommand(actorUserId, { ...editor, sortOrder: Math.max(1000, ...commands.map((item) => item.sortOrder + 10)), }) + if (!alive.current || actorUserIdRef.current !== actorUserId) return const next = [...commands.filter((item) => item.id !== saved.id), saved] .sort((a, b) => a.sortOrder - b.sortOrder || a.createdAt.localeCompare(b.createdAt)) setCommands(next) setSelectedId(saved.id) setEditor(null) } catch (error) { + if (!alive.current || actorUserIdRef.current !== actorUserId) return const code = error instanceof CommandSyncError ? error.code : 'server' setEditorError(code) if (code === 'conflict') void load(false, true) } finally { - setMutationId(null) + if (alive.current) setMutationId(null) } } async function remove(command: SyncedCommand): Promise { if (!user?.id || mutationId) return + const actorUserId = user.id setMutationId(command.id) try { - await deleteSyncedCommand(user.id, command) + await deleteSyncedCommand(actorUserId, command) + if (!alive.current || actorUserIdRef.current !== actorUserId) return const next = commands.filter((item) => item.id !== command.id) setCommands(next) if (selectedId === command.id) setSelectedId(next[0]?.id ?? null) if (activeId === command.id) setActiveId(null) } catch (error) { + if (!alive.current || actorUserIdRef.current !== actorUserId) return setSyncError(error instanceof CommandSyncError ? error.code : 'server') } finally { - setMutationId(null) + if (alive.current) setMutationId(null) } } @@ -259,18 +274,23 @@ export default function CommandsScreen(): React.ReactElement { async function move(command: SyncedCommand, direction: 'up' | 'down'): Promise { if (!user?.id || mutationId) return + const actorUserId = user.id setMutationId(command.id) try { - setCommands(await reorderSyncedCommand(user.id, command, direction)) + const reordered = await reorderSyncedCommand(actorUserId, command, direction) + if (!alive.current || actorUserIdRef.current !== actorUserId) return + setCommands(reordered) } catch (error) { + if (!alive.current || actorUserIdRef.current !== actorUserId) return setSyncError(error instanceof CommandSyncError ? error.code : 'server') } finally { - setMutationId(null) + if (alive.current) setMutationId(null) } } const run = useCallback(async (): Promise => { if (!selected || running) return + const actorUserId = actorUserIdRef.current const token = session?.access_token ?? '' if (!token) { setRunError('AUTH_REQUIRED') @@ -283,12 +303,15 @@ export default function CommandsScreen(): React.ReactElement { setRunError(null) setRetryable(false) try { - setOutput(await executeSyncedCommand(selected, input, { + const result = await executeSyncedCommand(selected, input, { accessToken: token, model: preferences.preferredLlmModel, signal: controller.signal, - })) + }) + if (!alive.current || actorUserIdRef.current !== actorUserId) return + setOutput(result) } catch (error) { + if (!alive.current || actorUserIdRef.current !== actorUserId) return const failure = error instanceof CommandExecutionError ? error : new CommandExecutionError('SERVER_ERROR', true) diff --git a/apps/mobile-rn/src/screens/HistoryDetailScreen.tsx b/apps/mobile-rn/src/screens/HistoryDetailScreen.tsx index 33cfdba..e5fe1b3 100644 --- a/apps/mobile-rn/src/screens/HistoryDetailScreen.tsx +++ b/apps/mobile-rn/src/screens/HistoryDetailScreen.tsx @@ -89,6 +89,7 @@ export default function HistoryDetailScreen({ playerRef.current = player const mountedRef = useRef(true) const loadGenerationRef = useRef(0) + const playbackGenerationRef = useRef(0) const [detail, setDetail] = useState(null) const [loading, setLoading] = useState(true) const [error, setError] = useState(null) @@ -109,6 +110,7 @@ export default function HistoryDetailScreen({ return () => { mountedRef.current = false loadGenerationRef.current += 1 + playbackGenerationRef.current += 1 void Promise.resolve(playerRef.current.stopPlayer()).catch(() => undefined) } }, []) @@ -306,53 +308,62 @@ export default function HistoryDetailScreen({ const controlAudio = async (audioFile: AudioFile): Promise => { if (user === null || audioBusy) return + const playbackGeneration = ++playbackGenerationRef.current setAudioBusy(true) setError(null) try { if (activeAudioId === audioFile.id && player.state.isPlaying) { await player.pausePlayer() - if (mountedRef.current) setPaused(true) + if (mountedRef.current && playbackGeneration === playbackGenerationRef.current) setPaused(true) return } if (activeAudioId === audioFile.id && paused) { await player.resumePlayer() - if (mountedRef.current) setPaused(false) + if (mountedRef.current && playbackGeneration === playbackGenerationRef.current) setPaused(false) return } if (activeAudioId !== null) { await player.stopPlayer() - if (!mountedRef.current) return + if (!mountedRef.current || playbackGeneration !== playbackGenerationRef.current) return } const signedUrl = await createAudioPlaybackUrl(user.id, audioFile) - if (!mountedRef.current) return + if (!mountedRef.current || playbackGeneration !== playbackGenerationRef.current) return await player.startPlayer(signedUrl) if (!mountedRef.current) { void Promise.resolve(player.stopPlayer()).catch(() => undefined) return } + if (playbackGeneration !== playbackGenerationRef.current) return setActiveAudioId(audioFile.id) setPaused(false) } catch { - if (!mountedRef.current) return + if (!mountedRef.current || playbackGeneration !== playbackGenerationRef.current) return setActiveAudioId(null) setPaused(false) setError(t('mobile.hist.audioError')) } finally { - if (mountedRef.current) setAudioBusy(false) + if (mountedRef.current && playbackGeneration === playbackGenerationRef.current) { + setAudioBusy(false) + } } } const stopAudio = async (): Promise => { + const playbackGeneration = ++playbackGenerationRef.current setAudioBusy(true) try { await player.stopPlayer() - if (!mountedRef.current) return + if (!mountedRef.current || playbackGeneration !== playbackGenerationRef.current) return setActiveAudioId(null) setPaused(false) } catch { - if (mountedRef.current) setError(t('mobile.hist.audioError')) + if (mountedRef.current && playbackGeneration === playbackGenerationRef.current) { + setError(t('mobile.hist.audioError')) + } } finally { - if (mountedRef.current) setAudioBusy(false) + if (mountedRef.current && playbackGeneration === playbackGenerationRef.current) { + setAudioBusy(false) + } } } diff --git a/apps/mobile-rn/src/screens/HomeScreen.tsx b/apps/mobile-rn/src/screens/HomeScreen.tsx index 8b71b97..24bd413 100644 --- a/apps/mobile-rn/src/screens/HomeScreen.tsx +++ b/apps/mobile-rn/src/screens/HomeScreen.tsx @@ -1,7 +1,7 @@ // src/screens/HomeScreen.tsx — 홈(오늘). 데스크톱 HomePage 와 같은 문법: // 제목·날짜 → 녹음 시작 안내 → 한 줄 요약 → 최근 기록 5 · 최근 회의 3 → (무료) 요금제 한 줄. // 카드·통계 격자 없이 제목 + 1px 선. 조회한 값만 보여 주고, 못 불러오면 그렇다고 말한다. -import { useCallback, useMemo, useState } from 'react' +import { useCallback, useEffect, useMemo, useRef, useState } from 'react' import { Pressable, RefreshControl, @@ -91,21 +91,46 @@ export default function HomeScreen(): React.ReactElement { const [meetingsError, setMeetingsError] = useState(false) const [loading, setLoading] = useState(true) const [refreshing, setRefreshing] = useState(false) + const mountedRef = useRef(true) + const refreshGenerationRef = useRef(0) + const currentUserIdRef = useRef(user?.id ?? null) + + useEffect(() => { + mountedRef.current = true + return () => { + mountedRef.current = false + refreshGenerationRef.current += 1 + } + }, []) + + useEffect(() => { + currentUserIdRef.current = user?.id ?? null + }, [user?.id]) const refresh = useCallback(async (pullToRefresh = false): Promise => { - if (!user?.id) { + const generation = ++refreshGenerationRef.current + const targetUserId = user?.id ?? null + if (!targetUserId) { + setStats(null) + setMeetings(null) setStatsError(true) setMeetingsError(true) setLoading(false) + setRefreshing(false) return } if (pullToRefresh) setRefreshing(true) else setLoading(true) const [statsResult, meetingsResult] = await Promise.allSettled([ - loadDashboardStats(user.id), - listMeetingsPage({ userId: user.id, page: 0, pageSize: RECENT_MEETING_LIMIT }), + loadDashboardStats(targetUserId), + listMeetingsPage({ userId: targetUserId, page: 0, pageSize: RECENT_MEETING_LIMIT }), refreshEntitlement(), ]) + if ( + !mountedRef.current + || generation !== refreshGenerationRef.current + || currentUserIdRef.current !== targetUserId + ) return if (statsResult.status === 'fulfilled') { setStats(statsResult.value) setStatsError(false) diff --git a/apps/mobile-rn/src/screens/KnowledgeScreen.tsx b/apps/mobile-rn/src/screens/KnowledgeScreen.tsx index 9a2abb2..c72db62 100644 --- a/apps/mobile-rn/src/screens/KnowledgeScreen.tsx +++ b/apps/mobile-rn/src/screens/KnowledgeScreen.tsx @@ -127,6 +127,7 @@ export default function KnowledgeScreen(): React.ReactElement { const loadMore = async (): Promise => { if (user === null || loading || loadingMore || !hasMore) return + const generation = requestGeneration.current const targetPage = page + 1 setLoadingMore(true) try { @@ -135,14 +136,16 @@ export default function KnowledgeScreen(): React.ReactElement { search: activeDocumentSearch, page: targetPage, }) + if (generation !== requestGeneration.current) return setDocuments((current) => mergeKnowledgeDocuments(current, result.documents)) setPage(targetPage) setTotal(result.total) setHasMore(result.hasMore) } catch (requestError) { + if (generation !== requestGeneration.current) return setError(errorCode(requestError)) } finally { - setLoadingMore(false) + if (generation === requestGeneration.current) setLoadingMore(false) } } diff --git a/apps/mobile-rn/src/screens/MeetingsScreen.tsx b/apps/mobile-rn/src/screens/MeetingsScreen.tsx index 23f23a0..cd90bee 100644 --- a/apps/mobile-rn/src/screens/MeetingsScreen.tsx +++ b/apps/mobile-rn/src/screens/MeetingsScreen.tsx @@ -61,6 +61,7 @@ export default function MeetingsScreen({ const templateRequestGeneration = useRef(0) const editorBusyRef = useRef(false) const editorUserIdRef = useRef(user?.id ?? null) + const mountedRef = useRef(true) const handledCreateRequests = useRef(new Set()) const openCreateRef = useRef<() => void>(() => undefined) const [meetings, setMeetings] = useState([]) @@ -85,6 +86,13 @@ export default function MeetingsScreen({ const [editorError, setEditorError] = useState(null) const [editorBusy, setEditorBusy] = useState(false) + useEffect(() => { + mountedRef.current = true + return () => { + mountedRef.current = false + } + }, []) + useEffect(() => { const nextUserId = user?.id ?? null if (editorUserIdRef.current === nextUserId) return @@ -152,6 +160,7 @@ export default function MeetingsScreen({ const loadMore = async (): Promise => { if (user === null || loading || loadingMore || !hasMore) return + const generation = requestGeneration.current const targetPage = page + 1 setLoadingMore(true) try { @@ -160,14 +169,18 @@ export default function MeetingsScreen({ search: committedSearch, page: targetPage, }) + if (generation !== requestGeneration.current || !mountedRef.current) return setMeetings((current) => mergeMeetings(current, result.meetings)) setPage(targetPage) setTotal(result.total) setHasMore(result.hasMore) } catch (requestError) { + if (generation !== requestGeneration.current || !mountedRef.current) return setError(meetingErrorMessage(requestError, t)) } finally { - setLoadingMore(false) + if (generation === requestGeneration.current && mountedRef.current) { + setLoadingMore(false) + } } } @@ -257,6 +270,7 @@ export default function MeetingsScreen({ const saveEditor = async (): Promise => { if (user === null || editor === null || editorBusyRef.current) return const mode = editor + const actorUserId = user.id editorBusyRef.current = true setEditorBusy(true) setEditorError(null) @@ -269,13 +283,14 @@ export default function MeetingsScreen({ .split(/[\r\n,]+/) .map((attendee) => attendee.trim()) .filter((attendee) => attendee.length > 0) - const created = await createMeetingWorkspaceWithMetadata(user.id, { + const created = await createMeetingWorkspaceWithMetadata(actorUserId, { title: editorTitle, attendees, language: editorLanguage, templateId: editorTemplateId, idempotencyKey: editorCreationKey, }) + if (!mountedRef.current || editorUserIdRef.current !== actorUserId) return setMeetings((current) => mergeMeetings([created], current)) setTotal((current) => current + 1) setEditor(null) @@ -295,16 +310,20 @@ export default function MeetingsScreen({ } } else { const updated = await updateMeetingTitleRevisionSafe(mode.meeting, editorTitle) + if (!mountedRef.current || editorUserIdRef.current !== actorUserId) return setMeetings((current) => current.map((meeting) => ( meeting.id === updated.id ? updated : meeting ))) setEditor(null) } } catch (requestError) { + if (!mountedRef.current || editorUserIdRef.current !== actorUserId) return setEditorError(meetingErrorMessage(requestError, t)) } finally { - editorBusyRef.current = false - setEditorBusy(false) + if (mountedRef.current && editorUserIdRef.current === actorUserId) { + editorBusyRef.current = false + setEditorBusy(false) + } } } diff --git a/apps/mobile-rn/src/screens/RecordScreen.tsx b/apps/mobile-rn/src/screens/RecordScreen.tsx index 5702d43..4f56b16 100644 --- a/apps/mobile-rn/src/screens/RecordScreen.tsx +++ b/apps/mobile-rn/src/screens/RecordScreen.tsx @@ -703,6 +703,10 @@ export default function RecordScreen({ route, navigation }: RecordScreenProps): await processInput(input); } catch (importError) { if (!mountedRef.current) return; + if (importError instanceof AudioPipelineError && importError.code === 'cancelled') { + setState('idle'); + return; + } setError(errorMessage(importError, t('mobile.rec.sharedImportFailed'))); setState('error'); } finally { diff --git a/apps/mobile-rn/src/screens/TeamsScreen.tsx b/apps/mobile-rn/src/screens/TeamsScreen.tsx index 3782d48..8a4248c 100644 --- a/apps/mobile-rn/src/screens/TeamsScreen.tsx +++ b/apps/mobile-rn/src/screens/TeamsScreen.tsx @@ -1,4 +1,4 @@ -import { useCallback, useMemo, useRef, useState } from 'react' +import { useCallback, useEffect, useMemo, useRef, useState } from 'react' import { ActivityIndicator, KeyboardAvoidingView, @@ -37,6 +37,8 @@ export default function TeamsScreen({ navigation }: TeamsScreenProps): React.Rea const { palette } = useMobilePreferences() const styles = useMemo(() => createStyles(palette), [palette]) const loadGeneration = useRef(0) + const mountedRef = useRef(true) + const userIdRef = useRef(user?.id ?? null) const [teams, setTeams] = useState([]) const [loading, setLoading] = useState(true) const [refreshing, setRefreshing] = useState(false) @@ -70,6 +72,17 @@ export default function TeamsScreen({ navigation }: TeamsScreenProps): React.Rea } }, [user]) + useEffect(() => { + mountedRef.current = true + return () => { + mountedRef.current = false + } + }, []) + + useEffect(() => { + userIdRef.current = user?.id ?? null + }, [user?.id]) + useFocusEffect(useCallback(() => { void load(false) return () => { loadGeneration.current += 1 } @@ -77,18 +90,21 @@ export default function TeamsScreen({ navigation }: TeamsScreenProps): React.Rea const submitCreate = async (): Promise => { if (user === null || editorBusy) return + const actorUserId = user.id setEditorBusy(true) setEditorError(null) try { - const team = await createTeam(user.id, name) + const team = await createTeam(actorUserId, name) + if (!mountedRef.current || userIdRef.current !== actorUserId) return setTeams((current) => [team, ...current.filter((row) => row.id !== team.id)]) setName('') setEditorOpen(false) navigation.navigate('TeamDetail', { teamId: team.id }) } catch (requestError) { + if (!mountedRef.current || userIdRef.current !== actorUserId) return setEditorError(teamErrorCode(requestError)) } finally { - setEditorBusy(false) + if (mountedRef.current) setEditorBusy(false) } }