Files
opencode-mobile/app/_layout.tsx
Den 27362cee98 fix: request notification permission; resync session on focus; notif + reply bugs (#121)
Five correctness bugs from an adversarial review of the notification and
permission/approval paths (each verified against the code):

1. Notifications never worked for most users (HIGH): OS permission was only
   requested when a user manually toggled a Settings switch off→on. Since
   categories default on, that path never fired, permission stayed
   'undetermined', and send() silently no-op'd every notification. Now request
   it once on first live connection (in-context). (app/_layout.tsx)

2. Wrong-session data after back-navigation (HIGH): session screen reads a
   global store and its resync ran only on mount; the native stack keeps
   screens mounted underneath a pushed one, so returning to a session could
   show another session's messages and permission prompts — approving the wrong
   session's tool call. Re-select on focus via useFocusEffect. (app/session/[id].tsx)

3. 'Task completed' fired on aborted/errored runs (misleading, and a duplicate
   push alongside 'Session error'). Gate the notify by !aborted && !errored.
   (src/stores/events.ts)

4. Tapping a connection-drop notification (no sessionId) navigated to an empty
   '/session/' dead-end. Route to home instead. (app/_layout.tsx)

5. Double-tap on a single-select question sent two replies; the second hit an
   already-resolved request and popped a spurious 'Reply failed' alert. One-shot
   guard on reply/reject. (src/components/chat/QuestionPrompt.tsx)

Verified but intentionally NOT changed: 'completed' notifications default off
(a defensible anti-spam choice — the app still notifies when the agent needs
input). typecheck clean, 187/187 tests.


Claude-Session: https://claude.ai/code/session_01T12AhSnQVrSxNnvwfCx2z6

Co-authored-by: engineer <engineer@macbookpro.lan>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-18 06:04:15 -07:00

191 lines
6.9 KiB
TypeScript

import { useEffect, useRef, useState } from "react"
import { Stack, router } from "expo-router"
import { StatusBar } from "expo-status-bar"
import { useColorScheme, View, ActivityIndicator } from "react-native"
import { QueryClient, QueryClientProvider } from "@tanstack/react-query"
import { GestureHandlerRootView } from "react-native-gesture-handler"
import { BottomSheetModalProvider } from "@gorhom/bottom-sheet"
import { I18nextProvider, useTranslation } from "react-i18next"
import i18n from "../src/lib/i18n/config"
import { useAuth } from "../src/stores/auth"
import { useConnections } from "../src/stores/connections"
import { useEvents } from "../src/stores/events"
import { useCatalog } from "../src/stores/catalog"
import { useSettings } from "../src/stores/settings"
import { AuthGate } from "../src/components/AuthGate"
import { ErrorBoundary } from "../src/components/ErrorBoundary"
import { TelemetryConsentModal } from "../src/components/TelemetryConsentModal"
import * as notifications from "../src/lib/notifications"
import { addBreadcrumb, wrap } from "../src/lib/sentry"
import { loadTelemetryConsent, setTelemetryConsent } from "../src/lib/telemetry"
import { initAnalytics, trackAppOpened } from "../src/lib/analytics"
const queryClient = new QueryClient()
function RootLayout() {
const colorScheme = useColorScheme()
const isDark = colorScheme === "dark"
const { t } = useTranslation()
const { initialize: initAuth, isLoading: authLoading } = useAuth()
const { loadConnections, isLoading: connectionsLoading, client } = useConnections()
const sseStarted = useRef(false)
const notifPermissionRequested = useRef(false)
// Telemetry consent state: null = loading, 'unknown' = show modal, else decided
const [consentState, setConsentState] = useState<"loading" | "unknown" | "decided">("loading")
useEffect(() => {
initAuth()
loadConnections()
useSettings.getState().load()
// Connect notification preferences to the notification module
notifications.configure(() => useSettings.getState().notifications)
// Navigate to session when user taps a notification. Connection-drop
// notifications carry no sessionId (they aren't about a session) — route
// to the home tab instead of "/session/" (an empty, dead-end route).
const unsubNotifications = notifications.onTap((data) => {
if (data.sessionId) router.push(`/session/${data.sessionId}`)
else router.push("/")
})
// Load telemetry consent — initialise Sentry only if previously granted
loadTelemetryConsent()
.then((state) => {
if (state === "granted") {
import("../src/lib/sentry").then(({ initSentry }) => {
initSentry()
addBreadcrumb({ category: "app.lifecycle", message: "app started" })
})
initAnalytics()
trackAppOpened()
setConsentState("decided")
} else if (state === "denied") {
addBreadcrumb({ category: "app.lifecycle", message: "app started (telemetry off)" })
setConsentState("decided")
} else {
setConsentState("unknown")
}
})
.catch(() => {
// SecureStore unavailable — show modal so user can decide
setConsentState("unknown")
})
return unsubNotifications
}, [])
// Connect/disconnect SSE and load catalog when client changes
useEffect(() => {
if (client && !sseStarted.current) {
sseStarted.current = true
useEvents.getState().connect()
useCatalog.getState().load()
// Request OS notification permission once we have a live connection —
// the in-context moment the user will start running agent tasks they'll
// want to be pinged about. Previously this was only ever requested when
// a user manually toggled a notification switch off→on in Settings; since
// most categories default on, that path never fired for typical users
// and send() silently no-op'd on every notification (permission stayed
// "undetermined"). setup() is idempotent — it won't re-prompt once the
// OS has a decision — so the ref just avoids redundant calls per session.
if (!notifPermissionRequested.current) {
notifPermissionRequested.current = true
void notifications.setup()
}
} else if (!client && sseStarted.current) {
sseStarted.current = false
useEvents.getState().disconnect()
}
return () => {
if (sseStarted.current) {
sseStarted.current = false
useEvents.getState().disconnect()
}
}
}, [client])
const isLoading = authLoading || connectionsLoading || consentState === "loading"
if (isLoading) {
return (
<View
style={{
flex: 1,
justifyContent: "center",
alignItems: "center",
backgroundColor: isDark ? "#0a0a0a" : "#ffffff",
}}
>
<ActivityIndicator size="large" color={isDark ? "#ffffff" : "#0a0a0a"} />
</View>
)
}
return (
<ErrorBoundary>
<I18nextProvider i18n={i18n}>
<GestureHandlerRootView style={{ flex: 1 }}>
<BottomSheetModalProvider>
<QueryClientProvider client={queryClient}>
<AuthGate>
<Stack
screenOptions={{
headerStyle: {
backgroundColor: isDark ? "#0a0a0a" : "#ffffff",
},
headerTintColor: isDark ? "#ffffff" : "#0a0a0a",
contentStyle: {
backgroundColor: isDark ? "#0a0a0a" : "#ffffff",
},
}}
>
<Stack.Screen name="(tabs)" options={{ headerShown: false }} />
<Stack.Screen
name="session/[id]"
options={{
title: t("session.titleFallback"),
presentation: "card",
}}
/>
<Stack.Screen
name="connection/add"
options={{
title: t("nav.addConnectionTitle"),
presentation: "modal",
}}
/>
<Stack.Screen
name="connection/[id]"
options={{
title: t("nav.editConnectionTitle"),
presentation: "modal",
}}
/>
</Stack>
<StatusBar style={isDark ? "light" : "dark"} />
</AuthGate>
</QueryClientProvider>
</BottomSheetModalProvider>
</GestureHandlerRootView>
{/* Telemetry consent modal — shown once on first launch */}
<TelemetryConsentModal
visible={consentState === "unknown"}
onAllow={async () => {
await setTelemetryConsent(true)
setConsentState("decided")
}}
onDecline={async () => {
await setTelemetryConsent(false)
setConsentState("decided")
}}
/>
</I18nextProvider>
</ErrorBoundary>
)
}
export default wrap(RootLayout)