@bigmistqke/workpad 0.0.0-stage → 0.18.1

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.
Files changed (277) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +781 -2
  3. package/bin/workpad.ts +1526 -0
  4. package/dist/_virtual/_@oxc-project_runtime@0.156.0/helpers/esm/taggedTemplateLiteral.js +5 -0
  5. package/dist/bin/workpad.js +1202 -0
  6. package/dist/client/runtime.js +1194 -0
  7. package/dist/define.js +27 -0
  8. package/dist/plugins/alert/README.md +18 -0
  9. package/dist/plugins/alert/index.js +40 -0
  10. package/dist/plugins/alert/public/style.css +40 -0
  11. package/dist/plugins/ansi/README.md +36 -0
  12. package/dist/plugins/ansi/index.js +63 -0
  13. package/dist/plugins/ansi/public/style.css +28 -0
  14. package/dist/plugins/badge/README.md +32 -0
  15. package/dist/plugins/badge/index.js +28 -0
  16. package/dist/plugins/badge/public/style.css +30 -0
  17. package/dist/plugins/chat/README.md +81 -0
  18. package/dist/plugins/chat/index.js +96 -0
  19. package/dist/plugins/chat/public/client.js +3 -0
  20. package/dist/plugins/chat/public/style.css +143 -0
  21. package/dist/plugins/claude/README.md +116 -0
  22. package/dist/plugins/claude/channel.js +130 -0
  23. package/dist/plugins/claude/doctor.js +316 -0
  24. package/dist/plugins/claude/index.js +199 -0
  25. package/dist/plugins/claude/session.js +68 -0
  26. package/dist/plugins/code/README.md +54 -0
  27. package/dist/plugins/code/diff.js +75 -0
  28. package/dist/plugins/code/index.js +105 -0
  29. package/dist/plugins/code/public/client.js +1 -0
  30. package/dist/plugins/code/public/style.css +99 -0
  31. package/dist/plugins/comments/README.md +30 -0
  32. package/dist/plugins/comments/index.js +39 -0
  33. package/dist/plugins/comments/public/client.js +24 -0
  34. package/dist/plugins/comments/public/style.css +224 -0
  35. package/dist/plugins/details/README.md +24 -0
  36. package/dist/plugins/details/index.js +28 -0
  37. package/dist/plugins/details/public/style.css +7 -0
  38. package/dist/plugins/draft/README.md +14 -0
  39. package/dist/plugins/draft/index.js +27 -0
  40. package/dist/plugins/draft/public/style.css +21 -0
  41. package/dist/plugins/forge/README.md +22 -0
  42. package/dist/plugins/forge/index.js +83 -0
  43. package/dist/plugins/form/README.md +126 -0
  44. package/dist/plugins/form/index.js +179 -0
  45. package/dist/plugins/form/public/style.css +172 -0
  46. package/dist/plugins/grid/README.md +45 -0
  47. package/dist/plugins/grid/index.js +35 -0
  48. package/dist/plugins/grid/public/style.css +98 -0
  49. package/dist/plugins/iframe/README.md +18 -0
  50. package/dist/plugins/iframe/index.js +49 -0
  51. package/dist/plugins/iframe/public/style.css +28 -0
  52. package/dist/plugins/index.js +44 -0
  53. package/dist/plugins/lightbox/README.md +24 -0
  54. package/dist/plugins/lightbox/index.js +20 -0
  55. package/dist/plugins/lightbox/public/client.js +4 -0
  56. package/dist/plugins/lightbox/public/style.css +66 -0
  57. package/dist/plugins/mermaid/README.md +21 -0
  58. package/dist/plugins/mermaid/index.js +42 -0
  59. package/dist/plugins/mermaid/public/style.css +21 -0
  60. package/dist/plugins/opencode/README.md +48 -0
  61. package/dist/plugins/opencode/channel.js +92 -0
  62. package/dist/plugins/opencode/index.js +64 -0
  63. package/dist/plugins/opencode/shim.js +150 -0
  64. package/dist/plugins/quiet/README.md +26 -0
  65. package/dist/plugins/quiet/index.js +23 -0
  66. package/dist/plugins/tabs/README.md +44 -0
  67. package/dist/plugins/tabs/index.js +75 -0
  68. package/dist/plugins/tabs/public/client.js +1 -0
  69. package/dist/plugins/tabs/public/style.css +98 -0
  70. package/dist/plugins/terminal/README.md +63 -0
  71. package/dist/plugins/terminal/host.js +338 -0
  72. package/dist/plugins/terminal/index.js +170 -0
  73. package/dist/plugins/terminal/modes.js +32 -0
  74. package/dist/plugins/terminal/public/client.js +41 -0
  75. package/dist/plugins/terminal/public/style.css +511 -0
  76. package/dist/plugins/terminal/server.js +256 -0
  77. package/dist/plugins/terminal/sizes.js +58 -0
  78. package/dist/plugins/timeline/README.md +48 -0
  79. package/dist/plugins/timeline/index.js +83 -0
  80. package/dist/plugins/timeline/public/style.css +138 -0
  81. package/dist/plugins/toc/README.md +40 -0
  82. package/dist/plugins/toc/index.js +29 -0
  83. package/dist/plugins/toc/public/client.js +1 -0
  84. package/dist/plugins/toc/public/style.css +117 -0
  85. package/dist/plugins/window/README.md +51 -0
  86. package/dist/plugins/window/index.js +91 -0
  87. package/dist/solid/index.js +41 -0
  88. package/dist/src/agents.js +81 -0
  89. package/dist/src/anchors.js +52 -0
  90. package/dist/src/api.js +282 -0
  91. package/dist/src/archive.js +49 -0
  92. package/dist/src/auth.js +67 -0
  93. package/dist/src/build.js +159 -0
  94. package/dist/src/client/page/base.css +1762 -0
  95. package/dist/src/client/page/main.js +2121 -0
  96. package/dist/src/config.js +76 -0
  97. package/dist/src/document.js +93 -0
  98. package/dist/src/entries.js +264 -0
  99. package/dist/src/events.js +322 -0
  100. package/dist/src/files.js +47 -0
  101. package/dist/src/formstate.js +65 -0
  102. package/dist/src/help.js +213 -0
  103. package/dist/src/html.js +34 -0
  104. package/dist/src/hub.js +348 -0
  105. package/dist/src/icons.js +6 -0
  106. package/dist/src/listen.js +132 -0
  107. package/dist/src/listeners.js +64 -0
  108. package/dist/src/load.js +81 -0
  109. package/dist/src/loader.js +179 -0
  110. package/dist/src/migrate.js +314 -0
  111. package/dist/src/package.js +52 -0
  112. package/dist/src/pages/blocks.js +67 -0
  113. package/dist/src/pages/board.js +59 -0
  114. package/dist/src/pages/index.js +27 -0
  115. package/dist/src/pages/markdown.js +863 -0
  116. package/dist/src/pages/render.js +761 -0
  117. package/dist/src/pages/window.js +29 -0
  118. package/dist/src/plugins.js +283 -0
  119. package/dist/src/public.js +24 -0
  120. package/dist/src/rename.js +130 -0
  121. package/dist/src/running.js +146 -0
  122. package/dist/src/serve.js +188 -0
  123. package/dist/src/server.js +1105 -0
  124. package/dist/src/site.js +179 -0
  125. package/dist/src/state.js +155 -0
  126. package/dist/src/status.js +323 -0
  127. package/dist/src/thread.js +68 -0
  128. package/dist/src/watchdog.js +38 -0
  129. package/dist/src/ws.js +128 -0
  130. package/package.json +154 -4
  131. package/plugins/README.md +304 -0
  132. package/plugins/alert/README.md +18 -0
  133. package/plugins/alert/index.ts +50 -0
  134. package/plugins/alert/public/style.css +40 -0
  135. package/plugins/ansi/README.md +36 -0
  136. package/plugins/ansi/index.ts +95 -0
  137. package/plugins/ansi/public/style.css +28 -0
  138. package/plugins/badge/README.md +32 -0
  139. package/plugins/badge/index.ts +36 -0
  140. package/plugins/badge/public/style.css +30 -0
  141. package/plugins/chat/README.md +81 -0
  142. package/plugins/chat/autosize.ts +139 -0
  143. package/plugins/chat/client.tsx +187 -0
  144. package/plugins/chat/index.ts +146 -0
  145. package/plugins/chat/public/style.css +143 -0
  146. package/plugins/claude/README.md +116 -0
  147. package/plugins/claude/channel.ts +136 -0
  148. package/plugins/claude/doctor.ts +274 -0
  149. package/plugins/claude/index.ts +248 -0
  150. package/plugins/claude/session.ts +70 -0
  151. package/plugins/code/README.md +54 -0
  152. package/plugins/code/client.ts +73 -0
  153. package/plugins/code/diff.ts +96 -0
  154. package/plugins/code/index.ts +136 -0
  155. package/plugins/code/public/style.css +99 -0
  156. package/plugins/comments/README.md +30 -0
  157. package/plugins/comments/client.ts +723 -0
  158. package/plugins/comments/index.ts +48 -0
  159. package/plugins/comments/public/style.css +224 -0
  160. package/plugins/details/README.md +24 -0
  161. package/plugins/details/index.ts +30 -0
  162. package/plugins/details/public/style.css +7 -0
  163. package/plugins/draft/README.md +14 -0
  164. package/plugins/draft/index.ts +23 -0
  165. package/plugins/draft/public/style.css +21 -0
  166. package/plugins/forge/README.md +22 -0
  167. package/plugins/forge/index.ts +84 -0
  168. package/plugins/form/README.md +126 -0
  169. package/plugins/form/index.ts +199 -0
  170. package/plugins/form/public/style.css +172 -0
  171. package/plugins/grid/README.md +45 -0
  172. package/plugins/grid/index.ts +41 -0
  173. package/plugins/grid/public/style.css +98 -0
  174. package/plugins/iframe/README.md +18 -0
  175. package/plugins/iframe/index.ts +53 -0
  176. package/plugins/iframe/public/style.css +28 -0
  177. package/plugins/index.ts +49 -0
  178. package/plugins/lightbox/README.md +24 -0
  179. package/plugins/lightbox/client.ts +109 -0
  180. package/plugins/lightbox/index.ts +25 -0
  181. package/plugins/lightbox/public/style.css +66 -0
  182. package/plugins/mermaid/README.md +21 -0
  183. package/plugins/mermaid/index.ts +46 -0
  184. package/plugins/mermaid/public/style.css +21 -0
  185. package/plugins/opencode/README.md +48 -0
  186. package/plugins/opencode/channel.ts +112 -0
  187. package/plugins/opencode/index.ts +91 -0
  188. package/plugins/opencode/shim.ts +166 -0
  189. package/plugins/quiet/README.md +26 -0
  190. package/plugins/quiet/index.ts +28 -0
  191. package/plugins/tabs/README.md +44 -0
  192. package/plugins/tabs/client.ts +96 -0
  193. package/plugins/tabs/index.ts +103 -0
  194. package/plugins/tabs/public/style.css +98 -0
  195. package/plugins/terminal/README.md +63 -0
  196. package/plugins/terminal/client.ts +391 -0
  197. package/plugins/terminal/host.ts +434 -0
  198. package/plugins/terminal/index.ts +199 -0
  199. package/plugins/terminal/modes.ts +30 -0
  200. package/plugins/terminal/public/style.css +225 -0
  201. package/plugins/terminal/server.ts +266 -0
  202. package/plugins/terminal/sizes.ts +72 -0
  203. package/plugins/timeline/README.md +48 -0
  204. package/plugins/timeline/index.ts +82 -0
  205. package/plugins/timeline/public/style.css +138 -0
  206. package/plugins/toc/README.md +40 -0
  207. package/plugins/toc/client.ts +236 -0
  208. package/plugins/toc/index.ts +55 -0
  209. package/plugins/toc/public/style.css +117 -0
  210. package/plugins/window/README.md +51 -0
  211. package/plugins/window/index.ts +92 -0
  212. package/skills/workpad/SKILL.md +592 -0
  213. package/solid/index.tsx +80 -0
  214. package/src/agents.ts +134 -0
  215. package/src/anchors.ts +85 -0
  216. package/src/api.ts +444 -0
  217. package/src/archive.ts +75 -0
  218. package/src/auth.ts +99 -0
  219. package/src/build.ts +213 -0
  220. package/src/client/base.ts +19 -0
  221. package/src/client/forms.ts +420 -0
  222. package/src/client/markdown.ts +147 -0
  223. package/src/client/page/base.css +1762 -0
  224. package/src/client/page/board.ts +166 -0
  225. package/src/client/page/elsewhere.ts +153 -0
  226. package/src/client/page/fresh.ts +343 -0
  227. package/src/client/page/heading-link.ts +32 -0
  228. package/src/client/page/live.ts +134 -0
  229. package/src/client/page/main.ts +398 -0
  230. package/src/client/page/orphans.ts +64 -0
  231. package/src/client/page/place.ts +260 -0
  232. package/src/client/page/sort.ts +49 -0
  233. package/src/client/page/sticky.ts +58 -0
  234. package/src/client/page/theme.ts +36 -0
  235. package/src/client/page/view.ts +9 -0
  236. package/src/client/page/waiting.ts +278 -0
  237. package/src/client/page/window.ts +40 -0
  238. package/src/client/reactive.ts +19 -0
  239. package/src/client/read.ts +111 -0
  240. package/src/client/runtime.ts +499 -0
  241. package/src/client/scroll.ts +90 -0
  242. package/src/client/toast.ts +99 -0
  243. package/src/config.ts +111 -0
  244. package/src/define.ts +997 -0
  245. package/src/document.ts +191 -0
  246. package/src/entries.ts +352 -0
  247. package/src/events.ts +463 -0
  248. package/src/files.ts +74 -0
  249. package/src/formstate.ts +72 -0
  250. package/src/help.ts +240 -0
  251. package/src/html.ts +44 -0
  252. package/src/hub.ts +435 -0
  253. package/src/icons.ts +18 -0
  254. package/src/listen.ts +171 -0
  255. package/src/listeners.ts +89 -0
  256. package/src/load.ts +113 -0
  257. package/src/loader.ts +227 -0
  258. package/src/migrate.ts +352 -0
  259. package/src/package.ts +62 -0
  260. package/src/pages/blocks.ts +106 -0
  261. package/src/pages/board.ts +89 -0
  262. package/src/pages/index.ts +79 -0
  263. package/src/pages/markdown.ts +976 -0
  264. package/src/pages/render.ts +845 -0
  265. package/src/pages/window.ts +69 -0
  266. package/src/plugins.ts +319 -0
  267. package/src/public.ts +39 -0
  268. package/src/rename.ts +147 -0
  269. package/src/running.ts +171 -0
  270. package/src/serve.ts +221 -0
  271. package/src/server.ts +1385 -0
  272. package/src/site.ts +170 -0
  273. package/src/state.ts +327 -0
  274. package/src/status.ts +466 -0
  275. package/src/thread.ts +98 -0
  276. package/src/watchdog.ts +53 -0
  277. package/src/ws.ts +155 -0
@@ -0,0 +1,434 @@
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 * as NodePty from 'node-pty'
44
+ import type { IPty } from 'node-pty'
45
+ import xtermHeadless, { type Terminal as HeadlessTerminal } from '@xterm/headless'
46
+ import xtermSerialize, { type SerializeAddon as Serializer } from '@xterm/addon-serialize'
47
+ import { followMouseEncoding } from './modes.ts'
48
+ import { handOver, lastUsed, leave, report, type Sizes } from './sizes.ts'
49
+
50
+ const require = createRequire(import.meta.url)
51
+ const [dir, socket] = process.argv.slice(2)
52
+ if (!dir || !socket) {
53
+ console.error('usage: host <project dir> <socket path>')
54
+ process.exit(2)
55
+ }
56
+
57
+ /**
58
+ * node-pty, loaded when a session starts rather than imported: a native module that may not load on
59
+ * this machine, which then is an error to report, not a host that fails to start. Its prebuilt
60
+ * helper ships without execute permission (1.1.0): add it.
61
+ */
62
+ function loadPty(): typeof NodePty {
63
+ const pty = require('node-pty')
64
+ const helper = path.join(
65
+ path.dirname(require.resolve('node-pty/package.json')),
66
+ 'prebuilds',
67
+ `${process.platform}-${process.arch}`,
68
+ 'spawn-helper',
69
+ )
70
+ try {
71
+ if (fs.existsSync(helper) && !(fs.statSync(helper).mode & 0o111)) fs.chmodSync(helper, 0o755)
72
+ } catch {}
73
+ return pty
74
+ }
75
+
76
+ // CommonJS packages: their exports are the default's
77
+ const { Terminal } = xtermHeadless
78
+ const { SerializeAddon } = xtermSerialize
79
+
80
+ /** A program in a pseudo-terminal, and the headless terminal that keeps its screen. */
81
+ interface Session extends Sizes {
82
+ id: string
83
+ label: string
84
+ /** what it runs, for starting it again */
85
+ command: string
86
+ args: string[]
87
+ proc: IPty
88
+ screen: HeadlessTerminal
89
+ serializer: Serializer
90
+ /** what the serializer leaves out: the mouse encoding the program asked for (see modes.ts) */
91
+ mouseEncoding: () => string
92
+ cols: number
93
+ rows: number
94
+ /** the connections following it */
95
+ attached: Set<Conn>
96
+ exited: number | null
97
+ started: string
98
+ }
99
+
100
+ /** A connection; `queue` holds what arrives while it still waits for its screen. */
101
+ interface Conn {
102
+ socket: net.Socket
103
+ queue: unknown[] | null
104
+ /** the drawer it follows a session for (attach) */
105
+ viewer?: string
106
+ }
107
+
108
+ /** the sessions by id, in the order they were made */
109
+ const sessions = new Map<string, Session>()
110
+ let nextId = 1
111
+ // connections following some session: each hears when the list of sessions changes
112
+ const watchers = new Set<Conn>()
113
+
114
+ // a host with no program running leaves after a while (also one whose first start failed)
115
+ let idle: ReturnType<typeof setTimeout> | undefined
116
+ function checkIdle() {
117
+ clearTimeout(idle)
118
+ if (![...sessions.values()].some(s => s.exited == null))
119
+ idle = setTimeout(() => quit('no program ran for ten minutes'), 10 * 60 * 1000)
120
+ }
121
+
122
+ const list = () =>
123
+ [...sessions.values()].map(s => ({
124
+ id: s.id,
125
+ label: s.label,
126
+ running: s.exited == null,
127
+ exited: s.exited,
128
+ started: s.started,
129
+ }))
130
+ function announce() {
131
+ for (const c of watchers) send(c, { t: 'sessions', sessions: list() })
132
+ }
133
+
134
+ function start(id: string, command: string, args: string[], label: string): Session {
135
+ const pty = loadPty()
136
+ const before = sessions.get(id)
137
+ const cols = before?.cols ?? 100,
138
+ rows = before?.rows ?? 30
139
+ const attached = before?.attached ?? new Set<Conn>()
140
+ const viewers = before?.viewers ?? new Map()
141
+ const active = before?.active ?? null
142
+ if (before) endProcess(before)
143
+ const screen = new Terminal({ cols, rows, scrollback: 2000, allowProposedApi: true })
144
+ const serializer = new SerializeAddon()
145
+ screen.loadAddon(serializer)
146
+ const mouseEncoding = followMouseEncoding(screen)
147
+ const proc = pty.spawn(command, args, {
148
+ name: 'xterm-256color',
149
+ cols,
150
+ rows,
151
+ cwd: dir,
152
+ // WORKPAD_TERMINAL: which tab a program runs in, so it can show a page where its drawer is (`open`)
153
+ env: { ...process.env, TERM: 'xterm-256color', COLORTERM: 'truecolor', WORKPAD_TERMINAL: id },
154
+ })
155
+ const s: Session = {
156
+ id,
157
+ label,
158
+ command,
159
+ args,
160
+ proc,
161
+ screen,
162
+ serializer,
163
+ mouseEncoding,
164
+ cols,
165
+ rows,
166
+ attached,
167
+ viewers,
168
+ active,
169
+ exited: null,
170
+ started: new Date().toISOString(),
171
+ }
172
+ proc.onData(d => {
173
+ screen.write(d)
174
+ for (const c of s.attached) send(c, { t: 'data', d })
175
+ })
176
+ proc.onExit(({ exitCode, signal }) => {
177
+ s.exited = exitCode
178
+ log(`tab ${id} (${label}) ended: ${signal ? `signal ${signal}` : `exit code ${exitCode}`}`)
179
+ for (const c of s.attached) send(c, { t: 'exit', code: exitCode })
180
+ announce()
181
+ checkIdle()
182
+ })
183
+ sessions.set(id, s)
184
+ // a restarted session's followers get its new screen
185
+ for (const c of attached) sendScreen(c, s)
186
+ clearTimeout(idle)
187
+ announce()
188
+ return s
189
+ }
190
+
191
+ function endProcess(s: Session) {
192
+ try {
193
+ if (s.exited == null) s.proc.kill()
194
+ } catch {}
195
+ s.screen.dispose()
196
+ }
197
+
198
+ function close(id: string) {
199
+ const s = sessions.get(id)
200
+ if (!s) return
201
+ endProcess(s)
202
+ sessions.delete(id)
203
+ for (const c of s.attached) send(c, { t: 'none' })
204
+ announce()
205
+ checkIdle()
206
+ }
207
+
208
+ /** A line in the host's log (.workpad/terminal/host.log), with the time: what happened to it and its tabs. */
209
+ function log(line: string) {
210
+ console.log(`${new Date().toISOString()} terminal host ${process.pid}: ${line}`)
211
+ }
212
+
213
+ /** Leave, saying why: the log is where to look when the tabs are gone. */
214
+ function quit(reason: string) {
215
+ const running = [...sessions.values()].filter(s => s.exited == null).length
216
+ log(`leaves: ${reason}${running ? `, ending ${running} running tab${running > 1 ? 's' : ''}` : ''}`)
217
+ for (const id of [...sessions.keys()]) close(id)
218
+ try {
219
+ fs.unlinkSync(socket)
220
+ } catch {}
221
+ process.exit(0)
222
+ }
223
+
224
+ // ---- sizes (see sizes.ts) ----------------------------------------------------------------------
225
+
226
+ /** Give a session a size, and tell the drawers showing it. */
227
+ function resize(s: Session, cols: number, rows: number) {
228
+ if (cols !== s.cols || rows !== s.rows) {
229
+ s.cols = cols
230
+ s.rows = rows
231
+ s.screen.resize(cols, rows)
232
+ if (s.exited == null) s.proc.resize(cols, rows)
233
+ }
234
+ sendSize(s)
235
+ }
236
+
237
+ function sendSize(s: Session) {
238
+ for (const c of s.attached) send(c, { t: 'size', cols: s.cols, rows: s.rows, active: s.active })
239
+ }
240
+
241
+ /** A drawer stopped showing a session. If it was the active one, pass the session on, after a moment. */
242
+ function leaveSession(s: Session, viewer: string) {
243
+ // the same drawer may still show it through another connection
244
+ if ([...s.attached].some(c => c.viewer === viewer)) return
245
+ if (!leave(s, viewer)) return
246
+ setTimeout(() => {
247
+ if (sessions.get(s.id) !== s) return
248
+ const size = handOver(s, viewer)
249
+ if (size) resize(s, size.cols, size.rows)
250
+ }, 1500)
251
+ }
252
+
253
+ /** Write a message to a connection; one that is still waiting for its screen queues it. */
254
+ function send(conn: Conn, msg: unknown) {
255
+ if (conn.queue) return void conn.queue.push(msg)
256
+ conn.socket.write(JSON.stringify(msg) + '\n')
257
+ }
258
+
259
+ /** The screen once the headless terminal has parsed everything written so far; what arrives meanwhile follows it. */
260
+ function sendScreen(conn: Conn, s: Session) {
261
+ conn.queue = []
262
+ s.screen.write('', () => {
263
+ conn.socket.write(
264
+ JSON.stringify({
265
+ t: 'screen',
266
+ d: s.serializer.serialize() + s.mouseEncoding(),
267
+ cols: s.cols,
268
+ rows: s.rows,
269
+ active: s.active,
270
+ exited: s.exited,
271
+ }) + '\n',
272
+ )
273
+ const queued = conn.queue ?? []
274
+ conn.queue = null
275
+ for (const msg of queued) send(conn, msg)
276
+ })
277
+ }
278
+
279
+ function html(s: Session | undefined): string {
280
+ if (!s) return ''
281
+ try {
282
+ // the rows, without the wrapper that sets the serializer's own colors and font; text is escaped
283
+ const m = /<pre><div style='[^']*'>([\s\S]*)<\/div><\/pre>/.exec(s.serializer.serializeAsHTML())
284
+ return m ? m[1] : ''
285
+ } catch {
286
+ return ''
287
+ }
288
+ }
289
+
290
+ function handle(conn: Conn, req: Record<string, any>) {
291
+ const reply = (msg: unknown) => {
292
+ conn.socket.end(JSON.stringify(msg) + '\n')
293
+ }
294
+ const s = req.id != null ? sessions.get(String(req.id)) : undefined
295
+ switch (req.t) {
296
+ case 'list':
297
+ return reply({ sessions: list() })
298
+ case 'start': {
299
+ const id = req.id != null ? String(req.id) : String(nextId)
300
+ const running = sessions.get(id)
301
+ if (running && running.exited == null && !req.restart) return reply({ session: id, already: true })
302
+ // without a command: start it again as it was (restarting a tab)
303
+ const command = typeof req.command === 'string' && req.command ? req.command : running?.command
304
+ if (!command) return reply({ error: 'start needs a command' })
305
+ const args =
306
+ typeof req.command === 'string' && req.command
307
+ ? Array.isArray(req.args)
308
+ ? req.args.map(String)
309
+ : []
310
+ : running!.args
311
+ const label = String(req.label ?? (req.command ? path.basename(req.command) : running!.label))
312
+ try {
313
+ start(id, command, args, label)
314
+ } catch (e) {
315
+ return reply({ error: (e as Error).message })
316
+ }
317
+ log(`tab ${id} (${label}) ${running ? 'restarted' : 'started'}`)
318
+ // ids are never reused while the host runs, so a closed tab's id can't come back as another
319
+ if (Number(id) >= nextId) nextId = Number(id) + 1
320
+ return reply({ session: id })
321
+ }
322
+ case 'input':
323
+ if (s && s.exited == null && typeof req.d === 'string') s.proc.write(req.d)
324
+ return reply({ ok: true })
325
+ case 'resize': {
326
+ const { cols, rows } = req
327
+ const viewer = String(req.viewer ?? '')
328
+ if (
329
+ s &&
330
+ viewer &&
331
+ Number.isInteger(cols) &&
332
+ Number.isInteger(rows) &&
333
+ cols > 1 &&
334
+ rows > 1 &&
335
+ cols < 1000 &&
336
+ rows < 500
337
+ ) {
338
+ const size = report(s, viewer, cols, rows, !!req.active)
339
+ resize(s, size.cols, size.rows)
340
+ }
341
+ return reply({ ok: true })
342
+ }
343
+ case 'html':
344
+ return reply({ html: html(s ?? sessions.values().next().value) })
345
+ case 'close':
346
+ close(String(req.id))
347
+ return reply({ ok: true })
348
+ case 'open': {
349
+ // show a page in the browser tab whose drawer the reader used last: for session `id`, or
350
+ // without one, across all of them (where the reader is). With none active, in every drawer
351
+ // that shows the session.
352
+ const target =
353
+ s ??
354
+ (req.id == null
355
+ ? (lastUsed([...sessions.values()].filter(x => x.attached.size)) ??
356
+ [...sessions.values()].find(x => x.attached.size))
357
+ : undefined)
358
+ if (!target || typeof req.path !== 'string') return reply({ shown: 0 })
359
+ const mine = [...target.attached].filter(c => c.viewer && c.viewer === target.active)
360
+ const to = mine.length ? mine : [...target.attached]
361
+ // not `open`: a browser's EventSource has an event of that name already
362
+ for (const c of to) send(c, { t: 'navigate', path: req.path })
363
+ return reply({ shown: to.length })
364
+ }
365
+ case 'stop':
366
+ reply({ ok: true })
367
+ return void setTimeout(() => quit('asked to stop (workpad terminal stop)'), 50)
368
+ case 'attach': {
369
+ watchers.add(conn)
370
+ if (req.viewer) conn.viewer = String(req.viewer)
371
+ conn.socket.on('close', () => {
372
+ watchers.delete(conn)
373
+ for (const x of sessions.values()) if (x.attached.delete(conn) && conn.viewer) leaveSession(x, conn.viewer)
374
+ })
375
+ send(conn, { t: 'sessions', sessions: list() })
376
+ if (!s) return send(conn, { t: 'none' })
377
+ s.attached.add(conn)
378
+ sendScreen(conn, s)
379
+ return
380
+ }
381
+ default:
382
+ return reply({ error: `unknown request ${req.t}` })
383
+ }
384
+ }
385
+
386
+ const server = net.createServer(socketConn => {
387
+ const conn: Conn = { socket: socketConn, queue: null }
388
+ let buf = ''
389
+ socketConn.setEncoding('utf8')
390
+ socketConn.on('error', () => {})
391
+ socketConn.on('data', chunk => {
392
+ buf += chunk
393
+ const nl = buf.indexOf('\n')
394
+ if (nl < 0) return
395
+ const line = buf.slice(0, nl)
396
+ buf = ''
397
+ socketConn.removeAllListeners('data')
398
+ let req
399
+ try {
400
+ req = JSON.parse(line)
401
+ } catch {
402
+ return socketConn.end(JSON.stringify({ error: 'not JSON' }) + '\n')
403
+ }
404
+ handle(conn, req)
405
+ })
406
+ })
407
+
408
+ // a socket left by a host that is gone: remove it; one whose host still answers: leave, it's running
409
+ try {
410
+ await new Promise<void>((resolve, reject) => {
411
+ const probe = net.connect(socket)
412
+ probe.on('connect', () => {
413
+ probe.destroy()
414
+ reject(new Error('running'))
415
+ })
416
+ probe.on('error', () => resolve())
417
+ })
418
+ try {
419
+ fs.unlinkSync(socket)
420
+ } catch {}
421
+ } catch {
422
+ console.error('terminal host: another host answers on', socket)
423
+ process.exit(0)
424
+ }
425
+
426
+ server.listen(socket, () => {
427
+ // only its owner may talk to it: the socket runs code
428
+ try {
429
+ fs.chmodSync(socket, 0o600)
430
+ } catch {}
431
+ log(`listening on ${socket}`)
432
+ checkIdle()
433
+ })
434
+ for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP']) process.on(signal, () => quit(`got ${signal} from outside`))
@@ -0,0 +1,199 @@
1
+ // The terminal drawer, as a workpad 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/workpad/terminal'
5
+ // export default defineConfig({ plugins: [terminal()] })
6
+ //
7
+ // Every tab is the user's shell; "+" in the drawer opens one. `workpad 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
+ // `workpad 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 `.workpad/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 workpad-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 { builtinPublic } 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 = 'client.js'
23
+ const STYLE = '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>) =>
33
+ html`<aside id="wp-terminal" aria-label="Terminal" data-sessions="${JSON.stringify(state)}">
34
+ <div class="wp-term-grip" title="drag to resize"></div>
35
+ <div class="wp-term-bar">
36
+ <button type="button" class="wp-term-toggle" title="Toggle the terminal (Ctrl+\`)">
37
+ <span class="wp-term-chevron"></span>terminal</button
38
+ ><span class="wp-term-status"></span><span class="wp-term-actions"></span
39
+ ><span class="wp-term-tabs"
40
+ >${state.sessions.map(s => html`<button type="button" class="wp-term-tab" data-id="${s.id}">${s.label}</button>`)}</span
41
+ >
42
+ </div>
43
+ <div class="wp-term-screen">
44
+ ${state.sessions.map(s => screens[s.id] && html`<div class="wp-term-placeholder" data-id="${s.id}" aria-hidden="true">${raw(screens[s.id])}</div>`)}
45
+ </div>
46
+ </aside>
47
+ <script>
48
+ try {
49
+ const t = document.getElementById('wp-terminal'),
50
+ s = sessionStorage,
51
+ o = new URLSearchParams(location.search).get('terminal') === 'open' || s.getItem('wp-terminal-open') === '1'
52
+ t.dataset.state = o ? 'open' : 'collapsed'
53
+ const h = +s.getItem('wp-terminal-height')
54
+ if (h) document.documentElement.style.setProperty('--wp-term-h', h + 'px')
55
+ const tabs = [...t.querySelectorAll('.wp-term-tab')],
56
+ k = s.getItem('wp-terminal-tab'),
57
+ a = tabs.find(b => b.dataset.id === k) ?? tabs[0]
58
+ if (a) {
59
+ t.dataset.tab = a.dataset.id
60
+ a.classList.add('wp-current')
61
+ t.querySelector('.wp-term-placeholder[data-id="' + a.dataset.id + '"]')?.classList.add('wp-current')
62
+ }
63
+ } catch {}
64
+ </script>`
65
+
66
+ export default function terminal(): Plugin {
67
+ return {
68
+ name: 'terminal',
69
+ public: builtinPublic('terminal'),
70
+ // the drawer's look: on every page, since every page can have the drawer
71
+ style: STYLE,
72
+ setup(ctx) {
73
+ const term = createTerminal({ dir: ctx.project.dir, home: ctx.dataDir })
74
+ return {
75
+ // the drawer comes alive: client.js mounts on it in its slot
76
+ client: CLIENT,
77
+ // all of them run code or show what runs, so all need the project's token
78
+ routes: {
79
+ 'GET /sessions': {
80
+ description: "the sessions (the drawer's tabs): id, label, whether each runs",
81
+ auth: true,
82
+ run: () => term.sessions(),
83
+ },
84
+ 'POST /start': {
85
+ description:
86
+ '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',
87
+ auth: true,
88
+ body: { id: 'string?', program: 'string[]?', restart: 'boolean?' },
89
+ run: ({ body }) => term.start(body as StartOptions),
90
+ },
91
+ 'POST /input': {
92
+ description: 'keystrokes for a session, as the terminal sends them',
93
+ auth: true,
94
+ body: { id: 'string', data: 'string' },
95
+ run: ({ body }) => term.input(body.id as string, body.data as string),
96
+ },
97
+ 'POST /resize': {
98
+ description:
99
+ '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',
100
+ auth: true,
101
+ body: { id: 'string', viewer: 'string', cols: 'number', rows: 'number', active: 'boolean?' },
102
+ run: ({ body }) =>
103
+ term.resize(
104
+ body.id as string,
105
+ body.viewer as string,
106
+ body.cols as number,
107
+ body.rows as number,
108
+ !!body.active,
109
+ ),
110
+ },
111
+ 'GET /stream': {
112
+ description:
113
+ "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)",
114
+ auth: true,
115
+ stream: true,
116
+ query: { id: 'string?', viewer: 'string?' },
117
+ run: ({ req, res, query }) =>
118
+ term.stream(req, res!, query.id as string | undefined, query.viewer as string | undefined),
119
+ },
120
+ 'POST /close': {
121
+ description: 'end a session and drop its tab',
122
+ auth: true,
123
+ body: { id: 'string' },
124
+ run: ({ body }) => term.close(body.id as string),
125
+ },
126
+ 'POST /stop': { description: 'end every session and their host', auth: true, run: () => term.stop() },
127
+ 'POST /open': {
128
+ description:
129
+ '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',
130
+ auth: true,
131
+ body: { id: 'string?', path: 'string' },
132
+ run: ({ body }) => term.open(body.id as string | undefined, body.path as string),
133
+ },
134
+ },
135
+ // the drawer, in the bottom slot, there on the first render: the view transition between two
136
+ // pages morphs it, and the page leaves room for it from the first paint
137
+ async slots(req) {
138
+ if (!ctx.authorized(req)) return null
139
+ const state = await term.sessions()
140
+ return { bottom: drawer(state, await term.screens(state.sessions)) }
141
+ },
142
+ }
143
+ },
144
+ commands: {
145
+ '': {
146
+ description:
147
+ "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",
148
+ args: '[page]',
149
+ options: {
150
+ new: { type: 'boolean?', description: 'open a new tab with the shell' },
151
+ },
152
+ rest: '<program> [arguments]',
153
+ async run(ctx) {
154
+ if (ctx.options.new || ctx.rest.length) {
155
+ const body = (await call(ctx, 'POST', '/start', { program: ctx.rest })) as { session: string }
156
+ console.error(`workpad: started in tab ${body.session}`)
157
+ }
158
+ console.log(await ctx.authLink(`${ctx.pagePath(ctx.positionals[0])}?terminal=open`))
159
+ },
160
+ },
161
+ open: {
162
+ description:
163
+ "show a page in the browser tab whose drawer the reader used last (from a program in a terminal tab: that tab's drawer)",
164
+ args: '<page|file>',
165
+ async run(ctx) {
166
+ if (!ctx.positionals[0]) throw new Error('usage: workpad terminal open <page|file>')
167
+ // a program in a tab knows its tab; anything else gets the drawer the reader used last
168
+ const id = process.env.WORKPAD_TERMINAL || undefined
169
+ const path = ctx.pagePath(ctx.positionals[0])
170
+ const { shown } = (await call(ctx, 'POST', '/open', { id, path })) as { shown: number }
171
+ if (!shown)
172
+ throw new Error(
173
+ `no browser shows ${id ? `terminal tab ${id}` : 'the terminal drawer'} right now; the page is at ${await ctx.server()}${path}`,
174
+ )
175
+ console.log(`opened ${path} ${id ? `where tab ${id}'s drawer is` : 'where the drawer you used last is'}`)
176
+ },
177
+ },
178
+ stop: {
179
+ description: 'end every session and their host',
180
+ async run(ctx) {
181
+ const { stopped } = (await call(ctx, 'POST', '/stop')) as { stopped: boolean }
182
+ console.log(stopped ? 'stopped' : 'no session ran')
183
+ },
184
+ },
185
+ },
186
+ }
187
+ }
188
+
189
+ /** A request to one of the terminal's routes, from a command. */
190
+ async function call(ctx: CommandContext, method: string, route: string, body?: unknown): Promise<unknown> {
191
+ const res = await fetch(`${await ctx.server()}/api/terminal${route}`, {
192
+ method,
193
+ headers: { 'content-type': 'application/json', 'x-workpad-token': ctx.token },
194
+ body: body ? JSON.stringify(body) : undefined,
195
+ })
196
+ const out = await res.json().catch(() => ({}))
197
+ if (!res.ok) throw new Error(out.error ?? res.statusText)
198
+ return out
199
+ }
@@ -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
+ }