Skip to content

Conversation

@zhangmo8
Copy link
Collaborator

@zhangmo8 zhangmo8 commented Dec 15, 2025

close #1181

Summary by CodeRabbit

  • Bug Fixes
    • Added comprehensive error handling to catch and log unhandled exceptions and promise rejections, with user notifications for network-related errors.

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

@chatgpt-codex-connector
Copy link

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.
Credits must be used to enable repository wide code reviews.

@coderabbitai
Copy link
Contributor

coderabbitai bot commented Dec 15, 2025

Walkthrough

Adds global error handling in the main Electron process to catch uncaught exceptions and unhandled promise rejections. When network-related errors are detected, a non-blocking notification is sent to renderer windows via the event bus; all errors are logged.

Changes

Cohort / File(s) Summary
Main process error handling
src/main/index.ts
Added uncaughtException handler that logs errors and sends SHOW_ERROR notifications for network errors to renderer windows. Added unhandledRejection handler for logging unhandled promise rejections. New imports for electron-log, event bus, and notification event constants.

Estimated code review effort

🎯 2 (Simple) | ⏱️ ~10 minutes

  • Single file with straightforward error handler implementations
  • Clear error logging and notification flow
  • Consider reviewing the network error detection logic to ensure net::ERR_ patterns are correctly identified

Poem

🐰 A hop, skip, and error we catch,
No crash dialogs spoil the match!
Network hiccups now gracefully fall,
Logged and notified—handled for all! 🌐✨

Pre-merge checks and finishing touches

✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title 'feat: show network error' directly describes the main change: displaying network errors to users instead of showing uncaught exception dialogs.
Linked Issues check ✅ Passed The PR implements global error handlers for uncaughtException and unhandledRejection, logging errors and sending network error notifications to renderer windows, which addresses the core requirement to catch network errors in the main process and show user-friendly messages.
Out of Scope Changes check ✅ Passed All changes in src/main/index.ts are directly scoped to implementing global error handling for network errors as specified in issue #1181.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
✨ Finishing touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment

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

@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

🧹 Nitpick comments (3)
src/main/index.ts (3)

14-21: Consider checking error.code property for more reliable detection.

The current string-based detection is pragmatic but could miss errors or misclassify them. Node.js system errors expose a .code property (e.g., error.code === 'ECONNRESET') which is more reliable than substring matching.

Apply this diff to check error codes first:

   const msg = error.message || 'Unknown error'
+  const code = (error as any).code || ''
   const isNetworkError = [
     'net::ERR',
     'ECONNRESET',
     'ETIMEDOUT',
     'ENOTFOUND',
     'Network Error',
     'fetch failed'
-  ].some((k) => msg.includes(k))
+  ].some((k) => code === k || msg.includes(k))

Based on coding guidelines, distinguishing error types with appropriate handlers improves reliability.


28-29: Provide user-friendly error messages for end users.

The raw error message (e.g., "net::ERR_CONNECTION_CLOSED") is passed directly to users via the notification. Consider translating technical error codes into user-friendly messages like "Connection lost. Please check your network connection and try again."

Example improvement:

const userMessage = isNetworkError 
  ? 'Network connection failed. Please check your internet connection and try again.'
  : msg

// Then use userMessage in the notification payload
message: userMessage,

Based on coding guidelines, user-facing errors should have user-friendly messages.


35-37: Consider detecting network errors in promise rejections too.

The unhandledRejection handler only logs the error but doesn't check if it's a network-related rejection. For consistency with the uncaughtException handler, consider detecting network promise rejections and showing the same user-friendly notification.

Example:

process.on('unhandledRejection', (reason) => {
  log.error('Unhandled Rejection:', reason)
  
  // Apply same network detection logic as uncaughtException
  if (reason instanceof Error) {
    const msg = reason.message || 'Unknown error'
    const code = (reason as any).code || ''
    const isNetworkError = [
      'net::ERR',
      'ECONNRESET',
      'ETIMEDOUT',
      'ENOTFOUND',
      'Network Error',
      'fetch failed'
    ].some((k) => code === k || msg.includes(k))
    
    if (isNetworkError) {
      eventBus.sendToRenderer(NOTIFICATION_EVENTS.SHOW_ERROR, SendTarget.ALL_WINDOWS, {
        id: Date.now().toString(),
        title: 'Network Error',
        message: msg,
        type: 'error'
      })
    }
  }
})
📜 Review details

Configuration used: CodeRabbit UI

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between df6bad6 and c7148e7.

📒 Files selected for processing (1)
  • src/main/index.ts (1 hunks)
🧰 Additional context used
📓 Path-based instructions (11)
**/*.{ts,tsx,js,jsx,vue}

📄 CodeRabbit inference engine (CLAUDE.md)

Use English for logs and comments (Chinese text exists in legacy code, but new code should use English)

Files:

  • src/main/index.ts
**/*.{ts,tsx}

📄 CodeRabbit inference engine (CLAUDE.md)

Enable and maintain strict TypeScript type checking for all files

**/*.{ts,tsx}: Always use try-catch to handle possible errors in TypeScript code
Provide meaningful error messages when catching errors
Log detailed error logs including error details, context, and stack traces
Distinguish and handle different error types (UserError, NetworkError, SystemError, BusinessError) with appropriate handlers in TypeScript
Use structured logging with logger.error(), logger.warn(), logger.info(), logger.debug() methods from logging utilities
Do not suppress errors (avoid empty catch blocks or silently ignoring errors)
Provide user-friendly error messages for user-facing errors in TypeScript components
Implement error retry mechanisms for transient failures in TypeScript
Avoid logging sensitive information (passwords, tokens, PII) in logs

Files:

  • src/main/index.ts
src/main/**/*.ts

📄 CodeRabbit inference engine (CLAUDE.md)

Use EventBus from src/main/eventbus.ts for main-to-renderer communication, broadcasting events via mainWindow.webContents.send()

src/main/**/*.ts: Use EventBus pattern for inter-process communication within the main process to decouple modules
Use Electron's built-in APIs for file system and native dialogs instead of Node.js or custom implementations

src/main/**/*.ts: Electron main process code belongs in src/main/ with presenters in presenter/ (Window/Tab/Thread/Mcp/Config/LLMProvider) and eventbus.ts for app events
Use the Presenter pattern in the main process for UI coordination

Files:

  • src/main/index.ts
**/*.ts

📄 CodeRabbit inference engine (CLAUDE.md)

Do not include AI co-authoring information (e.g., 'Co-Authored-By: Claude') in git commits

Files:

  • src/main/index.ts
**/*.{js,ts,jsx,tsx,mjs,cjs}

📄 CodeRabbit inference engine (.cursor/rules/development-setup.mdc)

Write logs and comments in English

Files:

  • src/main/index.ts
src/**/*

📄 CodeRabbit inference engine (.cursor/rules/project-structure.mdc)

New features should be developed in the src directory

Files:

  • src/main/index.ts
src/main/**/*.{js,ts}

📄 CodeRabbit inference engine (.cursor/rules/project-structure.mdc)

Main process code for Electron should be placed in src/main

Files:

  • src/main/index.ts
src/**/*.{ts,tsx,vue,js,jsx}

📄 CodeRabbit inference engine (AGENTS.md)

Use Prettier with single quotes, no semicolons, and 100 character width

Files:

  • src/main/index.ts
src/**/*.{ts,tsx,js,jsx}

📄 CodeRabbit inference engine (AGENTS.md)

Use OxLint for linting JavaScript and TypeScript files

Files:

  • src/main/index.ts
src/**/*.{ts,tsx}

📄 CodeRabbit inference engine (AGENTS.md)

src/**/*.{ts,tsx}: Use camelCase for variable and function names in TypeScript files
Use PascalCase for type and class names in TypeScript
Use SCREAMING_SNAKE_CASE for constant names

Files:

  • src/main/index.ts
src/**/*.ts

📄 CodeRabbit inference engine (AGENTS.md)

Use EventBus for inter-process communication events

Files:

  • src/main/index.ts
🧠 Learnings (15)
📓 Common learnings
Learnt from: CR
Repo: ThinkInAIXYZ/deepchat PR: 0
File: .cursor/rules/error-logging.mdc:0-0
Timestamp: 2025-11-25T05:26:35.317Z
Learning: Applies to **/*.{ts,tsx} : Distinguish and handle different error types (UserError, NetworkError, SystemError, BusinessError) with appropriate handlers in TypeScript
Learnt from: CR
Repo: ThinkInAIXYZ/deepchat PR: 0
File: .cursor/rules/electron-best-practices.mdc:0-0
Timestamp: 2025-11-25T05:26:24.867Z
Learning: Implement proper error handling and logging for debugging in Electron applications
Learnt from: CR
Repo: ThinkInAIXYZ/deepchat PR: 0
File: .cursor/rules/provider-guidelines.mdc:0-0
Timestamp: 2025-11-25T05:27:39.200Z
Learning: Applies to **/*Provider**/index.ts : Error handling: use `error` event uniformly to carry error messages, avoid mixing errors into other event fields
Learnt from: CR
Repo: ThinkInAIXYZ/deepchat PR: 0
File: .cursor/rules/error-logging.mdc:0-0
Timestamp: 2025-11-25T05:26:35.317Z
Learning: Applies to **/*.{ts,tsx}x : Use error boundaries to catch rendering errors in React components
Learnt from: CR
Repo: ThinkInAIXYZ/deepchat PR: 0
File: .cursor/rules/error-logging.mdc:0-0
Timestamp: 2025-11-25T05:26:35.317Z
Learning: Implement graceful degradation when handling errors
Learnt from: CR
Repo: ThinkInAIXYZ/deepchat PR: 0
File: .cursor/rules/electron-best-practices.mdc:0-0
Timestamp: 2025-11-25T05:26:24.867Z
Learning: Applies to {src/main/presenter/**/*.ts,src/renderer/**/*.ts} : Implement proper inter-process communication (IPC) patterns using Electron's ipcRenderer and ipcMain APIs
📚 Learning: 2025-11-25T05:26:24.867Z
Learnt from: CR
Repo: ThinkInAIXYZ/deepchat PR: 0
File: .cursor/rules/electron-best-practices.mdc:0-0
Timestamp: 2025-11-25T05:26:24.867Z
Learning: Implement proper error handling and logging for debugging in Electron applications

Applied to files:

  • src/main/index.ts
📚 Learning: 2025-11-25T05:26:35.317Z
Learnt from: CR
Repo: ThinkInAIXYZ/deepchat PR: 0
File: .cursor/rules/error-logging.mdc:0-0
Timestamp: 2025-11-25T05:26:35.317Z
Learning: Applies to **/*.{ts,tsx} : Distinguish and handle different error types (UserError, NetworkError, SystemError, BusinessError) with appropriate handlers in TypeScript

Applied to files:

  • src/main/index.ts
📚 Learning: 2025-11-25T05:26:24.867Z
Learnt from: CR
Repo: ThinkInAIXYZ/deepchat PR: 0
File: .cursor/rules/electron-best-practices.mdc:0-0
Timestamp: 2025-11-25T05:26:24.867Z
Learning: Applies to {src/main/presenter/**/*.ts,src/renderer/**/*.ts} : Implement proper inter-process communication (IPC) patterns using Electron's ipcRenderer and ipcMain APIs

Applied to files:

  • src/main/index.ts
📚 Learning: 2025-11-25T05:28:20.513Z
Learnt from: CR
Repo: ThinkInAIXYZ/deepchat PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-11-25T05:28:20.513Z
Learning: Applies to src/main/**/*.ts : Electron main process code belongs in `src/main/` with presenters in `presenter/` (Window/Tab/Thread/Mcp/Config/LLMProvider) and `eventbus.ts` for app events

Applied to files:

  • src/main/index.ts
📚 Learning: 2025-11-25T05:27:39.200Z
Learnt from: CR
Repo: ThinkInAIXYZ/deepchat PR: 0
File: .cursor/rules/provider-guidelines.mdc:0-0
Timestamp: 2025-11-25T05:27:39.200Z
Learning: Applies to **/*Provider**/index.ts : Error handling: use `error` event uniformly to carry error messages, avoid mixing errors into other event fields

Applied to files:

  • src/main/index.ts
📚 Learning: 2025-11-25T05:26:11.312Z
Learnt from: CR
Repo: ThinkInAIXYZ/deepchat PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-11-25T05:26:11.312Z
Learning: Applies to src/main/**/*.ts : Use EventBus from `src/main/eventbus.ts` for main-to-renderer communication, broadcasting events via `mainWindow.webContents.send()`

Applied to files:

  • src/main/index.ts
📚 Learning: 2025-11-25T05:26:24.867Z
Learnt from: CR
Repo: ThinkInAIXYZ/deepchat PR: 0
File: .cursor/rules/electron-best-practices.mdc:0-0
Timestamp: 2025-11-25T05:26:24.867Z
Learning: Applies to src/main/**/*.ts : Use EventBus pattern for inter-process communication within the main process to decouple modules

Applied to files:

  • src/main/index.ts
📚 Learning: 2025-11-25T05:26:24.867Z
Learnt from: CR
Repo: ThinkInAIXYZ/deepchat PR: 0
File: .cursor/rules/electron-best-practices.mdc:0-0
Timestamp: 2025-11-25T05:26:24.867Z
Learning: Applies to src/main/**/*.ts : Use Electron's built-in APIs for file system and native dialogs instead of Node.js or custom implementations

Applied to files:

  • src/main/index.ts
📚 Learning: 2025-11-25T05:27:26.656Z
Learnt from: CR
Repo: ThinkInAIXYZ/deepchat PR: 0
File: .cursor/rules/project-structure.mdc:0-0
Timestamp: 2025-11-25T05:27:26.656Z
Learning: Applies to src/main/**/*.{js,ts} : Main process code for Electron should be placed in `src/main`

Applied to files:

  • src/main/index.ts
📚 Learning: 2025-11-25T05:28:20.513Z
Learnt from: CR
Repo: ThinkInAIXYZ/deepchat PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-11-25T05:28:20.513Z
Learning: Applies to src/**/*.ts : Use EventBus for inter-process communication events

Applied to files:

  • src/main/index.ts
📚 Learning: 2025-11-25T05:28:20.513Z
Learnt from: CR
Repo: ThinkInAIXYZ/deepchat PR: 0
File: AGENTS.md:0-0
Timestamp: 2025-11-25T05:28:20.513Z
Learning: Applies to src/main/**/*.ts : Use the Presenter pattern in the main process for UI coordination

Applied to files:

  • src/main/index.ts
📚 Learning: 2025-11-25T05:27:12.209Z
Learnt from: CR
Repo: ThinkInAIXYZ/deepchat PR: 0
File: .cursor/rules/llm-agent-loop.mdc:0-0
Timestamp: 2025-11-25T05:27:12.209Z
Learning: Applies to src/main/presenter/llmProviderPresenter/index.ts : In `src/main/presenter/llmProviderPresenter/index.ts`, listen for standardized events yielded by `coreStream` and handle them accordingly: buffer text content (`currentContent`), handle `tool_call_start/chunk/end` events by collecting tool details and calling `presenter.mcpPresenter.callTool`, send frontend events via `eventBus` with tool call status, format tool results for the next LLM call, and set `needContinueConversation = true`

Applied to files:

  • src/main/index.ts
📚 Learning: 2025-11-25T05:26:11.312Z
Learnt from: CR
Repo: ThinkInAIXYZ/deepchat PR: 0
File: CLAUDE.md:0-0
Timestamp: 2025-11-25T05:26:11.312Z
Learning: Applies to src/renderer/**/*.ts : Use the `usePresenter.ts` composable for renderer-to-main IPC communication to call presenter methods directly

Applied to files:

  • src/main/index.ts
📚 Learning: 2025-11-25T05:27:12.209Z
Learnt from: CR
Repo: ThinkInAIXYZ/deepchat PR: 0
File: .cursor/rules/llm-agent-loop.mdc:0-0
Timestamp: 2025-11-25T05:27:12.209Z
Learning: Implement separation of concerns where `src/main/presenter/llmProviderPresenter/index.ts` manages the Agent loop and conversation history, while Provider files handle LLM API interactions, Provider-specific request/response formatting, tool definition conversion, and native vs non-native tool call mechanisms

Applied to files:

  • src/main/index.ts
🧬 Code graph analysis (1)
src/main/index.ts (3)
src/main/eventbus.ts (1)
  • eventBus (151-151)
src/main/events.ts (1)
  • NOTIFICATION_EVENTS (155-159)
src/renderer/src/events.ts (1)
  • NOTIFICATION_EVENTS (118-122)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: build-check (x64)
🔇 Additional comments (1)
src/main/index.ts (1)

5-7: LGTM!

The imports are appropriate for implementing global error handling with structured logging and event bus communication to renderer processes.

Comment on lines +10 to +33
process.on('uncaughtException', (error) => {
log.error('Uncaught Exception:', error)

const msg = error.message || 'Unknown error'
const isNetworkError = [
'net::ERR',
'ECONNRESET',
'ETIMEDOUT',
'ENOTFOUND',
'Network Error',
'fetch failed'
].some((k) => msg.includes(k))

if (isNetworkError) {
// Send error to renderer to show a toast notification
// This is "elegant" and non-blocking
eventBus.sendToRenderer(NOTIFICATION_EVENTS.SHOW_ERROR, SendTarget.ALL_WINDOWS, {
id: Date.now().toString(),
title: 'Network Error',
message: msg,
type: 'error'
})
}
})
Copy link
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Verify eventBus initialization and sendToRenderer implementation
echo "=== Checking eventBus.sendToRenderer implementation ==="
rg -n -A 10 "sendToRenderer" --type ts src/main/eventbus.ts

echo -e "\n=== Checking if eventBus has null/initialization checks ==="
rg -n -B 3 -A 3 "eventBus\?" --type ts src/main/

echo -e "\n=== Checking for window availability checks before IPC ==="
rg -n -B 2 -A 5 "getAllWindows|BrowserWindow.getAllWindows" --type ts src/main/

echo -e "\n=== Checking index.ts initialization order ==="
head -50 src/main/index.ts

Repository: ThinkInAIXYZ/deepchat

Length of output: 13181


🏁 Script executed:

#!/bin/bash
# Check if there are try-catch wrappers around eventBus calls elsewhere
echo "=== Checking for try-catch patterns around eventBus.sendToRenderer ==="
rg -n -B 5 -A 5 "try.*eventBus|eventBus.*catch" --type ts src/main/

echo -e "\n=== Check for window state checks before sending ==="
rg -n "mainWindow|renderer.*window" --type ts src/main/presenter/ | head -20

Repository: ThinkInAIXYZ/deepchat

Length of output: 2269


Improve error message handling and clarify process exit behavior.

The sendToRenderer() call is safe due to internal guards in eventBus (returns early if windowPresenter unavailable), but several improvements are needed:

  1. User-friendly error messages: Raw error.message is passed directly to the notification (e.g., "net::ERR_CONNECTION_CLOSED"). Transform this to user-friendly text for non-technical users per error handling guidelines.

  2. Misleading comment: The comment states "prevent app crash or error dialogs", but the process will exit after this handler completes (Node.js default behavior for uncaughtException). The handler prevents system error dialogs, not the process exit. Either clarify the comment or explicitly prevent exit if that's the intent (e.g., process.exitCode = 0 or process.removeAllListeners() if intentional continuation is needed).

  3. Consider error.code for network error detection: The current string-matching approach in error.message is fragile. For Node.js system errors, checking error.code property (ECONNRESET, ETIMEDOUT, ENOTFOUND) alongside message matching would be more reliable.

@zerob13
Copy link
Collaborator

zerob13 commented Dec 15, 2025

@codex review

@chatgpt-codex-connector
Copy link

Codex Review: Didn't find any major issues. 🚀

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

@zerob13 zerob13 merged commit fc1405a into ThinkInAIXYZ:dev Dec 15, 2025
2 checks passed
@zhangmo8 zhangmo8 deleted the error-tips branch December 19, 2025 04:57
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.

[BUG]Unhandled network errors during connectivity checks cause main process crashes

2 participants