Skip to content

fix: resolve ESM crashes and enable multi-instance Electron for worktrees - #77

Merged
fum4 merged 4 commits into
masterfrom
various-fixes
Mar 16, 2026
Merged

fum4 merged 4 commits into
masterfrom
various-fixes

Conversation

@fum4

@fum4 fum4 commented Mar 16, 2026 •

Copy link
Copy Markdown
Owner
  • add "type": "module" to lib packages missing it (logger/node, logger/browser, agents, integrations) (Node.js v25 + tsx treated them as CJS, breaking named ESM exports)
  • switch server dev script from tsx to tsup watch mode (tsx can't load .md files imported by libs/agents in ESM context)
  • bundle @xterm/headless and @xterm/addon-serialize in server tsup (CJS packages fail named-export destructuring under plain node ESM)
  • scope Electron identity per worktree via WM_PORT_OFFSET (single-instance lock was killing worktree Electron immediately)
  • apply port offset to UI_DEV_SERVER_URL in Electron (Chromium networking bypasses both JS and native port hooks)
  • replace hardcoded "OpenKit" with APP_NAME constant in desktop-app

Summary by CodeRabbit

  • New Features

    • Desktop app: worktree support with scoped app naming, adjusted user data path, updated app title/protocol, and dev-server port offset handling for correct UI loading.
  • Chores

    • Switched server dev/watch script to a bundler-based workflow.
    • Enabled ES module resolution across multiple packages.
    • Adjusted bundler configuration to treat additional modules as non-bundled.
  • Refactor

    • Project config: cleaned compiler options, added path alias and exclude rules.

…rees

- add "type": "module" to lib packages missing it (logger/node, logger/browser, agents, integrations)
  (Node.js v25 + tsx treated them as CJS, breaking named ESM exports)
- switch server dev script from tsx to tsup watch mode
  (tsx can't load .md files imported by libs/agents in ESM context)
- bundle @xterm/headless and @xterm/addon-serialize in server tsup
  (CJS packages fail named-export destructuring under plain node ESM)
- scope Electron identity per worktree via __WM_PORT_OFFSET__
  (single-instance lock was killing worktree Electron immediately)
- apply port offset to UI_DEV_SERVER_URL in Electron
  (Chromium networking bypasses both JS and native port hooks)
- replace hardcoded "OpenKit" with APP_NAME constant in desktop-app
@fum4
fum4 requested a review from LunatiqueCoder March 16, 2026 17:30
@fum4 fum4 self-assigned this Mar 16, 2026
@vercel

vercel Bot commented Mar 16, 2026 •

Copy link
Copy Markdown

The latest updates on your projects. Learn more about Vercel for GitHub.

1 Skipped Deployment
Project Deployment Actions Updated (UTC)
openkit Skipped Skipped Mar 16, 2026 8:34pm

@coderabbitai

coderabbitai Bot commented Mar 16, 2026 •

Copy link
Copy Markdown

Caution

Review failed

Pull request was closed or merged during review

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: fdaf89ab-8cf8-4c52-b69b-99d85dc4ce9a

📥 Commits

Reviewing files that changed from the base of the PR and between 0903da0 and 19623c3.

📒 Files selected for processing (1)
  • apps/desktop-app/tsconfig.json

📝 Walkthrough

Walkthrough

Desktop app now scopes APP_NAME and userData by worktree port offsets, updates protocol and window title, and adjusts dev-server URLs for port offsets. tsconfig paths and excludes changed. Server dev script and tsup externals updated. Several libs' package.json files set "type": "module".

Changes

Cohort / File(s) Summary
Desktop App Main
apps/desktop-app/src/main.ts
When a worktree port offset (>0) is detected, append -worktree-N to APP_NAME, adjust app.setPath('userData', ...), change custom protocol to APP_NAME.toLowerCase(), update window title, and apply port-offset adjustments to UI_DEV_SERVER_URL handling and load URL logic. Added explanatory comments.
Desktop App TSConfig
apps/desktop-app/tsconfig.json
Removed several top-level compilerOptions (module, moduleResolution, outDir, rootDir, declaration, sourceMap); added path alias @openkit/shared/* -> ../../libs/shared/src/*; added exclude: [dist, node_modules].
Server Build & Scripts
apps/server/tsup.config.ts, apps/server/package.json
Expanded noExternal in tsup to include @xterm/headless and @xterm/addon-serialize. Replaced dev script to tsup --watch --onSuccess 'node dist/standalone.js' and removed tsx from devDependencies.
Library package.json -> ESM
libs/agents/package.json, libs/integrations/package.json, libs/logger/browser/package.json, libs/logger/node/package.json
Added top-level "type": "module" to each package.json to enable Node ESM module resolution.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐇 I hopped through lines and changed the name,

ports stacked neatly, worktrees play a game,
Modules wear their ESM hat,
tsup wakes the server's cat,
A tiny rabbit cheers—code not the same.

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main objectives: resolving ESM crashes across multiple packages and enabling multi-instance Electron for worktrees with port offset scoping.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch various-fixes
📝 Coding Plan
  • Generate coding plan for human review comments

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

@github-actions

github-actions Bot commented Mar 16, 2026 •

Copy link
Copy Markdown
Contributor

Code Review

🟢 Resolved from Previous Review

  1. Dev URL regex — Remains fixed. Uses new URL() parsing.
  2. PROTOCOL constant naming — Remains fixed. Uses APP_NAME.toLowerCase().
  3. Worktree userData path nesting — Remains fixed. getPath("userData") called before setName().

🟠 Medium

  1. tsx marked optional in lockfile but still used by tsup (pnpm-lock.yaml)
    Still present. tsx is removed from apps/server devDependencies and its transitive deps are now optional: true, but tsup still resolves with [email protected] in its dependency line. The dev script changed from tsx watch to tsup --watch --onSuccess 'node dist/standalone.js', which removes the direct tsx usage — good. However, tsup itself can optionally use tsx for config loading. If tsx disappears from the hoisted node_modules (e.g., if no other workspace package depends on it), tsup may fall back to a different loader or fail on .ts config files. Worth a quick smoke test to confirm tsup works when tsx is truly absent.

  2. noExternal additions without explanation (apps/server/tsup.config.ts:13)
    Still present. @xterm/headless and @xterm/addon-serialize are added to noExternal, bundling them into the server output. A brief comment explaining why these need bundling (e.g., ESM-only packages that fail at runtime without bundling, or standalone deployment requirement) would prevent someone from removing them later.

🟡 Minor

  1. "type": "module" additions (libs/agents, libs/integrations, libs/logger/browser, libs/logger/node)
    Still present. Four packages gain "type": "module". This is likely correct given the ESM migration, but verify no consumer uses require() for these packages.

  2. portOffset NaN guard (apps/desktop-app/src/main.ts:59-61)
    Still present. If __WM_PORT_OFFSET__ is a non-numeric string, Number.parseInt returns NaN, which fails the > 0 check and silently falls back to the default branch. Fine in practice since the env var is set programmatically, but a log.warn on NaN would aid debugging.

  3. tsconfig.json drops explicit compiler options (apps/desktop-app/tsconfig.json)
    The desktop-app tsconfig removes module, moduleResolution, outDir, rootDir, declaration, and sourceMap — presumably inheriting them from tsconfig.base.json. Confirm tsconfig.base.json provides compatible values (especially module: "NodeNext" and moduleResolution: "NodeNext") so the Electron main process code still compiles correctly.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@apps/desktop-app/src/main.ts`:
- Around line 257-261: The current devUrl port rewrite using a regex is brittle;
update the logic that modifies devUrl when portOffset > 0 to parse the string
with the URL class (or fallback by prepending a scheme if missing), adjust the
URL.port by adding portOffset to the parsed numeric port (or set to portOffset
when no port exists), and then serialize back to devUrl so pathname, query, and
hash are preserved; update the block around the devUrl and portOffset handling
to use new URL(...) and url.port manipulation instead of the current regex
replacement.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: d40544ee-725f-4e9a-97c2-d177c8505240

📥 Commits

Reviewing files that changed from the base of the PR and between de1881c and b9d0bc0.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (8)
  • apps/desktop-app/src/main.ts
  • apps/desktop-app/tsconfig.json
  • apps/server/package.json
  • apps/server/tsup.config.ts
  • libs/agents/package.json
  • libs/integrations/package.json
  • libs/logger/browser/package.json
  • libs/logger/node/package.json

Comment thread apps/desktop-app/src/main.ts Resolved
fum4 added 2 commits March 16, 2026 19:38
…t regex

- read userData path before setName to avoid double-nested worktree dir
- use URL parser instead of regex for dev server port offset
- custom URL schemes should be lowercase by convention
  (macOS/Linux normalize them anyway, but argv matching needs consistency)

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🧹 Nitpick comments (1)
apps/desktop-app/src/main.ts (1)

57-72: Consider adding debug logging when worktree mode activates.

When portOffset > 0, a debug log would help diagnose multi-instance issues and confirm the expected configuration is applied.

🔧 Proposed debug log
 if (portOffset > 0) {
   // Resolve userData BEFORE setName, since setName changes the default path.
   const baseUserData = app.getPath("userData");
   const suffix = `-worktree-${portOffset}`;
   app.setName(`${APP_NAME}${suffix}`);
   app.setPath("userData", path.join(baseUserData, `worktree-${portOffset}`));
+  log.debug("running in worktree mode", {
+    domain: "app-init",
+    portOffset,
+    appName: `${APP_NAME}${suffix}`,
+    userData: path.join(baseUserData, `worktree-${portOffset}`),
+  });
 } else {
   app.setName(APP_NAME);
 }

As per coding guidelines: "Always include a domain field in the metadata object to namespace logs by feature area."

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/desktop-app/src/main.ts` around lines 57 - 72, Add a debug log when
worktree mode activates (i.e., when portOffset > 0) to surface the computed
values; log the portOffset, APP_NAME, baseUserData and the suffix before calling
app.setName/app.setPath. Use the existing logging facility (or introduce one if
absent) and include a metadata object with domain set to "worktree" (e.g., {
domain: "worktree", portOffset }). Ensure the log occurs after computing suffix
and before setName/setPath, referencing portOffset, APP_NAME, baseUserData, and
suffix in the message.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@apps/desktop-app/src/main.ts`:
- Around line 259-264: Wrap the URL parsing around a try-catch so a malformed
UI_DEV_SERVER_URL doesn't crash startup: when you construct new URL(devUrl) (the
variable devUrl, and temporary u) guard it with if (devUrl) and try { const u =
new URL(devUrl); u.port = String(Number(u.port) + portOffset); devUrl =
u.toString(); } catch (err) { logger/error handler should log a meaningful
message including the original devUrl and the error (use the app's logger, e.g.,
processLogger.error) and leave devUrl unchanged or apply a safe fallback; ensure
the catch does not rethrow so the app can continue.

---

Nitpick comments:
In `@apps/desktop-app/src/main.ts`:
- Around line 57-72: Add a debug log when worktree mode activates (i.e., when
portOffset > 0) to surface the computed values; log the portOffset, APP_NAME,
baseUserData and the suffix before calling app.setName/app.setPath. Use the
existing logging facility (or introduce one if absent) and include a metadata
object with domain set to "worktree" (e.g., { domain: "worktree", portOffset }).
Ensure the log occurs after computing suffix and before setName/setPath,
referencing portOffset, APP_NAME, baseUserData, and suffix in the message.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: f09a672a-50aa-475b-a04b-1c4cc696248f

📥 Commits

Reviewing files that changed from the base of the PR and between b9d0bc0 and 0903da0.

📒 Files selected for processing (1)
  • apps/desktop-app/src/main.ts

Comment on lines +259 to +264
let devUrl = process.env.UI_DEV_SERVER_URL;
if (portOffset > 0) {
const u = new URL(devUrl);
u.port = String(Number(u.port) + portOffset);
devUrl = u.toString();
}

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Add error handling for URL parsing to prevent app crash on malformed input.

new URL(devUrl) throws if UI_DEV_SERVER_URL is malformed. Without a try-catch, this crashes the app at startup.

🛡️ Proposed fix with error handling
   let devUrl = process.env.UI_DEV_SERVER_URL;
   if (portOffset > 0) {
-    const u = new URL(devUrl);
-    u.port = String(Number(u.port) + portOffset);
-    devUrl = u.toString();
+    try {
+      const u = new URL(devUrl);
+      if (u.port) {
+        u.port = String(Number(u.port) + portOffset);
+        devUrl = u.toString();
+      }
+    } catch (error) {
+      log.warn("failed to apply worktree port offset to UI_DEV_SERVER_URL", {
+        domain: "window-bootstrap",
+        devUrl,
+        portOffset,
+        error,
+      });
+    }
   }
   mainWindow.loadURL(devUrl);

As per coding guidelines: "Every catch block, every fallback branch, every error callback must do something meaningful: log through the appropriate logger."

📝 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
let devUrl = process.env.UI_DEV_SERVER_URL;
if (portOffset > 0) {
const u = new URL(devUrl);
u.port = String(Number(u.port) + portOffset);
devUrl = u.toString();
}
let devUrl = process.env.UI_DEV_SERVER_URL;
if (portOffset > 0) {
try {
const u = new URL(devUrl);
if (u.port) {
u.port = String(Number(u.port) + portOffset);
devUrl = u.toString();
}
} catch (error) {
log.warn("failed to apply worktree port offset to UI_DEV_SERVER_URL", {
domain: "window-bootstrap",
devUrl,
portOffset,
error,
});
}
}
mainWindow.loadURL(devUrl);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/desktop-app/src/main.ts` around lines 259 - 264, Wrap the URL parsing
around a try-catch so a malformed UI_DEV_SERVER_URL doesn't crash startup: when
you construct new URL(devUrl) (the variable devUrl, and temporary u) guard it
with if (devUrl) and try { const u = new URL(devUrl); u.port =
String(Number(u.port) + portOffset); devUrl = u.toString(); } catch (err) {
logger/error handler should log a meaningful message including the original
devUrl and the error (use the app's logger, e.g., processLogger.error) and leave
devUrl unchanged or apply a safe fallback; ensure the catch does not rethrow so
the app can continue.

@fum4
fum4 merged commit b283717 into master Mar 16, 2026
19 checks passed
@fum4
fum4 deleted the various-fixes branch March 16, 2026 20:37

This branch was previously deployed

1 inactive deployment
Preview — 19623c33 Deployed Mar 16, 2026 by vercel[bot]
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