fix(mobile): harden recorder, queue, context, and screen async lifecycles

This commit is contained in:
Yun Chan 2026-11-14 15:10:18 +09:00
parent 3f9e412257
commit bd3c1a98d9
25 changed files with 2279 additions and 68 deletions

View file

@ -406,6 +406,9 @@ async function requestAdmin(path: string, options: RequestOptions): Promise<unkn
options.signal?.addEventListener('abort', abortFromCaller, { once: true })
const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS)
try {
if (options.signal?.aborted === true) {
throw new AdminServiceError('network', null, false)
}
const response = await fetch(`${SUPABASE_URL}/functions/v1/${path}`, {
method: options.method ?? 'GET',
headers: {

View file

@ -100,6 +100,9 @@ async function sendChatRequest(
const timer = setTimeout(() => controller.abort(), options.timeoutMs ?? 45_000)
try {
if (options.signal?.aborted === true) {
throw new ChatServiceError('CANCELLED', false)
}
const headers: Record<string, string> = {
Authorization: `Bearer ${token}`,
'Content-Type': 'application/json',

View file

@ -87,6 +87,14 @@ const DEVICE_COLUMNS = [
export async function registerCurrentDevice(
userId: string,
config: MobileRuntimeConfig,
): Promise<RegisteredDevice> {
return registerCurrentDeviceAttempt(userId, config, true)
}
async function registerCurrentDeviceAttempt(
userId: string,
config: MobileRuntimeConfig,
allowConflictRetry: boolean,
): Promise<RegisteredDevice> {
requireUserId(userId)
const existing = await supabase
@ -130,9 +138,11 @@ export async function registerCurrentDevice(
.select(DEVICE_COLUMNS)
.single()
if (inserted.error) {
// A simultaneous bootstrap may have won the unique key. Fetching again is
// safe and never clears a remote revocation.
if (inserted.error.code === '23505') return registerCurrentDevice(userId, config)
// A simultaneous bootstrap may have won the unique key. Retry once safely
// while preventing infinite recursion when conflict errors persist.
if (inserted.error.code === '23505' && allowConflictRetry) {
return registerCurrentDeviceAttempt(userId, config, false)
}
throw new DeviceServiceError('server')
}
return normalizeRegisteredDevice(inserted.data)

View file

@ -209,6 +209,7 @@ export function useHistorySync(): HistorySyncModel {
try {
const cached = await loadHistoryCache(userId)
if (currentRequest !== requestId.current) return
if (cached !== null) {
commitWindow({
entries: filterCachedHistory(cached.entries, filter, debouncedSearch),
@ -222,6 +223,7 @@ export function useHistorySync(): HistorySyncModel {
setOffline(normalized.code === 'network')
}
} catch (cacheError) {
if (currentRequest !== requestId.current) return
setCacheWarning(true)
setError(normalized.code === 'network' ? normalized : syncError(cacheError))
setOffline(normalized.code === 'network')
@ -378,6 +380,7 @@ export function useHistorySync(): HistorySyncModel {
entry.revision,
{ is_favorite: optimisticFavorite },
)
if (!isCurrentScope()) return
const replacement: HistoryListEntry = { ...entry, ...updated }
updateEntries((current) => {
if (filter === 'favorites' && !updated.is_favorite) {
@ -387,9 +390,11 @@ export function useHistorySync(): HistorySyncModel {
})
await patchCachedEntry(entry.id, replacement, isCurrentScope)
} catch (mutationError) {
updateEntries((current) => current.map((item) => (
item.id === entry.id ? entry : item
)))
if (isCurrentScope()) {
updateEntries((current) => current.map((item) => (
item.id === entry.id ? entry : item
)))
}
throw mutationError
} finally {
endMutation(entry.id)
@ -404,9 +409,12 @@ export function useHistorySync(): HistorySyncModel {
updateEntries((current) => current.filter((item) => item.id !== entry.id))
try {
await deleteHistoryRevisionSafe(userId, entry.id, entry.revision)
if (!isCurrentScope()) return
await patchCachedEntry(entry.id, null, isCurrentScope)
} catch (mutationError) {
updateEntries((current) => mergeHistoryEntries(current, [entry]))
if (isCurrentScope()) {
updateEntries((current) => mergeHistoryEntries(current, [entry]))
}
throw mutationError
} finally {
endMutation(entry.id)

View file

@ -438,7 +438,14 @@ async function processItemCore(item: DurableQueueItem): Promise<AudioPipelineRes
};
await replaceItem(current);
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;
} finally {
runningControllers.delete(item.id);
@ -523,6 +530,11 @@ export async function retryQueuedAudio(userId: string, itemId: string): Promise<
const items = await readQueue();
const item = items.find(candidate => candidate.id === itemId && candidate.userId === userId);
if (item === undefined) throw new AudioPipelineError('file-read', 'Queued audio was not found');
if (item.status === 'running' || runningItemPromises.has(item.id)) return;
if (item.status === 'cleanup') {
await removeItem(item);
return;
}
await replaceItem({
...item,
status: 'retry',

View file

@ -280,6 +280,7 @@ export async function streamTalkResponse(
const generationId = response.headers.get('X-D3RO-Generation-Id')?.trim() ?? ''
if (!isUuid(generationId)) {
await response.body?.cancel?.().catch(() => undefined)
throw new ChatServiceError('INVALID_RESPONSE', true)
}
const text = await consumeStreamingBody(response, options.onTextDelta)

View file

@ -44,6 +44,7 @@ export function createPlatformRecorderBackend(): RecorderBackend {
export class AudioRecorder {
private selectedBackend: RecorderBackend | null;
private lease: RecorderOwner | null = null;
private pendingClaim: { owner: RecorderOwner; depth: number } | null = null;
constructor(backend?: RecorderBackend) {
this.selectedBackend = backend ?? null;
@ -102,6 +103,9 @@ export class AudioRecorder {
}
private async assertAvailable(owner: RecorderOwner): Promise<void> {
if (this.pendingClaim !== null && this.pendingClaim.owner !== owner) {
throw new RecorderBusyError(this.pendingClaim.owner);
}
const holder = await this.holder();
if (holder !== null && holder !== owner) throw new RecorderBusyError(holder);
// Another owner may have started a capture while the status was read.
@ -115,9 +119,28 @@ export class AudioRecorder {
claim: boolean,
operation: () => Promise<T>,
): Promise<T> {
await this.assertAvailable(owner);
if (claim) this.lease = owner;
return operation();
if (this.pendingClaim !== null && this.pendingClaim.owner !== owner) {
throw new RecorderBusyError(this.pendingClaim.owner);
}
if (claim) {
this.pendingClaim = this.pendingClaim?.owner === owner
? { owner, depth: this.pendingClaim.depth + 1 }
: { owner, depth: 1 };
}
try {
await this.assertAvailable(owner);
if (claim) this.lease = owner;
return await operation();
} finally {
if (claim && this.pendingClaim?.owner === owner) {
if (this.pendingClaim.depth <= 1) {
this.pendingClaim = null;
} else {
this.pendingClaim = { owner, depth: this.pendingClaim.depth - 1 };
}
this.releaseIfIdle(owner);
}
}
}
private async cleanupAsOwner(

View file

@ -298,13 +298,24 @@ export function BillingProvider({ children }: { children: ReactNode }): React.Re
const [errorCode, setErrorCode] = useState<string | null>(null)
const inFlightPurchases = useRef(new Set<string>())
const userIdRef = useRef<string | null>(user?.id ?? null)
const mountedRef = useRef(true)
const productsGenerationRef = useRef(0)
const installedFromPlayStore = useMemo(
() => Platform.OS === 'android' && getMobileRuntimeConfig().installedFromPlayStore,
[],
)
useEffect(() => {
mountedRef.current = true
return () => {
mountedRef.current = false
productsGenerationRef.current += 1
}
}, [])
useEffect(() => {
userIdRef.current = user?.id ?? null
productsGenerationRef.current += 1
inFlightPurchases.current.clear()
setOperation('idle')
setErrorCode(null)
@ -329,11 +340,13 @@ export function BillingProvider({ children }: { children: ReactNode }): React.Re
productId: purchase.productId,
purchaseToken: purchase.purchaseToken,
})
if (!mountedRef.current || userIdRef.current !== currentUserId) return
if (!result.ok) throw new Error(billingFailureCode(result))
const data = result.data
const verifiedProduct = verifiedRestorableProduct(data, purchase.productId)
const verification = data && isRecord(data.verification) ? data.verification : null
const refreshed = await entitlement.refresh()
if (!mountedRef.current || userIdRef.current !== currentUserId) return
if (verifiedProduct !== null) {
if (
refreshed === null
@ -346,11 +359,15 @@ export function BillingProvider({ children }: { children: ReactNode }): React.Re
throw new Error('purchase_not_verified_active')
}
} catch (candidate) {
if (userIdRef.current !== currentUserId) return
if (!mountedRef.current || userIdRef.current !== currentUserId) return
const resolvedErrorCode = await functionErrorCode(candidate)
if (!mountedRef.current || userIdRef.current !== currentUserId) return
setOperation('failed')
setErrorCode(await functionErrorCode(candidate))
setErrorCode(resolvedErrorCode)
} finally {
inFlightPurchases.current.delete(identity)
if (userIdRef.current === currentUserId) {
inFlightPurchases.current.delete(identity)
}
}
}, [entitlement])
@ -406,16 +423,20 @@ export function BillingProvider({ children }: { children: ReactNode }): React.Re
setErrorCode('play_store_install_required')
return
}
const productsGeneration = ++productsGenerationRef.current
setOperation('loading-products')
setErrorCode(null)
try {
if (!connected) {
const didReconnect = await reconnect()
if (!mountedRef.current || productsGeneration !== productsGenerationRef.current) return
if (!didReconnect) throw new Error('store_connection_failed')
}
await fetchProducts({ skus: [...GOOGLE_PLAY_SUBSCRIPTION_IDS], type: 'subs' })
if (!mountedRef.current || productsGeneration !== productsGenerationRef.current) return
setOperation('idle')
} catch (candidate) {
if (!mountedRef.current || productsGeneration !== productsGenerationRef.current) return
setOperation('failed')
setErrorCode(candidate instanceof Error ? candidate.message : 'product_fetch_failed')
}
@ -454,6 +475,7 @@ export function BillingProvider({ children }: { children: ReactNode }): React.Re
const replacementPurchases = currentProvider === 'google_play'
? await getAvailablePurchases({ includeSuspendedAndroid: true })
: []
if (!mountedRef.current || userIdRef.current !== currentUserId) return
const replacementPurchase = currentProvider === 'google_play'
? replacementPurchases.find((candidate) => (
candidate.productId === currentProductId
@ -491,6 +513,7 @@ export function BillingProvider({ children }: { children: ReactNode }): React.Re
},
})
} catch (candidate) {
if (!mountedRef.current || userIdRef.current !== currentUserId) return
setOperation('failed')
setErrorCode(candidate instanceof Error ? candidate.message : 'purchase_failed')
}
@ -525,7 +548,9 @@ export function BillingProvider({ children }: { children: ReactNode }): React.Re
await restoreGooglePlayPurchaseSet(
restoredPurchases,
async (restoredPurchase) => {
if (userIdRef.current !== currentUserId) throw new Error('restore_session_changed')
if (!mountedRef.current || userIdRef.current !== currentUserId) {
throw new Error('restore_session_changed')
}
const result = await invokeEdgeFunction<IapVerifyResult>('iap-verify', {
platform: 'google_play',
productId: restoredPurchase.productId,
@ -536,14 +561,18 @@ export function BillingProvider({ children }: { children: ReactNode }): React.Re
return data
},
async () => {
if (userIdRef.current !== currentUserId) throw new Error('restore_session_changed')
if (!mountedRef.current || userIdRef.current !== currentUserId) {
throw new Error('restore_session_changed')
}
return entitlement.refresh()
},
)
if (userIdRef.current !== currentUserId) throw new Error('restore_session_changed')
if (!mountedRef.current || userIdRef.current !== currentUserId) {
throw new Error('restore_session_changed')
}
setOperation('succeeded')
} catch (candidate) {
if (userIdRef.current !== currentUserId) return
if (!mountedRef.current || userIdRef.current !== currentUserId) return
setOperation('failed')
setErrorCode(candidate instanceof Error ? candidate.message : 'restore_failed')
}

View file

@ -39,7 +39,12 @@ export function DeviceProvider({ children }: { children: ReactNode }): React.Rea
const handleRevocation = useCallback(async (): Promise<void> => {
if (revocationHandledRef.current) return
revocationHandledRef.current = true
await purgeLocalSession()
try {
await purgeLocalSession()
} catch (revocationError) {
revocationHandledRef.current = false
throw revocationError
}
}, [purgeLocalSession])
const refreshCurrentDevice = useCallback(async (): Promise<void> => {

View file

@ -280,7 +280,7 @@ function isCachedSnapshot(value: unknown, userId: string): value is CacheEnvelop
}
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
try {
const value: unknown = JSON.parse(serialized)
@ -393,7 +393,7 @@ export function EntitlementProvider({ children }: { children: ReactNode }): Reac
setSnapshot(cached)
setStale(true)
setLoading(false)
}).finally(() => {
}).catch(() => null).finally(() => {
if (!cancelled) void refresh()
})

View file

@ -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) {
setStatus('ready')
return
@ -96,11 +97,17 @@ export function MobileAdsProvider({ children }: { children: ReactNode }): React.
maxAdContentRating: MaxAdContentRating.T,
testDeviceIdentifiers: runtimeConfig?.debug ? ['EMULATOR'] : undefined,
})
if (expectedGeneration !== generation.current) return
await MobileAds().initialize()
if (expectedGeneration !== generation.current) return
initialized.current = true
setStatus('ready')
}, [runtimeConfig?.debug])
useEffect(() => () => {
generation.current += 1
}, [])
useEffect(() => {
const currentGeneration = ++generation.current
if (!eligible) {
@ -127,7 +134,7 @@ export function MobileAdsProvider({ children }: { children: ReactNode }): React.
setStatus('consent-blocked')
return
}
await initializeAds()
await initializeAds(currentGeneration)
})
.catch((candidate) => {
if (currentGeneration !== generation.current) return
@ -137,25 +144,36 @@ export function MobileAdsProvider({ children }: { children: ReactNode }): React.
}, [eligible, initializeAds, runtimeConfig])
useEffect(() => {
let cancelled = false
void AdsConsent.getConsentInfo().then((info) => {
if (cancelled) return
setPrivacyOptionsRequired(
info.privacyOptionsRequirementStatus
=== AdsConsentPrivacyOptionsRequirementStatus.REQUIRED,
)
}).catch(() => undefined)
return () => {
cancelled = true
}
}, [])
const showPrivacyOptions = useCallback(async (): Promise<boolean> => {
const opGeneration = generation.current
const opEligible = eligible
try {
const consentInfo = await AdsConsent.showPrivacyOptionsForm()
if (opGeneration !== generation.current) return false
setPrivacyOptionsRequired(
consentInfo.privacyOptionsRequirementStatus
=== AdsConsentPrivacyOptionsRequirementStatus.REQUIRED,
)
if (eligible && consentInfo.canRequestAds) await initializeAds()
if (eligible && !consentInfo.canRequestAds) setStatus('consent-blocked')
if (opEligible && consentInfo.canRequestAds) await initializeAds(opGeneration)
if (opEligible && !consentInfo.canRequestAds && opGeneration === generation.current) {
setStatus('consent-blocked')
}
return true
} catch (candidate) {
if (opGeneration !== generation.current) return false
setErrorCode(candidateMessage(candidate, 'privacy_options_unavailable'))
return false
}
@ -318,6 +336,7 @@ export function useRewardedCredits(): RewardedCreditsValue {
).then(async (credited) => {
if (currentGeneration !== verificationGeneration.current) return
await entitlement.refresh()
if (currentGeneration !== verificationGeneration.current) return
setStatus(credited ? 'credited' : 'verification-pending')
}).catch((candidate) => {
if (currentGeneration !== verificationGeneration.current) return

View file

@ -139,6 +139,8 @@ export class AndroidForegroundRecorderBackend implements RecorderBackend {
private progressHandler: RecordingProgressHandler | null = null;
private stateHandler: RecordingStateHandler | null = null;
private pollGeneration = 0;
private pollTimer: ReturnType<typeof setTimeout> | null = null;
private sessionGeneration = 0;
async requestPermission(): Promise<boolean> {
const permission = PermissionsAndroid.PERMISSIONS.RECORD_AUDIO;
@ -163,6 +165,7 @@ export class AndroidForegroundRecorderBackend implements RecorderBackend {
throw new Error(`Cannot start recorder while it is ${this.state}`);
}
const sessionGen = ++this.sessionGeneration;
this.state = 'starting';
this.progressHandler = onProgress;
this.stateHandler = options.onStateChange ?? null;
@ -174,6 +177,10 @@ export class AndroidForegroundRecorderBackend implements RecorderBackend {
: { meetingId: options.meetingId },
),
);
if (sessionGen !== this.sessionGeneration) {
await androidRecordingModule().cancel().catch(() => undefined);
throw new Error('Recording start was cancelled');
}
if (snapshot.state !== 'recording' || snapshot.recording === null) {
throw new Error('Android foreground recorder did not start');
}
@ -186,10 +193,9 @@ export class AndroidForegroundRecorderBackend implements RecorderBackend {
this.stateHandler?.(snapshot);
this.startPolling();
} catch (error) {
this.progressHandler = null;
this.stateHandler = null;
this.currentPath = null;
this.state = 'idle';
if (sessionGen === this.sessionGeneration) {
this.resetToIdle();
}
throw error;
}
}
@ -199,14 +205,20 @@ export class AndroidForegroundRecorderBackend implements RecorderBackend {
throw new Error(`Cannot pause recorder while it is ${this.state}`);
}
const sessionGen = this.sessionGeneration;
this.state = 'pausing';
try {
const snapshot = parseNativeSnapshot(await androidRecordingModule().pause());
if (sessionGen !== this.sessionGeneration) {
throw new Error('Recording was cancelled');
}
if (snapshot.state !== 'paused') throw new Error('Android recorder did not pause');
this.state = 'paused';
this.stateHandler?.(snapshot);
} catch (error) {
this.state = 'recording';
if (sessionGen === this.sessionGeneration) {
this.state = 'recording';
}
throw error;
}
}
@ -216,14 +228,20 @@ export class AndroidForegroundRecorderBackend implements RecorderBackend {
throw new Error(`Cannot resume recorder while it is ${this.state}`);
}
const sessionGen = this.sessionGeneration;
this.state = 'resuming';
try {
const snapshot = parseNativeSnapshot(await androidRecordingModule().resume());
if (sessionGen !== this.sessionGeneration) {
throw new Error('Recording was cancelled');
}
if (snapshot.state !== 'recording') throw new Error('Android recorder did not resume');
this.state = 'recording';
this.stateHandler?.(snapshot);
} catch (error) {
this.state = 'paused';
if (sessionGen === this.sessionGeneration) {
this.state = 'paused';
}
throw error;
}
}
@ -234,13 +252,19 @@ export class AndroidForegroundRecorderBackend implements RecorderBackend {
}
if (this.currentPath === null) throw new Error('Recorder has no output path');
const sessionGen = this.sessionGeneration;
const previousState = this.state;
this.state = 'stopping';
let snapshot: RecordingRuntimeSnapshot;
try {
snapshot = parseNativeSnapshot(await androidRecordingModule().stop());
if (sessionGen !== this.sessionGeneration) {
throw new Error('Recording was cancelled');
}
} catch (error) {
await this.resyncAfterFailedStop(previousState, null);
if (sessionGen === this.sessionGeneration) {
await this.resyncAfterFailedStop(previousState, null);
}
throw error;
}
@ -273,14 +297,19 @@ export class AndroidForegroundRecorderBackend implements RecorderBackend {
if (recording !== undefined && this.currentPath !== null && path !== this.currentPath) {
return;
}
this.sessionGeneration += 1;
this.stopPolling();
this.resetToIdle();
}
async cancel(): Promise<void> {
const cancelGen = ++this.sessionGeneration;
this.stopPolling();
await androidRecordingModule().cancel();
this.resetToIdle();
await androidRecordingModule().cancel();
if (cancelGen === this.sessionGeneration) {
this.resetToIdle();
}
}
async restore(
@ -288,6 +317,7 @@ export class AndroidForegroundRecorderBackend implements RecorderBackend {
onStateChange?: RecordingStateHandler,
): Promise<RecordingRuntimeSnapshot> {
const snapshot = parseNativeSnapshot(await androidRecordingModule().getStatus());
this.sessionGeneration += 1;
this.stopPolling();
this.progressHandler = onProgress ?? null;
this.stateHandler = onStateChange ?? null;
@ -386,7 +416,13 @@ export class AndroidForegroundRecorderBackend implements RecorderBackend {
this.stateHandler?.(snapshot);
if (snapshot.state === 'recording' || snapshot.state === 'paused') {
this.state = snapshot.state;
setTimeout(() => { void poll(); }, 250);
if (generation === this.pollGeneration) {
if (this.pollTimer !== null) clearTimeout(this.pollTimer);
this.pollTimer = setTimeout(() => {
this.pollTimer = null;
void poll();
}, 250);
}
} else {
this.currentPath = snapshot.recording?.path ?? null;
this.state = snapshot.state === 'idle' ? 'idle' : 'stopped';
@ -394,7 +430,11 @@ export class AndroidForegroundRecorderBackend implements RecorderBackend {
} catch {
// A transient React bridge failure must not stop the native foreground capture.
if (generation === this.pollGeneration) {
setTimeout(() => { void poll(); }, 500);
if (this.pollTimer !== null) clearTimeout(this.pollTimer);
this.pollTimer = setTimeout(() => {
this.pollTimer = null;
void poll();
}, 500);
}
}
};
@ -403,5 +443,9 @@ export class AndroidForegroundRecorderBackend implements RecorderBackend {
private stopPolling(): void {
this.pollGeneration += 1;
if (this.pollTimer !== null) {
clearTimeout(this.pollTimer);
this.pollTimer = null;
}
}
}

View file

@ -104,6 +104,7 @@ export class NitroRecorderBackend implements RecorderBackend {
private state: NitroRecorderState = 'idle';
private currentPath: string | null = null;
private progress: RecordingProgress = { durationMs: 0, meteringDb: null };
private startGeneration = 0;
private pendingStart: Promise<void> | null = null;
private pendingTransition: Promise<void> | 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}`);
}
const generation = ++this.startGeneration;
this.state = 'starting';
try {
await deleteStaleTemporaryFiles();
} catch (error) {
this.state = 'idle';
if (generation === this.startGeneration) {
this.state = 'idle';
}
throw error;
}
if (generation !== this.startGeneration) {
throw new Error('Recording start was cancelled');
}
const outputPath = createTemporaryPath();
this.currentPath = outputPath;
this.progress = { durationMs: 0, meteringDb: null };
@ -296,10 +304,15 @@ export class NitroRecorderBackend implements RecorderBackend {
}
async cancel(): Promise<void> {
this.startGeneration += 1;
if (this.state === 'starting' && this.pendingStart !== null) {
try {
await this.pendingStart;
} catch {
this.progressHandler = null;
this.currentPath = null;
this.state = 'idle';
this.progress = { durationMs: 0, meteringDb: null };
return;
}
}

View file

@ -176,16 +176,25 @@ export default function CommandsScreen(): React.ReactElement {
return () => { void supabase.removeChannel(channel) }
}, [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> {
if (!user?.id || mutationId) return
const actorUserId = user.id
setMutationId(command.id)
try {
setActiveId(await setActiveSyncedCommand(user.id, activeId === command.id ? null : command.id))
const nextActiveId = await setActiveSyncedCommand(actorUserId, activeId === command.id ? null : command.id)
if (!alive.current || actorUserIdRef.current !== actorUserId) return
setActiveId(nextActiveId)
setSyncError(null)
} catch (error) {
if (!alive.current || actorUserIdRef.current !== actorUserId) return
setSyncError(error instanceof CommandSyncError ? error.code : 'server')
} finally {
setMutationId(null)
if (alive.current) setMutationId(null)
}
}
@ -207,42 +216,48 @@ export default function CommandsScreen(): React.ReactElement {
async function save(): Promise<void> {
if (!editor || !user?.id || mutationId) return
const actorUserId = user.id
setMutationId(editor.command?.id ?? 'create')
setEditorError(null)
try {
const saved = editor.command
? await updateSyncedCommand(user.id, editor.command, editor)
: await createSyncedCommand(user.id, {
? await updateSyncedCommand(actorUserId, editor.command, editor)
: await createSyncedCommand(actorUserId, {
...editor,
sortOrder: Math.max(1000, ...commands.map((item) => item.sortOrder + 10)),
})
if (!alive.current || actorUserIdRef.current !== actorUserId) return
const next = [...commands.filter((item) => item.id !== saved.id), saved]
.sort((a, b) => a.sortOrder - b.sortOrder || a.createdAt.localeCompare(b.createdAt))
setCommands(next)
setSelectedId(saved.id)
setEditor(null)
} catch (error) {
if (!alive.current || actorUserIdRef.current !== actorUserId) return
const code = error instanceof CommandSyncError ? error.code : 'server'
setEditorError(code)
if (code === 'conflict') void load(false, true)
} finally {
setMutationId(null)
if (alive.current) setMutationId(null)
}
}
async function remove(command: SyncedCommand): Promise<void> {
if (!user?.id || mutationId) return
const actorUserId = user.id
setMutationId(command.id)
try {
await deleteSyncedCommand(user.id, command)
await deleteSyncedCommand(actorUserId, command)
if (!alive.current || actorUserIdRef.current !== actorUserId) return
const next = commands.filter((item) => item.id !== command.id)
setCommands(next)
if (selectedId === command.id) setSelectedId(next[0]?.id ?? null)
if (activeId === command.id) setActiveId(null)
} catch (error) {
if (!alive.current || actorUserIdRef.current !== actorUserId) return
setSyncError(error instanceof CommandSyncError ? error.code : 'server')
} finally {
setMutationId(null)
if (alive.current) setMutationId(null)
}
}
@ -259,18 +274,23 @@ export default function CommandsScreen(): React.ReactElement {
async function move(command: SyncedCommand, direction: 'up' | 'down'): Promise<void> {
if (!user?.id || mutationId) return
const actorUserId = user.id
setMutationId(command.id)
try {
setCommands(await reorderSyncedCommand(user.id, command, direction))
const reordered = await reorderSyncedCommand(actorUserId, command, direction)
if (!alive.current || actorUserIdRef.current !== actorUserId) return
setCommands(reordered)
} catch (error) {
if (!alive.current || actorUserIdRef.current !== actorUserId) return
setSyncError(error instanceof CommandSyncError ? error.code : 'server')
} finally {
setMutationId(null)
if (alive.current) setMutationId(null)
}
}
const run = useCallback(async (): Promise<void> => {
if (!selected || running) return
const actorUserId = actorUserIdRef.current
const token = session?.access_token ?? ''
if (!token) {
setRunError('AUTH_REQUIRED')
@ -283,12 +303,15 @@ export default function CommandsScreen(): React.ReactElement {
setRunError(null)
setRetryable(false)
try {
setOutput(await executeSyncedCommand(selected, input, {
const result = await executeSyncedCommand(selected, input, {
accessToken: token,
model: preferences.preferredLlmModel,
signal: controller.signal,
}))
})
if (!alive.current || actorUserIdRef.current !== actorUserId) return
setOutput(result)
} catch (error) {
if (!alive.current || actorUserIdRef.current !== actorUserId) return
const failure = error instanceof CommandExecutionError
? error
: new CommandExecutionError('SERVER_ERROR', true)

View file

@ -89,6 +89,7 @@ export default function HistoryDetailScreen({
playerRef.current = player
const mountedRef = useRef(true)
const loadGenerationRef = useRef(0)
const playbackGenerationRef = useRef(0)
const [detail, setDetail] = useState<HistoryDetail | null>(null)
const [loading, setLoading] = useState(true)
const [error, setError] = useState<string | null>(null)
@ -109,6 +110,7 @@ export default function HistoryDetailScreen({
return () => {
mountedRef.current = false
loadGenerationRef.current += 1
playbackGenerationRef.current += 1
void Promise.resolve(playerRef.current.stopPlayer()).catch(() => undefined)
}
}, [])
@ -306,53 +308,62 @@ export default function HistoryDetailScreen({
const controlAudio = async (audioFile: AudioFile): Promise<void> => {
if (user === null || audioBusy) return
const playbackGeneration = ++playbackGenerationRef.current
setAudioBusy(true)
setError(null)
try {
if (activeAudioId === audioFile.id && player.state.isPlaying) {
await player.pausePlayer()
if (mountedRef.current) setPaused(true)
if (mountedRef.current && playbackGeneration === playbackGenerationRef.current) setPaused(true)
return
}
if (activeAudioId === audioFile.id && paused) {
await player.resumePlayer()
if (mountedRef.current) setPaused(false)
if (mountedRef.current && playbackGeneration === playbackGenerationRef.current) setPaused(false)
return
}
if (activeAudioId !== null) {
await player.stopPlayer()
if (!mountedRef.current) return
if (!mountedRef.current || playbackGeneration !== playbackGenerationRef.current) return
}
const signedUrl = await createAudioPlaybackUrl(user.id, audioFile)
if (!mountedRef.current) return
if (!mountedRef.current || playbackGeneration !== playbackGenerationRef.current) return
await player.startPlayer(signedUrl)
if (!mountedRef.current) {
void Promise.resolve(player.stopPlayer()).catch(() => undefined)
return
}
if (playbackGeneration !== playbackGenerationRef.current) return
setActiveAudioId(audioFile.id)
setPaused(false)
} catch {
if (!mountedRef.current) return
if (!mountedRef.current || playbackGeneration !== playbackGenerationRef.current) return
setActiveAudioId(null)
setPaused(false)
setError(t('mobile.hist.audioError'))
} finally {
if (mountedRef.current) setAudioBusy(false)
if (mountedRef.current && playbackGeneration === playbackGenerationRef.current) {
setAudioBusy(false)
}
}
}
const stopAudio = async (): Promise<void> => {
const playbackGeneration = ++playbackGenerationRef.current
setAudioBusy(true)
try {
await player.stopPlayer()
if (!mountedRef.current) return
if (!mountedRef.current || playbackGeneration !== playbackGenerationRef.current) return
setActiveAudioId(null)
setPaused(false)
} catch {
if (mountedRef.current) setError(t('mobile.hist.audioError'))
if (mountedRef.current && playbackGeneration === playbackGenerationRef.current) {
setError(t('mobile.hist.audioError'))
}
} finally {
if (mountedRef.current) setAudioBusy(false)
if (mountedRef.current && playbackGeneration === playbackGenerationRef.current) {
setAudioBusy(false)
}
}
}

View file

@ -1,7 +1,7 @@
// src/screens/HomeScreen.tsx — 홈(오늘). 데스크톱 HomePage 와 같은 문법:
// 제목·날짜 → 녹음 시작 안내 → 한 줄 요약 → 최근 기록 5 · 최근 회의 3 → (무료) 요금제 한 줄.
// 카드·통계 격자 없이 제목 + 1px 선. 조회한 값만 보여 주고, 못 불러오면 그렇다고 말한다.
import { useCallback, useMemo, useState } from 'react'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import {
Pressable,
RefreshControl,
@ -91,21 +91,46 @@ export default function HomeScreen(): React.ReactElement {
const [meetingsError, setMeetingsError] = useState(false)
const [loading, setLoading] = useState(true)
const [refreshing, setRefreshing] = useState(false)
const mountedRef = useRef(true)
const refreshGenerationRef = useRef(0)
const currentUserIdRef = useRef<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> => {
if (!user?.id) {
const generation = ++refreshGenerationRef.current
const targetUserId = user?.id ?? null
if (!targetUserId) {
setStats(null)
setMeetings(null)
setStatsError(true)
setMeetingsError(true)
setLoading(false)
setRefreshing(false)
return
}
if (pullToRefresh) setRefreshing(true)
else setLoading(true)
const [statsResult, meetingsResult] = await Promise.allSettled([
loadDashboardStats(user.id),
listMeetingsPage({ userId: user.id, page: 0, pageSize: RECENT_MEETING_LIMIT }),
loadDashboardStats(targetUserId),
listMeetingsPage({ userId: targetUserId, page: 0, pageSize: RECENT_MEETING_LIMIT }),
refreshEntitlement(),
])
if (
!mountedRef.current
|| generation !== refreshGenerationRef.current
|| currentUserIdRef.current !== targetUserId
) return
if (statsResult.status === 'fulfilled') {
setStats(statsResult.value)
setStatsError(false)

View file

@ -127,6 +127,7 @@ export default function KnowledgeScreen(): React.ReactElement {
const loadMore = async (): Promise<void> => {
if (user === null || loading || loadingMore || !hasMore) return
const generation = requestGeneration.current
const targetPage = page + 1
setLoadingMore(true)
try {
@ -135,14 +136,16 @@ export default function KnowledgeScreen(): React.ReactElement {
search: activeDocumentSearch,
page: targetPage,
})
if (generation !== requestGeneration.current) return
setDocuments((current) => mergeKnowledgeDocuments(current, result.documents))
setPage(targetPage)
setTotal(result.total)
setHasMore(result.hasMore)
} catch (requestError) {
if (generation !== requestGeneration.current) return
setError(errorCode(requestError))
} finally {
setLoadingMore(false)
if (generation === requestGeneration.current) setLoadingMore(false)
}
}

View file

@ -61,6 +61,7 @@ export default function MeetingsScreen({
const templateRequestGeneration = useRef(0)
const editorBusyRef = useRef(false)
const editorUserIdRef = useRef(user?.id ?? null)
const mountedRef = useRef(true)
const handledCreateRequests = useRef(new Set<number>())
const openCreateRef = useRef<() => void>(() => undefined)
const [meetings, setMeetings] = useState<Meeting[]>([])
@ -85,6 +86,13 @@ export default function MeetingsScreen({
const [editorError, setEditorError] = useState<string | null>(null)
const [editorBusy, setEditorBusy] = useState(false)
useEffect(() => {
mountedRef.current = true
return () => {
mountedRef.current = false
}
}, [])
useEffect(() => {
const nextUserId = user?.id ?? null
if (editorUserIdRef.current === nextUserId) return
@ -152,6 +160,7 @@ export default function MeetingsScreen({
const loadMore = async (): Promise<void> => {
if (user === null || loading || loadingMore || !hasMore) return
const generation = requestGeneration.current
const targetPage = page + 1
setLoadingMore(true)
try {
@ -160,14 +169,18 @@ export default function MeetingsScreen({
search: committedSearch,
page: targetPage,
})
if (generation !== requestGeneration.current || !mountedRef.current) return
setMeetings((current) => mergeMeetings(current, result.meetings))
setPage(targetPage)
setTotal(result.total)
setHasMore(result.hasMore)
} catch (requestError) {
if (generation !== requestGeneration.current || !mountedRef.current) return
setError(meetingErrorMessage(requestError, t))
} finally {
setLoadingMore(false)
if (generation === requestGeneration.current && mountedRef.current) {
setLoadingMore(false)
}
}
}
@ -257,6 +270,7 @@ export default function MeetingsScreen({
const saveEditor = async (): Promise<void> => {
if (user === null || editor === null || editorBusyRef.current) return
const mode = editor
const actorUserId = user.id
editorBusyRef.current = true
setEditorBusy(true)
setEditorError(null)
@ -269,13 +283,14 @@ export default function MeetingsScreen({
.split(/[\r\n,]+/)
.map((attendee) => attendee.trim())
.filter((attendee) => attendee.length > 0)
const created = await createMeetingWorkspaceWithMetadata(user.id, {
const created = await createMeetingWorkspaceWithMetadata(actorUserId, {
title: editorTitle,
attendees,
language: editorLanguage,
templateId: editorTemplateId,
idempotencyKey: editorCreationKey,
})
if (!mountedRef.current || editorUserIdRef.current !== actorUserId) return
setMeetings((current) => mergeMeetings([created], current))
setTotal((current) => current + 1)
setEditor(null)
@ -295,16 +310,20 @@ export default function MeetingsScreen({
}
} else {
const updated = await updateMeetingTitleRevisionSafe(mode.meeting, editorTitle)
if (!mountedRef.current || editorUserIdRef.current !== actorUserId) return
setMeetings((current) => current.map((meeting) => (
meeting.id === updated.id ? updated : meeting
)))
setEditor(null)
}
} catch (requestError) {
if (!mountedRef.current || editorUserIdRef.current !== actorUserId) return
setEditorError(meetingErrorMessage(requestError, t))
} finally {
editorBusyRef.current = false
setEditorBusy(false)
if (mountedRef.current && editorUserIdRef.current === actorUserId) {
editorBusyRef.current = false
setEditorBusy(false)
}
}
}

View file

@ -703,6 +703,10 @@ export default function RecordScreen({ route, navigation }: RecordScreenProps):
await processInput(input);
} catch (importError) {
if (!mountedRef.current) return;
if (importError instanceof AudioPipelineError && importError.code === 'cancelled') {
setState('idle');
return;
}
setError(errorMessage(importError, t('mobile.rec.sharedImportFailed')));
setState('error');
} finally {

View file

@ -1,4 +1,4 @@
import { useCallback, useMemo, useRef, useState } from 'react'
import { useCallback, useEffect, useMemo, useRef, useState } from 'react'
import {
ActivityIndicator,
KeyboardAvoidingView,
@ -37,6 +37,8 @@ export default function TeamsScreen({ navigation }: TeamsScreenProps): React.Rea
const { palette } = useMobilePreferences()
const styles = useMemo(() => createStyles(palette), [palette])
const loadGeneration = useRef(0)
const mountedRef = useRef(true)
const userIdRef = useRef<string | null>(user?.id ?? null)
const [teams, setTeams] = useState<TeamSummary[]>([])
const [loading, setLoading] = useState(true)
const [refreshing, setRefreshing] = useState(false)
@ -70,6 +72,17 @@ export default function TeamsScreen({ navigation }: TeamsScreenProps): React.Rea
}
}, [user])
useEffect(() => {
mountedRef.current = true
return () => {
mountedRef.current = false
}
}, [])
useEffect(() => {
userIdRef.current = user?.id ?? null
}, [user?.id])
useFocusEffect(useCallback(() => {
void load(false)
return () => { loadGeneration.current += 1 }
@ -77,18 +90,21 @@ export default function TeamsScreen({ navigation }: TeamsScreenProps): React.Rea
const submitCreate = async (): Promise<void> => {
if (user === null || editorBusy) return
const actorUserId = user.id
setEditorBusy(true)
setEditorError(null)
try {
const team = await createTeam(user.id, name)
const team = await createTeam(actorUserId, name)
if (!mountedRef.current || userIdRef.current !== actorUserId) return
setTeams((current) => [team, ...current.filter((row) => row.id !== team.id)])
setName('')
setEditorOpen(false)
navigation.navigate('TeamDetail', { teamId: team.id })
} catch (requestError) {
if (!mountedRef.current || userIdRef.current !== actorUserId) return
setEditorError(teamErrorCode(requestError))
} finally {
setEditorBusy(false)
if (mountedRef.current) setEditorBusy(false)
}
}