aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--src/app.js55
-rw-r--r--src/ark/manager.js50
-rw-r--r--src/features/ark.js150
-rw-r--r--src/features/gifts-wallet.js4
-rw-r--r--src/features/gifts.js73
-rw-r--r--src/features/messages.js326
-rw-r--r--src/features/names.js106
-rw-r--r--src/features/nostrlogin.js10
-rw-r--r--src/features/nwc.js38
-rw-r--r--src/i18n.js12
-rw-r--r--src/locales/ar.json7
-rw-r--r--src/locales/bn.json7
-rw-r--r--src/locales/de.json7
-rw-r--r--src/locales/es.json7
-rw-r--r--src/locales/fr.json7
-rw-r--r--src/locales/hi.json7
-rw-r--r--src/locales/id.json9
-rw-r--r--src/locales/it.json7
-rw-r--r--src/locales/ja.json7
-rw-r--r--src/locales/ko.json7
-rw-r--r--src/locales/mr.json9
-rw-r--r--src/locales/pt.json7
-rw-r--r--src/locales/ru.json7
-rw-r--r--src/locales/sw.json9
-rw-r--r--src/locales/ta.json9
-rw-r--r--src/locales/te.json9
-rw-r--r--src/locales/tr.json7
-rw-r--r--src/locales/ur.json9
-rw-r--r--src/locales/vi.json9
-rw-r--r--src/locales/zh.json7
-rw-r--r--src/marmot-client.js2
-rw-r--r--src/media-timeline.js6
-rw-r--r--src/media-upload.js10
-rw-r--r--src/nostr-login.js42
-rw-r--r--src/nwc-bg.js61
-rw-r--r--src/nwc-lock.js18
-rw-r--r--src/nwc-respond.js290
-rw-r--r--src/style.css73
-rw-r--r--src/sw-nwc.js125
-rw-r--r--tools/amount-field-unit-test.js16
-rw-r--r--tools/ark/custody-foreign-test.js102
-rw-r--r--tools/ark/offboard-split-test.js128
-rw-r--r--tools/feed-video-pager-test.js2
-rw-r--r--tools/fullscreen-notice-test.js2
-rw-r--r--tools/gift-profile-setup-test.js96
-rw-r--r--tools/live-stream-test.js7
-rw-r--r--tools/ln-pay-double-wake.test.js74
-rw-r--r--tools/media-grid-order-test.js128
-rw-r--r--tools/media-moments-feed-test.js12
-rw-r--r--tools/nwc-sw-test.js127
-rw-r--r--tools/pager-caption-test.js4
-rw-r--r--tools/pager-close-test.js2
-rw-r--r--tools/pager-eager-test.js2
-rw-r--r--tools/pager-first-frame-test.js2
-rw-r--r--tools/pager-no-poster-test.js2
-rw-r--r--tools/pager-prime-test.js2
-rw-r--r--tools/pager-rotate-test.js2
-rw-r--r--tools/pager-seek-hide-test.js2
-rw-r--r--tools/pager-tail-test.js2
-rw-r--r--tools/post-edit-test.js1
-rw-r--r--tools/profile-publish-race-test.js111
-rw-r--r--tools/quoted-clip-fullscreen-test.js2
-rw-r--r--tools/receive-batch-fold-test.js20
-rw-r--r--tools/sw-push-quota.test.js16
-rw-r--r--tools/thread-reply-test.js21
-rw-r--r--tools/video-events-test.js2
-rw-r--r--tools/video-tap-test.js40
67 files changed, 2201 insertions, 331 deletions
diff --git a/src/app.js b/src/app.js
index ffe9ba8..9789401 100644
--- a/src/app.js
+++ b/src/app.js
@@ -589,9 +589,9 @@ let _bootDeciding = true;
// starts): the app notes the phase it reaches, and clears the count once it
// has lived eight seconds or leaves cleanly. A page iOS kills while opening
// does neither, so the third start in a row opens in safe mode.
-export function bootPhase(p) { try { localStorage.setItem('coinos-boot-phase', p); } catch {} }
+function bootPhase(p) { try { localStorage.setItem('coinos-boot-phase', p); } catch {} }
function bootSettled() { try { localStorage.removeItem('coinos-boot'); } catch {} }
-export const safeBoot = () => !!(typeof window !== 'undefined' && window.__safeBoot);
+const safeBoot = () => !!(typeof window !== 'undefined' && window.__safeBoot);
document.addEventListener('visibilitychange', () => { if (document.visibilityState === 'hidden') bootSettled(); });
addEventListener('pagehide', bootSettled);
// Belt and braces: a boot path that returns early (or throws) must not leave
@@ -1209,31 +1209,44 @@ let unit = (() => {
// been fetched — a third position showing blanks is worse than two that work.
function toggleUnit() {
const ring = haveRate() ? ['sats', 'btc', 'fiat'] : ['sats', 'btc'];
+ const was = unit;
unit = ring[(ring.indexOf(unit) + 1) % ring.length];
try {
localStorage.setItem(UNIT_KEY, unit);
} catch {}
+ // An amount already typed into the send form is the same money in the new
+ // unit, not the same digits: 1000 sats does not become 1000 BTC. Whatever
+ // doesn't parse is left as typed.
+ for (const r of (ui.send && ui.send.recipients) || []) {
+ if (!r.amount || !String(r.amount).trim()) continue;
+ const sat = parseField(r.amount, was);
+ if (sat) r.amount = amountField(sat);
+ }
render();
}
// A sats figure as the amount field types it in the current unit — what a
// Max button or a fixed-amount invoice fills in. Fiat is floored to the
// cent so a filled-in maximum never parses back to more than was offered.
-// The figure it filled is remembered with its exact sats: a fiat maximum
+// The figures it filled are remembered with their exact sats: a fiat maximum
// rounded to the cent would otherwise parse back a few sats short and leave
-// them behind. Typing anything else parses as typed.
-let lastFill = null;
+// them behind. Typing anything else parses as typed. Several are kept so a
+// form with more than one amount round-trips each of them.
+const fills = new Map();
function amountField(sat) {
let s;
const r = unit === 'fiat' && rateNow();
if (unit === 'sats') s = String(sat);
else if (r) s = (Math.floor((sat / 1e8) * r * 100) / 100).toFixed(2);
else s = (sat / 1e8).toFixed(8);
- lastFill = { s, unit, sat };
+ fills.delete(unit + '|' + s);
+ fills.set(unit + '|' + s, sat);
+ while (fills.size > 16) fills.delete(fills.keys().next().value);
return s;
}
function parseField(v, u = unit) {
- if (lastFill && lastFill.unit === u && String(v).trim() === lastFill.s) return lastFill.sat;
+ const k = u + '|' + String(v).trim();
+ if (fills.has(k)) return fills.get(k);
return parseAmount(v, u, rateNow());
}
@@ -3926,7 +3939,11 @@ async function publicMediaUpload(file) {
if (error instanceof MediaUploadError && error.code === 'unauthorized') throw new Error(t('mediaUploadUnauthorized'));
if (error instanceof MediaUploadError && error.code === 'too-big') throw new Error(t('mediaUploadTooBig'));
if (error instanceof MediaUploadError && error.code === 'unsupported') throw new Error(t('mediaUploadUnsupported'));
- throw new Error(t('msgUploadFailed'));
+ // what went wrong, said: "check your connection" alone hid a signer
+ // that never answered and hosts that refused the file
+ const why = String((error instanceof MediaUploadError ? error.details : '') || error?.message || '').slice(0, 200);
+ console.warn('media upload failed', error, why);
+ throw new Error(why && why !== 'failed' ? `${t('msgUploadFailed')} (${why})` : t('msgUploadFailed'));
} finally {
ui.mediaProgress = null;
}
@@ -4197,16 +4214,18 @@ function onboardScreen() {
}
if (o.step === 'spend') {
return page([
- title(t('onbSpendTitle')),
- h('p', { class: 'muted', style: 'margin:0' }, t('onbSpendBody')),
+ title(t(o.fromGift ? 'onbGiftNameTitle' : 'onbSpendTitle')),
+ h('p', { class: 'muted', style: 'margin:0' }, t(o.fromGift ? 'onbGiftNameBody' : 'onbSpendBody')),
featureHook('namesClaimForm') || h('div', { class: 'row gap6', style: 'align-items:center' }, h('span', { class: 'spinner sm' }), h('span', { class: 'small muted' }, t('onbNameWait'))),
// Optional means optional: one tap to the wallet, no questions — on
- // Savings, the account that exists without any setup.
+ // Savings, the account that exists without any setup (or, after a
+ // gift, the account the gift arrived in).
h('button', { class: 'btn-ghost btn-block', onClick: () => {
+ const home = o.home || 'savings';
ui.onb = null;
try { localStorage.removeItem(ONB_STEP_KEY); } catch {}
- ui.account = 'savings';
- try { localStorage.setItem(ACCOUNT_KEY, 'savings'); } catch {}
+ ui.account = home;
+ try { localStorage.setItem(ACCOUNT_KEY, home); } catch {}
ui.tab = 'receive';
render();
} }, t('onbNotNow')),
@@ -4426,6 +4445,15 @@ function claimMigratedName() {
attempt();
}
+// After a gift is claimed into a fresh wallet (and its seed written down):
+// the wizard's name → look → done steps, the rest of a first run. `home` is
+// the account a skip lands on — the one the gift arrived in.
+function offerProfileSetup({ home = 'savings' } = {}) {
+ if (!canOfferSpending()) return false;
+ ui.onb = { step: 'spend', enterAddr: undefined, fromGift: true, home };
+ return true;
+}
+
function leaveWizard() {
ui.onb = null;
try { localStorage.removeItem(ONB_STEP_KEY); } catch {}
@@ -6467,6 +6495,7 @@ const ctx = {
|| (wallet.nostrPubkey && wallet.nostrPubkey()) || (activeAccount() || {}).nostrPk || null,
getAccount: () => accountSel(),
setAccount: (a, dir) => setAccountSel(a, dir),
+ offerProfileSetup, pickConfirm,
// Open (or create) a wallet from a mnemonic — used by nostr login.
openMnemonic: async (mnemonic, passphrase, opts) => enterWallet(mnemonic, passphrase, opts),
// Profile pictures retain the metadata-scrubbing image uploader. Public
diff --git a/src/ark/manager.js b/src/ark/manager.js
index caece44..aea6020 100644
--- a/src/ark/manager.js
+++ b/src/ark/manager.js
@@ -92,6 +92,16 @@ const actionTs = (a) => Number(String(a.id || '').split('-').pop()) || 0;
// claim recorded before it stamped them — the same amount within minutes).
// Derived at read time, never deleted: a synced copy from another device
// can't bring a twin back.
+// Two receive rows that are one payment delivered as several coins (a gift
+// held in two swept at once, a dust-padded split): the same mailbox message
+// (`batch`), or for rows recorded before the stamp, the same delivery instant.
+// A receive the registrar's receipts tagged ⚡ is its own payment.
+export function sameDelivery(a, b) {
+ return !!a && !!b && a.type === 'receive' && b.type === 'receive'
+ && a.status === 'complete' && b.status === 'complete' && !a.viaLn && !b.viaLn
+ && (a.batch || b.batch ? a.batch === b.batch : !!a.ts && a.ts === b.ts);
+}
+
export function lnFoldedIds(movements) {
const out = new Set();
const recs = (movements || []).filter((m) => m.type === 'receive' && m.status === 'complete' && m.vtxoId);
@@ -805,9 +815,13 @@ export class ArkManager {
// same message concurrently (validation awaits in between), and only the
// copy that actually added the vtxo may record the receive movement.
if (!this._addVtxo(v, v._raw.bytes, 0)) continue;
+ // `batch` names the mailbox message: one payment can arrive as several
+ // coins (a sweep of a gift held in two, a dust-padded split), and the
+ // history folds a message's coins back into one row
this._movement({
type: 'receive', amountSat: v.amountSat, status: 'complete', vtxoId: v.id,
ts: ckTs ?? (live ? Date.now() : this._estimateReceiveTs(v, tip)),
+ ...(m.checkpoint ? { batch: String(m.checkpoint) } : {}),
});
changed = true;
}
@@ -1496,9 +1510,13 @@ export class ArkManager {
if (expectNet && dec.network && dec.network !== expectNet) throw new Error(`invoice is for ${dec.network}, wallet is on ${expectNet}`);
const amountSat = dec.amountSat ?? userAmountSat;
if (!amountSat || amountSat <= 0) throw new Error('invoice has no amount');
- if (this.state.actions.some((a) =>
- a.type === 'ln-pay' && a.paymentHash === dec.paymentHash && a.step !== 'failed')) {
- throw new Error('this invoice was already paid or is being paid');
+ const prior = this.state.actions.find((a) =>
+ a.type === 'ln-pay' && a.paymentHash === dec.paymentHash && a.step !== 'failed');
+ if (prior) {
+ // two messages, so a caller can tell a settled payment from one still
+ // on its way (an NWC client once read "already paid or is being paid"
+ // as paid, hours before the money moved)
+ throw new Error(prior.step === 'done' ? 'this invoice was already paid' : 'a payment for this invoice is already in progress');
}
const tip = await this.chain.tipHeight();
const routing = routingFeeSat != null ? routingFeeSat : await this.lnRouteFee(invoice, amountSat);
@@ -1678,9 +1696,16 @@ export class ArkManager {
action.step = 'initiated';
this._save();
} catch (e) {
+ // the HTLC already went to this payment: another context (a second
+ // wake of the phone's worker, seconds apart, over its own copy of the
+ // state) initiated it first. That payment is this one — follow it.
+ // (PullCap 2026-10-24 23:21: a paid send was marked 'revoking' here.)
+ if (e instanceof GrpcError && /state: ln-spent/i.test(e.message)) {
+ action.step = 'initiated';
+ this._save();
// INVALID_ARGUMENT: the server itself deems the invoice unpayable —
// retrying can never succeed, revoke the HTLC instead
- if (e instanceof GrpcError && e.grpcStatus === 3) {
+ } else if (e instanceof GrpcError && e.grpcStatus === 3) {
action.error = e.message;
action.step = 'revoking';
this._save();
@@ -1707,7 +1732,22 @@ export class ArkManager {
this._save();
}
}
- if (action.step === 'revoking') await this._revokeLnPay(action);
+ if (action.step === 'revoking') {
+ // Ask first: a send can land in 'revoking' over a stale copy of the
+ // state while the payment went through (or is still going) — a
+ // settled payment is settled here too, and one in flight waits.
+ const res = await checkLightningPayment(this.arkUrl, hex.decode(action.paymentHash), false).catch(() => null);
+ if (res && res.status === 'success' && res.preimage
+ && hex.encode(sha256(hex.decode(res.preimage))) === action.paymentHash) {
+ this._settleLnPay(action, res.preimage);
+ return;
+ }
+ if (res && res.status === 'pending' && action.htlcExpiry) {
+ const tip = await this.chain.tipHeight().catch(() => 0);
+ if (tip && tip <= action.htlcExpiry) { action.step = 'initiated'; delete action.error; this._save(); return; }
+ }
+ await this._revokeLnPay(action);
+ }
}
_settleLnPay(action, preimageHex) {
diff --git a/src/features/ark.js b/src/features/ark.js
index b155d17..0a529c5 100644
--- a/src/features/ark.js
+++ b/src/features/ark.js
@@ -8,7 +8,7 @@ import * as btc from '@scure/btc-signer';
import { HDKey } from '@scure/bip32';
import { hex, base32nopad, bech32 } from '@scure/base';
import { sha256 } from '@noble/hashes/sha256';
-import { ArkManager, remoteRenewalsInFlight, lnFoldedIds, renewPolicy, CUSTODY_TIERS } from '../ark/manager.js';
+import { ArkManager, remoteRenewalsInFlight, lnFoldedIds, sameDelivery, renewPolicy, CUSTODY_TIERS } from '../ark/manager.js';
export { remoteRenewalsInFlight };
// Coins this device may offer: spendable, and not held by a renewal another
@@ -1011,7 +1011,7 @@ export function arkFeature(ctx) {
offer,
autowithdraw: await awMirror(prev),
});
- if (prev) rec.spends = prev.spends; // the worker's log survives rewrites
+ if (prev) { rec.spends = prev.spends; rec.pendingPays = prev.pendingPays; } // the worker's log survives rewrites
if (prefs) rec.prefs = prefs; // notification choices the worker honours
await saveBg(wallet._cacheKey(), rec);
await disarmSiblingRecords(wallet._cacheKey(), rec).catch(() => {});
@@ -1499,9 +1499,12 @@ export function arkFeature(ctx) {
h('span', { class: g.claimed ? 'tag conf' : 'tag' },
g.claimed ? t('giftClaimedTag') : g.revoked ? t('giftRevokedTag') : t('giftUnclaimedTag')));
})(),
- (() => { const pk = zapNoteFor(m); return pk ? ctx.hook('profileChip', pk) : null; })(),
- m.status !== 'complete' && !failed ? h('span', { class: 'tag pending' }, m.status === 'pending' ? t('arkExitPendingTag') : m.status) : null),
- h('div', { class: 'small faint' }, timeAgo(m.ts / 1000))),
+ (() => { const pk = zapNoteFor(m); return pk ? ctx.hook('profileChip', pk) : null; })()),
+ // the status tag sits by the time, not the name: in the narrow wallet
+ // column the title row has room for the label and the chip, not a
+ // third thing — the chip was breaking mid-name to make space
+ h('div', { class: 'row gap6 small faint' }, timeAgo(m.ts / 1000),
+ m.status !== 'complete' && !failed ? h('span', { class: 'tag pending' }, m.status === 'pending' ? t('arkExitPendingTag') : m.status) : null)),
h('div', { style: 'text-align:right' },
// in fiat this is what the payment was worth when it was made
h('div', { class: failed ? 'muted' : incoming ? 'amount-pos' : 'amount-neg' }, fmtAmount(m.amountSat, m.ts / 1000)))
@@ -1670,6 +1673,7 @@ export function arkFeature(ctx) {
})(),
m.to ? row(t('arkPayTo'), shortAddr(m.to, 16, 12)) : null,
m.vtxoId ? row(t('arkVtxoId'), shortTxid(m.vtxoId)) : null,
+ m.type === 'receive' ? coinListRows(t('arkVtxoId'), m.vtxoIds) : null,
// the coins this payment consumed — a send can gather up to 24 inputs
coinListRows(t('arkVtxoInputs'), m.inputIds),
// An offboard's fee is two different pockets — the miners' cut for the
@@ -1718,7 +1722,7 @@ export function arkFeature(ctx) {
const g = giftForMovement(m);
const open = g && !g.claimed && !g.revoked;
const chips = [
- open ? copyBtn(`${location.origin}/g/${encodeArkGiftCode(getNetwork(), g.amountSat, hex.decode(g.secretHex))}`, t('giftCopyLinkAgain')) : null,
+ open ? copyBtn(`${location.origin}/g/${encodeArkGiftCode(getNetwork(), g.amountSat, hex.decode(g.secretHex))}${g.note ? '#m=' + encodeURIComponent(g.note) : ''}`, t('giftCopyLinkAgain')) : null,
m.preimage ? copyBtn(m.preimage, t('copyPreimage')) : null,
m.txid ? copyBtn(m.txid, t('copyTxid')) : null,
m.txid ? h('a', { class: 'btn btn-sm', href: url, target: '_blank', rel: 'noopener', onClick: (e) => { e.preventDefault(); openExternal(url); } }, t('viewOnMempool')) : null,
@@ -2224,23 +2228,8 @@ export function arkFeature(ctx) {
const spk = btc.OutScript.encode(btc.Address(wallet.netCfg.net).decode(target.address));
// Offboarding moves whole vtxos, so carve out the exact amount first
// when we're not sending everything.
- const spendables = () => freeCoins(mgr.state);
- const total = spendables().reduce((n, v) => n + v.amountSat, 0);
- let ids;
- if (amountSat < total) {
- let exact = spendables().find((v) => v.amountSat === amountSat);
- if (!exact) {
- const before = new Set(spendables().map((v) => v.id));
- await mgr.send(mgr.address(), amountSat);
- for (let i = 0; i < 30 && !exact; i++) {
- await new Promise((r) => setTimeout(r, 2000));
- await mgr.sync().catch(() => {});
- exact = spendables().find((v) => v.amountSat === amountSat && !before.has(v.id));
- }
- if (!exact) throw new Error(t('arkSplitTimeout'));
- }
- ids = [exact.id];
- }
+ const total = freeCoins(mgr.state).reduce((n, v) => n + v.amountSat, 0);
+ const ids = amountSat < total ? await carveCoins(mgr, amountSat) : undefined;
await mgr.startOffboard(spk, target.address, ids);
return;
}
@@ -2692,7 +2681,7 @@ export function arkFeature(ctx) {
const view = arkView();
const info = (view && view.info) || (cachedArkInfo(cfg && cfg.ark) || {}).info || null;
const honors = !!(cfg && cfg.honorsExpired);
- const cur = honors ? getCustody() : 'self';
+ const cur = getCustody(); // never 'custodial' on a server that doesn't honor expired coins
const base = (info && info.refreshFees && info.refreshFees.baseFeeSat) || 0;
const table = (info && info.refreshFees && info.refreshFees.ppmExpiryTable) || [];
const ppmAt = (blocks) => (table.filter((e) => e.thresholdBlocks <= blocks).pop()?.ppm) ?? 0;
@@ -3182,7 +3171,7 @@ export function arkFeature(ctx) {
// Fund a fresh bearer gift identity. Shared by the gifts feature's hook and
// the zap flow's locked-gift fallback; `lockedTo` records who a locked gift
// was for (the sender can still revoke either kind while unclaimed).
- async function createArkGift(amountSat, lockedTo = null) {
+ async function createArkGift(amountSat, lockedTo = null, note = null) {
const mgr = await connectArk();
const secret = crypto.getRandomValues(new Uint8Array(32));
const secretHex = hex.encode(secret);
@@ -3192,7 +3181,7 @@ export function arkFeature(ctx) {
const action = mgr.state.actions.find((a) => a.id === actionId);
if (!action || action.step === 'failed') throw new Error(action?.error || t('claimFailed'));
const vtxoId = decodeVtxo(hex.decode((action.destBytesList || [action.destBytes])[0])).id;
- arkGiftRecords().push({ id: vtxoId, amountSat, secretHex, created: Date.now(), revoked: false, claimed: false, ...(lockedTo ? { lockedTo } : {}) });
+ arkGiftRecords().push({ id: vtxoId, amountSat, secretHex, created: Date.now(), revoked: false, claimed: false, ...(lockedTo ? { lockedTo } : {}), ...(note ? { note } : {}) });
mgr._save();
return { code: encodeArkGiftCode(getNetwork(), amountSat, secret), amount: amountSat, address };
}
@@ -3316,6 +3305,58 @@ export function arkFeature(ctx) {
})());
}
+ // A set of coins adding up to exactly `amountSat`: one coin of that size,
+ // else the smallest subset of the free coins that sums to it (largest coins
+ // first, so an offboard takes as few inputs as it can). null when no subset
+ // fits. Reachable sums are built up coin by coin, capped so a balance in
+ // hundreds of dust coins can't stall the tap.
+ function exactCoins(coins, amountSat) {
+ const one = coins.find((v) => v.amountSat === amountSat);
+ if (one) return [one];
+ const sorted = [...coins].filter((v) => v.amountSat > 0 && v.amountSat < amountSat).sort((a, b) => b.amountSat - a.amountSat);
+ const reach = new Map([[0, null]]); // sum -> { coin, prev } that first reached it
+ for (const v of sorted) {
+ const add = [];
+ for (const sum of reach.keys()) {
+ const next = sum + v.amountSat;
+ if (next <= amountSat && !reach.has(next)) add.push([next, { coin: v, prev: sum }]);
+ }
+ for (const [sum, via] of add) reach.set(sum, via);
+ if (reach.has(amountSat)) break;
+ if (reach.size > 50_000) return null;
+ }
+ if (!reach.has(amountSat)) return null;
+ const picked = [];
+ for (let sum = amountSat; sum > 0;) { const via = reach.get(sum); picked.push(via.coin); sum = via.prev; }
+ return picked;
+ }
+ // The coins that leave Spending for an on-chain send of `amountSat`. An
+ // offboard moves whole vtxos, so the amount has to be covered exactly:
+ // by coins already in the wallet when they fit (a balance that happens to
+ // add up, or the halves an earlier split left behind), else an exact amount
+ // is split off by paying it to this wallet's own address. A payment spread
+ // over several inputs arrives as several coins, one per input with the last
+ // carrying the remainder, so what the split yields is every coin that lands
+ // on the receive key and adds up to the amount, not a single coin of that
+ // size: looking for one made every partial on-chain send from a balance
+ // in two or more coins time out (Jarryd, 2026-10-23, three splits and no
+ // send). Change from the split carries its own key index and stays.
+ async function carveCoins(mgr, amountSat) {
+ const free = () => freeCoins(mgr.state);
+ const have = exactCoins(free(), amountSat);
+ if (have) return have.map((v) => v.id);
+ const before = new Set(free().map((v) => v.id));
+ await mgr.send(mgr.address(), amountSat);
+ for (let i = 0; i < 30; i++) {
+ await mgr.sync().catch(() => {});
+ const landed = free().filter((v) => !before.has(v.id) && !v.keyIndex);
+ const hit = exactCoins(landed, amountSat);
+ if (hit) return hit.map((v) => v.id);
+ await new Promise((r) => setTimeout(r, 2000));
+ }
+ throw new Error(t('arkSplitTimeout'));
+ }
+
// vtxoIds: exactly these coins go (the coins page's ticked subset);
// otherwise an amount is split off the balance, or everything goes.
async function doArkOffboard(amountSat, destAddress = null, vtxoIds = undefined) {
@@ -3324,23 +3365,9 @@ export function arkFeature(ctx) {
const address = destAddress || wallet.freshReceive().address;
const spk = addrScript(address);
const mgr = await connectArk();
- const spendables = () => freeCoins(mgr.state);
- const total = spendables().reduce((n, v) => n + v.amountSat, 0);
+ const total = freeCoins(mgr.state).reduce((n, v) => n + v.amountSat, 0);
let ids = vtxoIds; // undefined = all spendable vtxos
- if (!ids && amountSat && amountSat < total) {
- let target = spendables().find((v) => v.amountSat === amountSat);
- if (!target) {
- const before = new Set(spendables().map((v) => v.id));
- await mgr.send(mgr.address(), amountSat);
- for (let i = 0; i < 30 && !target; i++) {
- await new Promise((r) => setTimeout(r, 2000));
- await mgr.sync().catch(() => {});
- target = spendables().find((v) => v.amountSat === amountSat && !before.has(v.id));
- }
- if (!target) throw new Error(t('arkSplitTimeout'));
- }
- ids = [target.id];
- }
+ if (!ids && amountSat && amountSat < total) ids = await carveCoins(mgr, amountSat);
const action = await mgr.startOffboard(spk, address, ids);
ui.arkOffboardAmt = '';
ui.arkMoveOpen = false;
@@ -3379,10 +3406,20 @@ export function arkFeature(ctx) {
// happening anyway, for next to nothing; the Manage page consolidates on
// request.
const CUSTODY_DEFAULT = 'custodial';
+ // The tier in force: the stored choice, except that "coinos holds my coins"
+ // exists only on a server that honors a coin past its timelock. Anywhere
+ // else (Second, a custom captaind) an expired coin is gone, so renewal is
+ // automatic there whatever is stored — the stored default stays on the
+ // record for a later switch back to a coinos server. From 2026-10-22 to
+ // 10-23 the stored default applied everywhere, and a wallet on such a
+ // server renewed nothing and warned of nothing, in the app and the worker.
function getCustody() {
let v = wallet.loadFeatureState ? wallet.loadFeatureState('arkCustody', null) : null;
if (v === 'early') v = 'exit'; // the third tier's first name (one day in October 2026)
- return CUSTODY_TIERS.includes(v) ? v : CUSTODY_DEFAULT;
+ const tier = CUSTODY_TIERS.includes(v) ? v : CUSTODY_DEFAULT;
+ if (tier !== 'custodial') return tier;
+ const cfg = getArkConfig();
+ return cfg && !cfg.honorsExpired ? 'self' : tier;
}
function setCustody(tier) { if (wallet.saveFeatureState) wallet.saveFeatureState('arkCustody', tier); }
const custodyPolicy = () => renewPolicy(getCustody(), getNetwork());
@@ -3393,8 +3430,10 @@ export function arkFeature(ctx) {
// (there is no cancel; a spent input voids one) — they were priced when
// registered and renew one coin each, once.
function applyCustody(tier) {
- if (!CUSTODY_TIERS.includes(tier) || tier === getCustody()) return;
- setCustody(tier);
+ if (!CUSTODY_TIERS.includes(tier)) return;
+ const same = tier === getCustody();
+ setCustody(tier); // the record keeps the choice even when it is already in force here
+ if (same) return;
arkAutoRefreshAt = 0; arkBackstopAt = 0; arkRenewWarn = null;
if (ark && ark.state) maybeAutoRefresh(ark).catch(() => {});
writeBgMirror().catch(() => {});
@@ -4254,7 +4293,22 @@ export function arkFeature(ctx) {
for (const m of s.movements || []) for (const id of m.inputIds || []) accounted.add(id);
const out = [];
const seenCoin = new Set();
+ // One payment delivered as several coins (a gift held in two, a
+ // dust-padded split) is one row: receives from the same mailbox
+ // message (`batch`; older rows: the same delivery instant) fold.
+ const folded = new Map();
for (const m of moves) {
+ if (m.type === 'receive' && sameDelivery(out[out.length - 1], m)) {
+ const last = out[out.length - 1];
+ if (!folded.has(last.id)) {
+ const f = { ...last, vtxoIds: [last.vtxoId], vtxoId: null };
+ out[out.length - 1] = f; folded.set(f.id, f);
+ }
+ const f = folded.get(last.id);
+ f.amountSat += m.amountSat;
+ f.vtxoIds.push(m.vtxoId);
+ continue;
+ }
if (m.type !== 'reconcile') { out.push(m); continue; }
if (m.vtxoId && (seenCoin.has(m.vtxoId) || accounted.has(m.vtxoId))) continue;
if (m.vtxoId) seenCoin.add(m.vtxoId);
@@ -4267,6 +4321,7 @@ export function arkFeature(ctx) {
out.push({ ...m, count: 1, vtxoIds: m.vtxoId ? [m.vtxoId] : [] });
}
}
+ this._histFolded = folded; // a folded row's detail shows the whole payment
return exits.concat(renewals, lnPending, out.map((m) => ({ time: m.ts, render: () => arkHistoryItem(m), csv: arkCsvRow(m) })));
},
historyDetail() {
@@ -4286,7 +4341,8 @@ export function arkFeature(ctx) {
if (done) return arkMoveDetailView(done);
if (a && !['done', 'failed'].includes(a.step)) return arkMoveDetailView(lnPendingMove(a));
}
- const m = s ? (s.movements || []).find((x) => x.id === ui.arkMoveDetail) : null;
+ if (s) this.historyEntries(); // (memoized) keeps the folded rows current
+ const m = s ? (this._histFolded && this._histFolded.get(ui.arkMoveDetail)) || (s.movements || []).find((x) => x.id === ui.arkMoveDetail) : null;
if (m) return arkMoveDetailView(m);
ui.arkMoveDetail = null;
return null;
@@ -4437,7 +4493,7 @@ export function arkFeature(ctx) {
setNetwork(g.net);
return true;
},
- arkGiftCreate(amountSat) { return createArkGift(amountSat); },
+ arkGiftCreate(amountSat, note) { return createArkGift(amountSat, null, note); },
// Claim-side status: claimable (with the live amount), taken, wrongnet, or
// unknown (not visible here — wrong server or not yet delivered).
async arkGiftStatus(code) {
diff --git a/src/features/gifts-wallet.js b/src/features/gifts-wallet.js
index 824ddc0..7004b12 100644
--- a/src/features/gifts-wallet.js
+++ b/src/features/gifts-wallet.js
@@ -274,9 +274,9 @@ export function installGiftWallet(wallet) {
// gift's link/QR can be re-viewed later and a claimed one identified in history.
_giftRecordsKey() { return this._cacheKey() + ':giftrec'; },
- recordGift({ code, locked, amount, claimCode, outpoints }) {
+ recordGift({ code, locked, amount, claimCode, outpoints, note }) {
if (!outpoints || !outpoints.length) return;
- this.giftRecords()[outpoints[0]] = { id: outpoints[0], code, locked: !!locked, amount, claimCode: claimCode || null, outpoints, created: Date.now(), revoked: false };
+ this.giftRecords()[outpoints[0]] = { id: outpoints[0], code, locked: !!locked, amount, claimCode: claimCode || null, outpoints, created: Date.now(), revoked: false, ...(note ? { note } : {}) };
this._saveGiftRecords();
try { this.saveCache(); } catch {} // publish the new gift to cross-device sync
},
diff --git a/src/features/gifts.js b/src/features/gifts.js
index 56fd99e..399a807 100644
--- a/src/features/gifts.js
+++ b/src/features/gifts.js
@@ -15,7 +15,7 @@ export function giftsFeature(ctx) {
h, ui, render, wallet, toast, copyBtn, pasteBtn, blankSend, goBack, goHome, openExternal,
fmtAmount, unitLabel, unitTag, parseAmount, getUnit, toggleUnit, download,
brandHeader, activeAccount, setAccounts, getAccounts, claimTargets,
- enterWallet, activateAccount, commitAccount,
+ enterWallet, activateAccount, commitAccount, pickConfirm,
} = ctx;
installGiftWallet(wallet); // gift primitives live outside the core wallet
// Ark-gift support comes from the ark feature (when this build ships it);
@@ -32,6 +32,7 @@ export function giftsFeature(ctx) {
try {
const am = location.pathname.match(/^\/ag\/([A-Za-z0-9]+)\/?$/i); // ark gift
if (am) {
+ ui.claimNote = readNoteFrag();
history.replaceState(null, '', '/');
return arkGiftOf(am[1]) ? am[1] : null;
}
@@ -43,6 +44,7 @@ export function giftsFeature(ctx) {
if (hm) code = hm[1];
}
if (!code) return null;
+ if (pm) ui.claimNote = readNoteFrag();
history.replaceState(null, '', '/');
return previewGift(code) ? code : null;
} catch {
@@ -57,6 +59,7 @@ export function giftsFeature(ctx) {
try {
const m = location.pathname.match(/^\/lg\/([A-Za-z0-9_-]+)\/?$/);
if (!m) return null;
+ ui.claimNote = null;
history.replaceState(null, '', '/');
return previewLockedGift(m[1]);
} catch { return null; }
@@ -120,6 +123,25 @@ export function giftsFeature(ctx) {
if (!acceptLockedPayload(payload)) { ui.claimError = t('claimCodeWrong'); render(); }
}
+ // A gift's note rides its link after the # (#m=<text>): the fragment never
+ // leaves the browser, so no server sees it, and it is only as private as the
+ // link itself (which already IS the money).
+ const GIFT_NOTE_MAX = 280;
+ const noteFrag = (note) => (note ? '#m=' + encodeURIComponent(note) : '');
+ function readNoteFrag() {
+ try {
+ const m = new URLSearchParams(location.hash.slice(1)).get('m');
+ return m ? m.trim().slice(0, GIFT_NOTE_MAX) || null : null;
+ } catch { return null; }
+ }
+ // the sender's words, quoted above the amount wherever the gift is opened
+ const giftNoteView = () => (ui.claimNote
+ ? h('blockquote', { class: 'gift-note' }, ui.claimNote)
+ : null);
+ // with a note the link has lower case in it: a byte-mode QR (the bare
+ // link is upper-cased into the denser alphanumeric mode)
+ const giftQr = (url, hasNote) => qrSvg(hasNote ? url : url.toUpperCase(), { ec: 'L', mode: hasNote ? undefined : 'Alphanumeric' });
+
// Entry point for claiming a gift code. If the recipient already has wallet(s),
// offer to claim into one or make a new one; otherwise go straight to a fresh
// wallet (the original first-timer flow).
@@ -171,6 +193,7 @@ export function giftsFeature(ctx) {
h('div', { class: 'card col', style: 'align-items:center;text-align:center;gap:12px' },
h('div', { class: 'check-badge', style: 'background:var(--accent)' }, '🎁'),
h('h2', { style: 'margin:0' }, t('giftWelcome')),
+ giftNoteView(),
pv ? h('div', { class: 'amt', style: 'font-size:30px' }, h('span', { class: 'amount-pos' }, fmtAmount(pv.room)), ' ', unitTag('unit')) : null,
h('div', { class: 'small faint' }, claimFeeNote(code)),
h('p', { class: 'muted', style: 'margin:0' }, t('claimIntoPrompt'))
@@ -214,7 +237,7 @@ export function giftsFeature(ctx) {
),
h('div', { class: 'row gap6' }, copyBtn(wallet.mnemonic, t('copyPhrase'))),
h('button', { class: 'btn-primary btn-block', onClick: () => { ui.confirm = pickConfirm(words); ui.claimError = ''; ui.claimStep = 'verify'; render(); } }, t('verifyBackup')),
- h('button', { class: 'btn-block', onClick: () => { ui.screen = 'wallet'; ui.claimStep = null; landAccount(); render(); } }, t('skipVerification'))
+ h('button', { class: 'btn-block', onClick: finishClaim }, t('skipVerification'))
)
);
}
@@ -246,13 +269,11 @@ export function giftsFeature(ctx) {
onClick: () => {
const ok = ui.confirm.every((c) => c.value.toLowerCase() === words[c.index]);
if (!ok) { ui.claimError = t('wordsMismatch'); render(); return; }
- ui.screen = 'wallet'; ui.claimStep = null; ui.claimError = '';
- landAccount();
- render();
+ finishClaim();
},
}, t('openWallet'))
),
- h('button', { class: 'btn-block', onClick: () => { ui.screen = 'wallet'; ui.claimStep = null; landAccount(); render(); } }, t('skipVerification'))
+ h('button', { class: 'btn-block', onClick: finishClaim }, t('skipVerification'))
)
);
}
@@ -313,6 +334,7 @@ export function giftsFeature(ctx) {
h('div', { class: 'card col', style: 'align-items:center;text-align:center;gap:12px' },
h('div', { class: 'check-badge', style: 'background:var(--accent)' }, '🎁'),
h('h2', { style: 'margin:0' }, t('giftWelcome')),
+ giftNoteView(),
h('div', { class: 'amt', style: 'font-size:30px' },
h('span', { class: 'amount-pos' }, fmtAmount(total)), ' ', unitTag('unit')
),
@@ -324,10 +346,12 @@ export function giftsFeature(ctx) {
!ui.claimError && ui.claimNotVisible && h('div', { class: 'notice info' }, t('claimNotVisibleBody')),
ui.busy || ui.claimChecking
? h('button', { class: 'btn-primary btn-block', disabled: true }, h('span', { class: 'spinner' }))
+ // an ark gift costs nothing to claim: just the button (an on-chain
+ // one says what its network fee will take)
: h('button', { class: 'btn-primary btn-block', onClick: doClaim },
- t('claimBtn'), ' ',
- h('span', { style: 'font-size:0.85em;opacity:0.9' },
- '(' + (ag ? t('claimArkFree') : t('claimFeeNote', { n: fmtAmount(estFee) + ' ' + unitLabel() })) + ')'))
+ ...(ag ? [t('claimNowBtn')] : [t('claimBtn'), ' ',
+ h('span', { style: 'font-size:0.85em;opacity:0.9' },
+ '(' + t('claimFeeNote', { n: fmtAmount(estFee) + ' ' + unitLabel() }) + ')')]))
);
}
@@ -388,6 +412,16 @@ export function giftsFeature(ctx) {
if (ctx.setAccount) ctx.setAccount('spending');
}
+ // The seed is written down: into the new wallet — by way of the
+ // wizard's username, avatar and cover, so a gift's recipient arrives as
+ // someone people can pay by name (skippable, like any first run).
+ function finishClaim() {
+ ui.screen = 'wallet'; ui.claimStep = null; ui.claimError = '';
+ landAccount();
+ if (ctx.offerProfileSetup) ctx.offerProfileSetup({ home: ui.claimVia === 'ark' ? 'spending' : 'savings' });
+ render();
+ }
+
function afterClaim(amount) {
ui.claimedAmount = amount;
const wasProvisional = !!(activeAccount() && activeAccount().provisional);
@@ -526,13 +560,14 @@ export function giftsFeature(ctx) {
// the sender can re-share an unclaimed gift.
function viewGiftView() {
const g = ui.viewGift; // { code, locked, amount, claimCode }
- const url = `${location.origin}/g/${g.code}`;
+ const url = `${location.origin}/g/${g.code}${noteFrag(g.note)}`;
let svg = null;
- try { svg = qrSvg(url.toUpperCase(), { ec: 'L', mode: 'Alphanumeric' }); } catch {}
+ try { svg = giftQr(url, !!g.note); } catch {}
return h('div', { class: 'col', style: 'gap:16px;padding:16px;max-width:460px;margin:0 auto;width:100%' },
h('div', { class: 'card col', style: 'gap:12px;align-items:center' },
h('h3', { style: 'margin:0' }, t('giftView')),
g.amount != null ? h('div', { class: 'amt' }, fmtAmount(g.amount), ' ', unitTag()) : null,
+ g.note ? h('blockquote', { class: 'gift-note', style: 'width:100%' }, g.note) : null,
svg ? h('div', { html: svg }) : h('div', { class: 'small faint', style: 'text-align:center;padding:8px' }, t('giftQrTooLong')),
h('div', { class: 'addr-box break', style: 'width:100%;font-size:12px' }, url),
copyBtn(url, t('copyLink')),
@@ -567,7 +602,7 @@ export function giftsFeature(ctx) {
}
ui.busy = true; ui.giftError = ''; render();
try {
- const g = await hook('arkGiftCreate', amt);
+ const g = await hook('arkGiftCreate', amt, giftNoteNow());
ui.giftIsArk = true;
finishGift(g, amt);
} catch (e) {
@@ -615,8 +650,10 @@ export function giftsFeature(ctx) {
function finishGift(g, fallbackAmt) {
const amount = g.amount || fallbackAmt || 0;
ui.giftCode = g.code;
- wallet.recordGift({ code: g.code, locked: false, amount, outpoints: g.reserved });
+ ui.giftNoteMade = giftNoteNow(); // the link says what was typed when it was made
+ wallet.recordGift({ code: g.code, locked: false, amount, outpoints: g.reserved, note: ui.giftNoteMade });
}
+ const giftNoteNow = () => String(ui.giftNote || '').trim().slice(0, GIFT_NOTE_MAX) || null;
function giftCard() {
const active = wallet.outstandingGifts();
@@ -631,13 +668,14 @@ export function giftsFeature(ctx) {
// (many-input) gift can exceed QR capacity — then fall back to the link.
(() => {
let svg = null;
- try { svg = qrSvg(giftUrl().toUpperCase(), { ec: 'L', mode: 'Alphanumeric' }); } catch {}
+ try { svg = giftQr(giftUrl(), !!ui.giftNoteMade); } catch {}
return svg ? h('div', { html: svg }) : h('div', { class: 'small faint', style: 'text-align:center;padding:8px' }, t('giftQrTooLong'));
})(),
+ ui.giftNoteMade ? h('blockquote', { class: 'gift-note', style: 'width:100%' }, ui.giftNoteMade) : null,
h('div', { class: 'addr-box break', style: 'width:100%;font-size:12px' }, giftUrl()),
h('div', { class: 'row gap6 wrap' },
copyBtn(giftUrl(), t('copyLink')),
- h('button', { class: 'btn-sm grow', onClick: () => { ui.giftCode = null; ui.giftAmount = ''; ui.giftMax = false; ui.giftIsArk = false; render(); } }, t('giftAnother'))
+ h('button', { class: 'btn-sm grow', onClick: () => { ui.giftCode = null; ui.giftAmount = ''; ui.giftNote = ''; ui.giftNoteMade = null; ui.giftMax = false; ui.giftIsArk = false; render(); } }, t('giftAnother'))
)
)
: ui.giftSplitOffer
@@ -692,6 +730,9 @@ export function giftsFeature(ctx) {
ui.giftSource === 'chain'
? h('div', { class: 'notice warn small' }, t('giftChainWarn'))
: null,
+ // an optional note, shown to whoever opens the gift
+ h('textarea', { class: 'gift-note-input', rows: 2, maxlength: GIFT_NOTE_MAX, placeholder: t('giftNotePlaceholder'),
+ value: ui.giftNote || '', onInput: (e) => { ui.giftNote = e.target.value; } }),
ui.giftError && h('div', { class: 'notice err' }, ui.giftError),
ui.busy
? h('button', { class: 'btn-block', disabled: true }, h('span', { class: 'spinner sm' }))
@@ -864,7 +905,7 @@ export function giftsFeature(ctx) {
// Gift link: presign a chosen amount as a #gift= PSBT that whoever opens claims
// into a fresh wallet only they control. The coin is reserved until claimed.
function giftUrl() {
- return `${location.origin}/${ui.giftIsArk ? 'ag' : 'g'}/${ui.giftCode}`;
+ return `${location.origin}/${ui.giftIsArk ? 'ag' : 'g'}/${ui.giftCode}${noteFrag(ui.giftNoteMade)}`;
}
function giftRate() {
diff --git a/src/features/messages.js b/src/features/messages.js
index 030d9fa..6c6b48d 100644
--- a/src/features/messages.js
+++ b/src/features/messages.js
@@ -67,7 +67,12 @@ import { mergeFeeds } from '../feed-sync.js';
// coinos's own relay and primal: both take DM gift wraps and pass call
// messages (ephemeral 21059) on live. nos.lol was here until 2026-10-19 — it
// refused or ignored the household IP's publishes, call answers among them.
-const DM_RELAYS = ['wss://relay.coinos.io', 'wss://relay.primal.net'];
+// messages.coinos.io (Magnitude Relay, built for gift-wrapped messages) leads;
+// relay.coinos.io stays on while older inbox lists still name it
+const MESSAGES_RELAY = 'wss://messages.coinos.io';
+const DM_RELAYS = [MESSAGES_RELAY, 'wss://relay.coinos.io', 'wss://relay.primal.net'];
+// what this app put in a wallet key's kind 10050 before messages.coinos.io
+const OLD_DM_DEFAULTS = ['wss://relay.coinos.io', 'wss://relay.primal.net', 'wss://nos.lol', 'wss://relay.damus.io'];
const NOTIFIER = 'https://nwcpush.coinos.io';
const APP_BASE = 'https://v3.coinos.io';
const CACHE_MAX = 50; // messages kept per channel / per DM thread in feature state
@@ -3314,12 +3319,19 @@ export function messagesFeature(ctx) {
// — the user's other clients own that. And when a login identity IS active,
// don't advertise the seed key at all: it's internal, not a second inbox
// (advertising it is what let DMs land on a phantom identity).
+ // A list this app wrote with its old defaults (nothing else in it) is
+ // brought up to today's, so senders find messages.coinos.io first.
async function ensureDmRelayList() {
if (!wallet.nostr || !wallet.nostr.sk) return;
if (hook('nostrLoginIdentity')) return;
const pk = wallet.nostr.pk;
const existing = await queryOn(DM_RELAYS, { kinds: [10050], authors: [pk] }, 2500);
- if (existing.length) return;
+ if (existing.length) {
+ const latest = existing.reduce((a, b) => (b.created_at > a.created_at ? b : a));
+ const urls = latest.tags.filter((x) => x[0] === 'relay').map((x) => String(x[1] || '').replace(/\/$/, ''));
+ const ours = urls.length && urls.every((u) => OLD_DM_DEFAULTS.includes(u));
+ if (!ours || urls.includes(DM_RELAYS[0])) return;
+ }
const evt = finalizeEvent({
kind: 10050,
content: '',
@@ -4123,7 +4135,8 @@ export function messagesFeature(ctx) {
// ---- profile notes: latest public posts & replies -----------------------
- const NOTE_RELAYS = [...new Set([...PROFILE_RELAYS, ...DM_RELAYS])];
+ // (not messages.coinos.io: it takes messages, not posts)
+ const NOTE_RELAYS = [...new Set([...PROFILE_RELAYS, ...DM_RELAYS.filter((r) => r !== MESSAGES_RELAY)])];
// ---- zap tallies ---------------------------------------------------------
// How much a post or chat message has been zapped: the public receipts
@@ -4528,10 +4541,12 @@ export function messagesFeature(ctx) {
const momentsOn = (id, file) => [...(timedActivity.get(id)?.values() || [])]
.filter(x => x.moment.url === mediaMoment(file, 0)?.url && !hiddenPk(x.ev.pubkey) && !isDeleted(x.ev))
.sort((a, b) => a.moment.seconds - b.moment.seconds)
- .map(x => ({ ...x, text: displayName(x.ev.kind === 9735 || x.ev.kind === 9737 ? zapperOf(x.ev) || x.ev.pubkey : x.ev.pubkey) + ' · ' + String(x.text || x.icon).slice(0, 240) }));
+ .map(x => ({ ...x, text: displayName(x.ev.kind === 9735 || x.ev.kind === 9737 ? zapperOf(x.ev) || x.ev.pubkey : x.ev.pubkey) + ' · ' + String(momentStripped(x.ev, x.text) || x.icon).slice(0, 240) }));
// how a moment shows on a bar: a reaction as its emoji (a :code: as its
- // picture, from the reaction's own tag), a zap ⚡, a reply ↩
+ // picture, from the reaction's own tag), a zap ⚡, a reply as its
+ // author's face
function momentGlyph(x) {
+ if (x.ev.kind === 1 || x.ev.kind === 1111) return avatar(x.ev.pubkey, 'chat-avatar media-mark-face', false);
if (x.ev.kind !== 7) return x.icon;
const code = shortcodeOf(x.ev.content);
const tag = code && x.ev.tags.find(t => t[0] === 'emoji' && t[1] === code && t[2]);
@@ -4551,6 +4566,19 @@ export function messagesFeature(ctx) {
}
return null;
}
+ // A comment made at a moment of a clip opens with its time as a link that
+ // plays the clip from there; the "[0:03] " other clients read as text is
+ // left out of the words beside it.
+ function momentLink(ev) {
+ const m = readMoment(ev);
+ if (!m) return null;
+ return h('a', { class: 'media-time-link', href: m.url + '#t=' + m.seconds, target: '_blank', rel: 'noopener noreferrer', onClick: e => {
+ e.stopPropagation();
+ const player = [...document.querySelectorAll('audio, video')].find(v => mediaMoment(v.dataset.clip || v.getAttribute('src'), 0)?.url === m.url);
+ if (player) { e.preventDefault(); const seek = () => { player.currentTime = Math.min(m.seconds, Number.isFinite(player.duration) ? player.duration : m.seconds); }; if (player.readyState) seek(); else player.addEventListener('loadedmetadata', seek, { once: true }); player.play().catch(() => {}); player.scrollIntoView({ block: 'center' }); }
+ } }, '▶ ' + mediaClock(m.seconds));
+ }
+ const momentStripped = (ev, text) => (readMoment(ev) ? String(text || '').replace(/^\s*\[\d{1,2}(?::\d{2}){1,2}\]\s*/, '') : text);
const withMoment = (ev) => { const m = momentOf(ev); return m ? { ...ev, mediaMoment: m } : ev; };
function attachMediaTimeline(player, url, explicitEvent) {
if (player._timeline) return;
@@ -4562,7 +4590,8 @@ export function messagesFeature(ctx) {
};
const box = player.parentElement;
box._skipMorph = true;
- box.append(mediaTimeline(player, url, { h, event, label: t, moments: momentsOn, glyph: momentGlyph }));
+ box.append(mediaTimeline(player, url, { h, event, label: t, moments: momentsOn, glyph: momentGlyph,
+ onMarks: player.tagName === 'VIDEO' ? (on) => ownBar(player, on) : null }));
player.dispatchEvent(new Event('timeupdate'));
}
function noteEvent(ev) {
@@ -7949,7 +7978,7 @@ export function messagesFeature(ctx) {
// known, never taller than the screen; only a clip taller than that sits
// in a black frame, rather than in a strip at the left.
const videoBoxStyle = (d) => d && d.width && d.height
- ? `width:100%;aspect-ratio:${d.width}/${d.height};max-height:100vh;object-fit:contain`
+ ? `width:100%;aspect-ratio:${d.width}/${d.height};max-height:var(--vid-cap);object-fit:contain`
: 'width:100%;aspect-ratio:16/9;object-fit:contain';
// Over a clip that waits for a tap: what it costs, and the tap that plays
// it (with sound — the reader asked for this one). The box is left alone
@@ -7967,7 +7996,7 @@ export function messagesFeature(ctx) {
if (v) {
if (v.getAttribute('src') !== playSrc(url)) v.setAttribute('src', playSrc(url));
v.preload = 'auto';
- v.play().catch(() => { wokeClips.add(url); box.classList.remove('idle'); v.controls = true; });
+ v.play().catch(() => { wokeClips.add(url); box.classList.remove('idle'); nativeControls(v); });
}
} }, h('span', { class: 'vid-heavy-play', 'aria-hidden': 'true' }, '\u25b6'), h('span', {}, heavyLabel(url)));
box.append(cover);
@@ -8095,10 +8124,38 @@ export function messagesFeature(ctx) {
});
}
// A tap on the picture itself (not the player's own play button or its
- // control bar): inline, it goes full screen — the corner button is a
+ // control bar): inline, a mouse click pauses a playing clip; a paused one
+ // (or any touch) goes full screen — the corner button is a
// reach on a phone. Full screen, it pauses a playing clip, and a tap on a
// paused one comes back out. The player's controls are inside the video
// element, so where they sit is judged from the tap's position.
+ // The big play/pause over a feed clip is for a mouse: <html> carries
+ // .has-mouse while the last pointer was one (a touch laptop switches with
+ // the hand), and CSS shows the button on :hover (a repaint can't drop it).
+ if (typeof document !== 'undefined') {
+ const mouseIs = (on) => document.documentElement.classList.toggle('has-mouse', on);
+ document.addEventListener('pointermove', (e) => { if (e.pointerType === 'mouse') mouseIs(true); }, { passive: true });
+ document.addEventListener('pointerdown', (e) => { if (e.pointerType !== 'mouse') mouseIs(false); }, { passive: true });
+ }
+ // A clip whose post has timed reactions seeks on the moments bar under it
+ // (the reactions sit on it at their moments), so the player's own controls
+ // — a second seek bar — stay off; the middle button and the sound button
+ // are its controls then (Adam: "hide the main seek bar … and only show a
+ // moments seek bar"). Otherwise the player's controls, once it has woken.
+ const nativeControls = (v) => { v.controls = !v._ownBar; };
+ function ownBar(player, on) {
+ const box = player.closest('.note-video-box');
+ if (!box || player._ownBar === on) return;
+ player._ownBar = on;
+ box.classList.toggle('own-bar', on);
+ if (!box.classList.contains('idle')) nativeControls(player);
+ // with no player controls, the sound button stays to turn it back down
+ if (on && !box.querySelector('.vid-sound')) {
+ const b = soundBtn((button) => { player.muted = !player.muted; button.setSound(!player.muted); });
+ b.setSound(!player.muted);
+ box.append(b);
+ }
+ }
const fsElement = () => (typeof document !== 'undefined' && (document.fullscreenElement || document.webkitFullscreenElement)) || null;
let videoTapAt = 0; // a touch's tap on a clip, taken at pointerup: the click after it lands on whatever opened
function videoTap(e, url) {
@@ -8120,12 +8177,24 @@ export function messagesFeature(ctx) {
else (document.exitFullscreen || document.webkitExitFullscreen || (() => {})).call(document)?.catch?.(() => {});
return true;
}
+ // a mouse click on a playing clip just pauses it (Adam: "clicking on a
+ // video that's playing should pause the video, not full screen it"); it
+ // keeps its controls and the middle button resumes it, and a click on it
+ // paused opens the pager. A touch has no middle button: its tap still opens.
+ if (!v.paused && e.pointerType === 'mouse') {
+ v.pause();
+ wokeClips.add(url);
+ const box = v.closest('.note-video-box');
+ if (box) { box.classList.remove('idle'); box._skipMorph = true; }
+ nativeControls(v);
+ return true;
+ }
if (openClip(v, url)) return true;
// a clip still idle (autoplaying, no controls) becomes the reader's
wokeClips.add(url);
const box = v.closest('.note-video-box');
if (box) { box.classList.remove('idle'); box._skipMorph = true; }
- v.controls = true;
+ nativeControls(v);
const go = v.requestFullscreen || v.webkitRequestFullscreen || v.webkitEnterFullscreen;
if (!go) return true;
// (the screen isn't turned for it: a wide clip plays with bars, and the
@@ -8187,13 +8256,38 @@ export function messagesFeature(ctx) {
if (videoTap(e, url)) el._tapAt = videoTapAt = Date.now();
});
v.muted = !loud; // the property, not just the attribute: a script-made element autoplays only muted
- const box = h('div', { class: 'note-video-box' + (idle ? ' idle' : '') }, v);
+ // a tall clip is held to the cap's height and the box narrows to its
+ // shape, instead of a full-width box of black bars (Adam, on a 1920 screen)
+ const boxCap = (w, ht) => w && ht ? `max-width:calc(var(--vid-cap) * ${w} / ${ht})` : undefined;
+ const known = feedMedia(url);
+ const box = h('div', { class: 'note-video-box' + (idle ? ' idle' : ''), style: boxCap(known && known.width, known && known.height) }, v);
+ v.addEventListener('loadedmetadata', () => { if (v.videoWidth && v.videoHeight) box.style.maxWidth = `calc(var(--vid-cap) * ${v.videoWidth} / ${v.videoHeight})`; });
if (loud) box._skipMorph = true;
+ // With a mouse: a big play/pause button in the middle while the pointer is
+ // over the clip. It plays or pauses in place, never full screen (a click
+ // elsewhere on a paused clip opens the pager). Touch keeps its taps.
+ const pp = h('button', { class: 'vid-pp', type: 'button', 'aria-label': t('videoPlay'), onClick: (e) => {
+ e.stopPropagation(); e.preventDefault();
+ const player = e.currentTarget.closest('.note-video-box')?.querySelector('video');
+ if (!player) return;
+ if (player.paused) { tappedClips.add(url); player.play().catch(() => {}); } else player.pause();
+ } }, h('span', { class: 'vid-pp-i', 'aria-hidden': 'true' }));
+ const ppState = () => {
+ const live = v.closest('.note-video-box');
+ const b = live && live.querySelector('.vid-pp');
+ if (!b) return;
+ b.classList.toggle('playing', !v.paused);
+ b.setAttribute('aria-label', t(v.paused ? 'videoPlay' : 'videoPause'));
+ };
+ v.addEventListener('play', ppState);
+ v.addEventListener('pause', ppState);
+ box.append(pp);
+
// remembered by clip, so a repaint draws the box as it now stands
const wake = () => {
wokeClips.add(url);
box.classList.remove('idle');
- v.controls = true;
+ nativeControls(v);
};
v.addEventListener('playing', wake);
const btn = loud ? null : soundBtn((button) => {
@@ -8202,14 +8296,19 @@ export function messagesFeature(ctx) {
const liveBox = button.closest('.note-video-box');
const player = liveBox?.querySelector('video');
if (!player) return;
+ if (player._ownBar && !player.muted) { player.muted = true; button.setSound(false); return; }
player.muted = false;
unmutedClips.add(url);
liveBox._skipMorph = true; // the box is the viewer's now: no repaint rebuilds it muted
if (player.paused) player.play().catch(() => {});
- button.remove(); // the player's own controls carry mute from here
+ // the player's own controls carry mute from here — unless they're off
+ // for the moments bar: then this button turns it down again
+ if (player._ownBar) button.setSound(true); else button.remove();
});
v.onvolumechange = () => {
- if (!v.muted) { unmutedClips.add(url); if (btn && btn.isConnected) btn.remove(); } // unmuted from the native control: same
+ const b = v.closest('.note-video-box')?.querySelector('.vid-sound');
+ if (v._ownBar && b && b.setSound) b.setSound(!v.muted);
+ if (!v.muted) { unmutedClips.add(url); if (btn && btn.isConnected && !v._ownBar) btn.remove(); } // unmuted from the native control: same
else unmutedClips.delete(url); // muted again from the control: the next box starts quiet
};
if (btn) box.append(btn);
@@ -9309,7 +9408,7 @@ export function messagesFeature(ctx) {
};
return h('div', { class: 'col live-page', style: 'gap:12px' },
ctx.brandHeader(!ui.pubProf && wallet.loaded),
- h('div', { class: 'card col', style: 'gap:10px' },
+ h('div', { class: 'card col live-main', style: 'gap:10px' },
h('div', { class: 'row gap6', style: 'align-items:center' },
mine ? h('button', { class: 'iconbtn chat-back', onClick: () => { if (confirm(t('goLiveEndAsk'))) endBroadcast(); } }, '‹')
: backBtn(() => { ui.liveStream = null; }),
@@ -9361,7 +9460,7 @@ export function messagesFeature(ctx) {
watchersRow(w),
liveSummary(ev) ? h('div', { class: 'small muted', style: 'white-space:pre-wrap;overflow-wrap:anywhere' }, liveSummary(ev).slice(0, 600)) : null,
ui.liveReport && ui.liveReport.a === s.a ? liveReportPanel(ev) : null),
- h('div', { class: 'card col', style: 'gap:8px' },
+ h('div', { class: 'card col live-chat-card', style: 'gap:8px' },
h('div', { class: 'small muted' }, t('liveChat')),
h('div', {
class: 'live-chat', 'data-key': 'live-chat:' + s.a,
@@ -11077,6 +11176,10 @@ export function messagesFeature(ctx) {
return null;
}
const hidden = (ev) => !!hiddenWhy(ev);
+ // A list row with nothing left to show: a post its author deleted, or a
+ // repost of one (a deletion that lands after the row did, too). Threads
+ // keep their deleted posts' places; lists just drop them.
+ const goneHere = (ev) => isDeleted(ev) || (ev.kind === REPOST && !!repostInner(ev) && isDeleted(repostInner(ev)));
const hiddenPk = (pk) => !!pk && !isMe(pk) && (isMuted(pk) || (baselineMutes() || { set: new Set() }).set.has(pk) || isSpammer(pk) || reportsNow().mine.has(pk));
const visiblePks = (pks) => [...(pks || [])].filter((pk) => !hiddenPk(pk));
@@ -11990,13 +12093,9 @@ export function messagesFeature(ctx) {
zapText(ev) ? h('div', {}, ...noteBody(zapText(ev))) : null)
: foreign
? h('div', { class: 'note-text small muted', style: 'white-space:pre-wrap;overflow-wrap:anywhere' }, (ev.kind === 64 ? '\u265f ' : '') + altText)
- : h('div', { class: 'note-text', style: 'white-space:pre-wrap;overflow-wrap:anywhere' }, ...(ev.kind === ARTICLE ? (open ? [articleCard(ev)] : articleBody(ev)) : noteBody(shownTranslation(ev)?.text ?? noteText(ev), 0, noteEmojiTags(ev)))),
- readMoment(ev) ? h('a', { class: 'small media-time-link', href: readMoment(ev).url + '#t=' + readMoment(ev).seconds, target: '_blank', rel: 'noopener noreferrer', onClick: e => {
- e.stopPropagation();
- const m = readMoment(ev);
- const player = [...document.querySelectorAll('audio, video')].find(v => mediaMoment(v.dataset.clip || v.getAttribute('src'), 0)?.url === m.url);
- if (player) { e.preventDefault(); const seek = () => { player.currentTime = Math.min(m.seconds, Number.isFinite(player.duration) ? player.duration : m.seconds); }; if (player.readyState) seek(); else player.addEventListener('loadedmetadata', seek, { once: true }); player.play().catch(() => {}); player.scrollIntoView({ block: 'center' }); }
- } }, '▶ ' + mediaClock(readMoment(ev).seconds)) : null,
+ : h('div', { class: 'note-text', style: 'white-space:pre-wrap;overflow-wrap:anywhere' },
+ momentLink(ev),
+ ...(ev.kind === ARTICLE ? (open ? [articleCard(ev)] : articleBody(ev)) : noteBody(momentStripped(ev, shownTranslation(ev)?.text ?? noteText(ev)), 0, noteEmojiTags(ev)))),
foreign || pending ? null : translateLine(ev),
ev.kind === POLL ? pollBox(ev) : null,
pending ? null : noteActions(pk, ev, { canZap }),
@@ -12447,7 +12546,9 @@ export function messagesFeature(ctx) {
onKeydown: (e) => {
mentionKey(e);
if (e.defaultPrevented) return;
- if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); e.target.closest('.col').querySelector('.thread-reply-send')?.click(); return; }
+ // a phone's Return is a new line (Reply is the button); a
+ // keyboard's Enter sends
+ if (e.key === 'Enter' && !e.shiftKey && !matchMedia('(pointer: coarse)').matches) { e.preventDefault(); e.target.closest('.col').querySelector('.thread-reply-send')?.click(); return; }
if (e.ctrlKey && (e.key === 'j' || e.key === 'J')) {
e.preventDefault();
const el = e.target;
@@ -12488,7 +12589,19 @@ export function messagesFeature(ctx) {
previewBtn(!!s.preview, () => { s.preview = !s.preview; render(); }),
h('button', {
class: 'btn-ghost btn-sm thread-reply-cancel', type: 'button',
- onClick: () => { s.replying = false; s.preview = false; s.mediaMoment = null; render(); },
+ // Cancel discards: the typed text, its attachments and the box.
+ // (It only folded the `replying` flag before, and the box stays
+ // up while a draft has text — so with anything typed it did
+ // nothing visible.) The field may still be focused, and the
+ // morph leaves a focused field's value alone: clear it by hand.
+ onClick: () => {
+ const text = s.draft || '';
+ s.draft = ''; s.replying = false; s.preview = false; s.mediaMoment = null;
+ ui.postMedia = (ui.postMedia || []).filter((m) => !text.includes(m.url));
+ const inp = document.querySelector('.thread-reply-input');
+ if (inp) inp.value = '';
+ render();
+ },
}, t('cancel'))),
h('button', {
class: 'btn-primary btn-sm thread-reply-send', disabled: !!s.sending || !!ui.postUploading,
@@ -12587,12 +12700,32 @@ export function messagesFeature(ctx) {
...noteOverlays());
}
- async function publishProfileFields(fields, opts = {}) {
+ // Every kind-0 publish merges over the newest copy on the relays, so two
+ // publishes in flight at once clobber each other: both read the same base,
+ // the later one lands without the earlier one's fields. That exact race
+ // put a migrated user's released placeholder name back into their lud16
+ // (the rename repointed it, the legacy-avatar import republished the old
+ // base nine seconds later). One at a time, and the base is never older
+ // than what this session last wrote.
+ let kind0Chain = Promise.resolve();
+ let kind0Last = null; // { at, content } — the newest kind 0 we published
+ const withKind0Lock = (fn) => { const p = kind0Chain.then(fn, fn); kind0Chain = p.catch(() => {}); return p; };
+ async function newestKind0(pk) {
+ const evs = await queryOn([...new Set([...PROFILE_RELAYS, ...DM_RELAYS])], { kinds: [0], authors: [pk] }, 3000);
+ let newest = evs.sort((a, b) => b.created_at - a.created_at)[0] || null;
+ if (kind0Last && kind0Last.pk === pk && (!newest || newest.created_at <= kind0Last.at)) newest = kind0Last;
+ let base = {};
+ try { base = newest ? JSON.parse(newest.content) : {}; } catch {}
+ return base;
+ }
+ // Strictly later than the last one we sent: relays keep the LOWEST id of
+ // two replaceable events with the same second, so a second publish in
+ // the same second as the first could lose to it.
+ const kind0Stamp = (pk) => { const now = Math.floor(Date.now() / 1000); return kind0Last && kind0Last.pk === pk ? Math.max(now, kind0Last.at + 1) : now; };
+ function publishProfileFields(fields, opts = {}) { return withKind0Lock(() => publishProfileFieldsNow(fields, opts)); }
+ async function publishProfileFieldsNow(fields, opts = {}) {
const id = await requireIdentity();
- const evs = await queryOn([...new Set([...PROFILE_RELAYS, ...DM_RELAYS])], { kinds: [0], authors: [id.pubkey] }, 3000);
- const newest = evs.sort((a, b) => b.created_at - a.created_at)[0];
- let base = {};
- try { base = newest ? JSON.parse(newest.content) : {}; } catch {}
+ const base = await newestKind0(id.pubkey);
if (opts.onlyWhen && !opts.onlyWhen(base)) return true; // condition says leave it be
const merged = { ...base };
// fillOnly fields are offers, not orders: the onboarding wizard suggests
@@ -12608,10 +12741,11 @@ export function messagesFeature(ctx) {
}
if (merged.name && !(fill.has('name') && taken('name'))) merged.display_name = merged.name;
if (JSON.stringify(merged) === JSON.stringify(base)) return true; // nothing to say
- const partial = { kind: 0, content: JSON.stringify(merged), tags: [], created_at: Math.floor(Date.now() / 1000) };
+ const partial = { kind: 0, content: JSON.stringify(merged), tags: [], created_at: kind0Stamp(id.pubkey) };
const evt = id.signer instanceof Uint8Array ? finalizeEvent(partial, id.signer) : await id.signer.signEvent(partial);
const ok = await publishOn([...new Set([...PROFILE_RELAYS, ...DM_RELAYS])], evt);
if (!ok) throw new Error(t('msgSendFailed'));
+ kind0Last = { pk: id.pubkey, at: evt.created_at, content: evt.content };
fullProfiles.set(id.pubkey, merged);
profiles.set(id.pubkey, { name: merged.name || null, picture: merged.picture || null, t: Date.now() });
return true;
@@ -12625,11 +12759,20 @@ export function messagesFeature(ctx) {
ui.profSaving = true;
render();
try {
+ await withKind0Lock(() => saveProfileNow(id, e));
+ ui.profEdit = null; ui.profEditFilled = false;
+ toast(t('profSaved'));
+ } catch (err) {
+ if (ui.profEdit === e && e.uname === err.migrationName) e.migrationName = err.migrationName;
+ toast(err.message || String(err));
+ } finally {
+ ui.profSaving = false;
+ render();
+ }
+ }
+ async function saveProfileNow(id, e) {
// merge over the newest published kind 0 so unknown fields round-trip
- const evs = await queryOn([...new Set([...PROFILE_RELAYS, ...DM_RELAYS])], { kinds: [0], authors: [id.pubkey] }, 3000);
- const newest = evs.sort((a, b) => b.created_at - a.created_at)[0];
- let base = {};
- try { base = newest ? JSON.parse(newest.content) : {}; } catch {}
+ const base = await newestKind0(id.pubkey);
// A changed username claims first — if the name is taken (or invalid)
// the save stops here and the editor stays open to fix it.
const oldAddr = hook('namesAddress');
@@ -12649,26 +12792,62 @@ export function messagesFeature(ctx) {
// when empty; move them when they pointed at our (old) address. A
// deliberately foreign lud16/nip05 is the user's business.
if (addr) {
- for (const k of ['lud16', 'nip05'])
- if (!merged[k] || merged[k] === oldAddr) merged[k] = addr;
+ const domain = addr.split('@')[1];
+ for (const k of ['lud16', 'nip05']) {
+ const cur = merged[k];
+ if (!cur || cur === oldAddr) { merged[k] = addr; continue; }
+ // a name at our own domain that is not ours and no longer answers
+ // (the placeholder a migration released) is ours now — Save is the
+ // heal an interactive signer can't do in the background
+ if (typeof cur === 'string' && cur !== addr && cur.split('@')[1] === domain && !/^_@/.test(cur) && await addressDead(cur)) merged[k] = addr;
+ }
}
if (merged.name) merged.display_name = merged.name;
- const partial = { kind: 0, content: JSON.stringify(merged), tags: [], created_at: Math.floor(Date.now() / 1000) };
+ const partial = { kind: 0, content: JSON.stringify(merged), tags: [], created_at: kind0Stamp(id.pubkey) };
const evt = id.signer instanceof Uint8Array ? finalizeEvent(partial, id.signer) : await id.signer.signEvent(partial);
const ok = await publishOn([...new Set([...PROFILE_RELAYS, ...DM_RELAYS])], evt);
if (!ok) throw new Error(t('msgSendFailed'));
+ kind0Last = { pk: id.pubkey, at: evt.created_at, content: evt.content };
fullProfiles.set(id.pubkey, merged);
profiles.set(id.pubkey, { name: merged.name || null, picture: merged.picture || null });
- ui.profEdit = null; ui.profEditFilled = false;
- toast(t('profSaved'));
- } catch (err) {
- if (ui.profEdit === e && e.uname === err.migrationName) e.migrationName = err.migrationName;
- toast(err.message || String(err));
- } finally {
- ui.profSaving = false;
- render();
+ }
+ // A payment-address rename released the old name: repoint the kind 0's
+ // lud16 and nip05 — but only where they pointed at the released address
+ // (or were empty). Deliberately different values are not ours to touch.
+ function repointAddress(oldAddr, newAddr) {
+ const follows = (k) => (base) => !base[k] || base[k] === oldAddr;
+ return publishProfileFields({ lud16: newAddr, nip05: newAddr }, {
+ onlyWhen: (base) => ['lud16', 'nip05'].some((k) => follows(k)(base) && base[k] !== newAddr),
+ fieldWhen: { lud16: follows('lud16'), nip05: follows('nip05') },
+ });
+ }
+ // Our kind 0 still names an address at our own domain that is not the one
+ // we hold — a placeholder name released by a migration whose repoint lost
+ // the race above. Repointed once the domain confirms the old name is dead;
+ // a same-domain name that still answers (a second account, say) is left
+ // alone. Once per address per session.
+ const addrHealed = new Set();
+ async function healStaleAddress(olds, myAddr) {
+ // Amber by intent needs a tap per signature: a background publish would
+ // sit in the kind-0 queue forever and block every later one. Save in the
+ // profile editor repoints the address for these users instead.
+ const id = await identity().catch(() => null);
+ if (!id || (id.signer && id.signer.interactive)) return;
+ for (const old of olds) {
+ if (addrHealed.has(old)) continue;
+ addrHealed.add(old);
+ try { if (await addressDead(old)) await repointAddress(old, myAddr); } catch {}
}
}
+ async function addressDead(addr) {
+ const [name, domain] = addr.split('@');
+ try {
+ const r = await fetch(`https://${domain}/.well-known/lnurlp/${encodeURIComponent(name)}`, { cache: 'no-store' });
+ if (!r.ok) return true;
+ const j = await r.json().catch(() => null);
+ return !j || j.status === 'ERROR' || !j.callback;
+ } catch { return false; } // unreachable is not dead
+ }
function profileScreen() {
const pk = ui.profilePk;
@@ -12808,9 +12987,17 @@ export function messagesFeature(ctx) {
// authoritative locally, a deep link carries the address in the URL
// (seeded as `addr`), and the light cache remembers it from last time.
const lp = profileOf(pk) || {};
- const rawNip05 = (full && full.nip05) || (mine && myAddr) || lp.nip05 || lp.addr || null;
+ // Our own page never shows a name at our domain that the registrar says
+ // is no longer ours (see healStaleAddress): the claimed address is the
+ // truth here, and the kind 0 is brought in line in the background.
+ const stale = (v) => mine && myAddr && typeof v === 'string' && v !== myAddr && v.split('@')[1] === myAddr.split('@')[1] && !/^_@/.test(v) ? v : null;
+ if (full) { const olds = [...new Set([stale(full.lud16), stale(full.nip05)].filter(Boolean))]; if (olds.length) healStaleAddress(olds, myAddr); }
+ const rawNip05 = (full && (stale(full.nip05) ? myAddr : full.nip05)) || (mine && myAddr) || lp.nip05 || lp.addr || null;
const nip05 = rawNip05 ? String(rawNip05).replace(/^_@/, '') : null;
- const lud16 = (full && full.lud16 ? String(full.lud16) : null) || lp.lud16 || null;
+ // the lightning line too: a stale same-domain lud16 (jar@ after the
+ // rename to jarryd@) showed under the right NIP-05 as a second address
+ const rawLud = (full && full.lud16 ? String(full.lud16) : null) || lp.lud16 || null;
+ const lud16 = rawLud ? (stale(rawLud) ? myAddr : rawLud) : null;
const showLud = lud16 && !/^npub1/i.test(lud16) && lud16 !== nip05;
// an about of "~" or a lone character is noise, not a bio.
// Until the full kind 0 lands, the light profile cache answers — it was
@@ -13054,7 +13241,8 @@ export function messagesFeature(ctx) {
// Streams joins the tabs once they've streamed
const streamed = pastOf(pk).length > 0;
const tab = profTab(pk) === 'streams' && !streamed ? 'posts' : profTab(pk);
- const shown = c.notes.filter((e) => (tab === 'replies') === replyish(e));
+ // a post its author deleted leaves the list (no "was deleted" row)
+ const shown = c.notes.filter((e) => (tab === 'replies') === replyish(e) && !goneHere(e));
// a tab that holds only a few of the pages fetched so far (someone
// who mostly replies, or mostly posts) asks for older ones by itself:
// too short to scroll means the scroll that loads more never comes
@@ -13087,7 +13275,7 @@ export function messagesFeature(ctx) {
return h('div', { class: 'col', style: 'gap:8px' },
tabs,
h('div', { class: 'card col notes-feed', style: 'gap:0', 'data-key': 'prof-notes:' + tab },
- ...(c.winList = () => c.notes.filter((e) => (profTab(pk) === 'replies') === replyish(e)), windowedRows(c, shown, (ev) => keyed(noteRow(pk, ev, name, { context: profTab(pk) === 'replies' }), ev.id)))),
+ ...(c.winList = () => c.notes.filter((e) => (profTab(pk) === 'replies') === replyish(e) && !goneHere(e)), windowedRows(c, shown, (ev) => keyed(noteRow(pk, ev, name, { context: profTab(pk) === 'replies' }), ev.id)))),
c.loadingMore
? h('div', { class: 'row gap6', style: 'justify-content:center;padding:4px 0' },
h('span', { class: 'spinner sm' }))
@@ -13498,7 +13686,9 @@ export function messagesFeature(ctx) {
const key = mediaIdxKey(feedId);
let r = mediaIdx.get(key);
if (r) return r;
- r = { key, replies: !!(feedDef(feedId) || {}).replies, images: new Map(), videos: new Map(), articles: new Map(), art: { until: 0, end: 0, empty: 0, head: 0 }, checked: new Set(), until: 0, end: false, empty: 0, loaded: false };
+ const order = () => ({ seq: new Map(), top: 0, bottom: 0, newest: 0 });
+ r = { key, replies: !!(feedDef(feedId) || {}).replies, images: new Map(), videos: new Map(), articles: new Map(), art: { until: 0, end: 0, empty: 0, head: 0 }, checked: new Set(), until: 0, end: false, empty: 0, loaded: false,
+ order: { images: order(), videos: order() } };
mediaIdx.set(key, r);
loadMediaIndex(key).then(async (rec) => {
if (rec) {
@@ -14037,7 +14227,27 @@ export function messagesFeature(ctx) {
out.push({ ev, url });
}
}
- return out;
+ return settledOrder(r, kind, out);
+ }
+ // The grid's order holds for the session (Adam, 2026-10-23: clips the
+ // crawl found landed in the middle of the grid, above an older tail the
+ // index had from before, and the tiles already there jumped): what it
+ // shows first is newest first, and whatever turns up after goes under what
+ // is already there, in its own date order. Only a post newer than the top
+ // tile goes above it. Nothing is settled until the kept index is in, so
+ // the first paint is one date order, not two batches.
+ function settledOrder(r, kind, out) {
+ if (!r.loaded) return out;
+ const o = r.order[kind];
+ const key = (it) => it.ev.id + '|' + it.url;
+ const fresh = out.filter((it) => !o.seq.has(key(it)));
+ if (fresh.length) {
+ const above = o.seq.size ? fresh.filter((it) => it.ev.created_at > o.newest) : [];
+ for (const it of above.reverse()) o.seq.set(key(it), --o.top);
+ for (const it of fresh) if (!o.seq.has(key(it))) o.seq.set(key(it), ++o.bottom);
+ for (const it of fresh) if (it.ev.created_at > o.newest) o.newest = it.ev.created_at;
+ }
+ return out.sort((a, b) => o.seq.get(key(a)) - o.seq.get(key(b)));
}
// The feed's pictures (or clips) in reading order — every one of a post
// before the next post's — for the pager opened from one in the feed: the
@@ -15868,7 +16078,7 @@ export function messagesFeature(ctx) {
// (a reply whose post every lookup came back without isn't shown: a
// "Couldn't find that note" over it told nobody anything — Adam, 2026-10-20)
const repliesHere = feedReplies(c);
- const shownHere = (ev) => !hidden(ev) && !(curatedFeed && notForPublic(ev)) && !(repliesHere && orphaned(ev));
+ const shownHere = (ev) => !hidden(ev) && !goneHere(ev) && !(curatedFeed && notForPublic(ev)) && !(repliesHere && orphaned(ev));
const visible = c.notes.filter(shownHere);
// Every child keyed by its post, hairlines included, so the morph
// reconciles the list by post: a new one at the top is inserted as its
@@ -18233,13 +18443,9 @@ export function messagesFeature(ctx) {
// A payment-address rename released the old name: repoint the kind 0's
// lud16 and nip05 — but only where they pointed at the released address
// (or were empty). Deliberately different values are not ours to touch.
- addressRenamed(oldAddr, newAddr) {
- const follows = (k) => (base) => !base[k] || base[k] === oldAddr;
- return publishProfileFields({ lud16: newAddr, nip05: newAddr }, {
- onlyWhen: (base) => ['lud16', 'nip05'].some((k) => follows(k)(base) && base[k] !== newAddr),
- fieldWhen: { lud16: follows('lud16'), nip05: follows('nip05') },
- }).catch(() => {});
- },
+ addressRenamed(oldAddr, newAddr) { return repointAddress(oldAddr, newAddr).catch(() => {}); },
+ // the profile editor's Save, without the editor (tests)
+ async saveProfileDraft(e) { const id = await identity(); return withKind0Lock(() => saveProfileNow(id, { name: '', about: '', picture: '', banner: '', ...e })); },
// opens the profile, unless the caller has a step to take first (the
// Accounts page switches to that identity before showing its profile)
profileChip(pk, size, onOpen) {
diff --git a/src/features/names.js b/src/features/names.js
index 45b0b36..d57bb19 100644
--- a/src/features/names.js
+++ b/src/features/names.js
@@ -455,29 +455,35 @@ export function namesFeature(ctx) {
// said as it's typed, not after a round trip (the registrar is the judge:
// a name claimed before the rule can still be retaken by its owner)
nameRuleHint(ui.nameClaim) ? h('div', { class: 'small', style: 'color:var(--red,#c0392b)' }, t('namesRule')) : null,
- h('button', { class: 'btn-primary btn-block', disabled: ui.busy, onClick: async () => {
- const name = (ui.nameClaim || '').toLowerCase().trim();
- if (!name) return;
- ui.busy = true; ui.nameClaimError = null; ui.nameClaimMigration = null; render();
- try {
- // Sign with the login identity when one can be (re)attached: the
- // registrar lets a migrated coinos user's own identity take their
- // name back, which the wallet key alone could never prove.
- const signer = await Promise.resolve(hook('nostrLoginResume')).catch(() => null);
- await claimRequestedName(name, signer ? { signer, manager: wallet.nostrPubkey() } : {});
- // the wizard's Spending step tells a name claimed here from one
- // the registrar handed back (an account set up before)
- if (ui.onb && ui.onb.step === 'spend') ui.onb.claimedHere = name;
- ui.nameClaim = '';
- ui.nameEditOpen = false;
- toast(t('namesClaimed', { name: `${name}@${DOMAIN()}` }));
- } catch (e) {
- ui.nameClaimError = e.message;
- if (ui.nameClaim === name) ui.nameClaimMigration = e.migrationName || null;
- }
- ui.busy = false; render();
- } }, ui.busy ? h('span', { class: 'spinner' }) : t('namesClaim')),
- ui.nameClaimMigration && ui.nameClaimMigration === ui.nameClaim && DOMAIN() === 'coinos.io'
+ h('button', { class: 'btn-primary btn-block', disabled: ui.busy, onClick: () => claimTyped(ui.nameClaim) }, ui.busy ? h('span', { class: 'spinner' }) : t('namesClaim')),
+ migrateLink());
+ }
+ async function claimTyped(typed) {
+ const name = (typed || '').toLowerCase().trim();
+ if (!name) return;
+ ui.busy = true; ui.nameClaimError = null; ui.nameClaimMigration = null; render();
+ try {
+ // Sign with the login identity when one can be (re)attached: the
+ // registrar lets a migrated coinos user's own identity take their
+ // name back, which the wallet key alone could never prove.
+ const signer = await Promise.resolve(hook('nostrLoginResume')).catch(() => null);
+ await claimRequestedName(name, signer ? { signer, manager: wallet.nostrPubkey() } : {});
+ // the wizard's Spending step tells a name claimed here from one
+ // the registrar handed back (an account set up before)
+ if (ui.onb && ui.onb.step === 'spend') ui.onb.claimedHere = name;
+ ui.nameClaim = '';
+ ui.nameEdit = null;
+ ui.nameEditOpen = false;
+ toast(t('namesClaimed', { name: `${name}@${DOMAIN()}` }));
+ } catch (e) {
+ ui.nameClaimError = e.message;
+ if ((ui.nameEdit ?? ui.nameClaim) === name) ui.nameClaimMigration = e.migrationName || null;
+ }
+ ui.busy = false; render();
+ }
+ // "I have a coinos account": a name the registrar holds for a legacy user
+ function migrateLink() {
+ return ui.nameClaimMigration && ui.nameClaimMigration === (ui.nameEdit ?? ui.nameClaim) && DOMAIN() === 'coinos.io'
? h('button', {
type: 'button', class: 'linklike small',
onClick: () => {
@@ -490,7 +496,48 @@ export function namesFeature(ctx) {
location.href = `https://coinos.io/migrate?to=${encodeURIComponent(addr)}&back=${encodeURIComponent(location.origin + '/')}`;
}
},
- }, t('onbHaveCoinos')) : null);
+ }, t('onbHaveCoinos')) : null;
+ }
+
+ // Settings: the address and changing it are one card — the name sits in
+ // its own field; typing a different one offers the change (and says the
+ // old address stops working), otherwise Copy and Release.
+ function addressCard(st) {
+ const domain = st.domain || DOMAIN();
+ const addr = `${st.name}@${domain}`;
+ const typed = ui.nameEdit ?? st.name;
+ const changed = !!typed && typed !== st.name;
+ return h('div', { class: 'card col', 'data-key': 'names' },
+ h('h3', {}, t('namesTitle')),
+ ui.nameClaimError ? h('div', { class: 'notice err' }, ui.nameClaimError) : null,
+ h('div', { class: 'row gap6 name-field' },
+ h('input', {
+ type: 'text', class: 'mono-input', placeholder: t('namesPlaceholder'), style: 'flex:1',
+ autocapitalize: 'none', autocomplete: 'off', spellcheck: 'false', 'aria-label': t('namesCustom'),
+ value: typed,
+ onInput: (e) => {
+ const was = changed;
+ ui.nameEdit = e.target.value.toLowerCase().trim();
+ ui.nameClaimError = null;
+ if (ui.nameClaimMigration) ui.nameClaimMigration = null;
+ if ((!!ui.nameEdit && ui.nameEdit !== st.name) !== was || nameRuleHint(ui.nameEdit)) render();
+ },
+ }),
+ h('span', { class: 'muted', style: 'align-self:center' }, '@' + domain)),
+ changed && nameRuleHint(typed) ? h('div', { class: 'small', style: 'color:var(--red,#c0392b)' }, t('namesRule')) : null,
+ changed
+ ? h('div', { class: 'col', style: 'gap:8px' },
+ h('p', { class: 'small muted', style: 'margin:0' }, t('namesCustomHow')),
+ h('div', { class: 'row gap6' },
+ h('button', { class: 'btn-ghost btn-sm', disabled: ui.busy, onClick: () => { ui.nameEdit = null; ui.nameClaimError = null; ui.nameClaimMigration = null; render(); } }, t('cancel')),
+ h('button', { class: 'btn-primary btn-sm grow', disabled: ui.busy, onClick: () => claimTyped(typed) },
+ ui.busy ? h('span', { class: 'spinner sm' }) : t('namesChangeTo', { addr: typed }))),
+ migrateLink())
+ : h('div', { class: 'row gap6' },
+ copyBtn(addr, t('namesCopy')),
+ h('button', { class: 'btn-ghost btn-sm', onClick: async () => {
+ await release(); toast(t('namesReleased')); render();
+ } }, t('namesRelease'))));
}
// Settings: one card per concern, all laid out (no collapsed sections —
@@ -519,14 +566,7 @@ export function namesFeature(ctx) {
h('div', { class: 'addr-box break', style: 'font-size:11px' },
`${st.name}.user._bitcoin-payment.yourdomain.com. CNAME ${st.name}.user._bitcoin-payment.${domain}.`)),
card('ownnode', t('namesOwnNode'), t('namesOwnNodeMenuHow'), ownNodeSection()),
- card('custom', t('namesCustom'), t('namesCustomHow'), claimForm(false)),
- card('names', t('namesTitle'), null,
- h('div', { class: 'addr-box break', style: 'font-size:14px' }, addr),
- h('div', { class: 'row gap6' },
- copyBtn(addr, t('namesCopy')),
- h('button', { class: 'btn-ghost btn-sm', onClick: async () => {
- await release(); toast(t('namesReleased')); render();
- } }, t('namesRelease')))),
+ addressCard(st),
].filter(Boolean);
}
// The terminal's cards live on the Point of sale settings page now — no
@@ -884,7 +924,7 @@ export function namesFeature(ctx) {
checked = false; lastError = null;
// The claim field is a draft for THIS account — a name typed before a
// logout used to greet the next account that opened on this device.
- ui.nameClaim = null; ui.nameClaimError = null; ui.nameClaimMigration = null; suggestedFor = null;
+ ui.nameClaim = null; ui.nameEdit = null; ui.nameClaimError = null; ui.nameClaimMigration = null; suggestedFor = null;
refresh();
},
// The pencil by the address opens this: choosing a name gets a page of
diff --git a/src/features/nostrlogin.js b/src/features/nostrlogin.js
index f7f9e16..f39f9c3 100644
--- a/src/features/nostrlogin.js
+++ b/src/features/nostrlogin.js
@@ -16,7 +16,7 @@ import { qrSvg } from '../qr.js';
import {
extensionSigner, bunkerSigner, keySigner, parseNostrSecret,
walletForSigner, publishWalletBackup, fetchWalletBackup, nostrConnect, nostrConnectPending, resumeBunker,
- amberAvailable, amberSigner, amberPending, amberDeliver, amberCancel, onAmberChange } from '../nostr-login.js';
+ amberAvailable, amberSigner, amberPending, amberDeliver, amberCancel, amberOpen, onAmberChange } from '../nostr-login.js';
// The nostr ostrich, in the brand's monochrome.
const OSTRICH = '<svg width="23" height="23" style="display:block" viewBox="0 0 2000 2000" fill="none" xmlns="http://www.w3.org/2000/svg"><defs><linearGradient id="ng" x1="0" y1="0" x2="1" y2="1"><stop offset="0%" stop-color="#B84FE8"/><stop offset="100%" stop-color="#6D28D9"/></linearGradient></defs><circle cx="1000" cy="1000" r="1000" fill="url(#ng)"/><g transform="translate(1000 1000) scale(0.82) translate(-1000 -1000)"><path d="M1574.29 770.408C1532.04 840.612 1445.92 888.367 1437.96 892.449C1421.84 901.02 1415.92 913.469 1416.94 932.041C1417.96 950.612 1413.47 1042.65 1357.35 1083.27C1328.57 1104.08 1212.45 1131.02 1159.18 1140C1131.84 1144.69 1125.51 1153.06 1110.41 1162.04C1090 1174.69 1017.55 1275.1 1005.31 1297.35C1006.94 1297.14 1233.67 1226.73 1243.88 1225.1C1270.82 1221.02 1291.22 1228.78 1304.49 1248.37C1317.14 1267.14 1329.59 1286.12 1342.04 1305.1C1346.53 1311.84 1350.82 1318.78 1355.1 1325.71L1359.59 1332.86C1361.22 1335.51 1363.47 1338.57 1364.49 1342.65C1365.31 1345.51 1367.14 1355.1 1361.63 1360.82C1356.53 1366.12 1347.76 1366.12 1343.06 1364.9C1338.57 1363.67 1331.84 1361.02 1326.33 1356.53L1318.78 1350.2C1312.86 1345.1 1301.63 1342.65 1292.86 1343.06C1282.65 1343.47 1269.18 1340.2 1262.65 1336.12C1250 1327.96 1246.73 1307.55 1246.73 1307.35C1245.1 1300.61 1240.2 1298.78 1235.71 1298.78C1227.55 1298.57 1221.22 1301.02 1214.69 1302.86C1184.9 1311.84 1155.31 1321.02 1125.51 1330.41L1082.86 1343.67C1061.84 1350.2 1040.82 1356.73 1020 1363.67C1014.29 1365.51 1008.78 1368.37 1002.86 1371.43C1000.41 1372.65 997.959 1373.88 995.51 1375.1C993.061 1376.33 990.408 1377.76 987.959 1379.18C982.449 1382.24 976.531 1385.51 970 1387.35C948.776 1393.67 930.204 1384.49 921.429 1363.27C915.714 1349.59 920.816 1322.45 923.878 1314.49C943.061 1264.69 1005.51 1170.82 1005.51 1170.2C1004.49 1169.8 936.327 1197.14 925.102 1205.71C894.286 1229.18 822.041 1284.69 821.02 1290C816.327 1314.69 801.02 1333.27 777.551 1342.45C760.612 1348.98 750.408 1362.45 740.408 1375.51C740.408 1375.51 559.388 1624.9 547.143 1638.37C543.469 1642.45 509.592 1677.96 500.612 1694.49C498.571 1698.57 490.816 1714.9 488.776 1718.98C487.143 1722.24 483.469 1731.02 469.592 1730.41C455.714 1729.8 455.306 1710.41 454.694 1702.04C453.265 1681.43 457.755 1661.22 468.571 1640C469.592 1637.96 481.837 1619.39 477.347 1604.49C473.265 1591.43 469.388 1571.22 475.51 1561.02C485.102 1544.9 502.041 1544.29 524.694 1540.61C540.408 1537.96 551.837 1530.2 562.857 1514.08C586.122 1480.2 673.674 1355.92 693.469 1327.14C698.776 1319.59 702.857 1309.8 704.694 1300.2C710.408 1271.22 727.959 1251.02 758.571 1238.57C765.102 1235.92 886.939 1134.08 886.939 1121.02C886.939 1111.63 873.674 1106.53 863.469 1103.67C862.041 1103.27 785.51 1083.47 750.612 1067.55C731.633 1058.98 717.347 1051.43 700.408 1039.18C677.347 1022.24 631.225 1030.41 624.49 1031.43C591.837 1036.12 567.551 1050.82 540 1069.39C535.102 1072.86 510 1081.84 497.347 1074.69C472.653 1060.61 418.367 1035.31 398.367 1004.9C389.184 990.816 390.408 967.959 396.939 942.653C417.959 883.878 448.98 857.551 506.327 841.633C547.143 827.551 629.388 824.49 668.98 821.429C671.633 820.612 759.388 818.571 821.02 786.939C862.041 765.918 983.878 684.898 1159.18 690.408C1230 692.653 1363.88 761.837 1415.51 763.878C1468.16 766.122 1494.49 760.204 1524.9 728.776C1533.47 719.796 1570 641.02 1535.51 597.959C1522.65 582.041 1509.39 567.755 1494.08 554.694C1473.47 537.143 1452.04 520.408 1433.47 500.612C1392.45 457.143 1379.8 397.755 1399.18 351.429C1411.63 318.98 1437.76 304.898 1475.51 312.245C1502.04 317.347 1521.43 341.225 1540.41 353.878C1551.02 361.02 1568.78 365.102 1580.41 367.959C1595.1 371.429 1606.12 382.653 1605.51 390.204C1604.9 397.755 1585.51 404.286 1566.94 402.857C1544.9 401.429 1507.14 401.225 1484.49 408.776C1469.39 414.286 1462.65 431.02 1467.14 447.551C1470.82 461.02 1499.59 485.102 1510.41 494.082C1532.04 511.837 1555.1 527.959 1573.06 550.204C1593.27 575.51 1603.88 604.286 1607.14 636.122C1612.04 684.898 1599.18 728.776 1574.29 770.408Z" fill="#fff"/></g></svg>';
@@ -408,7 +408,13 @@ export function nostrLoginFeature(ctx) {
if (!p) return null;
const e = ui.amberPaste || (ui.amberPaste = { text: '' });
return h('div', { class: 'card col amber-wait', style: 'gap:8px' },
- h('div', { class: 'row gap6', style: 'align-items:center' }, h('span', { class: 'spinner sm' }), h('span', { class: 'small' }, t('nlAmberWait'))),
+ // a request waiting for a tap (see amberOpen): the Open button is the
+ // way forward, not the spinner
+ p.needsTap
+ ? h('div', { class: 'col', style: 'gap:6px' },
+ h('div', { class: 'small' }, t('nlAmberTap')),
+ h('button', { class: 'btn-primary btn-block amber-open', type: 'button', onClick: () => amberOpen() }, t('nlAmberOpen')))
+ : h('div', { class: 'row gap6', style: 'align-items:center' }, h('span', { class: 'spinner sm' }), h('span', { class: 'small' }, t('nlAmberWait'))),
h('div', { class: 'small muted' }, t('nlAmberPasteHint')),
h('div', { class: 'row gap6' },
h('input', { type: 'text', class: 'grow amber-paste', placeholder: t('nlAmberPastePh'), value: e.text, autocapitalize: 'none', autocomplete: 'off', spellcheck: 'false',
diff --git a/src/features/nwc.js b/src/features/nwc.js
index 9c71a7f..a2730f5 100644
--- a/src/features/nwc.js
+++ b/src/features/nwc.js
@@ -30,7 +30,7 @@ import { t } from '../i18n.js';
import { dlog } from '../debug.js';
import { qrSvg } from '../qr.js';
import { getNetwork } from '../api.js';
-import { loadBg, saveBg, clearBg } from '../nwc-bg.js';
+import { loadBg, saveBg, clearBg, readBgLog } from '../nwc-bg.js';
import { encodeNoffer } from '../noffer.js';
import { maybeBolt11 } from '../ark/lightning.js';
import { withRequestLock } from '../nwc-lock.js';
@@ -56,7 +56,7 @@ const nowSec = () => Math.floor(Date.now() / 1000);
const errRes = (code, message) => ({ error: { code, message } });
export function nwcFeature(ctx) {
- const { h, ui, render, wallet, hook, fmtAmount, unitLabel, copyBtn, toast } = ctx;
+ const { h, ui, render, wallet, hook, fmtAmount, unitLabel, copyBtn, copy, toast } = ctx;
// Relay transport, injectable so the protocol can be driven in tests
// without a live relay.
const {
@@ -478,11 +478,21 @@ export function nwcFeature(ctx) {
try {
res = await hook('arkPayInvoice', invoice, { maxAmountSat: c.maxSat });
} catch (e) {
- // The ASP already holds a payment for this invoice: another device
- // of this wallet took the same request first. Its outcome is ours —
- // wait for it rather than report a failure over a zap that is
- // paying. The payer records the spend; this side only relays.
- if (!/already in progress/i.test(e.message || '')) throw e;
+ // A payment for this invoice already exists: ours, begun on an
+ // earlier request (the worker started it while closed, say), or
+ // another device's — the ASP refuses a second HTLC for one invoice.
+ // Its outcome is the answer, never an error whose text says "paid":
+ // a client once read "already paid or is being paid" as paid, hours
+ // before the money moved. The payer records the spend; this side
+ // only relays.
+ if (!/already in progress|already paid/i.test(e.message || '')) throw e;
+ const mine = await hook('arkLnLookup', { paymentHash: dec.paymentHash }).catch(() => null);
+ if (mine && mine.type === 'outgoing' && mine.state === 'settled' && mine.preimage) {
+ return { sibling: true, result: { preimage: mine.preimage, fees_paid: 0 } };
+ }
+ if (mine && mine.type === 'outgoing' && mine.state === 'pending') {
+ return errRes('OTHER', 'a payment for this invoice is still in progress; ask again in a moment');
+ }
const out = await hook('arkLnOutcome', dec.paymentHash, 60000);
if (!out || out.status !== 'success') throw e;
return { sibling: true, result: { preimage: out.preimage, fees_paid: 0 } };
@@ -1093,7 +1103,19 @@ export function nwcFeature(ctx) {
h('button', { class: 'btn-sm', onClick: () => {
const s = load(); s.paySentNotify = !on; save(s); writeBg(); render();
} }, on ? t('nwcOn') : t('nwcOff'))),
- h('div', { class: 'small faint' }, t('notifPaySentHint')))];
+ h('div', { class: 'small faint' }, t('notifPaySentHint'))),
+ // the worker's diary, for the report that says where a closed wallet
+ // got to (a phone stops it without a trace)
+ h('div', { class: 'card col', style: 'gap:10px' },
+ h('div', { class: 'row between' },
+ h('span', { class: 'small' }, t('nwcWorkerLog')),
+ h('button', { class: 'btn-sm', onClick: async () => {
+ const lines = await readBgLog();
+ if (!lines.length) { toast(t('nwcWorkerLogEmpty')); return; }
+ await copy(lines.join('\n'));
+ toast(t('copied'));
+ } }, t('copy'))),
+ h('div', { class: 'small faint' }, t('nwcWorkerLogHint')))];
},
};
}
diff --git a/src/i18n.js b/src/i18n.js
index 78ba336..a01999a 100644
--- a/src/i18n.js
+++ b/src/i18n.js
@@ -282,6 +282,8 @@ const STR = {
clipsAll: 'All shapes',
clipsToggleTitle: 'Which clips to show: the ones that fit the screen, or all',
videoTapToPlay: "Tap to play",
+ videoPlay: "Play",
+ videoPause: "Pause",
pagerFetchingVideo: "Fetching the next video…",
pagerFetchingPictures: "Fetching more pictures…",
pagerCaughtUp: "That’s everything for now",
@@ -1057,6 +1059,7 @@ const STR = {
giftWelcome: 'You’ve been sent Bitcoin',
giftBackedUp: 'I’ve written it down',
giftLink: 'Gift some Bitcoin',
+ giftNotePlaceholder: 'Add a note (optional)',
giftLinkDesc: 'Presign an amount as a link. Whoever opens it claims the Bitcoin into a brand-new wallet that only they control.',
giftLinkWarn: '⚠ Anyone who opens this link can claim the amount, so share it only with the person you are gifting. Keep amounts small.',
giftLinkReveal: 'Create gift link',
@@ -1120,6 +1123,7 @@ const STR = {
claimOr: 'or',
goToWallet: 'Go to wallet',
claimBtn: 'Claim it',
+ claimNowBtn: 'Claim it now',
claimFeeNote: '~{n} fee',
claimFailed: 'This gift has already been claimed or is no longer available.',
claimNotVisibleBody: 'The coins funding this gift aren\u2019t visible from this wallet\u2019s network/data source. Make sure this wallet uses the same network and data source as the sender, then try again.',
@@ -1386,6 +1390,8 @@ const STR = {
onbSpendBody: 'Claim a username and get your own payment address. People can send you bitcoin instantly, with just your name.',
onbNameWait: 'Getting things ready…',
onbNotNow: 'Not now',
+ onbGiftNameTitle: 'Now pick a username',
+ onbGiftNameBody: 'Claim a name and get your own payment address, so people can send you bitcoin with just your name. Then choose a picture and a cover.',
onbAvatarTitle: 'Choose your look',
onbAvatarBody: 'Pick a cover and an avatar, or upload your own. You can change them anytime.',
onbCover: 'Cover image',
@@ -1411,6 +1417,8 @@ const STR = {
nlExtension: 'Use browser extension',
nlAmber: 'Sign in with Amber (Android)',
nlAmberWait: 'Waiting for your signer app… approve there, then come back here.',
+ nlAmberTap: 'Your signer app has another request to answer. Open it to continue.',
+ nlAmberOpen: 'Open signer app',
nlAmberPasteHint: 'The answer is read from the clipboard when you return. If nothing happens, paste it here:',
nlAmberPastePh: 'Paste the signer’s answer',
nlAmberPasteBtn: 'Use it',
@@ -1472,6 +1480,7 @@ const STR = {
namesClaim: 'Claim',
namesClaimed: 'You are now {name}',
namesCopy: 'Copy address',
+ namesChangeTo: 'Change to {addr}',
namesMoreOpen: 'More options',
namesMoreTitle: 'More ways to get paid',
namesMoreBolt11: 'Lightning invoice (BOLT 11)',
@@ -1595,6 +1604,9 @@ const STR = {
notifChatHint: 'Community chat is opt-in per room. Turn it on from a room’s menu.',
notifPaySent: 'Payments sent by connected apps',
notifPaySentHint: 'A heads-up when a connected app (a nostr client zapping, for example) spends from this wallet while it’s closed.',
+ nwcWorkerLog: 'Background activity log',
+ nwcWorkerLogHint: 'What the wallet did while it was closed: wake-ups, payments, notifications. Copy it when reporting a problem.',
+ nwcWorkerLogEmpty: 'Nothing recorded yet',
nwcNotifHint: 'You’ll be asked to allow notifications. The connection uses them to answer when Coinos is closed.',
nwcNotifNeeded: 'Without notifications the connection couldn’t answer when Coinos is closed, so it wasn’t added. Allow notifications and try again.',
nwcNotifBlocked: 'Notifications are blocked for this site. Allow them in your browser settings, then add the connection again.',
diff --git a/src/locales/ar.json b/src/locales/ar.json
index f112568..7d11408 100644
--- a/src/locales/ar.json
+++ b/src/locales/ar.json
@@ -364,6 +364,7 @@
"giftWelcome": "لقد أُرسلت إليك عملة Bitcoin",
"giftBackedUp": "لقد دوّنتها",
"giftLink": "أهدِ بعض عملات Bitcoin",
+ "giftNotePlaceholder": "أضف ملاحظة (اختياري)",
"giftLinkDesc": "وقّع مبلغاً مسبقاً كرابط. من يفتحه يطالب بعملات Bitcoin في محفظة جديدة تماماً يتحكم بها وحده.",
"giftLinkWarn": "⚠ أي شخص يفتح هذا الرابط يمكنه المطالبة بالمبلغ، لذا شاركه فقط مع الشخص الذي تهديه إياه. أبقِ المبالغ صغيرة.",
"giftLinkReveal": "إنشاء رابط الإهداء",
@@ -425,6 +426,7 @@
"claimOr": "أو",
"goToWallet": "اذهب إلى المحفظة",
"claimBtn": "طالب بها",
+ "claimNowBtn": "استلمها الآن",
"claimFeeNote": "♪{n} الرسوم",
"claimFailed": "تمت المطالبة بهذه الهدية بالفعل أو لم تعد متاحة.",
"claimNotVisibleBody": "والعملات التي تمول هذه الهدية غير مرئية من مصدر هذه المحفظة/البيانات. تأكد من استخدام هذه المحفظة نفس الشبكة ومصدر البيانات كمرسل، ثم محاولة مرة أخرى.",
@@ -618,6 +620,8 @@
"onbSpendBody": "اطالب بلقب مستخدم والحصول على عنوان الدفع الخاص بك - الناس يمكن أن ترسل لك قليلا على الفور، مع مجرد اسمك.",
"onbNameWait": "جهز الأشياء",
"onbNotNow": "ليس الآن",
+ "onbGiftNameTitle": "الآن اختر اسم مستخدم",
+ "onbGiftNameBody": "احجز اسمًا واحصل على عنوان دفع خاص بك، ليتمكن الناس من إرسال البيتكوين إليك باسمك فقط. ثم اختر صورة وغلافًا.",
"onbAvatarTitle": "اختر مظهرك",
"onbAvatarBody": "اختر صورة رمزية أو ارفع صورتك. يمكنك تغييرها في أي وقت",
"onbUpload": "تحميل الصورة",
@@ -678,6 +682,7 @@
"namesClaim": "المطالبة",
"namesClaimed": "أنت الآن {name}",
"namesCopy": "عنوان الرسالة",
+ "namesChangeTo": "غيّره إلى {addr}",
"namesMoreOpen": "المزيد من الخيارات",
"namesMoreTitle": "المزيد من الطرق للحصول على أجر",
"namesMoreBolt11": "فاتورة البرق (BOLT 11)",
@@ -910,6 +915,8 @@
"mediaNoImages": "لا صور في هذه الخلاصة بعد.",
"mediaNoVideos": "لا فيديوهات عمودية في هذه الخلاصة بعد.",
"videoTapToPlay": "انقر للتشغيل",
+ "videoPlay": "تشغيل",
+ "videoPause": "إيقاف مؤقت",
"videoLargeTitle": "الفيديوهات",
"videoLargeToggle": "تشغيل الفيديوهات الكبيرة تلقائيًا",
"videoLargeHelp": "الفيديوهات التي تزيد على {mb} ميغابايت أو تتجاوز 1080p تنتظر نقرة، حتى لا تستهلك الخلاصة بياناتك. الحد أقل على الاتصال البطيء أو عند توفير البيانات.",
diff --git a/src/locales/bn.json b/src/locales/bn.json
index 85ce58a..27cac0b 100644
--- a/src/locales/bn.json
+++ b/src/locales/bn.json
@@ -364,6 +364,7 @@
"giftWelcome": "আপনাকে Bitcoin পাঠানো হয়েছে",
"giftBackedUp": "আমি এটি লিখে রেখেছি",
"giftLink": "কিছু Bitcoin উপহার দিন",
+ "giftNotePlaceholder": "একটি নোট যোগ করুন (ঐচ্ছিক)",
"giftLinkDesc": "একটি পরিমাণ লিঙ্ক হিসেবে আগে থেকে সই করুন। যে এটি খুলবে সে Bitcoin-টি একটি একদম নতুন ওয়ালেটে দাবি করে, যা কেবল সে-ই নিয়ন্ত্রণ করে।",
"giftLinkWarn": "⚠ যে কেউ এই লিঙ্ক খুললে পরিমাণটি দাবি করতে পারে, তাই কেবল যাকে উপহার দিচ্ছেন তার সাথেই এটি শেয়ার করুন। পরিমাণ কম রাখুন।",
"giftLinkReveal": "লিংক নির্মাণ করুন",
@@ -425,6 +426,7 @@
"claimOr": "অথবা",
"goToWallet": "ওয়ালেট যাও",
"claimBtn": "দাবি করুন",
+ "claimNowBtn": "এখনই নিন",
"claimFeeNote": "একটিও নয়{n} কাগজ",
"claimFailed": "এই উপহারটি আগেই দাবি করা হয়েছে অথবা আর পাওয়া যাচ্ছে না।",
"claimNotVisibleBody": "এই দানের অর্থ এই ওয়ালেটের নেটওয়ার্ক/ডাটা উৎস থেকে দেখা যাচ্ছে না। নিশ্চিত করুন যে এই ওয়ালেট একই নেটওয়ার্ক এবং ডাটা উৎস ব্যবহার করে, অতঃপর পুনরায় চেষ্টা করুন ।",
@@ -618,6 +620,8 @@
"onbSpendBody": "আপনার নাম শুধু আপনার নামের সঙ্গে সঙ্গে সঙ্গে সঙ্গে আপনি আপনার পেকেন পাঠাতে পারেন ।",
"onbNameWait": "জিনিস প্রস্তুত করা হচ্ছে...",
"onbNotNow": "এই মুহূর্তে নয়",
+ "onbGiftNameTitle": "এবার একটি ইউজারনেম বেছে নিন",
+ "onbGiftNameBody": "একটি নাম নিন এবং নিজের পেমেন্ট ঠিকানা পান, যাতে লোকে শুধু আপনার নাম দিয়েই আপনাকে বিটকয়েন পাঠাতে পারে। তারপর একটি ছবি আর একটি কভার বেছে নিন।",
"onbAvatarTitle": "আপনার চেহারা পছন্দ করুন",
"onbAvatarBody": "একটি অবতার বেছে নাও অথবা নিজের ছবি আপলোড করো। যেকোনো সময় এটি বদলাতে পারো।",
"onbUpload": "একটি ছবি আপলোড করুন",
@@ -678,6 +682,7 @@
"namesClaim": "মুছে ফেলুন (_D)",
"namesClaimed": "তুমি এখন {name}",
"namesCopy": "ঠিকানা কপি করো",
+ "namesChangeTo": "{addr}-এ বদলান",
"namesMoreOpen": "অতিরিক্ত বিকল্প",
"namesMoreTitle": "আরো টাকা পেতে",
"namesMoreBolt11": "(বিওএল ১১)",
@@ -910,6 +915,8 @@
"mediaNoImages": "এই ফিডে এখনও কোনো ছবি নেই।",
"mediaNoVideos": "এই ফিডে এখনও কোনো খাড়া ভিডিও নেই।",
"videoTapToPlay": "চালাতে ট্যাপ করুন",
+ "videoPlay": "চালান",
+ "videoPause": "বিরতি",
"videoLargeTitle": "ভিডিও",
"videoLargeToggle": "বড় ভিডিও নিজে থেকে চালান",
"videoLargeHelp": "{mb} MB-এর বেশি বা 1080p-এর ওপরের ভিডিও ট্যাপের অপেক্ষায় থাকে, যাতে ফিড আপনার ডেটা না খায়। ধীর বা ডেটা-সেভার সংযোগে সীমা কম।",
diff --git a/src/locales/de.json b/src/locales/de.json
index 0210332..3a18040 100644
--- a/src/locales/de.json
+++ b/src/locales/de.json
@@ -364,6 +364,7 @@
"giftWelcome": "Dir wurde Bitcoin gesendet",
"giftBackedUp": "Ich habe sie aufgeschrieben",
"giftLink": "Bitcoin verschenken",
+ "giftNotePlaceholder": "Notiz hinzufügen (optional)",
"giftLinkDesc": "Signiere einen Betrag im Voraus als Link. Wer ihn öffnet, beansprucht das Bitcoin in einer brandneuen Wallet, die nur er selbst kontrolliert.",
"giftLinkWarn": "⚠ Wer diesen Link öffnet, kann den Betrag beanspruchen. Teile ihn daher nur mit der Person, die du beschenkst. Halte die Beträge klein.",
"giftLinkReveal": "Geschenk-Link erstellen",
@@ -425,6 +426,7 @@
"claimOr": "oder",
"goToWallet": "Zur Brieftasche gehen",
"claimBtn": "Beanspruchen",
+ "claimNowBtn": "Jetzt einlösen",
"claimFeeNote": "~{n} Gebühr",
"claimFailed": "Dieses Geschenk wurde bereits beansprucht oder ist nicht mehr verfügbar.",
"claimNotVisibleBody": "Die Münzen finanzieren dieses Geschenk sind nicht sichtbar aus dieser Brieftasche Netzwerk / Datenquelle. Stellen Sie sicher, dass diese Brieftasche die gleiche Netzwerk- und Datenquelle wie der Absender verwendet, dann versuchen Sie es erneut.",
@@ -618,6 +620,8 @@
"onbSpendBody": "Fordern Sie einen Benutzernamen an und erhalten Sie Ihre eigene Zahlungsadresse Die Leute können Ihnen Bitcoin sofort mit Ihrem Namen senden.",
"onbNameWait": "Bereitmachen...",
"onbNotNow": "Nicht jetzt",
+ "onbGiftNameTitle": "Wähle jetzt einen Benutzernamen",
+ "onbGiftNameBody": "Sichere dir einen Namen und deine eigene Zahlungsadresse, damit man dir Bitcoin einfach an deinen Namen senden kann. Danach wählst du ein Bild und ein Titelbild.",
"onbAvatarTitle": "Wählen Sie Ihren Look",
"onbAvatarBody": "Wählen Sie einen Avatar oder laden Sie Ihr eigenes Bild hoch. Sie können ihn jederzeit ändern.",
"onbUpload": "Foto hochladen",
@@ -678,6 +682,7 @@
"namesClaim": "Anspruch",
"namesClaimed": "Du bist jetzt {name}",
"namesCopy": "Adresse kopieren",
+ "namesChangeTo": "Ändern zu {addr}",
"namesMoreOpen": "Weitere Optionen",
"namesMoreTitle": "Mehr Möglichkeiten, um bezahlt zu werden",
"namesMoreBolt11": "Blitzrechnung (BOLT 11)",
@@ -910,6 +915,8 @@
"mediaNoImages": "Noch keine Bilder in diesem Feed.",
"mediaNoVideos": "Noch keine Hochkant-Videos in diesem Feed.",
"videoTapToPlay": "Zum Abspielen tippen",
+ "videoPlay": "Abspielen",
+ "videoPause": "Pause",
"videoLargeTitle": "Videos",
"videoLargeToggle": "Große Videos automatisch abspielen",
"videoLargeHelp": "Videos über {mb} MB oder über 1080p warten auf einen Tipp, damit der Feed nicht dein Datenvolumen frisst. Bei langsamer Verbindung oder Datensparmodus ist die Grenze niedriger.",
diff --git a/src/locales/es.json b/src/locales/es.json
index 9637b0a..40176a7 100644
--- a/src/locales/es.json
+++ b/src/locales/es.json
@@ -364,6 +364,7 @@
"giftWelcome": "Te han enviado Bitcoin",
"giftBackedUp": "Ya la anoté",
"giftLink": "Regala algo de Bitcoin",
+ "giftNotePlaceholder": "Añade una nota (opcional)",
"giftLinkDesc": "Prefirma un importe como enlace. Quien lo abra reclama el Bitcoin en una billetera totalmente nueva que solo esa persona controla.",
"giftLinkWarn": "⚠ Cualquiera que abra este enlace puede reclamar el importe, así que compártelo solo con la persona a quien se lo regalas. Mantén los importes pequeños.",
"giftLinkReveal": "Crear enlace de regalo",
@@ -425,6 +426,7 @@
"claimOr": "o",
"goToWallet": "Ve a la cartera.",
"claimBtn": "Reclamarlo",
+ "claimNowBtn": "Reclámalo ahora",
"claimFeeNote": "~{n} tarifa",
"claimFailed": "Este regalo ya ha sido reclamado o ya no está disponible.",
"claimNotVisibleBody": "Las monedas que financian este regalo no son visibles desde la fuente de red/datos de esta cartera. Asegúrese de que esta cartera utiliza la misma red y fuente de datos que el remitente, a continuación, inténtelo de nuevo.",
@@ -618,6 +620,8 @@
"onbSpendBody": "Reclame un nombre de usuario y obtenga su propia dirección de pago, la gente puede enviarle bitcoin al instante, con sólo su nombre.",
"onbNameWait": "Preparando las cosas...",
"onbNotNow": "Ahora no.",
+ "onbGiftNameTitle": "Ahora elige un nombre de usuario",
+ "onbGiftNameBody": "Reclama un nombre y obtén tu propia dirección de pago, para que te puedan enviar bitcoin solo con tu nombre. Después elige una foto y una portada.",
"onbAvatarTitle": "Elige tu look",
"onbAvatarBody": "Escoge un avatar o sube tu propia imagen. Puedes cambiarlo en cualquier momento.",
"onbUpload": "Sube una foto",
@@ -678,6 +682,7 @@
"namesClaim": "Reclamación",
"namesClaimed": "Ahora sí. {name}",
"namesCopy": "Dirección de copia",
+ "namesChangeTo": "Cambiar a {addr}",
"namesMoreOpen": "Más opciones",
"namesMoreTitle": "Más formas de pagar",
"namesMoreBolt11": "Factura de relámpago (BOLT 11)",
@@ -910,6 +915,8 @@
"mediaNoImages": "Aún no hay imágenes en este feed.",
"mediaNoVideos": "Aún no hay vídeos verticales en este feed.",
"videoTapToPlay": "Toca para reproducir",
+ "videoPlay": "Reproducir",
+ "videoPause": "Pausa",
"videoLargeTitle": "Vídeos",
"videoLargeToggle": "Reproducir vídeos grandes automáticamente",
"videoLargeHelp": "Los vídeos de más de {mb} MB o por encima de 1080p esperan a que los toques, para que el feed no se coma tus datos. El límite es menor con una conexión lenta o en ahorro de datos.",
diff --git a/src/locales/fr.json b/src/locales/fr.json
index 280be04..407794b 100644
--- a/src/locales/fr.json
+++ b/src/locales/fr.json
@@ -364,6 +364,7 @@
"giftWelcome": "Vous avez reçu des Bitcoin",
"giftBackedUp": "Je l’ai notée",
"giftLink": "Offrir des Bitcoin",
+ "giftNotePlaceholder": "Ajouter un mot (facultatif)",
"giftLinkDesc": "Présignez un montant sous forme de lien. Celui qui l’ouvre récupère les Bitcoin dans un tout nouveau portefeuille qu’il est seul à contrôler.",
"giftLinkWarn": "⚠ Quiconque ouvre ce lien peut récupérer le montant, alors ne le partagez qu’avec la personne à qui vous l’offrez. Gardez les montants faibles.",
"giftLinkReveal": "Créer le lien cadeau",
@@ -425,6 +426,7 @@
"claimOr": "ou",
"goToWallet": "Allez dans le portefeuille",
"claimBtn": "Récupérer",
+ "claimNowBtn": "Récupérer maintenant",
"claimFeeNote": "~{n} Taxe",
"claimFailed": "Ce cadeau a déjà été réclamé ou n’est plus disponible.",
"claimNotVisibleBody": "Les pièces de monnaie qui financent ce cadeau ne sont pas visibles à partir de ce portefeuille. Assurez-vous que ce portefeuille utilise le même réseau et la même source de données que l'expéditeur, puis essayez à nouveau.",
@@ -618,6 +620,8 @@
"onbSpendBody": "Réclamez un nom d'utilisateur et obtenez votre propre adresse de paiement, les gens peuvent vous envoyer Bitcoin instantanément, avec juste votre nom.",
"onbNameWait": "Préparer les choses...",
"onbNotNow": "Pas maintenant.",
+ "onbGiftNameTitle": "Choisissez maintenant un nom d'utilisateur",
+ "onbGiftNameBody": "Réservez un nom et obtenez votre propre adresse de paiement, pour qu'on puisse vous envoyer des bitcoins avec votre seul nom. Choisissez ensuite une photo et une couverture.",
"onbAvatarTitle": "Choisissez votre look",
"onbAvatarBody": "Choisissez un avatar ou téléchargez votre propre photo. Vous pouvez le changer à tout moment.",
"onbUpload": "Télécharger une photo",
@@ -678,6 +682,7 @@
"namesClaim": "Réclamation",
"namesClaimed": "Vous êtes maintenant {name}",
"namesCopy": "Copier l'adresse",
+ "namesChangeTo": "Passer à {addr}",
"namesMoreOpen": "Autres options",
"namesMoreTitle": "Plus de moyens de se faire payer",
"namesMoreBolt11": "Facture de foudre (BOLT 11)",
@@ -910,6 +915,8 @@
"mediaNoImages": "Pas encore d’images dans ce fil.",
"mediaNoVideos": "Pas encore de vidéos verticales dans ce fil.",
"videoTapToPlay": "Touchez pour lire",
+ "videoPlay": "Lire",
+ "videoPause": "Pause",
"videoLargeTitle": "Vidéos",
"videoLargeToggle": "Lire automatiquement les grosses vidéos",
"videoLargeHelp": "Les vidéos de plus de {mb} Mo ou au-delà de 1080p attendent un toucher, pour que le fil ne dévore pas vos données. La limite est plus basse sur une connexion lente ou en économie de données.",
diff --git a/src/locales/hi.json b/src/locales/hi.json
index 8057344..41eb792 100644
--- a/src/locales/hi.json
+++ b/src/locales/hi.json
@@ -364,6 +364,7 @@
"giftWelcome": "आपको Bitcoin भेजा गया है",
"giftBackedUp": "मैंने इसे लिख लिया है",
"giftLink": "कुछ Bitcoin उपहार में दें",
+ "giftNotePlaceholder": "एक नोट जोड़ें (वैकल्पिक)",
"giftLinkDesc": "एक राशि को लिंक के रूप में पहले से साइन करें। जो भी इसे खोलेगा, वह Bitcoin को एक बिल्कुल नए वॉलेट में प्राप्त कर लेगा जिसे केवल वही नियंत्रित करता है।",
"giftLinkWarn": "⚠ जो भी इस लिंक को खोलेगा वह राशि प्राप्त कर सकता है, इसलिए इसे केवल उसी व्यक्ति के साथ साझा करें जिसे आप उपहार दे रहे हैं। राशि कम रखें।",
"giftLinkReveal": "उपहार लिंक बनाएँ",
@@ -425,6 +426,7 @@
"claimOr": "या",
"goToWallet": "वॉलेट पर जाएं",
"claimBtn": "इसे प्राप्त करें",
+ "claimNowBtn": "अभी लें",
"claimFeeNote": "~{n} शुल्क",
"claimFailed": "इस उपहार का दावा पहले ही किया जा चुका है या यह अब उपलब्ध नहीं है।",
"claimNotVisibleBody": "इस उपहार को वित्तपोषित करने वाले सिक्के इस वॉलेट के नेटवर्क / डेटा स्रोत से दिखाई नहीं देते हैं। सुनिश्चित करें कि यह वॉलेट प्रेषक के समान नेटवर्क और डेटा स्रोत का उपयोग करता है, फिर फिर से प्रयास करें।",
@@ -618,6 +620,8 @@
"onbSpendBody": "एक उपयोगकर्ता नाम का दावा करें और अपना खुद का भुगतान पता प्राप्त करें - लोग तुरंत अपने नाम के साथ बिटकॉइन भेज सकते हैं।",
"onbNameWait": "चीजों को तैयार करना",
"onbNotNow": "अब नहीं",
+ "onbGiftNameTitle": "अब एक यूज़रनेम चुनें",
+ "onbGiftNameBody": "एक नाम लें और अपना भुगतान पता पाएं, ताकि लोग सिर्फ़ आपके नाम से आपको बिटकॉइन भेज सकें। फिर एक तस्वीर और एक कवर चुनें।",
"onbAvatarTitle": "अपना लुक चुनें",
"onbAvatarBody": "एक अवतार चुनें या अपनी तस्वीर अपलोड करें। आप इसे कभी भी बदल सकते हैं।",
"onbUpload": "फ़ोटो अपलोड करें",
@@ -678,6 +682,7 @@
"namesClaim": "दावा",
"namesClaimed": "अब {name}",
"namesCopy": "पता कॉपी करें",
+ "namesChangeTo": "{addr} में बदलें",
"namesMoreOpen": "अधिक विकल्प",
"namesMoreTitle": "भुगतान करने के तरीके",
"namesMoreBolt11": "बिजली चालान (BOLT 11)",
@@ -910,6 +915,8 @@
"mediaNoImages": "इस फ़ीड में अभी कोई तस्वीर नहीं।",
"mediaNoVideos": "इस फ़ीड में अभी कोई वर्टिकल वीडियो नहीं।",
"videoTapToPlay": "चलाने के लिए टैप करें",
+ "videoPlay": "चलाएँ",
+ "videoPause": "रोकें",
"videoLargeTitle": "वीडियो",
"videoLargeToggle": "बड़े वीडियो अपने आप चलाएँ",
"videoLargeHelp": "{mb} MB से बड़े या 1080p से ऊपर के वीडियो टैप का इंतज़ार करते हैं, ताकि फ़ीड आपका डेटा न खाए। धीमे या डेटा-सेवर कनेक्शन पर सीमा कम होती है।",
diff --git a/src/locales/id.json b/src/locales/id.json
index 6773d96..f16c07b 100644
--- a/src/locales/id.json
+++ b/src/locales/id.json
@@ -137,6 +137,7 @@
"giftSkip": "Lewati dulu",
"giftBackedUp": "Saya sudah mencatatnya",
"giftLink": "Hadiahkan Bitcoin",
+ "giftNotePlaceholder": "Tambahkan catatan (opsional)",
"giftLinkDesc": "Tandatangani sejumlah dana sebagai tautan. Siapa pun yang membukanya mengklaim Bitcoin itu ke dompet baru yang hanya dia kendalikan.",
"giftLinkWarn": "⚠ Siapa pun yang membuka tautan ini bisa mengklaim jumlahnya, jadi bagikan hanya kepada orang yang Anda beri hadiah. Jaga jumlahnya tetap kecil.",
"giftAmountLabel": "Jumlah yang dihadiahkan",
@@ -145,6 +146,7 @@
"giftReserved": "Tautan hadiah belum diklaim ({n})",
"claimBody": "Klaim ke dompet baru yang hanya Anda kendalikan.",
"claimBtn": "Klaim",
+ "claimNowBtn": "Klaim sekarang",
"claimFailed": "Hadiah ini sudah diklaim atau tidak lagi tersedia.",
"claimedTitle": "Diklaim!",
"claimedBody": "Bitcoin Anda sedang dalam perjalanan. Cadangkan frasa pemulihan Anda agar tetap aman.",
@@ -247,6 +249,8 @@
"mediaNoImages": "Belum ada gambar di feed ini.",
"mediaNoVideos": "Belum ada video vertikal di feed ini.",
"videoTapToPlay": "Ketuk untuk memutar",
+ "videoPlay": "Putar",
+ "videoPause": "Jeda",
"videoLargeTitle": "Video",
"videoLargeToggle": "Putar otomatis video besar",
"videoLargeHelp": "Video di atas {mb} MB atau lebih dari 1080p menunggu ketukan, agar feed tidak menghabiskan kuota. Batasnya lebih rendah di koneksi lambat atau mode hemat data.",
@@ -261,5 +265,8 @@
"arkRenewViewTx": "Lihat transaksi ronde",
"pagerFetchingVideo": "Mengambil video berikutnya…",
"pagerFetchingPictures": "Mengambil gambar lainnya…",
- "pagerCaughtUp": "Sementara itu saja"
+ "pagerCaughtUp": "Sementara itu saja",
+ "onbGiftNameTitle": "Sekarang pilih nama pengguna",
+ "onbGiftNameBody": "Klaim sebuah nama dan dapatkan alamat pembayaran sendiri, agar orang bisa mengirimimu bitcoin hanya dengan namamu. Lalu pilih foto dan sampul.",
+ "namesChangeTo": "Ganti ke {addr}"
}
diff --git a/src/locales/it.json b/src/locales/it.json
index 7ac8b00..9988888 100644
--- a/src/locales/it.json
+++ b/src/locales/it.json
@@ -222,6 +222,8 @@
"playVideo": "Riproduci",
"videoUnmute": "Attiva audio",
"videoTapToPlay": "Tocca per riprodurre",
+ "videoPlay": "Riproduci",
+ "videoPause": "Pausa",
"videoNoPicture": "Questo browser non riesce a mostrare l'immagine di questo video",
"videoOpenFile": "Apri il file",
"videoLargeTitle": "Video",
@@ -825,6 +827,7 @@
"giftWelcome": "Ti hanno inviato dei Bitcoin",
"giftBackedUp": "L'ho scritta",
"giftLink": "Regala dei Bitcoin",
+ "giftNotePlaceholder": "Aggiungi un messaggio (facoltativo)",
"giftLinkDesc": "Prefirma un importo sotto forma di link. Chi lo apre riscuote i Bitcoin in un portafoglio nuovo di zecca che controlla solo lui.",
"giftLinkWarn": "⚠ Chiunque apra questo link può riscuotere l'importo, quindi condividilo solo con la persona a cui fai il regalo. Mantieni importi piccoli.",
"giftLinkReveal": "Crea link regalo",
@@ -888,6 +891,7 @@
"claimOr": "oppure",
"goToWallet": "Vai al portafoglio",
"claimBtn": "Riscuoti",
+ "claimNowBtn": "Riscatta ora",
"claimFeeNote": "~{n} di commissione",
"claimFailed": "Questo regalo è già stato riscosso o non è più disponibile.",
"claimNotVisibleBody": "Le monete che finanziano questo regalo non sono visibili dalla rete/fonte dati di questo portafoglio. Assicurati che questo portafoglio usi la stessa rete e fonte dati del mittente, poi riprova.",
@@ -1154,6 +1158,8 @@
"onbSpendBody": "Scegli un nome utente e ottieni il tuo indirizzo di pagamento. Chiunque potrà inviarti bitcoin all’istante, solo con il tuo nome.",
"onbNameWait": "Preparazione in corso…",
"onbNotNow": "Non ora",
+ "onbGiftNameTitle": "Ora scegli un nome utente",
+ "onbGiftNameBody": "Prendi un nome e ottieni il tuo indirizzo di pagamento, così ti possono inviare bitcoin solo con il tuo nome. Poi scegli una foto e una copertina.",
"onbAvatarTitle": "Scegli il tuo aspetto",
"onbAvatarBody": "Scegli una copertina e un avatar, oppure carica i tuoi. Puoi cambiarli quando vuoi.",
"onbCover": "Immagine di copertina",
@@ -1240,6 +1246,7 @@
"namesClaim": "Richiedi",
"namesClaimed": "Ora sei {name}",
"namesCopy": "Copia indirizzo",
+ "namesChangeTo": "Cambia in {addr}",
"namesMoreOpen": "Altre opzioni",
"namesMoreTitle": "Altri modi per farti pagare",
"namesMoreBolt11": "Fattura Lightning (BOLT 11)",
diff --git a/src/locales/ja.json b/src/locales/ja.json
index b8968cc..010955a 100644
--- a/src/locales/ja.json
+++ b/src/locales/ja.json
@@ -364,6 +364,7 @@
"giftWelcome": "Bitcoin が届きました",
"giftBackedUp": "書き留めました",
"giftLink": "Bitcoin を贈る",
+ "giftNotePlaceholder": "メッセージを添える(任意)",
"giftLinkDesc": "金額をリンクとして事前署名します。リンクを開いた人が、その人だけが管理できる真新しいウォレットに Bitcoin を受け取ります。",
"giftLinkWarn": "⚠ このリンクを開いた人は誰でもその金額を受け取れるので、贈る相手とだけ共有してください。金額は少なめにしましょう。",
"giftLinkReveal": "ギフトリンクを作成",
@@ -425,6 +426,7 @@
"claimOr": "または",
"goToWallet": "ウォレットに行く",
"claimBtn": "受け取る",
+ "claimNowBtn": "今すぐ受け取る",
"claimFeeNote": "ふりがな{n} 料金について",
"claimFailed": "このギフトはすでに受け取られたか、現在利用できません。",
"claimNotVisibleBody": "このギフトに資金を調達するコインは、このウォレットのネットワーク/データソースから表示されません。 このウォレットは、送信者と同じネットワークとデータソースを使用していて、もう一度お試しください。",
@@ -618,6 +620,8 @@
"onbSpendBody": "ユーザー名を主張し、独自の支払いアドレスを取得する, 人々は、あなたの名前だけで、即座にビットコインを送ることができます。",
"onbNameWait": "物事を準備する...",
"onbNotNow": "今は今",
+ "onbGiftNameTitle": "次にユーザー名を選びましょう",
+ "onbGiftNameBody": "名前を取得して自分の支払いアドレスを手に入れましょう。名前だけでビットコインを受け取れます。そのあと写真とカバーを選びます。",
"onbAvatarTitle": "お問い合わせ",
"onbAvatarBody": "アバターを選ぶか、自分の写真をアップロードしてください。いつでも変更できます。",
"onbUpload": "写真をアップロードする",
@@ -678,6 +682,7 @@
"namesClaim": "ログイン",
"namesClaimed": "これから {name}",
"namesCopy": "コピーアドレス",
+ "namesChangeTo": "{addr} に変更",
"namesMoreOpen": "その他のオプション",
"namesMoreTitle": "支払われるより多くの方法",
"namesMoreBolt11": "ライトニングインボイス(BOLT 11)",
@@ -910,6 +915,8 @@
"mediaNoImages": "このフィードにはまだ画像がありません。",
"mediaNoVideos": "このフィードにはまだ縦型動画がありません。",
"videoTapToPlay": "タップして再生",
+ "videoPlay": "再生",
+ "videoPause": "一時停止",
"videoLargeTitle": "動画",
"videoLargeToggle": "大きな動画を自動再生",
"videoLargeHelp": "{mb} MBを超える動画や1080pを超える動画は、データを使いすぎないようタップするまで再生しません。低速回線やデータセーバー時は上限が下がります。",
diff --git a/src/locales/ko.json b/src/locales/ko.json
index e4bf342..e25af6e 100644
--- a/src/locales/ko.json
+++ b/src/locales/ko.json
@@ -363,6 +363,7 @@
"giftWelcome": "Bitcoin을 받았습니다",
"giftBackedUp": "적어 두었습니다",
"giftLink": "Bitcoin 선물하기",
+ "giftNotePlaceholder": "메시지 추가 (선택)",
"giftLinkDesc": "금액을 링크로 미리 서명하세요. 링크를 여는 사람은 그 Bitcoin을 자신만 통제하는 완전히 새로운 지갑으로 받게 됩니다.",
"giftLinkWarn": "⚠ 이 링크를 여는 사람은 누구나 금액을 받을 수 있으니, 선물할 상대에게만 공유하세요. 금액은 적게 유지하세요.",
"giftLinkReveal": "선물 링크 만들기",
@@ -424,6 +425,7 @@
"claimOr": "또는",
"goToWallet": "지갑 바로가기",
"claimBtn": "받기",
+ "claimNowBtn": "지금 받기",
"claimFeeNote": "·{n} 요금안내",
"claimFailed": "이 선물은 이미 수령되었거나 더 이상 이용할 수 없습니다.",
"claimNotVisibleBody": "이 선물은 이 지갑의 네트워크/데이터 소스에서 볼 수 없습니다. 이 지갑이 같은 네트워크와 데이터 소스를 보낸 후 다시 시도하십시오.",
@@ -617,6 +619,8 @@
"onbSpendBody": "사용자 이름 및 자신의 지불 주소를 얻기, 사람들은 즉시 Bitcoin을 보낼 수 있습니다, 그냥 당신의 이름.",
"onbNameWait": "준비하는 것들 ...",
"onbNotNow": "현재 위치",
+ "onbGiftNameTitle": "이제 사용자 이름을 고르세요",
+ "onbGiftNameBody": "이름을 등록하고 나만의 결제 주소를 받으세요. 이름만으로 비트코인을 받을 수 있어요. 그다음 사진과 커버를 고르세요.",
"onbAvatarTitle": "자주 묻는 질문",
"onbAvatarBody": "아바타를 선택하거나 사진을 업로드하세요. 언제든지 변경할 수 있습니다.",
"onbUpload": "사진 업로드",
@@ -677,6 +681,7 @@
"namesClaim": "계정 만들기",
"namesClaimed": "현재 위치 {name}",
"namesCopy": "본문 바로가기",
+ "namesChangeTo": "{addr}(으)로 변경",
"namesMoreOpen": "더 많은 옵션",
"namesMoreTitle": "지불하는 방법",
"namesMoreBolt11": "번개 송장 (BOLT 11)",
@@ -909,6 +914,8 @@
"mediaNoImages": "이 피드에는 아직 이미지가 없습니다.",
"mediaNoVideos": "이 피드에는 아직 세로 동영상이 없습니다.",
"videoTapToPlay": "탭하여 재생",
+ "videoPlay": "재생",
+ "videoPause": "일시정지",
"videoLargeTitle": "동영상",
"videoLargeToggle": "큰 동영상 자동 재생",
"videoLargeHelp": "{mb}MB를 넘거나 1080p보다 높은 동영상은 데이터를 아끼기 위해 탭할 때까지 기다립니다. 느린 연결이나 데이터 절약 모드에서는 한도가 더 낮습니다.",
diff --git a/src/locales/mr.json b/src/locales/mr.json
index 17ee1d5..a603747 100644
--- a/src/locales/mr.json
+++ b/src/locales/mr.json
@@ -137,6 +137,7 @@
"giftSkip": "आत्ता वगळा",
"giftBackedUp": "मी ते लिहून ठेवले आहे",
"giftLink": "थोडे Bitcoin भेट द्या",
+ "giftNotePlaceholder": "एक नोंद जोडा (पर्यायी)",
"giftLinkDesc": "एखादी रक्कम लिंक म्हणून आधीच स्वाक्षरित करा. ती उघडणारा कोणीही ते Bitcoin फक्त त्याच्याच नियंत्रणातील एका नव्या कोऱ्या वॉलेटमध्ये घेतो.",
"giftLinkWarn": "⚠ ही लिंक उघडणारा कोणीही ती रक्कम घेऊ शकतो, म्हणून ज्याला भेट देत आहात फक्त त्याच्यासोबतच ती शेअर करा. रक्कम कमी ठेवा.",
"giftAmountLabel": "भेट देण्याची रक्कम",
@@ -145,6 +146,7 @@
"giftReserved": "दावा न केलेल्या भेट लिंक ({n})",
"claimBody": "ते फक्त तुमच्याच नियंत्रणातील एका नव्या कोऱ्या वॉलेटमध्ये घ्या.",
"claimBtn": "ते घ्या",
+ "claimNowBtn": "आता घ्या",
"claimFailed": "ही भेट आधीच घेतली गेली आहे किंवा आता उपलब्ध नाही.",
"claimedTitle": "घेतले!",
"claimedBody": "तुमचे Bitcoin येत आहे. ते सुरक्षित ठेवण्यासाठी तुमच्या रिकव्हरी वाक्यांशाचा बॅकअप घ्या.",
@@ -247,6 +249,8 @@
"mediaNoImages": "या फीडमध्ये अजून चित्रे नाहीत.",
"mediaNoVideos": "या फीडमध्ये अजून उभे व्हिडिओ नाहीत.",
"videoTapToPlay": "चालवण्यासाठी टॅप करा",
+ "videoPlay": "चालवा",
+ "videoPause": "थांबवा",
"videoLargeTitle": "व्हिडिओ",
"videoLargeToggle": "मोठे व्हिडिओ आपोआप चालवा",
"videoLargeHelp": "{mb} MB पेक्षा मोठे किंवा 1080p पेक्षा वरचे व्हिडिओ तुमचा डेटा वाचवण्यासाठी टॅपची वाट पाहतात. धीम्या किंवा डेटा-सेव्हर कनेक्शनवर मर्यादा कमी असते.",
@@ -261,5 +265,8 @@
"arkRenewViewTx": "राउंडचा व्यवहार पहा",
"pagerFetchingVideo": "पुढचा व्हिडिओ आणत आहे…",
"pagerFetchingPictures": "आणखी चित्रे आणत आहे…",
- "pagerCaughtUp": "सध्या एवढेच"
+ "pagerCaughtUp": "सध्या एवढेच",
+ "onbGiftNameTitle": "आता एक युजरनेम निवडा",
+ "onbGiftNameBody": "एक नाव घ्या आणि स्वतःचा पेमेंट पत्ता मिळवा, म्हणजे लोक फक्त तुमच्या नावाने तुम्हाला बिटकॉइन पाठवू शकतील. मग एक फोटो आणि कव्हर निवडा.",
+ "namesChangeTo": "{addr} मध्ये बदला"
}
diff --git a/src/locales/pt.json b/src/locales/pt.json
index 11ff22c..48496ee 100644
--- a/src/locales/pt.json
+++ b/src/locales/pt.json
@@ -364,6 +364,7 @@
"giftWelcome": "Você recebeu Bitcoin",
"giftBackedUp": "Já anotei",
"giftLink": "Presentear Bitcoin",
+ "giftNotePlaceholder": "Adicione um recado (opcional)",
"giftLinkDesc": "Pré-assine um valor como um link. Quem o abrir resgata os Bitcoin para uma carteira novinha que só essa pessoa controla.",
"giftLinkWarn": "⚠ Qualquer pessoa que abrir este link pode resgatar o valor, então compartilhe-o apenas com a pessoa que você está presenteando. Mantenha os valores baixos.",
"giftLinkReveal": "Criar link de presente",
@@ -425,6 +426,7 @@
"claimOr": "ou",
"goToWallet": "Ir para a carteira",
"claimBtn": "Resgatar",
+ "claimNowBtn": "Resgatar agora",
"claimFeeNote": "~{n} taxa",
"claimFailed": "Este presente já foi resgatado ou não está mais disponível.",
"claimNotVisibleBody": "As moedas que financiam este presente não são visíveis da rede/fonte de dados desta carteira. Certifique-se de que esta carteira usa a mesma rede e fonte de dados que o remetente e tente novamente.",
@@ -618,6 +620,8 @@
"onbSpendBody": "Reclame um nome de usuário e obtenha seu próprio endereço de pagamento, as pessoas podem enviar bitcoin instantaneamente, com apenas seu nome.",
"onbNameWait": "Preparando as coisas...",
"onbNotNow": "Agora não.",
+ "onbGiftNameTitle": "Agora escolha um nome de usuário",
+ "onbGiftNameBody": "Reserve um nome e ganhe seu próprio endereço de pagamento, para que possam te enviar bitcoin só com o seu nome. Depois escolha uma foto e uma capa.",
"onbAvatarTitle": "Escolha o seu look",
"onbAvatarBody": "Escolha um avatar ou carregue a sua própria foto. Podes mudá-lo quando quiseres.",
"onbUpload": "Enviar uma foto",
@@ -678,6 +682,7 @@
"namesClaim": "Alegação",
"namesClaimed": "Agora és. {name}",
"namesCopy": "Copiar endereço",
+ "namesChangeTo": "Mudar para {addr}",
"namesMoreOpen": "Mais opções",
"namesMoreTitle": "Mais formas de ser pago",
"namesMoreBolt11": "Factura relâmpago (BOLT 11)",
@@ -910,6 +915,8 @@
"mediaNoImages": "Ainda não há imagens neste feed.",
"mediaNoVideos": "Ainda não há vídeos verticais neste feed.",
"videoTapToPlay": "Toque para reproduzir",
+ "videoPlay": "Reproduzir",
+ "videoPause": "Pausar",
"videoLargeTitle": "Vídeos",
"videoLargeToggle": "Reproduzir vídeos grandes automaticamente",
"videoLargeHelp": "Vídeos acima de {mb} MB ou de 1080p esperam um toque, para o feed não consumir seus dados. O limite é menor em conexões lentas ou com economia de dados.",
diff --git a/src/locales/ru.json b/src/locales/ru.json
index 0f2936d..6c0b003 100644
--- a/src/locales/ru.json
+++ b/src/locales/ru.json
@@ -364,6 +364,7 @@
"giftWelcome": "Вам отправили Bitcoin",
"giftBackedUp": "Я записал(а)",
"giftLink": "Подарить немного Bitcoin",
+ "giftNotePlaceholder": "Добавьте записку (необязательно)",
"giftLinkDesc": "Заранее подпишите сумму в виде ссылки. Тот, кто откроет её, получит Bitcoin в совершенно новый кошелёк, которым управляет только он.",
"giftLinkWarn": "⚠ Любой, кто откроет эту ссылку, может получить эту сумму, поэтому делитесь ею только с тем, кому дарите. Держите суммы небольшими.",
"giftLinkReveal": "Создать ссылку-подарок",
@@ -425,6 +426,7 @@
"claimOr": "или",
"goToWallet": "Иди к кошельку",
"claimBtn": "Получить",
+ "claimNowBtn": "Получить сейчас",
"claimFeeNote": "~{n} взнос",
"claimFailed": "Этот подарок уже получен или больше недоступен.",
"claimNotVisibleBody": "Монеты, финансирующие этот подарок, не видны из сети / источника данных этого кошелька. Убедитесь, что этот кошелек использует ту же сеть и источник данных, что и отправитель.",
@@ -618,6 +620,8 @@
"onbSpendBody": "Заявите имя пользователя и получите свой собственный платежный адрес, люди могут отправить вам биткойн мгновенно, только с вашим именем.",
"onbNameWait": "Готовить вещи...",
"onbNotNow": "Не сейчас",
+ "onbGiftNameTitle": "Теперь выберите имя пользователя",
+ "onbGiftNameBody": "Займите имя и получите свой платёжный адрес — тогда вам смогут отправлять биткоин просто по имени. Потом выберите фото и обложку.",
"onbAvatarTitle": "Выберите свой взгляд",
"onbAvatarBody": "Выберите аватар или загрузите свою фотографию. Его можно изменить в любое время.",
"onbUpload": "Загрузить фото",
@@ -678,6 +682,7 @@
"namesClaim": "Претензия",
"namesClaimed": "Ты теперь {name}",
"namesCopy": "Адрес копии",
+ "namesChangeTo": "Сменить на {addr}",
"namesMoreOpen": "Больше вариантов",
"namesMoreTitle": "Больше способов получить оплату",
"namesMoreBolt11": "Инвойс молнии (BOLT 11)",
@@ -910,6 +915,8 @@
"mediaNoImages": "В этой ленте пока нет фото.",
"mediaNoVideos": "В этой ленте пока нет вертикальных видео.",
"videoTapToPlay": "Нажмите, чтобы воспроизвести",
+ "videoPlay": "Воспроизвести",
+ "videoPause": "Пауза",
"videoLargeTitle": "Видео",
"videoLargeToggle": "Автовоспроизведение больших видео",
"videoLargeHelp": "Видео больше {mb} МБ или выше 1080p ждут нажатия, чтобы лента не съедала трафик. На медленном соединении или в режиме экономии лимит ниже.",
diff --git a/src/locales/sw.json b/src/locales/sw.json
index b130faf..4ffba61 100644
--- a/src/locales/sw.json
+++ b/src/locales/sw.json
@@ -137,6 +137,7 @@
"giftSkip": "Ruka kwa sasa",
"giftBackedUp": "Nimeshakiandika",
"giftLink": "Toa Bitcoin kama zawadi",
+ "giftNotePlaceholder": "Ongeza ujumbe (si lazima)",
"giftLinkDesc": "Tia saini kiasi mapema kama kiungo. Yeyote anayekifungua hudai Bitcoin kwenye pochi mpya kabisa anayoidhibiti yeye pekee.",
"giftLinkWarn": "⚠ Yeyote anayefungua kiungo hiki anaweza kudai kiasi hicho, kwa hivyo kishiriki tu na mtu unayempa zawadi. Weka kiasi kidogo.",
"giftAmountLabel": "Kiasi cha kutoa zawadi",
@@ -145,6 +146,7 @@
"giftReserved": "Viungo vya zawadi visivyodaiwa ({n})",
"claimBody": "Idai kwenye pochi mpya kabisa unayoidhibiti wewe pekee.",
"claimBtn": "Idai",
+ "claimNowBtn": "Dai sasa",
"claimFailed": "Zawadi hii tayari imedaiwa au haipatikani tena.",
"claimedTitle": "Imedaiwa!",
"claimedBody": "Bitcoin yako inakuja. Hifadhi kifungu chako cha kurejesha ili kuilinda.",
@@ -247,6 +249,8 @@
"mediaNoImages": "Bado hakuna picha kwenye mlisho huu.",
"mediaNoVideos": "Bado hakuna video wima kwenye mlisho huu.",
"videoTapToPlay": "Gusa ili kucheza",
+ "videoPlay": "Cheza",
+ "videoPause": "Sitisha",
"videoLargeTitle": "Video",
"videoLargeToggle": "Cheza video kubwa zenyewe",
"videoLargeHelp": "Video zaidi ya MB {mb} au juu ya 1080p husubiri uguse, ili mlisho usimalize data yako. Kikomo ni cha chini kwenye muunganisho wa polepole au wa kuokoa data.",
@@ -261,5 +265,8 @@
"arkRenewViewTx": "Tazama muamala wa raundi",
"pagerFetchingVideo": "Inaleta video inayofuata…",
"pagerFetchingPictures": "Inaleta picha zaidi…",
- "pagerCaughtUp": "Hayo ndiyo yote kwa sasa"
+ "pagerCaughtUp": "Hayo ndiyo yote kwa sasa",
+ "onbGiftNameTitle": "Sasa chagua jina la mtumiaji",
+ "onbGiftNameBody": "Chukua jina upate anwani yako ya malipo, ili watu wakutumie bitcoin kwa jina lako tu. Kisha chagua picha na jalada.",
+ "namesChangeTo": "Badilisha kuwa {addr}"
}
diff --git a/src/locales/ta.json b/src/locales/ta.json
index da4e5b0..c9e6aae 100644
--- a/src/locales/ta.json
+++ b/src/locales/ta.json
@@ -137,6 +137,7 @@
"giftSkip": "இப்போதைக்குத் தவிர்",
"giftBackedUp": "நான் எழுதி வைத்துவிட்டேன்",
"giftLink": "கொஞ்சம் Bitcoin பரிசளி",
+ "giftNotePlaceholder": "ஒரு குறிப்பைச் சேர்க்கவும் (விருப்பம்)",
"giftLinkDesc": "ஒரு தொகையை இணைப்பாக முன்கூட்டியே கையொப்பமிடுங்கள். இதைத் திறப்பவர், அவர்கள் மட்டுமே கட்டுப்படுத்தும் புத்தம்புதிய வாலட்டிற்குள் Bitcoin-ஐ உரிமை கொள்வார்கள்.",
"giftLinkWarn": "⚠ இந்த இணைப்பைத் திறக்கும் எவரும் தொகையை உரிமை கொள்ளலாம், எனவே நீங்கள் பரிசளிக்கும் நபருடன் மட்டுமே இதைப் பகிரவும். தொகையைக் குறைவாக வைத்திருங்கள்.",
"giftAmountLabel": "பரிசளிக்கும் தொகை",
@@ -145,6 +146,7 @@
"giftReserved": "கோரப்படாத பரிசு இணைப்புகள் ({n})",
"claimBody": "நீங்கள் மட்டுமே கட்டுப்படுத்தும் புத்தம்புதிய வாலட்டிற்குள் இதை உரிமை கொள்ளுங்கள்.",
"claimBtn": "உரிமை கொள்",
+ "claimNowBtn": "இப்போதே பெறுங்கள்",
"claimFailed": "இந்தப் பரிசு ஏற்கனவே உரிமை கொள்ளப்பட்டுவிட்டது அல்லது இனி கிடைக்கவில்லை.",
"claimedTitle": "உரிமை கொள்ளப்பட்டது!",
"claimedBody": "உங்கள் Bitcoin வந்துகொண்டிருக்கிறது. அதைப் பாதுகாப்பாக வைக்க உங்கள் மீட்பு சொற்றொடரைக் காப்புப்பிரதி எடுங்கள்.",
@@ -247,6 +249,8 @@
"mediaNoImages": "இந்த ஊட்டத்தில் இன்னும் படங்கள் இல்லை.",
"mediaNoVideos": "இந்த ஊட்டத்தில் இன்னும் செங்குத்து வீடியோக்கள் இல்லை.",
"videoTapToPlay": "இயக்கத் தட்டவும்",
+ "videoPlay": "இயக்கு",
+ "videoPause": "இடைநிறுத்து",
"videoLargeTitle": "வீடியோக்கள்",
"videoLargeToggle": "பெரிய வீடியோக்களைத் தானாக இயக்கு",
"videoLargeHelp": "{mb} MB-க்கு மேல் அல்லது 1080p-க்கு மேலான வீடியோக்கள் உங்கள் டேட்டாவைச் சேமிக்க, தட்டும் வரை காத்திருக்கும். மெதுவான அல்லது டேட்டா சேமிப்பு இணைப்பில் வரம்பு குறைவு.",
@@ -261,5 +265,8 @@
"arkRenewViewTx": "சுற்றின் பரிவர்த்தனையைக் காண்க",
"pagerFetchingVideo": "அடுத்த வீடியோவைப் பெறுகிறது…",
"pagerFetchingPictures": "மேலும் படங்களைப் பெறுகிறது…",
- "pagerCaughtUp": "இப்போதைக்கு இவ்வளவுதான்"
+ "pagerCaughtUp": "இப்போதைக்கு இவ்வளவுதான்",
+ "onbGiftNameTitle": "இப்போது ஒரு பயனர்பெயரைத் தேர்ந்தெடுங்கள்",
+ "onbGiftNameBody": "ஒரு பெயரைப் பெற்று உங்கள் சொந்த பணம் பெறும் முகவரியைப் பெறுங்கள்; உங்கள் பெயரை மட்டும் வைத்தே மற்றவர்கள் பிட்காயின் அனுப்பலாம். பிறகு ஒரு படத்தையும் அட்டைப்படத்தையும் தேர்ந்தெடுங்கள்.",
+ "namesChangeTo": "{addr} ஆக மாற்று"
}
diff --git a/src/locales/te.json b/src/locales/te.json
index 7e60eaf..7a30efb 100644
--- a/src/locales/te.json
+++ b/src/locales/te.json
@@ -137,6 +137,7 @@
"giftSkip": "ప్రస్తుతానికి దాటవేయి",
"giftBackedUp": "నేను దాన్ని రాసుకున్నాను",
"giftLink": "కొంత Bitcoin బహుమతిగా ఇవ్వండి",
+ "giftNotePlaceholder": "ఒక సందేశం జోడించండి (ఐచ్ఛికం)",
"giftLinkDesc": "ఒక మొత్తాన్ని ముందుగా సంతకం చేసి లింక్‌గా ఇవ్వండి. దాన్ని తెరిచినవారు ఆ Bitcoinను తాము మాత్రమే నియంత్రించే సరికొత్త వాలెట్‌లోకి క్లెయిమ్ చేసుకుంటారు.",
"giftLinkWarn": "⚠ ఈ లింక్ తెరిచిన ఎవరైనా ఆ మొత్తాన్ని క్లెయిమ్ చేయగలరు, కాబట్టి మీరు బహుమతి ఇస్తున్న వ్యక్తికి మాత్రమే దీన్ని పంచుకోండి. మొత్తాలను తక్కువగా ఉంచండి.",
"giftAmountLabel": "బహుమతిగా ఇచ్చే మొత్తం",
@@ -145,6 +146,7 @@
"giftReserved": "దావా చేయని బహుమతి లింకులు ({n})",
"claimBody": "మీరు మాత్రమే నియంత్రించే సరికొత్త వాలెట్‌లోకి దాన్ని క్లెయిమ్ చేసుకోండి.",
"claimBtn": "క్లెయిమ్ చేసుకోండి",
+ "claimNowBtn": "ఇప్పుడే పొందండి",
"claimFailed": "ఈ బహుమతి ఇప్పటికే క్లెయిమ్ చేయబడింది లేదా ఇక అందుబాటులో లేదు.",
"claimedTitle": "క్లెయిమ్ అయింది!",
"claimedBody": "మీ Bitcoin మీ వద్దకు వస్తోంది. దాన్ని సురక్షితంగా ఉంచడానికి మీ రికవరీ ఫ్రేజ్‌ను బ్యాకప్ చేయండి.",
@@ -245,6 +247,8 @@
"mediaNoImages": "ఈ ఫీడ్‌లో ఇంకా చిత్రాలు లేవు.",
"mediaNoVideos": "ఈ ఫీడ్‌లో ఇంకా నిలువు వీడియోలు లేవు.",
"videoTapToPlay": "ప్లే చేయడానికి నొక్కండి",
+ "videoPlay": "ప్లే",
+ "videoPause": "పాజ్",
"videoLargeTitle": "వీడియోలు",
"videoLargeToggle": "పెద్ద వీడియోలను ఆటో‌ప్లే చేయి",
"videoLargeHelp": "{mb} MB కంటే పెద్దవి లేదా 1080p పైబడిన వీడియోలు మీ డేటా ఆదా కోసం నొక్కే వరకు ఆగుతాయి. నెమ్మదైన లేదా డేటా సేవర్ కనెక్షన్‌లో పరిమితి తక్కువ.",
@@ -259,5 +263,8 @@
"arkRenewViewTx": "రౌండ్ లావాదేవీని చూడండి",
"pagerFetchingVideo": "తదుపరి వీడియోను తెస్తోంది…",
"pagerFetchingPictures": "మరిన్ని చిత్రాలను తెస్తోంది…",
- "pagerCaughtUp": "ప్రస్తుతానికి ఇంతే"
+ "pagerCaughtUp": "ప్రస్తుతానికి ఇంతే",
+ "onbGiftNameTitle": "ఇప్పుడు ఒక యూజర్‌నేమ్ ఎంచుకోండి",
+ "onbGiftNameBody": "ఒక పేరు తీసుకుని మీ సొంత చెల్లింపు చిరునామా పొందండి, అప్పుడు మీ పేరుతోనే ఎవరైనా మీకు బిట్‌కాయిన్ పంపవచ్చు. తర్వాత ఒక ఫోటో, ఒక కవర్ ఎంచుకోండి.",
+ "namesChangeTo": "{addr}కి మార్చు"
}
diff --git a/src/locales/tr.json b/src/locales/tr.json
index 1e60eeb..a406b7b 100644
--- a/src/locales/tr.json
+++ b/src/locales/tr.json
@@ -363,6 +363,7 @@
"giftWelcome": "Size Bitcoin gönderildi",
"giftBackedUp": "Yazdım",
"giftLink": "Bitcoin hediye et",
+ "giftNotePlaceholder": "Not ekle (isteğe bağlı)",
"giftLinkDesc": "Bir tutarı önceden imzalayıp bağlantı olarak verin. Bağlantıyı açan, Bitcoin’i yalnızca kendi kontrolündeki yepyeni bir cüzdana alır.",
"giftLinkWarn": "⚠ Bu bağlantıyı açan herkes tutarı talep edebilir, bu yüzden yalnızca hediye ettiğiniz kişiyle paylaşın. Tutarları küçük tutun.",
"giftLinkReveal": "Hediye bağlantısı oluştur",
@@ -424,6 +425,7 @@
"claimOr": "veya",
"goToWallet": "Cüzdana git",
"claimBtn": "Talep et",
+ "claimNowBtn": "Şimdi al",
"claimFeeNote": "~{n} ücret ücreti",
"claimFailed": "Bu hediye zaten talep edilmiş veya artık kullanılamıyor.",
"claimNotVisibleBody": "Paralar bu hediyeyi finanse ediyor bu cüzdanın ağ/data kaynağından görünür değil. Bu cüzdanın aynı ağ ve veri kaynağını gönderileyici olarak kullandığından emin olun, sonra tekrar deneyin.",
@@ -617,6 +619,8 @@
"onbSpendBody": "Bir kullanıcı adı talep edin ve kendi ödeme adresinizi alın - insanlar size anında Bitcoin gönderebilir, sadece adınızla.",
"onbNameWait": "İşler hazır olsun...",
"onbNotNow": "Şimdi Değil",
+ "onbGiftNameTitle": "Şimdi bir kullanıcı adı seç",
+ "onbGiftNameBody": "Bir isim al ve kendi ödeme adresine sahip ol; insanlar sana sadece adınla bitcoin gönderebilsin. Sonra bir fotoğraf ve kapak seç.",
"onbAvatarTitle": "görünümünü seçin",
"onbAvatarBody": "Bir avatar seçin veya kendi resminizi yükleyin. İstediğiniz zaman değiştirebilirsiniz.",
"onbUpload": "Bir fotoğraf",
@@ -677,6 +681,7 @@
"namesClaim": "Talep Davası",
"namesClaimed": "You are now {name}",
"namesCopy": "Kopya adresi",
+ "namesChangeTo": "{addr} olarak değiştir",
"namesMoreOpen": "Daha fazla seçenek",
"namesMoreTitle": "Ödeme yapmak için daha fazla yol",
"namesMoreBolt11": "Yıldırım Fatura (BOLT 11)",
@@ -909,6 +914,8 @@
"mediaNoImages": "Bu akışta henüz görsel yok.",
"mediaNoVideos": "Bu akışta henüz dikey video yok.",
"videoTapToPlay": "Oynatmak için dokun",
+ "videoPlay": "Oynat",
+ "videoPause": "Duraklat",
"videoLargeTitle": "Videolar",
"videoLargeToggle": "Büyük videoları otomatik oynat",
"videoLargeHelp": "{mb} MB’den büyük veya 1080p’nin üzerindeki videolar, akış verini tüketmesin diye dokunmanı bekler. Yavaş ya da veri tasarruflu bağlantıda sınır daha düşüktür.",
diff --git a/src/locales/ur.json b/src/locales/ur.json
index 6efb6ec..1f35df9 100644
--- a/src/locales/ur.json
+++ b/src/locales/ur.json
@@ -137,6 +137,7 @@
"giftSkip": "ابھی چھوڑیں",
"giftBackedUp": "میں نے اسے لکھ لیا ہے",
"giftLink": "کچھ Bitcoin تحفے میں دیں",
+ "giftNotePlaceholder": "ایک نوٹ شامل کریں (اختیاری)",
"giftLinkDesc": "ایک رقم کو بطور لنک پہلے سے دستخط کریں۔ جو بھی اسے کھولے وہ Bitcoin کو ایک بالکل نئے والیٹ میں وصول کر لیتا ہے جو صرف اسی کے کنٹرول میں ہوتا ہے۔",
"giftLinkWarn": "⚠ جو بھی یہ لنک کھولے وہ اس رقم کا دعویٰ کر سکتا ہے، اس لیے اسے صرف اسی شخص کے ساتھ شیئر کریں جسے آپ تحفہ دے رہے ہیں۔ رقم کم رکھیں۔",
"giftLinkReveal": "تحفہ لنک بنائیں",
@@ -147,6 +148,7 @@
"giftReserved": "غیر دعویٰ شدہ تحفہ لنکس ({n})",
"claimBody": "اسے ایک بالکل نئے والیٹ میں وصول کریں جو صرف آپ کے کنٹرول میں ہو۔",
"claimBtn": "وصول کریں",
+ "claimNowBtn": "ابھی حاصل کریں",
"claimFailed": "اس تحفے کا پہلے ہی دعویٰ کیا جا چکا ہے یا یہ اب دستیاب نہیں۔",
"claimedTitle": "وصول ہو گیا!",
"claimedBody": "آپ کا Bitcoin راستے میں ہے۔ اسے محفوظ رکھنے کے لیے اپنے بحالی فقرے کا بیک اپ بنا لیں۔",
@@ -247,6 +249,8 @@
"mediaNoImages": "اس فیڈ میں ابھی کوئی تصویر نہیں۔",
"mediaNoVideos": "اس فیڈ میں ابھی کوئی عمودی ویڈیو نہیں۔",
"videoTapToPlay": "چلانے کے لیے ٹیپ کریں",
+ "videoPlay": "چلائیں",
+ "videoPause": "روکیں",
"videoLargeTitle": "ویڈیوز",
"videoLargeToggle": "بڑی ویڈیوز خود چلائیں",
"videoLargeHelp": "{mb} MB سے بڑی یا 1080p سے اوپر کی ویڈیوز ٹیپ کا انتظار کرتی ہیں، تاکہ فیڈ آپ کا ڈیٹا نہ کھائے۔ سست یا ڈیٹا بچت والے کنکشن پر حد کم ہوتی ہے۔",
@@ -261,5 +265,8 @@
"arkRenewViewTx": "راؤنڈ کی ٹرانزیکشن دیکھیں",
"pagerFetchingVideo": "اگلی ویڈیو لائی جا رہی ہے…",
"pagerFetchingPictures": "مزید تصاویر لائی جا رہی ہیں…",
- "pagerCaughtUp": "فی الحال بس اتنا ہی"
+ "pagerCaughtUp": "فی الحال بس اتنا ہی",
+ "onbGiftNameTitle": "اب ایک یوزرنیم چنیں",
+ "onbGiftNameBody": "ایک نام لیں اور اپنا ادائیگی کا پتہ پائیں، تاکہ لوگ صرف آپ کے نام سے آپ کو بٹ کوائن بھیج سکیں۔ پھر ایک تصویر اور ایک کور چنیں۔",
+ "namesChangeTo": "{addr} میں بدلیں"
}
diff --git a/src/locales/vi.json b/src/locales/vi.json
index 415f4e7..31f61ad 100644
--- a/src/locales/vi.json
+++ b/src/locales/vi.json
@@ -137,6 +137,7 @@
"giftSkip": "Bỏ qua lúc này",
"giftBackedUp": "Tôi đã ghi lại rồi",
"giftLink": "Tặng một ít Bitcoin",
+ "giftNotePlaceholder": "Thêm lời nhắn (không bắt buộc)",
"giftLinkDesc": "Ký trước một số tiền thành một liên kết. Ai mở liên kết sẽ nhận số Bitcoin đó vào một ví hoàn toàn mới mà chỉ riêng họ kiểm soát.",
"giftLinkWarn": "⚠ Bất kỳ ai mở liên kết này đều có thể nhận số tiền, vì vậy chỉ chia sẻ với người bạn muốn tặng. Hãy giữ số tiền nhỏ.",
"giftAmountLabel": "Số tiền muốn tặng",
@@ -145,6 +146,7 @@
"giftReserved": "Liên kết quà chưa nhận ({n})",
"claimBody": "Nhận nó vào một ví hoàn toàn mới mà chỉ riêng bạn kiểm soát.",
"claimBtn": "Nhận ngay",
+ "claimNowBtn": "Nhận ngay",
"claimFailed": "Món quà này đã được nhận hoặc không còn khả dụng.",
"claimedTitle": "Đã nhận!",
"claimedBody": "Bitcoin của bạn đang trên đường tới. Hãy sao lưu cụm từ khôi phục để giữ an toàn.",
@@ -247,6 +249,8 @@
"mediaNoImages": "Bảng tin này chưa có ảnh.",
"mediaNoVideos": "Bảng tin này chưa có video dọc.",
"videoTapToPlay": "Chạm để phát",
+ "videoPlay": "Phát",
+ "videoPause": "Tạm dừng",
"videoLargeTitle": "Video",
"videoLargeToggle": "Tự động phát video lớn",
"videoLargeHelp": "Video trên {mb} MB hoặc cao hơn 1080p sẽ chờ bạn chạm, để bảng tin không ngốn dữ liệu. Giới hạn thấp hơn khi kết nối chậm hoặc tiết kiệm dữ liệu.",
@@ -261,5 +265,8 @@
"arkRenewViewTx": "Xem giao dịch của vòng",
"pagerFetchingVideo": "Đang tải video tiếp theo…",
"pagerFetchingPictures": "Đang tải thêm ảnh…",
- "pagerCaughtUp": "Tạm thời chỉ có vậy"
+ "pagerCaughtUp": "Tạm thời chỉ có vậy",
+ "onbGiftNameTitle": "Giờ hãy chọn tên người dùng",
+ "onbGiftNameBody": "Nhận một cái tên và địa chỉ thanh toán của riêng bạn, để mọi người gửi bitcoin cho bạn chỉ bằng tên. Sau đó chọn ảnh đại diện và ảnh bìa.",
+ "namesChangeTo": "Đổi thành {addr}"
}
diff --git a/src/locales/zh.json b/src/locales/zh.json
index 6b3cc49..1ed54fa 100644
--- a/src/locales/zh.json
+++ b/src/locales/zh.json
@@ -364,6 +364,7 @@
"giftWelcome": "有人给你转了 Bitcoin",
"giftBackedUp": "我已经抄写下来了",
"giftLink": "赠送一些 Bitcoin",
+ "giftNotePlaceholder": "添加留言(可选)",
"giftLinkDesc": "将一笔金额预签为一个链接。打开链接的人可将这笔 Bitcoin 领取到一个仅由他们自己掌控的全新钱包中。",
"giftLinkWarn": "⚠ 任何打开此链接的人都能领取这笔金额,所以请仅分享给你要赠送的对象。请保持金额较小。",
"giftLinkReveal": "创建赠送链接",
@@ -425,6 +426,7 @@
"claimOr": "或者说",
"goToWallet": "转到钱包",
"claimBtn": "领取",
+ "claimNowBtn": "立即领取",
"claimFeeNote": "~ (法语){n} 收费",
"claimFailed": "此礼物已被领取或不再可用。",
"claimNotVisibleBody": "从这个钱包的网络/数据来源看, 确保这个钱包使用与发送者相同的网络和数据源,然后再次尝试.",
@@ -618,6 +620,8 @@
"onbSpendBody": "要求一个用户名并获得你自己的付款地址,人们可以立刻发送你比特币,只要你的名字.",
"onbNameWait": "准备...",
"onbNotNow": "现在不行",
+ "onbGiftNameTitle": "现在选一个用户名",
+ "onbGiftNameBody": "领取一个名字,获得你自己的收款地址,别人只用你的名字就能给你发比特币。然后选一张头像和封面。",
"onbAvatarTitle": "选择你的外观",
"onbAvatarBody": "选择一个头像或上传自己的照片。你可以随时更改",
"onbUpload": "上传相片",
@@ -678,6 +682,7 @@
"namesClaim": "索赔",
"namesClaimed": "你现在是 {name}",
"namesCopy": "复制地址",
+ "namesChangeTo": "改为 {addr}",
"namesMoreOpen": "更多选项",
"namesMoreTitle": "更多赚钱的方法",
"namesMoreBolt11": "闪电发票(BOLT 11)",
@@ -910,6 +915,8 @@
"mediaNoImages": "此动态中还没有图片。",
"mediaNoVideos": "此动态中还没有竖屏视频。",
"videoTapToPlay": "点按播放",
+ "videoPlay": "播放",
+ "videoPause": "暂停",
"videoLargeTitle": "视频",
"videoLargeToggle": "自动播放大视频",
"videoLargeHelp": "超过 {mb} MB 或高于 1080p 的视频会等你点按再播放,以免动态耗尽流量。在慢速或省流量连接下,上限更低。",
diff --git a/src/marmot-client.js b/src/marmot-client.js
index b514216..707003f 100644
--- a/src/marmot-client.js
+++ b/src/marmot-client.js
@@ -16,7 +16,7 @@ import { dlog } from './debug.js';
// Where the groups we found live. Signed into group state, so every member
// reads and writes the same list. Not relay.damus.io or relay.nostr.band:
// White Noise (MDK's RETIRED_RELAY_HOSTS) never dials those.
-export const GROUP_RELAYS = ['wss://relay.coinos.io', 'wss://nos.lol', 'wss://relay.primal.net'];
+export const GROUP_RELAYS = ['wss://messages.coinos.io', 'wss://relay.coinos.io', 'wss://nos.lol', 'wss://relay.primal.net'];
// Where White Noise looks people up. It will not invite an account whose
// relay lists (kinds 10002 and 10050) it cannot find, and one whose profile
diff --git a/src/media-timeline.js b/src/media-timeline.js
index 8b6045e..d8ae008 100644
--- a/src/media-timeline.js
+++ b/src/media-timeline.js
@@ -85,7 +85,7 @@ export function markAt(seconds, duration) {
// with closures pointing at a detached player. What was said, reacted or
// zapped at a moment sits on the bar at that moment; replies, reactions and
// zaps made while a clip plays carry its time on their own (see momentOf).
-export function mediaTimeline(player, url, { h, event, moments, glyph, label }) {
+export function mediaTimeline(player, url, { h, event, moments, glyph, label, onMarks = null }) {
const audio = player.tagName === 'AUDIO';
const box = h('div', { class: 'media-timeline', onClick: e => e.stopPropagation(), onPointerdown: e => e.stopPropagation() });
box._skipMorph = true;
@@ -123,6 +123,10 @@ export function mediaTimeline(player, url, { h, event, moments, glyph, label })
}
const items = ev && finite ? moments(ev.id, url) : [];
const next = items.map(x => x.id).join(',') + '@' + (finite ? player.duration : 0);
+ // a video has its own seek bar: this one shows under it only to carry
+ // what was said at a moment (two bars read as a glitch on a phone)
+ box.classList.toggle('has-marks', items.length > 0);
+ if (onMarks) onMarks(items.length > 0);
if (signature !== next) {
signature = next;
marks.replaceChildren(...items.map(x => h('button', { type: 'button', class: 'media-mark', title: mediaClock(x.moment.seconds) + ' ' + x.text,
diff --git a/src/media-upload.js b/src/media-upload.js
index f851943..7f020cf 100644
--- a/src/media-upload.js
+++ b/src/media-upload.js
@@ -73,6 +73,8 @@ function putWithProgress(url, { body, headers, signal }, onProgress) {
});
}
+const hostOf = (server) => { try { return new URL(server).hostname.replace(/^blossom\./, ''); } catch { return server; } };
+
// BUD-02 upload. `signEvent` is deliberately injected: the app can use its
// signed-in Nostr identity, while tests need no secret key.
export async function uploadPublicMedia(file, signEvent, {
@@ -97,7 +99,7 @@ export async function uploadPublicMedia(file, signEvent, {
// upload timeout. Any HTTP answer, even an error, means it's there.
if (i < servers.length - 1) {
try { await fetcher(server.replace(/\/$/, '') + '/upload', { method: 'HEAD', signal: AbortSignal.timeout(5000) }); }
- catch (error) { failures.push({ status: 0, reason: 'unreachable' }); continue; }
+ catch (error) { failures.push({ host: hostOf(server), status: 0, reason: 'unreachable' }); continue; }
}
try {
const init = {
@@ -116,12 +118,12 @@ export async function uploadPublicMedia(file, signEvent, {
try { body = await response.json(); } catch {}
const url = response.ok && responseUrl(body);
if (url) return mediaUrl(url, server, file);
- failures.push({ status: response.status, reason: response.headers.get('x-reason') || body?.message || '' });
+ failures.push({ host: hostOf(server), status: response.status, reason: response.headers.get('x-reason') || body?.message || '' });
} catch (error) {
- failures.push({ status: 0, reason: error?.message || '' });
+ failures.push({ host: hostOf(server), status: 0, reason: error?.message || '' });
}
}
- const details = failures.map((x) => [x.status, x.reason].filter(Boolean).join(' ')).filter(Boolean).join('; ');
+ const details = failures.map((x) => x.host + ': ' + ([x.status, x.reason].filter(Boolean).join(' ') || '?')).join('; ');
if (failures.length && failures.every((x) => x.status === 401 || x.status === 403)) throw new MediaUploadError('unauthorized', details);
if (failures.length && failures.every((x) => x.status === 413)) throw new MediaUploadError('too-big', details);
if (failures.length && failures.every((x) => x.status === 415)) throw new MediaUploadError('unsupported', details);
diff --git a/src/nostr-login.js b/src/nostr-login.js
index fe60261..3357f61 100644
--- a/src/nostr-login.js
+++ b/src/nostr-login.js
@@ -324,7 +324,7 @@ let amberWatch = null;
const amberListeners = new Set();
export const onAmberChange = (fn) => { amberListeners.add(fn); return () => amberListeners.delete(fn); };
const amberChanged = () => { for (const fn of amberListeners) { try { fn(); } catch {} } };
-export const amberPending = () => (amberReq ? { type: amberReq.type, since: amberReq.ts } : null);
+export const amberPending = () => (amberReq ? { type: amberReq.type, since: amberReq.ts, needsTap: !!amberReq.needsTap } : null);
const HEX64 = /^[0-9a-f]{64}$/i;
// What an answer of this type looks like — anything else on the clipboard
// is somebody's grocery list, not a signature.
@@ -384,7 +384,10 @@ function amberWatchClipboard() {
if (amberReq && amberDeliver(txt)) return;
} catch {} // no permission: the paste box is the way in
};
- const onVis = () => { if (document.visibilityState === 'visible') setTimeout(read, 250); };
+ const onVis = () => {
+ if (document.visibilityState === 'hidden') { if (amberReq) amberReq.hidden = true; return; } // the signer came up
+ setTimeout(read, 250);
+ };
document.addEventListener('visibilitychange', onVis);
window.addEventListener('focus', onVis);
const iv = setInterval(read, 800);
@@ -395,6 +398,35 @@ function amberLaunch(url) {
if (typeof window !== 'undefined' && typeof window.__coinosAmberLaunch === 'function') { window.__coinosAmberLaunch(url); return; } // tests
window.location.href = url;
}
+// Chrome lets a page open another app only on the heels of a tap: without
+// one the `nostrsigner:` navigation is dropped with a console warning the
+// page never sees ("Navigation is blocked"). The first request rides the
+// Sign-in tap; the ones the login fires once an answer is back (decrypt the
+// backup, sign the relay list…) have no tap behind them, so they wait for
+// one — the card shows an Open button — instead of spinning forever. A
+// launch that leaves the page in front is taken as blocked too.
+export function amberOpen() {
+ const r = amberReq;
+ if (!r) return false;
+ r.needsTap = false;
+ r.hidden = false;
+ clearTimeout(r.timer);
+ r.timer = setTimeout(() => amberCancel('signer did not answer'), r.timeoutMs);
+ amberChanged();
+ amberLaunch(r.url);
+ if (typeof window !== 'undefined' && typeof window.__coinosAmberLaunch === 'function') return true; // tests: no app to come up
+ setTimeout(() => {
+ if (amberReq !== r || r.hidden || typeof document === 'undefined' || document.visibilityState !== 'visible') return;
+ r.needsTap = true;
+ amberChanged();
+ }, 2500);
+ return true;
+}
+const amberTapAvailable = () => {
+ if (typeof window !== 'undefined' && typeof window.__coinosAmberLaunch === 'function') return true; // tests
+ const ua = typeof navigator !== 'undefined' ? navigator.userActivation : null;
+ return ua ? ua.isActive : true;
+};
// One trip at a time: the app fires several signatures at once right after a
// sign-in (the backup, the relay list, the follows), and Amber can only be
// asked for one; the rest wait their turn in this chain.
@@ -404,11 +436,11 @@ function amberRequest(type, payload, params = {}, { timeoutMs = 180_000 } = {})
if (params.pubkey) q.set('pubkey', params.pubkey);
const url = 'nostrsigner:' + encodeURIComponent(payload || '') + '?' + q.toString();
const run = () => new Promise((resolve, reject) => {
- amberReq = { type, payload: payload || '', ts: Date.now(), resolve, reject,
+ amberReq = { type, payload: payload || '', url, ts: Date.now(), resolve, reject, timeoutMs,
timer: setTimeout(() => amberCancel('signer did not answer'), timeoutMs) };
amberWatch = amberWatchClipboard();
- amberChanged();
- amberLaunch(url);
+ if (amberTapAvailable()) amberOpen();
+ else { amberReq.needsTap = true; amberChanged(); }
});
const p = amberQueue.then(run, run);
amberQueue = p.catch(() => {});
diff --git a/src/nwc-bg.js b/src/nwc-bg.js
index 3349126..ab083d9 100644
--- a/src/nwc-bg.js
+++ b/src/nwc-bg.js
@@ -57,6 +57,62 @@ export async function saveBg(walletKey, rec) {
export async function clearBg(walletKey) {
return tx('readwrite', (s) => { s.delete(walletKey); });
}
+
+// The worker's diary: what it did while the app was closed — each push, the
+// steps of a payment, every notification shown or refused. A phone stops a
+// worker without a trace, and the diary's last line says where it got to.
+// Settings → Notifications → Copy hands it to whoever is looking into it.
+// Appended line by line (a worker that dies mid-push keeps what it wrote),
+// one writer at a time, a few hundred lines kept.
+const LOG_KEY = '__log';
+const LOG_MAX = 400;
+let logChain = Promise.resolve();
+export function appendBgLog(line) {
+ logChain = logChain.then(() => tx('readwrite', async (s) => {
+ const cur = (await get(s, LOG_KEY)) || [];
+ cur.push(line);
+ s.put(cur.length > LOG_MAX ? cur.slice(-LOG_MAX) : cur, LOG_KEY);
+ })).catch(() => {});
+ return logChain;
+}
+export async function readBgLog() {
+ try { return (await tx('readonly', (s) => get(s, LOG_KEY))) || []; } catch { return []; }
+}
+export async function clearBgLog() {
+ return tx('readwrite', (s) => { s.delete(LOG_KEY); });
+}
+// A lease on the worker's wallet work, kept in this store. Two pushes seconds
+// apart ran side by side on iOS, each in its own worker (two "worker started"
+// lines), and nothing kept them apart: both finished one send, and the
+// second, over a stale copy, marked a paid send 'revoking'. The store is
+// the one thing both see, and a readwrite transaction is atomic across them.
+// A lease outlives a stopped worker only for its ttl.
+export async function takeLease(name, { ttl = 12_000, wait = 5_000 } = {}) {
+ const key = '__lease:' + name;
+ const me = Math.random().toString(36).slice(2);
+ const start = Date.now();
+ for (;;) {
+ let got = false;
+ try {
+ got = await tx('readwrite', async (s) => {
+ const cur = await get(s, key);
+ if (cur && cur.until > Date.now() && cur.owner !== me) return false;
+ s.put({ owner: me, until: Date.now() + ttl }, key);
+ return true;
+ });
+ } catch { got = true; } // no store, no lease: run
+ if (got) break;
+ if (Date.now() - start > wait) break; // a holder that overstays: go anyway
+ await new Promise((r) => setTimeout(r, 250));
+ }
+ const waited = Date.now() - start;
+ const release = () => tx('readwrite', async (s) => {
+ const cur = await get(s, key);
+ if (cur && cur.owner === me) s.delete(key);
+ }).catch(() => {});
+ return { waited, release };
+}
+
// The service worker doesn't know wallet cache keys — it finds the right
// record by the connection's service pubkey across all of them.
export async function allBgs() {
@@ -67,7 +123,8 @@ export async function allBgs() {
cur.onsuccess = () => {
const c = cur.result;
if (!c) return res(out);
- out.push({ walletKey: c.key, rec: c.value });
+ // the worker's diary shares the store under a reserved key
+ if (!(typeof c.key === 'string' && c.key.startsWith('__'))) out.push({ walletKey: c.key, rec: c.value });
c.continue();
};
cur.onerror = () => rej(cur.error);
@@ -119,7 +176,7 @@ export function buildBg({ ark, mgrState, keyFor, connections, offer, autowithdra
// worker counts what the app spent; a revoked one rides along flagged, to
// be refused rather than ignored.
connections: (connections || []).map((c) => ({
- id: c.id, servicePk: c.servicePk, serviceSk: c.serviceSk, clientPk: c.clientPk,
+ id: c.id, name: c.name || '', servicePk: c.servicePk, serviceSk: c.serviceSk, clientPk: c.clientPk,
maxSat: c.maxSat, dailySat: c.dailySat, period: c.period || 'day',
spentDate: c.spentDate || null, spentToday: c.spentToday || 0,
revoked: !!c.revoked,
diff --git a/src/nwc-lock.js b/src/nwc-lock.js
index c4fec08..bd8586a 100644
--- a/src/nwc-lock.js
+++ b/src/nwc-lock.js
@@ -7,6 +7,24 @@
// the sats had gone. Web Locks are shared by every same-origin context, so
// the first to claim a request's lock answers it and the rest stay quiet.
// Where locks are unavailable (tests, ancient engines) the caller just runs.
+// The worker's wallet work, one push at a time. Every push handler builds
+// its own manager over the one shared mirror, and two of them driving the
+// same send at once would sign it twice (a client's retry lands seconds
+// after its lookup). A waiting push keeps its waitUntil and reads the mirror
+// fresh once it gets the lock.
+// The Web Lock alone didn't hold on iOS (two workers at once, neither
+// waited), so the lease in the worker's store (nwc-bg.js) is taken inside it.
+export async function withWorkLock(fn, { lease = null } = {}) {
+ const locks = typeof navigator !== 'undefined' && navigator.locks;
+ const run = async () => {
+ if (!lease) return fn(0);
+ const l = await lease();
+ try { return await fn(l.waited); } finally { await l.release(); }
+ };
+ if (!locks) return run();
+ return locks.request('nwc-bg-work', run);
+}
+
export async function withRequestLock(id, fn, held = () => undefined) {
const locks = typeof navigator !== 'undefined' && navigator.locks;
if (!locks || !id) return fn();
diff --git a/src/nwc-respond.js b/src/nwc-respond.js
index 10692c9..0778813 100644
--- a/src/nwc-respond.js
+++ b/src/nwc-respond.js
@@ -61,10 +61,23 @@ export function shimAccount(rec) {
return { deriveChild: (chain) => ({ deriveChild: (i) => ({ privateKey: byChain(chain, i) }) }) };
}
-export async function bgManager(rec, walletKey, saveFn) {
+export async function bgManager(rec, walletKey, saveFn, log = null) {
+ // the diary follows each send's steps through the mirror's saves: a worker
+ // the phone stops mid-payment leaves its last step on record
+ const steps = new Map(((rec.mgr && rec.mgr.actions) || []).filter((a) => a.type === 'ln-pay').map((a) => [a.id, a.step]));
const storage = {
load: () => rec.mgr,
- save: (s) => { rec.mgr = s; saveFn(walletKey, rec).catch(() => {}); },
+ save: (s) => {
+ rec.mgr = s;
+ if (log) {
+ for (const a of s.actions || []) {
+ if (a.type !== 'ln-pay' || steps.get(a.id) === a.step) continue;
+ steps.set(a.id, a.step);
+ log(`ln-pay ${String(a.paymentHash || '').slice(0, 8)} → ${a.step}${a.error ? ': ' + a.error : ''}`);
+ }
+ }
+ Promise.resolve(saveFn(walletKey, rec)).catch(() => {});
+ },
};
return new ArkManager({
account: shimAccount(rec), storage,
@@ -73,6 +86,67 @@ export async function bgManager(rec, walletKey, saveFn) {
}).init();
}
+// ---- sends in flight across wakes ------------------------------------------
+// The phone stops a worker without warning: between reserving a coin and the
+// ASP's cosign, or between the ASP paying and our reply. The action stays in
+// the mirror at its last step, its coin reserved, and only the app used to
+// finish it. These let the worker finish it on a later wake instead.
+const pendingLnPays = (rec) => ((rec.mgr && rec.mgr.actions) || [])
+ .filter((a) => a.type === 'ln-pay' && !['done', 'failed'].includes(a.step));
+// which connection a send belongs to, kept beside the mirror: the action is
+// the manager's and knows nothing of NWC
+function notePending(rec, hash, conn) {
+ rec.pendingPays = (rec.pendingPays || []).filter((p) => p.hash !== hash).slice(-50);
+ rec.pendingPays.push({ hash, connId: conn.id, ts: Date.now() });
+}
+function forgetPending(rec, hash) {
+ if (rec.pendingPays) rec.pendingPays = rec.pendingPays.filter((p) => p.hash !== hash);
+}
+function connOf(rec, a) {
+ const p = (rec.pendingPays || []).find((x) => x.hash === a.paymentHash);
+ return (p && (rec.connections || []).find((c) => c.id === p.connId)) || null;
+}
+// A settled send goes on the worker's spend log once; the app absorbs it
+// into budgets and history on next open.
+function recordBgSpend(rec, a, conn, fallback = {}) {
+ const hash = a.paymentHash || fallback.paymentHash;
+ forgetPending(rec, hash);
+ rec.spends = rec.spends || [];
+ if (hash && rec.spends.some((s) => s.paymentHash === hash)) return;
+ rec.spends.push({
+ connId: conn ? conn.id : null, amountSat: a.amountSat || fallback.amountSat, feeSat: a.feeSat || 0,
+ paymentHash: hash, preimage: a.preimage, invoice: a.invoice || fallback.invoice, ts: Date.now(),
+ });
+ if (rec.spends.length > 200) rec.spends = rec.spends.slice(-200);
+}
+// Money left while the app was closed — that deserves a heads-up, unless
+// the user turned "payments sent" notifications off in Settings.
+function sentNotice(rec, a, conn, fallbackSat = 0) {
+ if (rec.prefs && rec.prefs.paySent === false) return true;
+ const paidSat = a.amountSat || fallbackSat;
+ const feeNote = a.feeSat ? ` (+${a.feeSat} fee)` : '';
+ return {
+ notify: {
+ title: 'Payment sent', tag: 'nwc-sent',
+ body: `-${paidSat.toLocaleString()} sats${feeNote} via ${(conn && conn.name) || 'a connected app'}`,
+ },
+ };
+}
+// Drive a Lightning send on until it settles, fails, or the budget is gone.
+// Every step is held to the deadline: a call to the ASP that hangs must not
+// carry the worker past its budget (iOS stops it, mid-line, with no trace).
+async function finishLnPay(mgr, id, deadline) {
+ const by = (p) => Promise.race([p, new Promise((r) => setTimeout(r, Math.max(0, deadline - Date.now())))]);
+ let a = await by(mgr.awaitLnPay(id, Math.max(500, deadline - Date.now())).catch(() => null));
+ a = mgr.lnAction(id);
+ while (a && !['done', 'failed'].includes(a.step) && Date.now() < deadline - 1500) {
+ await new Promise((r) => setTimeout(r, 1000));
+ await by(mgr.driveLn(id).catch(() => {}));
+ a = mgr.lnAction(id);
+ }
+ return a;
+}
+
// A CLINK offer request (kind 21001): mint an invoice against the mirrored
// wallet and reply. The payment itself arrives later over the ASP's hold
// invoice — the app claims it on next open, so we also ask the caller to
@@ -128,7 +202,7 @@ async function respondOffer(ev, rec, walletKey, { notifier, fetchFn, saveFn, log
// left to another device); false means "wake the user instead".
export async function respondFromBg(data, {
notifier, fetchFn = fetch, recordsFn = allBgs, saveFn = saveBg, log = () => {},
- errGraceMs = 3000,
+ errGraceMs = 3000, deadline: until = null,
} = {}) {
const ev = data && data.event;
if (!ev || !ev.id || !ev.pubkey) return false;
@@ -176,6 +250,9 @@ export async function respondFromBg(data, {
try { req = JSON.parse(await decrypt(scheme, conn.serviceSk, ev.pubkey, ev.content)); } catch { return false; }
const method = req?.method;
const params = req?.params || {};
+ // the push's budget (on iOS about ten seconds from the push, not thirty)
+ const deadline = until || Date.now() + PAY_WAIT_MS;
+ let lookupNotice = null;
// Revoked, lately: refuse out loud — a silent worker looks like a phone
// that is off, which is the one thing the other app cannot tell apart.
if (conn.revoked) {
@@ -252,23 +329,47 @@ export async function respondFromBg(data, {
await publish(errRes('lookup_invoice', 'OTHER', 'payment_hash or invoice required'));
return true;
}
- if (!rec.mgr) return false;
const q = { paymentHash: params.payment_hash, invoice: params.invoice };
- // read straight off the mirror; the ASP is only needed to claim
- const view = Object.assign(Object.create(ArkManager.prototype), { state: rec.mgr, account: shimAccount(rec) });
- let tx = view.lnLookup(q);
- const a = tx && tx.state === 'pending' && tx.type === 'incoming'
- && (rec.mgr.actions || []).find((x) => x.type === 'ln-recv' && x.paymentHash === tx.payment_hash);
+ // read straight off the mirror; the ASP is only needed to claim. Every
+ // copy of the connection is asked (the freshest may be another network's
+ // mirror: PullCap's lookups of a send in flight came back "not found").
+ let tx = null;
+ for (const m of matches) {
+ if (!m.rec.mgr) continue;
+ const view = Object.assign(Object.create(ArkManager.prototype), { state: m.rec.mgr, account: shimAccount(m.rec) });
+ tx = view.lnLookup(q);
+ if (tx) { ({ walletKey, rec, conn } = m); break; }
+ }
+ if (!tx && !rec.mgr) return false;
+ // a payment of ours still on its way (incoming: claim it; outgoing: a
+ // send an earlier wake began — drive it on, so the lookup itself can
+ // answer 'settled' with the preimage instead of a second pay request)
+ const a = tx && tx.state === 'pending'
+ && (rec.mgr.actions || []).find((x) => x.type === (tx.type === 'incoming' ? 'ln-recv' : 'ln-pay') && x.paymentHash === tx.payment_hash
+ && !['done', 'failed'].includes(x.step));
if (a) {
try {
- const mgr = await bgManager(rec, walletKey, saveFn);
- await Promise.race([mgr.driveLn(a.id).catch((e) => log('claim: ' + e.message)), new Promise((r) => setTimeout(r, PAY_WAIT_MS))]);
+ const mgr = await bgManager(rec, walletKey, saveFn, log);
+ if (a.type === 'ln-pay') {
+ const r = await finishLnPay(mgr, a.id, Math.min(deadline, Date.now() + 6000));
+ if (r && r.step === 'done') {
+ const c = connOf(rec, r) || conn;
+ recordBgSpend(rec, r, c);
+ log(`finished a ${r.amountSat} sat send from an earlier wake`);
+ const n = sentNotice(rec, r, c);
+ if (n !== true) lookupNotice = n.notify;
+ } else if (r && r.step === 'failed') forgetPending(rec, a.paymentHash);
+ await saveFn(walletKey, rec);
+ } else {
+ await Promise.race([mgr.driveLn(a.id).catch((e) => log('claim: ' + e.message)), new Promise((r) => setTimeout(r, Math.max(0, deadline - Date.now())))]);
+ }
tx = mgr.lnLookup(q);
- if (tx.state === 'settled') log(`received ${tx.amount / 1000} sat while closed`);
+ if (tx.state === 'settled' && tx.type === 'incoming') log(`received ${tx.amount / 1000} sat while closed`);
} catch (e) { log('ark init failed: ' + e.message); }
}
await publish(tx ? { result_type: 'lookup_invoice', result: tx } : errRes('lookup_invoice', 'NOT_FOUND', 'invoice not found'));
- return true;
+ log(`lookup: ${tx ? tx.type + ' ' + tx.state : 'not found'}`);
+ return lookupNotice ? { notify: lookupNotice } : true;
}
if (method === 'get_balance') {
await publish({ result_type: 'get_balance', result: { balance: spendableSat(rec) * 1000 } });
@@ -333,17 +434,22 @@ export async function respondFromBg(data, {
await publish(errRes('pay_invoice', 'QUOTA_EXCEEDED', `over the remaining ${renewalPeriod(conn.period)} budget (${left} sat)`));
return true;
}
- if (spendableSat(rec) < dec.amountSat) return false; // stale/empty mirror: wake the user
-
- // The ASP's own Lightning send, over the mirrored state. Change and HTLC
- // outputs allocate from nextKeyIndex, which must stay inside the key
- // window the app pre-derived; if it ran out, wake the user instead.
- if (!rec.keys[String(rec.mgr.nextKeyIndex || 1)]) { log('key window exhausted'); return false; }
- let mgr;
- try {
- mgr = await bgManager(rec, walletKey, saveFn);
- } catch (e) { log('ark init failed: ' + e.message); return false; }
-
+ // A send this worker began on an earlier wake and never finished (PullCap's
+ // night of 2026-10-23: three hours of fifteen). Its coin sat reserved in
+ // the mirror, so a fresh attempt at the SAME invoice was refused as
+ // "already paid or is being paid" — which the client read as paid, hours
+ // before the money moved — and one at any OTHER invoice found no spendable
+ // coin and woke the user. Finish what was begun first: the same invoice
+ // gets that payment's outcome, another invoice gets the coin back.
+ const stuck = pendingLnPays(rec);
+ const same = stuck.find((a) => a.paymentHash === dec.paymentHash)
+ || (rec.mgr.actions || []).find((a) => a.type === 'ln-pay' && a.paymentHash === dec.paymentHash && a.step === 'done');
+ let mgr = null;
+ let mgrP = null;
+ const ready = async () => mgr || (mgr = await (mgrP || (mgrP = bgManager(rec, walletKey, saveFn, log))));
+ // the manager's start (the ASP's info, the chain tip) runs while the
+ // notifier is asked whether anyone else answered
+ ready().catch(() => {});
// A local failure carries no urgency — wait out the grace period and
// re-check before publishing, so a sibling device's slower SUCCESS reply
// wins the client's eyes instead of being shouted over.
@@ -354,22 +460,81 @@ export async function respondFromBg(data, {
}
return true;
};
+ const settled = async (a, c, { record = true } = {}) => {
+ if (record) recordBgSpend(rec, a, c, { paymentHash: dec.paymentHash, amountSat: dec.amountSat, invoice });
+ // the mirror and the reply at once: every second counts on iOS, and the
+ // "Payment sent" line comes after both
+ await Promise.all([
+ saveFn(walletKey, rec),
+ publish({ result_type: 'pay_invoice', result: { preimage: a.preimage, fees_paid: (a.feeSat || 0) * 1000 } }).then(() => log('reply sent')),
+ ]);
+ return sentNotice(rec, a, c, dec.amountSat);
+ };
+ if (same) {
+ if (!(await claim())) { log('another device claimed this request — standing down'); return true; }
+ log(`a send for this invoice is already ${same.step} — finishing it`);
+ const wasDone = same.step === 'done';
+ let a = same;
+ if (!wasDone) {
+ try { await ready(); } catch (e) { log('ark init failed: ' + e.message); return false; }
+ a = await finishLnPay(mgr, same.id, deadline);
+ }
+ // settled earlier (by the app, perhaps): its preimage again, nothing new
+ // on the spend log
+ if (a && a.step === 'done') return settled(a, conn, { record: !wasDone });
+ if (a && a.step === 'failed') { forgetPending(rec, dec.paymentHash); return failQuietly(a.error || 'payment failed'); }
+ log('that send is still in flight — waking the user to finish it');
+ return false;
+ }
+ const notices = [];
+ // Only when they hold the coins this payment needs: otherwise the answer
+ // comes first and the wake's tending finishes them after.
+ if (stuck.length && spendableSat(rec) < dec.amountSat) {
+ try {
+ await ready();
+ for (const a of stuck) {
+ if (Date.now() > deadline - 4000) break;
+ const r = await finishLnPay(mgr, a.id, Math.min(deadline - 3000, Date.now() + 5000));
+ if (!r || r.step !== 'done') {
+ log(`ln-pay ${String(a.paymentHash || '').slice(0, 8)} from an earlier wake is still ${r ? r.step : 'gone'}`);
+ if (r && r.step === 'failed') forgetPending(rec, a.paymentHash);
+ continue;
+ }
+ const c = connOf(rec, r);
+ recordBgSpend(rec, r, c);
+ log(`finished a ${r.amountSat} sat send from an earlier wake`);
+ const n = sentNotice(rec, r, c);
+ if (n !== true) notices.push(n.notify);
+ }
+ await saveFn(walletKey, rec);
+ } catch (e) { log('ark init failed: ' + e.message); }
+ }
+ const withNotices = (out) => (notices.length && out ? { ...(out === true ? {} : out), notices } : out);
+
+ const spendable = spendableSat(rec);
+ if (spendable < dec.amountSat) { log(`${spendable} sat spendable in the mirror, ${dec.amountSat} asked — waking the user`); return false; }
+
+ // The ASP's own Lightning send, over the mirrored state. Change and HTLC
+ // outputs allocate from nextKeyIndex, which must stay inside the key
+ // window the app pre-derived; if it ran out, wake the user instead.
+ if (!rec.keys[String(rec.mgr.nextKeyIndex || 1)]) { log('key window exhausted'); return false; }
+ try { await ready(); } catch (e) { log('ark init failed: ' + e.message); return false; }
+
if (!(await claim())) { log('another device claimed this request — standing down'); return true; }
- const deadline = Date.now() + PAY_WAIT_MS;
+ // whose send this is, for the wake that finishes it should this one not
+ notePending(rec, dec.paymentHash, conn);
+ await saveFn(walletKey, rec);
+ log(`paying ${dec.amountSat} sat`);
let a = null;
for (let attempt = 0; ; attempt++) {
let id;
try {
id = await mgr.payLnInvoice(invoice);
} catch (e) {
+ forgetPending(rec, dec.paymentHash);
return failQuietly(e.message);
}
- a = await mgr.awaitLnPay(id, Math.max(1000, deadline - Date.now())).catch(() => mgr.lnAction(id));
- while (a && !['done', 'failed'].includes(a.step) && Date.now() < deadline) {
- await new Promise((r) => setTimeout(r, 1500));
- await mgr.driveLn(id).catch(() => {});
- a = mgr.lnAction(id);
- }
+ a = await finishLnPay(mgr, id, deadline);
// A ghost coin (spent elsewhere, this mirror never learned) dies on the
// launchpad in milliseconds. Reconcile against the server — flipping the
// ghost — and retry once from live coins; the budget has barely started.
@@ -384,6 +549,7 @@ export async function respondFromBg(data, {
// Another device of this wallet started this same payment first. Its
// outcome is ours: wait on it, and only speak if the payer stays quiet.
log('a sibling device is paying this invoice — waiting on its outcome');
+ forgetPending(rec, dec.paymentHash);
const out = await mgr.lnOutcome(dec.paymentHash, Math.max(3000, deadline - Date.now()));
if (out.status === 'failed') return failQuietly(a.error);
if (out.status !== 'success') { log('sibling payment still pending — leaving it to them'); return true; }
@@ -394,38 +560,50 @@ export async function respondFromBg(data, {
return true;
}
if (!a || a.step === 'failed') {
+ forgetPending(rec, dec.paymentHash);
return failQuietly((a && a.error) || 'payment failed');
}
if (a.step !== 'done') {
- // still in flight as our budget runs out: the app resumes it from the
- // mirrored state on next open — wake the user rather than guess.
+ // still in flight as our budget runs out: the next wake (or the app, on
+ // open) finishes it — wake the user rather than guess.
log('payment still pending at SW deadline');
return false;
}
-
- rec.spends = rec.spends || [];
- rec.spends.push({
- connId: conn.id, amountSat: a.amountSat || dec.amountSat, feeSat: a.feeSat || 0,
- paymentHash: dec.paymentHash, preimage: a.preimage, invoice, ts: Date.now(),
- });
- if (rec.spends.length > 200) rec.spends = rec.spends.slice(-200);
- await saveFn(walletKey, rec);
- await publish({
- result_type: 'pay_invoice',
- result: { preimage: a.preimage, fees_paid: (a.feeSat || 0) * 1000 },
- });
log(`paid ${a.amountSat || dec.amountSat} sat via the ASP from the background mirror`);
- // Money left while the app was closed — that deserves a heads-up, unless
- // the user turned "payments sent" notifications off in Settings.
- if (rec.prefs && rec.prefs.paySent === false) return true;
- const paidSat = a.amountSat || dec.amountSat;
- const feeNote = a.feeSat ? ` (+${a.feeSat} fee)` : '';
- return {
- notify: {
- title: 'Payment sent', tag: 'nwc-sent',
- body: `-${paidSat.toLocaleString()} sats${feeNote} via ${conn.name || 'a connected app'}`,
- },
- };
+ return withNotices(await settled(a, conn));
+}
+
+// Sends begun on an earlier wake and never finished (see pay_invoice): any
+// wake drives each on, within its budget, and hands back the "Payment sent"
+// lines for the ones that settle. Without this a stuck send waited for the
+// app to open, its coin reserved all the while.
+export async function tendLnPays({ recordsFn = allBgs, saveFn = saveBg, log = () => {}, deadline = Date.now() + 8000 } = {}) {
+ const notices = [];
+ for (const { walletKey, rec } of await recordsFn()) {
+ if (!rec || rec.v < 3 || !rec.mgr || !rec.ark) continue;
+ const stuck = pendingLnPays(rec);
+ if (!stuck.length || Date.now() > deadline - 3000) continue;
+ try {
+ const mgr = await Promise.race([bgManager(rec, walletKey, saveFn, log),
+ new Promise((_, rej) => setTimeout(() => rej(new Error('out of time')), Math.max(0, deadline - Date.now())))]);
+ for (const a of stuck) {
+ if (Date.now() > deadline - 3000) break;
+ const r = await finishLnPay(mgr, a.id, deadline);
+ if (!r || r.step !== 'done') {
+ log(`ln-pay ${String(a.paymentHash || '').slice(0, 8)} from an earlier wake is still ${r ? r.step : 'gone'}`);
+ if (r && r.step === 'failed') forgetPending(rec, a.paymentHash);
+ continue;
+ }
+ const c = connOf(rec, r);
+ recordBgSpend(rec, r, c);
+ log(`finished a ${r.amountSat} sat send from an earlier wake`);
+ const n = sentNotice(rec, r, c);
+ if (n !== true) notices.push(n.notify);
+ }
+ await saveFn(walletKey, rec);
+ } catch (e) { log('earlier sends: ' + e.message); }
+ }
+ return notices;
}
// Renewals while the app is closed. The app registers a standing order with
diff --git a/src/style.css b/src/style.css
index 275bb59..bf61f6a 100644
--- a/src/style.css
+++ b/src/style.css
@@ -359,6 +359,10 @@ textarea.send-dest::placeholder { font-family: var(--sans); }
/* ---- lists (tx / utxo) ---- */
.list { display: flex; flex-direction: column; }
.item { display: flex; align-items: center; gap: 12px; padding: 13px 2px; border-top: 1px solid var(--line); }
+/* the middle column may shrink: a long name chip beside the label then
+ ellipsizes on one line instead of breaking mid-name and pushing the
+ amount about */
+.item > .grow { min-width: 0; }
.item:first-child { border-top: 0; }
.ico { width: 34px; height: 34px; border-radius: 9px; flex: none; display: grid; place-items: center; font-size: 16px; }
.ico.in { background: var(--green-soft); color: var(--green); }
@@ -366,7 +370,7 @@ textarea.send-dest::placeholder { font-family: var(--sans); }
.amount-pos { color: var(--green); font-family: var(--mono); font-weight: 600; }
.amount-neg { color: var(--red); font-family: var(--mono); font-weight: 600; }
.amount { font-family: var(--mono); font-weight: 600; }
-.tag { font-size: 11px; font-weight: 700; padding: 2px 7px; border-radius: 6px; }
+.tag { font-size: 11px; font-weight: 700; padding: 2px 7px; border-radius: 6px; white-space: nowrap; flex: none; }
.tag.pending { background: var(--accent-soft); color: var(--accent-ink); }
.tag.conf { background: var(--green-soft); color: var(--green); }
@@ -847,11 +851,29 @@ html.no-scroll { overflow: hidden; scrollbar-gutter: auto; }
}
.lightbox-x:hover { background: rgba(255, 255, 255, .24); }
@keyframes lightbox-in { from { opacity: 0; } to { opacity: 1; } }
-.note-video { display: block; width: 100%; height: auto; max-height: 100vh; object-fit: contain; border-radius: 10px; margin-top: 6px; background: #000; }
+.note-video { display: block; width: 100%; height: auto; max-height: var(--vid-cap); object-fit: contain; border-radius: 10px; margin-top: 6px; background: #000; }
/* a video plays by itself, muted, while it is on screen; the corner button
turns the sound on (see autoplay in messages.js) */
.note-video-box { position: relative; display: block; max-width: 100%; margin-top: 6px; }
.note-video-box .note-video { margin-top: 0; }
+/* the height a feed clip may take: the whole screen on a phone, three
+ quarters of it on a computer (a portrait clip on a 1920 screen ran off it) */
+:root { --vid-cap: 100vh; }
+@media (min-width: 900px) { :root { --vid-cap: 75vh; } }
+/* with a mouse: the big play/pause in the middle, while the pointer is over the clip */
+.vid-pp {
+ position: absolute; left: 50%; top: 50%; z-index: 2; width: 64px; height: 64px; margin: -32px 0 0 -32px; padding: 0;
+ border: 0; border-radius: 50%; background: rgba(18, 18, 18, .6); color: #fff; cursor: pointer;
+ display: none; align-items: center; justify-content: center;
+}
+.vid-pp:hover { background: rgba(18, 18, 18, .85); }
+.vid-pp-i { width: 0; height: 0; margin-left: 5px; border-style: solid; border-width: 13px 0 13px 22px; border-color: transparent transparent transparent #fff; }
+.vid-pp.playing .vid-pp-i { width: 20px; height: 24px; margin: 0; border-width: 0 7px; border-color: #fff; }
+.has-mouse .note-video-box:hover .vid-pp, .vid-pp:focus-visible { display: flex; }
+/* the moments bar is the clip's only seek bar: the middle button is its play
+ control on a touch screen too, up whenever the clip is paused */
+.note-video-box.own-bar .vid-pp:not(.playing) { display: flex; }
+.note-video-box:has(.vid-heavy) .vid-pp { display: none; }
.vid-sound {
position: absolute; top: 8px; left: 8px; z-index: 2; margin: 0; padding: 4px 10px; border: 0;
border-radius: 999px; background: rgba(18, 18, 18, .7); color: #fff; font-size: 13px; line-height: 1.3;
@@ -929,6 +951,23 @@ html.no-scroll { overflow: hidden; scrollbar-gutter: auto; }
.live-line-body { min-width: 0; overflow-wrap: anywhere; white-space: pre-wrap; line-height: 1.35; }
.live-zap .live-line-body b { color: var(--accent); }
.live-chat .chat-row { padding-right: 2px; }
+/* on phones the stream is the page, the way Nostrich lays one out: the
+ picture runs edge to edge and the chat under it is a plain full-width
+ list of lines, no bubbles — the card walls step outside #app's padding */
+@media (max-width: 520px) {
+ .live-page > .card {
+ margin-left: -16px; margin-right: -16px; padding: 10px 0 12px;
+ border-left: none; border-right: none; border-radius: 0; box-shadow: none;
+ }
+ .live-page > .live-chat-card { margin-top: 0; padding-top: 6px; border-top: none; }
+ .live-page > .card > :not(.live-player, .live-chat) { margin-left: 14px; margin-right: 14px; }
+ .live-page .live-player { border-radius: 0; }
+ .live-page .live-chat { padding: 10px 14px 0; max-height: 60vh; }
+ .live-page .live-title { font-size: 17px; }
+ .live-chat .chat-row { gap: 10px; }
+ .live-chat .chat-bubble { display: block; background: transparent; border: 0; border-radius: 0; padding: 0; font-size: 15px; }
+ .live-chat .chat-quote { margin-bottom: 2px; }
+}
.bc-preview.mirror { transform: scaleX(-1); }
.bc-bar .bc-clock { font-variant-numeric: tabular-nums; font-weight: 650; }
.go-live-dot { display: inline-block; width: 10px; height: 10px; border-radius: 50%; background: #e0245e; box-shadow: 0 0 0 3px rgba(224, 36, 94, .25); }
@@ -1180,7 +1219,8 @@ html.no-scroll { overflow: hidden; scrollbar-gutter: auto; }
.profile-banner + .row .profile-avatar {
border: 3px solid var(--paper); box-sizing: content-box;
}
-.zap-chip { display: inline-flex; gap: 5px; align-items: center; cursor: pointer; background: var(--surface2); border: 1px solid var(--line); border-radius: 999px; padding: 1px 8px 1px 2px; }
+.zap-chip { display: inline-flex; gap: 5px; align-items: center; cursor: pointer; background: var(--surface2); border: 1px solid var(--line); border-radius: 999px; padding: 1px 8px 1px 2px; min-width: 0; max-width: 100%; }
+.zap-chip > span { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
.chat-avatar.mini { width: 18px; height: 18px; font-size: 8px; flex-shrink: 0; }
/* A feed row is the one place a face is the point, not a label on a line —
Amethyst gives it 55dp; at our 30px it read as a bullet beside the post.
@@ -1978,7 +2018,8 @@ html:has(.call-overlay:not(.call-min)) { overflow: hidden; scrollbar-gutter: aut
/* A post's audio/video timeline: the waveform (audio), and what was said,
reacted or zapped at a moment, sitting over the bar at that moment. */
-.media-timeline { padding: 24px 0 8px; white-space: normal; color: var(--text); }
+.media-timeline { padding: 8px 0; white-space: normal; color: var(--text); }
+.note-video-box .media-timeline:not(.has-marks) { display: none; }
.media-time { font-variant-numeric: tabular-nums; }
.media-seek { position: relative; height: 42px; --played: 0%; }
.media-wave { position: absolute; inset: 3px 0; display: flex; align-items: center; gap: 2px;
@@ -1989,12 +2030,20 @@ html:has(.call-overlay:not(.call-min)) { overflow: hidden; scrollbar-gutter: aut
.has-wave .media-wave::after { content: ''; position: absolute; inset: 0 0 0 var(--played); background: var(--bg, #fff); opacity: .55; pointer-events: none; }
.media-seek input { position: absolute; inset: 0; width: 100%; height: 100%; margin: 0; opacity: .01; cursor: pointer; }
.media-seek:focus-within { outline: 2px solid var(--accent); outline-offset: 2px; border-radius: 4px; }
-.media-marks { position: absolute; left: 0; right: 0; top: -22px; height: 22px; pointer-events: none; }
+/* the marks hang just under the line, at their moment (a plain bar: inside
+ its touch strip); under a waveform, below it */
+.media-marks { position: absolute; left: 0; right: 0; top: 24px; height: 18px; pointer-events: none; }
+.has-wave .media-marks { top: 100%; height: 22px; }
+.media-seek.has-wave:has(.media-mark) { margin-bottom: 22px; }
+.media-mark { bottom: auto; top: 0; }
.media-mark, .mp-mark {
position: absolute; bottom: 0; transform: translateX(-50%); padding: 0 2px; margin: 0; border: 0; background: none;
font-size: 16px; line-height: 1; cursor: pointer; pointer-events: auto;
}
.media-mark .cemoji, .mp-mark .cemoji { width: 20px; height: 20px; vertical-align: bottom; }
+.media-mark-face { display: block; width: 20px !important; height: 20px !important; min-width: 0; font-size: 8px; border-radius: 50%; }
+.mp-mark .media-mark-face { width: 26px !important; height: 26px !important; box-shadow: 0 0 0 1.5px #fff; }
+.mp-pop .media-mark-face { width: 36px !important; height: 36px !important; box-shadow: 0 0 0 2px #fff; }
/* the pager's: above its seek bar, there when the bar is */
.mp-marks { position: absolute; left: 0; right: 0; bottom: 10px; height: 26px; pointer-events: none; }
.mp-mark { font-size: 20px; filter: drop-shadow(0 1px 2px rgba(0, 0, 0, .6)); }
@@ -2016,8 +2065,22 @@ html:has(.call-overlay:not(.call-min)) { overflow: hidden; scrollbar-gutter: aut
}
@media (prefers-reduced-motion: reduce) { .mp-pop { animation: none; opacity: 0; } }
+/* a timed comment's time: a chip that plays the clip from there */
+.media-time-link { display: inline-flex; align-items: center; margin-right: 6px; padding: 1px 8px; border-radius: 999px;
+ background: var(--accent-soft); color: var(--accent); font-size: .85em; font-weight: 650; font-variant-numeric: tabular-nums;
+ text-decoration: none; vertical-align: 1px; white-space: nowrap; }
+.media-time-link:hover { background: color-mix(in srgb, var(--accent) 22%, transparent); }
.media-moment-detail { overflow-wrap: anywhere; max-height: 72px; overflow-y: auto; margin-top: 5px; }
.media-moment-detail:empty { display: none; }
.live-watching.has-who { cursor: pointer; text-decoration: underline dotted; text-underline-offset: 3px; }
.live-who { display: flex; flex-wrap: wrap; gap: 6px; }
.live-who-p { display: inline-flex; align-items: center; gap: 6px; padding: 3px 10px 3px 3px; border-radius: 999px; background: var(--bg2, rgba(127,127,127,.12)); border: 0; color: inherit; cursor: pointer; }
+
+/* a gift's note: the sender's words above the amount, and the field for them */
+.gift-note {
+ margin: 0; padding: 8px 12px; max-width: 100%;
+ border-left: 3px solid var(--accent); border-radius: 4px;
+ background: color-mix(in srgb, var(--accent) 8%, transparent);
+ font-style: italic; text-align: left; white-space: pre-wrap; overflow-wrap: anywhere;
+}
+.gift-note-input { width: 100%; min-height: 0; font-family: var(--sans); }
diff --git a/src/sw-nwc.js b/src/sw-nwc.js
index dbd2d98..3a48cff 100644
--- a/src/sw-nwc.js
+++ b/src/sw-nwc.js
@@ -4,12 +4,18 @@
// nwc-respond.js), and only falls back to the wake-the-user notification
// when it can't.
-import { respondFromBg, tendRenewals } from './nwc-respond.js';
-import { withRequestLock } from './nwc-lock.js';
+import { respondFromBg, tendRenewals, tendLnPays } from './nwc-respond.js';
+import { withRequestLock, withWorkLock } from './nwc-lock.js';
+import { appendBgLog, takeLease } from './nwc-bg.js';
import { bgAutoWithdraw } from './bg-autowithdraw.js';
import { allInboxes, classifyDm, shouldNotifyDm, classifyCall } from './dm-inbox.js';
const NOTIFIER = 'https://nwcpush.coinos.io';
+// The worker's diary (nwc-bg.js): every line also lands in IndexedDB as it is
+// written, so a worker the phone stops mid-push leaves its last step behind.
+const stamp = () => new Date().toISOString().replace('T', ' ').slice(0, 19);
+const diary = (m) => { console.log('[sw-nwc]', m); appendBgLog(`${stamp()} ${m}`); };
+diary(`worker started${typeof navigator !== 'undefined' && navigator.locks ? '' : ' (no Web Locks)'}`);
const CALL_CACHE = 'coinos-call'; // a call offer a push brought, for the app the tap opens
// where a call's offer wrap is fetched from: the notifier, or (the app served
// on this machine, as the tests do) this origin
@@ -29,7 +35,7 @@ async function applePush() {
} catch (_) { return false; }
}
async function standIn(visible) {
- if (!(await applePush())) return;
+ if (!(await applePush())) return false;
await self.registration.showNotification('Coinos', {
body: 'Your wallet checked in.', icon: 'icon-192.png', badge: 'badge-96.png',
tag: 'coinos-bg', renotify: false, silent: true, data: { url: './' },
@@ -38,6 +44,7 @@ async function standIn(visible) {
const open = await self.registration.getNotifications({ tag: 'coinos-bg' }).catch(() => []);
for (const n of open) n.close();
}
+ return true;
}
self.addEventListener('push', (e) => {
@@ -45,7 +52,18 @@ self.addEventListener('push', (e) => {
try { data = e.data ? e.data.json() : {}; } catch (_) {}
// every path below ends in a notification or, failing that, the stand-in
let showed = false;
- const show = (title, opts) => { showed = true; return self.registration.showNotification(title, opts); };
+ // A notification the platform refuses must not count as shown: the old
+ // code flagged it before the call, so a refusal left the push with no line
+ // at all — a silent push, on iOS a strike towards losing the subscription.
+ // (PullCap's night of 2026-10-22: paid four times, no "Payment sent" seen.)
+ // Try the full options; refused, try again with the plainest ones.
+ const show = async (title, opts) => {
+ try { await self.registration.showNotification(title, opts); showed = true; diary(`notification shown: ${title}`); return; }
+ catch (e) { diary(`notification refused (${title}): ${e && e.message}`); }
+ try { await self.registration.showNotification(title, { body: opts && opts.body, tag: opts && opts.tag, data: opts && opts.data }); showed = true; diary(`plain notification shown: ${title}`); }
+ catch (e) { diary(`plain notification refused too (${title}): ${e && e.message}`); }
+ };
+ diary(`push ${data.type || '?'}${data.reason ? '/' + data.reason : ''}${data.event && data.event.id ? ' ' + data.event.id.slice(0, 8) : ''}`);
// the stand-in, as soon as a path knows it has nothing to say (a long tail
// of work after it mustn't keep the push waiting for its notification)
const quiet = async () => {
@@ -161,11 +179,16 @@ self.addEventListener('push', (e) => {
// four payments, no line for the fourth, then no more wakes). On an
// Apple endpoint the stand-in goes up FIRST; the outcome replaces it.
const apple = await applePush();
+ // What a push may take. iOS stops the worker about ten seconds in (PullCap's
+ // diary of 2026-10-24: every wake's last line 8–12 s after its push, in the
+ // middle of a payment), whatever the waitUntil — so there everything is
+ // planned inside nine; elsewhere the usual thirty.
+ const budgetEnd = startedAt + (apple ? 9_000 : 27_000);
const dropStandIn = async () => {
const open = await self.registration.getNotifications({ tag: 'coinos-bg' }).catch(() => []);
for (const n of open) n.close();
};
- if (apple) { showed = true; await standIn(false).catch(() => {}); }
+ if (apple && await standIn(false).catch((e) => { diary('stand-in refused: ' + (e && e.message)); return false; })) { showed = true; diary('stand-in shown'); }
// An open window handles requests itself with full wallet state — nudge
// it and stay out of the way. On iOS only one on screen counts: a
// backgrounded app is suspended, so a nudge to it went unanswered.
@@ -174,49 +197,75 @@ self.addEventListener('push', (e) => {
if (clients.length) {
for (const c of clients) c.postMessage({ type: 'nwc-wake', servicePubkey: data.servicePubkey });
if (apple) await dropStandIn(); // the window on screen shows it live
+ diary('window on screen — handed over');
return;
}
+ const notice = (n) => show(n.title, {
+ body: n.body, icon: 'icon-192.png', badge: 'badge-96.png',
+ tag: n.tag || 'nwc-incoming', renotify: !apple, data: { url: './' },
+ });
// A wake is the only moment a closed wallet gets to look after its coins:
- // claim renewals whose round has run, cover coins without one. After the
- // answer, inside what is left of the push budget.
- const tend = () => tendRenewals({ deadline: startedAt + 27_000, log: (m) => console.log('[sw-renew]', m) })
- .catch((err) => console.warn('[sw-renew] failed:', err && err.message));
+ // finish sends an earlier wake left in flight, claim renewals whose round
+ // has run, cover coins without one. After the answer, inside what is
+ // left of the push budget.
+ const tend = async () => {
+ const late = await tendLnPays({ deadline: budgetEnd, log: diary }).catch((err) => { diary('earlier sends failed: ' + (err && err.message)); return []; });
+ for (const n of late) await notice(n);
+ if (late.length && apple) await dropStandIn();
+ await tendRenewals({ deadline: budgetEnd, log: (m) => diary('renew: ' + m) })
+ .catch((err) => diary('renewals failed: ' + (err && err.message)));
+ };
// an NWC wake-up may also have moved money in; check the rule after
setTimeout(() => { bgAutoWithdraw({ log: (m) => console.log('[sw-aw]', m) }).catch(() => {}); }, 0);
- let handled = false;
- try {
- handled = await withRequestLock(data.event && data.event.id,
- () => respondFromBg(data, { notifier: NOTIFIER, log: (m) => console.log('[sw-nwc]', m) }),
- () => { console.log('[sw-nwc] another context holds this request'); return true; });
- } catch (err) {
- console.warn('[sw-nwc] auto-answer failed:', err && err.message);
- }
- // handled-with-a-heads-up: e.g. an invoice was minted while closed and
- // the user should open coinos to complete the receive
- if (handled && handled.notify) {
- await show(handled.notify.title, {
- body: handled.notify.body,
+ // one push at a time over the shared mirror (a client's retry lands
+ // seconds after its lookup, and each push builds its own manager)
+ await withWorkLock(async () => {
+ const waited = Date.now() - startedAt;
+ if (waited > 500) diary(`waited ${waited} ms for an earlier push to finish`);
+ if (Date.now() > budgetEnd - 2_000) { diary('no time left after waiting — leaving it to the next try'); return; }
+ let handled = false;
+ try {
+ handled = await withRequestLock(data.event && data.event.id,
+ () => respondFromBg(data, { notifier: NOTIFIER, log: diary, deadline: budgetEnd }),
+ () => { diary('another context holds this request'); return true; });
+ } catch (err) {
+ diary('auto-answer failed: ' + (err && err.message));
+ }
+ // sends from an earlier wake that settled on the way to this answer
+ const late = (handled && handled.notices) || [];
+ for (const n of late) await notice(n);
+ // handled-with-a-heads-up: e.g. an invoice was minted while closed and
+ // the user should open coinos to complete the receive
+ if (handled && handled.notify) {
+ await notice(handled.notify);
+ if (apple) await dropStandIn();
+ await tend();
+ return;
+ }
+ if (handled) {
+ if (late.length && apple) await dropStandIn();
+ diary('answered quietly');
+ await quiet();
+ await tend();
+ return;
+ }
+ if (Date.now() > budgetEnd) { diary('out of time — leaving it to the next try'); return; }
+ // A kind-21001 offer request is money coming IN (someone asking us to
+ // mint an invoice) — "an app wants to pay" would read as the opposite.
+ const incoming = data.event && data.event.kind === 21001;
+ diary(incoming ? 'waking the user: incoming payment' : 'waking the user: payment request');
+ await show(incoming ? 'Incoming payment' : 'Payment request', {
+ body: incoming
+ ? 'Someone is trying to send you money. Open coinos so your wallet can receive it.'
+ : 'An app is asking your wallet to pay. Open Coinos to approve.',
icon: 'icon-192.png', badge: 'badge-96.png',
- tag: handled.notify.tag || 'nwc-incoming', renotify: true,
+ tag: 'nwc-' + (data.servicePubkey || 'req'), renotify: false,
data: { url: './' },
});
if (apple) await dropStandIn();
await tend();
- return;
- }
- if (handled) { await quiet(); await tend(); return; }
- // A kind-21001 offer request is money coming IN (someone asking us to
- // mint an invoice) — "an app wants to pay" would read as the opposite.
- const incoming = data.event && data.event.kind === 21001;
- await show(incoming ? 'Incoming payment' : 'Payment request', {
- body: incoming
- ? 'Someone is trying to send you money. Open coinos so your wallet can receive it.'
- : 'An app is asking your wallet to pay. Open Coinos to approve.',
- icon: 'icon-192.png', badge: 'badge-96.png',
- tag: 'nwc-' + (data.servicePubkey || 'req'), renotify: false,
- data: { url: './' },
- });
- if (apple) await dropStandIn();
+ }, { lease: () => takeLease('work', { wait: Math.max(0, budgetEnd - Date.now() - 3_000) }) });
+ diary(`push done in ${Date.now() - startedAt} ms`);
});
});
diff --git a/tools/amount-field-unit-test.js b/tools/amount-field-unit-test.js
index b984064..596969d 100644
--- a/tools/amount-field-unit-test.js
+++ b/tools/amount-field-unit-test.js
@@ -2,6 +2,8 @@
// showing: in fiat that is money to the cent, floored so a filled-in maximum
// never parses back to more sats than were offered — not a BTC figure under a
// CAD label (2026-10-08: Max on an ark recipient filled 0.00004978 'CAD').
+// Switching the unit with an amount already typed into the send form converts
+// it (2026-10-23): the same money in the new unit, round-tripping exactly.
// Run: bun tools/amount-field-unit-test.js
import assert from 'node:assert/strict';
import puppeteer from './puppeteer.js';
@@ -9,7 +11,7 @@ import puppeteer from './puppeteer.js';
const bundle = await Bun.build({ entrypoints: ['src/app.js'], target: 'browser', minify: true,
plugins: [{ name: 'amount-field-test', setup(build) {
build.onLoad({ filter: /src\/app\.js$/ }, async ({ path }) => ({ loader: 'js', contents: await Bun.file(path).text() + `
-window.amtApp = { ctx, toggleUnit, get unit() { return unit; } };
+window.amtApp = { ctx, ui, toggleUnit, get unit() { return unit; } };
` }));
build.onLoad({ filter: /src\/video-compress\.js$/ }, () => ({ loader: 'js', contents: 'export async function compressVideo(f) { return f; }' }));
} }] });
@@ -37,6 +39,13 @@ try {
while (amtApp.unit !== 'sats') amtApp.toggleUnit();
out.sats = ctx.amountField(62212);
amtApp.toggleUnit(); out.btc = ctx.amountField(62212);
+ // typed into the send form, then the unit toggled around the ring
+ while (amtApp.unit !== 'sats') amtApp.toggleUnit();
+ const rs = amtApp.ui.send.recipients;
+ rs[0].amount = '62212'; rs.push({ address: '', amount: '93.318' }, { address: '', amount: '' }, { address: '', amount: 'abc' });
+ out.ring = [];
+ for (let i = 0; i < 3; i++) { amtApp.toggleUnit(); out.ring.push([amtApp.unit, ...rs.map((r) => r.amount)]); }
+ rs.splice(1);
return out;
});
console.log(r);
@@ -46,6 +55,11 @@ try {
assert.equal(r.typed, 62207, 'the same money typed as something else parses as typed');
assert.equal(r.sats, '62212');
assert.equal(r.btc, '0.00062212');
+ assert.deepEqual(r.ring, [
+ ['btc', '0.00062212', '0.00000093', '', 'abc'],
+ ['fiat', '93.31', '0.13', '', 'abc'],
+ ['sats', '62212', '93', '', 'abc'],
+ ], 'a typed amount follows the unit around the ring and comes back exact; blanks and junk are left alone');
assert.deepEqual(errors, []);
console.log('✅ amount fills follow the display unit');
} finally { await browser.close(); server.stop(true); }
diff --git a/tools/ark/custody-foreign-test.js b/tools/ark/custody-foreign-test.js
new file mode 100644
index 0000000..148622d
--- /dev/null
+++ b/tools/ark/custody-foreign-test.js
@@ -0,0 +1,102 @@
+// On a server that does not honor a coin past its timelock (Second, a custom
+// captaind) "coinos holds my coins" is not a tier: whatever is stored, the
+// tier in force is "self" (or "exit" when chosen), the card offers only those
+// two, and the renewal pass registers backstops and renews what is due.
+// Real app with a local Ark manager stub; nothing is sent anywhere.
+// Run: bun tools/ark/custody-foreign-test.js
+import assert from 'node:assert/strict';
+import puppeteer from '../puppeteer.js';
+import { generateMnemonic } from '@scure/bip39';
+import { wordlist } from '@scure/bip39/wordlists/english';
+
+const bundle = await Bun.build({ entrypoints: ['src/app.js'], target: 'browser', minify: true,
+ plugins: [{ name: 'custody-foreign-test', setup(build) {
+ build.onLoad({ filter: /src\/app\.js$/ }, async ({ path }) => ({ loader: 'js', contents: await Bun.file(path).text() + `
+window.coopApp = { ui, wallet, ctx, render, enterWallet, openWalletSettings, get ready() { return !_bootDeciding; },
+ setSpending: (on = true) => { const a = activeAccount(); if (a) { if (on) a.kind = 'spending'; else delete a.kind; } } };
+` }));
+ build.onLoad({ filter: /src\/features\/ark\.js$/ }, async ({ path }) => ({ loader: 'js', contents:
+ (await Bun.file(path).text()).replace(" return {\n id: 'ark',", `
+ window.coopFeature = { setManager: (mgr) => { ark = mgr; }, getCustody, applyCustody, maybeAutoRefresh, autoRefreshCalls: [] };
+ return {\n id: 'ark',`) }));
+ build.onLoad({ filter: /src\/video-compress\.js$/ }, () => ({ loader: 'js', contents: 'export async function compressVideo(f) { return f; }' }));
+ } }] });
+assert(bundle.success, bundle.logs.join('\n'));
+const html = `<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><style>${await Bun.file('src/style.css').text()}</style><div id="app"></div><script type="module">${await bundle.outputs[0].text()}</script>`;
+const server = Bun.serve({ port: 0, fetch: (req) => new URL(req.url).pathname === '/'
+ ? new Response(html, { headers: { 'Content-Type': 'text/html' } }) : new Response(null, { status: 404 }) });
+const browser = await puppeteer.launch({ executablePath: '/usr/bin/google-chrome', headless: true, args: ['--no-sandbox'] });
+try {
+ const page = await browser.newPage(), errors = [];
+ page.on('pageerror', (e) => errors.push(e.message));
+ await page.setViewport({ width: 390, height: 844 });
+ const cdp = await page.createCDPSession();
+ await cdp.send('Network.enable');
+ await cdp.send('Network.setBlockedURLs', { urls: ['wss://*', 'ws://*'] });
+ await page.setRequestInterception(true);
+ page.on('request', (r) => r.url().startsWith(server.url.origin) || r.url().startsWith('data:') ? r.continue() : r.abort());
+ await page.evaluateOnNewDocument(() => {
+ localStorage.setItem('btc-wallet-network', 'regtest');
+ // a custom server: no honorsExpired on its record, like Second's preset
+ localStorage.setItem('btc-wallet-ark-provider:regtest', 'custom');
+ localStorage.setItem('btc-wallet-ark-custom:regtest', JSON.stringify({ ark: 'http://localhost:3535', esplora: 'http://localhost:30002' }));
+ });
+ await page.goto(server.url.href, { waitUntil: 'domcontentloaded' });
+ await page.waitForFunction(() => window.coopApp?.ready);
+ await page.evaluate(async (mn) => {
+ await coopApp.enterWallet(mn, '', { fresh: true, generated: true });
+ coopApp.ui.onb = null; localStorage.removeItem('btc-wallet-onb-step');
+ coopApp.wallet.scan = async () => {};
+ const table = [{ thresholdBlocks: 0, ppm: 0 }, { thresholdBlocks: 288, ppm: 2000 }, { thresholdBlocks: 1008, ppm: 4000 }, { thresholdBlocks: 2016, ppm: 5000 }];
+ window.coopManager = {
+ honorsExpired: false,
+ state: { vtxos: [
+ { id: 'coin-0', amountSat: 20000, state: 'spendable', expiryHeight: 973921, depth: 2 }, // weeks left
+ { id: 'coin-1', amountSat: 5000, state: 'spendable', expiryHeight: 969760, depth: 1 }, // 9 blocks from its timelock
+ ], actions: [], movements: [], scheduled: [] },
+ info: { network: 'regtest', vtxoExpiryDelta: 4032, roundIntervalSecs: 3600, refreshFees: { baseFeeSat: 0, ppmExpiryTable: table } }, _tipH: 969751,
+ chain: { tipHeight: async () => 969751 },
+ vtxos() { return this.state.vtxos; },
+ _decoded(v) { return { genesis: new Array(v.depth || 1).fill({}), policy: { type: 'pubkey' } }; },
+ balance() { return { spendableSat: 25000, pendingSat: 0, boardingSat: 0, expiredSat: 0 }; },
+ refreshFee(inputs, tip) {
+ let u = 0;
+ for (const v of inputs) u += v.amountSat * (table.filter((e) => e.thresholdBlocks <= v.expiryHeight - tip).pop()?.ppm ?? 0);
+ return Math.ceil(u / 1e6);
+ },
+ async ensureScheduledRefreshes(margin, max, grid) { coopFeature.autoRefreshCalls.push(['ensure', margin, max, grid]); return 0; },
+ async refresh(ids) { coopFeature.autoRefreshCalls.push(['refresh', ids]); return 'refresh-1'; },
+ unseenReceives() { return []; }, ackReceives() {},
+ address() { return 'test-ark-address'; },
+ };
+ coopFeature.setManager(coopManager);
+ coopApp.setSpending(true);
+ coopApp.openWalletSettings('spending');
+ }, generateMnemonic(wordlist));
+ await page.waitForSelector('.ark-custody');
+
+ // nothing stored: the tier in force is "self", and the card offers no custodial option
+ assert.equal(await page.evaluate(() => coopFeature.getCustody()), 'self');
+ assert.equal(await page.evaluate(() => coopApp.wallet.loadFeatureState('arkCustody', null)), null, 'nothing was written to the record');
+ const opts = await page.$$eval('#ark-custody-select option', (os) => os.map((o) => [o.value, o.selected]));
+ assert.deepEqual(opts, [['self', true], ['exit', false]]);
+ console.log('✓ a server that does not honor expired coins has no "coinos holds my coins" tier; "self" is in force');
+
+ // the stored default from a coinos wallet does not switch renewals off here
+ await page.evaluate(() => coopApp.wallet.saveFeatureState('arkCustody', 'custodial'));
+ assert.equal(await page.evaluate(() => coopFeature.getCustody()), 'self');
+ console.log('✓ a stored "custodial" choice reads as "self" on such a server');
+
+ // the renewal pass runs: backstop orders are registered and the coin at its timelock renews now
+ const calls = await page.evaluate(async () => { coopFeature.autoRefreshCalls.length = 0; await coopFeature.maybeAutoRefresh(coopManager); return coopFeature.autoRefreshCalls; });
+ assert.deepEqual(calls[0], ['ensure', 6, 8, 1], 'backstop orders registered (regtest margin 6)');
+ assert.deepEqual(calls[1], ['refresh', ['coin-1']], 'the coin close to its timelock is renewed now');
+ console.log('✓ automatic renewal runs on such a server with nothing opted into');
+
+ // the exit tier can still be chosen, and is kept
+ await page.evaluate(() => coopFeature.applyCustody('exit'));
+ assert.equal(await page.evaluate(() => coopFeature.getCustody()), 'exit');
+ assert.equal(await page.evaluate(() => coopApp.wallet.loadFeatureState('arkCustody', null)), 'exit');
+ console.log('✓ "exit" can be chosen there and is saved');
+ assert.deepEqual(errors, [], 'no page errors');
+} finally { await browser.close(); server.stop(true); }
diff --git a/tools/ark/offboard-split-test.js b/tools/ark/offboard-split-test.js
new file mode 100644
index 0000000..561ee2b
--- /dev/null
+++ b/tools/ark/offboard-split-test.js
@@ -0,0 +1,128 @@
+// A partial on-chain send from Spending moves whole coins: the amount is
+// covered by coins that already add up to it, else split off via a self-send
+// that lands as one coin per input — all of them go, not one of the exact
+// size (Jarryd, 2026-10-23: three splits, no send). Local manager stub.
+// Run: bun tools/ark/offboard-split-test.js
+import assert from 'node:assert/strict';
+import puppeteer from '../puppeteer.js';
+import { generateMnemonic } from '@scure/bip39';
+import { wordlist } from '@scure/bip39/wordlists/english';
+
+const bundle = await Bun.build({ entrypoints: ['src/app.js'], target: 'browser', minify: true,
+ plugins: [{ name: 'offboard-split-test', setup(build) {
+ build.onLoad({ filter: /src\/app\.js$/ }, async ({ path }) => ({ loader: 'js', contents: await Bun.file(path).text() + `
+window.coopApp = { ui, wallet, ctx, render, enterWallet, get ready() { return !_bootDeciding; } };
+` }));
+ build.onLoad({ filter: /src\/features\/ark\.js$/ }, async ({ path }) => ({ loader: 'js', contents:
+ (await Bun.file(path).text()).replace(" return {\n id: 'ark',", `
+ window.coopFeature = { setManager: (mgr) => { ark = mgr; }, offboard: doArkOffboard, exactCoins };
+ return {\n id: 'ark',`) }));
+ build.onLoad({ filter: /src\/video-compress\.js$/ }, () => ({ loader: 'js', contents: 'export async function compressVideo(f) { return f; }' }));
+ } }] });
+assert(bundle.success, bundle.logs.join('\n'));
+const html = `<!doctype html><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><style>${await Bun.file('src/style.css').text()}</style><div id="app"></div><script type="module">${await bundle.outputs[0].text()}</script>`;
+const server = Bun.serve({ port: 0, fetch: (req) => new URL(req.url).pathname === '/'
+ ? new Response(html, { headers: { 'Content-Type': 'text/html' } }) : new Response(null, { status: 404 }) });
+const browser = await puppeteer.launch({ executablePath: '/usr/bin/google-chrome', headless: true, args: ['--no-sandbox'] });
+try {
+ const page = await browser.newPage(), errors = [];
+ page.on('pageerror', (e) => errors.push(e.message));
+ await page.setViewport({ width: 390, height: 844 });
+ const cdp = await page.createCDPSession();
+ await cdp.send('Network.enable');
+ await cdp.send('Network.setBlockedURLs', { urls: ['wss://*', 'ws://*'] });
+ await page.setRequestInterception(true);
+ page.on('request', (r) => r.url().startsWith(server.url.origin) || r.url().startsWith('data:') ? r.continue() : r.abort());
+ await page.evaluateOnNewDocument(() => {
+ localStorage.setItem('btc-wallet-network', 'regtest');
+ localStorage.setItem('btc-wallet-ark-provider:regtest', 'off');
+ });
+ await page.goto(server.url.href, { waitUntil: 'domcontentloaded' });
+ await page.waitForFunction(() => window.coopApp?.ready);
+ await page.evaluate(async (mn) => {
+ await coopApp.enterWallet(mn, '', { fresh: true, generated: true });
+ coopApp.ui.onb = null; localStorage.removeItem('btc-wallet-onb-step');
+ coopApp.wallet.scan = async () => {};
+ window.coopCalls = [];
+ window.coopManager = {
+ state: { vtxos: [], actions: [], movements: [], nextKeyIndex: 5 },
+ async offboardQuote() { return { chainSat: 736, serviceSat: 204, totalSat: 940, minSat: 1270 }; },
+ info: { network: 'regtest' }, _tipH: 100,
+ vtxos() { return this.state.vtxos; },
+ refreshFee() { return 0; }, unseenReceives() { return []; }, ackReceives() {},
+ address() { return 'test-ark-address'; },
+ // the real thing: largest inputs first until covered, one destination
+ // coin per input (the last carries the remainder), change on a new key;
+ // the destination coins land on the receive key at the next sync
+ async send(address, amount) {
+ coopCalls.push({ type: 'split', address, amount });
+ const free = this.state.vtxos.filter((v) => v.state === 'spendable').sort((a, b) => b.amountSat - a.amountSat);
+ const inputs = []; let sum = 0;
+ for (const v of free) { inputs.push(v); sum += v.amountSat; if (sum >= amount) break; }
+ let remaining = amount; const landing = [];
+ for (const v of inputs) {
+ const dest = Math.min(remaining, v.amountSat); remaining -= dest;
+ landing.push({ id: `dest-${v.id}`, amountSat: dest, state: 'spendable', keyIndex: 0 });
+ if (v.amountSat > dest) this.state.vtxos.push({ id: `change-${v.id}`, amountSat: v.amountSat - dest, state: 'spendable', keyIndex: this.state.nextKeyIndex++ });
+ v.state = 'spent';
+ }
+ this.pendingLanding = landing;
+ return 'send-1';
+ },
+ async sync() { if (this.pendingLanding) { this.state.vtxos.push(...this.pendingLanding); this.pendingLanding = null; } },
+ async startOffboard(spk, address, ids) {
+ coopCalls.push({ type: 'offboard', address, ids: ids || null });
+ return { txid: 'ab'.repeat(32), netSat: 1, feeSat: 1 };
+ },
+ };
+ coopFeature.setManager(coopManager);
+ coopApp.ui.screen = 'wallet'; coopApp.ui.tab = 'send'; coopApp.render();
+ }, generateMnemonic(wordlist));
+ const run = (coins, amount) => page.evaluate(async (coins, amount) => {
+ coopManager.state.vtxos = coins.map((c) => ({ state: 'spendable', keyIndex: 0, ...c }));
+ coopCalls.length = 0;
+ coopApp.ui.arkError = ''; coopApp.ui.arkOffboarded = null;
+ await coopFeature.offboard(amount, coopApp.wallet.derive(0, 1).address);
+ return { calls: coopCalls, err: coopApp.ui.arkError, done: !!coopApp.ui.arkOffboarded };
+ }, coins, amount);
+
+ // Jarryd's balance after one split: the halves add up, so nothing is split again
+ let r = await run([{ id: 'a', amountSat: 109958 }, { id: 'b', amountSat: 75042 }, { id: 'c', amountSat: 24958, keyIndex: 2 }], 185000);
+ assert.equal(r.err, '');
+ assert(r.done);
+ assert.deepEqual(r.calls.map((c) => c.type), ['offboard']);
+ assert.deepEqual([...r.calls[0].ids].sort(), ['a', 'b']);
+ console.log('✓ coins that already add up to the amount go as they are, no split');
+
+ // one coin of the exact size
+ r = await run([{ id: 'a', amountSat: 109958 }, { id: 'c', amountSat: 24958 }], 24958);
+ assert.deepEqual(r.calls, [{ type: 'offboard', address: r.calls[0].address, ids: ['c'] }]);
+ console.log('✓ a single coin of the exact size is the one that goes');
+
+ // Jarryd's first attempt: 185,000 out of 100,000 + 109,958 — nothing adds
+ // up, so a self-send splits it off and lands as two coins; both go
+ r = await run([{ id: 'a', amountSat: 100000 }, { id: 'b', amountSat: 109958 }], 185000);
+ assert.equal(r.err, '');
+ assert(r.done);
+ assert.deepEqual(r.calls.map((c) => c.type), ['split', 'offboard']);
+ assert.equal(r.calls[0].amount, 185000);
+ assert.deepEqual([...r.calls[1].ids].sort(), ['dest-a', 'dest-b']);
+ const left = await page.evaluate(() => coopManager.state.vtxos.filter((v) => v.state === 'spendable').map((v) => [v.id, v.amountSat, v.keyIndex]));
+ assert.deepEqual(left.filter(([id]) => id.startsWith('change')), [['change-a', 24958, 5]]);
+ console.log('✓ a split that lands as two coins sends both; the change stays behind');
+
+ // everything: no carving at all
+ r = await run([{ id: 'a', amountSat: 100000 }, { id: 'b', amountSat: 109958 }], 0);
+ assert.deepEqual(r.calls, [{ type: 'offboard', address: r.calls[0].address, ids: null }]);
+ console.log('✓ the whole balance goes without a split');
+
+ // the subset search: prefers few large coins, gives up on no fit
+ const sub = await page.evaluate(() => {
+ const coins = (a) => a.map((amountSat, i) => ({ id: 'c' + i, amountSat }));
+ const pick = (a, n) => { const r = coopFeature.exactCoins(coins(a), n); return r && r.map((v) => v.amountSat).sort((x, y) => y - x); };
+ return [pick([5000, 3000, 2000, 1000, 1000], 6000), pick([5000, 3000], 7000), pick([5000, 3000, 2000], 5000), pick([7000, 3000], 3000)];
+ });
+ assert.deepEqual(sub, [[5000, 1000], null, [5000], [3000]]);
+ console.log('✓ exactCoins finds a subset, the single coin, or nothing');
+ assert.deepEqual(errors, []);
+} finally { await browser.close(); server.stop(true); }
diff --git a/tools/feed-video-pager-test.js b/tools/feed-video-pager-test.js
index cccde41..61119a0 100644
--- a/tools/feed-video-pager-test.js
+++ b/tools/feed-video-pager-test.js
@@ -67,6 +67,8 @@ const openClip = async (word) => {
await page.evaluate((w) => { const r = [...document.querySelectorAll('.notes-feed [data-key]')].find((n) => n.textContent.includes(w)); r.querySelector('video.note-video').scrollIntoView({ block: 'center' }); }, word);
await sleep(400);
const at = await page.evaluate((w) => { const r = [...document.querySelectorAll('.notes-feed [data-key]')].find((n) => n.textContent.includes(w)); const b = r.querySelector('video.note-video').getBoundingClientRect(); return { x: b.x + b.width * 0.2, y: b.y + b.height * 0.3 }; }, word);
+ // a mouse click on a playing clip pauses it; a paused one opens
+ await page.evaluate(([x, y]) => { const v = document.elementFromPoint(x, y); if (v && v.tagName === 'VIDEO') v.pause(); }, [at.x, at.y]);
await page.mouse.click(at.x, at.y);
await waitFor(() => !!document.querySelector('.media-pager.videos'), null, 4000);
};
diff --git a/tools/fullscreen-notice-test.js b/tools/fullscreen-notice-test.js
index cf15f8c..d3b2785 100644
--- a/tools/fullscreen-notice-test.js
+++ b/tools/fullscreen-notice-test.js
@@ -68,6 +68,8 @@ async function run(lockOk) {
await page.evaluate((w) => { const r = [...document.querySelectorAll('.notes-feed [data-key]')].find((n) => n.textContent.includes(w)); r.querySelector('video.note-video').scrollIntoView({ block: 'center' }); }, word);
await sleep(400);
const at = await page.evaluate((w) => { const r = [...document.querySelectorAll('.notes-feed [data-key]')].find((n) => n.textContent.includes(w)); const b = r.querySelector('video.note-video').getBoundingClientRect(); return { x: b.x + b.width * 0.2, y: b.y + b.height * 0.3 }; }, word);
+ // a mouse click on a playing clip pauses it; a paused one opens
+ await page.evaluate(([x, y]) => { const v = document.elementFromPoint(x, y); if (v && v.tagName === 'VIDEO') v.pause(); }, [at.x, at.y]);
await page.mouse.click(at.x, at.y);
await waitFor(() => !!document.querySelector('.media-pager.videos'), null, 4000);
};
diff --git a/tools/gift-profile-setup-test.js b/tools/gift-profile-setup-test.js
new file mode 100644
index 0000000..9304d1a
--- /dev/null
+++ b/tools/gift-profile-setup-test.js
@@ -0,0 +1,96 @@
+// After a gift is opened into a fresh wallet and its seed written down, the
+// first-run wizard asks for a username, then a picture and a cover — the gift's
+// recipient should arrive as someone people can pay by name. "Not now" lands in
+// the account the gift went to.
+// Drives an ark gift on mutinynet whose bearer key holds nothing (a random
+// secret: the staging ASP sees no coin, so the sweep finds it taken), then
+// "Create wallet anyway" → the seed → on to the wizard.
+// Run: bun run build && bun tools/gift-profile-setup-test.js [screenshot.png]
+import puppeteer from './puppeteer.js';
+import { base32nopad } from '@scure/base';
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+let ok = true;
+const check = (n, c, d = '') => { console.log(` ${c ? '✓' : '✗'} ${n}${d ? ' — ' + d : ''}`); if (!c) ok = false; };
+const server = Bun.serve({ port: 0, async fetch(req) {
+ const p = new URL(req.url).pathname;
+ const f = Bun.file('dist' + (p === '/' ? '/index.html' : p));
+ return (await f.exists()) ? new Response(f) : new Response(Bun.file('dist/index.html'), { headers: { 'content-type': 'text/html' } });
+} });
+const giftCode = () => {
+ const b = new Uint8Array(42);
+ b[0] = 0x11; b[1] = 3; // ark gift, mutinynet
+ new DataView(b.buffer).setBigUint64(2, 1000n, true);
+ b.set(crypto.getRandomValues(new Uint8Array(32)), 10);
+ return base32nopad.encode(b);
+};
+const browser = await puppeteer.launch({ executablePath: '/usr/bin/google-chrome', headless: true, args: ['--no-sandbox'] });
+const text = (page) => page.evaluate(() => document.body.innerText);
+const click = (page, x) => page.evaluate((x) => {
+ const e = [...document.querySelectorAll('button')].find((n) => n.textContent.trim().toLowerCase().includes(x));
+ e?.click(); return !!e;
+}, x);
+const waitText = async (page, re, ms = 30000) => {
+ for (let t = 0; t < ms; t += 250) { if (re.test(await text(page))) return true; await sleep(250); }
+ return false;
+};
+async function toSeed(page, note) {
+ await page.goto(server.url.href);
+ await page.evaluate(() => { localStorage.clear(); localStorage.setItem('btc-wallet-network', 'mutinynet'); });
+ await page.goto(server.url.href + 'ag/' + giftCode() + (note ? '#m=' + encodeURIComponent(note) : ''));
+ check('the gift opens: the server sees no coin behind it', await waitText(page, /aren.t visible/i));
+ if (note) {
+ const q = await page.evaluate(() => document.querySelector('.gift-note')?.textContent || null);
+ check('the sender\'s note shows on the gift', q === note, String(q));
+ check('...and leaves the address bar with the code', await page.evaluate(() => location.pathname === '/' && !location.hash));
+ }
+ await click(page, 'claim');
+ check('...so the claim finds it taken', await waitText(page, /create a wallet anyway/i));
+ check('...create a wallet anyway shows the seed', await click(page, 'create a wallet anyway') && await waitText(page, /recovery phrase/i, 10000));
+}
+try {
+ const page = await browser.newPage();
+ const errors = [];
+ page.on('pageerror', (e) => errors.push(String(e)));
+ await page.setViewport({ width: 390, height: 844, deviceScaleFactor: 2 });
+ await toSeed(page, 'Happy birthday! 🎂 <b>not bold</b>');
+ await click(page, 'skip verification');
+ check('the seed done: the wizard asks for a username', await waitText(page, /now pick a username/i, 10000), (await text(page)).slice(0, 200));
+ check('...with the claim form (or its wait) and Not now', await page.evaluate(() => !!document.querySelector('.onb')) && /not now/i.test(await text(page)));
+ if (process.argv[2]) await page.screenshot({ path: process.argv[2] });
+ // the look step follows the name, as in any first run
+ await page.evaluate(() => localStorage.setItem('btc-wallet-onb-step', 'avatar'));
+ await page.reload();
+ check('the next step is the picture and cover', !!await page.waitForSelector('.onb-cover', { timeout: 15000 }).catch(() => null));
+ // a second gift, verified this time, then Not now
+ const p2 = await browser.newPage();
+ p2.on('pageerror', (e) => errors.push(String(e)));
+ await p2.setViewport({ width: 390, height: 844, deviceScaleFactor: 2 });
+ await toSeed(p2);
+ check('Verify backup opens the word check', await click(p2, 'verify') && await waitText(p2, /word #?\d/i, 5000));
+ await sleep(500);
+ // the verify page doesn't show the words: read them from the account
+ const filled = await p2.evaluate(() => {
+ const accs = JSON.parse(sessionStorage.getItem('btc-wallet-accounts') || '{}');
+ const list = Array.isArray(accs) ? accs : accs.accounts || accs.list || [];
+ const m = list.map((a) => a.mnemonic).filter(Boolean).pop(); if (!m) return false;
+ const w = m.split(' ');
+ for (const lab of document.querySelectorAll('label.field')) {
+ const n = Number(lab.querySelector('.lab').textContent.match(/\d+/)[0]);
+ const inp = lab.querySelector('input');
+ const set = Object.getOwnPropertyDescriptor(HTMLInputElement.prototype, 'value').set;
+ set.call(inp, w[n - 1]); inp.dispatchEvent(new Event('input', { bubbles: true }));
+ }
+ return true;
+ });
+ if (filled) {
+ await click(p2, 'open wallet');
+ check('a verified seed leads to the username step too', await waitText(p2, /now pick a username/i, 10000));
+ await click(p2, 'not now');
+ let gone = false;
+ for (let i = 0; i < 20 && !gone; i++) { await sleep(250); gone = !(await p2.evaluate(() => !!document.querySelector('.onb'))); }
+ check('Not now: into the wallet, the wizard gone', gone, (await text(p2)).slice(0, 200));
+ } else console.log(' (accounts not in localStorage — verify path not driven)');
+ check('no page errors', errors.length === 0, errors.join(' | '));
+} finally { await browser.close(); server.stop(true); }
+console.log(ok ? '\n✅ a gift\'s new wallet is offered a name, a picture and a cover' : '\n❌ failed');
+process.exit(ok ? 0 : 1);
diff --git a/tools/live-stream-test.js b/tools/live-stream-test.js
index ef76043..2be6051 100644
--- a/tools/live-stream-test.js
+++ b/tools/live-stream-test.js
@@ -197,6 +197,12 @@ try {
check('the host\'s face on their post wears the live ring', await waitFor((pk) => !!document.querySelector('.notes-feed .note-post .note-avatar.live-ring'), 5000));
await page.evaluate(() => document.querySelector('.notes-feed .note-post .note-avatar.live-ring').click());
check('...and a tap on it opens the stream', await waitFor(() => !!document.querySelector('.live-page'), 5000));
+ const lay = await page.evaluate(() => {
+ const r = (q) => document.querySelector(q)?.getBoundingClientRect();
+ const p = r('.live-page .live-player'), c = r('.live-page .live-chat');
+ return { w: document.body.clientWidth, player: p && [p.left, p.width], chat: c && [c.left, c.width] };
+ });
+ check('on a phone the picture runs edge to edge and the chat is as wide', lay.player && lay.player[0] === 0 && lay.player[1] === lay.w && lay.chat && lay.chat[0] === 0 && lay.chat[1] === lay.w, JSON.stringify(lay));
await page.goBack();
await waitFor(() => !document.querySelector('.live-page') && !!document.querySelector('.media-modes'), 5000);
await page.evaluate(() => document.querySelector('.media-mode[data-mode="live"]').click());
@@ -217,6 +223,7 @@ try {
check('...and the zap, its amount and words', await waitText('zapped 21 sats', 5000) && await waitText('great stream', 1000));
const rowSel = '.live-message[data-key="' + chat.id + '"]';
check('comments use the group-chat bubble and shared composer', await page.$(rowSel + ' .chat-bubble') && await page.$('.live-page coinos-text#msg-draft'));
+ check('...drawn plain on a phone, no bubble walls', await page.evaluate((q) => { const b = document.querySelector(q); return b && getComputedStyle(b).borderStyle === 'none' && getComputedStyle(b).display === 'block'; }, rowSel + ' .chat-bubble'));
check('another client’s e-only reaction arrives on the comment', await waitFor(id => document.querySelector('.live-message[data-key="'+id+'"] .chat-reacts')?.textContent.includes('👍'), 6000, chat.id));
check('per-comment zap receipts show under the bubble', await waitFor(id => document.querySelector('.live-message[data-key="'+id+'"] .zap-tally')?.textContent.includes('5'), 6000, chat.id));
await page.click(rowSel + ' .chat-bubble');
diff --git a/tools/ln-pay-double-wake.test.js b/tools/ln-pay-double-wake.test.js
new file mode 100644
index 0000000..18a1943
--- /dev/null
+++ b/tools/ln-pay-double-wake.test.js
@@ -0,0 +1,74 @@
+// Two wakes of the phone's worker, seconds apart, each over its own copy of
+// the wallet, both drive one Lightning send (PullCap, 2026-10-24 23:21). The
+// second's InitiateLightningPayment is refused — the HTLC is already 'ln-spent'
+// to this very payment — and that once marked a PAID send 'revoking'. Now the
+// send follows the payment instead, and a send in 'revoking' asks the ASP
+// before revoking: paid → settled; still in flight → back to waiting.
+// Run: bun test tools/ln-pay-double-wake.test.js
+import { test, expect, mock } from 'bun:test';
+import { hex } from '@scure/base';
+import { sha256 } from '@noble/hashes/sha256';
+import * as realLn from '../src/ark/lightning.js';
+import * as realProto from '../src/ark/proto.js';
+import * as realSend from '../src/ark/send.js';
+
+const PRE = 'ab'.repeat(32);
+const HASH = hex.encode(sha256(hex.decode(PRE)));
+const asp = { initiate: null, check: null, revoked: 0, checks: 0 };
+mock.module('../src/ark/lightning.js', () => ({
+ ...realLn,
+ initiateLightningPayment: async () => { if (asp.initiate) throw asp.initiate; },
+ checkLightningPayment: async () => { asp.checks++; if (asp.check instanceof Error) throw asp.check; return asp.check; },
+ requestLightningPayHtlcRevocation: async () => { asp.revoked++; throw new Error('revocation should not be asked for'); },
+}));
+mock.module('../src/ark/proto.js', () => ({ ...realProto, decodeVtxo: () => ({ id: 'htlc1', point: { raw: new Uint8Array(36) } }) }));
+mock.module('../src/ark/send.js', () => ({ ...realSend, registerVtxoTransactions: async () => {},
+ buildArkoorSend: () => ({}), genUserNonces: () => ({}), cosignPartBytes: () => new Uint8Array(1) }));
+const { ArkManager } = await import('../src/ark/manager.js');
+const { GrpcError } = realProto;
+
+function mgrWith(step) {
+ const action = { id: 'lnpay-1700000000000', type: 'ln-pay', step, paymentHash: HASH, amountSat: 1, htlcExpiry: 1000, htlcBytesList: ['00'], htlcVtxoIds: ['htlc1'], changeBytesList: [], invoice: 'lnbc1' };
+ const m = Object.create(ArkManager.prototype);
+ const own = {
+ arkUrl: 'http://ark.test', chain: { tipHeight: async () => 900 },
+ state: { actions: [action], vtxos: [{ id: 'htlc1', state: 'pending', amountSat: 1 }], movements: [] },
+ _save: () => {}, _lnDriving: new Set(), _spentRetried: new Set(),
+ _key: () => ({ pubkey: new Uint8Array(33) }), _mailboxKey: () => ({ pubkey: new Uint8Array(33) }),
+ };
+ for (const [k, v] of Object.entries(own)) Object.defineProperty(m, k, { value: v, writable: true, configurable: true });
+ return { m, action };
+}
+
+test("a second wake's initiate refused as 'ln-spent' follows the payment to done", async () => {
+ Object.assign(asp, { initiate: new GrpcError(3, 'bad user input: vtxo b47f…:0 is not spendable (state: ln-spent)', 'bark_server.ArkService/InitiateLightningPayment'), check: { status: 'success', preimage: PRE }, revoked: 0 });
+ const { m, action } = mgrWith('cosigned');
+ await m._driveLnPay(action);
+ expect(action.step).toBe('done');
+ expect(action.preimage).toBe(PRE);
+ expect(asp.revoked).toBe(0);
+ expect(m.state.movements.filter((x) => x.type === 'ln-send' && x.status === 'complete').length).toBe(1);
+});
+
+test("a send in 'revoking' that the ASP paid settles, nothing revoked", async () => {
+ Object.assign(asp, { initiate: null, check: { status: 'success', preimage: PRE }, revoked: 0 });
+ const { m, action } = mgrWith('revoking');
+ await m._driveLnPay(action);
+ expect(action.step).toBe('done');
+ expect(asp.revoked).toBe(0);
+});
+
+test("a send in 'revoking' still in flight before its expiry goes back to waiting", async () => {
+ Object.assign(asp, { initiate: null, check: { status: 'pending' }, revoked: 0 });
+ const { m, action } = mgrWith('revoking');
+ await m._driveLnPay(action);
+ expect(action.step).toBe('initiated');
+ expect(asp.revoked).toBe(0);
+});
+
+test("a send the ASP never saw (not found) is still revoked", async () => {
+ Object.assign(asp, { initiate: null, check: new GrpcError(5, 'not found: payment attempt not found', 'x'), revoked: 0 });
+ const { m, action } = mgrWith('revoking');
+ await m._driveLnPay(action).catch(() => {});
+ expect(asp.revoked).toBe(1);
+});
diff --git a/tools/media-grid-order-test.js b/tools/media-grid-order-test.js
new file mode 100644
index 0000000..9274d92
--- /dev/null
+++ b/tools/media-grid-order-test.js
@@ -0,0 +1,128 @@
+// The Videos grid's order holds for the session (Adam, 2026-10-23: clips the
+// crawl found landed in the middle of the grid and the tiles already there
+// jumped around): tiles found later go under the ones already showing, in
+// their own date order, even when they are dated between them; only a post
+// newer than the top tile goes above it. Run: bun tools/media-grid-order-test.js
+import puppeteer from './puppeteer.js';
+import { cacheKeyFor } from '../src/wallet.js';
+import { generateSecretKey, getPublicKey, finalizeEvent } from 'nostr-tools/pure';
+import { buildHtml } from '../build.js';
+import { mkdtempSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+let ok = true;
+const check = (n, c, d = '') => { console.log(` ${c ? '✓' : '✗'} ${n}${d ? ' — ' + d : ''}`); if (!c) ok = false; };
+const dir = mkdtempSync(tmpdir() + '/morder-');
+const NAMES = ['a', 'b', 'c', 'gap1', 'gap2', 'old1', 'old2', 'fresh'];
+for (const [i, n] of NAMES.entries()) {
+ const p = Bun.spawnSync(['ffmpeg', '-y', '-loglevel', 'error', '-f', 'lavfi', '-i', 'testsrc=size=360x640:rate=10', '-t', String(2 + i / 4), '-c:v', 'libx264', '-pix_fmt', 'yuv420p', '-movflags', '+faststart', `${dir}/${n}.mp4`]);
+ if (p.exitCode !== 0) throw new Error('ffmpeg failed');
+}
+const html = await buildHtml({ minify: true, pwa: false });
+const server = Bun.serve({ port: 0, idleTimeout: 30, fetch: async (req) => {
+ const path = new URL(req.url).pathname;
+ if (path.startsWith('/v/')) {
+ const f = Bun.file(dir + path.slice(2));
+ const cors = { 'access-control-allow-origin': '*', 'access-control-expose-headers': 'content-range, content-length', 'content-type': 'video/mp4', 'accept-ranges': 'bytes' };
+ if (req.method === 'HEAD') return new Response(null, { headers: { ...cors, 'content-length': String(f.size) } });
+ const m = /bytes=(\d+)-(\d*)/.exec(req.headers.get('range') || '');
+ if (m) { const a = +m[1], b = Math.min(m[2] ? +m[2] : f.size - 1, f.size - 1); return new Response(f.slice(a, b + 1), { status: 206, headers: { ...cors, 'content-range': `bytes ${a}-${b}/${f.size}` } }); }
+ return new Response(f, { headers: cors });
+ }
+ if (path.startsWith('/punks') || path === '/verify-worker.js') return new Response(Bun.file('dist' + path));
+ return new Response(html, { headers: { 'content-type': 'text/html' } });
+} });
+const page0 = server.url.origin, base = page0.replace('localhost', '127.0.0.1');
+const SK = generateSecretKey(), PK = getPublicKey(SK);
+const now = Math.floor(Date.now() / 1000);
+const clip = (name, at) => finalizeEvent({ kind: 1, created_at: at, content: name + ' ' + base + '/v/' + name + '.mp4',
+ tags: [['imeta', 'url ' + base + '/v/' + name + '.mp4', 'm video/mp4', 'dim 360x640']] }, SK);
+const words = (i, at) => finalizeEvent({ kind: 1, created_at: at, tags: [], content: 'just words ' + i }, SK);
+// the page: words and three clips minutes apart; the crawl (a hundred at a
+// time) from under the page finds only two clips from long ago; the feed's
+// own next page of posts (asked as the grid is scrolled to its end) brings
+// two clips dated between c and old1
+const abc = [clip('a', now - 3000), clip('b', now - 3400), clip('c', now - 3800)];
+const gap = [clip('gap1', now - 12000), clip('gap2', now - 14000)];
+const tail = [clip('old1', now - 20000), clip('old2', now - 30000)];
+const wordsAll = []; for (let i = 0; i < 10; i++) wordsAll.push(words(i, i < 5 ? now - 100 - i * 400 : now - 4000 - (i - 5) * 400));
+const fresh = clip('fresh', now + 5);
+const all = [...wordsAll, ...abc, ...gap, ...tail].sort((x, y) => y.created_at - x.created_at);
+
+const browser = await puppeteer.launch({ relays: 'read', executablePath: process.env.CHROME || '/usr/bin/google-chrome', headless: 'new', args: ['--no-sandbox', '--autoplay-policy=no-user-gesture-required'] });
+const page = await browser.newPage();
+await page.evaluateOnNewDocument(([all, tail, fresh, pk]) => {
+ window.__crawls = 0; window.__pages = 0; window.__live = []; window.__reqs = [];
+ const Real = window.WebSocket;
+ window.WebSocket = function (...a) {
+ const ws = new Real(...a);
+ const send = ws.send.bind(ws);
+ const emit = (sub, ev) => ws.dispatchEvent(new MessageEvent('message', { data: JSON.stringify(['EVENT', sub, ev]) }));
+ ws.send = (data) => {
+ try {
+ const m = JSON.parse(data);
+ if (m[0] === 'REQ') {
+ const f = m[2] || {};
+ let out = [];
+ if ((f.kinds || []).includes(1) && (f.authors || []).includes(pk) && !f['#e'] && !f.ids) {
+ window.__reqs.push({ until: f.until, since: f.since, limit: f.limit });
+ if (f.since && !f.until) window.__live.push(() => emit(m[1], fresh));
+ else if (f.limit === 100 && f.until) { window.__crawls++; out = tail.filter((e) => e.created_at <= f.until); }
+ else { window.__pages += f.until ? 1 : 0; out = all.filter((e) => !f.until || e.created_at <= f.until).slice(0, f.limit || 30); }
+ }
+ setTimeout(() => {
+ for (const ev of out) emit(m[1], ev);
+ ws.dispatchEvent(new MessageEvent('message', { data: JSON.stringify(['EOSE', m[1]]) }));
+ }, 0);
+ return;
+ }
+ if (m[0] === 'EVENT') return;
+ } catch {}
+ return send(data);
+ };
+ return ws;
+ };
+ window.WebSocket.prototype = Real.prototype; Object.assign(window.WebSocket, Real);
+}, [all, tail, fresh, PK]);
+const errs = [];
+page.on('pageerror', (e) => errs.push(String(e)));
+const click = (t) => page.evaluate((x) => { const e = [...document.querySelectorAll('button')].find((n) => n.textContent.trim().toLowerCase().includes(x)); if (e) { e.click(); return true; } return false; }, t);
+const waitText = async (x, ms = 25000) => { for (let i = 0; i < ms / 250; i++) { if ((await page.evaluate(() => document.body.innerText)).toLowerCase().includes(x)) return true; await sleep(250); } return false; };
+const waitFor = async (fn, ms = 10000) => { for (let i = 0; i < ms / 100; i++) { if (await page.evaluate(fn)) return true; await sleep(100); } return false; };
+const order = () => page.evaluate(() => [...document.querySelectorAll('.media-grid .media-tile.video')].map((t) => t.getAttribute('data-key').split('/').pop().replace('.mp4', '')));
+
+try {
+ await page.setViewport({ width: 390, height: 844 });
+ await page.goto(page0, { waitUntil: 'domcontentloaded' });
+ await page.evaluate(() => localStorage.setItem('btc-wallet-network', 'regtest'));
+ await page.reload({ waitUntil: 'domcontentloaded' }); await sleep(400);
+ await click('create a new wallet'); await sleep(600);
+ await page.waitForSelector('.words .w .t');
+ const mn = (await page.$$eval('.words .w .t', (l) => l.map((e) => e.textContent.trim()))).join(' ');
+ await click('skip verification');
+ await waitText('receive', 20000);
+ const key = cacheKeyFor(mn + '\n');
+ await page.evaluate(([k, pk]) => {
+ localStorage.setItem(k + ':follows', JSON.stringify({ tags: [['p', pk]], c: '', at: Math.floor(Date.now() / 1000) }));
+ localStorage.setItem(k + ':profiles', JSON.stringify({ [pk]: { name: 'Clip Poster', t: Date.now() } }));
+ localStorage.setItem('btc-wallet-feed:' + k, 'following');
+ }, [key, PK]);
+ await page.reload({ waitUntil: 'domcontentloaded' });
+ await waitText('receive', 20000);
+ await page.evaluate(() => [...document.querySelectorAll('.app-nav-button, button')].find((b) => b.textContent.trim() === 'Feed')?.click());
+ await waitFor(() => !!document.querySelector('.media-modes'), 20000);
+ await page.evaluate(() => document.querySelector('.media-mode[data-mode="videos"]').click());
+ check('the grid: the page\'s three clips, newest first', await waitFor(() => document.querySelectorAll('.media-grid .media-tile.video').length === 3, 20000) && (await order()).join(' ') === 'a b c', (await order()).join(' '));
+ check('the crawl finds the two from long ago, under them', await waitFor(() => window.__crawls >= 1 && document.querySelectorAll('.media-grid .media-tile.video').length === 5, 25000) && (await order()).join(' ') === 'a b c old1 old2', (await order()).join(' ') + ' crawls ' + await page.evaluate(() => window.__crawls));
+ for (let i = 0; i < 40 && !(await page.evaluate(() => document.querySelectorAll('.media-grid .media-tile.video').length === 7)); i++) {
+ await page.evaluate(() => window.scrollTo(0, document.documentElement.scrollHeight));
+ await sleep(500);
+ }
+ check('the feed\'s next page, asked at the grid\'s end, brings the two dated between c and old1', await page.evaluate(() => window.__pages >= 1 && document.querySelectorAll('.media-grid .media-tile.video').length === 7), (await order()).join(' ') + ' pages ' + await page.evaluate(() => window.__pages));
+ check('...shown under the tiles already there, in their own date order', (await order()).join(' ') === 'a b c old1 old2 gap1 gap2', (await order()).join(' '));
+ await page.evaluate(() => { for (const f of window.__live) f(); });
+ check('a post newer than the top tile goes above it', await waitFor(() => document.querySelectorAll('.media-grid .media-tile.video').length === 8, 20000) && (await order()).join(' ') === 'fresh a b c old1 old2 gap1 gap2', (await order()).join(' '));
+ check('no page errors', errs.length === 0, errs.slice(0, 2).join(' | '));
+} finally { await browser.close(); server.stop(true); }
+console.log(ok ? '\n✅ media grid: found later, shown under' : '\n❌ failed');
+process.exit(ok ? 0 : 1);
diff --git a/tools/media-moments-feed-test.js b/tools/media-moments-feed-test.js
index a188c5d..7b429c9 100644
--- a/tools/media-moments-feed-test.js
+++ b/tools/media-moments-feed-test.js
@@ -175,6 +175,18 @@ try {
check('...and shows over the pager\'s seek bar', await page.waitForFunction(() => !!document.querySelector('.media-pager .mp-cur .mp-seek .mp-mark'), { timeout: 3000 }).then(() => true, () => false));
check('no timeline panel over the pager', await page.evaluate(() => !document.querySelector('.media-pager .media-timeline')));
await page.screenshot({ path: '/tmp/media-timeline-pager.png' });
+ // back in the feed: the clip has a moment now, so the moments bar is its
+ // only seek bar (no player controls), with the middle button to play it
+ await page.keyboard.press('Escape'); await sleep(500);
+ await page.evaluate(() => { const v = document.querySelector('video.note-video'); v.pause(); v.dispatchEvent(new Event('timeupdate')); });
+ await sleep(200);
+ const one = await page.evaluate(() => { const v = document.querySelector('video.note-video'); const b = v.closest('.note-video-box'); const tl = b.querySelector('.media-timeline');
+ return { controls: v.controls, own: b.classList.contains('own-bar'), bar: !!tl && getComputedStyle(tl).display !== 'none', mark: !!b.querySelector('.media-mark'), pp: getComputedStyle(b.querySelector('.vid-pp')).display }; });
+ check('in the feed, a clip with a moment has one seek bar: the moments bar, no player controls', !one.controls && one.own && one.bar && one.mark, JSON.stringify(one));
+ check('...and the middle button plays it, on a touch screen too', one.pp === 'flex', JSON.stringify(one));
+ const vid2 = await page.evaluate(() => { const b = document.querySelector('.note-video-box .vid-pp').getBoundingClientRect(); return { x: b.x + b.width / 2, y: b.y + b.height / 2 }; });
+ await page.mouse.click(vid2.x, vid2.y); await sleep(600);
+ check('...which plays it in place', await page.evaluate(() => !document.querySelector('video.note-video').paused && !document.querySelector('.media-pager')));
check('no browser exceptions', errs.length === 0, errs.join(' | '));
await page.screenshot({ path: '/tmp/media-timeline-feed.png' });
} finally { await browser.close(); server.stop(); }
diff --git a/tools/nwc-sw-test.js b/tools/nwc-sw-test.js
index f037275..5a15d48 100644
--- a/tools/nwc-sw-test.js
+++ b/tools/nwc-sw-test.js
@@ -5,7 +5,8 @@ import { hex } from '@scure/base';
import * as nip04 from 'nostr-tools/nip04';
import * as nip44 from 'nostr-tools/nip44';
import { finalizeEvent, generateSecretKey, getPublicKey } from 'nostr-tools/pure';
-import { respondFromBg } from '../src/nwc-respond.js';
+import { respondFromBg, tendLnPays } from '../src/nwc-respond.js';
+import { maybeBolt11 } from '../src/ark/lightning.js';
let fails = 0;
const check = (name, ok, detail = '') => {
@@ -118,6 +119,24 @@ console.log('\n[merchant methods (BTCPay)]');
check('list_transactions includes receives', txs.some((t) => t.type === 'incoming' && t.amount === 21000), JSON.stringify(txs));
}
{
+ // PullCap 2026-10-24: lookups of a send in flight came back "not found".
+ // Every copy of the connection is asked; an outgoing send answers as one.
+ const INV = 'lnbc210n1p4xuk2wpp506wkjr0xk3677nu7je9c55vq4lzlkyd0ztcq2mlvumap0zpe3alqhp5ppg7g8qwpdv34hgpymhw446y37duzwcn388yp3pw05n7tlulyn2scqzysxqrrssrzjqv3dpepm8kfdxrk3sl6wzqdf49s9c0h9ljtjrek6c08r6aejlwcnur0dwyqqvusqqqqqqqlgqqqq86qqjqsp5dc0jrq94ke2f4dzx8c2dwqsc6a65eu56dt2j599l7kxp7q2hs6zq9qxpqysgqdjeft8gkl0uga24e502pvcp5vgsfap3dxuutcpgfaj33fffuqs9psmnrklshp3fg3py7vlnzsea90vj9ahqq5t9xuy67u3pk0sfnheqpn95f2g';
+ const H = '7e9d690de6b475ef4f9e964b8a5180afc5fb11af12f0056fece6fa1788398f7e';
+ const fresher = baseRec(); fresher.updated = 2; fresher.ark = { ...fresher.ark, network: 'signet' };
+ const live = baseRec(); live.updated = 1;
+ live.mgr.actions.push({ id: 'lnpay-1', type: 'ln-pay', step: 'done', paymentHash: H, preimage: 'cd'.repeat(32), amountSat: 21, invoice: INV });
+ const { deps, published, decryptReply } = harness({ recs: [{ walletKey: 'old', rec: fresher }, { walletKey: 'w1', rec: live }] });
+ await respondFromBg({ type: 'nwc', event: ev(makeReq('lookup_invoice', { payment_hash: H })) }, deps);
+ const r = decryptReply(published[0]).result || {};
+ check('lookup_invoice finds a send in the older copy of the connection → outgoing, settled, its preimage', r.type === 'outgoing' && r.state === 'settled' && r.preimage === 'cd'.repeat(32), JSON.stringify(r));
+ live.mgr.actions[0].step = 'initiated'; delete live.mgr.actions[0].preimage;
+ const t0 = Date.now();
+ await respondFromBg({ type: 'nwc', event: ev(makeReq('lookup_invoice', { payment_hash: H })) }, { ...deps, deadline: Date.now() + 2500 });
+ const r2 = decryptReply(published[1]).result || {};
+ check('…one still in flight (ASP unreachable here) → outgoing, pending, inside the push budget', r2.type === 'outgoing' && r2.state === 'pending' && Date.now() - t0 < 4000, JSON.stringify(r2) + ` ${Date.now() - t0} ms`);
+}
+{
const { deps } = harness(); // a mirror without receive keys
check('make_invoice on an old mirror → wake the user', (await respondFromBg({ type: 'nwc', event: ev(makeReq('make_invoice', { amount: 21000 })) }, deps)) === false);
}
@@ -178,6 +197,112 @@ const INV21 = 'lnbc210n1p4xuk2wpp506wkjr0xk3677nu7je9c55vq4lzlkyd0ztcq2mlvumap0z
check('exhausted key window → wake the user', handled === false);
}
+console.log('\n[pay outcome]');
+{
+ // a payment that goes through: the worker hands the push handler a
+ // "Payment sent" heads-up (unless the user turned those off)
+ const { ArkManager } = await import('../src/ark/manager.js');
+ const orig = { init: ArkManager.prototype.init, pay: ArkManager.prototype.payLnInvoice, wait: ArkManager.prototype.awaitLnPay, act: ArkManager.prototype.lnAction };
+ const done = { id: 'ln-1', step: 'done', amountSat: 21, feeSat: 0, preimage: 'ab'.repeat(32) };
+ ArkManager.prototype.init = async function () { this.state = this.storage.load(); return this; };
+ ArkManager.prototype.payLnInvoice = async () => 'ln-1';
+ ArkManager.prototype.awaitLnPay = async () => done;
+ ArkManager.prototype.lnAction = () => done;
+ try {
+ const { deps, published, decryptReply } = harness();
+ const handled = await respondFromBg({ type: 'nwc', event: ev(makeReq('pay_invoice', { invoice: INV21 })) }, deps);
+ check('a paid invoice answers with the preimage', published.length === 1 && decryptReply(published[0]).result?.preimage === done.preimage, JSON.stringify(handled));
+ check('…and asks for a "Payment sent" notification', handled && handled.notify && handled.notify.title === 'Payment sent', JSON.stringify(handled));
+ const rec = baseRec(); rec.prefs = { paySent: false };
+ const h2 = harness({ rec });
+ const quiet = await respondFromBg({ type: 'nwc', event: ev(makeReq('pay_invoice', { invoice: INV21 })) }, h2.deps);
+ check('payments-sent notifications off → paid quietly', quiet === true && h2.published.length === 1);
+ } finally {
+ Object.assign(ArkManager.prototype, { init: orig.init, payLnInvoice: orig.pay, awaitLnPay: orig.wait, lnAction: orig.act });
+ }
+}
+
+console.log('\n[sends begun on an earlier wake]');
+// The worker died mid-payment on an earlier wake: the action sits in the
+// mirror at 'created' with its coin reserved (PullCap, 2026-10-23).
+{
+ const { ArkManager } = await import('../src/ark/manager.js');
+ const HASH = maybeBolt11(INV21).paymentHash;
+ const PRE = 'cd'.repeat(32);
+ const names = ['init', 'payLnInvoice', 'awaitLnPay', 'lnAction', 'driveLn'];
+ const orig = Object.fromEntries(names.map((k) => [k, ArkManager.prototype[k]]));
+ ArkManager.prototype.init = async function () { this.state = this.storage.load(); return this; };
+ // a fresh attempt at an invoice with an action on the books is refused…
+ ArkManager.prototype.payLnInvoice = async function (invoice) {
+ const hash = maybeBolt11(invoice).paymentHash;
+ if (this.state.actions.some((a) => a.type === 'ln-pay' && a.paymentHash === hash && a.step !== 'failed')) throw new Error('a payment for this invoice is already in progress');
+ const a = { id: 'lnpay-new', type: 'ln-pay', step: 'done', invoice, paymentHash: hash, amountSat: 21, feeSat: 0, preimage: 'ab'.repeat(32) };
+ this.state.actions.push(a); this.storage.save(this.state);
+ return a.id;
+ };
+ // …and a drive takes the stuck one through to done, freeing its change
+ ArkManager.prototype.awaitLnPay = async function (id) { return this.driveLn(id); };
+ ArkManager.prototype.driveLn = async function (id) {
+ const a = this.state.actions.find((x) => x.id === id);
+ if (a && a.step !== 'done') {
+ a.step = 'done'; a.preimage = PRE;
+ for (const v of this.state.vtxos) if (v.state === 'pending') v.state = 'spendable';
+ this.storage.save(this.state);
+ }
+ return a;
+ };
+ ArkManager.prototype.lnAction = function (id) { return this.state.actions.find((x) => x.id === id); };
+ const stuckRec = (hash) => {
+ const rec = baseRec();
+ rec.mgr.vtxos[0].state = 'pending';
+ rec.mgr.actions.push({ id: 'lnpay-stuck', type: 'ln-pay', step: 'created', invoice: INV21, paymentHash: hash, amountSat: 21, feeSat: 0 });
+ rec.pendingPays = [{ hash, connId: 'c1', ts: 1 }];
+ return rec;
+ };
+ try {
+ {
+ // the SAME invoice asked again: finish that send, answer with ITS preimage
+ const rec = stuckRec(HASH);
+ const log = [];
+ const { deps, published, decryptReply } = harness({ rec });
+ const handled = await respondFromBg({ type: 'nwc', event: ev(makeReq('pay_invoice', { invoice: INV21 })) }, { ...deps, log: (m) => log.push(m) });
+ check('same invoice → the stuck send is finished and answered with its preimage', published.length === 1 && decryptReply(published[0]).result?.preimage === PRE, JSON.stringify(handled));
+ check('…recorded once on the spend log, under its connection', rec.spends.length === 1 && rec.spends[0].connId === 'c1' && rec.spends[0].preimage === PRE && rec.pendingPays.length === 0, JSON.stringify(rec.spends));
+ check('…with a "Payment sent" heads-up', handled && handled.notify && handled.notify.title === 'Payment sent');
+ check('…and the diary names the step it reached', log.some((m) => /already created/.test(m)) && log.some((m) => /→ done/.test(m)), log.join(' | '));
+ }
+ {
+ // a send that settled earlier (in the app, say): its preimage again,
+ // nothing new on the spend log
+ const rec = baseRec();
+ rec.mgr.actions.push({ id: 'lnpay-old', type: 'ln-pay', step: 'done', invoice: INV21, paymentHash: HASH, amountSat: 21, feeSat: 0, preimage: PRE });
+ const { deps, published, decryptReply } = harness({ rec });
+ await respondFromBg({ type: 'nwc', event: ev(makeReq('pay_invoice', { invoice: INV21 })) }, deps);
+ check('an invoice paid earlier answers with the same preimage', published.length === 1 && decryptReply(published[0]).result?.preimage === PRE);
+ check('…without a second spend', (rec.spends || []).length === 0);
+ }
+ {
+ // a stuck send for ANOTHER invoice holds the only coin: finish it first,
+ // then pay the new request from the freed coin
+ const rec = stuckRec('ee'.repeat(32));
+ const { deps, published, decryptReply } = harness({ rec });
+ const handled = await respondFromBg({ type: 'nwc', event: ev(makeReq('pay_invoice', { invoice: INV21 })) }, deps);
+ check('another invoice → the earlier send is finished, then this one paid', published.length === 1 && decryptReply(published[0]).result?.preimage === 'ab'.repeat(32), JSON.stringify(handled));
+ check('…both on the spend log', rec.spends.length === 2 && rec.spends[0].preimage === PRE && rec.spends[1].preimage === 'ab'.repeat(32));
+ check('…the earlier one gets its own "Payment sent" line', handled && handled.notices && handled.notices.length === 1 && handled.notify && handled.notify.title === 'Payment sent', JSON.stringify(handled));
+ }
+ {
+ // any wake at all finishes it (a lookup, a push for something else)
+ const rec = stuckRec(HASH);
+ const notices = await tendLnPays({ recordsFn: async () => [{ walletKey: 'w1', rec }], saveFn: async () => {} });
+ check('tendLnPays finishes a stuck send and reports it', notices.length === 1 && notices[0].title === 'Payment sent' && rec.spends.length === 1 && rec.spends[0].connId === 'c1', JSON.stringify(notices));
+ check('…and a second wake has nothing left to do', (await tendLnPays({ recordsFn: async () => [{ walletKey: 'w1', rec }], saveFn: async () => {} })).length === 0);
+ }
+ } finally {
+ Object.assign(ArkManager.prototype, orig);
+ }
+}
+
console.log('\n[network fit]');
{
// a mutinynet-era mirror must not answer a mainnet invoice with a nonsense
diff --git a/tools/pager-caption-test.js b/tools/pager-caption-test.js
index 5952d81..50ffe4f 100644
--- a/tools/pager-caption-test.js
+++ b/tools/pager-caption-test.js
@@ -55,6 +55,8 @@ const openClip = async (word) => {
await page.evaluate((w) => { const r = [...document.querySelectorAll('.notes-feed [data-key]')].find((n) => n.textContent.includes(w)); r.querySelector('video.note-video').scrollIntoView({ block: 'center' }); }, word);
await sleep(400);
const at = await page.evaluate((w) => { const r = [...document.querySelectorAll('.notes-feed [data-key]')].find((n) => n.textContent.includes(w)); const b = r.querySelector('video.note-video').getBoundingClientRect(); return { x: b.x + b.width * 0.2, y: b.y + b.height * 0.3 }; }, word);
+ // a mouse click on a playing clip pauses it; a paused one opens
+ await page.evaluate(([x, y]) => { const v = document.elementFromPoint(x, y); if (v && v.tagName === 'VIDEO') v.pause(); }, [at.x, at.y]);
await page.mouse.click(at.x, at.y);
const opened = await waitFor(() => !!document.querySelector('.media-pager.videos .mp-slide'), null, 4000);
// the caption and the counts show on a tap on the clip (details), as a reader sees them
@@ -72,6 +74,8 @@ const clickIn = async (sel, where) => {
// the caption's first word sits at its left edge; a link in the middle
return where === 'start' ? { x: r.left + 12, y: r.top + 9 } : { x: r.left + r.width / 2, y: r.top + r.height / 2 };
}, ['(' + CAP + ')', sel, where]);
+ // a mouse click on a playing clip pauses it; a paused one opens
+ await page.evaluate(([x, y]) => { const v = document.elementFromPoint(x, y); if (v && v.tagName === 'VIDEO') v.pause(); }, [at.x, at.y]);
await page.mouse.click(at.x, at.y);
};
const toFeed = async () => { await page.evaluate(() => document.querySelector('.app-nav-button[aria-label="Feed"]').click()); await waitFor(() => !!document.querySelector('.notes-feed video.note-video'), null, 8000); };
diff --git a/tools/pager-close-test.js b/tools/pager-close-test.js
index 73aa15b..a7c6c12 100644
--- a/tools/pager-close-test.js
+++ b/tools/pager-close-test.js
@@ -84,6 +84,8 @@ const st = () => page.evaluate(() => ({ pager: !!document.querySelector('.media-
const openFirst = async () => {
const r = await page.evaluate(() => { const row = [...document.querySelectorAll('.notes-feed [data-key]')].find((n) => n.textContent.includes('clip zero')); row.querySelector('video.note-video').scrollIntoView({ block: 'center' }); const b = row.querySelector('video.note-video').getBoundingClientRect(); return { x: b.x + b.width * 0.2, y: b.y + b.height * 0.3 }; });
await sleep(400);
+ // a mouse click on a playing clip pauses it; a paused one opens
+ await page.evaluate(([x, y]) => { const v = document.elementFromPoint(x, y); if (v && v.tagName === 'VIDEO') v.pause(); }, [r.x, r.y]);
await page.mouse.click(r.x, r.y);
return waitFor(() => !!document.querySelector('.media-pager.videos'), null, 4000);
};
diff --git a/tools/pager-eager-test.js b/tools/pager-eager-test.js
index 3b5c5c3..3d980fb 100644
--- a/tools/pager-eager-test.js
+++ b/tools/pager-eager-test.js
@@ -117,6 +117,8 @@ async function run(saveData, slow = false) {
await waitFor(() => { const v = [...document.querySelectorAll('.notes-feed [data-key]')].find((n) => n.textContent.includes('clip c0 here')).querySelector('video.note-video'); return v && !v.paused && v.currentTime > 0; }, null, 10000);
const r = await feedRow('clip c0 here');
log = log.filter((e) => e.clip === 'c0');
+ // a mouse click on a playing clip pauses it; a paused one opens
+ await page.evaluate(([x, y]) => { const v = document.elementFromPoint(x, y); if (v && v.tagName === 'VIDEO') v.pause(); }, [r.x, r.y]);
await page.mouse.click(r.x, r.y);
check('the pager opens', await waitFor(() => !!document.querySelector('.media-pager.videos'), null, 4000));
await sleep(slow ? 8000 : 3000);
diff --git a/tools/pager-first-frame-test.js b/tools/pager-first-frame-test.js
index 6507607..0d477b7 100644
--- a/tools/pager-first-frame-test.js
+++ b/tools/pager-first-frame-test.js
@@ -99,6 +99,8 @@ try {
await page.evaluate(() => { const r = [...document.querySelectorAll('.notes-feed [data-key]')].find((n) => n.textContent.includes('a wide one')); r.querySelector('video.note-video').scrollIntoView({ block: 'center' }); });
await sleep(600);
const at = await page.evaluate(() => { const r = [...document.querySelectorAll('.notes-feed [data-key]')].find((n) => n.textContent.includes('a wide one')); const b = r.querySelector('video.note-video').getBoundingClientRect(); return { x: b.x + b.width * 0.2, y: b.y + b.height * 0.3 }; });
+ // a mouse click on a playing clip pauses it; a paused one opens
+ await page.evaluate(([x, y]) => { const v = document.elementFromPoint(x, y); if (v && v.tagName === 'VIDEO') v.pause(); }, [at.x, at.y]);
await page.mouse.click(at.x, at.y);
check('the pager opens', await waitFor(() => !!document.querySelector('.media-pager.videos .mp-slide'), null, 4000));
check('the clip on screen plays', await waitFor(() => [...document.querySelectorAll('.mp-slide.mp-cur video.mp-media')].some((v) => !v.paused), null, 8000));
diff --git a/tools/pager-no-poster-test.js b/tools/pager-no-poster-test.js
index 0930834..332eb53 100644
--- a/tools/pager-no-poster-test.js
+++ b/tools/pager-no-poster-test.js
@@ -64,6 +64,8 @@ const openClip = async (word) => {
await page.evaluate((w) => { const r = [...document.querySelectorAll('.notes-feed [data-key]')].find((n) => n.textContent.includes(w)); r.querySelector('video.note-video').scrollIntoView({ block: 'center' }); }, word);
await sleep(400);
const at = await page.evaluate((w) => { const r = [...document.querySelectorAll('.notes-feed [data-key]')].find((n) => n.textContent.includes(w)); const b = r.querySelector('video.note-video').getBoundingClientRect(); return { x: b.x + b.width * 0.2, y: b.y + b.height * 0.3 }; }, word);
+ // a mouse click on a playing clip pauses it; a paused one opens
+ await page.evaluate(([x, y]) => { const v = document.elementFromPoint(x, y); if (v && v.tagName === 'VIDEO') v.pause(); }, [at.x, at.y]);
await page.mouse.click(at.x, at.y);
await waitFor(() => !!document.querySelector('.media-pager.videos'), null, 4000);
};
diff --git a/tools/pager-prime-test.js b/tools/pager-prime-test.js
index 7263ee1..4989790 100644
--- a/tools/pager-prime-test.js
+++ b/tools/pager-prime-test.js
@@ -114,6 +114,8 @@ async function run() {
await page.waitForSelector('.notes-feed video.note-video', { timeout: 20000 });
const r = await page.evaluate(() => { const row = [...document.querySelectorAll('.notes-feed [data-key]')].find((n) => n.textContent.includes('clip c0 here')); row.querySelector('.note-video-box').scrollIntoView({ block: 'center' }); const v = row.querySelector('video.note-video').getBoundingClientRect(); return { x: v.x + v.width * 0.2, y: v.y + v.height * 0.3 }; });
await sleep(800);
+ // a mouse click on a playing clip pauses it; a paused one opens
+ await page.evaluate(([x, y]) => { const v = document.elementFromPoint(x, y); if (v && v.tagName === 'VIDEO') v.pause(); }, [r.x, r.y]);
await page.mouse.click(r.x, r.y);
check('the pager opens', await waitFor(() => !!document.querySelector('.media-pager.videos'), null, 4000));
check('the next clip\'s warm player has played a moment, unheard, and waits paused a frame or two in', await waitFor(() => { const s = [...document.querySelectorAll('.mp-slide')].find((x) => x.getAttribute('data-k').endsWith('/c1.webm')); const v = s && s.querySelector('video.mp-media'); return v && v.paused && v.currentTime >= 0.03 && v.currentTime < 0.6; }, null, 10000), JSON.stringify(await vid('c1')));
diff --git a/tools/pager-rotate-test.js b/tools/pager-rotate-test.js
index 9912b7a..9dcc7e3 100644
--- a/tools/pager-rotate-test.js
+++ b/tools/pager-rotate-test.js
@@ -91,6 +91,8 @@ async function run(unmuteFirst) {
await sleep(800);
}
const at = await rowOf(); await sleep(300);
+ // a mouse click on a playing clip pauses it; a paused one opens
+ await page.evaluate(([x, y]) => { const v = document.elementFromPoint(x, y); if (v && v.tagName === 'VIDEO') v.pause(); }, [at.x, at.y]);
await page.mouse.click(at.x, at.y);
check('the pager opens', await waitFor(() => !!document.querySelector('.media-pager.videos'), null, 4000));
await waitFor(() => { const v = document.querySelector('.media-pager video[src]'); return v && !v.paused && v.currentTime > 1.5; }, null, 8000);
diff --git a/tools/pager-seek-hide-test.js b/tools/pager-seek-hide-test.js
index f25ff49..50863ba 100644
--- a/tools/pager-seek-hide-test.js
+++ b/tools/pager-seek-hide-test.js
@@ -88,6 +88,8 @@ try {
await page.evaluate(() => { const r = [...document.querySelectorAll('.notes-feed [data-key]')].find((n) => n.textContent.includes('a wide one')); r.querySelector('video.note-video').scrollIntoView({ block: 'center' }); });
await sleep(400);
const at = await page.evaluate(() => { const r = [...document.querySelectorAll('.notes-feed [data-key]')].find((n) => n.textContent.includes('a wide one')); const b = r.querySelector('video.note-video').getBoundingClientRect(); return { x: b.x + b.width * 0.2, y: b.y + b.height * 0.3 }; });
+ // a mouse click on a playing clip pauses it; a paused one opens
+ await page.evaluate(([x, y]) => { const v = document.elementFromPoint(x, y); if (v && v.tagName === 'VIDEO') v.pause(); }, [at.x, at.y]);
await page.mouse.click(at.x, at.y);
check('the pager opens', await waitFor(() => !!document.querySelector('.media-pager.videos .mp-slide'), null, 4000));
diff --git a/tools/pager-tail-test.js b/tools/pager-tail-test.js
index b294b8f..9d537e1 100644
--- a/tools/pager-tail-test.js
+++ b/tools/pager-tail-test.js
@@ -103,6 +103,8 @@ try {
const r = await page.evaluate(() => { const row = [...document.querySelectorAll('.notes-feed [data-key]')].find((n) => n.textContent.includes('clip zero')); row.querySelector('video.note-video').scrollIntoView({ block: 'center' }); const b = row.querySelector('video.note-video').getBoundingClientRect(); return { x: b.x + b.width * 0.2, y: b.y + b.height * 0.3 }; });
await sleep(400);
+ // a mouse click on a playing clip pauses it; a paused one opens
+ await page.evaluate(([x, y]) => { const v = document.elementFromPoint(x, y); if (v && v.tagName === 'VIDEO') v.pause(); }, [r.x, r.y]);
await page.mouse.click(r.x, r.y);
check('the pager opens on the first clip', await waitFor(() => !!document.querySelector('.media-pager.videos'), null, 4000) && await resting('c0'), await at());
check('a loading screen waits at the end, after the clips', (await tail())?.last, JSON.stringify(await tail()));
diff --git a/tools/post-edit-test.js b/tools/post-edit-test.js
index 0b8bf6f..2ed1260 100644
--- a/tools/post-edit-test.js
+++ b/tools/post-edit-test.js
@@ -160,6 +160,7 @@ try {
await openFeed();
check('the feed is back', await waitText('a post a stranger tried to delete', 15000));
check('my deleted post stays gone', !(await has('my own post')));
+ check('...with no "was deleted" row in its place', !(await has('deleted by its author')));
check('no page errors', errs.length === 0, errs.slice(0, 2).join(' | '));
} finally { await browser.close(); server.stop(true); }
console.log(ok ? '\n✅ post edits and deletions' : '\n❌ failed');
diff --git a/tools/profile-publish-race-test.js b/tools/profile-publish-race-test.js
new file mode 100644
index 0000000..becf375
--- /dev/null
+++ b/tools/profile-publish-race-test.js
@@ -0,0 +1,111 @@
+// Two kind-0 publishes at once used to clobber each other: both read the
+// same base off the relays, the later one landed without the earlier one's
+// fields. The migration did exactly that — the rename repointed lud16/nip05
+// to the new name while the legacy-avatar import republished the old base
+// nine seconds later, so a user's published lightning address was the
+// placeholder name their rename had just released (Jarryd, 2026-10-24).
+// Now kind-0 publishes go one at a time and merge over what was last sent.
+// Run: bun tools/profile-publish-race-test.js
+import { generateSecretKey, getPublicKey, finalizeEvent } from 'nostr-tools/pure';
+
+let fails = 0;
+const check = (name, ok, detail = '') => {
+ console.log(` ${ok ? '✓' : '✗'} ${name}${detail ? ' — ' + String(detail).slice(0, 160) : ''}`);
+ if (!ok) fails++;
+};
+
+globalThis.localStorage = {
+ _d: {}, getItem(k) { return this._d[k] ?? null; }, setItem(k, v) { this._d[k] = String(v); },
+ removeItem(k) { delete this._d[k]; }, key(i) { return Object.keys(this._d)[i] ?? null; },
+ get length() { return Object.keys(this._d).length; },
+};
+
+// One in-memory relay behind every socket: EVENT stores, REQ answers with
+// what matches (newest first) and EOSE. Enough for a kind-0 round trip.
+const store = [];
+const published = [];
+class FakeSocket {
+ constructor(url) {
+ this.url = url; this.readyState = 0;
+ setTimeout(() => { this.readyState = 1; this.onopen && this.onopen({}); }, 0);
+ }
+ reply(msg) { setTimeout(() => { if (this.readyState === 1 && this.onmessage) this.onmessage({ data: JSON.stringify(msg) }); }, 0); }
+ send(str) {
+ let m; try { m = JSON.parse(str); } catch { return; }
+ if (m[0] === 'EVENT') { store.push(m[1]); published.push(m[1]); this.reply(['OK', m[1].id, true, '']); }
+ if (m[0] === 'REQ') {
+ const [, sub, ...filters] = m;
+ const hit = store.filter((e) => filters.some((f) => (!f.kinds || f.kinds.includes(e.kind)) && (!f.authors || f.authors.includes(e.pubkey))));
+ hit.sort((a, b) => b.created_at - a.created_at);
+ for (const e of hit) this.reply(['EVENT', sub, e]);
+ this.reply(['EOSE', sub]);
+ }
+ }
+ close() { this.readyState = 3; this.onclose && this.onclose({}); }
+}
+globalThis.WebSocket = FakeSocket;
+globalThis.Image = class { set src(v) { this._src = v; } };
+// the legacy account the migration brings along
+globalThis.fetch = async (url) => {
+ if (/coinos\.io\/api\/users\//.test(String(url))) return { ok: true, json: async () => ({ profile: 'face', banner: 'cover' }) };
+ throw new Error('offline');
+};
+
+const { messagesFeature } = await import('../src/features/messages.js');
+
+const sk = generateSecretKey();
+const pk = getPublicKey(sk);
+const signer = { pubkey: pk, signEvent: async (e) => finalizeEvent(e, sk) };
+let now = Math.floor(Date.now() / 1000) - 100;
+const seed = finalizeEvent({ kind: 0, created_at: now, tags: [], content: JSON.stringify({ name: 'Jarryd', lud16: '[email protected]', nip05: '[email protected]' }) }, sk);
+store.push(seed);
+
+const walletSk = generateSecretKey();
+const wallet = {
+ mnemonic: 'x '.repeat(11) + 'y', utxos: [], txs: [],
+ nostr: { sk: walletSk, pk: getPublicKey(walletSk), ck: new Uint8Array(32) },
+ loadFeatureState: () => null, saveFeatureState: () => {},
+ _cacheKey: () => 'race-test', saveCache: () => {}, registerCacheExtension: () => {}, registerLoadHook: () => {},
+};
+let namesAddr = null; // what the registrar says our address is
+const feature = messagesFeature({
+ h: (tag, attrs, ...kids) => ({ tag, attrs, kids }), ui: {}, render: () => {}, wallet, toast: () => {}, brandHeader: () => null,
+ hook: (name) => (name === 'nostrLoginIdentity' ? { pubkey: pk, signer } : name === 'namesAddress' ? namesAddr : null),
+});
+
+console.log('[the migration: rename and avatar import fired together]');
+await Promise.all([
+ feature.addressRenamed('[email protected]', '[email protected]'),
+ feature.adoptLegacyProfile('jarryd'),
+]);
+const newest = store.filter((e) => e.kind === 0 && e.pubkey === pk).sort((a, b) => b.created_at - a.created_at)[0];
+const final = JSON.parse(newest.content);
+const sent = [...new Map(published.filter((e) => e.kind === 0).map((e) => [e.id, e])).values()];
+check('two kind 0s went out, one after the other', sent.length === 2 && sent[1].created_at > sent[0].created_at, sent.map((e) => e.created_at + ' ' + JSON.parse(e.content).lud16 + ' ' + (JSON.parse(e.content).picture ? 'face' : '-')).join(' → '));
+check('the newest kind 0 carries the new address', final.lud16 === '[email protected]' && final.nip05 === '[email protected]', JSON.stringify(final));
+check('...and the legacy face and cover', /face\.webp$/.test(final.picture || '') && /cover\.webp$/.test(final.banner || ''), final.picture + ' ' + final.banner);
+check('...and the name it had', final.name === 'Jarryd');
+
+console.log('[a second rename right behind, before the relays answer]');
+published.length = 0;
+await Promise.all([feature.addressRenamed('[email protected]', '[email protected]'), feature.publishProfile({ about: 'hi' })]);
+const last = JSON.parse(store.filter((e) => e.kind === 0 && e.pubkey === pk).sort((a, b) => b.created_at - a.created_at)[0].content);
+check('both changes survive', last.lud16 === '[email protected]' && last.about === 'hi' && /face/.test(last.picture), JSON.stringify(last));
+
+console.log('[Save in the editor repoints a dead same-domain address]');
+// The heal never ran (an Amber user: no background signatures), so the kind 0
+// still names the released placeholder. The domain says jar is dead, other
+// is alive.
+store.push(finalizeEvent({ kind: 0, created_at: now + 1000, tags: [], content: JSON.stringify({ name: 'Jarryd', lud16: '[email protected]', nip05: '[email protected]' }) }, sk));
+namesAddr = '[email protected]';
+globalThis.fetch = async (url) => /lnurlp\/jar$/.test(url)
+ ? { ok: false, status: 500, json: async () => null }
+ : { ok: true, status: 200, json: async () => ({ tag: 'payRequest', callback: 'https://x/cb' }) };
+published.length = 0;
+await feature.saveProfileDraft({ uname: 'jarryd', name: 'Jarryd' });
+const saved = JSON.parse(published.filter((e) => e.kind === 0).pop().content);
+check('the dead placeholder moves to the claimed address', saved.lud16 === '[email protected]', JSON.stringify(saved));
+check('a same-domain address that still answers is left alone', saved.nip05 === '[email protected]', saved.nip05);
+
+console.log(fails ? `\n❌ ${fails} failing` : '\n✅ kind-0 publishes take turns');
+process.exit(fails ? 1 : 0);
diff --git a/tools/quoted-clip-fullscreen-test.js b/tools/quoted-clip-fullscreen-test.js
index bd8dd45..41984a2 100644
--- a/tools/quoted-clip-fullscreen-test.js
+++ b/tools/quoted-clip-fullscreen-test.js
@@ -70,6 +70,8 @@ try {
console.log('\n[a tap on the picture]');
const box = await (await page.$(SEL)).boundingBox();
+ // a mouse click on a playing clip pauses it; a paused one opens
+ await page.evaluate(([x, y]) => { const v = document.elementFromPoint(x, y); if (v && v.tagName === 'VIDEO') v.pause(); }, [box.x + box.width / 2, box.y + box.height * 0.25]);
await page.mouse.click(box.x + box.width / 2, box.y + box.height * 0.25); // above the middle: not the play button
check('the clip goes full screen', await waitFor(() => document.fullscreenElement && document.fullscreenElement.matches('video'), 4000), JSON.stringify(await state()));
await sleep(600);
diff --git a/tools/receive-batch-fold-test.js b/tools/receive-batch-fold-test.js
new file mode 100644
index 0000000..8e38265
--- /dev/null
+++ b/tools/receive-batch-fold-test.js
@@ -0,0 +1,20 @@
+// One payment delivered as several coins — a gift whose 886 sats sat in two
+// (595 + 291, dust padding) swept in one claim — is one Received row.
+// sameDelivery decides which receive rows fold; nothing else does.
+// Run: bun tools/receive-batch-fold-test.js
+import { sameDelivery } from '../src/ark/manager.js';
+let ok = true;
+const check = (n, c) => { console.log(` ${c ? '✓' : '✗'} ${n}`); if (!c) ok = false; };
+const T = 1_790_000_000_000;
+const rcv = (id, sat, ts, extra = {}) => ({ id, type: 'receive', status: 'complete', amountSat: sat, ts, vtxoId: 'v-' + id, ...extra });
+check('two coins of one mailbox message fold', sameDelivery(rcv('a', 595, T, { batch: '7' }), rcv('b', 291, T, { batch: '7' })));
+check('...even when their instants differ (live, no checkpoint time)', sameDelivery(rcv('a', 595, T, { batch: '7' }), rcv('b', 291, T + 40, { batch: '7' })));
+check('two messages stay two rows, same instant or not', !sameDelivery(rcv('a', 595, T, { batch: '7' }), rcv('b', 291, T, { batch: '8' })));
+check('a stamped row never folds an unstamped one', !sameDelivery(rcv('a', 595, T, { batch: '7' }), rcv('b', 291, T)));
+check('older rows (no stamp) fold on the same delivery instant', sameDelivery(rcv('a', 595, T), rcv('b', 291, T)));
+check('...not a millisecond apart', !sameDelivery(rcv('a', 595, T), rcv('b', 291, T + 1)));
+check('a ⚡ receive is its own payment', !sameDelivery(rcv('a', 595, T, { batch: '7' }), rcv('b', 291, T, { batch: '7', viaLn: true })));
+check('a rejected coin is not part of the payment', !sameDelivery(rcv('a', 595, T, { batch: '7' }), rcv('b', 291, T, { batch: '7', status: 'rejected' })));
+check('only receives fold', !sameDelivery({ ...rcv('a', 595, T), type: 'send' }, rcv('b', 291, T)));
+console.log(ok ? '\n✅ one delivery, one row' : '\n❌ failed');
+process.exit(ok ? 0 : 1);
diff --git a/tools/sw-push-quota.test.js b/tools/sw-push-quota.test.js
index e7d00f2..cf4a7bf 100644
--- a/tools/sw-push-quota.test.js
+++ b/tools/sw-push-quota.test.js
@@ -4,8 +4,9 @@
import { test, expect, mock } from 'bun:test';
let respond = async () => true;
-mock.module('../src/nwc-respond.js', () => ({ respondFromBg: (...a) => respond(...a), tendRenewals: async () => {} }));
-mock.module('../src/nwc-lock.js', () => ({ withRequestLock: async (_id, fn) => fn() }));
+mock.module('../src/nwc-respond.js', () => ({ respondFromBg: (...a) => respond(...a), tendRenewals: async () => {}, tendLnPays: async () => [] }));
+mock.module('../src/nwc-lock.js', () => ({ withRequestLock: async (_id, fn) => fn(), withWorkLock: async (fn) => fn() }));
+mock.module('../src/nwc-bg.js', () => ({ appendBgLog: async () => {}, takeLease: async () => ({ waited: 0, release: async () => {} }) }));
mock.module('../src/bg-autowithdraw.js', () => ({ bgAutoWithdraw: async () => {} }));
mock.module('../src/dm-inbox.js', () => ({
allInboxes: async () => [{ muted: ['m'.repeat(64)] }],
@@ -50,6 +51,13 @@ test('apple: every quiet path shows the stand-in', async () => {
expect(closed.length).toBe(0);
});
+test('apple: a send finished from an earlier wake shows its own line and drops the stand-in', async () => {
+ endpoint = 'https://web.push.apple.com/abc'; windows = [];
+ respond = async () => ({ notices: [{ title: 'Payment sent', body: '-21 sats via a connected app', tag: 'nwc-sent' }] });
+ expect(await push(nwc)).toEqual(['Coinos', 'Payment sent']);
+ expect(closed.length).toBe(1);
+});
+
test('apple: an app on screen gets the stand-in closed at once', async () => {
windows = [visible];
expect(await push({ type: 'notify', reason: 'payment', amountSat: 5 })).toEqual(['Coinos']);
@@ -60,7 +68,9 @@ test('apple: a suspended background app does not swallow the request', async ()
windows = [hidden];
let asked = 0;
respond = async () => { asked++; return { notify: { title: 'Payment sent', body: '' } }; };
- expect(await push(nwc)).toEqual(['Payment sent']);
+ // the stand-in goes up first and the outcome replaces it (91dbee4)
+ expect(await push(nwc)).toEqual(['Coinos', 'Payment sent']);
+ expect(closed.length).toBe(1);
expect(asked).toBe(1);
});
diff --git a/tools/thread-reply-test.js b/tools/thread-reply-test.js
index 738a31c..f3bda91 100644
--- a/tools/thread-reply-test.js
+++ b/tools/thread-reply-test.js
@@ -78,6 +78,27 @@ try {
await page.click('#app .note-act');
check('Reply immediately shows its composer beneath the tapped post', await inline());
check('the input receives focus before relay queries finish', await page.evaluate(() => document.activeElement.matches('.thread-reply-input')));
+ // Cancel with text typed: the box folds and the draft is gone (it used to
+ // stay open — the box shows while a draft has text, and Cancel only
+ // cleared the replying flag)
+ await page.type('.thread-reply-input', 'Half a thought');
+ await page.evaluate(() => document.querySelector('.thread-reply-cancel').click());
+ check('Cancel with text typed hides the box and discards the draft', await page.evaluate(() =>
+ !document.querySelector('.thread-reply-input') && !(test.ui.noteThread.draft || '').length));
+ await page.evaluate(() => document.querySelector('#app .note-act').click()); // one atomic tap, as below
+ await page.waitForSelector('.thread-reply-input');
+ check('Reply again opens an empty field', await page.evaluate(() => document.querySelector('.thread-reply-input')?.value === ''));
+ // a phone: Return is a new line, not a send
+ await page.evaluate(() => { const mm = window.matchMedia; window._mm = mm; window.matchMedia = (q) => q === '(pointer: coarse)' ? { matches: true } : mm(q); });
+ await page.type('.thread-reply-input', 'Line one');
+ await page.keyboard.press('Enter');
+ await page.type('.thread-reply-input', 'two');
+ check("on a phone, Return adds a line instead of sending", await page.evaluate(() =>
+ document.querySelector('.thread-reply-input')?.value === 'Line one\ntwo' && sent.length === 0), await page.evaluate(() => document.querySelector('.thread-reply-input')?.value));
+ await page.evaluate(() => { window.matchMedia = window._mm; });
+ await page.focus('.thread-reply-input');
+ await page.keyboard.down('Control'); await page.keyboard.press('a'); await page.keyboard.up('Control');
+ await page.keyboard.press('Backspace');
await page.type('.thread-reply-input', 'A reply before the root loads');
// (one atomic tap: a repaint landing between finding the button and clicking it replaces it)
await page.waitForFunction(() => !document.querySelector('.thread-reply-send')?.disabled);
diff --git a/tools/video-events-test.js b/tools/video-events-test.js
index bef0956..c024949 100644
--- a/tools/video-events-test.js
+++ b/tools/video-events-test.js
@@ -128,6 +128,8 @@ try {
await page.evaluate(() => { const r = [...document.querySelectorAll('.notes-feed > [data-key]')].find((n) => n.textContent.includes('A normal clip')); r.querySelector('video.note-video').scrollIntoView({ block: 'center' }); });
await sleep(500);
const at = await page.evaluate(() => { const r = [...document.querySelectorAll('.notes-feed > [data-key]')].find((n) => n.textContent.includes('A normal clip')); const b = r.querySelector('video.note-video').getBoundingClientRect(); return { x: b.x + b.width * 0.2, y: b.y + b.height * 0.3 }; });
+ // a mouse click on a playing clip pauses it; a paused one opens
+ await page.evaluate(([x, y]) => { const v = document.elementFromPoint(x, y); if (v && v.tagName === 'VIDEO') v.pause(); }, [at.x, at.y]);
await page.mouse.click(at.x, at.y);
check('a tap opens the pager', await waitFor(() => !!document.querySelector('.media-pager.videos'), null, 4000));
const slides = await page.evaluate(() => [...document.querySelectorAll('.mp-slide')].map((s) => s.getAttribute('data-k').split('|')[1].replace(location.origin, '')));
diff --git a/tools/video-tap-test.js b/tools/video-tap-test.js
index f82238b..50e5a69 100644
--- a/tools/video-tap-test.js
+++ b/tools/video-tap-test.js
@@ -1,8 +1,7 @@
-// Tapping a video: in the feed it opens the media pager (feed-video-pager-
-// test.js has the rest). In a thread, anywhere on the picture (not the
-// player's own play button or control bar) goes full screen — the corner
-// button is a reach on a phone. Full screen, a tap pauses a playing clip; a
-// tap on a paused one comes back out. Taps on the controls stay the player's.
+// Tapping a video: inline, a playing clip pauses. A paused one, in the feed,
+// and in a thread opens the media pager (feed-video-pager-test.js has the
+// rest). With a mouse the middle of the clip is a big play/pause button that
+// never goes full screen.
// Run: bun tools/video-tap-test.js
import puppeteer from './puppeteer.js';
import { cacheKeyFor } from '../src/wallet.js';
@@ -69,8 +68,18 @@ try {
for (let i = 0; i < 40 && (await st()).paused; i++) await sleep(250);
check('the clip autoplays in the feed', !(await st()).paused);
+ // the hover button: pauses and plays in place
+ const pp = async () => { const b = await page.evaluate(() => { const r = document.querySelector('.notes-feed .note-video-box').getBoundingClientRect(); return { x: r.x + r.width / 2, y: r.y + r.height / 2 }; }); await page.mouse.move(b.x - 40, b.y); await page.mouse.move(b.x, b.y, { steps: 3 }); await sleep(250); if (!(await page.evaluate(() => getComputedStyle(document.querySelector('.notes-feed .vid-pp')).display === 'flex'))) check('a mouse over the clip brings up the middle button', false); await page.mouse.click(b.x, b.y); await sleep(700); };
+ check('no middle button until a mouse comes over the clip', await page.evaluate(() => getComputedStyle(document.querySelector('.notes-feed .vid-pp')).display === 'none'));
+ await pp();
+ check('the middle button pauses the clip in place', await page.evaluate(() => document.querySelector('video.note-video').paused && !document.querySelector('.media-pager') && !document.fullscreenElement));
+ check('...and shows play while paused', await page.evaluate(() => !document.querySelector('.vid-pp').classList.contains('playing')));
+ await pp();
+ check('the middle button plays it again, still inline', await page.evaluate(() => !document.querySelector('video.note-video').paused && !document.querySelector('.media-pager') && !document.fullscreenElement));
await tap(0.2, 0.3);
- check('in the feed, a tap opens the media pager', await page.evaluate(() => !!document.querySelector('.media-pager.videos')));
+ check('in the feed, a tap on a playing clip pauses it, no pager', await page.evaluate(() => document.querySelector('video.note-video').paused && !document.querySelector('.media-pager')));
+ await tap(0.2, 0.3);
+ check('a tap on the paused clip opens the media pager', await page.evaluate(() => !!document.querySelector('.media-pager.videos')));
await page.keyboard.press('Escape'); await sleep(700);
check('...which Escape closes', await page.evaluate(() => !document.querySelector('.media-pager') && !document.fullscreenElement));
// the thread: the post's words open it
@@ -87,22 +96,11 @@ try {
for (let i = 0; i < 40 && (await st()).paused; i++) await sleep(250);
await tap(0.2, 0.3);
let s = await st();
- check('in a thread, a tap on the picture goes full screen', s.fs, JSON.stringify(s));
- check('...and not the pager', await page.evaluate(() => !document.querySelector('.media-pager')));
- await tap(0.25, 0.3);
- s = await st();
- check('full screen, a tap pauses the playing clip', s.fs && s.paused, JSON.stringify(s));
- await tap(0.5, 0.5);
- s = await st();
- check('a tap on the paused clip\'s play button is left to the player', s.fs, JSON.stringify(s));
- await page.evaluate(() => document.querySelector('.thread-card video.note-video').pause()); await sleep(300);
+ check('in a thread, a tap on the playing clip pauses it in place', !s.fs && s.paused, JSON.stringify(s));
await tap(0.2, 0.3);
- s = await st();
- check('a tap elsewhere on the paused clip comes out of full screen', !s.fs, JSON.stringify(s));
- await tap(0.3, 0.97);
- s = await st();
- check('a tap on the control bar stays the player\'s', !s.fs, JSON.stringify(s));
+ check('a tap on the paused clip opens the media pager there too', await page.evaluate(() => !!document.querySelector('.media-pager.videos')));
+ await page.keyboard.press('Escape'); await sleep(700);
check('no page errors', errs.length === 0, errs.slice(0, 2).join(' | '));
} finally { await browser.close(); server.stop(true); }
-console.log(ok ? '\n✅ video taps: full screen, pause, back out' : '\n❌ failed');
+console.log(ok ? '\n✅ video taps: pause in place, pager when paused, middle button' : '\n❌ failed');
process.exit(ok ? 0 : 1);