Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 6 additions & 1 deletion src/context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,14 @@ export class Context {
return this._ws;
}

set ws(ws: WebSocket) {
set ws(ws: WebSocket | undefined) {
this._ws = ws;
}

clearWs() {
this._ws = undefined;
}

hasWs(): boolean {
return !!this._ws;
}
Expand Down Expand Up @@ -48,5 +52,6 @@ export class Context {
return;
}
await this._ws.close();
this._ws = undefined;
}
}
23 changes: 21 additions & 2 deletions src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,27 @@ export async function createServerWithTools(options: Options): Promise<Server> {
wss.on("connection", (websocket) => {
// Close any existing connections
if (context.hasWs()) {
context.ws.close();
try {
context.ws.close();
} catch {}
}
context.ws = websocket;

// Ping heartbeat to keep Chrome MV3 background service worker alive
const pingInterval = setInterval(() => {
if (websocket.readyState === websocket.OPEN) {
websocket.ping();
} else {
clearInterval(pingInterval);
}
}, 5000);

websocket.on("close", () => {
clearInterval(pingInterval);
if (context.hasWs() && context.ws === websocket) {
context.clearWs();
}
});
});

server.setRequestHandler(ListToolsRequestSchema, async () => {
Expand Down Expand Up @@ -82,8 +100,9 @@ export async function createServerWithTools(options: Options): Promise<Server> {
return { contents };
});

const originalClose = server.close.bind(server);
server.close = async () => {
await server.close();
await originalClose();
await wss.close();
await context.close();
};
Expand Down
11 changes: 7 additions & 4 deletions src/utils/port.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,15 @@ export function killProcessOnPort(port: number) {
try {
if (process.platform === "win32") {
execSync(
`FOR /F "tokens=5" %a in ('netstat -ano ^| findstr :${port}') do taskkill /F /PID %a`,
`FOR /F "tokens=5" %a in ('netstat -ano ^| findstr :${port}') do taskkill /F /PID %a 2>nul`,
{ stdio: "ignore" },
);
} else {
execSync(`lsof -ti:${port} | xargs kill -9`);
execSync(`lsof -ti:${port} | xargs kill -9 2>/dev/null`, {
stdio: "ignore",
});
}
} catch (error) {
console.error(`Failed to kill process on port ${port}:`, error);
} catch {
// Port might not be in use, ignore expected exit code
}
}