Skip to content
Merged
Show file tree
Hide file tree
Changes from 9 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .github/workflows/mobile-ios-release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,8 @@ jobs:
run: node -e 'const fs = require("node:fs"); const { expo } = require("./app.json"); fs.appendFileSync(process.env.GITHUB_OUTPUT, `version=${expo.version}\nbuild_number=${expo.ios.buildNumber}\n`)'

- name: Expo prebuild
env:
ORCA_IOS_APS_ENVIRONMENT: production
run: npx expo prebuild --platform ios --no-install

- name: Install CocoaPods
Expand Down
32 changes: 32 additions & 0 deletions mobile/app.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
// Why this file exists: a bare "expo-notifications" plugin entry writes
// `aps-environment: development` into the iOS entitlements, while push-token.ts
// reports `production` for every non-__DEV__ build. A TestFlight or App Store build
// would then register a production APNs token against a sandbox entitlement, and the
// gateway's pushes would be accepted by Apple and delivered nowhere. Deriving the
// mode from an env var the release workflow sets makes the two agree by construction
// instead of relying on the export step to rewrite the entitlement.
//
// app.json stays the source for everything else: Expo reads it first and hands it to
// this function, so the fastlane version/buildNumber rewrite still flows through.
const APS_ENVIRONMENT =
process.env.ORCA_IOS_APS_ENVIRONMENT === 'production' ? 'production' : 'development'
Comment thread
pullfrog[bot] marked this conversation as resolved.
Resolved

module.exports = ({ config }) => ({
...config,
ios: {
...config.ios,
entitlements: { ...config.ios?.entitlements, 'aps-environment': APS_ENVIRONMENT }
},
plugins: (config.plugins ?? []).map((plugin) =>
plugin === 'expo-notifications'
? [
'expo-notifications',
{
enableBackgroundRemoteNotifications: true,
mode: APS_ENVIRONMENT,
icon: './assets/notification-icon.png'
}
]
: plugin
)
})
4 changes: 3 additions & 1 deletion mobile/app.json
Original file line number Diff line number Diff line change
Expand Up @@ -75,10 +75,12 @@
"allowBackup": false,
"permissions": ["RECORD_AUDIO", "MODIFY_AUDIO_SETTINGS"],
"package": "com.stably.orca.mobile",
"versionCode": 16
"versionCode": 16,
"googleServicesFile": "./google-services.json"
},
"plugins": [
"expo-router",
"expo-notifications",
"./plugins/android-respect-rotation-lock.js",
[
"expo-splash-screen",
Expand Down
60 changes: 45 additions & 15 deletions mobile/app/_layout.tsx
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import { registerPushDismissalTask } from '../src/notifications/push-background-dismissal'
import { readNativeNotificationData } from '../src/notifications/native-notification-data'
import { setNotificationViewingWorkspace } from '../src/notifications/notification-viewing-policy'
import { useCallback, useEffect, useRef } from 'react'
import { View, StyleSheet } from 'react-native'
import { Stack, useRouter } from 'expo-router'
import { Stack, useRouter, useGlobalSearchParams, usePathname } from 'expo-router'
import { StatusBar } from 'expo-status-bar'
import * as SplashScreen from 'expo-splash-screen'
import * as Notifications from 'expo-notifications'
Expand All @@ -10,6 +13,13 @@ import { OrcaLogo } from '../src/components/OrcaLogo'
import { RpcClientProvider } from '../src/transport/client-context'
import { getNotificationNavigationTarget } from '../src/notifications/notification-routing'
import { useOpenNotificationRoute } from '../src/notifications/use-open-notification-route'
import {
isRemotePushTrigger,
pushNotificationRouteData,
foregroundNotificationBehavior
} from '../src/notifications/push-receive'
import { startPushTokenSync } from '../src/notifications/push-registration'
import { ensureDesktopNotificationChannel } from '../src/notifications/desktop-notification-channel'
import { loadHostCatalog } from '../src/transport/host-store'
import { extractPairingCodeFromUrl } from '../src/transport/pairing'
import { recoverMobileRelayPairing } from '../src/transport/mobile-relay-pairing-recovery'
Expand All @@ -19,22 +29,29 @@ import { recoverMobileRelayPairing } from '../src/transport/mobile-relay-pairing
// between the native splash and the first React paint.
SplashScreen.preventAutoHideAsync()

// Why: without this, expo-notifications silently drops notifications when
// the app is in the foreground. Setting all three to true makes iOS/Android
// display the banner, play the sound, and show the badge even while the
// app is active. This runs once at module load time before any notification
// is scheduled.
// Why at boot and not only on subscribe: the gateway's FCM payload targets the
// 'orca-desktop' channel, and a background push can land before any socket has
// connected. Android drops a notification whose channel does not exist yet.
void ensureDesktopNotificationChannel().catch(() => {})
void registerPushDismissalTask().catch(() => {})

// Register before scheduling so foreground delivery uses the same suppression policy.
Notifications.setNotificationHandler({
handleNotification: async () => ({
shouldShowBanner: true,
shouldShowList: true,
shouldPlaySound: true,
shouldSetBadge: false
})
handleNotification: foregroundNotificationBehavior
})

export default function RootLayout() {
const router = useRouter()
const pathname = usePathname()
const { hostId, worktreeId } = useGlobalSearchParams<{ hostId?: string; worktreeId?: string }>()
useEffect(() => {
setNotificationViewingWorkspace(
pathname.includes('/session/') && typeof hostId === 'string' && typeof worktreeId === 'string'
? { hostId, worktreeId }
: null
)
return () => setNotificationViewingWorkspace(null)
}, [pathname, hostId, worktreeId])
const openNotificationRoute = useOpenNotificationRoute()
const handledNotificationIdsRef = useRef<Set<string>>(new Set())

Expand All @@ -44,6 +61,10 @@ export default function RootLayout() {
void recoverMobileRelayPairing()
}, [])

// Why: a rolled APNs/FCM token stops delivering silently, so every paired host
// has to be re-registered with the new one as soon as the provider hands it over.
useEffect(() => startPushTokenSync(), [])

// Why: route `orca://pair?...` deep links to the confirm screen so
// the same pairing flow runs whether the link arrived via QR scan,
// paste, AirDrop, Messages, or `xcrun simctl openurl`. getInitialURL
Expand Down Expand Up @@ -94,9 +115,18 @@ export default function RootLayout() {
}
}

async function getNavigationTarget(data: unknown) {
async function getNavigationTarget(notification: Notifications.Notification) {
const hosts = await loadHostCatalog().catch(() => null)
return getNotificationNavigationTarget(data, {
const data = readNativeNotificationData(notification.request)
// A gateway push names its host by key fingerprint, not by this device's hostId.
// With no catalog to resolve against, such a push stays unrouted instead of
// falling back to whatever hostId its raw data carries.
const routeData = pushNotificationRouteData(
data,
hosts ?? [],
isRemotePushTrigger(notification.request.trigger)
)
return getNotificationNavigationTarget(routeData, {
knownHostIds: hosts ? new Set(hosts.map((host) => host.id)) : undefined,
credentialStatusByHostId: hosts
? new Map(hosts.map((host) => [host.id, host.credentialStatus]))
Expand Down Expand Up @@ -124,7 +154,7 @@ export default function RootLayout() {
}
}

const target = await getNavigationTarget(response.notification.request.content.data)
const target = await getNavigationTarget(response.notification)
clearLastNotificationResponse()
if (disposed) {
return
Expand Down
4 changes: 2 additions & 2 deletions mobile/app/mobile-onboarding.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ import {
saveDefaultSessionView,
type MobileSessionView
} from '../src/storage/session-view-preferences'
import { savePushNotificationsEnabled } from '../src/storage/preferences'
import { setRemotePushEnabled } from '../src/notifications/push-registration'

const SLIDE_DURATION_MS = 280

Expand Down Expand Up @@ -127,7 +127,7 @@ function MobileOnboardingFlow({
setError(null)
try {
const enabled = choice === 'enable' ? await ensureNotificationPermissions() : false
await savePushNotificationsEnabled(enabled)
await setRemotePushEnabled(enabled)
advanceOrContinue()
} catch {
setError('Notification settings could not be updated. Try again.')
Expand Down
12 changes: 11 additions & 1 deletion mobile/app/notifications.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import { NotificationDisplayTest } from '../src/settings/notification-display-test'
import { NativeNotificationDeliverySettings } from '../src/settings/native-notification-delivery-settings'
import { useRouter } from 'expo-router'
import NotificationsScreen from '../src/settings/notification-settings-screen'
import { nativeNotificationSettingsOperations } from '../src/settings/native-notification-settings-operations'
Expand All @@ -7,6 +9,14 @@ export default function NativeNotificationsRoute() {
<NotificationsScreen
operations={nativeNotificationSettingsOperations}
onBack={() => router.back()}
/>
description="Get agent alerts even when the app is closed. Delivered through Orca’s push service and Apple or Google."
>
{(enabled) => (
<>
<NativeNotificationDeliverySettings enabled={enabled} />
<NotificationDisplayTest onTroubleshoot={() => router.push('/troubleshoot')} />
</>
)}
</NotificationsScreen>
)
}
Binary file added mobile/assets/notification-icon.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
39 changes: 39 additions & 0 deletions mobile/google-services.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
{
"project_info": {
"project_number": "120364513935",
"project_id": "onorca-cloud",
"storage_bucket": "onorca-cloud.firebasestorage.app"
},
"client": [
{
"client_info": {
"mobilesdk_app_id": "1:120364513935:android:1d951dc430aeb9bc664efa",
"android_client_info": {
"package_name": "com.stably.orca.mobile"
}
},
"oauth_client": [
{
"client_id": "120364513935-evfa8502bp5r9hn7afhd9i03oibs8223.apps.googleusercontent.com",
"client_type": 3
}
],
"api_key": [
{
"current_key": "AIzaSyBmT_w0OUQSiVfxblx-F0qlRvGkBBkTNQU"
}
],
"services": {
"appinvite_service": {
"other_platform_oauth_client": [
{
"client_id": "120364513935-evfa8502bp5r9hn7afhd9i03oibs8223.apps.googleusercontent.com",
"client_type": 3
}
]
}
}
}
],
"configuration_version": "1"
}
3 changes: 3 additions & 0 deletions mobile/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
// Headless notification launches do not mount the router layout.
import './src/notifications/push-background-dismissal'
import 'expo-router/entry'
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"platforms": ["apple"],
"apple": {
"modules": ["OrcaNotificationDismissalModule"],
"appDelegateSubscribers": ["OrcaNotificationDismissalSubscriber"]
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
Pod::Spec.new do |s|
s.name = 'OrcaNotificationDismissal'
s.version = '0.0.1'
s.summary = 'Native notification dismissal and sequence fencing'
s.description = s.summary
s.license = { :type => 'MIT' }
s.author = 'Orca'
s.homepage = 'https://onorca.dev'
s.source = { :git => 'https://github.com/stablyai/orca.git' }
s.platforms = { :ios => '15.1' }
s.swift_version = '5.9'
s.static_framework = true
s.dependency 'ExpoModulesCore'
s.source_files = '**/*.swift'
end
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import ExpoModulesCore

public class OrcaNotificationDismissalModule: Module {
public func definition() -> ModuleDefinition {
Name("OrcaNotificationDismissal")
AsyncFunction("remember") { (payload: [String: Any]) in
if let identity = PushDismissalIdentity(payload) { PushDismissalLedger.shared.remember(identity) }
}
AsyncFunction("wasDismissed") { (payload: [String: Any]) -> Bool in
guard let identity = PushDismissalIdentity(payload) else { return false }
return PushDismissalLedger.shared.contains(identity)
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import ExpoModulesCore
import UserNotifications

public class OrcaNotificationDismissalSubscriber: ExpoAppDelegateSubscriber {
public func application(
_ application: UIApplication,
didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void
) {
guard let payload = userInfo["orca"] as? [String: Any],
payload["kind"] as? String == "dismiss", let fence = PushDismissalIdentity(payload)
else { completionHandler(.noData); return }
PushDismissalLedger.shared.remember(fence)
let center = UNUserNotificationCenter.current()
center.getDeliveredNotifications { notifications in
let ids = notifications.compactMap { notification -> String? in
guard let data = notification.request.content.userInfo["orca"] as? [String: Any],
data["hostFingerprint"] as? String == fence.hostFingerprint,
PushDismissalLedger.shared.containsNotification(data) else { return nil }
return notification.request.identifier
}
center.removeDeliveredNotifications(withIdentifiers: ids)
completionHandler(ids.isEmpty ? .noData : .newData)
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
import Foundation
import CoreFoundation

struct PushDismissalIdentity: Codable {
let hostFingerprint: String
let notificationId: String
let notificationEpoch: String
let notificationSeq: Int64

init?(_ value: [String: Any]) {
guard let host = value["hostFingerprint"] as? String, !host.isEmpty, host.count <= 512,
let id = value["notificationId"] as? String, !id.isEmpty, id.count <= 2048,
let epoch = value["notificationEpoch"] as? String, !epoch.isEmpty, epoch.count <= 128,
let seq = value["notificationSeq"] as? NSNumber,
CFGetTypeID(seq) != CFBooleanGetTypeID(), seq.doubleValue.isFinite,
seq.doubleValue >= 0, seq.doubleValue <= 9_007_199_254_740_991,
seq.doubleValue.rounded(.down) == seq.doubleValue else { return nil }
hostFingerprint = host; notificationId = id; notificationEpoch = epoch
notificationSeq = seq.int64Value
}

func matches(_ other: PushDismissalIdentity) -> Bool {
hostFingerprint == other.hostFingerprint && notificationId == other.notificationId &&
notificationEpoch == other.notificationEpoch
}
}

final class PushDismissalLedger {
static let shared = PushDismissalLedger()
private struct Entry: Codable { let identity: PushDismissalIdentity; let expiresAt: TimeInterval }
private let defaults: UserDefaults
private let lock = NSLock()
private let storageKey = "orca.pushDismissals.v1"
init(defaults: UserDefaults = .standard) { self.defaults = defaults }

private func read(now: TimeInterval) -> [Entry] {
guard let data = defaults.data(forKey: storageKey),
let entries = try? JSONDecoder().decode([Entry].self, from: data) else { return [] }
return entries.filter { $0.expiresAt > now }
}

func remember(_ identity: PushDismissalIdentity, now: TimeInterval = Date().timeIntervalSince1970) {
lock.lock(); defer { lock.unlock() }
let entries = read(now: now)
let previous = entries.first { $0.identity.matches(identity) }
let newest = (previous?.identity.notificationSeq ?? -1) > identity.notificationSeq
? previous!.identity : identity
// Keep every live fence: count-based eviction lets delayed alerts reappear.
let next = entries.filter { !$0.identity.matches(identity) } +
[Entry(identity: newest, expiresAt: now + 86400)]
if let data = try? JSONEncoder().encode(next) {
defaults.set(data, forKey: storageKey)
}
}

func contains(_ identity: PushDismissalIdentity, now: TimeInterval = Date().timeIntervalSince1970) -> Bool {
lock.lock(); defer { lock.unlock() }
return read(now: now).contains {
$0.identity.matches(identity) && $0.identity.notificationSeq >= identity.notificationSeq
}
}

func containsNotification(_ payload: [String: Any], now: TimeInterval = Date().timeIntervalSince1970) -> Bool {
guard let identity = PushDismissalIdentity(payload) else { return false }
return contains(identity, now: now)
}
}
5 changes: 5 additions & 0 deletions mobile/modules/orca-notification-dismissal/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"name": "orca-notification-dismissal",
"version": "0.0.1",
"private": true
}
Loading