pinokiod 8.3.9 → 8.3.11

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.
@@ -0,0 +1,93 @@
1
+ "use strict"
2
+
3
+ // spec/requirements/request-files.md
4
+ const test = require("node:test")
5
+ const assert = require("node:assert/strict")
6
+ const fs = require("fs")
7
+ const os = require("os")
8
+ const path = require("path")
9
+ const RequestFile = require("../kernel/request_file")
10
+
11
+ const withFolder = async (run) => {
12
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), "pinokio-request-file-"))
13
+ try {
14
+ await run(dir)
15
+ } finally {
16
+ fs.rmSync(dir, { recursive: true, force: true })
17
+ }
18
+ }
19
+ const LINE = (file) => `My message is in ${file}. Read it and respond as if I had typed it here.`
20
+
21
+ test("the request line is one line that names the file", () => {
22
+ assert.equal(RequestFile.line("SPEC.md"), LINE("SPEC.md"))
23
+ assert.equal(/[\r\n]/.test(RequestFile.line(".pinokio-temp/requests/20261117-aaaaaaaa.md")), false)
24
+ })
25
+
26
+ test("an Ask's request is saved in the folder the agent starts in, lines intact", async () => {
27
+ await withFolder(async (dir) => {
28
+ const line = await RequestFile.save(dir, "20261117-aaaaaaaa", "one\n\ntwo\n- three")
29
+ assert.equal(line, LINE(".pinokio-temp/requests/20261117-aaaaaaaa.md"), "the path uses / on every system")
30
+ assert.equal(fs.readFileSync(path.join(dir, ".pinokio-temp", "requests", "20261117-aaaaaaaa.md"), "utf8"), "one\n\ntwo\n- three\n")
31
+ await RequestFile.save(dir, "20261117-bbbbbbbb", "another")
32
+ assert.equal(fs.readdirSync(path.join(dir, ".pinokio-temp", "requests")).length, 2, "an earlier request is kept")
33
+ })
34
+ })
35
+
36
+ test("a new folder's request line points to the SPEC.md that holds the words", async () => {
37
+ await withFolder(async (dir) => {
38
+ assert.equal(await RequestFile.forSpec(dir, "build a thing"), null, "no SPEC.md")
39
+ fs.writeFileSync(path.join(dir, "SPEC.md"), "build a thing\nwith two lines\n")
40
+ assert.equal(await RequestFile.forSpec(dir, " build a thing\nwith two lines "), LINE("SPEC.md"))
41
+ assert.equal(await RequestFile.forSpec(dir, "something else"), null, "SPEC.md holds other words")
42
+ assert.equal(await RequestFile.forSpec(dir, ""), null, "no words")
43
+ })
44
+ })
45
+
46
+ test("a start address carries the request line in place of the words", async () => {
47
+ await withFolder(async (dir) => {
48
+ const words = "make a radio\n\nwith a queue & a 100% volume knob"
49
+ const address = `/p/radio/dev?plugin=/plugin/codex/pinokio.js&prompt=${encodeURIComponent(words)}`
50
+ assert.equal(await RequestFile.pointAddressToSpec(address, dir), address, "left alone without SPEC.md")
51
+ fs.writeFileSync(path.join(dir, "SPEC.md"), `${words}\n`)
52
+ const pointed = new URL(await RequestFile.pointAddressToSpec(address, dir), "http://x")
53
+ assert.equal(pointed.pathname, "/p/radio/dev")
54
+ assert.equal(pointed.searchParams.get("plugin"), "/plugin/codex/pinokio.js")
55
+ assert.equal(pointed.searchParams.get("prompt"), LINE("SPEC.md"))
56
+ for (const same of ["/p/radio/dev", "/p/radio/dev?plugin=/plugin/codex/pinokio.js&prompt=", undefined, ""]) {
57
+ assert.equal(await RequestFile.pointAddressToSpec(same, dir), same)
58
+ }
59
+ })
60
+ })
61
+
62
+ test("creating an app hands back an address that carries the request line", async () => {
63
+ const Proto = require("../kernel/prototype")
64
+ await withFolder(async (home) => {
65
+ // a creation script that does what the real ones do with the words:
66
+ // save them as SPEC.md and put them in the address
67
+ const script = path.join(home, "prototype", "system", "default", "new", "index.js")
68
+ fs.mkdirSync(path.dirname(script), { recursive: true })
69
+ fs.writeFileSync(script, `
70
+ const fs = require("fs"), path = require("path")
71
+ module.exports = async (req) => {
72
+ fs.mkdirSync(req.cwd, { recursive: true })
73
+ if (req.input.aiPrompt) fs.writeFileSync(path.resolve(req.cwd, "SPEC.md"), req.input.aiPrompt + "\\n")
74
+ return { success: "/p/" + req.input.name + "/dev?plugin=/plugin/" + req.input.tool + "/pinokio.js&prompt=" + encodeURIComponent(req.input.aiPrompt) }
75
+ }`)
76
+ const kernel = { path: (...parts) => path.resolve(home, ...parts), require: async (file) => require(file) }
77
+ const log = console.log
78
+ console.log = () => {}
79
+ let made
80
+ let bare
81
+ try {
82
+ made = await new Proto(kernel).create({ cwd: path.join(home, "api"), params: { name: "radio", projectType: "default", startType: "new", aiPrompt: "make a radio\nwith a queue", tool: "codex" } }, () => {})
83
+ bare = await new Proto(kernel).create({ cwd: path.join(home, "api"), params: { name: "empty", projectType: "default", startType: "new", aiPrompt: "", tool: "codex" } }, () => {})
84
+ } finally {
85
+ console.log = log
86
+ }
87
+ const address = new URL(made.success, "http://x")
88
+ assert.equal(address.pathname, "/p/radio/dev")
89
+ assert.equal(address.searchParams.get("prompt"), LINE("SPEC.md"))
90
+ assert.equal(fs.readFileSync(path.join(home, "api", "radio", "SPEC.md"), "utf8"), "make a radio\nwith a queue\n")
91
+ assert.equal(new URL(bare.success, "http://x").searchParams.get("prompt"), "", "no words, nothing to point to")
92
+ })
93
+ })
@@ -0,0 +1,322 @@
1
+ // Mouse input from a terminal page to the program, in both formats a program
2
+ // can ask for, and across reopening a running session.
3
+ //
4
+ // SGR format (?1006h / ?1016h) text, sent on the terminal's data channel
5
+ // old format (no ?1006h) bytes, sent on the terminal's binary channel
6
+ //
7
+ // A reopened session's terminal is rebuilt from ShellStateSync's serialized
8
+ // state. The serializer restores which mouse events were asked for but not the
9
+ // format (xtermjs/xterm.js#6174, open), so ShellStateSync adds the format back.
10
+ // It reads it from the headless terminal's mouse service, which is not public
11
+ // API: the first tests here fail if a library upgrade moves it.
12
+ //
13
+ // A finger drag in a full-screen program is replayed by the page as wheel steps.
14
+ const assert = require('node:assert/strict')
15
+ const fs = require('node:fs')
16
+ const path = require('node:path')
17
+ const test = require('node:test')
18
+ const { JSDOM } = require('jsdom')
19
+
20
+ const { Terminal } = require('@xterm/headless')
21
+ const { SerializeAddon } = require('xterm-addon-serialize')
22
+ const pty = require('@homebridge/node-pty-prebuilt-multiarch')
23
+
24
+ const Shell = require('../kernel/shell')
25
+ const Shells = require('../kernel/shells')
26
+ const ShellStateSync = require('../kernel/shell_state_sync')
27
+
28
+ function terminal() {
29
+ const vt = new Terminal({ allowProposedApi: true, cols: 80, rows: 24 })
30
+ const vts = new SerializeAddon()
31
+ vt.loadAddon(vts)
32
+ return { vt, vts }
33
+ }
34
+
35
+ function write(vt, data) {
36
+ return new Promise((resolve) => vt.write(data, resolve))
37
+ }
38
+
39
+ // What a page that reopens the session ends up with: the program's output goes
40
+ // into the server-side terminal, its serialized state into a fresh terminal.
41
+ async function reopened(programOutput) {
42
+ const server = terminal()
43
+ const sync = new ShellStateSync({
44
+ vt: server.vt,
45
+ vts: server.vts,
46
+ stripAnsi: Shell.prototype.stripAnsi,
47
+ ready: true
48
+ })
49
+ await write(server.vt, programOutput)
50
+ const { buf, cleaned } = sync.refresh(true)
51
+ const page = terminal()
52
+ await write(page.vt, buf)
53
+ return {
54
+ tracking: page.vt.modes.mouseTrackingMode,
55
+ format: page.vt._core.coreMouseService.activeEncoding,
56
+ cleaned: cleaned.trim()
57
+ }
58
+ }
59
+
60
+ test('the headless terminal still exposes the mouse format where ShellStateSync reads it', async () => {
61
+ const { vt } = terminal()
62
+ assert.equal(vt._core.coreMouseService.activeEncoding, 'DEFAULT')
63
+ await write(vt, '\x1b[?1006h')
64
+ assert.equal(vt._core.coreMouseService.activeEncoding, 'SGR')
65
+ })
66
+
67
+ test('a reopened session keeps the SGR mouse format an agent TUI asked for', async () => {
68
+ const state = await reopened('\x1b[?1049h\x1b[?1003h\x1b[?1006hhello')
69
+ assert.deepEqual(state, { tracking: 'any', format: 'SGR', cleaned: 'hello' })
70
+ })
71
+
72
+ test('a reopened session keeps the SGR pixel mouse format', async () => {
73
+ const state = await reopened('\x1b[?1000h\x1b[?1016hhello')
74
+ assert.deepEqual(state, { tracking: 'vt200', format: 'SGR_PIXELS', cleaned: 'hello' })
75
+ })
76
+
77
+ test('a reopened session is not given a mouse format the program did not ask for', async () => {
78
+ assert.deepEqual(await reopened('\x1b[?1000hhello'), { tracking: 'vt200', format: 'DEFAULT', cleaned: 'hello' })
79
+ assert.deepEqual(await reopened('hello'), { tracking: 'none', format: 'DEFAULT', cleaned: 'hello' })
80
+ assert.deepEqual(
81
+ await reopened('\x1b[?1003h\x1b[?1006hhello\x1b[?1006l\x1b[?1003l'),
82
+ { tracking: 'none', format: 'DEFAULT', cleaned: 'hello' }
83
+ )
84
+ })
85
+
86
+ // wheel up at column 150, row 10 in the old format: ESC [ M, then one byte each
87
+ // for button (0x60), column (32 + 150 = 0xb6) and row (32 + 10 = 0x2a)
88
+ const OLD_FORMAT_REPORT = '\x1b[M\x60\xb6\x2a'
89
+ const OLD_FORMAT_BYTES = [0x1b, 0x5b, 0x4d, 0x60, 0xb6, 0x2a]
90
+
91
+ // The page side: server/public/terminal-input.js, called by every terminal page.
92
+ // The terminal here is a stand-in with the parts of the library's API it uses.
93
+ function page(t, { screen = 'normal', mouse = 'none' } = {}) {
94
+ const dom = new JSDOM('<div class="xterm"><div class="xterm-screen"></div></div>', { runScripts: 'outside-only' })
95
+ t.after(() => dom.window.close())
96
+ const { window } = dom
97
+ window.eval(fs.readFileSync(path.resolve(__dirname, '../server/public/terminal-input.js'), 'utf8'))
98
+ const element = window.document.querySelector('.xterm')
99
+ // 10 rows of 20px; a hidden terminal measures 0
100
+ const screenSize = { height: 200, measured: 0 }
101
+ Object.defineProperty(element.querySelector('.xterm-screen'), 'clientHeight', {
102
+ get() {
103
+ screenSize.measured += 1
104
+ return screenSize.height
105
+ }
106
+ })
107
+ const term = {
108
+ element,
109
+ rows: 10,
110
+ buffer: { active: { type: screen } },
111
+ modes: { mouseTrackingMode: mouse },
112
+ onBinary(handler) { term.binary = handler }
113
+ }
114
+ const wheel = []
115
+ element.addEventListener('wheel', (event) => wheel.push(event.deltaY))
116
+ const touch = (type, ...ys) => {
117
+ const event = new window.Event(type, { bubbles: true, cancelable: true })
118
+ event.touches = ys.map((clientY) => ({ clientX: 50, clientY }))
119
+ element.dispatchEvent(event)
120
+ return event
121
+ }
122
+ // a page with a shell and an open connection
123
+ const connection = { ws: { readyState: window.WebSocket.OPEN }, shell: 'shell-1' }
124
+ const attach = () => window.PinokioTerminalInput.attach(term, () => connection, () => connection.shell)
125
+ return { window, term, wheel, touch, attach, connection, screenSize }
126
+ }
127
+
128
+ test('a terminal page sends the binary channel to its shell, marked binary', (t) => {
129
+ const { window, term } = page(t)
130
+ const sentMessages = []
131
+ const state = { socket: null, shellId: null }
132
+ window.PinokioTerminalInput.attach(term, () => state.socket, () => state.shellId)
133
+
134
+ // before the page has a connection or a shell: nothing is sent, nothing opened
135
+ term.binary(OLD_FORMAT_REPORT)
136
+ // copied, because the message object is made inside the page's own context
137
+ state.socket = { ws: null, emit: (message) => sentMessages.push({ ...message }) }
138
+ state.shellId = 'shell-1'
139
+ term.binary(OLD_FORMAT_REPORT)
140
+ assert.deepEqual(sentMessages, [])
141
+
142
+ // still connecting (a reconnect): sending now would throw
143
+ state.socket.ws = { readyState: window.WebSocket.CONNECTING }
144
+ term.binary(OLD_FORMAT_REPORT)
145
+ assert.deepEqual(sentMessages, [])
146
+
147
+ state.socket.ws = { readyState: window.WebSocket.OPEN }
148
+ term.binary(OLD_FORMAT_REPORT)
149
+ assert.deepEqual(sentMessages, [{ key: OLD_FORMAT_REPORT, id: 'shell-1', binary: true }])
150
+ })
151
+
152
+ test('a finger drag in a full-screen program is replayed as one wheel step per row', (t) => {
153
+ const { wheel, touch, attach } = page(t, { screen: 'alternate' })
154
+ attach()
155
+ touch('touchstart', 300)
156
+ // 5px: not a row yet, but already taken from the browser, which would pan the page
157
+ assert.equal(touch('touchmove', 295).defaultPrevented, true)
158
+ assert.deepEqual(wheel, [])
159
+ // 65px up in all: three rows down the program's content, 5px carried over
160
+ touch('touchmove', 235)
161
+ assert.deepEqual(wheel, [1, 1, 1])
162
+ // back down past the start
163
+ touch('touchmove', 280)
164
+ assert.deepEqual(wheel, [1, 1, 1, -1, -1])
165
+ })
166
+
167
+ test('a finger drag scrolls a program that tracks the mouse on the normal screen', (t) => {
168
+ const { wheel, touch, attach } = page(t, { mouse: 'vt200' })
169
+ attach()
170
+ touch('touchstart', 300)
171
+ touch('touchmove', 260)
172
+ assert.deepEqual(wheel, [1, 1])
173
+ })
174
+
175
+ test('at a shell prompt a finger drag is left to the terminal and sends nothing', (t) => {
176
+ const { wheel, touch, attach, screenSize } = page(t)
177
+ attach()
178
+ touch('touchstart', 300)
179
+ assert.equal(touch('touchmove', 200).defaultPrevented, false)
180
+ // and costs nothing: the terminal is not measured while its scrollback scrolls
181
+ assert.equal(screenSize.measured, 0)
182
+ assert.deepEqual(wheel, [])
183
+ })
184
+
185
+ test('two fingers (a pinch) are not a scroll', (t) => {
186
+ const { wheel, touch, attach } = page(t, { screen: 'alternate' })
187
+ attach()
188
+ touch('touchstart', 300, 400)
189
+ touch('touchmove', 200, 400)
190
+ touch('touchstart', 300)
191
+ touch('touchmove', 250, 400)
192
+ touch('touchmove', 200)
193
+ assert.deepEqual(wheel, [])
194
+ })
195
+
196
+ // What can change while the finger is still down.
197
+ test('a drag stops being replayed when the program exits under the finger', (t) => {
198
+ const { term, wheel, touch, attach } = page(t, { screen: 'alternate' })
199
+ attach()
200
+ touch('touchstart', 300)
201
+ touch('touchmove', 260)
202
+ assert.deepEqual(wheel, [1, 1])
203
+ // back at the shell prompt: wheel steps here could reach the shell as arrow keys
204
+ term.buffer.active.type = 'normal'
205
+ assert.equal(touch('touchmove', 100).defaultPrevented, false)
206
+ term.buffer.active.type = 'alternate'
207
+ touch('touchmove', 40)
208
+ assert.deepEqual(wheel, [1, 1])
209
+ })
210
+
211
+ test('a drag that began at a shell prompt does not reach a program that opens under it', (t) => {
212
+ const { term, wheel, touch, attach } = page(t)
213
+ attach()
214
+ touch('touchstart', 300)
215
+ term.buffer.active.type = 'alternate'
216
+ assert.equal(touch('touchmove', 200).defaultPrevented, false)
217
+ assert.deepEqual(wheel, [])
218
+ })
219
+
220
+ test('a drag does not reach a shell that replaced the one it began on', (t) => {
221
+ const { wheel, touch, attach, connection } = page(t, { screen: 'alternate' })
222
+ attach()
223
+ touch('touchstart', 300)
224
+ touch('touchmove', 280)
225
+ assert.deepEqual(wheel, [1])
226
+ connection.shell = 'shell-2'
227
+ touch('touchmove', 200)
228
+ assert.deepEqual(wheel, [1])
229
+ })
230
+
231
+ test('a drag over a terminal that has been hidden is dropped', (t) => {
232
+ const { wheel, touch, attach, screenSize } = page(t, { screen: 'alternate' })
233
+ attach()
234
+ touch('touchstart', 300)
235
+ // no row height: the distance cannot be turned into rows
236
+ screenSize.height = 0
237
+ touch('touchmove', 200)
238
+ assert.deepEqual(wheel, [])
239
+ })
240
+
241
+ test('nothing is replayed while the connection is not open', (t) => {
242
+ const { window, wheel, touch, attach, connection } = page(t, { screen: 'alternate' })
243
+ attach()
244
+ connection.ws.readyState = window.WebSocket.CONNECTING
245
+ touch('touchstart', 300)
246
+ touch('touchmove', 200)
247
+ assert.deepEqual(wheel, [])
248
+
249
+ // lost while the finger is down: the rest of the drag is dropped too
250
+ connection.ws.readyState = window.WebSocket.OPEN
251
+ touch('touchstart', 300)
252
+ touch('touchmove', 280)
253
+ connection.ws.readyState = window.WebSocket.CONNECTING
254
+ touch('touchmove', 200)
255
+ assert.deepEqual(wheel, [1])
256
+ })
257
+
258
+ function shellsWith(session) {
259
+ const shells = Object.create(Shells.prototype)
260
+ shells.get = () => session
261
+ return shells
262
+ }
263
+
264
+ test('input from the binary channel reaches the shell as the same bytes', () => {
265
+ const received = []
266
+ const shells = shellsWith({ emit: (message) => received.push(message) })
267
+ shells.emit({ id: 'a', emit: OLD_FORMAT_REPORT, binary: true })
268
+ assert.equal(received.length, 1)
269
+ assert.ok(Buffer.isBuffer(received[0]))
270
+ assert.deepEqual([...received[0]], OLD_FORMAT_BYTES)
271
+ })
272
+
273
+ test('typed text and pastes are still passed on as text', () => {
274
+ const received = []
275
+ const shells = shellsWith({ emit: (message) => received.push(message) })
276
+ shells.emit({ id: 'a', emit: 'ls\r' })
277
+ shells.emit({ id: 'a', emit: 'pasted', paste: true })
278
+ assert.deepEqual(received, ['ls\r', '\x1b[200~pasted\x1b[201~'])
279
+ })
280
+
281
+ test('the shell writes bytes to the program unchanged', () => {
282
+ const written = []
283
+ const shell = Object.create(Shell.prototype)
284
+ shell.input = true
285
+ shell.ptyProcess = { write: (data) => written.push(data) }
286
+ shell.stateSync = { noteInput() {} }
287
+ shell.emit(Buffer.from(OLD_FORMAT_REPORT, 'binary'))
288
+ assert.equal(written.length, 1)
289
+ assert.deepEqual([...written[0]], OLD_FORMAT_BYTES)
290
+ })
291
+
292
+ // The pty library documents text input only. This is the check that bytes
293
+ // written to it arrive at the program one for one (as text, 0xb6 would arrive
294
+ // as the two bytes c2 b6).
295
+ test('a program receives an old-format mouse report byte for byte', { skip: process.platform === 'win32' }, async () => {
296
+ const output = await new Promise((resolve, reject) => {
297
+ // "ready" is printed once stty has put the terminal in raw mode
298
+ const child = pty.spawn('/bin/sh', ['-c', 'stty raw -echo; printf ready; head -c 6 | od -An -tx1'], {
299
+ name: 'xterm-color',
300
+ cols: 200,
301
+ rows: 30
302
+ })
303
+ let out = ''
304
+ const timer = setTimeout(() => {
305
+ child.kill()
306
+ reject(new Error(`timed out, output so far: ${JSON.stringify(out)}`))
307
+ }, 10000)
308
+ let written = false
309
+ child.onData((data) => {
310
+ out += data
311
+ if (!written && out.includes('ready')) {
312
+ written = true
313
+ child.write(Buffer.from(OLD_FORMAT_REPORT, 'binary'))
314
+ }
315
+ })
316
+ child.onExit(() => {
317
+ clearTimeout(timer)
318
+ resolve(out)
319
+ })
320
+ })
321
+ assert.equal(output.replace('ready', '').trim().split(/\s+/).join(' '), '1b 5b 4d 60 b6 2a')
322
+ })