fix: red-team round 3 hardening across desktop, mobile, core and server

Batch of red-team r3 fixes that were in the working tree before the
2026-09-28 design overhaul, committed as one unit with their tests.

- desktop main: STT timeouts and sidecar, voice recording store, sync
  (credentials, audio, knowledge reindex, push gates), runtime
  provisioner, update policy, AltGr keybindings, voice-command policy,
  dictionary file codec/limits, meeting transcript condensing and a
  local recording ledger so interrupted-session recovery only closes
  meetings this device recorded (a phone's live meeting is left alone).
- mobile: login CSRF via implicit token callbacks rejected, account
  deletion/retention, durable queue retention, knowledge realtime
  without unfiltered DELETE, meeting re-record failure paths, cloud STT
  client, preferences store/resync.
- core: text chunking splits long unbroken transcripts to fit, template
  field policy, dictionary limits, meeting markdown inline handling.
- server: payple webhook policy and cancellation order scope, meeting
  document generation quota, team RPC null-role guard, unified LLM
  quota in-flight accounting, knowledge chunk vector index, meeting
  re-record failure paths (migrations 20260929*).
- ci: portable/runtime feed gates, update-policy schema, Forgejo file
  delete and alias planning.

Four older tests are updated to the new contracts rather than the old
behavior: token-pair auth callbacks are rejected, knowledge realtime no
longer subscribes to DELETE, long transcript lines are split, and
meeting recovery requires the local recording ledger for empty rows.
This commit is contained in:
Yun Chan 2026-09-28 20:45:52 +09:00
parent 2428ede03d
commit ba9ef9741e
161 changed files with 17056 additions and 2379 deletions

View file

@ -1,11 +1,21 @@
import { clearAllActionHistories } from '../features/actions/action-service'
import { clearAllHistoryCaches } from '../features/history/history-cache'
import { deleteNativePushRegistration } from '../features/notifications/notification-native'
import { clearAllQueuedAudio } from '../features/recording/durable-processing-queue'
import {
clearAllQueuedAudio,
retainQueuedAudioOnlyForUser,
} from '../features/recording/durable-processing-queue'
import { clearEveryGenerationIdempotencyKey } from '../features/templates'
import { audioRecorder } from './audio-recorder'
import {
DISCARD_UNSYNCED_WORK,
unsyncedWorkDispositionKey,
type UnsyncedWorkDisposition,
} from './auth-transition-policy'
import { clearAllEntitlementCaches } from './entitlement-context'
import { clearAllUserPreferenceCaches } from './preferences-context'
import { stopLiveCaptureKeepingFile } from './retain-live-capture'
import { retainedAccountWork } from './retained-account-work'
export class AccountLocalDataPurgeError extends Error {
readonly code = 'account_local_data_purge_failed'
@ -16,34 +26,88 @@ export class AccountLocalDataPurgeError extends Error {
}
}
let purgeInFlight: Promise<void> | null = null
type PurgeTask = () => Promise<void>
/** Account-scoped caches: always removed, they can be rebuilt from the server. */
const ACCOUNT_CACHE_TASKS: readonly PurgeTask[] = [
clearAllHistoryCaches,
clearAllEntitlementCaches,
clearAllUserPreferenceCaches,
clearAllActionHistories,
clearEveryGenerationIdempotencyKey,
deleteNativePushRegistration,
]
/**
* Removes every account-scoped local artifact before an auth boundary opens.
* Unsynced user-owned work (the live capture and durable-queue recordings) is
* the only copy of that audio. It is deleted only for a discard boundary; on a
* retain boundary the microphone is stopped, the owner's files are kept and
* the owner is recorded so a different account can still never see them.
*/
function unsyncedWorkTasks(disposition: UnsyncedWorkDisposition): PurgeTask[] {
if (disposition.kind === 'discard') {
return [
() => audioRecorder.cancel(),
clearAllQueuedAudio,
() => retainedAccountWork.release(),
]
}
const owner = disposition.ownerUserId
return [
() => retainedAccountWork.retain(owner),
() => stopLiveCaptureKeepingFile(audioRecorder),
() => retainQueuedAudioOnlyForUser(owner),
]
}
function startTask(task: PurgeTask): Promise<void> {
try {
return Promise.resolve(task())
} catch (error) {
return Promise.reject(error)
}
}
async function runPurge(disposition: UnsyncedWorkDisposition): Promise<void> {
const results = await Promise.allSettled(
[...ACCOUNT_CACHE_TASKS, ...unsyncedWorkTasks(disposition)].map(startTask),
)
if (results.some((result) => result.status === 'rejected')) {
throw new AccountLocalDataPurgeError()
}
}
interface PurgeRun {
key: string
promise: Promise<void>
}
let purgeInFlight: PurgeRun | null = null
/**
* Removes account-scoped local artifacts before an auth boundary opens.
* All tasks are allowed to settle so an early failure cannot skip deletion of
* unrelated caches or raw audio; callers receive only a stable public code.
*
* Concurrent calls with the same disposition share one run; a call with a
* different disposition (for example a sign-out immediately replaced by
* another account) runs after the current one so its stricter cleanup is
* never swallowed by the earlier, weaker one.
*/
export function purgeAllAccountLocalData(): Promise<void> {
if (purgeInFlight !== null) return purgeInFlight
export function purgeAllAccountLocalData(
unsyncedWork: UnsyncedWorkDisposition = DISCARD_UNSYNCED_WORK,
): Promise<void> {
const key = unsyncedWorkDispositionKey(unsyncedWork)
const previous = purgeInFlight
if (previous !== null && previous.key === key) return previous.promise
const operation = (async (): Promise<void> => {
const results = await Promise.allSettled([
clearAllHistoryCaches(),
clearAllEntitlementCaches(),
clearAllUserPreferenceCaches(),
audioRecorder.cancel(),
clearAllQueuedAudio(),
clearAllActionHistories(),
clearEveryGenerationIdempotencyKey(),
deleteNativePushRegistration(),
])
if (results.some((result) => result.status === 'rejected')) {
throw new AccountLocalDataPurgeError()
}
})().finally(() => {
if (purgeInFlight === operation) purgeInFlight = null
const run = previous === null
? runPurge(unsyncedWork)
: previous.promise.catch(() => undefined).then(() => runPurge(unsyncedWork))
const promise: Promise<void> = run.finally(() => {
if (purgeInFlight?.promise === promise) purgeInFlight = null
})
purgeInFlight = operation
return operation
purgeInFlight = { key, promise }
return promise
}

View file

@ -14,6 +14,8 @@ import { supabase, isSupabaseConfigured } from './supabase'
import { completeAuthRedirect, isAuthRedirectUrl } from './auth-redirect'
import { clearAllSecureAuthStorage } from './secure-auth-storage'
import { purgeAllAccountLocalData } from './account-local-data'
import { DISCARD_UNSYNCED_WORK, planAuthTransition } from './auth-transition-policy'
import { retainedAccountWork } from './retained-account-work'
export type AuthPrivacyCleanupState = 'ready' | 'purging' | 'failed'
@ -106,12 +108,19 @@ export function AuthProvider({ children }: { children: ReactNode }): React.React
): Promise<boolean> => {
const generation = ++transitionGenerationRef.current
const previousUserId = committedSessionRef.current?.user.id ?? null
const nextUserId = transition.session?.user.id ?? null
const needsPurge = transition.forcePurge
|| privacyCleanupStateRef.current !== 'ready'
|| (previousUserId !== null && previousUserId !== nextUserId)
const plan = planAuthTransition({
previousUserId,
nextUserId: transition.session?.user.id ?? null,
retainedOwnerUserId: retainedAccountWork.current(),
forcePurge: transition.forcePurge,
cleanupPending: privacyCleanupStateRef.current !== 'ready',
explicit: transition.explicit,
})
if (!needsPurge) {
if (!plan.purge) {
// The owner of work kept by an earlier session loss is back: the queue
// hook and Record screen resume it, so the retention marker can go.
if (plan.releaseRetainedWork) void retainedAccountWork.release().catch(() => undefined)
pendingTransitionRef.current = null
commitSession(transition.session, transition.event)
updatePrivacyCleanupState('ready')
@ -122,7 +131,7 @@ export function AuthProvider({ children }: { children: ReactNode }): React.React
updatePrivacyCleanupState('purging')
try {
await purgeAllAccountLocalData()
await purgeAllAccountLocalData(plan.unsyncedWork)
if (generation !== transitionGenerationRef.current) return false
if (transition.clearSecureAuth) {
@ -130,21 +139,31 @@ export function AuthProvider({ children }: { children: ReactNode }): React.React
// A SIGNED_OUT notification can race with a direct A -> B account
// replacement. Preserve a newer different-account session that the
// auth client has already committed to secure storage.
let replacementSession: Session | null = null
try {
const { data } = await supabase.auth.getSession()
if (generation !== transitionGenerationRef.current) return false
const latestSession = data.session
const latestUserId = latestSession?.user.id ?? null
if (latestSession !== null && latestUserId !== previousUserId) {
pendingTransitionRef.current = null
commitSession(latestSession, 'SIGNED_IN')
updatePrivacyCleanupState('ready')
return true
replacementSession = latestSession
}
} catch {
// If the auth client cannot prove that a newer session exists,
// fail closed by removing the signed-out account's secure data.
}
if (replacementSession !== null) {
if (plan.unsyncedWork.kind === 'retain') {
// Work kept for the signed-out account must not stay on a
// device that another account has already taken over.
await purgeAllAccountLocalData(DISCARD_UNSYNCED_WORK)
if (generation !== transitionGenerationRef.current) return false
}
pendingTransitionRef.current = null
commitSession(replacementSession, 'SIGNED_IN')
updatePrivacyCleanupState('ready')
return true
}
}
try {
@ -228,6 +247,9 @@ export function AuthProvider({ children }: { children: ReactNode }): React.React
}
try {
// The retained-work owner must be known before the first boundary
// decides between keeping and discarding unsynced recordings.
await retainedAccountWork.load().catch(() => null)
const initialUrl = await Linking.getInitialURL()
if (initialUrl !== null) await handleUrl(initialUrl)
const { data: { session: restoredSession }, error } = await supabase.auth.getSession()

View file

@ -6,22 +6,19 @@ export const AUTH_REDIRECT_URL = 'd3ro-voice://auth-callback'
export type AuthRedirectType = 'recovery' | 'signed-in' | 'cancelled' | 'ignored'
/**
* The only auth operation a callback may drive. A session is created solely by
* a PKCE code exchange, which the auth server binds to the code verifier this
* device stored when it started the flow.
*/
type AuthRedirectOperations = {
exchangeCodeForSession: typeof supabase.auth.exchangeCodeForSession
setSession: typeof supabase.auth.setSession
}
type ParsedAuthRedirect =
| { kind: 'ignored' }
| { kind: 'cancelled' }
| { kind: 'code'; code: string; recovery: boolean; replayKey: string }
| {
kind: 'tokens'
accessToken: string
refreshToken: string
recovery: boolean
replayKey: string
}
export class AuthRedirectError extends Error {
readonly code: 'invalid_callback' | 'provider_error'
@ -46,8 +43,8 @@ function hasAuthMaterial(parsedUrl: URL): boolean {
|| fragment.has('error_description')
}
function replayFingerprint(kind: 'code' | 'tokens', secret: string): string {
return `${kind}:${bytesToHex(sha256(utf8ToBytes(secret)))}`
function replayFingerprint(secret: string): string {
return `code:${bytesToHex(sha256(utf8ToBytes(secret)))}`
}
export function isAuthRedirectUrl(url: string): boolean {
@ -89,34 +86,23 @@ function parseAuthRedirect(url: string): ParsedAuthRedirect {
throw new AuthRedirectError('provider_error')
}
const code = query.get('code')
const accessToken = fragment.get('access_token')
const refreshToken = fragment.get('refresh_token')
const hasCode = typeof code === 'string' && code.length > 0
const hasAccessToken = typeof accessToken === 'string' && accessToken.length > 0
const hasRefreshToken = typeof refreshToken === 'string' && refreshToken.length > 0
// Implicit-flow session material (#access_token/#refresh_token) is never
// accepted. The client runs every flow as PKCE, so a legitimate callback
// carries only ?code=. A bare token pair is bound to nothing this device
// started: any web page or app could open it and sign the device into
// another account (login CSRF), which would also trigger the account-switch
// purge of this user's local data.
if (fragment.has('access_token') || fragment.has('refresh_token')) {
throw new AuthRedirectError('invalid_callback')
}
if (hasCode && (hasAccessToken || hasRefreshToken)) {
throw new AuthRedirectError('invalid_callback')
}
if (hasAccessToken !== hasRefreshToken) {
throw new AuthRedirectError('invalid_callback')
}
if (hasCode) {
const code = query.get('code')
if (typeof code === 'string' && code.length > 0) {
return {
kind: 'code',
code,
recovery: query.get('type') === 'recovery',
replayKey: replayFingerprint('code', code),
}
}
if (hasAccessToken && hasRefreshToken) {
return {
kind: 'tokens',
accessToken,
refreshToken,
recovery: fragment.get('type') === 'recovery',
replayKey: replayFingerprint('tokens', `${accessToken}\u0000${refreshToken}`),
replayKey: replayFingerprint(code),
}
}
return { kind: 'ignored' }
@ -146,21 +132,12 @@ export function createAuthRedirectHandler(
if (existing !== undefined) return existing
const operation = (async (): Promise<AuthRedirectType> => {
if (parsed.kind === 'code') {
const { data, error } = await auth.exchangeCodeForSession(parsed.code)
if (error !== null) throw error
const redirectData = data as typeof data & { redirectType?: string | null }
return parsed.recovery || redirectData.redirectType === 'recovery'
? 'recovery'
: 'signed-in'
}
const { error } = await auth.setSession({
access_token: parsed.accessToken,
refresh_token: parsed.refreshToken,
})
const { data, error } = await auth.exchangeCodeForSession(parsed.code)
if (error !== null) throw error
return parsed.recovery ? 'recovery' : 'signed-in'
const redirectData = data as typeof data & { redirectType?: string | null }
return parsed.recovery || redirectData.redirectType === 'recovery'
? 'recovery'
: 'signed-in'
})()
inFlight.set(parsed.replayKey, operation)

View file

@ -0,0 +1,69 @@
/**
* Pure policy for the mobile auth privacy boundary: given who was signed in,
* who is signing in, and whose unsynced work is parked on the device, decide
* whether local account data must be purged and what happens to the user's
* unsynced recordings (durable-queue items and the live capture file).
*
* Caches are always purged when the boundary runs. Unsynced work is different:
* it is the only copy of the user's audio, and queue items are already keyed
* by their owner, so it is kept across an involuntary session loss (a revoked
* refresh token, a password change on another device, a cold boot without a
* session) and deleted only when another account takes the device or the user
* signs out on purpose.
*/
export type UnsyncedWorkDisposition =
| { readonly kind: 'discard' }
| { readonly kind: 'retain'; readonly ownerUserId: string }
export const DISCARD_UNSYNCED_WORK: UnsyncedWorkDisposition = Object.freeze({ kind: 'discard' })
export interface AuthTransitionFacts {
/** Account whose session is currently committed to the UI. */
previousUserId: string | null
/** Account the transition would commit, or null for a signed-out state. */
nextUserId: string | null
/** Account whose unsynced work was kept by an earlier session loss. */
retainedOwnerUserId: string | null
/** The caller requires the boundary even for an unchanged account. */
forcePurge: boolean
/** An earlier boundary has not completed yet. */
cleanupPending: boolean
/** The user asked to sign out (logout, account deletion, device revoke). */
explicit: boolean
}
export type AuthTransitionPlan =
| {
readonly purge: false
/** The retained work's owner is back; the retention marker can go. */
readonly releaseRetainedWork: boolean
}
| { readonly purge: true; readonly unsyncedWork: UnsyncedWorkDisposition }
export function planAuthTransition(facts: AuthTransitionFacts): AuthTransitionPlan {
const workOwner = facts.previousUserId ?? facts.retainedOwnerUserId
const accountLeaves = facts.previousUserId !== null && facts.previousUserId !== facts.nextUserId
const otherAccountArrives = facts.nextUserId !== null
&& workOwner !== null
&& workOwner !== facts.nextUserId
if (!facts.forcePurge && !facts.cleanupPending && !accountLeaves && !otherAccountArrives) {
return {
purge: false,
releaseRetainedWork: facts.retainedOwnerUserId !== null
&& facts.retainedOwnerUserId === facts.nextUserId,
}
}
const involuntarySessionLoss = facts.nextUserId === null && !facts.explicit
if (involuntarySessionLoss && workOwner !== null) {
return { purge: true, unsyncedWork: { kind: 'retain', ownerUserId: workOwner } }
}
return { purge: true, unsyncedWork: DISCARD_UNSYNCED_WORK }
}
/** Stable key so concurrent boundaries with the same disposition share one run. */
export function unsyncedWorkDispositionKey(disposition: UnsyncedWorkDisposition): string {
return disposition.kind === 'retain' ? `retain:${disposition.ownerUserId}` : 'discard'
}

View file

@ -27,7 +27,12 @@ import {
type EntitlementSnapshot,
type MobileSubscriptionTier,
} from './entitlement-context'
import { supabase } from './supabase'
import {
invokeEdgeFunction,
readEdgeFunctionHttpFailure,
type EdgeFunctionFailure,
type EdgeFunctionHttpBody,
} from './edge-functions'
import { getMobileRuntimeConfig } from './native-config'
export const GOOGLE_PLAY_SUBSCRIPTION_IDS = [
@ -256,21 +261,37 @@ export async function restoreGooglePlayPurchaseSet(
return refreshed
}
async function functionErrorCode(candidate: unknown): Promise<string> {
if (candidate && typeof candidate === 'object' && 'context' in candidate) {
const context = (candidate as { context?: unknown }).context
if (context instanceof Response) {
try {
const body = await context.clone().json() as { error?: unknown }
if (typeof body.error === 'string') return body.error
} catch {
return 'purchase_verification_failed'
}
}
const DEFAULT_VERIFICATION_ERROR = 'purchase_verification_failed'
/**
* Billing Edge Functions put the machine code in `error`. Returns null when
* the body carries no usable code so callers fall back to the Error message.
*/
function billingCodeFromBody(body: EdgeFunctionHttpBody): string | null {
if (!body.readable || body.payload === null) return DEFAULT_VERIFICATION_ERROR
const payload = body.payload
if (typeof payload === 'object') {
const code = (payload as { error?: unknown }).error
if (typeof code === 'string') return code
}
return null
}
function errorMessageOrDefault(candidate: unknown): string {
return candidate instanceof Error && candidate.message
? candidate.message
: 'purchase_verification_failed'
: DEFAULT_VERIFICATION_ERROR
}
function billingFailureCode(failure: EdgeFunctionFailure): string {
const code = failure.body === null ? null : billingCodeFromBody(failure.body)
return code ?? errorMessageOrDefault(failure.cause)
}
async function functionErrorCode(candidate: unknown): Promise<string> {
const http = await readEdgeFunctionHttpFailure(candidate)
const code = http === null ? null : billingCodeFromBody(http.body)
return code ?? errorMessageOrDefault(candidate)
}
export function BillingProvider({ children }: { children: ReactNode }): React.ReactElement {
@ -306,14 +327,13 @@ export function BillingProvider({ children }: { children: ReactNode }): React.Re
setOperation(purchase.purchaseState === 'pending' ? 'pending' : 'verifying')
setErrorCode(null)
try {
const { data, error } = await supabase.functions.invoke<IapVerifyResult>('iap-verify', {
body: {
platform: 'google_play',
productId: purchase.productId,
purchaseToken: purchase.purchaseToken,
},
const result = await invokeEdgeFunction<IapVerifyResult>('iap-verify', {
platform: 'google_play',
productId: purchase.productId,
purchaseToken: purchase.purchaseToken,
})
if (error) throw new Error(await functionErrorCode(error))
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()
@ -509,14 +529,13 @@ export function BillingProvider({ children }: { children: ReactNode }): React.Re
restoredPurchases,
async (restoredPurchase) => {
if (userIdRef.current !== currentUserId) throw new Error('restore_session_changed')
const { data, error } = await supabase.functions.invoke<IapVerifyResult>('iap-verify', {
body: {
platform: 'google_play',
productId: restoredPurchase.productId,
purchaseToken: restoredPurchase.purchaseToken,
},
const result = await invokeEdgeFunction<IapVerifyResult>('iap-verify', {
platform: 'google_play',
productId: restoredPurchase.productId,
purchaseToken: restoredPurchase.purchaseToken,
})
if (error) throw new Error(await functionErrorCode(error))
if (!result.ok) throw new Error(billingFailureCode(result))
const data = result.data
return data
},
async () => {

View file

@ -0,0 +1,129 @@
// src/lib/edge-functions.ts — typed transport adapter for Supabase Edge Functions.
//
// functions-js returns `{ data: null, error: FunctionsHttpError }` for every
// non-2xx response and keeps the server's JSON body only inside
// `error.context` (a fetch Response). Callers must never inspect `data` to
// find a failure code. This adapter decodes that transport detail once so
// feature services only see a discriminated result.
//
// Edge functions do not share one error-body convention (team/billing put the
// code in `error`, account-delete puts it in `code` and a human string in
// `error`), so the adapter deliberately does NOT pick a code field. It hands
// back the parsed payload and each caller keeps its own field selection.
import { supabase } from './supabase'
/** Decoded body of a non-2xx Edge Function response. */
export type EdgeFunctionHttpBody =
| { readable: true; payload: unknown }
| { readable: false }
export interface EdgeFunctionHttpFailure {
status: number
body: EdgeFunctionHttpBody
}
export interface EdgeFunctionSuccess<T> {
ok: true
data: T | null
}
export interface EdgeFunctionFailure {
ok: false
/** HTTP status when the function responded; null for fetch/relay failures. */
status: number | null
/** Parsed response body when the function responded; null otherwise. */
body: EdgeFunctionHttpBody | null
/** Untranslated transport message. For diagnostics only, never for UI. */
message: string | null
/** The original SDK error (or thrown value), for callers that map it further. */
cause: unknown
}
export type EdgeFunctionResult<T> = EdgeFunctionSuccess<T> | EdgeFunctionFailure
/** Minimal port of the Supabase client this adapter depends on. */
export interface EdgeFunctionsClient {
functions: {
invoke(
name: string,
options: { body: Record<string, unknown> },
): Promise<{ data: unknown; error: unknown }>
}
}
/** Invocation port that feature services depend on instead of the SDK. */
export type EdgeFunctionInvoker = <T = unknown>(
name: string,
body: Record<string, unknown>,
) => Promise<EdgeFunctionResult<T>>
function errorMessage(error: unknown): string | null {
if (error instanceof Error) return error.message || null
if (typeof error === 'object' && error !== null && 'message' in error) {
const message = (error as { message?: unknown }).message
return typeof message === 'string' && message ? message : null
}
return null
}
/**
* Reads the HTTP response carried by a FunctionsHttpError. Returns null when
* the error has no Response context (fetch/relay errors, thrown values).
*/
export async function readEdgeFunctionHttpFailure(
error: unknown,
): Promise<EdgeFunctionHttpFailure | null> {
if (typeof error !== 'object' || error === null || !('context' in error)) return null
const context = (error as { context?: unknown }).context
if (!(context instanceof Response)) return null
try {
const payload: unknown = await context.clone().json()
return { status: context.status, body: { readable: true, payload } }
} catch {
return { status: context.status, body: { readable: false } }
}
}
/** Converts an SDK `{ data, error }` pair (or thrown value) into a typed result. */
export async function toEdgeFunctionResult<T>(
data: unknown,
error: unknown,
): Promise<EdgeFunctionResult<T>> {
if (error === null || error === undefined) {
return { ok: true, data: (data ?? null) as T | null }
}
const http = await readEdgeFunctionHttpFailure(error)
return {
ok: false,
status: http?.status ?? null,
body: http?.body ?? null,
message: errorMessage(error),
cause: error,
}
}
export async function invokeEdgeFunction<T = unknown>(
name: string,
body: Record<string, unknown>,
client: EdgeFunctionsClient = supabase,
): Promise<EdgeFunctionResult<T>> {
let response: { data: unknown; error: unknown }
try {
response = await client.functions.invoke(name, { body })
} catch (thrown) {
return toEdgeFunctionResult<T>(null, thrown ?? new Error('edge_function_invoke_failed'))
}
return toEdgeFunctionResult<T>(response.data, response.error)
}
/** Reads a string field from a decoded failure payload, if present. */
export function edgeFailureField(
failure: Pick<EdgeFunctionFailure, 'body'>,
field: string,
): string | null {
if (failure.body === null || !failure.body.readable) return null
const payload = failure.body.payload
if (typeof payload !== 'object' || payload === null || Array.isArray(payload)) return null
const value = (payload as Record<string, unknown>)[field]
return typeof value === 'string' ? value : null
}

View file

@ -0,0 +1,26 @@
/**
* Minimal scoped logger for the React Native app. It is the single sink that
* talks to the JS console (Metro / logcat / Xcode), so feature code never
* calls `console.*` directly and the output format stays consistent.
*/
export interface Logger {
info: (message: string, ...details: unknown[]) => void;
warn: (message: string, ...details: unknown[]) => void;
error: (message: string, ...details: unknown[]) => void;
}
type LogLevel = keyof Logger;
type ConsoleSink = Pick<Console, LogLevel>;
export function createLogger(scope: string, sink: ConsoleSink = console): Logger {
const prefix = `[${scope}]`;
const write = (level: LogLevel) => (message: string, ...details: unknown[]): void => {
sink[level](`${prefix} ${message}`, ...details);
};
return {
info: write('info'),
warn: write('warn'),
error: write('error'),
};
}

View file

@ -0,0 +1,81 @@
// Production adapters for the preferences store ports (AsyncStorage + Supabase).
import AsyncStorage from '@react-native-async-storage/async-storage'
import type { SupabaseClient } from '@supabase/supabase-js'
import { supabase } from './supabase'
import {
USER_SETTINGS_COLUMNS,
type PreferencesRemote,
type PreferencesStorage,
} from './preferences-store'
const UNIQUE_VIOLATION = '23505'
export const asyncStoragePreferencesStorage: PreferencesStorage = {
multiGet: (keys) => AsyncStorage.multiGet(keys),
setItem: (key, value) => AsyncStorage.setItem(key, value),
multiSet: (pairs) => AsyncStorage.multiSet(pairs),
getAllKeys: () => AsyncStorage.getAllKeys(),
multiRemove: (keys) => AsyncStorage.multiRemove(keys),
}
export function createSupabasePreferencesRemote(
client: SupabaseClient = supabase,
): PreferencesRemote {
return {
async fetchRow(userId) {
const { data, error } = await client
.from('user_settings')
.select(USER_SETTINGS_COLUMNS)
.eq('user_id', userId)
.maybeSingle()
if (error) throw error
return data
},
async insertRow(row) {
const { data, error } = await client
.from('user_settings')
.insert(row)
.select(USER_SETTINGS_COLUMNS)
.single()
if (error?.code === UNIQUE_VIOLATION) return { status: 'duplicate' }
if (error) throw error
return { status: 'inserted', row: data }
},
async updateRowAtRevision(row, expectedRevision) {
const { data, error } = await client
.from('user_settings')
.update(row)
.eq('user_id', row.user_id)
.eq('revision', expectedRevision)
.select(USER_SETTINGS_COLUMNS)
.maybeSingle()
if (error) throw error
return data
},
}
}
/** Subscribes to UPDATEs of the user's settings row; returns an unsubscribe function. */
export function subscribeToUserSettingsChanges(
userId: string,
onRow: (row: unknown) => void,
client: SupabaseClient = supabase,
): () => void {
const channel = client
.channel(`mobile-user-settings-${userId}`)
.on(
'postgres_changes',
{
event: 'UPDATE',
schema: 'public',
table: 'user_settings',
filter: `user_id=eq.${userId}`,
},
(payload) => onRow(payload.new),
)
.subscribe()
return () => {
void client.removeChannel(channel)
}
}

View file

@ -1,4 +1,3 @@
import AsyncStorage from '@react-native-async-storage/async-storage'
import {
AppState,
useColorScheme,
@ -9,84 +8,49 @@ import {
useContext,
useEffect,
useMemo,
useRef,
useState,
useSyncExternalStore,
} from 'react'
import type { ReactNode } from 'react'
import { useAuth } from './auth-context'
import { supabase } from './supabase'
import {
asyncStoragePreferencesStorage,
createSupabasePreferencesRemote,
subscribeToUserSettingsChanges,
} from './preferences-adapters'
import {
CURRENT_ONBOARDING_VERSION,
clearUserPreferenceCaches,
createPreferencesStore,
preferencesOwnerFor,
type MobilePreferences,
type MobilePreferencesPatch,
type PreferenceMutationResult,
type PreferencesErrorCode,
type PreferencesStore,
type PreferencesSyncStatus,
} from './preferences-store'
import {
getMobileThemePalette,
isMobileThemeMode,
resolveEffectiveTheme,
type EffectiveMobileTheme,
type MobileThemeMode,
type MobileThemePalette,
} from '../theme/mobile-theme'
export const CURRENT_ONBOARDING_VERSION = 1
const CACHE_SCHEMA_VERSION = 1
const INSTALLATION_CACHE_KEY = '@d3ro/mobile/preferences/installation-v1'
const USER_CACHE_PREFIX = '@d3ro/mobile/preferences/user-v1/'
const USER_SETTINGS_COLUMNS = [
'user_id',
'theme_mode',
'locale',
'haptic_enabled',
'auto_polish_enabled',
'preferred_stt_model',
'preferred_llm_model',
'onboarding_version',
'tutorial_completed_at',
'revision',
'updated_at',
].join(',')
export type SupportedMobileLocale = 'ko' | 'en'
export type PreferencesSyncStatus =
| 'loading'
| 'local'
| 'saving'
| 'synced'
| 'offline'
| 'error'
export type PreferencesErrorCode =
| 'CACHE_READ_FAILED'
| 'CACHE_WRITE_FAILED'
| 'SYNC_FAILED'
| 'SYNC_CONFLICT'
export interface MobilePreferences {
themeMode: MobileThemeMode
locale: SupportedMobileLocale
hapticEnabled: boolean
autoPolishEnabled: boolean
preferredSttModel: string | null
preferredLlmModel: string | null
onboardingVersion: number
tutorialCompletedAt: string | null
revision: number
updatedAt: string | null
}
export type MobilePreferencesPatch = Partial<Pick<
export {
CURRENT_ONBOARDING_VERSION,
applyPreferencesPatch,
normalizePreferences,
normalizePreferencesPatch,
} from './preferences-store'
export type {
MobilePreferences,
| 'themeMode'
| 'locale'
| 'hapticEnabled'
| 'autoPolishEnabled'
| 'preferredSttModel'
| 'preferredLlmModel'
| 'onboardingVersion'
| 'tutorialCompletedAt'
>>
export interface PreferenceMutationResult {
localSaved: boolean
serverSynced: boolean
}
MobilePreferencesPatch,
PreferenceMutationResult,
PreferencesErrorCode,
PreferencesSyncStatus,
SupportedMobileLocale,
} from './preferences-store'
interface PreferencesContextValue {
preferences: MobilePreferences
@ -104,758 +68,70 @@ interface PreferencesContextValue {
retrySync: () => Promise<void>
}
interface CacheEnvelope {
schemaVersion: number
preferences: MobilePreferences
pendingPatch: MobilePreferencesPatch
lastSyncedAt: string | null
}
interface SettingsRow {
user_id: string
theme_mode: unknown
locale: unknown
haptic_enabled: unknown
auto_polish_enabled: unknown
preferred_stt_model: unknown
preferred_llm_model: unknown
onboarding_version: unknown
tutorial_completed_at: unknown
revision: unknown
updated_at: unknown
}
interface ProviderSnapshot {
ownerKey: string
preferences: MobilePreferences
loading: boolean
syncStatus: PreferencesSyncStatus
errorCode: PreferencesErrorCode | null
lastSyncedAt: string | null
}
const DEFAULT_PREFERENCES: MobilePreferences = Object.freeze({
themeMode: 'system',
locale: 'ko',
hapticEnabled: true,
autoPolishEnabled: true,
preferredSttModel: null,
preferredLlmModel: null,
onboardingVersion: 0,
tutorialCompletedAt: null,
revision: 1,
updatedAt: null,
})
const PreferencesContext = createContext<PreferencesContextValue | null>(null)
export async function clearAllUserPreferenceCaches(): Promise<void> {
const keys = await AsyncStorage.getAllKeys()
const userKeys = keys.filter((key) => key.startsWith(USER_CACHE_PREFIX))
if (userKeys.length > 0) await AsyncStorage.multiRemove(userKeys)
export function clearAllUserPreferenceCaches(): Promise<void> {
return clearUserPreferenceCaches(asyncStoragePreferencesStorage)
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value)
}
function normalizeLocale(value: unknown): SupportedMobileLocale {
return value === 'en' ? 'en' : 'ko'
}
function normalizeNullableString(value: unknown): string | null {
return typeof value === 'string' && value.trim().length > 0
? value.trim()
: null
}
function normalizeNonNegativeInteger(value: unknown, fallback: number): number {
const numeric = typeof value === 'number' ? value : Number(value)
return Number.isSafeInteger(numeric) && numeric >= 0 ? numeric : fallback
}
function normalizePositiveInteger(value: unknown, fallback: number): number {
const numeric = typeof value === 'number' ? value : Number(value)
return Number.isSafeInteger(numeric) && numeric > 0 ? numeric : fallback
}
function normalizeIsoDate(value: unknown): string | null {
if (typeof value !== 'string') return null
const timestamp = Date.parse(value)
return Number.isFinite(timestamp) ? new Date(timestamp).toISOString() : null
}
export function normalizePreferences(
value: unknown,
fallback: MobilePreferences = DEFAULT_PREFERENCES,
): MobilePreferences {
if (!isRecord(value)) return { ...fallback }
return {
themeMode: isMobileThemeMode(value.themeMode) ? value.themeMode : fallback.themeMode,
locale: normalizeLocale(value.locale ?? fallback.locale),
hapticEnabled: typeof value.hapticEnabled === 'boolean'
? value.hapticEnabled
: fallback.hapticEnabled,
autoPolishEnabled: typeof value.autoPolishEnabled === 'boolean'
? value.autoPolishEnabled
: fallback.autoPolishEnabled,
preferredSttModel: value.preferredSttModel === undefined
? fallback.preferredSttModel
: normalizeNullableString(value.preferredSttModel),
preferredLlmModel: value.preferredLlmModel === undefined
? fallback.preferredLlmModel
: normalizeNullableString(value.preferredLlmModel),
onboardingVersion: normalizeNonNegativeInteger(
value.onboardingVersion,
fallback.onboardingVersion,
),
tutorialCompletedAt: value.tutorialCompletedAt === undefined
? fallback.tutorialCompletedAt
: normalizeIsoDate(value.tutorialCompletedAt),
revision: normalizePositiveInteger(value.revision, fallback.revision),
updatedAt: value.updatedAt === undefined
? fallback.updatedAt
: normalizeIsoDate(value.updatedAt),
}
}
export function normalizePreferencesPatch(value: unknown): MobilePreferencesPatch {
if (!isRecord(value)) return {}
const patch: MobilePreferencesPatch = {}
if (isMobileThemeMode(value.themeMode)) patch.themeMode = value.themeMode
if (value.locale === 'ko' || value.locale === 'en') patch.locale = value.locale
if (typeof value.hapticEnabled === 'boolean') patch.hapticEnabled = value.hapticEnabled
if (typeof value.autoPolishEnabled === 'boolean') {
patch.autoPolishEnabled = value.autoPolishEnabled
}
if (value.preferredSttModel === null || typeof value.preferredSttModel === 'string') {
patch.preferredSttModel = normalizeNullableString(value.preferredSttModel)
}
if (value.preferredLlmModel === null || typeof value.preferredLlmModel === 'string') {
patch.preferredLlmModel = normalizeNullableString(value.preferredLlmModel)
}
if (value.onboardingVersion !== undefined) {
patch.onboardingVersion = normalizeNonNegativeInteger(value.onboardingVersion, 0)
}
if (value.tutorialCompletedAt === null || typeof value.tutorialCompletedAt === 'string') {
patch.tutorialCompletedAt = normalizeIsoDate(value.tutorialCompletedAt)
}
return patch
}
export function applyPreferencesPatch(
preferences: MobilePreferences,
patch: MobilePreferencesPatch,
): MobilePreferences {
return normalizePreferences({ ...preferences, ...normalizePreferencesPatch(patch) }, preferences)
}
function parseSettingsRow(value: unknown): MobilePreferences | null {
if (!isRecord(value) || typeof value.user_id !== 'string') return null
const row = value as unknown as SettingsRow
return normalizePreferences({
themeMode: row.theme_mode,
locale: row.locale,
hapticEnabled: row.haptic_enabled,
autoPolishEnabled: row.auto_polish_enabled,
preferredSttModel: row.preferred_stt_model,
preferredLlmModel: row.preferred_llm_model,
onboardingVersion: row.onboarding_version,
tutorialCompletedAt: row.tutorial_completed_at,
revision: row.revision,
updatedAt: row.updated_at,
function createDefaultStore(): PreferencesStore {
return createPreferencesStore({
storage: asyncStoragePreferencesStorage,
remote: createSupabasePreferencesRemote(),
})
}
function parseCacheEnvelope(raw: string | null): CacheEnvelope | null {
if (raw === null) return null
const parsed: unknown = JSON.parse(raw)
if (!isRecord(parsed) || parsed.schemaVersion !== CACHE_SCHEMA_VERSION) {
throw new Error('Unsupported mobile preferences cache schema')
}
return {
schemaVersion: CACHE_SCHEMA_VERSION,
preferences: normalizePreferences(parsed.preferences),
pendingPatch: normalizePreferencesPatch(parsed.pendingPatch),
lastSyncedAt: normalizeIsoDate(parsed.lastSyncedAt),
}
}
function createEnvelope(
preferences: MobilePreferences,
pendingPatch: MobilePreferencesPatch,
lastSyncedAt: string | null,
): CacheEnvelope {
return {
schemaVersion: CACHE_SCHEMA_VERSION,
preferences,
pendingPatch: normalizePreferencesPatch(pendingPatch),
lastSyncedAt,
}
}
function toInstallationPreferences(
preferences: MobilePreferences,
): MobilePreferences {
return {
...DEFAULT_PREFERENCES,
themeMode: preferences.themeMode,
locale: preferences.locale,
hapticEnabled: preferences.hapticEnabled,
onboardingVersion: preferences.onboardingVersion,
tutorialCompletedAt: preferences.tutorialCompletedAt,
}
}
function getUserCacheKey(userId: string): string {
return `${USER_CACHE_PREFIX}${userId}`
}
function serializeEnvelope(envelope: CacheEnvelope): string {
return JSON.stringify(envelope)
}
async function writeCaches(
userId: string | null,
preferences: MobilePreferences,
userPendingPatch: MobilePreferencesPatch,
lastSyncedAt: string | null,
installationPendingPatch: MobilePreferencesPatch = {},
): Promise<void> {
const installationEnvelope = createEnvelope(
toInstallationPreferences(preferences),
installationPendingPatch,
lastSyncedAt,
)
if (userId === null) {
await AsyncStorage.setItem(
INSTALLATION_CACHE_KEY,
serializeEnvelope(installationEnvelope),
)
return
}
const userEnvelope = createEnvelope(
preferences,
userPendingPatch,
lastSyncedAt,
)
await AsyncStorage.multiSet([
[INSTALLATION_CACHE_KEY, serializeEnvelope(installationEnvelope)],
[getUserCacheKey(userId), serializeEnvelope(userEnvelope)],
])
}
function toRowMutation(
userId: string,
preferences: MobilePreferences,
): Record<string, unknown> {
return {
user_id: userId,
theme_mode: preferences.themeMode,
locale: preferences.locale,
haptic_enabled: preferences.hapticEnabled,
auto_polish_enabled: preferences.autoPolishEnabled,
preferred_stt_model: preferences.preferredSttModel,
preferred_llm_model: preferences.preferredLlmModel,
onboarding_version: preferences.onboardingVersion,
tutorial_completed_at: preferences.tutorialCompletedAt,
revision: preferences.revision,
}
}
async function fetchServerPreferences(userId: string): Promise<MobilePreferences | null> {
const { data, error } = await supabase
.from('user_settings')
.select(USER_SETTINGS_COLUMNS)
.eq('user_id', userId)
.maybeSingle()
if (error) throw error
return parseSettingsRow(data)
}
async function writeServerPreferences(
userId: string,
fallback: MobilePreferences,
patch: MobilePreferencesPatch,
): Promise<MobilePreferences> {
for (let attempt = 0; attempt < 3; attempt += 1) {
const remote = await fetchServerPreferences(userId)
if (remote === null) {
const desired = applyPreferencesPatch(fallback, patch)
const insertValue: MobilePreferences = {
...desired,
revision: Math.max(1, desired.revision),
}
const { data, error } = await supabase
.from('user_settings')
.insert(toRowMutation(userId, insertValue))
.select(USER_SETTINGS_COLUMNS)
.single()
if (error?.code === '23505') continue
if (error) throw error
const inserted = parseSettingsRow(data)
if (inserted === null) throw new Error('Invalid user settings insert response')
return inserted
}
const desired: MobilePreferences = {
...applyPreferencesPatch(remote, patch),
revision: remote.revision + 1,
}
const { data, error } = await supabase
.from('user_settings')
.update(toRowMutation(userId, desired))
.eq('user_id', userId)
.eq('revision', remote.revision)
.select(USER_SETTINGS_COLUMNS)
.maybeSingle()
if (error) throw error
const updated = parseSettingsRow(data)
if (updated !== null) return updated
}
const conflict = new Error('User settings changed repeatedly on another device')
conflict.name = 'PreferencesSyncConflictError'
throw conflict
}
function isPatchEmpty(patch: MobilePreferencesPatch): boolean {
return Object.keys(patch).length === 0
}
function removeCommittedPatch(
current: MobilePreferencesPatch,
committed: MobilePreferencesPatch,
): MobilePreferencesPatch {
const remaining: MobilePreferencesPatch = { ...current }
for (const key of Object.keys(committed) as Array<keyof MobilePreferencesPatch>) {
if (remaining[key] === committed[key]) {
delete remaining[key]
}
}
return remaining
}
function errorCodeForSync(error: unknown): PreferencesErrorCode {
return error instanceof Error && error.name === 'PreferencesSyncConflictError'
? 'SYNC_CONFLICT'
: 'SYNC_FAILED'
}
export function MobilePreferencesProvider({
children,
store: injectedStore,
}: {
children: ReactNode
/** Test seam: defaults to the AsyncStorage + Supabase backed store. */
store?: PreferencesStore
}): React.ReactElement {
const { user } = useAuth()
const systemScheme = useColorScheme()
const userId = user?.id ?? null
const ownerKey = userId === null ? 'installation' : `user:${userId}`
const ownerKey = preferencesOwnerFor(userId).ownerKey
const [snapshot, setSnapshot] = useState<ProviderSnapshot>({
ownerKey: 'uninitialized',
preferences: { ...DEFAULT_PREFERENCES },
loading: true,
syncStatus: 'loading',
errorCode: null,
lastSyncedAt: null,
})
const ownerKeyRef = useRef(ownerKey)
const userIdRef = useRef<string | null>(userId)
const preferencesRef = useRef<MobilePreferences>({ ...DEFAULT_PREFERENCES })
const pendingPatchRef = useRef<MobilePreferencesPatch>({})
const lastSyncedAtRef = useRef<string | null>(null)
const loadGenerationRef = useRef(0)
const serverQueueRef = useRef<Promise<void>>(Promise.resolve())
const localQueueRef = useRef<Promise<void>>(Promise.resolve())
ownerKeyRef.current = ownerKey
userIdRef.current = userId
const flushPendingPatch = useCallback(async (targetUserId: string): Promise<boolean> => {
if (userIdRef.current !== targetUserId) return false
const committedPatch = { ...pendingPatchRef.current }
if (isPatchEmpty(committedPatch)) return true
setSnapshot((current) => current.ownerKey === `user:${targetUserId}`
? { ...current, syncStatus: 'saving', errorCode: null }
: current)
try {
const saved = await writeServerPreferences(
targetUserId,
preferencesRef.current,
committedPatch,
)
if (userIdRef.current !== targetUserId) return false
const remainingPatch = removeCommittedPatch(
pendingPatchRef.current,
committedPatch,
)
const nextPreferences = applyPreferencesPatch(saved, remainingPatch)
const syncedAt = new Date().toISOString()
preferencesRef.current = nextPreferences
pendingPatchRef.current = remainingPatch
lastSyncedAtRef.current = syncedAt
try {
await writeCaches(
targetUserId,
nextPreferences,
remainingPatch,
syncedAt,
)
setSnapshot({
ownerKey: `user:${targetUserId}`,
preferences: nextPreferences,
loading: false,
syncStatus: isPatchEmpty(remainingPatch) ? 'synced' : 'saving',
errorCode: null,
lastSyncedAt: syncedAt,
})
} catch {
setSnapshot({
ownerKey: `user:${targetUserId}`,
preferences: nextPreferences,
loading: false,
syncStatus: 'error',
errorCode: 'CACHE_WRITE_FAILED',
lastSyncedAt: syncedAt,
})
}
return isPatchEmpty(remainingPatch)
} catch (error) {
if (userIdRef.current !== targetUserId) return false
setSnapshot((current) => current.ownerKey === `user:${targetUserId}`
? {
...current,
loading: false,
syncStatus: 'offline',
errorCode: errorCodeForSync(error),
}
: current)
return false
}
}, [])
const queueServerFlush = useCallback((targetUserId: string): Promise<boolean> => {
const run = serverQueueRef.current.then(
() => flushPendingPatch(targetUserId),
() => flushPendingPatch(targetUserId),
)
serverQueueRef.current = run.then(() => undefined, () => undefined)
return run
}, [flushPendingPatch])
const loadPreferences = useCallback(async (
targetOwnerKey: string,
targetUserId: string | null,
): Promise<void> => {
const generation = ++loadGenerationRef.current
setSnapshot((current) => ({
...current,
ownerKey: targetOwnerKey,
loading: true,
syncStatus: 'loading',
errorCode: null,
}))
let installationEnvelope: CacheEnvelope | null = null
let userEnvelope: CacheEnvelope | null = null
let cacheReadFailed = false
let cacheWriteFailed = false
try {
const keys = targetUserId === null
? [INSTALLATION_CACHE_KEY]
: [INSTALLATION_CACHE_KEY, getUserCacheKey(targetUserId)]
const entries = await AsyncStorage.multiGet(keys)
installationEnvelope = parseCacheEnvelope(entries[0]?.[1] ?? null)
if (targetUserId !== null) {
userEnvelope = parseCacheEnvelope(entries[1]?.[1] ?? null)
}
} catch {
cacheReadFailed = true
}
if (generation !== loadGenerationRef.current || ownerKeyRef.current !== targetOwnerKey) {
return
}
if (targetUserId === null) {
const localPreferences = installationEnvelope?.preferences ?? { ...DEFAULT_PREFERENCES }
const localPending = installationEnvelope?.pendingPatch ?? {}
preferencesRef.current = localPreferences
pendingPatchRef.current = localPending
lastSyncedAtRef.current = installationEnvelope?.lastSyncedAt ?? null
setSnapshot({
ownerKey: targetOwnerKey,
preferences: localPreferences,
loading: false,
syncStatus: cacheReadFailed ? 'error' : 'local',
errorCode: cacheReadFailed ? 'CACHE_READ_FAILED' : null,
lastSyncedAt: installationEnvelope?.lastSyncedAt ?? null,
})
return
}
const cachedPreferences = userEnvelope?.preferences
?? installationEnvelope?.preferences
?? { ...DEFAULT_PREFERENCES }
const stagedPatch: MobilePreferencesPatch = {
...(userEnvelope?.pendingPatch ?? {}),
...(installationEnvelope?.pendingPatch ?? {}),
}
const cachedWithPending = applyPreferencesPatch(cachedPreferences, stagedPatch)
preferencesRef.current = cachedWithPending
pendingPatchRef.current = stagedPatch
lastSyncedAtRef.current = userEnvelope?.lastSyncedAt
?? installationEnvelope?.lastSyncedAt
?? null
setSnapshot({
ownerKey: targetOwnerKey,
preferences: cachedWithPending,
loading: false,
syncStatus: 'loading',
errorCode: cacheReadFailed ? 'CACHE_READ_FAILED' : null,
lastSyncedAt: userEnvelope?.lastSyncedAt ?? installationEnvelope?.lastSyncedAt ?? null,
})
try {
await writeCaches(
targetUserId,
cachedWithPending,
stagedPatch,
userEnvelope?.lastSyncedAt ?? null,
)
} catch {
cacheWriteFailed = true
}
let resolved: MobilePreferences
try {
const remote = await fetchServerPreferences(targetUserId)
if (remote === null || !isPatchEmpty(stagedPatch)) {
resolved = await writeServerPreferences(
targetUserId,
remote ?? cachedWithPending,
stagedPatch,
)
} else {
resolved = remote
}
if (generation !== loadGenerationRef.current || ownerKeyRef.current !== targetOwnerKey) {
return
}
} catch (error) {
if (generation !== loadGenerationRef.current || ownerKeyRef.current !== targetOwnerKey) {
return
}
setSnapshot({
ownerKey: targetOwnerKey,
preferences: cachedWithPending,
loading: false,
syncStatus: 'offline',
errorCode: cacheReadFailed
? 'CACHE_READ_FAILED'
: cacheWriteFailed
? 'CACHE_WRITE_FAILED'
: errorCodeForSync(error),
lastSyncedAt: userEnvelope?.lastSyncedAt ?? installationEnvelope?.lastSyncedAt ?? null,
})
return
}
if (generation !== loadGenerationRef.current || ownerKeyRef.current !== targetOwnerKey) {
return
}
const syncedAt = new Date().toISOString()
try {
await writeCaches(targetUserId, resolved, {}, syncedAt)
} catch {
cacheWriteFailed = true
}
preferencesRef.current = resolved
pendingPatchRef.current = {}
lastSyncedAtRef.current = syncedAt
setSnapshot({
ownerKey: targetOwnerKey,
preferences: resolved,
loading: false,
syncStatus: cacheReadFailed || cacheWriteFailed ? 'error' : 'synced',
errorCode: cacheReadFailed
? 'CACHE_READ_FAILED'
: cacheWriteFailed
? 'CACHE_WRITE_FAILED'
: null,
lastSyncedAt: syncedAt,
})
}, [])
const [store] = useState<PreferencesStore>(() => injectedStore ?? createDefaultStore())
const snapshot = useSyncExternalStore(store.subscribe, store.getSnapshot)
// Owner change → first load (the store alone decides initial vs background).
useEffect(() => {
void loadPreferences(ownerKey, userId)
}, [loadPreferences, ownerKey, userId])
void store.load(preferencesOwnerFor(userId))
}, [store, userId])
// Realtime rows from other devices.
useEffect(() => {
if (userId === null) return undefined
return subscribeToUserSettingsChanges(userId, (row) => {
store.applyRemote(userId, row)
})
}, [store, userId])
const channel = supabase
.channel(`mobile-user-settings-${userId}`)
.on(
'postgres_changes',
{
event: 'UPDATE',
schema: 'public',
table: 'user_settings',
filter: `user_id=eq.${userId}`,
},
(payload) => {
if (userIdRef.current !== userId || !isPatchEmpty(pendingPatchRef.current)) return
const remote = parseSettingsRow(payload.new)
if (remote === null) return
// Foreground → background resync; never re-enters the initial-loading phase.
useEffect(() => {
const subscription = AppState.addEventListener('change', (state) => {
if (state !== 'active' || !store.needsForegroundResync()) return
void store.resync()
})
return () => subscription.remove()
}, [store])
const syncedAt = new Date().toISOString()
preferencesRef.current = remote
lastSyncedAtRef.current = syncedAt
setSnapshot({
ownerKey: `user:${userId}`,
preferences: remote,
loading: false,
syncStatus: 'synced',
errorCode: null,
lastSyncedAt: syncedAt,
})
void writeCaches(userId, remote, {}, syncedAt).catch(() => {
if (userIdRef.current !== userId) return
setSnapshot((current) => ({
...current,
syncStatus: 'error',
errorCode: 'CACHE_WRITE_FAILED',
}))
})
},
)
.subscribe()
return () => {
void supabase.removeChannel(channel)
}
}, [userId])
const commitPatch = useCallback(async (
requestedPatch: MobilePreferencesPatch,
): Promise<PreferenceMutationResult> => {
const targetOwnerKey = ownerKeyRef.current
const targetUserId = userIdRef.current
const patch = normalizePreferencesPatch(requestedPatch)
if (isPatchEmpty(patch)) {
return {
localSaved: true,
serverSynced: targetUserId === null || isPatchEmpty(pendingPatchRef.current),
}
}
const nextPreferences = applyPreferencesPatch(preferencesRef.current, patch)
const nextPendingPatch = {
...pendingPatchRef.current,
...patch,
}
try {
await writeCaches(
targetUserId,
nextPreferences,
nextPendingPatch,
lastSyncedAtRef.current,
targetUserId === null ? nextPendingPatch : {},
)
} catch {
if (ownerKeyRef.current === targetOwnerKey) {
setSnapshot((current) => ({
...current,
syncStatus: 'error',
errorCode: 'CACHE_WRITE_FAILED',
}))
}
return { localSaved: false, serverSynced: false }
}
if (ownerKeyRef.current !== targetOwnerKey) {
return { localSaved: true, serverSynced: false }
}
preferencesRef.current = nextPreferences
pendingPatchRef.current = nextPendingPatch
setSnapshot((current) => ({
...current,
ownerKey: targetOwnerKey,
preferences: nextPreferences,
loading: false,
syncStatus: targetUserId === null ? 'local' : 'saving',
errorCode: null,
}))
if (targetUserId === null) {
return { localSaved: true, serverSynced: false }
}
const serverSynced = await queueServerFlush(targetUserId)
return { localSaved: true, serverSynced }
}, [queueServerFlush])
const updatePreferences = useCallback((
patch: MobilePreferencesPatch,
): Promise<PreferenceMutationResult> => {
const run = localQueueRef.current.then(
() => commitPatch(patch),
() => commitPatch(patch),
)
localQueueRef.current = run.then(() => undefined, () => undefined)
return run
}, [commitPatch])
const updatePreferences = useCallback(
(patch: MobilePreferencesPatch): Promise<PreferenceMutationResult> => store.commit(patch),
[store],
)
const completeOnboarding = useCallback((
outcome: 'completed' | 'skipped',
): Promise<PreferenceMutationResult> => updatePreferences({
): Promise<PreferenceMutationResult> => store.commit({
onboardingVersion: CURRENT_ONBOARDING_VERSION,
tutorialCompletedAt: outcome === 'completed' ? new Date().toISOString() : null,
}), [updatePreferences])
}), [store])
const retrySync = useCallback(async (): Promise<void> => {
const targetOwnerKey = ownerKeyRef.current
const targetUserId = userIdRef.current
if (targetUserId !== null && !isPatchEmpty(pendingPatchRef.current)) {
await queueServerFlush(targetUserId)
return
}
await loadPreferences(targetOwnerKey, targetUserId)
}, [loadPreferences, queueServerFlush])
useEffect(() => {
const subscription = AppState.addEventListener('change', (state) => {
if (state !== 'active' || userIdRef.current === null) return
if (isPatchEmpty(pendingPatchRef.current) && snapshot.syncStatus !== 'offline') return
void retrySync()
})
return () => subscription.remove()
}, [retrySync, snapshot.syncStatus])
const retrySync = useCallback((): Promise<void> => store.resync(), [store])
const effectiveTheme = resolveEffectiveTheme(
snapshot.preferences.themeMode,
@ -865,7 +141,7 @@ export function MobilePreferencesProvider({
() => getMobileThemePalette(effectiveTheme),
[effectiveTheme],
)
const loading = snapshot.loading || snapshot.ownerKey !== ownerKey
const loading = snapshot.phase === 'initial-loading' || snapshot.ownerKey !== ownerKey
const contextValue = useMemo<PreferencesContextValue>(() => ({
preferences: snapshot.preferences,

View file

@ -0,0 +1,898 @@
// Mobile preferences store — framework-free sync core.
//
// Owns the cache envelope codec, pending-patch bookkeeping, the revision-checked
// server writer and the owner/generation guards. IO is injected through the
// PreferencesStorage and PreferencesRemote ports so the whole sync flow can be
// unit-tested without React, AsyncStorage or Supabase. The React provider only
// subscribes to snapshots and forwards triggers (owner change, foreground,
// realtime rows, Settings retry).
import { isMobileThemeMode, type MobileThemeMode } from '../theme/mobile-theme'
export const CURRENT_ONBOARDING_VERSION = 1
const CACHE_SCHEMA_VERSION = 1
export const INSTALLATION_CACHE_KEY = '@d3ro/mobile/preferences/installation-v1'
export const USER_CACHE_PREFIX = '@d3ro/mobile/preferences/user-v1/'
export const USER_SETTINGS_COLUMNS = [
'user_id',
'theme_mode',
'locale',
'haptic_enabled',
'auto_polish_enabled',
'preferred_stt_model',
'preferred_llm_model',
'onboarding_version',
'tutorial_completed_at',
'revision',
'updated_at',
].join(',')
const MAX_WRITE_ATTEMPTS = 3
export type SupportedMobileLocale = 'ko' | 'en'
export type PreferencesSyncStatus =
| 'loading'
| 'local'
| 'saving'
| 'synced'
| 'offline'
| 'error'
export type PreferencesErrorCode =
| 'CACHE_READ_FAILED'
| 'CACHE_WRITE_FAILED'
| 'SYNC_FAILED'
| 'SYNC_CONFLICT'
export interface MobilePreferences {
themeMode: MobileThemeMode
locale: SupportedMobileLocale
hapticEnabled: boolean
autoPolishEnabled: boolean
preferredSttModel: string | null
preferredLlmModel: string | null
onboardingVersion: number
tutorialCompletedAt: string | null
revision: number
updatedAt: string | null
}
export type MobilePreferencesPatch = Partial<Pick<
MobilePreferences,
| 'themeMode'
| 'locale'
| 'hapticEnabled'
| 'autoPolishEnabled'
| 'preferredSttModel'
| 'preferredLlmModel'
| 'onboardingVersion'
| 'tutorialCompletedAt'
>>
export interface PreferenceMutationResult {
localSaved: boolean
serverSynced: boolean
}
/**
* 'initial-loading' is entered only when the store starts serving a new owner.
* Background resyncs of an already-loaded owner keep the phase at 'ready' so
* the app tree that depends on preferences never unmounts.
*/
export type PreferencesPhase = 'initial-loading' | 'ready'
export interface PreferencesOwner {
ownerKey: string
userId: string | null
}
export interface PreferencesStoreSnapshot {
readonly ownerKey: string
readonly phase: PreferencesPhase
readonly preferences: MobilePreferences
readonly syncStatus: PreferencesSyncStatus
readonly errorCode: PreferencesErrorCode | null
readonly lastSyncedAt: string | null
}
export type UserSettingsRowMutation = {
user_id: string
theme_mode: MobileThemeMode
locale: SupportedMobileLocale
haptic_enabled: boolean
auto_polish_enabled: boolean
preferred_stt_model: string | null
preferred_llm_model: string | null
onboarding_version: number
tutorial_completed_at: string | null
revision: number
}
/** Local key-value persistence port (AsyncStorage in production). */
export interface PreferencesStorage {
multiGet(keys: readonly string[]): Promise<ReadonlyArray<readonly [string, string | null]>>
setItem(key: string, value: string): Promise<void>
multiSet(pairs: Array<[string, string]>): Promise<void>
getAllKeys(): Promise<readonly string[]>
multiRemove(keys: readonly string[]): Promise<void>
}
export type RemoteInsertResult =
| { status: 'inserted', row: unknown }
| { status: 'duplicate' }
/** user_settings persistence port (Supabase in production). Every method throws on failure. */
export interface PreferencesRemote {
/** Returns the raw row, or null when the user has no settings row yet. */
fetchRow(userId: string): Promise<unknown>
/** Inserts a row; a unique-violation race is reported as 'duplicate'. */
insertRow(row: UserSettingsRowMutation): Promise<RemoteInsertResult>
/** Updates only when the stored revision still equals expectedRevision; null otherwise. */
updateRowAtRevision(row: UserSettingsRowMutation, expectedRevision: number): Promise<unknown>
}
export interface PreferencesStoreDeps {
storage: PreferencesStorage
remote: PreferencesRemote
now?: () => string
}
export interface PreferencesStore {
getSnapshot(): PreferencesStoreSnapshot
subscribe(listener: () => void): () => void
/** Switches to (or re-reads) an owner. Only an owner change enters 'initial-loading'. */
load(owner: PreferencesOwner): Promise<void>
/** Background resync of the current owner. Never re-enters 'initial-loading'. */
resync(): Promise<void>
/** Whether returning to the foreground should trigger resync(). */
needsForegroundResync(): boolean
/** Serialized local-first commit followed by a server flush for signed-in owners. */
commit(patch: MobilePreferencesPatch): Promise<PreferenceMutationResult>
/** Applies a realtime user_settings row unless local edits are still pending. */
applyRemote(userId: string, row: unknown): void
}
interface CacheEnvelope {
schemaVersion: number
preferences: MobilePreferences
pendingPatch: MobilePreferencesPatch
lastSyncedAt: string | null
}
interface SettingsRow {
user_id: string
theme_mode: unknown
locale: unknown
haptic_enabled: unknown
auto_polish_enabled: unknown
preferred_stt_model: unknown
preferred_llm_model: unknown
onboarding_version: unknown
tutorial_completed_at: unknown
revision: unknown
updated_at: unknown
}
export const DEFAULT_PREFERENCES: MobilePreferences = Object.freeze({
themeMode: 'system',
locale: 'ko',
hapticEnabled: true,
autoPolishEnabled: true,
preferredSttModel: null,
preferredLlmModel: null,
onboardingVersion: 0,
tutorialCompletedAt: null,
revision: 1,
updatedAt: null,
})
// ── Pure helpers ─────────────────────────────────────────────────────────────
export function preferencesOwnerFor(userId: string | null): PreferencesOwner {
return {
ownerKey: userId === null ? 'installation' : `user:${userId}`,
userId,
}
}
function isRecord(value: unknown): value is Record<string, unknown> {
return typeof value === 'object' && value !== null && !Array.isArray(value)
}
function normalizeLocale(value: unknown): SupportedMobileLocale {
return value === 'en' ? 'en' : 'ko'
}
function normalizeNullableString(value: unknown): string | null {
return typeof value === 'string' && value.trim().length > 0
? value.trim()
: null
}
function normalizeNonNegativeInteger(value: unknown, fallback: number): number {
const numeric = typeof value === 'number' ? value : Number(value)
return Number.isSafeInteger(numeric) && numeric >= 0 ? numeric : fallback
}
function normalizePositiveInteger(value: unknown, fallback: number): number {
const numeric = typeof value === 'number' ? value : Number(value)
return Number.isSafeInteger(numeric) && numeric > 0 ? numeric : fallback
}
function normalizeIsoDate(value: unknown): string | null {
if (typeof value !== 'string') return null
const timestamp = Date.parse(value)
return Number.isFinite(timestamp) ? new Date(timestamp).toISOString() : null
}
export function normalizePreferences(
value: unknown,
fallback: MobilePreferences = DEFAULT_PREFERENCES,
): MobilePreferences {
if (!isRecord(value)) return { ...fallback }
return {
themeMode: isMobileThemeMode(value.themeMode) ? value.themeMode : fallback.themeMode,
locale: normalizeLocale(value.locale ?? fallback.locale),
hapticEnabled: typeof value.hapticEnabled === 'boolean'
? value.hapticEnabled
: fallback.hapticEnabled,
autoPolishEnabled: typeof value.autoPolishEnabled === 'boolean'
? value.autoPolishEnabled
: fallback.autoPolishEnabled,
preferredSttModel: value.preferredSttModel === undefined
? fallback.preferredSttModel
: normalizeNullableString(value.preferredSttModel),
preferredLlmModel: value.preferredLlmModel === undefined
? fallback.preferredLlmModel
: normalizeNullableString(value.preferredLlmModel),
onboardingVersion: normalizeNonNegativeInteger(
value.onboardingVersion,
fallback.onboardingVersion,
),
tutorialCompletedAt: value.tutorialCompletedAt === undefined
? fallback.tutorialCompletedAt
: normalizeIsoDate(value.tutorialCompletedAt),
revision: normalizePositiveInteger(value.revision, fallback.revision),
updatedAt: value.updatedAt === undefined
? fallback.updatedAt
: normalizeIsoDate(value.updatedAt),
}
}
export function normalizePreferencesPatch(value: unknown): MobilePreferencesPatch {
if (!isRecord(value)) return {}
const patch: MobilePreferencesPatch = {}
if (isMobileThemeMode(value.themeMode)) patch.themeMode = value.themeMode
if (value.locale === 'ko' || value.locale === 'en') patch.locale = value.locale
if (typeof value.hapticEnabled === 'boolean') patch.hapticEnabled = value.hapticEnabled
if (typeof value.autoPolishEnabled === 'boolean') {
patch.autoPolishEnabled = value.autoPolishEnabled
}
if (value.preferredSttModel === null || typeof value.preferredSttModel === 'string') {
patch.preferredSttModel = normalizeNullableString(value.preferredSttModel)
}
if (value.preferredLlmModel === null || typeof value.preferredLlmModel === 'string') {
patch.preferredLlmModel = normalizeNullableString(value.preferredLlmModel)
}
if (value.onboardingVersion !== undefined) {
patch.onboardingVersion = normalizeNonNegativeInteger(value.onboardingVersion, 0)
}
if (value.tutorialCompletedAt === null || typeof value.tutorialCompletedAt === 'string') {
patch.tutorialCompletedAt = normalizeIsoDate(value.tutorialCompletedAt)
}
return patch
}
export function applyPreferencesPatch(
preferences: MobilePreferences,
patch: MobilePreferencesPatch,
): MobilePreferences {
return normalizePreferences({ ...preferences, ...normalizePreferencesPatch(patch) }, preferences)
}
export function parseSettingsRow(value: unknown): MobilePreferences | null {
if (!isRecord(value) || typeof value.user_id !== 'string') return null
const row = value as unknown as SettingsRow
return normalizePreferences({
themeMode: row.theme_mode,
locale: row.locale,
hapticEnabled: row.haptic_enabled,
autoPolishEnabled: row.auto_polish_enabled,
preferredSttModel: row.preferred_stt_model,
preferredLlmModel: row.preferred_llm_model,
onboardingVersion: row.onboarding_version,
tutorialCompletedAt: row.tutorial_completed_at,
revision: row.revision,
updatedAt: row.updated_at,
})
}
function parseCacheEnvelope(raw: string | null): CacheEnvelope | null {
if (raw === null) return null
const parsed: unknown = JSON.parse(raw)
if (!isRecord(parsed) || parsed.schemaVersion !== CACHE_SCHEMA_VERSION) {
throw new Error('Unsupported mobile preferences cache schema')
}
return {
schemaVersion: CACHE_SCHEMA_VERSION,
preferences: normalizePreferences(parsed.preferences),
pendingPatch: normalizePreferencesPatch(parsed.pendingPatch),
lastSyncedAt: normalizeIsoDate(parsed.lastSyncedAt),
}
}
function serializeEnvelope(
preferences: MobilePreferences,
pendingPatch: MobilePreferencesPatch,
lastSyncedAt: string | null,
): string {
const envelope: CacheEnvelope = {
schemaVersion: CACHE_SCHEMA_VERSION,
preferences,
pendingPatch: normalizePreferencesPatch(pendingPatch),
lastSyncedAt,
}
return JSON.stringify(envelope)
}
function toInstallationPreferences(
preferences: MobilePreferences,
): MobilePreferences {
return {
...DEFAULT_PREFERENCES,
themeMode: preferences.themeMode,
locale: preferences.locale,
hapticEnabled: preferences.hapticEnabled,
onboardingVersion: preferences.onboardingVersion,
tutorialCompletedAt: preferences.tutorialCompletedAt,
}
}
export function getUserCacheKey(userId: string): string {
return `${USER_CACHE_PREFIX}${userId}`
}
export function toRowMutation(
userId: string,
preferences: MobilePreferences,
): UserSettingsRowMutation {
return {
user_id: userId,
theme_mode: preferences.themeMode,
locale: preferences.locale,
haptic_enabled: preferences.hapticEnabled,
auto_polish_enabled: preferences.autoPolishEnabled,
preferred_stt_model: preferences.preferredSttModel,
preferred_llm_model: preferences.preferredLlmModel,
onboarding_version: preferences.onboardingVersion,
tutorial_completed_at: preferences.tutorialCompletedAt,
revision: preferences.revision,
}
}
export function isPatchEmpty(patch: MobilePreferencesPatch): boolean {
return Object.keys(patch).length === 0
}
export function removeCommittedPatch(
current: MobilePreferencesPatch,
committed: MobilePreferencesPatch,
): MobilePreferencesPatch {
const remaining: MobilePreferencesPatch = { ...current }
for (const key of Object.keys(committed) as Array<keyof MobilePreferencesPatch>) {
if (remaining[key] === committed[key]) {
delete remaining[key]
}
}
return remaining
}
export function errorCodeForSync(error: unknown): PreferencesErrorCode {
return error instanceof Error && error.name === 'PreferencesSyncConflictError'
? 'SYNC_CONFLICT'
: 'SYNC_FAILED'
}
/** Cache failures outrank sync failures: CACHE_READ_FAILED > CACHE_WRITE_FAILED > sync. */
function resolveErrorCode(
cacheReadFailed: boolean,
cacheWriteFailed: boolean,
syncError: PreferencesErrorCode | null,
): PreferencesErrorCode | null {
if (cacheReadFailed) return 'CACHE_READ_FAILED'
if (cacheWriteFailed) return 'CACHE_WRITE_FAILED'
return syncError
}
// ── IO helpers over the ports ────────────────────────────────────────────────
export async function clearUserPreferenceCaches(storage: PreferencesStorage): Promise<void> {
const keys = await storage.getAllKeys()
const userKeys = keys.filter((key) => key.startsWith(USER_CACHE_PREFIX))
if (userKeys.length > 0) await storage.multiRemove(userKeys)
}
async function writeCaches(
storage: PreferencesStorage,
userId: string | null,
preferences: MobilePreferences,
userPendingPatch: MobilePreferencesPatch,
lastSyncedAt: string | null,
installationPendingPatch: MobilePreferencesPatch = {},
): Promise<void> {
const installationValue = serializeEnvelope(
toInstallationPreferences(preferences),
installationPendingPatch,
lastSyncedAt,
)
if (userId === null) {
await storage.setItem(INSTALLATION_CACHE_KEY, installationValue)
return
}
await storage.multiSet([
[INSTALLATION_CACHE_KEY, installationValue],
[getUserCacheKey(userId), serializeEnvelope(preferences, userPendingPatch, lastSyncedAt)],
])
}
async function fetchServerPreferences(
remote: PreferencesRemote,
userId: string,
): Promise<MobilePreferences | null> {
return parseSettingsRow(await remote.fetchRow(userId))
}
/**
* Revision-checked write: re-reads the row, applies the patch on top and
* updates only if nobody else bumped the revision in between. Retries a few
* times, then reports a PreferencesSyncConflictError.
*/
export async function writeServerPreferences(
remote: PreferencesRemote,
userId: string,
fallback: MobilePreferences,
patch: MobilePreferencesPatch,
): Promise<MobilePreferences> {
for (let attempt = 0; attempt < MAX_WRITE_ATTEMPTS; attempt += 1) {
const current = await fetchServerPreferences(remote, userId)
if (current === null) {
const desired = applyPreferencesPatch(fallback, patch)
const insertValue: MobilePreferences = {
...desired,
revision: Math.max(1, desired.revision),
}
const result = await remote.insertRow(toRowMutation(userId, insertValue))
if (result.status === 'duplicate') continue
const inserted = parseSettingsRow(result.row)
if (inserted === null) throw new Error('Invalid user settings insert response')
return inserted
}
const desired: MobilePreferences = {
...applyPreferencesPatch(current, patch),
revision: current.revision + 1,
}
const updated = parseSettingsRow(
await remote.updateRowAtRevision(toRowMutation(userId, desired), current.revision),
)
if (updated !== null) return updated
}
const conflict = new Error('User settings changed repeatedly on another device')
conflict.name = 'PreferencesSyncConflictError'
throw conflict
}
interface CacheReadResult {
installation: CacheEnvelope | null
user: CacheEnvelope | null
failed: boolean
}
async function readCaches(
storage: PreferencesStorage,
userId: string | null,
): Promise<CacheReadResult> {
try {
const keys = userId === null
? [INSTALLATION_CACHE_KEY]
: [INSTALLATION_CACHE_KEY, getUserCacheKey(userId)]
const entries = await storage.multiGet(keys)
return {
installation: parseCacheEnvelope(entries[0]?.[1] ?? null),
user: userId === null ? null : parseCacheEnvelope(entries[1]?.[1] ?? null),
failed: false,
}
} catch {
return { installation: null, user: null, failed: true }
}
}
// ── Store ────────────────────────────────────────────────────────────────────
type RefreshMode = 'initial' | 'background'
export function createPreferencesStore(deps: PreferencesStoreDeps): PreferencesStore {
const { storage, remote } = deps
const now = deps.now ?? (() => new Date().toISOString())
let owner: PreferencesOwner = { ownerKey: 'uninitialized', userId: null }
let snapshot: PreferencesStoreSnapshot = Object.freeze({
ownerKey: 'uninitialized',
phase: 'initial-loading',
preferences: { ...DEFAULT_PREFERENCES },
syncStatus: 'loading',
errorCode: null,
lastSyncedAt: null,
})
let preferences: MobilePreferences = { ...DEFAULT_PREFERENCES }
let pendingPatch: MobilePreferencesPatch = {}
let lastSyncedAt: string | null = null
let loadGeneration = 0
let serverQueue: Promise<void> = Promise.resolve()
let localQueue: Promise<void> = Promise.resolve()
let resyncInFlight: Promise<void> | null = null
const listeners = new Set<() => void>()
function setSnapshot(
next:
| PreferencesStoreSnapshot
| ((current: PreferencesStoreSnapshot) => PreferencesStoreSnapshot),
): void {
const resolved = typeof next === 'function' ? next(snapshot) : next
if (resolved === snapshot) return
snapshot = Object.freeze({ ...resolved })
for (const listener of [...listeners]) listener()
}
function isCurrentLoad(generation: number, ownerKey: string): boolean {
return generation === loadGeneration && owner.ownerKey === ownerKey
}
function enqueue<T>(
queue: 'server' | 'local',
task: () => Promise<T>,
): Promise<T> {
const tail = queue === 'server' ? serverQueue : localQueue
const run = tail.then(task, task)
const settled = run.then(() => undefined, () => undefined)
if (queue === 'server') serverQueue = settled
else localQueue = settled
return run
}
async function flushPendingPatch(targetUserId: string): Promise<boolean> {
if (owner.userId !== targetUserId) return false
const committedPatch = { ...pendingPatch }
if (isPatchEmpty(committedPatch)) return true
const targetOwnerKey = preferencesOwnerFor(targetUserId).ownerKey
setSnapshot((current) => current.ownerKey === targetOwnerKey
? { ...current, syncStatus: 'saving', errorCode: null }
: current)
try {
const saved = await writeServerPreferences(
remote,
targetUserId,
preferences,
committedPatch,
)
if (owner.userId !== targetUserId) return false
const remainingPatch = removeCommittedPatch(pendingPatch, committedPatch)
const nextPreferences = applyPreferencesPatch(saved, remainingPatch)
const syncedAt = now()
preferences = nextPreferences
pendingPatch = remainingPatch
lastSyncedAt = syncedAt
try {
await writeCaches(storage, targetUserId, nextPreferences, remainingPatch, syncedAt)
setSnapshot({
ownerKey: targetOwnerKey,
phase: 'ready',
preferences: nextPreferences,
syncStatus: isPatchEmpty(remainingPatch) ? 'synced' : 'saving',
errorCode: null,
lastSyncedAt: syncedAt,
})
} catch {
setSnapshot({
ownerKey: targetOwnerKey,
phase: 'ready',
preferences: nextPreferences,
syncStatus: 'error',
errorCode: 'CACHE_WRITE_FAILED',
lastSyncedAt: syncedAt,
})
}
return isPatchEmpty(remainingPatch)
} catch (error) {
if (owner.userId !== targetUserId) return false
setSnapshot((current) => current.ownerKey === targetOwnerKey
? {
...current,
phase: 'ready',
syncStatus: 'offline',
errorCode: errorCodeForSync(error),
}
: current)
return false
}
}
function queueServerFlush(targetUserId: string): Promise<boolean> {
return enqueue('server', () => flushPendingPatch(targetUserId))
}
async function refresh(target: PreferencesOwner, mode: RefreshMode): Promise<void> {
if (mode === 'background' && owner.ownerKey !== target.ownerKey) return
const targetOwnerKey = target.ownerKey
const targetUserId = target.userId
const generation = ++loadGeneration
setSnapshot((current) => {
if (mode === 'initial') {
return {
...current,
ownerKey: targetOwnerKey,
phase: 'initial-loading',
syncStatus: 'loading',
errorCode: null,
}
}
// Background: keep the phase so dependent UI stays mounted.
return current.ownerKey === targetOwnerKey
? { ...current, syncStatus: 'loading', errorCode: null }
: current
})
const cache = await readCaches(storage, targetUserId)
const cacheReadFailed = cache.failed
let cacheWriteFailed = false
if (!isCurrentLoad(generation, targetOwnerKey)) return
if (targetUserId === null) {
const localPreferences = cache.installation?.preferences ?? { ...DEFAULT_PREFERENCES }
preferences = localPreferences
pendingPatch = cache.installation?.pendingPatch ?? {}
lastSyncedAt = cache.installation?.lastSyncedAt ?? null
setSnapshot({
ownerKey: targetOwnerKey,
phase: 'ready',
preferences: localPreferences,
syncStatus: cacheReadFailed ? 'error' : 'local',
errorCode: cacheReadFailed ? 'CACHE_READ_FAILED' : null,
lastSyncedAt,
})
return
}
const cachedPreferences = cache.user?.preferences
?? cache.installation?.preferences
?? { ...DEFAULT_PREFERENCES }
const stagedPatch: MobilePreferencesPatch = {
...(cache.user?.pendingPatch ?? {}),
...(cache.installation?.pendingPatch ?? {}),
}
const cachedWithPending = applyPreferencesPatch(cachedPreferences, stagedPatch)
const cachedSyncedAt = cache.user?.lastSyncedAt ?? cache.installation?.lastSyncedAt ?? null
preferences = cachedWithPending
pendingPatch = stagedPatch
lastSyncedAt = cachedSyncedAt
setSnapshot({
ownerKey: targetOwnerKey,
phase: 'ready',
preferences: cachedWithPending,
syncStatus: 'loading',
errorCode: cacheReadFailed ? 'CACHE_READ_FAILED' : null,
lastSyncedAt: cachedSyncedAt,
})
try {
await writeCaches(
storage,
targetUserId,
cachedWithPending,
stagedPatch,
cache.user?.lastSyncedAt ?? null,
)
} catch {
cacheWriteFailed = true
}
let resolved: MobilePreferences
try {
const server = await fetchServerPreferences(remote, targetUserId)
resolved = server === null || !isPatchEmpty(stagedPatch)
? await writeServerPreferences(
remote,
targetUserId,
server ?? cachedWithPending,
stagedPatch,
)
: server
} catch (error) {
if (!isCurrentLoad(generation, targetOwnerKey)) return
setSnapshot({
ownerKey: targetOwnerKey,
phase: 'ready',
preferences: cachedWithPending,
syncStatus: 'offline',
errorCode: resolveErrorCode(cacheReadFailed, cacheWriteFailed, errorCodeForSync(error)),
lastSyncedAt: cachedSyncedAt,
})
return
}
if (!isCurrentLoad(generation, targetOwnerKey)) return
// Edits committed while this refresh was in flight stay pending on top of
// the server value instead of being dropped.
const remainingPatch = removeCommittedPatch(pendingPatch, stagedPatch)
const nextPreferences = applyPreferencesPatch(resolved, remainingPatch)
const syncedAt = now()
preferences = nextPreferences
pendingPatch = remainingPatch
lastSyncedAt = syncedAt
try {
await writeCaches(storage, targetUserId, nextPreferences, remainingPatch, syncedAt)
} catch {
cacheWriteFailed = true
}
if (!isCurrentLoad(generation, targetOwnerKey)) return
// Read the in-memory state again: a commit may have landed during the cache write.
const errorCode = resolveErrorCode(cacheReadFailed, cacheWriteFailed, null)
setSnapshot({
ownerKey: targetOwnerKey,
phase: 'ready',
preferences,
syncStatus: errorCode !== null
? 'error'
: isPatchEmpty(pendingPatch) ? 'synced' : 'saving',
errorCode,
lastSyncedAt: syncedAt,
})
}
function load(target: PreferencesOwner): Promise<void> {
const sameOwnerReady = snapshot.ownerKey === target.ownerKey && snapshot.phase === 'ready'
owner = { ...target }
return refresh(owner, sameOwnerReady ? 'background' : 'initial')
}
function resync(): Promise<void> {
const target = owner
if (target.userId !== null && !isPatchEmpty(pendingPatch)) {
return queueServerFlush(target.userId).then(() => undefined)
}
if (resyncInFlight !== null) return resyncInFlight
const run = enqueue('server', () => refresh(target, 'background'))
const tracked = run.finally(() => {
if (resyncInFlight === tracked) resyncInFlight = null
})
resyncInFlight = tracked
return tracked
}
function needsForegroundResync(): boolean {
if (owner.userId === null) return false
return !isPatchEmpty(pendingPatch) || snapshot.syncStatus === 'offline'
}
async function commitNow(
requestedPatch: MobilePreferencesPatch,
): Promise<PreferenceMutationResult> {
const targetOwnerKey = owner.ownerKey
const targetUserId = owner.userId
const patch = normalizePreferencesPatch(requestedPatch)
if (isPatchEmpty(patch)) {
return {
localSaved: true,
serverSynced: targetUserId === null || isPatchEmpty(pendingPatch),
}
}
const nextPreferences = applyPreferencesPatch(preferences, patch)
const nextPendingPatch = { ...pendingPatch, ...patch }
try {
await writeCaches(
storage,
targetUserId,
nextPreferences,
nextPendingPatch,
lastSyncedAt,
targetUserId === null ? nextPendingPatch : {},
)
} catch {
if (owner.ownerKey === targetOwnerKey) {
setSnapshot((current) => ({
...current,
syncStatus: 'error',
errorCode: 'CACHE_WRITE_FAILED',
}))
}
return { localSaved: false, serverSynced: false }
}
if (owner.ownerKey !== targetOwnerKey) {
return { localSaved: true, serverSynced: false }
}
preferences = nextPreferences
pendingPatch = nextPendingPatch
setSnapshot((current) => ({
...current,
ownerKey: targetOwnerKey,
phase: 'ready',
preferences: nextPreferences,
syncStatus: targetUserId === null ? 'local' : 'saving',
errorCode: null,
}))
if (targetUserId === null) {
return { localSaved: true, serverSynced: false }
}
const serverSynced = await queueServerFlush(targetUserId)
return { localSaved: true, serverSynced }
}
function commit(patch: MobilePreferencesPatch): Promise<PreferenceMutationResult> {
return enqueue('local', () => commitNow(patch))
}
function applyRemote(userId: string, row: unknown): void {
if (owner.userId !== userId || !isPatchEmpty(pendingPatch)) return
const parsed = parseSettingsRow(row)
if (parsed === null) return
const syncedAt = now()
preferences = parsed
lastSyncedAt = syncedAt
setSnapshot({
ownerKey: preferencesOwnerFor(userId).ownerKey,
phase: 'ready',
preferences: parsed,
syncStatus: 'synced',
errorCode: null,
lastSyncedAt: syncedAt,
})
void writeCaches(storage, userId, parsed, {}, syncedAt).catch(() => {
if (owner.userId !== userId) return
setSnapshot((current) => ({
...current,
syncStatus: 'error',
errorCode: 'CACHE_WRITE_FAILED',
}))
})
}
return {
getSnapshot: () => snapshot,
subscribe(listener) {
listeners.add(listener)
return () => {
listeners.delete(listener)
}
},
load,
resync,
needsForegroundResync,
commit,
applyRemote,
}
}

View file

@ -0,0 +1,57 @@
import { RecorderBusyError } from './recorder/recorder-errors'
import type {
RecorderOwner,
RecorderSession,
RecordingRuntimeSnapshot,
} from './recorder/recorder-types'
/** The part of the shared recorder facade this policy needs. */
export interface CaptureRecorderPort {
acquire(owner: RecorderOwner): Promise<RecorderSession>
}
function isLive(snapshot: RecordingRuntimeSnapshot): boolean {
return snapshot.state === 'recording' || snapshot.state === 'paused'
}
function isReattachable(snapshot: RecordingRuntimeSnapshot): boolean {
return (snapshot.state === 'stopped' || snapshot.state === 'recoverable')
&& snapshot.recording !== null
}
/**
* Stops the microphone when the signed-in session is lost involuntarily, but
* keeps the meeting capture's file so its owner can process it after signing
* back in (Record restores a stopped capture as a recoverable recording).
*
* - A Talk turn is transient conversation input, not durable work: discarded.
* - A capture the backend cannot hand back after the screen unmounts (the
* in-process iOS recorder reports no reattachable snapshot) is discarded as
* before, because a stranded stopped capture would block every new
* recording.
*/
export async function stopLiveCaptureKeepingFile(recorder: CaptureRecorderPort): Promise<void> {
let session: RecorderSession
try {
session = await recorder.acquire('record')
} catch (error) {
if (!(error instanceof RecorderBusyError)) throw error
const holder = await recorder.acquire(error.holder)
await holder.cancel()
return
}
try {
await session.stop()
} catch {
// Nothing is driven by this JS process (idle, already stopped, or a
// foreground-service capture that outlived a restart): inspect it below.
}
let snapshot = await session.restore()
if (isLive(snapshot)) {
await session.stop()
snapshot = await session.restore()
}
if (isReattachable(snapshot)) return
await session.cancel()
}

View file

@ -0,0 +1,77 @@
import AsyncStorage from '@react-native-async-storage/async-storage'
const STORAGE_KEY = '@d3ro/account-retained-work/v1'
const MAX_USER_ID_LENGTH = 128
/** Storage port; AsyncStorage in the app, an in-memory fake in tests. */
export interface RetainedWorkStoragePort {
getItem(key: string): Promise<string | null>
setItem(key: string, value: string): Promise<void>
removeItem(key: string): Promise<void>
}
/**
* Persisted marker naming the account whose unsynced recordings were kept on
* this device when its session was lost involuntarily. It survives a restart
* so the next boundary can tell "the owner came back" (keep and resume) from
* "another account arrived" (discard before that account sees the device).
*
* `current()` is synchronous so the auth boundary can decide without an extra
* await; `load()` must have settled once before the first decision.
*/
export interface RetainedWorkOwnerStore {
load(): Promise<string | null>
current(): string | null
retain(userId: string): Promise<void>
release(): Promise<void>
}
function parseOwner(raw: string | null): string | null {
if (raw === null) return null
const trimmed = raw.trim()
return trimmed.length > 0 && trimmed.length <= MAX_USER_ID_LENGTH ? trimmed : null
}
export function createRetainedWorkOwnerStore(
storage: RetainedWorkStoragePort,
): RetainedWorkOwnerStore {
let cached: string | null = null
let version = 0
let loading: Promise<string | null> | null = null
return {
load(): Promise<string | null> {
if (loading !== null) return loading
const loadVersion = version
const operation = storage.getItem(STORAGE_KEY).then((raw) => {
// A retain/release issued while the read was in flight is newer.
if (version === loadVersion) cached = parseOwner(raw)
return cached
})
loading = operation
operation.catch(() => {
if (loading === operation) loading = null
})
return operation
},
current(): string | null {
return cached
},
async retain(userId: string): Promise<void> {
const owner = parseOwner(userId)
if (owner === null) throw new Error('retained_work_owner_invalid')
version += 1
cached = owner
await storage.setItem(STORAGE_KEY, owner)
},
async release(): Promise<void> {
version += 1
cached = null
await storage.removeItem(STORAGE_KEY)
},
}
}
export const retainedAccountWork: RetainedWorkOwnerStore = createRetainedWorkOwnerStore(AsyncStorage)
export const retainedAccountWorkTestContract = { storageKey: STORAGE_KEY }