Skip to content

feat: React Native / Expo worktree support - #81

Merged
fum4 merged 4 commits into
masterfrom
feat/react-native-expo-worktree-support
Mar 17, 2026
Merged

fum4 merged 4 commits into
masterfrom
feat/react-native-expo-worktree-support

Conversation

@LunatiqueCoder

@LunatiqueCoder LunatiqueCoder commented Mar 17, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

  • Auto-detect React Native / Expo projects from package.json dependencies (on PortManager construction and during port discovery)
  • PTY spawn for RN/Expo worktrees via node-pty — gives Metro a real TTY so QR codes, press a/press i commands, and interactive output work
  • Metro port offsetting — injects --port <offset> flag directly to the start command so multiple worktrees use different ports
  • Expo env vars — sets CI=0, EXPO_OFFLINE=0 to prevent "Networking has been disabled" warnings
  • RCT_METRO_PORT env var for native app connectivity, with fallback to default port 8081
  • adb reverse on worktree start for Android device connectivity (best-effort)
  • Start command detection — RN/Expo projects get npm start / yarn start instead of npm run dev
  • Extract pty.ts — shared resolveNodePtyModule() used by both manager.ts and terminal-manager.ts
  • RunningProcess type — changed from process: ChildProcess to kill: (signal?) => void to support both ChildProcess and IPty
  • Port hook console.log guarded behind __WM_DEBUG__ env var to reduce noise

Test plan

  • 308 server tests pass (including 85 port-manager tests with new framework detection, port args, env var, and auto-detect suites)
  • 25 shared tests pass (including 14 new detect-config tests)
  • TypeScript compiles cleanly
  • Lint and format checks pass
  • Manual: start two Expo worktrees → verify different ports in logs
  • Manual: verify QR code and interactive Metro output appears
  • Manual: verify generic (non-RN) projects still work with piped stdio

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features

    • Auto-detect React Native/Expo projects, auto-apply Metro port defaults, inject port args and env vars into start commands, and use PTY-backed starts with best-effort ADB reverse.
    • API now exposes detected framework for UIs and tooling.
  • Documentation

    • Added framework configuration docs and a detailed React Native/Expo support guide.
  • Tests

    • Extensive tests covering detection, Metro port resolution, port/env mapping, and start-command behaviors.

…t offsetting

Enable multiple RN/Expo worktrees to run simultaneously by auto-detecting
the project framework and applying Metro-specific port offsetting, PTY
spawning for interactive terminal output (QR codes, press a/i commands),
and adb reverse for Android device connectivity.

- Auto-detect framework from package.json on PortManager construction
- Spawn RN/Expo worktrees via node-pty for real TTY (QR code, interactive UI)
- Inject --port flag to Metro bundler with offset port
- Set RCT_METRO_PORT, CI=0, EXPO_OFFLINE=0 env vars for Expo
- Fall back to default Metro port 8081 when discovery hasn't run
- Add framework field to reloadConfig() and config API
- Extract resolveNodePtyModule to shared pty.ts module
- Change RunningProcess.process to kill() function for PTY compatibility
- Guard port-hook.cjs console.log behind __WM_DEBUG__ env var
- Detect "npm start" as start command for RN/Expo projects
- Run adb reverse on worktree start for Android connectivity
- Add comprehensive tests (framework detection, port args, env vars, auto-detect)

Co-Authored-By: Claude Opus 4.6 <[email protected]>
@vercel

vercel Bot commented Mar 17, 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 17, 2026 6:38pm

@coderabbitai

coderabbitai Bot commented Mar 17, 2026 •

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

Adds framework detection for React Native and Expo, Metro port discovery, merges framework defaults into port discovery and env mappings, spawns RN/Expo worktrees via PTY, runs best-effort adb reverse after start, updates public worktree types, and adds tests and docs.

Changes

Cohort / File(s) Summary
Framework detection
apps/server/src/framework-detect.ts, apps/server/src/framework-detect.test.ts
New detection API: detectFramework and detectMetroPort (DEFAULT_METRO_PORT=8081). Detects expo/react-native from package.json, reads metro.config.* for custom ports, handles malformed/missing files. Comprehensive tests for detection and metro port parsing.
Port manager & env/ports logic
apps/server/src/port-manager.ts, apps/server/src/port-manager.test.ts
PortManager now auto-detects/persists framework, merges framework default ports and env templates, adds getFramework(), needsAdbReverse(), and getStartCommandPortArgs(). Discovery persists env mapping and framework. Tests expanded for env parsing, start-command arg injection, offsets, and .env behavior.
Worktree / process manager & PTY
apps/server/src/manager.ts, apps/server/src/terminal-manager.ts, apps/server/src/pty.ts
Centralized PTY resolver (pty.ts). RN/Expo worktrees spawn via node-pty (when available), unified log streaming, lifecycle handling, new runAdbReverse and improved termination/child-pid cleanup. Terminal manager delegates PTY resolution.
Types & public contracts
libs/shared/src/worktree-types.ts
Added optional framework to WorktreeConfig. RunningProcess no longer exposes ChildProcess; replaced with kill(signal?: string) => void.
Start command & package-manager detection
libs/shared/src/detect-config.ts, libs/shared/src/detect-config.test.ts
Adds local RN/Expo detection to choose start for Metro-based projects; resilient package.json reads; bun detection updated to check bun.lockb/bun.lock. Tests expanded for PM/start-command detection and edge cases.
API route
apps/server/src/routes/config.ts
GET /api/ports response now includes framework from PortManager.
Runtime hook logging
apps/server/src/runtime/port-hook.cjs
Introduces gated debug(...) controlled by __WM_DEBUG__ and replaces direct console.debug/log calls with it.
Docs
docs/CONFIGURATION.md, docs/PORT-MAPPING.md
Documentation updated with RN/Expo support details: framework config, Metro defaults, start-command/--port behavior, PTY usage, and adb reverse notes.
Tests & misc updates
apps/server/src/framework-detect.test.ts, apps/server/src/port-manager.test.ts, libs/shared/src/detect-config.test.ts
Extensive new tests covering detection, port resolution, env parsing/persistence, PM detection, and start-command logic. Test utilities and temp-dir isolation added.

Sequence Diagram

sequenceDiagram
    participant Client
    participant PortManager
    participant FrameworkDetector
    participant WorktreeManager
    participant NodePtyLoader
    participant ADB
    participant Process

    Client->>PortManager: request start / discover ports
    PortManager->>FrameworkDetector: detectFramework(projectDir)
    FrameworkDetector-->>PortManager: FrameworkDetection(fr, defaultPorts, envVarTemplates)
    PortManager->>PortManager: merge defaults, persist framework/env mapping

    WorktreeManager->>PortManager: getFramework()
    PortManager-->>WorktreeManager: framework

    alt framework is react-native or expo
        WorktreeManager->>NodePtyLoader: resolveNodePtyModule()
        NodePtyLoader-->>WorktreeManager: NodePtyModule
        WorktreeManager->>Process: spawn via PTY (cmd,args,env)
    else
        WorktreeManager->>Process: spawn via child_process (cmd,args,env)
    end

    WorktreeManager->>ADB: runAdbReverse(discoveredPorts)
    ADB-->>WorktreeManager: success/failure
    Process-->>WorktreeManager: stdout/stderr, exit
    WorktreeManager->>WorktreeManager: handleExit(), cleanup, emit events
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Poem

🐰 I dug through package.json beneath the moonlight,

I sniffed Metro ports and set defaults just right.
I spawn PTYs, nudge adb to bend, then hop—
persist the framework, tidy logs when processes stop.
A little rabbit patch to keep devs on the hop!

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 18.18% 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 'feat: React Native / Expo worktree support' directly and clearly summarizes the main change: adding React Native and Expo framework support for worktrees, which is the primary objective of this comprehensive pull request.

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

✨ Finishing Touches
  • 📝 Generate docstrings (stacked PR)
  • 📝 Generate docstrings (commit on current branch)
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/react-native-expo-worktree-support
📝 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 17, 2026 •

Copy link
Copy Markdown
Contributor

Clode Review

🟠 Medium

  1. Command injection via non-PTY spawn path — apps/server/src/manager.ts:886-892. The generic spawn path still uses shell: true with a command string split on spaces. The new comment explains the trust model (user-configured .openkit/config.json, same as npm scripts), which is a reasonable justification. However, the naive split on spaces means a start command like PORT=3000 npm run dev will incorrectly split PORT=3000 as the command. The shell: true flag actually masks this since the shell reassembles the string, but it means cmd and args are meaningless — the entire string is passed to the shell regardless. Consider passing the full command as a single string to spawn(command, { shell: true }) without splitting, which is clearer about intent.

  2. Race condition in framework detection — port-manager.ts:45 runs ensureFrameworkDetected() in the constructor, and discoverPorts() at line ~476 runs detectFramework() again, overwriting this.frameworkDetection. The new comment at lines 45-52 acknowledges this is intentional (project state may change), but there's no synchronization. If discoverPorts() runs concurrently with getEnvForOffset() or getStartCommandPortArgs(), the frameworkDetection field could change mid-read. This is likely fine in practice (single-threaded Node), but the dual-detection + dual-persist pattern adds complexity for minimal benefit — consider detecting once lazily instead.

  3. getChildPids only finds direct children — manager.ts:1027-1040. pgrep -P returns only immediate children of parentPid, not the full descendant tree. Metro spawns worker processes that are grandchildren. A recursive approach or pgrep -P with --ancestor (if available) or a library like tree-kill would be more thorough.

  4. isReactNativeProject uses console.warn — libs/shared/src/detect-config.ts:87-91. The comment explains that libs/shared has no logger dependency, but this is a shared library imported by both CLI and server. A console.warn in a library is a code smell — consider accepting an optional logger callback, or simply staying silent (as the server-side detectFramework handles proper logging for the same check).

🟡 Minor

  1. Regex port extraction is fragile — framework-detect.ts:38. The negative lookbehind (?<![a-zA-Z]) prevents matching reportPort and viewport, and the tests at lines 185-210 verify this. However, a key like _port: 9999 or $port: 9999 would still match. Low risk for metro configs, but worth noting.

  2. getStartCommandPortArgs splits on space naively — port-manager.ts:147. startsWith("npm ") won't match /usr/bin/npm. The new JSDoc comment at lines 145-149 documents this as intentional ("OpenKit resolves commands via the user's PATH, not absolute paths"). Addressed.

  3. runAdbReverse uses execFileSync on the hot path — manager.ts:1042-1057. This runs synchronously during worktree start. If adb hangs (e.g., waiting for device authorization), the 5-second timeout will block the event loop. Consider using execFile (async) or spawning in the background.

🟢 Resolved

  1. Temp directories not cleaned up in tests — framework-detect.test.ts:15-33 now tracks created dirs in createdDirs[] and cleans them up in afterAll.

  2. ChildProcess import removed from worktree-types.ts — The process field has been replaced with a kill function on RunningProcess, and manager.ts uses killFn for both PTY and spawn paths.

  3. Port hook connect logs suppressed by default — port-hook.cjs:25-28 now uses a debug() function gated behind __WM_DEBUG__ env var, replacing all raw console.log calls.

  4. getProjectDir() called but not shown in diff — port-manager.ts:55 calls this.getProjectDir(). The method is exercised successfully in tests.

  5. detectStartCommand returns "npm start" instead of "npm run start" — libs/shared/src/detect-config.ts:84 correctly returns "npm start" for RN projects. The new test suite in detect-config.test.ts covers this.

  6. Error handling in catch block — apps/server/src/manager.ts:947-950. The catch block now logs with log.error() and includes domain metadata.

  7. Magic number 8081 repeated — port-manager.ts now imports DEFAULT_METRO_PORT from framework-detect.ts and uses it consistently.

  8. console.warn in shared lib — libs/shared/src/detect-config.ts:78-85. Now has proper ENOENT vs non-ENOENT handling with a comment explaining the trade-off.

  9. Missing bun.lock detection — libs/shared/src/detect-config.ts:65-68 now checks both bun.lockb and bun.lock. Verified by test at detect-config.test.ts:119-123.

  10. node-pty module resolution extracted to shared module — pty.ts extracted from terminal-manager.ts and reused in manager.ts.

  11. PTY process group cleanup improved — manager.ts:987-1010. stopWorktree now walks the process tree via getChildPids() when the process group kill fails, addressing the orphaned-child concern (partially — see Medium build(deps): bump astro from 5.17.2 to 5.17.3 in /website #3 above about recursive traversal).

  12. CI=0 scoped to PTY env only — manager.ts:871-878. CI=0 and EXPO_OFFLINE=0 are now set only in the PTY spawn env, not in getEnvForOffset(). Tests at port-manager.test.ts:949-985 verify this scoping.

  13. bun start handling documented — port-manager.ts:145-149 JSDoc now mentions bun alongside yarn/pnpm. Test at port-manager.test.ts:928-937 covers it.

  14. Command injection via PTY path — The PTY path now passes cmd and args directly to pty.spawn() without shell wrapping, avoiding metacharacter interpretation. The generic path retains shell: true with documented justification.

@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: 2

Caution

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

⚠️ Outside diff range comments (2)
apps/server/src/runtime/port-hook.cjs (1)

62-85: ⚠️ Potential issue | 🟡 Minor

Route debug traces to stderr and parse __WM_DEBUG__ explicitly.

Using if (process.env.__WM_DEBUG__) enables logs for "0", and console.log emits to stdout, which can pollute proxied app output. Prefer a strict flag and stderr for diagnostics.

Suggested patch
+const DEBUG_ENABLED = process.env.__WM_DEBUG__ === "1";
+function debug(msg) {
+  if (DEBUG_ENABLED) process.stderr.write(`[wm-port-hook] ${msg}\n`);
+}
...
-        if (process.env.__WM_DEBUG__) console.log(`connect :${port} → :${args[0]}`);
+        debug(`connect :${port} → :${args[0]}`);
...
-          if (process.env.__WM_DEBUG__) console.log(`connect :${port} → :${port + offset}`);
+          debug(`connect :${port} → :${port + offset}`);
...
-        if (process.env.__WM_DEBUG__) console.log(`connect :${port} → :${port + offset}`);
+        debug(`connect :${port} → :${port + offset}`);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server/src/runtime/port-hook.cjs` around lines 62 - 85, The debug checks
currently use if (process.env.__WM_DEBUG__) and console.log which treats "0" as
truthy and writes to stdout; update each debug condition (the console lines
inside the three connect branches) to only enable when the flag is explicitly
set (e.g., process.env.__WM_DEBUG__ === '1' || process.env.__WM_DEBUG__ ===
'true') and route messages to stderr (replace console.log with console.error or
process.stderr.write). Look for the three debug lines near the connect handling
logic (the blocks that use toPort, knownPortSet, and isLocalhost) and change
their conditions and logging calls accordingly so diagnostics go to stderr only
when the flag is explicitly enabled.
apps/server/src/manager.ts (1)

974-980: ⚠️ Potential issue | 🟡 Minor

Empty catch block violates error handling guidelines.

The inner catch block at line 977-978 silently swallows potential errors. Per coding guidelines, every catch block must log or handle errors meaningfully.

🛠️ Proposed fix
     try {
       processInfo.kill("SIGTERM");
-    } catch {
-      // Process may have already exited
+    } catch (err) {
+      log.debug(`Process ${worktreeId} may have already exited: ${err instanceof Error ? err.message : String(err)}`, {
+        domain: "worktree",
+      });
     }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server/src/manager.ts` around lines 974 - 980, The inner empty catch
that wraps processInfo.kill("SIGTERM") should not silently swallow errors;
change it to catch the error (e.g., catch (err)) and log it using the module's
logger (e.g., processLogger.error or processLogger.warn) including context such
as the PID or processInfo identifier and the error object so failures to send
SIGTERM are recorded; update the catch block around processInfo.kill("SIGTERM")
accordingly and ensure the logger symbol you use exists in this file.
🧹 Nitpick comments (2)
apps/server/src/framework-detect.ts (1)

44-49: Add structured metadata to failure logs for easier triage.

These debug logs currently carry most context in message text. Please add fields like projectDir, configPath/pkgPath, and normalized error in metadata so failures are easier to filter and correlate.

Suggested patch
-      log.debug(
-        `Failed to read ${filename}, falling back to default Metro port: ${err instanceof Error ? err.message : String(err)}`,
-        { domain: "framework-detect" },
-      );
+      log.debug("Failed to read Metro config; falling back to default Metro port", {
+        domain: "framework-detect",
+        projectDir,
+        configPath,
+        filename,
+        error: err instanceof Error ? err.message : String(err),
+      });
...
-    log.debug(`Failed to parse ${pkgPath}: ${err instanceof Error ? err.message : String(err)}`, {
-      domain: "framework-detect",
-    });
+    log.debug("Failed to parse package.json for framework detection", {
+      domain: "framework-detect",
+      projectDir,
+      pkgPath,
+      error: err instanceof Error ? err.message : String(err),
+    });

As per coding guidelines "Include actionable metadata in error logs: what operation failed, what inputs caused it, and any IDs or state needed to reproduce."

Also applies to: 75-78

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

In `@apps/server/src/framework-detect.ts` around lines 44 - 49, The debug log in
the catch block around the read of filename uses only a text message; update the
log.debug call (the one passing `domain: "framework-detect"`) to include
structured metadata keys such as projectDir, configPath or pkgPath (whichever is
relevant in the surrounding code), and a normalized error field (e.g. error:
err?.stack ?? err?.message ?? String(err)) instead of embedding the error only
in the message; do the same change for the analogous log.debug at lines 75-78 so
both places emit structured metadata for easier triage while preserving the
original message text.
apps/server/src/framework-detect.test.ts (1)

16-23: Consider cleaning up temp directories after tests.

The createTempDir helper creates directories in the system temp folder but doesn't clean them up. While the OS typically clears temp eventually, in CI environments this could accumulate. Consider using Vitest's afterEach or afterAll to clean up, or use a test utility that handles cleanup automatically.

♻️ Optional cleanup pattern
+const createdDirs: string[] = [];
+
 function createTempDir(): string {
   const dir = path.join(
     tmpdir(),
     `openkit-framework-test-${Date.now()}-${Math.random().toString(36).slice(2)}`,
   );
   mkdirSync(dir, { recursive: true });
+  createdDirs.push(dir);
   return dir;
 }
+
+afterAll(() => {
+  for (const dir of createdDirs) {
+    try {
+      rmSync(dir, { recursive: true, force: true });
+    } catch {
+      // Ignore cleanup errors
+    }
+  }
+});
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server/src/framework-detect.test.ts` around lines 16 - 23, createTempDir
creates temp directories but never removes them; update the tests to track and
clean up those directories after tests run by collecting returned paths from
createTempDir (or expose a helper array) and removing them in a Vitest
afterEach/afterAll hook using fs.rmdir/fs.rm or equivalent. Modify the test
suite that calls createTempDir (framework-detect.test.ts) to push each created
dir into a list and add an afterEach/afterAll that iterates the list and deletes
each directory, ensuring proper error handling if removal fails.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@docs/CONFIGURATION.md`:
- Around line 234-237: The docs text about the `framework` setting implies
detection happens only during port discovery; update the copy to state that the
project framework is auto-detected both during port discovery and when the
manager is constructed/started (so detection can occur at manager startup as
well as during port discovery). Edit the paragraph that begins "Detected project
framework, auto-set during port discovery..." to mention both "auto-detected
during port discovery or when the manager is constructed/started" and keep the
rest of the behavior details (react-native/expo, Metro port 8081,
RCT_METRO_PORT, adb reverse) unchanged.

In `@libs/shared/src/detect-config.ts`:
- Around line 74-80: The isReactNativeProject function currently swallows any
read/parse errors and returns false silently; update its catch block to log the
failure (include projectDir and the package.json path) and the caught error
using the project's logger (e.g., log.error) before returning false so the root
cause is visible; locate the function named isReactNativeProject and modify its
catch to construct the package.json path with path.join(projectDir,
"package.json") and call log.error with a clear message and the error object,
then retain the false fallback.

---

Outside diff comments:
In `@apps/server/src/manager.ts`:
- Around line 974-980: The inner empty catch that wraps
processInfo.kill("SIGTERM") should not silently swallow errors; change it to
catch the error (e.g., catch (err)) and log it using the module's logger (e.g.,
processLogger.error or processLogger.warn) including context such as the PID or
processInfo identifier and the error object so failures to send SIGTERM are
recorded; update the catch block around processInfo.kill("SIGTERM") accordingly
and ensure the logger symbol you use exists in this file.

In `@apps/server/src/runtime/port-hook.cjs`:
- Around line 62-85: The debug checks currently use if
(process.env.__WM_DEBUG__) and console.log which treats "0" as truthy and writes
to stdout; update each debug condition (the console lines inside the three
connect branches) to only enable when the flag is explicitly set (e.g.,
process.env.__WM_DEBUG__ === '1' || process.env.__WM_DEBUG__ === 'true') and
route messages to stderr (replace console.log with console.error or
process.stderr.write). Look for the three debug lines near the connect handling
logic (the blocks that use toPort, knownPortSet, and isLocalhost) and change
their conditions and logging calls accordingly so diagnostics go to stderr only
when the flag is explicitly enabled.

---

Nitpick comments:
In `@apps/server/src/framework-detect.test.ts`:
- Around line 16-23: createTempDir creates temp directories but never removes
them; update the tests to track and clean up those directories after tests run
by collecting returned paths from createTempDir (or expose a helper array) and
removing them in a Vitest afterEach/afterAll hook using fs.rmdir/fs.rm or
equivalent. Modify the test suite that calls createTempDir
(framework-detect.test.ts) to push each created dir into a list and add an
afterEach/afterAll that iterates the list and deletes each directory, ensuring
proper error handling if removal fails.

In `@apps/server/src/framework-detect.ts`:
- Around line 44-49: The debug log in the catch block around the read of
filename uses only a text message; update the log.debug call (the one passing
`domain: "framework-detect"`) to include structured metadata keys such as
projectDir, configPath or pkgPath (whichever is relevant in the surrounding
code), and a normalized error field (e.g. error: err?.stack ?? err?.message ??
String(err)) instead of embedding the error only in the message; do the same
change for the analogous log.debug at lines 75-78 so both places emit structured
metadata for easier triage while preserving the original message text.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 54709fda-609b-45f0-9cd9-9562b72e724e

📥 Commits

Reviewing files that changed from the base of the PR and between f89822f and 8421daa.

📒 Files selected for processing (14)
  • apps/server/src/framework-detect.test.ts
  • apps/server/src/framework-detect.ts
  • apps/server/src/manager.ts
  • apps/server/src/port-manager.test.ts
  • apps/server/src/port-manager.ts
  • apps/server/src/pty.ts
  • apps/server/src/routes/config.ts
  • apps/server/src/runtime/port-hook.cjs
  • apps/server/src/terminal-manager.ts
  • docs/CONFIGURATION.md
  • docs/PORT-MAPPING.md
  • libs/shared/src/detect-config.test.ts
  • libs/shared/src/detect-config.ts
  • libs/shared/src/worktree-types.ts

Comment thread docs/CONFIGURATION.md Resolved
Comment on lines +74 to +80
function isReactNativeProject(projectDir: string): boolean {
try {
const pkg = JSON.parse(readFileSync(path.join(projectDir, "package.json"), "utf-8"));
const deps = { ...pkg.dependencies, ...pkg.devDependencies };
return "react-native" in deps || "expo" in deps;
} catch {
return false;

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 | 🟠 Major

Silent fallback in RN/Expo detection hides root cause.

If package.json read/parse fails, this silently returns false and changes command selection to * dev without any diagnostics. Please log this failure with context (projectDir, package.json path, error) before falling back.

As per coding guidelines "Every catch block, every fallback branch, every error callback must do something meaningful: log through the appropriate logger (log.error() / log.warn()), surface to the user via toast, or both. Silent catch {} blocks are never acceptable."

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

In `@libs/shared/src/detect-config.ts` around lines 74 - 80, The
isReactNativeProject function currently swallows any read/parse errors and
returns false silently; update its catch block to log the failure (include
projectDir and the package.json path) and the caught error using the project's
logger (e.g., log.error) before returning false so the root cause is visible;
locate the function named isReactNativeProject and modify its catch to construct
the package.json path with path.join(projectDir, "package.json") and call
log.error with a clear message and the error object, then retain the false
fallback.

- clarify framework detection timing in docs
  (detection happens on startup too, not just during port discovery)
- log failed package.json reads in isReactNativeProject
  (silent catch was hiding root cause of start command fallback)
- route port-hook debug traces to stderr with strict __WM_DEBUG__==="1" check
  (was polluting stdout and treating "0" as truthy)
- spawn PTY directly with cmd+args instead of shell -lc wrapping
  (eliminates shell metacharacter interpretation in startCommand)
- use no-arg kill() for PTY processes to avoid cross-platform signal issues
- add structured metadata to framework-detect debug logs for easier triage
- replace magic number 8081 with exported DEFAULT_METRO_PORT constant
- trim() startCommand before startsWith check in port arg injection
- document CI=0 broad side-effect on other tools in process tree
- remove console.warn from libs/shared detect-config (no logger dependency)
- add bun.lock detection alongside bun.lockb for newer Bun versions
- add temp dir cleanup and regex behavior test in framework-detect tests
- log errors in stopWorktree catch blocks instead of silently swallowing

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

🧹 Nitpick comments (1)
apps/server/src/port-manager.ts (1)

337-339: Add logging or a comment to the empty catch block.

The scanDir catch block silently ignores errors. Per coding guidelines, every catch block should do something meaningful - either log or add a comment explaining why it's safe to ignore.

📝 Suggested fix
       } catch {
-        // Directory may not be readable
+        // Directory may not be readable; non-critical for env detection
       }

Or with logging:

       } catch (err) {
+        log.debug("Failed to scan directory for env files", {
+          domain: "port-discovery",
+          dir,
+          error: err instanceof Error ? err.message : String(err),
+        });
       }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/server/src/port-manager.ts` around lines 337 - 339, The empty catch in
scanDir silently swallows errors; update the catch block in the scanDir
implementation to either log the error (e.g., using the module's logger or
console.debug/console.warn) with context like "scanDir: failed to read
directory" and the error object, or add a concise comment explaining why the
error is safe to ignore (for example, permission denied or non-existent
directory expected); reference the catch after the scanDir try block and ensure
the log/comment makes the intended behavior explicit.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@apps/server/src/port-manager.ts`:
- Around line 337-339: The empty catch in scanDir silently swallows errors;
update the catch block in the scanDir implementation to either log the error
(e.g., using the module's logger or console.debug/console.warn) with context
like "scanDir: failed to read directory" and the error object, or add a concise
comment explaining why the error is safe to ignore (for example, permission
denied or non-existent directory expected); reference the catch after the
scanDir try block and ensure the log/comment makes the intended behavior
explicit.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: ca546fc3-e327-4753-b53e-c3bf9704e7bd

📥 Commits

Reviewing files that changed from the base of the PR and between 535cb14 and 8bd37ab.

📒 Files selected for processing (7)
  • apps/server/src/framework-detect.test.ts
  • apps/server/src/framework-detect.ts
  • apps/server/src/manager.ts
  • apps/server/src/port-manager.ts
  • apps/server/src/runtime/port-hook.cjs
  • libs/shared/src/detect-config.test.ts
  • libs/shared/src/detect-config.ts
🚧 Files skipped from review as they are similar to previous changes (3)
  • libs/shared/src/detect-config.ts
  • libs/shared/src/detect-config.test.ts
  • apps/server/src/framework-detect.test.ts

- differentiate ENOENT from unexpected errors in isReactNativeProject
  (silent fallback for missing files, console.warn for permission errors)
- scope CI=0 and EXPO_OFFLINE=0 to PTY spawn env only to avoid
  broad side-effect on other tools in the process tree
- add process tree cleanup via pgrep for PTY processes where
  process group kill fails (prevents orphaned Metro workers)
- fix regex false positive for viewport/reportPort in metro config
  port detection (added negative lookbehind for letters)
- document shell: true trust model, framework re-detection pattern,
  and bun support in getStartCommandPortArgs

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

🧹 Nitpick comments (1)
apps/server/src/framework-detect.test.ts (1)

28-36: Empty catch block in test cleanup.

While test cleanup failures are generally non-critical, the coding guidelines require meaningful handling for all catch blocks. Consider logging the cleanup error at debug level to aid troubleshooting if temp directories fail to clean up.

 afterAll(() => {
   for (const dir of createdDirs) {
     try {
       rmSync(dir, { recursive: true, force: true });
     } catch {
-      // Ignore cleanup errors in tests
+      // Cleanup errors in tests are non-critical but log for debugging
+      console.warn(`[test cleanup] Failed to remove temp dir: ${dir}`);
     }
   }
 });

As per coding guidelines: "Every catch block, every fallback branch, every error callback must do something meaningful... Silent catch {} blocks are never acceptable."

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

In `@apps/server/src/framework-detect.test.ts` around lines 28 - 36, The empty
catch in the test cleanup should log the error instead of swallowing it; in the
afterAll block that iterates createdDirs and calls rmSync, capture the caught
error and emit a debug-level log (e.g., using the test logger or console.debug)
including the dir path and error details so cleanup failures are visible; update
the catch in the afterAll cleanup loop (referencing createdDirs and rmSync) to
log a descriptive debug message with the caught error.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@apps/server/src/framework-detect.test.ts`:
- Around line 28-36: The empty catch in the test cleanup should log the error
instead of swallowing it; in the afterAll block that iterates createdDirs and
calls rmSync, capture the caught error and emit a debug-level log (e.g., using
the test logger or console.debug) including the dir path and error details so
cleanup failures are visible; update the catch in the afterAll cleanup loop
(referencing createdDirs and rmSync) to log a descriptive debug message with the
caught error.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 7bb24b99-c0c2-44e7-b34f-caa098921825

📥 Commits

Reviewing files that changed from the base of the PR and between 8bd37ab and 74e9b17.

📒 Files selected for processing (7)
  • apps/server/src/framework-detect.test.ts
  • apps/server/src/framework-detect.ts
  • apps/server/src/manager.ts
  • apps/server/src/port-manager.test.ts
  • apps/server/src/port-manager.ts
  • libs/shared/src/detect-config.test.ts
  • libs/shared/src/detect-config.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • libs/shared/src/detect-config.test.ts
  • apps/server/src/framework-detect.ts

@fum4
fum4 merged commit 2673034 into master Mar 17, 2026
19 checks passed
@fum4
fum4 deleted the feat/react-native-expo-worktree-support branch March 17, 2026 20:38

This branch was previously deployed

1 inactive deployment
Preview — 74e9b176 Deployed Mar 17, 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.

2 participants