pinokiod 8.3.10 → 8.3.12

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.
@@ -58,6 +58,22 @@ class ShellStateSync {
58
58
  const line = this.tail.replaceAll(/[\r\n]/g, "")
59
59
  return terminationPromptRe.test(line)
60
60
  }
61
+ // The serialized state restores which mouse events a program asked for
62
+ // (?1000h / ?1002h / ?1003h) but not how it asked for them to be written
63
+ // (?1006h SGR, ?1016h SGR pixels). A page that attaches to a running program
64
+ // from this state would then report the mouse in the old byte format, which
65
+ // the program is not reading, so the wheel and a finger drag would do nothing
66
+ // in a full-screen program such as an agent's TUI. The format the program
67
+ // chose is added back here. It is read from the terminal's mouse service,
68
+ // which is not public API: test/terminal-mouse-input.test.js fails if a
69
+ // library upgrade moves it.
70
+ mouseEncodingMode() {
71
+ const service = this.shell.vt._core.coreMouseService
72
+ const encoding = service ? service.activeEncoding : ""
73
+ if (encoding === "SGR") return "\x1b[?1006h"
74
+ if (encoding === "SGR_PIXELS") return "\x1b[?1016h"
75
+ return ""
76
+ }
61
77
  refresh(force = false) {
62
78
  const now = Date.now()
63
79
  const shouldRefresh = force ||
@@ -65,7 +81,7 @@ class ShellStateSync {
65
81
  !this.cachedBuf ||
66
82
  (now - this.lastStateSyncAt >= this.stateInterval)
67
83
  if (shouldRefresh) {
68
- this.cachedBuf = this.shell.vts.serialize()
84
+ this.cachedBuf = this.shell.vts.serialize() + this.mouseEncodingMode()
69
85
  this.cachedCleaned = this.shell.stripAnsi(this.cachedBuf)
70
86
  this.shell.state = this.cachedCleaned
71
87
  this.lastStateSyncAt = now
package/kernel/shells.js CHANGED
@@ -771,6 +771,17 @@ class Shells {
771
771
  } else {
772
772
  session.emit(payload)
773
773
  }
774
+ } else if (params.binary) {
775
+ const report = Buffer.from(String(params.emit), "binary")
776
+ // Legacy mouse input is ESC [ M followed by button, column and row bytes.
777
+ // Coordinates start at 1 and are encoded as value + 32. From column or
778
+ // row 96, Windows ConPTY's UTF-8 decoding can corrupt the position.
779
+ if (this.kernel.platform === "win32" && report.length === 6 &&
780
+ report[0] === 0x1b && report[1] === 0x5b && report[2] === 0x4d &&
781
+ (report[4] > 127 || report[5] > 127)) {
782
+ return true
783
+ }
784
+ session.emit(report)
774
785
  } else {
775
786
  session.emit(params.emit)
776
787
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pinokiod",
3
- "version": "8.3.10",
3
+ "version": "8.3.12",
4
4
  "description": "",
5
5
  "main": "index.js",
6
6
  "scripts": {
@@ -500,11 +500,18 @@ html.agent-bar-panel-open .agent-dock {
500
500
  .agent-bar .agent-dock__liststop i {
501
501
  font-size: 8px;
502
502
  }
503
- .agent-dock__listrow:hover .agent-dock__liststop,
504
503
  .agent-bar .agent-dock__liststop:focus-visible,
505
504
  .agent-bar .agent-dock__liststop[data-armed="true"] {
506
505
  display: inline-flex;
507
506
  }
507
+ /* Only where there is a pointer that can hover. On a touch screen a rule that
508
+ reveals something on :hover makes the first tap count as the hover, so the
509
+ row would need a second tap to open. Stop is in the session's own header. */
510
+ @media (hover: hover) {
511
+ .agent-dock__listrow:hover .agent-dock__liststop {
512
+ display: inline-flex;
513
+ }
514
+ }
508
515
 
509
516
  /* ---- a short message (something could not be done) ---- */
510
517
  .agent-dock__toast {
@@ -0,0 +1,220 @@
1
+ // Storage sweep: removes what closed windows left behind in localStorage.
2
+ //
3
+ // Every Pinokio window has an id (the `?session=` in its address). Its layout
4
+ // and its selected tabs are saved under that id so a reload brings them back:
5
+ // pinokio:layout:<id> the panes of the window (layout.js)
6
+ // pinokio:session:<id>:... selected tabs, split sizes (window_storage.js)
7
+ // Nothing removed these when a window was closed for good, so they piled up
8
+ // until the browser's limit for the site was reached and new saves failed.
9
+ //
10
+ // How a window's age is known:
11
+ // pinokio:seen:<id> when the window was last used, written here on
12
+ // load and refreshed while the window stays open
13
+ // the id itself ids made by layout.js end in their creation
14
+ // time; used for windows that have no stamp yet
15
+ // neither stamped as used now, so it gets the full period
16
+ //
17
+ // When it runs:
18
+ // - a moment after a page loads, at most once a day
19
+ // - when a save fails because storage is full: it sweeps at once and the
20
+ // save is tried again
21
+ //
22
+ // Only the three kinds of entries above are ever removed.
23
+ (() => {
24
+ if (window.PinokioStorageSweep) return;
25
+
26
+ let store;
27
+ try {
28
+ store = window.localStorage;
29
+ if (!store) return;
30
+ } catch (_) {
31
+ return;
32
+ }
33
+
34
+ const HOUR = 60 * 60 * 1000;
35
+ const DAY = 24 * HOUR;
36
+ const KEEP_MS = 30 * DAY; // a window unused for this long is removed
37
+ const SWEEP_EVERY_MS = DAY;
38
+ const STAMP_EVERY_MS = 12 * HOUR;
39
+
40
+ const LAYOUT = 'pinokio:layout:';
41
+ const SESSION = 'pinokio:session:';
42
+ const SEEN = 'pinokio:seen:';
43
+ const LAST_SWEEP = 'pinokio:sweep:last';
44
+
45
+ const rawSetItem = Storage.prototype.setItem;
46
+
47
+ function read(key) {
48
+ try {
49
+ return store.getItem(key);
50
+ } catch (_) {
51
+ return null;
52
+ }
53
+ }
54
+
55
+ // Writes made by the sweep itself never trigger another sweep.
56
+ function write(key, value) {
57
+ try {
58
+ rawSetItem.call(store, key, String(value));
59
+ return true;
60
+ } catch (_) {
61
+ return false;
62
+ }
63
+ }
64
+
65
+ function windowIdOf(key) {
66
+ if (typeof key !== 'string') return null;
67
+ if (key.startsWith(LAYOUT)) return key.slice(LAYOUT.length) || null;
68
+ if (key.startsWith(SEEN)) return key.slice(SEEN.length) || null;
69
+ if (key.startsWith(SESSION)) return key.slice(SESSION.length).split(':')[0] || null;
70
+ return null;
71
+ }
72
+
73
+ // The id of the window this page is shown in: its own address, or the
74
+ // address of the page it is a pane of.
75
+ function currentWindowId() {
76
+ const frames = [window];
77
+ try { if (window.parent && window.parent !== window) frames.push(window.parent); } catch (_) {}
78
+ try { if (window.top && frames.indexOf(window.top) < 0) frames.push(window.top); } catch (_) {}
79
+ for (const frame of frames) {
80
+ try {
81
+ const fromUrl = new URL(frame.location.href).searchParams.get('session');
82
+ if (fromUrl) return fromUrl;
83
+ const layout = frame.PinokioLayout;
84
+ const fromLayout = layout && typeof layout.getSessionId === 'function' ? layout.getSessionId() : null;
85
+ if (fromLayout) return fromLayout;
86
+ } catch (_) {}
87
+ }
88
+ return null;
89
+ }
90
+
91
+ // layout.js makes ids as 'f_' + random letters + the time in base 36.
92
+ function createdAt(id, now) {
93
+ const match = /^f_[a-z0-9]*([a-z0-9]{8})$/.exec(id);
94
+ if (!match) return 0;
95
+ const time = parseInt(match[1], 36);
96
+ return time > Date.UTC(2020, 0, 1) && time < now + DAY ? time : 0;
97
+ }
98
+
99
+ // Every window that has entries: its keys and when it was last used
100
+ // (0 when that cannot be told).
101
+ function collect(now) {
102
+ const windows = new Map();
103
+ for (let i = 0; i < store.length; i += 1) {
104
+ const key = store.key(i);
105
+ const id = windowIdOf(key);
106
+ if (!id) continue;
107
+ let entry = windows.get(id);
108
+ if (!entry) {
109
+ entry = { id, keys: [], seen: 0 };
110
+ windows.set(id, entry);
111
+ }
112
+ entry.keys.push(key);
113
+ if (key.startsWith(SEEN)) entry.seen = Number(store.getItem(key)) || 0;
114
+ }
115
+ windows.forEach((entry) => {
116
+ entry.used = entry.seen || createdAt(entry.id, now);
117
+ });
118
+ return windows;
119
+ }
120
+
121
+ function removeWindow(entry) {
122
+ entry.keys.forEach((key) => {
123
+ try { store.removeItem(key); } catch (_) {}
124
+ });
125
+ return entry.keys.length;
126
+ }
127
+
128
+ // Marks this window as used now.
129
+ function touch() {
130
+ const id = currentWindowId();
131
+ if (!id) return;
132
+ const now = Date.now();
133
+ if (now - (Number(read(SEEN + id)) || 0) < STAMP_EVERY_MS) return;
134
+ write(SEEN + id, now);
135
+ }
136
+
137
+ // Removes the entries of every window unused for longer than the period.
138
+ // Returns how many entries were removed.
139
+ function sweep(options) {
140
+ const force = !!(options && options.force);
141
+ const now = Date.now();
142
+ if (!force && now - (Number(read(LAST_SWEEP)) || 0) < SWEEP_EVERY_MS) return 0;
143
+ let removed = 0;
144
+ try {
145
+ const current = currentWindowId();
146
+ const undated = [];
147
+ collect(now).forEach((entry) => {
148
+ if (entry.id === current) return;
149
+ if (!entry.used) undated.push(entry.id);
150
+ else if (now - entry.used > KEEP_MS) removed += removeWindow(entry);
151
+ });
152
+ // after the removals, so there is room to write the stamps
153
+ undated.forEach((id) => write(SEEN + id, now));
154
+ touch();
155
+ write(LAST_SWEEP, now);
156
+ } catch (_) {}
157
+ return removed;
158
+ }
159
+
160
+ // Storage is full: sweep now. If that frees nothing, remove the quarter of
161
+ // the other windows that were used longest ago.
162
+ function makeRoom() {
163
+ const removed = sweep({ force: true });
164
+ if (removed) return removed;
165
+ let dropped = 0;
166
+ try {
167
+ const current = currentWindowId();
168
+ const others = Array.from(collect(Date.now()).values())
169
+ .filter((entry) => entry.id !== current)
170
+ .sort((a, b) => a.used - b.used);
171
+ others.slice(0, Math.ceil(others.length / 4)).forEach((entry) => {
172
+ dropped += removeWindow(entry);
173
+ });
174
+ } catch (_) {}
175
+ return dropped;
176
+ }
177
+
178
+ function isFull(error) {
179
+ return !!error && (error.name === 'QuotaExceededError' || error.name === 'NS_ERROR_DOM_QUOTA_REACHED' || error.code === 22);
180
+ }
181
+
182
+ // A save that fails because storage is full makes room and is tried again.
183
+ let makingRoom = false;
184
+ Storage.prototype.setItem = function setItem(key, value) {
185
+ try {
186
+ return rawSetItem.call(this, key, value);
187
+ } catch (error) {
188
+ if (this !== store || makingRoom || !isFull(error)) throw error;
189
+ makingRoom = true;
190
+ try {
191
+ for (let attempt = 0; attempt < 3; attempt += 1) {
192
+ if (!makeRoom()) break;
193
+ try {
194
+ return rawSetItem.call(this, key, value);
195
+ } catch (again) {
196
+ if (!isFull(again)) throw again;
197
+ }
198
+ }
199
+ } finally {
200
+ makingRoom = false;
201
+ }
202
+ throw error;
203
+ }
204
+ };
205
+
206
+ function tick() {
207
+ touch();
208
+ sweep();
209
+ }
210
+
211
+ window.PinokioStorageSweep = { sweep, makeRoom, touch };
212
+
213
+ const start = () => {
214
+ if (typeof window.requestIdleCallback === 'function') window.requestIdleCallback(tick, { timeout: 5000 });
215
+ else window.setTimeout(tick, 2000);
216
+ window.setInterval(tick, HOUR);
217
+ };
218
+ if (document.readyState === 'complete') start();
219
+ else window.addEventListener('load', start, { once: true });
220
+ })();
@@ -1961,6 +1961,18 @@ body.columns .containers {
1961
1961
  */
1962
1962
  overflow: auto;
1963
1963
  }
1964
+ /* The terminal takes the room its container has. "height: 100%" alone is read
1965
+ by iPhone browsers as the height of the whole page, so the terminal counted
1966
+ more rows than fit and its last rows (the prompt) sat below the visible
1967
+ part, out of reach once the keyboard is up. */
1968
+ body > .terminal-container {
1969
+ display: flex;
1970
+ flex-direction: column;
1971
+ }
1972
+ body > .terminal-container > #terminal {
1973
+ flex: 1 1 0;
1974
+ min-height: 0;
1975
+ }
1964
1976
  .terminal-container #terminal-resize {
1965
1977
  position: absolute;
1966
1978
  bottom: 10px;
@@ -2055,6 +2067,13 @@ body.columns .containers {
2055
2067
  font-variant-ligatures: none;
2056
2068
  font-feature-settings: "liga" 0, "clig" 0, "calt" 0, "rlig" 0;
2057
2069
  }
2070
+ /* A finger drag that starts on text keeps scrolling. A touch belongs to the
2071
+ element it started on, and the terminal replaces a row's text elements when
2072
+ it redraws, so a drag that started on one stopped after the first line.
2073
+ With this the touch lands on the screen behind the rows, which stays. */
2074
+ .xterm .xterm-rows {
2075
+ pointer-events: none;
2076
+ }
2058
2077
  .xterm {
2059
2078
  padding: 0 10px !important;
2060
2079
  /*
@@ -0,0 +1,79 @@
1
+ // Terminal input that the terminal library (xterm.js) does not send to the
2
+ // shell by itself. Every page with a terminal you can type in calls, once per
3
+ // terminal, after it is opened:
4
+ //
5
+ // PinokioTerminalInput.attach(term, () => socket, () => shell_id)
6
+ //
7
+ // 1. Bytes. Typing and pastes come as text (onData), which the pages already
8
+ // send. Mouse reports in the old format, used when a program tracks the
9
+ // mouse without asking for the SGR format, come as bytes on a second channel
10
+ // (onBinary), one byte per character. They are sent marked "binary", so the
11
+ // server writes them to the program as bytes.
12
+ //
13
+ // 2. Finger scrolling of full-screen programs. Under a finger the library
14
+ // scrolls only its own scrollback. When the program owns the screen
15
+ // (alternate screen) or tracks the mouse there is no scrollback to move, so
16
+ // a drag is replayed as wheel steps, one per row. The library turns those
17
+ // into what the program reads, exactly as it does for a real wheel: mouse
18
+ // reports, or arrow keys.
19
+ //
20
+ // The socket and shell id are read each time: pages create both after the terminal.
21
+ (function (window) {
22
+ 'use strict'
23
+
24
+ if (window.PinokioTerminalInput) return
25
+
26
+ function attach(term, getSocket, getShellId) {
27
+ // The shell that input goes to right now, or null. It must exist, and the
28
+ // connection must already be open: a send while it is still connecting (a
29
+ // reconnect) throws, and nothing here opens one.
30
+ const target = () => {
31
+ const socket = getSocket()
32
+ return (socket && socket.ws && socket.ws.readyState === window.WebSocket.OPEN && getShellId()) || null
33
+ }
34
+
35
+ term.onBinary((data) => {
36
+ const id = target()
37
+ if (id) getSocket().emit({ key: data, id, binary: true })
38
+ })
39
+
40
+ const programScrolls = () => term.buffer.active.type === 'alternate' || term.modes.mouseTrackingMode !== 'none'
41
+ // A drag belongs to the shell and program it started on. Any other touch is
42
+ // left to the library, which scrolls its scrollback.
43
+ let drag = null
44
+ term.element.addEventListener('touchstart', (event) => {
45
+ const shell = event.touches.length === 1 && programScrolls() && target()
46
+ drag = shell ? { shell, y: event.touches[0].clientY, pending: 0 } : null
47
+ }, { passive: true })
48
+ term.element.addEventListener('touchmove', (event) => {
49
+ if (!drag) return
50
+ const rowHeight = term.element.querySelector('.xterm-screen').clientHeight / term.rows
51
+ // Dropped if anything changed while the finger was down: a second finger,
52
+ // the program exited, the terminal was hidden (no row height), or the
53
+ // shell was replaced or its connection lost.
54
+ if (event.touches.length !== 1 || !programScrolls() || !rowHeight || target() !== drag.shell) {
55
+ drag = null
56
+ return
57
+ }
58
+ // from the first move on, or the browser takes the drag to pan the page
59
+ if (event.cancelable) event.preventDefault()
60
+ const touch = event.touches[0]
61
+ drag.pending += drag.y - touch.clientY
62
+ drag.y = touch.clientY
63
+ const rows = Math.trunc(drag.pending / rowHeight)
64
+ drag.pending -= rows * rowHeight
65
+ for (let i = 0; i < Math.abs(rows); i++) {
66
+ term.element.dispatchEvent(new window.WheelEvent('wheel', {
67
+ bubbles: true,
68
+ cancelable: true,
69
+ deltaMode: 1, // lines
70
+ deltaY: Math.sign(rows),
71
+ clientX: touch.clientX,
72
+ clientY: touch.clientY
73
+ }))
74
+ }
75
+ }, { passive: false })
76
+ }
77
+
78
+ window.PinokioTerminalInput = { attach }
79
+ })(window)
package/server/socket.js CHANGED
@@ -392,7 +392,8 @@ class Socket {
392
392
  this.parent.kernel.shell.emit({
393
393
  id: keyId,
394
394
  emit: req.key,
395
- paste: req.paste
395
+ paste: req.paste,
396
+ binary: req.binary === true
396
397
  })
397
398
  } else if (req.resize && req.id) {
398
399
  const targetId = this.shell_to_path[req.id] || req.id
@@ -8375,6 +8375,7 @@ body.dark .pinokio-custom-terminal-header {
8375
8375
  </script>
8376
8376
  <link rel="stylesheet" href="/agent-bar.css">
8377
8377
  <link rel="stylesheet" href="/agent-bar-app.css">
8378
+ <script src="/storage-sweep.js"></script>
8378
8379
  <script src="/agent-bar.js" data-agent-bar="true"></script>
8379
8380
  <script src="/agent-bar-app.js" data-agent-bar-app="true"></script>
8380
8381
  <link rel="stylesheet" href="/agent-bar-panel.css">
@@ -1497,6 +1497,7 @@ body.dark .ace-editor {
1497
1497
  <script src="/report.js"></script>
1498
1498
  <script src="/normalize.js"></script>
1499
1499
  <script src="/Socket.js"></script>
1500
+ <script src="/terminal-input.js"></script>
1500
1501
  <script src="/resizeSync.js"></script>
1501
1502
  <script src="/terminal-settings.js"></script>
1502
1503
  <script src="/pinokio-touch.js"></script>
@@ -2685,6 +2686,8 @@ const createTerm = async (_theme) => {
2685
2686
  })
2686
2687
  }
2687
2688
  });
2689
+ // input the terminal library does not send by itself (see terminal-input.js)
2690
+ window.PinokioTerminalInput.attach(term, () => socket, () => shell_id)
2688
2691
 
2689
2692
  let observer = new ResizeObserver(() => {
2690
2693
  fitAddon.fit()
@@ -500,6 +500,7 @@ body.install-page #terminal .xterm {
500
500
  <script src="/xterm-addon-web-links.js"></script>
501
501
  <script src="/xterm-theme.js"></script>
502
502
  <script src="/Socket.js"></script>
503
+ <script src="/terminal-input.js"></script>
503
504
  <script src="/terminal-settings.js"></script>
504
505
  <script src="/pinokio-touch.js"></script>
505
506
  <!--
@@ -846,6 +847,8 @@ document.addEventListener("DOMContentLoaded", async () => {
846
847
  })
847
848
  }
848
849
  })
850
+ // input the terminal library does not send by itself (see terminal-input.js)
851
+ window.PinokioTerminalInput.attach(term, () => socket, () => shell_id)
849
852
  let observer = new ResizeObserver(() => {
850
853
  fitAddon.fit()
851
854
  });
@@ -13,7 +13,7 @@
13
13
  --layout-dragger-bg: var(--layout-background);
14
14
  --layout-dragger-border: rgba(15, 23, 42, 0.06);
15
15
  --layout-shadow: rgba(0, 0, 0, 0.06);
16
- --layout-viewport-height: 100vh;
16
+ --layout-viewport-height: 100%;
17
17
  --layout-dragger-height: 0px;
18
18
  color-scheme: light dark;
19
19
  }
@@ -63,10 +63,17 @@
63
63
  color: #f3f3f3;
64
64
  }
65
65
 
66
+ /* The panes fill the part of the window that can be seen. That is the whole
67
+ window, except while a phone's on-screen keyboard is up: the keyboard
68
+ covers the bottom of the window without making it any smaller, and the
69
+ browser may also slide the page up under it. The script below measures the
70
+ part left visible (its height and where it starts). Using the height
71
+ without the start is what left an empty band above the keyboard. */
66
72
  #layout-root {
67
73
  position: relative;
74
+ top: var(--layout-viewport-top, 0px);
68
75
  width: 100%;
69
- height: calc(100% - var(--layout-dragger-height, 0px));
76
+ height: calc(var(--layout-viewport-height) - var(--layout-dragger-height, 0px));
70
77
  background: var(--layout-background);
71
78
  overflow: hidden;
72
79
  }
@@ -129,19 +136,37 @@
129
136
  (function () {
130
137
  const root = document.documentElement;
131
138
  let lastViewportHeight = null;
139
+ let lastViewportTop = null;
132
140
  const updateViewportHeight = () => {
133
141
  const viewport = window.visualViewport;
142
+ // Pinch-zoomed in: the visible part is then a magnified piece of the page,
143
+ // not what a keyboard leaves free. The panes fill the window, as they do
144
+ // with no measurement.
145
+ if (viewport && Math.abs(viewport.scale - 1) > 0.01) {
146
+ if (lastViewportHeight !== null) {
147
+ lastViewportHeight = null;
148
+ root.style.removeProperty('--layout-viewport-height');
149
+ root.style.removeProperty('--layout-viewport-top');
150
+ window.dispatchEvent(new CustomEvent('pinokio:viewport-change'));
151
+ }
152
+ return;
153
+ }
134
154
  const height = viewport ? viewport.height : window.innerHeight;
135
155
  if (!height || !Number.isFinite(height)) {
136
156
  return;
137
157
  }
158
+ // where the visible part starts, in the page's own coordinates
159
+ const top = viewport ? viewport.pageTop : 0;
138
160
  const clampedHeight = Math.max(0, height);
139
161
  const roundedHeight = Number(clampedHeight.toFixed(2));
140
- if (lastViewportHeight === roundedHeight) {
162
+ const roundedTop = Number(Math.max(0, top || 0).toFixed(2));
163
+ if (lastViewportHeight === roundedHeight && lastViewportTop === roundedTop) {
141
164
  return;
142
165
  }
143
166
  lastViewportHeight = roundedHeight;
167
+ lastViewportTop = roundedTop;
144
168
  root.style.setProperty('--layout-viewport-height', `${roundedHeight}px`);
169
+ root.style.setProperty('--layout-viewport-top', `${roundedTop}px`);
145
170
  window.dispatchEvent(new CustomEvent('pinokio:viewport-change', {
146
171
  detail: { height: roundedHeight },
147
172
  }));
@@ -181,5 +206,6 @@
181
206
  <script src="/Socket.js"></script>
182
207
  <script src="/common.js"></script>
183
208
  <script src="/layout.js"></script>
209
+ <script src="/storage-sweep.js"></script>
184
210
  </body>
185
211
  </html>
@@ -2,6 +2,7 @@
2
2
  const sidebarSelected = (typeof selected !== "undefined" && selected) ? String(selected) : "";
3
3
  %>
4
4
  <link rel="stylesheet" href="/agent-bar.css">
5
+ <script src="/storage-sweep.js"></script>
5
6
  <script src="/agent-bar.js" data-agent-bar="true"></script>
6
7
  <link rel="stylesheet" href="/agent-bar-panel.css">
7
8
  <script src="/agent-bar-panel.js" data-agent-bar-panel="true"></script>
@@ -14,6 +14,7 @@
14
14
  <script src="/xterm-addon-search-bar.js"></script>
15
15
  <script src="/sweetalert2.js"></script>
16
16
  <script src="/Socket.js"></script>
17
+ <script src="/terminal-input.js"></script>
17
18
  <script src="/resizeSync.js"></script>
18
19
  <script src="/terminal-settings.js"></script>
19
20
  <script src="/pinokio-touch.js"></script>
@@ -287,6 +288,8 @@ const createTerm = async (_theme) => {
287
288
  })
288
289
  }
289
290
  });
291
+ // input the terminal library does not send by itself (see terminal-input.js)
292
+ window.PinokioTerminalInput.attach(term, () => socket, () => shell_id)
290
293
 
291
294
  let observer = new ResizeObserver(() => {
292
295
  fitAddon.fit()
@@ -981,6 +981,7 @@ body.dark .appcanvas {
981
981
  <script src="/report.js"></script>
982
982
  <script src="/normalize.js"></script>
983
983
  <script src="/Socket.js"></script>
984
+ <script src="/terminal-input.js"></script>
984
985
  <script src="/resizeSync.js"></script>
985
986
  <script src="/terminal-settings.js"></script>
986
987
  <script src="/pinokio-touch.js"></script>
@@ -1619,6 +1620,8 @@ async function displayResults(config) {
1619
1620
  })
1620
1621
  }
1621
1622
  });
1623
+ // input the terminal library does not send by itself (see terminal-input.js)
1624
+ window.PinokioTerminalInput.attach(term, () => socket, () => shell_id)
1622
1625
  const fitAddon = new FitAddon.FitAddon();
1623
1626
  term.loadAddon(fitAddon);
1624
1627
  fitAddon.fit();
@@ -14,6 +14,7 @@
14
14
  <script src="/xterm-addon-search-bar.js"></script>
15
15
  <script src="/sweetalert2.js"></script>
16
16
  <script src="/Socket.js"></script>
17
+ <script src="/terminal-input.js"></script>
17
18
  <script src="/resizeSync.js"></script>
18
19
  <script src="/terminal_input_tracker.js"></script>
19
20
  <script src="/terminal_input_utils.js"></script>
@@ -1763,6 +1764,8 @@ document.addEventListener("DOMContentLoaded", async () => {
1763
1764
  this.captureTextInput(data)
1764
1765
  }
1765
1766
  })
1767
+ // input the terminal library does not send by itself (see terminal-input.js)
1768
+ window.PinokioTerminalInput.attach(term, () => this.socket, () => shell_id)
1766
1769
 
1767
1770
  const fitAddon = new FitAddon.FitAddon();
1768
1771
  // const searchAddon = new SearchAddon.SearchAddon();
@@ -14,6 +14,7 @@
14
14
  <script src="/xterm-addon-search-bar.js"></script>
15
15
  <script src="/sweetalert2.js"></script>
16
16
  <script src="/Socket.js"></script>
17
+ <script src="/terminal-input.js"></script>
17
18
  <script src="/resizeSync.js"></script>
18
19
  <script src="/terminal_input_tracker.js"></script>
19
20
  <script src="/terminal_input_utils.js"></script>
@@ -3219,6 +3220,8 @@ document.addEventListener("DOMContentLoaded", async () => {
3219
3220
  this.captureTextInput(data)
3220
3221
  }
3221
3222
  })
3223
+ // input the terminal library does not send by itself (see terminal-input.js)
3224
+ window.PinokioTerminalInput.attach(term, () => this.socket, () => shell_id)
3222
3225
 
3223
3226
  const fitAddon = new FitAddon.FitAddon();
3224
3227
  // const searchAddon = new SearchAddon.SearchAddon();
@@ -0,0 +1,125 @@
1
+ // The layout shell (server/views/layout.ejs, the page at "/") and a phone's
2
+ // on-screen keyboard.
3
+ //
4
+ // A keyboard covers the bottom of the window without making the window smaller,
5
+ // and the browser may slide the page up under it. The shell measures the part
6
+ // left visible (window.visualViewport) and its panes must fill exactly that
7
+ // part, so a terminal's last rows (an agent's input line) stay above the keyboard.
8
+ //
9
+ // History this guards: the measurement was added in Nov 2025 using the height
10
+ // only, which left an empty band above the keyboard when the page had slid up;
11
+ // the fix for the band stopped using the measurement at all, so the bottom of
12
+ // every pane was hidden under the keyboard again.
13
+ const assert = require('node:assert/strict')
14
+ const fs = require('node:fs')
15
+ const path = require('node:path')
16
+ const test = require('node:test')
17
+ const ejs = require('ejs')
18
+ const { JSDOM } = require('jsdom')
19
+
20
+ const filename = path.resolve(__dirname, '../server/views/layout.ejs')
21
+ const template = fs.readFileSync(filename, 'utf8')
22
+
23
+ // a phone window with no keyboard up
24
+ function fullWindow() {
25
+ return { height: 812, offsetTop: 0, pageTop: 0, scale: 1, addEventListener() {} }
26
+ }
27
+
28
+ function shell(t, viewport) {
29
+ const html = ejs.render(template, {
30
+ theme: 'dark',
31
+ agent: 'browser',
32
+ platform: 'darwin',
33
+ initialPath: '/home',
34
+ defaultPath: '/home',
35
+ sessionId: null
36
+ }, { filename })
37
+ const frames = []
38
+ const changes = []
39
+ const dom = new JSDOM(html, {
40
+ url: 'http://127.0.0.1:42000/',
41
+ // inline scripts only: Socket.js, common.js and layout.js are not loaded
42
+ runScripts: 'dangerously',
43
+ beforeParse(window) {
44
+ window.requestAnimationFrame = (callback) => frames.push(callback)
45
+ window.visualViewport = viewport
46
+ window.addEventListener('pinokio:viewport-change', (event) => changes.push(event.detail))
47
+ }
48
+ })
49
+ t.after(() => dom.window.close())
50
+ const { window } = dom
51
+ const style = window.document.documentElement.style
52
+ return {
53
+ window,
54
+ changes,
55
+ // what the browser does when the keyboard moves: an event, then a frame
56
+ resize() {
57
+ window.dispatchEvent(new window.Event('resize'))
58
+ frames.splice(0).forEach((callback) => callback())
59
+ },
60
+ measured: () => ({
61
+ height: style.getPropertyValue('--layout-viewport-height'),
62
+ top: style.getPropertyValue('--layout-viewport-top')
63
+ })
64
+ }
65
+ }
66
+
67
+ test('the panes are sized and placed by the measured visible part of the window', () => {
68
+ const css = template.slice(template.indexOf('#layout-root {'), template.indexOf('}', template.indexOf('#layout-root {')))
69
+ assert.match(css, /height:\s*calc\(var\(--layout-viewport-height\)/)
70
+ assert.match(css, /top:\s*var\(--layout-viewport-top/)
71
+ })
72
+
73
+ test('with the keyboard up, the visible part is what is left above it', (t) => {
74
+ const viewport = fullWindow()
75
+ const page = shell(t, viewport)
76
+ assert.deepEqual(page.measured(), { height: '812px', top: '0px' })
77
+
78
+ viewport.height = 470
79
+ page.resize()
80
+ assert.deepEqual(page.measured(), { height: '470px', top: '0px' })
81
+ assert.equal(page.changes.at(-1).height, 470)
82
+
83
+ viewport.height = 812
84
+ page.resize()
85
+ assert.deepEqual(page.measured(), { height: '812px', top: '0px' })
86
+ })
87
+
88
+ test('when the browser slides the page up under the keyboard, the panes follow', (t) => {
89
+ const viewport = fullWindow()
90
+ const page = shell(t, viewport)
91
+ Object.assign(viewport, { height: 470, offsetTop: 120, pageTop: 120 })
92
+ page.resize()
93
+ assert.deepEqual(page.measured(), { height: '470px', top: '120px' })
94
+
95
+ // only the position changes: still followed
96
+ Object.assign(viewport, { offsetTop: 40, pageTop: 40 })
97
+ page.resize()
98
+ assert.deepEqual(page.measured(), { height: '470px', top: '40px' })
99
+ })
100
+
101
+ test('pinch zoom is not mistaken for a keyboard', (t) => {
102
+ const viewport = fullWindow()
103
+ const page = shell(t, viewport)
104
+ Object.assign(viewport, { height: 470, offsetTop: 120, pageTop: 120 })
105
+ page.resize()
106
+ assert.deepEqual(page.measured(), { height: '470px', top: '120px' })
107
+
108
+ // zoomed in: no measurement, so the panes fill the window as the stylesheet says
109
+ Object.assign(viewport, { height: 235, offsetTop: 300, pageTop: 300, scale: 2 })
110
+ page.resize()
111
+ assert.deepEqual(page.measured(), { height: '', top: '' })
112
+ const changes = page.changes.length
113
+ page.resize()
114
+ assert.equal(page.changes.length, changes)
115
+
116
+ // zoomed back out: measured again
117
+ Object.assign(viewport, { height: 470, offsetTop: 120, pageTop: 120, scale: 1 })
118
+ page.resize()
119
+ assert.deepEqual(page.measured(), { height: '470px', top: '120px' })
120
+ })
121
+
122
+ test('without a visual viewport the window height is used', (t) => {
123
+ const page = shell(t, undefined)
124
+ assert.deepEqual(page.measured(), { height: `${page.window.innerHeight}px`, top: '0px' })
125
+ })
@@ -448,6 +448,7 @@ test("successful runtime cleanup resubmits the interrupted install", async (t) =
448
448
  window.WebLinksAddon = { WebLinksAddon: class {} }
449
449
  window.xtermTheme = { FrontEndDelight: {} }
450
450
  window.PinokioTouch = { bindTerminalFocus() {} }
451
+ window.PinokioTerminalInput = { attach() {} }
451
452
  window.PinokioPathRemoval = {
452
453
  show: async ({ retry }) => await retry(),
453
454
  tryRemove: async (payload) => {
@@ -522,6 +523,7 @@ test("fresh install shows removal status and waits for cleanup before starting",
522
523
  window.WebLinksAddon = { WebLinksAddon: class {} }
523
524
  window.xtermTheme = { FrontEndDelight: {} }
524
525
  window.PinokioTouch = { bindTerminalFocus() {} }
526
+ window.PinokioTerminalInput = { attach() {} }
525
527
  window.PinokioPathRemoval = {
526
528
  remove: async () => {
527
529
  cleanupStarted = true
@@ -0,0 +1,335 @@
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, platform = process.platform) {
259
+ const shells = new Shells({ platform })
260
+ shells.get = () => session
261
+ return shells
262
+ }
263
+
264
+ test('Unix shells receive the original legacy mouse bytes even at wide columns', () => {
265
+ for (const platform of ['darwin', 'linux']) {
266
+ const received = []
267
+ const shells = shellsWith({ emit: (message) => received.push(message) }, platform)
268
+ shells.emit({ id: 'a', emit: OLD_FORMAT_REPORT, binary: true })
269
+ assert.deepEqual(received, [Buffer.from(OLD_FORMAT_BYTES)])
270
+ }
271
+ })
272
+
273
+ test('Windows drops only legacy mouse reports beyond column or row 95', () => {
274
+ const received = []
275
+ const shells = shellsWith({ emit: (message) => received.push(message) }, 'win32')
276
+ const lastValid = '\x1b[M\x60\x7f\x7f'
277
+ const otherBinary = '\x1b[X\x60\x80\x80'
278
+ for (const emit of [lastValid, '\x1b[M\x60\x80\x7f', '\x1b[M\x60\x7f\x80', otherBinary]) {
279
+ assert.equal(shells.emit({ id: 'a', emit, binary: true }), true)
280
+ }
281
+ const sgr = '\x1b[<64;164;5M'
282
+ shells.emit({ id: 'a', emit: sgr })
283
+ assert.deepEqual(received, [Buffer.from(lastValid, 'binary'), Buffer.from(otherBinary, 'binary'), sgr])
284
+ })
285
+
286
+ test('typed text and pastes are still passed on as text', () => {
287
+ const received = []
288
+ const shells = shellsWith({ emit: (message) => received.push(message) })
289
+ shells.emit({ id: 'a', emit: 'ls\r' })
290
+ shells.emit({ id: 'a', emit: 'pasted', paste: true })
291
+ assert.deepEqual(received, ['ls\r', '\x1b[200~pasted\x1b[201~'])
292
+ })
293
+
294
+ test('the shell writes bytes to the program unchanged', () => {
295
+ const written = []
296
+ const shell = Object.create(Shell.prototype)
297
+ shell.input = true
298
+ shell.ptyProcess = { write: (data) => written.push(data) }
299
+ shell.stateSync = { noteInput() {} }
300
+ shell.emit(Buffer.from(OLD_FORMAT_REPORT, 'binary'))
301
+ assert.equal(written.length, 1)
302
+ assert.deepEqual([...written[0]], OLD_FORMAT_BYTES)
303
+ })
304
+
305
+ // The pty library documents text input only. This is the check that bytes
306
+ // written to it arrive at the program one for one (as text, 0xb6 would arrive
307
+ // as the two bytes c2 b6).
308
+ test('a program receives an old-format mouse report byte for byte', { skip: process.platform === 'win32' }, async () => {
309
+ const output = await new Promise((resolve, reject) => {
310
+ // "ready" is printed once stty has put the terminal in raw mode
311
+ const child = pty.spawn('/bin/sh', ['-c', 'stty raw -echo; printf ready; head -c 6 | od -An -tx1'], {
312
+ name: 'xterm-color',
313
+ cols: 200,
314
+ rows: 30
315
+ })
316
+ let out = ''
317
+ const timer = setTimeout(() => {
318
+ child.kill()
319
+ reject(new Error(`timed out, output so far: ${JSON.stringify(out)}`))
320
+ }, 10000)
321
+ let written = false
322
+ child.onData((data) => {
323
+ out += data
324
+ if (!written && out.includes('ready')) {
325
+ written = true
326
+ child.write(Buffer.from(OLD_FORMAT_REPORT, 'binary'))
327
+ }
328
+ })
329
+ child.onExit(() => {
330
+ clearTimeout(timer)
331
+ resolve(out)
332
+ })
333
+ })
334
+ assert.equal(output.replace('ready', '').trim().split(/\s+/).join(' '), '1b 5b 4d 60 b6 2a')
335
+ })