Skip to content

fix(desktop): unpack renderer files for custom protocol handler - #767

Merged
saddlepaddle merged 4 commits into
mainfrom
fix/desktop-production-protocol-handler
Jan 15, 2026
Merged

saddlepaddle merged 4 commits into
mainfrom
fix/desktop-production-protocol-handler

Conversation

@saddlepaddle

@saddlepaddle saddlepaddle commented Jan 15, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

  • Fixes production app failing to load with ERR_FAILED (-2) when loading superset://app/index.html#/
  • Unpacks renderer files from asar archive so custom protocol handler can serve them via file:// URLs
  • Updates protocol handler to use app.asar.unpacked path for renderer files

Problem

The custom protocol handler (superset://) was failing to load the app in production because:

  1. Renderer files were packed inside the asar archive (app.asar/dist/renderer/)
  2. net.fetch() with file:// URLs cannot access files inside asar archives
  3. This resulted in ERR_FAILED (-2) errors when trying to load the app

Solution

  • Added dist/renderer/**/* to asarUnpack in electron-builder.ts
  • Updated protocol handler to use app.asar.unpacked path instead of app.asar
  • Added debug logging to protocol handler for troubleshooting

Test Plan

  • Build canary release with these changes
  • Install and launch Superset Canary
  • Verify app loads successfully without ERR_FAILED errors
  • Verify logs show correct file paths being served

Summary by CodeRabbit

  • Refactor
    • Desktop app now loads its UI using the local file path in production rather than a custom protocol, simplifying startup.
    • Added user-visible logging for successful page loads and detailed failures to improve diagnostics and app reliability.

✏️ Tip: You can customize this high-level summary in your review settings.

@coderabbitai

coderabbitai Bot commented Jan 15, 2026 •

Copy link
Copy Markdown
Contributor
📝 Walkthrough

Walkthrough

Removed Electron custom protocol handling from the main process and switched production window loading to use file:// via loadFile() with hash routing; development (Vite) loading remains unchanged. Added navigation success and failure logging in the window loader.

Changes

Cohort / File(s) Summary
Main process: protocol removal
apps/desktop/src/main/index.ts
Dropped net and protocol imports and removed the production-time custom protocol registration block; kept app startup flow and added readiness logging.
Window loader: file:// + navigation logging
apps/desktop/src/lib/window-loader.ts
Removed PROTOCOL_SCHEME usage and custom-protocol URL construction; production now uses loadFile() with hash routing (#/); added did-finish-load and did-fail-load listeners to log navigation results.

Sequence Diagram(s)

(omitted — changes do not introduce a new multi-component control flow requiring sequence visualization)

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

Possibly related PRs

Poem

🐰 I hopped through ports and tiny schemes,
Left custom paths for file-born streams,
Hashes guide the window's view,
Logs tell when the page comes through,
A quiet change — a lighter dream ✨

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title accurately summarizes the main change: unpacking renderer files for the custom protocol handler to fix production loading issues.
Description check ✅ Passed The PR description covers the problem, solution, and test plan comprehensively, though it doesn't fully match the template structure with explicit section headings.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ 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

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 0

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
apps/desktop/src/main/index.ts (1)

214-230: Path traversal vulnerability: Validate that resolved path stays within renderer directory.

The pathname is derived from an external URL and, while path.normalize is applied, it doesn't prevent directory traversal attacks. A malicious URL like superset://app/../../../etc/passwd could potentially escape the renderer directory.

Consider adding a check to ensure the resolved path remains within the expected renderer directory:

🔒 Proposed fix to prevent path traversal
 			protocol.handle(PROTOCOL_SCHEME, (request) => {
 				// Parse URL to extract pathname (e.g., superset://app/index.html#/ -> /index.html)
 				const parsedUrl = new URL(request.url);
 				const pathname = parsedUrl.pathname;

 				// Renderer files are unpacked from asar for protocol handler access
 				// They're located in app.asar.unpacked/dist/renderer instead of app.asar/dist/renderer
 				const rendererPath = __dirname.replace("app.asar", "app.asar.unpacked");
+				const rendererDir = path.normalize(path.join(rendererPath, "../renderer"));
 				const filePath = path.normalize(
 					path.join(rendererPath, "../renderer", pathname),
 				);

+				// Prevent path traversal attacks
+				if (!filePath.startsWith(rendererDir)) {
+					console.error("[protocol-handler] Path traversal attempt blocked:", request.url);
+					return new Response("Forbidden", { status: 403 });
+				}
+
 				console.log("[protocol-handler] Request URL:", request.url);
 				console.log("[protocol-handler] File path:", filePath);

 				return net.fetch(`file://${filePath}`);
 			});
🧹 Nitpick comments (1)
apps/desktop/src/main/index.ts (1)

226-227: Consider removing or gating debug logs for production.

The logging follows the correct [domain/operation] pattern and is useful for troubleshooting. However, these logs will emit for every resource request (JS, CSS, images, etc.) in production, which could be noisy.

Consider either:

  1. Removing after verifying the fix works
  2. Gating behind a DEBUG environment variable
  3. Using a lower log level if a logging framework is available
📜 Review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 213cc65 and 9c6cbe6.

📒 Files selected for processing (2)
  • apps/desktop/electron-builder.ts
  • apps/desktop/src/main/index.ts
🧰 Additional context used
📓 Path-based instructions (5)
apps/desktop/**/*.{ts,tsx}

📄 CodeRabbit inference engine (apps/desktop/AGENTS.md)

apps/desktop/**/*.{ts,tsx}: For Electron interprocess communication, ALWAYS use tRPC as defined in src/lib/trpc
Use alias as defined in tsconfig.json when possible
Prefer zustand for state management if it makes sense. Do not use effect unless absolutely necessary.
For tRPC subscriptions with trpc-electron, ALWAYS use the observable pattern from @trpc/server/observable instead of async generators, as the library explicitly checks isObservable(result) and throws an error otherwise

Files:

  • apps/desktop/src/main/index.ts
  • apps/desktop/electron-builder.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{ts,tsx}: Use object parameters for functions with 2+ parameters instead of positional arguments
Functions with 2+ parameters should accept a single params object with named properties for self-documentation and extensibility
Use prefixed console logging with context pattern: [domain/operation] message
Extract magic numbers and hardcoded values to named constants at module top
Use lookup objects/maps instead of repeated if (type === ...) conditionals
Avoid using any type - maintain type safety in TypeScript code
Never swallow errors silently - at minimum log them with context
Import from concrete files directly when possible - avoid barrel file abuse that creates circular dependencies
Avoid deep nesting (4+ levels) - use early returns, extract functions, and invert conditions
Use named properties in options objects instead of boolean parameters to avoid boolean blindness

Files:

  • apps/desktop/src/main/index.ts
  • apps/desktop/electron-builder.ts
apps/**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

Use Drizzle ORM for all database operations - never use raw SQL

Files:

  • apps/desktop/src/main/index.ts
  • apps/desktop/electron-builder.ts
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (AGENTS.md)

Use Biome for formatting and linting - run at root level with bun run lint:fix or biome check --write

Files:

  • apps/desktop/src/main/index.ts
  • apps/desktop/electron-builder.ts
apps/desktop/src/main/index.ts

📄 CodeRabbit inference engine (AGENTS.md)

Load environment variables from monorepo root .env in desktop app with override: true before any imports in src/main/index.ts and electron.vite.config.ts

Files:

  • apps/desktop/src/main/index.ts
🧠 Learnings (3)
📚 Learning: 2026-01-02T06:50:28.671Z
Learnt from: CR
Repo: superset-sh/superset PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-02T06:50:28.671Z
Learning: Applies to apps/desktop/src/renderer/**/*.{ts,tsx} : Never import Node.js modules (fs, path, os, net) in renderer process or shared code - they are externalized for browser compatibility

Applied to files:

  • apps/desktop/src/main/index.ts
  • apps/desktop/electron-builder.ts
📚 Learning: 2026-01-02T06:50:28.671Z
Learnt from: CR
Repo: superset-sh/superset PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-02T06:50:28.671Z
Learning: Applies to apps/desktop/src/lib/electron-router-dom.ts : Do not import Node.js modules like node:path or dotenv in electron-router-dom.ts and similar shared files - they run in both main and renderer processes

Applied to files:

  • apps/desktop/src/main/index.ts
  • apps/desktop/electron-builder.ts
📚 Learning: 2026-01-02T06:50:28.671Z
Learnt from: CR
Repo: superset-sh/superset PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-02T06:50:28.671Z
Learning: Applies to apps/desktop/src/lib/*.ts : Never import Node.js modules in shared code like electron-router-dom.ts - it runs in both main and renderer processes

Applied to files:

  • apps/desktop/src/main/index.ts
  • apps/desktop/electron-builder.ts
🔇 Additional comments (1)
apps/desktop/electron-builder.ts (1)

47-48: LGTM!

The addition of **/dist/renderer/**/* to asarUnpack correctly addresses the root cause where net.fetch() with file:// URLs cannot access files inside asar archives. The comment clearly documents the reasoning.

✏️ Tip: You can disable this entire section by setting review_details to false in your review settings.

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 1

🤖 Fix all issues with AI agents
In `@apps/desktop/src/main/index.ts`:
- Around line 217-240: The protocol handler in protocol.handle (PROTOCOL_SCHEME)
currently joins the untrusted parsedUrl.pathname into rendererPath without
validation, allowing path traversal; fix it by resolving the renderer base
directory (e.g., const rendererDir =
path.resolve(__dirname.replace("app.asar","app.asar.unpacked"), "../renderer")),
then compute the candidate path via path.resolve(rendererDir, pathname) and
verify the candidate path starts with rendererDir + path.sep (or equals
rendererDir); if the check fails, reject the request (throw or return an
error/403) instead of calling net.fetch. Also sanitize/remove leading slashes
from parsedUrl.pathname or reject any pathname containing ".." before resolving
to be extra safe; reference symbols: protocol.handle, parsedUrl, pathname,
rendererPath/rendererDir, filePath, net.fetch.
🧹 Nitpick comments (2)
apps/desktop/src/lib/window-loader.ts (1)

38-48: Event listeners are never removed — potential for duplicate handlers.

If registerRoute is called multiple times for the same BrowserWindow, each call appends new did-finish-load and did-fail-load listeners. Consider using once if only the initial load matters, or removing previous listeners before adding new ones.

♻️ Option: Use `once` for initial load logging
-	props.browserWindow.webContents.on("did-finish-load", () => {
+	props.browserWindow.webContents.once("did-finish-load", () => {
 		console.log("[window-loader] Successfully loaded:", props.browserWindow.webContents.getURL());
 	});

-	props.browserWindow.webContents.on("did-fail-load", (_event, errorCode, errorDescription, validatedURL) => {
+	props.browserWindow.webContents.once("did-fail-load", (_event, errorCode, errorDescription, validatedURL) => {
 		console.error("[window-loader] Failed to load URL:", validatedURL);
 		console.error("[window-loader] Error code:", errorCode);
 		console.error("[window-loader] Error description:", errorDescription);
 	});
apps/desktop/src/main/index.ts (1)

230-233: Consider reducing log verbosity in production.

These logs emit for every protocol request, which could be noisy. Once the fix is verified working, consider removing or gating behind a debug flag.

📜 Review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 9c6cbe6 and 2e8de29.

📒 Files selected for processing (2)
  • apps/desktop/src/lib/window-loader.ts
  • apps/desktop/src/main/index.ts
🧰 Additional context used
📓 Path-based instructions (6)
apps/desktop/**/*.{ts,tsx}

📄 CodeRabbit inference engine (apps/desktop/AGENTS.md)

apps/desktop/**/*.{ts,tsx}: For Electron interprocess communication, ALWAYS use tRPC as defined in src/lib/trpc
Use alias as defined in tsconfig.json when possible
Prefer zustand for state management if it makes sense. Do not use effect unless absolutely necessary.
For tRPC subscriptions with trpc-electron, ALWAYS use the observable pattern from @trpc/server/observable instead of async generators, as the library explicitly checks isObservable(result) and throws an error otherwise

Files:

  • apps/desktop/src/main/index.ts
  • apps/desktop/src/lib/window-loader.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{ts,tsx}: Use object parameters for functions with 2+ parameters instead of positional arguments
Functions with 2+ parameters should accept a single params object with named properties for self-documentation and extensibility
Use prefixed console logging with context pattern: [domain/operation] message
Extract magic numbers and hardcoded values to named constants at module top
Use lookup objects/maps instead of repeated if (type === ...) conditionals
Avoid using any type - maintain type safety in TypeScript code
Never swallow errors silently - at minimum log them with context
Import from concrete files directly when possible - avoid barrel file abuse that creates circular dependencies
Avoid deep nesting (4+ levels) - use early returns, extract functions, and invert conditions
Use named properties in options objects instead of boolean parameters to avoid boolean blindness

Files:

  • apps/desktop/src/main/index.ts
  • apps/desktop/src/lib/window-loader.ts
apps/**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

Use Drizzle ORM for all database operations - never use raw SQL

Files:

  • apps/desktop/src/main/index.ts
  • apps/desktop/src/lib/window-loader.ts
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (AGENTS.md)

Use Biome for formatting and linting - run at root level with bun run lint:fix or biome check --write

Files:

  • apps/desktop/src/main/index.ts
  • apps/desktop/src/lib/window-loader.ts
apps/desktop/src/main/index.ts

📄 CodeRabbit inference engine (AGENTS.md)

Load environment variables from monorepo root .env in desktop app with override: true before any imports in src/main/index.ts and electron.vite.config.ts

Files:

  • apps/desktop/src/main/index.ts
apps/desktop/src/lib/*.ts

📄 CodeRabbit inference engine (AGENTS.md)

Never import Node.js modules in shared code like electron-router-dom.ts - it runs in both main and renderer processes

Files:

  • apps/desktop/src/lib/window-loader.ts
🧠 Learnings (2)
📚 Learning: 2026-01-02T06:50:28.671Z
Learnt from: CR
Repo: superset-sh/superset PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-02T06:50:28.671Z
Learning: Applies to apps/desktop/src/renderer/**/*.{ts,tsx} : Never import Node.js modules (fs, path, os, net) in renderer process or shared code - they are externalized for browser compatibility

Applied to files:

  • apps/desktop/src/main/index.ts
📚 Learning: 2026-01-02T06:50:28.671Z
Learnt from: CR
Repo: superset-sh/superset PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-02T06:50:28.671Z
Learning: Applies to apps/desktop/src/lib/electron-router-dom.ts : Do not import Node.js modules like node:path or dotenv in electron-router-dom.ts and similar shared files - they run in both main and renderer processes

Applied to files:

  • apps/desktop/src/main/index.ts
🧬 Code graph analysis (1)
apps/desktop/src/lib/window-loader.ts (1)
apps/desktop/src/shared/constants.ts (1)
  • PROTOCOL_SCHEME (30-31)
🔇 Additional comments (2)
apps/desktop/src/lib/window-loader.ts (1)

27-27: LGTM on logging additions.

The debug logging follows the [domain/operation] message pattern correctly and will help troubleshoot production protocol issues.

Also applies to: 34-34

apps/desktop/src/main/index.ts (1)

214-216: LGTM on registration logging.

The diagnostic logging for __dirname will help verify path resolution in production builds.

✏️ Tip: You can disable this entire section by setting review_details to false in your review settings.

Comment thread apps/desktop/src/main/index.ts Resolved

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 1

📜 Review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 83584b7 and 0c94a8b.

📒 Files selected for processing (1)
  • packages/auth/src/server.ts
🧰 Additional context used
📓 Path-based instructions (2)
**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{ts,tsx}: Use object parameters for functions with 2+ parameters instead of positional arguments
Functions with 2+ parameters should accept a single params object with named properties for self-documentation and extensibility
Use prefixed console logging with context pattern: [domain/operation] message
Extract magic numbers and hardcoded values to named constants at module top
Use lookup objects/maps instead of repeated if (type === ...) conditionals
Avoid using any type - maintain type safety in TypeScript code
Never swallow errors silently - at minimum log them with context
Import from concrete files directly when possible - avoid barrel file abuse that creates circular dependencies
Avoid deep nesting (4+ levels) - use early returns, extract functions, and invert conditions
Use named properties in options objects instead of boolean parameters to avoid boolean blindness

Files:

  • packages/auth/src/server.ts
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (AGENTS.md)

Use Biome for formatting and linting - run at root level with bun run lint:fix or biome check --write

Files:

  • packages/auth/src/server.ts
🧠 Learnings (4)
📚 Learning: 2025-12-21T04:39:28.543Z
Learnt from: CR
Repo: superset-sh/superset PR: 0
File: apps/desktop/AGENTS.md:0-0
Timestamp: 2025-12-21T04:39:28.543Z
Learning: Applies to apps/desktop/**/*.{ts,tsx} : For Electron interprocess communication, ALWAYS use tRPC as defined in `src/lib/trpc`

Applied to files:

  • packages/auth/src/server.ts
📚 Learning: 2026-01-02T06:50:28.671Z
Learnt from: CR
Repo: superset-sh/superset PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-02T06:50:28.671Z
Learning: Applies to apps/desktop/src/lib/electron-router-dom.ts : Do not import Node.js modules like node:path or dotenv in electron-router-dom.ts and similar shared files - they run in both main and renderer processes

Applied to files:

  • packages/auth/src/server.ts
📚 Learning: 2026-01-02T06:50:28.671Z
Learnt from: CR
Repo: superset-sh/superset PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-02T06:50:28.671Z
Learning: Applies to apps/desktop/src/renderer/**/*.{ts,tsx} : Never import Node.js modules (fs, path, os, net) in renderer process or shared code - they are externalized for browser compatibility

Applied to files:

  • packages/auth/src/server.ts
📚 Learning: 2026-01-02T06:50:28.671Z
Learnt from: CR
Repo: superset-sh/superset PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-02T06:50:28.671Z
Learning: Applies to apps/desktop/src/lib/*.ts : Never import Node.js modules in shared code like electron-router-dom.ts - it runs in both main and renderer processes

Applied to files:

  • packages/auth/src/server.ts
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: build / Build - macOS (arm64)

✏️ Tip: You can disable this entire section by setting review_details to false in your review settings.

Comment thread packages/auth/src/server.ts Resolved
…l not needed

The custom protocol handler (superset://) was added under the assumption it was needed
for Better Auth CORS, but this was incorrect:

1. Better Auth makes requests to the remote API server (env.NEXT_PUBLIC_API_URL),
   not the local app origin
2. The desktop app uses bearer token authentication, not cookies
3. OAuth deep linking (superset://auth/callback) is handled separately via
   app.setAsDefaultProtocolClient() and doesn't require a file-serving protocol

Changes:
- Remove protocol.registerSchemesAsPrivileged() - not needed
- Remove protocol.handle() file-serving handler - not needed
- Remove unpacking of renderer files from asar - not needed
- Switch back to standard loadFile() in production (like before commit c5f0b67)
- Keep OAuth deep link handling (app.setAsDefaultProtocolClient) - still needed

This simplifies the architecture and uses the standard Electron pattern that 90% of
apps use. The app now loads via file:// protocol in production, which works fine
with Better Auth since all auth requests go to the remote API server.
The desktop app now loads via standard loadFile() which uses the file:// protocol.
Better Auth needs to trust this origin for the desktop app's API requests.
@saddlepaddle
saddlepaddle force-pushed the fix/desktop-production-protocol-handler branch from 0f0d80b to 2c0efd4 Compare January 15, 2026 22:18

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 1

🤖 Fix all issues with AI agents
In `@apps/desktop/src/lib/window-loader.ts`:
- Around line 23-33: registerRoute defines a query object but the dev and prod
loaders drop it; fix registerRoute/loader to preserve query by serializing the
query into the dev URL and by passing it to loadFile in production: when calling
props.browserWindow.loadURL in the isDev branch, append a properly encoded query
string (e.g., new URLSearchParams(props.query).toString()) to the URL while
keeping the "#/" hash, and when calling props.browserWindow.loadFile in the else
branch, pass the query object as the query option in the second argument
(props.browserWindow.loadFile(props.htmlFile, { hash: "/", query: props.query
})). Ensure you reference the existing symbols props.browserWindow.loadURL,
props.browserWindow.loadFile, and props.query/registerRoute so callers' query
params are preserved.
📜 Review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 52e7ed5 and 2fdee75.

📒 Files selected for processing (2)
  • apps/desktop/src/lib/window-loader.ts
  • apps/desktop/src/main/index.ts
🧰 Additional context used
📓 Path-based instructions (6)
apps/desktop/**/*.{ts,tsx}

📄 CodeRabbit inference engine (apps/desktop/AGENTS.md)

apps/desktop/**/*.{ts,tsx}: For Electron interprocess communication, ALWAYS use tRPC as defined in src/lib/trpc
Use alias as defined in tsconfig.json when possible
Prefer zustand for state management if it makes sense. Do not use effect unless absolutely necessary.
For tRPC subscriptions with trpc-electron, ALWAYS use the observable pattern from @trpc/server/observable instead of async generators, as the library explicitly checks isObservable(result) and throws an error otherwise

Files:

  • apps/desktop/src/lib/window-loader.ts
  • apps/desktop/src/main/index.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

**/*.{ts,tsx}: Use object parameters for functions with 2+ parameters instead of positional arguments
Functions with 2+ parameters should accept a single params object with named properties for self-documentation and extensibility
Use prefixed console logging with context pattern: [domain/operation] message
Extract magic numbers and hardcoded values to named constants at module top
Use lookup objects/maps instead of repeated if (type === ...) conditionals
Avoid using any type - maintain type safety in TypeScript code
Never swallow errors silently - at minimum log them with context
Import from concrete files directly when possible - avoid barrel file abuse that creates circular dependencies
Avoid deep nesting (4+ levels) - use early returns, extract functions, and invert conditions
Use named properties in options objects instead of boolean parameters to avoid boolean blindness

Files:

  • apps/desktop/src/lib/window-loader.ts
  • apps/desktop/src/main/index.ts
apps/desktop/src/lib/*.ts

📄 CodeRabbit inference engine (AGENTS.md)

Never import Node.js modules in shared code like electron-router-dom.ts - it runs in both main and renderer processes

Files:

  • apps/desktop/src/lib/window-loader.ts
apps/**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

Use Drizzle ORM for all database operations - never use raw SQL

Files:

  • apps/desktop/src/lib/window-loader.ts
  • apps/desktop/src/main/index.ts
**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (AGENTS.md)

Use Biome for formatting and linting - run at root level with bun run lint:fix or biome check --write

Files:

  • apps/desktop/src/lib/window-loader.ts
  • apps/desktop/src/main/index.ts
apps/desktop/src/main/index.ts

📄 CodeRabbit inference engine (AGENTS.md)

Load environment variables from monorepo root .env in desktop app with override: true before any imports in src/main/index.ts and electron.vite.config.ts

Files:

  • apps/desktop/src/main/index.ts
🧠 Learnings (7)
📓 Common learnings
Learnt from: CR
Repo: superset-sh/superset PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-02T06:50:28.671Z
Learning: Applies to apps/desktop/src/lib/electron-router-dom.ts : Do not import Node.js modules like node:path or dotenv in electron-router-dom.ts and similar shared files - they run in both main and renderer processes
📚 Learning: 2026-01-02T06:50:28.671Z
Learnt from: CR
Repo: superset-sh/superset PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-02T06:50:28.671Z
Learning: Applies to apps/desktop/src/lib/electron-router-dom.ts : Do not import Node.js modules like node:path or dotenv in electron-router-dom.ts and similar shared files - they run in both main and renderer processes

Applied to files:

  • apps/desktop/src/lib/window-loader.ts
  • apps/desktop/src/main/index.ts
📚 Learning: 2025-12-21T04:39:28.543Z
Learnt from: CR
Repo: superset-sh/superset PR: 0
File: apps/desktop/AGENTS.md:0-0
Timestamp: 2025-12-21T04:39:28.543Z
Learning: Applies to apps/desktop/**/*.{ts,tsx} : For Electron interprocess communication, ALWAYS use tRPC as defined in `src/lib/trpc`

Applied to files:

  • apps/desktop/src/lib/window-loader.ts
  • apps/desktop/src/main/index.ts
📚 Learning: 2026-01-02T06:50:28.671Z
Learnt from: CR
Repo: superset-sh/superset PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-02T06:50:28.671Z
Learning: Applies to apps/desktop/src/lib/*.ts : Never import Node.js modules in shared code like electron-router-dom.ts - it runs in both main and renderer processes

Applied to files:

  • apps/desktop/src/lib/window-loader.ts
  • apps/desktop/src/main/index.ts
📚 Learning: 2026-01-02T06:50:28.671Z
Learnt from: CR
Repo: superset-sh/superset PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-02T06:50:28.671Z
Learning: Applies to apps/desktop/src/renderer/**/*.{ts,tsx} : Never import Node.js modules (fs, path, os, net) in renderer process or shared code - they are externalized for browser compatibility

Applied to files:

  • apps/desktop/src/main/index.ts
📚 Learning: 2026-01-02T06:50:28.671Z
Learnt from: CR
Repo: superset-sh/superset PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-02T06:50:28.671Z
Learning: Applies to apps/desktop/src/main/index.ts : Load environment variables from monorepo root .env in desktop app with override: true before any imports in src/main/index.ts and electron.vite.config.ts

Applied to files:

  • apps/desktop/src/main/index.ts
📚 Learning: 2025-12-21T04:39:28.543Z
Learnt from: CR
Repo: superset-sh/superset PR: 0
File: apps/desktop/AGENTS.md:0-0
Timestamp: 2025-12-21T04:39:28.543Z
Learning: Applies to apps/desktop/**/*.{ts,tsx} : Use alias as defined in `tsconfig.json` when possible

Applied to files:

  • apps/desktop/src/main/index.ts
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: Build
🔇 Additional comments (4)
apps/desktop/src/lib/window-loader.ts (3)

2-2: Nice cleanup of the import surface.

No issues here.


8-14: Docs align with the new hash-based/file:// behavior.

Thanks for keeping the comment accurate.


35-51: The premise of this review is incorrect. registerRoute is called exactly once per window during creation in createWindow(). While the main window does register additional listeners for the same events (in main/windows/main.ts lines 189 and 198), these are intentional and complementary—the generic listeners in window-loader.ts provide initialization logging, while the main window listeners handle window restoration (maximization state) and fallback UI display on load failures. There is no problematic listener stacking from multiple registerRoute calls.

Likely an incorrect or invalid review comment.

apps/desktop/src/main/index.ts (1)

7-7: Import cleanup confirmed. Line 7 imports only the required Electron symbols (app, BrowserWindow, dialog), and no remaining net or protocol references exist in the file.

✏️ Tip: You can disable this entire section by setting review_details to false in your review settings.

Comment on lines 23 to 33
if (isDev) {
// Development: load from Vite dev server with hash routing
const url = `http://localhost:${PORTS.VITE_DEV_SERVER}/#/`;
console.log(`[window-loader] Loading dev URL: ${url}`);
props.browserWindow.loadURL(url).catch((error) => {
console.error("[window-loader] Failed to load dev URL:", error);
});
console.log("[window-loader] Loading development URL:", url);
props.browserWindow.loadURL(url);
} else {
// Production: load from custom protocol with hash routing
// Origin becomes: superset://app (trusted by Better Auth)
// Split on both forward and back slashes for cross-platform compatibility
const fileName = props.htmlFile.split(/[/\\]/).pop() || "index.html";
const url = `${PROTOCOL_SCHEME}://app/${fileName}#/`;
console.log(`[window-loader] Loading production URL: ${url}`);
console.log(`[window-loader] HTML file path: ${props.htmlFile}`);
props.browserWindow.loadURL(url).catch((error) => {
console.error("[window-loader] Failed to load production URL:", error);
console.error("[window-loader] Attempted URL:", url);
});
// Production: load from file with hash routing
// TanStack Router uses hash-based routing, so we always start at #/
console.log("[window-loader] Loading file:", props.htmlFile);
props.browserWindow.loadFile(props.htmlFile, { hash: "/" });
}

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.

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

# First, let's look at the window-loader.ts file to understand the context
cat -n apps/desktop/src/lib/window-loader.ts

Repository: superset-sh/superset

Length of output: 2212


🏁 Script executed:

# Search for callers of registerRoute function
rg "registerRoute" --type ts --type tsx -A 3 -B 3

Repository: superset-sh/superset

Length of output: 91


🏁 Script executed:

# Also check the Electron version in package.json to verify API compatibility
cat -n package.json | grep -A 2 -B 2 '"electron"'

Repository: superset-sh/superset

Length of output: 46


🏁 Script executed:

# Search for callers of registerRoute function
rg "registerRoute" -A 3 -B 3

Repository: superset-sh/superset

Length of output: 2237


🏁 Script executed:

# Check Electron version in package.json
cat package.json | grep electron

Repository: superset-sh/superset

Length of output: 46


🏁 Script executed:

# Search for Electron version in different locations
find . -name "package.json" -type f | xargs grep -l "electron" 2>/dev/null | head -5

Repository: superset-sh/superset

Length of output: 91


🏁 Script executed:

# Get more context about registerRoute calls
rg "registerRoute\(" -A 5

Repository: superset-sh/superset

Length of output: 923


🏁 Script executed:

# Get Electron version from desktop package.json
cat apps/desktop/package.json | grep -A 2 -B 2 '"electron"'

Repository: superset-sh/superset

Length of output: 228


🏁 Script executed:

# Check if query params are passed anywhere when calling registerRoute or createWindow
rg "createWindow" -A 10 | head -50

Repository: superset-sh/superset

Length of output: 3860


🏁 Script executed:

# Get full context of the create.ts file to see if query params are passed
cat -n apps/desktop/src/lib/electron-app/factories/windows/create.ts

Repository: superset-sh/superset

Length of output: 996


🏁 Script executed:

# Check main.ts to see all createWindow calls and if query params are used
cat -n apps/desktop/src/main/windows/main.ts | head -100

Repository: superset-sh/superset

Length of output: 3911


🏁 Script executed:

# Check the WindowProps type definition to see if it includes query
cat -n apps/desktop/src/shared/types/electron.ts

Repository: superset-sh/superset

Length of output: 352


🏁 Script executed:

# Check if Electron's BrowserWindow.loadFile supports query parameter
# Let's search for any documentation or comments about this
rg "loadFile" -B 3 -A 3

Repository: superset-sh/superset

Length of output: 606


🏁 Script executed:

# Check if there are any tests or examples showing loadFile usage
rg "loadFile\(" --type-list

Repository: superset-sh/superset

Length of output: 453


🌐 Web query:

Electron BrowserWindow loadFile query parameter API v39

💡 Result:

Yes — in Electron v39 the loadFile API accepts an options object with query/search/hash that are passed to url.format. Use it like:

  • Main (main process)
    const { BrowserWindow } = require('electron')
    const win = new BrowserWindow()
    await win.loadFile('index.html', {
    query: { foo: 'bar', id: '42' }, // becomes ?foo=bar&id=42
    hash: 'section1' // becomes #section1
    })

  • Renderer (in the loaded page) read via location:
    location.search // "?foo=bar&id=42"
    new URLSearchParams(location.search).get('foo') // "bar"
    location.hash // "#section1"

References: Electron docs for webContents/loadFile and BrowserWindow loadFile options, and example of reading location in renderer. [1][2][3]

Sources:
[1] Electron webContents.loadFile / options (query/search/hash).
[2] Electron BrowserWindow.loadFile (same options).
[3] Example: reading query/hash via location in renderer (StackOverflow).


🏁 Script executed:

# Check if TanStack Router or the renderer actually uses query params with hash routing
rg "query" apps/desktop/src -B 2 -A 2 | head -60

Repository: superset-sh/superset

Length of output: 3855


🏁 Script executed:

# Check the router configuration to understand routing setup
find apps/desktop -name "*router*" -type f | head -10

Repository: superset-sh/superset

Length of output: 46


🏁 Script executed:

# Search for any actual usage of createWindow or registerRoute with query params
rg "query.*:" apps/desktop/src -B 3 -A 3

Repository: superset-sh/superset

Length of output: 17606


🏁 Script executed:

# Check if there are any about window or other window creations that might use query
find apps/desktop/src -name "*.ts" -exec grep -l "about" {} \; | head -10

Repository: superset-sh/superset

Length of output: 315


🏁 Script executed:

# Search for about window creation
rg "about" apps/desktop/src -B 2 -A 2 | grep -i window

Repository: superset-sh/superset

Length of output: 347


🏁 Script executed:

# Check if any code is trying to use the query param anywhere
rg "props\.query" apps/desktop/src

Repository: superset-sh/superset

Length of output: 46


🏁 Script executed:

# Look for about window creation
rg "about" apps/desktop/src --type ts -B 5 -A 5

Repository: superset-sh/superset

Length of output: 8320


🏁 Script executed:

# Check if there are any other calls to registerRoute we might have missed
rg "registerRoute" apps/desktop/src --type ts -B 2 -A 10

Repository: superset-sh/superset

Length of output: 3801


Preserve query parameters when building the dev/prod URL.

The query parameter is defined in registerRoute (line 19) but is not passed through to loadURL or loadFile in either code path (lines 25–32). Although no current callers pass query params, if they do in the future, the params will be silently lost. Electron v39's loadFile API supports a query option in its second argument, and loadURL can accept query params in the URL.

🛠️ Proposed fix
 	if (isDev) {
 		// Development: load from Vite dev server with hash routing
-		const url = `http://localhost:${PORTS.VITE_DEV_SERVER}/#/`;
+		const query =
+			props.query && Object.keys(props.query).length > 0
+				? `?${new URLSearchParams(props.query).toString()}`
+				: "";
+		const url = `http://localhost:${PORTS.VITE_DEV_SERVER}/${query}#/`;
 		console.log("[window-loader] Loading development URL:", url);
 		props.browserWindow.loadURL(url);
 	} else {
 		// Production: load from file with hash routing
 		// TanStack Router uses hash-based routing, so we always start at `#/`
 		console.log("[window-loader] Loading file:", props.htmlFile);
-		props.browserWindow.loadFile(props.htmlFile, { hash: "/" });
+		props.browserWindow.loadFile(props.htmlFile, {
+			hash: "/",
+			query: props.query,
+		});
 	}
📝 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
if (isDev) {
// Development: load from Vite dev server with hash routing
const url = `http://localhost:${PORTS.VITE_DEV_SERVER}/#/`;
console.log(`[window-loader] Loading dev URL: ${url}`);
props.browserWindow.loadURL(url).catch((error) => {
console.error("[window-loader] Failed to load dev URL:", error);
});
console.log("[window-loader] Loading development URL:", url);
props.browserWindow.loadURL(url);
} else {
// Production: load from custom protocol with hash routing
// Origin becomes: superset://app (trusted by Better Auth)
// Split on both forward and back slashes for cross-platform compatibility
const fileName = props.htmlFile.split(/[/\\]/).pop() || "index.html";
const url = `${PROTOCOL_SCHEME}://app/${fileName}#/`;
console.log(`[window-loader] Loading production URL: ${url}`);
console.log(`[window-loader] HTML file path: ${props.htmlFile}`);
props.browserWindow.loadURL(url).catch((error) => {
console.error("[window-loader] Failed to load production URL:", error);
console.error("[window-loader] Attempted URL:", url);
});
// Production: load from file with hash routing
// TanStack Router uses hash-based routing, so we always start at #/
console.log("[window-loader] Loading file:", props.htmlFile);
props.browserWindow.loadFile(props.htmlFile, { hash: "/" });
}
if (isDev) {
// Development: load from Vite dev server with hash routing
const query =
props.query && Object.keys(props.query).length > 0
? `?${new URLSearchParams(props.query).toString()}`
: "";
const url = `http://localhost:${PORTS.VITE_DEV_SERVER}/${query}#/`;
console.log("[window-loader] Loading development URL:", url);
props.browserWindow.loadURL(url);
} else {
// Production: load from file with hash routing
// TanStack Router uses hash-based routing, so we always start at `#/`
console.log("[window-loader] Loading file:", props.htmlFile);
props.browserWindow.loadFile(props.htmlFile, {
hash: "/",
query: props.query,
});
}
🤖 Prompt for AI Agents
In `@apps/desktop/src/lib/window-loader.ts` around lines 23 - 33, registerRoute
defines a query object but the dev and prod loaders drop it; fix
registerRoute/loader to preserve query by serializing the query into the dev URL
and by passing it to loadFile in production: when calling
props.browserWindow.loadURL in the isDev branch, append a properly encoded query
string (e.g., new URLSearchParams(props.query).toString()) to the URL while
keeping the "#/" hash, and when calling props.browserWindow.loadFile in the else
branch, pass the query object as the query option in the second argument
(props.browserWindow.loadFile(props.htmlFile, { hash: "/", query: props.query
})). Ensure you reference the existing symbols props.browserWindow.loadURL,
props.browserWindow.loadFile, and props.query/registerRoute so callers' query
params are preserved.

@saddlepaddle
saddlepaddle merged commit 7a2b42b into main Jan 15, 2026
5 checks passed
@github-actions

Copy link
Copy Markdown
Contributor

🧹 Preview Cleanup Complete

The following preview resources have been cleaned up:

  • ⚠️ Neon database branch
  • ⚠️ Electric Fly.io app

Thank you for your contribution! 🎉

@Kitenite
Kitenite deleted the fix/desktop-production-protocol-handler branch January 16, 2026 18:08
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