@ghostlytools/cli 1.10.6 → 1.11.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. package/README.md +27 -22
  2. package/SKILL.md +8 -5
  3. package/dist/assets/api-D89ubgas.js +3 -0
  4. package/dist/assets/{api-DppWqAP3.js → api-DL0Uazf6.js} +543 -204
  5. package/dist/assets/api-DL0Uazf6.js.map +1 -0
  6. package/dist/assets/{apiKit-DFIho4Ev.js → apiKit-D78MXTrk.js} +97 -13
  7. package/dist/assets/apiKit-D78MXTrk.js.map +1 -0
  8. package/dist/assets/{apps-yBnbEtfV.js → apps--pAqmfgQ.js} +16 -4
  9. package/dist/assets/apps--pAqmfgQ.js.map +1 -0
  10. package/dist/assets/{apps-1MkGMH8m.js → apps-BlSl1nGn.js} +1 -1
  11. package/dist/assets/{arkade-bFAS6imn.js → arkade-DxB-MR43.js} +2 -2
  12. package/dist/assets/{arkade-bFAS6imn.js.map → arkade-DxB-MR43.js.map} +1 -1
  13. package/dist/assets/{backup-vj4J7M3e.js → backup-B3JJd75o.js} +35 -7
  14. package/dist/assets/backup-B3JJd75o.js.map +1 -0
  15. package/dist/assets/{backup-ejIX59o7.js → backup-T7gFpU80.js} +1 -1
  16. package/dist/assets/bark_ffi_wasm_bg-EY2uc0Bx.js.map +1 -1
  17. package/dist/assets/bitcoindevkit_bg-B-iLWrmX.js.map +1 -1
  18. package/dist/assets/{blobFiles-XZ9PEXYy.js → blobFiles-BmsrvZc3.js} +3 -3
  19. package/dist/assets/{blobFiles-XZ9PEXYy.js.map → blobFiles-BmsrvZc3.js.map} +1 -1
  20. package/dist/assets/{buttons-BoDMx3Ky.js → buttons-C1VbDihe.js} +61 -30
  21. package/dist/assets/buttons-C1VbDihe.js.map +1 -0
  22. package/dist/assets/buttons-DwWuK_uN.js +2 -0
  23. package/dist/assets/{client-BQArefYa.js → client-CGLuWFRV.js} +55 -10
  24. package/dist/assets/client-CGLuWFRV.js.map +1 -0
  25. package/dist/assets/{codec-_MwTUz5E.js → codec-YGJDr7uH.js} +2 -2
  26. package/dist/assets/{codec-_MwTUz5E.js.map → codec-YGJDr7uH.js.map} +1 -1
  27. package/dist/assets/{envelope-CeZBNGX-.js → envelope-Dwq8EN8x.js} +2 -2
  28. package/dist/assets/{envelope-CeZBNGX-.js.map → envelope-Dwq8EN8x.js.map} +1 -1
  29. package/dist/assets/{irohWeb-C_Wnw7Q9.js → fedimintSdk-CqTeMdF0.js} +2 -354
  30. package/dist/assets/fedimintSdk-CqTeMdF0.js.map +1 -0
  31. package/dist/assets/{fileBytes-DqnfKIkj.js → fileBytes-B0z9A6Le.js} +2 -2
  32. package/dist/assets/{fileBytes-DqnfKIkj.js.map → fileBytes-B0z9A6Le.js.map} +1 -1
  33. package/dist/assets/{fileBytes-BABGEF13.js → fileBytes-BLPZq9YU.js} +3 -3
  34. package/dist/assets/{fileBytes-BABGEF13.js.map → fileBytes-BLPZq9YU.js.map} +1 -1
  35. package/dist/assets/{fileBytes-CQQK2uOh.js → fileBytes-BtIyoDF2.js} +1 -1
  36. package/dist/assets/{fileBytesIdb-DrXmDUSy.js → fileBytesIdb-Bmlrl9EO.js} +3 -3
  37. package/dist/assets/{fileBytesIdb-DrXmDUSy.js.map → fileBytesIdb-Bmlrl9EO.js.map} +1 -1
  38. package/dist/assets/fileBytesIdb-D8mAK4pF.js +2 -0
  39. package/dist/assets/{fileBytesOpfs-udKCzcLe.js → fileBytesOpfs-DBS0kbPT.js} +3 -3
  40. package/dist/assets/{fileBytesOpfs-udKCzcLe.js.map → fileBytesOpfs-DBS0kbPT.js.map} +1 -1
  41. package/dist/assets/{fixedHosts-B_2Rvyja.js → fixedHosts-CINXidpd.js} +3 -3
  42. package/dist/assets/{fixedHosts-B_2Rvyja.js.map → fixedHosts-CINXidpd.js.map} +1 -1
  43. package/dist/assets/{host-DFLzzKNr.js → host-CGlHkiQv.js} +336 -84
  44. package/dist/assets/host-CGlHkiQv.js.map +1 -0
  45. package/dist/assets/{hyperdhtRelay-CV6qMrom.js → hyperdhtRelay-Bj5jJT5w.js} +2 -2
  46. package/dist/assets/{hyperdhtRelay-CV6qMrom.js.map → hyperdhtRelay-Bj5jJT5w.js.map} +1 -1
  47. package/dist/assets/{idb-BHsAqENE.js → idb-CEuoNsTv.js} +16 -5
  48. package/dist/assets/idb-CEuoNsTv.js.map +1 -0
  49. package/dist/assets/{groupFiles-D-ZUUHrx.js → irohWeb-CYn0uB_A.js} +471 -18
  50. package/dist/assets/irohWeb-CYn0uB_A.js.map +1 -0
  51. package/dist/assets/{main-DxRwajM_.js → main-CgLW_Gyx.js} +409 -126
  52. package/dist/assets/main-CgLW_Gyx.js.map +1 -0
  53. package/dist/assets/{mainline-Bx184Ixg.js → mainline-B0h8RchD.js} +2 -2
  54. package/dist/assets/{mainline-Bx184Ixg.js.map → mainline-B0h8RchD.js.map} +1 -1
  55. package/dist/assets/{networkReason-BlQhTbXk.js → networkReason-BBosp2KG.js} +4 -4
  56. package/dist/assets/{networkReason-BlQhTbXk.js.map → networkReason-BBosp2KG.js.map} +1 -1
  57. package/dist/assets/{nwc-B3-PHX0L.js → nwc-SSNS1aJ-.js} +4 -4
  58. package/dist/assets/nwc-SSNS1aJ-.js.map +1 -0
  59. package/dist/assets/{nwcProvider-BeQBPB2q.js → nwcProvider-BXqJmM98.js} +11 -3
  60. package/dist/assets/nwcProvider-BXqJmM98.js.map +1 -0
  61. package/dist/assets/{ownDid-DAzW-Urb.js → ownDid--DtH_Jdi.js} +2 -2
  62. package/dist/assets/{ownDid-DAzW-Urb.js.map → ownDid--DtH_Jdi.js.map} +1 -1
  63. package/dist/assets/{words-BvdNuw_v.js → ownStatus-CQPGjCUR.js} +56 -4
  64. package/dist/assets/ownStatus-CQPGjCUR.js.map +1 -0
  65. package/dist/assets/{profiles-Bg43mRXu.js → profiles-4UQ1Hsds.js} +22 -12
  66. package/dist/assets/profiles-4UQ1Hsds.js.map +1 -0
  67. package/dist/assets/{registry-CAk2-5BQ.js → registry-B6BXKv6Q.js} +1 -1
  68. package/dist/assets/{registry-BDnsZJBi.js → registry-BKCFTEYp.js} +123 -99
  69. package/dist/assets/registry-BKCFTEYp.js.map +1 -0
  70. package/dist/assets/{resolve-UAfshn6j.js → resolve-MFeFljsN.js} +2 -2
  71. package/dist/assets/{resolve-UAfshn6j.js.map → resolve-MFeFljsN.js.map} +1 -1
  72. package/dist/assets/{restoredRows-YhlbokEE.js → restoredRows-C3LcxmOw.js} +4 -4
  73. package/dist/assets/{restoredRows-YhlbokEE.js.map → restoredRows-C3LcxmOw.js.map} +1 -1
  74. package/dist/assets/{server-DYdR0_Fj.js → server-rHKhnog1.js} +2100 -685
  75. package/dist/assets/server-rHKhnog1.js.map +1 -0
  76. package/dist/assets/{src-BTRPAi5X.js → src-BzsyAvPf.js} +1604 -305
  77. package/dist/assets/src-BzsyAvPf.js.map +1 -0
  78. package/dist/assets/{sshForges-KtHK5x1x.js → sshForges-qITn-RoV.js} +2 -2
  79. package/dist/assets/{sshForges-KtHK5x1x.js.map → sshForges-qITn-RoV.js.map} +1 -1
  80. package/dist/assets/{translate-CYuygrvA.js → translate-Bkr_iDgp.js} +9 -7
  81. package/dist/assets/translate-Bkr_iDgp.js.map +1 -0
  82. package/dist/assets/{usdt-Dw9IENe_.js → usdt-Bp7T2iqt.js} +3 -3
  83. package/dist/assets/{usdt-Dw9IENe_.js.map → usdt-Bp7T2iqt.js.map} +1 -1
  84. package/dist/assets/{waitNotice-Ce3YCinu.js → waitNotice-Cn0WJ-He.js} +3 -1
  85. package/dist/assets/waitNotice-Cn0WJ-He.js.map +1 -0
  86. package/dist/ghostly.mjs +1 -1
  87. package/examples/claude-code-agent.sh +5 -0
  88. package/package.json +2 -2
  89. package/dist/assets/api-DppWqAP3.js.map +0 -1
  90. package/dist/assets/api-K-i5MrP-.js +0 -3
  91. package/dist/assets/apiKit-DFIho4Ev.js.map +0 -1
  92. package/dist/assets/apps-yBnbEtfV.js.map +0 -1
  93. package/dist/assets/backup-vj4J7M3e.js.map +0 -1
  94. package/dist/assets/buttons-BoDMx3Ky.js.map +0 -1
  95. package/dist/assets/buttons-DG1CKgAI.js +0 -2
  96. package/dist/assets/client-BQArefYa.js.map +0 -1
  97. package/dist/assets/fileBytesIdb-BtXATa7j.js +0 -2
  98. package/dist/assets/groupFiles-D-ZUUHrx.js.map +0 -1
  99. package/dist/assets/host-DFLzzKNr.js.map +0 -1
  100. package/dist/assets/idb-BHsAqENE.js.map +0 -1
  101. package/dist/assets/irohWeb-C_Wnw7Q9.js.map +0 -1
  102. package/dist/assets/main-DxRwajM_.js.map +0 -1
  103. package/dist/assets/nwc-B3-PHX0L.js.map +0 -1
  104. package/dist/assets/nwcProvider-BeQBPB2q.js.map +0 -1
  105. package/dist/assets/profiles-Bg43mRXu.js.map +0 -1
  106. package/dist/assets/registry-BDnsZJBi.js.map +0 -1
  107. package/dist/assets/server-DYdR0_Fj.js.map +0 -1
  108. package/dist/assets/src-BTRPAi5X.js.map +0 -1
  109. package/dist/assets/translate-CYuygrvA.js.map +0 -1
  110. package/dist/assets/waitNotice-Ce3YCinu.js.map +0 -1
  111. package/dist/assets/words-BvdNuw_v.js.map +0 -1
@@ -1,17 +1,17 @@
1
1
  import { n as traceJoin } from "./joinTrace-CjRDFy85.js";
2
- import { $a as ReactionWindow, $c as openRequest, $i as HOLD_DATED_BACK_MS, $l as deviceEchoFrame, $n as engineError, $o as PRESENCE_WINDOW, $r as PIN_LIMITS, $s as handoffReleaseFrame, $t as ONCHAIN_PROVIDER, $u as sanitizeDisplayText, A as knockIdentity, Ac as enrollProofFrame, An as ENDPOINT, Ao as claimedTime, Ar as lobbyKeys, As as HANDOFF_HELLO, Au as currentRelays, Ba as EDIT_RATE_WINDOW_MS, Bc as takeRequest, Bl as createDeviceInvite, Bn as NO_PICTURE_METADATA, Bo as rosterAdmin, Br as shouldBeHub, Bs as handoffAttemptFailed, C as communityHasFrame, Ca as peekDhtMailbox, Ci as UPGRADE_CAPABILITY, Cl as isAppHash, Cr as pickMeshHubs, Cs as HTTP_SERVICE_PROTO, Cu as turnVerifierMark, D as decodeGroupEntryLink, Da as sanitizeFileName, Dc as enrollDoneFrame, Di as dialDescriptors, Dl as readAppRevocationShape, Dr as doorHubs, Ds as HANDOFF_CANCEL, Du as RelayTransport, Ea as formatFileSize, Ec as enrollDigits, Ei as capsDescriptors, El as readAppRevocation, Eo as sameButtonText, Er as beaconRecords, Es as HANDOFF_ACK, F as GroupWakeLimiter, Fa as parseVoiceMeta, Fc as endedRequests, Fi as emptyIdentityLedger, Fn as parseCashuRequestPayload, Fo as GROUP_MEMBER_CAP, Fr as pickHubs, Fs as HANDOFF_TIMINGS, Gc as contactAskerHolds, Gi as emptyProofLedger, Gl as decodeInviteCode, Gn as GhostLink, Go as RatchetBox, Gr as transferEnded, Gs as handoffContextProof, Gt as didDhtDocument, Gu as createIdentity, H as GroupSession, Ha as REMOVED_TEXT, Hc as ContactRequestError, Hl as readDeviceInvite, Hn as isStrippedPicture, Ho as verifyCommitSignature, Hr as FILE_LIMITS, Hs as handoffBusyFrame, I as groupWakeFrame, Ic as inboxRecord, Il as readCanonicalJson, In as parseFedimintRequestPayload, Ir as rankHubs, Is as HANDOFF_VERIFIED, Iu as budgetRetryMs, J as meshMessageRef, Ja as forwardedAgain, Jc as knockSlotOf, Ji as automaticTransport, Jl as inviteOwnership, Jn as PAIRED_FRAME_TOO_LARGE, Jo as DirectPathWatch, Js as handoffEphemeral, Jt as encodeDidDhtPacket, Ju as publicKeyFromZ32, K as GROUP_EDIT_TEXT_BYTES, Kc as contactDay, Ki as validExternalKey, Kl as encodeInviteCode, Kn as INVITE_TAKEN, Ko as emptyRatchetState, Kr as transferStalled, Ks as handoffDataFrame, Kt as didDhtFromPublicKey, Ku as identityFromSeed, L as groupWakes, Lc as newInbox, Ll as createContactLink, Lo as MEMBER_KEY, Lr as readBeacon, Ls as NO_ATTEMPTS, Lu as isDiscoveryBudgetError, M as mergeKnocks, Mc as readEnrollHello, Ml as parseImageMeta, Mn as fedimintRequestPayload, Mo as receivedTimestamp, Mr as mergeBeacon, Ms as HANDOFF_PAKE, N as readKnocks, Nc as verifyEnrollProof, Nn as findEndpoint, No as shownTime, Nr as mergeLobby, Ns as HANDOFF_PIECE_BYTES, O as encodeGroupEntryLink, Oa as sanitizeMime, Oc as enrollGrantFrame, Oo as statusCardText, Or as freshHubs, Os as HANDOFF_DONE, Pa as fileMessageText, Pc as clearMissed, Pl as canonicalJson, Pn as isFederationId, Po as GROUP_ADMIN_OFF_ERROR, Pr as newerHead, Ps as HANDOFF_REQUEST, Pu as traceLink, Qa as REACTION_LIMITS, Qc as mergeContactKnocks, Qi as HOLD_CAPABILITY, Ql as HANDOFF_CAPABILITY, Qn as EngineError, Qs as handoffPakeFrame, Qt as EVM_TEST_CHAINS, Qu as hasVisible, R as parseGroupWakeFrame, Ra as parseVideoMeta, Rc as planKnocks, Rl as encodeContactLink, Rn as videoMetadataPatches, Ro as commitHash, Rr as readBeaconHead, Rs as filePartName, Ru as withRequestOptions, S as GROUP_READ_NOTE_COMMUNITY, Sa as DHT_MESSAGE_TTL, Si as STATUS_CARD_CAPABILITY, Sr as meshHubs, Ss as emptyLinkRecords, Su as turnStatedVerifier, T as encodeCommunityLink, Ta as dhtFileId, Tc as enrollCancelReason, Ti as DHT_TEXT_CAPABILITY, Tl as isAppRef, To as checkStatusCard, Tr as beaconKeys, Ts as serviceIdFromName, U as frameBytes, Ua as RateWindow, Uc as REQUEST_LIFETIME_MS, Ui as lastSharedWithMe, Ul as OwnInviteError, Un as stripPictureMetadata, Uo as edgeParams, Us as handoffCancelFrame, V as GROUP_READ_NOTE, Va as MAX_REMOVAL_NUMBER, Vc as turnOff, Vi as receivedIdentityStatus, Vl as deviceInviteJoinerParams, Vn as PICTURE_METADATA_LIMITS, Vo as rosterHas, Vr as ChatFiles, Vs as handoffAttemptSucceeded, Vu as createRelayPayload, Wa as dhtEditId, Wc as contactAskerFrame, Wi as PeerProofs, Wl as createChatInvite, Wo as RATCHET_CAPABILITY, Wr as sentWhole, Ws as handoffContext, X as mentionsMember, Xa as COMMUNITY_REACTION_FRAME, Xc as linkRecords, Xl as DEVICES_CAPABILITY, Xn as pairedMessageFits, Xs as handoffManifestFrames, Xt as signDidDhtPacket, Y as parseCommunityEdit, Ya as readForwarded, Yc as knockSlotRecords, Yn as pairedEditFits, Yr as TypingSender, Ys as handoffHelloFrame, Yu as verify, Z as groupName, Za as GROUP_REACTION_FRAME, Zc as makeStampPaced, Zl as ENROLL_CAPABILITY, Zn as pairedMessageFrame, Zo as DHT_POLL_INTERVALS, Zr as typingActivity, Zs as handoffOfferFrame, Zt as ETHEREUM_USDT, Zu as sanitizeAvatar, _ as groupTypingEpoch, _c as setUpdateFrame, _i as chatAppId, _t as isAtprotoDid, _u as signTurnPacket, a as appRevocationFor, aa as readManifest, ac as readHandoffCancel, ad as toBase64Url, ai as WAKE_CALL_INTERVAL_MS, al as APP_BUNDLE_MAGIC, an as WALLET_NETWORKS, ao as validReactionNumber, as as parseLocalTarget, au as seedSigner, b as COMMUNITY_LIMITS, bi as BUTTONS_CAPABILITY, bl as appRef, br as MESH_HUBS, bs as parseCallSignal, bu as turnKeys, c as checkAppBeforeRun, cc as readHandoffHello, cd as utf8Encode, ci as newWakeToken, cl as appDigest, cn as assertWholeSats, co as readReply, cs as decodeControl, cu as TURN_RAISE_READ_TIMEOUT_MS, dc as readHandoffVerified, di as wakeRequest, dn as walletNetworkOf, du as turnPutSummary, ea as HOLD_LIMITS, ec as handoffRetryAfter, ed as stripHidden, ei as mayPin, el as readKnockSlot, en as PaymentPreflightError, eo as nextReactionNumber, er as engineText, es as RELAY_POLL_INTERVALS, eu as deviceEchoNonce, fc as sealHandoffPiece, fi as checkPushEndpoint, fl as isAppUrl, fn as SPARK_NETWORKS, fu as TURN_LAST_SEQUENCE, g as GroupTypingBoard, gc as setAckFrame, gl as sha256Paced, gn as isBitcoinAddress, gu as readTurnPacket, hc as readSetUpdate, hi as isServeId, hl as readAppBundleAsync, hn as sparkInvoiceDetails, hu as nextTurnPosition, i as addedAppPermissions, ia as newMailbox, ic as readHandoffAck, id as randomBytes, ii as readPin, il as APP_BUNDLE_LIMITS, in as USDT_PUBLIC_RPC, io as readReaction, is as formatLocalTarget, iu as newDeviceSetSecret, j as knockRecords, jc as readEnrollGrant, jn as cashuRequestPayload, jo as heardTime, jr as lobbyRecords, js as HANDOFF_OFFER, ju as normalizeRelayUrl, k as entryParams, kc as enrollHelloFrame, kn as decodeBolt11, ko as arrivalKey, kr as hubRank, ks as HANDOFF_HAVE, l as planAppUpdate, lc as readHandoffPake, li as parseWakeFrame, ll as appViewOf, ln as formatPaymentAmount, lo as replySnippet, lr as readGroupFileMeta, ls as encodeControl, lu as TURN_SETTLE_MS, mi as APP_RANGE_LIMITS, mn as sparkAddressKind, mu as firstDeviceSetSecret, n as readX401SdJwtVc, na as HoldRefusedError, nc as handoffVersions, nd as fromBase64Url, ni as pinIsNewer, nl as requestRecords, no as reactionEmoji, nr as GROUP_FILE_LIMITS, ns as presenceSeenAt, nu as deviceLinkPairing, o as appStoreDecision, oc as readHandoffDone, od as toZ32, oi as WakeLimiter, on as arkAddressPrefix, oo as wireReaction, os as webLocalFetch, ou as webCryptoSigner, p as readAppStoreSteps, pi as vapidKeysMatch, pl as pacer, pn as SPARK_PROVIDER, pr as CarriedTransport, ps as RTC_CONFIG, pu as TURN_MAX, q as carryMentions, qa as parseLinkPreview, qc as knockSlotIdentity, qi as TRANSPORTS, ql as inviteLink, qn as LIVENESS_PING_MS, qo as ratchetSessionOf, qs as handoffDigest, qt as encodeDidDhtDeactivated, qu as identityFromSeedB64, r as sameX401HolderJwk, ra as isHoldUrl, rc as newHandoffId, ri as pinNumberHolds, rl as seenEntry, rn as TEST_USDT_FAUCET_AMOUNT, ro as reactionIsNewer, rr as GROUP_HAVE_FRAME, rs as GhostlyHttpError, ru as devicePingFrame, s as appUpdateDecision, sc as readHandoffHave, sd as utf8Decode, si as deviceWakeRequest, sn as assertTokenUnits, so as pairedReplyAuthor, sr as groupFileFallback, ss as LIMITS, t as newX401HolderKey, ta as HoldKeys, tc as handoffStreamKey, td as bytesEqual, ti as nextPinNumber, tl as readLinkRecord, tn as SEPOLIA_TEST_USDT, to as queueReaction, tr as parseEngineError, ts as WATCH_PEER_MS, tu as deviceKeyZ32, u as APP_STORE_LIMITS, uc as readHandoffTurnFrame, ui as relayRequest, un as validatePaymentTarget, uo as BUTTON_ID, uu as classifyTurnRead, v as openGroupTyping, vc as signTombstone, vi as isAppVersion, vl as APP_STATEMENT_LIMITS, vn as isPubkyKey, vo as STATUS_CARD_LIMITS, vr as groupSignalFrame, vs as contactRtcConfig, vt as normalizeAtprotoHandle, vu as signTurnRelease, w as decodeCommunityLink, wa as DHT_FILE_CAPABILITY, wc as enrollCancelFrame, wi as CapsExchange, wl as isAppKey, wr as COMMUNITY_TOPOLOGY, ws as LEGACY_SERVICES, wu as DEFAULT_RELAYS, x as CommunitySession, xi as EDIT_CAPABILITY, xl as appRefPublisher, xr as mayBeHub, xu as turnName, y as sealGroupTyping, yc as verifySetUpdate, yi as APPS_CAPABILITY, yl as appFingerprint, yr as readGroupSignal, yu as turnInstance, z as GROUP_LIMITS, za as EDIT_BUFFER_MS, zc as settleRequest, zl as readContactLink, zn as withoutVideoMetadata, zo as parseGroupCommit, zr as readLobby, zs as handoffAttemptAllowed, zu as PacketTooLargeError } from "./src-BTRPAi5X.js";
2
+ import { $a as REMOVED_TEXT, $c as turnOff, $l as createDeviceInvite, $n as pairedMessageFits, $o as rosterHas, $r as personStatus, $s as handoffAttemptSucceeded, $t as ONCHAIN_PROVIDER, A as knockIdentity, Ac as signTombstone, Ai as APPS_CAPABILITY, Al as APP_STATEMENT_LIMITS, An as ENDPOINT, Ar as doorHubs, As as contactRtcConfig, Au as signTurnPacket, Bc as enrollGrantFrame, Bl as readAppRevocationShape, Br as readBeacon, Bs as HANDOFF_DONE, Bu as RelayTransport, C as communityHasFrame, Cc as readHandoffVerified, Ci as checkPushEndpoint, Cr as MESH_HUBS, Cu as classifyTurnRead, D as decodeGroupEntryLink, Dc as readSetUpdate, Dl as readAppBundleAsync, Dr as COMMUNITY_TOPOLOGY, Du as firstDeviceSetSecret, Ei as isServeId, Er as pickMeshHubs, Eu as TURN_MAX, F as GroupWakeLimiter, Fa as DHT_FILE_CAPABILITY, Fi as CapsExchange, Fl as isAppHash, Fn as parseCashuRequestPayload, Fr as mergeBeacon, Fs as HTTP_SERVICE_PROTO, Fu as turnStatedVerifier, Ga as fileMessageText, Gc as verifyEnrollProof, Gl as parseImageMeta, Gn as isStrippedPicture, Go as shownTime, Gr as FILE_LIMITS, Gs as HANDOFF_PIECE_BYTES, Gt as didDhtDocument, H as GroupSession, Hc as enrollProofFrame, Hn as withoutVideoMetadata, Ho as claimedTime, Hr as readLobby, Hs as HANDOFF_HELLO, I as groupWakeFrame, Ia as dhtFileId, Ic as enrollCancelFrame, Ii as DHT_TEXT_CAPABILITY, Il as isAppKey, In as parseFedimintRequestPayload, Io as checkStatusCard, Ir as mergeLobby, Is as LEGACY_SERVICES, Iu as turnVerifierMark, J as meshMessageRef, Jc as inboxRecord, Jl as canonicalJsonBytes, Jn as GhostLink, Jr as transferEnded, Js as HANDOFF_VERIFIED, Jt as encodeDidDhtPacket, K as GROUP_EDIT_TEXT_BYTES, Ka as parseVoiceMeta, Kc as clearMissed, Ki as emptyIdentityLedger, Kn as stripPictureMetadata, Ko as GROUP_ADMIN_OFF_ERROR, Ks as HANDOFF_REQUEST, Kt as didDhtFromPublicKey, L as groupWakes, La as formatFileSize, Lc as enrollCancelReason, Li as capsDescriptors, Lo as sameButtonText, Lr as newerHead, Ls as serviceIdFromName, Lu as DEFAULT_RELAYS, M as mergeKnocks, Mi as EDIT_CAPABILITY, Ml as appRef, Mn as fedimintRequestPayload, Mr as hubRank, Ms as parseCallSignal, Mu as turnInstance, N as readKnocks, Na as DHT_MESSAGE_TTL, Ni as STATUS_CARD_CAPABILITY, Nl as appRefPublisher, Nn as findEndpoint, Nr as lobbyKeys, Nu as turnKeys, O as encodeGroupEntryLink, Oc as setAckFrame, Oi as chatAppId, Ol as sha256Paced, Or as beaconKeys, Ou as nextTurnPosition, Pa as peekDhtMailbox, Pi as UPGRADE_CAPABILITY, Pn as isFederationId, Pr as lobbyRecords, Ps as emptyLinkRecords, Pu as turnName, Qa as MAX_REMOVAL_NUMBER, Qc as takeRequest, Qi as receivedIdentityStatus, Ql as readContactLink, Qn as pairedEditFits, Qo as rosterAdmin, Qr as liveStatus, Qs as handoffAttemptFailed, Qt as EVM_TEST_CHAINS, Qu as PacketTooLargeError, R as parseGroupWakeFrame, Ra as sanitizeFileName, Rc as enrollDigits, Ri as dialDescriptors, Rl as isAppRef, Rn as audioMetadataPatches, Rr as pickHubs, Rs as HANDOFF_ACK, S as GROUP_READ_NOTE_COMMUNITY, Sc as readHandoffTurnFrame, Si as wakeRequest, Sr as readGroupSignal, Su as TURN_SETTLE_MS, T as encodeCommunityLink, Ti as APP_RANGE_LIMITS, Tl as pacer, Tr as meshHubs, Ts as RTC_CONFIG, Tu as TURN_LAST_SEQUENCE, U as frameBytes, Uc as readEnrollGrant, Un as NO_PICTURE_METADATA, Uo as heardTime, Ur as shouldBeHub, Us as HANDOFF_OFFER, Uu as currentRelays, V as GROUP_READ_NOTE, Vc as enrollHelloFrame, Vn as videoMetadataPatches, Vo as arrivalKey, Vr as readBeaconHead, Vs as HANDOFF_HAVE, Wc as readEnrollHello, Wn as PICTURE_METADATA_LIMITS, Wo as receivedTimestamp, Wr as ChatFiles, Ws as HANDOFF_PAKE, Wu as normalizeRelayUrl, X as mentionsMember, Xa as EDIT_BUFFER_MS, Xc as planKnocks, Xl as createContactLink, Xn as LIVENESS_PING_MS, Xo as commitHash, Xs as filePartName, Xt as signDidDhtPacket, Xu as isDiscoveryBudgetError, Y as parseCommunityEdit, Ya as parseVideoMeta, Yc as newInbox, Yl as readCanonicalJson, Yn as INVITE_TAKEN, Yo as MEMBER_KEY, Yr as transferStalled, Ys as NO_ATTEMPTS, Yu as budgetRetryMs, Z as groupName, Za as EDIT_RATE_WINDOW_MS, Zc as settleRequest, Zl as encodeContactLink, Zn as PAIRED_FRAME_TOO_LARGE, Zo as parseGroupCommit, Zr as STATUS_IDLE_AFTER_MS, Zs as handoffAttemptAllowed, Zt as ETHEREUM_USDT, Zu as withRequestOptions, _ as groupTypingEpoch, _c as readHandoffCancel, _d as randomBytes, _i as WakeLimiter, _l as APP_BUNDLE_MAGIC, _o as wireReaction, _s as parseLocalTarget, _t as isAtprotoDid, _u as newDeviceSetSecret, a as appRevocationFor, aa as automaticTransport, ac as handoffDigest, ad as identityFromSeed, ai as typingActivity, al as knockSlotIdentity, an as WALLET_NETWORKS, ao as forwardedAgain, ar as GROUP_FILE_LIMITS, as as ratchetSessionOf, au as encodeInviteCode, b as COMMUNITY_LIMITS, bc as readHandoffHello, bd as utf8Decode, bi as parseWakeFrame, bl as appDigest, bo as replySnippet, bs as decodeControl, c as checkAppBeforeRun, cc as handoffManifestFrames, cd as verify, ci as mayPin, cl as linkRecords, cn as assertWholeSats, co as GROUP_REACTION_FRAME, da as HOLD_LIMITS, dc as handoffReleaseFrame, dd as hasVisible, di as pinNumberHolds, dl as openRequest, dn as walletNetworkOf, do as nextReactionNumber, ds as PRESENCE_WINDOW, du as HANDOFF_CAPABILITY, ea as lastSharedWithMe, ec as handoffBusyFrame, ed as createRelayPayload, el as ContactRequestError, en as PaymentPreflightError, eo as RateWindow, er as pairedMessageFrame, es as verifyCommitSignature, eu as deviceInviteJoinerParams, fa as HoldKeys, fc as handoffRetryAfter, fd as sanitizeDisplayText, fi as readPin, fl as readKnockSlot, fn as SPARK_NETWORKS, fo as queueReaction, fr as readGroupFileMeta, fs as RELAY_POLL_INTERVALS, fu as deviceEchoFrame, g as GroupTypingBoard, ga as readManifest, gc as readHandoffAck, gl as APP_BUNDLE_LIMITS, gn as isBitcoinAddress, go as validReactionNumber, gr as CarriedTransport, gs as formatLocalTarget, gu as devicePingFrame, ha as newMailbox, hc as newHandoffId, hd as fromBase64Url, hi as WAKE_ONLINE_DELAY_MS, hl as seenEntry, hn as sparkInvoiceDetails, ho as readReaction, hs as GhostlyHttpError, hu as deviceLinkPairing, i as addedAppPermissions, ia as TRANSPORTS, ic as handoffDataFrame, id as createIdentity, il as contactDay, in as USDT_PUBLIC_RPC, io as parseLinkPreview, ir as parseEngineError, is as emptyRatchetState, iu as decodeInviteCode, j as knockRecords, jc as verifySetUpdate, ji as BUTTONS_CAPABILITY, jl as appFingerprint, jn as cashuRequestPayload, jr as freshHubs, ju as signTurnRelease, k as entryParams, kc as setUpdateFrame, ki as isAppVersion, kn as decodeBolt11, ko as STATUS_CARD_LIMITS, kr as beaconRecords, ku as readTurnPacket, l as planAppUpdate, la as HOLD_CAPABILITY, lc as handoffOfferFrame, li as nextPinNumber, ll as makeStampPaced, ln as formatPaymentAmount, lo as REACTION_LIMITS, ls as DHT_POLL_INTERVALS, lu as DEVICES_CAPABILITY, ma as isHoldUrl, mc as handoffVersions, md as bytesEqual, mi as WAKE_ONLINE_BATCH_MS, ml as requestRecords, mn as sparkAddressKind, mo as reactionIsNewer, ms as presenceSeenAt, mu as deviceKeyZ32, n as readX401SdJwtVc, na as emptyProofLedger, nc as handoffContext, nl as contactAskerFrame, nr as engineError, ns as RATCHET_CAPABILITY, nu as OwnInviteError, o as appStoreDecision, oc as handoffEphemeral, od as identityFromSeedB64, ol as knockSlotOf, on as arkAddressPrefix, oo as readForwarded, or as GROUP_HAVE_FRAME, os as DirectPathWatch, ou as inviteLink, p as readAppStoreSteps, pa as HoldRefusedError, pc as handoffStreamKey, pd as stripHidden, pi as WAKE_CALL_INTERVAL_MS, pl as readLinkRecord, pn as SPARK_PROVIDER, po as reactionEmoji, ps as WATCH_PEER_MS, pu as deviceEchoNonce, q as carryMentions, qc as endedRequests, ql as canonicalJson, qo as GROUP_MEMBER_CAP, qr as sentWhole, qs as HANDOFF_TIMINGS, qt as encodeDidDhtDeactivated, qu as traceLink, r as sameX401HolderJwk, ra as validExternalKey, rc as handoffContextProof, ri as TypingSender, rl as contactAskerHolds, rn as TEST_USDT_FAUCET_AMOUNT, rr as engineText, rs as RatchetBox, ru as createChatInvite, s as appUpdateDecision, sc as handoffHelloFrame, sd as publicKeyFromZ32, si as PIN_LIMITS, sl as knockSlotRecords, sn as assertTokenUnits, so as COMMUNITY_REACTION_FRAME, su as inviteOwnership, t as newX401HolderKey, ta as PeerProofs, tc as handoffCancelFrame, tl as REQUEST_LIFETIME_MS, tn as SEPOLIA_TEST_USDT, to as dhtEditId, tr as EngineError, ts as edgeParams, tu as readDeviceInvite, u as APP_STORE_LIMITS, ua as HOLD_DATED_BACK_MS, uc as handoffPakeFrame, ud as sanitizeAvatar, ui as pinIsNewer, ul as mergeContactKnocks, un as validatePaymentTarget, uo as ReactionWindow, ur as groupFileFallback, uu as ENROLL_CAPABILITY, v as openGroupTyping, vc as readHandoffDone, vd as toBase64Url, vi as deviceWakeRequest, vn as isPubkyKey, vo as pairedReplyAuthor, vs as webLocalFetch, vt as normalizeAtprotoHandle, vu as seedSigner, w as decodeCommunityLink, wc as sealHandoffPiece, wi as vapidKeysMatch, wl as isAppUrl, wr as mayBeHub, wu as turnPutSummary, x as CommunitySession, xc as readHandoffPake, xd as utf8Encode, xi as relayRequest, xl as appViewOf, xo as BUTTON_ID, xr as groupSignalFrame, xs as encodeControl, xu as TURN_RAISE_READ_TIMEOUT_MS, y as sealGroupTyping, yc as readHandoffHave, yd as toZ32, yi as newWakeToken, yo as readReply, ys as LIMITS, yu as webCryptoSigner, z as GROUP_LIMITS, za as sanitizeMime, zc as enrollDoneFrame, zl as readAppRevocation, zn as withoutAudioMetadata, zo as statusCardText, zr as rankHubs, zs as HANDOFF_CANCEL } from "./src-BzsyAvPf.js";
3
3
  import { i as SourceUnreachableError, n as PROVIDER_PLATFORMS, o as isNothingSpentError, r as SourceConfigError, t as NothingSpentError, u as redact } from "./types-C4_KafL_.js";
4
4
  import { t as bitcoindRpc } from "./bitcoindProvider-DGw3xBSa.js";
5
- import { t as nwc } from "./nwcProvider-BeQBPB2q.js";
6
- import { a as clearProfileStores, c as deleteDatabase, d as newestWalletTx, f as openDb, g as wrap, h as transact, i as STORES$1, l as errorLine, m as store, n as APP_STORAGE_SCOPE_INDEX, o as committed, p as profileOpenFailure, r as CARD_INDEX, s as databaseName, t as APP_STORAGE_CHAT_INDEX, u as fileStore } from "./idb-BHsAqENE.js";
7
- import { a as sealSeed, c as openRow, d as sealRow, f as sealedStore, g as whenDataKeyDropped, h as sealSecret, i as newDeviceKey, l as openRows, m as openSecret, o as unsealSeed, p as hasDataKey, r as intentRepository, s as RowSeals, u as proofKey } from "./networkReason-BlQhTbXk.js";
8
- import { $ as ModeGate, A as IdentityProofs, B as ProviderSources, C as FileAppender, D as streamStored, E as storedSize, F as normalizePhrase, G as breezDatabase, H as CASHU_MINT_SOURCE, I as journaledPayment, J as dropBreezDatabase, K as breezDatabaseInUse, L as lightningPaying, M as LightningCards, N as cardsKey, P as isRecoveryPhrase, Q as ModeChanged, R as INVOICE_PACE, S as WALLET_TYPES, T as removeStored, U as cashuMint, V as sourceKey, W as AskBackoff, X as iceServerSetting, Y as iceServerProblem, Z as relayOnlyProblem, _ as crossNetwork, a as storedGroupFiles, at as setAwayWallets, b as walletInstances, c as receivedPairedReply, d as paymentAlias, et as WrongNetworkError, f as paymentWireId, g as createTiming, h as createFailure, i as groupOfFile, it as requireTurn, j as CASHU_CARD, l as replyRef, m as assertConfirmedReal, n as groupFileId, nt as awayFrom, o as groupReply, ot as setSingleWriterGate, p as WALLET_NAMES, q as breezDatabasesFor, r as groupFileText, rt as refuseAway, s as pairedWireReply, t as GroupFileDesk, tt as networkLabel, u as replyTo, v as paymentNetwork, w as readStored$2, y as paymentNetworksOf, z as nextInvoiceAsk } from "./groupFiles-D-ZUUHrx.js";
9
- import { a as fedimintDatabase, i as onPublicIrohRelay, n as createIrohWebEndpoint, r as irohRelayProblem, s as loadFedimintSdk, t as DEFAULT_IROH_RELAYS } from "./irohWeb-C_Wnw7Q9.js";
5
+ import { t as nwc } from "./nwcProvider-BXqJmM98.js";
6
+ import { _ as openDb, a as GROUP_LIGHT_RANGE, b as transact, c as clearProfileStores, d as deleteDatabase, f as errorLine, g as newestWalletTx, h as groupLiveKey, i as FILE_INDEX, l as committed, m as groupLightKey, n as APP_STORAGE_SCOPE_INDEX, o as GROUP_LIVE_RANGE, p as fileStore, r as CARD_INDEX, s as STORES$1, t as APP_STORAGE_CHAT_INDEX, u as databaseName, v as profileOpenFailure, x as wrap, y as store } from "./idb-CEuoNsTv.js";
7
+ import { a as sealSeed, c as openRow, d as sealRow, f as sealedStore, g as whenDataKeyDropped, h as sealSecret, i as newDeviceKey, l as openRows, m as openSecret, o as unsealSeed, p as hasDataKey, r as intentRepository, s as RowSeals, u as proofKey } from "./networkReason-BBosp2KG.js";
8
+ import { c as fileSpace, f as FILE_BYTES_STEP, o as fileBytes, r as blobDigest, s as fileBytesOf, u as removeFileBytes } from "./fileBytes-BLPZq9YU.js";
9
+ import { $ as iceServerProblem, A as storedSize, B as journaledPayment, C as paymentNetworksOf, D as FileAppender, E as WALLET_TYPES, F as CASHU_CARD, G as sourceKey, H as INVOICE_PACE, I as LightningCards, J as AskBackoff, K as CASHU_MINT_SOURCE, L as cardsKey, O as readStored$2, P as IdentityProofs, Q as dropBreezDatabase, R as isRecoveryPhrase, S as paymentNetwork, U as nextInvoiceAsk, V as lightningPaying, W as ProviderSources, X as breezDatabaseInUse, Y as breezDatabase, Z as breezDatabasesFor, _ as WALLET_NAMES, a as GroupFileDesk, at as networkLabel, b as createTiming, c as groupOfFile, ct as requireTurn, d as pairedWireReply, et as iceServerSetting, f as receivedPairedReply, g as paymentWireId, h as paymentAlias, i as onPublicIrohRelay, it as WrongNetworkError, j as streamStored, k as removeStored, l as storedGroupFiles, lt as setAwayWallets, m as replyTo, n as createIrohWebEndpoint, nt as ModeChanged, o as groupFileId, ot as awayFrom, p as replyRef, q as cashuMint, r as irohRelayProblem, rt as ModeGate, s as groupFileText, st as refuseAway, t as DEFAULT_IROH_RELAYS, tt as relayOnlyProblem, u as groupReply, ut as setSingleWriterGate, v as assertConfirmedReal, w as walletInstances, x as crossNetwork, y as createFailure, z as normalizePhrase } from "./irohWeb-CYn0uB_A.js";
10
+ import { r as loadFedimintSdk, t as fedimintDatabase } from "./fedimintSdk-CqTeMdF0.js";
10
11
  import { c as isTestMint, d as mintUrlSpelling, f as paysItsOwnInvoices, l as isWorthlessMint, n as DEFAULT_MINTS, o as fakesLightning, r as TEST_MINT, t as BITCOIN_INVOICE_ON_TESTNET, u as mintNetwork } from "./mints-j5XAOk4f.js";
11
- import { a as registeredLightningProviders, c as boundedIdentityFetch, d as testSwitch, n as setOwnDidSource, o as registeredOnchainProviders, r as onAdaptersChanged, s as reserveAdapterIds, u as testBuild } from "./ownDid-DAzW-Urb.js";
12
- import { d as chosenResolver, m as setPkarrRelaySource, r as resolveAtprotoDid, t as assertPublicServer } from "./resolve-UAfshn6j.js";
13
- import { c as fileSpace, f as FILE_BYTES_STEP, o as fileBytes, r as blobDigest, s as fileBytesOf, u as removeFileBytes } from "./fileBytes-BABGEF13.js";
14
- import { n as MAX_BACKUP_BYTES, t as BACKUP_MEDIA_TYPE } from "./envelope-CeZBNGX-.js";
12
+ import { a as registeredLightningProviders, c as boundedIdentityFetch, d as testSwitch, n as setOwnDidSource, o as registeredOnchainProviders, r as onAdaptersChanged, s as reserveAdapterIds, u as testBuild } from "./ownDid--DtH_Jdi.js";
13
+ import { d as chosenResolver, m as setPkarrRelaySource, r as resolveAtprotoDid, t as assertPublicServer } from "./resolve-MFeFljsN.js";
14
+ import { n as MAX_BACKUP_BYTES, t as BACKUP_MEDIA_TYPE } from "./envelope-Dwq8EN8x.js";
15
15
  import { t as hyperdhtRelayProblem } from "./hyperdhtRelay-1wzya_0L.js";
16
16
  import { sha256 } from "@noble/hashes/sha2.js";
17
17
  import { hkdf } from "@noble/hashes/hkdf.js";
@@ -124,6 +124,552 @@ var ClockWatch = class {
124
124
  }
125
125
  };
126
126
  //#endregion
127
+ //#region ../browser/src/shared/messageChanges.ts
128
+ /** A row as a page gets it: without the frame a private group's message came in (`StoredMessage.frame`), which only the engine reads. */
129
+ function withoutFrame(message) {
130
+ if (message.frame === void 0) return message;
131
+ const { frame: _frame, ...row } = message;
132
+ return row;
133
+ }
134
+ //#endregion
135
+ //#region ../browser/src/engine/db.ts
136
+ /**
137
+ * The newest `count` rows of an index range, newest first: one descending read where IndexedDB has it (the options
138
+ * that came with `getAllRecords`), else a cursor from the end.
139
+ */
140
+ function newestMessages(index, query, count) {
141
+ if (typeof index.getAllRecords === "function") return wrap(index.getAll({
142
+ query,
143
+ count,
144
+ direction: "prev"
145
+ }));
146
+ return new Promise((resolve, reject) => {
147
+ const rows = [];
148
+ const request = index.openCursor(query, "prev");
149
+ request.onerror = () => reject(request.error);
150
+ request.onsuccess = () => {
151
+ const cursor = request.result;
152
+ if (cursor) rows.push(cursor.value);
153
+ if (!cursor || rows.length >= count) resolve(rows);
154
+ else cursor.continue();
155
+ };
156
+ });
157
+ }
158
+ /** A write that waits for no disk sync of its own (in a browser, the engine's default already; on Node, the CLI's store). */
159
+ var RELAXED = { durability: "relaxed" };
160
+ var CHANGED = Symbol("changed");
161
+ /**
162
+ * While on (`keepNewest`), each whole history read (`getMessages`) keeps its newest rows as the engine's `messagePage`
163
+ * hands them, so a reader of that page right after the engine's start (the CLI's event check) reads nothing again: at 200
164
+ * chats of 300 messages that second read was a fifth of a one-shot command. Kept only when no write of that history
165
+ * was on its way while it was read, and dropped by the next one (`written`).
166
+ */
167
+ var keepLimit = 0;
168
+ var keptNewest = /* @__PURE__ */ new Map();
169
+ /** Per chat or group, its message writes started and ended; and the writes still on their way. */
170
+ var writeTurns = /* @__PURE__ */ new Map();
171
+ var writesOn = /* @__PURE__ */ new Map();
172
+ /** Runs a write of a history's rows: what was kept of it is dropped as the write starts and as it ends. */
173
+ async function written(linkId, write) {
174
+ const turn = (on) => {
175
+ writeTurns.set(linkId, (writeTurns.get(linkId) ?? 0) + 1);
176
+ writesOn.set(linkId, (writesOn.get(linkId) ?? 0) + on);
177
+ if (!writesOn.get(linkId)) writesOn.delete(linkId);
178
+ keptNewest.delete(linkId);
179
+ };
180
+ turn(1);
181
+ try {
182
+ return await write();
183
+ } finally {
184
+ turn(-1);
185
+ }
186
+ }
187
+ /** The newest rows of a whole history read (in `getMessages`' order), kept as its page would read them. */
188
+ function keepPage(linkId, turn, messages) {
189
+ if (writeTurns.get(linkId) !== turn || writesOn.has(linkId) || !messages.every((m) => Number.isFinite(m.timestamp))) {
190
+ keptNewest.delete(linkId);
191
+ return;
192
+ }
193
+ keptNewest.set(linkId, {
194
+ messages: structuredClone(messages.slice(-keepLimit).map(withoutFrame)),
195
+ more: messages.length > keepLimit
196
+ });
197
+ }
198
+ /**
199
+ * A chat's pinned key, for the transaction that checks and changes it, and the seals of the keys that change writes.
200
+ * Sealed (the data key is set), it is opened before the transaction, and holds inside it only while the row still has
201
+ * the sealed value that was opened: `CHANGED` otherwise.
202
+ */
203
+ async function pinnedKey(linkId, key) {
204
+ const seals = new RowSeals();
205
+ if (!seals.on) return {
206
+ seals,
207
+ pinned: (link) => link?.pairedPeerKey
208
+ };
209
+ const seen = await wrap((await store(STORES$1.links, "readonly")).get(linkId));
210
+ const opened = await openRow(STORES$1.links, seen);
211
+ await seals.prepare(STORES$1.links, [{
212
+ id: linkId,
213
+ pairedPeerKey: key,
214
+ peerTrust: { verifiedKey: key }
215
+ }, {
216
+ id: linkId,
217
+ peerTrust: { verifiedKey: opened?.pairedPeerKey }
218
+ }]);
219
+ const then = JSON.stringify(seen?.pairedPeerKey);
220
+ return {
221
+ seals,
222
+ pinned: (link) => JSON.stringify(link?.pairedPeerKey) === then ? opened?.pairedPeerKey : CHANGED
223
+ };
224
+ }
225
+ /**
226
+ * Durable local state of the browser peer. Identity seeds live here the same
227
+ * way Desktop keeps them in its WebView storage: local to this profile, never
228
+ * published. Network presence is not stored; it only exists while the engine runs.
229
+ */
230
+ var db = {
231
+ async getLinks() {
232
+ return openRows(STORES$1.links, await wrap((await store(STORES$1.links, "readonly")).getAll()));
233
+ },
234
+ async putLink(link) {
235
+ const row = await sealRow(STORES$1.links, link);
236
+ const tx = (await openDb()).transaction(STORES$1.links, "readwrite");
237
+ tx.objectStore(STORES$1.links).put(row);
238
+ await new Promise((resolve, reject) => {
239
+ tx.oncomplete = () => resolve();
240
+ tx.onerror = tx.onabort = () => reject(tx.error ?? /* @__PURE__ */ new Error("Link storage failed"));
241
+ });
242
+ },
243
+ /** `relaxed`: for what a power cut may cost (a round trip, a note made again later), no disk sync of its own. */
244
+ async patchLink(linkId, patch, relaxed = false) {
245
+ const sealed = await sealRow(STORES$1.links, {
246
+ ...patch,
247
+ id: linkId
248
+ });
249
+ const tx = (await openDb()).transaction(STORES$1.links, "readwrite", relaxed ? RELAXED : void 0);
250
+ const links = tx.objectStore(STORES$1.links);
251
+ const request = links.get(linkId);
252
+ request.onsuccess = () => {
253
+ if (!request.result) {
254
+ tx.abort();
255
+ return;
256
+ }
257
+ links.put({
258
+ ...request.result,
259
+ ...sealed
260
+ });
261
+ };
262
+ await new Promise((resolve, reject) => {
263
+ tx.oncomplete = () => resolve();
264
+ tx.onerror = tx.onabort = () => reject(tx.error ?? /* @__PURE__ */ new Error("Link unavailable"));
265
+ });
266
+ },
267
+ async updatePeerProofs(linkId, change) {
268
+ const tx = (await openDb()).transaction(STORES$1.links, "readwrite");
269
+ const links = tx.objectStore(STORES$1.links);
270
+ let result;
271
+ let failure;
272
+ const request = links.get(linkId);
273
+ request.onsuccess = () => {
274
+ try {
275
+ const link = request.result;
276
+ if (!link?.pairedPeerKey) throw new Error("Confirmed conversation unavailable");
277
+ result = change(link.peerProofs ?? emptyProofLedger());
278
+ links.put({
279
+ ...link,
280
+ peerProofs: result
281
+ });
282
+ } catch (e) {
283
+ failure = e;
284
+ tx.abort();
285
+ }
286
+ };
287
+ await new Promise((resolve, reject) => {
288
+ tx.oncomplete = () => resolve();
289
+ tx.onerror = tx.onabort = () => reject(failure ?? tx.error ?? /* @__PURE__ */ new Error("Proof storage failed"));
290
+ });
291
+ return result;
292
+ },
293
+ /** Read-transform-write of a chat's identity ledger in one transaction, keeping every other field. */
294
+ async updateIdentities(linkId, change) {
295
+ const tx = (await openDb()).transaction(STORES$1.links, "readwrite");
296
+ const links = tx.objectStore(STORES$1.links);
297
+ let result;
298
+ let failure;
299
+ const request = links.get(linkId);
300
+ request.onsuccess = () => {
301
+ try {
302
+ const link = request.result;
303
+ if (!link?.profile) throw new Error("Paired chat unavailable");
304
+ result = change(link.identities ?? emptyIdentityLedger());
305
+ links.put({
306
+ ...link,
307
+ identities: result
308
+ });
309
+ } catch (e) {
310
+ failure = e;
311
+ tx.abort();
312
+ }
313
+ };
314
+ await new Promise((resolve, reject) => {
315
+ tx.oncomplete = () => resolve();
316
+ tx.onerror = tx.onabort = () => reject(failure ?? tx.error ?? /* @__PURE__ */ new Error("Identity storage failed"));
317
+ });
318
+ return result;
319
+ },
320
+ async pinPeer(linkId, key, signedSignals = false) {
321
+ const { seals, pinned } = await pinnedKey(linkId, key);
322
+ const tx = (await openDb()).transaction(STORES$1.links, "readwrite");
323
+ const links = tx.objectStore(STORES$1.links);
324
+ const request = links.get(linkId);
325
+ request.onsuccess = () => {
326
+ const link = request.result;
327
+ const before = pinned(link);
328
+ if (!link?.participationSeed || before === CHANGED || before && before !== key) {
329
+ tx.abort();
330
+ return;
331
+ }
332
+ links.put(seals.row(STORES$1.links, {
333
+ ...link,
334
+ peerTrust: link.peerTrust ?? {
335
+ version: 1,
336
+ verifiedKey: before
337
+ },
338
+ pairedPeerKey: key,
339
+ requireSignedSignals: link.requireSignedSignals || signedSignals,
340
+ inviteCode: void 0
341
+ }));
342
+ };
343
+ await new Promise((resolve, reject) => {
344
+ tx.oncomplete = () => resolve();
345
+ tx.onerror = tx.onabort = () => reject(tx.error ?? /* @__PURE__ */ new Error("Invitation already consumed or unavailable"));
346
+ });
347
+ },
348
+ async verifyPeer(linkId, key) {
349
+ const { seals, pinned } = await pinnedKey(linkId, key);
350
+ const tx = (await openDb()).transaction(STORES$1.links, "readwrite");
351
+ const links = tx.objectStore(STORES$1.links);
352
+ const request = links.get(linkId);
353
+ request.onsuccess = () => {
354
+ const link = request.result;
355
+ if (!link?.pairedPeerKey || pinned(link) !== key) {
356
+ tx.abort();
357
+ return;
358
+ }
359
+ links.put(seals.row(STORES$1.links, {
360
+ ...link,
361
+ peerTrust: {
362
+ version: 1,
363
+ verifiedKey: key,
364
+ verifiedAt: Date.now()
365
+ }
366
+ }));
367
+ };
368
+ await new Promise((resolve, reject) => {
369
+ tx.oncomplete = () => resolve();
370
+ tx.onerror = tx.onabort = () => reject(tx.error ?? /* @__PURE__ */ new Error("Contact changed or verification could not be saved"));
371
+ });
372
+ },
373
+ async deleteLink(linkId) {
374
+ await committed((await store(STORES$1.links, "readwrite")).delete(linkId));
375
+ await written(linkId, async () => committed((await store(STORES$1.messages, "readwrite")).delete(IDBKeyRange.bound([linkId], [linkId, []]))));
376
+ await fileStore.deleteForLink(linkId);
377
+ await removeFileBytes(`${linkId}-in-`);
378
+ await removeFileBytes(`${linkId}-out-`);
379
+ const appStorage = await store(STORES$1.appStorage, "readwrite");
380
+ await new Promise((resolve, reject) => {
381
+ appStorage.transaction.oncomplete = () => resolve();
382
+ appStorage.transaction.onerror = appStorage.transaction.onabort = () => reject(appStorage.transaction.error ?? /* @__PURE__ */ new Error("App storage failed"));
383
+ const request = appStorage.index(APP_STORAGE_CHAT_INDEX).openKeyCursor(IDBKeyRange.only(linkId));
384
+ request.onsuccess = () => {
385
+ const cursor = request.result;
386
+ if (!cursor) return;
387
+ const [ref] = cursor.primaryKey;
388
+ appStorage.delete(IDBKeyRange.bound([ref, linkId], [
389
+ ref,
390
+ linkId,
391
+ []
392
+ ]));
393
+ cursor.continue();
394
+ };
395
+ });
396
+ },
397
+ /**
398
+ * A chat's whole history, by time. Read by its key range (every key is `[linkId, id]`, ids are strings: from `[linkId]`
399
+ * to `[linkId, []]`), the same rows in the same order as the `byLink` index has them, without looking each one up
400
+ * again: in the CLI's store (fake-indexeddb) that lookup cost 4-9 times the read itself.
401
+ */
402
+ async getMessages(linkId) {
403
+ const turn = writeTurns.get(linkId);
404
+ const messages = await wrap((await store(STORES$1.messages, "readonly")).getAll(IDBKeyRange.bound([linkId], [linkId, []])));
405
+ messages.sort((a, b) => a.timestamp - b.timestamp);
406
+ if (keepLimit) keepPage(linkId, turn, messages);
407
+ return messages;
408
+ },
409
+ /**
410
+ * From now on, each whole history read keeps its newest `limit` rows for `takeNewest` (0: none, and what was kept
411
+ * goes). Only the CLI's engine keeps them, for its start.
412
+ */
413
+ keepNewest(limit) {
414
+ keepLimit = limit;
415
+ keptNewest.clear();
416
+ },
417
+ /** What was kept of the histories read whole (`keepNewest`), by chat or group, still as stored; keeping stops. */
418
+ takeNewest() {
419
+ const kept = new Map(keptNewest);
420
+ keepLimit = 0;
421
+ keptNewest.clear();
422
+ return kept;
423
+ },
424
+ /** Whether the chat has a message with this id. */
425
+ async hasMessage(linkId, id) {
426
+ return await wrap((await store(STORES$1.messages, "readonly")).getKey([linkId, id])) !== void 0;
427
+ },
428
+ async getMessage(linkId, id) {
429
+ return wrap((await store(STORES$1.messages, "readonly")).get([linkId, id]));
430
+ },
431
+ /**
432
+ * These rows of a chat, in the order asked (undefined where none is), in one transaction: in the CLI's store
433
+ * (fake-indexeddb) each transaction waiting at once is checked against all the others, so one per row costs the square.
434
+ */
435
+ async getMessagesById(linkId, ids) {
436
+ if (!ids.length) return [];
437
+ const messages = await store(STORES$1.messages, "readonly");
438
+ return Promise.all(ids.map((id) => wrap(messages.get([linkId, id]))));
439
+ },
440
+ /**
441
+ * The newest `limit` messages of a chat before `before`, oldest first, in `getMessages`' order (time, then id), and
442
+ * whether older ones remain. Reads those rows only: a long chat's first page costs what a short one's does.
443
+ * `before`: a message's place (the page ends just before it), or a time (`id` left out: the page ends before it).
444
+ */
445
+ async getMessagePage(linkId, { limit, before }) {
446
+ const range = IDBKeyRange.bound([linkId, -Infinity], [linkId, before?.timestamp ?? Infinity], false, !!before && before.id === void 0);
447
+ const kept = (m) => !(before?.id !== void 0 && m.timestamp === before.timestamp && m.id >= before.id);
448
+ for (let want = limit + 1;;) {
449
+ const newest = await newestMessages((await store(STORES$1.messages, "readonly")).index("byLinkTime"), range, want);
450
+ const page = newest.filter(kept);
451
+ if (page.length > limit || newest.length < want) return {
452
+ messages: page.slice(0, limit).reverse(),
453
+ more: page.length > limit
454
+ };
455
+ want += newest.length - page.length;
456
+ }
457
+ },
458
+ /**
459
+ * The oldest `limit` messages of a chat after `after` (and before `before`, when given), oldest first, and whether
460
+ * newer ones remain in that window. Reads those rows only: a bot that reads what came since its last message costs
461
+ * a page, where reading the whole history and cutting it cost 94 ms of the daemon's time a call at 7,000 messages.
462
+ */
463
+ async getMessagePageAfter(linkId, { limit, before, after }) {
464
+ const upper = before?.timestamp ?? Infinity;
465
+ if (after.timestamp > upper || after.timestamp === upper && (after.id === void 0 || before?.id === void 0)) return {
466
+ messages: [],
467
+ more: false
468
+ };
469
+ const range = IDBKeyRange.bound([linkId, after.timestamp], [linkId, upper], after.id === void 0, !!before && before.id === void 0);
470
+ const kept = (m) => !(after.id !== void 0 && m.timestamp === after.timestamp && m.id <= after.id) && !(before?.id !== void 0 && m.timestamp === before.timestamp && m.id >= before.id);
471
+ for (let want = limit + 1;;) {
472
+ const oldest = await wrap((await store(STORES$1.messages, "readonly")).index("byLinkTime").getAll(range, want));
473
+ const page = oldest.filter(kept);
474
+ if (page.length > limit || oldest.length < want) return {
475
+ messages: page.slice(0, limit),
476
+ more: page.length > limit
477
+ };
478
+ want += oldest.length - page.length;
479
+ }
480
+ },
481
+ /**
482
+ * Every message of this profile that carries a task, a routine or a usage card, from every chat and group, oldest first (time,
483
+ * then id). Reads the card index only (`CARD_INDEX`): no chat's history is read, however long. The index follows the
484
+ * rows, so an edit's card, a deleted message and a deleted chat or group are in step with no bookkeeping.
485
+ */
486
+ async getCardMessages() {
487
+ const index = (await store(STORES$1.messages, "readonly")).index(CARD_INDEX);
488
+ return (await Promise.all([
489
+ "task",
490
+ "routine",
491
+ "usage"
492
+ ].map((kind) => wrap(index.getAll(kind))))).flat().sort((a, b) => a.timestamp - b.timestamp || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
493
+ },
494
+ /**
495
+ * A chat's or a group's messages that carry a file, by time (then id), as `getMessages` has them. Reads the file index
496
+ * only (`FILE_INDEX`): a chat of thousands of texts and a few files costs the files.
497
+ */
498
+ async getFileMessages(linkId) {
499
+ const index = (await store(STORES$1.messages, "readonly")).index(FILE_INDEX);
500
+ return (await wrap(index.getAll(IDBKeyRange.bound([linkId], [linkId, []])))).sort((a, b) => a.timestamp - b.timestamp || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
501
+ },
502
+ /** Returns false when the message was already stored. */
503
+ addMessage(message) {
504
+ return written(message.linkId, async () => {
505
+ const tx = (await openDb()).transaction(STORES$1.messages, "readwrite");
506
+ const messages = tx.objectStore(STORES$1.messages);
507
+ let added = false;
508
+ const request = messages.getKey([message.linkId, message.id]);
509
+ request.onsuccess = () => {
510
+ if (request.result !== void 0) return;
511
+ messages.put(message);
512
+ added = true;
513
+ };
514
+ await new Promise((resolve, reject) => {
515
+ tx.oncomplete = () => resolve();
516
+ tx.onerror = tx.onabort = () => reject(tx.error ?? /* @__PURE__ */ new Error("Message storage failed"));
517
+ });
518
+ return added;
519
+ });
520
+ },
521
+ /** Writes a message whether or not it is there: lines of history that change as what they tell changes. */
522
+ async putMessage(message) {
523
+ await written(message.linkId, async () => committed((await store(STORES$1.messages, "readwrite")).put(message)));
524
+ },
525
+ updateDelivery(linkId, id, delivery, deliveryError, extra) {
526
+ return written(linkId, async () => {
527
+ const tx = (await openDb()).transaction(STORES$1.messages, "readwrite", delivery === "sent" || delivery === "delivered" ? RELAXED : void 0);
528
+ const messages = tx.objectStore(STORES$1.messages);
529
+ const request = messages.get([linkId, id]);
530
+ request.onsuccess = () => {
531
+ const message = request.result;
532
+ if (!message?.delivery || message.delivery === "delivered") return;
533
+ if (message.delivery === delivery && message.deliveryError === deliveryError && Object.entries(extra ?? {}).every(([key, value]) => message[key] === value)) return;
534
+ messages.put({
535
+ ...message,
536
+ ...extra,
537
+ delivery,
538
+ deliveryError
539
+ });
540
+ };
541
+ await new Promise((resolve, reject) => {
542
+ tx.oncomplete = () => resolve();
543
+ tx.onerror = tx.onabort = () => reject(tx.error ?? /* @__PURE__ */ new Error("Receipt storage failed"));
544
+ });
545
+ });
546
+ },
547
+ /**
548
+ * Changes one message row in place, in one transaction: `change` sees the row as stored and gives the fields to
549
+ * set (`null`: leave it). A row that is not there is not made. Used for what the delivery states do not carry
550
+ * (the message's details record), on rows in any state. `relaxed`: for what can be made again or is only a note
551
+ * (a receipt's mark, the details record), written with no disk sync of its own.
552
+ */
553
+ patchMessage(linkId, id, change, relaxed = false) {
554
+ return written(linkId, async () => {
555
+ const tx = (await openDb()).transaction(STORES$1.messages, "readwrite", relaxed ? RELAXED : void 0);
556
+ const messages = tx.objectStore(STORES$1.messages);
557
+ const request = messages.get([linkId, id]);
558
+ let result;
559
+ request.onsuccess = () => {
560
+ const message = request.result;
561
+ if (!message) return;
562
+ const patch = change(message);
563
+ if (!patch) return;
564
+ result = {
565
+ ...message,
566
+ ...patch
567
+ };
568
+ messages.put(result);
569
+ };
570
+ await new Promise((resolve, reject) => {
571
+ tx.oncomplete = () => resolve();
572
+ tx.onerror = tx.onabort = () => reject(tx.error ?? /* @__PURE__ */ new Error("Message storage failed"));
573
+ });
574
+ return result;
575
+ });
576
+ },
577
+ /**
578
+ * `patchMessage` on these rows of one history, all in one transaction: one disk sync for all of them. Resolves to
579
+ * the rows changed, in the order of `ids`.
580
+ */
581
+ patchMessages(linkId, ids, change) {
582
+ return written(linkId, async () => {
583
+ const tx = (await openDb()).transaction(STORES$1.messages, "readwrite");
584
+ const messages = tx.objectStore(STORES$1.messages);
585
+ const results = [];
586
+ ids.forEach((id, i) => {
587
+ const request = messages.get([linkId, id]);
588
+ request.onsuccess = () => {
589
+ const message = request.result;
590
+ const patch = message && change(message);
591
+ if (!patch) return;
592
+ messages.put(results[i] = {
593
+ ...message,
594
+ ...patch
595
+ });
596
+ };
597
+ });
598
+ await new Promise((resolve, reject) => {
599
+ tx.oncomplete = () => resolve();
600
+ tx.onerror = tx.onabort = () => reject(tx.error ?? /* @__PURE__ */ new Error("Message storage failed"));
601
+ });
602
+ return results.filter((row) => !!row);
603
+ });
604
+ },
605
+ async deleteMessage(linkId, messageId) {
606
+ await written(linkId, async () => committed((await store(STORES$1.messages, "readwrite")).delete([linkId, messageId])));
607
+ },
608
+ async getGroups() {
609
+ return openRows(STORES$1.groups, await wrap((await store(STORES$1.groups, "readonly")).getAll()));
610
+ },
611
+ /**
612
+ * `live`: the group's small row (`GroupLive`) in the same transaction, or `null` to delete it. It holds none of the
613
+ * fields the encrypted profile seals; the record's are sealed before the transaction opens. The record holds the
614
+ * group's pin and deletions for everyone again: their row (`GroupLight`) goes.
615
+ */
616
+ async putGroup(group, live) {
617
+ const row = await sealRow(STORES$1.groups, group);
618
+ if (live === void 0) {
619
+ await committed((await store(STORES$1.groups, "readwrite")).put(row));
620
+ return;
621
+ }
622
+ const tx = (await openDb()).transaction([STORES$1.groups, STORES$1.settings], "readwrite");
623
+ tx.objectStore(STORES$1.groups).put(row);
624
+ const settings = tx.objectStore(STORES$1.settings);
625
+ settings.delete(groupLightKey(group.id));
626
+ if (live) await committed(settings.put(live, groupLiveKey(group.id)));
627
+ else await committed(settings.delete(groupLiveKey(group.id)));
628
+ },
629
+ /** Every private group's small row, by group id. */
630
+ async getGroupLive() {
631
+ const settings = await store(STORES$1.settings, "readonly");
632
+ const [keys, rows] = await Promise.all([wrap(settings.getAllKeys(GROUP_LIVE_RANGE())), wrap(settings.getAll(GROUP_LIVE_RANGE()))]);
633
+ return new Map(keys.map((key, i) => [String(key).slice(groupLiveKey("").length), rows[i]]));
634
+ },
635
+ async putGroupLive(groupId, live) {
636
+ await committed((await store(STORES$1.settings, "readwrite")).put(live, groupLiveKey(groupId)));
637
+ },
638
+ /** Every private group's pin and deletions for everyone that its record is behind on, by group id. */
639
+ async getGroupLight() {
640
+ const settings = await store(STORES$1.settings, "readonly");
641
+ const [keys, rows] = await Promise.all([wrap(settings.getAllKeys(GROUP_LIGHT_RANGE())), wrap(settings.getAll(GROUP_LIGHT_RANGE()))]);
642
+ return new Map(keys.map((key, i) => [String(key).slice(groupLightKey("").length), rows[i]]));
643
+ },
644
+ async putGroupLight(groupId, light) {
645
+ await committed((await store(STORES$1.settings, "readwrite")).put(light, groupLightKey(groupId)));
646
+ },
647
+ /** The group and its history. */
648
+ async deleteGroup(groupId) {
649
+ const tx = (await openDb()).transaction([STORES$1.groups, STORES$1.settings], "readwrite");
650
+ tx.objectStore(STORES$1.groups).delete(groupId);
651
+ tx.objectStore(STORES$1.settings).delete(groupLightKey(groupId));
652
+ await committed(tx.objectStore(STORES$1.settings).delete(groupLiveKey(groupId)));
653
+ const link = `group:${groupId}`;
654
+ await written(link, async () => committed((await store(STORES$1.messages, "readwrite")).delete(IDBKeyRange.bound([link], [link, []]))));
655
+ },
656
+ async getServices() {
657
+ return wrap((await store(STORES$1.services, "readonly")).getAll());
658
+ },
659
+ async putService(service) {
660
+ await committed((await store(STORES$1.services, "readwrite")).put(service));
661
+ },
662
+ async deleteService(serviceId) {
663
+ await committed((await store(STORES$1.services, "readwrite")).delete(serviceId));
664
+ },
665
+ async getSettings() {
666
+ return await wrap((await store(STORES$1.settings, "readonly")).get("settings")) ?? {};
667
+ },
668
+ async putSettings(settings) {
669
+ await committed((await store(STORES$1.settings, "readwrite")).put(settings, "settings"));
670
+ }
671
+ };
672
+ //#endregion
127
673
  //#region ../browser/src/engine/paymentAdapters/walletNetworks.ts
128
674
  /** Where the wallet of one network is stored. The same key an older app parks it under, so it finds it too. */
129
675
  var walletKey = (rail, network) => `${rail}-mode-${network}`;
@@ -199,7 +745,7 @@ function viewNews(before, after) {
199
745
  //#endregion
200
746
  //#region ../browser/src/engine/paymentAdapters/usdtWallet.ts
201
747
  /** The Ethereum libraries, a large part of the app: loaded once a USDT wallet is made, opened or restored, not with the engine. */
202
- var loadUsdt = () => import("./usdt-Dw9IENe_.js");
748
+ var loadUsdt = () => import("./usdt-Bp7T2iqt.js");
203
749
  /** Every new profile starts with this wallet: an address to receive on, nothing to set up. */
204
750
  var DEFAULT_USDT = {
205
751
  network: "ethereum",
@@ -558,6 +1104,7 @@ var SWITCHES = [
558
1104
  "shareProfile",
559
1105
  "publicProfiles",
560
1106
  "sendTyping",
1107
+ "sharePresence",
561
1108
  "autoDownloads",
562
1109
  "serveFiles"
563
1110
  ];
@@ -686,7 +1233,7 @@ async function restoreArkDatabase(walletId, snapshot) {
686
1233
  //#endregion
687
1234
  //#region ../browser/src/engine/paymentAdapters/arkWallet.ts
688
1235
  /** The Ark SDK, a large part of the app: loaded once an Ark wallet is made, opened or restored, not with the engine. */
689
- var loadArkade = () => import("./arkade-bFAS6imn.js");
1236
+ var loadArkade = () => import("./arkade-DxB-MR43.js");
690
1237
  /** How long a Testnet wallet about to make way for another waits for its server to say what it holds. */
691
1238
  var RETIRE_READ_MS = 1e4;
692
1239
  /** Every new profile starts with this wallet: nothing to set up before receiving. */
@@ -3626,6 +4173,15 @@ function mintRefused(error) {
3626
4173
  * those outputs is ever signed; new ones on the keyset it signs with now can be. cashu-ts says it in its own English,
3627
4174
  * which is never shown to a person.
3628
4175
  */
4176
+ /**
4177
+ * The mint failed, and said nothing of the request: a server error (5xx, "internal error"), or no answer at all (a
4178
+ * closed connection, cashu-ts's `NetworkError`). Unlike a refusal, it may work later. By name, as `mintRefused`.
4179
+ */
4180
+ function mintFailed(error) {
4181
+ if (!(error instanceof Error)) return false;
4182
+ const status = error.status;
4183
+ return error.name === "NetworkError" || error.name === "HttpResponseError" && typeof status === "number" && status >= 500;
4184
+ }
3629
4185
  function keysetRefused(error) {
3630
4186
  return error instanceof Error && error.name === "StaleKeysetError" && mintRefused(error);
3631
4187
  }
@@ -9262,7 +9818,7 @@ var HostNotContacted = class extends Error {};
9262
9818
  */
9263
9819
  function fixedHostsFetch(fetch) {
9264
9820
  return async (url, options) => {
9265
- const { fixedIdentityHosts } = await import("./fixedHosts-B_2Rvyja.js");
9821
+ const { fixedIdentityHosts } = await import("./fixedHosts-CINXidpd.js");
9266
9822
  const host = hostOf$1(url);
9267
9823
  if (!fixedIdentityHosts().has(host) && host !== hostOf$1("https://public.api.bsky.app") && host !== hostOf$1("https://nexus.pubky.app")) throw new HostNotContacted(`Hide my IP from contacts is on: ${host}, a server your contact chose, was not contacted`);
9268
9824
  return fetch(url, options);
@@ -10499,15 +11055,16 @@ function patchedRead(read, patches) {
10499
11055
  };
10500
11056
  }
10501
11057
  /**
10502
- * A received picture or video as it goes on: without its metadata (one from an app that sent it with them keeps where
10503
- * its author took it, the device, the time), as one sent from here; undefined for any other file, copied as it is. A
10504
- * picture is read whole; a video's stripped bytes are a Blob when it is kept in one, else read through the parts
10505
- * changed. Refused with `NO_PICTURE_METADATA` or `NO_VIDEO_METADATA` when its metadata cannot be removed.
11058
+ * A received picture, video, audio file or voice note as it goes on: without its metadata (one from an app that sent
11059
+ * it with them keeps where its author took it, the device, the time, an audio file's tags), as one sent from here;
11060
+ * undefined for any other file, copied as it is. A picture is read whole; a video's or an audio file's stripped bytes
11061
+ * are a Blob when it is kept in one, else read through the parts changed. Refused with `NO_PICTURE_METADATA`,
11062
+ * `NO_VIDEO_METADATA` or `NO_AUDIO_METADATA` when its metadata cannot be removed.
10506
11063
  */
10507
11064
  async function withoutMetadata(source, size, file, read) {
10508
- if (file.voice || !size) return void 0;
10509
- if (file.video || !isStrippedPicture(await read(0, Math.min(PICTURE_METADATA_LIMITS.headBytes, size)), file.mime)) {
10510
- if (source.blob) return withoutVideoMetadata(source.blob, file.mime);
11065
+ if (!size) return void 0;
11066
+ if (file.video || file.voice || !isStrippedPicture(await read(0, Math.min(PICTURE_METADATA_LIMITS.headBytes, size)), file.mime)) {
11067
+ if (source.blob) return await withoutVideoMetadata(source.blob, file.mime) ?? await withoutAudioMetadata(source.blob, file.mime);
10511
11068
  const readFully = async (offset, length) => {
10512
11069
  const whole = new Uint8Array(Math.max(0, Math.min(length, size - offset)));
10513
11070
  for (let at = 0; at < whole.length;) {
@@ -10521,6 +11078,9 @@ async function withoutMetadata(source, size, file, read) {
10521
11078
  const patches = await videoMetadataPatches({
10522
11079
  size,
10523
11080
  read: readFully
11081
+ }, file.mime) ?? await audioMetadataPatches({
11082
+ size,
11083
+ read: readFully
10524
11084
  }, file.mime);
10525
11085
  return patches && patchedRead(read, patches);
10526
11086
  }
@@ -10534,13 +11094,29 @@ async function withoutMetadata(source, size, file, read) {
10534
11094
  }
10535
11095
  return new Blob(stripPictureMetadata(whole, file.mime), { type: source.blob?.type ?? file.mime });
10536
11096
  }
11097
+ /** What a forward of a message deleted meanwhile says, whether it went before the forward or while its file was copied. */
11098
+ var FORWARD_MESSAGE_GONE = "That message is not in this chat";
10537
11099
  /**
10538
11100
  * A copy of a file on this device, for sending in another chat under `file.id`: a small one whole, a larger one a
10539
- * step at a time, never whole in memory; a picture without its metadata, read whole, and a video without its. Refused
10540
- * while it is still arriving, or when its bytes are gone. Resolves to `file` as it goes: a stripped file's size is its
10541
- * copy's.
11101
+ * step at a time, never whole in memory; a picture without its metadata, read whole, and a video or an audio file
11102
+ * without its. Refused while it is still arriving, or when its bytes are gone. Resolves to `file` as it goes: a
11103
+ * stripped file's size is its copy's.
11104
+ *
11105
+ * A copy cut off because its source went meanwhile says why, as one started after would: its message deleted (here, or
11106
+ * for everyone by its sender, which takes its file: `messageGone`, asked only once the copy failed) is
11107
+ * `FORWARD_MESSAGE_GONE`, its record gone with the message still here is "not on this device any more". Only bytes
11108
+ * missing from a source still kept whole on record stay "shorter than it says".
10542
11109
  */
10543
- async function copyForForward(sourceId, target) {
11110
+ async function copyForForward(sourceId, target, messageGone) {
11111
+ try {
11112
+ return await copyFile(sourceId, target);
11113
+ } catch (error) {
11114
+ if (await messageGone?.().catch(() => false)) throw Object.assign(/* @__PURE__ */ new Error(FORWARD_MESSAGE_GONE), { cause: error });
11115
+ if (!(await fileStore.get(sourceId).catch(() => ({ metadata: true })))?.metadata) throw Object.assign(/* @__PURE__ */ new Error("The file is not on this device any more"), { cause: error });
11116
+ throw error;
11117
+ }
11118
+ }
11119
+ async function copyFile(sourceId, target) {
10544
11120
  const source = await fileStore.get(sourceId);
10545
11121
  if (!source?.metadata) throw new Error("The file is not on this device any more");
10546
11122
  const stored = storedSize(source);
@@ -11089,6 +11665,19 @@ var PEEK_BYTES = APP_BUNDLE_MAGIC.length + 4 + APP_BUNDLE_LIMITS.manifestBytes;
11089
11665
  /** What a peek reads first: the magic, the length and any usual manifest (about 1 KiB). A longer one is read to its end after. */
11090
11666
  var PEEK_FIRST_BYTES = 4096;
11091
11667
  var bundleId = (digest) => `app-${digest}`;
11668
+ /** A bundle's signature statement: `{alg, key, sig}` with its 52-character key and 86-character signature, canonical. */
11669
+ var STATEMENT_BYTES = canonicalJsonBytes({
11670
+ alg: "ed25519",
11671
+ key: "y".repeat(52),
11672
+ sig: "A".repeat(86)
11673
+ }).length;
11674
+ /**
11675
+ * The length of the whole bundle of a manifest (core's `assembleAppBundle` layout: magic, u32, the canonical manifest,
11676
+ * u32, the statement, the files): what its stored file holds once written. A shorter or longer one is not that bundle.
11677
+ */
11678
+ function bundleLength(manifest) {
11679
+ return utf8Encode(APP_BUNDLE_MAGIC).length + 8 + canonicalJsonBytes(manifest).length + STATEMENT_BYTES + manifest.files.reduce((sum, f) => sum + f.size, 0);
11680
+ }
11092
11681
  /**
11093
11682
  * The key of a scope's counter row (`AppScopeCount` as JSON in `value`, `size` 0): an app's key is never empty
11094
11683
  * (`keyOf`), and the app's own rows of a scope are `keysOf`, which leaves it out.
@@ -11442,6 +12031,16 @@ var Apps = class {
11442
12031
  /** Reads of a bundle's URL under way: an install screen opened again waits on the read the closed one began, not on a second. */
11443
12032
  bundleReads = /* @__PURE__ */ new Map();
11444
12033
  /**
12034
+ * The last write of a bundle under way, by digest: a second write of the same files (Open while the update check
12035
+ * fetches them, two Installs) waits for it and finds them stored, never removing the file the first one is filling.
12036
+ */
12037
+ bundleWrites = /* @__PURE__ */ new Map();
12038
+ /**
12039
+ * Fetches of an installed app's files under way, by `ref digest`: Open or Get its files while the update check fetches
12040
+ * them waits for that fetch, with no download, hash or read-back of its own.
12041
+ */
12042
+ filesFetches = /* @__PURE__ */ new Map();
12043
+ /**
11445
12044
  * The `icon.png` of each checked bundle, by digest (at most 256 KiB and 1024 × 1024 pixels, or null for none): every icon shown on the Apps
11446
12045
  * page, in a chat's cards and in the composer's Apps is read without the whole bundle again.
11447
12046
  */
@@ -11506,6 +12105,10 @@ var Apps = class {
11506
12105
  stopped = false;
11507
12106
  /** Bundles written by this engine (`writeBundle`), by digest: one whose record is not written yet is not swept (`sweepBundles`). */
11508
12107
  written = /* @__PURE__ */ new Set();
12108
+ /** Bundle writes of this engine by digest: how many started, and how many still run (a read meanwhile may see part of one). */
12109
+ writes = /* @__PURE__ */ new Map();
12110
+ /** `bundleLength` of each installed version's manifest, by digest. */
12111
+ lengths = /* @__PURE__ */ new Map();
11509
12112
  /** The sweep of `start` while it runs: a bundle written meanwhile waits for it. */
11510
12113
  sweeping = null;
11511
12114
  constructor(host) {
@@ -11709,18 +12312,27 @@ var Apps = class {
11709
12312
  if (!app && this.ran.has(ref)) fail("not-installed", "This app is not installed");
11710
12313
  if (app) await this.stillRunnable(app, digest);
11711
12314
  }
11712
- /** Writes an app's record, keeping the revocations the record holds now (one kept since the caller read it among them). */
12315
+ /**
12316
+ * Writes an app's record, keeping the revocations the record holds now (one kept since the caller read it among them).
12317
+ * Only while the app has a record: one uninstalled since the caller read it (another tab, Uninstall while Update was
12318
+ * busy) is not put back with its data gone. False: not written.
12319
+ */
11713
12320
  async putApp(app) {
11714
12321
  const tx = (await openDb()).transaction(STORES$1.apps, "readwrite");
12322
+ let put = false;
11715
12323
  const read = tx.objectStore(STORES$1.apps).get(app.ref);
11716
12324
  read.onsuccess = () => {
11717
- tx.objectStore(STORES$1.apps).put(withRevocations(app, read.result?.revocations ?? []));
12325
+ const now = read.result;
12326
+ if (!now) return;
12327
+ tx.objectStore(STORES$1.apps).put(withRevocations(app, now.revocations ?? []));
12328
+ put = true;
11718
12329
  };
11719
12330
  try {
11720
12331
  await done(tx);
11721
12332
  } finally {
11722
12333
  this.held.delete(app.ref);
11723
12334
  }
12335
+ return put;
11724
12336
  }
11725
12337
  /**
11726
12338
  * Writes an app's record back only while it is still the record `was` (`sameRecord`), read and written in one
@@ -11836,10 +12448,30 @@ var Apps = class {
11836
12448
  /**
11837
12449
  * Stores a bundle's bytes. A browser that keeps no files fails here: Safari's Private Browsing (and WebKit's in-memory
11838
12450
  * contexts) refuses a Blob in IndexedDB with "Error preparing Blob/File data to be stored in object store". Any such
11839
- * failure is `storage`, with the browser's own words after it for the logs, and leaves no piece behind.
12451
+ * failure is `storage`, with the browser's own words after it for the logs, and leaves no piece behind. Writes of one
12452
+ * digest run one after the other (`bundleWrites`): a file store takes a file's pieces only in order.
11840
12453
  */
11841
- async writeBundle(digest, bytes) {
12454
+ writeBundle(digest, bytes) {
11842
12455
  this.written.add(digest);
12456
+ const writes = this.writes.get(digest) ?? {
12457
+ started: 0,
12458
+ running: 0
12459
+ };
12460
+ this.writes.set(digest, writes);
12461
+ writes.started++;
12462
+ writes.running++;
12463
+ const before = this.bundleWrites.get(digest);
12464
+ const write = (before ? before.catch(() => {}).then(() => this.writeBundleBytes(digest, bytes)) : this.writeBundleBytes(digest, bytes)).finally(() => {
12465
+ if (--writes.running === 0 && this.writes.get(digest) === writes) this.writes.delete(digest);
12466
+ });
12467
+ this.bundleWrites.set(digest, write);
12468
+ const done = () => {
12469
+ if (this.bundleWrites.get(digest) === write) this.bundleWrites.delete(digest);
12470
+ };
12471
+ write.then(done, done);
12472
+ return write;
12473
+ }
12474
+ async writeBundleBytes(digest, bytes) {
11843
12475
  const id = bundleId(digest);
11844
12476
  const expected = toBase64Url(await sha256Paced(bytes));
11845
12477
  let files;
@@ -11882,14 +12514,23 @@ var Apps = class {
11882
12514
  }
11883
12515
  return out;
11884
12516
  }
11885
- async hasBundle(kind, digest) {
12517
+ /**
12518
+ * Whether an installed version's files are here: a file of its whole length. One cut short (the page, the worker or
12519
+ * the app went away while `writeBundle` appended it) or longer is not, so Open, Get its files, the update check and
12520
+ * an install of the same version write it again. Its size only, no read: a list asks it of every app.
12521
+ */
12522
+ async hasBundle(kind, digest, manifest) {
11886
12523
  const files = await fileBytesOf(kind);
11887
- return !!files && await files.size(bundleId(digest)) !== null;
12524
+ if (!files) return false;
12525
+ let length = this.lengths.get(digest);
12526
+ if (length === void 0) this.lengths.set(digest, length = bundleLength(manifest));
12527
+ return await files.size(bundleId(digest)) === length;
11888
12528
  }
11889
12529
  async removeBundle(kind, digest) {
11890
12530
  this.verified.delete(digest);
11891
12531
  this.runUsed.delete(digest);
11892
12532
  this.icons.delete(digest);
12533
+ this.lengths.delete(digest);
11893
12534
  await (await fileBytesOf(kind))?.remove(bundleId(digest)).catch(() => {});
11894
12535
  }
11895
12536
  /** A bundle's bytes removed unless the app's record (installed again meanwhile) holds that version, or waits for it. */
@@ -11934,10 +12575,20 @@ var Apps = class {
11934
12575
  const under = this.verifying.get(app.digest);
11935
12576
  if (under) return under;
11936
12577
  const reading = (async () => {
12578
+ const writes = this.writes.get(app.digest)?.started ?? 0;
11937
12579
  const bytes = await this.readBundleBytes(app.bytes, app.digest);
11938
12580
  if (!bytes) fail("needs-files", "This app's files are not on this device yet");
11939
12581
  const read = await readAppBundleAsync(bytes);
11940
- if (!read.ok || read.bundle.digest !== app.digest) fail("damaged", "This app's stored files do not match what was installed");
12582
+ if (!read.ok || read.bundle.digest !== app.digest) {
12583
+ const now = this.writes.get(app.digest);
12584
+ if ((now?.started ?? 0) === writes && !now?.running) {
12585
+ await this.removeBundle(app.bytes, app.digest);
12586
+ try {
12587
+ this.host.checked?.([]);
12588
+ } catch {}
12589
+ }
12590
+ fail("damaged", "This app's stored files do not match what was installed");
12591
+ }
11941
12592
  this.verified.set(app.digest, read.bundle);
11942
12593
  this.dropUnusedBundles();
11943
12594
  this.icons.set(app.digest, read.bundle.files.get("icon.png")?.slice() ?? null);
@@ -12627,7 +13278,7 @@ var Apps = class {
12627
13278
  const added = installed ? addedAppPermissions(installed.permissions, manifest.permissions) : [...manifest.permissions];
12628
13279
  if (added.some((p) => !shown.includes(p))) fail("permissions-changed", `This install now asks for ${added.join(", ")}; look at it again`);
12629
13280
  if (decision === "same" && installed) {
12630
- const files = await this.hasBundle(installed.bytes, digest) ? null : wrote = await this.writeBundle(digest, bytes);
13281
+ const files = await this.hasBundle(installed.bytes, digest, installed.manifest) ? null : wrote = await this.writeBundle(digest, bytes);
12631
13282
  const pin = fromStore !== void 0 && installed.store !== fromStore;
12632
13283
  if (files || pin) {
12633
13284
  const { pending, ...rest } = installed;
@@ -12701,7 +13352,7 @@ var Apps = class {
12701
13352
  const read = bytes ? await readAppBundleAsync(bytes) : null;
12702
13353
  if (!read?.ok || read.bundle.digest !== pending.digest) {
12703
13354
  const { pending: _p, ...rest } = installed;
12704
- await this.putApp(rest);
13355
+ if (!await this.putApp(rest)) fail("not-installed", "This app is not installed");
12705
13356
  fail("needs-files", "The update's files are gone; it is fetched again at the next check");
12706
13357
  }
12707
13358
  const stores = await this.stores();
@@ -12716,13 +13367,13 @@ var Apps = class {
12716
13367
  if (plan.action === "refuse") fail(plan.decision, "This update can no longer be installed");
12717
13368
  const added = plan.action === "ask" ? plan.added : [];
12718
13369
  if (added.length !== pending.added.length || added.some((p) => !pending.added.includes(p))) {
12719
- await this.putApp({
13370
+ if (!await this.putApp({
12720
13371
  ...installed,
12721
13372
  pending: {
12722
13373
  ...pending,
12723
13374
  added
12724
13375
  }
12725
- });
13376
+ })) fail("not-installed", "This app is not installed");
12726
13377
  fail("permissions-changed", `This update now adds ${added.length ? added.join(", ") : "no permission"}; look at it again`);
12727
13378
  }
12728
13379
  if (shown && added.some((p) => !shown.includes(p))) fail("permissions-changed", `This update now adds ${added.join(", ")}; look at it again`);
@@ -12768,7 +13419,7 @@ var Apps = class {
12768
13419
  }
12769
13420
  /** One app's part of the update check (`checkNow`); null when it is not installed any more. */
12770
13421
  async checkApp(listed, stores) {
12771
- if (!await this.hasBundle(listed.bytes, listed.digest)) await this.fetchFiles({ ref: listed.ref }).catch(() => {});
13422
+ if (!await this.hasBundle(listed.bytes, listed.digest, listed.manifest)) await this.fetchFiles({ ref: listed.ref }).catch(() => {});
12772
13423
  const first = await this.app(listed.ref);
12773
13424
  if (!first) return null;
12774
13425
  let stored = first;
@@ -12958,22 +13609,31 @@ var Apps = class {
12958
13609
  */
12959
13610
  async fetchFiles({ ref }) {
12960
13611
  const app = await this.installedOrFail(ref);
13612
+ const key = `${app.ref} ${app.digest}`;
13613
+ const under = this.filesFetches.get(key);
13614
+ if (under) return under;
13615
+ const fetching = this.fetchFilesOf(app).finally(() => {
13616
+ this.filesFetches.delete(key);
13617
+ });
13618
+ this.filesFetches.set(key, fetching);
13619
+ return fetching;
13620
+ }
13621
+ async fetchFilesOf(app) {
12961
13622
  const stores = await this.stores();
12962
- if (await this.hasBundle(app.bytes, app.digest)) return this.runCheckOf(app, stores);
13623
+ if (await this.hasBundle(app.bytes, app.digest, app.manifest)) return this.runCheckOf(app, stores);
12963
13624
  const carried = this.builtIn(app.ref);
12964
13625
  if (carried && carried.digest === app.digest) {
12965
13626
  const held = await this.bundled(carried).catch(() => null);
12966
13627
  if (held) {
12967
13628
  const kind = await this.writeBundle(app.digest, held.bytes);
12968
13629
  const now = await this.app(app.ref);
12969
- if (!now || now.digest !== app.digest) {
13630
+ if (!now || now.digest !== app.digest || now.bytes !== kind && !await this.putApp({
13631
+ ...now,
13632
+ bytes: kind
13633
+ })) {
12970
13634
  await this.removeBundle(kind, app.digest);
12971
13635
  fail("not-installed", "This app is not installed");
12972
13636
  }
12973
- if (now.bytes !== kind) await this.putApp({
12974
- ...now,
12975
- bytes: kind
12976
- });
12977
13637
  return this.runCheckOf({
12978
13638
  ...now,
12979
13639
  bytes: kind
@@ -13001,14 +13661,13 @@ var Apps = class {
13001
13661
  if (fetched.bundle.digest !== app.digest) continue;
13002
13662
  const kind = await this.writeBundle(app.digest, fetched.bytes);
13003
13663
  const now = await this.app(app.ref);
13004
- if (!now || now.digest !== app.digest) {
13664
+ if (!now || now.digest !== app.digest || now.bytes !== kind && !await this.putApp({
13665
+ ...now,
13666
+ bytes: kind
13667
+ })) {
13005
13668
  await this.removeBundle(kind, app.digest);
13006
13669
  fail("not-installed", "This app is not installed");
13007
13670
  }
13008
- if (now.bytes !== kind) await this.putApp({
13009
- ...now,
13010
- bytes: kind
13011
- });
13012
13671
  return this.runCheckOf({
13013
13672
  ...now,
13014
13673
  bytes: kind
@@ -13017,7 +13676,7 @@ var Apps = class {
13017
13676
  return { status: "needs-files" };
13018
13677
  }
13019
13678
  async runCheckOf(app, stores) {
13020
- if (!await this.hasBundle(app.bytes, app.digest)) return { status: "needs-files" };
13679
+ if (!await this.hasBundle(app.bytes, app.digest, app.manifest)) return { status: "needs-files" };
13021
13680
  return this.runStatus(app, this.storeViews(stores), app.revocations);
13022
13681
  }
13023
13682
  /** Before an app runs (WISP 1200 § Takedowns): revoked stops it, removed by a store of the person's warns. No request. */
@@ -13597,6 +14256,7 @@ function isPush(value) {
13597
14256
  function isEarlierSet(value) {
13598
14257
  const set = value;
13599
14258
  if (!set || typeof set !== "object" || !bytes(set.d) || !bytes(set.tombstone) || !text(set.setUpdate) || !Array.isArray(set.pending) || !set.pending.every(bytes)) return false;
14259
+ if (set.delivered !== void 0 && (!Array.isArray(set.delivered) || set.delivered.length > 36 || !set.delivered.every((entry) => !!entry && typeof entry === "object" && bytes(entry.key) && bytes(entry.d)))) return false;
13600
14260
  return set.pending.length <= 4 && (set.foreign === void 0 || set.foreign === true) && optional(set.removed, bytes);
13601
14261
  }
13602
14262
  /** Why a stored record cannot be trusted. The gate then starts nothing (see `gate.ts`). */
@@ -14946,6 +15606,16 @@ function tombstoneBelieved(record, tombstone) {
14946
15606
  const key = toBase64Url(author.key);
14947
15607
  return key === (record.activeSlot === void 0 ? void 0 : record.deviceSet[record.activeSlot]?.key) || key === record.handoff?.release?.to || key === record.handoff?.peer;
14948
15608
  }
15609
+ /**
15610
+ * Whether a tombstone leaves this device with no exit but enrolling anew: it does not list this device, it is not
15611
+ * believed, and this device holds no copy to start a set of its own from. It may be the real tombstone of a device the
15612
+ * profile moved to while this one was off: that device sends no frame to a device it removed, and the device this one
15613
+ * believes signs nothing any more. A forged one ends nothing either way: a `set-update` the believed device signs is
15614
+ * still accepted (WISP 06 § Removing a device).
15615
+ */
15616
+ function stranded(record, read) {
15617
+ return read.result === "tombstone" && !!read.record && read.listed === false && !record.copy && !tombstoneBelieved(record, read.record);
15618
+ }
14949
15619
  /** The record's slots as the device state keeps them. */
14950
15620
  function deviceSetOf(record) {
14951
15621
  return record.slots.map((slot) => slot && {
@@ -15450,7 +16120,7 @@ var TurnKeeper = class {
15450
16120
  } : {};
15451
16121
  const tombstoned = state === "moving" && read.result === "tombstone" && read.record && read.payload ? {
15452
16122
  tombstone: toBase64Url(read.payload),
15453
- ...storedActiveListed(held.record, read.record) || foreign && ran ? {} : { reenroll: true }
16123
+ ...(storedActiveListed(held.record, read.record) || foreign && ran) && (ran || !stranded(held.record, read)) ? {} : { reenroll: true }
15454
16124
  } : {};
15455
16125
  const stopped = won && held.record.handoff?.peer ? held.record.deviceSet.find((slot) => slot?.key === held.record.handoff.peer) : void 0;
15456
16126
  held.record = await this.store.move(this.options.profile, state, {
@@ -15519,12 +16189,14 @@ var TurnKeeper = class {
15519
16189
  kind: "wait",
15520
16190
  read
15521
16191
  };
15522
- case "stay": return {
15523
- kind: "stay",
15524
- offers: action.offers,
15525
- ...action.awaits ? { awaits: action.awaits } : {},
15526
- read
15527
- };
16192
+ case "stay":
16193
+ if (held.record.state === "moving" && !held.record.reenroll && stranded(held.record, read)) held.record = await this.store.amend(this.options.profile, { reenroll: true });
16194
+ return {
16195
+ kind: "stay",
16196
+ offers: action.offers,
16197
+ ...action.awaits ? { awaits: action.awaits } : {},
16198
+ read
16199
+ };
15528
16200
  case "impossible": return {
15529
16201
  kind: "impossible",
15530
16202
  row,
@@ -16726,10 +17398,39 @@ function wakeOwnerOf(current, self) {
16726
17398
  if (!current?.device || !self) return void 0;
16727
17399
  return current.device === self ? "here" : "away";
16728
17400
  }
17401
+ /** The most of a push relay's own error text kept to show the person (`PushRelayRefusal.text`). */
17402
+ var RELAY_TEXT_CHARS = 120;
17403
+ /**
17404
+ * The push relay answered, but not with a push service's status: its own refusal (403 `Origin not allowed`, 400 naming
17405
+ * a header, 429), a web page or JSON without `status` (a wrong address or path, a proxy with no route). `text` is the
17406
+ * relay's own `{ error }` text when it gave one, on one line and cut to `RELAY_TEXT_CHARS`; a web page gives none.
17407
+ */
17408
+ var PushRelayRefusal = class extends Error {
17409
+ http;
17410
+ text;
17411
+ cause;
17412
+ constructor(http, text, cause) {
17413
+ super(`The push relay did not forward it (HTTP ${http})`);
17414
+ this.http = http;
17415
+ this.text = text;
17416
+ this.cause = cause;
17417
+ this.name = "PushRelayRefusal";
17418
+ }
17419
+ };
17420
+ /** The relay's own `{ error: "..." }` text in `body`, one line, cut; undefined when it gave none. */
17421
+ function relayErrorText(body) {
17422
+ const error = body && typeof body === "object" ? body.error : void 0;
17423
+ if (typeof error !== "string") return void 0;
17424
+ const line = error.replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029\u200e\u200f\u202a-\u202e\u2066-\u2069]+/g, " ").replace(/\s+/g, " ").trim();
17425
+ if (!line) return void 0;
17426
+ const chars = [...line];
17427
+ return chars.length > RELAY_TEXT_CHARS ? `${chars.slice(0, 119).join("")}…` : line;
17428
+ }
16729
17429
  /**
16730
17430
  * Posts a push: the host's way (Desktop and the CLI post it themselves), or `fetch`, then the person's push relay when
16731
- * a page may not post it (the push services answer without CORS). Answers the push service's HTTP status; throws when
16732
- * the relay does not answer with it.
17431
+ * a page may not post it (the push services answer without CORS). Answers the push service's HTTP status; throws a
17432
+ * `PushRelayRefusal` when the relay answers without it (`relayed` is told when it answers with it), and the fetch's
17433
+ * own error when the relay cannot be reached at all.
16733
17434
  */
16734
17435
  async function postPush(request, options) {
16735
17436
  if (options.pushSend) return options.pushSend(request);
@@ -16755,8 +17456,9 @@ async function postPush(request, options) {
16755
17456
  signal: AbortSignal.timeout(15e3),
16756
17457
  ...quiet
16757
17458
  });
16758
- const answer = response.ok ? await response.json().catch(() => null) : null;
16759
- if (typeof answer?.status !== "number") throw Object.assign(/* @__PURE__ */ new Error(`The push relay did not forward it (HTTP ${response.status})`), { cause: error });
17459
+ const answer = await response.json().catch(() => null);
17460
+ if (!response.ok || typeof answer?.status !== "number") throw new PushRelayRefusal(response.status, relayErrorText(answer), error);
17461
+ options.relayed?.();
16760
17462
  return answer.status;
16761
17463
  }
16762
17464
  }
@@ -16863,10 +17565,10 @@ async function planSetMove(record, signer, options = {}) {
16863
17565
  by = readSetUpdate(JSON.parse(set.setUpdate))?.by;
16864
17566
  } catch {}
16865
17567
  if (!by || !bytesEqual(by, signer.publicKey)) {
16866
- earlier.push({
17568
+ earlier.push(withDelivered({
16867
17569
  ...set,
16868
17570
  pending
16869
- });
17571
+ }, []));
16870
17572
  continue;
16871
17573
  }
16872
17574
  const setKeys = turnKeys(fromBase64Url(set.d)), tombBytes = fromBase64Url(set.tombstone);
@@ -16880,11 +17582,11 @@ async function planSetMove(record, signer, options = {}) {
16880
17582
  set: kept,
16881
17583
  tomb: tombBytes
16882
17584
  }, signer)) : set.setUpdate;
16883
- earlier.push({
17585
+ earlier.push(withDelivered({
16884
17586
  ...set,
16885
17587
  pending,
16886
17588
  setUpdate
16887
- });
17589
+ }, []));
16888
17590
  }
16889
17591
  earlier.push({
16890
17592
  d: record.d,
@@ -17044,10 +17746,37 @@ function pendingFrames(record) {
17044
17746
  */
17045
17747
  function acknowledged(record, key, d) {
17046
17748
  if (!record?.earlierSets.some((set) => (d === void 0 || set.d === d) && set.pending.includes(key))) return null;
17047
- return { earlierSets: record.earlierSets.map((set) => d === void 0 || set.d === d ? {
17749
+ return { earlierSets: record.earlierSets.map((set) => d === void 0 || set.d === d ? withDelivered({
17048
17750
  ...set,
17049
17751
  pending: set.pending.filter((k) => k !== key)
17050
- } : set) };
17752
+ }, []) : set) };
17753
+ }
17754
+ /**
17755
+ * The record once the frame of the set under `d` went to `key` over a live link (`EarlierDeviceSet.delivered`): the
17756
+ * device may hold the secret that frame names, and keep it if its `set-ack` is lost. Null when that is noted already.
17757
+ */
17758
+ function delivered(record, key, d) {
17759
+ const set = record?.earlierSets.find((s) => s.d === d && s.pending.includes(key));
17760
+ let named;
17761
+ try {
17762
+ const update = set && readSetUpdate(JSON.parse(set.setUpdate));
17763
+ if (update) named = toBase64Url(update.d);
17764
+ } catch {}
17765
+ if (!record || !set || named === void 0 || set.delivered?.some((e) => e.key === key && e.d === named)) return null;
17766
+ const kept = /* @__PURE__ */ new Set([record.d, ...record.earlierSets.map((s) => s.d)]);
17767
+ return { earlierSets: record.earlierSets.map((s) => s === set ? withDelivered(s, [{
17768
+ key,
17769
+ d: named
17770
+ }], kept) : s) };
17771
+ }
17772
+ /** `set` with `more` delivered, and only entries of devices still pending under a secret the record keeps (`kept`). */
17773
+ function withDelivered(set, more, kept) {
17774
+ const { delivered: was, ...rest } = set;
17775
+ const entries = [...was ?? [], ...more].filter((e) => set.pending.includes(e.key) && (!kept || kept.has(e.d)));
17776
+ return entries.length ? {
17777
+ ...rest,
17778
+ delivered: entries
17779
+ } : rest;
17051
17780
  }
17052
17781
  //#endregion
17053
17782
  //#region ../browser/src/devices/takeover.ts
@@ -17364,6 +18093,14 @@ async function supersedeOwnTombstone(ports, before, removerTomb) {
17364
18093
  }
17365
18094
  //#endregion
17366
18095
  //#region ../browser/src/devices/restoreGuard.ts
18096
+ /**
18097
+ * The slot a bundle names active, or undefined when it names none: a bundle from before the field, or a value that is
18098
+ * not the index of a device in its set (a damaged copy names no device rather than a wrong one).
18099
+ */
18100
+ function bundleActiveSlot(devices) {
18101
+ const at = devices?.active;
18102
+ return typeof at === "number" && Number.isSafeInteger(at) && at >= 0 && at < 4 && !!devices.set[at] ? at : void 0;
18103
+ }
17367
18104
  /** Reads the turn at the address of `d`, as a device that holds no record of the set yet. */
17368
18105
  async function peekTurn(d, network) {
17369
18106
  const keys = turnKeys(d);
@@ -17402,7 +18139,7 @@ function restoredStandby(devices, didSeed, peek, ownKey, name) {
17402
18139
  if (!d) throw new Error("This backup leads to no device set");
17403
18140
  const listed = peek?.record?.slots ?? devices?.set ?? [];
17404
18141
  const set = Array.from({ length: 4 }, (_, i) => listed[i] ?? null);
17405
- const active = peek?.record && peek.record.active < 4 ? peek.record.active : set.findIndex((slot) => slot);
18142
+ const active = peek?.record && peek.record.active < 4 ? peek.record.active : bundleActiveSlot(devices) ?? -1;
17406
18143
  let own = set.findIndex((slot) => !slot);
17407
18144
  if (own < 0) own = active >= 0 ? active : 0;
17408
18145
  set[own] = {
@@ -17880,7 +18617,8 @@ var DeviceLinks = class {
17880
18617
  for (const staying of record.deviceSet) {
17881
18618
  if (!staying || staying.key === own) continue;
17882
18619
  const key = staying.key;
17883
- for (let set = pendingFor(key); set;) {
18620
+ const took = record.earlierSets.flatMap((set) => set.pending.includes(key) ? (set.delivered ?? []).filter((e) => e.key === key).map((e) => pendingFor(key, e.d)) : []);
18621
+ for (const start of [pendingFor(key), ...took]) for (let set = start; set;) {
17884
18622
  const id = `${set.d}|${key}`;
17885
18623
  if (wanted.some((w) => w.id === id)) break;
17886
18624
  wanted.push({
@@ -18288,7 +19026,10 @@ var DeviceLinks = class {
18288
19026
  if (pending.d !== running.d || pending.key !== running.key) continue;
18289
19027
  try {
18290
19028
  running.link.sendDeviceFrame(pending.frame);
18291
- } catch {}
19029
+ } catch {
19030
+ continue;
19031
+ }
19032
+ if (record.state === "active" && delivered(record, pending.key, pending.d)) await amendDevice(this.options.profile, (current) => delivered(current, pending.key, pending.d));
18292
19033
  }
18293
19034
  return;
18294
19035
  }
@@ -19693,6 +20434,10 @@ var HandoffGiver = class {
19693
20434
  this.pake = null;
19694
20435
  this.secret = null;
19695
20436
  this.bundleMade = null;
20437
+ this.haveBuffer = {
20438
+ d: [],
20439
+ p: {}
20440
+ };
19696
20441
  this.offerHellos.clear();
19697
20442
  this.sender = new PartSender(this.now);
19698
20443
  }
@@ -19707,6 +20452,10 @@ var HandoffGiver = class {
19707
20452
  this.refused = refused;
19708
20453
  this.pake = null;
19709
20454
  this.have = null;
20455
+ this.haveBuffer = {
20456
+ d: [],
20457
+ p: {}
20458
+ };
19710
20459
  this.planned = null;
19711
20460
  this.secret = null;
19712
20461
  this.bundleMade = null;
@@ -19822,7 +20571,7 @@ async function room() {
19822
20571
  async function handoffSelf(profileHost) {
19823
20572
  return {
19824
20573
  app: profileHost.app.replace(/[^0-9A-Za-z.+_-]/g, "").slice(0, 40) || "0",
19825
- db: 15,
20574
+ db: 16,
19826
20575
  pins: { ...WALLET_SDK_PINS },
19827
20576
  kind: profileHost.kind,
19828
20577
  room: await room(),
@@ -21098,7 +21847,10 @@ var FileDesk = class {
21098
21847
  const offset = Math.min(have, record.confirmed);
21099
21848
  if (have > offset) await bytes.truncate(id, offset);
21100
21849
  if (size === null && record.file.size === 0) await bytes.append(id, 0, /* @__PURE__ */ new Uint8Array());
21101
- if (stored && stored.bytes !== bytes.kind) await fileStore.patch(id, { bytes: bytes.kind });
21850
+ if (stored && (stored.bytes !== bytes.kind || stored.leftOut)) await fileStore.patch(id, {
21851
+ bytes: bytes.kind,
21852
+ ...stored.leftOut && { leftOut: false }
21853
+ });
21102
21854
  const appender = new FileAppender(bytes, id, offset);
21103
21855
  return {
21104
21856
  offset,
@@ -21615,14 +22367,6 @@ function forgetWallet(records, id) {
21615
22367
  return rest;
21616
22368
  }
21617
22369
  //#endregion
21618
- //#region ../browser/src/shared/messageChanges.ts
21619
- /** A row as a page gets it: without the frame a private group's message came in (`StoredMessage.frame`), which only the engine reads. */
21620
- function withoutFrame(message) {
21621
- if (message.frame === void 0) return message;
21622
- const { frame: _frame, ...row } = message;
21623
- return row;
21624
- }
21625
- //#endregion
21626
22370
  //#region ../browser/src/shared/buttons.ts
21627
22371
  /** The buttons of a message, when it has any. */
21628
22372
  function messageButtons(message) {
@@ -21813,6 +22557,20 @@ var KEPT_CANCELLED = 1e3;
21813
22557
  var DEADLINE_SKEW_MS = 6e4;
21814
22558
  /** The longest delay a timer keeps: past it (about 24.8 days) `setTimeout` fires at once, in Node and in browsers. */
21815
22559
  var MAX_TIMER_MS = 2 ** 31 - 1;
22560
+ /**
22561
+ * A clock in ms that keeps counting while the machine is suspended, where the platform has one apart from the wall
22562
+ * clock: Linux's boot time (`os.uptime()` reads `CLOCK_BOOTTIME`) for Node on Linux. Node's monotonic clock there
22563
+ * (`CLOCK_MONOTONIC`, what `performance.now()` reads) stands still in a suspend, so a session that slept and a wall
22564
+ * clock set forward looked the same to `Outbox.clock`. On macOS Node's monotonic clock counts sleep already, and a
22565
+ * browser or Android's WebView has no such clock: none there (`Outbox.clock` counts the time it ran).
22566
+ */
22567
+ function bootClock() {
22568
+ const host = globalThis.process;
22569
+ if (host?.platform !== "linux" || typeof host.getBuiltinModule !== "function") return void 0;
22570
+ const uptime = host.getBuiltinModule("node:os")?.uptime;
22571
+ if (typeof uptime !== "function") return void 0;
22572
+ return () => uptime() * 1e3;
22573
+ }
21816
22574
  /** The most rows a new message's look reads one by one (`Outbox.look`), where the store cannot read them in one go. */
21817
22575
  var KNOWN_ROWS = 16;
21818
22576
  /**
@@ -21850,7 +22608,7 @@ var Outbox = class {
21850
22608
  * Queued: when it is looked at again, how far along the backoff, since when. `at` and `since` are on the monotonic
21851
22609
  * clock (`monotonic`): they live only in this session, and a step of the device clock must not move them. Read by the
21852
22610
  * wall clock, a clock set back an hour after a text was queued handed it to store-and-forward an hour late, not at
21853
- * its first check past a minute (`holdAfterMs`).
22611
+ * its first check past a minute (`holdAfterMs`). `wallSince`: the same moment by the wall clock (`waitedOut`).
21854
22612
  */
21855
22613
  waiting = /* @__PURE__ */ new Map();
21856
22614
  /**
@@ -21915,7 +22673,9 @@ var Outbox = class {
21915
22673
  policy;
21916
22674
  now;
21917
22675
  monotonic;
21918
- /** The wall clock and the monotonic clock when this outbox began: `clock` counts on from there. */
22676
+ /** A clock that counts a suspend (`bootClock`), where the platform has one. */
22677
+ boot;
22678
+ /** The wall, monotonic and boot clocks when this outbox began: `clock` counts on from there. */
21919
22679
  origin;
21920
22680
  constructor(store, send, timeoutMs = 2e4, pendingUntil, options = {}) {
21921
22681
  this.store = store;
@@ -21929,18 +22689,34 @@ var Outbox = class {
21929
22689
  };
21930
22690
  this.now = options.now ?? Date.now;
21931
22691
  this.monotonic = options.monotonic ?? (() => performance.now());
22692
+ this.boot = options.boot === void 0 ? bootClock() : options.boot ?? void 0;
21932
22693
  this.origin = {
21933
22694
  wall: this.now(),
21934
- monotonic: this.monotonic()
22695
+ monotonic: this.monotonic(),
22696
+ boot: this.boot?.()
21935
22697
  };
21936
22698
  }
21937
22699
  /**
21938
22700
  * The time a stored deadline (`resendUntil`, set by the wall clock) is judged by: the wall clock, never ahead of the
21939
- * time this session has run since it began. A clock set forward 8 days failed every queued text at its next check,
21940
- * as not confirmed within 7 days, a few seconds after it was written.
22701
+ * time that passed since this session began. A clock set forward 8 days failed every queued text at its next check,
22702
+ * as not confirmed within 7 days, a few seconds after it was written. The time that passed counts a suspend where a
22703
+ * clock says so (`bootClock`): a laptop asleep 9 days fails a text queued before at its first check after the wake,
22704
+ * where it went on a week of the machine awake. Elsewhere it is the time the session ran.
21941
22705
  */
21942
22706
  clock() {
21943
- return Math.min(this.now(), this.origin.wall + this.monotonic() - this.origin.monotonic);
22707
+ let passed = this.monotonic() - this.origin.monotonic;
22708
+ if (this.boot && this.origin.boot !== void 0) passed = Math.max(passed, this.boot() - this.origin.boot);
22709
+ return Math.min(this.now(), this.origin.wall + passed);
22710
+ }
22711
+ /**
22712
+ * Queued a minute (`holdAfterMs`), so it may be handed to store-and-forward: by the monotonic clock or by the wall
22713
+ * clock, whichever counts more. A clock set back must not delay it (the monotonic clock counts), and a suspend must
22714
+ * not either: on Linux and Android the monotonic clock stands still in one, and a text queued before a night asleep
22715
+ * waited out its minute again after the wake. A clock set forward hands it over at its next check: harmless, a text to
22716
+ * an away contact goes there anyway.
22717
+ */
22718
+ waitedOut(wait) {
22719
+ return Math.max(this.monotonic() - wait.since, this.now() - wait.wallSince) >= this.policy.holdAfterMs;
21944
22720
  }
21945
22721
  /**
21946
22722
  * Its window to go is over (`resendUntil`, by `clock`). A deadline further ahead than a whole window was set before
@@ -22153,11 +22929,11 @@ var Outbox = class {
22153
22929
  * receipt and nothing waiting read the chat's whole history for nothing, twice (the link says it is open in two
22154
22930
  * ways): 600 ms of a daemon's time per reconnect at 10,000 messages (agents#2468).
22155
22931
  */
22156
- async held() {
22932
+ async held(id) {
22157
22933
  this.looks++;
22158
22934
  const at = this.writes ? void 0 : this.stamp;
22159
22935
  try {
22160
- const messages = await this.look();
22936
+ const messages = await this.look(id);
22161
22937
  if (at !== void 0 && !messages.some((m) => this.unknown(m))) this.seen = at;
22162
22938
  return messages;
22163
22939
  } finally {
@@ -22400,7 +23176,7 @@ var Outbox = class {
22400
23176
  async check(id) {
22401
23177
  if (this.stopped) return;
22402
23178
  if (!this.waiting.has(id) || this.waiting.get(id)?.timer || this.receipts.has(id)) return;
22403
- const messages = await this.store.read(), message = messages.find((m) => m.id === id);
23179
+ const messages = await this.held(id), message = messages.find((m) => m.id === id);
22404
23180
  if (!message || !(toGo(message) || this.file(message))) {
22405
23181
  await this.attempt(id);
22406
23182
  return;
@@ -22430,7 +23206,7 @@ var Outbox = class {
22430
23206
  */
22431
23207
  waitsOn(message) {
22432
23208
  const wait = this.waiting.get(message.id);
22433
- return !!wait && (message.delivery === "queued" || message.delivery === "waiting") && message.via !== "hold" && !this.pastDeadline(message) && !this.resender.ready(message) && !(this.resender.divert && this.monotonic() - wait.since >= this.policy.holdAfterMs);
23209
+ return !!wait && (message.delivery === "queued" || message.delivery === "waiting") && message.via !== "hold" && !this.pastDeadline(message) && !this.resender.ready(message) && !(this.resender.divert && this.waitedOut(wait));
22434
23210
  }
22435
23211
  /**
22436
23212
  * A queued or waiting message is looked at; one sent and awaiting its receipt goes again now, if the chat can carry
@@ -22526,7 +23302,7 @@ var Outbox = class {
22526
23302
  await this.transmitNow(id);
22527
23303
  return true;
22528
23304
  }
22529
- if (this.resender.divert && wait && this.monotonic() - wait.since >= this.policy.holdAfterMs && await this.resender.divert(message)) {
23305
+ if (this.resender.divert && wait && this.waitedOut(wait) && await this.resender.divert(message)) {
22530
23306
  this.forget(id);
22531
23307
  return true;
22532
23308
  }
@@ -22605,6 +23381,7 @@ var Outbox = class {
22605
23381
  const wait = this.waiting.get(id) ?? {
22606
23382
  step: 0,
22607
23383
  since: this.monotonic(),
23384
+ wallSince: this.now(),
22608
23385
  at: 0
22609
23386
  };
22610
23387
  if (wait.timer) clearTimeout(wait.timer);
@@ -22628,6 +23405,7 @@ var Outbox = class {
22628
23405
  if (!wait) this.waiting.set(id, {
22629
23406
  step: 0,
22630
23407
  since: this.monotonic(),
23408
+ wallSince: this.now(),
22631
23409
  at: 0
22632
23410
  });
22633
23411
  }
@@ -23302,7 +24080,7 @@ var TARGETED = /* @__PURE__ */ new Set([
23302
24080
  * close. A request of ours counts only for the wallet it can be paid through, and only when there is one: a request a
23303
24081
  * Cashu mint and another Lightning source can both be paid through is not lost when one of them goes.
23304
24082
  */
23305
- function walletAwaiting({ network, mints, quotes, lightningOps, lightningSource, lightningCard, lightningOwner = (op) => op.card, payments, now }) {
24083
+ function walletAwaiting({ network, mints, quotes, lightningOps, lightningSource, lightningCard, lightningOwner = (op) => op.card, payments, now, chatGone }) {
23306
24084
  const at = new Set(mints);
23307
24085
  const live = (expiresAt) => !expiresAt || expiresAt + GRACE_MS > now;
23308
24086
  const invoiceKey = (invoice) => invoice.trim().toLowerCase();
@@ -23400,12 +24178,14 @@ function walletAwaiting({ network, mints, quotes, lightningOps, lightningSource,
23400
24178
  }
23401
24179
  for (const p of payments) {
23402
24180
  if (p.kind !== "payment" || p.direction !== "out" || p.state !== "pending" || !p.token) continue;
24181
+ const gone = chatGone?.(p.id) ? { chatGone: true } : {};
23403
24182
  if (p.target?.method === "fedimint" || p.federation) {
23404
24183
  if (paymentNetwork(p) === network) out.push({
23405
24184
  type: "fedimint",
23406
24185
  kind: "sent",
23407
24186
  amount: p.amount,
23408
- paymentId: p.id
24187
+ paymentId: p.id,
24188
+ ...gone
23409
24189
  });
23410
24190
  continue;
23411
24191
  }
@@ -23414,7 +24194,8 @@ function walletAwaiting({ network, mints, quotes, lightningOps, lightningSource,
23414
24194
  type: "cashu",
23415
24195
  kind: "sent",
23416
24196
  amount: p.amount,
23417
- paymentId: p.id
24197
+ paymentId: p.id,
24198
+ ...gone
23418
24199
  });
23419
24200
  }
23420
24201
  return out;
@@ -23445,445 +24226,15 @@ function mintAwaiting(mint, sources) {
23445
24226
  */
23446
24227
  /** What one press asks a test mint for: small, fixed, worth nothing. */
23447
24228
  var TEST_COINS_SATS = 1e4;
23448
- /** A faucet's failure in words a person can act on: rate limited says to wait, anything else says what failed. */
24229
+ /** A faucet's failure in words a person can act on: rate limited says to wait, a failed mint to try later, anything else says what failed. */
23449
24230
  function faucetError(error) {
24231
+ if (error?.engineCode === "mintFailedFaucet") return error;
23450
24232
  const message = error instanceof Error ? error.message : String(error);
23451
24233
  if (error?.status === 429 || /\b429\b|rate.?limit|too many requests/i.test(message)) return /* @__PURE__ */ new Error("Rate limited: the faucet is busy. Try again in a minute.");
23452
24234
  if (/failed to fetch|networkerror|did not answer|load failed/i.test(message)) return /* @__PURE__ */ new Error(`The faucet did not answer: ${message}`);
23453
24235
  return /* @__PURE__ */ new Error(`The faucet did not pay: ${message}`);
23454
24236
  }
23455
24237
  //#endregion
23456
- //#region ../browser/src/engine/db.ts
23457
- /**
23458
- * The newest `count` rows of an index range, newest first: one descending read where IndexedDB has it (the options
23459
- * that came with `getAllRecords`), else a cursor from the end.
23460
- */
23461
- function newestMessages(index, query, count) {
23462
- if (typeof index.getAllRecords === "function") return wrap(index.getAll({
23463
- query,
23464
- count,
23465
- direction: "prev"
23466
- }));
23467
- return new Promise((resolve, reject) => {
23468
- const rows = [];
23469
- const request = index.openCursor(query, "prev");
23470
- request.onerror = () => reject(request.error);
23471
- request.onsuccess = () => {
23472
- const cursor = request.result;
23473
- if (cursor) rows.push(cursor.value);
23474
- if (!cursor || rows.length >= count) resolve(rows);
23475
- else cursor.continue();
23476
- };
23477
- });
23478
- }
23479
- /** A write that waits for no disk sync of its own (in a browser, the engine's default already; on Node, the CLI's store). */
23480
- var RELAXED = { durability: "relaxed" };
23481
- var CHANGED = Symbol("changed");
23482
- /**
23483
- * A chat's pinned key, for the transaction that checks and changes it, and the seals of the keys that change writes.
23484
- * Sealed (the data key is set), it is opened before the transaction, and holds inside it only while the row still has
23485
- * the sealed value that was opened: `CHANGED` otherwise.
23486
- */
23487
- async function pinnedKey(linkId, key) {
23488
- const seals = new RowSeals();
23489
- if (!seals.on) return {
23490
- seals,
23491
- pinned: (link) => link?.pairedPeerKey
23492
- };
23493
- const seen = await wrap((await store(STORES$1.links, "readonly")).get(linkId));
23494
- const opened = await openRow(STORES$1.links, seen);
23495
- await seals.prepare(STORES$1.links, [{
23496
- id: linkId,
23497
- pairedPeerKey: key,
23498
- peerTrust: { verifiedKey: key }
23499
- }, {
23500
- id: linkId,
23501
- peerTrust: { verifiedKey: opened?.pairedPeerKey }
23502
- }]);
23503
- const then = JSON.stringify(seen?.pairedPeerKey);
23504
- return {
23505
- seals,
23506
- pinned: (link) => JSON.stringify(link?.pairedPeerKey) === then ? opened?.pairedPeerKey : CHANGED
23507
- };
23508
- }
23509
- /**
23510
- * Durable local state of the browser peer. Identity seeds live here the same
23511
- * way Desktop keeps them in its WebView storage: local to this profile, never
23512
- * published. Network presence is not stored; it only exists while the engine runs.
23513
- */
23514
- var db = {
23515
- async getLinks() {
23516
- return openRows(STORES$1.links, await wrap((await store(STORES$1.links, "readonly")).getAll()));
23517
- },
23518
- async putLink(link) {
23519
- const row = await sealRow(STORES$1.links, link);
23520
- const tx = (await openDb()).transaction(STORES$1.links, "readwrite");
23521
- tx.objectStore(STORES$1.links).put(row);
23522
- await new Promise((resolve, reject) => {
23523
- tx.oncomplete = () => resolve();
23524
- tx.onerror = tx.onabort = () => reject(tx.error ?? /* @__PURE__ */ new Error("Link storage failed"));
23525
- });
23526
- },
23527
- /** `relaxed`: for what a power cut may cost (a round trip, a note made again later), no disk sync of its own. */
23528
- async patchLink(linkId, patch, relaxed = false) {
23529
- const sealed = await sealRow(STORES$1.links, {
23530
- ...patch,
23531
- id: linkId
23532
- });
23533
- const tx = (await openDb()).transaction(STORES$1.links, "readwrite", relaxed ? RELAXED : void 0);
23534
- const links = tx.objectStore(STORES$1.links);
23535
- const request = links.get(linkId);
23536
- request.onsuccess = () => {
23537
- if (!request.result) {
23538
- tx.abort();
23539
- return;
23540
- }
23541
- links.put({
23542
- ...request.result,
23543
- ...sealed
23544
- });
23545
- };
23546
- await new Promise((resolve, reject) => {
23547
- tx.oncomplete = () => resolve();
23548
- tx.onerror = tx.onabort = () => reject(tx.error ?? /* @__PURE__ */ new Error("Link unavailable"));
23549
- });
23550
- },
23551
- async updatePeerProofs(linkId, change) {
23552
- const tx = (await openDb()).transaction(STORES$1.links, "readwrite");
23553
- const links = tx.objectStore(STORES$1.links);
23554
- let result;
23555
- let failure;
23556
- const request = links.get(linkId);
23557
- request.onsuccess = () => {
23558
- try {
23559
- const link = request.result;
23560
- if (!link?.pairedPeerKey) throw new Error("Confirmed conversation unavailable");
23561
- result = change(link.peerProofs ?? emptyProofLedger());
23562
- links.put({
23563
- ...link,
23564
- peerProofs: result
23565
- });
23566
- } catch (e) {
23567
- failure = e;
23568
- tx.abort();
23569
- }
23570
- };
23571
- await new Promise((resolve, reject) => {
23572
- tx.oncomplete = () => resolve();
23573
- tx.onerror = tx.onabort = () => reject(failure ?? tx.error ?? /* @__PURE__ */ new Error("Proof storage failed"));
23574
- });
23575
- return result;
23576
- },
23577
- /** Read-transform-write of a chat's identity ledger in one transaction, keeping every other field. */
23578
- async updateIdentities(linkId, change) {
23579
- const tx = (await openDb()).transaction(STORES$1.links, "readwrite");
23580
- const links = tx.objectStore(STORES$1.links);
23581
- let result;
23582
- let failure;
23583
- const request = links.get(linkId);
23584
- request.onsuccess = () => {
23585
- try {
23586
- const link = request.result;
23587
- if (!link?.profile) throw new Error("Paired chat unavailable");
23588
- result = change(link.identities ?? emptyIdentityLedger());
23589
- links.put({
23590
- ...link,
23591
- identities: result
23592
- });
23593
- } catch (e) {
23594
- failure = e;
23595
- tx.abort();
23596
- }
23597
- };
23598
- await new Promise((resolve, reject) => {
23599
- tx.oncomplete = () => resolve();
23600
- tx.onerror = tx.onabort = () => reject(failure ?? tx.error ?? /* @__PURE__ */ new Error("Identity storage failed"));
23601
- });
23602
- return result;
23603
- },
23604
- async pinPeer(linkId, key, signedSignals = false) {
23605
- const { seals, pinned } = await pinnedKey(linkId, key);
23606
- const tx = (await openDb()).transaction(STORES$1.links, "readwrite");
23607
- const links = tx.objectStore(STORES$1.links);
23608
- const request = links.get(linkId);
23609
- request.onsuccess = () => {
23610
- const link = request.result;
23611
- const before = pinned(link);
23612
- if (!link?.participationSeed || before === CHANGED || before && before !== key) {
23613
- tx.abort();
23614
- return;
23615
- }
23616
- links.put(seals.row(STORES$1.links, {
23617
- ...link,
23618
- peerTrust: link.peerTrust ?? {
23619
- version: 1,
23620
- verifiedKey: before
23621
- },
23622
- pairedPeerKey: key,
23623
- requireSignedSignals: link.requireSignedSignals || signedSignals,
23624
- inviteCode: void 0
23625
- }));
23626
- };
23627
- await new Promise((resolve, reject) => {
23628
- tx.oncomplete = () => resolve();
23629
- tx.onerror = tx.onabort = () => reject(tx.error ?? /* @__PURE__ */ new Error("Invitation already consumed or unavailable"));
23630
- });
23631
- },
23632
- async verifyPeer(linkId, key) {
23633
- const { seals, pinned } = await pinnedKey(linkId, key);
23634
- const tx = (await openDb()).transaction(STORES$1.links, "readwrite");
23635
- const links = tx.objectStore(STORES$1.links);
23636
- const request = links.get(linkId);
23637
- request.onsuccess = () => {
23638
- const link = request.result;
23639
- if (!link?.pairedPeerKey || pinned(link) !== key) {
23640
- tx.abort();
23641
- return;
23642
- }
23643
- links.put(seals.row(STORES$1.links, {
23644
- ...link,
23645
- peerTrust: {
23646
- version: 1,
23647
- verifiedKey: key,
23648
- verifiedAt: Date.now()
23649
- }
23650
- }));
23651
- };
23652
- await new Promise((resolve, reject) => {
23653
- tx.oncomplete = () => resolve();
23654
- tx.onerror = tx.onabort = () => reject(tx.error ?? /* @__PURE__ */ new Error("Contact changed or verification could not be saved"));
23655
- });
23656
- },
23657
- async deleteLink(linkId) {
23658
- await committed((await store(STORES$1.links, "readwrite")).delete(linkId));
23659
- await committed((await store(STORES$1.messages, "readwrite")).delete(IDBKeyRange.bound([linkId], [linkId, []])));
23660
- await fileStore.deleteForLink(linkId);
23661
- await removeFileBytes(`${linkId}-in-`);
23662
- await removeFileBytes(`${linkId}-out-`);
23663
- const appStorage = await store(STORES$1.appStorage, "readwrite");
23664
- await new Promise((resolve, reject) => {
23665
- appStorage.transaction.oncomplete = () => resolve();
23666
- appStorage.transaction.onerror = appStorage.transaction.onabort = () => reject(appStorage.transaction.error ?? /* @__PURE__ */ new Error("App storage failed"));
23667
- const request = appStorage.index(APP_STORAGE_CHAT_INDEX).openKeyCursor(IDBKeyRange.only(linkId));
23668
- request.onsuccess = () => {
23669
- const cursor = request.result;
23670
- if (!cursor) return;
23671
- const [ref] = cursor.primaryKey;
23672
- appStorage.delete(IDBKeyRange.bound([ref, linkId], [
23673
- ref,
23674
- linkId,
23675
- []
23676
- ]));
23677
- cursor.continue();
23678
- };
23679
- });
23680
- },
23681
- /**
23682
- * A chat's whole history, by time. Read by its key range (every key is `[linkId, id]`, ids are strings: from `[linkId]`
23683
- * to `[linkId, []]`), the same rows in the same order as the `byLink` index has them, without looking each one up
23684
- * again: in the CLI's store (fake-indexeddb) that lookup cost 4-9 times the read itself.
23685
- */
23686
- async getMessages(linkId) {
23687
- return (await wrap((await store(STORES$1.messages, "readonly")).getAll(IDBKeyRange.bound([linkId], [linkId, []])))).sort((a, b) => a.timestamp - b.timestamp);
23688
- },
23689
- /** Whether the chat has a message with this id. */
23690
- async hasMessage(linkId, id) {
23691
- return await wrap((await store(STORES$1.messages, "readonly")).getKey([linkId, id])) !== void 0;
23692
- },
23693
- async getMessage(linkId, id) {
23694
- return wrap((await store(STORES$1.messages, "readonly")).get([linkId, id]));
23695
- },
23696
- /**
23697
- * These rows of a chat, in the order asked (undefined where none is), in one transaction: in the CLI's store
23698
- * (fake-indexeddb) each transaction waiting at once is checked against all the others, so one per row costs the square.
23699
- */
23700
- async getMessagesById(linkId, ids) {
23701
- if (!ids.length) return [];
23702
- const messages = await store(STORES$1.messages, "readonly");
23703
- return Promise.all(ids.map((id) => wrap(messages.get([linkId, id]))));
23704
- },
23705
- /**
23706
- * The newest `limit` messages of a chat before `before`, oldest first, in `getMessages`' order (time, then id), and
23707
- * whether older ones remain. Reads those rows only: a long chat's first page costs what a short one's does.
23708
- * `before`: a message's place (the page ends just before it), or a time (`id` left out: the page ends before it).
23709
- */
23710
- async getMessagePage(linkId, { limit, before }) {
23711
- const range = IDBKeyRange.bound([linkId, -Infinity], [linkId, before?.timestamp ?? Infinity], false, !!before && before.id === void 0);
23712
- const kept = (m) => !(before?.id !== void 0 && m.timestamp === before.timestamp && m.id >= before.id);
23713
- for (let want = limit + 1;;) {
23714
- const newest = await newestMessages((await store(STORES$1.messages, "readonly")).index("byLinkTime"), range, want);
23715
- const page = newest.filter(kept);
23716
- if (page.length > limit || newest.length < want) return {
23717
- messages: page.slice(0, limit).reverse(),
23718
- more: page.length > limit
23719
- };
23720
- want += newest.length - page.length;
23721
- }
23722
- },
23723
- /**
23724
- * The oldest `limit` messages of a chat after `after` (and before `before`, when given), oldest first, and whether
23725
- * newer ones remain in that window. Reads those rows only: a bot that reads what came since its last message costs
23726
- * a page, where reading the whole history and cutting it cost 94 ms of the daemon's time a call at 7,000 messages.
23727
- */
23728
- async getMessagePageAfter(linkId, { limit, before, after }) {
23729
- const upper = before?.timestamp ?? Infinity;
23730
- if (after.timestamp > upper || after.timestamp === upper && (after.id === void 0 || before?.id === void 0)) return {
23731
- messages: [],
23732
- more: false
23733
- };
23734
- const range = IDBKeyRange.bound([linkId, after.timestamp], [linkId, upper], after.id === void 0, !!before && before.id === void 0);
23735
- const kept = (m) => !(after.id !== void 0 && m.timestamp === after.timestamp && m.id <= after.id) && !(before?.id !== void 0 && m.timestamp === before.timestamp && m.id >= before.id);
23736
- for (let want = limit + 1;;) {
23737
- const oldest = await wrap((await store(STORES$1.messages, "readonly")).index("byLinkTime").getAll(range, want));
23738
- const page = oldest.filter(kept);
23739
- if (page.length > limit || oldest.length < want) return {
23740
- messages: page.slice(0, limit),
23741
- more: page.length > limit
23742
- };
23743
- want += oldest.length - page.length;
23744
- }
23745
- },
23746
- /**
23747
- * Every message of this profile that carries a task, a routine or a usage card, from every chat and group, oldest first (time,
23748
- * then id). Reads the card index only (`CARD_INDEX`): no chat's history is read, however long. The index follows the
23749
- * rows, so an edit's card, a deleted message and a deleted chat or group are in step with no bookkeeping.
23750
- */
23751
- async getCardMessages() {
23752
- const index = (await store(STORES$1.messages, "readonly")).index(CARD_INDEX);
23753
- return (await Promise.all([
23754
- "task",
23755
- "routine",
23756
- "usage"
23757
- ].map((kind) => wrap(index.getAll(kind))))).flat().sort((a, b) => a.timestamp - b.timestamp || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0));
23758
- },
23759
- /** Returns false when the message was already stored. */
23760
- async addMessage(message) {
23761
- const tx = (await openDb()).transaction(STORES$1.messages, "readwrite");
23762
- const messages = tx.objectStore(STORES$1.messages);
23763
- let added = false;
23764
- const request = messages.getKey([message.linkId, message.id]);
23765
- request.onsuccess = () => {
23766
- if (request.result !== void 0) return;
23767
- messages.put(message);
23768
- added = true;
23769
- };
23770
- await new Promise((resolve, reject) => {
23771
- tx.oncomplete = () => resolve();
23772
- tx.onerror = tx.onabort = () => reject(tx.error ?? /* @__PURE__ */ new Error("Message storage failed"));
23773
- });
23774
- return added;
23775
- },
23776
- /** Writes a message whether or not it is there: lines of history that change as what they tell changes. */
23777
- async putMessage(message) {
23778
- await committed((await store(STORES$1.messages, "readwrite")).put(message));
23779
- },
23780
- async updateDelivery(linkId, id, delivery, deliveryError, extra) {
23781
- const tx = (await openDb()).transaction(STORES$1.messages, "readwrite", delivery === "sent" || delivery === "delivered" ? RELAXED : void 0);
23782
- const messages = tx.objectStore(STORES$1.messages);
23783
- const request = messages.get([linkId, id]);
23784
- request.onsuccess = () => {
23785
- const message = request.result;
23786
- if (!message?.delivery || message.delivery === "delivered") return;
23787
- if (message.delivery === delivery && message.deliveryError === deliveryError && Object.entries(extra ?? {}).every(([key, value]) => message[key] === value)) return;
23788
- messages.put({
23789
- ...message,
23790
- ...extra,
23791
- delivery,
23792
- deliveryError
23793
- });
23794
- };
23795
- await new Promise((resolve, reject) => {
23796
- tx.oncomplete = () => resolve();
23797
- tx.onerror = tx.onabort = () => reject(tx.error ?? /* @__PURE__ */ new Error("Receipt storage failed"));
23798
- });
23799
- },
23800
- /**
23801
- * Changes one message row in place, in one transaction: `change` sees the row as stored and gives the fields to
23802
- * set (`null`: leave it). A row that is not there is not made. Used for what the delivery states do not carry
23803
- * (the message's details record), on rows in any state. `relaxed`: for what can be made again or is only a note
23804
- * (a receipt's mark, the details record), written with no disk sync of its own.
23805
- */
23806
- async patchMessage(linkId, id, change, relaxed = false) {
23807
- const tx = (await openDb()).transaction(STORES$1.messages, "readwrite", relaxed ? RELAXED : void 0);
23808
- const messages = tx.objectStore(STORES$1.messages);
23809
- const request = messages.get([linkId, id]);
23810
- let result;
23811
- request.onsuccess = () => {
23812
- const message = request.result;
23813
- if (!message) return;
23814
- const patch = change(message);
23815
- if (!patch) return;
23816
- result = {
23817
- ...message,
23818
- ...patch
23819
- };
23820
- messages.put(result);
23821
- };
23822
- await new Promise((resolve, reject) => {
23823
- tx.oncomplete = () => resolve();
23824
- tx.onerror = tx.onabort = () => reject(tx.error ?? /* @__PURE__ */ new Error("Message storage failed"));
23825
- });
23826
- return result;
23827
- },
23828
- /**
23829
- * `patchMessage` on these rows of one history, all in one transaction: one disk sync for all of them. Resolves to
23830
- * the rows changed, in the order of `ids`.
23831
- */
23832
- async patchMessages(linkId, ids, change) {
23833
- const tx = (await openDb()).transaction(STORES$1.messages, "readwrite");
23834
- const messages = tx.objectStore(STORES$1.messages);
23835
- const results = [];
23836
- ids.forEach((id, i) => {
23837
- const request = messages.get([linkId, id]);
23838
- request.onsuccess = () => {
23839
- const message = request.result;
23840
- const patch = message && change(message);
23841
- if (!patch) return;
23842
- messages.put(results[i] = {
23843
- ...message,
23844
- ...patch
23845
- });
23846
- };
23847
- });
23848
- await new Promise((resolve, reject) => {
23849
- tx.oncomplete = () => resolve();
23850
- tx.onerror = tx.onabort = () => reject(tx.error ?? /* @__PURE__ */ new Error("Message storage failed"));
23851
- });
23852
- return results.filter((row) => !!row);
23853
- },
23854
- async deleteMessage(linkId, messageId) {
23855
- await committed((await store(STORES$1.messages, "readwrite")).delete([linkId, messageId]));
23856
- },
23857
- async getGroups() {
23858
- return openRows(STORES$1.groups, await wrap((await store(STORES$1.groups, "readonly")).getAll()));
23859
- },
23860
- async putGroup(group) {
23861
- const row = await sealRow(STORES$1.groups, group);
23862
- await committed((await store(STORES$1.groups, "readwrite")).put(row));
23863
- },
23864
- /** The group and its history. */
23865
- async deleteGroup(groupId) {
23866
- await committed((await store(STORES$1.groups, "readwrite")).delete(groupId));
23867
- const link = `group:${groupId}`;
23868
- await committed((await store(STORES$1.messages, "readwrite")).delete(IDBKeyRange.bound([link], [link, []])));
23869
- },
23870
- async getServices() {
23871
- return wrap((await store(STORES$1.services, "readonly")).getAll());
23872
- },
23873
- async putService(service) {
23874
- await committed((await store(STORES$1.services, "readwrite")).put(service));
23875
- },
23876
- async deleteService(serviceId) {
23877
- await committed((await store(STORES$1.services, "readwrite")).delete(serviceId));
23878
- },
23879
- async getSettings() {
23880
- return await wrap((await store(STORES$1.settings, "readonly")).get("settings")) ?? {};
23881
- },
23882
- async putSettings(settings) {
23883
- await committed((await store(STORES$1.settings, "readwrite")).put(settings, "settings"));
23884
- }
23885
- };
23886
- //#endregion
23887
24238
  //#region ../browser/src/engine/arrival.ts
23888
24239
  /**
23889
24240
  * A history stored before a received row was placed where it arrived (WISP 400, requirement 10; until 2026-10): a
@@ -24344,7 +24695,8 @@ async function pinnedRow(host, chat, id) {
24344
24695
  }
24345
24696
  /**
24346
24697
  * This side's pin (`messageId` its row here or the id both sides know; `remove` unpins): numbered past the pin shown
24347
- * now, or why it cannot be.
24698
+ * now, or why it cannot be. The message pinned already (its number holding) is `already`: nothing is numbered or sent,
24699
+ * so the pin stays its pinner's, and goes only when they leave a group.
24348
24700
  */
24349
24701
  async function myPin(host, chat, messageId, remove, current, now = Date.now()) {
24350
24702
  const n = nextPinNumber(current?.n, now);
@@ -24359,6 +24711,7 @@ async function myPin(host, chat, messageId, remove, current, now = Date.now()) {
24359
24711
  const target = host.message ? await host.message(chat, messageId) ?? await pinnedRow(host, chat, messageId) : (await host.messages(chat)).find((m) => m.id === messageId) ?? await pinnedRow(host, chat, messageId);
24360
24712
  const id = target && replyRef(target, group);
24361
24713
  if (!target || !id) return { error: `That message is not in this ${group ? "group" : "chat"}, or cannot be pinned` };
24714
+ if (current?.id === id && pinNumberHolds(current.n, now)) return { already: true };
24362
24715
  return {
24363
24716
  id,
24364
24717
  n,
@@ -24368,6 +24721,289 @@ async function myPin(host, chat, messageId, remove, current, now = Date.now()) {
24368
24721
  };
24369
24722
  }
24370
24723
  //#endregion
24724
+ //#region ../browser/src/engine/groupRows.ts
24725
+ /**
24726
+ * A private group's record in two rows. A message sent or received changes a few fields of the group's state (my
24727
+ * sequence number, what I saw, my last frames, my texts not yet stored or said); the rest, its membership chain above
24728
+ * all, changes with a commit or a secret only. Each commit carries the whole roster and the chain is never compacted,
24729
+ * so the record grew with every join and leave, and each message wrote all of it again: 50 KB in a group of 32 just
24730
+ * made, 800 KB after 150 joins and leaves. Now a message writes the group's small row (`GroupLive`, in the settings
24731
+ * store) alone, and the record is written when the rest changes.
24732
+ *
24733
+ * An app from before reads the record alone. Each time the record is written, its `state.seq` is `SEQ_BLOCK` above
24734
+ * mine (`StoredGroup.seqReserved`), and it is written again before I send at that number: such an app sends above
24735
+ * everything I said, and the members do not drop its messages as already seen. Back here, a record whose `state.seq`
24736
+ * is not the number reserved was written by such an app since, and the small row is stale: the record counts.
24737
+ */
24738
+ var SEQ_BLOCK = 1024;
24739
+ /** The fields of the state the small row holds. */
24740
+ var LIVE = [
24741
+ "seq",
24742
+ "seqEpoch",
24743
+ "seen",
24744
+ "sent",
24745
+ "alone",
24746
+ "provisional",
24747
+ "nicks",
24748
+ "unsaid"
24749
+ ];
24750
+ /**
24751
+ * The fields of the record a row of their own holds (`GroupLight`) while nothing else of it changed: what a pin (mine
24752
+ * or a member's) and a deletion for everyone change. Each wrote the whole record, as a message did before (150 KB in a
24753
+ * group of 31 after 20 joins and leaves, 350 KB after 60). Apart from the small row: up to 500 ids each, which a message
24754
+ * would write again every time. `came` is the small row's. The same row holds the state's `relayEdits` (up to 64 frames):
24755
+ * each edit and deletion for everyone a member's app takes in changes them, and wrote the whole record too.
24756
+ *
24757
+ * And the hubs I keep for my next start (`StoredGroup.hubs`, at most eight keys): they change each time a hub goes
24758
+ * offline or comes back, and wrote the whole record each time (two hubs away 90 s every 2 minutes: 30 whole records,
24759
+ * 1.7 MB, per other hub in 30 min in a group of 31). Only read at the next start, before the beacon is: an app from
24760
+ * before, or a row it left stale, starts on the hubs of an older list, and reads the beacon as before. With them,
24761
+ * the members whose apps said they take rosters past eight (`StoredGroup.large`), noted when an edge with one first
24762
+ * comes up: a member moving to a hub it never had an edge with noted it, and wrote the whole record for that. The row
24763
+ * holds the ones noted since the record was written whole, and the list only grows: at load, the record's and the
24764
+ * row's together, so none an app from before noted in the record since is lost.
24765
+ */
24766
+ var LIGHT = [
24767
+ "pin",
24768
+ "removedIds",
24769
+ "removals",
24770
+ "hubs",
24771
+ "large"
24772
+ ];
24773
+ var topOf = (state) => state.chain[state.chain.length - 1]?.sig ?? "";
24774
+ /** The members' edits the state keeps to hand on, by their signatures. */
24775
+ var editsOf = (state) => (state.relayEdits ?? []).map((f) => f.sig).join(" ");
24776
+ /** The state as its record holds it, but for `LIVE` and `relayEdits`, in one string: its frames and statements by their signatures. */
24777
+ function recordKey(state) {
24778
+ const { chain, relay, relayEdits: _edits, meta, metaPast, ...rest } = state;
24779
+ for (const field of LIVE) delete rest[field];
24780
+ return JSON.stringify([
24781
+ rest,
24782
+ chain.length,
24783
+ chain[0]?.sig,
24784
+ topOf(state),
24785
+ relay?.map((f) => f.sig),
24786
+ meta?.sig,
24787
+ metaPast?.map((m) => m.sig)
24788
+ ]);
24789
+ }
24790
+ /** The record but for its state, `LIGHT` and `came` (the small row's), in one string. */
24791
+ function restKey(group) {
24792
+ const { state: _state, seqReserved: _reserved, came: _came, ...rest } = group;
24793
+ for (const field of LIGHT) delete rest[field];
24794
+ return JSON.stringify(rest);
24795
+ }
24796
+ /** The row for `group`, whose record holds the members' apps in `kept` (`StoredGroup.large`) already. */
24797
+ function lightOf(group, kept) {
24798
+ const large = group.large?.filter((key) => !kept.includes(key));
24799
+ return {
24800
+ ...group.pin && { pin: group.pin },
24801
+ removedIds: group.removedIds ?? [],
24802
+ removals: group.removals ?? [],
24803
+ relayEdits: group.state?.relayEdits ?? [],
24804
+ ...group.hubs && { hubs: group.hubs },
24805
+ ...large?.length ? { large } : {}
24806
+ };
24807
+ }
24808
+ /**
24809
+ * What a record holds of `LIGHT` (`lightOf`, in one string), as their row's `of`: an app from before that took a pin, an
24810
+ * unpin or a deletion for everyone wrote the record and not their row, and changed nothing the small row's check sees.
24811
+ */
24812
+ var markOf = (light) => bytesToHex(sha256(utf8ToBytes(light))).slice(0, 32);
24813
+ function liveOf(group) {
24814
+ const s = group.state;
24815
+ return {
24816
+ top: topOf(s),
24817
+ state: {
24818
+ seq: s.seq,
24819
+ seqEpoch: s.seqEpoch,
24820
+ seen: s.seen,
24821
+ sent: s.sent,
24822
+ nicks: s.nicks,
24823
+ ...s.alone && { alone: s.alone },
24824
+ ...s.provisional && { provisional: s.provisional },
24825
+ ...s.unsaid?.length ? { unsaid: s.unsaid } : {}
24826
+ },
24827
+ ...group.came && { came: group.came }
24828
+ };
24829
+ }
24830
+ var cameOf = (group) => JSON.stringify(group.came ?? {});
24831
+ var later = (a, b) => a === void 0 ? b : b === void 0 ? a : Math.max(a, b);
24832
+ var GroupRows = class {
24833
+ raw;
24834
+ written = /* @__PURE__ */ new Map();
24835
+ /** What the engine writes a private group through: its record holds the state as it was last written whole. */
24836
+ store;
24837
+ constructor(raw) {
24838
+ this.raw = raw;
24839
+ this.store = {
24840
+ getGroups: () => raw.getGroups(),
24841
+ putGroup: (group) => this.put(group),
24842
+ deleteGroup: async (groupId) => {
24843
+ this.written.delete(groupId);
24844
+ await raw.deleteGroup(groupId);
24845
+ },
24846
+ getMessages: (linkId) => raw.getMessages(linkId)
24847
+ };
24848
+ }
24849
+ /**
24850
+ * At load: the state of each record that no app from before wrote since takes what its small row says, and its pin,
24851
+ * deletions for everyone, hubs, members' apps and members' edits what their row says while the record still holds of
24852
+ * them what it did when the row was written (`of`).
24853
+ */
24854
+ async load(groups) {
24855
+ if (!this.raw.getGroupLive) return;
24856
+ const rows = await this.raw.getGroupLive().catch(() => /* @__PURE__ */ new Map());
24857
+ const lights = await this.raw.getGroupLight?.().catch(() => void 0) ?? /* @__PURE__ */ new Map();
24858
+ for (const group of groups) {
24859
+ const live = rows.get(group.id), state = group.state, held = group.seqReserved;
24860
+ if (!live || !state || group.community) continue;
24861
+ if (!held || held.e !== state.seqEpoch || held.n !== state.seq || live.top !== topOf(state) || live.state.seqEpoch !== state.seqEpoch || !(live.state.seq <= state.seq)) {
24862
+ if (live.came) group.came = {
24863
+ ...group.came,
24864
+ ...live.came,
24865
+ peer: later(group.came?.peer, live.came.peer),
24866
+ mention: later(group.came?.mention, live.came.mention)
24867
+ };
24868
+ continue;
24869
+ }
24870
+ if (live.came) group.came = live.came;
24871
+ else delete group.came;
24872
+ const recorded = group.large ?? [], of = markOf(JSON.stringify(lightOf(group, recorded)));
24873
+ const light = lights.get(group.id), fresh = light && (light.of === void 0 || light.of === of) ? light : void 0;
24874
+ if (fresh) {
24875
+ if (fresh.pin) group.pin = fresh.pin;
24876
+ else delete group.pin;
24877
+ if (fresh.removedIds.length) group.removedIds = fresh.removedIds;
24878
+ else delete group.removedIds;
24879
+ if (fresh.removals.length) group.removals = fresh.removals;
24880
+ else delete group.removals;
24881
+ if (fresh.hubs) group.hubs = fresh.hubs;
24882
+ if (fresh.large) group.large = [.../* @__PURE__ */ new Set([...recorded, ...fresh.large])];
24883
+ }
24884
+ const merged = { ...state };
24885
+ for (const field of LIVE) delete merged[field];
24886
+ group.state = Object.assign(merged, live.state, fresh?.relayEdits && { relayEdits: fresh.relayEdits });
24887
+ this.written.set(group.id, {
24888
+ key: recordKey(state),
24889
+ state: structuredClone(state),
24890
+ rest: restKey(group),
24891
+ of,
24892
+ large: recorded,
24893
+ edits: editsOf(group.state),
24894
+ came: cameOf(group)
24895
+ });
24896
+ }
24897
+ }
24898
+ /**
24899
+ * A session's save: its small row alone while the rest of its state is what the record holds, and the members' edits'
24900
+ * row when they changed; else the record too.
24901
+ */
24902
+ async save(group) {
24903
+ const written = this.written.get(group.id), state = group.state, edits = editsOf(state);
24904
+ if (this.raw.putGroupLive && written && holds(written.state, written.key, state) && (edits === written.edits || this.raw.putGroupLight)) {
24905
+ await this.raw.putGroupLive(group.id, liveOf(group));
24906
+ written.came = cameOf(group);
24907
+ if (edits === written.edits) return;
24908
+ await this.raw.putGroupLight(group.id, {
24909
+ ...lightOf(group, written.large),
24910
+ of: written.of
24911
+ });
24912
+ written.edits = edits;
24913
+ return;
24914
+ }
24915
+ await this.put(group);
24916
+ }
24917
+ async put(group) {
24918
+ const state = group.state;
24919
+ if (!this.raw.putGroupLive || group.community) return this.raw.putGroup(group);
24920
+ if (!state) {
24921
+ this.written.delete(group.id);
24922
+ return this.raw.putGroup(group, null);
24923
+ }
24924
+ const was = this.written.get(group.id);
24925
+ if (was && holds(was.state, was.key, state)) {
24926
+ const rest = restKey(group);
24927
+ if (rest === was.rest && this.raw.putGroupLight) {
24928
+ await this.raw.putGroupLight(group.id, {
24929
+ ...lightOf(group, was.large),
24930
+ of: was.of
24931
+ });
24932
+ was.edits = editsOf(state);
24933
+ const came = cameOf(group);
24934
+ if (came !== was.came) {
24935
+ await this.raw.putGroupLive(group.id, liveOf(group));
24936
+ was.came = came;
24937
+ }
24938
+ return;
24939
+ }
24940
+ const record = {
24941
+ ...group,
24942
+ state: {
24943
+ ...was.state,
24944
+ relayEdits: state.relayEdits
24945
+ },
24946
+ seqReserved: {
24947
+ e: was.state.seqEpoch,
24948
+ n: was.state.seq
24949
+ }
24950
+ };
24951
+ await this.whole(group, record, was);
24952
+ Object.assign(was, {
24953
+ rest,
24954
+ large: record.large ?? [],
24955
+ edits: editsOf(state),
24956
+ came: cameOf(group)
24957
+ });
24958
+ return;
24959
+ }
24960
+ const written = {
24961
+ key: recordKey(state),
24962
+ state: {
24963
+ ...structuredClone(state),
24964
+ seq: state.seq + SEQ_BLOCK
24965
+ },
24966
+ rest: restKey(group),
24967
+ of: "",
24968
+ large: group.large ?? [],
24969
+ edits: editsOf(state),
24970
+ came: cameOf(group)
24971
+ };
24972
+ this.written.set(group.id, written);
24973
+ try {
24974
+ await this.whole(group, {
24975
+ ...group,
24976
+ state: written.state,
24977
+ seqReserved: {
24978
+ e: state.seqEpoch,
24979
+ n: written.state.seq
24980
+ }
24981
+ }, written);
24982
+ } catch (error) {
24983
+ if (this.written.get(group.id) === written) this.written.delete(group.id);
24984
+ throw error;
24985
+ }
24986
+ }
24987
+ /**
24988
+ * The record written whole as `record`, with the small row, and its `GroupLight` row deleted: the record holds the pin,
24989
+ * the deletions, the hubs, the members' apps and the members' edits again (`written.of`). One that changed while it was
24990
+ * being written goes to its row again after it.
24991
+ */
24992
+ async whole(group, record, written) {
24993
+ const kept = record.large ?? [], light = JSON.stringify(lightOf(record, kept)), of = markOf(light);
24994
+ written.of = of;
24995
+ await this.raw.putGroup(record, liveOf(group));
24996
+ if (this.raw.putGroupLight && JSON.stringify(lightOf(group, kept)) !== light) await this.raw.putGroupLight(group.id, {
24997
+ ...lightOf(group, kept),
24998
+ of
24999
+ });
25000
+ }
25001
+ };
25002
+ /** Whether a record holding `written` (its `recordKey` `key`) holds `state` too, but for what the small row says. */
25003
+ function holds(written, key, state) {
25004
+ return written.seqEpoch === state.seqEpoch && state.seq <= written.seq && key === recordKey(state);
25005
+ }
25006
+ //#endregion
24371
25007
  //#region ../browser/src/engine/groupAuthorOrder.ts
24372
25008
  /**
24373
25009
  * How long a member's message may still be placed again below that member's older ones (WISP 400, requirement 10):
@@ -24849,9 +25485,9 @@ var ENTRY_LINGER_MS$1 = 2e4;
24849
25485
  * often while it stays full, its side of the entry session closed `FULL_LINGER_MS` after. The joiner shows it is full
24850
25486
  * for `FULL_SAID_MS` after the last one (one answer missed included), then waits as before.
24851
25487
  */
24852
- var FULL_TELL_MS = 3e5;
24853
- var FULL_LINGER_MS = 5e3;
24854
- var FULL_SAID_MS = 66e4;
25488
+ var FULL_TELL_MS$1 = 3e5;
25489
+ var FULL_LINGER_MS$1 = 5e3;
25490
+ var FULL_SAID_MS$1 = 66e4;
24855
25491
  /**
24856
25492
  * Whether this device can let in no one new now (WISP 903 § Admissions while the admin is away): members signed
24857
25493
  * `COMMUNITY_LIMITS.memberAdmissions` admissions in a row, counted as the session's `commit` counts them. Its hub
@@ -24903,7 +25539,18 @@ var FAREWELL_SKEW_MS = 3e5;
24903
25539
  var HUB_CLOCK_READ_GAP_MS$1 = 45e3;
24904
25540
  /** A member that opens the group's link again knocks to check it is still in, this long at most (`joinByLink`). */
24905
25541
  var CHECK_MS = 18e4;
25542
+ /** How long a community I left follows its chain (`leftBehind`): a hand-over that crossed my leave reaches me within it. */
25543
+ var LEFT_FOLLOW_MS = 6e5;
25544
+ /**
25545
+ * A role that reached my leave goes on this long after: the leave its giver said right after its `role` commit (an
25546
+ * admin's leave does) is heard first, so the role does not go back to a leaver.
25547
+ */
25548
+ var LEFT_HAND_ON_MS$1 = 1e3;
24906
25549
  var MESSAGE_LINK$1 = (groupId) => `group:${groupId}`;
25550
+ /** The newest hand-over in a chain. */
25551
+ var lastRole = (chain) => {
25552
+ for (let i = chain.length - 1; i >= 0; i--) if (chain[i].k === "role") return chain[i];
25553
+ };
24907
25554
  /**
24908
25555
  * A member key for a joiner whose entry session the member's side dials. Of a paired session's two
24909
25556
  * ends only the lower key dials, and only once it has seen the other; the member's side opens when it
@@ -24948,6 +25595,11 @@ var Communities = class {
24948
25595
  /** Since when this run knocks with nobody answering (`JOIN_GIVE_UP_MS`), and the joins it gave up (`Groups.giveUpJoin`). */
24949
25596
  knockingSince = /* @__PURE__ */ new Map();
24950
25597
  gaveUp = /* @__PURE__ */ new Set();
25598
+ /**
25599
+ * Communities I left, gone from here but for their session and edges, which follow the chain a while
25600
+ * (`LEFT_FOLLOW_MS`): the leave I said, whose leaves I heard since, and when a role that reached me goes on.
25601
+ */
25602
+ leftBehind = /* @__PURE__ */ new Map();
24951
25603
  /** Joiners: the knock record a knock read whose write the relays refused, and when it was read (`knock`). */
24952
25604
  knockRead = /* @__PURE__ */ new Map();
24953
25605
  /** My frames an edge took, and which of them carry an edit (`frame id → editKey`). */
@@ -25006,8 +25658,9 @@ var Communities = class {
25006
25658
  }
25007
25659
  /** Files and voice messages (WISP 503), the desk `Groups` keeps for every group. */
25008
25660
  files;
25661
+ /** A community I left is still this engine's while it follows its chain (`leftBehind`): its edges' frames come here. */
25009
25662
  has(groupId) {
25010
- return this.stored.has(groupId);
25663
+ return this.stored.has(groupId) || this.leftBehind.has(groupId);
25011
25664
  }
25012
25665
  ids() {
25013
25666
  return [...this.stored.keys()];
@@ -25129,7 +25782,7 @@ var Communities = class {
25129
25782
  community: {
25130
25783
  hub: live.hub,
25131
25784
  hubs: hubs.length,
25132
- connected: [...edges.keys()].filter(ready).length,
25785
+ connected: [...edges.keys()].filter((key) => ready(key) && !this.gone(live, key)).length,
25133
25786
  ...s.isAdmin && live.unansweredTold && { unansweredKnocks: live.unanswered.size }
25134
25787
  },
25135
25788
  members: roster.map(([key, role]) => ({
@@ -25157,7 +25810,7 @@ var Communities = class {
25157
25810
  /** A member's app said lately that the community is full (`group-full`): how full, as it said. */
25158
25811
  fullSaid(groupId) {
25159
25812
  const told = this.toldFull.get(groupId);
25160
- return told && this.now() - told.at < FULL_SAID_MS ? {
25813
+ return told && this.now() - told.at < FULL_SAID_MS$1 ? {
25161
25814
  n: told.n,
25162
25815
  max: told.max
25163
25816
  } : void 0;
@@ -25182,6 +25835,7 @@ var Communities = class {
25182
25835
  if (!link) throw new Error("This is not a link to a group");
25183
25836
  const existing = this.stored.get(link.g);
25184
25837
  const live = this.live.get(link.g);
25838
+ await this.dropLeftBehind(link.g);
25185
25839
  if (existing?.joining && existing.joining.host === link.host) {
25186
25840
  await this.knockAgain(link.g);
25187
25841
  return link.g;
@@ -25359,11 +26013,13 @@ var Communities = class {
25359
26013
  };
25360
26014
  }
25361
26015
  /** An application frame to everyone in the group (WISP 903 · Group Community § Payments). */
25362
- async sendApp(groupId, frame) {
26016
+ /** `key`: what taking the frame takes, for `taken` (a reaction's `reactionKey`). */
26017
+ async sendApp(groupId, frame, key) {
25363
26018
  const live = this.live.get(groupId);
25364
26019
  if (!live) throw new Error("You are not in this group yet");
25365
26020
  const result = await live.session.sendApp(frame, this.host.myNick?.(), this.now());
25366
26021
  if ("error" in result) throw new Error(result.error);
26022
+ if (key) this.carry(groupId, result.id, key);
25367
26023
  }
25368
26024
  /** An edit of my message, through the group like any frame (WISP 903 · Group Community § Edits). An error when it cannot go now. */
25369
26025
  async sendEdit(groupId, edit) {
@@ -25379,12 +26035,15 @@ var Communities = class {
25379
26035
  ...edit.rm && { remove: true }
25380
26036
  }, this.host.myNick?.(), this.now());
25381
26037
  if ("error" in result) return result.error;
25382
- const key = editKey(edit.id, edit.e);
25383
- this.carriers.set(result.id, key);
25384
- if (this.carriers.size > 512) this.carriers.delete(this.carriers.keys().next().value);
25385
- for (let i = 0; i < this.frames.count(groupId, result.id); i++) this.frames.add(groupId, key);
26038
+ this.carry(groupId, result.id, editKey(edit.id, edit.e));
25386
26039
  return null;
25387
26040
  }
26041
+ /** What rides in a frame of its own (an edit, a reaction): what takes that frame (now, or in a catch-up later) takes it. */
26042
+ carry(groupId, id, key) {
26043
+ this.carriers.set(id, key);
26044
+ if (this.carriers.size > 512) this.carriers.delete(this.carriers.keys().next().value);
26045
+ for (let i = 0; i < this.frames.count(groupId, id); i++) this.frames.add(groupId, key);
26046
+ }
25388
26047
  /** A payload for one member only, sealed to them and carried by the group (hubs relay it, members keep it for them). */
25389
26048
  async sendPair(groupId, to, payload) {
25390
26049
  const live = this.live.get(groupId);
@@ -25417,11 +26076,104 @@ var Communities = class {
25417
26076
  next = s.others.find((key) => connected.has(key)) ?? s.others[0];
25418
26077
  await s.transferAdmin(next);
25419
26078
  }
25420
- await s.leave();
25421
- await this.forget(groupId);
26079
+ const frame = await s.leave(true);
26080
+ if (frame) this.leftBehind.set(groupId, {
26081
+ session: s,
26082
+ frame,
26083
+ since: this.now(),
26084
+ heard: /* @__PURE__ */ new Set()
26085
+ });
26086
+ await this.forget(groupId, !!frame);
26087
+ await s.followAfterLeave();
25422
26088
  return next;
25423
26089
  }
25424
26090
  /**
26091
+ * A community I left, and a frame from its edges (WISP 903 § Leaving, "A role that reaches a leave"): a member's leave
26092
+ * (the role does not go on to it), or what moves the chain. Once it takes me out, my leave is done; when it makes me
26093
+ * the admin, the role goes on at the next tick past `LEFT_HAND_ON_MS` (`handOn`).
26094
+ */
26095
+ async afterLeave(groupId, from, raw) {
26096
+ const left = this.leftBehind.get(groupId), s = left?.session;
26097
+ if (!left || !s || !raw || typeof raw !== "object") return;
26098
+ const f = raw;
26099
+ let fresh = false;
26100
+ if (f.t === "group-leave") {
26101
+ const by = f.s !== s.myKey && !left.heard.has(f.s) ? s.signedLeave(f) : void 0;
26102
+ if (by) {
26103
+ left.heard.add(by);
26104
+ fresh = true;
26105
+ }
26106
+ } else fresh = await s.handle(from, raw) && f.t === "group-commit";
26107
+ if (fresh && rosterHas(s.roster, s.myKey)) {
26108
+ for (const [key, linkId] of this.host.edges(groupId)) if (key !== from) this.sendTo(linkId, f);
26109
+ }
26110
+ await this.leftMoved(groupId, this.now());
26111
+ }
26112
+ /** Where the chain of a community I left stands now: out (done), or the admin (the role goes on), or neither. */
26113
+ async leftMoved(groupId, now) {
26114
+ const left = this.leftBehind.get(groupId), s = left?.session;
26115
+ if (!left || !s) return;
26116
+ if (!rosterHas(s.roster, s.myKey) && !this.handedToLeaver(left)) await this.dropLeftBehind(groupId);
26117
+ else if (now - left.since > LEFT_FOLLOW_MS) await this.dropLeftBehind(groupId);
26118
+ else if (!rosterHas(s.roster, s.myKey)) left.handOnAt = void 0;
26119
+ else if (s.admin !== s.myKey) left.handOnAt = void 0;
26120
+ else {
26121
+ if (s.leftWaitsForSecret && now - (left.askedAt ?? 0) >= 5e3) {
26122
+ left.askedAt = now;
26123
+ const ready = [...this.host.edges(groupId)].filter(([key, id]) => key !== s.myKey && this.host.linkReady(id, 2) && rosterHas(s.roster, key)).map(([key]) => key);
26124
+ for (const key of ready.slice(0, 3)) s.catchUp(key);
26125
+ }
26126
+ if (left.handOnAt === void 0) left.handOnAt = now + LEFT_HAND_ON_MS$1;
26127
+ else if (now >= left.handOnAt) await this.handOn(groupId, now);
26128
+ }
26129
+ }
26130
+ /**
26131
+ * The role I handed on before I left is still with the member I gave it to, and that member's leave reached me: its
26132
+ * hand-on (`handOn`) may reach the group only through my edges, even once a hub committed my own leave (WISP 903,
26133
+ * "A role that reaches a leave": an older hub does not keep my request while the admin's waits).
26134
+ */
26135
+ handedToLeaver(left) {
26136
+ const s = left.session, admin = s.admin, role = lastRole(s.state.chain);
26137
+ return !!admin && admin !== s.myKey && role?.by === s.myKey && role.s === admin && (left.heard.has(admin) || s.state.pendingLeaves.some((r) => r.s === admin));
26138
+ }
26139
+ /**
26140
+ * Whom a role that reached my leave goes on to: the member whose `role` commit gave it to me (`by`, whatever was
26141
+ * committed on top since), while it stays; else the first other member whose edge is up,
26142
+ * else the first in the roster. Never one whose leave I heard, nor one I handed the role to myself (an admin who left):
26143
+ * with two leavers the role would go back and forth between them.
26144
+ */
26145
+ nextAdmin(groupId, left, by) {
26146
+ const s = left.session, handed = new Set(s.state.chain.filter((c) => c.k === "role" && c.by === s.myKey).map((c) => c.s));
26147
+ const eligible = s.others.filter((key) => !left.heard.has(key) && !handed.has(key));
26148
+ if (eligible.includes(by)) return by;
26149
+ const edges = this.host.edges(groupId);
26150
+ return eligible.find((key) => {
26151
+ const id = edges.get(key);
26152
+ return !!id && this.host.linkReady(id, 2);
26153
+ }) ?? eligible[0];
26154
+ }
26155
+ /**
26156
+ * A role that reached my leave goes on (`nextAdmin`), and my leave is said again: a hub from before dropped it while
26157
+ * it named the admin, and one that came on since never had it.
26158
+ */
26159
+ async handOn(groupId, now) {
26160
+ const left = this.leftBehind.get(groupId), s = left?.session;
26161
+ if (!left || !s) return;
26162
+ try {
26163
+ if (!await s.handOnAfterLeave((by) => this.nextAdmin(groupId, left, by), now)) return;
26164
+ } catch {
26165
+ return;
26166
+ }
26167
+ left.handOnAt = void 0;
26168
+ left.since = now;
26169
+ for (const [, linkId] of this.host.edges(groupId)) this.sendTo(linkId, left.frame);
26170
+ }
26171
+ /** A community I left stops following its chain: its edges close, unless I am in it again. */
26172
+ async dropLeftBehind(groupId) {
26173
+ if (!this.leftBehind.delete(groupId) || this.stored.has(groupId)) return;
26174
+ for (const linkId of this.host.edges(groupId).values()) await this.host.closeEdge(linkId);
26175
+ }
26176
+ /**
25425
26177
  * Delete from this device: left first, as Leave does. With nothing connected to carry the request, a member's leave
25426
26178
  * goes unsaid and the group goes anyway, as a private group's failed goodbye does: the others still list the device,
25427
26179
  * but members who never open the app again kept it here for good. An admin with members is still refused: gone with
@@ -25501,7 +26253,8 @@ var Communities = class {
25501
26253
  if (live) throw new Error("You were in this group: leave it to stop trying to get back in");
25502
26254
  await this.forget(groupId);
25503
26255
  }
25504
- async forget(groupId) {
26256
+ /** `keepEdges`: a community I just left, whose edges follow its chain a while yet (`leftBehind`). */
26257
+ async forget(groupId, keepEdges = false) {
25505
26258
  const live = this.live.get(groupId);
25506
26259
  if (live?.hub) await this.publishBeacon(groupId, live, this.now(), false).catch(() => {});
25507
26260
  this.live.delete(groupId);
@@ -25512,7 +26265,8 @@ var Communities = class {
25512
26265
  this.knockingSince.delete(groupId);
25513
26266
  this.gaveUp.delete(groupId);
25514
26267
  this.lineOrder.forget(MESSAGE_LINK$1(groupId));
25515
- for (const linkId of [...this.host.edges(groupId).values(), ...this.host.entries(groupId).values()]) await this.host.closeEdge(linkId);
26268
+ if (!keepEdges) this.leftBehind.delete(groupId);
26269
+ for (const linkId of [...keepEdges ? [] : this.host.edges(groupId).values(), ...this.host.entries(groupId).values()]) await this.host.closeEdge(linkId);
25516
26270
  await this.store.deleteGroup(groupId);
25517
26271
  await this.files?.drop(groupId);
25518
26272
  this.host.historyGone?.(groupId);
@@ -25585,6 +26339,7 @@ var Communities = class {
25585
26339
  await this.topology(group.id, live, now).catch(() => {});
25586
26340
  }
25587
26341
  for (const [key, until] of this.refused) if (until <= now) this.refused.delete(key);
26342
+ for (const groupId of [...this.leftBehind.keys()]) await this.leftMoved(groupId, now);
25588
26343
  }
25589
26344
  async topology(groupId, live, now) {
25590
26345
  const s = live.session, me = s.myKey;
@@ -25786,6 +26541,7 @@ var Communities = class {
25786
26541
  for (const key of ready.slice(0, 3)) s.catchUp(key);
25787
26542
  }
25788
26543
  await s.resume().catch(() => {});
26544
+ if (s.settleGaps()) this.host.emit();
25789
26545
  await s.reseal().catch(() => {});
25790
26546
  await this.reconcile(groupId, live, now);
25791
26547
  }
@@ -26031,7 +26787,10 @@ var Communities = class {
26031
26787
  * into the beacon (CLI daemons on local relays, 2026-10-03).
26032
26788
  */
26033
26789
  gone(live, key) {
26034
- return live.session.wasRemoved(key) || live.session.state.pendingLeaves.some((r) => r.s === key);
26790
+ const s = live.session;
26791
+ if (s.wasRemoved(key)) return true;
26792
+ if (key === s.admin || !s.state.pendingLeaves.some((r) => r.s === key)) return false;
26793
+ return !(s.state.pendingLeaves.some((r) => r.s === s.admin) && [...s.state.chain].reverse().find((c) => c.k === "role")?.by === key);
26035
26794
  }
26036
26795
  /** Out of the group by its own leave (it signed the request), not removed: its app knows it went. */
26037
26796
  leftItself(live, key) {
@@ -26047,6 +26806,7 @@ var Communities = class {
26047
26806
  mayHear(live, key, frame, said = false) {
26048
26807
  const f = frame;
26049
26808
  if (live?.session.wasRemoved(key)) return f.t === "group-commit" && (f.commit?.k === "remove" || f.commit?.k === "leave") && f.commit.s === key;
26809
+ if (live && said && this.gone(live, key)) return f.t === "group-commit" || f.t === "group-leave";
26050
26810
  if (!live || !said || rosterHas(live.session.roster, key)) return true;
26051
26811
  return f.t === "group-commit" && live.session.isRecentMember(key);
26052
26812
  }
@@ -26198,7 +26958,7 @@ var Communities = class {
26198
26958
  for (const key of live.farewells.keys()) wanted.add(key);
26199
26959
  for (const key of live.ahead.keys()) wanted.add(key);
26200
26960
  } else for (const key of live.myHubs) wanted.add(key);
26201
- for (const [key, id] of existing) if (this.host.linkReady(id, 2) && (live.members.has(key) || this.recentHub(live, key)) && !s.wasRemoved(key)) wanted.add(key);
26961
+ for (const [key, id] of existing) if (this.host.linkReady(id, 2) && (live.members.has(key) || this.recentHub(live, key)) && !this.gone(live, key)) wanted.add(key);
26202
26962
  }
26203
26963
  for (const [key, since] of live.restored) {
26204
26964
  if (!since) live.restored.set(key, now);
@@ -26319,7 +27079,7 @@ var Communities = class {
26319
27079
  const s = live.session;
26320
27080
  if (!s.adminWork || !s.entryKey || !s.state.entry.seedB64) return;
26321
27081
  const full = s.roster.length >= COMMUNITY_LIMITS.members, held = admissionsHeld(s);
26322
- for (const [key, at] of live.fullTold) if (now - at >= FULL_TELL_MS) live.fullTold.delete(key);
27082
+ for (const [key, at] of live.fullTold) if (now - at >= FULL_TELL_MS$1) live.fullTold.delete(key);
26323
27083
  const link = {
26324
27084
  g: groupId,
26325
27085
  host: s.entryKey
@@ -26515,7 +27275,7 @@ var Communities = class {
26515
27275
  } catch {}
26516
27276
  live.pendingEntries.delete(peer);
26517
27277
  live.fullTold.set(peer, now);
26518
- live.lingering.set(linkId, now + FULL_LINGER_MS);
27278
+ live.lingering.set(linkId, now + FULL_LINGER_MS$1);
26519
27279
  return true;
26520
27280
  }
26521
27281
  if (!rosterHas(s.roster, peer) && admissionsHeld(s)) {
@@ -26681,7 +27441,11 @@ var Communities = class {
26681
27441
  /** A frame on an edge, from the member it is pinned to: handled, then relayed on by a hub. */
26682
27442
  async handleEdgeFrame(groupId, peerKey, frame) {
26683
27443
  const live = this.live.get(groupId);
26684
- if (!live || !frame || typeof frame !== "object") return;
27444
+ if (!live) {
27445
+ await this.afterLeave(groupId, peerKey, frame);
27446
+ return;
27447
+ }
27448
+ if (!frame || typeof frame !== "object") return;
26685
27449
  const f = frame;
26686
27450
  if (live.session.wasRemoved(peerKey)) {
26687
27451
  if (f.t === "group-sync" && live.session.isMember) this.sayFarewell(groupId, live, peerKey, f);
@@ -28091,9 +28855,14 @@ function otherEndSeen(presence, dataLink, now = Date.now()) {
28091
28855
  }
28092
28856
  /** The key an edit of message `id` goes by in `FramesTaken`. */
28093
28857
  var editKey = (id, e) => `${id}#e${e}`;
28858
+ /** The key my reaction numbered `n` goes by in `FramesTaken` (the number is mine in the group, whatever the message). */
28859
+ var reactionKey = (n) => `#r${n}`;
28860
+ /** The key my pin (or unpin) numbered `n` goes by in `FramesTaken`: one pin per group, its number newer each time. */
28861
+ var pinKey = (n) => `#p${n}`;
28094
28862
  /**
28095
28863
  * Which of my frames an edge took (handed to an open session), per group: what `ghostly group send --wait sent` waits
28096
- * for. A message by its id, an edit by `editKey`. A group has no receipts: this is as far as the author can see.
28864
+ * for. A message by its id, an edit by `editKey`, a reaction by `reactionKey`, a pin by `pinKey`. A group has no
28865
+ * receipts: this is as far as the author can see.
28097
28866
  */
28098
28867
  var FramesTaken = class {
28099
28868
  counts = /* @__PURE__ */ new Map();
@@ -28317,6 +29086,14 @@ var JAMMED_WINDOW_MS = 9e5;
28317
29086
  /** A joiner refused (its app cannot follow the group) is not answered again for this long. */
28318
29087
  var REFUSED_FOR_MS = 6e5;
28319
29088
  /**
29089
+ * A full group's admin answers a knock with `group-full` (WISP 902 § A full group): the same joiner at most this often
29090
+ * while there is no room, its side of the entry session closed `FULL_LINGER_MS` after. The joiner shows it is full for
29091
+ * `FULL_SAID_MS` after the last one (one answer missed included), then waits as before.
29092
+ */
29093
+ var FULL_TELL_MS = 3e5;
29094
+ var FULL_LINGER_MS = 5e3;
29095
+ var FULL_SAID_MS = 66e4;
29096
+ /**
28320
29097
  * The removed ids with this one noted. Full, the oldest of the author who has the most goes (the one just noted's own on
28321
29098
  * a tie): a member's removals of messages that are not here, as many as they like, push out only their own.
28322
29099
  */
@@ -28371,6 +29148,8 @@ var ACCEPT_AGAINS = 5;
28371
29148
  var REWELCOME_MS = ACCEPT_AGAIN_MS / 2;
28372
29149
  /** Invitee side: the invitations one contact chat may have waiting here at a time. More are answered as declined. */
28373
29150
  var MAX_INVITATIONS_PER_CHAT = 4;
29151
+ /** Invitee side: the invitations that may wait here at a time, all contact chats together. More are not kept. */
29152
+ var MAX_WAITING_INVITATIONS = 32;
28374
29153
  /** Other groups kept beside one under its id (`StoredGroup.others`), at most; an invitation past them is declined. */
28375
29154
  var MAX_OTHER_GROUPS = 4;
28376
29155
  /** Invitee side, removed and invited again: the chat that let me into the group I kept, if it is its admin's. */
@@ -28456,7 +29235,6 @@ function meshEdgeIntervals(base, members) {
28456
29235
  */
28457
29236
  var Groups = class {
28458
29237
  host;
28459
- store;
28460
29238
  timings;
28461
29239
  stored = /* @__PURE__ */ new Map();
28462
29240
  sessions = /* @__PURE__ */ new Map();
@@ -28492,6 +29270,12 @@ var Groups = class {
28492
29270
  refused = /* @__PURE__ */ new Map();
28493
29271
  /** Admin side: entry sessions of a member key that timed out in a row, and when the last did. */
28494
29272
  entryTimeouts = /* @__PURE__ */ new Map();
29273
+ /** Admin side: joiners told the group has no room (`group-full`), per group: member key → when. */
29274
+ fullTold = /* @__PURE__ */ new Map();
29275
+ /** Admin side: entry sessions a `group-full` went over, closed at `until`. */
29276
+ fullClosing = /* @__PURE__ */ new Map();
29277
+ /** Joiner side: the last `group-full` the admin's app answered with, and when. */
29278
+ toldFull = /* @__PURE__ */ new Map();
28495
29279
  lastPoll = /* @__PURE__ */ new Map();
28496
29280
  /** Admin side: when a link nobody is using was last read. Those links share one `pollMs` between them, read in turn. */
28497
29281
  lastQuietPoll = 0;
@@ -28594,10 +29378,14 @@ var Groups = class {
28594
29378
  signals;
28595
29379
  /** Files and voice messages in every group, private or community (WISP 503 · Group Files). */
28596
29380
  files;
29381
+ /** Where private groups are written: a message writes the group's small row, a commit its record too (`GroupRows`). */
29382
+ rows;
29383
+ store;
28597
29384
  constructor(host, store = db, timings = ENTRY_TIMINGS, communityTimings = COMMUNITY_TIMINGS, random, hubTimings = MESH_HUB_TIMINGS) {
28598
29385
  this.host = host;
28599
- this.store = store;
28600
29386
  this.timings = timings;
29387
+ this.rows = new GroupRows(store);
29388
+ this.store = this.rows.store;
28601
29389
  this.communities = new Communities(host, store, communityTimings, random);
28602
29390
  this.hubs = new MeshHubs(host, {
28603
29391
  stored: (id) => this.stored.get(id),
@@ -28678,6 +29466,7 @@ var Groups = class {
28678
29466
  /** `asItIs`: a copy that must stay as it was stored (limited mode, WISP 06), so nothing left over is cleared from it. */
28679
29467
  async load(asItIs = false) {
28680
29468
  const all = await this.store.getGroups();
29469
+ await this.rows.load(all);
28681
29470
  await this.communities.load(all.filter((g) => g.community || g.joining));
28682
29471
  for (const group of all.filter((g) => !g.community && !g.joining)) {
28683
29472
  this.stored.set(group.id, group);
@@ -28764,7 +29553,7 @@ var Groups = class {
28764
29553
  ...group.others?.length ? { others: group.others.map((other) => this.otherView(other)) } : {}
28765
29554
  };
28766
29555
  if (!session) {
28767
- const invitation = group.invitation;
29556
+ const invitation = group.invitation, full = invitation.entry && !invitation.admin ? this.fullSaid(group.id) : void 0;
28768
29557
  return {
28769
29558
  ...base,
28770
29559
  name: groupName(invitation.name) ?? "",
@@ -28784,6 +29573,10 @@ var Groups = class {
28784
29573
  viaLink: true,
28785
29574
  stage: this.joinStage(group),
28786
29575
  ...this.gaveUp.has(group.id) && { unanswered: true },
29576
+ ...full && { full: {
29577
+ n: full.n,
29578
+ max: full.max
29579
+ } },
28787
29580
  ...this.othersKnocked.has(group.id) && { othersKnocked: true }
28788
29581
  } : {}
28789
29582
  }
@@ -28877,20 +29670,25 @@ var Groups = class {
28877
29670
  return this.isCommunity(groupId);
28878
29671
  }
28879
29672
  /** Through a community group: an application frame to everyone, or a payload sealed to one member. */
28880
- sendCommunityApp(groupId, frame) {
28881
- return this.communities.sendApp(groupId, frame);
29673
+ sendCommunityApp(groupId, frame, key) {
29674
+ return this.communities.sendApp(groupId, frame, key);
28882
29675
  }
28883
29676
  sendCommunityPair(groupId, to, payload) {
28884
29677
  return this.communities.sendPair(groupId, to, payload);
28885
29678
  }
28886
29679
  /**
28887
- * How many edges took my message `messageId` (or its edit number `edit`) so far: in a private group, members' edges;
28888
- * in a community, the edges to my hubs, which pass it on. 0 while none did.
29680
+ * How many edges took my message `messageId` (or its edit number `edit`, or my reaction numbered `reaction`, or my pin
29681
+ * numbered `pin`) so far: in a private group, members' edges; in a community, the edges to my hubs, which pass it on.
29682
+ * 0 while none did.
28889
29683
  */
28890
- taken(groupId, messageId, edit) {
28891
- const key = edit ? editKey(messageId, edit) : messageId;
29684
+ taken(groupId, messageId, edit, reaction, pin) {
29685
+ const key = pin ? pinKey(pin) : reaction ? reactionKey(reaction) : edit ? editKey(messageId, edit) : messageId;
28892
29686
  return this.isCommunity(groupId) ? this.communities.taken(groupId, key) : this.frames.count(groupId, key);
28893
29687
  }
29688
+ /** An edge of a private group took a frame of mine the engine said on it (a reaction, a pin): `key` as `taken` reads it. */
29689
+ noteTaken(groupId, key) {
29690
+ this.frames.add(groupId, key);
29691
+ }
28894
29692
  /**
28895
29693
  * Says an edit of my message to the group (WISP 902 § Edits): over the edges of a private group (to member `to`
28896
29694
  * alone, when given), through a community like any frame. An error when it cannot go now.
@@ -29131,6 +29929,35 @@ var Groups = class {
29131
29929
  };
29132
29930
  }
29133
29931
  }
29932
+ /**
29933
+ * Invitee side: 32 invitations wait, and a new one comes over a chat whose invitations this app accepts by itself
29934
+ * (`GroupsHost.autoJoins`). It takes the place of the oldest waiting from the chat that holds the most (of chats tied,
29935
+ * the one whose oldest is oldest), its inviter told no as one past the 32 is, so that contacts whose invitations
29936
+ * nobody here answers cannot keep it out. Never one over such a chat, one being accepted, or a link's join. Nothing
29937
+ * is made room for when the new one replaces one waiting under its id (it takes no new room) or its chat holds its
29938
+ * four already. True when room was made.
29939
+ */
29940
+ async roomForAutoJoin(linkId, existing) {
29941
+ if (!this.host.autoJoins?.(linkId) || existing?.invitation && !existing.invitation.takenBack) return false;
29942
+ const waiting = [...this.stored.values()].filter((x) => x.invitation && !x.invitation.takenBack);
29943
+ if (waiting.filter((x) => x.invitation.linkId === linkId).length >= MAX_INVITATIONS_PER_CHAT) return false;
29944
+ const autoJoined = /* @__PURE__ */ new Map();
29945
+ const autoJoins = (chat) => autoJoined.get(chat) ?? autoJoined.set(chat, !!this.host.autoJoins?.(chat)).get(chat);
29946
+ const others = waiting.filter((x) => !x.state && !x.invitation.entry && !x.invitation.seedB64 && !autoJoins(x.invitation.linkId));
29947
+ const held = /* @__PURE__ */ new Map();
29948
+ for (const x of others) held.set(x.invitation.linkId, (held.get(x.invitation.linkId) ?? 0) + 1);
29949
+ const most = Math.max(0, ...held.values());
29950
+ const oldest = others.filter((x) => held.get(x.invitation.linkId) === most).sort((a, b) => a.createdAt - b.createdAt)[0];
29951
+ if (!oldest) return false;
29952
+ try {
29953
+ this.host.sendOnLink(oldest.invitation.linkId, {
29954
+ t: "group-decline",
29955
+ g: oldest.id
29956
+ });
29957
+ } catch {}
29958
+ await this.dropInvitation(oldest);
29959
+ return true;
29960
+ }
29134
29961
  /** Invitee side: a decline its inviter's chat was down for is said once that chat is up, or dropped after `LEFT_KEPT_MS`. */
29135
29962
  async declineOwed(group, now) {
29136
29963
  const { at, linkId } = group.declined;
@@ -29623,6 +30450,8 @@ var Groups = class {
29623
30450
  this.lastRoster.delete(groupId);
29624
30451
  this.lastTold.delete(groupId);
29625
30452
  this.pendingEntries.delete(groupId);
30453
+ this.fullTold.delete(groupId);
30454
+ this.toldFull.delete(groupId);
29626
30455
  this.entriesSeen.delete(groupId);
29627
30456
  this.unansweredEntries.delete(groupId);
29628
30457
  this.framesKept.delete(groupId);
@@ -29838,7 +30667,7 @@ var Groups = class {
29838
30667
  if (linkId) await this.host.closeEdge(linkId);
29839
30668
  }
29840
30669
  this.noteUnanswered(group.id, now, unanswered);
29841
- const busy = (pending?.size ?? 0) >= MAX_PENDING_ENTRIES || session.roster.length + (pending?.size ?? 0) >= GROUP_MEMBER_CAP.max;
30670
+ const busy = (pending?.size ?? 0) >= MAX_PENDING_ENTRIES;
29842
30671
  const since = now - (this.lastPoll.get(group.id) ?? 0);
29843
30672
  if (busy) continue;
29844
30673
  const held = this.knocksHeldUntil.get(group.id);
@@ -29856,6 +30685,10 @@ var Groups = class {
29856
30685
  }
29857
30686
  }
29858
30687
  for (const [key, until] of this.refused) if (until <= now) this.refused.delete(key);
30688
+ for (const [linkId, { groupId, until }] of this.fullClosing) if (now >= until || !this.host.linkReady(linkId)) {
30689
+ this.fullClosing.delete(linkId);
30690
+ if ([...this.host.entries(groupId).values()].includes(linkId)) await this.host.closeEdge(linkId);
30691
+ }
29859
30692
  for (const [key, { at }] of this.entryTimeouts) if (now - at > 36e5) this.entryTimeouts.delete(key);
29860
30693
  for (const [groupId, kept] of this.lingering) if (now >= kept.until) await this.endLinger(groupId);
29861
30694
  this.meshTick(now);
@@ -29939,6 +30772,29 @@ var Groups = class {
29939
30772
  }
29940
30773
  const session = this.sessions.get(groupId), group = this.stored.get(groupId);
29941
30774
  if (!session?.isAdmin || !group || !this.pendingEntries.get(groupId)?.has(peer)) return;
30775
+ const full = rosterHas(session.roster, peer) ? null : this.noRoom(group, session, peer);
30776
+ if (full) {
30777
+ try {
30778
+ this.host.sendOnLink(linkId, {
30779
+ t: "group-full",
30780
+ g: groupId,
30781
+ n: full.n,
30782
+ max: GROUP_MEMBER_CAP.max,
30783
+ ...full.update && { why: "update" }
30784
+ });
30785
+ traceJoin(groupId, "full.sent");
30786
+ } catch {}
30787
+ const now = this.now();
30788
+ this.pendingEntries.get(groupId)?.delete(peer);
30789
+ let told = this.fullTold.get(groupId);
30790
+ if (!told) this.fullTold.set(groupId, told = /* @__PURE__ */ new Map());
30791
+ told.set(peer, now);
30792
+ this.fullClosing.set(linkId, {
30793
+ groupId,
30794
+ until: now + FULL_LINGER_MS
30795
+ });
30796
+ return;
30797
+ }
29942
30798
  if (!rosterHas(session.roster, peer) && this.growthBlocked(group, session, session.roster.length + 1, linkId)) {
29943
30799
  this.pendingEntries.get(groupId)?.delete(peer);
29944
30800
  this.refused.set(peer, Date.now() + REFUSED_FOR_MS);
@@ -29995,9 +30851,20 @@ var Groups = class {
29995
30851
  joinStage(group) {
29996
30852
  const invitation = group.invitation;
29997
30853
  if (invitation.admin) return "admitted";
30854
+ const full = this.fullSaid(group.id);
30855
+ if (full) return full.update ? "blocked" : "full";
29998
30856
  if (this.host.linkReady(invitation.linkId) || this.host.linkSeen?.(invitation.linkId)) return "answered";
29999
30857
  return this.knocked.has(group.id) ? "knocked" : "knocking";
30000
30858
  }
30859
+ /** The admin's app said lately that the group has no room (`group-full`): how full, as it said, and whether it waits for updates. */
30860
+ fullSaid(groupId) {
30861
+ const told = this.toldFull.get(groupId);
30862
+ return told && this.now() - told.at < FULL_SAID_MS ? {
30863
+ n: told.n,
30864
+ max: told.max,
30865
+ update: told.update
30866
+ } : void 0;
30867
+ }
30001
30868
  entryOf(group) {
30002
30869
  if (!group.entry) return void 0;
30003
30870
  const { seedB64 } = group.entry;
@@ -30148,15 +31015,18 @@ var Groups = class {
30148
31015
  });
30149
31016
  let pending = this.pendingEntries.get(group.id);
30150
31017
  let ever;
31018
+ const told = this.fullTold.get(group.id);
31019
+ for (const [key, at] of told ?? []) if (now - at >= FULL_TELL_MS) told?.delete(key);
30151
31020
  for (const { key, ts } of knocks) {
30152
31021
  const again = this.unwelcomed(group, session, key);
30153
31022
  if (now - ts > 18e4 || rosterHas(session.roster, key) && !again || this.refused.has(key) || pending?.has(key) || key === entry.link.host) continue;
30154
31023
  if (!again && (ever ??= everMembers(session)).has(key)) continue;
30155
31024
  if (again && this.rewelcomedLately(group.id, key)) continue;
30156
- const entryIds = new Set(this.host.entries(group.id).values());
30157
- const contactsInvited = [...this.invited.get(group.id) ?? []].filter((id) => !entryIds.has(id)).length;
30158
- const size = session.roster.length + contactsInvited + (pending?.size ?? 0);
30159
- if ((pending?.size ?? 0) >= MAX_PENDING_ENTRIES || !again && (size >= GROUP_MEMBER_CAP.max || this.growthBlocked(group, session, size + 1))) break;
31025
+ if ((pending?.size ?? 0) >= MAX_PENDING_ENTRIES) break;
31026
+ if (!again && this.noRoom(group, session)) {
31027
+ const linkId = this.host.entries(group.id).get(key);
31028
+ if (this.fullTold.get(group.id)?.has(key) || linkId && this.fullClosing.has(linkId)) continue;
31029
+ }
30160
31030
  if (!pending) this.pendingEntries.set(group.id, pending = /* @__PURE__ */ new Map());
30161
31031
  pending.set(key, now);
30162
31032
  this.warmUntil.set(group.id, now + this.timings.warmMs);
@@ -30169,6 +31039,25 @@ var Groups = class {
30169
31039
  }
30170
31040
  return held;
30171
31041
  }
31042
+ /**
31043
+ * Why the group has no room for one more joiner, or null: full (those invited and those being let in counted, `except`
31044
+ * the joiner asked about), or past eight while a member's app takes only eight (`update`; the newcomer's own app is
31045
+ * checked on its entry session). `n`: the members it has.
31046
+ */
31047
+ noRoom(group, session, except) {
31048
+ const entryIds = new Set(this.host.entries(group.id).values());
31049
+ const contactsInvited = [...this.invited.get(group.id) ?? []].filter((id) => !entryIds.has(id)).length;
31050
+ const pending = [...this.pendingEntries.get(group.id)?.keys() ?? []].filter((key) => key !== except).length;
31051
+ const size = session.roster.length + contactsInvited + pending;
31052
+ if (size >= GROUP_MEMBER_CAP.max) return {
31053
+ n: session.roster.length,
31054
+ update: false
31055
+ };
31056
+ return this.growthBlocked(group, session, size + 1) ? {
31057
+ n: session.roster.length,
31058
+ update: true
31059
+ } : null;
31060
+ }
30172
31061
  /** The admin's entry sessions of this group whose other side was seen, once and for as long as they are open. */
30173
31062
  seenEntries(groupId) {
30174
31063
  let seen = this.entriesSeen.get(groupId);
@@ -30218,8 +31107,7 @@ var Groups = class {
30218
31107
  });
30219
31108
  const ownWaiting = existing?.invitation && !existing.invitation.takenBack && existing.invitation.linkId === linkId || existing?.others?.some((o) => "linkId" in o && o.linkId === linkId);
30220
31109
  const waiting = [...this.stored.values()].flatMap((x) => [...x.invitation && !x.invitation.takenBack ? [x.invitation.linkId] : [], ...(x.others ?? []).flatMap((o) => "linkId" in o ? [o.linkId] : [])]);
30221
- if (!ownWaiting && waiting.length >= 32) return;
30222
- if (!ownWaiting && waiting.filter((chat) => chat === linkId).length >= MAX_INVITATIONS_PER_CHAT) {
31110
+ if (!ownWaiting && (waiting.filter((chat) => chat === linkId).length >= MAX_INVITATIONS_PER_CHAT || waiting.length >= MAX_WAITING_INVITATIONS && !await this.roomForAutoJoin(linkId, existing))) {
30223
31111
  try {
30224
31112
  this.host.sendOnLink(linkId, {
30225
31113
  t: "group-decline",
@@ -30238,6 +31126,7 @@ var Groups = class {
30238
31126
  ...invitationClaims(frame)
30239
31127
  };
30240
31128
  await this.store.putGroup(existing);
31129
+ this.toldFull.delete(g);
30241
31130
  traceJoin(g, "invite.received");
30242
31131
  this.host.sendOnLink(linkId, {
30243
31132
  t: "group-accept",
@@ -30292,6 +31181,20 @@ var Groups = class {
30292
31181
  this.host.emit();
30293
31182
  return;
30294
31183
  }
31184
+ case "group-full": {
31185
+ const invitation = this.stored.get(g)?.invitation, { n, max } = frame;
31186
+ if (!invitation?.entry || this.stored.get(g).state || invitation.linkId !== linkId || invitation.admin) return;
31187
+ if (!Number.isSafeInteger(n) || !Number.isSafeInteger(max) || max < 1 || n < 0) return;
31188
+ this.toldFull.set(g, {
31189
+ n,
31190
+ max,
31191
+ update: frame.why === "update",
31192
+ at: this.now()
31193
+ });
31194
+ traceJoin(g, "full.received");
31195
+ this.host.emit();
31196
+ return;
31197
+ }
30295
31198
  case "group-accept": {
30296
31199
  const session = this.sessions.get(g);
30297
31200
  if (typeof frame.key !== "string" || !MEMBER_KEY.test(frame.key)) return;
@@ -31285,7 +32188,7 @@ var Groups = class {
31285
32188
  const group = this.stored.get(state.id);
31286
32189
  if (!group || this.sessions.get(state.id) !== session) return;
31287
32190
  group.state = next;
31288
- await this.store.putGroup(group);
32191
+ await this.rows.save(group);
31289
32192
  },
31290
32193
  send: (to, frame) => {
31291
32194
  const edge = this.host.edges(state.id).get(to);
@@ -34420,12 +35323,13 @@ var PEEK_LIMITS = {
34420
35323
  windowMs: 6e5
34421
35324
  };
34422
35325
  /**
34423
- * How a profile reads Pkarr records: the DHT itself (Desktop, unless its relays are read too), or these relays.
34424
- * Two profiles with the same path show the network nothing new when one reads the other's records.
35326
+ * How a profile reads Pkarr records: the DHT itself (Desktop, unless its relays are read too), or these relays (a
35327
+ * browser, or a Desktop profile with Hide my IP from contacts on, which keeps off the DHT). Two profiles with the same
35328
+ * path show the network nothing new when one reads the other's records.
34425
35329
  */
34426
35330
  function readPathOf(settings, direct) {
34427
35331
  const relays = [...new Set(currentRelays(settings?.relays?.length ? settings.relays : DEFAULT_RELAYS).map(normalizeRelayUrl).filter((r) => !!r))].sort();
34428
- if (direct) return settings?.readRelays === true ? `dht+${relays.join(",")}` : "dht";
35332
+ if (direct && settings?.relayOnly !== true) return settings?.readRelays === true ? `dht+${relays.join(",")}` : "dht";
34429
35333
  return relays.join(",");
34430
35334
  }
34431
35335
  /** A community group this profile is in (mesh groups publish nothing to look at). */
@@ -34969,10 +35873,8 @@ var SwapUnsettledError = class extends Error {
34969
35873
  * contact is told when the mint never made a redeem (`PaymentDesk.onSwapSettled`). The token stays unspent.
34970
35874
  */
34971
35875
  var MINT_DID_NOT_CONFIRM = "The mint did not confirm the ecash";
34972
- /** When a swap with no answer can no longer reach the mint: a request's longest life, and a margin after its last try. */
34973
- var swapOverdueAt = (swap) => Math.max(swap.createdAt + CASHU_REQUEST_TIMEOUT_MS + SWAP_SETTLED_MS, (swap.attemptEndedAt ?? Number.POSITIVE_INFINITY) + SWAP_SETTLED_MS);
34974
- /** When a melt with no answer can no longer reach the mint: its one request is sent right after it is written down. */
34975
- var meltOverdueAt = (melt) => melt.createdAt + CASHU_REQUEST_TIMEOUT_MS + SWAP_SETTLED_MS;
35876
+ /** How many of the times melts and swaps wrote down a wallet keeps on the monotonic clock (`CashuWallet.passed`). */
35877
+ var WRITTEN_KEPT = 1e3;
34976
35878
  var swapOf = (swap) => swap.swap;
34977
35879
  function normalizeMintUrl(input) {
34978
35880
  let url;
@@ -35111,13 +36013,21 @@ function within$1(ms, work, mint) {
35111
36013
  });
35112
36014
  return Promise.race([work, late]).finally(() => clearTimeout(timer));
35113
36015
  }
36016
+ /**
36017
+ * How long a mint that could not be loaded stays so for the payment poll's reads, then twice as long after each failed
36018
+ * load up to `MINT_FAILED_CAP_MS`: the payments of one round at a gone mint share its failure, instead of each loading
36019
+ * it again (three requests each), and so do payments made at different times, whose own backoffs are out of step.
36020
+ */
36021
+ var MINT_FAILED_MS = 5e3;
36022
+ var MINT_FAILED_CAP_MS = 6e5;
35114
36023
  var CashuWallet = class CashuWallet {
35115
36024
  getMints;
35116
36025
  events;
35117
36026
  getKnownMints;
35118
36027
  wallets = /* @__PURE__ */ new Map();
35119
- /** When the load in `wallets` of a mint failed: it is tried again once `MINT_FAILED_MS` passed. */
35120
- failedLoads = /* @__PURE__ */ new Map();
36028
+ /** The mints whose load in `wallets` failed: the payment poll's reads try them again at `mintAsk`'s pace. */
36029
+ failedLoads = /* @__PURE__ */ new Set();
36030
+ mintAsk = new AskBackoff(MINT_FAILED_MS, MINT_FAILED_CAP_MS);
35121
36031
  names = /* @__PURE__ */ new Map();
35122
36032
  infos = /* @__PURE__ */ new Map();
35123
36033
  locks = /* @__PURE__ */ new Map();
@@ -35153,6 +36063,12 @@ var CashuWallet = class CashuWallet {
35153
36063
  * (the mint's reserve and the coins' own fees). Only these are paid, for no more. */
35154
36064
  shownQuotes = /* @__PURE__ */ new Map();
35155
36065
  /**
36066
+ * Per time a melt or swap wrote down (`createdAt`, `attemptEndedAt`): where it stands on the monotonic clock. Whether a
36067
+ * request of it can still reach the mint is measured from there (`passed`): read by the wall clock, a clock stepped an
36068
+ * hour forward booked a melt whose answer was lost unpaid within seconds, its sats back, and then the mint paid it.
36069
+ */
36070
+ writtenAt = /* @__PURE__ */ new Map();
36071
+ /**
35156
36072
  * `getMints`: the mints of one network (the engine's default when none is named), primary first: balances,
35157
36073
  * invoices, payments of that network's Cashu wallet. `getKnownMints`: every mint the user added, whatever its
35158
36074
  * network: ecash from any of them is taken in, and counts in its own network's wallet.
@@ -35193,6 +36109,38 @@ var CashuWallet = class CashuWallet {
35193
36109
  }
35194
36110
  /** How long `stop` waits for a swap in a per-mint lock. */
35195
36111
  static STOP_WAIT_MS = 3e4;
36112
+ /** The wall-clock time a melt or swap writes down, its place on the monotonic clock kept for `passed`. */
36113
+ stamp() {
36114
+ const now = Date.now();
36115
+ this.keepWritten(now, performance.now());
36116
+ return now;
36117
+ }
36118
+ keepWritten(at, monotonic) {
36119
+ this.writtenAt.set(at, monotonic);
36120
+ if (this.writtenAt.size > WRITTEN_KEPT) this.writtenAt.delete(this.writtenAt.keys().next().value);
36121
+ }
36122
+ /**
36123
+ * How long really passed since `at`, a time a melt or swap wrote down, while this wallet ran. One written by an earlier
36124
+ * run counts by the wall clock up to the first time this run asks, never below nothing: written by a clock ahead of
36125
+ * this one, its window starts again rather than waiting for the clock to get there.
36126
+ */
36127
+ passed(at) {
36128
+ let since = this.writtenAt.get(at);
36129
+ if (since === void 0) this.keepWritten(at, since = performance.now() - Math.max(0, Date.now() - at));
36130
+ return performance.now() - since;
36131
+ }
36132
+ /** Whether no request of this melt can reach the mint any more: its one request is sent right after it is written down. */
36133
+ meltOverdue(melt) {
36134
+ return this.passed(melt.createdAt) >= CASHU_REQUEST_TIMEOUT_MS + SWAP_SETTLED_MS;
36135
+ }
36136
+ /** Whether no request of this swap can reach the mint any more: a request's longest life, and a margin after its last try. */
36137
+ swapOverdue(swap) {
36138
+ return swap.attemptEndedAt !== void 0 && this.passed(swap.createdAt) >= 42e4 && this.passed(swap.attemptEndedAt) >= 12e4;
36139
+ }
36140
+ /** Whether a swap is past the hour it is watched for (`SWAP_WATCH_MS`). */
36141
+ pastWatch(swap) {
36142
+ return this.passed(swap.createdAt) >= SWAP_WATCH_MS;
36143
+ }
35196
36144
  /**
35197
36145
  * The Cashu wallet of one network: its mints, their balance, and the network's newest movements (every network's when
35198
36146
  * none is named) with the fees they paid. Only those movements are read, however long the history is. `read` is the
@@ -35397,7 +36345,15 @@ var CashuWallet = class CashuWallet {
35397
36345
  assertAmount(amount);
35398
36346
  const mint = this.getMints(network).find(paysItsOwnInvoices);
35399
36347
  if (!mint) throw new Error("This wallet has no test mint to ask for test coins");
35400
- const response = await within$1(MINT_TIMEOUT_MS, mintInvoice(await this.wallet(mint), amount, "Ghostly test coins"), mint);
36348
+ let response;
36349
+ try {
36350
+ response = await within$1(MINT_TIMEOUT_MS, mintInvoice(await this.wallet(mint), amount, "Ghostly test coins"), mint);
36351
+ } catch (error) {
36352
+ throw mintFailed(error) ? Object.assign(engineError("mintFailedFaucet", {
36353
+ host: new URL(mint).host,
36354
+ reason: mintReason(error)
36355
+ }), { cause: error }) : error;
36356
+ }
35401
36357
  const quote = {
35402
36358
  quote: response.quote,
35403
36359
  mint,
@@ -35994,7 +36950,7 @@ var CashuWallet = class CashuWallet {
35994
36950
  mint,
35995
36951
  kind: "receive",
35996
36952
  swap: serializeSwapPreview(preview),
35997
- createdAt: Date.now(),
36953
+ createdAt: this.stamp(),
35998
36954
  token,
35999
36955
  ...records(preview.amount.toNumber())
36000
36956
  };
@@ -36059,7 +37015,7 @@ var CashuWallet = class CashuWallet {
36059
37015
  mint,
36060
37016
  kind: "send",
36061
37017
  swap: serializeSwapPreview(preview),
36062
- createdAt: Date.now()
37018
+ createdAt: this.stamp()
36063
37019
  };
36064
37020
  const inputs = among(preview.inputs);
36065
37021
  await this.sealedTransact([STORES$1.proofs, STORES$1.swaps], {
@@ -36098,7 +37054,7 @@ var CashuWallet = class CashuWallet {
36098
37054
  const refused = mintRefused(error) && swap.attemptEndedAt === void 0;
36099
37055
  const ended = {
36100
37056
  ...swap,
36101
- attemptEndedAt: Date.now()
37057
+ attemptEndedAt: this.stamp()
36102
37058
  };
36103
37059
  await this.putSwap(ended).catch(() => {});
36104
37060
  const outcome = await this.swapOutcome(ended, refused).catch(() => ({ state: "open" }));
@@ -36220,7 +37176,7 @@ var CashuWallet = class CashuWallet {
36220
37176
  gone,
36221
37177
  final: true
36222
37178
  };
36223
- if (Date.now() >= swapOverdueAt(swap)) return {
37179
+ if (this.swapOverdue(swap)) return {
36224
37180
  state: "never",
36225
37181
  gone,
36226
37182
  final: false
@@ -36352,7 +37308,7 @@ var CashuWallet = class CashuWallet {
36352
37308
  * pay the request, which another member may pay.
36353
37309
  */
36354
37310
  async redeemingFor(requestId) {
36355
- return (await this.readSwaps()).some((s) => s.kind === "receive" && !s.released && s.payment?.requestId === requestId && !(s.stuck && Date.now() >= s.createdAt + SWAP_WATCH_MS));
37311
+ return (await this.readSwaps()).some((s) => s.kind === "receive" && !s.released && s.payment?.requestId === requestId && !(s.stuck && this.pastWatch(s)));
36356
37312
  }
36357
37313
  async pollSwaps(mints) {
36358
37314
  if (!mints) {
@@ -36387,7 +37343,7 @@ var CashuWallet = class CashuWallet {
36387
37343
  if (swap.attemptEndedAt === void 0) {
36388
37344
  swap = {
36389
37345
  ...swap,
36390
- attemptEndedAt: Date.now()
37346
+ attemptEndedAt: this.stamp()
36391
37347
  };
36392
37348
  await this.putSwap(swap);
36393
37349
  }
@@ -36398,7 +37354,7 @@ var CashuWallet = class CashuWallet {
36398
37354
  };
36399
37355
  if (!(outcome.state === "open" && outcome.idle && swap.kind === "receive" && !swap.released)) this.swapAsk.forget(id);
36400
37356
  if (outcome.state === "open") {
36401
- if (swap.released && Date.now() >= swap.createdAt + SWAP_WATCH_MS) {
37357
+ if (swap.released && this.pastWatch(swap)) {
36402
37358
  await this.dropSwap(swap, /* @__PURE__ */ new Set());
36403
37359
  return;
36404
37360
  }
@@ -36431,7 +37387,7 @@ var CashuWallet = class CashuWallet {
36431
37387
  }
36432
37388
  swap = {
36433
37389
  ...swap,
36434
- attemptEndedAt: Date.now()
37390
+ attemptEndedAt: this.stamp()
36435
37391
  };
36436
37392
  await this.putSwap(swap);
36437
37393
  const refusal = mintRefused(error) ? await this.swapOutcome(swap, true).catch(() => void 0) : void 0;
@@ -36447,8 +37403,8 @@ var CashuWallet = class CashuWallet {
36447
37403
  this.events.onChange();
36448
37404
  } else later(this.swapAsk.missed(id, Date.now()));
36449
37405
  }
36450
- } else if (outcome.pending && swap.kind === "receive" && !swap.released && Date.now() >= swapOverdueAt(swap)) {
36451
- if (Date.now() < swap.createdAt + SWAP_WATCH_MS) {
37406
+ } else if (outcome.pending && swap.kind === "receive" && !swap.released && this.swapOverdue(swap)) {
37407
+ if (!this.pastWatch(swap)) {
36452
37408
  await this.putSwap({
36453
37409
  ...swap,
36454
37410
  askAt: Date.now() + SWAP_SLOW_POLL_MS
@@ -36469,7 +37425,7 @@ var CashuWallet = class CashuWallet {
36469
37425
  else if (swap.payment) later(SWAP_POLL_MS);
36470
37426
  }
36471
37427
  } else if (swap.released) {
36472
- if (outcome.final || Date.now() >= swap.createdAt + SWAP_WATCH_MS) await this.dropSwap(swap, outcome.gone);
37428
+ if (outcome.final || this.pastWatch(swap)) await this.dropSwap(swap, outcome.gone);
36473
37429
  else later(SWAP_SLOW_POLL_MS);
36474
37430
  return;
36475
37431
  } else {
@@ -36479,9 +37435,9 @@ var CashuWallet = class CashuWallet {
36479
37435
  }
36480
37436
  this.events.onChange();
36481
37437
  } catch {
36482
- if (swap.released && Date.now() >= swap.createdAt + SWAP_WATCH_MS) await this.dropSwap(swap, /* @__PURE__ */ new Set()).catch(() => {});
37438
+ if (swap.released && this.pastWatch(swap)) await this.dropSwap(swap, /* @__PURE__ */ new Set()).catch(() => {});
36483
37439
  else if (swap.released) later(SWAP_SLOW_POLL_MS);
36484
- else later(this.swapAsk.missed(id, Date.now(), Date.now() < swapOverdueAt(swap)));
37440
+ else later(this.swapAsk.missed(id, Date.now(), !this.swapOverdue(swap)));
36485
37441
  }
36486
37442
  }).catch(() => {
36487
37443
  later(SWAP_POLL_MS);
@@ -36536,7 +37492,10 @@ var CashuWallet = class CashuWallet {
36536
37492
  feeReserve: fee
36537
37493
  };
36538
37494
  } catch (error) {
36539
- lastError = error;
37495
+ lastError = mintFailed(error) ? Object.assign(engineError("mintFailedQuote", {
37496
+ host: new URL(mint).host,
37497
+ reason: mintReason(error)
37498
+ }), { cause: error }) : error;
36540
37499
  }
36541
37500
  throw lastError instanceof Error ? lastError : new Error(String(lastError));
36542
37501
  }
@@ -36591,7 +37550,7 @@ var CashuWallet = class CashuWallet {
36591
37550
  outputs: preview.outputData.map((o) => OutputData.serialize(o)),
36592
37551
  note: note?.slice(0, 140),
36593
37552
  paymentId,
36594
- createdAt: Date.now()
37553
+ createdAt: this.stamp()
36595
37554
  };
36596
37555
  await this.sealedTransact([
36597
37556
  STORES$1.proofs,
@@ -36663,7 +37622,7 @@ var CashuWallet = class CashuWallet {
36663
37622
  this.events.onChange();
36664
37623
  }
36665
37624
  } catch {}
36666
- this.meltAsk.missed(melt.quote, Date.now(), Date.now() < meltOverdueAt(melt));
37625
+ this.meltAsk.missed(melt.quote, Date.now(), !this.meltOverdue(melt));
36667
37626
  }
36668
37627
  const remaining = new Set((await this.readMelts()).map((m) => m.quote));
36669
37628
  this.meltAsk.keepOnly(remaining);
@@ -36697,7 +37656,7 @@ var CashuWallet = class CashuWallet {
36697
37656
  return "paid";
36698
37657
  }
36699
37658
  if (quote.state === "PENDING") return "pending";
36700
- if (!answered && Date.now() < meltOverdueAt(melt)) return "pending";
37659
+ if (!answered && !this.meltOverdue(melt)) return "pending";
36701
37660
  const inputs = await this.reservedProofs(melt);
36702
37661
  const states = inputs.length > 0 ? await wallet.checkProofsStates(inputs) : [];
36703
37662
  if (states.some((s) => s.state === "PENDING")) return "pending";
@@ -36805,14 +37764,17 @@ var CashuWallet = class CashuWallet {
36805
37764
  }
36806
37765
  return out;
36807
37766
  }
37767
+ /** Whether the payment poll's reads at this mint may ask it now: its last load did not fail, or its next try came. */
37768
+ mintDue(mint, now) {
37769
+ return !this.failedLoads.has(mint) || this.mintAsk.due(mint, now);
37770
+ }
36808
37771
  /**
36809
37772
  * A mint's loaded wallet. A failed load is tried again by the next caller, unless that one takes `recentFailure`
36810
- * (a payment's reads in the poll): a load failed within `MINT_FAILED_MS` is its answer too.
37773
+ * (a payment's reads in the poll): a failed load is its answer too until the mint's next try (`mintAsk`).
36811
37774
  */
36812
37775
  wallet(mint, recentFailure = false) {
36813
- const failed = this.failedLoads.get(mint);
36814
37776
  let wallet = this.wallets.get(mint);
36815
- if (failed !== void 0 && !(recentFailure && Date.now() - failed < 5e3)) wallet = void 0;
37777
+ if (this.failedLoads.has(mint) && !(recentFailure && !this.mintAsk.due(mint, Date.now()))) wallet = void 0;
36816
37778
  if (!wallet) {
36817
37779
  const loading = (async () => {
36818
37780
  const instance = new (await (loadCashu())).Wallet(mint, { unit: UNIT$1 });
@@ -36824,8 +37786,10 @@ var CashuWallet = class CashuWallet {
36824
37786
  wallet = loading;
36825
37787
  this.failedLoads.delete(mint);
36826
37788
  this.wallets.set(mint, loading);
36827
- loading.catch(() => {
36828
- if (this.wallets.get(mint) === loading) this.failedLoads.set(mint, Date.now());
37789
+ loading.then(() => this.mintAsk.forget(mint), () => {
37790
+ if (this.wallets.get(mint) !== loading) return;
37791
+ this.failedLoads.add(mint);
37792
+ this.mintAsk.missed(mint, Date.now());
36829
37793
  });
36830
37794
  }
36831
37795
  return wallet;
@@ -36961,11 +37925,13 @@ var NoEcashError = class extends Error {
36961
37925
  var arkSats = (network) => network === "bitcoin" ? "sats" : "test sats";
36962
37926
  /** The English line kept with a payment message (the CLI and older apps show it): test sats say so. */
36963
37927
  var satsOn = (network) => network === "testnet" ? "test sats" : "sats";
37928
+ /** An amount in that line, "21,000" whatever digits the device's own language writes numbers with. */
37929
+ var englishAmount = (amount) => amount.toLocaleString("en-US");
36964
37930
  /** The sender's chat line of ecash sent in a chat, from its record: one id, whether written as it goes or on a later start. */
36965
37931
  var ecashLine = (payment) => ({
36966
37932
  linkId: payment.linkId,
36967
37933
  id: `me_${payment.createdAt}`,
36968
- text: `⚡ ${payment.amount.toLocaleString()} ${satsOn(paymentNetwork(payment))}`,
37934
+ text: `⚡ ${englishAmount(payment.amount)} ${satsOn(paymentNetwork(payment))}`,
36969
37935
  sender: "me",
36970
37936
  timestamp: payment.createdAt,
36971
37937
  via: "datalink",
@@ -37148,6 +38114,18 @@ var RAIL_LOOK_MS = 1e4;
37148
38114
  * ago: otherwise a pace stays shut for as long as the clock went back.
37149
38115
  */
37150
38116
  var within = (now, at, ms) => at !== void 0 && at <= now && now - at < ms;
38117
+ /**
38118
+ * How often a wallet's own refresh asks about an open Ark request (at its server's indexer) or a contact's pending Ark
38119
+ * or USDT receipt (at the server or the chain) that has no answer yet (`AskBackoff`): at the wallet's pace while the
38120
+ * request is new (`INVOICE_PACE.fastForMs`) or the transaction is seen confirming, then twice as late after each ask
38121
+ * with nothing, up to `RECEIPT_ASK_CAP_MS`. Asked at every refresh, 5 open Ark requests cost 30 indexer reads a
38122
+ * minute and a receipt whose transaction never lands 3 RPC calls every 8 s, for as long as the app ran.
38123
+ * A refresh that read new money asks about every one at once, as do a contact's receipt or check and a wallet's removal,
38124
+ * so money that lands late, an expired request's included, is still seen.
38125
+ */
38126
+ var ARK_ASK_MS = 1e4;
38127
+ var USDT_ASK_MS = 8e3;
38128
+ var RECEIPT_ASK_CAP_MS = INVOICE_PACE.missedCapMs;
37151
38129
  var PaymentDesk = class {
37152
38130
  wallet;
37153
38131
  host;
@@ -37164,6 +38142,10 @@ var PaymentDesk = class {
37164
38142
  cashuSent = /* @__PURE__ */ new Set();
37165
38143
  checkingArk = false;
37166
38144
  checkingUsdt = false;
38145
+ /** Open Ark requests (by request id) and pending Ark receipts (by payment id) asked with nothing found yet. */
38146
+ arkAsk = new AskBackoff(ARK_ASK_MS, RECEIPT_ASK_CAP_MS);
38147
+ /** Pending USDT receipts (by payment id) whose transaction the chain does not show settled yet. */
38148
+ usdtAsk = new AskBackoff(USDT_ASK_MS, RECEIPT_ASK_CAP_MS);
37167
38149
  checkingBark = false;
37168
38150
  checkingBitcoin = false;
37169
38151
  redeeming = /* @__PURE__ */ new Map();
@@ -37424,7 +38406,7 @@ var PaymentDesk = class {
37424
38406
  await this.host.storeMessage({
37425
38407
  linkId: params.linkId,
37426
38408
  id: `me_${params.timestamp}`,
37427
- text: `Requested ${params.amount.toLocaleString()} ${test ? "test sats" : "sats"} on Fedimint`,
38409
+ text: `Requested ${englishAmount(params.amount)} ${test ? "test sats" : "sats"} on Fedimint`,
37428
38410
  sender: "me",
37429
38411
  timestamp: params.timestamp,
37430
38412
  via: "datalink",
@@ -37554,7 +38536,7 @@ var PaymentDesk = class {
37554
38536
  await this.host.storeMessage({
37555
38537
  linkId: params.linkId,
37556
38538
  id: `me_${params.timestamp}`,
37557
- text: `⚡ Requested ${params.amount.toLocaleString()} ${network === "testnet" ? "test sats" : "sats"}`,
38539
+ text: `⚡ Requested ${englishAmount(params.amount)} ${network === "testnet" ? "test sats" : "sats"}`,
37558
38540
  sender: "me",
37559
38541
  timestamp: params.timestamp,
37560
38542
  via: held ? "hold" : "datalink",
@@ -37614,7 +38596,7 @@ var PaymentDesk = class {
37614
38596
  await this.host.storeMessage({
37615
38597
  linkId,
37616
38598
  id: `me_${params.timestamp}`,
37617
- text: `⚡ Requested ${params.amount.toLocaleString()} ${satsOn(network)} from the group`,
38599
+ text: `⚡ Requested ${englishAmount(params.amount)} ${satsOn(network)} from the group`,
37618
38600
  sender: "me",
37619
38601
  timestamp: params.timestamp,
37620
38602
  via: "datalink",
@@ -38113,7 +39095,7 @@ var PaymentDesk = class {
38113
39095
  await this.host.storeMessage({
38114
39096
  linkId,
38115
39097
  id: `peer_${request.timestamp}`,
38116
- text: `⚡ Requested ${amount.toLocaleString()} ${satsOn(network)}`,
39098
+ text: `⚡ Requested ${englishAmount(amount)} ${satsOn(network)}`,
38117
39099
  sender: "peer",
38118
39100
  timestamp: request.timestamp,
38119
39101
  via: held ? "hold" : "datalink",
@@ -38290,7 +39272,7 @@ var PaymentDesk = class {
38290
39272
  await this.host.storeMessage({
38291
39273
  linkId,
38292
39274
  id: `peer_${record.createdAt}`,
38293
- text: `⚡ ${amount.toLocaleString()} ${isWorthlessMint(mint) ? "test sats" : "sats"}`,
39275
+ text: `⚡ ${englishAmount(amount)} ${isWorthlessMint(mint) ? "test sats" : "sats"}`,
38294
39276
  sender: "peer",
38295
39277
  timestamp: record.createdAt,
38296
39278
  via: "datalink",
@@ -38752,19 +39734,30 @@ var PaymentDesk = class {
38752
39734
  assertTokenUnits(unique);
38753
39735
  return unique;
38754
39736
  }
38755
- async reconcileUsdtReceipts() {
39737
+ /**
39738
+ * Each pending USDT receipt asked at the chain. `paced` (a wallet refresh that read nothing new): only the receipts
39739
+ * whose turn came (`usdtAsk`); otherwise every one now.
39740
+ */
39741
+ async reconcileUsdtReceipts(paced = false) {
38756
39742
  if (this.checkingUsdt || !this.usdt) return;
38757
39743
  this.checkingUsdt = true;
38758
39744
  try {
39745
+ const open = /* @__PURE__ */ new Set();
38759
39746
  for (const payment of this.payments.values()) {
38760
39747
  if (payment.kind !== "payment" || payment.direction !== "in" || payment.state !== "pending" || !payment.txid || payment.target?.method !== "usdt") continue;
39748
+ open.add(payment.id);
38761
39749
  const adapter = this.usdt[walletNetworkOf(payment.target.network)].adapter;
38762
39750
  if (!adapter) continue;
39751
+ if (paced && !this.usdtAsk.due(payment.id, Date.now())) continue;
38763
39752
  const result = await adapter.receipt(payment.txid, {
38764
39753
  ...payment.target,
38765
39754
  amount: payment.amount
38766
39755
  }).catch(() => null);
38767
- if (!result?.settled && !result?.failed) continue;
39756
+ if (!result?.settled && !result?.failed) {
39757
+ this.usdtAsk.missed(payment.id, Date.now(), !!result?.pending);
39758
+ continue;
39759
+ }
39760
+ this.usdtAsk.forget(payment.id);
38768
39761
  if (result.settled && this.usdtTxUsed(payment.txid, payment.requestId)) {
38769
39762
  await this.save({
38770
39763
  ...payment,
@@ -38787,6 +39780,7 @@ var PaymentDesk = class {
38787
39780
  });
38788
39781
  }
38789
39782
  }
39783
+ this.usdtAsk.keepOnly(open);
38790
39784
  } finally {
38791
39785
  this.checkingUsdt = false;
38792
39786
  }
@@ -38961,18 +39955,32 @@ var PaymentDesk = class {
38961
39955
  /**
38962
39956
  * An Ark request is paid when a virtual output of at least the amount reached the address made for it,
38963
39957
  * whoever sent it: with the contact's receipt (its txid, verified), or without one, through the indexer.
39958
+ * `paced` (a wallet refresh that read nothing new): only the requests and receipts whose turn came (`arkAsk`);
39959
+ * otherwise every one now.
38964
39960
  */
38965
- async reconcileArkReceipts() {
39961
+ async reconcileArkReceipts(paced = false) {
38966
39962
  if (this.checkingArk || !this.ark || !distinct(this.ark).some((w) => w.adapter)) return;
38967
39963
  this.checkingArk = true;
38968
39964
  try {
39965
+ const open = /* @__PURE__ */ new Set();
39966
+ const claimers = /* @__PURE__ */ new Map();
39967
+ for (const p of this.payments.values()) if (p.target?.method === "arkade" && p.kind === "request" && p.txid) claimers.set(p.txid, (claimers.get(p.txid) ?? 0) + 1);
39968
+ let claimed = new Set(claimers.keys());
38969
39969
  for (const request of [...this.payments.values()]) {
38970
39970
  if (request.kind !== "request" || request.direction !== "out" || request.state !== "pending" || request.target?.method !== "arkade") continue;
39971
+ open.add(request.id);
38971
39972
  const adapter = this.ark[walletNetworkOf(request.target.network)].adapter;
38972
39973
  if (!adapter || request.target.provider !== adapter.config.provider || request.target.network !== adapter.config.network) continue;
38973
- const claimed = new Set([...this.payments.values()].filter((p) => p.target?.method === "arkade" && p.kind === "request" && p.id !== request.id && p.txid).map((p) => p.txid));
38974
- const txid = await adapter.received(request.target.address, request.amount, request.createdAt, claimed).catch(() => void 0);
38975
- if (!txid) continue;
39974
+ if (paced && !this.arkAsk.due(request.id, Date.now())) continue;
39975
+ const own = request.txid && claimers.get(request.txid) === 1 ? request.txid : void 0;
39976
+ const txid = await adapter.received(request.target.address, request.amount, request.createdAt, own ? new Set([...claimed].filter((t) => t !== own)) : claimed).catch(() => void 0);
39977
+ if (!txid) {
39978
+ this.arkAsk.missed(request.id, Date.now(), Date.now() < request.createdAt + INVOICE_PACE.fastForMs);
39979
+ continue;
39980
+ }
39981
+ this.arkAsk.forget(request.id);
39982
+ claimers.set(txid, (claimers.get(txid) ?? 0) + 1);
39983
+ claimed = /* @__PURE__ */ new Set([...claimed, txid]);
38976
39984
  await this.settleRequest(request, { txid });
38977
39985
  for (const payment of this.payments.values()) if (payment.kind === "payment" && payment.direction === "in" && payment.requestId === request.id && payment.state === "pending") await this.save({
38978
39986
  ...payment,
@@ -38982,9 +39990,15 @@ var PaymentDesk = class {
38982
39990
  }
38983
39991
  for (const payment of this.payments.values()) {
38984
39992
  if (payment.kind !== "payment" || payment.direction !== "in" || payment.state !== "pending" || !payment.txid || payment.target?.method !== "arkade") continue;
39993
+ open.add(payment.id);
38985
39994
  const adapter = this.ark[walletNetworkOf(payment.target.network)].adapter;
38986
39995
  if (!adapter || payment.target.provider !== adapter.config.provider || payment.target.network !== adapter.config.network) continue;
38987
- if (!await adapter.verifyReceipt(payment.txid, payment.target.address, payment.amount).catch(() => false)) continue;
39996
+ if (paced && !this.arkAsk.due(payment.id, Date.now())) continue;
39997
+ if (!await adapter.verifyReceipt(payment.txid, payment.target.address, payment.amount).catch(() => false)) {
39998
+ this.arkAsk.missed(payment.id, Date.now());
39999
+ continue;
40000
+ }
40001
+ this.arkAsk.forget(payment.id);
38988
40002
  await this.save({
38989
40003
  ...payment,
38990
40004
  state: "settled"
@@ -38992,6 +40006,7 @@ var PaymentDesk = class {
38992
40006
  const request = payment.requestId ? this.payments.get(payment.requestId) : void 0;
38993
40007
  if (request?.linkId === payment.linkId && request.state === "pending") await this.settleRequest(request, { txid: payment.txid });
38994
40008
  }
40009
+ this.arkAsk.keepOnly(open);
38995
40010
  } finally {
38996
40011
  this.checkingArk = false;
38997
40012
  }
@@ -39299,7 +40314,7 @@ var PaymentDesk = class {
39299
40314
  await this.host.storeMessage({
39300
40315
  linkId: review.linkId,
39301
40316
  id: `me_${review.createdAt}`,
39302
- text: `${review.amount.toLocaleString()} ${review.network === "bitcoin" ? "sats" : "test sats"} on Fedimint`,
40317
+ text: `${englishAmount(review.amount)} ${review.network === "bitcoin" ? "sats" : "test sats"} on Fedimint`,
39303
40318
  sender: "me",
39304
40319
  timestamp: review.createdAt,
39305
40320
  via: "datalink",
@@ -39504,7 +40519,7 @@ var PaymentDesk = class {
39504
40519
  await this.host.storeMessage({
39505
40520
  linkId: payment.linkId,
39506
40521
  id: `peer_${payment.createdAt}`,
39507
- text: `⚡ ${payment.amount.toLocaleString()} ${test ? "test sats" : "sats"} on Fedimint`,
40522
+ text: `⚡ ${englishAmount(payment.amount)} ${test ? "test sats" : "sats"} on Fedimint`,
39508
40523
  sender: "peer",
39509
40524
  timestamp: payment.createdAt,
39510
40525
  via: "datalink",
@@ -40411,6 +41426,16 @@ var RTT_SAVE_MS = 3e5;
40411
41426
  var REACTION_RESEND_MS = 3e4;
40412
41427
  /** How long a deleted chat's session stays up once the ends of its moving files are said, so they get there (as a yield's goodbye). */
40413
41428
  var FILES_END_MS = 300;
41429
+ /** A link event that only asks something and acts on nothing: a deleted chat's link may still ask it (`whileChat`). */
41430
+ var ASKS_ONLY = /* @__PURE__ */ new Set(["onFileRoom"]);
41431
+ /**
41432
+ * A chat's link events, acted on only while `current` says the link is still the chat's. A deleted chat's link stays
41433
+ * up a moment to say the ends of its files (`removeLink`): what it hears meanwhile (a text, a reaction, a pin, a
41434
+ * payment, a call signal) is not taken. Each handler the chat has stays there, so the link offers what it offered.
41435
+ */
41436
+ function whileChat(events, current) {
41437
+ return Object.fromEntries(Object.entries(events).map(([name, handler]) => [name, typeof handler !== "function" || ASKS_ONLY.has(name) ? handler : (...args) => current() ? handler(...args) : void 0]));
41438
+ }
40414
41439
  /** A chat's reactions shown on the chat list before the one shown now, kept to show again when that one is taken back. */
40415
41440
  var REACTION_NOTES_KEPT = 8;
40416
41441
  /** When the contact's newest message over the DHT in these was sent (`LiveLink.pkarrSeenAt`). */
@@ -40600,6 +41625,10 @@ var LIMITED_MODE_METHODS = /* @__PURE__ */ new Set([
40600
41625
  "setFastPoll",
40601
41626
  "exportLinks",
40602
41627
  "walletBackupReminder",
41628
+ "setPresence",
41629
+ "setOwnStatus",
41630
+ "clearOwnStatus",
41631
+ "getOwnStatus",
40603
41632
  "savedMessages",
40604
41633
  "saveMessage",
40605
41634
  "deviceRestoreStartOwn"
@@ -40684,7 +41713,8 @@ var GhostlyNode = class GhostlyNode {
40684
41713
  edgeRtcOff = /* @__PURE__ */ new Map();
40685
41714
  /** Edges put back on WebRTC by a return (`edgeRtcPresence`) since the network last changed: failing again holds them native. */
40686
41715
  edgeRtcRetried = /* @__PURE__ */ new Set();
40687
- pollIntervals;
41716
+ /** The pace the app gave (`NodeOptions.pollIntervals`): the Desktop's is the DHT's. */
41717
+ ownPollIntervals;
40688
41718
  localFetch;
40689
41719
  links = /* @__PURE__ */ new Map();
40690
41720
  services = [];
@@ -40724,6 +41754,7 @@ var GhostlyNode = class GhostlyNode {
40724
41754
  walletFeedbackIds = /* @__PURE__ */ new Set();
40725
41755
  /** `cue`: a finer sound the page plays instead of the event's own when its category is on (apps/ui/src/lib/cues.ts). */
40726
41756
  feedback(type, id, linkId, mention = false, cue) {
41757
+ if ((type === "message" || type === "reaction") && this.doNotDisturb) return;
40727
41758
  const key = type + ":" + id;
40728
41759
  if (this.feedbackIds.has(key)) return;
40729
41760
  this.feedbackIds.add(key);
@@ -40743,6 +41774,12 @@ var GhostlyNode = class GhostlyNode {
40743
41774
  }
40744
41775
  /** The newest time written in each chat while this engine runs: a message written well before it is a catch-up. */
40745
41776
  newestAt = /* @__PURE__ */ new Map();
41777
+ /**
41778
+ * The chats deleted while this engine runs (`removeLink`), with how many times each was: a row that comes for one
41779
+ * later is not stored, nor one whose store was under way as it was deleted (`storeNewMessage`), the same invite
41780
+ * joined again meanwhile or not.
41781
+ */
41782
+ removedChats = /* @__PURE__ */ new Map();
40746
41783
  /** The chats whose contact's joined line came while this engine runs (`firstContactRow`), whatever `stored` says. */
40747
41784
  contactSpoke = /* @__PURE__ */ new WeakSet();
40748
41785
  /** Per group: when the last message written well before it came, came. What comes after it, as old, is its catch-up. */
@@ -40825,6 +41862,8 @@ var GhostlyNode = class GhostlyNode {
40825
41862
  cardPresses = /* @__PURE__ */ new Map();
40826
41863
  /** At most one wake-up per contact per `WAKE_INTERVAL_MS` (WISP 401 § Wake-up push). */
40827
41864
  wakeLimiter = new WakeLimiter();
41865
+ /** The push relay's last answer that was not a push service's status, until it forwards one (`EngineState.pushRelayRefused`). */
41866
+ pushRelayRefusal;
40828
41867
  /** Call wake-ups have their own, shorter limit: a call is rarer than a message and cannot wait five minutes. */
40829
41868
  callWakeLimiter = new WakeLimiter(WAKE_CALL_INTERVAL_MS);
40830
41869
  /** Mentions in private groups: one per member per 5 minutes, four per group per minute (WISP 902 · Group Mesh § Wake-up push). */
@@ -40929,11 +41968,11 @@ var GhostlyNode = class GhostlyNode {
40929
41968
  */
40930
41969
  usdtWallets = perNetwork((network) => new UsdtWallet(network, (viewChanged = true) => {
40931
41970
  if (viewChanged) this.walletChanged();
40932
- this.desk.reconcileUsdtReceipts().catch(() => {});
41971
+ this.desk.reconcileUsdtReceipts(!viewChanged).catch(() => {});
40933
41972
  }));
40934
41973
  arkWallets = perNetwork((network) => new ArkWallet(network, (viewChanged = true) => {
40935
41974
  if (viewChanged) this.walletChanged();
40936
- this.desk.reconcileArkReceipts().catch(() => {});
41975
+ this.desk.reconcileArkReceipts(!viewChanged).catch(() => {});
40937
41976
  }));
40938
41977
  barkWallets = perNetwork((network) => new BarkWallet(network, (viewChanged = true) => {
40939
41978
  if (viewChanged) this.walletChanged();
@@ -41456,10 +42495,7 @@ var GhostlyNode = class GhostlyNode {
41456
42495
  this.accepting = true;
41457
42496
  try {
41458
42497
  const { linkId } = await this.joinLink({ inviteCode: request.invite });
41459
- this.renameLink({
41460
- linkId,
41461
- label: request.name
41462
- });
42498
+ const peerNick = sanitizeDisplayText(request.name.trim().replace(/\s+/gu, " "), 48)?.replace(/ {2,}/g, " ");
41463
42499
  const message = `peer_contact_${request.key.slice(0, 32)}`;
41464
42500
  const contactAsker = {
41465
42501
  link: request.link,
@@ -41469,9 +42505,14 @@ var GhostlyNode = class GhostlyNode {
41469
42505
  const live = this.links.get(linkId);
41470
42506
  if (live) live.stored = {
41471
42507
  ...live.stored,
42508
+ peerNick,
41472
42509
  contactAsker
41473
42510
  };
41474
- await db.patchLink(linkId, { contactAsker });
42511
+ await db.patchLink(linkId, {
42512
+ peerNick,
42513
+ contactAsker
42514
+ });
42515
+ this.emitState();
41475
42516
  await this.storeMessage({
41476
42517
  linkId,
41477
42518
  id: message,
@@ -41785,6 +42826,7 @@ var GhostlyNode = class GhostlyNode {
41785
42826
  seqFloor: () => this.counterFloor,
41786
42827
  adminWork: (groupId) => !this.limitedMode && !this.groupAdminOff.has(groupId),
41787
42828
  adminTurn: (_groupId, options) => this.confirmTurn({ within: options?.wait === false ? 0 : GhostlyNode.TURN_CONFIRM_WAIT_MS }),
42829
+ autoJoins: (linkId) => !!this.options.autoJoins?.(linkId),
41788
42830
  staysOnline: () => this.options.staysOnline ?? (this.options.platform === "desktop" && typeof RTCPeerConnection !== "undefined"),
41789
42831
  peerRoom: (groupId) => {
41790
42832
  const native = Object.keys(this.nativeFactories);
@@ -41946,6 +42988,7 @@ var GhostlyNode = class GhostlyNode {
41946
42988
  const moved = row ?? (this.groups.movedMarks(groupId, id) ? await db.getMessage(chat, id) : void 0);
41947
42989
  await this.groups.removed(groupId, id);
41948
42990
  await db.deleteMessage(chat, id);
42991
+ if (id.includes(":me_")) this.awaitingSoon();
41949
42992
  if (moved) await this.groups.unmark(groupId, moved);
41950
42993
  this.quoteSweeps.add(chat, id, id);
41951
42994
  await this.messagesChanged(chat, [id]);
@@ -42070,26 +43113,40 @@ var GhostlyNode = class GhostlyNode {
42070
43113
  ...options.singleDevice ? { runsHere: async () => true } : {},
42071
43114
  readPath: () => readPathOf(this.relays ? { relays: this.relays.describe().relays } : this.settings, !!this.transport.configure)
42072
43115
  });
42073
- this.pollIntervals = options.pollIntervals ?? RELAY_POLL_INTERVALS;
43116
+ this.ownPollIntervals = options.pollIntervals ?? RELAY_POLL_INTERVALS;
42074
43117
  this.localFetch = options.localFetch ?? webLocalFetch;
42075
43118
  this.hold.host.transport = this.transport;
42076
43119
  this.transport.subscribe?.(() => this.emitState());
42077
43120
  this.clockOff = this.transport.onServerTime?.((time) => this.clock.server(time.source, time.date, time.sent, time.received));
42078
43121
  }
42079
- /** The Desktop reaches the DHT itself: the relays in Settings are written to, and read from only when the person chose so. */
43122
+ /**
43123
+ * The Desktop reaches the DHT itself: the relays in Settings are written to, and read from only when the person chose
43124
+ * so. With Hide my IP from contacts on, it does not reach the DHT at all: reads and writes go through the relays.
43125
+ */
42080
43126
  configureDirect() {
42081
43127
  this.transport.configure?.({
42082
43128
  relays: this.settings.relays,
42083
- readRelays: this.settings.readRelays === true
43129
+ readRelays: this.settings.readRelays === true,
43130
+ dhtDirect: this.settings.relayOnly !== true
42084
43131
  });
42085
43132
  }
42086
43133
  /**
43134
+ * How often links read Pkarr. The Desktop that keeps to the relays (Hide my IP from contacts) reads every packet from
43135
+ * them, background reads too, so it goes at the relays' pace, not the DHT's: at the DHT's, one waiting invite was 45
43136
+ * relay reads a minute, against a browser's 30. Links take it as they start; turning the switch restarts them.
43137
+ */
43138
+ get pollIntervals() {
43139
+ return this.transport.configure && this.settings.relayOnly === true ? RELAY_POLL_INTERVALS : this.ownPollIntervals;
43140
+ }
43141
+ /**
42087
43142
  * What each network's wallets still wait for (see `walletAwaiting`): open requests and invoices, paid invoices not
42088
43143
  * claimed yet, ecash sent and not taken. Read from the Cashu quotes, the Lightning journals and the payments.
42089
43144
  */
42090
43145
  /** What each network's wallets still wait for, and each mint on its own (`mints`, only the mints that wait for something). */
42091
43146
  async readAwaiting() {
42092
43147
  const quotes = await this.wallet.quotes(), payments = this.desk.records(), now = Date.now();
43148
+ const lost = this.transfersRestored ? await this.sentWithoutLine(payments) : void 0;
43149
+ const chatGone = lost && ((paymentId) => lost.has(paymentId));
42093
43150
  const out = {};
42094
43151
  const mints = /* @__PURE__ */ new Map();
42095
43152
  for (const network of WALLET_NETWORKS) {
@@ -42103,7 +43160,8 @@ var GhostlyNode = class GhostlyNode {
42103
43160
  lightningCard: lightning.receivingId,
42104
43161
  lightningOwner: (op) => lightning.owner(op),
42105
43162
  payments,
42106
- now
43163
+ now,
43164
+ chatGone
42107
43165
  });
42108
43166
  for (const url of this.networkMints(network)) {
42109
43167
  const waits = mintAwaiting(url, {
@@ -42120,6 +43178,47 @@ var GhostlyNode = class GhostlyNode {
42120
43178
  mints
42121
43179
  };
42122
43180
  }
43181
+ /**
43182
+ * The ecash sent and not taken yet whose chat line, the bubble with its Take it back, is in no chat the person can
43183
+ * open (`WalletAwaitingView.chatGone`): its 1:1 chat deleted, or joined again by the same invite (the same id) without
43184
+ * its old history, or its group gone. Asked of the line itself, not of the link it went over: a member's edge closes
43185
+ * when they leave the group, and the line stays in the group's history.
43186
+ *
43187
+ * The line's id is the payment's own (`me_<createdAt>`, as `paymentMessage` reads it first); a member's is filed in
43188
+ * the group under the edge's id (`storeNewMessage`). An edge closed since says no more which group it was: every
43189
+ * group here is asked, one row each. A community's payment link with no member is no chat: never said gone.
43190
+ */
43191
+ async sentWithoutLine(payments) {
43192
+ const lost = /* @__PURE__ */ new Set();
43193
+ const sent = payments.filter((p) => p.kind === "payment" && p.direction === "out" && p.state === "pending" && p.token);
43194
+ if (!sent.length) return lost;
43195
+ let groups;
43196
+ const everyGroup = () => groups ??= this.groups.views().map((g) => g.id);
43197
+ const groupHere = (groupId) => !!this.groups.view(groupId);
43198
+ const asked = /* @__PURE__ */ new Map();
43199
+ const ask = (chat, id, paymentId) => {
43200
+ const ids = asked.get(chat) ?? /* @__PURE__ */ new Map();
43201
+ asked.set(chat, ids.set(id, [...ids.get(id) ?? [], paymentId]));
43202
+ };
43203
+ for (const p of sent) {
43204
+ const line = `me_${p.createdAt}`, stored = this.links.get(p.linkId)?.stored, pay = parsePayLink(p.linkId);
43205
+ if (pay && !pay.member) continue;
43206
+ lost.add(p.id);
43207
+ if (stored && !stored.group) ask(p.linkId, line, p.id);
43208
+ else if (stored?.group && stored.groupPeer && !stored.groupEntry) {
43209
+ if (groupHere(stored.group)) ask(`group:${stored.group}`, `${p.linkId}:${line}`, p.id);
43210
+ } else if (pay) {
43211
+ if (groupHere(pay.groupId)) ask(`group:${pay.groupId}`, `${p.linkId}:${line}`, p.id);
43212
+ } else if (!stored) for (const groupId of everyGroup()) ask(`group:${groupId}`, `${p.linkId}:${line}`, p.id);
43213
+ }
43214
+ for (const [chat, ids] of asked) {
43215
+ const keys = [...ids.keys()];
43216
+ (await db.getMessagesById(chat, keys)).forEach((row, i) => {
43217
+ for (const paymentId of ids.get(keys[i])) if (row?.sender === "me" && row.paymentId === paymentId) lost.delete(paymentId);
43218
+ });
43219
+ }
43220
+ return lost;
43221
+ }
42123
43222
  /** A mint as the wallet page shows it, with what it still waits for when it does (asked about before it is removed). */
42124
43223
  withWaits(mints, waits) {
42125
43224
  return mints.map(({ awaiting: _, ...mint }) => waits.has(mint.url) ? {
@@ -42301,12 +43400,11 @@ var GhostlyNode = class GhostlyNode {
42301
43400
  continue;
42302
43401
  }
42303
43402
  const network = walletNetworkOf(review.network);
43403
+ const prepared = saved.prepared;
43404
+ if (review.method === "cashu" && !prepared.abandoned && !prepared.spentElsewhere && !this.wallet.mintDue(prepared.mint, Date.now())) continue;
42304
43405
  if (review.method === "arkade" && !this.arkWallets[network].adapter || review.method === "bark" && !this.barkWallets[network].adapter || review.method === "spark" && !this.sparkWallets[network].adapter || review.method === "usdt" && !this.usdtWallets[network].adapter || review.method === "bitcoin" && !this.bitcoins[network].sources.active || review.method === "fedimint" && !this.fedimintWallets[network].federation(review.provider)) continue;
42305
43406
  const after = await this.reconcilePayment({ id: review.id }).catch(() => review);
42306
- if (review.method === "cashu" && ["submitted", "unknown"].includes(after.state)) {
42307
- const prepared = saved.prepared;
42308
- this.cashuPayAsk.missed(id, Date.now(), Date.now() < (prepared.token ? (review.submittedAt ?? review.createdAt) + 6e4 : swapSettledAt(review, prepared)));
42309
- }
43407
+ if (review.method === "cashu" && ["submitted", "unknown"].includes(after.state)) this.cashuPayAsk.missed(id, Date.now(), Date.now() < (prepared.token ? (review.submittedAt ?? review.createdAt) + 6e4 : swapSettledAt(review, prepared)));
42310
43408
  }
42311
43409
  } finally {
42312
43410
  if (!this.shuttingDown) this.paymentTimer = setTimeout(() => void this.pollPaymentStatus(), 1e4);
@@ -42331,6 +43429,7 @@ var GhostlyNode = class GhostlyNode {
42331
43429
  ...DEFAULT_SETTINGS,
42332
43430
  ...stored
42333
43431
  };
43432
+ this.armOwnStatusEnd();
42334
43433
  this.settings.relays = currentRelays(this.settings.relays);
42335
43434
  this.relays?.setRelays(this.settings.relays);
42336
43435
  this.configureDirect();
@@ -42386,6 +43485,7 @@ var GhostlyNode = class GhostlyNode {
42386
43485
  if (stored.profile) await this.outboxFor(stored.id).recover(messages);
42387
43486
  }
42388
43487
  this.transfersRestored = true;
43488
+ this.awaitingSoon();
42389
43489
  this.publicProfiles.start();
42390
43490
  await this.startLinks(links.map((stored) => stored.id), (linkId) => {
42391
43491
  if (!this.links.get(linkId)?.stored.group) this.refreshPublicProfiles({ linkId }).catch(() => {});
@@ -42396,6 +43496,7 @@ var GhostlyNode = class GhostlyNode {
42396
43496
  this.hold.start();
42397
43497
  this.startGroupEntries();
42398
43498
  this.prepareSpare(STARTUP_QUIET_MS);
43499
+ this.announceOnline();
42399
43500
  }
42400
43501
  if (!this.limitedMode) this.openStartedWallets(fresh);
42401
43502
  if (this.appsOn && !this.appsWireOnly) this.appStore.start().catch(() => {});
@@ -42644,6 +43745,7 @@ var GhostlyNode = class GhostlyNode {
42644
43745
  this.hold.start();
42645
43746
  this.startGroupEntries();
42646
43747
  this.prepareSpare(STARTUP_QUIET_MS);
43748
+ this.announceOnline();
42647
43749
  this.did.publishNow().catch(() => {});
42648
43750
  this.identities.networkBack();
42649
43751
  }
@@ -42820,6 +43922,7 @@ var GhostlyNode = class GhostlyNode {
42820
43922
  clearTimeout(this.limitedTimer);
42821
43923
  this.limitedTimer = null;
42822
43924
  }
43925
+ clearTimeout(this.onlineTimer);
42823
43926
  this.appShelf?.stop();
42824
43927
  if (!quiet) this.depart({ quitting: options.quitting === true });
42825
43928
  const linksStopped = Promise.allSettled([...this.links.values()].map(async (live) => {
@@ -42842,6 +43945,12 @@ var GhostlyNode = class GhostlyNode {
42842
43945
  this.reactionTimers.clear();
42843
43946
  for (const timer of this.pinTimers.values()) clearTimeout(timer);
42844
43947
  this.pinTimers.clear();
43948
+ for (const timer of [
43949
+ this.idleTimer,
43950
+ this.ownStatusTimer,
43951
+ ...this.peerStatusTimers.values()
43952
+ ]) clearTimeout(timer);
43953
+ this.peerStatusTimers.clear();
42845
43954
  this.stopGroupEntries();
42846
43955
  this.stopWatchingAdapters?.();
42847
43956
  this.enrollment?.cancel().catch(() => {});
@@ -43002,6 +44111,7 @@ var GhostlyNode = class GhostlyNode {
43002
44111
  ...this.limitedMode && this.restoreCheck && { restoreCheck: this.restoreCheck },
43003
44112
  ...this.limitedMode && this.startChecking && { startCheck: true },
43004
44113
  ...wakeOwnerOf(this.settings.wake, this.ownDeviceKey) && { wakeOwner: wakeOwnerOf(this.settings.wake, this.ownDeviceKey) },
44114
+ ...this.pushRelayRefusal && this.pushRelayRefusal.url === this.settings.pushRelay && { pushRelayRefused: this.pushRelayRefusal },
43005
44115
  transport: {
43006
44116
  ...this.transport.describe(),
43007
44117
  ...this.options.irohWeb || this.ownIrohRelays ? { iroh: {
@@ -43108,6 +44218,10 @@ var GhostlyNode = class GhostlyNode {
43108
44218
  async getMessages(linkId) {
43109
44219
  return (await db.getMessages(linkId)).map(withoutFrame);
43110
44220
  }
44221
+ /** A chat's or a group's (`group:<id>`) messages that carry a file, by time: read without the rest of its history. */
44222
+ async fileMessages(linkId) {
44223
+ return (await db.getFileMessages(linkId)).map(withoutFrame);
44224
+ }
43111
44225
  /**
43112
44226
  * The 1:1 chats among `linkIds` with a message whose text holds `query`, whatever the case and the accents: the chat
43113
44227
  * list's search, read here so a page that holds each chat's newest page only is not sent every whole history for it.
@@ -43757,11 +44871,72 @@ var GhostlyNode = class GhostlyNode {
43757
44871
  await db.patchLink(linkId, { wakeToken: token });
43758
44872
  this.emitState();
43759
44873
  }
44874
+ const online = this.settings.wakeOnline !== false && wakeOwnerOf(own, this.ownDeviceKey) !== "away";
43760
44875
  live.link.sendWake({
43761
44876
  ...own,
43762
- token
44877
+ token,
44878
+ ...online && { online: true }
43763
44879
  });
43764
44880
  }
44881
+ /**
44882
+ * Whether paired contacts are asked for an online notice (Settings → Notifications, on by default). Each live one is
44883
+ * told again now; one away hears it on its next session, and until then may still send one, which shows.
44884
+ */
44885
+ async setWakeOnline({ on }) {
44886
+ if (this.settings.wakeOnline !== false === on) return;
44887
+ this.settings = {
44888
+ ...this.settings,
44889
+ wakeOnline: false
44890
+ };
44891
+ if (on) delete this.settings.wakeOnline;
44892
+ await db.putSettings(this.settings);
44893
+ for (const live of this.links.values()) if (live.stored.profile && !live.stored.group) await this.shareWake(live.stored.id);
44894
+ this.emitState();
44895
+ }
44896
+ onlineTimer;
44897
+ /**
44898
+ * This app came online (it started, or its network came back): once the chats had `WAKE_ONLINE_DELAY_MS` to go live,
44899
+ * the contacts still away that asked are told (`sayOnline`). A contact whose app is open goes live and is not pushed.
44900
+ */
44901
+ announceOnline() {
44902
+ clearTimeout(this.onlineTimer);
44903
+ this.onlineTimer = setTimeout(() => {
44904
+ this.onlineTimer = void 0;
44905
+ this.sayOnline();
44906
+ }, WAKE_ONLINE_DELAY_MS);
44907
+ }
44908
+ /**
44909
+ * An online wake-up (WISP 401 § Wake-up push, revision 2026-10-27) to each paired contact that asked for one, whose
44910
+ * chat is not live: at most one per contact per `WAKE_ONLINE_INTERVAL_MS`, counted across restarts, since a restart is
44911
+ * what says it. Apart from the message wake-ups' limit, so it never holds one back. A muted chat's contact shared no
44912
+ * target; a group's edge is never told. `WAKE_ONLINE_BATCH` at a time, the rest a `WAKE_ONLINE_BATCH_MS` later (those
44913
+ * still away then), so a push relay's minute keeps room for the message and call wake-ups. None while this profile does
44914
+ * not share when it is online (`sharePresence`).
44915
+ */
44916
+ sayOnline(now = Date.now()) {
44917
+ if (!this.networkOn || this.shuttingDown || this.settings.sharePresence === false) return;
44918
+ let sent = 0;
44919
+ for (const live of this.links.values()) {
44920
+ const { id, peerWake: target, profile, group, onlineWokeAt } = live.stored;
44921
+ if (!target?.online || !profile || group || live.link?.isDataLinkOpen) continue;
44922
+ if (onlineWokeAt !== void 0 && onlineWokeAt <= now && now - onlineWokeAt < 18e5) continue;
44923
+ if (sent === 10) {
44924
+ clearTimeout(this.onlineTimer);
44925
+ this.onlineTimer = setTimeout(() => {
44926
+ this.onlineTimer = void 0;
44927
+ this.sayOnline();
44928
+ }, WAKE_ONLINE_BATCH_MS);
44929
+ return;
44930
+ }
44931
+ sent += 1;
44932
+ live.stored = {
44933
+ ...live.stored,
44934
+ onlineWokeAt: now
44935
+ };
44936
+ db.patchLink(id, { onlineWokeAt: now });
44937
+ this.postWake(id, target, "online");
44938
+ }
44939
+ }
43765
44940
  /** An edge of a private group: where a member shares how to wake it. A community has none between two members. */
43766
44941
  meshEdge(stored) {
43767
44942
  return !!stored.group && !!stored.groupPeer && !stored.groupEntry && !this.groups.isCommunityGroup(stored.group);
@@ -43796,6 +44971,7 @@ var GhostlyNode = class GhostlyNode {
43796
44971
  this.reactionNotesBefore.delete(linkId);
43797
44972
  this.reactionNotesWhole.delete(linkId);
43798
44973
  this.events.onMessages(linkId, []);
44974
+ this.awaitingSoon();
43799
44975
  }
43800
44976
  async setGroupWakeMuted(groupId, muted) {
43801
44977
  const list = this.settings.wakeMutedGroups ?? [];
@@ -43895,11 +45071,15 @@ var GhostlyNode = class GhostlyNode {
43895
45071
  wakePeer(live, kind = "message") {
43896
45072
  const target = live.stored.peerWake, linkId = live.stored.id;
43897
45073
  if (!target || !live.stored.profile || live.stored.group || !this.networkOn) return;
43898
- if (!(kind === "call" ? this.callWakeLimiter : this.wakeLimiter).take(linkId)) return;
43899
- this.postWake(linkId, target, kind);
45074
+ const limiter = kind === "call" ? this.callWakeLimiter : this.wakeLimiter, takenAt = Date.now();
45075
+ if (!limiter.take(linkId, takenAt)) return;
45076
+ this.postWake(linkId, target, kind, () => limiter.missed(linkId, takenAt));
43900
45077
  }
43901
- /** Posts one wake-up to the target a link holds; a subscription gone (404, 410) is forgotten. */
43902
- postWake(linkId, target, kind) {
45078
+ /**
45079
+ * Posts one wake-up to the target a link holds; a subscription gone (404, 410) is forgotten. `missed`: it did not
45080
+ * reach the push service (no network, the relay did not forward it, or the service answered 429 or 5xx).
45081
+ */
45082
+ postWake(linkId, target, kind, missed) {
43903
45083
  let request;
43904
45084
  try {
43905
45085
  request = wakeRequest(target, Date.now(), kind);
@@ -43907,6 +45087,7 @@ var GhostlyNode = class GhostlyNode {
43907
45087
  return;
43908
45088
  }
43909
45089
  this.postPush(request).then((status) => {
45090
+ if (status === 429 || status >= 500) missed?.();
43910
45091
  if ((status === 404 || status === 410) && this.links.get(linkId)?.stored.peerWake?.endpoint === target.endpoint) {
43911
45092
  const current = this.links.get(linkId);
43912
45093
  current.stored = {
@@ -43916,7 +45097,9 @@ var GhostlyNode = class GhostlyNode {
43916
45097
  db.patchLink(linkId, { peerWake: void 0 });
43917
45098
  this.emitState();
43918
45099
  }
43919
- }).catch(() => {});
45100
+ }).catch(() => {
45101
+ missed?.();
45102
+ });
43920
45103
  }
43921
45104
  /**
43922
45105
  * A call to a contact whose app is closed (WISP 401 § Wake-up push, calls): one "call" wake-up, so its app shows
@@ -43930,12 +45113,36 @@ var GhostlyNode = class GhostlyNode {
43930
45113
  live.link?.session.pollNow();
43931
45114
  return true;
43932
45115
  }
43933
- /** Posts a wake-up: the host's way, or `fetch`, then the push relay when a page may not post it itself. */
43934
- postPush(request) {
43935
- return postPush(request, {
43936
- pushSend: this.options.pushSend,
43937
- relay: this.settings.pushRelay
43938
- });
45116
+ /**
45117
+ * Posts a wake-up: the host's way, or `fetch`, then the push relay when a page may not post it itself. A relay that
45118
+ * answers but not as a push relay is kept for the pages (`EngineState.pushRelayRefused`) until it forwards one; a
45119
+ * relay that cannot be reached at all (offline, timed out) is not, as a page cannot tell that from being offline.
45120
+ */
45121
+ async postPush(request) {
45122
+ const relay = this.settings.pushRelay;
45123
+ try {
45124
+ return await postPush(request, {
45125
+ pushSend: this.options.pushSend,
45126
+ relay,
45127
+ relayed: () => {
45128
+ if (this.pushRelayRefusal?.url === relay) {
45129
+ this.pushRelayRefusal = void 0;
45130
+ this.emitState();
45131
+ }
45132
+ }
45133
+ });
45134
+ } catch (error) {
45135
+ if (error instanceof PushRelayRefusal && relay) {
45136
+ this.pushRelayRefusal = {
45137
+ url: relay,
45138
+ at: Date.now(),
45139
+ http: error.http,
45140
+ ...error.text !== void 0 && { text: error.text }
45141
+ };
45142
+ this.emitState();
45143
+ }
45144
+ throw error;
45145
+ }
43939
45146
  }
43940
45147
  removeLink({ linkId }) {
43941
45148
  const live = this.links.get(linkId);
@@ -43951,6 +45158,13 @@ var GhostlyNode = class GhostlyNode {
43951
45158
  live.carried?.stop();
43952
45159
  const filesEnded = this.fileDesk.drop(linkId);
43953
45160
  this.links.delete(linkId);
45161
+ this.removedChats.set(linkId, (this.removedChats.get(linkId) ?? 0) + 1);
45162
+ this.newestAt.delete(linkId);
45163
+ this.clockLeads.delete(linkId);
45164
+ this.placedAt.delete(linkId);
45165
+ this.reactionNotes.delete(linkId);
45166
+ this.reactionNotesBefore.delete(linkId);
45167
+ this.reactionNotesWhole.delete(linkId);
43954
45168
  if (filesEnded) setTimeout(() => void live.link?.stop(true), FILES_END_MS);
43955
45169
  else live.link?.stop(true);
43956
45170
  live.caps?.stop();
@@ -43963,6 +45177,7 @@ var GhostlyNode = class GhostlyNode {
43963
45177
  if (live.stored.wakeToken) this.rotateWake().then(() => this.emitState());
43964
45178
  db.deleteLink(linkId);
43965
45179
  this.desk.forgetLink(linkId);
45180
+ this.awaitingSoon();
43966
45181
  this.emitState();
43967
45182
  }
43968
45183
  renameLink({ linkId, label }) {
@@ -44289,12 +45504,15 @@ var GhostlyNode = class GhostlyNode {
44289
45504
  const reply = message.replyTo;
44290
45505
  if (!reply || reply.messageId) return message;
44291
45506
  const group = message.linkId.startsWith("group:");
45507
+ const gone = () => !group && !this.links.has(message.linkId) && this.removedChats.has(message.linkId);
45508
+ if (gone()) return message;
44292
45509
  let original, history;
44293
45510
  for (const rowId of group ? [reply.id] : [
44294
45511
  `peer_${reply.id}`,
44295
45512
  `me_${reply.id}`,
44296
45513
  ...await this.rowsNamed(message.linkId, reply.id)
44297
45514
  ]) {
45515
+ if (gone()) return message;
44298
45516
  const row = rowId === message.id ? void 0 : await db.getMessage(message.linkId, rowId);
44299
45517
  if (row && replyRef(row, group) === reply.id) {
44300
45518
  original = row;
@@ -44326,7 +45544,7 @@ var GhostlyNode = class GhostlyNode {
44326
45544
  const id = (await this.unkeyedRowsOf(this.links.get(message.linkId))).get(reply.id);
44327
45545
  const row = id === void 0 || id === message.id ? void 0 : await db.getMessage(message.linkId, id);
44328
45546
  if (row && replyRef(row) === reply.id) original = row;
44329
- } else if (!original && !group) {
45547
+ } else if (!original && !group && !gone()) {
44330
45548
  history = await db.getMessages(message.linkId);
44331
45549
  original = history.find((m) => m.id !== message.id && replyRef(m) === reply.id);
44332
45550
  }
@@ -45113,15 +46331,17 @@ var GhostlyNode = class GhostlyNode {
45113
46331
  this.emitState();
45114
46332
  }
45115
46333
  }
46334
+ /** `everyone`: whether it is deleted for everyone, a waiting text the outbox already handed to the link; else only here. */
45116
46335
  deleteMessage({ linkId, messageId }) {
45117
46336
  if (this.outboxes.get(linkId)?.cancel(messageId)) {
45118
46337
  this.removeMessage({
45119
46338
  linkId,
45120
46339
  messageId
45121
46340
  }).then(({ refused }) => refused ? this.forgetMessage(linkId, messageId) : void 0).catch(() => {});
45122
- return;
46341
+ return { everyone: true };
45123
46342
  }
45124
46343
  this.forgetMessage(linkId, messageId);
46344
+ return { everyone: false };
45125
46345
  }
45126
46346
  /**
45127
46347
  * Deletes a message of mine for everyone (WISP 400 § Delete for everyone): it goes from this device at once, as a delete
@@ -45274,6 +46494,7 @@ var GhostlyNode = class GhostlyNode {
45274
46494
  this.transfers.delete(message.file.id);
45275
46495
  }
45276
46496
  await db.deleteMessage(linkId, messageId);
46497
+ if (message?.sender === "me" && message.paymentId) this.awaitingSoon();
45277
46498
  live.lastMessageAt = (await db.getMessagePage(linkId, { limit: 1 })).messages[0]?.timestamp ?? 0;
45278
46499
  if (removed) this.quoteSweeps.add(linkId, messageId, replyRef(message ?? {
45279
46500
  id: messageId,
@@ -45984,19 +47205,20 @@ var GhostlyNode = class GhostlyNode {
45984
47205
  * `chosen`: a choice from the chat's Connection menu, a row in its timeline even when it names the transport already
45985
47206
  * set. Left out (the RPC), only a change of transport is: the Fallback switch sends the same preference again, and
45986
47207
  * is neither a row nor a switch intent. On Automatic it sends back the transport Automatic names: only the fallback
45987
- * changes, and the chat stays on Automatic.
47208
+ * changes (and with it what Automatic names), and the chat stays on Automatic.
45988
47209
  */
45989
47210
  async setTransportPreference({ linkId, preferred, fallback }, chosen) {
45990
47211
  const live = this.links.get(linkId);
45991
47212
  if (!live?.stored.profile || !live.link?.availableTransports.includes(preferred) || typeof fallback !== "boolean") throw new Error("Transport unavailable");
45992
- if (chosen === void 0 && live.stored.preferredTransport === void 0 && preferred === automaticTransport(live.link.availableTransports)) {
47213
+ const available = live.link.availableTransports;
47214
+ if (chosen === void 0 && live.stored.preferredTransport === void 0 && [true, false].some((f) => preferred === automaticTransport(available, f))) {
45993
47215
  await db.patchLink(linkId, { transportFallback: fallback });
45994
47216
  live.stored = {
45995
47217
  ...live.stored,
45996
47218
  transportFallback: fallback
45997
47219
  };
45998
47220
  this.emitState();
45999
- await live.link.setTransportPreference(preferred, fallback, true, false);
47221
+ await live.link.setTransportPreference(automaticTransport(available, fallback), fallback, true, false);
46000
47222
  this.capsChanged(linkId);
46001
47223
  return;
46002
47224
  }
@@ -46408,7 +47630,7 @@ var GhostlyNode = class GhostlyNode {
46408
47630
  if (targets.length > 5) throw new Error(`Forward to at most 5 chats at once`);
46409
47631
  if (linkId.startsWith("group:") ? !this.groups.view(linkId.slice(6)) : this.links.get(linkId)?.stored.group !== void 0 || !this.links.has(linkId)) throw new Error("Chat not found");
46410
47632
  const chosen = await Promise.all(ids.map((id) => db.getMessage(linkId, id)));
46411
- if (chosen.some((m) => !m)) throw new Error("That message is not in this chat");
47633
+ if (chosen.some((m) => !m)) throw new Error(FORWARD_MESSAGE_GONE);
46412
47634
  const messages = chosen.sort((a, b) => a.timestamp - b.timestamp);
46413
47635
  for (const message of messages) {
46414
47636
  const kind = forwardKind(message);
@@ -46436,6 +47658,7 @@ var GhostlyNode = class GhostlyNode {
46436
47658
  }
46437
47659
  for (const message of messages) {
46438
47660
  const hops = forwardedAgain(message.forwarded);
47661
+ const gone = () => this.forwardSourceGone(linkId, message.id);
46439
47662
  try {
46440
47663
  if (forwardKind(message) === "text") {
46441
47664
  const sent = groupId ? await this.groups.send(groupId, message.text, [], void 0, hops) : !live.link && !(this.limitedMode && live.stored.profile) ? { error: this.limitedMode ? LIMITED_MODE_ERROR : "You are offline" } : live.stored.profile ? await this.sendChatText(live, message.text.trim(), now(), message.preview, void 0, hops) : await this.sendMessage({
@@ -46471,7 +47694,7 @@ var GhostlyNode = class GhostlyNode {
46471
47694
  wireId: picked.id.slice(`group-${groupId}-out-`.length),
46472
47695
  timestamp: now(),
46473
47696
  file: picked
46474
- });
47697
+ }, gone);
46475
47698
  const sent = await this.sendGroupFile({
46476
47699
  groupId,
46477
47700
  file,
@@ -46505,7 +47728,7 @@ var GhostlyNode = class GhostlyNode {
46505
47728
  wireId,
46506
47729
  timestamp,
46507
47730
  file: picked
46508
- });
47731
+ }, gone);
46509
47732
  try {
46510
47733
  await this.sendFile({
46511
47734
  linkId: to,
@@ -46527,9 +47750,19 @@ var GhostlyNode = class GhostlyNode {
46527
47750
  }
46528
47751
  return { results };
46529
47752
  }
46530
- /** How many edges took my message (or its edit number `edit`) so far: what `group send --wait sent` waits for. */
46531
- groupTaken({ groupId, messageId, edit }) {
46532
- return this.groups.taken(groupId, messageId, edit);
47753
+ /**
47754
+ * A message being forwarded was deleted meanwhile: here, or for everyone by its author. Its deletion is written down
47755
+ * (a chat's `deletedIds`, a group's removals) before its file goes, and its row after: either says so.
47756
+ */
47757
+ async forwardSourceGone(linkId, messageId) {
47758
+ return (linkId.startsWith("group:") ? this.groups.isRemoved(linkId.slice(6), messageId) : !!this.links.get(linkId)?.stored.deletedIds?.includes(messageId)) || !await db.getMessage(linkId, messageId);
47759
+ }
47760
+ /**
47761
+ * How many edges took my message (or its edit number `edit`, or my reaction numbered `reaction`, as `react` gave it,
47762
+ * or my pin numbered `pin`, as `pinMessage` gave it) so far: what `group send`, `group react` and `pin --wait sent` wait for.
47763
+ */
47764
+ groupTaken({ groupId, messageId, edit, reaction, pin }) {
47765
+ return this.groups.taken(groupId, messageId, edit, reaction, pin);
46533
47766
  }
46534
47767
  /** The numbers of my reactions and of my pin in a 1:1 chat that the contact has not confirmed: what `react` and `pin` wait for. */
46535
47768
  chatUnconfirmed({ linkId }) {
@@ -46541,7 +47774,8 @@ var GhostlyNode = class GhostlyNode {
46541
47774
  }
46542
47775
  /**
46543
47776
  * Reacts to a message of a chat or a group (WISP 400 § Reactions): shown here at once; a 1:1 chat keeps it until the
46544
- * contact confirms it (the live session, or DHT envelopes meanwhile), a group sends it to its members.
47777
+ * contact confirms it (the live session, or DHT envelopes meanwhile), a group sends it to its members. In a group, `n`
47778
+ * is its number, for `groupTaken`.
46545
47779
  */
46546
47780
  async react({ linkId, messageId, emoji }) {
46547
47781
  if (typeof linkId !== "string" || !linkId) return { error: "No chat to react in" };
@@ -46552,7 +47786,12 @@ var GhostlyNode = class GhostlyNode {
46552
47786
  refused: true
46553
47787
  };
46554
47788
  const result = await this.reactions.mine(linkId, messageId, emoji);
46555
- return "error" in result ? result : this.sendGroupReaction(groupId, result.reaction);
47789
+ if ("error" in result) return result;
47790
+ const sent = await this.sendGroupReaction(groupId, result.reaction);
47791
+ return sent.error ? sent : {
47792
+ error: null,
47793
+ n: result.reaction.n
47794
+ };
46556
47795
  }
46557
47796
  const live = this.links.get(linkId);
46558
47797
  if (!live || live.stored.group) return { error: "No such chat" };
@@ -46620,13 +47859,16 @@ var GhostlyNode = class GhostlyNode {
46620
47859
  this.reactionTimers.delete(linkId);
46621
47860
  } else if (upTo) this.flushReactions(linkId);
46622
47861
  }
46623
- /** A group reaction goes to every member: over each edge in a private group, through the group in a community. */
47862
+ /**
47863
+ * A group reaction goes to every member: over each edge in a private group, through the group in a community. Each
47864
+ * edge that takes it counts for `groupTaken` (`reactionKey`), as a message does.
47865
+ */
46624
47866
  async sendGroupReaction(groupId, reaction) {
46625
47867
  if (this.groups.isCommunityGroup(groupId)) try {
46626
47868
  await this.groups.sendCommunityApp(groupId, {
46627
47869
  t: COMMUNITY_REACTION_FRAME,
46628
47870
  ...wireReaction(reaction)
46629
- });
47871
+ }, reactionKey(reaction.n));
46630
47872
  return { error: null };
46631
47873
  } catch (error) {
46632
47874
  return { error: error instanceof Error ? error.message : String(error) };
@@ -46637,11 +47879,20 @@ var GhostlyNode = class GhostlyNode {
46637
47879
  ...wireReaction(reaction),
46638
47880
  ...this.groups.signReaction(groupId, wireReaction(reaction))
46639
47881
  };
46640
- for (const edge of this.memberEdges(groupId).values()) try {
46641
- this.links.get(edge)?.link?.sendGroupFrame(frame);
46642
- } catch {}
47882
+ for (const edge of this.memberEdges(groupId).values()) this.sayGroupReaction(groupId, this.links.get(edge)?.link, frame);
46643
47883
  return { error: null };
46644
47884
  }
47885
+ /** My reaction frame on one edge of a private group: whether the edge took it (counted for `groupTaken`). */
47886
+ sayGroupReaction(groupId, link, frame) {
47887
+ if (!link) return false;
47888
+ try {
47889
+ link.sendGroupFrame(frame);
47890
+ } catch {
47891
+ return false;
47892
+ }
47893
+ this.groups.noteTaken(groupId, reactionKey(frame.n));
47894
+ return true;
47895
+ }
46645
47896
  /** A group's history read in flight for edges that opened, by chat: its callers of the moment share it. */
46646
47897
  edgeOpenReads = /* @__PURE__ */ new Map();
46647
47898
  /**
@@ -46666,16 +47917,12 @@ var GhostlyNode = class GhostlyNode {
46666
47917
  const mine = groupReactionsToResend(await this.edgeOpenHistory(`group:${groupId}`), REACTION_LIMITS.pending);
46667
47918
  const link = this.links.get(linkId)?.link;
46668
47919
  const say = (batch) => {
46669
- for (const reaction of batch) try {
46670
- link?.sendGroupFrame({
46671
- t: GROUP_REACTION_FRAME,
46672
- g: groupId,
46673
- ...reaction,
46674
- ...this.groups.signReaction(groupId, reaction)
46675
- });
46676
- } catch {
46677
- return;
46678
- }
47920
+ for (const reaction of batch) if (!this.sayGroupReaction(groupId, link, {
47921
+ t: "group-react",
47922
+ g: groupId,
47923
+ ...reaction,
47924
+ ...this.groups.signReaction(groupId, reaction)
47925
+ })) return;
46679
47926
  };
46680
47927
  say(mine.slice(0, REACTION_LIMITS.send));
46681
47928
  for (let start = REACTION_LIMITS.send, turn = 1; start < mine.length; start += REACTION_LIMITS.send, turn++) {
@@ -46698,7 +47945,8 @@ var GhostlyNode = class GhostlyNode {
46698
47945
  /**
46699
47946
  * Pins a message of a chat or a group, or unpins (WISP 400 § Pinned message): one per chat, the last pin winning. A
46700
47947
  * 1:1 chat keeps it until the contact confirms it on a live session; a group sends it to its members, where the rule
46701
- * (`mayPin`) allows it.
47948
+ * (`mayPin`) allows it. In a group, `n` is the pin's number, for `groupTaken`. The message pinned already is not
47949
+ * pinned again: nothing goes, and the pin stays its pinner's (`n` only when that is me).
46702
47950
  */
46703
47951
  async pinMessage({ linkId, messageId, remove }) {
46704
47952
  if (typeof linkId !== "string" || !linkId) return { error: "No chat to pin in" };
@@ -46710,20 +47958,27 @@ var GhostlyNode = class GhostlyNode {
46710
47958
  refused: true
46711
47959
  };
46712
47960
  if (!mayPinIn(view)) return { error: "Only the admin pins in a community" };
46713
- const pin = await myPin(host, linkId, messageId, !!remove, this.groups.pinOf(groupId));
47961
+ const current = this.groups.pinOf(groupId), pin = await myPin(host, linkId, messageId, !!remove, current);
46714
47962
  if ("error" in pin) return pin;
47963
+ if ("already" in pin) return {
47964
+ error: null,
47965
+ ...current?.by === "me" && { n: current.n }
47966
+ };
46715
47967
  if (this.groups.isCommunityGroup(groupId)) {
46716
47968
  try {
46717
47969
  await this.groups.sendCommunityApp(groupId, {
46718
47970
  t: "pin",
46719
47971
  id: pin.id,
46720
47972
  n: pin.n
46721
- });
47973
+ }, pinKey(pin.n));
46722
47974
  } catch (error) {
46723
47975
  return { error: error instanceof Error ? error.message : String(error) };
46724
47976
  }
46725
47977
  await this.groups.setPin(groupId, pin);
46726
- return { error: null };
47978
+ return {
47979
+ error: null,
47980
+ n: pin.n
47981
+ };
46727
47982
  }
46728
47983
  const frame = this.groups.pinFrame(groupId, pin);
46729
47984
  if (!frame) return { error: "You are not in this group" };
@@ -46733,13 +47988,17 @@ var GhostlyNode = class GhostlyNode {
46733
47988
  sig: frame.sig
46734
47989
  });
46735
47990
  for (const member of this.memberEdges(groupId).keys()) this.sendGroupPinFrame(groupId, member);
46736
- return { error: null };
47991
+ return {
47992
+ error: null,
47993
+ n: pin.n
47994
+ };
46737
47995
  }
46738
47996
  const live = this.links.get(linkId);
46739
47997
  if (!live || live.stored.group) return { error: "No such chat" };
46740
47998
  if (!live.stored.profile) return { error: "Pins need a current chat; this compatibility chat sends text only." };
46741
47999
  const pin = await myPin(host, linkId, messageId, !!remove, live.stored.pin);
46742
48000
  if ("error" in pin) return pin;
48001
+ if ("already" in pin) return { error: null };
46743
48002
  await this.keepLinkPin(linkId, pin, {
46744
48003
  id: pin.id,
46745
48004
  n: pin.n
@@ -47019,7 +48278,10 @@ var GhostlyNode = class GhostlyNode {
47019
48278
  }) || !via) return;
47020
48279
  for (const key of this.memberEdges(groupId).keys()) if (key !== via.from && key !== member) this.sendGroupPinFrame(groupId, key);
47021
48280
  }
47022
- /** A private group's pin, as its pinner signed it, over the edge to `member`; nothing when it is down (said when it opens). */
48281
+ /**
48282
+ * A private group's pin, as its pinner signed it, over the edge to `member`; nothing when it is down (said when it
48283
+ * opens). An edge that took my own pin counts for `groupTaken` (`pinKey`).
48284
+ */
47023
48285
  sendGroupPinFrame(groupId, member) {
47024
48286
  const pin = this.groups.pinOf(groupId), edge = this.memberEdges(groupId).get(member);
47025
48287
  if (!pin?.k || !pin.sig || !edge || this.groups.isCommunityGroup(groupId) || !pinNumberHolds(pin.n)) return;
@@ -47031,9 +48293,14 @@ var GhostlyNode = class GhostlyNode {
47031
48293
  k: pin.k,
47032
48294
  sig: pin.sig
47033
48295
  };
48296
+ const link = this.links.get(edge)?.link;
48297
+ if (!link) return;
47034
48298
  try {
47035
- this.links.get(edge)?.link?.sendGroupFrame(frame);
47036
- } catch {}
48299
+ link.sendGroupFrame(frame);
48300
+ } catch {
48301
+ return;
48302
+ }
48303
+ if (pin.by === "me") this.groups.noteTaken(groupId, pinKey(pin.n));
47037
48304
  }
47038
48305
  /** `admin`: the member a leaving admin handed the role to. */
47039
48306
  async leaveGroup({ groupId }) {
@@ -47083,6 +48350,91 @@ var GhostlyNode = class GhostlyNode {
47083
48350
  if (typing === true && this.settings.sendTyping !== false) this.groups.setTyping(groupId, true, typingActivity(kind, status));
47084
48351
  else this.groups.setTyping(groupId, false);
47085
48352
  }
48353
+ /** The longest a timer waits (a later end is waited for in steps). */
48354
+ static TIMER_MAX_MS = 2 ** 31 - 1;
48355
+ /** This profile's presence as the pages last said it (`setPresence`): none before their first word. */
48356
+ ownPresence;
48357
+ idleTimer;
48358
+ /** Ends this profile's status at its `until`. */
48359
+ ownStatusTimer;
48360
+ /** Per chat: when the contact's status ends, so its view is drawn again without it. */
48361
+ peerStatusTimers = /* @__PURE__ */ new Map();
48362
+ /** WISP 401 § Presence and status: `active` at a page's word, `idle` 10 minutes after the last one (or at a page's). */
48363
+ setPresence({ presence }) {
48364
+ if (presence !== "active" && presence !== "idle") return;
48365
+ clearTimeout(this.idleTimer);
48366
+ if (presence === "active") this.idleTimer = setTimeout(() => this.setPresence({ presence: "idle" }), STATUS_IDLE_AFTER_MS);
48367
+ if (presence === this.ownPresence) return;
48368
+ this.ownPresence = presence;
48369
+ this.sayStatus();
48370
+ }
48371
+ /** A status checked as a contact would read it: one already over is none. Said at once, then saved. */
48372
+ async setOwnStatus({ status }) {
48373
+ const clean = liveStatus(personStatus(status));
48374
+ if (!clean) return this.clearOwnStatus();
48375
+ this.settings = {
48376
+ ...this.settings,
48377
+ ownStatus: clean
48378
+ };
48379
+ this.ownStatusChanged();
48380
+ await db.putSettings(this.settings);
48381
+ }
48382
+ async clearOwnStatus() {
48383
+ if (!this.settings.ownStatus) return;
48384
+ const { ownStatus: _cleared, ...settings } = this.settings;
48385
+ this.settings = settings;
48386
+ this.ownStatusChanged();
48387
+ await db.putSettings(this.settings);
48388
+ }
48389
+ getOwnStatus() {
48390
+ const status = liveStatus(this.settings.ownStatus);
48391
+ return {
48392
+ ...this.ownPresence ? { presence: this.ownPresence } : {},
48393
+ ...status ? { status } : {},
48394
+ sharePresence: this.settings.sharePresence !== false
48395
+ };
48396
+ }
48397
+ /** While this profile's status says Do not disturb: messages make no sound and no notice here. */
48398
+ get doNotDisturb() {
48399
+ return liveStatus(this.settings.ownStatus)?.availability === "dnd";
48400
+ }
48401
+ /** What this side says: presence only while shared, the status while it lasts. */
48402
+ statusToSay() {
48403
+ const status = liveStatus(this.settings.ownStatus);
48404
+ return {
48405
+ ...this.ownPresence && this.settings.sharePresence !== false ? { presence: this.ownPresence } : {},
48406
+ ...status ? { status } : {}
48407
+ };
48408
+ }
48409
+ /** Every 1:1 chat's link keeps it and says it where both sides offer `status/1` (a group edge never). */
48410
+ sayStatus() {
48411
+ const state = this.statusToSay();
48412
+ for (const live of this.links.values()) if (live.stored.profile && !live.stored.group) live.link?.setStatus(state);
48413
+ }
48414
+ ownStatusChanged() {
48415
+ this.armOwnStatusEnd();
48416
+ this.sayStatus();
48417
+ this.emitState();
48418
+ }
48419
+ armOwnStatusEnd() {
48420
+ clearTimeout(this.ownStatusTimer);
48421
+ const until = this.settings.ownStatus?.until;
48422
+ if (until === void 0) return;
48423
+ this.ownStatusTimer = setTimeout(() => {
48424
+ if (liveStatus(this.settings.ownStatus)) this.armOwnStatusEnd();
48425
+ else this.clearOwnStatus().catch(() => {});
48426
+ }, Math.min(Math.max(until - Date.now(), 0), GhostlyNode.TIMER_MAX_MS));
48427
+ }
48428
+ redrawAtStatusEnd(linkId, until) {
48429
+ clearTimeout(this.peerStatusTimers.get(linkId));
48430
+ this.peerStatusTimers.delete(linkId);
48431
+ if (until === void 0 || until <= Date.now()) return;
48432
+ this.peerStatusTimers.set(linkId, setTimeout(() => {
48433
+ this.peerStatusTimers.delete(linkId);
48434
+ if (until > Date.now()) this.redrawAtStatusEnd(linkId, until);
48435
+ else this.emitState();
48436
+ }, Math.min(until - Date.now() + 1, GhostlyNode.TIMER_MAX_MS)));
48437
+ }
47086
48438
  /**
47087
48439
  * A call's signaling: read the contact's record fast, for its `_call`. A compatibility chat's only: a paired chat's
47088
48440
  * signals go only over its live session (WISP 601), so a read finds nothing for the call, and its data link keeps
@@ -48101,6 +49453,7 @@ var GhostlyNode = class GhostlyNode {
48101
49453
  const { nostr, ...rest } = patch;
48102
49454
  const settings = rest;
48103
49455
  delete settings.backupReminders;
49456
+ delete settings.ownStatus;
48104
49457
  const wasOnline = this.networkOn;
48105
49458
  if (Array.isArray(settings.iceServers)) settings.iceServers = settings.iceServers.map(iceServerSetting);
48106
49459
  for (const server of settings.iceServers ?? []) {
@@ -48135,6 +49488,7 @@ var GhostlyNode = class GhostlyNode {
48135
49488
  }
48136
49489
  delete settings.wake;
48137
49490
  delete settings.wakeRotate;
49491
+ delete settings.wakeOnline;
48138
49492
  delete settings.wakeMutedGroups;
48139
49493
  delete settings.wakeHeldBy;
48140
49494
  delete settings.wakeRenew;
@@ -48162,7 +49516,7 @@ var GhostlyNode = class GhostlyNode {
48162
49516
  if (this.relays) this.settings.relays = this.relays.describe().relays;
48163
49517
  else if (this.transport.configure) this.settings.relays = [...new Set(settings.relays.map(normalizeRelayUrl).filter((relay) => relay !== null))];
48164
49518
  }
48165
- if (settings.relays || settings.readRelays !== void 0) {
49519
+ if (settings.relays || settings.readRelays !== void 0 || relayOnlyChanged) {
48166
49520
  if (this.settings.readRelays !== true) delete this.settings.readRelays;
48167
49521
  this.configureDirect();
48168
49522
  }
@@ -48184,6 +49538,12 @@ var GhostlyNode = class GhostlyNode {
48184
49538
  this.groups.stopTyping();
48185
49539
  }
48186
49540
  }
49541
+ if (settings.sharePresence !== void 0) {
49542
+ if (settings.sharePresence !== false) delete this.settings.sharePresence;
49543
+ else this.settings.sharePresence = false;
49544
+ await db.putSettings(this.settings);
49545
+ this.sayStatus();
49546
+ }
48187
49547
  for (const key of ["autoDownloads", "serveFiles"]) {
48188
49548
  if (settings[key] === void 0) continue;
48189
49549
  if (settings[key] !== false) delete this.settings[key];
@@ -48238,6 +49598,7 @@ var GhostlyNode = class GhostlyNode {
48238
49598
  this.hold.start();
48239
49599
  this.startGroupEntries();
48240
49600
  this.prepareSpare(STARTUP_QUIET_MS);
49601
+ this.announceOnline();
48241
49602
  this.did.publishNow().catch(() => {});
48242
49603
  this.identities.networkBack();
48243
49604
  if (!this.options.singleDevice && knownDeviceGate()?.state === "active") this.startDeviceSet({ justRead: true }).catch(() => {});
@@ -48715,6 +50076,9 @@ var GhostlyNode = class GhostlyNode {
48715
50076
  */
48716
50077
  async deviceEnrollInvite({ name }) {
48717
50078
  this.enrollAllowed();
50079
+ const handoff = this.handoffGiver?.view();
50080
+ if (handoff && handoff.step !== "failed") throw new Error("enroll-busy: The profile is moving. Try again after it.");
50081
+ if (this.settingMove) throw new Error("enroll-busy: The device set is already changing.");
48718
50082
  await this.enrollment?.cancel().catch(() => {});
48719
50083
  const inviter = new EnrollInviter({
48720
50084
  profile: databaseName(),
@@ -49696,6 +51060,7 @@ var GhostlyNode = class GhostlyNode {
49696
51060
  largeFilesSupport: true,
49697
51061
  binaryFilesSupport: true,
49698
51062
  typingSupport: true,
51063
+ statusSupport: !stored.group,
49699
51064
  reactionsSupport: this.options.reactions !== false,
49700
51065
  editSupport: !GhostlyNode.testNoEdit(),
49701
51066
  pinSupport: true,
@@ -49805,7 +51170,7 @@ var GhostlyNode = class GhostlyNode {
49805
51170
  getPairedServices: () => this.advertisedServices(stored.peerPubKeyZ32).filter((service) => service.type === "http"),
49806
51171
  getHostedHttpService: (id) => this.hostedService(id, stored.peerPubKeyZ32),
49807
51172
  groupsSupport: !!stored.profile,
49808
- events: {
51173
+ events: whileChat({
49809
51174
  onPairingProgress: (progress) => {
49810
51175
  if (knockCue(live.pairingProgress, progress)) this.cueFeedback({
49811
51176
  cue: "knock",
@@ -50036,6 +51401,10 @@ var GhostlyNode = class GhostlyNode {
50036
51401
  },
50037
51402
  onCallSignal: (signal) => this.events.onCallSignal(linkId, signal),
50038
51403
  onPeerTyping: () => this.emitState(),
51404
+ onPeerStatus: (state) => {
51405
+ this.emitState();
51406
+ this.redrawAtStatusEnd(linkId, state.status?.until);
51407
+ },
50039
51408
  onReaction: async (reaction) => await this.reactions.receive(linkId, "peer", reaction) !== "dropped",
50040
51409
  onReactionReceipt: (n) => this.reactionReceipt(linkId, n),
50041
51410
  onReactionsTaken: (n) => this.reactionReceipt(linkId, n, true),
@@ -50079,9 +51448,11 @@ var GhostlyNode = class GhostlyNode {
50079
51448
  },
50080
51449
  onFileAnnounced: stored.profile && !stored.group ? (file, packet) => this.fileAnnounced(linkId, file, packet) : void 0,
50081
51450
  onFileFailed: (id, reason, direction) => this.fileSettled(this.localFileId(linkId, id, direction, { failed: true }), reason, linkId)
50082
- }
51451
+ }, () => this.links.get(linkId) === live)
50083
51452
  });
50084
51453
  const link = live.link;
51454
+ const said = stored.profile && !stored.group ? this.statusToSay() : {};
51455
+ if (said.presence || said.status) link.setStatus(said);
50085
51456
  if (linkId === this.activeLinkId) link.setChatActive(true);
50086
51457
  link.start();
50087
51458
  this.emitState();
@@ -50208,7 +51579,9 @@ var GhostlyNode = class GhostlyNode {
50208
51579
  * The native transports this engine runs for its contacts: the host's, Iroh's browser build where it runs in the
50209
51580
  * page, and HyperDHT through a relay where one is set and the host has no HyperDHT of its own. While "Hide my IP from
50210
51581
  * contacts" is on, not the host's own: its endpoints tell a contact this device's addresses (an Iroh descriptor lists
50211
- * them, HyperDHT connects directly); HyperDHT then goes through the relay, as in a browser.
51582
+ * them, HyperDHT connects directly); HyperDHT then goes through the relay, as in a browser. Iroh's browser build stays,
51583
+ * dialling a contact only on one of the person's own Iroh relays: through the relay the contact names, a contact who
51584
+ * runs it would see this device's address.
50212
51585
  */
50213
51586
  get nativeFactories() {
50214
51587
  return this.nativeFactoriesFor(this.settings.relayOnly === true);
@@ -50220,11 +51593,12 @@ var GhostlyNode = class GhostlyNode {
50220
51593
  nativeFactoriesFor(relayOnly) {
50221
51594
  const relay = relayOnly || this.relaysHyperdhtNatively ? this.hyperdhtRelay : "";
50222
51595
  return {
50223
- ...relay ? { "hyperdht/1": async (seedB64) => (await import("./hyperdhtRelay-CV6qMrom.js")).createRelayedHyperEndpoint(seedB64, relay) } : {},
51596
+ ...relay ? { "hyperdht/1": async (seedB64) => (await import("./hyperdhtRelay-Bj5jJT5w.js")).createRelayedHyperEndpoint(seedB64, relay) } : {},
50224
51597
  ...relayOnly ? {} : this.options.nativeTransports,
50225
51598
  ...this.ownIrohRelays && !relayOnly ? { "iroh/1": (seedB64) => this.options.nativeTransports["iroh/1"](seedB64, this.settings.irohRelays?.length ? { relays: [...this.settings.irohRelays] } : {}) } : {},
50226
51599
  ...this.options.irohWeb ? { "iroh/1": (seedB64) => createIrohWebEndpoint(seedB64, {
50227
51600
  relays: this.irohRelays,
51601
+ ...relayOnly && { ownRelaysOnly: true },
50228
51602
  ...this.options.irohPublicRelay && { publicRelay: this.options.irohPublicRelay }
50229
51603
  }) } : {}
50230
51604
  };
@@ -51099,6 +52473,10 @@ var GhostlyNode = class GhostlyNode {
51099
52473
  };
51100
52474
  message = this.placed(message, place);
51101
52475
  const live = this.links.get(message.linkId);
52476
+ const deletes = this.removedChats.get(message.linkId);
52477
+ if (!live && deletes !== void 0) return false;
52478
+ const chat = message.linkId;
52479
+ const kept = () => this.removedChats.get(chat) === deletes;
51102
52480
  if (live?.stored.deletedIds?.includes(message.id)) return false;
51103
52481
  if (message.linkId.startsWith("group:") && this.groups.isRemoved(message.linkId.slice(6), message.id)) return false;
51104
52482
  const first = live ? this.firstContactRow(live, message) : false;
@@ -51131,7 +52509,8 @@ var GhostlyNode = class GhostlyNode {
51131
52509
  }
51132
52510
  };
51133
52511
  }
51134
- if (!await db.addMessage(message)) return false;
52512
+ if (!await this.addRowWhile(message, kept)) return false;
52513
+ if (message.sender === "me" && message.paymentId) this.awaitingSoon();
51135
52514
  if (live && waitsForLive(message)) live.waitingSends?.then((known) => known.add(message.id), () => {});
51136
52515
  const unkeyed = live && !live.stored.group && unkeyedRef(message);
51137
52516
  if (unkeyed) live.unkeyedRows?.then((rows) => rows.set(unkeyed, message.id), () => {});
@@ -51145,14 +52524,28 @@ var GhostlyNode = class GhostlyNode {
51145
52524
  const early = message.sender === "peer" && message.id.startsWith("peer_") ? this.editBuffer.take(message.linkId, message.id.slice(5)) : void 0;
51146
52525
  if (early) {
51147
52526
  await this.applyPeerEdit(message.linkId, message, early);
52527
+ if (!kept()) return false;
51148
52528
  live?.link?.confirmEdit(early.id, early.e);
51149
52529
  }
51150
52530
  await this.messagesChanged(message.linkId, [message.id]);
52531
+ if (!kept()) return false;
51151
52532
  this.emitState();
51152
52533
  await this.reactions.stored(message);
51153
52534
  await this.groupEdits.stored(message);
51154
52535
  return true;
51155
52536
  }
52537
+ /**
52538
+ * Writes a new message's row while `kept` says its chat is still the one its store began for, checked right before
52539
+ * the write and again once it is done: a chat deleted while the row was being written loses it again, as the
52540
+ * chat's other rows went (`db.deleteLink`). False when it was there already, or its chat went.
52541
+ */
52542
+ async addRowWhile(message, kept) {
52543
+ if (!kept()) return false;
52544
+ if (!await db.addMessage(message)) return false;
52545
+ if (kept()) return true;
52546
+ await db.deleteMessage(message.linkId, message.id).catch(() => {});
52547
+ return false;
52548
+ }
51156
52549
  servicesChanged() {
51157
52550
  for (const live of this.links.values()) live.link?.refreshServices();
51158
52551
  this.emitState();
@@ -51177,6 +52570,8 @@ var GhostlyNode = class GhostlyNode {
51177
52570
  sessionOffers: stored.profile ? live.link?.sessionOffers : void 0,
51178
52571
  callsUnavailable: !stored.profile ? void 0 : live.link ? live.link.callsUnavailable : "Calls need a live connection",
51179
52572
  ...stored.profile && !stored.group && live.link?.peerTyping ? typingView(live.link.peerTypingActivity) : {},
52573
+ ...stored.profile && !stored.group && live.link?.peerStatus?.presence ? { peerPresence: live.link.peerStatus.presence } : {},
52574
+ ...stored.profile && !stored.group && live.link?.peerStatus?.status ? { peerStatus: live.link.peerStatus.status } : {},
51180
52575
  ...stored.profile && !stored.group && {
51181
52576
  wakeToken: this.settings.wake ? stored.wakeToken : void 0,
51182
52577
  peerWakes: !!stored.peerWake,
@@ -51204,7 +52599,7 @@ var GhostlyNode = class GhostlyNode {
51204
52599
  canSendText: (live.link?.canSendText ?? false) || this.holdingFor(live),
51205
52600
  textDelivery: this.holdingFor(live) ? "hold" : live.link?.textDelivery ?? "unavailable",
51206
52601
  transportErrors: live.transportErrors,
51207
- preferredTransport: live.stored.preferredTransport ?? automaticTransport(live.link?.availableTransports ?? []),
52602
+ preferredTransport: live.stored.preferredTransport ?? automaticTransport(live.link?.availableTransports ?? [], live.stored.transportFallback ?? true),
51208
52603
  transportFallback: live.stored.transportFallback ?? true,
51209
52604
  transportAutomatic: live.stored.preferredTransport === void 0,
51210
52605
  peerTransports: live.link?.peerAvailableTransports,
@@ -51325,12 +52720,22 @@ var EngineServer = class {
51325
52720
  /** How many history changes the engine told; per chat or group, the count at its last one (`historyMark`). */
51326
52721
  changes = 0;
51327
52722
  changedAt = /* @__PURE__ */ new Map();
52723
+ /**
52724
+ * An attention event while no client is attached to hear it: the host tells the person itself. The extension's peer
52725
+ * runs with no tab open, and a message that came then showed nothing until Ghostly was opened.
52726
+ */
52727
+ unheardAttention;
52728
+ /**
52729
+ * `keepNewest`: the start keeps each chat's and group's newest rows that many, from the whole histories it reads anyway,
52730
+ * for `takeStartNewest` (the CLI's event check at start, which read them again).
52731
+ */
51328
52732
  constructor(options = {}) {
52733
+ if (options.keepNewest) db.keepNewest(options.keepNewest);
51329
52734
  this.node = new GhostlyNode({
51330
- onAttention: (event) => this.broadcast({
52735
+ onAttention: (event) => this.clients.size ? this.broadcast({
51331
52736
  kind: "attention",
51332
52737
  event
51333
- }),
52738
+ }) : this.unheardAttention?.(event),
51334
52739
  onState: (state) => this.broadcast({
51335
52740
  kind: "state",
51336
52741
  state
@@ -51369,7 +52774,17 @@ var EngineServer = class {
51369
52774
  })
51370
52775
  }, options);
51371
52776
  this.ready = this.node.start();
51372
- this.ready.catch(() => {});
52777
+ this.ready.catch(() => {
52778
+ if (options.keepNewest) db.keepNewest(0);
52779
+ });
52780
+ }
52781
+ /**
52782
+ * Once the engine has started: per chat or group, its newest rows (`keepNewest`) as `messagePage` reads them, from the
52783
+ * whole history the start read. A history written since that read is not in it; one changed since the engine was made
52784
+ * may be (`historyChanged` says). Keeping stops: a second call gets none.
52785
+ */
52786
+ takeStartNewest() {
52787
+ return db.takeNewest();
51373
52788
  }
51374
52789
  /** A point in the engine's history changes: a history read after it can be handed to `attach` as read. */
51375
52790
  get historyMark() {
@@ -51603,4 +53018,4 @@ function signalKind(signal) {
51603
53018
  //#endregion
51604
53019
  export { EngineServer };
51605
53020
 
51606
- //# sourceMappingURL=server-DYdR0_Fj.js.map
53021
+ //# sourceMappingURL=server-rHKhnog1.js.map