@gjermundgaraba/clankermux 0.3.0 → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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 `send` 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)
@@ -398,10 +602,14 @@ class Client {
398
602
  }
399
603
  /** The mouse: a press clears the selection, or selects a word or a line
400
604
  * at once; a drag selects; the release copies what is selected. */
401
- select(action, at, time) {
605
+ select(action, at, time, copy) {
402
606
  const term = this.attachment?.term();
403
- if (!term)
607
+ 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 });
404
611
  return;
612
+ }
405
613
  switch (action) {
406
614
  case "press":
407
615
  this.claim();
@@ -421,7 +629,7 @@ class Client {
421
629
  // (trimmed to nothing) are no text to copy.
422
630
  const text = term.selectionText() || undefined;
423
631
  this.selected = text !== undefined;
424
- this.post({ type: "selection", text, copy: true });
632
+ this.post({ type: "selection", mount: this.id, text, ...(copy !== undefined ? { copy } : {}) });
425
633
  break;
426
634
  }
427
635
  }
@@ -439,7 +647,7 @@ class Client {
439
647
  }
440
648
  unselected() {
441
649
  this.selected = false;
442
- this.post({ type: "selection", text: undefined, copy: false });
650
+ this.post({ type: "selection", mount: this.id, text: undefined });
443
651
  }
444
652
  /** The terminal goes, and its selection and the gesture's anchor with it. */
445
653
  forgetSelection(term) {
@@ -450,16 +658,17 @@ class Client {
450
658
  /** Closes the current attachment's channel and forgets it. An
451
659
  * attachment the server ended needs no CLOSE; one whose stream ended
452
660
  * (EXITED) does. */
453
- detach() {
661
+ close() {
454
662
  if (!this.attachment)
455
663
  return;
456
664
  // Still alive: the gesture's anchor is released in it.
457
665
  this.forgetSelection(this.attachment.term());
458
- if (this.conn) {
459
- this.conn.release(this.channel);
666
+ const conn = this.hub.conn;
667
+ if (conn) {
668
+ conn.release(this.channel);
460
669
  if (!this.attachment.closed()) {
461
670
  try {
462
- this.conn.send(FrameType.Close, this.channel, new Uint8Array());
671
+ conn.send(FrameType.Close, this.channel, new Uint8Array());
463
672
  }
464
673
  catch {
465
674
  // The connection is gone; nothing to close.
@@ -468,81 +677,50 @@ class Client {
468
677
  }
469
678
  this.attachment.free();
470
679
  this.attachment = undefined;
680
+ this.openOn = undefined;
471
681
  }
472
- /** Attaches `session`; after the server refused or ended the
473
- * connection, connects again first. */
682
+ /** Detaches the current session and attaches `session`; after the
683
+ * server refused or ended the connection, connects again first. */
474
684
  attach(session) {
475
- this.detach();
685
+ this.close();
476
686
  this.writes = Promise.resolve();
477
687
  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
- }
688
+ this.hub.reattach(this);
487
689
  }
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
- }
690
+ /** Detaches, and stays attached to none. */
691
+ detach() {
692
+ const had = this.session !== undefined;
693
+ this.giveUp();
694
+ this.writes = Promise.resolve();
695
+ if (had && this.hub.conn) {
696
+ this.status("no session");
697
+ this.link({ state: "connected", session: undefined });
525
698
  }
526
- this.post({ type: "done", id });
527
699
  }
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
- }
534
- /** Input for the session, dropped unless attached on a live connection.
535
- * Keys go as INPUT; a paste goes as `send` 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. */
700
+ dispose() {
701
+ this.close();
702
+ this.disposed = true;
703
+ if (this.paintTimer !== undefined)
704
+ clearTimeout(this.paintTimer);
705
+ if (this.reopenTimer !== undefined)
706
+ clearTimeout(this.reopenTimer);
707
+ this.render.free();
708
+ this.gesture.forget(undefined);
709
+ }
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. */
539
716
  input(bytes, paste) {
540
- const conn = this.conn;
717
+ const conn = this.hub.conn;
541
718
  const attachment = this.attachment;
542
719
  const session = this.session;
543
720
  const channel = this.channel;
544
- if (bytes.length === 0 || !conn || !attachment || attachment.ended() || session === undefined)
721
+ if (bytes.length === 0 || this.readOnly || !conn || !attachment || attachment.ended() || session === undefined) {
545
722
  return;
723
+ }
546
724
  this.claim();
547
725
  this.live();
548
726
  this.unselect();
@@ -566,8 +744,8 @@ class Client {
566
744
  catch (err) {
567
745
  // A connection loss is reported through onEnd; a refused chunk
568
746
  // ends the paste there.
569
- if (conn === this.conn)
570
- this.post({ type: "status", text: String(err) });
747
+ if (conn === this.hub.conn)
748
+ this.status(String(err));
571
749
  }
572
750
  });
573
751
  }
@@ -585,12 +763,12 @@ class Client {
585
763
  this.paint();
586
764
  return;
587
765
  }
588
- this.input(this.keys.encode(term, input), false);
766
+ this.input(this.hub.keys.encode(term, input), false);
589
767
  }
590
768
  /** The wheel. On the alternate screen, with alternate scroll (mode
591
769
  * 1007, on by default), it is the arrow keys, as a full-screen program
592
770
  * such as `less` expects; without it, nothing. */
593
- scroll(rows) {
771
+ wheel(rows) {
594
772
  const term = this.attachment?.term();
595
773
  if (!term || rows === 0)
596
774
  return;
@@ -603,12 +781,25 @@ class Client {
603
781
  if (!term.mode(1007))
604
782
  return;
605
783
  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 });
784
+ const arrow = this.hub.keys.encode(term, { code, key: code, action: "press", shift: false, ctrl: false, alt: false, meta: false });
607
785
  const bytes = new Uint8Array(arrow.length * Math.abs(rows));
608
786
  for (let i = 0; i < Math.abs(rows); i++)
609
787
  bytes.set(arrow, i * arrow.length);
610
788
  this.input(bytes, false);
611
789
  }
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
+ view(rows) {
793
+ const term = this.attachment?.term();
794
+ if (!term || term.alternate)
795
+ return;
796
+ if (rows === "live")
797
+ this.live();
798
+ else if (rows !== 0) {
799
+ term.scroll(rows);
800
+ this.paint();
801
+ }
802
+ }
612
803
  /** Back to the live screen before input, as any terminal does. */
613
804
  live() {
614
805
  const term = this.attachment?.term();
@@ -630,18 +821,18 @@ class Client {
630
821
  const term = this.attachment?.term();
631
822
  if (!term)
632
823
  return;
633
- this.input(this.engine.encodePaste(text, term.mode(2004)), true);
824
+ this.input(this.hub.engine.encodePaste(text, term.mode(2004)), true);
634
825
  }
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. */
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. */
639
830
  setViewport(size, profile, active) {
640
831
  this.viewport = size;
641
832
  this.profile = profile;
642
833
  this.active = active;
643
834
  const attachment = this.attachment;
644
- if (!this.conn || !attachment || attachment.ended())
835
+ if (!this.hub.conn || !attachment || attachment.ended())
645
836
  return;
646
837
  this.applyProfile(attachment.term());
647
838
  this.paint();
@@ -651,7 +842,7 @@ class Client {
651
842
  report() {
652
843
  this.reclaim = false;
653
844
  try {
654
- this.conn?.sendJson(FrameType.Viewport, this.channel, { ...this.viewport, profile: this.profile });
845
+ this.hub.conn?.sendJson(FrameType.Viewport, this.channel, { ...this.viewport, profile: this.profile });
655
846
  }
656
847
  catch {
657
848
  // Reported through onEnd.
@@ -662,6 +853,35 @@ class Client {
662
853
  if (this.reclaim && this.active && this.attachment && !this.attachment.ended())
663
854
  this.report();
664
855
  }
856
+ focus(focused) {
857
+ this.focused = focused;
858
+ this.recheck();
859
+ }
860
+ /** Looks at this terminal's session again, as `changed` does. */
861
+ recheck() {
862
+ const session = this.session === undefined ? undefined : this.hub.session(this.session);
863
+ if (session)
864
+ this.changed(session);
865
+ }
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
+ changed(session) {
870
+ if (!this.ackOnFocus || !this.focused || this.acking || session.id !== this.session)
871
+ return;
872
+ if (!this.attachment?.term() || !ACKED.has(session.attention?.state ?? ""))
873
+ return;
874
+ const conn = this.hub.live();
875
+ if (!conn)
876
+ 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
+ this.acking = true;
880
+ conn.call("ack", { session: session.id }).then(() => {
881
+ this.acking = false;
882
+ this.recheck();
883
+ }, () => (this.acking = false));
884
+ }
665
885
  }
666
886
  /** The reason an error code ends the link with. */
667
887
  function linkEnd(code) {
@@ -670,46 +890,69 @@ function linkEnd(code) {
670
890
  function describe(exit) {
671
891
  return "code" in exit ? `code ${exit.code}` : `signal ${exit.signal}`;
672
892
  }
673
- /** Serves a page's `mountTerminal` on `port`: the worker module the page
674
- * starts calls `runWorker(self)`. */
893
+ /** Serves a page's `connect` on `port`: the worker module the page starts
894
+ * calls `runWorker(self)`. */
675
895
  export function runWorker(port) {
676
- const client = new Client((message) => port.postMessage(message));
896
+ const hub = new Hub((message) => port.postMessage(message));
677
897
  port.onmessage = (e) => {
678
898
  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;
919
+ }
920
+ const mount = hub.mounts.get(message.mount);
921
+ if (!mount)
922
+ return;
679
923
  switch (message.type) {
680
- case "init":
681
- void client.init(message);
682
- break;
683
924
  case "attach":
684
- client.attach(message.session);
925
+ mount.attach(message.session);
685
926
  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);
927
+ case "detach":
928
+ mount.detach();
692
929
  break;
693
930
  case "key":
694
- client.key(message.input);
931
+ mount.key(message.input);
695
932
  break;
696
933
  case "paste":
697
- client.paste(message.text);
934
+ mount.paste(message.text);
698
935
  break;
699
936
  case "text":
700
- client.text(message.text);
937
+ mount.text(message.text);
701
938
  break;
702
939
  case "select":
703
- client.select(message.action, message.at, message.time);
940
+ mount.select(message.action, message.at, message.time, message.action === "release" ? message.copy : undefined);
941
+ break;
942
+ case "wheel":
943
+ mount.wheel(message.rows);
704
944
  break;
705
- case "scroll":
706
- client.scroll(message.rows);
945
+ case "view":
946
+ mount.view(message.rows);
707
947
  break;
708
948
  case "viewport":
709
- client.setViewport(message.size, message.profile, message.active);
949
+ mount.setViewport(message.size, message.profile, message.active);
950
+ break;
951
+ case "focus":
952
+ mount.focus(message.focused);
710
953
  break;
711
954
  case "repaint":
712
- client.repaint();
955
+ mount.repaint();
713
956
  break;
714
957
  }
715
958
  };