section 4: Phase 4: Frontend terminal client and xterm view

This commit is contained in:
Chris Scott committed 2026-10-03 01:24:03 -04:00
1 parent 13c29c635e
commit dc7cd2382f
11 files changed
+856

No files matched your search

@@ -0,0 +1,204 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { act, renderHook } from '@testing-library/react'
import { useTerminalSocket } from './useTerminalSocket'
class FakeWebSocket {
static CONNECTING = 0
static OPEN = 1
static CLOSING = 2
static CLOSED = 3
static instances: FakeWebSocket[] = []
url: string
binaryType = 'blob'
readyState = FakeWebSocket.CONNECTING
sent: string[] = []
onopen: ((event: Event) => void) | null = null
onmessage: ((event: MessageEvent) => void) | null = null
onclose: ((event: CloseEvent) => void) | null = null
onerror: ((event: Event) => void) | null = null
constructor(url: string) {
this.url = url
FakeWebSocket.instances.push(this)
}
send(data: string) {
this.sent.push(data)
}
close() {
this.readyState = FakeWebSocket.CLOSED
}
open() {
this.readyState = FakeWebSocket.OPEN
this.onopen?.(new Event('open'))
}
message(data: string | ArrayBuffer) {
this.onmessage?.({ data } as MessageEvent)
}
serverClose(code: number) {
this.readyState = FakeWebSocket.CLOSED
this.onclose?.({ code } as CloseEvent)
}
}
function metaFrame(cursor: number): ArrayBuffer {
const payload = new TextEncoder().encode(JSON.stringify({ cursor }))
const bytes = new Uint8Array(payload.length + 1)
bytes[0] = 0x00
bytes.set(payload, 1)
return bytes.buffer
}
function renderSocket(overrides: Partial<Parameters<typeof useTerminalSocket>[0]> = {}) {
return renderHook(() =>
useTerminalSocket({
repoId: 1,
directory: '/work/repo',
ptyID: 'pty-1',
onOutput: vi.fn(),
onExit: vi.fn(),
enabled: true,
...overrides,
}),
)
}
describe('useTerminalSocket', () => {
beforeEach(() => {
FakeWebSocket.instances = []
vi.stubGlobal('WebSocket', FakeWebSocket)
vi.useFakeTimers()
})
afterEach(() => {
vi.useRealTimers()
vi.unstubAllGlobals()
})
it('includes the directory in the connection url', () => {
renderSocket()
const url = new URL(FakeWebSocket.instances[0].url)
expect(url.pathname).toBe('/api/repos/1/terminals/pty-1/connect')
expect(url.searchParams.get('directory')).toBe('/work/repo')
})
it('accumulates the cursor and sends it when reconnecting after 1006', () => {
renderSocket()
const first = FakeWebSocket.instances[0]
act(() => {
first.open()
first.message(metaFrame(5))
first.message('abc')
})
act(() => {
first.serverClose(1006)
})
expect(FakeWebSocket.instances).toHaveLength(1)
act(() => {
vi.advanceTimersByTime(1000)
})
expect(FakeWebSocket.instances).toHaveLength(2)
const second = new URL(FakeWebSocket.instances[1].url)
expect(second.searchParams.get('cursor')).toBe('8')
expect(second.searchParams.get('directory')).toBe('/work/repo')
})
it('calls onExit without reconnecting on close code 4404', () => {
const onExit = vi.fn()
renderSocket({ onExit })
act(() => {
FakeWebSocket.instances[0].serverClose(4404)
})
act(() => {
vi.advanceTimersByTime(60000)
})
expect(onExit).toHaveBeenCalledTimes(1)
expect(FakeWebSocket.instances).toHaveLength(1)
})
it('exhausts the retry budget when upstream connections keep failing after open', () => {
const { result } = renderSocket()
const delays = [1000, 2000, 5000, 5000, 5000]
for (const delay of delays) {
const socket = FakeWebSocket.instances[FakeWebSocket.instances.length - 1]
act(() => {
socket.open()
socket.serverClose(1011)
})
expect(result.current.status).toBe('reconnecting')
act(() => {
vi.advanceTimersByTime(delay)
})
}
const finalSocket = FakeWebSocket.instances[FakeWebSocket.instances.length - 1]
act(() => {
finalSocket.open()
finalSocket.serverClose(1011)
})
expect(result.current.status).toBe('closed')
expect(FakeWebSocket.instances).toHaveLength(6)
act(() => {
vi.advanceTimersByTime(60000)
})
expect(FakeWebSocket.instances).toHaveLength(6)
})
it('resets the retry budget only after a healthy upstream session', () => {
const { result } = renderSocket()
act(() => {
FakeWebSocket.instances[0].open()
FakeWebSocket.instances[0].message(metaFrame(0))
FakeWebSocket.instances[0].serverClose(1011)
})
act(() => {
vi.advanceTimersByTime(1000)
})
expect(FakeWebSocket.instances).toHaveLength(2)
act(() => {
FakeWebSocket.instances[1].open()
FakeWebSocket.instances[1].serverClose(1011)
})
expect(result.current.status).toBe('reconnecting')
act(() => {
vi.advanceTimersByTime(2000)
})
expect(FakeWebSocket.instances).toHaveLength(3)
})
it('forwards send to the open socket', () => {
const { result } = renderSocket()
const socket = FakeWebSocket.instances[0]
act(() => {
socket.open()
})
act(() => {
result.current.send('ls\n')
})
expect(socket.sent).toContain('ls\n')
})
it('does not connect when disabled', () => {
renderSocket({ enabled: false })
expect(FakeWebSocket.instances).toHaveLength(0)
})
})
+135
View File
@@ -0,0 +1,135 @@
import { useCallback, useEffect, useRef, useState } from 'react'
import { TerminalFrameDecoder } from '@/lib/terminal-protocol'
import { toWebSocketUrl } from '@/lib/websocket-url'
export type TerminalSocketStatus = 'connecting' | 'open' | 'reconnecting' | 'closed'
export interface UseTerminalSocketOptions {
repoId: number
directory: string | undefined
ptyID: string
onOutput: (text: string) => void
onExit: () => void
enabled: boolean
}
const RECONNECT_DELAYS_MS = [1000, 2000, 5000, 5000, 5000]
const TERMINAL_CLOSE_CODES = new Set([1000, 4404])
function buildSocketUrl(
repoId: number,
ptyID: string,
directory: string | undefined,
cursor: number | undefined,
): string {
const params = new URLSearchParams()
if (directory !== undefined) params.set('directory', directory)
if (cursor !== undefined) params.set('cursor', String(cursor))
const query = params.toString()
return toWebSocketUrl(
`/api/repos/${repoId}/terminals/${encodeURIComponent(ptyID)}/connect${query ? `?${query}` : ''}`,
)
}
export function useTerminalSocket({
repoId,
directory,
ptyID,
onOutput,
onExit,
enabled,
}: UseTerminalSocketOptions) {
const socketRef = useRef<WebSocket | null>(null)
const cursorRef = useRef<number | undefined>(undefined)
const onOutputRef = useRef(onOutput)
const onExitRef = useRef(onExit)
onOutputRef.current = onOutput
onExitRef.current = onExit
const [status, setStatus] = useState<TerminalSocketStatus>(enabled ? 'connecting' : 'closed')
const send = useCallback((data: string) => {
const socket = socketRef.current
if (socket && socket.readyState === WebSocket.OPEN) {
socket.send(data)
}
}, [])
useEffect(() => {
if (!enabled) {
setStatus('closed')
return
}
let disposed = false
let attempt = 0
let reconnectTimer: ReturnType<typeof setTimeout> | null = null
const decoder = new TerminalFrameDecoder()
cursorRef.current = undefined
const connect = () => {
if (disposed) return
setStatus(attempt === 0 ? 'connecting' : 'reconnecting')
const socket = new WebSocket(buildSocketUrl(repoId, ptyID, directory, cursorRef.current))
socket.binaryType = 'arraybuffer'
socketRef.current = socket
socket.onopen = () => {
if (disposed || socketRef.current !== socket) return
setStatus('open')
}
socket.onmessage = (event) => {
if (disposed || socketRef.current !== socket) return
const frame = decoder.decode(event.data as string | ArrayBuffer)
if (frame.type === 'cursor') {
attempt = 0
cursorRef.current = frame.cursor
return
}
cursorRef.current = (cursorRef.current ?? 0) + frame.text.length
onOutputRef.current(frame.text)
}
socket.onclose = (event) => {
if (disposed || socketRef.current !== socket) return
socketRef.current = null
if (TERMINAL_CLOSE_CODES.has(event.code)) {
setStatus('closed')
onExitRef.current()
return
}
if (attempt >= RECONNECT_DELAYS_MS.length) {
setStatus('closed')
return
}
const delay = RECONNECT_DELAYS_MS[attempt]
attempt += 1
setStatus('reconnecting')
reconnectTimer = setTimeout(connect, delay)
}
}
connect()
return () => {
disposed = true
if (reconnectTimer) clearTimeout(reconnectTimer)
const socket = socketRef.current
socketRef.current = null
if (socket) {
socket.onopen = null
socket.onmessage = null
socket.onclose = null
socket.onerror = null
socket.close()
}
}
}, [repoId, directory, ptyID, enabled])
return { send, status }
}