@decentnetwork/beagle 0.1.132 → 0.1.142

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.
@@ -13,20 +13,37 @@ import { EventEmitter } from "node:events";
13
13
  import { existsSync } from "node:fs";
14
14
  import { mkdir, readFile, writeFile, unlink } from "node:fs/promises";
15
15
  import { basename, resolve } from "node:path";
16
+ import { createHash } from "node:crypto";
16
17
  import { CarrierNode } from "./carrier-node.js";
17
18
  import { MessageStore } from "./message-store.js";
18
- import { parseGroupFile, withoutFileData } from "./group-file.js";
19
+ import { parseGroupFile, storedGroupFiles, withoutFileData } from "./group-file.js";
19
20
  import { FriendMetaStore } from "./friend-meta.js";
20
21
  import { Logger } from "./logger.js";
21
22
  import { acquireIdentityLock } from "./identity-lock.js";
22
23
  import { refreshPendingAvatars, requesterAvatar } from "./pending-requests.js";
23
- /** Files bigger than this are not queued for an offline friend — the bytes sit
24
- * on disk until they reconnect, and an unbounded queue is how you fill a
25
- * user's disk by accident. Live transfers have no such limit. */
26
- const OUTBOX_MAX_FILE_BYTES = 25 * 1024 * 1024;
24
+ import { OFFER_WINDOW_MS, routeFileSend } from "./file-route.js";
27
25
  /** Inline envelope ceiling for a JS peer: base64 (~1.34x) inside a 16MB
28
26
  * bulkmsg cap. */
29
27
  const INLINE_MAX_BYTES = 11 * 1024 * 1024;
28
+ /** Re-offer backoff for a queued file whose live delivery the SDK gave up on
29
+ * (#liveDeliveryGaveUp): 15 s, 30 s, 1 min… capped at 5 min. */
30
+ const LIVE_RETRY_BASE_MS = 15_000;
31
+ const LIVE_RETRY_MAX_MS = 5 * 60_000;
32
+ /** What a sending-side `file-cancel` means (peer's `onFileCancel` reasons):
33
+ * none = the friend's KILL, they declined it → "cancelled"; "local" = our own
34
+ * cancelSend, the caller sets the row; anything else ("no-response",
35
+ * "timeout", "peer-offline", or a reason a later peer adds) = the SDK gave up
36
+ * on the path → the file is still owed (#liveDeliveryGaveUp). */
37
+ export function liveCancelMeaning(reason) {
38
+ if (!reason)
39
+ return "declined";
40
+ if (reason === "local")
41
+ return "ours";
42
+ return "gave-up";
43
+ }
44
+ /** A live send with no progress event for this long counts as a give-up
45
+ * (#giveUpStalledSends) — same rule as lan 0.1.325 (LIVE_STALL_MS). */
46
+ const LIVE_STALL_MS = 90_000;
30
47
  /** Native (iOS/Android) peers get NO inline shortcut at any size — they
31
48
  * stream via sendFile → DNFT1 (peer >= 0.1.141) like everyone else, because
32
49
  * the inline envelope has no usable confirmation against a native peer:
@@ -54,7 +71,7 @@ function sanitizeFileName(name) {
54
71
  export class EmbeddedHost {
55
72
  kind = "embedded";
56
73
  hasVirtualLan = false;
57
- #node = new CarrierNode();
74
+ #node;
58
75
  #messages;
59
76
  #meta;
60
77
  #logger = new Logger({ prefix: "Beagle" });
@@ -83,11 +100,25 @@ export class EmbeddedHost {
83
100
  #callWaiters = [];
84
101
  /** fileId -> which chat message it belongs to, so progress can patch it. */
85
102
  #activeSends = new Map();
103
+ /** Checks live sends for LIVE_STALL_MS without progress (#giveUpStalledSends). */
104
+ #stallTimer = null;
105
+ /** fileId -> the offer-window timer of a live send that may still fall back
106
+ * to Express (iOS `offerWindow`, file-route.ts). Cleared on the first sign
107
+ * the friend accepted (an ack = file-progress), on complete and on cancel. */
108
+ #offerWindows = new Map();
109
+ /** `<peer>:<sha256>` of inbound files being saved right now, so two
110
+ * deliveries of the same bytes arriving together still make one row. */
111
+ #savingInbound = new Set();
112
+ /** msgId -> when a queued file whose live delivery the SDK gave up on may be
113
+ * offered again (#liveDeliveryGaveUp). Backs off per file; the friend
114
+ * reconnecting clears it. In memory: a restart retries at once. */
115
+ #retryBackoff = new Map();
86
116
  #autoAccept;
87
117
  /** Released when this peer stops, so the daemon may take the identity. */
88
118
  #releaseIdentity = null;
89
119
  constructor(opts) {
90
120
  this.#opts = opts;
121
+ this.#node = opts.node ?? new CarrierNode();
91
122
  this.#autoAccept = opts.autoAcceptFriends;
92
123
  this.#messages = new MessageStore(resolve(opts.configDir, "messages.json"));
93
124
  this.#meta = new FriendMetaStore(resolve(opts.configDir, "friends-meta.json"));
@@ -129,6 +160,7 @@ export class EmbeddedHost {
129
160
  // checks this same file, so holding it is what stops `agentnet up` from
130
161
  // starting a second peer on our keypair while we are live.
131
162
  this.#releaseIdentity = acquireIdentityLock(this.#opts.dataDir);
163
+ void this.#migrateStoredGroupFiles();
132
164
  try {
133
165
  await this.#startPeer();
134
166
  }
@@ -179,6 +211,9 @@ export class EmbeddedHost {
179
211
  })();
180
212
  }, 8000);
181
213
  this.#sweepTimer.unref?.();
214
+ const stallMs = this.#opts.liveStallMs ?? LIVE_STALL_MS;
215
+ this.#stallTimer = setInterval(() => this.#giveUpStalledSends(Date.now()), Math.min(8000, Math.max(20, stallMs / 4)));
216
+ this.#stallTimer.unref?.();
182
217
  }
183
218
  #sweeping = false;
184
219
  /** A session that can actually carry traffic right now. */
@@ -254,8 +289,13 @@ export class EmbeddedHost {
254
289
  // sat visibly stuck despite the peer being online. One delayed retry
255
290
  // covers that gap; the per-send chain and later reconnects cover the
256
291
  // rest.
257
- if (e.status === "connected")
258
- void this.#chainFlush(e.pubkey); // fast path
292
+ if (e.status === "connected") {
293
+ // A fresh session is a fresh chance: offer backed-off files now.
294
+ for (const b of this.#retryBackoff.values())
295
+ if (b.peer === e.pubkey)
296
+ b.notBefore = 0;
297
+ void this.#chainFlush(e.pubkey);
298
+ } // fast path
259
299
  });
260
300
  this.#node.on("call-signal", (evt) => {
261
301
  this.#callLog.push({
@@ -270,9 +310,11 @@ export class EmbeddedHost {
270
310
  for (const w of waiters)
271
311
  w();
272
312
  });
273
- // Inline files (the path native iOS/Android peers use).
313
+ // Inline files: the path native iOS/Android peers use online, and (peer
314
+ // >= 0.1.176) an offline file message pulled from Express — `via`
315
+ // "offline", `fileId` = SHA-256 of the bytes. Stored once per bytes.
274
316
  this.#node.on("inline-file", (f) => {
275
- void this.#saveIncoming(f.pubkey, f.name, Buffer.from(f.data));
317
+ void this.#saveIncoming(f.pubkey, f.name, Buffer.from(f.data), { via: f.via, sha256: f.fileId });
276
318
  });
277
319
  // toxcore file transfer. The daemon logs an incoming file once, on
278
320
  // completion — no "receiving" chip — and MessageStore's status enum has no
@@ -291,17 +333,23 @@ export class EmbeddedHost {
291
333
  // `sending` is authoritative for direction — no map scanning needed.
292
334
  if (!p.sending)
293
335
  return;
336
+ // An ack means the friend accepted: no Express fallback for this one.
337
+ this.#endOfferWindow(p.fileId);
294
338
  const s = this.#activeSends.get(p.fileId);
295
- if (s)
296
- this.#messages.patchFile(s.peer, s.msgId, { sent: p.received });
339
+ if (!s)
340
+ return;
341
+ s.lastMs = Date.now();
342
+ this.#messages.patchFile(s.peer, s.msgId, { sent: p.received });
297
343
  });
298
344
  this.#node.on("file-complete", (p) => {
299
345
  if (p.sending) {
346
+ this.#endOfferWindow(p.fileId);
300
347
  const s = this.#activeSends.get(p.fileId);
301
348
  if (!s)
302
349
  return;
303
350
  this.#messages.patchFile(s.peer, s.msgId, { status: "sent", sent: p.size });
304
351
  this.#activeSends.delete(p.fileId);
352
+ this.#retryBackoff.delete(s.msgId);
305
353
  void unlink(resolve(this.outboxDir, s.msgId)).catch(() => undefined);
306
354
  this.#events.emit("event", { type: "chat", userid: s.peer, dir: "out" });
307
355
  return;
@@ -313,11 +361,30 @@ export class EmbeddedHost {
313
361
  this.#node.on("file-cancel", (p) => {
314
362
  if (!p.sending)
315
363
  return;
364
+ this.#endOfferWindow(p.fileId);
316
365
  const s = this.#activeSends.get(p.fileId);
317
366
  if (!s)
318
367
  return;
319
- this.#messages.patchFile(s.peer, s.msgId, { status: "cancelled" });
368
+ const meaning = liveCancelMeaning(p.reason);
369
+ // Our own cancelSend: whoever called it sets the row (they forget the
370
+ // send first, so this is only a stray). Left tracked, so the 90 s
371
+ // no-progress backstop still settles it.
372
+ if (meaning === "ours")
373
+ return;
320
374
  this.#activeSends.delete(p.fileId);
375
+ // The SDK ending a send itself — no answer to the offer ("no-response"),
376
+ // no ack progress ("timeout"), the friend's session gone
377
+ // ("peer-offline", peer >= 0.1.178), or any reason it adds later — is the
378
+ // PATH failing, not anyone cancelling. The file is still owed: Express
379
+ // if it fits, else back to the outbox and offered again when they are
380
+ // back. Never "cancelled".
381
+ if (meaning === "gave-up") {
382
+ void this.#liveDeliveryGaveUp(s.peer, s.msgId, p.reason);
383
+ return;
384
+ }
385
+ // No reason: the friend's KILL — they declined it.
386
+ this.#messages.patchFile(s.peer, s.msgId, { status: "cancelled" });
387
+ this.#events.emit("event", { type: "chat", userid: s.peer, dir: "out" });
321
388
  });
322
389
  }
323
390
  /** A group file that came with its bytes: downloads/<name> (a different
@@ -328,17 +395,7 @@ export class EmbeddedHost {
328
395
  try {
329
396
  if (f.sha256 && this.#messages.hasFileSha(pubkey, f.sha256))
330
397
  return;
331
- await mkdir(this.downloadsDir, { recursive: true });
332
- const safe = sanitizeFileName(f.name);
333
- const dot = safe.lastIndexOf(".");
334
- let name = safe;
335
- for (let i = 2; i < 1000; i++) {
336
- const existing = await readFile(resolve(this.downloadsDir, name)).catch(() => undefined);
337
- if (!existing || existing.equals(f.data))
338
- break;
339
- name = dot > 0 ? `${safe.slice(0, dot)}-${i}${safe.slice(dot)}` : `${safe}-${i}`;
340
- }
341
- await writeFile(resolve(this.downloadsDir, name), f.data);
398
+ const name = await this.#writeGroupDownload(f);
342
399
  this.#messages.appendFile(pubkey, "in", { name, size: f.data.length, sha256: f.sha256 }, Date.now(), { origin: { userid: f.origin.userid, nickname: f.origin.nickname }, via });
343
400
  this.#logger.info(`saved group file "${name}" (${f.data.length}B) from ${f.origin.nickname || "member"} in ${pubkey.slice(0, 8)}`);
344
401
  }
@@ -349,20 +406,84 @@ export class EmbeddedHost {
349
406
  this.#meta.ensure(pubkey);
350
407
  this.#events.emit("event", { type: "chat", userid: pubkey, dir: "in" });
351
408
  }
352
- /** Persist a received file under downloads/ and log it in the thread. */
353
- async #saveIncoming(pubkey, name, data) {
354
- const safe = sanitizeFileName(name);
409
+ /** downloads/<name> ← a group file's bytes; a different file of the same
410
+ * name gets "-2", "-3"… Returns the name used. */
411
+ async #writeGroupDownload(f) {
412
+ return this.#writeDownload(f.name, f.data);
413
+ }
414
+ /** downloads/<name> ← bytes, never over a DIFFERENT file of the same name:
415
+ * that one keeps its name and these get "-2", "-3"… Returns the name used. */
416
+ async #writeDownload(fileName, data) {
417
+ await mkdir(this.downloadsDir, { recursive: true });
418
+ const safe = sanitizeFileName(fileName);
419
+ const dot = safe.lastIndexOf(".");
420
+ let name = safe;
421
+ for (let i = 2; i < 1000; i++) {
422
+ const existing = await readFile(resolve(this.downloadsDir, name)).catch(() => undefined);
423
+ if (!existing || existing.equals(data))
424
+ break;
425
+ name = dot > 0 ? `${safe.slice(0, dot)}-${i}${safe.slice(dot)}` : `${safe}-${i}`;
426
+ }
427
+ await writeFile(resolve(this.downloadsDir, name), data);
428
+ return name;
429
+ }
430
+ /** On start: group files a host older than beagle 0.1.131 stored as CGP1
431
+ * text with their bytes inside become playable files in place (and
432
+ * messages.json loses the base64); a copy of bytes already saved is
433
+ * dropped. A no-op once nothing is left. */
434
+ async #migrateStoredGroupFiles() {
435
+ let saved = 0;
436
+ let dropped = 0;
437
+ for (const peer of [...this.#messages.lastMessages().keys()]) {
438
+ const todo = storedGroupFiles(this.#messages.thread(peer));
439
+ for (const p of todo) {
440
+ try {
441
+ if (p.duplicate) {
442
+ this.#messages.deleteMessages(peer, [p.id]);
443
+ dropped++;
444
+ continue;
445
+ }
446
+ const name = await this.#writeGroupDownload(p.file);
447
+ this.#messages.convertToFile(peer, p.id, { name, size: p.file.data.length, sha256: p.file.sha256 }, { userid: p.file.origin.userid, nickname: p.file.origin.nickname });
448
+ saved++;
449
+ }
450
+ catch (e) {
451
+ this.#logger.warn(`stored group file "${p.file.name}" not converted: ${e.message}`);
452
+ }
453
+ }
454
+ if (todo.length)
455
+ this.#events.emit("event", { type: "chat", userid: peer, dir: "in" });
456
+ }
457
+ if (saved || dropped)
458
+ this.#logger.info(`stored group files: ${saved} saved as files, ${dropped} duplicates dropped`);
459
+ }
460
+ /** Persist a received file under downloads/ and log it in the thread.
461
+ *
462
+ * Once per bytes (iOS OFFLINE-FILE-MESSAGE.md, "Identity and dedup": the
463
+ * row id is `ft-` + SHA-256): Express re-delivering an offline file on
464
+ * reconnect, or a file that came live AND through the 10 s Express
465
+ * fallback, makes one row. Received rows carry `sha256` from now on. */
466
+ async #saveIncoming(pubkey, name, data, opts = {}) {
467
+ const sha256 = (opts.sha256 || createHash("sha256").update(data).digest("hex")).toLowerCase();
468
+ const key = `${pubkey}:${sha256}`;
469
+ if (this.#savingInbound.has(key) || this.#messages.hasFileSha(pubkey, sha256, "in")) {
470
+ this.#logger.info(`"${name}" from ${pubkey.slice(0, 8)} already received (ft-${sha256.slice(0, 16)}) — not stored twice`);
471
+ return;
472
+ }
473
+ this.#savingInbound.add(key);
355
474
  try {
356
- await mkdir(this.downloadsDir, { recursive: true });
357
- await writeFile(resolve(this.downloadsDir, safe), data);
358
- this.#messages.appendFile(pubkey, "in", { name: safe, size: data.length });
475
+ const saved = await this.#writeDownload(name, data);
476
+ this.#messages.appendFile(pubkey, "in", { name: saved, size: data.length, sha256 }, Date.now(), { via: opts.via });
359
477
  this.#meta.ensure(pubkey);
360
478
  this.#events.emit("event", { type: "chat", userid: pubkey, dir: "in" });
361
- this.#logger.info(`saved "${safe}" (${data.length}B) from ${pubkey.slice(0, 8)}`);
479
+ this.#logger.info(`saved "${saved}" (${data.length}B) from ${pubkey.slice(0, 8)}${opts.via === "offline" ? " (offline, via Express)" : ""}`);
362
480
  }
363
481
  catch (e) {
364
482
  this.#logger.warn(`could not save incoming file: ${e.message}`);
365
483
  }
484
+ finally {
485
+ this.#savingInbound.delete(key);
486
+ }
366
487
  }
367
488
  /** Deliver anything queued while this friend was offline. */
368
489
  async #flushOutbox(pubkey) {
@@ -387,15 +508,29 @@ export class EmbeddedHost {
387
508
  continue;
388
509
  }
389
510
  const path = resolve(this.outboxDir, msg.id);
390
- if (!existsSync(path))
511
+ if (!existsSync(path)) {
512
+ // Nothing left to deliver: say so instead of "waits here" forever.
513
+ this.#messages.patchFile(pubkey, msg.id, { status: "failed" });
514
+ this.#events.emit("event", { type: "chat", userid: pubkey, dir: "out" });
515
+ continue;
516
+ }
517
+ const backoff = this.#retryBackoff.get(msg.id);
518
+ if (backoff && backoff.notBefore > Date.now())
391
519
  continue;
392
520
  try {
393
521
  const data = await readFile(path);
394
522
  const fileId = this.#node.sendFile(pubkey, new Uint8Array(data), msg.file.name);
395
523
  if (fileId) {
396
524
  this.#messages.patchFile(pubkey, msg.id, { status: "sending", sent: 0 });
397
- this.#activeSends.set(fileId, { peer: pubkey, msgId: msg.id });
398
- this.#logger.info(`delivering queued "${msg.file.name}" to ${pubkey.slice(0, 8)}`);
525
+ this.#activeSends.set(fileId, { peer: pubkey, msgId: msg.id, lastMs: Date.now() });
526
+ // Same rule as a fresh send: a file that fits Express falls back
527
+ // there if the friend does not accept within the offer window.
528
+ const route = routeFileSend({ online: true, name: msg.file.name, size: data.length, expressAvailable: this.#node.canSendFileViaExpress() });
529
+ if (route.kind === "live" && route.offerWindow)
530
+ this.#startOfferWindow(fileId, pubkey, msg.id, msg.file.name);
531
+ this.#events.emit("event", { type: "chat", userid: pubkey, dir: "out" });
532
+ this.#logger.info(`delivering queued "${msg.file.name}" to ${pubkey.slice(0, 8)}` +
533
+ (backoff ? ` (attempt ${backoff.attempts + 1})` : ""));
399
534
  }
400
535
  }
401
536
  catch (e) {
@@ -423,6 +558,17 @@ export class EmbeddedHost {
423
558
  clearInterval(this.#sweepTimer);
424
559
  this.#sweepTimer = null;
425
560
  }
561
+ if (this.#stallTimer) {
562
+ clearInterval(this.#stallTimer);
563
+ this.#stallTimer = null;
564
+ }
565
+ for (const t of this.#offerWindows.values())
566
+ clearTimeout(t);
567
+ this.#offerWindows.clear();
568
+ this.#retryBackoff.clear();
569
+ // The store writes on a 1 s debounce; a stop inside that window lost the
570
+ // last change (a file's "sending" row, a just-sent message).
571
+ this.#messages.flush();
426
572
  // Stop the peer FIRST, then release the lock. The reverse order would open
427
573
  // a window where a daemon could start while our peer is still live.
428
574
  await this.#node.stop();
@@ -715,6 +861,7 @@ export class EmbeddedHost {
715
861
  for (const [fileId, s] of this.#activeSends) {
716
862
  if (s.msgId !== id)
717
863
  continue;
864
+ this.#endOfferWindow(fileId);
718
865
  if (this.#node.cancelSend(s.peer, fileId))
719
866
  cancelled++;
720
867
  this.#activeSends.delete(fileId);
@@ -730,9 +877,12 @@ export class EmbeddedHost {
730
877
  if (!existsSync(path))
731
878
  continue;
732
879
  const data = await readFile(path);
733
- const fileId = this.#node.sendFile(req.peer, new Uint8Array(data), `retry-${id}`);
880
+ // The row's own name — the friend should not receive "retry-<id>".
881
+ const row = (this.#messages.history(req.peer)[req.peer] ?? []).find((m) => m.id === id);
882
+ const fileId = this.#node.sendFile(req.peer, new Uint8Array(data), row?.file?.name ?? `retry-${id}`);
734
883
  if (fileId) {
735
- this.#activeSends.set(fileId, { peer: req.peer, msgId: id });
884
+ this.#activeSends.set(fileId, { peer: req.peer, msgId: id, lastMs: Date.now() });
885
+ this.#retryBackoff.delete(id);
736
886
  this.#messages.patchFile(req.peer, id, { status: "sending", sent: 0 });
737
887
  retried++;
738
888
  }
@@ -801,29 +951,56 @@ export class EmbeddedHost {
801
951
  }
802
952
  })();
803
953
  }
804
- if (!this.#node.isFriendOnline(userid)) {
805
- if (data.length > OUTBOX_MAX_FILE_BYTES) {
806
- throw new Error(`Peer is offline — queued files are limited to ${(OUTBOX_MAX_FILE_BYTES / 1024 / 1024) | 0} MB ` +
807
- `(this is ${(data.length / 1024 / 1024).toFixed(1)} MB). Send it once they're online.`);
808
- }
809
- const msg = this.#messages.appendFile(userid, "out", { name: safe, size: data.length, status: "queued", sent: 0 });
954
+ // The row carries the SHA-256 of the bytes: iOS keys a file row as
955
+ // `ft-` + its first 16 hex chars, and so does Express re-delivery.
956
+ const sha256 = createHash("sha256").update(data).digest("hex");
957
+ const route = routeFileSend({
958
+ online: this.#node.isFriendOnline(userid),
959
+ name: safe,
960
+ size: data.length,
961
+ expressAvailable: this.#node.canSendFileViaExpress(),
962
+ });
963
+ if (route.kind === "refuse")
964
+ throw new Error(route.reason);
965
+ if (route.kind === "express" || route.kind === "outbox") {
966
+ // Offline friend. Either way the bytes are kept in outbox/<id> first:
967
+ // for Express until the post succeeded (a failed post leaves the row
968
+ // queued here), for the outbox until the friend is online.
969
+ const express = route.kind === "express";
970
+ const msg = this.#messages.appendFile(userid, "out", {
971
+ name: safe, size: data.length, status: express ? "sending" : "queued", sent: 0, sha256,
972
+ });
810
973
  if (!msg)
811
974
  throw new Error("Could not queue file");
812
975
  await mkdir(this.outboxDir, { recursive: true });
813
976
  await writeFile(resolve(this.outboxDir, msg.id), data);
814
977
  this.#meta.ensure(userid);
815
978
  this.#events.emit("event", { type: "chat", userid, dir: "out" });
816
- return { queued: true, name: safe, size: data.length };
979
+ if (!express) {
980
+ this.#logger.info(`"${safe}" (${data.length}B) waits in the outbox until ${userid.slice(0, 8)} is online`);
981
+ return { queued: true, name: safe, size: data.length };
982
+ }
983
+ // Non-blocking, like every send: the post is up to 5 MiB to Express.
984
+ void this.#parkOnExpress(userid, msg.id, data, safe, "friend offline");
985
+ return { offline: true, pending: true, name: safe, size: data.length };
817
986
  }
818
987
  // Everyone streams — a native friend's packets ride DNFT1 frames inside
819
988
  // friend messages (see the note on the deleted native inline gate above).
820
989
  const native = this.#node.isNativeFriend(userid);
821
- const msg = this.#messages.appendFile(userid, "out", { name: safe, size: data.length, status: "sending", sent: 0 });
990
+ const msg = this.#messages.appendFile(userid, "out", { name: safe, size: data.length, status: "sending", sent: 0, sha256 });
822
991
  if (!msg)
823
992
  throw new Error("Could not create file message");
824
993
  await mkdir(this.outboxDir, { recursive: true });
825
994
  await writeFile(resolve(this.outboxDir, msg.id), data);
826
995
  const fileId = this.#node.sendFile(userid, new Uint8Array(data), safe);
996
+ if (!fileId && route.offerWindow) {
997
+ // No transfer slot, but it fits Express: park it there, as the offer
998
+ // window would after 10 s anyway.
999
+ this.#meta.ensure(userid);
1000
+ this.#events.emit("event", { type: "chat", userid, dir: "out" });
1001
+ void this.#parkOnExpress(userid, msg.id, data, safe, "no free transfer slot");
1002
+ return { offline: true, pending: true, name: safe, size: data.length };
1003
+ }
827
1004
  if (!fileId) {
828
1005
  // No transfer slot. The inline fallback only helps a JS friend (their
829
1006
  // text-ack makes it confirmable); to a native it is unconfirmable by
@@ -862,10 +1039,135 @@ export class EmbeddedHost {
862
1039
  })();
863
1040
  return { inline: true, name: safe, size: data.length, pending: true };
864
1041
  }
865
- this.#activeSends.set(fileId, { peer: userid, msgId: msg.id });
1042
+ this.#activeSends.set(fileId, { peer: userid, msgId: msg.id, lastMs: Date.now() });
1043
+ if (route.offerWindow)
1044
+ this.#startOfferWindow(fileId, userid, msg.id, safe);
866
1045
  this.#meta.ensure(userid);
867
1046
  this.#events.emit("event", { type: "chat", userid, dir: "out" });
868
1047
  return { fileId, name: safe, size: data.length };
869
1048
  }
1049
+ /** The SDK gave up on a live send: no answer to the offer, or no ack
1050
+ * progress, for 60 s (a half-open session: we see the friend online but
1051
+ * nothing gets through). Never a total-time limit — a slow transfer that
1052
+ * keeps acking runs as long as it needs. The bytes are still in
1053
+ * outbox/<id>: a file that fits Express goes there, anything else waits
1054
+ * "queued" and is offered again, backing off 15 s, 30 s, 1 min… up to
1055
+ * 5 min, and at once when the friend reconnects. The receiver resumes
1056
+ * from what it already holds (same fileId = same bytes). */
1057
+ async #liveDeliveryGaveUp(peer, msgId, reason) {
1058
+ const data = await readFile(resolve(this.outboxDir, msgId)).catch(() => undefined);
1059
+ const msg = (this.#messages.history(peer)[peer] ?? []).find((m) => m.id === msgId);
1060
+ const name = msg?.file?.name ?? msgId;
1061
+ const why = reason === "no-response" ? "no answer to the offer for 60 s" :
1062
+ reason === "timeout" ? "no progress for 60 s" :
1063
+ reason === "peer-offline" ? "their session went away" :
1064
+ reason === "stalled" ? `no progress for ${Math.round((this.#opts.liveStallMs ?? LIVE_STALL_MS) / 1000)} s` :
1065
+ `ended by the SDK: ${reason}`;
1066
+ if (!data) {
1067
+ this.#messages.patchFile(peer, msgId, { status: "failed" });
1068
+ this.#events.emit("event", { type: "chat", userid: peer, dir: "out" });
1069
+ this.#logger.warn(`live delivery of "${name}" to ${peer.slice(0, 8)} gave up (${why}) and its bytes are gone`);
1070
+ return;
1071
+ }
1072
+ const route = routeFileSend({ online: false, name, size: data.length, expressAvailable: this.#node.canSendFileViaExpress() });
1073
+ if (route.kind === "express") {
1074
+ this.#messages.patchFile(peer, msgId, { status: "sending", sent: 0 });
1075
+ this.#events.emit("event", { type: "chat", userid: peer, dir: "out" });
1076
+ if (await this.#parkOnExpress(peer, msgId, data, name, `live delivery gave up: ${why}`))
1077
+ return;
1078
+ }
1079
+ const prev = this.#retryBackoff.get(msgId);
1080
+ const attempts = (prev?.attempts ?? 0) + 1;
1081
+ const delay = Math.min(LIVE_RETRY_MAX_MS, (this.#opts.liveRetryBaseMs ?? LIVE_RETRY_BASE_MS) * 2 ** (attempts - 1));
1082
+ this.#retryBackoff.set(msgId, { peer, attempts, notBefore: Date.now() + delay });
1083
+ this.#messages.patchFile(peer, msgId, { status: "queued", sent: 0 });
1084
+ this.#events.emit("event", { type: "chat", userid: peer, dir: "out" });
1085
+ this.#logger.warn(`live delivery of "${name}" to ${peer.slice(0, 8)} gave up (${why}) — queued, next try in ${Math.round(delay / 1000)} s`);
1086
+ }
1087
+ /** Live sends with no progress for LIVE_STALL_MS: withdrawn and handled as a
1088
+ * give-up (#liveDeliveryGaveUp). Backstop for peer's own no-progress
1089
+ * give-up ("timeout"), which never fires in peer 0.1.176 — every stall
1090
+ * resets its clock — so a receiver frozen mid-transfer left the row
1091
+ * "sending" forever. 90 s, so peer's 60 s timer wins once it is fixed
1092
+ * (0.1.177). The offer phase counts from the offer; peer's working 60 s
1093
+ * "no-response" give-up normally ends it first. The receiver keeps its
1094
+ * .part (a KILL does not delete it), so the next offer resumes. */
1095
+ #giveUpStalledSends(now) {
1096
+ const stallMs = this.#opts.liveStallMs ?? LIVE_STALL_MS;
1097
+ for (const [fileId, s] of [...this.#activeSends]) {
1098
+ if (now - s.lastMs < stallMs)
1099
+ continue;
1100
+ // Forget it first, so our own KILL is not read as anything else.
1101
+ this.#activeSends.delete(fileId);
1102
+ this.#endOfferWindow(fileId);
1103
+ try {
1104
+ this.#node.cancelSend(s.peer, fileId);
1105
+ }
1106
+ catch { /* already gone */ }
1107
+ void this.#liveDeliveryGaveUp(s.peer, s.msgId, "stalled");
1108
+ }
1109
+ }
1110
+ /** Post one offline file message to Express (peer >= 0.1.176). The row goes
1111
+ * "sent" + via "offline": stored on Express, theirs when they come online.
1112
+ * If Express refuses or cannot be reached, the bytes stay in outbox/<id>
1113
+ * and the row goes "queued": delivered live when the friend is next online
1114
+ * (#flushOutbox). Never re-flushes from here — a friend who is "online"
1115
+ * but not accepting would otherwise bounce between the two forever. */
1116
+ async #parkOnExpress(userid, msgId, data, name, why) {
1117
+ try {
1118
+ const { fileId } = await this.#node.sendFileViaExpress(userid, new Uint8Array(data), name);
1119
+ this.#messages.patchFile(userid, msgId, { status: "sent", sent: data.length });
1120
+ this.#messages.setFileVia(userid, msgId, "offline");
1121
+ void unlink(resolve(this.outboxDir, msgId)).catch(() => undefined);
1122
+ this.#logger.info(`"${name}" (${data.length}B) parked on Express for ${userid.slice(0, 8)} (${why}; ft-${fileId.slice(0, 16)})`);
1123
+ this.#events.emit("event", { type: "chat", userid, dir: "out" });
1124
+ return true;
1125
+ }
1126
+ catch (e) {
1127
+ this.#messages.patchFile(userid, msgId, { status: "queued", sent: 0 });
1128
+ this.#messages.setFileVia(userid, msgId, undefined);
1129
+ this.#logger.warn(`"${name}" could not go to Express (${e.message}) — it waits here until ${userid.slice(0, 8)} is online`);
1130
+ this.#events.emit("event", { type: "chat", userid, dir: "out" });
1131
+ return false;
1132
+ }
1133
+ }
1134
+ /** iOS `offerWindow`: a live offer of a file that fits Express gets
1135
+ * OFFER_WINDOW_MS to be accepted. */
1136
+ #startOfferWindow(fileId, peer, msgId, name) {
1137
+ this.#endOfferWindow(fileId);
1138
+ const t = setTimeout(() => void this.#offerWindowExpired(fileId, peer, msgId, name), this.#opts.offerWindowMs ?? OFFER_WINDOW_MS);
1139
+ t.unref?.();
1140
+ this.#offerWindows.set(fileId, t);
1141
+ }
1142
+ #endOfferWindow(fileId) {
1143
+ const t = this.#offerWindows.get(fileId);
1144
+ if (t)
1145
+ clearTimeout(t);
1146
+ this.#offerWindows.delete(fileId);
1147
+ }
1148
+ /** Not accepted in time: withdraw the offer (KILL) and park the file on
1149
+ * Express. The receiver keys both by the bytes' SHA-256, so a late ACCEPT
1150
+ * racing this still ends in one row on their side. */
1151
+ async #offerWindowExpired(fileId, peer, msgId, name) {
1152
+ this.#offerWindows.delete(fileId);
1153
+ if (!this.#activeSends.has(fileId))
1154
+ return; // finished or cancelled meanwhile
1155
+ // Forget it BEFORE cancelling, so our own KILL is not read as the user
1156
+ // cancelling the transfer.
1157
+ this.#activeSends.delete(fileId);
1158
+ try {
1159
+ this.#node.cancelSend(peer, fileId);
1160
+ }
1161
+ catch { /* already gone */ }
1162
+ const data = await readFile(resolve(this.outboxDir, msgId)).catch(() => undefined);
1163
+ if (!data) {
1164
+ this.#messages.patchFile(peer, msgId, { status: "failed" });
1165
+ this.#events.emit("event", { type: "chat", userid: peer, dir: "out" });
1166
+ return;
1167
+ }
1168
+ this.#logger.info(`"${name}" not accepted by ${peer.slice(0, 8)} within ${(this.#opts.offerWindowMs ?? OFFER_WINDOW_MS) / 1000} s — offer withdrawn, sending through Express`);
1169
+ this.#messages.patchFile(peer, msgId, { status: "sending", sent: 0 });
1170
+ await this.#parkOnExpress(peer, msgId, data, name, "offer not accepted in time");
1171
+ }
870
1172
  }
871
1173
  _a = EmbeddedHost;
@@ -0,0 +1,43 @@
1
+ /** Files bigger than this are not queued for an offline friend — the bytes sit
2
+ * on disk until they reconnect, and an unbounded queue is how you fill a
3
+ * user's disk by accident. Live transfers have no such limit. */
4
+ export declare const OUTBOX_MAX_FILE_BYTES: number;
5
+ /** iOS `offerWindow`: how long a live offer may go unaccepted before a file
6
+ * that fits Express is withdrawn and parked there instead. */
7
+ export declare const OFFER_WINDOW_MS = 10000;
8
+ /** The exact size of the offline file message sendFileViaExpress would post
9
+ * for this name and size (the meta JSON is built the same way). */
10
+ export declare function expressMessageBytes(name: string, size: number): {
11
+ total: number;
12
+ meta: number;
13
+ };
14
+ /** True when one offline file message on Express can carry this file. */
15
+ export declare function fitsExpress(name: string, size: number): boolean;
16
+ export type FileRoute =
17
+ /** Live transfer; `offerWindow` = fall back to Express if not accepted in time. */
18
+ {
19
+ kind: "live";
20
+ offerWindow: boolean;
21
+ }
22
+ /** One offline file message on Express. */
23
+ | {
24
+ kind: "express";
25
+ }
26
+ /** Kept in the local outbox until the friend is online. */
27
+ | {
28
+ kind: "outbox";
29
+ }
30
+ /** Offline and over the outbox cap: refused up front. */
31
+ | {
32
+ kind: "refuse";
33
+ reason: string;
34
+ };
35
+ /** The routing table above. `expressAvailable` is false on a peer SDK without
36
+ * sendFileViaExpress or with no Express node: then an offline file of any
37
+ * size waits in the outbox, as it did before. */
38
+ export declare function routeFileSend(opts: {
39
+ online: boolean;
40
+ name: string;
41
+ size: number;
42
+ expressAvailable: boolean;
43
+ }): FileRoute;