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

fix(suite-desktop-core): refactor desktop state patches to avoid breaking change #17602

Open
wants to merge 1 commit into
base: develop
Choose a base branch
from

Conversation

Lemonexe
Copy link
Contributor

@Lemonexe Lemonexe commented Mar 12, 2025

Description

Partial revert of 5a84a1f (#17526)

  • There, desktop state patch process args were refactored, as they stopped working in Electron 35
    • that was a breaking change for Trezor Suite process args 😞
  • I believed at the time that Electron checks args at startup and throws if there are dots on the left-hand side of assignment in a switch.
  • It is not so; only the app.commandLine.getSwitchValue throws. And it's actually not related to dots but uppercase letters!
  • But that function call was not needed at all, even in the original implementation.
  • In 5a84a1f, the processStatePatch + tests were also refactored for better clarity, so this PR keeps that...
  • ...but reverts to the original API ➡️ no breaking change 🙂

Notes

👉 I will still did file a bug with Electron electron/electron#45991, because the function started throwing without mention in changelog. But they said the function is not supposed to be used for custom application parameters, it's an API to set Chromium flags. We are supposed to use process.argv for custom params, as it currently is 🙂

@Lemonexe Lemonexe added the no-project This label is used to specify that PR doesn't need to be added to a project label Mar 12, 2025
@Lemonexe Lemonexe requested a review from marekrjpolak March 12, 2025 10:42
@Lemonexe Lemonexe marked this pull request as ready for review March 12, 2025 10:42
];

describe('process state patch', () => {
FIXTURES.map(([name, args, value]) => {
it(name, () => {
process.argv = args.map(arg => `--${arg}`);
process.argv = args;
Copy link
Contributor Author

Choose a reason for hiding this comment

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

I think mapping the -- just obfuscated the test flow, so I simplified it even further..

.reduce<ProcessStatePatchResult>(
(prev, cur) => mergeDeepObject.withOptions({ dotNotation: true }, prev ?? {}, cur),
undefined,
);
)?.state;
Copy link
Contributor Author

Choose a reason for hiding this comment

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

with this implementation, everything is under { state: {...patches}} until this line, where I extract it or dump the undefined..

Copy link

coderabbitai bot commented Mar 12, 2025

Walkthrough

The changes update how state-related string assignments are formatted and processed across the application. The disableHashCheckStatePatch variable's string format was altered from using an equal sign (=) to a dot (.) for firmware hash checks in the Electron launch configuration. In the test suite, state strings for various cases were prefixed with double dashes (--), and the FIXTURES array was updated accordingly. Additionally, the parseAssignment function was removed, and the logic in the processStatePatch function was revised to utilize a regex pattern for matching state assignments directly. This streamlining enhances the efficiency of argument processing. No modifications were made to any exported or public declarations.

Tip

⚡🧪 Multi-step agentic review comment chat (experimental)
  • We're introducing multi-step agentic chat in review comments. This experimental feature enhances review discussions with the CodeRabbit agentic chat by enabling advanced interactions, including the ability to create pull requests directly from comments.
    - To enable this feature, set early_access to true under in the settings.

📜 Recent review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between aa33352 and 683bd11.

📒 Files selected for processing (3)
  • packages/suite-desktop-core/e2e/support/electron.ts (1 hunks)
  • packages/suite-desktop-core/src/__tests__/app-utils.test.ts (1 hunks)
  • packages/suite-desktop-core/src/libs/app-utils.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/suite-desktop-core/e2e/support/electron.ts
  • packages/suite-desktop-core/src/tests/app-utils.test.ts
⏰ Context from checks skipped due to timeout of 90000ms (5)
  • GitHub Check: run-e2e-suite-desktop-tests (@group=wallet, trezor-user-env-unix bitcoin-regtest)
  • GitHub Check: run-e2e-suite-desktop-tests (@group=passphrase, trezor-user-env-unix)
  • GitHub Check: build-web
  • GitHub Check: Setup and Cache Dependencies
  • GitHub Check: Analyze with CodeQL (javascript)
🔇 Additional comments (3)
packages/suite-desktop-core/src/libs/app-utils.ts (3)

38-38: Good addition of a clear regex pattern.

The new STATE_ASSIGNMENT_REGEX constant improves code readability and maintainability by clearly defining the pattern for state assignments. The pattern correctly handles the first equality sign as a separator, which allows passing JSON values that may contain equal signs.


46-52: Improved argument processing implementation.

The refactored code streamlines the processing of command-line arguments by:

  1. Directly applying the regex pattern to find and extract matching arguments
  2. Using destructuring to cleanly extract key-value pairs
  3. Creating objects with the parsed values in a more straightforward manner

This approach is more maintainable and aligns with the PR objective to retain clarity improvements while avoiding breaking changes.


56-56: Extraction of state property maintains API compatibility.

The addition of ?.state at the end of the chain properly extracts the state property from the result or returns undefined if the result is undefined. This maintains compatibility with the original API while improving the function's implementation.

✨ Finishing Touches
  • 📝 Generate Docstrings

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


return { [key]: tryParseJson(value) };
};

const STATE_ASSIGNMENT_REGEX = /^--state[^=]*=[^=]+$/;
Copy link
Contributor

Choose a reason for hiding this comment

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

The only tiny thing which came to my mind is that this regex disallow to pass a json value containing string with equal sign, which in theory may be wanted.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

True! I'll fix that.

Copy link
Contributor Author

Choose a reason for hiding this comment

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

Done. Now I only split by the first equality sign, so I changed .test+.split back to .match with two capturing groups

@Lemonexe Lemonexe force-pushed the fix-state-patch-process-args branch from 6b17f57 to aa33352 Compare March 12, 2025 12:34
@Lemonexe Lemonexe requested a review from marekrjpolak March 12, 2025 12:35
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: 0

🧹 Nitpick comments (1)
packages/suite-desktop-core/src/libs/app-utils.ts (1)

46-52: The implementation properly handles command-line state patches.

The refactored code effectively extracts and processes state patches from command-line arguments using regex matching instead of a separate parsing function. This approach is more direct and maintainable.

However, consider replacing the sequential map-filter-map operations with a single reduce for better performance:

-    process.argv
-        .map(arg => arg.match(STATE_ASSIGNMENT_REGEX))
-        .filter(match => match !== null)
-        .map((assignment: RegExpMatchArray) => {
-            const [_, key, value] = assignment;
-
-            return { [key]: tryParseJson(value) };
-        })
+    process.argv.reduce<Record<string, any>[]>((acc, arg) => {
+        const match = arg.match(STATE_ASSIGNMENT_REGEX);
+        if (match !== null) {
+            const [_, key, value] = match;
+            acc.push({ [key]: tryParseJson(value) });
+        }
+        return acc;
+    }, [])
📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between 6b17f57 and aa33352.

📒 Files selected for processing (3)
  • packages/suite-desktop-core/e2e/support/electron.ts (1 hunks)
  • packages/suite-desktop-core/src/__tests__/app-utils.test.ts (1 hunks)
  • packages/suite-desktop-core/src/libs/app-utils.ts (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • packages/suite-desktop-core/e2e/support/electron.ts
  • packages/suite-desktop-core/src/tests/app-utils.test.ts
⏰ Context from checks skipped due to timeout of 90000ms (9)
  • GitHub Check: run-e2e-suite-desktop-tests (@group=wallet, trezor-user-env-unix bitcoin-regtest)
  • GitHub Check: run-e2e-suite-desktop-tests (@group=other, trezor-user-env-unix)
  • GitHub Check: run-e2e-suite-desktop-tests (@group=passphrase, trezor-user-env-unix)
  • GitHub Check: run-e2e-suite-desktop-tests (@group=settings, trezor-user-env-unix bitcoin-regtest)
  • GitHub Check: run-e2e-suite-desktop-tests (@group=device-management, trezor-user-env-unix)
  • GitHub Check: run-e2e-suite-desktop-tests (@group=suite, trezor-user-env-unix)
  • GitHub Check: Setup and Cache Dependencies
  • GitHub Check: build-web
  • GitHub Check: Analyze with CodeQL (javascript)
🔇 Additional comments (2)
packages/suite-desktop-core/src/libs/app-utils.ts (2)

56-56: The null-safe extraction of the state property is correct.

This line correctly extracts the state property from the result or returns undefined if the reduction produces no results.


38-38:

✅ Verification successful

Review the regex pattern to ensure it handles all valid JSON values.

The regex pattern captures state assignments well, but it may have limitations when parsing JSON strings containing equal signs within the value part. Consider if this is an intended limitation or if the regex should be refined to handle more complex JSON values.


🏁 Script executed:

#!/bin/bash
# Check if there are any use cases in the codebase that might pass JSON with equal signs
echo "Searching for potential JSON values with equal signs passed to state patches..."
rg -A 3 "state.*=" --no-filename | grep -E "(\".*=.*\"|\{.*=.*\})" || echo "No instances found"

Length of output: 2549


State Assignment Regex Verified

After investigating potential cases where a JSON value containing equal signs might be passed, there is no evidence in the codebase that the current regex causes issues. The pattern

const STATE_ASSIGNMENT_REGEX = /^--(state[^=]*)=(.+)$/;

correctly captures state assignments—even if the value includes equal signs. If more complex JSON values ever become a requirement, consider revisiting the parsing strategy.

@Lemonexe
Copy link
Contributor Author

/rebase

Copy link

@trezor-ci trezor-ci force-pushed the fix-state-patch-process-args branch from aa33352 to 683bd11 Compare March 12, 2025 20:44
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
no-project This label is used to specify that PR doesn't need to be added to a project
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants