Skip to content

Fix 'WebSocket is not defined' #2158

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

Closed
wants to merge 1 commit into from

Conversation

nahoj
Copy link

@nahoj nahoj commented May 3, 2025

I just cloned the project. When I tried task dev / task start, I encountered the following error:

error initializing wshrpc ReferenceError: WebSocket is not defined

Running in development mode
2025-05-03 06:24:38.554 waveterm-app starting, data_dir=/home/jg/.local/share/waveterm-dev, config_dir=/home/jg/.config/waveterm-dev electronpath=/home/jg/perso/soft/waveterm/dist gopath=/home/jg/perso/soft/waveterm/dist arch=linux/x64
2025-05-03 06:24:38.555 waveterm-app WAVETERM_DEV set
2025-05-03 06:24:38.558 trying to run local server /home/jg/perso/soft/waveterm/dist/bin/wavesrv.x64
2025-05-03 06:24:38.569 spawned wavesrv
2025-05-03 06:24:38.680 [wavesrv] 2025/05/03 06:24:38.584276 checking endpoint "wss://wsapi-dev.waveterm.dev/"
2025-05-03 06:24:38.680 [wavesrv] 2025/05/03 06:24:38.584346 [base] acquiring lock on /home/jg/.local/share/waveterm-dev/wave.lock
2025-05-03 06:24:38.680 [wavesrv] 2025/05/03 06:24:38.584361 wave version: 0.11.3-beta.5 (202505030616)
2025-05-03 06:24:38.680 [wavesrv] 2025/05/03 06:24:38.584364 wave data dir: /home/jg/.local/share/waveterm-dev
2025-05-03 06:24:38.680 [wavesrv] 2025/05/03 06:24:38.584366 wave config dir: /home/jg/.config/waveterm-dev
2025-05-03 06:24:38.680 [wavesrv] 2025/05/03 06:24:38.584376 [db] opening db /home/jg/.local/share/waveterm-dev/db/filestore.db
2025-05-03 06:24:38.680 [wavesrv] 2025/05/03 06:24:38.584404 migrate filestore
2025-05-03 06:24:38.680 [wavesrv] 2025/05/03 06:24:38.587095 filestore initialized
2025-05-03 06:24:38.681 [wavesrv] 2025/05/03 06:24:38.587118 migrate wstore
2025-05-03 06:24:38.681 [wavesrv] 2025/05/03 06:24:38.589947 wstore initialized
2025-05-03 06:24:38.681 [wavesrv] 2025/05/03 06:24:38.590976 initializing wsh and shell startup files
2025-05-03 06:24:38.681 [wavesrv] 2025/05/03 06:24:38.591029 clientid: e525681b-a39c-414e-9426-e516e4b22a3f
2025-05-03 06:24:38.681 [wavesrv] 2025/05/03 06:24:38.591042 client has one window
2025-05-03 06:24:38.681 [wavesrv] 2025/05/03 06:24:38.591046 CheckAndFixWindow e8e13948-76b6-4774-816c-59239cd162a4
2025-05-03 06:24:38.681 [wavesrv] 2025/05/03 06:24:38.591452 [router] registering wsh route "wavesrv"
2025-05-03 06:24:38.681 [wavesrv] 2025/05/03 06:24:38.591472 [router] registering wsh route "conn:local"
2025-05-03 06:24:38.681 [wavesrv] 2025/05/03 06:24:38.591903 subdirs: [/home/jg/.config/waveterm-dev/mimetypes /home/jg/.config/waveterm-dev/defaultwidgets /home/jg/.config/waveterm-dev/widgets /home/jg/.config/waveterm-dev/presets /home/jg/.config/waveterm-dev/termthemes /home/jg/.config/waveterm-dev/connections /home/jg/.config/waveterm-dev/bookmarks]
2025-05-03 06:24:38.681 [wavesrv] 2025/05/03 06:24:38.591946 failed to add path /home/jg/.config/waveterm-dev/mimetypes to watcher: no such file or directory
2025-05-03 06:24:38.681 [wavesrv] 2025/05/03 06:24:38.591956 failed to add path /home/jg/.config/waveterm-dev/defaultwidgets to watcher: no such file or directory
2025-05-03 06:24:38.681 [wavesrv] 2025/05/03 06:24:38.591961 failed to add path /home/jg/.config/waveterm-dev/widgets to watcher: no such file or directory
2025-05-03 06:24:38.681 [wavesrv] 2025/05/03 06:24:38.591972 failed to add path /home/jg/.config/waveterm-dev/termthemes to watcher: no such file or directory
2025-05-03 06:24:38.681 [wavesrv] 2025/05/03 06:24:38.591976 failed to add path /home/jg/.config/waveterm-dev/connections to watcher: no such file or directory
2025-05-03 06:24:38.681 [wavesrv] 2025/05/03 06:24:38.591982 failed to add path /home/jg/.config/waveterm-dev/bookmarks to watcher: no such file or directory
2025-05-03 06:24:38.681 [wavesrv] 2025/05/03 06:24:38.591984 starting file watcher
2025-05-03 06:24:38.681 [wavesrv] 2025/05/03 06:24:38.596015 error (non-fatal), could not resolve wsh binary "/home/jg/perso/soft/waveterm/dist/bin/wsh-0.11.3-beta.5-linux.x64": stat /home/jg/perso/soft/waveterm/dist/bin/wsh-0.11.3-beta.5-linux.x64: no such file or directory
2025-05-03 06:24:38.681 [wavesrv] 2025/05/03 06:24:38.598517 [router] registering wsh route "bare"
2025-05-03 06:24:38.681 [wavesrv] 2025/05/03 06:24:38.598629 Server [web] listening on 127.0.0.1:38363
2025-05-03 06:24:38.681 [wavesrv] 2025/05/03 06:24:38.598664 Server [websocket] listening on 127.0.0.1:37909
2025-05-03 06:24:38.681 [wavesrv] 2025/05/03 06:24:38.598755 [websocket] running websocket server on 127.0.0.1:37909
2025-05-03 06:24:38.682 [wavesrv] 2025/05/03 06:24:38.599272 Server [unix-domain] listening on /home/jg/.local/share/waveterm-dev/wave.sock
2025-05-03 06:24:38.682 [wavesrv] 2025/05/03 06:24:38.599386 Docsite is nil, initializing
2025-05-03 06:24:38.682 [wavesrv] 2025/05/03 06:24:38.599395 Found static site at /home/jg/perso/soft/waveterm/dist/docsite, serving
2025-05-03 06:24:38.682 [wavesrv] 2025/05/03 06:24:38.599410 Schema is nil, initializing
2025-05-03 06:24:38.682 [wavesrv] 2025/05/03 06:24:38.599412 Found static site at /home/jg/perso/soft/waveterm/dist/schema, serving
2025-05-03 06:24:38.683 wavesrv ready signal received true 126 ms
2025-05-03 06:24:38.792 error initializing wshrpc ReferenceError: WebSocket is not defined
    at newWebSocket (file:///home/jg/perso/soft/waveterm/dist/main/index.js:6219:5)
    at WSControl.connectNow (file:///home/jg/perso/soft/waveterm/dist/main/index.js:7034:19)
    at initElectronWshrpc (file:///home/jg/perso/soft/waveterm/dist/main/index.js:7605:12)
    at appMain (file:///home/jg/perso/soft/waveterm/dist/main/index.js:47479:5)
2025-05-03 06:24:48.599 [wavesrv] 2025/05/03 06:24:48.598906 [wcloud] sending 5 tevents
2025-05-03 06:24:48.600 [wavesrv] 2025/05/03 06:24:48.599609 [wcloud] sending request POST https://api-dev.waveterm.dev/central/tevents
2025-05-03 06:24:50.637 [wavesrv] 2025/05/03 06:24:50.636841 [wcloud] sending telemetry data
2025-05-03 06:24:50.637 [wavesrv] 2025/05/03 06:24:50.636966 [wcloud] sending request POST https://api-dev.waveterm.dev/central/telemetry

An AI suggested this fix which works for me. Its comments were:

I replaced the async import('ws') with a synchronous lazy require inside newWebSocket().

Why this fixes startup:

  • In the Electron main (Node) context window is undefined, so frontend code expected ws to be loaded.
  • The old async import often hadn’t finished when newWebSocket() ran, so NodeWebSocket was still null → “WebSocket is not defined” + subsequent undefined.close crashes.

Key changes in frontend/util/wsutil.ts

  • Removed top-level dynamic import.
  • Initialise NodeWebSocket synchronously the first time newWebSocket() is called (only in Node).
  • Made headers param optional.
  • Returned browser WebSocket unchanged for renderer.

As for why I encounter the bug when other contributors don't, it suggested:

  1. Recent regression [...]
  2. Environment difference:
    • System specificity: The issue might only appear on certain Linux distributions or hardware combinations that affect Node/Electron timing
    • The error happens consistently for you but might be intermittent for others
    • Maintainers might work primarily on macOS where Node timing is different

I am not familiar with the stack so I don't know whether this is actually a good change! I hope it's valid.

@CLAassistant
Copy link

CLAassistant commented May 3, 2025

CLA assistant check
All committers have signed the CLA.

Copy link
Contributor

coderabbitai bot commented May 3, 2025

Walkthrough

The update refactors the WebSocket utility to improve handling of browser and Node.js/Electron environments. The newWebSocket function now synchronously requires the ws module when running outside the browser, caching the constructor for subsequent use. This eliminates the previous asynchronous import and ensures the WebSocket constructor is always available when needed. The function signature is modified to make the headers parameter optional. In Node contexts, the function creates a WebSocket instance with the given URL and optional headers, while in browser contexts it uses the global WebSocket constructor without headers. The type alias for a combined WebSocket type remains unchanged, and an explicit export for this type alias is added. No other public API changes are introduced.


📜 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 0b16593 and 7f7b6ac.

📒 Files selected for processing (1)
  • frontend/util/wsutil.ts (1 hunks)
🔇 Additional comments (7)
frontend/util/wsutil.ts (7)

4-6: Clear explanation of the environment detection logic

The updated comment clearly explains when and why different WebSocket implementations are used based on the runtime environment, which improves code maintainability.


8-10: Good type-only import approach

Using a type-only import from the ws package avoids bundling the actual module code when this file is compiled for browser environments, which is a good optimization.


12-13: Appropriate caching mechanism for Node WebSocket

The lazy initialization pattern with a module-level cache variable is a clean approach to avoid repeated imports while ensuring the constructor is available when needed.


17-20: Function signature properly updated for optional headers

Making the headers parameter optional with ? and allowing null provides better flexibility and matches the actual usage in different environments.


21-36: Effective fix for "WebSocket is not defined" error

The synchronous require approach solves the timing issue that was causing the "WebSocket is not defined" errors with the previous asynchronous implementation. By checking and initializing the constructor before use, you ensure it's always available when needed.

The error handling for different module formats (default export vs direct export) is also handled well with the fallback syntax.


38-39: Clean browser implementation

The browser path is kept simple and clean, using the global WebSocket constructor directly without any unnecessary additions.


43-43: Helpful type export

Explicitly exporting the type alias makes it easier for consumers to import the WebSocket type directly, which improves the API's usability.

✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ 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.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

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 generate sequence diagram to generate a sequence diagram of the changes in 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.

@nahoj
Copy link
Author

nahoj commented May 3, 2025

I didn't see the existing PR for this: #2101

@nahoj nahoj closed this May 3, 2025
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.

2 participants