Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Tighten Dispatch type - HELP WANTED #17204

Open
wants to merge 5 commits into
base: develop
Choose a base branch
from

Conversation

komret
Copy link
Contributor

@komret komret commented Feb 24, 2025

Trying to tighten Dispatch type so that it provides some type security to our actions, preventing bugs like this one.

1st commit changes the Dispatch type and fixes code wherever I more or less knew what to do.
2nd commit skips type check for lines that I couldn't fix - HELP WANTED.
3rd commit fixes types related to metadata, @mroz22, please check.

QA: Some cleanup in code related to labelling and password manager. It would be good to test that nothing was broken in the process.

@komret komret added the code Code improvements label Feb 24, 2025
Copy link

github-actions bot commented Feb 24, 2025

🚀 Expo preview is ready!

  • Project → trezor-suite-preview
  • Platforms → android, ios
  • Scheme → trezorsuitelite
  • Runtime Version → 26
  • More info

Learn more about 𝝠 Expo Github Action

@komret komret force-pushed the chore/tighten-dispatch-type branch 3 times, most recently from c3806ed to 57a9a9a Compare February 27, 2025 15:33
@komret komret marked this pull request as ready for review February 27, 2025 15:35
@komret komret added the no-project This label is used to specify that PR doesn't need to be added to a project label Feb 27, 2025
Copy link

coderabbitai bot commented Feb 27, 2025

Warning

Rate limit exceeded

@komret has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 7 minutes and 11 seconds before requesting another review.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

📥 Commits

Reviewing files that changed from the base of the PR and between 4f176e3 and 0b7bf7d.

📒 Files selected for processing (10)
  • packages/suite/src/actions/suite/guideActions.ts (1 hunks)
  • packages/suite/src/actions/suite/metadataActions.ts (4 hunks)
  • packages/suite/src/actions/suite/metadataPasswordsActions.ts (3 hunks)
  • packages/suite/src/actions/suite/metadataProviderActions.ts (1 hunks)
  • packages/suite/src/actions/suite/modalActions.ts (1 hunks)
  • packages/suite/src/actions/suite/routerActions.ts (1 hunks)
  • packages/suite/src/actions/suite/suiteActions.ts (2 hunks)
  • packages/suite/src/middlewares/suite/routerMiddleware.ts (1 hunks)
  • packages/suite/src/reducers/suite/metadataReducer.ts (1 hunks)
  • packages/suite/src/types/suite/index.ts (2 hunks)

Walkthrough

The pull request refines type declarations and action payload definitions across various modules. Functions now have explicit return types—for example, the unsetNode function is updated to return a specific type rather than the default any. Action creators and reducers have been adjusted: payload types are tightened by specifying partial picks or unions, and conditions for state updates are modified to check for the presence of required properties. In some cases, variable renaming improves clarity, and several TypeScript error suppression comments have been added to annotate known type issues without altering overall logic. Changes are applied to metadata, provider, modal, router, and suite-related actions, as well as middleware and type definitions within the Redux configuration. The modifications enhance consistency in how action types and payloads are handled without affecting the underlying business logic.


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
suite-common/metadata-types/src/metadataTypes.ts (1)

197-197: Clean up potential type redundancy.

Extending Labels to include PasswordManagerState makes sense, but there's a redundancy in the Data type definition (line 201-204) which now has Labels | PasswordManagerState where Labels already includes PasswordManagerState.

Consider refactoring the Data type definition to:

-type Data = Record<
-    LabelableEntityKeys['fileName'], // unique "id" for mapping with labelable entitties
-    Labels | PasswordManagerState
->;
+type Data = Record<
+    LabelableEntityKeys['fileName'], // unique "id" for mapping with labelable entitties
+    Labels
+>;
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 89011d7 and 57a9a9a.

📒 Files selected for processing (12)
  • packages/suite/src/actions/suite/guideActions.ts (1 hunks)
  • packages/suite/src/actions/suite/metadataActions.ts (4 hunks)
  • packages/suite/src/actions/suite/metadataPasswordsActions.ts (3 hunks)
  • packages/suite/src/actions/suite/metadataProviderActions.ts (1 hunks)
  • packages/suite/src/actions/suite/modalActions.ts (1 hunks)
  • packages/suite/src/actions/suite/routerActions.ts (1 hunks)
  • packages/suite/src/actions/suite/suiteActions.ts (2 hunks)
  • packages/suite/src/middlewares/suite/routerMiddleware.ts (1 hunks)
  • packages/suite/src/reducers/suite/metadataReducer.ts (1 hunks)
  • packages/suite/src/types/suite/index.ts (2 hunks)
  • suite-common/metadata-types/src/metadataTypes.ts (1 hunks)
  • suite-common/redux-utils/src/extraDependenciesType.ts (1 hunks)
✅ Files skipped from review due to trivial changes (1)
  • packages/suite/src/middlewares/suite/routerMiddleware.ts
⏰ Context from checks skipped due to timeout of 90000ms (10)
  • GitHub Check: check-project-or-issue
  • GitHub Check: Releases revision Checks
  • GitHub Check: Type Checking
  • GitHub Check: Build libs for publishing
  • GitHub Check: Other Checks
  • GitHub Check: Unit Tests
  • GitHub Check: Linting and formatting
  • GitHub Check: prepare_android_test_app
  • GitHub Check: build-web
  • GitHub Check: Analyze with CodeQL (javascript)
🔇 Additional comments (18)
packages/suite/src/actions/suite/guideActions.ts (1)

43-43: Good type safety enhancement.

Adding explicit return type GuideAction to the unsetNode function improves type safety by ensuring it always returns the expected action type.

packages/suite/src/actions/suite/routerActions.ts (1)

36-36: Type refinement matches actual usage.

The change from payload: AnchorType to payload: AnchorType | undefined aligns with the function onAnchorChange (line 80), which already has an optional anchor parameter. This makes the action type definition consistent with its actual usage.

packages/suite/src/reducers/suite/metadataReducer.ts (1)

80-83: Good handling of undefined clientId.

The added condition properly handles the case when clientId is undefined or falsy by removing the provider entry from the selectedProvider object. This prevents potential errors from trying to store an undefined value as a client ID.

packages/suite/src/actions/suite/metadataProviderActions.ts (1)

130-146: Improved type safety in disconnectProvider

The payload for the METADATA.REMOVE_PROVIDER action has been simplified to only include the clientId property, which is more focused and type-safe. This aligns with the PR objective of enhancing type security.

packages/suite/src/actions/suite/modalActions.ts (1)

82-83: Type issue needs to be resolved properly

This comment suppresses a TypeScript error that the author couldn't resolve. While this allows the code to compile, it introduces a technical debt that should be addressed.

Could you provide more details about the exact error message TypeScript is giving here? Understanding the error would help us determine how to properly fix the typing issue instead of suppressing it.

packages/suite/src/actions/suite/metadataPasswordsActions.ts (3)

31-36: Improved variable naming and error handling

Renaming from response to providerDetails makes the code more descriptive and easier to understand. The error handling now correctly passes the complete provider details object to the error handler.


58-59: Consistent use of providerDetails variable

Using providerDetails.payload consistently throughout the function improves code clarity and maintainability.


79-79: More specific condition check for device state

The condition has been refined to check not just for the existence of state but specifically for staticSessionId which is required for the functionality to work correctly. This prevents potential runtime errors if state exists but staticSessionId is undefined.

packages/suite/src/types/suite/index.ts (3)

7-7: Added new import for addLog function.

This addition complements the change on line 88 where you've added the new action type. Good practice to keep imports organized together.


87-88: Extended the Action union type with logger action.

Adding ReturnType<typeof addLog> to the Action union type ensures that logger actions can be properly dispatched through your Redux store. This improves type safety by making the Action type more comprehensive.


96-96: Improved type inference in Dispatch interface.

This is a key improvement to the Dispatch interface. By changing from <Action>(action: Action) to <A extends Action>(action: A), you're ensuring that the return type is correctly inferred based on the specific action being dispatched, rather than using a generic Action type. This provides better type checking and autocompletion.

packages/suite/src/actions/suite/suiteActions.ts (2)

98-100: Tightened payload type for appChanged action.

You've removed the possibility of unknown type in the payload, restricting it to only accept valid AppState['router']['app'] values. This is a good practice that prevents potential type errors at runtime.


305-310: Enhanced type safety for firmware authenticity checks.

You've improved the implementation by using a constant typed array (as const) for firmware authenticity checks. This ensures that the array is treated as readonly and maintains its specific tuple type, providing better type inference in the forEach loop.

packages/suite/src/actions/suite/metadataActions.ts (5)

40-40: Restricted REMOVE_PROVIDER payload to only include clientId.

Using Pick<MetadataProvider, 'clientId'> reduces the payload to only what's needed - just the clientId. This is a good practice that ensures you're only passing the minimum required data in your actions.


49-50: Improved flexibility of provider and data types.

You've made two important changes:

  1. Changed provider type to Omit<MetadataProvider, 'data'> & Pick<Partial<MetadataProvider>, 'data'> to allow for optional data
  2. Made the data field explicitly accept undefined values

This gives more flexibility when working with metadata providers that might not have complete data yet.


57-57: Added support for undefined clientId in SET_SELECTED_PROVIDER action.

Making clientId accept undefined values allows for clearing the selected provider, which is a necessary operation in certain scenarios.


103-103: Added optional chaining for safer property access.

Using optional chaining (?.) is a defensive programming practice that prevents runtime errors when accessing potentially undefined properties.


137-137: Removed support for undefined data in setMetadata.

The commented-out | undefined suggests you're no longer supporting undefined data in the setMetadata function. Make sure all callers of this function are updated to never pass undefined.

Is this comment intentional or should it be removed completely?

@@ -105,7 +105,7 @@ export type ExtraDependencies = {
localCurrency: FiatCurrencyCode;
}>;
lockDevice: ActionCreatorWithPreparedPayload<[payload: boolean], boolean>;
appChanged: ActionCreatorWithPayload<unknown>;
appChanged: ActionCreatorWithPayload<any>;
Copy link

Choose a reason for hiding this comment

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

⚠️ Potential issue

Type safety regression from unknown to any

Changing the type from ActionCreatorWithPayload<unknown> to ActionCreatorWithPayload<any> actually reduces type safety. The unknown type requires explicit type checking before use, while any allows unchecked usage, potentially leading to runtime errors.

Consider keeping unknown or using a more specific type if available:

-appChanged: ActionCreatorWithPayload<any>;
+appChanged: ActionCreatorWithPayload<unknown>;

If the specific type is known (like AppState['router']['app']), consider using that instead.

📝 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.

Suggested change
appChanged: ActionCreatorWithPayload<any>;
appChanged: ActionCreatorWithPayload<unknown>;

@komret komret removed the no-project This label is used to specify that PR doesn't need to be added to a project label Feb 27, 2025
@komret
Copy link
Contributor Author

komret commented Feb 27, 2025

I added 4f176e3 fixup, the idea come to me from coderabbit. I'd keep password manager data separate from labels because they are semantically different. @martykan

@komret komret force-pushed the chore/tighten-dispatch-type branch from 1c6816b to 0b7bf7d Compare February 27, 2025 16:27
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
code Code improvements
Projects
Status: 🔎 Needs review
Development

Successfully merging this pull request may close these issues.

2 participants