fix(mobile): harden recorder, queue, context, and screen async lifecycles
This commit is contained in:
parent
3f9e412257
commit
bd3c1a98d9
25 changed files with 2279 additions and 68 deletions
87
apps/mobile-rn/__tests__/abort-and-stream-guards.test.ts
Normal file
87
apps/mobile-rn/__tests__/abort-and-stream-guards.test.ts
Normal file
|
|
@ -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)
|
||||||
|
})
|
||||||
|
})
|
||||||
467
apps/mobile-rn/__tests__/context-lifecycle-guards.test.tsx
Normal file
467
apps/mobile-rn/__tests__/context-lifecycle-guards.test.tsx
Normal file
|
|
@ -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<Promise<unknown>, []>(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<string, unknown> & {
|
||||||
|
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<T>() {
|
||||||
|
let resolve: (value: T) => void = () => undefined
|
||||||
|
let reject: (reason?: unknown) => void = () => undefined
|
||||||
|
const promise = new Promise<T>((res, rej) => {
|
||||||
|
resolve = res
|
||||||
|
reject = rej
|
||||||
|
})
|
||||||
|
return { promise, resolve, reject }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function flushMicrotasks(): Promise<void> {
|
||||||
|
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<unknown[]>()
|
||||||
|
mockedAds.MobileAds.mockImplementation(() => ({
|
||||||
|
setRequestConfiguration: jest.fn(async () => undefined),
|
||||||
|
initialize: jest.fn(() => initGate.promise),
|
||||||
|
}))
|
||||||
|
|
||||||
|
let latestAds: ReturnType<typeof useMobileAds> | null = null
|
||||||
|
function Probe(): null {
|
||||||
|
latestAds = useMobileAds()
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
let renderer!: ReactTestRenderer.ReactTestRenderer
|
||||||
|
await act(async () => {
|
||||||
|
renderer = ReactTestRenderer.create(
|
||||||
|
<MobileAdsProvider><Probe /></MobileAdsProvider>,
|
||||||
|
)
|
||||||
|
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(<MobileAdsProvider><Probe /></MobileAdsProvider>)
|
||||||
|
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<typeof useRewardedCredits> | 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<unknown>()
|
||||||
|
mockEntitlementHookValue.refresh = jest.fn(() => refreshGate.promise)
|
||||||
|
|
||||||
|
function Probe(): null {
|
||||||
|
latestRewarded = useRewardedCredits()
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
let renderer!: ReactTestRenderer.ReactTestRenderer
|
||||||
|
await act(async () => {
|
||||||
|
renderer = ReactTestRenderer.create(
|
||||||
|
<MobileAdsProvider><Probe /></MobileAdsProvider>,
|
||||||
|
)
|
||||||
|
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<unknown>()
|
||||||
|
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<typeof useBilling> | null = null
|
||||||
|
function Probe(): null {
|
||||||
|
latestBilling = useBilling()
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
let renderer!: ReactTestRenderer.ReactTestRenderer
|
||||||
|
await act(async () => {
|
||||||
|
renderer = ReactTestRenderer.create(
|
||||||
|
<BillingProvider><Probe /></BillingProvider>,
|
||||||
|
)
|
||||||
|
activeRenderer = renderer
|
||||||
|
await flushMicrotasks()
|
||||||
|
})
|
||||||
|
|
||||||
|
let pendingPurchase: Promise<unknown> = 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(<BillingProvider><Probe /></BillingProvider>)
|
||||||
|
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<typeof useDevice> | null = null
|
||||||
|
function Probe(): null {
|
||||||
|
latestDevice = useDevice()
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
let renderer!: ReactTestRenderer.ReactTestRenderer
|
||||||
|
await act(async () => {
|
||||||
|
renderer = ReactTestRenderer.create(
|
||||||
|
<DeviceProvider><Probe /></DeviceProvider>,
|
||||||
|
)
|
||||||
|
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<string, unknown> = {
|
||||||
|
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<typeof actualModule.useEntitlement> | null = null
|
||||||
|
function Probe(): null {
|
||||||
|
latestEnt = actualModule.useEntitlement()
|
||||||
|
return null
|
||||||
|
}
|
||||||
|
|
||||||
|
let renderer!: ReactTestRenderer.ReactTestRenderer
|
||||||
|
await act(async () => {
|
||||||
|
renderer = ReactTestRenderer.create(
|
||||||
|
<actualModule.EntitlementProvider><Probe /></actualModule.EntitlementProvider>,
|
||||||
|
)
|
||||||
|
activeRenderer = renderer
|
||||||
|
await flushMicrotasks()
|
||||||
|
await new Promise<void>((resolve) => setTimeout(resolve, 0))
|
||||||
|
})
|
||||||
|
|
||||||
|
process.off('unhandledRejection', onUnhandled)
|
||||||
|
expect(unhandledError).toBe(null)
|
||||||
|
expect(latestEnt?.loading).toBe(false)
|
||||||
|
act(() => renderer.unmount())
|
||||||
|
})
|
||||||
|
})
|
||||||
316
apps/mobile-rn/__tests__/queue-and-history-races.test.ts
Normal file
316
apps/mobile-rn/__tests__/queue-and-history-races.test.ts
Normal file
|
|
@ -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<Promise<AudioPipelineResult>, [LocalAudioInput, unknown]>()
|
||||||
|
const mockListHistoryPage = jest.fn<Promise<HistoryPageResult>, [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<string, string> }
|
||||||
|
|
||||||
|
function makeQueueItem(
|
||||||
|
userId: string,
|
||||||
|
suffix: string,
|
||||||
|
overrides: Partial<DurableQueueItem> = {},
|
||||||
|
): 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<T>() {
|
||||||
|
let resolve: (value: T) => void = () => undefined
|
||||||
|
let reject: (reason?: unknown) => void = () => undefined
|
||||||
|
const promise = new Promise<T>((res, rej) => {
|
||||||
|
resolve = res
|
||||||
|
reject = rej
|
||||||
|
})
|
||||||
|
return { promise, resolve, reject }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function flushMicrotasks(): Promise<void> {
|
||||||
|
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<AudioPipelineResult>()
|
||||||
|
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<typeof useHistorySync> | 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<HistoryListEntry>()
|
||||||
|
mockUpdateHistoryRevisionSafe.mockReturnValueOnce(favGate.promise)
|
||||||
|
const staleEntry = makeHistoryEntry('shared-like-entry', USER_A)
|
||||||
|
let pendingToggle: Promise<unknown> = 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())
|
||||||
|
})
|
||||||
|
})
|
||||||
238
apps/mobile-rn/__tests__/recorder-lifecycle-races.test.ts
Normal file
238
apps/mobile-rn/__tests__/recorder-lifecycle-races.test.ts
Normal file
|
|
@ -0,0 +1,238 @@
|
||||||
|
import { NativeModules } from 'react-native'
|
||||||
|
import { FileSystem } from 'react-native-file-access'
|
||||||
|
|
||||||
|
const mockStartRecorder = jest.fn<Promise<string>, [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<T>() {
|
||||||
|
let resolve: (value: T) => void = () => undefined
|
||||||
|
let reject: (reason?: unknown) => void = () => undefined
|
||||||
|
const promise = new Promise<T>((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<string, unknown>).D3RORecording
|
||||||
|
})
|
||||||
|
|
||||||
|
test('AudioRecorder_동시start클레임경합시_한소유자만인정하고실패시임대해제', async () => {
|
||||||
|
const busyChecks: Array<ReturnType<typeof deferred<boolean>>> = []
|
||||||
|
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<boolean>()
|
||||||
|
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<string[]>()
|
||||||
|
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<string, unknown>).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<ReturnType<typeof nativeSnapshot>>()
|
||||||
|
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<string, unknown>).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)
|
||||||
|
})
|
||||||
|
})
|
||||||
832
apps/mobile-rn/__tests__/screen-async-lifecycle.test.tsx
Normal file
832
apps/mobile-rn/__tests__/screen-async-lifecycle.test.tsx
Normal file
|
|
@ -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<Promise<MobileDashboardStats>, [string]>()
|
||||||
|
const mockListMeetingsPage = jest.fn()
|
||||||
|
const mockListKnowledgeDocuments = jest.fn()
|
||||||
|
const mockConsumeIncomingMediaAudio = jest.fn<Promise<LocalAudioInput | null>, []>()
|
||||||
|
const mockEnqueueAudioProcessing = jest.fn()
|
||||||
|
const mockProcessQueuedAudioNow = jest.fn()
|
||||||
|
const mockGetHistoryDetail = jest.fn<Promise<HistoryDetail>, [string, string]>()
|
||||||
|
const mockCreateAudioPlaybackUrl = jest.fn<Promise<string>, [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<T>() {
|
||||||
|
let resolve: (value: T) => void = () => undefined
|
||||||
|
let reject: (reason?: unknown) => void = () => undefined
|
||||||
|
const promise = new Promise<T>((res, rej) => {
|
||||||
|
resolve = res
|
||||||
|
reject = rej
|
||||||
|
})
|
||||||
|
return { promise, resolve, reject }
|
||||||
|
}
|
||||||
|
|
||||||
|
async function flush(): Promise<void> {
|
||||||
|
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<MobileDashboardStats>()
|
||||||
|
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(<HomeScreen />)
|
||||||
|
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(<HomeScreen />)
|
||||||
|
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(<MeetingsScreen navigation={mockNavigation as never} />)
|
||||||
|
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(<KnowledgeScreen />)
|
||||||
|
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(
|
||||||
|
<RecordScreen
|
||||||
|
route={{ params: { incomingMediaId: 'media-cancel-1' } }}
|
||||||
|
navigation={{ getParent: () => 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<string>()
|
||||||
|
mockCreateAudioPlaybackUrl
|
||||||
|
.mockReturnValueOnce(slowUrlGate.promise)
|
||||||
|
.mockResolvedValueOnce('https://storage.example/track-2.wav')
|
||||||
|
|
||||||
|
let renderer!: ReactTestRenderer
|
||||||
|
await act(async () => {
|
||||||
|
renderer = create(
|
||||||
|
<HistoryDetailScreen
|
||||||
|
route={{ key: 'HistoryDetail-1', name: 'HistoryDetail', params: { historyId: HISTORY_ID } }}
|
||||||
|
navigation={{ goBack: mockGoBack } as never}
|
||||||
|
/>,
|
||||||
|
)
|
||||||
|
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<SyncedCommand>()
|
||||||
|
mockCreateSyncedCommand.mockReturnValueOnce(saveGate.promise)
|
||||||
|
|
||||||
|
let renderer!: ReactTestRenderer
|
||||||
|
await act(async () => {
|
||||||
|
renderer = create(<CommandsScreen />)
|
||||||
|
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(<TeamsScreen navigation={mockNavigation as never} />)
|
||||||
|
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()
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
@ -406,6 +406,9 @@ async function requestAdmin(path: string, options: RequestOptions): Promise<unkn
|
||||||
options.signal?.addEventListener('abort', abortFromCaller, { once: true })
|
options.signal?.addEventListener('abort', abortFromCaller, { once: true })
|
||||||
const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS)
|
const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS)
|
||||||
try {
|
try {
|
||||||
|
if (options.signal?.aborted === true) {
|
||||||
|
throw new AdminServiceError('network', null, false)
|
||||||
|
}
|
||||||
const response = await fetch(`${SUPABASE_URL}/functions/v1/${path}`, {
|
const response = await fetch(`${SUPABASE_URL}/functions/v1/${path}`, {
|
||||||
method: options.method ?? 'GET',
|
method: options.method ?? 'GET',
|
||||||
headers: {
|
headers: {
|
||||||
|
|
|
||||||
|
|
@ -100,6 +100,9 @@ async function sendChatRequest(
|
||||||
const timer = setTimeout(() => controller.abort(), options.timeoutMs ?? 45_000)
|
const timer = setTimeout(() => controller.abort(), options.timeoutMs ?? 45_000)
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
if (options.signal?.aborted === true) {
|
||||||
|
throw new ChatServiceError('CANCELLED', false)
|
||||||
|
}
|
||||||
const headers: Record<string, string> = {
|
const headers: Record<string, string> = {
|
||||||
Authorization: `Bearer ${token}`,
|
Authorization: `Bearer ${token}`,
|
||||||
'Content-Type': 'application/json',
|
'Content-Type': 'application/json',
|
||||||
|
|
|
||||||
|
|
@ -87,6 +87,14 @@ const DEVICE_COLUMNS = [
|
||||||
export async function registerCurrentDevice(
|
export async function registerCurrentDevice(
|
||||||
userId: string,
|
userId: string,
|
||||||
config: MobileRuntimeConfig,
|
config: MobileRuntimeConfig,
|
||||||
|
): Promise<RegisteredDevice> {
|
||||||
|
return registerCurrentDeviceAttempt(userId, config, true)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function registerCurrentDeviceAttempt(
|
||||||
|
userId: string,
|
||||||
|
config: MobileRuntimeConfig,
|
||||||
|
allowConflictRetry: boolean,
|
||||||
): Promise<RegisteredDevice> {
|
): Promise<RegisteredDevice> {
|
||||||
requireUserId(userId)
|
requireUserId(userId)
|
||||||
const existing = await supabase
|
const existing = await supabase
|
||||||
|
|
@ -130,9 +138,11 @@ export async function registerCurrentDevice(
|
||||||
.select(DEVICE_COLUMNS)
|
.select(DEVICE_COLUMNS)
|
||||||
.single()
|
.single()
|
||||||
if (inserted.error) {
|
if (inserted.error) {
|
||||||
// A simultaneous bootstrap may have won the unique key. Fetching again is
|
// A simultaneous bootstrap may have won the unique key. Retry once safely
|
||||||
// safe and never clears a remote revocation.
|
// while preventing infinite recursion when conflict errors persist.
|
||||||
if (inserted.error.code === '23505') return registerCurrentDevice(userId, config)
|
if (inserted.error.code === '23505' && allowConflictRetry) {
|
||||||
|
return registerCurrentDeviceAttempt(userId, config, false)
|
||||||
|
}
|
||||||
throw new DeviceServiceError('server')
|
throw new DeviceServiceError('server')
|
||||||
}
|
}
|
||||||
return normalizeRegisteredDevice(inserted.data)
|
return normalizeRegisteredDevice(inserted.data)
|
||||||
|
|
|
||||||
|
|
@ -209,6 +209,7 @@ export function useHistorySync(): HistorySyncModel {
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const cached = await loadHistoryCache(userId)
|
const cached = await loadHistoryCache(userId)
|
||||||
|
if (currentRequest !== requestId.current) return
|
||||||
if (cached !== null) {
|
if (cached !== null) {
|
||||||
commitWindow({
|
commitWindow({
|
||||||
entries: filterCachedHistory(cached.entries, filter, debouncedSearch),
|
entries: filterCachedHistory(cached.entries, filter, debouncedSearch),
|
||||||
|
|
@ -222,6 +223,7 @@ export function useHistorySync(): HistorySyncModel {
|
||||||
setOffline(normalized.code === 'network')
|
setOffline(normalized.code === 'network')
|
||||||
}
|
}
|
||||||
} catch (cacheError) {
|
} catch (cacheError) {
|
||||||
|
if (currentRequest !== requestId.current) return
|
||||||
setCacheWarning(true)
|
setCacheWarning(true)
|
||||||
setError(normalized.code === 'network' ? normalized : syncError(cacheError))
|
setError(normalized.code === 'network' ? normalized : syncError(cacheError))
|
||||||
setOffline(normalized.code === 'network')
|
setOffline(normalized.code === 'network')
|
||||||
|
|
@ -378,6 +380,7 @@ export function useHistorySync(): HistorySyncModel {
|
||||||
entry.revision,
|
entry.revision,
|
||||||
{ is_favorite: optimisticFavorite },
|
{ is_favorite: optimisticFavorite },
|
||||||
)
|
)
|
||||||
|
if (!isCurrentScope()) return
|
||||||
const replacement: HistoryListEntry = { ...entry, ...updated }
|
const replacement: HistoryListEntry = { ...entry, ...updated }
|
||||||
updateEntries((current) => {
|
updateEntries((current) => {
|
||||||
if (filter === 'favorites' && !updated.is_favorite) {
|
if (filter === 'favorites' && !updated.is_favorite) {
|
||||||
|
|
@ -387,9 +390,11 @@ export function useHistorySync(): HistorySyncModel {
|
||||||
})
|
})
|
||||||
await patchCachedEntry(entry.id, replacement, isCurrentScope)
|
await patchCachedEntry(entry.id, replacement, isCurrentScope)
|
||||||
} catch (mutationError) {
|
} catch (mutationError) {
|
||||||
updateEntries((current) => current.map((item) => (
|
if (isCurrentScope()) {
|
||||||
item.id === entry.id ? entry : item
|
updateEntries((current) => current.map((item) => (
|
||||||
)))
|
item.id === entry.id ? entry : item
|
||||||
|
)))
|
||||||
|
}
|
||||||
throw mutationError
|
throw mutationError
|
||||||
} finally {
|
} finally {
|
||||||
endMutation(entry.id)
|
endMutation(entry.id)
|
||||||
|
|
@ -404,9 +409,12 @@ export function useHistorySync(): HistorySyncModel {
|
||||||
updateEntries((current) => current.filter((item) => item.id !== entry.id))
|
updateEntries((current) => current.filter((item) => item.id !== entry.id))
|
||||||
try {
|
try {
|
||||||
await deleteHistoryRevisionSafe(userId, entry.id, entry.revision)
|
await deleteHistoryRevisionSafe(userId, entry.id, entry.revision)
|
||||||
|
if (!isCurrentScope()) return
|
||||||
await patchCachedEntry(entry.id, null, isCurrentScope)
|
await patchCachedEntry(entry.id, null, isCurrentScope)
|
||||||
} catch (mutationError) {
|
} catch (mutationError) {
|
||||||
updateEntries((current) => mergeHistoryEntries(current, [entry]))
|
if (isCurrentScope()) {
|
||||||
|
updateEntries((current) => mergeHistoryEntries(current, [entry]))
|
||||||
|
}
|
||||||
throw mutationError
|
throw mutationError
|
||||||
} finally {
|
} finally {
|
||||||
endMutation(entry.id)
|
endMutation(entry.id)
|
||||||
|
|
|
||||||
|
|
@ -438,7 +438,14 @@ async function processItemCore(item: DurableQueueItem): Promise<AudioPipelineRes
|
||||||
};
|
};
|
||||||
await replaceItem(current);
|
await replaceItem(current);
|
||||||
await reportMeetingFailure(current, error, !canRetry);
|
await reportMeetingFailure(current, error, !canRetry);
|
||||||
if (canRetry) scheduler.arm(current.userId, current.nextAttemptAtMs);
|
if (discardedItems.has(current.id)) {
|
||||||
|
discardedItems.delete(current.id);
|
||||||
|
await removeItem(current).catch(() => 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;
|
throw canRetry ? new QueuedAudioPendingError(current) : error;
|
||||||
} finally {
|
} finally {
|
||||||
runningControllers.delete(item.id);
|
runningControllers.delete(item.id);
|
||||||
|
|
@ -523,6 +530,11 @@ export async function retryQueuedAudio(userId: string, itemId: string): Promise<
|
||||||
const items = await readQueue();
|
const items = await readQueue();
|
||||||
const item = items.find(candidate => candidate.id === itemId && candidate.userId === userId);
|
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 === 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({
|
await replaceItem({
|
||||||
...item,
|
...item,
|
||||||
status: 'retry',
|
status: 'retry',
|
||||||
|
|
|
||||||
|
|
@ -280,6 +280,7 @@ export async function streamTalkResponse(
|
||||||
|
|
||||||
const generationId = response.headers.get('X-D3RO-Generation-Id')?.trim() ?? ''
|
const generationId = response.headers.get('X-D3RO-Generation-Id')?.trim() ?? ''
|
||||||
if (!isUuid(generationId)) {
|
if (!isUuid(generationId)) {
|
||||||
|
await response.body?.cancel?.().catch(() => undefined)
|
||||||
throw new ChatServiceError('INVALID_RESPONSE', true)
|
throw new ChatServiceError('INVALID_RESPONSE', true)
|
||||||
}
|
}
|
||||||
const text = await consumeStreamingBody(response, options.onTextDelta)
|
const text = await consumeStreamingBody(response, options.onTextDelta)
|
||||||
|
|
|
||||||
|
|
@ -44,6 +44,7 @@ export function createPlatformRecorderBackend(): RecorderBackend {
|
||||||
export class AudioRecorder {
|
export class AudioRecorder {
|
||||||
private selectedBackend: RecorderBackend | null;
|
private selectedBackend: RecorderBackend | null;
|
||||||
private lease: RecorderOwner | null = null;
|
private lease: RecorderOwner | null = null;
|
||||||
|
private pendingClaim: { owner: RecorderOwner; depth: number } | null = null;
|
||||||
|
|
||||||
constructor(backend?: RecorderBackend) {
|
constructor(backend?: RecorderBackend) {
|
||||||
this.selectedBackend = backend ?? null;
|
this.selectedBackend = backend ?? null;
|
||||||
|
|
@ -102,6 +103,9 @@ export class AudioRecorder {
|
||||||
}
|
}
|
||||||
|
|
||||||
private async assertAvailable(owner: RecorderOwner): Promise<void> {
|
private async assertAvailable(owner: RecorderOwner): Promise<void> {
|
||||||
|
if (this.pendingClaim !== null && this.pendingClaim.owner !== owner) {
|
||||||
|
throw new RecorderBusyError(this.pendingClaim.owner);
|
||||||
|
}
|
||||||
const holder = await this.holder();
|
const holder = await this.holder();
|
||||||
if (holder !== null && holder !== owner) throw new RecorderBusyError(holder);
|
if (holder !== null && holder !== owner) throw new RecorderBusyError(holder);
|
||||||
// Another owner may have started a capture while the status was read.
|
// Another owner may have started a capture while the status was read.
|
||||||
|
|
@ -115,9 +119,28 @@ export class AudioRecorder {
|
||||||
claim: boolean,
|
claim: boolean,
|
||||||
operation: () => Promise<T>,
|
operation: () => Promise<T>,
|
||||||
): Promise<T> {
|
): Promise<T> {
|
||||||
await this.assertAvailable(owner);
|
if (this.pendingClaim !== null && this.pendingClaim.owner !== owner) {
|
||||||
if (claim) this.lease = owner;
|
throw new RecorderBusyError(this.pendingClaim.owner);
|
||||||
return operation();
|
}
|
||||||
|
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(
|
private async cleanupAsOwner(
|
||||||
|
|
|
||||||
|
|
@ -298,13 +298,24 @@ export function BillingProvider({ children }: { children: ReactNode }): React.Re
|
||||||
const [errorCode, setErrorCode] = useState<string | null>(null)
|
const [errorCode, setErrorCode] = useState<string | null>(null)
|
||||||
const inFlightPurchases = useRef(new Set<string>())
|
const inFlightPurchases = useRef(new Set<string>())
|
||||||
const userIdRef = useRef<string | null>(user?.id ?? null)
|
const userIdRef = useRef<string | null>(user?.id ?? null)
|
||||||
|
const mountedRef = useRef(true)
|
||||||
|
const productsGenerationRef = useRef(0)
|
||||||
const installedFromPlayStore = useMemo(
|
const installedFromPlayStore = useMemo(
|
||||||
() => Platform.OS === 'android' && getMobileRuntimeConfig().installedFromPlayStore,
|
() => Platform.OS === 'android' && getMobileRuntimeConfig().installedFromPlayStore,
|
||||||
[],
|
[],
|
||||||
)
|
)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
mountedRef.current = true
|
||||||
|
return () => {
|
||||||
|
mountedRef.current = false
|
||||||
|
productsGenerationRef.current += 1
|
||||||
|
}
|
||||||
|
}, [])
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
userIdRef.current = user?.id ?? null
|
userIdRef.current = user?.id ?? null
|
||||||
|
productsGenerationRef.current += 1
|
||||||
inFlightPurchases.current.clear()
|
inFlightPurchases.current.clear()
|
||||||
setOperation('idle')
|
setOperation('idle')
|
||||||
setErrorCode(null)
|
setErrorCode(null)
|
||||||
|
|
@ -329,11 +340,13 @@ export function BillingProvider({ children }: { children: ReactNode }): React.Re
|
||||||
productId: purchase.productId,
|
productId: purchase.productId,
|
||||||
purchaseToken: purchase.purchaseToken,
|
purchaseToken: purchase.purchaseToken,
|
||||||
})
|
})
|
||||||
|
if (!mountedRef.current || userIdRef.current !== currentUserId) return
|
||||||
if (!result.ok) throw new Error(billingFailureCode(result))
|
if (!result.ok) throw new Error(billingFailureCode(result))
|
||||||
const data = result.data
|
const data = result.data
|
||||||
const verifiedProduct = verifiedRestorableProduct(data, purchase.productId)
|
const verifiedProduct = verifiedRestorableProduct(data, purchase.productId)
|
||||||
const verification = data && isRecord(data.verification) ? data.verification : null
|
const verification = data && isRecord(data.verification) ? data.verification : null
|
||||||
const refreshed = await entitlement.refresh()
|
const refreshed = await entitlement.refresh()
|
||||||
|
if (!mountedRef.current || userIdRef.current !== currentUserId) return
|
||||||
if (verifiedProduct !== null) {
|
if (verifiedProduct !== null) {
|
||||||
if (
|
if (
|
||||||
refreshed === null
|
refreshed === null
|
||||||
|
|
@ -346,11 +359,15 @@ export function BillingProvider({ children }: { children: ReactNode }): React.Re
|
||||||
throw new Error('purchase_not_verified_active')
|
throw new Error('purchase_not_verified_active')
|
||||||
}
|
}
|
||||||
} catch (candidate) {
|
} 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')
|
setOperation('failed')
|
||||||
setErrorCode(await functionErrorCode(candidate))
|
setErrorCode(resolvedErrorCode)
|
||||||
} finally {
|
} finally {
|
||||||
inFlightPurchases.current.delete(identity)
|
if (userIdRef.current === currentUserId) {
|
||||||
|
inFlightPurchases.current.delete(identity)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}, [entitlement])
|
}, [entitlement])
|
||||||
|
|
||||||
|
|
@ -406,16 +423,20 @@ export function BillingProvider({ children }: { children: ReactNode }): React.Re
|
||||||
setErrorCode('play_store_install_required')
|
setErrorCode('play_store_install_required')
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
const productsGeneration = ++productsGenerationRef.current
|
||||||
setOperation('loading-products')
|
setOperation('loading-products')
|
||||||
setErrorCode(null)
|
setErrorCode(null)
|
||||||
try {
|
try {
|
||||||
if (!connected) {
|
if (!connected) {
|
||||||
const didReconnect = await reconnect()
|
const didReconnect = await reconnect()
|
||||||
|
if (!mountedRef.current || productsGeneration !== productsGenerationRef.current) return
|
||||||
if (!didReconnect) throw new Error('store_connection_failed')
|
if (!didReconnect) throw new Error('store_connection_failed')
|
||||||
}
|
}
|
||||||
await fetchProducts({ skus: [...GOOGLE_PLAY_SUBSCRIPTION_IDS], type: 'subs' })
|
await fetchProducts({ skus: [...GOOGLE_PLAY_SUBSCRIPTION_IDS], type: 'subs' })
|
||||||
|
if (!mountedRef.current || productsGeneration !== productsGenerationRef.current) return
|
||||||
setOperation('idle')
|
setOperation('idle')
|
||||||
} catch (candidate) {
|
} catch (candidate) {
|
||||||
|
if (!mountedRef.current || productsGeneration !== productsGenerationRef.current) return
|
||||||
setOperation('failed')
|
setOperation('failed')
|
||||||
setErrorCode(candidate instanceof Error ? candidate.message : 'product_fetch_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'
|
const replacementPurchases = currentProvider === 'google_play'
|
||||||
? await getAvailablePurchases({ includeSuspendedAndroid: true })
|
? await getAvailablePurchases({ includeSuspendedAndroid: true })
|
||||||
: []
|
: []
|
||||||
|
if (!mountedRef.current || userIdRef.current !== currentUserId) return
|
||||||
const replacementPurchase = currentProvider === 'google_play'
|
const replacementPurchase = currentProvider === 'google_play'
|
||||||
? replacementPurchases.find((candidate) => (
|
? replacementPurchases.find((candidate) => (
|
||||||
candidate.productId === currentProductId
|
candidate.productId === currentProductId
|
||||||
|
|
@ -491,6 +513,7 @@ export function BillingProvider({ children }: { children: ReactNode }): React.Re
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
} catch (candidate) {
|
} catch (candidate) {
|
||||||
|
if (!mountedRef.current || userIdRef.current !== currentUserId) return
|
||||||
setOperation('failed')
|
setOperation('failed')
|
||||||
setErrorCode(candidate instanceof Error ? candidate.message : 'purchase_failed')
|
setErrorCode(candidate instanceof Error ? candidate.message : 'purchase_failed')
|
||||||
}
|
}
|
||||||
|
|
@ -525,7 +548,9 @@ export function BillingProvider({ children }: { children: ReactNode }): React.Re
|
||||||
await restoreGooglePlayPurchaseSet(
|
await restoreGooglePlayPurchaseSet(
|
||||||
restoredPurchases,
|
restoredPurchases,
|
||||||
async (restoredPurchase) => {
|
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<IapVerifyResult>('iap-verify', {
|
const result = await invokeEdgeFunction<IapVerifyResult>('iap-verify', {
|
||||||
platform: 'google_play',
|
platform: 'google_play',
|
||||||
productId: restoredPurchase.productId,
|
productId: restoredPurchase.productId,
|
||||||
|
|
@ -536,14 +561,18 @@ export function BillingProvider({ children }: { children: ReactNode }): React.Re
|
||||||
return data
|
return data
|
||||||
},
|
},
|
||||||
async () => {
|
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()
|
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')
|
setOperation('succeeded')
|
||||||
} catch (candidate) {
|
} catch (candidate) {
|
||||||
if (userIdRef.current !== currentUserId) return
|
if (!mountedRef.current || userIdRef.current !== currentUserId) return
|
||||||
setOperation('failed')
|
setOperation('failed')
|
||||||
setErrorCode(candidate instanceof Error ? candidate.message : 'restore_failed')
|
setErrorCode(candidate instanceof Error ? candidate.message : 'restore_failed')
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -39,7 +39,12 @@ export function DeviceProvider({ children }: { children: ReactNode }): React.Rea
|
||||||
const handleRevocation = useCallback(async (): Promise<void> => {
|
const handleRevocation = useCallback(async (): Promise<void> => {
|
||||||
if (revocationHandledRef.current) return
|
if (revocationHandledRef.current) return
|
||||||
revocationHandledRef.current = true
|
revocationHandledRef.current = true
|
||||||
await purgeLocalSession()
|
try {
|
||||||
|
await purgeLocalSession()
|
||||||
|
} catch (revocationError) {
|
||||||
|
revocationHandledRef.current = false
|
||||||
|
throw revocationError
|
||||||
|
}
|
||||||
}, [purgeLocalSession])
|
}, [purgeLocalSession])
|
||||||
|
|
||||||
const refreshCurrentDevice = useCallback(async (): Promise<void> => {
|
const refreshCurrentDevice = useCallback(async (): Promise<void> => {
|
||||||
|
|
|
||||||
|
|
@ -280,7 +280,7 @@ function isCachedSnapshot(value: unknown, userId: string): value is CacheEnvelop
|
||||||
}
|
}
|
||||||
|
|
||||||
async function readCache(userId: string): Promise<EntitlementSnapshot | null> {
|
async function readCache(userId: string): Promise<EntitlementSnapshot | null> {
|
||||||
const serialized = await AsyncStorage.getItem(cacheKey(userId))
|
const serialized = await AsyncStorage.getItem(cacheKey(userId)).catch(() => null)
|
||||||
if (!serialized) return null
|
if (!serialized) return null
|
||||||
try {
|
try {
|
||||||
const value: unknown = JSON.parse(serialized)
|
const value: unknown = JSON.parse(serialized)
|
||||||
|
|
@ -393,7 +393,7 @@ export function EntitlementProvider({ children }: { children: ReactNode }): Reac
|
||||||
setSnapshot(cached)
|
setSnapshot(cached)
|
||||||
setStale(true)
|
setStale(true)
|
||||||
setLoading(false)
|
setLoading(false)
|
||||||
}).finally(() => {
|
}).catch(() => null).finally(() => {
|
||||||
if (!cancelled) void refresh()
|
if (!cancelled) void refresh()
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -86,7 +86,8 @@ export function MobileAdsProvider({ children }: { children: ReactNode }): React.
|
||||||
}
|
}
|
||||||
}, [])
|
}, [])
|
||||||
|
|
||||||
const initializeAds = useCallback(async (): Promise<void> => {
|
const initializeAds = useCallback(async (expectedGeneration: number): Promise<void> => {
|
||||||
|
if (expectedGeneration !== generation.current) return
|
||||||
if (initialized.current) {
|
if (initialized.current) {
|
||||||
setStatus('ready')
|
setStatus('ready')
|
||||||
return
|
return
|
||||||
|
|
@ -96,11 +97,17 @@ export function MobileAdsProvider({ children }: { children: ReactNode }): React.
|
||||||
maxAdContentRating: MaxAdContentRating.T,
|
maxAdContentRating: MaxAdContentRating.T,
|
||||||
testDeviceIdentifiers: runtimeConfig?.debug ? ['EMULATOR'] : undefined,
|
testDeviceIdentifiers: runtimeConfig?.debug ? ['EMULATOR'] : undefined,
|
||||||
})
|
})
|
||||||
|
if (expectedGeneration !== generation.current) return
|
||||||
await MobileAds().initialize()
|
await MobileAds().initialize()
|
||||||
|
if (expectedGeneration !== generation.current) return
|
||||||
initialized.current = true
|
initialized.current = true
|
||||||
setStatus('ready')
|
setStatus('ready')
|
||||||
}, [runtimeConfig?.debug])
|
}, [runtimeConfig?.debug])
|
||||||
|
|
||||||
|
useEffect(() => () => {
|
||||||
|
generation.current += 1
|
||||||
|
}, [])
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const currentGeneration = ++generation.current
|
const currentGeneration = ++generation.current
|
||||||
if (!eligible) {
|
if (!eligible) {
|
||||||
|
|
@ -127,7 +134,7 @@ export function MobileAdsProvider({ children }: { children: ReactNode }): React.
|
||||||
setStatus('consent-blocked')
|
setStatus('consent-blocked')
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
await initializeAds()
|
await initializeAds(currentGeneration)
|
||||||
})
|
})
|
||||||
.catch((candidate) => {
|
.catch((candidate) => {
|
||||||
if (currentGeneration !== generation.current) return
|
if (currentGeneration !== generation.current) return
|
||||||
|
|
@ -137,25 +144,36 @@ export function MobileAdsProvider({ children }: { children: ReactNode }): React.
|
||||||
}, [eligible, initializeAds, runtimeConfig])
|
}, [eligible, initializeAds, runtimeConfig])
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
|
let cancelled = false
|
||||||
void AdsConsent.getConsentInfo().then((info) => {
|
void AdsConsent.getConsentInfo().then((info) => {
|
||||||
|
if (cancelled) return
|
||||||
setPrivacyOptionsRequired(
|
setPrivacyOptionsRequired(
|
||||||
info.privacyOptionsRequirementStatus
|
info.privacyOptionsRequirementStatus
|
||||||
=== AdsConsentPrivacyOptionsRequirementStatus.REQUIRED,
|
=== AdsConsentPrivacyOptionsRequirementStatus.REQUIRED,
|
||||||
)
|
)
|
||||||
}).catch(() => undefined)
|
}).catch(() => undefined)
|
||||||
|
return () => {
|
||||||
|
cancelled = true
|
||||||
|
}
|
||||||
}, [])
|
}, [])
|
||||||
|
|
||||||
const showPrivacyOptions = useCallback(async (): Promise<boolean> => {
|
const showPrivacyOptions = useCallback(async (): Promise<boolean> => {
|
||||||
|
const opGeneration = generation.current
|
||||||
|
const opEligible = eligible
|
||||||
try {
|
try {
|
||||||
const consentInfo = await AdsConsent.showPrivacyOptionsForm()
|
const consentInfo = await AdsConsent.showPrivacyOptionsForm()
|
||||||
|
if (opGeneration !== generation.current) return false
|
||||||
setPrivacyOptionsRequired(
|
setPrivacyOptionsRequired(
|
||||||
consentInfo.privacyOptionsRequirementStatus
|
consentInfo.privacyOptionsRequirementStatus
|
||||||
=== AdsConsentPrivacyOptionsRequirementStatus.REQUIRED,
|
=== AdsConsentPrivacyOptionsRequirementStatus.REQUIRED,
|
||||||
)
|
)
|
||||||
if (eligible && consentInfo.canRequestAds) await initializeAds()
|
if (opEligible && consentInfo.canRequestAds) await initializeAds(opGeneration)
|
||||||
if (eligible && !consentInfo.canRequestAds) setStatus('consent-blocked')
|
if (opEligible && !consentInfo.canRequestAds && opGeneration === generation.current) {
|
||||||
|
setStatus('consent-blocked')
|
||||||
|
}
|
||||||
return true
|
return true
|
||||||
} catch (candidate) {
|
} catch (candidate) {
|
||||||
|
if (opGeneration !== generation.current) return false
|
||||||
setErrorCode(candidateMessage(candidate, 'privacy_options_unavailable'))
|
setErrorCode(candidateMessage(candidate, 'privacy_options_unavailable'))
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
@ -318,6 +336,7 @@ export function useRewardedCredits(): RewardedCreditsValue {
|
||||||
).then(async (credited) => {
|
).then(async (credited) => {
|
||||||
if (currentGeneration !== verificationGeneration.current) return
|
if (currentGeneration !== verificationGeneration.current) return
|
||||||
await entitlement.refresh()
|
await entitlement.refresh()
|
||||||
|
if (currentGeneration !== verificationGeneration.current) return
|
||||||
setStatus(credited ? 'credited' : 'verification-pending')
|
setStatus(credited ? 'credited' : 'verification-pending')
|
||||||
}).catch((candidate) => {
|
}).catch((candidate) => {
|
||||||
if (currentGeneration !== verificationGeneration.current) return
|
if (currentGeneration !== verificationGeneration.current) return
|
||||||
|
|
|
||||||
|
|
@ -139,6 +139,8 @@ export class AndroidForegroundRecorderBackend implements RecorderBackend {
|
||||||
private progressHandler: RecordingProgressHandler | null = null;
|
private progressHandler: RecordingProgressHandler | null = null;
|
||||||
private stateHandler: RecordingStateHandler | null = null;
|
private stateHandler: RecordingStateHandler | null = null;
|
||||||
private pollGeneration = 0;
|
private pollGeneration = 0;
|
||||||
|
private pollTimer: ReturnType<typeof setTimeout> | null = null;
|
||||||
|
private sessionGeneration = 0;
|
||||||
|
|
||||||
async requestPermission(): Promise<boolean> {
|
async requestPermission(): Promise<boolean> {
|
||||||
const permission = PermissionsAndroid.PERMISSIONS.RECORD_AUDIO;
|
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}`);
|
throw new Error(`Cannot start recorder while it is ${this.state}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const sessionGen = ++this.sessionGeneration;
|
||||||
this.state = 'starting';
|
this.state = 'starting';
|
||||||
this.progressHandler = onProgress;
|
this.progressHandler = onProgress;
|
||||||
this.stateHandler = options.onStateChange ?? null;
|
this.stateHandler = options.onStateChange ?? null;
|
||||||
|
|
@ -174,6 +177,10 @@ export class AndroidForegroundRecorderBackend implements RecorderBackend {
|
||||||
: { meetingId: options.meetingId },
|
: { 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) {
|
if (snapshot.state !== 'recording' || snapshot.recording === null) {
|
||||||
throw new Error('Android foreground recorder did not start');
|
throw new Error('Android foreground recorder did not start');
|
||||||
}
|
}
|
||||||
|
|
@ -186,10 +193,9 @@ export class AndroidForegroundRecorderBackend implements RecorderBackend {
|
||||||
this.stateHandler?.(snapshot);
|
this.stateHandler?.(snapshot);
|
||||||
this.startPolling();
|
this.startPolling();
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
this.progressHandler = null;
|
if (sessionGen === this.sessionGeneration) {
|
||||||
this.stateHandler = null;
|
this.resetToIdle();
|
||||||
this.currentPath = null;
|
}
|
||||||
this.state = 'idle';
|
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -199,14 +205,20 @@ export class AndroidForegroundRecorderBackend implements RecorderBackend {
|
||||||
throw new Error(`Cannot pause recorder while it is ${this.state}`);
|
throw new Error(`Cannot pause recorder while it is ${this.state}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const sessionGen = this.sessionGeneration;
|
||||||
this.state = 'pausing';
|
this.state = 'pausing';
|
||||||
try {
|
try {
|
||||||
const snapshot = parseNativeSnapshot(await androidRecordingModule().pause());
|
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');
|
if (snapshot.state !== 'paused') throw new Error('Android recorder did not pause');
|
||||||
this.state = 'paused';
|
this.state = 'paused';
|
||||||
this.stateHandler?.(snapshot);
|
this.stateHandler?.(snapshot);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
this.state = 'recording';
|
if (sessionGen === this.sessionGeneration) {
|
||||||
|
this.state = 'recording';
|
||||||
|
}
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -216,14 +228,20 @@ export class AndroidForegroundRecorderBackend implements RecorderBackend {
|
||||||
throw new Error(`Cannot resume recorder while it is ${this.state}`);
|
throw new Error(`Cannot resume recorder while it is ${this.state}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const sessionGen = this.sessionGeneration;
|
||||||
this.state = 'resuming';
|
this.state = 'resuming';
|
||||||
try {
|
try {
|
||||||
const snapshot = parseNativeSnapshot(await androidRecordingModule().resume());
|
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');
|
if (snapshot.state !== 'recording') throw new Error('Android recorder did not resume');
|
||||||
this.state = 'recording';
|
this.state = 'recording';
|
||||||
this.stateHandler?.(snapshot);
|
this.stateHandler?.(snapshot);
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
this.state = 'paused';
|
if (sessionGen === this.sessionGeneration) {
|
||||||
|
this.state = 'paused';
|
||||||
|
}
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
@ -234,13 +252,19 @@ export class AndroidForegroundRecorderBackend implements RecorderBackend {
|
||||||
}
|
}
|
||||||
if (this.currentPath === null) throw new Error('Recorder has no output path');
|
if (this.currentPath === null) throw new Error('Recorder has no output path');
|
||||||
|
|
||||||
|
const sessionGen = this.sessionGeneration;
|
||||||
const previousState = this.state;
|
const previousState = this.state;
|
||||||
this.state = 'stopping';
|
this.state = 'stopping';
|
||||||
let snapshot: RecordingRuntimeSnapshot;
|
let snapshot: RecordingRuntimeSnapshot;
|
||||||
try {
|
try {
|
||||||
snapshot = parseNativeSnapshot(await androidRecordingModule().stop());
|
snapshot = parseNativeSnapshot(await androidRecordingModule().stop());
|
||||||
|
if (sessionGen !== this.sessionGeneration) {
|
||||||
|
throw new Error('Recording was cancelled');
|
||||||
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
await this.resyncAfterFailedStop(previousState, null);
|
if (sessionGen === this.sessionGeneration) {
|
||||||
|
await this.resyncAfterFailedStop(previousState, null);
|
||||||
|
}
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -273,14 +297,19 @@ export class AndroidForegroundRecorderBackend implements RecorderBackend {
|
||||||
if (recording !== undefined && this.currentPath !== null && path !== this.currentPath) {
|
if (recording !== undefined && this.currentPath !== null && path !== this.currentPath) {
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
this.sessionGeneration += 1;
|
||||||
this.stopPolling();
|
this.stopPolling();
|
||||||
this.resetToIdle();
|
this.resetToIdle();
|
||||||
}
|
}
|
||||||
|
|
||||||
async cancel(): Promise<void> {
|
async cancel(): Promise<void> {
|
||||||
|
const cancelGen = ++this.sessionGeneration;
|
||||||
this.stopPolling();
|
this.stopPolling();
|
||||||
await androidRecordingModule().cancel();
|
|
||||||
this.resetToIdle();
|
this.resetToIdle();
|
||||||
|
await androidRecordingModule().cancel();
|
||||||
|
if (cancelGen === this.sessionGeneration) {
|
||||||
|
this.resetToIdle();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async restore(
|
async restore(
|
||||||
|
|
@ -288,6 +317,7 @@ export class AndroidForegroundRecorderBackend implements RecorderBackend {
|
||||||
onStateChange?: RecordingStateHandler,
|
onStateChange?: RecordingStateHandler,
|
||||||
): Promise<RecordingRuntimeSnapshot> {
|
): Promise<RecordingRuntimeSnapshot> {
|
||||||
const snapshot = parseNativeSnapshot(await androidRecordingModule().getStatus());
|
const snapshot = parseNativeSnapshot(await androidRecordingModule().getStatus());
|
||||||
|
this.sessionGeneration += 1;
|
||||||
this.stopPolling();
|
this.stopPolling();
|
||||||
this.progressHandler = onProgress ?? null;
|
this.progressHandler = onProgress ?? null;
|
||||||
this.stateHandler = onStateChange ?? null;
|
this.stateHandler = onStateChange ?? null;
|
||||||
|
|
@ -386,7 +416,13 @@ export class AndroidForegroundRecorderBackend implements RecorderBackend {
|
||||||
this.stateHandler?.(snapshot);
|
this.stateHandler?.(snapshot);
|
||||||
if (snapshot.state === 'recording' || snapshot.state === 'paused') {
|
if (snapshot.state === 'recording' || snapshot.state === 'paused') {
|
||||||
this.state = snapshot.state;
|
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 {
|
} else {
|
||||||
this.currentPath = snapshot.recording?.path ?? null;
|
this.currentPath = snapshot.recording?.path ?? null;
|
||||||
this.state = snapshot.state === 'idle' ? 'idle' : 'stopped';
|
this.state = snapshot.state === 'idle' ? 'idle' : 'stopped';
|
||||||
|
|
@ -394,7 +430,11 @@ export class AndroidForegroundRecorderBackend implements RecorderBackend {
|
||||||
} catch {
|
} catch {
|
||||||
// A transient React bridge failure must not stop the native foreground capture.
|
// A transient React bridge failure must not stop the native foreground capture.
|
||||||
if (generation === this.pollGeneration) {
|
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 {
|
private stopPolling(): void {
|
||||||
this.pollGeneration += 1;
|
this.pollGeneration += 1;
|
||||||
|
if (this.pollTimer !== null) {
|
||||||
|
clearTimeout(this.pollTimer);
|
||||||
|
this.pollTimer = null;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -104,6 +104,7 @@ export class NitroRecorderBackend implements RecorderBackend {
|
||||||
private state: NitroRecorderState = 'idle';
|
private state: NitroRecorderState = 'idle';
|
||||||
private currentPath: string | null = null;
|
private currentPath: string | null = null;
|
||||||
private progress: RecordingProgress = { durationMs: 0, meteringDb: null };
|
private progress: RecordingProgress = { durationMs: 0, meteringDb: null };
|
||||||
|
private startGeneration = 0;
|
||||||
private pendingStart: Promise<void> | null = null;
|
private pendingStart: Promise<void> | null = null;
|
||||||
private pendingTransition: Promise<void> | null = null;
|
private pendingTransition: Promise<void> | null = null;
|
||||||
private pendingStop: Promise<RecordedAudio> | null = null;
|
private pendingStop: Promise<RecordedAudio> | null = null;
|
||||||
|
|
@ -144,14 +145,21 @@ export class NitroRecorderBackend implements RecorderBackend {
|
||||||
throw new Error(`Cannot start recorder while it is ${this.state}`);
|
throw new Error(`Cannot start recorder while it is ${this.state}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const generation = ++this.startGeneration;
|
||||||
this.state = 'starting';
|
this.state = 'starting';
|
||||||
try {
|
try {
|
||||||
await deleteStaleTemporaryFiles();
|
await deleteStaleTemporaryFiles();
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
this.state = 'idle';
|
if (generation === this.startGeneration) {
|
||||||
|
this.state = 'idle';
|
||||||
|
}
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
if (generation !== this.startGeneration) {
|
||||||
|
throw new Error('Recording start was cancelled');
|
||||||
|
}
|
||||||
|
|
||||||
const outputPath = createTemporaryPath();
|
const outputPath = createTemporaryPath();
|
||||||
this.currentPath = outputPath;
|
this.currentPath = outputPath;
|
||||||
this.progress = { durationMs: 0, meteringDb: null };
|
this.progress = { durationMs: 0, meteringDb: null };
|
||||||
|
|
@ -296,10 +304,15 @@ export class NitroRecorderBackend implements RecorderBackend {
|
||||||
}
|
}
|
||||||
|
|
||||||
async cancel(): Promise<void> {
|
async cancel(): Promise<void> {
|
||||||
|
this.startGeneration += 1;
|
||||||
if (this.state === 'starting' && this.pendingStart !== null) {
|
if (this.state === 'starting' && this.pendingStart !== null) {
|
||||||
try {
|
try {
|
||||||
await this.pendingStart;
|
await this.pendingStart;
|
||||||
} catch {
|
} catch {
|
||||||
|
this.progressHandler = null;
|
||||||
|
this.currentPath = null;
|
||||||
|
this.state = 'idle';
|
||||||
|
this.progress = { durationMs: 0, meteringDb: null };
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -176,16 +176,25 @@ export default function CommandsScreen(): React.ReactElement {
|
||||||
return () => { void supabase.removeChannel(channel) }
|
return () => { void supabase.removeChannel(channel) }
|
||||||
}, [load, user?.id])
|
}, [load, user?.id])
|
||||||
|
|
||||||
|
const actorUserIdRef = useRef<string | null>(user?.id ?? null)
|
||||||
|
useEffect(() => {
|
||||||
|
actorUserIdRef.current = user?.id ?? null
|
||||||
|
}, [user?.id])
|
||||||
|
|
||||||
async function toggleActive(command: SyncedCommand): Promise<void> {
|
async function toggleActive(command: SyncedCommand): Promise<void> {
|
||||||
if (!user?.id || mutationId) return
|
if (!user?.id || mutationId) return
|
||||||
|
const actorUserId = user.id
|
||||||
setMutationId(command.id)
|
setMutationId(command.id)
|
||||||
try {
|
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)
|
setSyncError(null)
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
if (!alive.current || actorUserIdRef.current !== actorUserId) return
|
||||||
setSyncError(error instanceof CommandSyncError ? error.code : 'server')
|
setSyncError(error instanceof CommandSyncError ? error.code : 'server')
|
||||||
} finally {
|
} finally {
|
||||||
setMutationId(null)
|
if (alive.current) setMutationId(null)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -207,42 +216,48 @@ export default function CommandsScreen(): React.ReactElement {
|
||||||
|
|
||||||
async function save(): Promise<void> {
|
async function save(): Promise<void> {
|
||||||
if (!editor || !user?.id || mutationId) return
|
if (!editor || !user?.id || mutationId) return
|
||||||
|
const actorUserId = user.id
|
||||||
setMutationId(editor.command?.id ?? 'create')
|
setMutationId(editor.command?.id ?? 'create')
|
||||||
setEditorError(null)
|
setEditorError(null)
|
||||||
try {
|
try {
|
||||||
const saved = editor.command
|
const saved = editor.command
|
||||||
? await updateSyncedCommand(user.id, editor.command, editor)
|
? await updateSyncedCommand(actorUserId, editor.command, editor)
|
||||||
: await createSyncedCommand(user.id, {
|
: await createSyncedCommand(actorUserId, {
|
||||||
...editor,
|
...editor,
|
||||||
sortOrder: Math.max(1000, ...commands.map((item) => item.sortOrder + 10)),
|
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]
|
const next = [...commands.filter((item) => item.id !== saved.id), saved]
|
||||||
.sort((a, b) => a.sortOrder - b.sortOrder || a.createdAt.localeCompare(b.createdAt))
|
.sort((a, b) => a.sortOrder - b.sortOrder || a.createdAt.localeCompare(b.createdAt))
|
||||||
setCommands(next)
|
setCommands(next)
|
||||||
setSelectedId(saved.id)
|
setSelectedId(saved.id)
|
||||||
setEditor(null)
|
setEditor(null)
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
if (!alive.current || actorUserIdRef.current !== actorUserId) return
|
||||||
const code = error instanceof CommandSyncError ? error.code : 'server'
|
const code = error instanceof CommandSyncError ? error.code : 'server'
|
||||||
setEditorError(code)
|
setEditorError(code)
|
||||||
if (code === 'conflict') void load(false, true)
|
if (code === 'conflict') void load(false, true)
|
||||||
} finally {
|
} finally {
|
||||||
setMutationId(null)
|
if (alive.current) setMutationId(null)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function remove(command: SyncedCommand): Promise<void> {
|
async function remove(command: SyncedCommand): Promise<void> {
|
||||||
if (!user?.id || mutationId) return
|
if (!user?.id || mutationId) return
|
||||||
|
const actorUserId = user.id
|
||||||
setMutationId(command.id)
|
setMutationId(command.id)
|
||||||
try {
|
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)
|
const next = commands.filter((item) => item.id !== command.id)
|
||||||
setCommands(next)
|
setCommands(next)
|
||||||
if (selectedId === command.id) setSelectedId(next[0]?.id ?? null)
|
if (selectedId === command.id) setSelectedId(next[0]?.id ?? null)
|
||||||
if (activeId === command.id) setActiveId(null)
|
if (activeId === command.id) setActiveId(null)
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
if (!alive.current || actorUserIdRef.current !== actorUserId) return
|
||||||
setSyncError(error instanceof CommandSyncError ? error.code : 'server')
|
setSyncError(error instanceof CommandSyncError ? error.code : 'server')
|
||||||
} finally {
|
} 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<void> {
|
async function move(command: SyncedCommand, direction: 'up' | 'down'): Promise<void> {
|
||||||
if (!user?.id || mutationId) return
|
if (!user?.id || mutationId) return
|
||||||
|
const actorUserId = user.id
|
||||||
setMutationId(command.id)
|
setMutationId(command.id)
|
||||||
try {
|
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) {
|
} catch (error) {
|
||||||
|
if (!alive.current || actorUserIdRef.current !== actorUserId) return
|
||||||
setSyncError(error instanceof CommandSyncError ? error.code : 'server')
|
setSyncError(error instanceof CommandSyncError ? error.code : 'server')
|
||||||
} finally {
|
} finally {
|
||||||
setMutationId(null)
|
if (alive.current) setMutationId(null)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const run = useCallback(async (): Promise<void> => {
|
const run = useCallback(async (): Promise<void> => {
|
||||||
if (!selected || running) return
|
if (!selected || running) return
|
||||||
|
const actorUserId = actorUserIdRef.current
|
||||||
const token = session?.access_token ?? ''
|
const token = session?.access_token ?? ''
|
||||||
if (!token) {
|
if (!token) {
|
||||||
setRunError('AUTH_REQUIRED')
|
setRunError('AUTH_REQUIRED')
|
||||||
|
|
@ -283,12 +303,15 @@ export default function CommandsScreen(): React.ReactElement {
|
||||||
setRunError(null)
|
setRunError(null)
|
||||||
setRetryable(false)
|
setRetryable(false)
|
||||||
try {
|
try {
|
||||||
setOutput(await executeSyncedCommand(selected, input, {
|
const result = await executeSyncedCommand(selected, input, {
|
||||||
accessToken: token,
|
accessToken: token,
|
||||||
model: preferences.preferredLlmModel,
|
model: preferences.preferredLlmModel,
|
||||||
signal: controller.signal,
|
signal: controller.signal,
|
||||||
}))
|
})
|
||||||
|
if (!alive.current || actorUserIdRef.current !== actorUserId) return
|
||||||
|
setOutput(result)
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
if (!alive.current || actorUserIdRef.current !== actorUserId) return
|
||||||
const failure = error instanceof CommandExecutionError
|
const failure = error instanceof CommandExecutionError
|
||||||
? error
|
? error
|
||||||
: new CommandExecutionError('SERVER_ERROR', true)
|
: new CommandExecutionError('SERVER_ERROR', true)
|
||||||
|
|
|
||||||
|
|
@ -89,6 +89,7 @@ export default function HistoryDetailScreen({
|
||||||
playerRef.current = player
|
playerRef.current = player
|
||||||
const mountedRef = useRef(true)
|
const mountedRef = useRef(true)
|
||||||
const loadGenerationRef = useRef(0)
|
const loadGenerationRef = useRef(0)
|
||||||
|
const playbackGenerationRef = useRef(0)
|
||||||
const [detail, setDetail] = useState<HistoryDetail | null>(null)
|
const [detail, setDetail] = useState<HistoryDetail | null>(null)
|
||||||
const [loading, setLoading] = useState(true)
|
const [loading, setLoading] = useState(true)
|
||||||
const [error, setError] = useState<string | null>(null)
|
const [error, setError] = useState<string | null>(null)
|
||||||
|
|
@ -109,6 +110,7 @@ export default function HistoryDetailScreen({
|
||||||
return () => {
|
return () => {
|
||||||
mountedRef.current = false
|
mountedRef.current = false
|
||||||
loadGenerationRef.current += 1
|
loadGenerationRef.current += 1
|
||||||
|
playbackGenerationRef.current += 1
|
||||||
void Promise.resolve(playerRef.current.stopPlayer()).catch(() => undefined)
|
void Promise.resolve(playerRef.current.stopPlayer()).catch(() => undefined)
|
||||||
}
|
}
|
||||||
}, [])
|
}, [])
|
||||||
|
|
@ -306,53 +308,62 @@ export default function HistoryDetailScreen({
|
||||||
|
|
||||||
const controlAudio = async (audioFile: AudioFile): Promise<void> => {
|
const controlAudio = async (audioFile: AudioFile): Promise<void> => {
|
||||||
if (user === null || audioBusy) return
|
if (user === null || audioBusy) return
|
||||||
|
const playbackGeneration = ++playbackGenerationRef.current
|
||||||
setAudioBusy(true)
|
setAudioBusy(true)
|
||||||
setError(null)
|
setError(null)
|
||||||
try {
|
try {
|
||||||
if (activeAudioId === audioFile.id && player.state.isPlaying) {
|
if (activeAudioId === audioFile.id && player.state.isPlaying) {
|
||||||
await player.pausePlayer()
|
await player.pausePlayer()
|
||||||
if (mountedRef.current) setPaused(true)
|
if (mountedRef.current && playbackGeneration === playbackGenerationRef.current) setPaused(true)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if (activeAudioId === audioFile.id && paused) {
|
if (activeAudioId === audioFile.id && paused) {
|
||||||
await player.resumePlayer()
|
await player.resumePlayer()
|
||||||
if (mountedRef.current) setPaused(false)
|
if (mountedRef.current && playbackGeneration === playbackGenerationRef.current) setPaused(false)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if (activeAudioId !== null) {
|
if (activeAudioId !== null) {
|
||||||
await player.stopPlayer()
|
await player.stopPlayer()
|
||||||
if (!mountedRef.current) return
|
if (!mountedRef.current || playbackGeneration !== playbackGenerationRef.current) return
|
||||||
}
|
}
|
||||||
const signedUrl = await createAudioPlaybackUrl(user.id, audioFile)
|
const signedUrl = await createAudioPlaybackUrl(user.id, audioFile)
|
||||||
if (!mountedRef.current) return
|
if (!mountedRef.current || playbackGeneration !== playbackGenerationRef.current) return
|
||||||
await player.startPlayer(signedUrl)
|
await player.startPlayer(signedUrl)
|
||||||
if (!mountedRef.current) {
|
if (!mountedRef.current) {
|
||||||
void Promise.resolve(player.stopPlayer()).catch(() => undefined)
|
void Promise.resolve(player.stopPlayer()).catch(() => undefined)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
if (playbackGeneration !== playbackGenerationRef.current) return
|
||||||
setActiveAudioId(audioFile.id)
|
setActiveAudioId(audioFile.id)
|
||||||
setPaused(false)
|
setPaused(false)
|
||||||
} catch {
|
} catch {
|
||||||
if (!mountedRef.current) return
|
if (!mountedRef.current || playbackGeneration !== playbackGenerationRef.current) return
|
||||||
setActiveAudioId(null)
|
setActiveAudioId(null)
|
||||||
setPaused(false)
|
setPaused(false)
|
||||||
setError(t('mobile.hist.audioError'))
|
setError(t('mobile.hist.audioError'))
|
||||||
} finally {
|
} finally {
|
||||||
if (mountedRef.current) setAudioBusy(false)
|
if (mountedRef.current && playbackGeneration === playbackGenerationRef.current) {
|
||||||
|
setAudioBusy(false)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const stopAudio = async (): Promise<void> => {
|
const stopAudio = async (): Promise<void> => {
|
||||||
|
const playbackGeneration = ++playbackGenerationRef.current
|
||||||
setAudioBusy(true)
|
setAudioBusy(true)
|
||||||
try {
|
try {
|
||||||
await player.stopPlayer()
|
await player.stopPlayer()
|
||||||
if (!mountedRef.current) return
|
if (!mountedRef.current || playbackGeneration !== playbackGenerationRef.current) return
|
||||||
setActiveAudioId(null)
|
setActiveAudioId(null)
|
||||||
setPaused(false)
|
setPaused(false)
|
||||||
} catch {
|
} catch {
|
||||||
if (mountedRef.current) setError(t('mobile.hist.audioError'))
|
if (mountedRef.current && playbackGeneration === playbackGenerationRef.current) {
|
||||||
|
setError(t('mobile.hist.audioError'))
|
||||||
|
}
|
||||||
} finally {
|
} finally {
|
||||||
if (mountedRef.current) setAudioBusy(false)
|
if (mountedRef.current && playbackGeneration === playbackGenerationRef.current) {
|
||||||
|
setAudioBusy(false)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,7 @@
|
||||||
// src/screens/HomeScreen.tsx — 홈(오늘). 데스크톱 HomePage 와 같은 문법:
|
// src/screens/HomeScreen.tsx — 홈(오늘). 데스크톱 HomePage 와 같은 문법:
|
||||||
// 제목·날짜 → 녹음 시작 안내 → 한 줄 요약 → 최근 기록 5 · 최근 회의 3 → (무료) 요금제 한 줄.
|
// 제목·날짜 → 녹음 시작 안내 → 한 줄 요약 → 최근 기록 5 · 최근 회의 3 → (무료) 요금제 한 줄.
|
||||||
// 카드·통계 격자 없이 제목 + 1px 선. 조회한 값만 보여 주고, 못 불러오면 그렇다고 말한다.
|
// 카드·통계 격자 없이 제목 + 1px 선. 조회한 값만 보여 주고, 못 불러오면 그렇다고 말한다.
|
||||||
import { useCallback, useMemo, useState } from 'react'
|
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||||
import {
|
import {
|
||||||
Pressable,
|
Pressable,
|
||||||
RefreshControl,
|
RefreshControl,
|
||||||
|
|
@ -91,21 +91,46 @@ export default function HomeScreen(): React.ReactElement {
|
||||||
const [meetingsError, setMeetingsError] = useState(false)
|
const [meetingsError, setMeetingsError] = useState(false)
|
||||||
const [loading, setLoading] = useState(true)
|
const [loading, setLoading] = useState(true)
|
||||||
const [refreshing, setRefreshing] = useState(false)
|
const [refreshing, setRefreshing] = useState(false)
|
||||||
|
const mountedRef = useRef(true)
|
||||||
|
const refreshGenerationRef = useRef(0)
|
||||||
|
const currentUserIdRef = useRef<string | null>(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<void> => {
|
const refresh = useCallback(async (pullToRefresh = false): Promise<void> => {
|
||||||
if (!user?.id) {
|
const generation = ++refreshGenerationRef.current
|
||||||
|
const targetUserId = user?.id ?? null
|
||||||
|
if (!targetUserId) {
|
||||||
|
setStats(null)
|
||||||
|
setMeetings(null)
|
||||||
setStatsError(true)
|
setStatsError(true)
|
||||||
setMeetingsError(true)
|
setMeetingsError(true)
|
||||||
setLoading(false)
|
setLoading(false)
|
||||||
|
setRefreshing(false)
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if (pullToRefresh) setRefreshing(true)
|
if (pullToRefresh) setRefreshing(true)
|
||||||
else setLoading(true)
|
else setLoading(true)
|
||||||
const [statsResult, meetingsResult] = await Promise.allSettled([
|
const [statsResult, meetingsResult] = await Promise.allSettled([
|
||||||
loadDashboardStats(user.id),
|
loadDashboardStats(targetUserId),
|
||||||
listMeetingsPage({ userId: user.id, page: 0, pageSize: RECENT_MEETING_LIMIT }),
|
listMeetingsPage({ userId: targetUserId, page: 0, pageSize: RECENT_MEETING_LIMIT }),
|
||||||
refreshEntitlement(),
|
refreshEntitlement(),
|
||||||
])
|
])
|
||||||
|
if (
|
||||||
|
!mountedRef.current
|
||||||
|
|| generation !== refreshGenerationRef.current
|
||||||
|
|| currentUserIdRef.current !== targetUserId
|
||||||
|
) return
|
||||||
if (statsResult.status === 'fulfilled') {
|
if (statsResult.status === 'fulfilled') {
|
||||||
setStats(statsResult.value)
|
setStats(statsResult.value)
|
||||||
setStatsError(false)
|
setStatsError(false)
|
||||||
|
|
|
||||||
|
|
@ -127,6 +127,7 @@ export default function KnowledgeScreen(): React.ReactElement {
|
||||||
|
|
||||||
const loadMore = async (): Promise<void> => {
|
const loadMore = async (): Promise<void> => {
|
||||||
if (user === null || loading || loadingMore || !hasMore) return
|
if (user === null || loading || loadingMore || !hasMore) return
|
||||||
|
const generation = requestGeneration.current
|
||||||
const targetPage = page + 1
|
const targetPage = page + 1
|
||||||
setLoadingMore(true)
|
setLoadingMore(true)
|
||||||
try {
|
try {
|
||||||
|
|
@ -135,14 +136,16 @@ export default function KnowledgeScreen(): React.ReactElement {
|
||||||
search: activeDocumentSearch,
|
search: activeDocumentSearch,
|
||||||
page: targetPage,
|
page: targetPage,
|
||||||
})
|
})
|
||||||
|
if (generation !== requestGeneration.current) return
|
||||||
setDocuments((current) => mergeKnowledgeDocuments(current, result.documents))
|
setDocuments((current) => mergeKnowledgeDocuments(current, result.documents))
|
||||||
setPage(targetPage)
|
setPage(targetPage)
|
||||||
setTotal(result.total)
|
setTotal(result.total)
|
||||||
setHasMore(result.hasMore)
|
setHasMore(result.hasMore)
|
||||||
} catch (requestError) {
|
} catch (requestError) {
|
||||||
|
if (generation !== requestGeneration.current) return
|
||||||
setError(errorCode(requestError))
|
setError(errorCode(requestError))
|
||||||
} finally {
|
} finally {
|
||||||
setLoadingMore(false)
|
if (generation === requestGeneration.current) setLoadingMore(false)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -61,6 +61,7 @@ export default function MeetingsScreen({
|
||||||
const templateRequestGeneration = useRef(0)
|
const templateRequestGeneration = useRef(0)
|
||||||
const editorBusyRef = useRef(false)
|
const editorBusyRef = useRef(false)
|
||||||
const editorUserIdRef = useRef(user?.id ?? null)
|
const editorUserIdRef = useRef(user?.id ?? null)
|
||||||
|
const mountedRef = useRef(true)
|
||||||
const handledCreateRequests = useRef(new Set<number>())
|
const handledCreateRequests = useRef(new Set<number>())
|
||||||
const openCreateRef = useRef<() => void>(() => undefined)
|
const openCreateRef = useRef<() => void>(() => undefined)
|
||||||
const [meetings, setMeetings] = useState<Meeting[]>([])
|
const [meetings, setMeetings] = useState<Meeting[]>([])
|
||||||
|
|
@ -85,6 +86,13 @@ export default function MeetingsScreen({
|
||||||
const [editorError, setEditorError] = useState<string | null>(null)
|
const [editorError, setEditorError] = useState<string | null>(null)
|
||||||
const [editorBusy, setEditorBusy] = useState(false)
|
const [editorBusy, setEditorBusy] = useState(false)
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
mountedRef.current = true
|
||||||
|
return () => {
|
||||||
|
mountedRef.current = false
|
||||||
|
}
|
||||||
|
}, [])
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const nextUserId = user?.id ?? null
|
const nextUserId = user?.id ?? null
|
||||||
if (editorUserIdRef.current === nextUserId) return
|
if (editorUserIdRef.current === nextUserId) return
|
||||||
|
|
@ -152,6 +160,7 @@ export default function MeetingsScreen({
|
||||||
|
|
||||||
const loadMore = async (): Promise<void> => {
|
const loadMore = async (): Promise<void> => {
|
||||||
if (user === null || loading || loadingMore || !hasMore) return
|
if (user === null || loading || loadingMore || !hasMore) return
|
||||||
|
const generation = requestGeneration.current
|
||||||
const targetPage = page + 1
|
const targetPage = page + 1
|
||||||
setLoadingMore(true)
|
setLoadingMore(true)
|
||||||
try {
|
try {
|
||||||
|
|
@ -160,14 +169,18 @@ export default function MeetingsScreen({
|
||||||
search: committedSearch,
|
search: committedSearch,
|
||||||
page: targetPage,
|
page: targetPage,
|
||||||
})
|
})
|
||||||
|
if (generation !== requestGeneration.current || !mountedRef.current) return
|
||||||
setMeetings((current) => mergeMeetings(current, result.meetings))
|
setMeetings((current) => mergeMeetings(current, result.meetings))
|
||||||
setPage(targetPage)
|
setPage(targetPage)
|
||||||
setTotal(result.total)
|
setTotal(result.total)
|
||||||
setHasMore(result.hasMore)
|
setHasMore(result.hasMore)
|
||||||
} catch (requestError) {
|
} catch (requestError) {
|
||||||
|
if (generation !== requestGeneration.current || !mountedRef.current) return
|
||||||
setError(meetingErrorMessage(requestError, t))
|
setError(meetingErrorMessage(requestError, t))
|
||||||
} finally {
|
} finally {
|
||||||
setLoadingMore(false)
|
if (generation === requestGeneration.current && mountedRef.current) {
|
||||||
|
setLoadingMore(false)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
@ -257,6 +270,7 @@ export default function MeetingsScreen({
|
||||||
const saveEditor = async (): Promise<void> => {
|
const saveEditor = async (): Promise<void> => {
|
||||||
if (user === null || editor === null || editorBusyRef.current) return
|
if (user === null || editor === null || editorBusyRef.current) return
|
||||||
const mode = editor
|
const mode = editor
|
||||||
|
const actorUserId = user.id
|
||||||
editorBusyRef.current = true
|
editorBusyRef.current = true
|
||||||
setEditorBusy(true)
|
setEditorBusy(true)
|
||||||
setEditorError(null)
|
setEditorError(null)
|
||||||
|
|
@ -269,13 +283,14 @@ export default function MeetingsScreen({
|
||||||
.split(/[\r\n,]+/)
|
.split(/[\r\n,]+/)
|
||||||
.map((attendee) => attendee.trim())
|
.map((attendee) => attendee.trim())
|
||||||
.filter((attendee) => attendee.length > 0)
|
.filter((attendee) => attendee.length > 0)
|
||||||
const created = await createMeetingWorkspaceWithMetadata(user.id, {
|
const created = await createMeetingWorkspaceWithMetadata(actorUserId, {
|
||||||
title: editorTitle,
|
title: editorTitle,
|
||||||
attendees,
|
attendees,
|
||||||
language: editorLanguage,
|
language: editorLanguage,
|
||||||
templateId: editorTemplateId,
|
templateId: editorTemplateId,
|
||||||
idempotencyKey: editorCreationKey,
|
idempotencyKey: editorCreationKey,
|
||||||
})
|
})
|
||||||
|
if (!mountedRef.current || editorUserIdRef.current !== actorUserId) return
|
||||||
setMeetings((current) => mergeMeetings([created], current))
|
setMeetings((current) => mergeMeetings([created], current))
|
||||||
setTotal((current) => current + 1)
|
setTotal((current) => current + 1)
|
||||||
setEditor(null)
|
setEditor(null)
|
||||||
|
|
@ -295,16 +310,20 @@ export default function MeetingsScreen({
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
const updated = await updateMeetingTitleRevisionSafe(mode.meeting, editorTitle)
|
const updated = await updateMeetingTitleRevisionSafe(mode.meeting, editorTitle)
|
||||||
|
if (!mountedRef.current || editorUserIdRef.current !== actorUserId) return
|
||||||
setMeetings((current) => current.map((meeting) => (
|
setMeetings((current) => current.map((meeting) => (
|
||||||
meeting.id === updated.id ? updated : meeting
|
meeting.id === updated.id ? updated : meeting
|
||||||
)))
|
)))
|
||||||
setEditor(null)
|
setEditor(null)
|
||||||
}
|
}
|
||||||
} catch (requestError) {
|
} catch (requestError) {
|
||||||
|
if (!mountedRef.current || editorUserIdRef.current !== actorUserId) return
|
||||||
setEditorError(meetingErrorMessage(requestError, t))
|
setEditorError(meetingErrorMessage(requestError, t))
|
||||||
} finally {
|
} finally {
|
||||||
editorBusyRef.current = false
|
if (mountedRef.current && editorUserIdRef.current === actorUserId) {
|
||||||
setEditorBusy(false)
|
editorBusyRef.current = false
|
||||||
|
setEditorBusy(false)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -703,6 +703,10 @@ export default function RecordScreen({ route, navigation }: RecordScreenProps):
|
||||||
await processInput(input);
|
await processInput(input);
|
||||||
} catch (importError) {
|
} catch (importError) {
|
||||||
if (!mountedRef.current) return;
|
if (!mountedRef.current) return;
|
||||||
|
if (importError instanceof AudioPipelineError && importError.code === 'cancelled') {
|
||||||
|
setState('idle');
|
||||||
|
return;
|
||||||
|
}
|
||||||
setError(errorMessage(importError, t('mobile.rec.sharedImportFailed')));
|
setError(errorMessage(importError, t('mobile.rec.sharedImportFailed')));
|
||||||
setState('error');
|
setState('error');
|
||||||
} finally {
|
} finally {
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
import { useCallback, useMemo, useRef, useState } from 'react'
|
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
|
||||||
import {
|
import {
|
||||||
ActivityIndicator,
|
ActivityIndicator,
|
||||||
KeyboardAvoidingView,
|
KeyboardAvoidingView,
|
||||||
|
|
@ -37,6 +37,8 @@ export default function TeamsScreen({ navigation }: TeamsScreenProps): React.Rea
|
||||||
const { palette } = useMobilePreferences()
|
const { palette } = useMobilePreferences()
|
||||||
const styles = useMemo(() => createStyles(palette), [palette])
|
const styles = useMemo(() => createStyles(palette), [palette])
|
||||||
const loadGeneration = useRef(0)
|
const loadGeneration = useRef(0)
|
||||||
|
const mountedRef = useRef(true)
|
||||||
|
const userIdRef = useRef<string | null>(user?.id ?? null)
|
||||||
const [teams, setTeams] = useState<TeamSummary[]>([])
|
const [teams, setTeams] = useState<TeamSummary[]>([])
|
||||||
const [loading, setLoading] = useState(true)
|
const [loading, setLoading] = useState(true)
|
||||||
const [refreshing, setRefreshing] = useState(false)
|
const [refreshing, setRefreshing] = useState(false)
|
||||||
|
|
@ -70,6 +72,17 @@ export default function TeamsScreen({ navigation }: TeamsScreenProps): React.Rea
|
||||||
}
|
}
|
||||||
}, [user])
|
}, [user])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
mountedRef.current = true
|
||||||
|
return () => {
|
||||||
|
mountedRef.current = false
|
||||||
|
}
|
||||||
|
}, [])
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
userIdRef.current = user?.id ?? null
|
||||||
|
}, [user?.id])
|
||||||
|
|
||||||
useFocusEffect(useCallback(() => {
|
useFocusEffect(useCallback(() => {
|
||||||
void load(false)
|
void load(false)
|
||||||
return () => { loadGeneration.current += 1 }
|
return () => { loadGeneration.current += 1 }
|
||||||
|
|
@ -77,18 +90,21 @@ export default function TeamsScreen({ navigation }: TeamsScreenProps): React.Rea
|
||||||
|
|
||||||
const submitCreate = async (): Promise<void> => {
|
const submitCreate = async (): Promise<void> => {
|
||||||
if (user === null || editorBusy) return
|
if (user === null || editorBusy) return
|
||||||
|
const actorUserId = user.id
|
||||||
setEditorBusy(true)
|
setEditorBusy(true)
|
||||||
setEditorError(null)
|
setEditorError(null)
|
||||||
try {
|
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)])
|
setTeams((current) => [team, ...current.filter((row) => row.id !== team.id)])
|
||||||
setName('')
|
setName('')
|
||||||
setEditorOpen(false)
|
setEditorOpen(false)
|
||||||
navigation.navigate('TeamDetail', { teamId: team.id })
|
navigation.navigate('TeamDetail', { teamId: team.id })
|
||||||
} catch (requestError) {
|
} catch (requestError) {
|
||||||
|
if (!mountedRef.current || userIdRef.current !== actorUserId) return
|
||||||
setEditorError(teamErrorCode(requestError))
|
setEditorError(teamErrorCode(requestError))
|
||||||
} finally {
|
} finally {
|
||||||
setEditorBusy(false)
|
if (mountedRef.current) setEditorBusy(false)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue