| 111 | } |
| 112 | |
| 113 | export async function create(input: CreateInput) { |
| 114 | const id = Identifier.create("pty", false) |
| 115 | const command = input.command || Shell.preferred() |
| 116 | const args = input.args || [] |
| 117 | const cwd = input.cwd || Instance.directory |
| 118 | const env = { ...process.env, ...input.env } as Record<string, string> |
| 119 | log.info("creating session", { id, cmd: command, args, cwd }) |
| 120 | |
| 121 | const spawn = await pty() |
| 122 | const ptyProcess = spawn(command, args, { |
| 123 | name: "xterm-256color", |
| 124 | cwd, |
| 125 | env, |
| 126 | }) |
| 127 | const info = { |
| 128 | id, |
| 129 | title: input.title || `Terminal ${id.slice(-4)}`, |
| 130 | command, |
| 131 | args, |
| 132 | cwd, |
| 133 | status: "running", |
| 134 | pid: ptyProcess.pid, |
| 135 | } as const |
| 136 | const session: ActiveSession = { |
| 137 | info, |
| 138 | process: ptyProcess, |
| 139 | buffer: "", |
| 140 | subscribers: new Set(), |
| 141 | } |
| 142 | state().set(id, session) |
| 143 | ptyProcess.onData((data) => { |
| 144 | if (session.subscribers.size === 0) { |
| 145 | session.buffer += data |
| 146 | return |
| 147 | } |
| 148 | for (const ws of session.subscribers) { |
| 149 | if (ws.readyState === 1) { |
| 150 | ws.send(data) |
| 151 | } |
| 152 | } |
| 153 | }) |
| 154 | ptyProcess.onExit(({ exitCode }) => { |
| 155 | log.info("session exited", { id, exitCode }) |
| 156 | session.info.status = "exited" |
| 157 | Bus.publish(Event.Exited, { id, exitCode }) |
| 158 | state().delete(id) |
| 159 | }) |
| 160 | Bus.publish(Event.Created, { info }) |
| 161 | return info |
| 162 | } |
| 163 | |
| 164 | export async function update(id: string, input: UpdateInput) { |
| 165 | const session = state().get(id) |