Skip to content

refactor: remove unsafe assertions from navigation and debug helpers - #100768

Merged
blimpich merged 10 commits into
Expensify:mainfrom
KJ21-ENG:seatbelt-v2/batch1-group1-43192ddd
Oct 26, 2026
Merged

blimpich merged 10 commits into
Expensify:mainfrom
KJ21-ENG:seatbelt-v2/batch1-group1-43192ddd

Conversation

@KJ21-ENG

@KJ21-ENG KJ21-ENG commented Sep 9, 2026 •

Copy link
Copy Markdown
Contributor

Explanation of Change

Remove unsafe assertions from navigation state, nested action parameters, and development debug getters. Known routes keep their navigation behavior. Invalid nested parameters stop the sidebar-marker traversal at the last safe object; debug Onyx reads use Onyx's public get, and the debug-only Onyx.log is declared optional because it exists only after non-production setup. Transaction lookup now prefers modern object messages, using legacy originalMessage for array or absent messages; a modern message without a linked ID does not reuse that action's legacy ID. Lookup preserves direct route ID priority, then the parent IOU action, then the first report IOU action with a nonempty linked ID in iteration order.

Fixed Issues

$ #94739
PROPOSAL: #94739 (comment)

Tests

Upstream Jest, typecheck and lint passed. The navigation suites cover path parsing and serialization.

Platforms: Android native, Android mWeb Chrome, iOS native, iOS mWeb Safari and macOS Chrome/Safari. Run desktop-only steps where applicable. Use browser Back/Forward on web and the App back control on native.

Report and message links

Setup: Use a conversation with links to another report and a specific message, plus an existing attachment.

  1. Follow the report link. Verify the intended report opens.
  2. Go Back. Verify the starting conversation returns directly.
  3. Follow the message link. Verify the intended message opens.
  4. On web, go Back, Forward, then Back. Verify the same message target and starting conversation return without duplicate history steps.
  5. Open the attachment, then close it. Verify the same conversation returns.

Workspace navigation

Setup: Use two accessible rooms in different workspaces and an account with workspace-member access.

  1. Open room details for each room. Verify the workspace label matches its room.
  2. Close details. Verify the original room returns.
  3. In a narrow layout, open Workspaces → Search Members → workspace → Members.
  4. Go Back. Verify Workspaces returns without an extra sidebar step.

Concierge return

  1. Open About → Report a bug. Verify Concierge opens.
  2. Go Back without sending a message. Verify About returns.

Development debug getters

Setup: Use a development web build and an existing expense thread. These getters are unavailable in production.

  1. In browser developer tools, read await window.report. Verify its ID matches the open report.
  2. Read await window.transaction. Verify its ID matches the open expense.
  3. Open the expense’s workspace and read await window.policy. Verify its ID matches that workspace.
  4. For a route without an associated record, verify the corresponding getter returns undefined without hanging or throwing.
  5. Run Onyx.log('session'). Verify the stored session value prints in the console.

Offline tests

No additional offline case: request queuing, persistence and reconnect handling are unchanged.

QA Steps

Same as the navigation cases in Tests. Development debug getters require a development build.

PR Author Checklist

  • I linked the correct issue in the ### Fixed Issues section above
  • I wrote clear testing steps that cover the changes made in this PR
    • I added steps for local testing in the Tests section
    • I added steps for the expected offline behavior in the Offline steps section
    • I added steps for Staging and/or Production testing in the QA steps section
    • I added steps to cover failure scenarios (i.e. verify an input displays the correct error message if the entered data is not correct)
    • I turned off my network connection and tested it while offline to ensure it matches the expected behavior (i.e. verify the default avatar icon is displayed if app is offline)
    • I tested this PR with a High Traffic account against the staging or production API to ensure there are no regressions (e.g. long loading states that impact usability).
  • I included screenshots or videos for tests on all platforms
  • I ran the tests on all platforms & verified they passed on:
    • Android: Native
    • Android: mWeb Chrome
    • iOS: Native
    • iOS: mWeb Safari
    • MacOS: Chrome / Safari
  • I verified there are no console errors (if there's a console error not related to the PR, report it or open an issue for it to be fixed)
  • I followed proper code patterns (see Reviewing the code)
    • I verified that comments were added to code that is not self explanatory
    • I verified that any new or modified comments were clear, correct English, and explained "why" the code was doing something instead of only explaining "what" the code was doing.
    • I verified any copy / text that was added to the app is grammatically correct in English. It adheres to proper capitalization guidelines (note: only the first word of header/labels should be capitalized), and is either coming verbatim from figma or has been approved by marketing (in order to get marketing approval, ask the Bug Zero team member to add the Waiting for copy label to the issue)
  • If a new code pattern is added I verified it was agreed to be used by multiple Expensify engineers
  • I followed the guidelines as stated in the Review Guidelines
  • I tested other components that can be impacted by my changes (i.e. if the PR modifies a shared library or component like Avatar, I verified the components using Avatar are working as expected)
  • If a new CSS style is added I verified that:
    • A similar style doesn't already exist
    • The style can't be created with an existing StyleUtils function (i.e. StyleUtils.getBackgroundAndBorderStyle(theme.componentBG))
  • If new assets were added or existing ones were modified, I verified that:
    • The assets are optimized and compressed (for SVG files, run npm run compress-svg)
    • The assets load correctly across all supported platforms.
  • If the PR modifies code that runs when editing or sending messages, I tested and verified there is no unexpected behavior for all supported markdown - URLs, single line code, code blocks, quotes, headings, bold, strikethrough, and italic.
  • If the PR modifies a generic component, I tested and verified that those changes do not break usages of that component in the rest of the App (i.e. if a shared library or component like Avatar is modified, I verified that Avatar is working as expected in all cases)
  • If the PR modifies a component related to any of the existing Storybook stories, I tested and verified all stories for that component are still working as expected.
  • If the PR modifies a component or page that can be accessed by a direct deeplink, I verified that the code functions as expected when the deeplink is used - from a logged in and logged out account.
  • If the PR modifies the UI (e.g. new buttons, new UI components, changing the padding/spacing/sizing, moving components, etc) or modifies the form input styles:
    • I verified that all the inputs inside a form are aligned with each other.
    • I added Design label and/or tagged @Expensify/design so the design team can review the changes.
  • I added unit tests for any new feature or bug fix in this PR to help automatically prevent regressions in this user flow.
  • If the main branch was merged into this PR after a review, I tested again and verified the outcome was still expected according to the Test steps.

Screenshots/Videos

Recordings (5)
01-report-message-links-narrow.mp4
02-room-context-desktop.mp4
03-members-return-narrow.mp4
04-concierge-return-narrow.mp4
05-marked-message-forward-desktop.mp4

Seatbelt-Operation: s08-43192ddd-4541881-sign-1
Seatbelt-Operation: recovery-20260924-100768-merge-sign-1
@codecov

codecov Bot commented Sep 25, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ Changes either increased or maintained existing code coverage, great job!

Files with missing lines Coverage Δ
...s/Navigation/helpers/getMatchingFullScreenRoute.ts 80.76% <100.00%> (ø)
src/libs/Navigation/helpers/getPathFromState.ts 96.42% <100.00%> (+0.48%) ⬆️
src/libs/Navigation/helpers/getStateFromPath.ts 95.83% <100.00%> (ø)
.../libs/Navigation/helpers/hasDifferentSplitScope.ts 100.00% <100.00%> (ø)
...libs/Navigation/helpers/linkTo/getMinimalAction.ts 100.00% <100.00%> (ø)
src/libs/Navigation/helpers/linkTo/index.ts 94.92% <100.00%> (+0.07%) ⬆️
...ibs/Navigation/helpers/replacePathInNestedState.ts 80.00% <100.00%> (ø)
src/setup/addUtilsToWindow.ts 97.53% <100.00%> (+81.09%) ⬆️
...libs/Navigation/helpers/getAdaptedStateFromPath.ts 83.33% <77.77%> (ø)
... and 23 files with indirect coverage changes

Seatbelt-Operation: recovery-20260925-100768-knip-sign-1
Seatbelt-Operation: main-refresh-100768-20261014-sign-db381862
Seatbelt-Operation: main-refresh-100768-20261014-26cd-sign-53276dcc
Seatbelt-Operation: remaining-100768-oneoff-sign-c34274b3-afc2-4902-8306-972be711fed8
@KJ21-ENG KJ21-ENG changed the title Remove unsafe assertions from navigation and debug helpers refactor: remove unsafe assertions from navigation and debug helpers Oct 19, 2026
@KJ21-ENG
KJ21-ENG marked this pull request as ready for review October 22, 2026 19:55
@KJ21-ENG
KJ21-ENG requested review from a team as code owners October 22, 2026 19:55
@melvin-bot
melvin-bot Bot requested review from garrettmknight and ikevin127 and removed request for a team October 22, 2026 19:55
@melvin-bot

melvin-bot Bot commented Oct 22, 2026

Copy link
Copy Markdown

@ikevin127 Please copy/paste the Reviewer Checklist from here into a new comment on this PR and complete it. If you have the K2 extension, you can simply click: [this button]

@melvin-bot
melvin-bot Bot removed the request for review from a team October 22, 2026 19:55
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 22, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-22T20:31:30.534484Z 0eebc62 Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@ikevin127

ikevin127 commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

Reviewer Checklist

  • I have verified the author checklist is complete (all boxes are checked off).
  • I verified the correct issue is linked in the ### Fixed Issues section above
  • I verified testing steps are clear and they cover the changes made in this PR
    • I verified the steps for local testing are in the Tests section
    • I verified the steps for Staging and/or Production testing are in the QA steps section
    • I verified the steps cover any possible failure scenarios (i.e. verify an input displays the correct error message if the entered data is not correct)
    • I turned off my network connection and tested it while offline to ensure it matches the expected behavior (i.e. verify the default avatar icon is displayed if app is offline)
  • I checked that screenshots or videos are included for tests on all platforms
  • I included screenshots or videos for tests on all platforms
  • I verified that the composer does not automatically focus or open the keyboard on mobile unless explicitly intended. This includes checking that returning the app from the background does not unexpectedly open the keyboard.
  • I verified tests pass on all platforms & I tested again on:
    • Android: HybridApp
    • Android: mWeb Chrome
    • iOS: HybridApp
    • iOS: mWeb Safari
    • MacOS: Chrome / Safari
  • If there are any errors in the console that are unrelated to this PR, I either fixed them (preferred) or linked to where I reported them in Slack
  • I verified proper code patterns were followed (see Reviewing the code)
    • I verified that comments were added to code that is not self explanatory
    • I verified that any new or modified comments were clear, correct English, and explained "why" the code was doing something instead of only explaining "what" the code was doing.
    • I verified any copy / text that was added to the app is grammatically correct in English. It adheres to proper capitalization guidelines (note: only the first word of header/labels should be capitalized), and is either coming verbatim from figma or has been approved by marketing (in order to get marketing approval, ask the Bug Zero team member to add the Waiting for copy label to the issue)
  • If a new code pattern is added I verified it was agreed to be used by multiple Expensify engineers
  • I verified that this PR follows the guidelines as stated in the Review Guidelines
  • I verified other components that can be impacted by these changes have been tested, and I retested again (i.e. if the PR modifies a shared library or component like Avatar, I verified the components using Avatar have been tested & I retested again)
  • If a new component is created I verified that:
    • A similar component doesn't exist in the codebase
    • All props are defined accurately
    • The component has a clear name that is non-ambiguous and the purpose of the component can be inferred from the name alone
    • The only data being stored in the state is data necessary for rendering and nothing else
    • The component has the minimum amount of code necessary for its purpose, and it is broken down into smaller components in order to separate concerns and functions
  • If a new CSS style is added I verified that:
    • A similar style doesn't already exist
    • The style can't be created with an existing StyleUtils function (i.e. StyleUtils.getBackgroundAndBorderStyle(theme.componentBG)
  • If the PR modifies code that runs when editing or sending messages, I tested and verified there is no unexpected behavior for all supported markdown - URLs, single line code, code blocks, quotes, headings, bold, strikethrough, and italic.
  • If the PR modifies a generic component, I tested and verified that those changes do not break usages of that component in the rest of the App (i.e. if a shared library or component like Avatar is modified, I verified that Avatar is working as expected in all cases)
  • If the PR modifies a component related to any of the existing Storybook stories, I tested and verified all stories for that component are still working as expected.
  • If the PR modifies a component or page that can be accessed by a direct deeplink, I verified that the code functions as expected when the deeplink is used - from a logged in and logged out account.
  • If the PR modifies the UI (e.g. new buttons, new UI components, changing the padding/spacing/sizing, moving components, etc) or modifies the form input styles:
    • I verified that all the inputs inside a form are aligned with each other.
    • I added Design label and/or tagged @Expensify/design so the design team can review the changes.
  • If the PR adds or modifies the UI:
    • I asked an AI agent to review the changes for accessibility issues and addressed its findings.
    • I tested with a screen reader (VoiceOver on macOS) and verified all new/changed elements are reachable with a logical focus order.
    • I verified all new/changed elements have meaningful accessible names and roles.
    • I verified state changes are announced (e.g. checked/unchecked, expanded/collapsed, selected).
  • For any bug fix or new feature in this PR, I verified that sufficient unit tests are included to prevent regressions in this flow.
  • If the main branch was merged into this PR after a review, I tested again and verified the outcome was still expected according to the Test steps.
  • I have checked off every checkbox in the PR reviewer checklist, including those that don't apply to this PR.

Screenshots/Videos

Screen.Recording.2026-10-22.at.15.54.49.mov

@ikevin127 ikevin127 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

No hard blockers, but a few code-comments need addressed. Please tag me once that's done.

const currentTopRoute = currentState.routes[currentState.index];
if (currentTopRoute?.name !== NAVIGATORS.TAB_NAVIGATOR && typedPayload.name === NAVIGATORS.TAB_NAVIGATOR) {
(action as {type: string}).type = CONST.NAVIGATION.ACTION_TYPE.PUSH;
if (currentTopRoute?.name !== NAVIGATORS.TAB_NAVIGATOR && 'payload' in action && action.payload && 'name' in action.payload && action.payload.name === NAVIGATORS.TAB_NAVIGATOR) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 isNamedActionPayload is already imported in this file, so this inline narrowing can reuse it:

if (currentTopRoute?.name !== NAVIGATORS.TAB_NAVIGATOR && isNamedActionPayload(action.payload) && action.payload.name === NAVIGATORS.TAB_NAVIGATOR) {

👁️ Written by AI, reviewed by Kevin.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reused the existing isNamedActionPayload(action.payload) predicate at this site. The route-name comparison and dispatch behavior are unchanged.

}

const {action: resolvedAction, isFocusedRouteInDifferentScope} = getMinimalAction(action, navigation.getRootState());
const resolvedActionName = resolvedAction.payload && 'name' in resolvedAction.payload && typeof resolvedAction.payload.name === 'string' ? resolvedAction.payload.name : undefined;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Same here, isNamedActionPayload covers this:

const resolvedActionName = isNamedActionPayload(resolvedAction.payload) ? resolvedAction.payload.name : undefined;

👁️ Written by AI, reviewed by Kevin.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated this site to use isNamedActionPayload(resolvedAction.payload) too, retaining the undefined fallback when the payload has no string name.

Comment thread src/setup/addUtilsToWindow.ts Outdated
window.Onyx.get = function (key: CollectionKeyBase) {
function get<TKey extends OnyxKey>(key: TKey): Promise<OnyxValue<TKey>> {
return new Promise((resolve) => {
const connectionReference: {current?: ReturnType<typeof Onyx.connectWithoutView>} = {};

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 The connectionReference / isResolved handling is for a synchronous callback, which can't happen.

OnyxConnectionManager.connect defers it with Promise.resolve().then(...), so "the result connection object is available when the callback fires".

The original get had no assertion, so can we keep its body and only change the signature?

function get<TKey extends OnyxKey>(key: TKey): Promise<OnyxValue<TKey>> {
    return new Promise((resolve) => {
        const connection = Onyx.connectWithoutView({
            key,
            callback: (value) => {
                Onyx.disconnect(connection);
                resolve(value);
            },
        });
    });
}

👁️ Written by AI, reviewed by Kevin.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removed the synchronous-callback bookkeeping and now disconnect the captured connection before resolving the one-shot read. The installed Onyx 3.0.117 defers initial delivery through PendingWrites. Tests using real Onyx verify deferred delivery, the exact disconnect handle, and ordinary-key, collection-member, and collection-root reads. I also aligned the public get declaration with the existing producer’s generic key/value signature so those valid calls remain fully typed.

Comment thread src/setup/addUtilsToWindow.ts Outdated
const parentReportActions = await onyxWithDebugUtils.get(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${report.parentReportID}`);
const parentAction = parentReportActions?.[report.parentReportActionID];
// Debug lookups intentionally prefer the legacy message even when a modern message exists.
const parentMessage = parentAction ? getOriginalMessage({...parentAction, message: undefined}) : undefined;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 getOriginalMessage({...parentAction, message: undefined}) copies the action just to force the legacy field, so it misses the ID when the original message lives in message.

getLinkedTransactionID from ReportActionsUtils already does this lookup (with the isMoneyRequestAction check). Can we use it here and in the fallback loop below?

const parentTransactionID = getLinkedTransactionID(parentReportActions?.[report.parentReportActionID]);
if (parentTransactionID) {
    return parentTransactionID;
}

// ...

for (const action of Object.values(reportActions ?? {})) {
    const transactionID = getLinkedTransactionID(action);
    if (transactionID) {
        return transactionID;
    }
}

👁️ Written by AI, reviewed by Kevin.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Replaced both forced-legacy message copies with getLinkedTransactionID. Lookup still prefers the direct route ID, then the parent action, then the first valid fallback action. The tests cover modern and legacy messages, conflicting IDs, IOU-action filtering, missing/empty IDs, and parent-versus-fallback priority using the real message helpers.

Comment thread src/setup/addUtilsToWindow.ts Outdated
const getReportID = async (params: Record<string, string> | undefined) => {
if (params?.reportID) {
async function getReportID(params: ReturnType<typeof getRouteParams>): Promise<string | undefined> {
if (params && typeof params === 'object' && 'reportID' in params && typeof params.reportID === 'string' && params.reportID) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 This params && typeof params === 'object' && 'X' in params && typeof params.X === 'string' && params.X guard is repeated 5 times in this file.

Can we extract one helper (isRecord from @libs/ObjectUtils)?

function getStringRouteParam(params: ReturnType<typeof getRouteParams>, key: 'reportID' | 'transactionID' | 'policyID'): string | undefined {
    if (!isRecord(params)) {
        return undefined;
    }
    const value = params[key];
    return typeof value === 'string' && value ? value : undefined;
}

👁️ Written by AI, reviewed by Kevin.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added one local getStringRouteParam helper using isRecord and reused it at all five sites. It accepts only nonempty strings without coercion or trimming. The getter tests cover missing, empty, invalid, and valid parameters while preserving direct-route and report/parent fallback priorities.

newRoutes[index] = {...focusedRoute, state: nestedResult};
return {...state, routes: newRoutes, index} as State;
// Rebuild from the narrowed state to preserve full and partial route categories.
if (state.stale === false) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 No tests were added, and Codecov shows this file at 63.63% patch coverage (-9.05%).

The existing getPathFromStateTests.ts states have no stale, so only the partial branch runs. This stale === false branch is the one the app hits with a full root state.

Can we add stale: false cases for:

  • a nested dynamic route
  • removing a sibling route

👁️ Written by AI, reviewed by Kevin.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Added two complete stale: false state cases: nested full-state rebuilding and removal of a focused dynamic sibling from the middle of a full root. Both assert the resulting path, the exact reduced state passed to the base serializer, and input immutability. Coverage confirms both full-state branches execute, and mutation probes catch dropping the nested rebuild or removing the wrong sibling.

}

let actualSuffix = buildSuffixFromPattern(suffixPattern, focusedRoute?.params as Record<string, unknown> | undefined);
let actualSuffix = buildSuffixFromPattern(suffixPattern, focusedRoute?.params ? {...focusedRoute.params} : undefined);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 {...focusedRoute.params} makes a copy only to get a Record<string, unknown>. isRecord narrows it without the copy, matching the rest of this PR:

isRecord(focusedRoute?.params) ? focusedRoute.params : undefined

Same for both shallowCompare arguments in linkTo/index.ts:61.

👁️ Written by AI, reviewed by Kevin.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removed the params copies in the serializer and both shallow-comparison inputs, using isRecord to narrow the original values directly. Necessary state/action copies remain. Serializer tests and production linkTo probes cover absent, empty, equal, and different record parameters.

Seatbelt-Operation: 2039c3a5-1f02-40d5-aa18-aea6dce4e324

@ikevin127 ikevin127 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the changes! All 7 previous threads are fixed in f8f3f3c, the new code breaks nothing, and the PR description matches the code. I posted 1 🟡 and 2 🟢, all in the new code, none of them block - but should be addressed before merging.

Please tag me once addressed 🙌

Comment thread src/setup/addUtilsToWindow.ts Outdated
}

function getStringRouteParam(params: ReturnType<typeof getRouteParams>, key: 'reportID' | 'transactionID' | 'policyID'): string | undefined {
if (!isRecord(params) || !hasKey(params, key)) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 hasKey doesn't add anything after isRecord. params is already a Record<string, unknown>, so params[key] is unknown and the typeof check below handles a missing key.

if (!isRecord(params)) {
    return undefined;
}

👁️ Written by AI, reviewed by Kevin.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Removed hasKey and its import. After the isRecord check, I use a checked local Record<string, unknown> assignment before indexing because TypeScript retains the existing route-parameter union. The lookup remains unknown, and the existing string/nonempty check handles missing or invalid values. No cast or additional runtime guard was added.

Comment thread tests/unit/addUtilsToWindowTest.ts Outdated
Comment on lines +280 to +287
['report_report' satisfies OnyxKey]: {reportID: 'report', parentReportID: 'parent', parentReportActionID: 'parent-action'} satisfies Report,
['reportActions_parent' satisfies OnyxKey]: {[parentAction.reportActionID]: parentAction},
['reportActions_report' satisfies OnyxKey]: {
fallback: {...iouAction, reportActionID: 'fallback', message: {type: CONST.IOU.REPORT_ACTION_TYPE.CREATE, text: '', IOUTransactionID: 'fallback'}},
},
['transactions_modern' satisfies OnyxKey]: modernTransaction,
['transactions_legacy' satisfies OnyxKey]: legacyTransaction,
['transactions_fallback' satisfies OnyxKey]: fallbackTransaction,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Can we build these keys from ONYXKEYS like the rest of this file already does (${ONYXKEYS.COLLECTION.REPORT}report, L330)?

There are about 25 hard-coded prefixes ('report_', 'reportActions_', 'transactions_', 'policy_'). satisfies OnyxKey only checks that some collection prefix matches, so it won't catch a renamed key.

[`${ONYXKEYS.COLLECTION.REPORT}report`]: {reportID: 'report', parentReportID: 'parent', parentReportActionID: 'parent-action'} satisfies Report,
[`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}parent`]: {[parentAction.reportActionID]: parentAction},
[`${ONYXKEYS.COLLECTION.TRANSACTION}modern`]: modernTransaction,

👁️ Written by AI, reviewed by Kevin.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Replaced all 27 literal collection-prefix occurrences in the fixtures and expected results with the corresponding ONYXKEYS.COLLECTION constants. The suffixes, fixture values, and expected results are preserved.

Comment thread tests/unit/addUtilsToWindowTest.ts Outdated
// Then resolution follows one disconnect of the returned handle and later writes have no live subscription.
expect(value).toEqual(modernTransaction);
expect(disconnect).toHaveBeenCalledTimes(1);
expect(connect).toHaveReturnedWith(disconnect.mock.calls.at(0)?.[0]);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 The same connect, disconnect and exact-handle block is repeated in 4 tests (here, L155, L175, and 3 times in the collection-root test).

Can we extract one helper so each test only shows what's different? It counts relative to the calls already made, so repeated reads in one test still work.

async function readOnce<TKey extends OnyxKey>(key: TKey) {
    const connect = jest.spyOn(Onyx, 'connectWithoutView');
    const disconnect = jest.spyOn(Onyx, 'disconnect');
    const disconnectsBefore = disconnect.mock.calls.length;
    const result = window.Onyx.get(key);
    expect(disconnect).toHaveBeenCalledTimes(disconnectsBefore);
    const value = await result;
    expect(disconnect).toHaveBeenCalledTimes(disconnectsBefore + 1);
    expect(connect).toHaveLastReturnedWith(disconnect.mock.calls.at(-1)?.[0]);
    return value;
}

👁️ Written by AI, reviewed by Kevin.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Extracted one generic readDebugOnyxOnce helper and reused it at all six read sites. It checks connection/disconnection counts relative to the calls already made, deferred delivery, and the exact successful connection handle. Each test retains its scenario-specific value assertions and later-write checks, including the repeated collection-root reads.

Seatbelt-Operation: 981bc10d-de59-405e-a1ed-f597bf83c62e
@KJ21-ENG

Copy link
Copy Markdown
Contributor Author

Hi @ikevin127, addressed the redundant guard, collection keys, and repeated test assertions. Could you please take another look?

@ikevin127 ikevin127 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 LGTM - Author addressed all 3 comments from my Oct 23 round in c7072cb, and that commit introduces no problems. I posted one optional 🟢.

Comment thread src/setup/addUtilsToWindow.ts Outdated
if (!isRecord(params)) {
return undefined;
}
const recordParams: Record<string, unknown> = params;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟢 Can we type params as unknown instead? Then isRecord narrows it straight to Record<string, unknown> and the extra alias goes away.

function getStringRouteParam(params: unknown, key: 'reportID' | 'transactionID' | 'policyID'): string | undefined {
    if (!isRecord(params)) {
        return undefined;
    }
    const value = params[key];
    return typeof value === 'string' && value ? value : undefined;
}

👁️ Written by AI, reviewed by Kevin.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Changed params to unknown, so isRecord now narrows it directly to Record<string, unknown> and the recordParams alias is gone. The guard, key union and nonempty-string check are unchanged, and callers keep their existing types.

@melvin-bot
melvin-bot Bot requested a review from blimpich October 24, 2026 22:11
Seatbelt-Operation: ea2c4845-1b6f-4086-a320-6f4997a308b7
Seatbelt-Operation: 340c0d02-b546-4639-a70e-7253bfa02749
@KJ21-ENG

KJ21-ENG commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor Author

Hi @ikevin127, after your approval, #102135 (Onyx 3.0.119) merged and conflicted with this PR in addUtilsToWindow.ts and react-native-onyx.d.ts. That PR adds a public Onyx.get, removes the debug window.Onyx.get wrapper, and adds the no-unsafe-onyx-read lint rule. I merged main in 643dae9 and resolved it like this:

  • Dropped our custom get and its declaration. The debug helpers now use the native window.Onyx.get.
  • Exposed Onyx with the plain window.Onyx = Onyx, the one use the new rule allows, and then attached log. To avoid an as cast there, log is now optional on Window.Onyx, since it only exists after non-production setup.
  • Removed the tests for the deleted get (readDebugOnyxOnce). The report/transaction/policy getter tests are unchanged, and I added tests for the native get and log output.
  • Kept your params: unknown suggestion from 0711258.

The other files are unchanged from what you approved.

@blimpich
blimpich merged commit d3f5dbb into Expensify:main Oct 26, 2026
38 of 40 checks passed
@OSBotify

Copy link
Copy Markdown
Contributor

✋ This PR was not deployed to staging yet because QA is ongoing. It will be automatically deployed to staging after the next production release.

@github-actions

Copy link
Copy Markdown
Contributor

🚧 blimpich has triggered a test Expensify/App build. You can view the workflow run here.

@github-actions

Copy link
Copy Markdown
Contributor

@OSBotify

Copy link
Copy Markdown
Contributor

🚀 Deployed to staging by https://github.com/blimpich in version: 9.5.21-0 🚀

platform result
🕸 web 🕸 success ✅
🤖 android 🤖 success ✅
🍎 iOS 🍎 success ✅

@MelvinBot

Copy link
Copy Markdown
Contributor

No help site update is needed. This PR removes unsafe type assertions in navigation helpers and development-only debug getters, so users see the same navigation and features as before.


view run

@OSBotify

Copy link
Copy Markdown
Contributor

🚀 Deployed to staging by https://github.com/blimpich in version: 9.5.23-0 🚀

platform result
🕸 web 🕸 success ✅
🤖 android 🤖 success ✅
🍎 iOS 🍎 success ✅

@MelvinBot

Copy link
Copy Markdown
Contributor

No help site update is needed. This PR only removes unsafe type assertions in navigation helpers and development-only debug getters, so user-facing navigation and features are unchanged.


view run

@OSBotify

Copy link
Copy Markdown
Contributor

🚀 Deployed to production by https://github.com/jasperhuangg in version: 9.5.23-3 🚀

platform result
🕸 web 🕸 success ✅
🤖 android 🤖 success ✅
🍎 iOS 🍎 success ✅

Bundle Size Analysis (Sentry):

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants