@gjermundgaraba/clankermux 0.2.0 → 0.4.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,8 +1,9 @@
1
1
  /**
2
- * The engine side of a mounted terminal: the connection, the attachment
3
- * and the render state live in a worker; the page draws frames and
4
- * reports input. Imported as `@gjermundgaraba/clankermux/worker`, so a worker
5
- * typechecked without the DOM library does not see the page's types.
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.
6
7
  */
7
8
  import { ENGINE, Engine, KeyEncoder, RenderState, SelectionGesture, } from "../engine/index.js";
8
9
  import { FrameType, } from "../proto/index.js";
@@ -23,6 +24,8 @@ const BACKOFF_MIN_MS = 250;
23
24
  const BACKOFF_MAX_MS = 5000;
24
25
  /** Ending errors of an OPEN that a new OPEN would only get again. */
25
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"]);
26
29
  /** A WebSocket as the client's message transport. */
27
30
  class SocketTransport {
28
31
  socket;
@@ -49,183 +52,375 @@ class SocketTransport {
49
52
  this.socket.close();
50
53
  }
51
54
  }
52
- class Client {
55
+ function failureOf(err) {
56
+ return err instanceof ClientError
57
+ ? { kind: err.kind, message: err.message, ...(err.server && { server: err.server }) }
58
+ : { kind: "protocol", message: err instanceof Error ? err.message : String(err) };
59
+ }
60
+ /** The link ended with `error`: the server's, else the client's own. */
61
+ function endedWith(err, retry) {
62
+ const server = err instanceof ClientError ? err.server : undefined;
63
+ return server
64
+ ? { state: "ended", reason: linkEnd(server.code), code: server.code, message: server.message, retry }
65
+ : { state: "ended", reason: "error", message: err instanceof Error ? err.message : String(err), retry };
66
+ }
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
+ class Hub {
53
72
  post;
54
73
  constructor(post) {
55
74
  this.post = post;
56
75
  }
57
76
  engine;
58
- render;
59
77
  keys;
60
- gesture;
61
- /** The page holds a selection's text. */
62
- selected = false;
63
78
  url = "";
64
- viewport;
65
- profile;
66
- /** The page is in use; only then are its size and profile reported. */
67
- active = false;
68
- /** Another client resized the session while this page was in use: its
69
- * next input reports its size again. */
70
- reclaim = false;
79
+ client = "clankermux-web";
71
80
  conn;
72
- attachment;
73
- channel = 0;
74
- /** The session attached or being attached. */
75
- session;
76
- sessions = new Map();
77
- /** Input in order: a paste goes as `write` requests, and keys typed
78
- * meanwhile wait behind it. `attach` starts a fresh chain; input queued
79
- * for an attachment that is gone is dropped, but a paste under way
80
- * finishes (cut short, it would leave the program inside a bracketed
81
- * paste). */
82
- writes = Promise.resolve();
83
- clipboard = new Osc52Scanner();
84
- paintTimer;
85
- /** Shared by reconnects and re-attaches after a failure; reset by a screen. */
86
- backoff = BACKOFF_MIN_MS;
87
- reopenTimer;
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. */
85
+ statusText = "connecting";
88
86
  /** Connection attempts since a server last answered. */
89
87
  attempt = 0;
88
+ backoff = BACKOFF_MIN_MS;
90
89
  /** The connection ended for good with the server's refusal or error;
91
- * `attach` connects again. */
90
+ * an `attach` connects again. */
92
91
  refused = false;
93
- link(link) {
94
- this.post({ type: "link", link });
95
- }
96
- /** The link ended with `error`: the server's, else the client's own. */
97
- endedWith(err, retry) {
98
- const server = err instanceof ClientError ? err.server : undefined;
99
- this.link(server
100
- ? { state: "ended", reason: linkEnd(server.code), code: server.code, message: server.message, retry }
101
- : { state: "ended", reason: "error", message: err instanceof Error ? err.message : String(err), retry });
102
- }
103
- delay() {
104
- const delay = this.backoff;
105
- this.backoff = Math.min(this.backoff * 2, BACKOFF_MAX_MS);
106
- return delay;
107
- }
92
+ /** Frame channels, shared by the terminals of the one connection. */
93
+ channel = 0;
94
+ mounts = new Map();
95
+ sessions = new Map();
96
+ /** The list is being paged: not shown to the page until it is whole. */
97
+ 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. */
101
+ requests = new Map();
108
102
  async init(message) {
109
103
  this.url = message.url;
110
- this.viewport = message.viewport;
111
- this.profile = message.profile;
112
- this.active = message.active;
113
- this.session = message.session;
114
- this.post({ type: "status", text: "loading engine" });
104
+ if (message.client)
105
+ this.client = message.client;
115
106
  try {
116
107
  const wasm = await (await fetch(message.wasm)).arrayBuffer();
117
108
  this.engine = await Engine.load(wasm);
118
109
  }
119
110
  catch (err) {
120
- this.post({ type: "status", text: `cannot load the engine: ${err}` });
121
- this.endedWith(err, false);
111
+ this.post({ type: "failed", message: `cannot load the engine: ${err}` });
122
112
  return;
123
113
  }
124
- this.render = new RenderState(this.engine);
125
114
  this.keys = new KeyEncoder(this.engine);
126
- this.gesture = new SelectionGesture(this.engine);
115
+ this.post({ type: "ready" });
127
116
  await this.connect();
128
117
  }
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
+ linkAll(link) {
126
+ this.state = link.state === "ended" && link.retry ? { state: "connecting", attempt: this.attempt + 1 } : link;
127
+ this.post({ type: "connection", link });
128
+ for (const mount of this.mounts.values())
129
+ mount.link(link);
130
+ }
131
+ statusAll(text) {
132
+ this.statusText = text;
133
+ for (const mount of this.mounts.values())
134
+ mount.status(text);
135
+ }
136
+ /** The connection is up and subscribed: terminals may open channels. */
137
+ live() {
138
+ return this.state.state === "connected" ? this.conn : undefined;
139
+ }
140
+ /** The connection ended for good with `err`. */
141
+ refuse(err) {
142
+ this.refused = true;
143
+ this.statusAll(err instanceof Error ? err.message : String(err));
144
+ this.linkAll(endedWith(err, false));
145
+ }
129
146
  async connect() {
130
- this.post({ type: "status", text: this.attachment ? "reconnecting" : "connecting" });
131
- this.link({ state: "connecting", attempt: ++this.attempt });
147
+ this.statusAll(this.events ? "reconnecting" : "connecting");
148
+ this.linkAll({ state: "connecting", attempt: ++this.attempt });
132
149
  let conn;
133
150
  try {
134
- conn = await Connection.connect(await SocketTransport.connect(this.url), hello("clankermux-web", ENGINE));
151
+ conn = await Connection.connect(await SocketTransport.connect(this.url), hello(this.client, ENGINE));
135
152
  }
136
153
  catch (err) {
137
154
  // A server that answers and refuses is not retried; a lost one is.
138
155
  if (err instanceof ClientError && (err.kind === "server" || err.kind === "protocol")) {
139
- this.post({ type: "status", text: err.message });
140
- this.refused = true;
141
- this.endedWith(err, false);
156
+ this.refuse(err);
142
157
  return;
143
158
  }
144
159
  setTimeout(() => void this.connect(), this.delay());
145
160
  return;
146
161
  }
147
162
  this.attempt = 0;
163
+ this.backoff = BACKOFF_MIN_MS;
148
164
  this.conn = conn;
149
165
  conn.onEnd = (err) => {
150
166
  if (this.conn !== conn)
151
167
  return;
152
168
  this.conn = undefined;
153
169
  if (err.kind === "server") {
154
- this.post({ type: "status", text: err.message });
155
- this.refused = true;
156
- this.endedWith(err, false);
170
+ this.refuse(err);
157
171
  }
158
172
  else {
159
- this.link({ state: "ended", reason: "closed", retry: true });
173
+ this.linkAll({ state: "ended", reason: "closed", retry: true });
160
174
  setTimeout(() => void this.connect(), this.delay());
161
175
  }
162
176
  };
163
177
  conn.onEvent = (event) => this.event(event);
164
178
  try {
165
- // Events arriving between pages are applied to the same map: a
166
- // later page cannot hold a session removed before it was produced.
167
- this.sessions.clear();
168
- let page = await conn.call("subscribe", {});
169
- for (;;) {
170
- for (const s of page.sessions)
171
- this.sessions.set(s.id, s);
172
- if (page.next === undefined)
173
- break;
174
- page = await conn.call("list", { after: page.next });
175
- }
179
+ await this.subscribe(conn);
176
180
  }
177
181
  catch (err) {
178
- this.post({ type: "status", text: String(err) });
179
182
  // A lost connection is reported through onEnd, which ran first; a
180
183
  // refused subscription ends this one for good.
181
184
  if (this.conn === conn) {
182
185
  this.conn = undefined;
183
186
  conn.close();
184
- this.refused = true;
185
- this.endedWith(err, false);
187
+ this.refuse(err);
186
188
  }
187
189
  return;
188
190
  }
189
- this.postSessions();
190
- if (this.session !== undefined) {
191
- this.open();
191
+ this.state = { state: "connected", session: undefined };
192
+ this.statusText = "connected";
193
+ this.post({ type: "connection", link: this.state });
194
+ for (const mount of this.mounts.values())
195
+ mount.connected();
196
+ }
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
+ async subscribe(conn) {
201
+ const incarnation = conn.welcome.incarnation;
202
+ if (this.events) {
203
+ const replay = await conn.call("subscribe", {
204
+ after: this.events.seq,
205
+ incarnation: this.events.incarnation,
206
+ });
207
+ if (!replay.gap)
208
+ return;
209
+ this.events = { incarnation, seq: replay.latest };
210
+ await this.page(conn, await conn.call("list", {}));
211
+ this.post({ type: "gap", incarnation });
212
+ for (const mount of this.mounts.values())
213
+ mount.recheck();
214
+ return;
192
215
  }
193
- else {
194
- this.post({ type: "status", text: "no session" });
195
- this.link({ state: "connected", session: undefined });
216
+ const first = await conn.call("subscribe", {});
217
+ this.events = { incarnation, seq: first.latest };
218
+ await this.page(conn, { sessions: first.sessions ?? [], ...(first.next !== undefined && { next: first.next }) });
219
+ }
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
+ async page(conn, page) {
224
+ this.sessions.clear();
225
+ this.paging = true;
226
+ try {
227
+ for (;;) {
228
+ for (const s of page.sessions)
229
+ this.sessions.set(s.id, s);
230
+ if (page.next === undefined)
231
+ break;
232
+ page = await conn.call("list", { after: page.next });
233
+ }
196
234
  }
235
+ finally {
236
+ this.paging = false;
237
+ }
238
+ this.postSessions();
197
239
  }
198
240
  event(event) {
241
+ if (this.events)
242
+ this.events.seq = event.seq;
199
243
  switch (event.event) {
200
244
  case "session_created":
201
245
  case "session_changed":
202
246
  case "session_exited":
203
247
  this.sessions.set(event.session.id, event.session);
248
+ this.postSessions();
249
+ for (const mount of this.mounts.values())
250
+ mount.changed(event.session);
204
251
  break;
205
252
  case "session_removed":
206
253
  this.sessions.delete(event.id);
254
+ this.postSessions();
207
255
  break;
208
256
  }
209
- this.postSessions();
257
+ this.post({ type: "event", event });
258
+ }
259
+ session(id) {
260
+ return this.sessions.get(id);
210
261
  }
211
262
  postSessions() {
212
- this.post({ type: "sessions", sessions: [...this.sessions.values()], current: this.session });
263
+ if (!this.paging)
264
+ this.post({ type: "sessions", sessions: [...this.sessions.values()] });
265
+ }
266
+ nextChannel() {
267
+ return ++this.channel;
268
+ }
269
+ /** A protocol request from the page; its outcome goes back by `id`. */
270
+ async request(id, method, params) {
271
+ const conn = this.conn;
272
+ if (!conn) {
273
+ this.post({ type: "reply", id, error: { kind: "closed", message: "not connected" } });
274
+ return;
275
+ }
276
+ const { id: wire, reply } = conn.request(method, params);
277
+ this.requests.set(id, { conn, wire });
278
+ try {
279
+ this.post({ type: "reply", id, result: await reply });
280
+ }
281
+ catch (err) {
282
+ this.post({ type: "reply", id, error: failureOf(err) });
283
+ }
284
+ finally {
285
+ this.requests.delete(id);
286
+ }
287
+ }
288
+ /** Cancels the page's request `id`, when it is still pending. Its own
289
+ * reply is the server's `cancelled`. */
290
+ cancel(id) {
291
+ const pending = this.requests.get(id);
292
+ if (!pending || pending.conn !== this.conn)
293
+ return;
294
+ pending.conn.call("cancel", { id: pending.wire }).catch(() => { });
295
+ }
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
+ mount(id, init) {
300
+ const mount = new Mount(this, id, init);
301
+ this.mounts.set(id, mount);
302
+ mount.status(this.statusText);
303
+ if (this.refused)
304
+ this.reattach(mount);
305
+ else if (this.live())
306
+ mount.connected();
307
+ else
308
+ mount.link(this.state);
309
+ }
310
+ unmount(id) {
311
+ this.mounts.get(id)?.dispose();
312
+ this.mounts.delete(id);
313
+ }
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
+ reattach(mount) {
318
+ if (this.refused) {
319
+ this.refused = false;
320
+ this.attempt = 0;
321
+ void this.connect();
322
+ }
323
+ else {
324
+ mount.open();
325
+ }
326
+ }
327
+ }
328
+ /** One mounted terminal: an attachment on the hub's connection, its render
329
+ * state, selection, input and size. */
330
+ class Mount {
331
+ hub;
332
+ id;
333
+ attachment;
334
+ channel = 0;
335
+ /** The connection the channel is open on. */
336
+ openOn;
337
+ /** An `ack` is under way. */
338
+ acking = false;
339
+ /** The session attached or being attached. */
340
+ session;
341
+ viewport;
342
+ profile;
343
+ /** The page is in use; only then are its size and profile reported. */
344
+ active;
345
+ readOnly;
346
+ ackOnFocus;
347
+ /** The terminal has the keyboard and its window the focus. */
348
+ 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;
352
+ render;
353
+ gesture;
354
+ /** The page holds a selection's text. */
355
+ 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();
362
+ clipboard = new Osc52Scanner();
363
+ paintTimer;
364
+ /** Re-attaches after a failure; reset by a screen. */
365
+ backoff = BACKOFF_MIN_MS;
366
+ reopenTimer;
367
+ disposed = false;
368
+ constructor(hub, id, init) {
369
+ this.hub = hub;
370
+ this.id = id;
371
+ this.session = init.session;
372
+ this.viewport = init.viewport;
373
+ this.profile = init.profile;
374
+ this.active = init.active;
375
+ this.readOnly = init.readOnly;
376
+ this.ackOnFocus = init.ackOnFocus;
377
+ this.render = new RenderState(hub.engine);
378
+ this.gesture = new SelectionGesture(hub.engine);
379
+ }
380
+ post(message) {
381
+ if (!this.disposed)
382
+ this.hub.post(message);
383
+ }
384
+ link(link) {
385
+ this.post({ type: "link", mount: this.id, link });
386
+ }
387
+ status(text) {
388
+ this.post({ type: "status", mount: this.id, text });
389
+ }
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
+ connected() {
397
+ if (this.session !== undefined) {
398
+ this.open();
399
+ }
400
+ else {
401
+ this.status("no session");
402
+ this.link({ state: "connected", session: undefined });
403
+ }
213
404
  }
214
405
  /** Opens a channel for `this.session`, resuming when the attachment can. */
215
406
  open() {
216
- const conn = this.conn;
217
- if (!conn || this.session === undefined)
407
+ const conn = this.hub.live();
408
+ if (!conn || this.session === undefined || this.disposed || this.openOn === conn)
218
409
  return;
219
410
  if (!this.attachment)
220
- this.attachment = new Attachment(this.engine);
411
+ this.attachment = new Attachment(this.hub.engine);
221
412
  const attachment = this.attachment;
222
413
  attachment.openOn(conn.welcome);
223
- const channel = ++this.channel;
414
+ const channel = this.hub.nextChannel();
415
+ this.channel = channel;
416
+ this.openOn = conn;
417
+ const resume = attachment.resume();
224
418
  // An OPEN with a viewport or profile is a report applied at once.
225
419
  const open = {
226
420
  session: this.session,
421
+ ...(this.readOnly && { read_only: true }),
227
422
  ...(this.active && { viewport: this.viewport, profile: this.profile }),
228
- resume: attachment.resume(),
423
+ ...(resume && { resume }),
229
424
  };
230
425
  try {
231
426
  conn.open(channel, open, (frame) => {
@@ -238,9 +433,9 @@ class Client {
238
433
  catch (err) {
239
434
  // A lost place in the stream: CLOSE and OPEN again, afresh. Any
240
435
  // other fault would only repeat.
241
- this.post({ type: "status", text: String(err) });
436
+ this.status(String(err));
242
437
  const desync = err instanceof ClientError && err.kind === "desync";
243
- this.endedWith(err, desync);
438
+ this.link(endedWith(err, desync));
244
439
  if (desync)
245
440
  this.reopen();
246
441
  else
@@ -248,19 +443,20 @@ class Client {
248
443
  return;
249
444
  }
250
445
  if (frame.header.type === FrameType.Attached && actions.length === 0) {
251
- this.post({ type: "status", text: "attached" });
252
446
  // Resumed: the terminal shows the stream already, and an exit
253
447
  // still to come arrives as EXITED. A snapshot's screen comes
254
448
  // later, as an action.
255
- if (attachment.resume())
449
+ if (attachment.resume()) {
450
+ this.status("resumed");
256
451
  this.link({ state: "connected", session: attachment.session });
452
+ }
257
453
  }
258
454
  for (const action of actions)
259
455
  this.apply(action);
260
456
  });
261
457
  }
262
458
  catch (err) {
263
- this.post({ type: "status", text: String(err) });
459
+ this.status(String(err));
264
460
  }
265
461
  }
266
462
  /** The screen of `session` is shown: `connected`, and at once `ended
@@ -273,13 +469,12 @@ class Client {
273
469
  }
274
470
  /** Detaches for good: a reconnect does not try the session again. */
275
471
  giveUp() {
276
- this.detach();
472
+ this.close();
277
473
  this.session = undefined;
278
- this.postSessions();
279
474
  }
280
475
  /** Detaches and attaches the same session again after a backoff. */
281
476
  reopen() {
282
- this.detach();
477
+ this.close();
283
478
  this.reopenTimer ??= setTimeout(() => {
284
479
  this.reopenTimer = undefined;
285
480
  if (this.session !== undefined && !this.attachment)
@@ -300,16 +495,19 @@ class Client {
300
495
  : session?.exit
301
496
  ? `exited: ${describe(session.exit)}`
302
497
  : "attached";
303
- this.post({ type: "status", text });
498
+ this.status(text);
304
499
  this.attached(session);
500
+ if (session)
501
+ this.changed(session);
305
502
  break;
306
503
  }
307
504
  case "output":
308
505
  for (const write of this.clipboard.feed(action.bytes)) {
309
506
  // Only the clipboard selection; primary and secondary have no
310
507
  // browser equivalent.
311
- if (write.selection === "" || write.selection.includes("c"))
312
- this.post({ type: "clipboard", text: write.text });
508
+ if (write.selection === "" || write.selection.includes("c")) {
509
+ this.post({ type: "clipboard", mount: this.id, text: write.text });
510
+ }
313
511
  }
314
512
  this.paintTimer ??= setTimeout(() => this.paint(), PAINT_MS);
315
513
  break;
@@ -323,24 +521,30 @@ class Client {
323
521
  break;
324
522
  case "exited":
325
523
  this.paint();
326
- this.post({ type: "status", text: `exited: ${describe(action.exit)}` });
524
+ this.status(`exited: ${describe(action.exit)}`);
327
525
  this.link({ state: "ended", reason: "exited", exit: action.exit, retry: false });
328
526
  break;
329
527
  case "gap":
330
528
  this.clipboard.reset();
331
529
  this.forgetSelection();
332
- this.post({ type: "status", text: "resynchronising" });
530
+ this.status("resynchronising");
333
531
  break;
334
532
  case "closed":
335
- this.post({ type: "status", text: `closed: ${action.reason}` });
533
+ this.status(`closed: ${action.reason}`);
336
534
  // `stopping` is followed by the connection's close, and the
337
- // reconnect attaches again; a removed session is gone for good.
338
- this.link({ state: "ended", reason: action.reason, retry: action.reason === "stopping" });
339
- if (action.reason === "removed")
535
+ // reconnect attaches again; a removed session is gone for good,
536
+ // and a detached page does not take its session back.
537
+ this.link({
538
+ state: "ended",
539
+ reason: action.reason,
540
+ ...(action.message !== undefined && { message: action.message }),
541
+ retry: action.reason === "stopping",
542
+ });
543
+ if (action.reason === "removed" || action.reason === "detached")
340
544
  this.giveUp();
341
545
  break;
342
546
  case "error": {
343
- this.post({ type: "status", text: `${action.error.code}: ${action.error.message}` });
547
+ this.status(`${action.error.code}: ${action.error.message}`);
344
548
  // An error ended the attachment: attach again after a backoff
345
549
  // (`too_slow`, a snapshot that could not be taken), unless a new
346
550
  // OPEN would fail the same way.
@@ -379,7 +583,7 @@ class Client {
379
583
  // update full; so does a resize. A full repaint of the same terminal
380
584
  // comes from a clean render state.
381
585
  this.render.free();
382
- this.render = new RenderState(this.engine);
586
+ this.render = new RenderState(this.hub.engine);
383
587
  this.paint();
384
588
  }
385
589
  paint() {
@@ -388,9 +592,9 @@ class Client {
388
592
  this.paintTimer = undefined;
389
593
  }
390
594
  const term = this.attachment?.term();
391
- if (!term)
595
+ if (!term || this.disposed)
392
596
  return;
393
- this.post({ type: "frame", frame: this.render.update(term) });
597
+ this.post({ type: "frame", mount: this.id, frame: this.render.update(term) });
394
598
  this.render.clean();
395
599
  // A switch to the alternate screen or a full reset took the selection.
396
600
  if (this.selected && !term.selected)
@@ -421,7 +625,7 @@ class Client {
421
625
  // (trimmed to nothing) are no text to copy.
422
626
  const text = term.selectionText() || undefined;
423
627
  this.selected = text !== undefined;
424
- this.post({ type: "selection", text, copy: true });
628
+ this.post({ type: "selection", mount: this.id, text, copy: true });
425
629
  break;
426
630
  }
427
631
  }
@@ -439,7 +643,7 @@ class Client {
439
643
  }
440
644
  unselected() {
441
645
  this.selected = false;
442
- this.post({ type: "selection", text: undefined, copy: false });
646
+ this.post({ type: "selection", mount: this.id, text: undefined, copy: false });
443
647
  }
444
648
  /** The terminal goes, and its selection and the gesture's anchor with it. */
445
649
  forgetSelection(term) {
@@ -450,16 +654,17 @@ class Client {
450
654
  /** Closes the current attachment's channel and forgets it. An
451
655
  * attachment the server ended needs no CLOSE; one whose stream ended
452
656
  * (EXITED) does. */
453
- detach() {
657
+ close() {
454
658
  if (!this.attachment)
455
659
  return;
456
660
  // Still alive: the gesture's anchor is released in it.
457
661
  this.forgetSelection(this.attachment.term());
458
- if (this.conn) {
459
- this.conn.release(this.channel);
662
+ const conn = this.hub.conn;
663
+ if (conn) {
664
+ conn.release(this.channel);
460
665
  if (!this.attachment.closed()) {
461
666
  try {
462
- this.conn.send(FrameType.Close, this.channel, new Uint8Array());
667
+ conn.send(FrameType.Close, this.channel, new Uint8Array());
463
668
  }
464
669
  catch {
465
670
  // The connection is gone; nothing to close.
@@ -468,81 +673,50 @@ class Client {
468
673
  }
469
674
  this.attachment.free();
470
675
  this.attachment = undefined;
676
+ this.openOn = undefined;
471
677
  }
472
- /** Attaches `session`; after the server refused or ended the
473
- * connection, connects again first. */
678
+ /** Detaches the current session and attaches `session`; after the
679
+ * server refused or ended the connection, connects again first. */
474
680
  attach(session) {
475
- this.detach();
681
+ this.close();
476
682
  this.writes = Promise.resolve();
477
683
  this.session = session;
478
- this.postSessions();
479
- if (this.refused) {
480
- this.refused = false;
481
- this.attempt = 0;
482
- void this.connect();
483
- }
484
- else {
485
- this.open();
486
- }
684
+ this.hub.reattach(this);
487
685
  }
488
- /** Creates a session at the current size and attaches it; `on_exit`
489
- * only when given, so the server's default holds otherwise. */
490
- async create(id, onExit) {
491
- const conn = this.conn;
492
- if (!conn)
493
- return this.fail(id, new ClientError("closed", "not connected"));
494
- const params = { cols: this.viewport.cols, rows: this.viewport.rows };
495
- if (onExit !== undefined)
496
- params.on_exit = onExit;
497
- let session;
498
- try {
499
- session = await conn.call("create", params);
500
- }
501
- catch (err) {
502
- this.post({ type: "status", text: String(err) });
503
- return this.fail(id, err);
504
- }
505
- this.attach(session.id);
506
- this.post({ type: "done", id, session });
507
- }
508
- /** `end` (SIGHUP) or `remove` for the session attached or being
509
- * attached. `not_running` from `end` is success: there is nothing left
510
- * to end. */
511
- async request(id, method) {
512
- const conn = this.conn;
513
- const session = this.session;
514
- if (!conn)
515
- return this.fail(id, new ClientError("closed", "not connected"));
516
- if (session === undefined)
517
- return this.fail(id, new Error("no session is attached"));
518
- try {
519
- await conn.call(method, { session });
520
- }
521
- catch (err) {
522
- if (!(method === "end" && err instanceof ClientError && err.server?.code === "not_running")) {
523
- return this.fail(id, err);
524
- }
686
+ /** Detaches, and stays attached to none. */
687
+ detach() {
688
+ const had = this.session !== undefined;
689
+ this.giveUp();
690
+ this.writes = Promise.resolve();
691
+ if (had && this.hub.conn) {
692
+ this.status("no session");
693
+ this.link({ state: "connected", session: undefined });
525
694
  }
526
- this.post({ type: "done", id });
527
- }
528
- fail(id, err) {
529
- const error = err instanceof ClientError
530
- ? { kind: err.kind, message: err.message, ...(err.server && { server: err.server }) }
531
- : { message: err instanceof Error ? err.message : String(err) };
532
- this.post({ type: "done", id, error });
533
695
  }
534
- /** Input for the session, dropped unless attached on a live connection.
535
- * Keys go as INPUT; a paste goes as `write` requests, each answered
536
- * once the PTY took it, since INPUT frames are not acknowledged and a
537
- * paste would overflow the input queue. This tab's input is sent in
538
- * order, so none of it lands inside a paste. */
696
+ dispose() {
697
+ this.close();
698
+ this.disposed = true;
699
+ if (this.paintTimer !== undefined)
700
+ clearTimeout(this.paintTimer);
701
+ if (this.reopenTimer !== undefined)
702
+ clearTimeout(this.reopenTimer);
703
+ this.render.free();
704
+ this.gesture.forget(undefined);
705
+ }
706
+ /** Input for the session, dropped unless attached on a live connection,
707
+ * and for a read-only terminal. Keys go as INPUT; a paste goes as
708
+ * `send` requests, each answered once the PTY took it, since INPUT
709
+ * frames are not acknowledged and a paste would overflow the input
710
+ * queue. This terminal's input is sent in order, so none of it lands
711
+ * inside a paste. */
539
712
  input(bytes, paste) {
540
- const conn = this.conn;
713
+ const conn = this.hub.conn;
541
714
  const attachment = this.attachment;
542
715
  const session = this.session;
543
716
  const channel = this.channel;
544
- if (bytes.length === 0 || !conn || !attachment || attachment.ended() || session === undefined)
717
+ if (bytes.length === 0 || this.readOnly || !conn || !attachment || attachment.ended() || session === undefined) {
545
718
  return;
719
+ }
546
720
  this.claim();
547
721
  this.live();
548
722
  this.unselect();
@@ -560,14 +734,14 @@ class Client {
560
734
  return;
561
735
  }
562
736
  for (let at = 0; at < bytes.length; at += chunk) {
563
- await conn.call("write", { session, data: base64(bytes.subarray(at, at + chunk)) });
737
+ await conn.call("send", { session, data: base64(bytes.subarray(at, at + chunk)) });
564
738
  }
565
739
  }
566
740
  catch (err) {
567
741
  // A connection loss is reported through onEnd; a refused chunk
568
742
  // ends the paste there.
569
- if (conn === this.conn)
570
- this.post({ type: "status", text: String(err) });
743
+ if (conn === this.hub.conn)
744
+ this.status(String(err));
571
745
  }
572
746
  });
573
747
  }
@@ -585,12 +759,12 @@ class Client {
585
759
  this.paint();
586
760
  return;
587
761
  }
588
- this.input(this.keys.encode(term, input), false);
762
+ this.input(this.hub.keys.encode(term, input), false);
589
763
  }
590
764
  /** The wheel. On the alternate screen, with alternate scroll (mode
591
765
  * 1007, on by default), it is the arrow keys, as a full-screen program
592
766
  * such as `less` expects; without it, nothing. */
593
- scroll(rows) {
767
+ wheel(rows) {
594
768
  const term = this.attachment?.term();
595
769
  if (!term || rows === 0)
596
770
  return;
@@ -603,12 +777,25 @@ class Client {
603
777
  if (!term.mode(1007))
604
778
  return;
605
779
  const code = rows < 0 ? "ArrowUp" : "ArrowDown";
606
- const arrow = this.keys.encode(term, { code, key: code, action: "press", shift: false, ctrl: false, alt: false, meta: false });
780
+ const arrow = this.hub.keys.encode(term, { code, key: code, action: "press", shift: false, ctrl: false, alt: false, meta: false });
607
781
  const bytes = new Uint8Array(arrow.length * Math.abs(rows));
608
782
  for (let i = 0; i < Math.abs(rows); i++)
609
783
  bytes.set(arrow, i * arrow.length);
610
784
  this.input(bytes, false);
611
785
  }
786
+ /** The view through the history, as the page asks: by rows, or back to
787
+ * the live screen. The alternate screen has no history. */
788
+ view(rows) {
789
+ const term = this.attachment?.term();
790
+ if (!term || term.alternate)
791
+ return;
792
+ if (rows === "live")
793
+ this.live();
794
+ else if (rows !== 0) {
795
+ term.scroll(rows);
796
+ this.paint();
797
+ }
798
+ }
612
799
  /** Back to the live screen before input, as any terminal does. */
613
800
  live() {
614
801
  const term = this.attachment?.term();
@@ -630,18 +817,18 @@ class Client {
630
817
  const term = this.attachment?.term();
631
818
  if (!term)
632
819
  return;
633
- this.input(this.engine.encodePaste(text, term.mode(2004)), true);
820
+ this.input(this.hub.engine.encodePaste(text, term.mode(2004)), true);
634
821
  }
635
- /** Keeps the page's size (for `create`) and colours (for the local
636
- * terminal), and reports them to the session while the page is active.
637
- * A report repeats the last one when the page becomes active again, so
638
- * the session takes its size back from another client. */
822
+ /** Keeps the page's size and colours (for the local terminal), and
823
+ * reports them to the session while the page is active. A report
824
+ * repeats the last one when the page becomes active again, so the
825
+ * session takes its size back from another client. */
639
826
  setViewport(size, profile, active) {
640
827
  this.viewport = size;
641
828
  this.profile = profile;
642
829
  this.active = active;
643
830
  const attachment = this.attachment;
644
- if (!this.conn || !attachment || attachment.ended())
831
+ if (!this.hub.conn || !attachment || attachment.ended())
645
832
  return;
646
833
  this.applyProfile(attachment.term());
647
834
  this.paint();
@@ -651,7 +838,7 @@ class Client {
651
838
  report() {
652
839
  this.reclaim = false;
653
840
  try {
654
- this.conn?.sendJson(FrameType.Viewport, this.channel, { ...this.viewport, profile: this.profile });
841
+ this.hub.conn?.sendJson(FrameType.Viewport, this.channel, { ...this.viewport, profile: this.profile });
655
842
  }
656
843
  catch {
657
844
  // Reported through onEnd.
@@ -662,6 +849,35 @@ class Client {
662
849
  if (this.reclaim && this.active && this.attachment && !this.attachment.ended())
663
850
  this.report();
664
851
  }
852
+ focus(focused) {
853
+ this.focused = focused;
854
+ this.recheck();
855
+ }
856
+ /** Looks at this terminal's session again, as `changed` does. */
857
+ recheck() {
858
+ const session = this.session === undefined ? undefined : this.hub.session(this.session);
859
+ if (session)
860
+ this.changed(session);
861
+ }
862
+ /** A session changed: when it is this terminal's, its screen is shown,
863
+ * the page opted in and the terminal has the focus, the `done` and
864
+ * `error` records that want the user are marked seen. */
865
+ changed(session) {
866
+ if (!this.ackOnFocus || !this.focused || this.acking || session.id !== this.session)
867
+ return;
868
+ if (!this.attachment?.term() || !ACKED.has(session.attention?.state ?? ""))
869
+ return;
870
+ const conn = this.hub.live();
871
+ if (!conn)
872
+ return;
873
+ // One at a time; a record that came meanwhile is looked at once the
874
+ // ack is answered (not after a refusal, which would only repeat).
875
+ this.acking = true;
876
+ conn.call("ack", { session: session.id }).then(() => {
877
+ this.acking = false;
878
+ this.recheck();
879
+ }, () => (this.acking = false));
880
+ }
665
881
  }
666
882
  /** The reason an error code ends the link with. */
667
883
  function linkEnd(code) {
@@ -670,46 +886,69 @@ function linkEnd(code) {
670
886
  function describe(exit) {
671
887
  return "code" in exit ? `code ${exit.code}` : `signal ${exit.signal}`;
672
888
  }
673
- /** Serves a page's `mountTerminal` on `port`: the worker module the page
674
- * starts calls `runWorker(self)`. */
889
+ /** Serves a page's `connect` on `port`: the worker module the page starts
890
+ * calls `runWorker(self)`. */
675
891
  export function runWorker(port) {
676
- const client = new Client((message) => port.postMessage(message));
892
+ const hub = new Hub((message) => port.postMessage(message));
677
893
  port.onmessage = (e) => {
678
894
  const message = e.data;
895
+ if (message.type === "init") {
896
+ void hub.init(message);
897
+ return;
898
+ }
899
+ if (message.type === "request") {
900
+ void hub.request(message.id, message.method, message.params);
901
+ return;
902
+ }
903
+ if (message.type === "cancel") {
904
+ hub.cancel(message.id);
905
+ return;
906
+ }
907
+ if (message.type === "mount") {
908
+ const { type: _, mount, ...init } = message;
909
+ hub.mount(mount, init);
910
+ return;
911
+ }
912
+ if (message.type === "unmount") {
913
+ hub.unmount(message.mount);
914
+ return;
915
+ }
916
+ const mount = hub.mounts.get(message.mount);
917
+ if (!mount)
918
+ return;
679
919
  switch (message.type) {
680
- case "init":
681
- void client.init(message);
682
- break;
683
920
  case "attach":
684
- client.attach(message.session);
921
+ mount.attach(message.session);
685
922
  break;
686
- case "create":
687
- void client.create(message.id, message.onExit);
688
- break;
689
- case "end":
690
- case "remove":
691
- void client.request(message.id, message.type);
923
+ case "detach":
924
+ mount.detach();
692
925
  break;
693
926
  case "key":
694
- client.key(message.input);
927
+ mount.key(message.input);
695
928
  break;
696
929
  case "paste":
697
- client.paste(message.text);
930
+ mount.paste(message.text);
698
931
  break;
699
932
  case "text":
700
- client.text(message.text);
933
+ mount.text(message.text);
701
934
  break;
702
935
  case "select":
703
- client.select(message.action, message.at, message.time);
936
+ mount.select(message.action, message.at, message.time);
937
+ break;
938
+ case "wheel":
939
+ mount.wheel(message.rows);
704
940
  break;
705
- case "scroll":
706
- client.scroll(message.rows);
941
+ case "view":
942
+ mount.view(message.rows);
707
943
  break;
708
944
  case "viewport":
709
- client.setViewport(message.size, message.profile, message.active);
945
+ mount.setViewport(message.size, message.profile, message.active);
946
+ break;
947
+ case "focus":
948
+ mount.focus(message.focused);
710
949
  break;
711
950
  case "repaint":
712
- client.repaint();
951
+ mount.repaint();
713
952
  break;
714
953
  }
715
954
  };