MCPcopy Create free account
hub / github.com/tiann/hapi / useTerminalSocket

Function useTerminalSocket

web/src/hooks/useTerminalSocket.ts:37–231  ·  view source on GitHub ↗
(options: UseTerminalSocketOptions)

Source from the content-addressed store, hash-verified

35}
36
37export function useTerminalSocket(options: UseTerminalSocketOptions): {
38 state: TerminalConnectionState
39 connect: (cols: number, rows: number) => void
40 write: (data: string) => void
41 resize: (cols: number, rows: number) => void
42 disconnect: () => void
43 onOutput: (handler: (data: string) => void) => void
44 onExit: (handler: (code: number | null, signal: string | null) => void) => void
45} {
46 const [state, setState] = useState<TerminalConnectionState>({ status: 'idle' })
47 const socketRef = useRef<Socket | null>(null)
48 const outputHandlerRef = useRef<(data: string) => void>(() => {})
49 const exitHandlerRef = useRef<(code: number | null, signal: string | null) => void>(() => {})
50 const sessionIdRef = useRef(options.sessionId)
51 const terminalIdRef = useRef(options.terminalId)
52 const tokenRef = useRef(options.token)
53 const baseUrlRef = useRef(options.baseUrl)
54 const lastSizeRef = useRef<{ cols: number; rows: number } | null>(null)
55
56 useEffect(() => {
57 sessionIdRef.current = options.sessionId
58 terminalIdRef.current = options.terminalId
59 baseUrlRef.current = options.baseUrl
60 }, [options.sessionId, options.terminalId, options.baseUrl])
61
62 useEffect(() => {
63 tokenRef.current = options.token
64 const socket = socketRef.current
65 if (!socket) {
66 return
67 }
68 if (!options.token) {
69 if (socket.connected) {
70 socket.disconnect()
71 }
72 return
73 }
74 socket.auth = { token: options.token }
75 if (socket.connected) {
76 socket.disconnect()
77 socket.connect()
78 }
79 }, [options.token])
80
81 const isCurrentTerminal = useCallback((terminalId: string) => terminalId === terminalIdRef.current, [])
82
83 const emitCreate = useCallback((socket: Socket, size: { cols: number; rows: number }) => {
84 socket.emit('terminal:create', {
85 sessionId: sessionIdRef.current,
86 terminalId: terminalIdRef.current,
87 cols: size.cols,
88 rows: size.rows
89 })
90 }, [])
91
92 const setErrorState = useCallback((message: string) => {
93 setState({ status: 'error', error: message })
94 }, [])

Callers 1

TerminalPageFunction · 0.90

Calls 5

setStateFunction · 0.85
disconnectMethod · 0.65
connectMethod · 0.45
emitMethod · 0.45
onMethod · 0.45

Tested by

no test coverage detected