@decentnetwork/beagle 0.1.138 → 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.
@@ -5,6 +5,9 @@ export interface InlineFileEvent {
5
5
  fileType?: string;
6
6
  data: Uint8Array;
7
7
  via: "online" | "offline";
8
+ /** peer >= 0.1.176: SHA-256 hex of `data`. The Beagle apps key the row
9
+ * `ft-` + its first 16 chars, so a re-delivery is stored once. */
10
+ fileId?: string;
8
11
  }
9
12
  export interface InviteEvent {
10
13
  pubkey: string;
@@ -41,6 +44,16 @@ export interface FileCancel {
41
44
  friendId: string;
42
45
  fileId: string;
43
46
  sending: boolean;
47
+ /** Set by the SDK when it ended the transfer itself: "no-response" (no
48
+ * answer to the offer for 60 s), "timeout" (no ack progress for 60 s),
49
+ * "peer-offline" (the friend's session went away, peer >= 0.1.178),
50
+ * "local" (our own cancelSend). Absent = the friend sent KILL. */
51
+ reason?: "no-response" | "timeout" | "peer-offline" | "local" | string;
52
+ /** Incoming only (peer >= 0.1.178): how far it got, and whether the prefix
53
+ * is kept for a resumed re-offer. */
54
+ received?: number;
55
+ total?: number;
56
+ resumable?: boolean;
44
57
  }
45
58
  export interface CarrierNodeOptions {
46
59
  keyFile: string;
@@ -122,6 +135,14 @@ export declare class CarrierNode extends EventEmitter {
122
135
  * earns a "sent" checkmark. Older SDKs resolve void: report "accepted"
123
136
  * (bytes out, delivery unproven) rather than inventing a confirmation. */
124
137
  sendInlineFile(userid: string, data: Uint8Array, name: string): Promise<"acked" | "accepted" | "offline">;
138
+ /** Whether this SDK can park a file on Express (peer >= 0.1.176). Whether
139
+ * an Express node answers is only known when the post is tried. */
140
+ canSendFileViaExpress(): boolean;
141
+ /** Park a file on Express for an offline friend. Throws when the SDK cannot,
142
+ * the message is over 5 MiB, there is no Express node, or the post fails. */
143
+ sendFileViaExpress(userid: string, data: Uint8Array, name: string): Promise<{
144
+ fileId: string;
145
+ }>;
125
146
  /** True when the friend is a NATIVE Carrier client (iOS/Android/C): it can
126
147
  * only receive files as the inline envelope — a toxcore sendFile offer is
127
148
  * invisible to it and would hang at "sending" until the 60s give-up. */
@@ -43,7 +43,9 @@ export class CarrierNode extends EventEmitter {
43
43
  compatibilityMode: "legacy",
44
44
  bootstrapNodes: opts.bootstrapNodes,
45
45
  expressNodes: opts.expressNodes,
46
- nickname: opts.nickname,
46
+ // No name set yet: advertise none, not the SDK's default
47
+ // "@decentnetwork/peer" (the phones show that as the friend's name).
48
+ nickname: opts.nickname ?? "",
47
49
  statusMessage: opts.statusMessage,
48
50
  punkId: opts.punkId,
49
51
  fileResumeDir: opts.fileResumeDir,
@@ -227,6 +229,20 @@ export class CarrierNode extends EventEmitter {
227
229
  const r = await peer.sendInlineFile(userid, { name, data });
228
230
  return (r && typeof r === "object" ? r.delivery : undefined) ?? "accepted";
229
231
  }
232
+ /** Whether this SDK can park a file on Express (peer >= 0.1.176). Whether
233
+ * an Express node answers is only known when the post is tried. */
234
+ canSendFileViaExpress() {
235
+ return typeof this.#peer?.sendFileViaExpress === "function";
236
+ }
237
+ /** Park a file on Express for an offline friend. Throws when the SDK cannot,
238
+ * the message is over 5 MiB, there is no Express node, or the post fails. */
239
+ async sendFileViaExpress(userid, data, name) {
240
+ const peer = this.#require();
241
+ if (!peer.sendFileViaExpress)
242
+ throw new Error("This peer SDK build cannot send files through Express (needs >= 0.1.176)");
243
+ const r = await peer.sendFileViaExpress(userid, { name, data });
244
+ return { fileId: r.fileId };
245
+ }
230
246
  /** True when the friend is a NATIVE Carrier client (iOS/Android/C): it can
231
247
  * only receive files as the inline envelope — a toxcore sendFile offer is
232
248
  * invisible to it and would hang at "sending" until the 60s give-up. */
@@ -1,4 +1,4 @@
1
- window.__DK_UI_VERSION="0.1.138";
1
+ window.__DK_UI_VERSION="0.1.142";
2
2
  "use strict";
3
3
  (() => {
4
4
  // packages/beagle-ui/dist/beagle-ui.js
@@ -1879,6 +1879,114 @@ ${lines}`, { assistant: { kind: "adopt", rows: fresh } }));
1879
1879
  function isGreetingItem(m) {
1880
1880
  return !!m && m.kind === GREETING_KIND;
1881
1881
  }
1882
+ var nextId = 1;
1883
+ function createFileSendQueue({ onChange, onFinish } = {}) {
1884
+ let items = [];
1885
+ let running = false;
1886
+ const view = () => items.map(({ file, sender, ...rest }) => ({ ...rest }));
1887
+ const emit = () => {
1888
+ if (onChange)
1889
+ onChange(view());
1890
+ };
1891
+ async function run() {
1892
+ running = true;
1893
+ for (; ; ) {
1894
+ const it = items.find((x) => x.status === "waiting");
1895
+ if (!it)
1896
+ break;
1897
+ it.status = "sending";
1898
+ it.pct = 0;
1899
+ emit();
1900
+ const onProgress = (p) => {
1901
+ if (!p || it.status !== "sending")
1902
+ return;
1903
+ if (p.pct != null)
1904
+ it.pct = p.pct;
1905
+ if (p.sent != null)
1906
+ it.sent = p.sent;
1907
+ if (p.size)
1908
+ it.size = p.size;
1909
+ if (p.kbps != null)
1910
+ it.kbps = p.kbps;
1911
+ emit();
1912
+ };
1913
+ try {
1914
+ const r = await it.sender(it.file, onProgress);
1915
+ if (r && r.ok === false) {
1916
+ it.status = "failed";
1917
+ it.error = r.error && String(r.error) || "send failed";
1918
+ } else {
1919
+ it.status = "sent";
1920
+ it.pct = 100;
1921
+ }
1922
+ } catch (e) {
1923
+ it.status = "failed";
1924
+ it.error = e && e.message || String(e);
1925
+ }
1926
+ emit();
1927
+ }
1928
+ const done = view();
1929
+ items = [];
1930
+ running = false;
1931
+ emit();
1932
+ if (onFinish)
1933
+ onFinish(done);
1934
+ }
1935
+ return {
1936
+ /** Queue every file in `files` (a FileList or an array) for `sender`.
1937
+ * `meta` (`via`, `peerId`) rides on each item for the UI. The FileList
1938
+ * is copied now: the caller clears its <input> right after. */
1939
+ add(files, sender, meta = {}) {
1940
+ const list = Array.from(files || []).filter(Boolean);
1941
+ if (!list.length || typeof sender !== "function")
1942
+ return 0;
1943
+ for (const file of list) {
1944
+ items.push({
1945
+ id: nextId++,
1946
+ name: file.name || "file",
1947
+ size: file.size || 0,
1948
+ sent: 0,
1949
+ pct: null,
1950
+ kbps: null,
1951
+ status: "waiting",
1952
+ error: null,
1953
+ via: meta.via,
1954
+ peerId: meta.peerId,
1955
+ file,
1956
+ sender
1957
+ });
1958
+ }
1959
+ emit();
1960
+ if (!running)
1961
+ run();
1962
+ return list.length;
1963
+ },
1964
+ get running() {
1965
+ return running;
1966
+ },
1967
+ get items() {
1968
+ return view();
1969
+ }
1970
+ };
1971
+ }
1972
+ function failureReport(done, lang) {
1973
+ const failed = (done || []).filter((x) => x.status === "failed");
1974
+ if (!failed.length)
1975
+ return null;
1976
+ const zh = lang === "zh";
1977
+ if (done.length === 1)
1978
+ return (zh ? "\u53D1\u9001\u5931\u8D25: " : "Send failed: ") + (failed[0].error || "");
1979
+ const head = zh ? `${done.length} \u4E2A\u6587\u4EF6\u4E2D\u6709 ${failed.length} \u4E2A\u6CA1\u6709\u53D1\u9001:` : `${failed.length} of ${done.length} files did not send:`;
1980
+ return head + "\n\n" + failed.map((x) => `\u2022 ${x.name} \u2014 ${x.error || (zh ? "\u53D1\u9001\u5931\u8D25" : "send failed")}`).join("\n");
1981
+ }
1982
+ function successFlash(done, lang) {
1983
+ const n = (done || []).length;
1984
+ const zh = lang === "zh";
1985
+ const rtc = n > 0 && done.every((x) => x.via === "webrtc");
1986
+ if (n <= 1)
1987
+ return rtc ? zh ? "WebRTC \u6587\u4EF6\u53D1\u9001\u5B8C\u6210" : "WebRTC file sent" : zh ? "\u6587\u4EF6\u5DF2\u63D0\u4EA4\u53D1\u9001" : "File send started";
1988
+ return rtc ? zh ? `\u5DF2\u901A\u8FC7 WebRTC \u53D1\u9001 ${n} \u4E2A\u6587\u4EF6` : `${n} files sent via WebRTC` : zh ? `\u5DF2\u63D0\u4EA4\u53D1\u9001 ${n} \u4E2A\u6587\u4EF6` : `${n} file sends started`;
1989
+ }
1882
1990
  var PROOF_KEY = { eth: "proof.eth", sol: "proof.sol" };
1883
1991
  var HEAD = "Beagle wallet binding";
1884
1992
  var LINE = "I bind this wallet to my Beagle identity.";
@@ -3145,7 +3253,7 @@ ${lines}`, { assistant: { kind: "adopt", rows: fresh } }));
3145
3253
  cursor: mine ? "default" : "pointer"
3146
3254
  };
3147
3255
  const icon = /* @__PURE__ */ React.createElement("div", { style: { width: 34, height: 34, borderRadius: 7, flexShrink: 0, background: mine ? "rgba(255,255,255,0.16)" : "var(--chip)", display: "flex", alignItems: "center", justifyContent: "center", color: mine ? "#fff" : "var(--accent)" } }, /* @__PURE__ */ React.createElement(Icon, { name: m.file.media === "image" ? "image" : m.file.media === "video" ? "video" : m.file.media === "audio" ? "play" : "file", size: 18, stroke: 1.9 }));
3148
- const meta = /* @__PURE__ */ React.createElement("div", { style: { minWidth: 0, flex: 1 } }, /* @__PURE__ */ React.createElement("div", { style: { fontFamily: "var(--mono)", fontSize: 12.5, fontWeight: 600, color: mine ? "#fff" : "var(--text)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" } }, m.file.name), /* @__PURE__ */ React.createElement("div", { style: { fontFamily: "var(--mono)", fontSize: 11, color: mine ? "rgba(255,255,255,0.7)" : "var(--faint)", marginTop: 1 } }, busy === "cancel" ? `${m.file.size} \xB7 ${T.cancelling || "Cancelling\u2026"}` : busy === "retry" ? `${m.file.size} \xB7 ${T.retrying || "Retrying\u2026"}` : m.file.status === "queued" ? `${m.file.size} \xB7 ${T.queued || "queued"}` : m.file.status === "sending" ? `${m.file.size} \xB7 ${dkPct(m.file.pct)}${m.file.kbps ? " \xB7 " + dkSpeed(m.file.kbps) : ""}` : m.file.status === "failed" ? `${m.file.size} \xB7 failed` : m.file.status === "cancelled" ? `${m.file.size} \xB7 ${T.cancelled || "cancelled"}` : mine ? `${m.file.size} \xB7 sent` : `${m.file.size} \xB7 ${T.open || "open"}`));
3256
+ const meta = /* @__PURE__ */ React.createElement("div", { style: { minWidth: 0, flex: 1 } }, /* @__PURE__ */ React.createElement("div", { style: { fontFamily: "var(--mono)", fontSize: 12.5, fontWeight: 600, color: mine ? "#fff" : "var(--text)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" } }, m.file.name), /* @__PURE__ */ React.createElement("div", { style: { fontFamily: "var(--mono)", fontSize: 11, color: mine ? "rgba(255,255,255,0.7)" : "var(--faint)", marginTop: 1 } }, busy === "cancel" ? `${m.file.size} \xB7 ${T.cancelling || "Cancelling\u2026"}` : busy === "retry" ? `${m.file.size} \xB7 ${T.retrying || "Retrying\u2026"}` : m.file.status === "queued" ? `${m.file.size} \xB7 ${mine ? T.fileWaitsHere || "waits on this computer until they are online" : T.queued || "queued"}` : m.file.status === "sending" ? `${m.file.size} \xB7 ${dkPct(m.file.pct)}${m.file.kbps ? " \xB7 " + dkSpeed(m.file.kbps) : ""}` : m.file.status === "failed" ? `${m.file.size} \xB7 failed` : m.file.status === "cancelled" ? `${m.file.size} \xB7 ${T.cancelled || "cancelled"}` : mine && m.via === "offline" ? `${m.file.size} \xB7 ${T.fileOnExpress || "offline \xB7 stored on Express"}` : mine ? `${m.file.size} \xB7 sent` : `${m.file.size} \xB7 ${T.open || "open"}`));
3149
3257
  if (mine) {
3150
3258
  const btnBusy = !!busy;
3151
3259
  return /* @__PURE__ */ React.createElement(
@@ -3180,7 +3288,7 @@ ${lines}`, { assistant: { kind: "adopt", rows: fresh } }));
3180
3288
  },
3181
3289
  /* @__PURE__ */ React.createElement(Icon, { name: "download", size: 15, stroke: 2, color: "rgba(255,255,255,0.85)" })
3182
3290
  ),
3183
- busy === "cancel" || busy === "retry" ? /* @__PURE__ */ React.createElement(Icon, { name: "clock", size: 16, stroke: 2, color: "rgba(255,255,255,0.85)" }) : m.file.status === "queued" ? /* @__PURE__ */ React.createElement(Icon, { name: "clock", size: 16, stroke: 2, color: "rgba(255,255,255,0.85)" }) : m.file.status === "sending" ? /* @__PURE__ */ React.createElement("span", { style: { fontFamily: "var(--mono)", fontSize: 11, fontWeight: 700, color: "rgba(255,255,255,0.9)", whiteSpace: "nowrap" } }, dkPct(m.file.pct), m.file.kbps ? " \xB7 " + dkSpeed(m.file.kbps) : "") : m.file.status === "failed" || m.file.status === "cancelled" ? /* @__PURE__ */ React.createElement(Icon, { name: "x", size: 16, stroke: 2.4, color: "rgba(255,200,190,0.95)" }) : /* @__PURE__ */ React.createElement(Icon, { name: "checkCheck", size: 16, stroke: 2, color: "rgba(255,255,255,0.85)" }),
3291
+ busy === "cancel" || busy === "retry" ? /* @__PURE__ */ React.createElement(Icon, { name: "clock", size: 16, stroke: 2, color: "rgba(255,255,255,0.85)" }) : m.file.status === "queued" ? /* @__PURE__ */ React.createElement(Icon, { name: "clock", size: 16, stroke: 2, color: "rgba(255,255,255,0.85)" }) : m.file.status === "sending" ? /* @__PURE__ */ React.createElement("span", { style: { fontFamily: "var(--mono)", fontSize: 11, fontWeight: 700, color: "rgba(255,255,255,0.9)", whiteSpace: "nowrap" } }, dkPct(m.file.pct), m.file.kbps ? " \xB7 " + dkSpeed(m.file.kbps) : "") : m.file.status === "failed" || m.file.status === "cancelled" ? /* @__PURE__ */ React.createElement(Icon, { name: "x", size: 16, stroke: 2.4, color: "rgba(255,200,190,0.95)" }) : m.via === "offline" ? /* @__PURE__ */ React.createElement(Icon, { name: "check", size: 16, stroke: 2, color: "rgba(255,255,255,0.85)" }) : /* @__PURE__ */ React.createElement(Icon, { name: "checkCheck", size: 16, stroke: 2, color: "rgba(255,255,255,0.85)" }),
3184
3292
  (m.file.status === "sending" || m.file.status === "queued" || busy === "cancel") && m.id && /* @__PURE__ */ React.createElement(
3185
3293
  "button",
3186
3294
  {
@@ -3280,7 +3388,8 @@ ${lines}`, { assistant: { kind: "adopt", rows: fresh } }));
3280
3388
  wordBreak: "break-word"
3281
3389
  } }, /* @__PURE__ */ React.createElement(MarkdownText, { text: read.text, onNameCard })));
3282
3390
  })(), read.form && /* @__PURE__ */ React.createElement("div", { style: { marginTop: 6 } }, /* @__PURE__ */ React.createElement(DkChatForm, { form: read.form, submitted, peer, onSubmit: onFormSubmit })), m.assistant && onAssistantRemove && /* @__PURE__ */ React.createElement(AssistantPanel, { m, T, lang, onRemove: onAssistantRemove, onAdopt: onAssistantAdopt }), /* @__PURE__ */ React.createElement("div", { style: { display: "flex", alignItems: "center", gap: 4, margin: "3px 3px 0" } }, /* @__PURE__ */ React.createElement("span", { style: { fontFamily: "var(--mono)", fontSize: 10, color: "var(--faint)" } }, m.time), (() => {
3283
- const sentDone = mine && m.status && m.status !== "queued" && m.status !== "sending" && m.status !== "failed";
3391
+ const st = m.file ? m.file.status : m.status;
3392
+ const sentDone = mine && st && st !== "queued" && st !== "sending" && st !== "failed" && st !== "cancelled";
3284
3393
  const via = !mine ? m.via : sentDone ? m.via === "offline" ? "offline" : "online" : null;
3285
3394
  if (!via)
3286
3395
  return null;
@@ -3297,7 +3406,7 @@ ${lines}`, { assistant: { kind: "adopt", rows: fresh } }));
3297
3406
  style: { background: "none", border: "none", cursor: "pointer", padding: 0, marginLeft: 2, display: "inline-flex", opacity: 0.55 }
3298
3407
  },
3299
3408
  /* @__PURE__ */ React.createElement(Icon, { name: "trash", size: 11, stroke: 2, color: "var(--faint)" })
3300
- ), mine && m.status === "failed" ? (
3409
+ ), mine && m.file && ["queued", "sending", "failed", "cancelled"].includes(m.file.status) ? null : mine && m.status === "failed" ? (
3301
3410
  /* Not delivered. Says so, and one tap tries again — silently
3302
3411
  rendering this as a sent message is how a chat loses mail. */
3303
3412
  /* @__PURE__ */ React.createElement(
@@ -3629,30 +3738,30 @@ ${lines}`, { assistant: { kind: "adopt", rows: fresh } }));
3629
3738
  requestAnimationFrame(scrollToBottom);
3630
3739
  }
3631
3740
  };
3741
+ const finishRef = React.useRef(null);
3742
+ finishRef.current = (done) => {
3743
+ const report = failureReport(done, lang);
3744
+ if (report)
3745
+ window.alert(report);
3746
+ else
3747
+ showFlash("ok", successFlash(done, lang));
3748
+ requestAnimationFrame(scrollToBottom);
3749
+ };
3750
+ const queueRef = React.useRef(null);
3751
+ if (!queueRef.current) {
3752
+ queueRef.current = createFileSendQueue({
3753
+ onChange: (items) => setSending(items.length ? items : null),
3754
+ onFinish: (done) => finishRef.current && finishRef.current(done)
3755
+ });
3756
+ }
3632
3757
  const sendFiles = (files, mode) => {
3633
3758
  const sender = mode === "webrtc" ? onSendRtcFile : onSendFile;
3634
3759
  if (!files || !files.length || !sender)
3635
3760
  return;
3636
- const file = files[0];
3637
3761
  followScrollRef.current = true;
3638
- setSending({ name: file.name, via: mode, pct: 0, sent: 0, size: file.size });
3639
- const onProgress = (p) => setSending((s) => s && s.name === file.name ? {
3640
- ...s,
3641
- pct: p && p.pct,
3642
- sent: p && p.sent,
3643
- size: p && p.size || s.size,
3644
- kbps: p && p.kbps
3645
- } : s);
3646
- Promise.resolve(sender(file, onProgress)).then((r) => {
3647
- if (r && r.ok === false)
3648
- window.alert((lang === "zh" ? "\u53D1\u9001\u5931\u8D25: " : "Send failed: ") + (r.error || ""));
3649
- else
3650
- showFlash("ok", mode === "webrtc" ? lang === "zh" ? "WebRTC \u6587\u4EF6\u53D1\u9001\u5B8C\u6210" : "WebRTC file sent" : lang === "zh" ? "\u6587\u4EF6\u5DF2\u63D0\u4EA4\u53D1\u9001" : "File send started");
3651
- }).finally(() => {
3652
- setSending(null);
3653
- requestAnimationFrame(scrollToBottom);
3654
- });
3762
+ queueRef.current.add(files, sender, { via: mode, peerId: peer.id });
3655
3763
  };
3764
+ const mySending = sending ? sending.filter((s) => s.peerId === peer.id) : [];
3656
3765
  const onDrop = (e) => {
3657
3766
  e.preventDefault();
3658
3767
  setDragOver(false);
@@ -3673,7 +3782,7 @@ ${lines}`, { assistant: { kind: "adopt", rows: fresh } }));
3673
3782
  },
3674
3783
  onDrop
3675
3784
  },
3676
- dragOver && /* @__PURE__ */ React.createElement("div", { style: { position: "absolute", inset: 0, zIndex: 30, background: "rgba(91,140,255,0.10)", border: "2px dashed var(--accent)", borderRadius: 12, display: "flex", alignItems: "center", justifyContent: "center", pointerEvents: "none", fontFamily: "var(--mono)", fontSize: 14, color: "var(--accent)" } }, lang === "zh" ? "\u677E\u5F00\u53D1\u9001\u6587\u4EF6" : "Drop to send file"),
3785
+ dragOver && /* @__PURE__ */ React.createElement("div", { style: { position: "absolute", inset: 0, zIndex: 30, background: "rgba(91,140,255,0.10)", border: "2px dashed var(--accent)", borderRadius: 12, display: "flex", alignItems: "center", justifyContent: "center", pointerEvents: "none", fontFamily: "var(--mono)", fontSize: 14, color: "var(--accent)" } }, lang === "zh" ? "\u677E\u5F00\u53D1\u9001\u6587\u4EF6" : "Drop to send files"),
3677
3786
  /* @__PURE__ */ React.createElement("div", { style: { height: phone ? 56 : 60, boxSizing: "content-box", paddingTop: phone ? "env(safe-area-inset-top, 0px)" : 0, flexShrink: 0, borderBottom: "1px solid var(--line)", display: "flex", alignItems: "center", gap: phone ? 8 : 12, paddingLeft: phone ? 4 : 16, paddingRight: phone ? 8 : 16, background: "var(--panel)" } }, phone && onBack && /* @__PURE__ */ React.createElement(
3678
3787
  "button",
3679
3788
  {
@@ -3710,6 +3819,7 @@ ${peer.address}`
3710
3819
  {
3711
3820
  ref: rtcFileRef,
3712
3821
  type: "file",
3822
+ multiple: true,
3713
3823
  style: { display: "none" },
3714
3824
  onChange: (e) => {
3715
3825
  sendFiles(e.target.files, "webrtc");
@@ -3803,11 +3913,20 @@ ${peer.address}`
3803
3913
  stroke: 2.2,
3804
3914
  color: flash.kind === "err" ? "var(--danger)" : "var(--accent)"
3805
3915
  }
3806
- ), flash.msg), sending && /* @__PURE__ */ React.createElement("div", { style: { maxWidth: 1200, margin: "0 auto 8px", display: "flex", alignItems: "center", gap: 8, fontFamily: "var(--mono)", fontSize: 11.5, color: "var(--faint)" } }, /* @__PURE__ */ React.createElement(Icon, { name: "paperclip", size: 13, stroke: 2, color: "var(--accent)" }), (lang === "zh" ? "\u53D1\u9001\u4E2D: " : "Sending: ") + (sending.via === "webrtc" ? "WebRTC \xB7 " : "") + sending.name + (sending.size ? " \xB7 " + dkFileSize(sending.sent || 0) + " / " + dkFileSize(sending.size) : "") + (sending.pct != null ? " \xB7 " + Math.min(100, Math.max(0, sending.pct)).toFixed(1) + "%" : "") + (sending.kbps != null ? " \xB7 " + dkSpeed(sending.kbps) : "")), /* @__PURE__ */ React.createElement("div", { style: { maxWidth: 1200, margin: "0 auto", display: "flex", alignItems: "center", gap: phone ? 6 : 10 } }, /* @__PURE__ */ React.createElement(
3916
+ ), flash.msg), mySending.length > 0 && /* @__PURE__ */ React.createElement("div", { "data-testid": "file-send-queue", style: { maxWidth: 1200, margin: "0 auto 8px", display: "flex", flexDirection: "column", gap: 3, fontFamily: "var(--mono)", fontSize: 11.5, color: "var(--faint)", maxHeight: 132, overflowY: "auto" } }, mySending.length > 1 && /* @__PURE__ */ React.createElement("div", { style: { color: "var(--dim)" } }, (lang === "zh" ? "\u53D1\u9001 " : "Sending ") + mySending.filter((s) => s.status === "sent" || s.status === "failed").length + " / " + mySending.length + (lang === "zh" ? " \u4E2A\u6587\u4EF6" : " files")), mySending.map((s) => /* @__PURE__ */ React.createElement("div", { key: s.id, "data-status": s.status, style: { display: "flex", alignItems: "center", gap: 8, minWidth: 0, color: s.status === "failed" ? "var(--danger)" : void 0 } }, /* @__PURE__ */ React.createElement(
3917
+ Icon,
3918
+ {
3919
+ name: s.status === "sent" ? "check" : s.status === "failed" ? "x" : "paperclip",
3920
+ size: 13,
3921
+ stroke: 2,
3922
+ color: s.status === "failed" ? "var(--danger)" : s.status === "waiting" ? "var(--faint)" : "var(--accent)"
3923
+ }
3924
+ ), /* @__PURE__ */ React.createElement("span", { style: { overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", minWidth: 0 } }, (s.status === "sending" ? lang === "zh" ? "\u53D1\u9001\u4E2D: " : "Sending: " : "") + (s.via === "webrtc" ? "WebRTC \xB7 " : "") + s.name + (s.status === "sending" ? (s.size ? " \xB7 " + dkFileSize(s.sent || 0) + " / " + dkFileSize(s.size) : "") + (s.pct != null ? " \xB7 " + Math.min(100, Math.max(0, s.pct)).toFixed(1) + "%" : "") + (s.kbps != null ? " \xB7 " + dkSpeed(s.kbps) : "") : s.status === "waiting" ? " \xB7 " + (s.size ? dkFileSize(s.size) + " \xB7 " : "") + (lang === "zh" ? "\u7B49\u5F85\u4E2D" : "waiting") : s.status === "failed" ? " \xB7 " + (s.error || "") : " \xB7 " + (lang === "zh" ? "\u5DF2\u63D0\u4EA4" : "done")))))), /* @__PURE__ */ React.createElement("div", { style: { maxWidth: 1200, margin: "0 auto", display: "flex", alignItems: "center", gap: phone ? 6 : 10 } }, /* @__PURE__ */ React.createElement(
3807
3925
  "input",
3808
3926
  {
3809
3927
  ref: fileRef,
3810
3928
  type: "file",
3929
+ multiple: true,
3811
3930
  style: { display: "none" },
3812
3931
  onChange: (e) => {
3813
3932
  sendFiles(e.target.files);
@@ -7180,6 +7299,8 @@ ${peer.address}`
7180
7299
  message: "Message",
7181
7300
  send: "Send",
7182
7301
  pickPeer: "Select a peer to open the conversation",
7302
+ fileWaitsHere: "waits on this computer until they are online",
7303
+ fileOnExpress: "offline \xB7 stored on Express",
7183
7304
  queued: "queued",
7184
7305
  sendingMsg: "sending",
7185
7306
  groupTag: "group",
@@ -7408,6 +7529,8 @@ ${peer.address}`
7408
7529
  message: "\u6D88\u606F",
7409
7530
  send: "\u53D1\u9001",
7410
7531
  pickPeer: "\u9009\u62E9\u4E00\u4F4D\u597D\u53CB\u5F00\u59CB\u4F1A\u8BDD",
7532
+ fileWaitsHere: "\u5728\u672C\u673A\u7B49\u5F85,\u597D\u53CB\u4E0A\u7EBF\u540E\u53D1\u9001",
7533
+ fileOnExpress: "\u79BB\u7EBF \xB7 \u5DF2\u5B58\u5230 Express",
7411
7534
  queued: "\u5F85\u53D1\u9001",
7412
7535
  sendingMsg: "\u53D1\u9001\u4E2D",
7413
7536
  groupTag: "\u7FA4",
@@ -1,5 +1,12 @@
1
+ import { CarrierNode } from "./carrier-node.js";
1
2
  import type { IpcRequest, IpcResponse } from "./ipc.js";
2
3
  import type { PeerHost } from "./peer-host.js";
4
+ /** What a sending-side `file-cancel` means (peer's `onFileCancel` reasons):
5
+ * none = the friend's KILL, they declined it → "cancelled"; "local" = our own
6
+ * cancelSend, the caller sets the row; anything else ("no-response",
7
+ * "timeout", "peer-offline", or a reason a later peer adds) = the SDK gave up
8
+ * on the path → the file is still owed (#liveDeliveryGaveUp). */
9
+ export declare function liveCancelMeaning(reason: string | undefined): "declined" | "ours" | "gave-up";
3
10
  export interface EmbeddedHostOptions {
4
11
  configDir: string;
5
12
  keyFile: string;
@@ -30,6 +37,12 @@ export interface EmbeddedHostOptions {
30
37
  /** @decentnetwork/peer version backing this embedded node, surfaced by `ping`
31
38
  * so the panel can name the code that is actually running. */
32
39
  peerVersion?: string;
40
+ /** Tests only: a CarrierNode stand-in, a shorter offer window, a shorter
41
+ * first re-offer backoff, and a shorter no-progress give-up. */
42
+ node?: CarrierNode;
43
+ offerWindowMs?: number;
44
+ liveRetryBaseMs?: number;
45
+ liveStallMs?: number;
33
46
  }
34
47
  export declare class EmbeddedHost implements PeerHost {
35
48
  #private;
@@ -13,6 +13,7 @@ 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
19
  import { parseGroupFile, storedGroupFiles, withoutFileData } from "./group-file.js";
@@ -20,13 +21,29 @@ 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"));
@@ -180,6 +211,9 @@ export class EmbeddedHost {
180
211
  })();
181
212
  }, 8000);
182
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?.();
183
217
  }
184
218
  #sweeping = false;
185
219
  /** A session that can actually carry traffic right now. */
@@ -255,8 +289,13 @@ export class EmbeddedHost {
255
289
  // sat visibly stuck despite the peer being online. One delayed retry
256
290
  // covers that gap; the per-send chain and later reconnects cover the
257
291
  // rest.
258
- if (e.status === "connected")
259
- 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
260
299
  });
261
300
  this.#node.on("call-signal", (evt) => {
262
301
  this.#callLog.push({
@@ -271,9 +310,11 @@ export class EmbeddedHost {
271
310
  for (const w of waiters)
272
311
  w();
273
312
  });
274
- // 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.
275
316
  this.#node.on("inline-file", (f) => {
276
- 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 });
277
318
  });
278
319
  // toxcore file transfer. The daemon logs an incoming file once, on
279
320
  // completion — no "receiving" chip — and MessageStore's status enum has no
@@ -292,17 +333,23 @@ export class EmbeddedHost {
292
333
  // `sending` is authoritative for direction — no map scanning needed.
293
334
  if (!p.sending)
294
335
  return;
336
+ // An ack means the friend accepted: no Express fallback for this one.
337
+ this.#endOfferWindow(p.fileId);
295
338
  const s = this.#activeSends.get(p.fileId);
296
- if (s)
297
- 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 });
298
343
  });
299
344
  this.#node.on("file-complete", (p) => {
300
345
  if (p.sending) {
346
+ this.#endOfferWindow(p.fileId);
301
347
  const s = this.#activeSends.get(p.fileId);
302
348
  if (!s)
303
349
  return;
304
350
  this.#messages.patchFile(s.peer, s.msgId, { status: "sent", sent: p.size });
305
351
  this.#activeSends.delete(p.fileId);
352
+ this.#retryBackoff.delete(s.msgId);
306
353
  void unlink(resolve(this.outboxDir, s.msgId)).catch(() => undefined);
307
354
  this.#events.emit("event", { type: "chat", userid: s.peer, dir: "out" });
308
355
  return;
@@ -314,11 +361,30 @@ export class EmbeddedHost {
314
361
  this.#node.on("file-cancel", (p) => {
315
362
  if (!p.sending)
316
363
  return;
364
+ this.#endOfferWindow(p.fileId);
317
365
  const s = this.#activeSends.get(p.fileId);
318
366
  if (!s)
319
367
  return;
320
- 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;
321
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" });
322
388
  });
323
389
  }
324
390
  /** A group file that came with its bytes: downloads/<name> (a different
@@ -343,17 +409,22 @@ export class EmbeddedHost {
343
409
  /** downloads/<name> ← a group file's bytes; a different file of the same
344
410
  * name gets "-2", "-3"… Returns the name used. */
345
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) {
346
417
  await mkdir(this.downloadsDir, { recursive: true });
347
- const safe = sanitizeFileName(f.name);
418
+ const safe = sanitizeFileName(fileName);
348
419
  const dot = safe.lastIndexOf(".");
349
420
  let name = safe;
350
421
  for (let i = 2; i < 1000; i++) {
351
422
  const existing = await readFile(resolve(this.downloadsDir, name)).catch(() => undefined);
352
- if (!existing || existing.equals(f.data))
423
+ if (!existing || existing.equals(data))
353
424
  break;
354
425
  name = dot > 0 ? `${safe.slice(0, dot)}-${i}${safe.slice(dot)}` : `${safe}-${i}`;
355
426
  }
356
- await writeFile(resolve(this.downloadsDir, name), f.data);
427
+ await writeFile(resolve(this.downloadsDir, name), data);
357
428
  return name;
358
429
  }
359
430
  /** On start: group files a host older than beagle 0.1.131 stored as CGP1
@@ -386,20 +457,33 @@ export class EmbeddedHost {
386
457
  if (saved || dropped)
387
458
  this.#logger.info(`stored group files: ${saved} saved as files, ${dropped} duplicates dropped`);
388
459
  }
389
- /** Persist a received file under downloads/ and log it in the thread. */
390
- async #saveIncoming(pubkey, name, data) {
391
- const safe = sanitizeFileName(name);
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);
392
474
  try {
393
- await mkdir(this.downloadsDir, { recursive: true });
394
- await writeFile(resolve(this.downloadsDir, safe), data);
395
- 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 });
396
477
  this.#meta.ensure(pubkey);
397
478
  this.#events.emit("event", { type: "chat", userid: pubkey, dir: "in" });
398
- 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)" : ""}`);
399
480
  }
400
481
  catch (e) {
401
482
  this.#logger.warn(`could not save incoming file: ${e.message}`);
402
483
  }
484
+ finally {
485
+ this.#savingInbound.delete(key);
486
+ }
403
487
  }
404
488
  /** Deliver anything queued while this friend was offline. */
405
489
  async #flushOutbox(pubkey) {
@@ -424,15 +508,29 @@ export class EmbeddedHost {
424
508
  continue;
425
509
  }
426
510
  const path = resolve(this.outboxDir, msg.id);
427
- 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())
428
519
  continue;
429
520
  try {
430
521
  const data = await readFile(path);
431
522
  const fileId = this.#node.sendFile(pubkey, new Uint8Array(data), msg.file.name);
432
523
  if (fileId) {
433
524
  this.#messages.patchFile(pubkey, msg.id, { status: "sending", sent: 0 });
434
- this.#activeSends.set(fileId, { peer: pubkey, msgId: msg.id });
435
- 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})` : ""));
436
534
  }
437
535
  }
438
536
  catch (e) {
@@ -460,6 +558,17 @@ export class EmbeddedHost {
460
558
  clearInterval(this.#sweepTimer);
461
559
  this.#sweepTimer = null;
462
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();
463
572
  // Stop the peer FIRST, then release the lock. The reverse order would open
464
573
  // a window where a daemon could start while our peer is still live.
465
574
  await this.#node.stop();
@@ -752,6 +861,7 @@ export class EmbeddedHost {
752
861
  for (const [fileId, s] of this.#activeSends) {
753
862
  if (s.msgId !== id)
754
863
  continue;
864
+ this.#endOfferWindow(fileId);
755
865
  if (this.#node.cancelSend(s.peer, fileId))
756
866
  cancelled++;
757
867
  this.#activeSends.delete(fileId);
@@ -767,9 +877,12 @@ export class EmbeddedHost {
767
877
  if (!existsSync(path))
768
878
  continue;
769
879
  const data = await readFile(path);
770
- 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}`);
771
883
  if (fileId) {
772
- 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);
773
886
  this.#messages.patchFile(req.peer, id, { status: "sending", sent: 0 });
774
887
  retried++;
775
888
  }
@@ -838,29 +951,56 @@ export class EmbeddedHost {
838
951
  }
839
952
  })();
840
953
  }
841
- if (!this.#node.isFriendOnline(userid)) {
842
- if (data.length > OUTBOX_MAX_FILE_BYTES) {
843
- throw new Error(`Peer is offline — queued files are limited to ${(OUTBOX_MAX_FILE_BYTES / 1024 / 1024) | 0} MB ` +
844
- `(this is ${(data.length / 1024 / 1024).toFixed(1)} MB). Send it once they're online.`);
845
- }
846
- 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
+ });
847
973
  if (!msg)
848
974
  throw new Error("Could not queue file");
849
975
  await mkdir(this.outboxDir, { recursive: true });
850
976
  await writeFile(resolve(this.outboxDir, msg.id), data);
851
977
  this.#meta.ensure(userid);
852
978
  this.#events.emit("event", { type: "chat", userid, dir: "out" });
853
- 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 };
854
986
  }
855
987
  // Everyone streams — a native friend's packets ride DNFT1 frames inside
856
988
  // friend messages (see the note on the deleted native inline gate above).
857
989
  const native = this.#node.isNativeFriend(userid);
858
- 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 });
859
991
  if (!msg)
860
992
  throw new Error("Could not create file message");
861
993
  await mkdir(this.outboxDir, { recursive: true });
862
994
  await writeFile(resolve(this.outboxDir, msg.id), data);
863
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
+ }
864
1004
  if (!fileId) {
865
1005
  // No transfer slot. The inline fallback only helps a JS friend (their
866
1006
  // text-ack makes it confirmable); to a native it is unconfirmable by
@@ -899,10 +1039,135 @@ export class EmbeddedHost {
899
1039
  })();
900
1040
  return { inline: true, name: safe, size: data.length, pending: true };
901
1041
  }
902
- 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);
903
1045
  this.#meta.ensure(userid);
904
1046
  this.#events.emit("event", { type: "chat", userid, dir: "out" });
905
1047
  return { fileId, name: safe, size: data.length };
906
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
+ }
907
1172
  }
908
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;
@@ -0,0 +1,55 @@
1
+ // Where an outgoing file goes: live, Express, or this computer's outbox.
2
+ //
3
+ // decent-hq TASK-2026-11-13-desktop-multifile-and-offline-files, part C.2,
4
+ // following iOS (1.8.37+, Elastos.NET.WebRTC.Swift.SDK docs/OFFLINE-FILE-MESSAGE.md,
5
+ // "Sender rules"):
6
+ //
7
+ // friend offline, fits Express → ONE offline file message on Express
8
+ // (peer >= 0.1.176 sendFileViaExpress); the
9
+ // row reads "offline" — stored, not yet theirs.
10
+ // friend offline, too big → the local outbox (25 MB cap, as before); the
11
+ // row says it waits on this computer until the
12
+ // friend is online. Over 25 MB: refused.
13
+ // friend online → live transfer. When it fits Express and the
14
+ // friend has not accepted within OFFER_WINDOW_MS
15
+ // (iOS `offerWindow`), the offer is withdrawn
16
+ // and the file goes to Express instead.
17
+ //
18
+ // "Fits Express" is the whole message: [u32 metaLen][meta JSON][bytes] ≤
19
+ // 5 242 880 bytes (Carrier's legacy bulk-message cap), meta ≤ 4096.
20
+ import { OFFLINE_FILE_MAX_MESSAGE_BYTES, OFFLINE_FILE_MAX_META_BYTES, contentTypeForFileName } from "@decentnetwork/peer";
21
+ /** Files bigger than this are not queued for an offline friend — the bytes sit
22
+ * on disk until they reconnect, and an unbounded queue is how you fill a
23
+ * user's disk by accident. Live transfers have no such limit. */
24
+ export const OUTBOX_MAX_FILE_BYTES = 25 * 1024 * 1024;
25
+ /** iOS `offerWindow`: how long a live offer may go unaccepted before a file
26
+ * that fits Express is withdrawn and parked there instead. */
27
+ export const OFFER_WINDOW_MS = 10_000;
28
+ /** The exact size of the offline file message sendFileViaExpress would post
29
+ * for this name and size (the meta JSON is built the same way). */
30
+ export function expressMessageBytes(name, size) {
31
+ const meta = Buffer.byteLength(JSON.stringify({ type: "file", filename: name, contentType: contentTypeForFileName(name), size }), "utf-8");
32
+ return { total: 4 + meta + size, meta };
33
+ }
34
+ /** True when one offline file message on Express can carry this file. */
35
+ export function fitsExpress(name, size) {
36
+ const { total, meta } = expressMessageBytes(name, size);
37
+ return total <= OFFLINE_FILE_MAX_MESSAGE_BYTES && meta <= OFFLINE_FILE_MAX_META_BYTES;
38
+ }
39
+ /** The routing table above. `expressAvailable` is false on a peer SDK without
40
+ * sendFileViaExpress or with no Express node: then an offline file of any
41
+ * size waits in the outbox, as it did before. */
42
+ export function routeFileSend(opts) {
43
+ const fits = opts.expressAvailable && fitsExpress(opts.name, opts.size);
44
+ if (opts.online)
45
+ return { kind: "live", offerWindow: fits };
46
+ if (fits)
47
+ return { kind: "express" };
48
+ if (opts.size <= OUTBOX_MAX_FILE_BYTES)
49
+ return { kind: "outbox" };
50
+ return {
51
+ kind: "refuse",
52
+ reason: `Peer is offline — queued files are limited to ${(OUTBOX_MAX_FILE_BYTES / 1024 / 1024) | 0} MB ` +
53
+ `(this is ${(opts.size / 1024 / 1024).toFixed(1)} MB). Send it once they're online.`,
54
+ };
55
+ }
@@ -80,6 +80,9 @@ export declare class MessageStore {
80
80
  /** Record how an outgoing text travelled: "online" over a live session,
81
81
  * "offline" posted to the express relay for the peer to collect. */
82
82
  setVia(peer: string, id: string, via: "online" | "offline"): boolean;
83
+ /** The same for a FILE row: "offline" = parked on Express, "online" = a
84
+ * live transfer, undefined = not on the wire yet (waiting in the outbox). */
85
+ setFileVia(peer: string, id: string, via: "online" | "offline" | undefined): boolean;
83
86
  /** Has this peer ever sent us anything? Used as proof-of-friendship for
84
87
  * records that predate the SDK's acceptedAt bookkeeping — a message can
85
88
  * only arrive over an established session. */
@@ -111,8 +114,10 @@ export declare class MessageStore {
111
114
  }, origin?: ChatMessage["origin"]): ChatMessage | undefined;
112
115
  /** Every message in a peer's thread (oldest first). Read-only use. */
113
116
  thread(peer: string): readonly ChatMessage[];
114
- /** True when this peer's thread already holds a file with these bytes. */
115
- hasFileSha(peer: string, sha256: string): boolean;
117
+ /** True when this peer's thread already holds a file with these bytes —
118
+ * in `dir` only, when given (a received file must not be dropped because
119
+ * we once SENT the same bytes). */
120
+ hasFileSha(peer: string, sha256: string, dir?: "in" | "out"): boolean;
116
121
  /** Patch an existing file message's transfer fields (status / sent bytes).
117
122
  * No-op if the id isn't found. Returns true if it patched. */
118
123
  patchFile(peer: string, id: string, patch: {
@@ -38,6 +38,12 @@ export class MessageStore {
38
38
  for (const m of msgs)
39
39
  if (m.status === "sending")
40
40
  m.status = "queued";
41
+ // Same for an outgoing file: its transfer died with the process, and
42
+ // its bytes are still in outbox/<id>. Left "sending" it was stuck
43
+ // forever — nothing ever offers a "sending" row again.
44
+ for (const m of msgs)
45
+ if (m.dir === "out" && m.file?.status === "sending")
46
+ m.file.status = "queued";
41
47
  this.byPeer.set(peer, msgs);
42
48
  total += msgs.length;
43
49
  }
@@ -96,6 +102,19 @@ export class MessageStore {
96
102
  this.scheduleSave();
97
103
  return true;
98
104
  }
105
+ /** The same for a FILE row: "offline" = parked on Express, "online" = a
106
+ * live transfer, undefined = not on the wire yet (waiting in the outbox). */
107
+ setFileVia(peer, id, via) {
108
+ const msg = this.byPeer.get(peer)?.find((m) => m.id === id);
109
+ if (!msg || !msg.file)
110
+ return false;
111
+ if (via)
112
+ msg.via = via;
113
+ else
114
+ delete msg.via;
115
+ this.scheduleSave();
116
+ return true;
117
+ }
99
118
  /** Has this peer ever sent us anything? Used as proof-of-friendship for
100
119
  * records that predate the SDK's acceptedAt bookkeeping — a message can
101
120
  * only arrive over an established session. */
@@ -145,9 +164,12 @@ export class MessageStore {
145
164
  thread(peer) {
146
165
  return this.byPeer.get(peer) ?? [];
147
166
  }
148
- /** True when this peer's thread already holds a file with these bytes. */
149
- hasFileSha(peer, sha256) {
150
- return (this.history(peer)[peer] ?? []).some((m) => m.file?.sha256 === sha256);
167
+ /** True when this peer's thread already holds a file with these bytes —
168
+ * in `dir` only, when given (a received file must not be dropped because
169
+ * we once SENT the same bytes). */
170
+ hasFileSha(peer, sha256, dir) {
171
+ const want = sha256.toLowerCase();
172
+ return (this.history(peer)[peer] ?? []).some((m) => m.file?.sha256?.toLowerCase() === want && (!dir || m.dir === dir));
151
173
  }
152
174
  /** Patch an existing file message's transfer fields (status / sent bytes).
153
175
  * No-op if the id isn't found. Returns true if it patched. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@decentnetwork/beagle",
3
- "version": "0.1.138",
3
+ "version": "0.1.142",
4
4
  "description": "Beagle — P2P chat, file transfer and calls for regular users, on the Decent Network. No admin privilege required.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -26,10 +26,10 @@
26
26
  "start": "node dist/cli.js"
27
27
  },
28
28
  "dependencies": {
29
- "@decentnetwork/beagle-ui": "^0.2.43",
29
+ "@decentnetwork/beagle-ui": "^0.2.44",
30
30
  "@decentnetwork/chat-components": "^0.1.3",
31
31
  "@decentnetwork/lan": "^0.1.316",
32
- "@decentnetwork/peer": "^0.1.172",
32
+ "@decentnetwork/peer": "^0.1.178",
33
33
  "@decentnetwork/peer-webrtc": "^0.2.21",
34
34
  "js-yaml": "^4.1.0",
35
35
  "ws": "^8.21.1",