fix(mobile): delete cleanup audio files on retry and isolate screen busy state across user switches

This commit is contained in:
Yun Chan 2026-11-14 15:17:52 +09:00
parent bd3c1a98d9
commit cc3f7460be
5 changed files with 376 additions and 45 deletions

View file

@ -61,7 +61,10 @@ import {
} 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> }
const mockFileSystem = FileSystem as typeof FileSystem & {
filesystem: Map<string, string>
unlink: jest.Mock
}
function makeQueueItem(
userId: string,
@ -148,6 +151,7 @@ describe('durable queue and history sync race guards', () => {
jest.useFakeTimers({ now: START_MS })
await AsyncStorage.clear()
mockFileSystem.filesystem.clear()
mockFileSystem.unlink.mockClear()
mockProcessAudioInput.mockReset()
mockListHistoryPage.mockReset()
mockLoadHistoryCache.mockReset()
@ -227,9 +231,10 @@ describe('durable queue and history sync race guards', () => {
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.
// cleanup item must not be downgraded to retry and re-transcribed, and its local file must be removed.
expect(mockProcessAudioInput).not.toHaveBeenCalled()
expect(cleanupState).toBeUndefined()
expect(mockFileSystem.filesystem.has(cleaningItem.path)).toBe(false)
await retryQueuedAudio(USER_A, runningItem.id)
const afterRunningRetry = durableQueueTestContract.parseQueue(
@ -238,6 +243,35 @@ describe('durable queue and history sync race guards', () => {
expect(afterRunningRetry.find((candidate) => candidate.id === runningItem.id)?.status).toBe('running')
})
test('durableQueue_정리단계재시도중파일삭제실패시_큐항목을유지하고정리재시도를예약함', async () => {
const cleaningItem = makeQueueItem(USER_A, 'aaaa0004', {
status: 'cleanup',
phase: 'saving',
})
mockFileSystem.filesystem.set(cleaningItem.path, 'audio-bytes')
await AsyncStorage.setItem(durableQueueTestContract.storageKey, JSON.stringify([cleaningItem]))
mockFileSystem.unlink.mockRejectedValueOnce(new Error('filesystem busy'))
await retryQueuedAudio(USER_A, cleaningItem.id)
const retained = durableQueueTestContract.parseQueue(
await AsyncStorage.getItem(durableQueueTestContract.storageKey),
)
expect(retained.find((candidate) => candidate.id === cleaningItem.id)?.status).toBe('cleanup')
expect(mockFileSystem.filesystem.has(cleaningItem.path)).toBe(true)
expect(jest.getTimerCount()).toBe(1)
await jest.advanceTimersByTimeAsync(60_000)
await flushMicrotasks()
const afterScheduledCleanup = durableQueueTestContract.parseQueue(
await AsyncStorage.getItem(durableQueueTestContract.storageKey),
)
expect(afterScheduledCleanup.find((candidate) => candidate.id === cleaningItem.id)).toBeUndefined()
expect(mockFileSystem.filesystem.has(cleaningItem.path)).toBe(false)
expect(mockProcessAudioInput).not.toHaveBeenCalled()
})
test('useHistorySync_오프라인캐시조회중새요청이나언마운트시_오래된캐시로덮어쓰지않음', async () => {
jest.useRealTimers()
let latestState: ReturnType<typeof useHistorySync> | null = null

View file

@ -1,5 +1,5 @@
import React from 'react'
import { TextInput } from 'react-native'
import { Modal, 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'
@ -57,6 +57,7 @@ const mockStartPlayer = jest.fn(async () => 'started')
const mockStopPlayer = jest.fn(async () => 'stopped')
const mockLoadSyncedCommandCatalog = jest.fn()
const mockCreateSyncedCommand = jest.fn()
const mockExecuteSyncedCommand = jest.fn()
const mockListTeams = jest.fn()
const mockCreateTeam = jest.fn()
@ -237,7 +238,7 @@ jest.mock('../src/features/commands/command-service', () => {
CommandSyncError: MockCommandSyncError,
createSyncedCommand: (...args: unknown[]) => mockCreateSyncedCommand(...args),
deleteSyncedCommand: jest.fn(),
executeSyncedCommand: jest.fn(),
executeSyncedCommand: (...args: unknown[]) => mockExecuteSyncedCommand(...args),
loadSyncedCommandCatalog: (...args: unknown[]) => mockLoadSyncedCommandCatalog(...args),
reorderSyncedCommand: jest.fn(),
setActiveSyncedCommand: jest.fn(),
@ -337,6 +338,7 @@ describe('screen async lifecycle and race guards', () => {
mockStopPlayer.mockClear()
mockLoadSyncedCommandCatalog.mockReset()
mockCreateSyncedCommand.mockReset()
mockExecuteSyncedCommand.mockReset()
mockListTeams.mockReset()
mockCreateTeam.mockReset()
})
@ -829,4 +831,233 @@ describe('screen async lifecycle and race guards', () => {
expect(mockNavigate).not.toHaveBeenCalled()
})
test('TeamsScreen_팀생성중계정전환후신규계정생성시_이전계정완료가현재생성중상태를해제하지않음', async () => {
mockListTeams.mockResolvedValue([])
const createGateA = deferred<{
id: string
name: string
ownerId: string
role: 'owner'
memberCount: number
createdAt: string
updatedAt: string
}>()
const createGateB = deferred<{
id: string
name: string
ownerId: string
role: 'owner'
memberCount: number
createdAt: string
updatedAt: string
}>()
mockCreateTeam
.mockReturnValueOnce(createGateA.promise)
.mockReturnValueOnce(createGateB.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('Team A')
})
await act(async () => {
renderer.root.findByProps({ testID: 'team-create-submit' }).props.onPress()
await Promise.resolve()
})
expect(renderer.root.findByProps({ testID: 'team-create-submit' }).props.disabled).toBe(true)
// Switch account from USER_A to USER_B while USER_A's createTeam is pending.
mockCurrentUser = { id: USER_B, email: 'b@example.com' }
await act(async () => {
renderer.update(<TeamsScreen navigation={mockNavigation as never} />)
await flush()
})
expect(renderer.root.findAllByType(Modal)[0]?.props.visible).toBe(false)
// User B opens modal and starts creating their own team.
act(() => {
renderer.root.findByProps({ testID: 'teams-create' }).props.onPress()
})
expect(renderer.root.findByProps({ testID: 'team-name-input' }).props.value).toBe('')
expect(renderer.root.findByProps({ testID: 'team-create-submit' }).props.label).toBe('mobile.teams.create')
act(() => {
renderer.root.findByProps({ testID: 'team-name-input' }).props.onChangeText('Team B')
})
await act(async () => {
renderer.root.findByProps({ testID: 'team-create-submit' }).props.onPress()
await Promise.resolve()
})
expect(renderer.root.findByProps({ testID: 'team-create-submit' }).props.disabled).toBe(true)
expect(renderer.root.findByProps({ testID: 'team-create-submit' }).props.label).toBe('mobile.teams.creating')
// Stale USER_A creation finishes now; must NOT clear USER_B's editorBusy or navigate.
await act(async () => {
createGateA.resolve({
id: TEAM_ID,
name: 'Team A',
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()
expect(renderer.root.findByProps({ testID: 'team-create-submit' }).props.disabled).toBe(true)
expect(renderer.root.findByProps({ testID: 'team-create-submit' }).props.label).toBe('mobile.teams.creating')
await act(async () => {
createGateB.resolve({
id: '99999999-9999-4999-8999-999999999998',
name: 'Team B',
ownerId: USER_B,
role: 'owner',
memberCount: 1,
createdAt: '2026-08-21T00:00:00.000Z',
updatedAt: '2026-08-21T00:00:00.000Z',
})
await flush()
})
expect(mockNavigate).toHaveBeenCalledWith('TeamDetail', { teamId: '99999999-9999-4999-8999-999999999998' })
activeRenderer = null
act(() => renderer.unmount())
})
test('CommandsScreen_명령변경및실행중계정전환시_이전계정완료가현재계정상태를해제하지않음', async () => {
const commandA: SyncedCommand = {
id: COMMAND_ID,
userId: USER_A,
builtinKey: null,
name: 'Cmd A',
description: '',
prompt: 'A: {{text}}',
icon: 'bolt',
sortOrder: 0,
revision: 1,
createdAt: '2026-08-21T00:00:00.000Z',
updatedAt: '2026-08-21T00:00:00.000Z',
}
const commandB: SyncedCommand = {
...commandA,
id: '77777777-7777-4777-8777-777777777778',
userId: USER_B,
name: 'Cmd B',
}
mockLoadSyncedCommandCatalog
.mockResolvedValueOnce({ commands: [commandA], activeInstructionId: null })
.mockResolvedValueOnce({ commands: [commandB], activeInstructionId: null })
const saveGateA = deferred<SyncedCommand>()
const saveGateB = deferred<SyncedCommand>()
mockCreateSyncedCommand
.mockReturnValueOnce(saveGateA.promise)
.mockReturnValueOnce(saveGateB.promise)
const runGateA = deferred<{ text: string; generationId: string }>()
const runGateB = deferred<{ text: string; generationId: string }>()
mockExecuteSyncedCommand
.mockReturnValueOnce(runGateA.promise)
.mockReturnValueOnce(runGateB.promise)
let renderer!: ReactTestRenderer
await act(async () => {
renderer = create(<CommandsScreen />)
activeRenderer = renderer
await flush()
})
// Start both a command execution and a create mutation as USER_A.
act(() => {
renderer.root.findByProps({ testID: 'commands-input' }).props.onChangeText('input A')
})
await act(async () => {
renderer.root.findByProps({ testID: 'commands-run' }).props.onPress()
await Promise.resolve()
})
act(() => {
renderer.root.findByProps({ testID: 'commands-add' }).props.onPress()
})
const editorA = renderer.root.findByProps({ testID: 'commands-editor' })
const inputsA = editorA.findAllByType(TextInput)
act(() => {
inputsA[0]?.props.onChangeText('New Cmd A')
inputsA[2]?.props.onChangeText('Prompt A: {{text}}')
})
await act(async () => {
renderer.root.findByProps({ testID: 'commands-editor-save' }).props.onPress()
await Promise.resolve()
})
expect(renderer.root.findByProps({ testID: 'commands-run' }).props.label).toBe('mobile.commands.running')
expect(renderer.root.findByProps({ testID: 'commands-editor-save' }).props.label).toBe('mobile.commands.saving')
// Switch account to USER_B while both USER_A requests are still pending.
mockCurrentUser = { id: USER_B, email: 'b@example.com' }
await act(async () => {
renderer.update(<CommandsScreen />)
await flush()
})
expect(renderer.root.findAllByProps({ testID: 'commands-editor' })).toHaveLength(0)
expect(renderer.root.findByProps({ testID: 'commands-add' }).props.disabled).toBe(false)
expect(renderer.root.findByProps({ testID: 'commands-run' }).props.label).toBe('mobile.commands.run')
// Start new execution and save as USER_B.
act(() => {
renderer.root.findByProps({ testID: 'commands-input' }).props.onChangeText('input B')
})
await act(async () => {
renderer.root.findByProps({ testID: 'commands-run' }).props.onPress()
await Promise.resolve()
})
act(() => {
renderer.root.findByProps({ testID: 'commands-add' }).props.onPress()
})
const editorB = renderer.root.findByProps({ testID: 'commands-editor' })
const inputsB = editorB.findAllByType(TextInput)
act(() => {
inputsB[0]?.props.onChangeText('New Cmd B')
inputsB[2]?.props.onChangeText('Prompt B: {{text}}')
})
await act(async () => {
renderer.root.findByProps({ testID: 'commands-editor-save' }).props.onPress()
await Promise.resolve()
})
expect(renderer.root.findByProps({ testID: 'commands-run' }).props.label).toBe('mobile.commands.running')
expect(renderer.root.findByProps({ testID: 'commands-editor-save' }).props.label).toBe('mobile.commands.saving')
// Stale USER_A save and run reject; USER_B's busy states must remain active.
await act(async () => {
saveGateA.reject(new CommandSyncError('server', 'late A failure'))
runGateA.reject(new Error('late A run failure'))
await flush()
})
expect(renderer.root.findByProps({ testID: 'commands-run' }).props.label).toBe('mobile.commands.running')
expect(renderer.root.findByProps({ testID: 'commands-editor-save' }).props.label).toBe('mobile.commands.saving')
expect(renderer.root.findByProps({ testID: 'commands-add' }).props.disabled).toBe(true)
await act(async () => {
saveGateB.resolve({ ...commandB, id: '77777777-7777-4777-8777-777777777779', name: 'New Cmd B' })
runGateB.resolve({ text: 'ok B', generationId: 'gen-b' })
await flush()
})
expect(renderer.root.findByProps({ testID: 'commands-run' }).props.label).toBe('mobile.commands.run')
expect(renderer.root.findAllByProps({ testID: 'commands-editor' })).toHaveLength(0)
activeRenderer = null
act(() => renderer.unmount())
})
})

View file

@ -473,6 +473,17 @@ export async function processQueuedAudioNow(
return processItem(item);
}
async function finishCleanupItem(item: DurableQueueItem): Promise<void> {
try {
await removeOwnedFile(item.path);
await removeItem(item);
} catch {
if (!suspendedUsers.has(item.userId)) {
scheduler.arm(item.userId, Date.now() + 60_000);
}
}
}
/**
* One pass over the user's queue. The listing only fixes the visiting order;
* every item is re-read right before acting on it, so work done meanwhile by
@ -492,12 +503,7 @@ async function runResumePass(userId: string): Promise<void> {
if (item === undefined || item.userId !== userId) continue;
if (item.status === 'terminal') continue;
if (item.status === 'cleanup') {
try {
await removeOwnedFile(item.path);
await removeItem(item);
} catch {
scheduler.arm(userId, Date.now() + 60_000);
}
await finishCleanupItem(item);
continue;
}
if (item.nextAttemptAtMs > Date.now()) {
@ -532,7 +538,7 @@ export async function retryQueuedAudio(userId: string, itemId: string): Promise<
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);
await finishCleanupItem(item);
return;
}
await replaceItem({

View file

@ -98,6 +98,14 @@ export default function CommandsScreen(): React.ReactElement {
const styles = useMemo(() => createStyles(palette), [palette])
const alive = useRef(true)
const request = useRef<AbortController | null>(null)
const loadGeneration = useRef(0)
const actorUserIdRef = useRef<string | null>(user?.id ?? null)
const scopeGenerationRef = useRef(0)
const isCurrentActor = useCallback((actorUserId: string | null, actorScope: number): boolean => (
alive.current
&& actorUserIdRef.current === actorUserId
&& scopeGenerationRef.current === actorScope
), [])
const [commands, setCommands] = useState<SyncedCommand[]>([])
const [activeId, setActiveId] = useState<string | null>(null)
const [selectedId, setSelectedId] = useState<string | null>(null)
@ -123,16 +131,20 @@ export default function CommandsScreen(): React.ReactElement {
), [t])
const load = useCallback(async (pull = false, silent = false): Promise<void> => {
if (!user?.id) {
const generation = ++loadGeneration.current
const actorUserId = user?.id ?? null
const actorScope = scopeGenerationRef.current
if (!actorUserId) {
setLoading(false)
setRefreshing(false)
setSyncError('auth')
return
}
if (pull) setRefreshing(true)
else if (!silent) setLoading(true)
try {
const catalog = await loadSyncedCommandCatalog(user.id)
if (!alive.current) return
const catalog = await loadSyncedCommandCatalog(actorUserId)
if (!isCurrentActor(actorUserId, actorScope) || generation !== loadGeneration.current) return
setCommands(catalog.commands)
setActiveId(catalog.activeInstructionId)
setSelectedId((current) => (
@ -142,19 +154,51 @@ export default function CommandsScreen(): React.ReactElement {
))
setSyncError(null)
} catch (error) {
if (alive.current) setSyncError(error instanceof CommandSyncError ? error.code : 'server')
if (isCurrentActor(actorUserId, actorScope) && generation === loadGeneration.current) {
setSyncError(error instanceof CommandSyncError ? error.code : 'server')
}
} finally {
if (alive.current) {
if (isCurrentActor(actorUserId, actorScope) && generation === loadGeneration.current) {
setLoading(false)
setRefreshing(false)
}
}
}, [isCurrentActor, user?.id])
useEffect(() => {
const nextUserId = user?.id ?? null
if (actorUserIdRef.current === nextUserId) return
actorUserIdRef.current = nextUserId
scopeGenerationRef.current += 1
loadGeneration.current += 1
request.current?.abort()
request.current = null
setCommands([])
setActiveId(null)
setSelectedId(null)
setSyncError(null)
setMutationId(null)
setEditor(null)
setEditorError(null)
setInput('')
setOutput(null)
setReportTarget(null)
setRunning(false)
setRunError(null)
setRetryable(false)
}, [user?.id])
useFocusEffect(useCallback(() => { void load() }, [load]))
useEffect(() => () => {
alive.current = false
request.current?.abort()
useFocusEffect(useCallback(() => {
void load()
return () => { loadGeneration.current += 1 }
}, [load]))
useEffect(() => {
alive.current = true
return () => {
alive.current = false
loadGeneration.current += 1
request.current?.abort()
}
}, [])
useEffect(() => {
if (!user?.id) return undefined
@ -176,25 +220,21 @@ 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
const actorScope = scopeGenerationRef.current
setMutationId(command.id)
try {
const nextActiveId = await setActiveSyncedCommand(actorUserId, activeId === command.id ? null : command.id)
if (!alive.current || actorUserIdRef.current !== actorUserId) return
if (!isCurrentActor(actorUserId, actorScope)) return
setActiveId(nextActiveId)
setSyncError(null)
} catch (error) {
if (!alive.current || actorUserIdRef.current !== actorUserId) return
if (!isCurrentActor(actorUserId, actorScope)) return
setSyncError(error instanceof CommandSyncError ? error.code : 'server')
} finally {
if (alive.current) setMutationId(null)
if (isCurrentActor(actorUserId, actorScope)) setMutationId(null)
}
}
@ -217,6 +257,7 @@ export default function CommandsScreen(): React.ReactElement {
async function save(): Promise<void> {
if (!editor || !user?.id || mutationId) return
const actorUserId = user.id
const actorScope = scopeGenerationRef.current
setMutationId(editor.command?.id ?? 'create')
setEditorError(null)
try {
@ -226,38 +267,39 @@ export default function CommandsScreen(): React.ReactElement {
...editor,
sortOrder: Math.max(1000, ...commands.map((item) => item.sortOrder + 10)),
})
if (!alive.current || actorUserIdRef.current !== actorUserId) return
if (!isCurrentActor(actorUserId, actorScope)) 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
if (!isCurrentActor(actorUserId, actorScope)) return
const code = error instanceof CommandSyncError ? error.code : 'server'
setEditorError(code)
if (code === 'conflict') void load(false, true)
} finally {
if (alive.current) setMutationId(null)
if (isCurrentActor(actorUserId, actorScope)) setMutationId(null)
}
}
async function remove(command: SyncedCommand): Promise<void> {
if (!user?.id || mutationId) return
const actorUserId = user.id
const actorScope = scopeGenerationRef.current
setMutationId(command.id)
try {
await deleteSyncedCommand(actorUserId, command)
if (!alive.current || actorUserIdRef.current !== actorUserId) return
if (!isCurrentActor(actorUserId, actorScope)) 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
if (!isCurrentActor(actorUserId, actorScope)) return
setSyncError(error instanceof CommandSyncError ? error.code : 'server')
} finally {
if (alive.current) setMutationId(null)
if (isCurrentActor(actorUserId, actorScope)) setMutationId(null)
}
}
@ -275,22 +317,24 @@ 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
const actorScope = scopeGenerationRef.current
setMutationId(command.id)
try {
const reordered = await reorderSyncedCommand(actorUserId, command, direction)
if (!alive.current || actorUserIdRef.current !== actorUserId) return
if (!isCurrentActor(actorUserId, actorScope)) return
setCommands(reordered)
} catch (error) {
if (!alive.current || actorUserIdRef.current !== actorUserId) return
if (!isCurrentActor(actorUserId, actorScope)) return
setSyncError(error instanceof CommandSyncError ? error.code : 'server')
} finally {
if (alive.current) setMutationId(null)
if (isCurrentActor(actorUserId, actorScope)) setMutationId(null)
}
}
const run = useCallback(async (): Promise<void> => {
if (!selected || running) return
const actorUserId = actorUserIdRef.current
const actorScope = scopeGenerationRef.current
const token = session?.access_token ?? ''
if (!token) {
setRunError('AUTH_REQUIRED')
@ -308,10 +352,10 @@ export default function CommandsScreen(): React.ReactElement {
model: preferences.preferredLlmModel,
signal: controller.signal,
})
if (!alive.current || actorUserIdRef.current !== actorUserId) return
if (!isCurrentActor(actorUserId, actorScope)) return
setOutput(result)
} catch (error) {
if (!alive.current || actorUserIdRef.current !== actorUserId) return
if (!isCurrentActor(actorUserId, actorScope)) return
const failure = error instanceof CommandExecutionError
? error
: new CommandExecutionError('SERVER_ERROR', true)
@ -321,9 +365,9 @@ export default function CommandsScreen(): React.ReactElement {
}
} finally {
if (request.current === controller) request.current = null
if (alive.current) setRunning(false)
if (isCurrentActor(actorUserId, actorScope)) setRunning(false)
}
}, [input, preferences.preferredLlmModel, running, selected, session?.access_token])
}, [input, isCurrentActor, preferences.preferredLlmModel, running, selected, session?.access_token])
return (
<KeyboardAvoidingView

View file

@ -39,6 +39,7 @@ export default function TeamsScreen({ navigation }: TeamsScreenProps): React.Rea
const loadGeneration = useRef(0)
const mountedRef = useRef(true)
const userIdRef = useRef<string | null>(user?.id ?? null)
const scopeGenerationRef = useRef(0)
const [teams, setTeams] = useState<TeamSummary[]>([])
const [loading, setLoading] = useState(true)
const [refreshing, setRefreshing] = useState(false)
@ -80,7 +81,16 @@ export default function TeamsScreen({ navigation }: TeamsScreenProps): React.Rea
}, [])
useEffect(() => {
userIdRef.current = user?.id ?? null
const nextUserId = user?.id ?? null
if (userIdRef.current === nextUserId) return
userIdRef.current = nextUserId
scopeGenerationRef.current += 1
setTeams([])
setError(null)
setEditorOpen(false)
setName('')
setEditorBusy(false)
setEditorError(null)
}, [user?.id])
useFocusEffect(useCallback(() => {
@ -91,20 +101,26 @@ export default function TeamsScreen({ navigation }: TeamsScreenProps): React.Rea
const submitCreate = async (): Promise<void> => {
if (user === null || editorBusy) return
const actorUserId = user.id
const actorScope = scopeGenerationRef.current
const isCurrentActor = (): boolean => (
mountedRef.current
&& userIdRef.current === actorUserId
&& scopeGenerationRef.current === actorScope
)
setEditorBusy(true)
setEditorError(null)
try {
const team = await createTeam(actorUserId, name)
if (!mountedRef.current || userIdRef.current !== actorUserId) return
if (!isCurrentActor()) 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
if (!isCurrentActor()) return
setEditorError(teamErrorCode(requestError))
} finally {
if (mountedRef.current) setEditorBusy(false)
if (isCurrentActor()) setEditorBusy(false)
}
}