VibeTunnel Web Architecture Specification
This document provides a comprehensive map of the VibeTunnel web application architecture, including server components, client structure, API specifications, and protocol details. Updated: 2025-07-01Key Files Quick Reference
Server Core
- Entry Point:
src/server/server.ts:912
-startVibeTunnelServer()
- App Creation:
src/server/server.ts:330
-createApp()
- Configuration:
src/server/server.ts:57
-Config
interface - CLI Entry:
src/server/cli.ts:51-56
-vibetunnel fwd
command
Authentication
- Service:
src/server/services/auth-service.ts:144-271
- SSH key verification - Middleware:
src/server/middleware/auth.ts:20-105
- JWT validation - Routes:
src/server/routes/auth.ts:20-178
- Auth endpoints
Session Management
- PTY Manager:
src/server/pty/pty-manager.ts:57
- Session Map - Session Manager:
src/server/pty/session-manager.ts:40-141
- Session lifecycle - Routes:
src/server/routes/sessions.ts:134-1252
- Session API
Real-time Communication
- Binary Buffer:
src/server/services/terminal-manager.ts:378-574
- Buffer encoding - WebSocket Server:
src/server/services/buffer-aggregator.ts:44-344
- Buffer streaming - Input Handler:
src/server/routes/websocket-input.ts:156-164
- Input protocol
Client Core
- Entry Point:
src/client/app-entry.ts:1-28
- App initialization - Main Component:
src/client/app.ts:44-1355
-<vibetunnel-app>
- Terminal:
src/client/components/terminal.ts:23-1567
- xterm.js wrapper
Server Architecture
Main Server (src/server/server.ts
)
The server provides a comprehensive API for terminal session management with support for distributed deployments.
Configuration Options:
port
: Server port (default: 4020)bind
: Bind address (default: 127.0.0.1)isHQMode
: Run as headquarters serverhqUrl/hqUsername/hqPassword
: Remote server registrationenableSSHKeys
: Enable SSH key authenticationnoAuth
: Disable all authentication
- Authentication (JWT + SSH keys)
- Session management (PTY processes)
- WebSocket communication (binary buffers + input)
- File system operations
- Push notifications
- Activity monitoring
Authentication System
Supported Methods:- SSH Key Authentication (
src/server/routes/auth.ts:52
)- Challenge-response with Ed25519 signatures
- Verifies against
~/.ssh/authorized_keys
- Password Authentication (
src/server/routes/auth.ts:101
)- PAM authentication or environment variables
- Bearer Token (HQ mode)
- For server-to-server communication
- Local Bypass (optional)
- Localhost connections with optional token
- Client requests challenge from
/api/auth/challenge
- Server generates random challenge
- Client signs challenge and sends to
/api/auth/ssh-key
- Server verifies signature and returns JWT token
Session Management
Session Lifecycle:-
Creation (
src/server/routes/sessions.ts:134
):- Spawns PTY process using node-pty
- Creates session directory in
~/.vibetunnel/control/
- Saves metadata to
session.json
-
Tracking:
- In-memory:
PtyManager.sessions
Map - On-disk: Session directories with stdout/stdin files
- In-memory:
-
Cleanup (
src/server/pty/session-manager.ts:297
):- Automatic cleanup of exited sessions
- 5-minute cleanup interval
- Zombie process detection
Client Architecture
Component Hierarchy
State Management
- Component-level state using LitElement’s
@state()
decorator - localStorage for persistent data (auth tokens, preferences)
- Event-driven communication between components
- No global state management library
Services
AuthClient (src/client/services/auth-client.ts
):
- Manages authentication state
- Handles SSH key and password auth
- Stores tokens in localStorage
src/client/services/buffer-subscription-service.ts
):
- WebSocket connection for binary terminal buffers
- Automatic reconnection with exponential backoff
- Multiplexed subscriptions per session
src/client/services/websocket-input-client.ts
):
- Low-latency input transmission
- Fire-and-forget protocol
- Per-session connections
API Specification
REST Endpoints
Sessions
GET /api/sessions
- List all sessionsPOST /api/sessions
- Create new sessionGET /api/sessions/:id
- Get session infoDELETE /api/sessions/:id
- Kill sessionPOST /api/sessions/:id/input
- Send inputPOST /api/sessions/:id/resize
- Resize terminalGET /api/sessions/:id/stream
- SSE output streamGET /api/sessions/:id/text
- Get text outputGET /api/sessions/:id/buffer
- Get binary bufferGET /api/sessions/activity
- Get all activity
Authentication
POST /api/auth/challenge
- Request challengePOST /api/auth/ssh-key
- SSH key authPOST /api/auth/password
- Password authGET /api/auth/verify
- Verify tokenGET /api/auth/config
- Get auth config
HQ Mode (Distributed)
GET /api/remotes
- List remote serversPOST /api/remotes/register
- Register remoteDELETE /api/remotes/:id
- Unregister remote
Git Integration
GET /api/worktrees
- List worktreesPOST /api/worktrees
- Create worktreePOST /api/worktrees/follow
- Enable/disable follow modeGET /api/worktrees/follow
- Get follow mode statusPOST /api/git/events
- Git hook notifications
WebSocket Protocols
Binary Buffer Protocol (/buffers
)
Connection: WebSocket with Bearer token authentication
Client → Server Messages (JSON):
Input Protocol (/ws/input
)
Connection: ws://host/ws/input?sessionId=X&token=Y
Message Format:
- Regular text: Sent as-is
- Special keys:
\x00key_name\x00
Server-Sent Events (SSE)
Session Output Stream (/api/sessions/:id/stream
)
Uses asciinema cast v2 format:
fwd.ts Application
Thefwd.ts
tool (src/server/fwd.ts
) wraps any command in a VibeTunnel session:
Usage: pnpm exec tsx src/fwd.ts [options] <command> [args...]
Options:
--session-id <id>
: Use specific session ID--title-mode <mode>
: none|filter|static|dynamic--update-title <title>
: Update existing session title
- Auto-detects Claude AI and enables dynamic titles
- Forwards stdin/stdout through PTY infrastructure
- Creates sessions accessible via web interface
- Activity detection for intelligent status updates
src/server/pty/socket-protocol.ts
):
HQ Mode & Distributed Architecture
Remote Registration
- Remote servers register with HQ using bearer tokens
- HQ maintains registry of all remote servers
- Health checks every 15 seconds
- Automatic session discovery
Request Routing
- HQ checks session ownership via registry
- Forwards API requests to appropriate remote
- Proxies SSE streams transparently
- Multiplexes WebSocket connections
High Availability
- Graceful degradation on remote failure
- Continues serving local sessions
- Automatic reconnection for WebSocket streams
- Session ownership tracking for reliability
Activity Tracking
Activity Monitor (src/server/services/activity-monitor.ts
)
- Monitors stdout file changes (100ms intervals)
- Marks sessions inactive after 500ms of no output
- Persists activity to
activity.json
- Provides real-time activity status
Activity Detection (src/server/utils/activity-detector.ts
)
- App-specific status detection (Claude AI)
- Filters prompt-only output
- Dynamic title updates based on activity
- 5-second activity timeout
Additional Features
Push Notifications
- Web Push API with VAPID authentication
- Bell event notifications from terminal
- Service worker for offline support
- Process context in notifications
File Browser
- Full filesystem browsing with Git status
- Monaco Editor for code preview
- Git diff visualization
- Image preview support
SSH Key Management
- Browser-based Ed25519 key generation
- Import/export functionality
- Password-protected key support
- Web Crypto API integration
Native Terminal Spawning (macOS)
- Unix socket at
/tmp/vibetunnel-terminal.sock
- Requests native Terminal.app windows
- Falls back to web terminal
Performance Optimizations
- Binary buffer compression (empty row encoding)
- Fire-and-forget input protocol
- Debounced buffer notifications (50ms)
- Efficient cell encoding with bit-packing
Development Commands
Git Follow Mode
Git follow mode creates an intelligent synchronization between a main repository and a specific worktree, enabling seamless development workflows where agents work in worktrees while developers maintain their IDE and server setups in the main repository. Key Components:- Git Hooks (
src/server/utils/git-hooks.ts
): Manages post-commit, post-checkout, post-merge hooks - Git Event Handler (
src/server/routes/git.ts:186-482
): Processes git events and handles synchronization - Socket API (
src/server/api-socket-server.ts:217-267
): Socket-based follow mode control - CLI Integration (
web/bin/vt
): Smart command handling with path/branch detection
- Single config option:
vibetunnel.followWorktree
stores the worktree path being followed - Config is stored in the main repository’s
.git/config
- Follow mode is active when this config contains a valid worktree path
- Worktree → Main (Primary): Branch switches, commits, and checkouts sync to main repo
- Main → Worktree (Limited): Only commits sync; branch switches auto-unfollow
- Auto-unfollow: Switching branches in main repo disables follow mode
- Hooks installed in BOTH main repository and worktree
- Hooks execute
vt git event
which notifies server via socket API - Server processes events based on source (main vs worktree)
- Existing hooks are preserved with
.vtbak
extension
- Git event occurs (checkout, commit, merge)
- Hook executes
vt git event
- CLI sends event via socket to server
- Server determines sync action based on event source
- Appropriate git commands executed to maintain sync
Architecture Principles
- Modular Design: Clear separation between auth, sessions, and real-time communication
- Scalability: Horizontal scaling via HQ mode and remote servers
- Reliability: Automatic reconnection, health checks, graceful degradation
- Performance: Binary protocols, compression, minimal latency
- Security: Multiple auth methods, JWT tokens, secure WebSocket connections