@bigmistqke/whiteboard 0.0.0-stage → 0.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +628 -2
- package/bin/whiteboard.ts +488 -0
- package/dist/_virtual/_@oxc-project_runtime@0.156.0/helpers/esm/taggedTemplateLiteral.js +5 -0
- package/dist/bin/whiteboard.js +542 -0
- package/dist/client/runtime.js +544 -0
- package/dist/define.js +7 -0
- package/dist/plugins/callout/README.md +13 -0
- package/dist/plugins/callout/index.js +27 -0
- package/dist/plugins/callout/style.css +12 -0
- package/dist/plugins/chat/README.md +46 -0
- package/dist/plugins/chat/client.js +3 -0
- package/dist/plugins/chat/index.js +47 -0
- package/dist/plugins/chat/style.css +24 -0
- package/dist/plugins/claude-code/index.js +120 -0
- package/dist/plugins/code/README.md +42 -0
- package/dist/plugins/code/diff.js +65 -0
- package/dist/plugins/code/index.js +77 -0
- package/dist/plugins/code/style.css +29 -0
- package/dist/plugins/comments/client.js +10 -0
- package/dist/plugins/comments/index.js +54 -0
- package/dist/plugins/comments/style.css +40 -0
- package/dist/plugins/details/README.md +17 -0
- package/dist/plugins/details/index.js +17 -0
- package/dist/plugins/details/style.css +3 -0
- package/dist/plugins/forge/README.md +12 -0
- package/dist/plugins/forge/index.js +83 -0
- package/dist/plugins/form/README.md +111 -0
- package/dist/plugins/form/index.js +102 -0
- package/dist/plugins/form/style.css +41 -0
- package/dist/plugins/gallery/README.md +30 -0
- package/dist/plugins/gallery/client.js +1 -0
- package/dist/plugins/gallery/index.js +74 -0
- package/dist/plugins/gallery/style.css +27 -0
- package/dist/plugins/grid/README.md +33 -0
- package/dist/plugins/grid/index.js +33 -0
- package/dist/plugins/grid/style.css +25 -0
- package/dist/plugins/iframe/README.md +18 -0
- package/dist/plugins/iframe/client.js +1 -0
- package/dist/plugins/iframe/index.js +40 -0
- package/dist/plugins/iframe/style.css +29 -0
- package/dist/plugins/index.js +30 -0
- package/dist/plugins/mermaid/README.md +21 -0
- package/dist/plugins/mermaid/index.js +35 -0
- package/dist/plugins/mermaid/style.css +16 -0
- package/dist/plugins/quiet/README.md +26 -0
- package/dist/plugins/quiet/index.js +17 -0
- package/dist/plugins/terminal/client.js +41 -0
- package/dist/plugins/terminal/host.js +332 -0
- package/dist/plugins/terminal/index.js +171 -0
- package/dist/plugins/terminal/modes.js +32 -0
- package/dist/plugins/terminal/server.js +256 -0
- package/dist/plugins/terminal/sizes.js +57 -0
- package/dist/plugins/terminal/style.css +357 -0
- package/dist/solid/index.js +36 -0
- package/dist/src/auth.js +54 -0
- package/dist/src/client/page/base.css +295 -0
- package/dist/src/client/page/main.js +1228 -0
- package/dist/src/config.js +76 -0
- package/dist/src/events.js +183 -0
- package/dist/src/html.js +34 -0
- package/dist/src/icons.js +6 -0
- package/dist/src/load.js +77 -0
- package/dist/src/loader.js +126 -0
- package/dist/src/package.js +33 -0
- package/dist/src/pages/blocks.js +50 -0
- package/dist/src/pages/index.js +15 -0
- package/dist/src/pages/markdown.js +410 -0
- package/dist/src/pages/render.js +311 -0
- package/dist/src/plugins.js +238 -0
- package/dist/src/running.js +24 -0
- package/dist/src/serve.js +71 -0
- package/dist/src/server.js +725 -0
- package/dist/src/status.js +71 -0
- package/package.json +131 -4
- package/plugins/callout/README.md +13 -0
- package/plugins/callout/index.ts +25 -0
- package/plugins/callout/style.css +12 -0
- package/plugins/chat/README.md +46 -0
- package/plugins/chat/autosize.ts +101 -0
- package/plugins/chat/client.tsx +93 -0
- package/plugins/chat/index.ts +61 -0
- package/plugins/chat/style.css +24 -0
- package/plugins/claude-code/index.ts +136 -0
- package/plugins/code/README.md +42 -0
- package/plugins/code/diff.ts +64 -0
- package/plugins/code/index.ts +94 -0
- package/plugins/code/style.css +29 -0
- package/plugins/comments/client.ts +492 -0
- package/plugins/comments/index.ts +54 -0
- package/plugins/comments/style.css +40 -0
- package/plugins/details/README.md +17 -0
- package/plugins/details/index.ts +21 -0
- package/plugins/details/style.css +3 -0
- package/plugins/forge/README.md +12 -0
- package/plugins/forge/index.ts +71 -0
- package/plugins/form/README.md +111 -0
- package/plugins/form/index.ts +104 -0
- package/plugins/form/style.css +41 -0
- package/plugins/gallery/README.md +30 -0
- package/plugins/gallery/client.tsx +64 -0
- package/plugins/gallery/index.ts +67 -0
- package/plugins/gallery/style.css +27 -0
- package/plugins/grid/README.md +33 -0
- package/plugins/grid/index.ts +36 -0
- package/plugins/grid/style.css +25 -0
- package/plugins/iframe/README.md +18 -0
- package/plugins/iframe/client.ts +46 -0
- package/plugins/iframe/index.ts +54 -0
- package/plugins/iframe/style.css +29 -0
- package/plugins/index.ts +21 -0
- package/plugins/mermaid/README.md +21 -0
- package/plugins/mermaid/index.ts +40 -0
- package/plugins/mermaid/style.css +16 -0
- package/plugins/quiet/README.md +26 -0
- package/plugins/quiet/index.ts +27 -0
- package/plugins/terminal/client.ts +317 -0
- package/plugins/terminal/host.ts +326 -0
- package/plugins/terminal/index.ts +138 -0
- package/plugins/terminal/modes.ts +30 -0
- package/plugins/terminal/server.ts +215 -0
- package/plugins/terminal/sizes.ts +60 -0
- package/plugins/terminal/style.css +71 -0
- package/skills/whiteboard/SKILL.md +302 -0
- package/solid/index.tsx +59 -0
- package/src/auth.ts +66 -0
- package/src/client/forms.ts +185 -0
- package/src/client/markdown.ts +36 -0
- package/src/client/page/base.css +295 -0
- package/src/client/page/elsewhere.ts +70 -0
- package/src/client/page/fresh.ts +205 -0
- package/src/client/page/live.ts +30 -0
- package/src/client/page/main.ts +272 -0
- package/src/client/page/orphans.ts +46 -0
- package/src/client/page/sort.ts +38 -0
- package/src/client/page/theme.ts +32 -0
- package/src/client/page/view.ts +9 -0
- package/src/client/page/waiting.ts +182 -0
- package/src/client/read.ts +73 -0
- package/src/client/runtime.ts +183 -0
- package/src/client/toast.ts +25 -0
- package/src/config.ts +96 -0
- package/src/define.ts +612 -0
- package/src/events.ts +218 -0
- package/src/html.ts +40 -0
- package/src/icons.ts +8 -0
- package/src/load.ts +89 -0
- package/src/loader.ts +112 -0
- package/src/package.ts +39 -0
- package/src/pages/blocks.ts +70 -0
- package/src/pages/index.ts +42 -0
- package/src/pages/markdown.ts +364 -0
- package/src/pages/render.ts +233 -0
- package/src/plugins.ts +197 -0
- package/src/running.ts +22 -0
- package/src/serve.ts +52 -0
- package/src/server.ts +667 -0
- package/src/status.ts +113 -0
|
@@ -0,0 +1,326 @@
|
|
|
1
|
+
// The terminal's host: a small process of its own that runs the sessions, so they outlive the page
|
|
2
|
+
// server. The server starts it (detached, like the server itself) the first time a session starts,
|
|
3
|
+
// and talks to it over a Unix socket; a restarted server connects again and finds the sessions as
|
|
4
|
+
// they were.
|
|
5
|
+
//
|
|
6
|
+
// node terminal/host.ts <project dir> <socket path>
|
|
7
|
+
//
|
|
8
|
+
// Each session is a program in a pseudo-terminal (node-pty), followed by a headless terminal that
|
|
9
|
+
// keeps its screen; the drawer shows them as tabs. A session has an id ('1', '2', …). One JSON
|
|
10
|
+
// object per line, each way. A connection sends one request:
|
|
11
|
+
//
|
|
12
|
+
// { t: 'list' } → { sessions: [{ id, label, running, exited, started }] }
|
|
13
|
+
// { t: 'start', id?, command?, args, label?, restart }
|
|
14
|
+
// → { session, already? }: in the session `id` (a new one
|
|
15
|
+
// without), unless it runs and restart is false (`already`);
|
|
16
|
+
// without a command, it starts again as it was
|
|
17
|
+
// { t: 'input', id, d } → { ok }
|
|
18
|
+
// { t: 'resize', id, viewer, cols, rows, active? }
|
|
19
|
+
// → { ok }: the size that fits drawer `viewer`; `active`:
|
|
20
|
+
// the reader is using that drawer now. A session takes
|
|
21
|
+
// the size of its active viewer (see sizes.ts)
|
|
22
|
+
// { t: 'html', id? } → { html }: a screen as HTML rows (the first session's
|
|
23
|
+
// without an id), for a page's first render
|
|
24
|
+
// { t: 'close', id } → { ok }: end the session and drop its tab
|
|
25
|
+
// { t: 'open', id?, path } → { shown }: show the page at `path` in the browser tab
|
|
26
|
+
// whose drawer the reader used last, for session `id`
|
|
27
|
+
// or, without one, of all (a `navigate` to its attach)
|
|
28
|
+
// { t: 'stop' } → { ok }, and the host exits
|
|
29
|
+
// { t: 'attach', id, viewer } → { t: 'sessions', sessions }, then { t: 'none' } or
|
|
30
|
+
// { t: 'screen', d, cols, rows, active, exited }, and then
|
|
31
|
+
// { t: 'data', d }, { t: 'exit', code },
|
|
32
|
+
// { t: 'size', cols, rows, active }, { t: 'navigate', path } and
|
|
33
|
+
// { t: 'sessions', sessions } for as long as it stays open
|
|
34
|
+
//
|
|
35
|
+
// A session has one size for every drawer showing it: whose, is sizes.ts. Every drawer is told of
|
|
36
|
+
// each change (`size`), and shows the session at that size.
|
|
37
|
+
//
|
|
38
|
+
// It exits on `stop`, and after ten minutes without a program running.
|
|
39
|
+
import fs from 'node:fs'
|
|
40
|
+
import net from 'node:net'
|
|
41
|
+
import path from 'node:path'
|
|
42
|
+
import { createRequire } from 'node:module'
|
|
43
|
+
import type { IPty } from 'node-pty'
|
|
44
|
+
import type { Terminal as HeadlessTerminal } from '@xterm/headless'
|
|
45
|
+
import type { SerializeAddon as Serializer } from '@xterm/addon-serialize'
|
|
46
|
+
import { followMouseEncoding } from './modes.ts'
|
|
47
|
+
import { handOver, lastUsed, leave, report, type Sizes } from './sizes.ts'
|
|
48
|
+
|
|
49
|
+
const require = createRequire(import.meta.url)
|
|
50
|
+
const [dir, socket] = process.argv.slice(2)
|
|
51
|
+
if (!dir || !socket) { console.error('usage: host <project dir> <socket path>'); process.exit(2) }
|
|
52
|
+
|
|
53
|
+
/** node-pty. Its prebuilt helper ships without execute permission (1.1.0): add it. */
|
|
54
|
+
function loadPty(): typeof import('node-pty') {
|
|
55
|
+
const pty = require('node-pty')
|
|
56
|
+
const helper = path.join(path.dirname(require.resolve('node-pty/package.json')), 'prebuilds', `${process.platform}-${process.arch}`, 'spawn-helper')
|
|
57
|
+
try { if (fs.existsSync(helper) && !(fs.statSync(helper).mode & 0o111)) fs.chmodSync(helper, 0o755) } catch {}
|
|
58
|
+
return pty
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const { Terminal } = (await import('@xterm/headless')).default
|
|
62
|
+
const { SerializeAddon } = (await import('@xterm/addon-serialize')).default
|
|
63
|
+
|
|
64
|
+
/** A program in a pseudo-terminal, and the headless terminal that keeps its screen. */
|
|
65
|
+
interface Session extends Sizes {
|
|
66
|
+
id: string
|
|
67
|
+
label: string
|
|
68
|
+
/** what it runs, for starting it again */
|
|
69
|
+
command: string
|
|
70
|
+
args: string[]
|
|
71
|
+
proc: IPty
|
|
72
|
+
screen: HeadlessTerminal
|
|
73
|
+
serializer: Serializer
|
|
74
|
+
/** what the serializer leaves out: the mouse encoding the program asked for (see modes.ts) */
|
|
75
|
+
mouseEncoding: () => string
|
|
76
|
+
cols: number
|
|
77
|
+
rows: number
|
|
78
|
+
/** the connections following it */
|
|
79
|
+
attached: Set<Conn>
|
|
80
|
+
exited: number | null
|
|
81
|
+
started: string
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** A connection; `queue` holds what arrives while it still waits for its screen. */
|
|
85
|
+
interface Conn {
|
|
86
|
+
socket: net.Socket
|
|
87
|
+
queue: unknown[] | null
|
|
88
|
+
/** the drawer it follows a session for (attach) */
|
|
89
|
+
viewer?: string
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** the sessions by id, in the order they were made */
|
|
93
|
+
const sessions = new Map<string, Session>()
|
|
94
|
+
let nextId = 1
|
|
95
|
+
// connections following some session: each hears when the list of sessions changes
|
|
96
|
+
const watchers = new Set<Conn>()
|
|
97
|
+
|
|
98
|
+
// a host with no program running leaves after a while (also one whose first start failed)
|
|
99
|
+
let idle: ReturnType<typeof setTimeout> | undefined
|
|
100
|
+
function checkIdle() {
|
|
101
|
+
clearTimeout(idle)
|
|
102
|
+
if (![...sessions.values()].some(s => s.exited == null)) idle = setTimeout(() => quit('no program ran for ten minutes'), 10 * 60 * 1000)
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
const list = () => [...sessions.values()].map(s => ({ id: s.id, label: s.label, running: s.exited == null, exited: s.exited, started: s.started }))
|
|
106
|
+
function announce() { for (const c of watchers) send(c, { t: 'sessions', sessions: list() }) }
|
|
107
|
+
|
|
108
|
+
function start(id: string, command: string, args: string[], label: string): Session {
|
|
109
|
+
const pty = loadPty()
|
|
110
|
+
const before = sessions.get(id)
|
|
111
|
+
const cols = before?.cols ?? 100, rows = before?.rows ?? 30
|
|
112
|
+
const attached = before?.attached ?? new Set<Conn>()
|
|
113
|
+
const viewers = before?.viewers ?? new Map()
|
|
114
|
+
const active = before?.active ?? null
|
|
115
|
+
if (before) endProcess(before)
|
|
116
|
+
const screen = new Terminal({ cols, rows, scrollback: 2000, allowProposedApi: true })
|
|
117
|
+
const serializer = new SerializeAddon()
|
|
118
|
+
screen.loadAddon(serializer)
|
|
119
|
+
const mouseEncoding = followMouseEncoding(screen)
|
|
120
|
+
const proc = pty.spawn(command, args, {
|
|
121
|
+
name: 'xterm-256color', cols, rows, cwd: dir,
|
|
122
|
+
// WHITEBOARD_TERMINAL: which tab a program runs in, so it can show a page where its drawer is (`open`)
|
|
123
|
+
env: { ...process.env, TERM: 'xterm-256color', COLORTERM: 'truecolor', WHITEBOARD_TERMINAL: id },
|
|
124
|
+
})
|
|
125
|
+
const s: Session = { id, label, command, args, proc, screen, serializer, mouseEncoding, cols, rows, attached, viewers, active, exited: null, started: new Date().toISOString() }
|
|
126
|
+
proc.onData(d => {
|
|
127
|
+
screen.write(d)
|
|
128
|
+
for (const c of s.attached) send(c, { t: 'data', d })
|
|
129
|
+
})
|
|
130
|
+
proc.onExit(({ exitCode, signal }) => {
|
|
131
|
+
s.exited = exitCode
|
|
132
|
+
log(`tab ${id} (${label}) ended: ${signal ? `signal ${signal}` : `exit code ${exitCode}`}`)
|
|
133
|
+
for (const c of s.attached) send(c, { t: 'exit', code: exitCode })
|
|
134
|
+
announce()
|
|
135
|
+
checkIdle()
|
|
136
|
+
})
|
|
137
|
+
sessions.set(id, s)
|
|
138
|
+
// a restarted session's followers get its new screen
|
|
139
|
+
for (const c of attached) sendScreen(c, s)
|
|
140
|
+
clearTimeout(idle)
|
|
141
|
+
announce()
|
|
142
|
+
return s
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function endProcess(s: Session) {
|
|
146
|
+
try { if (s.exited == null) s.proc.kill() } catch {}
|
|
147
|
+
s.screen.dispose()
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
function close(id: string) {
|
|
151
|
+
const s = sessions.get(id)
|
|
152
|
+
if (!s) return
|
|
153
|
+
endProcess(s)
|
|
154
|
+
sessions.delete(id)
|
|
155
|
+
for (const c of s.attached) send(c, { t: 'none' })
|
|
156
|
+
announce()
|
|
157
|
+
checkIdle()
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** A line in the host's log (.whiteboard/terminal/host.log), with the time: what happened to it and its tabs. */
|
|
161
|
+
function log(line: string) {
|
|
162
|
+
console.log(`${new Date().toISOString()} terminal host ${process.pid}: ${line}`)
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** Leave, saying why: the log is where to look when the tabs are gone. */
|
|
166
|
+
function quit(reason: string) {
|
|
167
|
+
const running = [...sessions.values()].filter(s => s.exited == null).length
|
|
168
|
+
log(`leaves: ${reason}${running ? `, ending ${running} running tab${running > 1 ? 's' : ''}` : ''}`)
|
|
169
|
+
for (const id of [...sessions.keys()]) close(id)
|
|
170
|
+
try { fs.unlinkSync(socket) } catch {}
|
|
171
|
+
process.exit(0)
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
// ---- sizes (see sizes.ts) ----------------------------------------------------------------------
|
|
175
|
+
|
|
176
|
+
/** Give a session a size, and tell the drawers showing it. */
|
|
177
|
+
function resize(s: Session, cols: number, rows: number) {
|
|
178
|
+
if (cols !== s.cols || rows !== s.rows) {
|
|
179
|
+
s.cols = cols; s.rows = rows
|
|
180
|
+
s.screen.resize(cols, rows)
|
|
181
|
+
if (s.exited == null) s.proc.resize(cols, rows)
|
|
182
|
+
}
|
|
183
|
+
sendSize(s)
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
function sendSize(s: Session) {
|
|
187
|
+
for (const c of s.attached) send(c, { t: 'size', cols: s.cols, rows: s.rows, active: s.active })
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
/** A drawer stopped showing a session. If it was the active one, pass the session on, after a moment. */
|
|
191
|
+
function leaveSession(s: Session, viewer: string) {
|
|
192
|
+
// the same drawer may still show it through another connection
|
|
193
|
+
if ([...s.attached].some(c => c.viewer === viewer)) return
|
|
194
|
+
if (!leave(s, viewer)) return
|
|
195
|
+
setTimeout(() => {
|
|
196
|
+
if (sessions.get(s.id) !== s) return
|
|
197
|
+
const size = handOver(s, viewer)
|
|
198
|
+
if (size) resize(s, size.cols, size.rows)
|
|
199
|
+
}, 1500)
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** Write a message to a connection; one that is still waiting for its screen queues it. */
|
|
203
|
+
function send(conn: Conn, msg: unknown) {
|
|
204
|
+
if (conn.queue) return void conn.queue.push(msg)
|
|
205
|
+
conn.socket.write(JSON.stringify(msg) + '\n')
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/** The screen once the headless terminal has parsed everything written so far; what arrives meanwhile follows it. */
|
|
209
|
+
function sendScreen(conn: Conn, s: Session) {
|
|
210
|
+
conn.queue = []
|
|
211
|
+
s.screen.write('', () => {
|
|
212
|
+
conn.socket.write(JSON.stringify({ t: 'screen', d: s.serializer.serialize() + s.mouseEncoding(), cols: s.cols, rows: s.rows, active: s.active, exited: s.exited }) + '\n')
|
|
213
|
+
const queued = conn.queue ?? []
|
|
214
|
+
conn.queue = null
|
|
215
|
+
for (const msg of queued) send(conn, msg)
|
|
216
|
+
})
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
function html(s: Session | undefined): string {
|
|
220
|
+
if (!s) return ''
|
|
221
|
+
try {
|
|
222
|
+
// the rows, without the wrapper that sets the serializer's own colors and font; text is escaped
|
|
223
|
+
const m = /<pre><div style='[^']*'>([\s\S]*)<\/div><\/pre>/.exec(s.serializer.serializeAsHTML())
|
|
224
|
+
return m ? m[1] : ''
|
|
225
|
+
} catch { return '' }
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
function handle(conn: Conn, req: Record<string, any>) {
|
|
229
|
+
const reply = (msg: unknown) => { conn.socket.end(JSON.stringify(msg) + '\n') }
|
|
230
|
+
const s = req.id != null ? sessions.get(String(req.id)) : undefined
|
|
231
|
+
switch (req.t) {
|
|
232
|
+
case 'list': return reply({ sessions: list() })
|
|
233
|
+
case 'start': {
|
|
234
|
+
const id = req.id != null ? String(req.id) : String(nextId)
|
|
235
|
+
const running = sessions.get(id)
|
|
236
|
+
if (running && running.exited == null && !req.restart) return reply({ session: id, already: true })
|
|
237
|
+
// without a command: start it again as it was (restarting a tab)
|
|
238
|
+
const command = typeof req.command === 'string' && req.command ? req.command : running?.command
|
|
239
|
+
if (!command) return reply({ error: 'start needs a command' })
|
|
240
|
+
const args = typeof req.command === 'string' && req.command ? (Array.isArray(req.args) ? req.args.map(String) : []) : running!.args
|
|
241
|
+
const label = String(req.label ?? (req.command ? path.basename(req.command) : running!.label))
|
|
242
|
+
try { start(id, command, args, label) } catch (e) { return reply({ error: (e as Error).message }) }
|
|
243
|
+
log(`tab ${id} (${label}) ${running ? 'restarted' : 'started'}`)
|
|
244
|
+
// ids are never reused while the host runs, so a closed tab's id can't come back as another
|
|
245
|
+
if (Number(id) >= nextId) nextId = Number(id) + 1
|
|
246
|
+
return reply({ session: id })
|
|
247
|
+
}
|
|
248
|
+
case 'input':
|
|
249
|
+
if (s && s.exited == null && typeof req.d === 'string') s.proc.write(req.d)
|
|
250
|
+
return reply({ ok: true })
|
|
251
|
+
case 'resize': {
|
|
252
|
+
const { cols, rows } = req
|
|
253
|
+
const viewer = String(req.viewer ?? '')
|
|
254
|
+
if (s && viewer && Number.isInteger(cols) && Number.isInteger(rows) && cols > 1 && rows > 1 && cols < 1000 && rows < 500) {
|
|
255
|
+
const size = report(s, viewer, cols, rows, !!req.active)
|
|
256
|
+
resize(s, size.cols, size.rows)
|
|
257
|
+
}
|
|
258
|
+
return reply({ ok: true })
|
|
259
|
+
}
|
|
260
|
+
case 'html': return reply({ html: html(s ?? sessions.values().next().value) })
|
|
261
|
+
case 'close': close(String(req.id)); return reply({ ok: true })
|
|
262
|
+
case 'open': {
|
|
263
|
+
// show a page in the browser tab whose drawer the reader used last: for session `id`, or
|
|
264
|
+
// without one, across all of them (where the reader is). With none active, in every drawer
|
|
265
|
+
// that shows the session.
|
|
266
|
+
const target = s ?? (req.id == null ? lastUsed([...sessions.values()].filter(x => x.attached.size)) ?? [...sessions.values()].find(x => x.attached.size) : undefined)
|
|
267
|
+
if (!target || typeof req.path !== 'string') return reply({ shown: 0 })
|
|
268
|
+
const mine = [...target.attached].filter(c => c.viewer && c.viewer === target.active)
|
|
269
|
+
const to = mine.length ? mine : [...target.attached]
|
|
270
|
+
// not `open`: a browser's EventSource has an event of that name already
|
|
271
|
+
for (const c of to) send(c, { t: 'navigate', path: req.path })
|
|
272
|
+
return reply({ shown: to.length })
|
|
273
|
+
}
|
|
274
|
+
case 'stop': reply({ ok: true }); return void setTimeout(() => quit('asked to stop (whiteboard terminal stop)'), 50)
|
|
275
|
+
case 'attach': {
|
|
276
|
+
watchers.add(conn)
|
|
277
|
+
if (req.viewer) conn.viewer = String(req.viewer)
|
|
278
|
+
conn.socket.on('close', () => {
|
|
279
|
+
watchers.delete(conn)
|
|
280
|
+
for (const x of sessions.values()) if (x.attached.delete(conn) && conn.viewer) leaveSession(x, conn.viewer)
|
|
281
|
+
})
|
|
282
|
+
send(conn, { t: 'sessions', sessions: list() })
|
|
283
|
+
if (!s) return send(conn, { t: 'none' })
|
|
284
|
+
s.attached.add(conn)
|
|
285
|
+
sendScreen(conn, s)
|
|
286
|
+
return
|
|
287
|
+
}
|
|
288
|
+
default: return reply({ error: `unknown request ${req.t}` })
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
|
|
292
|
+
const server = net.createServer(socketConn => {
|
|
293
|
+
const conn: Conn = { socket: socketConn, queue: null }
|
|
294
|
+
let buf = ''
|
|
295
|
+
socketConn.setEncoding('utf8')
|
|
296
|
+
socketConn.on('error', () => {})
|
|
297
|
+
socketConn.on('data', chunk => {
|
|
298
|
+
buf += chunk
|
|
299
|
+
const nl = buf.indexOf('\n')
|
|
300
|
+
if (nl < 0) return
|
|
301
|
+
const line = buf.slice(0, nl)
|
|
302
|
+
buf = ''
|
|
303
|
+
socketConn.removeAllListeners('data')
|
|
304
|
+
let req
|
|
305
|
+
try { req = JSON.parse(line) } catch { return socketConn.end(JSON.stringify({ error: 'not JSON' }) + '\n') }
|
|
306
|
+
handle(conn, req)
|
|
307
|
+
})
|
|
308
|
+
})
|
|
309
|
+
|
|
310
|
+
// a socket left by a host that is gone: remove it; one whose host still answers: leave, it's running
|
|
311
|
+
try {
|
|
312
|
+
await new Promise<void>((resolve, reject) => {
|
|
313
|
+
const probe = net.connect(socket)
|
|
314
|
+
probe.on('connect', () => { probe.destroy(); reject(new Error('running')) })
|
|
315
|
+
probe.on('error', () => resolve())
|
|
316
|
+
})
|
|
317
|
+
try { fs.unlinkSync(socket) } catch {}
|
|
318
|
+
} catch { console.error('terminal host: another host answers on', socket); process.exit(0) }
|
|
319
|
+
|
|
320
|
+
server.listen(socket, () => {
|
|
321
|
+
// only its owner may talk to it: the socket runs code
|
|
322
|
+
try { fs.chmodSync(socket, 0o600) } catch {}
|
|
323
|
+
log(`listening on ${socket}`)
|
|
324
|
+
checkIdle()
|
|
325
|
+
})
|
|
326
|
+
for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP']) process.on(signal, () => quit(`got ${signal} from outside`))
|
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
// The terminal drawer, as a whiteboard plugin: a terminal at the bottom of every page, with tabs, each
|
|
2
|
+
// a session that outlives the browser tab and the page server. In a config:
|
|
3
|
+
//
|
|
4
|
+
// import terminal from '@bigmistqke/whiteboard/terminal'
|
|
5
|
+
// export default defineConfig({ plugins: [terminal()] })
|
|
6
|
+
//
|
|
7
|
+
// Every tab is the user's shell; "+" in the drawer opens one. `whiteboard terminal -- <program>`
|
|
8
|
+
// runs a program in a new tab, in the shell, which takes over when it exits, so a tab ends at a
|
|
9
|
+
// prompt.
|
|
10
|
+
//
|
|
11
|
+
// `whiteboard terminal` prints the link that gives a browser the project's token; only a browser
|
|
12
|
+
// with it gets the drawer. The host's socket and log are in `.whiteboard/terminal/`. What the
|
|
13
|
+
// terminal can do is what the server can: it runs with the rights of whoever started the server.
|
|
14
|
+
//
|
|
15
|
+
// The parts are whiteboard-free: server.ts is a request handler, host.ts the process that runs the
|
|
16
|
+
// sessions, client.ts the drawer in the browser. This file wires them in.
|
|
17
|
+
import { html, raw } from '../../src/html.ts'
|
|
18
|
+
import { packagePath } from '../../src/package.ts'
|
|
19
|
+
import { createTerminal, type Sessions, type StartOptions } from './server.ts'
|
|
20
|
+
import type { CommandContext, Plugin } from '../../src/define.ts'
|
|
21
|
+
|
|
22
|
+
const CLIENT = packagePath('dist/plugins/terminal/client.js')
|
|
23
|
+
const STYLE = packagePath('dist/plugins/terminal/style.css')
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* The drawer's markup, written by the server so that it is there when the page first renders and
|
|
27
|
+
* the browser can morph it from the previous page (a view transition across the page load). Its
|
|
28
|
+
* open state, height and tab come from this browser tab's sessionStorage, set before the first
|
|
29
|
+
* render, and each session's screen is in it as HTML, so a page shows it from its first render on;
|
|
30
|
+
* client.js puts the live terminal in its place.
|
|
31
|
+
*/
|
|
32
|
+
const drawer = (state: Sessions, screens: Record<string, string>, client: string) => html`<aside id="wb-terminal" aria-label="Terminal" data-sessions="${JSON.stringify(state)}">
|
|
33
|
+
<div class="wb-term-grip" title="drag to resize"></div>
|
|
34
|
+
<div class="wb-term-bar"><button type="button" class="wb-term-toggle" title="Toggle the terminal (Ctrl+\`)"><span class="wb-term-chevron"></span>terminal</button><span class="wb-term-status"></span><span class="wb-term-actions"></span><span class="wb-term-tabs">${state.sessions.map(s => html`<button type="button" class="wb-term-tab" data-id="${s.id}">${s.label}</button>`)}</span></div>
|
|
35
|
+
<div class="wb-term-screen">${state.sessions.map(s => screens[s.id] && html`<div class="wb-term-placeholder" data-id="${s.id}" aria-hidden="true">${raw(screens[s.id])}</div>`)}</div>
|
|
36
|
+
</aside>
|
|
37
|
+
<script>try{const t=document.getElementById('wb-terminal'),s=sessionStorage,o=new URLSearchParams(location.search).get('terminal')==='open'||s.getItem('wb-terminal-open')==='1';t.dataset.state=o?'open':'collapsed';const h=+s.getItem('wb-terminal-height');if(h)document.documentElement.style.setProperty('--wb-term-h',h+'px');const tabs=[...t.querySelectorAll('.wb-term-tab')],k=s.getItem('wb-terminal-tab'),a=tabs.find(b=>b.dataset.id===k)??tabs[0];if(a){t.dataset.tab=a.dataset.id;a.classList.add('wb-current');t.querySelector('.wb-term-placeholder[data-id="'+a.dataset.id+'"]')?.classList.add('wb-current')}}catch{}</script>
|
|
38
|
+
<script type="module" src="${client}"></script>`
|
|
39
|
+
|
|
40
|
+
export default function terminal(): Plugin {
|
|
41
|
+
return {
|
|
42
|
+
name: 'terminal',
|
|
43
|
+
// the drawer's look: on every page, since every page can have the drawer
|
|
44
|
+
style: STYLE,
|
|
45
|
+
setup(ctx) {
|
|
46
|
+
const term = createTerminal({ dir: ctx.project.dir, home: ctx.dataDir })
|
|
47
|
+
const client = ctx.asset(CLIENT)
|
|
48
|
+
return {
|
|
49
|
+
// all of them run code or show what runs, so all need the project's token
|
|
50
|
+
routes: {
|
|
51
|
+
'GET /sessions': { description: 'the sessions (the drawer\'s tabs): id, label, whether each runs', auth: true, run: () => term.sessions() },
|
|
52
|
+
'POST /start': {
|
|
53
|
+
description: 'start a tab: the shell, or program (with its arguments) in it; in session id, a new tab without one; with restart, start it again as it was',
|
|
54
|
+
auth: true,
|
|
55
|
+
body: { id: 'string?', program: 'string[]?', restart: 'boolean?' },
|
|
56
|
+
run: ({ body }) => term.start(body as StartOptions),
|
|
57
|
+
},
|
|
58
|
+
'POST /input': { description: 'keystrokes for a session, as the terminal sends them', auth: true, body: { id: 'string', data: 'string' }, run: ({ body }) => term.input(body.id as string, body.data as string) },
|
|
59
|
+
'POST /resize': {
|
|
60
|
+
description: 'the size that fits the terminal in a page (`viewer`: that drawer); `active`: the reader uses this drawer now, so the session takes its size',
|
|
61
|
+
auth: true,
|
|
62
|
+
body: { id: 'string', viewer: 'string', cols: 'number', rows: 'number', active: 'boolean?' },
|
|
63
|
+
run: ({ body }) => term.resize(body.id as string, body.viewer as string, body.cols as number, body.rows as number, !!body.active),
|
|
64
|
+
},
|
|
65
|
+
'GET /stream': {
|
|
66
|
+
description: 'the tabs and a session\'s whole screen, then its output as it comes (events sessions, screen, data, size, navigate, exit; none without that session)',
|
|
67
|
+
auth: true,
|
|
68
|
+
stream: true,
|
|
69
|
+
query: { id: 'string?', viewer: 'string?' },
|
|
70
|
+
run: ({ req, res, query }) => term.stream(req, res!, query.id as string | undefined, query.viewer as string | undefined),
|
|
71
|
+
},
|
|
72
|
+
'POST /close': { description: 'end a session and drop its tab', auth: true, body: { id: 'string' }, run: ({ body }) => term.close(body.id as string) },
|
|
73
|
+
'POST /stop': { description: 'end every session and their host', auth: true, run: () => term.stop() },
|
|
74
|
+
'POST /open': {
|
|
75
|
+
description: 'show the page at path in the browser tab whose drawer the reader used last, for session id or, without one, of all; how many were shown',
|
|
76
|
+
auth: true,
|
|
77
|
+
body: { id: 'string?', path: 'string' },
|
|
78
|
+
run: ({ body }) => term.open(body.id as string | undefined, body.path as string),
|
|
79
|
+
},
|
|
80
|
+
},
|
|
81
|
+
async shell(req) {
|
|
82
|
+
if (!ctx.authorized(req)) return null
|
|
83
|
+
const state = await term.sessions()
|
|
84
|
+
return { body: drawer(state, await term.screens(state.sessions), client) }
|
|
85
|
+
},
|
|
86
|
+
}
|
|
87
|
+
},
|
|
88
|
+
commands: {
|
|
89
|
+
'': {
|
|
90
|
+
description: 'print a link that opens the terminal drawer in this browser (it gives the browser the project\'s token); with --new, open a tab with the shell; with a program after --, run it in a new tab',
|
|
91
|
+
args: '[page]',
|
|
92
|
+
options: {
|
|
93
|
+
new: { type: 'boolean?', description: 'open a new tab with the shell' },
|
|
94
|
+
},
|
|
95
|
+
rest: '<program> [arguments]',
|
|
96
|
+
async run(ctx) {
|
|
97
|
+
if (ctx.options.new || ctx.rest.length) {
|
|
98
|
+
const body = await call(ctx, 'POST', '/start', { program: ctx.rest }) as { session: string }
|
|
99
|
+
console.error(`whiteboard: started in tab ${body.session}`)
|
|
100
|
+
}
|
|
101
|
+
console.log(await ctx.authLink(`${ctx.pagePath(ctx.positionals[0])}?terminal=open`))
|
|
102
|
+
},
|
|
103
|
+
},
|
|
104
|
+
open: {
|
|
105
|
+
description: 'show a page in the browser tab whose drawer the reader used last (from a program in a terminal tab: that tab\'s drawer)',
|
|
106
|
+
args: '<page|file>',
|
|
107
|
+
async run(ctx) {
|
|
108
|
+
if (!ctx.positionals[0]) throw new Error('usage: whiteboard terminal open <page|file>')
|
|
109
|
+
// a program in a tab knows its tab; anything else gets the drawer the reader used last
|
|
110
|
+
const id = process.env.WHITEBOARD_TERMINAL || undefined
|
|
111
|
+
const path = ctx.pagePath(ctx.positionals[0])
|
|
112
|
+
const { shown } = await call(ctx, 'POST', '/open', { id, path }) as { shown: number }
|
|
113
|
+
if (!shown) throw new Error(`no browser shows ${id ? `terminal tab ${id}` : 'the terminal drawer'} right now; the page is at ${await ctx.server()}${path}`)
|
|
114
|
+
console.log(`opened ${path} ${id ? `where tab ${id}'s drawer is` : 'where the drawer you used last is'}`)
|
|
115
|
+
},
|
|
116
|
+
},
|
|
117
|
+
stop: {
|
|
118
|
+
description: 'end every session and their host',
|
|
119
|
+
async run(ctx) {
|
|
120
|
+
const { stopped } = await call(ctx, 'POST', '/stop') as { stopped: boolean }
|
|
121
|
+
console.log(stopped ? 'stopped' : 'no session ran')
|
|
122
|
+
},
|
|
123
|
+
},
|
|
124
|
+
},
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** A request to one of the terminal's routes, from a command. */
|
|
129
|
+
async function call(ctx: CommandContext, method: string, route: string, body?: unknown): Promise<unknown> {
|
|
130
|
+
const res = await fetch(`${await ctx.server()}/api/terminal${route}`, {
|
|
131
|
+
method,
|
|
132
|
+
headers: { 'content-type': 'application/json', 'x-whiteboard-token': ctx.token },
|
|
133
|
+
body: body ? JSON.stringify(body) : undefined,
|
|
134
|
+
})
|
|
135
|
+
const out = await res.json().catch(() => ({}))
|
|
136
|
+
if (!res.ok) throw new Error(out.error ?? res.statusText)
|
|
137
|
+
return out
|
|
138
|
+
}
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
// What a screen snapshot leaves out. The host restores a session's screen in a browser from the
|
|
2
|
+
// serialize addon, which writes the screen and most terminal modes back, but not how mouse events
|
|
3
|
+
// are encoded. A full-screen program (Claude Code, an editor) asks for SGR encoding (`?1006`) along
|
|
4
|
+
// with mouse reporting; restored without it, the browser's terminal sends the wheel in the old
|
|
5
|
+
// encoding, the program ignores it, and the page can't scroll until a resize makes the program ask
|
|
6
|
+
// again. So the host follows the encoding itself and adds it to the snapshot.
|
|
7
|
+
import type { Terminal } from '@xterm/headless'
|
|
8
|
+
|
|
9
|
+
/** The mouse encodings a program can ask for: UTF-8 (1005), SGR (1006), URXVT (1015). */
|
|
10
|
+
const ENCODINGS = [1005, 1006, 1015]
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Follow the mouse encoding the program on `terminal` asks for. Returns what to append to a
|
|
14
|
+
* serialized screen to restore it: the escape sequence, or '' for the default encoding.
|
|
15
|
+
*/
|
|
16
|
+
export function followMouseEncoding(terminal: Terminal): () => string {
|
|
17
|
+
let encoding: number | null = null
|
|
18
|
+
const handle = (on: boolean) => (params: (number | number[])[]) => {
|
|
19
|
+
for (const p of params.flat()) {
|
|
20
|
+
if (!ENCODINGS.includes(p)) continue
|
|
21
|
+
if (on) encoding = p
|
|
22
|
+
else if (encoding === p) encoding = null
|
|
23
|
+
}
|
|
24
|
+
// the terminal handles the sequence as it would anyway
|
|
25
|
+
return false
|
|
26
|
+
}
|
|
27
|
+
terminal.parser.registerCsiHandler({ prefix: '?', final: 'h' }, handle(true))
|
|
28
|
+
terminal.parser.registerCsiHandler({ prefix: '?', final: 'l' }, handle(false))
|
|
29
|
+
return () => (encoding ? `\x1b[?${encoding}h` : '')
|
|
30
|
+
}
|