start terminal ui + logic

This commit is contained in:
Ishaan Dey
2024-04-28 20:06:47 -04:00
parent 9726e7c249
commit ec900d3d77
12 changed files with 322 additions and 56 deletions

View File

@ -6,6 +6,7 @@ import { Server } from "socket.io"
import { z } from "zod"
import { User } from "./types"
import { getSandboxFiles, renameFile, saveFile } from "./utils"
import { Pty } from "./terminal"
dotenv.config()
@ -19,6 +20,8 @@ const io = new Server(httpServer, {
},
})
const terminals: { [id: string]: Pty } = {}
const handshakeSchema = z.object({
userId: z.string(),
sandboxId: z.string(),
@ -76,6 +79,7 @@ io.on("connection", async (socket) => {
const file = sandboxFiles.fileData.find((f) => f.id === fileId)
if (!file) return
console.log("get file " + file.id + ": ", file.data.slice(0, 10) + "...")
callback(file.data)
})
@ -96,6 +100,26 @@ io.on("connection", async (socket) => {
await renameFile(fileId, newName, file.data)
})
socket.on("createTerminal", ({ id }: { id: string }) => {
console.log("creating terminal (" + id + ")")
terminals[id] = new Pty(socket, id)
})
socket.on("terminalData", ({ id, data }: { id: string; data: string }) => {
console.log(`Received data for terminal ${id}: ${data}`)
if (!terminals[id]) {
console.log("terminal not found")
console.log("terminals", terminals)
return
}
console.log(`Writing to terminal ${id}`)
terminals[id].write(data)
})
socket.on("disconnect", () => {})
})
httpServer.listen(port, () => {

View File

@ -0,0 +1,49 @@
import { spawn, IPty } from "node-pty"
import { Socket } from "socket.io"
import os from "os"
export class Pty {
socket: Socket
ptyProcess: IPty
shell: string
constructor(socket: Socket, id: string) {
this.socket = socket
this.shell = os.platform() === "win32" ? "cmd.exe" : "bash"
this.ptyProcess = spawn(this.shell, [], {
name: "xterm",
cols: 100,
cwd: `/temp`,
// env: process.env as { [key: string]: string },
})
this.ptyProcess.onData((data) => {
console.log("onData", data)
this.send(data)
})
// this.write("hello world")
}
write(data: string) {
console.log("writing data", data)
this.ptyProcess.write(data)
}
send(data: string) {
this.socket.emit("terminalResponse", {
data: Buffer.from(data, "utf-8"),
})
}
// kill() {
// console.log("killing terminal")
// if (os.platform() !== "win32") {
// this.ptyProcess.kill()
// return
// }
// }
}