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
46 changes: 46 additions & 0 deletions server/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -1396,13 +1396,35 @@ function handleChatConnection(ws, request) {
// Add to connected clients for project updates
connectedClients.add(ws);

// Heartbeat: detect dead connections (mobile backgrounding kills sockets silently)
let isAlive = true;
ws.on('pong', () => { isAlive = true; });
const heartbeatInterval = setInterval(() => {
if (!isAlive) {
console.log('[INFO] Chat WebSocket heartbeat failed, terminating');
clearInterval(heartbeatInterval);
ws.terminate();
return;
}
isAlive = false;
try { ws.ping(); } catch (_) { /* socket already closing */ }
}, 30000);

// Wrap WebSocket with writer for consistent interface with SSEStreamWriter
const writer = new WebSocketWriter(ws, request?.user?.id ?? request?.user?.userId ?? null);

ws.on('message', async (message) => {
try {
const data = JSON.parse(message);

// Application-level ping for foreground-resume checks
if (data.type === 'ping') {
if (ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({ type: 'pong', timestamp: Date.now() }));
}
return;
}

if (data.type === 'claude-command') {
console.log('[DEBUG] User message:', data.command || '[Continue/Resume]');
console.log('📁 Project:', data.options?.projectPath || 'Unknown');
Expand Down Expand Up @@ -1532,6 +1554,7 @@ function handleChatConnection(ws, request) {

ws.on('close', () => {
console.log('🔌 Chat client disconnected');
clearInterval(heartbeatInterval);
// Remove from connected clients
connectedClients.delete(ws);
});
Expand All @@ -1545,11 +1568,33 @@ function handleShellConnection(ws) {
let urlDetectionBuffer = '';
const announcedAuthUrls = new Set();

// Heartbeat: detect dead connections from mobile backgrounding
let isAlive = true;
ws.on('pong', () => { isAlive = true; });
const heartbeatInterval = setInterval(() => {
if (!isAlive) {
console.log('[INFO] Shell WebSocket heartbeat failed, terminating');
clearInterval(heartbeatInterval);
ws.terminate();
return;
}
isAlive = false;
try { ws.ping(); } catch (_) { /* socket already closing */ }
}, 30000);

ws.on('message', async (message) => {
try {
const data = JSON.parse(message);
console.log('📨 Shell message received:', data.type);

// Application-level ping for foreground-resume checks
if (data.type === 'ping') {
if (ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify({ type: 'pong', timestamp: Date.now() }));
}
return;
}

if (data.type === 'init') {
const projectPath = data.projectPath || process.cwd();
const sessionId = data.sessionId;
Expand Down Expand Up @@ -1873,6 +1918,7 @@ function handleShellConnection(ws) {

ws.on('close', () => {
console.log('🔌 Shell client disconnected');
clearInterval(heartbeatInterval);

if (ptySessionKey) {
const session = ptySessionsMap.get(ptySessionKey);
Expand Down
4 changes: 4 additions & 0 deletions src/components/app/AppContent.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { useWebSocket } from '../../contexts/WebSocketContext';
import { useDeviceSettings } from '../../hooks/useDeviceSettings';
import { useSessionProtection } from '../../hooks/useSessionProtection';
import { useProjectsState } from '../../hooks/useProjectsState';
import { useWakeLock } from '../../hooks/useWakeLock';

export default function AppContent() {
const navigate = useNavigate();
Expand All @@ -26,6 +27,9 @@ export default function AppContent() {
replaceTemporarySession,
} = useSessionProtection();

// Keep screen awake on mobile while an agent session is processing
useWakeLock(isMobile && processingSessions.size > 0);

const {
selectedProject,
selectedSession,
Expand Down
55 changes: 54 additions & 1 deletion src/components/shell/hooks/useShellConnection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,12 @@ import type { Terminal } from '@xterm/xterm';
import type { Project, ProjectSession } from '../../../types/app';
import { TERMINAL_INIT_DELAY_MS } from '../constants/constants';
import { getShellWebSocketUrl, parseShellMessage, sendSocketMessage } from '../utils/socket';
import { useAppLifecycle } from '../../../hooks/useAppLifecycle';

const ANSI_ESCAPE_REGEX =
/(?:\u001B\[[0-?]*[ -/]*[@-~]|\u009B[0-?]*[ -/]*[@-~]|\u001B\][^\u0007\u001B]*(?:\u0007|\u001B\\)|\u009D[^\u0007\u009C]*(?:\u0007|\u009C)|\u001B[PX^_][^\u001B]*\u001B\\|[\u0090\u0098\u009E\u009F][^\u009C]*\u009C|\u001B[@-Z\\-_])/g;
const PROCESS_EXIT_REGEX = /Process exited with code (\d+)/;
const SHELL_RECONNECT_DELAY_MS = 5000;

type UseShellConnectionOptions = {
wsRef: MutableRefObject<WebSocket | null>;
Expand Down Expand Up @@ -54,6 +56,10 @@ export function useShellConnection({
const [isConnected, setIsConnected] = useState(false);
const [isConnecting, setIsConnecting] = useState(false);
const connectingRef = useRef(false);
const wasConnectedRef = useRef(false);
const shouldReconnectRef = useRef(true);
const reconnectTimeoutRef = useRef<NodeJS.Timeout | null>(null);
const { onForeground } = useAppLifecycle();

const handleProcessCompletion = useCallback(
(output: string) => {
Expand Down Expand Up @@ -165,7 +171,19 @@ export function useShellConnection({
setIsConnected(false);
setIsConnecting(false);
connectingRef.current = false;
clearTerminalScreen();

if (!shouldReconnectRef.current) return;

// Don't clear terminal — server will replay buffered output on reconnect.
// Track that we were connected so foreground resume can auto-reconnect.
wasConnectedRef.current = true;

// Auto-reconnect after delay (with jitter)
const jitter = Math.random() * 1000;
reconnectTimeoutRef.current = setTimeout(() => {
if (wsRef.current?.readyState === WebSocket.OPEN) return;
connectWebSocket();
}, SHELL_RECONNECT_DELAY_MS + jitter);
};

socket.onerror = () => {
Expand Down Expand Up @@ -200,12 +218,19 @@ export function useShellConnection({
return;
}

shouldReconnectRef.current = true;
connectingRef.current = true;
setIsConnecting(true);
connectWebSocket(true);
}, [connectWebSocket, isConnected, isConnecting, isInitialized]);

const disconnectFromShell = useCallback(() => {
shouldReconnectRef.current = false;
if (reconnectTimeoutRef.current) {
clearTimeout(reconnectTimeoutRef.current);
reconnectTimeoutRef.current = null;
}
wasConnectedRef.current = false;
closeSocket();
clearTerminalScreen();
setIsConnected(false);
Expand All @@ -222,6 +247,34 @@ export function useShellConnection({
connectToShell();
}, [autoConnect, connectToShell, isConnected, isConnecting, isInitialized]);

// Foreground resume: auto-reconnect if we were previously connected
useEffect(() => {
const cleanup = onForeground(() => {
if (!wasConnectedRef.current) return;
const ws = wsRef.current;
if (ws && ws.readyState === WebSocket.OPEN) return;

// Cancel any pending reconnect timer and connect immediately
if (reconnectTimeoutRef.current) {
clearTimeout(reconnectTimeoutRef.current);
reconnectTimeoutRef.current = null;
}
console.log('[Shell] Foreground resume: reconnecting to shell');
connectWebSocket();
});

return cleanup;
}, [onForeground, connectWebSocket, wsRef]);

// Clean up reconnect timer on unmount
useEffect(() => {
return () => {
if (reconnectTimeoutRef.current) {
clearTimeout(reconnectTimeoutRef.current);
}
};
}, []);

return {
isConnected,
isConnecting,
Expand Down
Loading