[Bug]: Node plugin API retains closed WebSocket after reconnect (HideApp hangs)
Platform
Windows (Windows 11)
Desktop Environment
N/A (not a Linux user)
Display Server
N/A (not a Linux user)
Wox Version
2.4.4. The same connection lifecycle is present in the inspected 2.4.5 source; the automated reproduction below targets 2.4.4.
Description
A custom Node.js capture plugin successfully writes a daily-note entry, but Wox intermittently stays open after Enter. The plugin sets PreventHideAfterAction: true and calls await API.HideApp(ctx) after the write succeeds. Restarting Wox restores normal behavior.
Source investigation found a stale WebSocket reference in the Node host after reconnect. Incoming queries can work through the replacement connection while the plugin's PluginAPI still sends through the closed connection. A source-level harness reproduces this behavior and verifies a small proposed correction below.
Expected: an already-loaded plugin should use the live connection for API calls after the host reconnects, allowing HideApp to complete and close the launcher after a successful capture.
Actual: capture succeeds and HideApp is invoked, but the window remains open. The reconstructed stale-socket case leaves the API promise unsettled.
Relevant log excerpts
On 23 September 2026, node.log contains the following events (trace, host, and request IDs omitted):
21:42:34.277 [info] [node-<id>] connection closed, code: 1006, reason:
22:18:47.920 [info] invoke <TaskNotes Capture> method: action
22:18:47.929 [info] <TaskNotes Capture> start invoke method to Wox: HideApp, id: <id>The corresponding query returned a result normally, and the entry was confirmed in the daily note. The supplied main Wox log excerpt has no corresponding inbound HideApp request; the Node excerpt ends immediately after that invocation.
These observations are consistent with the source defect, but the excerpts do not prove what caused the original disconnect. This has not been reproduced reliably by a particular sequence of UI actions. Private vault contents and unrelated log entries are omitted.
Source analysis
jsonrpc.ts,initPluginconstructsnew PluginAPI(ws, ...)and passes that API object to the plugin.index.ts, theconnectionhandler updates the logger's socket on reconnect, but does not update loaded plugins' API objects. The new request handler and response path use the new connection directly, explaining why queries still work.pluginAPI.ts,invokeMethodsends viathis.wswithout a send callback, then waits on a deferred response with no timeout. The officialwsimplementation's closed-socket send path reports failure through the optional callback; without one, no exception reaches the plugin and no response arrives.
Proposed narrow correction for review
Rebind each loaded plugin's existing API object when the host receives the replacement connection. Keeping the same API object preserves the object held by plugin code and its registered callbacks.
--- a/wox.plugin.host.nodejs/src/index.ts
+++ b/wox.plugin.host.nodejs/src/index.ts
@@ -1,6 +1,6 @@
import "winston-daily-rotate-file"
import { WebSocketServer } from "ws"
-import { handleRequestFromWox,PluginJsonRpcTypeRequest, PluginJsonRpcTypeResponse } from "./jsonrpc"
+import { handleRequestFromWox,PluginJsonRpcTypeRequest, PluginJsonRpcTypeResponse, pluginInstances } from "./jsonrpc"
import { logger } from "./logger"
import * as crypto from "crypto"
import Deferred from "promise-deferred"
@@ -47,6 +47,11 @@
const wss = new WebSocketServer({ port: Number.parseInt(port) })
wss.on("connection", function connection(ws) {
logger.updateWebSocket(ws)
+
+ // Loaded plugins retain their API object across host socket reconnects.
+ for (const instance of pluginInstances.values()) {
+ if (instance.API) instance.API.ws = ws
+ }
ws.on("error", function (error) {
logger.updateWebSocket(undefined)This only addresses calls made after the replacement connection has been established. It does not replay writes, reinitialize plugins, resolve already-pending calls, or prevent the original disconnect. Handling in-flight requests and API timeouts would need separate consideration.
Reproduction and validation
A source-level test executes the actual unmodified 2.4.4 index.ts and PluginAPI class, using an in-memory WebSocket transport and stubs for the logger, process, and request dispatcher. It then executes the same entry point with the proposed change. The transport models ws.send dropping a closed-socket message without throwing when no callback is provided.
The test verifies:
- Normal API calls before disconnect.
- Query responses on the replacement connection while the original API still points at the old socket.
- A dropped
HideApprequest and an unsettled promise in the original code. - Successful
HideAppcalls after two successive reconnects with the proposed change. - Preservation of the original API object's identity.
To run: use a clean Wox checkout at tag v2.4.4, save the script below as reconnect-proof.cjs in the repository root, then run it with Node.js 24:
node reconnect-proof.cjsNo dependency installation is required. The script reads source files and makes the proposed change in memory; it does not edit the checkout, run Wox, or touch any notes. Node may print an experimental warning for stripTypeScriptTypes.
Verified output:
Original v2.4.4: query succeeds on new socket; HideApp uses closed socket and waits forever.
Connection-rebind patch: queries and HideApp both use the live socket after repeated reconnects.The original-case assertion checks that the promise remains unsettled after queued work completes; the indefinite wait follows from the lack of a response/error/timeout path for the dropped request. This is not a real TCP/WebSocket integration test or a Windows UI test. A full build and Windows smoke test remain outstanding. The source analysis and harness were prepared with Codex.
Self-contained source-level reproduction (Node.js 24)// SPDX-License-Identifier: GPL-3.0-only
'use strict'
// Execute Wox v2.4.4's actual host entry point and PluginAPI class with an
// in-memory WebSocket transport. No Wox installation or user notes are changed.
const assert = require('node:assert/strict')
const fs = require('node:fs')
const path = require('node:path')
const crypto = require('node:crypto')
const { EventEmitter } = require('node:events')
const { stripTypeScriptTypes } = require('node:module')
const root = path.resolve(process.argv[2] || 'wox.plugin.host.nodejs/src')
const requestType = 'WOX_JSONRPC_REQUEST'
const responseType = 'WOX_JSONRPC_RESPONSE'
const source = name => fs.readFileSync(path.join(root, name), 'utf8')
function runnable(text) {
return stripTypeScriptTypes(text)
.replace(/^import[\s\S]*?["'][^"']+["'];?\s*$/gm, '')
.replace(/^export /gm, '')
}
class Deferred {
constructor() { this.promise = new Promise((resolve, reject) => { this.resolve = resolve; this.reject = reject }) }
}
// ws.send on an already CLOSED socket does not throw without a callback.
// Its sendAfterClose branch buffers the byte count and drops the message.
class Socket extends EventEmitter {
constructor() { super(); this.readyState = 1; this.sent = []; this.dropped = []; this.bufferedAmount = 0 }
send(raw, callback) {
const message = JSON.parse(raw)
if (this.readyState !== 1) {
this.dropped.push(message)
this.bufferedAmount += Buffer.byteLength(raw)
if (callback) queueMicrotask(() => callback(new Error('WebSocket is not open')))
return
}
this.sent.push(message)
if (message.Type === requestType) {
queueMicrotask(() => this.emit('message', JSON.stringify({ Type: responseType, Id: message.Id, TraceId: message.TraceId, Result: '' })))
}
if (callback) queueMicrotask(() => callback())
}
disconnect() { this.readyState = 3; this.emit('close', 1006, '') }
pong() {}
}
async function replay(patched) {
const pluginInstances = new Map()
let server, queries = 0
const ctx = { Values: {}, Get: () => 'reproduction-trace' }
const logger = { info() {}, error() {}, debug() {}, updateWebSocket() {} }
class Server extends EventEmitter { constructor() { super(); server = this } }
const originalEntry = source('index.ts')
const originalImport = 'import { handleRequestFromWox,PluginJsonRpcTypeRequest, PluginJsonRpcTypeResponse } from "./jsonrpc"'
const correctedImport = 'import { handleRequestFromWox,PluginJsonRpcTypeRequest, PluginJsonRpcTypeResponse, pluginInstances } from "./jsonrpc"'
const connectionLine = ' logger.updateWebSocket(ws)'
assert.equal(originalEntry.split(originalImport).length, 2, 'Use unmodified Wox v2.4.4 source')
assert.equal(originalEntry.split(connectionLine).length, 2)
const entry = patched
? originalEntry.replace(originalImport, correctedImport).replace(connectionLine, connectionLine + '\n\n // Loaded plugins retain their API object across host socket reconnects.\n for (const instance of pluginInstances.values()) {\n if (instance.API) instance.API.ws = ws\n }')
: originalEntry
const entryArgs = {
WebSocketServer: Server, logger, crypto, Deferred, pluginInstances,
process: { argv: ['node', 'index.js', '12345', 'logs', '1'], on() {}, kill() {} },
setInterval: () => 0, NewTraceContext: () => ctx, TraceIdKey: 'traceId',
NewContextWithValue: () => ctx, PluginJsonRpcTypeRequest: requestType, PluginJsonRpcTypeResponse: responseType,
handleRequestFromWox: async () => { queries++; return { Results: [{ Title: 'Capture preview' }] } }
}
const entryModule = new Function(...Object.keys(entryArgs), runnable(entry) + '\nreturn {waitingForResponse};')(...Object.values(entryArgs))
const apiArgs = { logger, crypto, Deferred, pluginInstances, waitingForResponse: entryModule.waitingForResponse, PluginJsonRpcTypeRequest: requestType }
const PluginAPI = new Function(...Object.keys(apiArgs), runnable(source('pluginAPI.ts')) + '\nreturn PluginAPI;')(...Object.values(apiArgs))
const original = new Socket()
server.emit('connection', original)
const api = new PluginAPI(original, 'tasknotes', 'TaskNotes Capture')
const savedAPI = api
pluginInstances.set('tasknotes', { API: api })
await api.HideApp(ctx)
assert.equal(original.sent.filter(x => x.Method === 'HideApp').length, 1)
original.disconnect()
const replacement = new Socket()
server.emit('connection', replacement)
replacement.emit('message', JSON.stringify({ Type: requestType, Id: 'query-after-reconnect', Method: 'query', PluginId: 'tasknotes', TraceId: 'trace' }))
await new Promise(setImmediate)
assert.equal(queries, 1)
assert.ok(replacement.sent.some(x => x.Id === 'query-after-reconnect' && x.Type === responseType))
assert.equal(pluginInstances.get('tasknotes').API, savedAPI, 'Do not replace the API object held by the plugin')
let completed = false
void api.HideApp(ctx).then(() => { completed = true })
await new Promise(setImmediate)
if (!patched) {
assert.equal(api.ws, original)
assert.equal(original.dropped.at(-1).Method, 'HideApp')
assert.equal(replacement.sent.filter(x => x.Method === 'HideApp').length, 0)
assert.equal(completed, false)
console.log('Original v2.4.4: query succeeds on new socket; HideApp uses closed socket and waits forever.')
} else {
assert.equal(api.ws, replacement)
assert.equal(original.dropped.length, 0)
assert.equal(replacement.sent.filter(x => x.Method === 'HideApp').length, 1)
assert.equal(completed, true)
// A second reconnect also works while preserving the same API object.
replacement.disconnect()
const third = new Socket()
server.emit('connection', third)
await api.HideApp(ctx)
assert.equal(api.ws, third)
assert.equal(third.sent.filter(x => x.Method === 'HideApp').length, 1)
console.log('Connection-rebind patch: queries and HideApp both use the live socket after repeated reconnects.')
}
}
(async () => { await replay(false); await replay(true) })().catch(error => { console.error(error); process.exitCode = 1 })Thanks for maintaining Wox. @qianlifeng, could you review whether rebinding loaded plugins to the current host connection is the appropriate correction here?
Source: Wox-launcher/Wox