jsgotty 1.3.0 → 1.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.en.md CHANGED
@@ -349,3 +349,7 @@ printf '\033]52;c;%s\007' "$(printf 'Hello' | base64 | tr -d '\n')"
349
349
  Applications can send `ESC ] 52 ; c ; ? ST` to read and receive a base64-encoded OSC 52 reply on stdin.
350
350
 
351
351
  `jsgotty --client` **does not intercept OSC 52**: it forwards reads and writes unchanged for the outer terminal emulator to handle.
352
+
353
+ ### Touch dragging and right click
354
+
355
+ When the application enables mouse reporting, double-tap and hold the second tap to drag with the left button; lifting your finger releases it. Single-finger swipes still scroll. The existing image long-press menu now includes `Right click` below `Remove image`; it sends a right click at the position where the menu was opened. Pinch zoom and the existing remove-image gesture remain unchanged. To disable double-tap dragging, set `window.touchDoubleTapDrag = false` in the page JavaScript.
package/README.md CHANGED
@@ -351,3 +351,7 @@ printf '\033]52;c;%s\007' "$(printf 'Hello' | base64 | tr -d '\n')"
351
351
  程式可送出 `ESC ] 52 ; c ; ? ST` 讀取,並從 stdin 接收 base64 編碼的 OSC 52 回覆。
352
352
 
353
353
  `jsgotty --client` **不攔截 OSC 52**,讀寫控制碼都原樣轉送,交給最外層真正的終端模擬器決定。
354
+
355
+ ### 觸控拖曳與右鍵
356
+
357
+ 在程式啟用滑鼠回報時,快速點兩下並按住第二下可拖曳左鍵,放開即釋放;單指滑動仍是捲動。既有圖片長按選單的 `Remove image` 下方新增 `Right click`,會在叫出選單的原始位置送出右鍵點擊。雙指縮放與原本的移除圖片入口不變。若要停用雙擊拖曳,可在網頁 JavaScript 設定 `window.touchDoubleTapDrag = false`。
package/gotty.js CHANGED
@@ -16,6 +16,7 @@ const { TerminalModeTracker } = require("./terminal-modes.js");
16
16
  const { WebSocketServer } = WebSocket;
17
17
  const { ClipboardHost, handleOSC52 } = require("./clipboard.js");
18
18
  const clipboardHost = new ClipboardHost();
19
+ const { KittyFrameFlow } = require("./kitty-flow.js");
19
20
 
20
21
  const MSG_INPUT = "1";
21
22
  const MSG_PING = "2";
@@ -1856,7 +1857,8 @@ class PtySession {
1856
1857
  remoteAddr,
1857
1858
  encoding: "null",
1858
1859
  readOnly,
1859
- sendQueue: Promise.resolve()
1860
+ sendQueue: Promise.resolve(),
1861
+ kittyFlow: new KittyFrameFlow(graphic => this.queueSend(ws, MSG_KITTY_GRAPHICS + JSON.stringify(graphic)))
1860
1862
  });
1861
1863
  if (this.permitWrite && !readOnly && !this.writerWs) {
1862
1864
  this.writerWs = ws;
@@ -1919,6 +1921,7 @@ class PtySession {
1919
1921
  const writable = this.isWriter(ws);
1920
1922
  this.send(MSG_SET_ROLE, JSON.stringify({
1921
1923
  role: writable ? "writer" : "viewer",
1924
+ kittyFrameFlow: 1,
1922
1925
  writable
1923
1926
  }), ws);
1924
1927
  }
@@ -2452,6 +2455,9 @@ class PtySession {
2452
2455
  }
2453
2456
 
2454
2457
  switch (type) {
2458
+ case "G":
2459
+ try { client.kittyFlow.control(JSON.parse(payload)); } catch {}
2460
+ break;
2455
2461
  case "C":
2456
2462
  handleOSC52(this, ws, payload, clipboardHost);
2457
2463
  break;
@@ -2580,6 +2586,13 @@ class PtySession {
2580
2586
  return;
2581
2587
  }
2582
2588
 
2589
+ // Negotiate browser-only image credits; never throttle terminal byte output.
2590
+ if (!binary && client.kittyFlow.enabled && payload[0] === MSG_KITTY_GRAPHICS) {
2591
+ const graphic = JSON.parse(payload.slice(1));
2592
+ if (!graphic.frameSequence && client.kittyFlow.graphic(graphic)) return;
2593
+ }
2594
+ if (!binary && payload[0] === MSG_OUTPUT) client.kittyFlow.output(payload.slice(1));
2595
+
2583
2596
  const sendOne = async () => {
2584
2597
  await new Promise((resolve, reject) => {
2585
2598
  try {
package/kitty-flow.js ADDED
@@ -0,0 +1,40 @@
1
+ // Per browser connection. Only replaceable C=1 placements use frame credits;
2
+ // ordinary terminal output, scrolling placements and CLI clients stay ordered.
3
+ class KittyFrameFlow {
4
+ constructor(send) { this.send=send;this.enabled=false;this.visible=true;this.sequence=0;this.inFlight=new Set();this.pending=new Map();this.tail=''; }
5
+ control(message) {
6
+ if(message?.version!==1)return;
7
+ this.enabled=true;
8
+ if(typeof message.visible==='boolean')this.visible=message.visible;
9
+ if(Number.isSafeInteger(message.ack))this.inFlight.delete(message.ack);
10
+ this.flush();
11
+ }
12
+ graphic(graphic) {
13
+ if(!this.enabled)return false;
14
+ if(graphic.kind==='delete'){
15
+ const d=graphic.delete||{};
16
+ for(const [key,g] of this.pending)if(d.scope==='a'||d.scope==='A'||String(g.image.id)===String(d.imageId))this.pending.delete(key);
17
+ return false;
18
+ }
19
+ const c=graphic.control||{},id=c.i||c.I||graphic.image?.id;
20
+ if(graphic.kind!=='placement'||!graphic.image||!id)return false;
21
+ if(String(c.C)!=='1'){this.pending.delete(`${id}:${c.p||'0'}`);return false;}
22
+ const key=`${id}:${c.p||'0'}`;
23
+ // Preserve ordering among different placements when replacing an update.
24
+ this.pending.delete(key);this.pending.set(key,graphic);this.flush();return true;
25
+ }
26
+ output(payload) {
27
+ if(!this.enabled)return;
28
+ const text=this.tail+Buffer.from(payload,'base64').toString('utf8');
29
+ if(text.includes('\x1bc')||text.includes('\f')||/\x1b\[\?(?:1049|1047|47)[hl]/.test(text))this.pending.clear();
30
+ this.tail=text.slice(-32);
31
+ }
32
+ flush() {
33
+ while(this.enabled&&this.visible&&this.inFlight.size<2&&this.pending.size){
34
+ const [key,graphic]=this.pending.entries().next().value;this.pending.delete(key);
35
+ const sequence=++this.sequence;this.inFlight.add(sequence);
36
+ this.send({...graphic,frameSequence:sequence});
37
+ }
38
+ }
39
+ }
40
+ module.exports={KittyFrameFlow};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "jsgotty",
3
- "version": "1.3.0",
3
+ "version": "1.4.1",
4
4
  "description": "Share your terminal as a web application: A JavaScript rewrite of GoTTY",
5
5
  "license": "MIT",
6
6
  "bin": {
@@ -17,3 +17,10 @@ html, body, #terminal {
17
17
  #terminal, #terminal .xterm, #terminal .xterm-viewport, #terminal .xterm-screen {
18
18
  touch-action: manipulation;
19
19
  }
20
+
21
+ /* Chromium skips focused-editable auto-zoom when that element disallows
22
+ pinch zoom. Restrict only the hidden input, not the terminal canvas:
23
+ native paste/IME remain available and the visible terminal can still pinch. */
24
+ #terminal .xterm-helper-textarea {
25
+ touch-action: none;
26
+ }
@@ -15997,8 +15997,15 @@
15997
15997
  !1 === e._customWheelEventHandler(t)
15998
15998
  )
15999
15999
  return !1;
16000
- if (0 === e.viewport.getLinesScrolled(t))
16001
- return !1;
16000
+ // Preserve both axes of diagonal wheel/touch gestures.
16001
+ // CoreMouseService already encodes wheel actions 2/3 as 66/67.
16002
+ if (t.deltaX) e.coreMouseService.triggerMouseEvent({
16003
+ col: i.col, row: i.row, x: i.x, y: i.y,
16004
+ button: 4, action: t.deltaX < 0 ? 2 : 3,
16005
+ ctrl: t.ctrlKey, alt: t.altKey, shift: t.shiftKey,
16006
+ });
16007
+ if (0 === e.viewport.getLinesScrolled(t, true))
16008
+ return !!t.deltaX;
16002
16009
  ((s = t.deltaY < 0 ? 0 : 1), (r = 4));
16003
16010
  break;
16004
16011
  default:
@@ -16972,8 +16979,9 @@
16972
16979
  }
16973
16980
  return { bufferElements: s, cursorElement: i };
16974
16981
  }
16975
- getLinesScrolled(e) {
16976
- if (0 === e.deltaY || e.shiftKey) return 0;
16982
+ getLinesScrolled(e, mouseReporting = false) {
16983
+ // Shift belongs to the remote application while mouse reporting is active.
16984
+ if (0 === e.deltaY || (e.shiftKey && !mouseReporting)) return 0;
16977
16985
  let t = this._applyScrollModifier(e.deltaY, e);
16978
16986
  return (
16979
16987
  e.deltaMode === WheelEvent.DOM_DELTA_PIXEL
@@ -561,6 +561,26 @@
561
561
  state.renderBound = state.renderDisposables.length > 0;
562
562
  }
563
563
 
564
+ // Touch gestures report mouse input without DOM mousedown: xterm's DOM
565
+ // handler focuses its hidden textarea, which can zoom Android WebView.
566
+ function reportTouchMouse(type, point, button = 0) {
567
+ const core = terminal?.__gottyXterm?._core;
568
+ if (!core?.coreMouseService?.areMouseEventsActive) return;
569
+ const screen = core.screenElement;
570
+ if (!screen) return;
571
+ const rect = screen.getBoundingClientRect();
572
+ const coords = core._mouseService.getMouseReportCoords({
573
+ clientX: Math.max(rect.left, Math.min(rect.right - 1, point.clientX)),
574
+ clientY: Math.max(rect.top, Math.min(rect.bottom - 1, point.clientY)),
575
+ }, screen);
576
+ if (!coords) return;
577
+ core.coreMouseService.triggerMouseEvent({
578
+ ...coords, button,
579
+ action: type === "mousedown" ? 1 : type === "mousemove" ? 32 : 0,
580
+ ctrl: false, alt: false, shift: false,
581
+ });
582
+ }
583
+
564
584
  function dispatchSyntheticWheel(target, touch, deltaX, deltaY) {
565
585
  if (!target) {
566
586
  return;
@@ -597,22 +617,69 @@
597
617
  return screen || viewport || xterm || terminal;
598
618
  };
599
619
 
620
+ let lastTap = null;
621
+ let drag = null;
622
+ const mouse = (type, point) => reportTouchMouse(type, point);
623
+ const releaseDrag = () => {
624
+ if (drag) {
625
+ const point = drag;
626
+ drag = null;
627
+ mouse("mouseup", point);
628
+ }
629
+ };
630
+ const cancelGesture = () => {
631
+ releaseDrag();
632
+ lastTap = null;
633
+ state.touchScroll = null;
634
+ };
635
+ state.cancelTouchGesture = cancelGesture;
636
+ bindTarget.addEventListener("contextmenu", (event) => {
637
+ if (drag) { event.preventDefault(); event.stopImmediatePropagation(); }
638
+ }, true);
639
+ window.addEventListener("blur", cancelGesture);
640
+ document.addEventListener("visibilitychange", () => {
641
+ if (document.hidden) cancelGesture();
642
+ });
643
+
600
644
  bindTarget.addEventListener("touchstart", (event) => {
601
645
  if (event.touches.length !== 1) {
602
- state.touchScroll = null;
646
+ cancelGesture();
603
647
  return;
604
648
  }
605
649
  const touch = event.touches[0];
650
+ const reporting = terminal.__gottyXterm?._core?.coreMouseService?.areMouseEventsActive;
651
+ if (reporting && window.touchDoubleTapDrag !== false && lastTap &&
652
+ performance.now() - lastTap.time < 350 &&
653
+ Math.hypot(touch.clientX - lastTap.x, touch.clientY - lastTap.y) < 24) {
654
+ lastTap = null;
655
+ state.touchScroll = null;
656
+ drag = { identifier: touch.identifier, clientX: touch.clientX, clientY: touch.clientY };
657
+ // Cancel compatibility mouse events: this is the second press, not a third click.
658
+ event.preventDefault();
659
+ mouse("mousedown", drag);
660
+ return;
661
+ }
662
+ lastTap = null;
606
663
  state.touchScroll = {
664
+ startX: touch.clientX, startY: touch.clientY, startTime: performance.now(), moved: false,
607
665
  identifier: touch.identifier,
608
666
  lastX: touch.clientX,
609
667
  lastY: touch.clientY,
610
668
  residualX: 0,
611
669
  residualY: 0
612
670
  };
613
- }, { passive: true });
671
+ }, { passive: false });
614
672
 
615
673
  bindTarget.addEventListener("touchmove", (event) => {
674
+ if (drag) {
675
+ const touch = Array.from(event.touches).find(t => t.identifier === drag.identifier);
676
+ if (!touch || event.touches.length !== 1) { cancelGesture(); return; }
677
+ event.preventDefault();
678
+ drag.clientX = touch.clientX;
679
+ drag.clientY = touch.clientY;
680
+ mouse("mousemove", drag);
681
+ return;
682
+ }
616
683
  if (!state.touchScroll) {
617
684
  return;
618
685
  }
@@ -621,6 +688,8 @@
621
688
  return;
622
689
  }
623
690
 
691
+ if (Math.hypot(touch.clientX - state.touchScroll.startX,
692
+ touch.clientY - state.touchScroll.startY) > 8) state.touchScroll.moved = true;
624
693
  const deltaX = state.touchScroll.lastX - touch.clientX;
625
694
  const deltaY = state.touchScroll.lastY - touch.clientY;
626
695
  state.touchScroll.lastX = touch.clientX;
@@ -653,11 +722,20 @@
653
722
  state.touchScroll.residualY -= ticksY * threshold * stepY;
654
723
  }, { passive: false });
655
724
 
656
- const clearTouchScroll = () => {
725
+ bindTarget.addEventListener("touchend", (event) => {
726
+ if (drag) {
727
+ event.preventDefault();
728
+ releaseDrag();
729
+ } else {
730
+ const scroll = state.touchScroll;
731
+ if (scroll && !scroll.moved && event.touches.length === 0 &&
732
+ performance.now() - scroll.startTime < 350) {
733
+ lastTap = { x: scroll.lastX, y: scroll.lastY, time: performance.now() };
734
+ }
735
+ }
657
736
  state.touchScroll = null;
658
- };
659
- bindTarget.addEventListener("touchend", clearTouchScroll, { passive: true });
660
- bindTarget.addEventListener("touchcancel", clearTouchScroll, { passive: true });
737
+ }, { passive: false });
738
+ bindTarget.addEventListener("touchcancel", cancelGesture, { passive: true });
661
739
  state.touchBound = true;
662
740
  }
663
741
 
@@ -676,9 +754,25 @@
676
754
  removeButton.textContent = "Remove image";
677
755
  menu.appendChild(removeButton);
678
756
 
757
+ const separator = document.createElement("hr");
758
+ const rightButton = document.createElement("button");
759
+ rightButton.type = "button";
760
+ rightButton.className = "kitty-context-menu__item";
761
+ rightButton.textContent = "Right click";
762
+ menu.append(separator, rightButton);
763
+ rightButton.addEventListener("click", (event) => {
764
+ event.preventDefault();
765
+ event.stopPropagation();
766
+ const point = state.contextMenu?.point;
767
+ hideContextMenu();
768
+ if (!point || !terminal.__gottyXterm?._core?.coreMouseService?.areMouseEventsActive) return;
769
+ reportTouchMouse("mousedown", { clientX: point.x, clientY: point.y }, 2);
770
+ reportTouchMouse("mouseup", { clientX: point.x, clientY: point.y }, 2);
771
+ });
772
+
679
773
  state.contextMenu = {
680
774
  root: menu,
681
- removeButton,
775
+ removeButton, rightButton, separator,
682
776
  targetKey: null
683
777
  };
684
778
 
@@ -722,6 +816,9 @@
722
816
  function showContextMenu(x, y, key) {
723
817
  const menu = ensureContextMenu();
724
818
  menu.targetKey = key;
819
+ menu.point = { x, y };
820
+ const reporting = !!terminal.__gottyXterm?._core?.coreMouseService?.areMouseEventsActive;
821
+ menu.rightButton.hidden = menu.separator.hidden = !reporting;
725
822
  menu.root.hidden = false;
726
823
 
727
824
  const margin = 10;
@@ -982,7 +1079,31 @@
982
1079
  state.outputTail = text.slice(-64);
983
1080
  }
984
1081
 
985
- function handleKittyMessage(payload) {
1082
+ // Only a server advertising this capability receives the private control.
1083
+ const frameFlowSockets = new WeakSet();
1084
+ function sendFrameControl(socket, fields) {
1085
+ if (socket?.readyState === 1 && frameFlowSockets.has(socket))
1086
+ socket.send("G" + JSON.stringify({version: 1, ...fields}));
1087
+ }
1088
+ function inspectFrameCapability(socket, data) {
1089
+ if (typeof data !== "string" || data[0] !== "a") return;
1090
+ try {
1091
+ if (JSON.parse(data.slice(1)).kittyFrameFlow !== 1 || frameFlowSockets.has(socket)) return;
1092
+ frameFlowSockets.add(socket);
1093
+ sendFrameControl(socket, {visible: !document.hidden});
1094
+ } catch {}
1095
+ }
1096
+ document.addEventListener("visibilitychange", () => {
1097
+ sendFrameControl(state.socket, {visible: !document.hidden});
1098
+ });
1099
+ function acknowledgeFrame(socket, sequence) {
1100
+ if (!Number.isSafeInteger(sequence)) return;
1101
+ // rAF stops while hidden and also bounds delivery if WebView is suspended
1102
+ // without a visibility event. Credits belong to their original connection.
1103
+ requestAnimationFrame(() => sendFrameControl(socket, {ack: sequence}));
1104
+ }
1105
+
1106
+ function handleKittyMessage(payload, socket) {
986
1107
  const message = JSON.parse(payload);
987
1108
  sendBrowserDebug("kitty-message", {
988
1109
  kind: message.kind,
@@ -994,7 +1115,9 @@
994
1115
  // The server records this cursor exactly where the Kitty APC occurred.
995
1116
  // Do not replace it with xterm's later cursor, which may already have
996
1117
  // moved because of redraw or scrolling output queued after the APC.
997
- placeImage(message);
1118
+ Promise.resolve(placeImage(message)).catch(error => {
1119
+ console.warn("Kitty image decode failed", error);
1120
+ }).finally(() => acknowledgeFrame(socket, message.frameSequence));
998
1121
  return true;
999
1122
  }
1000
1123
  if (message.kind === "delete") {
@@ -1004,6 +1127,15 @@
1004
1127
  return false;
1005
1128
  }
1006
1129
 
1130
+ const watchedSockets = new WeakSet();
1131
+ function watchTouchSocket(socket) {
1132
+ if (watchedSockets.has(socket)) return;
1133
+ watchedSockets.add(socket);
1134
+ socket.addEventListener("close", () => {
1135
+ if (state.socket === socket) state.cancelTouchGesture?.();
1136
+ });
1137
+ }
1138
+
1007
1139
  const nativeSend = WebSocket.prototype.send;
1008
1140
  const nativeOnOpen = WebSocket.prototype.addEventListener;
1009
1141
  WebSocket.prototype.addEventListener = function (type, listener, options) {
@@ -1012,9 +1144,11 @@
1012
1144
  }
1013
1145
  const wrapped = function (event) {
1014
1146
  state.socket = this;
1147
+ watchTouchSocket(this);
1148
+ inspectFrameCapability(this, event.data);
1015
1149
  inspectTerminalOutput(event.data);
1016
1150
  if (typeof event.data === "string" && event.data[0] === MSG_KITTY) {
1017
- if (handleKittyMessage(event.data.slice(1))) {
1151
+ if (handleKittyMessage(event.data.slice(1), this)) {
1018
1152
  return;
1019
1153
  }
1020
1154
  }
@@ -1058,9 +1192,11 @@
1058
1192
  }
1059
1193
  const wrapped = function (event) {
1060
1194
  state.socket = this;
1195
+ watchTouchSocket(this);
1196
+ inspectFrameCapability(this, event.data);
1061
1197
  inspectTerminalOutput(event.data);
1062
1198
  if (typeof event.data === "string" && event.data[0] === MSG_KITTY) {
1063
- if (handleKittyMessage(event.data.slice(1))) {
1199
+ if (handleKittyMessage(event.data.slice(1), this)) {
1064
1200
  return;
1065
1201
  }
1066
1202
  }
@@ -0,0 +1,43 @@
1
+ // CHROMIUM_HEADLESS=/usr/local/bin/chromium-headless-shell bun test tests/kitty-flow-browser.test.js
2
+ const test=require('node:test'),assert=require('node:assert/strict');
3
+ const fs=require('node:fs'),path=require('node:path'),http=require('node:http');
4
+ const {spawn}=require('node:child_process'),{once}=require('node:events');
5
+ const WebSocket=require('ws'),{KittyFrameFlow}=require('../kitty-flow.js');
6
+ test('real browser resumes latest image after visibility loss or suspended animation callbacks',{skip:!process.env.CHROMIUM_HEADLESS,timeout:30000},async()=>{
7
+ const source=fs.readFileSync(path.join(__dirname,'../static/js/kitty.js'));
8
+ const server=http.createServer((req,res)=>{
9
+ if(req.url==='/kitty.js'){res.setHeader('Content-Type','text/javascript');res.end(source);return;}
10
+ res.end(`<div id="terminal" style="width:800px;height:600px"><div class="xterm-screen"></div></div><div id="kitty-overlay"></div>
11
+ <script>window.hidden=false;Object.defineProperty(document,'hidden',{get:()=>window.hidden});window.held=[];window.suspended=false;const raf=window.requestAnimationFrame.bind(window);window.requestAnimationFrame=fn=>suspended?(held.push(fn),0):raf(fn);</script>
12
+ <script src="/kitty.js"></script><script>window.messages=[];window.socket=new WebSocket('ws://'+location.host);socket.onmessage=e=>messages.push(e.data);</script>`);
13
+ });server.listen(0,'127.0.0.1');await once(server,'listening');
14
+ const wss=new WebSocket.WebSocketServer({server});let flow,socket,count=0,last=null;
15
+ wss.on('connection',ws=>{socket=ws;flow=new KittyFrameFlow(g=>{count++;last=g;ws.send('7'+JSON.stringify(g));});ws.on('message',m=>{if(String(m)[0]==='G')flow.control(JSON.parse(String(m).slice(1)))});ws.send('a{"kittyFrameFlow":1}');});
16
+ const child=spawn(process.env.CHROMIUM_HEADLESS,['--no-sandbox','--disable-gpu','--remote-debugging-port=0','http://127.0.0.1:'+server.address().port],{stdio:['ignore','ignore','pipe']});let cdp;
17
+ try{
18
+ const endpoint=await new Promise((resolve,reject)=>{let log='';child.on('error',reject);child.stderr.on('data',b=>{log+=b;const m=log.match(/DevTools listening on (ws:\/\/[^\s]+)/);if(m)resolve(m[1]);});});
19
+ let tab;for(let i=0;i<100;i++){tab=(await(await fetch('http://'+new URL(endpoint).host+'/json/list')).json()).find(x=>x.type==='page');if(tab)break;await new Promise(r=>setTimeout(r,20));}
20
+ cdp=new WebSocket(tab.webSocketDebuggerUrl);await once(cdp,'open');let id=0;const pending=new Map();cdp.on('message',data=>{const m=JSON.parse(data),p=pending.get(m.id);if(p){pending.delete(m.id);m.error?p.reject(m.error):p.resolve(m.result)}});
21
+ const call=(method,params)=>new Promise((resolve,reject)=>{pending.set(++id,{resolve,reject});cdp.send(JSON.stringify({id,method,params}));});
22
+ const evaluate=async expression=>{const r=await call('Runtime.evaluate',{expression,returnByValue:true,awaitPromise:true});if(r.exceptionDetails)throw Error(JSON.stringify(r.exceptionDetails));return r.result.value;};
23
+ const until=async check=>{for(let i=0;i<100;i++){if(await check())return;await new Promise(r=>setTimeout(r,20));}throw Error('fixture timed out')};
24
+ await until(()=>flow?.enabled);
25
+ const png=await evaluate(`(()=>{const c=document.createElement('canvas');c.width=c.height=1;c.getContext('2d').fillRect(0,0,1,1);return c.toDataURL().split(',')[1]})()`);
26
+ const frame=n=>({kind:'placement',control:{i:'1',C:'1',c:'2',r:'2'},cursor:{row:1,col:1},image:{id:'1',format:100,data:png},testFrame:n});
27
+ flow.graphic(frame(0));await until(()=>flow.inFlight.size===0);
28
+ await evaluate('window.hidden=true;document.dispatchEvent(new Event("visibilitychange"))');await until(()=>flow.visible===false);
29
+ const before=count;for(let n=1;n<=1800;n++)flow.graphic(frame(n));assert.equal(count,before);assert.equal(flow.pending.size,1);
30
+ socket.send('1'+Buffer.from('TEXT_WHILE_HIDDEN').toString('base64'));
31
+ await until(async()=>await evaluate('messages.some(x=>x.startsWith("1"))'));
32
+ await evaluate('window.hidden=false;document.dispatchEvent(new Event("visibilitychange"))');await until(()=>flow.inFlight.size===0&&last.testFrame===1800);
33
+ assert.equal(count,before+1);
34
+ // A renderer can freeze without delivering visibilitychange. Missing rAF
35
+ // acknowledgements still bound the server to two outstanding frames.
36
+ await evaluate('window.suspended=true');const baseline=count;
37
+ for(let n=1801;n<=3600;n++)flow.graphic(frame(n));assert.equal(count,baseline+2);assert.equal(flow.pending.size,1);
38
+ await until(async()=>await evaluate('held.length>=2'));
39
+ await evaluate('window.suspended=false;for(const fn of held.splice(0))requestAnimationFrame(fn)');
40
+ await until(()=>flow.inFlight.size===0&&last.testFrame===3600);assert.equal(count,baseline+3);
41
+ await until(async()=>await evaluate('document.querySelector("img.kitty-image__content").naturalWidth===1'));
42
+ }finally{cdp?.close();for(const ws of wss.clients)ws.terminate();wss.close();server.close();child.kill();}
43
+ });
@@ -0,0 +1,55 @@
1
+ const {test}=require('node:test');
2
+ const assert=require('node:assert/strict');
3
+ const {KittyFrameFlow}=require('../kitty-flow.js');
4
+ const graphic=(n,id='1')=>({kind:'placement',control:{i:id,C:'1'},cursor:{row:2,col:1},image:{id,data:String(n)}});
5
+ test('browser credits bound suspension to two frames and latest replacement',()=>{
6
+ const sent=[],flow=new KittyFrameFlow(g=>sent.push(g));
7
+ assert.equal(flow.graphic(graphic(0)),false); // CLI and old WebViews unchanged
8
+ flow.control({version:1,visible:true});
9
+ for(let n=0;n<1800;n++)assert.equal(flow.graphic(graphic(n)),true);
10
+ assert.equal(sent.length,2);assert.equal(flow.pending.size,1);
11
+ flow.control({version:1,ack:9999});assert.equal(sent.length,2);
12
+ flow.control({version:1,ack:sent[0].frameSequence});
13
+ assert.equal(sent.length,3);assert.equal(sent[2].image.data,'1799');
14
+ flow.control({version:1,ack:sent[0].frameSequence});assert.equal(sent.length,3);
15
+ });
16
+ test('hidden viewers keep only latest per placement and resume without another update',()=>{
17
+ const sent=[],flow=new KittyFrameFlow(g=>sent.push(g));flow.control({version:1,visible:false});
18
+ for(let n=0;n<100;n++){flow.graphic(graphic(n,'1'));flow.graphic(graphic(n,'2'));}
19
+ assert.equal(sent.length,0);assert.equal(flow.pending.size,2);
20
+ flow.control({version:1,visible:true});assert.deepEqual(sent.map(g=>g.image.data),['99','99']);
21
+ });
22
+ test('delete, terminal reset and alternate screen do not resurrect pending images',()=>{
23
+ const sent=[],flow=new KittyFrameFlow(g=>sent.push(g));flow.control({version:1,visible:false});
24
+ flow.graphic(graphic(1));flow.graphic(graphic(2,'2'));
25
+ assert.equal(flow.graphic({kind:'delete',delete:{imageId:'1'}}),false);
26
+ assert.equal(flow.pending.size,1);
27
+ flow.output(Buffer.from('\x1b[?104').toString('base64'));
28
+ flow.output(Buffer.from('9l').toString('base64'));assert.equal(flow.pending.size,0);
29
+ flow.graphic(graphic(3));flow.graphic({kind:'delete',delete:{scope:'a'}});
30
+ flow.control({version:1,visible:true});assert.equal(sent.length,0);
31
+ });
32
+ test('connections have independent credits; normal scrolling images are unchanged',()=>{
33
+ const one=[],two=[],a=new KittyFrameFlow(g=>one.push(g)),b=new KittyFrameFlow(g=>two.push(g));
34
+ a.control({version:1,visible:false});b.control({version:1,visible:true});
35
+ a.graphic(graphic(1));b.graphic(graphic(1));assert.equal(one.length,0);assert.equal(two.length,1);
36
+ const scroll=graphic(2);delete scroll.control.C;assert.equal(a.graphic(scroll),false);
37
+ // A later ordinary placement replaces the same deferred position immediately.
38
+ assert.equal(a.pending.size,0);a.graphic(graphic(3));
39
+ a.output(Buffer.from('ordinary text').toString('base64'));assert.equal(a.pending.size,1);
40
+ });
41
+
42
+ test('browser negotiates only on advertisement and acknowledges after animation opportunity',async()=>{
43
+ const fs=require('node:fs'),vm=require('node:vm'),source=fs.readFileSync(require('node:path').join(__dirname,'../static/js/kitty.js'),'utf8');
44
+ const start=source.indexOf(' // Only a server advertising'),end=source.indexOf(' function deleteImages');
45
+ const helpers=source.slice(start,source.indexOf(' function handleKittyMessage',start));
46
+ const frames=[],events={},sent=[],socket={readyState:1,send:m=>sent.push(JSON.parse(m.slice(1)))};
47
+ const document={hidden:true,addEventListener:(k,fn)=>events[k]=fn};
48
+ const api=vm.runInNewContext(`(()=>{${helpers};return {inspectFrameCapability,acknowledgeFrame}})()`,{document,state:{socket},requestAnimationFrame:fn=>frames.push(fn)});
49
+ api.inspectFrameCapability(socket,'a{"role":"viewer"}');assert.equal(sent.length,0);
50
+ api.inspectFrameCapability(socket,'a{"kittyFrameFlow":1}');assert.equal(sent[0].visible,false);
51
+ api.acknowledgeFrame(socket,1);assert.equal(sent.length,1); // suspended rAF
52
+ document.hidden=false;events.visibilitychange();assert.equal(sent[1].visible,true);
53
+ frames.shift()();assert.equal(sent[2].ack,1);
54
+ socket.readyState=3;api.acknowledgeFrame(socket,2);frames.shift()();assert.equal(sent.length,3);
55
+ });
@@ -0,0 +1,18 @@
1
+ // bun tests/manual/fps-collector.mjs [log.jsonl]
2
+ import {appendFileSync} from 'node:fs';
3
+ import {resolve} from 'node:path';
4
+ const log=resolve(process.argv[2]||'jsgotty-fps.jsonl'),token=crypto.randomUUID();
5
+ const source=await Bun.file(new URL('./fps-debug.js',import.meta.url)).text();
6
+ let rows=0;
7
+ const headers={'Access-Control-Allow-Origin':'*','Access-Control-Allow-Methods':'POST, OPTIONS','Access-Control-Allow-Headers':'Content-Type','Access-Control-Allow-Private-Network':'true','Cache-Control':'no-store'};
8
+ const server=Bun.serve({hostname:'127.0.0.1',port:0,maxRequestBodySize:262144,async fetch(req){
9
+ if(new URL(req.url).pathname!=='/'+token)return new Response('',{status:404});
10
+ if(req.method==='OPTIONS')return new Response(null,{status:204,headers});
11
+ if(req.method!=='POST')return new Response('',{status:405,headers});
12
+ if(rows>=1200)return new Response('',{status:429,headers});
13
+ try{const row=await req.json();appendFileSync(log,JSON.stringify({receivedAt:Date.now(),...row})+'\n',{mode:0o600});rows++;return new Response(null,{status:204,headers});}
14
+ catch{return new Response('',{status:400,headers});}
15
+ }});
16
+ const endpoint=`http://127.0.0.1:${server.port}/${token}`;
17
+ const script=log+'.inject.js';await Bun.write(script,source+'\nwindow.startGottyFpsDebug({endpoint:'+JSON.stringify(endpoint)+'});\n');
18
+ console.log(JSON.stringify({endpoint,log,script,pid:process.pid}));
@@ -0,0 +1,31 @@
1
+ // Eval manually; counts completed Kitty <img> loads, not physical display flips.
2
+ window.startGottyFpsDebug = ({endpoint, duration=600000}={}) => {
3
+ window.stopGottyFpsDebug?.(); window.stopKittyFPS?.();
4
+ const box=document.createElement('div');
5
+ box.style.cssText='position:fixed;top:0;right:0;z-index:2147483647;background:#000b;color:cyan;padding:4px 8px;font:16px monospace;pointer-events:none';
6
+ box.textContent='Kitty: 0 FPS';document.body.append(box);
7
+ const session=Date.now().toString(36),ids=new WeakMap();let id=0,previous=0,started=performance.now(),last=started,frames=[],busy=false,dropped=0,sequence=0,stopped=false;
8
+ const records=[];window.__gottyFpsRecords=records;
9
+ const load=e=>{const el=e.target;if(!el.matches?.('img.kitty-image__content'))return;
10
+ const now=performance.now();if(!ids.has(el))ids.set(el,++id);
11
+ if(frames.length<2000)frames.push({t:now,id:ids.get(el),gap:previous?now-previous:null,w:el.naturalWidth,h:el.naturalHeight});else dropped++;
12
+ previous=now;
13
+ };
14
+ document.addEventListener('load',load,true);
15
+ const flush=()=>{
16
+ const now=performance.now(),batch=frames;frames=[];
17
+ const gaps=batch.map(f=>f.gap).filter(g=>g!==null).sort((a,b)=>a-b);
18
+ const row={session,sequence:sequence++,time:Date.now(),timeOrigin:performance.timeOrigin,elapsed:now-last,fps:batch.length*1000/(now-last),hidden:document.hidden,frames:batch,dropped,
19
+ p95:gaps[Math.floor(gaps.length*.95)]??null,p99:gaps[Math.floor(gaps.length*.99)]??null,max:gaps.at(-1)??null};last=now;
20
+ box.textContent=`Kitty: ${row.fps.toFixed(1)} FPS`;
21
+ records.push(row);if(records.length>600)records.shift();window.__gottyFpsLatest=row;
22
+ if(endpoint&&!busy){busy=true;fetch(endpoint,{method:'POST',headers:{'Content-Type':'text/plain'},body:JSON.stringify(row),signal:AbortSignal.timeout(5000)})
23
+ .then(r=>{if(!r.ok)throw Error('HTTP '+r.status);window.__gottyFpsDeliveryError=null;})
24
+ .catch(e=>{window.__gottyFpsDeliveryError=String(e);dropped+=batch.length;}).finally(()=>{busy=false;});}
25
+ else if(endpoint)dropped+=batch.length;
26
+ };
27
+ const timer=setInterval(flush,1000);
28
+ const expiry=setTimeout(()=>window.stopGottyFpsDebug?.(),Math.max(1000,Math.min(duration,600000)));
29
+ window.stopGottyFpsDebug=()=>{if(stopped)return;stopped=true;document.removeEventListener('load',load,true);clearInterval(timer);clearTimeout(expiry);box.remove();};
30
+ return 'Kitty FPS enabled (image loads; auto-stop in at most 10 minutes)';
31
+ };
@@ -0,0 +1,35 @@
1
+ (() => {
2
+ window.stopKittyFPS?.();
3
+
4
+ const box = document.createElement("div");
5
+ box.style.cssText =
6
+ "position:fixed;top:0;right:0;z-index:2147483647;" +
7
+ "background:#000b;color:cyan;padding:4px 8px;" +
8
+ "font:16px monospace;pointer-events:none";
9
+ box.textContent = "Kitty: 0 FPS";
10
+ document.body.append(box);
11
+
12
+ let count = 0, last = performance.now();
13
+ const loaded = e => {
14
+ if (e.target.matches?.("img.kitty-image__content"))
15
+ count++;
16
+ };
17
+ document.addEventListener("load", loaded, true);
18
+
19
+ const timer = setInterval(() => {
20
+ const now = performance.now();
21
+ box.textContent =
22
+ `Kitty: ${(count * 1000 / (now - last)).toFixed(1)}
23
+ FPS`;
24
+ count = 0;
25
+ last = now;
26
+ }, 1000);
27
+
28
+ window.stopKittyFPS = () => {
29
+ clearInterval(timer);
30
+ document.removeEventListener("load", loaded, true);
31
+ box.remove();
32
+ delete window.stopKittyFPS;
33
+ };
34
+ return "Kitty FPS enabled";
35
+ })()
@@ -0,0 +1,24 @@
1
+ // Eval manually. Counts delivery, bitmap decoding, image loads and animation ticks.
2
+ // Observational only: no frame dropping, focus changes or socket reconnects.
3
+ window.startKittyBackgroundDebug = (endpoint) => {
4
+ window.stopKittyBackgroundDebug?.();
5
+ const parse=JSON.parse,bitmap=window.createImageBitmap,history=[];
6
+ let received=0,bytes=0,decoded=0,loads=0,ticks=0,pending=0,maxPending=0,decodeMs=0,last=performance.now(),busy=false,stopped=false,raf;
7
+ const wrappedParse=function(...args){const v=parse.apply(this,args);if(v?.kind==='placement'&&v.image){received++;bytes+=v.image.data?.length||0;}return v;};
8
+ const wrappedBitmap=async function(...args){const start=performance.now();pending++;maxPending=Math.max(maxPending,pending);try{return await bitmap.apply(this,args)}finally{pending--;decoded++;decodeMs+=performance.now()-start;}};
9
+ JSON.parse=wrappedParse;if(bitmap)window.createImageBitmap=wrappedBitmap;
10
+ const load=e=>{if(e.target.matches?.('img.kitty-image__content'))loads++;};
11
+ document.addEventListener('load',load,true);
12
+ const tick=()=>{ticks++;if(!stopped)raf=requestAnimationFrame(tick)};raf=requestAnimationFrame(tick);
13
+ function flush(reason='interval'){
14
+ const now=performance.now(),row={kind:'background-profile',time:Date.now(),elapsed:now-last,reason,hidden:document.hidden,received,bytes,decoded,loads,ticks,pending,maxPending,decodeMs};
15
+ last=now;received=bytes=decoded=loads=ticks=decodeMs=0;maxPending=pending;
16
+ history.push(row);if(history.length>600)history.shift();window.__kittyBackgroundLatest=row;
17
+ if(endpoint&&!busy){busy=true;fetch(endpoint,{method:'POST',headers:{'Content-Type':'text/plain'},body:JSON.stringify(row),signal:AbortSignal.timeout(5000)}).catch(()=>{}).finally(()=>busy=false);}
18
+ }
19
+ const visibility=()=>flush('visibilitychange');document.addEventListener('visibilitychange',visibility);
20
+ const timer=setInterval(flush,1000),expiry=setTimeout(()=>window.stopKittyBackgroundDebug(),600000);
21
+ window.__kittyBackgroundHistory=history;
22
+ window.stopKittyBackgroundDebug=()=>{stopped=true;if(JSON.parse===wrappedParse)JSON.parse=parse;if(window.createImageBitmap===wrappedBitmap)window.createImageBitmap=bitmap;document.removeEventListener('load',load,true);document.removeEventListener('visibilitychange',visibility);cancelAnimationFrame(raf);clearInterval(timer);clearTimeout(expiry);};
23
+ return 'background diagnostic enabled';
24
+ };
@@ -0,0 +1,55 @@
1
+ // Usage: node tests/manual/zoom-collector.cjs [port] [output.jsonl]
2
+ const http = require('node:http');
3
+ const fs = require('node:fs');
4
+ const path = require('node:path');
5
+ const os = require('node:os');
6
+ const { randomBytes } = require('node:crypto');
7
+ const port = Number(process.argv[2] || 18767);
8
+ const file = path.resolve(process.argv[3] || path.join(os.tmpdir(), 'jsgotty-zoom-debug.jsonl'));
9
+ const token = randomBytes(16).toString('hex');
10
+ const endpoint = `http://127.0.0.1:${port}/${token}`;
11
+ const client = fs.readFileSync(path.join(__dirname, 'zoom-debug.js'), 'utf8') +
12
+ `\nwindow.startGottyZoomDebug({endpoint:${JSON.stringify(endpoint)}});\n`;
13
+ let count = 0;
14
+ http.createServer((req, res) => {
15
+ res.setHeader('Access-Control-Allow-Origin', '*');
16
+ res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
17
+ res.setHeader('Access-Control-Allow-Headers', 'Content-Type');
18
+ res.setHeader('Access-Control-Allow-Private-Network', 'true');
19
+ res.setHeader('Cache-Control', 'no-store');
20
+ if (req.url !== '/' + token && req.url !== '/' + token + '/client.js') {
21
+ res.writeHead(404); return res.end();
22
+ }
23
+ if (req.method === 'OPTIONS') { res.writeHead(204); return res.end(); }
24
+ if (req.method === 'GET' && req.url.endsWith('/client.js')) {
25
+ res.setHeader('Content-Type', 'application/javascript');
26
+ return res.end(client);
27
+ }
28
+ if (req.method !== 'POST' || req.url !== '/' + token) {
29
+ res.writeHead(405); return res.end();
30
+ }
31
+ let body = '';
32
+ req.on('data', chunk => {
33
+ body += chunk;
34
+ if (body.length > 16384) req.destroy();
35
+ });
36
+ req.on('end', () => {
37
+ if (count >= 20000) { res.writeHead(429); return res.end(); }
38
+ let event;
39
+ try { event = JSON.parse(body); }
40
+ catch { res.writeHead(400); return res.end(); }
41
+ try {
42
+ fs.appendFileSync(file, JSON.stringify({receivedAt: new Date().toISOString(), event}) + '\n', {mode: 0o600});
43
+ count++;
44
+ res.writeHead(204); res.end();
45
+ } catch (error) {
46
+ console.error(error.message);
47
+ res.writeHead(500); res.end();
48
+ }
49
+ });
50
+ }).listen(port, '127.0.0.1', () => {
51
+ console.log('Log (append): ' + file);
52
+ console.log('Run in the connected jsgotty page via DevTools or CDP:');
53
+ console.log(`fetch(${JSON.stringify(endpoint + '/client.js')}).then(r => r.text()).then(source => (0, eval)(source))`);
54
+ console.log('Stop browser capture: window.stopGottyZoomDebug()');
55
+ });
@@ -0,0 +1,39 @@
1
+ // Manual WebView zoom diagnostics. Does not change focus, selection or gestures.
2
+ window.startGottyZoomDebug = ({endpoint} = {}) => {
3
+ window.stopGottyZoomDebug?.();
4
+ window.__zoomDiag?.stop();
5
+ const logs = [], cleanup = [], started = Date.now();
6
+ const session = Math.random().toString(36).slice(2);
7
+ let stopped = false;
8
+ const label = el => el ? `${el.tagName || ''}#${el.id || ''}.${String(el.className || '')}` : null;
9
+ const record = event => {
10
+ if (stopped || logs.length >= 4000 || Date.now() - started > 600000) return;
11
+ const v = window.visualViewport, active = document.activeElement;
12
+ const row = {session, sequence:logs.length, time:Date.now(), type:event.type,
13
+ target:label(event.target), active:label(active), trusted:event.isTrusted,
14
+ touches:event.touches?.length, viewport:document.querySelector('meta[name=viewport]')?.content,
15
+ scale:v?.scale, offset:v ? [v.offsetLeft,v.offsetTop] : null,
16
+ size:v ? [v.width,v.height] : null, scroll:[scrollX,scrollY],
17
+ selection:document.getSelection()?.type,
18
+ fontSize:active ? getComputedStyle(active).fontSize : null};
19
+ logs.push(row);
20
+ if(endpoint) fetch(endpoint,{method:'POST',headers:{'Content-Type':'text/plain'},body:JSON.stringify(row)})
21
+ .catch(e=>{window.__gottyZoomDeliveryError=String(e)});
22
+ };
23
+ const listen=(target,type)=>{
24
+ target.addEventListener(type,record,{capture:true,passive:true});
25
+ cleanup.push(()=>target.removeEventListener(type,record,true));
26
+ };
27
+ for(const type of ['touchstart','touchend','touchcancel','mousedown','mouseup','click',
28
+ 'contextmenu','focusin','focusout','selectionchange','visibilitychange'])listen(document,type);
29
+ if(window.visualViewport)for(const type of ['resize','scroll'])listen(visualViewport,type);
30
+ const observer=new MutationObserver(()=>record({type:'viewport-mutation'}));
31
+ const meta=document.querySelector('meta[name=viewport]');
32
+ if(meta)observer.observe(meta,{attributes:true});
33
+ cleanup.push(()=>observer.disconnect());
34
+ window.stopGottyZoomDebug=()=>{stopped=true;cleanup.forEach(fn=>fn())};
35
+ window.__gottyZoomRecords=logs;
36
+ window.markGottyZoomDebug=label=>record({type:'mark:'+label});
37
+ record({type:'ready'});
38
+ return 'Zoom diagnostics started';
39
+ };
@@ -0,0 +1,106 @@
1
+ // Opt-in real bundled-xterm integration; no browser/dependency downloads.
2
+ // CHROMIUM_HEADLESS=/path/to/chromium-headless-shell node --test tests/touch-drag-browser.test.js
3
+ const test=require('node:test');
4
+ const assert=require('node:assert/strict');
5
+ const fs=require('node:fs');
6
+ const path=require('node:path');
7
+ const http=require('node:http');
8
+ const {spawn}=require('node:child_process');
9
+ const {once}=require('node:events');
10
+ const WebSocket=require('ws');
11
+ const root=path.join(__dirname,'../static');
12
+ test('touch double-tap drag and image-menu right click use bundled xterm', {skip:!process.env.CHROMIUM_HEADLESS,timeout:60000},async()=>{
13
+ const bundle=fs.readFileSync(path.join(root,'js/gotty.js'),'utf8').replace('(i.nc = void 0));','(i.nc = void 0)); window.TestGoTTYXterm = i(634).GoTTYXterm;');
14
+ const server=http.createServer((req,res)=>{
15
+ if(req.url==='/index.css'){res.setHeader('Content-Type','text/css');res.end(fs.readFileSync(path.join(root,'css/index.css')));}
16
+ else if(req.url==='/bundle.js'){res.setHeader('Content-Type','text/javascript');res.end(bundle);}
17
+ else if(req.url==='/gestures.js'){
18
+ const source=fs.readFileSync(path.join(root,'js/kitty.js'),'utf8');
19
+ res.setHeader('Content-Type','text/javascript');
20
+ res.end(source.slice(source.indexOf(' function reportTouchMouse('),source.indexOf(' function ensureContextMenu('))+source.slice(source.indexOf(' function ensureContextMenu('),source.indexOf(' function bindImageContextMenu('))+source.slice(source.indexOf(' function bindImageContextMenu('),source.indexOf(' function bindImageContextMenu(')+source.slice(source.indexOf(' function bindImageContextMenu(')).indexOf('\n function ',5))+'\nbindTouchScrolling();bindImageContextMenu();');
21
+ }
22
+ else if(req.url==='/keyboard.js'){res.setHeader('Content-Type','text/javascript');res.end(fs.readFileSync(path.join(root,'js/kitty-keyboard.js')));}
23
+ else res.end('<!doctype html><div id="terminal"><div id="fixture" style="width:800px;height:600px"></div></div><link rel="stylesheet" href="/index.css"><script src="/keyboard.js"></script><script src="/bundle.js"></script><script>window.wrapper=new TestGoTTYXterm(document.getElementById("fixture"));window.sent=[];wrapper.onInput(b=>sent.push(new TextDecoder().decode(b)));wrapper.kittyKeyboard.android=true;</script>');
24
+ });
25
+ server.listen(0,'127.0.0.1');await once(server,'listening');
26
+ const child=spawn(process.env.CHROMIUM_HEADLESS,['--no-sandbox','--disable-gpu','--remote-debugging-port=0','http://127.0.0.1:'+server.address().port],{detached:true,stdio:['ignore','ignore','pipe']});
27
+ let ws;
28
+ try{
29
+ const endpoint=await new Promise((resolve,reject)=>{let log='';const timer=setTimeout(()=>reject(Error('Browser startup timeout: '+log)),15000);child.on('error',reject);child.on('exit',code=>{clearTimeout(timer);reject(Error('Browser exited '+code+': '+log));});child.stderr.on('data',b=>{log+=b;const m=log.match(/DevTools listening on (ws:\/\/[^\s]+)/);if(m){clearTimeout(timer);resolve(m[1]);}});});
30
+ const u=new URL(endpoint);let tab;
31
+ for(let i=0;i<50;i++){tab=(await (await fetch('http://'+u.host+'/json/list')).json()).find(x=>x.type==='page');if(tab)break;await new Promise(r=>setTimeout(r,100));}
32
+ ws=new WebSocket(tab.webSocketDebuggerUrl);await once(ws,'open');let id=0;const pending=new Map();ws.on('message',data=>{const m=JSON.parse(data);if(pending.has(m.id)){const {resolve,reject}=pending.get(m.id);pending.delete(m.id);m.error?reject(m.error):resolve(m.result);}});
33
+ const call=(method,params)=>new Promise((resolve,reject)=>{pending.set(++id,{resolve,reject});ws.send(JSON.stringify({id,method,params}));});
34
+ for(let i=0;i<50;i++){const r=await call('Runtime.evaluate',{expression:'Boolean(window.wrapper)',returnByValue:true});if(r.result.value)break;await new Promise(r=>setTimeout(r,100));}
35
+ const result=await call('Runtime.evaluate',{awaitPromise:true,returnByValue:true,expression:`(async()=>{
36
+ const term=wrapper.term;
37
+ const write=s=>new Promise(r=>term.write(s,r));
38
+ const equal=(a,b)=>{if(JSON.stringify(a)!==JSON.stringify(b))throw Error(JSON.stringify({actual:a,expected:b}));};
39
+ await write('\\x1b[?1002h\\x1b[?1006h');
40
+ const terminal=document.getElementById('fixture');terminal.__gottyXterm=term;
41
+ const screen=term.element.querySelector('.xterm-screen'), rect=screen.getBoundingClientRect();
42
+ const state={placements:new Map()};
43
+ const xtermElements=()=>({screen});
44
+ const DEFAULT_TOUCH_SCROLL_THRESHOLD=24;
45
+ const removePlacementNode=node=>node.remove();
46
+ eval(await (await fetch('/gestures.js')).text());
47
+ const touch=(type,x=30,y=30,count=1)=>{
48
+ const point=new Touch({identifier:1,target:screen,clientX:rect.left+x,clientY:rect.top+y});
49
+ const touches=type==='touchend'||type==='touchcancel'?[]:count===1?[point]:[point,new Touch({identifier:2,target:screen,clientX:rect.left+x+30,clientY:rect.top+y})];
50
+ const event=new TouchEvent(type,{bubbles:true,cancelable:true,touches,changedTouches:[point]});
51
+ screen.dispatchEvent(event);return event.defaultPrevented;
52
+ };
53
+ const codes=()=>sent.map(s=>{const m=s.match(/<([0-9]+);[0-9]+;[0-9]+([Mm])/);return m?m[1]+m[2]:s;});
54
+ let focusCalls=0;const originalFocus=term._core.focus;term._core.focus=function(...args){focusCalls++;return originalFocus.apply(this,args);};
55
+ const firstTap=()=>{touch('touchstart');touch('touchend');
56
+ // Browser compatibility mouse sequence after an ordinary tap.
57
+ for(const type of ['mousedown','mouseup'])screen.dispatchEvent(new MouseEvent(type,{bubbles:true,clientX:rect.left+30,clientY:rect.top+30,button:0,buttons:type==='mousedown'?1:0}));};
58
+ sent.length=0;firstTap();equal(codes(),['0M','0m']);
59
+ const focusBeforeDrag=focusCalls;
60
+ if(!touch('touchstart'))throw Error('Second press must suppress compatibility click');
61
+ equal(codes(),['0M','0m','0M']); // still held, no premature release
62
+ touch('touchmove',80,70);touch('touchend',80,70);
63
+ equal(codes(),['0M','0m','0M','32M','0m']);
64
+ equal(focusCalls,focusBeforeDrag);
65
+ sent.length=0;firstTap();touch('touchstart');touch('touchend');
66
+ equal(codes(),['0M','0m','0M','0m']); // ordinary double click
67
+ for(const cancel of [()=>touch('touchcancel'),()=>touch('touchstart',30,30,2),()=>window.dispatchEvent(new Event('blur')),()=>state.cancelTouchGesture()]){
68
+ sent.length=0;firstTap();touch('touchstart');cancel();touch('touchend');equal(codes(),['0M','0m','0M','0m']);
69
+ }
70
+ sent.length=0;firstTap();touch('touchstart');
71
+ touch('touchmove',-200,-200);touch('touchend',-200,-200);
72
+ equal(codes(),['0M','0m','0M','32M','0m']); // release outside grid still reaches application
73
+ sent.length=0;touch('touchstart');touch('touchmove',30,90);touch('touchend',30,90);
74
+ if(!codes().length||codes().some(x=>!x.startsWith('64')))throw Error('Single touch must remain scrolling: '+codes());
75
+ sent.length=0;touch('touchstart');touch('touchmove',30,90);touch('touchend',30,90);
76
+ if(codes().some(x=>x==='0M'))throw Error('Scroll must not arm double tap');
77
+ // Use precisely the existing image context-menu path, with its original location.
78
+ const node=document.createElement('div');node.style.zIndex='0';node.getBoundingClientRect=()=>({left:0,top:0,right:1000,bottom:1000});state.placements.set('image',node);
79
+ screen.dispatchEvent(new MouseEvent('contextmenu',{bubbles:true,cancelable:true,clientX:rect.left+30,clientY:rect.top+30,button:2}));
80
+ if(state.contextMenu.root.hidden)throw Error('Menu missing');
81
+ const focusBeforeRight=focusCalls;
82
+ sent.length=0;state.contextMenu.rightButton.click();equal(focusCalls,focusBeforeRight);equal(codes(),['2M','2m']);
83
+ if(!state.contextMenu.root.hidden||!state.placements.has('image'))throw Error('Right click must hide menu and preserve image');
84
+ await write('\\x1b[?1002l');state.cancelTouchGesture();sent.length=0;
85
+ firstTap();touch('touchstart');touch('touchmove',80,70);touch('touchend');
86
+ if(codes().some(x=>/^[032][Mm]$/.test(x)))throw Error('No application mouse reporting outside mouse mode');
87
+ state.cancelTouchGesture();state.placements.clear();
88
+ term.focus();const textarea=term.textarea;
89
+ screen.dispatchEvent(new MouseEvent('contextmenu',{bubbles:true,cancelable:true,clientX:rect.left+30,clientY:rect.top+30,button:2}));
90
+ if(document.activeElement!==textarea)throw Error('Context menu must keep textarea focused for native paste');
91
+ const data=new DataTransfer();data.setData('text/plain','paste-check');sent.length=0;
92
+ textarea.dispatchEvent(new ClipboardEvent('paste',{bubbles:true,cancelable:true,clipboardData:data}));
93
+ if(!sent.join('').includes('paste-check'))throw Error('Paste stopped working');
94
+ equal(getComputedStyle(textarea).touchAction,'none');
95
+ equal(getComputedStyle(screen).touchAction,'manipulation');
96
+ touch('touchstart');
97
+ if(document.activeElement!==textarea)throw Error('Touch must not blur the input');
98
+ touch('touchend');
99
+ wrapper.close();return 'ok';
100
+ })()`});
101
+ assert.equal(result.exceptionDetails,undefined,JSON.stringify(result.exceptionDetails));assert.equal(result.result.value,'ok');
102
+ }finally{
103
+ ws?.close();if(child.pid){try{process.kill(-child.pid,'SIGTERM');}catch{}}
104
+ server.closeAllConnections();await new Promise(r=>server.close(r));
105
+ }
106
+ });
@@ -0,0 +1,60 @@
1
+ // Opt-in real bundled-xterm integration; no browser/dependency downloads.
2
+ // CHROMIUM_HEADLESS=/path/to/chromium-headless-shell node --test tests/kitty-keyboard-browser.test.js
3
+ const test=require('node:test');
4
+ const assert=require('node:assert/strict');
5
+ const fs=require('node:fs');
6
+ const path=require('node:path');
7
+ const http=require('node:http');
8
+ const {spawn}=require('node:child_process');
9
+ const {once}=require('node:events');
10
+ const WebSocket=require('ws');
11
+ const root=path.join(__dirname,'../static');
12
+ test('shipped xterm reports horizontal, vertical and diagonal wheel events', {skip:!process.env.CHROMIUM_HEADLESS,timeout:60000},async()=>{
13
+ const bundle=fs.readFileSync(path.join(root,'js/gotty.js'),'utf8').replace('(i.nc = void 0));','(i.nc = void 0)); window.TestGoTTYXterm = i(634).GoTTYXterm;');
14
+ const server=http.createServer((req,res)=>{
15
+ if(req.url==='/bundle.js'){res.setHeader('Content-Type','text/javascript');res.end(bundle);}
16
+ else if(req.url==='/keyboard.js'){res.setHeader('Content-Type','text/javascript');res.end(fs.readFileSync(path.join(root,'js/kitty-keyboard.js')));}
17
+ else res.end('<!doctype html><div id="fixture" style="width:800px;height:600px"></div><script src="/keyboard.js"></script><script src="/bundle.js"></script><script>window.wrapper=new TestGoTTYXterm(document.getElementById("fixture"));window.sent=[];wrapper.onInput(b=>sent.push(new TextDecoder().decode(b)));wrapper.kittyKeyboard.android=true;</script>');
18
+ });
19
+ server.listen(0,'127.0.0.1');await once(server,'listening');
20
+ const child=spawn(process.env.CHROMIUM_HEADLESS,['--no-sandbox','--disable-gpu','--remote-debugging-port=0','http://127.0.0.1:'+server.address().port],{detached:true,stdio:['ignore','ignore','pipe']});
21
+ let ws;
22
+ try{
23
+ const endpoint=await new Promise((resolve,reject)=>{let log='';const timer=setTimeout(()=>reject(Error('Browser startup timeout: '+log)),15000);child.on('error',reject);child.on('exit',code=>{clearTimeout(timer);reject(Error('Browser exited '+code+': '+log));});child.stderr.on('data',b=>{log+=b;const m=log.match(/DevTools listening on (ws:\/\/[^\s]+)/);if(m){clearTimeout(timer);resolve(m[1]);}});});
24
+ const u=new URL(endpoint);let tab;
25
+ for(let i=0;i<50;i++){tab=(await (await fetch('http://'+u.host+'/json/list')).json()).find(x=>x.type==='page');if(tab)break;await new Promise(r=>setTimeout(r,100));}
26
+ ws=new WebSocket(tab.webSocketDebuggerUrl);await once(ws,'open');let id=0;const pending=new Map();ws.on('message',data=>{const m=JSON.parse(data);if(pending.has(m.id)){const {resolve,reject}=pending.get(m.id);pending.delete(m.id);m.error?reject(m.error):resolve(m.result);}});
27
+ const call=(method,params)=>new Promise((resolve,reject)=>{pending.set(++id,{resolve,reject});ws.send(JSON.stringify({id,method,params}));});
28
+ for(let i=0;i<50;i++){const r=await call('Runtime.evaluate',{expression:'Boolean(window.wrapper)',returnByValue:true});if(r.result.value)break;await new Promise(r=>setTimeout(r,100));}
29
+ const result=await call('Runtime.evaluate',{awaitPromise:true,returnByValue:true,expression:`(async()=>{
30
+ const term=wrapper.term;
31
+ const write=s=>new Promise(r=>term.write(s,r));
32
+ const equal=(a,b)=>{if(JSON.stringify(a)!==JSON.stringify(b))throw Error(JSON.stringify({actual:a,expected:b}));};
33
+ await write('\\x1b[?1002h\\x1b[?1006h');
34
+ const screen=term.element.querySelector('.xterm-screen'), rect=screen.getBoundingClientRect();
35
+ const wheel=(deltaX,deltaY,mods={})=>{
36
+ sent.length=0;
37
+ const event=new WheelEvent('wheel',{clientX:rect.left+20,clientY:rect.top+20,deltaX,deltaY,deltaMode:1,bubbles:true,cancelable:true,...mods});
38
+ screen.dispatchEvent(event);
39
+ if(term._core.coreMouseService.areMouseEventsActive&&!event.defaultPrevented)throw Error('Wheel default was not prevented');
40
+ return sent.map(s=>Number(s.match(/<([0-9]+);/)[1]));
41
+ };
42
+ equal(wheel(-1,0),[66]);equal(wheel(1,0),[67]);
43
+ equal(wheel(0,-1,{shiftKey:true}),[68]);equal(wheel(0,1,{shiftKey:true}),[69]);
44
+ equal(wheel(0,-1),[64]);equal(wheel(0,1),[65]);
45
+ equal(wheel(1,-1),[67,64]);
46
+ equal(wheel(-1,0,{shiftKey:true,altKey:true,ctrlKey:true}),[94]);
47
+ for(let bits=0;bits<8;bits++) {
48
+ const mods={shiftKey:!!(bits&1),altKey:!!(bits&2),ctrlKey:!!(bits&4)};
49
+ for(const [dx,dy,code] of [[0,-1,64],[0,1,65],[-1,0,66],[1,0,67]])
50
+ equal(wheel(dx,dy,mods),[code+(bits<<2)]);
51
+ }
52
+ await write('\\x1b[?1002l');equal(wheel(1,0),[]);
53
+ wrapper.close();return 'ok';
54
+ })()`});
55
+ assert.equal(result.exceptionDetails,undefined,JSON.stringify(result.exceptionDetails));assert.equal(result.result.value,'ok');
56
+ }finally{
57
+ ws?.close();if(child.pid){try{process.kill(-child.pid,'SIGTERM');}catch{}}
58
+ server.closeAllConnections();await new Promise(r=>server.close(r));
59
+ }
60
+ });