* Wire PTY → scrollback + WebSocket. * Called once per session lifetime (idempotent via `wiredPtys` guard).
(token: string, pty: IPty)
| 234 | * Called once per session lifetime (idempotent via `wiredPtys` guard). |
| 235 | */ |
| 236 | private wirePtyEvents(token: string, pty: IPty): void { |
| 237 | if (this.wiredPtys.has(token)) return; |
| 238 | this.wiredPtys.add(token); |
| 239 | |
| 240 | const session = this.store.get(token); |
| 241 | if (!session) return; |
| 242 | |
| 243 | pty.onData((data: string) => { |
| 244 | // Always capture to scrollback for future replay |
| 245 | session.scrollback.write(data); |
| 246 | // Forward to the currently attached WebSocket, if any |
| 247 | const ws = session.ws; |
| 248 | if (ws && ws.readyState === 1 /* OPEN */) { |
| 249 | ws.send(data); |
| 250 | } |
| 251 | }); |
| 252 | |
| 253 | pty.onExit(({ exitCode, signal }) => { |
| 254 | this.wiredPtys.delete(token); |
| 255 | console.log( |
| 256 | `[session ${token.slice(0, 8)}] PTY exited: code=${exitCode}, signal=${signal}`, |
| 257 | ); |
| 258 | const ws = session.ws; |
| 259 | if (ws && ws.readyState === 1 /* OPEN */) { |
| 260 | ws.send(JSON.stringify({ type: "exit", exitCode, signal })); |
| 261 | ws.close(1000, "PTY exited"); |
| 262 | } |
| 263 | this.store.destroy(token); |
| 264 | }); |
| 265 | } |
| 266 | |
| 267 | /** |
| 268 | * Wire WebSocket → PTY (input, resize, ping). |