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:
@@ -1,7 +1,6 @@
|
||||
<script setup lang="ts">
|
||||
import { ref, onMounted, onUnmounted, watch } from 'vue'
|
||||
import { RouterView, useRoute, useRouter } from 'vue-router'
|
||||
import StatusBar from './components/StatusBar.vue'
|
||||
import Toolbar from './components/Toolbar.vue'
|
||||
import TorchButton from './components/TorchButton.vue'
|
||||
import FloatingTerminal from './components/FloatingTerminal.vue'
|
||||
@@ -348,7 +347,6 @@ watch(() => route.name, (newPage) => {
|
||||
<header class="app-header">
|
||||
<div class="header-left">
|
||||
<h1 class="logo">Agent UI</h1>
|
||||
<TorchButton />
|
||||
<button class="debug-btn" :class="{ active: showDebugConsole }" @click="showDebugConsole = !showDebugConsole" title="Debug Console">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
|
||||
<path d="M12 20h9"/><path d="M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z"/>
|
||||
@@ -357,13 +355,15 @@ watch(() => route.name, (newPage) => {
|
||||
</button>
|
||||
<PwaInstallBanner />
|
||||
</div>
|
||||
<button class="refresh-btn" @click="hardRefresh" title="Hard refresh (Ctrl+F5)">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8"/>
|
||||
<path d="M21 3v5h-5"/>
|
||||
</svg>
|
||||
</button>
|
||||
<StatusBar />
|
||||
<div class="header-right">
|
||||
<button class="refresh-btn" @click="hardRefresh" title="Hard refresh (Ctrl+F5)">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8"/>
|
||||
<path d="M21 3v5h-5"/>
|
||||
</svg>
|
||||
</button>
|
||||
<TorchButton />
|
||||
</div>
|
||||
</header>
|
||||
<main class="app-main">
|
||||
<Toolbar />
|
||||
@@ -545,6 +545,12 @@ watch(() => route.name, (newPage) => {
|
||||
gap: 1.5rem;
|
||||
}
|
||||
|
||||
.header-right {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.logo {
|
||||
font-size: 1.25rem;
|
||||
font-weight: 600;
|
||||
|
||||
@@ -1,8 +1,46 @@
|
||||
<script setup lang="ts">
|
||||
import { computed } from 'vue'
|
||||
import { useTorchStore } from '../stores/torch'
|
||||
import { useCanvasStore } from '../stores/canvas'
|
||||
import { requestTorch, releaseTorch } from '../services/torch'
|
||||
|
||||
const torchStore = useTorchStore()
|
||||
const canvasStore = useCanvasStore()
|
||||
|
||||
// Combined state
|
||||
const hasTorch = computed(() => torchStore.hasTorch)
|
||||
const isConnected = computed(() => canvasStore.isConnected)
|
||||
const isReconnecting = computed(() => canvasStore.isReconnecting)
|
||||
|
||||
// Visual states:
|
||||
// - No torch: gray, "Sin control"
|
||||
// - Has torch, reconnecting: orange pulse, "Conectando..."
|
||||
// - Has torch, not connected: orange, "Conectando..."
|
||||
// - Has torch, connected: green glow, "Conectado"
|
||||
const buttonState = computed(() => {
|
||||
if (!hasTorch.value) return 'no-torch'
|
||||
if (isReconnecting.value) return 'reconnecting'
|
||||
if (isConnected.value) return 'connected'
|
||||
return 'has-torch'
|
||||
})
|
||||
|
||||
const statusText = computed(() => {
|
||||
if (!hasTorch.value) return 'Sin control'
|
||||
if (isReconnecting.value) return 'Conectando...'
|
||||
if (isConnected.value) return 'Conectado'
|
||||
return 'Conectando...'
|
||||
})
|
||||
|
||||
const tooltipText = computed(() => {
|
||||
if (!hasTorch.value) {
|
||||
return torchStore.torchHolderId
|
||||
? 'Otro browser tiene el control - click para solicitar'
|
||||
: 'Click para solicitar control MCP'
|
||||
}
|
||||
if (isReconnecting.value) return 'Reconectando al MCP...'
|
||||
if (isConnected.value) return 'Conectado al MCP - click para liberar control'
|
||||
return 'Tiene control, conectando al MCP...'
|
||||
})
|
||||
|
||||
async function handleClick() {
|
||||
if (torchStore.hasTorch) {
|
||||
@@ -16,20 +54,12 @@ async function handleClick() {
|
||||
<template>
|
||||
<button
|
||||
class="torch-btn"
|
||||
:class="{
|
||||
'has-torch': torchStore.hasTorch,
|
||||
'torch-held': torchStore.torchHolderId && !torchStore.hasTorch,
|
||||
'requesting': torchStore.isRequesting
|
||||
}"
|
||||
:class="[buttonState, { requesting: torchStore.isRequesting }]"
|
||||
@click="handleClick"
|
||||
:title="torchStore.hasTorch ? 'You have the torch - click to release' : torchStore.torchHolderId ? 'Torch held by another client - click to request' : 'Click to request the torch'"
|
||||
:title="tooltipText"
|
||||
>
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
||||
<!-- Torch/flame icon -->
|
||||
<path d="M12 2c1 3 2.5 3.5 3.5 4.5A5 5 0 0 1 17 10a5 5 0 0 1-5 5 5 5 0 0 1-5-5 5 5 0 0 1 1.5-3.5C9.5 5.5 11 5 12 2z"/>
|
||||
<path d="M12 15v7"/>
|
||||
<path d="M10 22h4"/>
|
||||
</svg>
|
||||
<span class="status-dot"></span>
|
||||
<span class="status-text">{{ statusText }}</span>
|
||||
<span v-if="torchStore.isRequesting" class="requesting-indicator"></span>
|
||||
</button>
|
||||
</template>
|
||||
@@ -38,45 +68,86 @@ async function handleClick() {
|
||||
.torch-btn {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
padding: 6px 10px;
|
||||
background: var(--bg-secondary);
|
||||
border: 1px solid var(--border-color);
|
||||
border-radius: 6px;
|
||||
color: var(--text-secondary);
|
||||
gap: 0.5rem;
|
||||
padding: 0.375rem 0.75rem;
|
||||
border-radius: 9999px;
|
||||
font-size: 0.75rem;
|
||||
font-weight: 500;
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
transition: all 0.2s ease;
|
||||
transition: all 0.3s ease;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.torch-btn:hover {
|
||||
background: var(--bg-tertiary);
|
||||
color: var(--text-primary);
|
||||
.status-dot {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-radius: 50%;
|
||||
transition: all 0.3s ease;
|
||||
}
|
||||
|
||||
/* Has the torch - golden glow */
|
||||
.status-text {
|
||||
transition: all 0.3s ease;
|
||||
}
|
||||
|
||||
/* No torch - gray/red, dimmed */
|
||||
.torch-btn.no-torch {
|
||||
background: rgba(239, 68, 68, 0.1);
|
||||
color: #ef4444;
|
||||
}
|
||||
|
||||
.torch-btn.no-torch .status-dot {
|
||||
background: #ef4444;
|
||||
}
|
||||
|
||||
.torch-btn.no-torch:hover {
|
||||
background: rgba(245, 158, 11, 0.15);
|
||||
color: #f59e0b;
|
||||
}
|
||||
|
||||
.torch-btn.no-torch:hover .status-dot {
|
||||
background: #f59e0b;
|
||||
box-shadow: 0 0 8px #f59e0b;
|
||||
}
|
||||
|
||||
/* Has torch but connecting - orange pulse */
|
||||
.torch-btn.has-torch {
|
||||
background: linear-gradient(135deg, #ff9500 0%, #ff6b00 100%);
|
||||
border-color: #ff9500;
|
||||
color: white;
|
||||
box-shadow: 0 0 12px rgba(255, 149, 0, 0.5);
|
||||
animation: torch-glow 2s ease-in-out infinite;
|
||||
background: rgba(245, 158, 11, 0.15);
|
||||
color: #f59e0b;
|
||||
animation: status-pulse 2s ease-in-out infinite;
|
||||
}
|
||||
|
||||
.torch-btn.has-torch:hover {
|
||||
background: linear-gradient(135deg, #ffaa33 0%, #ff8533 100%);
|
||||
.torch-btn.has-torch .status-dot {
|
||||
background: #f59e0b;
|
||||
box-shadow: 0 0 8px #f59e0b;
|
||||
animation: dot-pulse 1.5s ease-in-out infinite;
|
||||
}
|
||||
|
||||
/* Torch held by another */
|
||||
.torch-btn.torch-held {
|
||||
background: var(--bg-secondary);
|
||||
border-color: #ff9500;
|
||||
color: #ff9500;
|
||||
opacity: 0.7;
|
||||
/* Reconnecting - orange with faster pulse */
|
||||
.torch-btn.reconnecting {
|
||||
background: rgba(245, 158, 11, 0.15);
|
||||
color: #f59e0b;
|
||||
animation: status-pulse 1s ease-in-out infinite;
|
||||
}
|
||||
|
||||
.torch-btn.torch-held:hover {
|
||||
opacity: 1;
|
||||
.torch-btn.reconnecting .status-dot {
|
||||
background: #f59e0b;
|
||||
animation: dot-pulse 0.8s ease-in-out infinite;
|
||||
}
|
||||
|
||||
/* Connected - green glow */
|
||||
.torch-btn.connected {
|
||||
background: rgba(34, 197, 94, 0.1);
|
||||
color: #22c55e;
|
||||
}
|
||||
|
||||
.torch-btn.connected .status-dot {
|
||||
background: #22c55e;
|
||||
box-shadow: 0 0 8px #22c55e;
|
||||
}
|
||||
|
||||
.torch-btn.connected:hover {
|
||||
background: rgba(34, 197, 94, 0.2);
|
||||
}
|
||||
|
||||
/* Requesting state */
|
||||
@@ -90,27 +161,39 @@ async function handleClick() {
|
||||
right: -2px;
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
background: var(--accent-color);
|
||||
background: #6366f1;
|
||||
border-radius: 50%;
|
||||
animation: pulse 1s ease-in-out infinite;
|
||||
animation: request-pulse 1s ease-in-out infinite;
|
||||
}
|
||||
|
||||
@keyframes torch-glow {
|
||||
/* Animations */
|
||||
@keyframes status-pulse {
|
||||
0%, 100% {
|
||||
box-shadow: 0 0 12px rgba(255, 149, 0, 0.5);
|
||||
opacity: 1;
|
||||
}
|
||||
50% {
|
||||
box-shadow: 0 0 20px rgba(255, 149, 0, 0.8);
|
||||
opacity: 0.7;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes pulse {
|
||||
@keyframes dot-pulse {
|
||||
0%, 100% {
|
||||
transform: scale(1);
|
||||
opacity: 1;
|
||||
}
|
||||
50% {
|
||||
transform: scale(1.2);
|
||||
transform: scale(1.3);
|
||||
opacity: 0.8;
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes request-pulse {
|
||||
0%, 100% {
|
||||
transform: scale(1);
|
||||
opacity: 1;
|
||||
}
|
||||
50% {
|
||||
transform: scale(1.3);
|
||||
opacity: 0.7;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -50,8 +50,8 @@ export const endpoints = {
|
||||
// WebMCP HTTP API (for token requests)
|
||||
webmcpHttp: buildHttpUrl('/mcp', 4102),
|
||||
|
||||
// Torch WebSocket (multi-browser sync)
|
||||
torch: buildWsUrl('/ws/torch', 4106),
|
||||
// Torch WebSocket (multi-browser sync) - same port as git
|
||||
torch: buildWsUrl('/ws/git', 4105),
|
||||
|
||||
// API base URL (Vite proxy handles /api in dev)
|
||||
api: '/api'
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useTorchStore } from '../stores/torch'
|
||||
import { getWebMCP, autoConnect } from './webmcp'
|
||||
import { autoConnect, disconnectWebMCP } from './webmcp'
|
||||
import { endpoints } from '../config/endpoints'
|
||||
|
||||
let torchWs: WebSocket | null = null
|
||||
@@ -71,9 +71,9 @@ async function handleMessage(data: any) {
|
||||
torchStore.setClientId(data.id)
|
||||
console.log(`[Torch] Registered as ${data.id}, hasTorch: ${data.hasTorch}`)
|
||||
|
||||
// Just update state, don't auto-connect - user must request torch explicitly
|
||||
if (data.hasTorch) {
|
||||
torchStore.setTorchState(data.id)
|
||||
await connectToMCP()
|
||||
}
|
||||
break
|
||||
}
|
||||
@@ -147,17 +147,6 @@ export async function releaseTorch(): Promise<boolean> {
|
||||
* Connect to MCP (when we have the torch)
|
||||
*/
|
||||
async function connectToMCP(): Promise<void> {
|
||||
const webmcp = getWebMCP()
|
||||
if (!webmcp) {
|
||||
console.error('[Torch] WebMCP not initialized')
|
||||
return
|
||||
}
|
||||
|
||||
if (webmcp.isConnected) {
|
||||
console.log('[Torch] Already connected to MCP')
|
||||
return
|
||||
}
|
||||
|
||||
console.log('[Torch] Connecting to MCP...')
|
||||
const success = await autoConnect()
|
||||
if (success) {
|
||||
@@ -171,13 +160,8 @@ async function connectToMCP(): Promise<void> {
|
||||
* Disconnect from MCP (when we lose the torch)
|
||||
*/
|
||||
function disconnectFromMCP(): void {
|
||||
const webmcp = getWebMCP()
|
||||
if (!webmcp) return
|
||||
|
||||
if (webmcp.isConnected && typeof webmcp.disconnect === 'function') {
|
||||
console.log('[Torch] Disconnecting from MCP...')
|
||||
webmcp.disconnect()
|
||||
}
|
||||
console.log('[Torch] Disconnecting from MCP...')
|
||||
disconnectWebMCP()
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -195,6 +195,34 @@ export function clearAllTools() {
|
||||
registeredTools.clear()
|
||||
}
|
||||
|
||||
/**
|
||||
* Disconnect from WebMCP without destroying the instance
|
||||
* Used when losing the torch to another browser
|
||||
*/
|
||||
export function disconnectWebMCP(): void {
|
||||
if (!webmcpInstance) {
|
||||
console.warn('[WebMCP] Instance not initialized')
|
||||
return
|
||||
}
|
||||
|
||||
if (!webmcpInstance.isConnected) {
|
||||
console.log('[WebMCP] Already disconnected')
|
||||
return
|
||||
}
|
||||
|
||||
if (typeof webmcpInstance.disconnect === 'function') {
|
||||
console.log('[WebMCP] Disconnecting...')
|
||||
webmcpInstance.disconnect()
|
||||
|
||||
// Update store immediately (event handler will also fire)
|
||||
const canvasStore = useCanvasStore()
|
||||
canvasStore.setConnected(false)
|
||||
canvasStore.setConnectionInfo(null)
|
||||
} else {
|
||||
console.warn('[WebMCP] disconnect method not available')
|
||||
}
|
||||
}
|
||||
|
||||
export function destroyWebMCP() {
|
||||
// Unsubscribe all event handlers
|
||||
for (const unsub of eventUnsubscribers) {
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
"version": "1.0.0",
|
||||
"description": "Dynamic canvas for Claude Code interaction",
|
||||
"scripts": {
|
||||
"kill-ports": "node -e \"const {execSync} = require('child_process'); [4101,4102,4103,4105,4106].forEach(p => { try { const pid = execSync('netstat -ano | findstr :' + p + ' | findstr LISTENING', {encoding:'utf8'}).split(/\\s+/).pop().trim(); if(pid) execSync('taskkill /PID ' + pid + ' /F', {stdio:'ignore'}); } catch(e){} }); console.log('Ports cleared');\"",
|
||||
"kill-ports": "node -e \"const {execSync} = require('child_process'); [4101,4102,4103,4105].forEach(p => { try { const pid = execSync('netstat -ano | findstr :' + p + ' | findstr LISTENING', {encoding:'utf8'}).split(/\\s+/).pop().trim(); if(pid) execSync('taskkill /PID ' + pid + ' /F', {stdio:'ignore'}); } catch(e){} }); console.log('Ports cleared');\"",
|
||||
"start": "bun run kill-ports && concurrently -n api,terminal,frontend -c blue,yellow,green \"cd server && bun --watch run index.ts\" \"cd server && bun run terminal.ts\" \"cd frontend && bun run dev --host\"",
|
||||
"start:api": "cd server && bun --watch run index.ts",
|
||||
"start:terminal": "cd server && bun run terminal.ts",
|
||||
|
||||
@@ -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$/, '')
|
||||
|
||||
@@ -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()
|
||||
}
|
||||
86
server/services/handlers/git-handler.ts
Normal file
86
server/services/handlers/git-handler.ts
Normal 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
|
||||
}
|
||||
}
|
||||
143
server/services/handlers/torch-handler.ts
Normal file
143
server/services/handlers/torch-handler.ts
Normal 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
|
||||
}
|
||||
109
server/services/sync-server.ts
Normal file
109
server/services/sync-server.ts
Normal 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()
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -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()
|
||||
|
||||
Reference in New Issue
Block a user