Repository navigation
fix(mobile): keep hosts visible when credentials are unavailable - #12775
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughThe mobile host flow now loads catalog entries with explicit credential states and derives connectable profiles from ready credentials. Host storage uses shared metadata and device-token helpers with revision-aware writes and guarded cleanup. Host cards display pairing or retry guidance for unavailable credentials. Notification routing directs missing credentials to pairing and temporarily unavailable credentials to retry before session navigation. Tests cover catalog selection, credential states, routing, and storage recovery. 🚥 Pre-merge checks | ✅ 3 | ❌ 2❌ Failed checks (2 warnings)
✅ Passed checks (3 passed)
✨ Finishing Touches 💡 1📝 Generate docstrings 💡
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (1)
mobile/src/transport/host-store.test.ts (1)
334-346: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAdd a concurrency case for the cleanup guard.
This test covers cleanup with no competing write. The related race in
mobile/src/transport/host-store.tslines 141-154 needs a case that startssaveHostfor the same id while the scheduled cleanup is in flight, then asserts thatdeleteItemAsyncdid not remove the committed token. Add it together with the serialization fix.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: f0438b8c-8989-4f22-9c63-d1c0a8131194
📒 Files selected for processing (15)
mobile/app/_layout.tsxmobile/app/index.tsxmobile/src/components/MobileHostCard.test.tsxmobile/src/components/MobileHostCard.tsxmobile/src/notifications/notification-routing.test.tsmobile/src/notifications/notification-routing.tsmobile/src/notifications/use-open-notification-route.tsmobile/src/transport/host-catalog-credential-join.tsmobile/src/transport/host-catalog-selection.test.tsmobile/src/transport/host-catalog-selection.tsmobile/src/transport/host-device-token-store.tsmobile/src/transport/host-list-load-sharing.tsmobile/src/transport/host-store.test.tsmobile/src/transport/host-store.tsmobile/src/transport/types.ts
| const recoveryRoute = notificationCredentialRecoveryRoute(target) | ||
| if (recoveryRoute) { | ||
| router.push(recoveryRoute) | ||
| return | ||
| } |
There was a problem hiding this comment.
🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Description: Compare push/navigate/replace usage for the home route across mobile navigation code.
rg -nP --type=ts --type=tsx -C2 "router\.(push|navigate|replace)\(\s*['\"]/['\"]" mobile || true
rg -nP -C3 "router\.navigate\(" mobile/src mobile/app || trueRepository: stablyai/orca
Length of output: 183
🌐 Web query:
expo-router router.push same route already focused duplicate stack entry navigate difference
💡 Result:
In recent versions of Expo Router (v4 and later, which align with React Navigation v7), the behavior of navigation functions has changed significantly [1][2][3]. When you use router.push to navigate to a route that is already focused or exists in the navigation stack, it will always add a new entry to the stack, effectively creating a duplicate entry [4][1][2]. The difference between common navigation methods is summarized below: 1. router.push: This function explicitly adds a new screen to the top of the navigation stack every time it is called, regardless of whether that route is already present in the history [1][5][6]. 2. router.navigate: In older versions of Expo Router, this acted as "smart" navigation (unwinding the stack if the route existed). However, in current versions (following React Navigation v7), it has been updated to function similarly to push [1][2][3]. It no longer automatically pops screens to return to an existing instance of a route [3]. 3. router.dismissTo: This is the recommended alternative for the legacy "navigate" behavior [1][2]. If you want to navigate to a route and ensure it is the only instance of that route in the stack (unwinding or "dismissing" all screens above it), use router.dismissTo('/path') [1][7]. 4. router.replace: This replaces the current screen in the stack with the new route, meaning no new entry is added, but the previous screen is removed [5][6]. If you find that your application is creating unintended duplicate stack entries, you should evaluate if your navigation logic relies on the old "smart" navigate behavior. If so, migrating those calls to router.dismissTo will generally restore the desired behavior of finding the existing route in the stack and unwinding to it [1][7]. Note: For advanced control, some developers use the getId prop on a Screen component to define how routes should be identified and handled during navigation (e.g., whether to replace the existing route or push a new one) [4][8][9].
Citations:
- 1: [expo-router] Breaking change in router navigation behavior from v3 to v4 expo/expo#35212
- 2: [docs] [expo-router] router.navigate docs are incorrect! expo/expo#37469
- 3:
router.navigate()doesn’t expose pop: true option introduced in React Navigation 7 expo/expo#40402 - 4: [router] fix router.push not pushing the same route multiple times expo/expo#27307
- 5: https://docs.expo.dev/versions/latest/sdk/router/
- 6: https://docs.expo.dev/router/basics/navigation/
- 7: <Link> does not "unwind" to the route that is already in the stack expo/expo#33014
- 8: Navigating to the same route? expo/router#506
- 9: Expo Router 4: Forced push navigation to the same route with different parameters doesn’t work expo/expo#33175
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== package refs =="
rg -n '"expo-router"|expo-router' package.json package-lock.json yarn.lock pnpm-lock.yaml 2>/dev/null || true
echo "== file outline/list =="
fd -a 'use-open-notification-route|notificationCredentialRecoveryRoute|react-native-gesture-handler' . | sed 's#^\./##' | head -100
echo "== target file =="
file="$(fd 'use-open-notification-route\.ts$' . | head -1 || true)"
if [ -n "${file:-}" ]; then
wc -l "$file"
cat -n "$file"
fi
echo "== route helper usages =="
rg -n -C4 "notificationCredentialRecoveryRoute|retry|pair-scan|router\.(push|navigate|replace|dismissTo)" . -g '*.ts' -g '*.tsx' || trueRepository: stablyai/orca
Length of output: 50370
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "== package versions =="
jq -r '
(.dependencies["expo-router"]? // .devDependencies["expo-router"]? // .overrides?["expo-router"]? // .resolutions?["expo-router"]?),
(.dependencies["`@react-navigation/native-stack`"]? // .devDependencies["`@react-navigation/native-stack`"]? // .overrides?["`@react-navigation/native-stack`"]? // .resolutions?["`@react-navigation/native-stack`"]?)
' package.json mobile/package.json 2>/dev/null || true
echo "== lockfile expo-router snippets =="
rg -n 'name: "expo-router"|/expo-router|expo-router@|version: [0-9]' yarn.lock package-lock.json pnpm-lock.yaml | head -80 || true
echo "== mobile target file =="
file="$(fd 'use-open-notification-route\.ts$' mobile . | head -1 || true)"
if [ -n "${file:-}" ]; then
wc -l "$file"
cat -n "$file"
fi
echo "== route helper definition and usages =="
rg -n -C4 "function notificationCredentialRecoveryRoute|const notificationCredentialRecoveryRoute|notificationCredentialRecoveryRoute|credential-recovery|pair-scan" mobile -g '*.ts' -g '*.tsx' -g '*.json' || true
echo "== navigation calls to home and pairing =="
rg -n -C3 "router\.(push|navigate|replace|dismissTo|setParams|canGoBack|back)\(" mobile/src mobile/app mobile -g '*.ts' -g '*.tsx' | sed -n '1,220p' || trueRepository: stablyai/orca
Length of output: 33768
🌐 Web query:
React Navigation v7 router.navigate if already focused existing stack current screen does not create new navigator
💡 Result:
In React Navigation v7, the behavior of the navigation.navigate method in a stack navigator is designed to prevent creating a new screen if you are already focused on a screen with the same name [1][2]. When you call navigate('ScreenName'): - If you are already focused on a screen with that name, React Navigation will update its parameters and will not push a new screen onto the stack [1][2]. - If you are on a different screen, it will push the new screen onto the stack [1][2]. This behavior differs from versions prior to 6.x, which would sometimes navigate back if the screen already existed in the stack [3][4]. To explicitly go back to an existing screen in the stack, you should use the popTo(screenName) method, which was introduced to replace the old navigation behavior and reduce confusion [3][4][5]. If you need to ensure that a screen appears only once in the stack regardless of where it is located, you can use the getId property on your screen definition [1][2][6]. When a screen has an ID, navigate will check for any existing route with that ID in the stack; if found, it will bring that screen into focus and update its params instead of adding a new one [1][2][6]. Note that the getId property may have limited or different support depending on whether you are using the standard Stack Navigator or the Native Stack Navigator [6].
Citations:
- 1: https://reactnavigation.org/docs/navigation-actions/
- 2: https://reactnavigation.org/docs/navigation-object
- 3: https://reactnavigation.org/docs/upgrading-from-6.x/
- 4: feat!: add
popTomethod for stack and remove going back behaviour ofnavigatereact-navigation/react-navigation#10818 - 5: https://reactnavigation.org/docs/stack-actions
- 6: https://reactnavigation.org/docs/screen/
🌐 Web query:
Expo Router router.navigate docs same screen already focused navigate vs push
💡 Result:
In recent versions of Expo Router, there is a distinct difference between router.push and router.navigate, though the behavior of the latter has been subject to updates that sometimes cause confusion in documentation [1][2]. router.push Always pushes a new instance of a route onto the navigation stack [3]. It does not check if the route already exists in the history stack, resulting in the screen being added regardless of whether it is already focused [2][3]. router.navigate Historically, this was described as "smart navigation" that would unwind or pop the stack to an existing route if it was already present, or push a new one if it was not [4][3]. However, due to updates in the underlying React Navigation library, its behavior has shifted [1][2]. In newer versions, calling router.navigate often behaves similarly to router.push by adding a new instance, or may not behave as expected for "unwinding" [1][2]. If your goal is specifically to handle screens that are already focused or to "unwind" to an existing screen in the stack (a common pattern when you want to avoid duplicate screens), you should consider: 1. router.dismissTo(href): This is the recommended approach for "unwinding" to an existing route [2]. It dismisses screens in the current stack until it reaches the target route, matching the desired "smart" behavior that was previously associated with navigation [2]. 2. Stack configuration: You can use the getId function on a <Stack.Screen /> to define unique identifiers for routes [5]. This allows the stack navigator to automatically handle duplicates; if a new route with the same ID is pushed, it will update the existing screen instead of adding a new one [5]. Because documentation can sometimes lag behind these breaking changes, developers are frequently advised to verify navigation behavior in their specific Expo Router version, as the underlying library updates (particularly React Navigation v7) have deprecated or altered the behavior of simple navigation methods [1][2].
Citations:
- 1: [docs] [expo-router] router.navigate docs are incorrect! expo/expo#37469
- 2: [expo-router] Breaking change in router navigation behavior from v3 to v4 expo/expo#35212
- 3: https://deepwiki.com/expo/expo/7.4-imperative-api-and-hooks
- 4: https://docs.expo.dev/router/basics/navigation/
- 5: https://docs.expo.dev/router/advanced/stack
Route the credential retry without duplicating home.
notificationCredentialRecoveryRoute returns / for retry, and router.push('/') adds another home instance. This happens even from the home screen, so back gestures can return to home again. Use a non-stack-adding navigation action for retry, while keeping push for /pair-scan.
There was a problem hiding this comment.
Actionable comments posted: 2
🧹 Nitpick comments (3)
mobile/src/transport/unpaired-host-credential-deletion.ts (1)
32-46: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueRemove the redundant trailing revision checks and state the guard rationale once.
Each of lines 32, 36, and 40 evaluates
shouldSkip(...)and thenwriteRevisionChanged(...).shouldSkipalready ends withwriteRevisionChangedat line 28. Noawaitruns between that final check and the call-site check, so the trailing term can never be true whenshouldSkipreturnsfalse. The extra term adds no protection and hides the actual guard sequence.Add one line that explains why the checks repeat between deletions.
♻️ Proposed simplification
return async (hostId: string, writeRevision: number): Promise<void> => { - if ((await shouldSkip(hostId, writeRevision)) || writeRevisionChanged(hostId, writeRevision)) { + // Recheck between deletions: a replacement pairing can commit a new credential mid-cleanup. + if (await shouldSkip(hostId, writeRevision)) { return } await deleteHostDeviceToken(hostId) - if ((await shouldSkip(hostId, writeRevision)) || writeRevisionChanged(hostId, writeRevision)) { + if (await shouldSkip(hostId, writeRevision)) { return } await deleteMobileRelayCredentialBundle(hostId) - if ((await shouldSkip(hostId, writeRevision)) || writeRevisionChanged(hostId, writeRevision)) { + if (await shouldSkip(hostId, writeRevision)) { return } await deleteMobileRelayDirectUpgradeJournal(hostId) if (writeRevisionChanged(hostId, writeRevision)) { return }mobile/src/transport/host-store.ts (1)
286-288: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueThe retry path captures the revision at call time, which disables the revision guard.
scheduleUnpairedHostCredentialCleanupat line 149 captures the revision when cleanup is scheduled. A later credential write then bumps the revision and cancels the delete. That is the intended guard.Line 287 captures the revision at retry time instead.
writeRevisionChangedtherefore compares the current revision against itself and always returnsfalse. For pending retries the guard contributes nothing, and correctness rests only on thehasStoredHostcheck increateUnpairedHostCredentialDeletion.The
hasStoredHostcheck does cover the re-pair case, so I see no defect today. The asymmetry is still worth making explicit. Either persist the schedule-time revision with the pending cleanup intent, or add a comment stating that this path relies on stored-host presence rather than on the revision.♻️ Proposed clarification
+ // Why: pending ids predate this call, so no schedule-time revision exists. + // Stored-host presence is the guard here; the revision compare is a no-op. return retryPendingHostCredentialCleanups((hostId) => deleteUnpairedHostCredentials(hostId, getHostCredentialWriteRevision(hostId)) )mobile/src/transport/host-store.test.ts (1)
274-284: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winAssert that
staleCleanupis defined; the optional call can make these tests pass vacuously.Lines 276-278 type
staleCleanupas possiblyundefined, and line 281 invokes it withstaleCleanup?.(HOST_ONE.id). IfremoveHoststops scheduling cleanup forHOST_ONE.id, the lookup returnsundefined, the optional call no-ops, andexpect(secureStoreMock.deleteItemAsync).not.toHaveBeenCalled()still passes. The test then reports success while covering nothing.The same pattern appears at lines 288-290 and 317-319. Add an explicit definedness assertion in each test, or extract a small helper that fails when the scheduled callback is absent.
♻️ Proposed helper and usage
+function takeScheduledCleanup(hostId: string): (id: string) => Promise<void> { + const call = scheduleCleanupMock.mock.calls.find(([id]) => id === hostId) + expect(call).toBeDefined() + return call?.[1] as (id: string) => Promise<void> +}it('does not let stale removal cleanup delete a replacement relay bundle before publication', async () => { await removeHost(HOST_ONE.id) - const staleCleanup = scheduleCleanupMock.mock.calls.find(([id]) => id === HOST_ONE.id)?.[1] as - | ((hostId: string) => Promise<void>) - | undefined + const staleCleanup = takeScheduledCleanup(HOST_ONE.id) await writeMobileRelayCredentialBundle(HOST_ONE_RELAY_BUNDLE) - await staleCleanup?.(HOST_ONE.id) + await staleCleanup(HOST_ONE.id) expect(secureStoreMock.deleteItemAsync).not.toHaveBeenCalled() })
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 55f0b3e3-4a5f-490f-b62c-86df7e4fdacc
📒 Files selected for processing (6)
mobile/src/transport/host-credential-write-revision.tsmobile/src/transport/host-store.test.tsmobile/src/transport/host-store.tsmobile/src/transport/mobile-relay-credential-bundle.tsmobile/src/transport/mobile-relay-direct-upgrade-journal.tsmobile/src/transport/unpaired-host-credential-deletion.ts
There was a problem hiding this comment.
🧹 Nitpick comments (1)
mobile/src/transport/host-credential-cleanup.test.ts (1)
82-92: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick winCover cancellation of the in-memory fallback queue.
mobile/src/transport/host-credential-cleanup.test.tscovers the persisted cleanup-intent cancellation, but no test covers cancellation aftersetItemfails. Add coverage that schedules with a write failure, callscancelPendingHostCredentialCleanup, and asserts both the fallback listener state andloadPendingHostCredentialCleanupIds()no longer surface canceled fallback cleanup IDs.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 6bc2b000-0302-41c9-981f-be63754e78ce
📒 Files selected for processing (5)
mobile/src/transport/host-credential-cleanup.test.tsmobile/src/transport/host-credential-cleanup.tsmobile/src/transport/host-store.test.tsmobile/src/transport/host-store.tsmobile/src/transport/unpaired-host-credential-deletion.ts
🚧 Files skipped from review as they are similar to previous changes (3)
- mobile/src/transport/unpaired-host-credential-deletion.ts
- mobile/src/transport/host-store.ts
- mobile/src/transport/host-store.test.ts
UI validationValidated pushed head
Electron Mobile settingsMissing credential remains visibleTemporary credential failure remains retryableMissing credential opens re-pair |
There was a problem hiding this comment.
Actionable comments posted: 1
ℹ️ Review info
⚙️ Run configuration
Configuration used: Repository UI
Review profile: CHILL
Plan: Pro Plus
Run ID: 8d6fac32-1914-4d9b-8b26-f7d751e9ac42
📒 Files selected for processing (3)
mobile/src/transport/host-metadata-store.tsmobile/src/transport/host-store.test.tsmobile/src/transport/host-store.ts
🚧 Files skipped from review as they are similar to previous changes (2)
- mobile/src/transport/host-store.test.ts
- mobile/src/transport/host-store.ts
| function parseStoredHostProfiles(raw: string | null): StoredHostProfile[] | null { | ||
| if (!raw) { | ||
| return [] | ||
| } |
There was a problem hiding this comment.
🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "Locate file:"
fd -a 'host-metadata-store\.ts$' . || true
file="$(fd 'host-metadata-store\.ts$' . | head -n 1 || true)"
if [ -n "${file:-}" ]; then
echo "File: $file"
echo "Line count:"
wc -l "$file"
echo "--- outline ---"
ast-grep outline "$file" || true
echo "--- relevant content ---"
cat -n "$file" | sed -n '1,220p'
fi
echo "--- searches for relevant functions/usages ---"
rg -n "parseStoredHostProfiles|readStoredHostProfilesForMutation|write|setItem|getItem|storedHostProfiles|host-metadata" . --glob '!node_modules' --glob '!dist' --glob '!build' || trueRepository: stablyai/orca
Length of output: 50370
🏁 Script executed:
#!/bin/bash
set -euo pipefail
file="mobile/src/transport/host-metadata-store.ts"
if [ ! -f "$file" ]; then
file="$(find mobile -name host-metadata-store.ts 2>/dev/null | head -n 1 || true)"
fi
echo "Target file: $file"
if [ -z "${file:-}" ] || [ ! -f "$file" ]; then
echo "File not found"
exit 0
fi
echo "--- candidate files ---"
find mobile/src -name '*host*' -o -name '*metadata*' -o -name '*profile*' 2>/dev/null | head -100 || true
echo "--- host-metadata-store.ts line count ---"
wc -l "$file"
echo "--- host-metadata-store.ts ---"
cat -n "$file"
echo "--- focused search in mobile ---"
rg -n "parseStoredHostProfiles|readStoredHostProfilesForMutation|writeStoredHostProfilesForMutation|getItem\\(|setItem\\(|host-metadata|StoredHostProfile" mobile --glob '!**/*.test.*' --glob '!**/*.spec.*' || true
echo "--- tests in mobile ---"
rg -n "parseStoredHostProfiles|readStoredHostProfilesForMutation|writeStoredHostProfilesForMutation|getItem\\(|setItem\\(|host-metadata|StoredHostProfile" mobile --glob '*test*' --glob '*spec*' || trueRepository: stablyai/orca
Length of output: 15890
🏁 Script executed:
#!/bin/bash
set -euo pipefail
echo "--- host-store.ts ---"
cat -n mobile/src/transport/host-store.ts | sed -n '1,240p'
echo "--- host-store.test.ts ---"
cat -n mobile/src/transport/host-store.test.ts | sed -n '1,320p'
echo "--- types host profile schema ---"
cat -n mobile/src/transport/types.ts | sed -n '80,120p'
echo "--- parser behavior probe as file text only ---"
python3 - <<'PY'
from pathlib import Path
p = Path("mobile/src/transport/host-metadata-store.ts")
text = p.read_text()
cases = {
"missing": None,
"empty": "",
"blank": " \t",
"non_array": "{}",
"empty_array": "[]",
}
print("function body contains:")
for needle in ["if (!raw)", "if (raw === null)", "try {", "return null"]:
print(f"{needle!r}: {needle in text}")
PYRepository: stablyai/orca
Length of output: 26611
Treat only a missing host-list key as an empty array.
raw is a stored payload when it is ''; parseStoredHostProfiles('') currently returns [] instead of null. That lets resolvePairingHostIdentity() load an empty host list and later call writeStoredHostProfiles([...]), overwriting the malformed '' key. Use raw === null and add a regression test for the empty-string case.
Proposed fix
function parseStoredHostProfiles(raw: string | null): StoredHostProfile[] | null {
- if (!raw) {
+ if (raw === null) {
return []
}📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| function parseStoredHostProfiles(raw: string | null): StoredHostProfile[] | null { | |
| if (!raw) { | |
| return [] | |
| } | |
| function parseStoredHostProfiles(raw: string | null): StoredHostProfile[] | null { | |
| if (raw === null) { | |
| return [] | |
| } |
|
Electron QA evidence for
|
iOS simulator validationValidated exact HEAD
|
…blyai#12775) * fix(mobile): keep hosts visible when credentials are unavailable * fix(mobile): guard unavailable host recovery * fix(mobile): protect replacement credential writes * fix(mobile): retain superseded cleanup intents * fix(mobile): preserve credential cleanup authority * fix(mobile): make host cleanup crash-safe







Summary
Root cause
Host metadata and device tokens are stored separately. The previous host-list join silently omitted metadata whenever SecureStore threw or returned null, so a refresh after pairing could make an existing host disappear. Same-key pairing cleanup also mutated metadata before the replacement credential was durable, and stale cleanup could delete newer credentials or clear retry intent after a failed replacement write.
Testing