@gjermundgaraba/clankermux 0.5.0 → 0.7.0

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.
Files changed (40) hide show
  1. package/README.md +1 -1
  2. package/dist/client/attachment.d.ts +9 -29
  3. package/dist/client/attachment.js +28 -41
  4. package/dist/client/client.d.ts +0 -2
  5. package/dist/client/client.js +6 -11
  6. package/dist/client/connection.d.ts +1 -19
  7. package/dist/client/connection.js +0 -17
  8. package/dist/client/copy.d.ts +0 -14
  9. package/dist/client/copy.js +4 -25
  10. package/dist/client/keyboard.d.ts +1 -27
  11. package/dist/client/keyboard.js +18 -34
  12. package/dist/client/link.d.ts +143 -0
  13. package/dist/client/link.js +205 -0
  14. package/dist/client/listeners.d.ts +3 -1
  15. package/dist/client/listeners.js +20 -4
  16. package/dist/client/mount.d.ts +0 -5
  17. package/dist/client/mount.js +20 -72
  18. package/dist/client/osc52.d.ts +1 -4
  19. package/dist/client/osc52.js +20 -17
  20. package/dist/client/profile.d.ts +0 -6
  21. package/dist/client/profile.js +0 -6
  22. package/dist/client/worker.d.ts +3 -44
  23. package/dist/client/worker.js +185 -332
  24. package/dist/engine/decoder.d.ts +0 -20
  25. package/dist/engine/decoder.js +8 -27
  26. package/dist/engine/index.d.ts +2 -49
  27. package/dist/engine/index.js +7 -48
  28. package/dist/engine/keys.d.ts +0 -7
  29. package/dist/engine/keys.js +9 -15
  30. package/dist/engine/render.d.ts +7 -18
  31. package/dist/engine/render.js +32 -32
  32. package/dist/engine/selection.d.ts +0 -17
  33. package/dist/engine/selection.js +8 -30
  34. package/dist/proto/frame.d.ts +2 -23
  35. package/dist/proto/frame.js +1 -21
  36. package/dist/proto/messages.d.ts +49 -9
  37. package/dist/proto/messages.js +42 -1
  38. package/dist/renderer/index.d.ts +3 -4
  39. package/dist/renderer/index.js +38 -42
  40. package/package.json +5 -6
@@ -1,32 +1,21 @@
1
- /**
2
- * The engine side of a client: the connection, the attachments and their
3
- * render state live in a worker; the page draws frames and reports input.
4
- * One worker serves one `Client` and every terminal mounted from it.
5
- * Imported as `@gjermundgaraba/clankermux/worker`, so a worker typechecked
6
- * without the DOM library does not see the page's types.
7
- */
8
1
  import { ENGINE, Engine, KeyEncoder, RenderState, SelectionGesture, } from "../engine/index.js";
9
2
  import { FrameType, } from "../proto/index.js";
10
3
  import { Attachment } from "./attachment.js";
11
4
  import { ClientError, Connection, hello } from "./connection.js";
5
+ import { endedWith, lineOf, linkOf, mountMachine, } from "./link.js";
12
6
  import { Osc52Scanner } from "./osc52.js";
13
- /** The keys that, with Shift, scroll the history: by pages, or to its
14
- * top or bottom. */
15
7
  const SCROLL_KEYS = {
16
8
  PageUp: -1,
17
9
  PageDown: 1,
18
10
  Home: "top",
19
11
  End: "bottom",
20
12
  };
21
- /** Coalescing window for paints. */
22
- const PAINT_MS = 16;
13
+ const PAINT_COALESCE_MS = 16;
23
14
  const BACKOFF_MIN_MS = 250;
24
15
  const BACKOFF_MAX_MS = 5000;
25
- /** Ending errors of an OPEN that a new OPEN would only get again. */
26
- const PERMANENT = new Set(["no_such_session", "engine_mismatch", "invalid_request"]);
27
- /** The records `ack` marks seen. */
28
- const ACKED = new Set(["done", "error"]);
29
- /** Delays before trying again, doubling up to the maximum. */
16
+ const ACKABLE_ATTENTION_STATES = new Set(["done", "error"]);
17
+ const ALTERNATE_SCROLL_MODE = 1007;
18
+ const SEND_REQUEST_OVERHEAD_BYTES = 1024;
30
19
  class Backoff {
31
20
  ms = BACKOFF_MIN_MS;
32
21
  next() {
@@ -38,7 +27,6 @@ class Backoff {
38
27
  this.ms = BACKOFF_MIN_MS;
39
28
  }
40
29
  }
41
- /** A WebSocket as the client's message transport. */
42
30
  class SocketTransport {
43
31
  socket;
44
32
  onMessage;
@@ -64,22 +52,30 @@ class SocketTransport {
64
52
  this.socket.close();
65
53
  }
66
54
  }
55
+ function refusedByServer(err) {
56
+ return err instanceof ClientError && (err.kind === "server" || err.kind === "protocol");
57
+ }
58
+ function endedTheConnection(err) {
59
+ return err instanceof ClientError && err.server?.id === undefined;
60
+ }
61
+ function pasteChunkSize(limits) {
62
+ const bytesFittingAsBase64 = Math.floor((limits.control_body - SEND_REQUEST_OVERHEAD_BYTES) / 4) * 3;
63
+ return Math.max(1, Math.min(bytesFittingAsBase64, limits.input_queue));
64
+ }
65
+ class InputQueue {
66
+ tail = Promise.resolve();
67
+ stopWaitingOnSendsUnderWay() {
68
+ this.tail = Promise.resolve();
69
+ }
70
+ enqueueUnlessDetached(attached, send) {
71
+ this.tail = this.tail.then(() => (attached() ? send() : undefined));
72
+ }
73
+ }
67
74
  function failureOf(err) {
68
75
  return err instanceof ClientError
69
76
  ? { kind: err.kind, message: err.message, ...(err.server && { server: err.server }) }
70
77
  : { kind: "protocol", message: err instanceof Error ? err.message : String(err) };
71
78
  }
72
- /** The link ended with `error`: the server's, else the client's own. */
73
- function endedWith(err, retry) {
74
- const server = err instanceof ClientError ? err.server : undefined;
75
- return server
76
- ? { state: "ended", reason: linkEnd(server.code), code: server.code, message: server.message, retry }
77
- : { state: "ended", reason: "error", message: err instanceof Error ? err.message : String(err), retry };
78
- }
79
- /**
80
- * The client: one connection, reconnected after a loss, its session list
81
- * and event stream, the page's requests, and the mounted terminals.
82
- */
83
79
  class Hub {
84
80
  post;
85
81
  constructor(post) {
@@ -90,24 +86,15 @@ class Hub {
90
86
  url = "";
91
87
  client = "clankermux-web";
92
88
  conn;
93
- /** The connection-level link, as a terminal mounted now first sees it:
94
- * `connecting`, `connected` (to no session), or `ended` for good, with
95
- * the server's refusal or error, when an `attach` connects again. */
96
- state = { state: "connecting", attempt: 1 };
97
- /** The latest connection-level status text, for a terminal mounted later. */
89
+ connectionLink = { state: "connecting", attempt: 1 };
98
90
  statusText = "connecting";
99
- /** Connection attempts since a server last answered. */
100
91
  attempt = 0;
101
92
  backoff = new Backoff();
102
- /** Frame channels, shared by the terminals of the one connection. */
103
93
  channel = 0;
104
94
  mounts = new Map();
105
95
  sessions = new Map();
106
- /** The list is being paged: not shown to the page until it is whole. */
107
96
  paging = false;
108
- /** Where the event stream is, to replay from after a reconnect. */
109
- events;
110
- /** The page's pending requests: their connection and its request id. */
97
+ eventCursor;
111
98
  requests = new Map();
112
99
  async init(message) {
113
100
  this.url = message.url;
@@ -125,10 +112,8 @@ class Hub {
125
112
  this.post({ type: "ready" });
126
113
  await this.connect();
127
114
  }
128
- /** A connection-level change, to the page and every terminal. A
129
- * retrying end leaves the connection `connecting` meanwhile. */
130
115
  linkAll(link) {
131
- this.state = link.state === "ended" && link.retry ? { state: "connecting", attempt: this.attempt + 1 } : link;
116
+ this.connectionLink = link.state === "ended" && link.retry ? { state: "connecting", attempt: this.attempt + 1 } : link;
132
117
  this.post({ type: "connection", link });
133
118
  for (const mount of this.mounts.values())
134
119
  mount.link(link);
@@ -138,25 +123,22 @@ class Hub {
138
123
  for (const mount of this.mounts.values())
139
124
  mount.status(text);
140
125
  }
141
- /** The connection is up and subscribed: terminals may open channels. */
142
126
  live() {
143
- return this.state.state === "connected" ? this.conn : undefined;
127
+ return this.connectionLink.state === "connected" ? this.conn : undefined;
144
128
  }
145
- /** The connection ended for good with `err`. */
146
129
  refuse(err) {
147
130
  this.statusAll(err instanceof Error ? err.message : String(err));
148
131
  this.linkAll(endedWith(err, false));
149
132
  }
150
133
  async connect() {
151
- this.statusAll(this.events ? "reconnecting" : "connecting");
134
+ this.statusAll(this.eventCursor ? "reconnecting" : "connecting");
152
135
  this.linkAll({ state: "connecting", attempt: ++this.attempt });
153
136
  let conn;
154
137
  try {
155
138
  conn = await Connection.connect(await SocketTransport.connect(this.url), hello(this.client, ENGINE));
156
139
  }
157
140
  catch (err) {
158
- // A server that answers and refuses is not retried; a lost one is.
159
- if (err instanceof ClientError && (err.kind === "server" || err.kind === "protocol")) {
141
+ if (refusedByServer(err)) {
160
142
  this.refuse(err);
161
143
  return;
162
144
  }
@@ -170,6 +152,8 @@ class Hub {
170
152
  if (this.conn !== conn)
171
153
  return;
172
154
  this.conn = undefined;
155
+ for (const mount of this.mounts.values())
156
+ mount.disconnected();
173
157
  if (err.kind === "server") {
174
158
  this.refuse(err);
175
159
  }
@@ -183,34 +167,29 @@ class Hub {
183
167
  await this.subscribe(conn);
184
168
  }
185
169
  catch (err) {
186
- // A lost connection is reported through onEnd, which ran first; a
187
- // refused subscription ends this one for good.
188
- if (this.conn === conn) {
189
- this.conn = undefined;
190
- conn.close();
191
- this.refuse(err);
192
- }
170
+ if (endedTheConnection(err))
171
+ return;
172
+ this.conn = undefined;
173
+ conn.close();
174
+ this.refuse(err);
193
175
  return;
194
176
  }
195
- this.state = { state: "connected", session: undefined };
177
+ this.connectionLink = { state: "connected", session: undefined };
196
178
  this.statusText = "connected";
197
- this.post({ type: "connection", link: this.state });
179
+ this.post({ type: "connection", link: this.connectionLink });
198
180
  for (const mount of this.mounts.values())
199
- mount.connected();
181
+ mount.connected(conn);
200
182
  }
201
- /** Subscribes: from the first page on the first connection; after a
202
- * reconnect from the last event seen, replaying those missed, or, when
203
- * the server cannot (a gap), from the first page again. */
204
183
  async subscribe(conn) {
205
184
  const incarnation = conn.welcome.incarnation;
206
- if (this.events) {
185
+ if (this.eventCursor) {
207
186
  const replay = await conn.call("subscribe", {
208
- after: this.events.seq,
209
- incarnation: this.events.incarnation,
187
+ after: this.eventCursor.seq,
188
+ incarnation: this.eventCursor.incarnation,
210
189
  });
211
190
  if (!replay.gap)
212
191
  return;
213
- this.events = { incarnation, seq: replay.latest };
192
+ this.eventCursor = { incarnation, seq: replay.latest };
214
193
  await this.page(conn, await conn.call("list", {}));
215
194
  this.post({ type: "gap", incarnation });
216
195
  for (const mount of this.mounts.values())
@@ -218,12 +197,9 @@ class Hub {
218
197
  return;
219
198
  }
220
199
  const first = await conn.call("subscribe", {});
221
- this.events = { incarnation, seq: first.latest };
200
+ this.eventCursor = { incarnation, seq: first.latest };
222
201
  await this.page(conn, { sessions: first.sessions ?? [], ...(first.next !== undefined && { next: first.next }) });
223
202
  }
224
- /** The session list from `page` on. Events arriving between pages are
225
- * applied to the same map: a later page cannot hold a session removed
226
- * before it was produced. The page sees the list once it is whole. */
227
203
  async page(conn, page) {
228
204
  this.sessions.clear();
229
205
  this.paging = true;
@@ -242,8 +218,8 @@ class Hub {
242
218
  this.postSessions();
243
219
  }
244
220
  event(event) {
245
- if (this.events)
246
- this.events.seq = event.seq;
221
+ if (this.eventCursor)
222
+ this.eventCursor.seq = event.seq;
247
223
  switch (event.event) {
248
224
  case "session_created":
249
225
  case "session_changed":
@@ -270,7 +246,6 @@ class Hub {
270
246
  nextChannel() {
271
247
  return ++this.channel;
272
248
  }
273
- /** A protocol request from the page; its outcome goes back by `id`. */
274
249
  async request(id, method, params) {
275
250
  const conn = this.conn;
276
251
  if (!conn) {
@@ -289,93 +264,61 @@ class Hub {
289
264
  this.requests.delete(id);
290
265
  }
291
266
  }
292
- /** Cancels the page's request `id`, when it is still pending. Its own
293
- * reply is the server's `cancelled`. */
294
267
  cancel(id) {
295
268
  const pending = this.requests.get(id);
296
269
  if (!pending || pending.conn !== this.conn)
297
270
  return;
298
271
  pending.conn.call("cancel", { id: pending.wire }).catch(() => { });
299
272
  }
300
- /** A terminal mounted after the connection ended for good connects
301
- * again, as an `attach` does; otherwise it first sees the connection as
302
- * it is now, as a terminal mounted at the start would have. */
303
273
  mount(id, init) {
304
274
  const mount = new Mount(this, id, init);
305
275
  this.mounts.set(id, mount);
306
276
  mount.status(this.statusText);
307
- if (this.state.state === "ended")
308
- this.reattach(mount);
309
- else if (this.live())
310
- mount.connected();
311
- else
312
- mount.link(this.state);
277
+ const conn = this.live();
278
+ if (conn)
279
+ mount.connected(conn);
280
+ else if (this.connectionLink.state !== "ended")
281
+ mount.link(this.connectionLink);
282
+ this.reconnectIfEnded();
313
283
  }
314
284
  unmount(id) {
315
285
  this.mounts.get(id)?.dispose();
316
286
  this.mounts.delete(id);
317
287
  }
318
- /** After the server refused or ended the connection, connects again;
319
- * otherwise opens `mount`'s session, or leaves it to the connection
320
- * coming up. */
321
- reattach(mount) {
322
- if (this.state.state === "ended") {
323
- this.attempt = 0;
324
- void this.connect();
325
- }
326
- else {
327
- mount.open();
328
- }
288
+ reconnectIfEnded() {
289
+ if (this.connectionLink.state !== "ended")
290
+ return;
291
+ this.attempt = 0;
292
+ void this.connect();
329
293
  }
330
294
  }
331
- /** One mounted terminal: an attachment on the hub's connection, its render
332
- * state, selection, input and size. */
333
295
  class Mount {
334
296
  hub;
335
297
  id;
336
- attachment;
337
- channel = 0;
338
- /** The connection the channel is open on. */
339
- openOn;
340
- /** An `ack` is under way. */
298
+ snapshot = mountMachine.initialState;
299
+ reopenTimer;
341
300
  acking = false;
342
- /** The session attached or being attached. */
343
- session;
344
301
  viewport;
345
302
  profile;
346
- /** The page is in use; only then are its size and profile reported. */
347
303
  active;
348
304
  visible;
349
305
  readOnly;
350
306
  ackOnFocus;
351
- /** The terminal has the keyboard and its window the focus. */
352
307
  focused = false;
353
- /** Another client resized the session while this page was in use: its
354
- * next input reports its size again. */
355
- reclaim = false;
308
+ sizeTakenByOtherClient = false;
356
309
  render;
357
310
  gesture;
358
- /** The page holds a selection's text. */
359
311
  selected = false;
360
- /** Input in order: a paste goes as `send` requests, and keys typed
361
- * meanwhile wait behind it. `attach` starts a fresh chain; input queued
362
- * for an attachment that is gone is dropped, but a paste under way
363
- * finishes (cut short, it would leave the program inside a bracketed
364
- * paste). */
365
- writes = Promise.resolve();
312
+ inputQueue = new InputQueue();
366
313
  clipboard = new Osc52Scanner();
367
314
  paintTimer;
368
315
  paintPending = false;
369
316
  frameInFlight = false;
370
317
  fullNext = false;
371
- /** Re-attaches after a failure; reset by a screen. */
372
318
  backoff = new Backoff();
373
- reopenTimer;
374
- disposed = false;
375
319
  constructor(hub, id, init) {
376
320
  this.hub = hub;
377
321
  this.id = id;
378
- this.session = init.session;
379
322
  this.viewport = init.viewport;
380
323
  this.profile = init.profile;
381
324
  this.active = init.active;
@@ -384,9 +327,17 @@ class Mount {
384
327
  this.ackOnFocus = init.ackOnFocus;
385
328
  this.render = new RenderState(hub.engine);
386
329
  this.gesture = new SelectionGesture(hub.engine);
330
+ if (init.session !== undefined)
331
+ this.step({ type: "page.attach", session: init.session, open: undefined });
332
+ }
333
+ get attachment() {
334
+ return this.snapshot.context.attachment;
335
+ }
336
+ get session() {
337
+ return this.snapshot.context.session;
387
338
  }
388
339
  post(message, options) {
389
- if (!this.disposed)
340
+ if (this.snapshot.value !== "disposed")
390
341
  this.hub.post(message, options);
391
342
  }
392
343
  link(link) {
@@ -395,36 +346,52 @@ class Mount {
395
346
  status(text) {
396
347
  this.post({ type: "status", mount: this.id, text });
397
348
  }
398
- /** The hub's connection is up: attach the session, if there is one. */
399
- connected() {
400
- if (this.session !== undefined) {
401
- this.open();
402
- }
403
- else {
404
- this.status("no session");
405
- this.link({ state: "connected", session: undefined });
406
- }
349
+ connected(conn) {
350
+ this.step({ type: "hub.live", open: this.offer(conn) });
351
+ }
352
+ disconnected() {
353
+ this.step({ type: "hub.down" });
407
354
  }
408
- /** Opens a channel for `this.session`, resuming when the attachment can. */
409
- open() {
355
+ offer(conn) {
356
+ return { conn, channel: this.hub.nextChannel(), fresh: new Attachment(this.hub.engine) };
357
+ }
358
+ offerIfLive() {
410
359
  const conn = this.hub.live();
411
- if (!conn || this.session === undefined || this.disposed || this.openOn === conn)
412
- return;
413
- if (!this.attachment)
414
- this.attachment = new Attachment(this.hub.engine);
415
- const attachment = this.attachment;
416
- attachment.openOn(conn.welcome);
417
- const channel = this.hub.nextChannel();
418
- this.channel = channel;
419
- this.openOn = conn;
420
- const resume = attachment.resume();
421
- // An OPEN with a viewport or profile is a report applied at once.
360
+ return conn && this.offer(conn);
361
+ }
362
+ step(event) {
363
+ const prev = this.snapshot;
364
+ const [next] = mountMachine.transition(prev, event);
365
+ if (next === prev)
366
+ return;
367
+ const { attachment } = prev.context;
368
+ if (attachment && attachment !== next.context.attachment)
369
+ this.close(attachment, lineOf(prev));
370
+ if (prev.value === "backoff")
371
+ clearTimeout(this.reopenTimer);
372
+ this.snapshot = next;
373
+ if (next.value === "opening")
374
+ this.open(next.context);
375
+ if (next.value === "backoff") {
376
+ this.reopenTimer = setTimeout(() => this.step({ type: "reopen.due", open: this.offerIfLive() }), this.backoff.next());
377
+ }
378
+ const link = linkOf(next);
379
+ if (!link)
380
+ return;
381
+ if (link.state === "connected" && link.session === undefined)
382
+ this.status("no session");
383
+ this.link(link);
384
+ }
385
+ open({ session, attachment, channel, conn }) {
386
+ const resume = attachment.open(conn.welcome);
422
387
  const open = {
423
- session: this.session,
388
+ session,
424
389
  ...(this.readOnly && { read_only: true }),
425
390
  ...(this.active && { viewport: this.viewport, profile: this.profile }),
426
391
  ...(resume && { resume }),
427
392
  };
393
+ if (this.active)
394
+ this.sizeTakenByOtherClient = false;
428
395
  conn.open(channel, open, (frame) => {
429
396
  if (this.attachment !== attachment)
430
397
  return;
@@ -433,51 +400,22 @@ class Mount {
433
400
  actions = attachment.handle(frame);
434
401
  }
435
402
  catch (err) {
436
- // A lost place in the stream: CLOSE and OPEN again, afresh. Any
437
- // other fault would only repeat.
438
403
  this.status(String(err));
439
- const desync = err instanceof ClientError && err.kind === "desync";
440
- this.link(endedWith(err, desync));
441
- if (desync)
442
- this.reopen();
443
- else
444
- this.giveUp();
404
+ this.step({ type: "attachment.threw", error: err });
445
405
  return;
446
406
  }
447
- if (frame.header.type === FrameType.Attached && actions.length === 0) {
448
- // Resumed: the terminal shows the stream already, and an exit
449
- // still to come arrives as EXITED. A snapshot's screen comes
450
- // later, as an action.
451
- if (attachment.resume()) {
452
- this.status("resumed");
453
- this.link({ state: "connected", session: attachment.session });
454
- }
455
- }
456
407
  for (const action of actions)
457
408
  this.apply(action);
458
409
  });
459
410
  }
460
- /** The screen of `session` is shown: `connected`, and at once `ended
461
- * exited` when its program has exited already. */
462
- attached(session) {
463
- this.link({ state: "connected", session });
464
- if (session?.status === "exited") {
465
- this.link({ state: "ended", reason: "exited", ...(session.exit && { exit: session.exit }), retry: false });
411
+ close(attachment, line) {
412
+ this.forgetSelection(attachment.term());
413
+ if (line) {
414
+ line.conn.release(line.channel);
415
+ if (!attachment.closed())
416
+ line.conn.send(FrameType.Close, line.channel, new Uint8Array());
466
417
  }
467
- }
468
- /** Detaches for good: a reconnect does not try the session again. */
469
- giveUp() {
470
- this.close();
471
- this.session = undefined;
472
- }
473
- /** Detaches and attaches the same session again after a backoff. */
474
- reopen() {
475
- this.close();
476
- this.reopenTimer ??= setTimeout(() => {
477
- this.reopenTimer = undefined;
478
- if (this.session !== undefined && !this.attachment)
479
- this.open();
480
- }, this.backoff.next());
418
+ attachment.free();
481
419
  }
482
420
  apply(action) {
483
421
  switch (action.type) {
@@ -494,38 +432,38 @@ class Mount {
494
432
  ? `exited: ${describe(session.exit)}`
495
433
  : "attached";
496
434
  this.status(text);
497
- this.attached(session);
435
+ this.step({ type: "frame.screen", session });
436
+ if (session?.status === "exited")
437
+ this.step({ type: "frame.exited", exit: session.exit });
498
438
  if (session)
499
439
  this.changed(session);
500
440
  break;
501
441
  }
442
+ case "resumed":
443
+ this.status("resumed");
444
+ this.step({ type: "frame.resumed", session: this.attachment?.session });
445
+ break;
502
446
  case "output":
503
- // Selection state must reach the page even while painting is paused.
504
447
  if (this.selected && !this.attachment?.term()?.selected)
505
448
  this.unselected();
506
449
  for (const write of this.clipboard.feed(action.bytes)) {
507
- // Only the clipboard selection; primary and secondary have no
508
- // browser equivalent.
509
- if (write.selection === "" || write.selection.includes("c")) {
450
+ if (write.toClipboard)
510
451
  this.post({ type: "clipboard", mount: this.id, text: write.text });
511
- }
512
452
  }
513
453
  this.paintPending = true;
514
454
  if (this.visible && !this.frameInFlight)
515
- this.paintTimer ??= setTimeout(() => this.paint(), PAINT_MS);
455
+ this.paintTimer ??= setTimeout(() => this.paint(), PAINT_COALESCE_MS);
516
456
  break;
517
457
  case "resized":
518
- // Another client's size, while this page kept its focus (the user
519
- // went to another machine): taken back at this page's next input.
520
458
  if (this.active && (action.cols !== this.viewport.cols || action.rows !== this.viewport.rows)) {
521
- this.reclaim = true;
459
+ this.sizeTakenByOtherClient = true;
522
460
  }
523
461
  this.paint();
524
462
  break;
525
463
  case "exited":
526
464
  this.paint();
527
465
  this.status(`exited: ${describe(action.exit)}`);
528
- this.link({ state: "ended", reason: "exited", exit: action.exit, retry: false });
466
+ this.step({ type: "frame.exited", exit: action.exit });
529
467
  break;
530
468
  case "gap":
531
469
  this.clipboard.reset();
@@ -534,38 +472,14 @@ class Mount {
534
472
  break;
535
473
  case "closed":
536
474
  this.status(`closed: ${action.reason}`);
537
- // `stopping` is followed by the connection's close, and the
538
- // reconnect attaches again; a removed session is gone for good,
539
- // and a detached page does not take its session back.
540
- this.link({
541
- state: "ended",
542
- reason: action.reason,
543
- ...(action.message !== undefined && { message: action.message }),
544
- retry: action.reason === "stopping",
545
- });
546
- if (action.reason === "removed" || action.reason === "detached")
547
- this.giveUp();
475
+ this.step({ type: "frame.closed", reason: action.reason, message: action.message });
548
476
  break;
549
- case "error": {
477
+ case "error":
550
478
  this.status(`${action.error.code}: ${action.error.message}`);
551
- // An error ended the attachment: attach again after a backoff
552
- // (`too_slow`, a snapshot that could not be taken), unless a new
553
- // OPEN would fail the same way.
554
- if (!this.attachment?.closed())
555
- break;
556
- const { code, message } = action.error;
557
- const retry = !PERMANENT.has(code);
558
- this.link({ state: "ended", reason: linkEnd(code), code, message, retry });
559
- if (retry)
560
- this.reopen();
561
- else
562
- this.giveUp();
479
+ this.step({ type: "frame.error", error: action.error, endsAttachment: this.attachment?.closed() === true });
563
480
  break;
564
- }
565
481
  }
566
482
  }
567
- /** The page's colours on the local terminal, as the server has them on
568
- * its own: the stream does not carry default colours. */
569
483
  applyProfile(term) {
570
484
  if (!term)
571
485
  return;
@@ -607,31 +521,24 @@ class Mount {
607
521
  }
608
522
  this.paintPending = true;
609
523
  const term = this.attachment?.term();
610
- if (!term || this.disposed || !this.visible || this.frameInFlight)
524
+ if (!term || !this.visible || this.frameInFlight)
611
525
  return;
612
526
  if (this.fullNext) {
613
527
  this.render.free();
614
528
  this.render = new RenderState(this.hub.engine);
615
529
  this.fullNext = false;
616
530
  }
617
- const frame = this.render.updatePacked(term);
618
- // Clean only the captured rows. While this frame is in flight, no
619
- // extraction runs, so subsequent changes accumulate in the engine.
620
- this.render.clean();
531
+ const frame = this.render.takePackedFrame(term);
621
532
  this.paintPending = false;
622
533
  this.frameInFlight = true;
623
534
  this.post({ type: "frame", mount: this.id, frame }, { transfer: frame.lines.map((row) => row.cells.data.buffer) });
624
- // A switch to the alternate screen or a full reset took the selection.
625
535
  if (this.selected && !term.selected)
626
536
  this.unselected();
627
537
  }
628
- /** The mouse: a press clears the selection, or selects a word or a line
629
- * at once; a drag selects; the release copies what is selected. */
630
538
  select(message) {
631
539
  const { at, time } = message;
632
540
  const term = this.attachment?.term();
633
541
  if (!term) {
634
- // Nothing to select: the page's copy waits for the answer even so.
635
542
  if (message.action === "release") {
636
543
  this.post({ type: "selection", mount: this.id, text: undefined, copy: message.copy });
637
544
  }
@@ -652,8 +559,6 @@ class Mount {
652
559
  }
653
560
  case "release": {
654
561
  this.gesture.release(term, at);
655
- // Answered either way: the page's copy waits for it. Blanks only
656
- // (trimmed to nothing) are no text to copy.
657
562
  const text = term.selectionText() || undefined;
658
563
  this.selected = text !== undefined;
659
564
  this.post({ type: "selection", mount: this.id, text, copy: message.copy });
@@ -662,7 +567,6 @@ class Mount {
662
567
  }
663
568
  this.paint();
664
569
  }
665
- /** Input clears the selection. */
666
570
  unselect() {
667
571
  const term = this.attachment?.term();
668
572
  if (!term?.selected)
@@ -676,95 +580,64 @@ class Mount {
676
580
  this.selected = false;
677
581
  this.post({ type: "selection", mount: this.id, text: undefined });
678
582
  }
679
- /** The terminal goes, and its selection and the gesture's anchor with it. */
680
583
  forgetSelection(term) {
681
584
  this.gesture.forget(term);
682
585
  if (this.selected)
683
586
  this.unselected();
684
587
  }
685
- /** Closes the current attachment's channel and forgets it. An
686
- * attachment the server ended needs no CLOSE; one whose stream ended
687
- * (EXITED) does. */
688
- close() {
689
- if (!this.attachment)
690
- return;
691
- // Still alive: the gesture's anchor is released in it.
692
- this.forgetSelection(this.attachment.term());
693
- const conn = this.hub.conn;
694
- if (conn) {
695
- conn.release(this.channel);
696
- if (!this.attachment.closed())
697
- conn.send(FrameType.Close, this.channel, new Uint8Array());
698
- }
699
- this.attachment.free();
700
- this.attachment = undefined;
701
- this.openOn = undefined;
702
- }
703
- /** Detaches the current session and attaches `session`; after the
704
- * server refused or ended the connection, connects again first. */
705
588
  attach(session) {
706
- this.close();
707
- this.writes = Promise.resolve();
708
- this.session = session;
709
- this.hub.reattach(this);
589
+ this.step({ type: "page.attach", session, open: this.offerIfLive() });
590
+ this.inputQueue.stopWaitingOnSendsUnderWay();
591
+ this.hub.reconnectIfEnded();
710
592
  }
711
- /** Detaches, and stays attached to none. */
712
593
  detach() {
713
- const had = this.session !== undefined;
714
- this.giveUp();
715
- this.writes = Promise.resolve();
716
- if (had && this.hub.conn) {
717
- this.status("no session");
718
- this.link({ state: "connected", session: undefined });
719
- }
594
+ this.step({ type: "page.detach", live: this.hub.live() !== undefined });
595
+ this.inputQueue.stopWaitingOnSendsUnderWay();
720
596
  }
721
597
  dispose() {
722
- this.close();
723
- this.disposed = true;
598
+ this.step({ type: "page.unmount" });
724
599
  if (this.paintTimer !== undefined)
725
600
  clearTimeout(this.paintTimer);
726
- if (this.reopenTimer !== undefined)
727
- clearTimeout(this.reopenTimer);
728
601
  this.render.free();
729
602
  this.gesture.forget(undefined);
730
603
  }
731
- /** Input for the session, dropped unless attached on a live connection,
732
- * and for a read-only terminal. Keys go as INPUT; a paste goes as
733
- * `send` requests, each answered once the PTY took it, since INPUT
734
- * frames are not acknowledged and a paste would overflow the input
735
- * queue. This terminal's input is sent in order, so none of it lands
736
- * inside a paste. */
737
- input(bytes, paste) {
738
- const conn = this.hub.conn;
739
- const attachment = this.attachment;
740
- const session = this.session;
741
- const channel = this.channel;
742
- if (bytes.length === 0 || this.readOnly || !conn || !attachment || attachment.ended() || session === undefined) {
604
+ sendInput(bytes) {
605
+ if (!this.typed(bytes))
743
606
  return;
744
- }
607
+ const line = lineOf(this.snapshot);
608
+ if (line)
609
+ this.deliver(line.conn, async () => line.conn.send(FrameType.Input, line.channel, bytes));
610
+ }
611
+ sendPaste(bytes) {
612
+ if (!this.typed(bytes))
613
+ return;
614
+ const { conn } = this.hub;
615
+ const { session } = this;
616
+ if (!conn || session === undefined)
617
+ return;
618
+ this.deliver(conn, async () => {
619
+ const chunk = pasteChunkSize(conn.welcome.limits);
620
+ for (let at = 0; at < bytes.length; at += chunk) {
621
+ await conn.call("send", { session, data: base64(bytes.subarray(at, at + chunk)) });
622
+ }
623
+ });
624
+ }
625
+ typed(bytes) {
626
+ const { attachment } = this;
627
+ if (bytes.length === 0 || this.readOnly || !attachment || attachment.ended())
628
+ return false;
745
629
  this.claim();
746
630
  this.backToLive();
747
631
  this.unselect();
748
- // Each request's base64 fits the control body with room for the rest,
749
- // and its bytes fit the input queue (at least one byte, so the loop
750
- // moves on an absurd limit).
751
- const { control_body, input_queue } = conn.welcome.limits;
752
- const chunk = Math.max(1, Math.min(Math.floor((control_body - 1024) / 4) * 3, input_queue));
753
- this.writes = this.writes.then(async () => {
754
- if (this.attachment !== attachment)
755
- return;
632
+ return true;
633
+ }
634
+ deliver(conn, send) {
635
+ const { attachment } = this;
636
+ this.inputQueue.enqueueUnlessDetached(() => this.attachment === attachment, async () => {
756
637
  try {
757
- if (!paste) {
758
- conn.send(FrameType.Input, channel, bytes);
759
- return;
760
- }
761
- for (let at = 0; at < bytes.length; at += chunk) {
762
- await conn.call("send", { session, data: base64(bytes.subarray(at, at + chunk)) });
763
- }
638
+ await send();
764
639
  }
765
640
  catch (err) {
766
- // A connection loss is reported through onEnd; a refused chunk
767
- // ends the paste there.
768
641
  if (conn === this.hub.conn)
769
642
  this.status(String(err));
770
643
  }
@@ -774,8 +647,6 @@ class Mount {
774
647
  const term = this.attachment?.term();
775
648
  if (!term)
776
649
  return;
777
- // Shift+PageUp, PageDown, Home and End scroll the history, press and
778
- // release; on the alternate screen, which has none, they are keys.
779
650
  const scroll = SCROLL_KEYS[input.code];
780
651
  if (scroll && input.shift && !input.ctrl && !input.alt && !input.meta && !term.alternate) {
781
652
  if (input.action === "release")
@@ -784,11 +655,8 @@ class Mount {
784
655
  this.paint();
785
656
  return;
786
657
  }
787
- this.input(this.hub.keys.encode(term, input), false);
658
+ this.sendInput(this.hub.keys.encode(term, input));
788
659
  }
789
- /** The wheel. On the alternate screen, with alternate scroll (mode
790
- * 1007, on by default), it is the arrow keys, as a full-screen program
791
- * such as `less` expects; without it, nothing. */
792
660
  wheel(rows) {
793
661
  const term = this.attachment?.term();
794
662
  if (!term || rows === 0)
@@ -799,17 +667,15 @@ class Mount {
799
667
  this.paint();
800
668
  return;
801
669
  }
802
- if (!term.mode(1007))
670
+ if (!term.mode(ALTERNATE_SCROLL_MODE))
803
671
  return;
804
672
  const code = rows < 0 ? "ArrowUp" : "ArrowDown";
805
673
  const arrow = this.hub.keys.encode(term, { code, key: code, action: "press", shift: false, ctrl: false, alt: false, meta: false });
806
674
  const bytes = new Uint8Array(arrow.length * Math.abs(rows));
807
675
  for (let i = 0; i < Math.abs(rows); i++)
808
676
  bytes.set(arrow, i * arrow.length);
809
- this.input(bytes, false);
677
+ this.sendInput(bytes);
810
678
  }
811
- /** The view through the history, as the page asks: by rows, or back to
812
- * the live screen. The alternate screen has no history. */
813
679
  view(rows) {
814
680
  const term = this.attachment?.term();
815
681
  if (!term || term.alternate)
@@ -821,7 +687,6 @@ class Mount {
821
687
  this.paint();
822
688
  }
823
689
  }
824
- /** Back to the live screen before input, as any terminal does. */
825
690
  backToLive() {
826
691
  const term = this.attachment?.term();
827
692
  if (!term)
@@ -832,28 +697,23 @@ class Mount {
832
697
  term.scroll("bottom");
833
698
  this.paint();
834
699
  }
835
- /** Text no key sent, as UTF-8: a composition's, the emoji picker's. */
836
700
  text(text) {
837
701
  if (!this.attachment?.term())
838
702
  return;
839
- this.input(new TextEncoder().encode(text), false);
703
+ this.sendInput(new TextEncoder().encode(text));
840
704
  }
841
705
  paste(text) {
842
706
  const term = this.attachment?.term();
843
707
  if (!term)
844
708
  return;
845
- this.input(this.hub.engine.encodePaste(text, term.mode(2004)), true);
709
+ this.sendPaste(this.hub.engine.encodePaste(text, term.mode(2004)));
846
710
  }
847
- /** Keeps the page's size and colours (for the local terminal), and
848
- * reports them to the session while the page is active. A report
849
- * repeats the last one when the page becomes active again, so the
850
- * session takes its size back from another client. */
851
711
  setViewport(size, profile, active) {
852
712
  this.viewport = size;
853
713
  this.profile = profile;
854
714
  this.active = active;
855
- const attachment = this.attachment;
856
- if (!this.hub.conn || !attachment || attachment.ended())
715
+ const { attachment } = this;
716
+ if (!attachment || attachment.ended())
857
717
  return;
858
718
  this.applyProfile(attachment.term());
859
719
  this.paint();
@@ -861,37 +721,34 @@ class Mount {
861
721
  this.report();
862
722
  }
863
723
  report() {
864
- this.reclaim = false;
865
- this.hub.conn?.sendJson(FrameType.Viewport, this.channel, { ...this.viewport, profile: this.profile });
724
+ const line = lineOf(this.snapshot);
725
+ if (!line)
726
+ return;
727
+ this.sizeTakenByOtherClient = false;
728
+ line.conn.sendJson(FrameType.Viewport, line.channel, { ...this.viewport, profile: this.profile });
866
729
  }
867
- /** Input from the page in use: its size again if another client took it. */
868
730
  claim() {
869
- if (this.reclaim && this.active && this.attachment && !this.attachment.ended())
731
+ const { attachment } = this;
732
+ if (this.sizeTakenByOtherClient && this.active && attachment && !attachment.ended())
870
733
  this.report();
871
734
  }
872
735
  focus(focused) {
873
736
  this.focused = focused;
874
737
  this.recheck();
875
738
  }
876
- /** Looks at this terminal's session again, as `changed` does. */
877
739
  recheck() {
878
740
  const session = this.session === undefined ? undefined : this.hub.session(this.session);
879
741
  if (session)
880
742
  this.changed(session);
881
743
  }
882
- /** A session changed: when it is this terminal's, its screen is shown,
883
- * the page opted in and the terminal has the focus, the `done` and
884
- * `error` records that want the user are marked seen. */
885
744
  changed(session) {
886
745
  if (!this.ackOnFocus || !this.focused || this.acking || session.id !== this.session)
887
746
  return;
888
- if (!this.attachment?.term() || !ACKED.has(session.attention?.state ?? ""))
747
+ if (!this.attachment?.term() || !ACKABLE_ATTENTION_STATES.has(session.attention?.state ?? ""))
889
748
  return;
890
749
  const conn = this.hub.live();
891
750
  if (!conn)
892
751
  return;
893
- // One at a time; a record that came meanwhile is looked at once the
894
- // ack is answered (not after a refusal, which would only repeat).
895
752
  this.acking = true;
896
753
  conn.call("ack", { session: session.id }).then(() => {
897
754
  this.acking = false;
@@ -899,10 +756,6 @@ class Mount {
899
756
  }, () => (this.acking = false));
900
757
  }
901
758
  }
902
- /** The reason an error code ends the link with. */
903
- function linkEnd(code) {
904
- return code === "no_such_session" || code === "engine_mismatch" ? code : "error";
905
- }
906
759
  function describe(exit) {
907
760
  return "code" in exit ? `code ${exit.code}` : `signal ${exit.signal}`;
908
761
  }