Skip to content

[Bug] Bun NAPI crash on TUI exit: process.exit() in SIGINT handler conflicts with onnxruntime-node native cleanup #114

@keetyHuang

Description

@keetyHuang

Description

When using opencode-mem plugin with Bun runtime, exiting the TUI via Ctrl+C consistently crashes Bun with:

panic: NAPI FATAL ERROR: Error::New napi_create_error

Root Cause

The plugin registers a SIGINT/SIGTERM handler in dist/index.js that calls process.exit() after cleanup. When exiting opencode TUI:

  1. Plugin's SIGINT handler fires, calls memoryClient.close() then process.exit(0)
  2. onnxruntime-node (used via @xenova/transformers for local embeddings) has an InferenceSession loaded in a worker thread
  3. process.exit() triggers process termination — Bun starts tearing down the NAPI environment
  4. The ONNX Runtime GC finalizer (InferenceSessionWrap::FinalizeCallback) tries to destroy the session
  5. During destruction, Napi::Error::New(napi_env__*) is called, but the napi_env is already partially destroyed
  6. Bun panics with NAPI FATAL ERROR: Error::New napi_create_error

Crash Stack (from macOS crash report)

InferenceSessionWrap::FinalizeCallback()
  → InferenceSessionWrap::~InferenceSessionWrap()
    → Napi::ObjectWrap<InferenceSessionWrap>::~ObjectWrap()
      → Napi::Error::New(napi_env__*)
        → Napi::Error::Fatal() → Bun panic

Environment

  • Bun: 1.3.14
  • opencode-mem: 2.14.3
  • opencode: 1.15.10
  • macOS 15.5 (Apple Silicon arm64)
  • onnxruntime-node: 1.14.0

Suggested Fix

Remove process.exit() from the shutdownHandler — let the host process manage lifecycle:

const shutdownHandler = async () => {
    try {
        if (webServer) await webServer.stop();
        memoryClient.close();
        // DO NOT call process.exit()
    } catch (error) {
        log("Shutdown error", { error: String(error) });
    }
};

Related

See also #97, #88 for other NAPI/native addon issues on arm64.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions