refactor: Unify sync server and combine torch with connection UI

- Consolidate git and torch WebSocket servers on port 4105
- Create separate handlers for git and torch in handlers/ directory
- Combine TorchButton with connection status into single pill button
- Remove StatusBar (now redundant with TorchButton)
- Remove auto-assign torch on register/disconnect
- Remove auto-connect to MCP on page load
- Connection only happens when user explicitly requests torch
This commit is contained in:
2026-02-14 17:13:32 -06:00
parent c98f3e2b99
commit 0f73bd60bf
13 changed files with 519 additions and 434 deletions

View File

@@ -2,7 +2,6 @@
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$/, '')

View File

@@ -1,158 +0,0 @@
/**
* Git Watcher Service
* WebSocket server dedicado para notificaciones de cambios en git.
* Completamente separado del terminal.
*/
import { watch, type FSWatcher } from 'fs'
import { join } from 'path'
import { PORT_GIT, WORKING_DIR } from '../config'
// Connected clients (simple WebSocket set, no PTY, no sessions)
const clients = new Set<any>()
// Git watcher
let gitWatcher: FSWatcher | null = null
let debounceTimer: ReturnType<typeof setTimeout> | null = null
const DEBOUNCE_MS = 300
// Files to ignore
const IGNORE_PATTERNS = [
'FETCH_HEAD',
'gc.log',
'.lock',
'COMMIT_EDITMSG',
'ORIG_HEAD',
'gitk.cache',
'sourcetreeconfig',
'.DS_Store',
'fsmonitor',
'packed-refs'
]
function broadcastGitChange() {
const message = JSON.stringify({
type: 'git-change',
timestamp: Date.now()
})
let count = 0
for (const ws of clients) {
try {
ws.send(message)
count++
} catch {
// Client disconnected
clients.delete(ws)
}
}
if (count > 0) {
console.log(`[Git] Change → ${count} clients`)
}
}
function startWatcher() {
const gitDir = join(WORKING_DIR, '.git')
try {
gitWatcher = watch(gitDir, { recursive: true }, (_, filename) => {
if (!filename) return
// Ignore noisy files
if (IGNORE_PATTERNS.some(p => filename.includes(p))) return
// Only meaningful changes
const isRelevant =
filename.includes('refs/') ||
filename === 'HEAD' ||
filename === 'index' ||
filename.includes('objects/')
if (!isRelevant) return
// Debounce
if (debounceTimer) clearTimeout(debounceTimer)
debounceTimer = setTimeout(() => {
console.log(`[Git] Change: ${filename}`)
broadcastGitChange()
}, DEBOUNCE_MS)
})
console.log(`[Git] Watching ${gitDir}`)
} catch (e: any) {
console.error(`[Git] Watch failed: ${e.message}`)
}
}
export function startGitServer() {
const server = Bun.serve({
port: PORT_GIT,
fetch(req, server) {
const url = new URL(req.url)
// CORS
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,
watching: gitWatcher !== null
}, { 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('Git WebSocket Server\n\nConnect via WebSocket for real-time git notifications.', { status: 200 })
},
websocket: {
open(ws) {
clients.add(ws)
console.log(`[Git] Client connected (${clients.size} total)`)
ws.send(JSON.stringify({ type: 'connected' }))
},
message() {
// No messages expected from client
},
close(ws) {
clients.delete(ws)
console.log(`[Git] Client disconnected (${clients.size} total)`)
}
}
})
console.log(`[Git] WebSocket server on port ${PORT_GIT}`)
// Start file watcher
startWatcher()
return server
}
export function stopGitServer() {
if (gitWatcher) {
gitWatcher.close()
gitWatcher = null
}
if (debounceTimer) {
clearTimeout(debounceTimer)
debounceTimer = null
}
clients.clear()
}

View File

@@ -0,0 +1,86 @@
/**
* Git Handler
* Handles git file watching and client notifications for the sync server.
*/
import { watch, type FSWatcher } from 'fs'
import { join } from 'path'
// Git watcher state
let gitWatcher: FSWatcher | null = null
let debounceTimer: ReturnType<typeof setTimeout> | null = null
const DEBOUNCE_MS = 300
// Files to ignore
const IGNORE_PATTERNS = [
'FETCH_HEAD',
'gc.log',
'.lock',
'COMMIT_EDITMSG',
'ORIG_HEAD',
'gitk.cache',
'sourcetreeconfig',
'.DS_Store',
'fsmonitor',
'packed-refs'
]
/**
* Set up git directory watcher
*/
export function setupGitWatcher(workingDir: string, broadcast: (message: string, filter?: (ws: any) => boolean) => void) {
const gitDir = join(workingDir, '.git')
try {
gitWatcher = watch(gitDir, { recursive: true }, (_, filename) => {
if (!filename) return
// Ignore noisy files
if (IGNORE_PATTERNS.some(p => filename.includes(p))) return
// Only meaningful changes
const isRelevant =
filename.includes('refs/') ||
filename === 'HEAD' ||
filename === 'index' ||
filename.includes('objects/')
if (!isRelevant) return
// Debounce
if (debounceTimer) clearTimeout(debounceTimer)
debounceTimer = setTimeout(() => {
console.log(`[Git] Change: ${filename}`)
broadcast(JSON.stringify({
type: 'git-change',
timestamp: Date.now()
}))
}, DEBOUNCE_MS)
})
console.log(`[Git] Watching ${gitDir}`)
} catch (e: any) {
console.error(`[Git] Watch failed: ${e.message}`)
}
}
/**
* Handle new git client connection
*/
export function handleGitClient(ws: any) {
ws.send(JSON.stringify({ type: 'connected' }))
}
/**
* Cleanup git watcher
*/
export function cleanupGitWatcher() {
if (gitWatcher) {
gitWatcher.close()
gitWatcher = null
}
if (debounceTimer) {
clearTimeout(debounceTimer)
debounceTimer = null
}
}

View File

@@ -0,0 +1,143 @@
/**
* Torch Handler
* Handles multi-browser MCP control synchronization for the sync server.
* Only one browser can have the "torch" and connect to MCP at a time.
*/
// Client metadata
interface TorchClient {
ws: any
id: string
userAgent: string
hostname: string
connectedAt: Date
}
// Connected torch clients (separate tracking from main clients set)
const torchClients = 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 broadcastTorchState(broadcast: (message: string, filter?: (ws: any) => boolean) => void) {
const clientList = Array.from(torchClients.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)
}
/**
* Handle torch client connection
*/
export function handleTorchConnect(ws: any, broadcast: (message: string, filter?: (ws: any) => boolean) => void) {
const id = generateClientId()
torchClients.set(ws, {
ws,
id,
userAgent: 'Unknown',
hostname: 'Unknown',
connectedAt: new Date()
})
console.log(`[Torch] Client connected: ${id} (${torchClients.size} total)`)
}
/**
* Handle torch messages
*/
export function handleTorchMessage(ws: any, data: any, broadcast: (message: string, filter?: (ws: any) => boolean) => void) {
const client = torchClients.get(ws)
if (!client) return
switch (data.type) {
case 'register': {
client.userAgent = data.userAgent || 'Unknown'
client.hostname = data.hostname || 'Unknown'
// No auto-assign - torch must be explicitly requested
const hasTorch = torchHolderId === client.id
ws.send(JSON.stringify({
type: 'registered',
id: client.id,
hasTorch
}))
console.log(`[Torch] Registered: ${client.id} (torch: ${hasTorch})`)
broadcastTorchState(broadcast)
break
}
case 'request': {
const previousHolder = torchHolderId
torchHolderId = client.id
ws.send(JSON.stringify({ type: 'granted' }))
console.log(`[Torch] Transferred: ${previousHolder}${client.id}`)
broadcastTorchState(broadcast)
break
}
case 'release': {
if (torchHolderId === client.id) {
torchHolderId = null
ws.send(JSON.stringify({ type: 'released' }))
console.log(`[Torch] Released by: ${client.id}`)
broadcastTorchState(broadcast)
}
break
}
}
}
/**
* Handle torch client disconnect
*/
export function handleTorchDisconnect(ws: any, broadcast: (message: string, filter?: (ws: any) => boolean) => void) {
const client = torchClients.get(ws)
if (client) {
console.log(`[Torch] Client disconnected: ${client.id}`)
// If this client had the torch, release it (no auto-assign)
if (torchHolderId === client.id) {
torchHolderId = null
console.log(`[Torch] Torch released (holder disconnected)`)
}
torchClients.delete(ws)
broadcastTorchState(broadcast)
}
}
/**
* Get torch status for health check
*/
export function getTorchStatus() {
return {
clients: torchClients.size,
torchHolder: torchHolderId
}
}
/**
* Cleanup torch handler
*/
export function cleanupTorchHandler() {
torchClients.clear()
torchHolderId = null
}

View File

@@ -0,0 +1,109 @@
/**
* Sync Server
* Unified WebSocket server for real-time synchronization:
* - Git change notifications
* - Torch (multi-browser MCP control)
*/
import { PORT_GIT, WORKING_DIR } from '../config'
import { setupGitWatcher, handleGitClient, cleanupGitWatcher } from './handlers/git-handler'
import { handleTorchMessage, handleTorchConnect, handleTorchDisconnect, getTorchStatus, cleanupTorchHandler } from './handlers/torch-handler'
// Connected clients
const clients = new Set<any>()
export function broadcast(message: string, filter?: (ws: any) => boolean) {
for (const ws of clients) {
if (filter && !filter(ws)) continue
try {
ws.send(message)
} catch {
clients.delete(ws)
}
}
}
export function getClients() {
return clients
}
export function startSyncServer() {
const server = Bun.serve({
port: PORT_GIT,
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') {
const torchStatus = getTorchStatus()
return Response.json({
status: 'ok',
clients: clients.size,
torch: torchStatus
}, { 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('Sync WebSocket Server (Git + Torch)', { status: 200 })
},
websocket: {
open(ws) {
clients.add(ws)
console.log(`[Sync] Client connected (${clients.size} total)`)
// Initialize client for both services
handleGitClient(ws)
handleTorchConnect(ws, broadcast)
},
message(ws, message) {
try {
const data = JSON.parse(message.toString())
// Route to appropriate handler based on message type
if (data.type?.startsWith('torch-') || ['register', 'request', 'release'].includes(data.type)) {
handleTorchMessage(ws, data, broadcast)
}
// Git doesn't expect messages from client
} catch (e) {
console.error('[Sync] Invalid message:', e)
}
},
close(ws) {
clients.delete(ws)
console.log(`[Sync] Client disconnected (${clients.size} total)`)
handleTorchDisconnect(ws, broadcast)
}
}
})
console.log(`[Sync] WebSocket server on port ${PORT_GIT}`)
// Start git file watcher
setupGitWatcher(WORKING_DIR, broadcast)
return server
}
export function stopSyncServer() {
cleanupGitWatcher()
cleanupTorchHandler()
clients.clear()
}

View File

@@ -1,192 +0,0 @@
/**
* 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
}

View File

@@ -6,16 +6,14 @@
*/
import { startTerminalServer } from './services/terminal'
import { startGitServer } from './services/git-watcher'
import { startTorchServer } from './services/torch-server'
import { startSyncServer } from './services/sync-server'
import { WORKING_DIR } from './config'
console.log('')
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(` Sync WebSocket (Git + Torch): ws://localhost:4105`)
console.log(` Working Dir: ${WORKING_DIR}`)
console.log('')
console.log('This process is stable and won\'t restart')
@@ -24,5 +22,4 @@ console.log('='.repeat(50))
console.log('')
startTerminalServer()
startGitServer()
startTorchServer()
startSyncServer()