File size: 3,969 Bytes
4dcc016
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
import { useCallback, useEffect, useRef, useState } from 'react'
import {
  createOrAttachSession,
  openTerminalSocket,
  resizeTerminalSession,
  sendTerminalInput,
  stopTerminalSession,
} from '../api/terminal'

const BUFFER_LIMIT = 160000

function trimBuffer(text) {
  return text.length > BUFFER_LIMIT ? text.slice(-BUFFER_LIMIT) : text
}

export function useTerminalSession(jobId) {
  const [session, setSession] = useState(null)
  const [buffer, setBuffer] = useState('')
  const [connectionState, setConnectionState] = useState('connecting')
  const [error, setError] = useState('')
  const [lastOutputAt, setLastOutputAt] = useState(null)

  const socketRef = useRef(null)
  const resizeRef = useRef({ cols: null, rows: null })

  const attachSocket = useCallback((sessionId) => {
    if (socketRef.current) {
      socketRef.current.close()
    }

    const socket = openTerminalSocket(sessionId)
    socketRef.current = socket
    setConnectionState('connecting')

    socket.addEventListener('open', () => {
      setConnectionState('connected')
    })

    socket.addEventListener('message', (event) => {
      const payload = JSON.parse(event.data)

      if (payload.type === 'snapshot') {
        setSession(payload.session)
        setBuffer(payload.buffer || '')
        return
      }

      if (payload.type === 'output') {
        setLastOutputAt(Date.now())
        setBuffer((previous) => trimBuffer(previous + payload.data))
        return
      }

      if (payload.type === 'exit') {
        setSession((previous) =>
          previous
            ? {
                ...previous,
                status: payload.status,
                exit_code: payload.exit_code,
                finished_at: payload.finished_at,
              }
            : previous,
        )
      }
    })

    socket.addEventListener('close', () => {
      setConnectionState('disconnected')
    })

    socket.addEventListener('error', () => {
      setConnectionState('error')
    })
  }, [])

  const bootSession = useCallback(
    async (restart = false) => {
      try {
        setError('')
        const payload = await createOrAttachSession(jobId, { restart })
        setSession(payload.session)
        setBuffer(payload.buffer || '')
        attachSocket(payload.session.id)
      } catch (caughtError) {
        setError(caughtError.message)
        setConnectionState('error')
      }
    },
    [attachSocket, jobId],
  )

  useEffect(() => {
    const timeoutId = window.setTimeout(() => {
      void bootSession(false)
    }, 0)

    return () => {
      window.clearTimeout(timeoutId)
      if (socketRef.current) {
        socketRef.current.close()
      }
    }
  }, [bootSession])

  const restart = useCallback(() => bootSession(true), [bootSession])

  const stop = useCallback(async () => {
    if (!session?.id) {
      return
    }
    try {
      await stopTerminalSession(session.id)
    } catch (caughtError) {
      setError(caughtError.message)
    }
  }, [session])

  const sendInput = useCallback(
    async (value, appendNewline = true) => {
      if (!session?.id || !value.trim()) {
        return
      }
      try {
        await sendTerminalInput(session.id, value, appendNewline)
      } catch (caughtError) {
        setError(caughtError.message)
      }
    },
    [session],
  )

  const resize = useCallback(
    async (cols, rows) => {
      if (!session?.id) {
        return
      }

      const previous = resizeRef.current
      if (previous.cols === cols && previous.rows === rows) {
        return
      }
      resizeRef.current = { cols, rows }

      try {
        await resizeTerminalSession(session.id, cols, rows)
      } catch {
        // Ignore resize errors so rendering stays responsive.
      }
    },
    [session],
  )

  return {
    buffer,
    connectionState,
    error,
    lastOutputAt,
    restart,
    resize,
    sendInput,
    session,
    start: () => bootSession(false),
    stop,
  }
}