refactor: Use dedicated WebSocket server for torch sync
- Add torch WebSocket server on port 4106 - Remove HTTP polling, use WebSocket for instant sync - Torch state changes broadcast immediately to all clients - Auto-reconnect on disconnect - Add port 4106 to kill-ports script
This commit is contained in:
@@ -2,6 +2,7 @@
|
||||
export const PORT_HTTP = 4101
|
||||
export const PORT_TERMINAL = 4103
|
||||
export const PORT_GIT = 4105
|
||||
export const PORT_TORCH = 4106
|
||||
|
||||
// Terminal configuration
|
||||
export const WORKING_DIR = process.cwd().replace(/[\\\/]server$/, '')
|
||||
|
||||
@@ -11,7 +11,6 @@ import { handleWhisperRoutes } from './whisper'
|
||||
import { handleRecordingsRoutes } from './recordings'
|
||||
import { handleClaudeStatus } from './claude-status'
|
||||
import { handleGitStatus, handleGitDiff, handleGitLog, handleGitLogCommit, handleGitCompare, handleGitBranches, handleGitCurrentBranch, handleGitTree, handleGitFile } from './git'
|
||||
import { handleTorch } from './torch'
|
||||
|
||||
export async function handleRequest(req: Request): Promise<Response> {
|
||||
const url = new URL(req.url)
|
||||
@@ -51,12 +50,6 @@ export async function handleRequest(req: Request): Promise<Response> {
|
||||
if (res) return res
|
||||
}
|
||||
|
||||
// Torch (multi-browser MCP control)
|
||||
if (path.startsWith('/api/torch')) {
|
||||
const res = await handleTorch(req, url)
|
||||
if (res) return res
|
||||
}
|
||||
|
||||
// Claude Code status (thinking/idle)
|
||||
if (path === '/api/claude-status') {
|
||||
const res = await handleClaudeStatus(req)
|
||||
|
||||
@@ -1,159 +0,0 @@
|
||||
import { jsonResponse, errorResponse } from '../utils/cors'
|
||||
|
||||
// Torch state - which client has control
|
||||
interface TorchClient {
|
||||
id: string
|
||||
userAgent: string
|
||||
hostname: string
|
||||
connectedAt: Date
|
||||
}
|
||||
|
||||
let torchState: {
|
||||
holderId: string | null
|
||||
clients: Map<string, TorchClient>
|
||||
} = {
|
||||
holderId: null,
|
||||
clients: new Map()
|
||||
}
|
||||
|
||||
// Generate unique client ID
|
||||
let clientIdCounter = 1
|
||||
function generateClientId(): string {
|
||||
return `client_${clientIdCounter++}_${Date.now().toString(36)}`
|
||||
}
|
||||
|
||||
// GET /api/torch - Get current torch state
|
||||
export async function handleTorchGet() {
|
||||
const clients = Array.from(torchState.clients.values()).map(c => ({
|
||||
...c,
|
||||
connectedAt: c.connectedAt.toISOString(),
|
||||
hasTorch: c.id === torchState.holderId
|
||||
}))
|
||||
|
||||
return jsonResponse({
|
||||
holderId: torchState.holderId,
|
||||
clients
|
||||
})
|
||||
}
|
||||
|
||||
// POST /api/torch/register - Register a new client
|
||||
export async function handleTorchRegister(req: Request) {
|
||||
const body = await req.json()
|
||||
const { userAgent, hostname } = body
|
||||
|
||||
const id = generateClientId()
|
||||
const client: TorchClient = {
|
||||
id,
|
||||
userAgent: userAgent || 'Unknown',
|
||||
hostname: hostname || 'Unknown',
|
||||
connectedAt: new Date()
|
||||
}
|
||||
|
||||
torchState.clients.set(id, client)
|
||||
|
||||
// Auto-assign torch if no one has it
|
||||
const shouldHaveTorch = !torchState.holderId
|
||||
if (shouldHaveTorch) {
|
||||
torchState.holderId = id
|
||||
}
|
||||
|
||||
console.log(`[Torch] Client registered: ${id} (torch: ${shouldHaveTorch})`)
|
||||
|
||||
return jsonResponse({
|
||||
id,
|
||||
hasTorch: shouldHaveTorch
|
||||
})
|
||||
}
|
||||
|
||||
// POST /api/torch/request - Request the torch
|
||||
export async function handleTorchRequest(req: Request) {
|
||||
const body = await req.json()
|
||||
const { clientId } = body
|
||||
|
||||
if (!clientId || !torchState.clients.has(clientId)) {
|
||||
return errorResponse('Invalid client ID', 400)
|
||||
}
|
||||
|
||||
const previousHolder = torchState.holderId
|
||||
torchState.holderId = clientId
|
||||
|
||||
console.log(`[Torch] Torch transferred: ${previousHolder} -> ${clientId}`)
|
||||
|
||||
return jsonResponse({
|
||||
success: true,
|
||||
previousHolder
|
||||
})
|
||||
}
|
||||
|
||||
// POST /api/torch/release - Release the torch
|
||||
export async function handleTorchRelease(req: Request) {
|
||||
const body = await req.json()
|
||||
const { clientId } = body
|
||||
|
||||
if (torchState.holderId !== clientId) {
|
||||
return errorResponse('You do not have the torch', 400)
|
||||
}
|
||||
|
||||
torchState.holderId = null
|
||||
console.log(`[Torch] Torch released by: ${clientId}`)
|
||||
|
||||
return jsonResponse({ success: true })
|
||||
}
|
||||
|
||||
// DELETE /api/torch/client/:id - Unregister a client
|
||||
export async function handleTorchUnregister(clientId: string) {
|
||||
if (!torchState.clients.has(clientId)) {
|
||||
return errorResponse('Client not found', 404)
|
||||
}
|
||||
|
||||
torchState.clients.delete(clientId)
|
||||
|
||||
// If this client had the torch, release it
|
||||
if (torchState.holderId === clientId) {
|
||||
torchState.holderId = null
|
||||
|
||||
// Auto-assign to next client if any
|
||||
const nextClient = torchState.clients.keys().next().value
|
||||
if (nextClient) {
|
||||
torchState.holderId = nextClient
|
||||
console.log(`[Torch] Auto-assigned to: ${nextClient}`)
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`[Torch] Client unregistered: ${clientId}`)
|
||||
|
||||
return jsonResponse({ success: true })
|
||||
}
|
||||
|
||||
// Main handler
|
||||
export async function handleTorch(req: Request, url: URL) {
|
||||
const path = url.pathname
|
||||
|
||||
// GET /api/torch - Get state
|
||||
if (req.method === 'GET' && path === '/api/torch') {
|
||||
return handleTorchGet()
|
||||
}
|
||||
|
||||
// POST /api/torch/register - Register client
|
||||
if (req.method === 'POST' && path === '/api/torch/register') {
|
||||
return handleTorchRegister(req)
|
||||
}
|
||||
|
||||
// POST /api/torch/request - Request torch
|
||||
if (req.method === 'POST' && path === '/api/torch/request') {
|
||||
return handleTorchRequest(req)
|
||||
}
|
||||
|
||||
// POST /api/torch/release - Release torch
|
||||
if (req.method === 'POST' && path === '/api/torch/release') {
|
||||
return handleTorchRelease(req)
|
||||
}
|
||||
|
||||
// DELETE /api/torch/client/:id - Unregister
|
||||
const unregisterMatch = path.match(/^\/api\/torch\/client\/(.+)$/)
|
||||
if (req.method === 'DELETE' && unregisterMatch) {
|
||||
return handleTorchUnregister(unregisterMatch[1])
|
||||
}
|
||||
|
||||
return null
|
||||
}
|
||||
192
server/services/torch-server.ts
Normal file
192
server/services/torch-server.ts
Normal file
@@ -0,0 +1,192 @@
|
||||
/**
|
||||
* Torch Server
|
||||
* WebSocket server for multi-browser MCP control synchronization.
|
||||
* Only one browser can have the "torch" and connect to MCP at a time.
|
||||
*/
|
||||
|
||||
import { PORT_TORCH } from '../config'
|
||||
|
||||
// Client metadata
|
||||
interface TorchClient {
|
||||
ws: any
|
||||
id: string
|
||||
userAgent: string
|
||||
hostname: string
|
||||
connectedAt: Date
|
||||
}
|
||||
|
||||
// Connected clients
|
||||
const clients = new Map<any, TorchClient>()
|
||||
let clientIdCounter = 1
|
||||
|
||||
// Torch state - who has control
|
||||
let torchHolderId: string | null = null
|
||||
|
||||
function generateClientId(): string {
|
||||
return `client_${clientIdCounter++}_${Date.now().toString(36)}`
|
||||
}
|
||||
|
||||
function broadcast(message: string) {
|
||||
for (const [ws] of clients) {
|
||||
try {
|
||||
ws.send(message)
|
||||
} catch {
|
||||
clients.delete(ws)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function broadcastTorchState() {
|
||||
const clientList = Array.from(clients.values()).map(c => ({
|
||||
id: c.id,
|
||||
userAgent: c.userAgent,
|
||||
hostname: c.hostname,
|
||||
connectedAt: c.connectedAt.toISOString(),
|
||||
hasTorch: c.id === torchHolderId
|
||||
}))
|
||||
|
||||
const message = JSON.stringify({
|
||||
type: 'torch-update',
|
||||
holderId: torchHolderId,
|
||||
clients: clientList
|
||||
})
|
||||
|
||||
broadcast(message)
|
||||
}
|
||||
|
||||
function handleMessage(ws: any, data: any) {
|
||||
const client = clients.get(ws)
|
||||
if (!client) return
|
||||
|
||||
switch (data.type) {
|
||||
case 'register': {
|
||||
client.userAgent = data.userAgent || 'Unknown'
|
||||
client.hostname = data.hostname || 'Unknown'
|
||||
|
||||
// Auto-assign torch if no one has it
|
||||
const shouldHaveTorch = !torchHolderId
|
||||
if (shouldHaveTorch) {
|
||||
torchHolderId = client.id
|
||||
}
|
||||
|
||||
ws.send(JSON.stringify({
|
||||
type: 'registered',
|
||||
id: client.id,
|
||||
hasTorch: shouldHaveTorch
|
||||
}))
|
||||
|
||||
console.log(`[Torch] Registered: ${client.id} (torch: ${shouldHaveTorch})`)
|
||||
broadcastTorchState()
|
||||
break
|
||||
}
|
||||
|
||||
case 'request': {
|
||||
const previousHolder = torchHolderId
|
||||
torchHolderId = client.id
|
||||
|
||||
ws.send(JSON.stringify({ type: 'granted' }))
|
||||
console.log(`[Torch] Transferred: ${previousHolder} → ${client.id}`)
|
||||
broadcastTorchState()
|
||||
break
|
||||
}
|
||||
|
||||
case 'release': {
|
||||
if (torchHolderId === client.id) {
|
||||
torchHolderId = null
|
||||
ws.send(JSON.stringify({ type: 'released' }))
|
||||
console.log(`[Torch] Released by: ${client.id}`)
|
||||
broadcastTorchState()
|
||||
}
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function startTorchServer() {
|
||||
const server = Bun.serve({
|
||||
port: PORT_TORCH,
|
||||
fetch(req, server) {
|
||||
const url = new URL(req.url)
|
||||
|
||||
// CORS headers
|
||||
const corsHeaders = {
|
||||
'Access-Control-Allow-Origin': '*',
|
||||
'Access-Control-Allow-Methods': 'GET, OPTIONS',
|
||||
'Access-Control-Allow-Headers': 'Content-Type'
|
||||
}
|
||||
|
||||
if (req.method === 'OPTIONS') {
|
||||
return new Response(null, { headers: corsHeaders })
|
||||
}
|
||||
|
||||
// Health check
|
||||
if (url.pathname === '/health') {
|
||||
return Response.json({
|
||||
status: 'ok',
|
||||
clients: clients.size,
|
||||
torchHolder: torchHolderId
|
||||
}, { headers: corsHeaders })
|
||||
}
|
||||
|
||||
// WebSocket upgrade
|
||||
const upgrade = req.headers.get('upgrade')
|
||||
if (upgrade?.toLowerCase() === 'websocket') {
|
||||
const success = server.upgrade(req)
|
||||
if (success) return undefined
|
||||
return new Response('WebSocket upgrade failed', { status: 400 })
|
||||
}
|
||||
|
||||
return new Response('Torch WebSocket Server', { status: 200 })
|
||||
},
|
||||
websocket: {
|
||||
open(ws) {
|
||||
const id = generateClientId()
|
||||
clients.set(ws, {
|
||||
ws,
|
||||
id,
|
||||
userAgent: 'Unknown',
|
||||
hostname: 'Unknown',
|
||||
connectedAt: new Date()
|
||||
})
|
||||
console.log(`[Torch] Client connected: ${id} (${clients.size} total)`)
|
||||
},
|
||||
message(ws, message) {
|
||||
try {
|
||||
const data = JSON.parse(message.toString())
|
||||
handleMessage(ws, data)
|
||||
} catch (e) {
|
||||
console.error('[Torch] Invalid message:', e)
|
||||
}
|
||||
},
|
||||
close(ws) {
|
||||
const client = clients.get(ws)
|
||||
if (client) {
|
||||
console.log(`[Torch] Client disconnected: ${client.id}`)
|
||||
|
||||
// If this client had the torch, release it
|
||||
if (torchHolderId === client.id) {
|
||||
torchHolderId = null
|
||||
|
||||
// Auto-assign to next client
|
||||
const nextClient = clients.values().next().value
|
||||
if (nextClient && nextClient.ws !== ws) {
|
||||
torchHolderId = nextClient.id
|
||||
console.log(`[Torch] Auto-assigned to: ${nextClient.id}`)
|
||||
}
|
||||
}
|
||||
|
||||
clients.delete(ws)
|
||||
broadcastTorchState()
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
console.log(`[Torch] WebSocket server on port ${PORT_TORCH}`)
|
||||
return server
|
||||
}
|
||||
|
||||
export function stopTorchServer() {
|
||||
clients.clear()
|
||||
torchHolderId = null
|
||||
}
|
||||
@@ -7,6 +7,7 @@
|
||||
|
||||
import { startTerminalServer } from './services/terminal'
|
||||
import { startGitServer } from './services/git-watcher'
|
||||
import { startTorchServer } from './services/torch-server'
|
||||
import { WORKING_DIR } from './config'
|
||||
|
||||
console.log('')
|
||||
@@ -14,6 +15,7 @@ console.log('='.repeat(50))
|
||||
console.log('Terminal Server (Independent Process)')
|
||||
console.log(` Terminal WebSocket: ws://localhost:4103`)
|
||||
console.log(` Git WebSocket: ws://localhost:4105`)
|
||||
console.log(` Torch WebSocket: ws://localhost:4106`)
|
||||
console.log(` Working Dir: ${WORKING_DIR}`)
|
||||
console.log('')
|
||||
console.log('This process is stable and won\'t restart')
|
||||
@@ -23,3 +25,4 @@ console.log('')
|
||||
|
||||
startTerminalServer()
|
||||
startGitServer()
|
||||
startTorchServer()
|
||||
|
||||
Reference in New Issue
Block a user