Repository navigation
feat: React Native / Expo worktree support - #81
Conversation
…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]>
|
The latest updates on your projects. Learn more about Vercel for GitHub. |
📝 WalkthroughWalkthroughAdds 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
Sequence DiagramsequenceDiagram
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
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches
🧪 Generate unit tests (beta)
📝 Coding Plan
Comment |
|
There was a problem hiding this comment.
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 | 🟡 MinorRoute debug traces to
stderrand parse__WM_DEBUG__explicitly.Using
if (process.env.__WM_DEBUG__)enables logs for"0", andconsole.logemits to stdout, which can pollute proxied app output. Prefer a strict flag andstderrfor 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 | 🟡 MinorEmpty 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 normalizederrorin 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
createTempDirhelper 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'safterEachorafterAllto 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
📒 Files selected for processing (14)
apps/server/src/framework-detect.test.tsapps/server/src/framework-detect.tsapps/server/src/manager.tsapps/server/src/port-manager.test.tsapps/server/src/port-manager.tsapps/server/src/pty.tsapps/server/src/routes/config.tsapps/server/src/runtime/port-hook.cjsapps/server/src/terminal-manager.tsdocs/CONFIGURATION.mddocs/PORT-MAPPING.mdlibs/shared/src/detect-config.test.tslibs/shared/src/detect-config.tslibs/shared/src/worktree-types.ts
| 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; |
There was a problem hiding this comment.
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
There was a problem hiding this comment.
🧹 Nitpick comments (1)
apps/server/src/port-manager.ts (1)
337-339: Add logging or a comment to the empty catch block.The
scanDircatch 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
📒 Files selected for processing (7)
apps/server/src/framework-detect.test.tsapps/server/src/framework-detect.tsapps/server/src/manager.tsapps/server/src/port-manager.tsapps/server/src/runtime/port-hook.cjslibs/shared/src/detect-config.test.tslibs/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
There was a problem hiding this comment.
🧹 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
catchblock, every fallback branch, every error callback must do something meaningful... Silentcatch {}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
📒 Files selected for processing (7)
apps/server/src/framework-detect.test.tsapps/server/src/framework-detect.tsapps/server/src/manager.tsapps/server/src/port-manager.test.tsapps/server/src/port-manager.tslibs/shared/src/detect-config.test.tslibs/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
Summary
package.jsondependencies (on PortManager construction and during port discovery)node-pty— gives Metro a real TTY so QR codes,press a/press icommands, and interactive output work--port <offset>flag directly to the start command so multiple worktrees use different portsCI=0,EXPO_OFFLINE=0to prevent "Networking has been disabled" warningsRCT_METRO_PORTenv var for native app connectivity, with fallback to default port 8081adb reverseon worktree start for Android device connectivity (best-effort)npm start/yarn startinstead ofnpm run devpty.ts— sharedresolveNodePtyModule()used by bothmanager.tsandterminal-manager.tsRunningProcesstype — changed fromprocess: ChildProcesstokill: (signal?) => voidto support both ChildProcess and IPty__WM_DEBUG__env var to reduce noiseTest plan
🤖 Generated with Claude Code
Summary by CodeRabbit
New Features
Documentation
Tests