Skip to content

Conversation

@sikbrad
Copy link

@sikbrad sikbrad commented Jan 19, 2026

Summary

  • Fix server process not being fully terminated on macOS/Linux when restarting the Electron app
  • Use pkill -P to kill all child processes of the server
  • Use SIGKILL instead of SIGTERM for reliable process termination

Problem

When restarting the built Electron app (build:electron:mac:dir), the previous server process and its children were not properly terminated. This caused port 3008/3007 to remain occupied, preventing the app from restarting correctly.

Solution

  • Kill entire process tree using pkill -P <pid> before killing the parent process
  • Use SIGKILL for guaranteed termination (SIGTERM can be ignored by processes)
  • Applied to both window-all-closed and before-quit event handlers

Test plan

  • Build the Electron app with npm run build:electron:mac:dir
  • Launch the app and verify server starts on port 3008
  • Quit and relaunch the app
  • Verify the app restarts without port conflict errors

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Bug Fixes
    • Centralized and consolidated server cleanup on app quit and window-close events to ensure the server is reliably stopped and resources are released.
    • Improved consistency of shutdown behavior and logging across platforms; macOS quit behavior preserved.

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

Previously, the Electron app only sent SIGTERM to the server process on
Unix systems, which could leave child processes running and cause port
conflicts when restarting the app. This change uses pkill to terminate
all child processes and SIGKILL for reliable termination.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
@gemini-code-assist
Copy link
Contributor

Summary of Changes

Hello @sikbrad, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request resolves a critical issue in the Electron application where the server process and its child processes were not reliably terminated on macOS/Linux, leading to port conflicts and preventing successful app restarts. The changes introduce a more aggressive and comprehensive process termination strategy, ensuring that all related processes are properly shut down, thereby improving the application's stability and restart reliability.

Highlights

  • Server Process Termination: Implemented a robust mechanism to ensure the server process and its child processes are fully terminated on macOS/Linux when the Electron app closes or restarts.
  • Process Tree Killing: Utilized pkill -P <pid> to effectively terminate the entire process tree associated with the server, preventing orphaned processes.
  • Reliable Termination Signal: Switched from SIGTERM to SIGKILL for the main server process to guarantee termination, as SIGTERM can be ignored by processes.
  • Event Handler Integration: Applied the enhanced termination logic to both the window-all-closed and before-quit Electron event handlers for comprehensive coverage.

🧠 New Feature in Public Preview: You can now enable Memory to help Gemini Code Assist learn from your team's feedback. This makes future code reviews more consistent and personalized to your project's style. Click here to enable Memory in your admin console.

Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for Github and other Google products, sign up here.

You can also get AI-powered code generation, chat, as well as code reviews directly in the IDE at no cost with the Gemini Code Assist IDE Extension.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution.

@coderabbitai
Copy link

coderabbitai bot commented Jan 19, 2026

Note

Other AI code review bot(s) detected

CodeRabbit has detected other AI code review bot(s) in this pull request and will avoid duplicating their findings in the review comments. This may lead to a less comprehensive review.

📝 Walkthrough

Walkthrough

Centralized and consolidated server shutdown logic in the Electron main process by adding cleanupServerProcess(reason) that terminates serverProcess (Windows: taskkill /t, non-Windows: pkill -P <pid> then SIGKILL), closes staticServer, and is invoked from both window-all-closed and before-quit handlers; retains platform-specific handling and logging.

Changes

Cohort / File(s) Summary
Server shutdown consolidation
apps/ui/src/main.ts
Added cleanupServerProcess(reason) to centralize termination: Windows uses taskkill /t, non-Windows runs pkill -P <pid> then kill -9 on the server PID; ensures staticServer.close() and sets serverProcess = null. Replaced per-handler termination code in app.on('window-all-closed') and app.on('before-quit') with calls to the new cleanup routine; app.quit() still called on non-macOS in window-all-closed.

Sequence Diagram(s)

sequenceDiagram
    autonumber
    participant App as "Electron App"
    participant Cleanup as "cleanupServerProcess"
    participant Server as "serverProcess"
    participant OS as "OS (taskkill/pkill)"
    participant Static as "staticServer"

    App->>Cleanup: on 'before-quit' / 'window-all-closed' (reason)
    Cleanup->>Server: if Windows -> taskkill /t <pid>
    Cleanup->>OS: run: taskkill /t /pid <pid> (Windows) (rgba(0,128,0,0.5))
    Cleanup->>Server: if non-Windows -> pkill -P <pid>
    Cleanup->>OS: run: pkill -P <pid> (ignore errors) (rgba(0,0,255,0.5))
    Cleanup->>OS: run: kill -9 <pid> (force) (rgba(255,0,0,0.5))
    Cleanup->>Static: if staticServer -> close()
    Cleanup->>App: set serverProcess = null
    App->>App: if not macOS and from 'window-all-closed' -> quit()
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Poem

🐰 I hopped through code with tidy paws,

I chased the children, fixed the flaws,
A taskkill here, a pkill there,
All servers hushed with gentle care,
— Hoppy Rabbit 🥕

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main fix: ensuring server process tree termination on macOS/Linux, which aligns with the core objective of preventing port occupation issues through proper process cleanup.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.

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

Copy link
Contributor

@gemini-code-assist gemini-code-assist bot left a comment

Choose a reason for hiding this comment

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

Code Review

This pull request effectively resolves an issue with orphaned server processes on macOS and Linux by implementing a more robust termination strategy using pkill -P and SIGKILL. The changes are applied to both relevant application lifecycle events. My main feedback is to address the significant code duplication between the window-all-closed and before-quit event handlers by extracting the process termination logic into a shared helper function. This will improve the code's maintainability and prevent future inconsistencies.

Comment on lines 777 to 788
// Unix/Linux: kill entire process tree
try {
execSync(`pkill -P ${serverProcess.pid}`, { stdio: 'ignore' });
} catch {
// pkill returns non-zero if no processes found, ignore
}
try {
process.kill(serverProcess.pid, 'SIGKILL');
} catch {
// Process may already be dead
}
}
Copy link
Contributor

Choose a reason for hiding this comment

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

high

This logic for terminating the server process tree is nearly identical to the logic in the before-quit event handler on lines 815-828. Duplicating this code makes it harder to maintain and increases the risk of introducing inconsistencies in the future.

To improve this, I recommend extracting the entire server termination logic (for both Windows and Unix-like systems) into a single helper function. This function can then be called from both window-all-closed and before-quit handlers.

Here's an example of how you could structure it:

function cleanupServerProcess(reason: 'window-closed' | 'quitting'): void {
  if (!serverProcess || !serverProcess.pid) {
    return;
  }

  const logMessage = reason === 'window-closed' 
    ? 'All windows closed, stopping server...' 
    : 'Stopping server...';
  logger.info(logMessage);

  if (process.platform === 'win32') {
    try {
      execSync(`taskkill /f /t /pid ${serverProcess.pid}`, { stdio: 'ignore' });
    } catch (error) {
      logger.error('Failed to kill server process:', (error as Error).message);
    }
  } else {
    // Unix/macOS: kill entire process tree
    try {
      execSync(`pkill -P ${serverProcess.pid}`, { stdio: 'ignore' });
    } catch {
      // pkill returns non-zero if no processes found, ignore
    }
    try {
      process.kill(serverProcess.pid, 'SIGKILL');
    } catch {
      // Process may already be dead
    }
  }
  serverProcess = null;
}

// Then call it from the handlers:
app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    cleanupServerProcess('window-closed');
    // ... rest of the handler
  }
});

app.on('before-quit', () => {
  cleanupServerProcess('quitting');
  // ... rest of the handler
});

Copy link

@coderabbitai coderabbitai bot left a comment

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/ui/src/main.ts`:
- Around line 815-828: The comment incorrectly states "SIGTERM first, then
SIGKILL" while the code only sends SIGKILL to the server process; update the
comment near the shutdown block that references serverProcess, execSync and
process.kill to accurately describe behavior (e.g., "Use pkill to terminate
child processes, then send SIGKILL to the server process; SIGTERM is not issued
here") or implement the intended SIGTERM-then-SIGKILL sequence by sending
SIGTERM to serverProcess, waiting briefly for exit, and only then sending
SIGKILL if still alive; adjust comments to match whichever approach you choose
so execSync(`pkill -P ${serverProcess.pid}`), process.kill(serverProcess.pid,
'SIGTERM')/SIGKILL and related try/catch blocks are consistent.

Address PR review feedback:
- Extract duplicate process termination logic into cleanupServerProcess()
- Fix misleading comment about SIGTERM (code only uses SIGKILL)
- Consolidate static server cleanup into the same helper

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
Copy link

@coderabbitai coderabbitai bot left a comment

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/ui/src/main.ts (1)

764-802: Add SIGKILL flag to pkill to guarantee child process termination.

pkill -P defaults to SIGTERM, which child processes can ignore. This contradicts the stated goal of preventing orphaned processes and port conflicts on restart. Align with the Windows strategy by using pkill -KILL to guarantee termination of child processes that may not respond to SIGTERM.

🔧 Proposed hard-kill for child processes
-      // Unix/macOS: kill child processes with pkill, then SIGKILL the server
+      // Unix/macOS: SIGKILL child processes with pkill, then SIGKILL the server
       try {
-        execSync(`pkill -P ${serverProcess.pid}`, { stdio: 'ignore' });
+        execSync(`pkill -KILL -P ${serverProcess.pid}`, { stdio: 'ignore' });
       } catch {
         // pkill returns non-zero if no processes found, ignore
       }

@sikbrad
Copy link
Author

sikbrad commented Jan 19, 2026

/gemini review
@coderabbitai review

@coderabbitai
Copy link

coderabbitai bot commented Jan 19, 2026

@sikbrad: I'll review the changes in this PR right away.

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

@sikbrad
Copy link
Author

sikbrad commented Jan 19, 2026

/gemini review
@coderabbitai review

@gemini-code-assist
Copy link
Contributor

Hello @sikbrad, I've received your request for a code review and will begin processing it shortly. Please note that the review will be posted as a separate comment once completed.

@coderabbitai
Copy link

coderabbitai bot commented Jan 19, 2026

@sikbrad: I'll review the changes in this PR right away.

✅ Actions performed

Review triggered.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

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