@ghostlytools/cli 1.5.2 → 1.5.3

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 (101) hide show
  1. package/README.md +16 -11
  2. package/dist/assets/{api-CHD8_kcJ.js → api-BIg0Msax.js} +2 -2
  3. package/dist/assets/{api-CMohP9Pw.js → api-d2aXkbM5.js} +341 -114
  4. package/dist/assets/api-d2aXkbM5.js.map +1 -0
  5. package/dist/assets/{apiKit-CfwVtBcw.js → apiKit-Ba_t7MZO.js} +4 -4
  6. package/dist/assets/apiKit-Ba_t7MZO.js.map +1 -0
  7. package/dist/assets/{apps-733nXRBy.js → apps-B_F3gEI4.js} +1 -1
  8. package/dist/assets/{apps-LG-QOIxs.js → apps-CJo1MmSY.js} +17 -16
  9. package/dist/assets/apps-CJo1MmSY.js.map +1 -0
  10. package/dist/assets/{arkade-C8x3Efyj.js → arkade-DTne0O3Q.js} +12 -5
  11. package/dist/assets/arkade-DTne0O3Q.js.map +1 -0
  12. package/dist/assets/{backup-CfJenOQo.js → backup-BY88aZr5.js} +11 -8
  13. package/dist/assets/backup-BY88aZr5.js.map +1 -0
  14. package/dist/assets/{backup-nCbNWJ7-.js → backup-CqpDAZZG.js} +1 -1
  15. package/dist/assets/bark_ffi_wasm_bg-EY2uc0Bx.js.map +1 -1
  16. package/dist/assets/bitcoindevkit_bg-B-iLWrmX.js.map +1 -1
  17. package/dist/assets/{blobFiles-1wUBd8ZD.js → blobFiles-B1lX6iGy.js} +3 -3
  18. package/dist/assets/{blobFiles-1wUBd8ZD.js.map → blobFiles-B1lX6iGy.js.map} +1 -1
  19. package/dist/assets/{buttons-BC0stvPg.js → buttons-B5EnA2nh.js} +23 -6
  20. package/dist/assets/buttons-B5EnA2nh.js.map +1 -0
  21. package/dist/assets/buttons-azvbN6xn.js +2 -0
  22. package/dist/assets/{daemonProof-CWTVNUmr.js → daemonProof-Dx3N_DLC.js} +19 -37
  23. package/dist/assets/daemonProof-Dx3N_DLC.js.map +1 -0
  24. package/dist/assets/{endpoint-Cl3cgAYl.js → endpoint-BdaeBw2L.js} +3 -3
  25. package/dist/assets/endpoint-BdaeBw2L.js.map +1 -0
  26. package/dist/assets/{envelope-BbvUBjc5.js → envelope-BU-BB1wR.js} +2 -2
  27. package/dist/assets/{envelope-BbvUBjc5.js.map → envelope-BU-BB1wR.js.map} +1 -1
  28. package/dist/assets/{errors-BLSPp0tK.js → errors-DI6Z3jTH.js} +26 -1
  29. package/dist/assets/errors-DI6Z3jTH.js.map +1 -0
  30. package/dist/assets/{fileBytes-gTd_8l-P.js → fileBytes-BMlLVdfg.js} +1 -1
  31. package/dist/assets/{fileBytes-uRqLyxa0.js → fileBytes-D0CYuRwZ.js} +2 -2
  32. package/dist/assets/{fileBytes-uRqLyxa0.js.map → fileBytes-D0CYuRwZ.js.map} +1 -1
  33. package/dist/assets/{fileBytes-B8eTZfAT.js → fileBytes-D85lBh-Q.js} +3 -3
  34. package/dist/assets/{fileBytes-B8eTZfAT.js.map → fileBytes-D85lBh-Q.js.map} +1 -1
  35. package/dist/assets/fileBytesIdb-Dn9levD1.js +2 -0
  36. package/dist/assets/{fileBytesIdb-BIFKtgln.js → fileBytesIdb-LAhH7kY2.js} +7 -7
  37. package/dist/assets/fileBytesIdb-LAhH7kY2.js.map +1 -0
  38. package/dist/assets/{fileBytesOpfs-ChrHcCVV.js → fileBytesOpfs-DjBBghvq.js} +3 -3
  39. package/dist/assets/{fileBytesOpfs-ChrHcCVV.js.map → fileBytesOpfs-DjBBghvq.js.map} +1 -1
  40. package/dist/assets/{ghostly_iroh_web-BsAEFIjl.js → ghostly_iroh_web-BXCsSxxo.js} +29 -29
  41. package/dist/assets/{ghostly_iroh_web-BsAEFIjl.js.map → ghostly_iroh_web-BXCsSxxo.js.map} +1 -1
  42. package/dist/assets/ghostly_iroh_web_bg.wasm +0 -0
  43. package/dist/assets/{groupFiles-Bmo-SkVQ.js → groupFiles-D9k6fyhf.js} +61 -17
  44. package/dist/assets/groupFiles-D9k6fyhf.js.map +1 -0
  45. package/dist/assets/{host-DxDRCRKD.js → host-DrL7FPG4.js} +125 -47
  46. package/dist/assets/host-DrL7FPG4.js.map +1 -0
  47. package/dist/assets/{hyperdhtRelay-CZfsPfT9.js → hyperdhtRelay-C-BsT6_V.js} +2 -2
  48. package/dist/assets/{hyperdhtRelay-CZfsPfT9.js.map → hyperdhtRelay-C-BsT6_V.js.map} +1 -1
  49. package/dist/assets/{idb-BJARz3Qi.js → idb-CWvq4HKc.js} +25 -3
  50. package/dist/assets/{idb-BJARz3Qi.js.map → idb-CWvq4HKc.js.map} +1 -1
  51. package/dist/assets/{irohWeb-BUvaADop.js → irohWeb-DdHXEwgj.js} +3 -3
  52. package/dist/assets/{irohWeb-BUvaADop.js.map → irohWeb-DdHXEwgj.js.map} +1 -1
  53. package/dist/assets/{main-BIXIs84L.js → main-xeoX7yLM.js} +160 -50
  54. package/dist/assets/main-xeoX7yLM.js.map +1 -0
  55. package/dist/assets/{mainline-HQVJ5ukA.js → mainline-CEqGvRYJ.js} +46 -16
  56. package/dist/assets/mainline-CEqGvRYJ.js.map +1 -0
  57. package/dist/assets/{networkReason-CKBiFTwt.js → networkReason-RGRU5xoa.js} +3 -3
  58. package/dist/assets/{networkReason-CKBiFTwt.js.map → networkReason-RGRU5xoa.js.map} +1 -1
  59. package/dist/assets/{nwc-Dm4RSvvF.js → nwc-s5xHLqNf.js} +3 -3
  60. package/dist/assets/{nwc-Dm4RSvvF.js.map → nwc-s5xHLqNf.js.map} +1 -1
  61. package/dist/assets/{nwcProvider-yQdL-DfC.js → nwcProvider-CfAFO5Fr.js} +2 -2
  62. package/dist/assets/{nwcProvider-yQdL-DfC.js.map → nwcProvider-CfAFO5Fr.js.map} +1 -1
  63. package/dist/assets/{profiles-BehWURA9.js → profiles-gZdQPyaz.js} +74 -13
  64. package/dist/assets/profiles-gZdQPyaz.js.map +1 -0
  65. package/dist/assets/{registry-CHVZ0Jzl.js → registry-BUhSjM-J.js} +1 -1
  66. package/dist/assets/{registry-C9f2Ogff.js → registry-CVUdD4bJ.js} +3 -3
  67. package/dist/assets/{registry-C9f2Ogff.js.map → registry-CVUdD4bJ.js.map} +1 -1
  68. package/dist/assets/{resolve-Cqj1jjK2.js → resolve-uZECJ3f7.js} +2 -2
  69. package/dist/assets/{resolve-Cqj1jjK2.js.map → resolve-uZECJ3f7.js.map} +1 -1
  70. package/dist/assets/{restoredRows-DGuKtIBz.js → restoredRows-D6WZUA2U.js} +2 -2
  71. package/dist/assets/{restoredRows-DGuKtIBz.js.map → restoredRows-D6WZUA2U.js.map} +1 -1
  72. package/dist/assets/{server-CcAs54Yb.js → server-DOtUKoYR.js} +776 -248
  73. package/dist/assets/server-DOtUKoYR.js.map +1 -0
  74. package/dist/assets/{src-BLHey3Q1.js → src-Dd_7Ew1X.js} +459 -129
  75. package/dist/assets/src-Dd_7Ew1X.js.map +1 -0
  76. package/dist/assets/{usdt-DMKpMhdM.js → usdt-C2Anx8p7.js} +3 -3
  77. package/dist/assets/{usdt-DMKpMhdM.js.map → usdt-C2Anx8p7.js.map} +1 -1
  78. package/dist/assets/{words-DUlvkoUT.js → words-DoLU6p8H.js} +4 -4
  79. package/dist/assets/words-DoLU6p8H.js.map +1 -0
  80. package/dist/ghostly.mjs +1 -1
  81. package/package.json +1 -1
  82. package/dist/assets/api-CMohP9Pw.js.map +0 -1
  83. package/dist/assets/apiKit-CfwVtBcw.js.map +0 -1
  84. package/dist/assets/apps-LG-QOIxs.js.map +0 -1
  85. package/dist/assets/arkade-C8x3Efyj.js.map +0 -1
  86. package/dist/assets/backup-CfJenOQo.js.map +0 -1
  87. package/dist/assets/buttons-BC0stvPg.js.map +0 -1
  88. package/dist/assets/buttons-BDKeKyKw.js +0 -2
  89. package/dist/assets/daemonProof-CWTVNUmr.js.map +0 -1
  90. package/dist/assets/endpoint-Cl3cgAYl.js.map +0 -1
  91. package/dist/assets/errors-BLSPp0tK.js.map +0 -1
  92. package/dist/assets/fileBytesIdb-BIFKtgln.js.map +0 -1
  93. package/dist/assets/fileBytesIdb-BVVr_rWX.js +0 -2
  94. package/dist/assets/groupFiles-Bmo-SkVQ.js.map +0 -1
  95. package/dist/assets/host-DxDRCRKD.js.map +0 -1
  96. package/dist/assets/main-BIXIs84L.js.map +0 -1
  97. package/dist/assets/mainline-HQVJ5ukA.js.map +0 -1
  98. package/dist/assets/profiles-BehWURA9.js.map +0 -1
  99. package/dist/assets/server-CcAs54Yb.js.map +0 -1
  100. package/dist/assets/src-BLHey3Q1.js.map +0 -1
  101. package/dist/assets/words-DUlvkoUT.js.map +0 -1
@@ -1,16 +1,16 @@
1
1
  import { n as traceJoin } from "./joinTrace-CjRDFy85.js";
2
- import { $a as sameButtonText, $c as deviceInviteJoinerParams, $o as HANDOFF_TIMINGS, $r as isServeId, $s as inboxRecord, A as knockRecords, Aa as queueReaction, Ac as readAppBundleAsync, Ai as CapsExchange, Al as signTurnRelease, An as findEndpoint, Ar as transferStalled, B as GROUP_READ_NOTE, Bc as readAppRevocation, Bi as emptyIdentityLedger, Bn as engineError, Bo as emptyLinkRecords, Br as pinIsNewer, C as decodeCommunityLink, Ca as forwardedAgain, Cc as appDigest, Cl as turnPutSummary, Co as GhostlyHttpError, Cr as readBeacon, Cs as readHandoffDone, D as encodeGroupEntryLink, Da as REACTION_LIMITS, Dc as isAppUrl, Dl as nextTurnPosition, Dn as ENDPOINT, Do as LIMITS, Dr as ChatFiles, Ds as readHandoffTurnFrame, E as decodeGroupEntryLink, Ea as GROUP_REACTION_FRAME, El as firstDeviceSetSecret, En as decodeBolt11, Eo as webLocalFetch, Er as shouldBeHub, Es as readHandoffPake, F as groupWakeFrame, Fa as wireReaction, Fc as appRef, Fl as turnVerifierMark, Fn as INVITE_TAKEN, Fr as typingActivity, Fs as signTombstone, G as GROUP_EDIT_TEXT_BYTES, Gi as revokesIdentity, Gl as budgetRetryMs, Go as HANDOFF_CANCEL, Gr as deviceWakeRequest, Gs as enrollGrantFrame, Gt as encodeDidDhtPacket, H as frameBytes, Hi as identityStatement, Hl as normalizeRelayUrl, Hn as parseEngineError, Ho as LEGACY_SERVICES, Hr as readPin, Hs as enrollCancelReason, Ht as didDhtDocument, I as groupWakes, Ia as pairedReplyAuthor, Ii as IDENTITY_REVOCATION_LABEL, Il as DEFAULT_RELAYS, In as LIVENESS_PING_MS, Io as contactRtcConfig, Is as verifySetUpdate, J as mentionsMember, Jc as readCanonicalJson, Ji as emptyProofLedger, Jl as PacketTooLargeError, Jn as groupFileFallback, Jo as HANDOFF_HELLO, Jr as relayRequest, Js as readEnrollGrant, Jt as ETHEREUM_USDT, K as carryMentions, Ka as STATUS_CARD_LIMITS, Kc as canonicalJson, Ki as lastSharedWithMe, Kl as isDiscoveryBudgetError, Ko as HANDOFF_DONE, Kr as newWakeToken, Ks as enrollHelloFrame, L as parseGroupWakeFrame, La as readReply, Lc as isAppHash, Ln as PAIRED_FRAME_TOO_LARGE, Lr as PIN_LIMITS, M as readKnocks, Ma as reactionIsNewer, Mi as capsDescriptors, Ml as turnKeys, Mn as parseCashuRequestPayload, Ms as readSetUpdate, Na as readReaction, Nc as APP_STATEMENT_LIMITS, Ni as dialDescriptors, Nl as turnName, Nn as parseFedimintRequestPayload, Nr as TypingSender, Ns as setAckFrame, O as entryParams, Oa as ReactionWindow, Oc as pacer, Ol as readTurnPacket, On as cashuRequestPayload, Oo as decodeControl, Or as FILE_LIMITS, Os as readHandoffVerified, P as GroupWakeLimiter, Pa as validReactionNumber, Pc as appFingerprint, Pl as turnStatedVerifier, Pn as GhostLink, Ps as setUpdateFrame, Qa as checkStatusCard, Qc as createDeviceInvite, Qo as HANDOFF_REQUEST, Qr as APP_RANGE_LIMITS, Qs as endedRequests, Qt as SEPOLIA_TEST_USDT, R as GROUP_LIMITS, Ra as replySnippet, Rc as isAppKey, Ri as IdentityExchange, Rl as RelayTransport, Rn as pairedMessageFits, Ro as parseCallSignal, Rr as mayPin, S as communityHasFrame, Sa as parseLinkPreview, Sl as classifyTurnRead, So as presenceSeenAt, Sr as rankHubs, Ss as readHandoffCancel, Ta as COMMUNITY_REACTION_FRAME, Tl as TURN_MAX, To as parseLocalTarget, Tr as readLobby, Ts as readHandoffHello, Ui as newIdentityBinding, Un as GROUP_FILE_LIMITS, Uo as serviceIdFromName, Ur as WAKE_CALL_INTERVAL_MS, Us as enrollDigits, Ut as didDhtFromPublicKey, V as GroupSession, Vi as identityRevocationValue, Vl as currentRelays, Vn as engineText, Vo as HTTP_SERVICE_PROTO, Vr as pinNumberHolds, Vs as enrollCancelFrame, Wc as parseImageMeta, Wi as receivedIdentityStatus, Wl as traceLink, Wo as HANDOFF_ACK, Wr as WakeLimiter, Ws as enrollDoneFrame, Wt as encodeDidDhtDeactivated, Xc as encodeContactLink, Xi as TRANSPORTS, Xl as createRelayPayload, Xn as readGroupFileMeta, Xo as HANDOFF_PAKE, Xr as checkPushEndpoint, Xs as verifyEnrollProof, Xt as ONCHAIN_PROVIDER, Y as groupName, Yc as createContactLink, Yi as validExternalKey, Yo as HANDOFF_OFFER, Yr as wakeRequest, Ys as readEnrollHello, Yt as EVM_TEST_CHAINS, Zc as readContactLink, Zi as automaticTransport, Zo as HANDOFF_PIECE_BYTES, Zr as vapidKeysMatch, Zs as clearMissed, Zt as PaymentPreflightError, _ as openGroupTyping, _a as EDIT_RATE_WINDOW_MS, _c as requestRecords, _l as seedSigner, _r as lobbyRecords, _s as handoffRetryAfter, a as appStoreDecision, aa as formatFileSize, ac as ContactRequestError, ai as EDIT_CAPABILITY, al as inviteLink, an as assertWholeSats, ao as shownTime, ar as groupSignalFrame, as as handoffBusyFrame, b as CommunitySession, ba as RateWindow, bc as APP_BUNDLE_MAGIC, bl as TURN_RAISE_READ_TIMEOUT_MS, bo as RELAY_POLL_INTERVALS, br as newerHead, bs as newHandoffId, c as planAppUpdate, cc as knockSlotIdentity, ci as HOLD_CAPABILITY, cl as DEVICES_CAPABILITY, cn as walletNetworkOf, cr as mayBeHub, cs as handoffContextProof, cu as bytesEqual, da as fileMessageText, dc as linkRecords, di as HoldKeys, dl as deviceEchoFrame, dn as sparkAddressKind, do as parseGroupCommit, dr as COMMUNITY_TOPOLOGY, ds as handoffEphemeral, du as randomBytes, ec as newInbox, el as readDeviceInvite, en as TEST_USDT_FAUCET_AMOUNT, eo as statusCardText, er as CarriedTransport, es as HANDOFF_VERIFIED, eu as createIdentity, f as readAppStoreSteps, fa as parseVoiceMeta, fc as makeStampPaced, fi as HoldRefusedError, fl as deviceEchoNonce, fn as sparkInvoiceDetails, fo as rosterAdmin, fr as beaconKeys, fs as handoffHelloFrame, fu as toBase64Url, g as groupTypingEpoch, ga as EDIT_BUFFER_MS, gc as readLinkRecord, gl as newDeviceSetSecret, go as DirectPathWatch, gr as lobbyKeys, gs as handoffReleaseFrame, gt as normalizeAtprotoHandle, h as GroupTypingBoard, ha as parseVideoMeta, hc as readKnockSlot, hi as readManifest, hl as devicePingFrame, hn as isPubkyKey, ho as edgeParams, hr as freshHubs, hs as handoffPakeFrame, ht as isAtprotoDid, hu as utf8Encode, i as appRevocationFor, ia as dhtFileId, ic as turnOff, ii as BUTTONS_CAPABILITY, il as encodeInviteCode, in as assertTokenUnits, io as receivedTimestamp, is as handoffAttemptSucceeded, iu as verify, j as mergeKnocks, ja as reactionEmoji, jc as sha256Paced, ji as DHT_TEXT_CAPABILITY, jl as turnInstance, jn as isFederationId, jo as RTC_CONFIG, k as knockIdentity, ka as nextReactionNumber, kl as signTurnPacket, kn as fedimintRequestPayload, ko as encodeControl, kr as transferEnded, ks as sealHandoffPiece, l as APP_STORE_LIMITS, lc as knockSlotOf, li as HOLD_DATED_BACK_MS, ll as ENROLL_CAPABILITY, ln as SPARK_NETWORKS, lo as MEMBER_KEY, lr as meshHubs, ls as handoffDataFrame, lu as fromBase64Url, mc as openRequest, mi as newMailbox, ml as deviceLinkPairing, mo as verifyCommitSignature, mr as doorHubs, ms as handoffOfferFrame, mu as utf8Decode, n as readX401SdJwtVc, na as peekDhtMailbox, nc as settleRequest, ni as isAppVersion, nl as createChatInvite, nn as WALLET_NETWORKS, no as claimedTime, ns as handoffAttemptAllowed, nu as identityFromSeedB64, o as appUpdateDecision, oa as sanitizeFileName, oc as REQUEST_LIFETIME_MS, oi as STATUS_CARD_CAPABILITY, ol as inviteOwnership, on as formatPaymentAmount, oo as GROUP_ADMIN_OFF_ERROR, or as readGroupSignal, os as handoffCancelFrame, ou as sanitizeAvatar, pc as mergeContactKnocks, pi as isHoldUrl, pl as deviceKeyZ32, pn as isBitcoinAddress, po as rosterHas, pr as beaconRecords, ps as handoffManifestFrames, pu as toZ32, q as parseCommunityEdit, qi as PeerProofs, ql as withRequestOptions, qo as HANDOFF_HAVE, qr as parseWakeFrame, qs as enrollProofFrame, qt as signDidDhtPacket, r as sameX401HolderJwk, ra as DHT_FILE_CAPABILITY, rc as takeRequest, ri as APPS_CAPABILITY, rl as decodeInviteCode, rn as arkAddressPrefix, ro as heardTime, rs as handoffAttemptFailed, ru as publicKeyFromZ32, s as checkAppBeforeRun, sa as sanitizeMime, sc as contactDay, si as UPGRADE_CAPABILITY, sn as validatePaymentTarget, so as GROUP_MEMBER_CAP, sr as MESH_HUBS, ss as handoffContext, su as sanitizeDisplayText, t as newX401HolderKey, ta as DHT_MESSAGE_TTL, tc as planKnocks, ti as chatAppId, tl as OwnInviteError, tn as USDT_PUBLIC_RPC, to as arrivalKey, ts as filePartName, tu as identityFromSeed, uc as knockSlotRecords, ui as HOLD_LIMITS, ul as HANDOFF_CAPABILITY, un as SPARK_PROVIDER, uo as commitHash, ur as pickMeshHubs, us as handoffDigest, v as sealGroupTyping, va as MAX_REMOVAL_NUMBER, vc as seenEntry, vl as webCryptoSigner, vo as DHT_POLL_INTERVALS, vr as mergeBeacon, vs as handoffStreamKey, w as encodeCommunityLink, wa as readForwarded, wc as appViewOf, wl as TURN_LAST_SEQUENCE, wo as formatLocalTarget, wr as readBeaconHead, ws as readHandoffHave, x as GROUP_READ_NOTE_COMMUNITY, xa as dhtEditId, xc as APP_ICON_PATH, xl as TURN_SETTLE_MS, xo as WATCH_PEER_MS, xr as pickHubs, xs as readHandoffAck, y as COMMUNITY_LIMITS, ya as REMOVED_TEXT, yc as APP_BUNDLE_LIMITS, yr as mergeLobby, ys as handoffVersions, za as BUTTON_ID, zc as isAppRef, zn as pairedMessageFrame, zr as nextPinNumber } from "./src-BLHey3Q1.js";
2
+ import { $c as createContactLink, $i as automaticTransport, $l as PacketTooLargeError, $o as HANDOFF_OFFER, $r as vapidKeysMatch, $s as readEnrollHello, A as knockRecords, Aa as GROUP_REACTION_FRAME, Al as firstDeviceSetSecret, An as findEndpoint, Ao as webLocalFetch, As as readHandoffPake, B as GROUP_READ_NOTE, Ba as pairedReplyAuthor, Bi as IdentityExchange, Bl as DEFAULT_RELAYS, Bn as EngineError, Bo as contactRtcConfig, Br as mayPin, Bs as verifySetUpdate, C as decodeCommunityLink, Ca as REMOVED_TEXT, Cc as APP_BUNDLE_LIMITS, Cr as rankHubs, Cs as handoffVersions, D as encodeGroupEntryLink, Da as forwardedAgain, Dc as appDigest, Dl as turnPutSummary, Dn as ENDPOINT, Do as GhostlyHttpError, Dr as shouldBeHub, Ds as readHandoffDone, E as decodeGroupEntryLink, Ea as parseLinkPreview, El as classifyTurnRead, En as decodeBolt11, Eo as presenceSeenAt, Er as readLobby, Es as readHandoffCancel, F as groupWakeFrame, Fa as reactionEmoji, Fc as sha256Paced, Fi as dialDescriptors, Fl as turnInstance, Fn as INVITE_TAKEN, Fo as RTC_CONFIG, Fr as TypingSender, G as GROUP_EDIT_TEXT_BYTES, Gi as newIdentityBinding, Go as HTTP_SERVICE_PROTO, Gr as WAKE_CALL_INTERVAL_MS, Gs as enrollCancelFrame, Gt as encodeDidDhtPacket, H as frameBytes, Ha as replySnippet, Hc as isAppKey, Hi as emptyIdentityLedger, Hn as engineText, Ho as parseCallSignal, Hr as pinIsNewer, Ht as didDhtDocument, I as groupWakes, Ia as reactionIsNewer, Il as turnKeys, In as LIVENESS_PING_MS, Is as readSetUpdate, J as mentionsMember, Jc as parseImageMeta, Ji as lastSharedWithMe, Jo as HANDOFF_ACK, Jr as newWakeToken, Js as enrollDoneFrame, Jt as ETHEREUM_USDT, K as carryMentions, Ki as receivedIdentityStatus, Kl as currentRelays, Ko as LEGACY_SERVICES, Kr as WakeLimiter, Ks as enrollCancelReason, L as parseGroupWakeFrame, La as readReaction, Lc as APP_STATEMENT_LIMITS, Ll as turnName, Ln as PAIRED_FRAME_TOO_LARGE, Lr as typingActivity, Ls as setAckFrame, M as readKnocks, Ma as ReactionWindow, Mc as pacer, Mi as CapsExchange, Ml as readTurnPacket, Mn as parseCashuRequestPayload, Mo as decodeControl, Mr as transferStalled, Ms as readHandoffVerified, Na as nextReactionNumber, Ni as DHT_TEXT_CAPABILITY, Nl as signTurnPacket, Nn as parseFedimintRequestPayload, No as encodeControl, Ns as sealHandoffPiece, O as entryParams, Oa as readForwarded, Oc as appViewOf, Ol as TURN_LAST_SEQUENCE, On as cashuRequestPayload, Oo as formatLocalTarget, Or as ChatFiles, Os as readHandoffHave, P as GroupWakeLimiter, Pa as queueReaction, Pc as readAppBundleAsync, Pi as capsDescriptors, Pl as signTurnRelease, Pn as GhostLink, Qc as readCanonicalJson, Qi as TRANSPORTS, Ql as withRequestOptions, Qo as HANDOFF_HELLO, Qr as checkPushEndpoint, Qs as readEnrollGrant, Qt as SEPOLIA_TEST_USDT, R as GROUP_LIMITS, Ra as validReactionNumber, Rc as appFingerprint, Ri as IDENTITY_REVOCATION_LABEL, Rl as turnStatedVerifier, Rn as pairedMessageFits, Rs as setUpdateFrame, S as communityHasFrame, Sa as MAX_REMOVAL_NUMBER, Sc as seenEntry, Sl as webCryptoSigner, So as DHT_POLL_INTERVALS, Sr as pickHubs, Ss as handoffStreamKey, Ta as dhtEditId, Tc as APP_ICON_PATH, Tl as TURN_SETTLE_MS, To as WATCH_PEER_MS, Tr as readBeaconHead, Ts as readHandoffAck, Ua as BUTTON_ID, Uc as isAppRef, Ui as identityRevocationValue, Ul as RelayTransport, Un as parseEngineError, Ur as pinNumberHolds, Ut as didDhtFromPublicKey, V as GroupSession, Va as readReply, Vc as isAppHash, Vn as engineError, Vr as nextPinNumber, Wc as readAppRevocation, Wi as identityStatement, Wn as GROUP_FILE_LIMITS, Wo as emptyLinkRecords, Wr as readPin, Wt as encodeDidDhtDeactivated, Xa as STATUS_CARD_LIMITS, Xc as canonicalJson, Xi as emptyProofLedger, Xl as budgetRetryMs, Xo as HANDOFF_DONE, Xr as relayRequest, Xs as enrollHelloFrame, Xt as ONCHAIN_PROVIDER, Y as groupName, Yi as PeerProofs, Yl as traceLink, Yn as groupFileFallback, Yo as HANDOFF_CANCEL, Yr as parseWakeFrame, Ys as enrollGrantFrame, Yt as EVM_TEST_CHAINS, Zi as validExternalKey, Zl as isDiscoveryBudgetError, Zn as readGroupFileMeta, Zo as HANDOFF_HAVE, Zr as wakeRequest, Zs as enrollProofFrame, Zt as PaymentPreflightError, _ as openGroupTyping, _c as mergeContactKnocks, _i as readManifest, _l as deviceKeyZ32, _o as rosterHas, _r as lobbyKeys, _s as handoffManifestFrames, _u as toBase64Url, a as appStoreDecision, aa as DHT_FILE_CAPABILITY, ac as planKnocks, ai as APPS_CAPABILITY, al as OwnInviteError, an as assertWholeSats, ao as arrivalKey, as as filePartName, au as createIdentity, b as CommunitySession, ba as EDIT_BUFFER_MS, bc as readLinkRecord, bl as newDeviceSetSecret, bo as DirectPathWatch, br as mergeLobby, bs as handoffReleaseFrame, bu as utf8Encode, c as planAppUpdate, ca as sanitizeFileName, cc as turnOff, ci as STATUS_CARD_CAPABILITY, cl as encodeInviteCode, cn as walletNetworkOf, co as receivedTimestamp, cr as MESH_HUBS, cs as handoffAttemptSucceeded, cu as publicKeyFromZ32, dc as contactDay, di as HOLD_DATED_BACK_MS, dn as sparkAddressKind, do as GROUP_MEMBER_CAP, dr as pickMeshHubs, ds as handoffContext, du as sanitizeAvatar, ec as verifyEnrollProof, ei as APP_RANGE_LIMITS, el as encodeContactLink, en as TEST_USDT_FAUCET_AMOUNT, es as HANDOFF_PAKE, f as readAppStoreSteps, fc as knockSlotIdentity, fi as HOLD_LIMITS, fl as DEVICES_CAPABILITY, fn as sparkInvoiceDetails, fr as COMMUNITY_TOPOLOGY, fs as handoffContextProof, fu as sanitizeDisplayText, g as groupTypingEpoch, ga as parseVoiceMeta, gc as makeStampPaced, gi as newMailbox, gl as deviceEchoNonce, go as rosterAdmin, gr as freshHubs, gs as handoffHelloFrame, gt as normalizeAtprotoHandle, gu as randomBytes, h as GroupTypingBoard, ha as fileMessageText, hc as linkRecords, hi as isHoldUrl, hl as deviceEchoFrame, hn as isPubkyKey, ho as parseGroupCommit, hr as doorHubs, hs as handoffEphemeral, ht as isAtprotoDid, i as appRevocationFor, ia as peekDhtMailbox, ic as newInbox, ii as isAppVersion, il as readDeviceInvite, in as assertTokenUnits, io as statusCardText, is as HANDOFF_VERIFIED, j as mergeKnocks, ja as REACTION_LIMITS, jc as isAppUrl, jl as nextTurnPosition, jn as isFederationId, jo as LIMITS, jr as transferEnded, js as readHandoffTurnFrame, k as knockIdentity, ka as COMMUNITY_REACTION_FRAME, kl as TURN_MAX, kn as fedimintRequestPayload, ko as parseLocalTarget, kr as FILE_LIMITS, ks as readHandoffHello, l as APP_STORE_LIMITS, la as sanitizeMime, lc as ContactRequestError, li as UPGRADE_CAPABILITY, ll as inviteLink, ln as SPARK_NETWORKS, lo as shownTime, lr as mayBeHub, ls as handoffBusyFrame, lu as verify, mc as knockSlotRecords, mi as HoldRefusedError, ml as HANDOFF_CAPABILITY, mo as commitHash, mr as beaconRecords, ms as handoffDigest, mu as fromBase64Url, n as readX401SdJwtVc, nc as endedRequests, nl as createDeviceInvite, nn as WALLET_NETWORKS, no as checkStatusCard, ns as HANDOFF_REQUEST, o as appUpdateDecision, oa as dhtFileId, oc as settleRequest, oi as BUTTONS_CAPABILITY, ol as createChatInvite, on as formatPaymentAmount, oo as claimedTime, or as groupSignalFrame, os as handoffAttemptAllowed, ou as identityFromSeed, pc as knockSlotOf, pi as HoldKeys, pl as ENROLL_CAPABILITY, pn as isBitcoinAddress, po as MEMBER_KEY, pr as beaconKeys, ps as handoffDataFrame, pu as bytesEqual, q as parseCommunityEdit, qi as revokesIdentity, ql as normalizeRelayUrl, qo as serviceIdFromName, qr as deviceWakeRequest, qs as enrollDigits, qt as signDidDhtPacket, r as sameX401HolderJwk, ra as DHT_MESSAGE_TTL, rc as inboxRecord, ri as chatAppId, rl as deviceInviteJoinerParams, rn as arkAddressPrefix, ro as sameButtonText, rs as HANDOFF_TIMINGS, s as checkAppBeforeRun, sa as formatFileSize, sc as takeRequest, si as EDIT_CAPABILITY, sl as decodeInviteCode, sn as validatePaymentTarget, so as heardTime, sr as readGroupSignal, ss as handoffAttemptFailed, su as identityFromSeedB64, t as newX401HolderKey, tc as clearMissed, ti as isServeId, tl as readContactLink, tn as USDT_PUBLIC_RPC, tr as CarriedTransport, ts as HANDOFF_PIECE_BYTES, tu as createRelayPayload, uc as REQUEST_LIFETIME_MS, ui as HOLD_CAPABILITY, ul as inviteOwnership, un as SPARK_PROVIDER, uo as GROUP_ADMIN_OFF_ERROR, ur as meshHubs, us as handoffCancelFrame, v as sealGroupTyping, vc as openRequest, vl as deviceLinkPairing, vo as verifyCommitSignature, vr as lobbyRecords, vs as handoffOfferFrame, vu as toZ32, w as encodeCommunityLink, wa as RateWindow, wc as APP_BUNDLE_MAGIC, wl as TURN_RAISE_READ_TIMEOUT_MS, wo as RELAY_POLL_INTERVALS, wr as readBeacon, ws as newHandoffId, x as GROUP_READ_NOTE_COMMUNITY, xa as EDIT_RATE_WINDOW_MS, xc as requestRecords, xl as seedSigner, xr as newerHead, xs as handoffRetryAfter, y as COMMUNITY_LIMITS, ya as parseVideoMeta, yc as readKnockSlot, yl as devicePingFrame, yo as edgeParams, yr as mergeBeacon, ys as handoffPakeFrame, yu as utf8Decode, za as wireReaction, zc as appRef, zl as turnVerifierMark, zn as pairedMessageFrame, zr as PIN_LIMITS, zs as signTombstone } from "./src-Dd_7Ew1X.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-yQdL-DfC.js";
6
- import { a as clearProfileStores, c as errorLine, d as openDb, f as profileOpenFailure, h as wrap, i as STORES$1, l as fileStore, m as transact, n as APP_STORAGE_SCOPE_INDEX, o as databaseName, p as store, r as CARD_INDEX, s as deleteDatabase, t as APP_STORAGE_CHAT_INDEX, u as newestWalletTx } from "./idb-BJARz3Qi.js";
7
- import { a as sealSeed, i as newDeviceKey, o as unsealSeed, r as intentRepository } from "./networkReason-CKBiFTwt.js";
8
- import { $ as setAwayWallets, A as LightningCards, B as breezDatabaseInUse, C as FileAppender, D as streamStored, E as storedSize, F as ProviderSources, G as relayOnlyProblem, H as dropBreezDatabase, I as sourceKey, J as WrongNetworkError, K as ModeChanged, L as CASHU_MINT_SOURCE, M as isRecoveryPhrase, N as normalizePhrase, P as lightningPaying, Q as requireTurn, R as cashuMint, S as WALLET_TYPES, T as removeStored, U as iceServerProblem, V as breezDatabasesFor, W as iceServerSetting, X as awayFrom, Y as networkLabel, Z as refuseAway, _ as crossNetwork, a as storedGroupFiles, b as walletInstances, c as receivedPairedReply, d as paymentAlias, et as setSingleWriterGate, f as paymentWireId, g as createTiming, h as createFailure, i as groupOfFile, j as cardsKey, k as CASHU_CARD, l as replyRef, m as assertConfirmedReal, n as groupFileId, o as groupReply, p as WALLET_NAMES, q as ModeGate, r as groupFileText, s as pairedWireReply, t as GroupFileDesk, u as replyTo, v as paymentNetwork, w as readStored$1, y as paymentNetworksOf, z as breezDatabase } from "./groupFiles-Bmo-SkVQ.js";
9
- import { i as fedimintDatabase, n as createIrohWebEndpoint, o as loadFedimintSdk, r as irohRelayProblem, t as DEFAULT_IROH_RELAYS } from "./irohWeb-BUvaADop.js";
5
+ import { t as nwc } from "./nwcProvider-CfAFO5Fr.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-CWvq4HKc.js";
7
+ import { a as sealSeed, i as newDeviceKey, o as unsealSeed, r as intentRepository } from "./networkReason-RGRU5xoa.js";
8
+ import { $ as setAwayWallets, A as LightningCards, B as breezDatabaseInUse, C as FileAppender, D as streamStored, E as storedSize, F as ProviderSources, G as relayOnlyProblem, H as dropBreezDatabase, I as sourceKey, J as WrongNetworkError, K as ModeChanged, L as CASHU_MINT_SOURCE, M as isRecoveryPhrase, N as normalizePhrase, P as lightningPaying, Q as requireTurn, R as cashuMint, S as WALLET_TYPES, T as removeStored, U as iceServerProblem, V as breezDatabasesFor, W as iceServerSetting, X as awayFrom, Y as networkLabel, Z as refuseAway, _ as crossNetwork, a as storedGroupFiles, b as walletInstances, c as receivedPairedReply, d as paymentAlias, et as setSingleWriterGate, f as paymentWireId, g as createTiming, h as createFailure, i as groupOfFile, j as cardsKey, k as CASHU_CARD, l as replyRef, m as assertConfirmedReal, n as groupFileId, o as groupReply, p as WALLET_NAMES, q as ModeGate, r as groupFileText, s as pairedWireReply, t as GroupFileDesk, u as replyTo, v as paymentNetwork, w as readStored$1, y as paymentNetworksOf, z as breezDatabase } from "./groupFiles-D9k6fyhf.js";
9
+ import { i as fedimintDatabase, n as createIrohWebEndpoint, o as loadFedimintSdk, r as irohRelayProblem, t as DEFAULT_IROH_RELAYS } from "./irohWeb-DdHXEwgj.js";
10
10
  import { c as isTestMint, d 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-BrlY773j.js";
11
- import { _ as reserveAdapterIds, b as testBuild, f as setOwnDidSource, g as registeredOnchainProviders, h as registeredLightningProviders, l as chosenResolver, n as resolveAtprotoDid, p as onAdaptersChanged, t as assertPublicServer, v as boundedIdentityFetch, y as verifyIdentity } from "./resolve-Cqj1jjK2.js";
12
- import { i as fromBase64Url$1, n as MAX_BACKUP_BYTES, t as BACKUP_MEDIA_TYPE } from "./envelope-BbvUBjc5.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-B8eTZfAT.js";
11
+ import { _ as reserveAdapterIds, b as testBuild, f as setOwnDidSource, g as registeredOnchainProviders, h as registeredLightningProviders, l as chosenResolver, n as resolveAtprotoDid, p as onAdaptersChanged, t as assertPublicServer, v as boundedIdentityFetch, y as verifyIdentity } from "./resolve-uZECJ3f7.js";
12
+ import { i as fromBase64Url$1, n as MAX_BACKUP_BYTES, t as BACKUP_MEDIA_TYPE } from "./envelope-BU-BB1wR.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-D85lBh-Q.js";
14
14
  import { t as hyperdhtRelayProblem } from "./hyperdhtRelay-BT_wRxab.js";
15
15
  import { sha256 } from "@noble/hashes/sha2.js";
16
16
  import { hkdf } from "@noble/hashes/hkdf.js";
@@ -198,7 +198,7 @@ function viewNews(before, after) {
198
198
  //#endregion
199
199
  //#region ../browser/src/engine/paymentAdapters/usdtWallet.ts
200
200
  /** The Ethereum libraries, a large part of the app: loaded once a USDT wallet is made, opened or restored, not with the engine. */
201
- var loadUsdt = () => import("./usdt-DMKpMhdM.js");
201
+ var loadUsdt = () => import("./usdt-C2Anx8p7.js");
202
202
  /** Every new profile starts with this wallet: an address to receive on, nothing to set up. */
203
203
  var DEFAULT_USDT = {
204
204
  network: "ethereum",
@@ -647,7 +647,7 @@ async function restoreArkDatabase(walletId, snapshot) {
647
647
  //#endregion
648
648
  //#region ../browser/src/engine/paymentAdapters/arkWallet.ts
649
649
  /** The Ark SDK, a large part of the app: loaded once an Ark wallet is made, opened or restored, not with the engine. */
650
- var loadArkade = () => import("./arkade-C8x3Efyj.js");
650
+ var loadArkade = () => import("./arkade-DTne0O3Q.js");
651
651
  /** How long a Testnet wallet about to make way for another waits for its server to say what it holds. */
652
652
  var RETIRE_READ_MS = 1e4;
653
653
  /** Every new profile starts with this wallet: nothing to set up before receiving. */
@@ -994,8 +994,10 @@ var ArkWallet = class {
994
994
  };
995
995
  this.changed();
996
996
  }
997
- const balance = await read("balance", () => adapter.balance(), this.view.balance);
998
- const incoming = await read("incoming", () => adapter.incoming(), this.view.incoming);
997
+ const { balance, incoming } = await read("balance", () => adapter.balances(), {
998
+ balance: this.view.balance,
999
+ incoming: this.view.incoming
1000
+ });
999
1001
  const { recoverable, sweeping, small } = await read("recoverable", () => adapter.expired(), {
1000
1002
  recoverable: this.view.recoverable,
1001
1003
  sweeping: this.view.sweeping,
@@ -1006,7 +1008,7 @@ var ArkWallet = class {
1006
1008
  return this.view.expiresAt;
1007
1009
  });
1008
1010
  if (this.adapter !== adapter) return;
1009
- const balancesRead = this.view.read || !failed.some((what) => what === "balance" || what === "incoming" || what === "recoverable");
1011
+ const balancesRead = this.view.read || !failed.some((what) => what === "balance" || what === "recoverable");
1010
1012
  const before = this.view;
1011
1013
  this.view = {
1012
1014
  configured: true,
@@ -6813,7 +6815,7 @@ var registry;
6813
6815
  var loading$1;
6814
6816
  var listeners = /* @__PURE__ */ new Set();
6815
6817
  function loadIdentityProviders() {
6816
- return loading$1 ??= import("./registry-CHVZ0Jzl.js").then((m) => {
6818
+ return loading$1 ??= import("./registry-BUhSjM-J.js").then((m) => {
6817
6819
  registry = m;
6818
6820
  for (const listener of listeners) listener();
6819
6821
  return m;
@@ -7630,7 +7632,7 @@ var ProfileDid = class {
7630
7632
  return this.seed;
7631
7633
  }
7632
7634
  async save(next) {
7633
- await wrap((await store(STORES$1.settings, "readwrite")).put(next, KEY$1));
7635
+ await committed((await store(STORES$1.settings, "readwrite")).put(next, KEY$1));
7634
7636
  this.stored = next;
7635
7637
  }
7636
7638
  };
@@ -10871,7 +10873,11 @@ var SavedMessages = class {
10871
10873
  if (row) return row;
10872
10874
  }
10873
10875
  }
10874
- /** Saves a message, or unsaves it with `remove`. Saving one already saved keeps its first time. */
10876
+ /**
10877
+ * Saves a message, or unsaves it with `remove`. Saving one already saved keeps its first time. `removed`: whether a
10878
+ * mark went. An id that names neither a mark nor a message of the chat (a typo) is "not in this chat", as `save` says
10879
+ * it; before, it answered done and the message meant stayed saved (agents#1580).
10880
+ */
10875
10881
  save({ linkId, messageId, remove }) {
10876
10882
  return this.serial(async () => {
10877
10883
  if (typeof linkId !== "string" || !linkId) return { error: "No chat named" };
@@ -10886,8 +10892,15 @@ var SavedMessages = class {
10886
10892
  if (next.length !== marks.length) {
10887
10893
  await this.write(next);
10888
10894
  this.changed();
10895
+ return {
10896
+ error: null,
10897
+ removed: true
10898
+ };
10889
10899
  }
10890
- return { error: null };
10900
+ return row ? {
10901
+ error: null,
10902
+ removed: false
10903
+ } : { error: "That message is not in this chat" };
10891
10904
  }
10892
10905
  const row = await this.row(linkId, messageId);
10893
10906
  if (!row) return { error: "That message is not in this chat" };
@@ -11612,7 +11625,7 @@ var Apps = class {
11612
11625
  }
11613
11626
  async putApp(app) {
11614
11627
  try {
11615
- await wrap((await store(STORES$1.apps, "readwrite")).put(app));
11628
+ await committed((await store(STORES$1.apps, "readwrite")).put(app));
11616
11629
  } finally {
11617
11630
  this.held.delete(app.ref);
11618
11631
  }
@@ -11655,7 +11668,7 @@ var Apps = class {
11655
11668
  async writeStores(write, apply) {
11656
11669
  const before = this.records();
11657
11670
  const written = before.then(async (held) => {
11658
- await wrap(write(await store(STORES$1.appStores, "readwrite")));
11671
+ await committed(write(await store(STORES$1.appStores, "readwrite")));
11659
11672
  apply(held);
11660
11673
  this.views = null;
11661
11674
  });
@@ -11669,9 +11682,6 @@ var Apps = class {
11669
11682
  putStore(record) {
11670
11683
  return this.writeStores((records) => records.put(record), (held) => held.set(record.key, record));
11671
11684
  }
11672
- deleteStore(key) {
11673
- return this.writeStores((records) => records.delete(key), (held) => held.delete(key));
11674
- }
11675
11685
  /** The stores' views, made once and again after a store is written here: an app's every storage call and chat frame checks them. */
11676
11686
  heldViews() {
11677
11687
  return this.views ??= this.stores().then((s) => this.storeViews(s), (error) => {
@@ -11995,8 +12005,10 @@ var Apps = class {
11995
12005
  }
11996
12006
  /**
11997
12007
  * Adds a store the person chose: read at its URL and pinned to its key (`key`, when given, is the key the person saw,
11998
- * and another one is refused). A store already added under that key takes the URL and the newer index. The index the
11999
- * preview just read at that URL, under that key, is taken as it is (only its expiry again), not downloaded again.
12008
+ * and another one is refused). A store already added under that key keeps the URL it is read from and takes only a newer
12009
+ * index: a copy of its signed index at another URL, the same one or an older one, never moves it there (it would be
12010
+ * read only there from then on, frozen). The index the preview just read at that URL, under that key, is taken as it
12011
+ * is (only its expiry again), not downloaded again.
12000
12012
  */
12001
12013
  async addStore({ url, key }) {
12002
12014
  if (key !== void 0 && !isAppKey(key)) fail("store-key", "Not a store key");
@@ -12014,10 +12026,16 @@ var Apps = class {
12014
12026
  if (!read.ok) fail(read.reason, "This is not a store Ghostly can read");
12015
12027
  const { index, digest } = read.store;
12016
12028
  const held = await this.storeRecord(index.key);
12017
- const record = held && !held.removed ? {
12018
- ...held,
12019
- url: at
12020
- } : {
12029
+ const seen = held?.removed && held.seen && appStoreDecision({
12030
+ key: held.key,
12031
+ ...held.seen
12032
+ }, {
12033
+ key: index.key,
12034
+ sequence: index.sequence,
12035
+ digest
12036
+ });
12037
+ if (seen === "rollback" || seen === "equivocation") fail(seen, `This store's index is older than the one you had (sequence ${held.seen.sequence})`);
12038
+ const record = held && !held.removed ? held : {
12021
12039
  key: index.key,
12022
12040
  url: at,
12023
12041
  addedAt: this.now(),
@@ -12076,14 +12094,18 @@ var Apps = class {
12076
12094
  async removeStore({ key }) {
12077
12095
  const held = await this.storeRecord(key);
12078
12096
  if (!held) return;
12079
- if (held.preloaded) await this.putStore({
12097
+ const seen = held.index ? {
12098
+ sequence: held.index.sequence,
12099
+ digest: held.digest ?? ""
12100
+ } : held.seen;
12101
+ await this.putStore({
12080
12102
  key: held.key,
12081
12103
  url: held.url,
12082
12104
  addedAt: held.addedAt,
12083
- preloaded: true,
12084
- removed: true
12105
+ ...held.preloaded && { preloaded: true },
12106
+ removed: true,
12107
+ ...seen && { seen }
12085
12108
  });
12086
- else await this.deleteStore(key);
12087
12109
  for (const app of await this.installed()) {
12088
12110
  if (app.store !== key) continue;
12089
12111
  const { store: _s, ...unpinned } = app;
@@ -12854,7 +12876,7 @@ var Apps = class {
12854
12876
  value: text,
12855
12877
  size
12856
12878
  });
12857
- await wrap(writing.put(counterRow(app.ref, where, next)));
12879
+ await committed(writing.put(counterRow(app.ref, where, next)));
12858
12880
  this.usage.set(`${app.ref}\0${where}`, next);
12859
12881
  });
12860
12882
  }
@@ -12876,7 +12898,7 @@ var Apps = class {
12876
12898
  where,
12877
12899
  name
12878
12900
  ]);
12879
- await (next.rows ? wrap(writing.put(counterRow(app.ref, where, next))) : wrap(writing.delete([
12901
+ await (next.rows ? committed(writing.put(counterRow(app.ref, where, next))) : committed(writing.delete([
12880
12902
  app.ref,
12881
12903
  where,
12882
12904
  COUNT_KEY
@@ -20800,8 +20822,9 @@ var Outbox = class {
20800
20822
  };
20801
20823
  this.now = options.now ?? Date.now;
20802
20824
  }
20803
- async recover() {
20804
- for (const message of await this.store.read()) {
20825
+ /** `messages`: the chat's history as the caller just read it (a start has), so it is not read a second time. */
20826
+ async recover(messages) {
20827
+ for (const message of messages ?? await this.store.read()) {
20805
20828
  if (message.via === "hold" || message.sender !== "me") continue;
20806
20829
  if (message.delivery === "queued") {
20807
20830
  await this.queue(message, message.deliveryError ?? "Not confirmed yet.");
@@ -20822,10 +20845,13 @@ var Outbox = class {
20822
20845
  }
20823
20846
  /**
20824
20847
  * One at a time, in the order asked: `run` starts when the turns before it are over. A turn that takes longer than
20825
- * `TURN_MS` no longer holds the next one back.
20848
+ * `TURN_MS` no longer holds the next one back. Its `TURN_MS` counts from when it begins, not from when it was
20849
+ * queued: counted from the queueing, every turn queued behind a slow one was past its time when its turn came, and
20850
+ * they all started at once (45 whole-chat reads together after a link drop, the heap past 1 GB: agents#1693).
20826
20851
  */
20827
20852
  turn(run) {
20828
- const result = this.line.then(async () => {
20853
+ const before = this.line;
20854
+ const result = before.then(async () => {
20829
20855
  if (this.dropped) {
20830
20856
  this.dropped = false;
20831
20857
  await this.requeueUnconfirmed();
@@ -20833,13 +20859,13 @@ var Outbox = class {
20833
20859
  this.began = this.closed;
20834
20860
  return run();
20835
20861
  });
20836
- this.line = new Promise((next) => {
20862
+ this.line = before.then(() => new Promise((next) => {
20837
20863
  const timer = setTimeout(next, TURN_MS);
20838
20864
  result.then(() => {}, () => {}).then(() => {
20839
20865
  clearTimeout(timer);
20840
20866
  next();
20841
20867
  });
20842
- });
20868
+ }));
20843
20869
  return result;
20844
20870
  }
20845
20871
  /** The link has not closed since this turn began: what the turn sends goes on the link the turn looked at. */
@@ -21625,8 +21651,7 @@ var QuoteSweeps = class {
21625
21651
  let state = this.chats.get(chat);
21626
21652
  if (!state) this.chats.set(chat, state = {
21627
21653
  due: /* @__PURE__ */ new Map(),
21628
- at: -Infinity,
21629
- busy: false
21654
+ at: -Infinity
21630
21655
  });
21631
21656
  state.due.set(id, ref);
21632
21657
  this.next(chat);
@@ -21636,9 +21661,18 @@ var QuoteSweeps = class {
21636
21661
  clearTimeout(this.chats.get(chat)?.timer);
21637
21662
  this.chats.delete(chat);
21638
21663
  }
21639
- stop() {
21640
- for (const state of this.chats.values()) clearTimeout(state.timer);
21664
+ /**
21665
+ * The peer stops: what waits is swept now, after a sweep still running, not dropped. Nothing would look again at the
21666
+ * next start, so the replies would keep the removed messages' lines for good.
21667
+ */
21668
+ async stop() {
21669
+ const chats = [...this.chats];
21641
21670
  this.chats.clear();
21671
+ await Promise.allSettled(chats.map(async ([chat, state]) => {
21672
+ clearTimeout(state.timer);
21673
+ await state.busy;
21674
+ if (state.due.size) await this.sweep(chat, state.due);
21675
+ }));
21642
21676
  }
21643
21677
  next(chat) {
21644
21678
  const state = this.chats.get(chat);
@@ -21653,10 +21687,9 @@ var QuoteSweeps = class {
21653
21687
  }
21654
21688
  const removed = state.due;
21655
21689
  state.due = /* @__PURE__ */ new Map();
21656
- state.busy = true;
21657
21690
  state.at = this.now();
21658
- this.sweep(chat, removed).catch(() => {}).finally(() => {
21659
- state.busy = false;
21691
+ state.busy = this.sweep(chat, removed).catch(() => {}).finally(() => {
21692
+ state.busy = void 0;
21660
21693
  if (this.chats.get(chat) === state) this.next(chat);
21661
21694
  });
21662
21695
  }
@@ -22217,8 +22250,8 @@ var db = {
22217
22250
  });
22218
22251
  },
22219
22252
  async deleteLink(linkId) {
22220
- await wrap((await store(STORES$1.links, "readwrite")).delete(linkId));
22221
- await wrap((await store(STORES$1.messages, "readwrite")).delete(IDBKeyRange.bound([linkId], [linkId, []])));
22253
+ await committed((await store(STORES$1.links, "readwrite")).delete(linkId));
22254
+ await committed((await store(STORES$1.messages, "readwrite")).delete(IDBKeyRange.bound([linkId], [linkId, []])));
22222
22255
  await fileStore.deleteForLink(linkId);
22223
22256
  await removeFileBytes(`${linkId}-in-`);
22224
22257
  await removeFileBytes(`${linkId}-out-`);
@@ -22314,7 +22347,7 @@ var db = {
22314
22347
  },
22315
22348
  /** Writes a message whether or not it is there: lines of history that change as what they tell changes. */
22316
22349
  async putMessage(message) {
22317
- await wrap((await store(STORES$1.messages, "readwrite")).put(message));
22350
+ await committed((await store(STORES$1.messages, "readwrite")).put(message));
22318
22351
  },
22319
22352
  async updateDelivery(linkId, id, delivery, deliveryError, extra) {
22320
22353
  const tx = (await openDb()).transaction(STORES$1.messages, "readwrite", delivery === "sent" || delivery === "delivered" ? RELAXED : void 0);
@@ -22391,34 +22424,34 @@ var db = {
22391
22424
  return results.filter((row) => !!row);
22392
22425
  },
22393
22426
  async deleteMessage(linkId, messageId) {
22394
- await wrap((await store(STORES$1.messages, "readwrite")).delete([linkId, messageId]));
22427
+ await committed((await store(STORES$1.messages, "readwrite")).delete([linkId, messageId]));
22395
22428
  },
22396
22429
  async getGroups() {
22397
22430
  return wrap((await store(STORES$1.groups, "readonly")).getAll());
22398
22431
  },
22399
22432
  async putGroup(group) {
22400
- await wrap((await store(STORES$1.groups, "readwrite")).put(group));
22433
+ await committed((await store(STORES$1.groups, "readwrite")).put(group));
22401
22434
  },
22402
22435
  /** The group and its history. */
22403
22436
  async deleteGroup(groupId) {
22404
- await wrap((await store(STORES$1.groups, "readwrite")).delete(groupId));
22437
+ await committed((await store(STORES$1.groups, "readwrite")).delete(groupId));
22405
22438
  const link = `group:${groupId}`;
22406
- await wrap((await store(STORES$1.messages, "readwrite")).delete(IDBKeyRange.bound([link], [link, []])));
22439
+ await committed((await store(STORES$1.messages, "readwrite")).delete(IDBKeyRange.bound([link], [link, []])));
22407
22440
  },
22408
22441
  async getServices() {
22409
22442
  return wrap((await store(STORES$1.services, "readonly")).getAll());
22410
22443
  },
22411
22444
  async putService(service) {
22412
- await wrap((await store(STORES$1.services, "readwrite")).put(service));
22445
+ await committed((await store(STORES$1.services, "readwrite")).put(service));
22413
22446
  },
22414
22447
  async deleteService(serviceId) {
22415
- await wrap((await store(STORES$1.services, "readwrite")).delete(serviceId));
22448
+ await committed((await store(STORES$1.services, "readwrite")).delete(serviceId));
22416
22449
  },
22417
22450
  async getSettings() {
22418
22451
  return await wrap((await store(STORES$1.settings, "readonly")).get("settings")) ?? {};
22419
22452
  },
22420
22453
  async putSettings(settings) {
22421
- await wrap((await store(STORES$1.settings, "readwrite")).put(settings, "settings"));
22454
+ await committed((await store(STORES$1.settings, "readwrite")).put(settings, "settings"));
22422
22455
  }
22423
22456
  };
22424
22457
  //#endregion
@@ -22684,10 +22717,11 @@ var Reactions = class {
22684
22717
  }
22685
22718
  /**
22686
22719
  * The row a received reaction names. Most often the row of that id (a group's), or of `peer_` or `me_` and that id (a
22687
- * chat's): those are read alone. Any other (a file's, a payment's, one not here yet) is looked for in the whole chat;
22688
- * in a group there is no other, since a row that takes a reaction goes by its own id there. A `received` one is looked
22689
- * for so at most once a `REACTION_LOOKUP_MS` per chat, since the contact can name ids that never were: one that comes
22690
- * meanwhile waits, and the next read finds what waited (`lookUpWaiting`).
22720
+ * chat's), else a row the host knows that id names (a file of mine, a payment): those are read alone. Any other (one
22721
+ * not here yet) is looked for in the whole chat; in a group there is no other, since a row that takes a reaction goes
22722
+ * by its own id there. A `received` one is looked for so at most once a `REACTION_LOOKUP_MS` per chat, since the
22723
+ * contact can name ids that never were: one that comes meanwhile waits, and the next read finds what waited
22724
+ * (`lookUpWaiting`).
22691
22725
  */
22692
22726
  async find(chat, id, received = false) {
22693
22727
  const group = isGroup$1(chat);
@@ -22697,6 +22731,10 @@ var Reactions = class {
22697
22731
  if (row && replyRef(row, group) === id) return row;
22698
22732
  }
22699
22733
  if (group) return void 0;
22734
+ for (const rowId of await this.host.rows?.(chat, id) ?? []) {
22735
+ const row = await this.host.message(chat, rowId);
22736
+ if (row && replyRef(row, false) === id) return row;
22737
+ }
22700
22738
  if (received && !this.lookupDue(chat)) return void 0;
22701
22739
  }
22702
22740
  return reactionTarget(await this.host.messages(chat), id, group);
@@ -23351,6 +23389,13 @@ var Communities = class {
23351
23389
  /** The latest message from another member, per group: what makes it unread in the list. */
23352
23390
  lastPeerMessageAt = /* @__PURE__ */ new Map();
23353
23391
  lastMentionAt = /* @__PURE__ */ new Map();
23392
+ /** The maps above, and what moved them last (`markCame`, `unmark`). */
23393
+ marks = {
23394
+ lastMessageAt: this.lastMessageAt,
23395
+ lastPeerMessageAt: this.lastPeerMessageAt,
23396
+ lastMentionAt: this.lastMentionAt,
23397
+ by: /* @__PURE__ */ new Map()
23398
+ };
23354
23399
  refused = /* @__PURE__ */ new Map();
23355
23400
  lastKnock = /* @__PURE__ */ new Map();
23356
23401
  /** Joiners: groups whose knock is out (published), and the knock record it is in. */
@@ -23431,14 +23476,9 @@ var Communities = class {
23431
23476
  for (const group of groups) {
23432
23477
  this.stored.set(group.id, group);
23433
23478
  if (group.community) this.attach(group.community);
23434
- const history = await this.store.getMessages(MESSAGE_LINK$1(group.id)), said = history.filter((m) => !m.event && !m.groupPay);
23435
- const last = said[said.length - 1], lastPeer = [...said].reverse().find((m) => m.sender !== "me");
23436
- if (last) this.lastMessageAt.set(group.id, last.timestamp);
23437
- const peerAt = cameOrWritten(lastPeer?.timestamp, lastPeer ? group.came?.peer : void 0);
23438
- if (peerAt) this.lastPeerMessageAt.set(group.id, peerAt);
23439
- const mention = [...history].reverse().find((m) => m.mentioned);
23440
- const mentionAt = cameOrWritten(mention?.timestamp, mention ? group.came?.mention : void 0);
23441
- if (mentionAt) this.lastMentionAt.set(group.id, mentionAt);
23479
+ const history = await this.store.getMessages(MESSAGE_LINK$1(group.id));
23480
+ loadMarks(this.marks, group, history);
23481
+ this.host.loaded?.(group.id, history);
23442
23482
  for (const [, linkId] of this.host.entries(group.id)) if (group.joining?.linkId !== linkId) await this.host.closeEdge(linkId);
23443
23483
  const live = this.live.get(group.id);
23444
23484
  if (live) for (const key of this.host.edges(group.id).keys()) live.restored.set(key, 0);
@@ -23448,6 +23488,15 @@ var Communities = class {
23448
23488
  record(groupId) {
23449
23489
  return this.stored.get(groupId);
23450
23490
  }
23491
+ /** What moved this group's marks last (`markCame`). */
23492
+ markedBy(groupId) {
23493
+ return this.marks.by.get(groupId);
23494
+ }
23495
+ /** A message deleted for everyone left this device: the marks it set go back (`unmark` in groups.ts). */
23496
+ async unmark(groupId, removed) {
23497
+ const group = this.stored.get(groupId);
23498
+ if (await unmark(this.marks, group, groupId, () => this.store.getMessages(MESSAGE_LINK$1(groupId)), removed) && group) await this.store.putGroup(group);
23499
+ }
23451
23500
  views() {
23452
23501
  return [...this.stored.values()].flatMap((group) => this.viewOf(group));
23453
23502
  }
@@ -23494,7 +23543,8 @@ var Communities = class {
23494
23543
  return !!id && this.host.linkReady(id, 2);
23495
23544
  };
23496
23545
  const hubs = freshHubs(this.hubs(live), this.now()).map((h) => h.key);
23497
- const former = Object.entries(s.state.nicks).filter(([key]) => !rosterHas(s.roster, key));
23546
+ const roster = s.roster, inRoster = new Set(roster.map(([key]) => key));
23547
+ const former = Object.entries(s.state.nicks).filter(([key]) => !inRoster.has(key));
23498
23548
  return [{
23499
23549
  ...base,
23500
23550
  name: s.name,
@@ -23516,7 +23566,7 @@ var Communities = class {
23516
23566
  hubs: hubs.length,
23517
23567
  connected: [...edges.keys()].filter(ready).length
23518
23568
  },
23519
- members: s.roster.map(([key, role]) => ({
23569
+ members: roster.map(([key, role]) => ({
23520
23570
  key,
23521
23571
  role,
23522
23572
  me: key === s.myKey,
@@ -23707,7 +23757,8 @@ var Communities = class {
23707
23757
  await this.forget(groupId);
23708
23758
  return;
23709
23759
  }
23710
- const edges = [...this.host.edges(groupId).entries()].filter(([, id]) => this.host.linkReady(id, 2));
23760
+ const others = new Set(s.others);
23761
+ const edges = [...this.host.edges(groupId).entries()].filter(([key, id]) => others.has(key) && this.host.linkReady(id, 2));
23711
23762
  if (!edges.length) throw new Error("Nobody in the group is connected right now to take your leave. Try again in a moment.");
23712
23763
  let next;
23713
23764
  if (s.isAdmin) {
@@ -23799,9 +23850,7 @@ var Communities = class {
23799
23850
  if (live?.hub) await this.publishBeacon(groupId, live, this.now(), false).catch(() => {});
23800
23851
  this.live.delete(groupId);
23801
23852
  this.stored.delete(groupId);
23802
- this.lastMessageAt.delete(groupId);
23803
- this.lastPeerMessageAt.delete(groupId);
23804
- this.lastMentionAt.delete(groupId);
23853
+ dropMarks(this.marks, groupId);
23805
23854
  this.knockingWith.delete(groupId);
23806
23855
  this.knockRead.delete(groupId);
23807
23856
  this.lineOrder.forget(MESSAGE_LINK$1(groupId));
@@ -23828,9 +23877,11 @@ var Communities = class {
23828
23877
  for (const group of [...this.stored.values()]) {
23829
23878
  const live = this.live.get(group.id);
23830
23879
  if (group.joining && (this.knocking(group, live) || group.joining.check)) {
23831
- const waited = now - group.joining.since, every = waited > this.timings.patienceMs ? this.timings.slowKnockMs : this.timings.knockMs;
23832
- if (!this.knocking(group, live) && waited > CHECK_MS) await this.endCheck(group);
23833
- else if (!this.host.linkReady(group.joining.linkId, 2) && !this.host.linkSeen?.(group.joining.linkId) && now - (this.lastKnock.get(group.id) ?? 0) >= (this.knocked.has(group.id) ? every : Math.min(every, 3e3))) await this.knock(group, now).catch(() => {});
23880
+ const knocking = this.knocking(group, live), waited = now - group.joining.since;
23881
+ const answered = this.host.linkReady(group.joining.linkId, 2) || !!this.host.linkSeen?.(group.joining.linkId);
23882
+ const every = joinKnockWait(waited, this.timings, countWaitingJoin(this.host, group.id, now, knocking && !answered && waited > this.timings.patienceMs));
23883
+ if (!knocking && waited > CHECK_MS) await this.endCheck(group);
23884
+ else if (!answered && now - (this.lastKnock.get(group.id) ?? 0) >= (this.knocked.has(group.id) ? every : Math.min(every, 3e3))) await this.knock(group, now).catch(() => {});
23834
23885
  if (!live) continue;
23835
23886
  }
23836
23887
  if (!live) continue;
@@ -24930,7 +24981,7 @@ var Communities = class {
24930
24981
  message: async (m) => {
24931
24982
  const timestamp = m.timestamp;
24932
24983
  const mentioned = m.sender !== session.myKey && mentionsMember(m.mentions, session.myKey);
24933
- const file = m.file && this.files ? await this.files.announced(id, {
24984
+ const file = m.file && this.files && !this.stored.get(id)?.removedIds?.includes(m.id) ? await this.files.announced(id, {
24934
24985
  id: m.id,
24935
24986
  sender: m.sender,
24936
24987
  ts: m.timestamp,
@@ -24956,10 +25007,9 @@ var Communities = class {
24956
25007
  ...file && { file }
24957
25008
  });
24958
25009
  placing(stored !== false);
25010
+ if (stored === false && this.stored.get(id)?.removedIds?.includes(m.id)) return;
24959
25011
  const came = m.sender === session.myKey ? timestamp : cameAt(timestamp, stored, arrivalNow(this.now()));
24960
- this.lastMessageAt.set(id, Math.max(this.lastMessageAt.get(id) ?? 0, came));
24961
- if (mentioned) this.lastMentionAt.set(id, Math.max(this.lastMentionAt.get(id) ?? 0, came));
24962
- if (m.sender !== session.myKey) this.lastPeerMessageAt.set(id, Math.max(this.lastPeerMessageAt.get(id) ?? 0, came));
25012
+ markCame(this.marks, id, m.id, came, m.sender !== session.myKey, mentioned);
24963
25013
  noteCame(this.stored.get(id), came, m.sender !== session.myKey, mentioned);
24964
25014
  },
24965
25015
  app: (m) => this.deliver(id, () => m.frame.t === "group-have" ? this.files?.communityApp(id, m.sender, m.frame) : this.host.communityApp?.(id, m.sender, m.frame)),
@@ -24980,6 +25030,7 @@ var Communities = class {
24980
25030
  seqFloor: () => this.host.seqFloor?.() ?? 0,
24981
25031
  adminWork: () => this.host.adminWork?.(id) ?? true,
24982
25032
  adminTurn: () => this.host.adminTurn?.(id) ?? Promise.resolve(true),
25033
+ removed: (messageId) => !!this.stored.get(id)?.removedIds?.includes(messageId),
24983
25034
  relay: (frame) => {
24984
25035
  if (this.live.get(id)?.hub) for (const [, linkId] of this.hearers(id, frame)) this.sendTo(linkId, frame);
24985
25036
  },
@@ -25118,6 +25169,19 @@ var GONE_LINGER_MS = 15e3;
25118
25169
  */
25119
25170
  var HUB_CLOCK_READ_GAP_MS = 75e3;
25120
25171
  /**
25172
+ * A member steps up as a hub only while the beacon lists fewer fresh hubs than `maxHubs` less this. At `maxHubs` less
25173
+ * one, one entry crossing its freshness (a hub whose write the budget held a while) brought a member back up, which
25174
+ * pushed another out, and so on: 14-20 hubs of 20 members for minutes (agents#1691).
25175
+ */
25176
+ var STEP_UP_MARGIN = 2;
25177
+ /**
25178
+ * Too few hubs: a member steps up after a delay of its own, under this (the same for its key and epoch), and only on a
25179
+ * reading made after it. Every member read the same short beacon in the same minute and stepped up together.
25180
+ */
25181
+ var STEP_UP_DELAY_MS = 6e4;
25182
+ /** The longest a write of my entry waits for the budget it was told of: within an entry's freshness (90 s). */
25183
+ var PUBLISH_WAIT_MAX_MS = 3e4;
25184
+ /**
25121
25185
  * The hubs of the private groups this device is in (WISP 902 · Group Mesh § Hubs): whether a group runs on hubs, who
25122
25186
  * they are (the community's sealed beacon and lobbies, under the epoch's rendezvous secret), whether I am one, which
25123
25187
  * edges that asks for, and passing frames on as a hub. `Groups` owns the sessions and the edges; this decides.
@@ -25163,6 +25227,9 @@ var MeshHubs = class {
25163
25227
  lastRead: 0,
25164
25228
  lastWrite: 0,
25165
25229
  lastTry: 0,
25230
+ publishAfter: 0,
25231
+ readAt: 0,
25232
+ stepUpAt: 0,
25166
25233
  hub: false,
25167
25234
  hubSince: 0,
25168
25235
  members: /* @__PURE__ */ new Map(),
@@ -25361,6 +25428,9 @@ var MeshHubs = class {
25361
25428
  live.lastTry = 0;
25362
25429
  live.beacon = [];
25363
25430
  live.epochRead = false;
25431
+ live.publishAfter = 0;
25432
+ live.stepUpAt = 0;
25433
+ live.readAt = 0;
25364
25434
  live.clocks.restart();
25365
25435
  }
25366
25436
  const policy = session.hubPolicy, me = session.myKey, inRoster = (key) => rosterHas(session.roster, key);
@@ -25370,7 +25440,11 @@ var MeshHubs = class {
25370
25440
  const others = this.listed(live, session, now);
25371
25441
  const fits = this.fits(groupId, session);
25372
25442
  if (live.hub) live.need = session.others.length;
25373
- if (!live.hub && may && fits && (policy.pin.includes(me) || live.epochRead && others.length < MESH_HUBS.maxHubs)) {
25443
+ const counted = this.counted(live, session, now), short = live.epochRead && counted < MESH_HUBS.maxHubs - STEP_UP_MARGIN;
25444
+ const needed = counted < MESH_HUBS.hubsPerMember;
25445
+ if (!short || live.hub) live.stepUpAt = 0;
25446
+ else if (!live.stepUpAt) live.stepUpAt = needed ? now : now + stepUpDelay(me, session.epoch);
25447
+ if (!live.hub && may && fits && (policy.pin.includes(me) || short && now >= live.stepUpAt && (needed || live.readAt >= live.stepUpAt))) {
25374
25448
  live.hub = true;
25375
25449
  live.hubSince = now;
25376
25450
  live.myHubs = [];
@@ -25380,7 +25454,7 @@ var MeshHubs = class {
25380
25454
  live.hub = false;
25381
25455
  live.members.clear();
25382
25456
  if (!may || !fits) await this.publish(groupId, session, live, now, false).catch(() => {});
25383
- } else if (live.hub && now - live.lastTry >= 5e3 && (now - live.lastWrite >= this.timings.beaconEveryMs || !live.beacon.some((h) => h.key === me))) await this.publish(groupId, session, live, now, true).catch(() => {});
25457
+ } else if (live.hub && now - live.lastTry >= 5e3 && now >= live.publishAfter && (now - live.lastWrite >= this.timings.beaconEveryMs || !live.beacon.some((h) => h.key === me))) await this.publish(groupId, session, live, now, true).catch(() => {});
25384
25458
  if (live.hub) {
25385
25459
  await this.serve(groupId, session, live, now, rv);
25386
25460
  const hubs = others.map((h) => h.key).sort();
@@ -25397,7 +25471,18 @@ var MeshHubs = class {
25397
25471
  * pinned hub lists itself whatever the beacon holds.
25398
25472
  */
25399
25473
  full(live, session, now) {
25400
- return live.epochRead && !session.hubPolicy.pin.includes(session.myKey) && !live.beacon.some((h) => h.key === session.myKey) && this.listed(live, session, now).length >= MESH_HUBS.maxHubs;
25474
+ return live.epochRead && !session.hubPolicy.pin.includes(session.myKey) && !live.beacon.some((h) => h.key === session.myKey) && this.counted(live, session, now) >= MESH_HUBS.maxHubs;
25475
+ }
25476
+ /**
25477
+ * The other hubs there are, as far as stepping up or down goes: the beacon's fresh ones and those a reading showed
25478
+ * fresh within `graceMs`. A hub whose republish the relays' budget held back past the entry's 90 s is still a hub:
25479
+ * counted on fresh entries alone, every such entry brought a member up, and none ever saw enough to step down
25480
+ * (agents#1691: 14-20 hubs of 20 members, beacon writes refused 290 times of 339).
25481
+ */
25482
+ counted(live, session, now) {
25483
+ const keys = new Set(this.listed(live, session, now).map((h) => h.key));
25484
+ for (const [key, at] of live.seenHubs) if (now - at <= this.timings.graceMs && key !== session.myKey && rosterHas(session.roster, key) && !live.departed.has(key)) keys.add(key);
25485
+ return keys.size;
25401
25486
  }
25402
25487
  shape(live) {
25403
25488
  return `${live.hub}|${live.myHubs.join(",")}|${[...live.members.keys()].sort().join(",")}|${live.beacon.map((h) => h.key).sort().join(",")}`;
@@ -25411,11 +25496,18 @@ var MeshHubs = class {
25411
25496
  } catch {
25412
25497
  return;
25413
25498
  }
25499
+ if (this.held(keys.identity.pubKeyZ32)) return;
25414
25500
  live.beacon = live.clocks.inMyTime(readBeacon(keys, records ?? []), now);
25415
25501
  live.firstRead = true;
25416
25502
  live.epochRead = true;
25503
+ live.readAt = now;
25417
25504
  this.noteHubs(live, session, now);
25418
25505
  }
25506
+ /** How long the relays' budget holds the read of this key back: the read that just ended answered no relay's packet. */
25507
+ held(pubKeyZ32) {
25508
+ const wait = this.host.readHeldBackFor?.(pubKeyZ32);
25509
+ return wait !== void 0 && wait > 0 ? wait : void 0;
25510
+ }
25419
25511
  noteHubs(live, session, now) {
25420
25512
  for (const h of this.listed(live, session, now)) live.seenHubs.set(h.key, now);
25421
25513
  for (const [key, at] of live.seenHubs) if (now - at > this.timings.graceMs || !rosterHas(session.roster, key)) live.seenHubs.delete(key);
@@ -25432,10 +25524,17 @@ var MeshHubs = class {
25432
25524
  let records;
25433
25525
  try {
25434
25526
  records = await this.host.resolve(keys.identity.pubKeyZ32, true);
25435
- } catch {
25527
+ } catch (error) {
25528
+ this.holdPublish(live, now, error);
25529
+ return;
25530
+ }
25531
+ const wait = this.held(keys.identity.pubKeyZ32);
25532
+ if (wait !== void 0) {
25533
+ live.publishAfter = now + wait;
25436
25534
  return;
25437
25535
  }
25438
25536
  existing = live.clocks.inMyTime(readBeacon(keys, records ?? []), now);
25537
+ live.readAt = now;
25439
25538
  if (listed) {
25440
25539
  live.beacon = existing;
25441
25540
  live.lastRead = now;
@@ -25452,14 +25551,27 @@ var MeshHubs = class {
25452
25551
  load: live.members.size,
25453
25552
  since: live.hubSince || now
25454
25553
  } : null, now, (key) => rosterHas(session.roster, key) && !policy.no.includes(key));
25455
- await this.host.publish(keys.identity, beaconRecords(keys, live.clocks.asWritten(hubs)), true);
25554
+ try {
25555
+ await this.host.publish(keys.identity, beaconRecords(keys, live.clocks.asWritten(hubs)), true);
25556
+ } catch (error) {
25557
+ this.holdPublish(live, now, error);
25558
+ throw error;
25559
+ }
25456
25560
  live.beacon = hubs;
25457
25561
  live.lastWrite = now;
25458
25562
  live.lastRead = now;
25563
+ live.readAt = now;
25459
25564
  live.firstRead = true;
25460
25565
  live.epochRead = true;
25461
25566
  this.noteHubs(live, session, now);
25462
25567
  }
25568
+ /**
25569
+ * A write of my entry (or the read before it) the relays' budget held back: not tried again every 5 s (each try a
25570
+ * read, held 290 times of 339 on 20 apps: agents#1691), but once the budget says it frees a request.
25571
+ */
25572
+ holdPublish(live, now, error) {
25573
+ if (isDiscoveryBudgetError(error)) live.publishAfter = now + Math.min(Math.max(error.retryInMs, 5e3), PUBLISH_WAIT_MAX_MS);
25574
+ }
25463
25575
  /** As a hub: who asked in my lobby, and which of my members are still around. */
25464
25576
  async serve(groupId, session, live, now, rv) {
25465
25577
  const edges = this.host.edges(groupId);
@@ -25694,6 +25806,12 @@ function authorOf(frame) {
25694
25806
  default: return;
25695
25807
  }
25696
25808
  }
25809
+ /** A member's own delay before it steps up (`STEP_UP_DELAY_MS`): from its key and the epoch, so members spread out. */
25810
+ function stepUpDelay(key, epoch) {
25811
+ let hash = epoch | 0;
25812
+ for (let i = 0; i < key.length; i++) hash = Math.imul(hash, 31) + key.charCodeAt(i) | 0;
25813
+ return (hash >>> 0) % STEP_UP_DELAY_MS;
25814
+ }
25697
25815
  //#endregion
25698
25816
  //#region ../browser/src/engine/groupTyping.ts
25699
25817
  /**
@@ -26074,11 +26192,111 @@ function noteCame(group, came, peer, mentioned) {
26074
26192
  }
26075
26193
  /** What `load` starts the unread marks from: the history's own times, or when its latest came if that was later. */
26076
26194
  var cameOrWritten = (written, came) => written === void 0 && came === void 0 ? void 0 : Math.max(written ?? 0, came ?? 0);
26195
+ /** Every key that was a member of the group at some epoch of its chain. */
26196
+ function everMembers(session) {
26197
+ const keys = /* @__PURE__ */ new Set();
26198
+ for (const commit of session.state.chain) if (commit) for (const [key] of commit.m) keys.add(key);
26199
+ return keys;
26200
+ }
26077
26201
  /** The view's `lastPeerMessageAt`, when there is one. */
26078
26202
  var peerMessageAt = (map, groupId) => {
26079
26203
  const at = map.get(groupId);
26080
26204
  return at ? { lastPeerMessageAt: at } : {};
26081
26205
  };
26206
+ /**
26207
+ * A message came at `came`: the marks move to it (never back), and it is noted as the one that moved them (`unmark`
26208
+ * reads the history again only for one of those).
26209
+ */
26210
+ function markCame(marks, groupId, id, came, peer, mentioned) {
26211
+ const by = { ...marks.by.get(groupId) };
26212
+ const move = (map) => {
26213
+ if (came < (map.get(groupId) ?? 0)) return false;
26214
+ map.set(groupId, came);
26215
+ return true;
26216
+ };
26217
+ if (move(marks.lastMessageAt)) by.last = id;
26218
+ if (mentioned && move(marks.lastMentionAt)) by.mention = id;
26219
+ if (peer && move(marks.lastPeerMessageAt)) by.peer = id;
26220
+ marks.by.set(groupId, by);
26221
+ }
26222
+ /** What `load` reads a group's marks from: the newest rows (`newestMarked`), and when its latest came if later (`came`). */
26223
+ function loadMarks(marks, group, history) {
26224
+ const { last, peer, mention } = newestMarked(history);
26225
+ if (last) marks.lastMessageAt.set(group.id, last.timestamp);
26226
+ const peerAt = cameOrWritten(peer?.timestamp, peer ? group.came?.peer : void 0);
26227
+ if (peerAt) marks.lastPeerMessageAt.set(group.id, peerAt);
26228
+ const mentionAt = cameOrWritten(mention?.timestamp, mention ? group.came?.mention : void 0);
26229
+ if (mentionAt) marks.lastMentionAt.set(group.id, mentionAt);
26230
+ marks.by.set(group.id, {
26231
+ last: last?.id,
26232
+ peer: peer?.id,
26233
+ mention: mention?.id
26234
+ });
26235
+ }
26236
+ /** A group gone from this engine: its marks too. */
26237
+ function dropMarks(marks, groupId) {
26238
+ marks.lastMessageAt.delete(groupId);
26239
+ marks.lastPeerMessageAt.delete(groupId);
26240
+ marks.lastMentionAt.delete(groupId);
26241
+ marks.by.delete(groupId);
26242
+ }
26243
+ /** The newest rows `load` reads the marks from: a group's last message, last of a member's, last mentioning me. */
26244
+ function newestMarked(history) {
26245
+ const said = history.filter((m) => !m.event && !m.groupPay);
26246
+ return {
26247
+ last: said[said.length - 1],
26248
+ peer: [...said].reverse().find((m) => m.sender !== "me"),
26249
+ mention: [...history].reverse().find((m) => m.mentioned)
26250
+ };
26251
+ }
26252
+ /**
26253
+ * A message deleted for everyone (WISP 400 § Delete for everyone: a tombstone does not count as unread or move the
26254
+ * chat): the marks it moved go back to the newest line still kept, as `load` reads them, and the record's `came` it
26255
+ * raised goes too. A mark a newer line moved stays, and the history is read only when the message moved one
26256
+ * (`markedBy`): removals go at the pace of edits. `history`: the group's rows, with it gone. True when `came` changed
26257
+ * (the record is to be saved).
26258
+ */
26259
+ async function unmark(marks, group, groupId, history, removed) {
26260
+ const by = marks.by.get(groupId);
26261
+ if (!by || ![
26262
+ by.last,
26263
+ by.peer,
26264
+ by.mention
26265
+ ].includes(removed.id)) return false;
26266
+ const newest = newestMarked((await history()).filter((m) => m.id !== removed.id));
26267
+ const back = (map, row) => {
26268
+ if (row) map.set(groupId, row.timestamp);
26269
+ else map.delete(groupId);
26270
+ };
26271
+ let came = false;
26272
+ if (by.last === removed.id) back(marks.lastMessageAt, newest.last);
26273
+ if (by.peer === removed.id) {
26274
+ back(marks.lastPeerMessageAt, newest.peer);
26275
+ if (group?.came?.peer !== void 0) {
26276
+ group.came = {
26277
+ ...group.came,
26278
+ peer: void 0
26279
+ };
26280
+ came = true;
26281
+ }
26282
+ }
26283
+ if (by.mention === removed.id) {
26284
+ back(marks.lastMentionAt, newest.mention);
26285
+ if (group?.came?.mention !== void 0) {
26286
+ group.came = {
26287
+ ...group.came,
26288
+ mention: void 0
26289
+ };
26290
+ came = true;
26291
+ }
26292
+ }
26293
+ marks.by.set(groupId, {
26294
+ last: by.last === removed.id ? newest.last?.id : by.last,
26295
+ peer: by.peer === removed.id ? newest.peer?.id : by.peer,
26296
+ mention: by.mention === removed.id ? newest.mention?.id : by.mention
26297
+ });
26298
+ return came;
26299
+ }
26082
26300
  var ENTRY_TIMINGS = {
26083
26301
  pollMs: 5e3,
26084
26302
  warmPollMs: 2e3,
@@ -26087,6 +26305,32 @@ var ENTRY_TIMINGS = {
26087
26305
  slowKnockMs: 2e4,
26088
26306
  patienceMs: 12e4
26089
26307
  };
26308
+ /**
26309
+ * A link join nobody answers (the link replaced or turned off, the group deleted, its admin's app gone) knocks less
26310
+ * often the longer it waits, once past `patienceMs`: a fifth of the wait between knocks, up to this, but no longer than
26311
+ * the joins waiting need (`JOIN_KNOCKS_PER_MINUTE`), and never sooner than `slowKnockMs`. Under `KNOCK_TTL_MS`, so an
26312
+ * admin's app that comes back still finds the knock fresh. Every `slowKnockMs` for good, four such links took 27 of the
26313
+ * app's 30 relay requests a minute, 20 minutes on (bug hunt 1019-0904, 2026-10-20).
26314
+ */
26315
+ var JOIN_KNOCK_WAIT_MAX_MS = 15e4;
26316
+ /** A join counted as waiting (`countWaitingJoin`) and not counted again this long is gone (joined, given up, forgotten). */
26317
+ var WAITING_JOIN_SEEN_MS = 1e4;
26318
+ var waitingJoins = /* @__PURE__ */ new WeakMap();
26319
+ /** Counts the link join of `groupId` among the waiting ones of `host`'s app while `waiting`, or no longer: how many there are. */
26320
+ function countWaitingJoin(host, groupId, now, waiting) {
26321
+ let joins = waitingJoins.get(host);
26322
+ if (!joins) waitingJoins.set(host, joins = /* @__PURE__ */ new Map());
26323
+ if (waiting) joins.set(groupId, now);
26324
+ else joins.delete(groupId);
26325
+ for (const [id, at] of joins) if (now - at > WAITING_JOIN_SEEN_MS) joins.delete(id);
26326
+ return joins.size;
26327
+ }
26328
+ /** The wait between a joiner's knocks, `waited` after it opened the link, one of `joins` waiting (`JOIN_KNOCK_WAIT_MAX_MS`). */
26329
+ function joinKnockWait(waited, timings, joins) {
26330
+ if (waited <= timings.patienceMs) return timings.knockMs;
26331
+ const share = Math.round(joins * 6e4 / 2);
26332
+ return Math.max(timings.slowKnockMs, Math.min(JOIN_KNOCK_WAIT_MAX_MS, Math.round(waited / 5), share));
26333
+ }
26090
26334
  var KNOCK_VERIFY_SPREAD_MS = 700;
26091
26335
  /** Entry sessions the admin runs at once; a joiner who does not finish in time is not answered again for a while. */
26092
26336
  var MAX_PENDING_ENTRIES = 4;
@@ -26141,17 +26385,6 @@ function invitationClaims(frame) {
26141
26385
  var FAREWELL_ANSWERS = 3;
26142
26386
  /** Commits sent to a removed member that was behind when it left, at most. */
26143
26387
  var FAREWELL_COMMITS = 64;
26144
- /**
26145
- * A member whose messages were just asked of another (`Groups.askOf`) is told where I am only once that one's answer
26146
- * has come: no message of it for this long, or `MESH_SYNC_HOLD_MAX_MS` after it was asked. Told at once, its own
26147
- * answer raced the other's, which holds the same messages among everyone's in the order they were written, and a
26148
- * member back in a group of five read each member's lines apart, the newest above older ones (WISP 902 § Catch-up).
26149
- * A message of the answer is one written before the asking: what the member writes meanwhile is no reason to wait, so
26150
- * the longest wait only has to cover a whole answer (the 256 messages a member keeps for the others and its own last
26151
- * 32) at the pace of a phone with a long history, 600 ms a frame. At ten seconds, an answer of 200 messages at four a
26152
- * second was cut at the 40th, and the others' newest lines landed above what was still coming.
26153
- */
26154
- var MESH_SYNC_HOLD_MS = 1500;
26155
26388
  /** Where a member's gossip turns start among the members it is connected to: a number of its own, from its key. */
26156
26389
  var gossipStart = (key) => {
26157
26390
  let n = 0;
@@ -26223,6 +26456,13 @@ var Groups = class {
26223
26456
  lastPeerMessageAt = /* @__PURE__ */ new Map();
26224
26457
  /** The latest message that names me, per group (the chat list's "@" while it is unread). */
26225
26458
  lastMentionAt = /* @__PURE__ */ new Map();
26459
+ /** The maps above, and what moved them last (`markCame`, `unmark`). */
26460
+ marks = {
26461
+ lastMessageAt: this.lastMessageAt,
26462
+ lastPeerMessageAt: this.lastPeerMessageAt,
26463
+ lastMentionAt: this.lastMentionAt,
26464
+ by: /* @__PURE__ */ new Map()
26465
+ };
26226
26466
  reconciling = Promise.resolve();
26227
26467
  /** Admin side: joiners with an entry session open, per group: member key → since when. */
26228
26468
  pendingEntries = /* @__PURE__ */ new Map();
@@ -26381,7 +26621,7 @@ var Groups = class {
26381
26621
  await this.communities.load(all.filter((g) => g.community || g.joining));
26382
26622
  for (const group of all.filter((g) => !g.community && !g.joining)) {
26383
26623
  this.stored.set(group.id, group);
26384
- const history = await this.store.getMessages(MESSAGE_LINK(group.id)), said = history.filter((m) => !m.event && !m.groupPay);
26624
+ const history = await this.store.getMessages(MESSAGE_LINK(group.id));
26385
26625
  const framed = history.filter((m) => m.frame);
26386
26626
  this.framesKept.set(group.id, framed.map((m) => ({
26387
26627
  id: m.id,
@@ -26389,13 +26629,8 @@ var Groups = class {
26389
26629
  })));
26390
26630
  if (group.state) this.attach(group.state, framed.map((m) => m.frame));
26391
26631
  if (group.invited) this.invited.set(group.id, new Set(Object.keys(group.invited)));
26392
- const last = said[said.length - 1], lastPeer = [...said].reverse().find((m) => m.sender !== "me");
26393
- if (last) this.lastMessageAt.set(group.id, last.timestamp);
26394
- const peerAt = cameOrWritten(lastPeer?.timestamp, lastPeer ? group.came?.peer : void 0);
26395
- if (peerAt) this.lastPeerMessageAt.set(group.id, peerAt);
26396
- const mention = [...history].reverse().find((m) => m.mentioned);
26397
- const mentionAt = cameOrWritten(mention?.timestamp, mention ? group.came?.mention : void 0);
26398
- if (mentionAt) this.lastMentionAt.set(group.id, mentionAt);
26632
+ loadMarks(this.marks, group, history);
26633
+ this.host.loaded?.(group.id, history);
26399
26634
  }
26400
26635
  for (const id of this.sessions.keys()) this.reconcileEdges(id);
26401
26636
  await this.files?.load(all.map((g) => g.id));
@@ -26437,7 +26672,12 @@ var Groups = class {
26437
26672
  return view && this.pinned(view);
26438
26673
  }
26439
26674
  pinned(view) {
26440
- const pin = pinView(this.record(view.id)?.pin);
26675
+ const record = this.record(view.id), kept = record?.pin;
26676
+ const pin = pinView(!!kept?.id && !!record?.removedIds?.some((id) => id === kept.id || id === kept.messageId) ? {
26677
+ ...kept,
26678
+ id: "",
26679
+ messageId: void 0
26680
+ } : kept);
26441
26681
  return pin ? {
26442
26682
  ...view,
26443
26683
  pin
@@ -26913,9 +27153,7 @@ var Groups = class {
26913
27153
  this.pendingEntries.delete(groupId);
26914
27154
  this.welcomed.delete(groupId);
26915
27155
  this.lingering.delete(groupId);
26916
- this.lastMessageAt.delete(groupId);
26917
- this.lastPeerMessageAt.delete(groupId);
26918
- this.lastMentionAt.delete(groupId);
27156
+ dropMarks(this.marks, groupId);
26919
27157
  this.authorOrder.forget(groupId);
26920
27158
  this.lineOrder.forget(MESSAGE_LINK(groupId));
26921
27159
  await this.store.deleteGroup(groupId);
@@ -27054,8 +27292,23 @@ var Groups = class {
27054
27292
  group.removedIds = [...group.removedIds ?? [], messageId].slice(-500);
27055
27293
  await this.store.putGroup(group);
27056
27294
  }
27295
+ this.communities.session(groupId)?.forget(messageId);
27057
27296
  await this.files?.forget(groupId, messageId);
27058
27297
  }
27298
+ /**
27299
+ * A message deleted for everyone left this device (`removed`, the row as it was): the group's unread, "@" and place
27300
+ * in the list go back to what they were without it (`unmark`), after a restart too.
27301
+ */
27302
+ /** Whether this message moved one of the group's marks last (`unmark` has something to do for it). */
27303
+ movedMarks(groupId, messageId) {
27304
+ const by = (this.isCommunity(groupId) ? this.communities.markedBy(groupId) : this.marks.by.get(groupId)) ?? {};
27305
+ return by.last === messageId || by.peer === messageId || by.mention === messageId;
27306
+ }
27307
+ async unmark(groupId, removed) {
27308
+ if (this.isCommunity(groupId)) return this.communities.unmark(groupId, removed);
27309
+ const group = this.stored.get(groupId);
27310
+ if (await unmark(this.marks, group, groupId, () => this.store.getMessages(MESSAGE_LINK(groupId)), removed) && group) await this.store.putGroup(group);
27311
+ }
27059
27312
  /** The connection of an edge opened. One kept to tell a removed member closes a while after, whatever its app says or does not say. */
27060
27313
  edgeOpen(groupId, peerKey) {
27061
27314
  const group = this.stored.get(groupId), farewell = group?.farewells?.[peerKey];
@@ -27297,8 +27550,10 @@ var Groups = class {
27297
27550
  continue;
27298
27551
  }
27299
27552
  if (group.invitation?.entry && !group.state) {
27300
- const every = now - group.createdAt > this.timings.patienceMs ? this.timings.slowKnockMs : this.timings.knockMs;
27301
- if (!(this.host.linkReady(group.invitation.linkId) || !!this.host.linkSeen?.(group.invitation.linkId)) && (now - (this.lastKnock.get(group.id) ?? 0) >= every || now >= (this.knockCheckAt.get(group.id) ?? Infinity))) await this.knock(group, now).catch(() => {});
27553
+ const answered = this.host.linkReady(group.invitation.linkId) || !!this.host.linkSeen?.(group.invitation.linkId);
27554
+ const waited = now - group.createdAt, joins = countWaitingJoin(this.host, group.id, now, !answered && waited > this.timings.patienceMs);
27555
+ const every = joinKnockWait(waited, this.timings, joins);
27556
+ if (!answered && (now - (this.lastKnock.get(group.id) ?? 0) >= every || now >= (this.knockCheckAt.get(group.id) ?? Infinity))) await this.knock(group, now).catch(() => {});
27302
27557
  continue;
27303
27558
  }
27304
27559
  if (group.invitation?.seedB64 && !group.state) {
@@ -27546,7 +27801,7 @@ var Groups = class {
27546
27801
  }, now)));
27547
27802
  const rewrites = (this.knockRewrites.get(group.id) ?? 0) + 1;
27548
27803
  this.knockRewrites.set(group.id, rewrites);
27549
- if (rewrites <= 2) this.knockCheckAt.set(group.id, now + 800 + gossipStart(key) % KNOCK_VERIFY_SPREAD_MS);
27804
+ if (rewrites <= 2 && now - group.createdAt <= this.timings.patienceMs) this.knockCheckAt.set(group.id, now + 800 + gossipStart(key) % KNOCK_VERIFY_SPREAD_MS);
27550
27805
  traceJoin(group.id, "knock.published", { ms: Date.now() - started });
27551
27806
  if (!this.knocked.has(group.id)) {
27552
27807
  this.knocked.add(group.id);
@@ -27562,9 +27817,11 @@ var Groups = class {
27562
27817
  knocks: knocks.length
27563
27818
  });
27564
27819
  let pending = this.pendingEntries.get(group.id);
27820
+ let ever;
27565
27821
  for (const { key, ts } of knocks) {
27566
27822
  const again = this.unwelcomed(group, session, key);
27567
27823
  if (now - ts > 18e4 || rosterHas(session.roster, key) && !again || this.refused.has(key) || pending?.has(key) || key === entry.link.host) continue;
27824
+ if (!again && (ever ??= everMembers(session)).has(key)) continue;
27568
27825
  if (again && this.rewelcomedLately(group.id, key)) continue;
27569
27826
  const entryIds = new Set(this.host.entries(group.id).values());
27570
27827
  const contactsInvited = [...this.invited.get(group.id) ?? []].filter((id) => !entryIds.has(id)).length;
@@ -28178,12 +28435,16 @@ var Groups = class {
28178
28435
  }
28179
28436
  /**
28180
28437
  * Whether the answer of the member asked for someone's messages may still be coming: its edge up, asked under
28181
- * `MESH_SYNC_HOLD_MAX_MS` ago, and a message of its answer (or the asking) under `MESH_SYNC_HOLD_MS` ago.
28438
+ * `MESH_SYNC_HOLD_MAX_MS` ago, and a message of its answer (or the asking) under `MESH_SYNC_HOLD_MS` ago; or, however
28439
+ * long ago, frames of its edge still waiting to be handled here. An app that handles a frame a second was still on the
28440
+ * others' syncs ahead of that answer 1.5 s after the ask, and on its 200 messages three minutes after: the next member
28441
+ * was asked for the same messages, and both handed them on.
28182
28442
  */
28183
28443
  answering(groupId, { via, at }, now) {
28184
28444
  const edge = this.host.edges(groupId).get(via);
28185
- if (!edge || !this.host.linkReady(edge) || now - at >= 18e4) return false;
28186
- return now - Math.max(at, this.lastHanded.get(groupId)?.get(via) ?? 0) < MESH_SYNC_HOLD_MS;
28445
+ if (!edge || !this.host.linkReady(edge)) return false;
28446
+ if ((this.host.linkWaiting?.(edge) ?? 0) > 0) return true;
28447
+ return now - at < 18e4 && now - Math.max(at, this.lastHanded.get(groupId)?.get(via) ?? 0) < 1500;
28187
28448
  }
28188
28449
  /**
28189
28450
  * Whether the sync to a member whose edge just opened waits (`heldSyncs` sends it): its messages were asked of
@@ -28508,6 +28769,7 @@ var Groups = class {
28508
28769
  seqFloor: () => this.host.seqFloor?.() ?? 0,
28509
28770
  adminWork: () => this.host.adminWork?.(state.id) ?? true,
28510
28771
  adminTurn: () => this.host.adminTurn?.(state.id) ?? Promise.resolve(true),
28772
+ removed: (id) => this.isRemoved(state.id, id),
28511
28773
  save: async (next) => {
28512
28774
  const group = this.stored.get(state.id);
28513
28775
  if (!group || this.sessions.get(state.id) !== session) return;
@@ -28535,7 +28797,7 @@ var Groups = class {
28535
28797
  message: async (m) => {
28536
28798
  const timestamp = m.timestamp;
28537
28799
  const mentioned = m.sender !== session.myKey && mentionsMember(m.mentions, session.myKey);
28538
- const file = m.file && this.files ? await this.files.announced(state.id, {
28800
+ const file = m.file && this.files && !this.isRemoved(state.id, m.id) ? await this.files.announced(state.id, {
28539
28801
  id: m.id,
28540
28802
  sender: m.sender,
28541
28803
  ts: m.timestamp,
@@ -28578,10 +28840,12 @@ var Groups = class {
28578
28840
  ...row,
28579
28841
  at: this.now()
28580
28842
  }, placedAbove);
28843
+ if (stored === false && !completed && this.isRemoved(state.id, m.id)) {
28844
+ this.typings.messageFrom(state.id, m.sender);
28845
+ return;
28846
+ }
28581
28847
  const came = m.sender === session.myKey ? timestamp : cameAt(timestamp, stored, arrivalNow(this.now()));
28582
- this.lastMessageAt.set(state.id, Math.max(this.lastMessageAt.get(state.id) ?? 0, came));
28583
- if (mentioned) this.lastMentionAt.set(state.id, Math.max(this.lastMentionAt.get(state.id) ?? 0, came));
28584
- if (m.sender !== session.myKey) this.lastPeerMessageAt.set(state.id, Math.max(this.lastPeerMessageAt.get(state.id) ?? 0, came));
28848
+ markCame(this.marks, state.id, m.id, came, m.sender !== session.myKey, mentioned);
28585
28849
  noteCame(this.stored.get(state.id), came, m.sender !== session.myKey, mentioned);
28586
28850
  this.typings.messageFrom(state.id, m.sender);
28587
28851
  },
@@ -28592,10 +28856,10 @@ var Groups = class {
28592
28856
  edit: (e) => this.host.groupEdit?.(state.id, e),
28593
28857
  changed: () => {
28594
28858
  if (session.status === "removed" && this.hubs.isHub(state.id) && !this.removedAt.has(state.id)) this.removedAt.set(state.id, this.now());
28595
- this.membershipChanged(state.id);
28859
+ this.membershipChanged(state.id).catch(() => {});
28596
28860
  },
28597
28861
  metaChanged: (by, change, at) => {
28598
- this.metaChanged(state.id, session, by, change, at);
28862
+ this.metaChanged(state.id, session, by, change, at).catch(() => {});
28599
28863
  },
28600
28864
  ...this.host.linkHandled && { handled: (to) => {
28601
28865
  const edge = this.host.edges(state.id).get(to);
@@ -29131,6 +29395,8 @@ var GroupEdits = class {
29131
29395
  heard = /* @__PURE__ */ new Map();
29132
29396
  /** The connection `resend` last spoke on, per group and member: a new one hears my latest edits again. */
29133
29397
  resentOn = /* @__PURE__ */ new Map();
29398
+ /** The list of my edited messages a paced resend goes on with, and the edge it was read for (`resendNow`). */
29399
+ keptMine = /* @__PURE__ */ new Map();
29134
29400
  resendPace = /* @__PURE__ */ new Map();
29135
29401
  resendTimers = /* @__PURE__ */ new Map();
29136
29402
  resending = /* @__PURE__ */ new Map();
@@ -29431,23 +29697,30 @@ var GroupEdits = class {
29431
29697
  * A new connection hears my latest `GROUP_EDIT_RESEND` again whatever it heard: one may have come before its message
29432
29698
  * and been dropped. Called again while the edge is the same, it goes on from where it was.
29433
29699
  */
29434
- resend(groupId, to) {
29700
+ resend(groupId, to, paced = false) {
29435
29701
  const key = resendKey(groupId, to);
29436
- const run = (this.resending.get(key) ?? Promise.resolve()).then(() => this.resendNow(groupId, to));
29702
+ const run = (this.resending.get(key) ?? Promise.resolve()).then(() => this.resendNow(groupId, to, paced));
29437
29703
  const settled = run.catch(() => {}).finally(() => {
29438
29704
  if (this.resending.get(key) === settled) this.resending.delete(key);
29439
29705
  });
29440
29706
  this.resending.set(key, settled);
29441
29707
  return run;
29442
29708
  }
29443
- async resendNow(groupId, to) {
29709
+ /**
29710
+ * `paced`: the pace's timer goes on with the list of my edited messages read when the edge opened (`keptMine`), on
29711
+ * that same edge. Read again each window, 7 edges with 256 edits each to say read a history of 10,000 rows 112
29712
+ * times at a start, ~5.9 s of a CLI's engine, not 7 (agents#1679). Edits made meanwhile go live (`flush`).
29713
+ */
29714
+ async resendNow(groupId, to, paced = false) {
29444
29715
  const key = resendKey(groupId, to), chat = chatOf(groupId);
29445
29716
  clearTimeout(this.resendTimers.get(key));
29446
29717
  this.resendTimers.delete(key);
29447
29718
  const open = () => this.host.edge ? this.host.edge(groupId, to) : true;
29448
29719
  const edge = open(), membership = this.host.membership(groupId);
29720
+ const kept = this.keptMine.get(key);
29721
+ this.keptMine.delete(key);
29449
29722
  if (this.stopped || edge === void 0 || !membership || membership.community || !membership.members.has(to)) return;
29450
- const mine = (await (this.host.history ? this.host.history(chat) : this.host.messages(chat))).filter((m) => m.sender === "me" && m.edit && !m.edit.pending && canEditInGroup(m)).sort((a, b) => a.edit.at - b.edit.at || (a.id < b.id ? -1 : 1));
29723
+ const mine = paced && kept?.edge === edge ? kept.mine : (await (this.host.history ? this.host.history(chat) : this.host.messages(chat))).filter((m) => m.sender === "me" && m.edit && !m.edit.pending && canEditInGroup(m)).sort((a, b) => a.edit.at - b.edit.at || (a.id < b.id ? -1 : 1));
29451
29724
  const last = this.heard.get(key);
29452
29725
  const after = (m) => !last || m.edit.at > last.at || m.edit.at === last.at && m.id > last.id;
29453
29726
  const unheard = last ? mine.filter(after).length : Math.min(mine.length, 256);
@@ -29459,8 +29732,12 @@ var GroupEdits = class {
29459
29732
  for (const m of due) {
29460
29733
  if (this.stopped || open() !== edge) return;
29461
29734
  if (!pace.take()) {
29735
+ this.keptMine.set(key, {
29736
+ edge,
29737
+ mine
29738
+ });
29462
29739
  this.resendTimers.set(key, setTimeout(() => {
29463
- this.resend(groupId, to).catch(() => {});
29740
+ this.resend(groupId, to, true).catch(() => {});
29464
29741
  }, Math.max(50, pace.wait())));
29465
29742
  return;
29466
29743
  }
@@ -29482,6 +29759,7 @@ var GroupEdits = class {
29482
29759
  for (const key of [...this.heard.keys()]) if (of(key)) this.heard.delete(key);
29483
29760
  for (const key of [...this.resendPace.keys()]) if (of(key)) this.resendPace.delete(key);
29484
29761
  for (const key of [...this.resentOn.keys()]) if (of(key)) this.resentOn.delete(key);
29762
+ for (const key of [...this.keptMine.keys()]) if (of(key)) this.keptMine.delete(key);
29485
29763
  }
29486
29764
  forget(groupId) {
29487
29765
  clearTimeout(this.timers.get(groupId));
@@ -31858,6 +32136,8 @@ var SWAP_POLL_MS = 3e4;
31858
32136
  var SWAP_SLOW_POLL_MS = 6e5;
31859
32137
  /** How long a swap whose inputs were given back is still asked about, in case the mint made it after all. */
31860
32138
  var SWAP_WATCH_MS = 36e5;
32139
+ /** How many proofs of tokens refused as spent are remembered. */
32140
+ var SPENT_KEPT = 1e3;
31861
32141
  /** Cashu's library (174 KiB) loads with the wallet's first use of a mint or a token, not with the app's start. */
31862
32142
  var loadCashu = () => import("@cashu/cashu-ts");
31863
32143
  async function reviewedCashuFee(preview) {
@@ -31958,6 +32238,11 @@ var CashuWallet = class CashuWallet {
31958
32238
  failedFees = /* @__PURE__ */ new Map();
31959
32239
  /** Melt quotes that ended unpaid with proofs the mint read spent: ecash spent somewhere else, said as such. */
31960
32240
  spentAway = /* @__PURE__ */ new Set();
32241
+ /**
32242
+ * Proofs of tokens the mint read spent by something else (`mint secret`), the newest SPENT_KEPT: spent stays spent,
32243
+ * so the same token sent again, under any id or encoding, is refused without asking the mint again.
32244
+ */
32245
+ spentTokens = /* @__PURE__ */ new Set();
31961
32246
  /** Per melt quote shown to the person: the invoice, its amount and the fee reserve the mint quoted. Only these are paid. */
31962
32247
  shownQuotes = /* @__PURE__ */ new Map();
31963
32248
  /**
@@ -32127,7 +32412,7 @@ var CashuWallet = class CashuWallet {
32127
32412
  paymentId,
32128
32413
  ...paysItsOwnInvoices(mint) ? { held: true } : {}
32129
32414
  };
32130
- await wrap((await store(STORES$1.quotes, "readwrite")).put(quote));
32415
+ await committed((await store(STORES$1.quotes, "readwrite")).put(quote));
32131
32416
  this.pollQuotes();
32132
32417
  return quote;
32133
32418
  }
@@ -32140,7 +32425,7 @@ var CashuWallet = class CashuWallet {
32140
32425
  const wanted = invoice.trim().toLowerCase();
32141
32426
  const quote = (await wrap((await store(STORES$1.quotes, "readonly")).getAll())).find((q) => q.invoice.toLowerCase() === wanted);
32142
32427
  if (!quote) return false;
32143
- if (quote.held) await wrap((await store(STORES$1.quotes, "readwrite")).put({
32428
+ if (quote.held) await committed((await store(STORES$1.quotes, "readwrite")).put({
32144
32429
  ...quote,
32145
32430
  held: void 0
32146
32431
  }));
@@ -32170,7 +32455,7 @@ var CashuWallet = class CashuWallet {
32170
32455
  expiresAt: response.expiry ? response.expiry * 1e3 : null,
32171
32456
  testCoins: true
32172
32457
  };
32173
- await wrap((await store(STORES$1.quotes, "readwrite")).put(quote));
32458
+ await committed((await store(STORES$1.quotes, "readwrite")).put(quote));
32174
32459
  const deadline = Date.now() + TEST_COINS_WAIT_MS;
32175
32460
  for (;;) {
32176
32461
  if (await this.locked(mint, () => this.settleQuote(quote.quote))) {
@@ -32209,7 +32494,7 @@ var CashuWallet = class CashuWallet {
32209
32494
  this.quoteTimer = null;
32210
32495
  if (this.stopped) return;
32211
32496
  const quotes = await wrap((await store(STORES$1.quotes, "readonly")).getAll());
32212
- for (const held of quotes.filter((q) => q.held && q.expiresAt && q.expiresAt + 6e4 < Date.now())) await wrap((await store(STORES$1.quotes, "readwrite")).delete(held.quote));
32497
+ for (const held of quotes.filter((q) => q.held && q.expiresAt && q.expiresAt + 6e4 < Date.now())) await committed((await store(STORES$1.quotes, "readwrite")).delete(held.quote));
32213
32498
  await this.settleQuotes(quotes);
32214
32499
  const remaining = await wrap((await store(STORES$1.quotes, "readonly")).getAll());
32215
32500
  if (!this.stopped && remaining.some((q) => !q.issuedUnclaimed && !q.held)) this.quoteTimer = setTimeout(() => void this.pollQuotes(), QUOTE_POLL_MS);
@@ -32232,7 +32517,7 @@ var CashuWallet = class CashuWallet {
32232
32517
  const answer = await wallet.checkMintQuoteBolt11(quote.quote);
32233
32518
  const { state } = answer;
32234
32519
  if (state === "UNPAID") {
32235
- if (quote.expiresAt && quote.expiresAt + 6e4 < Date.now()) await wrap((await store(STORES$1.quotes, "readwrite")).delete(quote.quote));
32520
+ if (quote.expiresAt && quote.expiresAt + 6e4 < Date.now()) await committed((await store(STORES$1.quotes, "readwrite")).delete(quote.quote));
32236
32521
  return null;
32237
32522
  }
32238
32523
  const saved = quote.outputs?.map((o) => OutputData.deserialize(o));
@@ -32240,7 +32525,7 @@ var CashuWallet = class CashuWallet {
32240
32525
  const issued = saved?.length ? await this.signedOutputs(wallet, saved) : void 0;
32241
32526
  if (Array.isArray(issued)) return this.storeMinted(quote, issued);
32242
32527
  console.warn(`[wallet] ${quote.mint} issued quote ${quote.quote} (${quote.amount} sats) but this wallet holds no ecash for it`);
32243
- await wrap((await store(STORES$1.quotes, "readwrite")).put({
32528
+ await committed((await store(STORES$1.quotes, "readwrite")).put({
32244
32529
  ...quote,
32245
32530
  issuedUnclaimed: true
32246
32531
  }));
@@ -32256,14 +32541,14 @@ var CashuWallet = class CashuWallet {
32256
32541
  paid: true,
32257
32542
  outputs: saved ? quote.outputs : preview.outputData.map((o) => OutputData.serialize(o))
32258
32543
  };
32259
- if (!quote.paid || !saved) await wrap((await store(STORES$1.quotes, "readwrite")).put(written));
32544
+ if (!quote.paid || !saved) await committed((await store(STORES$1.quotes, "readwrite")).put(written));
32260
32545
  let proofs;
32261
32546
  try {
32262
32547
  proofs = await wallet.completeMint(preview);
32263
32548
  } catch (error) {
32264
32549
  if (saved && isMintOperationError(error) && (await wallet.checkMintQuoteBolt11(quote.quote).catch(() => null))?.state === "PAID") {
32265
32550
  const { outputs: _refused, ...fresh } = written;
32266
- await wrap((await store(STORES$1.quotes, "readwrite")).put(fresh));
32551
+ await committed((await store(STORES$1.quotes, "readwrite")).put(fresh));
32267
32552
  }
32268
32553
  throw error;
32269
32554
  }
@@ -32654,6 +32939,7 @@ var CashuWallet = class CashuWallet {
32654
32939
  };
32655
32940
  if (!swap) {
32656
32941
  const preview = await (await this.wallet(mint)).prepareSwapToReceive(token);
32942
+ if (preview.inputs.some((p) => this.spentTokens.has(`${mint} ${p.secret}`))) throw engineError("ecashAlreadySpent");
32657
32943
  const redeeming = new Set(written.flatMap((s) => (swapOf(s).inputs ?? []).map((p) => p.secret)));
32658
32944
  if (preview.inputs.some((p) => redeeming.has(p.secret))) throw engineError("ecashBeingReceived");
32659
32945
  swap = {
@@ -32665,7 +32951,7 @@ var CashuWallet = class CashuWallet {
32665
32951
  token,
32666
32952
  ...records(preview.amount.toNumber())
32667
32953
  };
32668
- await wrap((await store(STORES$1.swaps, "readwrite")).put(swap));
32954
+ await committed((await store(STORES$1.swaps, "readwrite")).put(swap));
32669
32955
  }
32670
32956
  const { keep } = await this.completeSwap(swap);
32671
32957
  const credited = sats(keep);
@@ -32757,11 +33043,12 @@ var CashuWallet = class CashuWallet {
32757
33043
  ...swap,
32758
33044
  attemptEndedAt: Date.now()
32759
33045
  };
32760
- await (async () => wrap((await store(STORES$1.swaps, "readwrite")).put(ended)))().catch(() => {});
33046
+ await (async () => committed((await store(STORES$1.swaps, "readwrite")).put(ended)))().catch(() => {});
32761
33047
  const outcome = await this.swapOutcome(ended, refused).catch(() => ({ state: "open" }));
32762
33048
  if (outcome.state === "done") return outcome;
32763
33049
  if (outcome.state === "never" && outcome.final) {
32764
33050
  await this.dropSwap(ended, outcome.gone);
33051
+ if (swap.kind === "receive") this.rememberSpent(swap.mint, outcome.gone);
32765
33052
  throw outcome.gone.size > 0 ? Object.assign(engineError("ecashAlreadySpent"), { cause: error }) : error;
32766
33053
  }
32767
33054
  this.swapsAgainIn(SWAP_POLL_MS);
@@ -32901,6 +33188,17 @@ var CashuWallet = class CashuWallet {
32901
33188
  });
32902
33189
  if (gone.size > 0 && inputs.length > 0) this.recheck(swap.mint).catch(() => {});
32903
33190
  }
33191
+ rememberSpent(mint, secrets) {
33192
+ for (const secret of secrets) {
33193
+ const key = `${mint} ${secret}`;
33194
+ this.spentTokens.delete(key);
33195
+ this.spentTokens.add(key);
33196
+ }
33197
+ for (const oldest of this.spentTokens) {
33198
+ if (this.spentTokens.size <= SPENT_KEPT) break;
33199
+ this.spentTokens.delete(oldest);
33200
+ }
33201
+ }
32904
33202
  /** The proofs a split reserved, as they are stored now. */
32905
33203
  async storedInputs(swap) {
32906
33204
  const secrets = new Set(swapOf(swap).inputs.map((p) => p.secret));
@@ -32960,7 +33258,7 @@ var CashuWallet = class CashuWallet {
32960
33258
  if (!swap) return;
32961
33259
  try {
32962
33260
  if (swap.finished) {
32963
- if (await this.tellSwap(swap, true)) await wrap((await store(STORES$1.swaps, "readwrite")).delete(swap.id));
33261
+ if (await this.tellSwap(swap, true)) await committed((await store(STORES$1.swaps, "readwrite")).delete(swap.id));
32964
33262
  else later(SWAP_POLL_MS);
32965
33263
  return;
32966
33264
  }
@@ -32973,7 +33271,7 @@ var CashuWallet = class CashuWallet {
32973
33271
  ...swap,
32974
33272
  attemptEndedAt: Date.now()
32975
33273
  };
32976
- await wrap((await store(STORES$1.swaps, "readwrite")).put(swap));
33274
+ await committed((await store(STORES$1.swaps, "readwrite")).put(swap));
32977
33275
  }
32978
33276
  const outcome = await this.swapOutcome(swap);
32979
33277
  if (outcome.state === "open") {
@@ -32984,7 +33282,7 @@ var CashuWallet = class CashuWallet {
32984
33282
  if (outcome.slow) {
32985
33283
  const stuck = (swap.stuck ?? 0) + 1;
32986
33284
  const wait = stuck <= 6 ? SWAP_SLOW_POLL_MS : stuck <= 30 ? 36e5 : 864e5;
32987
- await wrap((await store(STORES$1.swaps, "readwrite")).put({
33285
+ await committed((await store(STORES$1.swaps, "readwrite")).put({
32988
33286
  ...swap,
32989
33287
  stuck,
32990
33288
  askAt: Date.now() + wait
@@ -32997,7 +33295,7 @@ var CashuWallet = class CashuWallet {
32997
33295
  const { keep } = await (await this.wallet(mint)).completeSwap(deserializeSwapPreview(swapOf(swap)));
32998
33296
  if (await this.finishSwap(swap, keep, [], true)) {
32999
33297
  const told = await this.tellSwap(swap, true);
33000
- if (swap.payment && told) await wrap((await store(STORES$1.swaps, "readwrite")).delete(swap.id));
33298
+ if (swap.payment && told) await committed((await store(STORES$1.swaps, "readwrite")).delete(swap.id));
33001
33299
  else if (swap.payment) later(SWAP_POLL_MS);
33002
33300
  this.events.onChange();
33003
33301
  }
@@ -33006,12 +33304,12 @@ var CashuWallet = class CashuWallet {
33006
33304
  ...swap,
33007
33305
  attemptEndedAt: Date.now()
33008
33306
  };
33009
- await wrap((await store(STORES$1.swaps, "readwrite")).put(swap));
33307
+ await committed((await store(STORES$1.swaps, "readwrite")).put(swap));
33010
33308
  const refusal = isMintOperationError(error) ? await this.swapOutcome(swap, true).catch(() => void 0) : void 0;
33011
33309
  if (refusal?.state === "done") {
33012
33310
  if (await this.finishSwap(swap, refusal.keep, refusal.send, true)) {
33013
33311
  const told = await this.tellSwap(swap, true);
33014
- if (swap.payment && told) await wrap((await store(STORES$1.swaps, "readwrite")).delete(swap.id));
33312
+ if (swap.payment && told) await committed((await store(STORES$1.swaps, "readwrite")).delete(swap.id));
33015
33313
  }
33016
33314
  this.events.onChange();
33017
33315
  } else if (refusal?.state === "never") {
@@ -33022,7 +33320,7 @@ var CashuWallet = class CashuWallet {
33022
33320
  }
33023
33321
  } else if (outcome.pending && swap.kind === "receive" && !swap.released && Date.now() >= swapOverdueAt(swap)) {
33024
33322
  if (Date.now() < swap.createdAt + SWAP_WATCH_MS) {
33025
- await wrap((await store(STORES$1.swaps, "readwrite")).put({
33323
+ await committed((await store(STORES$1.swaps, "readwrite")).put({
33026
33324
  ...swap,
33027
33325
  askAt: Date.now() + SWAP_SLOW_POLL_MS
33028
33326
  }));
@@ -33038,7 +33336,7 @@ var CashuWallet = class CashuWallet {
33038
33336
  if (outcome.state === "done") {
33039
33337
  if (await this.finishSwap(swap, outcome.keep, outcome.send, true)) {
33040
33338
  const told = await this.tellSwap(swap, true);
33041
- if (swap.payment && told) await wrap((await store(STORES$1.swaps, "readwrite")).delete(swap.id));
33339
+ if (swap.payment && told) await committed((await store(STORES$1.swaps, "readwrite")).delete(swap.id));
33042
33340
  else if (swap.payment) later(SWAP_POLL_MS);
33043
33341
  }
33044
33342
  } else if (swap.released) {
@@ -33446,10 +33744,95 @@ var allows = (link, method) => method === "arkade" ? link.supportsArkPayments :
33446
33744
  /** Federation ecash is counted in msats; a chat counts whole sats. */
33447
33745
  var fedimintSats = (msats) => Math.floor(msats / 1e3);
33448
33746
  /**
33449
- * Which notes these are, whatever the spelling: the Fedimint client drops whitespace anywhere and reads URL-safe or
33450
- * standard base64, so the digest is of the bytes. Text that is no base64 is digested without its whitespace.
33747
+ * The bytes of notes as the Fedimint client reads them (OOBNotes::from_str), whitespace already dropped: base32hex
33748
+ * after a `fedimint` prefix in any case (least significant bits first, a short last group dropped), else URL-safe
33749
+ * or standard base64. Undefined: no such text.
33750
+ */
33751
+ function oobNotesBytes(text) {
33752
+ const lower = text.toLowerCase();
33753
+ if (lower.startsWith("fedimint")) {
33754
+ const out = [];
33755
+ let buffer = 0, bits = 0;
33756
+ for (const ch of lower.slice(8)) {
33757
+ const value = "0123456789abcdefghijklmnopqrstuv".indexOf(ch);
33758
+ if (value < 0) {
33759
+ out.length = 0;
33760
+ bits = -1;
33761
+ break;
33762
+ }
33763
+ buffer |= value << bits;
33764
+ bits += 5;
33765
+ while (bits >= 8) {
33766
+ out.push(buffer & 255);
33767
+ buffer >>>= 8;
33768
+ bits -= 8;
33769
+ }
33770
+ }
33771
+ if (bits >= 0) return Uint8Array.from(out);
33772
+ }
33773
+ try {
33774
+ return fromBase64Url(text.replace(/=+$/, "").replace(/\+/g, "-").replace(/\//g, "_"));
33775
+ } catch {
33776
+ return;
33777
+ }
33778
+ }
33779
+ /** A BigSize number (Fedimint's consensus integer) at `at`, and where what follows it starts. */
33780
+ function bigSize(bytes, at) {
33781
+ const first = bytes[at];
33782
+ const width = first === 253 ? 2 : first === 254 ? 4 : first === 255 ? 8 : 0;
33783
+ if (first === void 0 || at + 1 + width > bytes.length) throw new Error("short");
33784
+ let value = width ? 0 : first;
33785
+ for (let i = 1; i <= width; i++) value = value * 256 + bytes[at + i];
33786
+ return [value, at + 1 + width];
33787
+ }
33788
+ /**
33789
+ * The signatures of the notes the federation redeems, sorted, each once: OOBNotes are a list of parts (tag, length,
33790
+ * bytes) and the client takes the first Notes part (tag 0: tiers of amount, count, then 48-byte signature and 32-byte
33791
+ * key per note). Undefined: the bytes are no OOBNotes.
33792
+ */
33793
+ function oobNoteSignatures(bytes) {
33794
+ try {
33795
+ let [parts, at] = bigSize(bytes, 0);
33796
+ let signatures;
33797
+ for (; parts > 0; parts--) {
33798
+ const [tag, sized] = bigSize(bytes, at);
33799
+ const [length, start] = bigSize(bytes, sized);
33800
+ const end = start + length;
33801
+ if (end > bytes.length) return void 0;
33802
+ if (tag === 0 && !signatures) {
33803
+ const found = /* @__PURE__ */ new Set();
33804
+ const part = bytes.subarray(0, end);
33805
+ let [tiers, i] = bigSize(part, start);
33806
+ for (; tiers > 0; tiers--) {
33807
+ let count;
33808
+ [, i] = bigSize(part, i);
33809
+ [count, i] = bigSize(part, i);
33810
+ if (i + count * 80 > end) return void 0;
33811
+ for (; count > 0; count--, i += 80) found.add(hexOf(bytes.subarray(i, i + 48)));
33812
+ }
33813
+ if (i !== end || !found.size) return void 0;
33814
+ signatures = [...found].sort();
33815
+ }
33816
+ at = end;
33817
+ }
33818
+ return at === bytes.length ? signatures : void 0;
33819
+ } catch {
33820
+ return;
33821
+ }
33822
+ }
33823
+ var hexOf = (bytes) => Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
33824
+ /**
33825
+ * Which notes these are, whatever the encoding: the digest of the signatures of the notes the federation redeems, so
33826
+ * reordered or repeated parts, an unknown part, notes reordered in a tier and base32 or base64 spellings all give the
33827
+ * same one. Text that is no OOBNotes is digested as `fedimintBytesDigest` does.
33451
33828
  */
33452
33829
  function fedimintNotesDigest(notes) {
33830
+ const bytes = oobNotesBytes(notes.replace(/\s+/g, ""));
33831
+ const signatures = bytes && oobNoteSignatures(bytes);
33832
+ return signatures ? digestHex(`fedimint-notes:${signatures.join(",")}`) : fedimintBytesDigest(notes);
33833
+ }
33834
+ /** What earlier versions wrote down for notes: the digest of their base64 bytes, or of the text without its whitespace. */
33835
+ function fedimintBytesDigest(notes) {
33453
33836
  const text = notes.replace(/\s+/g, "");
33454
33837
  try {
33455
33838
  return digestHex(toBase64Url(fromBase64Url(text.replace(/=+$/, ""))));
@@ -34533,10 +34916,11 @@ var PaymentDesk = class {
34533
34916
  error: reason
34534
34917
  });
34535
34918
  const sats = parseSats(payment.amount.value, payment.amount.asset);
34919
+ const spent = error instanceof EngineError && error.engineCode === "ecashAlreadySpent";
34536
34920
  try {
34537
34921
  await this.host.storeMessage({
34538
34922
  linkId,
34539
- id: `peer_${payment.timestamp}_refused`,
34923
+ id: spent ? `peer_spent_${digestHex(token).slice(0, 32)}` : `peer_${payment.timestamp}_refused`,
34540
34924
  text: `Could not receive ${sats === null ? "a payment" : `${sats.toLocaleString()} sats`}: ${reason}`,
34541
34925
  sender: "peer",
34542
34926
  timestamp: payment.timestamp,
@@ -34721,6 +35105,8 @@ var PaymentDesk = class {
34721
35105
  lastCheckFrom = /* @__PURE__ */ new Map();
34722
35106
  /** `receiveInvoicePaid`'s last look, by `<link id>:<invoice>`: only the last 3 seconds' are kept. */
34723
35107
  lastInvoiceCheck = /* @__PURE__ */ new Map();
35108
+ /** The looks `receiveInvoicePaid` made for each chat in the last 3 s (at most `INVOICE_LOOKS_PER_CHAT`). */
35109
+ invoiceLooks = /* @__PURE__ */ new Map();
34724
35110
  /**
34725
35111
  * "I paid it from another wallet": the contact's app is asked to look at its wallet now. Nothing here
34726
35112
  * marks anything paid; the request settles when the payee's wallet sees the money, with or without this.
@@ -34780,7 +35166,9 @@ var PaymentDesk = class {
34780
35166
  * The contact says it paid an invoice of ours it found in the chat, with no request: a Receive-screen invoice is
34781
35167
  * held on a test mint until then (StoredQuote `held`), and that one alone is let go. A request's invoice is spoken
34782
35168
  * for by its own contact only (`receiveCheck`). Bounded: one look every 3 seconds per invoice of a chat, so two
34783
- * invoices paid one right after the other are both let go.
35169
+ * invoices paid one right after the other are both let go, and `INVOICE_LOOKS_PER_CHAT` looks every 3 seconds per
35170
+ * chat: the invoice is the contact's text, and a frame per text made each one a read of every invoice of the wallet
35171
+ * (2,000 frames, 2,000 reads), each also walking every key of the last 3 s (agents#1586).
34784
35172
  */
34785
35173
  async receiveInvoicePaid(linkId, link, invoice) {
34786
35174
  if (!link.allowsPayment("lightning")) return;
@@ -34788,8 +35176,19 @@ var PaymentDesk = class {
34788
35176
  const wanted = invoice.trim().toLowerCase();
34789
35177
  const key = `${linkId}:${wanted}`;
34790
35178
  if (now - (this.lastInvoiceCheck.get(key) ?? 0) < 3e3) return;
34791
- for (const [seen, at] of this.lastInvoiceCheck) if (now - at >= 3e3) this.lastInvoiceCheck.delete(seen);
35179
+ const looks = (this.invoiceLooks.get(linkId) ?? []).filter((at) => now - at < 3e3);
35180
+ if (looks.length >= 5) {
35181
+ this.invoiceLooks.set(linkId, looks);
35182
+ return;
35183
+ }
35184
+ this.invoiceLooks.set(linkId, [...looks, now]);
35185
+ for (const [seen, at] of this.lastInvoiceCheck) {
35186
+ if (now - at < 3e3) break;
35187
+ this.lastInvoiceCheck.delete(seen);
35188
+ }
35189
+ this.lastInvoiceCheck.delete(key);
34792
35190
  this.lastInvoiceCheck.set(key, now);
35191
+ for (const [chat, times] of this.invoiceLooks) if (chat !== linkId && times.every((at) => now - at >= 3e3)) this.invoiceLooks.delete(chat);
34793
35192
  try {
34794
35193
  const quote = (await this.wallet.quotes()).find((q) => q.held && !q.paymentId && q.invoice.toLowerCase() === wanted);
34795
35194
  if (quote) await this.wallet.vouch(quote.invoice);
@@ -35558,8 +35957,9 @@ var PaymentDesk = class {
35558
35957
  return;
35559
35958
  }
35560
35959
  const digest = fedimintNotesDigest(notes);
35960
+ const bytes = fedimintBytesDigest(notes);
35561
35961
  const spelled = digestHex(notes.trim());
35562
- const before = [...this.payments.values()].find((p) => (p.notesDigest === digest || p.notesDigest === spelled) && p.direction === "in" && p.kind === "payment");
35962
+ const before = [...this.payments.values()].find((p) => (p.notesDigest === digest || p.notesDigest === bytes || p.notesDigest === spelled) && p.direction === "in" && p.kind === "payment");
35563
35963
  if (before) {
35564
35964
  link.sendPaymentResult({
35565
35965
  id: payment.id,
@@ -36103,7 +36503,7 @@ var PaymentDesk = class {
36103
36503
  }
36104
36504
  async save(payment) {
36105
36505
  this.payments.set(payment.id, payment);
36106
- await wrap((await store(STORES$1.payments, "readwrite")).put(payment));
36506
+ await committed((await store(STORES$1.payments, "readwrite")).put(payment));
36107
36507
  this.host.onChange();
36108
36508
  }
36109
36509
  /**
@@ -36613,6 +37013,8 @@ var LIMITED_MODE_METHODS = /* @__PURE__ */ new Set([
36613
37013
  "setFastPoll",
36614
37014
  "exportLinks",
36615
37015
  "walletBackupReminder",
37016
+ "savedMessages",
37017
+ "saveMessage",
36616
37018
  "deviceRestoreStartOwn"
36617
37019
  ]);
36618
37020
  /** Thrown by the transport when something tries to publish in limited mode: a bug in a switch point, never a wait. */
@@ -36634,6 +37036,19 @@ function refusingWhileLimited(transport, limited) {
36634
37036
  if (transport.publishPayload) guarded.publishPayload = (pubKeyZ32, payload, options) => limited() ? Promise.reject(new LimitedModeError()) : transport.publishPayload(pubKeyZ32, payload, options);
36635
37037
  return guarded;
36636
37038
  }
37039
+ /**
37040
+ * My key in an active group, and who is in it, from its one view. A received reaction, edit or pin reads it per frame:
37041
+ * built from every group's sorted views, a 256-frame catch-up in 10 communities of 256 took 11 s, not 1.1 s
37042
+ * (agents#1700).
37043
+ */
37044
+ function membershipOf(group) {
37045
+ return group?.status === "active" && group.myKey ? {
37046
+ me: group.myKey,
37047
+ members: new Set(group.members.map((m) => m.key))
37048
+ } : void 0;
37049
+ }
37050
+ /** The wire part of the ids the payment desk gives a contact's payment, request or refusal line (`peer_<this>`). */
37051
+ var PAYMENT_LINE_ID = /^(?:\d+(?:_refused)?|spent_[0-9a-f]{32})$/;
36637
37052
  var GhostlyNode = class GhostlyNode {
36638
37053
  events;
36639
37054
  options;
@@ -37559,6 +37974,11 @@ var GhostlyNode = class GhostlyNode {
37559
37974
  reactions = new Reactions({
37560
37975
  messages: (chat) => db.getMessages(chat),
37561
37976
  message: (chat, id) => db.getMessage(chat, id),
37977
+ rows: async (chat, id) => {
37978
+ const file = await fileStore.get(GhostlyNode.outgoingFileId(chat, id)).catch(() => void 0);
37979
+ const payment = this.desk.payment(paymentAlias(id, chat)) ?? this.desk.payment(id);
37980
+ return [...file?.linkId === chat && file.metadata ? [`me_${file.metadata.timestamp}`] : [], ...payment?.linkId === chat ? [`me_${payment.createdAt}`, `peer_${payment.createdAt}`] : []];
37981
+ },
37562
37982
  patch: (chat, id, change) => db.patchMessage(chat, id, change),
37563
37983
  changed: async (chat, id, note) => {
37564
37984
  const shown = this.reactionNotes.get(chat);
@@ -37603,7 +38023,12 @@ var GhostlyNode = class GhostlyNode {
37603
38023
  },
37604
38024
  linkReady: (linkId, version = 1) => !!this.links.get(linkId)?.link?.supportsGroupVersion(version),
37605
38025
  linkHandled: (linkId) => this.links.get(linkId)?.link?.handled() ?? Promise.resolve(false),
38026
+ linkWaiting: (linkId) => this.links.get(linkId)?.link?.framesWaiting() ?? 0,
37606
38027
  linkOpen: (linkId) => !!this.links.get(linkId)?.link?.isDataLinkOpen,
38028
+ loaded: (groupId, history) => {
38029
+ const note = latestReaction(history);
38030
+ if (note) this.reactionNotes.set(`group:${groupId}`, note);
38031
+ },
37607
38032
  myNick: () => this.sharedNick,
37608
38033
  seqFloor: () => this.counterFloor,
37609
38034
  adminWork: (groupId) => !this.limitedMode && !this.groupAdminOff.has(groupId),
@@ -37614,7 +38039,7 @@ var GhostlyNode = class GhostlyNode {
37614
38039
  if (typeof RTCPeerConnection === "undefined" && native.length) {
37615
38040
  let held = 0;
37616
38041
  for (const live of this.links.values()) if (live.stored.group && live.stored.group !== groupId && live.link) held++;
37617
- return Math.max(0, Math.max(...native.map((key) => this.groupNativeSlots(key))) - held);
38042
+ return Math.max(0, Math.max(...native.map((key) => this.groupNativeRoom(key))) - held);
37618
38043
  }
37619
38044
  const budget = this.options.peerBudget;
37620
38045
  if (budget === void 0) return void 0;
@@ -37651,6 +38076,7 @@ var GhostlyNode = class GhostlyNode {
37651
38076
  door,
37652
38077
  back
37653
38078
  }))?.records ?? null,
38079
+ readHeldBackFor: (pubKeyZ32) => this.groupTransport.readHeldBackFor?.(pubKeyZ32),
37654
38080
  expectPeer: (linkId) => this.links.get(linkId)?.link?.expectPeer(),
37655
38081
  signalIn: (linkId, payload, direct) => !!this.links.get(linkId)?.carried?.accept(payload, direct),
37656
38082
  edgeSignal: (linkId) => this.links.get(linkId)?.carried?.latest() ?? null,
@@ -37738,11 +38164,11 @@ var GhostlyNode = class GhostlyNode {
37738
38164
  },
37739
38165
  changed: (chat, id) => this.messagesChanged(chat, [id]),
37740
38166
  membership: (groupId) => {
37741
- const membership = this.membership(groupId);
38167
+ const view = this.groups.view(groupId), membership = membershipOf(view);
37742
38168
  return membership && {
37743
38169
  ...membership,
37744
38170
  community: this.groups.isCommunityGroup(groupId),
37745
- admin: !!this.groups.views().find((g) => g.id === groupId)?.isAdmin
38171
+ admin: !!view?.isAdmin
37746
38172
  };
37747
38173
  },
37748
38174
  send: (groupId, edit, to) => this.groups.sendEdit(groupId, edit, to),
@@ -37750,7 +38176,7 @@ var GhostlyNode = class GhostlyNode {
37750
38176
  removeMine: async (chat, message, removal) => {
37751
38177
  const groupId = chat.slice(6);
37752
38178
  await this.groups.setRemovals(groupId, withRemoval(this.groups.removals(groupId), removal));
37753
- await this.forgetGroupMessage(chat, message.id);
38179
+ await this.forgetGroupMessage(chat, message.id, message);
37754
38180
  },
37755
38181
  edge: (groupId, member) => {
37756
38182
  const link = this.links.get(this.memberEdges(groupId).get(member) ?? "")?.link;
@@ -37761,9 +38187,12 @@ var GhostlyNode = class GhostlyNode {
37761
38187
  * A group's message deleted for everyone, by its author or by me: gone from this device with its file, and noted so a
37762
38188
  * copy that comes again (a catch-up, a member handing it on) is not stored. The replies here that quote it lose its line.
37763
38189
  */
37764
- async forgetGroupMessage(chat, id) {
37765
- await this.groups.removed(chat.slice(6), id);
38190
+ async forgetGroupMessage(chat, id, row) {
38191
+ const groupId = chat.slice(6);
38192
+ const moved = row ?? (this.groups.movedMarks(groupId, id) ? await db.getMessage(chat, id) : void 0);
38193
+ await this.groups.removed(groupId, id);
37766
38194
  await db.deleteMessage(chat, id);
38195
+ if (moved) await this.groups.unmark(groupId, moved);
37767
38196
  this.quoteSweeps.add(chat, id, id);
37768
38197
  await this.messagesChanged(chat, [id]);
37769
38198
  this.emitState();
@@ -37783,11 +38212,7 @@ var GhostlyNode = class GhostlyNode {
37783
38212
  }
37784
38213
  /** My key in an active group, and who is in it. */
37785
38214
  membership(groupId) {
37786
- const group = this.groups.views().find((g) => g.id === groupId);
37787
- return group?.status === "active" && group.myKey ? {
37788
- me: group.myKey,
37789
- members: new Set(group.members.map((m) => m.key))
37790
- } : void 0;
38215
+ return membershipOf(this.groups.view(groupId));
37791
38216
  }
37792
38217
  /** The link payments with `linkId` go over: a chat's or an edge's, or a community member's through the group. */
37793
38218
  paymentLink(linkId) {
@@ -38153,13 +38578,9 @@ var GhostlyNode = class GhostlyNode {
38153
38578
  for (const message of messages.slice(-20)) this.clockSample(message);
38154
38579
  const note = latestReaction(messages);
38155
38580
  if (note) this.reactionNotes.set(stored.id, note);
38156
- if (stored.profile) await this.outboxFor(stored.id).recover();
38581
+ if (stored.profile) await this.outboxFor(stored.id).recover(messages);
38157
38582
  }
38158
38583
  this.transfersRestored = true;
38159
- for (const group of this.groups.views()) {
38160
- const note = latestReaction(await db.getMessages(`group:${group.id}`));
38161
- if (note) this.reactionNotes.set(`group:${group.id}`, note);
38162
- }
38163
38584
  this.publicProfiles.start();
38164
38585
  await this.startLinks(links.map((stored) => stored.id), (linkId) => {
38165
38586
  if (!this.links.get(linkId)?.stored.group) this.refreshPublicProfiles({ linkId }).catch(() => {});
@@ -38258,7 +38679,7 @@ var GhostlyNode = class GhostlyNode {
38258
38679
  return wrap((await store(STORES$1.settings, "readonly")).get(RESTORE_UNCHECKED_KEY)).catch(() => null);
38259
38680
  }
38260
38681
  async clearRestoreMark() {
38261
- await wrap((await store(STORES$1.settings, "readwrite")).delete(RESTORE_UNCHECKED_KEY));
38682
+ await committed((await store(STORES$1.settings, "readwrite")).delete(RESTORE_UNCHECKED_KEY));
38262
38683
  }
38263
38684
  /**
38264
38685
  * "Start it as a profile of its own" on a restored copy whose read found a tombstone (WISP 06 § A backup restored where
@@ -38321,7 +38742,7 @@ var GhostlyNode = class GhostlyNode {
38321
38742
  }
38322
38743
  await this.groups.files?.sweep((await db.getGroups()).map((group) => group.id)).catch(() => {});
38323
38744
  await this.leaveLimited(start.readAt ?? null).catch(() => {});
38324
- if (!this.options.singleDevice && !this.limitedMode && this.networkOn && knownDeviceGate()?.state === "active") this.startDeviceSet().catch(() => {});
38745
+ if (!this.options.singleDevice && !this.limitedMode && this.networkOn && knownDeviceGate()?.state === "active") this.startDeviceSet({ justRead: start.readAt !== void 0 }).catch(() => {});
38325
38746
  }
38326
38747
  readTurnWhileLimited(after = 3e4) {
38327
38748
  if (this.limitedTimer) clearTimeout(this.limitedTimer);
@@ -38341,7 +38762,7 @@ var GhostlyNode = class GhostlyNode {
38341
38762
  }
38342
38763
  if (outcome && (outcome.kind === "start" || outcome.kind === "go-on" && !outcome.restricted)) {
38343
38764
  await this.leaveLimited().catch(() => {});
38344
- if (!this.limitedMode && this.networkOn) this.startDeviceSet().catch(() => {});
38765
+ if (!this.limitedMode && this.networkOn) this.startDeviceSet({ justRead: true }).catch(() => {});
38345
38766
  return;
38346
38767
  }
38347
38768
  this.readTurnWhileLimited();
@@ -38630,7 +39051,6 @@ var GhostlyNode = class GhostlyNode {
38630
39051
  for (const queue of this.editQueues.values()) queue.stop();
38631
39052
  for (const restore of this.cardRestores.values()) clearTimeout(restore.timer);
38632
39053
  this.cardRestores.clear();
38633
- this.quoteSweeps.stop();
38634
39054
  this.groupEdits.stop();
38635
39055
  this.reactions.stop();
38636
39056
  this.cardEdits.stop();
@@ -38638,6 +39058,7 @@ var GhostlyNode = class GhostlyNode {
38638
39058
  linksStopped,
38639
39059
  links?.stop(),
38640
39060
  this.groups.flush(),
39061
+ this.quoteSweeps.stop(),
38641
39062
  ...WALLET_NETWORKS.flatMap((network) => [
38642
39063
  this.arkWallets,
38643
39064
  this.barkWallets,
@@ -38857,6 +39278,10 @@ var GhostlyNode = class GhostlyNode {
38857
39278
  async getMessages(linkId) {
38858
39279
  return (await db.getMessages(linkId)).map(withoutFrame);
38859
39280
  }
39281
+ /** The ids of the messages deleted in a chat (`deletedIds`, the newest `MAX_DELETED_IDS`): a whole history goes with them. */
39282
+ deletedIdsOf(linkId) {
39283
+ return this.links.get(linkId)?.stored.deletedIds ?? [];
39284
+ }
38860
39285
  /** One message of a chat, read by its id: the whole history costs a read of every row. */
38861
39286
  async getMessage(linkId, id) {
38862
39287
  const message = await db.getMessage(linkId, id);
@@ -39750,10 +40175,12 @@ var GhostlyNode = class GhostlyNode {
39750
40175
  error: `Message too large for DHT (${bytes} bytes, max 500). Try a shorter message or share a link instead.`,
39751
40176
  refused: true
39752
40177
  };
39753
- if (!live?.link) return { error: "You are offline" };
40178
+ const waitsForCheck = !!live && !live.link && this.limitedMode && !!live.stored.profile;
40179
+ if (live && !live.link && this.limitedMode && !live.stored.profile) return { error: LIMITED_MODE_ERROR };
40180
+ if (!live || !live.link && !waitsForCheck) return { error: "You are offline" };
39754
40181
  if (!trimmed) return { error: null };
39755
40182
  const timestamp = params.timestamp ?? arrivalKey(Date.now(), this.placedAt.get(linkId));
39756
- if (live.stored.profile) live.link.setTyping(false);
40183
+ if (live.stored.profile) live.link?.setTyping(false);
39757
40184
  if (live.stored.profile) {
39758
40185
  const found = params.replyTo === void 0 ? void 0 : await this.replyFor(linkId, params.replyTo);
39759
40186
  if (typeof found === "string") return {
@@ -39779,6 +40206,7 @@ var GhostlyNode = class GhostlyNode {
39779
40206
  error: "Replies need a current chat; this compatibility chat sends text only.",
39780
40207
  refused: true
39781
40208
  };
40209
+ if (!live.link) return { error: "You are offline" };
39782
40210
  const via = live.link.isDataLinkOpen ? "datalink" : "pkarr";
39783
40211
  await this.storeMessage({
39784
40212
  linkId,
@@ -39822,7 +40250,7 @@ var GhostlyNode = class GhostlyNode {
39822
40250
  */
39823
40251
  async sendChatText(live, trimmed, timestamp, preview, reply, forwarded, card) {
39824
40252
  const { link } = live, linkId = live.stored.id;
39825
- if (!link) return { error: "You are offline" };
40253
+ if (!link && !this.limitedMode) return { error: "You are offline" };
39826
40254
  this.chatInUse(live);
39827
40255
  const bytes = new TextEncoder().encode(trimmed).length;
39828
40256
  if (bytes > LIMITS.maxChatMessageBytes) return {
@@ -39835,6 +40263,32 @@ var GhostlyNode = class GhostlyNode {
39835
40263
  };
39836
40264
  const stop = this.chatStopped(live);
39837
40265
  if (stop) return { error: stop };
40266
+ const answers = {
40267
+ ...reply && { replyTo: reply },
40268
+ ...forwarded && { forwarded },
40269
+ ...card && { card }
40270
+ };
40271
+ if (!link) {
40272
+ const id = `me_${toBase64Url(randomBytes(16))}`, wireId = id.slice(3), reason = "Sent once Ghostly can check which device is active.";
40273
+ await this.storeMessage({
40274
+ linkId,
40275
+ id,
40276
+ wireId,
40277
+ text: trimmed,
40278
+ sender: "me",
40279
+ timestamp,
40280
+ via: "datalink",
40281
+ delivery: "waiting",
40282
+ deliveryError: reason,
40283
+ ...preview && { preview },
40284
+ ...answers
40285
+ });
40286
+ await this.outboxFor(linkId).wait(id, reason);
40287
+ return {
40288
+ error: null,
40289
+ messageId: id
40290
+ };
40291
+ }
39838
40292
  if (!link.isDataLinkOpen && link.dhtDelivery?.inviteTaken) return {
39839
40293
  error: INVITE_TAKEN,
39840
40294
  refused: true
@@ -39842,11 +40296,6 @@ var GhostlyNode = class GhostlyNode {
39842
40296
  const wireId = toBase64Url(randomBytes(16)), id = `me_${wireId}`;
39843
40297
  const delivery = link.isDataLinkOpen ? "stream" : link.textDelivery === "dht" ? "dht" : "unavailable";
39844
40298
  if (delivery !== "stream") this.wakePeer(live);
39845
- const answers = {
39846
- ...reply && { replyTo: reply },
39847
- ...forwarded && { forwarded },
39848
- ...card && { card }
39849
- };
39850
40299
  if (delivery === "stream" || delivery === "dht" && bytes <= 256) {
39851
40300
  const validationError = link.validateText(trimmed, timestamp, wireId, reply && pairedWireReply(reply));
39852
40301
  if (!validationError) {
@@ -40102,6 +40551,7 @@ var GhostlyNode = class GhostlyNode {
40102
40551
  }
40103
40552
  if (edit.rm) {
40104
40553
  const message = await db.getMessage(linkId, id);
40554
+ if (!message && PAYMENT_LINE_ID.test(edit.id)) return true;
40105
40555
  if (!message || canRemove(message)) await this.forgetMessage(linkId, id, true);
40106
40556
  return true;
40107
40557
  }
@@ -40285,7 +40735,7 @@ var GhostlyNode = class GhostlyNode {
40285
40735
  ...live.stored,
40286
40736
  removals: live.stored.removals.filter((r) => r.id !== messageId)
40287
40737
  };
40288
- await db.patchLink(linkId, { removals: live.stored.removals });
40738
+ await this.writeDeletions(linkId, { removals: live.stored.removals }, true);
40289
40739
  return;
40290
40740
  }
40291
40741
  if (await db.patchMessage(linkId, messageId, (current) => {
@@ -40698,13 +41148,50 @@ var GhostlyNode = class GhostlyNode {
40698
41148
  ...live.stored,
40699
41149
  removals: withRemoval(live.stored.removals, removal)
40700
41150
  };
40701
- await db.patchLink(linkId, { removals: live.stored.removals });
40702
- await this.forgetMessage(linkId, messageId, true);
41151
+ const written = this.writeDeletions(linkId, { removals: live.stored.removals });
41152
+ const forgot = this.forgetMessage(linkId, messageId, true);
41153
+ await written;
41154
+ await forgot;
40703
41155
  const edits = this.editsFor(linkId);
40704
41156
  edits.edited(messageId);
40705
41157
  edits.flush().catch(() => {});
40706
41158
  return { error: null };
40707
41159
  }
41160
+ /** A chat's row write of its removals and deleted ids waiting to go, by chat (`writeDeletions`). */
41161
+ deletionWrites = /* @__PURE__ */ new Map();
41162
+ /** The last such write of each chat, which the next one follows. */
41163
+ deletionTail = /* @__PURE__ */ new Map();
41164
+ /**
41165
+ * Writes a chat's `removals` and `deletedIds` to its row, merged with any other change of them not written yet: one
41166
+ * write of the row for what a burst changed, not one per change. The row carries up to 500 removals on their way and
41167
+ * the last 500 deleted ids, rewritten whole each time: a CLI daemon deleting 300 messages for everyone wrote 19.5 MB of
41168
+ * journal and synced it 1,207 times, a removal and its id written apart, then each receipt again (agents#1572). The
41169
+ * values are `live.stored`'s at the time of the call, so the newest of each field wins. `relaxed` (no disk sync of its
41170
+ * own, `db.patchLink`) holds only while every change merged into the write is.
41171
+ */
41172
+ writeDeletions(linkId, patch, relaxed = false) {
41173
+ const waiting = this.deletionWrites.get(linkId);
41174
+ if (waiting) {
41175
+ Object.assign(waiting.patch, patch);
41176
+ waiting.relaxed &&= relaxed;
41177
+ return waiting.done;
41178
+ }
41179
+ const entry = {
41180
+ patch: { ...patch },
41181
+ relaxed,
41182
+ done: Promise.resolve()
41183
+ };
41184
+ this.deletionWrites.set(linkId, entry);
41185
+ entry.done = (this.deletionTail.get(linkId) ?? Promise.resolve()).catch(() => {}).then(() => {
41186
+ this.deletionWrites.delete(linkId);
41187
+ return db.patchLink(linkId, entry.patch, entry.relaxed);
41188
+ });
41189
+ this.deletionTail.set(linkId, entry.done);
41190
+ entry.done.catch(() => {}).then(() => {
41191
+ if (this.deletionTail.get(linkId) === entry.done) this.deletionTail.delete(linkId);
41192
+ });
41193
+ return entry.done;
41194
+ }
40708
41195
  /**
40709
41196
  * Forgets one message of a chat on this device, the bytes of its file and any transfer of it, and keeps its id so a
40710
41197
  * copy that comes again is not stored: a delete here, or the contact's own removal (WISP 400 § Delete for everyone),
@@ -40717,7 +41204,7 @@ var GhostlyNode = class GhostlyNode {
40717
41204
  ...live.stored,
40718
41205
  deletedIds: [...live.stored.deletedIds ?? [], messageId].slice(-500)
40719
41206
  };
40720
- db.patchLink(linkId, { deletedIds: live.stored.deletedIds });
41207
+ this.writeDeletions(linkId, { deletedIds: live.stored.deletedIds }).catch(() => {});
40721
41208
  this.hold.forget(linkId, messageId).catch(() => {});
40722
41209
  const message = await db.getMessage(linkId, messageId);
40723
41210
  if (message?.paymentId && message.delivery === "waiting") await this.desk.withdraw(message.paymentId).catch(() => {});
@@ -41592,7 +42079,9 @@ var GhostlyNode = class GhostlyNode {
41592
42079
  if (!this.links.get(linkId)?.stored.profile || this.links.get(linkId)?.stored.group) throw new Error("Invite a paired contact");
41593
42080
  return this.groups.invite(groupId, linkId);
41594
42081
  }
41595
- acceptGroupInvitation({ groupId }) {
42082
+ /** Offline, every chat's link is down: said as this app's state, not as the inviter's (who may well be online). */
42083
+ async acceptGroupInvitation({ groupId }) {
42084
+ if (!this.networkOn) throw new Error("Go online to join a group");
41596
42085
  return this.groups.accept(groupId);
41597
42086
  }
41598
42087
  declineGroupInvitation({ groupId }) {
@@ -41765,7 +42254,7 @@ var GhostlyNode = class GhostlyNode {
41765
42254
  if (ids.length > 30) throw new Error(`Forward at most 30 messages at once`);
41766
42255
  if (!targets.length) throw new Error("No chat to forward to");
41767
42256
  if (targets.length > 5) throw new Error(`Forward to at most 5 chats at once`);
41768
- if (linkId.startsWith("group:") ? !this.groups.views().some((g) => g.id === linkId.slice(6)) : this.links.get(linkId)?.stored.group !== void 0 || !this.links.has(linkId)) throw new Error("Chat not found");
42257
+ 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");
41769
42258
  const chosen = await Promise.all(ids.map((id) => db.getMessage(linkId, id)));
41770
42259
  if (chosen.some((m) => !m)) throw new Error("That message is not in this chat");
41771
42260
  const messages = chosen.sort((a, b) => a.timestamp - b.timestamp);
@@ -41797,7 +42286,7 @@ var GhostlyNode = class GhostlyNode {
41797
42286
  const hops = forwardedAgain(message.forwarded);
41798
42287
  try {
41799
42288
  if (forwardKind(message) === "text") {
41800
- const sent = groupId ? await this.groups.send(groupId, message.text, [], void 0, hops) : !live.link ? { error: "You are offline" } : live.stored.profile ? await this.sendChatText(live, message.text.trim(), now(), message.preview, void 0, hops) : await this.sendMessage({
42289
+ 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({
41801
42290
  linkId: to,
41802
42291
  text: message.text,
41803
42292
  timestamp: now()
@@ -41899,7 +42388,7 @@ var GhostlyNode = class GhostlyNode {
41899
42388
  if (linkId.startsWith("group:")) {
41900
42389
  const groupId = linkId.slice(6);
41901
42390
  if (!this.membership(groupId)) return {
41902
- error: this.groups.views().find((g) => g.id === groupId)?.statusReason ?? "You are not in this group",
42391
+ error: this.groups.view(groupId)?.statusReason ?? "You are not in this group",
41903
42392
  refused: true
41904
42393
  };
41905
42394
  const result = await this.reactions.mine(linkId, messageId, emoji);
@@ -42058,7 +42547,7 @@ var GhostlyNode = class GhostlyNode {
42058
42547
  message: (chat, id) => db.getMessage(chat, id)
42059
42548
  };
42060
42549
  if (linkId.startsWith("group:")) {
42061
- const groupId = linkId.slice(6), view = this.groups.views().find((g) => g.id === groupId);
42550
+ const groupId = linkId.slice(6), view = this.groups.view(groupId);
42062
42551
  if (!view || view.status !== "active") return { error: "You are not in this group" };
42063
42552
  if (!mayPinIn(view)) return { error: "Only the admin pins in a community" };
42064
42553
  const pin = await myPin(host, linkId, messageId, !!remove, this.groups.pinOf(groupId));
@@ -42170,6 +42659,8 @@ var GhostlyNode = class GhostlyNode {
42170
42659
  * ask again while the page still reads the first ask, whose answer must not go out as the second's.
42171
42660
  */
42172
42661
  appRangeAsked(linkId, task) {
42662
+ const link = this.links.get(linkId)?.link;
42663
+ for (const [key, held] of this.appRanges) if (key.startsWith(`${linkId} `) && (!link || !link.holdsAppRange(held))) this.appRanges.delete(key);
42173
42664
  const request = ++this.nextAppRangeAsk;
42174
42665
  this.appRanges.set(`${linkId} ${task.app} ${request}`, task);
42175
42666
  const { app, serve, file, offset, length } = task;
@@ -42182,29 +42673,49 @@ var GhostlyNode = class GhostlyNode {
42182
42673
  length
42183
42674
  });
42184
42675
  }
42676
+ /** The app reference and running version behind each chat app id that served a file, by chat: what an answer is checked against. */
42677
+ appServing = /* @__PURE__ */ new Map();
42185
42678
  /** Lets the contact's app read `file`, one of this side's linked files, while both have the app open on this session. */
42186
- appServe({ linkId, ref, file }) {
42679
+ async appServe({ linkId, ref, file, digest }) {
42187
42680
  const { live, app } = this.appChat(linkId, ref);
42188
42681
  if (typeof file !== "string" || !file) throw new Error("Not a file");
42189
- return live.link ? live.link.serveAppFile(app, file) : { error: "offline" };
42682
+ await this.appChatRunnable(ref, digest);
42683
+ if (!live.link) return { error: "offline" };
42684
+ const served = live.link.serveAppFile(app, file);
42685
+ if ("serve" in served) this.appServing.set(`${linkId} ${app}`, {
42686
+ ref,
42687
+ ...digest !== void 0 && { digest }
42688
+ });
42689
+ return served;
42190
42690
  }
42191
42691
  appUnserve({ linkId, serve }) {
42192
42692
  if (!this.appsOn) throw this.appsOff();
42193
42693
  this.links.get(linkId)?.link?.unserveAppFile(serve);
42194
42694
  }
42195
42695
  /** A page's answer to an `app-range` it served: the bytes and the file's size go to the contact, or why they cannot. */
42196
- appRangeAnswer({ linkId, app, request, bytes, size, error }) {
42696
+ async appRangeAnswer({ linkId, app, request, bytes, size, error }) {
42197
42697
  if (!this.appsOn) throw this.appsOff();
42198
- const key = `${linkId} ${app} ${request}`, task = this.appRanges.get(key), link = this.links.get(linkId)?.link;
42698
+ const key = `${linkId} ${app} ${request}`, task = this.appRanges.get(key);
42199
42699
  this.appRanges.delete(key);
42200
- if (!task || !link) return;
42700
+ if (!task) return;
42701
+ const serving = this.appServing.get(`${linkId} ${app}`);
42702
+ const stopped = serving && await this.appChatRunnable(serving.ref, serving.digest).then(() => false, () => true);
42703
+ const link = this.links.get(linkId)?.link;
42704
+ if (!link) return;
42705
+ if (stopped) {
42706
+ link.failAppRange(task, "gone");
42707
+ for (const serve of link.appServes(app)) link.unserveAppFile(serve);
42708
+ this.appServing.delete(`${linkId} ${app}`);
42709
+ return;
42710
+ }
42201
42711
  if (error === "changed" || error === "gone") return link.failAppRange(task, error);
42202
42712
  if (!(bytes instanceof Uint8Array) || typeof size !== "number" || !Number.isSafeInteger(size) || size < 0) return link.failAppRange(task, "gone");
42203
42713
  link.sendAppRange(task, bytes, size);
42204
42714
  }
42205
42715
  /** Reads a range of what the contact's app serves in this chat, or why not. */
42206
- async appRemoteRead({ linkId, ref, serve, offset, length }) {
42716
+ async appRemoteRead({ linkId, ref, serve, offset, length, digest }) {
42207
42717
  const { live, app } = this.appChat(linkId, ref);
42718
+ await this.appChatRunnable(ref, digest);
42208
42719
  if (!live.link) return { error: "offline" };
42209
42720
  if (!isServeId(serve)) return { error: "not-served" };
42210
42721
  if (!Number.isSafeInteger(offset) || offset < 0 || !Number.isSafeInteger(length) || length < 1 || length > APP_RANGE_LIMITS.requestBytes || !Number.isSafeInteger(offset + length)) throw new Error("Not a range");
@@ -42288,7 +42799,7 @@ var GhostlyNode = class GhostlyNode {
42288
42799
  * other edges, so members with no edge to the pinner get it.
42289
42800
  */
42290
42801
  async receiveGroupPin(groupId, member, pin, via) {
42291
- const view = this.groups.views().find((g) => g.id === groupId);
42802
+ const view = this.groups.view(groupId);
42292
42803
  if (!pin || !view?.myKey || view.status !== "active" || !view.members.some((m) => m.key === member)) return;
42293
42804
  if (!mayPin(view.profile, member, view.members.find((m) => m.role === "admin")?.key)) return;
42294
42805
  if (!pinIsNewer(this.groups.pinOf(groupId), pin)) return;
@@ -43260,7 +43771,7 @@ var GhostlyNode = class GhostlyNode {
43260
43771
  }
43261
43772
  /** A request any member of a group may pay, once (WISP 902 § Payments). */
43262
43773
  requestGroupPayment(params) {
43263
- const group = this.groups.views().find((g) => g.id === params.groupId);
43774
+ const group = this.groups.view(params.groupId);
43264
43775
  if (group?.status !== "active") throw new Error("You are not in this group");
43265
43776
  if (group.members.length < 2) throw new Error("Nobody else is in the group yet");
43266
43777
  return this.desk.requestFromGroup({
@@ -43562,7 +44073,7 @@ var GhostlyNode = class GhostlyNode {
43562
44073
  const next = new Set(this.groupAdminOff);
43563
44074
  if (on) next.delete(groupId);
43564
44075
  else next.add(groupId);
43565
- await wrap((await store(STORES$1.settings, "readwrite")).put({
44076
+ await committed((await store(STORES$1.settings, "readwrite")).put({
43566
44077
  at: Date.now(),
43567
44078
  groups: [...next].sort()
43568
44079
  }, GROUP_ADMIN_OFF_KEY));
@@ -43638,9 +44149,10 @@ var GhostlyNode = class GhostlyNode {
43638
44149
  /**
43639
44150
  * The active device's links to the other devices, and its stored turn record put again (WISP 06 § Publishing and
43640
44151
  * reading: "The active device puts its stored bytes at start"). This is also what completes an enrollment that a
43641
- * crash stopped after the record with the new device was stored and before it was put.
44152
+ * crash stopped after the record with the new device was stored and before it was put. `justRead`: it starts on a good
44153
+ * turn read made a moment before (the read at start, or limited mode's), which counts while it is fresh.
43642
44154
  */
43643
- async startDeviceSet() {
44155
+ async startDeviceSet({ justRead = false } = {}) {
43644
44156
  if (this.shuttingDown) return;
43645
44157
  const own = await readDeviceRecord(databaseName()).catch(() => null);
43646
44158
  this.ownDeviceKey = own?.ownSlot !== void 0 ? own.deviceSet[own.ownSlot]?.key ?? null : null;
@@ -43671,15 +44183,18 @@ var GhostlyNode = class GhostlyNode {
43671
44183
  await recoverEnrollment(databaseName(), this.turnNetwork()).catch(() => false);
43672
44184
  await this.syncDeviceVerifier().catch(() => {});
43673
44185
  const keeper = await this.deviceLinks.turnKeeper();
43674
- const outcome = await keeper?.check(false);
43675
- if (outcome?.kind === "go-on" && !outcome.restricted) {
43676
- this.noteGoodTurn();
43677
- await keeper?.stateVerifier().catch(() => null);
43678
- }
43679
- if (outcome?.kind === "gated" && !this.shuttingDown) {
43680
- const record = await readDeviceRecord(databaseName());
43681
- if (record) await this.stopReplaced(viewOf(record));
43682
- return;
44186
+ if (justRead && this.turnFresh()) await keeper?.stateVerifier().catch(() => null);
44187
+ else {
44188
+ const outcome = await keeper?.check(false);
44189
+ if (outcome?.kind === "go-on" && !outcome.restricted) {
44190
+ this.noteGoodTurn();
44191
+ await keeper?.stateVerifier().catch(() => null);
44192
+ }
44193
+ if (outcome?.kind === "gated" && !this.shuttingDown) {
44194
+ const record = await readDeviceRecord(databaseName());
44195
+ if (record) await this.stopReplaced(viewOf(record));
44196
+ return;
44197
+ }
43683
44198
  }
43684
44199
  this.watchActiveTurn();
43685
44200
  this.watchTombstones();
@@ -44042,7 +44557,7 @@ var GhostlyNode = class GhostlyNode {
44042
44557
  }
44043
44558
  try {
44044
44559
  const verifier = await makeHandoffVerifier(password);
44045
- await wrap((await store(STORES$1.settings, "readwrite")).put(verifier, GhostlyNode.HANDOFF_VERIFIER));
44560
+ await committed((await store(STORES$1.settings, "readwrite")).put(verifier, GhostlyNode.HANDOFF_VERIFIER));
44046
44561
  await this.syncDeviceVerifier().catch(() => {});
44047
44562
  await this.stateDeviceVerifier();
44048
44563
  } catch (error) {
@@ -44052,7 +44567,7 @@ var GhostlyNode = class GhostlyNode {
44052
44567
  }
44053
44568
  /** The profile has no verifier any more: its settings, the device state, and what the turn record states. */
44054
44569
  async dropHandoffVerifier() {
44055
- await wrap((await store(STORES$1.settings, "readwrite")).delete(GhostlyNode.HANDOFF_VERIFIER)).catch(() => {});
44570
+ await committed((await store(STORES$1.settings, "readwrite")).delete(GhostlyNode.HANDOFF_VERIFIER)).catch(() => {});
44056
44571
  await this.syncDeviceVerifier().catch(() => {});
44057
44572
  await this.stateDeviceVerifier();
44058
44573
  }
@@ -44430,7 +44945,7 @@ var GhostlyNode = class GhostlyNode {
44430
44945
  throw error;
44431
44946
  }
44432
44947
  if (this.networkOn) this.startLink(id);
44433
- if (expectPeer) this.links.get(id)?.link?.expectPeer();
44948
+ if (expectPeer) this.links.get(id)?.link?.expectPeer(true);
44434
44949
  return id;
44435
44950
  }
44436
44951
  /**
@@ -44800,6 +45315,7 @@ var GhostlyNode = class GhostlyNode {
44800
45315
  } : void 0;
44801
45316
  const resumed = stored.pairedPeerKey && stored.deliveryMode !== "dht" ? resumeHere(this.transportLogOf(live), this.transportsHere(), stored.peerTransports ?? live.caps?.peer?.transports) : {};
44802
45317
  let dhtShown;
45318
+ let dhtFlushed;
44803
45319
  let wasTaken = false;
44804
45320
  live.link = new GhostLink({
44805
45321
  paymentMethods: stored.paymentMethods,
@@ -44929,7 +45445,11 @@ var GhostlyNode = class GhostlyNode {
44929
45445
  onGroupFrame: stored.profile ? (frame) => this.groups.handleContactFrame(linkId, frame) : void 0,
44930
45446
  onGroupsSupport: () => this.emitState(),
44931
45447
  onDhtDelivery: (view) => {
44932
- if (stored.profile && !stored.group) this.outboxes.get(linkId)?.flush().catch(() => {}).then(() => this.editQueues.get(linkId)?.flush()).catch(() => {});
45448
+ const viewed = JSON.stringify(view);
45449
+ if (stored.profile && !stored.group && viewed !== dhtFlushed) {
45450
+ dhtFlushed = viewed;
45451
+ this.outboxes.get(linkId)?.flush().catch(() => {}).then(() => this.editQueues.get(linkId)?.flush()).catch(() => {});
45452
+ }
44933
45453
  this.observeTransport(linkId);
44934
45454
  const taken = !!live.link?.takenFromUs;
44935
45455
  if (taken !== wasTaken) {
@@ -45304,7 +45824,7 @@ var GhostlyNode = class GhostlyNode {
45304
45824
  get nativeFactories() {
45305
45825
  const relay = this.relaysHyperdht ? this.hyperdhtRelay : "";
45306
45826
  return {
45307
- ...relay ? { "hyperdht/1": async (seedB64) => (await import("./hyperdhtRelay-CZfsPfT9.js")).createRelayedHyperEndpoint(seedB64, relay) } : {},
45827
+ ...relay ? { "hyperdht/1": async (seedB64) => (await import("./hyperdhtRelay-C-BsT6_V.js")).createRelayedHyperEndpoint(seedB64, relay) } : {},
45308
45828
  ...this.options.nativeTransports,
45309
45829
  ...this.ownIrohRelays ? { "iroh/1": (seedB64) => this.options.nativeTransports["iroh/1"](seedB64, this.settings.irohRelays?.length ? { relays: [...this.settings.irohRelays] } : {}) } : {},
45310
45830
  ...this.options.irohWeb ? { "iroh/1": (seedB64) => createIrohWebEndpoint(seedB64, { relays: this.irohRelays }) } : {}
@@ -45452,20 +45972,23 @@ var GhostlyNode = class GhostlyNode {
45452
45972
  }
45453
45973
  anchorCheckAt = 0;
45454
45974
  /**
45455
- * A group's edge whose native listener has been up `GROUP_ANCHOR_ANSWER_MS` with no session, and whose member's
45456
- * packet says it holds none there (or it is away): nobody answers it.
45975
+ * A group's edge whose native listener has been up `GROUP_ANCHOR_ANSWER_MS` with no session, and whose member is there
45976
+ * and says in its packet it holds none for it: nobody answers it. Not one whose member is away: no other edge would
45977
+ * be answered either, and the one passed over gave its listener up and asked for none again once its member came
45978
+ * back, whose texts then came only through another member (a hub with no WebRTC, 2026-10-20); nor did passing stop
45979
+ * while every member was away, a listener moving from edge to edge every few minutes for nothing.
45457
45980
  */
45458
45981
  unanswered(live, now) {
45459
45982
  const link = live.link;
45460
- if (!link || link.isDataLinkOpen) return false;
45983
+ if (!link || link.isDataLinkOpen || !live.presence.online) return false;
45461
45984
  const up = Object.keys(this.nativeFactories).filter((t) => link.availableTransports.includes(t)).map((t) => live.nativeUpAt?.[t] ?? now);
45462
45985
  if (!up.length || now - Math.min(...up) < 2e4) return false;
45463
- return !this.chosenByPeer(live) || !live.presence.online;
45986
+ return !this.chosenByPeer(live);
45464
45987
  }
45465
45988
  /**
45466
45989
  * Every few seconds, each group not on screen whose edges run native transports: the one edge it keeps has a
45467
45990
  * listener (or waits for one, `groupNativeWaiting`), and when its member has not answered it in
45468
- * `GROUP_ANCHOR_ANSWER_MS` (it is away, or it has no listener for it: all its own taken), the group keeps the next
45991
+ * `GROUP_ANCHOR_ANSWER_MS` (it is there with no listener for it: all its own taken), the group keeps the next
45469
45992
  * one instead (hub, then admin, then the member heard from last), whose member answers the edge it keeps
45470
45993
  * (`chosenByPeer`). Not while any edge of the group is live: the group is reachable through it. Every other one passed
45471
45994
  * over lately too: the one it keeps stays, without its listener going back and forth.
@@ -45550,6 +46073,17 @@ var GhostlyNode = class GhostlyNode {
45550
46073
  return this.nativeSlots(key) - CHAT_NATIVE_SLOTS;
45551
46074
  }
45552
46075
  /**
46076
+ * The links its groups may have on an app with no WebRTC (`peerRoom`): the transport's listeners that 1:1 chats do
46077
+ * not hold, and what is kept for groups (`groupNativeSlots`) at least. Capped at that alone, a Desktop with no chats
46078
+ * opened four edges in a private group of seven, and the two members left out were never reached, even on screen
46079
+ * with half its listeners free: an edge of the group on screen takes a free listener, or a held one (WISP 902 § Transports).
46080
+ */
46081
+ groupNativeRoom(key) {
46082
+ let chats = 0;
46083
+ for (const live of this.links.values()) if (!live.stored.group && live.link?.availableTransports.includes(key)) chats++;
46084
+ return Math.max(this.groupNativeSlots(key), this.nativeSlots(key) - chats);
46085
+ }
46086
+ /**
45553
46087
  * One transport's listener for one chat, in that transport's queue. "no-slot" when a group's link found no slot free,
45554
46088
  * "failed" when the listener could not start.
45555
46089
  */
@@ -46202,11 +46736,7 @@ var EngineServer = class {
46202
46736
  if (sent.has(link.id)) continue;
46203
46737
  await this.inOrder(link.id, async () => {
46204
46738
  if (!this.clients.has(client)) return;
46205
- client.post(scope.newest ? await this.newestOf(link.id, scope.newest) : {
46206
- kind: "messages",
46207
- linkId: link.id,
46208
- messages: await this.node.getMessages(link.id)
46209
- });
46739
+ client.post(scope.newest ? await this.newestOf(link.id, scope.newest) : this.historyEvent(link.id, await this.node.getMessages(link.id)));
46210
46740
  this.histories.get(client)?.add(link.id);
46211
46741
  });
46212
46742
  }
@@ -46277,29 +46807,21 @@ var EngineServer = class {
46277
46807
  linkId,
46278
46808
  limit
46279
46809
  });
46280
- return {
46281
- kind: "messages",
46282
- linkId,
46283
- messages: page.messages,
46284
- ...page.more ? { more: true } : {}
46285
- };
46810
+ return this.historyEvent(linkId, page.messages, page.more);
46286
46811
  }
46287
46812
  /**
46288
46813
  * A chat's or group's whole history, to this client alone as a `messages` event, after what is still being sent for it
46289
- * (a `HistoryRequest`, which the host hands here): what changes while it is read follows it.
46814
+ * (a `HistoryRequest`, which the host hands here): what changes while it is read follows it. A group's, once the groups
46815
+ * are read, as `groupMessages` answers: a group that opens while the engine starts is not left on its newest page.
46290
46816
  */
46291
46817
  async history(client, linkId) {
46292
46818
  if (typeof linkId !== "string" || !this.clients.has(client)) return;
46293
46819
  try {
46294
- await this.ready;
46820
+ await (linkId.startsWith("group:") ? Promise.race([this.ready, this.node.groupsRead]) : this.ready);
46295
46821
  await this.inOrder(linkId, async () => {
46296
46822
  if (!this.clients.has(client)) return;
46297
46823
  const messages = await this.node.getMessages(linkId);
46298
- if (this.clients.has(client) && this.post(client, {
46299
- kind: "messages",
46300
- linkId,
46301
- messages
46302
- })) this.histories.get(client)?.add(linkId);
46824
+ if (this.clients.has(client) && this.post(client, this.historyEvent(linkId, messages))) this.histories.get(client)?.add(linkId);
46303
46825
  });
46304
46826
  } catch {}
46305
46827
  }
@@ -46314,12 +46836,22 @@ var EngineServer = class {
46314
46836
  });
46315
46837
  return running;
46316
46838
  }
46317
- sendHistory(linkId, messages) {
46318
- this.broadcast({
46839
+ /**
46840
+ * A history (whole, or its newest page with `more`) as a client gets it: with the ids the engine deleted in it, which
46841
+ * a list cannot show.
46842
+ */
46843
+ historyEvent(linkId, messages, more) {
46844
+ const deleted = this.node.deletedIdsOf(linkId);
46845
+ return {
46319
46846
  kind: "messages",
46320
46847
  linkId,
46321
- messages
46322
- });
46848
+ messages,
46849
+ ...more ? { more: true } : {},
46850
+ ...deleted.length > 0 && { deleted }
46851
+ };
46852
+ }
46853
+ sendHistory(linkId, messages) {
46854
+ this.broadcast(this.historyEvent(linkId, messages));
46323
46855
  for (const client of this.clients) this.histories.get(client)?.add(linkId);
46324
46856
  }
46325
46857
  sendChanges(linkId, changes) {
@@ -46339,11 +46871,7 @@ var EngineServer = class {
46339
46871
  return this.node.getMessages(linkId).then((messages) => {
46340
46872
  for (const client of behind) {
46341
46873
  if (!this.clients.has(client)) continue;
46342
- if (this.post(client, {
46343
- kind: "messages",
46344
- linkId,
46345
- messages
46346
- })) this.histories.get(client)?.add(linkId);
46874
+ if (this.post(client, this.historyEvent(linkId, messages))) this.histories.get(client)?.add(linkId);
46347
46875
  }
46348
46876
  });
46349
46877
  }
@@ -46377,4 +46905,4 @@ function signalKind(signal) {
46377
46905
  //#endregion
46378
46906
  export { EngineServer };
46379
46907
 
46380
- //# sourceMappingURL=server-CcAs54Yb.js.map
46908
+ //# sourceMappingURL=server-DOtUKoYR.js.map