hop2 0.11.11 → 0.11.13

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/hay/CHANGELOG.md CHANGED
@@ -23,6 +23,7 @@
23
23
  - **Status bar / hints toggles are session-only**: `Opt+B` (status bar) and `Opt+T` (hints) no longer persist to `.hop.json`, so an in-session toggle can't silently become your permanent default. The default is taken from `.hop.json` (`showStatusBar`/`showHints`, both default `true`); toggles affect only the current session and the notice now says so. (Other toggles like mouse capture and sync-size still persist.)
24
24
 
25
25
  #### Web Client
26
+ - **One size rule everywhere — the last user action owns the terminal size**: the server-side size election (typing-recency plus 60s/2.5s idle windows) is replaced by a single ownership rule: whoever acted last — opened the session or pressed a key — owns the PTY size, and their refits (window drag, rotation, keyboard) flow straight through. A keystroke transfers ownership and snaps the PTY to the typist's declared fit immediately. `active_size` is now interpreted by **identity** (the owner's clientId) instead of by comparing sizes. When a peer owns the size, the web terminal in Auto-fit now **follows the owner's grid** — rendered at the PTY's true geometry, scaled and letterboxed to the viewport — instead of rewrapping the buffer at its own width; typing (or the drawer's Fit button) takes the size back. Scrolling doesn't count: wheel/mouse reports never transfer ownership, so reading a session on the phone no longer steals the size from a desk. Resize sends are debounced (150ms) and the stale pre-switch resize on reconnect is gone, so a session switch reshapes the PTY once, not twice.
26
27
  - **Restyle to the hop identity**: the web client now shares the CLI bars' palette and language — accent session chip, semantic state dot, and keycap-style find control in a real status-bar footer; mono-led chrome (brand, presence names, session labels); refined light/dark themes; dot-grid join page. The hop session picker got the same treatment, including dark-mode support.
27
28
  - **Drawer polish**: quick actions split into two clusters — utility icons (keyboard / share / find) then named actions (Fit / Manage) — and the drawer FAB now defaults to the top-right (clear of the status bar, mirroring the close button) instead of bottom-left. It stays draggable.
28
29
  - **Autofit by default + fit on every session load**: the terminal fits the viewport on connect and on each session switch, on every platform. Autofit resizes the shared PTY, so other viewers follow this client; switch to Manual in the drawer to opt out.
@@ -34,7 +35,7 @@
34
35
 
35
36
  #### Web terminal
36
37
  - **Claude screens render completely on attach without a scroll**: Hop now starts its authoritative screen grid when a session enters alternate-screen or mouse-reporting TUI mode, before startup rows can fall out of a bounded replay tail. Full-screen attaches use that serialized screen, and direct snapshot paints re-arm one delayed repaint in case the browser misses the first WebGL frame.
37
- - **Resizing another desktop view no longer leaves a terminal unable to reach the live bottom**: Hop now reconciles xterm's follow state after every geometry change and keeps authoritative screen resizes ordered behind the output that preceded them.
38
+ - **Resizing another desktop view no longer leaves a terminal unable to reach the live bottom**: Wall/watch tiles now resize only unattended sessions instead of overriding an open desktop's Claude grid, Hop reconciles xterm's follow state after local geometry changes, and authoritative screen resizes stay ordered behind the output that preceded them.
38
39
 
39
40
  #### Session restore
40
41
  - **`hop restore` actually restores now (Claude conversations included), from the SessionStart-hook records**: restore built its candidate list from the workspace-scoped session store, which is only populated when a workspace is active — and no workspace is ever activated in normal use, so `restore` found nothing and silently restored zero sessions. It now sources candidates directly from the durable per-session records the SessionStart hook writes (`~/.hop2/claude-sessions/<name>.json` = `{ sessionId, cwd }`), which survive a crash/reboot and carry the exact conversation id. So after a restart, `hop restore` recreates each session in its directory and resumes its Claude conversation with `claude --resume <id>` — no manual capture step. Sessions already live are skipped (idempotent), and `hop restore` now starts the daemon itself if it isn't running, so post-reboot recovery is a single command. `--dry-run` previews the plan. Records are pruned when a session is deleted, so restore never resurrects a session you intentionally closed (and if an unwanted one does come back, deleting it once keeps it gone).
@@ -75,6 +75,7 @@ wss.on("connection", (ws, req) => {
75
75
  const url = new URL(req.url ?? "", `http://${req.headers.host ?? "localhost"}`);
76
76
  const roomId = sanitizeRoom(url.searchParams.get("room"));
77
77
  const name = sanitizeName(url.searchParams.get("name"));
78
+ const source = url.searchParams.get("source") || "";
78
79
  const cols = Number(url.searchParams.get("cols") ?? 80);
79
80
  const rows = Number(url.searchParams.get("rows") ?? 24);
80
81
 
@@ -91,6 +92,7 @@ wss.on("connection", (ws, req) => {
91
92
  {
92
93
  id: clientId,
93
94
  name,
95
+ source,
94
96
  colorIndex,
95
97
  cols,
96
98
  rows
@@ -119,6 +119,7 @@ export function attachTermshare(options: TermshareServerOptions) {
119
119
  const url = new URL(req.url ?? "", `http://${req.headers.host ?? "localhost"}`);
120
120
  const roomId = sanitizeRoom(url.searchParams.get("room"));
121
121
  const name = sanitizeName(url.searchParams.get("name"));
122
+ const source = url.searchParams.get("source") || "";
122
123
  const cols = Number(url.searchParams.get("cols") ?? 80);
123
124
  const rows = Number(url.searchParams.get("rows") ?? 24);
124
125
 
@@ -135,6 +136,7 @@ export function attachTermshare(options: TermshareServerOptions) {
135
136
  {
136
137
  id: clientId,
137
138
  name,
139
+ source,
138
140
  colorIndex,
139
141
  cols,
140
142
  rows
@@ -24,6 +24,11 @@ export type ClientInfo = {
24
24
  // switcher wall): excluded from presence and client counts, and given a
25
25
  // small snapshot so a wall of tiles doesn't pull megabytes per open.
26
26
  source?: string;
27
+ // Stable per-browser-tab identity (device id + tab id). A tab holds one
28
+ // live connection per room, so a new attach bearing the same key means the
29
+ // previous connection is dead even if its socket never closed — it is
30
+ // evicted on the spot instead of haunting presence until TCP notices.
31
+ deviceKey?: string;
27
32
  colorIndex: number;
28
33
  cols: number;
29
34
  rows: number;
@@ -117,25 +122,20 @@ const SERIALIZED_MAX_REQUEST = 524_288;
117
122
  // snapshot never trips).
118
123
  const SERIALIZED_CAPPED_HINT_BYTES = 262_144;
119
124
 
120
- // Autofit-on-attach: a resize may claim the shared size when every OTHER
121
- // client has been input-idle at least this long. Someone actively typing keeps
122
- // the size they set; a viewer opening the session after everyone went idle
123
- // takes it over immediately instead of waiting to type first.
124
- const RESIZE_CLAIM_IDLE_MS = (() => {
125
- const env = Number(process.env.HAY_RESIZE_CLAIM_IDLE_MS);
126
- return Number.isFinite(env) && env >= 0 ? env : 60_000;
127
- })();
128
- // A claim:"attach" resize (a fresh client's first autofit) is deliberate:
129
- // someone just opened the session there. It takes the shared size unless a
130
- // peer typed within this window — only an actively-typing peer holds it.
131
- // 2.5s (was 5s): an actively typing peer keeps refreshing its own window, so
132
- // this only decides how long a PAUSED typist blocks a deliberate new attach —
133
- // measured 5s made wall-tile focus feel stuck (converged at ~5s through the
134
- // tunnel; ~3s with this).
135
- const ATTACH_CLAIM_IDLE_MS = (() => {
136
- const env = Number(process.env.HAY_ATTACH_CLAIM_IDLE_MS);
137
- return Number.isFinite(env) && env >= 0 ? env : 2_500;
138
- })();
125
+ // Size ownership: the last USER ACTION owns the PTY size — opening the
126
+ // session (a claim:"attach" or user:true resize) or a real keystroke,
127
+ // whichever happened last. No idle windows, no election. The owner's
128
+ // resizes apply unconditionally (their viewport IS the session's size);
129
+ // everyone else's are recorded as that client's declared fit and answered
130
+ // with a corrective active_size so followers can adopt the owner's grid.
131
+ // When a keystroke transfers ownership, the PTY immediately takes the new
132
+ // owner's declared fit. Monitors (source=monitor: wall tiles, preview
133
+ // sockets) never own the size; they may size an UNATTENDED session so
134
+ // previews render true. Wheel/mouse reports are reading, not typing, and
135
+ // transfer nothing. SGR mouse reports only — every hop client sends wheel
136
+ // as CSI < b;x;y M/m. Anchored and exclusive: a payload containing
137
+ // anything besides mouse reports still counts as typing.
138
+ const PURE_MOUSE_REPORT = /^(?:\x1b\[<\d+;\d+;\d+[Mm])+$/;
139
139
  const CONTROL_SEQUENCE_TAIL = 32;
140
140
  const DEBUG_STATE = process.env.HAY_DEBUG === "1";
141
141
 
@@ -185,12 +185,12 @@ class ClientState {
185
185
  color: string;
186
186
  typing = false;
187
187
  lastActive = now();
188
- // Timestamp of this client's last real keystroke input (not resize, not the
189
- // typing indicator, not connect). 0 = has never typed. Drives the active PTY
190
- // size election so size follows the active typer, not whoever last resized.
191
- lastInputAt = 0;
192
188
  socket: SocketAdapter;
193
189
  source: string;
190
+ deviceKey: string;
191
+ // Declared fit: the size this client's viewport wants, updated by every
192
+ // resize message whether or not it applied. Becomes the PTY size the
193
+ // moment a keystroke makes this client the size owner.
194
194
  cols: number;
195
195
  rows: number;
196
196
 
@@ -198,6 +198,7 @@ class ClientState {
198
198
  this.id = info.id;
199
199
  this.name = info.name;
200
200
  this.source = info.source || "";
201
+ this.deviceKey = info.deviceKey || "";
201
202
  this.color = pickPresenceColor(info.colorIndex);
202
203
  this.socket = socket;
203
204
  this.cols = info.cols;
@@ -224,7 +225,9 @@ export class Room extends EventEmitter {
224
225
  private clients = new Map<string, ClientState>();
225
226
  private collabMode = true;
226
227
  private controllerId: string | null = null;
227
- private activeClientId: string | null = null;
228
+ // The client whose last user action (open or keystroke) owns the PTY size.
229
+ // null = up for grabs (fresh room, or the owner detached).
230
+ private sizeOwnerId: string | null = null;
228
231
  private activeCols: number;
229
232
  private activeRows: number;
230
233
  // Retained raw output as a chunk ring: append is O(1) and trimming drops
@@ -365,6 +368,19 @@ export class Room extends EventEmitter {
365
368
  this.cleanupTimer = null;
366
369
  }
367
370
 
371
+ // Same tab, same room: the newcomer replaces its predecessor. A phone
372
+ // that dropped off the network never sends a close, so its old
373
+ // connection would otherwise sit in presence as a second "iPhone"
374
+ // until TCP gives up on the corpse.
375
+ if (info.deviceKey) {
376
+ for (const [id, peer] of [...this.clients]) {
377
+ if (peer.deviceKey === info.deviceKey && peer.source !== "monitor") {
378
+ try { peer.socket.close(); } catch { /* already dead */ }
379
+ this.removeClient(id);
380
+ }
381
+ }
382
+ }
383
+
368
384
  const client = new ClientState(info, socket);
369
385
  this.clients.set(client.id, client);
370
386
  const created = !this.hasHadClient;
@@ -385,7 +401,7 @@ export class Room extends EventEmitter {
385
401
  socket.send(
386
402
  JSON.stringify({
387
403
  type: "active_size",
388
- clientId: this.activeClientId ?? client.id,
404
+ clientId: this.sizeOwnerId ?? client.id,
389
405
  cols: this.activeCols,
390
406
  rows: this.activeRows
391
407
  } satisfies ServerMessage)
@@ -880,7 +896,21 @@ export class Room extends EventEmitter {
880
896
  return;
881
897
  }
882
898
  client.lastActive = now();
883
- client.lastInputAt = now();
899
+ // A real keystroke takes the size: transfer ownership and bring the PTY
900
+ // to the new owner's declared fit immediately, so typing from a phone
901
+ // reshapes the session even before its next resize message arrives.
902
+ // Wheel/mouse reports are reading, not typing — a phone scrolling claude
903
+ // must not take the size from someone typing at a desk.
904
+ if (
905
+ client.source !== "monitor" &&
906
+ this.sizeOwnerId !== client.id &&
907
+ !PURE_MOUSE_REPORT.test(data)
908
+ ) {
909
+ this.sizeOwnerId = client.id;
910
+ if (client.cols !== this.activeCols || client.rows !== this.activeRows) {
911
+ this.applySize(client, client.cols, client.rows);
912
+ }
913
+ }
884
914
  this.pty.write(data);
885
915
  this.emit("pty_input", { roomId: this.id, clientId: client.id, data, timestamp: now() });
886
916
  }
@@ -889,60 +919,76 @@ export class Room extends EventEmitter {
889
919
  if (!Number.isFinite(cols) || !Number.isFinite(rows)) return;
890
920
  if (cols < 1 || cols > 500 || rows < 1 || rows > 200) return;
891
921
 
922
+ // Always record the declared fit, applied or not — a later keystroke
923
+ // makes it the PTY size (see handleInput).
892
924
  client.cols = cols;
893
925
  client.rows = rows;
894
- // The active PTY size follows whoever is actively typing — not whoever last
895
- // resized. Previously a resize bumped lastActive and then checked "am I the
896
- // most active?", which was trivially true for the resizer, so every resize
897
- // won: a passive viewer resizing their window yanked the size from the
898
- // active typer, and two differently-sized clients flapped. Elect on typing
899
- // recency (lastInputAt) instead. A client that has never typed (lastInputAt
900
- // 0) only wins when no one else has typed either — so the first/sole client
901
- // can still size the PTY before typing.
902
- const maxInputAt = Math.max(...[...this.clients.values()].map((c) => c.lastInputAt));
903
- const othersMaxInputAt = Math.max(
904
- 0,
905
- ...[...this.clients.values()].filter((c) => c.id !== client.id).map((c) => c.lastInputAt)
906
- );
907
- const claimIdleMs = claim === "attach" ? ATTACH_CLAIM_IDLE_MS : RESIZE_CLAIM_IDLE_MS;
908
- // A user-flagged claim is a deliberate human act (clicking a wall tile,
909
- // switching to the session): it wins outright. Anyone actively typing
910
- // elsewhere reclaims with their next keystroke, so misfires self-heal.
911
- const isActive = userClaim ||
912
- client.lastInputAt >= maxInputAt || now() - othersMaxInputAt > claimIdleMs;
913
- if (isActive) {
914
- this.pty.resize(cols, rows);
915
- this.activeCols = cols;
916
- this.activeRows = rows;
917
- this.grid?.resize(cols, rows);
918
- this.activeClientId = client.id;
919
- // Broadcast the new active size to other clients so they can adjust —
920
- // and CONFIRM to the winner: a claimant otherwise learns nothing on
921
- // success and can only distinguish accept from reject by timeout.
922
- this.broadcastActiveSize(client);
923
- client.socket.send(
924
- JSON.stringify({
925
- type: "active_size",
926
- clientId: client.id,
927
- cols,
928
- rows
929
- } satisfies ServerMessage)
930
- );
931
- this.emit("pty_resize", { roomId: this.id, clientId: client.id, cols, rows, timestamp: now() });
932
- } else if (cols !== this.activeCols || rows !== this.activeRows) {
933
- // The resize lost the election (a passive viewer auto-fitted itself).
934
- // Snap that client back to the shared size — otherwise its local
935
- // terminal re-wraps the buffer at a size the PTY isn't, and it has no
936
- // way to learn the real size until the next winning resize.
937
- client.socket.send(
938
- JSON.stringify({
939
- type: "active_size",
940
- clientId: this.activeClientId ?? client.id,
941
- cols: this.activeCols,
942
- rows: this.activeRows
943
- } satisfies ServerMessage)
926
+
927
+ // A wall/watch tile may size an unattended session so previews render
928
+ // true, but must never clip a live client by forcing Claude's alternate
929
+ // screen to the tile's grid — and never takes ownership.
930
+ if (client.source === "monitor") {
931
+ const hasInteractivePeer = [...this.clients.values()].some(
932
+ (peer) => peer.id !== client.id && peer.source !== "monitor"
944
933
  );
934
+ if (!hasInteractivePeer) {
935
+ this.applySize(client, cols, rows);
936
+ } else if (cols !== this.activeCols || rows !== this.activeRows) {
937
+ this.sendActiveSize(client, this.sizeOwnerId ?? client.id);
938
+ }
939
+ return;
940
+ }
941
+
942
+ // Opening the session here (claim:"attach") or a deliberate click
943
+ // (user:true) is a user action: strict recency, it takes ownership
944
+ // outright. Whoever was typing elsewhere takes it back with their next
945
+ // keystroke, so misfires self-heal.
946
+ if (claim === "attach" || userClaim) {
947
+ this.sizeOwnerId = client.id;
948
+ this.applySize(client, cols, rows);
949
+ return;
950
+ }
951
+
952
+ // The owner's viewport IS the session's size: its refits (rotation,
953
+ // keyboard show/hide, window drag) flow straight through. While nobody
954
+ // owns the size (fresh room, owner detached), any interactive client
955
+ // may size it without claiming it.
956
+ if (this.sizeOwnerId === client.id || this.sizeOwnerId === null) {
957
+ this.applySize(client, cols, rows);
958
+ return;
945
959
  }
960
+
961
+ // Not the owner: the declaration is recorded; snap the client back to
962
+ // the shared size — otherwise its local terminal re-wraps the buffer at
963
+ // a size the PTY isn't, and it has no way to learn the real size until
964
+ // the next broadcast.
965
+ if (cols !== this.activeCols || rows !== this.activeRows) {
966
+ this.sendActiveSize(client, this.sizeOwnerId);
967
+ }
968
+ }
969
+
970
+ private applySize(client: ClientState, cols: number, rows: number) {
971
+ this.pty.resize(cols, rows);
972
+ this.activeCols = cols;
973
+ this.activeRows = rows;
974
+ this.grid?.resize(cols, rows);
975
+ // Broadcast to the others so they can adopt — and CONFIRM to the
976
+ // applier: a claimant otherwise learns nothing on success and can only
977
+ // distinguish accept from reject by timeout.
978
+ this.broadcastActiveSize(client);
979
+ this.sendActiveSize(client, client.id);
980
+ this.emit("pty_resize", { roomId: this.id, clientId: client.id, cols, rows, timestamp: now() });
981
+ }
982
+
983
+ private sendActiveSize(client: ClientState, ownerId: string) {
984
+ client.socket.send(
985
+ JSON.stringify({
986
+ type: "active_size",
987
+ clientId: ownerId,
988
+ cols: this.activeCols,
989
+ rows: this.activeRows
990
+ } satisfies ServerMessage)
991
+ );
946
992
  }
947
993
 
948
994
  private broadcastActiveSize(client: ClientState) {
@@ -995,6 +1041,11 @@ export class Room extends EventEmitter {
995
1041
  private removeClient(clientId: string) {
996
1042
  const wasController = this.controllerId === clientId;
997
1043
  this.clients.delete(clientId);
1044
+ if (this.sizeOwnerId === clientId) {
1045
+ // The owner left: the size is up for grabs, so a remaining client's
1046
+ // next refit (not just its next keystroke) may take it.
1047
+ this.sizeOwnerId = null;
1048
+ }
998
1049
  if (wasController && !this.collabMode) {
999
1050
  this.collabMode = true;
1000
1051
  this.controllerId = null;
@@ -39,6 +39,9 @@ export const GRID_SCROLLBACK = (() => {
39
39
  const env = Number(process.env.HAY_GRID_SCROLLBACK);
40
40
  return Number.isFinite(env) && env >= 0 ? Math.floor(env) : 1000;
41
41
  })();
42
+ // Preserve ordinary shrink/grow sequences exactly while bounding an abusive
43
+ // resize storm's retained work behind a single xterm write marker.
44
+ const MAX_QUEUED_RESIZE_TRANSITIONS = 256;
42
45
 
43
46
  let deps: GridDeps | null = null;
44
47
  let loading: Promise<boolean> | null = null;
@@ -110,27 +113,52 @@ export const createScreenGrid = (cols: number, rows: number): ScreenGrid | null
110
113
  return null;
111
114
  }
112
115
  let disposed = false;
116
+ let coalescibleResizes: number[] | null = null;
113
117
  return {
114
118
  write(data: string) {
115
119
  if (disposed) return;
120
+ // Output is an ordering boundary: a later resize must run after it,
121
+ // rather than coalescing into a resize marker queued before it.
122
+ if (data) coalescibleResizes = null;
116
123
  try { term.write(data); } catch { /* parser hiccup — next write continues */ }
117
124
  },
118
125
  resize(nextCols: number, nextRows: number) {
119
126
  if (disposed) return;
120
127
  const cols = Math.max(2, nextCols);
121
128
  const rows = Math.max(1, nextRows);
129
+ if (coalescibleResizes) {
130
+ if (coalescibleResizes.length < MAX_QUEUED_RESIZE_TRANSITIONS * 2) {
131
+ coalescibleResizes.push(cols, rows);
132
+ } else {
133
+ coalescibleResizes[coalescibleResizes.length - 2] = cols;
134
+ coalescibleResizes[coalescibleResizes.length - 1] = rows;
135
+ }
136
+ return;
137
+ }
138
+ const scheduled = [cols, rows];
139
+ coalescibleResizes = scheduled;
122
140
  try {
123
141
  // xterm parses write() asynchronously. Queue the resize behind every
124
142
  // earlier byte so room order stays PTY output → SIGWINCH, while later
125
143
  // writes naturally queue behind this callback's synchronous resize.
144
+ // Consecutive resizes share this marker. Replay ordinary geometry
145
+ // changes exactly: shrink/grow transitions mutate xterm's grid even
146
+ // without output. Only an abusive overflow degrades to the latest size.
126
147
  term.write("", () => {
127
148
  if (disposed) return;
128
- try { term.resize(cols, rows); } catch { /* keep old size */ }
149
+ if (coalescibleResizes === scheduled) coalescibleResizes = null;
150
+ for (let i = 0; i < scheduled.length; i += 2) {
151
+ try { term.resize(scheduled[i], scheduled[i + 1]); } catch { /* keep previous size */ }
152
+ }
129
153
  });
130
- } catch { /* keep old size */ }
154
+ } catch {
155
+ if (coalescibleResizes === scheduled) coalescibleResizes = null;
156
+ }
131
157
  },
132
158
  serialize(callback: (data: string | null) => void, scrollback: number = GRID_SCROLLBACK) {
133
159
  if (disposed) { callback(null); return; }
160
+ // A later resize must not move ahead of this point-in-time snapshot.
161
+ coalescibleResizes = null;
134
162
  try {
135
163
  // An empty write's callback fires once all queued data has parsed —
136
164
  // the serialize then reflects every byte up to this attach.