@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.
@@ -1,4 +1,4 @@
1
- window.__DK_UI_VERSION="0.1.131";
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);
@@ -5189,6 +5308,44 @@ ${peer.address}`
5189
5308
  justifyContent: "center"
5190
5309
  } }, /* @__PURE__ */ React.createElement(Icon, { name: app.icon, size: 19, color: "var(--accent)", stroke: 1.8 })), /* @__PURE__ */ React.createElement("div", { style: { flex: 1, minWidth: 0 } }, /* @__PURE__ */ React.createElement("div", { style: { fontFamily: "var(--ui)", fontSize: 14, fontWeight: 600, color: "var(--text)" } }, pickText(app.name, t && t.lang, app.id)), /* @__PURE__ */ React.createElement("div", { style: { fontFamily: "var(--ui)", fontSize: 12.5, color: "var(--faint)", marginTop: 2 } }, pickText(app.blurb, t && t.lang, "")), /* @__PURE__ */ React.createElement("div", { style: { fontFamily: "var(--mono)", fontSize: 11, color: "var(--dim)", marginTop: 3 } }, app.host ? zh ? "\u672C\u673A\u5E94\u7528" : "runs in this app" : String(app.origin || "").replace(/^https?:\/\//, ""))), /* @__PURE__ */ React.createElement(Btn, { tone: "accent", size: "sm", onClick: busy ? void 0 : () => open(app) }, busy === app.id ? zh ? "\u6253\u5F00\u4E2D\u2026" : "opening\u2026" : zh ? "\u6253\u5F00" : "Open")))));
5191
5310
  }
5311
+ var CLAIM_SUPPRESS_MS = 5 * 6e4;
5312
+ function newPageId() {
5313
+ return "p" + Math.random().toString(36).slice(2, 10) + Date.now().toString(36).slice(-4);
5314
+ }
5315
+ var norm = (id) => String(id || "").trim().toLowerCase();
5316
+ function silencedFor(rec, myPage) {
5317
+ if (!rec)
5318
+ return false;
5319
+ if (rec.state === "ended")
5320
+ return true;
5321
+ if (rec.state === "claimed")
5322
+ return !(rec.claim && rec.claim.page === myPage);
5323
+ return false;
5324
+ }
5325
+ function applyCallsTable(table, myPage, suppressed, now) {
5326
+ const stop = [];
5327
+ const ended = [];
5328
+ for (const rec of Array.isArray(table) ? table : []) {
5329
+ if (!rec || !rec.callId)
5330
+ continue;
5331
+ const id = norm(rec.callId);
5332
+ if (rec.state === "ended")
5333
+ ended.push(id);
5334
+ if (!silencedFor(rec, myPage))
5335
+ continue;
5336
+ if (!suppressed.has(id))
5337
+ suppressed.set(id, now);
5338
+ stop.push(id);
5339
+ }
5340
+ return { stop, ended };
5341
+ }
5342
+ function isSuppressed(suppressed, callId, now) {
5343
+ const at = suppressed.get(norm(callId));
5344
+ return !!at && now - at < CLAIM_SUPPRESS_MS;
5345
+ }
5346
+ function sameCall(a, b) {
5347
+ return !!a && !!b && norm(a) === norm(b);
5348
+ }
5192
5349
  var DK_FALLBACK_ICE_SERVERS = [
5193
5350
  { urls: "stun:stun.l.google.com:19302" },
5194
5351
  { urls: "turn:tokyo.fi.chat:3478", username: "allcom", credential: "allcompass" },
@@ -5296,6 +5453,9 @@ ${peer.address}`
5296
5453
  function dkRtcSignalBus() {
5297
5454
  if (window.__dkRtcSignalBus)
5298
5455
  return window.__dkRtcSignalBus;
5456
+ const pageId = window.__dkPageId || (window.__dkPageId = newPageId());
5457
+ let callsVersion = null;
5458
+ let callsTable = [];
5299
5459
  const PW = window.PeerWebRTC;
5300
5460
  const handlers = /* @__PURE__ */ new Map();
5301
5461
  const pendingCalls = [];
@@ -5326,12 +5486,18 @@ ${peer.address}`
5326
5486
  while (!stopped) {
5327
5487
  let signals = [];
5328
5488
  try {
5329
- const u = cursor == null ? "/api/call-poll" : "/api/call-poll?since=" + cursor;
5489
+ const u = cursor == null ? "/api/call-poll" : "/api/call-poll?since=" + cursor + (callsVersion == null ? "" : "&cv=" + callsVersion);
5330
5490
  const r = await fetch(u, { headers: { "cache-control": "no-cache" } });
5331
5491
  const d = await r.json();
5332
5492
  signals = d && d.signals || [];
5333
5493
  if (d && typeof d.cursor === "number")
5334
5494
  cursor = d.cursor;
5495
+ if (d && Array.isArray(d.calls)) {
5496
+ callsTable = d.calls;
5497
+ if (typeof d.callsVersion === "number")
5498
+ callsVersion = d.callsVersion;
5499
+ emit("calls", null, callsTable);
5500
+ }
5335
5501
  } catch (e) {
5336
5502
  await new Promise((res) => setTimeout(res, 1e3));
5337
5503
  continue;
@@ -5367,6 +5533,12 @@ ${peer.address}`
5367
5533
  handlers.set(kind, /* @__PURE__ */ new Set());
5368
5534
  handlers.get(kind).add(cb);
5369
5535
  this.start();
5536
+ if (kind === "calls" && callsTable.length) {
5537
+ try {
5538
+ cb(null, callsTable);
5539
+ } catch (e) {
5540
+ }
5541
+ }
5370
5542
  if (kind === "call" && pendingCalls.length) {
5371
5543
  const queued = pendingCalls.splice(0);
5372
5544
  console.log("[rtc] flushing " + queued.length + " buffered call signal(s)");
@@ -5383,16 +5555,54 @@ ${peer.address}`
5383
5555
  return (_a = handlers.get(kind)) == null ? void 0 : _a.delete(cb);
5384
5556
  };
5385
5557
  },
5558
+ pageId,
5559
+ calls() {
5560
+ return callsTable;
5561
+ },
5386
5562
  async send(userid, data) {
5387
- const body = JSON.stringify({ userid, data: typeof data === "string" ? data : JSON.stringify(data) });
5563
+ const body = JSON.stringify({ userid, data: typeof data === "string" ? data : JSON.stringify(data), page: pageId });
5388
5564
  const r = await fetch("/api/call-signal", {
5389
5565
  method: "POST",
5390
5566
  headers: { "content-type": "application/json" },
5391
5567
  body
5392
5568
  });
5393
5569
  const d = await r.json().catch(() => ({ ok: r.ok }));
5394
- if (!d.ok)
5395
- throw new Error(d.error || "call-signal send failed");
5570
+ if (!d.ok) {
5571
+ const err = new Error(d.error || "call-signal send failed");
5572
+ if (d.answeredElsewhere)
5573
+ err.answeredElsewhere = true;
5574
+ throw err;
5575
+ }
5576
+ },
5577
+ // Claim an incoming call on the server before answering or declining it.
5578
+ // `won: false` = another page or client already has it. A server that
5579
+ // does not know the route (an older host) or does not answer within
5580
+ // 1.5 s counts as won — /api/call-signal still refuses a second answer.
5581
+ async claim(callId, peerId, action) {
5582
+ const ctl = typeof AbortController === "function" ? new AbortController() : null;
5583
+ const t = setTimeout(() => {
5584
+ try {
5585
+ if (ctl)
5586
+ ctl.abort();
5587
+ } catch (e) {
5588
+ }
5589
+ }, 1500);
5590
+ try {
5591
+ const r = await fetch("/api/call-claim", {
5592
+ method: "POST",
5593
+ headers: { "content-type": "application/json" },
5594
+ body: JSON.stringify({ callId, peerId, action, page: pageId }),
5595
+ signal: ctl ? ctl.signal : void 0
5596
+ });
5597
+ const d = await r.json().catch(() => null);
5598
+ if (!d || d.ok !== true || typeof d.won !== "boolean")
5599
+ return { won: true, unknown: true };
5600
+ return { won: d.won, call: d.call };
5601
+ } catch (e) {
5602
+ return { won: true, unknown: true };
5603
+ } finally {
5604
+ clearTimeout(t);
5605
+ }
5396
5606
  },
5397
5607
  stop() {
5398
5608
  stopped = true;
@@ -5423,7 +5633,7 @@ ${peer.address}`
5423
5633
  };
5424
5634
  }
5425
5635
  Object.assign(window, { dkRtcSignalBus, makeDaemonSignaling });
5426
- var CALL_END_STATES = /* @__PURE__ */ new Set(["noAnswer", "unreachable", "failed", "busy", "declined"]);
5636
+ var CALL_END_STATES = /* @__PURE__ */ new Set(["noAnswer", "unreachable", "failed", "busy", "declined", "elsewhere"]);
5427
5637
  var CALL_END_LINGER_MS = 3500;
5428
5638
  var EN = {
5429
5639
  calling: "calling\u2026",
@@ -5434,7 +5644,8 @@ ${peer.address}`
5434
5644
  cantReach: "Can't reach {name}",
5435
5645
  callFailed: "Call failed",
5436
5646
  busy: "Busy",
5437
- declined: "Declined"
5647
+ declined: "Declined",
5648
+ answeredElsewhere: "Answered elsewhere"
5438
5649
  };
5439
5650
  function str(T, key) {
5440
5651
  return T && T[key] || EN[key];
@@ -5460,6 +5671,8 @@ ${peer.address}`
5460
5671
  return str(T, "busy");
5461
5672
  case "declined":
5462
5673
  return str(T, "declined");
5674
+ case "elsewhere":
5675
+ return str(T, "answeredElsewhere");
5463
5676
  default:
5464
5677
  return state || "";
5465
5678
  }
@@ -5547,16 +5760,26 @@ ${peer.address}`
5547
5760
  return;
5548
5761
  }
5549
5762
  engine.on("incomingCall", (info) => {
5550
- const claimedAt = claimedCalls.current.get(String(info.callId).toLowerCase());
5551
- if (claimedAt && Date.now() - claimedAt < 5 * 6e4) {
5763
+ const pre = preAccepted.current.get(String(info.callId).toLowerCase());
5764
+ if (pre) {
5765
+ preAccepted.current.delete(String(info.callId).toLowerCase());
5766
+ setIncoming((i) => i && sameCall(i.callId, info.callId) ? null : i);
5767
+ engine.accept(info.callId).catch((e) => {
5768
+ console.warn("[call] accept after ring failed:", e && e.message || e);
5769
+ endWithReason((a) => sameCall(a.callId, info.callId), "failed");
5770
+ });
5771
+ return;
5772
+ }
5773
+ if (isSuppressed(claimedCalls.current, info.callId, Date.now())) {
5552
5774
  try {
5553
5775
  engine.discard && engine.discard(info.callId);
5554
5776
  } catch (e) {
5555
5777
  }
5556
5778
  return;
5557
5779
  }
5780
+ const wasRinging = incomingRef.current && sameCall(incomingRef.current.callId, info.callId);
5558
5781
  setIncoming(info);
5559
- if (onCallLogRef.current)
5782
+ if (!wasRinging && onCallLogRef.current)
5560
5783
  onCallLogRef.current(info.peerId, !!info.video, "incoming");
5561
5784
  });
5562
5785
  engine.on("stateChanged", (info, state) => setActive((a) => a && !a.ended && a.callId === info.callId ? { ...a, state } : a));
@@ -5664,6 +5887,81 @@ ${peer.address}`
5664
5887
  claimBus.current = null;
5665
5888
  };
5666
5889
  }, []);
5890
+ const preAccepted = React.useRef(/* @__PURE__ */ new Map());
5891
+ const silence = React.useCallback((callId) => {
5892
+ const inc = incomingRef.current;
5893
+ if (inc && sameCall(inc.callId, callId))
5894
+ setIncoming(null);
5895
+ const a = activeRef.current;
5896
+ if (a && sameCall(a.callId, callId))
5897
+ return;
5898
+ try {
5899
+ engineRef.current && engineRef.current.discard && engineRef.current.discard(callId);
5900
+ } catch (e) {
5901
+ }
5902
+ }, []);
5903
+ React.useEffect(() => {
5904
+ const bus = dkRtcSignalBus();
5905
+ const offCalls = bus.on("calls", (_u, table) => {
5906
+ const { stop, ended } = applyCallsTable(table, bus.pageId, claimedCalls.current, Date.now());
5907
+ for (const id of stop)
5908
+ silence(id);
5909
+ for (const id of ended) {
5910
+ if (preAccepted.current.has(id)) {
5911
+ preAccepted.current.delete(id);
5912
+ setActive((a) => a && sameCall(a.callId, id) && a.state === "connecting" ? null : a);
5913
+ }
5914
+ }
5915
+ });
5916
+ const offRing = bus.on("call-ring", (userid, env) => {
5917
+ if (!env || !env.callId || !userid)
5918
+ return;
5919
+ if (isSuppressed(claimedCalls.current, env.callId, Date.now()))
5920
+ return;
5921
+ if (preAccepted.current.has(String(env.callId).toLowerCase()))
5922
+ return;
5923
+ const a = activeRef.current;
5924
+ if (a && sameCall(a.callId, env.callId))
5925
+ return;
5926
+ const inc = incomingRef.current;
5927
+ if (inc && sameCall(inc.callId, env.callId))
5928
+ return;
5929
+ setIncoming({ callId: env.callId, peerId: userid, video: !!env.video, audio: true, ringOnly: true, callName: env.callName || env.name });
5930
+ if (onCallLogRef.current)
5931
+ onCallLogRef.current(userid, !!env.video, "incoming");
5932
+ try {
5933
+ bus.send(userid, window.PeerWebRTC.encodeSignal({ type: "event", event: "ringing", callId: env.callId })).catch(() => {
5934
+ });
5935
+ } catch (e) {
5936
+ }
5937
+ });
5938
+ const offStop = bus.on("call-ring-stop", (_u, env) => {
5939
+ if (!env || !env.callId)
5940
+ return;
5941
+ const id = String(env.callId).toLowerCase();
5942
+ if (env.reason === "answered" && preAccepted.current.has(id))
5943
+ return;
5944
+ if (!claimedCalls.current.has(id))
5945
+ claimedCalls.current.set(id, Date.now());
5946
+ silence(env.callId);
5947
+ if (env.reason !== "answered" && preAccepted.current.has(id)) {
5948
+ preAccepted.current.delete(id);
5949
+ setActive((a) => a && sameCall(a.callId, id) && a.state === "connecting" ? null : a);
5950
+ }
5951
+ });
5952
+ return () => {
5953
+ offCalls();
5954
+ offRing();
5955
+ offStop();
5956
+ };
5957
+ }, [silence]);
5958
+ const showElsewhere = React.useCallback((inc) => {
5959
+ silence(inc.callId);
5960
+ claimedCalls.current.set(String(inc.callId).toLowerCase(), Date.now());
5961
+ setActive({ callId: inc.callId, peerId: inc.peerId, video: inc.video, direction: "incoming", state: "elsewhere", ended: true });
5962
+ clearTimeout(lingerTimer.current);
5963
+ lingerTimer.current = setTimeout(() => setActive((a) => a && a.ended ? null : a), CALL_END_LINGER_MS);
5964
+ }, [silence]);
5667
5965
  const broadcastClaim = React.useCallback((inc, action) => {
5668
5966
  try {
5669
5967
  if (claimBus.current)
@@ -5678,29 +5976,66 @@ ${peer.address}`
5678
5976
  broadcastClaim(pending, "accepted");
5679
5977
  setIncoming(null);
5680
5978
  setActive({ callId: pending.callId, peerId: pending.peerId, video: pending.video, direction: "incoming", state: "connecting" });
5681
- waitEngine().then((eng) => {
5682
- if (!eng)
5683
- throw new Error("Calls unavailable (engine not ready)");
5684
- return eng.accept(pending.callId);
5979
+ const bus = dkRtcSignalBus();
5980
+ bus.claim(pending.callId, pending.peerId, "accepted").then((c) => {
5981
+ if (!c.won) {
5982
+ showElsewhere(pending);
5983
+ return null;
5984
+ }
5985
+ if (pending.ringOnly) {
5986
+ preAccepted.current.set(String(pending.callId).toLowerCase(), Date.now());
5987
+ return bus.send(pending.peerId, window.PeerWebRTC.encodeSignal({ type: "action", action: "accept", callId: pending.callId }));
5988
+ }
5989
+ return waitEngine().then((eng) => {
5990
+ if (!eng)
5991
+ throw new Error("Calls unavailable (engine not ready)");
5992
+ return eng.accept(pending.callId);
5993
+ });
5685
5994
  }).catch((e) => {
5995
+ if (e && e.answeredElsewhere) {
5996
+ showElsewhere(pending);
5997
+ return;
5998
+ }
5686
5999
  console.warn("[call] accept failed:", e && e.message || e);
5687
6000
  endWithReason((a) => a.callId === pending.callId, "failed");
5688
6001
  });
5689
- }, [waitEngine, endWithReason]);
6002
+ }, [waitEngine, endWithReason, broadcastClaim, showElsewhere]);
5690
6003
  const reject = React.useCallback(() => {
5691
- const eng = engineRef.current;
5692
6004
  const inc = incomingRef.current;
5693
- if (inc)
5694
- broadcastClaim(inc, "rejected");
5695
- if (eng && inc)
5696
- eng.reject(inc.callId);
5697
6005
  setIncoming(null);
5698
- }, [broadcastClaim]);
6006
+ if (!inc)
6007
+ return;
6008
+ broadcastClaim(inc, "rejected");
6009
+ const bus = dkRtcSignalBus();
6010
+ bus.claim(inc.callId, inc.peerId, "rejected").then((c) => {
6011
+ if (!c.won) {
6012
+ silence(inc.callId);
6013
+ return;
6014
+ }
6015
+ if (inc.ringOnly) {
6016
+ bus.send(inc.peerId, window.PeerWebRTC.encodeSignal({ type: "action", action: "reject", callId: inc.callId })).catch(() => {
6017
+ });
6018
+ return;
6019
+ }
6020
+ const eng = engineRef.current;
6021
+ if (eng)
6022
+ eng.reject(inc.callId);
6023
+ });
6024
+ }, [broadcastClaim, silence]);
5699
6025
  const hangup = React.useCallback(() => {
5700
6026
  const eng = engineRef.current;
5701
6027
  const a = activeRef.current;
5702
6028
  clearTimeout(lingerTimer.current);
5703
- if (eng && a && a.callId && !a.ended)
6029
+ const preId = a && a.callId ? String(a.callId).toLowerCase() : "";
6030
+ if (preId && preAccepted.current.has(preId) && !a.ended) {
6031
+ preAccepted.current.delete(preId);
6032
+ claimedCalls.current.set(preId, Date.now());
6033
+ try {
6034
+ dkRtcSignalBus().send(a.peerId, window.PeerWebRTC.encodeSignal({ type: "bye", reason: "normal", callId: a.callId })).catch(() => {
6035
+ });
6036
+ } catch (e) {
6037
+ }
6038
+ } else if (eng && a && a.callId && !a.ended)
5704
6039
  eng.hangup(a.callId);
5705
6040
  setActive(null);
5706
6041
  setLocalStream(null);
@@ -6964,6 +7299,8 @@ ${peer.address}`
6964
7299
  message: "Message",
6965
7300
  send: "Send",
6966
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",
6967
7304
  queued: "queued",
6968
7305
  sendingMsg: "sending",
6969
7306
  groupTag: "group",
@@ -7127,6 +7464,7 @@ ${peer.address}`
7127
7464
  callFailed: "Call failed",
7128
7465
  busy: "Busy",
7129
7466
  declined: "Declined",
7467
+ answeredElsewhere: "Answered elsewhere",
7130
7468
  joinGroup: "Join group",
7131
7469
  cardIsFriend: "Already in your chats.",
7132
7470
  cardNoEns: "No beagles.eth name registered.",
@@ -7191,6 +7529,8 @@ ${peer.address}`
7191
7529
  message: "\u6D88\u606F",
7192
7530
  send: "\u53D1\u9001",
7193
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",
7194
7534
  queued: "\u5F85\u53D1\u9001",
7195
7535
  sendingMsg: "\u53D1\u9001\u4E2D",
7196
7536
  groupTag: "\u7FA4",
@@ -7354,6 +7694,7 @@ ${peer.address}`
7354
7694
  callFailed: "\u901A\u8BDD\u5931\u8D25",
7355
7695
  busy: "\u5BF9\u65B9\u5FD9",
7356
7696
  declined: "\u5BF9\u65B9\u5DF2\u62D2\u7EDD",
7697
+ answeredElsewhere: "\u5DF2\u5728\u5176\u4ED6\u8BBE\u5907\u63A5\u542C",
7357
7698
  joinGroup: "\u52A0\u5165\u7FA4",
7358
7699
  cardIsFriend: "\u5DF2\u5728\u4F60\u7684\u4F1A\u8BDD\u91CC\u3002",
7359
7700
  cardNoEns: "\u5BF9\u65B9\u8FD8\u6CA1\u6709\u6CE8\u518C beagles.eth \u540D\u5B57\u3002",