@ghostlytools/cli 1.5.1 → 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 (99) hide show
  1. package/README.md +16 -11
  2. package/dist/assets/{api-oUpBfryK.js → api-BIg0Msax.js} +2 -2
  3. package/dist/assets/{api-Dy_05gaq.js → api-d2aXkbM5.js} +343 -116
  4. package/dist/assets/api-d2aXkbM5.js.map +1 -0
  5. package/dist/assets/{apiKit-B-PUYkXH.js → apiKit-Ba_t7MZO.js} +18 -4
  6. package/dist/assets/apiKit-Ba_t7MZO.js.map +1 -0
  7. package/dist/assets/{apps-C6MBfO-I.js → apps-B_F3gEI4.js} +1 -1
  8. package/dist/assets/{apps-ejb6H1lT.js → apps-CJo1MmSY.js} +17 -16
  9. package/dist/assets/apps-CJo1MmSY.js.map +1 -0
  10. package/dist/assets/{arkade-DXyOeKEI.js → arkade-DTne0O3Q.js} +12 -5
  11. package/dist/assets/arkade-DTne0O3Q.js.map +1 -0
  12. package/dist/assets/{backup-DRIIguzE.js → backup-BY88aZr5.js} +11 -8
  13. package/dist/assets/backup-BY88aZr5.js.map +1 -0
  14. package/dist/assets/{backup-Bt6UjCiM.js → backup-CqpDAZZG.js} +1 -1
  15. package/dist/assets/{blobFiles-1wUBd8ZD.js → blobFiles-B1lX6iGy.js} +3 -3
  16. package/dist/assets/{blobFiles-1wUBd8ZD.js.map → blobFiles-B1lX6iGy.js.map} +1 -1
  17. package/dist/assets/{buttons-DoccJ_cK.js → buttons-B5EnA2nh.js} +23 -6
  18. package/dist/assets/buttons-B5EnA2nh.js.map +1 -0
  19. package/dist/assets/buttons-azvbN6xn.js +2 -0
  20. package/dist/assets/{daemonProof-CWTVNUmr.js → daemonProof-Dx3N_DLC.js} +19 -37
  21. package/dist/assets/daemonProof-Dx3N_DLC.js.map +1 -0
  22. package/dist/assets/{endpoint-Cl3cgAYl.js → endpoint-BdaeBw2L.js} +3 -3
  23. package/dist/assets/endpoint-BdaeBw2L.js.map +1 -0
  24. package/dist/assets/{envelope-hJ0SfbAh.js → envelope-BU-BB1wR.js} +2 -2
  25. package/dist/assets/{envelope-hJ0SfbAh.js.map → envelope-BU-BB1wR.js.map} +1 -1
  26. package/dist/assets/{errors-BLSPp0tK.js → errors-DI6Z3jTH.js} +26 -1
  27. package/dist/assets/errors-DI6Z3jTH.js.map +1 -0
  28. package/dist/assets/{fileBytes-gTd_8l-P.js → fileBytes-BMlLVdfg.js} +1 -1
  29. package/dist/assets/{fileBytes-uRqLyxa0.js → fileBytes-D0CYuRwZ.js} +2 -2
  30. package/dist/assets/{fileBytes-uRqLyxa0.js.map → fileBytes-D0CYuRwZ.js.map} +1 -1
  31. package/dist/assets/{fileBytes-B8eTZfAT.js → fileBytes-D85lBh-Q.js} +3 -3
  32. package/dist/assets/{fileBytes-B8eTZfAT.js.map → fileBytes-D85lBh-Q.js.map} +1 -1
  33. package/dist/assets/fileBytesIdb-Dn9levD1.js +2 -0
  34. package/dist/assets/{fileBytesIdb-BIFKtgln.js → fileBytesIdb-LAhH7kY2.js} +7 -7
  35. package/dist/assets/fileBytesIdb-LAhH7kY2.js.map +1 -0
  36. package/dist/assets/{fileBytesOpfs-ChrHcCVV.js → fileBytesOpfs-DjBBghvq.js} +3 -3
  37. package/dist/assets/{fileBytesOpfs-ChrHcCVV.js.map → fileBytesOpfs-DjBBghvq.js.map} +1 -1
  38. package/dist/assets/{ghostly_iroh_web-BsAEFIjl.js → ghostly_iroh_web-BXCsSxxo.js} +29 -29
  39. package/dist/assets/{ghostly_iroh_web-BsAEFIjl.js.map → ghostly_iroh_web-BXCsSxxo.js.map} +1 -1
  40. package/dist/assets/ghostly_iroh_web_bg.wasm +0 -0
  41. package/dist/assets/{groupFiles-BXPINkVJ.js → groupFiles-D9k6fyhf.js} +61 -17
  42. package/dist/assets/groupFiles-D9k6fyhf.js.map +1 -0
  43. package/dist/assets/{host-CzgYwupN.js → host-DrL7FPG4.js} +157 -49
  44. package/dist/assets/host-DrL7FPG4.js.map +1 -0
  45. package/dist/assets/{hyperdhtRelay-CJBqsS_e.js → hyperdhtRelay-C-BsT6_V.js} +2 -2
  46. package/dist/assets/{hyperdhtRelay-CJBqsS_e.js.map → hyperdhtRelay-C-BsT6_V.js.map} +1 -1
  47. package/dist/assets/{idb-BJARz3Qi.js → idb-CWvq4HKc.js} +25 -3
  48. package/dist/assets/{idb-BJARz3Qi.js.map → idb-CWvq4HKc.js.map} +1 -1
  49. package/dist/assets/{irohWeb-CrGOD-OD.js → irohWeb-DdHXEwgj.js} +3 -3
  50. package/dist/assets/{irohWeb-CrGOD-OD.js.map → irohWeb-DdHXEwgj.js.map} +1 -1
  51. package/dist/assets/{main-BDOIJ_ls.js → main-xeoX7yLM.js} +160 -50
  52. package/dist/assets/main-xeoX7yLM.js.map +1 -0
  53. package/dist/assets/{mainline-Cw7rnEWM.js → mainline-CEqGvRYJ.js} +46 -16
  54. package/dist/assets/mainline-CEqGvRYJ.js.map +1 -0
  55. package/dist/assets/{networkReason-C0VY94cG.js → networkReason-RGRU5xoa.js} +3 -3
  56. package/dist/assets/{networkReason-C0VY94cG.js.map → networkReason-RGRU5xoa.js.map} +1 -1
  57. package/dist/assets/{nwc-lpGWvzYU.js → nwc-s5xHLqNf.js} +3 -3
  58. package/dist/assets/{nwc-lpGWvzYU.js.map → nwc-s5xHLqNf.js.map} +1 -1
  59. package/dist/assets/{nwcProvider-CAGRn2ly.js → nwcProvider-CfAFO5Fr.js} +2 -2
  60. package/dist/assets/{nwcProvider-CAGRn2ly.js.map → nwcProvider-CfAFO5Fr.js.map} +1 -1
  61. package/dist/assets/{profiles-BehWURA9.js → profiles-gZdQPyaz.js} +74 -13
  62. package/dist/assets/profiles-gZdQPyaz.js.map +1 -0
  63. package/dist/assets/{registry-D2bK-k1T.js → registry-BUhSjM-J.js} +1 -1
  64. package/dist/assets/{registry-DWkkBN57.js → registry-CVUdD4bJ.js} +3 -3
  65. package/dist/assets/{registry-DWkkBN57.js.map → registry-CVUdD4bJ.js.map} +1 -1
  66. package/dist/assets/{resolve-CvYK0Lbt.js → resolve-uZECJ3f7.js} +2 -2
  67. package/dist/assets/{resolve-CvYK0Lbt.js.map → resolve-uZECJ3f7.js.map} +1 -1
  68. package/dist/assets/{restoredRows-DGuKtIBz.js → restoredRows-D6WZUA2U.js} +2 -2
  69. package/dist/assets/{restoredRows-DGuKtIBz.js.map → restoredRows-D6WZUA2U.js.map} +1 -1
  70. package/dist/assets/{server-BktMmp7L.js → server-DOtUKoYR.js} +797 -251
  71. package/dist/assets/server-DOtUKoYR.js.map +1 -0
  72. package/dist/assets/{src-Bpy99Z2K.js → src-Dd_7Ew1X.js} +512 -141
  73. package/dist/assets/src-Dd_7Ew1X.js.map +1 -0
  74. package/dist/assets/{usdt-DFusiw8x.js → usdt-C2Anx8p7.js} +3 -3
  75. package/dist/assets/{usdt-DFusiw8x.js.map → usdt-C2Anx8p7.js.map} +1 -1
  76. package/dist/assets/{words-Z-izzDBN.js → words-DoLU6p8H.js} +4 -4
  77. package/dist/assets/words-DoLU6p8H.js.map +1 -0
  78. package/dist/ghostly.mjs +1 -1
  79. package/package.json +1 -1
  80. package/dist/assets/api-Dy_05gaq.js.map +0 -1
  81. package/dist/assets/apiKit-B-PUYkXH.js.map +0 -1
  82. package/dist/assets/apps-ejb6H1lT.js.map +0 -1
  83. package/dist/assets/arkade-DXyOeKEI.js.map +0 -1
  84. package/dist/assets/backup-DRIIguzE.js.map +0 -1
  85. package/dist/assets/buttons-B3bi6p_d.js +0 -2
  86. package/dist/assets/buttons-DoccJ_cK.js.map +0 -1
  87. package/dist/assets/daemonProof-CWTVNUmr.js.map +0 -1
  88. package/dist/assets/endpoint-Cl3cgAYl.js.map +0 -1
  89. package/dist/assets/errors-BLSPp0tK.js.map +0 -1
  90. package/dist/assets/fileBytesIdb-BIFKtgln.js.map +0 -1
  91. package/dist/assets/fileBytesIdb-BVVr_rWX.js +0 -2
  92. package/dist/assets/groupFiles-BXPINkVJ.js.map +0 -1
  93. package/dist/assets/host-CzgYwupN.js.map +0 -1
  94. package/dist/assets/main-BDOIJ_ls.js.map +0 -1
  95. package/dist/assets/mainline-Cw7rnEWM.js.map +0 -1
  96. package/dist/assets/profiles-BehWURA9.js.map +0 -1
  97. package/dist/assets/server-BktMmp7L.js.map +0 -1
  98. package/dist/assets/src-Bpy99Z2K.js.map +0 -1
  99. package/dist/assets/words-Z-izzDBN.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-Bpy99Z2K.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-CAGRn2ly.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-C0VY94cG.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-BXPINkVJ.js";
9
- import { i as fedimintDatabase, n as createIrohWebEndpoint, o as loadFedimintSdk, r as irohRelayProblem, t as DEFAULT_IROH_RELAYS } from "./irohWeb-CrGOD-OD.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-CvYK0Lbt.js";
12
- import { i as fromBase64Url$1, n as MAX_BACKUP_BYTES, t as BACKUP_MEDIA_TYPE } from "./envelope-hJ0SfbAh.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-DFusiw8x.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-DXyOeKEI.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-D2bK-k1T.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,
@@ -23559,13 +23609,17 @@ var Communities = class {
23559
23609
  if (existing?.joining && existing.joining.host === link.host) return link.g;
23560
23610
  if (live) {
23561
23611
  const s = live.session;
23612
+ const door = s.entryKey === link.host;
23562
23613
  if (s.status === "active" && s.roster.length === 1) return link.g;
23563
23614
  if (s.status === "active") {
23564
- await this.startJoining(link, s.state.seedB64, this.now(), true);
23615
+ if (s.entryKey) await this.startJoining(door ? link : {
23616
+ g: link.g,
23617
+ host: s.entryKey
23618
+ }, s.state.seedB64, this.now(), true);
23565
23619
  return link.g;
23566
23620
  }
23567
23621
  if (s.status === "removed" || s.status === "lost") {
23568
- await this.startJoining(link, s.state.seedB64, this.now());
23622
+ await this.startJoining(link, door ? s.state.seedB64 : dialedKey(link), this.now());
23569
23623
  return link.g;
23570
23624
  }
23571
23625
  }
@@ -23703,7 +23757,8 @@ var Communities = class {
23703
23757
  await this.forget(groupId);
23704
23758
  return;
23705
23759
  }
23706
- 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));
23707
23762
  if (!edges.length) throw new Error("Nobody in the group is connected right now to take your leave. Try again in a moment.");
23708
23763
  let next;
23709
23764
  if (s.isAdmin) {
@@ -23795,9 +23850,7 @@ var Communities = class {
23795
23850
  if (live?.hub) await this.publishBeacon(groupId, live, this.now(), false).catch(() => {});
23796
23851
  this.live.delete(groupId);
23797
23852
  this.stored.delete(groupId);
23798
- this.lastMessageAt.delete(groupId);
23799
- this.lastPeerMessageAt.delete(groupId);
23800
- this.lastMentionAt.delete(groupId);
23853
+ dropMarks(this.marks, groupId);
23801
23854
  this.knockingWith.delete(groupId);
23802
23855
  this.knockRead.delete(groupId);
23803
23856
  this.lineOrder.forget(MESSAGE_LINK$1(groupId));
@@ -23824,9 +23877,11 @@ var Communities = class {
23824
23877
  for (const group of [...this.stored.values()]) {
23825
23878
  const live = this.live.get(group.id);
23826
23879
  if (group.joining && (this.knocking(group, live) || group.joining.check)) {
23827
- const waited = now - group.joining.since, every = waited > this.timings.patienceMs ? this.timings.slowKnockMs : this.timings.knockMs;
23828
- if (!this.knocking(group, live) && waited > CHECK_MS) await this.endCheck(group);
23829
- 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(() => {});
23830
23885
  if (!live) continue;
23831
23886
  }
23832
23887
  if (!live) continue;
@@ -24926,7 +24981,7 @@ var Communities = class {
24926
24981
  message: async (m) => {
24927
24982
  const timestamp = m.timestamp;
24928
24983
  const mentioned = m.sender !== session.myKey && mentionsMember(m.mentions, session.myKey);
24929
- 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, {
24930
24985
  id: m.id,
24931
24986
  sender: m.sender,
24932
24987
  ts: m.timestamp,
@@ -24952,10 +25007,9 @@ var Communities = class {
24952
25007
  ...file && { file }
24953
25008
  });
24954
25009
  placing(stored !== false);
25010
+ if (stored === false && this.stored.get(id)?.removedIds?.includes(m.id)) return;
24955
25011
  const came = m.sender === session.myKey ? timestamp : cameAt(timestamp, stored, arrivalNow(this.now()));
24956
- this.lastMessageAt.set(id, Math.max(this.lastMessageAt.get(id) ?? 0, came));
24957
- if (mentioned) this.lastMentionAt.set(id, Math.max(this.lastMentionAt.get(id) ?? 0, came));
24958
- 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);
24959
25013
  noteCame(this.stored.get(id), came, m.sender !== session.myKey, mentioned);
24960
25014
  },
24961
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)),
@@ -24976,6 +25030,7 @@ var Communities = class {
24976
25030
  seqFloor: () => this.host.seqFloor?.() ?? 0,
24977
25031
  adminWork: () => this.host.adminWork?.(id) ?? true,
24978
25032
  adminTurn: () => this.host.adminTurn?.(id) ?? Promise.resolve(true),
25033
+ removed: (messageId) => !!this.stored.get(id)?.removedIds?.includes(messageId),
24979
25034
  relay: (frame) => {
24980
25035
  if (this.live.get(id)?.hub) for (const [, linkId] of this.hearers(id, frame)) this.sendTo(linkId, frame);
24981
25036
  },
@@ -25114,6 +25169,19 @@ var GONE_LINGER_MS = 15e3;
25114
25169
  */
25115
25170
  var HUB_CLOCK_READ_GAP_MS = 75e3;
25116
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
+ /**
25117
25185
  * The hubs of the private groups this device is in (WISP 902 · Group Mesh § Hubs): whether a group runs on hubs, who
25118
25186
  * they are (the community's sealed beacon and lobbies, under the epoch's rendezvous secret), whether I am one, which
25119
25187
  * edges that asks for, and passing frames on as a hub. `Groups` owns the sessions and the edges; this decides.
@@ -25159,6 +25227,9 @@ var MeshHubs = class {
25159
25227
  lastRead: 0,
25160
25228
  lastWrite: 0,
25161
25229
  lastTry: 0,
25230
+ publishAfter: 0,
25231
+ readAt: 0,
25232
+ stepUpAt: 0,
25162
25233
  hub: false,
25163
25234
  hubSince: 0,
25164
25235
  members: /* @__PURE__ */ new Map(),
@@ -25357,6 +25428,9 @@ var MeshHubs = class {
25357
25428
  live.lastTry = 0;
25358
25429
  live.beacon = [];
25359
25430
  live.epochRead = false;
25431
+ live.publishAfter = 0;
25432
+ live.stepUpAt = 0;
25433
+ live.readAt = 0;
25360
25434
  live.clocks.restart();
25361
25435
  }
25362
25436
  const policy = session.hubPolicy, me = session.myKey, inRoster = (key) => rosterHas(session.roster, key);
@@ -25366,7 +25440,11 @@ var MeshHubs = class {
25366
25440
  const others = this.listed(live, session, now);
25367
25441
  const fits = this.fits(groupId, session);
25368
25442
  if (live.hub) live.need = session.others.length;
25369
- 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))) {
25370
25448
  live.hub = true;
25371
25449
  live.hubSince = now;
25372
25450
  live.myHubs = [];
@@ -25376,7 +25454,7 @@ var MeshHubs = class {
25376
25454
  live.hub = false;
25377
25455
  live.members.clear();
25378
25456
  if (!may || !fits) await this.publish(groupId, session, live, now, false).catch(() => {});
25379
- } 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(() => {});
25380
25458
  if (live.hub) {
25381
25459
  await this.serve(groupId, session, live, now, rv);
25382
25460
  const hubs = others.map((h) => h.key).sort();
@@ -25393,7 +25471,18 @@ var MeshHubs = class {
25393
25471
  * pinned hub lists itself whatever the beacon holds.
25394
25472
  */
25395
25473
  full(live, session, now) {
25396
- 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;
25397
25486
  }
25398
25487
  shape(live) {
25399
25488
  return `${live.hub}|${live.myHubs.join(",")}|${[...live.members.keys()].sort().join(",")}|${live.beacon.map((h) => h.key).sort().join(",")}`;
@@ -25407,11 +25496,18 @@ var MeshHubs = class {
25407
25496
  } catch {
25408
25497
  return;
25409
25498
  }
25499
+ if (this.held(keys.identity.pubKeyZ32)) return;
25410
25500
  live.beacon = live.clocks.inMyTime(readBeacon(keys, records ?? []), now);
25411
25501
  live.firstRead = true;
25412
25502
  live.epochRead = true;
25503
+ live.readAt = now;
25413
25504
  this.noteHubs(live, session, now);
25414
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
+ }
25415
25511
  noteHubs(live, session, now) {
25416
25512
  for (const h of this.listed(live, session, now)) live.seenHubs.set(h.key, now);
25417
25513
  for (const [key, at] of live.seenHubs) if (now - at > this.timings.graceMs || !rosterHas(session.roster, key)) live.seenHubs.delete(key);
@@ -25428,10 +25524,17 @@ var MeshHubs = class {
25428
25524
  let records;
25429
25525
  try {
25430
25526
  records = await this.host.resolve(keys.identity.pubKeyZ32, true);
25431
- } 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;
25432
25534
  return;
25433
25535
  }
25434
25536
  existing = live.clocks.inMyTime(readBeacon(keys, records ?? []), now);
25537
+ live.readAt = now;
25435
25538
  if (listed) {
25436
25539
  live.beacon = existing;
25437
25540
  live.lastRead = now;
@@ -25448,14 +25551,27 @@ var MeshHubs = class {
25448
25551
  load: live.members.size,
25449
25552
  since: live.hubSince || now
25450
25553
  } : null, now, (key) => rosterHas(session.roster, key) && !policy.no.includes(key));
25451
- 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
+ }
25452
25560
  live.beacon = hubs;
25453
25561
  live.lastWrite = now;
25454
25562
  live.lastRead = now;
25563
+ live.readAt = now;
25455
25564
  live.firstRead = true;
25456
25565
  live.epochRead = true;
25457
25566
  this.noteHubs(live, session, now);
25458
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
+ }
25459
25575
  /** As a hub: who asked in my lobby, and which of my members are still around. */
25460
25576
  async serve(groupId, session, live, now, rv) {
25461
25577
  const edges = this.host.edges(groupId);
@@ -25690,6 +25806,12 @@ function authorOf(frame) {
25690
25806
  default: return;
25691
25807
  }
25692
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
+ }
25693
25815
  //#endregion
25694
25816
  //#region ../browser/src/engine/groupTyping.ts
25695
25817
  /**
@@ -26070,11 +26192,111 @@ function noteCame(group, came, peer, mentioned) {
26070
26192
  }
26071
26193
  /** What `load` starts the unread marks from: the history's own times, or when its latest came if that was later. */
26072
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
+ }
26073
26201
  /** The view's `lastPeerMessageAt`, when there is one. */
26074
26202
  var peerMessageAt = (map, groupId) => {
26075
26203
  const at = map.get(groupId);
26076
26204
  return at ? { lastPeerMessageAt: at } : {};
26077
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
+ }
26078
26300
  var ENTRY_TIMINGS = {
26079
26301
  pollMs: 5e3,
26080
26302
  warmPollMs: 2e3,
@@ -26083,6 +26305,32 @@ var ENTRY_TIMINGS = {
26083
26305
  slowKnockMs: 2e4,
26084
26306
  patienceMs: 12e4
26085
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
+ }
26086
26334
  var KNOCK_VERIFY_SPREAD_MS = 700;
26087
26335
  /** Entry sessions the admin runs at once; a joiner who does not finish in time is not answered again for a while. */
26088
26336
  var MAX_PENDING_ENTRIES = 4;
@@ -26137,17 +26385,6 @@ function invitationClaims(frame) {
26137
26385
  var FAREWELL_ANSWERS = 3;
26138
26386
  /** Commits sent to a removed member that was behind when it left, at most. */
26139
26387
  var FAREWELL_COMMITS = 64;
26140
- /**
26141
- * A member whose messages were just asked of another (`Groups.askOf`) is told where I am only once that one's answer
26142
- * has come: no message of it for this long, or `MESH_SYNC_HOLD_MAX_MS` after it was asked. Told at once, its own
26143
- * answer raced the other's, which holds the same messages among everyone's in the order they were written, and a
26144
- * member back in a group of five read each member's lines apart, the newest above older ones (WISP 902 § Catch-up).
26145
- * A message of the answer is one written before the asking: what the member writes meanwhile is no reason to wait, so
26146
- * the longest wait only has to cover a whole answer (the 256 messages a member keeps for the others and its own last
26147
- * 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
26148
- * second was cut at the 40th, and the others' newest lines landed above what was still coming.
26149
- */
26150
- var MESH_SYNC_HOLD_MS = 1500;
26151
26388
  /** Where a member's gossip turns start among the members it is connected to: a number of its own, from its key. */
26152
26389
  var gossipStart = (key) => {
26153
26390
  let n = 0;
@@ -26219,6 +26456,13 @@ var Groups = class {
26219
26456
  lastPeerMessageAt = /* @__PURE__ */ new Map();
26220
26457
  /** The latest message that names me, per group (the chat list's "@" while it is unread). */
26221
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
+ };
26222
26466
  reconciling = Promise.resolve();
26223
26467
  /** Admin side: joiners with an entry session open, per group: member key → since when. */
26224
26468
  pendingEntries = /* @__PURE__ */ new Map();
@@ -26377,7 +26621,7 @@ var Groups = class {
26377
26621
  await this.communities.load(all.filter((g) => g.community || g.joining));
26378
26622
  for (const group of all.filter((g) => !g.community && !g.joining)) {
26379
26623
  this.stored.set(group.id, group);
26380
- 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));
26381
26625
  const framed = history.filter((m) => m.frame);
26382
26626
  this.framesKept.set(group.id, framed.map((m) => ({
26383
26627
  id: m.id,
@@ -26385,13 +26629,8 @@ var Groups = class {
26385
26629
  })));
26386
26630
  if (group.state) this.attach(group.state, framed.map((m) => m.frame));
26387
26631
  if (group.invited) this.invited.set(group.id, new Set(Object.keys(group.invited)));
26388
- const last = said[said.length - 1], lastPeer = [...said].reverse().find((m) => m.sender !== "me");
26389
- if (last) this.lastMessageAt.set(group.id, last.timestamp);
26390
- const peerAt = cameOrWritten(lastPeer?.timestamp, lastPeer ? group.came?.peer : void 0);
26391
- if (peerAt) this.lastPeerMessageAt.set(group.id, peerAt);
26392
- const mention = [...history].reverse().find((m) => m.mentioned);
26393
- const mentionAt = cameOrWritten(mention?.timestamp, mention ? group.came?.mention : void 0);
26394
- if (mentionAt) this.lastMentionAt.set(group.id, mentionAt);
26632
+ loadMarks(this.marks, group, history);
26633
+ this.host.loaded?.(group.id, history);
26395
26634
  }
26396
26635
  for (const id of this.sessions.keys()) this.reconcileEdges(id);
26397
26636
  await this.files?.load(all.map((g) => g.id));
@@ -26433,7 +26672,12 @@ var Groups = class {
26433
26672
  return view && this.pinned(view);
26434
26673
  }
26435
26674
  pinned(view) {
26436
- 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);
26437
26681
  return pin ? {
26438
26682
  ...view,
26439
26683
  pin
@@ -26909,9 +27153,7 @@ var Groups = class {
26909
27153
  this.pendingEntries.delete(groupId);
26910
27154
  this.welcomed.delete(groupId);
26911
27155
  this.lingering.delete(groupId);
26912
- this.lastMessageAt.delete(groupId);
26913
- this.lastPeerMessageAt.delete(groupId);
26914
- this.lastMentionAt.delete(groupId);
27156
+ dropMarks(this.marks, groupId);
26915
27157
  this.authorOrder.forget(groupId);
26916
27158
  this.lineOrder.forget(MESSAGE_LINK(groupId));
26917
27159
  await this.store.deleteGroup(groupId);
@@ -27050,8 +27292,23 @@ var Groups = class {
27050
27292
  group.removedIds = [...group.removedIds ?? [], messageId].slice(-500);
27051
27293
  await this.store.putGroup(group);
27052
27294
  }
27295
+ this.communities.session(groupId)?.forget(messageId);
27053
27296
  await this.files?.forget(groupId, messageId);
27054
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
+ }
27055
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. */
27056
27313
  edgeOpen(groupId, peerKey) {
27057
27314
  const group = this.stored.get(groupId), farewell = group?.farewells?.[peerKey];
@@ -27293,8 +27550,10 @@ var Groups = class {
27293
27550
  continue;
27294
27551
  }
27295
27552
  if (group.invitation?.entry && !group.state) {
27296
- const every = now - group.createdAt > this.timings.patienceMs ? this.timings.slowKnockMs : this.timings.knockMs;
27297
- 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(() => {});
27298
27557
  continue;
27299
27558
  }
27300
27559
  if (group.invitation?.seedB64 && !group.state) {
@@ -27542,7 +27801,7 @@ var Groups = class {
27542
27801
  }, now)));
27543
27802
  const rewrites = (this.knockRewrites.get(group.id) ?? 0) + 1;
27544
27803
  this.knockRewrites.set(group.id, rewrites);
27545
- 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);
27546
27805
  traceJoin(group.id, "knock.published", { ms: Date.now() - started });
27547
27806
  if (!this.knocked.has(group.id)) {
27548
27807
  this.knocked.add(group.id);
@@ -27558,9 +27817,11 @@ var Groups = class {
27558
27817
  knocks: knocks.length
27559
27818
  });
27560
27819
  let pending = this.pendingEntries.get(group.id);
27820
+ let ever;
27561
27821
  for (const { key, ts } of knocks) {
27562
27822
  const again = this.unwelcomed(group, session, key);
27563
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;
27564
27825
  if (again && this.rewelcomedLately(group.id, key)) continue;
27565
27826
  const entryIds = new Set(this.host.entries(group.id).values());
27566
27827
  const contactsInvited = [...this.invited.get(group.id) ?? []].filter((id) => !entryIds.has(id)).length;
@@ -28174,12 +28435,16 @@ var Groups = class {
28174
28435
  }
28175
28436
  /**
28176
28437
  * Whether the answer of the member asked for someone's messages may still be coming: its edge up, asked under
28177
- * `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.
28178
28442
  */
28179
28443
  answering(groupId, { via, at }, now) {
28180
28444
  const edge = this.host.edges(groupId).get(via);
28181
- if (!edge || !this.host.linkReady(edge) || now - at >= 18e4) return false;
28182
- 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;
28183
28448
  }
28184
28449
  /**
28185
28450
  * Whether the sync to a member whose edge just opened waits (`heldSyncs` sends it): its messages were asked of
@@ -28504,6 +28769,7 @@ var Groups = class {
28504
28769
  seqFloor: () => this.host.seqFloor?.() ?? 0,
28505
28770
  adminWork: () => this.host.adminWork?.(state.id) ?? true,
28506
28771
  adminTurn: () => this.host.adminTurn?.(state.id) ?? Promise.resolve(true),
28772
+ removed: (id) => this.isRemoved(state.id, id),
28507
28773
  save: async (next) => {
28508
28774
  const group = this.stored.get(state.id);
28509
28775
  if (!group || this.sessions.get(state.id) !== session) return;
@@ -28531,7 +28797,7 @@ var Groups = class {
28531
28797
  message: async (m) => {
28532
28798
  const timestamp = m.timestamp;
28533
28799
  const mentioned = m.sender !== session.myKey && mentionsMember(m.mentions, session.myKey);
28534
- 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, {
28535
28801
  id: m.id,
28536
28802
  sender: m.sender,
28537
28803
  ts: m.timestamp,
@@ -28574,10 +28840,12 @@ var Groups = class {
28574
28840
  ...row,
28575
28841
  at: this.now()
28576
28842
  }, placedAbove);
28843
+ if (stored === false && !completed && this.isRemoved(state.id, m.id)) {
28844
+ this.typings.messageFrom(state.id, m.sender);
28845
+ return;
28846
+ }
28577
28847
  const came = m.sender === session.myKey ? timestamp : cameAt(timestamp, stored, arrivalNow(this.now()));
28578
- this.lastMessageAt.set(state.id, Math.max(this.lastMessageAt.get(state.id) ?? 0, came));
28579
- if (mentioned) this.lastMentionAt.set(state.id, Math.max(this.lastMentionAt.get(state.id) ?? 0, came));
28580
- 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);
28581
28849
  noteCame(this.stored.get(state.id), came, m.sender !== session.myKey, mentioned);
28582
28850
  this.typings.messageFrom(state.id, m.sender);
28583
28851
  },
@@ -28588,10 +28856,10 @@ var Groups = class {
28588
28856
  edit: (e) => this.host.groupEdit?.(state.id, e),
28589
28857
  changed: () => {
28590
28858
  if (session.status === "removed" && this.hubs.isHub(state.id) && !this.removedAt.has(state.id)) this.removedAt.set(state.id, this.now());
28591
- this.membershipChanged(state.id);
28859
+ this.membershipChanged(state.id).catch(() => {});
28592
28860
  },
28593
28861
  metaChanged: (by, change, at) => {
28594
- this.metaChanged(state.id, session, by, change, at);
28862
+ this.metaChanged(state.id, session, by, change, at).catch(() => {});
28595
28863
  },
28596
28864
  ...this.host.linkHandled && { handled: (to) => {
28597
28865
  const edge = this.host.edges(state.id).get(to);
@@ -28968,6 +29236,8 @@ function authoredNote(p, at, all, current, memberOf = () => void 0, federationNe
28968
29236
  var GroupPayments = class {
28969
29237
  host;
28970
29238
  notes = /* @__PURE__ */ new Map();
29239
+ /** Per group, the ids of others' notes still `undescribed`, oldest first. */
29240
+ waiting = /* @__PURE__ */ new Map();
28971
29241
  queue = Promise.resolve();
28972
29242
  constructor(host) {
28973
29243
  this.host = host;
@@ -29051,7 +29321,18 @@ var GroupPayments = class {
29051
29321
  return notes;
29052
29322
  }
29053
29323
  async write(groupId, me, note) {
29054
- this.notes.get(groupId)?.set(note.id, note);
29324
+ const notes = this.notes.get(groupId);
29325
+ notes?.set(note.id, note);
29326
+ let waiting = this.waiting.get(groupId);
29327
+ if (note.undescribed && !note.mine) {
29328
+ if (!waiting) this.waiting.set(groupId, waiting = /* @__PURE__ */ new Set());
29329
+ waiting.add(note.id);
29330
+ for (const id of waiting) {
29331
+ if (waiting.size <= 256) break;
29332
+ waiting.delete(id);
29333
+ notes?.delete(id);
29334
+ }
29335
+ } else waiting?.delete(note.id);
29055
29336
  if (note.undescribed) return;
29056
29337
  const initiator = note.kind === "request" ? note.to : note.from;
29057
29338
  await this.host.putMessage({
@@ -29114,6 +29395,8 @@ var GroupEdits = class {
29114
29395
  heard = /* @__PURE__ */ new Map();
29115
29396
  /** The connection `resend` last spoke on, per group and member: a new one hears my latest edits again. */
29116
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();
29117
29400
  resendPace = /* @__PURE__ */ new Map();
29118
29401
  resendTimers = /* @__PURE__ */ new Map();
29119
29402
  resending = /* @__PURE__ */ new Map();
@@ -29414,23 +29697,30 @@ var GroupEdits = class {
29414
29697
  * A new connection hears my latest `GROUP_EDIT_RESEND` again whatever it heard: one may have come before its message
29415
29698
  * and been dropped. Called again while the edge is the same, it goes on from where it was.
29416
29699
  */
29417
- resend(groupId, to) {
29700
+ resend(groupId, to, paced = false) {
29418
29701
  const key = resendKey(groupId, to);
29419
- 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));
29420
29703
  const settled = run.catch(() => {}).finally(() => {
29421
29704
  if (this.resending.get(key) === settled) this.resending.delete(key);
29422
29705
  });
29423
29706
  this.resending.set(key, settled);
29424
29707
  return run;
29425
29708
  }
29426
- 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) {
29427
29715
  const key = resendKey(groupId, to), chat = chatOf(groupId);
29428
29716
  clearTimeout(this.resendTimers.get(key));
29429
29717
  this.resendTimers.delete(key);
29430
29718
  const open = () => this.host.edge ? this.host.edge(groupId, to) : true;
29431
29719
  const edge = open(), membership = this.host.membership(groupId);
29720
+ const kept = this.keptMine.get(key);
29721
+ this.keptMine.delete(key);
29432
29722
  if (this.stopped || edge === void 0 || !membership || membership.community || !membership.members.has(to)) return;
29433
- 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));
29434
29724
  const last = this.heard.get(key);
29435
29725
  const after = (m) => !last || m.edit.at > last.at || m.edit.at === last.at && m.id > last.id;
29436
29726
  const unheard = last ? mine.filter(after).length : Math.min(mine.length, 256);
@@ -29442,8 +29732,12 @@ var GroupEdits = class {
29442
29732
  for (const m of due) {
29443
29733
  if (this.stopped || open() !== edge) return;
29444
29734
  if (!pace.take()) {
29735
+ this.keptMine.set(key, {
29736
+ edge,
29737
+ mine
29738
+ });
29445
29739
  this.resendTimers.set(key, setTimeout(() => {
29446
- this.resend(groupId, to).catch(() => {});
29740
+ this.resend(groupId, to, true).catch(() => {});
29447
29741
  }, Math.max(50, pace.wait())));
29448
29742
  return;
29449
29743
  }
@@ -29465,6 +29759,7 @@ var GroupEdits = class {
29465
29759
  for (const key of [...this.heard.keys()]) if (of(key)) this.heard.delete(key);
29466
29760
  for (const key of [...this.resendPace.keys()]) if (of(key)) this.resendPace.delete(key);
29467
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);
29468
29763
  }
29469
29764
  forget(groupId) {
29470
29765
  clearTimeout(this.timers.get(groupId));
@@ -31841,6 +32136,8 @@ var SWAP_POLL_MS = 3e4;
31841
32136
  var SWAP_SLOW_POLL_MS = 6e5;
31842
32137
  /** How long a swap whose inputs were given back is still asked about, in case the mint made it after all. */
31843
32138
  var SWAP_WATCH_MS = 36e5;
32139
+ /** How many proofs of tokens refused as spent are remembered. */
32140
+ var SPENT_KEPT = 1e3;
31844
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. */
31845
32142
  var loadCashu = () => import("@cashu/cashu-ts");
31846
32143
  async function reviewedCashuFee(preview) {
@@ -31941,6 +32238,11 @@ var CashuWallet = class CashuWallet {
31941
32238
  failedFees = /* @__PURE__ */ new Map();
31942
32239
  /** Melt quotes that ended unpaid with proofs the mint read spent: ecash spent somewhere else, said as such. */
31943
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();
31944
32246
  /** Per melt quote shown to the person: the invoice, its amount and the fee reserve the mint quoted. Only these are paid. */
31945
32247
  shownQuotes = /* @__PURE__ */ new Map();
31946
32248
  /**
@@ -32110,7 +32412,7 @@ var CashuWallet = class CashuWallet {
32110
32412
  paymentId,
32111
32413
  ...paysItsOwnInvoices(mint) ? { held: true } : {}
32112
32414
  };
32113
- await wrap((await store(STORES$1.quotes, "readwrite")).put(quote));
32415
+ await committed((await store(STORES$1.quotes, "readwrite")).put(quote));
32114
32416
  this.pollQuotes();
32115
32417
  return quote;
32116
32418
  }
@@ -32123,7 +32425,7 @@ var CashuWallet = class CashuWallet {
32123
32425
  const wanted = invoice.trim().toLowerCase();
32124
32426
  const quote = (await wrap((await store(STORES$1.quotes, "readonly")).getAll())).find((q) => q.invoice.toLowerCase() === wanted);
32125
32427
  if (!quote) return false;
32126
- 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({
32127
32429
  ...quote,
32128
32430
  held: void 0
32129
32431
  }));
@@ -32153,7 +32455,7 @@ var CashuWallet = class CashuWallet {
32153
32455
  expiresAt: response.expiry ? response.expiry * 1e3 : null,
32154
32456
  testCoins: true
32155
32457
  };
32156
- await wrap((await store(STORES$1.quotes, "readwrite")).put(quote));
32458
+ await committed((await store(STORES$1.quotes, "readwrite")).put(quote));
32157
32459
  const deadline = Date.now() + TEST_COINS_WAIT_MS;
32158
32460
  for (;;) {
32159
32461
  if (await this.locked(mint, () => this.settleQuote(quote.quote))) {
@@ -32192,7 +32494,7 @@ var CashuWallet = class CashuWallet {
32192
32494
  this.quoteTimer = null;
32193
32495
  if (this.stopped) return;
32194
32496
  const quotes = await wrap((await store(STORES$1.quotes, "readonly")).getAll());
32195
- 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));
32196
32498
  await this.settleQuotes(quotes);
32197
32499
  const remaining = await wrap((await store(STORES$1.quotes, "readonly")).getAll());
32198
32500
  if (!this.stopped && remaining.some((q) => !q.issuedUnclaimed && !q.held)) this.quoteTimer = setTimeout(() => void this.pollQuotes(), QUOTE_POLL_MS);
@@ -32215,7 +32517,7 @@ var CashuWallet = class CashuWallet {
32215
32517
  const answer = await wallet.checkMintQuoteBolt11(quote.quote);
32216
32518
  const { state } = answer;
32217
32519
  if (state === "UNPAID") {
32218
- 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));
32219
32521
  return null;
32220
32522
  }
32221
32523
  const saved = quote.outputs?.map((o) => OutputData.deserialize(o));
@@ -32223,7 +32525,7 @@ var CashuWallet = class CashuWallet {
32223
32525
  const issued = saved?.length ? await this.signedOutputs(wallet, saved) : void 0;
32224
32526
  if (Array.isArray(issued)) return this.storeMinted(quote, issued);
32225
32527
  console.warn(`[wallet] ${quote.mint} issued quote ${quote.quote} (${quote.amount} sats) but this wallet holds no ecash for it`);
32226
- await wrap((await store(STORES$1.quotes, "readwrite")).put({
32528
+ await committed((await store(STORES$1.quotes, "readwrite")).put({
32227
32529
  ...quote,
32228
32530
  issuedUnclaimed: true
32229
32531
  }));
@@ -32239,14 +32541,14 @@ var CashuWallet = class CashuWallet {
32239
32541
  paid: true,
32240
32542
  outputs: saved ? quote.outputs : preview.outputData.map((o) => OutputData.serialize(o))
32241
32543
  };
32242
- 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));
32243
32545
  let proofs;
32244
32546
  try {
32245
32547
  proofs = await wallet.completeMint(preview);
32246
32548
  } catch (error) {
32247
32549
  if (saved && isMintOperationError(error) && (await wallet.checkMintQuoteBolt11(quote.quote).catch(() => null))?.state === "PAID") {
32248
32550
  const { outputs: _refused, ...fresh } = written;
32249
- await wrap((await store(STORES$1.quotes, "readwrite")).put(fresh));
32551
+ await committed((await store(STORES$1.quotes, "readwrite")).put(fresh));
32250
32552
  }
32251
32553
  throw error;
32252
32554
  }
@@ -32637,6 +32939,7 @@ var CashuWallet = class CashuWallet {
32637
32939
  };
32638
32940
  if (!swap) {
32639
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");
32640
32943
  const redeeming = new Set(written.flatMap((s) => (swapOf(s).inputs ?? []).map((p) => p.secret)));
32641
32944
  if (preview.inputs.some((p) => redeeming.has(p.secret))) throw engineError("ecashBeingReceived");
32642
32945
  swap = {
@@ -32648,7 +32951,7 @@ var CashuWallet = class CashuWallet {
32648
32951
  token,
32649
32952
  ...records(preview.amount.toNumber())
32650
32953
  };
32651
- await wrap((await store(STORES$1.swaps, "readwrite")).put(swap));
32954
+ await committed((await store(STORES$1.swaps, "readwrite")).put(swap));
32652
32955
  }
32653
32956
  const { keep } = await this.completeSwap(swap);
32654
32957
  const credited = sats(keep);
@@ -32740,11 +33043,12 @@ var CashuWallet = class CashuWallet {
32740
33043
  ...swap,
32741
33044
  attemptEndedAt: Date.now()
32742
33045
  };
32743
- 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(() => {});
32744
33047
  const outcome = await this.swapOutcome(ended, refused).catch(() => ({ state: "open" }));
32745
33048
  if (outcome.state === "done") return outcome;
32746
33049
  if (outcome.state === "never" && outcome.final) {
32747
33050
  await this.dropSwap(ended, outcome.gone);
33051
+ if (swap.kind === "receive") this.rememberSpent(swap.mint, outcome.gone);
32748
33052
  throw outcome.gone.size > 0 ? Object.assign(engineError("ecashAlreadySpent"), { cause: error }) : error;
32749
33053
  }
32750
33054
  this.swapsAgainIn(SWAP_POLL_MS);
@@ -32884,6 +33188,17 @@ var CashuWallet = class CashuWallet {
32884
33188
  });
32885
33189
  if (gone.size > 0 && inputs.length > 0) this.recheck(swap.mint).catch(() => {});
32886
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
+ }
32887
33202
  /** The proofs a split reserved, as they are stored now. */
32888
33203
  async storedInputs(swap) {
32889
33204
  const secrets = new Set(swapOf(swap).inputs.map((p) => p.secret));
@@ -32943,7 +33258,7 @@ var CashuWallet = class CashuWallet {
32943
33258
  if (!swap) return;
32944
33259
  try {
32945
33260
  if (swap.finished) {
32946
- 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));
32947
33262
  else later(SWAP_POLL_MS);
32948
33263
  return;
32949
33264
  }
@@ -32956,7 +33271,7 @@ var CashuWallet = class CashuWallet {
32956
33271
  ...swap,
32957
33272
  attemptEndedAt: Date.now()
32958
33273
  };
32959
- await wrap((await store(STORES$1.swaps, "readwrite")).put(swap));
33274
+ await committed((await store(STORES$1.swaps, "readwrite")).put(swap));
32960
33275
  }
32961
33276
  const outcome = await this.swapOutcome(swap);
32962
33277
  if (outcome.state === "open") {
@@ -32967,7 +33282,7 @@ var CashuWallet = class CashuWallet {
32967
33282
  if (outcome.slow) {
32968
33283
  const stuck = (swap.stuck ?? 0) + 1;
32969
33284
  const wait = stuck <= 6 ? SWAP_SLOW_POLL_MS : stuck <= 30 ? 36e5 : 864e5;
32970
- await wrap((await store(STORES$1.swaps, "readwrite")).put({
33285
+ await committed((await store(STORES$1.swaps, "readwrite")).put({
32971
33286
  ...swap,
32972
33287
  stuck,
32973
33288
  askAt: Date.now() + wait
@@ -32980,7 +33295,7 @@ var CashuWallet = class CashuWallet {
32980
33295
  const { keep } = await (await this.wallet(mint)).completeSwap(deserializeSwapPreview(swapOf(swap)));
32981
33296
  if (await this.finishSwap(swap, keep, [], true)) {
32982
33297
  const told = await this.tellSwap(swap, true);
32983
- 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));
32984
33299
  else if (swap.payment) later(SWAP_POLL_MS);
32985
33300
  this.events.onChange();
32986
33301
  }
@@ -32989,12 +33304,12 @@ var CashuWallet = class CashuWallet {
32989
33304
  ...swap,
32990
33305
  attemptEndedAt: Date.now()
32991
33306
  };
32992
- await wrap((await store(STORES$1.swaps, "readwrite")).put(swap));
33307
+ await committed((await store(STORES$1.swaps, "readwrite")).put(swap));
32993
33308
  const refusal = isMintOperationError(error) ? await this.swapOutcome(swap, true).catch(() => void 0) : void 0;
32994
33309
  if (refusal?.state === "done") {
32995
33310
  if (await this.finishSwap(swap, refusal.keep, refusal.send, true)) {
32996
33311
  const told = await this.tellSwap(swap, true);
32997
- 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));
32998
33313
  }
32999
33314
  this.events.onChange();
33000
33315
  } else if (refusal?.state === "never") {
@@ -33005,7 +33320,7 @@ var CashuWallet = class CashuWallet {
33005
33320
  }
33006
33321
  } else if (outcome.pending && swap.kind === "receive" && !swap.released && Date.now() >= swapOverdueAt(swap)) {
33007
33322
  if (Date.now() < swap.createdAt + SWAP_WATCH_MS) {
33008
- await wrap((await store(STORES$1.swaps, "readwrite")).put({
33323
+ await committed((await store(STORES$1.swaps, "readwrite")).put({
33009
33324
  ...swap,
33010
33325
  askAt: Date.now() + SWAP_SLOW_POLL_MS
33011
33326
  }));
@@ -33021,7 +33336,7 @@ var CashuWallet = class CashuWallet {
33021
33336
  if (outcome.state === "done") {
33022
33337
  if (await this.finishSwap(swap, outcome.keep, outcome.send, true)) {
33023
33338
  const told = await this.tellSwap(swap, true);
33024
- 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));
33025
33340
  else if (swap.payment) later(SWAP_POLL_MS);
33026
33341
  }
33027
33342
  } else if (swap.released) {
@@ -33429,10 +33744,95 @@ var allows = (link, method) => method === "arkade" ? link.supportsArkPayments :
33429
33744
  /** Federation ecash is counted in msats; a chat counts whole sats. */
33430
33745
  var fedimintSats = (msats) => Math.floor(msats / 1e3);
33431
33746
  /**
33432
- * Which notes these are, whatever the spelling: the Fedimint client drops whitespace anywhere and reads URL-safe or
33433
- * 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.
33434
33828
  */
33435
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) {
33436
33836
  const text = notes.replace(/\s+/g, "");
33437
33837
  try {
33438
33838
  return digestHex(toBase64Url(fromBase64Url(text.replace(/=+$/, ""))));
@@ -34516,10 +34916,11 @@ var PaymentDesk = class {
34516
34916
  error: reason
34517
34917
  });
34518
34918
  const sats = parseSats(payment.amount.value, payment.amount.asset);
34919
+ const spent = error instanceof EngineError && error.engineCode === "ecashAlreadySpent";
34519
34920
  try {
34520
34921
  await this.host.storeMessage({
34521
34922
  linkId,
34522
- id: `peer_${payment.timestamp}_refused`,
34923
+ id: spent ? `peer_spent_${digestHex(token).slice(0, 32)}` : `peer_${payment.timestamp}_refused`,
34523
34924
  text: `Could not receive ${sats === null ? "a payment" : `${sats.toLocaleString()} sats`}: ${reason}`,
34524
34925
  sender: "peer",
34525
34926
  timestamp: payment.timestamp,
@@ -34704,6 +35105,8 @@ var PaymentDesk = class {
34704
35105
  lastCheckFrom = /* @__PURE__ */ new Map();
34705
35106
  /** `receiveInvoicePaid`'s last look, by `<link id>:<invoice>`: only the last 3 seconds' are kept. */
34706
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();
34707
35110
  /**
34708
35111
  * "I paid it from another wallet": the contact's app is asked to look at its wallet now. Nothing here
34709
35112
  * marks anything paid; the request settles when the payee's wallet sees the money, with or without this.
@@ -34763,7 +35166,9 @@ var PaymentDesk = class {
34763
35166
  * The contact says it paid an invoice of ours it found in the chat, with no request: a Receive-screen invoice is
34764
35167
  * held on a test mint until then (StoredQuote `held`), and that one alone is let go. A request's invoice is spoken
34765
35168
  * for by its own contact only (`receiveCheck`). Bounded: one look every 3 seconds per invoice of a chat, so two
34766
- * 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).
34767
35172
  */
34768
35173
  async receiveInvoicePaid(linkId, link, invoice) {
34769
35174
  if (!link.allowsPayment("lightning")) return;
@@ -34771,8 +35176,19 @@ var PaymentDesk = class {
34771
35176
  const wanted = invoice.trim().toLowerCase();
34772
35177
  const key = `${linkId}:${wanted}`;
34773
35178
  if (now - (this.lastInvoiceCheck.get(key) ?? 0) < 3e3) return;
34774
- 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);
34775
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);
34776
35192
  try {
34777
35193
  const quote = (await this.wallet.quotes()).find((q) => q.held && !q.paymentId && q.invoice.toLowerCase() === wanted);
34778
35194
  if (quote) await this.wallet.vouch(quote.invoice);
@@ -35541,8 +35957,9 @@ var PaymentDesk = class {
35541
35957
  return;
35542
35958
  }
35543
35959
  const digest = fedimintNotesDigest(notes);
35960
+ const bytes = fedimintBytesDigest(notes);
35544
35961
  const spelled = digestHex(notes.trim());
35545
- 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");
35546
35963
  if (before) {
35547
35964
  link.sendPaymentResult({
35548
35965
  id: payment.id,
@@ -36086,7 +36503,7 @@ var PaymentDesk = class {
36086
36503
  }
36087
36504
  async save(payment) {
36088
36505
  this.payments.set(payment.id, payment);
36089
- await wrap((await store(STORES$1.payments, "readwrite")).put(payment));
36506
+ await committed((await store(STORES$1.payments, "readwrite")).put(payment));
36090
36507
  this.host.onChange();
36091
36508
  }
36092
36509
  /**
@@ -36596,6 +37013,8 @@ var LIMITED_MODE_METHODS = /* @__PURE__ */ new Set([
36596
37013
  "setFastPoll",
36597
37014
  "exportLinks",
36598
37015
  "walletBackupReminder",
37016
+ "savedMessages",
37017
+ "saveMessage",
36599
37018
  "deviceRestoreStartOwn"
36600
37019
  ]);
36601
37020
  /** Thrown by the transport when something tries to publish in limited mode: a bug in a switch point, never a wait. */
@@ -36617,6 +37036,19 @@ function refusingWhileLimited(transport, limited) {
36617
37036
  if (transport.publishPayload) guarded.publishPayload = (pubKeyZ32, payload, options) => limited() ? Promise.reject(new LimitedModeError()) : transport.publishPayload(pubKeyZ32, payload, options);
36618
37037
  return guarded;
36619
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})$/;
36620
37052
  var GhostlyNode = class GhostlyNode {
36621
37053
  events;
36622
37054
  options;
@@ -37294,6 +37726,7 @@ var GhostlyNode = class GhostlyNode {
37294
37726
  },
37295
37727
  receivePaymentRequest: (linkId, request) => this.desk.onPaymentRequest(linkId, request, true),
37296
37728
  changed: () => this.emitState(),
37729
+ fetch: (...request) => (this.options.holdFetch ?? globalThis.fetch)(...request),
37297
37730
  loopbackStorage: () => this.options.holdLoopback === true,
37298
37731
  ttlMs: () => {
37299
37732
  try {
@@ -37541,6 +37974,11 @@ var GhostlyNode = class GhostlyNode {
37541
37974
  reactions = new Reactions({
37542
37975
  messages: (chat) => db.getMessages(chat),
37543
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
+ },
37544
37982
  patch: (chat, id, change) => db.patchMessage(chat, id, change),
37545
37983
  changed: async (chat, id, note) => {
37546
37984
  const shown = this.reactionNotes.get(chat);
@@ -37585,7 +38023,12 @@ var GhostlyNode = class GhostlyNode {
37585
38023
  },
37586
38024
  linkReady: (linkId, version = 1) => !!this.links.get(linkId)?.link?.supportsGroupVersion(version),
37587
38025
  linkHandled: (linkId) => this.links.get(linkId)?.link?.handled() ?? Promise.resolve(false),
38026
+ linkWaiting: (linkId) => this.links.get(linkId)?.link?.framesWaiting() ?? 0,
37588
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
+ },
37589
38032
  myNick: () => this.sharedNick,
37590
38033
  seqFloor: () => this.counterFloor,
37591
38034
  adminWork: (groupId) => !this.limitedMode && !this.groupAdminOff.has(groupId),
@@ -37596,7 +38039,7 @@ var GhostlyNode = class GhostlyNode {
37596
38039
  if (typeof RTCPeerConnection === "undefined" && native.length) {
37597
38040
  let held = 0;
37598
38041
  for (const live of this.links.values()) if (live.stored.group && live.stored.group !== groupId && live.link) held++;
37599
- 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);
37600
38043
  }
37601
38044
  const budget = this.options.peerBudget;
37602
38045
  if (budget === void 0) return void 0;
@@ -37633,6 +38076,7 @@ var GhostlyNode = class GhostlyNode {
37633
38076
  door,
37634
38077
  back
37635
38078
  }))?.records ?? null,
38079
+ readHeldBackFor: (pubKeyZ32) => this.groupTransport.readHeldBackFor?.(pubKeyZ32),
37636
38080
  expectPeer: (linkId) => this.links.get(linkId)?.link?.expectPeer(),
37637
38081
  signalIn: (linkId, payload, direct) => !!this.links.get(linkId)?.carried?.accept(payload, direct),
37638
38082
  edgeSignal: (linkId) => this.links.get(linkId)?.carried?.latest() ?? null,
@@ -37720,11 +38164,11 @@ var GhostlyNode = class GhostlyNode {
37720
38164
  },
37721
38165
  changed: (chat, id) => this.messagesChanged(chat, [id]),
37722
38166
  membership: (groupId) => {
37723
- const membership = this.membership(groupId);
38167
+ const view = this.groups.view(groupId), membership = membershipOf(view);
37724
38168
  return membership && {
37725
38169
  ...membership,
37726
38170
  community: this.groups.isCommunityGroup(groupId),
37727
- admin: !!this.groups.views().find((g) => g.id === groupId)?.isAdmin
38171
+ admin: !!view?.isAdmin
37728
38172
  };
37729
38173
  },
37730
38174
  send: (groupId, edit, to) => this.groups.sendEdit(groupId, edit, to),
@@ -37732,7 +38176,7 @@ var GhostlyNode = class GhostlyNode {
37732
38176
  removeMine: async (chat, message, removal) => {
37733
38177
  const groupId = chat.slice(6);
37734
38178
  await this.groups.setRemovals(groupId, withRemoval(this.groups.removals(groupId), removal));
37735
- await this.forgetGroupMessage(chat, message.id);
38179
+ await this.forgetGroupMessage(chat, message.id, message);
37736
38180
  },
37737
38181
  edge: (groupId, member) => {
37738
38182
  const link = this.links.get(this.memberEdges(groupId).get(member) ?? "")?.link;
@@ -37743,9 +38187,12 @@ var GhostlyNode = class GhostlyNode {
37743
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
37744
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.
37745
38189
  */
37746
- async forgetGroupMessage(chat, id) {
37747
- 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);
37748
38194
  await db.deleteMessage(chat, id);
38195
+ if (moved) await this.groups.unmark(groupId, moved);
37749
38196
  this.quoteSweeps.add(chat, id, id);
37750
38197
  await this.messagesChanged(chat, [id]);
37751
38198
  this.emitState();
@@ -37765,11 +38212,7 @@ var GhostlyNode = class GhostlyNode {
37765
38212
  }
37766
38213
  /** My key in an active group, and who is in it. */
37767
38214
  membership(groupId) {
37768
- const group = this.groups.views().find((g) => g.id === groupId);
37769
- return group?.status === "active" && group.myKey ? {
37770
- me: group.myKey,
37771
- members: new Set(group.members.map((m) => m.key))
37772
- } : void 0;
38215
+ return membershipOf(this.groups.view(groupId));
37773
38216
  }
37774
38217
  /** The link payments with `linkId` go over: a chat's or an edge's, or a community member's through the group. */
37775
38218
  paymentLink(linkId) {
@@ -38135,13 +38578,9 @@ var GhostlyNode = class GhostlyNode {
38135
38578
  for (const message of messages.slice(-20)) this.clockSample(message);
38136
38579
  const note = latestReaction(messages);
38137
38580
  if (note) this.reactionNotes.set(stored.id, note);
38138
- if (stored.profile) await this.outboxFor(stored.id).recover();
38581
+ if (stored.profile) await this.outboxFor(stored.id).recover(messages);
38139
38582
  }
38140
38583
  this.transfersRestored = true;
38141
- for (const group of this.groups.views()) {
38142
- const note = latestReaction(await db.getMessages(`group:${group.id}`));
38143
- if (note) this.reactionNotes.set(`group:${group.id}`, note);
38144
- }
38145
38584
  this.publicProfiles.start();
38146
38585
  await this.startLinks(links.map((stored) => stored.id), (linkId) => {
38147
38586
  if (!this.links.get(linkId)?.stored.group) this.refreshPublicProfiles({ linkId }).catch(() => {});
@@ -38240,7 +38679,7 @@ var GhostlyNode = class GhostlyNode {
38240
38679
  return wrap((await store(STORES$1.settings, "readonly")).get(RESTORE_UNCHECKED_KEY)).catch(() => null);
38241
38680
  }
38242
38681
  async clearRestoreMark() {
38243
- 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));
38244
38683
  }
38245
38684
  /**
38246
38685
  * "Start it as a profile of its own" on a restored copy whose read found a tombstone (WISP 06 § A backup restored where
@@ -38303,7 +38742,7 @@ var GhostlyNode = class GhostlyNode {
38303
38742
  }
38304
38743
  await this.groups.files?.sweep((await db.getGroups()).map((group) => group.id)).catch(() => {});
38305
38744
  await this.leaveLimited(start.readAt ?? null).catch(() => {});
38306
- 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(() => {});
38307
38746
  }
38308
38747
  readTurnWhileLimited(after = 3e4) {
38309
38748
  if (this.limitedTimer) clearTimeout(this.limitedTimer);
@@ -38323,7 +38762,7 @@ var GhostlyNode = class GhostlyNode {
38323
38762
  }
38324
38763
  if (outcome && (outcome.kind === "start" || outcome.kind === "go-on" && !outcome.restricted)) {
38325
38764
  await this.leaveLimited().catch(() => {});
38326
- if (!this.limitedMode && this.networkOn) this.startDeviceSet().catch(() => {});
38765
+ if (!this.limitedMode && this.networkOn) this.startDeviceSet({ justRead: true }).catch(() => {});
38327
38766
  return;
38328
38767
  }
38329
38768
  this.readTurnWhileLimited();
@@ -38612,7 +39051,6 @@ var GhostlyNode = class GhostlyNode {
38612
39051
  for (const queue of this.editQueues.values()) queue.stop();
38613
39052
  for (const restore of this.cardRestores.values()) clearTimeout(restore.timer);
38614
39053
  this.cardRestores.clear();
38615
- this.quoteSweeps.stop();
38616
39054
  this.groupEdits.stop();
38617
39055
  this.reactions.stop();
38618
39056
  this.cardEdits.stop();
@@ -38620,6 +39058,7 @@ var GhostlyNode = class GhostlyNode {
38620
39058
  linksStopped,
38621
39059
  links?.stop(),
38622
39060
  this.groups.flush(),
39061
+ this.quoteSweeps.stop(),
38623
39062
  ...WALLET_NETWORKS.flatMap((network) => [
38624
39063
  this.arkWallets,
38625
39064
  this.barkWallets,
@@ -38839,6 +39278,10 @@ var GhostlyNode = class GhostlyNode {
38839
39278
  async getMessages(linkId) {
38840
39279
  return (await db.getMessages(linkId)).map(withoutFrame);
38841
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
+ }
38842
39285
  /** One message of a chat, read by its id: the whole history costs a read of every row. */
38843
39286
  async getMessage(linkId, id) {
38844
39287
  const message = await db.getMessage(linkId, id);
@@ -39732,10 +40175,12 @@ var GhostlyNode = class GhostlyNode {
39732
40175
  error: `Message too large for DHT (${bytes} bytes, max 500). Try a shorter message or share a link instead.`,
39733
40176
  refused: true
39734
40177
  };
39735
- 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" };
39736
40181
  if (!trimmed) return { error: null };
39737
40182
  const timestamp = params.timestamp ?? arrivalKey(Date.now(), this.placedAt.get(linkId));
39738
- if (live.stored.profile) live.link.setTyping(false);
40183
+ if (live.stored.profile) live.link?.setTyping(false);
39739
40184
  if (live.stored.profile) {
39740
40185
  const found = params.replyTo === void 0 ? void 0 : await this.replyFor(linkId, params.replyTo);
39741
40186
  if (typeof found === "string") return {
@@ -39761,6 +40206,7 @@ var GhostlyNode = class GhostlyNode {
39761
40206
  error: "Replies need a current chat; this compatibility chat sends text only.",
39762
40207
  refused: true
39763
40208
  };
40209
+ if (!live.link) return { error: "You are offline" };
39764
40210
  const via = live.link.isDataLinkOpen ? "datalink" : "pkarr";
39765
40211
  await this.storeMessage({
39766
40212
  linkId,
@@ -39804,7 +40250,7 @@ var GhostlyNode = class GhostlyNode {
39804
40250
  */
39805
40251
  async sendChatText(live, trimmed, timestamp, preview, reply, forwarded, card) {
39806
40252
  const { link } = live, linkId = live.stored.id;
39807
- if (!link) return { error: "You are offline" };
40253
+ if (!link && !this.limitedMode) return { error: "You are offline" };
39808
40254
  this.chatInUse(live);
39809
40255
  const bytes = new TextEncoder().encode(trimmed).length;
39810
40256
  if (bytes > LIMITS.maxChatMessageBytes) return {
@@ -39817,6 +40263,32 @@ var GhostlyNode = class GhostlyNode {
39817
40263
  };
39818
40264
  const stop = this.chatStopped(live);
39819
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
+ }
39820
40292
  if (!link.isDataLinkOpen && link.dhtDelivery?.inviteTaken) return {
39821
40293
  error: INVITE_TAKEN,
39822
40294
  refused: true
@@ -39824,11 +40296,6 @@ var GhostlyNode = class GhostlyNode {
39824
40296
  const wireId = toBase64Url(randomBytes(16)), id = `me_${wireId}`;
39825
40297
  const delivery = link.isDataLinkOpen ? "stream" : link.textDelivery === "dht" ? "dht" : "unavailable";
39826
40298
  if (delivery !== "stream") this.wakePeer(live);
39827
- const answers = {
39828
- ...reply && { replyTo: reply },
39829
- ...forwarded && { forwarded },
39830
- ...card && { card }
39831
- };
39832
40299
  if (delivery === "stream" || delivery === "dht" && bytes <= 256) {
39833
40300
  const validationError = link.validateText(trimmed, timestamp, wireId, reply && pairedWireReply(reply));
39834
40301
  if (!validationError) {
@@ -40084,6 +40551,7 @@ var GhostlyNode = class GhostlyNode {
40084
40551
  }
40085
40552
  if (edit.rm) {
40086
40553
  const message = await db.getMessage(linkId, id);
40554
+ if (!message && PAYMENT_LINE_ID.test(edit.id)) return true;
40087
40555
  if (!message || canRemove(message)) await this.forgetMessage(linkId, id, true);
40088
40556
  return true;
40089
40557
  }
@@ -40267,7 +40735,7 @@ var GhostlyNode = class GhostlyNode {
40267
40735
  ...live.stored,
40268
40736
  removals: live.stored.removals.filter((r) => r.id !== messageId)
40269
40737
  };
40270
- await db.patchLink(linkId, { removals: live.stored.removals });
40738
+ await this.writeDeletions(linkId, { removals: live.stored.removals }, true);
40271
40739
  return;
40272
40740
  }
40273
40741
  if (await db.patchMessage(linkId, messageId, (current) => {
@@ -40680,13 +41148,50 @@ var GhostlyNode = class GhostlyNode {
40680
41148
  ...live.stored,
40681
41149
  removals: withRemoval(live.stored.removals, removal)
40682
41150
  };
40683
- await db.patchLink(linkId, { removals: live.stored.removals });
40684
- 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;
40685
41155
  const edits = this.editsFor(linkId);
40686
41156
  edits.edited(messageId);
40687
41157
  edits.flush().catch(() => {});
40688
41158
  return { error: null };
40689
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
+ }
40690
41195
  /**
40691
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
40692
41197
  * copy that comes again is not stored: a delete here, or the contact's own removal (WISP 400 § Delete for everyone),
@@ -40699,7 +41204,7 @@ var GhostlyNode = class GhostlyNode {
40699
41204
  ...live.stored,
40700
41205
  deletedIds: [...live.stored.deletedIds ?? [], messageId].slice(-500)
40701
41206
  };
40702
- db.patchLink(linkId, { deletedIds: live.stored.deletedIds });
41207
+ this.writeDeletions(linkId, { deletedIds: live.stored.deletedIds }).catch(() => {});
40703
41208
  this.hold.forget(linkId, messageId).catch(() => {});
40704
41209
  const message = await db.getMessage(linkId, messageId);
40705
41210
  if (message?.paymentId && message.delivery === "waiting") await this.desk.withdraw(message.paymentId).catch(() => {});
@@ -41574,7 +42079,9 @@ var GhostlyNode = class GhostlyNode {
41574
42079
  if (!this.links.get(linkId)?.stored.profile || this.links.get(linkId)?.stored.group) throw new Error("Invite a paired contact");
41575
42080
  return this.groups.invite(groupId, linkId);
41576
42081
  }
41577
- 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");
41578
42085
  return this.groups.accept(groupId);
41579
42086
  }
41580
42087
  declineGroupInvitation({ groupId }) {
@@ -41747,7 +42254,7 @@ var GhostlyNode = class GhostlyNode {
41747
42254
  if (ids.length > 30) throw new Error(`Forward at most 30 messages at once`);
41748
42255
  if (!targets.length) throw new Error("No chat to forward to");
41749
42256
  if (targets.length > 5) throw new Error(`Forward to at most 5 chats at once`);
41750
- 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");
41751
42258
  const chosen = await Promise.all(ids.map((id) => db.getMessage(linkId, id)));
41752
42259
  if (chosen.some((m) => !m)) throw new Error("That message is not in this chat");
41753
42260
  const messages = chosen.sort((a, b) => a.timestamp - b.timestamp);
@@ -41779,7 +42286,7 @@ var GhostlyNode = class GhostlyNode {
41779
42286
  const hops = forwardedAgain(message.forwarded);
41780
42287
  try {
41781
42288
  if (forwardKind(message) === "text") {
41782
- 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({
41783
42290
  linkId: to,
41784
42291
  text: message.text,
41785
42292
  timestamp: now()
@@ -41881,7 +42388,7 @@ var GhostlyNode = class GhostlyNode {
41881
42388
  if (linkId.startsWith("group:")) {
41882
42389
  const groupId = linkId.slice(6);
41883
42390
  if (!this.membership(groupId)) return {
41884
- 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",
41885
42392
  refused: true
41886
42393
  };
41887
42394
  const result = await this.reactions.mine(linkId, messageId, emoji);
@@ -42040,7 +42547,7 @@ var GhostlyNode = class GhostlyNode {
42040
42547
  message: (chat, id) => db.getMessage(chat, id)
42041
42548
  };
42042
42549
  if (linkId.startsWith("group:")) {
42043
- 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);
42044
42551
  if (!view || view.status !== "active") return { error: "You are not in this group" };
42045
42552
  if (!mayPinIn(view)) return { error: "Only the admin pins in a community" };
42046
42553
  const pin = await myPin(host, linkId, messageId, !!remove, this.groups.pinOf(groupId));
@@ -42152,6 +42659,8 @@ var GhostlyNode = class GhostlyNode {
42152
42659
  * ask again while the page still reads the first ask, whose answer must not go out as the second's.
42153
42660
  */
42154
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);
42155
42664
  const request = ++this.nextAppRangeAsk;
42156
42665
  this.appRanges.set(`${linkId} ${task.app} ${request}`, task);
42157
42666
  const { app, serve, file, offset, length } = task;
@@ -42164,29 +42673,49 @@ var GhostlyNode = class GhostlyNode {
42164
42673
  length
42165
42674
  });
42166
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();
42167
42678
  /** Lets the contact's app read `file`, one of this side's linked files, while both have the app open on this session. */
42168
- appServe({ linkId, ref, file }) {
42679
+ async appServe({ linkId, ref, file, digest }) {
42169
42680
  const { live, app } = this.appChat(linkId, ref);
42170
42681
  if (typeof file !== "string" || !file) throw new Error("Not a file");
42171
- 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;
42172
42690
  }
42173
42691
  appUnserve({ linkId, serve }) {
42174
42692
  if (!this.appsOn) throw this.appsOff();
42175
42693
  this.links.get(linkId)?.link?.unserveAppFile(serve);
42176
42694
  }
42177
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. */
42178
- appRangeAnswer({ linkId, app, request, bytes, size, error }) {
42696
+ async appRangeAnswer({ linkId, app, request, bytes, size, error }) {
42179
42697
  if (!this.appsOn) throw this.appsOff();
42180
- 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);
42181
42699
  this.appRanges.delete(key);
42182
- 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
+ }
42183
42711
  if (error === "changed" || error === "gone") return link.failAppRange(task, error);
42184
42712
  if (!(bytes instanceof Uint8Array) || typeof size !== "number" || !Number.isSafeInteger(size) || size < 0) return link.failAppRange(task, "gone");
42185
42713
  link.sendAppRange(task, bytes, size);
42186
42714
  }
42187
42715
  /** Reads a range of what the contact's app serves in this chat, or why not. */
42188
- async appRemoteRead({ linkId, ref, serve, offset, length }) {
42716
+ async appRemoteRead({ linkId, ref, serve, offset, length, digest }) {
42189
42717
  const { live, app } = this.appChat(linkId, ref);
42718
+ await this.appChatRunnable(ref, digest);
42190
42719
  if (!live.link) return { error: "offline" };
42191
42720
  if (!isServeId(serve)) return { error: "not-served" };
42192
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");
@@ -42270,7 +42799,7 @@ var GhostlyNode = class GhostlyNode {
42270
42799
  * other edges, so members with no edge to the pinner get it.
42271
42800
  */
42272
42801
  async receiveGroupPin(groupId, member, pin, via) {
42273
- const view = this.groups.views().find((g) => g.id === groupId);
42802
+ const view = this.groups.view(groupId);
42274
42803
  if (!pin || !view?.myKey || view.status !== "active" || !view.members.some((m) => m.key === member)) return;
42275
42804
  if (!mayPin(view.profile, member, view.members.find((m) => m.role === "admin")?.key)) return;
42276
42805
  if (!pinIsNewer(this.groups.pinOf(groupId), pin)) return;
@@ -43242,7 +43771,7 @@ var GhostlyNode = class GhostlyNode {
43242
43771
  }
43243
43772
  /** A request any member of a group may pay, once (WISP 902 § Payments). */
43244
43773
  requestGroupPayment(params) {
43245
- const group = this.groups.views().find((g) => g.id === params.groupId);
43774
+ const group = this.groups.view(params.groupId);
43246
43775
  if (group?.status !== "active") throw new Error("You are not in this group");
43247
43776
  if (group.members.length < 2) throw new Error("Nobody else is in the group yet");
43248
43777
  return this.desk.requestFromGroup({
@@ -43544,7 +44073,7 @@ var GhostlyNode = class GhostlyNode {
43544
44073
  const next = new Set(this.groupAdminOff);
43545
44074
  if (on) next.delete(groupId);
43546
44075
  else next.add(groupId);
43547
- await wrap((await store(STORES$1.settings, "readwrite")).put({
44076
+ await committed((await store(STORES$1.settings, "readwrite")).put({
43548
44077
  at: Date.now(),
43549
44078
  groups: [...next].sort()
43550
44079
  }, GROUP_ADMIN_OFF_KEY));
@@ -43620,9 +44149,10 @@ var GhostlyNode = class GhostlyNode {
43620
44149
  /**
43621
44150
  * The active device's links to the other devices, and its stored turn record put again (WISP 06 § Publishing and
43622
44151
  * reading: "The active device puts its stored bytes at start"). This is also what completes an enrollment that a
43623
- * 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.
43624
44154
  */
43625
- async startDeviceSet() {
44155
+ async startDeviceSet({ justRead = false } = {}) {
43626
44156
  if (this.shuttingDown) return;
43627
44157
  const own = await readDeviceRecord(databaseName()).catch(() => null);
43628
44158
  this.ownDeviceKey = own?.ownSlot !== void 0 ? own.deviceSet[own.ownSlot]?.key ?? null : null;
@@ -43653,15 +44183,18 @@ var GhostlyNode = class GhostlyNode {
43653
44183
  await recoverEnrollment(databaseName(), this.turnNetwork()).catch(() => false);
43654
44184
  await this.syncDeviceVerifier().catch(() => {});
43655
44185
  const keeper = await this.deviceLinks.turnKeeper();
43656
- const outcome = await keeper?.check(false);
43657
- if (outcome?.kind === "go-on" && !outcome.restricted) {
43658
- this.noteGoodTurn();
43659
- await keeper?.stateVerifier().catch(() => null);
43660
- }
43661
- if (outcome?.kind === "gated" && !this.shuttingDown) {
43662
- const record = await readDeviceRecord(databaseName());
43663
- if (record) await this.stopReplaced(viewOf(record));
43664
- 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
+ }
43665
44198
  }
43666
44199
  this.watchActiveTurn();
43667
44200
  this.watchTombstones();
@@ -44024,7 +44557,7 @@ var GhostlyNode = class GhostlyNode {
44024
44557
  }
44025
44558
  try {
44026
44559
  const verifier = await makeHandoffVerifier(password);
44027
- 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));
44028
44561
  await this.syncDeviceVerifier().catch(() => {});
44029
44562
  await this.stateDeviceVerifier();
44030
44563
  } catch (error) {
@@ -44034,7 +44567,7 @@ var GhostlyNode = class GhostlyNode {
44034
44567
  }
44035
44568
  /** The profile has no verifier any more: its settings, the device state, and what the turn record states. */
44036
44569
  async dropHandoffVerifier() {
44037
- 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(() => {});
44038
44571
  await this.syncDeviceVerifier().catch(() => {});
44039
44572
  await this.stateDeviceVerifier();
44040
44573
  }
@@ -44412,7 +44945,7 @@ var GhostlyNode = class GhostlyNode {
44412
44945
  throw error;
44413
44946
  }
44414
44947
  if (this.networkOn) this.startLink(id);
44415
- if (expectPeer) this.links.get(id)?.link?.expectPeer();
44948
+ if (expectPeer) this.links.get(id)?.link?.expectPeer(true);
44416
44949
  return id;
44417
44950
  }
44418
44951
  /**
@@ -44782,6 +45315,7 @@ var GhostlyNode = class GhostlyNode {
44782
45315
  } : void 0;
44783
45316
  const resumed = stored.pairedPeerKey && stored.deliveryMode !== "dht" ? resumeHere(this.transportLogOf(live), this.transportsHere(), stored.peerTransports ?? live.caps?.peer?.transports) : {};
44784
45317
  let dhtShown;
45318
+ let dhtFlushed;
44785
45319
  let wasTaken = false;
44786
45320
  live.link = new GhostLink({
44787
45321
  paymentMethods: stored.paymentMethods,
@@ -44911,7 +45445,11 @@ var GhostlyNode = class GhostlyNode {
44911
45445
  onGroupFrame: stored.profile ? (frame) => this.groups.handleContactFrame(linkId, frame) : void 0,
44912
45446
  onGroupsSupport: () => this.emitState(),
44913
45447
  onDhtDelivery: (view) => {
44914
- 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
+ }
44915
45453
  this.observeTransport(linkId);
44916
45454
  const taken = !!live.link?.takenFromUs;
44917
45455
  if (taken !== wasTaken) {
@@ -45286,7 +45824,7 @@ var GhostlyNode = class GhostlyNode {
45286
45824
  get nativeFactories() {
45287
45825
  const relay = this.relaysHyperdht ? this.hyperdhtRelay : "";
45288
45826
  return {
45289
- ...relay ? { "hyperdht/1": async (seedB64) => (await import("./hyperdhtRelay-CJBqsS_e.js")).createRelayedHyperEndpoint(seedB64, relay) } : {},
45827
+ ...relay ? { "hyperdht/1": async (seedB64) => (await import("./hyperdhtRelay-C-BsT6_V.js")).createRelayedHyperEndpoint(seedB64, relay) } : {},
45290
45828
  ...this.options.nativeTransports,
45291
45829
  ...this.ownIrohRelays ? { "iroh/1": (seedB64) => this.options.nativeTransports["iroh/1"](seedB64, this.settings.irohRelays?.length ? { relays: [...this.settings.irohRelays] } : {}) } : {},
45292
45830
  ...this.options.irohWeb ? { "iroh/1": (seedB64) => createIrohWebEndpoint(seedB64, { relays: this.irohRelays }) } : {}
@@ -45434,20 +45972,23 @@ var GhostlyNode = class GhostlyNode {
45434
45972
  }
45435
45973
  anchorCheckAt = 0;
45436
45974
  /**
45437
- * A group's edge whose native listener has been up `GROUP_ANCHOR_ANSWER_MS` with no session, and whose member's
45438
- * 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.
45439
45980
  */
45440
45981
  unanswered(live, now) {
45441
45982
  const link = live.link;
45442
- if (!link || link.isDataLinkOpen) return false;
45983
+ if (!link || link.isDataLinkOpen || !live.presence.online) return false;
45443
45984
  const up = Object.keys(this.nativeFactories).filter((t) => link.availableTransports.includes(t)).map((t) => live.nativeUpAt?.[t] ?? now);
45444
45985
  if (!up.length || now - Math.min(...up) < 2e4) return false;
45445
- return !this.chosenByPeer(live) || !live.presence.online;
45986
+ return !this.chosenByPeer(live);
45446
45987
  }
45447
45988
  /**
45448
45989
  * Every few seconds, each group not on screen whose edges run native transports: the one edge it keeps has a
45449
45990
  * listener (or waits for one, `groupNativeWaiting`), and when its member has not answered it in
45450
- * `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
45451
45992
  * one instead (hub, then admin, then the member heard from last), whose member answers the edge it keeps
45452
45993
  * (`chosenByPeer`). Not while any edge of the group is live: the group is reachable through it. Every other one passed
45453
45994
  * over lately too: the one it keeps stays, without its listener going back and forth.
@@ -45532,6 +46073,17 @@ var GhostlyNode = class GhostlyNode {
45532
46073
  return this.nativeSlots(key) - CHAT_NATIVE_SLOTS;
45533
46074
  }
45534
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
+ /**
45535
46087
  * One transport's listener for one chat, in that transport's queue. "no-slot" when a group's link found no slot free,
45536
46088
  * "failed" when the listener could not start.
45537
46089
  */
@@ -46184,11 +46736,7 @@ var EngineServer = class {
46184
46736
  if (sent.has(link.id)) continue;
46185
46737
  await this.inOrder(link.id, async () => {
46186
46738
  if (!this.clients.has(client)) return;
46187
- client.post(scope.newest ? await this.newestOf(link.id, scope.newest) : {
46188
- kind: "messages",
46189
- linkId: link.id,
46190
- messages: await this.node.getMessages(link.id)
46191
- });
46739
+ client.post(scope.newest ? await this.newestOf(link.id, scope.newest) : this.historyEvent(link.id, await this.node.getMessages(link.id)));
46192
46740
  this.histories.get(client)?.add(link.id);
46193
46741
  });
46194
46742
  }
@@ -46259,29 +46807,21 @@ var EngineServer = class {
46259
46807
  linkId,
46260
46808
  limit
46261
46809
  });
46262
- return {
46263
- kind: "messages",
46264
- linkId,
46265
- messages: page.messages,
46266
- ...page.more ? { more: true } : {}
46267
- };
46810
+ return this.historyEvent(linkId, page.messages, page.more);
46268
46811
  }
46269
46812
  /**
46270
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
46271
- * (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.
46272
46816
  */
46273
46817
  async history(client, linkId) {
46274
46818
  if (typeof linkId !== "string" || !this.clients.has(client)) return;
46275
46819
  try {
46276
- await this.ready;
46820
+ await (linkId.startsWith("group:") ? Promise.race([this.ready, this.node.groupsRead]) : this.ready);
46277
46821
  await this.inOrder(linkId, async () => {
46278
46822
  if (!this.clients.has(client)) return;
46279
46823
  const messages = await this.node.getMessages(linkId);
46280
- if (this.clients.has(client) && this.post(client, {
46281
- kind: "messages",
46282
- linkId,
46283
- messages
46284
- })) 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);
46285
46825
  });
46286
46826
  } catch {}
46287
46827
  }
@@ -46296,12 +46836,22 @@ var EngineServer = class {
46296
46836
  });
46297
46837
  return running;
46298
46838
  }
46299
- sendHistory(linkId, messages) {
46300
- 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 {
46301
46846
  kind: "messages",
46302
46847
  linkId,
46303
- messages
46304
- });
46848
+ messages,
46849
+ ...more ? { more: true } : {},
46850
+ ...deleted.length > 0 && { deleted }
46851
+ };
46852
+ }
46853
+ sendHistory(linkId, messages) {
46854
+ this.broadcast(this.historyEvent(linkId, messages));
46305
46855
  for (const client of this.clients) this.histories.get(client)?.add(linkId);
46306
46856
  }
46307
46857
  sendChanges(linkId, changes) {
@@ -46321,11 +46871,7 @@ var EngineServer = class {
46321
46871
  return this.node.getMessages(linkId).then((messages) => {
46322
46872
  for (const client of behind) {
46323
46873
  if (!this.clients.has(client)) continue;
46324
- if (this.post(client, {
46325
- kind: "messages",
46326
- linkId,
46327
- messages
46328
- })) this.histories.get(client)?.add(linkId);
46874
+ if (this.post(client, this.historyEvent(linkId, messages))) this.histories.get(client)?.add(linkId);
46329
46875
  }
46330
46876
  });
46331
46877
  }
@@ -46359,4 +46905,4 @@ function signalKind(signal) {
46359
46905
  //#endregion
46360
46906
  export { EngineServer };
46361
46907
 
46362
- //# sourceMappingURL=server-BktMmp7L.js.map
46908
+ //# sourceMappingURL=server-DOtUKoYR.js.map