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