jsgotty 1.1.3 → 1.1.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.en.md CHANGED
@@ -40,11 +40,14 @@
40
40
  - for copying text on mobile devices
41
41
 
42
42
  ## Intro
43
+ - Expose your terminal through browsers, CLI clients, and modern web protocols.
43
44
  - This is a GoTTY-compatible server rewritten in JavaScript / Bun.
44
45
  - It is based on the original GoTTY code, with most of the new code generated by Codex.
45
46
  - It includes a frontend and WebTTY protocol implementation adjusted for `jsgotty`.
46
47
  - Original repository:
47
48
  - https://github.com/sorenisanerd/gotty
49
+ - .
50
+ - Keywords: Terminal, TTY, Browser, CLI Client, Session management, Kitty graphics protocol, ZMODEM
48
51
 
49
52
  ### Features
50
53
  - Resumable reconnect: after the browser disconnects, you can reconnect to the original shell / PTY with a reconnect token instead of spawning a new shell.
@@ -53,6 +56,7 @@
53
56
  * See the detailed mode explanation below.
54
57
  - Kitty Graphics Protocol: displays inline terminal images.
55
58
  * For example, `bun viu.mjs 1.png` shows an image directly in the terminal.
59
+ * Set `JSGOTTY_KITTY_DEBUG=1` to write the Kitty image debug log.
56
60
  * Windows does not use Kitty protocol; it uses a custom protocol.
57
61
  - ZMODEM / `rz/sz`: select files in the browser and upload them to the remote shell.
58
62
  * You can also download files from the remote shell.
package/README.md CHANGED
@@ -37,11 +37,14 @@
37
37
  - for copying text on mobile devices
38
38
 
39
39
  ## Intro 介紹
40
- - 這是用 JavaScript / Bun 重新實作的 GoTTY 相容伺服器
41
- - 參考原本 GoTTY 的程式碼,大部分以 Codex 生成
40
+ - 本專案旨在透過瀏覽器、命令列用戶端與現代 Web 協定,讓你的終端機隨處可用。
41
+ - 它是用 JavaScript / Bun 重新實作的 GoTTY 相容伺服器
42
+ - 參考了原本 GoTTY 的程式碼,大部分以 Codex 生成
42
43
  - 包含已針對 `jsgotty` 調整過的前端與 WebTTY 協定實作
43
44
  - 原版 repo:
44
45
  - https://github.com/sorenisanerd/gotty
46
+ - .
47
+ - 關鍵字: 終端機 瀏覽器 命令列用戶端 工作階段管理 Kitty圖形協議 ZMODEM
45
48
 
46
49
  ### Features 特色功能
47
50
  - Resumable reconnect: 瀏覽器斷線後可以用 reconnect token 接回原本的 shell / PTY,而不是重開一個新的 shell。
@@ -51,6 +54,7 @@
51
54
  * 見下方詳細說明兩種模式
52
55
  - Kitty Graphics Protocol: 可以顯示終端內嵌圖片
53
56
  * 像是用 `bun viu.mjs 1.png` 直接在終端中顯示圖片。
57
+ * 設定 `JSGOTTY_KITTY_DEBUG=1` 才會寫入 Kitty 圖片除錯 log。
54
58
  * Windows 不是使用 Kitty 協定,而是自訂協議
55
59
  - ZMODEM / `rz/sz` 上傳/下載功能
56
60
  * 可以從瀏覽器端選檔並上傳到遠端 shell
package/gotty.js CHANGED
@@ -33,10 +33,36 @@ const MSG_CONTROL_RESULT = "b";
33
33
  const MSG_ZMODEM_MODE = "z";
34
34
  const MSG_ZMODEM_OUTPUT = "y";
35
35
  const MSG_ZMODEM_ACK = "Y";
36
- const KITTY_TRACE = process.env.KITTY_TRACE === "1";
36
+ const MSG_KITTY_DEBUG = "K";
37
+ const KITTY_TRACE = /^(1|true|yes|on)$/i.test(String(process.env.JSGOTTY_KITTY_DEBUG || ""));
37
38
  const WINDOWS_BRIDGE_TRACE = process.env.WINDOWS_BRIDGE_TRACE === "1";
38
39
  const WINDOWS_BRIDGE_PREFIX = Buffer.from("@@GOTTYCTL:", "ascii");
39
40
  const WINDOWS_BRIDGE_SUFFIX = Buffer.from("@@", "ascii");
41
+ const KITTY_PLACEMENT_LOG = path.resolve(__dirname, "kitty-placement.log");
42
+
43
+ function kittyPlacementLog(stage, details = {}) {
44
+ if (!KITTY_TRACE) {
45
+ return;
46
+ }
47
+ try {
48
+ fs.appendFileSync(KITTY_PLACEMENT_LOG, JSON.stringify({
49
+ time: new Date().toISOString(),
50
+ pid: process.pid,
51
+ stage,
52
+ ...details,
53
+ }) + "\n");
54
+ } catch (error) {
55
+ // Placement diagnostics must never affect terminal output.
56
+ }
57
+ }
58
+
59
+ function cursorControls(buffer) {
60
+ const text = Buffer.from(buffer).toString("utf8");
61
+ return Array.from(text.matchAll(/\u001b\[([0-9;?]*)([A-Za-z])/g), (match) => ({
62
+ params: match[1],
63
+ final: match[2],
64
+ })).filter((entry) => "ABCDEFGHfJKhl".includes(entry.final));
65
+ }
40
66
 
41
67
  const DEFAULTS = {
42
68
  address: "0.0.0.0",
@@ -974,11 +1000,10 @@ class KittyGraphicsParser {
974
1000
  ));
975
1001
  }
976
1002
 
977
- consume(raw, cursor) {
1003
+ consume(raw) {
978
1004
  const data = this.pending.length > 0 ? Buffer.concat([this.pending, raw]) : raw;
979
1005
  this.pending = Buffer.alloc(0);
980
- const plain = [];
981
- const graphics = [];
1006
+ const events = [];
982
1007
  let offset = 0;
983
1008
  let plainStart = 0;
984
1009
 
@@ -986,19 +1011,19 @@ class KittyGraphicsParser {
986
1011
  if (data[offset] === 0x1b && offset + 2 < data.length && data[offset + 1] === 0x5f && data[offset + 2] === 0x47) {
987
1012
  const commandEnd = this._findApcEnd(data, offset + 3);
988
1013
  if (commandEnd === -1) {
1014
+ if (plainStart < offset) {
1015
+ events.push({ kind: "plain", data: data.subarray(plainStart, offset) });
1016
+ }
989
1017
  this.pending = data.subarray(offset);
990
1018
  break;
991
1019
  }
992
1020
 
993
1021
  if (plainStart < offset) {
994
- plain.push(data.subarray(plainStart, offset));
1022
+ events.push({ kind: "plain", data: data.subarray(plainStart, offset) });
995
1023
  }
996
1024
 
997
1025
  const packet = data.subarray(offset + 3, commandEnd);
998
- const parsed = this._parsePacket(packet, cursor);
999
- if (parsed) {
1000
- graphics.push(parsed);
1001
- }
1026
+ events.push({ kind: "kitty", packet });
1002
1027
 
1003
1028
  offset = commandEnd + 2;
1004
1029
  plainStart = offset;
@@ -1008,10 +1033,14 @@ class KittyGraphicsParser {
1008
1033
  }
1009
1034
 
1010
1035
  if (plainStart < data.length && this.pending.length === 0) {
1011
- plain.push(data.subarray(plainStart));
1036
+ events.push({ kind: "plain", data: data.subarray(plainStart) });
1012
1037
  }
1013
1038
 
1014
- return { plain, graphics };
1039
+ return { events };
1040
+ }
1041
+
1042
+ parsePacket(packet, cursor) {
1043
+ return this._parsePacket(packet, cursor);
1015
1044
  }
1016
1045
 
1017
1046
  acknowledge(graphic) {
@@ -1094,11 +1123,18 @@ class KittyGraphicsParser {
1094
1123
  }
1095
1124
 
1096
1125
  if (action === "d") {
1126
+ const deleteScope = control.d || "a";
1127
+ const deleteImageId = control.i || control.I || null;
1128
+ if (deleteScope === "A") {
1129
+ this.images.clear();
1130
+ } else if (deleteScope === "I" && deleteImageId) {
1131
+ this.images.delete(deleteImageId);
1132
+ }
1097
1133
  return {
1098
1134
  kind: "delete",
1099
1135
  delete: {
1100
- scope: control.d || "a",
1101
- imageId: control.i || control.I || null,
1136
+ scope: deleteScope,
1137
+ imageId: deleteImageId,
1102
1138
  placementId: control.p || null,
1103
1139
  cursor
1104
1140
  }
@@ -1170,6 +1206,7 @@ class KittyGraphicsParser {
1170
1206
  format: Number.parseInt(existing.control.f || "32", 10),
1171
1207
  width: Number.parseInt(existing.control.s || "0", 10),
1172
1208
  height: Number.parseInt(existing.control.v || "0", 10),
1209
+ mime: existing.control.U || existing.control.mime || null,
1173
1210
  data: binary.toString("base64")
1174
1211
  };
1175
1212
 
@@ -1643,49 +1680,84 @@ class PtySession {
1643
1680
  this.sendChunk(MSG_OUTPUT, raw);
1644
1681
  return;
1645
1682
  }
1646
- const cursorBefore = this.cursorTracker.snapshot();
1647
- const parsed = this.kittyParser.consume(raw, cursorBefore);
1648
- if (parsed.graphics.length > 0) {
1649
- traceLog("graphics", parsed.graphics.map((graphic) => ({
1650
- kind: graphic.kind,
1651
- control: graphic.control || null,
1652
- imageId: graphic.image ? graphic.image.id : null
1653
- })));
1654
- }
1655
- for (const chunk of parsed.plain) {
1683
+ const parsed = this.kittyParser.consume(raw);
1684
+ for (const event of parsed.events) {
1685
+ if (event.kind === "kitty") {
1686
+ const cursorAtApc = this.cursorTracker.snapshot();
1687
+ const graphic = this.kittyParser.parsePacket(event.packet, cursorAtApc);
1688
+ if (!graphic) {
1689
+ continue;
1690
+ }
1691
+ kittyPlacementLog("server-kitty-event", {
1692
+ cursorAtApc,
1693
+ kind: graphic.kind,
1694
+ control: graphic.control || null,
1695
+ delete: graphic.delete || null,
1696
+ imageId: graphic.image?.id || null,
1697
+ });
1698
+ traceLog("graphics", JSON.stringify({
1699
+ kind: graphic.kind,
1700
+ control: graphic.control || null,
1701
+ imageId: graphic.image ? graphic.image.id : null
1702
+ }));
1703
+ if (graphic.kind === "placement") {
1704
+ this.cursorTracker.applyKittyPlacement(graphic.control);
1705
+ }
1706
+ this.send(MSG_KITTY_GRAPHICS, JSON.stringify(graphic));
1707
+ const syntheticCursorMotion = this.buildKittyCursorMotion(graphic);
1708
+ if (syntheticCursorMotion) {
1709
+ this.sendChunk(MSG_OUTPUT, Buffer.from(syntheticCursorMotion, "utf8"));
1710
+ }
1711
+ const ack = this.kittyParser.acknowledge(graphic);
1712
+ if (ack) {
1713
+ traceLog("graphics-ack", JSON.stringify(graphic.control || {}), JSON.stringify(ack));
1714
+ this.backend.write(Buffer.from(ack, "utf8"));
1715
+ }
1716
+ continue;
1717
+ }
1718
+
1719
+ const chunk = event.data;
1656
1720
  const filteredChunk = this.filterEchoedTerminalReplies(chunk);
1657
1721
  if (filteredChunk.length === 0) {
1658
1722
  continue;
1659
1723
  }
1660
1724
  if (!this.supportsWindowsBridge) {
1725
+ const cursorBefore = this.cursorTracker.snapshot();
1661
1726
  this.cursorTracker.consume(filteredChunk);
1727
+ const cursorAfter = this.cursorTracker.snapshot();
1728
+ const controls = cursorControls(filteredChunk);
1729
+ if (controls.length > 0) {
1730
+ kittyPlacementLog("server-plain-cursor-controls", {
1731
+ bytes: filteredChunk.length,
1732
+ cursorBefore,
1733
+ cursorAfter,
1734
+ controls,
1735
+ });
1736
+ }
1662
1737
  this.sendChunk(MSG_OUTPUT, filteredChunk);
1663
1738
  continue;
1664
1739
  }
1665
1740
  const bridged = this.windowsBridgeParser.consume(filteredChunk);
1666
1741
  if (bridged.plain.length > 0) {
1742
+ const cursorBefore = this.cursorTracker.snapshot();
1667
1743
  this.cursorTracker.consume(bridged.plain);
1744
+ const cursorAfter = this.cursorTracker.snapshot();
1745
+ const controls = cursorControls(bridged.plain);
1746
+ if (controls.length > 0) {
1747
+ kittyPlacementLog("server-plain-cursor-controls", {
1748
+ bytes: bridged.plain.length,
1749
+ cursorBefore,
1750
+ cursorAfter,
1751
+ controls,
1752
+ windowsBridge: true,
1753
+ });
1754
+ }
1668
1755
  this.sendChunk(MSG_OUTPUT, bridged.plain);
1669
1756
  }
1670
1757
  for (const control of bridged.controls) {
1671
1758
  this.handleWindowsBridgeControl(control);
1672
1759
  }
1673
1760
  }
1674
- for (const graphic of parsed.graphics) {
1675
- if (graphic.kind === "placement") {
1676
- this.cursorTracker.applyKittyPlacement(graphic.control);
1677
- }
1678
- this.send(MSG_KITTY_GRAPHICS, JSON.stringify(graphic));
1679
- const syntheticCursorMotion = this.buildKittyCursorMotion(graphic);
1680
- if (syntheticCursorMotion) {
1681
- this.sendChunk(MSG_OUTPUT, Buffer.from(syntheticCursorMotion, "utf8"));
1682
- }
1683
- const ack = this.kittyParser.acknowledge(graphic);
1684
- if (ack) {
1685
- traceLog("graphics-ack", JSON.stringify(graphic.control || {}), JSON.stringify(ack));
1686
- this.backend.write(Buffer.from(ack, "utf8"));
1687
- }
1688
- }
1689
1761
  });
1690
1762
 
1691
1763
  this.backend.onExit(() => {
@@ -2354,6 +2426,16 @@ class PtySession {
2354
2426
  case MSG_PING:
2355
2427
  this.send(MSG_PONG, "", ws);
2356
2428
  break;
2429
+ case MSG_KITTY_DEBUG:
2430
+ if (!KITTY_TRACE) {
2431
+ break;
2432
+ }
2433
+ try {
2434
+ kittyPlacementLog("browser", JSON.parse(payload));
2435
+ } catch (error) {
2436
+ kittyPlacementLog("browser-malformed", { payload });
2437
+ }
2438
+ break;
2357
2439
  case MSG_WINDOWS_BRIDGE: {
2358
2440
  if (!this.supportsWindowsBridge || !this.isWriter(ws) || payload.length === 0) {
2359
2441
  return;
@@ -3227,7 +3309,17 @@ async function bootstrap() {
3227
3309
  }
3228
3310
  }
3229
3311
 
3230
- bootstrap().catch((error) => {
3231
- console.error(String(error && error.stack ? error.stack : error));
3232
- process.exitCode = 1;
3233
- });
3312
+ module.exports.CursorStateTracker = CursorStateTracker;
3313
+ module.exports.KittyGraphicsParser = KittyGraphicsParser;
3314
+
3315
+ if (require.main === module) {
3316
+ if (KITTY_TRACE) {
3317
+ try {
3318
+ fs.writeFileSync(KITTY_PLACEMENT_LOG, "");
3319
+ } catch {}
3320
+ }
3321
+ bootstrap().catch((error) => {
3322
+ console.error(String(error && error.stack ? error.stack : error));
3323
+ process.exitCode = 1;
3324
+ });
3325
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "jsgotty",
3
- "version": "1.1.3",
3
+ "version": "1.1.4",
4
4
  "description": "Share your terminal as a web application: A JavaScript rewrite of GoTTY",
5
5
  "bin": {
6
6
  "jsgotty": "./gotty.js"
@@ -11,6 +11,13 @@
11
11
  }
12
12
 
13
13
  #kitty-overlay .kitty-image {
14
+ position: absolute;
15
+ display: block;
16
+ overflow: hidden;
17
+ pointer-events: none;
18
+ }
19
+
20
+ #kitty-overlay .kitty-image__content {
14
21
  position: absolute;
15
22
  display: block;
16
23
  max-width: none;
package/static/help.md CHANGED
@@ -89,7 +89,7 @@ Useful methods/properties:
89
89
 
90
90
  - `window.getTerminalText`: helper exposed by `GoTTYXterm` for debugging/copying the full visible buffer as plain text.
91
91
  - `window.Zmodem`: ZMODEM helper namespace exposed by `zmodem.js`. Useful methods are used by the file-transfer addon, especially `Browser.send_files(...)` and `Browser.save_to_disk(...)`.
92
- - `window.gotty_kitty_trace`: boolean trace flag consumed by `kitty.js`. When true, kitty-specific debug logging is enabled.
92
+ - `window.gotty_kitty_trace`: boolean trace flag consumed by `kitty.js`. It is enabled by starting jsgotty with `JSGOTTY_KITTY_DEBUG=1`.
93
93
  - `window.touchScrollThreshold`: mobile touch-scroll threshold in pixels used by `kitty.js` to convert finger movement into synthetic wheel ticks. Default: 24 px. Lower means faster scrolling.
94
94
  - `alert_advanced(text, asHtml, closeOnClick)`: page-local modal helper used by custom UI scripts.
95
95
  - `noWinOpenUseFetch()`: intentional monkey patch for link handling.
@@ -19,9 +19,56 @@
19
19
  touchBound: false,
20
20
  touchScroll: null,
21
21
  contextMenu: null,
22
- imageContextBound: false
22
+ imageContextBound: false,
23
+ socket: null
23
24
  };
24
25
 
26
+ function browserTerminalState() {
27
+ const xterm = terminal && terminal.__gottyXterm;
28
+ const active = xterm && xterm.buffer && xterm.buffer.active;
29
+ if (!active) {
30
+ return null;
31
+ }
32
+ const { screen, viewport } = xtermElements();
33
+ const terminalRect = terminal.getBoundingClientRect();
34
+ const screenRect = screen && screen.getBoundingClientRect();
35
+ const viewportRect = viewport && viewport.getBoundingClientRect();
36
+ return {
37
+ type: active.type || null,
38
+ baseY: active.baseY,
39
+ viewportY: active.viewportY,
40
+ cursorX: active.cursorX,
41
+ cursorY: active.cursorY,
42
+ cursorCol: active.cursorX + 1,
43
+ cursorRow: active.cursorY + 1,
44
+ absoluteCursorRow: active.baseY + active.cursorY + 1,
45
+ windowInnerWidth: window.innerWidth,
46
+ documentClientWidth: document.documentElement.clientWidth,
47
+ terminalWidth: terminalRect.width,
48
+ screenWidth: screenRect?.width ?? null,
49
+ viewportWidth: viewportRect?.width ?? null,
50
+ viewportClientWidth: viewport?.clientWidth ?? null,
51
+ viewportScrollWidth: viewport?.scrollWidth ?? null,
52
+ };
53
+ }
54
+
55
+ function sendBrowserDebug(stage, details = {}) {
56
+ if (!KITTY_TRACE) {
57
+ return;
58
+ }
59
+ const socket = state.socket;
60
+ if (!socket || socket.readyState !== 1) {
61
+ return;
62
+ }
63
+ try {
64
+ socket.send("K" + JSON.stringify({
65
+ stage,
66
+ terminal: browserTerminalState(),
67
+ ...details,
68
+ }));
69
+ } catch (error) {}
70
+ }
71
+
25
72
  function xtermElements() {
26
73
  if (!terminal) {
27
74
  return {};
@@ -98,36 +145,65 @@
98
145
  return `${imageId}:${control.p || "0"}`;
99
146
  }
100
147
 
101
- function currentCursorPosition() {
102
- const xterm = terminal && terminal.__gottyXterm;
103
- const active = xterm && xterm.buffer && xterm.buffer.active;
104
- if (!active) {
105
- return null;
106
- }
107
- return {
108
- bufferRow: active.baseY + active.cursorY + 1,
109
- col: active.cursorX + 1
110
- };
111
- }
112
-
113
148
  function currentViewportY() {
114
149
  const xterm = terminal && terminal.__gottyXterm;
115
150
  const active = xterm && xterm.buffer && xterm.buffer.active;
116
151
  return active ? active.viewportY : 0;
117
152
  }
118
153
 
119
- function createPlacementMarker() {
154
+ function createPlacementMarker(cursor) {
120
155
  const xterm = terminal && terminal.__gottyXterm;
121
156
  if (!xterm || typeof xterm.registerMarker !== "function") {
122
157
  return null;
123
158
  }
124
159
  try {
125
- return xterm.registerMarker(0);
160
+ const active = xterm.buffer && xterm.buffer.active;
161
+ let offset = 0;
162
+ if (active && cursor && Number.isFinite(cursor.bufferRow)) {
163
+ const currentBufferRow = active.baseY + active.cursorY + 1;
164
+ offset = Math.trunc(cursor.bufferRow - currentBufferRow);
165
+ } else if (
166
+ active && cursor && Number.isFinite(cursor.row) &&
167
+ cursor.row >= 1 && cursor.row <= state.rows
168
+ ) {
169
+ // Kitty's cursor row is 1-based within the live terminal screen.
170
+ // registerMarker() takes an offset from xterm's current 0-based row.
171
+ offset = Math.trunc(cursor.row - (active.cursorY + 1));
172
+ }
173
+ const marker = xterm.registerMarker(offset);
174
+ sendBrowserDebug("marker-created", {
175
+ protocolCursor: cursor,
176
+ offset,
177
+ markerLine: marker?.line ?? null,
178
+ });
179
+ return marker;
126
180
  } catch (error) {
127
181
  return null;
128
182
  }
129
183
  }
130
184
 
185
+ function disposePlacementMarker(node) {
186
+ if (!node || !node.__kittyMarker) {
187
+ return;
188
+ }
189
+ try {
190
+ node.__kittyMarker.dispose();
191
+ } catch (error) {
192
+ // The marker may already have been disposed by xterm buffer trimming.
193
+ }
194
+ node.__kittyMarker = null;
195
+ }
196
+
197
+ function removePlacementNode(node) {
198
+ if (!node) {
199
+ return;
200
+ }
201
+ disposePlacementMarker(node);
202
+ node.__kittyGeneration = (node.__kittyGeneration || 0) + 1;
203
+ revokeNodeUrl(node);
204
+ node.remove();
205
+ }
206
+
131
207
  function decodeRawImage(image) {
132
208
  const binary = atob(image.data);
133
209
  const bytes = new Uint8ClampedArray(binary.length);
@@ -197,6 +273,35 @@
197
273
  });
198
274
  }
199
275
 
276
+ function sourceRectangle(width, height, control = {}) {
277
+ const sourceWidth = Math.max(1, Math.trunc(Number(width) || 1));
278
+ const sourceHeight = Math.max(1, Math.trunc(Number(height) || 1));
279
+ const requestedX = Math.max(0, Math.trunc(Number.parseInt(control.x || "0", 10) || 0));
280
+ const requestedY = Math.max(0, Math.trunc(Number.parseInt(control.y || "0", 10) || 0));
281
+ const requestedWidth = Math.max(0, Math.trunc(Number.parseInt(control.w || "0", 10) || 0));
282
+ const requestedHeight = Math.max(0, Math.trunc(Number.parseInt(control.h || "0", 10) || 0));
283
+ const right = requestedWidth > 0 ? requestedX + requestedWidth : sourceWidth;
284
+ const bottom = requestedHeight > 0 ? requestedY + requestedHeight : sourceHeight;
285
+ const x = Math.min(sourceWidth, requestedX);
286
+ const y = Math.min(sourceHeight, requestedY);
287
+ const clippedRight = Math.min(sourceWidth, Math.max(x, right));
288
+ const clippedBottom = Math.min(sourceHeight, Math.max(y, bottom));
289
+ const cropWidth = clippedRight - x;
290
+ const cropHeight = clippedBottom - y;
291
+ if (cropWidth < 1 || cropHeight < 1) {
292
+ return null;
293
+ }
294
+ return {
295
+ x,
296
+ y,
297
+ width: cropWidth,
298
+ height: cropHeight,
299
+ sourceWidth,
300
+ sourceHeight,
301
+ cropped: x !== 0 || y !== 0 || cropWidth !== sourceWidth || cropHeight !== sourceHeight,
302
+ };
303
+ }
304
+
200
305
  async function blobDimensions(blob) {
201
306
  if (typeof createImageBitmap === "function") {
202
307
  const bitmap = await createImageBitmap(blob);
@@ -224,23 +329,35 @@
224
329
  });
225
330
  }
226
331
 
227
- async function resolveImageAsset(image) {
332
+ async function resolveImageAsset(image, control = {}) {
228
333
  if (!image) {
229
334
  return null;
230
335
  }
336
+ let blob;
337
+ let dimensions;
231
338
  if (image.format === 100) {
232
- const blob = new Blob([binaryFromBase64(image.data)], {
339
+ blob = new Blob([binaryFromBase64(image.data)], {
233
340
  type: inferBlobMimeType(image, image.control || {})
234
341
  });
235
- const dimensions = await blobDimensions(blob);
236
- return { blob, width: dimensions.width, height: dimensions.height };
342
+ dimensions = await blobDimensions(blob);
343
+ } else {
344
+ const canvas = decodeRawImage(image);
345
+ if (!canvas) {
346
+ return null;
347
+ }
348
+ blob = await canvasToBlob(canvas);
349
+ dimensions = { width: canvas.width, height: canvas.height };
237
350
  }
238
- const canvas = decodeRawImage(image);
239
- if (!canvas) {
351
+ const sourceRect = sourceRectangle(dimensions.width, dimensions.height, control);
352
+ if (!sourceRect) {
240
353
  return null;
241
354
  }
242
- const blob = await canvasToBlob(canvas);
243
- return { blob, width: canvas.width, height: canvas.height };
355
+ return {
356
+ blob,
357
+ width: sourceRect.width,
358
+ height: sourceRect.height,
359
+ sourceRect,
360
+ };
244
361
  }
245
362
 
246
363
  function revokeNodeUrl(node) {
@@ -254,22 +371,116 @@
254
371
  if (!node || !node.__kittyPlacement) {
255
372
  return;
256
373
  }
257
- const { control, cursor, intrinsicWidth, intrinsicHeight } = node.__kittyPlacement;
374
+ const { control, cursor, intrinsicWidth, intrinsicHeight, sourceRect } = node.__kittyPlacement;
258
375
  const metrics = cellMetrics();
259
376
  const anchor = anchorOffset();
260
- const cols = Number.parseInt(control.c || "0", 10) || Math.max(1, Math.round(intrinsicWidth / Math.max(1, metrics.width)));
261
- const rows = Number.parseInt(control.r || "0", 10) || Math.max(1, Math.round(intrinsicHeight / Math.max(1, metrics.height)));
377
+ const controlCols = Math.max(0, Number.parseInt(control.c || "0", 10) || 0);
378
+ const controlRows = Math.max(0, Number.parseInt(control.r || "0", 10) || 0);
379
+ let requestedCols;
380
+ let requestedRows;
381
+ if (controlCols > 0 && controlRows > 0) {
382
+ requestedCols = controlCols;
383
+ requestedRows = controlRows;
384
+ } else if (controlCols > 0) {
385
+ requestedCols = controlCols;
386
+ requestedRows = Math.max(1, Math.round(
387
+ controlCols * metrics.width * intrinsicHeight / intrinsicWidth / metrics.height,
388
+ ));
389
+ } else if (controlRows > 0) {
390
+ requestedRows = controlRows;
391
+ requestedCols = Math.max(1, Math.round(
392
+ controlRows * metrics.height * intrinsicWidth / intrinsicHeight / metrics.width,
393
+ ));
394
+ } else {
395
+ requestedCols = Math.max(1, Math.round(intrinsicWidth / Math.max(1, metrics.width)));
396
+ requestedRows = Math.max(1, Math.round(intrinsicHeight / Math.max(1, metrics.height)));
397
+ }
398
+ const xterm = terminal && terminal.__gottyXterm;
399
+ const viewerCols = Math.max(1, Math.trunc(Number(xterm?.cols) || state.cols));
400
+ const viewerRows = Math.max(1, Math.trunc(Number(xterm?.rows) || state.rows));
401
+ const cursorCol = Math.max(1, Math.trunc(Number(cursor?.col) || 1));
402
+ // A fixed-width PTY may be wider than the browser's xterm instance. Match
403
+ // viu's final-column safety margin using the viewer's real column count,
404
+ // then scale both axes so the image is visible rather than merely clipped.
405
+ const availableViewerCols = Math.max(1, viewerCols - cursorCol);
406
+ const scale = Math.min(1, availableViewerCols / requestedCols);
407
+ const cols = Math.max(1, Math.min(requestedCols, availableViewerCols));
408
+ const rows = Math.max(1, Math.round(requestedRows * scale));
262
409
  const marker = node.__kittyMarker;
263
- const row = marker && !marker.isDisposed && Number.isFinite(marker.line)
264
- ? marker.line - currentViewportY() + 1
410
+ const activeBuffer = xterm?.buffer?.active;
411
+ const useProtocolRow = activeBuffer?.type === "alternate" && cursor && Number.isFinite(cursor.row);
412
+ const row = useProtocolRow
413
+ ? cursor.row
414
+ : marker && !marker.isDisposed && Number.isFinite(marker.line)
415
+ ? marker.line - currentViewportY() + 1
265
416
  : cursor && Number.isFinite(cursor.bufferRow)
266
417
  ? cursor.bufferRow - currentViewportY()
267
418
  : (cursor && cursor.row) || 1;
419
+ // Fixed-size PTYs can have more rows than the browser-side xterm. Leave
420
+ // the viewer's final row for the TUI status line in that mismatch mode.
421
+ const viewerBottomRow = Math.max(1, viewerRows - (viewerRows < state.rows ? 1 : 0));
422
+ const visibleRows = Math.max(0, Math.min(rows, viewerBottomRow - row + 1));
423
+ node.style.display = visibleRows > 0 ? "block" : "none";
268
424
  node.style.left = `${anchor.left + (Math.max(1, cursor.col) - 1) * metrics.width}px`;
269
425
  node.style.top = `${anchor.top + (row - 1) * metrics.height}px`;
270
426
  node.style.width = `${cols * metrics.width}px`;
271
- node.style.height = `${rows * metrics.height}px`;
427
+ node.style.height = `${visibleRows * metrics.height}px`;
272
428
  node.style.zIndex = String(Number.parseInt(control.z || "0", 10) || 0);
429
+ const imageElement = node.__kittyImageElement;
430
+ if (imageElement && sourceRect) {
431
+ const targetWidth = cols * metrics.width;
432
+ const targetHeight = rows * metrics.height;
433
+ const sourceScaleX = targetWidth / sourceRect.width;
434
+ const sourceScaleY = targetHeight / sourceRect.height;
435
+ imageElement.style.left = `${-sourceRect.x * sourceScaleX}px`;
436
+ imageElement.style.top = `${-sourceRect.y * sourceScaleY}px`;
437
+ imageElement.style.width = `${sourceRect.sourceWidth * sourceScaleX}px`;
438
+ imageElement.style.height = `${sourceRect.sourceHeight * sourceScaleY}px`;
439
+ }
440
+ const { screen, viewport } = xtermElements();
441
+ const overlayRect = overlay.getBoundingClientRect();
442
+ const terminalRect = terminal.getBoundingClientRect();
443
+ const screenRect = screen && screen.getBoundingClientRect();
444
+ const viewportRect = viewport && viewport.getBoundingClientRect();
445
+ sendBrowserDebug("layout", {
446
+ imageId: control.i || control.I || null,
447
+ placementId: control.p || null,
448
+ requestedCols,
449
+ requestedRows,
450
+ viewerCols,
451
+ viewerRows,
452
+ viewerBottomRow,
453
+ terminalVisibleRows: visibleRows,
454
+ availableViewerCols,
455
+ viewerScale: scale,
456
+ positionSource: useProtocolRow ? "protocol" : "marker",
457
+ sourceRect: sourceRect || null,
458
+ protocolCursor: cursor,
459
+ markerLine: marker?.line ?? null,
460
+ markerDisposed: marker?.isDisposed ?? null,
461
+ currentViewportY: currentViewportY(),
462
+ selectedRow: row,
463
+ cssLeft: node.style.left,
464
+ cssTop: node.style.top,
465
+ cssWidth: node.style.width,
466
+ cssHeight: node.style.height,
467
+ cellWidth: metrics.width,
468
+ cellHeight: metrics.height,
469
+ geometry: {
470
+ windowInnerWidth: window.innerWidth,
471
+ documentClientWidth: document.documentElement.clientWidth,
472
+ terminalWidth: terminalRect.width,
473
+ screenWidth: screenRect?.width ?? null,
474
+ viewportWidth: viewportRect?.width ?? null,
475
+ viewportClientWidth: viewport?.clientWidth ?? null,
476
+ viewportScrollWidth: viewport?.scrollWidth ?? null,
477
+ overlayWidth: overlayRect.width,
478
+ overlayClientWidth: overlay.clientWidth,
479
+ overlayScrollWidth: overlay.scrollWidth,
480
+ overlayComputedWidth: getComputedStyle(overlay).width,
481
+ overlayOverflow: getComputedStyle(overlay).overflow,
482
+ },
483
+ });
273
484
  }
274
485
 
275
486
  function relayoutAll() {
@@ -297,7 +508,10 @@
297
508
  if (!viewport) {
298
509
  return;
299
510
  }
300
- viewport.addEventListener("scroll", relayoutAll, { passive: true });
511
+ viewport.addEventListener("scroll", () => {
512
+ sendBrowserDebug("viewport-scroll", { currentViewportY: currentViewportY() });
513
+ relayoutAll();
514
+ }, { passive: true });
301
515
  state.scrollBound = true;
302
516
  }
303
517
 
@@ -455,8 +669,7 @@
455
669
  }
456
670
  const node = state.placements.get(state.contextMenu.targetKey);
457
671
  if (node) {
458
- revokeNodeUrl(node);
459
- node.remove();
672
+ removePlacementNode(node);
460
673
  state.placements.delete(state.contextMenu.targetKey);
461
674
  }
462
675
  hideContextMenu();
@@ -577,15 +790,24 @@
577
790
  const key = placementKey(message);
578
791
  const control = message.control || {};
579
792
  const cursor = message.bufferCursor || message.cursor || { row: 1, col: 1 };
793
+ sendBrowserDebug("placement-start", {
794
+ key,
795
+ control,
796
+ protocolCursor: message.cursor || null,
797
+ selectedCursor: cursor,
798
+ });
580
799
  if (message.image) {
581
800
  message.image.control = control;
582
801
  }
583
-
584
802
  let node = state.placements.get(key);
585
803
  if (!node) {
586
- node = document.createElement("img");
804
+ node = document.createElement("div");
587
805
  node.className = "kitty-image";
588
- node.alt = "";
806
+ const imageElement = document.createElement("img");
807
+ imageElement.className = "kitty-image__content";
808
+ imageElement.alt = "";
809
+ node.__kittyImageElement = imageElement;
810
+ node.appendChild(imageElement);
589
811
  node.__kittyObjectUrl = "";
590
812
  node.__kittyMarker = null;
591
813
  node.addEventListener("contextmenu", (event) => {
@@ -595,12 +817,13 @@
595
817
  overlay.appendChild(node);
596
818
  }
597
819
 
598
- if (!node.__kittyMarker) {
599
- node.__kittyMarker = createPlacementMarker();
600
- }
820
+ disposePlacementMarker(node);
821
+ node.__kittyMarker = createPlacementMarker(cursor);
822
+ const generation = (node.__kittyGeneration || 0) + 1;
823
+ node.__kittyGeneration = generation;
601
824
 
602
- const asset = await resolveImageAsset(message.image);
603
- if (!asset) {
825
+ const asset = await resolveImageAsset(message.image, control);
826
+ if (!asset || node.__kittyGeneration !== generation) {
604
827
  return;
605
828
  }
606
829
  const objectUrl = URL.createObjectURL(asset.blob);
@@ -610,9 +833,10 @@
610
833
  control,
611
834
  cursor,
612
835
  intrinsicWidth: asset.width,
613
- intrinsicHeight: asset.height
836
+ intrinsicHeight: asset.height,
837
+ sourceRect: asset.sourceRect,
614
838
  };
615
- node.src = objectUrl;
839
+ node.__kittyImageElement.src = objectUrl;
616
840
  bindViewportScroll();
617
841
  bindTerminalRender();
618
842
  bindTouchScrolling();
@@ -622,10 +846,13 @@
622
846
 
623
847
  function deleteImages(message) {
624
848
  const info = message.delete || {};
625
- if (info.scope === "a") {
849
+ sendBrowserDebug("delete", {
850
+ delete: info,
851
+ placementKeys: Array.from(state.placements.keys()),
852
+ });
853
+ if (info.scope === "a" || info.scope === "A") {
626
854
  for (const node of state.placements.values()) {
627
- revokeNodeUrl(node);
628
- node.remove();
855
+ removePlacementNode(node);
629
856
  }
630
857
  state.placements.clear();
631
858
  return;
@@ -634,8 +861,7 @@
634
861
  if (info.imageId) {
635
862
  for (const [key, node] of state.placements.entries()) {
636
863
  if (key.startsWith(`${info.imageId}:`)) {
637
- revokeNodeUrl(node);
638
- node.remove();
864
+ removePlacementNode(node);
639
865
  state.placements.delete(key);
640
866
  }
641
867
  }
@@ -716,8 +942,16 @@
716
942
 
717
943
  function handleKittyMessage(payload) {
718
944
  const message = JSON.parse(payload);
945
+ sendBrowserDebug("kitty-message", {
946
+ kind: message.kind,
947
+ control: message.control || null,
948
+ protocolCursor: message.cursor || message.delete?.cursor || null,
949
+ delete: message.delete || null,
950
+ });
719
951
  if (message.kind === "placement") {
720
- message.bufferCursor = currentCursorPosition();
952
+ // The server records this cursor exactly where the Kitty APC occurred.
953
+ // Do not replace it with xterm's later cursor, which may already have
954
+ // moved because of redraw or scrolling output queued after the APC.
721
955
  placeImage(message);
722
956
  return true;
723
957
  }
@@ -735,6 +969,7 @@
735
969
  return nativeOnOpen.call(this, type, listener, options);
736
970
  }
737
971
  const wrapped = function (event) {
972
+ state.socket = this;
738
973
  inspectTerminalOutput(event.data);
739
974
  if (typeof event.data === "string" && event.data[0] === MSG_KITTY) {
740
975
  if (handleKittyMessage(event.data.slice(1))) {
@@ -774,6 +1009,7 @@
774
1009
  return;
775
1010
  }
776
1011
  descriptor.set.call(this, function (event) {
1012
+ state.socket = this;
777
1013
  inspectTerminalOutput(event.data);
778
1014
  if (typeof event.data === "string" && event.data[0] === MSG_KITTY) {
779
1015
  if (handleKittyMessage(event.data.slice(1))) {
@@ -0,0 +1,58 @@
1
+ const assert = require("node:assert/strict");
2
+ const test = require("node:test");
3
+ const { CursorStateTracker, KittyGraphicsParser } = require("../gotty.js");
4
+
5
+ test("Kitty parsing preserves ANSI/APC order and captures the cursor at the APC", () => {
6
+ const parser = new KittyGraphicsParser();
7
+ const tracker = new CursorStateTracker();
8
+ const raw = Buffer.from(
9
+ "\x1b[5;4H" +
10
+ "\x1b_Ga=T,f=100,i=7,p=7,q=2,C=1,x=10,y=20,w=30,h=40,c=5,r=6,m=0;AA==\x1b\\" +
11
+ "\x1b[9;2H",
12
+ );
13
+
14
+ const { events } = parser.consume(raw);
15
+ assert.deepEqual(events.map((event) => event.kind), ["plain", "kitty", "plain"]);
16
+
17
+ tracker.consume(events[0].data);
18
+ const graphic = parser.parsePacket(events[1].packet, tracker.snapshot());
19
+ assert.equal(graphic.kind, "placement");
20
+ assert.deepEqual(graphic.cursor, { row: 5, col: 4 });
21
+ assert.deepEqual(
22
+ Object.fromEntries(["x", "y", "w", "h", "c", "r"].map((key) => [key, graphic.control[key]])),
23
+ { x: "10", y: "20", w: "30", h: "40", c: "5", r: "6" },
24
+ );
25
+
26
+ tracker.consume(events[2].data);
27
+ assert.deepEqual(tracker.snapshot(), { row: 9, col: 2 });
28
+ });
29
+
30
+ test("an APC split across PTY chunks stays ordered after preceding output", () => {
31
+ const parser = new KittyGraphicsParser();
32
+ const first = parser.consume(Buffer.from("\x1b[3;6H\x1b_Ga=d,d=i"));
33
+ assert.deepEqual(first.events.map((event) => event.kind), ["plain"]);
34
+
35
+ const second = parser.consume(Buffer.from(",i=9;\x1b\\tail"));
36
+ assert.deepEqual(second.events.map((event) => event.kind), ["kitty", "plain"]);
37
+ });
38
+
39
+ test("placement-only packets reuse the server-side cached image", () => {
40
+ const parser = new KittyGraphicsParser();
41
+ const parse = (packet) => {
42
+ const event = parser.consume(Buffer.from(packet)).events.find((item) => item.kind === "kitty");
43
+ return event ? parser.parsePacket(event.packet, { row: 1, col: 1 }) : null;
44
+ };
45
+
46
+ const transfer = parse("\x1b_Ga=T,f=100,i=7,p=7,U=image/png,m=0;AA==\x1b\\");
47
+ assert.equal(transfer.image.data, "AA==");
48
+ assert.equal(transfer.image.mime, "image/png");
49
+
50
+ const placement = parse("\x1b_Ga=p,i=7,p=7,c=5,r=2,C=1;\x1b\\");
51
+ assert.equal(placement.image.id, "7");
52
+ assert.equal(placement.image.data, "AA==");
53
+
54
+ parse("\x1b_Ga=d,d=i,i=7;\x1b\\");
55
+ assert.ok(parse("\x1b_Ga=p,i=7,p=7;\x1b\\"));
56
+ parse("\x1b_Ga=d,d=I,i=7;\x1b\\");
57
+ assert.equal(parse("\x1b_Ga=p,i=7,p=7;\x1b\\"), null);
58
+ });
package/viu.mjs CHANGED
@@ -43,6 +43,7 @@ function buildControlFields(imageId, mime, cols, rows, more, compat) {
43
43
  "a=T",
44
44
  "f=100",
45
45
  `i=${imageId}`,
46
+ `p=${imageId}`,
46
47
  "q=2",
47
48
  "t=d",
48
49
  `c=${cols}`,
@@ -61,7 +62,13 @@ function writePacket(control, payload) {
61
62
 
62
63
  function writeKittyImage(buffer, mime, width, height, compat) {
63
64
  const base64 = buffer.toString("base64");
64
- const imageId = Date.now() % 2147483647;
65
+ let imageId = Date.now() % 2147483647;
66
+
67
+ imageId = process.env.JSGOTTY_IMGID || imageId ;
68
+
69
+ if(process.env.JSGOTTY_DEBUG)
70
+ console.error(imageId)
71
+
65
72
  const { cols, rows } = fitImageCells(width, height);
66
73
 
67
74
  if (process.platform === "win32") {