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

feat(tauri): Migrate from Tauri v1 to v2 #6374

Open
wants to merge 2 commits into
base: main
Choose a base branch
from

Conversation

klinkin
Copy link

@klinkin klinkin commented Mar 15, 2025

Summary

This commit completes the migration from Tauri v1 to v2, resolves configuration issues, upgrades Next.js, and adds test coverage for critical components to ensure stability during the transition.

Details

Tauri v2 Migration

  • Updated Tauri dependencies to v2.3.0 series in package.json
  • Restructured build configuration in /app/config/build.ts to align with Tauri v2 requirements
  • Fixed imports and API usage patterns across the codebase
  • Added compatibility layer for window.TAURI references to maintain backward compatibility

Next.js Issues

  • Upgraded Next.js from 14.1.1 to 14.2.24
  • Resolved caching problems with Server Actions
  • Updated eslint-config-next to match the new version
  • Cleared Next.js cache and temporary files to address build issues

Testing & Stability

  • Added comprehensive tests for stream.ts to verify streaming functionality
  • Created mocks for Tauri API to support test environment
  • Verified that critical functionality continues to work correctly
  • Translated all comments to English for consistency

Infrastructure

  • Fixed peer dependency warnings during installation
  • Ensured proper integration with Tauri v2 plugins (clipboard-manager, dialog, fs, http, notification, shell, updater, window-state)

Approach

Prioritized stability by:

  1. Making minimal necessary changes to configuration files
  2. Preserving most window.__TAURI__ calls as they still function in v2
  3. Planning gradual migration to new APIs with test coverage for critical components
  4. Documenting areas that will require future attention

Testing

  • Created unit tests for critical streaming functionality
  • Performed manual testing of key application features
  • Verified successful build and launch with Tauri v2

Future Work

  • Future PRs will gradually replace deprecated Tauri v1 API calls with v2 equivalents
  • Additional test coverage will be added for other critical components

💻 变更类型 | Change Type

  • feat
  • fix
  • refactor
  • perf
  • style
  • test
  • docs
  • ci
  • chore
  • build

🔀 变更说明 | Description of Change

📝 补充信息 | Additional Information

Summary by CodeRabbit

  • New Features

    • Enhanced file export with a more intuitive save prompt.
    • Improved notification handling that seamlessly manages permission requests.
    • Strengthened streaming operations for smoother data processing and clearer error feedback.
  • Chores

    • Updated dependencies and configurations to boost security, stability, and cross-platform performance.
    • Integrated additional system plugins to streamline file, clipboard, and network interactions.
  • Tests

    • Introduced a comprehensive test suite to ensure reliable streaming functionality across environments.

# Summary
This commit completes the migration from Tauri v1 to v2, resolves configuration issues, upgrades Next.js, and adds test coverage for critical components to ensure stability during the transition.

# Details
## Tauri v2 Migration
- Updated Tauri dependencies to v2.3.0 series in package.json
- Restructured build configuration in `/app/config/build.ts` to align with Tauri v2 requirements
- Fixed imports and API usage patterns across the codebase
- Added compatibility layer for window.__TAURI__ references to maintain backward compatibility

## Next.js Issues
- Upgraded Next.js from 14.1.1 to 14.2.24
- Resolved caching problems with Server Actions
- Updated eslint-config-next to match the new version
- Cleared Next.js cache and temporary files to address build issues

## Testing & Stability
- Added comprehensive tests for `stream.ts` to verify streaming functionality
- Created mocks for Tauri API to support test environment
- Verified that critical functionality continues to work correctly
- Translated all comments to English for consistency

## Infrastructure
- Fixed peer dependency warnings during installation
- Ensured proper integration with Tauri v2 plugins (clipboard-manager, dialog, fs, http, notification, shell, updater, window-state)

# Approach
Prioritized stability by:
1. Making minimal necessary changes to configuration files
2. Preserving most `window.__TAURI__` calls as they still function in v2
3. Planning gradual migration to new APIs with test coverage for critical components
4. Documenting areas that will require future attention

# Testing
- Created unit tests for critical streaming functionality
- Performed manual testing of key application features
- Verified successful build and launch with Tauri v2

# Future Work
- Future PRs will gradually replace deprecated Tauri v1 API calls with v2 equivalents
- Additional test coverage will be added for other critical components
Copy link

vercel bot commented Mar 15, 2025

Someone is attempting to deploy a commit to the NextChat Team on Vercel.

A member of the Team first needs to authorize it.

Copy link
Contributor

coderabbitai bot commented Mar 15, 2025

Walkthrough

This pull request integrates several Tauri plugins to replace direct API calls with plugin function imports. Frontend files have been updated for file saving, clipboard management, notifications, and stream handling. Additionally, configuration files, dependency declarations, and Tauri backend components have been restructured and upgraded. New capability definitions and a test suite for stream fetching have also been introduced.

Changes

File(s) Change Summary
app/**
(components/exporter.tsx, config/build.ts, store/update.ts, utils.ts, utils/stream.ts)
Updated to use Tauri plugin APIs: exporter now uses save and writeFile for file exports; build config accesses tauriConfig.version; update store handles notifications via isPermissionGranted, requestPermission, and sendNotification; utils use writeText, save, and writeTextFile, and stream events now use invoke/listen.
Configuration & Dependencies
(package.json, src-tauri/Cargo.toml, src-tauri/tauri.conf.json, src-tauri/build.rs)
Upgraded dependencies with new Tauri plugin versions, restructured the Tauri configuration (e.g., replacing the old "tauri" section with a new "bundle" and simplified "security" settings), and adjusted build script formatting.
Tauri Capabilities & Plugins
(src-tauri/capabilities/desktop.json, src-tauri/capabilities/migrated.json, src-tauri/src/main.rs, src-tauri/src/stream.rs)
Introduced new JSON files for desktop capabilities and migrated permissions; added multiple plugins in the Tauri main function; modified stream_fetch to accept a different window type and improved error handling with updated stream response structures.
Testing
(test/stream-fetch.test.ts)
Added a Jest test suite for the stream-fetch function with mocks for Tauri API modules to validate functionality in both Tauri and non-Tauri environments.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Exporter as ImagePreviewer
    participant Dialog as Tauri Dialog Plugin
    participant FS as Tauri FS Plugin
    User->>Exporter: Click "Download" image
    Exporter->>Dialog: Call save() to choose file path
    Dialog-->>Exporter: Return selected file path
    Exporter->>FS: Call writeFile() to save image data
    FS-->>Exporter: Confirm file saved
Loading
sequenceDiagram
    participant UpdateStore
    participant Notif as Tauri Notification Plugin
    UpdateStore->>Notif: Call isPermissionGranted()
    alt Permission not granted
      Notif->>UpdateStore: RequestPermission and return result
    end
    UpdateStore->>Notif: Call sendNotification()
    Notif-->>UpdateStore: Notification dispatched
Loading
sequenceDiagram
    participant Client
    participant Stream as Tauri Stream Fetch
    Client->>Stream: Invoke stream_fetch with parameters
    Stream->>Stream: Process request & convert body to bytes
    Stream->>Client: Emit stream-response events (chunks/errors)
Loading

Poem

I'm a hoppin' rabbit in a code garden bright,
Plugins and updates make my ears perk at the sight.
File saves and notifications now dance in my view,
Streams and events flow fresh like morning dew.
With Tauri magic, my code fields gleam and sing,
A digital wonderland where every change is spring!

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 8fa7c14 and 956ec96.

📒 Files selected for processing (1)
  • app/utils/stream.ts (4 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • app/utils/stream.ts

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

@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 (5)
src-tauri/capabilities/migrated.json (2)

15-16: Remove duplicate permission entry

There's a duplicate entry for fs:allow-remove that appears twice in consecutive lines.

    "fs:allow-mkdir",
    "fs:allow-remove",
-   "fs:allow-remove",
    "fs:allow-rename",

47-55: Consider consolidating default permissions

You've listed several individual permissions and also included their corresponding default permission groups. For example, both notification:default and specific notification permissions are included, which may be redundant.

If you're including the :default permissions (which typically grant access to all capabilities in that category), the individual permissions in the same category could be removed to make the configuration cleaner.

test/stream-fetch.test.ts (3)

59-59: Avoid using 'Function' as a type

TypeScript best practices recommend against using the generic 'Function' type as it's too broad.

-        transformCallback: (callback: Function) => callback,
+        transformCallback: (callback: (...args: any[]) => any) => callback,
🧰 Tools
🪛 Biome (1.9.4)

[error] 59-59: Don't use 'Function' as a type.

Prefer explicitly define the function shape. This type accepts any function-like value, which can be a common source of bugs.

(lint/complexity/noBannedTypes)


64-64: Remove unnecessary constructor

This empty constructor is unnecessary and can be removed.

        Headers: class Headers {
-          constructor() {}
          entries() { return []; }
        },
🧰 Tools
🪛 Biome (1.9.4)

[error] 64-64: This constructor is unnecessary.

Unsafe fix: Remove the unnecessary constructor.

(lint/complexity/noUselessConstructor)


104-104: Avoid using the delete operator for performance

The delete operator can have performance implications. Consider using undefined assignment instead.

-    delete (tempWindow as any).__TAURI__;
+    (tempWindow as any).__TAURI__ = undefined;
🧰 Tools
🪛 Biome (1.9.4)

[error] 104-104: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)

📜 Review details

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

📥 Commits

Reviewing files that changed from the base of the PR and between b6f5d75 and 8fa7c14.

⛔ Files ignored due to path filters (6)
  • src-tauri/Cargo.lock is excluded by !**/*.lock
  • src-tauri/gen/schemas/acl-manifests.json is excluded by !**/gen/**
  • src-tauri/gen/schemas/capabilities.json is excluded by !**/gen/**
  • src-tauri/gen/schemas/desktop-schema.json is excluded by !**/gen/**
  • src-tauri/gen/schemas/macOS-schema.json is excluded by !**/gen/**
  • yarn.lock is excluded by !**/yarn.lock, !**/*.lock
📒 Files selected for processing (14)
  • app/components/exporter.tsx (3 hunks)
  • app/config/build.ts (1 hunks)
  • app/store/update.ts (2 hunks)
  • app/utils.ts (5 hunks)
  • app/utils/stream.ts (3 hunks)
  • package.json (4 hunks)
  • src-tauri/Cargo.toml (1 hunks)
  • src-tauri/build.rs (1 hunks)
  • src-tauri/capabilities/desktop.json (1 hunks)
  • src-tauri/capabilities/migrated.json (1 hunks)
  • src-tauri/src/main.rs (1 hunks)
  • src-tauri/src/stream.rs (1 hunks)
  • src-tauri/tauri.conf.json (2 hunks)
  • test/stream-fetch.test.ts (1 hunks)
🧰 Additional context used
🪛 Biome (1.9.4)
test/stream-fetch.test.ts

[error] 64-64: This constructor is unnecessary.

Unsafe fix: Remove the unnecessary constructor.

(lint/complexity/noUselessConstructor)


[error] 104-104: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)


[error] 59-59: Don't use 'Function' as a type.

Prefer explicitly define the function shape. This type accepts any function-like value, which can be a common source of bugs.

(lint/complexity/noBannedTypes)

app/utils/stream.ts

[error] 69-69: Don't use 'Function' as a type.

Prefer explicitly define the function shape. This type accepts any function-like value, which can be a common source of bugs.

(lint/complexity/noBannedTypes)

🔇 Additional comments (38)
src-tauri/build.rs (1)

1-3: Proper indentation maintained in the Tauri build file.

The indentation change aligns with Rust's standard style and maintains the functionality of the Tauri build process during the v1 to v2 migration.

app/config/build.ts (1)

13-13: Version path updated to match Tauri v2 configuration structure.

The change from tauriConfig.package.version to tauriConfig.version reflects the structural changes in Tauri v2's configuration format. This adaptation is necessary for the migration.

src-tauri/capabilities/desktop.json (1)

1-14: New capability definition added for Tauri v2.

This new capability file is essential for Tauri v2's permissions model. It properly defines:

  • The capability identifier
  • Supported platforms (macOS, Windows, Linux)
  • Windows configuration
  • Required updater permissions

This aligns with Tauri v2's capability-based security model which replaces the allowlist system from v1.

src-tauri/src/main.rs (1)

7-17: Tauri v2 plugins properly integrated.

The changes implement the Tauri v2 plugin architecture correctly. The code now:

  1. Uses the plugin builder pattern consistently
  2. Includes all necessary plugins that were previously part of the core package
  3. Maintains the existing stream_fetch handler
  4. Preserves window state functionality

This implementation follows Tauri v2's modular design where core functionality has been moved to plugins.

src-tauri/capabilities/migrated.json (1)

1-57: Good implementation of Tauri v2 capability definitions

This new capability definition file aligns with Tauri v2's permission model, properly defining all the necessary permissions for your application after migration.

app/components/exporter.tsx (3)

43-44: Good migration to Tauri v2 plugin imports

Well done on replacing direct Tauri API calls with the plugin-specific imports, which is the recommended approach for Tauri v2.


461-473: Successfully migrated to plugin-dialog API

The save function from the dialog plugin is correctly implemented, maintaining the same functionality while following Tauri v2 guidelines.


479-479: Good implementation of writeFile from plugin-fs

Well done on replacing the direct window.__TAURI__.fs.writeBinaryFile call with the writeFile function from the plugin-fs package.

app/store/update.ts (2)

13-17: Good migration to Tauri v2 notification plugin

Excellent work importing the appropriate functions from the notification plugin instead of using the global Tauri API.


98-130: Improved notification permission handling and error management

This refactored implementation correctly:

  1. Checks if notification permission is granted
  2. Requests permission if needed
  3. Sends the notification with proper error handling

The try-catch block is a good addition for robustness.

test/stream-fetch.test.ts (4)

1-45: Well-structured test setup with proper mocking

Good job setting up the test environment with appropriate mocks for Tauri's API and global objects needed for stream functionality.


46-100: Good test lifecycle management

The test setup correctly:

  1. Preserves original global objects
  2. Sets up mocked Tauri environment
  3. Cleans up after tests
  4. Resets mocks between tests

This ensures test isolation and prevents side effects.

🧰 Tools
🪛 Biome (1.9.4)

[error] 64-64: This constructor is unnecessary.

Unsafe fix: Remove the unnecessary constructor.

(lint/complexity/noUselessConstructor)


[error] 59-59: Don't use 'Function' as a type.

Prefer explicitly define the function shape. This type accepts any function-like value, which can be a common source of bugs.

(lint/complexity/noBannedTypes)


101-120: Good test for fallback to native fetch

This test correctly verifies that the application falls back to using native fetch when Tauri is unavailable, which is important for ensuring compatibility across different environments.

🧰 Tools
🪛 Biome (1.9.4)

[error] 104-104: Avoid the delete operator which can impact performance.

Unsafe fix: Use an undefined assignment instead.

(lint/performance/noDelete)


122-167: Comprehensive Tauri API and abort signal tests

These tests thoroughly verify:

  1. The proper invocation of Tauri API when available
  2. The correct handling of abort signals

This testing approach ensures both the functionality and error handling of the stream-fetch utility are working as expected.

app/utils/stream.ts (2)

6-7: Well-implemented module imports for Tauri v2

This correctly implements the migration from direct window.TAURI calls to module imports from Tauri API packages, following the Tauri v2 migration best practices.


79-88: Properly migrated invoke implementation

The change from window.__TAURI__.invoke to the imported invoke function is correct and follows Tauri v2 best practices.

src-tauri/src/stream.rs (4)

4-12: Updated imports for Tauri v2 compatibility

The imports have been correctly updated to use the Tauri v2 plugin system. Using the tauri_plugin_http module instead of direct reqwest dependencies is the recommended approach.


16-34: Improved struct definitions with trailing commas

The addition of trailing commas in struct definitions is a good practice that makes future modifications cleaner by reducing diff noise when adding new fields.

The change from bytes::Bytes to Vec<u8> in the ChunkPayload struct is appropriate for Tauri v2 compatibility.


38-38: Updated parameter type for Tauri v2

Changed from tauri::Window to tauri::WebviewWindow as required by Tauri v2's API changes.


47-175: Well-restructured HTTP handling implementation

The HTTP request and response handling has been properly refactored for Tauri v2. Key improvements include:

  • Better error handling with detailed error messages
  • Proper header parsing and conversion
  • Improved chunk emission with error handling for emit failures
  • Better error response handling by converting error messages to bytes

The implementation maintains the original functionality while adapting to Tauri v2's API changes.

app/utils.ts (5)

15-17: Properly imported Tauri plugin modules

Added imports from the appropriate Tauri v2 plugin packages instead of using direct window.__TAURI__ references, which aligns with the migration objectives.


26-27: Improved regex pattern for trimming topics

Enhanced the regex patterns to better handle different quote characters, providing more robust text cleaning.


34-34: Migrated clipboard functionality to plugin API

Correctly updated to use the Tauri v2 plugin API for clipboard operations.


58-74: Updated file dialog and file system operations

Successfully migrated from direct window.__TAURI__ API calls to the modular plugin-based approach required by Tauri v2.


454-477: Improved updater implementation

The client update function has been restructured to properly check for the availability of the Tauri updater before attempting to use it, which adds robustness to the code. The implementation also includes proper type annotations for the update results.

src-tauri/Cargo.toml (4)

15-15: Updated tauri-build dependency to v2

Correctly updated the tauri-build dependency to version 2, which is required for the Tauri v2 migration.


20-21: Simplified tauri dependency configuration

The tauri dependency has been updated to version 2 with a simplified feature set. This is the recommended approach for Tauri v2 since many features are now provided through plugins.


22-33: Added required Tauri v2 plugin dependencies

Added the necessary plugin dependencies for Tauri v2, which replaces the feature-based approach of Tauri v1. This is a core part of the migration to the new plugin-based architecture.


41-42: Added platform-specific updater plugin

Correctly configured the updater plugin to only be included for desktop platforms (excluding Android and iOS), which follows best practices for cross-platform Tauri applications.

package.json (4)

29-36: New Tauri Plugin Dependencies Added
The addition of the Tauri plugin dependencies (clipboard-manager, dialog, fs, http, notification, shell, updater, window-state) with the specified versions appears correct and aligns with the migration to Tauri v2.


50-50: Next.js Upgrade
The Next.js dependency has been updated to version 14.2.24. Please verify that any breaking changes introduced by this upgrade are covered by your tests and do not affect the existing codebase.


70-71: Tauri API and CLI Dependency Updates
The updates to @tauri-apps/api (v2.3.0) and @tauri-apps/cli (v2.3.1) are in line with the Tauri v2 migration. Confirm that the changes in these dependencies are fully integrated and that any API changes are handled elsewhere in the codebase.


86-86: ESLint Config Upgrade
Upgrading eslint-config-next to version 14.2.24 should help maintain compatibility with the new Next.js version. Ensure that linting rules and project style guidelines have been revalidated after this upgrade.

src-tauri/tauri.conf.json (5)

6-7: Updated Build Configuration
Replacing the deprecated devPath and distDir with devUrl and frontendDist complies with Tauri v2 requirements. Please verify that the paths ("../out" and "http://localhost:3000") correctly reflect your development and production setups.


9-43: New Bundle Configuration Introduced
The newly added "bundle" section provides detailed metadata including icons, platform-specific settings, and updater artifacts. This is a necessary change for Tauri v2. Ensure that all fields (like certificate details, longDescription, and platform targets) are correctly configured for your deployment targets.


44-47: Top-Level Metadata Enhancement
Adding top-level properties—productName, mainBinaryName, version, and identifier—clarifies the application’s identity and versioning. Confirm that these details match your branding and release strategy.


48-57: Updater Plugin Configuration Check
The updater configuration now includes endpoints and a public key. Ensure that the endpoint URL for release updates is current and that the pubkey is securely managed.


59-76: Revised App Configuration
The new "app" section introduces global Tauri usage (withGlobalTauri), a refined windows configuration (including hiddenTitle, titleBarStyle: "Overlay", and useHttpsScheme), and security settings via CSP. Validate that these changes result in the intended UI behavior and enhanced security across target platforms.

- Replace generic Function type with specific () => void for unlisten
- Enhance typing for setRequestId from Function to ((value: number) => void)
- Address code review feedback from Biome linter
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.

1 participant